@north-light/cli 0.3.665 → 0.3.667

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/dist/api/client.d.ts +5 -0
  2. package/dist/api/client.js +3 -3
  3. package/dist/api/contract.d.ts +1 -1
  4. package/dist/api/contract.js +1 -1
  5. package/dist/api/dto/environments.d.ts +25 -0
  6. package/dist/api/dto/environments.js +0 -0
  7. package/dist/api/dto/nodes.d.ts +2 -0
  8. package/dist/api/dto/profiles.d.ts +15 -0
  9. package/dist/api/index.d.ts +1 -0
  10. package/dist/api/index.js +1 -1
  11. package/dist/api/routes.d.ts +1 -0
  12. package/dist/api/routes.js +1 -1
  13. package/dist/builtin-memory/02-turn-lifecycle/00-ending-a-turn.md +3 -1
  14. package/dist/builtin-memory/04-base-worker-exploring.md +2 -2
  15. package/dist/builtin-memory/crouter-concepts/scopes-and-trust.md +1 -1
  16. package/dist/builtin-memory/crouter-sdk/release-notes.md +6 -0
  17. package/dist/builtin-memory/northlight-apps/guides/files-and-documents.md +4 -8
  18. package/dist/clients/attach/chrome/canvas-panels.d.ts +9 -1
  19. package/dist/clients/attach/chrome/canvas-panels.js +1 -1
  20. package/dist/clients/attach/chrome/roster.js +6 -6
  21. package/dist/clients/attach/viewer.js +499 -499
  22. package/dist/commands/node.js +1 -1
  23. package/dist/commands/profile/environment.d.ts +2 -0
  24. package/dist/commands/profile/environment.js +2 -0
  25. package/dist/commands/profile/new.js +1 -1
  26. package/dist/commands/profile.js +1 -1
  27. package/dist/core/canvas/canvas.js +18 -18
  28. package/dist/core/environment-recipe.d.ts +20 -10
  29. package/dist/core/environment-recipe.js +1 -1
  30. package/dist/core/environment-repos.d.ts +7 -0
  31. package/dist/core/environment-repos.js +1 -0
  32. package/dist/core/environments.d.ts +4 -1
  33. package/dist/core/environments.js +1 -1
  34. package/dist/core/profiles/manifest.d.ts +7 -1
  35. package/dist/core/profiles/manifest.js +1 -1
  36. package/dist/core/providers/files.js +1 -1
  37. package/dist/core/runs/operations.js +7 -7
  38. package/dist/core/runtime/runner/blaxel/image-build.d.ts +6 -2
  39. package/dist/core/runtime/runner/blaxel/image-build.js +6 -5
  40. package/dist/core/secrets/blaxel-launch.js +3 -3
  41. package/dist/core/storage/caller-file.d.ts +12 -0
  42. package/dist/core/storage/caller-file.js +1 -0
  43. package/dist/core/storage/client.d.ts +0 -1
  44. package/dist/core/storage/client.js +2 -2
  45. package/dist/core/storage/shares.d.ts +0 -12
  46. package/dist/core/storage/shares.js +1 -1
  47. package/dist/daemon/api/app-listener.js +9 -9
  48. package/dist/daemon/api/environment-of.d.ts +2 -0
  49. package/dist/daemon/api/environment-of.js +3 -3
  50. package/dist/daemon/api/handlers/app-profiles.d.ts +1 -0
  51. package/dist/daemon/api/handlers/app-profiles.js +1 -1
  52. package/dist/daemon/api/handlers/attach.js +1 -1
  53. package/dist/daemon/api/handlers/environments.d.ts +2 -0
  54. package/dist/daemon/api/handlers/environments.js +1 -0
  55. package/dist/daemon/api/handlers/profiles.js +1 -1
  56. package/dist/daemon/api/handlers/transfer.d.ts +0 -6
  57. package/dist/daemon/api/handlers/transfer.js +1 -1
  58. package/dist/daemon/api/map.js +2 -2
  59. package/dist/daemon/api/operations.d.ts +2 -2
  60. package/dist/daemon/api/operations.js +1 -1
  61. package/dist/daemon/api/server.js +1 -1
  62. package/dist/daemon/crtrd.js +11 -11
  63. package/dist/daemon/due-sources.d.ts +1 -1
  64. package/dist/daemon/due-sources.js +1 -1
  65. package/dist/daemon/due.js +6 -6
  66. package/dist/daemon/reconcilers/idle-sandbox.d.ts +18 -0
  67. package/dist/daemon/reconcilers/idle-sandbox.js +7 -0
  68. package/dist/daemon/reconcilers/recipe-image.js +4 -4
  69. package/docs/apps/guides/files-and-documents.md +2 -6
  70. package/docs/concepts/scopes-and-trust.md +1 -1
  71. package/docs/sdk/release-notes.md +6 -0
  72. package/package.json +2 -2
  73. package/packages/crouter-identity/package.json +1 -1
  74. package/runtime.lock.json +13 -13
  75. package/dist/core/storage/download.d.ts +0 -23
  76. package/dist/core/storage/download.js +0 -1
@@ -1 +1 @@
1
- var ze=Object.defineProperty;var o=(e,r)=>ze(e,"name",{value:r,configurable:!0});import{IMPORT_TOKEN_PREFIX as He,importPrincipalFor as Le}from"./import-auth.js";import{createServer as ie}from"node:http";import{createServer as Be}from"node:https";import{chmodSync as xe,existsSync as G,readFileSync as se,unlinkSync as ae}from"node:fs";import{MINIMUM_RUNTIME_VERSION_HEADER as le,RUNTIME_VERSION_HEADER as Y,minimumRuntimeRefusal as De}from"../../api/runtime-version.js";import{CONTRACT_HEADER as K,CONTRACT_LEVEL as ce,REQUIRED_CONTRACT_HEADER as ue,contractRefusal as Fe}from"../../api/contract.js";import{crtrVersion as X}from"../../shared/crtr-version.js";import{apiSocketPath as Me}from"../../core/canvas/paths.js";import{resolveNodeToken as $e}from"../../core/canvas/node-tokens.js";import{isCloudRole as H,runAsPerson as J}from"../../core/canvas/person.js";import{isCanvasRequest as Je,serveCanvas as We}from"./canvas-host.js";import{personBearerVerifier as pe}from"./auth/person-bearer.js";import{personHasSnapshot as Z}from"../../core/scoped-state/person-store.js";import{loadPersonSettings as Q}from"../../core/scoped-state/person-rows.js";import{AppPrincipalResolver as je}from"./principal.js";import{createAppRequestHandler as Ve}from"./app-listener.js";import{decodeJwt as Ge}from"jose";import{handleRuntimeSignIn as Ye,isRuntimeSignInPath as Ke}from"./key-signin.js";import{RunError as S}from"../../core/runs/operations.js";import{removeVendorAccount as Xe,vendorStatus as Ze}from"./handlers/vendor-status.js";import{toErrorBody as Qe}from"./map.js";import{CONTROL_BODY_MAX_BYTES as qe}from"../../core/llm/body-limits.js";import{grantFor as er,hasSyncedGrants as rr}from"../../core/grants/mirror.js";import{readConfig as de}from"../../core/config.js";import{directoryIssuer as tr}from"../../core/directory/issuer.js";import{peerUid as nr}from"../../native/linux.js";import{findScopedApiToken as or,getApiToken as ir,listScopedApiTokens as sr}from"../../core/secrets.js";import{emitEvent as A}from"../../core/events/emit.js";import{envCrtrdTcp as ar,envCrtrdToken as lr}from"../../shared/env.js";import{Router as fe,actsAsPerson as me}from"./router.js";import{handleAttachUpgrade as cr,refuseUpgrade as y}from"./bridge.js";import{handleMachineLinkUpgrade as ur,machineLinkEnvironment as pr,setApiAddress as dr}from"../machine-link/holder.js";import{handleMachineViewUpgrade as fr,machineViewEnvironment as mr}from"../machine-link/forward.js";import{boundDaemonControl as gr}from"../control.js";import{attachRoutes as hr,mayAttachNode as ge}from"./handlers/attach.js";import{peerRoutes as Rr}from"../peer/handlers.js";import{bashJobRoutes as Ar}from"./handlers/bash-jobs.js";import{nodeFileRoutes as yr}from"./handlers/node-files.js";import{bashRoutes as vr}from"./handlers/bash.js";import{hookExecRoutes as _r}from"./handlers/hook-exec.js";import{brokerOperationRoutes as he}from"./handlers/broker-ops.js";import{brokerSignalRoutes as wr,brokerSignalStreams as Er}from"./handlers/broker-signals.js";import{brokerRecoveryRoutes as Re,nodeFaultRoutes as Sr}from"./handlers/broker-recovery.js";import{canvasRoutes as br}from"./handlers/canvas.js";import{conversationRoutes as Tr}from"./handlers/conversations.js";import{chatInventoryRoutes as Cr}from"./handlers/chat-inventory.js";import{daemonRoutes as kr}from"./handlers/daemon.js";import{fileRoutes as Ur}from"./handlers/files.js";import{focusRoutes as Or}from"./handlers/focus.js";import{analyticsRoutes as Pr}from"./handlers/analytics.js";import{memoryReadsRoutes as Nr}from"./handlers/memory-reads.js";import{memoryRoutes as Ir}from"./handlers/memory.js";import{healthRoutes as zr}from"./handlers/health.js";import{humanRequestRoutes as Hr}from"./handlers/human-requests.js";import{inboxRoutes as Lr}from"./handlers/inbox.js";import{feedbackCommentRoutes as Br}from"./handlers/feedback-comments.js";import{objectRoutes as xr}from"./handlers/objects.js";import{shareRoutes as Dr}from"./handlers/shares.js";import{customObjectRoutes as Fr}from"./handlers/custom-objects.js";import{docRoutes as Mr}from"./handlers/docs.js";import{deliveryRoutes as Ae}from"./handlers/delivery.js";import{deliveryRetryRoutes as $r}from"./handlers/delivery-retry.js";import{packageDocRoutes as Jr}from"./handlers/package-docs.js";import{documentAccessRoutes as Wr}from"./handlers/document-access.js";import{pluginAppRoutes as jr}from"./handlers/plugin-app-token.js";import{brokerMailRoutes as ye,messageRoutes as Vr}from"./handlers/messages.js";import{modelAuthRoutes as Gr}from"./handlers/modelauth.js";import{llmRoutes as Yr}from"./handlers/llm.js";import{providerRoutes as Kr}from"./handlers/providers.js";import{modelConfigRoutes as Xr}from"./handlers/model-config.js";import{settingsRoutes as Zr}from"./handlers/settings.js";import{nodeRoutes as Qr}from"./handlers/nodes.js";import{nodeRecordRoutes as qr}from"./handlers/node-records.js";import{nodeOutcomeRoutes as et}from"./handlers/node-outcomes.js";import{nodeEventRoutes as rt}from"./handlers/node-events.js";import{profileRoutes as tt}from"./handlers/profiles.js";import{prospectiveChatInventoryRoutes as nt}from"./handlers/prospective-chat-inventory.js";import{reportRoutes as ot}from"./handlers/reports.js";import{runRoutes as it}from"./handlers/run-routes.js";import{reviewCommentRoutes as st}from"./handlers/review-comments.js";import{reviewRoutes as at}from"./handlers/reviews.js";import{subscriptionRoutes as lt}from"./handlers/subscriptions.js";import{structuredRequestRoutes as ct}from"./handlers/structured-requests.js";import{cronRoutes as ut}from"./handlers/crons.js";import{setCronRequestHandler as ve}from"../cron/run-socket.js";import{RUN_TOKEN_PREFIX as pt,cronPrincipalForRunToken as dt}from"../cron/run-token.js";import{worktreeRoutes as ft}from"./handlers/worktree.js";import{limitsRoutes as mt}from"./handlers/limits.js";import{chargeRoutes as gt,spendLimitRoutes as ht}from"./handlers/charges.js";import{executionStartRoutes as Rt}from"./handlers/execution-start.js";import{machineCredentialRoutes as At}from"./handlers/machine-credential.js";import{importRoutes as yt}from"./handlers/imports.js";import{gitCredentialRoutes as vt}from"./handlers/git-credential.js";function _t(e){return new fe().registerAll(zr(e)).registerAll(kr).registerAll(Dr).registerAll(Qr).registerAll(qr).registerAll(et).registerAll($r).registerAll(rt).registerAll(Ar).registerAll(yr).registerAll(vr).registerAll(_r).registerAll(he).registerAll(wr).registerAll(Ae).registerAll(Re).registerAll(Sr).registerAll(ft).registerAll(mt).registerAll(gt).registerAll(Rt).registerAll(At).registerAll(yt).registerAll(vt).registerAll(ht).registerAll(ye).registerAll(Vr).registerAll(ot).registerAll(it).registerAll(ct).registerAll(hr).registerAll(br).registerAll(Tr).registerAll(Pr).registerAll(Nr).registerAll(Ir).registerAll(Ur).registerAll(xr).registerAll(Fr).registerAll(Mr).registerAll(Jr).registerAll(Wr).registerAll(jr).registerAll(Or).registerAll(lt).registerAll(ut).registerAll(tt).registerAll(Gr).registerAll(Yr).registerAll(Kr).registerAll(Xr).registerAll(Zr).registerAll(at).registerAll(st).registerAll(Lr).registerAll(Hr).registerAll(Cr).registerAll(nt).registerAll(Br).registerAll(Rr)}o(_t,"buildRouter");function wt(e,r){if(e.toUpperCase()!=="GET")return null;const i=r.split("/").filter(u=>u.length>0);if(i.length!==4||i[0]!=="v1"||i[1]!=="nodes"||i[3]!=="attach")return null;const a=i[2];return a===void 0||a===""?null:decodeURIComponent(a)}o(wt,"attachNodeId");function Et(e){const r=e.trim();if(r==="")return null;const i=r.lastIndexOf(":");if(i<0)return null;const a=r.slice(0,i),u=r.slice(i+1),d=Number(u);return!Number.isInteger(d)||d<0||d>65535?null:{host:a===""?"0.0.0.0":a,port:d}}o(Et,"parseTcp");function St(e,r){return`${e.includes(":")?`[${e}]`:e}:${r}`}o(St,"formatTcpAddress");const P={code:"unauthorized",message:"missing or invalid bearer token"},L={code:"owner_only",message:"attach is owner-only; a scoped token does not reach it"},F={code:"person_bearer_not_supported",message:"this listener accepts a person bearer only on a cloud role with CRTR_DIRECTORY_URL and CRTR_PUBLIC_API_URL set; call with a node, app or public token"},q={class:"anonymous",app:"",node:"",run:null,uid:-1,sub:"",grant:null,client_id:null,scopes:[]},B=new WeakMap;function M(e){return B.get(e)}o(M,"socketPrincipal");async function _e(e,r){const i=process.platform==="linux"?nr(e.socket):null,a=e.headers.authorization;if(a===void 0)return i===null||r.has(i)?{class:"person"}:"unauthorized";if(typeof a!="string"||!a.startsWith("Bearer "))return"unauthorized";if(a.slice(7).startsWith("crtr_pub_"))return q;if(a.slice(7).startsWith(ee)){const u=be(a.slice(7));return u!==void 0&&(i===null||r.has(i))?u.principal:"unauthorized"}return we(a.slice(7),i)}o(_e,"resolveSocketPrincipal");async function we(e,r){const i=await $e(e);if(!i||r!==null&&r!==i.uid)return"unauthorized";const a=tr();if(a&&!H()&&!await rr(a))return"runtime_starting";const u=i.grant??(await er("app:terminal",i.sub))?.id??null;return{class:"broker",...i,grant:u}}o(we,"brokerPrincipal");function Ee(e){if(!(e.class==="anonymous"||e.class==="import"))return e.sub!==void 0&&e.sub!==""?e.sub:void 0}o(Ee,"requestPerson");function Se(e,r){r.class==="broker"&&A({event:"api.request.principal",level:r.app==="app:terminal"?"debug":"info",node_id:r.node,fields:{principal:`${r.app} node:${r.node}`,method:e.method,path:e.url}})}o(Se,"noteBrokerRequest");const ee="crtr_app_";function be(e){const r=e.startsWith(ee)?or(e):void 0;return r===void 0?void 0:{principal:{class:"app",app:r.grantee,scopes:r.scopes},ceiling:r.scopes}}o(be,"appBearer");function bt(e){const r=new Map;for(const i of sr("user"))r.set(i.token,{principal:{class:"app",app:i.grantee,scopes:i.scopes},ceiling:i.scopes});return e!==void 0&&r.set(e,{principal:{class:"person"},ceiling:null}),r}o(bt,"resolveBearers");function Tt(e){try{return Ge(e).act!==void 0}catch{return!1}}o(Tt,"carriesAct");const Ct=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*$/;function k(e,r){return e!==void 0&&(e.reason=r),"unauthorized"}o(k,"deny");async function Te(e,r,i){const a=e.headers.authorization;if(a===void 0&&(e.method??"GET").toUpperCase()==="GET"&&(e.url??"").split("?")[0]==="/healthz")return{principal:q,ceiling:null};if(typeof a!="string"||!a.startsWith("Bearer "))return k(i,a===void 0?"no_authorization_header":"not_a_bearer");const u=a.slice(7);if(u.startsWith("crtr_pub_"))return{principal:q,ceiling:null};if(u.startsWith(ee))return be(u)??k(i,"app_token_unknown");if(u.startsWith(pt)){const w=await dt(u);return w===null?k(i,"run_token_invalid_or_settled"):{principal:w,ceiling:null}}const d=r.get(u);if(d!==void 0)return d;const R=Le(u);if(R!==null)return{principal:R,ceiling:null};if(u.startsWith(He))return k(i,"import_token_invalid");if(Ct.test(u)){if(H()&&Tt(u)){const x=j();if(x===null)return"person_bearer";try{const _=await x.verifyCall(a);return _.chain[0]?.sub.startsWith("app:")?{call:_}:k(i,"call_token_presenter_not_an_app")}catch(_){return _ instanceof S&&_.status===503?"runtime_starting":k(i,`call_token_${_ instanceof S?_.code:"invalid"}`)}}const w=H()?pe():null;if(w===null)return"person_bearer";const U=await w.verify(u);return U===null?k(i,"person_bearer_not_verified"):{principal:{class:"person",sub:U},ceiling:null}}const m=await we(u,null);return m==="unauthorized"?k(i,"node_token_unknown"):typeof m=="string"?m:{principal:m,ceiling:null}}o(Te,"authorizeTcp");let W;function j(){if(W!==void 0)return W;const e=process.env.CRTR_DIRECTORY_URL||void 0,r=process.env.CRTR_PUBLIC_API_URL||void 0;return W=e===void 0||r===void 0?null:new je(e,r,async()=>{}),W}o(j,"cloudCallResolver");let Ce;function kt(){const e=j();if(e===null)throw new S(503,"runtime_starting","app calls are not configured on this listener");return Ce??=Ve(e,async()=>!0,async()=>{}),Ce}o(kt,"cloudAppCalls");async function Ut(e,r){N(r),I(r);const i=j();try{if(i===null)throw new S(503,"runtime_starting","sign-in is not configured on this listener");await Ye(e,r,new URL(e.url??"/","http://runtime.local"),i)}catch(a){if(!(a instanceof S))throw a;if(r.headersSent){r.destroy();return}r.writeHead(a.status,{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}),r.end(JSON.stringify({error:{code:a.code,message:a.message,...a.param?{param:a.param}:{},origin:"runtime"}}))}}o(Ut,"serveRuntimeSignIn");function Ot(){const e=process.env.CRTRD_TLS_CERT||void 0,r=process.env.CRTRD_TLS_KEY||void 0;if(e===void 0&&r===void 0)return null;if(e===void 0||r===void 0)throw new Error("CRTRD_TLS_CERT and CRTRD_TLS_KEY must be set together");return{cert:se(e),key:se(r)}}o(Ot,"tcpTls");function N(e){e.setHeader(Y,X()),e.setHeader(K,ce)}o(N,"advertiseRuntime");function I(e){e.setHeader("Access-Control-Allow-Origin","*"),e.setHeader("Access-Control-Expose-Headers",`${Y}, ${K}`)}o(I,"exposeRuntimeHeaders");function Pt(e,r){return(e.method??"GET").toUpperCase()!=="OPTIONS"?!1:(N(r),r.writeHead(204,{"Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":`${Y}, ${K}`,"Access-Control-Allow-Headers":`authorization, content-type, ${le.toLowerCase()}, ${ue.toLowerCase()}`,"Access-Control-Allow-Methods":"GET, POST, PATCH, PUT, DELETE, OPTIONS","Access-Control-Max-Age":"600"}),r.end(),!0)}o(Pt,"answerPreflight");function V(e,r=!1){N(e),r&&I(e),e.writeHead(401,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{...P,origin:"runtime"}}))}o(V,"writeUnauthorized");function Nt(e){N(e),I(e),e.writeHead(401,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{...F,origin:"runtime"}}))}o(Nt,"writePersonBearerRefused");const It={"/v1/runtime/vendor-status":{method:"GET",purpose:"vendor_status"},"/v1/runtime/vendor-account-remove":{method:"POST",purpose:"vendor_account_remove"}};async function zt(e,r){if(!H())return!1;const i=new URL(e.url??"/","http://runtime.local").pathname,a=It[i];if(a===void 0||e.method!==a.method)return!1;const u=o((d,R)=>{N(r),I(r),r.writeHead(d,{"content-type":"application/json; charset=utf-8"}),r.end(JSON.stringify(R))},"answer");try{const d=pe();if(d===null)throw new S(401,F.code,F.message);const R=e.headers.authorization,m=R?.startsWith("Bearer ")?await d.verifyPurpose(R.slice(7),a.purpose):null;if(m===null)throw new S(401,"unauthorized","invalid directory token");const w=a.purpose==="vendor_status"?void 0:await Ht(e);u(200,await J(m,async()=>a.purpose==="vendor_status"?Ze():await Xe(w)))}catch(d){const{status:R,body:m}=Qe(d);u(R,m)}return!0}o(zt,"serveCloudVendorRoute");async function Ht(e){const r=[];let i=0;for await(const a of e){if(i+=a.length,i>qe)throw new S(400,"invalid_request","request body too large");r.push(a)}if(i!==0)try{return JSON.parse(Buffer.concat(r).toString("utf8"))}catch{throw new S(400,"invalid_request","invalid JSON body")}}o(Ht,"readVendorBody");function ke(e){N(e),e.writeHead(503,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{code:"runtime_starting",message:"grant sync is not ready",type:"server_error",origin:"runtime",retryable:!0}}))}o(ke,"writeRuntimeStarting");function Lt(e,r){e.writeHead(503,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{code:"startup_blocked",message:r,origin:"runtime"}}))}o(Lt,"writeStartupBlocked");function Ue(e,r,i){return new Promise(a=>{for(const m of r)m.destroy();if(i===void 0){try{e.closeAllConnections()}catch{}e.close(()=>a());return}const u=[];e.close(()=>{for(const m of u)clearTimeout(m);a()});const d=setInterval(()=>e.closeIdleConnections(),250),R=setTimeout(()=>e.closeAllConnections(),i);u.push(d,R),e.closeIdleConnections()})}o(Ue,"closeServer");function To(e={}){let r=null;const i=_t(()=>r),a=new fe().registerAll(he).registerAll(Ae).registerAll(Re).registerAll(ye),u=o((t,s)=>{const c=gr()?.startupBlock()??null;return c===null||t==="GET"&&(s==="/healthz"||s==="/v1/status"||s==="/v1/ready")||t==="POST"&&(s==="/v1/daemon/migrate"||s==="/v1/daemon/admit")||c.phase==="recovering"&&a.match(t,s)!==null?null:c},"startupBlockFor"),d=e.socketPath??Me(),R=new Set([process.getuid?.()??0,...de("user").runtime?.person_uids??[]]),m=o((t,s,c)=>{N(s);const p=o(n=>Array.isArray(n)?n[0]:n,"first"),O=p(t.headers[le.toLowerCase()]),h=De(O,X())??Fe(p(t.headers[ue.toLowerCase()]),ce,{legacyMinimum:O,runtimeVersion:X()});if(h!==null){s.writeHead(h.status,{"content-type":"application/json; charset=utf-8"}),s.end(JSON.stringify({error:{code:h.code,message:h.message,type:"invalid_request_error",origin:"runtime",retryable:!1,..."param"in h?{param:h.param}:{details:h.details}}}));return}const E=o(n=>{const l=M(t);A({event:"api.request.failed",level:"error",...l?.class==="broker"?{node_id:l.node}:{},error:n instanceof Error?n:new Error(String(n))});try{s.headersSent||s.writeHead(500,{"content-type":"application/json; charset=utf-8"}),s.end(JSON.stringify({error:{code:"internal",message:"internal error",origin:"runtime"}}))}catch{}},"internalFailure");let T;try{T=new URL(t.url??"/","http://127.0.0.1")}catch{try{s.writeHead(400,{"content-type":"application/json; charset=utf-8"}),s.end(JSON.stringify({error:{code:"invalid_request",message:"request URL is invalid",origin:"runtime"}}))}catch{}return}try{const n=u((t.method??"GET").toUpperCase(),T.pathname);if(n!==null){Lt(s,n.message);return}const l=M(t)??{class:"person"},f=Ee(l),g=o(()=>i.handle(t,s,c,l),"handled");(f===void 0?g():J(f,o(async()=>{Z()||await Q(f),await g()},"handledAsPerson"))).catch(E)}catch(n){E(n)}},"onRequest"),w=o(async(t,s,c)=>{const p=M(t);return p===void 0||me(p)||await ge(p,"either",c)?!0:(y(s,404,"Not Found","node_not_found",`no node ${c}`),!1)},"authorizeAttachUpgrade"),U=new Set,x=o(t=>{U.add(t),t.once("close",()=>U.delete(t)),t.on("error",()=>{})},"trackUpgrade"),_=o((t,s,c)=>{try{const p=new URL(t.url??"/","http://127.0.0.1"),O=u((t.method??"GET").toUpperCase(),p.pathname);if(O!==null){y(s,503,"Service Unavailable","startup_blocked",O.message);return}const h=wt(t.method??"GET",p.pathname);if(h===null){s.destroy();return}const E=(()=>{const n=M(t);return n===void 0?void 0:Ee(n)})(),T=o(()=>w(t,s,h).then(n=>n?cr(t,s,c,h,async l=>{const f=M(t);return f===void 0||me(f)||await ge(f,l,h)}):void 0),"attach");(E===void 0?T():J(E,async()=>{Z()||await Q(E),await T()})).catch(()=>{try{s.destroy()}catch{}})}catch{try{s.destroy()}catch{}}},"onUpgrade"),Oe=o(t=>{t.on("error",s=>{A({event:"api.server.failed",level:"error",error:s})})},"bindErrorHandler"),Pe=o(async(t,s)=>{try{const c=await _e(t,R);if(c==="unauthorized"){A({event:"api.principal.denied",level:"warn",fields:{method:t.method}}),V(s);return}if(c==="runtime_starting"){ke(s);return}B.set(t,c),Se(t,c),m(t,s,c.class==="app"?c.scopes:null)}catch(c){A({event:"api.principal.failed",level:"error",error:c instanceof Error?c:new Error(String(c))}),V(s)}},"onSocketRequest"),D=ie((t,s)=>{Pe(t,s).catch(c=>A({event:"api.principal.failed",level:"error",error:c instanceof Error?c:new Error(String(c))}))}),Ne=o(async(t,s,c)=>{try{const p=await _e(t,R);if(p==="unauthorized"||p==="runtime_starting"){p==="unauthorized"&&A({event:"api.principal.denied",level:"warn",fields:{method:t.method}}),y(s,p==="unauthorized"?401:503,"Unauthorized",p,"socket principal unavailable");return}if(p.class!=="person"&&p.class!=="broker"){y(s,403,"Forbidden",L.code,L.message);return}B.set(t,p),_(t,s,c)}catch(p){A({event:"api.principal.failed",level:"error",error:p instanceof Error?p:new Error(String(p))}),y(s,401,"Unauthorized",P.code,P.message)}},"onSocketUpgrade");D.on("upgrade",(t,s,c)=>{x(s),Ne(t,s,c).catch(p=>A({event:"api.principal.failed",level:"error",error:p instanceof Error?p:new Error(String(p))}))}),ve((t,s,c)=>{B.set(t,c),m(t,s,null)});let re=!1,te,ne;const Ie=new Promise((t,s)=>{te=t,ne=s});D.once("listening",()=>{re=!0,te()}),D.on("error",t=>{A({event:"api.server.failed",level:"error",error:t}),re||ne(t)});try{G(d)&&ae(d)}catch{}D.listen(d,()=>{try{xe(d,process.platform==="linux"&&G("/run/crtr/launcher.sock")?438:384)}catch(t){A({event:"api.socket.chmod_failed",level:"error",error:t instanceof Error?t:new Error(String(t))})}});let b;const $=e.tcp??ar()??de("user").api.tcp;if($!==void 0&&$!==""){const t=Et($);if(t===null)A({event:"api.tcp.invalid",level:"error",error:new Error(`invalid CRTRD_TCP/--tcp spec: ${$}`)});else{H()&&j();const s=e.token??lr()??ir("user"),c=bt(s),p=o(async(n,l)=>{if(Je(n)){await We(n,l);return}if(Pt(n,l))return;if(H()&&Ke(new URL(n.url??"/","http://runtime.local").pathname)){await Ut(n,l);return}if(await zt(n,l))return;const f={},g=await Te(n,c,f);if(g==="runtime_starting"){I(l),ke(l);return}if(g==="person_bearer"){Nt(l);return}if(g==="unauthorized"){A({event:"api.principal.denied",level:"warn",fields:{method:n.method,listener:"tcp",path:new URL(n.url??"/","http://runtime.local").pathname,reason:f.reason??"unknown"}}),V(l,!0);return}if("call"in g){I(l);const z=g.call.sub;await J(z,async()=>{Z()||await Q(z),await kt()(n,l,g.call)});return}B.set(n,g.principal),Se(n,g.principal),I(l),m(n,l,g.ceiling)},"tcpOnRequest"),O=o(async(n,l,f)=>{const g=pr(n);if(g!==null){const v=await ur(n,l,f,g);v!==null&&y(l,v.status,v.text,v.code,v.message);return}const z=mr(n);if(z!==null){const v=fr(n,l,f,z);v!==null&&y(l,v.status,v.text,v.code,v.message);return}const C=await Te(n,c);if(C==="runtime_starting"){y(l,503,"Service Unavailable","runtime_starting","grant sync is not ready");return}if(C==="person_bearer"){y(l,401,"Unauthorized",F.code,F.message);return}if(C==="unauthorized"){y(l,401,"Unauthorized",P.code,P.message);return}if("call"in C){y(l,403,"Forbidden",L.code,L.message);return}if(C.ceiling!==null||C.principal.class==="anonymous"||C.principal.class==="import"){y(l,403,"Forbidden",L.code,L.message);return}B.set(n,C.principal),_(n,l,f)},"tcpOnUpgrade"),h=o(n=>{A({event:"api.principal.failed",level:"error",error:n instanceof Error?n:new Error(String(n))})},"failed"),E=o((n,l)=>{p(n,l).catch(f=>{h(f),l.headersSent?l.destroy():V(l,!0)})},"listener"),T=Ot();b=T===null?ie(E):Be(T,E),b.on("upgrade",(n,l,f)=>{x(l),O(n,l,f).catch(g=>{h(g),y(l,401,"Unauthorized",P.code,P.message)})}),Oe(b),b.once("listening",()=>{const n=b?.address();if(n!==null&&typeof n=="object"){const{address:l,port:f}=n;r=St(l,f),l!=="0.0.0.0"&&l!=="::"&&dr(r)}}),b.listen(t.port,t.host)}}let oe=!1;return{ready:Ie,tcpAddress:o(()=>r,"tcpAddress"),close:o(async(t={})=>{if(!oe){oe=!0,ve(null),Er.close(),await Promise.all([Ue(D,U,t.graceMs),b!==void 0?Ue(b,U,t.graceMs):Promise.resolve()]);try{G(d)&&ae(d)}catch{}}},"close")}}o(To,"createApiServer");export{_t as buildRouter,Ue as closeServer,To as createApiServer,M as socketPrincipal};
1
+ var ze=Object.defineProperty;var o=(e,r)=>ze(e,"name",{value:r,configurable:!0});import{IMPORT_TOKEN_PREFIX as He,importPrincipalFor as Le}from"./import-auth.js";import{createServer as ie}from"node:http";import{createServer as Be}from"node:https";import{chmodSync as xe,existsSync as G,readFileSync as se,unlinkSync as ae}from"node:fs";import{MINIMUM_RUNTIME_VERSION_HEADER as le,RUNTIME_VERSION_HEADER as Y,minimumRuntimeRefusal as De}from"../../api/runtime-version.js";import{CONTRACT_HEADER as K,CONTRACT_LEVEL as ce,REQUIRED_CONTRACT_HEADER as ue,contractRefusal as Fe}from"../../api/contract.js";import{crtrVersion as X}from"../../shared/crtr-version.js";import{apiSocketPath as Me}from"../../core/canvas/paths.js";import{resolveNodeToken as $e}from"../../core/canvas/node-tokens.js";import{isCloudRole as H,runAsPerson as J}from"../../core/canvas/person.js";import{isCanvasRequest as Je,serveCanvas as We}from"./canvas-host.js";import{personBearerVerifier as pe}from"./auth/person-bearer.js";import{personHasSnapshot as Z}from"../../core/scoped-state/person-store.js";import{loadPersonSettings as Q}from"../../core/scoped-state/person-rows.js";import{AppPrincipalResolver as je}from"./principal.js";import{createAppRequestHandler as Ve}from"./app-listener.js";import{decodeJwt as Ge}from"jose";import{handleRuntimeSignIn as Ye,isRuntimeSignInPath as Ke}from"./key-signin.js";import{RunError as S}from"../../core/runs/operations.js";import{removeVendorAccount as Xe,vendorStatus as Ze}from"./handlers/vendor-status.js";import{toErrorBody as Qe}from"./map.js";import{CONTROL_BODY_MAX_BYTES as qe}from"../../core/llm/body-limits.js";import{grantFor as er,hasSyncedGrants as rr}from"../../core/grants/mirror.js";import{readConfig as de}from"../../core/config.js";import{directoryIssuer as tr}from"../../core/directory/issuer.js";import{peerUid as nr}from"../../native/linux.js";import{findScopedApiToken as or,getApiToken as ir,listScopedApiTokens as sr}from"../../core/secrets.js";import{emitEvent as A}from"../../core/events/emit.js";import{envCrtrdTcp as ar,envCrtrdToken as lr}from"../../shared/env.js";import{Router as fe,actsAsPerson as me}from"./router.js";import{handleAttachUpgrade as cr,refuseUpgrade as y}from"./bridge.js";import{handleMachineLinkUpgrade as ur,machineLinkEnvironment as pr,setApiAddress as dr}from"../machine-link/holder.js";import{handleMachineViewUpgrade as fr,machineViewEnvironment as mr}from"../machine-link/forward.js";import{boundDaemonControl as gr}from"../control.js";import{attachRoutes as hr,mayAttachNode as ge}from"./handlers/attach.js";import{peerRoutes as Rr}from"../peer/handlers.js";import{bashJobRoutes as Ar}from"./handlers/bash-jobs.js";import{nodeFileRoutes as yr}from"./handlers/node-files.js";import{bashRoutes as vr}from"./handlers/bash.js";import{hookExecRoutes as _r}from"./handlers/hook-exec.js";import{brokerOperationRoutes as he}from"./handlers/broker-ops.js";import{brokerSignalRoutes as wr,brokerSignalStreams as Er}from"./handlers/broker-signals.js";import{brokerRecoveryRoutes as Re,nodeFaultRoutes as Sr}from"./handlers/broker-recovery.js";import{canvasRoutes as br}from"./handlers/canvas.js";import{conversationRoutes as Tr}from"./handlers/conversations.js";import{chatInventoryRoutes as Cr}from"./handlers/chat-inventory.js";import{daemonRoutes as kr}from"./handlers/daemon.js";import{fileRoutes as Ur}from"./handlers/files.js";import{focusRoutes as Or}from"./handlers/focus.js";import{analyticsRoutes as Pr}from"./handlers/analytics.js";import{memoryReadsRoutes as Nr}from"./handlers/memory-reads.js";import{memoryRoutes as Ir}from"./handlers/memory.js";import{healthRoutes as zr}from"./handlers/health.js";import{humanRequestRoutes as Hr}from"./handlers/human-requests.js";import{inboxRoutes as Lr}from"./handlers/inbox.js";import{feedbackCommentRoutes as Br}from"./handlers/feedback-comments.js";import{objectRoutes as xr}from"./handlers/objects.js";import{shareRoutes as Dr}from"./handlers/shares.js";import{customObjectRoutes as Fr}from"./handlers/custom-objects.js";import{docRoutes as Mr}from"./handlers/docs.js";import{deliveryRoutes as Ae}from"./handlers/delivery.js";import{deliveryRetryRoutes as $r}from"./handlers/delivery-retry.js";import{packageDocRoutes as Jr}from"./handlers/package-docs.js";import{documentAccessRoutes as Wr}from"./handlers/document-access.js";import{pluginAppRoutes as jr}from"./handlers/plugin-app-token.js";import{brokerMailRoutes as ye,messageRoutes as Vr}from"./handlers/messages.js";import{modelAuthRoutes as Gr}from"./handlers/modelauth.js";import{llmRoutes as Yr}from"./handlers/llm.js";import{providerRoutes as Kr}from"./handlers/providers.js";import{modelConfigRoutes as Xr}from"./handlers/model-config.js";import{settingsRoutes as Zr}from"./handlers/settings.js";import{nodeRoutes as Qr}from"./handlers/nodes.js";import{nodeRecordRoutes as qr}from"./handlers/node-records.js";import{nodeOutcomeRoutes as et}from"./handlers/node-outcomes.js";import{nodeEventRoutes as rt}from"./handlers/node-events.js";import{profileRoutes as tt}from"./handlers/profiles.js";import{environmentRoutes as nt}from"./handlers/environments.js";import{prospectiveChatInventoryRoutes as ot}from"./handlers/prospective-chat-inventory.js";import{reportRoutes as it}from"./handlers/reports.js";import{runRoutes as st}from"./handlers/run-routes.js";import{reviewCommentRoutes as at}from"./handlers/review-comments.js";import{reviewRoutes as lt}from"./handlers/reviews.js";import{subscriptionRoutes as ct}from"./handlers/subscriptions.js";import{structuredRequestRoutes as ut}from"./handlers/structured-requests.js";import{cronRoutes as pt}from"./handlers/crons.js";import{setCronRequestHandler as ve}from"../cron/run-socket.js";import{RUN_TOKEN_PREFIX as dt,cronPrincipalForRunToken as ft}from"../cron/run-token.js";import{worktreeRoutes as mt}from"./handlers/worktree.js";import{limitsRoutes as gt}from"./handlers/limits.js";import{chargeRoutes as ht,spendLimitRoutes as Rt}from"./handlers/charges.js";import{executionStartRoutes as At}from"./handlers/execution-start.js";import{machineCredentialRoutes as yt}from"./handlers/machine-credential.js";import{importRoutes as vt}from"./handlers/imports.js";import{gitCredentialRoutes as _t}from"./handlers/git-credential.js";function wt(e){return new fe().registerAll(zr(e)).registerAll(kr).registerAll(Dr).registerAll(Qr).registerAll(qr).registerAll(et).registerAll($r).registerAll(rt).registerAll(Ar).registerAll(yr).registerAll(vr).registerAll(_r).registerAll(he).registerAll(wr).registerAll(Ae).registerAll(Re).registerAll(Sr).registerAll(mt).registerAll(gt).registerAll(ht).registerAll(At).registerAll(yt).registerAll(vt).registerAll(_t).registerAll(Rt).registerAll(ye).registerAll(Vr).registerAll(it).registerAll(st).registerAll(ut).registerAll(hr).registerAll(br).registerAll(Tr).registerAll(Pr).registerAll(Nr).registerAll(Ir).registerAll(Ur).registerAll(xr).registerAll(Fr).registerAll(Mr).registerAll(Jr).registerAll(Wr).registerAll(jr).registerAll(Or).registerAll(ct).registerAll(pt).registerAll(tt).registerAll(nt).registerAll(Gr).registerAll(Yr).registerAll(Kr).registerAll(Xr).registerAll(Zr).registerAll(lt).registerAll(at).registerAll(Lr).registerAll(Hr).registerAll(Cr).registerAll(ot).registerAll(Br).registerAll(Rr)}o(wt,"buildRouter");function Et(e,r){if(e.toUpperCase()!=="GET")return null;const i=r.split("/").filter(u=>u.length>0);if(i.length!==4||i[0]!=="v1"||i[1]!=="nodes"||i[3]!=="attach")return null;const a=i[2];return a===void 0||a===""?null:decodeURIComponent(a)}o(Et,"attachNodeId");function St(e){const r=e.trim();if(r==="")return null;const i=r.lastIndexOf(":");if(i<0)return null;const a=r.slice(0,i),u=r.slice(i+1),d=Number(u);return!Number.isInteger(d)||d<0||d>65535?null:{host:a===""?"0.0.0.0":a,port:d}}o(St,"parseTcp");function bt(e,r){return`${e.includes(":")?`[${e}]`:e}:${r}`}o(bt,"formatTcpAddress");const P={code:"unauthorized",message:"missing or invalid bearer token"},L={code:"owner_only",message:"attach is owner-only; a scoped token does not reach it"},F={code:"person_bearer_not_supported",message:"this listener accepts a person bearer only on a cloud role with CRTR_DIRECTORY_URL and CRTR_PUBLIC_API_URL set; call with a node, app or public token"},q={class:"anonymous",app:"",node:"",run:null,uid:-1,sub:"",grant:null,client_id:null,scopes:[]},B=new WeakMap;function M(e){return B.get(e)}o(M,"socketPrincipal");async function _e(e,r){const i=process.platform==="linux"?nr(e.socket):null,a=e.headers.authorization;if(a===void 0)return i===null||r.has(i)?{class:"person"}:"unauthorized";if(typeof a!="string"||!a.startsWith("Bearer "))return"unauthorized";if(a.slice(7).startsWith("crtr_pub_"))return q;if(a.slice(7).startsWith(ee)){const u=be(a.slice(7));return u!==void 0&&(i===null||r.has(i))?u.principal:"unauthorized"}return we(a.slice(7),i)}o(_e,"resolveSocketPrincipal");async function we(e,r){const i=await $e(e);if(!i||r!==null&&r!==i.uid)return"unauthorized";const a=tr();if(a&&!H()&&!await rr(a))return"runtime_starting";const u=i.grant??(await er("app:terminal",i.sub))?.id??null;return{class:"broker",...i,grant:u}}o(we,"brokerPrincipal");function Ee(e){if(!(e.class==="anonymous"||e.class==="import"))return e.sub!==void 0&&e.sub!==""?e.sub:void 0}o(Ee,"requestPerson");function Se(e,r){r.class==="broker"&&A({event:"api.request.principal",level:r.app==="app:terminal"?"debug":"info",node_id:r.node,fields:{principal:`${r.app} node:${r.node}`,method:e.method,path:e.url}})}o(Se,"noteBrokerRequest");const ee="crtr_app_";function be(e){const r=e.startsWith(ee)?or(e):void 0;return r===void 0?void 0:{principal:{class:"app",app:r.grantee,scopes:r.scopes},ceiling:r.scopes}}o(be,"appBearer");function Tt(e){const r=new Map;for(const i of sr("user"))r.set(i.token,{principal:{class:"app",app:i.grantee,scopes:i.scopes},ceiling:i.scopes});return e!==void 0&&r.set(e,{principal:{class:"person"},ceiling:null}),r}o(Tt,"resolveBearers");function Ct(e){try{return Ge(e).act!==void 0}catch{return!1}}o(Ct,"carriesAct");const kt=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*$/;function k(e,r){return e!==void 0&&(e.reason=r),"unauthorized"}o(k,"deny");async function Te(e,r,i){const a=e.headers.authorization;if(a===void 0&&(e.method??"GET").toUpperCase()==="GET"&&(e.url??"").split("?")[0]==="/healthz")return{principal:q,ceiling:null};if(typeof a!="string"||!a.startsWith("Bearer "))return k(i,a===void 0?"no_authorization_header":"not_a_bearer");const u=a.slice(7);if(u.startsWith("crtr_pub_"))return{principal:q,ceiling:null};if(u.startsWith(ee))return be(u)??k(i,"app_token_unknown");if(u.startsWith(dt)){const w=await ft(u);return w===null?k(i,"run_token_invalid_or_settled"):{principal:w,ceiling:null}}const d=r.get(u);if(d!==void 0)return d;const R=Le(u);if(R!==null)return{principal:R,ceiling:null};if(u.startsWith(He))return k(i,"import_token_invalid");if(kt.test(u)){if(H()&&Ct(u)){const x=j();if(x===null)return"person_bearer";try{const _=await x.verifyCall(a);return _.chain[0]?.sub.startsWith("app:")?{call:_}:k(i,"call_token_presenter_not_an_app")}catch(_){return _ instanceof S&&_.status===503?"runtime_starting":k(i,`call_token_${_ instanceof S?_.code:"invalid"}`)}}const w=H()?pe():null;if(w===null)return"person_bearer";const U=await w.verify(u);return U===null?k(i,"person_bearer_not_verified"):{principal:{class:"person",sub:U},ceiling:null}}const m=await we(u,null);return m==="unauthorized"?k(i,"node_token_unknown"):typeof m=="string"?m:{principal:m,ceiling:null}}o(Te,"authorizeTcp");let W;function j(){if(W!==void 0)return W;const e=process.env.CRTR_DIRECTORY_URL||void 0,r=process.env.CRTR_PUBLIC_API_URL||void 0;return W=e===void 0||r===void 0?null:new je(e,r,async()=>{}),W}o(j,"cloudCallResolver");let Ce;function Ut(){const e=j();if(e===null)throw new S(503,"runtime_starting","app calls are not configured on this listener");return Ce??=Ve(e,async()=>!0,async()=>{}),Ce}o(Ut,"cloudAppCalls");async function Ot(e,r){N(r),I(r);const i=j();try{if(i===null)throw new S(503,"runtime_starting","sign-in is not configured on this listener");await Ye(e,r,new URL(e.url??"/","http://runtime.local"),i)}catch(a){if(!(a instanceof S))throw a;if(r.headersSent){r.destroy();return}r.writeHead(a.status,{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}),r.end(JSON.stringify({error:{code:a.code,message:a.message,...a.param?{param:a.param}:{},origin:"runtime"}}))}}o(Ot,"serveRuntimeSignIn");function Pt(){const e=process.env.CRTRD_TLS_CERT||void 0,r=process.env.CRTRD_TLS_KEY||void 0;if(e===void 0&&r===void 0)return null;if(e===void 0||r===void 0)throw new Error("CRTRD_TLS_CERT and CRTRD_TLS_KEY must be set together");return{cert:se(e),key:se(r)}}o(Pt,"tcpTls");function N(e){e.setHeader(Y,X()),e.setHeader(K,ce)}o(N,"advertiseRuntime");function I(e){e.setHeader("Access-Control-Allow-Origin","*"),e.setHeader("Access-Control-Expose-Headers",`${Y}, ${K}`)}o(I,"exposeRuntimeHeaders");function Nt(e,r){return(e.method??"GET").toUpperCase()!=="OPTIONS"?!1:(N(r),r.writeHead(204,{"Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":`${Y}, ${K}`,"Access-Control-Allow-Headers":`authorization, content-type, ${le.toLowerCase()}, ${ue.toLowerCase()}`,"Access-Control-Allow-Methods":"GET, POST, PATCH, PUT, DELETE, OPTIONS","Access-Control-Max-Age":"600"}),r.end(),!0)}o(Nt,"answerPreflight");function V(e,r=!1){N(e),r&&I(e),e.writeHead(401,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{...P,origin:"runtime"}}))}o(V,"writeUnauthorized");function It(e){N(e),I(e),e.writeHead(401,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{...F,origin:"runtime"}}))}o(It,"writePersonBearerRefused");const zt={"/v1/runtime/vendor-status":{method:"GET",purpose:"vendor_status"},"/v1/runtime/vendor-account-remove":{method:"POST",purpose:"vendor_account_remove"}};async function Ht(e,r){if(!H())return!1;const i=new URL(e.url??"/","http://runtime.local").pathname,a=zt[i];if(a===void 0||e.method!==a.method)return!1;const u=o((d,R)=>{N(r),I(r),r.writeHead(d,{"content-type":"application/json; charset=utf-8"}),r.end(JSON.stringify(R))},"answer");try{const d=pe();if(d===null)throw new S(401,F.code,F.message);const R=e.headers.authorization,m=R?.startsWith("Bearer ")?await d.verifyPurpose(R.slice(7),a.purpose):null;if(m===null)throw new S(401,"unauthorized","invalid directory token");const w=a.purpose==="vendor_status"?void 0:await Lt(e);u(200,await J(m,async()=>a.purpose==="vendor_status"?Ze():await Xe(w)))}catch(d){const{status:R,body:m}=Qe(d);u(R,m)}return!0}o(Ht,"serveCloudVendorRoute");async function Lt(e){const r=[];let i=0;for await(const a of e){if(i+=a.length,i>qe)throw new S(400,"invalid_request","request body too large");r.push(a)}if(i!==0)try{return JSON.parse(Buffer.concat(r).toString("utf8"))}catch{throw new S(400,"invalid_request","invalid JSON body")}}o(Lt,"readVendorBody");function ke(e){N(e),e.writeHead(503,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{code:"runtime_starting",message:"grant sync is not ready",type:"server_error",origin:"runtime",retryable:!0}}))}o(ke,"writeRuntimeStarting");function Bt(e,r){e.writeHead(503,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{code:"startup_blocked",message:r,origin:"runtime"}}))}o(Bt,"writeStartupBlocked");function Ue(e,r,i){return new Promise(a=>{for(const m of r)m.destroy();if(i===void 0){try{e.closeAllConnections()}catch{}e.close(()=>a());return}const u=[];e.close(()=>{for(const m of u)clearTimeout(m);a()});const d=setInterval(()=>e.closeIdleConnections(),250),R=setTimeout(()=>e.closeAllConnections(),i);u.push(d,R),e.closeIdleConnections()})}o(Ue,"closeServer");function ko(e={}){let r=null;const i=wt(()=>r),a=new fe().registerAll(he).registerAll(Ae).registerAll(Re).registerAll(ye),u=o((t,s)=>{const c=gr()?.startupBlock()??null;return c===null||t==="GET"&&(s==="/healthz"||s==="/v1/status"||s==="/v1/ready")||t==="POST"&&(s==="/v1/daemon/migrate"||s==="/v1/daemon/admit")||c.phase==="recovering"&&a.match(t,s)!==null?null:c},"startupBlockFor"),d=e.socketPath??Me(),R=new Set([process.getuid?.()??0,...de("user").runtime?.person_uids??[]]),m=o((t,s,c)=>{N(s);const p=o(n=>Array.isArray(n)?n[0]:n,"first"),O=p(t.headers[le.toLowerCase()]),h=De(O,X())??Fe(p(t.headers[ue.toLowerCase()]),ce,{legacyMinimum:O,runtimeVersion:X()});if(h!==null){s.writeHead(h.status,{"content-type":"application/json; charset=utf-8"}),s.end(JSON.stringify({error:{code:h.code,message:h.message,type:"invalid_request_error",origin:"runtime",retryable:!1,..."param"in h?{param:h.param}:{details:h.details}}}));return}const E=o(n=>{const l=M(t);A({event:"api.request.failed",level:"error",...l?.class==="broker"?{node_id:l.node}:{},error:n instanceof Error?n:new Error(String(n))});try{s.headersSent||s.writeHead(500,{"content-type":"application/json; charset=utf-8"}),s.end(JSON.stringify({error:{code:"internal",message:"internal error",origin:"runtime"}}))}catch{}},"internalFailure");let T;try{T=new URL(t.url??"/","http://127.0.0.1")}catch{try{s.writeHead(400,{"content-type":"application/json; charset=utf-8"}),s.end(JSON.stringify({error:{code:"invalid_request",message:"request URL is invalid",origin:"runtime"}}))}catch{}return}try{const n=u((t.method??"GET").toUpperCase(),T.pathname);if(n!==null){Bt(s,n.message);return}const l=M(t)??{class:"person"},f=Ee(l),g=o(()=>i.handle(t,s,c,l),"handled");(f===void 0?g():J(f,o(async()=>{Z()||await Q(f),await g()},"handledAsPerson"))).catch(E)}catch(n){E(n)}},"onRequest"),w=o(async(t,s,c)=>{const p=M(t);return p===void 0||me(p)||await ge(p,"either",c)?!0:(y(s,404,"Not Found","node_not_found",`no node ${c}`),!1)},"authorizeAttachUpgrade"),U=new Set,x=o(t=>{U.add(t),t.once("close",()=>U.delete(t)),t.on("error",()=>{})},"trackUpgrade"),_=o((t,s,c)=>{try{const p=new URL(t.url??"/","http://127.0.0.1"),O=u((t.method??"GET").toUpperCase(),p.pathname);if(O!==null){y(s,503,"Service Unavailable","startup_blocked",O.message);return}const h=Et(t.method??"GET",p.pathname);if(h===null){s.destroy();return}const E=(()=>{const n=M(t);return n===void 0?void 0:Ee(n)})(),T=o(()=>w(t,s,h).then(n=>n?cr(t,s,c,h,async l=>{const f=M(t);return f===void 0||me(f)||await ge(f,l,h)}):void 0),"attach");(E===void 0?T():J(E,async()=>{Z()||await Q(E),await T()})).catch(()=>{try{s.destroy()}catch{}})}catch{try{s.destroy()}catch{}}},"onUpgrade"),Oe=o(t=>{t.on("error",s=>{A({event:"api.server.failed",level:"error",error:s})})},"bindErrorHandler"),Pe=o(async(t,s)=>{try{const c=await _e(t,R);if(c==="unauthorized"){A({event:"api.principal.denied",level:"warn",fields:{method:t.method}}),V(s);return}if(c==="runtime_starting"){ke(s);return}B.set(t,c),Se(t,c),m(t,s,c.class==="app"?c.scopes:null)}catch(c){A({event:"api.principal.failed",level:"error",error:c instanceof Error?c:new Error(String(c))}),V(s)}},"onSocketRequest"),D=ie((t,s)=>{Pe(t,s).catch(c=>A({event:"api.principal.failed",level:"error",error:c instanceof Error?c:new Error(String(c))}))}),Ne=o(async(t,s,c)=>{try{const p=await _e(t,R);if(p==="unauthorized"||p==="runtime_starting"){p==="unauthorized"&&A({event:"api.principal.denied",level:"warn",fields:{method:t.method}}),y(s,p==="unauthorized"?401:503,"Unauthorized",p,"socket principal unavailable");return}if(p.class!=="person"&&p.class!=="broker"){y(s,403,"Forbidden",L.code,L.message);return}B.set(t,p),_(t,s,c)}catch(p){A({event:"api.principal.failed",level:"error",error:p instanceof Error?p:new Error(String(p))}),y(s,401,"Unauthorized",P.code,P.message)}},"onSocketUpgrade");D.on("upgrade",(t,s,c)=>{x(s),Ne(t,s,c).catch(p=>A({event:"api.principal.failed",level:"error",error:p instanceof Error?p:new Error(String(p))}))}),ve((t,s,c)=>{B.set(t,c),m(t,s,null)});let re=!1,te,ne;const Ie=new Promise((t,s)=>{te=t,ne=s});D.once("listening",()=>{re=!0,te()}),D.on("error",t=>{A({event:"api.server.failed",level:"error",error:t}),re||ne(t)});try{G(d)&&ae(d)}catch{}D.listen(d,()=>{try{xe(d,process.platform==="linux"&&G("/run/crtr/launcher.sock")?438:384)}catch(t){A({event:"api.socket.chmod_failed",level:"error",error:t instanceof Error?t:new Error(String(t))})}});let b;const $=e.tcp??ar()??de("user").api.tcp;if($!==void 0&&$!==""){const t=St($);if(t===null)A({event:"api.tcp.invalid",level:"error",error:new Error(`invalid CRTRD_TCP/--tcp spec: ${$}`)});else{H()&&j();const s=e.token??lr()??ir("user"),c=Tt(s),p=o(async(n,l)=>{if(Je(n)){await We(n,l);return}if(Nt(n,l))return;if(H()&&Ke(new URL(n.url??"/","http://runtime.local").pathname)){await Ot(n,l);return}if(await Ht(n,l))return;const f={},g=await Te(n,c,f);if(g==="runtime_starting"){I(l),ke(l);return}if(g==="person_bearer"){It(l);return}if(g==="unauthorized"){A({event:"api.principal.denied",level:"warn",fields:{method:n.method,listener:"tcp",path:new URL(n.url??"/","http://runtime.local").pathname,reason:f.reason??"unknown"}}),V(l,!0);return}if("call"in g){I(l);const z=g.call.sub;await J(z,async()=>{Z()||await Q(z),await Ut()(n,l,g.call)});return}B.set(n,g.principal),Se(n,g.principal),I(l),m(n,l,g.ceiling)},"tcpOnRequest"),O=o(async(n,l,f)=>{const g=pr(n);if(g!==null){const v=await ur(n,l,f,g);v!==null&&y(l,v.status,v.text,v.code,v.message);return}const z=mr(n);if(z!==null){const v=fr(n,l,f,z);v!==null&&y(l,v.status,v.text,v.code,v.message);return}const C=await Te(n,c);if(C==="runtime_starting"){y(l,503,"Service Unavailable","runtime_starting","grant sync is not ready");return}if(C==="person_bearer"){y(l,401,"Unauthorized",F.code,F.message);return}if(C==="unauthorized"){y(l,401,"Unauthorized",P.code,P.message);return}if("call"in C){y(l,403,"Forbidden",L.code,L.message);return}if(C.ceiling!==null||C.principal.class==="anonymous"||C.principal.class==="import"){y(l,403,"Forbidden",L.code,L.message);return}B.set(n,C.principal),_(n,l,f)},"tcpOnUpgrade"),h=o(n=>{A({event:"api.principal.failed",level:"error",error:n instanceof Error?n:new Error(String(n))})},"failed"),E=o((n,l)=>{p(n,l).catch(f=>{h(f),l.headersSent?l.destroy():V(l,!0)})},"listener"),T=Pt();b=T===null?ie(E):Be(T,E),b.on("upgrade",(n,l,f)=>{x(l),O(n,l,f).catch(g=>{h(g),y(l,401,"Unauthorized",P.code,P.message)})}),Oe(b),b.once("listening",()=>{const n=b?.address();if(n!==null&&typeof n=="object"){const{address:l,port:f}=n;r=bt(l,f),l!=="0.0.0.0"&&l!=="::"&&dr(r)}}),b.listen(t.port,t.host)}}let oe=!1;return{ready:Ie,tcpAddress:o(()=>r,"tcpAddress"),close:o(async(t={})=>{if(!oe){oe=!0,ve(null),Er.close(),await Promise.all([Ue(D,U,t.graceMs),b!==void 0?Ue(b,U,t.graceMs):Promise.resolve()]);try{G(d)&&ae(d)}catch{}}},"close")}}o(ko,"createApiServer");export{wt as buildRouter,Ue as closeServer,ko as createApiServer,M as socketPrincipal};
@@ -1,19 +1,19 @@
1
- var lr=Object.defineProperty;var s=(e,c)=>lr(e,"name",{value:c,configurable:!0});import{applyBootSettings as dr}from"./boot-settings.js";import{startPeerOutbox as mr}from"./peer/outbox.js";import{reportMachineStatus as pr}from"../core/peer/directory.js";import{createPeerRelay as fr}from"./peer/relay-service.js";import{writeFileSync as ur,readFileSync as hr,rmSync as wr,mkdirSync as Ee,existsSync as R,unlinkSync as Ie,chmodSync as xe}from"node:fs";import{createServer as Q}from"node:http";import{dirname as vr}from"node:path";import{envCrtrdTcp as De,envDocumentPort as gr}from"../shared/env.js";import{openCanvasConversationStore as yr,serveCanvasConversationStore as Sr}from"../core/canvas/sessions.js";import{installConversationStore as _r}from"../core/conversation-store/index.js";import{pollRunObservers as br}from"./runs/observer.js";import{randomBytes as Te}from"node:crypto";import{apiSocketPath as Ce,crtrHome as kr}from"../core/canvas/paths.js";import{activeAppUsers as Rr}from"../core/spaces/users.js";import{ensureAppSpace as Pr,ensureUserFiles as Er}from"../core/spaces/space.js";import{LAUNCHER_SOCKET as D}from"../launcher/spec.js";import{launcherRequest as A}from"../launcher/client.js";import{installLauncherEventSink as Ir}from"./launcher-events.js";import{initializeEmptyLayout as xr,layoutNeedsMigration as Dr,socketDir as Le}from"../core/layout.js";import{migrateLooseKeys as Tr}from"../core/layout-migrate/loose-keys.js";import{relocateProfileFolders as Cr}from"../core/profiles/relocate.js";import{getNode as Lr,getRow as $r,listNodesForSupervision as $e,listParkedResidentsWithWakeMail as Ar,setFrozen as Ae}from"../core/canvas/index.js";import{createApiServer as Nr,closeServer as Ne}from"./api/server.js";import{Router as Mr}from"./api/router.js";import{healthRoutes as Gr}from"./api/handlers/health.js";import{createDocumentListener as Or}from"./api/document-listener.js";import{documentSecret as Fr}from"./api/document-secret.js";import{createAppListener as Br}from"./api/app-listener.js";import{registerMachineEnvironment as Hr}from"../core/environments.js";import{registerBlaxelRunnerFromEnv as jr}from"../core/secrets/blaxel-register.js";import{markCloudRole as zr,resolvePerson as Ur,retireLocalPerson as qr,setPersonId as Wr}from"../core/canvas/person.js";import{backfillNodeApps as Me,runPermissionsBoot as Jr}from"../core/permissions/boot.js";import{startRunNotices as Kr}from"./run-notices.js";import{startGrantEffects as Vr}from"./reconcilers/grant-effects.js";import{syncPackages as Yr}from"../core/packages/directory-sync.js";import{startActivationDelivery as Qr}from"../core/model-auth/activations.js";import{createGrantSync as Xr,GRANT_SYNC_INTERVAL_S as Ge}from"../core/grants/sync.js";import{sweepSandboxes as Zr}from"../core/grants/on-sync.js";import{rebuildCronExecutions as et}from"./cron/run-socket.js";import{hasSyncedGrants as rt}from"../core/grants/mirror.js";import{readConfig as me}from"../core/config.js";import{reconcileUndeliveredTickets as tt}from"./human/sweep.js";import{resetHandedOffDeliveries as nt}from"../core/canvas/deliveries.js";import{resetHandedOffDaemonActions as ot}from"../core/canvas/daemon-actions.js";import{sweepReviews as it}from"./review/sweep.js";import{pidfilePath as pe}from"./pidfile.js";import{rendererWarning as at}from"../core/runtime/package-health.js";import{DEFAULT_INTERVAL_MS as st}from"./supervise-cadence.js";import{createResumeDetector as ct}from"./resume-detector.js";import{setFatalFaultAnnouncer as lt}from"../core/canvas/recovery.js";import{BrokerSupervisionReconciler as dt}from"./reconcilers/broker-supervision.js";import{ControllerDeathReconciler as mt}from"./reconcilers/controller-death.js";import{NodeLifecycleReconciler as pt}from"./reconcilers/node-lifecycle/tick.js";import{NodeDeadlineReconciler as ft}from"./reconcilers/node-deadline.js";import{CronLaneReconciler as ut}from"./reconcilers/cron-lane.js";import{DeliveryLaneReconciler as ht}from"./reconcilers/delivery-lane.js";import{ActionLaneReconciler as wt}from"./reconcilers/action-lane.js";import{endLiveExecution as vt,hasObservedExit as gt,latestExecutionForNode as yt,migrateLegacyExecutionIdentities as St}from"../core/canvas/executions.js";import{revokePriorEpochNodeTokens as _t}from"../core/canvas/node-tokens.js";import{PendingReviewSubmitReconciler as bt}from"./reconcilers/pending-review-submit.js";import{StorageMaintenanceReconciler as kt}from"./reconcilers/storage-maintenance.js";import{StorageDueWorkReconciler as Rt}from"./reconcilers/storage-due-work.js";import{PurgeDueWorkReconciler as Pt}from"./reconcilers/purge-due-work.js";import{assertLedgerEnv as Et}from"../core/ledger/rates.js";import{LedgerSandboxReconciler as It}from"./reconcilers/ledger-sandbox.js";import{LedgerStorageReconciler as xt}from"./reconcilers/ledger-storage.js";import{LedgerR2Reconciler as Dt}from"./reconcilers/ledger-r2.js";import{importedNodesHeld as fe}from"./reconcilers/live-obligation.js";import{ImportLaneReconciler as Tt}from"./reconcilers/import-lane.js";import{BashDeadlineReconciler as Ct}from"./reconcilers/bash-deadline.js";import{FaultRetryBackstopReconciler as Lt}from"./reconcilers/fault-retry-backstop.js";import{StructuredRequestReconciler as $t}from"./reconcilers/structured-request-lane.js";import{RecipeImageReconciler as At,subscribeImageBuilt as Nt}from"./reconcilers/recipe-image.js";import{reconcileStructuredRequestSidecars as Mt}from"./structured-requests/boot.js";import{captureLivenessSnapshot as Oe,capturePidCommand as Gt,captureTeardownSnapshot as Fe,isPidAlive as Ot,isAnyPidAlive as Be,killProcessTreePids as He}from"../core/canvas/pid.js";import{bindFleet as Ft,boundFleet as je}from"../core/runtime/fleet.js";import{bindDaemonControl as Bt,clearDaemonControl as Ht}from"./control.js";import{execDaemon as jt,spawnDaemon as zt}from"./manage.js";import{reconcileAndMigrateBoot as Ut}from"../core/canvas/boot.js";import{resolveInstallId as qt}from"../core/canvas/install-id.js";import{setInstallId as Wt}from"../core/runtime/nodes.js";import{claimDaemonOwnership as Jt,daemonOwnershipApplies as Kt,daemonOwnershipClaimed as Vt,releaseDaemonOwnership as ze}from"../core/canvas/daemon-owner.js";import{canvasDatabaseUrl as Yt,closeAllDbs as ue,openDb as Ue,withCanvasWrite as he}from"../core/canvas/db.js";import{importSqliteCanvasIfPresent as Qt}from"../core/canvas/import-sqlite.js";import{ensurePostgres as Xt,ensurePostgresHealthy as Zt,stopPostgres as en,withPostgresStartLock as rn}from"./postgres/index.js";import{brokerSignalBus as N}from"./broker-signals/bus.js";import{brokerSignalStreams as tn}from"./api/handlers/broker-signals.js";import{setRequestsStartRunObservers as nn}from"./api/handlers/broker-ops.js";import{reconcilePackages as on}from"../core/graph/package-reconcile.js";import{migrateAppInstalls as an}from"../core/scoped-state/migrate-app-installs.js";import{publish as sn,readBuiltinSnapshot as cn}from"../core/graph/package-publish.js";import{startRepoSync as ln}from"../core/graph/repo-sync/index.js";import{prewarmRecentRecipes as dn,reapStaleSpares as mn}from"../core/runtime/warm-pool.js";import{DaemonFleet as pn}from"./fleet.js";import{copyNodeFilesToRows as fn}from"../core/runtime/first-boot-rows.js";import{BOOT_MIGRATIONS as un}from"./boot-migrations.js";import{emitEvent as p}from"../core/events/emit.js";import{operationIdContext as _}from"../core/events/operation-id.js";import{bindDaemonEventSource as hn}from"../core/events/source.js";import{activateCanvasImport as wn,MigrationBlockedError as vn,runForcedCanvasImport as gn}from"../migrations/activation.js";import{adoptInstallPerson as yn,convertLegacyScopedStore as Sn,personStoresCopied as _n}from"../core/scoped-state/migrate.js";import{readLegacyUserSnapshot as bn}from"../core/scoped-state/legacy-profiles.js";import{heldPersons as qe,installPreludeSnapshot as kn}from"../core/scoped-state/person-store.js";import{loadPersonSettings as We}from"../core/scoped-state/person-rows.js";import{userScopeRoot as Je}from"../core/scope.js";import{brokerCommandDeclaresCanvasHome as we}from"../core/runtime/broker-ownership.js";import{brokerCommandDeclaresCanvasHome as ta}from"../core/runtime/broker-ownership.js";function ve(e){return/ --epoch (\S+) /.exec(e)?.[1]??null}s(ve,"brokerCommandEpoch");const Rn=5e3,Ke=150;async function Pn(e){const c=Oe();if(c===null)throw p({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness"}}),new Error("prior-epoch broker census could not capture the process table");const f=kr(),d=[];for(const[r,l]of c.processes){const S=l.command;if(l.zombie||!S.includes("broker-cli.js")||!we(S,f)||ve(S)===e)continue;const P=S.trim().split(/\s+/).at(-1)??"";P===""||P.endsWith("broker-cli.js")||d.push({pid:r,nodeId:P})}let v=0;const i=[];for(const r of d){const l=Gt(r.pid);if(l===null||!l.includes("broker-cli.js")||!we(l,f)||ve(l)===e||l.trim().split(/\s+/).at(-1)!==r.nodeId)continue;const S=Fe(r.pid,null);if(!S.reused){try{process.platform==="linux"&&R(D)?await A({operation:"stop",pid:r.pid}):process.kill(r.pid,"SIGTERM")}catch{continue}v++,i.push({pid:r.pid,snap:S})}}const h=Date.now()+Rn;for(;Date.now()<h&&i.some(r=>Be(r.snap.tree.length>0?r.snap.tree:[r.pid]));)await new Promise(r=>setTimeout(r,Ke));let g=0;for(const r of i){const l=r.snap.tree.length>0?r.snap.tree:[r.pid];Be(l)&&(process.platform==="linux"&&R(D)?await A({operation:"stop",pid:r.pid}):He(l,"SIGKILL",r.snap.identities),g++)}g>0&&await new Promise(r=>setTimeout(r,Ke));const m=Oe();if(m===null)throw p({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness",stage:"final"}}),new Error("prior-epoch broker census could not capture the final process table");const u=[];for(const[r,l]of m.processes){const S=l.command;l.zombie||!S.includes("broker-cli.js")||we(S,f)&&ve(S)!==e&&u.push(r)}if(u.length>0)throw new Error(`prior-epoch broker census could not prove termination of pid(s): ${u.join(", ")}`);p({level:"info",event:"daemon.census.completed",fields:{prior_epoch_brokers:d.length,sigtermed:v,sigkilled:g}})}s(Pn,"reapPriorEpochBrokers");const En=5e3;async function In(e){const c=Array.from(e.entries());if(c.length===0)return;for(const[i]of c){const h=(await Lr(i))?.status;(h==="active"||h==="idle")&&await Ae(i,new Date().toISOString())}const f=c.map(([,i])=>({pid:i.pid,snap:Fe(i.pid,null),exited:i.handle.exited}));for(const i of f)if(!i.snap.reused)try{process.platform==="linux"&&R(D)?await A({operation:"stop",pid:i.pid}):process.kill(i.pid,"SIGTERM")}catch{}const d=new Promise(i=>{setTimeout(i,En).unref()});await Promise.allSettled(f.map(i=>Promise.race([i.exited.then(()=>{}),d])));const v=[];for(const i of f)Ot(i.pid)&&(process.platform==="linux"&&R(D)?await A({operation:"stop",pid:i.pid}):He(i.snap.tree.length>0?i.snap.tree:[i.pid],"SIGKILL",i.snap.identities),v.push(i));await Promise.all(v.map(i=>i.exited));for(const[i]of c)await vt(i,{reason:"daemon-teardown"});p({level:"info",event:"daemon.fleet_teardown.completed",fields:{brokers:f.length,sigkilled:v.length}})}s(In,"teardownFleet");function Ve(){Ee(vr(pe()),{recursive:!0}),ur(pe(),String(process.pid),"utf8")}s(Ve,"writePidfile");function Ye(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}s(Ye,"isMissingPathError");function Qe(e){const c=pe();let f;try{f=hr(c,"utf8")}catch(d){if(Ye(d))return;throw d}if(f.trim()!==String(e))throw new Error(`daemon readiness mirror does not name this invocation (expected pid ${e})`);try{wr(c)}catch(d){if(Ye(d))return;throw d}}s(Qe,"removeOwnedPidfileMirror");const xn={acceptsDetachedWork:s(()=>!0,"acceptsDetachedWork"),registerDetached:s(e=>{e.catch(()=>{})},"registerDetached")},X=new dt;lt(e=>X.handleFatalFault(e,!1));const Dn=new mt,Xe=new pt,Tn=new ft,Cn=new ut,Ln=new ht,$n=new wt,An=new bt,Nn=new kt,Mn=new Rt,Gn=new Pt,On=new It,Fn=new xt,Bn=new Dt,Hn=new Tt,jn=new Ct,zn=new Lt,Un=new $t,qn=new At;async function Wn(e=Date.now(),c=xn){const f=je(),d=await X.runFleetPreamble(f);let v,i,h;try{i=await fe();const m=(await $e()).filter(r=>!i.has(r.node_id));v=m.filter(r=>r.status==="active"||r.status==="idle"),h=m.filter(r=>r.status==="done"||r.status==="canceled"||r.status==="dead");const u=new Set(h.map(r=>r.node_id));h.push(...(await Ar()).filter(r=>!u.has(r.node_id)&&!i.has(r.node_id)))}catch(m){p({level:"error",event:"canvas.node_list.failed",error:m});return}await X.run(e,{rows:v,fleet:f,lifecycle:c,held:i}),await Dn.run(e,{rows:v,held:i});const g=await Xe.run(e,{rows:[...v,...h],fleet:f});await Tn.run(e,i),await Un.run(e,i),await qn.run(e,{lifecycle:c}),await Cn.run(e,{lifecycle:c,held:i}),await Ln.run(e,{lifecycle:c}),await $n.run(e,{lifecycle:c}),await An.run(e,{lifecycle:c}),await Nn.run(e,{lifecycle:c,fleet:f,held:i}),Mn.run(e,{lifecycle:c}),Gn.run(e,{lifecycle:c}),On.run(e,{lifecycle:c}),Fn.run(e,{lifecycle:c}),Bn.run(e,{lifecycle:c}),Hn.run(e,{lifecycle:c}),await br(),zn.run(e,{fleet:f,lifecycle:c}),await jn.run(e,{rows:v}),X.warnIfSaturated({fleet:f,lifecycle:c,thresholds:d,frozen:g})}s(Wn,"superviseTick");async function Jn(e,c=Date.now()){if((await fe()).has(e))return;const f=await yt(e);if(f===null||!gt(f))return;const d=await $r(e);d===null||d.kind==="human"||await Xe.runNode(c,d,je())}s(Jn,"exitedNodePass");function j(e){return e===void 0||e==="reconcile"}s(j,"roleRunsLanes");function M(e){return e===void 0||e==="api"}s(M,"roleServesRequests");const Kn=66e4;function Vn(e){const c=new Mr().registerAll(Gr(()=>null).filter(r=>r.pattern==="/healthz")),f=s((r,l)=>{const S=(r.url??"/").split("?")[0];if((r.method??"GET").toUpperCase()==="GET"&&S==="/healthz"){c.handle(r,l,null,{class:"person"});return}l.writeHead(404,{"content-type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:{code:"not_found",message:"this process serves only /healthz",origin:"runtime"}}))},"handler"),d=Ce();R(d)&&Ie(d);const v=Q(f),i=new Promise((r,l)=>{v.once("error",l),v.listen(d,()=>{v.off("error",l),xe(d,384),r()})});let h,g=null;const m=e.tcp??De()??me("user").api.tcp;if(m!==void 0&&m!==""){const r=/^(.*):(\d+)$/.exec(m.trim());if(r===null||Number(r[2])>65535)throw new Error(`invalid reconcile probe TCP address: ${m}`);const l=Q(f);l.on("error",S=>p({event:"api.server.failed",level:"error",error:S})),l.listen(Number(r[2]),r[1]===""?"0.0.0.0":r[1],()=>{g=`${r[1]===""?"0.0.0.0":r[1]}:${r[2]}`}),h=l}let u=!1;return{ready:i,tcpAddress:s(()=>g,"tcpAddress"),async close(r={}){if(!u){u=!0,await Promise.all([Ne(v,new Set,r.graceMs),h===void 0?Promise.resolve():Ne(h,new Set,r.graceMs)]);try{R(d)&&Ie(d)}catch{}}}}}s(Vn,"createProbeServer");const Yn="daemon is draining for shutdown and admits no new work";async function Qn(e){Ee(Le(),{recursive:!0,mode:493}),process.platform==="linux"&&xe(Le(),493);const c=Ce();if(R(c))throw new Error(`layout refusal cannot bind occupied socket: ${c}`);const f=Q((m,u)=>{if(m.method==="GET"&&m.url==="/healthz"){u.writeHead(200,{"content-type":"application/json; charset=utf-8"}),u.end(JSON.stringify({ok:!1,daemon_up:!0,store_accessible:!1,brokers_reconciled:!1,startup_phase:"blocked",startup_blocked:"layout_migration_required"}));return}u.writeHead(503,{"content-type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:{code:"layout_migration_required",message:"run crtr sys migrate while the runtime is offline",type:"server_error",origin:"runtime",retryable:!1}}))});await new Promise((m,u)=>{f.once("error",u),f.listen(c,()=>{f.off("error",u),m()})});let d;const v=e.tcp??De();if(v){const m=/^(.*):(\d+)$/.exec(v);if(!m||Number(m[2])>65535)throw new Error(`invalid refusal TCP address: ${v}`);const u=Q(f.listeners("request")[0]);await new Promise((r,l)=>{u.once("error",l),u.listen(Number(m[2]),m[1],()=>{u.off("error",l),r()})}),d=u}Ve();let i;const h=s(()=>(i??=(async()=>{f.closeAllConnections(),d?.closeAllConnections(),await Promise.all([f,d].filter(m=>m!==void 0).map(m=>new Promise((u,r)=>m.close(l=>l?r(l):u())))),Qe(process.pid),process.off("SIGINT",g),process.off("SIGTERM",g)})(),i),"cleanup"),g=s(()=>{h().then(()=>process.exit(0),m=>{process.stderr.write(`[crtrd] layout refusal cleanup failed: ${String(m)}
2
- `),process.exit(1)})},"onSignal");return process.on("SIGINT",g),process.on("SIGTERM",g),h}s(Qn,"serveLayoutRefusal");async function Xn(e={}){if(e.role==="machine")return(await import("./machine-daemon.js")).runMachineDaemon();if(Dr())return Qn(e);xr();const c=s(n=>{process.stderr.write(`[crtrd] ${n}
3
- `)},"logPostgres"),f=!!process.env.CRTR_TEST_PG_URL,d=Kt(e.role);nn(j(e.role));const v=s(async()=>d?await Jt(Te(16).toString("hex")):{claimed:!0,claim:{pid:process.pid,pid_identity:"",token:Te(16).toString("hex")}},"claimOwnership"),{database:i,ownership:h}=f?{database:{url:await Yt()},ownership:await v()}:await rn(async()=>({database:await Xt({log:c,startLockHeld:!0}),ownership:await v()}));if(!h.claimed){if(h.reason==="incumbent_alive")process.stderr.write(`[crtrd] already running (pid ${h.incumbentPid??"?"})
1
+ var lr=Object.defineProperty;var s=(e,c)=>lr(e,"name",{value:c,configurable:!0});import{applyBootSettings as dr}from"./boot-settings.js";import{startPeerOutbox as mr}from"./peer/outbox.js";import{reportMachineStatus as pr}from"../core/peer/directory.js";import{createPeerRelay as fr}from"./peer/relay-service.js";import{writeFileSync as ur,readFileSync as hr,rmSync as wr,mkdirSync as Ee,existsSync as R,unlinkSync as Ie,chmodSync as xe}from"node:fs";import{createServer as Q}from"node:http";import{dirname as vr}from"node:path";import{envCrtrdTcp as De,envDocumentPort as gr}from"../shared/env.js";import{openCanvasConversationStore as Sr,serveCanvasConversationStore as yr}from"../core/canvas/sessions.js";import{installConversationStore as _r}from"../core/conversation-store/index.js";import{pollRunObservers as br}from"./runs/observer.js";import{randomBytes as Te}from"node:crypto";import{apiSocketPath as Ce,crtrHome as kr}from"../core/canvas/paths.js";import{activeAppUsers as Rr}from"../core/spaces/users.js";import{ensureAppSpace as Pr,ensureUserFiles as Er}from"../core/spaces/space.js";import{LAUNCHER_SOCKET as D}from"../launcher/spec.js";import{launcherRequest as A}from"../launcher/client.js";import{installLauncherEventSink as Ir}from"./launcher-events.js";import{initializeEmptyLayout as xr,layoutNeedsMigration as Dr,socketDir as Le}from"../core/layout.js";import{migrateLooseKeys as Tr}from"../core/layout-migrate/loose-keys.js";import{relocateProfileFolders as Cr}from"../core/profiles/relocate.js";import{getNode as Lr,getRow as $r,listNodesForSupervision as $e,listParkedResidentsWithWakeMail as Ar,setFrozen as Ae}from"../core/canvas/index.js";import{createApiServer as Nr,closeServer as Ne}from"./api/server.js";import{Router as Mr}from"./api/router.js";import{healthRoutes as Gr}from"./api/handlers/health.js";import{createDocumentListener as Or}from"./api/document-listener.js";import{documentSecret as Fr}from"./api/document-secret.js";import{createAppListener as Br}from"./api/app-listener.js";import{registerMachineEnvironment as Hr}from"../core/environments.js";import{registerBlaxelRunnerFromEnv as jr}from"../core/secrets/blaxel-register.js";import{markCloudRole as zr,resolvePerson as Ur,retireLocalPerson as qr,setPersonId as Wr}from"../core/canvas/person.js";import{backfillNodeApps as Me,runPermissionsBoot as Jr}from"../core/permissions/boot.js";import{startRunNotices as Kr}from"./run-notices.js";import{startGrantEffects as Vr}from"./reconcilers/grant-effects.js";import{syncPackages as Yr}from"../core/packages/directory-sync.js";import{startActivationDelivery as Qr}from"../core/model-auth/activations.js";import{createGrantSync as Xr,GRANT_SYNC_INTERVAL_S as Ge}from"../core/grants/sync.js";import{sweepSandboxes as Zr}from"../core/grants/on-sync.js";import{rebuildCronExecutions as et}from"./cron/run-socket.js";import{hasSyncedGrants as rt}from"../core/grants/mirror.js";import{readConfig as me}from"../core/config.js";import{reconcileUndeliveredTickets as tt}from"./human/sweep.js";import{resetHandedOffDeliveries as nt}from"../core/canvas/deliveries.js";import{resetHandedOffDaemonActions as ot}from"../core/canvas/daemon-actions.js";import{sweepReviews as it}from"./review/sweep.js";import{pidfilePath as pe}from"./pidfile.js";import{rendererWarning as at}from"../core/runtime/package-health.js";import{DEFAULT_INTERVAL_MS as st}from"./supervise-cadence.js";import{createResumeDetector as ct}from"./resume-detector.js";import{setFatalFaultAnnouncer as lt}from"../core/canvas/recovery.js";import{BrokerSupervisionReconciler as dt}from"./reconcilers/broker-supervision.js";import{ControllerDeathReconciler as mt}from"./reconcilers/controller-death.js";import{NodeLifecycleReconciler as pt}from"./reconcilers/node-lifecycle/tick.js";import{NodeDeadlineReconciler as ft}from"./reconcilers/node-deadline.js";import{CronLaneReconciler as ut}from"./reconcilers/cron-lane.js";import{DeliveryLaneReconciler as ht}from"./reconcilers/delivery-lane.js";import{ActionLaneReconciler as wt}from"./reconcilers/action-lane.js";import{endLiveExecution as vt,hasObservedExit as gt,latestExecutionForNode as St,migrateLegacyExecutionIdentities as yt}from"../core/canvas/executions.js";import{revokePriorEpochNodeTokens as _t}from"../core/canvas/node-tokens.js";import{PendingReviewSubmitReconciler as bt}from"./reconcilers/pending-review-submit.js";import{StorageMaintenanceReconciler as kt}from"./reconcilers/storage-maintenance.js";import{StorageDueWorkReconciler as Rt}from"./reconcilers/storage-due-work.js";import{PurgeDueWorkReconciler as Pt}from"./reconcilers/purge-due-work.js";import{assertLedgerEnv as Et}from"../core/ledger/rates.js";import{IdleSandboxReconciler as It}from"./reconcilers/idle-sandbox.js";import{LedgerSandboxReconciler as xt}from"./reconcilers/ledger-sandbox.js";import{LedgerStorageReconciler as Dt}from"./reconcilers/ledger-storage.js";import{LedgerR2Reconciler as Tt}from"./reconcilers/ledger-r2.js";import{importedNodesHeld as fe}from"./reconcilers/live-obligation.js";import{ImportLaneReconciler as Ct}from"./reconcilers/import-lane.js";import{BashDeadlineReconciler as Lt}from"./reconcilers/bash-deadline.js";import{FaultRetryBackstopReconciler as $t}from"./reconcilers/fault-retry-backstop.js";import{StructuredRequestReconciler as At}from"./reconcilers/structured-request-lane.js";import{RecipeImageReconciler as Nt,subscribeImageBuilt as Mt}from"./reconcilers/recipe-image.js";import{reconcileStructuredRequestSidecars as Gt}from"./structured-requests/boot.js";import{captureLivenessSnapshot as Oe,capturePidCommand as Ot,captureTeardownSnapshot as Fe,isPidAlive as Ft,isAnyPidAlive as Be,killProcessTreePids as He}from"../core/canvas/pid.js";import{bindFleet as Bt,boundFleet as je}from"../core/runtime/fleet.js";import{bindDaemonControl as Ht,clearDaemonControl as jt}from"./control.js";import{execDaemon as zt,spawnDaemon as Ut}from"./manage.js";import{reconcileAndMigrateBoot as qt}from"../core/canvas/boot.js";import{resolveInstallId as Wt}from"../core/canvas/install-id.js";import{setInstallId as Jt}from"../core/runtime/nodes.js";import{claimDaemonOwnership as Kt,daemonOwnershipApplies as Vt,daemonOwnershipClaimed as Yt,releaseDaemonOwnership as ze}from"../core/canvas/daemon-owner.js";import{canvasDatabaseUrl as Qt,closeAllDbs as ue,openDb as Ue,withCanvasWrite as he}from"../core/canvas/db.js";import{importSqliteCanvasIfPresent as Xt}from"../core/canvas/import-sqlite.js";import{ensurePostgres as Zt,ensurePostgresHealthy as en,stopPostgres as rn,withPostgresStartLock as tn}from"./postgres/index.js";import{brokerSignalBus as N}from"./broker-signals/bus.js";import{brokerSignalStreams as nn}from"./api/handlers/broker-signals.js";import{setRequestsStartRunObservers as on}from"./api/handlers/broker-ops.js";import{reconcilePackages as an}from"../core/graph/package-reconcile.js";import{migrateAppInstalls as sn}from"../core/scoped-state/migrate-app-installs.js";import{publish as cn,readBuiltinSnapshot as ln}from"../core/graph/package-publish.js";import{startRepoSync as dn}from"../core/graph/repo-sync/index.js";import{prewarmRecentRecipes as mn,reapStaleSpares as pn}from"../core/runtime/warm-pool.js";import{DaemonFleet as fn}from"./fleet.js";import{copyNodeFilesToRows as un}from"../core/runtime/first-boot-rows.js";import{BOOT_MIGRATIONS as hn}from"./boot-migrations.js";import{emitEvent as p}from"../core/events/emit.js";import{operationIdContext as _}from"../core/events/operation-id.js";import{bindDaemonEventSource as wn}from"../core/events/source.js";import{activateCanvasImport as vn,MigrationBlockedError as gn,runForcedCanvasImport as Sn}from"../migrations/activation.js";import{adoptInstallPerson as yn,convertLegacyScopedStore as _n,personStoresCopied as bn}from"../core/scoped-state/migrate.js";import{readLegacyUserSnapshot as kn}from"../core/scoped-state/legacy-profiles.js";import{heldPersons as qe,installPreludeSnapshot as Rn}from"../core/scoped-state/person-store.js";import{loadPersonSettings as We}from"../core/scoped-state/person-rows.js";import{userScopeRoot as Je}from"../core/scope.js";import{brokerCommandDeclaresCanvasHome as we}from"../core/runtime/broker-ownership.js";import{brokerCommandDeclaresCanvasHome as ia}from"../core/runtime/broker-ownership.js";function ve(e){return/ --epoch (\S+) /.exec(e)?.[1]??null}s(ve,"brokerCommandEpoch");const Pn=5e3,Ke=150;async function En(e){const c=Oe();if(c===null)throw p({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness"}}),new Error("prior-epoch broker census could not capture the process table");const f=kr(),d=[];for(const[r,l]of c.processes){const y=l.command;if(l.zombie||!y.includes("broker-cli.js")||!we(y,f)||ve(y)===e)continue;const P=y.trim().split(/\s+/).at(-1)??"";P===""||P.endsWith("broker-cli.js")||d.push({pid:r,nodeId:P})}let v=0;const i=[];for(const r of d){const l=Ot(r.pid);if(l===null||!l.includes("broker-cli.js")||!we(l,f)||ve(l)===e||l.trim().split(/\s+/).at(-1)!==r.nodeId)continue;const y=Fe(r.pid,null);if(!y.reused){try{process.platform==="linux"&&R(D)?await A({operation:"stop",pid:r.pid}):process.kill(r.pid,"SIGTERM")}catch{continue}v++,i.push({pid:r.pid,snap:y})}}const h=Date.now()+Pn;for(;Date.now()<h&&i.some(r=>Be(r.snap.tree.length>0?r.snap.tree:[r.pid]));)await new Promise(r=>setTimeout(r,Ke));let g=0;for(const r of i){const l=r.snap.tree.length>0?r.snap.tree:[r.pid];Be(l)&&(process.platform==="linux"&&R(D)?await A({operation:"stop",pid:r.pid}):He(l,"SIGKILL",r.snap.identities),g++)}g>0&&await new Promise(r=>setTimeout(r,Ke));const m=Oe();if(m===null)throw p({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness",stage:"final"}}),new Error("prior-epoch broker census could not capture the final process table");const u=[];for(const[r,l]of m.processes){const y=l.command;l.zombie||!y.includes("broker-cli.js")||we(y,f)&&ve(y)!==e&&u.push(r)}if(u.length>0)throw new Error(`prior-epoch broker census could not prove termination of pid(s): ${u.join(", ")}`);p({level:"info",event:"daemon.census.completed",fields:{prior_epoch_brokers:d.length,sigtermed:v,sigkilled:g}})}s(En,"reapPriorEpochBrokers");const In=5e3;async function xn(e){const c=Array.from(e.entries());if(c.length===0)return;for(const[i]of c){const h=(await Lr(i))?.status;(h==="active"||h==="idle")&&await Ae(i,new Date().toISOString())}const f=c.map(([,i])=>({pid:i.pid,snap:Fe(i.pid,null),exited:i.handle.exited}));for(const i of f)if(!i.snap.reused)try{process.platform==="linux"&&R(D)?await A({operation:"stop",pid:i.pid}):process.kill(i.pid,"SIGTERM")}catch{}const d=new Promise(i=>{setTimeout(i,In).unref()});await Promise.allSettled(f.map(i=>Promise.race([i.exited.then(()=>{}),d])));const v=[];for(const i of f)Ft(i.pid)&&(process.platform==="linux"&&R(D)?await A({operation:"stop",pid:i.pid}):He(i.snap.tree.length>0?i.snap.tree:[i.pid],"SIGKILL",i.snap.identities),v.push(i));await Promise.all(v.map(i=>i.exited));for(const[i]of c)await vt(i,{reason:"daemon-teardown"});p({level:"info",event:"daemon.fleet_teardown.completed",fields:{brokers:f.length,sigkilled:v.length}})}s(xn,"teardownFleet");function Ve(){Ee(vr(pe()),{recursive:!0}),ur(pe(),String(process.pid),"utf8")}s(Ve,"writePidfile");function Ye(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}s(Ye,"isMissingPathError");function Qe(e){const c=pe();let f;try{f=hr(c,"utf8")}catch(d){if(Ye(d))return;throw d}if(f.trim()!==String(e))throw new Error(`daemon readiness mirror does not name this invocation (expected pid ${e})`);try{wr(c)}catch(d){if(Ye(d))return;throw d}}s(Qe,"removeOwnedPidfileMirror");const Dn={acceptsDetachedWork:s(()=>!0,"acceptsDetachedWork"),registerDetached:s(e=>{e.catch(()=>{})},"registerDetached")},X=new dt;lt(e=>X.handleFatalFault(e,!1));const Tn=new mt,Xe=new pt,Cn=new ft,Ln=new ut,$n=new ht,An=new wt,Nn=new bt,Mn=new kt,Gn=new Rt,On=new Pt,Fn=new xt,Bn=new It,Hn=new Dt,jn=new Tt,zn=new Ct,Un=new Lt,qn=new $t,Wn=new At,Jn=new Nt;async function Kn(e=Date.now(),c=Dn){const f=je(),d=await X.runFleetPreamble(f);let v,i,h;try{i=await fe();const m=(await $e()).filter(r=>!i.has(r.node_id));v=m.filter(r=>r.status==="active"||r.status==="idle"),h=m.filter(r=>r.status==="done"||r.status==="canceled"||r.status==="dead");const u=new Set(h.map(r=>r.node_id));h.push(...(await Ar()).filter(r=>!u.has(r.node_id)&&!i.has(r.node_id)))}catch(m){p({level:"error",event:"canvas.node_list.failed",error:m});return}await X.run(e,{rows:v,fleet:f,lifecycle:c,held:i}),await Tn.run(e,{rows:v,held:i});const g=await Xe.run(e,{rows:[...v,...h],fleet:f});await Cn.run(e,i),await Wn.run(e,i),await Jn.run(e,{lifecycle:c}),await Ln.run(e,{lifecycle:c,held:i}),await $n.run(e,{lifecycle:c}),await An.run(e,{lifecycle:c}),await Nn.run(e,{lifecycle:c}),await Mn.run(e,{lifecycle:c,fleet:f,held:i}),Gn.run(e,{lifecycle:c}),On.run(e,{lifecycle:c}),Fn.run(e,{lifecycle:c}),Bn.run(e,{lifecycle:c}),Hn.run(e,{lifecycle:c}),jn.run(e,{lifecycle:c}),zn.run(e,{lifecycle:c}),await br(),qn.run(e,{fleet:f,lifecycle:c}),await Un.run(e,{rows:v}),X.warnIfSaturated({fleet:f,lifecycle:c,thresholds:d,frozen:g})}s(Kn,"superviseTick");async function Vn(e,c=Date.now()){if((await fe()).has(e))return;const f=await St(e);if(f===null||!gt(f))return;const d=await $r(e);d===null||d.kind==="human"||await Xe.runNode(c,d,je())}s(Vn,"exitedNodePass");function j(e){return e===void 0||e==="reconcile"}s(j,"roleRunsLanes");function M(e){return e===void 0||e==="api"}s(M,"roleServesRequests");const Yn=66e4;function Qn(e){const c=new Mr().registerAll(Gr(()=>null).filter(r=>r.pattern==="/healthz")),f=s((r,l)=>{const y=(r.url??"/").split("?")[0];if((r.method??"GET").toUpperCase()==="GET"&&y==="/healthz"){c.handle(r,l,null,{class:"person"});return}l.writeHead(404,{"content-type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:{code:"not_found",message:"this process serves only /healthz",origin:"runtime"}}))},"handler"),d=Ce();R(d)&&Ie(d);const v=Q(f),i=new Promise((r,l)=>{v.once("error",l),v.listen(d,()=>{v.off("error",l),xe(d,384),r()})});let h,g=null;const m=e.tcp??De()??me("user").api.tcp;if(m!==void 0&&m!==""){const r=/^(.*):(\d+)$/.exec(m.trim());if(r===null||Number(r[2])>65535)throw new Error(`invalid reconcile probe TCP address: ${m}`);const l=Q(f);l.on("error",y=>p({event:"api.server.failed",level:"error",error:y})),l.listen(Number(r[2]),r[1]===""?"0.0.0.0":r[1],()=>{g=`${r[1]===""?"0.0.0.0":r[1]}:${r[2]}`}),h=l}let u=!1;return{ready:i,tcpAddress:s(()=>g,"tcpAddress"),async close(r={}){if(!u){u=!0,await Promise.all([Ne(v,new Set,r.graceMs),h===void 0?Promise.resolve():Ne(h,new Set,r.graceMs)]);try{R(d)&&Ie(d)}catch{}}}}}s(Qn,"createProbeServer");const Xn="daemon is draining for shutdown and admits no new work";async function Zn(e){Ee(Le(),{recursive:!0,mode:493}),process.platform==="linux"&&xe(Le(),493);const c=Ce();if(R(c))throw new Error(`layout refusal cannot bind occupied socket: ${c}`);const f=Q((m,u)=>{if(m.method==="GET"&&m.url==="/healthz"){u.writeHead(200,{"content-type":"application/json; charset=utf-8"}),u.end(JSON.stringify({ok:!1,daemon_up:!0,store_accessible:!1,brokers_reconciled:!1,startup_phase:"blocked",startup_blocked:"layout_migration_required"}));return}u.writeHead(503,{"content-type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:{code:"layout_migration_required",message:"run crtr sys migrate while the runtime is offline",type:"server_error",origin:"runtime",retryable:!1}}))});await new Promise((m,u)=>{f.once("error",u),f.listen(c,()=>{f.off("error",u),m()})});let d;const v=e.tcp??De();if(v){const m=/^(.*):(\d+)$/.exec(v);if(!m||Number(m[2])>65535)throw new Error(`invalid refusal TCP address: ${v}`);const u=Q(f.listeners("request")[0]);await new Promise((r,l)=>{u.once("error",l),u.listen(Number(m[2]),m[1],()=>{u.off("error",l),r()})}),d=u}Ve();let i;const h=s(()=>(i??=(async()=>{f.closeAllConnections(),d?.closeAllConnections(),await Promise.all([f,d].filter(m=>m!==void 0).map(m=>new Promise((u,r)=>m.close(l=>l?r(l):u())))),Qe(process.pid),process.off("SIGINT",g),process.off("SIGTERM",g)})(),i),"cleanup"),g=s(()=>{h().then(()=>process.exit(0),m=>{process.stderr.write(`[crtrd] layout refusal cleanup failed: ${String(m)}
2
+ `),process.exit(1)})},"onSignal");return process.on("SIGINT",g),process.on("SIGTERM",g),h}s(Zn,"serveLayoutRefusal");async function eo(e={}){if(e.role==="machine")return(await import("./machine-daemon.js")).runMachineDaemon();if(Dr())return Zn(e);xr();const c=s(n=>{process.stderr.write(`[crtrd] ${n}
3
+ `)},"logPostgres"),f=!!process.env.CRTR_TEST_PG_URL,d=Vt(e.role);on(j(e.role));const v=s(async()=>d?await Kt(Te(16).toString("hex")):{claimed:!0,claim:{pid:process.pid,pid_identity:"",token:Te(16).toString("hex")}},"claimOwnership"),{database:i,ownership:h}=f?{database:{url:await Qt()},ownership:await v()}:await tn(async()=>({database:await Zt({log:c,startLockHeld:!0}),ownership:await v()}));if(!h.claimed){if(h.reason==="incumbent_alive")process.stderr.write(`[crtrd] already running (pid ${h.incumbentPid??"?"})
4
4
  `);else{const n=[h.incumbentPid!==void 0?`pid ${h.incumbentPid}`:void 0,h.verdict!==void 0?`verdict ${h.verdict}`:void 0].filter(w=>w!==void 0),a=n.length>0?` (${n.join(", ")})`:"";process.stderr.write(`[crtrd] claim lost: ${h.reason}${a}
5
- `),h.reason==="own_identity_indeterminate"&&process.stderr.write("[crtrd] cannot read its own process identity. crouter needs /proc on Linux, or the `ps` command elsewhere (Debian/Ubuntu: apt-get install procps).\n"),(h.reason==="own_identity_indeterminate"||h.reason==="incumbent_malformed")&&(process.exitCode=1)}return async()=>{}}const g=h.claim;let m=null,u=null,r=null,l=null,S,P="";try{d&&await Pn(g.token);for(const t of Cr())process.stderr.write(`[crtrd] ${t}
5
+ `),h.reason==="own_identity_indeterminate"&&process.stderr.write("[crtrd] cannot read its own process identity. crouter needs /proc on Linux, or the `ps` command elsewhere (Debian/Ubuntu: apt-get install procps).\n"),(h.reason==="own_identity_indeterminate"||h.reason==="incumbent_malformed")&&(process.exitCode=1)}return async()=>{}}const g=h.claim;let m=null,u=null,r=null,l=null,y,P="";try{d&&await En(g.token);for(const t of Cr())process.stderr.write(`[crtrd] ${t}
6
6
  `);for(const t of await Tr())process.stderr.write(`[crtrd] ${t}
7
- `);await Ue(),await Qt(i.url,c);const n=e.role===void 0&&!await _n();let a=null;n&&(Sn({kind:"user",root:Je()}),a=bn(Je())),e.role===void 0&&kn(a??{profiles:[],defaults:{},settings:{},state:{},apps:{}}),await N.listen(i.url);const w=s(t=>{We(t).catch(o=>p({level:"error",event:"daemon.settings.reload_failed",error:o}))},"reloadPerson");if(S=await N.subscribe(t=>{qe().includes(t)&&w(t)},{kinds:["settings"],onListenStart:s(()=>{for(const t of qe())w(t)},"onListenStart")}),e.role!==void 0&&zr(),e.role!==void 0){let t;try{t=cn()}catch(b){p({level:"error",event:"daemon.packages.snapshot_failed",error:b})}const o=await he(async b=>(await Me(b),t===void 0?void 0:await sn(b,t,"release")));l=await he(async b=>await an(b));for(const b of o?.invalid??[])process.stderr.write(`[crtrd] package file is not a document: ${b.path}: ${b.error}
8
- `)}else{const t=await he(async o=>(await Me(o),await on(o)));for(const o of t.conflicts)process.stderr.write(`[crtrd] plugin documents not reconciled: ${o.message}
7
+ `);await Ue(),await Xt(i.url,c);const n=e.role===void 0&&!await bn();let a=null;n&&(_n({kind:"user",root:Je()}),a=kn(Je())),e.role===void 0&&Rn(a??{profiles:[],defaults:{},settings:{},state:{},apps:{}}),await N.listen(i.url);const w=s(t=>{We(t).catch(o=>p({level:"error",event:"daemon.settings.reload_failed",error:o}))},"reloadPerson");if(y=await N.subscribe(t=>{qe().includes(t)&&w(t)},{kinds:["settings"],onListenStart:s(()=>{for(const t of qe())w(t)},"onListenStart")}),e.role!==void 0&&zr(),e.role!==void 0){let t;try{t=ln()}catch(b){p({level:"error",event:"daemon.packages.snapshot_failed",error:b})}const o=await he(async b=>(await Me(b),t===void 0?void 0:await cn(b,t,"release")));l=await he(async b=>await sn(b));for(const b of o?.invalid??[])process.stderr.write(`[crtrd] package file is not a document: ${b.path}: ${b.error}
8
+ `)}else{const t=await he(async o=>(await Me(o),await an(o)));for(const o of t.conflicts)process.stderr.write(`[crtrd] plugin documents not reconciled: ${o.message}
9
9
  `);for(const o of t.invalid)process.stderr.write(`[crtrd] package file is not a document: ${o.path}: ${o.error}
10
10
  `);for(const o of t.quarantined)process.stderr.write(`[crtrd] plugin "${o.name}" has a damaged ${o.file} (${o.reason}); ${o.movedTo!==void 0?`moved to ${o.movedTo}`:"left in place and skipped"}
11
11
  `);for(const o of t.kinds.refused)process.stderr.write(`[crtrd] plugin "${o.plugin}" kind ${o.kind} not registered: ${o.message}
12
12
  `);for(const o of t.kinds.invalid)process.stderr.write(`[crtrd] plugin "${o.plugin}" declares invalid object kinds or scopes; no kinds registered and no app token: ${o.error}
13
- `)}if(P=await qt(),Wt(P),e.role===void 0&&(m=await Ur(),m!==null)){if(Wr(m.id),await yn(m.id),process.platform==="darwin"){const{readConfig:t,updateConfig:o}=await import("../core/config.js");if(t("user").paths?.user_files===void 0){const{homedir:b}=await import("node:os");await o("user",Pe=>{Pe.paths??={},Pe.paths.user_files??=b()})}}u=await qr(),u.joinedFrom!==null&&await We(u.person),await dr(),r=await Jr()}if(process.platform==="linux"&&R(D)&&(Ir(),await A({operation:"users.sync",users:await Rr()})),d){await _t(g.token);const t=await fn();Object.values(t).some(o=>o>0)&&process.stderr.write(`[crtrd] node files copied into rows: ${JSON.stringify(t)}
14
- `)}}catch(n){await N.close();try{if(d){const{released:a}=await ze(g);if(!a)throw new Error("daemon ownership claim was not released")}await ue()}catch(a){throw new AggregateError([n,a],"daemon startup failed and cleanup also failed")}throw n}let T=!0,Z,z=Promise.resolve(),ee=!1,U,re,te,ne,C;const q=new Set;let oe=!1,ge=!1,E,L,ie,W=!1,J,G,O,F,B,ae,se,ce,le;const Ze=ct();let I,y={phase:"initializing",message:"daemon startup is running the canvas import and normal services are unavailable",blockerPaths:[]},$="initial startup activation",er=null;function rr(){return y.phase==="ready"?null:{phase:y.phase,message:y.message,blockerPaths:y.blockerPaths}}s(rr,"startupBlock");function k(n){q.add(n),n.finally(()=>{q.delete(n)}).catch(()=>{})}s(k,"registerDetached");const ye={acceptsDetachedWork:s(()=>T,"acceptsDetachedWork"),registerDetached:k};j(e.role)&&await ln(ye,Ue);async function tr(){try{T=!1,tn.close(),re?.(),re=void 0,te?.(),S?.(),te=void 0,ne?.(),ne=void 0,ce?.(),ce=void 0,await N.close(),U!==void 0&&(clearInterval(U),U=void 0),O!==void 0&&(clearInterval(O),O=void 0),F!==void 0&&(clearInterval(F),F=void 0),le?.(),le=void 0;let n;do n=z,await n;while(n!==z);for(;q.size>0;)await Promise.allSettled([...q]);if(C!==void 0&&(d&&await In(C),await C.exitsSettled(),C.dispose()),ie!==void 0&&await ie.close(),L!==void 0&&!W&&(W=!0,await L.close()),ae?.(),ae=void 0,se?.(),se=void 0,B!==void 0){const a=B;B=void 0,await a.stop()}if(G!==void 0){const a=G;G=void 0,await a.close()}if(J!==void 0){const a=J;J=void 0,await a.close()}if(oe||(Qe(process.pid),oe=!0),oe&&!ge){if(d){const{released:a}=await ze(g);if(!a)throw new Error("daemon ownership claim was not released")}ge=!0,await ue()}}finally{Ht(),process.off("SIGINT",be),process.off("SIGTERM",ke),process.off("exit",Re)}}s(tr,"cleanupAttempt");const K=1e3;let Se=!1;function nr(){if(e.role!==void 0)throw new Error(`a ${e.role} daemon never hands over to a successor: its orchestrator replaces it`);return Se?{graceMs:K}:(Se=!0,_.fresh(()=>{p({level:"info",event:"daemon.handover.armed",fields:{pid:process.pid,grace_ms:K}})}),setTimeout(()=>{or()},K),{graceMs:K})}s(nr,"requestHandover");async function or(){try{await x()}catch(n){const a=n instanceof Error?n.stack??n.message:String(n);process.stderr.write(`[crtrd] handover cleanup failed:
13
+ `)}if(P=await Wt(),Jt(P),e.role===void 0&&(m=await Ur(),m!==null)){if(Wr(m.id),await yn(m.id),process.platform==="darwin"){const{readConfig:t,updateConfig:o}=await import("../core/config.js");if(t("user").paths?.user_files===void 0){const{homedir:b}=await import("node:os");await o("user",Pe=>{Pe.paths??={},Pe.paths.user_files??=b()})}}u=await qr(),u.joinedFrom!==null&&await We(u.person),await dr(),r=await Jr()}if(process.platform==="linux"&&R(D)&&(Ir(),await A({operation:"users.sync",users:await Rr()})),d){await _t(g.token);const t=await un();Object.values(t).some(o=>o>0)&&process.stderr.write(`[crtrd] node files copied into rows: ${JSON.stringify(t)}
14
+ `)}}catch(n){await N.close();try{if(d){const{released:a}=await ze(g);if(!a)throw new Error("daemon ownership claim was not released")}await ue()}catch(a){throw new AggregateError([n,a],"daemon startup failed and cleanup also failed")}throw n}let T=!0,Z,z=Promise.resolve(),ee=!1,U,re,te,ne,C;const q=new Set;let oe=!1,ge=!1,E,L,ie,W=!1,J,G,O,F,B,ae,se,ce,le;const Ze=ct();let I,S={phase:"initializing",message:"daemon startup is running the canvas import and normal services are unavailable",blockerPaths:[]},$="initial startup activation",er=null;function rr(){return S.phase==="ready"?null:{phase:S.phase,message:S.message,blockerPaths:S.blockerPaths}}s(rr,"startupBlock");function k(n){q.add(n),n.finally(()=>{q.delete(n)}).catch(()=>{})}s(k,"registerDetached");const Se={acceptsDetachedWork:s(()=>T,"acceptsDetachedWork"),registerDetached:k};j(e.role)&&await dn(Se,Ue);async function tr(){try{T=!1,nn.close(),re?.(),re=void 0,te?.(),y?.(),te=void 0,ne?.(),ne=void 0,ce?.(),ce=void 0,await N.close(),U!==void 0&&(clearInterval(U),U=void 0),O!==void 0&&(clearInterval(O),O=void 0),F!==void 0&&(clearInterval(F),F=void 0),le?.(),le=void 0;let n;do n=z,await n;while(n!==z);for(;q.size>0;)await Promise.allSettled([...q]);if(C!==void 0&&(d&&await xn(C),await C.exitsSettled(),C.dispose()),ie!==void 0&&await ie.close(),L!==void 0&&!W&&(W=!0,await L.close()),ae?.(),ae=void 0,se?.(),se=void 0,B!==void 0){const a=B;B=void 0,await a.stop()}if(G!==void 0){const a=G;G=void 0,await a.close()}if(J!==void 0){const a=J;J=void 0,await a.close()}if(oe||(Qe(process.pid),oe=!0),oe&&!ge){if(d){const{released:a}=await ze(g);if(!a)throw new Error("daemon ownership claim was not released")}ge=!0,await ue()}}finally{jt(),process.off("SIGINT",be),process.off("SIGTERM",ke),process.off("exit",Re)}}s(tr,"cleanupAttempt");const K=1e3;let ye=!1;function nr(){if(e.role!==void 0)throw new Error(`a ${e.role} daemon never hands over to a successor: its orchestrator replaces it`);return ye?{graceMs:K}:(ye=!0,_.fresh(()=>{p({level:"info",event:"daemon.handover.armed",fields:{pid:process.pid,grace_ms:K}})}),setTimeout(()=>{or()},K),{graceMs:K})}s(nr,"requestHandover");async function or(){try{await x()}catch(n){const a=n instanceof Error?n.stack??n.message:String(n);process.stderr.write(`[crtrd] handover cleanup failed:
15
15
  ${a}
16
- `),process.exit(1)}try{process.platform==="linux"&&R(D)&&(await A({operation:"daemon.handover"}),process.exit(0)),process.pid===1&&await jt();const n=await zt({waitForJoinLock:!0});_.fresh(()=>{p({level:"info",event:"daemon.handover.completed",fields:{predecessor_pid:process.pid,successor_pid:n.pid??n.existing_pid??null,spawned:n.started}})})}catch(n){_.fresh(()=>{p({level:"error",event:"daemon.handover.successor_failed",error:n})});const a=n instanceof Error?n.message:String(n);process.stderr.write(`[crtrd] handover successor failed to start: ${a}
17
- `),process.exit(1)}process.exit(0)}s(or,"performHandover");function x(){if(E!==void 0)return E;const n=tr();return E=n,n.then(()=>{E===n&&(E=void 0)},()=>{E===n&&(E=void 0)}),n}s(x,"requestCleanup");async function ir(){y={phase:"initializing",message:Yn,blockerPaths:[]},L!==void 0&&!W&&(W=!0,await L.close({graceMs:Kn}))}s(ir,"drainApi");async function _e(n){try{n==="SIGTERM"&&e.role==="api"&&await ir(),await x(),await en({claimed:s(async()=>{try{return d&&await Vt()}finally{await ue()}},"claimed")}),process.exit(0)}catch(a){process.exitCode=1;const w=a instanceof Error?a.stack??`${a.name}: ${a.message}`:String(a);process.stderr.write(`[crtrd] ${n} cleanup failed:
16
+ `),process.exit(1)}try{process.platform==="linux"&&R(D)&&(await A({operation:"daemon.handover"}),process.exit(0)),process.pid===1&&await zt();const n=await Ut({waitForJoinLock:!0});_.fresh(()=>{p({level:"info",event:"daemon.handover.completed",fields:{predecessor_pid:process.pid,successor_pid:n.pid??n.existing_pid??null,spawned:n.started}})})}catch(n){_.fresh(()=>{p({level:"error",event:"daemon.handover.successor_failed",error:n})});const a=n instanceof Error?n.message:String(n);process.stderr.write(`[crtrd] handover successor failed to start: ${a}
17
+ `),process.exit(1)}process.exit(0)}s(or,"performHandover");function x(){if(E!==void 0)return E;const n=tr();return E=n,n.then(()=>{E===n&&(E=void 0)},()=>{E===n&&(E=void 0)}),n}s(x,"requestCleanup");async function ir(){S={phase:"initializing",message:Xn,blockerPaths:[]},L!==void 0&&!W&&(W=!0,await L.close({graceMs:Yn}))}s(ir,"drainApi");async function _e(n){try{n==="SIGTERM"&&e.role==="api"&&await ir(),await x(),await rn({claimed:s(async()=>{try{return d&&await Yt()}finally{await ue()}},"claimed")}),process.exit(0)}catch(a){process.exitCode=1;const w=a instanceof Error?a.stack??`${a.name}: ${a.message}`:String(a);process.stderr.write(`[crtrd] ${n} cleanup failed:
18
18
  ${w}
19
- `),process.exit(1)}}s(_e,"handleSignal");function be(){_e("SIGINT")}s(be,"onSigint");function ke(){_e("SIGTERM")}s(ke,"onSigterm");function Re(){x().catch(()=>{})}s(Re,"onExit");async function V(n){T&&(z=z.then(n).then(()=>{},a=>{_.fresh(()=>{p({level:"error",event:"daemon.lane_job.failed",error:a})})}))}s(V,"enqueue");async function Y(){!T||ee||(Ze.check()&&I&&(p({level:"info",event:"daemon.resume.detected"}),k(I().catch(()=>{}))),ee=!0,await V(async()=>{if(ee=!1,!!T)try{f||await Zt({log:c}),await Wn(Date.now(),ye)}catch(n){_.fresh(()=>{p({level:"error",event:"daemon.tick.failed",error:n})})}}))}s(Y,"enqueueTick");let H=null;async function ar(){if(H!==null)throw{status:500,code:"admission_failed",message:`daemon admission previously failed: ${H instanceof Error?H.message:String(H)}`};if(y.phase==="ready")return{admitted:!1,already_admitted:!0,startup_phase:"ready"};if(y.phase!=="prepared"&&y.phase!=="recovering")throw{status:409,code:"not_prepared",message:y.message};const n=y.phase==="prepared";try{return await de(),y={phase:"ready",message:"",blockerPaths:[]},n?{admitted:!0,already_admitted:!1,startup_phase:"ready"}:{admitted:!1,already_admitted:!0,startup_phase:"ready"}}catch(a){throw H=a,{status:500,code:"admission_failed",message:`daemon admission failed: ${a instanceof Error?a.message:String(a)}`}}}s(ar,"admitStartup");async function sr(n){if($!==null)throw{status:409,code:"migration_in_progress",message:`the canvas import is already running (${$})`};$="repair";try{const a=await gn({dryRun:n.dryRun});if(n.dryRun||a.pending||y.phase!=="blocked")return{result:a,resumed:!1};if(e.prepare)return y={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]},{result:a,resumed:!1};try{return await de(),y={phase:"ready",message:"",blockerPaths:[]},{result:a,resumed:!0}}catch(w){const t=w instanceof Error?w.message:String(w);return setTimeout(()=>{x().catch(()=>{})},1e3),{result:a,resumed:!1,resumeError:t}}}finally{$=null}}s(sr,"repairMigrations");async function cr(){Z=e.intervalMs??st;const n=g.token;C=new pn({epoch:n,enqueue:V}),Ft(C),y={phase:"recovering",message:"daemon startup recovery is running and normal services are unavailable",blockerPaths:[]},_.fresh(()=>{p({level:"info",event:"daemon.started",fields:{pid:process.pid,interval_ms:Z}})});const a=P;_.fresh(()=>{p({level:"info",event:"daemon.install_id.resolved",fields:{install_id:a}})});const w=await Hr(a);if(_.fresh(()=>{p({level:"info",event:"daemon.environment.registered",fields:{environment_id:w.environmentId,created:w.created}})}),_.fresh(()=>{let t;try{t=at()}catch{return}t!==null&&p({level:"warn",event:"daemon.startup.warning",fields:{stage:"termrender",warning:t.slice(0,2048)}})}),Et(),e.role!==void 0&&!process.env.CRTR_DIRECTORY_URL)throw new Error("CRTR_DIRECTORY_URL must be set on a cloud role (--role api|reconcile): it names the directory this deployment mints tokens against");if(e.role!==void 0&&jr(),!j(e.role)){y={phase:"ready",message:"",blockerPaths:[]};return}if(await _.fresh(async()=>{await it(),await tt(),await nt(Date.now()),await ot(Date.now())}),e.role===void 0&&await _.fresh(async()=>{const{reconcile:t,migrated:o}=await Ut(St);t.changed&&p({level:"info",event:"daemon.boot_change.reconciled",fields:{cleared_count:t.cleared.length,same_boot_proven:t.sameBootProven}}),o.length>0&&p({level:"info",event:"daemon.pid_identity.migrated",fields:{migrated_count:o.length}})}),await _.fresh(async()=>{const t=await fe();for(const o of await $e())t.has(o.node_id)||o.status!=="active"||o.pi_pid!=null||o.frozen_at!=null||o.respawn_not_before!=null||(await Ae(o.node_id,new Date().toISOString()),p({level:"warn",event:"daemon.startup.launch_debt_recorded",node_id:o.node_id}))}),await _.fresh(async()=>{await Mt();for(const t of un){const o=await t.apply();o.changed&&p({level:"info",event:"daemon.boot_migration.applied",fields:{migration:t.id,...o.summary}})}}),k(et()),I){const t=s(()=>{k(I().catch(()=>{})),k(pr().then(o=>B?.observe(o)).then(()=>{},o=>{p({level:"warn",event:"daemon.peer.status_failed",error:o})}))},"refresh");k(Zr().then(({completion:o})=>o).catch(o=>{p({level:"error",event:"daemon.grants.sweep_failed",error:o})})),t(),O=setInterval(t,Ge*1e3),O.unref(),le=mr({joined:!0,register:k})}await V(async()=>{await mn(),await dn()}),U=setInterval(()=>{Y().catch(t=>p({level:"error",event:"daemon.tick.failed",error:t}))},Z),re=await Nt(()=>{Y().catch(t=>p({level:"error",event:"daemon.tick.failed",error:t}))}),te=await N.subscribe(()=>{Y().catch(t=>p({level:"error",event:"daemon.tick.failed",error:t}))},{kinds:["spend_limits"]}),ne=await N.subscribe(t=>{V(()=>_.fresh(()=>Jn(t)))},{kinds:["execution_exit"]}),await Y(),e.role===void 0&&import("../commands/sys/import/move.js").then(({settleMoveAtDaemonStart:t})=>t(()=>!T,o=>p({level:"warn",event:"daemon.move.settle_failed",error:o}))).catch(t=>p({level:"warn",event:"daemon.move.settle_failed",error:t}))}s(cr,"completeStartup");function de(){return er??=cr().catch(n=>{throw y={phase:"initializing",message:"daemon startup recovery failed and normal services are unavailable",blockerPaths:[]},n})}s(de,"resumeStartup");try{process.on("SIGINT",be),process.on("SIGTERM",ke),process.on("exit",Re),hn(),m!==null&&p({level:"info",event:"daemon.person.resolved",fields:{person_id:m.id,source:m.source}}),l!==null&&!l.alreadyDone&&p({level:"info",event:"daemon.packages.install_migration_done",fields:{moved:l.moved,discarded:l.discarded,people:l.people}}),r!==null&&p({level:"info",event:"daemon.permissions.boot",fields:{...r}}),u!==null&&p({level:"info",event:"daemon.person.retired",fields:{person_id:u.person,joined_from:u.joinedFrom,retired:u.retired,columns:u.columns}}),M(e.role)?J=await Sr():_r(yr());const n=g.token;Bt({epoch:n,requestHandover:nr,registerDetached:k,startupBlock:rr,admitStartup:ar,repairMigrations:sr}),Ve(),L=M(e.role)?Nr({tcp:e.tcp}):Vn(e),await L.ready;const a=gr()??me("user").document_port;if(M(e.role)){const t=Or(a,Fr());try{await t.ready,ie=t}catch(o){p({level:"warn",event:"daemon.document_listener.bind_failed",fields:{port:a,error:o instanceof Error?o.message:String(o)}})}}const w=me("user").runtime;if(w?.issuer&&(I=Xr(w.issuer,k),w.unsandboxed===!0&&(B=fr({syncGrants:I}))),e.role==="api"){const t=s(()=>k(Yr().catch(o=>{p({level:"error",event:"daemon.packages.sync_failed",error:o})})),"packageTick");t(),F=setInterval(t,Ge*1e3),F.unref()}if(M(e.role)&&(ae=await Kr()),j(e.role)&&(se=Qr()),ce=await Vr({serves:M(e.role),runsLanes:j(e.role)}),w?.unsandboxed===!0&&w.listener!==void 0&&p({level:"warn",event:"daemon.app_listener.refused_unsandboxed",fields:{reason:"runtime.unsandboxed is set; runtime.listener is ignored"}}),M(e.role)&&w!==void 0&&w.listener!==void 0&&w.unsandboxed!==!0&&(G=await Br(w,async()=>await rt(w.issuer.replace(/\/$/,"")),I),await G.ready),e.role===void 0)try{await wn()}catch(t){if($=null,t instanceof vn)return y={phase:"blocked",message:t.message,blockerPaths:t.blockerPaths},x;throw t}process.platform==="linux"&&R(D)&&(Er(),await Pr("app:terminal"));try{e.prepare?y={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]}:(await de(),y={phase:"ready",message:"",blockerPaths:[]})}finally{$=null}return x}catch(n){try{await x()}catch(a){throw new AggregateError([n,a],"daemon startup failed and cleanup also failed")}throw n}}s(Xn,"runDaemon");var Zi=Xn;export{Kn as API_DRAIN_GRACE_MS,ta as brokerCommandDeclaresCanvasHome,ve as brokerCommandEpoch,Zi as default,Jn as exitedNodePass,j as roleRunsLanes,M as roleServesRequests,Xn as runDaemon,Wn as superviseTick,In as teardownFleet};
19
+ `),process.exit(1)}}s(_e,"handleSignal");function be(){_e("SIGINT")}s(be,"onSigint");function ke(){_e("SIGTERM")}s(ke,"onSigterm");function Re(){x().catch(()=>{})}s(Re,"onExit");async function V(n){T&&(z=z.then(n).then(()=>{},a=>{_.fresh(()=>{p({level:"error",event:"daemon.lane_job.failed",error:a})})}))}s(V,"enqueue");async function Y(){!T||ee||(Ze.check()&&I&&(p({level:"info",event:"daemon.resume.detected"}),k(I().catch(()=>{}))),ee=!0,await V(async()=>{if(ee=!1,!!T)try{f||await en({log:c}),await Kn(Date.now(),Se)}catch(n){_.fresh(()=>{p({level:"error",event:"daemon.tick.failed",error:n})})}}))}s(Y,"enqueueTick");let H=null;async function ar(){if(H!==null)throw{status:500,code:"admission_failed",message:`daemon admission previously failed: ${H instanceof Error?H.message:String(H)}`};if(S.phase==="ready")return{admitted:!1,already_admitted:!0,startup_phase:"ready"};if(S.phase!=="prepared"&&S.phase!=="recovering")throw{status:409,code:"not_prepared",message:S.message};const n=S.phase==="prepared";try{return await de(),S={phase:"ready",message:"",blockerPaths:[]},n?{admitted:!0,already_admitted:!1,startup_phase:"ready"}:{admitted:!1,already_admitted:!0,startup_phase:"ready"}}catch(a){throw H=a,{status:500,code:"admission_failed",message:`daemon admission failed: ${a instanceof Error?a.message:String(a)}`}}}s(ar,"admitStartup");async function sr(n){if($!==null)throw{status:409,code:"migration_in_progress",message:`the canvas import is already running (${$})`};$="repair";try{const a=await Sn({dryRun:n.dryRun});if(n.dryRun||a.pending||S.phase!=="blocked")return{result:a,resumed:!1};if(e.prepare)return S={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]},{result:a,resumed:!1};try{return await de(),S={phase:"ready",message:"",blockerPaths:[]},{result:a,resumed:!0}}catch(w){const t=w instanceof Error?w.message:String(w);return setTimeout(()=>{x().catch(()=>{})},1e3),{result:a,resumed:!1,resumeError:t}}}finally{$=null}}s(sr,"repairMigrations");async function cr(){Z=e.intervalMs??st;const n=g.token;C=new fn({epoch:n,enqueue:V}),Bt(C),S={phase:"recovering",message:"daemon startup recovery is running and normal services are unavailable",blockerPaths:[]},_.fresh(()=>{p({level:"info",event:"daemon.started",fields:{pid:process.pid,interval_ms:Z}})});const a=P;_.fresh(()=>{p({level:"info",event:"daemon.install_id.resolved",fields:{install_id:a}})});const w=await Hr(a);if(_.fresh(()=>{p({level:"info",event:"daemon.environment.registered",fields:{environment_id:w.environmentId,created:w.created}})}),_.fresh(()=>{let t;try{t=at()}catch{return}t!==null&&p({level:"warn",event:"daemon.startup.warning",fields:{stage:"termrender",warning:t.slice(0,2048)}})}),Et(),e.role!==void 0&&!process.env.CRTR_DIRECTORY_URL)throw new Error("CRTR_DIRECTORY_URL must be set on a cloud role (--role api|reconcile): it names the directory this deployment mints tokens against");if(e.role!==void 0&&jr(),!j(e.role)){S={phase:"ready",message:"",blockerPaths:[]};return}if(await _.fresh(async()=>{await it(),await tt(),await nt(Date.now()),await ot(Date.now())}),e.role===void 0&&await _.fresh(async()=>{const{reconcile:t,migrated:o}=await qt(yt);t.changed&&p({level:"info",event:"daemon.boot_change.reconciled",fields:{cleared_count:t.cleared.length,same_boot_proven:t.sameBootProven}}),o.length>0&&p({level:"info",event:"daemon.pid_identity.migrated",fields:{migrated_count:o.length}})}),await _.fresh(async()=>{const t=await fe();for(const o of await $e())t.has(o.node_id)||o.status!=="active"||o.pi_pid!=null||o.frozen_at!=null||o.respawn_not_before!=null||(await Ae(o.node_id,new Date().toISOString()),p({level:"warn",event:"daemon.startup.launch_debt_recorded",node_id:o.node_id}))}),await _.fresh(async()=>{await Gt();for(const t of hn){const o=await t.apply();o.changed&&p({level:"info",event:"daemon.boot_migration.applied",fields:{migration:t.id,...o.summary}})}}),k(et()),I){const t=s(()=>{k(I().catch(()=>{})),k(pr().then(o=>B?.observe(o)).then(()=>{},o=>{p({level:"warn",event:"daemon.peer.status_failed",error:o})}))},"refresh");k(Zr().then(({completion:o})=>o).catch(o=>{p({level:"error",event:"daemon.grants.sweep_failed",error:o})})),t(),O=setInterval(t,Ge*1e3),O.unref(),le=mr({joined:!0,register:k})}await V(async()=>{await pn(),await mn()}),U=setInterval(()=>{Y().catch(t=>p({level:"error",event:"daemon.tick.failed",error:t}))},Z),re=await Mt(()=>{Y().catch(t=>p({level:"error",event:"daemon.tick.failed",error:t}))}),te=await N.subscribe(()=>{Y().catch(t=>p({level:"error",event:"daemon.tick.failed",error:t}))},{kinds:["spend_limits"]}),ne=await N.subscribe(t=>{V(()=>_.fresh(()=>Vn(t)))},{kinds:["execution_exit"]}),await Y(),e.role===void 0&&import("../commands/sys/import/move.js").then(({settleMoveAtDaemonStart:t})=>t(()=>!T,o=>p({level:"warn",event:"daemon.move.settle_failed",error:o}))).catch(t=>p({level:"warn",event:"daemon.move.settle_failed",error:t}))}s(cr,"completeStartup");function de(){return er??=cr().catch(n=>{throw S={phase:"initializing",message:"daemon startup recovery failed and normal services are unavailable",blockerPaths:[]},n})}s(de,"resumeStartup");try{process.on("SIGINT",be),process.on("SIGTERM",ke),process.on("exit",Re),wn(),m!==null&&p({level:"info",event:"daemon.person.resolved",fields:{person_id:m.id,source:m.source}}),l!==null&&!l.alreadyDone&&p({level:"info",event:"daemon.packages.install_migration_done",fields:{moved:l.moved,discarded:l.discarded,people:l.people}}),r!==null&&p({level:"info",event:"daemon.permissions.boot",fields:{...r}}),u!==null&&p({level:"info",event:"daemon.person.retired",fields:{person_id:u.person,joined_from:u.joinedFrom,retired:u.retired,columns:u.columns}}),M(e.role)?J=await yr():_r(Sr());const n=g.token;Ht({epoch:n,requestHandover:nr,registerDetached:k,startupBlock:rr,admitStartup:ar,repairMigrations:sr}),Ve(),L=M(e.role)?Nr({tcp:e.tcp}):Qn(e),await L.ready;const a=gr()??me("user").document_port;if(M(e.role)){const t=Or(a,Fr());try{await t.ready,ie=t}catch(o){p({level:"warn",event:"daemon.document_listener.bind_failed",fields:{port:a,error:o instanceof Error?o.message:String(o)}})}}const w=me("user").runtime;if(w?.issuer&&(I=Xr(w.issuer,k),w.unsandboxed===!0&&(B=fr({syncGrants:I}))),e.role==="api"){const t=s(()=>k(Yr().catch(o=>{p({level:"error",event:"daemon.packages.sync_failed",error:o})})),"packageTick");t(),F=setInterval(t,Ge*1e3),F.unref()}if(M(e.role)&&(ae=await Kr()),j(e.role)&&(se=Qr()),ce=await Vr({serves:M(e.role),runsLanes:j(e.role)}),w?.unsandboxed===!0&&w.listener!==void 0&&p({level:"warn",event:"daemon.app_listener.refused_unsandboxed",fields:{reason:"runtime.unsandboxed is set; runtime.listener is ignored"}}),M(e.role)&&w!==void 0&&w.listener!==void 0&&w.unsandboxed!==!0&&(G=await Br(w,async()=>await rt(w.issuer.replace(/\/$/,"")),I),await G.ready),e.role===void 0)try{await vn()}catch(t){if($=null,t instanceof gn)return S={phase:"blocked",message:t.message,blockerPaths:t.blockerPaths},x;throw t}process.platform==="linux"&&R(D)&&(Er(),await Pr("app:terminal"));try{e.prepare?S={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]}:(await de(),S={phase:"ready",message:"",blockerPaths:[]})}finally{$=null}return x}catch(n){try{await x()}catch(a){throw new AggregateError([n,a],"daemon startup failed and cleanup also failed")}throw n}}s(eo,"runDaemon");var ta=eo;export{Yn as API_DRAIN_GRACE_MS,ia as brokerCommandDeclaresCanvasHome,ve as brokerCommandEpoch,ta as default,Vn as exitedNodePass,j as roleRunsLanes,M as roleServesRequests,eo as runDaemon,Kn as superviseTick,xn as teardownFleet};
@@ -1,5 +1,5 @@
1
1
  /** Every lane `superviseTick` runs, named as in crtrd.ts. Keep in tick order. */
2
- export declare const TICK_LANES: readonly ["brokerSupervision", "controllerDeath", "nodeLifecycle", "nodeDeadline", "structuredRequests", "recipeImage", "cronLane", "deliveryLane", "actionLane", "pendingReviewSubmit", "storageMaintenance", "storageDueWork", "purgeDueWork", "pollRunObservers", "faultRetryBackstop", "bashDeadline", "ledgerSandbox", "ledgerStorage", "ledgerR2", "importLane"];
2
+ export declare const TICK_LANES: readonly ["brokerSupervision", "controllerDeath", "nodeLifecycle", "nodeDeadline", "structuredRequests", "recipeImage", "cronLane", "deliveryLane", "actionLane", "pendingReviewSubmit", "storageMaintenance", "storageDueWork", "purgeDueWork", "pollRunObservers", "faultRetryBackstop", "bashDeadline", "ledgerSandbox", "idleSandbox", "ledgerStorage", "ledgerR2", "importLane"];
3
3
  export interface DueSource {
4
4
  /** Epoch ms of the earliest timed work this lane owes; `now` when work is due already; null when none. */
5
5
  nextDue(now: number): Promise<number | null>;
@@ -1 +1 @@
1
- var d=Object.defineProperty;var r=(e,n)=>d(e,"name",{value:n,configurable:!0});const f=["brokerSupervision","controllerDeath","nodeLifecycle","nodeDeadline","structuredRequests","recipeImage","cronLane","deliveryLane","actionLane","pendingReviewSubmit","storageMaintenance","storageDueWork","purgeDueWork","pollRunObservers","faultRetryBackstop","bashDeadline","ledgerSandbox","ledgerStorage","ledgerR2","importLane"],u=new Map,a=new Map;function y(e,n){u.set(e,n)}r(y,"registerDueSource");function g(e,n){a.set(e,n)}r(g,"declareBusyOnly");function x(){return[...u.keys()]}r(x,"dueSourceLanes");function D(){return[...a.keys()]}r(D,"busyOnlyLanes");async function b(e,n=()=>{}){let o=null,s=!1;for(const[c,l]of u){let t;try{t=await l.nextDue(e)}catch(i){n(c,i),t=e}t===null||!Number.isFinite(t)||(t<=e&&(s=!0),(o===null||t<o)&&(o=t))}return{dueNow:s,nextDueMs:o}}r(b,"collectDue");export{f as TICK_LANES,D as busyOnlyLanes,b as collectDue,g as declareBusyOnly,x as dueSourceLanes,y as registerDueSource};
1
+ var d=Object.defineProperty;var r=(e,n)=>d(e,"name",{value:n,configurable:!0});const f=["brokerSupervision","controllerDeath","nodeLifecycle","nodeDeadline","structuredRequests","recipeImage","cronLane","deliveryLane","actionLane","pendingReviewSubmit","storageMaintenance","storageDueWork","purgeDueWork","pollRunObservers","faultRetryBackstop","bashDeadline","ledgerSandbox","idleSandbox","ledgerStorage","ledgerR2","importLane"],u=new Map,s=new Map;function y(e,n){u.set(e,n)}r(y,"registerDueSource");function x(e,n){s.set(e,n)}r(x,"declareBusyOnly");function g(){return[...u.keys()]}r(g,"dueSourceLanes");function b(){return[...s.keys()]}r(b,"busyOnlyLanes");async function D(e,n=()=>{}){let o=null,a=!1;for(const[l,c]of u){let t;try{t=await c.nextDue(e)}catch(i){n(l,i),t=e}t===null||!Number.isFinite(t)||(t<=e&&(a=!0),(o===null||t<o)&&(o=t))}return{dueNow:a,nextDueMs:o}}r(D,"collectDue");export{f as TICK_LANES,b as busyOnlyLanes,D as collectDue,x as declareBusyOnly,g as dueSourceLanes,y as registerDueSource};
@@ -1,12 +1,12 @@
1
- var D=Object.defineProperty;var a=(n,e)=>D(n,"name",{value:e,configurable:!0});import{openDb as E}from"../core/canvas/db.js";import{isPidPresent as R}from"../core/canvas/pid.js";import{isProfilePaused as p}from"../core/profiles/manifest.js";import{hasUnseenWakeMail as f}from"../core/canvas/deliveries.js";import{listPendingProviderRetries as g}from"../core/canvas/recovery.js";import{listSubmitRequestedRequests as x}from"../core/human/requests.js";import{storageConfig as I}from"../core/storage/client.js";import{emitEvent as O}from"../core/events/emit.js";import{wantsExecution as m}from"./reconcilers/node-lifecycle/wants-execution.js";import{dueAtMs as y}from"./reconcilers/fault-retry-backstop.js";import{UNUSED_UPLOAD_TTL_MS as T}from"./reconcilers/storage-due-work.js";import{IMAGE_BUILD_OWED_SQL as A,IMAGE_DELETE_OWED_SQL as M}from"./reconcilers/recipe-image.js";import{busyOnlyLanes as b,collectDue as h,declareBusyOnly as o,dueSourceLanes as v,registerDueSource as i}from"./due-sources.js";import{filterAsync as W}from"../core/async-array.js";const _=a(async(n,...e)=>await(await E()).prepare(n).all(...e),"rows"),r=a(async n=>await(await E()).prepare(n).get(),"first"),u=a(n=>{if(n==null)return null;const e=Date.parse(n);return Number.isFinite(e)?e:null},"iso"),c=a(n=>{let e=null;for(const t of n)t!==null&&(e===null||t<e)&&(e=t);return e},"earliest"),L="node_id NOT IN (SELECT node_id FROM warm_pool)";let N=!1;async function S(){if(N)return;N=!0,o("brokerSupervision","acts only on live broker processes, which already make busy true"),o("controllerDeath","acts only on live controller processes"),o("pollRunObservers","follows live pids only"),o("bashDeadline","acts only on running bash jobs, which already make busy true"),o("storageMaintenance","retention and placement housekeeping: never time-critical, and it must not wake or hold a sleeping runtime"),o("purgeDueWork","physical purge of objects soft-deleted over 30 days ago: housekeeping, and a tombstone a live object references stays due forever, so it must not wake or hold a sleeping runtime"),o("ledgerSandbox","bills awake time of executions that are busy or just exited; a sleeping runtime owes nothing until it wakes, and the lane must not wake it"),o("ledgerStorage","monthly storage billing: never time-critical, and it must not wake or hold a sleeping runtime"),o("ledgerR2","moves closed months to R2: housekeeping that must not wake or hold a sleeping runtime"),i("nodeLifecycle",{nextDue:a(async()=>c((await W(await _(`SELECT node_id, status, intent, profile_id, respawn_not_before FROM node_rows
1
+ var D=Object.defineProperty;var a=(n,e)=>D(n,"name",{value:e,configurable:!0});import{openDb as E}from"../core/canvas/db.js";import{isPidPresent as R}from"../core/canvas/pid.js";import{isProfilePaused as p}from"../core/profiles/manifest.js";import{hasUnseenWakeMail as f}from"../core/canvas/deliveries.js";import{listPendingProviderRetries as g}from"../core/canvas/recovery.js";import{listSubmitRequestedRequests as x}from"../core/human/requests.js";import{storageConfig as I}from"../core/storage/client.js";import{emitEvent as O}from"../core/events/emit.js";import{wantsExecution as m}from"./reconcilers/node-lifecycle/wants-execution.js";import{dueAtMs as y}from"./reconcilers/fault-retry-backstop.js";import{UNUSED_UPLOAD_TTL_MS as T}from"./reconcilers/storage-due-work.js";import{IMAGE_BUILD_OWED_SQL as h,IMAGE_DELETE_OWED_SQL as b}from"./reconcilers/recipe-image.js";import{busyOnlyLanes as A,collectDue as M,declareBusyOnly as r,dueSourceLanes as v,registerDueSource as i}from"./due-sources.js";import{filterAsync as k}from"../core/async-array.js";const _=a(async(n,...e)=>await(await E()).prepare(n).all(...e),"rows"),s=a(async n=>await(await E()).prepare(n).get(),"first"),u=a(n=>{if(n==null)return null;const e=Date.parse(n);return Number.isFinite(e)?e:null},"iso"),c=a(n=>{let e=null;for(const t of n)t!==null&&(e===null||t<e)&&(e=t);return e},"earliest"),L="node_id NOT IN (SELECT node_id FROM warm_pool)";let N=!1;async function S(){if(N)return;N=!0,r("brokerSupervision","acts only on live broker processes, which already make busy true"),r("controllerDeath","acts only on live controller processes"),r("pollRunObservers","follows live pids only"),r("bashDeadline","acts only on running bash jobs, which already make busy true"),r("storageMaintenance","retention and placement housekeeping: never time-critical, and it must not wake or hold a sleeping runtime"),r("purgeDueWork","physical purge of objects soft-deleted over 30 days ago: housekeeping, and a tombstone a live object references stays due forever, so it must not wake or hold a sleeping runtime"),r("ledgerSandbox","bills awake time of executions that are busy or just exited; a sleeping runtime owes nothing until it wakes, and the lane must not wake it"),r("idleSandbox","deletes dev-environment sandboxes idle for 7 days: housekeeping on a once-an-hour pass that must not wake or hold a sleeping runtime"),r("ledgerStorage","monthly storage billing: never time-critical, and it must not wake or hold a sleeping runtime"),r("ledgerR2","moves closed months to R2: housekeeping that must not wake or hold a sleeping runtime"),i("nodeLifecycle",{nextDue:a(async()=>c((await k(await _(`SELECT node_id, status, intent, profile_id, respawn_not_before FROM node_rows
2
2
  WHERE status IN ('active', 'idle') AND kind != 'human' AND ${L}
3
3
  AND pi_pid IS NULL AND respawn_not_before IS NOT NULL`),async e=>!p(e.profile_id)&&await m({node_id:e.node_id,status:e.status,intent:e.intent}))).map(e=>u(e.respawn_not_before))),"nextDue")}),i("nodeDeadline",{nextDue:a(async()=>c((await _(`SELECT deadline_at, profile_id FROM node_rows
4
- WHERE deadline_at IS NOT NULL AND outcome_at IS NULL AND status IN ('active', 'idle') AND kind != 'human'`)).filter(e=>!p(e.profile_id)).map(e=>u(e.deadline_at))),"nextDue")}),i("structuredRequests",{nextDue:a(async e=>await r("SELECT 1 FROM structured_requests WHERE state != 'pending' AND effects_done_at IS NULL LIMIT 1")!==void 0?e:(await r("SELECT MIN(deadline_at) AS at FROM structured_requests WHERE state = 'pending' AND deadline_at IS NOT NULL"))?.at??null,"nextDue")}),i("recipeImage",{nextDue:a(async e=>c((await _(`SELECT image_building_at FROM environments
5
- WHERE ${A} OR ${M}`)).map(t=>t.image_building_at===null?e:Math.max(e,u(t.image_building_at)??e))),"nextDue")}),i("cronLane",{nextDue:a(async()=>{const e=(await _(`SELECT fire_at, profile FROM crons
4
+ WHERE deadline_at IS NOT NULL AND outcome_at IS NULL AND status IN ('active', 'idle') AND kind != 'human'`)).filter(e=>!p(e.profile_id)).map(e=>u(e.deadline_at))),"nextDue")}),i("structuredRequests",{nextDue:a(async e=>await s("SELECT 1 FROM structured_requests WHERE state != 'pending' AND effects_done_at IS NULL LIMIT 1")!==void 0?e:(await s("SELECT MIN(deadline_at) AS at FROM structured_requests WHERE state = 'pending' AND deadline_at IS NOT NULL"))?.at??null,"nextDue")}),i("recipeImage",{nextDue:a(async e=>c((await _(`SELECT image_building_at FROM environments
5
+ WHERE ${h} OR ${b}`)).map(t=>t.image_building_at===null?e:Math.max(e,u(t.image_building_at)??e))),"nextDue")}),i("cronLane",{nextDue:a(async()=>{const e=(await _(`SELECT fire_at, profile FROM crons
6
6
  WHERE state = 'active' AND run_state = 'idle'
7
- AND NOT (held = 1 AND recur IS NULL AND expires_at IS NULL)`)).filter(s=>!p(s.profile)).map(s=>u(s.fire_at)),t=(await _("SELECT expires_at FROM crons WHERE expires_at IS NOT NULL AND run_state = 'idle'")).map(s=>u(s.expires_at));return c([...e,...t])},"nextDue")});const n=a(async e=>async()=>(await r(`SELECT MIN(next_attempt_at) AS at FROM ${e} WHERE state = 'pending' AND canceled_at IS NULL AND next_attempt_at IS NOT NULL`))?.at??null,"attempts");i("deliveryLane",{nextDue:await n("deliveries")}),i("actionLane",{nextDue:await n("daemon_actions")}),i("pendingReviewSubmit",{nextDue:a(async e=>(await x()).length>0?e:null,"nextDue")}),i("storageDueWork",{nextDue:a(async e=>{if(I()===null)return null;if(await r("SELECT 1 FROM uploads WHERE delete_pending_since IS NOT NULL LIMIT 1")!==void 0||await r("SELECT 1 FROM shares WHERE status = 'off' AND object_deleted_at IS NULL LIMIT 1")!==void 0)return e;const t=(await r("SELECT MIN(expires_at) AS at FROM shares WHERE status = 'on' AND expires_at IS NOT NULL"))?.at,s=(await r(`SELECT MIN(created_at) AS at FROM uploads u WHERE delete_pending_since IS NULL
8
- AND NOT EXISTS (SELECT 1 FROM upload_uses x WHERE x.upload_id = u.upload_id)`))?.at,l=u(s);return c([u(t),l===null?null:l+T])},"nextDue")}),i("importLane",{nextDue:a(async e=>await r(`SELECT 1 FROM import_runs WHERE state IN ('loading', 'committed') AND (claimed_by IS NULL OR lease_expires_at IS NULL OR lease_expires_at <= '${new Date(e).toISOString()}')`)!==void 0?e:null,"nextDue")}),i("faultRetryBackstop",{nextDue:a(async()=>c((await g()).map(e=>y(e))),"nextDue")})}a(S,"installDueSources");const w=12e4;async function U(n){const e=await _(`SELECT n.node_id, n.status, n.intent, n.profile_id, n.pi_pid, n.frozen_at, n.respawn_not_before, n.created, n.launched_at,
7
+ AND NOT (held = 1 AND recur IS NULL AND expires_at IS NULL)`)).filter(o=>!p(o.profile)).map(o=>u(o.fire_at)),t=(await _("SELECT expires_at FROM crons WHERE expires_at IS NOT NULL AND run_state = 'idle'")).map(o=>u(o.expires_at));return c([...e,...t])},"nextDue")});const n=a(async e=>async()=>(await s(`SELECT MIN(next_attempt_at) AS at FROM ${e} WHERE state = 'pending' AND canceled_at IS NULL AND next_attempt_at IS NOT NULL`))?.at??null,"attempts");i("deliveryLane",{nextDue:await n("deliveries")}),i("actionLane",{nextDue:await n("daemon_actions")}),i("pendingReviewSubmit",{nextDue:a(async e=>(await x()).length>0?e:null,"nextDue")}),i("storageDueWork",{nextDue:a(async e=>{if(I()===null)return null;if(await s("SELECT 1 FROM uploads WHERE delete_pending_since IS NOT NULL LIMIT 1")!==void 0||await s("SELECT 1 FROM shares WHERE status = 'off' AND object_deleted_at IS NULL LIMIT 1")!==void 0)return e;const t=(await s("SELECT MIN(expires_at) AS at FROM shares WHERE status = 'on' AND expires_at IS NOT NULL"))?.at,o=(await s(`SELECT MIN(created_at) AS at FROM uploads u WHERE delete_pending_since IS NULL
8
+ AND NOT EXISTS (SELECT 1 FROM upload_uses x WHERE x.upload_id = u.upload_id)`))?.at,l=u(o);return c([u(t),l===null?null:l+T])},"nextDue")}),i("importLane",{nextDue:a(async e=>await s(`SELECT 1 FROM import_runs WHERE state IN ('loading', 'committed') AND (claimed_by IS NULL OR lease_expires_at IS NULL OR lease_expires_at <= '${new Date(e).toISOString()}')`)!==void 0?e:null,"nextDue")}),i("faultRetryBackstop",{nextDue:a(async()=>c((await g()).map(e=>y(e))),"nextDue")})}a(S,"installDueSources");const w=12e4;async function W(n){const e=await _(`SELECT n.node_id, n.status, n.intent, n.profile_id, n.pi_pid, n.frozen_at, n.respawn_not_before, n.created, n.launched_at,
9
9
  n.turn_open_at, n.turn_closed_at,
10
10
  (SELECT x.started_at FROM executions x WHERE x.node_id = n.node_id AND x.state != 'exited') AS exec_started_at
11
11
  FROM node_rows n
12
- WHERE n.status IN ('active', 'idle') AND n.kind != 'human' AND n.${L}`);for(const t of e){if(p(t.profile_id)||!await m({node_id:t.node_id,status:t.status,intent:t.intent}))continue;if(t.pi_pid!==null&&R(t.pi_pid)){if(t.turn_open_at!==null&&t.turn_closed_at===null)return!0;const d=u(t.exec_started_at);if(t.turn_open_at===null&&d!==null&&n-d<w||await f(t.node_id))return!0;continue}if(t.respawn_not_before!==null)continue;if(t.pi_pid!==null||t.frozen_at!==null||t.status==="active")return!0;const l=Math.max(...[t.created,t.launched_at,t.exec_started_at].map(d=>u(d)??0));if(l>0&&n-l<w||t.status==="idle"&&await f(t.node_id))return!0}return!1}a(U,"nodesOweWork");async function V(n=Date.now()){await S();const{dueNow:e,nextDueMs:t}=await h(n,(l,d)=>{O({level:"warn",event:"daemon.due.source_failed",error:d,fields:{lane:l}})});return{busy:e||await U(n)||await r("SELECT 1 FROM crons WHERE run_state = 'running' LIMIT 1")!==void 0||await r("SELECT 1 FROM jobs j JOIN objects o ON o.id = j.object WHERE j.status = 'running' AND o.deleted_at IS NULL LIMIT 1")!==void 0,next_due_at:t===null?null:new Date(t).toISOString()}}a(V,"dueReport");async function Y(){return await S(),[...v(),...b()]}a(Y,"coveredLanes");export{w as START_GRACE_MS,Y as coveredLanes,V as dueReport,S as installDueSources};
12
+ WHERE n.status IN ('active', 'idle') AND n.kind != 'human' AND n.${L}`);for(const t of e){if(p(t.profile_id)||!await m({node_id:t.node_id,status:t.status,intent:t.intent}))continue;if(t.pi_pid!==null&&R(t.pi_pid)){if(t.turn_open_at!==null&&t.turn_closed_at===null)return!0;const d=u(t.exec_started_at);if(t.turn_open_at===null&&d!==null&&n-d<w||await f(t.node_id))return!0;continue}if(t.respawn_not_before!==null)continue;if(t.pi_pid!==null||t.frozen_at!==null||t.status==="active")return!0;const l=Math.max(...[t.created,t.launched_at,t.exec_started_at].map(d=>u(d)??0));if(l>0&&n-l<w||t.status==="idle"&&await f(t.node_id))return!0}return!1}a(W,"nodesOweWork");async function V(n=Date.now()){await S();const{dueNow:e,nextDueMs:t}=await M(n,(l,d)=>{O({level:"warn",event:"daemon.due.source_failed",error:d,fields:{lane:l}})});return{busy:e||await W(n)||await s("SELECT 1 FROM crons WHERE run_state = 'running' LIMIT 1")!==void 0||await s("SELECT 1 FROM jobs j JOIN objects o ON o.id = j.object WHERE j.status = 'running' AND o.deleted_at IS NULL LIMIT 1")!==void 0,next_due_at:t===null?null:new Date(t).toISOString()}}a(V,"dueReport");async function Y(){return await S(),[...v(),...A()]}a(Y,"coveredLanes");export{w as START_GRACE_MS,Y as coveredLanes,V as dueReport,S as installDueSources};
@@ -0,0 +1,18 @@
1
+ import type { RunnerExecution } from '../../core/runtime/runner/types.js';
2
+ import type { DetachedWorkLifecycle } from './broker-supervision.js';
3
+ import { type LanePass } from './throttled-lane.js';
4
+ export declare const IDLE_SANDBOX_INTERVAL_MS: number;
5
+ export declare const IDLE_SANDBOX_MAX_AGE_MS: number;
6
+ /** Sandboxes deleted per pass; the rest wait for the next pass. */
7
+ export declare const IDLE_SANDBOX_BUDGET = 50;
8
+ export interface IdleSandboxResult {
9
+ deleted: number;
10
+ failed: number;
11
+ }
12
+ export declare class IdleSandboxReconciler {
13
+ run(now: number, ctx: {
14
+ lifecycle: DetachedWorkLifecycle;
15
+ }): void;
16
+ /** One pass. `deleteExecution` is the runner's delete by default; tests pass their own. */
17
+ pass(now: number, lane?: LanePass, deleteExecution?: (execution: RunnerExecution) => Promise<void>): Promise<IdleSandboxResult>;
18
+ }
@@ -0,0 +1,7 @@
1
+ var u=Object.defineProperty;var c=(a,n)=>u(a,"name",{value:n,configurable:!0});import{openDb as p}from"../../core/canvas/db.js";import{endExecution as m}from"../../core/canvas/executions.js";import{emitEvent as r}from"../../core/events/emit.js";import{operationIdContext as _}from"../../core/events/operation-id.js";import{runnerForExecution as f}from"../../core/runtime/runner/index.js";import{runThrottledLane as E}from"./throttled-lane.js";const N=60*6e4,D=10080*6e4,S=10*6e4,b=50;class R{static{c(this,"IdleSandboxReconciler")}run(n,i){if(!i.lifecycle.acceptsDetachedWork())return;const d=_.fresh(()=>E("idle-sandbox","",n,N,S,async t=>{await this.pass(n,t)})).then(()=>{}).catch(t=>{_.fresh(()=>r({level:"error",event:"idle_sandbox.failed",error:t}))});i.lifecycle.registerDetached(d)}async pass(n,i,d=async t=>{const o=f("blaxel");if(o.deleteExecution===void 0)throw new Error("the Blaxel runner cannot delete one execution");await o.deleteExecution(t)}){const t={deleted:0,failed:0},o=new Date(n-D).toISOString(),l=await p(),x=await l.prepare(`SELECT x.execution_id, x.node_id, x.attempt, x.sandbox_name FROM executions x
2
+ JOIN nodes n ON n.node_id = x.node_id
3
+ JOIN profiles p ON p.id = n.profile_id
4
+ JOIN environments e ON e.object = p.environment_id
5
+ WHERE x.runner = 'blaxel' AND x.state = 'running' AND x.idle_at IS NOT NULL AND x.idle_at::timestamptz < ?::timestamptz
6
+ AND e.kind = 'blaxel' AND EXISTS (SELECT 1 FROM environment_repos r WHERE r.environment = e.object)
7
+ ORDER BY x.idle_at LIMIT ?`).all(o,b);for(const e of x){if(i&&!await i.holds())break;try{if(await l.prepare("SELECT 1 AS idle FROM executions WHERE execution_id = ? AND state = 'running' AND idle_at IS NOT NULL AND idle_at::timestamptz < ?::timestamptz").get(e.execution_id,o)===void 0)continue;await d({executionId:e.execution_id,nodeId:e.node_id,attempt:Number(e.attempt),sandboxName:e.sandbox_name}),await m(e.execution_id,{reason:"lost"}),t.deleted+=1,r({level:"info",event:"idle_sandbox.deleted",node_id:e.node_id,fields:{execution_id:e.execution_id}})}catch(s){t.failed+=1,r({level:"warn",event:"idle_sandbox.delete_failed",node_id:e.node_id,error:s,fields:{execution_id:e.execution_id}})}}return t}}export{b as IDLE_SANDBOX_BUDGET,N as IDLE_SANDBOX_INTERVAL_MS,D as IDLE_SANDBOX_MAX_AGE_MS,R as IdleSandboxReconciler};
@@ -1,6 +1,6 @@
1
- var A=Object.defineProperty;var d=(o,e)=>A(o,"name",{value:e,configurable:!0});import{mkdtempSync as T}from"node:fs";import{tmpdir as h}from"node:os";import{join as R}from"node:path";import{hasUnseenWakeMail as O}from"../../core/canvas/deliveries.js";import{openDb as l,withCanvasWrite as U}from"../../core/canvas/db.js";import{emitEvent as g}from"../../core/events/emit.js";import{appendRunEvent as y}from"../../core/runs/events.js";import{blaxelConfigFromEnv as u}from"../../core/runtime/runner/blaxel/client.js";import{buildImage as I,deleteImage as W,environmentImageName as f,prepareBuildDir as C,removeBuildDir as j}from"../../core/runtime/runner/blaxel/image-build.js";import{mintInstallationToken as H}from"../api/handlers/git-credential.js";import{RECIPE_HAS_CONTENT_SQL as w,recipeOf as x}from"../api/environment-of.js";import{brokerSignalBus as $}from"../broker-signals/bus.js";const E=3*6e4,N=10*6e4,p="EXISTS (SELECT 1 FROM objects o WHERE o.id = environments.object AND o.deleted_at IS NOT NULL)",b=`NOT ${p}`,S=`(kind = 'blaxel' AND ${b} AND recipe_revision > COALESCE(image_revision, 0) AND ${w})`,L=`(kind = 'blaxel' AND ${p} AND (image_ref IS NOT NULL OR image_revision IS NOT NULL OR image_building_at IS NOT NULL))`;async function ee(o){const e=await(await l()).prepare(`SELECT ${w} AS has_content, image_revision, image_ref, image_error FROM environments WHERE object = ?`).get(o);if(e===void 0)throw new Error(`no environment ${o}`);return e.has_content?e.image_ref===null||e.image_revision===null?{state:"pending",error:e.image_error}:{state:"image",ref:e.image_ref,revision:Number(e.image_revision)}:{state:"base"}}d(ee,"resolveEnvironmentImage");async function ie(o){return await $.subscribe(e=>{o(e)},{kinds:["environment_image"]})}d(ie,"subscribeImageBuilt");async function k(o,e){const t=o.recipe.repositories.map(r=>r.github_full_name),i=t.length===0?null:await H(o.person,t),a=T(R(h(),"crtr-recipe-image-"));try{return await C({recipe:o.recipe,revision:o.revision,token:i?.token??null,dir:a}),await I(e,f(o.environmentId),a)}finally{j(a)}}d(k,"defaultBuild");class te{static{d(this,"RecipeImageReconciler")}deps;constructor(e={}){this.deps=e}async run(e,t){if(t.lifecycle.acceptsDetachedWork())try{const i=new Date(e).toISOString(),a=await l(),r=await a.prepare(`SELECT object FROM environments WHERE ${S} AND (image_building_at IS NULL OR image_building_at <= ?)`).all(i);for(const{object:n}of r){const s=await this.claim(n,e,S,"recipe_revision");s!==null&&t.lifecycle.registerDetached(this.buildClaimed(n,Number(s.recipe_revision),s.lease).catch(_=>{g({level:"error",event:"recipe_image.failed",error:_})}))}const c=await a.prepare(`SELECT object FROM environments WHERE ${L} AND (image_building_at IS NULL OR image_building_at <= ?)`).all(i);for(const{object:n}of c){const s=await this.claim(n,e,L,"object");s!==null&&t.lifecycle.registerDetached(this.withLease(n,s.lease,_=>this.deleteClaimed(n,_)).catch(_=>{g({level:"error",event:"recipe_image.delete_failed",error:_})}))}}catch(i){g({level:"error",event:"recipe_image.reconcile_failed",error:i})}}async claim(e,t,i,a){const r=new Date(t+E).toISOString(),c=await(await l()).prepare(`UPDATE environments SET image_building_at = ?
1
+ var T=Object.defineProperty;var d=(o,e)=>T(o,"name",{value:e,configurable:!0});import{mkdtempSync as A}from"node:fs";import{tmpdir as h}from"node:os";import{join as R}from"node:path";import{hasUnseenWakeMail as O}from"../../core/canvas/deliveries.js";import{openDb as l,withCanvasWrite as U}from"../../core/canvas/db.js";import{emitEvent as g}from"../../core/events/emit.js";import{appendRunEvent as y}from"../../core/runs/events.js";import{blaxelConfigFromEnv as u}from"../../core/runtime/runner/blaxel/client.js";import{buildImage as I,deleteImage as W,environmentImageName as f,prepareBuildDir as C,removeBuildDir as j}from"../../core/runtime/runner/blaxel/image-build.js";import{mintInstallationToken as H}from"../api/handlers/git-credential.js";import{RECIPE_HAS_CONTENT_SQL as w,packagesTokenFor as k,recipeOf as x}from"../api/environment-of.js";import{brokerSignalBus as $}from"../broker-signals/bus.js";const E=3*6e4,N=10*6e4,p="EXISTS (SELECT 1 FROM objects o WHERE o.id = environments.object AND o.deleted_at IS NOT NULL)",b=`NOT ${p}`,S=`(kind = 'blaxel' AND ${b} AND recipe_revision > COALESCE(image_revision, 0) AND ${w})`,L=`(kind = 'blaxel' AND ${p} AND (image_ref IS NOT NULL OR image_revision IS NOT NULL OR image_building_at IS NOT NULL))`;async function ie(o){const e=await(await l()).prepare(`SELECT ${w} AS has_content, image_revision, image_ref, image_error FROM environments WHERE object = ?`).get(o);if(e===void 0)throw new Error(`no environment ${o}`);return e.has_content?e.image_ref===null||e.image_revision===null?{state:"pending",error:e.image_error}:{state:"image",ref:e.image_ref,revision:Number(e.image_revision)}:{state:"base"}}d(ie,"resolveEnvironmentImage");async function te(o){return await $.subscribe(e=>{o(e)},{kinds:["environment_image"]})}d(te,"subscribeImageBuilt");async function F(o,e){const t=o.recipe.repositories.map(r=>r.github_full_name),i=t.length===0?null:await H(o.person,t),a=A(R(h(),"crtr-recipe-image-"));try{return await C({recipe:o.recipe,revision:o.revision,token:i?.token??null,packagesToken:await k(o.environmentId),dir:a}),await I(e,f(o.environmentId),a)}finally{j(a)}}d(F,"defaultBuild");class re{static{d(this,"RecipeImageReconciler")}deps;constructor(e={}){this.deps=e}async run(e,t){if(t.lifecycle.acceptsDetachedWork())try{const i=new Date(e).toISOString(),a=await l(),r=await a.prepare(`SELECT object FROM environments WHERE ${S} AND (image_building_at IS NULL OR image_building_at <= ?)`).all(i);for(const{object:n}of r){const s=await this.claim(n,e,S,"recipe_revision");s!==null&&t.lifecycle.registerDetached(this.buildClaimed(n,Number(s.recipe_revision),s.lease).catch(_=>{g({level:"error",event:"recipe_image.failed",error:_})}))}const c=await a.prepare(`SELECT object FROM environments WHERE ${L} AND (image_building_at IS NULL OR image_building_at <= ?)`).all(i);for(const{object:n}of c){const s=await this.claim(n,e,L,"object");s!==null&&t.lifecycle.registerDetached(this.withLease(n,s.lease,_=>this.deleteClaimed(n,_)).catch(_=>{g({level:"error",event:"recipe_image.delete_failed",error:_})}))}}catch(i){g({level:"error",event:"recipe_image.reconcile_failed",error:i})}}async claim(e,t,i,a){const r=new Date(t+E).toISOString(),c=await(await l()).prepare(`UPDATE environments SET image_building_at = ?
2
2
  WHERE object = ? AND ${i} AND (image_building_at IS NULL OR image_building_at <= ?)
3
- RETURNING ${a} AS recipe_revision`).get(r,e,new Date(t).toISOString());return c===void 0?null:{recipe_revision:c.recipe_revision,lease:r}}async withLease(e,t,i){const a=this.deps.now??Date.now;let r=t;const c=setInterval(()=>{const n=new Date(a()+E).toISOString();(async()=>{(await(await l()).prepare("UPDATE environments SET image_building_at = ? WHERE object = ? AND image_building_at = ?").run(n,e,r)).changes===1&&(r=n)})().catch(()=>{})},E/3);c.unref();try{await i(()=>r)}finally{clearInterval(c)}}async deleteClaimed(e,t){try{await(this.deps.deleteImage??(i=>W(u(),i)))(f(e))}catch(i){const a=i instanceof Error?i.message:String(i),r=new Date((this.deps.now??Date.now)()+N).toISOString();(await(await l()).prepare("UPDATE environments SET image_error = ?, image_building_at = ? WHERE object = ? AND image_building_at = ?").run(`deleting the image failed: ${a}`,r,e,t())).changes===1&&g({level:"error",event:"recipe_image.delete_failed",fields:{environment_id:e,error:a}});return}await(await l()).prepare("UPDATE environments SET image_ref = NULL, image_revision = NULL, image_error = NULL, image_building_at = NULL WHERE object = ? AND image_building_at = ?").run(e,t())}async buildClaimed(e,t,i){const a=this.deps.now??Date.now;await this.withLease(e,i,async r=>{const c=await x(e);if(c===null||c.revision!==t){await(await l()).prepare("UPDATE environments SET image_building_at = NULL WHERE object = ? AND image_building_at = ?").run(e,r());return}let n;try{const m=await(await l()).prepare("SELECT person FROM profiles WHERE environment_id = ? ORDER BY created_at LIMIT 1").get(e);if(m===void 0)throw new Error(`no profile runs in environment ${e}, so there is no person to take a GitHub token for`);const D={environmentId:e,revision:t,recipe:c,person:m.person};n=await(this.deps.build??(v=>k(v,u())))(D)}catch(m){await this.recordFailure(e,r(),m instanceof Error?m.message:String(m),a());return}const s=await l();(await s.prepare(`UPDATE environments SET image_revision = ?, image_ref = ?, image_error = NULL, image_building_at = NULL
4
- WHERE object = ? AND image_building_at = ? AND COALESCE(image_revision, 0) < ? AND ${b}`).run(t,n.ref,e,r(),t)).changes!==1&&await s.prepare(`UPDATE environments SET image_ref = ?, image_building_at = NULL WHERE object = ? AND ${p}`).run(n.ref,e)})}async recordFailure(e,t,i,a){const r=new Date(a+N).toISOString();if((await(await l()).prepare("UPDATE environments SET image_error = ?, image_building_at = ? WHERE object = ? AND image_building_at = ?").run(i,r,e,t)).changes===1){g({level:"error",event:"recipe_image.build_failed",fields:{environment_id:e,error:i}});for(const n of await F(e))try{await U(async s=>{await y(s,n.run_id,n.node_id,"environment.image_failed",{environment_id:e,error:i})})}catch(s){g({level:"error",event:"recipe_image.failure_event_failed",node_id:n.node_id,error:s})}}}}async function F(o){const e=await(await l()).prepare(`SELECT n.node_id, n.run_id FROM nodes n JOIN profiles p ON p.id = n.profile_id
3
+ RETURNING ${a} AS recipe_revision`).get(r,e,new Date(t).toISOString());return c===void 0?null:{recipe_revision:c.recipe_revision,lease:r}}async withLease(e,t,i){const a=this.deps.now??Date.now;let r=t;const c=setInterval(()=>{const n=new Date(a()+E).toISOString();(async()=>{(await(await l()).prepare("UPDATE environments SET image_building_at = ? WHERE object = ? AND image_building_at = ?").run(n,e,r)).changes===1&&(r=n)})().catch(()=>{})},E/3);c.unref();try{await i(()=>r)}finally{clearInterval(c)}}async deleteClaimed(e,t){try{await(this.deps.deleteImage??(i=>W(u(),i)))(f(e))}catch(i){const a=i instanceof Error?i.message:String(i),r=new Date((this.deps.now??Date.now)()+N).toISOString();(await(await l()).prepare("UPDATE environments SET image_error = ?, image_building_at = ? WHERE object = ? AND image_building_at = ?").run(`deleting the image failed: ${a}`,r,e,t())).changes===1&&g({level:"error",event:"recipe_image.delete_failed",fields:{environment_id:e,error:a}});return}await(await l()).prepare("UPDATE environments SET image_ref = NULL, image_revision = NULL, image_error = NULL, image_building_at = NULL WHERE object = ? AND image_building_at = ?").run(e,t())}async buildClaimed(e,t,i){const a=this.deps.now??Date.now;await this.withLease(e,i,async r=>{const c=await x(e);if(c===null||c.revision!==t){await(await l()).prepare("UPDATE environments SET image_building_at = NULL WHERE object = ? AND image_building_at = ?").run(e,r());return}let n;try{const m=await(await l()).prepare("SELECT person FROM profiles WHERE environment_id = ? ORDER BY created_at LIMIT 1").get(e);if(m===void 0)throw new Error(`no profile runs in environment ${e}, so there is no person to take a GitHub token for`);const D={environmentId:e,revision:t,recipe:c,person:m.person};n=await(this.deps.build??(v=>F(v,u())))(D)}catch(m){await this.recordFailure(e,r(),m instanceof Error?m.message:String(m),a());return}const s=await l();(await s.prepare(`UPDATE environments SET image_revision = ?, image_ref = ?, image_error = NULL, image_building_at = NULL
4
+ WHERE object = ? AND image_building_at = ? AND COALESCE(image_revision, 0) < ? AND ${b}`).run(t,n.ref,e,r(),t)).changes!==1&&await s.prepare(`UPDATE environments SET image_ref = ?, image_building_at = NULL WHERE object = ? AND ${p}`).run(n.ref,e)})}async recordFailure(e,t,i,a){const r=new Date(a+N).toISOString();if((await(await l()).prepare("UPDATE environments SET image_error = ?, image_building_at = ? WHERE object = ? AND image_building_at = ?").run(i,r,e,t)).changes===1){g({level:"error",event:"recipe_image.build_failed",fields:{environment_id:e,error:i}});for(const n of await M(e))try{await U(async s=>{await y(s,n.run_id,n.node_id,"environment.image_failed",{environment_id:e,error:i})})}catch(s){g({level:"error",event:"recipe_image.failure_event_failed",node_id:n.node_id,error:s})}}}}async function M(o){const e=await(await l()).prepare(`SELECT n.node_id, n.run_id FROM nodes n JOIN profiles p ON p.id = n.profile_id
5
5
  WHERE p.environment_id = ? AND n.status IN ('active', 'idle') AND n.run_id IS NOT NULL
6
- AND NOT EXISTS (SELECT 1 FROM executions e WHERE e.node_id = n.node_id AND e.state != 'exited')`).all(o),t=[];for(const i of e)await O(i.node_id)&&t.push(i);return t}d(F,"nodesWaitingOnImage");export{p as ENVIRONMENT_DELETED_SQL,b as ENVIRONMENT_LIVE_SQL,S as IMAGE_BUILD_OWED_SQL,L as IMAGE_DELETE_OWED_SQL,E as LEASE_MS,N as RETRY_AFTER_FAILURE_MS,te as RecipeImageReconciler,F as nodesWaitingOnImage,ee as resolveEnvironmentImage,ie as subscribeImageBuilt};
6
+ AND NOT EXISTS (SELECT 1 FROM executions e WHERE e.node_id = n.node_id AND e.state != 'exited')`).all(o),t=[];for(const i of e)await O(i.node_id)&&t.push(i);return t}d(M,"nodesWaitingOnImage");export{p as ENVIRONMENT_DELETED_SQL,b as ENVIRONMENT_LIVE_SQL,S as IMAGE_BUILD_OWED_SQL,L as IMAGE_DELETE_OWED_SQL,E as LEASE_MS,N as RETRY_AFTER_FAILURE_MS,re as RecipeImageReconciler,M as nodesWaitingOnImage,ie as resolveEnvironmentImage,te as subscribeImageBuilt};
@@ -1,14 +1,10 @@
1
1
  ---
2
2
  title: Files and documents
3
- description: Download a file from a person's runtime with files.download, serve a file an agent handed to the person with files.link, and read the person's public documents with memory.list and memory.get.
3
+ description: Serve a file an agent handed to the person with files.link, share it with shares.create, and read the person's public documents with memory.list and memory.get.
4
4
  ---
5
5
 
6
6
  # Files and documents
7
7
 
8
- ## Download a file
9
-
10
- `runtime.files.download(path, options?)` returns the file's raw bytes as a Fetch `Response` (200, or 206 for a `range`) with `Content-Type`, `Content-Length` and `Content-Range`, so you can pipe its body on. `path` is an absolute path on the person's runtime that your app's grant lets it read. Options: `range` (one `Range` header value such as `bytes=0-0` or `bytes=-500`) and `signal`. A non-2xx answer is thrown as an `APIError`, never returned as bytes; a bad `range` is `416`. A cloud role refuses it with `permission_error`: use `files.link` there. What a path may reach depends on the grant: see [Scopes and grants](/docs/concepts/scopes-and-grants).
11
-
12
8
  ## Receive a file an agent made
13
9
 
14
10
  An agent gives the person a file with `crtr push file <path>`. The file is copied to storage and a `file.sent` event (`{file_id, name, media_type, size}`) appears in the run's event stream. Your app then serves it by `file_id`; the agent's own paths are never exposed, and only the app and person that own the run can reach the file.
@@ -20,7 +16,7 @@ const {url, name} = await runtime.files.link(event.file_id);
20
16
  res.redirect(url);
21
17
  ```
22
18
 
23
- `runtime.shares.create({file_id, expires_at?})` makes a public share link from the same file instead. `shares.create({path, expires_at?})` shares a file by path (refused on a cloud role); pass exactly one of `path` or `file_id`. The client your app gets from `oauth.client(userId)` exposes only `download` and `link` from `files`; reading, writing and listing are not available to apps.
19
+ `runtime.shares.create({file_id, expires_at?})` makes a public share link from the same file instead. A file is reached by `file_id` only: there is no download or share by path. The client your app gets from `oauth.client(userId)` exposes only `link` from `files`; reading, writing and listing are not available to apps.
24
20
 
25
21
  ## Read the person's public documents
26
22
 
@@ -17,7 +17,7 @@ Scope strings are prefixed with `crtr:`. These are the ones the daemon and CLI c
17
17
  | `crtr:memory:read:user[:path]`, `crtr:memory:rw:user[:path]`, `crtr:memory:manage:user` | The person's documents: reading, writing (`crtr doc`), and `manage` for every privacy level and every document |
18
18
  | `crtr:memory:read_private:user` | Read-only access to the person's `public` and `private` documents; no path suffix; an optional permission the person switches on; `manage:user` covers it, `read:user` and `rw:user` do not |
19
19
  | `crtr:memory:read:app:<id>`, `crtr:memory:rw:app:<id>` | An app's documents; `…:profile:<profile>` narrows to one of its profiles. A run with no `scopes` list, and an app's own server, reads and writes its own app's space freely; a run started with a `scopes` list needs these for its own app too |
20
- | `crtr:files:read\|rw:user:<dir>`, `crtr:files:read\|rw:app:<id>:<dir>`, `crtr:files:share` | Host files the run may mount, and sharing files beyond the app's own space |
20
+ | `crtr:files:read\|rw:user:<dir>`, `crtr:files:read\|rw:app:<id>:<dir>`, `crtr:files:share` | Host files the run may mount; `crtr:files:share` is still accepted but no route checks it, since sharing is by `file_id` only |
21
21
  | `crtr:conversations:read:app:<id>`, `crtr:objects:read:app:<id>` | Reading another app's conversations or node objects |
22
22
  | `<provider>:<group>` | One tool group of a provider |
23
23
 
@@ -7,6 +7,12 @@ description: Behavior changes in @north-light/sdk that an app must act on, newes
7
7
 
8
8
  Changes to `@north-light/sdk` that can change what an existing app sees. Newest first.
9
9
 
10
+ ## 0.3.666
11
+
12
+ ### `files.download` and `shares.create({path})` are removed (breaking)
13
+
14
+ `files.download(path)`, `FileDownloadOptions`, and the `path` option of `shares.create` are gone, and so is the runtime route `GET /v1/files/download`, on a Mac as well as on a cloud role. A file an agent made is handed over with `crtr push file`; your app reads its `file_id` from the run's `file.sent` event, serves it with `files.link(fileId)` and shares it with `shares.create({file_id})`. `shares.create` now requires `file_id`, and a request with `path` is a 400 (`unknown field path`). `GET /v1/files/download` answers `404 unknown operation`. Shares already created from a path keep working: the share's stored copy and public URL are unchanged, and `shares.list` and `shares.delete` still see them.
15
+
10
16
  ## 0.3.633
11
17
 
12
18
  ### `inferenceEndpoint` falls back to the app's API key when the team Claude pool cannot serve a Northlight-paid call
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.665",
3
+ "version": "0.3.667",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -149,7 +149,7 @@
149
149
  },
150
150
  "license": "UNLICENSED",
151
151
  "dependencies": {
152
- "@north-light/identity": "0.3.665",
152
+ "@north-light/identity": "0.3.667",
153
153
  "@earendil-works/chord": "1.5.2",
154
154
  "@earendil-works/pi-agent-core": "1.5.2",
155
155
  "@earendil-works/pi-ai": "1.5.2",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.665",
3
+ "version": "0.3.667",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",