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R0PcdvXk=
-- CEETOS_RELEASE_PAYLOAD_BEGIN
-- CeetOS installer. Generated; do not edit.
local files = {
  ["startup.lua"] = "local pendingPath,releasePath=\"/ceetos-updates/pending.lua\",\"/ceetos-updates/release.lua\"local pending if fs.exists(pendingPath)then local loader=loadfile(pendingPath)if loader then local ok,value=pcall(loader)if ok and type(value)==\"table\"then pending=value end end end if pending and pending.state==\"apply\"and fs.exists(releasePath)then shell.run(releasePath,\"--ceetos-apply\")elseif fs.exists(\"/ceetos/startup.lua\")then shell.run(\"/ceetos/startup.lua\")else shell.run(\"shell\")end",
  ["ceetos/startup.lua"] = "local root=\"/ceetos\"local profile={id=\"desktop\"}if fs.exists(root..\"/profile.lua\")then local loader=loadfile(root..\"/profile.lua\")if loader then local ok,value=pcall(loader);if ok and type(value)==\"table\"then profile=value end end end if profile.id~=\"desktop\"and fs.exists(root..\"/server.lua\")then shell.run(root..\"/server.lua\")elseif fs.exists(root..\"/ceet.lua\")then shell.run(root..\"/ceet.lua\")else printError(\"CeetOS is incomplete; starting CraftOS shell.\")shell.run(\"shell\")end",
  ["ceetos/profile.lua"] = "return {schema=1,id=\"desktop\"}",
  ["ceetos/ceet.lua"] = "package.path=\"/?.lua;/?/init.lua;\"..package.path local auth=require(\"ceetos.lib.auth\")local net=require(\"ceetos.lib.net\")local peripherals=require(\"ceetos.lib.peripherals\")local telemetry=require(\"ceetos.lib.telemetry\")local audit=require(\"ceetos.lib.audit\")local store=require(\"ceetos.lib.store\")local jobs=require(\"ceetos.lib.jobs\")local crafting=require(\"ceetos.lib.crafting\")local craftSources=require(\"ceetos.lib.craft_sources\")local networkIpc=require(\"ceetos.lib.network_ipc\")local updater=require(\"ceetos.lib.updater\")local profile=require(\"ceetos.lib.profile\")local cloudSync=require(\"ceetos.lib.cloud_sync\")local okVersion,version=pcall(require,\"ceetos.lib.version\")version=okVersion and version or{string=\"0.16.8\"}local SHELL_REPLY_PATH=\"/ceetos/data/shell-replies.lua\"local CRAFT_REPLY_PATH=\"/ceetos/data/craft-replies.lua\"local DEV_NETWORK_STATUS=\"/ceetos/data/network-status.lua\"local DEV_NETWORK_HEALTH=\"/ceetos/data/network-service.lua\"local DEV_NETWORK_IPC_DIAG=\"/ceetos/data/network-ipc-status.lua\"local JOB_INBOX=\"/ceetos/data/job-inbox.lua\"local JOB_OUTBOX=\"/ceetos/data/job-outbox.lua\"local CRAFT_STATE=\"/ceetos/data/crafting-state.lua\"local CRAFT_COMMANDS=\"/ceetos/data/crafting-commands\"local CRAFT_COMMAND_LEGACY=\"/ceetos/data/crafting-commands.lua\"local CRAFT_RECIPES=\"/ceetos/data/recipes.lua\"local PROFILE_CACHE=\"/ceetos/data/profile-cache.lua\"local lastJobTemplateSync=0 local lastProfileAdvert=0 local craftRecoveryChecked=false local function writeDevValue(path,value)if not fs.exists(\"/ceetos/data\")then fs.makeDir(\"/ceetos/data\")end local encoded,serialised=pcall(textutils.serialise,value)if not encoded then return false,tostring(serialised)end local handle=fs.open(path,\"w\")if not handle then return false,\"could not open diagnostic state file\"end handle.write(serialised);handle.close()return true end local function craftDefault()return{config={ticker=nil,requester=nil,recipeServer=nil,stockName=nil,requesterName=nil,orderAddress=\"Order\",timeout=120},sources={tickers={},requesters={},recipeServers={},updated=0},stock={},stockUpdated=0,cart={},craftMode=false,queue={},retries={},history={},sequence=0,acknowledgements={}}end local function craftState()local value=store.read(CRAFT_STATE,craftDefault())local defaults=craftDefault()for key,fallback in pairs(defaults)do if value[key]==nil then value[key]=fallback end end for key,fallback in pairs(defaults.config)do if value.config[key]==nil then value.config[key]=fallback end end if not value.config.ticker and value.config.stockName then value.config.ticker={transport=\"local\",name=value.config.stockName}end if not value.config.requester and value.config.requesterName then value.config.requester={transport=\"local\",name=value.config.requesterName}end if not craftRecoveryChecked then craftRecoveryChecked=true if value.active then local active,item=value.active,value.active.items and value.active.items[value.active.index]value.history[#value.history+1]={id=active.id,status=\"interrupted-unconfirmed\",name=item and item.name,requested=active.requested or(item and item.count),accepted=active.accepted,dispatched=active.delivered or 0,destination=active.destination,reason=\"CeetOS restarted; request was not replayed\",finished=os.epoch(\"utc\")}while#value.history>24 do table.remove(value.history,1)end value.active,value.nextRefresh,value.recoveryNotice=nil,0,\"An active Create request was interrupted and not replayed.\"store.write(CRAFT_STATE,value)end end return value end local function saveCraft(value)store.write(CRAFT_STATE,value)end local function craftRecipes()if not profile.capability(\"recipes\")then return nil,nil,\"Craft mode requires a reachable Recipe Server\"end local recipeDb=require((\"ceetos.lib.recipe_db\"))local base,databaseOrErr=recipeDb.loadBase()if not base then return nil,nil,databaseOrErr end local database,overlay=databaseOrErr,{recipes={},tags={}}if fs.exists(CRAFT_RECIPES)then local file=fs.open(CRAFT_RECIPES,\"r\");local raw=file and file.readAll()or nil if file then file.close()end local parsed,err=crafting.parseRecipeOverlay(raw or\"\")if not parsed then return nil,nil,err end overlay=parsed end return recipeDb.mergeOverlay(base,overlay.recipes),recipeDb.mergeTags(database.tags,overlay.tags),nil,overlay end local function peerSourceCandidates()local tickers,requesters={},{}for _,peer in ipairs(net.peers())do local cache=store.read(\"/ceetos/data/remote/\"..tostring(peer.id)..\".lua\",{})for _,item in ipairs(cache.peripherals or{})do local source={transport=\"peer\",peer=tostring(peer.id),name=item.name,type=item.type,mode=item.mode,label=\"Peer \"..tostring(peer.label or peer.id)..\" / \"..tostring(item.name)}local kind=tostring(item.type or\"\"):lower()if kind:find(\"stockticker\",1,true)then tickers[#tickers+1]=source elseif kind:find(\"redstonerequester\",1,true)then requesters[#requesters+1]=source end end end return tickers,requesters end local function recordProfile(peerId,body)if type(body)~=\"table\"or type(body.profile)~=\"string\"or not profile.IDS[body.profile]then return false end local cache=store.read(PROFILE_CACHE,{})cache[tostring(peerId)]={profile=body.profile,version=tostring(body.version or\"\"):sub(1,24),seen=os.epoch(\"utc\")}store.write(PROFILE_CACHE,cache)return true end local function refreshCraftSources(state,queryPeers)local tickers,requesters=craftSources.discoverLocal()local recipeServers={}local peerTickers,peerRequesters=peerSourceCandidates()for _,item in ipairs(peerTickers)do tickers[#tickers+1]=item end for _,item in ipairs(peerRequesters)do requesters[#requesters+1]=item end local profiles=store.read(PROFILE_CACHE,{})for _,peer in ipairs(net.peers())do local advertised=profiles[tostring(peer.id)]if advertised and advertised.profile==\"recipe-server\"then recipeServers[#recipeServers+1]={transport=\"peer\",peer=tostring(peer.id),label=\"Recipe Server \"..tostring(peer.label or peer.id)}end end if cloudSync.recipeOnline()then recipeServers[#recipeServers+1]={transport=\"cloud\",label=\"Cloud Recipe Server\"}end table.sort(recipeServers,function(a,b)return tostring(a.label)<tostring(b.label)end)state.sources={tickers=tickers,requesters=requesters,recipeServers=recipeServers,updated=os.epoch(\"utc\")}if queryPeers then for _,peer in ipairs(net.peers())do net.request(peer.id,\"peripheral_list\",{},{safe=true});net.request(peer.id,\"profile_query\",{},{safe=true})end end end local function sourceAvailable(source,needle)source=craftSources.kind(source)if not source then return false end if source.transport==\"peer\"then local tickers,requesters=peerSourceCandidates()local candidates=needle==\"stockticker\"and tickers or requesters for _,candidate in ipairs(candidates)do if craftSources.key(candidate)==craftSources.key(source)then return true end end return false end return peripheral.isPresent(source.name)and tostring(peripheral.getType(source.name)or\"\"):lower():find(needle,1,true)~=nil end local function pushCraftHistory(state,row)state.history[#state.history+1]=row while#state.history>24 do table.remove(state.history,1)end end local function failCraft(state,reason)local active=state.active local message=tostring(reason or\"unspecified crafting queue failure\")state.error=message if active then local item=active.items and active.items[active.index]pushCraftHistory(state,{id=active.id,status=\"failed\",name=item and item.name,requested=item and item.count,accepted=active.accepted,delivered=active.delivered,destination=active.destination,error=message,finished=os.epoch(\"utc\")})end state.active=nil end local function cancelCraft(state)local active=state.active if not active then return false end local item=active.items and active.items[active.index]pushCraftHistory(state,{id=active.id,status=crafting.cancellationStatus(active.issued),name=item and item.name,requested=active.requested or(item and item.count),accepted=active.accepted,delivered=active.delivered or 0,remaining=active.remaining,destination=active.destination,issued=active.issued==true,reason=active.issued and\"Create package may still arrive\"or\"Cancelled before dispatch\",finished=os.epoch(\"utc\"),})state.active=nil return true end local function completeCraftItem(state)local active=state.active;active.index=active.index+1;active.plan,active.step,active.requested,active.accepted,active.delivered,active.remaining,active.deadline,active.issued,active.issuedKind,active.issuedAt,active.requesterConfigured,active.requesterStrict,active.waitingFor,active.expectedOutput,active.craftStep,active.pendingCraftRequests,active.craftBaseline,active.nextCraftDispatch,active.packageIndex,active.packageRequest,active.peerRequest,active.planRequest=nil,1,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil active.packageRemaining,active.stepAddress,active.stepRoute,active.packageCount=nil,nil,nil,nil if active.index>#active.items then state.active=nil else active.phase=\"prepare\"end end local function applyCraftCommand(state,command)local status,detail=\"ignored\",nil if auth.allowed(\"operator\")then if command.action==\"add\"and type(command.name)==\"string\"and tonumber(command.count)and command.count>0 then crafting.addToCart(state.cart,command.name,command.count);status=\"ok\"elseif command.action==\"remove\"then table.remove(state.cart,tonumber(command.index)or 0);status=\"ok\"elseif command.action==\"edit\"and state.cart[tonumber(command.index)or 0]then state.cart[tonumber(command.index)].count=math.max(1,math.floor(tonumber(command.count)or 1));status=\"ok\"elseif command.action==\"mode\"then if command.value==true and not sourceAvailable(state.config.requester,\"redstonerequester\")then detail=\"Craft mode needs an available Redstone Requester source\"else state.craftMode=command.value==true;status=\"ok\"end elseif command.action==\"destination\"and type(command.value)==\"string\"and#command.value>0 and#command.value<=64 then state.config.orderAddress=command.value;status=\"ok\"elseif command.action==\"submit\"and#state.cart>0 and not state.active then state.sequence=state.sequence+1;state.queue[#state.queue+1]={id=\"craft-\"..tostring(os.epoch(\"utc\"))..\"-\"..tostring(state.sequence),items=state.cart,craftMode=state.craftMode,destination=state.config.orderAddress};state.cart,state.error={},nil;status=\"ok\"elseif command.action==\"retry\"and state.retries[tonumber(command.index)or 0]and not state.active then local retry=table.remove(state.retries,tonumber(command.index));state.queue[#state.queue+1]=retry;status=\"ok\"elseif command.action==\"cancel_active\"and state.active then cancelCraft(state);status=\"ok\"elseif command.action==\"refresh\"then state.nextRefresh,state.nextSourceRefresh=0,0;status=\"ok\"elseif command.action==\"source\"and(command.target==\"requester\"or command.target==\"recipes\")and command.value==false then if command.target==\"recipes\"then state.config.recipeServer=nil else state.config.requester,state.craftMode=nil,false end state.nextRefresh=0;status=\"ok\"elseif command.action==\"source\"and command.target==\"recipes\"then local source=type(command.value)==\"table\"and command.value or nil if source and source.transport==\"peer\"and type(source.peer)==\"string\"then state.config.recipeServer={transport=\"peer\",peer=source.peer,label=source.label};status=\"ok\"elseif source and source.transport==\"cloud\"then state.config.recipeServer={transport=\"cloud\",label=\"Cloud Recipe Server\"};status=\"ok\"else detail=\"invalid recipe server\"end elseif command.action==\"source\"and(command.target==\"ticker\"or command.target==\"requester\")then local source=craftSources.kind(command.value)if source and type(source.name)==\"string\"then state.config[command.target]=source;state.nextRefresh=0;status=\"ok\"else detail=\"invalid source\"end else detail=\"action unavailable\"end else detail=\"permission denied\"end if type(command.token)==\"string\"and#command.token<=80 then state.acknowledgements[command.token]={ok=status==\"ok\",error=detail,at=os.epoch(\"utc\")}end end local function takeCraftReply(requestId)if not requestId then return nil end store.invalidate(CRAFT_REPLY_PATH)local replies=store.read(CRAFT_REPLY_PATH,{})local reply=replies[requestId]if reply then replies[requestId]=nil;store.write(CRAFT_REPLY_PATH,replies)end return reply end local function newCraftRequestId(prefix)return prefix..\":\"..tostring(os.getComputerID())..\":\"..tostring(os.epoch(\"utc\"))..\":\"..tostring(math.random(1000,9999))end local function requestPeerCraft(source,typeName,body)local requestId=newCraftRequestId(typeName)body.request_id=requestId local ok,err=net.request(source.peer,typeName,body)return ok and requestId or nil,err end local function refreshCraftStock(state,source,now)if not source then return false,\"No Stock Ticker source selected\"end if source.transport~=\"peer\"then if not sourceAvailable(source,\"stockticker\")then return false,\"Selected Stock Ticker is unavailable\"end local ticker=peripheral.wrap(source.name)local ok,stock=pcall(ticker.stock,true)if not ok then return false,tostring(stock)end state.stock,state.stockUpdated,state.error=stock,now,nil return true end local pending=state.stockRequest if pending then local reply=takeCraftReply(pending.id)if reply then state.stockRequest=nil if not reply.ok then return false,tostring(reply.result or\"peer Stock Ticker request failed\")end state.stock,state.stockUpdated,state.error=reply.result or{},now,nil return true end if now-pending.sent>5000 then state.stockRequest=nil;return false,\"Peer Stock Ticker did not respond\"end return false,nil end local requestId,err=requestPeerCraft(source,\"craft_stock_request\",{name=source.name})if not requestId then return false,err end state.stockRequest={id=requestId,sent=now}return false,nil end local function consumeCraftCommands(state)if auth.refreshSession then auth.refreshSession()end if fs.exists(CRAFT_COMMAND_LEGACY)then store.invalidate(CRAFT_COMMAND_LEGACY)for _,command in ipairs(store.read(CRAFT_COMMAND_LEGACY,{}))do applyCraftCommand(state,command)end store.write(CRAFT_COMMAND_LEGACY,{})end if fs.exists(CRAFT_COMMANDS)and fs.isDir(CRAFT_COMMANDS)then local names=fs.list(CRAFT_COMMANDS);table.sort(names)for _,name in ipairs(names)do local path=fs.combine(CRAFT_COMMANDS,name)local handle=fs.open(path,\"r\");local raw=handle and handle.readAll()or nil if handle then handle.close()end fs.delete(path)local command=raw and textutils.unserialise(raw)or nil if type(command)==\"table\"then applyCraftCommand(state,command)end end end local count=0;for _ in pairs(state.acknowledgements)do count=count+1 end while count>32 do for key in pairs(state.acknowledgements)do state.acknowledgements[key]=nil;count=count-1;break end end end local function tickCraftQueue()local state=craftState();consumeCraftCommands(state)local now=os.epoch(\"utc\")if now>=(state.nextSourceRefresh or 0)then refreshCraftSources(state,true)state.nextSourceRefresh=now+8000 end local tickerSource,requesterSource,recipeServer=craftSources.kind(state.config.ticker),craftSources.kind(state.config.requester),state.config.recipeServer local recipes,recipeTags,recipeError,recipeOverlay=craftRecipes()state.recipes,state.recipeTags,state.recipeOverlay=recipes or{},recipeTags or{},recipeOverlay or{recipes={},tags={}}if recipeError then state.error=recipeError end if not tickerSource then state.error=\"Select a Stock Ticker source\";saveCraft(state);return end if now>=(state.nextRefresh or 0)then local ok,err=refreshCraftStock(state,tickerSource,now)if not ok and err then state.error=err end state.nextRefresh=now+(state.active and 500 or 5000)end if not state.active and#state.queue>0 then state.active=table.remove(state.queue,1);state.active.index,state.active.phase,state.active.step=1,\"prepare\",1 end local active=state.active if active then local item=active.items[active.index]local timeout=(tonumber(state.config.timeout)or 120)*1000 if active.deadline and now>active.deadline and active.phase:find(\"^await_\")then local waiting=active.phase==\"await_crafted_output\"and\"recipe output in Stock Ticker\"or active.phase==\"await_package_confirmation\"and\"Stock Ticker package confirmation\"or\"Stock Ticker delivery confirmation\"failCraft(state,\"timed out waiting for \"..waiting)saveCraft(state)return end if not item then completeCraftItem(state)elseif active.phase==\"prepare\"then if active.craftMode then if recipeServer and recipeServer.transport==\"peer\"then if not active.planRequest then local requestId,err=requestPeerCraft(recipeServer,\"recipe_plan_request\",{item=item.name,quantity=item.count,stock=state.stock})if not requestId then failCraft(state,err)else active.planRequest,active.phase={id=requestId,sent=now,source=recipeServer.peer},\"await_peer_plan\"end saveCraft(state);return end elseif recipeServer and recipeServer.transport==\"cloud\"then local plan,planErr=cloudSync.recipePlan(item.name,item.count,state.stock)if not plan then failCraft(state,planErr or\"cloud Recipe Server is unavailable\")else active.plan,active.step,active.phase=plan,1,\"craft\"end else local plan,planErr=recipes and crafting.plan(recipes,state.stock,item.name,item.count,{forceRoot=true,tags=recipeTags})or nil,recipeError if not plan then failCraft(state,planErr or\"recipe database is unavailable\")else active.plan,active.step,active.phase=plan,1,\"craft\"end end else active.phase=\"deliver\"end elseif active.phase==\"await_peer_plan\"then local pending=active.planRequest;local reply=takeCraftReply(pending and pending.id)if reply then active.planRequest=nil local plan,planErr=reply.ok and crafting.validateExecutionPlan(reply.result)or nil,(reply and reply.result)if not plan then failCraft(state,planErr or\"recipe database did not return a valid plan\")else active.plan,active.step,active.phase=plan,1,\"craft\"end elseif pending and now-(pending.sent or now)>5000 then failCraft(state,\"recipe database did not respond\")end elseif active.phase==\"craft\"then local step=active.plan[active.step]if step then active.stepAddress,active.stepRoute=step.address,(step.dispatch==\"requester\"and\"Requester -> \"or\"Stock Ticker -> \")..tostring(step.address)active.packageCount=step.inputs and#step.inputs or nil end if not step then active.phase=\"deliver\"elseif step.dispatch==\"requester\"and(not requesterSource or not sourceAvailable(requesterSource,\"redstonerequester\"))then failCraft(state,\"Recipe \"..tostring(step.name)..\" needs an available Redstone Requester for Crafter\")elseif step.dispatch==\"package\"then if active.craftStep~=active.step then active.craftStep,active.packageIndex,active.craftBaseline=active.step,1,crafting.normalise(state.stock)[step.name]or 0 end local input=step.inputs and step.inputs[active.packageIndex]if not input then active.phase,active.baseline,active.waitingFor,active.expectedOutput,active.deadline=\"await_crafted_output\",active.craftBaseline,step.name,step.produced,now+timeout state.nextRefresh=0 elseif not active.packageRequest then local baseline=crafting.normalise(state.stock)[input.name]or 0 local requested=active.packageRemaining or input.count local ok,result if tickerSource.transport==\"peer\"then local requestId,err=requestPeerCraft(tickerSource,\"craft_request\",{name=tickerSource.name,destination=step.address,filters={{name=input.name,_requestCount=requested}}})if not requestId then failCraft(state,err)else active.packageRequest,active.phase={id=requestId,input=input,requested=requested,baseline=baseline,sent=now},\"await_peer_package\"end saveCraft(state);return else ok,result=peripherals.craftRequest(\"local\",tickerSource.name,step.address,{{name=input.name,_requestCount=requested}})end local accepted,acceptErr=ok and crafting.acceptedCount(result,requested)or nil,result if not accepted then failCraft(state,acceptErr or\"Stock Ticker rejected package\")else active.issued,active.issuedKind,active.issuedAt=true,\"package\",now active.packageRequest={input=input,baseline=baseline,requested=requested,accepted=accepted,remaining=requested-accepted}active.phase,active.waitingFor,active.deadline=\"await_package_confirmation\",input.name,now+timeout state.nextRefresh=0 end end else if active.craftStep~=active.step then active.craftStep,active.pendingCraftRequests,active.craftBaseline,active.nextCraftDispatch=active.step,step.batches,crafting.normalise(state.stock)[step.name]or 0,0 end if now>=(active.nextCraftDispatch or 0)then local ok,result if requesterSource.transport==\"peer\"then if not active.peerRequest then local requestId,err=requestPeerCraft(requesterSource,\"craft_recipe_request\",{name=requesterSource.name,address=step.address,batches=1,grid=step.grid})if not requestId then failCraft(state,err)else active.peerRequest,active.phase={id=requestId,kind=\"craft\",sent=now},\"await_peer_craft\"end end saveCraft(state);return else ok,result=peripherals.craftingRecipeRequest(\"local\",requesterSource.name,step.address,1,step.grid)end if not ok then failCraft(state,result)else active.issued,active.issuedKind,active.issuedAt=true,\"craft\",now active.requesterConfigured=type(result)==\"table\"and result.configured==true active.requesterStrict=type(result)==\"table\"and result.strict==true active.pendingCraftRequests=active.pendingCraftRequests-1 active.nextCraftDispatch=now+100 if active.pendingCraftRequests<=0 then active.phase,active.baseline,active.waitingFor,active.expectedOutput,active.deadline=\"await_crafted_output\",active.craftBaseline,step.name,step.produced,now+timeout active.craftStep,active.craftBaseline,active.nextCraftDispatch=nil,nil,nil state.nextRefresh=0 end end end end elseif active.phase==\"await_peer_craft\"then local reply=takeCraftReply(active.peerRequest and active.peerRequest.id)if reply then active.peerRequest=nil if not reply.ok then failCraft(state,reply.result)else local step=active.plan[active.step]active.issued,active.issuedKind,active.issuedAt=true,\"craft\",now active.pendingCraftRequests=active.pendingCraftRequests-1 active.nextCraftDispatch=now+100 if active.pendingCraftRequests<=0 then active.phase,active.baseline,active.waitingFor,active.expectedOutput,active.deadline=\"await_crafted_output\",active.craftBaseline,step.name,step.produced,now+timeout;active.craftStep,active.craftBaseline,active.nextCraftDispatch=nil,nil,nil else active.phase=\"craft\"end end elseif active.peerRequest and now-(active.peerRequest.sent or now)>5000 then failCraft(state,\"Redstone Requester did not respond\")end elseif active.phase==\"await_peer_package\"then local pending=active.packageRequest local reply=takeCraftReply(pending and pending.id)if reply then active.packageRequest=nil local accepted,err=reply.ok and crafting.acceptedCount(reply.result,pending.requested or pending.input.count)or nil,reply.result if not accepted then failCraft(state,err or\"peer Stock Ticker rejected package\")else active.issued,active.issuedKind,active.issuedAt=true,\"package\",now active.packageRequest={input=pending.input,baseline=pending.baseline,requested=pending.requested or pending.input.count,accepted=accepted,remaining=(pending.requested or pending.input.count)-accepted}active.phase,active.waitingFor,active.deadline=\"await_package_confirmation\",pending.input.name,now+timeout state.nextRefresh=0 end elseif pending and now-(pending.sent or now)>5000 then failCraft(state,\"peer Stock Ticker did not respond to package request\")end elseif active.phase==\"await_package_confirmation\"then local package=active.packageRequest if not package then failCraft(state,\"lost package confirmation state\")elseif(crafting.normalise(state.stock)[package.input.name]or 0)<=package.baseline-package.accepted then if package.remaining and package.remaining>0 then active.packageRemaining,active.packageRequest,active.phase=package.remaining,nil,\"craft\"else active.packageIndex,active.packageRemaining,active.packageRequest,active.phase=(active.packageIndex or 1)+1,nil,nil,\"craft\"end else state.nextRefresh=0 end elseif active.phase==\"await_crafted_output\"then local step=active.plan[active.step]if(crafting.normalise(state.stock)[active.waitingFor]or 0)>=active.baseline+step.produced then active.step=active.step+1;active.phase=\"craft\"else state.nextRefresh=0 end elseif active.phase==\"deliver\"then local baseline=crafting.normalise(state.stock)[item.name]or 0 local ok,result if tickerSource.transport==\"peer\"then if not active.peerRequest then local requestId,err=requestPeerCraft(tickerSource,\"craft_request\",{name=tickerSource.name,destination=active.destination,filters={{name=item.name,_requestCount=item.count}}})if not requestId then failCraft(state,err)else active.peerRequest,active.phase={id=requestId,kind=\"delivery\",baseline=baseline,sent=now},\"await_peer_delivery\"end end saveCraft(state);return else ok,result=peripherals.craftRequest(\"local\",tickerSource.name,active.destination,{{name=item.name,_requestCount=item.count}})end local accepted,acceptError if ok then accepted,acceptError=crafting.acceptedCount(result,item.count)else acceptError=result end if not accepted then failCraft(state,acceptError or result)else active.requested,active.accepted,active.delivered,active.remaining=item.count,accepted,0,item.count-accepted active.issued,active.issuedKind,active.issuedAt=true,\"delivery\",now active.phase,active.baseline,active.waitingFor,active.deadline=\"await_delivery_confirmation\",baseline,item.name,now+timeout state.nextRefresh=0 end elseif active.phase==\"await_peer_delivery\"then local reply=takeCraftReply(active.peerRequest and active.peerRequest.id)if reply then local baseline=active.peerRequest.baseline;active.peerRequest=nil local accepted,err=reply.ok and crafting.acceptedCount(reply.result,item.count)or nil,reply.result if not accepted then failCraft(state,err or\"peer Stock Ticker rejected the request\")else active.requested,active.accepted,active.delivered,active.remaining=item.count,accepted,0,item.count-accepted active.issued,active.issuedKind,active.issuedAt=true,\"delivery\",now active.phase,active.baseline,active.waitingFor,active.deadline=\"await_delivery_confirmation\",baseline,item.name,now+timeout;state.nextRefresh=0 end end elseif active.phase==\"await_delivery_confirmation\"then if(crafting.normalise(state.stock)[active.waitingFor]or 0)<=active.baseline-active.accepted then active.delivered=active.accepted local itemResult={id=active.id,status=active.remaining>0 and\"partial-dispatched\"or\"dispatched\",name=item.name,requested=active.requested,accepted=active.accepted,dispatched=active.delivered,remaining=active.remaining,destination=active.destination,finished=os.epoch(\"utc\")}pushCraftHistory(state,itemResult)if active.remaining>0 then state.sequence=state.sequence+1 state.retries[#state.retries+1]={id=\"craft-retry-\"..tostring(os.epoch(\"utc\"))..\"-\"..tostring(state.sequence),items={{name=item.name,count=active.remaining}},craftMode=active.craftMode,destination=active.destination,retryOf=active.id}end completeCraftItem(state)else state.nextRefresh=0 end end end saveCraft(state)end local function craftingStatus()store.invalidate(CRAFT_STATE)local state=store.read(CRAFT_STATE,craftDefault())local active,item=state.active,state.active and state.active.items and state.active.items[state.active.index]local history=state.history or{}return{active=active and{id=active.id,phase=active.phase,name=item and item.name,requested=active.requested or(item and item.count),accepted=active.accepted,dispatched=active.delivered,remaining=active.remaining,destination=active.destination,issued=active.issued,issuedKind=active.issuedKind,requesterConfigured=active.requesterConfigured,requesterStrict=active.requesterStrict,waitingFor=active.waitingFor,expectedOutput=active.expectedOutput,pendingCraftRequests=active.pendingCraftRequests,stepAddress=active.stepAddress,stepRoute=active.stepRoute,packageIndex=active.packageIndex,packageCount=active.packageCount}or nil,queue=#(state.queue or{}),retries=#(state.retries or{}),error=state.error,recoveryNotice=state.recoveryNotice,recipeServer=state.config and state.config.recipeServer,last=history[#history],stockUpdated=state.stockUpdated,}end local function craftingPeripheralStatus()local state=craftState()refreshCraftSources(state,false)local tickerSource,requesterSource=craftSources.kind(state.config.ticker),craftSources.kind(state.config.requester)local requester=requesterSource and requesterSource.transport~=\"peer\"and peripheral.wrap(requesterSource.name)or nil local encoded=nil if requester and type(requester.getRequest)==\"function\"then local ok,value=pcall(requester.getRequest)if ok and type(value)==\"table\"then for _ in pairs(value)do encoded=(encoded or 0)+1 end end end local configuration=requester and type(requester.getConfiguration)==\"function\"and select(2,pcall(requester.getConfiguration))or nil local address=requester and type(requester.getAddress)==\"function\"and select(2,pcall(requester.getAddress))or nil return{ticker=tickerSource and{name=tickerSource.name,transport=tickerSource.transport,peer=tickerSource.peer,available=sourceAvailable(tickerSource,\"stockticker\")}or nil,requester=requesterSource and{name=requesterSource.name,transport=requesterSource.transport,peer=requesterSource.peer,available=sourceAvailable(requesterSource,\"redstonerequester\"),configuration=configuration,address=address,encodedSlots=encoded}or nil,sources=state.sources}end local function processDevNetworkCommand()local command=networkIpc.take()if type(command)~=\"table\"then return end writeDevValue(DEV_NETWORK_IPC_DIAG,{id=command.id,action=command.action,phase=\"received\",at=os.epoch(\"utc\")})local ok,result,detail=pcall(function()if command.action==\"network_status\"then return net.statusSnapshot()elseif command.action==\"route_status\"then return net.routeStatus(command.target)elseif command.action==\"network_trace\"then return net.transportTrace(command.kind)elseif command.action==\"peripheral_status\"then return{localDevices=peripherals.listLocal(),sharedDevices=peripherals.describe(),crafting=craftingPeripheralStatus()}elseif command.action==\"craft_status\"then return craftingStatus()elseif command.action==\"update_status\"then auth.require(\"operator\");return updater.status()elseif command.action==\"update_check\"then auth.require(\"operator\");return updater.check()elseif command.action==\"update_offers\"then auth.require(\"operator\");return updater.status().offers elseif command.action==\"update_download\"then auth.require(\"operator\");return updater.download(command.source)elseif command.action==\"update_cancel\"then auth.require(\"operator\");return updater.cancel()elseif command.action==\"update_clear_cache\"then auth.require(\"operator\");return updater.clearCache()elseif command.action==\"update_apply\"then auth.require(\"operator\")local applied,detail=updater.prepareApply()if not applied then return false,detail end return{reboot=true,detail=detail}elseif command.action==\"discovery_start\"then auth.require(\"operator\");return net.startDiscovery(command.mode or\"peer\",command.master or\"initiator\",command.phrase)elseif command.action==\"discovery_join\"then auth.require(\"operator\");return net.joinDiscovery(command.phrase)elseif command.action==\"discovery_confirm\"then auth.require(\"operator\");return net.confirmDiscovery()elseif command.action==\"discovery_cancel\"then auth.require(\"operator\");return net.cancelDiscovery()elseif command.action==\"remote_request\"then auth.require(\"operator\");return net.request(command.target,command.type,command.body or{})elseif command.action==\"auth_send\"then if type(command.target)~=\"string\"or type(command.type)~=\"string\"or type(command.body)~=\"table\"then return false,\"invalid authority request\"end return net.request(command.target,command.type,command.body,{safe=true,confidential=true})end error(\"unknown development network command\")end)if not ok then detail,result=result,nil elseif result==true and detail~=nil then result,detail=detail,nil elseif result==false then ok,detail=false,detail or\"network command failed\"end local replied,replyErr=networkIpc.reply(command.id,{id=command.id,ok=ok,result=ok and result or nil,error=ok and nil or tostring(detail)})if not replied then error(\"could not write network IPC result: \"..tostring(replyErr),0)end writeDevValue(DEV_NETWORK_IPC_DIAG,{id=command.id,action=command.action,phase=\"replied\",ok=ok,at=os.epoch(\"utc\")})networkIpc.prune(32)writeDevValue(DEV_NETWORK_STATUS,net.statusSnapshot())end math.randomseed(os.epoch(\"utc\"))auth.bootstrap()net.start()updater.recover()shell.setPath(\"/ceetos/bin:\"..shell.path())shell.setAlias(\"craftos-programs\",\"/rom/programs/programs.lua\")shell.setAlias(\"craftos-list\",\"/rom/programs/list.lua\")shell.setAlias(\"craftos-delete\",\"/rom/programs/delete.lua\")shell.setAlias(\"craftos-edit\",\"/rom/programs/edit.lua\")shell.setAlias(\"craftos-shell\",\"/ceetos/bin/craftos-shell.lua\")shell.setAlias(\"devices\",\"/ceetos/bin/ceetdevices.lua\")shell.setAlias(\"shareall\",\"/ceetos/bin/ceetshareall.lua\")shell.setAlias(\"unshareall\",\"/ceetos/bin/ceetunshareall.lua\")shell.setAlias(\"craft\",\"/ceetos/bin/ceetcraft.lua\")local function commandArgs(command)local result={}for token in tostring(command or\"\"):gmatch(\"%S+\")do result[#result+1]=token end return result end local function runCaptured(command)local output,old={},term.current()local capture={}function capture.write(text)output[#output+1]=tostring(text or\"\")end function capture.blit(text)output[#output+1]=tostring(text or\"\")end function capture.setCursorPos()end function capture.setCursorBlink()end setmetatable(capture,{__index=old})term.redirect(capture)local args=commandArgs(command)local ok,result=pcall(function()return shell.run(args[1],table.unpack(args,2))end)term.redirect(old)return ok,result,table.concat(output)end local function jobStatus()local state=jobs.state()local running=0;for _ in pairs(state.running or{})do running=running+1 end return{label=os.getComputerLabel(),capacity=state.capacity or 1,inFlight=running,queueDepth=#(state.queue or{}),available=true}end local function writeJobInbox(job)local inbox=store.read(JOB_INBOX,{})inbox[#inbox+1]=job while#inbox>16 do table.remove(inbox,1)end store.write(JOB_INBOX,inbox)end local function workerJobLoop()while true do store.invalidate(JOB_INBOX)local inbox=store.read(JOB_INBOX,{})local job=table.remove(inbox,1)if job then store.write(JOB_INBOX,inbox)local template=jobs.listTemplates()[job.template]local valid=template and template.revision==job.revision and template.command==job.command local ok,result,output=false,\"template mismatch\",\"\"if valid then ok,result,output=runCaptured(job.command)end local outbox=store.read(JOB_OUTBOX,{})outbox[#outbox+1]={id=job.id,controller=job.controller,ok=valid and ok and result~=false,output=output,error=valid and(ok and nil or tostring(result))or result}while#outbox>16 do table.remove(outbox,1)end store.write(JOB_OUTBOX,outbox)else sleep(0.15)end end end local function chooseWorker()local choices={}for workerId,worker in pairs(jobs.workers())do if worker.healthy and(worker.slots or 0)>0 then choices[#choices+1]=worker end end table.sort(choices,function(a,b)local aLoad,bLoad=(a.inFlight or 0)/math.max(1,a.capacity or 1),(b.inFlight or 0)/math.max(1,b.capacity or 1)if aLoad~=bLoad then return aLoad<bLoad end if(a.hops or 0)~=(b.hops or 0)then return(a.hops or 0)<(b.hops or 0)end return tostring(a.id)<tostring(b.id)end)return choices[1]end local function syncJobTemplates()if tostring(net.controller())~=tostring(os.getComputerID())then return end local payload={controller=net.controller(),templates=jobs.listTemplates()}for _,peer in ipairs(net.peers())do net.request(peer.id,\"job_sync\",payload)end end local function processJobOutbox()store.invalidate(JOB_OUTBOX)local outbox=store.read(JOB_OUTBOX,{})if#outbox==0 then return end store.write(JOB_OUTBOX,{})for _,row in ipairs(outbox)do if tostring(row.controller)==tostring(os.getComputerID())then if row.ok then pcall(jobs.complete,row.id,{output=row.output,ok=true})else pcall(jobs.fail,row.id,row.error or\"worker failed\")end else net.request(row.controller,\"job_result\",row)end end end local function dispatchJobs()if tostring(jobs.controller())~=tostring(net.controller())then jobs.setController(net.controller())end jobs.heartbeat(os.getComputerID(),jobStatus())if tostring(net.controller())~=tostring(os.getComputerID())then net.request(net.controller(),\"job_heartbeat\",jobStatus(),{safe=true})return end jobs.tick()if os.epoch(\"utc\")-lastJobTemplateSync>=10000 then syncJobTemplates();lastJobTemplateSync=os.epoch(\"utc\")end while true do local queued,worker=jobs.nextDispatch(),chooseWorker()if not queued or not worker then break end local ok,assigned=pcall(jobs.assign,queued,worker.id)if not ok then break end assigned.controller=tostring(os.getComputerID())if tostring(worker.id)==tostring(os.getComputerID())then writeJobInbox(assigned)else local sent,err=net.request(worker.id,\"job_dispatch\",assigned)if not sent then pcall(jobs.fail,assigned.id,err)end end end end local function syncAccounts()if auth.centralActive and auth.centralActive()then return end local snapshot=auth.snapshot()for _,peer in ipairs(net.directPeers())do net.request(peer.id,\"account_sync\",snapshot)end end net.publicHandler=function(packet,distance)local ok,err=pcall(updater.publicPacket,packet,distance)if not ok then audit.log(\"system\",\"update.public_packet_error\",{error=tostring(err):sub(1,120)})end end net.handler=function(from,peer,packet)if packet.type==\"update_query\"or packet.type==\"update_offer\"or packet.type==\"update_chunk_request\"or packet.type==\"update_chunk\"then local ok,err=pcall(updater.authenticatedPacket,from,peer,packet)if not ok then audit.log(\"system\",\"update.packet_error\",{error=tostring(err):sub(1,120)})end return end if packet.type==\"announce\"then print(\"[peer] \"..from..\" is online\"..((packet.body and packet.body.label)and(\" (\"..packet.body.label..\")\")or\"\"))elseif packet.type==\"profile_query\"then net.reply(packet,\"profile_status\",{profile=profile.id(),version=version.string},{safe=true})elseif packet.type==\"profile_status\"then recordProfile(packet.origin or from,packet.body)elseif packet.type==\"peripheral_list\"then net.reply(packet,\"peripheral_list_result\",peripherals.describe(),{safe=true})elseif packet.type==\"peripheral_list_result\"then local origin=packet.origin or from local cache=store.read(\"/ceetos/data/remote/\"..origin..\".lua\",{})cache.peripherals,cache.updated=packet.body or{},os.epoch(\"utc\")store.write(\"/ceetos/data/remote/\"..origin..\".lua\",cache)elseif packet.type==\"peripheral_call\"then local body=packet.body or{}local ok,result=peripherals.call(peer.master,body.name,body.method,body.args)net.reply(packet,\"peripheral_result\",{ok=ok,result=result})elseif packet.type==\"peripheral_result\"then local origin=packet.origin or from local cache=store.read(\"/ceetos/data/remote/\"..origin..\".lua\",{})cache.last_result,cache.updated=packet.body,os.epoch(\"utc\")store.write(\"/ceetos/data/remote/\"..origin..\".lua\",cache)elseif packet.type==\"craft_stock_request\"then local body=packet.body or{}local origin=tostring(packet.origin or from)local ok,result=peripherals.call(peer.master,body.name,\"stock\",{true})net.reply(packet,\"craft_stock_result\",{request_id=body.request_id,ok=ok,result=result},{safe=true})elseif packet.type==\"craft_stock_result\"then local body=packet.body or{}if type(body.request_id)==\"string\"then local replies=store.read(CRAFT_REPLY_PATH,{})replies[body.request_id]={ok=body.ok==true,result=body.result,received=os.epoch(\"utc\"),from=packet.origin or from}store.write(CRAFT_REPLY_PATH,replies)end elseif packet.type==\"recipe_plan_request\"then local body=packet.body or{}local valid=type(body.request_id)==\"string\"and#body.request_id<=120 and type(body.item)==\"string\"and#body.item<=128 and tonumber(body.quantity)and tonumber(body.quantity)>=1 and tonumber(body.quantity)<=256 and type(body.stock)==\"table\"local stockCount=0 for _,row in pairs(type(body.stock)==\"table\"and body.stock or{})do stockCount=stockCount+1 if stockCount>512 or type(row)~=\"table\"or type(row.name or row.id)~=\"string\"or tonumber(row.count or row.amount or row.quantity or 0)==nil then valid=false;break end end local ok,result=false,\"invalid recipe plan request\"if valid then local recipes,tags,err=craftRecipes()if recipes then local plan,planErr=crafting.plan(recipes,body.stock,body.item,math.floor(tonumber(body.quantity)),{forceRoot=true,tags=tags})if plan and#plan<=96 then local encoded=textutils.serialise(plan)if#encoded<=12*1024 then ok,result=true,plan else result=\"recipe plan exceeds remote reply limit\"end else result=planErr or\"recipe plan exceeds remote reply limit\"end else result=err or\"recipe database is unavailable\"end end net.reply(packet,\"recipe_plan_result\",{request_id=body.request_id,ok=ok,result=result},{safe=true})elseif packet.type==\"recipe_plan_result\"then local body=packet.body or{}if type(body.request_id)==\"string\"then local replies=store.read(CRAFT_REPLY_PATH,{})replies[body.request_id]={ok=body.ok==true,result=body.result,received=os.epoch(\"utc\"),from=packet.origin or from}store.write(CRAFT_REPLY_PATH,replies)end elseif packet.type==\"craft_request\"then local body=packet.body or{}local origin=tostring(packet.origin or from)local allowed=net.isDirectController(from,packet)and(peer.role==\"admin\"or peer.role==\"operator\")local ok,result=false,\"craft request is not authorised\"if allowed then ok,result=peripherals.craftRequest(peer.master,body.name,body.destination,body.filters)end net.reply(packet,\"craft_result\",{request_id=body.request_id,ok=ok,result=result})elseif packet.type==\"craft_recipe_request\"then local body=packet.body or{}local origin=tostring(packet.origin or from)local allowed=net.isDirectController(from,packet)and(peer.role==\"admin\"or peer.role==\"operator\")local ok,result=false,\"craft recipe request is not authorised\"if allowed then ok,result=peripherals.craftingRecipeRequest(peer.master,body.name,body.address,body.batches,body.grid)end net.reply(packet,\"craft_result\",{request_id=body.request_id,ok=ok,result=result})elseif packet.type==\"craft_result\"then local body=packet.body or{}if type(body.request_id)==\"string\"then local replies=store.read(CRAFT_REPLY_PATH,{})replies[body.request_id]={ok=body.ok==true,result=body.result,received=os.epoch(\"utc\"),from=packet.origin or from}local count=0;for _ in pairs(replies)do count=count+1 end if count>32 then local oldest,oldestTime for key,row in pairs(replies)do if not oldestTime or(row.received or 0)<oldestTime then oldest,oldestTime=key,row.received or 0 end end if oldest then replies[oldest]=nil end end store.write(CRAFT_REPLY_PATH,replies)end elseif packet.type==\"shell_request\"then if peer.role~=\"admin\"and peer.role~=\"operator\"then return end local command=packet.body and packet.body.command if type(command)~=\"string\"or#command>240 or command:match(\"^%s*nx%s+recover\")then return end audit.log(\"peer:\"..from,\"shell.request\",{command=command,session=packet.body and packet.body.session})print(\"[remote \"..from..\"] \"..command)local ok,result,output=runCaptured(command)if packet.body and packet.body.session then net.reply(packet,\"shell_result\",{session=packet.body.session,ok=ok and result~=false,output=output,error=ok and nil or tostring(result)})end elseif packet.type==\"shell_result\"then local replies=store.read(SHELL_REPLY_PATH,{})replies[#replies+1]={from=from,body=packet.body or{},received=os.epoch(\"utc\")}while#replies>20 do table.remove(replies,1)end store.write(SHELL_REPLY_PATH,replies)elseif packet.type==\"auth_seed_request\"then net.reply(packet,\"auth_seed\",{snapshot=auth.authoritySnapshot(),request_id=packet.body and packet.body.request_id},{safe=true,confidential=true})elseif packet.type==\"auth_authority\"then local ok,err=pcall(auth.acceptAuthority,packet.body)if not ok then audit.log(\"system\",\"auth.authority_rejected\",{error=tostring(err):sub(1,120)})end elseif packet.type==\"auth_login_begin_result\"or packet.type==\"auth_login_proof_result\"or packet.type==\"auth_mutate_result\"then require((\"ceetos.lib.auth_client\")).receive(packet.body)elseif packet.type==\"account_sync\"then local changed,mergeError=auth.merge(packet.body)if changed then audit.log(\"peer:\"..from,\"accounts.sync\",{});syncAccounts()elseif mergeError then audit.log(\"peer:\"..from,\"accounts.sync_rejected\",{})end elseif packet.type==\"job_heartbeat\"then if tostring(net.controller())==tostring(os.getComputerID())then local body=packet.body or{};body.hops=1 jobs.heartbeat(from,body)end elseif packet.type==\"job_sync\"then local body=packet.body or{}if net.isDirectController(from,packet)and tostring(body.controller)==tostring(net.controller())and type(jobs.syncTemplates)==\"function\"then jobs.syncTemplates(body.controller,body.templates or{})end elseif packet.type==\"job_dispatch\"then local body=packet.body or{}if not net.isDirectController(from,packet)or tostring(body.controller)~=tostring(net.controller())then audit.log(\"peer:\"..from,\"jobs.rejected\",{reason=\"not_controller\"});return end local template=jobs.listTemplates()[body.template]if not template or template.revision~=body.revision or template.command~=body.command then audit.log(\"peer:\"..from,\"jobs.rejected\",{reason=\"template_mismatch\"});return end writeJobInbox(body)elseif packet.type==\"job_result\"then if tostring(net.controller())==tostring(os.getComputerID())then local body=packet.body or{}if body.ok then pcall(jobs.complete,body.id,{output=body.output,ok=true})else pcall(jobs.fail,body.id,body.error or\"worker failed\")end end end end local function serviceLoop()local discoveryTimer,accountTimer,jobTimer,craftTimer,updateTimer,cloudTimer=os.startTimer(2),os.startTimer(2),os.startTimer(2),os.startTimer(0.1),os.startTimer(1),os.startTimer(5)local started,lastError=os.epoch(\"utc\"),nil local function health(errorText)if errorText then lastError=tostring(errorText):sub(1,240)end writeDevValue(DEV_NETWORK_HEALTH,{started=started,lastEvent=os.epoch(\"utc\"),healthy=lastError==nil,error=lastError,ipc=networkIpc.status()})end health()while true do local event={os.pullEventRaw()}local handled,handleErr=pcall(net.handle,event)if not handled then health(handleErr)audit.log(\"system\",\"network.packet_error\",{error=tostring(handleErr):sub(1,120)})else health()end local ipcOk,ipcErr=pcall(processDevNetworkCommand)if not ipcOk then health(ipcErr)audit.log(\"system\",\"network.ipc_error\",{error=tostring(ipcErr):sub(1,120)})end if event[1]==\"timer\"and event[2]==discoveryTimer then local tickOk,tickErr=pcall(net.tick)if not tickOk then health(tickErr)audit.log(\"system\",\"network.tick_error\",{error=tostring(tickErr):sub(1,120)})end local snapshotOk,snapshot=pcall(net.statusSnapshot)if snapshotOk then local wrote,writeErr=writeDevValue(DEV_NETWORK_STATUS,snapshot)if not wrote then health(writeErr)audit.log(\"system\",\"network.status_persist_error\",{error=tostring(writeErr):sub(1,120)})end else health(snapshot)audit.log(\"system\",\"network.status_error\",{error=tostring(snapshot):sub(1,120)})end discoveryTimer=os.startTimer(2)end if event[1]==\"timer\"and event[2]==accountTimer then syncAccounts()if os.epoch(\"utc\")-lastProfileAdvert>=30000 then for _,peer in ipairs(net.peers())do net.request(peer.id,\"profile_status\",{profile=profile.id(),version=version.string},{safe=true})end lastProfileAdvert=os.epoch(\"utc\")end accountTimer=os.startTimer(10)end if event[1]==\"timer\"and event[2]==jobTimer then processJobOutbox()local ok,err=pcall(dispatchJobs)if not ok then audit.log(\"system\",\"jobs.scheduler_error\",{error=tostring(err)})end jobTimer=os.startTimer(2)end if event[1]==\"timer\"and event[2]==craftTimer then local ok,err=pcall(tickCraftQueue)if not ok then local state=craftState()failCraft(state,\"crafting queue service error: \"..tostring(err))saveCraft(state)audit.log(\"system\",\"crafting.queue_error\",{error=tostring(err)})end craftTimer=os.startTimer(0.1)end if event[1]==\"timer\"and event[2]==updateTimer then local ok,err=pcall(updater.tick)if not ok then health(err)audit.log(\"system\",\"update.service_error\",{error=tostring(err):sub(1,120)})end updateTimer=os.startTimer(1)end if event[1]==\"timer\"and event[2]==cloudTimer then local ok,err=pcall(cloudSync.tick)if not ok then audit.log(\"system\",\"cloud.sync_error\",{error=tostring(err):sub(1,120)})end cloudTimer=os.startTimer(5)end end end local function userDesktop()print(\"CeetOS \"..version.string..\" | computer \"..os.getComputerID()..\" -- starting Desktop\")while true do if fs.exists(\"/ceetos/data/desktop-stop\")then fs.delete(\"/ceetos/data/desktop-stop\")end local ok=shell.run(\"/ceetos/bin/ceetui.lua\")if ok==false and not fs.exists(\"/ceetos/data/desktop-stop\")then printError(\"CeetUI stopped; restarting in 2 seconds...\")sleep(2)elseif fs.exists(\"/ceetos/data/desktop-stop\")then fs.delete(\"/ceetos/data/desktop-stop\")return end end end local function devBridgeLoop()local path=\"/ceetos-dev/connection.lua\"while true do if fs.exists(path)then local handle=fs.open(path,\"r\")local cfg=handle and textutils.unserialise(handle.readAll())or nil if handle then handle.close()end if type(cfg)==\"table\"and type(cfg.url)==\"string\"then local token=type(cfg.token)==\"string\"and cfg.token or\"\"if token~=\"\"then pcall(shell.run,\"/ceetos/bin/ceetdev.lua\",cfg.url,token)else pcall(shell.run,\"/ceetos/bin/ceetdev.lua\",cfg.url)end sleep(3)else sleep(5)end else sleep(5)end end end parallel.waitForAny(serviceLoop,workerJobLoop,userDesktop,devBridgeLoop)",
  ["ceetos/bin/nx.lua"] = "package.path=\"/?.lua;/?/init.lua;\"..package.path local auth=require(\"ceetos.lib.auth\")local net=require(\"ceetos.lib.net\")local peripherals=require(\"ceetos.lib.peripherals\")local telemetry=require(\"ceetos.lib.telemetry\")local cloudSync=require(\"ceetos.lib.cloud_sync\")local ownerService=require(\"ceetos.lib.owner_service\")local store=require(\"ceetos.lib.store\")local audit=require(\"ceetos.lib.audit\")local jobs=require(\"ceetos.lib.jobs\")local networkIpc=require(\"ceetos.lib.network_ipc\")local args={...}local requestSequence=0 local function networkRequest(action,body)requestSequence=requestSequence+1 local request=body or{}request.id=\"nx-\"..tostring(os.getComputerID())..\"-\"..tostring(os.epoch(\"utc\"))..\"-\"..tostring(requestSequence)request.action=action local submitted,submitErr=networkIpc.submit(request)if not submitted then return false,submitErr or\"CeetOS network service is unavailable\"end local deadline=os.epoch(\"utc\")+5000 while os.epoch(\"utc\")<deadline do local response=networkIpc.poll(request.id,true)if response and response.id==request.id then return response.ok==true,response.result or response.error end sleep(0.1)end return false,\"CeetOS network service did not respond\"end local function usage()print(\"CeetOS: help, gui, craft, whoami, login, logout, users, user add/edit/delete, discover, network, peers, share, unshare, peripherals, remote, jobs, update, telemetry, cloud status|enroll <code>|retry|clear, owner-service, recover\")end local function requireArgs(n)if#args<n then error(\"missing argument\",0)end end local command=args[1]or\"help\"if command==\"help\"then usage()elseif command==\"gui\"then shell.run(\"ceetui\")elseif command==\"craft\"then shell.run(\"ceetcraft\",table.unpack(args,2))elseif command==\"whoami\"then print(auth.current and(auth.current.name..\" (\"..auth.current.role..\")\")or\"not logged in\")elseif command==\"login\"then requireArgs(2);term.write(\"Password: \");local pass=read(\"*\")if auth.login(args[2],pass)then print(\"Logged in.\")else printError(\"Invalid credentials.\")end elseif command==\"logout\"then auth.logout();print(\"Logged out.\")elseif command==\"users\"then auth.require(\"operator\");for _,user in ipairs(auth.list())do print(user.name..\"\\t\"..user.role)end elseif command==\"user\"and args[2]==\"add\"then auth.require(\"operator\");requireArgs(4);term.write(\"Password for \"..args[3]..\": \");local pass=read(\"*\")auth.add(args[3],args[4],pass);audit.log(auth.current.name,\"user.add\",{name=args[3],role=args[4]});print(\"User created.\")elseif command==\"user\"and args[2]==\"edit\"then auth.require(\"operator\");requireArgs(4);auth.setRole(args[3],args[4]);audit.log(auth.current.name,\"user.role\",{name=args[3],role=args[4]});print(\"User role updated.\")elseif command==\"user\"and args[2]==\"delete\"then auth.require(\"operator\");requireArgs(3);auth.remove(args[3]);audit.log(auth.current.name,\"user.delete\",{name=args[3]});print(\"User deleted.\")elseif command==\"peers\"then local ok,result=networkRequest(\"network_status\",{})if not ok then printError(result)else for _,peer in ipairs(result.peers or{})do print(peer.id..\"\\t\"..peer.role..(peer.master and\"\\tmaster\"or\"\")..(peer.routed and\"\\trouted\"or\"\"))end end elseif command==\"discover\"then auth.require(\"operator\")if args[2]==\"status\"then local ok,result=networkRequest(\"network_status\",{});if not ok then printError(result)else print(textutils.serialize(result.discovery or{}))end elseif args[2]==\"cancel\"then local ok,result=networkRequest(\"discovery_cancel\",{});if ok then print(\"Discovery cancelled.\")else printError(result)end elseif args[2]==\"join\"then local ok,result=networkRequest(\"discovery_join\",{phrase=args[3]})if not ok then printError(result)elseif type(result)==\"table\"and result.state==\"candidate\"then print(\"Matching computer found. Run 'nx discover confirm' to pair.\")else print(\"Searching for a matching discovery session.\")end elseif args[2]==\"confirm\"then local ok,err=networkRequest(\"discovery_confirm\",{});if not ok then printError(err)else print(\"Pairing confirmation sent.\")end elseif args[2]==\"start\"then requireArgs(3)local phrase=args[3];local mode=args[4]==\"master\"and\"master\"or\"peer\";local master=args[5]or\"initiator\"local ok,err=networkRequest(\"discovery_start\",{phrase=phrase,mode=mode,master=master})if not ok then printError(err)else print(\"Discovery started. Keep this phrase private and have the other computer enter it.\")end else printError(\"use discover start <phrase> [peer|master] [initiator|joiner], join <phrase>, confirm, cancel, or status\")end elseif command==\"network\"and args[2]==\"status\"then local ok,result=networkRequest(\"network_status\",{});if not ok then printError(result)else print(textutils.serialize(result.transport or{}))end elseif command==\"network\"and args[2]==\"routes\"then local ok,result=networkRequest(\"route_status\",{target=args[3]});if not ok then printError(result)else for _,route in ipairs(result or{})do print(tostring(route.id)..\" via \"..tostring(route.next)..\" / \"..tostring(route.hops)..\" hop [\"..tostring(route.health)..\"]\"..(route.reason and(\" - \"..tostring(route.reason))or\"\"))end end elseif command==\"network\"and args[2]==\"trace\"then local ok,result=networkRequest(\"network_trace\",{kind=args[3]});if not ok then printError(result)else print(textutils.serialize(result))end elseif command==\"update\"then auth.require(\"operator\")local sub=args[2]or\"status\"if sub==\"status\"then local ok,result=networkRequest(\"update_status\",{})if not ok then printError(result)else print(\"CeetOS \"..tostring(result.version)..\" | \"..tostring(result.status or\"idle\"))if result.message then print(tostring(result.message))end if result.cache then print(\"Cached release: \"..tostring(result.cache.version)..\"  \"..tostring(result.cache.fingerprint)..\"  key \"..tostring(result.cache.keyId))end if result.transfer then print(\"Download: \"..tostring(result.transfer.received or 0)..\"/\"..tostring(result.transfer.size)..\" bytes from \"..tostring(result.transfer.label or result.transfer.source))end end elseif sub==\"check\"then local ok,result=networkRequest(\"update_check\",{})if not ok then printError(result)elseif type(result)==\"table\"then print(\"Cloud offers: \"..tostring(result.cloud or 0)..\" | direct mesh query: \"..(result.direct and\"sent\"or\"unavailable\")..\" | routed queries: \"..tostring(result.routed or 0))if result.cloudError then printError(\"Cloud check failed: \"..tostring(result.cloudError))end else print(\"Signed release check started.\")end elseif sub==\"offers\"then local ok,result=networkRequest(\"update_offers\",{})if not ok then printError(result)elseif#result==0 then print(\"No newer signed releases discovered.\")else for _,offer in ipairs(result)do print(tostring(offer.id)..\"\\t\"..tostring(offer.label)..\"\\t\"..tostring(offer.version)..\"\\t\"..tostring(offer.size)..\" bytes\\t\"..tostring(offer.fingerprint)..\"\\t\"..tostring(offer.keyId)..\"\\t\"..tostring(offer.transport))end end elseif sub==\"download\"then requireArgs(3)local ok,result=networkRequest(\"update_download\",{source=args[3]})if ok then print(\"Download started. Run 'nx update status' to follow verified progress.\")else printError(result)end elseif sub==\"cancel\"then local ok,result=networkRequest(\"update_cancel\",{});if ok then print(\"Update download cancelled.\")else printError(result)end elseif sub==\"clear-cache\"then local ok,result=networkRequest(\"update_clear_cache\",{});if ok then print(\"Verified release cache cleared.\")else printError(result)end elseif sub==\"apply\"then local ok,status=networkRequest(\"update_status\",{})if not ok then printError(status)elseif not status.cache then printError(\"No verified signed release is cached.\")else print(\"Apply CeetOS \"..tostring(status.cache.version)..\" from verified cache\")print(\"Fingerprint: \"..tostring(status.cache.fingerprint)..\"  Key: \"..tostring(status.cache.keyId))term.write(\"Type APPLY to reboot and install locally: \")if read()~=\"APPLY\"then print(\"Cancelled.\")else local prepared,result=networkRequest(\"update_apply\",{})if not prepared then printError(result)else print(\"Verified update approved; rebooting locally.\");os.reboot()end end end else printError(\"use update status|check|offers|download <source>|apply|cancel|clear-cache\")end elseif command==\"pair\"then printError(\"legacy ID/code pairing is disabled. Use 'nx discover start <phrase>' and 'nx discover join <phrase>'.\")elseif command==\"share\"then auth.require(\"operator\");requireArgs(2)if args[2]==\"all\"then print(\"Shared \"..peripherals.shareAll(args[3]==\"master\"and\"master\"or\"peer\")..\" peripherals\")else peripherals.share(args[2],args[3]or\"peer\");print(\"Shared \"..args[2])end elseif command==\"unshare\"then auth.require(\"operator\");requireArgs(2)if args[2]==\"all\"then print(\"Unshared \"..peripherals.unshareAll()..\" peripherals\")else peripherals.unshare(args[2]);print(\"Unshared \"..args[2])end elseif command==\"peripherals\"then for _,p in ipairs(peripherals.describe())do print(p.name..\"\\t\"..p.type..\"\\t\"..p.mode)end elseif command==\"remote\"then auth.require(\"operator\");requireArgs(3)local peer,mode=args[2],args[3]if mode==\"peripherals\"then local ok,err=networkRequest(\"remote_request\",{target=peer,type=\"peripheral_list\",body={}});if not ok then printError(err)else print(\"Peripheral query sent. Run 'nx remote \"..peer..\" cache' after the reply arrives.\")end elseif mode==\"cache\"then local cache=store.read(\"/ceetos/data/remote/\"..peer..\".lua\",{})if not cache.peripherals then print(\"No peripheral cache for peer \"..peer..\"; run 'nx remote \"..peer..\" peripherals' first.\")else for _,p in ipairs(cache.peripherals)do print(p.name..\"\\t\"..p.type..\"\\t\"..p.mode)end end elseif mode==\"call\"then requireArgs(5)local values={}for i=6,#args do values[#values+1]=tonumber(args[i])or args[i]end local ok,err=networkRequest(\"remote_request\",{target=peer,type=\"peripheral_call\",body={name=args[4],method=args[5],args=values}})if not ok then printError(err)else print(\"Peripheral call sent; the result will be displayed and cached when it arrives.\")end else local cmd=table.concat(args,\" \",3);local ok,err=networkRequest(\"remote_request\",{target=peer,type=\"shell_request\",body={command=cmd}});if not ok then printError(err)else print(\"Request sent.\")end end elseif command==\"jobs\"then local sub=args[2]or\"status\"local function controllerOnly()auth.require(\"admin\")assert(tostring(net.controller())==tostring(os.getComputerID()),\"this computer is not the network job controller (\"..tostring(net.controller())..\")\")end if sub==\"status\"then auth.require(\"operator\")local state=jobs.state();print(\"Controller: \"..tostring(net.controller())..\" | queue: \"..#(state.queue or{}))for id,worker in pairs(jobs.workers())do print(tostring(id)..\"\\t\"..tostring(worker.inFlight or 0)..\"/\"..tostring(worker.capacity or 1)..\"\\t\"..(worker.healthy and\"healthy\"or\"stale\"))end elseif sub==\"history\"then auth.require(\"operator\")for _,item in ipairs(jobs.history())do print(item.id..\"\\t\"..item.template..\"\\t\"..item.status..\"\\t\"..tostring(item.result and(item.result.error or item.result.output)or\"\"):sub(1,100))end elseif sub==\"templates\"then auth.require(\"operator\")for name,item in pairs(jobs.listTemplates())do print(name..\"\\t\"..(item.enabled==false and\"off\"or\"on\")..\"\\t\"..(item.retrySafe and\"retry-safe\"or\"no-retry\"))end elseif sub==\"template\"and args[3]==\"add\"then controllerOnly();requireArgs(5);local commandLine=table.concat(args,\" \",5)local template=jobs.addTemplate(args[4],commandLine,{});audit.log(auth.current.name,\"jobs.template_add\",{name=template.name});print(\"Template added.\")elseif sub==\"template\"and args[3]==\"retry-safe\"then controllerOnly();requireArgs(5);jobs.setTemplateRetrySafe(args[4],args[5]==\"on\");print(\"Retry policy updated.\")elseif sub==\"template\"and args[3]==\"enable\"then controllerOnly();requireArgs(5);jobs.setTemplateEnabled(args[4],args[5]~=\"off\");print(\"Template state updated.\")elseif sub==\"run\"then controllerOnly();requireArgs(3);local job=jobs.enqueue(args[3]);print(\"Queued \"..job.id)elseif sub==\"schedule\"then controllerOnly();requireArgs(4);local schedule=jobs.schedule(args[3],tonumber(args[4]));print(\"Scheduled \"..schedule.id)elseif sub==\"cancel\"then controllerOnly();requireArgs(3);jobs.cancel(args[3]);print(\"Schedule cancelled.\")elseif sub==\"capacity\"then auth.require(\"admin\");requireArgs(3);print(\"Worker capacity: \"..jobs.setCapacity(tonumber(args[3])))elseif sub==\"controller\"then controllerOnly();requireArgs(3);print(\"Controller: \"..net.setController(args[3]))else printError(\"use jobs status|history|templates|template add <name> <fixed command>|template retry-safe <name> on|off|run <name>|schedule <name> <seconds>|cancel <id>|capacity <slots>|controller <id>\")end elseif command==\"telemetry\"then requireArgs(2)if args[2]==\"status\"then auth.require(\"operator\")local status=cloudSync.status()print(\"Telemetry: \"..(telemetry.status()and\"enabled\"or\"disabled\")..\" | enrolled \"..(status.enrolled and\"yes\"or\"no\"))print(\"Last report: \"..tostring(status.telemetryLastSuccess or\"never\")..\" | next: \"..tostring(status.telemetryNext or\"disabled\"))if status.telemetryLastError then print(\"Last telemetry error: \"..status.telemetryLastError)end elseif args[2]==\"on\"or args[2]==\"off\"then auth.require(\"admin\");telemetry.setEnabled(args[2]==\"on\");audit.log(auth.current.name,\"telemetry\",{enabled=args[2]==\"on\"});print(\"Telemetry \"..args[2])else error(\"use telemetry status, telemetry on, or telemetry off\",0)end elseif command==\"cloud\"then local sub=args[2]or\"status\"if sub==\"status\"then auth.require(\"operator\")local status=cloudSync.status()print(\"Cloud: \"..(status.enrolled and\"enrolled\"or\"not enrolled\")..\" | auth \"..(status.authOnline and\"online\"or\"offline\")..\" | recipes \"..(status.recipeOnline and\"online\"or\"offline\"))if status.node then print(\"Node: \"..status.node)end if status.lastError then print(\"Last error: \"..status.lastError)end print(\"Telemetry: \"..(status.telemetryEnabled and\"enabled\"or\"disabled\")..\" | last \"..tostring(status.telemetryLastSuccess or\"never\")..\" | next \"..tostring(status.telemetryNext or\"disabled\"))print(\"Dashboard: https://dash.ceet.uk (Cloudflare Access)\")elseif sub==\"enroll\"then auth.require(\"admin\");requireArgs(3)local status,err=cloudSync.enroll(args[3]);if not status then printError(err)else audit.log(auth.current.name,\"cloud.enroll\",{node=status.node});print(\"Cloud node enrollment saved. Background sync is enabled.\")end elseif sub==\"retry\"then auth.require(\"operator\")local ok,err=cloudSync.tick(\"manual\");if ok then print(\"Cloud sync requested.\")else printError(err)end elseif sub==\"clear\"then auth.require(\"admin\")local ok,err=cloudSync.clear();if ok then audit.log(auth.current.name,\"cloud.clear\",{});print(\"Cloud enrollment removed.\")else printError(err)end else error(\"use cloud status|enroll <one-time-code>|retry|clear\",0)end elseif command==\"owner-service\"then auth.require(\"admin\")local sub=args[2]or\"status\"if sub==\"status\"then local status=ownerService.status()print(\"Owner service: \"..(status.enabled and\"enabled\"or\"disabled\")..\" | \"..(status.provisioned and\"provisioned\"or\"sealed\"))if status.owner then print(\"Owner: \"..status.owner)end print(\"Actions: \"..table.concat(status.actions or{},\", \"))elseif sub==\"on\"or sub==\"off\"then ownerService.setEnabled(sub==\"on\")audit.log(auth.current.name,\"owner-service.enabled\",{enabled=sub==\"on\"})print(\"Owner service \"..sub..\".\")elseif sub==\"set-token\"then term.write(\"Owner-service token: \");local token=read(\"*\")term.write(\"Repeat token: \");local repeatToken=read(\"*\")assert(token==repeatToken,\"tokens do not match\")ownerService.provision(token,auth.current.name)audit.log(auth.current.name,\"owner-service.provision\",{})print(\"Owner service provisioned. Configure the same secret in CEETOS_SERVICE_TOKENS on the dashboard.\")elseif sub==\"rotate-token\"then local token=ownerService.rotate(auth.current.name)audit.log(auth.current.name,\"owner-service.rotate\",{})print(\"New owner-service token (shown once): \"..token)print(\"Update CEETOS_SERVICE_TOKENS on the dashboard before making remote requests.\")else error(\"use owner-service status|on|off|set-token|rotate-token\",0)end elseif command==\"recover\"and args[2]==\"enable\"then auth.require(\"admin\");local minutes=tonumber(args[3])or 10;assert(minutes>0 and minutes<=60,\"minutes must be 1-60\")store.write(\"/ceetos/data/recovery.lua\",{until_ts=os.epoch(\"utc\")+minutes*60000});audit.log(auth.current.name,\"recovery.enable\",{minutes=minutes});print(\"Recovery access enabled for \"..minutes..\" minutes.\")elseif command==\"recover\"and args[2]==\"reset\"then requireArgs(3)local recovery=store.read(\"/ceetos/data/recovery.lua\",{})assert((recovery.until_ts or 0)>os.epoch(\"utc\"),\"recovery window is not active\")term.write(\"New password for \"..args[3]..\": \");local pass=read(\"*\")assert(#pass>=8,\"password must contain at least 8 characters\")auth.resetPassword(args[3],pass)audit.log(\"local-recovery\",\"password.reset\",{name=args[3]})print(\"Password reset. The recovery window remains active until it expires.\")else usage()end",
  ["ceetos/bin/ceetui.lua"] = "package.path=\"/?.lua;/?/init.lua;\"..package.path local gui=require(\"ceetos.lib.gui\")local auth=require(\"ceetos.lib.auth\")local net=require(\"ceetos.lib.net\")local peripherals=require(\"ceetos.lib.peripherals\")local telemetry=require(\"ceetos.lib.telemetry\")telemetry.markActivity(\"desktop\")local cloudSync=require(\"ceetos.lib.cloud_sync\")local audit=require(\"ceetos.lib.audit\")local store=require(\"ceetos.lib.store\")local files=require(\"ceetos.lib.files\")local clipboard=require(\"ceetos.lib.clipboard\")local networkIpc=require(\"ceetos.lib.network_ipc\")local terminalUi=require(\"ceetos.lib.terminal_ui\")local release=require(\"ceetos.lib.release_verify\")local launch={...}local state=gui.newState()local page=launch[1]==\"files\"and\"files\"or\"home\"if page==\"files\"and launch[2]and fs.exists(launch[2])then local target=launch[2]state.path=fs.isDir(target)and target or fs.getDir(target)state.selected=\"file:\"..target end local banner,targets,currentModel=nil,{},nil local remotePending=nil local function deps()return{auth=auth,net=net,peripherals=peripherals,telemetry=telemetry,cloud=cloudSync,audit=audit,files=files}end local function refresh(message,error)banner=message and{text=message,error=error}or nil currentModel=gui.model(page,deps(),state)targets=gui.draw(currentModel,state,banner)end local function prompt(label,secret)local _,height=term.getSize()term.setCursorPos(1,height);term.setBackgroundColor(colors.black);term.setTextColor(colors.white);term.clearLine()term.write(label..\": \")return read(secret and\"*\"or nil)end local function fill(x,y,width,height,background)return terminalUi.fill(x,y,width,height,background)end local function choose(label,options)if#options==0 then return nil end local selected=1 local function draw()gui.draw(currentModel,state,banner)local width,height=term.getSize();local boxWidth=math.max(28,math.min(width-4,42));local x=math.max(2,math.floor((width-boxWidth)/2));local y=math.max(3,math.floor((height-math.min(#options+4,height-4))/2))fill(x,y,boxWidth,math.min(#options+4,height-4),colors.black)term.setTextColor(colors.white);term.setCursorPos(x+2,y+1);term.write(label:sub(1,boxWidth-4))for index,option in ipairs(options)do if y+index+1<height then term.setBackgroundColor(index==selected and colors.gray or colors.black);term.setTextColor(colors.white);term.setCursorPos(x+2,y+index+1);term.write(tostring(option.label or option):sub(1,boxWidth-4))end end return x,y,boxWidth end local x,y,boxWidth=draw()while true do local event,first,second,third=os.pullEvent()if event==\"key\"then local key=keys.getName(first)if key==\"up\"then selected=math.max(1,selected-1);x,y,boxWidth=draw()elseif key==\"down\"then selected=math.min(#options,selected+1);x,y,boxWidth=draw()elseif key==\"enter\"then return options[selected].value or options[selected]elseif key==\"backspace\"then return nil end elseif event==\"mouse_click\"and second>=x and second<=x+boxWidth and third>=y+2 and third<=y+#options+1 then local index=third-y-1;if options[index]then return options[index].value or options[index]end elseif event==\"term_resize\"then x,y,boxWidth=draw()end end end local networkRequestCounter=0 local function networkRequest(action,payload)networkRequestCounter=networkRequestCounter+1 local request=payload or{}request.id=\"ui-\"..tostring(os.epoch(\"utc\"))..\"-\"..tostring(networkRequestCounter)request.action=action local submitted,submitErr=networkIpc.submit(request)if not submitted then return false,submitErr or\"CeetOS network service is unavailable\"end local deadline=os.epoch(\"utc\")+5000 while os.epoch(\"utc\")<deadline do local result=networkIpc.poll(request.id,true)if result and result.id==request.id then return result.ok==true,result.result or result.error end sleep(0.1)end return false,\"CeetOS network service did not respond\"end local function displayRemoteResult(result)if type(result)~=\"table\"then return tostring(result or\"\")end if result.ok==false then return tostring(result.result or result.error or\"request failed\")end local value=result.result local text=type(value)==\"table\"and textutils.serialise(value,{compact=true})or tostring(value)return terminalUi.clean(text):sub(1,240)end local function confirm(label)local function draw()gui.draw(currentModel,state,banner)local width,height=term.getSize()local boxWidth=math.min(width-4,math.max(28,#label+4))local boxHeight,x,y=6,math.floor((width-boxWidth)/2)+1,math.max(3,math.floor((height-6)/2))fill(x,y,boxWidth,boxHeight,colors.black)term.setTextColor(colors.white);term.setCursorPos(x+2,y+1);term.write(label:sub(1,boxWidth-4))local confirmX,cancelX=x+2,x+math.floor(boxWidth/2)+1 term.setBackgroundColor(colors.green);term.setTextColor(colors.black);term.setCursorPos(confirmX,y+4);term.write(\" Confirm \")term.setBackgroundColor(colors.gray);term.setTextColor(colors.white);term.setCursorPos(cancelX,y+4);term.write(\" Cancel \")term.setBackgroundColor(colors.black);term.setTextColor(colors.lightGray);term.setCursorPos(x+2,y+2);term.write(\"Click a choice or press Enter / Backspace\")term.setTextColor(colors.white)return{confirmX=confirmX,cancelX=cancelX,y=y+4}end local modal=draw()while true do local event,first,second,third=os.pullEvent()if event==\"mouse_click\"and third==modal.y then if second>=modal.confirmX and second<=modal.confirmX+8 then return true end if second>=modal.cancelX and second<=modal.cancelX+7 then return false end elseif event==\"key\"then local key=keys.getName(first)if key==\"enter\"or key==\"y\"then return true end if key==\"backspace\"or key==\"n\"then return false end elseif event==\"char\"then if first:lower()==\"y\"then return true elseif first:lower()==\"n\"then return false end elseif event==\"term_resize\"then modal=draw()end end end local function chooseRole()local roles={\"viewer\",\"operator\",\"admin\"}local function draw()local width,height=term.getSize();local boxWidth=30;local x,y=math.max(2,math.floor((width-boxWidth)/2)),math.max(3,math.floor((height-8)/2))fill(x,y,boxWidth,8,colors.black)term.setTextColor(colors.white);term.setCursorPos(x+2,y+1);term.write(\"Choose account role\")for index,roleName in ipairs(roles)do term.setBackgroundColor(index==1 and colors.gray or colors.black);term.setTextColor(colors.white);term.setCursorPos(x+2,y+index+1);term.write(\"[\"..index..\"] \"..roleName)end term.setBackgroundColor(colors.black);term.setTextColor(colors.gray);term.setCursorPos(x+2,y+6);term.write(\"Click a role or press 1-3 / Backspace\")return x,y end local x,y=draw()while true do local event,first,second,third=os.pullEvent()if event==\"char\"then local index=tonumber(first);if index and roles[index]then return roles[index]end elseif event==\"mouse_click\"and second>=x+1 and second<=x+18 and third>=y+2 and third<=y+4 then return roles[third-y-1]elseif event==\"key\"and keys.getName(first)==\"backspace\"then return nil elseif event==\"term_resize\"then x,y=draw()end end end local function values(text)local out={}for item in(text or\"\"):gmatch(\"[^,]+\")do out[#out+1]=tonumber(item)or item end return out end local function openMenu(item)local items=gui.context(item)if#items==0 then return refresh(\"No actions available for \"..tostring(item and item.label or\"item\"),true)end state.menu={items=items,selected=1}refresh()end local function cacheFor(peer)local cachePath=\"/ceetos/data/remote/\"..tostring(peer)..\".lua\"store.invalidate(cachePath)return store.read(cachePath,{}),cachePath end local function beginRemoteRequest(kind,peer,body,continueCall)networkRequestCounter=networkRequestCounter+1 local requested=os.epoch(\"utc\")local request={id=\"ui-remote-\"..tostring(requested)..\"-\"..tostring(networkRequestCounter),action=\"remote_request\",target=peer,type=kind==\"list\"and\"peripheral_list\"or\"peripheral_call\",body=body,}local sent,err=networkIpc.submit(request)if not sent then state.remoteResult={status=\"error\",error=true,peer=tostring(peer),text=err or\"CeetOS network service is unavailable\"}return false end local cache,cachePath=cacheFor(peer)remotePending={kind=kind,peer=peer,body=body,continueCall=continueCall==true,id=request.id,requested=requested,cachePath=cachePath,phase=\"dispatch\",deadline=requested+5000,cache=cache}state.remoteResult={status=\"pending\",pending=true,peer=tostring(peer),device=body and body.name,method=body and body.method,text=kind==\"list\"and\"Requesting peripheral list...\"or\"Calling remote peripheral...\"}return true end local function chooseRemoteCall(peer,cache)local choices={}for _,item in ipairs(cache.peripherals or{})do choices[#choices+1]={label=tostring(item.name)..\" (\"..tostring(item.type or\"unknown\")..\")\",value=item}end local device=choose(\"Choose peripheral\",choices);if not device then return false end local methods={};for _,method in ipairs(device.methods or{})do methods[#methods+1]={label=method,value=method}end local method=choose(\"Choose function\",methods);if not method then return false end return beginRemoteRequest(\"call\",peer.id or peer,{name=device.name,method=method,args=values(prompt(\"Arguments (comma separated)\"))})end local function pollRemoteRequest()if not remotePending then return false end local pending,now=remotePending,os.epoch(\"utc\")if now>=pending.deadline then state.remoteResult={status=\"error\",error=true,peer=tostring(pending.peer),device=pending.body and pending.body.name,method=pending.body and pending.body.method,text=pending.kind==\"list\"and\"No peripheral-list reply received\"or\"No peripheral-call reply received\"}remotePending=nil return true end if pending.phase==\"dispatch\"then local result=networkIpc.poll(pending.id,true)if result then if result.ok~=true then state.remoteResult={status=\"error\",error=true,peer=tostring(pending.peer),text=tostring(result.error or\"Remote request was rejected\")}remotePending=nil return true end pending.phase=\"reply\"return true end return false end store.invalidate(pending.cachePath)local cache=store.read(pending.cachePath,{})if cache.updated and cache.updated>=pending.requested and(pending.kind~=\"list\"or type(cache.peripherals)==\"table\")and(pending.kind~=\"call\"or cache.last_result~=nil)then remotePending=nil if pending.kind==\"list\"and pending.continueCall then state.remoteResult={status=\"ready\",peer=tostring(pending.peer),text=\"Peripheral list received. Choose a device.\"}chooseRemoteCall({id=pending.peer},cache)elseif pending.kind==\"list\"then state.remoteResult={status=\"ready\",peer=tostring(pending.peer),text=tostring(#(cache.peripherals or{}))..\" shared peripherals available\"}else local result=cache.last_result state.remoteResult={status=result and result.ok==false and\"error\"or\"complete\",error=result and result.ok==false or false,peer=tostring(pending.peer),device=pending.body and pending.body.name,method=pending.body and pending.body.method,text=displayRemoteResult(result)}end return true end return false end local function run(action)state.menu=nil if action:sub(1,5)==\"page:\"then page=action:sub(6);state.selected=nil;return refresh()end if action==\"terminal\"then term.setBackgroundColor(colors.black);term.setTextColor(colors.white);term.clear();term.setCursorPos(1,1)local ok,result=pcall(shell.run,\"/ceetos/bin/ceetshell.lua\")if not ok or result==false then return refresh(\"Terminal failed to start: \"..tostring(result or\"runtime error\"),true)end return refresh()end if action==\"crafting\"then term.setBackgroundColor(colors.black);term.setTextColor(colors.white);term.clear();term.setCursorPos(1,1)local ok,result=pcall(shell.run,\"/ceetos/bin/ceetcraft.lua\")if not ok or result==false then return refresh(\"Crafting console failed to start\",true)end return refresh()end if action==\"peripheral_view\"then state.peripheralView=true;state.selected=nil;return refresh()end if action==\"trash_open\"then state.trash=true;state.selected=nil;return refresh()end if action:sub(1,3)==\"up:\"then state.path=table.remove(state.history)or action:sub(4);state.selected=nil;return refresh()end if action:sub(1,4)==\"dir:\"then state.history[#state.history+1]=state.path;state.path=action:sub(5);state.selected=nil;return refresh()end if action:sub(1,4)==\"run:\"then if not auth.allowed(\"viewer\")then return refresh(\"Login required to run programs\",true)end local path=action:sub(5)if not files.runnable(path)then return refresh(\"This file is not a runnable Lua program\",true)end term.setBackgroundColor(colors.black);term.setTextColor(colors.white);term.clear();term.setCursorPos(1,1)shell.run(\"/ceetos/bin/ceetlaunch.lua\",path)return refresh()end if action:sub(1,5)==\"edit:\"then local path=action:sub(6)term.setBackgroundColor(colors.black);term.setTextColor(colors.white);term.clear();term.setCursorPos(1,1)shell.run(\"/ceetos/bin/ceetedit.lua\",path)return refresh()end local ok,result=pcall(function()if action:sub(1,11)==\"copy_label:\"then local id=action:sub(12);local item=currentModel and gui.selected(currentModel,state)if item and item.id==id then clipboard.set(item.label or\"\");return\"Copied\"end return\"Nothing selected\"elseif action:sub(1,11)==\"copy_text:\"then clipboard.set(action:sub(12));return\"Copied\"elseif action==\"remote_result_copy\"then local result=state.remoteResult if not result or not result.text then return\"No remote result to copy\"end clipboard.set(result.text);return true elseif action==\"remote_result_clear\"then state.remoteResult=nil;return true elseif action:sub(1,7)==\"rename:\"then auth.require(\"operator\")local path,name=action:sub(8),prompt(\"New name\")if not confirm(\"Rename \"..fs.getName(path)..\" to \"..name)then return\"Cancelled\"end local target=files.rename(path,name);state.selected=\"file:\"..target;return target elseif action:sub(1,6)==\"trash:\"then auth.require(\"operator\")local path=action:sub(7)if not confirm(\"Move \"..fs.getName(path)..\" to Trash\")then return\"Cancelled\"end local id=files.moveToTrash(path);state.selected=nil;return\"Moved to Trash\"elseif action:sub(1,8)==\"restore:\"then auth.require(\"operator\")local path=files.restore(action:sub(9));return\"Restored \"..fs.getName(path)elseif action:sub(1,13)==\"delete_trash:\"then auth.require(\"operator\")if not confirm(\"Delete this Trash item permanently\")then return\"Cancelled\"end files.deleteTrash(action:sub(14));return true elseif action==\"new_folder\"then auth.require(\"operator\")local name=prompt(\"Folder name\")if not confirm(\"Create folder \"..name)then return\"Cancelled\"end return files.makeDirectory(state.path,name)elseif action==\"empty_trash\"then auth.require(\"operator\")if not confirm(\"Permanently delete all Trash items\")then return\"Cancelled\"end files.emptyTrash();return true elseif action==\"start_discovery\"then local phrase=prompt(\"Choose discovery phrase\")local mode=prompt(\"Mode (peer/master)\")local master=mode==\"master\"and prompt(\"Master side (initiator/joiner)\")or\"initiator\"if not confirm(\"Start \"..(mode==\"master\"and\"master/slave\"or\"peer\")..\" discovery with this phrase\")then return\"Cancelled\"end local ok,err=networkRequest(\"discovery_start\",{phrase=phrase,mode=mode,master=master});if ok then return\"Discovery active (waiting for join)\"end;return err elseif action==\"join_discovery\"then local phrase=prompt(\"Discovery phrase\",true);local ok,result=networkRequest(\"discovery_join\",{phrase=phrase})if not ok then return result end if type(result)==\"table\"and result.state==\"candidate\"then local candidate=result.candidate or{}local peerLabel=tostring(candidate.label or(\"Computer \"..tostring(candidate.id or\"?\")))local relationship=candidate.mode==\"master\"and\"master/slave\"or\"equal-peer\"if not confirm(\"Pair directly with \"..peerLabel..\" (\"..relationship..\")\")then return\"Pairing confirmation cancelled\"end local confirmed,confirmErr=networkRequest(\"discovery_confirm\",{})return confirmed and\"Pairing confirmation sent\"or confirmErr end return\"Searching for a matching discovery session\"elseif action==\"confirm_discovery\"then if not confirm(\"Confirm the selected direct pairing\")then return\"Cancelled\"end local ok,err=networkRequest(\"discovery_confirm\",{})return ok and\"Pairing confirmation sent\"or err elseif action==\"cancel_discovery\"then networkRequest(\"discovery_cancel\",{});return\"Discovery cancelled\"elseif action==\"discover\"then return net.discover()elseif action==\"pair_offer\"then local id,code=prompt(\"Peer ID\"),prompt(\"Pair code\",true);if not confirm(\"Send pairing offer\")then return\"Cancelled\"end;return net.offer(id,code)elseif action==\"pair_accept\"then local id,code=prompt(\"Peer ID\"),prompt(\"Pair code\",true);local peerRole=prompt(\"Role (viewer/operator/admin)\");local master=confirm(\"Is this peer the master\")if not confirm(\"Accept pairing\")then return\"Cancelled\"end;return net.accept(id,code,peerRole==\"\"and\"operator\"or peerRole,master)elseif action==\"remote_refresh\"then local live=store.read(\"/ceetos/data/network-status.lua\",{});local choices={}for _,peer in ipairs(live.peers or net.peers())do choices[#choices+1]={label=(peer.label or(\"Computer \"..peer.id))..\" (\"..peer.id..\")\",value=peer.id}end local peer=choose(\"Refresh peripherals from\",choices);if not peer then return false end return beginRemoteRequest(\"list\",peer)elseif action:sub(1,15)==\"peripheral_set:\"then local name,mode=action:match(\"^peripheral_set:(.-):(.+)$\")if mode~=\"peer\"and mode~=\"master\"then return\"Invalid sharing mode\"end local current for _,item in ipairs(peripherals.describe())do if item.name==name then current=item.mode end end if current==mode then peripherals.unshare(name);return\"Unshared \"..name end peripherals.share(name,mode);return\"Shared \"..name..(mode==\"master\"and\" (master only)\"or\" (peers)\")elseif action:sub(1,19)==\"peripheral_unshare:\"then local name=action:sub(20)peripherals.unshare(name);return\"Unshared \"..name elseif action==\"share_all:peer\"or action==\"share_all:master\"then local mode=action:sub(11)if not confirm(\"Share every detected peripheral\"..(mode==\"master\"and\" with master only\"or\" with peers\"))then return\"Cancelled\"end return\"Shared \"..peripherals.shareAll(mode)..\" peripherals\"elseif action==\"unshare_all\"then if not confirm(\"Stop sharing every peripheral\")then return\"Cancelled\"end return\"Unshared \"..peripherals.unshareAll()..\" peripherals\"elseif action==\"remote_cache\"then local live,choices=store.read(\"/ceetos/data/network-status.lua\",{}),{}for _,peer in ipairs(live.peers or net.peers())do choices[#choices+1]={label=(peer.label or(\"Computer \"..peer.id))..\" (\"..peer.id..\")\",value=peer.id}end local peer=choose(\"View cached peripherals from\",choices);if not peer then return false end local cache=cacheFor(peer)state.remoteResult={status=\"ready\",peer=tostring(peer),text=tostring(#(cache.peripherals or{}))..\" cached peripherals\"}return true elseif action==\"remote_call\"then local live,peers=store.read(\"/ceetos/data/network-status.lua\",{}),{}for _,peer in ipairs(live.peers or net.peers())do peers[#peers+1]={label=(peer.label or(\"Computer \"..peer.id))..\" (\"..peer.id..\")\",value=peer}end local peer=choose(\"Choose peer\",peers);if not peer then return false end local cache=cacheFor(peer.id)if not cache.peripherals or#cache.peripherals==0 then return beginRemoteRequest(\"list\",peer.id,nil,true)end return chooseRemoteCall(peer,cache)elseif action==\"update_check\"then auth.require(\"operator\")local checked,err=networkRequest(\"update_check\",{})if not checked then return err end if type(err)==\"table\"then if err.cloudError then return\"Cloud check failed: \"..tostring(err.cloudError)end return\"Found \"..tostring(err.cloud or 0)..\" cloud offer(s); mesh check sent to \"..tostring(err.routed or 0)..\" peer(s)\"end return\"Signed release check started\"elseif action:sub(1,16)==\"update_download:\"then auth.require(\"operator\")local source=action:sub(17)local started,err=networkRequest(\"update_download\",{source=source})return started and\"Verified download started\"or err elseif action==\"update_cancel\"then auth.require(\"operator\")local cancelled,err=networkRequest(\"update_cancel\",{})return cancelled and\"Update download cancelled\"or err elseif action==\"update_clear\"then auth.require(\"operator\")if not confirm(\"Clear the verified release cache\")then return\"Cancelled\"end local cleared,err=networkRequest(\"update_clear_cache\",{})return cleared and\"Release cache cleared\"or err elseif action==\"update_apply\"then auth.require(\"operator\")local statusOk,update=networkRequest(\"update_status\",{})if not statusOk or not update.cache then return(statusOk and\"No verified release is cached\"or update)end local label=\"Apply CeetOS \"..tostring(update.cache.version)..\" (\"..tostring(update.cache.fingerprint)..\", key \"..tostring(update.cache.keyId)..\")\"if not confirm(label)then return\"Cancelled\"end local prepared,err=networkRequest(\"update_apply\",{})if not prepared then return err end term.setBackgroundColor(colors.black);term.setTextColor(colors.white);term.clear();term.setCursorPos(1,1)print(\"Verified release approved. Rebooting locally...\")sleep(0.3);os.reboot()elseif action==\"telemetry_toggle\"then if not confirm(\"Change telemetry state\")then return\"Cancelled\"end;telemetry.setEnabled(not telemetry.status());audit.log(auth.current.name,\"telemetry\",{enabled=telemetry.status()});return true elseif action==\"cloud_enroll\"then auth.require(\"admin\")local code=prompt(\"One-time Cloud enrollment code\",true)if not confirm(\"Enroll this computer with auth.ceet.uk\")then return\"Cancelled\"end local enrolled,enrollErr=cloudSync.enroll(code)if not enrolled then return enrollErr end audit.log(auth.current.name,\"cloud.enroll\",{node=enrolled.node})return\"Cloud enrollment saved; syncing in the background\"elseif action==\"cloud_retry\"then auth.require(\"operator\")local synced,syncErr=cloudSync.tick(\"manual\")return synced and\"Cloud sync requested\"or syncErr elseif action==\"cloud_clear\"then auth.require(\"admin\")if not confirm(\"Remove this computer's Cloud enrollment\")then return\"Cancelled\"end local cleared,clearErr=cloudSync.clear()if cleared then audit.log(auth.current.name,\"cloud.clear\",{})end return cleared and\"Cloud enrollment removed\"or clearErr elseif action==\"login\"then return auth.login(prompt(\"User\"),prompt(\"Password\",true))elseif action==\"logout\"then if not confirm(\"Logout\")then return\"Cancelled\"end;auth.logout();return true elseif action==\"user_add\"then local name,userRole,password=prompt(\"User name\"),chooseRole(),prompt(\"Password\",true)if not userRole then return\"Cancelled\"end if not confirm(\"Create user \"..name)then return\"Cancelled\"end;auth.add(name,userRole,password);audit.log(auth.current.name,\"user.add\",{name=name,role=userRole});return true elseif action:sub(1,10)==\"user_role:\"then local name,userRole=action:match(\"^user_role:(.-):(.+)$\")if not confirm(\"Change \"..name..\" to \"..userRole)then return\"Cancelled\"end;auth.setRole(name,userRole);audit.log(auth.current.name,\"user.role\",{name=name,role=userRole});return true elseif action:sub(1,11)==\"user_reset:\"then local name,password=action:sub(12),prompt(\"New password for \"..action:sub(12),true)if not confirm(\"Reset password for \"..name)then return\"Cancelled\"end;auth.adminResetPassword(name,password);audit.log(auth.current.name,\"user.password\",{name=name});return true elseif action:sub(1,11)==\"user_delete:\"then local name=action:sub(12)if not confirm(\"Delete user \"..name)then return\"Cancelled\"end;auth.remove(name);audit.log(auth.current.name,\"user.delete\",{name=name});return true elseif action==\"recovery_enable\"then local minutes=tonumber(prompt(\"Recovery minutes (1-60)\"))or 10 if not confirm(\"Enable recovery window\")then return\"Cancelled\"end;store.write(\"/ceetos/data/recovery.lua\",{until_ts=os.epoch(\"utc\")+minutes*60000});audit.log(auth.current.name,\"recovery.enable\",{minutes=minutes});return true elseif action==\"recovery_reset\"then local recovery=store.read(\"/ceetos/data/recovery.lua\",{});assert((recovery.until_ts or 0)>os.epoch(\"utc\"),\"recovery window is not active\")local name,password=prompt(\"User name\"),prompt(\"New password\",true);if not confirm(\"Reset password for \"..name)then return\"Cancelled\"end;auth.resetPassword(name,password);audit.log(\"local-recovery\",\"password.reset\",{name=name});return true end end)if not ok then return refresh(tostring(result),true)end if result==false then return refresh(\"Request failed\",true)end return refresh()end local function activateSelected()local item=gui.selected(currentModel,state)if item and item.action then run(item.action)elseif item then refresh(\"This file cannot be opened\",true)end end local function nextEvent()while true do local event,first,second,third=os.pullEventRaw()if event~=\"terminate\"then return event,first,second,third end if auth.allowed(\"operator\")then if fs.exists(\"/ceetos/data\")then local marker=fs.open(\"/ceetos/data/desktop-stop\",\"w\")if marker then marker.write(\"terminate\");marker.close()end end return false end refresh(\"Viewer mode: Ctrl+T is disabled\",true)end end refresh()local uiTimer=os.startTimer(0.2)while true do local event,first,second,third=nextEvent()if event==false then return false end if event==\"timer\"and first==uiTimer then uiTimer=os.startTimer(0.2)if pollRemoteRequest()or page==\"updates\"then refresh()end elseif event==\"key\"then local name=keys.getName(first)if state.menu then if name==\"up\"then state.menu.selected=math.max(1,state.menu.selected-1);refresh()elseif name==\"down\"then state.menu.selected=math.min(#state.menu.items,state.menu.selected+1);refresh()elseif name==\"enter\"then run(state.menu.items[state.menu.selected].action)elseif name==\"backspace\"or name==\"m\"then state.menu=nil;refresh()end elseif name==\"q\"then if page==\"home\"then refresh(\"CeetOS Desktop stays active. Open Terminal for commands.\")else page=\"home\";state.selected=nil;refresh()end elseif name==\"r\"then refresh()elseif name==\"up\"or name==\"down\"or name==\"left\"or name==\"right\"then gui.move(currentModel,state,name);refresh()elseif name==\"enter\"then activateSelected()elseif name==\"m\"then openMenu(gui.selected(currentModel,state))elseif name==\"n\"and page==\"files\"and not state.trash then run(\"new_folder\")elseif name==\"t\"and page==\"files\"and not state.trash then run(\"trash_open\")elseif name==\"e\"and page==\"files\"and state.trash then run(\"empty_trash\")elseif name==\"backspace\"then if page==\"peripherals\"and state.peripheralView then state.peripheralView=false;state.selected=nil;refresh()elseif page==\"files\"and state.trash then state.trash=false;state.selected=nil;refresh()elseif page==\"files\"and state.path~=\"/\"then state.path=table.remove(state.history)or\"/\";state.selected=nil;refresh()else page=\"home\";state.selected=nil;refresh()end end elseif event==\"mouse_click\"then local target=terminalUi.hit(targets,second,third)if target then if target.kind==\"menu\"then run(target.item.action)elseif target.item.toggle then gui.select(currentModel,state,target.item);run(target.item.action)elseif first==2 then gui.select(currentModel,state,target.item);openMenu(target.item)elseif state.selected==target.item.id then if target.item.kind==\"account\"then openMenu(target.item)else activateSelected()end else gui.select(currentModel,state,target.item);refresh()end end elseif event==\"file_transfer\"then local ok,result=pcall(function()local transfers=first.getFiles();local imported,updated={},0 for _,transfer in ipairs(transfers)do local name=transfer.getName and transfer.getName()or\"\"local devBuild=name:match(\"^ceetos%-devbuild[%w%._%-]*%.lua$\")or name==\"ceetos-pastebin.lua\"local releaseBuild=name:match(\"^ceetos%-release[%w%._%-]*%.lua$\")or name==\"ceetos-release.lua\"if devBuild or releaseBuild then auth.require(\"operator\")local chunks={};while true do local chunk=transfer.read(8192);if not chunk then break end;chunks[#chunks+1]=chunk end local source=table.concat(chunks)if releaseBuild then local metadata,cacheErr=release.cache(source,\"file transfer\")assert(metadata,cacheErr or\"not a signed CeetOS release\")if confirm(\"Verified CeetOS \"..tostring(metadata.version)..\" received. Apply locally now\")then local prepared,applyErr=networkRequest(\"update_apply\",{})assert(prepared,applyErr or\"could not prepare update\")term.setBackgroundColor(colors.black);term.setTextColor(colors.white);term.clear();term.setCursorPos(1,1)print(\"Verified release approved. Rebooting locally...\")sleep(0.3);os.reboot()end updated=updated+1 else assert(source:find(\"CeetOS installer\",1,true)and source:find(\"local files\",1,true),\"not a CeetOS installer\")local installer=assert(load(source,name,\"t\"));installer();updated=updated+1 end else local importedFiles=files.import({transfer},\"/programs/imports\")for _,path in ipairs(importedFiles)do imported[#imported+1]=path end end end return{imported=imported,updated=updated}end)if ok then refresh()else refresh(tostring(result),true)end elseif event==\"term_resize\"then refresh()end end term.setBackgroundColor(colors.black);term.setTextColor(colors.white);term.clear();term.setCursorPos(1,1)",
  ["ceetos/bin/ceetshell.lua"] = "package.path=\"/?.lua;/?/init.lua;\"..package.path local history=require(\"ceetos.lib.terminal\")local clipboard=require(\"ceetos.lib.clipboard\")local inputState=require(\"ceetos.lib.input\")local terminalUi=require(\"ceetos.lib.terminal_ui\")local auth=require(\"ceetos.lib.auth\")local telemetry=require(\"ceetos.lib.telemetry\")telemetry.markActivity(\"terminal\")auth.require(\"operator\")local net=require(\"ceetos.lib.net\")local store=require(\"ceetos.lib.store\")local launch={...}local remoteId,remoteLabel,remoteSession if launch[1]==\"--remote\"and launch[2]then remoteId=tostring(launch[2]);remoteLabel=\"peer-\"..remoteId for _,peer in ipairs(net.peers())do if tostring(peer.id)==remoteId and peer.label and peer.label~=\"\"then remoteLabel=peer.label end end for _,peer in ipairs(net.seenPeers())do if tostring(peer.id)==remoteId and peer.label and peer.label~=\"\"then remoteLabel=peer.label end end remoteSession=tostring(os.epoch(\"utc\"))..\"-\"..tostring(math.random(1000,9999))end local function localLabel()return(os.getComputerLabel and os.getComputerLabel())or(\"computer-\"..tostring(os.getComputerID()))end local promptIdentity=(auth.current and auth.current.name or\"guest\")..\"@\"..(remoteLabel or localLabel())local function parse(line)local out,token,quote,escaped={},\"\",nil,false for index=1,#line do local char=line:sub(index,index)if escaped then token,escaped=token..char,false elseif char==\"\\\\\"then escaped=true elseif quote then if char==quote then quote=nil else token=token..char end elseif char=='\"'or char==\"'\"then quote=char elseif char:match(\"%s\")then if token~=\"\"then out[#out+1],token=token,\"\"end else token=token..char end end if token~=\"\"then out[#out+1]=token end return out end local function candidates(word)local result,seen={},{}local function add(value)if value and not seen[value]then result[#result+1],seen[value]=value,true end end if word:find(\"/\")then local directory,prefix=fs.getDir(word),fs.getName(word)directory=directory==\"\"and\"/\"or directory if fs.exists(directory)and fs.isDir(directory)then for _,name in ipairs(fs.list(directory))do if name:sub(1,#prefix)==prefix then add(fs.combine(directory,name))end end end else for directory in shell.path():gmatch(\"[^:]+\")do if fs.exists(directory)and fs.isDir(directory)then for _,name in ipairs(fs.list(directory))do add(name:gsub(\"%.lua$\",\"\"))end end end end return result end local function readCommand()local input,cursor,entries,index,draft,anchor,viewOffset=\"\",0,history.history(),nil,\"\",nil,0 local held=inputState.modifiers()local selection=require(\"ceetos.lib.selection\")local promptX,promptY=1,select(2,term.getCursorPos())local function draw()local width,height=term.getSize()local prompt=promptIdentity..\":~$ \"local available=math.max(1,width-#prompt)if cursor<viewOffset then viewOffset=cursor elseif cursor>viewOffset+available then viewOffset=cursor-available end viewOffset=math.max(0,math.min(math.max(0,#input-available),viewOffset))terminalUi.clearLine(promptY,colors.black);terminalUi.write(promptX,promptY,prompt,colors.lime,colors.black,width)local visible=input:sub(viewOffset+1,viewOffset+available)local lo,hi=anchor and math.min(anchor,cursor)or nil,anchor and math.max(anchor,cursor)or nil if lo and hi and lo~=hi then local from,to=math.max(lo,viewOffset),math.min(hi,viewOffset+#visible)if from<to then terminalUi.write(#prompt+1,promptY,input:sub(viewOffset+1,from),colors.white,colors.black,available)terminalUi.write(#prompt+1+from-viewOffset,promptY,input:sub(from+1,to),colors.black,colors.white,available-(from-viewOffset))terminalUi.write(#prompt+1+to-viewOffset,promptY,input:sub(to+1,viewOffset+#visible),colors.white,colors.black,available-(to-viewOffset))else terminalUi.write(#prompt+1,promptY,visible,colors.white,colors.black,available)end term.setBackgroundColor(colors.black)else terminalUi.write(#prompt+1,promptY,visible,colors.white,colors.black,available)end term.setCursorPos(math.min(width,#prompt+cursor-viewOffset+1),promptY);if term.setCursorBlink then term.setCursorBlink(true)end terminalUi.clearLine(height,colors.black);terminalUi.write(1,height,\"Cursor \"..tostring(cursor+1)..\"/\"..tostring(#input+1)..\"  |  Enter run  |  Tab complete  |  exit returns\",colors.gray,colors.black,width)term.setTextColor(colors.white);term.setCursorPos(math.min(width,#prompt+cursor-viewOffset+1),promptY)end draw()while true do local event,first,second,third=os.pullEvent()if event==\"char\"then if held.ctrl and held.shift and(first==\"c\"or first==\"C\")and anchor then local s=require(\"ceetos.lib.selection\").new({input});require(\"ceetos.lib.selection\").start(s,1,anchor);require(\"ceetos.lib.selection\").update(s,1,cursor);require(\"ceetos.lib.selection\").copy(s,clipboard)elseif held.ctrl and held.shift and(first==\"v\"or first==\"V\")then local text=clipboard.get();input=input:sub(1,cursor)..text..input:sub(cursor+1);cursor=cursor+#text;anchor=nil else if anchor and anchor~=cursor then input=input:sub(1,math.min(anchor,cursor))..input:sub(math.max(anchor,cursor)+1);cursor=math.min(anchor,cursor);anchor=nil end;input=input:sub(1,cursor)..first..input:sub(cursor+1);cursor=cursor+#first end;draw()elseif event==\"paste\"then if anchor and anchor~=cursor then input=input:sub(1,math.min(anchor,cursor))..input:sub(math.max(anchor,cursor)+1);cursor=math.min(anchor,cursor);anchor=nil end;input=input:sub(1,cursor)..first..input:sub(cursor+1);cursor=cursor+#first;draw()elseif event==\"key_down\"then inputState.key(held,keys.getName(first)or first)elseif event==\"key_up\"then inputState.keyUp(held,keys.getName(first)or first)elseif event==\"key\"then local key=tostring(keys.getName(first)or first or\"\"):lower()local copyShortcut=held.ctrl and held.shift and key==\"c\"local pasteShortcut=held.ctrl and held.shift and key==\"v\"if key==\"leftctrl\"or key==\"rightctrl\"or key==\"ctrl\"or key==\"leftshift\"or key==\"rightshift\"or key==\"shift\"then inputState.key(held,key);draw()elseif copyShortcut then held.ctrl,held.shift=false,false if anchor and anchor~=cursor then local s=selection.new({input});selection.start(s,1,anchor);selection.update(s,1,cursor);selection.copy(s,clipboard)end;draw()elseif pasteShortcut then held.ctrl,held.shift=false,false local text=clipboard.get();if anchor and anchor~=cursor then input=input:sub(1,math.min(anchor,cursor))..input:sub(math.max(anchor,cursor)+1);cursor=math.min(anchor,cursor);anchor=nil end;input=input:sub(1,cursor)..text..input:sub(cursor+1);cursor=cursor+#text;draw()elseif key==\"enter\"then term.setCursorPos(1,promptY+1);return input elseif key==\"backspace\"then if anchor and anchor~=cursor then input=input:sub(1,math.min(anchor,cursor))..input:sub(math.max(anchor,cursor)+1);cursor=math.min(anchor,cursor);anchor=nil elseif cursor>0 then input=input:sub(1,cursor-1)..input:sub(cursor+1);cursor=cursor-1 end;draw()elseif key==\"delete\"and cursor<#input then if anchor and anchor~=cursor then input=input:sub(1,math.min(anchor,cursor))..input:sub(math.max(anchor,cursor)+1);cursor=math.min(anchor,cursor);anchor=nil else input=input:sub(1,cursor)..input:sub(cursor+2)end;draw()elseif key==\"left\"then if held.shift then anchor=anchor or cursor end;cursor=math.max(0,cursor-1);if not held.shift then anchor=nil end;draw()elseif key==\"right\"then if held.shift then anchor=anchor or cursor end;cursor=math.min(#input,cursor+1);if not held.shift then anchor=nil end;draw()elseif key==\"home\"then if held.shift then anchor=anchor or cursor end;cursor=0;if not held.shift then anchor=nil end;draw()elseif key==\"end\"then if held.shift then anchor=anchor or cursor end;cursor=#input;if not held.shift then anchor=nil end;draw()elseif key==\"up\"then if#entries>0 then if not index then draft,index=input,#entries else index=math.max(1,index-1)end;input,cursor=entries[index],#entries[index];draw()end elseif key==\"down\"and index then index=index+1;input=index>#entries and draft or entries[index];if index>#entries then index=nil end;cursor=#input;draw()elseif key==\"tab\"then local word=input:match(\"([^%s]*)$\")or\"\";local matches=history.complete(word,candidates(word))if#matches==1 then input=input:sub(1,#input-#word)..matches[1];cursor=#input;draw()end end elseif event==\"mouse_click\"and first==2 and anchor and anchor~=cursor then local s=selection.new({input});selection.start(s,1,anchor);selection.update(s,1,cursor);selection.copy(s,clipboard);draw()elseif event==\"mouse_click\"and first==1 and third==promptY then local prompt=promptIdentity..\":~$ \";anchor=math.max(0,math.min(#input,viewOffset+second-#prompt-1));cursor=anchor;draw()elseif event==\"mouse_drag\"and first==1 and third==promptY then local prompt=promptIdentity..\":~$ \";cursor=math.max(0,math.min(#input,viewOffset+second-#prompt-1));draw()end end end local function banner()local width=select(1,term.getSize())term.setBackgroundColor(colors.black);term.setTextColor(colors.cyan);term.clear();terminalUi.write(1,1,\"CeetOS Terminal  |  \"..promptIdentity..\"  |  Tab complete  |  exit returns to Desktop\",colors.cyan,colors.black,width)term.setCursorPos(1,3)term.setTextColor(colors.white)end local function waitRemote()if not remoteSession then return end local timer,deadline=os.startTimer(0.2),os.epoch(\"utc\")+2000 while os.epoch(\"utc\")<deadline do local event,value=os.pullEvent()if event==\"timer\"and value==timer then local replies,pending=store.read(\"/ceetos/data/shell-replies.lua\",{}),{}for _,reply in ipairs(replies)do if reply.from==remoteId and reply.body and reply.body.session==remoteSession then if reply.body.output and reply.body.output~=\"\"then print(reply.body.output)end if not reply.body.ok and reply.body.error then printError(reply.body.error)end else pending[#pending+1]=reply end end store.write(\"/ceetos/data/shell-replies.lua\",pending)if#pending<#replies then return end timer=os.startTimer(0.2)end end printError(\"Remote command timed out\")end local function configureDevBridge(url,token)if not url or url==\"\"then printError(\"usage: ceetdev <ws://bridge:port/dev> [token]\");return end if not fs.exists(\"/ceetos-dev\")then fs.makeDir(\"/ceetos-dev\")end local handle=assert(fs.open(\"/ceetos-dev/connection.lua\",\"w\"))handle.write(textutils.serialize({url=url,token=token or\"\",auth=(token and token~=\"\")and\"token\"or\"none\"}));handle.close()print(\"Development bridge configured; connection continues in the background.\")end banner()while true do local line=readCommand()if line==nil or line==\"exit\"then break end if line==\"clear\"then banner()else local args=parse(line)if#args>0 then history.add(line)if remoteId then local ok,err=net.request(remoteId,\"shell_request\",{command=line,session=remoteSession})if not ok then printError(err)else waitRemote()end else local ok,result if args[1]==\"ceetdev\"then configureDevBridge(args[2],args[3]);ok,result=true,true else ok,result=pcall(shell.run,args[1],table.unpack(args,2))end if not ok then printError(result)elseif result==false then printError(\"Command failed\")end end end end end",
  ["ceetos/bin/ceetlaunch.lua"] = "package.path=\"/?.lua;/?/init.lua;\"..package.path local auth=require(\"ceetos.lib.auth\")local capabilities=require(\"ceetos.lib.program_capabilities\")local audit=require(\"ceetos.lib.audit\")local telemetry=require(\"ceetos.lib.telemetry\")local args={...}local requestedPath=table.remove(args,1)assert(requestedPath and requestedPath~=\"\",\"usage: ceetlaunch <program> [args]\")if auth.refreshSession then auth.refreshSession()end local current=auth.current local actor=current and current.name or\"anonymous\"local normalized,pathErr=capabilities.normaliseProgramPath(requestedPath)if not normalized then audit.log(actor,\"program.launch_denied\",{path=tostring(requestedPath),reason=tostring(pathErr)})error(pathErr,0)end telemetry.markActivity(\"program: \"..(fs.getName(normalized)or\"program\"))local runner if auth.allowed(\"operator\")then audit.log(actor,\"program.launch\",{path=normalized,mode=\"full\",role=auth.current and auth.current.role})runner=function()return shell.run(normalized,table.unpack(args))end elseif auth.allowed(\"viewer\")then local chunk,record=capabilities.loadViewer(normalized,actor)if not chunk then audit.log(actor,\"program.launch_denied\",{path=normalized,reason=tostring(record)})error(record,0)end audit.log(actor,\"program.launch\",{path=normalized,mode=\"sandbox\",trust=record.trust,stale=record.stale==true,})runner=function()return chunk(table.unpack(args))end else audit.log(actor,\"program.launch_denied\",{path=normalized,reason=\"requires viewer\"})error(\"permission denied (requires viewer)\",0)end local child=coroutine.create(runner)local function resume(...)local ok,result=coroutine.resume(child,...)if not ok then audit.log(actor,\"program.failed\",{path=normalized,reason=\"program error\"})error(result,0)end return coroutine.status(child)==\"dead\",result end local done,result=resume()while not done do local event={os.pullEventRaw()}if event[1]==\"key\"and event[2]==keys.backspace then term.setTextColor(colors.gray)print(\"Backspace: returned to CeetOS Desktop\")return true end done,result=resume(table.unpack(event))end return result",
  ["ceetos/bin/craftos-shell.lua"] = "package.path=\"/?.lua;/?/init.lua;\"..package.path local auth=require(\"ceetos.lib.auth\")auth.require(\"operator\")shell.run(\"/rom/programs/shell.lua\")",
  ["ceetos/bin/ceetedit.lua"] = "package.path=\"/?.lua;/?/init.lua;\"..package.path local editor=require(\"ceetos.lib.editor\")local clipboard=require(\"ceetos.lib.clipboard\")local inputState=require(\"ceetos.lib.input\")local terminalUi=require(\"ceetos.lib.terminal_ui\")local auth=require(\"ceetos.lib.auth\")local files=require(\"ceetos.lib.files\")local args={...}local path=args[1]assert(path and path~=\"\",\"usage: ceetedit <file>\")auth.require(\"operator\")assert(not files.isProtected(path),\"protected files must be edited with craftos-edit\")local buffer=editor.new(fs.exists(path)and files.readText(path)or\"\")local scroll,ctrl,shift=1,false,false local held=inputState.modifiers()local tokenColours={text=colors.white,comment=colors.gray,string=colors.orange,keyword=colors.purple,number=colors.cyan,builtin=colors.lightBlue}local function fitCursor(height)local visible=math.max(1,height-3)if buffer.line<scroll then scroll=buffer.line elseif buffer.line>=scroll+visible then scroll=buffer.line-visible+1 end end local function render(message)local width,height=term.getSize();fitCursor(height)term.setBackgroundColor(colors.black);term.setTextColor(colors.white);term.clear()if width<24 or height<8 then terminalUi.minimum(\"CeetOS Editor\",\"Editor needs 24x8\",\"Resize | Ctrl+Q exit\");return end terminalUi.clearLine(1,colors.blue);terminalUi.write(2,1,\"CeetOS Editor | \"..path..(buffer.changed and\" *\"or\"\"),colors.white,colors.blue,width-2)local digits=math.max(2,#tostring(#buffer.lines));local gutter=digits+3 local lua=path:sub(-4):lower()==\".lua\"for row=2,height-1 do local lineNumber,line=scroll+row-2,buffer.lines[scroll+row-2]if line then local selected=lineNumber==buffer.line term.setBackgroundColor(selected and colors.gray or colors.black);terminalUi.write(1,row,(\"%\"..digits..\"d \"):format(lineNumber),colors.lightGray,selected and colors.gray or colors.black,gutter-1)term.setTextColor(colors.white)local x=gutter for _,token in ipairs(editor.tokens(line,lua))do if x<width then terminalUi.write(x,row,token.text,tokenColours[token.kind]or colors.white,selected and colors.gray or colors.black,width-x+1);x=x+#token.text end end end end local range=buffer.selection and require(\"ceetos.lib.selection\").range(buffer.selection)if range then for line=range.first.line,range.last.line do local row=line-scroll+2 if row>=2 and row<height then local from=line==range.first.line and range.first.column or 0 local to=line==range.last.line and range.last.column or#(buffer.lines[line]or\"\")if to>from and gutter+from<=width then terminalUi.write(gutter+from,row,(buffer.lines[line]or\"\"):sub(from+1,to),colors.black,colors.white,width-gutter-from+1)term.setBackgroundColor(colors.black)end end end end terminalUi.clearLine(height,colors.black);terminalUi.write(1,height,message or\"Ctrl+S save | F2 save as | Ctrl+F find | Ctrl+G line | F5 run | Ctrl+Q exit\",colors.gray,colors.black,width)local cursorY=buffer.line-scroll+2 if cursorY>=2 and cursorY<height then term.setCursorPos(math.min(width,gutter+buffer.column),cursorY)end term.setTextColor(colors.white)end local function prompt(label)local _,height=term.getSize();term.setBackgroundColor(colors.black);term.setTextColor(colors.white);term.setCursorPos(1,height);term.clearLine();term.write(label..\": \");return read()end local function save(target)target=target or path local ok,err=pcall(files.writeText,target,editor.text(buffer))if ok then path,buffer.changed=target,false;return true else render(tostring(err));return false end end local function leaveChoice()if not buffer.changed then return\"discard\"end local function draw()render()local width,height=term.getSize();local boxWidth=math.max(20,math.min(32,width-2));local x,y=math.max(1,math.floor((width-boxWidth)/2)+1),math.max(2,math.floor((height-5)/2))terminalUi.fill(x,y,boxWidth,5,colors.black)terminalUi.write(x+2,y+1,\"Unsaved changes\",colors.white,colors.black,boxWidth-4)local compact=boxWidth<31 local saveText,discardText,cancelText=compact and\"[S]\"or\" Save \",compact and\"[D]\"or\" Discard \",compact and\"[C]\"or\" Cancel \"local saveX,discardX,cancelX=x+2,x+2+#saveText+2,x+2+#saveText+#discardText+4 terminalUi.write(saveX,y+3,saveText,colors.black,colors.green)terminalUi.write(discardX,y+3,discardText,colors.white,colors.red)terminalUi.write(cancelX,y+3,cancelText,colors.white,colors.gray)return{y=y+3,saveX=saveX,saveWidth=#saveText,discardX=discardX,discardWidth=#discardText,cancelX=cancelX,cancelWidth=#cancelText}end local modal=draw()while true do local event,first,second,third=os.pullEvent()if event==\"mouse_click\"and third==modal.y then if second>=modal.saveX and second<modal.saveX+modal.saveWidth then return\"save\"elseif second>=modal.discardX and second<modal.discardX+modal.discardWidth then return\"discard\"elseif second>=modal.cancelX and second<modal.cancelX+modal.cancelWidth then return\"cancel\"end elseif event==\"key\"then local key=keys.getName(first);if key==\"enter\"then return\"save\"elseif key==\"d\"then return\"discard\"elseif key==\"backspace\"then return\"cancel\"end end if event==\"term_resize\"then modal=draw()end end end render()while true do local event,first,second,third=os.pullEvent()if event==\"char\"then editor.insert(buffer,first);render()elseif event==\"paste\"then editor.insert(buffer,first);render()elseif event==\"key_up\"then local released=tostring(keys.getName(first)or first or\"\"):lower()inputState.keyUp(held,released);ctrl,shift=held.ctrl,held.shift elseif event==\"key\"then local key=tostring(keys.getName(first)or first or\"\"):lower()if key==\"leftctrl\"or key==\"rightctrl\"or key==\"ctrl\"or key==\"leftshift\"or key==\"rightshift\"or key==\"shift\"then inputState.key(held,key);ctrl,shift=held.ctrl,held.shift elseif ctrl and key==\"c\"then editor.copySelection(buffer,clipboard);ctrl,shift,held.ctrl,held.shift=false,false,false,false;render(\"Copied\")elseif ctrl and key==\"v\"then editor.insert(buffer,clipboard.get());ctrl,shift,held.ctrl,held.shift=false,false,false,false;render()elseif ctrl and key==\"s\"then save();render(\"Saved\")elseif ctrl and key==\"q\"then local choice=leaveChoice();if choice==\"save\"then if save()then break end elseif choice==\"discard\"then break else render()end end elseif ctrl and key==\"f\"then local needle=prompt(\"Find\");if not editor.find(buffer,needle)then render(\"Not found\")else render()end elseif ctrl and key==\"g\"then editor.gotoLine(buffer,prompt(\"Go to line\"));render()elseif key==\"f2\"then local target=prompt(\"Save as\");if target~=\"\"then save(target);render(\"Saved\")else render()end elseif key==\"f5\"then if not auth.allowed(\"operator\")then render(\"Operator role required to run programs\")elseif save()then term.clear();term.setCursorPos(1,1);shell.run(\"/ceetos/bin/ceetlaunch.lua\",path);render(\"Returned from program\")end elseif key==\"left\"then if shift and not buffer.selection.anchor then editor.selectStart(buffer)end;editor.move(buffer,0,-1);if shift then editor.selectTo(buffer,buffer.line,buffer.column)else editor.clearSelection(buffer)end;render()elseif key==\"right\"then if shift and not buffer.selection.anchor then editor.selectStart(buffer)end;editor.move(buffer,0,1);if shift then editor.selectTo(buffer,buffer.line,buffer.column)else editor.clearSelection(buffer)end;render()elseif key==\"up\"then if shift and not buffer.selection.anchor then editor.selectStart(buffer)end;editor.move(buffer,-1,0);if shift then editor.selectTo(buffer,buffer.line,buffer.column)else editor.clearSelection(buffer)end;render()elseif key==\"down\"then if shift and not buffer.selection.anchor then editor.selectStart(buffer)end;editor.move(buffer,1,0);if shift then editor.selectTo(buffer,buffer.line,buffer.column)else editor.clearSelection(buffer)end;render()elseif key==\"home\"then if shift and not buffer.selection.anchor then editor.selectStart(buffer)end;editor.gotoLine(buffer,buffer.line,0);if shift then editor.selectTo(buffer,buffer.line,buffer.column)else editor.clearSelection(buffer)end;render()elseif key==\"end\"then if shift and not buffer.selection.anchor then editor.selectStart(buffer)end;editor.gotoLine(buffer,buffer.line,#editor.current(buffer));if shift then editor.selectTo(buffer,buffer.line,buffer.column)else editor.clearSelection(buffer)end;render()elseif key==\"pageup\"then editor.move(buffer,-10,0);render()elseif key==\"pagedown\"then editor.move(buffer,10,0);render()elseif key==\"enter\"then editor.insert(buffer,\"\\n\");render()elseif key==\"tab\"then editor.insert(buffer,\"  \");render()elseif key==\"backspace\"then if not editor.deleteSelection(buffer)then editor.backspace(buffer)end;render()elseif key==\"delete\"then if not editor.deleteSelection(buffer)then editor.delete(buffer)end;render()elseif event==\"mouse_click\"and first==2 then if buffer.selection and require(\"ceetos.lib.selection\").range(buffer.selection)then editor.copySelection(buffer,clipboard);render(\"Copied\")else editor.insert(buffer,clipboard.get());render()end elseif event==\"mouse_click\"and first==1 then local width,height=term.getSize()local digits=math.max(2,#tostring(#buffer.lines));local gutter=digits+3 local line=scroll+third-2 if third>=2 and third<height and line>=1 and line<=#buffer.lines then local column=math.max(0,math.min(#(buffer.lines[line]or\"\"),second-gutter))editor.gotoLine(buffer,line,column);editor.selectStart(buffer);render()end elseif event==\"mouse_drag\"and first==1 then local width,height=term.getSize()local digits=math.max(2,#tostring(#buffer.lines));local gutter=digits+3 local line=math.max(1,math.min(#buffer.lines,scroll+third-2))local column=math.max(0,math.min(#(buffer.lines[line]or\"\"),second-gutter))editor.selectTo(buffer,line,column);editor.gotoLine(buffer,line,column);render()elseif event==\"term_resize\"then render()end end term.setBackgroundColor(colors.black);term.setTextColor(colors.white);term.clear();term.setCursorPos(1,1)",
  ["ceetos/bin/edit.lua"] = "local args={...}if#args==0 then shell.run(\"/ceetos/bin/ceetui.lua\",\"files\")else shell.run(\"/ceetos/bin/ceetedit.lua\",args[1])end",
  ["ceetos/bin/programs.lua"] = "shell.run(\"/ceetos/bin/ceetui.lua\")",
  ["ceetos/bin/files.lua"] = "shell.run(\"/ceetos/bin/ceetui.lua\",\"files\")",
  ["ceetos/bin/list.lua"] = "shell.run(\"/ceetos/bin/ceetui.lua\",\"files\")",
  ["ceetos/bin/delete.lua"] = "shell.run(\"/ceetos/bin/ceetui.lua\",\"files\")",
  ["ceetos/lib/store.lua"] = "local M={}local cache={}local function internalPath(path)return type(path)~=\"string\"or path:sub(-4)==\".new\"or path:sub(-4)==\".bak\"end local function call(fn,...)local result={pcall(fn,...)}if not result[1]then return false,tostring(result[2])end if result[2]==false then return false,tostring(result[3]or\"operation failed\")end return true,result[2],result[3]end local function exists(path)local ok,value=call(fs.exists,path)return ok and value==true end local function remove(path)if not exists(path)then return true end local ok,err=call(fs.delete,path)return ok,err end local function ensureDirectory(path)local dir=fs.getDir(path)if dir==\"\"or exists(dir)then return true end local ok,err=call(fs.makeDir,dir)return ok,err end local function readRaw(path)local ok,handleOrErr=call(fs.open,path,\"r\")if not ok or not handleOrErr then return false,nil,tostring(handleOrErr or\"could not open file\")end local handle=handleOrErr local readOk,content=call(handle.readAll)local closeOk,closeErr=call(handle.close)if not readOk then return false,nil,content end if not closeOk then return false,nil,closeErr end return true,content end local function writeRaw(path,content)local ok,handleOrErr=call(fs.open,path,\"w\")if not ok or not handleOrErr then return false,tostring(handleOrErr or\"could not open file\")end local handle=handleOrErr local writeOk,writeErr=call(handle.write,content)local closeOk,closeErr=call(handle.close)if not writeOk then return false,writeErr end if not closeOk then return false,closeErr end return true end local function move(source,destination)local ok,err=call(fs.move,source,destination)return ok,err end local function decode(raw)local ok,value=pcall(textutils.unserialise,raw)if not ok or value==nil then return false,nil,\"invalid serialised value\"end return true,value end local function readValue(path)local ok,raw,err=readRaw(path)if not ok then return false,nil,err end return decode(raw)end local function recoverValue(path)local activeOk,activeValue=false,nil if exists(path)then activeOk,activeValue=readValue(path)end if activeOk then remove(path..\".new\")remove(path..\".bak\")return true,activeValue end local backupOk,backupValue=false,nil if exists(path..\".bak\")then backupOk,backupValue=readValue(path..\".bak\")end if backupOk then if exists(path)then remove(path)end if not exists(path)then move(path..\".bak\",path)end remove(path..\".new\")return true,backupValue end remove(path..\".new\")return false,nil end local function validLines(raw)for line in(raw..\"\\n\"):gmatch(\"(.-)\\n\")do if line~=\"\"then local ok,value=pcall(textutils.unserialise,line)if not ok or value==nil then return false,\"invalid appended value\"end end end return true end local function recoverAppend(path)if exists(path)then local activeOk,raw=readRaw(path)if activeOk then local valid=validLines(raw)if valid then remove(path..\".new\")remove(path..\".bak\")return true,raw end end end if exists(path..\".bak\")then local backupOk,raw=readRaw(path..\".bak\")if backupOk and validLines(raw)then if exists(path)then remove(path)end if not exists(path)then move(path..\".bak\",path)end remove(path..\".new\")return true,raw end end remove(path..\".new\")return false,\"no valid appended value\"end local function commitRaw(path,raw,validator)local dirOk,dirErr=ensureDirectory(path)if not dirOk then return false,dirErr end local temporary,backup=path..\".new\",path..\".bak\"local removeOk,removeErr=remove(temporary)if not removeOk then return false,removeErr end local writeOk,writeErr=writeRaw(temporary,raw)if not writeOk then remove(temporary);return false,writeErr end local checkOk,checkedRaw,checkErr=readRaw(temporary)if not checkOk then remove(temporary);return false,checkErr end local valid,validErr=validator(checkedRaw)if not valid then remove(temporary);return false,validErr or\"temporary validation failed\"end local backupRemoveOk,backupRemoveErr=remove(backup)if not backupRemoveOk then remove(temporary);return false,backupRemoveErr end if exists(path)then local backupOk,backupErr=move(path,backup)if not backupOk then remove(temporary);return false,backupErr end local activateOk,activateErr=move(temporary,path)if not activateOk then if not exists(path)then move(backup,path)end remove(temporary)return false,activateErr end else local activateOk,activateErr=move(temporary,path)if not activateOk then remove(temporary);return false,activateErr end end return true end function M.readCached(path,fallback)if internalPath(path)then return fallback end local entry=cache[path]if entry~=nil then return entry.value end return M.readFresh(path,fallback)end function M.readFresh(path,fallback)if internalPath(path)then return fallback end local ok,value=recoverValue(path)if not ok then value=fallback end cache[path]={value=value}return value end function M.read(path,fallback)return M.readCached(path,fallback)end function M.writeAtomic(path,value)if internalPath(path)then return false,\"cannot write store temporary or backup path\"end if value==nil then return false,\"cannot store nil\"end local serialisedOk,raw=pcall(textutils.serialise,value,{compact=true})if not serialisedOk or type(raw)~=\"string\"then return false,tostring(raw or\"could not serialise value\")end local valid=decode(raw)if not valid then return false,\"could not validate serialised value\"end recoverValue(path)local ok,err=commitRaw(path,raw,decode)if ok then cache[path]={value=value}end return ok,err end function M.write(path,value)return M.writeAtomic(path,value)end function M.append(path,value,limits)if internalPath(path)then return false,\"cannot append to store temporary or backup path\"end if value==nil then return false,\"cannot append nil\"end local serialisedOk,line=pcall(textutils.serialise,value,{compact=true})if not serialisedOk or type(line)~=\"string\"then return false,tostring(line or\"could not serialise value\")end local valid=validLines(line..\"\\n\")if not valid then return false,\"could not validate appended value\"end local recovered,current=recoverAppend(path)if not recovered then if exists(path)or exists(path..\".bak\")then return false,current end current=\"\"end local lines={}for existing in(current..\"\\n\"):gmatch(\"(.-)\\n\")do if existing~=\"\"then lines[#lines+1]=existing end end lines[#lines+1]=line local maxEntries=limits and tonumber(limits.maxEntries)local maxBytes=limits and tonumber(limits.maxBytes)if maxEntries then maxEntries=math.max(1,math.floor(maxEntries))end if maxBytes then maxBytes=math.max(1,math.floor(maxBytes))end while maxEntries and#lines>maxEntries do table.remove(lines,1)end local raw=table.concat(lines,\"\\n\")if#raw>0 then raw=raw..\"\\n\"end while maxBytes and#raw>maxBytes and#lines>1 do table.remove(lines,1)raw=table.concat(lines,\"\\n\")..\"\\n\"end if maxBytes and#raw>maxBytes then return false,\"appended value exceeds byte limit\"end local ok,err=commitRaw(path,raw,validLines)if ok then cache[path]=nil end return ok,err end function M.readAppend(path)if internalPath(path)then return\"\"end local ok,raw=recoverAppend(path)return ok and raw or\"\"end function M.invalidate(path)cache[path]=nil end return M",
  ["ceetos/lib/profile.lua"] = "local store=require(\"ceetos.lib.store\")local M={}M.PATH=\"/ceetos/profile.lua\"M.IDS={desktop=true,[\"recipe-server\"]=true,[\"router-server\"]=true,[\"auth-server\"]=true}local cache local function normalise(value)if type(value)~=\"table\"then value={}end local id=tostring(value.id or value.profile or\"desktop\")if not M.IDS[id]then id=\"desktop\"end return{schema=1,id=id,installedAt=tonumber(value.installedAt)or 0}end function M.current()if not cache then cache=normalise(store.read(M.PATH,{id=\"desktop\"}))end return cache end function M.id()return M.current().id end function M.is(id)return M.id()==id end function M.isServer()return M.id()~=\"desktop\"end function M.set(id)assert(M.IDS[id],\"invalid CeetOS profile\")cache={schema=1,id=id,installedAt=os.epoch(\"utc\")}return store.write(M.PATH,cache)end function M.capability(name)local id=M.id()local tableFor={desktop={desktop=true,craftingClient=true,orders=true},[\"recipe-server\"]={server=true,recipes=true,recipeImport=true,recipePlan=true},[\"router-server\"]={server=true,routing=true},[\"auth-server\"]={server=true,authAuthority=true},}return tableFor[id][name]==true end return M",
  ["ceetos/lib/auth.lua"] = "local store=require(\"ceetos.lib.store\")local password=require(\"ceetos.lib.password\")local audit=require(\"ceetos.lib.audit\")local M={current=nil}local USERS=\"/ceetos/data/users.lua\"local SESSION=\"/ceetos/data/session.lua\"local TOMBSTONES=\"/ceetos/data/user-tombstones.lua\"local THROTTLE=\"/ceetos/data/login-throttle.lua\"local RECOVERY=\"/ceetos/data/recovery.lua\"local AUTHORITY=\"/ceetos/data/auth-authority.lua\"local CENTRAL_SESSION=\"/ceetos/data/auth-session.lua\"local DIRECTORY=\"/ceetos/data/auth-directory.lua\"local rank={viewer=1,operator=2,admin=3}M.SESSION_TTL_MS=8*60*60*1000 M.LOGIN_THROTTLE={failures=5,windowMs=5*60*1000,lockMs=60*1000,maxEntries=64}local configuredWorkFactor=password.DEFAULT_WORK_FACTOR local sessionPathDelete local function now()return os.epoch(\"utc\")end local function accountName(name)return type(name)==\"string\"and name:match(\"^[%w_%-]+$\")and#name<=32 end local function users()store.invalidate(USERS);return store.read(USERS,{})end local function save(value)return store.write(USERS,value)end local function tombstones()store.invalidate(TOMBSTONES);return store.read(TOMBSTONES,{})end local function saveTombstones(value)return store.write(TOMBSTONES,value)end local function authority()store.invalidate(AUTHORITY)local value=store.read(AUTHORITY,nil)return type(value)==\"table\"and value.active==true and type(value.id)==\"string\"and value or nil end function M.authority()return authority()end function M.centralActive()return authority()~=nil end local function centralDirectory()store.invalidate(DIRECTORY)local value=store.read(DIRECTORY,{})return type(value)==\"table\"and type(value.users)==\"table\"and value or{users={}}end function M.acceptAuthority(record)assert(type(record)==\"table\"and type(record.id)==\"string\"and#record.id<=64,\"invalid auth authority\")local public={schema=1,active=true,id=record.id,term=math.max(0,math.floor(tonumber(record.term)or 0)),revision=math.max(0,math.floor(tonumber(record.revision)or 0)),seen=now()}assert(store.write(AUTHORITY,public),\"could not save auth authority\")if type(record.directory)==\"table\"then assert(store.write(DIRECTORY,{schema=1,revision=public.revision,users=record.directory}),\"could not save account directory\")end local loaded,profile=pcall(require,\"ceetos.lib.profile\")if not loaded or not profile.is(\"auth-server\")then if fs.exists(USERS)then fs.delete(USERS)end if fs.exists(TOMBSTONES)then fs.delete(TOMBSTONES)end sessionPathDelete()end return public end function M.updateDirectory(directory,revision)if type(directory)~=\"table\"then return false,\"invalid account directory\"end return store.write(DIRECTORY,{schema=1,revision=math.max(0,math.floor(tonumber(revision)or 0)),users=directory})end function M.saveCentralSession(value)if type(value)~=\"table\"or not accountName(value.name)or type(value.role)~=\"string\"then return false,\"invalid central session\"end local session={sessionVersion=3,name=value.name,role=value.role,token=value.token,issued=value.issued,expires=value.expires,accountRevision=value.accountRevision,authority=value.authority}if type(session.token)~=\"string\"or#session.token<16 then return false,\"invalid central session token\"end store.write(CENTRAL_SESSION,session)M.current=nil return true end local function safeAudit(action,detail)pcall(audit.log,\"auth\",action,detail or{})end local function stamp(account)account.updated=now()account.origin=tostring(os.getComputerID())account.revision=math.max(0,math.floor(tonumber(account.revision)or 0))+1 return account end local function makeAccount(role,plainPassword,context)local record,err=password.record(plainPassword,password.newSalt(context),configuredWorkFactor)assert(record,err)record.role=role return stamp(record)end sessionPathDelete=function()if fs.exists(SESSION)then fs.delete(SESSION)end store.invalidate(SESSION)end local function saveSession()if M.current==nil then sessionPathDelete();return end local durable={sessionVersion=2,name=M.current.name,nonce=M.current.nonce,issued=M.current.issued,expires=M.current.expires,accountRevision=M.current.accountRevision,}store.write(SESSION,durable)end local function makeSession(name,account)local issued=now()M.current={name=name,role=account.role,nonce=password.newSalt(\"session:\"..name),issued=issued,expires=issued+M.SESSION_TTL_MS,accountRevision=tonumber(account.revision)or 0,}saveSession()return M.current end local function liveAccount(name)local all=users()return all[name],all end local function normaliseSession(saved,account)if type(saved)~=\"table\"or not account or account.disabled then return nil end if saved.sessionVersion==2 then local issued,expires,revision=tonumber(saved.issued),tonumber(saved.expires),tonumber(saved.accountRevision)if type(saved.nonce)~=\"string\"or#saved.nonce<16 or not issued or not expires or not revision then return nil end if expires<=now()or revision~=(tonumber(account.revision)or 0)then return nil end return{name=saved.name,role=account.role,nonce=saved.nonce,issued=issued,expires=expires,accountRevision=revision}end if saved.sessionVersion==nil and type(saved.role)==\"string\"then return\"legacy\"end return nil end function M.refreshSession()local central=authority()if central then store.invalidate(CENTRAL_SESSION)local saved=store.read(CENTRAL_SESSION,nil)local entry=type(saved)==\"table\"and centralDirectory().users[saved.name]or nil if type(saved)~=\"table\"or saved.sessionVersion~=3 or saved.authority~=central.id or type(saved.token)~=\"string\"or(tonumber(saved.expires)or 0)<=now()or type(entry)~=\"table\"or entry.disabled==true or saved.accountRevision~=entry.revision then M.current=nil if fs.exists(CENTRAL_SESSION)then fs.delete(CENTRAL_SESSION)end return nil end M.current={name=saved.name,role=entry.role,nonce=saved.token,issued=saved.issued,expires=saved.expires,accountRevision=saved.accountRevision,authority=central.id,central=true}return M.current end store.invalidate(SESSION)local saved=store.read(SESSION,nil)if type(saved)~=\"table\"or not accountName(saved.name)then M.current=nil;return nil end local account=liveAccount(saved.name)local session=normaliseSession(saved,account)if session==\"legacy\"then return makeSession(saved.name,account)end if not session then M.current=nil sessionPathDelete()return nil end M.current=session return M.current end local function throttleState()store.invalidate(THROTTLE)local data=store.read(THROTTLE,{})return type(data)==\"table\"and data or{}end local function saveThrottle(data)local entries={}for name,entry in pairs(data)do if accountName(name)and type(entry)==\"table\"and type(entry.last)==\"number\"then entries[#entries+1]={name=name,last=entry.last}end end table.sort(entries,function(a,b)return a.last>b.last end)local kept={}for index,entry in ipairs(entries)do if index<=M.LOGIN_THROTTLE.maxEntries then kept[entry.name]=data[entry.name]end end store.write(THROTTLE,kept)end local function locked(name)if not accountName(name)then return false end local entry=throttleState()[name]return entry and(tonumber(entry.lockedUntil)or 0)>now()or false end local function noteFailure(name,reason)if not accountName(name)then return end local data,entry,time=throttleState(),nil,now()entry=data[name]or{failures=0,first=time}if time-(tonumber(entry.first)or 0)>M.LOGIN_THROTTLE.windowMs then entry.failures,entry.first=0,time end entry.failures=math.max(0,math.floor(tonumber(entry.failures)or 0))+1 entry.last=time if entry.failures>=M.LOGIN_THROTTLE.failures then entry.lockedUntil=time+M.LOGIN_THROTTLE.lockMs end data[name]=entry saveThrottle(data)safeAudit(\"login.failure\",{account=name,reason=reason or\"invalid\",throttled=(entry.lockedUntil or 0)>time})end local function clearFailures(name)local data=throttleState()if data[name]~=nil then data[name]=nil;saveThrottle(data)end end function M.throttleStatus(name)local entry=accountName(name)and throttleState()[name]or nil if not entry then return{failures=0,lockedUntil=0}end return{failures=tonumber(entry.failures)or 0,lockedUntil=tonumber(entry.lockedUntil)or 0}end function M.setPasswordWorkFactor(value)local work,err=password.normaliseWorkFactor(value)assert(work,err)configuredWorkFactor=work return work end function M.passwordWorkFactor()return configuredWorkFactor end function M.bootstrap(initialPassword)if authority()then return false end local all=users()if next(all)then return false end local plainPassword=initialPassword if plainPassword==nil then term.write(\"Create CeetOS admin password: \");plainPassword=read(\"*\")end local account=makeAccount(\"admin\",plainPassword,\"admin\")all.admin=account assert(save(all),\"could not save administrator account\")makeSession(\"admin\",account)safeAudit(\"bootstrap\",{account=\"admin\"})return true end function M.login(name,plainPassword)if authority()then local client=require((\"ceetos.lib.auth_client\"))return client.login(name,plainPassword)end if not accountName(name)or type(plainPassword)~=\"string\"then noteFailure(name,\"invalid\")return false,\"invalid credentials\"end if locked(name)then safeAudit(\"login.failure\",{account=name,reason=\"throttled\",throttled=true})return false,\"too many failed attempts; try again later\"end local account,all=liveAccount(name)if not account or account.disabled then noteFailure(name,\"invalid\")return false,\"invalid credentials\"end local valid,state=password.verify(account,plainPassword)if not valid then noteFailure(name,\"invalid\")return false,\"invalid credentials\"end if state==\"legacy\"then local upgraded=makeAccount(account.role,plainPassword,\"upgrade:\"..name)upgraded.updated=account.updated or upgraded.updated upgraded.origin=account.origin or upgraded.origin upgraded.revision=math.max(tonumber(account.revision)or 0,upgraded.revision)stamp(upgraded)all[name]=upgraded assert(save(all),\"could not upgrade password record\")account=upgraded safeAudit(\"password.upgraded\",{account=name})end clearFailures(name)makeSession(name,account)safeAudit(\"login.success\",{account=name})return true end function M.logout()M.current=nil sessionPathDelete()if fs.exists(CENTRAL_SESSION)then fs.delete(CENTRAL_SESSION)end end function M.add(name,role,plainPassword)if authority()then assert(rank[role]and accountName(name),\"invalid user or role\")local record,err=makeAccount(role,plainPassword,\"central:\"..name)assert(record,err)return require((\"ceetos.lib.auth_client\")).mutate(\"add\",{name=name,role=role,record=record})end M.require(\"operator\")assert(rank[role],\"invalid role\")if role==\"admin\"then M.require(\"admin\")end assert(accountName(name),\"invalid user name\")local all=users()assert(not all[name],\"user exists\")all[name]=makeAccount(role,plainPassword,name)assert(save(all),\"could not save user\")safeAudit(\"user.add\",{account=name,role=role})end local function adminCount(all)local count=0 for _,account in pairs(all)do if account.role==\"admin\"and not account.disabled then count=count+1 end end return count end function M.setRole(name,role)if authority()then return require((\"ceetos.lib.auth_client\")).mutate(\"role\",{name=name,role=role})end M.require(\"operator\")assert(accountName(name)and rank[role],\"invalid user or role\")local all,account=users(),users()[name]assert(account,\"unknown user\")if role==\"admin\"or account.role==\"admin\"then M.require(\"admin\")end assert(not(M.current and M.current.name==name),\"cannot change the active account role\")assert(not(account.role==\"admin\"and role~=\"admin\"and adminCount(all)<=1),\"cannot remove the last administrator\")account.role=role stamp(account)all[name]=account assert(save(all),\"could not save account role\")safeAudit(\"user.role\",{account=name,role=role})end function M.setDisabled(name,disabled)if authority()then return require((\"ceetos.lib.auth_client\")).mutate(\"disable\",{name=name,disabled=disabled==true})end M.require(\"admin\")assert(accountName(name),\"invalid user name\")local all,account=users(),users()[name]assert(account,\"unknown user\")assert(not(M.current and M.current.name==name),\"cannot disable the active account\")if disabled then assert(not(account.role==\"admin\"and adminCount(all)<=1),\"cannot disable the last administrator\")end account.disabled=disabled==true stamp(account)all[name]=account assert(save(all),\"could not save account state\")safeAudit(\"user.disabled\",{account=name,disabled=account.disabled})end function M.remove(name)if authority()then return require((\"ceetos.lib.auth_client\")).mutate(\"remove\",{name=name})end M.require(\"operator\")assert(accountName(name),\"invalid user name\")local all,account=users(),users()[name]assert(account,\"unknown user\")if account.role==\"admin\"then M.require(\"admin\")end assert(not(M.current and M.current.name==name),\"cannot delete the active account\")assert(not(account.role==\"admin\"and adminCount(all)<=1),\"cannot delete the last administrator\")all[name]=nil local removed=tombstones()removed[name]=now()assert(saveTombstones(removed),\"could not save account tombstone\")assert(save(all),\"could not remove account\")safeAudit(\"user.remove\",{account=name})end local function recoveryActive()store.invalidate(RECOVERY)local recovery=store.read(RECOVERY,{})return type(recovery)==\"table\"and(tonumber(recovery.until_ts)or 0)>now()end local function setPassword(name,plainPassword)assert(accountName(name),\"invalid user name\")local all,account=users(),users()[name]assert(account,\"unknown user\")local replacement=makeAccount(account.role,plainPassword,\"reset:\"..name)replacement.updated=account.updated or replacement.updated replacement.origin=account.origin or replacement.origin replacement.revision=math.max(tonumber(account.revision)or 0,replacement.revision)replacement.disabled=account.disabled==true stamp(replacement)all[name]=replacement assert(save(all),\"could not save password\")if M.current and M.current.name==name then M.current=nil;sessionPathDelete()end safeAudit(\"password.reset\",{account=name})return true end function M.resetPassword(name,plainPassword)if authority()then local account=centralDirectory().users[name];assert(account,\"unknown user\")local record,err=makeAccount(account.role,plainPassword,\"central-reset:\"..name);assert(record,err)return require((\"ceetos.lib.auth_client\")).mutate(\"reset\",{name=name,record=record})end if not M.allowed(\"admin\")and not recoveryActive()then error(\"permission denied (requires admin or active recovery window)\",2)end return setPassword(name,plainPassword)end function M.adminResetPassword(name,plainPassword)if authority()then local account=centralDirectory().users[name];assert(account,\"unknown user\")local record,err=makeAccount(account.role,plainPassword,\"central-reset:\"..name);assert(record,err)return require((\"ceetos.lib.auth_client\")).mutate(\"reset\",{name=name,record=record})end M.require(\"operator\")local account=users()[name]assert(account,\"unknown user\")if account.role==\"admin\"then M.require(\"admin\")end return setPassword(name,plainPassword)end function M.allowed(role)if not rank[role]then return false end local current=M.refreshSession()return current~=nil and rank[current.role]>=rank[role]end function M.require(role)if not M.allowed(role)then error(\"permission denied (requires \"..tostring(role)..\")\",2)end end function M.list()local out={}local source=authority()and centralDirectory().users or users()for name,account in pairs(source)do out[#out+1]={name=name,role=account.role,disabled=account.disabled==true,revision=account.revision}end table.sort(out,function(a,b)return a.name<b.name end)return out end function M.snapshot()if authority()then return{users={},tombstones={},source=tostring(os.getComputerID()),schema=3,central=true}end return M.authoritySnapshot()end function M.authoritySnapshot()local copy={users={},tombstones={},source=tostring(os.getComputerID()),schema=2}for name,account in pairs(users())do copy.users[name]={role=account.role,salt=account.salt,verifier=account.verifier,passwordVersion=account.passwordVersion,scheme=account.scheme,workFactor=account.workFactor,revision=tonumber(account.revision)or 0,disabled=account.disabled==true,updated=account.updated or 0,origin=account.origin or copy.source,}end for name,removed in pairs(tombstones())do copy.tombstones[name]=removed end return copy end local function validIncomingPassword(account)if password.isModern(account)then local work=password.normaliseWorkFactor(account.workFactor)return work~=nil and type(account.verifier)==\"string\"and#account.verifier==64 and account.verifier:match(\"^[0-9a-f]+$\")~=nil end return type(account.salt)==\"string\"and#account.salt>0 and#account.salt<=256 and type(account.verifier)==\"string\"and account.verifier:match(\"^[0-9a-fA-F]+$\")~=nil and#account.verifier==8 end function M.merge(snapshot,authoritySeed)if authority()and authoritySeed~=true then return false,\"distributed account sync is disabled by central authority\"end if type(snapshot)~=\"table\"or type(snapshot.users)~=\"table\"then return false,\"invalid account sync\"end local all,removed,changed=users(),tombstones(),false for name,deletedAt in pairs(snapshot.tombstones or{})do if accountName(name)and type(deletedAt)==\"number\"and deletedAt>(removed[name]or 0)then local localAccount=all[name]if not localAccount or(localAccount.updated or 0)<=deletedAt then all[name],removed[name],changed=nil,deletedAt,true end end end for name,account in pairs(snapshot.users)do if accountName(name)and type(account)==\"table\"and rank[account.role]and validIncomingPassword(account)then local updated=tonumber(account.updated)or 0 local localAccount,incomingOrigin=all[name],tostring(account.origin or snapshot.source or\"\")local localOrigin=localAccount and tostring(localAccount.origin or os.getComputerID())or\"\"local wins=not localAccount or updated>(localAccount.updated or 0)or(updated==(localAccount.updated or 0)and incomingOrigin~=\"\"and incomingOrigin<localOrigin)if(removed[name]==nil or updated>removed[name])and wins then all[name]={role=account.role,salt=account.salt,verifier=account.verifier,passwordVersion=account.passwordVersion,scheme=account.scheme,workFactor=account.workFactor,revision=math.max(0,math.floor(tonumber(account.revision)or 0)),disabled=account.disabled==true,updated=updated,origin=incomingOrigin,}changed=true end end end if changed then assert(save(all),\"could not save account sync\")assert(saveTombstones(removed),\"could not save account tombstones\")M.refreshSession()end return changed end function M.authorityAccount(name)if not accountName(name)then return nil end return users()[name]end function M.authorityDirectory()local out={}for name,account in pairs(users())do out[name]={role=account.role,disabled=account.disabled==true,revision=tonumber(account.revision)or 0}end return out end function M.authorityMutate(action,fields)fields=type(fields)==\"table\"and fields or{}local name=fields.name assert(accountName(name),\"invalid user name\")local all,account=users(),users()[name]if action==\"add\"then assert(not account,\"user exists\")assert(rank[fields.role],\"invalid role\")local record=fields.record assert(type(record)==\"table\"and password.isModern(record),\"central account mutation requires a verifier record\")record.role,record.disabled=fields.role,false;all[name]=stamp(record);assert(save(all),\"could not save user\")elseif action==\"role\"then assert(account and rank[fields.role],\"unknown user or invalid role\")if account.role==\"admin\"and fields.role~=\"admin\"then local admins=0;for _,candidate in pairs(all)do if candidate.role==\"admin\"and not candidate.disabled then admins=admins+1 end end assert(admins>1,\"cannot demote the last active admin\")end account.role=fields.role;stamp(account);all[name]=account;assert(save(all),\"could not save role\")elseif action==\"disable\"then if account and account.role==\"admin\"and fields.disabled==true then local admins=0;for _,candidate in pairs(all)do if candidate.role==\"admin\"and not candidate.disabled then admins=admins+1 end end assert(admins>1,\"cannot disable the last active admin\")end assert(account,\"unknown user\");account.disabled=fields.disabled==true;stamp(account);all[name]=account;assert(save(all),\"could not save user state\")elseif action==\"remove\"then assert(account,\"unknown user\")if account.role==\"admin\"and not account.disabled then local admins=0;for _,candidate in pairs(all)do if candidate.role==\"admin\"and not candidate.disabled then admins=admins+1 end end assert(admins>1,\"cannot remove the last active admin\")end all[name]=nil;local removed=tombstones();removed[name]=now();assert(saveTombstones(removed),\"could not save tombstone\");assert(save(all),\"could not remove user\")elseif action==\"reset\"then assert(account,\"unknown user\")local replacement=fields.record assert(type(replacement)==\"table\"and password.isModern(replacement),\"central password reset requires a verifier record\")replacement.role,replacement.disabled=account.role,account.disabled==true;all[name]=stamp(replacement);assert(save(all),\"could not save password\")else error(\"unsupported account mutation\")end safeAudit(\"authority.\"..action,{account=name})return M.authorityDirectory()end M.refreshSession()return M",
  ["ceetos/lib/password.lua"] = "local M={}M.SCHEME=\"pbkdf2-hmac-sha256\"M.PASSWORD_VERSION=2 M.DEFAULT_WORK_FACTOR=256 M.MIN_WORK_FACTOR=64 M.MAX_WORK_FACTOR=2048 M.MIN_LENGTH=8 M.MAX_LENGTH=128 local MOD=4294967296 local band,bor,bxor,bnot=bit32.band,bit32.bor,bit32.bxor,bit32.bnot local rshift,lshift=bit32.rshift,bit32.lshift local unpack=table.unpack or unpack local K={0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2,}local initial={0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19,}local function add(...)local value=0 for i=1,select(\"#\",...)do value=(value+(select(i,...)or 0))%MOD end return value end local function rrotate(value,amount)if bit32.rrotate then return bit32.rrotate(value,amount)end return bor(rshift(value,amount),lshift(value,32-amount))end local function word(bytes,index)return bytes:byte(index)*16777216+bytes:byte(index+1)*65536+bytes:byte(index+2)*256+bytes:byte(index+3)end local function packWord(value)return string.char(band(rshift(value,24),0xff),band(rshift(value,16),0xff),band(rshift(value,8),0xff),band(value,0xff))end local function sha256Raw(value)local bitLength=#value*8 value=value..string.char(0x80)value=value..string.rep(\"\\0\",(56-(#value%64))%64)value=value..packWord(math.floor(bitLength/MOD))..packWord(bitLength%MOD)local h={unpack(initial)}for offset=1,#value,64 do if#value>16384 and offset>1 and((offset-1)/64)%128==0 and type(sleep)==\"function\"then sleep(0)end local w={}for i=1,16 do w[i]=word(value,offset+(i-1)*4)end for i=17,64 do local x,y=w[i-15],w[i-2]local s0=bxor(rrotate(x,7),rrotate(x,18),rshift(x,3))local s1=bxor(rrotate(y,17),rrotate(y,19),rshift(y,10))w[i]=add(w[i-16],s0,w[i-7],s1)end local a,b,c,d,e,f,g,hh=unpack(h)for i=1,64 do local s1=bxor(rrotate(e,6),rrotate(e,11),rrotate(e,25))local choice=bxor(band(e,f),band(bnot(e),g))local t1=add(hh,s1,choice,K[i],w[i])local s0=bxor(rrotate(a,2),rrotate(a,13),rrotate(a,22))local majority=bxor(band(a,b),band(a,c),band(b,c))local t2=add(s0,majority)hh,g,f,e,d,c,b,a=g,f,e,add(d,t1),c,b,a,add(t1,t2)end h[1],h[2],h[3],h[4]=add(h[1],a),add(h[2],b),add(h[3],c),add(h[4],d)h[5],h[6],h[7],h[8]=add(h[5],e),add(h[6],f),add(h[7],g),add(h[8],hh)end local result={}for i=1,8 do result[i]=packWord(h[i])end return table.concat(result)end local function hmac(key,message)if#key>64 then key=sha256Raw(key)end key=key..string.rep(\"\\0\",64-#key)local inner,outer={},{}for i=1,64 do local byte=key:byte(i)inner[i],outer[i]=string.char(bxor(byte,0x36)),string.char(bxor(byte,0x5c))end return sha256Raw(table.concat(outer)..sha256Raw(table.concat(inner)..message))end local function xorBytes(left,right)local out={}for i=1,#left do out[i]=string.char(bxor(left:byte(i),right:byte(i)))end return table.concat(out)end local function cooperate(round)if round%32~=0 or not(os and os.queueEvent and os.pullEvent)then return end os.queueEvent(\"ceetos_password_yield\")os.pullEvent(\"ceetos_password_yield\")end local function toHex(value)return(value:gsub(\".\",function(byte)return string.format(\"%02x\",byte:byte())end))end local function constantEqual(left,right)if type(left)~=\"string\"or type(right)~=\"string\"then return false end local differing=bxor(#left,#right)local length=math.max(#left,#right)for i=1,length do differing=bor(differing,bxor(left:byte(i)or 0,right:byte(i)or 0))end return differing==0 end function M.hmacSha256(key,message)if type(key)~=\"string\"or type(message)~=\"string\"then return nil,\"HMAC key and message must be strings\"end return toHex(hmac(key,message))end function M.sha256(value)if type(value)~=\"string\"then return nil,\"SHA-256 input must be a string\"end return toHex(sha256Raw(value))end function M.constantTimeEqual(left,right)return constantEqual(left,right)end function M.legacyDigest(value)local h=2166136261 for i=1,#value do h=bxor(h,value:byte(i))h=(h*16777619)%MOD end return string.format(\"%08x\",h)end function M.normaliseWorkFactor(value)value=tonumber(value)if not value or value%1~=0 then return nil,\"invalid password work factor\"end if value<M.MIN_WORK_FACTOR or value>M.MAX_WORK_FACTOR then return nil,\"password work factor must be \"..M.MIN_WORK_FACTOR..\"-\"..M.MAX_WORK_FACTOR end return value end function M.policy(password)if type(password)~=\"string\"then return false,\"password is required\"end if#password<M.MIN_LENGTH or#password>M.MAX_LENGTH then return false,\"password must contain \"..M.MIN_LENGTH..\"-\"..M.MAX_LENGTH..\" characters\"end if password:find(\"[%z\\1-\\31\\127]\")then return false,\"password contains control characters\"end return true end function M.derive(password,salt,workFactor)local work,err=M.normaliseWorkFactor(workFactor)if not work then return nil,err end if type(password)~=\"string\"or type(salt)~=\"string\"or#salt<16 or#salt>256 then return nil,\"invalid password record\"end local block=string.char(0,0,0,1)local value=hmac(password,salt..block)local result=value for _=2,work do value=hmac(password,value)result=xorBytes(result,value)cooperate(_)end return toHex(result)end local saltCounter=0 function M.newSalt(context)saltCounter=saltCounter+1 local now=os.epoch and os.epoch(\"utc\")or 0 local computer=os.getComputerID and os.getComputerID()or 0 local label=os.getComputerLabel and os.getComputerLabel()or\"\"local random=math.random and math.random(0,2147483647)or 0 return toHex(sha256Raw(table.concat({tostring(now),tostring(computer),tostring(label),tostring(context or\"\"),tostring(saltCounter),tostring(random)},\":\"))):sub(1,32)end function M.record(password,salt,workFactor)local valid,err=M.policy(password)if not valid then return nil,err end local work,workErr=M.normaliseWorkFactor(workFactor or M.DEFAULT_WORK_FACTOR)if not work then return nil,workErr end salt=salt or M.newSalt()local verifier,deriveErr=M.derive(password,salt,work)if not verifier then return nil,deriveErr end return{passwordVersion=M.PASSWORD_VERSION,scheme=M.SCHEME,salt=salt,verifier=verifier,workFactor=work,}end function M.isModern(record)return type(record)==\"table\"and record.passwordVersion==M.PASSWORD_VERSION and record.scheme==M.SCHEME end function M.verify(record,password)if type(record)~=\"table\"or type(password)~=\"string\"or type(record.salt)~=\"string\"or type(record.verifier)~=\"string\"then return false,\"invalid password record\"end if M.isModern(record)then local verifier,err=M.derive(password,record.salt,record.workFactor)if not verifier then return false,err end return constantEqual(record.verifier,verifier),nil end return constantEqual(record.verifier,M.legacyDigest(record.salt..password)),\"legacy\"end return M",
  ["ceetos/lib/release_keys.lua"] = "return{algorithm=\"lamport-sha256-v1\",roots={[\"desktop-release-0.16.6\"]={public=\"/IHkkeuPk+ILl9AhGuZUxCu6gqyMZnfs5OcpKtPUt5q24/mJLszGGI9edEw/0pqPd5NSXW4iY5PuZagXrjwYZeHpY/dr/1RNVGpl2hUsFpeKktXtJ76Y9tS7fxPYEAEl+tplVWyhQlBPcaiV2U+EzCWCP6iYLYS+VGS8aBJW7Og+nGowIXQk6je2tH6+gg6ZRUT0sn93hlrU9o8SJM1GuATvUzH1UI9EMKx7m+hFAJngMwKmS1jn8eJK1YJtpCz5yXfKj9kn5mlHlQBgH2ggkhCO6q3WGUv67YXRVwnHrU9s23+YcZ/jl80lSgW7HRrM4iV3ugkie3cm16SDUjalt189yOISjJAvBrxAR1Pa9HL+/cTx5nIaxC7cXdheYBMuE2MXWfzq3CjFxP2fHmJU062tBTwsEbEIHYWGF3/9GnDYdH2W/Ws6Li5TsEetsyvZrjK9A5M9ykHqdULd4/0WY0njf7ERk42Vo4RuPf9VZRHZf8ZTPQsLPMBF9dPljxsCdCKbHT/3WlZ5vRD2WTAyJ35u2mnS/VTRAV1wESNEojrOKXea9X2bRjTMNfG83Lo25pOuCLF1X66B9AUcnDVF39I3uDkAaqPb/At3yJMQ1yD647SR4gUFTsS1KTiwZSj/L4TwkkRPxNCFYmDzAnGwqNiXjY/vE7+1xxwGV2+XQlUUZlfiNbgl7lKhehwapR3V4tUXu9kp8VDYCTc5kHHQyndJvQyFwSX1cVcKrOqSPQWy7u5rg3uYOcAoTBXHKUjGoxaP0GwXI4/FKDQ+dmzT3o51RBPZhqbE5W4ydGIkkA/XN5iYhGh5FFupNVwbg5+S6UPSmqxboV4mLephEHuzLG2LsNWMZmDfT8564TkyZe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lNaV6N91MNaoKSefR3sIZ8ymgferwimaiFyk1P8ho05BVzfP7PBkXLc67/cgcYK3Df/v9f2TrmYVvyEHmkZun2mgD1ZLOtsJs0SPQCgBKIjxCKSd5dJAZNiSjRuo7F1GutjNbP7k+59uHkviYN/y18PCS3uQnEYz55l2Fbvedm21/VVNOl+xDNP2jgrD2dKVwVS9LQGSC8DCny9NmANxqVl2dTuwFdb39+/X4AEaT0wabaPy/AJR+oUbpLFuPk1ORmPXcgywN79Hy2JMaalIyQ0SzIVcUWUTMgKQ6CgPR0yEExF1zytwBbpd09ddrDdH0vunaLMqcADviz5s4p3RlsqPkDcXMvaEZp38LtqPrrkFn4CnMuE7GLAMCu7P2c7xmM46ah/n/wIk56tEImlYkKlhKTaXfKHpiN6QB0ktkhbZU8NlRQPX8yHPwwipXfov0XA9t8wYYex9pWrsKgQrBxAzAXFgAQGuP1teKG6wVfNcYXfU8ghmqrHysYiazyvwv1C+x0gFj4nvbNmv3uYCDHjq7ChBBb3wt0gA/Bb3r1VnvbQDvaZDodzGve1TXim5vDr8E0AMlh/qG7hDNxCwpD/Yxk9DclhqAFaBf3GD5pckfMUYIXiTjL8Dzf/q4L6Mb+/cr1X1smdoDhQII2i0JfMxL4eRBT/X/mznSiIu/4lnxBxXwYuouaaQiOlw0atWp1iVQljl6SLyuE28Ki4psjrZg1LVY8py005Vyqs3WmRByA3xdBjvc9VMaDgeWrxh8i0A==\",profile=\"desktop\"},},}",
  ["ceetos/lib/release_verify.lua"] = "local password=require(\"ceetos.lib.password\")local roots=require(\"ceetos.lib.release_keys\")local profile=require(\"ceetos.lib.profile\")local M={}M.CACHE_ROOT=\"/ceetos-updates\"M.CACHE_FILE=\"/ceetos-updates/release.lua\"M.META_FILE=\"/ceetos-updates/cache.lua\"M.PART_FILE=\"/ceetos-updates/release.part\"M.PENDING_FILE=\"/ceetos-updates/pending.lua\"M.MAX_PACKAGE_BYTES=1024*1024 M.MAX_MANIFEST_BYTES=48*1024 M.CHUNK_BYTES=3072 M.KEY_PARTS=256 local alphabet=\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\"local decodeMap={}for i=1,#alphabet do decodeMap[alphabet:sub(i,i)]=i-1 end local function read(path)if not fs.exists(path)or fs.isDir(path)then return nil end local handle=fs.open(path,\"r\")if not handle then return nil end local value=handle.readAll();handle.close()return value end local function write(path,value)local parent=fs.getDir(path)if parent~=\"\"and not fs.exists(parent)then fs.makeDir(parent)end local temporary=path..\".tmp\"if fs.exists(temporary)then fs.delete(temporary)end local handle=assert(fs.open(temporary,\"w\"),\"could not create temporary release state\")handle.write(value);handle.close()if fs.exists(path)then fs.delete(path)end fs.move(temporary,path)end local function encode(value)local out,index={},1 while index<=#value do local a,b,c=value:byte(index,index+2)local n=(a or 0)*65536+(b or 0)*256+(c or 0)out[#out+1]=alphabet:sub(math.floor(n/262144)%64+1,math.floor(n/262144)%64+1)out[#out+1]=alphabet:sub(math.floor(n/4096)%64+1,math.floor(n/4096)%64+1)out[#out+1]=b and alphabet:sub(math.floor(n/64)%64+1,math.floor(n/64)%64+1)or\"=\"out[#out+1]=c and alphabet:sub(n%64+1,n%64+1)or\"=\"index=index+3 end return table.concat(out)end local function decode(value)if type(value)~=\"string\"or#value%4~=0 or#value>M.MAX_MANIFEST_BYTES*2 then return nil,\"invalid base64\"end local out={}for index=1,#value,4 do local a,b,c,d=value:sub(index,index),value:sub(index+1,index+1),value:sub(index+2,index+2),value:sub(index+3,index+3)if not decodeMap[a]or not decodeMap[b]or(c~=\"=\"and not decodeMap[c])or(d~=\"=\"and not decodeMap[d])then return nil,\"invalid base64\"end if(c==\"=\"and d~=\"=\")or((c==\"=\"or d==\"=\")and index+3~=#value)then return nil,\"invalid base64 padding\"end local n=decodeMap[a]*262144+decodeMap[b]*4096+(decodeMap[c]or 0)*64+(decodeMap[d]or 0)out[#out+1]=string.char(math.floor(n/65536)%256)if c~=\"=\"then out[#out+1]=string.char(math.floor(n/256)%256)end if d~=\"=\"then out[#out+1]=string.char(n%256)end end return table.concat(out)end local function unhex(value)if type(value)~=\"string\"or#value%2~=0 or value:find(\"[^%x]\")then return nil end return(value:gsub(\"..\",function(pair)return string.char(tonumber(pair,16))end))end local function semver(value)if type(value)~=\"string\"then return nil end local major,minor,patch=value:match(\"^(%d+)%.(%d+)%.(%d+)$\")if not major then return nil end return tonumber(major),tonumber(minor),tonumber(patch)end function M.compareVersions(left,right)local a,b,c=semver(left);local x,y,z=semver(right)if not a or not x then return nil,\"invalid semantic version\"end if a~=x then return a<x and-1 or 1 end if b~=y then return b<y and-1 or 1 end if c~=z then return c<z and-1 or 1 end return 0 end local function canonical(manifest)if manifest._legacyProfile==true then return table.concat({\"ceetos-release-v1\",tostring(manifest.channel),tostring(manifest.version),tostring(manifest.size),tostring(manifest.digest),tostring(manifest.key_id),tostring(manifest.next_key_id),tostring(manifest.next_public),},\"|\")end return table.concat({\"ceetos-release-v2\",tostring(manifest.channel),tostring(manifest.profile),tostring(manifest.version),tostring(manifest.size),tostring(manifest.digest),tostring(manifest.key_id),tostring(manifest.next_key_id),tostring(manifest.next_public),},\"|\")end local function unpackKey(value)local raw,err=decode(value)if not raw or#raw~=M.KEY_PARTS*2*32 then return nil,err or\"invalid public key\"end local parts={}for index=1,M.KEY_PARTS*2 do parts[index]=raw:sub((index-1)*32+1,index*32)end return parts end function M.validPublicKey(value)return unpackKey(value)end local function lookupKey(keyId)local saved=M.trustedKeys()local value=saved[keyId]if value then return unpackKey(value)end value=roots.roots and roots.roots[keyId]if type(value)==\"table\"and type(value.public)==\"string\"then value=value.public end return unpackKey(value)end local function bitAt(digest,index)local byte=digest:byte(math.floor((index-1)/8)+1)return bit32.band(bit32.rshift(byte,7-((index-1)%8)),1)end local function decodeSignature(value)local raw,err=decode(value)if not raw or#raw~=M.KEY_PARTS*32 then return nil,err or\"invalid signature\"end local parts={}for index=1,M.KEY_PARTS do parts[index]=raw:sub((index-1)*32+1,index*32)end return parts end local function verifySignature(manifest,signature)if roots.algorithm~=\"lamport-sha256-v1\"then return false,\"unsupported release signing algorithm\"end local public,publicErr=lookupKey(manifest.key_id)local parts,signatureErr=decodeSignature(signature)if not public or not parts then local prefix=not public and\"invalid release public key: \"or\"invalid release signature: \"return false,prefix..tostring(publicErr or signatureErr or\"unknown release key\")end local digest=unhex(password.sha256(canonical(manifest))or\"\")if not digest then return false,\"could not hash release manifest\"end for index=1,M.KEY_PARTS do local expected=public[(index-1)*2+bitAt(digest,index)+1]local candidate=unhex(password.sha256(parts[index])or\"\")if not candidate or not password.constantTimeEqual(candidate,expected)then return false,\"invalid release signature\"end end return true end local function validateManifest(manifest)if type(manifest)~=\"table\"or manifest.channel~=\"release\"then return nil,\"only signed release packages are accepted\"end if manifest.profile==nil then manifest.profile,manifest._legacyProfile=\"desktop\",true end if type(manifest.profile)~=\"string\"or not profile.IDS[manifest.profile]then return nil,\"invalid release profile\"end if not semver(manifest.version)or type(manifest.size)~=\"number\"or manifest.size<1 or manifest.size>M.MAX_PACKAGE_BYTES then return nil,\"invalid release manifest size or version\"end if type(manifest.digest)~=\"string\"or#manifest.digest~=64 or manifest.digest:find(\"[^%x]\")then return nil,\"invalid release digest\"end if type(manifest.key_id)~=\"string\"or#manifest.key_id<1 or#manifest.key_id>64 then return nil,\"invalid release key id\"end if type(manifest.next_key_id)~=\"string\"or#manifest.next_key_id<1 or#manifest.next_key_id>64 then return nil,\"invalid next release key id\"end local nextKey=unpackKey(manifest.next_public)if not nextKey then return nil,\"invalid successor release key\"end return manifest end function M.parse(source)if type(source)~=\"string\"or#source>M.MAX_PACKAGE_BYTES then return nil,\"release package is too large\"end local encodedManifest,encodedSignature=source:match(\"^%-%- CEETOS_RELEASE_MANIFEST:([^\\r\\n]+)[\\r\\n]+%-%- CEETOS_RELEASE_SIGNATURE:([^\\r\\n]+)\")if not encodedManifest then encodedManifest,encodedSignature=source:match(\"^%-%- CeetOS signed release%. Generated; do not edit%.[\\r\\n]+%-%- CEETOS_RELEASE_MANIFEST:([^\\r\\n]+)[\\r\\n]+%-%- CEETOS_RELEASE_SIGNATURE:([^\\r\\n]+)\")end local first=source:find(\"%-%- CEETOS_RELEASE_PAYLOAD_BEGIN[\\r\\n]+\")if not encodedManifest or not encodedSignature or not first then return nil,\"not a signed CeetOS release package\"end local decoded,decodeErr=decode(encodedManifest)if not decoded then return nil,\"invalid release manifest encoding: \"..tostring(decodeErr)end local loader=load(\"return \"..decoded,\"=release-manifest\",\"t\",{})if not loader then return nil,\"invalid release manifest\"end local ok,manifest=pcall(loader)if not ok then return nil,\"invalid release manifest\"end local valid,manifestErr=validateManifest(manifest)if not valid then return nil,manifestErr end local start=source:find(\"\\n\",first)+1 local finish=start+valid.size-1 local payload=source:sub(start,finish)local suffix=source:sub(finish+1)if suffix~=\"\\n-- CEETOS_RELEASE_PAYLOAD_END\\n\"and suffix~=\"\\n-- CEETOS_RELEASE_PAYLOAD_END\"and suffix~=\"\\r\\n-- CEETOS_RELEASE_PAYLOAD_END\\r\\n\"and suffix~=\"\\r\\n-- CEETOS_RELEASE_PAYLOAD_END\"then return nil,\"release payload boundary mismatch\"end if#payload~=valid.size or not password.constantTimeEqual(password.sha256(payload)or\"\",valid.digest)then return nil,\"release payload digest mismatch\"end local signed,signatureErr=verifySignature(valid,encodedSignature)if not signed then return nil,signatureErr end return{manifest=valid,signature=encodedSignature,payload=payload,source=source}end function M.trustedKeys()local raw=read(M.CACHE_ROOT..\"/trusted-keys.lua\")if not raw then return{}end local loader=load(raw,\"=trusted-release-keys\",\"t\",{})if not loader then return{}end local ok,value=pcall(loader)return ok and type(value)==\"table\"and value or{}end local function saveKeys(value)local encoded=textutils.serialise(value,{compact=true})write(M.CACHE_ROOT..\"/trusted-keys.lua\",\"return \"..encoded)end function M.metadata()local raw=read(M.META_FILE)if not raw then return nil end local loader=load(raw,\"=release-cache\",\"t\",{})if not loader then return nil end local ok,value=pcall(loader)return ok and type(value)==\"table\"and value or nil end function M.cache(source,provider)local package,err=M.parse(source)if not package then return nil,err end if fs.exists(M.CACHE_ROOT)and fs.isDir(M.CACHE_ROOT)then if fs.exists(M.PART_FILE)then fs.delete(M.PART_FILE)end elseif not fs.exists(M.CACHE_ROOT)then fs.makeDir(M.CACHE_ROOT)end write(M.CACHE_FILE,package.source)local metadata={schema=2,channel=package.manifest.channel,profile=package.manifest.profile,version=package.manifest.version,size=package.manifest.size,digest=package.manifest.digest,keyId=package.manifest.key_id,nextKeyId=package.manifest.next_key_id,source=provider and tostring(provider)or\"local\",cachedAt=os.epoch(\"utc\"),}write(M.META_FILE,\"return \"..textutils.serialise(metadata,{compact=true}))local keys=M.trustedKeys();keys[package.manifest.next_key_id]=package.manifest.next_public;saveKeys(keys)return metadata end function M.promotePart(path,provider)if type(path)~=\"string\"or path~=M.PART_FILE then return nil,\"invalid release staging path\"end local source=read(path)local package,err=M.parse(source)if not package then return nil,err end if not fs.exists(M.CACHE_ROOT)then fs.makeDir(M.CACHE_ROOT)end if fs.exists(M.CACHE_FILE)then fs.delete(M.CACHE_FILE)end fs.move(M.PART_FILE,M.CACHE_FILE)local metadata={schema=2,channel=package.manifest.channel,profile=package.manifest.profile,version=package.manifest.version,size=package.manifest.size,digest=package.manifest.digest,keyId=package.manifest.key_id,nextKeyId=package.manifest.next_key_id,source=provider and tostring(provider)or\"local\",cachedAt=os.epoch(\"utc\"),}write(M.META_FILE,\"return \"..textutils.serialise(metadata,{compact=true}))M.adopt(package)return metadata end function M.adopt(package)if type(package)~=\"table\"or type(package.manifest)~=\"table\"then return false,\"invalid verified package\"end local keys=M.trustedKeys()keys[package.manifest.next_key_id]=package.manifest.next_public saveKeys(keys)return true end function M.cachedPackage()local source,metadata=read(M.CACHE_FILE),M.metadata()if not source then return nil end local package,err=M.parse(source)if not package then return nil,err end if not metadata then metadata={schema=2,channel=package.manifest.channel,profile=package.manifest.profile,version=package.manifest.version,size=package.manifest.size,digest=package.manifest.digest,keyId=package.manifest.key_id,nextKeyId=package.manifest.next_key_id,source=\"local installer\",cachedAt=os.epoch(\"utc\"),}write(M.META_FILE,\"return \"..textutils.serialise(metadata,{compact=true}))end M.adopt(package)return package,metadata end function M.clear()if fs.exists(M.PART_FILE)then fs.delete(M.PART_FILE)end if fs.exists(M.CACHE_FILE)then fs.delete(M.CACHE_FILE)end if fs.exists(M.META_FILE)then fs.delete(M.META_FILE)end return true end function M.encode(value)return encode(value)end function M.decode(value)return decode(value)end function M.canonical(manifest)return canonical(manifest)end return M",
  ["ceetos/lib/updater.lua"] = "local store=require(\"ceetos.lib.store\")local release=require(\"ceetos.lib.release_verify\")local version=require(\"ceetos.lib.version\")local net=require(\"ceetos.lib.net\")local profile=require(\"ceetos.lib.profile\")local M={}local STATE_PATH=\"/ceetos/data/update-status.lua\"local OFFER_LIMIT,HISTORY_LIMIT=20,16 local BEACON_INTERVAL,REQUEST_TIMEOUT,REQUEST_LIMIT=30000,3500,3 local MAX_OFFER_AGE=5*60*1000 local CLOUD_RELEASE_ORIGIN=\"https://releases.ceet.uk\"local CLOUD_MANIFEST_URL=CLOUD_RELEASE_ORIGIN..\"/manifest.json\"local CLOUD_SOURCE_ID=\"cloud.releases.ceet.uk\"local state=nil local lastBeacon,lastCacheRead=0,0 local cached=nil local function now()return os.epoch(\"utc\")end local function localId()return tostring(os.getComputerID())end local function localLabel()return os.getComputerLabel()or(\"Computer \"..localId())end local function defaults()return{schema=1,offers={},history={},revision=0,status=\"idle\",message=nil,transfer=nil,cache=nil}end local function loadState()if state then return state end state=store.read(STATE_PATH,defaults())for key,value in pairs(defaults())do if state[key]==nil then state[key]=value end end state.offers=type(state.offers)==\"table\"and state.offers or{}state.history=type(state.history)==\"table\"and state.history or{}return state end local function save()local value=loadState()value.revision=(tonumber(value.revision)or 0)+1 store.write(STATE_PATH,value)end local function record(kind,fields)local value=loadState()local row={at=now(),kind=tostring(kind):sub(1,48)}for key,item in pairs(fields or{})do if key~=\"data\"and key~=\"source\"and key~=\"signature\"then row[key]=item end end value.history[#value.history+1]=row while#value.history>HISTORY_LIMIT do table.remove(value.history,1)end end local function setStatus(status,message)local value=loadState()value.status,value.message=status,message and tostring(message):sub(1,180)or nil end local function validId(value)return type(value)==\"string\"and value:match(\"^[%w_%-%.]+$\")and#value<=96 end local function releaseFilename(profileId,releaseVersion)if profileId==\"desktop\"then return\"desktop/ceetos-release\"..releaseVersion..\".lua\"end return profileId..\"/ceetos-\"..profileId..\"-release\"..releaseVersion..\".lua\"end local function readHttp(url,limit)if not http or type(http.get)~=\"function\"then return nil,\"HTTP is unavailable; enable it to check releases.ceet.uk\"end local ok,response,requestErr=pcall(http.get,url,{[\"Accept\"]=\"application/json\"})if not ok or not response then return nil,tostring(requestErr or\"release server request failed\")end local chunks,total={},0 while true do local part=response.read(math.min(4096,limit-total+1))if not part or part==\"\"then break end total=total+#part if total>limit then pcall(response.close);return nil,\"release server response is too large\"end chunks[#chunks+1]=part end pcall(response.close)return table.concat(chunks)end local function validOffer(body)if type(body)~=\"table\"or type(body.version)~=\"string\"or type(body.size)~=\"number\"or type(body.digest)~=\"string\"or type(body.keyId)~=\"string\"or type(body.profile)~=\"string\"then return nil,\"malformed release offer\"end if body.profile~=profile.id()then return nil,\"release profile does not match this installation\"end local compare=release.compareVersions(body.version,version.string)if compare==nil then return nil,\"invalid release version\"end if body.size<1 or body.size>release.MAX_PACKAGE_BYTES then return nil,\"invalid release size\"end if#body.digest~=64 or body.digest:find(\"[^%x]\")then return nil,\"invalid release digest\"end if#body.keyId<1 or#body.keyId>64 then return nil,\"invalid release key ID\"end local filename=body.filename if filename~=nil and filename~=releaseFilename(body.profile,body.version)then return nil,\"invalid release filename\"end return{profile=body.profile,version=body.version,size=math.floor(body.size),digest=body.digest:lower(),keyId=body.keyId,filename=filename,fingerprint=body.digest:sub(1,16),newer=compare>0}end local function refreshCached()local timestamp=now()if cached and timestamp-lastCacheRead<5000 then return cached end lastCacheRead=timestamp local value=loadState()local previous=value.cache and(tostring(value.cache.version)..\":\"..tostring(value.cache.digest))or nil local package,metadata=release.cachedPackage()if package and package.manifest.profile==profile.id()then cached={package=package,metadata=metadata,offer={version=package.manifest.version,size=#package.source,digest=package.manifest.digest,profile=package.manifest.profile,keyId=package.manifest.key_id,fingerprint=package.manifest.digest:sub(1,16),}}value.cache={profile=package.manifest.profile,version=package.manifest.version,size=#package.source,digest=package.manifest.digest,keyId=package.manifest.key_id,fingerprint=package.manifest.digest:sub(1,16),source=metadata and metadata.source or\"local\",verifiedAt=timestamp}else cached=nil value.cache=nil end local current=value.cache and(tostring(value.cache.version)..\":\"..tostring(value.cache.digest))or nil if current~=previous then save()end return cached end local function providerOffer()local available=refreshCached()if not available then return nil end return{version=available.offer.version,size=available.offer.size,digest=available.offer.digest,profile=available.offer.profile,keyId=available.offer.keyId,label=localLabel(),id=localId(),}end local function upsertOffer(source,body,transport,distance)source=tostring(source)if source==localId()then return false,\"ignored own release offer\"end local offer,err=validOffer(body)if not offer then return false,err end if not offer.newer then return false,\"offered release is not newer\"end local value=loadState()local key=source..\":\"..offer.version..\":\"..offer.digest:sub(1,16)value.offers[key]={id=source,label=tostring(body.label or(\"Computer \"..source)):sub(1,96),version=offer.version,profile=offer.profile,size=offer.size,digest=offer.digest,fingerprint=offer.fingerprint,keyId=offer.keyId,filename=offer.filename,transport=transport,distance=tonumber(distance),seen=now(),key=key,}local rows={}for entryKey,item in pairs(value.offers)do rows[#rows+1]={key=entryKey,seen=tonumber(item.seen)or 0}end table.sort(rows,function(a,b)return a.seen>b.seen end)while#rows>OFFER_LIMIT do value.offers[table.remove(rows).key]=nil end setStatus(\"offers\",\"Signed release \"..offer.version..\" available from \"..tostring(body.label or source))record(\"offer\",{id=source,version=offer.version,transport=transport,distance=distance})save()return true end local function checkCloudManifest()local raw,readErr=readHttp(CLOUD_MANIFEST_URL,release.MAX_MANIFEST_BYTES)if not raw then return 0,readErr end local ok,catalogue=pcall(textutils.unserialiseJSON,raw)if not ok or type(catalogue)~=\"table\"or catalogue.schema~=1 or type(catalogue.releases)~=\"table\"or#catalogue.releases>OFFER_LIMIT then return 0,\"invalid signed-release catalogue\"end local count=0 for index=1,#catalogue.releases do local entry=catalogue.releases[index]if type(entry)==\"table\"and entry.profile==profile.id()then local accepted=upsertOffer(CLOUD_SOURCE_ID,entry,\"cloud\")if accepted then count=count+1 end end end return count end local function offers()local value,timestamp,rows=loadState(),now(),{}for key,item in pairs(value.offers)do if type(item)==\"table\"and timestamp-(tonumber(item.seen)or 0)<=MAX_OFFER_AGE then rows[#rows+1]=item else value.offers[key]=nil end end table.sort(rows,function(left,right)local compare=release.compareVersions(left.version,right.version)or 0 if compare~=0 then return compare>0 end return tostring(left.id)<tostring(right.id)end)return rows end local function findOffer(source)source=tostring(source)for _,item in ipairs(offers())do if item.key==source or tostring(item.id)==source then return item end end return nil,\"release source is unavailable; run update check first\"end local function removePart()if fs.exists(release.PART_FILE)then fs.delete(release.PART_FILE)end end local function appendPart(data)local handle,err=fs.open(release.PART_FILE,\"a\")if not handle then return false,err or\"could not open update staging file\"end handle.write(data);handle.close()return true end local function cachedSource()local available=refreshCached()return available and available.package and available.package.source end local function transferRequest(transfer)local length=math.min(release.CHUNK_BYTES,transfer.size-transfer.offset+1)if length<1 then return false,\"transfer is already complete\"end transfer.awaiting,transfer.requestedAt=true,now()local body={transfer=transfer.id,offset=transfer.offset,length=length}local sent,err if transfer.transport==\"routed\"then sent,err=net.request(transfer.source,\"update_chunk_request\",body,{safe=true})else sent,err=net.publicSend(transfer.source,\"update_chunk_request\",body)end if not sent then transfer.awaiting=false;return false,err end return true end local function beginDownload(source)local offer,err=findOffer(source)if not offer then return false,err end local compare=release.compareVersions(offer.version,version.string)if not compare or compare<=0 then return false,\"refusing a downgrade or current release\"end local free=fs.getFreeSpace and fs.getFreeSpace(\"/\")or nil if type(free)==\"number\"and free<offer.size+4096 then return false,\"not enough free space for one verified release cache\"end removePart()release.clear();cached=nil local value=loadState()if offer.transport==\"cloud\"then setStatus(\"downloading\",\"Downloading signed release \"..offer.version..\" from releases.ceet.uk\")save()local sourceText,readErr=readHttp(CLOUD_RELEASE_ORIGIN..\"/\"..tostring(offer.filename or\"\"),release.MAX_PACKAGE_BYTES)if not sourceText then setStatus(\"error\",readErr);record(\"download_failed\",{id=CLOUD_SOURCE_ID,error=readErr});save();return false,readErr end local parsed,parseErr=release.parse(sourceText)if not parsed or parsed.manifest.profile~=offer.profile or parsed.manifest.version~=offer.version or parsed.manifest.digest:lower()~=offer.digest or parsed.manifest.key_id~=offer.keyId then local reason=parseErr or\"verified package did not match selected release offer\"setStatus(\"error\",reason);record(\"download_failed\",{id=CLOUD_SOURCE_ID,error=reason});save();return false,reason end local metadata,cacheErr=release.cache(sourceText,\"releases.ceet.uk\")if not metadata then setStatus(\"error\",cacheErr);record(\"download_failed\",{id=CLOUD_SOURCE_ID,error=cacheErr});save();return false,cacheErr end cached=nil;refreshCached()setStatus(\"downloaded\",\"Verified release \"..metadata.version..\" is ready for local confirmation\")record(\"download_verified\",{id=CLOUD_SOURCE_ID,version=metadata.version,digest=metadata.digest:sub(1,16)})save()return true,metadata end value.transfer={id=\"update-\"..localId()..\"-\"..tostring(now())..\"-\"..tostring(math.random(1000,9999)),source=tostring(offer.id),label=offer.label,transport=offer.transport==\"routed\"and\"routed\"or\"direct\",profile=offer.profile,version=offer.version,size=offer.size,digest=offer.digest,keyId=offer.keyId,offset=1,received=0,retries=0,awaiting=false,started=now(),}setStatus(\"downloading\",\"Downloading signed release \"..offer.version..\" from \"..offer.label)record(\"download_started\",{id=offer.id,version=offer.version,transport=value.transfer.transport})local sent,sendErr=transferRequest(value.transfer)if not sent then value.transfer=nil;setStatus(\"error\",sendErr);record(\"download_failed\",{id=offer.id,error=sendErr})end save()return sent,sendErr end local function finishTransfer(transfer)local handle=fs.open(release.PART_FILE,\"r\")local source=handle and handle.readAll()or nil if handle then handle.close()end if not source or#source~=transfer.size then return false,\"download size did not match offer\"end local parsed,parseErr=release.parse(source)if not parsed then return false,parseErr end if parsed.manifest.profile~=profile.id()or parsed.manifest.profile~=transfer.profile or parsed.manifest.version~=transfer.version or parsed.manifest.digest:lower()~=transfer.digest:lower()or parsed.manifest.key_id~=transfer.keyId then return false,\"verified package did not match selected release offer\"end local metadata,promoteErr=release.promotePart(release.PART_FILE,transfer.label)if not metadata then return false,promoteErr end cached=nil;refreshCached()local value=loadState();value.transfer=nil setStatus(\"downloaded\",\"Verified release \"..metadata.version..\" is ready for local confirmation\")record(\"download_verified\",{id=transfer.source,version=metadata.version,digest=metadata.digest:sub(1,16)})save()return true,metadata end local function acceptChunk(source,body,transport)local value,transfer=loadState(),loadState().transfer if not transfer or transfer.transport~=transport or tostring(source)~=tostring(transfer.source)then return false,\"unexpected update chunk\"end if type(body)~=\"table\"or body.transfer~=transfer.id or math.floor(tonumber(body.offset)or 0)~=transfer.offset or type(body.data)~=\"string\"then return false,\"malformed update chunk\"end local remaining=transfer.size-transfer.offset+1 if#body.data<1 or#body.data>math.min(release.CHUNK_BYTES,remaining)then return false,\"invalid update chunk length\"end local ok,err=appendPart(body.data)if not ok then transfer.awaiting=false;setStatus(\"error\",err);record(\"download_failed\",{error=err});save();return false,err end transfer.offset,transfer.received,transfer.awaiting,transfer.retries=transfer.offset+#body.data,(transfer.received or 0)+#body.data,false,0 if transfer.offset>transfer.size then local complete,result=finishTransfer(transfer)if not complete then removePart();value.transfer=nil;setStatus(\"error\",result);record(\"download_failed\",{id=source,error=result});save()end return complete,result end local sent,sendErr=transferRequest(transfer)if not sent then setStatus(\"error\",sendErr);record(\"download_failed\",{id=source,error=sendErr});value.transfer=nil;removePart()end save()return sent,sendErr end local function serveChunk(target,body,routed,request)if type(body)~=\"table\"or not validId(body.transfer)or math.floor(tonumber(body.offset)or 0)<1 or math.floor(tonumber(body.length)or 0)<1 or tonumber(body.length)>release.CHUNK_BYTES then return false,\"invalid update chunk request\"end local source=cachedSource()if not source then return false,\"no verified newer signed release is cached\"end local offset,length=math.floor(body.offset),math.floor(body.length)if offset>#source then return false,\"requested update offset is beyond package\"end local data=source:sub(offset,math.min(#source,offset+length-1))local response={transfer=body.transfer,offset=offset,data=data}if routed then return net.reply(request,\"update_chunk\",response,{safe=true})end return net.publicSend(target,\"update_chunk\",response)end function M.publicPacket(packet,distance)local source,body=tostring(packet.from),packet.body or{}if packet.type==\"update_query\"then if body.profile~=profile.id()then return false,\"release profile does not match this installation\"end local offer=providerOffer()local compare=offer and release.compareVersions(offer.version,body.version or\"\")if offer and compare and compare>0 then net.publicSend(source,\"update_offer\",offer)end return elseif packet.type==\"update_offer\"then return upsertOffer(source,body,\"direct\",distance)elseif packet.type==\"update_chunk_request\"then return serveChunk(source,body,false)elseif packet.type==\"update_chunk\"then return acceptChunk(source,body,\"direct\")end end function M.authenticatedPacket(from,peer,packet)local body=packet.body or{}if packet.type==\"update_query\"then if body.profile~=profile.id()then return false,\"release profile does not match this installation\"end local offer=providerOffer()local compare=offer and release.compareVersions(offer.version,body.version or\"\")if offer and compare and compare>0 then return net.reply(packet,\"update_offer\",offer,{safe=true})end elseif packet.type==\"update_offer\"then return upsertOffer(from,body,\"routed\")elseif packet.type==\"update_chunk_request\"then return serveChunk(from,body,true,packet)elseif packet.type==\"update_chunk\"then return acceptChunk(from,body,\"routed\")end end function M.check()local value=loadState()for key in pairs(value.offers)do value.offers[key]=nil end setStatus(\"checking\",\"Looking for newer signed releases\")local cloudOffers,cloudErr=checkCloudManifest()local sent,err=net.publicBroadcast(\"update_query\",{version=version.string,profile=profile.id()})local routed=0 for _,peer in ipairs(net.peers())do if not peer.rekeyRequired then local ok=net.request(peer.id,\"update_query\",{version=version.string,profile=profile.id()},{safe=true})if ok then routed=routed+1 end end end if cloudErr then setStatus(\"warning\",\"Cloud release check failed: \"..tostring(cloudErr):sub(1,120))elseif cloudOffers==0 and not(sent or routed>0)then setStatus(\"idle\",\"No newer signed release is available\")elseif cloudOffers>0 then setStatus(\"offers\",tostring(cloudOffers)..\" signed cloud release offer\"..(cloudOffers==1 and\"\"or\"s\")..\" available\")end record(\"check\",{cloud=cloudOffers,direct=sent==true,routed=routed,cloudError=cloudErr,error=sent and nil or err})save()if cloudErr and not sent and routed==0 then return false,cloudErr end return true,{cloud=cloudOffers,direct=sent==true,routed=routed,cloudError=cloudErr}end function M.download(source)return beginDownload(source)end function M.cancel()local value=loadState()if not value.transfer then return false,\"no update transfer is active\"end record(\"download_cancelled\",{id=value.transfer.source,version=value.transfer.version})value.transfer=nil;removePart();setStatus(\"cancelled\",\"Update download cancelled\");save()return true end function M.clearCache()local value=loadState()if value.transfer then return false,\"cancel the active download first\"end release.clear();cached=nil;value.cache=nil;setStatus(\"idle\",\"Verified release cache cleared\");record(\"cache_cleared\");save()return true end function M.prepareApply()local package,metadata=release.cachedPackage()if not package then return false,metadata or\"no verified signed release is cached\"end local compare=release.compareVersions(package.manifest.version,version.string)if not compare or compare<=0 then return false,\"cached release is not newer than this CeetOS installation\"end if package.manifest.profile~=profile.id()then return false,\"cached release profile does not match this installation\"end local marker={schema=2,state=\"apply\",profile=package.manifest.profile,version=package.manifest.version,digest=package.manifest.digest,keyId=package.manifest.key_id,approvedAt=now()}store.write(release.PENDING_FILE,marker)local value=loadState();setStatus(\"applying\",\"Applying verified release \"..package.manifest.version..\" after reboot\");record(\"apply_approved\",{version=package.manifest.version,digest=package.manifest.digest:sub(1,16),keyId=package.manifest.key_id});save()return true,{version=package.manifest.version,fingerprint=package.manifest.digest:sub(1,16),keyId=package.manifest.key_id}end function M.recover()local marker=store.read(release.PENDING_FILE,nil)if type(marker)~=\"table\"or marker.state~=\"verify\"then return end local value=loadState()if marker.version==version.string and(marker.profile==nil or marker.profile==profile.id())then if fs.exists(release.PENDING_FILE)then fs.delete(release.PENDING_FILE)end setStatus(\"applied\",\"Verified release \"..version.string..\" is now active\")record(\"apply_verified\",{version=version.string})else setStatus(\"error\",\"Update installed but running version did not match \"..tostring(marker.version))record(\"apply_version_mismatch\",{expected=marker.version,actual=version.string})end save()end function M.tick()local value,timestamp=loadState(),now()local offer=providerOffer()if offer and timestamp-lastBeacon>=BEACON_INTERVAL then net.publicBroadcast(\"update_offer\",offer)lastBeacon=timestamp end local transfer=value.transfer if transfer and transfer.awaiting and timestamp-(transfer.requestedAt or timestamp)>=REQUEST_TIMEOUT then transfer.awaiting,transfer.retries=false,(transfer.retries or 0)+1 if transfer.retries>REQUEST_LIMIT then record(\"download_timeout\",{id=transfer.source,version=transfer.version})value.transfer=nil;removePart();setStatus(\"error\",\"Update source timed out\");save()else local sent,err=transferRequest(transfer)if not sent then value.transfer=nil;removePart();setStatus(\"error\",err);record(\"download_failed\",{id=transfer.source,error=err});save()end end end end function M.status()local value=loadState()return{profile=profile.id(),version=version.string,status=value.status,message=value.message,revision=value.revision,offers=offers(),transfer=value.transfer,cache=value.cache,history=value.history,cacheRoot=release.CACHE_ROOT,maxPackageBytes=release.MAX_PACKAGE_BYTES,}end return M",
  ["ceetos/lib/mesh_crypto.lua"] = "local password=require(\"ceetos.lib.password\")local M={}local band,bor,bxor=bit32.band,bit32.bor,bit32.bxor local lshift,rshift=bit32.lshift,bit32.rshift local MOD32,LIMB=4294967296,67108864 local function add32(...)local n=0 for i=1,select(\"#\",...)do n=(n+(select(i,...)or 0))%MOD32 end return n end local function rotl(v,bits)return bor(lshift(v,bits),rshift(v,32-bits))end local function le32(data,index)local a,b,c,d=data:byte(index,index+3)return(a or 0)+(b or 0)*256+(c or 0)*65536+(d or 0)*16777216 end local function put32(value)value=value%MOD32 return string.char(value%256,math.floor(value/256)%256,math.floor(value/65536)%256,math.floor(value/16777216)%256)end local function le64(value)value=math.max(0,math.floor(tonumber(value)or 0))local low,high=value%MOD32,math.floor(value/MOD32)%MOD32 return put32(low)..put32(high)end local function hexToRaw(value)if type(value)~=\"string\"or#value%2~=0 or value:find(\"[^%x]\")then return nil end return(value:gsub(\"..\",function(pair)return string.char(tonumber(pair,16))end))end local function rawToHex(value)return(value:gsub(\".\",function(byte)return string.format(\"%02x\",byte:byte())end))end local function xorBytes(left,right)local out={}for i=1,#left do out[i]=string.char(bxor(left:byte(i),right:byte(i)))end return table.concat(out)end local function quarter(x,a,b,c,d)x[a]=add32(x[a],x[b]);x[d]=rotl(bxor(x[d],x[a]),16)x[c]=add32(x[c],x[d]);x[b]=rotl(bxor(x[b],x[c]),12)x[a]=add32(x[a],x[b]);x[d]=rotl(bxor(x[d],x[a]),8)x[c]=add32(x[c],x[d]);x[b]=rotl(bxor(x[b],x[c]),7)end local function chachaBlock(key,counter,nonce)local state={0x61707865,0x3320646e,0x79622d32,0x6b206574}for i=1,8 do state[4+i]=le32(key,(i-1)*4+1)end state[13],state[14],state[15],state[16]=counter%MOD32,le32(nonce,1),le32(nonce,5),le32(nonce,9)local x={}for i=1,16 do x[i]=state[i]end for _=1,10 do quarter(x,1,5,9,13);quarter(x,2,6,10,14);quarter(x,3,7,11,15);quarter(x,4,8,12,16)quarter(x,1,6,11,16);quarter(x,2,7,12,13);quarter(x,3,8,9,14);quarter(x,4,5,10,15)end local out={}for i=1,16 do out[i]=put32(add32(x[i],state[i]))end return table.concat(out)end local function chachaXor(key,nonce,counter,plaintext)local out,position={},1 while position<=#plaintext do local block=chachaBlock(key,counter,nonce)local part=plaintext:sub(position,position+63)out[#out+1]=xorBytes(part,block:sub(1,#part))position,counter=position+#part,(counter+1)%MOD32 end return table.concat(out)end local function poly1305(message,key)local function zero(length)local out={};for i=1,length do out[i]=0 end;return out end local function normalise(value)local carry=0 for i=1,#value do local n=(value[i]or 0)+carry value[i],carry=n%256,math.floor(n/256)end while carry>0 do value[#value+1],carry=carry%256,math.floor(carry/256)end return value end local function add(left,right)local out=zero(math.max(#left,#right)+1)for i=1,#left do out[i]=out[i]+left[i]end for i=1,#right do out[i]=out[i]+right[i]end return normalise(out)end local function multiply(left,right)local out=zero(#left+#right+1)for i=1,#left do for j=1,#right do out[i+j-1]=out[i+j-1]+left[i]*right[j]end end return normalise(out)end local function high130(value)local out={}for i=1,#value-16 do local low=value[i+16]or 0 local high=value[i+17]or 0 out[i]=math.floor(low/4)+(high%4)*64 end return normalise(out)end local function hasHigh(value)if#value>17 then for i=18,#value do if value[i]~=0 then return true end end end return(value[17]or 0)>=4 end local function reduce(value)while hasHigh(value)do local low,high=zero(17),high130(value)for i=1,17 do low[i]=value[i]or 0 end low[17]=low[17]%4 for i=1,#high do high[i]=high[i]*5 end value=add(low,high)end local prime={251}for i=2,16 do prime[i]=255 end prime[17]=3 local greater=false for i=17,1,-1 do if(value[i]or 0)~=prime[i]then greater=(value[i]or 0)>prime[i];break end end if greater then local borrow=0 for i=1,17 do local n=(value[i]or 0)-prime[i]-borrow if n<0 then n,borrow=n+256,1 else borrow=0 end value[i]=n end end return value end local r,h=zero(17),zero(17)for i=1,16 do r[i]=key:byte(i)end r[4],r[8],r[12],r[16]=band(r[4],15),band(r[8],15),band(r[12],15),band(r[16],15)r[5],r[9],r[13]=band(r[5],252),band(r[9],252),band(r[13],252)for at=1,#message,16 do local part,n=message:sub(at,at+15),zero(17)for i=1,#part do n[i]=part:byte(i)end n[#part+1]=1 h=reduce(multiply(add(h,n),r))end local pad,out,carry={},{},0 for i=1,16 do pad[i]=key:byte(i+16)end for i=1,16 do local n=(h[i]or 0)+pad[i]+carry out[i],carry=n%256,math.floor(n/256)end return string.char(table.unpack(out))end local function padded(value)return value..string.rep(\"\\0\",(16-(#value%16))%16)end local function derive(linkKey)local raw=hexToRaw(password.hmacSha256(linkKey,\"ceetos/mesh/aead-key/v1\")or\"\")return raw end function M.nonce(linkKey,counter,context)local raw=hexToRaw(password.hmacSha256(linkKey,\"ceetos/mesh/aead-nonce/v1|\"..tostring(counter)..\"|\"..tostring(context or\"\"))or\"\")return raw and raw:sub(1,12)or nil end function M.seal(linkKey,nonce,aad,plaintext)if type(linkKey)~=\"string\"or type(nonce)~=\"string\"or#nonce~=12 or type(aad)~=\"string\"or type(plaintext)~=\"string\"then return nil,\"invalid mesh envelope input\"end local key=derive(linkKey);if not key or#key~=32 then return nil,\"could not derive mesh envelope key\"end local polyKey=chachaBlock(key,0,nonce):sub(1,32)local ciphertext=chachaXor(key,nonce,1,plaintext)local tag=poly1305(padded(aad)..padded(ciphertext)..le64(#aad)..le64(#ciphertext),polyKey)return{nonce=rawToHex(nonce),ciphertext=rawToHex(ciphertext),tag=rawToHex(tag)}end function M.open(linkKey,envelope,aad)if type(linkKey)~=\"string\"or type(envelope)~=\"table\"or type(aad)~=\"string\"then return nil,\"invalid mesh envelope\"end local nonce,ciphertext,tag=hexToRaw(envelope.nonce or\"\"),hexToRaw(envelope.ciphertext or\"\"),hexToRaw(envelope.tag or\"\")if not nonce or#nonce~=12 or not ciphertext or not tag or#tag~=16 then return nil,\"invalid mesh envelope encoding\"end local key=derive(linkKey);if not key or#key~=32 then return nil,\"could not derive mesh envelope key\"end local polyKey=chachaBlock(key,0,nonce):sub(1,32)local expected=rawToHex(poly1305(padded(aad)..padded(ciphertext)..le64(#aad)..le64(#ciphertext),polyKey))if not password.constantTimeEqual(expected,envelope.tag)then return nil,\"mesh envelope authentication failed\"end return chachaXor(key,nonce,1,ciphertext)end function M.selfTest()local key=hexToRaw(\"85d6be7857556d337f4452fe42d506a80103808afb0db2fd4abff6af4149f51b\")local tag=poly1305(\"Cryptographic Forum Research Group\",key)return rawToHex(tag)==\"a8061dc1305136c6c22b8baf0c0127a9\"end return M",
  ["ceetos/lib/audit.lua"] = "local store=require(\"ceetos.lib.store\")local M={}local PATH=\"/ceetos/data/audit.log\"M.LIMITS={maxEntries=250,maxBytes=64*1024}function M.log(actor,action,detail)return store.append(PATH,{ts=os.epoch(\"utc\"),actor=actor or\"system\",action=action,detail=detail,},M.LIMITS)end function M.recent(limit)limit=math.max(1,math.min(50,tonumber(limit)or 10))local raw=store.readAppend(PATH)local result={}for line in(raw..\"\\n\"):gmatch(\"(.-)\\n\")do if line~=\"\"then local entry=textutils.unserialise(line)if entry then result[#result+1]=entry if#result>limit then table.remove(result,1)end end end end return result end return M",
  ["ceetos/lib/net.lua"] = "local store=require(\"ceetos.lib.store\")local audit=require(\"ceetos.lib.audit\")local password=require(\"ceetos.lib.password\")local meshCrypto=require(\"ceetos.lib.mesh_crypto\")local M={handler=nil,publicHandler=nil}local PATH=\"/ceetos/data/network.lua\"local SECURITY_PATH=\"/ceetos/data/network-security.lua\"local SEEN_PATH=\"/ceetos/data/seen-peers.lua\"local CHANNEL,PROTOCOL=45731,\"ceetos/2\"local PUBLIC_UPDATE_PROTOCOL=\"ceetos/update/1\"local PUBLIC_UPDATE_TYPES={update_query=true,update_offer=true,update_chunk_request=true,update_chunk=true,}local DISCOVERY_CHANNEL=CHANNEL local DISCOVERY_TTL,ROUTE_TTL,PACKET_TTL=120000,120000,8 local DISCOVERY_INTERVAL,PAIR_RETRY,ROUTE_INTERVAL=2000,2000,15000 local MESH_BEACON_INTERVAL,MESH_FULL_INTERVAL=15000,30000 local PROBE_INTERVAL,PROBE_DEGRADED,PROBE_OFFLINE,PROBE_RECOVERY=5000,3,6,10000 local ROUTE_CANDIDATE_LIMIT,ROUTE_BUCKET_LIMIT=4,96 local SAFE_READ_WINDOW,SAFE_READ_LIMIT=1000,16 local MAX_PACKET_STRING,MAX_PACKET_TABLE,MAX_PACKET_DEPTH=8192,128,6 local COUNTER_RESERVATION,MAX_RX_EPOCHS,MAX_REVERSE_ROUTES=64,3,128 local routes,discovered,confirmations,seenPackets,reverseRoutes={},{},{},{},{}local routeSequence,lastRouteAdvertisement,routesDirty=0,0,false local discovery,lastDiscovery=nil,{state=\"inactive\"}local security={tx={},rx={}}local autoEdges,linkHealth,meshOffers,meshSeen,advertisedRoutes,meshEnrollmentSends={},{},{},{},{},{}local lastMeshBeacon,lastMeshFull,meshDirty=0,0,false local transport={modem=false,wireless=false,name=nil,channels={},lastTransmit=nil,lastReceive=nil,lastDistance=nil,lastError=nil,rejected=0,}local traces={discovery={},routing={},transport={}}local TRACE_LIMIT=48 local MESH_STATE_LIMIT=128 local rejectPacket local function now()return os.epoch(\"utc\")end local function id()return tostring(os.getComputerID())end local function label()return os.getComputerLabel()or(\"Computer \"..id())end local function isBroadcast(value)return tostring(value)==\"0\"end local function isForUs(value)return tostring(value)==id()end local function copy(value,depth)if type(value)~=\"table\"then return value end if(depth or 0)>MAX_PACKET_DEPTH then return nil end local out={}for k,v in pairs(value)do out[k]=copy(v,(depth or 0)+1)end return out end local function trace(kind,phase,fields)local bucket=traces[kind]or traces.transport local row={time=now(),phase=phase}for key,value in pairs(fields or{})do if key~=\"phrase\"and key~=\"proof\"and key~=\"key\"and key~=\"secret\"and key~=\"mac\"and key~=\"packet\"and key~=\"tag\"then row[key]=value end end bucket[#bucket+1]=row while#bucket>TRACE_LIMIT do table.remove(bucket,1)end end local function read(path,fallback)if store.invalidate then store.invalidate(path)end return store.read(path,fallback)end local function config()local value=read(PATH,{peers={},channel=CHANNEL})value.peers=type(value.peers)==\"table\"and value.peers or{}value.channel=tonumber(value.channel)or CHANNEL return value end local function save(value)local ok,err=store.write(PATH,value)if ok==false then error(err or\"could not save network configuration\",0)end end local function migrateV1Links()local value,changed=config(),false for _,peer in pairs(value.peers)do if peer.protocol~=2 or peer.rekeyRequired or type(peer.key)~=\"string\"or#peer.key<32 then peer.protocol,peer.rekeyRequired,peer.key=1,true,nil peer.secret=nil changed=true end end if changed then save(value)end return value end local function activePeer(value,peerId)local peer=value.peers[tostring(peerId)]if peer and peer.protocol==2 and peer.rekeyRequired~=true and type(peer.key)==\"string\"and#peer.key>=32 then return peer end return nil end local function activeLink(value,peerId)local manual=activePeer(value,peerId)if manual then return manual,\"direct\"end local edge=autoEdges[tostring(peerId)]if edge and type(edge.key)==\"string\"and#edge.key>=32 and(edge.expires or 0)>now()then return edge,\"mesh\"end return nil end local function healthFor(peerId)peerId=tostring(peerId)local state=linkHealth[peerId]if not state then state={state=\"healthy\",successes=0,misses=0,lastAuthenticated=now(),stableSince=now(),inFlight=0}linkHealth[peerId]=state end return state end local function linkState(peerId)return healthFor(peerId).state or\"healthy\"end local function currentInFlight(state,timestamp)state.inFlightUntil=type(state.inFlightUntil)==\"table\"and state.inFlightUntil or{}local kept={}for _,expires in ipairs(state.inFlightUntil)do if expires>timestamp then kept[#kept+1]=expires end end state.inFlightUntil,state.inFlight=kept,#kept return state.inFlight end local function markInFlight(state)local timestamp=now()currentInFlight(state,timestamp)state.inFlightUntil[#state.inFlightUntil+1]=timestamp+SAFE_READ_WINDOW table.sort(state.inFlightUntil)while#state.inFlightUntil>SAFE_READ_LIMIT do table.remove(state.inFlightUntil,1)end state.inFlight=#state.inFlightUntil end local function linkUsable(value,peerId,allowDegraded)if not activeLink(value,peerId)then return false end local state=linkState(peerId)return state==\"healthy\"or(allowDegraded and state==\"degraded\")end local function touchLink(peerId,distance,source)local state,timestamp=healthFor(peerId),now()state.lastAuthenticated,state.lastDistance,state.lastSource=timestamp,distance,source or\"traffic\"state.misses,state.awaiting,state.probeToken=0,false,nil state.loss=math.max(0,(state.loss or 0)*0.5)if state.state~=\"healthy\"then state.successes=(state.successes or 0)+1 if state.successes>=2 then state.state,state.stableSince,state.recoveredAt=\"healthy\",timestamp,timestamp routesDirty=true trace(\"routing\",\"link_recovered\",{peer=peerId,source=source})end else state.successes=math.min(2,(state.successes or 0)+1)end end local function allDirectLinks(value)local out,seen={},{}for peerId in pairs(value.peers)do if activePeer(value,peerId)then out[#out+1],seen[peerId]=tostring(peerId),true end end for peerId,edge in pairs(autoEdges)do if not seen[peerId]and edge.expires>now()then out[#out+1]=tostring(peerId)end end table.sort(out,function(a,b)return tonumber(a)<tonumber(b)end)return out end local function remember(peer,peerLabel,extra)local value=read(SEEN_PATH,{})local old=value[tostring(peer)]or{}old.label,old.seen=peerLabel or old.label or(\"Computer \"..tostring(peer)),now()if extra then for key,item in pairs(extra)do if key~=\"tag\"and key~=\"proof\"then old[key]=item end end end value[tostring(peer)]=old store.write(SEEN_PATH,value)end local function modem(requireWireless)local candidates,used={},{}local sides=rs and rs.getSides and rs.getSides()or{}for _,name in ipairs(sides)do if peripheral.getType(name)==\"modem\"and not used[name]then candidates[#candidates+1],used[name]=name,true end end if peripheral.getNames then for _,name in ipairs(peripheral.getNames())do if peripheral.getType(name)==\"modem\"and not used[name]then candidates[#candidates+1],used[name]=name,true end end end local fallback for _,name in ipairs(candidates)do local wrapped=peripheral.wrap(name)if wrapped then fallback=fallback or wrapped local ok,wireless=pcall(function()return not wrapped.isWireless or wrapped.isWireless()end)if ok and wireless then return wrapped end end end return requireWireless and nil or fallback end local function modems()local out,seen={},{}local function add(name)if not seen[name]and peripheral.getType(name)==\"modem\"then local wrapped=peripheral.wrap(name)if wrapped then out[#out+1],seen[name]={name=name,modem=wrapped},true end end end for _,name in ipairs(rs and rs.getSides and rs.getSides()or{})do add(name)end for _,name in ipairs(peripheral.getNames and peripheral.getNames()or{})do add(name)end return out end local function wirelessModems()local out={}for _,item in ipairs(modems())do local ok,wireless=pcall(function()return not item.modem.isWireless or item.modem.isWireless()end)if ok and wireless then out[#out+1]=item end end return out end local function openChannels(value)local channels={value.channel or CHANNEL}if channels[1]~=DISCOVERY_CHANNEL then channels[#channels+1]=DISCOVERY_CHANNEL end transport.channels=channels local all=modems()if#all==0 then transport.lastError=\"no modem attached\";trace(\"transport\",\"modem_missing\");return channels end for _,item in ipairs(all)do for _,channel in ipairs(channels)do local ok,err=pcall(item.modem.open,channel)if not ok then transport.lastError=tostring(err)trace(\"transport\",\"channel_open_failed\",{channel=channel,error=transport.lastError,modem=item.name})end end end return channels end local function canonical(value,depth)depth=depth or 0 local kind=type(value)if kind==\"nil\"then return\"n\"end if kind==\"boolean\"then return value and\"b1\"or\"b0\"end if kind==\"number\"then if value~=value or value==math.huge or value==-math.huge then return nil,\"invalid numeric packet value\"end return\"d\"..string.format(\"%.17g\",value)..\";\"end if kind==\"string\"then if#value>MAX_PACKET_STRING then return nil,\"packet string exceeds limit\"end return\"s\"..tostring(#value)..\":\"..value end if kind~=\"table\"then return nil,\"unsupported packet value\"end if depth>=MAX_PACKET_DEPTH then return nil,\"packet nesting exceeds limit\"end local entries={}for key,item in pairs(value)do if#entries>=MAX_PACKET_TABLE then return nil,\"packet table exceeds limit\"end local encodedKey,keyErr=canonical(key,depth+1);if not encodedKey then return nil,keyErr end local encodedValue,valueErr=canonical(item,depth+1);if not encodedValue then return nil,valueErr end entries[#entries+1]=encodedKey..\"=\"..encodedValue end table.sort(entries)return\"t\"..tostring(#entries)..\"{\"..table.concat(entries,\",\")..\"}\"end local function packetMaterial(packet)return canonical({protocol=packet.protocol,type=packet.type,from=packet.from,to=packet.to,origin=packet.origin,destination=packet.destination,ttl=packet.ttl,request_id=packet.request_id,timestamp=packet.timestamp,reply_to=packet.reply_to,auth=packet.auth and{epoch=packet.auth.epoch,counter=packet.auth.counter}or nil,confidential=packet.confidential==true,body=packet.body,})end local function confidentialAad(packet)return table.concat({\"ceetos/confidential/v1\",tostring(packet.type),tostring(packet.origin),tostring(packet.destination),tostring(packet.request_id)},\"|\")end local function sealBody(peer,packet)local encoded=textutils.serialise(packet.body or{},{compact=true})if#encoded>6144 then return nil,\"confidential payload exceeds limit\"end local nonce=meshCrypto.nonce(peer.key,password.newSalt(\"confidential:\"..tostring(packet.request_id)),confidentialAad(packet))if not nonce then return nil,\"could not create confidential nonce\"end local envelope,err=meshCrypto.seal(peer.key,nonce,confidentialAad(packet),encoded)if not envelope then return nil,err end return{envelope=envelope}end local function openBody(peer,packet)if type(packet.body)~=\"table\"or type(packet.body.envelope)~=\"table\"then return nil,\"malformed confidential envelope\"end local decoded,err=meshCrypto.open(peer.key,packet.body.envelope,confidentialAad(packet))if not decoded or#decoded>6144 then return nil,err or\"invalid confidential payload\"end local ok,value=pcall(textutils.unserialise,decoded)if not ok or type(value)~=\"table\"then return nil,\"invalid confidential payload\"end return value end local function loadSecurity()security=read(SECURITY_PATH,{tx={},rx={}})security.tx=type(security.tx)==\"table\"and security.tx or{}security.rx=type(security.rx)==\"table\"and security.rx or{}end local function saveSecurity()local ok,err=store.write(SECURITY_PATH,security)if ok==false then error(err or\"could not persist peer replay state\",0)end end local function counter(peerId)local key=tostring(peerId)local tx=security.tx[key]if not tx then tx={epoch=password.newSalt(\"peer-tx:\"..key),reserved=0};security.tx[key]=tx end tx.next=tonumber(tx.next)or((tonumber(tx.reserved)or 0)+1)if tx.next>(tonumber(tx.reserved)or 0)then tx.reserved=tx.next+COUNTER_RESERVATION-1 saveSecurity()end local value=tx.next;tx.next=value+1 return tx.epoch,value end local function verifyReplay(from,auth)if type(auth)~=\"table\"or type(auth.epoch)~=\"string\"or#auth.epoch<16 or#auth.epoch>128 then return false,\"invalid packet epoch\"end local sequence=tonumber(auth.counter)if not sequence or sequence<1 or sequence%1~=0 then return false,\"invalid packet counter\"end local key=tostring(from)local row=security.rx[key]or{epochs={}}row.epochs=type(row.epochs)==\"table\"and row.epochs or{}local old=tonumber(row.epochs[auth.epoch])if old and sequence<=old then return false,\"replayed packet counter\"end row.epochs[auth.epoch]=sequence local order={}for epoch,max in pairs(row.epochs)do order[#order+1]={epoch=epoch,max=tonumber(max)or 0}end table.sort(order,function(a,b)return a.max>b.max end)while#order>MAX_RX_EPOCHS do row.epochs[table.remove(order).epoch]=nil end security.rx[key]=row saveSecurity()return true end local function newRequestId()return id()..\":\"..password.newSalt(\"peer-request\")end local function sign(peerId,peer,packet)local epoch,sequence=counter(peerId)packet.auth={epoch=epoch,counter=sequence}local material,err=packetMaterial(packet)if not material then return false,err end local mac,macErr=password.hmacSha256(peer.key,material)if not mac then return false,macErr end packet.auth.mac=mac return true end local function verifyPacket(packet,value)if type(packet)~=\"table\"then return false,\"packet is not a table\"end if packet.protocol~=PROTOCOL then return false,packet.protocol==\"ceetos/1\"and\"v1 packet rejected; rekey required\"or\"invalid packet protocol\"end if type(packet.type)~=\"string\"or#packet.type==0 or#packet.type>64 then return false,\"invalid packet type\"end if type(packet.from)~=\"string\"and type(packet.from)~=\"number\"then return false,\"invalid packet sender\"end local from=tostring(packet.from)local peer=activeLink(value,from)if not peer then return false,\"sender is not an active direct or mesh peer\"end if not isForUs(packet.to)then return false,\"packet addressed to another hop\"end if type(packet.origin)~=\"string\"and type(packet.origin)~=\"number\"then return false,\"invalid packet origin\"end if type(packet.destination)~=\"string\"and type(packet.destination)~=\"number\"then return false,\"invalid packet destination\"end if type(packet.request_id)~=\"string\"or#packet.request_id==0 or#packet.request_id>128 then return false,\"invalid packet request ID\"end if packet.reply_to~=nil and(type(packet.reply_to)~=\"string\"or#packet.reply_to==0 or#packet.reply_to>128)then return false,\"invalid reply correlation ID\"end local ttl=tonumber(packet.ttl)if not ttl or ttl%1~=0 or ttl<1 or ttl>PACKET_TTL then return false,\"invalid packet TTL\"end local timestamp=tonumber(packet.timestamp)if not timestamp or math.abs(now()-timestamp)>ROUTE_TTL then return false,\"stale packet timestamp\"end if type(packet.auth)~=\"table\"or type(packet.auth.mac)~=\"string\"or#packet.auth.mac~=64 then return false,\"missing packet MAC\"end local receivedMac=packet.auth.mac packet.auth.mac=nil local material,materialErr=packetMaterial(packet)packet.auth.mac=receivedMac if not material then return false,materialErr end local expected,macErr=password.hmacSha256(peer.key,material)if not expected or not password.constantTimeEqual(expected,receivedMac)then return false,macErr or\"invalid packet MAC\"end local replayOk,replayErr=verifyReplay(from,packet.auth)if not replayOk then return false,replayErr end return true,peer end local function routeBucket(targetId)local bucket=routes[tostring(targetId)]if bucket and bucket.next then bucket={candidates={{next=tostring(bucket.next),hops=tonumber(bucket.hops)or PACKET_TTL,expires=tonumber(bucket.expires)or 0,label=bucket.label,mode=bucket.mode,masterId=bucket.masterId,legacy=true,loss=1,}},primary=tostring(bucket.next),changedAt=now(),reason=\"legacy route\"}routes[tostring(targetId)]=bucket end if not bucket then bucket={candidates={},changedAt=now(),reason=\"new\"}routes[tostring(targetId)]=bucket end bucket.candidates=type(bucket.candidates)==\"table\"and bucket.candidates or{}return bucket end local function candidateHealth(candidate)local state=healthFor(candidate.next)local rank=state.state==\"healthy\"and 0 or(state.state==\"degraded\"and 1 or 2)return rank,state end local function directCandidate(value,targetId)local link,kind=activeLink(value,targetId)if link then return{next=targetId,hops=1,expires=now()+ROUTE_TTL,kind=kind,direct=true,label=link.label,mode=link.mode,masterId=link.masterId}end end local function validCandidates(targetId,value)local timestamp,out,seen=now(),{},{}local direct=directCandidate(value,targetId)if direct then out[#out+1],seen[direct.next..\":\"..direct.kind]=direct,true end local bucket=routes[tostring(targetId)]if bucket then for _,candidate in ipairs(routeBucket(targetId).candidates)do local key=tostring(candidate.next)..\":\"..tostring(candidate.kind or\"route\")if not seen[key]and candidate.expires>timestamp and candidate.hops>=1 and candidate.hops<=PACKET_TTL and activeLink(value,candidate.next)then out[#out+1],seen[key]=candidate,true end end end return out end local function compareCandidates(a,b)local ar,ah=candidateHealth(a)local br,bh=candidateHealth(b)if ar~=br then return ar<br end if(a.hops or PACKET_TTL)~=(b.hops or PACKET_TTL)then return(a.hops or PACKET_TTL)<(b.hops or PACKET_TTL)end if(ah.loss or 0)~=(bh.loss or 0)then return(ah.loss or 0)<(bh.loss or 0)end if(ah.rtt or 0)~=(bh.rtt or 0)then return(ah.rtt or 0)<(bh.rtt or 0)end return tostring(a.next)<tostring(b.next)end local function primaryCandidate(targetId,value,safe)local candidates=validCandidates(targetId,value)if#candidates==0 then return nil end table.sort(candidates,compareCandidates)local target,bucket,selected=tostring(targetId),routeBucket(targetId),candidates[1]local existing for _,item in ipairs(candidates)do if tostring(item.next)==tostring(bucket.primary)then existing=item;break end end if existing then local oldRank,newRank=candidateHealth(existing),candidateHealth(selected)if oldRank<newRank then selected=existing elseif oldRank==newRank and oldRank==0 and(selected.hops or 99)<(existing.hops or 99)then local health=healthFor(selected.next)if(health.successes or 0)<2 or(health.recoveredAt and now()-(health.stableSince or now())<PROBE_RECOVERY)then selected=existing end end end if safe then local rank,_,choices=candidateHealth(selected),nil,{}for _,item in ipairs(candidates)do local itemRank=candidateHealth(item)if itemRank==rank and item.hops==selected.hops then choices[#choices+1]=item end end if#choices>1 then table.sort(choices,function(a,b)local ah,bh=healthFor(a.next),healthFor(b.next)local aLoad,bLoad=currentInFlight(ah,now()),currentInFlight(bh,now())if aLoad~=bLoad then return aLoad<bLoad end return tostring(a.next)<tostring(b.next)end)selected=choices[1]end end if bucket.primary~=tostring(selected.next)then bucket.primary,bucket.changedAt,bucket.reason=tostring(selected.next),now(),existing and\"health/hop selection\"or\"initial selection\"trace(\"routing\",\"route_selected\",{destination=target,next=selected.next,hops=selected.hops,reason=bucket.reason})end return selected end local function nextHop(target,safe)local candidate=primaryCandidate(target,config(),safe)if candidate then local health=healthFor(candidate.next)if safe then markInFlight(health)end health.lastSelected=now()return candidate.next,candidate end routes[tostring(target)]=nil end local function transmit(items,channel,packet)if#items==0 then return false,\"no compatible modem attached\"end local sent,lastError=false,nil for _,item in ipairs(items)do local ok,err=pcall(item.modem.transmit,channel,channel,packet)if ok then sent=true else lastError=tostring(err)end end if not sent then transport.lastError=lastError or\"modem transmit failed\"end return sent,transport.lastError end local function send(target,input,forcedHop)local hop=forcedHop or nextHop(target,input.routeSafe==true and input.balanceSafe==true)if not hop then return false,\"peer is unreachable or requires rekey\"end local value,peer=config(),activeLink(config(),hop)if not peer then return false,\"direct route is unavailable\"end local packet=copy(input)packet.auth,packet.protocol,packet.from,packet.to=nil,PROTOCOL,id(),hop packet.origin,packet.destination=tostring(packet.origin or id()),tostring(packet.destination or target)packet.ttl=math.floor(tonumber(packet.ttl)or PACKET_TTL)packet.timestamp=now()if packet.ttl<1 or packet.ttl>PACKET_TTL then return false,\"invalid packet TTL\"end if type(packet.request_id)~=\"string\"or#packet.request_id==0 then packet.request_id=newRequestId()end if packet.confidential==true then local sealed,sealErr=sealBody(peer,packet)if not sealed then return false,sealErr end packet.body=sealed end local signed,signErr=sign(hop,peer,packet)if not signed then return false,signErr end openChannels(value)local links=wirelessModems()if#links==0 then return false,\"no wireless modem attached\"end local sent,err=transmit(links,value.channel or CHANNEL,packet)if not sent then trace(\"transport\",\"transmit_failed\",{type=packet.type,to=hop,error=err});return false,err end transport.lastTransmit,transport.lastError=now(),nil healthFor(hop).lastTransmit=now()trace(\"routing\",\"packet_sent\",{type=packet.type,to=hop,destination=packet.destination,links=#links})return true end local function rememberReverse(packet,previousHop)if type(packet)~=\"table\"or type(packet.request_id)~=\"string\"or#packet.request_id==0 then return false end local requestId,origin=packet.request_id,tostring(packet.origin)local existing=reverseRoutes[requestId]if existing and(existing.previous~=tostring(previousHop)or existing.origin~=origin)then return false,\"reverse route collision\"end reverseRoutes[requestId]={previous=tostring(previousHop),origin=origin,expires=now()+ROUTE_TTL}local entries={}for key,route in pairs(reverseRoutes)do entries[#entries+1]={id=key,expires=route.expires or 0}end table.sort(entries,function(a,b)return a.expires<b.expires end)while#entries>MAX_REVERSE_ROUTES do reverseRoutes[table.remove(entries,1).id]=nil end return true end local function broadcast(packet)local links=wirelessModems()if#links==0 then transport.lastError=\"no wireless modem attached\";trace(\"discovery\",\"wireless_missing\");return false,transport.lastError end local out=copy(packet)out.protocol,out.from,out.to=PROTOCOL,id(),0 out.timestamp=now()openChannels(config())local sent,err=transmit(links,DISCOVERY_CHANNEL,out)if not sent then trace(\"discovery\",\"transmit_failed\",{type=out.type,error=err});return false,err end transport.lastTransmit,transport.lastError=now(),nil trace(\"discovery\",out.type==\"discover\"and\"announcement_sent\"or\"discovery_packet_sent\",{type=out.type})return true end local function publicTransmit(target,typeName,body)if not PUBLIC_UPDATE_TYPES[typeName]then return false,\"invalid public update packet type\"end local encoded,encodeErr=canonical(body or{})if not encoded then return false,encodeErr or\"invalid public update body\"end local links=wirelessModems()if#links==0 then transport.lastError=\"no wireless modem attached\";return false,transport.lastError end openChannels(config())local packet={protocol=PUBLIC_UPDATE_PROTOCOL,type=typeName,from=id(),to=tostring(target),timestamp=now(),request_id=newRequestId(),body=body or{},}local sent,err=transmit(links,DISCOVERY_CHANNEL,packet)if not sent then transport.lastError=err or\"public update transmit failed\"trace(\"transport\",\"public_update_transmit_failed\",{type=typeName,to=target,error=transport.lastError})return false,transport.lastError end transport.lastTransmit,transport.lastError=now(),nil trace(\"transport\",\"public_update_sent\",{type=typeName,to=target,bytes=#encoded})return true end function M.publicSend(target,typeName,body)if tostring(target)==\"0\"or tostring(target)==\"\"then return false,\"public update target must be a computer ID\"end return publicTransmit(target,typeName,body)end function M.publicBroadcast(typeName,body)return publicTransmit(\"0\",typeName,body)end local function handshake(target,packet)local links=wirelessModems()if#links==0 then transport.lastError=\"no wireless modem attached\";return false,transport.lastError end local out=copy(packet)out.protocol,out.from,out.to,out.timestamp=PROTOCOL,id(),tostring(target),now()out.destination,out.ttl=tostring(target),1 openChannels(config())local sent,err=transmit(links,config().channel or CHANNEL,out)if not sent then trace(\"discovery\",\"handshake_transmit_failed\",{type=out.type,to=target,error=err});return false,err end transport.lastTransmit=now()trace(\"discovery\",out.type..\"_sent\",{to=target})return true end local function phraseTag(phrase,sessionId,hostId)return password.hmacSha256(phrase,\"ceetos/discovery/v2|\"..sessionId..\"|\"..tostring(hostId))end local function joinProof(phrase,sessionId,hostId,joinerId,nonce)return password.hmacSha256(phrase,\"ceetos/pair/join/v2|\"..sessionId..\"|\"..tostring(hostId)..\"|\"..tostring(joinerId)..\"|\"..nonce)end local function confirmProof(phrase,sessionId,hostId,joinerId,nonce,mode,master)return password.hmacSha256(phrase,\"ceetos/pair/confirm/v2|\"..sessionId..\"|\"..tostring(hostId)..\"|\"..tostring(joinerId)..\"|\"..nonce..\"|\"..tostring(mode)..\"|\"..tostring(master or\"\"))end local function linkKey(phrase,sessionId,hostId,joinerId,nonce)return password.derive(phrase,\"ceetos/link/v2|\"..sessionId..\"|\"..tostring(hostId)..\"|\"..tostring(joinerId)..\"|\"..nonce,64)end local function keyId(key)local value=password.hmacSha256(key,\"ceetos/key-id/v2\")return value and value:sub(1,16)or\"\"end local function activeSession()return discovery and(discovery.state==\"hosting\"or discovery.state==\"searching\"or discovery.state==\"candidate\"or discovery.state==\"confirming\")end local function setLast(state,message)lastDiscovery={state=state,message=message,at=now()}end local function persistPair(peerId,key,metadata,masterId)local value=config()value.peers[tostring(peerId)]={protocol=2,rekeyRequired=false,key=key,keyId=keyId(key),role=\"operator\",mode=metadata.mode or\"peer\",master=tostring(masterId or\"\")==id(),masterId=tostring(masterId or\"\"),label=metadata.label,}save(value)remember(peerId,metadata.label,{mode=metadata.mode,masterId=masterId})routes[tostring(peerId)]=nil routesDirty=true audit.log(\"local\",\"peer.rekeyed\",{peer=peerId,mode=metadata.mode})end local function markRejected(reason)if discovery then discovery=nil end setLast(\"cancelled\",reason)end local function discoveryAnnouncement()if not discovery or discovery.state~=\"hosting\"then return false,\"no active host discovery\"end return broadcast({type=\"discover\",session=discovery.id,tag=discovery.tag,label=discovery.label,mode=discovery.mode,master=discovery.masterSide,expires=discovery.expires,})end local function queueConfirmation(peerId,host)confirmations[host.id]=host local sent,err=handshake(peerId,{type=\"pair_confirm\",session=host.id,nonce=host.joinNonce,proof=host.confirmProof,label=host.label,mode=host.mode,master=host.masterId,})host.lastSent,host.retries=now(),0 if not sent then host.error=err end return sent,err end local function expireState(timestamp)if discovery and discovery.expires<=timestamp then local old=discovery.state discovery=nil setLast(\"expired\",old==\"searching\"and\"no matching discovery announcement received\"or\"discovery session expired\")trace(\"discovery\",\"session_expired\",{previous=old})end end local function boundMap(value,limit,timestamp)local entries={}for key,row in pairs(value)do entries[#entries+1]={key=key,at=type(row)==\"number\"and row or(type(row)==\"table\"and(row.expires or row.time or row.seen or row.lastAuthenticated or 0)or 0)}end table.sort(entries,function(a,b)if a.at~=b.at then return a.at<b.at end return tostring(a.key)<tostring(b.key)end)while#entries>limit do value[table.remove(entries,1).key]=nil end end local function pruneRouteBuckets(timestamp)local value=config()local entries={}for peerId,bucket in pairs(routes)do local latest=tonumber(bucket.changedAt)or 0 for _,candidate in ipairs(type(bucket.candidates)==\"table\"and bucket.candidates or{})do latest=math.max(latest,tonumber(candidate.expires)or 0)end entries[#entries+1]={peer=peerId,latest=latest}end table.sort(entries,function(a,b)if a.latest~=b.latest then return a.latest<b.latest end return tostring(a.peer)<tostring(b.peer)end)while#entries>ROUTE_BUCKET_LIMIT do local old=table.remove(entries,1)routes[old.peer],routesDirty=nil,true trace(\"routing\",\"route_bucket_evicted\",{destination=old.peer})end for peerId,state in pairs(linkHealth)do if not activeLink(value,peerId)and not routes[peerId]then linkHealth[peerId]=nil end end for peerId in pairs(advertisedRoutes)do if not activeLink(value,peerId)then advertisedRoutes[peerId]=nil end end boundMap(meshOffers,MESH_STATE_LIMIT,timestamp)boundMap(meshSeen,MESH_STATE_LIMIT,timestamp)end local function controller(value)value=value or config()if value.controller and tostring(value.controller)~=\"\"then local chosen=tostring(value.controller)if chosen==id()or activeLink(value,chosen)then return chosen end local known=routes[chosen]if known then if known.expires and known.expires>now()then return chosen end if type(known.candidates)==\"table\"then for _,candidate in ipairs(known.candidates)do if(candidate.expires or 0)>now()and activeLink(value,candidate.next)then return chosen end end end end trace(\"routing\",\"controller_unreachable\",{controller=chosen})end local selected=tonumber(id())or 0 for peerId in pairs(value.peers)do if activePeer(value,peerId)then local n=tonumber(peerId);if n and n<selected then selected=n end end end for peerId,route in pairs(routes)do local reachable=route.expires and route.expires>now()if type(route.candidates)==\"table\"then reachable=false for _,candidate in ipairs(route.candidates)do if(candidate.expires or 0)>now()then reachable=true;break end end end if reachable then local n=tonumber(peerId);if n and n<selected then selected=n end end end return tostring(selected)end local function meshConfig(value)value=value or config()local mesh=value.mesh if type(mesh)==\"table\"and type(mesh.id)==\"string\"and#mesh.id>=16 and type(mesh.root)==\"string\"and#mesh.root>=32 and tonumber(mesh.epoch)then return mesh end return nil end local function meshMaterial(packet)return canonical({protocol=packet.protocol,type=packet.type,from=packet.from,to=packet.to,mesh=packet.mesh,epoch=packet.epoch,nonce=packet.nonce,offer=packet.offer,timestamp=packet.timestamp})end local function meshTag(mesh,packet)local material=meshMaterial(packet)return material and password.hmacSha256(mesh.root,material)or nil end local function meshPacket(typeName,target,fields)local value,mesh=config(),meshConfig()if not mesh then return false,\"mesh enrollment is pending\"end local packet=copy(fields or{})packet.protocol,packet.type,packet.from,packet.to=PROTOCOL,typeName,id(),target and tostring(target)or 0 packet.mesh,packet.epoch,packet.timestamp=mesh.id,mesh.epoch,now()packet.tag=meshTag(mesh,packet)if not packet.tag then return false,\"could not authenticate mesh packet\"end openChannels(value)local links=wirelessModems()if#links==0 then return false,\"no wireless modem attached\"end local sent,err=transmit(links,value.channel or CHANNEL,packet)if sent then trace(\"routing\",typeName..\"_sent\",{to=packet.to,mesh=mesh.id:sub(1,8)})end return sent,err end local function deriveAutoEdge(mesh,peerId,firstNonce,secondNonce)local left,right=tostring(id()),tostring(peerId)if left>right then left,right=right,left end return password.hmacSha256(mesh.root,\"ceetos/mesh-edge/v1|\"..tostring(mesh.epoch)..\"|\"..left..\"|\"..right..\"|\"..tostring(firstNonce)..\"|\"..tostring(secondNonce))end local function ownsMeshOffer(peerId)local ours,theirs=tonumber(id()),tonumber(peerId)if ours and theirs then return ours<theirs end return tostring(id())<tostring(peerId)end local function installAutoEdge(mesh,peerId,firstNonce,secondNonce,peerLabel)peerId=tostring(peerId)local value=config()if activePeer(value,peerId)then return false,\"manual direct link already exists\"end local key=deriveAutoEdge(mesh,peerId,firstNonce,secondNonce)if not key then return false,\"could not derive mesh edge\"end autoEdges[peerId]={key=key,label=peerLabel,mesh=mesh.id,epoch=mesh.epoch,expires=now()+ROUTE_TTL,firstNonce=firstNonce,secondNonce=secondNonce}local state=healthFor(peerId)state.state,state.successes,state.misses,state.lastAuthenticated,state.stableSince=\"healthy\",2,0,now(),now()routesDirty,meshDirty=true,true trace(\"routing\",\"mesh_edge_active\",{peer=peerId,mesh=mesh.id:sub(1,8)})return true end local function meshEnrollmentAad(from,to,meshId,epoch,nonceCounter)return canonical({protocol=PROTOCOL,type=\"mesh_enroll\",from=tostring(from),to=tostring(to),mesh=meshId,epoch=tonumber(epoch),counter=tonumber(nonceCounter)})end local function sendEnrollment(peerId)local value,mesh,peer=config(),meshConfig(),activePeer(config(),peerId)if not mesh or not peer then return false,\"mesh or direct link unavailable\"end local _,nonceCounter=counter(peerId)local aad=meshEnrollmentAad(id(),peerId,mesh.id,mesh.epoch,nonceCounter)local nonce=meshCrypto.nonce(peer.key,nonceCounter,\"mesh-enroll|\"..id()..\"|\"..tostring(peerId))local plaintext=textutils.serialise({id=mesh.id,epoch=mesh.epoch,root=mesh.root},{compact=true})local envelope,err=meshCrypto.seal(peer.key,nonce,aad,plaintext)if not envelope then return false,err end local sent,sendErr=send(peerId,{type=\"mesh_enroll\",body={mesh=mesh.id,epoch=mesh.epoch,counter=nonceCounter,envelope=envelope},request_id=newRequestId()},peerId)if sent then trace(\"routing\",\"mesh_enrollment_sent\",{to=peerId,epoch=mesh.epoch})end return sent,sendErr end local function acceptEnrollment(from,peer,packet)if not activePeer(config(),from)then return rejectPacket(\"mesh enrollment requires a manual direct link\",packet)end local body=packet.body if type(body)~=\"table\"or type(body.mesh)~=\"string\"or type(body.envelope)~=\"table\"or not tonumber(body.epoch)or not tonumber(body.counter)then return rejectPacket(\"malformed_mesh_enrollment\",packet)end local aad=meshEnrollmentAad(from,id(),body.mesh,body.epoch,body.counter)local plaintext,err=meshCrypto.open(peer.key,body.envelope,aad)if not plaintext then return rejectPacket(err or\"mesh enrollment authentication failed\",packet)end local ok,mesh=pcall(textutils.unserialise,plaintext)if not ok or type(mesh)~=\"table\"or mesh.id~=body.mesh or tonumber(mesh.epoch)~=tonumber(body.epoch)or type(mesh.root)~=\"string\"or#mesh.root<32 then return rejectPacket(\"invalid_mesh_enrollment\",packet)end local value,existing=config(),meshConfig()if existing and existing.id==mesh.id and tonumber(existing.epoch)>tonumber(mesh.epoch)then return end value.mesh={id=mesh.id,epoch=tonumber(mesh.epoch),root=mesh.root,enrolledAt=now(),enrolledBy=tostring(from)}save(value)meshDirty,routesDirty=true,true trace(\"routing\",\"mesh_enrolled\",{from=from,mesh=mesh.id:sub(1,8),epoch=mesh.epoch})end local function ensureMeshEnrollment(timestamp)local value,mesh=config(),meshConfig()if not mesh then if(M._meshBootstrapAt or 0)>timestamp or controller(value)~=id()then return end value.mesh={id=password.newSalt(\"mesh-id:\"..id()),root=password.newSalt(\"mesh-root:\"..id()),epoch=1,createdAt=timestamp,controller=id()}save(value);mesh,meshDirty,routesDirty=value.mesh,true,true trace(\"routing\",\"mesh_created\",{mesh=mesh.id:sub(1,8),epoch=mesh.epoch})end for _,peerId in ipairs(allDirectLinks(value))do if activePeer(value,peerId)then local previous=meshEnrollmentSends[peerId]if not previous or previous.epoch~=mesh.epoch or timestamp-previous.at>=MESH_FULL_INTERVAL then local sent=sendEnrollment(peerId)if sent then meshEnrollmentSends[peerId]={epoch=mesh.epoch,at=timestamp}end end end end end local function meshBeacon(timestamp)local mesh=meshConfig()if not mesh or timestamp-lastMeshBeacon<MESH_BEACON_INTERVAL then return end lastMeshBeacon=timestamp meshPacket(\"mesh_beacon\",nil,{nonce=password.newSalt(\"mesh-beacon:\"..id()),label=label()})end local function verifyMeshPacket(packet)local mesh=meshConfig()if not mesh or type(packet)~=\"table\"or packet.protocol~=PROTOCOL or packet.mesh~=mesh.id or tonumber(packet.epoch)~=tonumber(mesh.epoch)then return false,\"mesh membership proof failed\"end if type(packet.from)~=\"string\"and type(packet.from)~=\"number\"then return false,\"invalid mesh sender\"end if type(packet.nonce)~=\"string\"or#packet.nonce<16 or#packet.nonce>128 then return false,\"invalid mesh nonce\"end if math.abs(now()-(tonumber(packet.timestamp)or 0))>ROUTE_TTL then return false,\"stale mesh packet\"end local material,tag=meshMaterial(packet),packet.tag local expected=material and password.hmacSha256(mesh.root,material)if type(tag)~=\"string\"or not expected or not password.constantTimeEqual(expected,tag)then return false,\"invalid mesh packet tag\"end local replay=tostring(packet.from)..\"|\"..tostring(packet.type)..\"|\"..tostring(packet.nonce)..\"|\"..tostring(packet.offer or\"\")if meshSeen[replay]and meshSeen[replay]+ROUTE_TTL>now()then return false,\"replayed mesh packet\"end meshSeen[replay]=now()return true,mesh end local function handleMeshPacket(packet,distance)local valid,meshOrErr=verifyMeshPacket(packet)if not valid then return rejectPacket(meshOrErr,packet,nil,distance)end local mesh,from=meshOrErr,tostring(packet.from)if from==id()then return end if packet.type==\"mesh_beacon\"then remember(from,packet.label,{mesh=mesh.id})if not activePeer(config(),from)and not autoEdges[from]and ownsMeshOffer(from)then local nonce=password.newSalt(\"mesh-offer:\"..from)meshOffers[from]={offer=nonce,expires=now()+DISCOVERY_TTL}meshPacket(\"mesh_edge_offer\",from,{nonce=nonce,label=label()})end return end if not isForUs(packet.to)then return rejectPacket(\"mesh packet addressed to another peer\",packet,nil,distance)end if packet.type==\"mesh_edge_offer\"then if activePeer(config(),from)then return end local response=password.newSalt(\"mesh-accept:\"..from)installAutoEdge(mesh,from,packet.nonce,response,packet.label)return meshPacket(\"mesh_edge_accept\",from,{nonce=response,offer=packet.nonce,label=label()})end if packet.type==\"mesh_edge_accept\"then local offer=meshOffers[from]if not offer or offer.expires<=now()or offer.offer~=packet.offer then return rejectPacket(\"unexpected mesh edge acceptance\",packet,nil,distance)end meshOffers[from]=nil return installAutoEdge(mesh,from,offer.offer,packet.nonce,packet.label)end end local function probeLinks(timestamp)local value=config()for _,peerId in ipairs(allDirectLinks(value))do local health=healthFor(peerId)local interval=health.state==\"offline\"and PROBE_INTERVAL*3 or PROBE_INTERVAL if timestamp-(health.lastAuthenticated or 0)>=interval and timestamp-(health.lastProbe or 0)>=interval then if health.awaiting then health.misses=(health.misses or 0)+1 health.loss=math.min(1,((health.loss or 0)*3+1)/4)local nextState=health.misses>=PROBE_OFFLINE and\"offline\"or(health.misses>=PROBE_DEGRADED and\"degraded\"or health.state)if nextState~=health.state then health.state,health.successes,health.recoveredAt=nextState,0,nil trace(\"routing\",\"link_\"..nextState,{peer=peerId,misses=health.misses})end routesDirty=true end health.awaiting,health.lastProbe,health.probeToken=true,timestamp,password.newSalt(\"mesh-probe:\"..peerId)send(peerId,{type=\"mesh_probe\",body={token=health.probeToken},request_id=newRequestId()},peerId)end end end local function advertisedMembers(value,peerId,timestamp)local members={}for other,manual in pairs(value.peers)do if other~=peerId and activeLink(value,other)and linkState(other)==\"healthy\"then members[other]={label=manual.label,mode=manual.mode,masterId=manual.masterId,hops=1,kind=\"direct\"}end end for other,edge in pairs(autoEdges)do if other~=peerId and edge.expires>timestamp and linkState(other)==\"healthy\"then members[other]={label=edge.label,mode=\"peer\",hops=1,kind=\"mesh\"}end end for other in pairs(routes)do if other~=peerId and not members[other]then local candidate=primaryCandidate(other,value,false)if candidate and candidate.next~=peerId and linkState(candidate.next)==\"healthy\"then members[other]={label=candidate.label,mode=candidate.mode,masterId=candidate.masterId,hops=candidate.hops,kind=candidate.kind or\"route\"}end end end return members end local function sameAdvertisement(left,right)local leftValue,leftErr=canonical(left)local rightValue,rightErr=canonical(right)return leftValue~=nil and rightValue~=nil and not leftErr and not rightErr and leftValue==rightValue end local function advertiseRoutes(force)local timestamp,value=now(),config()if not force and not routesDirty and timestamp-lastRouteAdvertisement<ROUTE_INTERVAL then return end lastRouteAdvertisement,routesDirty=timestamp,false local full=timestamp-lastMeshFull>=MESH_FULL_INTERVAL if full then lastMeshFull=timestamp end for _,peerId in ipairs(allDirectLinks(value))do if linkUsable(value,peerId,false)then local desired,previous=advertisedMembers(value,peerId,timestamp),advertisedRoutes[peerId]or{}local members,withdrawals={},{}if full then members=desired else for target,meta in pairs(desired)do if not sameAdvertisement(meta,previous[target])then members[target]=meta end end for target in pairs(previous)do if not desired[target]then withdrawals[#withdrawals+1]=target end end end table.sort(withdrawals,function(a,b)return tostring(a)<tostring(b)end)if full or next(members)~=nil or#withdrawals>0 then routeSequence=routeSequence+1 local body={sequence=routeSequence,routeVersion=2,full=full,controller=controller(value),members=members,withdrawals=withdrawals}if send(peerId,{type=\"route_advertise\",body=body,routeSafe=true,request_id=newRequestId()})then advertisedRoutes[peerId]=copy(desired)trace(\"routing\",full and\"route_snapshot_sent\"or\"route_delta_sent\",{to=peerId,changes=(full and 0 or#withdrawals)})end end else advertisedRoutes[peerId]=nil end end end function M.start()migrateV1Links()loadSecurity()assert(meshCrypto.selfTest(),\"CeetOS mesh cryptography self-test failed\")openChannels(config())local status=M.transportStatus()trace(\"transport\",status.wireless and\"wireless_modem_detected\"or\"wireless_modem_missing\",{name=status.name})routesDirty,M._meshBootstrapAt=true,now()end function M.transportStatus()local wireless=wirelessModems()transport.modem,transport.wireless=#modems()>0,#wireless>0 transport.name=wireless[1]and wireless[1].name or nil local out=copy(transport)out.wirelessLinks,out.wirelessLinkCount={},#wireless for _,item in ipairs(wireless)do out.wirelessLinks[#out.wirelessLinks+1]=item.name end out.usesAllWirelessLinks,out.protocol=true,2 out.directPeers,out.manualDirectPeers,out.meshPeers,out.rekeyRequiredPeers,out.routedPeers=0,0,0,0,0 out.healthyLinks,out.degradedLinks,out.offlineLinks=0,0,0 local value=config()for peerId,peer in pairs(value.peers)do if activePeer(value,peerId)then out.directPeers,out.manualDirectPeers=out.directPeers+1,out.manualDirectPeers+1 elseif peer.rekeyRequired then out.rekeyRequiredPeers=out.rekeyRequiredPeers+1 end end for peerId,edge in pairs(autoEdges)do if edge.expires>now()then out.meshPeers,out.directPeers=out.meshPeers+1,out.directPeers+1 end end for peerId,health in pairs(linkHealth)do if health.state==\"healthy\"then out.healthyLinks=out.healthyLinks+1 elseif health.state==\"degraded\"then out.degradedLinks=out.degradedLinks+1 elseif health.state==\"offline\"then out.offlineLinks=out.offlineLinks+1 end end for peerId,bucket in pairs(routes)do local usable=primaryCandidate(peerId,value,false)if usable and not value.peers[peerId]and not autoEdges[peerId]then out.routedPeers=out.routedPeers+1 end end local mesh=meshConfig(value)out.mesh=mesh and{id=mesh.id:sub(1,8),epoch=mesh.epoch,enrolled=true}or{enrolled=false}out.health={healthy=out.healthyLinks,degraded=out.degradedLinks,offline=out.offlineLinks}return out end function M.transportTrace(kind)if kind==\"discovery\"or kind==\"routing\"or kind==\"transport\"then return copy(traces[kind])end return{discovery=copy(traces.discovery),routing=copy(traces.routing),transport=copy(traces.transport)}end function M.discovery()expireState(now())return copy(discovery)end function M.discoveryStatus()expireState(now())local candidate=discovery and discovery.candidate and{id=discovery.candidate.from,label=discovery.candidate.label,mode=discovery.candidate.mode,master=discovery.candidate.master,}or nil local session=discovery and{session=discovery.id,state=discovery.state,mode=discovery.mode,master=discovery.masterSide,expires=discovery.expires,retries=discovery.retries or 0,candidate=candidate and copy(candidate)or nil,}or nil local state=session and session.state or(lastDiscovery and lastDiscovery.state or\"inactive\")return{state=state,active=session~=nil,lastState=lastDiscovery and lastDiscovery.state or\"inactive\",lastMessage=lastDiscovery and lastDiscovery.message or nil,session=session,searching=session and session.state==\"searching\"or false,candidate=candidate,discovered=#M.seenPeers(),transport=M.transportStatus(),message=(discovery and discovery.error)or(lastDiscovery and lastDiscovery.message),}end function M.startDiscovery(mode,masterSide,phrase)if activeSession()then return false,\"cancel the active discovery session first\"end local normalized,phraseErr=M.normalizePhrase(phrase)if not normalized then return false,phraseErr end mode=mode==\"master\"and\"master\"or\"peer\"masterSide=masterSide==\"joiner\"and\"joiner\"or\"initiator\"local sessionId=password.newSalt(\"discovery:\"..id())discovery={id=sessionId,state=\"hosting\",phrase=normalized,tag=phraseTag(normalized,sessionId,id()),mode=mode,masterSide=masterSide,label=label(),initiator=id(),expires=now()+DISCOVERY_TTL,retries=0,lastBroadcast=0,}local sent,err=discoveryAnnouncement()if not sent then discovery=nil;setLast(\"cancelled\",err);return false,err end discovery.lastBroadcast=now()setLast(\"hosting\")return true,{state=\"hosting\",session=sessionId,expires=discovery.expires}end function M.joinDiscovery(phrase)if activeSession()then return false,\"cancel the active discovery session first\"end local normalized,phraseErr=M.normalizePhrase(phrase)if not normalized then return false,phraseErr end local candidate for _,item in pairs(discovered)do if item.expires>now()and password.constantTimeEqual(item.tag or\"\",phraseTag(normalized,item.session,item.from))then candidate=item;break end end discovery={state=\"searching\",phrase=normalized,expires=now()+DISCOVERY_TTL,retries=0,lastQuery=0}if candidate then discovery.state,discovery.candidate=\"candidate\",candidate return true,{state=\"candidate\",candidate={id=candidate.from,label=candidate.label,mode=candidate.mode,master=candidate.master}}end local sent,err=broadcast({type=\"discover_query\"})if not sent then discovery=nil;setLast(\"cancelled\",err);return false,err end discovery.lastQuery=now()setLast(\"searching\",\"waiting for matching discovery announcement\")return true,{state=\"searching\"}end function M.confirmDiscovery()if not discovery or discovery.state~=\"candidate\"or not discovery.candidate then return false,\"no discovery candidate is awaiting confirmation\"end local candidate,value=discovery.candidate,config()local existing=value.peers[tostring(candidate.from)]if existing and not existing.rekeyRequired then return false,\"computer is already a network member\"end if routes[tostring(candidate.from)]and not existing then return false,\"computer is already a routed network member\"end local nonce=password.newSalt(\"pair-join:\"..candidate.session)local proof=joinProof(discovery.phrase,candidate.session,candidate.from,id(),nonce)discovery.state,discovery.joinNonce,discovery.joinProof,discovery.lastSent,discovery.retries=\"confirming\",nonce,proof,now(),0 local sent,err=handshake(candidate.from,{type=\"pair_join\",session=candidate.session,nonce=nonce,proof=proof,label=label()})if not sent then discovery.error=err;return false,err end trace(\"discovery\",\"pair_confirmation_requested\",{peer=candidate.from})return true end function M.cancelDiscovery()if discovery and discovery.state==\"hosting\"then broadcast({type=\"discover_cancel\",session=discovery.id})end discovery=nil setLast(\"cancelled\",\"discovery cancelled\")trace(\"discovery\",\"session_cancelled\")return true end function M.normalizePhrase(value)if type(value)~=\"string\"then return nil,\"phrase is required\"end if value:find(\"[%z\\1-\\31\\127]\")then return nil,\"phrase contains control characters\"end value=value:gsub(\"^%s+\",\"\"):gsub(\"%s+$\",\"\")if#value<8 then return nil,\"phrase must be at least 8 characters\"end if#value>128 then return nil,\"phrase must be at most 128 characters\"end return value end function M.tick()local timestamp=now()expireState(timestamp)if discovery then if discovery.state==\"hosting\"and timestamp-(discovery.lastBroadcast or 0)>=math.min(30000,DISCOVERY_INTERVAL*(2^math.min(discovery.retries or 0,4)))then local sent,err=discoveryAnnouncement()discovery.lastBroadcast=timestamp discovery.retries=(discovery.retries or 0)+1 if not sent then discovery.error=err end elseif discovery.state==\"searching\"and timestamp-(discovery.lastQuery or 0)>=DISCOVERY_INTERVAL then local sent,err=broadcast({type=\"discover_query\"})discovery.lastQuery,discovery.retries=timestamp,(discovery.retries or 0)+1 if not sent then discovery.error=err end elseif discovery.state==\"confirming\"and timestamp-(discovery.lastSent or 0)>=PAIR_RETRY then local candidate=discovery.candidate local sent,err=handshake(candidate.from,{type=\"pair_join\",session=candidate.session,nonce=discovery.joinNonce,proof=discovery.joinProof,label=label()})discovery.lastSent,discovery.retries=timestamp,(discovery.retries or 0)+1 if not sent then discovery.error=err end end end for sessionId,item in pairs(discovered)do if item.expires<=timestamp then discovered[sessionId]=nil end end for sessionId,record in pairs(confirmations)do if record.expires<=timestamp then confirmations[sessionId]=nil elseif timestamp-(record.lastSent or 0)>=PAIR_RETRY then queueConfirmation(record.peer,record)end end for peerId,bucket in pairs(routes)do local kept={}for _,candidate in ipairs(routeBucket(peerId).candidates)do if candidate.expires>timestamp then kept[#kept+1]=candidate end end bucket.candidates=kept if#kept==0 and not activeLink(config(),peerId)then routes[peerId],routesDirty=nil,true end end for peerId,edge in pairs(autoEdges)do if edge.expires<=timestamp then autoEdges[peerId],routesDirty=nil,true;trace(\"routing\",\"mesh_edge_expired\",{peer=peerId})end end for key,seenAt in pairs(meshSeen)do if seenAt+ROUTE_TTL<=timestamp then meshSeen[key]=nil end end for peerId,offer in pairs(meshOffers)do if offer.expires<=timestamp then meshOffers[peerId]=nil end end for requestId,seenAt in pairs(seenPackets)do if seenAt+ROUTE_TTL<=timestamp then seenPackets[requestId]=nil end end for requestId,route in pairs(reverseRoutes)do if route.expires<=timestamp then reverseRoutes[requestId]=nil end end boundMap(meshSeen,MESH_STATE_LIMIT,timestamp)boundMap(meshOffers,MESH_STATE_LIMIT,timestamp)pruneRouteBuckets(timestamp)ensureMeshEnrollment(timestamp)meshBeacon(timestamp)probeLinks(timestamp)advertiseRoutes(false)end function M.peers()local out,value,seen={},config(),read(SEEN_PATH,{})for peerId,peer in pairs(value.peers)do out[#out+1]={id=peerId,label=peer.label or(seen[peerId]and seen[peerId].label),role=peer.role or\"operator\",mode=peer.mode or\"peer\",master=peer.master==true,masterId=peer.masterId,direct=true,active=activePeer(value,peerId)~=nil,rekeyRequired=peer.rekeyRequired==true or peer.protocol~=2,health=linkState(peerId),auto=false,}end for peerId,edge in pairs(autoEdges)do if not value.peers[peerId]and edge.expires>now()then out[#out+1]={id=peerId,label=edge.label or(seen[peerId]and seen[peerId].label),role=\"mesh\",mode=\"peer\",direct=true,auto=true,active=true,health=linkState(peerId)}end end for peerId in pairs(routes)do if not value.peers[peerId]and not autoEdges[peerId]then local route=primaryCandidate(peerId,value,false)if route then out[#out+1]={id=peerId,label=route.label or(seen[peerId]and seen[peerId].label),role=\"routed\",mode=route.mode or\"peer\",masterId=route.masterId,routed=true,hops=route.hops,next=route.next,health=linkState(route.next),alternates=#routeBucket(peerId).candidates-1}end end end table.sort(out,function(a,b)return tonumber(a.id)<tonumber(b.id)end)return out end function M.directPeers()local out={}for _,peer in ipairs(M.peers())do if peer.direct and peer.active then out[#out+1]=peer end end return out end function M.seenPeers()local out={}for peerId,item in pairs(read(SEEN_PATH,{}))do if not item.seen or item.seen+DISCOVERY_TTL*2>now()then out[#out+1]={id=peerId,label=item.label,seen=item.seen,session=item.session}end end table.sort(out,function(a,b)return tonumber(a.id)<tonumber(b.id)end)return out end function M.routeStatus(target)local value,out=config(),{}local function row(peerId)local selected=primaryCandidate(peerId,value,false)if not selected then return end local health=healthFor(selected.next)local alternates={}for _,candidate in ipairs(validCandidates(peerId,value))do if tostring(candidate.next)~=tostring(selected.next)then local state=healthFor(candidate.next)alternates[#alternates+1]={next=candidate.next,hops=candidate.hops,kind=candidate.kind or\"route\",health=state.state,loss=state.loss or 0,rtt=state.rtt,distance=state.lastDistance}end end table.sort(alternates,compareCandidates)while#alternates>ROUTE_CANDIDATE_LIMIT-1 do table.remove(alternates)end out[#out+1]={id=tostring(peerId),label=selected.label,next=selected.next,hops=selected.hops,kind=selected.kind or\"route\",health=health.state,loss=health.loss or 0,rtt=health.rtt,distance=health.lastDistance,selectedAt=routeBucket(peerId).changedAt,reason=routeBucket(peerId).reason,alternates=alternates,}end if target then row(tostring(target))else local ids,seen={},{}for peerId in pairs(value.peers)do ids[#ids+1],seen[peerId]=peerId,true end for peerId in pairs(autoEdges)do if not seen[peerId]then ids[#ids+1],seen[peerId]=peerId,true end end for peerId in pairs(routes)do if not seen[peerId]then ids[#ids+1],seen[peerId]=peerId,true end end table.sort(ids,function(a,b)return tonumber(a)<tonumber(b)end)for _,peerId in ipairs(ids)do row(peerId)end end return out end function M.statusSnapshot()return{protocol=2,transport=M.transportStatus(),discovery=M.discoveryStatus(),peers=M.peers(),routes=M.routeStatus(),trace=M.transportTrace(),controller=M.controller()}end function M.controller()return controller()end function M.isDirectController(from,packet)return tostring(from)==tostring(controller())and type(packet)==\"table\"and tostring(packet.origin or\"\")==tostring(from)end function M.setController(value)assert(tonumber(value),\"controller must be a computer ID\")local saved=config();saved.controller=tostring(value);save(saved);routesDirty=true audit.log(\"local\",\"jobs.controller\",{controller=saved.controller})return saved.controller end function M.request(target,typeName,body,options)if type(typeName)~=\"string\"or#typeName==0 or#typeName>64 then return false,\"invalid request type\"end local destination=tostring(target)local value=config()if not primaryCandidate(destination,value,options and options.safe==true)then return false,\"peer is unreachable, degraded, or requires rekey\"end return send(destination,{type=typeName,body=body or{},origin=id(),routeSafe=options and options.safe==true,balanceSafe=options and options.safe==true,confidential=options and options.confidential==true,request_id=newRequestId()})end function M.reply(request,typeName,body,options)if type(request)~=\"table\"or type(typeName)~=\"string\"or#typeName==0 or#typeName>64 then return false,\"invalid reply\"end local requestId,destination=request.request_id,tostring(request.origin or\"\")local reverse=type(requestId)==\"string\"and reverseRoutes[requestId]or nil if destination==\"\"or not reverse or reverse.expires<=now()or reverse.origin~=destination then return false,\"reverse reply route is unavailable\"end return send(destination,{type=typeName,body=body or{},origin=id(),destination=destination,reply_to=requestId,routeSafe=options and options.safe==true,confidential=options and options.confidential==true,request_id=newRequestId(),},reverse.previous)end function M.offer()return false,\"legacy pairing is disabled; use phrase discovery\"end function M.accept()return false,\"legacy pairing is disabled; use phrase discovery\"end function M.discover()return broadcast({type=\"discover_query\"})end rejectPacket=function(reason,packet,channel,distance)transport.rejected=transport.rejected+1 trace(\"transport\",\"packet_rejected\",{reason=reason,type=type(packet)==\"table\"and packet.type or nil,channel=channel,distance=distance,from=type(packet)==\"table\"and packet.from or nil})end local function handleDiscovery(packet,channel,distance)local from=tostring(packet.from)if packet.type==\"discover_cancel\"and isBroadcast(packet.to)then discovered[tostring(packet.session)]=nil trace(\"discovery\",\"cancel_received\",{from=from,distance=distance})return end if packet.type==\"discover_query\"and isBroadcast(packet.to)and discovery and discovery.state==\"hosting\"then discoveryAnnouncement()trace(\"discovery\",\"query_answered\",{from=from,distance=distance})return end if packet.type==\"discover\"and isBroadcast(packet.to)and from~=id()then if type(packet.session)~=\"string\"or#packet.session<16 or type(packet.tag)~=\"string\"or#packet.tag~=64 then return rejectPacket(\"malformed_discovery\",packet,channel,distance)end local expires=tonumber(packet.expires)or(now()+DISCOVERY_TTL)discovered[packet.session]={session=packet.session,from=from,tag=packet.tag,label=tostring(packet.label or(\"Computer \"..from)):sub(1,128),mode=packet.mode==\"master\"and\"master\"or\"peer\",master=packet.master==\"joiner\"and\"joiner\"or\"initiator\",expires=math.min(expires,now()+DISCOVERY_TTL)}remember(from,packet.label,{session=packet.session})trace(\"discovery\",\"announcement_received\",{from=from,label=packet.label,distance=distance})if discovery and discovery.state==\"searching\"and password.constantTimeEqual(packet.tag,phraseTag(discovery.phrase,packet.session,from))then local value,existing=config(),config().peers[from]if existing and not existing.rekeyRequired then markRejected(\"computer is already a direct peer\")elseif routes[from]and not existing then markRejected(\"computer is already a routed network member\")else discovery.state,discovery.candidate,discovery.error=\"candidate\",discovered[packet.session],nil setLast(\"candidate\",\"matching computer found; confirm pairing\")trace(\"discovery\",\"candidate_found\",{from=from,label=packet.label,distance=distance})end end return end end local function handlePairJoin(packet,distance)if not discovery or discovery.state~=\"hosting\"or packet.session~=discovery.id then return end local from=tostring(packet.from)local value,existing=config(),config().peers[from]if(existing and not existing.rekeyRequired)or(routes[from]and not existing)then handshake(from,{type=\"pair_reject\",session=packet.session,reason=\"already_network_member\"})trace(\"discovery\",\"pair_rejected\",{from=from,reason=\"already_network_member\"})return end if type(packet.nonce)~=\"string\"or#packet.nonce<16 or#packet.nonce>128 or type(packet.proof)~=\"string\"or#packet.proof~=64 then return rejectPacket(\"malformed_pair_join\",packet,nil,distance)end local expected=joinProof(discovery.phrase,discovery.id,id(),from,packet.nonce)if not password.constantTimeEqual(expected,packet.proof)then discovery.failures=(discovery.failures or 0)+1 if discovery.failures>=5 then markRejected(\"too many invalid pairing proofs\")end handshake(from,{type=\"pair_reject\",session=packet.session,reason=\"phrase_mismatch\"})trace(\"discovery\",\"pair_rejected\",{from=from,reason=\"phrase_mismatch\"})return end local masterId=discovery.mode==\"master\"and(discovery.masterSide==\"initiator\"and id()or from)or\"\"local key,keyErr=linkKey(discovery.phrase,discovery.id,id(),from,packet.nonce)if not key then return markRejected(keyErr)end persistPair(from,key,{mode=discovery.mode,label=packet.label},masterId)local record={id=discovery.id,peer=from,joinNonce=packet.nonce,mode=discovery.mode,masterId=masterId,label=label(),expires=now()+DISCOVERY_TTL}record.confirmProof=confirmProof(discovery.phrase,record.id,id(),from,record.joinNonce,record.mode,record.masterId)discovery=nil setLast(\"paired\",\"awaiting pairing acknowledgement\")trace(\"discovery\",\"pair_join_verified\",{from=from,distance=distance})return queueConfirmation(from,record)end local function handlePairConfirm(packet,distance)if not discovery or discovery.state~=\"confirming\"or not discovery.candidate or packet.session~=discovery.candidate.session then return end local from=tostring(packet.from)if from~=tostring(discovery.candidate.from)or packet.nonce~=discovery.joinNonce then return rejectPacket(\"unexpected_pair_confirmation\",packet,nil,distance)end local expected=confirmProof(discovery.phrase,packet.session,from,id(),discovery.joinNonce,packet.mode==\"master\"and\"master\"or\"peer\",packet.master or\"\")if not password.constantTimeEqual(expected,packet.proof or\"\")then return markRejected(\"pair confirmation proof did not match\")end local key,err=linkKey(discovery.phrase,packet.session,from,id(),discovery.joinNonce)if not key then return markRejected(err)end persistPair(from,key,{mode=packet.mode,label=packet.label},packet.master)local sessionId=packet.session discovery=nil setLast(\"paired\",\"paired with \"..tostring(packet.label or from))handshake(from,{type=\"pair_ack\",session=sessionId,proof=password.hmacSha256(key,\"ceetos/pair/ack/v2|\"..sessionId)})trace(\"discovery\",\"pair_confirmed\",{from=from,distance=distance})return true end local function handlePairAck(packet)local record=confirmations[packet.session]if not record or tostring(record.peer)~=tostring(packet.from)then return end local value,peer=config(),activePeer(config(),record.peer)if not peer then return end local expected=password.hmacSha256(peer.key,\"ceetos/pair/ack/v2|\"..packet.session)if password.constantTimeEqual(expected,packet.proof or\"\")then confirmations[packet.session]=nil setLast(\"paired\",\"paired with \"..tostring(record.peer))routesDirty=true trace(\"discovery\",\"pair_acknowledged\",{from=packet.from})end end local function handleRouteAdvertisement(from,packet)local body=packet.body if type(body)~=\"table\"or type(body.sequence)~=\"number\"or type(body.members)~=\"table\"or(body.withdrawals~=nil and type(body.withdrawals)~=\"table\")then return rejectPacket(\"malformed_route_advertisement\",packet)end local key=tostring(from)M._routeSequences=M._routeSequences or{}if(M._routeSequences[key]or-1)>=body.sequence then return end M._routeSequences[key]=body.sequence local value,changed,count=config(),false,0 if body.controller and not value.controller then value.controller,changed=tostring(body.controller),true end local announced={}for advertisedId,meta in pairs(body.members)do count=count+1 if count>MAX_PACKET_TABLE then return rejectPacket(\"route_advertisement_too_large\",packet)end local peerId=tostring(advertisedId)announced[peerId]=true if peerId~=id()and peerId~=key and type(meta)==\"table\"then local hops=math.floor(tonumber(meta.hops)or 0)+1 if hops>1 and hops<=PACKET_TTL and type(meta.label)~=\"table\"and type(meta.mode)~=\"table\"then local bucket,found=routeBucket(peerId),nil for _,candidate in ipairs(bucket.candidates)do if tostring(candidate.next)==key then found=candidate;break end end if found then local metadataChanged=found.hops~=hops or found.label~=meta.label or found.mode~=meta.mode or tostring(found.masterId or\"\")~=tostring(meta.masterId or\"\")or found.kind~=(meta.kind or\"route\")found.hops,found.expires=hops,now()+ROUTE_TTL found.label,found.mode,found.masterId,found.kind=meta.label,meta.mode,meta.masterId,meta.kind or\"route\"if metadataChanged then changed=true end else bucket.candidates[#bucket.candidates+1]={next=key,hops=hops,expires=now()+ROUTE_TTL,label=type(meta.label)==\"string\"and meta.label:sub(1,128)or nil,mode=meta.mode==\"master\"and\"master\"or\"peer\",masterId=meta.masterId and tostring(meta.masterId)or nil,kind=meta.kind==\"mesh\"and\"mesh\"or\"route\"}table.sort(bucket.candidates,compareCandidates)while#bucket.candidates>ROUTE_CANDIDATE_LIMIT do table.remove(bucket.candidates)end changed=true end end end end local withdrawals=body.withdrawals or{}for _,withdrawnId in pairs(withdrawals)do count=count+1 if count>MAX_PACKET_TABLE then return rejectPacket(\"route_advertisement_too_large\",packet)end local bucket=routes[tostring(withdrawnId)]if bucket and type(bucket.candidates)==\"table\"then local kept={}for _,candidate in ipairs(bucket.candidates)do if tostring(candidate.next)~=key then kept[#kept+1]=candidate else changed=true end end bucket.candidates=kept end end if body.full==true then for peerId,bucket in pairs(routes)do if type(bucket.candidates)==\"table\"and not announced[tostring(peerId)]then local kept={}for _,candidate in ipairs(bucket.candidates)do if tostring(candidate.next)~=key then kept[#kept+1]=candidate else changed=true end end bucket.candidates=kept end end end if changed then if value.controller then save(value)end;routesDirty=true;trace(\"routing\",\"route_table_updated\",{from=from})end end local function handleProbe(from,packet)local token=type(packet.body)==\"table\"and packet.body.token if type(token)~=\"string\"or#token<16 or#token>128 then return rejectPacket(\"malformed link probe\",packet)end touchLink(from,nil,\"probe\")return send(from,{type=\"mesh_probe_ack\",body={token=token},request_id=newRequestId()},from)end local function handleProbeAck(from,packet)local health,token=healthFor(from),type(packet.body)==\"table\"and packet.body.token if not health.awaiting or token~=health.probeToken then return rejectPacket(\"unexpected link probe acknowledgement\",packet)end local sample=math.max(0,now()-(health.lastProbe or now()))health.rtt=health.rtt and math.floor((health.rtt*3+sample)/4)or sample health.awaiting,health.misses,health.probeToken=false,0,nil touchLink(from,health.lastDistance,\"probe_ack\")end function M.handle(event)if event[1]~=\"modem_message\"then return end local channel,packet,distance=event[3],event[5],event[6]local expected=false for _,item in ipairs(transport.channels or{})do if channel==item then expected=true;break end end if not expected then return rejectPacket(\"unexpected_channel\",packet,channel,distance)end transport.lastReceive,transport.lastDistance=now(),distance if type(packet)~=\"table\"then return rejectPacket(\"packet_not_table\",packet,channel,distance)end if packet.protocol==PUBLIC_UPDATE_PROTOCOL then if channel~=DISCOVERY_CHANNEL or not PUBLIC_UPDATE_TYPES[packet.type]or type(packet.from)~=\"string\"and type(packet.from)~=\"number\"or not(isForUs(packet.to)or isBroadcast(packet.to))then return rejectPacket(\"invalid_public_update_packet\",packet,channel,distance)end local encoded,encodeErr=canonical(packet.body or{})if not encoded then return rejectPacket(\"invalid_public_update_body:\"..tostring(encodeErr),packet,channel,distance)end trace(\"transport\",\"public_update_received\",{type=packet.type,from=packet.from,distance=distance,bytes=#encoded})if M.publicHandler then return M.publicHandler(packet,distance)end return end local discoveryPacket=packet.type==\"discover\"or packet.type==\"discover_query\"or packet.type==\"discover_cancel\"local handshakePacket=packet.type==\"pair_join\"or packet.type==\"pair_confirm\"or packet.type==\"pair_ack\"or packet.type==\"pair_reject\"local meshPacketType=packet.type==\"mesh_beacon\"or packet.type==\"mesh_edge_offer\"or packet.type==\"mesh_edge_accept\"if discoveryPacket then if packet.protocol~=PROTOCOL or channel~=DISCOVERY_CHANNEL then return rejectPacket(\"invalid_discovery_transport\",packet,channel,distance)end return handleDiscovery(packet,channel,distance)end if handshakePacket then if not isForUs(packet.to)then return end if packet.protocol~=PROTOCOL or channel~=(config().channel or CHANNEL)then return rejectPacket(\"invalid_handshake_transport\",packet,channel,distance)end if packet.type==\"pair_join\"then return handlePairJoin(packet,distance)elseif packet.type==\"pair_confirm\"then return handlePairConfirm(packet,distance)elseif packet.type==\"pair_ack\"then return handlePairAck(packet)elseif packet.type==\"pair_reject\"and discovery then markRejected(\"pairing rejected: \"..tostring(packet.reason or\"remote peer rejected it\"));return end return end if meshPacketType then if packet.protocol~=PROTOCOL or channel~=(config().channel or CHANNEL)then return rejectPacket(\"invalid mesh transport\",packet,channel,distance)end if packet.type~=\"mesh_beacon\"and not isForUs(packet.to)then return end return handleMeshPacket(packet,distance)end if not isForUs(packet.to)then return end local value=config()local valid,peerOrReason=verifyPacket(packet,value)if not valid then return rejectPacket(peerOrReason,packet,channel,distance)end local peer,from=peerOrReason,tostring(packet.from)if packet.confidential==true then local opened,openErr=openBody(peer,packet)if not opened then return rejectPacket(openErr or\"could not open confidential packet\",packet,channel,distance)end packet.body=opened end touchLink(from,distance,\"authenticated_packet\")if autoEdges[from]then autoEdges[from].expires=now()+ROUTE_TTL end trace(\"routing\",\"packet_received\",{type=packet.type,from=from,destination=packet.destination,distance=distance})if packet.type==\"mesh_enroll\"then return acceptEnrollment(from,peer,packet)end if packet.type==\"mesh_probe\"then return handleProbe(from,packet)end if packet.type==\"mesh_probe_ack\"then return handleProbeAck(from,packet)end if packet.type==\"route_advertise\"then return handleRouteAdvertisement(from,packet)end if packet.reply_to and packet.destination and tostring(packet.destination)~=id()then local reverse=reverseRoutes[packet.reply_to]if not reverse or reverse.expires<=now()or reverse.origin~=tostring(packet.destination)then return rejectPacket(\"reverse reply route unavailable\",packet,channel,distance)end local requestId=tostring(packet.request_id or\"\")if seenPackets[requestId]then return trace(\"routing\",\"forward_duplicate\",{from=from,type=packet.type})end seenPackets[requestId]=now()if(tonumber(packet.ttl)or 0)<=1 then return rejectPacket(\"TTL exhausted\",packet,channel,distance)end packet.ttl=packet.ttl-1 trace(\"routing\",\"reverse_reply_forwarded\",{from=from,to=reverse.previous,type=packet.type})return send(packet.destination,packet,reverse.previous)end if packet.destination and tostring(packet.destination)~=id()then local requestId=tostring(packet.request_id or\"\")if requestId==\"\"or seenPackets[requestId]then return trace(\"routing\",\"forward_duplicate\",{from=from,type=packet.type})end seenPackets[requestId]=now()local remembered,rememberErr=rememberReverse(packet,from)if not remembered then return rejectPacket(rememberErr or\"could not record reverse route\",packet,channel,distance)end if(tonumber(packet.ttl)or 0)<=1 then return rejectPacket(\"TTL exhausted\",packet,channel,distance)end packet.ttl=packet.ttl-1 return send(packet.destination,packet)end local requestId=tostring(packet.request_id or\"\")if requestId==\"\"then return rejectPacket(\"missing request ID\",packet,channel,distance)end if seenPackets[requestId]then return trace(\"routing\",\"destination_duplicate\",{from=from,type=packet.type})end seenPackets[requestId]=now()local remembered,rememberErr=rememberReverse(packet,from)if not remembered then return rejectPacket(rememberErr or\"could not record reverse route\",packet,channel,distance)end packet.authenticatedHop,packet.originVerified=from,false if M.handler then return M.handler(from,peer,packet)end end return M",
  ["ceetos/lib/network_ipc.lua"] = "local store=require(\"ceetos.lib.store\")local M={}local ROOT=\"/ceetos/data/network-ipc\"local COMMANDS=ROOT..\"/commands\"local RESULTS=ROOT..\"/results\"local function ensure(path)if not fs.exists(path)then fs.makeDir(path)end end local function safeId(value)return type(value)==\"string\"and value:match(\"^[%w_%-%.]+$\")and#value<=160 end local function path(directory,requestId)return fs.combine(directory,requestId..\".lua\")end function M.submit(request)if type(request)~=\"table\"or not safeId(request.id)then return false,\"invalid IPC request ID\"end ensure(ROOT);ensure(COMMANDS);ensure(RESULTS)local target=path(COMMANDS,request.id)if fs.exists(target)then return false,\"IPC request already exists\"end return store.write(target,request)end function M.take()ensure(ROOT);ensure(COMMANDS);ensure(RESULTS)local names=fs.list(COMMANDS)table.sort(names)for _,name in ipairs(names)do local requestId=name:match(\"^([%w_%-%.]+)%.lua$\")if requestId and safeId(requestId)then local target=fs.combine(COMMANDS,name)store.invalidate(target)local request=store.readFresh(target,nil)fs.delete(target)if type(request)==\"table\"and request.id==requestId then return request end end end end function M.reply(requestId,value)if not safeId(requestId)or type(value)~=\"table\"then return false,\"invalid IPC result\"end ensure(ROOT);ensure(COMMANDS);ensure(RESULTS)return store.write(path(RESULTS,requestId),value)end function M.poll(requestId,consume)if not safeId(requestId)then return nil,\"invalid IPC request ID\"end local target=path(RESULTS,requestId)if not fs.exists(target)then return nil end local handle=fs.open(target,\"r\")if not handle then return nil end local raw=handle.readAll()handle.close()local ok,result=pcall(textutils.unserialise,raw)if not ok or type(result)~=\"table\"or result.id~=requestId then return nil,\"invalid IPC result\"end if consume then fs.delete(target)end return result end function M.prune(limit)ensure(ROOT);ensure(COMMANDS);ensure(RESULTS)limit=math.max(1,math.floor(tonumber(limit)or 32))local names={}for _,name in ipairs(fs.list(RESULTS))do if name:match(\"^[%w_%-%.]+%.lua$\")then names[#names+1]=name end end table.sort(names)while#names>limit do fs.delete(fs.combine(RESULTS,table.remove(names,1)))end end function M.status()ensure(ROOT);ensure(COMMANDS);ensure(RESULTS)local function count(directory)local total=0 for _,name in ipairs(fs.list(directory))do if name:match(\"^[%w_%-%.]+%.lua$\")then total=total+1 end end return total end return{commands=count(COMMANDS),results=count(RESULTS)}end return M",
  ["ceetos/lib/auth_client.lua"] = "local store=require(\"ceetos.lib.store\")local password=require(\"ceetos.lib.password\")local networkIpc=require(\"ceetos.lib.network_ipc\")local M={}local REPLIES=\"/ceetos/data/auth-replies.lua\"local sequence=0 local function now()return os.epoch(\"utc\")end local function authority()store.invalidate(\"/ceetos/data/auth-authority.lua\")local value=store.read(\"/ceetos/data/auth-authority.lua\",nil)return type(value)==\"table\"and value.active==true and value or nil end local function requestId(kind)sequence=sequence+1 return table.concat({\"auth\",kind,tostring(os.getComputerID()),tostring(now()),tostring(sequence)},\"-\")end local function take(id)store.invalidate(REPLIES)local replies=store.read(REPLIES,{})local row=replies[id]if row then replies[id]=nil;store.write(REPLIES,replies)end return row end function M.receive(body)if type(body)~=\"table\"or type(body.request_id)~=\"string\"or#body.request_id>160 then return false,\"invalid authority reply\"end local replies=store.read(REPLIES,{})replies[body.request_id]={ok=body.ok==true,result=body.result,error=body.error,at=now()}local rows={}for id,row in pairs(replies)do rows[#rows+1]={id=id,at=tonumber(row.at)or 0}end table.sort(rows,function(a,b)return a.at>b.at end)while#rows>32 do replies[table.remove(rows).id]=nil end return store.write(REPLIES,replies)end local function send(typeName,body,timeout)local server=authority()if not server then return nil,\"no Auth Server is reachable\"end local id=body.request_id or requestId(typeName)body.request_id=id local command={id=\"auth-\"..id,action=\"auth_send\",target=server.id,type=typeName,body=body}local ok,err=networkIpc.submit(command)if not ok then return nil,err or\"could not reach CeetOS network service\"end local deadline=now()+(timeout or 6000)while now()<deadline do local ack=networkIpc.poll(command.id,true)if ack and ack.ok~=true then return nil,ack.error or\"Auth Server request was not sent\"end local reply=take(id)if reply then return reply.ok and reply.result or nil,reply.error or\"Auth Server rejected request\"end sleep(0.05)end return nil,\"Auth Server did not respond\"end local function loginProof(verifier,server,request,challenge,expires)return password.hmacSha256(verifier,table.concat({\"ceetos/auth/login/v1\",tostring(server),tostring(os.getComputerID()),tostring(request),tostring(challenge),tostring(expires)},\"|\"))end function M.login(name,plainPassword)if type(name)~=\"string\"or type(plainPassword)~=\"string\"then return false,\"invalid credentials\"end local cloud=require(\"ceetos.lib.cloud_sync\")if cloud.authOnline()then return cloud.login(name,plainPassword)end local request=requestId(\"begin\")local begin,beginErr=send(\"auth_login_begin\",{request_id=request,username=name,node=tostring(os.getComputerID())})if not begin then return false,beginErr end local verifier,deriveErr=password.derive(plainPassword,begin.salt,begin.workFactor)if not verifier then return false,deriveErr end local proof=loginProof(verifier,begin.authority,request,begin.challenge,begin.expires)local result,proofErr=send(\"auth_login_proof\",{request_id=request,username=name,node=tostring(os.getComputerID()),challenge=begin.challenge,proof=proof})if not result then return false,proofErr end local auth=require((\"ceetos.lib.auth\"))local saved,saveErr=auth.saveCentralSession(result.session)if not saved then return false,saveErr end if type(result.directory)==\"table\"then auth.updateDirectory(result.directory,result.revision)end return true end function M.mutate(action,fields)local auth=require((\"ceetos.lib.auth\"))local cloud=require(\"ceetos.lib.cloud_sync\")if cloud.authOnline()then return cloud.mutate(action,fields)end local current,server=auth.refreshSession(),authority()if not current or not current.central or not server then return false,\"an Auth Server login is required\"end local result,err=send(\"auth_mutate\",{action=action,fields=fields,session=current.nonce,node=tostring(os.getComputerID()),revision=current.accountRevision})if not result then return false,err end if type(result.directory)==\"table\"then auth.updateDirectory(result.directory,result.revision)end return true end return M",
  ["ceetos/lib/jobs.lua"] = "local store=require(\"ceetos.lib.store\")local audit=require(\"ceetos.lib.audit\")local M={}local PATH,WORKERS_PATH=\"/ceetos/data/jobs.lua\",\"/ceetos/data/job-workers.lua\"local HISTORY_LIMIT,OUTPUT_LIMIT=48,4096 local HEARTBEAT_TIMEOUT,DEFAULT_CAPACITY=15000,1 local DEFAULT_TIMEOUT,DEFAULT_ATTEMPTS=60000,2 local context=nil local function now()if context and context.now then return context.now()end return os.epoch(\"utc\")end local function localId()if context and(context.id~=nil or context.nodeId~=nil)then return tostring(context.id or context.nodeId)end return tostring(os.getComputerID())end local function backend()return context and context.store or store end local function paths()return context and context.path or PATH,context and context.workersPath or WORKERS_PATH end local function log(action,detail)if not(context and context.noAudit~=false)then audit.log(\"system\",action,detail)end end local function copy(value,seen)if type(value)~=\"table\"then return value end seen=seen or{}if seen[value]then return seen[value]end local result={};seen[value]=result for key,item in pairs(value)do result[copy(key,seen)]=copy(item,seen)end return result end local function clampNumber(value,low,high,fallback)value=tonumber(value)if not value then return fallback end return math.max(low,math.min(high,math.floor(value)))end local function cleanOutput(value)value=tostring(value or\"\")if#value>OUTPUT_LIMIT then return value:sub(1,OUTPUT_LIMIT)..\"\\n[output truncated]\"end return value end local function defaultState()return{controller=(context and context.controllerId and tostring(context.controllerId))or localId(),capacity=DEFAULT_CAPACITY,workers={},templates={},queue={},running={},schedules={},history={},sequence=0,fair=0,}end local function normalise(data)data=type(data)==\"table\"and data or defaultState()local defaults=defaultState()for key,value in pairs(defaults)do if data[key]==nil then data[key]=value end end data.controller=tostring(data.controller or localId())data.capacity=clampNumber(data.capacity,1,32,DEFAULT_CAPACITY)data.workers,data.templates,data.queue=data.workers or{},data.templates or{},data.queue or{}data.running,data.schedules,data.history=data.running or{},data.schedules or{},data.history or{}data.sequence,data.fair=tonumber(data.sequence)or 0,tonumber(data.fair)or 0 return data end local function load()local mainPath,workersPath=paths()local disk=backend()if disk.invalidate then disk.invalidate(mainPath);disk.invalidate(workersPath)end local data=normalise(disk.read(mainPath,defaultState()))data.workers=disk.read(workersPath,data.workers or{})or{}return normalise(data)end local function save(data)local mainPath,workersPath=paths()local disk=backend()local workers=data.workers or{}local main=copy(data);main.workers=nil disk.write(mainPath,main)disk.write(workersPath,copy(workers))end local function nextId(data,prefix)data.sequence=data.sequence+1 return string.format(\"%s-%s-%d\",prefix,tostring(now()),data.sequence)end local function findQueue(data,jobId)for index,job in ipairs(data.queue)do if job.id==jobId then return index,job end end end local function finish(data,job,status,result)data.running[job.id]=nil local worker=job.worker and data.workers[tostring(job.worker)]if worker then worker.inFlight=math.max(0,(tonumber(worker.inFlight)or 0)-1)end job.status,job.finished,job.result=status,now(),result or{}job.result.output=cleanOutput(job.result.output or job.result.stdout or\"\")data.history[#data.history+1]=job local limit=(context and tonumber(context.historyLimit))or HISTORY_LIMIT while#data.history>limit do table.remove(data.history,1)end end local function addJob(data,templateName,scheduleId)local template=data.templates[templateName]assert(template and template.enabled~=false,\"template unavailable\")local job={id=nextId(data,\"job\"),template=templateName,revision=template.revision,command=template.command,scheduleId=scheduleId,created=now(),status=\"queued\",attempts=0,retrySafe=template.retrySafe==true,maxAttempts=template.maxAttempts,}data.queue[#data.queue+1]=job return job end function M.state()return copy(load())end function M.setController(value)assert(value~=nil and tostring(value)~=\"\",\"controller id required\")local data=load();data.controller=tostring(value);save(data)log(\"jobs_controller\",data.controller)return data.controller end function M.controller()return load().controller end function M.isController()return M.controller()==localId()end local function requireController()assert(M.isController(),\"controller required\")end function M.setCapacity(value)local data=load();data.capacity=clampNumber(value,1,32,DEFAULT_CAPACITY);save(data)return data.capacity end function M.heartbeat(peer,status)assert(peer~=nil and tostring(peer)~=\"\",\"worker id required\")status=type(status)==\"table\"and status or{}local data,id=load(),tostring(peer)local old=data.workers[id]or{}data.workers[id]={id=id,label=status.label or old.label or id,capacity=clampNumber(status.capacity,1,32,old.capacity or DEFAULT_CAPACITY),inFlight=clampNumber(status.inFlight,0,32,old.inFlight or 0),queueDepth=clampNumber(status.queueDepth,0,1024,0),route=status.route or old.route,hops=clampNumber(status.hops or status.routeHops,0,32,old.hops or 99),available=status.available~=false,lastSeen=now(),lastError=status.lastError,}save(data)return copy(data.workers[id])end M.updateWorker=M.heartbeat function M.workers()local data,at,result=load(),now(),{}for id,worker in pairs(data.workers)do local row=copy(worker)row.healthy=row.available~=false and at-(row.lastSeen or 0)<=HEARTBEAT_TIMEOUT row.slots=math.max(0,(row.capacity or DEFAULT_CAPACITY)-(row.inFlight or 0))result[id]=row end return result end function M.addTemplate(name,command,options)requireController()if type(name)==\"table\"then options,command,name=name,name.command,name.id or name.name end assert(type(name)==\"string\"and name:match(\"^[%w_%-]+$\"),\"invalid template name\")assert(type(command)==\"string\"and#command>0 and#command<=512,\"invalid fixed command\")options=type(options)==\"table\"and options or{}local data=load()assert(not data.templates[name],\"template already exists\")data.templates[name]={name=name,command=command,enabled=options.enabled~=false,timeout=clampNumber(options.timeout,1000,600000,DEFAULT_TIMEOUT),retrySafe=options.retrySafe==true,maxAttempts=clampNumber(options.maxAttempts,1,5,DEFAULT_ATTEMPTS),revision=nextId(data,\"template\"),created=now(),}save(data);log(\"jobs_template_added\",name)return copy(data.templates[name])end function M.listTemplates()return copy(load().templates)end function M.setTemplateRetrySafe(name,enabled)requireController()local data=load();assert(data.templates[name],\"unknown template\")data.templates[name].retrySafe=enabled==true;save(data)return copy(data.templates[name])end function M.setTemplateEnabled(name,enabled)requireController()local data=load();assert(data.templates[name],\"unknown template\")data.templates[name].enabled=enabled~=false;save(data)return copy(data.templates[name])end function M.removeTemplate(name)requireController()local data=load();assert(data.templates[name],\"unknown template\")for _,job in ipairs(data.queue)do assert(job.template~=name,\"template has queued jobs\")end for _,job in pairs(data.running)do assert(job.template~=name,\"template has running jobs\")end for _,schedule in pairs(data.schedules)do assert(schedule.template~=name or not schedule.enabled,\"template has active schedule\")end data.templates[name]=nil;save(data);log(\"jobs_template_removed\",name)return true end function M.enqueue(templateName,scheduleId)requireController()local data,job=load(),nil job=addJob(data,templateName,scheduleId)save(data)return copy(job)end function M.selectWorker()local data,at,candidates=load(),now(),{}for id,worker in pairs(data.workers)do local healthy=worker.available~=false and at-(worker.lastSeen or 0)<=HEARTBEAT_TIMEOUT local capacity,inFlight=worker.capacity or DEFAULT_CAPACITY,worker.inFlight or 0 if healthy and inFlight<capacity then candidates[#candidates+1]={id=id,worker=worker,load=inFlight/capacity,hops=tonumber(worker.hops)or tonumber(worker.routeHops)or 99}end end table.sort(candidates,function(a,b)if a.load~=b.load then return a.load<b.load end if a.hops~=b.hops then return a.hops<b.hops end return a.id<b.id end)if#candidates==0 then return nil end local best,count=candidates[1],1 while candidates[count+1]and candidates[count+1].load==best.load and candidates[count+1].hops==best.hops do count=count+1 end local chosen=candidates[(data.fair%count)+1]return copy(chosen.worker)end function M.dispatchNext()local job,worker=M.nextDispatch(),M.selectWorker()if not job or not worker then return nil,job and\"no healthy worker\"or\"no queued job\"end local assigned=M.assign(job,worker.id)if context and type(context.execute)==\"function\"then local template=M.listTemplates()[assigned.template]local ok,first,second=pcall(context.execute,copy(worker),copy(template),copy(assigned))if not ok then return M.fail(assigned.id,first)end if first==false then return M.fail(assigned.id,second or\"worker rejected job\")end if type(first)==\"table\"then return M.complete(assigned.id,first)end end return assigned end function M.run(templateName,scheduleId)assert(scheduleId==nil or type(scheduleId)==\"string\",\"runtime job arguments are not allowed\")local job=M.enqueue(templateName,scheduleId)local dispatched,reason=M.dispatchNext()return dispatched or job,reason end function M.nextDispatch()local data=load()for _,job in ipairs(data.queue)do if job.status==\"queued\"then return copy(job)end end return nil end function M.assign(jobValue,workerValue)local data,jobId,workerId=load(),type(jobValue)==\"table\"and jobValue.id or jobValue,tostring(workerValue)local index,job=findQueue(data,jobId)assert(job and job.status==\"queued\",\"job is not queued\")local worker=data.workers[workerId]assert(worker,\"unknown worker\")assert(worker.available~=false and now()-(worker.lastSeen or 0)<=HEARTBEAT_TIMEOUT,\"worker unavailable\")assert((worker.inFlight or 0)<(worker.capacity or DEFAULT_CAPACITY),\"worker saturated\")table.remove(data.queue,index)job.status,job.worker,job.started=\"running\",workerId,now()job.attempts=(job.attempts or 0)+1 job.deadline=job.started+(data.templates[job.template].timeout or DEFAULT_TIMEOUT)data.running[job.id]=job;worker.inFlight=(worker.inFlight or 0)+1 data.fair=data.fair+1 save(data)return copy(job)end function M.complete(jobId,result,stdout,stderr)local data,job=load(),nil job=data.running[jobId];assert(job,\"unknown running job\")if result==false then return M.fail(jobId,stderr or stdout or\"worker failed\")end local payload if type(result)==\"table\"then payload=copy(result)elseif stdout~=nil or stderr~=nil then payload={ok=result~=false,stdout=tostring(stdout or\"\"),stderr=tostring(stderr or\"\"),output=tostring(stdout or\"\")}else payload={output=tostring(result or\"\")}end finish(data,job,\"complete\",payload)save(data)return copy(job)end function M.fail(jobId,reason)local data,job=load(),nil job=data.running[jobId];assert(job,\"unknown running job\")data.running[job.id]=nil local worker=job.worker and data.workers[tostring(job.worker)]if worker then worker.inFlight=math.max(0,(worker.inFlight or 0)-1)end if job.retrySafe and(job.attempts or 0)<(job.maxAttempts or DEFAULT_ATTEMPTS)then job.status,job.worker,job.deadline=\"queued\",nil,nil job.lastError,job.updated=tostring(reason or\"failed\"),now()data.queue[#data.queue+1]=job save(data)return copy(job),true end finish(data,job,\"failed\",{error=tostring(reason or\"failed\")})save(data)return copy(job),false end function M.schedule(templateName,interval)requireController()interval=tonumber(interval)assert(interval and interval>=1 and interval<=86400,\"interval must be 1..86400 seconds\")local data=load()assert(data.templates[templateName],\"unknown template\")local id=nextId(data,\"schedule\")data.schedules[id]={id=id,template=templateName,interval=interval*1000,enabled=true,nextRun=now()+interval*1000,created=now()}save(data);log(\"jobs_schedule_added\",id)return copy(data.schedules[id])end function M.cancel(scheduleId)requireController()local data=load();assert(data.schedules[scheduleId],\"unknown schedule\")data.schedules[scheduleId].enabled=false;data.schedules[scheduleId].cancelled=now();save(data)return true end function M.history()return copy(load().history)end function M.queue()return copy(load().queue)end function M.running()return copy(load().running)end function M.localStatus()local data=load()return{id=localId(),controller=data.controller,capacity=data.capacity,inFlight=(function()local total=0;for _ in pairs(data.running)do total=total+1 end;return total end)(),queueDepth=#data.queue}end function M.syncTemplates(controllerId,templates)assert(controllerId~=nil and tostring(controllerId)~=\"\",\"controller id required\")assert(type(templates)==\"table\",\"template snapshot required\")local data=load();data.controller,data.templates=tostring(controllerId),{}for name,template in pairs(templates)do assert(type(name)==\"string\"and type(template)==\"table\"and type(template.command)==\"string\",\"invalid template snapshot\")data.templates[name]={name=name,command=template.command,enabled=template.enabled~=false,timeout=clampNumber(template.timeout,1000,600000,DEFAULT_TIMEOUT),retrySafe=template.retrySafe==true,maxAttempts=clampNumber(template.maxAttempts,1,5,DEFAULT_ATTEMPTS),revision=template.revision or\"synced\",created=template.created or now(),}end save(data)return copy(data.templates)end M.scheduleInterval=M.schedule function M.tick()local data,at,added,timedOut,stale=load(),now(),0,0,0 for _,schedule in pairs(data.schedules)do if M.isController()and schedule.enabled and at>=(schedule.nextRun or at)then addJob(data,schedule.template,schedule.id);added=added+1 repeat schedule.nextRun=(schedule.nextRun or at)+schedule.interval until schedule.nextRun>at end end for _,worker in pairs(data.workers)do if worker.available~=false and at-(worker.lastSeen or 0)>HEARTBEAT_TIMEOUT then worker.stale=true;stale=stale+1 end end local expired={}for id,job in pairs(data.running)do if at>=(job.deadline or at)then expired[#expired+1]=id end end for _,id in ipairs(expired)do local job=data.running[id]if job then timedOut=timedOut+1;data.running[id]=nil local worker=job.worker and data.workers[tostring(job.worker)]if worker then worker.inFlight=math.max(0,(worker.inFlight or 0)-1)end if job.retrySafe and(job.attempts or 0)<(job.maxAttempts or DEFAULT_ATTEMPTS)then job.status,job.worker,job.deadline,job.lastError=\"queued\",nil,nil,\"timeout\";data.queue[#data.queue+1]=job else finish(data,job,\"failed\",{error=\"timeout\"})end end end if added>0 or timedOut>0 or stale>0 then save(data)end if context and type(context.execute)==\"function\"then M.dispatchNext()end return{enqueued=added,timedOut=timedOut,staleWorkers=stale}end function M.new(options)options=options or{}local service={}local names={\"state\",\"setController\",\"controller\",\"isController\",\"setCapacity\",\"heartbeat\",\"updateWorker\",\"workers\",\"addTemplate\",\"listTemplates\",\"setTemplateRetrySafe\",\"setTemplateEnabled\",\"removeTemplate\",\"syncTemplates\",\"enqueue\",\"run\",\"nextDispatch\",\"selectWorker\",\"dispatchNext\",\"assign\",\"complete\",\"fail\",\"tick\",\"schedule\",\"scheduleInterval\",\"cancel\",\"history\",\"queue\",\"running\",\"localStatus\",}local function invoke(fn,...)local prior=context;context=options local result={pcall(fn,...)}context=prior if not result[1]then error(result[2],0)end return table.unpack(result,2)end for _,name in ipairs(names)do service[name]=function(...)local args={...}if args[1]==service then table.remove(args,1)end return invoke(M[name],table.unpack(args))end end return service end return M",
  ["ceetos/lib/peripherals.lua"] = "local store=require(\"ceetos.lib.store\")local audit=require(\"ceetos.lib.audit\")local M={}local PATH=\"/ceetos/data/shares.lua\"local SAFE={getItemDetail=true,list=true,size=true,getMetadata=true,getType=true,getMethods=true,getInput=true,getOutput=true,getAngles=true,getVelocity=true,getHeight=true,getAirPressure=true,getSpeed=true,getStress=true,getStressCapacity=true,stock=true,getStockItemDetail=true,getConfiguration=true,getAddress=true,}local function requestMatchesGrid(request,slots)if type(request)~=\"table\"then return false,\"redstone requester did not return its encoded request\"end local exact=true for slot=1,9 do local expected=slots[slot]if expected and expected~=\"minecraft:air\"then local actual=request[slot]or request[tostring(slot)]if type(actual)~=\"table\"or actual.name~=expected then exact=false;break end end end if exact then return true end local expected,actual={},{}for slot=1,9 do if slots[slot]and slots[slot]~=\"minecraft:air\"then expected[#expected+1]=slots[slot]end end for key,value in pairs(request)do local index=tonumber(key)if index and type(value)==\"table\"and type(value.name)==\"string\"and value.name~=\"minecraft:air\"then actual[#actual+1]={index=index,name=value.name}end end table.sort(actual,function(a,b)return a.index<b.index end)if#actual~=#expected then return false,\"redstone requester retained an incomplete crafting request\"end for index,item in ipairs(actual)do if item.name~=expected[index]then return false,\"redstone requester retained different crafting ingredients\"end end return true end local function shares()return store.read(PATH,{})end local function save(s)store.write(PATH,s)end local function safeMethods(name)local out={}local available=peripheral.getMethods and peripheral.getMethods(name)or nil if available then for _,method in ipairs(available)do if SAFE[method]then out[#out+1]=method end end else for method in pairs(SAFE)do out[#out+1]=method end end table.sort(out)return out end function M.listLocal()local result={}for _,name in ipairs(peripheral.getNames())do result[#result+1]={name=name,type=peripheral.getType(name)}end return result end function M.share(name,mode)assert(peripheral.isPresent(name),\"peripheral is not present\")assert(mode==\"peer\"or mode==\"master\",\"mode must be peer or master\")local s=shares()s[name]={mode=mode,methods=SAFE}save(s)audit.log(\"local\",\"peripheral.share\",{name=name,mode=mode})end function M.unshare(name)local s=shares();s[name]=nil;save(s)audit.log(\"local\",\"peripheral.unshare\",{name=name})end function M.shareAll(mode)assert(mode==\"peer\"or mode==\"master\",\"mode must be peer or master\")local count=0 for _,item in ipairs(M.listLocal())do M.share(item.name,mode);count=count+1 end audit.log(\"local\",\"peripheral.share_all\",{mode=mode,count=count})return count end function M.unshareAll()local s,count=shares(),0 for name in pairs(s)do s[name],count=nil,count+1 end save(s)audit.log(\"local\",\"peripheral.unshare_all\",{count=count})return count end function M.describe()local s,result=shares(),{}for name,spec in pairs(s)do if peripheral.isPresent(name)then result[#result+1]={name=name,type=peripheral.getType(name),mode=spec.mode,methods=safeMethods(name)}end end return result end function M.call(peerIsMaster,name,method,args)local spec=shares()[name]if not spec or not peripheral.isPresent(name)then return false,\"not shared\"end if spec.mode==\"master\"and not peerIsMaster then return false,\"master-only peripheral\"end if not spec.methods[method]then return false,\"method not allowed\"end local api=peripheral.wrap(name)if type(api[method])~=\"function\"then return false,\"method unavailable\"end local ok,result=pcall(api[method],table.unpack(args or{}))return ok,result end function M.craftRequest(peerIsMaster,name,address,filters)local spec=shares()[name]local localAccess=peerIsMaster==\"local\"if not peripheral.isPresent(name)then return false,\"stock ticker is unavailable\"end if not localAccess and not spec then return false,\"stock ticker is not shared\"end if not localAccess and spec.mode==\"master\"and not peerIsMaster then return false,\"master-only peripheral\"end if type(address)~=\"string\"or#address<1 or#address>64 or address:find(\"[%z\\1-\\31\\127]\")then return false,\"invalid destination address\"end if type(filters)~=\"table\"or#filters<1 or#filters>32 then return false,\"invalid craft filters\"end local clean={}for index,filter in ipairs(filters)do if type(filter)~=\"table\"or type(filter.name)~=\"string\"or#filter.name>128 then return false,\"invalid item filter \"..tostring(index)end local count=tonumber(filter._requestCount or filter.count)if not count or count<1 or count>256 or count~=math.floor(count)then return false,\"invalid request count\"end clean[index]={name=filter.name,_requestCount=count}end local api=peripheral.wrap(name)if not api or type(api.requestFiltered)~=\"function\"then return false,\"stock ticker requestFiltered is unavailable\"end local ok,result=pcall(api.requestFiltered,address,table.unpack(clean))if ok then audit.log(\"network\",\"peripheral.craft_request\",{name=name,address=address,filters=#clean})end return ok,result end function M.craftingRecipeRequest(peerIsMaster,name,address,batches,grid)local spec=shares()[name]local localAccess=peerIsMaster==\"local\"if not peripheral.isPresent(name)then return false,\"redstone requester is unavailable\"end if not localAccess and not spec then return false,\"redstone requester is not shared\"end if not localAccess and spec.mode==\"master\"and not peerIsMaster then return false,\"master-only peripheral\"end if type(address)~=\"string\"or#address<1 or#address>64 or address:find(\"[%z\\1-\\31\\127]\")then return false,\"invalid craft address\"end batches=tonumber(batches)if not batches or batches<1 or batches>256 or batches~=math.floor(batches)then return false,\"invalid craft batches\"end if type(grid)~=\"table\"then return false,\"invalid crafting grid\"end local slots={}for slot=1,9 do local value=grid[slot]if value~=nil and value~=false and(type(value)~=\"string\"or#value>128)then return false,\"invalid craft grid slot\"end if type(value)==\"string\"and value:sub(1,1)==\"#\"then return false,\"Create Redstone Requester requires concrete item IDs; resolve recipe tags first\"end slots[slot]=(value==nil or value==false)and\"minecraft:air\"or value end local api=peripheral.wrap(name)if not api or type(api.setCraftingRequest)~=\"function\"or type(api.setAddress)~=\"function\"or type(api.request)~=\"function\"then return false,\"redstone requester crafting API is unavailable\"end local ok,result=pcall(function()if type(api.setConfiguration)==\"function\"then api.setConfiguration(\"strict\")end api.setCraftingRequest(batches,slots[1],slots[2],slots[3],slots[4],slots[5],slots[6],slots[7],slots[8],slots[9])api.setAddress(address)local configured=nil if type(api.getRequest)==\"function\"then configured=api.getRequest()local retained,retainError=requestMatchesGrid(configured,slots)if not retained then error(retainError)end end if type(api.getAddress)==\"function\"and api.getAddress()~=address then error(\"redstone requester did not retain the craft address\")end local submitted=api.request()if submitted==false then error(\"redstone requester rejected the crafting request\")end return{submitted=true,strict=type(api.setConfiguration)==\"function\",configured=configured~=nil,address=address}end)if ok then audit.log(\"network\",\"peripheral.crafting_recipe_request\",{name=name,address=address,batches=batches})end return ok,result end return M",
  ["ceetos/lib/telemetry.lua"] = "local store=require(\"ceetos.lib.store\")local M={}local PATH=\"/ceetos/data/config.lua\"local activity=\"desktop\"local function text(value,limit)if type(value)~=\"string\"then return nil end value=value:gsub(\"[%z\\1-\\31\\127]\",\" \")if value==\"\"then return nil end return value:sub(1,limit)end local function config()local value=store.read(PATH,{})if type(value)~=\"table\"then value={}end if value.telemetry==nil then value.telemetry=true store.write(PATH,value)end return value end function M.setEnabled(value)assert(type(value)==\"boolean\",\"telemetry state must be boolean\")require(\"ceetos.lib.auth\").require(\"admin\")local valueForSave=config()valueForSave.telemetry=value return store.write(PATH,valueForSave)end function M.status()return config().telemetry==true end function M.configuration()return{enabled=M.status()}end function M.markActivity(value)activity=text(value,48)or activity return activity end function M.activity()return activity end function M.snapshot(currentActivity)if currentActivity then M.markActivity(currentActivity)end local data={ts=os.epoch(\"utc\"),id=os.getComputerID(),label=text(os.getComputerLabel(),96),activity=activity,}if turtle and type(turtle.getFuelLevel)==\"function\"then local ok,fuel=pcall(turtle.getFuelLevel)if ok and type(fuel)==\"number\"then data.fuel=fuel end end if gps and type(gps.locate)==\"function\"then local ok,x,y,z=pcall(gps.locate,0.2)if ok and type(x)==\"number\"and type(y)==\"number\"and type(z)==\"number\"then data.gps={x=x,y=y,z=z}end end return data end return M",
  ["ceetos/lib/cloud.lua"] = "local store=require(\"ceetos.lib.store\")local password=require(\"ceetos.lib.password\")local profile=require(\"ceetos.lib.profile\")local M={}M.PATH=\"/ceetos/data/cloud.lua\"M.MAX_BODY=48*1024 M.MAX_RESPONSE=64*1024 M.DEFAULTS={auth=\"https://auth.ceet.uk\",recipe=\"https://recipe.ceet.uk\",dashboard=\"https://dash.ceet.uk\",}local function now()return os.epoch(\"utc\")end local function validUrl(value)if type(value)~=\"string\"or#value>160 then return false end return value:match(\"^https://[%w%-%.]+%.ceet%.uk$\")~=nil end local function validId(value)return type(value)==\"string\"and value:match(\"^[%w_.%-]+$\")~=nil and#value<=96 end local function copy(value)local out={}for key,item in pairs(value or{})do out[key]=item end return out end local function normalise(value)value=type(value)==\"table\"and value or{}local urls=type(value.urls)==\"table\"and value.urls or{}local result={schema=1,enabled=value.enabled==true,urls={auth=validUrl(urls.auth)and urls.auth or M.DEFAULTS.auth,recipe=validUrl(urls.recipe)and urls.recipe or M.DEFAULTS.recipe,dashboard=validUrl(urls.dashboard)and urls.dashboard or M.DEFAULTS.dashboard,},node=type(value.node)==\"table\"and copy(value.node)or nil,}if result.node and(not validId(result.node.id)or type(result.node.secret)~=\"string\"or#result.node.secret<32 or#result.node.secret>192)then result.node=nil end return result end function M.load()store.invalidate(M.PATH)return normalise(store.read(M.PATH,{}))end function M.save(value)local clean=normalise(value)return store.write(M.PATH,clean)end function M.configure(urls)local value=M.load()urls=type(urls)==\"table\"and urls or{}for key in pairs(M.DEFAULTS)do if urls[key]~=nil then if not validUrl(urls[key])then return false,\"invalid \"..key..\" cloud URL\"end value.urls[key]=urls[key]end end return M.save(value)end function M.clear()local value=M.load();value.enabled,value.node=false,nil return M.save(value)end function M.publicStatus()local value=M.load()return{enabled=value.enabled,enrolled=value.node~=nil,node=value.node and value.node.id or nil,urls=copy(value.urls),profile=profile.id()}end local function readBounded(handle,limit)local chunks,total={},0 while true do local part=handle.read(math.min(4096,limit-total+1))if not part or part==\"\"then break end total=total+#part if total>limit then return nil,\"cloud response is too large\"end chunks[#chunks+1]=part end return table.concat(chunks)end local function json(value)local ok,result=pcall(textutils.unserialiseJSON,value)return ok and type(result)==\"table\"and result or nil end local function canonical(node,timestamp,nonce,method,path,body)local digest=assert(password.sha256(body))return table.concat({\"ceetos-cloud-node-v1\",node,tostring(timestamp),nonce,method,path,digest},\"\\n\")end local nonceCounter=0 local function nonce()nonceCounter=nonceCounter+1 return password.newSalt(\"cloud:\"..tostring(nonceCounter))end local function perform(url,method,path,body,headers)if not http or type(http.post)~=\"function\"then return nil,\"HTTP is unavailable\"end local response local ok,err=pcall(function()response=http.post(url..path,body,headers)end)if not ok or not response then return nil,tostring(err or\"cloud request failed\")end local raw,readErr=readBounded(response,M.MAX_RESPONSE)pcall(response.close)if not raw then return nil,readErr end local decoded=json(raw)if not decoded then return nil,\"cloud returned invalid JSON\"end if decoded.ok==false then return nil,tostring(decoded.error or\"cloud rejected request\"):sub(1,180)end return decoded end function M.enroll(code)if type(code)~=\"string\"or#code<12 or#code>128 or code:find(\"[%z\\1-\\31\\127]\")then return nil,\"invalid enrollment code\"end local value=M.load()local payload=textutils.serialiseJSON({code=code,profile=profile.id(),label=os.getComputerLabel()or(\"Computer \"..tostring(os.getComputerID())),computerId=tostring(os.getComputerID())})if#payload>M.MAX_BODY then return nil,\"enrollment request is too large\"end local result,err=perform(value.urls.auth,\"POST\",\"/v1/nodes/enroll\",payload,{[\"Content-Type\"]=\"application/json\"})if not result then return nil,err end if type(result.node)~=\"table\"or not validId(result.node.id)or type(result.node.secret)~=\"string\"or#result.node.secret<32 then return nil,\"cloud returned invalid enrollment\"end value.enabled,value.node=true,{id=result.node.id,secret=result.node.secret,enrolledAt=now()}local saved,saveErr=M.save(value)if not saved then return nil,saveErr or\"could not save cloud enrollment\"end return M.publicStatus()end function M.call(service,path,payload)local value=M.load()if not value.enabled or not value.node then return nil,\"cloud node is not enrolled\"end if not M.DEFAULTS[service]or type(path)~=\"string\"or not path:match(\"^/v1/[%w%-%._/]+$\")or#path>128 then return nil,\"invalid cloud endpoint\"end local body=textutils.serialiseJSON(type(payload)==\"table\"and payload or{})if#body>M.MAX_BODY then return nil,\"cloud request is too large\"end local timestamp,requestNonce=now(),nonce()local signature=password.hmacSha256(value.node.secret,canonical(value.node.id,timestamp,requestNonce,\"POST\",path,body))if not signature then return nil,\"could not sign cloud request\"end return perform(value.urls[service],\"POST\",path,body,{[\"Content-Type\"]=\"application/json\",[\"X-CeetOS-Node\"]=value.node.id,[\"X-CeetOS-Time\"]=tostring(timestamp),[\"X-CeetOS-Nonce\"]=requestNonce,[\"X-CeetOS-Signature\"]=signature,})end return M",
  ["ceetos/lib/cloud_sync.lua"] = "local cloud=require(\"ceetos.lib.cloud\")local store=require(\"ceetos.lib.store\")local password=require(\"ceetos.lib.password\")local profile=require(\"ceetos.lib.profile\")local telemetryService=require(\"ceetos.lib.telemetry\")local RECIPE_SERVICE_MODULE=\"ceetos.lib.\"..\"recipe_service\"local M={}local STATE=\"/ceetos/data/cloud-state.lua\"local INTERVALS={telemetry=24*60*60*1000,authority=30000,recipes=30000}local TELEMETRY_RETRIES={15*60*1000,60*60*1000,4*60*60*1000}local function now()return os.epoch(\"utc\")end local function defaults()return{schema=2,revision=0,auth={online=false,next=0},recipe={online=false,next=0,revision=0},telemetry={enabled=nil,next=0,lastSuccess=nil,failures=0,lastError=nil},lastError=nil}end local function state()store.invalidate(STATE)local value=store.read(STATE,defaults())if type(value)~=\"table\"then value=defaults()end if type(value.auth)~=\"table\"then value.auth={}end if type(value.recipe)~=\"table\"then value.recipe={}end if type(value.telemetry)~=\"table\"then value.telemetry={}end for key,fallback in pairs(defaults())do if value[key]==nil then value[key]=fallback end end for key,fallback in pairs(defaults().recipe)do if value.recipe[key]==nil then value.recipe[key]=fallback end end for key,fallback in pairs(defaults().telemetry)do if value.telemetry[key]==nil then value.telemetry[key]=fallback end end return value end local function save(value)value.revision=(tonumber(value.revision)or 0)+1 return store.write(STATE,value)end local function errorState(value,message)value.lastError=tostring(message or\"cloud request failed\"):sub(1,180)end function M.status()local value,cfg=state(),cloud.publicStatus()return{enabled=cfg.enabled,enrolled=cfg.enrolled,node=cfg.node,urls=cfg.urls,authOnline=value.auth.online==true,recipeOnline=value.recipe.online==true,telemetryNext=tonumber(value.telemetry and value.telemetry.next)or 0,telemetryInterval=INTERVALS.telemetry,telemetryEnabled=telemetryService.status(),telemetryLastSuccess=value.telemetry and value.telemetry.lastSuccess or nil,telemetryLastError=value.telemetry and value.telemetry.lastError or nil,telemetryFailures=math.max(0,math.floor(tonumber(value.telemetry and value.telemetry.failures)or 0)),lastSync=value.lastSync,lastError=value.lastError,}end function M.configure(urls)return cloud.configure(urls)end function M.enroll(code)local enrolled,err=cloud.enroll(code)if not enrolled then return nil,err end local value=state()value.telemetry.next,value.telemetry.failures,value.telemetry.lastError=0,0,nil save(value)return enrolled end function M.clear()local ok,err=cloud.clear();if ok then store.write(STATE,defaults())end return ok,err end function M.authOnline()return M.status().authOnline==true end function M.recipeOnline()return M.status().recipeOnline==true end local function cloudAuthority(result)local auth=require(\"ceetos.lib.auth\")if type(result)~=\"table\"or type(result.directory)~=\"table\"then return false,\"invalid cloud authority response\"end local cfg=cloud.publicStatus()local record={id=\"cloud:\"..tostring(cfg.urls.auth),term=tonumber(result.term)or 0,revision=tonumber(result.revision)or 0,directory=result.directory}return pcall(auth.acceptAuthority,record)end function M.login(name,plainPassword)if type(name)~=\"string\"or type(plainPassword)~=\"string\"then return false,\"invalid credentials\"end local begin,beginErr=cloud.call(\"auth\",\"/v1/auth/login/begin\",{username=name,node=tostring(os.getComputerID())})if not begin then return false,beginErr end if type(begin.salt)~=\"string\"or type(begin.workFactor)~=\"number\"or type(begin.challenge)~=\"string\"or type(begin.expires)~=\"number\"then return false,\"invalid cloud login challenge\"end local verifier,deriveErr=password.derive(plainPassword,begin.salt,begin.workFactor)if not verifier then return false,deriveErr end local proof=password.hmacSha256(verifier,table.concat({\"ceetos/auth/login/v1\",tostring(begin.authority),tostring(os.getComputerID()),tostring(begin.requestId),tostring(begin.challenge),tostring(begin.expires)},\"|\"))local result,resultErr=cloud.call(\"auth\",\"/v1/auth/login/proof\",{username=name,node=tostring(os.getComputerID()),requestId=begin.requestId,challenge=begin.challenge,proof=proof})if not result then return false,resultErr end local auth=require(\"ceetos.lib.auth\")local saved,saveErr=auth.saveCentralSession(result.session)if not saved then return false,saveErr end if type(result.directory)==\"table\"then auth.updateDirectory(result.directory,result.revision)end return true end function M.mutate(action,fields)local auth=require(\"ceetos.lib.auth\")local current=auth.refreshSession()if not current or not current.central then return false,\"cloud login is required\"end local result,err=cloud.call(\"auth\",\"/v1/auth/mutate\",{action=action,fields=fields,session=current.nonce,node=tostring(os.getComputerID()),revision=current.accountRevision})if not result then return false,err end if type(result.directory)==\"table\"then auth.updateDirectory(result.directory,result.revision)end return true end function M.recipePlan(item,quantity,stock)if not M.recipeOnline()then return nil,\"cloud Recipe Server is unavailable\"end local result,err=cloud.call(\"recipe\",\"/v1/recipe/plan\",{item=item,quantity=quantity,stock=stock})if not result then return nil,err end return result.plan,result.error end local function telemetry()local snapshot=telemetryService.snapshot()local net=require(\"ceetos.lib.net\")local transport=net.statusSnapshot and net.statusSnapshot().transport or{}snapshot.health={profile=profile.id(),version=require(\"ceetos.lib.version\").string,uptime=os.clock(),freeSpace=fs.getFreeSpace(\"/\"),peers=#(net.peers and net.peers()or{}),healthyLinks=transport and transport.healthyLinks or 0,lastError=M.status().lastError,}local result,err=cloud.call(\"dashboard\",\"/v1/telemetry/ingest\",snapshot)return result~=nil,err end local function syncAuth()if profile.is(\"auth-server\")then local auth=require(\"ceetos.lib.auth\")local snapshot=auth.authoritySnapshot()local pushed,pushErr=cloud.call(\"auth\",\"/v1/auth/replica/merge\",{snapshot=snapshot,source=\"mesh\"})if not pushed then return false,pushErr end if type(pushed.snapshot)==\"table\"then auth.merge(pushed.snapshot,true)end local ok,authErr=cloudAuthority(pushed)if not ok then return false,authErr end return true end local result,err=cloud.call(\"auth\",\"/v1/auth/directory\",{})if not result then return false,err end local ok,authErr=cloudAuthority(result)if not ok then return false,authErr end return true end local function syncRecipes()if not profile.is(\"recipe-server\")then local result,err=cloud.call(\"recipe\",\"/v1/recipe/status\",{})return result~=nil,err end local service=require(RECIPE_SERVICE_MODULE)if type(service.exportOverlay)~=\"function\"then return false,\"recipe export unavailable\"end local payload,exportErr=service.exportOverlay()if not payload then return false,exportErr end local value=state()value.recipe=value.recipe or{revision=0}local result,err=cloud.call(\"recipe\",\"/v1/recipe/replica/merge\",{overlay=payload,baseRevision=math.max(0,math.floor(tonumber(value.recipe.revision)or 0)),})if not result then return false,err end if type(result.overlay)==\"table\"and type(service.replaceOverlay)==\"function\"then local applied,applyErr=service.replaceOverlay(result.overlay)if not applied then return false,applyErr end end return true,nil,math.max(0,math.floor(tonumber(result.revision)or 0))end function M.tick(activity)local cfg=cloud.publicStatus();if not cfg.enabled or not cfg.enrolled then return false,\"cloud node is not enrolled\"end local value,timestamp=state(),now()local changed=false if timestamp>=(tonumber(value.auth.next)or 0)then local ok,err=syncAuth();value.auth.online,value.auth.next=ok==true,timestamp+INTERVALS.authority if not ok then errorState(value,err)else value.lastError=nil end changed=true end if timestamp>=(tonumber(value.recipe.next)or 0)then local ok,err,recipeRevision=syncRecipes();value.recipe.online,value.recipe.next=ok==true,timestamp+INTERVALS.recipes if recipeRevision~=nil then value.recipe.revision=recipeRevision end if not ok then errorState(value,err)end changed=true end local telemetryEnabled=telemetryService.status()if not telemetryEnabled then if value.telemetry.enabled~=false or value.telemetry.next~=0 then value.telemetry.enabled,value.telemetry.next,value.telemetry.failures,value.telemetry.lastError=false,0,0,nil changed=true end elseif value.telemetry.enabled~=true then value.telemetry.enabled,value.telemetry.next,value.telemetry.failures,value.telemetry.lastError=true,0,0,nil changed=true elseif timestamp>=(tonumber(value.telemetry.next)or 0)then local ok,err=telemetry()if ok then value.telemetry.next,value.telemetry.lastSuccess,value.telemetry.failures,value.telemetry.lastError=timestamp+INTERVALS.telemetry,timestamp,0,nil else local failures=math.max(0,math.floor(tonumber(value.telemetry.failures)or 0))+1 value.telemetry.failures,value.telemetry.lastError=failures,tostring(err or\"telemetry upload failed\"):sub(1,180)value.telemetry.next=timestamp+(TELEMETRY_RETRIES[failures]or INTERVALS.telemetry)errorState(value,value.telemetry.lastError)end changed=true end if changed then value.lastSync=timestamp;save(value)end return true end return M",
  ["ceetos/lib/owner_service.lua"] = "local store=require(\"ceetos.lib.store\")local password=require(\"ceetos.lib.password\")local telemetry=require(\"ceetos.lib.telemetry\")local M={}local PATH=\"/ceetos/data/owner-service.lua\"M.VERSION=1 M.MAX_AGE_MS=60*1000 M.MAX_USED_NONCES=64 local actions={snapshot=true,status=true}local function now()return os.epoch(\"utc\")end local function state()local value=store.read(PATH,{})if type(value)~=\"table\"then value={}end if value.enabled==nil then value.enabled=true end value.version=M.VERSION if type(value.used)~=\"table\"then value.used={}end return value end local function save(value)return store.write(PATH,value)end local function validToken(token)return type(token)==\"string\"and#token>=32 and#token<=128 and not token:find(\"[%z\\1-\\31\\127]\")end local function validId(value)return type(value)==\"string\"and value:match(\"^[%w_%-]+$\")and#value>=8 and#value<=96 end local function validNonce(value)return type(value)==\"string\"and value:match(\"^[%x]+$\")and#value>=16 and#value<=128 end local function canonical(node,request)return table.concat({\"ceetos-owner-service-v1\",tostring(node),tostring(request.id),tostring(request.action),tostring(math.floor(tonumber(request.ts)or-1)),tostring(request.nonce),},\"\\n\")end local function prune(value,time)local kept,rows={},{}for nonce,expires in pairs(value.used or{})do expires=tonumber(expires)if validNonce(nonce)and expires and expires>time then rows[#rows+1]={nonce=nonce,expires=expires}end end table.sort(rows,function(a,b)return a.expires>b.expires end)for index,row in ipairs(rows)do if index<=M.MAX_USED_NONCES then kept[row.nonce]=row.expires end end value.used=kept end function M.status()local value=state()prune(value,now())return{enabled=value.enabled~=false,provisioned=validToken(value.token),owner=type(value.owner)==\"string\"and value.owner or nil,actions={\"snapshot\",\"status\"},}end function M.setEnabled(enabled)local value=state();value.enabled=enabled==true;prune(value,now());save(value)return M.status()end function M.provision(token,owner)assert(validToken(token),\"owner-service token must be 32-128 printable characters\")assert(type(owner)==\"string\"and owner:match(\"^[%w_%-]+$\")and#owner<=32,\"invalid owner\")local value=state()value.token,value.owner,value.enabled,value.used=token,owner,true,{}assert(save(value),\"could not save owner-service configuration\")return M.status()end function M.rotate(owner)local token=password.newSalt(\"owner-service-a\")..password.newSalt(\"owner-service-b\")M.provision(token,owner)return token end function M.signature(token,node,request)assert(validToken(token),\"invalid owner-service token\")return assert(password.hmacSha256(token,canonical(node,request)))end function M.verify(request)if type(request)~=\"table\"then return false,\"service request must be an object\"end local value,time=state(),now()prune(value,time)if value.enabled==false then return false,\"owner service is disabled\"end if not validToken(value.token)then return false,\"owner service has not been provisioned\"end if not validId(request.id)or not actions[request.action]or not validNonce(request.nonce)then return false,\"invalid service request\"end local timestamp=tonumber(request.ts)if not timestamp or math.floor(timestamp)~=timestamp or math.abs(time-timestamp)>M.MAX_AGE_MS then return false,\"service request expired\"end if value.used[request.nonce]then return false,\"service request was already used\"end if type(request.tag)~=\"string\"or not request.tag:match(\"^[%x]+$\")or#request.tag~=64 then return false,\"invalid service authenticator\"end local expected=M.signature(value.token,os.getComputerID(),request)if not password.constantTimeEqual(expected,request.tag:lower())then return false,\"service authentication failed\"end value.used[request.nonce]=timestamp+M.MAX_AGE_MS prune(value,time)assert(save(value),\"could not persist service replay state\")return true,value end function M.dispatch(request)local ok,value=M.verify(request)if not ok then return false,value end if request.action==\"snapshot\"then return true,{action=\"snapshot\",telemetry=telemetry.snapshot(\"owner-service\"),owner=value.owner}end return true,{action=\"status\",service=M.status(),telemetryEnabled=telemetry.status()}end return M",
  ["ceetos/lib/gui.lua"] = "local M={}local store=require(\"ceetos.lib.store\")local terminalUi=require(\"ceetos.lib.terminal_ui\")M.pages={home=\"Desktop\",peers=\"Peers\",peripherals=\"Devices\",telemetry=\"Telemetry\",updates=\"Updates\",admin=\"Administration\",audit=\"Audit log\",jobs=\"Jobs\",files=\"Explorer\"}local function add(items,allowed,item)if allowed then items[#items+1]=item end end local function role(deps,required)return deps.auth.allowed(required)end local function colour(item)if item.kind==\"directory\"then return colors.lightBlue end if item.kind==\"program\"then return colors.lime end if item.kind==\"file\"then return colors.white end return colors.lightGray end local function system(id,label)return{id=id,label=label,kind=\"system\",action=id}end local function count(value)if type(value)~=\"table\"then return 0 end local total=0 for _ in pairs(value)do total=total+1 end return total end local function entries(value)if type(value)~=\"table\"then return{}end local out={}for key,item in pairs(value)do if type(item)==\"table\"then local copy={}for field,fieldValue in pairs(item)do copy[field]=fieldValue end copy._ceetosKey=tostring(key)item=copy else item={value=item,_ceetosKey=tostring(key)}end out[#out+1]=item end table.sort(out,function(left,right)return tostring(left.name or left.id or left._ceetosKey)<tostring(right.name or right.id or right._ceetosKey)end)return out end local function short(value,limit)value=terminalUi.clean(value or\"-\")return#value>limit and value:sub(1,math.max(1,limit-3))..\"...\"or value end function M.newState()return{selected=nil,desktopPage=1,menu=nil,path=\"/\",history={},trash=false,peripheralScroll=1}end function M.model(page,deps,state)state=state or M.newState()local items,lines={},{}local auth,net,peripherals,telemetry,cloud=deps.auth,deps.net,deps.peripherals,deps.telemetry,deps.cloud local account=auth.current and(auth.current.name..\" (\"..auth.current.role..\")\")or\"not logged in\"local liveNetwork=store.read(\"/ceetos/data/network-status.lua\",{})local visiblePeers=liveNetwork.peers or net.peers()local craftState=store.read(\"/ceetos/data/crafting-state.lua\",{})local craftSources=craftState.sources or{}local selectedTicker=craftState.config and craftState.config.ticker local craftingAvailable=selectedTicker~=nil or#(craftSources.tickers or{})>0 if not craftingAvailable and peripheral and peripheral.getNames then for _,name in ipairs(peripheral.getNames())do if tostring(peripheral.getType(name)or\"\"):lower():find(\"stockticker\",1,true)then craftingAvailable=true;break end end end if page==\"home\"then add(items,role(deps,\"operator\"),system(\"terminal\",\"Terminal\"))if role(deps,\"viewer\")then for _,program in ipairs(deps.files.programs())do items[#items+1]={id=\"file:\"..program.path,label=program.name,kind=\"program\",path=program.path,runnable=true,canRun=true,canModify=role(deps,\"operator\"),protected=program.protected,action=\"run:\"..program.path}end end if craftingAvailable then items[#items+1]=system(\"crafting\",\"Crafting\")end if role(deps,\"operator\")then items[#items+1]=system(\"page:files\",\"Files\")items[#items+1]=system(\"page:peers\",\"Peers\")items[#items+1]=system(\"page:peripherals\",\"Devices\")items[#items+1]=system(\"page:telemetry\",\"Telemetry\")items[#items+1]=system(\"page:jobs\",\"Jobs\")items[#items+1]=system(\"page:updates\",\"Updates\")end items[#items+1]=system(\"page:admin\",\"Admin\")return{page=page,title=\"CeetOS Desktop\",desktop=true,items=items,subtitle=account..\"  |  \"..#visiblePeers..\" network peers  |  \"..#peripherals.describe()..\" shared  |  telemetry \"..(telemetry.status()and\"on\"or\"off\"),}elseif page==\"files\"then local source=state.trash and deps.files.trashList()or deps.files.list(state.path)for _,entry in ipairs(source)do local kind=entry.directory and\"directory\"or(entry.runnable and\"program\"or\"file\")items[#items+1]={id=(entry.trashed and\"trash:\"..entry.id or\"file:\"..entry.path),label=entry.name,kind=kind,path=entry.path,original=entry.original,trashId=entry.id,parent=entry.parent,directory=entry.directory,runnable=entry.runnable,protected=entry.protected,trashed=entry.trashed,canRun=role(deps,\"viewer\"),canModify=role(deps,\"operator\"),action=entry.parent and\"up:\"..entry.path or(entry.directory and\"dir:\"..entry.path or(entry.runnable and role(deps,\"viewer\")and\"run:\"..entry.path or nil)),}end return{page=page,title=\"CeetOS Explorer\",items=items,path=state.trash and\"Trash\"or state.path,trash=state.trash}elseif page==\"peers\"then local live=liveNetwork local diag=live.discovery or(net.discoveryStatus and net.discoveryStatus()or{})local session,transport=diag.session,diag.transport or live.transport or{}local peerList,directCount,routedCount,rekeyCount=visiblePeers,0,0,0 for _,peer in ipairs(peerList)do if peer.routed then routedCount=routedCount+1 else directCount=directCount+1 end if peer.rekeyRequired then rekeyCount=rekeyCount+1 end end local discoveryActive=diag.active==true or session~=nil local discoveryState=discoveryActive and tostring((session and session.state)or diag.state or\"inactive\")or\"inactive\"local discoveryText=\"Discovery: \"..discoveryState if session and tonumber(session.expires)then local remaining=math.max(0,math.ceil((tonumber(session.expires)-os.epoch(\"utc\"))/1000))discoveryText=discoveryText..\" (\"..tostring(remaining)..\"s remaining)\"end if session and session.retries then discoveryText=discoveryText..\" (retries \"..tostring(session.retries)..\")\"end if session and session.candidate then discoveryText=discoveryText..\" - candidate \"..tostring(session.candidate.label or session.candidate.id)end local modemText=transport.wireless and(\"wireless links: \"..tostring(transport.wirelessLinkCount or 1))or\"no wireless modem\"local mesh=transport.mesh or{}lines={\"Network peers: \"..(directCount+routedCount)..\" (\"..directCount..\" direct, \"..routedCount..\" routed)\",discoveryText,modemText,\"Protocol: v\"..tostring(live.protocol or transport.protocol or 2)..\" | Rekey required: \"..tostring(rekeyCount),\"Links: \"..tostring(transport.healthyLinks or 0)..\" healthy / \"..tostring(transport.degradedLinks or 0)..\" degraded / \"..tostring(transport.offlineLinks or 0)..\" offline\",\"Mesh: \"..(mesh.enrolled and(\"enrolled e\"..tostring(mesh.epoch))or\"enrollment pending\"),\"Last receive distance: \"..tostring(transport.lastDistance or\"-\")}for _,peer in ipairs(peerList)do local kind=peer.routed and\"Routed\"or\"Direct\"local route=peer.routed and(\" via \"..tostring(peer.next or\"?\")..\" (\"..tostring(peer.hops or\"?\")..\" hop)\")or(peer.auto and\" mesh edge\"or\"\")lines[#lines+1]=kind..\": \"..tostring(peer.label or(\"Computer \"..tostring(peer.id)))..\" (\"..tostring(peer.id)..\")\"..route..\" [\"..tostring(peer.health or\"unknown\")..\"]\"end if not discoveryActive and diag.lastState and diag.lastState~=\"inactive\"then lines[#lines+1]=\"Previous discovery: \"..tostring(diag.lastState)..(diag.lastMessage and(\" - \"..tostring(diag.lastMessage))or\"\")elseif diag.message then lines[#lines+1]=\"Network: \"..tostring(diag.message)end local canBegin=not discoveryActive add(items,role(deps,\"operator\")and canBegin,system(\"start_discovery\",\"Start discovery\"))add(items,role(deps,\"operator\")and canBegin,system(\"join_discovery\",\"Join discovery\"))add(items,role(deps,\"operator\")and discoveryState==\"candidate\",system(\"confirm_discovery\",\"Confirm pairing\"))add(items,role(deps,\"operator\")and not canBegin,system(\"cancel_discovery\",\"Cancel discovery\"))add(items,role(deps,\"operator\"),system(\"remote_refresh\",\"Refresh remote peripherals\"))elseif page==\"peripherals\"then local shared={}for _,item in ipairs(peripherals.describe())do shared[item.name]=item.mode end local detected=peripherals.listLocal()lines={\"Detected devices: \"..#detected,\"Shared devices: \"..#peripherals.describe()}if not state.peripheralView then add(items,role(deps,\"operator\"),system(\"peripheral_view\",\"View peripherals\"))end for _,item in ipairs(detected)do local mode=shared[item.name]items[#items+1]={id=\"peripheral_check:\"..item.name..\":peer\",name=item.name,label=item.name,type=item.type,kind=\"peripheral\",sharedMode=mode,mode=\"peer\",checked=mode==\"peer\",toggle=true,action=\"peripheral_set:\"..item.name..\":peer\"}items[#items+1]={id=\"peripheral_check:\"..item.name..\":master\",name=item.name,label=item.name,type=item.type,kind=\"peripheral\",sharedMode=mode,mode=\"master\",checked=mode==\"master\",toggle=true,action=\"peripheral_set:\"..item.name..\":master\"}end add(items,role(deps,\"operator\"),system(\"share_all:peer\",\"Share all - peers\"))add(items,role(deps,\"operator\"),system(\"share_all:master\",\"Share all - master only\"))add(items,role(deps,\"operator\"),system(\"unshare_all\",\"Unshare all\"))add(items,role(deps,\"operator\"),system(\"remote_cache\",\"View remote cache\"))add(items,role(deps,\"operator\"),system(\"remote_call\",\"Call remote peripheral\"))local shown={}for _,entry in ipairs(items)do local checkbox=entry.id:sub(1,17)==\"peripheral_check:\"local bulk=entry.action==\"share_all:peer\"or entry.action==\"share_all:master\"or entry.action==\"unshare_all\"if state.peripheralView or(not checkbox and not bulk)then shown[#shown+1]=entry end end items=shown elseif page==\"telemetry\"then local c=telemetry.configuration()local cloudStatus=cloud and cloud.status and cloud.status()or{}lines={\"Telemetry: \"..(c.enabled and\"enabled\"or\"disabled\"),\"Cloud node: \"..(cloudStatus.enrolled and(\"enrolled as \"..tostring(cloudStatus.node))or\"not enrolled\"),\"Cloud auth: \"..(cloudStatus.authOnline and\"online\"or\"offline\")..\" | recipes: \"..(cloudStatus.recipeOnline and\"online\"or\"offline\"),cloudStatus.enrolled and(\"Last report: \"..tostring(cloudStatus.telemetryLastSuccess or\"pending\")..\" | next: \"..tostring(cloudStatus.telemetryNext or\"pending\"))or\"Enroll this computer before it can appear on dash.ceet.uk.\",cloudStatus.telemetryLastError and(\"Telemetry error: \"..short(cloudStatus.telemetryLastError,58))or\"Cloud telemetry uploads daily and does not block this UI.\",}add(items,role(deps,\"admin\"),system(\"telemetry_toggle\",c.enabled and\"Disable telemetry\"or\"Enable telemetry\"))add(items,role(deps,\"admin\")and not cloudStatus.enrolled,system(\"cloud_enroll\",\"Enroll this computer with CeetOS Cloud\"))add(items,role(deps,\"operator\")and cloudStatus.enrolled,system(\"cloud_retry\",\"Retry cloud sync now\"))add(items,role(deps,\"admin\")and cloudStatus.enrolled,system(\"cloud_clear\",\"Remove cloud enrollment\"))elseif page==\"updates\"then local update=store.read(\"/ceetos/data/update-status.lua\",{})local cache,transfer=update.cache,update.transfer lines={\"Installed: \"..tostring(update.version or\"unknown\")..\"  |  \"..tostring(update.status or\"idle\"),update.message and short(update.message,72)or\"Only locally confirmed signed releases can be applied.\",cache and(\"Verified cache: \"..tostring(cache.version)..\"  \"..tostring(cache.fingerprint or\"-\")..\"  key \"..tostring(cache.keyId or\"-\"))or\"Verified cache: none\",transfer and(\"Downloading: \"..tostring(transfer.received or 0)..\"/\"..tostring(transfer.size or\"?\")..\" bytes from \"..tostring(transfer.label or transfer.source))or\"No active download\",}add(items,role(deps,\"operator\"),system(\"update_check\",\"Check for signed releases\"))for _,offer in ipairs(update.offers or{})do local route=offer.transport==\"cloud\"and\"cloud\"or(offer.transport==\"routed\"and\"routed\"or\"direct\")items[#items+1]={id=\"update-source:\"..tostring(offer.key or offer.id),label=\"Download \"..tostring(offer.version)..\" from \"..short(offer.label or offer.id,18)..\" (\"..route..\")\",kind=\"update\",action=\"update_download:\"..tostring(offer.key or offer.id),offer=offer}end add(items,role(deps,\"operator\")and transfer~=nil,system(\"update_cancel\",\"Cancel download\"))add(items,role(deps,\"operator\")and cache~=nil,system(\"update_apply\",\"Apply verified cached release\"))add(items,role(deps,\"operator\")and cache~=nil and transfer==nil,system(\"update_clear\",\"Clear release cache\"))elseif page==\"admin\"then lines={\"Session: \"..account}add(items,auth.current==nil,system(\"login\",\"Login\"))add(items,auth.current~=nil,system(\"logout\",\"Logout\"))if role(deps,\"operator\")then for _,user in ipairs(auth.list())do items[#items+1]={id=\"account:\"..user.name,label=user.name..\"  (\"..user.role..\")\",kind=\"account\",name=user.name,userRole=user.role,canGrantAdmin=role(deps,\"admin\"),active=auth.current and auth.current.name==user.name}end add(items,true,system(\"user_add\",\"Create user\"))add(items,true,system(\"recovery_enable\",\"Enable recovery window\"))add(items,true,system(\"recovery_reset\",\"Recovery reset\"))add(items,true,system(\"page:audit\",\"View audit log\"))add(items,true,system(\"page:jobs\",\"Jobs\"))end elseif page==\"audit\"then lines={\"Latest audit events:\"}for _,event in ipairs(deps.audit.recent(10))do lines[#lines+1]=event.actor..\" - \"..event.action end elseif page==\"jobs\"then store.invalidate(\"/ceetos/data/jobs.lua\")store.invalidate(\"/ceetos/data/job-workers.lua\")local jobState=store.read(\"/ceetos/data/jobs.lua\",{})local workerState=store.read(\"/ceetos/data/job-workers.lua\",{})local controller=jobState.controllerId or jobState.masterId or workerState.controllerId or workerState.masterId local workers=workerState.workers or jobState.workers or{}local queue=jobState.queue or{}local schedules=jobState.schedules or{}local history=jobState.history or jobState.results or{}lines={\"Controller: \"..tostring(controller or\"electing / unavailable\"),\"Workers: \"..count(workers)..\"  |  Queue: \"..count(queue),\"Schedules: \"..count(schedules)..\"  |  Recent results: \"..count(history),role(deps,\"admin\")and\"Administrator view: scheduler controls are available through nx jobs.\"or\"Operator view: scheduler state is read-only.\",}for _,worker in ipairs(entries(workers))do local name=worker.label or worker.name or worker.id or worker._ceetosKey local active=worker.inFlight or worker.active or 0 local capacity=worker.capacity or 1 local health=worker.available==false and\"offline\"or(worker.health or\"ready\")items[#items+1]={id=\"job-worker:\"..tostring(worker.id or worker._ceetosKey),label=\"Worker  \"..short(name,18)..\"  \"..tostring(active)..\"/\"..tostring(capacity)..\"  \"..short(health,10),kind=\"job\"}end for _,schedule in ipairs(entries(schedules))do local name=schedule.name or schedule.template or schedule.id or schedule._ceetosKey local interval=schedule.interval or schedule.every or\"once\"local status=schedule.enabled==false and\"paused\"or(schedule.status or\"scheduled\")items[#items+1]={id=\"job-schedule:\"..tostring(schedule.id or schedule._ceetosKey),label=\"Schedule  \"..short(name,17)..\"  \"..short(interval,10)..\"  \"..short(status,10),kind=\"job\"}end for _,result in ipairs(entries(history))do local name=result.template or result.name or result.jobId or result.id or result._ceetosKey local status=result.status or(result.ok==false and\"failed\"or\"complete\")local worker=result.worker or result.workerId or\"-\"items[#items+1]={id=\"job-result:\"..tostring(result.id or result._ceetosKey),label=\"Result  \"..short(name,15)..\"  \"..short(status,10)..\"  \"..short(worker,10),kind=\"job\"}end end return{page=page,title=\"CeetOS | \"..(M.pages[page]or page),items=items,lines=lines,remoteResult=page==\"peripherals\"and state.remoteResult or nil}end local function indexOf(model,id)for index,item in ipairs(model.items)do if item.id==id then return index end end end function M.selected(model,state)if#model.items==0 then return nil end local index=indexOf(model,state.selected)if not index then index=1;state.selected=model.items[1].id end return model.items[index],index end function M.select(model,state,item)if item then state.selected=item.id end return item end function M.move(model,state,direction)local _,index=M.selected(model,state)if not index then return end local delta=direction==\"left\"and-1 or direction==\"right\"and 1 or direction==\"up\"and-(model.columns or 1)or(model.columns or 1)local nextIndex=math.max(1,math.min(#model.items,index+delta))state.selected=model.items[nextIndex].id end function M.context(item)if not item or item.parent then return{}end local copy=item.label and{system(\"copy_label:\"..(item.id or\"\"),\"Copy text\")}or{}if item.kind==\"account\"then local actions={system(\"user_role:\"..item.name..\":viewer\",\"Set role: viewer\"),system(\"user_role:\"..item.name..\":operator\",\"Set role: operator\")}if item.canGrantAdmin then actions[#actions+1]=system(\"user_role:\"..item.name..\":admin\",\"Set role: admin\")end actions[#actions+1]=system(\"user_reset:\"..item.name,\"Reset password\")actions[#actions+1]=system(\"user_delete:\"..item.name,\"Delete user\")for _,action in ipairs(copy)do actions[#actions+1]=action end return actions end if item.kind==\"peripheral\"then local actions={}if item.sharedMode then actions[#actions+1]=system(\"peripheral_set:\"..item.name..\":peer\",\"Share with peers\")actions[#actions+1]=system(\"peripheral_set:\"..item.name..\":master\",\"Share with master only\")actions[#actions+1]=system(\"peripheral_unshare:\"..item.name,\"Stop sharing\")else actions[#actions+1]=system(\"peripheral_set:\"..item.name..\":peer\",\"Share with peers\")actions[#actions+1]=system(\"peripheral_set:\"..item.name..\":master\",\"Share with master only\")end return actions end if item.trashed then copy[#copy+1]=system(\"restore:\"..item.trashId,\"Restore\");copy[#copy+1]=system(\"delete_trash:\"..item.trashId,\"Delete permanently\");return copy end if not item.path then if item.action then copy[#copy+1]=system(item.action,\"Open\")end;return copy end local actions={}if item.action and(not item.runnable or item.canRun~=false)then actions[#actions+1]=system(item.action,item.directory and\"Open\"or\"Run\")end if not item.protected and item.canModify then if not item.directory then actions[#actions+1]=system(\"edit:\"..item.path,\"Edit\")end actions[#actions+1]=system(\"rename:\"..item.path,\"Rename\")actions[#actions+1]=system(\"trash:\"..item.path,\"Move to Trash\")end for _,action in ipairs(copy)do actions[#actions+1]=action end return actions end local function drawHeader(model,banner,width,height)term.setBackgroundColor(colors.black);term.setTextColor(colors.white);term.clear()terminalUi.clearLine(1,colors.blue);terminalUi.write(2,1,model.title,colors.white,colors.blue,width-2)if height>=2 then terminalUi.write(2,2,model.subtitle or model.path or\"\",colors.lightGray,colors.black,width-2)end if banner and height>=3 then terminalUi.write(2,3,banner.text,banner.error and colors.red or colors.lightGray,colors.black,width-2)end return banner and 4 or 3 end local function drawRemoteResult(result,top,width,height,targets)if not result or top>=height then return top end local pending=result.pending==true or result.status==\"pending\"local failed=result.error==true or result.ok==false or result.status==\"error\"local label=pending and\"Remote request pending\"or(failed and\"Remote request failed\"or\"Remote result\")if result.peer then label=label..\" | \"..tostring(result.peer)end if result.device then label=label..\" | \"..tostring(result.device)end if result.method then label=label..\".\"..tostring(result.method)end terminalUi.clearLine(top,failed and colors.black or colors.gray)terminalUi.write(2,top,label,failed and colors.red or colors.white,failed and colors.black or colors.gray,width-4)if not pending then local clearLabel,copyLabel=\"[Clear]\",\"[Copy]\"local clearX,copyX=width-#clearLabel-1,width-#clearLabel-#copyLabel-3 terminalUi.write(copyX,top,copyLabel,colors.lightBlue,colors.gray)terminalUi.write(clearX,top,clearLabel,colors.lightBlue,colors.gray)targets[#targets+1]={kind=\"item\",item=system(\"remote_result_copy\",\"Copy remote result\"),x1=copyX,x2=copyX+#copyLabel-1,y1=top,y2=top}targets[#targets+1]={kind=\"item\",item=system(\"remote_result_clear\",\"Clear remote result\"),x1=clearX,x2=clearX+#clearLabel-1,y1=top,y2=top}end if top+1<height then terminalUi.write(2,top+1,result.text or result.message or result.value or\"\",failed and colors.red or colors.lightGray,colors.black,width-3)end return top+2 end local function drawMenu(menu,width,height)if not menu or#menu.items==0 then return{}end local longest=0 for _,item in ipairs(menu.items)do longest=math.max(longest,#terminalUi.clean(item.label))end local boxWidth,x=math.max(8,math.min(width-2,longest+4)),math.max(1,width-math.max(8,math.min(width-2,longest+4)))local y=math.max(2,height-#menu.items-1)local targets={}for index,item in ipairs(menu.items)do local selected=index==menu.selected terminalUi.fill(x,y+index-1,boxWidth,1,selected and colors.gray or colors.black)terminalUi.write(x+1,y+index-1,item.label,selected and colors.white or colors.lightGray,selected and colors.gray or colors.black,boxWidth-2)targets[#targets+1]={kind=\"menu\",item=item,x1=x,x2=x+boxWidth-1,y1=y+index-1,y2=y+index-1}end return targets end local function drawDesktop(model,state,banner,width,height)if width<24 or height<9 then return terminalUi.minimum(model.title,\"Desktop needs 24x9\",\"Resize | Backspace\")end local top=drawHeader(model,banner,width,height)+1 local columns=math.max(2,math.floor((width-2)/14))local cellWidth,cellHeight=math.floor((width-2)/columns),4 local rows,capacity=math.max(1,math.floor((height-top-1)/cellHeight)),9 capacity=math.min(capacity,columns*rows)model.columns=columns local item,selectedIndex=M.selected(model,state)local totalPages=math.max(1,math.ceil(#model.items/capacity))state.desktopPage=math.max(1,math.min(math.floor((selectedIndex-1)/capacity)+1,totalPages))local first,last=(state.desktopPage-1)*capacity+1,math.min(#model.items,state.desktopPage*capacity)local targets={}for index=first,last do local slot,entry=index-first,model.items[index]local x,y=2+(slot%columns)*cellWidth,top+math.floor(slot/columns)*cellHeight local selected=entry.id==state.selected terminalUi.fill(x,y,cellWidth,3,selected and colors.gray or colors.black)terminalUi.write(x+1,y+1,entry.label,colour(entry),selected and colors.gray or colors.black,cellWidth-2)targets[#targets+1]={kind=\"item\",item=entry,x1=x,x2=x+cellWidth-1,y1=y,y2=y+2}end terminalUi.write(2,height,\"Arrows select | Enter open | M menu | [\"..state.desktopPage..\"/\"..totalPages..\"] | Q close\",colors.gray,colors.black,width-2)return targets end local function drawList(model,state,banner,width,height)if width<24 or height<8 then return terminalUi.minimum(model.title,\"Screen needs 24x8\",\"Resize | Backspace\")end local targets={}local top,footer=drawHeader(model,banner,width,height)+1,height-1 if model.page==\"peripherals\"then top=drawRemoteResult(model.remoteResult,top,width,footer,targets)+1 end for _,line in ipairs(model.lines or{})do if top>=footer-2 then break end terminalUi.write(2,top,line,colors.lightGray,colors.black,width-2);top=top+1 end local _,selectedIndex=M.selected(model,state)selectedIndex=selectedIndex or 1 local visible=math.max(1,footer-top)local first=math.max(1,math.min(math.max(1,#model.items-visible+1),selectedIndex-math.floor(visible/2)))model.columns=1 for row=0,visible-1 do local entry=model.items[first+row]if not entry then break end local y,selected=top+row,entry.id==state.selected terminalUi.clearLine(y,selected and colors.gray or colors.black)terminalUi.write(3,y,entry.label,colour(entry),selected and colors.gray or colors.black,width-4)targets[#targets+1]={kind=\"item\",item=entry,x1=1,x2=width,y1=y,y2=y}end local footerText if model.page==\"files\"then footerText=model.trash and\"Enter select | M menu | Backspace Explorer | E empty Trash\"or\"Enter open | M menu | N new folder | T Trash | Backspace up\"else footerText=\"Arrows select | Enter open | Backspace desktop | Q close\"end terminalUi.write(2,height,footerText,colors.gray,colors.black,width-2)return targets end local function drawPeripheralMatrix(model,state,banner,width,height)if width<36 or height<15 then return terminalUi.minimum(model.title,\"Devices matrix needs 36x15\",\"Resize | Backspace\")end local targets={}local top,footer=drawHeader(model,banner,width,height)+1,height-1 for _,line in ipairs(model.lines or{})do if top>=footer-1 then break end terminalUi.write(2,top,line,colors.lightGray,colors.black,width-2);top=top+1 end top=drawRemoteResult(model.remoteResult,top,width,footer,targets)+1 local devices,byKey={},{}for _,item in ipairs(model.items)do if item.id:sub(1,17)==\"peripheral_check:\"then if not byKey[item.name]then devices[#devices+1]={name=item.name,type=item.type or\"unknown\"};byKey[item.name]={}end byKey[item.name][item.mode]=item end end local controls={}for _,item in ipairs(model.items)do if item.kind==\"system\"and(item.action==\"share_all:peer\"or item.action==\"share_all:master\"or item.action==\"unshare_all\"or item.action==\"remote_cache\"or item.action==\"remote_call\")then controls[#controls+1]=item end end local nameX,masterX,peerX=2,width-11,width-17 local typeX=math.max(14,math.floor(width*0.45))local deviceRows=math.max(1,footer-top-#controls-2)local selectedDevice for index,device in ipairs(devices)do local row=byKey[device.name]if(row.peer and row.peer.id==state.selected)or(row.master and row.master.id==state.selected)then selectedDevice=index;break end end if selectedDevice then state.peripheralScroll=math.max(1,math.min(math.max(1,#devices-deviceRows+1),selectedDevice-math.floor(deviceRows/2)))end state.peripheralScroll=math.max(1,math.min(math.max(1,#devices-deviceRows+1),state.peripheralScroll or 1))terminalUi.write(nameX,top,\"Name\",colors.lightGray,colors.black,typeX-nameX-1)terminalUi.write(typeX,top,\"Type\",colors.lightGray,colors.black,peerX-typeX-1)terminalUi.write(peerX,top,\"Peer\",colors.lightGray,colors.black,5)terminalUi.write(masterX,top,\"Master\",colors.lightGray,colors.black,7)for row=0,deviceRows-1 do local device=devices[state.peripheralScroll+row]if not device then break end local y=top+row+1 terminalUi.write(nameX,y,device.name,colors.white,colors.black,typeX-nameX-1)terminalUi.write(typeX,y,device.type,colors.lightGray,colors.black,peerX-typeX-1)for _,mode in ipairs({\"peer\",\"master\"})do local item=byKey[device.name][mode]local selected,x=item and state.selected==item.id,mode==\"peer\"and peerX or masterX terminalUi.write(x,y,item and(item.checked and\"[x]\"or\"[ ]\")or\"   \",item and item.checked and colors.lime or colors.lightGray,selected and colors.gray or colors.black,3)if item then targets[#targets+1]={kind=\"item\",item=item,x1=x,x2=x+2,y1=y,y2=y}end end end local y=top+deviceRows+1 for _,item in ipairs(controls)do if y>=footer then break end local selected=state.selected==item.id terminalUi.clearLine(y,selected and colors.gray or colors.black)terminalUi.write(2,y,item.label,selected and colors.white or colors.lightGray,selected and colors.gray or colors.black,width-2)targets[#targets+1]={kind=\"item\",item=item,x1=1,x2=width,y1=y,y2=y}y=y+1 end terminalUi.write(2,height,\"Arrows select | Enter toggle | Click checkbox | Backspace devices\",colors.gray,colors.black,width-2)return targets end function M.draw(model,state,banner)local width,height=term.getSize()local targets=model.desktop and drawDesktop(model,state,banner,width,height)or(model.page==\"peripherals\"and state.peripheralView and drawPeripheralMatrix(model,state,banner,width,height)or drawList(model,state,banner,width,height))local menuTargets=drawMenu(state.menu,width,height)for _,target in ipairs(menuTargets)do targets[#targets+1]=target end term.setBackgroundColor(colors.black);term.setTextColor(colors.white)return targets end function M.actionFor(model,number)if model.page==\"peers\"and number==2 then return{id=\"pair_offer\",label=\"Start discovery\"}end return model.items[number]end return M",
  ["ceetos/lib/terminal_ui.lua"] = "local M={}local function size()local width,height=term.getSize()return math.max(1,width or 1),math.max(1,height or 1)end function M.clean(value)return tostring(value or\"\"):gsub(\"%c\",\" \")end function M.clip(value,width,suffix)value,width=M.clean(value),math.max(0,math.floor(tonumber(width)or 0))if width==0 then return\"\"end if#value<=width then return value end suffix=suffix==nil and\"...\"or tostring(suffix)if#suffix>=width then return suffix:sub(1,width)end return value:sub(1,width-#suffix)..suffix end function M.write(x,y,value,foreground,background,width)local terminalWidth,terminalHeight=size()x,y=math.floor(tonumber(x)or 1),math.floor(tonumber(y)or 1)if y<1 or y>terminalHeight or x>terminalWidth then return false end if x<1 then value=M.clean(value):sub(2-x)x=1 end local available=math.max(0,terminalWidth-x+1)if width~=nil then available=math.min(available,math.max(0,math.floor(width)))end if available<=0 then return false end if foreground then term.setTextColor(foreground)end if background then term.setBackgroundColor(background)end term.setCursorPos(x,y)term.write(M.clip(value,available,\"\"))return true end function M.clearLine(y,background)local width,height=size()y=math.floor(tonumber(y)or 0)if y<1 or y>height then return false end term.setCursorPos(1,y)if background then term.setBackgroundColor(background)end term.clearLine()return width>0 end function M.fill(x,y,width,height,background)local terminalWidth,terminalHeight=size()x,y=math.max(1,math.floor(tonumber(x)or 1)),math.max(1,math.floor(tonumber(y)or 1))width,height=math.max(0,math.floor(tonumber(width)or 0)),math.max(0,math.floor(tonumber(height)or 0))width,height=math.min(width,terminalWidth-x+1),math.min(height,terminalHeight-y+1)if width<=0 or height<=0 then return false end term.setBackgroundColor(background or colors.black)for row=y,y+height-1 do term.setCursorPos(x,row);term.write((\" \"):rep(width))end return true end function M.box(x1,y1,x2,y2,title,border,titleColour)local width,height=size()x1,y1=math.max(1,math.floor(x1 or 1)),math.max(1,math.floor(y1 or 1))x2,y2=math.min(width,math.floor(x2 or width)),math.min(height,math.floor(y2 or height))if x2-x1<2 or y2-y1<2 then return false end border=border or colors.gray term.setBackgroundColor(colors.black);term.setTextColor(border)M.write(x1,y1,\"+\"..(\"-\"):rep(x2-x1-1)..\"+\",border,colors.black)for row=y1+1,y2-1 do M.write(x1,row,\"|\",border,colors.black);M.write(x2,row,\"|\",border,colors.black)end M.write(x1,y2,\"+\"..(\"-\"):rep(x2-x1-1)..\"+\",border,colors.black)if title and title~=\"\"then M.write(x1+2,y1,\" \"..M.clean(title)..\" \",titleColour or colors.lightBlue,colors.black,math.max(0,x2-x1-3))end return true end function M.minimum(title,message,footer)local width,height=size()term.setBackgroundColor(colors.black);term.setTextColor(colors.white);term.clear()M.clearLine(1,colors.blue);M.write(2,1,title or\"CeetOS\",colors.white,colors.blue,width-2)M.write(2,math.max(2,math.floor(height/2)),message or\"Terminal is too small\",colors.red,colors.black,width-2)M.write(2,height,footer or\"Resize terminal or press Backspace\",colors.gray,colors.black,width-2)return{}end function M.hit(targets,x,y)for index=#(targets or{}),1,-1 do local target=targets[index]if x>=target.x1 and x<=target.x2 and y>=target.y1 and y<=target.y2 then return target end end end return M",
  ["ceetos/lib/files.lua"] = "local store=require(\"ceetos.lib.store\")local auth=require(\"ceetos.lib.auth\")local M={}local TRASH_DIR=\"/ceetos/data/trash\"local TRASH_INDEX=\"/ceetos/data/trash-index.lua\"local protectedRoots={\"/ceetos\",\"/rom\"}local protectedFiles={[\"/startup.lua\"]=true}local function absolute(path)if not path or path==\"\"or path==\"/\"then return\"/\"end return path:sub(1,1)==\"/\"and path or\"/\"..path end local function sort(items)table.sort(items,function(a,b)if a.directory~=b.directory then return a.directory end return a.name:lower()<b.name:lower()end)return items end local function availablePath(directory,name)name=fs.getName(name)local base,extension=name:match(\"^(.*)(%.[^.]*)$\")base,extension=base or name,extension or\"\"local path,index=fs.combine(directory,name),2 while fs.exists(path)do path=fs.combine(directory,base..\"-\"..index..extension)index=index+1 end return absolute(path)end function M.isProtected(path)path=absolute(path)if protectedFiles[path]then return true end for _,root in ipairs(protectedRoots)do if path==root or path:sub(1,#root+1)==root..\"/\"then return true end end return false end function M.describe(path)path=absolute(path)return{name=fs.getName(path),path=path,directory=fs.exists(path)and fs.isDir(path)or false,runnable=fs.exists(path)and not fs.isDir(path)and path:sub(-4):lower()==\".lua\",protected=M.isProtected(path),}end function M.list(path)path=absolute(path==\"\"and\"/\"or(path or\"/\"))local result={}if path~=\"/\"then local parent=absolute(fs.getDir(path))result[#result+1]={name=\"..\",path=parent,directory=true,parent=true,protected=M.isProtected(parent)}end for _,name in ipairs(fs.list(path))do result[#result+1]=M.describe(absolute(fs.combine(path,name)))end return sort(result)end local function collect(path,depth,result)if depth<0 or not fs.exists(path)or not fs.isDir(path)then return end for _,item in ipairs(M.list(path))do if not item.parent then if item.directory then collect(item.path,depth-1,result)elseif item.runnable then result[#result+1]=item end end end end function M.programs()local result={}collect(\"/programs\",2,result)return result end function M.runnable(path)return M.describe(path).runnable end function M.path(directory,name)return absolute(fs.combine(directory,fs.getName(name)))end local function assertMutable(path)path=absolute(path)assert(path~=\"/\"and fs.exists(path),\"file not found\")assert(not M.isProtected(path),\"CeetOS system files cannot be changed from Explorer\")return path end function M.rename(path,name)path=assertMutable(path)assert(name and fs.getName(name)==name and name~=\"\",\"invalid file name\")local target=M.path(fs.getDir(path),name)assert(not M.isProtected(target),\"CeetOS system files cannot be changed from Explorer\")assert(not fs.exists(target),\"a file with that name already exists\")fs.move(path,target)return target end function M.makeDirectory(directory,name)directory=absolute(directory)assert(not M.isProtected(directory),\"CeetOS system folders cannot be changed from Explorer\")assert(name and fs.getName(name)==name and name~=\"\",\"invalid folder name\")local target=M.path(directory,name)assert(not fs.exists(target),\"a file with that name already exists\")fs.makeDir(target)return target end function M.readText(path)path=absolute(path)assert(fs.exists(path)and not fs.isDir(path),\"file not found\")local handle=assert(fs.open(path,\"r\"))local contents=handle.readAll()handle.close()return contents end function M.writeText(path,contents)path=absolute(path)assert(not M.isProtected(path),\"CeetOS system files cannot be changed from Editor\")local parent=absolute(fs.getDir(path))assert(fs.exists(parent)and fs.isDir(parent),\"parent folder does not exist\")local temporary,backup=path..\".ceetos-tmp\",path..\".ceetos-backup\"if fs.exists(temporary)then fs.delete(temporary)end if fs.exists(backup)then fs.delete(backup)end local handle=assert(fs.open(temporary,\"w\"));handle.write(contents);handle.close()if fs.exists(path)then fs.move(path,backup)end local ok,err=pcall(fs.move,temporary,path)if not ok then if fs.exists(backup)then fs.move(backup,path)end error(err,0)end if fs.exists(backup)then fs.delete(backup)end return path end local function trashIndex()return store.read(TRASH_INDEX,{})end local function saveTrashIndex(index)store.write(TRASH_INDEX,index)end function M.moveToTrash(path)path=assertMutable(path)if not fs.exists(TRASH_DIR)then fs.makeDir(TRASH_DIR)end local index=trashIndex()local id=tostring(os.epoch(\"utc\"))..\"-\"..tostring(math.random(1000,9999))while index[id]do id=id..\"x\"end local stored=absolute(fs.combine(TRASH_DIR,id))fs.move(path,stored)index[id]={original=path,name=fs.getName(path),directory=fs.isDir(stored),deletedAt=os.epoch(\"utc\")}saveTrashIndex(index)return id end function M.trashList()local index,result=trashIndex(),{}for id,entry in pairs(index)do local stored=absolute(fs.combine(TRASH_DIR,id))if fs.exists(stored)then result[#result+1]={id=id,path=stored,name=entry.name,original=entry.original,directory=entry.directory,trashed=true,deletedAt=entry.deletedAt,runnable=not entry.directory and entry.name:sub(-4):lower()==\".lua\"}else index[id]=nil end end saveTrashIndex(index)table.sort(result,function(a,b)return(a.deletedAt or 0)>(b.deletedAt or 0)end)return result end function M.restore(id)local index=trashIndex()local entry=index[id]assert(entry,\"trash item not found\")local stored=absolute(fs.combine(TRASH_DIR,id))assert(fs.exists(stored),\"trash item no longer exists\")local parent=absolute(fs.getDir(entry.original))assert(not M.isProtected(entry.original),\"cannot restore into a protected system path\")if not fs.exists(parent)then fs.makeDir(parent)end local target=availablePath(parent,fs.getName(entry.original))fs.move(stored,target)index[id]=nil;saveTrashIndex(index)return target end function M.deleteTrash(id)local index,entry=trashIndex(),trashIndex()[id]assert(entry,\"trash item not found\")local stored=absolute(fs.combine(TRASH_DIR,id))if fs.exists(stored)then fs.delete(stored)end index[id]=nil;saveTrashIndex(index)end function M.emptyTrash()if fs.exists(TRASH_DIR)then fs.delete(TRASH_DIR)end saveTrashIndex({})end function M.import(transfers,directory)auth.require(\"operator\")directory=directory or\"/programs/imports\"if not fs.exists(directory)then fs.makeDir(directory)end local imported={}for _,transfer in ipairs(transfers or{})do local name=transfer.getName and transfer.getName()if name and name~=\"\"then local path=availablePath(directory,name)local handle=assert(fs.open(path,\"wb\"))while true do local chunk=transfer.read(8192)if not chunk then break end handle.write(chunk)end handle.close()imported[#imported+1]=path end end return imported end return M",
  ["ceetos/lib/editor.lua"] = "local M={}local selection=require(\"ceetos.lib.selection\")local function clamp(value,low,high)return math.max(low,math.min(high,value))end local function split(text)text=(text or\"\"):gsub(\"\\r\\n\",\"\\n\"):gsub(\"\\r\",\"\\n\")local lines={}for line in(text..\"\\n\"):gmatch(\"(.-)\\n\")do lines[#lines+1]=line end if#lines==0 then lines[1]=\"\"end return lines end function M.new(text)local lines=split(text)return{lines=lines,line=1,column=0,changed=false,preferredColumn=nil,selection=selection.new(lines)}end function M.text(buffer)return table.concat(buffer.lines,\"\\n\")end function M.current(buffer)return buffer.lines[buffer.line]end function M.clampCursor(buffer)buffer.line=clamp(buffer.line,1,#buffer.lines)buffer.column=clamp(buffer.column,0,#buffer.lines[buffer.line])end function M.move(buffer,lineDelta,columnDelta)buffer.line=clamp(buffer.line+(lineDelta or 0),1,#buffer.lines)buffer.column=clamp((buffer.preferredColumn or buffer.column)+(columnDelta or 0),0,#buffer.lines[buffer.line])if lineDelta and lineDelta~=0 and columnDelta==0 then buffer.column=clamp(buffer.preferredColumn or buffer.column,0,#buffer.lines[buffer.line])end buffer.preferredColumn=buffer.column end function M.gotoLine(buffer,line,column)buffer.line=clamp(tonumber(line)or 1,1,#buffer.lines)buffer.column=clamp(tonumber(column)or 0,0,#buffer.lines[buffer.line])buffer.preferredColumn=buffer.column end function M.selectStart(buffer)buffer.selection.lines=buffer.lines;selection.start(buffer.selection,buffer.line,buffer.column);return buffer end function M.selectTo(buffer,line,column)buffer.selection.lines=buffer.lines;selection.update(buffer.selection,line,column);return buffer end function M.clearSelection(buffer)selection.clear(buffer.selection);return buffer end function M.selectionText(buffer)buffer.selection.lines=buffer.lines;return selection.text(buffer.selection)end function M.copySelection(buffer,clipboard)buffer.selection.lines=buffer.lines;return selection.copy(buffer.selection,clipboard)end function M.deleteSelection(buffer)local range=selection.range(buffer.selection);if not range then return false end local first,last=range.first,range.last local startText=(buffer.lines[first.line]or\"\"):sub(1,first.column)local endText=(buffer.lines[last.line]or\"\"):sub(last.column+1)buffer.lines[first.line]=startText..endText for _=first.line+1,last.line do table.remove(buffer.lines,first.line+1)end buffer.line,buffer.column,buffer.preferredColumn=first.line,first.column,first.column buffer.selection.lines=buffer.lines;selection.clear(buffer.selection);buffer.changed=true;return true end function M.insert(buffer,value)value=value or\"\"if selection.range(buffer.selection)then M.deleteSelection(buffer)end local before,after=M.current(buffer):sub(1,buffer.column),M.current(buffer):sub(buffer.column+1)local parts=split(value)if#parts==1 then buffer.lines[buffer.line]=before..value..after buffer.column=buffer.column+#value else buffer.lines[buffer.line]=before..parts[1]for index=2,#parts-1 do table.insert(buffer.lines,buffer.line+index-1,parts[index])end table.insert(buffer.lines,buffer.line+#parts-1,parts[#parts]..after)buffer.line,buffer.column=buffer.line+#parts-1,#parts[#parts]end buffer.changed,buffer.preferredColumn=true,buffer.column end function M.backspace(buffer)if buffer.column>0 then local line=M.current(buffer)buffer.lines[buffer.line]=line:sub(1,buffer.column-1)..line:sub(buffer.column+1)buffer.column=buffer.column-1 elseif buffer.line>1 then local previous=buffer.lines[buffer.line-1]buffer.lines[buffer.line-1]=previous..M.current(buffer)table.remove(buffer.lines,buffer.line);buffer.line,buffer.column=buffer.line-1,#previous else return false end buffer.changed,buffer.preferredColumn=true,buffer.column;return true end function M.delete(buffer)local line=M.current(buffer)if buffer.column<#line then buffer.lines[buffer.line]=line:sub(1,buffer.column)..line:sub(buffer.column+2)elseif buffer.line<#buffer.lines then buffer.lines[buffer.line]=line..buffer.lines[buffer.line+1];table.remove(buffer.lines,buffer.line+1)else return false end buffer.changed=true;return true end function M.find(buffer,needle,startLine)if not needle or needle==\"\"then return nil end for line=startLine or buffer.line,#buffer.lines do local column=buffer.lines[line]:find(needle,line==buffer.line and buffer.column+1 or 1,true)if column then buffer.line,buffer.column,buffer.preferredColumn=line,column-1,column-1;return line,column-1 end end return nil end local keywords={[\"and\"]=true,[\"break\"]=true,[\"do\"]=true,[\"else\"]=true,[\"elseif\"]=true,[\"end\"]=true,[\"false\"]=true,[\"for\"]=true,[\"function\"]=true,[\"if\"]=true,[\"in\"]=true,[\"local\"]=true,[\"nil\"]=true,[\"not\"]=true,[\"or\"]=true,[\"repeat\"]=true,[\"return\"]=true,[\"then\"]=true,[\"true\"]=true,[\"until\"]=true,[\"while\"]=true}local builtins={print=true,pairs=true,ipairs=true,tonumber=true,tostring=true,type=true,error=true,assert=true,fs=true,term=true,shell=true,peripheral=true,os=true,textutils=true}function M.tokens(line,lua)if not lua then return{{text=line,kind=\"text\"}}end local out,index={},1 local function add(text,kind)if text~=\"\"then out[#out+1]={text=text,kind=kind}end end while index<=#line do local rest=line:sub(index)if rest:sub(1,2)==\"--\"then add(rest,\"comment\");break end local quote=rest:sub(1,1)if quote==\"'\"or quote=='\"'then local finish,escaped=2,false while finish<=#rest do if rest:sub(finish,finish)==quote and not escaped then break end;escaped=rest:sub(finish,finish)==\"\\\\\"and not escaped;if rest:sub(finish,finish)~=\"\\\\\"then escaped=false end;finish=finish+1 end add(rest:sub(1,finish),\"string\");index=index+finish else local word=rest:match(\"^[%a_][%w_]*\")local number=rest:match(\"^%d+%.?%d*\")if word then add(word,keywords[word]and\"keyword\"or(builtins[word]and\"builtin\"or\"text\"));index=index+#word elseif number then add(number,\"number\");index=index+#number else add(rest:sub(1,1),\"text\");index=index+1 end end end return out end return M",
  ["ceetos/lib/terminal.lua"] = "local store=require(\"ceetos.lib.store\")local M,PATH,LIMIT={},\"/ceetos/data/terminal-history.lua\",50 function M.history()return store.read(PATH,{})end function M.add(command)if not command or command==\"\"then return end local history=M.history()if history[#history]~=command then history[#history+1]=command end while#history>LIMIT do table.remove(history,1)end store.write(PATH,history)end function M.complete(prefix,candidates)local result,seen={},{}for _,candidate in ipairs(candidates or{})do if candidate:sub(1,#prefix)==prefix and not seen[candidate]then result[#result+1],seen[candidate]=candidate,true end end table.sort(result);return result end return M",
  ["ceetos/lib/selection.lua"] = "local M={}local function point(line,column)return{line=math.max(1,tonumber(line)or 1),column=math.max(0,tonumber(column)or 0)}end local function before(a,b)return a.line<b.line or(a.line==b.line and a.column<=b.column)end local function norm(a,b)return before(a,b)and a or b,before(a,b)and b or a end function M.new(lines)return{lines=lines or{\"\"},anchor=nil,active=nil}end function M.position(line,column,maxLine,maxColumn)line=math.max(1,math.min(tonumber(maxLine)or line or 1,tonumber(line)or 1))column=math.max(0,tonumber(column)or 0)if maxColumn and line==maxLine then column=math.min(column,maxColumn)end return line,column end function M.start(s,line,column)s.anchor,s.active=point(line,column),point(line,column);return s end function M.update(s,line,column)if s.anchor then s.active=point(line,column)end;return s end function M.clear(s)s.anchor,s.active=nil,nil;return s end function M.range(s)if not s.anchor or not s.active then return nil end local first,last=norm(s.anchor,s.active)if first.line==last.line and first.column==last.column then return nil end return{first=first,last=last}end function M.text(s)local r=M.range(s);if not r then return\"\"end local out={}for line=r.first.line,r.last.line do local value=s.lines[line]or\"\"local from=line==r.first.line and r.first.column+1 or 1 local to=line==r.last.line and r.last.column or#value out[#out+1]=value:sub(from,to)end return table.concat(out,\"\\n\")end function M.copy(s,clipboard)local text=M.text(s);if text~=\"\"and clipboard then clipboard.set(text)end;return text end return M",
  ["ceetos/lib/clipboard.lua"] = "local store=require(\"ceetos.lib.store\")local M,PATH,OUTBOX,LIMIT={},\"/ceetos/data/clipboard.lua\",\"/ceetos-dev/clipboard-out.lua\",16384 local memory local function trim(value)return tostring(value or\"\"):sub(1,LIMIT)end function M.get()if memory~=nil then return memory end local value=store.read(PATH,{text=\"\"})memory=value and value.text or\"\"return memory end function M.set(value)local text=trim(value)memory=text pcall(store.write,PATH,{text=text})if fs and fs.makeDir and fs.open then pcall(function()if not fs.exists(\"/ceetos-dev\")then pcall(fs.makeDir,\"/ceetos-dev\")end local handle=fs.open(OUTBOX,\"w\")if handle then handle.write(textutils.serialize({text=text,queued=os.epoch and os.epoch(\"utc\")or 0}));handle.close()end end)end return text end function M.clear()return M.set(\"\")end function M.copy(value)return M.set(value)end function M.limit()return LIMIT end return M",
  ["ceetos/lib/input.lua"] = "local M={}function M.modifiers()return{ctrl=false,shift=false}end local function nameOf(name)name=tostring(name or\"\")local lower=name:lower()if lower==\"leftctrl\"or lower==\"rightctrl\"or lower==\"ctrl\"then return\"ctrl\"end if lower==\"leftshift\"or lower==\"rightshift\"or lower==\"shift\"then return\"shift\"end return lower end function M.key(state,name)name=nameOf(name)if name==\"ctrl\"then state.ctrl=true elseif name==\"shift\"then state.shift=true end return state end function M.keyUp(state,name)name=nameOf(name)if name==\"ctrl\"then state.ctrl=false elseif name==\"shift\"then state.shift=false end return state end function M.shortcut(state,name)name=nameOf(name)local active=state.ctrl and state.shift and(name==\"c\"or name==\"v\")if active then state.ctrl,state.shift=false,false end return active,name end return M",
  ["ceetos/lib/version.lua"] = "return{major=0,minor=16,patch=8,string=\"0.16.8\"}",
  ["ceetos/lib/crafting.lua"] = "local M={}M.RECIPE_PACK_MAX_BYTES=64*1024 function M.isLocalPeer(peer,computerId)return tostring(peer)==tostring(computerId)end function M.normalise(rows)local out={}for _,row in pairs(type(rows)==\"table\"and rows or{})do if type(row)==\"table\"then local name,count=row.name or row.id,tonumber(row.count or row.amount or row.quantity or 0)or 0 if type(name)==\"string\"and count>0 then out[name]=(out[name]or 0)+math.floor(count)end end end return out end function M.rows(stock,query,filter,recipes)local output,needle,available={},tostring(query or\"\"):lower(),M.normalise(stock)local names={}for name in pairs(available)do names[name]=true end for name in pairs(type(recipes)==\"table\"and recipes or{})do names[name]=true end for name in pairs(names)do local count=available[name]or 0 local craftable=type(recipes)==\"table\"and recipes[name]~=nil local include=needle==\"\"or name:lower():find(needle,1,true)if filter==\"craftable\"then include=include and craftable elseif filter==\"stocked\"then include=include and count>0 end if include then output[#output+1]={name=name,count=count,craftable=craftable,stocked=count>0}end end table.sort(output,function(a,b)return a.name<b.name end)return output end function M.addToCart(cart,name,count)if type(cart)~=\"table\"or type(name)~=\"string\"or name==\"\"then return nil,\"invalid cart item\"end count=tonumber(count)if not count or count<1 then return nil,\"invalid cart quantity\"end count=math.floor(count)for _,row in ipairs(cart)do if row.name==name then row.count=(tonumber(row.count)or 0)+count;return row end end local row={name=name,count=count}cart[#cart+1]=row return row end function M.cartTotals(cart)local items,quantity=0,0 for _,row in ipairs(type(cart)==\"table\"and cart or{})do items=items+1 quantity=quantity+math.max(0,math.floor(tonumber(row.count)or 0))end return items,quantity end function M.acceptedCount(result,requested)local accepted=tonumber(result)requested=tonumber(requested)if not accepted or not requested or requested<1 then return nil,\"invalid request result\"end accepted=math.floor(accepted)if accepted<1 then return nil,\"Stock Ticker accepted no items\"end return math.min(accepted,math.floor(requested))end function M.displayRow(name,count,width)local suffix=\" x\"..tostring(count)width=math.max(#suffix+1,math.floor(tonumber(width)or#suffix+1))if#name+#suffix<=width then return name..suffix end return name:sub(1,math.max(1,width-#suffix-1))..\"…\"..suffix end function M.cancellationStatus(issued)return issued and\"cancelled-unconfirmed\"or\"cancelled\"end local function validReference(name)return type(name)==\"string\"and name:match(\"^#?[%w_.:%-]+$\")~=nil and not name:find(\"##\",1,true)end local function recipeIngredients(recipe,batches)local combined={}local declared=type(recipe.ingredients)==\"table\"and#recipe.ingredients>0 if declared then for _,ingredient in ipairs(recipe.ingredients)do local name=type(ingredient)==\"table\"and ingredient.id or ingredient local count=type(ingredient)==\"table\"and tonumber(ingredient.count or 1)or 1 if validReference(name)then combined[name]=(combined[name]or 0)+batches*math.max(1,math.floor(count or 1))end end else for slot=1,9 do local name=recipe.grid and recipe.grid[slot]if name and name~=false then combined[name]=(combined[name]or 0)+batches end end end local out={}for name,count in pairs(combined)do out[#out+1]={name=name,count=count}end table.sort(out,function(a,b)return a.name<b.name end)return out end function M.recipeInputs(recipe,batches)return recipeIngredients(recipe or{},math.max(1,math.floor(tonumber(batches)or 1)))end function M.validateRecipes(recipes)if type(recipes)~=\"table\"then return nil,\"recipes must return a table\"end for name,recipe in pairs(recipes)do if type(name)~=\"string\"or not name:match(\"^[%w_.:%-]+$\")or type(recipe)~=\"table\"then return nil,\"invalid recipe item id\"end if type(recipe.alternatives)==\"table\"then if#recipe.alternatives<1 then return nil,\"recipe \"..name..\" has no alternatives\"end for _,alternative in ipairs(recipe.alternatives)do local valid,err=M.validateRecipes({[name]=alternative});if not valid then return nil,err end end else if recipe.mode~=\"crafting\"then return nil,\"recipe \"..name..\" must use mode = crafting\"end if type(recipe.address)~=\"string\"or recipe.address==\"\"or#recipe.address>64 then return nil,\"recipe \"..name..\" requires an address\"end local crafter=recipe.address==\"Crafter\"if crafter and type(recipe.grid)~=\"table\"then return nil,\"recipe \"..name..\" requires a 9-slot grid for Crafter\"end if not crafter and type(recipe.ingredients)~=\"table\"and type(recipe.grid)~=\"table\"then return nil,\"recipe \"..name..\" requires ingredients\"end local output=tonumber(recipe.output or 1)if not output or output<1 or output~=math.floor(output)then return nil,\"invalid output for \"..name end for slot=1,9 do local value=recipe.grid and recipe.grid[slot]if value~=nil and value~=false and not validReference(value)then return nil,\"invalid grid slot in \"..name end end for _,ingredient in ipairs(type(recipe.ingredients)==\"table\"and recipe.ingredients or{})do local id,count=type(ingredient)==\"table\"and ingredient.id or ingredient,type(ingredient)==\"table\"and ingredient.count or 1 if not validReference(id)or not tonumber(count)or tonumber(count)<1 then return nil,\"invalid ingredient in \"..name end end end end return recipes end local function dataParser(source,maximum)if type(source)~=\"string\"then return nil,\"recipe data must be text\"end if#source==0 or#source>(maximum or M.RECIPE_PACK_MAX_BYTES)then return nil,\"recipe data exceeds the 64 KiB import limit\"end local state={source=source,index=1,length=#source,depth=0,nodes=0}local function skip()while state.index<=state.length do local char=state.source:sub(state.index,state.index)if char:match(\"%s\")then state.index=state.index+1 elseif state.source:sub(state.index,state.index+1)==\"--\"then local ending=state.source:find(\"\\n\",state.index+2,true)state.index=ending and ending+1 or state.length+1 else return true end end return true end local function fail(message)return nil,message..\" near byte \"..tostring(state.index)end local function identifier()local name=state.source:match(\"^[%a_][%w_]*\",state.index)if name then state.index=state.index+#name end return name end local parseValue local function parseString()local quote=state.source:sub(state.index,state.index);state.index=state.index+1 local out={}while state.index<=state.length do local char=state.source:sub(state.index,state.index);state.index=state.index+1 if char==quote then return table.concat(out)end if char==\"\\\\\"then local escaped=state.source:sub(state.index,state.index);state.index=state.index+1 local values={n=\"\\n\",r=\"\\r\",t=\"\\t\",[\"\\\\\"]=\"\\\\\",[\"\\\"\"]=\"\\\"\",[\"'\"]=\"'\"}if not values[escaped]then return fail(\"unsupported string escape\")end out[#out+1]=values[escaped]elseif char:byte()<32 then return fail(\"control character in string\")else out[#out+1]=char end end return fail(\"unterminated string\")end local function parseTable()state.depth=state.depth+1 if state.depth>32 then return fail(\"recipe data is nested too deeply\")end state.index=state.index+1 local out,nextIndex,keys={},1,{}skip()while state.index<=state.length and state.source:sub(state.index,state.index)~=\"}\"do state.nodes=state.nodes+1 if state.nodes>4096 then return fail(\"recipe data has too many values\")end local key,value,err local start=state.index if state.source:sub(state.index,state.index)==\"[\"then state.index=state.index+1;key,err=parseValue();if err then return nil,err end skip();if state.source:sub(state.index,state.index)~=\"]\"then return fail(\"missing closing recipe key bracket\")end state.index=state.index+1;skip();if state.source:sub(state.index,state.index)~=\"=\"then return fail(\"missing recipe key assignment\")end state.index=state.index+1;skip();value,err=parseValue();if err then return nil,err end else local named=identifier();skip()if named and state.source:sub(state.index,state.index)==\"=\"then key,state.index=named,state.index+1;skip();value,err=parseValue();if err then return nil,err end else state.index=start;value,err=parseValue();if err then return nil,err end key,nextIndex=nextIndex,nextIndex+1 end end if type(key)~=\"string\"and type(key)~=\"number\"then return fail(\"recipe table key must be text or a number\")end local signature=type(key)..\":\"..tostring(key)if keys[signature]then return fail(\"duplicate recipe table key\")end keys[signature],out[key]=true,value skip();local separator=state.source:sub(state.index,state.index)if separator==\",\"or separator==\";\"then state.index=state.index+1;skip()elseif separator~=\"}\"then return fail(\"expected recipe table separator\")end end if state.source:sub(state.index,state.index)~=\"}\"then return fail(\"unterminated recipe table\")end state.index,state.depth=state.index+1,state.depth-1 return out end parseValue=function()skip();local char=state.source:sub(state.index,state.index)if char==\"{\"then return parseTable()end if char==\"\\\"\"or char==\"'\"then return parseString()end local number=state.source:match(\"^-?%d+\",state.index)if number then state.index=state.index+#number;return tonumber(number)end local name=identifier()if name==\"true\"then return true elseif name==\"false\"then return false elseif name==\"nil\"then return nil elseif name then return fail(\"bare recipe values are not allowed\")end return fail(\"invalid recipe value\")end skip()if identifier()~=\"return\"then return fail(\"recipe data must start with return\")end local value,err=parseValue();if err then return nil,err end skip();if state.index<=state.length then return fail(\"unexpected content after recipe table\")end return value end local function validTags(tags)if tags==nil then return{}end if type(tags)~=\"table\"then return nil,\"recipe tags must be a table\"end local out={}for tag,members in pairs(tags)do local key=tostring(tag):gsub(\"^#\",\"\")if not key:match(\"^[%w_.:%-]+$\")or type(members)~=\"table\"or#members<1 then return nil,\"invalid recipe tag \"..tostring(tag)end out[key]={}for _,member in ipairs(members)do if not validReference(member)or tostring(member):sub(1,1)==\"#\"then return nil,\"invalid member of #\"..key end out[key][#out[key]+1]=member end table.sort(out[key])end return out end function M.validateRecipeGraph(recipes,tags)local tagMap,tagErr=validTags(tags);if not tagMap then return nil,tagErr end local visiting,complete={},{}local function visit(name)if complete[name]then return true end if visiting[name]then return nil,\"recipe cycle at \"..name end local recipe=recipes[name]if type(recipe)==\"table\"and type(recipe.alternatives)==\"table\"then recipe=recipe.alternatives[1]end if not recipe then return true end visiting[name]=true for _,input in ipairs(recipeIngredients(recipe,1))do local ingredient=input.name local members=ingredient:sub(1,1)==\"#\"and tagMap[ingredient:sub(2)]or{ingredient}for _,member in ipairs(members or{})do if recipes[member]then local ok,err=visit(member);if not ok then return nil,err end end end end visiting[name],complete[name]=nil,true return true end for name in pairs(recipes)do local ok,err=visit(name);if not ok then return nil,err end end return true end function M.parseRecipeOverlay(source)local value,err=dataParser(source,M.RECIPE_PACK_MAX_BYTES)if not value then return nil,err end if type(value)~=\"table\"then return nil,\"recipe overlay must return a table\"end local recipes,tags if value.schema==1 and type(value.recipes)==\"table\"then recipes,tags=value.recipes,value.tags or{}else recipes,tags=value,{}end local valid,validationErr=M.validateRecipes(recipes)if not valid then return nil,validationErr end local tagMap,tagsErr=validTags(tags);if not tagMap then return nil,tagsErr end local graphOk,graphErr=M.validateRecipeGraph(recipes,tagMap)if not graphOk then return nil,graphErr end return{schema=1,recipes=recipes,tags=tagMap}end function M.parseRecipeFile(source)local overlay,err=M.parseRecipeOverlay(source)return overlay and overlay.recipes or nil,err end function M.parseRecipePack(source)local pack,err=dataParser(source,M.RECIPE_PACK_MAX_BYTES)if not pack then return nil,err end if type(pack)~=\"table\"or pack.schema~=1 or type(pack.recipes)~=\"table\"then return nil,\"recipe pack must return { schema = 1, recipes = { ... } }\"end local valid,validationErr=M.validateRecipes(pack.recipes)if not valid then return nil,validationErr end local tagMap,tagsErr=validTags(pack.tags or{});if not tagMap then return nil,tagsErr end local graphOk,graphErr=M.validateRecipeGraph(pack.recipes,tagMap)if not graphOk then return nil,graphErr end return{schema=1,recipes=pack.recipes,tags=tagMap}end function M.recipeEqual(left,right)if type(left)~=\"table\"or type(right)~=\"table\"then return false end if type(left.alternatives)==\"table\"then left=left.alternatives[1]end if type(right.alternatives)==\"table\"then right=right.alternatives[1]end if not left or not right or left.mode~=right.mode or left.kind~=right.kind or left.output~=right.output or left.address~=right.address then return false end for slot=1,9 do if left.grid and right.grid and left.grid[slot]~=right.grid[slot]then return false end end local a,b=recipeIngredients(left,1),recipeIngredients(right,1)if#a~=#b then return false end for index=1,#a do if a[index].name~=b[index].name or a[index].count~=b[index].count then return false end end return true end function M.reviewRecipePack(existing,incoming)local validExisting,existingErr=M.validateRecipes(existing)if not validExisting then return nil,existingErr end local validIncoming,incomingErr=M.validateRecipes(incoming)if not validIncoming then return nil,incomingErr end local rows,counts={},{new=0,unchanged=0,conflict=0,invalid=0}for name,recipe in pairs(incoming)do local prior=existing[name]local status=not prior and\"new\"or(M.recipeEqual(prior,recipe)and\"unchanged\"or\"conflict\")counts[status]=counts[status]+1 rows[#rows+1]={name=name,status=status,incoming=recipe,existing=prior,selected=status==\"new\"}end table.sort(rows,function(a,b)return a.name<b.name end)return{rows=rows,counts=counts}end local function cloneRecipe(recipe)if type(recipe)==\"table\"and type(recipe.alternatives)==\"table\"then recipe=recipe.alternatives[1]end local copy={mode=recipe.mode,kind=recipe.kind,output=recipe.output,address=recipe.address,grid={},ingredients={}}for slot=1,9 do copy.grid[slot]=recipe.grid and recipe.grid[slot]end for _,input in ipairs(recipe.ingredients or{})do copy.ingredients[#copy.ingredients+1]={id=input.id,count=input.count,tag=input.tag}end return copy end function M.mergeRecipePack(existing,review,existingTags,incomingTags)if type(existing)~=\"table\"or type(review)~=\"table\"or type(review.rows)~=\"table\"then return nil,\"invalid recipe import review\"end local merged,imported={},0 for name,recipe in pairs(existing)do merged[name]=cloneRecipe(recipe)end for _,row in ipairs(review.rows)do if row.status==\"new\"and row.selected==true then merged[row.name],imported=cloneRecipe(row.incoming),imported+1 elseif row.status==\"conflict\"and row.selected==true then merged[row.name],imported=cloneRecipe(row.incoming),imported+1 end end local tags={}for name,members in pairs(existingTags or{})do tags[name]=members end for name,members in pairs(incomingTags or{})do tags[name]=members end local valid,err=M.validateRecipes(merged);if not valid then return nil,err end local graphOk,graphErr=M.validateRecipeGraph(merged,tags);if not graphOk then return nil,graphErr end return merged,imported,tags end function M.encodeRecipeFile(recipes,tags)local valid,err=M.validateRecipes(recipes);if not valid then return nil,err end local tagMap,tagsErr=validTags(tags or{});if not tagMap then return nil,tagsErr end local graphOk,graphErr=M.validateRecipeGraph(recipes,tagMap);if not graphOk then return nil,graphErr end local ok,encoded=pcall(textutils.serialise,{schema=1,recipes=recipes,tags=tagMap},{compact=true})if not ok or type(encoded)~=\"string\"then return nil,\"could not serialise recipes\"end return\"return \"..encoded..\"\\n\"end function M.writeRecipeFile(path,recipes,tags)if type(path)~=\"string\"or path==\"\"then return false,\"invalid recipe file path\"end local raw,encodeErr=M.encodeRecipeFile(recipes,tags);if not raw then return false,encodeErr end local parent=fs.getDir(path);if parent~=\"\"and not fs.exists(parent)then fs.makeDir(parent)end local temporary,backup=path..\".new\",path..\".bak\"if fs.exists(temporary)then fs.delete(temporary)end local handle=fs.open(temporary,\"w\");if not handle then return false,\"could not stage recipes\"end handle.write(raw);handle.close()local check=fs.open(temporary,\"r\");local staged=check and check.readAll()or nil;if check then check.close()end if not M.parseRecipeOverlay(staged or\"\")then if fs.exists(temporary)then fs.delete(temporary)end;return false,\"could not validate staged recipes\"end if fs.exists(backup)then fs.delete(backup)end if fs.exists(path)then fs.move(path,backup)end local moved,moveErr=pcall(fs.move,temporary,path)if not moved then if fs.exists(backup)and not fs.exists(path)then fs.move(backup,path)end;if fs.exists(temporary)then fs.delete(temporary)end;return false,tostring(moveErr)end if fs.exists(backup)then fs.delete(backup)end return true end local function selectedRecipe(entry)if type(entry)==\"table\"and type(entry.alternatives)==\"table\"then return entry.alternatives[1]end return entry end local function tagMembers(tags,reference)if reference:sub(1,1)~=\"#\"then return{reference}end local members=tags[reference:sub(2)]if type(members)~=\"table\"or#members==0 then return nil,\"no known members for \"..reference end return members end local function chooseMember(reference,tags,available,recipes)local members,err=tagMembers(tags,reference);if not members then return nil,err end local best for _,member in ipairs(members)do if(available[member]or 0)>0 then return member end if recipes[member]and not best then best=member end end return best,best and nil or(\"no stocked or craftable member for \"..reference)end local function requesterGrid(recipe,resolved,tags,available,recipes)local grid={}for slot=1,9 do local value=recipe.grid and recipe.grid[slot]if type(value)==\"string\"and value:sub(1,1)==\"#\"then local concrete=resolved[value]if not concrete then concrete=select(1,chooseMember(value,tags,available,recipes))end if not concrete then return nil,\"no concrete item available for requester tag \"..value end grid[slot]=concrete else grid[slot]=value end end return grid end function M.plan(recipes,stock,item,quantity,options)quantity=tonumber(quantity)if type(item)~=\"string\"or item==\"\"or not quantity or quantity<1 or quantity~=math.floor(quantity)then return nil,\"invalid item or quantity\"end local valid,errorText=M.validateRecipes(recipes)if not valid then return nil,errorText end options=type(options)==\"table\"and options or{}local available,plan,visiting,tags=M.normalise(stock),{},{},type(options.tags)==\"table\"and options.tags or{}local function requireItem(name,needed)local used=options.forceRoot==true and name==item and 0 or math.min(available[name]or 0,needed)available[name]=(available[name]or 0)-used local missing=needed-used if missing<=0 then return true end if visiting[name]then return nil,\"recipe cycle at \"..name end local recipe=selectedRecipe(recipes[name])if not recipe then return nil,\"missing recipe for \"..name..\" (need \"..tostring(missing)..\")\"end if recipe.special or not recipe.output or not recipe.address then return nil,\"recipe \"..name..\" is not supported by Crafting Queue\"end visiting[name]=true local batches=math.ceil(missing/recipe.output)local inputs,resolved={},{}for _,ingredient in ipairs(recipeIngredients(recipe,batches))do local concrete,resolveErr=chooseMember(ingredient.name,tags,available,recipes)if not concrete then return nil,resolveErr end inputs[#inputs+1]={name=concrete,count=ingredient.count,source=ingredient.name,tag=ingredient.name:sub(1,1)==\"#\"and ingredient.name or nil}if ingredient.name:sub(1,1)==\"#\"then resolved[ingredient.name]=concrete end local ok,err=requireItem(concrete,ingredient.count)if not ok then return nil,err end end visiting[name]=nil local produced=batches*recipe.output available[name]=(available[name]or 0)+produced-missing local dispatch=recipe.address==\"Crafter\"and\"requester\"or\"package\"if dispatch==\"requester\"and type(recipe.grid)~=\"table\"then return nil,\"Crafter recipe \"..name..\" has no 3x3 grid\"end local grid,gridErr=recipe.grid,nil if dispatch==\"requester\"then grid,gridErr=requesterGrid(recipe,resolved,tags,available,recipes)if not grid then return nil,gridErr end end plan[#plan+1]={name=name,batches=batches,produced=produced,requested=missing,address=recipe.address,kind=recipe.kind,dispatch=dispatch,grid=grid,sourceGrid=recipe.grid,inputs=inputs,}return true end local ok,err=requireItem(item,quantity)return ok and plan or nil,err end function M.validateExecutionPlan(plan)if type(plan)~=\"table\"or#plan<1 or#plan>96 then return nil,\"invalid remote recipe plan\"end for _,step in ipairs(plan)do if type(step)~=\"table\"or not validReference(step.name)or tostring(step.name):sub(1,1)==\"#\"then return nil,\"invalid remote recipe output\"end if type(step.address)~=\"string\"or step.address==\"\"or#step.address>64 or step.address:find(\"[%c]\")then return nil,\"invalid remote recipe address\"end if step.dispatch~=\"requester\"and step.dispatch~=\"package\"then return nil,\"invalid remote recipe route\"end if(step.address==\"Crafter\")~=(step.dispatch==\"requester\")then return nil,\"invalid remote recipe executor\"end for _,field in ipairs({\"batches\",\"produced\",\"requested\"})do local value=tonumber(step[field])if not value or value<1 or value~=math.floor(value)or value>65536 then return nil,\"invalid remote recipe quantity\"end end if step.dispatch==\"requester\"then if type(step.grid)~=\"table\"then return nil,\"remote Crafter recipe has no grid\"end for slot=1,9 do local value=step.grid[slot]if value~=nil and value~=false and not validReference(value)then return nil,\"invalid remote recipe grid\"end if type(value)==\"string\"and value:sub(1,1)==\"#\"then return nil,\"remote requester grid contains unresolved tag\"end end end if type(step.inputs)~=\"table\"or#step.inputs>64 then return nil,\"invalid remote recipe inputs\"end for _,input in ipairs(step.inputs)do if type(input)~=\"table\"or not validReference(input.name)or tostring(input.name):sub(1,1)==\"#\"then return nil,\"invalid remote recipe input\"end local count=tonumber(input.count)if not count or count<1 or count~=math.floor(count)or count>65536 then return nil,\"invalid remote recipe input quantity\"end if input.source~=nil and not validReference(input.source)then return nil,\"invalid remote recipe input source\"end end end return plan end return M",
  ["ceetos/lib/craft_sources.lua"] = "local M={}local function isType(value,needle)return tostring(value or\"\"):lower():find(needle,1,true)~=nil end function M.kind(value)if type(value)==\"string\"then return{transport=\"local\",name=value}end return type(value)==\"table\"and value or nil end function M.key(value)value=M.kind(value)if not value then return nil end return tostring(value.transport or\"local\")..\":\"..tostring(value.peer or\"\")..\":\"..tostring(value.name or\"\")end function M.label(value)value=M.kind(value)if not value then return\"Not selected\"end if value.transport==\"peer\"then return\"Peer \"..tostring(value.peer)..\" / \"..tostring(value.name)end return tostring(value.name)end function M.discoverLocal()local tickers,requesters={},{}for _,name in ipairs(peripheral.getNames())do local typeName=peripheral.getType(name)if isType(typeName,\"stockticker\")then tickers[#tickers+1]={transport=\"local\",name=name,type=typeName,label=\"Local / \"..name}elseif isType(typeName,\"redstonerequester\")then requesters[#requesters+1]={transport=\"local\",name=name,type=typeName,label=\"Local / \"..name}end end table.sort(tickers,function(a,b)return a.name<b.name end)table.sort(requesters,function(a,b)return a.name<b.name end)return tickers,requesters end function M.matches(value,kind)value=M.kind(value)if not value or type(value.name)~=\"string\"then return false end local needle=(kind==\"ticker\"or kind==\"stockticker\")and\"stockticker\"or\"redstonerequester\"return isType(value.type,needle)end return M",
  ["ceetos/lib/program_capabilities.lua"] = "local store=require(\"ceetos.lib.store\")local auth=require(\"ceetos.lib.auth\")local audit=require(\"ceetos.lib.audit\")local M={}local PATH=\"/ceetos/data/program-capabilities.lua\"local SCHEMA=1 local SCRATCH_ROOT=\"/ceetos/data/programs\"local PROTECTED_ROOTS={\"/ceetos\",\"/ceetos-dev\",\"/rom\",}local READ_ONLY_METHODS={getAngles=true,getSpeed=true,getStress=true,getStressCapacity=true,getTargetSpeed=true,getItemDetail=true,getInventoryName=true,getMetadata=true,getFluidDetail=true,getEnergy=true,getCursorPos=true,getSize=true,getTextScale=true,isRunning=true,isPresent=true,list=true,size=true,}local function now()return os.epoch(\"utc\")end local function copy(value,seen)if type(value)~=\"table\"then return value end seen=seen or{}if seen[value]then return seen[value]end local result={}seen[value]=result for key,item in pairs(value)do result[copy(key,seen)]=copy(item,seen)end return result end local function defaultConfig()return{schema=SCHEMA,programs={}}end local function normalise(path)if type(path)~=\"string\"or path==\"\"or#path>240 or path:find(\"[%z\\1-\\31]\")then return nil,\"invalid program path\"end local parts={}for part in path:gmatch(\"[^/]+\")do if part==\"..\"then if#parts>0 then table.remove(parts)end elseif part~=\".\"and part~=\"\"then parts[#parts+1]=part end end return\"/\"..table.concat(parts,\"/\")end local function readSource(path)local handle,err=fs.open(path,\"r\")if not handle then return nil,err or\"could not read program\"end local source=handle.readAll()handle.close()return source end local function legacyHash(source)local hash=2166136261 for index=1,#source do hash=bit32.bxor(hash,source:byte(index))hash=(hash*16777619)%4294967296 end return string.format(\"fnv1a32:%08x\",hash)end local function programId(path)return\"p-\"..legacyHash(path):match(\":(%x+)$\")end local function loadConfig()local config=store.readFresh(PATH,defaultConfig())if type(config)~=\"table\"then return defaultConfig()end if type(config.programs)~=\"table\"then config.programs={}end config.schema=SCHEMA return config end local function saveConfig(config)local ok,err=store.writeAtomic(PATH,config)assert(ok,\"could not save program capabilities: \"..tostring(err))end local function adminActor()if auth.refreshSession then auth.refreshSession()end auth.require(\"admin\")return auth.current and auth.current.name or\"admin\"end local function pathWithin(path,root)return path==root or path:sub(1,#root+1)==root..\"/\"end local function protectedProgramPath(path)if path==\"/startup.lua\"then return true end for _,root in ipairs(PROTECTED_ROOTS)do if pathWithin(path,root)then return true end end return false end local function normaliseProgramPath(path)local normalized,err=normalise(path)if not normalized then return nil,err end if protectedProgramPath(normalized)then return nil,\"protected CeetOS/CraftOS program path\"end if normalized:sub(-4):lower()~=\".lua\"then return nil,\"program must be a Lua file\"end if not fs.exists(normalized)or fs.isDir(normalized)then return nil,\"program file not found\"end return normalized end local function defaultRecord(path,source,owner)return{path=path,id=programId(path),sourceHash=legacyHash(source),hashKind=\"fnv1a32-legacy-integrity-marker\",owner=owner or\"unassigned\",trust=\"sandboxed\",capabilities={scratch=true,peripherals={}},createdAt=now(),updatedAt=now(),}end local function cleanMethods(methods)if type(methods)~=\"table\"then return nil,\"methods must be a list\"end local seen,result={},{}for _,method in ipairs(methods)do if type(method)~=\"string\"or not READ_ONLY_METHODS[method]then return nil,\"method is not an approved read-only capability\"end if not seen[method]then seen[method]=true;result[#result+1]=method end end if#result==0 then return nil,\"at least one read-only method is required\"end table.sort(result)return result end local function recordIdAvailable(config,id,path)for savedPath,saved in pairs(config.programs)do if savedPath~=path and type(saved)==\"table\"and saved.id==id then return false end end return true end local function recordFrom(config,path,source)local saved=config.programs[path]local currentHash=legacyHash(source)local id=programId(path)if not recordIdAvailable(config,id,path)then return nil,nil,\"program capability ID collision; choose a different program path\"end if type(saved)==\"table\"and saved.sourceHash==currentHash and saved.path==path then local record=copy(saved)record.id=id record.hashKind=\"fnv1a32-legacy-integrity-marker\"record.capabilities=type(record.capabilities)==\"table\"and record.capabilities or{}record.capabilities.scratch=true record.capabilities.peripherals=type(record.capabilities.peripherals)==\"table\"and record.capabilities.peripherals or{}return record,false,nil end local record=defaultRecord(path,source,type(saved)==\"table\"and saved.owner or nil)record.stale=type(saved)==\"table\"return record,record.stale,nil end local function scratchPath(record)return SCRATCH_ROOT..\"/\"..record.id end local function normaliseScratch(path,root)if type(path)~=\"string\"or#path>240 or path:find(\"[%z\\1-\\31]\")then return nil end local candidate=path:sub(1,1)==\"/\"and path or root..\"/\"..path local normalized=normalise(candidate)if not normalized or not pathWithin(normalized,root)then return nil end return normalized end local function safeTerm()local source=term return{write=source.write,blit=source.blit,clear=source.clear,clearLine=source.clearLine,scroll=source.scroll,getSize=source.getSize,getCursorPos=source.getCursorPos,setCursorPos=source.setCursorPos,getCursorBlink=source.getCursorBlink,setCursorBlink=source.setCursorBlink,setTextColor=source.setTextColor,setTextColour=source.setTextColour,getTextColor=source.getTextColor,getTextColour=source.getTextColour,setBackgroundColor=source.setBackgroundColor,setBackgroundColour=source.setBackgroundColour,getBackgroundColor=source.getBackgroundColor,getBackgroundColour=source.getBackgroundColour,isColor=source.isColor,isColour=source.isColour,}end local function safeTextutils()return{serialise=textutils.serialise,serialize=textutils.serialize,serialiseJSON=textutils.serialiseJSON,serializeJSON=textutils.serializeJSON,unserialiseJSON=textutils.unserialiseJSON,unserializeJSON=textutils.unserializeJSON,formatTime=textutils.formatTime,urlEncode=textutils.urlEncode,}end local function tableCopy(value)local output={}for key,item in pairs(value or{})do output[key]=item end return output end local function safeFilesystem(record,actor,deny)local root=scratchPath(record)if not fs.exists(root)then local made,makeErr=pcall(fs.makeDir,root)if not made or makeErr==false then error(\"could not initialise program scratch storage\",2)end end local function target(path)local value=normaliseScratch(path,root)if not value then deny(\"filesystem path\")end return value end local function mutable(path)local value=target(path)if value==root then deny(\"program scratch root\")end return value end local proxy={}function proxy.exists(path)return fs.exists(target(path))end function proxy.isDir(path)return fs.isDir(target(path))end function proxy.list(path)return fs.list(target(path))end function proxy.getSize(path)return fs.getSize(target(path))end function proxy.open(path,mode)mode=tostring(mode or\"r\")if mode~=\"r\"and mode~=\"rb\"and mode~=\"w\"and mode~=\"wb\"and mode~=\"a\"and mode~=\"ab\"then deny(\"filesystem mode\")end return fs.open((mode==\"r\"or mode==\"rb\")and target(path)or mutable(path),mode)end function proxy.makeDir(path)return fs.makeDir(mutable(path))end function proxy.delete(path)return fs.delete(mutable(path))end function proxy.move(from,to)return fs.move(mutable(from),mutable(to))end function proxy.copy(from,to)return fs.copy(mutable(from),mutable(to))end function proxy.combine(a,b)local value=normaliseScratch(tostring(a or\"\")..\"/\"..tostring(b or\"\"),root)if not value then deny(\"filesystem path\")end return value end function proxy.getDir(path)return fs.getDir(target(path))end function proxy.getName(path)return fs.getName(target(path))end return proxy end local function safePeripheral(record,deny)local grants=record.trust==\"trusted\"and record.capabilities and record.capabilities.peripherals or{}local function methodsFor(name)local grant=type(grants)==\"table\"and grants[name]or nil local allowed={}for _,method in ipairs(type(grant)==\"table\"and grant.methods or{})do if READ_ONLY_METHODS[method]then allowed[method]=true end end return allowed end local proxy={}function proxy.getNames()local result={}for name in pairs(grants or{})do local methods=methodsFor(name)if next(methods)and peripheral.isPresent(name)then result[#result+1]=name end end table.sort(result)return result end function proxy.isPresent(name)return next(methodsFor(name))~=nil and peripheral.isPresent(name)or false end function proxy.getType(name)if next(methodsFor(name))==nil then deny(\"peripheral \"..tostring(name))end return peripheral.getType(name)end function proxy.getMethods(name)local result={}for method in pairs(methodsFor(name))do result[#result+1]=method end if#result==0 then deny(\"peripheral \"..tostring(name))end table.sort(result)return result end function proxy.wrap(name)local allowed=methodsFor(name)if next(allowed)==nil then deny(\"peripheral \"..tostring(name))end local wrapped={}for method in pairs(allowed)do wrapped[method]=function(...)local raw=peripheral.wrap(name)if not raw or type(raw[method])~=\"function\"then error(\"granted peripheral is unavailable\",2)end local args={...}if args[1]==wrapped then table.remove(args,1)end return raw[method](table.unpack(args))end end return wrapped end return proxy end function M.normaliseProgramPath(path)return normaliseProgramPath(path)end function M.legacySourceHash(source)assert(type(source)==\"string\",\"source must be a string\")return legacyHash(source)end function M.isReadOnlyMethod(method)return READ_ONLY_METHODS[method]==true end function M.describe(path)local normalized,err=normaliseProgramPath(path)if not normalized then return nil,err end local source,readErr=readSource(normalized)if not source then return nil,readErr end local record,_,recordErr=recordFrom(loadConfig(),normalized,source)if not record then return nil,recordErr end return copy(record)end function M.create(path,owner)local actor=adminActor()local normalized,err=normaliseProgramPath(path)assert(normalized,err)if owner~=nil then assert(type(owner)==\"string\"and owner:match(\"^[%w_.%-]+$\")and#owner<=64,\"invalid program owner\")end local source=assert(readSource(normalized))local config=loadConfig()assert(recordIdAvailable(config,programId(normalized),normalized),\"program capability ID collision; choose a different program path\")local record=defaultRecord(normalized,source,owner or actor)config.programs[normalized]=record saveConfig(config)audit.log(actor,\"program.capability_create\",{path=normalized,owner=record.owner})return copy(record)end function M.setTrust(path,trust)local actor=adminActor()assert(trust==\"sandboxed\"or trust==\"trusted\",\"invalid program trust state\")local normalized,err=normaliseProgramPath(path)assert(normalized,err)local source=assert(readSource(normalized))local config=loadConfig()local record,_,recordErr=recordFrom(config,normalized,source)assert(record,recordErr)record.trust,record.updatedAt=trust,now()if trust~=\"trusted\"then record.capabilities.peripherals={}end config.programs[normalized]=record saveConfig(config)audit.log(actor,\"program.trust\",{path=normalized,trust=trust})return copy(record)end function M.setOwner(path,owner)local actor=adminActor()assert(type(owner)==\"string\"and owner:match(\"^[%w_.%-]+$\")and#owner<=64,\"invalid program owner\")local normalized,err=normaliseProgramPath(path)assert(normalized,err)local source=assert(readSource(normalized))local config=loadConfig()local record,_,recordErr=recordFrom(config,normalized,source)assert(record,recordErr)record.owner,record.updatedAt=owner,now()config.programs[normalized]=record saveConfig(config)audit.log(actor,\"program.owner\",{path=normalized,owner=owner})return copy(record)end function M.grantReadOnlyPeripheral(path,name,methods)local actor=adminActor()assert(type(name)==\"string\"and name~=\"\"and#name<=128 and not name:find(\"[%z\\1-\\31]\"),\"invalid peripheral name\")local clean,methodErr=cleanMethods(methods)assert(clean,methodErr)local normalized,err=normaliseProgramPath(path)assert(normalized,err)local source=assert(readSource(normalized))local config=loadConfig()local record,_,recordErr=recordFrom(config,normalized,source)assert(record,recordErr)assert(record.trust==\"trusted\",\"admin must trust the program before granting peripherals\")record.capabilities.peripherals[name]={methods=clean}record.updatedAt=now()config.programs[normalized]=record saveConfig(config)audit.log(actor,\"program.peripheral_grant\",{path=normalized,peripheral=name,methods=clean})return copy(record)end function M.revokePeripheral(path,name)local actor=adminActor()local normalized,err=normaliseProgramPath(path)assert(normalized,err)local source=assert(readSource(normalized))local config=loadConfig()local record,_,recordErr=recordFrom(config,normalized,source)assert(record,recordErr)record.capabilities.peripherals[name]=nil record.updatedAt=now()config.programs[normalized]=record saveConfig(config)audit.log(actor,\"program.peripheral_revoke\",{path=normalized,peripheral=tostring(name)})return copy(record)end function M.viewerEnvironment(path,actor)local record,err=M.describe(path)if not record then return nil,err end actor=actor or\"viewer\"local denied={}local function deny(action)if not denied[action]then denied[action]=true audit.log(actor,\"program.denied\",{path=record.path,action=action})end error(\"permission denied: \"..action,3)end local function pullEvent(filter)while true do local event={os.pullEventRaw(filter)}if event[1]~=\"terminate\"then return table.unpack(event)end end end local safeOs={pullEvent=pullEvent,startTimer=os.startTimer,cancelTimer=os.cancelTimer,clock=os.clock,time=os.time,day=os.day,epoch=os.epoch,getComputerID=os.getComputerID,getComputerLabel=os.getComputerLabel,}local environment={_VERSION=_VERSION,assert=assert,error=error,ipairs=ipairs,next=next,pairs=pairs,pcall=pcall,select=select,tonumber=tonumber,tostring=tostring,type=type,xpcall=xpcall,print=print,printError=printError,read=read,write=write,math=tableCopy(math),string=tableCopy(string),table=tableCopy(table),coroutine=tableCopy(coroutine),bit32=tableCopy(bit32),utf8=tableCopy(utf8),keys=tableCopy(keys),colors=tableCopy(colors),colours=tableCopy(colours or colors),term=safeTerm(),textutils=safeTextutils(),os=safeOs,fs=safeFilesystem(record,actor,deny),peripheral=safePeripheral(record,deny),}return setmetatable(environment,{__index=function()return nil end}),record end function M.loadViewer(path,actor)local environment,record=M.viewerEnvironment(path,actor)if not environment then return nil,record end local chunk,err=loadfile(record.path,nil,environment)if not chunk then audit.log(actor or\"viewer\",\"program.denied\",{path=record.path,action=\"load\"})return nil,err end return chunk,record end function M.scratchPath(path)local record,err=M.describe(path)if not record then return nil,err end return scratchPath(record)end M.PATH=PATH M.SCHEMA=SCHEMA M.HASH_KIND=\"fnv1a32-legacy-integrity-marker\"return M",
  ["ceetos/bin/ceetver.lua"] = "package.path=\"/?.lua;/?/init.lua;\"..package.path local ok,version=pcall(require,\"ceetos.lib.version\")print(\"CeetOS \"..(ok and version.string or\"0.12.0\"))",
  ["ceetos/bin/ceetdevices.lua"] = "package.path=\"/?.lua;/?/init.lua;\"..package.path local peripherals=require(\"ceetos.lib.peripherals\")local shared={}for _,item in ipairs(peripherals.describe())do shared[item.name]=item.mode end for _,item in ipairs(peripherals.listLocal())do print(item.name..\"\\t\"..tostring(item.type or\"unknown\")..\"\\t\"..(shared[item.name]or\"not shared\"))end",
  ["ceetos/bin/ceetcraft.lua"] = "package.path=\"/?.lua;/?/init.lua;\"..package.path local auth,store,crafting=require(\"ceetos.lib.auth\"),require(\"ceetos.lib.store\"),require(\"ceetos.lib.crafting\")local telemetryOk,telemetry=pcall(require,\"ceetos.lib.telemetry\")if telemetryOk and telemetry and telemetry.markActivity then telemetry.markActivity(\"crafting queue\")end local terminalUi=require(\"ceetos.lib.terminal_ui\")local canMutate=auth.allowed(\"operator\")local STATE,COMMANDS=\"/ceetos/data/crafting-state.lua\",\"/ceetos/data/crafting-commands\"local query,filter,focus,selectedStock,selectedCart,buttonIndex,actionPage=\"\",\"all\",\"stock\",1,1,1,1 local RECIPE_FILE,RECIPE_IMPORTS=\"/ceetos/data/recipes.lua\",\"/ceetos/data/recipe-imports.lua\"local modal,pending,serial,armedAction,lastRowClick,feedback=nil,{},0,nil,nil,nil local importReview,importScroll,importArmed=nil,0,nil local actions={{label=\"Add\",action=\"add\"},{label=\"Edit\",action=\"edit\"},{label=\"Del\",action=\"delete\"},{label=\"Craft\",action=\"mode\"},{label=\"Ord D\",action=\"destination\"},{label=\"Sources\",action=\"sources\"},{label=\"Find\",action=\"search\"},{label=\"Filt\",action=\"filter\"},{label=\"R\",action=\"refresh\"},{label=\"Send O\",action=\"submit\"},{label=\"Retry\",action=\"retry\"},{label=\"Can C\",action=\"cancel\"},{label=\"Back\",action=\"back\"},}local function state()store.invalidate(STATE)return store.read(STATE,{stock={},cart={},queue={},retries={},acknowledgements={},config={orderAddress=\"Order\"},history={}})end local function clipped(value,width)return terminalUi.clip(value,math.max(1,tonumber(width)or 1),\"~\")end local function queueCommand(action,data,label)feedback=nil serial=serial+1 local token=\"craft-ui-\"..tostring(os.epoch(\"utc\"))..\"-\"..tostring(serial)if not fs.exists(COMMANDS)then fs.makeDir(COMMANDS)end data=data or{};data.action,data.token=action,token local handle=fs.open(fs.combine(COMMANDS,token..\".lua\"),\"w\")if not handle then return false,\"could not queue \"..tostring(label or action)end handle.write(textutils.serialise(data));handle.close()pending[token]={label=label or action,at=os.epoch(\"utc\")}return true end local function cleanPending(s)for token,row in pairs(pending)do local acknowledgement=(s.acknowledgements or{})[token]if acknowledgement then pending[token]=nil if acknowledgement.ok~=true then feedback=\"Cannot \"..row.label..\": \"..tostring(acknowledgement.error or\"request was rejected\")end elseif os.epoch(\"utc\")-row.at>5000 then pending[token]=nil;feedback=\"Crafting service did not acknowledge \"..row.label end end end local function pendingText()for _,row in pairs(pending)do return\"Pending: \"..row.label end return feedback end local function startModal(kind,label,value,replaceOnInput)modal={kind=kind,label=label,value=tostring(value or\"\"),replaceOnInput=replaceOnInput==true}end local function recordRecipeImport(entry)local history=store.read(RECIPE_IMPORTS,{})history[#history+1]=entry while#history>16 do table.remove(history,1)end store.write(RECIPE_IMPORTS,history)end local function currentOverlay(s)local handle=fs.exists(RECIPE_FILE)and fs.open(RECIPE_FILE,\"r\")or nil local source=handle and handle.readAll()or nil if handle then handle.close()end if source then local overlay,err=crafting.parseRecipeOverlay(source)if overlay then return overlay end return nil,err end return{schema=1,recipes={},tags={}}end local function beginRecipeImport(event,s)if not canMutate then feedback=\"Recipe import requires operator access\";return end local transfers=event and event.getFiles and event.getFiles()or nil if type(transfers)~=\"table\"or#transfers~=1 then feedback=\"Drop exactly one recipe pack into Crafting Queue\";return end local transfer,chunks,total=transfers[1],{},0 if not transfer or type(transfer.read)~=\"function\"then feedback=\"Dropped file is not readable\";return end while true do local chunk=transfer.read(4096)if not chunk then break end if type(chunk)~=\"string\"then feedback=\"Dropped recipe pack has invalid data\";return end total=total+#chunk if total>crafting.RECIPE_PACK_MAX_BYTES then feedback=\"Recipe pack exceeds the 64 KiB import limit\";return end chunks[#chunks+1]=chunk end local pack,packErr=crafting.parseRecipePack(table.concat(chunks))if not pack then feedback=\"Recipe pack rejected: \"..tostring(packErr);recordRecipeImport({at=os.epoch(\"utc\"),source=transfer.getName and transfer.getName()or\"dropped file\",status=\"rejected\",error=tostring(packErr):sub(1,120)});return end local overlay,overlayErr=currentOverlay(s)if not overlay then feedback=\"Could not read local recipe overlay: \"..tostring(overlayErr);return end local review,reviewErr=crafting.reviewRecipePack(s.recipes or{},pack.recipes)if not review then feedback=\"Recipe pack rejected: \"..tostring(reviewErr);return end importReview={source=tostring(transfer.getName and transfer.getName()or\"recipe pack\"):sub(1,96),overlay=overlay,incomingTags=pack.tags or{},review=review,selected=1}importScroll,importArmed,feedback=0,nil,nil end local function importSelection(row)if row and(row.status==\"new\"or row.status==\"conflict\")then row.selected=not row.selected end end local function applyImportAction(action)if not importReview then return end local rows=importReview.review.rows if action==\"all_new\"then for _,row in ipairs(rows)do if row.status==\"new\"then row.selected=true end end elseif action==\"keep_conflicts\"then for _,row in ipairs(rows)do if row.status==\"conflict\"then row.selected=false end end elseif action==\"replace_conflicts\"then for _,row in ipairs(rows)do if row.status==\"conflict\"then row.selected=true end end elseif action==\"cancel_import\"then recordRecipeImport({at=os.epoch(\"utc\"),source=importReview.source,status=\"cancelled\",counts=importReview.review.counts})importReview=nil elseif action==\"apply_import\"then local merged,importedOrErr,tags=crafting.mergeRecipePack(importReview.overlay.recipes,importReview.review,importReview.overlay.tags,importReview.incomingTags)if not merged then feedback=\"Recipe import rejected: \"..tostring(importedOrErr);return end local saved,saveErr=crafting.writeRecipeFile(RECIPE_FILE,merged,tags)if not saved then feedback=\"Could not save recipes: \"..tostring(saveErr);return end recordRecipeImport({at=os.epoch(\"utc\"),source=importReview.source,status=\"imported\",imported=importedOrErr,counts=importReview.review.counts})importReview,feedback=nil,nil end end local function finishModal(s,rows)local kind,value=modal.kind,modal.value;modal=nil if kind==\"search\"then query=value elseif kind==\"destination\"and value~=\"\"then queueCommand(\"destination\",{value=value},\"Order address\")elseif kind==\"add\"then local n=tonumber(value);if n and n>0 and rows[selectedStock]then queueCommand(\"add\",{name=rows[selectedStock].name,count=n},\"Add\")end elseif kind==\"edit\"then local n=tonumber(value);if n and n>0 and s.cart[selectedCart]then queueCommand(\"edit\",{index=selectedCart,count=n},\"Edit\")end elseif kind==\"cancel_confirm\"then queueCommand(\"cancel_active\",{},\"Cancel craft\")end end local function sourceChoices(s,target)local choices={}if target==\"requester\"then choices[#choices+1]={label=\"No Redstone Requester\",value=false}end local key=target==\"recipes\"and\"recipeServers\"or(target..\"s\")for _,source in ipairs(((s.sources or{})[key]or{}))do choices[#choices+1]={label=tostring(source.label or((source.transport==\"peer\"and\"Peer \"..tostring(source.peer)..\" / \")or\"Local / \")..tostring(source.name)),value=source}end return choices end local function chooseSource(s,target)local choices,selected=sourceChoices(s,target),1 if#choices==0 then return end while true do local w,h=term.getSize()term.setBackgroundColor(colors.black);term.setTextColor(colors.white);term.clear()term.setBackgroundColor(colors.blue);term.setCursorPos(1,1);term.clearLine();term.setCursorPos(2,1);term.write(\"CeetOS Crafting Queue | Select \"..target)term.setTextColor(colors.lightGray);term.setCursorPos(2,3);term.write(\"Use arrows/Enter or click a source. Backspace cancels.\")local targets={}for index,choice in ipairs(choices)do local y=4+index-1;if y>=h then break end term.setBackgroundColor(index==selected and colors.gray or colors.black);term.setTextColor(index==selected and colors.white or colors.lightGray);term.setCursorPos(2,y);term.clearLine();term.write(choice.label:sub(1,w-3))targets[#targets+1]={y=y,index=index}end local event,a,b,c=os.pullEvent()if event==\"key\"then local key=keys.getName(a)if key==\"backspace\"or key==\"q\"then return elseif key==\"up\"then selected=math.max(1,selected-1)elseif key==\"down\"then selected=math.min(#choices,selected+1)elseif key==\"enter\"then queueCommand(\"source\",{target=target,value=choices[selected].value},target..\" source\");return end elseif event==\"mouse_click\"and a==1 then for _,hit in ipairs(targets)do if c==hit.y then selected=hit.index;break end end elseif event==\"mouse_up\"and a==1 then for _,hit in ipairs(targets)do if c==hit.y then queueCommand(\"source\",{target=target,value=choices[hit.index].value},target..\" source\");return end end end end end local function applyAction(action,s,rows)if action==\"back\"then return\"exit\"end if action==\"more\"then actionPage=actionPage+1;buttonIndex=1;return end if not canMutate and action~=\"search\"and action~=\"filter\"and action~=\"refresh\"then return end if action==\"search\"then startModal(\"search\",\"Find ticker items\",query)elseif action==\"filter\"then filter=filter==\"all\"and\"craftable\"or(filter==\"craftable\"and\"stocked\"or\"all\")elseif action==\"refresh\"then queueCommand(\"refresh\",{},\"Refresh\")elseif action==\"mode\"then if(s.config or{}).requester then queueCommand(\"mode\",{value=not s.craftMode},\"Craft mode\")end elseif action==\"destination\"then startModal(\"destination\",\"Order address\",(s.config or{}).orderAddress or\"Order\")elseif action==\"sources\"then chooseSource(s,\"ticker\");s=state();chooseSource(s,\"requester\");s=state();chooseSource(s,\"recipes\")elseif action==\"submit\"then queueCommand(\"submit\",{},\"Submit\")elseif action==\"retry\"and#(s.retries or{})>0 then queueCommand(\"retry\",{index=1},\"Retry\")elseif action==\"cancel\"and s.active then startModal(\"cancel_confirm\",\"Cancel active craft? Issued Create packages may still arrive\",\"\")elseif action==\"delete\"and focus==\"cart\"then queueCommand(\"remove\",{index=selectedCart},\"Remove\")elseif action==\"add\"and focus==\"stock\"and rows[selectedStock]then startModal(\"add\",\"Add \"..rows[selectedStock].name..\" quantity\",\"1\",true)elseif action==\"edit\"and focus==\"cart\"and s.cart[selectedCart]then startModal(\"edit\",\"Set \"..s.cart[selectedCart].name..\" quantity\",s.cart[selectedCart].count,true)end end local function frame(x1,y1,x2,y2,title)return terminalUi.box(x1,y1,x2,y2,title,colors.gray,colors.lightBlue)end local function drawButton(x,y,entry,selected,armed,targets)local text=\"[\"..entry.label..\"]\"local width=select(1,term.getSize())if x+#text-1>width then return x end local background=armed and colors.yellow or(selected and colors.gray or colors.black)local enabled=canMutate or entry.action==\"search\"or entry.action==\"filter\"or entry.action==\"refresh\"or entry.action==\"back\"terminalUi.write(x,y,text,armed and colors.black or(enabled and(selected and colors.white or colors.lightGray)or colors.gray),background)targets[#targets+1]={x1=x,x2=x+#text-1,y1=y,y2=y,action=entry.action}return x+#text+1 end local function visibleActions(w)local pageSize=w>=48 and 7 or 5 local pages=math.max(1,math.ceil(#actions/pageSize))actionPage=math.max(1,math.min(pages,actionPage))local out,first,last={},(actionPage-1)*pageSize+1,math.min(#actions,actionPage*pageSize)for index=first,last do out[#out+1]=actions[index]end if pages>1 then out[#out+1]={label=\"More \"..actionPage..\"/\"..pages,action=\"more\"}end buttonIndex=math.max(1,math.min(#out,buttonIndex))return out end local function drawActionRows(w,h,targets)local entries=visibleActions(w)local firstCount=math.ceil(#entries/2)terminalUi.clearLine(h-2,colors.black);terminalUi.clearLine(h-1,colors.black)local x,row=2,h-2 for index,entry in ipairs(entries)do if index==firstCount+1 then x,row=2,h-1 end x=drawButton(x,row,entry,focus==\"actions\"and buttonIndex==index,armedAction==entry.action,targets)end return entries end local function drawModal(w,h)if not modal then return end terminalUi.clearLine(h-2,colors.gray);terminalUi.write(2,h-2,modal.label,colors.white,colors.gray,w-3)if modal.kind==\"cancel_confirm\"then terminalUi.clearLine(h-1,colors.gray);terminalUi.write(2,h-1,\"[Confirm cancel] [Keep running]\",colors.white,colors.gray,w-3)else terminalUi.clearLine(h-1,colors.gray)if modal.replaceOnInput then terminalUi.write(2,h-1,modal.value,colors.black,colors.lightBlue,w-4)else terminalUi.write(2,h-1,\"> \"..modal.value,colors.white,colors.gray,w-4)end term.setCursorPos(math.min(w-1,4+#modal.value),h-1)terminalUi.clearLine(h,colors.gray);terminalUi.write(2,h,\"[Save] [Cancel]\",colors.white,colors.gray,w-3)end end local function drawImportReview()local w,h=term.getSize()term.setBackgroundColor(colors.black);term.setTextColor(colors.white);term.clear()if w<36 or h<15 then terminalUi.minimum(\"Recipe import\",\"Recipe review needs 36x15\",\"Resize | Backspace\")return{targets={},rows={}}end local review,counts=importReview.review,importReview.review.counts terminalUi.clearLine(1,colors.blue);terminalUi.write(2,1,\"CeetOS Crafting Queue | Review recipe pack\",colors.white,colors.blue,w-2)terminalUi.write(2,3,\"File: \"..clipped(importReview.source,w-8),colors.lightGray,colors.black,w-3)terminalUi.write(2,4,(\"New: %d  Conflicts: %d  Unchanged: %d  Invalid: %d\"):format(counts.new or 0,counts.conflict or 0,counts.unchanged or 0,counts.invalid or 0),colors.white,colors.black,w-3)frame(1,5,w,h-4,\"Recipes\")local capacity=math.max(1,h-10)importReview.selected=math.max(1,math.min(math.max(1,#review.rows),importReview.selected or 1))if importReview.selected<=importScroll then importScroll=importReview.selected-1 end if importReview.selected>importScroll+capacity then importScroll=importReview.selected-capacity end importScroll=math.max(0,math.min(math.max(0,#review.rows-capacity),importScroll))local targets,visible={},{}for offset=1,capacity do local index,row,y=importScroll+offset,review.rows[importScroll+offset],5+offset if row then local marker=row.status==\"new\"and(row.selected and\"[+]\"or\"[ ]\")or row.status==\"conflict\"and(row.selected and\"[Replace]\"or\"[Keep]\")or\"[Same]\"local colour=row.status==\"new\"and colors.lime or row.status==\"conflict\"and colors.yellow or colors.gray terminalUi.write(3,y,marker..\" \"..row.name,colour,index==importReview.selected and colors.gray or colors.black,w-5)targets[#targets+1]={x1=2,x2=w-1,y1=y,y2=y,action=\"select_recipe\",index=index}visible[#visible+1]=row end end local selected=review.rows[importReview.selected]if selected then local localText=selected.existing and(\"Local: \"..tostring(selected.existing.output)..\" via \"..tostring(selected.existing.address))or\"Local: none\"local incomingText=\"Incoming: \"..tostring(selected.incoming.output)..\" via \"..tostring(selected.incoming.address)terminalUi.write(2,h-3,clipped(localText..\" | \"..incomingText,w-3),colors.lightGray,colors.black,w-3)end local buttons={{label=\"Import\",action=\"apply_import\"},{label=\"All new\",action=\"all_new\"},{label=\"Keep conflicts\",action=\"keep_conflicts\"},{label=\"Replace conflicts\",action=\"replace_conflicts\"},{label=\"Cancel\",action=\"cancel_import\"},}local x,buttonRow=2,h-2 for _,button in ipairs(buttons)do local text=\"[\"..button.label..\"]\"if x+#text-1>w-1 and buttonRow==h-2 then x,buttonRow=2,h-1 end if x+#text-1<=w-1 then terminalUi.write(x,buttonRow,text,importArmed==button.action and colors.black or colors.white,importArmed==button.action and colors.yellow or colors.gray)targets[#targets+1]={x1=x,x2=x+#text-1,y1=buttonRow,y2=buttonRow,action=button.action}x=x+#text+1 end end terminalUi.write(2,h,\"Arrows select | Space toggle | Enter import | A/K/X | Backspace cancel\",colors.gray,colors.black,w-3)return{targets=targets,rows=visible}end local function draw(s,rows)local w,h=term.getSize();term.setBackgroundColor(colors.black);term.setTextColor(colors.white);term.clear()if w<36 or h<15 then return{targets=terminalUi.minimum(\"CeetOS Crafting Queue\",\"Crafting Queue needs 36x15\",\"Resize | Backspace\")or{},compact=true,actions={}}end local config=s.config or{}local tickerLabel=config.ticker and tostring(config.ticker.label or config.ticker.name)or\"not selected\"local requesterLabel=config.requester and tostring(config.requester.label or config.requester.name)or\"none\"local recipeLabel=config.recipeServer and tostring(config.recipeServer.label or(\"Peer \"..tostring(config.recipeServer.peer)))or\"local\"terminalUi.clearLine(1,colors.blue);terminalUi.write(2,1,\"CeetOS Crafting Queue | Ticker: \"..tickerLabel..\" | Recipes: \"..recipeLabel,colors.white,colors.blue,w-2)local items,total=crafting.cartTotals(s.cart)frame(1,2,w,5,\"Order\")terminalUi.write(3,3,\"Destination: \"..tostring(config.orderAddress or\"Order\")..\"   Craft mode: \"..(s.craftMode and\"ON\"or\"OFF\")..(config.requester and\"\"or\" (requires requester)\"),colors.white,colors.black,w-5)terminalUi.write(3,4,(\"Cart: %d items / %d units    Filter: %s    Find: %s\"):format(items,total,filter,query==\"\"and\"all\"or query),colors.lightGray,colors.black,w-5)local active,status=s.active,pendingText()or\"Ready\"if active then local item=active.items and active.items[active.index]if active.phase==\"await_crafted_output\"then local route=active.stepRoute or\"recipe route\"status=(\"%s; waiting for +%s %s in Stock Ticker\"):format(route,tostring(active.expectedOutput or\"?\"),tostring(active.waitingFor or item and item.name or\"recipe\"))elseif active.phase==\"craft\"and active.pendingCraftRequests then status=(\"Requester batching %s; %s craft request%s remaining\"):format(tostring(item and item.name or\"recipe\"),tostring(active.pendingCraftRequests),active.pendingCraftRequests==1 and\"\"or\"s\")elseif active.phase==\"await_package_confirmation\"or active.phase==\"await_peer_package\"then status=(\"Stock Ticker -> %s; package %s/%s: waiting for %s\"):format(tostring(active.stepAddress or\"destination\"),tostring(active.packageIndex or 1),tostring(active.packageCount or\"?\"),tostring(active.waitingFor or\"ingredient\"))elseif active.phase==\"await_delivery_confirmation\"then status=(\"Order submitted to %s; waiting for ticker decrease of %s\"):format(tostring(active.destination),tostring(active.accepted or\"?\"))else status=(\"%s | %s  requested:%s accepted:%s dispatched:%s remaining:%s\"):format(tostring(active.phase),tostring(item and item.name or\"finishing\"),tostring(active.requested or(item and item.count)or 0),tostring(active.accepted or\"-\"),tostring(active.delivered or 0),tostring(active.remaining or\"-\"))end end frame(1,6,w,8,active and\"Active job\"or\"Status\")terminalUi.write(3,7,s.error or status,(s.error or feedback)and colors.red or(active and colors.yellow or colors.lightGray),colors.black,w-5)local split,top,bottom=math.max(24,math.floor(w*.57)),10,h-4 frame(1,9,split,bottom,\"Items & recipes\")frame(split+1,9,w,bottom,\"Request list\")local lines=math.max(0,bottom-top)for i=1,lines do local y,item,cart=top+i-1,rows[i],(s.cart or{})[i]if item then terminalUi.write(3,y,crafting.displayRow(item.name,item.count,split-4),item.craftable and colors.lime or colors.white,focus==\"stock\"and selectedStock==i and colors.gray or colors.black,split-4)end if cart then terminalUi.write(split+3,y,crafting.displayRow(cart.name,cart.count,w-split-4),colors.white,focus==\"cart\"and selectedCart==i and colors.gray or colors.black,w-split-4)end end local history,retry=(s.history or{})[#(s.history or{})],(s.retries or{})[1]local detail=s.recoveryNotice or(history and(\"Last: \"..tostring(history.status)..\" \"..tostring(history.name or\"job\")..\" \"..tostring(history.dispatched or history.delivered or 0)..\"/\"..tostring(history.requested or 0)..(history.error and(\" - \"..tostring(history.error))or\"\"))or\"No dispatched orders yet\")if retry then detail=detail..\" | Retry: \"..tostring(retry.items[1].name)..\" x\"..tostring(retry.items[1].count)end terminalUi.write(2,bottom+1,detail,colors.gray,colors.black,w-2)local targets={};local actionEntries=drawActionRows(w,h,targets);if modal then drawModal(w,h)end return{split=split,top=top,bottom=bottom-1,targets=targets,actions=actionEntries}end local function hit(targets,x,y)return terminalUi.hit(targets,x,y)end local timer=os.startTimer(0.2)while true do local s=state();cleanPending(s)local rows=crafting.rows(s.stock,query,filter,s.recipes)selectedStock=math.max(1,math.min(math.max(1,#rows),selectedStock));selectedCart=math.max(1,math.min(math.max(1,#s.cart),selectedCart))local layout=importReview and drawImportReview()or draw(s,rows)local event,a,b,c=os.pullEvent()if event==\"timer\"and a==timer then timer=os.startTimer(0.2)elseif importReview then if event==\"key\"then local key=keys.getName(a)if key==\"backspace\"or key==\"q\"then applyImportAction(\"cancel_import\")elseif key==\"up\"then importReview.selected=math.max(1,(importReview.selected or 1)-1)elseif key==\"down\"then importReview.selected=math.min(#importReview.review.rows,(importReview.selected or 1)+1)elseif key==\"space\"or key==\"left\"or key==\"right\"then importSelection(importReview.review.rows[importReview.selected])elseif key==\"a\"then applyImportAction(\"all_new\")elseif key==\"k\"then applyImportAction(\"keep_conflicts\")elseif key==\"x\"then applyImportAction(\"replace_conflicts\")elseif key==\"enter\"then applyImportAction(\"apply_import\")end elseif event==\"mouse_click\"and a==1 then local target=hit(layout.targets,b,c)if target and target.action==\"select_recipe\"then importReview.selected=target.index elseif target then importArmed=target.action end elseif event==\"mouse_drag\"and a==1 then local target=hit(layout.targets,b,c);importArmed=target and target.action or nil elseif event==\"mouse_up\"and a==1 then local target=hit(layout.targets,b,c)if target and target.action==\"select_recipe\"then importReview.selected=target.index;importSelection(importReview.review.rows[target.index])elseif target and target.action==importArmed then applyImportAction(target.action)end importArmed=nil end elseif modal then if event==\"char\"and modal.kind~=\"cancel_confirm\"then modal.value=(modal.replaceOnInput and\"\"or modal.value)..a;modal.replaceOnInput=false elseif event==\"paste\"and modal.kind~=\"cancel_confirm\"then modal.value=(modal.replaceOnInput and\"\"or modal.value)..tostring(a):gsub(\"[\\r\\n]\",\"\");modal.replaceOnInput=false elseif event==\"key\"then local key=keys.getName(a)if key==\"enter\"then finishModal(s,rows)elseif key==\"backspace\"then if modal.kind==\"cancel_confirm\"or#modal.value==0 then modal=nil else modal.value=modal.value:sub(1,-2);modal.replaceOnInput=false end end elseif event==\"mouse_up\"and a==1 then local _,h=term.getSize()if modal.kind==\"cancel_confirm\"then if c==h-1 and b>=2 and b<=17 then finishModal(s,rows)elseif c==h-1 then modal=nil end elseif c==h and b>=2 and b<=7 then finishModal(s,rows)elseif c==h and b>=9 then modal=nil end end elseif event==\"key\"then local key=keys.getName(a)if key==\"backspace\"or key==\"q\"then return elseif key==\"tab\"then focus=focus==\"stock\"and\"cart\"or(focus==\"cart\"and\"actions\"or\"stock\")elseif key==\"up\"then if focus==\"stock\"then selectedStock=math.max(1,selectedStock-1)elseif focus==\"cart\"then selectedCart=math.max(1,selectedCart-1)end elseif key==\"down\"then if focus==\"stock\"then selectedStock=math.min(math.max(1,#rows),selectedStock+1)elseif focus==\"cart\"then selectedCart=math.min(math.max(1,#s.cart),selectedCart+1)end elseif key==\"left\"and focus==\"actions\"then buttonIndex=math.max(1,buttonIndex-1)elseif key==\"right\"and focus==\"actions\"then buttonIndex=math.min(#layout.actions,buttonIndex+1)elseif key==\"s\"then applyAction(\"search\",s,rows)elseif key==\"f\"then applyAction(\"filter\",s,rows)elseif key==\"r\"then applyAction(\"refresh\",s,rows)elseif key==\"space\"then applyAction(\"mode\",s,rows)elseif key==\"d\"then applyAction(\"destination\",s,rows)elseif key==\"o\"then applyAction(\"submit\",s,rows)elseif key==\"c\"then applyAction(\"cancel\",s,rows)elseif key==\"delete\"then applyAction(\"delete\",s,rows)elseif key==\"enter\"then local action=focus==\"actions\"and layout.actions[buttonIndex]and layout.actions[buttonIndex].action or(focus==\"stock\"and\"add\"or\"edit\")if action and applyAction(action,s,rows)==\"exit\"then return end end elseif event==\"mouse_click\"and a==1 then local target=hit(layout.targets,b,c)if target then armedAction=target.action elseif c>=layout.top and c<=layout.bottom then local index=c-layout.top+1 if b<=layout.split and rows[index]then focus,selectedStock=\"stock\",index local now=os.epoch(\"utc\")if lastRowClick and lastRowClick.side==\"stock\"and lastRowClick.index==index and now-lastRowClick.at<=450 then startModal(\"add\",\"Add \"..rows[index].name..\" quantity\",\"1\",true);lastRowClick=nil else lastRowClick={side=\"stock\",index=index,at=now}end elseif b>layout.split and s.cart[index]then focus,selectedCart=\"cart\",index local now=os.epoch(\"utc\")if lastRowClick and lastRowClick.side==\"cart\"and lastRowClick.index==index and now-lastRowClick.at<=450 then startModal(\"edit\",\"Set \"..s.cart[index].name..\" quantity\",s.cart[index].count,true);lastRowClick=nil else lastRowClick={side=\"cart\",index=index,at=now}end end end elseif event==\"mouse_drag\"and a==1 then local target=hit(layout.targets,b,c);armedAction=target and target.action or nil elseif event==\"mouse_up\"and a==1 then local target=hit(layout.targets,b,c)if target and target.action==armedAction then if applyAction(target.action,s,rows)==\"exit\"then return end end armedAction=nil elseif event==\"file_transfer\"then feedback=\"Recipe packs must be imported on the selected Recipe Server\"end end",
  ["ceetos/bin/ceetshareall.lua"] = "package.path=\"/?.lua;/?/init.lua;\"..package.path local auth=require(\"ceetos.lib.auth\")local peripherals=require(\"ceetos.lib.peripherals\")local mode=(...)==\"master\"and\"master\"or\"peer\"auth.require(\"operator\")print(\"Shared \"..peripherals.shareAll(mode)..\" peripherals (\"..mode..\")\")",
  ["ceetos/bin/ceetunshareall.lua"] = "package.path=\"/?.lua;/?/init.lua;\"..package.path local auth=require(\"ceetos.lib.auth\")local peripherals=require(\"ceetos.lib.peripherals\")auth.require(\"operator\")print(\"Unshared \"..peripherals.unshareAll()..\" peripherals\")",
}
local CEETOS_RELEASE_INSTALLER = true
local CEETOS_PROFILE = "desktop"

-- `wget --install` may run inside a deliberately restricted CeetShell child
-- environment. Self-cleaning is optional there: never require the shell API
-- merely to install the runtime.
local args = { ... }
local automated = args[1] == "--ceetos-apply"
local self = shell and shell.getRunningProgram and shell.getRunningProgram()
local cache = "/ceetos-updates/release.lua"
-- A signed release launched directly is retained outside the replaceable
-- runtime tree for verified recovery. Development installers deliberately do
-- not become propagation sources. Do this before removing the downloaded
-- program itself, but avoid copying the cache onto itself during recovery.
if CEETOS_RELEASE_INSTALLER and not automated and self and fs.exists(self) and self ~= cache then
  if not fs.exists("/ceetos-updates") then fs.makeDir("/ceetos-updates") end
  if fs.exists(cache) then fs.delete(cache) end
  pcall(fs.copy, self, cache)
end
if self and self ~= cache and fs.exists(self) then pcall(fs.delete, self) end

local bytes = 0
for _, contents in pairs(files) do bytes = bytes + #contents end
print("CeetOS " .. CEETOS_PROFILE .. " installer (" .. bytes .. " bytes)")
if not automated then
  print("This will replace /ceetos and /startup.lua. Continue? [y/N]")
  if read():lower() ~= "y" then print("Cancelled."); return end
end

local backup, migrate, migrationData = nil, false, {}
-- Clean stale full-tree backups from older installers before measuring space.
for _, name in ipairs(fs.list(".")) do
  if name:match("^ceetos%.backup") or name == "ceetos-migrate" then fs.delete(name) end
end
-- Development transactions can be much larger than the runtime. Preserve
-- only the reconnect record; staged payloads, test data, and rollback trees
-- are disposable and must not prevent an install from starting.
for _, name in ipairs({ "staging", "backups", "test-data" }) do
  local path = fs.combine("ceetos-dev", name)
  if fs.exists(path) then fs.delete(path) end
end
if fs.exists("ceetos") then
  if automated then migrate = true else
    print("Migrate saved CeetOS configuration? [Y/n]")
    local choice = read():lower()
    migrate = choice ~= "n" and choice ~= "no"
  end
  -- Copy only durable configuration to a small migration area, then remove
  -- the old tree before writing the new one. This works on nearly-full CC
  -- drives where retaining a complete backup would make installation fail.
  if migrate then
    local durable = { "users.lua", "network.lua", "shares.lua", "config.lua", "owner-service.lua", "seen-peers.lua", "jobs.lua", "job-workers.lua", "crafting-state.lua", "auth-authority.lua", "auth-authority-state.lua", "auth-directory.lua", "auth-session.lua", "cloud.lua", "cloud-state.lua" }
    if CEETOS_PROFILE == "recipe-server" then durable[#durable + 1] = "recipes.lua" end
    for _, name in ipairs(durable) do
      local source = fs.combine("ceetos/data", name)
      if fs.exists(source) then
        local input = fs.open(source, "r")
        if input then migrationData[name] = input.readAll(); input.close() end
      end
    end
  end
  fs.delete("ceetos")
end

for path, contents in pairs(files) do
  local parent = fs.getDir(path)
  if parent ~= "" and not fs.exists(parent) then fs.makeDir(parent) end
  local handle = assert(fs.open(path, "w"))
  handle.write(contents)
  handle.close()
end

if migrate then
  -- Preserve durable configuration, but never preserve an active session,
  -- temporary recovery window, remote result cache, or stale audit entries.
  local durable = { "users.lua", "network.lua", "shares.lua", "config.lua", "owner-service.lua", "seen-peers.lua", "jobs.lua", "job-workers.lua", "crafting-state.lua", "auth-authority.lua", "auth-authority-state.lua", "auth-directory.lua", "auth-session.lua", "cloud.lua", "cloud-state.lua" }
  if CEETOS_PROFILE == "recipe-server" then durable[#durable + 1] = "recipes.lua" end
  for _, name in ipairs(durable) do
    local contents = migrationData[name]
    if contents then
      if not fs.exists("ceetos/data") then fs.makeDir("ceetos/data") end
      local output = assert(fs.open(fs.combine("ceetos/data", name), "w"))
      output.write(contents); output.close()
    end
  end
  print("Saved CeetOS configuration migrated. Please log in again.")
end

-- The installer is intentionally transactional while it runs, but retaining
-- a full tree backup after a successful install quickly exhausts small CC
-- drives. Durable data has already been copied, so remove the old tree.
if automated then
  -- The root startup launcher sees this marker and boots the freshly written
  -- runtime rather than replaying the installer. The runtime verifies its
  -- loaded version before clearing it.
  if not fs.exists("/ceetos-updates") then fs.makeDir("/ceetos-updates") end
  local marker = fs.open("/ceetos-updates/pending.lua", "w")
  if marker then marker.write("return {state='verify',version=" .. "0.16.8" .. ",profile=" .. "\"desktop\"" .. "}"); marker.close() end
  print("CeetOS installed. Rebooting to verify the update.")
  os.reboot()
end
print("CeetOS installed. Reboot to start it.")

-- CEETOS_RELEASE_PAYLOAD_END
