@north-light/cli 0.3.603 → 0.3.605

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 (34) hide show
  1. package/dist/clients/attach/viewer.js +433 -433
  2. package/dist/commands/api-client.d.ts +4 -0
  3. package/dist/commands/api-client.js +3 -3
  4. package/dist/commands/daemon-generation.d.ts +1 -1
  5. package/dist/commands/daemon-generation.js +1 -1
  6. package/dist/commands/sys/daemon.js +1 -1
  7. package/dist/core/canvas/canvas.js +20 -20
  8. package/dist/core/canvas/schema-pg/005-fleet-blobs.sql +1 -1
  9. package/dist/core/import/export/cloud.d.ts +8 -3
  10. package/dist/core/import/export/cloud.js +1 -1
  11. package/dist/core/import/export/files.d.ts +1 -0
  12. package/dist/core/import/export/files.js +1 -1
  13. package/dist/core/providers/bundles.js +2 -2
  14. package/dist/core/runs/operations.js +6 -6
  15. package/dist/core/runtime/runner/blaxel/runner.d.ts +1 -1
  16. package/dist/core/runtime/runner/blaxel/runner.js +3 -3
  17. package/dist/core/runtime/runner/delete-sandboxes.d.ts +3 -0
  18. package/dist/core/runtime/runner/delete-sandboxes.js +1 -0
  19. package/dist/core/runtime/runner/machine/executor.d.ts +14 -1
  20. package/dist/core/runtime/runner/machine/executor.js +1 -1
  21. package/dist/core/runtime/runner/machine/machine-executor.test.js +3 -3
  22. package/dist/core/storage/attachments.d.ts +1 -1
  23. package/dist/daemon/api/router.js +1 -1
  24. package/dist/daemon/api/server.d.ts +1 -2
  25. package/dist/daemon/api/server.js +1 -1
  26. package/dist/daemon/crtrd.js +13 -13
  27. package/dist/daemon/due.js +4 -4
  28. package/dist/daemon/reconcilers/recipe-image.d.ts +15 -1
  29. package/dist/daemon/reconcilers/recipe-image.js +5 -6
  30. package/dist/daemon/reconcilers/storage-due-work.d.ts +3 -4
  31. package/dist/daemon/reconcilers/storage-due-work.js +3 -2
  32. package/package.json +2 -2
  33. package/packages/crouter-identity/package.json +1 -1
  34. package/runtime.lock.json +13 -13
@@ -1 +1 @@
1
- var Ie=Object.defineProperty;var s=(e,r)=>Ie(e,"name",{value:r,configurable:!0});import{IMPORT_TOKEN_PREFIX as ze,importPrincipalFor as He}from"./import-auth.js";import{createServer as ie}from"node:http";import{createServer as Le}from"node:https";import{chmodSync as Be,existsSync as G,readFileSync as se,unlinkSync as ae}from"node:fs";import{MINIMUM_RUNTIME_VERSION_HEADER as le,RUNTIME_VERSION_HEADER as Y,minimumRuntimeRefusal as xe}from"../../api/runtime-version.js";import{CONTRACT_HEADER as K,CONTRACT_LEVEL as ce,REQUIRED_CONTRACT_HEADER as ue,contractRefusal as De}from"../../api/contract.js";import{crtrVersion as X}from"../../shared/crtr-version.js";import{apiSocketPath as Me}from"../../core/canvas/paths.js";import{resolveNodeToken as Fe}from"../../core/canvas/node-tokens.js";import{isCloudRole as H,runAsPerson as J}from"../../core/canvas/person.js";import{personBearerVerifier as pe}from"./auth/person-bearer.js";import{personHasSnapshot as Z}from"../../core/scoped-state/person-store.js";import{loadPersonSettings as Q}from"../../core/scoped-state/person-rows.js";import{AppPrincipalResolver as $e}from"./principal.js";import{createAppRequestHandler as Je}from"./app-listener.js";import{decodeJwt as We}from"jose";import{handleRuntimeSignIn as je,isRuntimeSignInPath as Ve}from"./key-signin.js";import{RunError as S}from"../../core/runs/operations.js";import{removeVendorAccount as Ge,vendorStatus as Ye}from"./handlers/vendor-status.js";import{toErrorBody as Ke}from"./map.js";import{CONTROL_BODY_MAX_BYTES as Xe}from"../../core/llm/body-limits.js";import{grantFor as Ze,hasSyncedGrants as Qe}from"../../core/grants/mirror.js";import{readConfig as de}from"../../core/config.js";import{directoryIssuer as qe}from"../../core/directory/issuer.js";import{peerUid as er}from"../../native/linux.js";import{findScopedApiToken as rr,getApiToken as tr,listScopedApiTokens as nr}from"../../core/secrets.js";import{emitEvent as A}from"../../core/events/emit.js";import{envCrtrdTcp as or,envCrtrdToken as ir}from"../../shared/env.js";import{Router as fe,actsAsPerson as me}from"./router.js";import{handleAttachUpgrade as sr,refuseUpgrade as y}from"./bridge.js";import{handleMachineLinkUpgrade as ar,machineLinkEnvironment as lr,setApiAddress as cr}from"../machine-link/holder.js";import{handleMachineViewUpgrade as ur,machineViewEnvironment as pr}from"../machine-link/forward.js";import{boundDaemonControl as dr}from"../control.js";import{attachRoutes as fr,mayAttachNode as ge}from"./handlers/attach.js";import{peerRoutes as mr}from"../peer/handlers.js";import{bashJobRoutes as gr}from"./handlers/bash-jobs.js";import{bashRoutes as hr}from"./handlers/bash.js";import{hookExecRoutes as Rr}from"./handlers/hook-exec.js";import{brokerOperationRoutes as he}from"./handlers/broker-ops.js";import{brokerSignalRoutes as Ar,brokerSignalStreams as yr}from"./handlers/broker-signals.js";import{brokerRecoveryRoutes as Re,nodeFaultRoutes as _r}from"./handlers/broker-recovery.js";import{canvasRoutes as vr}from"./handlers/canvas.js";import{conversationRoutes as wr}from"./handlers/conversations.js";import{chatInventoryRoutes as Er}from"./handlers/chat-inventory.js";import{daemonRoutes as Sr}from"./handlers/daemon.js";import{fileRoutes as br}from"./handlers/files.js";import{focusRoutes as Tr}from"./handlers/focus.js";import{analyticsRoutes as Cr}from"./handlers/analytics.js";import{memoryReadsRoutes as kr}from"./handlers/memory-reads.js";import{memoryRoutes as Ur}from"./handlers/memory.js";import{healthRoutes as Or}from"./handlers/health.js";import{humanRequestRoutes as Pr}from"./handlers/human-requests.js";import{inboxRoutes as Nr}from"./handlers/inbox.js";import{feedbackCommentRoutes as Ir}from"./handlers/feedback-comments.js";import{objectRoutes as zr}from"./handlers/objects.js";import{shareRoutes as Hr}from"./handlers/shares.js";import{customObjectRoutes as Lr}from"./handlers/custom-objects.js";import{docRoutes as Br}from"./handlers/docs.js";import{deliveryRoutes as Ae}from"./handlers/delivery.js";import{deliveryRetryRoutes as xr}from"./handlers/delivery-retry.js";import{packageDocRoutes as Dr}from"./handlers/package-docs.js";import{documentAccessRoutes as Mr}from"./handlers/document-access.js";import{pluginAppRoutes as Fr}from"./handlers/plugin-app-token.js";import{brokerMailRoutes as ye,messageRoutes as $r}from"./handlers/messages.js";import{modelAuthRoutes as Jr}from"./handlers/modelauth.js";import{llmRoutes as Wr}from"./handlers/llm.js";import{providerRoutes as jr}from"./handlers/providers.js";import{modelConfigRoutes as Vr}from"./handlers/model-config.js";import{settingsRoutes as Gr}from"./handlers/settings.js";import{nodeRoutes as Yr}from"./handlers/nodes.js";import{nodeRecordRoutes as Kr}from"./handlers/node-records.js";import{nodeOutcomeRoutes as Xr}from"./handlers/node-outcomes.js";import{nodeEventRoutes as Zr}from"./handlers/node-events.js";import{profileRoutes as Qr}from"./handlers/profiles.js";import{prospectiveChatInventoryRoutes as qr}from"./handlers/prospective-chat-inventory.js";import{reportRoutes as et}from"./handlers/reports.js";import{runRoutes as rt}from"./handlers/run-routes.js";import{reviewCommentRoutes as tt}from"./handlers/review-comments.js";import{reviewRoutes as nt}from"./handlers/reviews.js";import{subscriptionRoutes as ot}from"./handlers/subscriptions.js";import{structuredRequestRoutes as it}from"./handlers/structured-requests.js";import{cronRoutes as st}from"./handlers/crons.js";import{setCronRequestHandler as _e}from"../cron/run-socket.js";import{RUN_TOKEN_PREFIX as at,cronPrincipalForRunToken as lt}from"../cron/run-token.js";import{worktreeRoutes as ct}from"./handlers/worktree.js";import{limitsRoutes as ut}from"./handlers/limits.js";import{chargeRoutes as pt,spendLimitRoutes as dt}from"./handlers/charges.js";import{executionStartRoutes as ft}from"./handlers/execution-start.js";import{machineCredentialRoutes as mt}from"./handlers/machine-credential.js";import{importRoutes as gt}from"./handlers/imports.js";import{gitCredentialRoutes as ht}from"./handlers/git-credential.js";function Rt(e){return new fe().registerAll(Or(e)).registerAll(Sr).registerAll(Hr).registerAll(Yr).registerAll(Kr).registerAll(Xr).registerAll(xr).registerAll(Zr).registerAll(gr).registerAll(hr).registerAll(Rr).registerAll(he).registerAll(Ar).registerAll(Ae).registerAll(Re).registerAll(_r).registerAll(ct).registerAll(ut).registerAll(pt).registerAll(ft).registerAll(mt).registerAll(gt).registerAll(ht).registerAll(dt).registerAll(ye).registerAll($r).registerAll(et).registerAll(rt).registerAll(it).registerAll(fr).registerAll(vr).registerAll(wr).registerAll(Cr).registerAll(kr).registerAll(Ur).registerAll(br).registerAll(zr).registerAll(Lr).registerAll(Br).registerAll(Dr).registerAll(Mr).registerAll(Fr).registerAll(Tr).registerAll(ot).registerAll(st).registerAll(Qr).registerAll(Jr).registerAll(Wr).registerAll(jr).registerAll(Vr).registerAll(Gr).registerAll(nt).registerAll(tt).registerAll(Nr).registerAll(Pr).registerAll(Er).registerAll(qr).registerAll(Ir).registerAll(mr)}s(Rt,"buildRouter");function At(e,r){if(e.toUpperCase()!=="GET")return null;const o=r.split("/").filter(u=>u.length>0);if(o.length!==4||o[0]!=="v1"||o[1]!=="nodes"||o[3]!=="attach")return null;const a=o[2];return a===void 0||a===""?null:decodeURIComponent(a)}s(At,"attachNodeId");function yt(e){const r=e.trim();if(r==="")return null;const o=r.lastIndexOf(":");if(o<0)return null;const a=r.slice(0,o),u=r.slice(o+1),d=Number(u);return!Number.isInteger(d)||d<0||d>65535?null:{host:a===""?"0.0.0.0":a,port:d}}s(yt,"parseTcp");function _t(e,r){return`${e.includes(":")?`[${e}]`:e}:${r}`}s(_t,"formatTcpAddress");const P={code:"unauthorized",message:"missing or invalid bearer token"},L={code:"owner_only",message:"attach is owner-only; a scoped token does not reach it"},M={code:"person_bearer_not_supported",message:"this listener accepts a person bearer only on a cloud role with CRTR_DIRECTORY_URL and CRTR_PUBLIC_API_URL set; call with a node, app or public token"},q={class:"anonymous",app:"",node:"",run:null,uid:-1,sub:"",grant:null,client_id:null,scopes:[]},B=new WeakMap;function F(e){return B.get(e)}s(F,"socketPrincipal");async function ve(e,r){const o=process.platform==="linux"?er(e.socket):null,a=e.headers.authorization;if(a===void 0)return o===null||r.has(o)?{class:"person"}:"unauthorized";if(typeof a!="string"||!a.startsWith("Bearer "))return"unauthorized";if(a.slice(7).startsWith("crtr_pub_"))return q;if(a.slice(7).startsWith(ee)){const u=be(a.slice(7));return u!==void 0&&(o===null||r.has(o))?u.principal:"unauthorized"}return we(a.slice(7),o)}s(ve,"resolveSocketPrincipal");async function we(e,r){const o=await Fe(e);if(!o||r!==null&&r!==o.uid)return"unauthorized";const a=qe();if(a&&!H()&&!await Qe(a))return"runtime_starting";const u=o.grant??(await Ze("app:terminal",o.sub))?.id??null;return{class:"broker",...o,grant:u}}s(we,"brokerPrincipal");function Ee(e){if(!(e.class==="anonymous"||e.class==="import"))return e.sub!==void 0&&e.sub!==""?e.sub:void 0}s(Ee,"requestPerson");function Se(e,r){r.class==="broker"&&A({event:"api.request.principal",level:r.app==="app:terminal"?"debug":"info",node_id:r.node,fields:{principal:`${r.app} node:${r.node}`,method:e.method,path:e.url}})}s(Se,"noteBrokerRequest");const ee="crtr_app_";function be(e){const r=e.startsWith(ee)?rr(e):void 0;return r===void 0?void 0:{principal:{class:"app",app:r.grantee,scopes:r.scopes},ceiling:r.scopes}}s(be,"appBearer");function vt(e){const r=new Map;for(const o of nr("user"))r.set(o.token,{principal:{class:"app",app:o.grantee,scopes:o.scopes},ceiling:o.scopes});return e!==void 0&&r.set(e,{principal:{class:"person"},ceiling:null}),r}s(vt,"resolveBearers");function wt(e){try{return We(e).act!==void 0}catch{return!1}}s(wt,"carriesAct");const Et=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*$/;function k(e,r){return e!==void 0&&(e.reason=r),"unauthorized"}s(k,"deny");async function Te(e,r,o){const a=e.headers.authorization;if(a===void 0&&(e.method??"GET").toUpperCase()==="GET"&&(e.url??"").split("?")[0]==="/healthz")return{principal:q,ceiling:null};if(typeof a!="string"||!a.startsWith("Bearer "))return k(o,a===void 0?"no_authorization_header":"not_a_bearer");const u=a.slice(7);if(u.startsWith("crtr_pub_"))return{principal:q,ceiling:null};if(u.startsWith(ee))return be(u)??k(o,"app_token_unknown");if(u.startsWith(at)){const v=await lt(u);return v===null?k(o,"run_token_invalid_or_settled"):{principal:v,ceiling:null}}const d=r.get(u);if(d!==void 0)return d;const R=He(u);if(R!==null)return{principal:R,ceiling:null};if(u.startsWith(ze))return k(o,"import_token_invalid");if(Et.test(u)){if(H()&&wt(u)){const x=j();if(x===null)return"person_bearer";try{const w=await x.verifyCall(a);return w.chain[0]?.sub.startsWith("app:")?{call:w}:k(o,"call_token_presenter_not_an_app")}catch(w){return w instanceof S&&w.status===503?"runtime_starting":k(o,`call_token_${w instanceof S?w.code:"invalid"}`)}}const v=H()?pe():null;if(v===null)return"person_bearer";const U=await v.verify(u);return U===null?k(o,"person_bearer_not_verified"):{principal:{class:"person",sub:U},ceiling:null}}const m=await we(u,null);return m==="unauthorized"?k(o,"node_token_unknown"):typeof m=="string"?m:{principal:m,ceiling:null}}s(Te,"authorizeTcp");let W;function j(){if(W!==void 0)return W;const e=process.env.CRTR_DIRECTORY_URL||void 0,r=process.env.CRTR_PUBLIC_API_URL||void 0;return W=e===void 0||r===void 0?null:new $e(e,r,async()=>{}),W}s(j,"cloudCallResolver");let Ce;function St(){const e=j();if(e===null)throw new S(503,"runtime_starting","app calls are not configured on this listener");return Ce??=Je(e,async()=>!0,async()=>{}),Ce}s(St,"cloudAppCalls");async function bt(e,r){N(r),I(r);const o=j();try{if(o===null)throw new S(503,"runtime_starting","sign-in is not configured on this listener");await je(e,r,new URL(e.url??"/","http://runtime.local"),o)}catch(a){if(!(a instanceof S))throw a;if(r.headersSent){r.destroy();return}r.writeHead(a.status,{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}),r.end(JSON.stringify({error:{code:a.code,message:a.message,...a.param?{param:a.param}:{},origin:"runtime"}}))}}s(bt,"serveRuntimeSignIn");function Tt(){const e=process.env.CRTRD_TLS_CERT||void 0,r=process.env.CRTRD_TLS_KEY||void 0;if(e===void 0&&r===void 0)return null;if(e===void 0||r===void 0)throw new Error("CRTRD_TLS_CERT and CRTRD_TLS_KEY must be set together");return{cert:se(e),key:se(r)}}s(Tt,"tcpTls");function N(e){e.setHeader(Y,X()),e.setHeader(K,ce)}s(N,"advertiseRuntime");function I(e){e.setHeader("Access-Control-Allow-Origin","*"),e.setHeader("Access-Control-Expose-Headers",`${Y}, ${K}`)}s(I,"exposeRuntimeHeaders");function Ct(e,r){return(e.method??"GET").toUpperCase()!=="OPTIONS"?!1:(N(r),r.writeHead(204,{"Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":`${Y}, ${K}`,"Access-Control-Allow-Headers":`authorization, content-type, ${le.toLowerCase()}, ${ue.toLowerCase()}`,"Access-Control-Allow-Methods":"GET, POST, PATCH, PUT, DELETE, OPTIONS","Access-Control-Max-Age":"600"}),r.end(),!0)}s(Ct,"answerPreflight");function V(e,r=!1){N(e),r&&I(e),e.writeHead(401,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{...P,origin:"runtime"}}))}s(V,"writeUnauthorized");function kt(e){N(e),I(e),e.writeHead(401,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{...M,origin:"runtime"}}))}s(kt,"writePersonBearerRefused");const Ut={"/v1/runtime/vendor-status":{method:"GET",purpose:"vendor_status"},"/v1/runtime/vendor-account-remove":{method:"POST",purpose:"vendor_account_remove"}};async function Ot(e,r){if(!H())return!1;const o=new URL(e.url??"/","http://runtime.local").pathname,a=Ut[o];if(a===void 0||e.method!==a.method)return!1;const u=s((d,R)=>{N(r),I(r),r.writeHead(d,{"content-type":"application/json; charset=utf-8"}),r.end(JSON.stringify(R))},"answer");try{const d=pe();if(d===null)throw new S(401,M.code,M.message);const R=e.headers.authorization,m=R?.startsWith("Bearer ")?await d.verifyPurpose(R.slice(7),a.purpose):null;if(m===null)throw new S(401,"unauthorized","invalid directory token");const v=a.purpose==="vendor_status"?void 0:await Pt(e);u(200,await J(m,async()=>a.purpose==="vendor_status"?Ye():await Ge(v)))}catch(d){const{status:R,body:m}=Ke(d);u(R,m)}return!0}s(Ot,"serveCloudVendorRoute");async function Pt(e){const r=[];let o=0;for await(const a of e){if(o+=a.length,o>Xe)throw new S(400,"invalid_request","request body too large");r.push(a)}if(o!==0)try{return JSON.parse(Buffer.concat(r).toString("utf8"))}catch{throw new S(400,"invalid_request","invalid JSON body")}}s(Pt,"readVendorBody");function ke(e){N(e),e.writeHead(503,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{code:"runtime_starting",message:"grant sync is not ready",type:"server_error",origin:"runtime",retryable:!0}}))}s(ke,"writeRuntimeStarting");function Nt(e,r){e.writeHead(503,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{code:"startup_blocked",message:r,origin:"runtime"}}))}s(Nt,"writeStartupBlocked");function Ue(e,r,o){return new Promise(a=>{if(o===void 0){try{e.closeAllConnections()}catch{}e.close(()=>a());return}const u=[];e.close(()=>{for(const m of u)clearTimeout(m);a()});for(const m of r)m.destroy();const d=setInterval(()=>e.closeIdleConnections(),250),R=setTimeout(()=>e.closeAllConnections(),o);u.push(d,R),e.closeIdleConnections()})}s(Ue,"closeServer");function _o(e={}){let r=null;const o=Rt(()=>r),a=new fe().registerAll(he).registerAll(Ae).registerAll(Re).registerAll(ye),u=s((t,n)=>{const c=dr()?.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??Me(),R=new Set([process.getuid?.()??0,...de("user").runtime?.person_uids??[]]),m=s((t,n,c)=>{N(n);const p=s(i=>Array.isArray(i)?i[0]:i,"first"),O=p(t.headers[le.toLowerCase()]),h=xe(O,X())??De(p(t.headers[ue.toLowerCase()]),ce,{legacyMinimum:O,runtimeVersion:X()});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 E=s(i=>{const l=F(t);A({event:"api.request.failed",level:"error",...l?.class==="broker"?{node_id:l.node}:{},error:i instanceof Error?i:new Error(String(i))});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 T;try{T=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 i=u((t.method??"GET").toUpperCase(),T.pathname);if(i!==null){Nt(n,i.message);return}const l=F(t)??{class:"person"},f=Ee(l),g=s(()=>o.handle(t,n,c,l),"handled");(f===void 0?g():J(f,s(async()=>{Z()||await Q(f),await g()},"handledAsPerson"))).catch(E)}catch(i){E(i)}},"onRequest"),v=s(async(t,n,c)=>{const p=F(t);return p===void 0||me(p)||await ge(p,"either",c)?!0:(y(n,404,"Not Found","node_not_found",`no node ${c}`),!1)},"authorizeAttachUpgrade"),U=new Set,x=s((t,n,c)=>{U.add(n),n.once("close",()=>U.delete(n)),n.on("error",()=>{});try{const p=new URL(t.url??"/","http://127.0.0.1"),O=u((t.method??"GET").toUpperCase(),p.pathname);if(O!==null){y(n,503,"Service Unavailable","startup_blocked",O.message);return}const h=At(t.method??"GET",p.pathname);if(h===null){n.destroy();return}const E=(()=>{const i=F(t);return i===void 0?void 0:Ee(i)})(),T=s(()=>v(t,n,h).then(i=>i?sr(t,n,c,h,async l=>{const f=F(t);return f===void 0||me(f)||await ge(f,l,h)}):void 0),"attach");(E===void 0?T():J(E,async()=>{Z()||await Q(E),await T()})).catch(()=>{try{n.destroy()}catch{}})}catch{try{n.destroy()}catch{}}},"onUpgrade"),w=s(t=>{t.on("error",n=>{A({event:"api.server.failed",level:"error",error:n})})},"bindErrorHandler"),Oe=s(async(t,n)=>{try{const c=await ve(t,R);if(c==="unauthorized"){A({event:"api.principal.denied",level:"warn",fields:{method:t.method}}),V(n);return}if(c==="runtime_starting"){ke(n);return}B.set(t,c),Se(t,c),m(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))}),V(n)}},"onSocketRequest"),D=ie((t,n)=>{Oe(t,n).catch(c=>A({event:"api.principal.failed",level:"error",error:c instanceof Error?c:new Error(String(c))}))}),Pe=s(async(t,n,c)=>{try{const p=await ve(t,R);if(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),x(t,n,c)}catch(p){A({event:"api.principal.failed",level:"error",error:p instanceof Error?p:new Error(String(p))}),y(n,401,"Unauthorized",P.code,P.message)}},"onSocketUpgrade");D.on("upgrade",(t,n,c)=>{Pe(t,n,c).catch(p=>A({event:"api.principal.failed",level:"error",error:p instanceof Error?p:new Error(String(p))}))}),_e((t,n,c)=>{B.set(t,c),m(t,n,null)});let re=!1,te,ne;const Ne=new Promise((t,n)=>{te=t,ne=n});D.once("listening",()=>{re=!0,te()}),D.on("error",t=>{A({event:"api.server.failed",level:"error",error:t}),re||ne(t)});try{G(d)&&ae(d)}catch{}D.listen(d,()=>{try{Be(d,process.platform==="linux"&&G("/run/crtr/launcher.sock")?438:384)}catch(t){A({event:"api.socket.chmod_failed",level:"error",error:t instanceof Error?t:new Error(String(t))})}});let b;const $=e.tcp??or()??de("user").api.tcp;if($!==void 0&&$!==""){const t=yt($);if(t===null)A({event:"api.tcp.invalid",level:"error",error:new Error(`invalid CRTRD_TCP/--tcp spec: ${$}`)});else{H()&&j();const n=e.token??ir()??tr("user"),c=vt(n),p=s(async(i,l)=>{if(Ct(i,l))return;if(H()&&Ve(new URL(i.url??"/","http://runtime.local").pathname)){await bt(i,l);return}if(await Ot(i,l))return;const f={},g=await Te(i,c,f);if(g==="runtime_starting"){I(l),ke(l);return}if(g==="person_bearer"){kt(l);return}if(g==="unauthorized"){A({event:"api.principal.denied",level:"warn",fields:{method:i.method,listener:"tcp",path:new URL(i.url??"/","http://runtime.local").pathname,reason:f.reason??"unknown"}}),V(l,!0);return}if("call"in g){I(l);const z=g.call.sub;await J(z,async()=>{Z()||await Q(z),await St()(i,l,g.call)});return}B.set(i,g.principal),Se(i,g.principal),I(l),m(i,l,g.ceiling)},"tcpOnRequest"),O=s(async(i,l,f)=>{const g=lr(i);if(g!==null){const _=await ar(i,l,f,g);_!==null&&y(l,_.status,_.text,_.code,_.message);return}const z=pr(i);if(z!==null){const _=ur(i,l,f,z);_!==null&&y(l,_.status,_.text,_.code,_.message);return}const C=await Te(i,c);if(C==="runtime_starting"){y(l,503,"Service Unavailable","runtime_starting","grant sync is not ready");return}if(C==="person_bearer"){y(l,401,"Unauthorized",M.code,M.message);return}if(C==="unauthorized"){y(l,401,"Unauthorized",P.code,P.message);return}if("call"in C){y(l,403,"Forbidden",L.code,L.message);return}if(C.ceiling!==null||C.principal.class==="anonymous"||C.principal.class==="import"){y(l,403,"Forbidden",L.code,L.message);return}B.set(i,C.principal),x(i,l,f)},"tcpOnUpgrade"),h=s(i=>{A({event:"api.principal.failed",level:"error",error:i instanceof Error?i:new Error(String(i))})},"failed"),E=s((i,l)=>{p(i,l).catch(f=>{h(f),l.headersSent?l.destroy():V(l,!0)})},"listener"),T=Tt();b=T===null?ie(E):Le(T,E),b.on("upgrade",(i,l,f)=>{l.on("error",()=>{}),O(i,l,f).catch(g=>{h(g),y(l,401,"Unauthorized",P.code,P.message)})}),w(b),b.once("listening",()=>{const i=b?.address();if(i!==null&&typeof i=="object"){const{address:l,port:f}=i;r=_t(l,f),l!=="0.0.0.0"&&l!=="::"&&cr(r)}}),b.listen(t.port,t.host)}}let oe=!1;return{ready:Ne,tcpAddress:s(()=>r,"tcpAddress"),close:s(async(t={})=>{if(!oe){oe=!0,_e(null),yr.close(),await Promise.all([Ue(D,U,t.graceMs),b!==void 0?Ue(b,U,t.graceMs):Promise.resolve()]);try{G(d)&&ae(d)}catch{}}},"close")}}s(_o,"createApiServer");export{Rt as buildRouter,Ue as closeServer,_o as createApiServer,F as socketPrincipal};
1
+ var ze=Object.defineProperty;var n=(e,r)=>ze(e,"name",{value:r,configurable:!0});import{IMPORT_TOKEN_PREFIX as He,importPrincipalFor as Le}from"./import-auth.js";import{createServer as ie}from"node:http";import{createServer as Be}from"node:https";import{chmodSync as xe,existsSync as G,readFileSync as se,unlinkSync as ae}from"node:fs";import{MINIMUM_RUNTIME_VERSION_HEADER as le,RUNTIME_VERSION_HEADER as Y,minimumRuntimeRefusal as De}from"../../api/runtime-version.js";import{CONTRACT_HEADER as K,CONTRACT_LEVEL as ce,REQUIRED_CONTRACT_HEADER as ue,contractRefusal as Me}from"../../api/contract.js";import{crtrVersion as X}from"../../shared/crtr-version.js";import{apiSocketPath as Fe}from"../../core/canvas/paths.js";import{resolveNodeToken as $e}from"../../core/canvas/node-tokens.js";import{isCloudRole as H,runAsPerson as J}from"../../core/canvas/person.js";import{personBearerVerifier as pe}from"./auth/person-bearer.js";import{personHasSnapshot as Z}from"../../core/scoped-state/person-store.js";import{loadPersonSettings as Q}from"../../core/scoped-state/person-rows.js";import{AppPrincipalResolver as Je}from"./principal.js";import{createAppRequestHandler as We}from"./app-listener.js";import{decodeJwt as je}from"jose";import{handleRuntimeSignIn as Ve,isRuntimeSignInPath as Ge}from"./key-signin.js";import{RunError as S}from"../../core/runs/operations.js";import{removeVendorAccount as Ye,vendorStatus as Ke}from"./handlers/vendor-status.js";import{toErrorBody as Xe}from"./map.js";import{CONTROL_BODY_MAX_BYTES as Ze}from"../../core/llm/body-limits.js";import{grantFor as Qe,hasSyncedGrants as qe}from"../../core/grants/mirror.js";import{readConfig as de}from"../../core/config.js";import{directoryIssuer as er}from"../../core/directory/issuer.js";import{peerUid as rr}from"../../native/linux.js";import{findScopedApiToken as tr,getApiToken as nr,listScopedApiTokens as or}from"../../core/secrets.js";import{emitEvent as A}from"../../core/events/emit.js";import{envCrtrdTcp as ir,envCrtrdToken as sr}from"../../shared/env.js";import{Router as fe,actsAsPerson as me}from"./router.js";import{handleAttachUpgrade as ar,refuseUpgrade as y}from"./bridge.js";import{handleMachineLinkUpgrade as lr,machineLinkEnvironment as cr,setApiAddress as ur}from"../machine-link/holder.js";import{handleMachineViewUpgrade as pr,machineViewEnvironment as dr}from"../machine-link/forward.js";import{boundDaemonControl as fr}from"../control.js";import{attachRoutes as mr,mayAttachNode as ge}from"./handlers/attach.js";import{peerRoutes as gr}from"../peer/handlers.js";import{bashJobRoutes as hr}from"./handlers/bash-jobs.js";import{bashRoutes as Rr}from"./handlers/bash.js";import{hookExecRoutes as Ar}from"./handlers/hook-exec.js";import{brokerOperationRoutes as he}from"./handlers/broker-ops.js";import{brokerSignalRoutes as yr,brokerSignalStreams as _r}from"./handlers/broker-signals.js";import{brokerRecoveryRoutes as Re,nodeFaultRoutes as vr}from"./handlers/broker-recovery.js";import{canvasRoutes as wr}from"./handlers/canvas.js";import{conversationRoutes as Er}from"./handlers/conversations.js";import{chatInventoryRoutes as Sr}from"./handlers/chat-inventory.js";import{daemonRoutes as br}from"./handlers/daemon.js";import{fileRoutes as Tr}from"./handlers/files.js";import{focusRoutes as Cr}from"./handlers/focus.js";import{analyticsRoutes as kr}from"./handlers/analytics.js";import{memoryReadsRoutes as Ur}from"./handlers/memory-reads.js";import{memoryRoutes as Or}from"./handlers/memory.js";import{healthRoutes as Pr}from"./handlers/health.js";import{humanRequestRoutes as Nr}from"./handlers/human-requests.js";import{inboxRoutes as Ir}from"./handlers/inbox.js";import{feedbackCommentRoutes as zr}from"./handlers/feedback-comments.js";import{objectRoutes as Hr}from"./handlers/objects.js";import{shareRoutes as Lr}from"./handlers/shares.js";import{customObjectRoutes as Br}from"./handlers/custom-objects.js";import{docRoutes as xr}from"./handlers/docs.js";import{deliveryRoutes as Ae}from"./handlers/delivery.js";import{deliveryRetryRoutes as Dr}from"./handlers/delivery-retry.js";import{packageDocRoutes as Mr}from"./handlers/package-docs.js";import{documentAccessRoutes as Fr}from"./handlers/document-access.js";import{pluginAppRoutes as $r}from"./handlers/plugin-app-token.js";import{brokerMailRoutes as ye,messageRoutes as Jr}from"./handlers/messages.js";import{modelAuthRoutes as Wr}from"./handlers/modelauth.js";import{llmRoutes as jr}from"./handlers/llm.js";import{providerRoutes as Vr}from"./handlers/providers.js";import{modelConfigRoutes as Gr}from"./handlers/model-config.js";import{settingsRoutes as Yr}from"./handlers/settings.js";import{nodeRoutes as Kr}from"./handlers/nodes.js";import{nodeRecordRoutes as Xr}from"./handlers/node-records.js";import{nodeOutcomeRoutes as Zr}from"./handlers/node-outcomes.js";import{nodeEventRoutes as Qr}from"./handlers/node-events.js";import{profileRoutes as qr}from"./handlers/profiles.js";import{prospectiveChatInventoryRoutes as et}from"./handlers/prospective-chat-inventory.js";import{reportRoutes as rt}from"./handlers/reports.js";import{runRoutes as tt}from"./handlers/run-routes.js";import{reviewCommentRoutes as nt}from"./handlers/review-comments.js";import{reviewRoutes as ot}from"./handlers/reviews.js";import{subscriptionRoutes as it}from"./handlers/subscriptions.js";import{structuredRequestRoutes as st}from"./handlers/structured-requests.js";import{cronRoutes as at}from"./handlers/crons.js";import{setCronRequestHandler as _e}from"../cron/run-socket.js";import{RUN_TOKEN_PREFIX as lt,cronPrincipalForRunToken as ct}from"../cron/run-token.js";import{worktreeRoutes as ut}from"./handlers/worktree.js";import{limitsRoutes as pt}from"./handlers/limits.js";import{chargeRoutes as dt,spendLimitRoutes as ft}from"./handlers/charges.js";import{executionStartRoutes as mt}from"./handlers/execution-start.js";import{machineCredentialRoutes as gt}from"./handlers/machine-credential.js";import{importRoutes as ht}from"./handlers/imports.js";import{gitCredentialRoutes as Rt}from"./handlers/git-credential.js";function At(e){return new fe().registerAll(Pr(e)).registerAll(br).registerAll(Lr).registerAll(Kr).registerAll(Xr).registerAll(Zr).registerAll(Dr).registerAll(Qr).registerAll(hr).registerAll(Rr).registerAll(Ar).registerAll(he).registerAll(yr).registerAll(Ae).registerAll(Re).registerAll(vr).registerAll(ut).registerAll(pt).registerAll(dt).registerAll(mt).registerAll(gt).registerAll(ht).registerAll(Rt).registerAll(ft).registerAll(ye).registerAll(Jr).registerAll(rt).registerAll(tt).registerAll(st).registerAll(mr).registerAll(wr).registerAll(Er).registerAll(kr).registerAll(Ur).registerAll(Or).registerAll(Tr).registerAll(Hr).registerAll(Br).registerAll(xr).registerAll(Mr).registerAll(Fr).registerAll($r).registerAll(Cr).registerAll(it).registerAll(at).registerAll(qr).registerAll(Wr).registerAll(jr).registerAll(Vr).registerAll(Gr).registerAll(Yr).registerAll(ot).registerAll(nt).registerAll(Ir).registerAll(Nr).registerAll(Sr).registerAll(et).registerAll(zr).registerAll(gr)}n(At,"buildRouter");function yt(e,r){if(e.toUpperCase()!=="GET")return null;const o=r.split("/").filter(u=>u.length>0);if(o.length!==4||o[0]!=="v1"||o[1]!=="nodes"||o[3]!=="attach")return null;const a=o[2];return a===void 0||a===""?null:decodeURIComponent(a)}n(yt,"attachNodeId");function _t(e){const r=e.trim();if(r==="")return null;const o=r.lastIndexOf(":");if(o<0)return null;const a=r.slice(0,o),u=r.slice(o+1),d=Number(u);return!Number.isInteger(d)||d<0||d>65535?null:{host:a===""?"0.0.0.0":a,port:d}}n(_t,"parseTcp");function vt(e,r){return`${e.includes(":")?`[${e}]`:e}:${r}`}n(vt,"formatTcpAddress");const P={code:"unauthorized",message:"missing or invalid bearer token"},L={code:"owner_only",message:"attach is owner-only; a scoped token does not reach it"},M={code:"person_bearer_not_supported",message:"this listener accepts a person bearer only on a cloud role with CRTR_DIRECTORY_URL and CRTR_PUBLIC_API_URL set; call with a node, app or public token"},q={class:"anonymous",app:"",node:"",run:null,uid:-1,sub:"",grant:null,client_id:null,scopes:[]},B=new WeakMap;function F(e){return B.get(e)}n(F,"socketPrincipal");async function ve(e,r){const o=process.platform==="linux"?rr(e.socket):null,a=e.headers.authorization;if(a===void 0)return o===null||r.has(o)?{class:"person"}:"unauthorized";if(typeof a!="string"||!a.startsWith("Bearer "))return"unauthorized";if(a.slice(7).startsWith("crtr_pub_"))return q;if(a.slice(7).startsWith(ee)){const u=be(a.slice(7));return u!==void 0&&(o===null||r.has(o))?u.principal:"unauthorized"}return we(a.slice(7),o)}n(ve,"resolveSocketPrincipal");async function we(e,r){const o=await $e(e);if(!o||r!==null&&r!==o.uid)return"unauthorized";const a=er();if(a&&!H()&&!await qe(a))return"runtime_starting";const u=o.grant??(await Qe("app:terminal",o.sub))?.id??null;return{class:"broker",...o,grant:u}}n(we,"brokerPrincipal");function Ee(e){if(!(e.class==="anonymous"||e.class==="import"))return e.sub!==void 0&&e.sub!==""?e.sub:void 0}n(Ee,"requestPerson");function Se(e,r){r.class==="broker"&&A({event:"api.request.principal",level:r.app==="app:terminal"?"debug":"info",node_id:r.node,fields:{principal:`${r.app} node:${r.node}`,method:e.method,path:e.url}})}n(Se,"noteBrokerRequest");const ee="crtr_app_";function be(e){const r=e.startsWith(ee)?tr(e):void 0;return r===void 0?void 0:{principal:{class:"app",app:r.grantee,scopes:r.scopes},ceiling:r.scopes}}n(be,"appBearer");function wt(e){const r=new Map;for(const o of or("user"))r.set(o.token,{principal:{class:"app",app:o.grantee,scopes:o.scopes},ceiling:o.scopes});return e!==void 0&&r.set(e,{principal:{class:"person"},ceiling:null}),r}n(wt,"resolveBearers");function Et(e){try{return je(e).act!==void 0}catch{return!1}}n(Et,"carriesAct");const St=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*$/;function k(e,r){return e!==void 0&&(e.reason=r),"unauthorized"}n(k,"deny");async function Te(e,r,o){const a=e.headers.authorization;if(a===void 0&&(e.method??"GET").toUpperCase()==="GET"&&(e.url??"").split("?")[0]==="/healthz")return{principal:q,ceiling:null};if(typeof a!="string"||!a.startsWith("Bearer "))return k(o,a===void 0?"no_authorization_header":"not_a_bearer");const u=a.slice(7);if(u.startsWith("crtr_pub_"))return{principal:q,ceiling:null};if(u.startsWith(ee))return be(u)??k(o,"app_token_unknown");if(u.startsWith(lt)){const w=await ct(u);return w===null?k(o,"run_token_invalid_or_settled"):{principal:w,ceiling:null}}const d=r.get(u);if(d!==void 0)return d;const R=Le(u);if(R!==null)return{principal:R,ceiling:null};if(u.startsWith(He))return k(o,"import_token_invalid");if(St.test(u)){if(H()&&Et(u)){const x=j();if(x===null)return"person_bearer";try{const v=await x.verifyCall(a);return v.chain[0]?.sub.startsWith("app:")?{call:v}:k(o,"call_token_presenter_not_an_app")}catch(v){return v instanceof S&&v.status===503?"runtime_starting":k(o,`call_token_${v instanceof S?v.code:"invalid"}`)}}const w=H()?pe():null;if(w===null)return"person_bearer";const U=await w.verify(u);return U===null?k(o,"person_bearer_not_verified"):{principal:{class:"person",sub:U},ceiling:null}}const m=await we(u,null);return m==="unauthorized"?k(o,"node_token_unknown"):typeof m=="string"?m:{principal:m,ceiling:null}}n(Te,"authorizeTcp");let W;function j(){if(W!==void 0)return W;const e=process.env.CRTR_DIRECTORY_URL||void 0,r=process.env.CRTR_PUBLIC_API_URL||void 0;return W=e===void 0||r===void 0?null:new Je(e,r,async()=>{}),W}n(j,"cloudCallResolver");let Ce;function bt(){const e=j();if(e===null)throw new S(503,"runtime_starting","app calls are not configured on this listener");return Ce??=We(e,async()=>!0,async()=>{}),Ce}n(bt,"cloudAppCalls");async function Tt(e,r){N(r),I(r);const o=j();try{if(o===null)throw new S(503,"runtime_starting","sign-in is not configured on this listener");await Ve(e,r,new URL(e.url??"/","http://runtime.local"),o)}catch(a){if(!(a instanceof S))throw a;if(r.headersSent){r.destroy();return}r.writeHead(a.status,{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}),r.end(JSON.stringify({error:{code:a.code,message:a.message,...a.param?{param:a.param}:{},origin:"runtime"}}))}}n(Tt,"serveRuntimeSignIn");function Ct(){const e=process.env.CRTRD_TLS_CERT||void 0,r=process.env.CRTRD_TLS_KEY||void 0;if(e===void 0&&r===void 0)return null;if(e===void 0||r===void 0)throw new Error("CRTRD_TLS_CERT and CRTRD_TLS_KEY must be set together");return{cert:se(e),key:se(r)}}n(Ct,"tcpTls");function N(e){e.setHeader(Y,X()),e.setHeader(K,ce)}n(N,"advertiseRuntime");function I(e){e.setHeader("Access-Control-Allow-Origin","*"),e.setHeader("Access-Control-Expose-Headers",`${Y}, ${K}`)}n(I,"exposeRuntimeHeaders");function kt(e,r){return(e.method??"GET").toUpperCase()!=="OPTIONS"?!1:(N(r),r.writeHead(204,{"Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":`${Y}, ${K}`,"Access-Control-Allow-Headers":`authorization, content-type, ${le.toLowerCase()}, ${ue.toLowerCase()}`,"Access-Control-Allow-Methods":"GET, POST, PATCH, PUT, DELETE, OPTIONS","Access-Control-Max-Age":"600"}),r.end(),!0)}n(kt,"answerPreflight");function V(e,r=!1){N(e),r&&I(e),e.writeHead(401,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{...P,origin:"runtime"}}))}n(V,"writeUnauthorized");function Ut(e){N(e),I(e),e.writeHead(401,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{...M,origin:"runtime"}}))}n(Ut,"writePersonBearerRefused");const Ot={"/v1/runtime/vendor-status":{method:"GET",purpose:"vendor_status"},"/v1/runtime/vendor-account-remove":{method:"POST",purpose:"vendor_account_remove"}};async function Pt(e,r){if(!H())return!1;const o=new URL(e.url??"/","http://runtime.local").pathname,a=Ot[o];if(a===void 0||e.method!==a.method)return!1;const u=n((d,R)=>{N(r),I(r),r.writeHead(d,{"content-type":"application/json; charset=utf-8"}),r.end(JSON.stringify(R))},"answer");try{const d=pe();if(d===null)throw new S(401,M.code,M.message);const R=e.headers.authorization,m=R?.startsWith("Bearer ")?await d.verifyPurpose(R.slice(7),a.purpose):null;if(m===null)throw new S(401,"unauthorized","invalid directory token");const w=a.purpose==="vendor_status"?void 0:await Nt(e);u(200,await J(m,async()=>a.purpose==="vendor_status"?Ke():await Ye(w)))}catch(d){const{status:R,body:m}=Xe(d);u(R,m)}return!0}n(Pt,"serveCloudVendorRoute");async function Nt(e){const r=[];let o=0;for await(const a of e){if(o+=a.length,o>Ze)throw new S(400,"invalid_request","request body too large");r.push(a)}if(o!==0)try{return JSON.parse(Buffer.concat(r).toString("utf8"))}catch{throw new S(400,"invalid_request","invalid JSON body")}}n(Nt,"readVendorBody");function ke(e){N(e),e.writeHead(503,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{code:"runtime_starting",message:"grant sync is not ready",type:"server_error",origin:"runtime",retryable:!0}}))}n(ke,"writeRuntimeStarting");function It(e,r){e.writeHead(503,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{code:"startup_blocked",message:r,origin:"runtime"}}))}n(It,"writeStartupBlocked");function Ue(e,r,o){return new Promise(a=>{for(const m of r)m.destroy();if(o===void 0){try{e.closeAllConnections()}catch{}e.close(()=>a());return}const u=[];e.close(()=>{for(const m of u)clearTimeout(m);a()});const d=setInterval(()=>e.closeIdleConnections(),250),R=setTimeout(()=>e.closeAllConnections(),o);u.push(d,R),e.closeIdleConnections()})}n(Ue,"closeServer");function vo(e={}){let r=null;const o=At(()=>r),a=new fe().registerAll(he).registerAll(Ae).registerAll(Re).registerAll(ye),u=n((t,i)=>{const c=fr()?.startupBlock()??null;return c===null||t==="GET"&&(i==="/healthz"||i==="/v1/status"||i==="/v1/ready")||t==="POST"&&(i==="/v1/daemon/migrate"||i==="/v1/daemon/admit")||c.phase==="recovering"&&a.match(t,i)!==null?null:c},"startupBlockFor"),d=e.socketPath??Fe(),R=new Set([process.getuid?.()??0,...de("user").runtime?.person_uids??[]]),m=n((t,i,c)=>{N(i);const p=n(s=>Array.isArray(s)?s[0]:s,"first"),O=p(t.headers[le.toLowerCase()]),h=De(O,X())??Me(p(t.headers[ue.toLowerCase()]),ce,{legacyMinimum:O,runtimeVersion:X()});if(h!==null){i.writeHead(h.status,{"content-type":"application/json; charset=utf-8"}),i.end(JSON.stringify({error:{code:h.code,message:h.message,type:"invalid_request_error",origin:"runtime",retryable:!1,..."param"in h?{param:h.param}:{details:h.details}}}));return}const E=n(s=>{const l=F(t);A({event:"api.request.failed",level:"error",...l?.class==="broker"?{node_id:l.node}:{},error:s instanceof Error?s:new Error(String(s))});try{i.headersSent||i.writeHead(500,{"content-type":"application/json; charset=utf-8"}),i.end(JSON.stringify({error:{code:"internal",message:"internal error",origin:"runtime"}}))}catch{}},"internalFailure");let T;try{T=new URL(t.url??"/","http://127.0.0.1")}catch{try{i.writeHead(400,{"content-type":"application/json; charset=utf-8"}),i.end(JSON.stringify({error:{code:"invalid_request",message:"request URL is invalid",origin:"runtime"}}))}catch{}return}try{const s=u((t.method??"GET").toUpperCase(),T.pathname);if(s!==null){It(i,s.message);return}const l=F(t)??{class:"person"},f=Ee(l),g=n(()=>o.handle(t,i,c,l),"handled");(f===void 0?g():J(f,n(async()=>{Z()||await Q(f),await g()},"handledAsPerson"))).catch(E)}catch(s){E(s)}},"onRequest"),w=n(async(t,i,c)=>{const p=F(t);return p===void 0||me(p)||await ge(p,"either",c)?!0:(y(i,404,"Not Found","node_not_found",`no node ${c}`),!1)},"authorizeAttachUpgrade"),U=new Set,x=n(t=>{U.add(t),t.once("close",()=>U.delete(t)),t.on("error",()=>{})},"trackUpgrade"),v=n((t,i,c)=>{try{const p=new URL(t.url??"/","http://127.0.0.1"),O=u((t.method??"GET").toUpperCase(),p.pathname);if(O!==null){y(i,503,"Service Unavailable","startup_blocked",O.message);return}const h=yt(t.method??"GET",p.pathname);if(h===null){i.destroy();return}const E=(()=>{const s=F(t);return s===void 0?void 0:Ee(s)})(),T=n(()=>w(t,i,h).then(s=>s?ar(t,i,c,h,async l=>{const f=F(t);return f===void 0||me(f)||await ge(f,l,h)}):void 0),"attach");(E===void 0?T():J(E,async()=>{Z()||await Q(E),await T()})).catch(()=>{try{i.destroy()}catch{}})}catch{try{i.destroy()}catch{}}},"onUpgrade"),Oe=n(t=>{t.on("error",i=>{A({event:"api.server.failed",level:"error",error:i})})},"bindErrorHandler"),Pe=n(async(t,i)=>{try{const c=await ve(t,R);if(c==="unauthorized"){A({event:"api.principal.denied",level:"warn",fields:{method:t.method}}),V(i);return}if(c==="runtime_starting"){ke(i);return}B.set(t,c),Se(t,c),m(t,i,c.class==="app"?c.scopes:null)}catch(c){A({event:"api.principal.failed",level:"error",error:c instanceof Error?c:new Error(String(c))}),V(i)}},"onSocketRequest"),D=ie((t,i)=>{Pe(t,i).catch(c=>A({event:"api.principal.failed",level:"error",error:c instanceof Error?c:new Error(String(c))}))}),Ne=n(async(t,i,c)=>{try{const p=await ve(t,R);if(p==="unauthorized"||p==="runtime_starting"){p==="unauthorized"&&A({event:"api.principal.denied",level:"warn",fields:{method:t.method}}),y(i,p==="unauthorized"?401:503,"Unauthorized",p,"socket principal unavailable");return}if(p.class!=="person"&&p.class!=="broker"){y(i,403,"Forbidden",L.code,L.message);return}B.set(t,p),v(t,i,c)}catch(p){A({event:"api.principal.failed",level:"error",error:p instanceof Error?p:new Error(String(p))}),y(i,401,"Unauthorized",P.code,P.message)}},"onSocketUpgrade");D.on("upgrade",(t,i,c)=>{x(i),Ne(t,i,c).catch(p=>A({event:"api.principal.failed",level:"error",error:p instanceof Error?p:new Error(String(p))}))}),_e((t,i,c)=>{B.set(t,c),m(t,i,null)});let re=!1,te,ne;const Ie=new Promise((t,i)=>{te=t,ne=i});D.once("listening",()=>{re=!0,te()}),D.on("error",t=>{A({event:"api.server.failed",level:"error",error:t}),re||ne(t)});try{G(d)&&ae(d)}catch{}D.listen(d,()=>{try{xe(d,process.platform==="linux"&&G("/run/crtr/launcher.sock")?438:384)}catch(t){A({event:"api.socket.chmod_failed",level:"error",error:t instanceof Error?t:new Error(String(t))})}});let b;const $=e.tcp??ir()??de("user").api.tcp;if($!==void 0&&$!==""){const t=_t($);if(t===null)A({event:"api.tcp.invalid",level:"error",error:new Error(`invalid CRTRD_TCP/--tcp spec: ${$}`)});else{H()&&j();const i=e.token??sr()??nr("user"),c=wt(i),p=n(async(s,l)=>{if(kt(s,l))return;if(H()&&Ge(new URL(s.url??"/","http://runtime.local").pathname)){await Tt(s,l);return}if(await Pt(s,l))return;const f={},g=await Te(s,c,f);if(g==="runtime_starting"){I(l),ke(l);return}if(g==="person_bearer"){Ut(l);return}if(g==="unauthorized"){A({event:"api.principal.denied",level:"warn",fields:{method:s.method,listener:"tcp",path:new URL(s.url??"/","http://runtime.local").pathname,reason:f.reason??"unknown"}}),V(l,!0);return}if("call"in g){I(l);const z=g.call.sub;await J(z,async()=>{Z()||await Q(z),await bt()(s,l,g.call)});return}B.set(s,g.principal),Se(s,g.principal),I(l),m(s,l,g.ceiling)},"tcpOnRequest"),O=n(async(s,l,f)=>{const g=cr(s);if(g!==null){const _=await lr(s,l,f,g);_!==null&&y(l,_.status,_.text,_.code,_.message);return}const z=dr(s);if(z!==null){const _=pr(s,l,f,z);_!==null&&y(l,_.status,_.text,_.code,_.message);return}const C=await Te(s,c);if(C==="runtime_starting"){y(l,503,"Service Unavailable","runtime_starting","grant sync is not ready");return}if(C==="person_bearer"){y(l,401,"Unauthorized",M.code,M.message);return}if(C==="unauthorized"){y(l,401,"Unauthorized",P.code,P.message);return}if("call"in C){y(l,403,"Forbidden",L.code,L.message);return}if(C.ceiling!==null||C.principal.class==="anonymous"||C.principal.class==="import"){y(l,403,"Forbidden",L.code,L.message);return}B.set(s,C.principal),v(s,l,f)},"tcpOnUpgrade"),h=n(s=>{A({event:"api.principal.failed",level:"error",error:s instanceof Error?s:new Error(String(s))})},"failed"),E=n((s,l)=>{p(s,l).catch(f=>{h(f),l.headersSent?l.destroy():V(l,!0)})},"listener"),T=Ct();b=T===null?ie(E):Be(T,E),b.on("upgrade",(s,l,f)=>{x(l),O(s,l,f).catch(g=>{h(g),y(l,401,"Unauthorized",P.code,P.message)})}),Oe(b),b.once("listening",()=>{const s=b?.address();if(s!==null&&typeof s=="object"){const{address:l,port:f}=s;r=vt(l,f),l!=="0.0.0.0"&&l!=="::"&&ur(r)}}),b.listen(t.port,t.host)}}let oe=!1;return{ready:Ie,tcpAddress:n(()=>r,"tcpAddress"),close:n(async(t={})=>{if(!oe){oe=!0,_e(null),_r.close(),await Promise.all([Ue(D,U,t.graceMs),b!==void 0?Ue(b,U,t.graceMs):Promise.resolve()]);try{G(d)&&ae(d)}catch{}}},"close")}}n(vo,"createApiServer");export{At as buildRouter,Ue as closeServer,vo as createApiServer,F as socketPrincipal};
@@ -1,19 +1,19 @@
1
- var ir=Object.defineProperty;var a=(e,l)=>ir(e,"name",{value:l,configurable:!0});import{applyBootSettings as ar}from"./boot-settings.js";import{startPeerOutbox as sr}from"./peer/outbox.js";import{reportMachineStatus as cr}from"../core/peer/directory.js";import{createPeerRelay as lr}from"./peer/relay-service.js";import{writeFileSync as dr,readFileSync as mr,rmSync as pr,mkdirSync as Re,existsSync as R,unlinkSync as Pe,chmodSync as Ee}from"node:fs";import{createServer as Y}from"node:http";import{dirname as fr}from"node:path";import{envCrtrdTcp as Ie,envDocumentPort as ur}from"../shared/env.js";import{openCanvasConversationStore as wr,serveCanvasConversationStore as hr}from"../core/canvas/sessions.js";import{installConversationStore as vr}from"../core/conversation-store/index.js";import{pollRunObservers as gr}from"./runs/observer.js";import{randomBytes as xe}from"node:crypto";import{apiSocketPath as De,crtrHome as Sr}from"../core/canvas/paths.js";import{activeAppUsers as yr}from"../core/spaces/users.js";import{ensureAppSpace as _r,ensureUserFiles as br}from"../core/spaces/space.js";import{LAUNCHER_SOCKET as D}from"../launcher/spec.js";import{launcherRequest as $}from"../launcher/client.js";import{installLauncherEventSink as kr}from"./launcher-events.js";import{initializeEmptyLayout as Rr,layoutNeedsMigration as Pr,socketDir as Te}from"../core/layout.js";import{migrateLooseKeys as Er}from"../core/layout-migrate/loose-keys.js";import{relocateProfileFolders as Ir}from"../core/profiles/relocate.js";import{getNode as xr,listNodesForSupervision as Ce,listParkedResidentsWithWakeMail as Dr,setFrozen as Le}from"../core/canvas/index.js";import{createApiServer as Tr,closeServer as Ae}from"./api/server.js";import{Router as Cr}from"./api/router.js";import{healthRoutes as Lr}from"./api/handlers/health.js";import{createDocumentListener as Ar}from"./api/document-listener.js";import{documentSecret as $r}from"./api/document-secret.js";import{createAppListener as Nr}from"./api/app-listener.js";import{registerMachineEnvironment as Mr}from"../core/environments.js";import{registerBlaxelRunnerFromEnv as Gr}from"../core/secrets/blaxel-register.js";import{markCloudRole as Or,resolvePerson as Fr,retireLocalPerson as Br,setPersonId as Hr}from"../core/canvas/person.js";import{backfillNodeApps as $e,runPermissionsBoot as jr}from"../core/permissions/boot.js";import{startRunNotices as zr}from"./run-notices.js";import{startGrantEffects as Ur}from"./reconcilers/grant-effects.js";import{syncPackages as qr}from"../core/packages/directory-sync.js";import{startActivationDelivery as Wr}from"../core/model-auth/activations.js";import{createGrantSync as Jr,GRANT_SYNC_INTERVAL_S as Ne}from"../core/grants/sync.js";import{sweepSandboxes as Kr}from"../core/grants/on-sync.js";import{rebuildCronExecutions as Vr}from"./cron/run-socket.js";import{hasSyncedGrants as Yr}from"../core/grants/mirror.js";import{readConfig as de}from"../core/config.js";import{reconcileUndeliveredTickets as Qr}from"./human/sweep.js";import{resetHandedOffDeliveries as Xr}from"../core/canvas/deliveries.js";import{resetHandedOffDaemonActions as Zr}from"../core/canvas/daemon-actions.js";import{sweepReviews as et}from"./review/sweep.js";import{pidfilePath as me}from"./pidfile.js";import{rendererWarning as rt}from"../core/runtime/package-health.js";import{DEFAULT_INTERVAL_MS as tt}from"./supervise-cadence.js";import{createResumeDetector as nt}from"./resume-detector.js";import{setFatalFaultAnnouncer as ot}from"../core/canvas/recovery.js";import{BrokerSupervisionReconciler as it}from"./reconcilers/broker-supervision.js";import{ControllerDeathReconciler as at}from"./reconcilers/controller-death.js";import{NodeLifecycleReconciler as st}from"./reconcilers/node-lifecycle/tick.js";import{NodeDeadlineReconciler as ct}from"./reconcilers/node-deadline.js";import{CronLaneReconciler as lt}from"./reconcilers/cron-lane.js";import{DeliveryLaneReconciler as dt}from"./reconcilers/delivery-lane.js";import{ActionLaneReconciler as mt}from"./reconcilers/action-lane.js";import{endLiveExecution as pt,migrateLegacyExecutionIdentities as ft}from"../core/canvas/executions.js";import{revokePriorEpochNodeTokens as ut}from"../core/canvas/node-tokens.js";import{PendingReviewSubmitReconciler as wt}from"./reconcilers/pending-review-submit.js";import{StorageMaintenanceReconciler as ht}from"./reconcilers/storage-maintenance.js";import{StorageDueWorkReconciler as vt}from"./reconcilers/storage-due-work.js";import{PurgeDueWorkReconciler as gt}from"./reconcilers/purge-due-work.js";import{assertLedgerEnv as St}from"../core/ledger/rates.js";import{LedgerSandboxReconciler as yt}from"./reconcilers/ledger-sandbox.js";import{LedgerStorageReconciler as _t}from"./reconcilers/ledger-storage.js";import{LedgerR2Reconciler as bt}from"./reconcilers/ledger-r2.js";import{ImportLaneReconciler as kt}from"./reconcilers/import-lane.js";import{BashDeadlineReconciler as Rt}from"./reconcilers/bash-deadline.js";import{FaultRetryBackstopReconciler as Pt}from"./reconcilers/fault-retry-backstop.js";import{StructuredRequestReconciler as Et}from"./reconcilers/structured-request-lane.js";import{RecipeImageReconciler as It,subscribeImageBuilt as xt}from"./reconcilers/recipe-image.js";import{reconcileStructuredRequestSidecars as Dt}from"./structured-requests/boot.js";import{captureLivenessSnapshot as Me,capturePidCommand as Tt,captureTeardownSnapshot as Ge,isPidAlive as Ct,isAnyPidAlive as Oe,killProcessTreePids as Fe}from"../core/canvas/pid.js";import{bindFleet as Lt,boundFleet as At}from"../core/runtime/fleet.js";import{bindDaemonControl as $t,clearDaemonControl as Nt}from"./control.js";import{execDaemon as Mt,spawnDaemon as Gt}from"./manage.js";import{reconcileAndMigrateBoot as Ot}from"../core/canvas/boot.js";import{resolveInstallId as Ft}from"../core/canvas/install-id.js";import{setInstallId as Bt}from"../core/runtime/nodes.js";import{claimDaemonOwnership as Ht,daemonOwnershipApplies as jt,daemonOwnershipClaimed as zt,releaseDaemonOwnership as Be}from"../core/canvas/daemon-owner.js";import{canvasDatabaseUrl as Ut,closeAllDbs as pe,openDb as He,withCanvasWrite as fe}from"../core/canvas/db.js";import{importSqliteCanvasIfPresent as qt}from"../core/canvas/import-sqlite.js";import{ensurePostgres as Wt,ensurePostgresHealthy as Jt,stopPostgres as Kt,withPostgresStartLock as Vt}from"./postgres/index.js";import{brokerSignalBus as H}from"./broker-signals/bus.js";import{brokerSignalStreams as Yt}from"./api/handlers/broker-signals.js";import{setRequestsStartRunObservers as Qt}from"./api/handlers/broker-ops.js";import{reconcilePackages as Xt}from"../core/graph/package-reconcile.js";import{migrateAppInstalls as Zt}from"../core/scoped-state/migrate-app-installs.js";import{publish as en,readBuiltinSnapshot as rn}from"../core/graph/package-publish.js";import{startRepoSync as tn}from"../core/graph/repo-sync/index.js";import{prewarmRecentRecipes as nn,reapStaleSpares as on}from"../core/runtime/warm-pool.js";import{DaemonFleet as an}from"./fleet.js";import{copyNodeFilesToRows as sn}from"../core/runtime/first-boot-rows.js";import{BOOT_MIGRATIONS as cn}from"./boot-migrations.js";import{emitEvent as m}from"../core/events/emit.js";import{operationIdContext as _}from"../core/events/operation-id.js";import{bindDaemonEventSource as ln}from"../core/events/source.js";import{activateCanvasImport as dn,MigrationBlockedError as mn,runForcedCanvasImport as pn}from"../migrations/activation.js";import{adoptInstallPerson as fn,convertLegacyScopedStore as un,personStoresCopied as wn}from"../core/scoped-state/migrate.js";import{readLegacyUserSnapshot as hn}from"../core/scoped-state/legacy-profiles.js";import{heldPersons as je,installPreludeSnapshot as vn}from"../core/scoped-state/person-store.js";import{loadPersonSettings as ze}from"../core/scoped-state/person-rows.js";import{userScopeRoot as Ue}from"../core/scope.js";import{brokerCommandDeclaresCanvasHome as ue}from"../core/runtime/broker-ownership.js";import{brokerCommandDeclaresCanvasHome as Vi}from"../core/runtime/broker-ownership.js";function we(e){return/ --epoch (\S+) /.exec(e)?.[1]??null}a(we,"brokerCommandEpoch");const gn=5e3,qe=150;async function Sn(e){const l=Me();if(l===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 u=Sr(),f=[];for(const[n,d]of l.processes){const y=d.command;if(d.zombie||!y.includes("broker-cli.js")||!ue(y,u)||we(y)===e)continue;const P=y.trim().split(/\s+/).at(-1)??"";P===""||P.endsWith("broker-cli.js")||f.push({pid:n,nodeId:P})}let v=0;const s=[];for(const n of f){const d=Tt(n.pid);if(d===null||!d.includes("broker-cli.js")||!ue(d,u)||we(d)===e||d.trim().split(/\s+/).at(-1)!==n.nodeId)continue;const y=Ge(n.pid,null);if(!y.reused){try{process.platform==="linux"&&R(D)?await $({operation:"stop",pid:n.pid}):process.kill(n.pid,"SIGTERM")}catch{continue}v++,s.push({pid:n.pid,snap:y})}}const w=Date.now()+gn;for(;Date.now()<w&&s.some(n=>Oe(n.snap.tree.length>0?n.snap.tree:[n.pid]));)await new Promise(n=>setTimeout(n,qe));let g=0;for(const n of s){const d=n.snap.tree.length>0?n.snap.tree:[n.pid];Oe(d)&&(process.platform==="linux"&&R(D)?await $({operation:"stop",pid:n.pid}):Fe(d,"SIGKILL",n.snap.identities),g++)}g>0&&await new Promise(n=>setTimeout(n,qe));const p=Me();if(p===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 c=[];for(const[n,d]of p.processes){const y=d.command;d.zombie||!y.includes("broker-cli.js")||ue(y,u)&&we(y)!==e&&c.push(n)}if(c.length>0)throw new Error(`prior-epoch broker census could not prove termination of pid(s): ${c.join(", ")}`);m({level:"info",event:"daemon.census.completed",fields:{prior_epoch_brokers:f.length,sigtermed:v,sigkilled:g}})}a(Sn,"reapPriorEpochBrokers");const yn=5e3;async function _n(e){const l=Array.from(e.entries());if(l.length===0)return;for(const[s]of l){const w=(await xr(s))?.status;(w==="active"||w==="idle")&&await Le(s,new Date().toISOString())}const u=l.map(([,s])=>({pid:s.pid,snap:Ge(s.pid,null),exited:s.handle.exited}));for(const s of u)if(!s.snap.reused)try{process.platform==="linux"&&R(D)?await $({operation:"stop",pid:s.pid}):process.kill(s.pid,"SIGTERM")}catch{}const f=new Promise(s=>{setTimeout(s,yn).unref()});await Promise.allSettled(u.map(s=>Promise.race([s.exited.then(()=>{}),f])));const v=[];for(const s of u)Ct(s.pid)&&(process.platform==="linux"&&R(D)?await $({operation:"stop",pid:s.pid}):Fe(s.snap.tree.length>0?s.snap.tree:[s.pid],"SIGKILL",s.snap.identities),v.push(s));await Promise.all(v.map(s=>s.exited));for(const[s]of l)await pt(s,{reason:"daemon-teardown"});m({level:"info",event:"daemon.fleet_teardown.completed",fields:{brokers:u.length,sigkilled:v.length}})}a(_n,"teardownFleet");function We(){Re(fr(me()),{recursive:!0}),dr(me(),String(process.pid),"utf8")}a(We,"writePidfile");function Je(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}a(Je,"isMissingPathError");function Ke(e){const l=me();let u;try{u=mr(l,"utf8")}catch(f){if(Je(f))return;throw f}if(u.trim()!==String(e))throw new Error(`daemon readiness mirror does not name this invocation (expected pid ${e})`);try{pr(l)}catch(f){if(Je(f))return;throw f}}a(Ke,"removeOwnedPidfileMirror");const bn={acceptsDetachedWork:a(()=>!0,"acceptsDetachedWork"),registerDetached:a(e=>{e.catch(()=>{})},"registerDetached")},Q=new it;ot(e=>Q.handleFatalFault(e,!1));const kn=new at,Rn=new st,Pn=new ct,En=new lt,In=new dt,xn=new mt,Dn=new wt,Tn=new ht,Cn=new vt,Ln=new gt,An=new yt,$n=new _t,Nn=new bt,Mn=new kt,Gn=new Rt,On=new Pt,Fn=new Et,Bn=new It;async function Hn(e=Date.now(),l=bn){const u=At(),f=await Q.runFleetPreamble(u);let v,s;try{const g=await Ce();v=g.filter(c=>c.status==="active"||c.status==="idle"),s=g.filter(c=>c.status==="done"||c.status==="canceled"||c.status==="dead");const p=new Set(s.map(c=>c.node_id));s.push(...(await Dr()).filter(c=>!p.has(c.node_id)))}catch(g){m({level:"error",event:"canvas.node_list.failed",error:g});return}await Q.run(e,{rows:v,fleet:u,lifecycle:l}),await kn.run(e,{rows:v});const w=await Rn.run(e,{rows:[...v,...s],fleet:u});await Pn.run(e),await Fn.run(e),await Bn.run(e,{lifecycle:l}),await En.run(e,{lifecycle:l}),await In.run(e,{lifecycle:l}),await xn.run(e,{lifecycle:l}),await Dn.run(e,{lifecycle:l}),await Tn.run(e,{lifecycle:l,fleet:u}),Cn.run(e,{lifecycle:l}),Ln.run(e,{lifecycle:l}),An.run(e,{lifecycle:l}),$n.run(e,{lifecycle:l}),Nn.run(e,{lifecycle:l}),Mn.run(e,{lifecycle:l}),await gr(),On.run(e,{fleet:u,lifecycle:l}),await Gn.run(e,{rows:v}),Q.warnIfSaturated({fleet:u,lifecycle:l,thresholds:f,frozen:w})}a(Hn,"superviseTick");function j(e){return e===void 0||e==="reconcile"}a(j,"roleRunsLanes");function N(e){return e===void 0||e==="api"}a(N,"roleServesRequests");const jn=66e4;function zn(e){const l=new Cr().registerAll(Lr(()=>null).filter(n=>n.pattern==="/healthz")),u=a((n,d)=>{const y=(n.url??"/").split("?")[0];if((n.method??"GET").toUpperCase()==="GET"&&y==="/healthz"){l.handle(n,d,null,{class:"person"});return}d.writeHead(404,{"content-type":"application/json; charset=utf-8"}),d.end(JSON.stringify({error:{code:"not_found",message:"this process serves only /healthz",origin:"runtime"}}))},"handler"),f=De();R(f)&&Pe(f);const v=Y(u),s=new Promise((n,d)=>{v.once("error",d),v.listen(f,()=>{v.off("error",d),Ee(f,384),n()})});let w,g=null;const p=e.tcp??Ie()??de("user").api.tcp;if(p!==void 0&&p!==""){const n=/^(.*):(\d+)$/.exec(p.trim());if(n===null||Number(n[2])>65535)throw new Error(`invalid reconcile probe TCP address: ${p}`);const d=Y(u);d.on("error",y=>m({event:"api.server.failed",level:"error",error:y})),d.listen(Number(n[2]),n[1]===""?"0.0.0.0":n[1],()=>{g=`${n[1]===""?"0.0.0.0":n[1]}:${n[2]}`}),w=d}let c=!1;return{ready:s,tcpAddress:a(()=>g,"tcpAddress"),async close(n={}){if(!c){c=!0,await Promise.all([Ae(v,new Set,n.graceMs),w===void 0?Promise.resolve():Ae(w,new Set,n.graceMs)]);try{R(f)&&Pe(f)}catch{}}}}}a(zn,"createProbeServer");const Un="daemon is draining for shutdown and admits no new work";async function qn(e){Re(Te(),{recursive:!0,mode:493}),process.platform==="linux"&&Ee(Te(),493);const l=De();if(R(l))throw new Error(`layout refusal cannot bind occupied socket: ${l}`);const u=Y((p,c)=>{if(p.method==="GET"&&p.url==="/healthz"){c.writeHead(200,{"content-type":"application/json; charset=utf-8"}),c.end(JSON.stringify({ok:!1,daemon_up:!0,store_accessible:!1,brokers_reconciled:!1,startup_phase:"blocked",startup_blocked:"layout_migration_required"}));return}c.writeHead(503,{"content-type":"application/json; charset=utf-8"}),c.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((p,c)=>{u.once("error",c),u.listen(l,()=>{u.off("error",c),p()})});let f;const v=e.tcp??Ie();if(v){const p=/^(.*):(\d+)$/.exec(v);if(!p||Number(p[2])>65535)throw new Error(`invalid refusal TCP address: ${v}`);const c=Y(u.listeners("request")[0]);await new Promise((n,d)=>{c.once("error",d),c.listen(Number(p[2]),p[1],()=>{c.off("error",d),n()})}),f=c}We();let s;const w=a(()=>(s??=(async()=>{u.closeAllConnections(),f?.closeAllConnections(),await Promise.all([u,f].filter(p=>p!==void 0).map(p=>new Promise((c,n)=>p.close(d=>d?n(d):c())))),Ke(process.pid),process.off("SIGINT",g),process.off("SIGTERM",g)})(),s),"cleanup"),g=a(()=>{w().then(()=>process.exit(0),p=>{process.stderr.write(`[crtrd] layout refusal cleanup failed: ${String(p)}
2
- `),process.exit(1)})},"onSignal");return process.on("SIGINT",g),process.on("SIGTERM",g),w}a(qn,"serveLayoutRefusal");async function Wn(e={}){if(e.role==="machine")return(await import("./machine-daemon.js")).runMachineDaemon();if(Pr())return qn(e);Rr();const l=a(t=>{process.stderr.write(`[crtrd] ${t}
3
- `)},"logPostgres"),u=!!process.env.CRTR_TEST_PG_URL,f=jt(e.role);Qt(j(e.role));const v=a(async()=>f?await Ht(xe(16).toString("hex")):{claimed:!0,claim:{pid:process.pid,pid_identity:"",token:xe(16).toString("hex")}},"claimOwnership"),{database:s,ownership:w}=u?{database:{url:await Ut()},ownership:await v()}:await Vt(async()=>({database:await Wt({log:l,startLockHeld:!0}),ownership:await v()}));if(!w.claimed){if(w.reason==="incumbent_alive")process.stderr.write(`[crtrd] already running (pid ${w.incumbentPid??"?"})
4
- `);else{const t=[w.incumbentPid!==void 0?`pid ${w.incumbentPid}`:void 0,w.verdict!==void 0?`verdict ${w.verdict}`:void 0].filter(h=>h!==void 0),i=t.length>0?` (${t.join(", ")})`:"";process.stderr.write(`[crtrd] claim lost: ${w.reason}${i}
5
- `),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 g=w.claim;let p=null,c=null,n=null,d=null,y,P="";try{f&&await Sn(g.token);for(const r of Ir())process.stderr.write(`[crtrd] ${r}
1
+ var ir=Object.defineProperty;var a=(e,l)=>ir(e,"name",{value:l,configurable:!0});import{applyBootSettings as ar}from"./boot-settings.js";import{startPeerOutbox as sr}from"./peer/outbox.js";import{reportMachineStatus as cr}from"../core/peer/directory.js";import{createPeerRelay as lr}from"./peer/relay-service.js";import{writeFileSync as dr,readFileSync as mr,rmSync as pr,mkdirSync as Re,existsSync as R,unlinkSync as Pe,chmodSync as Ee}from"node:fs";import{createServer as Y}from"node:http";import{dirname as fr}from"node:path";import{envCrtrdTcp as Ie,envDocumentPort as ur}from"../shared/env.js";import{openCanvasConversationStore as hr,serveCanvasConversationStore as wr}from"../core/canvas/sessions.js";import{installConversationStore as vr}from"../core/conversation-store/index.js";import{pollRunObservers as gr}from"./runs/observer.js";import{randomBytes as xe}from"node:crypto";import{apiSocketPath as De,crtrHome as Sr}from"../core/canvas/paths.js";import{activeAppUsers as yr}from"../core/spaces/users.js";import{ensureAppSpace as _r,ensureUserFiles as br}from"../core/spaces/space.js";import{LAUNCHER_SOCKET as D}from"../launcher/spec.js";import{launcherRequest as A}from"../launcher/client.js";import{installLauncherEventSink as kr}from"./launcher-events.js";import{initializeEmptyLayout as Rr,layoutNeedsMigration as Pr,socketDir as Te}from"../core/layout.js";import{migrateLooseKeys as Er}from"../core/layout-migrate/loose-keys.js";import{relocateProfileFolders as Ir}from"../core/profiles/relocate.js";import{getNode as xr,listNodesForSupervision as Ce,listParkedResidentsWithWakeMail as Dr,setFrozen as Le}from"../core/canvas/index.js";import{createApiServer as Tr,closeServer as $e}from"./api/server.js";import{Router as Cr}from"./api/router.js";import{healthRoutes as Lr}from"./api/handlers/health.js";import{createDocumentListener as $r}from"./api/document-listener.js";import{documentSecret as Ar}from"./api/document-secret.js";import{createAppListener as Nr}from"./api/app-listener.js";import{registerMachineEnvironment as Mr}from"../core/environments.js";import{registerBlaxelRunnerFromEnv as Gr}from"../core/secrets/blaxel-register.js";import{markCloudRole as Or,resolvePerson as Fr,retireLocalPerson as Br,setPersonId as Hr}from"../core/canvas/person.js";import{backfillNodeApps as Ae,runPermissionsBoot as jr}from"../core/permissions/boot.js";import{startRunNotices as zr}from"./run-notices.js";import{startGrantEffects as Ur}from"./reconcilers/grant-effects.js";import{syncPackages as qr}from"../core/packages/directory-sync.js";import{startActivationDelivery as Wr}from"../core/model-auth/activations.js";import{createGrantSync as Jr,GRANT_SYNC_INTERVAL_S as Ne}from"../core/grants/sync.js";import{sweepSandboxes as Kr}from"../core/grants/on-sync.js";import{rebuildCronExecutions as Vr}from"./cron/run-socket.js";import{hasSyncedGrants as Yr}from"../core/grants/mirror.js";import{readConfig as de}from"../core/config.js";import{reconcileUndeliveredTickets as Qr}from"./human/sweep.js";import{resetHandedOffDeliveries as Xr}from"../core/canvas/deliveries.js";import{resetHandedOffDaemonActions as Zr}from"../core/canvas/daemon-actions.js";import{sweepReviews as et}from"./review/sweep.js";import{pidfilePath as me}from"./pidfile.js";import{rendererWarning as rt}from"../core/runtime/package-health.js";import{DEFAULT_INTERVAL_MS as tt}from"./supervise-cadence.js";import{createResumeDetector as nt}from"./resume-detector.js";import{setFatalFaultAnnouncer as ot}from"../core/canvas/recovery.js";import{BrokerSupervisionReconciler as it}from"./reconcilers/broker-supervision.js";import{ControllerDeathReconciler as at}from"./reconcilers/controller-death.js";import{NodeLifecycleReconciler as st}from"./reconcilers/node-lifecycle/tick.js";import{NodeDeadlineReconciler as ct}from"./reconcilers/node-deadline.js";import{CronLaneReconciler as lt}from"./reconcilers/cron-lane.js";import{DeliveryLaneReconciler as dt}from"./reconcilers/delivery-lane.js";import{ActionLaneReconciler as mt}from"./reconcilers/action-lane.js";import{endLiveExecution as pt,migrateLegacyExecutionIdentities as ft}from"../core/canvas/executions.js";import{revokePriorEpochNodeTokens as ut}from"../core/canvas/node-tokens.js";import{PendingReviewSubmitReconciler as ht}from"./reconcilers/pending-review-submit.js";import{StorageMaintenanceReconciler as wt}from"./reconcilers/storage-maintenance.js";import{StorageDueWorkReconciler as vt}from"./reconcilers/storage-due-work.js";import{PurgeDueWorkReconciler as gt}from"./reconcilers/purge-due-work.js";import{assertLedgerEnv as St}from"../core/ledger/rates.js";import{LedgerSandboxReconciler as yt}from"./reconcilers/ledger-sandbox.js";import{LedgerStorageReconciler as _t}from"./reconcilers/ledger-storage.js";import{LedgerR2Reconciler as bt}from"./reconcilers/ledger-r2.js";import{ImportLaneReconciler as kt}from"./reconcilers/import-lane.js";import{BashDeadlineReconciler as Rt}from"./reconcilers/bash-deadline.js";import{FaultRetryBackstopReconciler as Pt}from"./reconcilers/fault-retry-backstop.js";import{StructuredRequestReconciler as Et}from"./reconcilers/structured-request-lane.js";import{RecipeImageReconciler as It,subscribeImageBuilt as xt}from"./reconcilers/recipe-image.js";import{reconcileStructuredRequestSidecars as Dt}from"./structured-requests/boot.js";import{captureLivenessSnapshot as Me,capturePidCommand as Tt,captureTeardownSnapshot as Ge,isPidAlive as Ct,isAnyPidAlive as Oe,killProcessTreePids as Fe}from"../core/canvas/pid.js";import{bindFleet as Lt,boundFleet as $t}from"../core/runtime/fleet.js";import{bindDaemonControl as At,clearDaemonControl as Nt}from"./control.js";import{execDaemon as Mt,spawnDaemon as Gt}from"./manage.js";import{reconcileAndMigrateBoot as Ot}from"../core/canvas/boot.js";import{resolveInstallId as Ft}from"../core/canvas/install-id.js";import{setInstallId as Bt}from"../core/runtime/nodes.js";import{claimDaemonOwnership as Ht,daemonOwnershipApplies as jt,daemonOwnershipClaimed as zt,releaseDaemonOwnership as Be}from"../core/canvas/daemon-owner.js";import{canvasDatabaseUrl as Ut,closeAllDbs as pe,openDb as He,withCanvasWrite as fe}from"../core/canvas/db.js";import{importSqliteCanvasIfPresent as qt}from"../core/canvas/import-sqlite.js";import{ensurePostgres as Wt,ensurePostgresHealthy as Jt,stopPostgres as Kt,withPostgresStartLock as Vt}from"./postgres/index.js";import{brokerSignalBus as H}from"./broker-signals/bus.js";import{brokerSignalStreams as Yt}from"./api/handlers/broker-signals.js";import{setRequestsStartRunObservers as Qt}from"./api/handlers/broker-ops.js";import{reconcilePackages as Xt}from"../core/graph/package-reconcile.js";import{migrateAppInstalls as Zt}from"../core/scoped-state/migrate-app-installs.js";import{publish as en,readBuiltinSnapshot as rn}from"../core/graph/package-publish.js";import{startRepoSync as tn}from"../core/graph/repo-sync/index.js";import{prewarmRecentRecipes as nn,reapStaleSpares as on}from"../core/runtime/warm-pool.js";import{DaemonFleet as an}from"./fleet.js";import{copyNodeFilesToRows as sn}from"../core/runtime/first-boot-rows.js";import{BOOT_MIGRATIONS as cn}from"./boot-migrations.js";import{emitEvent as m}from"../core/events/emit.js";import{operationIdContext as _}from"../core/events/operation-id.js";import{bindDaemonEventSource as ln}from"../core/events/source.js";import{activateCanvasImport as dn,MigrationBlockedError as mn,runForcedCanvasImport as pn}from"../migrations/activation.js";import{adoptInstallPerson as fn,convertLegacyScopedStore as un,personStoresCopied as hn}from"../core/scoped-state/migrate.js";import{readLegacyUserSnapshot as wn}from"../core/scoped-state/legacy-profiles.js";import{heldPersons as je,installPreludeSnapshot as vn}from"../core/scoped-state/person-store.js";import{loadPersonSettings as ze}from"../core/scoped-state/person-rows.js";import{userScopeRoot as Ue}from"../core/scope.js";import{brokerCommandDeclaresCanvasHome as ue}from"../core/runtime/broker-ownership.js";import{brokerCommandDeclaresCanvasHome as Vi}from"../core/runtime/broker-ownership.js";function he(e){return/ --epoch (\S+) /.exec(e)?.[1]??null}a(he,"brokerCommandEpoch");const gn=5e3,qe=150;async function Sn(e){const l=Me();if(l===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 u=Sr(),f=[];for(const[n,d]of l.processes){const y=d.command;if(d.zombie||!y.includes("broker-cli.js")||!ue(y,u)||he(y)===e)continue;const P=y.trim().split(/\s+/).at(-1)??"";P===""||P.endsWith("broker-cli.js")||f.push({pid:n,nodeId:P})}let v=0;const s=[];for(const n of f){const d=Tt(n.pid);if(d===null||!d.includes("broker-cli.js")||!ue(d,u)||he(d)===e||d.trim().split(/\s+/).at(-1)!==n.nodeId)continue;const y=Ge(n.pid,null);if(!y.reused){try{process.platform==="linux"&&R(D)?await A({operation:"stop",pid:n.pid}):process.kill(n.pid,"SIGTERM")}catch{continue}v++,s.push({pid:n.pid,snap:y})}}const h=Date.now()+gn;for(;Date.now()<h&&s.some(n=>Oe(n.snap.tree.length>0?n.snap.tree:[n.pid]));)await new Promise(n=>setTimeout(n,qe));let g=0;for(const n of s){const d=n.snap.tree.length>0?n.snap.tree:[n.pid];Oe(d)&&(process.platform==="linux"&&R(D)?await A({operation:"stop",pid:n.pid}):Fe(d,"SIGKILL",n.snap.identities),g++)}g>0&&await new Promise(n=>setTimeout(n,qe));const p=Me();if(p===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 c=[];for(const[n,d]of p.processes){const y=d.command;d.zombie||!y.includes("broker-cli.js")||ue(y,u)&&he(y)!==e&&c.push(n)}if(c.length>0)throw new Error(`prior-epoch broker census could not prove termination of pid(s): ${c.join(", ")}`);m({level:"info",event:"daemon.census.completed",fields:{prior_epoch_brokers:f.length,sigtermed:v,sigkilled:g}})}a(Sn,"reapPriorEpochBrokers");const yn=5e3;async function _n(e){const l=Array.from(e.entries());if(l.length===0)return;for(const[s]of l){const h=(await xr(s))?.status;(h==="active"||h==="idle")&&await Le(s,new Date().toISOString())}const u=l.map(([,s])=>({pid:s.pid,snap:Ge(s.pid,null),exited:s.handle.exited}));for(const s of u)if(!s.snap.reused)try{process.platform==="linux"&&R(D)?await A({operation:"stop",pid:s.pid}):process.kill(s.pid,"SIGTERM")}catch{}const f=new Promise(s=>{setTimeout(s,yn).unref()});await Promise.allSettled(u.map(s=>Promise.race([s.exited.then(()=>{}),f])));const v=[];for(const s of u)Ct(s.pid)&&(process.platform==="linux"&&R(D)?await A({operation:"stop",pid:s.pid}):Fe(s.snap.tree.length>0?s.snap.tree:[s.pid],"SIGKILL",s.snap.identities),v.push(s));await Promise.all(v.map(s=>s.exited));for(const[s]of l)await pt(s,{reason:"daemon-teardown"});m({level:"info",event:"daemon.fleet_teardown.completed",fields:{brokers:u.length,sigkilled:v.length}})}a(_n,"teardownFleet");function We(){Re(fr(me()),{recursive:!0}),dr(me(),String(process.pid),"utf8")}a(We,"writePidfile");function Je(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}a(Je,"isMissingPathError");function Ke(e){const l=me();let u;try{u=mr(l,"utf8")}catch(f){if(Je(f))return;throw f}if(u.trim()!==String(e))throw new Error(`daemon readiness mirror does not name this invocation (expected pid ${e})`);try{pr(l)}catch(f){if(Je(f))return;throw f}}a(Ke,"removeOwnedPidfileMirror");const bn={acceptsDetachedWork:a(()=>!0,"acceptsDetachedWork"),registerDetached:a(e=>{e.catch(()=>{})},"registerDetached")},Q=new it;ot(e=>Q.handleFatalFault(e,!1));const kn=new at,Rn=new st,Pn=new ct,En=new lt,In=new dt,xn=new mt,Dn=new ht,Tn=new wt,Cn=new vt,Ln=new gt,$n=new yt,An=new _t,Nn=new bt,Mn=new kt,Gn=new Rt,On=new Pt,Fn=new Et,Bn=new It;async function Hn(e=Date.now(),l=bn){const u=$t(),f=await Q.runFleetPreamble(u);let v,s;try{const g=await Ce();v=g.filter(c=>c.status==="active"||c.status==="idle"),s=g.filter(c=>c.status==="done"||c.status==="canceled"||c.status==="dead");const p=new Set(s.map(c=>c.node_id));s.push(...(await Dr()).filter(c=>!p.has(c.node_id)))}catch(g){m({level:"error",event:"canvas.node_list.failed",error:g});return}await Q.run(e,{rows:v,fleet:u,lifecycle:l}),await kn.run(e,{rows:v});const h=await Rn.run(e,{rows:[...v,...s],fleet:u});await Pn.run(e),await Fn.run(e),await Bn.run(e,{lifecycle:l}),await En.run(e,{lifecycle:l}),await In.run(e,{lifecycle:l}),await xn.run(e,{lifecycle:l}),await Dn.run(e,{lifecycle:l}),await Tn.run(e,{lifecycle:l,fleet:u}),Cn.run(e,{lifecycle:l}),Ln.run(e,{lifecycle:l}),$n.run(e,{lifecycle:l}),An.run(e,{lifecycle:l}),Nn.run(e,{lifecycle:l}),Mn.run(e,{lifecycle:l}),await gr(),On.run(e,{fleet:u,lifecycle:l}),await Gn.run(e,{rows:v}),Q.warnIfSaturated({fleet:u,lifecycle:l,thresholds:f,frozen:h})}a(Hn,"superviseTick");function j(e){return e===void 0||e==="reconcile"}a(j,"roleRunsLanes");function N(e){return e===void 0||e==="api"}a(N,"roleServesRequests");const jn=66e4;function zn(e){const l=new Cr().registerAll(Lr(()=>null).filter(n=>n.pattern==="/healthz")),u=a((n,d)=>{const y=(n.url??"/").split("?")[0];if((n.method??"GET").toUpperCase()==="GET"&&y==="/healthz"){l.handle(n,d,null,{class:"person"});return}d.writeHead(404,{"content-type":"application/json; charset=utf-8"}),d.end(JSON.stringify({error:{code:"not_found",message:"this process serves only /healthz",origin:"runtime"}}))},"handler"),f=De();R(f)&&Pe(f);const v=Y(u),s=new Promise((n,d)=>{v.once("error",d),v.listen(f,()=>{v.off("error",d),Ee(f,384),n()})});let h,g=null;const p=e.tcp??Ie()??de("user").api.tcp;if(p!==void 0&&p!==""){const n=/^(.*):(\d+)$/.exec(p.trim());if(n===null||Number(n[2])>65535)throw new Error(`invalid reconcile probe TCP address: ${p}`);const d=Y(u);d.on("error",y=>m({event:"api.server.failed",level:"error",error:y})),d.listen(Number(n[2]),n[1]===""?"0.0.0.0":n[1],()=>{g=`${n[1]===""?"0.0.0.0":n[1]}:${n[2]}`}),h=d}let c=!1;return{ready:s,tcpAddress:a(()=>g,"tcpAddress"),async close(n={}){if(!c){c=!0,await Promise.all([$e(v,new Set,n.graceMs),h===void 0?Promise.resolve():$e(h,new Set,n.graceMs)]);try{R(f)&&Pe(f)}catch{}}}}}a(zn,"createProbeServer");const Un="daemon is draining for shutdown and admits no new work";async function qn(e){Re(Te(),{recursive:!0,mode:493}),process.platform==="linux"&&Ee(Te(),493);const l=De();if(R(l))throw new Error(`layout refusal cannot bind occupied socket: ${l}`);const u=Y((p,c)=>{if(p.method==="GET"&&p.url==="/healthz"){c.writeHead(200,{"content-type":"application/json; charset=utf-8"}),c.end(JSON.stringify({ok:!1,daemon_up:!0,store_accessible:!1,brokers_reconciled:!1,startup_phase:"blocked",startup_blocked:"layout_migration_required"}));return}c.writeHead(503,{"content-type":"application/json; charset=utf-8"}),c.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((p,c)=>{u.once("error",c),u.listen(l,()=>{u.off("error",c),p()})});let f;const v=e.tcp??Ie();if(v){const p=/^(.*):(\d+)$/.exec(v);if(!p||Number(p[2])>65535)throw new Error(`invalid refusal TCP address: ${v}`);const c=Y(u.listeners("request")[0]);await new Promise((n,d)=>{c.once("error",d),c.listen(Number(p[2]),p[1],()=>{c.off("error",d),n()})}),f=c}We();let s;const h=a(()=>(s??=(async()=>{u.closeAllConnections(),f?.closeAllConnections(),await Promise.all([u,f].filter(p=>p!==void 0).map(p=>new Promise((c,n)=>p.close(d=>d?n(d):c())))),Ke(process.pid),process.off("SIGINT",g),process.off("SIGTERM",g)})(),s),"cleanup"),g=a(()=>{h().then(()=>process.exit(0),p=>{process.stderr.write(`[crtrd] layout refusal cleanup failed: ${String(p)}
2
+ `),process.exit(1)})},"onSignal");return process.on("SIGINT",g),process.on("SIGTERM",g),h}a(qn,"serveLayoutRefusal");async function Wn(e={}){if(e.role==="machine")return(await import("./machine-daemon.js")).runMachineDaemon();if(Pr())return qn(e);Rr();const l=a(t=>{process.stderr.write(`[crtrd] ${t}
3
+ `)},"logPostgres"),u=!!process.env.CRTR_TEST_PG_URL,f=jt(e.role);Qt(j(e.role));const v=a(async()=>f?await Ht(xe(16).toString("hex")):{claimed:!0,claim:{pid:process.pid,pid_identity:"",token:xe(16).toString("hex")}},"claimOwnership"),{database:s,ownership:h}=u?{database:{url:await Ut()},ownership:await v()}:await Vt(async()=>({database:await Wt({log:l,startLockHeld:!0}),ownership:await v()}));if(!h.claimed){if(h.reason==="incumbent_alive")process.stderr.write(`[crtrd] already running (pid ${h.incumbentPid??"?"})
4
+ `);else{const t=[h.incumbentPid!==void 0?`pid ${h.incumbentPid}`:void 0,h.verdict!==void 0?`verdict ${h.verdict}`:void 0].filter(w=>w!==void 0),i=t.length>0?` (${t.join(", ")})`:"";process.stderr.write(`[crtrd] claim lost: ${h.reason}${i}
5
+ `),h.reason==="own_identity_indeterminate"&&process.stderr.write("[crtrd] cannot read its own process identity. crouter needs /proc on Linux, or the `ps` command elsewhere (Debian/Ubuntu: apt-get install procps).\n"),(h.reason==="own_identity_indeterminate"||h.reason==="incumbent_malformed")&&(process.exitCode=1)}return async()=>{}}const g=h.claim;let p=null,c=null,n=null,d=null,y,P="";try{f&&await Sn(g.token);for(const r of Ir())process.stderr.write(`[crtrd] ${r}
6
6
  `);for(const r of await Er())process.stderr.write(`[crtrd] ${r}
7
- `);await He(),await qt(s.url,l);const t=e.role===void 0&&!await wn();let i=null;t&&(un({kind:"user",root:Ue()}),i=hn(Ue())),e.role===void 0&&vn(i??{profiles:[],defaults:{},settings:{},state:{},apps:{}}),await H.listen(s.url);const h=a(r=>{ze(r).catch(o=>m({level:"error",event:"daemon.settings.reload_failed",error:o}))},"reloadPerson");if(y=await H.subscribe(r=>{je().includes(r)&&h(r)},{kinds:["settings"],onListenStart:a(()=>{for(const r of je())h(r)},"onListenStart")}),e.role!==void 0&&Or(),e.role!==void 0){let r;try{r=rn()}catch(b){m({level:"error",event:"daemon.packages.snapshot_failed",error:b})}const o=await fe(async b=>(await $e(b),r===void 0?void 0:await en(b,r,"release")));d=await fe(async b=>await Zt(b));for(const b of o?.invalid??[])process.stderr.write(`[crtrd] package file is not a document: ${b.path}: ${b.error}
8
- `)}else{const r=await fe(async o=>(await $e(o),await Xt(o)));for(const o of r.conflicts)process.stderr.write(`[crtrd] plugin documents not reconciled: ${o.message}
7
+ `);await He(),await qt(s.url,l);const t=e.role===void 0&&!await hn();let i=null;t&&(un({kind:"user",root:Ue()}),i=wn(Ue())),e.role===void 0&&vn(i??{profiles:[],defaults:{},settings:{},state:{},apps:{}}),await H.listen(s.url);const w=a(r=>{ze(r).catch(o=>m({level:"error",event:"daemon.settings.reload_failed",error:o}))},"reloadPerson");if(y=await H.subscribe(r=>{je().includes(r)&&w(r)},{kinds:["settings"],onListenStart:a(()=>{for(const r of je())w(r)},"onListenStart")}),e.role!==void 0&&Or(),e.role!==void 0){let r;try{r=rn()}catch(b){m({level:"error",event:"daemon.packages.snapshot_failed",error:b})}const o=await fe(async b=>(await Ae(b),r===void 0?void 0:await en(b,r,"release")));d=await fe(async b=>await Zt(b));for(const b of o?.invalid??[])process.stderr.write(`[crtrd] package file is not a document: ${b.path}: ${b.error}
8
+ `)}else{const r=await fe(async o=>(await Ae(o),await Xt(o)));for(const o of r.conflicts)process.stderr.write(`[crtrd] plugin documents not reconciled: ${o.message}
9
9
  `);for(const o of r.invalid)process.stderr.write(`[crtrd] package file is not a document: ${o.path}: ${o.error}
10
10
  `);for(const o of r.quarantined)process.stderr.write(`[crtrd] plugin "${o.name}" has a damaged ${o.file} (${o.reason}); ${o.movedTo!==void 0?`moved to ${o.movedTo}`:"left in place and skipped"}
11
11
  `);for(const o of r.kinds.refused)process.stderr.write(`[crtrd] plugin "${o.plugin}" kind ${o.kind} not registered: ${o.message}
12
12
  `);for(const o of r.kinds.invalid)process.stderr.write(`[crtrd] plugin "${o.plugin}" declares invalid object kinds or scopes; no kinds registered and no app token: ${o.error}
13
- `)}if(P=await Ft(),Bt(P),e.role===void 0&&(p=await Fr(),p!==null)){if(Hr(p.id),await fn(p.id),process.platform==="darwin"){const{readConfig:r,updateConfig:o}=await import("../core/config.js");if(r("user").paths?.user_files===void 0){const{homedir:b}=await import("node:os");await o("user",ke=>{ke.paths??={},ke.paths.user_files??=b()})}}c=await Br(),c.joinedFrom!==null&&await ze(c.person),await ar(),n=await jr()}if(process.platform==="linux"&&R(D)&&(kr(),await $({operation:"users.sync",users:await yr()})),f){await ut(g.token);const r=await sn();Object.values(r).some(o=>o>0)&&process.stderr.write(`[crtrd] node files copied into rows: ${JSON.stringify(r)}
14
- `)}}catch(t){await H.close();try{if(f){const{released:i}=await Be(g);if(!i)throw new Error("daemon ownership claim was not released")}await pe()}catch(i){throw new AggregateError([t,i],"daemon startup failed and cleanup also failed")}throw t}let T=!0,X,z=Promise.resolve(),Z=!1,U,ee,re,C;const q=new Set;let te=!1,he=!1,E,L,ne,W=!1,J,M,G,O,F,oe,ie,ae,se;const Ve=nt();let I,S={phase:"initializing",message:"daemon startup is running the canvas import and normal services are unavailable",blockerPaths:[]},A="initial startup activation",Ye=null;function Qe(){return S.phase==="ready"?null:{phase:S.phase,message:S.message,blockerPaths:S.blockerPaths}}a(Qe,"startupBlock");function k(t){q.add(t),t.finally(()=>{q.delete(t)}).catch(()=>{})}a(k,"registerDetached");const ve={acceptsDetachedWork:a(()=>T,"acceptsDetachedWork"),registerDetached:k};j(e.role)&&await tn(ve,He);async function Xe(){try{T=!1,Yt.close(),ee?.(),ee=void 0,re?.(),y?.(),re=void 0,ae?.(),ae=void 0,await H.close(),U!==void 0&&(clearInterval(U),U=void 0),G!==void 0&&(clearInterval(G),G=void 0),O!==void 0&&(clearInterval(O),O=void 0),se?.(),se=void 0;let t;do t=z,await t;while(t!==z);for(;q.size>0;)await Promise.allSettled([...q]);if(C!==void 0&&(f&&await _n(C),await C.exitsSettled(),C.dispose()),ne!==void 0&&await ne.close(),L!==void 0&&!W&&(W=!0,await L.close()),oe?.(),oe=void 0,ie?.(),ie=void 0,F!==void 0){const i=F;F=void 0,await i.stop()}if(M!==void 0){const i=M;M=void 0,await i.close()}if(J!==void 0){const i=J;J=void 0,await i.close()}if(te||(Ke(process.pid),te=!0),te&&!he){if(f){const{released:i}=await Be(g);if(!i)throw new Error("daemon ownership claim was not released")}he=!0,await pe()}}finally{Nt(),process.off("SIGINT",ye),process.off("SIGTERM",_e),process.off("exit",be)}}a(Xe,"cleanupAttempt");const K=1e3;let ge=!1;function Ze(){return ge?{graceMs:K}:(ge=!0,_.fresh(()=>{m({level:"info",event:"daemon.handover.armed",fields:{pid:process.pid,grace_ms:K}})}),setTimeout(()=>{er()},K),{graceMs:K})}a(Ze,"requestHandover");async function er(){try{await x()}catch(t){const i=t instanceof Error?t.stack??t.message:String(t);process.stderr.write(`[crtrd] handover cleanup failed:
13
+ `)}if(P=await Ft(),Bt(P),e.role===void 0&&(p=await Fr(),p!==null)){if(Hr(p.id),await fn(p.id),process.platform==="darwin"){const{readConfig:r,updateConfig:o}=await import("../core/config.js");if(r("user").paths?.user_files===void 0){const{homedir:b}=await import("node:os");await o("user",ke=>{ke.paths??={},ke.paths.user_files??=b()})}}c=await Br(),c.joinedFrom!==null&&await ze(c.person),await ar(),n=await jr()}if(process.platform==="linux"&&R(D)&&(kr(),await A({operation:"users.sync",users:await yr()})),f){await ut(g.token);const r=await sn();Object.values(r).some(o=>o>0)&&process.stderr.write(`[crtrd] node files copied into rows: ${JSON.stringify(r)}
14
+ `)}}catch(t){await H.close();try{if(f){const{released:i}=await Be(g);if(!i)throw new Error("daemon ownership claim was not released")}await pe()}catch(i){throw new AggregateError([t,i],"daemon startup failed and cleanup also failed")}throw t}let T=!0,X,z=Promise.resolve(),Z=!1,U,ee,re,C;const q=new Set;let te=!1,we=!1,E,L,ne,W=!1,J,M,G,O,F,oe,ie,ae,se;const Ve=nt();let I,S={phase:"initializing",message:"daemon startup is running the canvas import and normal services are unavailable",blockerPaths:[]},$="initial startup activation",Ye=null;function Qe(){return S.phase==="ready"?null:{phase:S.phase,message:S.message,blockerPaths:S.blockerPaths}}a(Qe,"startupBlock");function k(t){q.add(t),t.finally(()=>{q.delete(t)}).catch(()=>{})}a(k,"registerDetached");const ve={acceptsDetachedWork:a(()=>T,"acceptsDetachedWork"),registerDetached:k};j(e.role)&&await tn(ve,He);async function Xe(){try{T=!1,Yt.close(),ee?.(),ee=void 0,re?.(),y?.(),re=void 0,ae?.(),ae=void 0,await H.close(),U!==void 0&&(clearInterval(U),U=void 0),G!==void 0&&(clearInterval(G),G=void 0),O!==void 0&&(clearInterval(O),O=void 0),se?.(),se=void 0;let t;do t=z,await t;while(t!==z);for(;q.size>0;)await Promise.allSettled([...q]);if(C!==void 0&&(f&&await _n(C),await C.exitsSettled(),C.dispose()),ne!==void 0&&await ne.close(),L!==void 0&&!W&&(W=!0,await L.close()),oe?.(),oe=void 0,ie?.(),ie=void 0,F!==void 0){const i=F;F=void 0,await i.stop()}if(M!==void 0){const i=M;M=void 0,await i.close()}if(J!==void 0){const i=J;J=void 0,await i.close()}if(te||(Ke(process.pid),te=!0),te&&!we){if(f){const{released:i}=await Be(g);if(!i)throw new Error("daemon ownership claim was not released")}we=!0,await pe()}}finally{Nt(),process.off("SIGINT",ye),process.off("SIGTERM",_e),process.off("exit",be)}}a(Xe,"cleanupAttempt");const K=1e3;let ge=!1;function Ze(){if(e.role!==void 0)throw new Error(`a ${e.role} daemon never hands over to a successor: its orchestrator replaces it`);return ge?{graceMs:K}:(ge=!0,_.fresh(()=>{m({level:"info",event:"daemon.handover.armed",fields:{pid:process.pid,grace_ms:K}})}),setTimeout(()=>{er()},K),{graceMs:K})}a(Ze,"requestHandover");async function er(){try{await x()}catch(t){const i=t instanceof Error?t.stack??t.message:String(t);process.stderr.write(`[crtrd] handover cleanup failed:
15
15
  ${i}
16
- `),process.exit(1)}try{process.platform==="linux"&&R(D)&&(await $({operation:"daemon.handover"}),process.exit(0)),process.pid===1&&await Mt();const t=await Gt({waitForJoinLock:!0});_.fresh(()=>{m({level:"info",event:"daemon.handover.completed",fields:{predecessor_pid:process.pid,successor_pid:t.pid??t.existing_pid??null,spawned:t.started}})})}catch(t){_.fresh(()=>{m({level:"error",event:"daemon.handover.successor_failed",error:t})});const i=t instanceof Error?t.message:String(t);process.stderr.write(`[crtrd] handover successor failed to start: ${i}
17
- `),process.exit(1)}process.exit(0)}a(er,"performHandover");function x(){if(E!==void 0)return E;const t=Xe();return E=t,t.then(()=>{E===t&&(E=void 0)},()=>{E===t&&(E=void 0)}),t}a(x,"requestCleanup");async function rr(){S={phase:"initializing",message:Un,blockerPaths:[]},L!==void 0&&!W&&(W=!0,await L.close({graceMs:jn}))}a(rr,"drainApi");async function Se(t){try{t==="SIGTERM"&&e.role==="api"&&await rr(),await x(),await Kt({claimed:a(async()=>{try{return f&&await zt()}finally{await pe()}},"claimed")}),process.exit(0)}catch(i){process.exitCode=1;const h=i instanceof Error?i.stack??`${i.name}: ${i.message}`:String(i);process.stderr.write(`[crtrd] ${t} cleanup failed:
18
- ${h}
19
- `),process.exit(1)}}a(Se,"handleSignal");function ye(){Se("SIGINT")}a(ye,"onSigint");function _e(){Se("SIGTERM")}a(_e,"onSigterm");function be(){x().catch(()=>{})}a(be,"onExit");async function ce(t){T&&(z=z.then(t).then(()=>{},i=>{_.fresh(()=>{m({level:"error",event:"daemon.lane_job.failed",error:i})})}))}a(ce,"enqueue");async function V(){!T||Z||(Ve.check()&&I&&(m({level:"info",event:"daemon.resume.detected"}),k(I().catch(()=>{}))),Z=!0,await ce(async()=>{if(Z=!1,!!T)try{u||await Jt({log:l}),await Hn(Date.now(),ve)}catch(t){_.fresh(()=>{m({level:"error",event:"daemon.tick.failed",error:t})})}}))}a(V,"enqueueTick");let B=null;async function tr(){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 t=S.phase==="prepared";try{return await le(),S={phase:"ready",message:"",blockerPaths:[]},t?{admitted:!0,already_admitted:!1,startup_phase:"ready"}:{admitted:!1,already_admitted:!0,startup_phase:"ready"}}catch(i){throw B=i,{status:500,code:"admission_failed",message:`daemon admission failed: ${i instanceof Error?i.message:String(i)}`}}}a(tr,"admitStartup");async function nr(t){if(A!==null)throw{status:409,code:"migration_in_progress",message:`the canvas import is already running (${A})`};A="repair";try{const i=await pn({dryRun:t.dryRun});if(t.dryRun||i.pending||S.phase!=="blocked")return{result:i,resumed:!1};if(e.prepare)return S={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]},{result:i,resumed:!1};try{return await le(),S={phase:"ready",message:"",blockerPaths:[]},{result:i,resumed:!0}}catch(h){const r=h instanceof Error?h.message:String(h);return setTimeout(()=>{x().catch(()=>{})},1e3),{result:i,resumed:!1,resumeError:r}}}finally{A=null}}a(nr,"repairMigrations");async function or(){X=e.intervalMs??tt;const t=g.token;C=new an({epoch:t,enqueue:ce}),Lt(C),S={phase:"recovering",message:"daemon startup recovery is running and normal services are unavailable",blockerPaths:[]},_.fresh(()=>{m({level:"info",event:"daemon.started",fields:{pid:process.pid,interval_ms:X}})});const i=P;_.fresh(()=>{m({level:"info",event:"daemon.install_id.resolved",fields:{install_id:i}})});const h=await Mr(i);if(_.fresh(()=>{m({level:"info",event:"daemon.environment.registered",fields:{environment_id:h.environmentId,created:h.created}})}),_.fresh(()=>{let r;try{r=rt()}catch{return}r!==null&&m({level:"warn",event:"daemon.startup.warning",fields:{stage:"termrender",warning:r.slice(0,2048)}})}),St(),e.role!==void 0&&!process.env.CRTR_DIRECTORY_URL)throw new Error("CRTR_DIRECTORY_URL must be set on a cloud role (--role api|reconcile): it names the directory this deployment mints tokens against");if(e.role!==void 0&&Gr(),!j(e.role)){S={phase:"ready",message:"",blockerPaths:[]};return}if(await _.fresh(async()=>{await et(),await Qr(),await Xr(Date.now()),await Zr(Date.now())}),await _.fresh(async()=>{const{reconcile:r,migrated:o}=await Ot(ft);r.changed&&m({level:"info",event:"daemon.boot_change.reconciled",fields:{cleared_count:r.cleared.length,same_boot_proven:r.sameBootProven}}),o.length>0&&m({level:"info",event:"daemon.pid_identity.migrated",fields:{migrated_count:o.length}})}),await _.fresh(async()=>{for(const r of await Ce())r.status!=="active"||r.pi_pid!=null||r.frozen_at!=null||r.respawn_not_before!=null||(await Le(r.node_id,new Date().toISOString()),m({level:"warn",event:"daemon.startup.launch_debt_recorded",node_id:r.node_id}))}),await _.fresh(async()=>{await Dt();for(const r of cn){const o=await r.apply();o.changed&&m({level:"info",event:"daemon.boot_migration.applied",fields:{migration:r.id,...o.summary}})}}),k(Vr()),I){const r=a(()=>{k(I().catch(()=>{})),k(cr().then(o=>F?.observe(o)).then(()=>{},o=>{m({level:"warn",event:"daemon.peer.status_failed",error:o})}))},"refresh");k(Kr().then(({completion:o})=>o).catch(o=>{m({level:"error",event:"daemon.grants.sweep_failed",error:o})})),r(),G=setInterval(r,Ne*1e3),G.unref(),se=sr({joined:!0,register:k})}await ce(async()=>{await on(),await nn()}),U=setInterval(()=>{V().catch(r=>m({level:"error",event:"daemon.tick.failed",error:r}))},X),ee=await xt(()=>{V().catch(r=>m({level:"error",event:"daemon.tick.failed",error:r}))}),re=await H.subscribe(()=>{V().catch(r=>m({level:"error",event:"daemon.tick.failed",error:r}))},{kinds:["spend_limits"]}),await V(),e.role===void 0&&import("../commands/sys/import/move.js").then(({settleMoveAtDaemonStart:r})=>r(()=>!T,o=>m({level:"warn",event:"daemon.move.settle_failed",error:o}))).catch(r=>m({level:"warn",event:"daemon.move.settle_failed",error:r}))}a(or,"completeStartup");function le(){return Ye??=or().catch(t=>{throw S={phase:"initializing",message:"daemon startup recovery failed and normal services are unavailable",blockerPaths:[]},t})}a(le,"resumeStartup");try{process.on("SIGINT",ye),process.on("SIGTERM",_e),process.on("exit",be),ln(),p!==null&&m({level:"info",event:"daemon.person.resolved",fields:{person_id:p.id,source:p.source}}),d!==null&&!d.alreadyDone&&m({level:"info",event:"daemon.packages.install_migration_done",fields:{moved:d.moved,discarded:d.discarded,people:d.people}}),n!==null&&m({level:"info",event:"daemon.permissions.boot",fields:{...n}}),c!==null&&m({level:"info",event:"daemon.person.retired",fields:{person_id:c.person,joined_from:c.joinedFrom,retired:c.retired,columns:c.columns}}),N(e.role)?J=await hr():vr(wr());const t=g.token;$t({epoch:t,requestHandover:Ze,registerDetached:k,startupBlock:Qe,admitStartup:tr,repairMigrations:nr}),We(),L=N(e.role)?Tr({tcp:e.tcp}):zn(e),await L.ready;const i=ur()??de("user").document_port;if(N(e.role)){const r=Ar(i,$r());try{await r.ready,ne=r}catch(o){m({level:"warn",event:"daemon.document_listener.bind_failed",fields:{port:i,error:o instanceof Error?o.message:String(o)}})}}const h=de("user").runtime;if(h?.issuer&&(I=Jr(h.issuer,k),h.unsandboxed===!0&&(F=lr({syncGrants:I}))),e.role==="api"){const r=a(()=>k(qr().catch(o=>{m({level:"error",event:"daemon.packages.sync_failed",error:o})})),"packageTick");r(),O=setInterval(r,Ne*1e3),O.unref()}if(N(e.role)&&(oe=await zr()),j(e.role)&&(ie=Wr()),ae=await Ur({serves:N(e.role),runsLanes:j(e.role)}),h?.unsandboxed===!0&&h.listener!==void 0&&m({level:"warn",event:"daemon.app_listener.refused_unsandboxed",fields:{reason:"runtime.unsandboxed is set; runtime.listener is ignored"}}),N(e.role)&&h!==void 0&&h.listener!==void 0&&h.unsandboxed!==!0&&(M=await Nr(h,async()=>await Yr(h.issuer.replace(/\/$/,"")),I),await M.ready),e.role===void 0)try{await dn()}catch(r){if(A=null,r instanceof mn)return S={phase:"blocked",message:r.message,blockerPaths:r.blockerPaths},x;throw r}process.platform==="linux"&&R(D)&&(br(),await _r("app:terminal"));try{e.prepare?S={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]}:(await le(),S={phase:"ready",message:"",blockerPaths:[]})}finally{A=null}return x}catch(t){try{await x()}catch(i){throw new AggregateError([t,i],"daemon startup failed and cleanup also failed")}throw t}}a(Wn,"runDaemon");var Wi=Wn;export{jn as API_DRAIN_GRACE_MS,Vi as brokerCommandDeclaresCanvasHome,we as brokerCommandEpoch,Wi as default,j as roleRunsLanes,N as roleServesRequests,Wn as runDaemon,Hn as superviseTick,_n as teardownFleet};
16
+ `),process.exit(1)}try{process.platform==="linux"&&R(D)&&(await A({operation:"daemon.handover"}),process.exit(0)),process.pid===1&&await Mt();const t=await Gt({waitForJoinLock:!0});_.fresh(()=>{m({level:"info",event:"daemon.handover.completed",fields:{predecessor_pid:process.pid,successor_pid:t.pid??t.existing_pid??null,spawned:t.started}})})}catch(t){_.fresh(()=>{m({level:"error",event:"daemon.handover.successor_failed",error:t})});const i=t instanceof Error?t.message:String(t);process.stderr.write(`[crtrd] handover successor failed to start: ${i}
17
+ `),process.exit(1)}process.exit(0)}a(er,"performHandover");function x(){if(E!==void 0)return E;const t=Xe();return E=t,t.then(()=>{E===t&&(E=void 0)},()=>{E===t&&(E=void 0)}),t}a(x,"requestCleanup");async function rr(){S={phase:"initializing",message:Un,blockerPaths:[]},L!==void 0&&!W&&(W=!0,await L.close({graceMs:jn}))}a(rr,"drainApi");async function Se(t){try{t==="SIGTERM"&&e.role==="api"&&await rr(),await x(),await Kt({claimed:a(async()=>{try{return f&&await zt()}finally{await pe()}},"claimed")}),process.exit(0)}catch(i){process.exitCode=1;const w=i instanceof Error?i.stack??`${i.name}: ${i.message}`:String(i);process.stderr.write(`[crtrd] ${t} cleanup failed:
18
+ ${w}
19
+ `),process.exit(1)}}a(Se,"handleSignal");function ye(){Se("SIGINT")}a(ye,"onSigint");function _e(){Se("SIGTERM")}a(_e,"onSigterm");function be(){x().catch(()=>{})}a(be,"onExit");async function ce(t){T&&(z=z.then(t).then(()=>{},i=>{_.fresh(()=>{m({level:"error",event:"daemon.lane_job.failed",error:i})})}))}a(ce,"enqueue");async function V(){!T||Z||(Ve.check()&&I&&(m({level:"info",event:"daemon.resume.detected"}),k(I().catch(()=>{}))),Z=!0,await ce(async()=>{if(Z=!1,!!T)try{u||await Jt({log:l}),await Hn(Date.now(),ve)}catch(t){_.fresh(()=>{m({level:"error",event:"daemon.tick.failed",error:t})})}}))}a(V,"enqueueTick");let B=null;async function tr(){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 t=S.phase==="prepared";try{return await le(),S={phase:"ready",message:"",blockerPaths:[]},t?{admitted:!0,already_admitted:!1,startup_phase:"ready"}:{admitted:!1,already_admitted:!0,startup_phase:"ready"}}catch(i){throw B=i,{status:500,code:"admission_failed",message:`daemon admission failed: ${i instanceof Error?i.message:String(i)}`}}}a(tr,"admitStartup");async function nr(t){if($!==null)throw{status:409,code:"migration_in_progress",message:`the canvas import is already running (${$})`};$="repair";try{const i=await pn({dryRun:t.dryRun});if(t.dryRun||i.pending||S.phase!=="blocked")return{result:i,resumed:!1};if(e.prepare)return S={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]},{result:i,resumed:!1};try{return await le(),S={phase:"ready",message:"",blockerPaths:[]},{result:i,resumed:!0}}catch(w){const r=w instanceof Error?w.message:String(w);return setTimeout(()=>{x().catch(()=>{})},1e3),{result:i,resumed:!1,resumeError:r}}}finally{$=null}}a(nr,"repairMigrations");async function or(){X=e.intervalMs??tt;const t=g.token;C=new an({epoch:t,enqueue:ce}),Lt(C),S={phase:"recovering",message:"daemon startup recovery is running and normal services are unavailable",blockerPaths:[]},_.fresh(()=>{m({level:"info",event:"daemon.started",fields:{pid:process.pid,interval_ms:X}})});const i=P;_.fresh(()=>{m({level:"info",event:"daemon.install_id.resolved",fields:{install_id:i}})});const w=await Mr(i);if(_.fresh(()=>{m({level:"info",event:"daemon.environment.registered",fields:{environment_id:w.environmentId,created:w.created}})}),_.fresh(()=>{let r;try{r=rt()}catch{return}r!==null&&m({level:"warn",event:"daemon.startup.warning",fields:{stage:"termrender",warning:r.slice(0,2048)}})}),St(),e.role!==void 0&&!process.env.CRTR_DIRECTORY_URL)throw new Error("CRTR_DIRECTORY_URL must be set on a cloud role (--role api|reconcile): it names the directory this deployment mints tokens against");if(e.role!==void 0&&Gr(),!j(e.role)){S={phase:"ready",message:"",blockerPaths:[]};return}if(await _.fresh(async()=>{await et(),await Qr(),await Xr(Date.now()),await Zr(Date.now())}),await _.fresh(async()=>{const{reconcile:r,migrated:o}=await Ot(ft);r.changed&&m({level:"info",event:"daemon.boot_change.reconciled",fields:{cleared_count:r.cleared.length,same_boot_proven:r.sameBootProven}}),o.length>0&&m({level:"info",event:"daemon.pid_identity.migrated",fields:{migrated_count:o.length}})}),await _.fresh(async()=>{for(const r of await Ce())r.status!=="active"||r.pi_pid!=null||r.frozen_at!=null||r.respawn_not_before!=null||(await Le(r.node_id,new Date().toISOString()),m({level:"warn",event:"daemon.startup.launch_debt_recorded",node_id:r.node_id}))}),await _.fresh(async()=>{await Dt();for(const r of cn){const o=await r.apply();o.changed&&m({level:"info",event:"daemon.boot_migration.applied",fields:{migration:r.id,...o.summary}})}}),k(Vr()),I){const r=a(()=>{k(I().catch(()=>{})),k(cr().then(o=>F?.observe(o)).then(()=>{},o=>{m({level:"warn",event:"daemon.peer.status_failed",error:o})}))},"refresh");k(Kr().then(({completion:o})=>o).catch(o=>{m({level:"error",event:"daemon.grants.sweep_failed",error:o})})),r(),G=setInterval(r,Ne*1e3),G.unref(),se=sr({joined:!0,register:k})}await ce(async()=>{await on(),await nn()}),U=setInterval(()=>{V().catch(r=>m({level:"error",event:"daemon.tick.failed",error:r}))},X),ee=await xt(()=>{V().catch(r=>m({level:"error",event:"daemon.tick.failed",error:r}))}),re=await H.subscribe(()=>{V().catch(r=>m({level:"error",event:"daemon.tick.failed",error:r}))},{kinds:["spend_limits"]}),await V(),e.role===void 0&&import("../commands/sys/import/move.js").then(({settleMoveAtDaemonStart:r})=>r(()=>!T,o=>m({level:"warn",event:"daemon.move.settle_failed",error:o}))).catch(r=>m({level:"warn",event:"daemon.move.settle_failed",error:r}))}a(or,"completeStartup");function le(){return Ye??=or().catch(t=>{throw S={phase:"initializing",message:"daemon startup recovery failed and normal services are unavailable",blockerPaths:[]},t})}a(le,"resumeStartup");try{process.on("SIGINT",ye),process.on("SIGTERM",_e),process.on("exit",be),ln(),p!==null&&m({level:"info",event:"daemon.person.resolved",fields:{person_id:p.id,source:p.source}}),d!==null&&!d.alreadyDone&&m({level:"info",event:"daemon.packages.install_migration_done",fields:{moved:d.moved,discarded:d.discarded,people:d.people}}),n!==null&&m({level:"info",event:"daemon.permissions.boot",fields:{...n}}),c!==null&&m({level:"info",event:"daemon.person.retired",fields:{person_id:c.person,joined_from:c.joinedFrom,retired:c.retired,columns:c.columns}}),N(e.role)?J=await wr():vr(hr());const t=g.token;At({epoch:t,requestHandover:Ze,registerDetached:k,startupBlock:Qe,admitStartup:tr,repairMigrations:nr}),We(),L=N(e.role)?Tr({tcp:e.tcp}):zn(e),await L.ready;const i=ur()??de("user").document_port;if(N(e.role)){const r=$r(i,Ar());try{await r.ready,ne=r}catch(o){m({level:"warn",event:"daemon.document_listener.bind_failed",fields:{port:i,error:o instanceof Error?o.message:String(o)}})}}const w=de("user").runtime;if(w?.issuer&&(I=Jr(w.issuer,k),w.unsandboxed===!0&&(F=lr({syncGrants:I}))),e.role==="api"){const r=a(()=>k(qr().catch(o=>{m({level:"error",event:"daemon.packages.sync_failed",error:o})})),"packageTick");r(),O=setInterval(r,Ne*1e3),O.unref()}if(N(e.role)&&(oe=await zr()),j(e.role)&&(ie=Wr()),ae=await Ur({serves:N(e.role),runsLanes:j(e.role)}),w?.unsandboxed===!0&&w.listener!==void 0&&m({level:"warn",event:"daemon.app_listener.refused_unsandboxed",fields:{reason:"runtime.unsandboxed is set; runtime.listener is ignored"}}),N(e.role)&&w!==void 0&&w.listener!==void 0&&w.unsandboxed!==!0&&(M=await Nr(w,async()=>await Yr(w.issuer.replace(/\/$/,"")),I),await M.ready),e.role===void 0)try{await dn()}catch(r){if($=null,r instanceof mn)return S={phase:"blocked",message:r.message,blockerPaths:r.blockerPaths},x;throw r}process.platform==="linux"&&R(D)&&(br(),await _r("app:terminal"));try{e.prepare?S={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]}:(await le(),S={phase:"ready",message:"",blockerPaths:[]})}finally{$=null}return x}catch(t){try{await x()}catch(i){throw new AggregateError([t,i],"daemon startup failed and cleanup also failed")}throw t}}a(Wn,"runDaemon");var Wi=Wn;export{jn as API_DRAIN_GRACE_MS,Vi as brokerCommandDeclaresCanvasHome,he as brokerCommandEpoch,Wi as default,j as roleRunsLanes,N as roleServesRequests,Wn as runDaemon,Hn as superviseTick,_n as teardownFleet};
@@ -1,12 +1,12 @@
1
- var D=Object.defineProperty;var a=(n,e)=>D(n,"name",{value:e,configurable:!0});import{openDb as E}from"../core/canvas/db.js";import{isPidPresent as R}from"../core/canvas/pid.js";import{isProfilePaused as p}from"../core/profiles/manifest.js";import{hasUnseenWakeMail as f}from"../core/canvas/deliveries.js";import{listPendingProviderRetries as g}from"../core/canvas/recovery.js";import{listSubmitRequestedRequests as x}from"../core/human/requests.js";import{storageConfig as I}from"../core/storage/client.js";import{emitEvent as O}from"../core/events/emit.js";import{wantsExecution as m}from"./reconcilers/node-lifecycle/wants-execution.js";import{dueAtMs as y}from"./reconcilers/fault-retry-backstop.js";import{UNUSED_UPLOAD_TTL_MS as T}from"./reconcilers/storage-due-work.js";import{RECIPE_HAS_CONTENT_SQL as A}from"./api/environment-of.js";import{busyOnlyLanes as b,collectDue as h,declareBusyOnly as o,dueSourceLanes as M,registerDueSource as i}from"./due-sources.js";import{filterAsync as v}from"../core/async-array.js";const _=a(async(n,...e)=>await(await E()).prepare(n).all(...e),"rows"),r=a(async n=>await(await E()).prepare(n).get(),"first"),u=a(n=>{if(n==null)return null;const e=Date.parse(n);return Number.isFinite(e)?e:null},"iso"),c=a(n=>{let e=null;for(const t of n)t!==null&&(e===null||t<e)&&(e=t);return e},"earliest"),L="node_id NOT IN (SELECT node_id FROM warm_pool)";let N=!1;async function S(){if(N)return;N=!0,o("brokerSupervision","acts only on live broker processes, which already make busy true"),o("controllerDeath","acts only on live controller processes"),o("pollRunObservers","follows live pids only"),o("bashDeadline","acts only on running bash jobs, which already make busy true"),o("storageMaintenance","retention and placement housekeeping: never time-critical, and it must not wake or hold a sleeping runtime"),o("purgeDueWork","physical purge of objects soft-deleted over 30 days ago: housekeeping, and a tombstone a live object references stays due forever, so it must not wake or hold a sleeping runtime"),o("ledgerSandbox","bills awake time of executions that are busy or just exited; a sleeping runtime owes nothing until it wakes, and the lane must not wake it"),o("ledgerStorage","monthly storage billing: never time-critical, and it must not wake or hold a sleeping runtime"),o("ledgerR2","moves closed months to R2: housekeeping that must not wake or hold a sleeping runtime"),i("nodeLifecycle",{nextDue:a(async()=>c((await v(await _(`SELECT node_id, status, intent, profile_id, respawn_not_before FROM node_rows
1
+ var D=Object.defineProperty;var a=(n,e)=>D(n,"name",{value:e,configurable:!0});import{openDb as E}from"../core/canvas/db.js";import{isPidPresent as R}from"../core/canvas/pid.js";import{isProfilePaused as p}from"../core/profiles/manifest.js";import{hasUnseenWakeMail as f}from"../core/canvas/deliveries.js";import{listPendingProviderRetries as g}from"../core/canvas/recovery.js";import{listSubmitRequestedRequests as x}from"../core/human/requests.js";import{storageConfig as I}from"../core/storage/client.js";import{emitEvent as O}from"../core/events/emit.js";import{wantsExecution as m}from"./reconcilers/node-lifecycle/wants-execution.js";import{dueAtMs as y}from"./reconcilers/fault-retry-backstop.js";import{UNUSED_UPLOAD_TTL_MS as T}from"./reconcilers/storage-due-work.js";import{IMAGE_BUILD_OWED_SQL as A,IMAGE_DELETE_OWED_SQL as M}from"./reconcilers/recipe-image.js";import{busyOnlyLanes as b,collectDue as h,declareBusyOnly as o,dueSourceLanes as v,registerDueSource as i}from"./due-sources.js";import{filterAsync as W}from"../core/async-array.js";const _=a(async(n,...e)=>await(await E()).prepare(n).all(...e),"rows"),r=a(async n=>await(await E()).prepare(n).get(),"first"),u=a(n=>{if(n==null)return null;const e=Date.parse(n);return Number.isFinite(e)?e:null},"iso"),c=a(n=>{let e=null;for(const t of n)t!==null&&(e===null||t<e)&&(e=t);return e},"earliest"),L="node_id NOT IN (SELECT node_id FROM warm_pool)";let N=!1;async function S(){if(N)return;N=!0,o("brokerSupervision","acts only on live broker processes, which already make busy true"),o("controllerDeath","acts only on live controller processes"),o("pollRunObservers","follows live pids only"),o("bashDeadline","acts only on running bash jobs, which already make busy true"),o("storageMaintenance","retention and placement housekeeping: never time-critical, and it must not wake or hold a sleeping runtime"),o("purgeDueWork","physical purge of objects soft-deleted over 30 days ago: housekeeping, and a tombstone a live object references stays due forever, so it must not wake or hold a sleeping runtime"),o("ledgerSandbox","bills awake time of executions that are busy or just exited; a sleeping runtime owes nothing until it wakes, and the lane must not wake it"),o("ledgerStorage","monthly storage billing: never time-critical, and it must not wake or hold a sleeping runtime"),o("ledgerR2","moves closed months to R2: housekeeping that must not wake or hold a sleeping runtime"),i("nodeLifecycle",{nextDue:a(async()=>c((await W(await _(`SELECT node_id, status, intent, profile_id, respawn_not_before FROM node_rows
2
2
  WHERE status IN ('active', 'idle') AND kind != 'human' AND ${L}
3
3
  AND pi_pid IS NULL AND respawn_not_before IS NOT NULL`),async e=>!p(e.profile_id)&&await m({node_id:e.node_id,status:e.status,intent:e.intent}))).map(e=>u(e.respawn_not_before))),"nextDue")}),i("nodeDeadline",{nextDue:a(async()=>c((await _(`SELECT deadline_at, profile_id FROM node_rows
4
4
  WHERE deadline_at IS NOT NULL AND outcome_at IS NULL AND status IN ('active', 'idle') AND kind != 'human'`)).filter(e=>!p(e.profile_id)).map(e=>u(e.deadline_at))),"nextDue")}),i("structuredRequests",{nextDue:a(async e=>await r("SELECT 1 FROM structured_requests WHERE state != 'pending' AND effects_done_at IS NULL LIMIT 1")!==void 0?e:(await r("SELECT MIN(deadline_at) AS at FROM structured_requests WHERE state = 'pending' AND deadline_at IS NOT NULL"))?.at??null,"nextDue")}),i("recipeImage",{nextDue:a(async e=>c((await _(`SELECT image_building_at FROM environments
5
- WHERE kind = 'blaxel' AND recipe_revision > COALESCE(image_revision, 0) AND ${A}`)).map(t=>t.image_building_at===null?e:Math.max(e,u(t.image_building_at)??e))),"nextDue")}),i("cronLane",{nextDue:a(async()=>{const e=(await _(`SELECT fire_at, profile FROM crons
5
+ WHERE ${A} OR ${M}`)).map(t=>t.image_building_at===null?e:Math.max(e,u(t.image_building_at)??e))),"nextDue")}),i("cronLane",{nextDue:a(async()=>{const e=(await _(`SELECT fire_at, profile FROM crons
6
6
  WHERE state = 'active' AND run_state = 'idle'
7
7
  AND NOT (held = 1 AND recur IS NULL AND expires_at IS NULL)`)).filter(s=>!p(s.profile)).map(s=>u(s.fire_at)),t=(await _("SELECT expires_at FROM crons WHERE expires_at IS NOT NULL AND run_state = 'idle'")).map(s=>u(s.expires_at));return c([...e,...t])},"nextDue")});const n=a(async e=>async()=>(await r(`SELECT MIN(next_attempt_at) AS at FROM ${e} WHERE state = 'pending' AND canceled_at IS NULL AND next_attempt_at IS NOT NULL`))?.at??null,"attempts");i("deliveryLane",{nextDue:await n("deliveries")}),i("actionLane",{nextDue:await n("daemon_actions")}),i("pendingReviewSubmit",{nextDue:a(async e=>(await x()).length>0?e:null,"nextDue")}),i("storageDueWork",{nextDue:a(async e=>{if(I()===null)return null;if(await r("SELECT 1 FROM uploads WHERE delete_pending_since IS NOT NULL LIMIT 1")!==void 0||await r("SELECT 1 FROM shares WHERE status = 'off' AND object_deleted_at IS NULL LIMIT 1")!==void 0)return e;const t=(await r("SELECT MIN(expires_at) AS at FROM shares WHERE status = 'on' AND expires_at IS NOT NULL"))?.at,s=(await r(`SELECT MIN(created_at) AS at FROM uploads u WHERE delete_pending_since IS NULL
8
- AND NOT EXISTS (SELECT 1 FROM upload_uses x WHERE x.upload_id = u.upload_id)`))?.at,l=u(s);return c([u(t),l===null?null:l+T])},"nextDue")}),i("importLane",{nextDue:a(async e=>await r(`SELECT 1 FROM import_runs WHERE state IN ('loading', 'committed') AND (claimed_by IS NULL OR lease_expires_at IS NULL OR lease_expires_at <= '${new Date(e).toISOString()}')`)!==void 0?e:null,"nextDue")}),i("faultRetryBackstop",{nextDue:a(async()=>c((await g()).map(e=>y(e))),"nextDue")})}a(S,"installDueSources");const w=12e4;async function C(n){const e=await _(`SELECT n.node_id, n.status, n.intent, n.profile_id, n.pi_pid, n.frozen_at, n.respawn_not_before, n.created, n.launched_at,
8
+ AND NOT EXISTS (SELECT 1 FROM upload_uses x WHERE x.upload_id = u.upload_id)`))?.at,l=u(s);return c([u(t),l===null?null:l+T])},"nextDue")}),i("importLane",{nextDue:a(async e=>await r(`SELECT 1 FROM import_runs WHERE state IN ('loading', 'committed') AND (claimed_by IS NULL OR lease_expires_at IS NULL OR lease_expires_at <= '${new Date(e).toISOString()}')`)!==void 0?e:null,"nextDue")}),i("faultRetryBackstop",{nextDue:a(async()=>c((await g()).map(e=>y(e))),"nextDue")})}a(S,"installDueSources");const w=12e4;async function U(n){const e=await _(`SELECT n.node_id, n.status, n.intent, n.profile_id, n.pi_pid, n.frozen_at, n.respawn_not_before, n.created, n.launched_at,
9
9
  n.turn_open_at, n.turn_closed_at,
10
10
  (SELECT x.started_at FROM executions x WHERE x.node_id = n.node_id AND x.state != 'exited') AS exec_started_at
11
11
  FROM node_rows n
12
- WHERE n.status IN ('active', 'idle') AND n.kind != 'human' AND n.${L}`);for(const t of e){if(p(t.profile_id)||!await m({node_id:t.node_id,status:t.status,intent:t.intent}))continue;if(t.pi_pid!==null&&R(t.pi_pid)){if(t.turn_open_at!==null&&t.turn_closed_at===null)return!0;const d=u(t.exec_started_at);if(t.turn_open_at===null&&d!==null&&n-d<w||await f(t.node_id))return!0;continue}if(t.respawn_not_before!==null)continue;if(t.pi_pid!==null||t.frozen_at!==null||t.status==="active")return!0;const l=Math.max(...[t.created,t.launched_at,t.exec_started_at].map(d=>u(d)??0));if(l>0&&n-l<w||t.status==="idle"&&await f(t.node_id))return!0}return!1}a(C,"nodesOweWork");async function K(n=Date.now()){await S();const{dueNow:e,nextDueMs:t}=await h(n,(l,d)=>{O({level:"warn",event:"daemon.due.source_failed",error:d,fields:{lane:l}})});return{busy:e||await C(n)||await r("SELECT 1 FROM crons WHERE run_state = 'running' LIMIT 1")!==void 0||await r("SELECT 1 FROM jobs j JOIN objects o ON o.id = j.object WHERE j.status = 'running' AND o.deleted_at IS NULL LIMIT 1")!==void 0,next_due_at:t===null?null:new Date(t).toISOString()}}a(K,"dueReport");async function V(){return await S(),[...M(),...b()]}a(V,"coveredLanes");export{w as START_GRACE_MS,V as coveredLanes,K as dueReport,S as installDueSources};
12
+ WHERE n.status IN ('active', 'idle') AND n.kind != 'human' AND n.${L}`);for(const t of e){if(p(t.profile_id)||!await m({node_id:t.node_id,status:t.status,intent:t.intent}))continue;if(t.pi_pid!==null&&R(t.pi_pid)){if(t.turn_open_at!==null&&t.turn_closed_at===null)return!0;const d=u(t.exec_started_at);if(t.turn_open_at===null&&d!==null&&n-d<w||await f(t.node_id))return!0;continue}if(t.respawn_not_before!==null)continue;if(t.pi_pid!==null||t.frozen_at!==null||t.status==="active")return!0;const l=Math.max(...[t.created,t.launched_at,t.exec_started_at].map(d=>u(d)??0));if(l>0&&n-l<w||t.status==="idle"&&await f(t.node_id))return!0}return!1}a(U,"nodesOweWork");async function V(n=Date.now()){await S();const{dueNow:e,nextDueMs:t}=await h(n,(l,d)=>{O({level:"warn",event:"daemon.due.source_failed",error:d,fields:{lane:l}})});return{busy:e||await U(n)||await r("SELECT 1 FROM crons WHERE run_state = 'running' LIMIT 1")!==void 0||await r("SELECT 1 FROM jobs j JOIN objects o ON o.id = j.object WHERE j.status = 'running' AND o.deleted_at IS NULL LIMIT 1")!==void 0,next_due_at:t===null?null:new Date(t).toISOString()}}a(V,"dueReport");async function Y(){return await S(),[...v(),...b()]}a(Y,"coveredLanes");export{w as START_GRACE_MS,Y as coveredLanes,V as dueReport,S as installDueSources};
@@ -4,6 +4,13 @@ import type { DetachedWorkLifecycle } from './broker-supervision.js';
4
4
  export declare const LEASE_MS: number;
5
5
  /** After a failed build the same revision is not tried again for this long. */
6
6
  export declare const RETRY_AFTER_FAILURE_MS: number;
7
+ /** SQL predicates over `environments`: its object is soft-deleted / is not. */
8
+ export declare const ENVIRONMENT_DELETED_SQL = "EXISTS (SELECT 1 FROM objects o WHERE o.id = environments.object AND o.deleted_at IS NOT NULL)";
9
+ export declare const ENVIRONMENT_LIVE_SQL = "NOT EXISTS (SELECT 1 FROM objects o WHERE o.id = environments.object AND o.deleted_at IS NOT NULL)";
10
+ /** A live environment with a recipe revision no image has been built for. */
11
+ export declare const IMAGE_BUILD_OWED_SQL = "(kind = 'blaxel' AND NOT EXISTS (SELECT 1 FROM objects o WHERE o.id = environments.object AND o.deleted_at IS NOT NULL) AND recipe_revision > COALESCE(image_revision, 0) AND (btrim(COALESCE(environments.setup_script, '')) <> '' OR btrim(COALESCE(environments.pi_packages, '')) <> ''\n OR EXISTS (SELECT 1 FROM environment_repos r WHERE r.environment = environments.object)))";
12
+ /** A deleted environment that may still have an image in the registry. */
13
+ export declare const IMAGE_DELETE_OWED_SQL = "(kind = 'blaxel' AND EXISTS (SELECT 1 FROM objects o WHERE o.id = environments.object AND o.deleted_at IS NOT NULL) AND (image_ref IS NOT NULL OR image_revision IS NOT NULL OR image_building_at IS NOT NULL))";
7
14
  export type EnvironmentImage = {
8
15
  state: 'base';
9
16
  } | {
@@ -29,16 +36,23 @@ export interface RecipeImageDeps {
29
36
  build?: (input: RecipeBuildInput) => Promise<{
30
37
  ref: string;
31
38
  }>;
39
+ /** Deletes the registry image `name` with every tag; an absent image is done, not an error. The default is Blaxel's DELETE. */
40
+ deleteImage?: (name: string) => Promise<void>;
32
41
  now?: () => number;
33
42
  }
34
43
  export declare class RecipeImageReconciler {
35
44
  private readonly deps;
36
45
  constructor(deps?: RecipeImageDeps);
37
- /** One pass: claim every environment with an unbuilt revision and build it detached from the tick. */
46
+ /** One pass: claim every live environment with an unbuilt revision and build it, and every deleted environment that may still have an image and delete it, each detached from the tick. */
38
47
  run(nowMs: number, ctx: {
39
48
  lifecycle: DetachedWorkLifecycle;
40
49
  }): Promise<void>;
50
+ /** Takes the lease on `environmentId` if `owed` (re-evaluated in the same statement) holds and no live lease is held; returns the column asked for. */
41
51
  private claim;
52
+ /** Runs `work` while renewing the lease at a third of its length; `work` gets the lease value current when it starts, and renewal changes only the stored value. */
53
+ private withLease;
54
+ /** Deletes the environment's image under the lease, then clears every image column so nothing is owed and an undelete rebuilds. A failure keeps the columns and schedules the retry. */
55
+ private deleteClaimed;
42
56
  private buildClaimed;
43
57
  private recordFailure;
44
58
  }
@@ -1,7 +1,6 @@
1
- var E=Object.defineProperty;var _=(n,e)=>E(n,"name",{value:e,configurable:!0});import{mkdtempSync as w}from"node:fs";import{tmpdir as b}from"node:os";import{join as v}from"node:path";import{hasUnseenWakeMail as S}from"../../core/canvas/deliveries.js";import{openDb as s,withCanvasWrite as N}from"../../core/canvas/db.js";import{emitEvent as d}from"../../core/events/emit.js";import{appendRunEvent as D}from"../../core/runs/events.js";import{blaxelConfigFromEnv as A}from"../../core/runtime/runner/blaxel/client.js";import{buildImage as R,environmentImageName as h,prepareBuildDir as T,removeBuildDir as L}from"../../core/runtime/runner/blaxel/image-build.js";import{mintInstallationToken as O}from"../api/handlers/git-credential.js";import{RECIPE_HAS_CONTENT_SQL as p,recipeOf as y}from"../api/environment-of.js";import{brokerSignalBus as C}from"../broker-signals/bus.js";const g=3*6e4,I=10*6e4;async function X(n){const e=await(await s()).prepare(`SELECT ${p} AS has_content, image_revision, image_ref, image_error FROM environments WHERE object = ?`).get(n);if(e===void 0)throw new Error(`no environment ${n}`);return e.has_content?e.image_ref===null||e.image_revision===null?{state:"pending",error:e.image_error}:{state:"image",ref:e.image_ref,revision:Number(e.image_revision)}:{state:"base"}}_(X,"resolveEnvironmentImage");async function q(n){return await C.subscribe(e=>{n(e)},{kinds:["environment_image"]})}_(q,"subscribeImageBuilt");async function U(n,e){const i=n.recipe.repositories.map(a=>a.github_full_name),r=i.length===0?null:await O(n.person,i),t=w(v(b(),"crtr-recipe-image-"));try{return await T({recipe:n.recipe,revision:n.revision,token:r?.token??null,dir:t}),await R(e,h(n.environmentId),t)}finally{L(t)}}_(U,"defaultBuild");class z{static{_(this,"RecipeImageReconciler")}deps;constructor(e={}){this.deps=e}async run(e,i){if(i.lifecycle.acceptsDetachedWork())try{const r=new Date(e).toISOString(),t=await(await s()).prepare(`SELECT object FROM environments WHERE kind = 'blaxel' AND recipe_revision > COALESCE(image_revision, 0) AND ${p}
2
- AND (image_building_at IS NULL OR image_building_at <= ?)`).all(r);for(const{object:a}of t){const c=await this.claim(a,e);c!==null&&i.lifecycle.registerDetached(this.buildClaimed(a,c.revision,c.lease).catch(o=>{d({level:"error",event:"recipe_image.failed",error:o})}))}}catch(r){d({level:"error",event:"recipe_image.reconcile_failed",error:r})}}async claim(e,i){const r=new Date(i+g).toISOString(),t=await(await s()).prepare(`UPDATE environments SET image_building_at = ?
3
- WHERE object = ? AND kind = 'blaxel' AND recipe_revision > COALESCE(image_revision, 0) AND ${p} AND (image_building_at IS NULL OR image_building_at <= ?)
4
- RETURNING recipe_revision`).get(r,e,new Date(i).toISOString());return t===void 0?null:{revision:Number(t.recipe_revision),lease:r}}async buildClaimed(e,i,r){const t=this.deps.now??Date.now;let a=r;const c=setInterval(()=>{const o=new Date(t()+g).toISOString();(async()=>{(await(await s()).prepare("UPDATE environments SET image_building_at = ? WHERE object = ? AND image_building_at = ?").run(o,e,a)).changes===1&&(a=o)})().catch(()=>{})},g/3);c.unref();try{const o=await y(e);if(o===null||o.revision!==i){await(await s()).prepare("UPDATE environments SET image_building_at = NULL WHERE object = ? AND image_building_at = ?").run(e,a);return}let l;try{const m=await(await s()).prepare("SELECT person FROM profiles WHERE environment_id = ? ORDER BY created_at LIMIT 1").get(e);if(m===void 0)throw new Error(`no profile runs in environment ${e}, so there is no person to take a GitHub token for`);const u={environmentId:e,revision:i,recipe:o,person:m.person};l=await(this.deps.build??(f=>U(f,A())))(u)}catch(m){await this.recordFailure(e,a,m instanceof Error?m.message:String(m),t());return}await(await s()).prepare(`UPDATE environments SET image_revision = ?, image_ref = ?, image_error = NULL, image_building_at = NULL
5
- WHERE object = ? AND image_building_at = ? AND COALESCE(image_revision, 0) < ?`).run(i,l.ref,e,a,i)}finally{clearInterval(c)}}async recordFailure(e,i,r,t){const a=new Date(t+I).toISOString();if((await(await s()).prepare("UPDATE environments SET image_error = ?, image_building_at = ? WHERE object = ? AND image_building_at = ?").run(r,a,e,i)).changes===1){d({level:"error",event:"recipe_image.build_failed",fields:{environment_id:e,error:r}});for(const o of await W(e))try{await N(async l=>{await D(l,o.run_id,o.node_id,"environment.image_failed",{environment_id:e,error:r})})}catch(l){d({level:"error",event:"recipe_image.failure_event_failed",node_id:o.node_id,error:l})}}}}async function W(n){const e=await(await s()).prepare(`SELECT n.node_id, n.run_id FROM nodes n JOIN profiles p ON p.id = n.profile_id
1
+ var A=Object.defineProperty;var d=(o,e)=>A(o,"name",{value:e,configurable:!0});import{mkdtempSync as T}from"node:fs";import{tmpdir as h}from"node:os";import{join as R}from"node:path";import{hasUnseenWakeMail as O}from"../../core/canvas/deliveries.js";import{openDb as l,withCanvasWrite as U}from"../../core/canvas/db.js";import{emitEvent as g}from"../../core/events/emit.js";import{appendRunEvent as y}from"../../core/runs/events.js";import{blaxelConfigFromEnv as u}from"../../core/runtime/runner/blaxel/client.js";import{buildImage as I,deleteImage as W,environmentImageName as f,prepareBuildDir as C,removeBuildDir as j}from"../../core/runtime/runner/blaxel/image-build.js";import{mintInstallationToken as H}from"../api/handlers/git-credential.js";import{RECIPE_HAS_CONTENT_SQL as w,recipeOf as x}from"../api/environment-of.js";import{brokerSignalBus as $}from"../broker-signals/bus.js";const E=3*6e4,N=10*6e4,p="EXISTS (SELECT 1 FROM objects o WHERE o.id = environments.object AND o.deleted_at IS NOT NULL)",b=`NOT ${p}`,S=`(kind = 'blaxel' AND ${b} AND recipe_revision > COALESCE(image_revision, 0) AND ${w})`,L=`(kind = 'blaxel' AND ${p} AND (image_ref IS NOT NULL OR image_revision IS NOT NULL OR image_building_at IS NOT NULL))`;async function ee(o){const e=await(await l()).prepare(`SELECT ${w} AS has_content, image_revision, image_ref, image_error FROM environments WHERE object = ?`).get(o);if(e===void 0)throw new Error(`no environment ${o}`);return e.has_content?e.image_ref===null||e.image_revision===null?{state:"pending",error:e.image_error}:{state:"image",ref:e.image_ref,revision:Number(e.image_revision)}:{state:"base"}}d(ee,"resolveEnvironmentImage");async function ie(o){return await $.subscribe(e=>{o(e)},{kinds:["environment_image"]})}d(ie,"subscribeImageBuilt");async function k(o,e){const t=o.recipe.repositories.map(r=>r.github_full_name),i=t.length===0?null:await H(o.person,t),a=T(R(h(),"crtr-recipe-image-"));try{return await C({recipe:o.recipe,revision:o.revision,token:i?.token??null,dir:a}),await I(e,f(o.environmentId),a)}finally{j(a)}}d(k,"defaultBuild");class te{static{d(this,"RecipeImageReconciler")}deps;constructor(e={}){this.deps=e}async run(e,t){if(t.lifecycle.acceptsDetachedWork())try{const i=new Date(e).toISOString(),a=await l(),r=await a.prepare(`SELECT object FROM environments WHERE ${S} AND (image_building_at IS NULL OR image_building_at <= ?)`).all(i);for(const{object:n}of r){const s=await this.claim(n,e,S,"recipe_revision");s!==null&&t.lifecycle.registerDetached(this.buildClaimed(n,Number(s.recipe_revision),s.lease).catch(_=>{g({level:"error",event:"recipe_image.failed",error:_})}))}const c=await a.prepare(`SELECT object FROM environments WHERE ${L} AND (image_building_at IS NULL OR image_building_at <= ?)`).all(i);for(const{object:n}of c){const s=await this.claim(n,e,L,"object");s!==null&&t.lifecycle.registerDetached(this.withLease(n,s.lease,_=>this.deleteClaimed(n,_)).catch(_=>{g({level:"error",event:"recipe_image.delete_failed",error:_})}))}}catch(i){g({level:"error",event:"recipe_image.reconcile_failed",error:i})}}async claim(e,t,i,a){const r=new Date(t+E).toISOString(),c=await(await l()).prepare(`UPDATE environments SET image_building_at = ?
2
+ WHERE object = ? AND ${i} AND (image_building_at IS NULL OR image_building_at <= ?)
3
+ RETURNING ${a} AS recipe_revision`).get(r,e,new Date(t).toISOString());return c===void 0?null:{recipe_revision:c.recipe_revision,lease:r}}async withLease(e,t,i){const a=this.deps.now??Date.now;let r=t;const c=setInterval(()=>{const n=new Date(a()+E).toISOString();(async()=>{(await(await l()).prepare("UPDATE environments SET image_building_at = ? WHERE object = ? AND image_building_at = ?").run(n,e,r)).changes===1&&(r=n)})().catch(()=>{})},E/3);c.unref();try{await i(()=>r)}finally{clearInterval(c)}}async deleteClaimed(e,t){try{await(this.deps.deleteImage??(i=>W(u(),i)))(f(e))}catch(i){const a=i instanceof Error?i.message:String(i),r=new Date((this.deps.now??Date.now)()+N).toISOString();(await(await l()).prepare("UPDATE environments SET image_error = ?, image_building_at = ? WHERE object = ? AND image_building_at = ?").run(`deleting the image failed: ${a}`,r,e,t())).changes===1&&g({level:"error",event:"recipe_image.delete_failed",fields:{environment_id:e,error:a}});return}await(await l()).prepare("UPDATE environments SET image_ref = NULL, image_revision = NULL, image_error = NULL, image_building_at = NULL WHERE object = ? AND image_building_at = ?").run(e,t())}async buildClaimed(e,t,i){const a=this.deps.now??Date.now;await this.withLease(e,i,async r=>{const c=await x(e);if(c===null||c.revision!==t){await(await l()).prepare("UPDATE environments SET image_building_at = NULL WHERE object = ? AND image_building_at = ?").run(e,r());return}let n;try{const m=await(await l()).prepare("SELECT person FROM profiles WHERE environment_id = ? ORDER BY created_at LIMIT 1").get(e);if(m===void 0)throw new Error(`no profile runs in environment ${e}, so there is no person to take a GitHub token for`);const D={environmentId:e,revision:t,recipe:c,person:m.person};n=await(this.deps.build??(v=>k(v,u())))(D)}catch(m){await this.recordFailure(e,r(),m instanceof Error?m.message:String(m),a());return}const s=await l();(await s.prepare(`UPDATE environments SET image_revision = ?, image_ref = ?, image_error = NULL, image_building_at = NULL
4
+ WHERE object = ? AND image_building_at = ? AND COALESCE(image_revision, 0) < ? AND ${b}`).run(t,n.ref,e,r(),t)).changes!==1&&await s.prepare(`UPDATE environments SET image_ref = ?, image_building_at = NULL WHERE object = ? AND ${p}`).run(n.ref,e)})}async recordFailure(e,t,i,a){const r=new Date(a+N).toISOString();if((await(await l()).prepare("UPDATE environments SET image_error = ?, image_building_at = ? WHERE object = ? AND image_building_at = ?").run(i,r,e,t)).changes===1){g({level:"error",event:"recipe_image.build_failed",fields:{environment_id:e,error:i}});for(const n of await F(e))try{await U(async s=>{await y(s,n.run_id,n.node_id,"environment.image_failed",{environment_id:e,error:i})})}catch(s){g({level:"error",event:"recipe_image.failure_event_failed",node_id:n.node_id,error:s})}}}}async function F(o){const e=await(await l()).prepare(`SELECT n.node_id, n.run_id FROM nodes n JOIN profiles p ON p.id = n.profile_id
6
5
  WHERE p.environment_id = ? AND n.status IN ('active', 'idle') AND n.run_id IS NOT NULL
7
- AND NOT EXISTS (SELECT 1 FROM executions e WHERE e.node_id = n.node_id AND e.state != 'exited')`).all(n),i=[];for(const r of e)await S(r.node_id)&&i.push(r);return i}_(W,"nodesWaitingOnImage");export{g as LEASE_MS,I as RETRY_AFTER_FAILURE_MS,z as RecipeImageReconciler,W as nodesWaitingOnImage,X as resolveEnvironmentImage,q as subscribeImageBuilt};
6
+ AND NOT EXISTS (SELECT 1 FROM executions e WHERE e.node_id = n.node_id AND e.state != 'exited')`).all(o),t=[];for(const i of e)await O(i.node_id)&&t.push(i);return t}d(F,"nodesWaitingOnImage");export{p as ENVIRONMENT_DELETED_SQL,b as ENVIRONMENT_LIVE_SQL,S as IMAGE_BUILD_OWED_SQL,L as IMAGE_DELETE_OWED_SQL,E as LEASE_MS,N as RETRY_AFTER_FAILURE_MS,te as RecipeImageReconciler,F as nodesWaitingOnImage,ee as resolveEnvironmentImage,ie as subscribeImageBuilt};
@@ -7,8 +7,6 @@ export declare const STORAGE_DUE_WORK_INTERVAL_MS = 60000;
7
7
  export declare const UNUSED_UPLOAD_TTL_MS: number;
8
8
  /** Storage deletes attempted per kind per pass; the rest wait for the next pass. */
9
9
  export declare const STORAGE_DUE_WORK_BUDGET = 200;
10
- /** A deleted node's blobs and `objects` row are removed this long after `deleted_at`; until then the owner can undelete it. */
11
- export declare const NODE_BLOB_RETENTION_MS: number;
12
10
  /** Nodes purged per pass; the rest wait for the next pass. */
13
11
  export declare const NODE_PURGE_BUDGET = 25;
14
12
  /** Consecutive `storage_unavailable` failures after which a pass stops early. */
@@ -35,8 +33,9 @@ export declare class StorageDueWorkReconciler {
35
33
  run(now: number, ctx: StorageDueWorkContext): void;
36
34
  /** One pass over the due-work rows. Exposed for tests. */
37
35
  pass(now: number, lane?: LanePass): Promise<StorageDueWorkResult>;
38
- /** Delete the blobs of nodes deleted over 90 days ago, then the node's `objects` row. Every such node loses its blobs;
39
- * its row goes only if no foreign key refers to it (`objects.owner`, `revisions.author`, `object_kinds.owner` have no
36
+ /** Delete the blobs of every deleted node, then the node's `objects` row. A node cannot be undeleted, so nothing waits. A node is
37
+ * skipped while a live node still has its `run_id` (an isolated run's members outlive a deleted root and read the root's
38
+ * attachments). The row goes only if no foreign key refers to it (`objects.owner`, `revisions.author`, `object_kinds.owner` have no
40
39
  * cascade), which Postgres decides at the DELETE (23503), so a reference added meanwhile cannot slip through. Blobs go
41
40
  * first, outside any transaction: a crash between the two is retried (the retry finds no blobs), and two passes at once
42
41
  * both succeed because deleting an absent blob and an absent row are no-ops. The sweep walks `(deleted_at, id)` from a
@@ -1,2 +1,3 @@
1
- var S=Object.defineProperty;var u=(_,a)=>S(_,"name",{value:a,configurable:!0});import{blobStore as O}from"../../core/blobs/index.js";import{openDb as v,withCanvasWrite as w}from"../../core/canvas/db.js";import{emitEvent as h}from"../../core/events/emit.js";import{operationIdContext as E}from"../../core/events/operation-id.js";import{RunError as R}from"../../core/runs/operations.js";import{storageClient as b,storageConfig as N}from"../../core/storage/client.js";import{deleteUploadRow as T,expireShares as y,markShareObjectDeleted as k,markUploadsDeletePending as U,pendingUploadDeletes as A,sharesOwingObjectDelete as x,staleUnusedUploads as L}from"../../core/storage/tables.js";import{runThrottledLane as I}from"./throttled-lane.js";const j=6e4,W=1440*6e4,D=200,B=5*6e4,M=2160*60*6e4,m=25,F=["conversations","events","jobs","attachments"],G=3,C=u(_=>_ instanceof R&&_.code==="storage_unavailable","unavailable");class z{static{u(this,"StorageDueWorkReconciler")}deps;constructor(a={config:N,client:b}){this.deps=a}run(a,e){if(!e.lifecycle.acceptsDetachedWork())return;const t=E.fresh(()=>I("storage-due-work","",a,j,B,async l=>{await this.pass(a,l)})).then(()=>{}).catch(l=>{E.fresh(()=>h({level:"error",event:"storage.due_work.failed",error:l}))});e.lifecycle.registerDetached(t)}async pass(a,e){const t={marked_uploads:0,expired_shares:0,deleted_uploads:0,deleted_share_objects:0,purged_nodes:0,failed:0};return t.purged_nodes=await this.purgeDeletedNodes(a,e),this.deps.config()&&await this.settleFileTransfers(a,t),(t.purged_nodes||t.marked_uploads||t.expired_shares||t.deleted_uploads||t.deleted_share_objects)&&h({level:"info",event:"storage.due_work.settled",outcome:"succeeded",fields:{...t}}),t}async purgeDeletedNodes(a,e){const t=new Date(a-M).toISOString(),l=await v(),f=e?.state?JSON.parse(e.state):null,o=await l.prepare(`SELECT id, deleted_at FROM objects WHERE type = 'node' AND deleted_at < ?
2
- AND (deleted_at, id) > (?, ?) ORDER BY deleted_at, id LIMIT ?`).all(t,f?.deleted_at??"",f?.id??"",m);if(o.length===0)return f&&await e?.save(null),0;const p=await(this.deps.blobs??O)();let d=0,s=-1;for(const[r,{id:c}]of o.entries())try{for(const i of F)for(const n of await p.list(`${i}/${c}/`))await p.delete(n);await w(async i=>{await i.prepare("DELETE FROM objects WHERE id = ? AND type = 'node' AND deleted_at < ?").run(c,t)},{savepoint:!0}),d++}catch(i){i.code!=="23503"&&(s<0&&(s=r),h({level:"warn",event:"storage.due_work.node_purge_failed",error:i,fields:{node_id:c}}))}if(s>=0){const r=o[s-1];await e?.save(r?JSON.stringify({deleted_at:r.deleted_at,id:r.id}):e.state)}else{const r=o[o.length-1];await e?.save(o.length<m?null:JSON.stringify({deleted_at:r.deleted_at,id:r.id}))}return d}async settleFileTransfers(a,e){const t=new Date(a).toISOString(),{marked:l,expired:f}=await w(async d=>{const s=await L(new Date(a-W).toISOString(),d);return await U(s,d,t),{marked:s.length,expired:(await y(t,d)).length}});e.marked_uploads=l,e.expired_shares=f;const o=(await A()).slice(0,D),p=(await x()).slice(0,D);if(o.length||p.length){const d=this.deps.client();let s,r=0,c=!1;const i=u(async n=>{if(c)return!1;try{return await n(),r=0,!0}catch(g){return e.failed++,s??=g,r=C(g)?r+1:0,r>=G&&(c=!0),!1}},"attempt");for(const n of o)await i(()=>d.deleteUpload(n.upload_id))&&(await T(n.upload_id),e.deleted_uploads++);for(const n of p)await i(()=>d.deleteShare(n.share_id))&&(await k(n.share_id),e.deleted_share_objects++);s!==void 0&&h({level:"warn",event:"storage.due_work.deletes_failed",error:s,fields:{failed:e.failed,storage_unavailable:c}})}}}export{M as NODE_BLOB_RETENTION_MS,m as NODE_PURGE_BUDGET,G as STORAGE_DOWN_AFTER,D as STORAGE_DUE_WORK_BUDGET,j as STORAGE_DUE_WORK_INTERVAL_MS,z as StorageDueWorkReconciler,W as UNUSED_UPLOAD_TTL_MS};
1
+ var m=Object.defineProperty;var f=(c,e)=>m(c,"name",{value:e,configurable:!0});import{blobStore as O}from"../../core/blobs/index.js";import{openDb as R,withCanvasWrite as g}from"../../core/canvas/db.js";import{emitEvent as u}from"../../core/events/emit.js";import{operationIdContext as w}from"../../core/events/operation-id.js";import{RunError as b}from"../../core/runs/operations.js";import{storageClient as v,storageConfig as T}from"../../core/storage/client.js";import{deleteUploadRow as N,expireShares as y,markShareObjectDeleted as k,markUploadsDeletePending as L,pendingUploadDeletes as U,sharesOwingObjectDelete as A,staleUnusedUploads as I}from"../../core/storage/tables.js";import{runThrottledLane as x}from"./throttled-lane.js";const W=6e4,j=1440*6e4,S=200,M=5*6e4,D=25,F=["conversations","events","jobs","attachments"],C=3,G=f(c=>c instanceof b&&c.code==="storage_unavailable","unavailable");class q{static{f(this,"StorageDueWorkReconciler")}deps;constructor(e={config:T,client:v}){this.deps=e}run(e,r){if(!r.lifecycle.acceptsDetachedWork())return;const t=w.fresh(()=>x("storage-due-work","",e,W,M,async s=>{await this.pass(e,s)})).then(()=>{}).catch(s=>{w.fresh(()=>u({level:"error",event:"storage.due_work.failed",error:s}))});r.lifecycle.registerDetached(t)}async pass(e,r){const t={marked_uploads:0,expired_shares:0,deleted_uploads:0,deleted_share_objects:0,purged_nodes:0,failed:0};return t.purged_nodes=await this.purgeDeletedNodes(r),this.deps.config()&&await this.settleFileTransfers(e,t),(t.purged_nodes||t.marked_uploads||t.expired_shares||t.deleted_uploads||t.deleted_share_objects)&&u({level:"info",event:"storage.due_work.settled",outcome:"succeeded",fields:{...t}}),t}async purgeDeletedNodes(e){const r=await R(),t=e?.state?JSON.parse(e.state):null,s=await r.prepare(`SELECT id, deleted_at FROM objects WHERE type = 'node' AND deleted_at IS NOT NULL
2
+ AND NOT EXISTS (SELECT 1 FROM nodes n WHERE n.run_id = objects.id)
3
+ AND (deleted_at, id) > (?, ?) ORDER BY deleted_at, id LIMIT ?`).all(t?.deleted_at??"",t?.id??"",D);if(s.length===0)return t&&await e?.save(null),0;const _=await(this.deps.blobs??O)();let p=0,i=-1;for(const[a,{id:d}]of s.entries())try{for(const o of F)for(const l of await _.list(`${o}/${d}/`))o==="conversations"&&await r.prepare("SELECT 1 FROM conversation_parts WHERE blob_key = ? LIMIT 1").get(l)!==void 0||await _.delete(l);await g(async o=>{await o.prepare("DELETE FROM objects WHERE id = ? AND type = 'node' AND deleted_at IS NOT NULL").run(d)},{savepoint:!0}),p++}catch(o){o.code!=="23503"&&(i<0&&(i=a),u({level:"warn",event:"storage.due_work.node_purge_failed",error:o,fields:{node_id:d}}))}if(i>=0){const a=s[i-1];await e?.save(a?JSON.stringify({deleted_at:a.deleted_at,id:a.id}):e.state)}else{const a=s[s.length-1];await e?.save(s.length<D?null:JSON.stringify({deleted_at:a.deleted_at,id:a.id}))}return p}async settleFileTransfers(e,r){const t=new Date(e).toISOString(),{marked:s,expired:_}=await g(async a=>{const d=await I(new Date(e-j).toISOString(),a);return await L(d,a,t),{marked:d.length,expired:(await y(t,a)).length}});r.marked_uploads=s,r.expired_shares=_;const p=(await U()).slice(0,S),i=(await A()).slice(0,S);if(p.length||i.length){const a=this.deps.client();let d,o=0,l=!1;const h=f(async n=>{if(l)return!1;try{return await n(),o=0,!0}catch(E){return r.failed++,d??=E,o=G(E)?o+1:0,o>=C&&(l=!0),!1}},"attempt");for(const n of p)await h(()=>a.deleteUpload(n.upload_id))&&(await N(n.upload_id),r.deleted_uploads++);for(const n of i)await h(()=>a.deleteShare(n.share_id))&&(await k(n.share_id),r.deleted_share_objects++);d!==void 0&&u({level:"warn",event:"storage.due_work.deletes_failed",error:d,fields:{failed:r.failed,storage_unavailable:l}})}}}export{D as NODE_PURGE_BUDGET,C as STORAGE_DOWN_AFTER,S as STORAGE_DUE_WORK_BUDGET,W as STORAGE_DUE_WORK_INTERVAL_MS,q as StorageDueWorkReconciler,j as UNUSED_UPLOAD_TTL_MS};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.603",
3
+ "version": "0.3.605",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -145,7 +145,7 @@
145
145
  },
146
146
  "license": "UNLICENSED",
147
147
  "dependencies": {
148
- "@north-light/identity": "0.3.603",
148
+ "@north-light/identity": "0.3.605",
149
149
  "@earendil-works/chord": "1.1.0",
150
150
  "@earendil-works/pi-agent-core": "1.1.0",
151
151
  "@earendil-works/pi-ai": "1.1.0",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.603",
3
+ "version": "0.3.605",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",