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23FbWkpjfnIIpO1Y9taC1/sFKdNMw1niDsktx+6UJejIKUYq8+riWNAjNXwTLvg1cCFK2Y80h4KYUCSdTmliqDI7SHFpLd0gjc4HXTcha8mJaUF8DYqaofpJtvpyyxzEYcms9Y=
-- 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.9\"}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)local left,right=a.transport==\"cloud\",b.transport==\"cloud\"if left~=right then return not left end return tostring(a.label)<tostring(b.label)end)state.sources={tickers=tickers,requesters=requesters,recipeServers=recipeServers,updated=os.epoch(\"utc\")}if not state.config.recipeServer and#recipeServers>0 then local source=recipeServers[1]state.config.recipeServer={transport=source.transport,peer=source.peer,label=source.label}end 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 and not recipeServer 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.7\"]={public=\"TuXOgNPNNA9rKghCaKIfO29QUcqY9jNkEtq52ZeNj2oPMQpsFdoa7AYtj56cEvCIcH89Vri3DZxTUXHS6KOhK1aEd8HGxkW98IfdwkeO4XTScFfC/4OU5xqvOSMDbQKKNBaGqnIn+LsCAEI4W/75hqFpwtY4rVutNWyUh9JiKeT21P7Jursp2WL+sq7nT13SY+Z7ORzUvndmASkqh8dzs+w21VvE6HI+joRZgiv9EcJzNuIgwnauUUWABSAEsQHqboIjqzc9XXzbGELr+YM1TKDBPQk4EsfhSpdhS7nkqY/gIWBEHCbonhHj+7UkIGoM/OHYtkyhGax3uC7mMLn75qDYU496QCSTlfhp12Vwmiu3GSjR+qbwqJ5it+ZdKvNJfke4DfZa5BMv3viRtY0SRsHc0sSuGJZ7frIAFnI5giRr/2jtXDYzEItN8fuxDDmzFUmFRlmICPm3Xqo/r7u5KMffiF4tqktJ80P9YH3/P02AJdKl3UQnDc3wsS/5Mlr3A23d0EXX0UKR9yFRY1Je2gsHIIIq3EAy5mjlawrbEGaWJXwKQiYpG9AfgwIr0Kb7sfjxdX87jXE7WO+dBbpKtkA6bbvB0nms7rL9e9mtOOuNz+pX/3MOC2McM4oeTM2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"},},}",
  ["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=9,string=\"0.16.9\"}",
  ["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.9" .. ",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
