@north-light/cli 0.3.755 → 0.3.756

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 (121) hide show
  1. package/dist/api/client.d.ts +1 -2
  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/health.d.ts +0 -54
  6. package/dist/api/routes.d.ts +0 -1
  7. package/dist/api/routes.js +1 -1
  8. package/dist/build-root.d.ts +0 -3
  9. package/dist/build-root.js +1 -1
  10. package/dist/builtin-memory/internal/storage-tiers.md +1 -1
  11. package/dist/cli.js +8 -9
  12. package/dist/clients/attach/viewer.js +481 -481
  13. package/dist/commands/sys/branch.js +1 -1
  14. package/dist/commands/sys/daemon.js +1 -1
  15. package/dist/commands/sys.js +1 -1
  16. package/dist/core/bootstrap.js +1 -1
  17. package/dist/core/canvas/boot.d.ts +0 -25
  18. package/dist/core/canvas/boot.js +1 -1
  19. package/dist/core/canvas/executions.d.ts +0 -3
  20. package/dist/core/canvas/executions.js +1 -1
  21. package/dist/core/canvas/pid.d.ts +0 -10
  22. package/dist/core/canvas/pid.js +5 -5
  23. package/dist/core/directory/join.js +1 -1
  24. package/dist/core/grants/mirror.d.ts +0 -5
  25. package/dist/core/grants/mirror.js +6 -6
  26. package/dist/core/grants/sync.js +1 -1
  27. package/dist/core/human/page-schema.d.ts +1 -1
  28. package/dist/core/io.js +4 -4
  29. package/dist/core/layout.d.ts +0 -2
  30. package/dist/core/layout.js +2 -2
  31. package/dist/core/scoped-state/db.js +2 -2
  32. package/dist/daemon/api/handlers/daemon.js +1 -1
  33. package/dist/daemon/api/map.d.ts +1 -6
  34. package/dist/daemon/api/map.js +2 -2
  35. package/dist/daemon/api/operations.js +1 -1
  36. package/dist/daemon/api/server.js +1 -1
  37. package/dist/daemon/control.d.ts +0 -8
  38. package/dist/daemon/crtrd.js +18 -20
  39. package/dist/daemon/manage.js +3 -3
  40. package/package.json +3 -3
  41. package/packages/crouter-api/dist/api/client.js +0 -3
  42. package/packages/crouter-api/dist/api/contract.js +1 -1
  43. package/packages/crouter-api/dist/api/routes.js +0 -1
  44. package/packages/crouter-api/dist/build-root.js +0 -9
  45. package/packages/crouter-api/dist/commands/sys/branch.js +1 -1
  46. package/packages/crouter-api/dist/commands/sys/daemon.js +1 -1
  47. package/packages/crouter-api/dist/commands/sys.js +1 -2
  48. package/packages/crouter-api/dist/core/canvas/executions.js +1 -17
  49. package/packages/crouter-api/dist/core/canvas/pid.js +0 -16
  50. package/packages/crouter-api/dist/core/directory/join.js +18 -1
  51. package/packages/crouter-api/dist/core/grants/mirror.js +0 -7
  52. package/packages/crouter-api/dist/core/grants/sync.js +2 -2
  53. package/packages/crouter-api/dist/core/io.js +0 -5
  54. package/packages/crouter-api/dist/core/layout.js +2 -19
  55. package/packages/crouter-api/dist/daemon/api/map.js +0 -16
  56. package/packages/crouter-api/dist/daemon/api/operations.js +0 -1
  57. package/packages/crouter-api/dist/daemon/manage.js +1 -1
  58. package/packages/crouter-api/package.json +1 -1
  59. package/packages/crouter-identity/package.json +1 -1
  60. package/packages/crouter-plugin/package.json +3 -3
  61. package/runtime.lock.json +14 -14
  62. package/dist/commands/sys/migrate.d.ts +0 -1
  63. package/dist/commands/sys/migrate.js +0 -1
  64. package/dist/core/feed/inbox-migrate.d.ts +0 -11
  65. package/dist/core/feed/inbox-migrate.js +0 -3
  66. package/dist/core/graph/bodies-boot-copy.d.ts +0 -28
  67. package/dist/core/graph/bodies-boot-copy.js +0 -1
  68. package/dist/core/layout-migrate/index.d.ts +0 -38
  69. package/dist/core/layout-migrate/index.js +0 -4
  70. package/dist/core/layout-migrate/loose-keys.d.ts +0 -2
  71. package/dist/core/layout-migrate/loose-keys.js +0 -1
  72. package/dist/core/layout-migrate/paths.d.ts +0 -30
  73. package/dist/core/layout-migrate/paths.js +0 -1
  74. package/dist/core/layout-migrate/stored-paths.d.ts +0 -9
  75. package/dist/core/layout-migrate/stored-paths.js +0 -11
  76. package/dist/core/layout-migrate/stores.d.ts +0 -30
  77. package/dist/core/layout-migrate/stores.js +0 -3
  78. package/dist/core/scoped-state/migrate.d.ts +0 -15
  79. package/dist/core/scoped-state/migrate.js +0 -3
  80. package/dist/daemon/boot-migrations.d.ts +0 -14
  81. package/dist/daemon/boot-migrations.js +0 -1
  82. package/dist/migrations/004-canvas-documents/apply.d.ts +0 -8
  83. package/dist/migrations/004-canvas-documents/apply.js +0 -1
  84. package/dist/migrations/004-canvas-documents/index.d.ts +0 -16
  85. package/dist/migrations/004-canvas-documents/index.js +0 -2
  86. package/dist/migrations/004-canvas-documents/legacy/discover.d.ts +0 -16
  87. package/dist/migrations/004-canvas-documents/legacy/discover.js +0 -1
  88. package/dist/migrations/004-canvas-documents/legacy/history.d.ts +0 -5
  89. package/dist/migrations/004-canvas-documents/legacy/history.js +0 -2
  90. package/dist/migrations/004-canvas-documents/legacy/nested.d.ts +0 -7
  91. package/dist/migrations/004-canvas-documents/legacy/nested.js +0 -1
  92. package/dist/migrations/004-canvas-documents/legacy/parse.d.ts +0 -14
  93. package/dist/migrations/004-canvas-documents/legacy/parse.js +0 -1
  94. package/dist/migrations/004-canvas-documents/legacy/types.d.ts +0 -91
  95. package/dist/migrations/004-canvas-documents/legacy/types.js +0 -0
  96. package/dist/migrations/004-canvas-documents/plan.d.ts +0 -102
  97. package/dist/migrations/004-canvas-documents/plan.js +0 -3
  98. package/dist/migrations/004-canvas-documents/pointers.d.ts +0 -23
  99. package/dist/migrations/004-canvas-documents/pointers.js +0 -4
  100. package/dist/migrations/activation.d.ts +0 -17
  101. package/dist/migrations/activation.js +0 -2
  102. package/packages/crouter-api/dist/commands/sys/migrate.js +0 -79
  103. package/packages/crouter-api/dist/core/layout-migrate/index.js +0 -523
  104. package/packages/crouter-api/dist/core/layout-migrate/paths.js +0 -118
  105. package/packages/crouter-api/dist/core/layout-migrate/stored-paths.js +0 -424
  106. package/packages/crouter-api/dist/core/layout-migrate/stores.js +0 -543
  107. package/packages/crouter-api/dist/core/locked-file.js +0 -121
  108. package/packages/crouter-api/dist/core/scoped-state/db.js +0 -271
  109. package/packages/crouter-api/dist/core/scoped-state/legacy-profiles.js +0 -65
  110. package/packages/crouter-api/dist/core/scoped-state/migrate.js +0 -332
  111. package/packages/crouter-api/dist/core/scoped-state/schema.js +0 -52
  112. package/packages/crouter-api/dist/migrations/004-canvas-documents/apply.js +0 -113
  113. package/packages/crouter-api/dist/migrations/004-canvas-documents/index.js +0 -89
  114. package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/discover.js +0 -251
  115. package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/history.js +0 -37
  116. package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/nested.js +0 -37
  117. package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/parse.js +0 -24
  118. package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/types.js +0 -3
  119. package/packages/crouter-api/dist/migrations/004-canvas-documents/plan.js +0 -410
  120. package/packages/crouter-api/dist/migrations/004-canvas-documents/pointers.js +0 -95
  121. package/packages/crouter-api/dist/migrations/activation.js +0 -46
@@ -1 +1 @@
1
- var Fe=Object.defineProperty;var i=(e,r)=>Fe(e,"name",{value:r,configurable:!0});import{markAuthenticated as j,markReceived as V}from"../../core/step-timings.js";import{IMPORT_TOKEN_PREFIX as Me,importPrincipalFor as $e}from"./import-auth.js";import{createServer as pe}from"node:http";import{createServer as Je}from"node:https";import{chmodSync as We,existsSync as X,readFileSync as de,unlinkSync as me}from"node:fs";import{MINIMUM_RUNTIME_VERSION_HEADER as fe,RUNTIME_VERSION_HEADER as Z,minimumRuntimeRefusal as je}from"../../api/runtime-version.js";import{CONTRACT_HEADER as Q,CONTRACT_LEVEL as ge,REQUIRED_CONTRACT_HEADER as he,contractRefusal as Ve}from"../../api/contract.js";import{crtrVersion as q}from"../../shared/crtr-version.js";import{apiSocketPath as Ge}from"../../core/canvas/paths.js";import{resolveNodeToken as Ye}from"../../core/canvas/node-tokens.js";import{isCloudRole as I,runAsPerson as G}from"../../core/canvas/person.js";import{isCanvasRequest as Ke,serveCanvas as Xe}from"./canvas-host.js";import{personBearerVerifier as Re}from"./auth/person-bearer.js";import{personHasSnapshot as ee}from"../../core/scoped-state/person-store.js";import{loadPersonSettings as re}from"../../core/scoped-state/person-rows.js";import{AppPrincipalResolver as Ze}from"./principal.js";import{createAppRequestHandler as Qe}from"./app-listener.js";import{decodeJwt as qe}from"jose";import{handleRuntimeSignIn as er,isRuntimeSignInPath as rr}from"./key-signin.js";import{RunError as C}from"../../core/runs/operations.js";import{createRepoPluginHandler as tr,isRepoPluginPath as nr}from"./repo-plugin.js";import{removeVendorAccount as or,vendorStatus as ir}from"./handlers/vendor-status.js";import{toErrorBody as sr}from"./map.js";import{CONTROL_BODY_MAX_BYTES as ar}from"../../core/llm/body-limits.js";import{grantFor as lr,hasSyncedGrants as cr}from"../../core/grants/mirror.js";import{readConfig as Ae}from"../../core/config.js";import{directoryIssuer as ur}from"../../core/directory/issuer.js";import{peerUid as pr}from"../../native/linux.js";import{findScopedApiToken as dr,getApiToken as mr,listScopedApiTokens as fr}from"../../core/secrets.js";import{emitEvent as A}from"../../core/events/emit.js";import{envCrtrdTcp as gr,envCrtrdToken as hr}from"../../shared/env.js";import{Router as ve,actsAsPerson as ye}from"./router.js";import{handleAttachUpgrade as Rr,refuseUpgrade as y}from"./bridge.js";import{handleMachineLinkUpgrade as Ar,machineLinkEnvironment as vr,setApiAddress as yr}from"../machine-link/holder.js";import{handleMachineViewUpgrade as _r,machineViewEnvironment as wr}from"../machine-link/forward.js";import{boundDaemonControl as Er}from"../control.js";import{attachRoutes as Sr,mayAttachNode as _e}from"./handlers/attach.js";import{peerRoutes as br}from"../peer/handlers.js";import{bashJobRoutes as Tr}from"./handlers/bash-jobs.js";import{nodeFileRoutes as Cr}from"./handlers/node-files.js";import{bashRoutes as kr}from"./handlers/bash.js";import{hookExecRoutes as Pr}from"./handlers/hook-exec.js";import{brokerOperationRoutes as we}from"./handlers/broker-ops.js";import{brokerSignalRoutes as Ur,brokerSignalStreams as Or}from"./handlers/broker-signals.js";import{brokerRecoveryRoutes as Ee,nodeFaultRoutes as Nr}from"./handlers/broker-recovery.js";import{canvasRoutes as Ir}from"./handlers/canvas.js";import{conversationRoutes as Hr}from"./handlers/conversations.js";import{chatInventoryRoutes as zr}from"./handlers/chat-inventory.js";import{daemonRoutes as Lr}from"./handlers/daemon.js";import{fileRoutes as Br}from"./handlers/files.js";import{focusRoutes as xr}from"./handlers/focus.js";import{analyticsRoutes as Dr}from"./handlers/analytics.js";import{memoryReadsRoutes as Fr}from"./handlers/memory-reads.js";import{memoryRoutes as Mr}from"./handlers/memory.js";import{healthRoutes as $r}from"./handlers/health.js";import{humanRequestRoutes as Jr}from"./handlers/human-requests.js";import{inboxRoutes as Wr}from"./handlers/inbox.js";import{feedbackCommentRoutes as jr}from"./handlers/feedback-comments.js";import{objectRoutes as Vr}from"./handlers/objects.js";import{shareRoutes as Gr}from"./handlers/shares.js";import{customObjectRoutes as Yr}from"./handlers/custom-objects.js";import{docRoutes as Kr}from"./handlers/docs.js";import{deliveryRoutes as Se}from"./handlers/delivery.js";import{deliveryRetryRoutes as Xr}from"./handlers/delivery-retry.js";import{packageDocRoutes as Zr}from"./handlers/package-docs.js";import{documentAccessRoutes as Qr}from"./handlers/document-access.js";import{pluginAppRoutes as qr}from"./handlers/plugin-app-token.js";import{brokerMailRoutes as be,messageRoutes as et}from"./handlers/messages.js";import{modelAuthRoutes as rt}from"./handlers/modelauth.js";import{llmRoutes as tt}from"./handlers/llm.js";import{providerRoutes as nt}from"./handlers/providers.js";import{modelConfigRoutes as ot}from"./handlers/model-config.js";import{settingsRoutes as it}from"./handlers/settings.js";import{nodeRoutes as st}from"./handlers/nodes.js";import{nodeRecordRoutes as at}from"./handlers/node-records.js";import{nodeOutcomeRoutes as lt}from"./handlers/node-outcomes.js";import{nodeEventRoutes as ct}from"./handlers/node-events.js";import{profileRoutes as ut}from"./handlers/profiles.js";import{environmentRoutes as pt}from"./handlers/environments.js";import{appEnvironmentRoutes as dt}from"./handlers/app-environments.js";import{prospectiveChatInventoryRoutes as mt}from"./handlers/prospective-chat-inventory.js";import{reportRoutes as ft}from"./handlers/reports.js";import{runRoutes as gt}from"./handlers/run-routes.js";import{reviewCommentRoutes as ht}from"./handlers/review-comments.js";import{reviewRoutes as Rt}from"./handlers/reviews.js";import{subscriptionRoutes as At}from"./handlers/subscriptions.js";import{structuredRequestRoutes as vt}from"./handlers/structured-requests.js";import{cronRoutes as yt}from"./handlers/crons.js";import{setCronRequestHandler as Te}from"../cron/run-socket.js";import{RUN_TOKEN_PREFIX as _t,cronPrincipalForRunToken as wt}from"../cron/run-token.js";import{worktreeRoutes as Et}from"./handlers/worktree.js";import{limitsRoutes as St}from"./handlers/limits.js";import{chargeRoutes as bt,spendLimitRoutes as Tt}from"./handlers/charges.js";import{executionStartRoutes as Ct}from"./handlers/execution-start.js";import{machineCredentialRoutes as kt}from"./handlers/machine-credential.js";import{machineRoutes as Pt}from"./handlers/machines.js";import{importRoutes as Ut}from"./handlers/imports.js";import{gitCredentialRoutes as Ot}from"./handlers/git-credential.js";import{feedbackRoutes as Nt}from"./handlers/feedback.js";function It(e){return new ve().registerAll($r(e)).registerAll(Lr).registerAll(Gr).registerAll(st).registerAll(at).registerAll(lt).registerAll(Xr).registerAll(ct).registerAll(Tr).registerAll(Cr).registerAll(kr).registerAll(Pr).registerAll(we).registerAll(Ur).registerAll(Se).registerAll(Ee).registerAll(Nr).registerAll(Et).registerAll(St).registerAll(bt).registerAll(Ct).registerAll(kt).registerAll(Pt).registerAll(Ut).registerAll(Ot).registerAll(Nt).registerAll(Tt).registerAll(be).registerAll(et).registerAll(ft).registerAll(gt).registerAll(vt).registerAll(Sr).registerAll(Ir).registerAll(Hr).registerAll(Dr).registerAll(Fr).registerAll(Mr).registerAll(Br).registerAll(Vr).registerAll(Yr).registerAll(Kr).registerAll(Zr).registerAll(Qr).registerAll(qr).registerAll(xr).registerAll(At).registerAll(yt).registerAll(ut).registerAll(pt).registerAll(dt).registerAll(rt).registerAll(tt).registerAll(nt).registerAll(ot).registerAll(it).registerAll(Rt).registerAll(ht).registerAll(Wr).registerAll(Jr).registerAll(zr).registerAll(mt).registerAll(jr).registerAll(br)}i(It,"buildRouter");function Ht(e,r){if(e.toUpperCase()!=="GET")return null;const s=r.split("/").filter(u=>u.length>0);if(s.length!==4||s[0]!=="v1"||s[1]!=="nodes"||s[3]!=="attach")return null;const a=s[2];return a===void 0||a===""?null:decodeURIComponent(a)}i(Ht,"attachNodeId");function zt(e){const r=e.trim();if(r==="")return null;const s=r.lastIndexOf(":");if(s<0)return null;const a=r.slice(0,s),u=r.slice(s+1),d=Number(u);return!Number.isInteger(d)||d<0||d>65535?null:{host:a===""?"0.0.0.0":a,port:d}}i(zt,"parseTcp");function Lt(e,r){return`${e.includes(":")?`[${e}]`:e}:${r}`}i(Lt,"formatTcpAddress");const M={code:"unauthorized",message:"missing or invalid bearer token"},L={code:"owner_only",message:"attach is owner-only; a scoped token does not reach it"},$={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"},te={class:"anonymous",app:"",node:"",run:null,uid:-1,sub:"",grant:null,client_id:null,scopes:[]},B=new WeakMap;function J(e){return B.get(e)}i(J,"socketPrincipal");async function Ce(e,r){const s=process.platform==="linux"?pr(e.socket):null,a=e.headers.authorization;if(a===void 0)return s===null||r.has(s)?{class:"person"}:"unauthorized";if(typeof a!="string"||!a.startsWith("Bearer "))return"unauthorized";if(a.slice(7).startsWith("crtr_pub_"))return te;if(a.slice(7).startsWith(ne)){const u=Oe(a.slice(7));return u!==void 0&&(s===null||r.has(s))?u.principal:"unauthorized"}return ke(a.slice(7),s)}i(Ce,"resolveSocketPrincipal");async function ke(e,r){const s=await Ye(e);if(!s||r!==null&&r!==s.uid)return"unauthorized";const a=ur();if(a&&!I()&&!await cr(a))return"runtime_starting";const u=s.grant??(await lr("app:terminal",s.sub))?.id??null;return{class:"broker",...s,grant:u}}i(ke,"brokerPrincipal");function Pe(e){if(!(e.class==="anonymous"||e.class==="import"))return e.sub!==void 0&&e.sub!==""?e.sub:void 0}i(Pe,"requestPerson");function Ue(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}})}i(Ue,"noteBrokerRequest");const ne="crtr_app_";function Oe(e){const r=e.startsWith(ne)?dr(e):void 0;return r===void 0?void 0:{principal:{class:"app",app:r.grantee,scopes:r.scopes},ceiling:r.scopes}}i(Oe,"appBearer");function Bt(e){const r=new Map;for(const s of fr("user"))r.set(s.token,{principal:{class:"app",app:s.grantee,scopes:s.scopes},ceiling:s.scopes});return e!==void 0&&r.set(e,{principal:{class:"person"},ceiling:null}),r}i(Bt,"resolveBearers");function xt(e){try{return qe(e).act!==void 0}catch{return!1}}i(xt,"carriesAct");const Dt=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*$/;function U(e,r){return e!==void 0&&(e.reason=r),"unauthorized"}i(U,"deny");async function Ne(e,r,s){const a=e.headers.authorization;if(a===void 0&&(e.method??"GET").toUpperCase()==="GET"&&(e.url??"").split("?")[0]==="/healthz")return{principal:te,ceiling:null};if(typeof a!="string"||!a.startsWith("Bearer "))return U(s,a===void 0?"no_authorization_header":"not_a_bearer");const u=a.slice(7);if(u.startsWith("crtr_pub_"))return{principal:te,ceiling:null};if(u.startsWith(ne))return Oe(u)??U(s,"app_token_unknown");if(u.startsWith(_t)){const S=await wt(u);return S===null?U(s,"run_token_invalid_or_settled"):{principal:S,ceiling:null}}const d=r.get(u);if(d!==void 0)return d;const g=$e(u);if(g!==null)return{principal:g,ceiling:null};if(u.startsWith(Me))return U(s,"import_token_invalid");if(Dt.test(u)){if(I()&&xt(u)){const x=K();if(x===null)return"person_bearer";try{const w=await x.verifyCall(a);return w.chain[0]?.sub.startsWith("app:")?{call:w}:U(s,"call_token_presenter_not_an_app")}catch(w){return w instanceof C&&w.status===503?"runtime_starting":U(s,`call_token_${w instanceof C?w.code:"invalid"}`)}}const S=I()?Re():null;if(S===null)return"person_bearer";const O=await S.verify(u);return O===null?U(s,"person_bearer_not_verified"):{principal:{class:"person",sub:O},ceiling:null}}const f=await ke(u,null);return f==="unauthorized"?U(s,"node_token_unknown"):typeof f=="string"?f:{principal:f,ceiling:null}}i(Ne,"authorizeTcp");let Y;function K(){if(Y!==void 0)return Y;const e=process.env.CRTR_DIRECTORY_URL||void 0,r=process.env.CRTR_PUBLIC_API_URL||void 0;return Y=e===void 0||r===void 0?null:new Ze(e,r,async()=>{}),Y}i(K,"cloudCallResolver");let Ie;function Ft(){const e=K();if(e===null)throw new C(503,"runtime_starting","app calls are not configured on this listener");return Ie??=Qe(e,async()=>!0,async()=>{}),Ie}i(Ft,"cloudAppCalls");async function Mt(e,r){H(r),z(r);const s=K();try{if(s===null)throw new C(503,"runtime_starting","sign-in is not configured on this listener");await er(e,r,new URL(e.url??"/","http://runtime.local"),s)}catch(a){if(!(a instanceof C))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"}}))}}i(Mt,"serveRuntimeSignIn");function $t(){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:de(e),key:de(r)}}i($t,"tcpTls");function H(e){e.setHeader(Z,q()),e.setHeader(Q,ge)}i(H,"advertiseRuntime");function z(e){e.setHeader("Access-Control-Allow-Origin","*"),e.setHeader("Access-Control-Expose-Headers",`${Z}, ${Q}`)}i(z,"exposeRuntimeHeaders");function Jt(e,r){return(e.method??"GET").toUpperCase()!=="OPTIONS"?!1:(H(r),r.writeHead(204,{"Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":`${Z}, ${Q}`,"Access-Control-Allow-Headers":`authorization, content-type, ${fe.toLowerCase()}, ${he.toLowerCase()}`,"Access-Control-Allow-Methods":"GET, POST, PATCH, PUT, DELETE, OPTIONS","Access-Control-Max-Age":"600"}),r.end(),!0)}i(Jt,"answerPreflight");function oe(e,r=!1){H(e),r&&z(e),e.writeHead(401,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{...M,origin:"runtime"}}))}i(oe,"writeUnauthorized");function Wt(e){H(e),z(e),e.writeHead(401,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{...$,origin:"runtime"}}))}i(Wt,"writePersonBearerRefused");const jt={"/v1/runtime/vendor-status":{method:"GET",purpose:"vendor_status"},"/v1/runtime/vendor-account-remove":{method:"POST",purpose:"vendor_account_remove"}};async function Vt(e,r){if(!I())return!1;const s=new URL(e.url??"/","http://runtime.local").pathname,a=jt[s];if(a===void 0||e.method!==a.method)return!1;const u=i((d,g)=>{H(r),z(r),r.writeHead(d,{"content-type":"application/json; charset=utf-8"}),r.end(JSON.stringify(g))},"answer");try{const d=Re();if(d===null)throw new C(401,$.code,$.message);const g=e.headers.authorization,f=g?.startsWith("Bearer ")?await d.verifyPurpose(g.slice(7),a.purpose):null;if(f===null)throw new C(401,"unauthorized","invalid directory token");const S=a.purpose==="vendor_status"?void 0:await Gt(e);u(200,await G(f,async()=>a.purpose==="vendor_status"?ir():await or(S)))}catch(d){const{status:g,body:f}=sr(d);u(g,f)}return!0}i(Vt,"serveCloudVendorRoute");async function Gt(e){const r=[];let s=0;for await(const a of e){if(s+=a.length,s>ar)throw new C(400,"invalid_request","request body too large");r.push(a)}if(s!==0)try{return JSON.parse(Buffer.concat(r).toString("utf8"))}catch{throw new C(400,"invalid_request","invalid JSON body")}}i(Gt,"readVendorBody");function ie(e){H(e),e.writeHead(503,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{code:"runtime_starting",message:"runtime is not ready",type:"server_error",origin:"runtime",retryable:!0}}))}i(ie,"writeRuntimeStarting");function Yt(e,r){e.writeHead(503,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{code:"startup_blocked",message:r,origin:"runtime"}}))}i(Yt,"writeStartupBlocked");function He(e,r,s){return new Promise(a=>{for(const f of r)f.destroy();if(s===void 0){try{e.closeAllConnections()}catch{}e.close(()=>a());return}const u=[];e.close(()=>{for(const f of u)clearTimeout(f);a()});const d=setInterval(()=>e.closeIdleConnections(),250),g=setTimeout(()=>e.closeAllConnections(),s);u.push(d,g),e.closeIdleConnections()})}i(He,"closeServer");function Jo(e={}){let r=null;const s=It(()=>r),a=new ve().registerAll(we).registerAll(Se).registerAll(Ee).registerAll(be),u=i((t,n)=>{const c=Er()?.startupBlock()??null;return c===null||t==="GET"&&(n==="/healthz"||n==="/v1/status"||n==="/v1/ready")||t==="POST"&&(n==="/v1/daemon/migrate"||n==="/v1/daemon/admit")||c.phase==="recovering"&&a.match(t,n)!==null?null:c},"startupBlockFor"),d=e.socketPath??Ge(),g=new Set([process.getuid?.()??0,...Ae("user").runtime?.person_uids??[]]),f=i((t,n,c)=>{H(n);const p=i(m=>Array.isArray(m)?m[0]:m,"first"),N=p(t.headers[fe.toLowerCase()]),h=je(N,q())??Ve(p(t.headers[he.toLowerCase()]),ge,{legacyMinimum:N,runtimeVersion:q()});if(h!==null){n.writeHead(h.status,{"content-type":"application/json; charset=utf-8"}),n.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 T=i(m=>{const E=J(t);A({event:"api.request.failed",level:"error",...E?.class==="broker"?{node_id:E.node}:{},error:m instanceof Error?m:new Error(String(m))});try{n.headersSent||n.writeHead(500,{"content-type":"application/json; charset=utf-8"}),n.end(JSON.stringify({error:{code:"internal",message:"internal error",origin:"runtime"}}))}catch{}},"internalFailure");let k;try{k=new URL(t.url??"/","http://127.0.0.1")}catch{try{n.writeHead(400,{"content-type":"application/json; charset=utf-8"}),n.end(JSON.stringify({error:{code:"invalid_request",message:"request URL is invalid",origin:"runtime"}}))}catch{}return}try{const m=u((t.method??"GET").toUpperCase(),k.pathname);if(m!==null){Yt(n,m.message);return}const E=J(t)??{class:"person"},o=Pe(E),l=i(()=>s.handle(t,n,c,E),"handled");(o===void 0?l():G(o,i(async()=>{ee()||await re(o),await l()},"handledAsPerson"))).catch(T)}catch(m){T(m)}},"onRequest"),S=i(async(t,n,c)=>{const p=J(t);return p===void 0||ye(p)||await _e(p,"either",c)?!0:(y(n,404,"Not Found","node_not_found",`no node ${c}`),!1)},"authorizeAttachUpgrade"),O=new Set,x=i(t=>{O.add(t),t.once("close",()=>O.delete(t)),t.on("error",()=>{})},"trackUpgrade"),w=i((t,n,c)=>{try{const p=new URL(t.url??"/","http://127.0.0.1"),N=u((t.method??"GET").toUpperCase(),p.pathname);if(N!==null){y(n,503,"Service Unavailable","startup_blocked",N.message);return}const h=Ht(t.method??"GET",p.pathname);if(h===null){n.destroy();return}const T=(()=>{const m=J(t);return m===void 0?void 0:Pe(m)})(),k=i(()=>S(t,n,h).then(m=>m?Rr(t,n,c,h,async E=>{const o=J(t);return o===void 0||ye(o)||await _e(o,E,h)}):void 0),"attach");(T===void 0?k():G(T,async()=>{ee()||await re(T),await k()})).catch(()=>{try{n.destroy()}catch{}})}catch{try{n.destroy()}catch{}}},"onUpgrade"),ze=i(t=>{t.on("error",n=>{A({event:"api.server.failed",level:"error",error:n})})},"bindErrorHandler"),Le=i(async(t,n)=>{V(t);try{const c=await Ce(t,g);if(j(t),c==="unauthorized"){A({event:"api.principal.denied",level:"warn",fields:{method:t.method}}),oe(n);return}if(c==="runtime_starting"){ie(n);return}B.set(t,c),Ue(t,c),f(t,n,c.class==="app"?c.scopes:null)}catch(c){A({event:"api.principal.failed",level:"error",error:c instanceof Error?c:new Error(String(c))}),ie(n)}},"onSocketRequest"),D=pe((t,n)=>{Le(t,n).catch(c=>A({event:"api.principal.failed",level:"error",error:c instanceof Error?c:new Error(String(c))}))}),Be=i(async(t,n,c)=>{V(t);try{const p=await Ce(t,g);if(j(t),p==="unauthorized"||p==="runtime_starting"){p==="unauthorized"&&A({event:"api.principal.denied",level:"warn",fields:{method:t.method}}),y(n,p==="unauthorized"?401:503,"Unauthorized",p,"socket principal unavailable");return}if(p.class!=="person"&&p.class!=="broker"){y(n,403,"Forbidden",L.code,L.message);return}B.set(t,p),w(t,n,c)}catch(p){A({event:"api.principal.failed",level:"error",error:p instanceof Error?p:new Error(String(p))}),y(n,503,"Service Unavailable","runtime_starting","socket principal unavailable")}},"onSocketUpgrade");D.on("upgrade",(t,n,c)=>{x(n),Be(t,n,c).catch(p=>A({event:"api.principal.failed",level:"error",error:p instanceof Error?p:new Error(String(p))}))}),Te((t,n,c)=>{B.set(t,c),f(t,n,null)});let se=!1,ae,le;const xe=new Promise((t,n)=>{ae=t,le=n});D.once("listening",()=>{se=!0,ae()}),D.on("error",t=>{A({event:"api.server.failed",level:"error",error:t}),se||le(t)});try{X(d)&&me(d)}catch{}D.listen(d,()=>{try{We(d,process.platform==="linux"&&X("/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,ce=Promise.resolve();const W=e.tcp??gr()??Ae("user").api.tcp;if(W!==void 0&&W!==""){const t=zt(W);if(t===null)A({event:"api.tcp.invalid",level:"error",error:new Error(`invalid CRTRD_TCP/--tcp spec: ${W}`)});else{I()&&K();const n=I()?tr():null,c=e.token??hr()??mr("user"),p=Bt(c),N=i(async(o,l)=>{if(V(o),Ke(o)){await Xe(o,l);return}if(Jt(o,l))return;if(I()&&rr(new URL(o.url??"/","http://runtime.local").pathname)){await Mt(o,l);return}if(await Vt(o,l))return;if(n!==null&&nr(new URL(o.url??"/","http://runtime.local").pathname)){await n(o,l);return}const v={},R=await Ne(o,p,v);if(j(o),R==="runtime_starting"){z(l),ie(l);return}if(R==="person_bearer"){Wt(l);return}if(R==="unauthorized"){A({event:"api.principal.denied",level:"warn",fields:{method:o.method,listener:"tcp",path:new URL(o.url??"/","http://runtime.local").pathname,reason:v.reason??"unknown"}}),oe(l,!0);return}if("call"in R){z(l);const F=R.call.sub;await G(F,async()=>{ee()||await re(F),await Ft()(o,l,R.call)});return}B.set(o,R.principal),Ue(o,R.principal),z(l),f(o,l,R.ceiling)},"tcpOnRequest"),h=i(async(o,l,v)=>{V(o);const R=vr(o);if(R!==null){const _=await Ar(o,l,v,R);_!==null&&y(l,_.status,_.text,_.code,_.message);return}const F=wr(o);if(F!==null){const _=_r(o,l,v,F);_!==null&&y(l,_.status,_.text,_.code,_.message);return}const P=await Ne(o,p);if(j(o),P==="runtime_starting"){y(l,503,"Service Unavailable","runtime_starting","grant sync is not ready");return}if(P==="person_bearer"){y(l,401,"Unauthorized",$.code,$.message);return}if(P==="unauthorized"){y(l,401,"Unauthorized",M.code,M.message);return}if("call"in P){y(l,403,"Forbidden",L.code,L.message);return}if(P.ceiling!==null||P.principal.class==="anonymous"||P.principal.class==="import"){y(l,403,"Forbidden",L.code,L.message);return}B.set(o,P.principal),w(o,l,v)},"tcpOnUpgrade"),T=i(o=>{A({event:"api.principal.failed",level:"error",error:o instanceof Error?o:new Error(String(o))})},"failed"),k=i((o,l)=>{N(o,l).catch(v=>{T(v),l.headersSent?l.destroy():oe(l,!0)})},"listener"),m=$t();b=m===null?pe(k):Je(m,k),b.on("upgrade",(o,l,v)=>{x(l),h(o,l,v).catch(R=>{T(R),y(l,401,"Unauthorized",M.code,M.message)})}),ze(b),b.once("listening",()=>{const o=b?.address();if(o!==null&&typeof o=="object"){const{address:l,port:v}=o;r=Lt(l,v),l!=="0.0.0.0"&&l!=="::"&&yr(r)}});const E=b;ce=new Promise(o=>{E.once("listening",o),E.once("error",()=>o())}),b.listen(t.port,t.host)}}let ue=!1;const De=i(async(t={})=>{if(!ue){ue=!0,Te(null),Or.close(),await Promise.all([He(D,O,t.graceMs),b!==void 0?He(b,O,t.graceMs):Promise.resolve()]);try{X(d)&&me(d)}catch{}}},"close");return{ready:xe.then(()=>ce),tcpAddress:i(()=>r,"tcpAddress"),close:De}}i(Jo,"createApiServer");export{It as buildRouter,He as closeServer,Jo as createApiServer,J as socketPrincipal};
1
+ var Fe=Object.defineProperty;var o=(e,r)=>Fe(e,"name",{value:r,configurable:!0});import{markAuthenticated as j,markReceived as V}from"../../core/step-timings.js";import{IMPORT_TOKEN_PREFIX as Me,importPrincipalFor as $e}from"./import-auth.js";import{createServer as pe}from"node:http";import{createServer as Je}from"node:https";import{chmodSync as We,existsSync as X,readFileSync as de,unlinkSync as me}from"node:fs";import{MINIMUM_RUNTIME_VERSION_HEADER as fe,RUNTIME_VERSION_HEADER as Z,minimumRuntimeRefusal as je}from"../../api/runtime-version.js";import{CONTRACT_HEADER as Q,CONTRACT_LEVEL as ge,REQUIRED_CONTRACT_HEADER as he,contractRefusal as Ve}from"../../api/contract.js";import{crtrVersion as q}from"../../shared/crtr-version.js";import{apiSocketPath as Ge}from"../../core/canvas/paths.js";import{resolveNodeToken as Ye}from"../../core/canvas/node-tokens.js";import{isCloudRole as I,runAsPerson as G}from"../../core/canvas/person.js";import{isCanvasRequest as Ke,serveCanvas as Xe}from"./canvas-host.js";import{personBearerVerifier as Re}from"./auth/person-bearer.js";import{personHasSnapshot as ee}from"../../core/scoped-state/person-store.js";import{loadPersonSettings as re}from"../../core/scoped-state/person-rows.js";import{AppPrincipalResolver as Ze}from"./principal.js";import{createAppRequestHandler as Qe}from"./app-listener.js";import{decodeJwt as qe}from"jose";import{handleRuntimeSignIn as er,isRuntimeSignInPath as rr}from"./key-signin.js";import{RunError as C}from"../../core/runs/operations.js";import{createRepoPluginHandler as tr,isRepoPluginPath as nr}from"./repo-plugin.js";import{removeVendorAccount as or,vendorStatus as ir}from"./handlers/vendor-status.js";import{toErrorBody as sr}from"./map.js";import{CONTROL_BODY_MAX_BYTES as ar}from"../../core/llm/body-limits.js";import{grantFor as lr,hasSyncedGrants as cr}from"../../core/grants/mirror.js";import{readConfig as Ae}from"../../core/config.js";import{directoryIssuer as ur}from"../../core/directory/issuer.js";import{peerUid as pr}from"../../native/linux.js";import{findScopedApiToken as dr,getApiToken as mr,listScopedApiTokens as fr}from"../../core/secrets.js";import{emitEvent as A}from"../../core/events/emit.js";import{envCrtrdTcp as gr,envCrtrdToken as hr}from"../../shared/env.js";import{Router as ve,actsAsPerson as ye}from"./router.js";import{handleAttachUpgrade as Rr,refuseUpgrade as y}from"./bridge.js";import{handleMachineLinkUpgrade as Ar,machineLinkEnvironment as vr,setApiAddress as yr}from"../machine-link/holder.js";import{handleMachineViewUpgrade as _r,machineViewEnvironment as wr}from"../machine-link/forward.js";import{boundDaemonControl as Er}from"../control.js";import{attachRoutes as Sr,mayAttachNode as _e}from"./handlers/attach.js";import{peerRoutes as br}from"../peer/handlers.js";import{bashJobRoutes as Tr}from"./handlers/bash-jobs.js";import{nodeFileRoutes as Cr}from"./handlers/node-files.js";import{bashRoutes as kr}from"./handlers/bash.js";import{hookExecRoutes as Pr}from"./handlers/hook-exec.js";import{brokerOperationRoutes as we}from"./handlers/broker-ops.js";import{brokerSignalRoutes as Ur,brokerSignalStreams as Or}from"./handlers/broker-signals.js";import{brokerRecoveryRoutes as Ee,nodeFaultRoutes as Nr}from"./handlers/broker-recovery.js";import{canvasRoutes as Ir}from"./handlers/canvas.js";import{conversationRoutes as Hr}from"./handlers/conversations.js";import{chatInventoryRoutes as zr}from"./handlers/chat-inventory.js";import{daemonRoutes as Lr}from"./handlers/daemon.js";import{fileRoutes as Br}from"./handlers/files.js";import{focusRoutes as xr}from"./handlers/focus.js";import{analyticsRoutes as Dr}from"./handlers/analytics.js";import{memoryReadsRoutes as Fr}from"./handlers/memory-reads.js";import{memoryRoutes as Mr}from"./handlers/memory.js";import{healthRoutes as $r}from"./handlers/health.js";import{humanRequestRoutes as Jr}from"./handlers/human-requests.js";import{inboxRoutes as Wr}from"./handlers/inbox.js";import{feedbackCommentRoutes as jr}from"./handlers/feedback-comments.js";import{objectRoutes as Vr}from"./handlers/objects.js";import{shareRoutes as Gr}from"./handlers/shares.js";import{customObjectRoutes as Yr}from"./handlers/custom-objects.js";import{docRoutes as Kr}from"./handlers/docs.js";import{deliveryRoutes as Se}from"./handlers/delivery.js";import{deliveryRetryRoutes as Xr}from"./handlers/delivery-retry.js";import{packageDocRoutes as Zr}from"./handlers/package-docs.js";import{documentAccessRoutes as Qr}from"./handlers/document-access.js";import{pluginAppRoutes as qr}from"./handlers/plugin-app-token.js";import{brokerMailRoutes as be,messageRoutes as et}from"./handlers/messages.js";import{modelAuthRoutes as rt}from"./handlers/modelauth.js";import{llmRoutes as tt}from"./handlers/llm.js";import{providerRoutes as nt}from"./handlers/providers.js";import{modelConfigRoutes as ot}from"./handlers/model-config.js";import{settingsRoutes as it}from"./handlers/settings.js";import{nodeRoutes as st}from"./handlers/nodes.js";import{nodeRecordRoutes as at}from"./handlers/node-records.js";import{nodeOutcomeRoutes as lt}from"./handlers/node-outcomes.js";import{nodeEventRoutes as ct}from"./handlers/node-events.js";import{profileRoutes as ut}from"./handlers/profiles.js";import{environmentRoutes as pt}from"./handlers/environments.js";import{appEnvironmentRoutes as dt}from"./handlers/app-environments.js";import{prospectiveChatInventoryRoutes as mt}from"./handlers/prospective-chat-inventory.js";import{reportRoutes as ft}from"./handlers/reports.js";import{runRoutes as gt}from"./handlers/run-routes.js";import{reviewCommentRoutes as ht}from"./handlers/review-comments.js";import{reviewRoutes as Rt}from"./handlers/reviews.js";import{subscriptionRoutes as At}from"./handlers/subscriptions.js";import{structuredRequestRoutes as vt}from"./handlers/structured-requests.js";import{cronRoutes as yt}from"./handlers/crons.js";import{setCronRequestHandler as Te}from"../cron/run-socket.js";import{RUN_TOKEN_PREFIX as _t,cronPrincipalForRunToken as wt}from"../cron/run-token.js";import{worktreeRoutes as Et}from"./handlers/worktree.js";import{limitsRoutes as St}from"./handlers/limits.js";import{chargeRoutes as bt,spendLimitRoutes as Tt}from"./handlers/charges.js";import{executionStartRoutes as Ct}from"./handlers/execution-start.js";import{machineCredentialRoutes as kt}from"./handlers/machine-credential.js";import{machineRoutes as Pt}from"./handlers/machines.js";import{importRoutes as Ut}from"./handlers/imports.js";import{gitCredentialRoutes as Ot}from"./handlers/git-credential.js";import{feedbackRoutes as Nt}from"./handlers/feedback.js";function It(e){return new ve().registerAll($r(e)).registerAll(Lr).registerAll(Gr).registerAll(st).registerAll(at).registerAll(lt).registerAll(Xr).registerAll(ct).registerAll(Tr).registerAll(Cr).registerAll(kr).registerAll(Pr).registerAll(we).registerAll(Ur).registerAll(Se).registerAll(Ee).registerAll(Nr).registerAll(Et).registerAll(St).registerAll(bt).registerAll(Ct).registerAll(kt).registerAll(Pt).registerAll(Ut).registerAll(Ot).registerAll(Nt).registerAll(Tt).registerAll(be).registerAll(et).registerAll(ft).registerAll(gt).registerAll(vt).registerAll(Sr).registerAll(Ir).registerAll(Hr).registerAll(Dr).registerAll(Fr).registerAll(Mr).registerAll(Br).registerAll(Vr).registerAll(Yr).registerAll(Kr).registerAll(Zr).registerAll(Qr).registerAll(qr).registerAll(xr).registerAll(At).registerAll(yt).registerAll(ut).registerAll(pt).registerAll(dt).registerAll(rt).registerAll(tt).registerAll(nt).registerAll(ot).registerAll(it).registerAll(Rt).registerAll(ht).registerAll(Wr).registerAll(Jr).registerAll(zr).registerAll(mt).registerAll(jr).registerAll(br)}o(It,"buildRouter");function Ht(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(Ht,"attachNodeId");function zt(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(zt,"parseTcp");function Lt(e,r){return`${e.includes(":")?`[${e}]`:e}:${r}`}o(Lt,"formatTcpAddress");const M={code:"unauthorized",message:"missing or invalid bearer token"},L={code:"owner_only",message:"attach is owner-only; a scoped token does not reach it"},$={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"},te={class:"anonymous",app:"",node:"",run:null,uid:-1,sub:"",grant:null,client_id:null,scopes:[]},B=new WeakMap;function J(e){return B.get(e)}o(J,"socketPrincipal");async function Ce(e,r){const i=process.platform==="linux"?pr(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 te;if(a.slice(7).startsWith(ne)){const u=Oe(a.slice(7));return u!==void 0&&(i===null||r.has(i))?u.principal:"unauthorized"}return ke(a.slice(7),i)}o(Ce,"resolveSocketPrincipal");async function ke(e,r){const i=await Ye(e);if(!i||r!==null&&r!==i.uid)return"unauthorized";const a=ur();if(a&&!I()&&!await cr(a))return"runtime_starting";const u=i.grant??(await lr("app:terminal",i.sub))?.id??null;return{class:"broker",...i,grant:u}}o(ke,"brokerPrincipal");function Pe(e){if(!(e.class==="anonymous"||e.class==="import"))return e.sub!==void 0&&e.sub!==""?e.sub:void 0}o(Pe,"requestPerson");function Ue(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(Ue,"noteBrokerRequest");const ne="crtr_app_";function Oe(e){const r=e.startsWith(ne)?dr(e):void 0;return r===void 0?void 0:{principal:{class:"app",app:r.grantee,scopes:r.scopes},ceiling:r.scopes}}o(Oe,"appBearer");function Bt(e){const r=new Map;for(const i of fr("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 xt(e){try{return qe(e).act!==void 0}catch{return!1}}o(xt,"carriesAct");const Dt=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*$/;function U(e,r){return e!==void 0&&(e.reason=r),"unauthorized"}o(U,"deny");async function Ne(e,r,i){const a=e.headers.authorization;if(a===void 0&&(e.method??"GET").toUpperCase()==="GET"&&(e.url??"").split("?")[0]==="/healthz")return{principal:te,ceiling:null};if(typeof a!="string"||!a.startsWith("Bearer "))return U(i,a===void 0?"no_authorization_header":"not_a_bearer");const u=a.slice(7);if(u.startsWith("crtr_pub_"))return{principal:te,ceiling:null};if(u.startsWith(ne))return Oe(u)??U(i,"app_token_unknown");if(u.startsWith(_t)){const S=await wt(u);return S===null?U(i,"run_token_invalid_or_settled"):{principal:S,ceiling:null}}const d=r.get(u);if(d!==void 0)return d;const g=$e(u);if(g!==null)return{principal:g,ceiling:null};if(u.startsWith(Me))return U(i,"import_token_invalid");if(Dt.test(u)){if(I()&&xt(u)){const x=K();if(x===null)return"person_bearer";try{const w=await x.verifyCall(a);return w.chain[0]?.sub.startsWith("app:")?{call:w}:U(i,"call_token_presenter_not_an_app")}catch(w){return w instanceof C&&w.status===503?"runtime_starting":U(i,`call_token_${w instanceof C?w.code:"invalid"}`)}}const S=I()?Re():null;if(S===null)return"person_bearer";const O=await S.verify(u);return O===null?U(i,"person_bearer_not_verified"):{principal:{class:"person",sub:O},ceiling:null}}const f=await ke(u,null);return f==="unauthorized"?U(i,"node_token_unknown"):typeof f=="string"?f:{principal:f,ceiling:null}}o(Ne,"authorizeTcp");let Y;function K(){if(Y!==void 0)return Y;const e=process.env.CRTR_DIRECTORY_URL||void 0,r=process.env.CRTR_PUBLIC_API_URL||void 0;return Y=e===void 0||r===void 0?null:new Ze(e,r,async()=>{}),Y}o(K,"cloudCallResolver");let Ie;function Ft(){const e=K();if(e===null)throw new C(503,"runtime_starting","app calls are not configured on this listener");return Ie??=Qe(e,async()=>!0,async()=>{}),Ie}o(Ft,"cloudAppCalls");async function Mt(e,r){H(r),z(r);const i=K();try{if(i===null)throw new C(503,"runtime_starting","sign-in is not configured on this listener");await er(e,r,new URL(e.url??"/","http://runtime.local"),i)}catch(a){if(!(a instanceof C))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(Mt,"serveRuntimeSignIn");function $t(){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:de(e),key:de(r)}}o($t,"tcpTls");function H(e){e.setHeader(Z,q()),e.setHeader(Q,ge)}o(H,"advertiseRuntime");function z(e){e.setHeader("Access-Control-Allow-Origin","*"),e.setHeader("Access-Control-Expose-Headers",`${Z}, ${Q}`)}o(z,"exposeRuntimeHeaders");function Jt(e,r){return(e.method??"GET").toUpperCase()!=="OPTIONS"?!1:(H(r),r.writeHead(204,{"Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":`${Z}, ${Q}`,"Access-Control-Allow-Headers":`authorization, content-type, ${fe.toLowerCase()}, ${he.toLowerCase()}`,"Access-Control-Allow-Methods":"GET, POST, PATCH, PUT, DELETE, OPTIONS","Access-Control-Max-Age":"600"}),r.end(),!0)}o(Jt,"answerPreflight");function oe(e,r=!1){H(e),r&&z(e),e.writeHead(401,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{...M,origin:"runtime"}}))}o(oe,"writeUnauthorized");function Wt(e){H(e),z(e),e.writeHead(401,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{...$,origin:"runtime"}}))}o(Wt,"writePersonBearerRefused");const jt={"/v1/runtime/vendor-status":{method:"GET",purpose:"vendor_status"},"/v1/runtime/vendor-account-remove":{method:"POST",purpose:"vendor_account_remove"}};async function Vt(e,r){if(!I())return!1;const i=new URL(e.url??"/","http://runtime.local").pathname,a=jt[i];if(a===void 0||e.method!==a.method)return!1;const u=o((d,g)=>{H(r),z(r),r.writeHead(d,{"content-type":"application/json; charset=utf-8"}),r.end(JSON.stringify(g))},"answer");try{const d=Re();if(d===null)throw new C(401,$.code,$.message);const g=e.headers.authorization,f=g?.startsWith("Bearer ")?await d.verifyPurpose(g.slice(7),a.purpose):null;if(f===null)throw new C(401,"unauthorized","invalid directory token");const S=a.purpose==="vendor_status"?void 0:await Gt(e);u(200,await G(f,async()=>a.purpose==="vendor_status"?ir():await or(S)))}catch(d){const{status:g,body:f}=sr(d);u(g,f)}return!0}o(Vt,"serveCloudVendorRoute");async function Gt(e){const r=[];let i=0;for await(const a of e){if(i+=a.length,i>ar)throw new C(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 C(400,"invalid_request","invalid JSON body")}}o(Gt,"readVendorBody");function ie(e){H(e),e.writeHead(503,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{code:"runtime_starting",message:"runtime is not ready",type:"server_error",origin:"runtime",retryable:!0}}))}o(ie,"writeRuntimeStarting");function Yt(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(Yt,"writeStartupBlocked");function He(e,r,i){return new Promise(a=>{for(const f of r)f.destroy();if(i===void 0){try{e.closeAllConnections()}catch{}e.close(()=>a());return}const u=[];e.close(()=>{for(const f of u)clearTimeout(f);a()});const d=setInterval(()=>e.closeIdleConnections(),250),g=setTimeout(()=>e.closeAllConnections(),i);u.push(d,g),e.closeIdleConnections()})}o(He,"closeServer");function Jo(e={}){let r=null;const i=It(()=>r),a=new ve().registerAll(we).registerAll(Se).registerAll(Ee).registerAll(be),u=o((t,s)=>{const c=Er()?.startupBlock()??null;return c===null||t==="GET"&&(s==="/healthz"||s==="/v1/status"||s==="/v1/ready")||t==="POST"&&s==="/v1/daemon/admit"||c.phase==="recovering"&&a.match(t,s)!==null?null:c},"startupBlockFor"),d=e.socketPath??Ge(),g=new Set([process.getuid?.()??0,...Ae("user").runtime?.person_uids??[]]),f=o((t,s,c)=>{H(s);const p=o(m=>Array.isArray(m)?m[0]:m,"first"),N=p(t.headers[fe.toLowerCase()]),h=je(N,q())??Ve(p(t.headers[he.toLowerCase()]),ge,{legacyMinimum:N,runtimeVersion:q()});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 T=o(m=>{const E=J(t);A({event:"api.request.failed",level:"error",...E?.class==="broker"?{node_id:E.node}:{},error:m instanceof Error?m:new Error(String(m))});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 k;try{k=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 m=u((t.method??"GET").toUpperCase(),k.pathname);if(m!==null){Yt(s,m.message);return}const E=J(t)??{class:"person"},n=Pe(E),l=o(()=>i.handle(t,s,c,E),"handled");(n===void 0?l():G(n,o(async()=>{ee()||await re(n),await l()},"handledAsPerson"))).catch(T)}catch(m){T(m)}},"onRequest"),S=o(async(t,s,c)=>{const p=J(t);return p===void 0||ye(p)||await _e(p,"either",c)?!0:(y(s,404,"Not Found","node_not_found",`no node ${c}`),!1)},"authorizeAttachUpgrade"),O=new Set,x=o(t=>{O.add(t),t.once("close",()=>O.delete(t)),t.on("error",()=>{})},"trackUpgrade"),w=o((t,s,c)=>{try{const p=new URL(t.url??"/","http://127.0.0.1"),N=u((t.method??"GET").toUpperCase(),p.pathname);if(N!==null){y(s,503,"Service Unavailable","startup_blocked",N.message);return}const h=Ht(t.method??"GET",p.pathname);if(h===null){s.destroy();return}const T=(()=>{const m=J(t);return m===void 0?void 0:Pe(m)})(),k=o(()=>S(t,s,h).then(m=>m?Rr(t,s,c,h,async E=>{const n=J(t);return n===void 0||ye(n)||await _e(n,E,h)}):void 0),"attach");(T===void 0?k():G(T,async()=>{ee()||await re(T),await k()})).catch(()=>{try{s.destroy()}catch{}})}catch{try{s.destroy()}catch{}}},"onUpgrade"),ze=o(t=>{t.on("error",s=>{A({event:"api.server.failed",level:"error",error:s})})},"bindErrorHandler"),Le=o(async(t,s)=>{V(t);try{const c=await Ce(t,g);if(j(t),c==="unauthorized"){A({event:"api.principal.denied",level:"warn",fields:{method:t.method}}),oe(s);return}if(c==="runtime_starting"){ie(s);return}B.set(t,c),Ue(t,c),f(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))}),ie(s)}},"onSocketRequest"),D=pe((t,s)=>{Le(t,s).catch(c=>A({event:"api.principal.failed",level:"error",error:c instanceof Error?c:new Error(String(c))}))}),Be=o(async(t,s,c)=>{V(t);try{const p=await Ce(t,g);if(j(t),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),w(t,s,c)}catch(p){A({event:"api.principal.failed",level:"error",error:p instanceof Error?p:new Error(String(p))}),y(s,503,"Service Unavailable","runtime_starting","socket principal unavailable")}},"onSocketUpgrade");D.on("upgrade",(t,s,c)=>{x(s),Be(t,s,c).catch(p=>A({event:"api.principal.failed",level:"error",error:p instanceof Error?p:new Error(String(p))}))}),Te((t,s,c)=>{B.set(t,c),f(t,s,null)});let se=!1,ae,le;const xe=new Promise((t,s)=>{ae=t,le=s});D.once("listening",()=>{se=!0,ae()}),D.on("error",t=>{A({event:"api.server.failed",level:"error",error:t}),se||le(t)});try{X(d)&&me(d)}catch{}D.listen(d,()=>{try{We(d,process.platform==="linux"&&X("/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,ce=Promise.resolve();const W=e.tcp??gr()??Ae("user").api.tcp;if(W!==void 0&&W!==""){const t=zt(W);if(t===null)A({event:"api.tcp.invalid",level:"error",error:new Error(`invalid CRTRD_TCP/--tcp spec: ${W}`)});else{I()&&K();const s=I()?tr():null,c=e.token??hr()??mr("user"),p=Bt(c),N=o(async(n,l)=>{if(V(n),Ke(n)){await Xe(n,l);return}if(Jt(n,l))return;if(I()&&rr(new URL(n.url??"/","http://runtime.local").pathname)){await Mt(n,l);return}if(await Vt(n,l))return;if(s!==null&&nr(new URL(n.url??"/","http://runtime.local").pathname)){await s(n,l);return}const v={},R=await Ne(n,p,v);if(j(n),R==="runtime_starting"){z(l),ie(l);return}if(R==="person_bearer"){Wt(l);return}if(R==="unauthorized"){A({event:"api.principal.denied",level:"warn",fields:{method:n.method,listener:"tcp",path:new URL(n.url??"/","http://runtime.local").pathname,reason:v.reason??"unknown"}}),oe(l,!0);return}if("call"in R){z(l);const F=R.call.sub;await G(F,async()=>{ee()||await re(F),await Ft()(n,l,R.call)});return}B.set(n,R.principal),Ue(n,R.principal),z(l),f(n,l,R.ceiling)},"tcpOnRequest"),h=o(async(n,l,v)=>{V(n);const R=vr(n);if(R!==null){const _=await Ar(n,l,v,R);_!==null&&y(l,_.status,_.text,_.code,_.message);return}const F=wr(n);if(F!==null){const _=_r(n,l,v,F);_!==null&&y(l,_.status,_.text,_.code,_.message);return}const P=await Ne(n,p);if(j(n),P==="runtime_starting"){y(l,503,"Service Unavailable","runtime_starting","grant sync is not ready");return}if(P==="person_bearer"){y(l,401,"Unauthorized",$.code,$.message);return}if(P==="unauthorized"){y(l,401,"Unauthorized",M.code,M.message);return}if("call"in P){y(l,403,"Forbidden",L.code,L.message);return}if(P.ceiling!==null||P.principal.class==="anonymous"||P.principal.class==="import"){y(l,403,"Forbidden",L.code,L.message);return}B.set(n,P.principal),w(n,l,v)},"tcpOnUpgrade"),T=o(n=>{A({event:"api.principal.failed",level:"error",error:n instanceof Error?n:new Error(String(n))})},"failed"),k=o((n,l)=>{N(n,l).catch(v=>{T(v),l.headersSent?l.destroy():oe(l,!0)})},"listener"),m=$t();b=m===null?pe(k):Je(m,k),b.on("upgrade",(n,l,v)=>{x(l),h(n,l,v).catch(R=>{T(R),y(l,401,"Unauthorized",M.code,M.message)})}),ze(b),b.once("listening",()=>{const n=b?.address();if(n!==null&&typeof n=="object"){const{address:l,port:v}=n;r=Lt(l,v),l!=="0.0.0.0"&&l!=="::"&&yr(r)}});const E=b;ce=new Promise(n=>{E.once("listening",n),E.once("error",()=>n())}),b.listen(t.port,t.host)}}let ue=!1;const De=o(async(t={})=>{if(!ue){ue=!0,Te(null),Or.close(),await Promise.all([He(D,O,t.graceMs),b!==void 0?He(b,O,t.graceMs):Promise.resolve()]);try{X(d)&&me(d)}catch{}}},"close");return{ready:xe.then(()=>ce),tcpAddress:o(()=>r,"tcpAddress"),close:De}}o(Jo,"createApiServer");export{It as buildRouter,He as closeServer,Jo as createApiServer,J as socketPrincipal};
@@ -23,14 +23,6 @@ export interface DaemonControl {
23
23
  } | null;
24
24
  /** Admit normal work after the daemon has prepared its storage. */
25
25
  admitStartup(): Promise<DaemonAdmitDTO>;
26
- /** Plan or run the canvas import and resume normal startup when it completes. */
27
- repairMigrations(req: {
28
- dryRun: boolean;
29
- }): Promise<{
30
- result: import('../migrations/activation.js').CanvasImportResult;
31
- resumed: boolean;
32
- resumeError?: string;
33
- }>;
34
26
  }
35
27
  /** Bind this process's control surface. Called once, by `runDaemon`. */
36
28
  export declare function bindDaemonControl(control: DaemonControl): void;
@@ -1,21 +1,19 @@
1
- var lr=Object.defineProperty;var s=(e,c)=>lr(e,"name",{value:c,configurable:!0});import{applyBootSettings as cr}from"./boot-settings.js";import{startBrokerMemoryCap as dr}from"./broker-memory-cap.js";import{startPeerOutbox as pr}from"./peer/outbox.js";import{reportMachineStatus as mr}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 Pe,existsSync as E,unlinkSync as Ie,chmodSync as xe}from"node:fs";import{createServer as Y}from"node:http";import{dirname as vr}from"node:path";import{envCrtrdTcp as Te}from"../shared/env.js";import{openCanvasConversationStore as gr,serveCanvasConversationStore as yr}from"../core/canvas/sessions.js";import{installConversationStore as Sr}from"../core/conversation-store/index.js";import{pollRunObservers as _r}from"./runs/observer.js";import{randomBytes as De}from"node:crypto";import{apiSocketPath as Ce,crtrHome as br}from"../core/canvas/paths.js";import{activeAppUsers as kr}from"../core/spaces/users.js";import{ensureAppSpace as Rr,ensureUserFiles as Er}from"../core/spaces/space.js";import{LAUNCHER_SOCKET as C}from"../launcher/spec.js";import{launcherRequest as N}from"../launcher/client.js";import{installLauncherEventSink as Pr}from"./launcher-events.js";import{initializeEmptyLayout as Ir,layoutNeedsMigration as xr,socketDir as Ae}from"../core/layout.js";import{migrateLooseKeys as Tr}from"../core/layout-migrate/loose-keys.js";import{relocateProfileFolders as Dr}from"../core/profiles/relocate.js";import{getNode as Cr,getRow as Ar,listNodesForSupervision as Le,listParkedResidentsWithWakeMail as Lr,setFrozen as $e}from"../core/canvas/index.js";import{createApiServer as $r,closeServer as Ne}from"./api/server.js";import{Router as Nr}from"./api/router.js";import{healthRoutes as Mr}from"./api/handlers/health.js";import{createAppListener as Gr}from"./api/app-listener.js";import{registerBlaxelRunnerFromEnv as Or}from"../core/secrets/blaxel-register.js";import{markEnginesInProcess as Fr}from"../core/canvas/person-state.js";import{markCloudRole as Br,resolvePerson as Hr,retireLocalPerson as Ur,setPersonId as jr}from"../core/canvas/person.js";import{backfillNodeApps as Me,runPermissionsBoot as zr}from"../core/permissions/boot.js";import{startRunNotices as qr}from"./run-notices.js";import{startGrantEffects as Wr}from"./reconcilers/grant-effects.js";import{syncPackages as Kr}from"../core/packages/directory-sync.js";import{startActivationDelivery as Jr}from"../core/model-auth/activations.js";import{createGrantSync as Vr,GRANT_SYNC_INTERVAL_S as Ge}from"../core/grants/sync.js";import{sweepSandboxes as Yr}from"../core/grants/on-sync.js";import{rebuildCronExecutions as Qr}from"./cron/run-socket.js";import{hasSyncedGrants as Xr}from"../core/grants/mirror.js";import{readConfig as Oe}from"../core/config.js";import{reconcileUndeliveredTickets as Zr}from"./human/sweep.js";import{resetHandedOffDeliveries as et}from"../core/canvas/deliveries.js";import{resetHandedOffDaemonActions as rt}from"../core/canvas/daemon-actions.js";import{sweepReviews as tt}from"./review/sweep.js";import{pidfilePath as me}from"./pidfile.js";import{rendererWarning as nt}from"../core/runtime/package-health.js";import{DEFAULT_INTERVAL_MS as ot}from"./supervise-cadence.js";import{createResumeDetector as it}from"./resume-detector.js";import{setFatalFaultAnnouncer as at}from"../core/canvas/recovery.js";import{BrokerSupervisionReconciler as st}from"./reconcilers/broker-supervision.js";import{MachineOfflineReconciler as lt}from"./reconcilers/machine-offline.js";import{ControllerDeathReconciler as ct}from"./reconcilers/controller-death.js";import{NodeLifecycleReconciler as dt}from"./reconcilers/node-lifecycle/tick.js";import{NodeDeadlineReconciler as pt}from"./reconcilers/node-deadline.js";import{CronLaneReconciler as mt}from"./reconcilers/cron-lane.js";import{DeliveryLaneReconciler as ft}from"./reconcilers/delivery-lane.js";import{ActionLaneReconciler as ut}from"./reconcilers/action-lane.js";import{endLiveExecution as ht,hasObservedExit as wt,latestExecutionForNode as vt,migrateLegacyExecutionIdentities as gt}from"../core/canvas/executions.js";import{revokePriorEpochNodeTokens as yt}from"../core/canvas/node-tokens.js";import{PendingReviewSubmitReconciler as St}from"./reconcilers/pending-review-submit.js";import{StorageMaintenanceReconciler as _t}from"./reconcilers/storage-maintenance.js";import{StorageDueWorkReconciler as bt}from"./reconcilers/storage-due-work.js";import{GroupInviteExpiryReconciler as kt}from"./reconcilers/group-invite-expiry.js";import{PurgeDueWorkReconciler as Rt}from"./reconcilers/purge-due-work.js";import{assertLedgerEnv as Et}from"../core/ledger/rates.js";import{LedgerSandboxReconciler as Pt}from"./reconcilers/ledger-sandbox.js";import{LedgerStorageReconciler as It}from"./reconcilers/ledger-storage.js";import{LedgerR2Reconciler as xt}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 Dt}from"./reconcilers/bash-deadline.js";import{FaultRetryBackstopReconciler as Ct}from"./reconcilers/fault-retry-backstop.js";import{StructuredRequestReconciler as At}from"./reconcilers/structured-request-lane.js";import{RecipeImageReconciler as Lt,removeLeftoverBuildDirs as $t,subscribeImageBuilt as Nt}from"./reconcilers/recipe-image.js";import{reconcileStructuredRequestSidecars as Mt}from"./structured-requests/boot.js";import{captureLivenessSnapshot as Fe,capturePidCommand as Gt,captureTeardownSnapshot as Be,isPidAlive as Ot,isAnyPidAlive as He,killProcessTreePids as Ue}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 Ut,spawnDaemon as jt}from"./manage.js";import{reconcileAndMigrateBoot as zt}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 Kt,daemonOwnershipApplies as Jt,daemonOwnershipClaimed as Vt,releaseDaemonOwnership as ze}from"../core/canvas/daemon-owner.js";import{canvasDatabaseUrl as Yt,closeAllDbs as ue,openDb as Qt,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 M}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 ln,readBuiltinSnapshot as cn}from"../core/graph/package-publish.js";import{prewarmRecentRecipes as dn,reapStaleSpares as pn}from"../core/runtime/warm-pool.js";import{DaemonFleet as mn}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 m}from"../core/events/emit.js";import{operationIdContext as b}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 We}from"../core/scope.js";import{brokerCommandDeclaresCanvasHome as ve}from"../core/runtime/broker-ownership.js";import{brokerCommandDeclaresCanvasHome as oa}from"../core/runtime/broker-ownership.js";function ge(e){return/ --epoch (\S+) /.exec(e)?.[1]??null}s(ge,"brokerCommandEpoch");const Rn=5e3,Ke=150;async function En(e){const c=Fe();if(c===null)throw m({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=br(),p=[];for(const[i,l]of c.processes){const v=l.command;if(l.zombie||!v.includes("broker-cli.js")||!ve(v,f)||ge(v)===e)continue;const _=v.trim().split(/\s+/).at(-1)??"";_===""||_.endsWith("broker-cli.js")||p.push({pid:i,nodeId:_})}let g=0;const o=[];for(const i of p){const l=Gt(i.pid);if(l===null||!l.includes("broker-cli.js")||!ve(l,f)||ge(l)===e||l.trim().split(/\s+/).at(-1)!==i.nodeId)continue;const v=Be(i.pid,null);if(!v.reused){try{process.platform==="linux"&&E(C)?await N({operation:"stop",pid:i.pid}):process.kill(i.pid,"SIGTERM")}catch{continue}g++,o.push({pid:i.pid,snap:v})}}const w=Date.now()+Rn;for(;Date.now()<w&&o.some(i=>He(i.snap.tree.length>0?i.snap.tree:[i.pid]));)await new Promise(i=>setTimeout(i,Ke));let y=0;for(const i of o){const l=i.snap.tree.length>0?i.snap.tree:[i.pid];He(l)&&(process.platform==="linux"&&E(C)?await N({operation:"stop",pid:i.pid}):Ue(l,"SIGKILL",i.snap.identities),y++)}y>0&&await new Promise(i=>setTimeout(i,Ke));const d=Fe();if(d===null)throw m({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[i,l]of d.processes){const v=l.command;l.zombie||!v.includes("broker-cli.js")||ve(v,f)&&ge(v)!==e&&u.push(i)}if(u.length>0)throw new Error(`prior-epoch broker census could not prove termination of pid(s): ${u.join(", ")}`);m({level:"info",event:"daemon.census.completed",fields:{prior_epoch_brokers:p.length,sigtermed:g,sigkilled:y}})}s(En,"reapPriorEpochBrokers");const Pn=5e3;async function In(e){const c=Array.from(e.entries());if(c.length===0)return;for(const[o]of c){const w=(await Cr(o))?.status;(w==="active"||w==="idle")&&await $e(o,new Date().toISOString())}const f=c.map(([,o])=>({pid:o.pid,snap:Be(o.pid,null),exited:o.handle.exited}));for(const o of f)if(!o.snap.reused)try{process.platform==="linux"&&E(C)?await N({operation:"stop",pid:o.pid}):process.kill(o.pid,"SIGTERM")}catch{}const p=new Promise(o=>{setTimeout(o,Pn).unref()});await Promise.allSettled(f.map(o=>Promise.race([o.exited.then(()=>{}),p])));const g=[];for(const o of f)Ot(o.pid)&&(process.platform==="linux"&&E(C)?await N({operation:"stop",pid:o.pid}):Ue(o.snap.tree.length>0?o.snap.tree:[o.pid],"SIGKILL",o.snap.identities),g.push(o));await Promise.all(g.map(o=>o.exited));for(const[o]of c)await ht(o,{reason:"daemon-teardown"});m({level:"info",event:"daemon.fleet_teardown.completed",fields:{brokers:f.length,sigkilled:g.length}})}s(In,"teardownFleet");function Q(...e){Pe(vr(me()),{recursive:!0}),ur(me(),[process.pid,...e].join(`
2
- `),"utf8")}s(Q,"writePidfile");function Je(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}s(Je,"isMissingPathError");function Ve(e){const c=me();let f;try{f=hr(c,"utf8")}catch(p){if(Je(p))return;throw p}if(f.split(`
3
- `,1)[0].trim()!==String(e))throw new Error(`daemon readiness mirror does not name this invocation (expected pid ${e})`);try{wr(c)}catch(p){if(Je(p))return;throw p}}s(Ve,"removeOwnedPidfileMirror");const xn={acceptsDetachedWork:s(()=>!0,"acceptsDetachedWork"),registerDetached:s(e=>{e.catch(()=>{})},"registerDetached")},X=new st;at(e=>X.handleFatalFault(e,!1));const Tn=new ct,Dn=new lt,Ye=new dt,Cn=new pt,An=new mt,Ln=new ft,$n=new ut,Nn=new St,Mn=new _t,Gn=new bt,On=new Rt,Fn=new kt,Bn=new Pt,Hn=new It,Un=new xt,jn=new Tt,zn=new Dt,qn=new Ct,Wn=new At;$t();const Kn=new Lt;async function Jn(e=Date.now(),c=xn){const f=je(),p=await X.runFleetPreamble(f);let g,o,w;try{o=await fe();const d=(await Le()).filter(i=>!o.has(i.node_id));g=d.filter(i=>i.status==="active"||i.status==="idle"),w=d.filter(i=>i.status==="done"||i.status==="canceled"||i.status==="dead");const u=new Set(w.map(i=>i.node_id));w.push(...(await Lr()).filter(i=>!u.has(i.node_id)&&!o.has(i.node_id)))}catch(d){m({level:"error",event:"canvas.node_list.failed",error:d});return}await X.run(e,{rows:g,fleet:f,lifecycle:c,held:o}),await Tn.run(e,{rows:g,held:o}),await Dn.run(e);const y=await Ye.run(e,{rows:[...g,...w],fleet:f});await Cn.run(e,o),await Wn.run(e,o),await Kn.run(e,{lifecycle:c}),await An.run(e,{lifecycle:c,held:o}),await Ln.run(e,{lifecycle:c}),await $n.run(e,{lifecycle:c}),await Nn.run(e,{lifecycle:c}),await Mn.run(e,{lifecycle:c,fleet:f,held:o}),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}),Un.run(e,{lifecycle:c}),jn.run(e,{lifecycle:c}),await _r(),qn.run(e,{fleet:f,lifecycle:c}),await zn.run(e,{rows:g}),X.warnIfSaturated({fleet:f,lifecycle:c,thresholds:p,frozen:y})}s(Jn,"superviseTick");async function Vn(e,c=Date.now()){if((await fe()).has(e))return;const f=await vt(e);if(f===null||!wt(f))return;const p=await Ar(e);p===null||p.kind==="human"||await Ye.runNode(c,p,je())}s(Vn,"exitedNodePass");function Z(e){return e===void 0||e==="reconcile"||e==="all"}s(Z,"roleRunsLanes");function H(e){return e===void 0||e==="api"||e==="all"}s(H,"roleServesRequests");const Yn=66e4;function Qn(e){const c=new Nr().registerAll(Mr(()=>null).filter(l=>l.pattern==="/healthz")),f=s((l,v)=>{const _=(l.url??"/").split("?")[0];if((l.method??"GET").toUpperCase()==="GET"&&_==="/healthz"){c.handle(l,v,null,{class:"person"});return}v.writeHead(404,{"content-type":"application/json; charset=utf-8"}),v.end(JSON.stringify({error:{code:"not_found",message:"this process serves only /healthz",origin:"runtime"}}))},"handler"),p=Ce();E(p)&&Ie(p);const g=Y(f),o=new Promise((l,v)=>{g.once("error",v),g.listen(p,()=>{g.off("error",v),xe(p,384),l()})});let w,y=null,d=o;const u=e.tcp??Te()??Oe("user").api.tcp;if(u!==void 0&&u!==""){const l=/^(.*):(\d+)$/.exec(u.trim());if(l===null||Number(l[2])>65535)throw new Error(`invalid reconcile probe TCP address: ${u}`);const v=Y(f);v.on("error",_=>m({event:"api.server.failed",level:"error",error:_})),d=o.then(()=>new Promise(_=>{v.once("error",()=>_()),v.listen(Number(l[2]),l[1]===""?"0.0.0.0":l[1],()=>{const P=v.address();y=`${P.address}:${P.port}`,_()})})),w=v}let i=!1;return{ready:d,tcpAddress:s(()=>y,"tcpAddress"),async close(l={}){if(!i){i=!0,await Promise.all([Ne(g,new Set,l.graceMs),w===void 0?Promise.resolve():Ne(w,new Set,l.graceMs)]);try{E(p)&&Ie(p)}catch{}}}}}s(Qn,"createProbeServer");const Xn="daemon is draining for shutdown and admits no new work";async function Zn(e){Pe(Ae(),{recursive:!0,mode:493}),process.platform==="linux"&&xe(Ae(),493);const c=Ce();if(E(c))throw new Error(`layout refusal cannot bind occupied socket: ${c}`);const f=Y((d,u)=>{if(d.method==="GET"&&d.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((d,u)=>{f.once("error",u),f.listen(c,()=>{f.off("error",u),d()})});let p;const g=e.tcp??Te();if(g){const d=/^(.*):(\d+)$/.exec(g);if(!d||Number(d[2])>65535)throw new Error(`invalid refusal TCP address: ${g}`);const u=Y(f.listeners("request")[0]);await new Promise((i,l)=>{u.once("error",l),u.listen(Number(d[2]),d[1],()=>{u.off("error",l),i()})}),p=u}Q();let o;const w=s(()=>(o??=(async()=>{f.closeAllConnections(),p?.closeAllConnections(),await Promise.all([f,p].filter(d=>d!==void 0).map(d=>new Promise((u,i)=>d.close(l=>l?i(l):u())))),Ve(process.pid),process.off("SIGINT",y),process.off("SIGTERM",y)})(),o),"cleanup"),y=s(()=>{w().then(()=>process.exit(0),d=>{process.stderr.write(`[crtrd] layout refusal cleanup failed: ${String(d)}
4
- `),process.exit(1)})},"onSignal");return process.on("SIGINT",y),process.on("SIGTERM",y),w}s(Zn,"serveLayoutRefusal");async function eo(e={}){if(e.role==="machine")return(await import("./machine-daemon.js")).runMachineDaemon();if(xr())return Zn(e);Ir();const c=s(r=>{process.stderr.write(`[crtrd] ${r}
5
- `)},"logPostgres"),f=!!process.env.CRTR_TEST_PG_URL,p=Jt(e.role);on(Z(e.role));const g=s(async()=>p?await Kt(De(16).toString("hex")):{claimed:!0,claim:{pid:process.pid,pid_identity:"",token:De(16).toString("hex")}},"claimOwnership"),{database:o,ownership:w}=e.role!==void 0||f?{database:{url:await Yt()},ownership:await g()}:await tn(async()=>({database:await Zt({log:c,startLockHeld:!0}),ownership:await g()}));if(!w.claimed){if(w.reason==="incumbent_alive")process.stderr.write(`[crtrd] already running (pid ${w.incumbentPid??"?"})
6
- `);else{const r=[w.incumbentPid!==void 0?`pid ${w.incumbentPid}`:void 0,w.verdict!==void 0?`verdict ${w.verdict}`:void 0].filter(a=>a!==void 0),t=r.length>0?` (${r.join(", ")})`:"";process.stderr.write(`[crtrd] claim lost: ${w.reason}${t}
7
- `),w.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"),(w.reason==="own_identity_indeterminate"||w.reason==="incumbent_malformed")&&(process.exitCode=1)}return async()=>{}}const y=w.claim;let d=null,u=null,i=null,l=null,v,_="";try{p&&await En(y.token);for(const n of Dr())process.stderr.write(`[crtrd] ${n}
8
- `);for(const n of await Tr())process.stderr.write(`[crtrd] ${n}
9
- `);await Qt(),await Xt(o.url,c);const r=e.role===void 0&&!await _n();let t=null;r&&(Sn({kind:"user",root:We()}),t=bn(We())),e.role===void 0&&kn(t??{profiles:[],defaults:{},settings:{},state:{},apps:{}}),await M.listen(o.url);const a=s(n=>{we(n).catch(h=>m({level:"error",event:"daemon.settings.reload_failed",error:h}))},"reloadPerson");if(v=await M.subscribe(n=>{qe().includes(n)&&a(n)},{kinds:["settings"],onListenStart:s(()=>{for(const n of qe())a(n)},"onListenStart")}),e.role!==void 0&&Br(),e.role==="all"&&Fr(),e.role!==void 0){let n;try{n=cn()}catch(R){m({level:"error",event:"daemon.packages.snapshot_failed",error:R})}const h=await he(async R=>(await Me(R),n===void 0?void 0:await ln(R,n,"release")));l=await he(async R=>await sn(R));for(const R of h?.invalid??[])process.stderr.write(`[crtrd] package file is not a document: ${R.path}: ${R.error}
10
- `)}else{d=await Hr(),d!==null&&(jr(d.id),await we(d.id));const n=await he(async h=>(await Me(h),d===null?null:await an(h)));if(n!==null){for(const h of n.conflicts)process.stderr.write(`[crtrd] plugin documents not reconciled: ${h.message}
11
- `);for(const h of n.invalid)process.stderr.write(`[crtrd] package file is not a document: ${h.path}: ${h.error}
12
- `);for(const h of n.quarantined)process.stderr.write(`[crtrd] plugin "${h.name}" has a damaged ${h.file} (${h.reason}); ${h.movedTo!==void 0?`moved to ${h.movedTo}`:"left in place and skipped"}
13
- `);for(const h of n.kinds.refused)process.stderr.write(`[crtrd] plugin "${h.plugin}" kind ${h.kind} not registered: ${h.message}
14
- `);for(const h of n.kinds.invalid)process.stderr.write(`[crtrd] plugin "${h.plugin}" declares invalid object kinds or scopes; no kinds registered and no app token: ${h.error}
15
- `)}}if(_=await qt(),Wt(_),e.role===void 0&&d!==null){if(await yn(d.id),process.platform==="darwin"){const{readConfig:n,updateConfig:h}=await import("../core/config.js");if(n("user").paths?.user_files===void 0){const{homedir:R}=await import("node:os");await h("user",Ee=>{Ee.paths??={},Ee.paths.user_files??=R()})}}u=await Ur(),u.joinedFrom!==null&&await we(u.person),await cr(),i=await zr()}if(process.platform==="linux"&&E(C)&&(Pr(),await N({operation:"users.sync",users:await kr()})),p){await yt(y.token);const n=await fn();Object.values(n).some(h=>h>0)&&process.stderr.write(`[crtrd] node files copied into rows: ${JSON.stringify(n)}
16
- `)}}catch(r){await M.close();try{if(p){const{released:t}=await ze(y);if(!t)throw new Error("daemon ownership claim was not released")}await ue()}catch(t){throw new AggregateError([r,t],"daemon startup failed and cleanup also failed")}throw r}let P=!0,ee,U=Promise.resolve(),re=!1,j,te,ne,oe,ie,A;const z=new Set;let ae=!1,ye=!1,x,I,q=!1,W,L,G,O,F,se,le,ce,de;const Qe=it();let T,S={phase:"initializing",message:"daemon startup is running the canvas import and normal services are unavailable",blockerPaths:[]},$="initial startup activation",Xe=null;function Ze(){return S.phase==="ready"?null:{phase:S.phase,message:S.message,blockerPaths:S.blockerPaths}}s(Ze,"startupBlock");function k(r){z.add(r),r.finally(()=>{z.delete(r)}).catch(()=>{})}s(k,"registerDetached");const er={acceptsDetachedWork:s(()=>P,"acceptsDetachedWork"),registerDetached:k};async function rr(){try{P=!1,nn.close(),ne?.(),ne=void 0,oe?.(),v?.(),oe=void 0,ie?.(),ie=void 0,ce?.(),ce=void 0,await M.close(),j!==void 0&&(clearInterval(j),j=void 0),te?.(),te=void 0,G!==void 0&&(clearInterval(G),G=void 0),O!==void 0&&(clearInterval(O),O=void 0),de?.(),de=void 0;let r;do r=U,await r;while(r!==U);for(;z.size>0;)await Promise.allSettled([...z]);if(A!==void 0&&(p&&await In(A),await A.exitsSettled(),A.dispose()),I!==void 0&&!q&&(q=!0,await I.close()),se?.(),se=void 0,le?.(),le=void 0,F!==void 0){const t=F;F=void 0,await t.stop()}if(L!==void 0){const t=L;L=void 0,await t.close()}if(W!==void 0){const t=W;W=void 0,await t.close()}if(ae||(Ve(process.pid),ae=!0),ae&&!ye){if(p){const{released:t}=await ze(y);if(!t)throw new Error("daemon ownership claim was not released")}ye=!0,await ue()}}finally{Ht(),process.off("SIGINT",be),process.off("SIGTERM",ke),process.off("exit",Re)}}s(rr,"cleanupAttempt");const K=1e3;let Se=!1;function tr(){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,b.fresh(()=>{m({level:"info",event:"daemon.handover.armed",fields:{pid:process.pid,grace_ms:K}})}),setTimeout(()=>{nr()},K),{graceMs:K})}s(tr,"requestHandover");async function nr(){try{await D()}catch(r){const t=r instanceof Error?r.stack??r.message:String(r);process.stderr.write(`[crtrd] handover cleanup failed:
1
+ var Qe=Object.defineProperty;var a=(e,s)=>Qe(e,"name",{value:s,configurable:!0});import{applyBootSettings as Xe}from"./boot-settings.js";import{startBrokerMemoryCap as Ze}from"./broker-memory-cap.js";import{startPeerOutbox as er}from"./peer/outbox.js";import{reportMachineStatus as rr}from"../core/peer/directory.js";import{createPeerRelay as tr}from"./peer/relay-service.js";import{writeFileSync as nr,readFileSync as or,rmSync as ir,mkdirSync as ar,existsSync as R,unlinkSync as ke,chmodSync as sr}from"node:fs";import{createServer as be}from"node:http";import{dirname as lr}from"node:path";import{envCrtrdTcp as dr}from"../shared/env.js";import{openCanvasConversationStore as cr,serveCanvasConversationStore as pr}from"../core/canvas/sessions.js";import{installConversationStore as mr}from"../core/conversation-store/index.js";import{pollRunObservers as fr}from"./runs/observer.js";import{randomBytes as Re}from"node:crypto";import{apiSocketPath as ur,crtrHome as wr}from"../core/canvas/paths.js";import{activeAppUsers as hr}from"../core/spaces/users.js";import{ensureAppSpace as vr,ensureUserFiles as gr}from"../core/spaces/space.js";import{LAUNCHER_SOCKET as I}from"../launcher/spec.js";import{launcherRequest as A}from"../launcher/client.js";import{installLauncherEventSink as Sr}from"./launcher-events.js";import{initializeEmptyLayout as _r}from"../core/layout.js";import{relocateProfileFolders as yr}from"../core/profiles/relocate.js";import{getNode as kr,getRow as br,listNodesForSupervision as Ee,listParkedResidentsWithWakeMail as Rr,setFrozen as Pe}from"../core/canvas/index.js";import{createApiServer as Er,closeServer as xe}from"./api/server.js";import{Router as Pr}from"./api/router.js";import{healthRoutes as xr}from"./api/handlers/health.js";import{createAppListener as Dr}from"./api/app-listener.js";import{registerBlaxelRunnerFromEnv as Ir}from"../core/secrets/blaxel-register.js";import{markEnginesInProcess as Tr}from"../core/canvas/person-state.js";import{markCloudRole as Cr,resolvePerson as Ar,retireLocalPerson as Lr,setPersonId as $r}from"../core/canvas/person.js";import{backfillNodeApps as De,runPermissionsBoot as Nr}from"../core/permissions/boot.js";import{startRunNotices as Mr}from"./run-notices.js";import{startGrantEffects as Or}from"./reconcilers/grant-effects.js";import{syncPackages as Gr}from"../core/packages/directory-sync.js";import{startActivationDelivery as Fr}from"../core/model-auth/activations.js";import{createGrantSync as Br,GRANT_SYNC_INTERVAL_S as Ie}from"../core/grants/sync.js";import{sweepSandboxes as jr}from"../core/grants/on-sync.js";import{rebuildCronExecutions as Ur}from"./cron/run-socket.js";import{hasSyncedGrants as Hr}from"../core/grants/mirror.js";import{readConfig as Te}from"../core/config.js";import{reconcileUndeliveredTickets as zr}from"./human/sweep.js";import{resetHandedOffDeliveries as Wr}from"../core/canvas/deliveries.js";import{resetHandedOffDaemonActions as qr}from"../core/canvas/daemon-actions.js";import{sweepReviews as Kr}from"./review/sweep.js";import{pidfilePath as le}from"./pidfile.js";import{rendererWarning as Vr}from"../core/runtime/package-health.js";import{DEFAULT_INTERVAL_MS as Yr}from"./supervise-cadence.js";import{createResumeDetector as Jr}from"./resume-detector.js";import{setFatalFaultAnnouncer as Qr}from"../core/canvas/recovery.js";import{BrokerSupervisionReconciler as Xr}from"./reconcilers/broker-supervision.js";import{MachineOfflineReconciler as Zr}from"./reconcilers/machine-offline.js";import{ControllerDeathReconciler as et}from"./reconcilers/controller-death.js";import{NodeLifecycleReconciler as rt}from"./reconcilers/node-lifecycle/tick.js";import{NodeDeadlineReconciler as tt}from"./reconcilers/node-deadline.js";import{CronLaneReconciler as nt}from"./reconcilers/cron-lane.js";import{DeliveryLaneReconciler as ot}from"./reconcilers/delivery-lane.js";import{ActionLaneReconciler as it}from"./reconcilers/action-lane.js";import{endLiveExecution as at,hasObservedExit as st,latestExecutionForNode as lt}from"../core/canvas/executions.js";import{revokePriorEpochNodeTokens as dt}from"../core/canvas/node-tokens.js";import{PendingReviewSubmitReconciler as ct}from"./reconcilers/pending-review-submit.js";import{StorageMaintenanceReconciler as pt}from"./reconcilers/storage-maintenance.js";import{StorageDueWorkReconciler as mt}from"./reconcilers/storage-due-work.js";import{GroupInviteExpiryReconciler as ft}from"./reconcilers/group-invite-expiry.js";import{PurgeDueWorkReconciler as ut}from"./reconcilers/purge-due-work.js";import{assertLedgerEnv as wt}from"../core/ledger/rates.js";import{LedgerSandboxReconciler as ht}from"./reconcilers/ledger-sandbox.js";import{LedgerStorageReconciler as vt}from"./reconcilers/ledger-storage.js";import{LedgerR2Reconciler as gt}from"./reconcilers/ledger-r2.js";import{importedNodesHeld as de}from"./reconcilers/live-obligation.js";import{ImportLaneReconciler as St}from"./reconcilers/import-lane.js";import{BashDeadlineReconciler as _t}from"./reconcilers/bash-deadline.js";import{FaultRetryBackstopReconciler as yt}from"./reconcilers/fault-retry-backstop.js";import{StructuredRequestReconciler as kt}from"./reconcilers/structured-request-lane.js";import{RecipeImageReconciler as bt,removeLeftoverBuildDirs as Rt,subscribeImageBuilt as Et}from"./reconcilers/recipe-image.js";import{reconcileStructuredRequestSidecars as Pt}from"./structured-requests/boot.js";import{captureLivenessSnapshot as Ce,capturePidCommand as xt,captureTeardownSnapshot as Ae,isPidAlive as Dt,isAnyPidAlive as Le,killProcessTreePids as $e}from"../core/canvas/pid.js";import{bindFleet as It,boundFleet as Ne}from"../core/runtime/fleet.js";import{bindDaemonControl as Tt,clearDaemonControl as Ct}from"./control.js";import{execDaemon as At,spawnDaemon as Lt}from"./manage.js";import{reconcileBootLiveness as $t}from"../core/canvas/boot.js";import{resolveInstallId as Nt}from"../core/canvas/install-id.js";import{setInstallId as Mt}from"../core/runtime/nodes.js";import{claimDaemonOwnership as Ot,daemonOwnershipApplies as Gt,daemonOwnershipClaimed as Ft,releaseDaemonOwnership as Me}from"../core/canvas/daemon-owner.js";import{canvasDatabaseUrl as Bt,closeAllDbs as ce,openDb as jt,withCanvasWrite as pe}from"../core/canvas/db.js";import{importSqliteCanvasIfPresent as Ut}from"../core/canvas/import-sqlite.js";import{ensurePostgres as Ht,ensurePostgresHealthy as zt,stopPostgres as Wt,withPostgresStartLock as qt}from"./postgres/index.js";import{brokerSignalBus as L}from"./broker-signals/bus.js";import{brokerSignalStreams as Kt}from"./api/handlers/broker-signals.js";import{setRequestsStartRunObservers as Vt}from"./api/handlers/broker-ops.js";import{reconcilePackages as Yt}from"../core/graph/package-reconcile.js";import{migrateAppInstalls as Jt}from"../core/scoped-state/migrate-app-installs.js";import{publish as Qt,readBuiltinSnapshot as Xt}from"../core/graph/package-publish.js";import{prewarmRecentRecipes as Zt,reapStaleSpares as en}from"../core/runtime/warm-pool.js";import{DaemonFleet as rn}from"./fleet.js";import{copyNodeFilesToRows as tn}from"../core/runtime/first-boot-rows.js";import{emitEvent as d}from"../core/events/emit.js";import{operationIdContext as y}from"../core/events/operation-id.js";import{bindDaemonEventSource as nn}from"../core/events/source.js";import{heldPersons as Oe,installPreludeSnapshot as on}from"../core/scoped-state/person-store.js";import{loadPersonSettings as V}from"../core/scoped-state/person-rows.js";import{brokerCommandDeclaresCanvasHome as me}from"../core/runtime/broker-ownership.js";import{brokerCommandDeclaresCanvasHome as $i}from"../core/runtime/broker-ownership.js";function fe(e){return/ --epoch (\S+) /.exec(e)?.[1]??null}a(fe,"brokerCommandEpoch");const an=5e3,Ge=150;async function sn(e){const s=Ce();if(s===null)throw d({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 m=wr(),c=[];for(const[i,l]of s.processes){const u=l.command;if(l.zombie||!u.includes("broker-cli.js")||!me(u,m)||fe(u)===e)continue;const _=u.trim().split(/\s+/).at(-1)??"";_===""||_.endsWith("broker-cli.js")||c.push({pid:i,nodeId:_})}let h=0;const o=[];for(const i of c){const l=xt(i.pid);if(l===null||!l.includes("broker-cli.js")||!me(l,m)||fe(l)===e||l.trim().split(/\s+/).at(-1)!==i.nodeId)continue;const u=Ae(i.pid,null);if(!u.reused){try{process.platform==="linux"&&R(I)?await A({operation:"stop",pid:i.pid}):process.kill(i.pid,"SIGTERM")}catch{continue}h++,o.push({pid:i.pid,snap:u})}}const f=Date.now()+an;for(;Date.now()<f&&o.some(i=>Le(i.snap.tree.length>0?i.snap.tree:[i.pid]));)await new Promise(i=>setTimeout(i,Ge));let S=0;for(const i of o){const l=i.snap.tree.length>0?i.snap.tree:[i.pid];Le(l)&&(process.platform==="linux"&&R(I)?await A({operation:"stop",pid:i.pid}):$e(l,"SIGKILL",i.snap.identities),S++)}S>0&&await new Promise(i=>setTimeout(i,Ge));const w=Ce();if(w===null)throw d({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 v=[];for(const[i,l]of w.processes){const u=l.command;l.zombie||!u.includes("broker-cli.js")||me(u,m)&&fe(u)!==e&&v.push(i)}if(v.length>0)throw new Error(`prior-epoch broker census could not prove termination of pid(s): ${v.join(", ")}`);d({level:"info",event:"daemon.census.completed",fields:{prior_epoch_brokers:c.length,sigtermed:h,sigkilled:S}})}a(sn,"reapPriorEpochBrokers");const ln=5e3;async function dn(e){const s=Array.from(e.entries());if(s.length===0)return;for(const[o]of s){const f=(await kr(o))?.status;(f==="active"||f==="idle")&&await Pe(o,new Date().toISOString())}const m=s.map(([,o])=>({pid:o.pid,snap:Ae(o.pid,null),exited:o.handle.exited}));for(const o of m)if(!o.snap.reused)try{process.platform==="linux"&&R(I)?await A({operation:"stop",pid:o.pid}):process.kill(o.pid,"SIGTERM")}catch{}const c=new Promise(o=>{setTimeout(o,ln).unref()});await Promise.allSettled(m.map(o=>Promise.race([o.exited.then(()=>{}),c])));const h=[];for(const o of m)Dt(o.pid)&&(process.platform==="linux"&&R(I)?await A({operation:"stop",pid:o.pid}):$e(o.snap.tree.length>0?o.snap.tree:[o.pid],"SIGKILL",o.snap.identities),h.push(o));await Promise.all(h.map(o=>o.exited));for(const[o]of s)await at(o,{reason:"daemon-teardown"});d({level:"info",event:"daemon.fleet_teardown.completed",fields:{brokers:m.length,sigkilled:h.length}})}a(dn,"teardownFleet");function ue(...e){ar(lr(le()),{recursive:!0}),nr(le(),[process.pid,...e].join(`
2
+ `),"utf8")}a(ue,"writePidfile");function Fe(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}a(Fe,"isMissingPathError");function cn(e){const s=le();let m;try{m=or(s,"utf8")}catch(c){if(Fe(c))return;throw c}if(m.split(`
3
+ `,1)[0].trim()!==String(e))throw new Error(`daemon readiness mirror does not name this invocation (expected pid ${e})`);try{ir(s)}catch(c){if(Fe(c))return;throw c}}a(cn,"removeOwnedPidfileMirror");const pn={acceptsDetachedWork:a(()=>!0,"acceptsDetachedWork"),registerDetached:a(e=>{e.catch(()=>{})},"registerDetached")},Y=new Xr;Qr(e=>Y.handleFatalFault(e,!1));const mn=new et,fn=new Zr,Be=new rt,un=new tt,wn=new nt,hn=new ot,vn=new it,gn=new ct,Sn=new pt,_n=new mt,yn=new ut,kn=new ft,bn=new ht,Rn=new vt,En=new gt,Pn=new St,xn=new _t,Dn=new yt,In=new kt;Rt();const Tn=new bt;async function Cn(e=Date.now(),s=pn){const m=Ne(),c=await Y.runFleetPreamble(m);let h,o,f;try{o=await de();const w=(await Ee()).filter(i=>!o.has(i.node_id));h=w.filter(i=>i.status==="active"||i.status==="idle"),f=w.filter(i=>i.status==="done"||i.status==="canceled"||i.status==="dead");const v=new Set(f.map(i=>i.node_id));f.push(...(await Rr()).filter(i=>!v.has(i.node_id)&&!o.has(i.node_id)))}catch(w){d({level:"error",event:"canvas.node_list.failed",error:w});return}await Y.run(e,{rows:h,fleet:m,lifecycle:s,held:o}),await mn.run(e,{rows:h,held:o}),await fn.run(e);const S=await Be.run(e,{rows:[...h,...f],fleet:m});await un.run(e,o),await In.run(e,o),await Tn.run(e,{lifecycle:s}),await wn.run(e,{lifecycle:s,held:o}),await hn.run(e,{lifecycle:s}),await vn.run(e,{lifecycle:s}),await gn.run(e,{lifecycle:s}),await Sn.run(e,{lifecycle:s,fleet:m,held:o}),_n.run(e,{lifecycle:s}),yn.run(e,{lifecycle:s}),kn.run(e,{lifecycle:s}),bn.run(e,{lifecycle:s}),Rn.run(e,{lifecycle:s}),En.run(e,{lifecycle:s}),Pn.run(e,{lifecycle:s}),await fr(),Dn.run(e,{fleet:m,lifecycle:s}),await xn.run(e,{rows:h}),Y.warnIfSaturated({fleet:m,lifecycle:s,thresholds:c,frozen:S})}a(Cn,"superviseTick");async function An(e,s=Date.now()){if((await de()).has(e))return;const m=await lt(e);if(m===null||!st(m))return;const c=await br(e);c===null||c.kind==="human"||await Be.runNode(s,c,Ne())}a(An,"exitedNodePass");function J(e){return e===void 0||e==="reconcile"||e==="all"}a(J,"roleRunsLanes");function F(e){return e===void 0||e==="api"||e==="all"}a(F,"roleServesRequests");const Ln=66e4;function $n(e){const s=new Pr().registerAll(xr(()=>null).filter(l=>l.pattern==="/healthz")),m=a((l,u)=>{const _=(l.url??"/").split("?")[0];if((l.method??"GET").toUpperCase()==="GET"&&_==="/healthz"){s.handle(l,u,null,{class:"person"});return}u.writeHead(404,{"content-type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:{code:"not_found",message:"this process serves only /healthz",origin:"runtime"}}))},"handler"),c=ur();R(c)&&ke(c);const h=be(m),o=new Promise((l,u)=>{h.once("error",u),h.listen(c,()=>{h.off("error",u),sr(c,384),l()})});let f,S=null,w=o;const v=e.tcp??dr()??Te("user").api.tcp;if(v!==void 0&&v!==""){const l=/^(.*):(\d+)$/.exec(v.trim());if(l===null||Number(l[2])>65535)throw new Error(`invalid reconcile probe TCP address: ${v}`);const u=be(m);u.on("error",_=>d({event:"api.server.failed",level:"error",error:_})),w=o.then(()=>new Promise(_=>{u.once("error",()=>_()),u.listen(Number(l[2]),l[1]===""?"0.0.0.0":l[1],()=>{const b=u.address();S=`${b.address}:${b.port}`,_()})})),f=u}let i=!1;return{ready:w,tcpAddress:a(()=>S,"tcpAddress"),async close(l={}){if(!i){i=!0,await Promise.all([xe(h,new Set,l.graceMs),f===void 0?Promise.resolve():xe(f,new Set,l.graceMs)]);try{R(c)&&ke(c)}catch{}}}}}a($n,"createProbeServer");const Nn="daemon is draining for shutdown and admits no new work";async function Mn(e={}){if(e.role==="machine")return(await import("./machine-daemon.js")).runMachineDaemon();_r();const s=a(n=>{process.stderr.write(`[crtrd] ${n}
4
+ `)},"logPostgres"),m=!!process.env.CRTR_TEST_PG_URL,c=Gt(e.role);Vt(J(e.role));const h=a(async()=>c?await Ot(Re(16).toString("hex")):{claimed:!0,claim:{pid:process.pid,pid_identity:"",token:Re(16).toString("hex")}},"claimOwnership"),{database:o,ownership:f}=e.role!==void 0||m?{database:{url:await Bt()},ownership:await h()}:await qt(async()=>({database:await Ht({log:s,startLockHeld:!0}),ownership:await h()}));if(!f.claimed){if(f.reason==="incumbent_alive")process.stderr.write(`[crtrd] already running (pid ${f.incumbentPid??"?"})
5
+ `);else{const n=[f.incumbentPid!==void 0?`pid ${f.incumbentPid}`:void 0,f.verdict!==void 0?`verdict ${f.verdict}`:void 0].filter(t=>t!==void 0),r=n.length>0?` (${n.join(", ")})`:"";process.stderr.write(`[crtrd] claim lost: ${f.reason}${r}
6
+ `),f.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"),(f.reason==="own_identity_indeterminate"||f.reason==="incumbent_malformed")&&(process.exitCode=1)}return async()=>{}}const S=f.claim;let w=null,v=null,i=null,l=null,u,_="";try{c&&await sn(S.token);for(const r of yr())process.stderr.write(`[crtrd] ${r}
7
+ `);await jt(),await Ut(o.url,s),e.role===void 0&&on({profiles:[],defaults:{},settings:{},state:{},apps:{}}),await L.listen(o.url);const n=a(r=>{V(r).catch(t=>d({level:"error",event:"daemon.settings.reload_failed",error:t}))},"reloadPerson");if(u=await L.subscribe(r=>{Oe().includes(r)&&n(r)},{kinds:["settings"],onListenStart:a(()=>{for(const r of Oe())n(r)},"onListenStart")}),e.role!==void 0&&Cr(),e.role==="all"&&Tr(),e.role!==void 0){let r;try{r=Xt()}catch(p){d({level:"error",event:"daemon.packages.snapshot_failed",error:p})}const t=await pe(async p=>(await De(p),r===void 0?void 0:await Qt(p,r,"release")));l=await pe(async p=>await Jt(p));for(const p of t?.invalid??[])process.stderr.write(`[crtrd] package file is not a document: ${p.path}: ${p.error}
8
+ `)}else{w=await Ar(),w!==null&&($r(w.id),await V(w.id));const r=await pe(async t=>(await De(t),w===null?null:await Yt(t)));if(r!==null){for(const t of r.conflicts)process.stderr.write(`[crtrd] plugin documents not reconciled: ${t.message}
9
+ `);for(const t of r.invalid)process.stderr.write(`[crtrd] package file is not a document: ${t.path}: ${t.error}
10
+ `);for(const t of r.quarantined)process.stderr.write(`[crtrd] plugin "${t.name}" has a damaged ${t.file} (${t.reason}); ${t.movedTo!==void 0?`moved to ${t.movedTo}`:"left in place and skipped"}
11
+ `);for(const t of r.kinds.refused)process.stderr.write(`[crtrd] plugin "${t.plugin}" kind ${t.kind} not registered: ${t.message}
12
+ `);for(const t of r.kinds.invalid)process.stderr.write(`[crtrd] plugin "${t.plugin}" declares invalid object kinds or scopes; no kinds registered and no app token: ${t.error}
13
+ `)}}if(_=await Nt(),Mt(_),e.role===void 0&&w!==null){if(await V(w.id),process.platform==="darwin"){const{readConfig:r,updateConfig:t}=await import("../core/config.js");if(r("user").paths?.user_files===void 0){const{homedir:p}=await import("node:os");await t("user",P=>{P.paths??={},P.paths.user_files??=p()})}}v=await Lr(),v.joinedFrom!==null&&await V(v.person),await Xe(),i=await Nr()}if(process.platform==="linux"&&R(I)&&(Sr(),await A({operation:"users.sync",users:await hr()})),c){await dt(S.token);const r=await tn();Object.values(r).some(t=>t>0)&&process.stderr.write(`[crtrd] node files copied into rows: ${JSON.stringify(r)}
14
+ `)}}catch(n){await L.close();try{if(c){const{released:r}=await Me(S);if(!r)throw new Error("daemon ownership claim was not released")}await ce()}catch(r){throw new AggregateError([n,r],"daemon startup failed and cleanup also failed")}throw n}let b=!0,Q,B=Promise.resolve(),X=!1,j,Z,ee,re,te,T;const U=new Set;let ne=!1,we=!1,x,E,H=!1,z,C,$,N,M,oe,ie,ae,se;const je=Jr();let D,g={phase:"initializing",message:"daemon startup is running and normal services are unavailable",blockerPaths:[]},Ue=null;function He(){return g.phase==="ready"?null:{phase:g.phase,message:g.message,blockerPaths:g.blockerPaths}}a(He,"startupBlock");function k(n){U.add(n),n.finally(()=>{U.delete(n)}).catch(()=>{})}a(k,"registerDetached");const ze={acceptsDetachedWork:a(()=>b,"acceptsDetachedWork"),registerDetached:k};async function We(){try{b=!1,Kt.close(),ee?.(),ee=void 0,re?.(),u?.(),re=void 0,te?.(),te=void 0,ae?.(),ae=void 0,await L.close(),j!==void 0&&(clearInterval(j),j=void 0),Z?.(),Z=void 0,$!==void 0&&(clearInterval($),$=void 0),N!==void 0&&(clearInterval(N),N=void 0),se?.(),se=void 0;let n;do n=B,await n;while(n!==B);for(;U.size>0;)await Promise.allSettled([...U]);if(T!==void 0&&(c&&await dn(T),await T.exitsSettled(),T.dispose()),E!==void 0&&!H&&(H=!0,await E.close()),oe?.(),oe=void 0,ie?.(),ie=void 0,M!==void 0){const r=M;M=void 0,await r.stop()}if(C!==void 0){const r=C;C=void 0,await r.close()}if(z!==void 0){const r=z;z=void 0,await r.close()}if(ne||(cn(process.pid),ne=!0),ne&&!we){if(c){const{released:r}=await Me(S);if(!r)throw new Error("daemon ownership claim was not released")}we=!0,await ce()}}finally{Ct(),process.off("SIGINT",ge),process.off("SIGTERM",Se),process.off("exit",_e)}}a(We,"cleanupAttempt");const W=1e3;let he=!1;function qe(){if(e.role!==void 0)throw new Error(`a ${e.role} daemon never hands over to a successor: its orchestrator replaces it`);return he?{graceMs:W}:(he=!0,y.fresh(()=>{d({level:"info",event:"daemon.handover.armed",fields:{pid:process.pid,grace_ms:W}})}),setTimeout(()=>{Ke()},W),{graceMs:W})}a(qe,"requestHandover");async function Ke(){try{await O()}catch(n){const r=n instanceof Error?n.stack??n.message:String(n);process.stderr.write(`[crtrd] handover cleanup failed:
15
+ ${r}
16
+ `),process.exit(1)}try{process.platform==="linux"&&R(I)&&(await A({operation:"daemon.handover"}),process.exit(0)),process.pid===1&&await At();const n=await Lt();y.fresh(()=>{d({level:"info",event:"daemon.handover.completed",fields:{predecessor_pid:process.pid,successor_pid:n.pid??n.existing_pid??null,spawned:n.started}})})}catch(n){y.fresh(()=>{d({level:"error",event:"daemon.handover.successor_failed",error:n})});const r=n instanceof Error?n.message:String(n);process.stderr.write(`[crtrd] handover successor failed to start: ${r}
17
+ `),process.exit(1)}process.exit(0)}a(Ke,"performHandover");function O(){if(x!==void 0)return x;const n=We();return x=n,n.then(()=>{x===n&&(x=void 0)},()=>{x===n&&(x=void 0)}),n}a(O,"requestCleanup");async function Ve(){g={phase:"initializing",message:Nn,blockerPaths:[]},E!==void 0&&!H&&(H=!0,await E.close({graceMs:Ln}))}a(Ve,"drainApi");async function ve(n){try{n==="SIGTERM"&&e.role==="api"&&await Ve(),await O(),await Wt({claimed:a(async()=>{try{return c&&await Ft()}finally{await ce()}},"claimed")}),process.exit(0)}catch(r){process.exitCode=1;const t=r instanceof Error?r.stack??`${r.name}: ${r.message}`:String(r);process.stderr.write(`[crtrd] ${n} cleanup failed:
17
18
  ${t}
18
- `),process.exit(1)}try{process.platform==="linux"&&E(C)&&(await N({operation:"daemon.handover"}),process.exit(0)),process.pid===1&&await Ut();const r=await jt();b.fresh(()=>{m({level:"info",event:"daemon.handover.completed",fields:{predecessor_pid:process.pid,successor_pid:r.pid??r.existing_pid??null,spawned:r.started}})})}catch(r){b.fresh(()=>{m({level:"error",event:"daemon.handover.successor_failed",error:r})});const t=r instanceof Error?r.message:String(r);process.stderr.write(`[crtrd] handover successor failed to start: ${t}
19
- `),process.exit(1)}process.exit(0)}s(nr,"performHandover");function D(){if(x!==void 0)return x;const r=rr();return x=r,r.then(()=>{x===r&&(x=void 0)},()=>{x===r&&(x=void 0)}),r}s(D,"requestCleanup");async function or(){S={phase:"initializing",message:Xn,blockerPaths:[]},I!==void 0&&!q&&(q=!0,await I.close({graceMs:Yn}))}s(or,"drainApi");async function _e(r){try{r==="SIGTERM"&&e.role==="api"&&await or(),await D(),await rn({claimed:s(async()=>{try{return p&&await Vt()}finally{await ue()}},"claimed")}),process.exit(0)}catch(t){process.exitCode=1;const a=t instanceof Error?t.stack??`${t.name}: ${t.message}`:String(t);process.stderr.write(`[crtrd] ${r} cleanup failed:
20
- ${a}
21
- `),process.exit(1)}}s(_e,"handleSignal");function be(){_e("SIGINT")}s(be,"onSigint");function ke(){_e("SIGTERM")}s(ke,"onSigterm");function Re(){D().catch(()=>{})}s(Re,"onExit");async function J(r){P&&(U=U.then(r).then(()=>{},t=>{b.fresh(()=>{m({level:"error",event:"daemon.lane_job.failed",error:t})})}))}s(J,"enqueue");async function V(){!P||re||(Qe.check()&&T&&(m({level:"info",event:"daemon.resume.detected"}),k(T().catch(()=>{}))),re=!0,await J(async()=>{if(re=!1,!!P)try{f||await en({log:c}),await Jn(Date.now(),er)}catch(r){b.fresh(()=>{m({level:"error",event:"daemon.tick.failed",error:r})})}}))}s(V,"enqueueTick");let B=null;async function ir(){if(B!==null)throw{status:500,code:"admission_failed",message:`daemon admission previously failed: ${B instanceof Error?B.message:String(B)}`};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 r=S.phase==="prepared";try{return await pe(),S={phase:"ready",message:"",blockerPaths:[]},r?{admitted:!0,already_admitted:!1,startup_phase:"ready"}:{admitted:!1,already_admitted:!0,startup_phase:"ready"}}catch(t){throw B=t,{status:500,code:"admission_failed",message:`daemon admission failed: ${t instanceof Error?t.message:String(t)}`}}}s(ir,"admitStartup");async function ar(r){if($!==null)throw{status:409,code:"migration_in_progress",message:`the canvas import is already running (${$})`};$="repair";try{const t=await gn({dryRun:r.dryRun});if(r.dryRun||t.pending||S.phase!=="blocked")return{result:t,resumed:!1};if(e.prepare)return S={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]},{result:t,resumed:!1};try{return await pe(),S={phase:"ready",message:"",blockerPaths:[]},{result:t,resumed:!0}}catch(a){const n=a instanceof Error?a.message:String(a);return setTimeout(()=>{D().catch(()=>{})},1e3),{result:t,resumed:!1,resumeError:n}}}finally{$=null}}s(ar,"repairMigrations");async function sr(){ee=e.intervalMs??ot;const r=y.token;A=new mn({epoch:r,enqueue:J}),Ft(A),S={phase:"recovering",message:"daemon startup recovery is running and normal services are unavailable",blockerPaths:[]},b.fresh(()=>{m({level:"info",event:"daemon.started",fields:{pid:process.pid,interval_ms:ee}})});const t=_;if(b.fresh(()=>{m({level:"info",event:"daemon.install_id.resolved",fields:{install_id:t}})}),b.fresh(()=>{let a;try{a=nt()}catch{return}a!==null&&m({level:"warn",event:"daemon.startup.warning",fields:{stage:"termrender",warning:a.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|all): it names the directory this deployment mints tokens against");if(e.role==="all"&&!process.env.CRTR_DATABASE_URL&&!process.env.CRTR_TEST_PG_URL)throw new Error("CRTR_DATABASE_URL must be set on --role all: it names the Postgres this process serves");if(e.role!==void 0&&Or(),!Z(e.role)){S={phase:"ready",message:"",blockerPaths:[]};return}if(await b.fresh(async()=>{await tt(),await Zr();const a=e.role!==void 0;await et(Date.now(),a),await rt(Date.now(),a)}),e.role===void 0&&await b.fresh(async()=>{const{reconcile:a,migrated:n}=await zt(gt);a.changed&&m({level:"info",event:"daemon.boot_change.reconciled",fields:{cleared_count:a.cleared.length,same_boot_proven:a.sameBootProven}}),n.length>0&&m({level:"info",event:"daemon.pid_identity.migrated",fields:{migrated_count:n.length}})}),await b.fresh(async()=>{const a=await fe();for(const n of await Le())a.has(n.node_id)||n.status!=="active"||n.pi_pid!=null||n.frozen_at!=null||n.respawn_not_before!=null||(await $e(n.node_id,new Date().toISOString()),m({level:"warn",event:"daemon.startup.launch_debt_recorded",node_id:n.node_id}))}),await b.fresh(async()=>{await Mt();for(const a of un){const n=await a.apply();n.changed&&m({level:"info",event:"daemon.boot_migration.applied",fields:{migration:a.id,...n.summary}})}}),k(Qr()),T){const a=s(()=>{k(T().catch(()=>{})),k(mr().then(n=>F?.observe(n)).then(()=>{},n=>{m({level:"warn",event:"daemon.peer.status_failed",error:n})}))},"refresh");k(Yr().then(({completion:n})=>n).catch(n=>{m({level:"error",event:"daemon.grants.sweep_failed",error:n})})),a(),G=setInterval(a,Ge*1e3),G.unref(),de=pr({joined:!0,register:k})}await J(async()=>{await pn(),await dn()}),te=dr(),j=setInterval(()=>{V().catch(a=>m({level:"error",event:"daemon.tick.failed",error:a}))},ee),ne=await Nt(()=>{V().catch(a=>m({level:"error",event:"daemon.tick.failed",error:a}))}),oe=await M.subscribe(()=>{V().catch(a=>m({level:"error",event:"daemon.tick.failed",error:a}))},{kinds:["spend_limits"]}),ie=await M.subscribe(a=>{J(()=>b.fresh(()=>Vn(a)))},{kinds:["execution_exit"]}),await V(),e.role===void 0&&import("../commands/sys/import/move.js").then(({settleMoveAtDaemonStart:a})=>a(()=>!P,n=>m({level:"warn",event:"daemon.move.settle_failed",error:n}))).catch(a=>m({level:"warn",event:"daemon.move.settle_failed",error:a}))}s(sr,"completeStartup");function pe(){return Xe??=sr().catch(r=>{throw S={phase:"initializing",message:"daemon startup recovery failed and normal services are unavailable",blockerPaths:[]},r})}s(pe,"resumeStartup");try{process.on("SIGINT",be),process.on("SIGTERM",ke),process.on("exit",Re),hn(),d!==null&&m({level:"info",event:"daemon.person.resolved",fields:{person_id:d.id,source:d.source}}),l!==null&&!l.alreadyDone&&m({level:"info",event:"daemon.packages.install_migration_done",fields:{moved:l.moved,discarded:l.discarded,people:l.people}}),i!==null&&m({level:"info",event:"daemon.permissions.boot",fields:{...i}}),u!==null&&m({level:"info",event:"daemon.person.retired",fields:{person_id:u.person,joined_from:u.joinedFrom,retired:u.retired,columns:u.columns}}),H(e.role)?W=await yr():Sr(gr());const r=y.token;Bt({epoch:r,requestHandover:tr,registerDetached:k,startupBlock:Ze,admitStartup:ir,repairMigrations:ar}),Q(),I=H(e.role)?$r({tcp:e.tcp}):Qn(e),await I.ready,Q(I.tcpAddress()??"");const t=Oe("user").runtime;if(t?.issuer&&(T=Vr(t.issuer,k),t.unsandboxed===!0&&(F=fr({syncGrants:T}))),e.role==="api"||e.role==="all"){const a=s(()=>k(import("../core/providers/bundles.js").then(h=>h.syncProviderBundles()).catch(h=>{m({level:"error",event:"daemon.providers.bundle_sync_failed",error:h})})),"bundleTick"),n=s(()=>{k(Kr().catch(h=>{m({level:"error",event:"daemon.packages.sync_failed",error:h})})),a()},"packageTick");n(),O=setInterval(n,Ge*1e3),O.unref()}if(H(e.role)&&(se=await qr()),Z(e.role)&&(le=Jr()),ce=await Wr({serves:H(e.role),runsLanes:Z(e.role)}),t?.unsandboxed===!0&&t.listener!==void 0&&m({level:"warn",event:"daemon.app_listener.refused_unsandboxed",fields:{reason:"runtime.unsandboxed is set; runtime.listener is ignored"}}),H(e.role)&&t!==void 0&&t.listener!==void 0&&t.unsandboxed!==!0&&(L=await Gr(t,async()=>await Xr(t.issuer.replace(/\/$/,"")),T),await L.ready,Q(I.tcpAddress()??"",`${t.listener.address}:${L.port()}`)),e.role===void 0)try{await wn()}catch(a){if($=null,a instanceof vn)return S={phase:"blocked",message:a.message,blockerPaths:a.blockerPaths},D;throw a}process.platform==="linux"&&E(C)&&(Er(),await Rr("app:terminal"));try{e.prepare?S={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]}:(await pe(),S={phase:"ready",message:"",blockerPaths:[]})}finally{$=null}return D}catch(r){try{await D()}catch(t){throw new AggregateError([r,t],"daemon startup failed and cleanup also failed")}throw r}}s(eo,"runDaemon");var ra=eo;export{Yn as API_DRAIN_GRACE_MS,oa as brokerCommandDeclaresCanvasHome,ge as brokerCommandEpoch,ra as default,Vn as exitedNodePass,Z as roleRunsLanes,H as roleServesRequests,eo as runDaemon,Jn as superviseTick,In as teardownFleet};
19
+ `),process.exit(1)}}a(ve,"handleSignal");function ge(){ve("SIGINT")}a(ge,"onSigint");function Se(){ve("SIGTERM")}a(Se,"onSigterm");function _e(){O().catch(()=>{})}a(_e,"onExit");async function q(n){b&&(B=B.then(n).then(()=>{},r=>{y.fresh(()=>{d({level:"error",event:"daemon.lane_job.failed",error:r})})}))}a(q,"enqueue");async function K(){!b||X||(je.check()&&D&&(d({level:"info",event:"daemon.resume.detected"}),k(D().catch(()=>{}))),X=!0,await q(async()=>{if(X=!1,!!b)try{m||await zt({log:s}),await Cn(Date.now(),ze)}catch(n){y.fresh(()=>{d({level:"error",event:"daemon.tick.failed",error:n})})}}))}a(K,"enqueueTick");let G=null;async function Ye(){if(G!==null)throw{status:500,code:"admission_failed",message:`daemon admission previously failed: ${G instanceof Error?G.message:String(G)}`};if(g.phase==="ready")return{admitted:!1,already_admitted:!0,startup_phase:"ready"};if(g.phase!=="prepared"&&g.phase!=="recovering")throw{status:409,code:"not_prepared",message:g.message};const n=g.phase==="prepared";try{return await ye(),g={phase:"ready",message:"",blockerPaths:[]},n?{admitted:!0,already_admitted:!1,startup_phase:"ready"}:{admitted:!1,already_admitted:!0,startup_phase:"ready"}}catch(r){throw G=r,{status:500,code:"admission_failed",message:`daemon admission failed: ${r instanceof Error?r.message:String(r)}`}}}a(Ye,"admitStartup");async function Je(){Q=e.intervalMs??Yr;const n=S.token;T=new rn({epoch:n,enqueue:q}),It(T),g={phase:"recovering",message:"daemon startup recovery is running and normal services are unavailable",blockerPaths:[]},y.fresh(()=>{d({level:"info",event:"daemon.started",fields:{pid:process.pid,interval_ms:Q}})});const r=_;if(y.fresh(()=>{d({level:"info",event:"daemon.install_id.resolved",fields:{install_id:r}})}),y.fresh(()=>{let t;try{t=Vr()}catch{return}t!==null&&d({level:"warn",event:"daemon.startup.warning",fields:{stage:"termrender",warning:t.slice(0,2048)}})}),wt(),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|all): it names the directory this deployment mints tokens against");if(e.role==="all"&&!process.env.CRTR_DATABASE_URL&&!process.env.CRTR_TEST_PG_URL)throw new Error("CRTR_DATABASE_URL must be set on --role all: it names the Postgres this process serves");if(e.role!==void 0&&Ir(),!J(e.role)){g={phase:"ready",message:"",blockerPaths:[]};return}if(await y.fresh(async()=>{await Kr(),await zr();const t=e.role!==void 0;await Wr(Date.now(),t),await qr(Date.now(),t)}),e.role===void 0&&await y.fresh(async()=>{const t=await $t();t.changed&&d({level:"info",event:"daemon.boot_change.reconciled",fields:{cleared_count:t.cleared.length,same_boot_proven:t.sameBootProven}})}),await y.fresh(async()=>{const t=await de();for(const p of await Ee())t.has(p.node_id)||p.status!=="active"||p.pi_pid!=null||p.frozen_at!=null||p.respawn_not_before!=null||(await Pe(p.node_id,new Date().toISOString()),d({level:"warn",event:"daemon.startup.launch_debt_recorded",node_id:p.node_id}))}),await y.fresh(async()=>{await Pt()}),k(Ur()),D){const t=a(()=>{k(D().catch(()=>{})),k(rr().then(p=>M?.observe(p)).then(()=>{},p=>{d({level:"warn",event:"daemon.peer.status_failed",error:p})}))},"refresh");k(jr().then(({completion:p})=>p).catch(p=>{d({level:"error",event:"daemon.grants.sweep_failed",error:p})})),t(),$=setInterval(t,Ie*1e3),$.unref(),se=er({joined:!0,register:k})}await q(async()=>{await en(),await Zt()}),Z=Ze(),j=setInterval(()=>{K().catch(t=>d({level:"error",event:"daemon.tick.failed",error:t}))},Q),ee=await Et(()=>{K().catch(t=>d({level:"error",event:"daemon.tick.failed",error:t}))}),re=await L.subscribe(()=>{K().catch(t=>d({level:"error",event:"daemon.tick.failed",error:t}))},{kinds:["spend_limits"]}),te=await L.subscribe(t=>{q(()=>y.fresh(()=>An(t)))},{kinds:["execution_exit"]}),await K(),e.role===void 0&&import("../commands/sys/import/move.js").then(({settleMoveAtDaemonStart:t})=>t(()=>!b,p=>d({level:"warn",event:"daemon.move.settle_failed",error:p}))).catch(t=>d({level:"warn",event:"daemon.move.settle_failed",error:t}))}a(Je,"completeStartup");function ye(){return Ue??=Je().catch(n=>{throw g={phase:"initializing",message:"daemon startup recovery failed and normal services are unavailable",blockerPaths:[]},n})}a(ye,"resumeStartup");try{process.on("SIGINT",ge),process.on("SIGTERM",Se),process.on("exit",_e),nn(),w!==null&&d({level:"info",event:"daemon.person.resolved",fields:{person_id:w.id,source:w.source}}),l!==null&&!l.alreadyDone&&d({level:"info",event:"daemon.packages.install_migration_done",fields:{moved:l.moved,discarded:l.discarded,people:l.people}}),i!==null&&d({level:"info",event:"daemon.permissions.boot",fields:{...i}}),v!==null&&d({level:"info",event:"daemon.person.retired",fields:{person_id:v.person,joined_from:v.joinedFrom,retired:v.retired,columns:v.columns}}),F(e.role)?z=await pr():mr(cr());const n=S.token;Tt({epoch:n,requestHandover:qe,registerDetached:k,startupBlock:He,admitStartup:Ye}),ue(),E=F(e.role)?Er({tcp:e.tcp}):$n(e),await E.ready,ue(E.tcpAddress()??"");const r=Te("user").runtime;if(r?.issuer&&(D=Br(r.issuer,k),r.unsandboxed===!0&&(M=tr({syncGrants:D}))),e.role==="api"||e.role==="all"){const t=a(()=>k(import("../core/providers/bundles.js").then(P=>P.syncProviderBundles()).catch(P=>{d({level:"error",event:"daemon.providers.bundle_sync_failed",error:P})})),"bundleTick"),p=a(()=>{k(Gr().catch(P=>{d({level:"error",event:"daemon.packages.sync_failed",error:P})})),t()},"packageTick");p(),N=setInterval(p,Ie*1e3),N.unref()}return F(e.role)&&(oe=await Mr()),J(e.role)&&(ie=Fr()),ae=await Or({serves:F(e.role),runsLanes:J(e.role)}),r?.unsandboxed===!0&&r.listener!==void 0&&d({level:"warn",event:"daemon.app_listener.refused_unsandboxed",fields:{reason:"runtime.unsandboxed is set; runtime.listener is ignored"}}),F(e.role)&&r!==void 0&&r.listener!==void 0&&r.unsandboxed!==!0&&(C=await Dr(r,async()=>await Hr(r.issuer.replace(/\/$/,"")),D),await C.ready,ue(E.tcpAddress()??"",`${r.listener.address}:${C.port()}`)),process.platform==="linux"&&R(I)&&(gr(),await vr("app:terminal")),e.prepare?g={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]}:(await ye(),g={phase:"ready",message:"",blockerPaths:[]}),O}catch(n){try{await O()}catch(r){throw new AggregateError([n,r],"daemon startup failed and cleanup also failed")}throw n}}a(Mn,"runDaemon");var Ci=Mn;export{Ln as API_DRAIN_GRACE_MS,$i as brokerCommandDeclaresCanvasHome,fe as brokerCommandEpoch,Ci as default,An as exitedNodePass,J as roleRunsLanes,F as roleServesRequests,Mn as runDaemon,Cn as superviseTick,dn as teardownFleet};
@@ -1,3 +1,3 @@
1
- var J=Object.defineProperty;var o=(t,e)=>J(t,"name",{value:e,configurable:!0});import{spawn as K,execFileSync as q}from"node:child_process";import{createRequire as Q}from"node:module";import{dirname as x,join as T}from"node:path";import{fileURLToPath as Z,pathToFileURL as N}from"node:url";import{existsSync as F,lstatSync as tt,mkdirSync as et,openSync as H,closeSync as G,fstatSync as W,readSync as rt}from"node:fs";import{apiSocketPath as nt,crtrHome as S}from"../core/canvas/paths.js";import{listProcessTable as ot}from"../core/canvas/pid.js";import{bindDaemonEventSource as at,eventSource as it}from"../core/events/source.js";import{hostExecPath as I}from"../core/runtime/branded-host.js";import{isDaemonRunning as st,readPidfile as w,isPidAlive as R}from"./pidfile.js";import{DAEMON_STARTUP_WINDOW_MS as V}from"./startup-policy.js";import{computerIsUnset as ct,readMachineConfig as ut}from"./machine-link/config.js";import{exclusiveLockOwnerPid as lt}from"../core/exclusive-lock.js";import{onDiskMigrationLockPath as _t}from"../core/canvas/paths.js";import{envNoDaemonAutostart as dt}from"../shared/env.js";import{waitForDaemonAvailability as pt}from"../api/index.js";import{localClient as Rt}from"../api/node-transport.js";const ft=["TMUX","TMUX_PANE","NODE_OPTIONS"],mt=new Set(["CRTR_HOME","CRTR_RUNTIME_HOME","CRTR_PIDFILE","CRTR_RUNTIME","CRTR_INSTALL_ID","CRTR_LOG","CRTR_DEBUG","CRTR_DEBUG_PID_LIVENESS","CRTR_TIMING","CRTR_TIMING_PROC","CRTR_NO_DAEMON_AUTOSTART","CRTR_NO_AUTO_UPDATE","CRTR_NO_AUTO_INIT","CRTR_NO_EXPORTS","CRTR_LAYOUT_REFUSE","CRTR_POSTGRES_HOME","CRTR_DATABASE_URL","CRTR_DATABASE_SCHEMA","CRTR_DATABASE_POOL_MAX","CRTR_SCHEMA_DATABASE_URL","CRTR_DOCUMENT_PORT","CRTR_LAUNCHER_SOCKET","CRTR_API_ADDRESS","CRTR_DIRECTORY_URL","CRTR_PUBLIC_API_URL","CRTR_CANVAS_URL","CRTR_CANVAS_CLIENT_ID","CRTR_CANVAS_JWK_FILE","CRTR_SECRETS_KEY","CRTR_IMPORT_SERVICE_TOKEN","CRTR_PACKAGES_TOKEN","CRTR_FEEDBACK_ENDPOINT","CRTR_FEEDBACK_TOKEN","CRTR_SUPPORT_REPO","CRTR_BRANDED_HOST","CRTR_CODESIGN_IDENTITY","CRTR_PLUGIN_REVALIDATE_TTL_MS","CRTR_IMPORT_BLOB_WORKERS","CRTR_MAX_LIVE_BROKERS","CRTR_WARN_LIVE_BROKERS","CRTR_BROKER_RSS_CAP_MB","CRTR_UNATTENDED_PARK_MS","CRTR_WARM_POOL","CRTR_STREAM_WATCHDOG_MS","CRTR_CONVERSATION_COMMIT_DEADLINE_MS","CRTR_NAME_MODEL","CRTR_MODEL_PROVIDER","CRTR_BROKER_SIGNAL_LONG_PROOF"]),ht=["CRTR_DB_","CRTR_BOOT_","CRTR_R2_","CRTR_LEDGER_","CRTR_BASH_","CRTR_WATCHER_","CRTR_RECAP_","CRTR_MODEL_AUTH_","CRTR_TEST_","CRTR_FAULT_"];function Et(t){return ft.includes(t)?!1:t.startsWith("CRTR_")?mt.has(t)||ht.some(e=>t.startsWith(e)):!0}o(Et,"daemonKeepsEnv");function y(){const t={};for(const[e,r]of Object.entries(process.env))Et(e)&&(t[e]=r);return t}o(y,"sanitizedDaemonEnv");function Tt(){for(let t=x(Z(import.meta.url));;t=x(t)){if(F(T(t,"bin","runtime-generation-manifest.mjs")))return t;if(x(t)===t)throw new Error(`cannot locate the crouter generation root from ${import.meta.url}`)}}o(Tt,"generationRoot");async function g(){const t=Tt(),e=N(T(t,"bin","runtime-generation-manifest.mjs")).href,{runtimeHome:r}=await import(e);try{tt(T(r(),"selected"))}catch(u){if(u.code!=="ENOENT")throw u;return["--conditions","crtr-src","--import",N(Q(import.meta.url).resolve("tsx/esm")).href,T(t,"src","daemon","crtrd-cli.ts")]}const n=N(T(t,"bin","runtime-selector.mjs")).href,{tryResolveRuntime:a}=await import(n),s=a("daemon");if(!s.ok)throw new Error(`cannot resolve the selected runtime generation's daemon entry: ${s.error}`);return[s.runtime.entryPath]}o(g,"resolveDaemonLaunch");function wt(t,e){return t.includes(` --canvas-home ${e} `)||t.endsWith(` --canvas-home ${e}`)}o(wt,"daemonCommandDeclaresCanvasHome");function Dt(){const t=ot();if(t===null)return[];const e=S(),r=[];for(const{pid:n,command:a}of t)a.includes("daemon/crtrd")&&wt(a,e)&&n!==process.pid&&r.push(n);return r}o(Dt,"findDaemonPids");function St(t){const e=Dt().filter(n=>n!==t);for(const n of e)try{process.kill(n,"SIGTERM")}catch{}if(e.length===0)return e;const r=Date.now()+2e3;for(;Date.now()<r&&e.some(n=>R(n));)q("sleep",["0.1"]);for(const n of e)if(R(n))try{process.kill(n,"SIGKILL")}catch{}return e}o(St,"sweepStrayDaemons");async function Zt(){const t=process.execve;if(t===void 0)throw new Error(`this Node.js ${process.version} runtime cannot replace PID 1 with the successor daemon`);const e=I(),r=await g();return t(e,[e,...r,"--canvas-home",S()],y())}o(Zt,"execDaemon");async function P(t){const e=await g(),r=K(I(),[...e,...t],{stdio:["ignore","pipe","pipe"],env:y()});let n="",a="";r.stdout.setEncoding("utf8").on("data",c=>{n+=c}),r.stderr.setEncoding("utf8").on("data",c=>{a+=c});const s=await new Promise((c,d)=>{r.once("error",d),r.once("close",f=>c(f))});if(s!==0)throw new Error(a.trim()||`the ${t[0]} process exited with code ${s}`);const u=n.trim().split(`
2
- `).at(-1)??"";return JSON.parse(u)}o(P,"runDaemonEntry");function te(t,e){return P(["import-dump",t,e])}o(te,"runDaemonImportDump");function ee(t){return P(["import-dump",t,"bodies"])}o(ee,"runDaemonBodiesDump");function re(){return P(["import-dump","","install-id"])}o(re,"runDaemonInstallId");const j=2e4,L=10,v=1e3;async function b(t=v){const e=Math.min(t,v);return Rt({autostart:!1,timeoutMs:e,socketPath:nt()}).probeHealthz(e)}o(b,"probeDaemonHealth");function At(t){const e=t instanceof Error?t.message:String(t);if(typeof t!="object"||t===null)return e;const r=t.code,n=t.cause,a=typeof r=="string"?r:n?.code;return typeof a=="string"&&!e.includes(a)?`${e}: ${a}`:e}o(At,"probeErrorMessage");async function X(t=v){const e=await b(t);if(e.startup_phase==="blocked"){const r=w()??process.pid;throw new C(r,e.startup_blocked??"daemon startup is blocked")}if(!e.ok)throw new Error(e.startup_blocked??"crtrd health check reported not ready")}o(X,"probeDaemonServing");async function ne(){try{return await X(),!0}catch{return!1}}o(ne,"isDaemonServing");function U(t){return new Promise(e=>{setTimeout(e,t)})}o(U,"sleepMs");class k extends Error{static{o(this,"DaemonExitedBeforeReadyError")}stderrTail;constructor(e,r){super(r===""?e:`${e}
3
- ${r}`),this.name="DaemonExitedBeforeReadyError",this.stderrTail=r}}class Y extends Error{static{o(this,"DaemonLaunchError")}constructor(e){super(e instanceof Error?e.message:String(e),{cause:e}),this.name="DaemonLaunchError"}}class C extends Error{static{o(this,"DaemonStartupBlockedError")}constructor(e,r){super(`daemon ${e} is running but normal startup is blocked: ${r}`),this.name="DaemonStartupBlockedError"}}class B extends Error{static{o(this,"DaemonNotPreparedError")}constructor(e,r){super(r===void 0?`daemon ${e} is serving but did not report the prepared startup phase`:`daemon ${e} reported startup phase ${r}, not prepared`),this.name="DaemonNotPreparedError"}}async function Ct(t,e=V,r={},n="ready"){const a=r.readPidfile??w,s=r.isPidAlive??R,u=r.childExited,c=r.isDaemonServing,d=r.probeDaemonServing??(async h=>{if(c!==void 0){if(await c())return;throw new Error("crtrd health check reported not ready")}await X(h)}),f=r.probeDaemonHealth??b,D=r.sleepMs??U,i=r.now??Date.now;let p=null,l=null;return await pt({windowMs:e,pollIntervalMs:L,now:i,sleep:D,retry:o(h=>h!==l,"retry"),probe:o(async h=>{const m=a();if(m===null||!s(m)){const _=u?.();throw _!=null&&(_.signal!==null?l=new k(`daemon ${t} exited before becoming ready (by ${_.signal})`,r.childStderrTail?.()??""):_.code!==0&&(l=new k(`daemon ${t} exited before becoming ready (with exit code ${_.code??"?"})`,r.childStderrTail?.()??"")),l!==null)?l:new Error(`daemon ${t} has no live pidfile owner`)}if(n==="ready"){try{await d(h)}catch(_){throw _ instanceof C&&(l=_),_}p=m;return}const E=await f(h);if(E.startup_phase==="prepared"){p=m;return}throw E.startup_phase==="blocked"?(l=new C(m,E.startup_blocked??"on-disk migration is blocked"),l):E.startup_phase==="ready"?(l=new B(m,E.startup_phase),l):new Error(`daemon ${m} is ${E.startup_phase??"not reporting a startup phase"}; waiting for prepared`)},"probe")}),p===t?null:p}o(Ct,"verifyDaemonStartup");async function Ot(t,e=j,r={}){const n=r.readPidfile??w,a=r.isPidAlive??R,s=r.sleepMs??U,u=r.now??Date.now,c=u()+e;for(;u()<=c;){if(!a(t)&&n()!==t)return;await s(L)}throw new Error(`daemon ${t} did not exit and release its pidfile within ${e}ms`)}o(Ot,"waitForDaemonExit");const Mt=2e3,xt=5e3;async function z(t,e=j,r={}){const n=r.isPidAlive??R,a=r.sleepMs??U,s=r.now??Date.now;try{process.kill(t,"SIGTERM")}catch{}try{return await Ot(t,e,r),"terminated"}catch{}try{process.kill(t,"SIGKILL")}catch{}const u=s()+Mt;for(;s()<=u;){if(!n(t))return"killed";await a(L)}throw new Error(`daemon ${t} survived both SIGTERM and SIGKILL`)}o(z,"stopDaemonProcess");async function oe(){const t=w(),e=t!==null&&R(t),r=e&&await z(t)==="killed",n=St(null);return{stopped:e||n.length>0,...e?{pid:t}:{},strays_killed:n,force_killed:r}}o(oe,"stopAllDaemons");function Nt(t,e,r=2048){let n;try{n=H(t,"r");const{size:a}=W(n),s=Math.max(e,a-r),u=a-s;if(u<=0)return"";const c=Buffer.alloc(u);return rt(n,c,0,u,s),c.toString("utf8").trim()}catch{return""}finally{if(n!==void 0)try{G(n)}catch{}}}o(Nt,"readLogTailFrom");async function It(t={}){if(process.platform==="linux"&&F("/run/crtr/launcher.sock")&&!R(w()??-1)&&ut()===void 0)throw new Error("crtrd is managed by the root launcher; it cannot self-daemonize");const e=t.targetPhase??"ready",r=w();if(r!==null&&R(r))try{const i=await b();if(e==="prepared"){if(i.startup_phase==="prepared")return{started:!1,existing_pid:r,startup_phase:i.startup_phase};throw new B(r,i.startup_phase)}return i.ok?{started:!1,existing_pid:r,...i.startup_phase===void 0?{}:{startup_phase:i.startup_phase}}:{started:!1,existing_pid:r,running:!0,serving:!1,probe_error:i.startup_blocked??"crtrd health check reported not ready",...i.startup_phase===void 0?{}:{startup_phase:i.startup_phase}}}catch(i){if(i instanceof B)throw i;return{started:!1,existing_pid:r,running:!0,serving:!1,probe_error:At(i)}}et(S(),{recursive:!0});const n=await g().catch(i=>{throw new Y(i)}),a=T(S(),"crtrd.err"),s=H(a,"a"),u=(()=>{try{return W(s).size}catch{return 0}})();it()===void 0&&at();const c=K(I(),[...n,"--canvas-home",S(),...e==="prepared"?["--prepare"]:[]],{detached:!0,stdio:["ignore",s,s],env:y()});G(s);const d=c.pid;if(d===void 0)throw new Error("daemon spawn did not return a pid");let f=null;c.once("exit",(i,p)=>{f={code:i,signal:p}}),c.unref();let D;try{D=await Ct(d,V,{childExited:o(()=>f,"childExited"),childStderrTail:o(()=>Nt(a,u),"childStderrTail")},e)}catch(i){const p=lt(_t())===d;if(f===null&&!p&&!(i instanceof C))try{await z(d,xt)}catch{}throw i}return D!==null?{started:!1,existing_pid:D,startup_phase:e}:{started:!0,pid:d,startup_phase:e}}o(It,"spawnDaemon");function yt(){return dt()||process.argv.includes("--no-autostart")}o(yt,"autostartDisabled");const gt=5e3,Pt=6e4;let $=!1,A,O=0,M=0;function Lt(t){return Math.min(gt*2**(t-1),Pt)}o(Lt,"autostartBackoffMs");function vt(){A=void 0,O=0,M=0}o(vt,"resetDaemonAutostart");function ae(){return A}o(ae,"daemonAutostartStartupFailure");function ie(t={}){const e=t.isDaemonRunning??st,r=t.spawnDaemon??It,n=t.now??Date.now;if(!yt()&&!(!t.spawnDaemon&&ct())&&!$&&!(n()<M)){if(e()){vt();return}A=void 0,$=!0,r().then(()=>{A=void 0,O=0,M=0},a=>{(a instanceof k||a instanceof Y)&&(A=a.message),O+=1,M=n()+Lt(O)}).finally(()=>{$=!1})}}o(ie,"ensureDaemon");export{ft as DAEMON_ENV_STRIP_KEYS,k as DaemonExitedBeforeReadyError,Y as DaemonLaunchError,B as DaemonNotPreparedError,C as DaemonStartupBlockedError,yt as autostartDisabled,ae as daemonAutostartStartupFailure,wt as daemonCommandDeclaresCanvasHome,Et as daemonKeepsEnv,ie as ensureDaemon,Zt as execDaemon,Dt as findDaemonPids,ne as isDaemonServing,b as probeDaemonHealth,X as probeDaemonServing,At as probeErrorMessage,vt as resetDaemonAutostart,ee as runDaemonBodiesDump,te as runDaemonImportDump,re as runDaemonInstallId,y as sanitizedDaemonEnv,It as spawnDaemon,oe as stopAllDaemons,z as stopDaemonProcess,St as sweepStrayDaemons,Ct as verifyDaemonStartup,Ot as waitForDaemonExit};
1
+ var J=Object.defineProperty;var o=(t,e)=>J(t,"name",{value:e,configurable:!0});import{spawn as K,execFileSync as q}from"node:child_process";import{createRequire as Q}from"node:module";import{dirname as x,join as T}from"node:path";import{fileURLToPath as Z,pathToFileURL as N}from"node:url";import{existsSync as F,lstatSync as tt,mkdirSync as et,openSync as H,closeSync as G,fstatSync as W,readSync as rt}from"node:fs";import{apiSocketPath as nt,crtrHome as S}from"../core/canvas/paths.js";import{listProcessTable as ot}from"../core/canvas/pid.js";import{bindDaemonEventSource as at,eventSource as it}from"../core/events/source.js";import{hostExecPath as I}from"../core/runtime/branded-host.js";import{isDaemonRunning as st,readPidfile as w,isPidAlive as R}from"./pidfile.js";import{DAEMON_STARTUP_WINDOW_MS as V}from"./startup-policy.js";import{computerIsUnset as ct,readMachineConfig as ut}from"./machine-link/config.js";import{exclusiveLockOwnerPid as lt}from"../core/exclusive-lock.js";import{onDiskMigrationLockPath as dt}from"../core/canvas/paths.js";import{envNoDaemonAutostart as _t}from"../shared/env.js";import{waitForDaemonAvailability as pt}from"../api/index.js";import{localClient as Rt}from"../api/node-transport.js";const ft=["TMUX","TMUX_PANE","NODE_OPTIONS"],mt=new Set(["CRTR_HOME","CRTR_RUNTIME_HOME","CRTR_PIDFILE","CRTR_RUNTIME","CRTR_INSTALL_ID","CRTR_LOG","CRTR_DEBUG","CRTR_DEBUG_PID_LIVENESS","CRTR_TIMING","CRTR_TIMING_PROC","CRTR_NO_DAEMON_AUTOSTART","CRTR_NO_AUTO_UPDATE","CRTR_NO_AUTO_INIT","CRTR_NO_EXPORTS","CRTR_POSTGRES_HOME","CRTR_DATABASE_URL","CRTR_DATABASE_SCHEMA","CRTR_DATABASE_POOL_MAX","CRTR_SCHEMA_DATABASE_URL","CRTR_DOCUMENT_PORT","CRTR_LAUNCHER_SOCKET","CRTR_API_ADDRESS","CRTR_DIRECTORY_URL","CRTR_PUBLIC_API_URL","CRTR_CANVAS_URL","CRTR_CANVAS_CLIENT_ID","CRTR_CANVAS_JWK_FILE","CRTR_SECRETS_KEY","CRTR_IMPORT_SERVICE_TOKEN","CRTR_PACKAGES_TOKEN","CRTR_FEEDBACK_ENDPOINT","CRTR_FEEDBACK_TOKEN","CRTR_SUPPORT_REPO","CRTR_BRANDED_HOST","CRTR_CODESIGN_IDENTITY","CRTR_PLUGIN_REVALIDATE_TTL_MS","CRTR_IMPORT_BLOB_WORKERS","CRTR_MAX_LIVE_BROKERS","CRTR_WARN_LIVE_BROKERS","CRTR_BROKER_RSS_CAP_MB","CRTR_UNATTENDED_PARK_MS","CRTR_WARM_POOL","CRTR_STREAM_WATCHDOG_MS","CRTR_CONVERSATION_COMMIT_DEADLINE_MS","CRTR_NAME_MODEL","CRTR_MODEL_PROVIDER","CRTR_BROKER_SIGNAL_LONG_PROOF"]),ht=["CRTR_DB_","CRTR_BOOT_","CRTR_R2_","CRTR_LEDGER_","CRTR_BASH_","CRTR_WATCHER_","CRTR_RECAP_","CRTR_MODEL_AUTH_","CRTR_TEST_","CRTR_FAULT_"];function Et(t){return ft.includes(t)?!1:t.startsWith("CRTR_")?mt.has(t)||ht.some(e=>t.startsWith(e)):!0}o(Et,"daemonKeepsEnv");function y(){const t={};for(const[e,r]of Object.entries(process.env))Et(e)&&(t[e]=r);return t}o(y,"sanitizedDaemonEnv");function Tt(){for(let t=x(Z(import.meta.url));;t=x(t)){if(F(T(t,"bin","runtime-generation-manifest.mjs")))return t;if(x(t)===t)throw new Error(`cannot locate the crouter generation root from ${import.meta.url}`)}}o(Tt,"generationRoot");async function g(){const t=Tt(),e=N(T(t,"bin","runtime-generation-manifest.mjs")).href,{runtimeHome:r}=await import(e);try{tt(T(r(),"selected"))}catch(u){if(u.code!=="ENOENT")throw u;return["--conditions","crtr-src","--import",N(Q(import.meta.url).resolve("tsx/esm")).href,T(t,"src","daemon","crtrd-cli.ts")]}const n=N(T(t,"bin","runtime-selector.mjs")).href,{tryResolveRuntime:a}=await import(n),s=a("daemon");if(!s.ok)throw new Error(`cannot resolve the selected runtime generation's daemon entry: ${s.error}`);return[s.runtime.entryPath]}o(g,"resolveDaemonLaunch");function wt(t,e){return t.includes(` --canvas-home ${e} `)||t.endsWith(` --canvas-home ${e}`)}o(wt,"daemonCommandDeclaresCanvasHome");function Dt(){const t=ot();if(t===null)return[];const e=S(),r=[];for(const{pid:n,command:a}of t)a.includes("daemon/crtrd")&&wt(a,e)&&n!==process.pid&&r.push(n);return r}o(Dt,"findDaemonPids");function St(t){const e=Dt().filter(n=>n!==t);for(const n of e)try{process.kill(n,"SIGTERM")}catch{}if(e.length===0)return e;const r=Date.now()+2e3;for(;Date.now()<r&&e.some(n=>R(n));)q("sleep",["0.1"]);for(const n of e)if(R(n))try{process.kill(n,"SIGKILL")}catch{}return e}o(St,"sweepStrayDaemons");async function Zt(){const t=process.execve;if(t===void 0)throw new Error(`this Node.js ${process.version} runtime cannot replace PID 1 with the successor daemon`);const e=I(),r=await g();return t(e,[e,...r,"--canvas-home",S()],y())}o(Zt,"execDaemon");async function P(t){const e=await g(),r=K(I(),[...e,...t],{stdio:["ignore","pipe","pipe"],env:y()});let n="",a="";r.stdout.setEncoding("utf8").on("data",c=>{n+=c}),r.stderr.setEncoding("utf8").on("data",c=>{a+=c});const s=await new Promise((c,_)=>{r.once("error",_),r.once("close",f=>c(f))});if(s!==0)throw new Error(a.trim()||`the ${t[0]} process exited with code ${s}`);const u=n.trim().split(`
2
+ `).at(-1)??"";return JSON.parse(u)}o(P,"runDaemonEntry");function te(t,e){return P(["import-dump",t,e])}o(te,"runDaemonImportDump");function ee(t){return P(["import-dump",t,"bodies"])}o(ee,"runDaemonBodiesDump");function re(){return P(["import-dump","","install-id"])}o(re,"runDaemonInstallId");const j=2e4,L=10,v=1e3;async function b(t=v){const e=Math.min(t,v);return Rt({autostart:!1,timeoutMs:e,socketPath:nt()}).probeHealthz(e)}o(b,"probeDaemonHealth");function At(t){const e=t instanceof Error?t.message:String(t);if(typeof t!="object"||t===null)return e;const r=t.code,n=t.cause,a=typeof r=="string"?r:n?.code;return typeof a=="string"&&!e.includes(a)?`${e}: ${a}`:e}o(At,"probeErrorMessage");async function X(t=v){const e=await b(t);if(e.startup_phase==="blocked"){const r=w()??process.pid;throw new C(r,e.startup_blocked??"daemon startup is blocked")}if(!e.ok)throw new Error(e.startup_blocked??"crtrd health check reported not ready")}o(X,"probeDaemonServing");async function ne(){try{return await X(),!0}catch{return!1}}o(ne,"isDaemonServing");function k(t){return new Promise(e=>{setTimeout(e,t)})}o(k,"sleepMs");class U extends Error{static{o(this,"DaemonExitedBeforeReadyError")}stderrTail;constructor(e,r){super(r===""?e:`${e}
3
+ ${r}`),this.name="DaemonExitedBeforeReadyError",this.stderrTail=r}}class z extends Error{static{o(this,"DaemonLaunchError")}constructor(e){super(e instanceof Error?e.message:String(e),{cause:e}),this.name="DaemonLaunchError"}}class C extends Error{static{o(this,"DaemonStartupBlockedError")}constructor(e,r){super(`daemon ${e} is running but normal startup is blocked: ${r}`),this.name="DaemonStartupBlockedError"}}class B extends Error{static{o(this,"DaemonNotPreparedError")}constructor(e,r){super(r===void 0?`daemon ${e} is serving but did not report the prepared startup phase`:`daemon ${e} reported startup phase ${r}, not prepared`),this.name="DaemonNotPreparedError"}}async function Ct(t,e=V,r={},n="ready"){const a=r.readPidfile??w,s=r.isPidAlive??R,u=r.childExited,c=r.isDaemonServing,_=r.probeDaemonServing??(async h=>{if(c!==void 0){if(await c())return;throw new Error("crtrd health check reported not ready")}await X(h)}),f=r.probeDaemonHealth??b,D=r.sleepMs??k,i=r.now??Date.now;let p=null,l=null;return await pt({windowMs:e,pollIntervalMs:L,now:i,sleep:D,retry:o(h=>h!==l,"retry"),probe:o(async h=>{const m=a();if(m===null||!s(m)){const d=u?.();throw d!=null&&(d.signal!==null?l=new U(`daemon ${t} exited before becoming ready (by ${d.signal})`,r.childStderrTail?.()??""):d.code!==0&&(l=new U(`daemon ${t} exited before becoming ready (with exit code ${d.code??"?"})`,r.childStderrTail?.()??"")),l!==null)?l:new Error(`daemon ${t} has no live pidfile owner`)}if(n==="ready"){try{await _(h)}catch(d){throw d instanceof C&&(l=d),d}p=m;return}const E=await f(h);if(E.startup_phase==="prepared"){p=m;return}throw E.startup_phase==="blocked"?(l=new C(m,E.startup_blocked??"on-disk migration is blocked"),l):E.startup_phase==="ready"?(l=new B(m,E.startup_phase),l):new Error(`daemon ${m} is ${E.startup_phase??"not reporting a startup phase"}; waiting for prepared`)},"probe")}),p===t?null:p}o(Ct,"verifyDaemonStartup");async function Ot(t,e=j,r={}){const n=r.readPidfile??w,a=r.isPidAlive??R,s=r.sleepMs??k,u=r.now??Date.now,c=u()+e;for(;u()<=c;){if(!a(t)&&n()!==t)return;await s(L)}throw new Error(`daemon ${t} did not exit and release its pidfile within ${e}ms`)}o(Ot,"waitForDaemonExit");const Mt=2e3,xt=5e3;async function Y(t,e=j,r={}){const n=r.isPidAlive??R,a=r.sleepMs??k,s=r.now??Date.now;try{process.kill(t,"SIGTERM")}catch{}try{return await Ot(t,e,r),"terminated"}catch{}try{process.kill(t,"SIGKILL")}catch{}const u=s()+Mt;for(;s()<=u;){if(!n(t))return"killed";await a(L)}throw new Error(`daemon ${t} survived both SIGTERM and SIGKILL`)}o(Y,"stopDaemonProcess");async function oe(){const t=w(),e=t!==null&&R(t),r=e&&await Y(t)==="killed",n=St(null);return{stopped:e||n.length>0,...e?{pid:t}:{},strays_killed:n,force_killed:r}}o(oe,"stopAllDaemons");function Nt(t,e,r=2048){let n;try{n=H(t,"r");const{size:a}=W(n),s=Math.max(e,a-r),u=a-s;if(u<=0)return"";const c=Buffer.alloc(u);return rt(n,c,0,u,s),c.toString("utf8").trim()}catch{return""}finally{if(n!==void 0)try{G(n)}catch{}}}o(Nt,"readLogTailFrom");async function It(t={}){if(process.platform==="linux"&&F("/run/crtr/launcher.sock")&&!R(w()??-1)&&ut()===void 0)throw new Error("crtrd is managed by the root launcher; it cannot self-daemonize");const e=t.targetPhase??"ready",r=w();if(r!==null&&R(r))try{const i=await b();if(e==="prepared"){if(i.startup_phase==="prepared")return{started:!1,existing_pid:r,startup_phase:i.startup_phase};throw new B(r,i.startup_phase)}return i.ok?{started:!1,existing_pid:r,...i.startup_phase===void 0?{}:{startup_phase:i.startup_phase}}:{started:!1,existing_pid:r,running:!0,serving:!1,probe_error:i.startup_blocked??"crtrd health check reported not ready",...i.startup_phase===void 0?{}:{startup_phase:i.startup_phase}}}catch(i){if(i instanceof B)throw i;return{started:!1,existing_pid:r,running:!0,serving:!1,probe_error:At(i)}}et(S(),{recursive:!0});const n=await g().catch(i=>{throw new z(i)}),a=T(S(),"crtrd.err"),s=H(a,"a"),u=(()=>{try{return W(s).size}catch{return 0}})();it()===void 0&&at();const c=K(I(),[...n,"--canvas-home",S(),...e==="prepared"?["--prepare"]:[]],{detached:!0,stdio:["ignore",s,s],env:y()});G(s);const _=c.pid;if(_===void 0)throw new Error("daemon spawn did not return a pid");let f=null;c.once("exit",(i,p)=>{f={code:i,signal:p}}),c.unref();let D;try{D=await Ct(_,V,{childExited:o(()=>f,"childExited"),childStderrTail:o(()=>Nt(a,u),"childStderrTail")},e)}catch(i){const p=lt(dt())===_;if(f===null&&!p&&!(i instanceof C))try{await Y(_,xt)}catch{}throw i}return D!==null?{started:!1,existing_pid:D,startup_phase:e}:{started:!0,pid:_,startup_phase:e}}o(It,"spawnDaemon");function yt(){return _t()||process.argv.includes("--no-autostart")}o(yt,"autostartDisabled");const gt=5e3,Pt=6e4;let $=!1,A,O=0,M=0;function Lt(t){return Math.min(gt*2**(t-1),Pt)}o(Lt,"autostartBackoffMs");function vt(){A=void 0,O=0,M=0}o(vt,"resetDaemonAutostart");function ae(){return A}o(ae,"daemonAutostartStartupFailure");function ie(t={}){const e=t.isDaemonRunning??st,r=t.spawnDaemon??It,n=t.now??Date.now;if(!yt()&&!(!t.spawnDaemon&&ct())&&!$&&!(n()<M)){if(e()){vt();return}A=void 0,$=!0,r().then(()=>{A=void 0,O=0,M=0},a=>{(a instanceof U||a instanceof z)&&(A=a.message),O+=1,M=n()+Lt(O)}).finally(()=>{$=!1})}}o(ie,"ensureDaemon");export{ft as DAEMON_ENV_STRIP_KEYS,U as DaemonExitedBeforeReadyError,z as DaemonLaunchError,B as DaemonNotPreparedError,C as DaemonStartupBlockedError,yt as autostartDisabled,ae as daemonAutostartStartupFailure,wt as daemonCommandDeclaresCanvasHome,Et as daemonKeepsEnv,ie as ensureDaemon,Zt as execDaemon,Dt as findDaemonPids,ne as isDaemonServing,b as probeDaemonHealth,X as probeDaemonServing,At as probeErrorMessage,vt as resetDaemonAutostart,ee as runDaemonBodiesDump,te as runDaemonImportDump,re as runDaemonInstallId,y as sanitizedDaemonEnv,It as spawnDaemon,oe as stopAllDaemons,Y as stopDaemonProcess,St as sweepStrayDaemons,Ct as verifyDaemonStartup,Ot as waitForDaemonExit};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.755",
3
+ "version": "0.3.756",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -157,8 +157,8 @@
157
157
  },
158
158
  "license": "UNLICENSED",
159
159
  "dependencies": {
160
- "@north-light/identity": "0.3.755",
161
- "@north-light/plugin": "0.3.755",
160
+ "@north-light/identity": "0.3.756",
161
+ "@north-light/plugin": "0.3.756",
162
162
  "@earendil-works/chord": "1.5.2",
163
163
  "@earendil-works/pi-agent-core": "1.5.2",
164
164
  "@earendil-works/pi-ai": "1.5.2",
@@ -151,9 +151,6 @@ export class CrtrClient {
151
151
  admitDaemon() {
152
152
  return this.request('POST', routes.daemonAdmit());
153
153
  }
154
- migrateState(req) {
155
- return this.request('POST', routes.daemonMigrate(), req);
156
- }
157
154
  // Nodes
158
155
  appendNodeLog(id, req) {
159
156
  return this.request('POST', routes.nodeLog(this.nodePath(id)), req);
@@ -12,7 +12,7 @@
12
12
  //
13
13
  // PURITY (spec §3.1): Node built-ins + `src/api/*` only.
14
14
  /** The contract level this build serves and requires. Written by `scripts/contract.mjs release`; never edit by hand. */
15
- export const CONTRACT_LEVEL = '1.77';
15
+ export const CONTRACT_LEVEL = '1.78';
16
16
  /** Request header naming the one contract level the caller needs, e.g. `1.3`. Optional: absent means no check. */
17
17
  export const REQUIRED_CONTRACT_HEADER = 'Crouter-Required-Contract';
18
18
  /** Response header listing the contract levels the server serves, comma-separated, one per major, e.g. `1.3`. */
@@ -21,7 +21,6 @@ export const routes = {
21
21
  status: () => `${V}/status`,
22
22
  due: () => `${V}/due`,
23
23
  daemonRestart: () => `${V}/daemon/restart`,
24
- daemonMigrate: () => `${V}/daemon/migrate`,
25
24
  daemonDrain: () => `${V}/daemon/drain`,
26
25
  daemonAdmit: () => `${V}/daemon/admit`,
27
26
  // Nodes — collection + item
@@ -290,20 +290,11 @@ export function isPkgInstallInvocation(argv) {
290
290
  }
291
291
  export function isSignInInvocation(argv) { return isSysInvocation(argv, 'signin') || isSysInvocation(argv, 'signout'); }
292
292
  export function isJoinInvocation(argv) { return isSysInvocation(argv, 'join'); }
293
- export function isLayoutMigrationInvocation(argv) { return isSysInvocation(argv, 'migrate'); }
294
293
  /** Assemble the canonical daemon-control definitions without loading settings or plugin discovery. This path exists so `crtr sys daemon restart` can start the new generation that converts pre-SQL user state. */
295
294
  export async function resolveDaemonControlRoot() {
296
295
  const { registerDaemonControlSys } = await import('./commands/sys/daemon.js');
297
296
  return defineRoot({ tagline: TAGLINE, globals: GLOBALS, subtrees: [registerDaemonControlSys()] });
298
297
  }
299
- /** Migration runs offline before command plugins can read or initialize scoped state. */
300
- export async function resolveLayoutMigrationRoot() {
301
- const [{ defineSysBranch }, { sysMigrateLeaf }] = await Promise.all([
302
- import('./commands/sys/branch.js'),
303
- import('./commands/sys/migrate.js'),
304
- ]);
305
- return defineRoot({ tagline: TAGLINE, globals: GLOBALS, subtrees: [defineSysBranch([sysMigrateLeaf])] });
306
- }
307
298
  /** Build a root that contains only the subtree `first` dispatches into.
308
299
  * Returns the FULL root when `first` is not a recognized subtree — bare `crtr`,
309
300
  * `-h`/`--help`, `--version`, and any unknown leading token all need the
@@ -1,7 +1,7 @@
1
1
  import { defineBranch } from '../../core/command.js';
2
2
  const SYS_ROOT_ENTRY = {
3
3
  concept: 'crtr configuration, diagnostics, and self-management',
4
- desc: 'settings, config, connect, setup, tutorial, doctor, context, sync, migrate, join, update, version, feedback, logs, retry-delivery, support, limits, daemon',
4
+ desc: 'settings, config, connect, setup, tutorial, doctor, context, sync, join, update, version, feedback, logs, retry-delivery, support, limits, daemon',
5
5
  useWhen: 'managing the crtr installation, inspecting diagnostics, operating the crtrd supervisor process, or registering a hosted runtime with its directory before first boot',
6
6
  };
7
7
  const SYS_HELP = {
@@ -78,7 +78,7 @@ async function awaitDaemonPhase(phase, timeoutMs) {
78
78
  message: health.startup_blocked ?? 'daemon startup is blocked',
79
79
  received: health.startup_phase,
80
80
  field: 'phase',
81
- next: 'Repair the reported blocker paths with `crtr sys migrate`, then retry the await.',
81
+ next: 'Fix the reported blocker, then retry the await.',
82
82
  });
83
83
  }
84
84
  if (health.startup_phase === phase)
@@ -17,7 +17,6 @@ import { tutorialBranch } from './sys/tutorial/branch.js';
17
17
  import { supportBranch } from './sys/support.js';
18
18
  import { contextBranch } from './sys/context.js';
19
19
  import { sysSyncBranch } from './sys/sync.js';
20
- import { sysMigrateLeaf } from './sys/migrate.js';
21
20
  import { sysJoinLeaf } from './sys/join.js';
22
21
  import { sysImportBranch } from './sys/import/start.js';
23
22
  import { sysMachineBranch } from './sys/machine/rotate.js';
@@ -25,5 +24,5 @@ import { sysDesktopBranch } from './sys/desktop.js';
25
24
  import { sysSigninLeaf, sysSignoutLeaf } from './sys/signin.js';
26
25
  import { sysUpdateLeaf, sysVersionLeaf } from './sys/update.js';
27
26
  export function registerSys() {
28
- return defineSysBranch([sysSettingsLeaf, configBranch, sysEnvBranch, sysSetupLeaf, tutorialBranch, sysDoctorLeaf, contextBranch, sysFeedbackLeaf, sysLogsLeaf, sysWorktreesLeaf, sysRetryDeliveryLeaf, sysSpacesLeaf, sysLimitsBranch, sysSpendBranch, supportBranch, sysUpdateLeaf, sysVersionLeaf, sysMigrateLeaf, sysJoinLeaf, sysSyncBranch, sysImportBranch, sysMachineBranch, sysSigninLeaf, sysSignoutLeaf, sysDesktopBranch, daemonBranch]);
27
+ return defineSysBranch([sysSettingsLeaf, configBranch, sysEnvBranch, sysSetupLeaf, tutorialBranch, sysDoctorLeaf, contextBranch, sysFeedbackLeaf, sysLogsLeaf, sysWorktreesLeaf, sysRetryDeliveryLeaf, sysSpacesLeaf, sysLimitsBranch, sysSpendBranch, supportBranch, sysUpdateLeaf, sysVersionLeaf, sysJoinLeaf, sysSyncBranch, sysImportBranch, sysMachineBranch, sysSigninLeaf, sysSignoutLeaf, sysDesktopBranch, daemonBranch]);
29
28
  }
@@ -1,6 +1,6 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { openDb, withCanvasWrite } from './db.js';
3
- import { capturePidIdentities, captureLivenessSnapshot, identitiesMatch, recordedPidLiveness, isBootScopedIdentity, isLegacyTicksIdentity } from './pid.js';
3
+ import { capturePidIdentities, captureLivenessSnapshot, recordedPidLiveness } from './pid.js';
4
4
  import { existsSync, readFileSync } from 'node:fs';
5
5
  import { LAUNCHER_SOCKET } from '../../launcher/spec.js';
6
6
  import { revokeNodeTokens } from './node-tokens.js';
@@ -187,22 +187,6 @@ export async function endLiveExecution(nodeId, input) {
187
187
  return Number(ended.changes) === 1;
188
188
  });
189
189
  }
190
- export async function migrateLegacyExecutionIdentities(captureIdentity = (pid) => capturePidIdentities([pid])?.get(pid)) {
191
- const db = await openDb();
192
- const rows = await db.prepare("SELECT execution_id, pid, process_identity FROM executions WHERE state = 'running' AND pid IS NOT NULL AND process_identity IS NOT NULL").all();
193
- const update = db.prepare("UPDATE executions SET process_identity = ? WHERE execution_id = ? AND pid = ? AND process_identity = ? AND state = 'running'");
194
- const migrated = [];
195
- for (const row of rows) {
196
- if (!isLegacyTicksIdentity(row.process_identity))
197
- continue;
198
- const current = captureIdentity(row.pid);
199
- if (current === undefined || !isBootScopedIdentity(current) || !identitiesMatch(current, row.process_identity))
200
- continue;
201
- if ((await update.run(current, row.execution_id, row.pid, row.process_identity)).changes > 0)
202
- migrated.push(row.execution_id);
203
- }
204
- return { migrated };
205
- }
206
190
  /** Records a stop request on the node's live execution; the first request's time and reason stand. */
207
191
  export async function requestExecutionStop(nodeId, input) {
208
192
  const updated = await (await openDb()).prepare("UPDATE executions SET stop_requested_at = COALESCE(stop_requested_at, ?), stop_after_turn = CASE WHEN stop_requested_at IS NULL THEN ? ELSE stop_after_turn END, stop_reason = COALESCE(stop_reason, ?) WHERE node_id = ? AND state != 'exited'").run(now(), input.afterTurn ? 1 : 0, input.reason, nodeId);