@north-light/cli 0.3.744 → 0.3.745

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 (71) hide show
  1. package/README.md +2 -2
  2. package/dist/builtin-memory/crouter-concepts/scopes-and-trust.md +2 -2
  3. package/dist/builtin-memory/crouter-sdk/README.md +1 -1
  4. package/dist/builtin-memory/crouter-sdk/client.md +1 -1
  5. package/dist/builtin-memory/crouter-sdk/getting-started.md +3 -38
  6. package/dist/clients/attach/viewer.js +1 -1
  7. package/dist/commands/sys/provider-login.js +2 -2
  8. package/dist/commands/sys.js +1 -1
  9. package/dist/core/canvas/daemon-owner.d.ts +1 -1
  10. package/dist/core/canvas/paths.d.ts +1 -1
  11. package/dist/core/canvas/person-state.d.ts +3 -0
  12. package/dist/core/canvas/person-state.js +1 -1
  13. package/dist/core/canvas/person.d.ts +2 -3
  14. package/dist/core/canvas/person.js +7 -7
  15. package/dist/core/environments.d.ts +0 -10
  16. package/dist/core/environments.js +1 -1
  17. package/dist/core/runtime/blaxel-environment.js +1 -1
  18. package/dist/core/secrets.d.ts +2 -4
  19. package/dist/core/secrets.js +1 -1
  20. package/dist/core/spaces/space.js +2 -2
  21. package/dist/core/user-settings.js +1 -1
  22. package/dist/daemon/api/environment-of.d.ts +1 -1
  23. package/dist/daemon/api/environment-of.js +3 -3
  24. package/dist/daemon/api/handlers/document-access.js +1 -1
  25. package/dist/daemon/api/router.d.ts +1 -1
  26. package/dist/daemon/crtrd-cli.js +1 -1
  27. package/dist/daemon/crtrd.d.ts +4 -2
  28. package/dist/daemon/crtrd.js +20 -20
  29. package/dist/daemon/manage.d.ts +0 -8
  30. package/dist/daemon/manage.js +3 -3
  31. package/dist/daemon/reconcilers/node-lifecycle/remote-wake.js +2 -2
  32. package/dist/daemon/reconcilers/storage-maintenance.d.ts +0 -2
  33. package/dist/daemon/reconcilers/storage-maintenance.js +1 -1
  34. package/docs/concepts/scopes-and-trust.md +2 -2
  35. package/docs/public-api.md +1 -7
  36. package/docs/sdk/README.md +1 -1
  37. package/docs/sdk/client.md +1 -1
  38. package/docs/sdk/getting-started.md +3 -38
  39. package/package.json +3 -3
  40. package/packages/crouter-api/dist/commands/sys/provider-login.js +2 -2
  41. package/packages/crouter-api/dist/commands/sys.js +1 -3
  42. package/packages/crouter-api/dist/core/canvas/paths.js +1 -1
  43. package/packages/crouter-api/dist/core/canvas/person-state.js +4 -0
  44. package/packages/crouter-api/dist/core/canvas/person.js +2 -14
  45. package/packages/crouter-api/dist/core/environments.js +2 -38
  46. package/packages/crouter-api/dist/core/model-auth/daemon-login.js +2 -2
  47. package/packages/crouter-api/dist/core/runtime/blaxel-environment.js +3 -3
  48. package/packages/crouter-api/dist/core/secrets.js +1 -11
  49. package/packages/crouter-api/dist/core/spaces/space.js +2 -2
  50. package/packages/crouter-api/dist/core/user-settings.js +1 -1
  51. package/packages/crouter-api/dist/daemon/api/environment-of.js +7 -4
  52. package/packages/crouter-api/dist/daemon/manage.js +0 -4
  53. package/packages/crouter-api/dist/daemon/reconcilers/node-lifecycle/remote-wake.js +2 -2
  54. package/packages/crouter-api/package.json +1 -1
  55. package/packages/crouter-identity/package.json +1 -1
  56. package/packages/crouter-plugin/package.json +3 -3
  57. package/runtime.lock.json +14 -14
  58. package/dist/commands/sys/connect.d.ts +0 -1
  59. package/dist/commands/sys/connect.js +0 -3
  60. package/dist/commands/sys/db.d.ts +0 -1
  61. package/dist/commands/sys/db.js +0 -1
  62. package/dist/core/canvas/export-sqlite.d.ts +0 -14
  63. package/dist/core/canvas/export-sqlite.js +0 -3
  64. package/dist/daemon/api/document-listener.d.ts +0 -7
  65. package/dist/daemon/api/document-listener.js +0 -1
  66. package/dist/daemon/api/document-secret.d.ts +0 -2
  67. package/dist/daemon/api/document-secret.js +0 -1
  68. package/dist/daemon/export-sqlite-run.d.ts +0 -1
  69. package/dist/daemon/export-sqlite-run.js +0 -4
  70. package/packages/crouter-api/dist/commands/sys/connect.js +0 -185
  71. package/packages/crouter-api/dist/commands/sys/db.js +0 -69
@@ -1,21 +1,21 @@
1
- var lr=Object.defineProperty;var s=(e,l)=>lr(e,"name",{value:l,configurable:!0});import{applyBootSettings as dr}from"./boot-settings.js";import{startBrokerMemoryCap as pr}from"./broker-memory-cap.js";import{startPeerOutbox as mr}from"./peer/outbox.js";import{reportMachineStatus as fr}from"../core/peer/directory.js";import{createPeerRelay as ur}from"./peer/relay-service.js";import{writeFileSync as hr,readFileSync as wr,rmSync as vr,mkdirSync as xe,existsSync as P,unlinkSync as De,chmodSync as Te}from"node:fs";import{createServer as Y}from"node:http";import{dirname as gr}from"node:path";import{envCrtrdTcp as Ce,envDocumentPort as yr}from"../shared/env.js";import{openCanvasConversationStore as Sr,serveCanvasConversationStore as _r}from"../core/canvas/sessions.js";import{installConversationStore as br}from"../core/conversation-store/index.js";import{pollRunObservers as kr}from"./runs/observer.js";import{randomBytes as Le}from"node:crypto";import{apiSocketPath as $e,crtrHome as Rr}from"../core/canvas/paths.js";import{activeAppUsers as Pr}from"../core/spaces/users.js";import{ensureAppSpace as Er,ensureUserFiles as Ir}from"../core/spaces/space.js";import{LAUNCHER_SOCKET as C}from"../launcher/spec.js";import{launcherRequest as N}from"../launcher/client.js";import{installLauncherEventSink as xr}from"./launcher-events.js";import{initializeEmptyLayout as Dr,layoutNeedsMigration as Tr,socketDir as Ae}from"../core/layout.js";import{migrateLooseKeys as Cr}from"../core/layout-migrate/loose-keys.js";import{relocateProfileFolders as Lr}from"../core/profiles/relocate.js";import{getNode as $r,getRow as Ar,listNodesForSupervision as Ne,listParkedResidentsWithWakeMail as Nr,setFrozen as Me}from"../core/canvas/index.js";import{createApiServer as Mr,closeServer as Oe}from"./api/server.js";import{Router as Or}from"./api/router.js";import{healthRoutes as Gr}from"./api/handlers/health.js";import{createDocumentListener as Fr}from"./api/document-listener.js";import{documentSecret as Br}from"./api/document-secret.js";import{createAppListener as Hr}from"./api/app-listener.js";import{registerMachineEnvironment as jr}from"../core/environments.js";import{registerBlaxelRunnerFromEnv as zr}from"../core/secrets/blaxel-register.js";import{markCloudRole as Ur,resolvePerson as qr,retireLocalPerson as Wr,setPersonId as Kr}from"../core/canvas/person.js";import{backfillNodeApps as Ge,runPermissionsBoot as Jr}from"../core/permissions/boot.js";import{startRunNotices as Vr}from"./run-notices.js";import{startGrantEffects as Yr}from"./reconcilers/grant-effects.js";import{syncPackages as Qr}from"../core/packages/directory-sync.js";import{startActivationDelivery as Xr}from"../core/model-auth/activations.js";import{createGrantSync as Zr,GRANT_SYNC_INTERVAL_S as Fe}from"../core/grants/sync.js";import{sweepSandboxes as et}from"../core/grants/on-sync.js";import{rebuildCronExecutions as rt}from"./cron/run-socket.js";import{hasSyncedGrants as tt}from"../core/grants/mirror.js";import{readConfig as fe}from"../core/config.js";import{reconcileUndeliveredTickets as nt}from"./human/sweep.js";import{resetHandedOffDeliveries as ot}from"../core/canvas/deliveries.js";import{resetHandedOffDaemonActions as it}from"../core/canvas/daemon-actions.js";import{sweepReviews as at}from"./review/sweep.js";import{pidfilePath as ue}from"./pidfile.js";import{rendererWarning as st}from"../core/runtime/package-health.js";import{DEFAULT_INTERVAL_MS as ct}from"./supervise-cadence.js";import{createResumeDetector as lt}from"./resume-detector.js";import{setFatalFaultAnnouncer as dt}from"../core/canvas/recovery.js";import{BrokerSupervisionReconciler as pt}from"./reconcilers/broker-supervision.js";import{MachineOfflineReconciler as mt}from"./reconcilers/machine-offline.js";import{ControllerDeathReconciler as ft}from"./reconcilers/controller-death.js";import{NodeLifecycleReconciler as ut}from"./reconcilers/node-lifecycle/tick.js";import{NodeDeadlineReconciler as ht}from"./reconcilers/node-deadline.js";import{CronLaneReconciler as wt}from"./reconcilers/cron-lane.js";import{DeliveryLaneReconciler as vt}from"./reconcilers/delivery-lane.js";import{ActionLaneReconciler as gt}from"./reconcilers/action-lane.js";import{endLiveExecution as yt,hasObservedExit as St,latestExecutionForNode as _t,migrateLegacyExecutionIdentities as bt}from"../core/canvas/executions.js";import{revokePriorEpochNodeTokens as kt}from"../core/canvas/node-tokens.js";import{PendingReviewSubmitReconciler as Rt}from"./reconcilers/pending-review-submit.js";import{StorageMaintenanceReconciler as Pt}from"./reconcilers/storage-maintenance.js";import{StorageDueWorkReconciler as Et}from"./reconcilers/storage-due-work.js";import{GroupInviteExpiryReconciler as It}from"./reconcilers/group-invite-expiry.js";import{PurgeDueWorkReconciler as xt}from"./reconcilers/purge-due-work.js";import{assertLedgerEnv as Dt}from"../core/ledger/rates.js";import{LedgerSandboxReconciler as Tt}from"./reconcilers/ledger-sandbox.js";import{LedgerStorageReconciler as Ct}from"./reconcilers/ledger-storage.js";import{LedgerR2Reconciler as Lt}from"./reconcilers/ledger-r2.js";import{importedNodesHeld as he}from"./reconcilers/live-obligation.js";import{ImportLaneReconciler as $t}from"./reconcilers/import-lane.js";import{BashDeadlineReconciler as At}from"./reconcilers/bash-deadline.js";import{FaultRetryBackstopReconciler as Nt}from"./reconcilers/fault-retry-backstop.js";import{StructuredRequestReconciler as Mt}from"./reconcilers/structured-request-lane.js";import{RecipeImageReconciler as Ot,subscribeImageBuilt as Gt}from"./reconcilers/recipe-image.js";import{reconcileStructuredRequestSidecars as Ft}from"./structured-requests/boot.js";import{captureLivenessSnapshot as Be,capturePidCommand as Bt,captureTeardownSnapshot as He,isPidAlive as Ht,isAnyPidAlive as je,killProcessTreePids as ze}from"../core/canvas/pid.js";import{bindFleet as jt,boundFleet as Ue}from"../core/runtime/fleet.js";import{bindDaemonControl as zt,clearDaemonControl as Ut}from"./control.js";import{execDaemon as qt,spawnDaemon as Wt}from"./manage.js";import{reconcileAndMigrateBoot as Kt}from"../core/canvas/boot.js";import{resolveInstallId as Jt}from"../core/canvas/install-id.js";import{setInstallId as Vt}from"../core/runtime/nodes.js";import{claimDaemonOwnership as Yt,daemonOwnershipApplies as Qt,daemonOwnershipClaimed as Xt,releaseDaemonOwnership as qe}from"../core/canvas/daemon-owner.js";import{canvasDatabaseUrl as Zt,closeAllDbs as we,openDb as en,withCanvasWrite as ve}from"../core/canvas/db.js";import{importSqliteCanvasIfPresent as rn}from"../core/canvas/import-sqlite.js";import{ensurePostgres as tn,ensurePostgresHealthy as nn,stopPostgres as on,withPostgresStartLock as an}from"./postgres/index.js";import{brokerSignalBus as M}from"./broker-signals/bus.js";import{brokerSignalStreams as sn}from"./api/handlers/broker-signals.js";import{setRequestsStartRunObservers as cn}from"./api/handlers/broker-ops.js";import{reconcilePackages as ln}from"../core/graph/package-reconcile.js";import{migrateAppInstalls as dn}from"../core/scoped-state/migrate-app-installs.js";import{publish as pn,readBuiltinSnapshot as mn}from"../core/graph/package-publish.js";import{prewarmRecentRecipes as fn,reapStaleSpares as un}from"../core/runtime/warm-pool.js";import{DaemonFleet as hn}from"./fleet.js";import{copyNodeFilesToRows as wn}from"../core/runtime/first-boot-rows.js";import{BOOT_MIGRATIONS as vn}from"./boot-migrations.js";import{emitEvent as p}from"../core/events/emit.js";import{operationIdContext as k}from"../core/events/operation-id.js";import{bindDaemonEventSource as gn}from"../core/events/source.js";import{activateCanvasImport as yn,MigrationBlockedError as Sn,runForcedCanvasImport as _n}from"../migrations/activation.js";import{adoptInstallPerson as bn,convertLegacyScopedStore as kn,personStoresCopied as Rn}from"../core/scoped-state/migrate.js";import{readLegacyUserSnapshot as Pn}from"../core/scoped-state/legacy-profiles.js";import{heldPersons as We,installPreludeSnapshot as En}from"../core/scoped-state/person-store.js";import{loadPersonSettings as ge}from"../core/scoped-state/person-rows.js";import{userScopeRoot as Ke}from"../core/scope.js";import{brokerCommandDeclaresCanvasHome as ye}from"../core/runtime/broker-ownership.js";import{brokerCommandDeclaresCanvasHome as la}from"../core/runtime/broker-ownership.js";function Se(e){return/ --epoch (\S+) /.exec(e)?.[1]??null}s(Se,"brokerCommandEpoch");const In=5e3,Je=150;async function xn(e){const l=Be();if(l===null)throw p({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness"}}),new Error("prior-epoch broker census could not capture the process table");const f=Rr(),m=[];for(const[i,c]of l.processes){const w=c.command;if(c.zombie||!w.includes("broker-cli.js")||!ye(w,f)||Se(w)===e)continue;const b=w.trim().split(/\s+/).at(-1)??"";b===""||b.endsWith("broker-cli.js")||m.push({pid:i,nodeId:b})}let g=0;const o=[];for(const i of m){const c=Bt(i.pid);if(c===null||!c.includes("broker-cli.js")||!ye(c,f)||Se(c)===e||c.trim().split(/\s+/).at(-1)!==i.nodeId)continue;const w=He(i.pid,null);if(!w.reused){try{process.platform==="linux"&&P(C)?await N({operation:"stop",pid:i.pid}):process.kill(i.pid,"SIGTERM")}catch{continue}g++,o.push({pid:i.pid,snap:w})}}const h=Date.now()+In;for(;Date.now()<h&&o.some(i=>je(i.snap.tree.length>0?i.snap.tree:[i.pid]));)await new Promise(i=>setTimeout(i,Je));let y=0;for(const i of o){const c=i.snap.tree.length>0?i.snap.tree:[i.pid];je(c)&&(process.platform==="linux"&&P(C)?await N({operation:"stop",pid:i.pid}):ze(c,"SIGKILL",i.snap.identities),y++)}y>0&&await new Promise(i=>setTimeout(i,Je));const d=Be();if(d===null)throw p({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness",stage:"final"}}),new Error("prior-epoch broker census could not capture the final process table");const u=[];for(const[i,c]of d.processes){const w=c.command;c.zombie||!w.includes("broker-cli.js")||ye(w,f)&&Se(w)!==e&&u.push(i)}if(u.length>0)throw new Error(`prior-epoch broker census could not prove termination of pid(s): ${u.join(", ")}`);p({level:"info",event:"daemon.census.completed",fields:{prior_epoch_brokers:m.length,sigtermed:g,sigkilled:y}})}s(xn,"reapPriorEpochBrokers");const Dn=5e3;async function Tn(e){const l=Array.from(e.entries());if(l.length===0)return;for(const[o]of l){const h=(await $r(o))?.status;(h==="active"||h==="idle")&&await Me(o,new Date().toISOString())}const f=l.map(([,o])=>({pid:o.pid,snap:He(o.pid,null),exited:o.handle.exited}));for(const o of f)if(!o.snap.reused)try{process.platform==="linux"&&P(C)?await N({operation:"stop",pid:o.pid}):process.kill(o.pid,"SIGTERM")}catch{}const m=new Promise(o=>{setTimeout(o,Dn).unref()});await Promise.allSettled(f.map(o=>Promise.race([o.exited.then(()=>{}),m])));const g=[];for(const o of f)Ht(o.pid)&&(process.platform==="linux"&&P(C)?await N({operation:"stop",pid:o.pid}):ze(o.snap.tree.length>0?o.snap.tree:[o.pid],"SIGKILL",o.snap.identities),g.push(o));await Promise.all(g.map(o=>o.exited));for(const[o]of l)await yt(o,{reason:"daemon-teardown"});p({level:"info",event:"daemon.fleet_teardown.completed",fields:{brokers:f.length,sigkilled:g.length}})}s(Tn,"teardownFleet");function Q(...e){xe(gr(ue()),{recursive:!0}),hr(ue(),[process.pid,...e].join(`
2
- `),"utf8")}s(Q,"writePidfile");function Ve(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}s(Ve,"isMissingPathError");function Ye(e){const l=ue();let f;try{f=wr(l,"utf8")}catch(m){if(Ve(m))return;throw m}if(f.split(`
3
- `,1)[0].trim()!==String(e))throw new Error(`daemon readiness mirror does not name this invocation (expected pid ${e})`);try{vr(l)}catch(m){if(Ve(m))return;throw m}}s(Ye,"removeOwnedPidfileMirror");const Cn={acceptsDetachedWork:s(()=>!0,"acceptsDetachedWork"),registerDetached:s(e=>{e.catch(()=>{})},"registerDetached")},X=new pt;dt(e=>X.handleFatalFault(e,!1));const Ln=new ft,$n=new mt,Qe=new ut,An=new ht,Nn=new wt,Mn=new vt,On=new gt,Gn=new Rt,Fn=new Pt,Bn=new Et,Hn=new xt,jn=new It,zn=new Tt,Un=new Ct,qn=new Lt,Wn=new $t,Kn=new At,Jn=new Nt,Vn=new Mt,Yn=new Ot;async function Qn(e=Date.now(),l=Cn){const f=Ue(),m=await X.runFleetPreamble(f);let g,o,h;try{o=await he();const d=(await Ne()).filter(i=>!o.has(i.node_id));g=d.filter(i=>i.status==="active"||i.status==="idle"),h=d.filter(i=>i.status==="done"||i.status==="canceled"||i.status==="dead");const u=new Set(h.map(i=>i.node_id));h.push(...(await Nr()).filter(i=>!u.has(i.node_id)&&!o.has(i.node_id)))}catch(d){p({level:"error",event:"canvas.node_list.failed",error:d});return}await X.run(e,{rows:g,fleet:f,lifecycle:l,held:o}),await Ln.run(e,{rows:g,held:o}),await $n.run(e);const y=await Qe.run(e,{rows:[...g,...h],fleet:f});await An.run(e,o),await Vn.run(e,o),await Yn.run(e,{lifecycle:l}),await Nn.run(e,{lifecycle:l,held:o}),await Mn.run(e,{lifecycle:l}),await On.run(e,{lifecycle:l}),await Gn.run(e,{lifecycle:l}),await Fn.run(e,{lifecycle:l,fleet:f,held:o}),Bn.run(e,{lifecycle:l}),Hn.run(e,{lifecycle:l}),jn.run(e,{lifecycle:l}),zn.run(e,{lifecycle:l}),Un.run(e,{lifecycle:l}),qn.run(e,{lifecycle:l}),Wn.run(e,{lifecycle:l}),await kr(),Jn.run(e,{fleet:f,lifecycle:l}),await Kn.run(e,{rows:g}),X.warnIfSaturated({fleet:f,lifecycle:l,thresholds:m,frozen:y})}s(Qn,"superviseTick");async function Xn(e,l=Date.now()){if((await he()).has(e))return;const f=await _t(e);if(f===null||!St(f))return;const m=await Ar(e);m===null||m.kind==="human"||await Qe.runNode(l,m,Ue())}s(Xn,"exitedNodePass");function Z(e){return e===void 0||e==="reconcile"}s(Z,"roleRunsLanes");function O(e){return e===void 0||e==="api"}s(O,"roleServesRequests");const Zn=66e4;function eo(e){const l=new Or().registerAll(Gr(()=>null).filter(c=>c.pattern==="/healthz")),f=s((c,w)=>{const b=(c.url??"/").split("?")[0];if((c.method??"GET").toUpperCase()==="GET"&&b==="/healthz"){l.handle(c,w,null,{class:"person"});return}w.writeHead(404,{"content-type":"application/json; charset=utf-8"}),w.end(JSON.stringify({error:{code:"not_found",message:"this process serves only /healthz",origin:"runtime"}}))},"handler"),m=$e();P(m)&&De(m);const g=Y(f),o=new Promise((c,w)=>{g.once("error",w),g.listen(m,()=>{g.off("error",w),Te(m,384),c()})});let h,y=null,d=o;const u=e.tcp??Ce()??fe("user").api.tcp;if(u!==void 0&&u!==""){const c=/^(.*):(\d+)$/.exec(u.trim());if(c===null||Number(c[2])>65535)throw new Error(`invalid reconcile probe TCP address: ${u}`);const w=Y(f);w.on("error",b=>p({event:"api.server.failed",level:"error",error:b})),d=o.then(()=>new Promise(b=>{w.once("error",()=>b()),w.listen(Number(c[2]),c[1]===""?"0.0.0.0":c[1],()=>{const E=w.address();y=`${E.address}:${E.port}`,b()})})),h=w}let i=!1;return{ready:d,tcpAddress:s(()=>y,"tcpAddress"),async close(c={}){if(!i){i=!0,await Promise.all([Oe(g,new Set,c.graceMs),h===void 0?Promise.resolve():Oe(h,new Set,c.graceMs)]);try{P(m)&&De(m)}catch{}}}}}s(eo,"createProbeServer");const ro="daemon is draining for shutdown and admits no new work";async function to(e){xe(Ae(),{recursive:!0,mode:493}),process.platform==="linux"&&Te(Ae(),493);const l=$e();if(P(l))throw new Error(`layout refusal cannot bind occupied socket: ${l}`);const f=Y((d,u)=>{if(d.method==="GET"&&d.url==="/healthz"){u.writeHead(200,{"content-type":"application/json; charset=utf-8"}),u.end(JSON.stringify({ok:!1,daemon_up:!0,store_accessible:!1,brokers_reconciled:!1,startup_phase:"blocked",startup_blocked:"layout_migration_required"}));return}u.writeHead(503,{"content-type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:{code:"layout_migration_required",message:"run crtr sys migrate while the runtime is offline",type:"server_error",origin:"runtime",retryable:!1}}))});await new Promise((d,u)=>{f.once("error",u),f.listen(l,()=>{f.off("error",u),d()})});let m;const g=e.tcp??Ce();if(g){const d=/^(.*):(\d+)$/.exec(g);if(!d||Number(d[2])>65535)throw new Error(`invalid refusal TCP address: ${g}`);const u=Y(f.listeners("request")[0]);await new Promise((i,c)=>{u.once("error",c),u.listen(Number(d[2]),d[1],()=>{u.off("error",c),i()})}),m=u}Q();let o;const h=s(()=>(o??=(async()=>{f.closeAllConnections(),m?.closeAllConnections(),await Promise.all([f,m].filter(d=>d!==void 0).map(d=>new Promise((u,i)=>d.close(c=>c?i(c):u())))),Ye(process.pid),process.off("SIGINT",y),process.off("SIGTERM",y)})(),o),"cleanup"),y=s(()=>{h().then(()=>process.exit(0),d=>{process.stderr.write(`[crtrd] layout refusal cleanup failed: ${String(d)}
4
- `),process.exit(1)})},"onSignal");return process.on("SIGINT",y),process.on("SIGTERM",y),h}s(to,"serveLayoutRefusal");async function no(e={}){if(e.role==="machine")return(await import("./machine-daemon.js")).runMachineDaemon();if(Tr())return to(e);Dr();const l=s(t=>{process.stderr.write(`[crtrd] ${t}
5
- `)},"logPostgres"),f=!!process.env.CRTR_TEST_PG_URL,m=Qt(e.role);cn(Z(e.role));const g=s(async()=>m?await Yt(Le(16).toString("hex")):{claimed:!0,claim:{pid:process.pid,pid_identity:"",token:Le(16).toString("hex")}},"claimOwnership"),{database:o,ownership:h}=f?{database:{url:await Zt()},ownership:await g()}:await an(async()=>({database:await tn({log:l,startLockHeld:!0}),ownership:await g()}));if(!h.claimed){if(h.reason==="incumbent_alive")process.stderr.write(`[crtrd] already running (pid ${h.incumbentPid??"?"})
6
- `);else{const t=[h.incumbentPid!==void 0?`pid ${h.incumbentPid}`:void 0,h.verdict!==void 0?`verdict ${h.verdict}`:void 0].filter(v=>v!==void 0),a=t.length>0?` (${t.join(", ")})`:"";process.stderr.write(`[crtrd] claim lost: ${h.reason}${a}
7
- `),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 y=h.claim;let d=null,u=null,i=null,c=null,w,b="";try{m&&await xn(y.token);for(const r of Lr())process.stderr.write(`[crtrd] ${r}
8
- `);for(const r of await Cr())process.stderr.write(`[crtrd] ${r}
9
- `);await en(),await rn(o.url,l);const t=e.role===void 0&&!await Rn();let a=null;t&&(kn({kind:"user",root:Ke()}),a=Pn(Ke())),e.role===void 0&&En(a??{profiles:[],defaults:{},settings:{},state:{},apps:{}}),await M.listen(o.url);const v=s(r=>{ge(r).catch(n=>p({level:"error",event:"daemon.settings.reload_failed",error:n}))},"reloadPerson");if(w=await M.subscribe(r=>{We().includes(r)&&v(r)},{kinds:["settings"],onListenStart:s(()=>{for(const r of We())v(r)},"onListenStart")}),e.role!==void 0&&Ur(),e.role!==void 0){let r;try{r=mn()}catch(_){p({level:"error",event:"daemon.packages.snapshot_failed",error:_})}const n=await ve(async _=>(await Ge(_),r===void 0?void 0:await pn(_,r,"release")));c=await ve(async _=>await dn(_));for(const _ of n?.invalid??[])process.stderr.write(`[crtrd] package file is not a document: ${_.path}: ${_.error}
10
- `)}else{d=await qr(),d!==null&&(Kr(d.id),await ge(d.id));const r=await ve(async n=>(await Ge(n),d===null?null:await ln(n)));if(r!==null){for(const n of r.conflicts)process.stderr.write(`[crtrd] plugin documents not reconciled: ${n.message}
11
- `);for(const n of r.invalid)process.stderr.write(`[crtrd] package file is not a document: ${n.path}: ${n.error}
12
- `);for(const n of r.quarantined)process.stderr.write(`[crtrd] plugin "${n.name}" has a damaged ${n.file} (${n.reason}); ${n.movedTo!==void 0?`moved to ${n.movedTo}`:"left in place and skipped"}
13
- `);for(const n of r.kinds.refused)process.stderr.write(`[crtrd] plugin "${n.plugin}" kind ${n.kind} not registered: ${n.message}
14
- `);for(const n of r.kinds.invalid)process.stderr.write(`[crtrd] plugin "${n.plugin}" declares invalid object kinds or scopes; no kinds registered and no app token: ${n.error}
15
- `)}}if(b=await Jt(),Vt(b),e.role===void 0&&d!==null){if(await bn(d.id),process.platform==="darwin"){const{readConfig:r,updateConfig:n}=await import("../core/config.js");if(r("user").paths?.user_files===void 0){const{homedir:_}=await import("node:os");await n("user",Ie=>{Ie.paths??={},Ie.paths.user_files??=_()})}}u=await Wr(),u.joinedFrom!==null&&await ge(u.person),await dr(),i=await Jr()}if(process.platform==="linux"&&P(C)&&(xr(),await N({operation:"users.sync",users:await Pr()})),m){await kt(y.token);const r=await wn();Object.values(r).some(n=>n>0)&&process.stderr.write(`[crtrd] node files copied into rows: ${JSON.stringify(r)}
16
- `)}}catch(t){await M.close();try{if(m){const{released:a}=await qe(y);if(!a)throw new Error("daemon ownership claim was not released")}await we()}catch(a){throw new AggregateError([t,a],"daemon startup failed and cleanup also failed")}throw t}let E=!0,ee,j=Promise.resolve(),re=!1,z,te,ne,oe,ie,L;const U=new Set;let ae=!1,_e=!1,x,I,se,q=!1,W,$,G,F,B,ce,le,de,pe;const Xe=lt();let D,S={phase:"initializing",message:"daemon startup is running the canvas import and normal services are unavailable",blockerPaths:[]},A="initial startup activation",Ze=null;function er(){return S.phase==="ready"?null:{phase:S.phase,message:S.message,blockerPaths:S.blockerPaths}}s(er,"startupBlock");function R(t){U.add(t),t.finally(()=>{U.delete(t)}).catch(()=>{})}s(R,"registerDetached");const rr={acceptsDetachedWork:s(()=>E,"acceptsDetachedWork"),registerDetached:R};async function tr(){try{E=!1,sn.close(),ne?.(),ne=void 0,oe?.(),w?.(),oe=void 0,ie?.(),ie=void 0,de?.(),de=void 0,await M.close(),z!==void 0&&(clearInterval(z),z=void 0),te?.(),te=void 0,G!==void 0&&(clearInterval(G),G=void 0),F!==void 0&&(clearInterval(F),F=void 0),pe?.(),pe=void 0;let t;do t=j,await t;while(t!==j);for(;U.size>0;)await Promise.allSettled([...U]);if(L!==void 0&&(m&&await Tn(L),await L.exitsSettled(),L.dispose()),se!==void 0&&await se.close(),I!==void 0&&!q&&(q=!0,await I.close()),ce?.(),ce=void 0,le?.(),le=void 0,B!==void 0){const a=B;B=void 0,await a.stop()}if($!==void 0){const a=$;$=void 0,await a.close()}if(W!==void 0){const a=W;W=void 0,await a.close()}if(ae||(Ye(process.pid),ae=!0),ae&&!_e){if(m){const{released:a}=await qe(y);if(!a)throw new Error("daemon ownership claim was not released")}_e=!0,await we()}}finally{Ut(),process.off("SIGINT",Re),process.off("SIGTERM",Pe),process.off("exit",Ee)}}s(tr,"cleanupAttempt");const K=1e3;let be=!1;function nr(){if(e.role!==void 0)throw new Error(`a ${e.role} daemon never hands over to a successor: its orchestrator replaces it`);return be?{graceMs:K}:(be=!0,k.fresh(()=>{p({level:"info",event:"daemon.handover.armed",fields:{pid:process.pid,grace_ms:K}})}),setTimeout(()=>{or()},K),{graceMs:K})}s(nr,"requestHandover");async function or(){try{await T()}catch(t){const a=t instanceof Error?t.stack??t.message:String(t);process.stderr.write(`[crtrd] handover cleanup failed:
1
+ var lr=Object.defineProperty;var s=(e,c)=>lr(e,"name",{value:c,configurable:!0});import{applyBootSettings as cr}from"./boot-settings.js";import{startBrokerMemoryCap as dr}from"./broker-memory-cap.js";import{startPeerOutbox as pr}from"./peer/outbox.js";import{reportMachineStatus as mr}from"../core/peer/directory.js";import{createPeerRelay as fr}from"./peer/relay-service.js";import{writeFileSync as ur,readFileSync as hr,rmSync as wr,mkdirSync as Pe,existsSync as E,unlinkSync as Ie,chmodSync as xe}from"node:fs";import{createServer as Y}from"node:http";import{dirname as vr}from"node:path";import{envCrtrdTcp as Te}from"../shared/env.js";import{openCanvasConversationStore as gr,serveCanvasConversationStore as yr}from"../core/canvas/sessions.js";import{installConversationStore as Sr}from"../core/conversation-store/index.js";import{pollRunObservers as _r}from"./runs/observer.js";import{randomBytes as Ce}from"node:crypto";import{apiSocketPath as De,crtrHome as br}from"../core/canvas/paths.js";import{activeAppUsers as kr}from"../core/spaces/users.js";import{ensureAppSpace as Rr,ensureUserFiles as Er}from"../core/spaces/space.js";import{LAUNCHER_SOCKET as D}from"../launcher/spec.js";import{launcherRequest as N}from"../launcher/client.js";import{installLauncherEventSink as Pr}from"./launcher-events.js";import{initializeEmptyLayout as Ir,layoutNeedsMigration as xr,socketDir as Ae}from"../core/layout.js";import{migrateLooseKeys as Tr}from"../core/layout-migrate/loose-keys.js";import{relocateProfileFolders as Cr}from"../core/profiles/relocate.js";import{getNode as Dr,getRow as Ar,listNodesForSupervision as Le,listParkedResidentsWithWakeMail as Lr,setFrozen as $e}from"../core/canvas/index.js";import{createApiServer as $r,closeServer as Ne}from"./api/server.js";import{Router as Nr}from"./api/router.js";import{healthRoutes as Mr}from"./api/handlers/health.js";import{createAppListener as Gr}from"./api/app-listener.js";import{registerBlaxelRunnerFromEnv as Or}from"../core/secrets/blaxel-register.js";import{markEnginesInProcess as Fr}from"../core/canvas/person-state.js";import{markCloudRole as Br,resolvePerson as Hr,retireLocalPerson as Ur,setPersonId as jr}from"../core/canvas/person.js";import{backfillNodeApps as Me,runPermissionsBoot as zr}from"../core/permissions/boot.js";import{startRunNotices as qr}from"./run-notices.js";import{startGrantEffects as Wr}from"./reconcilers/grant-effects.js";import{syncPackages as Kr}from"../core/packages/directory-sync.js";import{startActivationDelivery as Jr}from"../core/model-auth/activations.js";import{createGrantSync as Vr,GRANT_SYNC_INTERVAL_S as Ge}from"../core/grants/sync.js";import{sweepSandboxes as Yr}from"../core/grants/on-sync.js";import{rebuildCronExecutions as Qr}from"./cron/run-socket.js";import{hasSyncedGrants as Xr}from"../core/grants/mirror.js";import{readConfig as Oe}from"../core/config.js";import{reconcileUndeliveredTickets as Zr}from"./human/sweep.js";import{resetHandedOffDeliveries as et}from"../core/canvas/deliveries.js";import{resetHandedOffDaemonActions as rt}from"../core/canvas/daemon-actions.js";import{sweepReviews as tt}from"./review/sweep.js";import{pidfilePath as me}from"./pidfile.js";import{rendererWarning as nt}from"../core/runtime/package-health.js";import{DEFAULT_INTERVAL_MS as ot}from"./supervise-cadence.js";import{createResumeDetector as it}from"./resume-detector.js";import{setFatalFaultAnnouncer as at}from"../core/canvas/recovery.js";import{BrokerSupervisionReconciler as st}from"./reconcilers/broker-supervision.js";import{MachineOfflineReconciler as lt}from"./reconcilers/machine-offline.js";import{ControllerDeathReconciler as ct}from"./reconcilers/controller-death.js";import{NodeLifecycleReconciler as dt}from"./reconcilers/node-lifecycle/tick.js";import{NodeDeadlineReconciler as pt}from"./reconcilers/node-deadline.js";import{CronLaneReconciler as mt}from"./reconcilers/cron-lane.js";import{DeliveryLaneReconciler as ft}from"./reconcilers/delivery-lane.js";import{ActionLaneReconciler as ut}from"./reconcilers/action-lane.js";import{endLiveExecution as ht,hasObservedExit as wt,latestExecutionForNode as vt,migrateLegacyExecutionIdentities as gt}from"../core/canvas/executions.js";import{revokePriorEpochNodeTokens as yt}from"../core/canvas/node-tokens.js";import{PendingReviewSubmitReconciler as St}from"./reconcilers/pending-review-submit.js";import{StorageMaintenanceReconciler as _t}from"./reconcilers/storage-maintenance.js";import{StorageDueWorkReconciler as bt}from"./reconcilers/storage-due-work.js";import{GroupInviteExpiryReconciler as kt}from"./reconcilers/group-invite-expiry.js";import{PurgeDueWorkReconciler as Rt}from"./reconcilers/purge-due-work.js";import{assertLedgerEnv as Et}from"../core/ledger/rates.js";import{LedgerSandboxReconciler as Pt}from"./reconcilers/ledger-sandbox.js";import{LedgerStorageReconciler as It}from"./reconcilers/ledger-storage.js";import{LedgerR2Reconciler as xt}from"./reconcilers/ledger-r2.js";import{importedNodesHeld as fe}from"./reconcilers/live-obligation.js";import{ImportLaneReconciler as Tt}from"./reconcilers/import-lane.js";import{BashDeadlineReconciler as Ct}from"./reconcilers/bash-deadline.js";import{FaultRetryBackstopReconciler as Dt}from"./reconcilers/fault-retry-backstop.js";import{StructuredRequestReconciler as At}from"./reconcilers/structured-request-lane.js";import{RecipeImageReconciler as Lt,subscribeImageBuilt as $t}from"./reconcilers/recipe-image.js";import{reconcileStructuredRequestSidecars as Nt}from"./structured-requests/boot.js";import{captureLivenessSnapshot as Fe,capturePidCommand as Mt,captureTeardownSnapshot as Be,isPidAlive as Gt,isAnyPidAlive as He,killProcessTreePids as Ue}from"../core/canvas/pid.js";import{bindFleet as Ot,boundFleet as je}from"../core/runtime/fleet.js";import{bindDaemonControl as Ft,clearDaemonControl as Bt}from"./control.js";import{execDaemon as Ht,spawnDaemon as Ut}from"./manage.js";import{reconcileAndMigrateBoot as jt}from"../core/canvas/boot.js";import{resolveInstallId as zt}from"../core/canvas/install-id.js";import{setInstallId as qt}from"../core/runtime/nodes.js";import{claimDaemonOwnership as Wt,daemonOwnershipApplies as Kt,daemonOwnershipClaimed as Jt,releaseDaemonOwnership as ze}from"../core/canvas/daemon-owner.js";import{canvasDatabaseUrl as Vt,closeAllDbs as ue,openDb as Yt,withCanvasWrite as he}from"../core/canvas/db.js";import{importSqliteCanvasIfPresent as Qt}from"../core/canvas/import-sqlite.js";import{ensurePostgres as Xt,ensurePostgresHealthy as Zt,stopPostgres as en,withPostgresStartLock as rn}from"./postgres/index.js";import{brokerSignalBus as M}from"./broker-signals/bus.js";import{brokerSignalStreams as tn}from"./api/handlers/broker-signals.js";import{setRequestsStartRunObservers as nn}from"./api/handlers/broker-ops.js";import{reconcilePackages as on}from"../core/graph/package-reconcile.js";import{migrateAppInstalls as an}from"../core/scoped-state/migrate-app-installs.js";import{publish as sn,readBuiltinSnapshot as ln}from"../core/graph/package-publish.js";import{prewarmRecentRecipes as cn,reapStaleSpares as dn}from"../core/runtime/warm-pool.js";import{DaemonFleet as pn}from"./fleet.js";import{copyNodeFilesToRows as mn}from"../core/runtime/first-boot-rows.js";import{BOOT_MIGRATIONS as fn}from"./boot-migrations.js";import{emitEvent as m}from"../core/events/emit.js";import{operationIdContext as b}from"../core/events/operation-id.js";import{bindDaemonEventSource as un}from"../core/events/source.js";import{activateCanvasImport as hn,MigrationBlockedError as wn,runForcedCanvasImport as vn}from"../migrations/activation.js";import{adoptInstallPerson as gn,convertLegacyScopedStore as yn,personStoresCopied as Sn}from"../core/scoped-state/migrate.js";import{readLegacyUserSnapshot as _n}from"../core/scoped-state/legacy-profiles.js";import{heldPersons as qe,installPreludeSnapshot as bn}from"../core/scoped-state/person-store.js";import{loadPersonSettings as we}from"../core/scoped-state/person-rows.js";import{userScopeRoot as We}from"../core/scope.js";import{brokerCommandDeclaresCanvasHome as ve}from"../core/runtime/broker-ownership.js";import{brokerCommandDeclaresCanvasHome as na}from"../core/runtime/broker-ownership.js";function ge(e){return/ --epoch (\S+) /.exec(e)?.[1]??null}s(ge,"brokerCommandEpoch");const kn=5e3,Ke=150;async function Rn(e){const c=Fe();if(c===null)throw m({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness"}}),new Error("prior-epoch broker census could not capture the process table");const f=br(),p=[];for(const[i,l]of c.processes){const v=l.command;if(l.zombie||!v.includes("broker-cli.js")||!ve(v,f)||ge(v)===e)continue;const _=v.trim().split(/\s+/).at(-1)??"";_===""||_.endsWith("broker-cli.js")||p.push({pid:i,nodeId:_})}let g=0;const o=[];for(const i of p){const l=Mt(i.pid);if(l===null||!l.includes("broker-cli.js")||!ve(l,f)||ge(l)===e||l.trim().split(/\s+/).at(-1)!==i.nodeId)continue;const v=Be(i.pid,null);if(!v.reused){try{process.platform==="linux"&&E(D)?await N({operation:"stop",pid:i.pid}):process.kill(i.pid,"SIGTERM")}catch{continue}g++,o.push({pid:i.pid,snap:v})}}const w=Date.now()+kn;for(;Date.now()<w&&o.some(i=>He(i.snap.tree.length>0?i.snap.tree:[i.pid]));)await new Promise(i=>setTimeout(i,Ke));let y=0;for(const i of o){const l=i.snap.tree.length>0?i.snap.tree:[i.pid];He(l)&&(process.platform==="linux"&&E(D)?await N({operation:"stop",pid:i.pid}):Ue(l,"SIGKILL",i.snap.identities),y++)}y>0&&await new Promise(i=>setTimeout(i,Ke));const d=Fe();if(d===null)throw m({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness",stage:"final"}}),new Error("prior-epoch broker census could not capture the final process table");const u=[];for(const[i,l]of d.processes){const v=l.command;l.zombie||!v.includes("broker-cli.js")||ve(v,f)&&ge(v)!==e&&u.push(i)}if(u.length>0)throw new Error(`prior-epoch broker census could not prove termination of pid(s): ${u.join(", ")}`);m({level:"info",event:"daemon.census.completed",fields:{prior_epoch_brokers:p.length,sigtermed:g,sigkilled:y}})}s(Rn,"reapPriorEpochBrokers");const En=5e3;async function Pn(e){const c=Array.from(e.entries());if(c.length===0)return;for(const[o]of c){const w=(await Dr(o))?.status;(w==="active"||w==="idle")&&await $e(o,new Date().toISOString())}const f=c.map(([,o])=>({pid:o.pid,snap:Be(o.pid,null),exited:o.handle.exited}));for(const o of f)if(!o.snap.reused)try{process.platform==="linux"&&E(D)?await N({operation:"stop",pid:o.pid}):process.kill(o.pid,"SIGTERM")}catch{}const p=new Promise(o=>{setTimeout(o,En).unref()});await Promise.allSettled(f.map(o=>Promise.race([o.exited.then(()=>{}),p])));const g=[];for(const o of f)Gt(o.pid)&&(process.platform==="linux"&&E(D)?await N({operation:"stop",pid:o.pid}):Ue(o.snap.tree.length>0?o.snap.tree:[o.pid],"SIGKILL",o.snap.identities),g.push(o));await Promise.all(g.map(o=>o.exited));for(const[o]of c)await ht(o,{reason:"daemon-teardown"});m({level:"info",event:"daemon.fleet_teardown.completed",fields:{brokers:f.length,sigkilled:g.length}})}s(Pn,"teardownFleet");function Q(...e){Pe(vr(me()),{recursive:!0}),ur(me(),[process.pid,...e].join(`
2
+ `),"utf8")}s(Q,"writePidfile");function Je(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}s(Je,"isMissingPathError");function Ve(e){const c=me();let f;try{f=hr(c,"utf8")}catch(p){if(Je(p))return;throw p}if(f.split(`
3
+ `,1)[0].trim()!==String(e))throw new Error(`daemon readiness mirror does not name this invocation (expected pid ${e})`);try{wr(c)}catch(p){if(Je(p))return;throw p}}s(Ve,"removeOwnedPidfileMirror");const In={acceptsDetachedWork:s(()=>!0,"acceptsDetachedWork"),registerDetached:s(e=>{e.catch(()=>{})},"registerDetached")},X=new st;at(e=>X.handleFatalFault(e,!1));const xn=new ct,Tn=new lt,Ye=new dt,Cn=new pt,Dn=new mt,An=new ft,Ln=new ut,$n=new St,Nn=new _t,Mn=new bt,Gn=new Rt,On=new kt,Fn=new Pt,Bn=new It,Hn=new xt,Un=new Tt,jn=new Ct,zn=new Dt,qn=new At,Wn=new Lt;async function Kn(e=Date.now(),c=In){const f=je(),p=await X.runFleetPreamble(f);let g,o,w;try{o=await fe();const d=(await Le()).filter(i=>!o.has(i.node_id));g=d.filter(i=>i.status==="active"||i.status==="idle"),w=d.filter(i=>i.status==="done"||i.status==="canceled"||i.status==="dead");const u=new Set(w.map(i=>i.node_id));w.push(...(await Lr()).filter(i=>!u.has(i.node_id)&&!o.has(i.node_id)))}catch(d){m({level:"error",event:"canvas.node_list.failed",error:d});return}await X.run(e,{rows:g,fleet:f,lifecycle:c,held:o}),await xn.run(e,{rows:g,held:o}),await Tn.run(e);const y=await Ye.run(e,{rows:[...g,...w],fleet:f});await Cn.run(e,o),await qn.run(e,o),await Wn.run(e,{lifecycle:c}),await Dn.run(e,{lifecycle:c,held:o}),await An.run(e,{lifecycle:c}),await Ln.run(e,{lifecycle:c}),await $n.run(e,{lifecycle:c}),await Nn.run(e,{lifecycle:c,fleet:f,held:o}),Mn.run(e,{lifecycle:c}),Gn.run(e,{lifecycle:c}),On.run(e,{lifecycle:c}),Fn.run(e,{lifecycle:c}),Bn.run(e,{lifecycle:c}),Hn.run(e,{lifecycle:c}),Un.run(e,{lifecycle:c}),await _r(),zn.run(e,{fleet:f,lifecycle:c}),await jn.run(e,{rows:g}),X.warnIfSaturated({fleet:f,lifecycle:c,thresholds:p,frozen:y})}s(Kn,"superviseTick");async function Jn(e,c=Date.now()){if((await fe()).has(e))return;const f=await vt(e);if(f===null||!wt(f))return;const p=await Ar(e);p===null||p.kind==="human"||await Ye.runNode(c,p,je())}s(Jn,"exitedNodePass");function Z(e){return e===void 0||e==="reconcile"||e==="all"}s(Z,"roleRunsLanes");function H(e){return e===void 0||e==="api"||e==="all"}s(H,"roleServesRequests");const Vn=66e4;function Yn(e){const c=new Nr().registerAll(Mr(()=>null).filter(l=>l.pattern==="/healthz")),f=s((l,v)=>{const _=(l.url??"/").split("?")[0];if((l.method??"GET").toUpperCase()==="GET"&&_==="/healthz"){c.handle(l,v,null,{class:"person"});return}v.writeHead(404,{"content-type":"application/json; charset=utf-8"}),v.end(JSON.stringify({error:{code:"not_found",message:"this process serves only /healthz",origin:"runtime"}}))},"handler"),p=De();E(p)&&Ie(p);const g=Y(f),o=new Promise((l,v)=>{g.once("error",v),g.listen(p,()=>{g.off("error",v),xe(p,384),l()})});let w,y=null,d=o;const u=e.tcp??Te()??Oe("user").api.tcp;if(u!==void 0&&u!==""){const l=/^(.*):(\d+)$/.exec(u.trim());if(l===null||Number(l[2])>65535)throw new Error(`invalid reconcile probe TCP address: ${u}`);const v=Y(f);v.on("error",_=>m({event:"api.server.failed",level:"error",error:_})),d=o.then(()=>new Promise(_=>{v.once("error",()=>_()),v.listen(Number(l[2]),l[1]===""?"0.0.0.0":l[1],()=>{const P=v.address();y=`${P.address}:${P.port}`,_()})})),w=v}let i=!1;return{ready:d,tcpAddress:s(()=>y,"tcpAddress"),async close(l={}){if(!i){i=!0,await Promise.all([Ne(g,new Set,l.graceMs),w===void 0?Promise.resolve():Ne(w,new Set,l.graceMs)]);try{E(p)&&Ie(p)}catch{}}}}}s(Yn,"createProbeServer");const Qn="daemon is draining for shutdown and admits no new work";async function Xn(e){Pe(Ae(),{recursive:!0,mode:493}),process.platform==="linux"&&xe(Ae(),493);const c=De();if(E(c))throw new Error(`layout refusal cannot bind occupied socket: ${c}`);const f=Y((d,u)=>{if(d.method==="GET"&&d.url==="/healthz"){u.writeHead(200,{"content-type":"application/json; charset=utf-8"}),u.end(JSON.stringify({ok:!1,daemon_up:!0,store_accessible:!1,brokers_reconciled:!1,startup_phase:"blocked",startup_blocked:"layout_migration_required"}));return}u.writeHead(503,{"content-type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:{code:"layout_migration_required",message:"run crtr sys migrate while the runtime is offline",type:"server_error",origin:"runtime",retryable:!1}}))});await new Promise((d,u)=>{f.once("error",u),f.listen(c,()=>{f.off("error",u),d()})});let p;const g=e.tcp??Te();if(g){const d=/^(.*):(\d+)$/.exec(g);if(!d||Number(d[2])>65535)throw new Error(`invalid refusal TCP address: ${g}`);const u=Y(f.listeners("request")[0]);await new Promise((i,l)=>{u.once("error",l),u.listen(Number(d[2]),d[1],()=>{u.off("error",l),i()})}),p=u}Q();let o;const w=s(()=>(o??=(async()=>{f.closeAllConnections(),p?.closeAllConnections(),await Promise.all([f,p].filter(d=>d!==void 0).map(d=>new Promise((u,i)=>d.close(l=>l?i(l):u())))),Ve(process.pid),process.off("SIGINT",y),process.off("SIGTERM",y)})(),o),"cleanup"),y=s(()=>{w().then(()=>process.exit(0),d=>{process.stderr.write(`[crtrd] layout refusal cleanup failed: ${String(d)}
4
+ `),process.exit(1)})},"onSignal");return process.on("SIGINT",y),process.on("SIGTERM",y),w}s(Xn,"serveLayoutRefusal");async function Zn(e={}){if(e.role==="machine")return(await import("./machine-daemon.js")).runMachineDaemon();if(xr())return Xn(e);Ir();const c=s(r=>{process.stderr.write(`[crtrd] ${r}
5
+ `)},"logPostgres"),f=!!process.env.CRTR_TEST_PG_URL,p=Kt(e.role);nn(Z(e.role));const g=s(async()=>p?await Wt(Ce(16).toString("hex")):{claimed:!0,claim:{pid:process.pid,pid_identity:"",token:Ce(16).toString("hex")}},"claimOwnership"),{database:o,ownership:w}=e.role!==void 0||f?{database:{url:await Vt()},ownership:await g()}:await rn(async()=>({database:await Xt({log:c,startLockHeld:!0}),ownership:await g()}));if(!w.claimed){if(w.reason==="incumbent_alive")process.stderr.write(`[crtrd] already running (pid ${w.incumbentPid??"?"})
6
+ `);else{const r=[w.incumbentPid!==void 0?`pid ${w.incumbentPid}`:void 0,w.verdict!==void 0?`verdict ${w.verdict}`:void 0].filter(a=>a!==void 0),t=r.length>0?` (${r.join(", ")})`:"";process.stderr.write(`[crtrd] claim lost: ${w.reason}${t}
7
+ `),w.reason==="own_identity_indeterminate"&&process.stderr.write("[crtrd] cannot read its own process identity. crouter needs /proc on Linux, or the `ps` command elsewhere (Debian/Ubuntu: apt-get install procps).\n"),(w.reason==="own_identity_indeterminate"||w.reason==="incumbent_malformed")&&(process.exitCode=1)}return async()=>{}}const y=w.claim;let d=null,u=null,i=null,l=null,v,_="";try{p&&await Rn(y.token);for(const n of Cr())process.stderr.write(`[crtrd] ${n}
8
+ `);for(const n of await Tr())process.stderr.write(`[crtrd] ${n}
9
+ `);await Yt(),await Qt(o.url,c);const r=e.role===void 0&&!await Sn();let t=null;r&&(yn({kind:"user",root:We()}),t=_n(We())),e.role===void 0&&bn(t??{profiles:[],defaults:{},settings:{},state:{},apps:{}}),await M.listen(o.url);const a=s(n=>{we(n).catch(h=>m({level:"error",event:"daemon.settings.reload_failed",error:h}))},"reloadPerson");if(v=await M.subscribe(n=>{qe().includes(n)&&a(n)},{kinds:["settings"],onListenStart:s(()=>{for(const n of qe())a(n)},"onListenStart")}),e.role!==void 0&&Br(),e.role==="all"&&Fr(),e.role!==void 0){let n;try{n=ln()}catch(R){m({level:"error",event:"daemon.packages.snapshot_failed",error:R})}const h=await he(async R=>(await Me(R),n===void 0?void 0:await sn(R,n,"release")));l=await he(async R=>await an(R));for(const R of h?.invalid??[])process.stderr.write(`[crtrd] package file is not a document: ${R.path}: ${R.error}
10
+ `)}else{d=await Hr(),d!==null&&(jr(d.id),await we(d.id));const n=await he(async h=>(await Me(h),d===null?null:await on(h)));if(n!==null){for(const h of n.conflicts)process.stderr.write(`[crtrd] plugin documents not reconciled: ${h.message}
11
+ `);for(const h of n.invalid)process.stderr.write(`[crtrd] package file is not a document: ${h.path}: ${h.error}
12
+ `);for(const h of n.quarantined)process.stderr.write(`[crtrd] plugin "${h.name}" has a damaged ${h.file} (${h.reason}); ${h.movedTo!==void 0?`moved to ${h.movedTo}`:"left in place and skipped"}
13
+ `);for(const h of n.kinds.refused)process.stderr.write(`[crtrd] plugin "${h.plugin}" kind ${h.kind} not registered: ${h.message}
14
+ `);for(const h of n.kinds.invalid)process.stderr.write(`[crtrd] plugin "${h.plugin}" declares invalid object kinds or scopes; no kinds registered and no app token: ${h.error}
15
+ `)}}if(_=await zt(),qt(_),e.role===void 0&&d!==null){if(await gn(d.id),process.platform==="darwin"){const{readConfig:n,updateConfig:h}=await import("../core/config.js");if(n("user").paths?.user_files===void 0){const{homedir:R}=await import("node:os");await h("user",Ee=>{Ee.paths??={},Ee.paths.user_files??=R()})}}u=await Ur(),u.joinedFrom!==null&&await we(u.person),await cr(),i=await zr()}if(process.platform==="linux"&&E(D)&&(Pr(),await N({operation:"users.sync",users:await kr()})),p){await yt(y.token);const n=await mn();Object.values(n).some(h=>h>0)&&process.stderr.write(`[crtrd] node files copied into rows: ${JSON.stringify(n)}
16
+ `)}}catch(r){await M.close();try{if(p){const{released:t}=await ze(y);if(!t)throw new Error("daemon ownership claim was not released")}await ue()}catch(t){throw new AggregateError([r,t],"daemon startup failed and cleanup also failed")}throw r}let P=!0,ee,U=Promise.resolve(),re=!1,j,te,ne,oe,ie,A;const z=new Set;let ae=!1,ye=!1,x,I,q=!1,W,L,G,O,F,se,le,ce,de;const Qe=it();let T,S={phase:"initializing",message:"daemon startup is running the canvas import and normal services are unavailable",blockerPaths:[]},$="initial startup activation",Xe=null;function Ze(){return S.phase==="ready"?null:{phase:S.phase,message:S.message,blockerPaths:S.blockerPaths}}s(Ze,"startupBlock");function k(r){z.add(r),r.finally(()=>{z.delete(r)}).catch(()=>{})}s(k,"registerDetached");const er={acceptsDetachedWork:s(()=>P,"acceptsDetachedWork"),registerDetached:k};async function rr(){try{P=!1,tn.close(),ne?.(),ne=void 0,oe?.(),v?.(),oe=void 0,ie?.(),ie=void 0,ce?.(),ce=void 0,await M.close(),j!==void 0&&(clearInterval(j),j=void 0),te?.(),te=void 0,G!==void 0&&(clearInterval(G),G=void 0),O!==void 0&&(clearInterval(O),O=void 0),de?.(),de=void 0;let r;do r=U,await r;while(r!==U);for(;z.size>0;)await Promise.allSettled([...z]);if(A!==void 0&&(p&&await Pn(A),await A.exitsSettled(),A.dispose()),I!==void 0&&!q&&(q=!0,await I.close()),se?.(),se=void 0,le?.(),le=void 0,F!==void 0){const t=F;F=void 0,await t.stop()}if(L!==void 0){const t=L;L=void 0,await t.close()}if(W!==void 0){const t=W;W=void 0,await t.close()}if(ae||(Ve(process.pid),ae=!0),ae&&!ye){if(p){const{released:t}=await ze(y);if(!t)throw new Error("daemon ownership claim was not released")}ye=!0,await ue()}}finally{Bt(),process.off("SIGINT",be),process.off("SIGTERM",ke),process.off("exit",Re)}}s(rr,"cleanupAttempt");const K=1e3;let Se=!1;function tr(){if(e.role!==void 0)throw new Error(`a ${e.role} daemon never hands over to a successor: its orchestrator replaces it`);return Se?{graceMs:K}:(Se=!0,b.fresh(()=>{m({level:"info",event:"daemon.handover.armed",fields:{pid:process.pid,grace_ms:K}})}),setTimeout(()=>{nr()},K),{graceMs:K})}s(tr,"requestHandover");async function nr(){try{await C()}catch(r){const t=r instanceof Error?r.stack??r.message:String(r);process.stderr.write(`[crtrd] handover cleanup failed:
17
+ ${t}
18
+ `),process.exit(1)}try{process.platform==="linux"&&E(D)&&(await N({operation:"daemon.handover"}),process.exit(0)),process.pid===1&&await Ht();const r=await Ut();b.fresh(()=>{m({level:"info",event:"daemon.handover.completed",fields:{predecessor_pid:process.pid,successor_pid:r.pid??r.existing_pid??null,spawned:r.started}})})}catch(r){b.fresh(()=>{m({level:"error",event:"daemon.handover.successor_failed",error:r})});const t=r instanceof Error?r.message:String(r);process.stderr.write(`[crtrd] handover successor failed to start: ${t}
19
+ `),process.exit(1)}process.exit(0)}s(nr,"performHandover");function C(){if(x!==void 0)return x;const r=rr();return x=r,r.then(()=>{x===r&&(x=void 0)},()=>{x===r&&(x=void 0)}),r}s(C,"requestCleanup");async function or(){S={phase:"initializing",message:Qn,blockerPaths:[]},I!==void 0&&!q&&(q=!0,await I.close({graceMs:Vn}))}s(or,"drainApi");async function _e(r){try{r==="SIGTERM"&&e.role==="api"&&await or(),await C(),await en({claimed:s(async()=>{try{return p&&await Jt()}finally{await ue()}},"claimed")}),process.exit(0)}catch(t){process.exitCode=1;const a=t instanceof Error?t.stack??`${t.name}: ${t.message}`:String(t);process.stderr.write(`[crtrd] ${r} cleanup failed:
17
20
  ${a}
18
- `),process.exit(1)}try{process.platform==="linux"&&P(C)&&(await N({operation:"daemon.handover"}),process.exit(0)),process.pid===1&&await qt();const t=await Wt();k.fresh(()=>{p({level:"info",event:"daemon.handover.completed",fields:{predecessor_pid:process.pid,successor_pid:t.pid??t.existing_pid??null,spawned:t.started}})})}catch(t){k.fresh(()=>{p({level:"error",event:"daemon.handover.successor_failed",error:t})});const a=t instanceof Error?t.message:String(t);process.stderr.write(`[crtrd] handover successor failed to start: ${a}
19
- `),process.exit(1)}process.exit(0)}s(or,"performHandover");function T(){if(x!==void 0)return x;const t=tr();return x=t,t.then(()=>{x===t&&(x=void 0)},()=>{x===t&&(x=void 0)}),t}s(T,"requestCleanup");async function ir(){S={phase:"initializing",message:ro,blockerPaths:[]},I!==void 0&&!q&&(q=!0,await I.close({graceMs:Zn}))}s(ir,"drainApi");async function ke(t){try{t==="SIGTERM"&&e.role==="api"&&await ir(),await T(),await on({claimed:s(async()=>{try{return m&&await Xt()}finally{await we()}},"claimed")}),process.exit(0)}catch(a){process.exitCode=1;const v=a instanceof Error?a.stack??`${a.name}: ${a.message}`:String(a);process.stderr.write(`[crtrd] ${t} cleanup failed:
20
- ${v}
21
- `),process.exit(1)}}s(ke,"handleSignal");function Re(){ke("SIGINT")}s(Re,"onSigint");function Pe(){ke("SIGTERM")}s(Pe,"onSigterm");function Ee(){T().catch(()=>{})}s(Ee,"onExit");async function J(t){E&&(j=j.then(t).then(()=>{},a=>{k.fresh(()=>{p({level:"error",event:"daemon.lane_job.failed",error:a})})}))}s(J,"enqueue");async function V(){!E||re||(Xe.check()&&D&&(p({level:"info",event:"daemon.resume.detected"}),R(D().catch(()=>{}))),re=!0,await J(async()=>{if(re=!1,!!E)try{f||await nn({log:l}),await Qn(Date.now(),rr)}catch(t){k.fresh(()=>{p({level:"error",event:"daemon.tick.failed",error:t})})}}))}s(V,"enqueueTick");let H=null;async function ar(){if(H!==null)throw{status:500,code:"admission_failed",message:`daemon admission previously failed: ${H instanceof Error?H.message:String(H)}`};if(S.phase==="ready")return{admitted:!1,already_admitted:!0,startup_phase:"ready"};if(S.phase!=="prepared"&&S.phase!=="recovering")throw{status:409,code:"not_prepared",message:S.message};const t=S.phase==="prepared";try{return await me(),S={phase:"ready",message:"",blockerPaths:[]},t?{admitted:!0,already_admitted:!1,startup_phase:"ready"}:{admitted:!1,already_admitted:!0,startup_phase:"ready"}}catch(a){throw H=a,{status:500,code:"admission_failed",message:`daemon admission failed: ${a instanceof Error?a.message:String(a)}`}}}s(ar,"admitStartup");async function sr(t){if(A!==null)throw{status:409,code:"migration_in_progress",message:`the canvas import is already running (${A})`};A="repair";try{const a=await _n({dryRun:t.dryRun});if(t.dryRun||a.pending||S.phase!=="blocked")return{result:a,resumed:!1};if(e.prepare)return S={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]},{result:a,resumed:!1};try{return await me(),S={phase:"ready",message:"",blockerPaths:[]},{result:a,resumed:!0}}catch(v){const r=v instanceof Error?v.message:String(v);return setTimeout(()=>{T().catch(()=>{})},1e3),{result:a,resumed:!1,resumeError:r}}}finally{A=null}}s(sr,"repairMigrations");async function cr(){ee=e.intervalMs??ct;const t=y.token;L=new hn({epoch:t,enqueue:J}),jt(L),S={phase:"recovering",message:"daemon startup recovery is running and normal services are unavailable",blockerPaths:[]},k.fresh(()=>{p({level:"info",event:"daemon.started",fields:{pid:process.pid,interval_ms:ee}})});const a=b;k.fresh(()=>{p({level:"info",event:"daemon.install_id.resolved",fields:{install_id:a}})});const v=await jr(a);if(k.fresh(()=>{p({level:"info",event:"daemon.environment.registered",fields:{environment_id:v.environmentId,created:v.created}})}),k.fresh(()=>{let r;try{r=st()}catch{return}r!==null&&p({level:"warn",event:"daemon.startup.warning",fields:{stage:"termrender",warning:r.slice(0,2048)}})}),Dt(),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&&zr(),!Z(e.role)){S={phase:"ready",message:"",blockerPaths:[]};return}if(await k.fresh(async()=>{await at(),await nt();const r=e.role!==void 0;await ot(Date.now(),r),await it(Date.now(),r)}),e.role===void 0&&await k.fresh(async()=>{const{reconcile:r,migrated:n}=await Kt(bt);r.changed&&p({level:"info",event:"daemon.boot_change.reconciled",fields:{cleared_count:r.cleared.length,same_boot_proven:r.sameBootProven}}),n.length>0&&p({level:"info",event:"daemon.pid_identity.migrated",fields:{migrated_count:n.length}})}),await k.fresh(async()=>{const r=await he();for(const n of await Ne())r.has(n.node_id)||n.status!=="active"||n.pi_pid!=null||n.frozen_at!=null||n.respawn_not_before!=null||(await Me(n.node_id,new Date().toISOString()),p({level:"warn",event:"daemon.startup.launch_debt_recorded",node_id:n.node_id}))}),await k.fresh(async()=>{await Ft();for(const r of vn){const n=await r.apply();n.changed&&p({level:"info",event:"daemon.boot_migration.applied",fields:{migration:r.id,...n.summary}})}}),R(rt()),D){const r=s(()=>{R(D().catch(()=>{})),R(fr().then(n=>B?.observe(n)).then(()=>{},n=>{p({level:"warn",event:"daemon.peer.status_failed",error:n})}))},"refresh");R(et().then(({completion:n})=>n).catch(n=>{p({level:"error",event:"daemon.grants.sweep_failed",error:n})})),r(),G=setInterval(r,Fe*1e3),G.unref(),pe=mr({joined:!0,register:R})}await J(async()=>{await un(),await fn()}),te=pr(),z=setInterval(()=>{V().catch(r=>p({level:"error",event:"daemon.tick.failed",error:r}))},ee),ne=await Gt(()=>{V().catch(r=>p({level:"error",event:"daemon.tick.failed",error:r}))}),oe=await M.subscribe(()=>{V().catch(r=>p({level:"error",event:"daemon.tick.failed",error:r}))},{kinds:["spend_limits"]}),ie=await M.subscribe(r=>{J(()=>k.fresh(()=>Xn(r)))},{kinds:["execution_exit"]}),await V(),e.role===void 0&&import("../commands/sys/import/move.js").then(({settleMoveAtDaemonStart:r})=>r(()=>!E,n=>p({level:"warn",event:"daemon.move.settle_failed",error:n}))).catch(r=>p({level:"warn",event:"daemon.move.settle_failed",error:r}))}s(cr,"completeStartup");function me(){return Ze??=cr().catch(t=>{throw S={phase:"initializing",message:"daemon startup recovery failed and normal services are unavailable",blockerPaths:[]},t})}s(me,"resumeStartup");try{process.on("SIGINT",Re),process.on("SIGTERM",Pe),process.on("exit",Ee),gn(),d!==null&&p({level:"info",event:"daemon.person.resolved",fields:{person_id:d.id,source:d.source}}),c!==null&&!c.alreadyDone&&p({level:"info",event:"daemon.packages.install_migration_done",fields:{moved:c.moved,discarded:c.discarded,people:c.people}}),i!==null&&p({level:"info",event:"daemon.permissions.boot",fields:{...i}}),u!==null&&p({level:"info",event:"daemon.person.retired",fields:{person_id:u.person,joined_from:u.joinedFrom,retired:u.retired,columns:u.columns}}),O(e.role)?W=await _r():br(Sr());const t=y.token;zt({epoch:t,requestHandover:nr,registerDetached:R,startupBlock:er,admitStartup:ar,repairMigrations:sr}),Q(),I=O(e.role)?Mr({tcp:e.tcp}):eo(e),await I.ready,Q(I.tcpAddress()??"");const a=yr()??fe("user").document_port;if(O(e.role)){const r=Fr(a,Br());try{await r.ready,se=r}catch(n){p({level:"warn",event:"daemon.document_listener.bind_failed",fields:{port:a,error:n instanceof Error?n.message:String(n)}})}}const v=fe("user").runtime;if(v?.issuer&&(D=Zr(v.issuer,R),v.unsandboxed===!0&&(B=ur({syncGrants:D}))),e.role==="api"){const r=s(()=>R(import("../core/providers/bundles.js").then(_=>_.syncProviderBundles()).catch(_=>{p({level:"error",event:"daemon.providers.bundle_sync_failed",error:_})})),"bundleTick"),n=s(()=>{R(Qr().catch(_=>{p({level:"error",event:"daemon.packages.sync_failed",error:_})})),r()},"packageTick");n(),F=setInterval(n,Fe*1e3),F.unref()}if(O(e.role)&&(ce=await Vr()),Z(e.role)&&(le=Xr()),de=await Yr({serves:O(e.role),runsLanes:Z(e.role)}),v?.unsandboxed===!0&&v.listener!==void 0&&p({level:"warn",event:"daemon.app_listener.refused_unsandboxed",fields:{reason:"runtime.unsandboxed is set; runtime.listener is ignored"}}),O(e.role)&&v!==void 0&&v.listener!==void 0&&v.unsandboxed!==!0&&($=await Hr(v,async()=>await tt(v.issuer.replace(/\/$/,"")),D),await $.ready,Q(I.tcpAddress()??"",`${v.listener.address}:${$.port()}`)),e.role===void 0)try{await yn()}catch(r){if(A=null,r instanceof Sn)return S={phase:"blocked",message:r.message,blockerPaths:r.blockerPaths},T;throw r}process.platform==="linux"&&P(C)&&(Ir(),await Er("app:terminal"));try{e.prepare?S={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]}:(await me(),S={phase:"ready",message:"",blockerPaths:[]})}finally{A=null}return T}catch(t){try{await T()}catch(a){throw new AggregateError([t,a],"daemon startup failed and cleanup also failed")}throw t}}s(no,"runDaemon");var aa=no;export{Zn as API_DRAIN_GRACE_MS,la as brokerCommandDeclaresCanvasHome,Se as brokerCommandEpoch,aa as default,Xn as exitedNodePass,Z as roleRunsLanes,O as roleServesRequests,no as runDaemon,Qn as superviseTick,Tn as teardownFleet};
21
+ `),process.exit(1)}}s(_e,"handleSignal");function be(){_e("SIGINT")}s(be,"onSigint");function ke(){_e("SIGTERM")}s(ke,"onSigterm");function Re(){C().catch(()=>{})}s(Re,"onExit");async function J(r){P&&(U=U.then(r).then(()=>{},t=>{b.fresh(()=>{m({level:"error",event:"daemon.lane_job.failed",error:t})})}))}s(J,"enqueue");async function V(){!P||re||(Qe.check()&&T&&(m({level:"info",event:"daemon.resume.detected"}),k(T().catch(()=>{}))),re=!0,await J(async()=>{if(re=!1,!!P)try{f||await Zt({log:c}),await Kn(Date.now(),er)}catch(r){b.fresh(()=>{m({level:"error",event:"daemon.tick.failed",error:r})})}}))}s(V,"enqueueTick");let B=null;async function ir(){if(B!==null)throw{status:500,code:"admission_failed",message:`daemon admission previously failed: ${B instanceof Error?B.message:String(B)}`};if(S.phase==="ready")return{admitted:!1,already_admitted:!0,startup_phase:"ready"};if(S.phase!=="prepared"&&S.phase!=="recovering")throw{status:409,code:"not_prepared",message:S.message};const r=S.phase==="prepared";try{return await pe(),S={phase:"ready",message:"",blockerPaths:[]},r?{admitted:!0,already_admitted:!1,startup_phase:"ready"}:{admitted:!1,already_admitted:!0,startup_phase:"ready"}}catch(t){throw B=t,{status:500,code:"admission_failed",message:`daemon admission failed: ${t instanceof Error?t.message:String(t)}`}}}s(ir,"admitStartup");async function ar(r){if($!==null)throw{status:409,code:"migration_in_progress",message:`the canvas import is already running (${$})`};$="repair";try{const t=await vn({dryRun:r.dryRun});if(r.dryRun||t.pending||S.phase!=="blocked")return{result:t,resumed:!1};if(e.prepare)return S={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]},{result:t,resumed:!1};try{return await pe(),S={phase:"ready",message:"",blockerPaths:[]},{result:t,resumed:!0}}catch(a){const n=a instanceof Error?a.message:String(a);return setTimeout(()=>{C().catch(()=>{})},1e3),{result:t,resumed:!1,resumeError:n}}}finally{$=null}}s(ar,"repairMigrations");async function sr(){ee=e.intervalMs??ot;const r=y.token;A=new pn({epoch:r,enqueue:J}),Ot(A),S={phase:"recovering",message:"daemon startup recovery is running and normal services are unavailable",blockerPaths:[]},b.fresh(()=>{m({level:"info",event:"daemon.started",fields:{pid:process.pid,interval_ms:ee}})});const t=_;if(b.fresh(()=>{m({level:"info",event:"daemon.install_id.resolved",fields:{install_id:t}})}),b.fresh(()=>{let a;try{a=nt()}catch{return}a!==null&&m({level:"warn",event:"daemon.startup.warning",fields:{stage:"termrender",warning:a.slice(0,2048)}})}),Et(),e.role!==void 0&&!process.env.CRTR_DIRECTORY_URL)throw new Error("CRTR_DIRECTORY_URL must be set on a cloud role (--role api|reconcile|all): it names the directory this deployment mints tokens against");if(e.role==="all"&&!process.env.CRTR_DATABASE_URL&&!process.env.CRTR_TEST_PG_URL)throw new Error("CRTR_DATABASE_URL must be set on --role all: it names the Postgres this process serves");if(e.role!==void 0&&Or(),!Z(e.role)){S={phase:"ready",message:"",blockerPaths:[]};return}if(await b.fresh(async()=>{await tt(),await Zr();const a=e.role!==void 0;await et(Date.now(),a),await rt(Date.now(),a)}),e.role===void 0&&await b.fresh(async()=>{const{reconcile:a,migrated:n}=await jt(gt);a.changed&&m({level:"info",event:"daemon.boot_change.reconciled",fields:{cleared_count:a.cleared.length,same_boot_proven:a.sameBootProven}}),n.length>0&&m({level:"info",event:"daemon.pid_identity.migrated",fields:{migrated_count:n.length}})}),await b.fresh(async()=>{const a=await fe();for(const n of await Le())a.has(n.node_id)||n.status!=="active"||n.pi_pid!=null||n.frozen_at!=null||n.respawn_not_before!=null||(await $e(n.node_id,new Date().toISOString()),m({level:"warn",event:"daemon.startup.launch_debt_recorded",node_id:n.node_id}))}),await b.fresh(async()=>{await Nt();for(const a of fn){const n=await a.apply();n.changed&&m({level:"info",event:"daemon.boot_migration.applied",fields:{migration:a.id,...n.summary}})}}),k(Qr()),T){const a=s(()=>{k(T().catch(()=>{})),k(mr().then(n=>F?.observe(n)).then(()=>{},n=>{m({level:"warn",event:"daemon.peer.status_failed",error:n})}))},"refresh");k(Yr().then(({completion:n})=>n).catch(n=>{m({level:"error",event:"daemon.grants.sweep_failed",error:n})})),a(),G=setInterval(a,Ge*1e3),G.unref(),de=pr({joined:!0,register:k})}await J(async()=>{await dn(),await cn()}),te=dr(),j=setInterval(()=>{V().catch(a=>m({level:"error",event:"daemon.tick.failed",error:a}))},ee),ne=await $t(()=>{V().catch(a=>m({level:"error",event:"daemon.tick.failed",error:a}))}),oe=await M.subscribe(()=>{V().catch(a=>m({level:"error",event:"daemon.tick.failed",error:a}))},{kinds:["spend_limits"]}),ie=await M.subscribe(a=>{J(()=>b.fresh(()=>Jn(a)))},{kinds:["execution_exit"]}),await V(),e.role===void 0&&import("../commands/sys/import/move.js").then(({settleMoveAtDaemonStart:a})=>a(()=>!P,n=>m({level:"warn",event:"daemon.move.settle_failed",error:n}))).catch(a=>m({level:"warn",event:"daemon.move.settle_failed",error:a}))}s(sr,"completeStartup");function pe(){return Xe??=sr().catch(r=>{throw S={phase:"initializing",message:"daemon startup recovery failed and normal services are unavailable",blockerPaths:[]},r})}s(pe,"resumeStartup");try{process.on("SIGINT",be),process.on("SIGTERM",ke),process.on("exit",Re),un(),d!==null&&m({level:"info",event:"daemon.person.resolved",fields:{person_id:d.id,source:d.source}}),l!==null&&!l.alreadyDone&&m({level:"info",event:"daemon.packages.install_migration_done",fields:{moved:l.moved,discarded:l.discarded,people:l.people}}),i!==null&&m({level:"info",event:"daemon.permissions.boot",fields:{...i}}),u!==null&&m({level:"info",event:"daemon.person.retired",fields:{person_id:u.person,joined_from:u.joinedFrom,retired:u.retired,columns:u.columns}}),H(e.role)?W=await yr():Sr(gr());const r=y.token;Ft({epoch:r,requestHandover:tr,registerDetached:k,startupBlock:Ze,admitStartup:ir,repairMigrations:ar}),Q(),I=H(e.role)?$r({tcp:e.tcp}):Yn(e),await I.ready,Q(I.tcpAddress()??"");const t=Oe("user").runtime;if(t?.issuer&&(T=Vr(t.issuer,k),t.unsandboxed===!0&&(F=fr({syncGrants:T}))),e.role==="api"||e.role==="all"){const a=s(()=>k(import("../core/providers/bundles.js").then(h=>h.syncProviderBundles()).catch(h=>{m({level:"error",event:"daemon.providers.bundle_sync_failed",error:h})})),"bundleTick"),n=s(()=>{k(Kr().catch(h=>{m({level:"error",event:"daemon.packages.sync_failed",error:h})})),a()},"packageTick");n(),O=setInterval(n,Ge*1e3),O.unref()}if(H(e.role)&&(se=await qr()),Z(e.role)&&(le=Jr()),ce=await Wr({serves:H(e.role),runsLanes:Z(e.role)}),t?.unsandboxed===!0&&t.listener!==void 0&&m({level:"warn",event:"daemon.app_listener.refused_unsandboxed",fields:{reason:"runtime.unsandboxed is set; runtime.listener is ignored"}}),H(e.role)&&t!==void 0&&t.listener!==void 0&&t.unsandboxed!==!0&&(L=await Gr(t,async()=>await Xr(t.issuer.replace(/\/$/,"")),T),await L.ready,Q(I.tcpAddress()??"",`${t.listener.address}:${L.port()}`)),e.role===void 0)try{await hn()}catch(a){if($=null,a instanceof wn)return S={phase:"blocked",message:a.message,blockerPaths:a.blockerPaths},C;throw a}process.platform==="linux"&&E(D)&&(Er(),await Rr("app:terminal"));try{e.prepare?S={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]}:(await pe(),S={phase:"ready",message:"",blockerPaths:[]})}finally{$=null}return C}catch(r){try{await C()}catch(t){throw new AggregateError([r,t],"daemon startup failed and cleanup also failed")}throw r}}s(Zn,"runDaemon");var ea=Zn;export{Vn as API_DRAIN_GRACE_MS,na as brokerCommandDeclaresCanvasHome,ge as brokerCommandEpoch,ea as default,Jn as exitedNodePass,Z as roleRunsLanes,H as roleServesRequests,Zn as runDaemon,Kn as superviseTick,Pn as teardownFleet};
@@ -47,14 +47,6 @@ export interface DaemonExportSqliteResult {
47
47
  ms: number;
48
48
  userVersion: number;
49
49
  }
50
- export interface DaemonExportSqliteResult {
51
- path: string;
52
- rows: number;
53
- ms: number;
54
- userVersion: number;
55
- }
56
- /** Run the selected generation's `crtrd-cli export-sqlite` and wait for it. */
57
- export declare function runDaemonExportSqlite(): Promise<DaemonExportSqliteResult>;
58
50
  /** Run the selected generation's `crtrd-cli import-dump`: the row files of the running canvas into `out`/rows. */
59
51
  export declare function runDaemonImportDump(out: string, kind: 'machine' | 'hosted'): Promise<DumpResult>;
60
52
  /** Run `crtrd-cli import-dump <out> bodies`: every `bodies` row into `out`/rows/bodies (the pre-pause dump; the later `runDaemonImportDump` adds the rows written since). */
@@ -1,3 +1,3 @@
1
- var q=Object.defineProperty;var o=(t,e)=>q(t,"name",{value:e,configurable:!0});import{spawn as K,execFileSync as J}from"node:child_process";import{createRequire as Q}from"node:module";import{dirname as N,join as T}from"node:path";import{fileURLToPath as Z,pathToFileURL as I}from"node:url";import{existsSync as F,lstatSync as tt,mkdirSync as et,openSync as H,closeSync as G,fstatSync as W,readSync as rt}from"node:fs";import{crtrHome as S}from"../core/canvas/paths.js";import{listProcessTable as nt}from"../core/canvas/pid.js";import{bindDaemonEventSource as ot,eventSource as at}from"../core/events/source.js";import{hostExecPath as y}from"../core/runtime/branded-host.js";import{isDaemonRunning as it,readPidfile as w,isPidAlive as R}from"./pidfile.js";import{DAEMON_STARTUP_WINDOW_MS as V}from"./startup-policy.js";import{computerIsUnset as st,readMachineConfig as ct}from"./machine-link/config.js";import{exclusiveLockOwnerPid as ut}from"../core/exclusive-lock.js";import{onDiskMigrationLockPath as lt}from"../core/canvas/paths.js";import{envNoDaemonAutostart as _t}from"../shared/env.js";import{waitForDaemonAvailability as dt}from"../api/index.js";import{localClient as pt}from"../api/node-transport.js";const Rt=["TMUX","TMUX_PANE","NODE_OPTIONS"],ft=new Set(["CRTR_HOME","CRTR_RUNTIME_HOME","CRTR_PIDFILE","CRTR_RUNTIME","CRTR_INSTALL_ID","CRTR_LOG","CRTR_DEBUG","CRTR_DEBUG_PID_LIVENESS","CRTR_TIMING","CRTR_TIMING_PROC","CRTR_NO_DAEMON_AUTOSTART","CRTR_NO_AUTO_UPDATE","CRTR_NO_AUTO_INIT","CRTR_NO_EXPORTS","CRTR_LAYOUT_REFUSE","CRTR_POSTGRES_HOME","CRTR_DATABASE_URL","CRTR_DATABASE_SCHEMA","CRTR_DATABASE_POOL_MAX","CRTR_SCHEMA_DATABASE_URL","CRTR_DOCUMENT_PORT","CRTR_LAUNCHER_SOCKET","CRTR_API_ADDRESS","CRTR_DIRECTORY_URL","CRTR_PUBLIC_API_URL","CRTR_CANVAS_URL","CRTR_CANVAS_CLIENT_ID","CRTR_CANVAS_JWK_FILE","CRTR_SECRETS_KEY","CRTR_IMPORT_SERVICE_TOKEN","CRTR_PACKAGES_TOKEN","CRTR_FEEDBACK_ENDPOINT","CRTR_FEEDBACK_TOKEN","CRTR_SUPPORT_REPO","CRTR_BRANDED_HOST","CRTR_CODESIGN_IDENTITY","CRTR_PLUGIN_REVALIDATE_TTL_MS","CRTR_IMPORT_BLOB_WORKERS","CRTR_MAX_LIVE_BROKERS","CRTR_WARN_LIVE_BROKERS","CRTR_BROKER_RSS_CAP_MB","CRTR_UNATTENDED_PARK_MS","CRTR_WARM_POOL","CRTR_STREAM_WATCHDOG_MS","CRTR_CONVERSATION_COMMIT_DEADLINE_MS","CRTR_NAME_MODEL","CRTR_MODEL_PROVIDER","CRTR_BROKER_SIGNAL_LONG_PROOF"]),mt=["CRTR_DB_","CRTR_BOOT_","CRTR_R2_","CRTR_LEDGER_","CRTR_BASH_","CRTR_WATCHER_","CRTR_RECAP_","CRTR_MODEL_AUTH_","CRTR_TEST_","CRTR_FAULT_"];function ht(t){return Rt.includes(t)?!1:t.startsWith("CRTR_")?ft.has(t)||mt.some(e=>t.startsWith(e)):!0}o(ht,"daemonKeepsEnv");function g(){const t={};for(const[e,r]of Object.entries(process.env))ht(e)&&(t[e]=r);return t}o(g,"sanitizedDaemonEnv");function Et(){for(let t=N(Z(import.meta.url));;t=N(t)){if(F(T(t,"bin","runtime-generation-manifest.mjs")))return t;if(N(t)===t)throw new Error(`cannot locate the crouter generation root from ${import.meta.url}`)}}o(Et,"generationRoot");async function P(){const t=Et(),e=I(T(t,"bin","runtime-generation-manifest.mjs")).href,{runtimeHome:r}=await import(e);try{tt(T(r(),"selected"))}catch(u){if(u.code!=="ENOENT")throw u;return["--conditions","crtr-src","--import",I(Q(import.meta.url).resolve("tsx/esm")).href,T(t,"src","daemon","crtrd-cli.ts")]}const n=I(T(t,"bin","runtime-selector.mjs")).href,{tryResolveRuntime:a}=await import(n),s=a("daemon");if(!s.ok)throw new Error(`cannot resolve the selected runtime generation's daemon entry: ${s.error}`);return[s.runtime.entryPath]}o(P,"resolveDaemonLaunch");function Tt(t,e){return t.includes(` --canvas-home ${e} `)||t.endsWith(` --canvas-home ${e}`)}o(Tt,"daemonCommandDeclaresCanvasHome");function wt(){const t=nt();if(t===null)return[];const e=S(),r=[];for(const{pid:n,command:a}of t)a.includes("daemon/crtrd")&&Tt(a,e)&&n!==process.pid&&r.push(n);return r}o(wt,"findDaemonPids");function Dt(t){const e=wt().filter(n=>n!==t);for(const n of e)try{process.kill(n,"SIGTERM")}catch{}if(e.length===0)return e;const r=Date.now()+2e3;for(;Date.now()<r&&e.some(n=>R(n));)J("sleep",["0.1"]);for(const n of e)if(R(n))try{process.kill(n,"SIGKILL")}catch{}return e}o(Dt,"sweepStrayDaemons");async function Qt(){const t=process.execve;if(t===void 0)throw new Error(`this Node.js ${process.version} runtime cannot replace PID 1 with the successor daemon`);const e=y(),r=await P();return t(e,[e,...r,"--canvas-home",S()],g())}o(Qt,"execDaemon");async function C(t){const e=await P(),r=K(y(),[...e,...t],{stdio:["ignore","pipe","pipe"],env:g()});let n="",a="";r.stdout.setEncoding("utf8").on("data",c=>{n+=c}),r.stderr.setEncoding("utf8").on("data",c=>{a+=c});const s=await new Promise((c,d)=>{r.once("error",d),r.once("close",f=>c(f))});if(s!==0)throw new Error(a.trim()||`the ${t[0]} process exited with code ${s}`);const u=n.trim().split(`
2
- `).at(-1)??"";return JSON.parse(u)}o(C,"runDaemonEntry");function Zt(){return C(["export-sqlite"])}o(Zt,"runDaemonExportSqlite");function te(t,e){return C(["import-dump",t,e])}o(te,"runDaemonImportDump");function ee(t){return C(["import-dump",t,"bodies"])}o(ee,"runDaemonBodiesDump");function re(){return C(["import-dump","","install-id"])}o(re,"runDaemonInstallId");const j=2e4,L=10,v=1e3;async function b(t=v){const e=Math.min(t,v);return pt({autostart:!1,timeoutMs:e}).probeHealthz(e)}o(b,"probeDaemonHealth");function St(t){const e=t instanceof Error?t.message:String(t);if(typeof t!="object"||t===null)return e;const r=t.code,n=t.cause,a=typeof r=="string"?r:n?.code;return typeof a=="string"&&!e.includes(a)?`${e}: ${a}`:e}o(St,"probeErrorMessage");async function X(t=v){const e=await b(t);if(e.startup_phase==="blocked"){const r=w()??process.pid;throw new O(r,e.startup_blocked??"daemon startup is blocked")}if(!e.ok)throw new Error(e.startup_blocked??"crtrd health check reported not ready")}o(X,"probeDaemonServing");async function ne(){try{return await X(),!0}catch{return!1}}o(ne,"isDaemonServing");function U(t){return new Promise(e=>{setTimeout(e,t)})}o(U,"sleepMs");class k extends Error{static{o(this,"DaemonExitedBeforeReadyError")}stderrTail;constructor(e,r){super(r===""?e:`${e}
3
- ${r}`),this.name="DaemonExitedBeforeReadyError",this.stderrTail=r}}class Y extends Error{static{o(this,"DaemonLaunchError")}constructor(e){super(e instanceof Error?e.message:String(e),{cause:e}),this.name="DaemonLaunchError"}}class O extends Error{static{o(this,"DaemonStartupBlockedError")}constructor(e,r){super(`daemon ${e} is running but normal startup is blocked: ${r}`),this.name="DaemonStartupBlockedError"}}class B extends Error{static{o(this,"DaemonNotPreparedError")}constructor(e,r){super(r===void 0?`daemon ${e} is serving but did not report the prepared startup phase`:`daemon ${e} reported startup phase ${r}, not prepared`),this.name="DaemonNotPreparedError"}}async function At(t,e=V,r={},n="ready"){const a=r.readPidfile??w,s=r.isPidAlive??R,u=r.childExited,c=r.isDaemonServing,d=r.probeDaemonServing??(async h=>{if(c!==void 0){if(await c())return;throw new Error("crtrd health check reported not ready")}await X(h)}),f=r.probeDaemonHealth??b,D=r.sleepMs??U,i=r.now??Date.now;let p=null,l=null;return await dt({windowMs:e,pollIntervalMs:L,now:i,sleep:D,retry:o(h=>h!==l,"retry"),probe:o(async h=>{const m=a();if(m===null||!s(m)){const _=u?.();throw _!=null&&(_.signal!==null?l=new k(`daemon ${t} exited before becoming ready (by ${_.signal})`,r.childStderrTail?.()??""):_.code!==0&&(l=new k(`daemon ${t} exited before becoming ready (with exit code ${_.code??"?"})`,r.childStderrTail?.()??"")),l!==null)?l:new Error(`daemon ${t} has no live pidfile owner`)}if(n==="ready"){try{await d(h)}catch(_){throw _ instanceof O&&(l=_),_}p=m;return}const E=await f(h);if(E.startup_phase==="prepared"){p=m;return}throw E.startup_phase==="blocked"?(l=new O(m,E.startup_blocked??"on-disk migration is blocked"),l):E.startup_phase==="ready"?(l=new B(m,E.startup_phase),l):new Error(`daemon ${m} is ${E.startup_phase??"not reporting a startup phase"}; waiting for prepared`)},"probe")}),p===t?null:p}o(At,"verifyDaemonStartup");async function Ct(t,e=j,r={}){const n=r.readPidfile??w,a=r.isPidAlive??R,s=r.sleepMs??U,u=r.now??Date.now,c=u()+e;for(;u()<=c;){if(!a(t)&&n()!==t)return;await s(L)}throw new Error(`daemon ${t} did not exit and release its pidfile within ${e}ms`)}o(Ct,"waitForDaemonExit");const Ot=2e3,xt=5e3;async function z(t,e=j,r={}){const n=r.isPidAlive??R,a=r.sleepMs??U,s=r.now??Date.now;try{process.kill(t,"SIGTERM")}catch{}try{return await Ct(t,e,r),"terminated"}catch{}try{process.kill(t,"SIGKILL")}catch{}const u=s()+Ot;for(;s()<=u;){if(!n(t))return"killed";await a(L)}throw new Error(`daemon ${t} survived both SIGTERM and SIGKILL`)}o(z,"stopDaemonProcess");async function oe(){const t=w(),e=t!==null&&R(t),r=e&&await z(t)==="killed",n=Dt(null);return{stopped:e||n.length>0,...e?{pid:t}:{},strays_killed:n,force_killed:r}}o(oe,"stopAllDaemons");function Mt(t,e,r=2048){let n;try{n=H(t,"r");const{size:a}=W(n),s=Math.max(e,a-r),u=a-s;if(u<=0)return"";const c=Buffer.alloc(u);return rt(n,c,0,u,s),c.toString("utf8").trim()}catch{return""}finally{if(n!==void 0)try{G(n)}catch{}}}o(Mt,"readLogTailFrom");async function Nt(t={}){if(process.platform==="linux"&&F("/run/crtr/launcher.sock")&&!R(w()??-1)&&ct()===void 0)throw new Error("crtrd is managed by the root launcher; it cannot self-daemonize");const e=t.targetPhase??"ready",r=w();if(r!==null&&R(r))try{const i=await b();if(e==="prepared"){if(i.startup_phase==="prepared")return{started:!1,existing_pid:r,startup_phase:i.startup_phase};throw new B(r,i.startup_phase)}return i.ok?{started:!1,existing_pid:r,...i.startup_phase===void 0?{}:{startup_phase:i.startup_phase}}:{started:!1,existing_pid:r,running:!0,serving:!1,probe_error:i.startup_blocked??"crtrd health check reported not ready",...i.startup_phase===void 0?{}:{startup_phase:i.startup_phase}}}catch(i){if(i instanceof B)throw i;return{started:!1,existing_pid:r,running:!0,serving:!1,probe_error:St(i)}}et(S(),{recursive:!0});const n=await P().catch(i=>{throw new Y(i)}),a=T(S(),"crtrd.err"),s=H(a,"a"),u=(()=>{try{return W(s).size}catch{return 0}})();at()===void 0&&ot();const c=K(y(),[...n,"--canvas-home",S(),...e==="prepared"?["--prepare"]:[]],{detached:!0,stdio:["ignore",s,s],env:g()});G(s);const d=c.pid;if(d===void 0)throw new Error("daemon spawn did not return a pid");let f=null;c.once("exit",(i,p)=>{f={code:i,signal:p}}),c.unref();let D;try{D=await At(d,V,{childExited:o(()=>f,"childExited"),childStderrTail:o(()=>Mt(a,u),"childStderrTail")},e)}catch(i){const p=ut(lt())===d;if(f===null&&!p&&!(i instanceof O))try{await z(d,xt)}catch{}throw i}return D!==null?{started:!1,existing_pid:D,startup_phase:e}:{started:!0,pid:d,startup_phase:e}}o(Nt,"spawnDaemon");function It(){return _t()||process.argv.includes("--no-autostart")}o(It,"autostartDisabled");const yt=5e3,gt=6e4;let $=!1,A,x=0,M=0;function Pt(t){return Math.min(yt*2**(t-1),gt)}o(Pt,"autostartBackoffMs");function Lt(){A=void 0,x=0,M=0}o(Lt,"resetDaemonAutostart");function ae(){return A}o(ae,"daemonAutostartStartupFailure");function ie(t={}){const e=t.isDaemonRunning??it,r=t.spawnDaemon??Nt,n=t.now??Date.now;if(!It()&&!(!t.spawnDaemon&&st())&&!$&&!(n()<M)){if(e()){Lt();return}A=void 0,$=!0,r().then(()=>{A=void 0,x=0,M=0},a=>{(a instanceof k||a instanceof Y)&&(A=a.message),x+=1,M=n()+Pt(x)}).finally(()=>{$=!1})}}o(ie,"ensureDaemon");export{Rt as DAEMON_ENV_STRIP_KEYS,k as DaemonExitedBeforeReadyError,Y as DaemonLaunchError,B as DaemonNotPreparedError,O as DaemonStartupBlockedError,It as autostartDisabled,ae as daemonAutostartStartupFailure,Tt as daemonCommandDeclaresCanvasHome,ht as daemonKeepsEnv,ie as ensureDaemon,Qt as execDaemon,wt as findDaemonPids,ne as isDaemonServing,b as probeDaemonHealth,X as probeDaemonServing,St as probeErrorMessage,Lt as resetDaemonAutostart,ee as runDaemonBodiesDump,Zt as runDaemonExportSqlite,te as runDaemonImportDump,re as runDaemonInstallId,g as sanitizedDaemonEnv,Nt as spawnDaemon,oe as stopAllDaemons,z as stopDaemonProcess,Dt as sweepStrayDaemons,At as verifyDaemonStartup,Ct as waitForDaemonExit};
1
+ var J=Object.defineProperty;var o=(e,t)=>J(e,"name",{value:t,configurable:!0});import{spawn as K,execFileSync as q}from"node:child_process";import{createRequire as Q}from"node:module";import{dirname as x,join as T}from"node:path";import{fileURLToPath as Z,pathToFileURL as N}from"node:url";import{existsSync as F,lstatSync as ee,mkdirSync as te,openSync as H,closeSync as G,fstatSync as W,readSync as re}from"node:fs";import{crtrHome as S}from"../core/canvas/paths.js";import{listProcessTable as ne}from"../core/canvas/pid.js";import{bindDaemonEventSource as oe,eventSource as ae}from"../core/events/source.js";import{hostExecPath as I}from"../core/runtime/branded-host.js";import{isDaemonRunning as ie,readPidfile as w,isPidAlive as R}from"./pidfile.js";import{DAEMON_STARTUP_WINDOW_MS as V}from"./startup-policy.js";import{computerIsUnset as se,readMachineConfig as ce}from"./machine-link/config.js";import{exclusiveLockOwnerPid as ue}from"../core/exclusive-lock.js";import{onDiskMigrationLockPath as le}from"../core/canvas/paths.js";import{envNoDaemonAutostart as _e}from"../shared/env.js";import{waitForDaemonAvailability as de}from"../api/index.js";import{localClient as pe}from"../api/node-transport.js";const Re=["TMUX","TMUX_PANE","NODE_OPTIONS"],fe=new Set(["CRTR_HOME","CRTR_RUNTIME_HOME","CRTR_PIDFILE","CRTR_RUNTIME","CRTR_INSTALL_ID","CRTR_LOG","CRTR_DEBUG","CRTR_DEBUG_PID_LIVENESS","CRTR_TIMING","CRTR_TIMING_PROC","CRTR_NO_DAEMON_AUTOSTART","CRTR_NO_AUTO_UPDATE","CRTR_NO_AUTO_INIT","CRTR_NO_EXPORTS","CRTR_LAYOUT_REFUSE","CRTR_POSTGRES_HOME","CRTR_DATABASE_URL","CRTR_DATABASE_SCHEMA","CRTR_DATABASE_POOL_MAX","CRTR_SCHEMA_DATABASE_URL","CRTR_DOCUMENT_PORT","CRTR_LAUNCHER_SOCKET","CRTR_API_ADDRESS","CRTR_DIRECTORY_URL","CRTR_PUBLIC_API_URL","CRTR_CANVAS_URL","CRTR_CANVAS_CLIENT_ID","CRTR_CANVAS_JWK_FILE","CRTR_SECRETS_KEY","CRTR_IMPORT_SERVICE_TOKEN","CRTR_PACKAGES_TOKEN","CRTR_FEEDBACK_ENDPOINT","CRTR_FEEDBACK_TOKEN","CRTR_SUPPORT_REPO","CRTR_BRANDED_HOST","CRTR_CODESIGN_IDENTITY","CRTR_PLUGIN_REVALIDATE_TTL_MS","CRTR_IMPORT_BLOB_WORKERS","CRTR_MAX_LIVE_BROKERS","CRTR_WARN_LIVE_BROKERS","CRTR_BROKER_RSS_CAP_MB","CRTR_UNATTENDED_PARK_MS","CRTR_WARM_POOL","CRTR_STREAM_WATCHDOG_MS","CRTR_CONVERSATION_COMMIT_DEADLINE_MS","CRTR_NAME_MODEL","CRTR_MODEL_PROVIDER","CRTR_BROKER_SIGNAL_LONG_PROOF"]),me=["CRTR_DB_","CRTR_BOOT_","CRTR_R2_","CRTR_LEDGER_","CRTR_BASH_","CRTR_WATCHER_","CRTR_RECAP_","CRTR_MODEL_AUTH_","CRTR_TEST_","CRTR_FAULT_"];function he(e){return Re.includes(e)?!1:e.startsWith("CRTR_")?fe.has(e)||me.some(t=>e.startsWith(t)):!0}o(he,"daemonKeepsEnv");function y(){const e={};for(const[t,r]of Object.entries(process.env))he(t)&&(e[t]=r);return e}o(y,"sanitizedDaemonEnv");function Ee(){for(let e=x(Z(import.meta.url));;e=x(e)){if(F(T(e,"bin","runtime-generation-manifest.mjs")))return e;if(x(e)===e)throw new Error(`cannot locate the crouter generation root from ${import.meta.url}`)}}o(Ee,"generationRoot");async function g(){const e=Ee(),t=N(T(e,"bin","runtime-generation-manifest.mjs")).href,{runtimeHome:r}=await import(t);try{ee(T(r(),"selected"))}catch(u){if(u.code!=="ENOENT")throw u;return["--conditions","crtr-src","--import",N(Q(import.meta.url).resolve("tsx/esm")).href,T(e,"src","daemon","crtrd-cli.ts")]}const n=N(T(e,"bin","runtime-selector.mjs")).href,{tryResolveRuntime:a}=await import(n),s=a("daemon");if(!s.ok)throw new Error(`cannot resolve the selected runtime generation's daemon entry: ${s.error}`);return[s.runtime.entryPath]}o(g,"resolveDaemonLaunch");function Te(e,t){return e.includes(` --canvas-home ${t} `)||e.endsWith(` --canvas-home ${t}`)}o(Te,"daemonCommandDeclaresCanvasHome");function we(){const e=ne();if(e===null)return[];const t=S(),r=[];for(const{pid:n,command:a}of e)a.includes("daemon/crtrd")&&Te(a,t)&&n!==process.pid&&r.push(n);return r}o(we,"findDaemonPids");function De(e){const t=we().filter(n=>n!==e);for(const n of t)try{process.kill(n,"SIGTERM")}catch{}if(t.length===0)return t;const r=Date.now()+2e3;for(;Date.now()<r&&t.some(n=>R(n));)q("sleep",["0.1"]);for(const n of t)if(R(n))try{process.kill(n,"SIGKILL")}catch{}return t}o(De,"sweepStrayDaemons");async function Qe(){const e=process.execve;if(e===void 0)throw new Error(`this Node.js ${process.version} runtime cannot replace PID 1 with the successor daemon`);const t=I(),r=await g();return e(t,[t,...r,"--canvas-home",S()],y())}o(Qe,"execDaemon");async function P(e){const t=await g(),r=K(I(),[...t,...e],{stdio:["ignore","pipe","pipe"],env:y()});let n="",a="";r.stdout.setEncoding("utf8").on("data",c=>{n+=c}),r.stderr.setEncoding("utf8").on("data",c=>{a+=c});const s=await new Promise((c,d)=>{r.once("error",d),r.once("close",f=>c(f))});if(s!==0)throw new Error(a.trim()||`the ${e[0]} process exited with code ${s}`);const u=n.trim().split(`
2
+ `).at(-1)??"";return JSON.parse(u)}o(P,"runDaemonEntry");function Ze(e,t){return P(["import-dump",e,t])}o(Ze,"runDaemonImportDump");function et(e){return P(["import-dump",e,"bodies"])}o(et,"runDaemonBodiesDump");function tt(){return P(["import-dump","","install-id"])}o(tt,"runDaemonInstallId");const j=2e4,L=10,v=1e3;async function b(e=v){const t=Math.min(e,v);return pe({autostart:!1,timeoutMs:t}).probeHealthz(t)}o(b,"probeDaemonHealth");function Se(e){const t=e instanceof Error?e.message:String(e);if(typeof e!="object"||e===null)return t;const r=e.code,n=e.cause,a=typeof r=="string"?r:n?.code;return typeof a=="string"&&!t.includes(a)?`${t}: ${a}`:t}o(Se,"probeErrorMessage");async function X(e=v){const t=await b(e);if(t.startup_phase==="blocked"){const r=w()??process.pid;throw new C(r,t.startup_blocked??"daemon startup is blocked")}if(!t.ok)throw new Error(t.startup_blocked??"crtrd health check reported not ready")}o(X,"probeDaemonServing");async function rt(){try{return await X(),!0}catch{return!1}}o(rt,"isDaemonServing");function U(e){return new Promise(t=>{setTimeout(t,e)})}o(U,"sleepMs");class k extends Error{static{o(this,"DaemonExitedBeforeReadyError")}stderrTail;constructor(t,r){super(r===""?t:`${t}
3
+ ${r}`),this.name="DaemonExitedBeforeReadyError",this.stderrTail=r}}class Y extends Error{static{o(this,"DaemonLaunchError")}constructor(t){super(t instanceof Error?t.message:String(t),{cause:t}),this.name="DaemonLaunchError"}}class C extends Error{static{o(this,"DaemonStartupBlockedError")}constructor(t,r){super(`daemon ${t} is running but normal startup is blocked: ${r}`),this.name="DaemonStartupBlockedError"}}class B extends Error{static{o(this,"DaemonNotPreparedError")}constructor(t,r){super(r===void 0?`daemon ${t} is serving but did not report the prepared startup phase`:`daemon ${t} reported startup phase ${r}, not prepared`),this.name="DaemonNotPreparedError"}}async function Ae(e,t=V,r={},n="ready"){const a=r.readPidfile??w,s=r.isPidAlive??R,u=r.childExited,c=r.isDaemonServing,d=r.probeDaemonServing??(async h=>{if(c!==void 0){if(await c())return;throw new Error("crtrd health check reported not ready")}await X(h)}),f=r.probeDaemonHealth??b,D=r.sleepMs??U,i=r.now??Date.now;let p=null,l=null;return await de({windowMs:t,pollIntervalMs:L,now:i,sleep:D,retry:o(h=>h!==l,"retry"),probe:o(async h=>{const m=a();if(m===null||!s(m)){const _=u?.();throw _!=null&&(_.signal!==null?l=new k(`daemon ${e} exited before becoming ready (by ${_.signal})`,r.childStderrTail?.()??""):_.code!==0&&(l=new k(`daemon ${e} exited before becoming ready (with exit code ${_.code??"?"})`,r.childStderrTail?.()??"")),l!==null)?l:new Error(`daemon ${e} has no live pidfile owner`)}if(n==="ready"){try{await d(h)}catch(_){throw _ instanceof C&&(l=_),_}p=m;return}const E=await f(h);if(E.startup_phase==="prepared"){p=m;return}throw E.startup_phase==="blocked"?(l=new C(m,E.startup_blocked??"on-disk migration is blocked"),l):E.startup_phase==="ready"?(l=new B(m,E.startup_phase),l):new Error(`daemon ${m} is ${E.startup_phase??"not reporting a startup phase"}; waiting for prepared`)},"probe")}),p===e?null:p}o(Ae,"verifyDaemonStartup");async function Ce(e,t=j,r={}){const n=r.readPidfile??w,a=r.isPidAlive??R,s=r.sleepMs??U,u=r.now??Date.now,c=u()+t;for(;u()<=c;){if(!a(e)&&n()!==e)return;await s(L)}throw new Error(`daemon ${e} did not exit and release its pidfile within ${t}ms`)}o(Ce,"waitForDaemonExit");const Oe=2e3,Me=5e3;async function z(e,t=j,r={}){const n=r.isPidAlive??R,a=r.sleepMs??U,s=r.now??Date.now;try{process.kill(e,"SIGTERM")}catch{}try{return await Ce(e,t,r),"terminated"}catch{}try{process.kill(e,"SIGKILL")}catch{}const u=s()+Oe;for(;s()<=u;){if(!n(e))return"killed";await a(L)}throw new Error(`daemon ${e} survived both SIGTERM and SIGKILL`)}o(z,"stopDaemonProcess");async function nt(){const e=w(),t=e!==null&&R(e),r=t&&await z(e)==="killed",n=De(null);return{stopped:t||n.length>0,...t?{pid:e}:{},strays_killed:n,force_killed:r}}o(nt,"stopAllDaemons");function xe(e,t,r=2048){let n;try{n=H(e,"r");const{size:a}=W(n),s=Math.max(t,a-r),u=a-s;if(u<=0)return"";const c=Buffer.alloc(u);return re(n,c,0,u,s),c.toString("utf8").trim()}catch{return""}finally{if(n!==void 0)try{G(n)}catch{}}}o(xe,"readLogTailFrom");async function Ne(e={}){if(process.platform==="linux"&&F("/run/crtr/launcher.sock")&&!R(w()??-1)&&ce()===void 0)throw new Error("crtrd is managed by the root launcher; it cannot self-daemonize");const t=e.targetPhase??"ready",r=w();if(r!==null&&R(r))try{const i=await b();if(t==="prepared"){if(i.startup_phase==="prepared")return{started:!1,existing_pid:r,startup_phase:i.startup_phase};throw new B(r,i.startup_phase)}return i.ok?{started:!1,existing_pid:r,...i.startup_phase===void 0?{}:{startup_phase:i.startup_phase}}:{started:!1,existing_pid:r,running:!0,serving:!1,probe_error:i.startup_blocked??"crtrd health check reported not ready",...i.startup_phase===void 0?{}:{startup_phase:i.startup_phase}}}catch(i){if(i instanceof B)throw i;return{started:!1,existing_pid:r,running:!0,serving:!1,probe_error:Se(i)}}te(S(),{recursive:!0});const n=await g().catch(i=>{throw new Y(i)}),a=T(S(),"crtrd.err"),s=H(a,"a"),u=(()=>{try{return W(s).size}catch{return 0}})();ae()===void 0&&oe();const c=K(I(),[...n,"--canvas-home",S(),...t==="prepared"?["--prepare"]:[]],{detached:!0,stdio:["ignore",s,s],env:y()});G(s);const d=c.pid;if(d===void 0)throw new Error("daemon spawn did not return a pid");let f=null;c.once("exit",(i,p)=>{f={code:i,signal:p}}),c.unref();let D;try{D=await Ae(d,V,{childExited:o(()=>f,"childExited"),childStderrTail:o(()=>xe(a,u),"childStderrTail")},t)}catch(i){const p=ue(le())===d;if(f===null&&!p&&!(i instanceof C))try{await z(d,Me)}catch{}throw i}return D!==null?{started:!1,existing_pid:D,startup_phase:t}:{started:!0,pid:d,startup_phase:t}}o(Ne,"spawnDaemon");function Ie(){return _e()||process.argv.includes("--no-autostart")}o(Ie,"autostartDisabled");const ye=5e3,ge=6e4;let $=!1,A,O=0,M=0;function Pe(e){return Math.min(ye*2**(e-1),ge)}o(Pe,"autostartBackoffMs");function Le(){A=void 0,O=0,M=0}o(Le,"resetDaemonAutostart");function ot(){return A}o(ot,"daemonAutostartStartupFailure");function at(e={}){const t=e.isDaemonRunning??ie,r=e.spawnDaemon??Ne,n=e.now??Date.now;if(!Ie()&&!(!e.spawnDaemon&&se())&&!$&&!(n()<M)){if(t()){Le();return}A=void 0,$=!0,r().then(()=>{A=void 0,O=0,M=0},a=>{(a instanceof k||a instanceof Y)&&(A=a.message),O+=1,M=n()+Pe(O)}).finally(()=>{$=!1})}}o(at,"ensureDaemon");export{Re as DAEMON_ENV_STRIP_KEYS,k as DaemonExitedBeforeReadyError,Y as DaemonLaunchError,B as DaemonNotPreparedError,C as DaemonStartupBlockedError,Ie as autostartDisabled,ot as daemonAutostartStartupFailure,Te as daemonCommandDeclaresCanvasHome,he as daemonKeepsEnv,at as ensureDaemon,Qe as execDaemon,we as findDaemonPids,rt as isDaemonServing,b as probeDaemonHealth,X as probeDaemonServing,Se as probeErrorMessage,Le as resetDaemonAutostart,et as runDaemonBodiesDump,Ze as runDaemonImportDump,tt as runDaemonInstallId,y as sanitizedDaemonEnv,Ne as spawnDaemon,nt as stopAllDaemons,z as stopDaemonProcess,De as sweepStrayDaemons,Ae as verifyDaemonStartup,Ce as waitForDaemonExit};
@@ -1,2 +1,2 @@
1
- var h=Object.defineProperty;var a=(e,t)=>h(e,"name",{value:t,configurable:!0});import{liveExecutionForNode as _,endExecution as f,recordExecutionAwake as v,endLaunchingExecution as m,requestExecutionStop as x}from"../../../core/canvas/executions.js";import{openDb as E}from"../../../core/canvas/db.js";import{isCloudRole as g}from"../../../core/canvas/person-state.js";import{getRow as b,recordRespawnAttempt as k}from"../../../core/canvas/index.js";import{fullName as y}from"../../../core/canvas/labels.js";import{publishNotice as $}from"../../../core/runtime/close.js";import{emitEvent as i}from"../../../core/events/emit.js";import{findRefusal as A,refusalError as R,refusedMark as L,writeCharge as N}from"../../../core/ledger/index.js";import{transition as w}from"../../../core/runtime/lifecycle.js";import{runnerForExecution as u}from"../../../core/runtime/runner/index.js";import{machineEnvironmentOfProfile as S}from"../../../core/runtime/runner/machine/environment.js";import{startCandidateOf as D}from"../../../core/runtime/start-check.js";import{settleSandboxBeforeWake as I}from"../ledger-sandbox.js";import{crtrVersion as C}from"../../../shared/crtr-version.js";import{resolveEnvironmentImage as O}from"../recipe-image.js";import{recordRespawnPolicy as T}from"./respawn-policy.js";import{recordLaunchFailure as P}from"./launch-failure.js";const U=45*6e4,W=12e4,F=a(()=>C(),"acceptedRelease");async function ae(e){return e===null||!g()?null:await S(e)}a(ae,"remoteMachineEnvironmentOf");async function oe(e){const t=await D(e);if(t===null)return;const r={scope:"call",payer:t.payer,funding:"bill",sub:t.sub,grantee:t.grantee,provider:"blaxel"},n=await A(r),s=await E();if(n===null){await s.prepare("UPDATE nodes SET spend_refusal = NULL WHERE node_id = ? AND spend_refusal IS NOT NULL").run(e.node_id);return}throw await s.prepare("UPDATE nodes SET spend_refusal = ? WHERE node_id = ?").run(JSON.stringify({limit:n.limit.id,usd:n.usd,reset_at:n.reset_at,at:new Date().toISOString()}),e.node_id),await N({id:`refused:sandbox:${e.node_id}:${n.limit.id}:${n.month}`,kind:"sandbox",what:"wake",usd:null,payer:r.payer,funding:"bill",sub:r.sub,grantee:r.grantee,node:e.node_id,run:e.run_id??null,provider:"blaxel",refused:L(n)}),R(n)}a(oe,"checkBilledWake");class ie extends Error{static{a(this,"EnvironmentImagePending")}environmentId;imageError;constructor(t,r){super(`environment ${t} has no built image yet${r===null?"":` (${r})`}; the wake waits for the build.`),this.environmentId=t,this.imageError=r,this.name="EnvironmentImagePending"}}async function se(e){return await O(e)}a(se,"imageForWake");async function le(e){if(e.release!==F()){if(await x(e.nodeId,{afterTurn:!1,reason:"release"}),e.stopRequestedAt!==null)return"lost";const t=await u(e.runner).stop(e,{reason:"release"});return t.confirmed?(await f(e.executionId,{reason:"release"}),"lost"):(i({level:"error",event:"broker.teardown.unconfirmed",node_id:e.nodeId,error:t.error}),"lost")}return await u(e.runner).wake(e)==="no_broker"?(await f(e.executionId,{reason:"lost"}),"lost"):(await I(e.executionId,Date.now()),await v(e.executionId),"woken")}a(le,"wakeResident");async function ue(e){const t=await u(e.runner).status(e,{idle:e.idleAt!==null});if(t.state!=="gone"&&t.state!=="failed")return!1;const r=await f(e.executionId,{reason:"lost"});return r&&i({level:"warn",event:"execution.lost",node_id:e.nodeId}),r}a(ue,"endRemoteExecutionIfGone");async function de(e,t){const r=await _(e);if(r===null||r.state!=="launching"||r.runner==="process")return!1;const n=u(r.runner),s=t-Date.parse(r.startedAt),o=await n.status(r);if(o.state==="unknown")return!1;if(o.state==="running")return s<=U||!await m(r.executionId,{reason:"launch_timeout"})?!1:(await n.stop(r,{reason:"launch_timeout"}),await w(e,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:"the sandbox launch did not report within the launch deadline"}}}),i({level:"warn",event:"execution.launch_timeout",node_id:e}),!0);if(o.state==="failed"){if(!await m(r.executionId,{reason:"launch_failed"}))return!1;const d=`the sandbox start script failed: ${o.reason}`;await P(r.executionId,new Error(o.output===void 0?d:`${d}
2
- ${o.output}`));const c=await b(e);if(c!==null){const l=await T(c,t);if(!l.exhausted)i({level:"warn",event:"execution.launch_failed",node_id:e,fields:{reason:o.reason,consecutive_failures:l.failures}});else{const p=`Child crashed \u2014 ${y(c)} (${e}) failed ${l.failures} consecutive sandbox launches (${d}) and is now dead. It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`;await k(e,{failures:l.failures,notBefore:null}),i({level:"error",event:"broker.respawn.exhausted",node_id:e}),await w(e,"crash",{reason:"crash_looped",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:p,respawn_failures:l.failures}}}),await $(e,"notice.crash",p,{reason:"child-crashed",child:e})}}return await n.delete(r.nodeId),!0}if(s>W){if(!await m(r.executionId,{reason:"launch_lost"}))return!1;i({level:"warn",event:"execution.launch_lost",node_id:e})}return!1}a(de,"recoverLaunching");export{ie as EnvironmentImagePending,U as LAUNCH_DEADLINE_MS,W as LAUNCH_LOST_GRACE_MS,F as acceptedRelease,oe as checkBilledWake,ue as endRemoteExecutionIfGone,se as imageForWake,de as recoverLaunching,ae as remoteMachineEnvironmentOf,le as wakeResident};
1
+ var h=Object.defineProperty;var a=(e,t)=>h(e,"name",{value:t,configurable:!0});import{liveExecutionForNode as _,endExecution as f,recordExecutionAwake as v,endLaunchingExecution as m,requestExecutionStop as E}from"../../../core/canvas/executions.js";import{openDb as g}from"../../../core/canvas/db.js";import{areEnginesInProcess as x,isCloudRole as b}from"../../../core/canvas/person-state.js";import{getRow as k,recordRespawnAttempt as y}from"../../../core/canvas/index.js";import{fullName as $}from"../../../core/canvas/labels.js";import{publishNotice as A}from"../../../core/runtime/close.js";import{emitEvent as i}from"../../../core/events/emit.js";import{findRefusal as R,refusalError as L,refusedMark as N,writeCharge as S}from"../../../core/ledger/index.js";import{transition as w}from"../../../core/runtime/lifecycle.js";import{runnerForExecution as u}from"../../../core/runtime/runner/index.js";import{machineEnvironmentOfProfile as I}from"../../../core/runtime/runner/machine/environment.js";import{startCandidateOf as D}from"../../../core/runtime/start-check.js";import{settleSandboxBeforeWake as C}from"../ledger-sandbox.js";import{crtrVersion as O}from"../../../shared/crtr-version.js";import{resolveEnvironmentImage as P}from"../recipe-image.js";import{recordRespawnPolicy as T}from"./respawn-policy.js";import{recordLaunchFailure as U}from"./launch-failure.js";const W=45*6e4,F=12e4,H=a(()=>O(),"acceptedRelease");async function oe(e){return e===null||!b()||x()?null:await I(e)}a(oe,"remoteMachineEnvironmentOf");async function ie(e){const t=await D(e);if(t===null)return;const r={scope:"call",payer:t.payer,funding:"bill",sub:t.sub,grantee:t.grantee,provider:"blaxel"},n=await R(r),s=await g();if(n===null){await s.prepare("UPDATE nodes SET spend_refusal = NULL WHERE node_id = ? AND spend_refusal IS NOT NULL").run(e.node_id);return}throw await s.prepare("UPDATE nodes SET spend_refusal = ? WHERE node_id = ?").run(JSON.stringify({limit:n.limit.id,usd:n.usd,reset_at:n.reset_at,at:new Date().toISOString()}),e.node_id),await S({id:`refused:sandbox:${e.node_id}:${n.limit.id}:${n.month}`,kind:"sandbox",what:"wake",usd:null,payer:r.payer,funding:"bill",sub:r.sub,grantee:r.grantee,node:e.node_id,run:e.run_id??null,provider:"blaxel",refused:N(n)}),L(n)}a(ie,"checkBilledWake");class se extends Error{static{a(this,"EnvironmentImagePending")}environmentId;imageError;constructor(t,r){super(`environment ${t} has no built image yet${r===null?"":` (${r})`}; the wake waits for the build.`),this.environmentId=t,this.imageError=r,this.name="EnvironmentImagePending"}}async function le(e){return await P(e)}a(le,"imageForWake");async function ue(e){if(e.release!==H()){if(await E(e.nodeId,{afterTurn:!1,reason:"release"}),e.stopRequestedAt!==null)return"lost";const t=await u(e.runner).stop(e,{reason:"release"});return t.confirmed?(await f(e.executionId,{reason:"release"}),"lost"):(i({level:"error",event:"broker.teardown.unconfirmed",node_id:e.nodeId,error:t.error}),"lost")}return await u(e.runner).wake(e)==="no_broker"?(await f(e.executionId,{reason:"lost"}),"lost"):(await C(e.executionId,Date.now()),await v(e.executionId),"woken")}a(ue,"wakeResident");async function de(e){const t=await u(e.runner).status(e,{idle:e.idleAt!==null});if(t.state!=="gone"&&t.state!=="failed")return!1;const r=await f(e.executionId,{reason:"lost"});return r&&i({level:"warn",event:"execution.lost",node_id:e.nodeId}),r}a(de,"endRemoteExecutionIfGone");async function ce(e,t){const r=await _(e);if(r===null||r.state!=="launching"||r.runner==="process")return!1;const n=u(r.runner),s=t-Date.parse(r.startedAt),o=await n.status(r);if(o.state==="unknown")return!1;if(o.state==="running")return s<=W||!await m(r.executionId,{reason:"launch_timeout"})?!1:(await n.stop(r,{reason:"launch_timeout"}),await w(e,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:"the sandbox launch did not report within the launch deadline"}}}),i({level:"warn",event:"execution.launch_timeout",node_id:e}),!0);if(o.state==="failed"){if(!await m(r.executionId,{reason:"launch_failed"}))return!1;const d=`the sandbox start script failed: ${o.reason}`;await U(r.executionId,new Error(o.output===void 0?d:`${d}
2
+ ${o.output}`));const c=await k(e);if(c!==null){const l=await T(c,t);if(!l.exhausted)i({level:"warn",event:"execution.launch_failed",node_id:e,fields:{reason:o.reason,consecutive_failures:l.failures}});else{const p=`Child crashed \u2014 ${$(c)} (${e}) failed ${l.failures} consecutive sandbox launches (${d}) and is now dead. It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`;await y(e,{failures:l.failures,notBefore:null}),i({level:"error",event:"broker.respawn.exhausted",node_id:e}),await w(e,"crash",{reason:"crash_looped",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:p,respawn_failures:l.failures}}}),await A(e,"notice.crash",p,{reason:"child-crashed",child:e})}}return await n.delete(r.nodeId),!0}if(s>F){if(!await m(r.executionId,{reason:"launch_lost"}))return!1;i({level:"warn",event:"execution.launch_lost",node_id:e})}return!1}a(ce,"recoverLaunching");export{se as EnvironmentImagePending,W as LAUNCH_DEADLINE_MS,F as LAUNCH_LOST_GRACE_MS,H as acceptedRelease,ie as checkBilledWake,de as endRemoteExecutionIfGone,le as imageForWake,ce as recoverLaunching,oe as remoteMachineEnvironmentOf,ue as wakeResident};
@@ -53,8 +53,6 @@ export declare class StorageMaintenanceReconciler {
53
53
  /** Delete expired `viewer_attachments` rows. A viewer that never detached cleanly (its API process died) leaves its
54
54
  * row behind; readers already ignore it by `expires_at`, so this only bounds the table. */
55
55
  private gcViewerAttachments;
56
- /** Stamp the machine environment as seen. A failed stamp is an event, never an error out of the tick. */
57
- private touchEnvironment;
58
56
  /** Collect dead or expired hidden warm-pool spares. */
59
57
  private gcWarmPool;
60
58
  }
@@ -1 +1 @@
1
- var I=Object.defineProperty;var p=(w,e)=>I(w,"name",{value:e,configurable:!0});import{rm as A}from"node:fs/promises";import{closeFocusRow as N,getFocusById as T,listFocuses as P,listNodes as C}from"../../core/canvas/index.js";import{pruneExpiredIdempotencyKeys as D}from"../../core/runs/operations.js";import{getNode as y,lastActivityMs as h,listTerminalPlacementResidue as x,pruneExpiredCreateRequests as F,pruneNodes as M}from"../../core/canvas/canvas.js";import{lastContextStripMs as b,stripContextDir as L}from"../../core/canvas/context-strip.js";import{isAppRun as W}from"../../core/canvas/app-run.js";import{isSafeNodeId as l}from"../../core/canvas/paths.js";import{emitEvent as a}from"../../core/events/emit.js";import{operationIdContext as s}from"../../core/events/operation-id.js";import{listLivePanesAsync as G,tearDownNode as V}from"../../core/runtime/placement.js";import{reapStaleSpares as k}from"../../core/runtime/warm-pool.js";import{GroveInstanceSweepReconciler as q}from"./grove-instance-sweep.js";import{ManagedWorktreeSweepReconciler as O}from"./managed-worktree-sweep.js";import{compactRunEvents as U}from"../../core/runs/events.js";import{archiveExpiredRunEvents as H}from"../../core/events/run-event-chunks.js";import{blobStore as Y}from"../../core/blobs/index.js";import{runThrottledLane as d}from"./throttled-lane.js";import{openDb as g}from"../../core/canvas/db.js";import{touchMachineEnvironment as z}from"../../core/environments.js";import{retentionHold as m}from"./live-obligation.js";import{deleteQuietNodeSandboxes as B}from"../../core/runtime/runner/delete-sandboxes.js";import{pruneMemoryReads as K}from"../../core/canvas/memory-reads.js";import{existsSync as Q}from"node:fs";import{launcherRequest as $}from"../../launcher/client.js";import{LAUNCHER_SOCKET as X}from"../../launcher/spec.js";import{cachePassDue as Z}from"../../launcher/limits/policy.js";const j=10*6e4,u=60*1e3,E=60*1e3,v=5*6e4,S=2,J=1440*6e4,ee=2e3,te=6e4;class Ce{static{p(this,"StorageMaintenanceReconciler")}focusGcInFlight=!1;lastCachePassAt=null;cachePassInFlight=!1;worktreeSweep=new O;groveInstanceSweep=new q;async run(e,t){await this.reapDeadResidue(e,t.held),this.scheduleFocusGc(t),await this.gcWarmPool(e),await this.touchEnvironment(e),await this.gcCreateRequests(e),await this.gcViewerAttachments(e);try{await d("run-event-maintenance","",e,ee,te,async r=>{await H(await Y(),e);const n=await U(e,r.state===null?0:Number(r.state));await r.save(String(n.cursor))})}catch(r){console.warn(`run event maintenance failed: ${String(r)}`)}await d("memory-read-prune","",e,60*6e4,10*6e4,async()=>{try{await K(e)}catch(r){console.warn(`memory-read log prune failed: ${String(r)}`)}}),await d("storage-analyze","",e,1440*6e4,10*6e4,async()=>{await(await g()).exec("ANALYZE")}),await this.sweepRetention(e,t),this.scheduleCachePass(e,t),this.scheduleContextStrip(e,t),this.worktreeSweep.run(e,t),this.groveInstanceSweep.run(e,t)}scheduleCachePass(e,t){this.cachePassInFlight||!Z(this.lastCachePassAt,e)||process.platform!=="linux"||!Q(X)||t.lifecycle.acceptsDetachedWork()&&(this.lastCachePassAt=e,this.cachePassInFlight=!0,t.lifecycle.registerDetached($({operation:"cache.purge"}).then(()=>{}).catch(r=>{s.fresh(()=>{a({level:"warn",event:"app.cache.pass_failed",error:r})})}).then(()=>{this.cachePassInFlight=!1})))}msSinceTerminalActivity(e,t){const r=h(e);return r===0?Number.POSITIVE_INFINITY:t-r}async sweepRetention(e,t){t.lifecycle.acceptsDetachedWork()&&await d("retention-sweep","",e,v,v,()=>s.fresh(async()=>{try{const r=await M({ttlDays:S,held:await m(t.fleet),removeDirs:p(i=>{t.lifecycle.registerDetached(Promise.all(i.map(c=>A(c,{recursive:!0,force:!0}))).then(()=>{}).catch(c=>{s.fresh(()=>{a({level:"error",event:"canvas.retention.failed",error:c})})}))},"removeDirs")});r.pruned.length>0&&a({level:"info",event:"canvas.retention.pruned",outcome:"succeeded",fields:{pruned_count:r.pruned.length}});const n=await m(t.fleet),o=e-S*24*60*6e4,f=await B({now:e,held:n,quiet:p(async i=>{const c=await y(i);return c!==null&&h(c)<o},"quiet")});f>0&&a({level:"info",event:"canvas.retention.sandboxes_deleted",outcome:"succeeded",fields:{deleted_count:f}})}catch(r){a({level:"error",event:"canvas.retention.failed",error:r})}}))}scheduleContextStrip(e,t){t.lifecycle.acceptsDetachedWork()&&t.lifecycle.registerDetached(d("context-strip","",e,v,10*6e4,()=>this.stripFinishedContexts(e,t)).then(()=>{},r=>{a({level:"error",event:"canvas.context_strip.failed",error:r})}))}async stripFinishedContexts(e,t){const r=await m(t.fleet),n=p(async i=>i!==null&&["done","canceled","dead"].includes(i.status)&&(i.pi_pid??null)===null&&(i.frozen_at??null)===null&&!W(i)&&h(i)<e-J&&!await r(i.node_id),"eligible");let o=0,f=0;try{for(const i of await C({status:["done","canceled","dead"]})){if(!l(i.node_id)||!await n(i))continue;const c=await b(i.node_id);if(c!==null&&c>=h(i)||!await n(await y(i.node_id)))continue;let _;try{_=await L(i.node_id)}catch(R){s.fresh(()=>{a({level:"warn",event:"canvas.context_strip.node_failed",error:R,fields:{node_id:i.node_id}})});continue}_.removed.length>0&&(o+=1,f+=_.bytes)}}catch(i){s.fresh(()=>{a({level:"error",event:"canvas.context_strip.failed",error:i})})}o>0&&s.fresh(()=>{a({level:"info",event:"canvas.context_strip.completed",outcome:"succeeded",fields:{node_count:o,bytes:f}})})}async reapDeadResidue(e,t){let r;try{r=await x()}catch(n){s.fresh(()=>{a({level:"error",event:"residue.reap_scan.failed",error:n})});return}for(const n of r)if(!t.has(n.node_id)){try{if(this.msSinceTerminalActivity(n,e)<j)continue}catch(o){s.fresh(()=>{a({level:"error",event:"residue.reap.failed",...l(n.node_id)?{node_id:n.node_id}:{},error:o,fields:{...l(n.node_id)?{}:{affected_node_id:n.node_id},pane:n.pane,window:n.window,tmux_session:n.tmux_session}})});continue}await s.fresh(async()=>{try{a({level:"info",event:"residue.reaped",...l(n.node_id)?{node_id:n.node_id}:{},fields:{...l(n.node_id)?{}:{affected_node_id:n.node_id},pane:n.pane,window:n.window,tmux_session:n.tmux_session}}),await V(n.node_id)}catch(o){a({level:"error",event:"residue.reap.failed",...l(n.node_id)?{node_id:n.node_id}:{},error:o,fields:{...l(n.node_id)?{}:{affected_node_id:n.node_id},pane:n.pane,window:n.window,tmux_session:n.tmux_session}})}})}}scheduleFocusGc(e){if(this.focusGcInFlight||!e.lifecycle.acceptsDetachedWork())return;this.focusGcInFlight=!0;const t=this.gcStaleFocuses().finally(()=>{this.focusGcInFlight=!1});e.lifecycle.registerDetached(t)}async gcStaleFocuses(){let e;try{e=await P()}catch(r){s.fresh(()=>{a({level:"error",event:"focus.gc.failed",error:r})});return}if(e.length===0)return;let t;try{t=await G()}catch(r){s.fresh(()=>{a({level:"error",event:"focus.gc.failed",error:r})});return}if(t!==null)for(const r of e){if(r.pane===null||t.has(r.pane))continue;if(!await s.fresh(async()=>{try{return(await T(r.focus_id))?.pane!==r.pane||(a({level:"info",event:"focus.gc.removed",...l(r.node_id)?{node_id:r.node_id}:{},fields:{focus_id:r.focus_id,focus_node_id:r.node_id,pane:r.pane}}),await N(r.focus_id)),!0}catch(o){return a({level:"error",event:"focus.gc.failed",error:o}),!1}}))return}}async gcCreateRequests(e){await d("create-request-gc","",e,E,E,()=>s.fresh(async()=>{const t=await F(e),r=await D(e);r>0&&a({level:"info",event:"canvas.idempotency_keys.reaped",outcome:"succeeded",fields:{reaped_count:r}}),t>0&&a({level:"info",event:"canvas.create_requests.reaped",outcome:"succeeded",fields:{reaped_count:t}})}))}async gcViewerAttachments(e){await d("viewer-attachment-gc","",e,u,u,()=>s.fresh(async()=>{const t=Number((await(await g()).prepare("DELETE FROM viewer_attachments WHERE expires_at <= ?").run(new Date(e).toISOString())).changes);t>0&&a({level:"info",event:"viewer_attachments.reaped",outcome:"succeeded",fields:{reaped_count:t}})}))}async touchEnvironment(e){await d("environment-touch","",e,u,u,()=>s.fresh(async()=>{try{await z(new Date(e).toISOString())}catch(t){a({level:"warn",event:"environment.touch.failed",error:t})}}))}async gcWarmPool(e){await d("warm-pool-gc","",e,u,u,()=>s.fresh(async()=>{const t=await k();t.length>0&&a({level:"info",event:"warm_pool.spares_reaped",outcome:"succeeded",fields:{reaped_count:t.length}})}))}}export{J as CONTEXT_STRIP_GRACE_MS,j as DEAD_REAP_GRACE_MS,v as RETENTION_SWEEP_INTERVAL_MS,S as RETENTION_TTL_DAYS,Ce as StorageMaintenanceReconciler};
1
+ var I=Object.defineProperty;var u=(w,e)=>I(w,"name",{value:e,configurable:!0});import{rm as A}from"node:fs/promises";import{closeFocusRow as N,getFocusById as T,listFocuses as P,listNodes as C}from"../../core/canvas/index.js";import{pruneExpiredIdempotencyKeys as D}from"../../core/runs/operations.js";import{getNode as y,lastActivityMs as p,listTerminalPlacementResidue as x,pruneExpiredCreateRequests as F,pruneNodes as M}from"../../core/canvas/canvas.js";import{lastContextStripMs as b,stripContextDir as L}from"../../core/canvas/context-strip.js";import{isAppRun as W}from"../../core/canvas/app-run.js";import{isSafeNodeId as d}from"../../core/canvas/paths.js";import{emitEvent as i}from"../../core/events/emit.js";import{operationIdContext as s}from"../../core/events/operation-id.js";import{listLivePanesAsync as G,tearDownNode as V}from"../../core/runtime/placement.js";import{reapStaleSpares as k}from"../../core/runtime/warm-pool.js";import{GroveInstanceSweepReconciler as q}from"./grove-instance-sweep.js";import{ManagedWorktreeSweepReconciler as O}from"./managed-worktree-sweep.js";import{compactRunEvents as U}from"../../core/runs/events.js";import{archiveExpiredRunEvents as H}from"../../core/events/run-event-chunks.js";import{blobStore as Y}from"../../core/blobs/index.js";import{runThrottledLane as l}from"./throttled-lane.js";import{openDb as g}from"../../core/canvas/db.js";import{retentionHold as m}from"./live-obligation.js";import{deleteQuietNodeSandboxes as z}from"../../core/runtime/runner/delete-sandboxes.js";import{pruneMemoryReads as B}from"../../core/canvas/memory-reads.js";import{existsSync as K}from"node:fs";import{launcherRequest as Q}from"../../launcher/client.js";import{LAUNCHER_SOCKET as $}from"../../launcher/spec.js";import{cachePassDue as X}from"../../launcher/limits/policy.js";const Z=10*6e4,h=60*1e3,S=60*1e3,v=5*6e4,E=2,j=1440*6e4,J=2e3,ee=6e4;class Te{static{u(this,"StorageMaintenanceReconciler")}focusGcInFlight=!1;lastCachePassAt=null;cachePassInFlight=!1;worktreeSweep=new O;groveInstanceSweep=new q;async run(e,r){await this.reapDeadResidue(e,r.held),this.scheduleFocusGc(r),await this.gcWarmPool(e),await this.gcCreateRequests(e),await this.gcViewerAttachments(e);try{await l("run-event-maintenance","",e,J,ee,async t=>{await H(await Y(),e);const n=await U(e,t.state===null?0:Number(t.state));await t.save(String(n.cursor))})}catch(t){console.warn(`run event maintenance failed: ${String(t)}`)}await l("memory-read-prune","",e,60*6e4,10*6e4,async()=>{try{await B(e)}catch(t){console.warn(`memory-read log prune failed: ${String(t)}`)}}),await l("storage-analyze","",e,1440*6e4,10*6e4,async()=>{await(await g()).exec("ANALYZE")}),await this.sweepRetention(e,r),this.scheduleCachePass(e,r),this.scheduleContextStrip(e,r),this.worktreeSweep.run(e,r),this.groveInstanceSweep.run(e,r)}scheduleCachePass(e,r){this.cachePassInFlight||!X(this.lastCachePassAt,e)||process.platform!=="linux"||!K($)||r.lifecycle.acceptsDetachedWork()&&(this.lastCachePassAt=e,this.cachePassInFlight=!0,r.lifecycle.registerDetached(Q({operation:"cache.purge"}).then(()=>{}).catch(t=>{s.fresh(()=>{i({level:"warn",event:"app.cache.pass_failed",error:t})})}).then(()=>{this.cachePassInFlight=!1})))}msSinceTerminalActivity(e,r){const t=p(e);return t===0?Number.POSITIVE_INFINITY:r-t}async sweepRetention(e,r){r.lifecycle.acceptsDetachedWork()&&await l("retention-sweep","",e,v,v,()=>s.fresh(async()=>{try{const t=await M({ttlDays:E,held:await m(r.fleet),removeDirs:u(a=>{r.lifecycle.registerDetached(Promise.all(a.map(c=>A(c,{recursive:!0,force:!0}))).then(()=>{}).catch(c=>{s.fresh(()=>{i({level:"error",event:"canvas.retention.failed",error:c})})}))},"removeDirs")});t.pruned.length>0&&i({level:"info",event:"canvas.retention.pruned",outcome:"succeeded",fields:{pruned_count:t.pruned.length}});const n=await m(r.fleet),o=e-E*24*60*6e4,f=await z({now:e,held:n,quiet:u(async a=>{const c=await y(a);return c!==null&&p(c)<o},"quiet")});f>0&&i({level:"info",event:"canvas.retention.sandboxes_deleted",outcome:"succeeded",fields:{deleted_count:f}})}catch(t){i({level:"error",event:"canvas.retention.failed",error:t})}}))}scheduleContextStrip(e,r){r.lifecycle.acceptsDetachedWork()&&r.lifecycle.registerDetached(l("context-strip","",e,v,10*6e4,()=>this.stripFinishedContexts(e,r)).then(()=>{},t=>{i({level:"error",event:"canvas.context_strip.failed",error:t})}))}async stripFinishedContexts(e,r){const t=await m(r.fleet),n=u(async a=>a!==null&&["done","canceled","dead"].includes(a.status)&&(a.pi_pid??null)===null&&(a.frozen_at??null)===null&&!W(a)&&p(a)<e-j&&!await t(a.node_id),"eligible");let o=0,f=0;try{for(const a of await C({status:["done","canceled","dead"]})){if(!d(a.node_id)||!await n(a))continue;const c=await b(a.node_id);if(c!==null&&c>=p(a)||!await n(await y(a.node_id)))continue;let _;try{_=await L(a.node_id)}catch(R){s.fresh(()=>{i({level:"warn",event:"canvas.context_strip.node_failed",error:R,fields:{node_id:a.node_id}})});continue}_.removed.length>0&&(o+=1,f+=_.bytes)}}catch(a){s.fresh(()=>{i({level:"error",event:"canvas.context_strip.failed",error:a})})}o>0&&s.fresh(()=>{i({level:"info",event:"canvas.context_strip.completed",outcome:"succeeded",fields:{node_count:o,bytes:f}})})}async reapDeadResidue(e,r){let t;try{t=await x()}catch(n){s.fresh(()=>{i({level:"error",event:"residue.reap_scan.failed",error:n})});return}for(const n of t)if(!r.has(n.node_id)){try{if(this.msSinceTerminalActivity(n,e)<Z)continue}catch(o){s.fresh(()=>{i({level:"error",event:"residue.reap.failed",...d(n.node_id)?{node_id:n.node_id}:{},error:o,fields:{...d(n.node_id)?{}:{affected_node_id:n.node_id},pane:n.pane,window:n.window,tmux_session:n.tmux_session}})});continue}await s.fresh(async()=>{try{i({level:"info",event:"residue.reaped",...d(n.node_id)?{node_id:n.node_id}:{},fields:{...d(n.node_id)?{}:{affected_node_id:n.node_id},pane:n.pane,window:n.window,tmux_session:n.tmux_session}}),await V(n.node_id)}catch(o){i({level:"error",event:"residue.reap.failed",...d(n.node_id)?{node_id:n.node_id}:{},error:o,fields:{...d(n.node_id)?{}:{affected_node_id:n.node_id},pane:n.pane,window:n.window,tmux_session:n.tmux_session}})}})}}scheduleFocusGc(e){if(this.focusGcInFlight||!e.lifecycle.acceptsDetachedWork())return;this.focusGcInFlight=!0;const r=this.gcStaleFocuses().finally(()=>{this.focusGcInFlight=!1});e.lifecycle.registerDetached(r)}async gcStaleFocuses(){let e;try{e=await P()}catch(t){s.fresh(()=>{i({level:"error",event:"focus.gc.failed",error:t})});return}if(e.length===0)return;let r;try{r=await G()}catch(t){s.fresh(()=>{i({level:"error",event:"focus.gc.failed",error:t})});return}if(r!==null)for(const t of e){if(t.pane===null||r.has(t.pane))continue;if(!await s.fresh(async()=>{try{return(await T(t.focus_id))?.pane!==t.pane||(i({level:"info",event:"focus.gc.removed",...d(t.node_id)?{node_id:t.node_id}:{},fields:{focus_id:t.focus_id,focus_node_id:t.node_id,pane:t.pane}}),await N(t.focus_id)),!0}catch(o){return i({level:"error",event:"focus.gc.failed",error:o}),!1}}))return}}async gcCreateRequests(e){await l("create-request-gc","",e,S,S,()=>s.fresh(async()=>{const r=await F(e),t=await D(e);t>0&&i({level:"info",event:"canvas.idempotency_keys.reaped",outcome:"succeeded",fields:{reaped_count:t}}),r>0&&i({level:"info",event:"canvas.create_requests.reaped",outcome:"succeeded",fields:{reaped_count:r}})}))}async gcViewerAttachments(e){await l("viewer-attachment-gc","",e,h,h,()=>s.fresh(async()=>{const r=Number((await(await g()).prepare("DELETE FROM viewer_attachments WHERE expires_at <= ?").run(new Date(e).toISOString())).changes);r>0&&i({level:"info",event:"viewer_attachments.reaped",outcome:"succeeded",fields:{reaped_count:r}})}))}async gcWarmPool(e){await l("warm-pool-gc","",e,h,h,()=>s.fresh(async()=>{const r=await k();r.length>0&&i({level:"info",event:"warm_pool.spares_reaped",outcome:"succeeded",fields:{reaped_count:r.length}})}))}}export{j as CONTEXT_STRIP_GRACE_MS,Z as DEAD_REAP_GRACE_MS,v as RETENTION_SWEEP_INTERVAL_MS,E as RETENTION_TTL_DAYS,Te as StorageMaintenanceReconciler};
@@ -21,7 +21,7 @@ Scope strings are prefixed with `crtr:`. These are the ones the daemon and CLI c
21
21
  | `crtr:conversations:read:app:<id>`, `crtr:objects:read:app:<id>` | Reading another app's conversations or node objects |
22
22
  | `<provider>:<group>` | One tool group of a provider |
23
23
 
24
- The `memory` in `crtr:memory:*` is the scope family's name for access to **documents** (see [Documents](./documents.md)); there is no separate memory store. The older short names (`ask`, `act`, `schedule`, `memory:read`, `memory:write`, `llm`) are not accepted by `crtr sys connect --scopes`. A node's own documents, and an app's documents for its own nodes, need no `crtr:memory` scope.
24
+ The `memory` in `crtr:memory:*` is the scope family's name for access to **documents** (see [Documents](./documents.md)); there is no separate memory store. A node's own documents, and an app's documents for its own nodes, need no `crtr:memory` scope.
25
25
 
26
26
  This is an allow-list, not a claim that code will behave. The daemon checks the scope at the route that performs the action and rejects an unavailable one. The node-create route's `scopes` field narrows a run: a run's list must stay inside what its creator and grant hold, and `crtr:act` requires `crtr:llm`. `client.memory` is not scope-gated: it lists and reads the person's `knowledge` and `preference` documents, and the answer is filtered by privacy, which is `public` or `private`. An app's ceiling is `public` documents; a grant holding `crtr:memory:read_private:user` or `crtr:memory:manage:user` widens it to `private` ones. Within that ceiling, the app's registered schema and the relation facts it writes decide who may read a document, not a per-call scope. The exception is a run started with a `scopes` list: it reads its own app's documents (including automatic delivery of them at boot) only with `crtr:memory:read:app:<id>` and writes or edits them only with `crtr:memory:rw:app:<id>`; a refused write answers `scope_missing` naming the scope. Such a run still publishes its own reports with `crtr push` and its promoted node still gets a roadmap, but cannot edit any other document through that path, and a child never regains a scope its parent's list dropped.
27
27
 
@@ -35,6 +35,6 @@ flowchart LR
35
35
 
36
36
  Scopes rely on a more basic trust boundary: `crtrd` is the sole writer of durable canvas state and the sole owner of broker lifecycle. SDK clients, the CLI, and viewers call its API; they do not open the canvas database or launch their own broker. One owner serializes lifecycle changes, makes the same API usable locally and remotely, and keeps a client from silently creating a second state authority.
37
37
 
38
- For a browser or remote process, run `crtr sys connect`. It enables the daemon’s TCP listener when needed and returns `base_url` plus a bearer `token` to give the application. `crtr sys connect --app <id> --scopes …` mints a new scoped token for that app instead of returning the owner token; `--scopes` requires `--app`, and accepts `crtr:llm`, `crtr:act`, `crtr:schedule`, `crtr:memory:read:user`, `crtr:memory:read:app`, `crtr:memory:rw:app`, `crtr:files:read:user:.` and `crtr:files:rw:user:.`. Treat either token as a credential: the remote app sends it as `Authorization: Bearer <token>`, and its scope list is the ceiling for scope-gated calls and newly created nodes.
38
+ A remote process sends a bearer token (`Authorization: Bearer <token>`); its scope list is the ceiling for scope-gated calls and newly created nodes. On Northlight the bearer is the person's or an app's, issued by the directory. Treat any token as a credential.
39
39
 
40
40
  The remote API is an explicit boundary, not permission to reach around it. Keep application code on the SDK or `/v1` contract, and let the daemon own state transitions. Run `crtr canvas read internal/nodes-and-canvas` for the operational ownership model.
@@ -80,13 +80,7 @@ also has a CLI/socket/schema surface to depend on instead of an import:
80
80
  `reload_auth` subset, and the `/v1` socket API. Each of those is versioned
81
81
  by the CLI's own `sys version` output rather than by a document here.
82
82
 
83
- The canvas is a supervised local Postgres owned by `crtrd`, not a file. The
84
- old `runtime/canvas.db` is no longer maintained: the first boot of a Postgres
85
- generation imports it and renames it `canvas.db.imported`. A sibling process
86
- reads the canvas through `/v1` or the root barrel's canvas reads above, never
87
- through the database itself. `crtr sys db export-sqlite` writes a `canvas.db`
88
- for rolling back to a SQLite generation; it is a one-time snapshot taken
89
- with the daemon stopped, not a live file to read.
83
+ The canvas is a Postgres that only the control plane's `crtrd` (`--role api|reconcile|all`) opens; a person's computer is a fleet machine (`crtrd --role machine`) and holds no database. A sibling process reads the canvas through `/v1` or the root barrel's canvas reads above, never through the database itself.
90
84
 
91
85
  ## Packaging
92
86
 
@@ -25,7 +25,7 @@ const node = await crtr.createNode({ prompt: 'List the top-level directories her
25
25
 
26
26
  | Page | Covers |
27
27
  |---|---|
28
- | [Getting started](./getting-started.md) | Install, `new Crouter()` on the owner's socket, `crtr sys connect` for a browser or remote app, Chrome's local-network prompt |
28
+ | [Getting started](./getting-started.md) | Install, `new Crouter()` on the owner's socket, `--tcp` and `CRTRD_TOKEN` for a browser or remote app, Chrome's local-network prompt |
29
29
  | [Client construction](./client.md) | Every constructor option and its environment-variable fallback; per-request options |
30
30
  | [Resource map](./resources.md) | Every namespace with its routes, and the `client.request()` escape hatch |
31
31
  | [Errors](./errors.md) | The daemon's scoped-token and wire errors, and identifier validation |
@@ -25,7 +25,7 @@ An app that signs people in with Northlight uses `OAuth2Client` and `oauth.clien
25
25
  |---|---|---|---|
26
26
  | `baseURL` | `string` | `CRTR_BASE_URL`, else unset | `http(s)://host:port` of a daemon TCP listener. |
27
27
  | `socketPath` | `string` | `CRTR_SOCKET`, else `CRTR_API_SOCKET`, else `api.sock` in the runtime root (`${CRTR_HOME:-~/.crouter}/runtime/api.sock` on macOS, `/run/crtr/api.sock` on Linux) | Unix socket. Node only; throws in a browser. |
28
- | `token` | `string` | `CRTRD_TOKEN` | Sent as `Authorization: Bearer <token>`. The owner token or a scoped token from `crtr sys connect`; a scoped token's ceiling is enforced per request (see [Getting started](./getting-started.md#a-token-that-holds-less-than-the-owner)). Ignored by a unix-socket daemon, which authenticates by filesystem permission. |
28
+ | `token` | `string` | `CRTRD_TOKEN` | Sent as `Authorization: Bearer <token>`. The token the daemon was started with (`CRTRD_TOKEN`); a scoped token's ceiling is enforced per request (see [Getting started](./getting-started.md#a-token-that-holds-less-than-the-owner)). Ignored by a unix-socket daemon, which authenticates by filesystem permission. |
29
29
  | `timeout` | `number` (ms) | `30_000` | Per-request wall clock. Does not apply to a stream. |
30
30
  | `maxRetries` | `number` | `2` | Transient-failure retries. Never applied to `POST` or `PATCH` — see [Errors](./errors.md). |
31
31
  | `defaultHeaders` | `Record<string, string>` | `{}` | Merged into every request. |
@@ -40,50 +40,15 @@ The SDK covers the app routes (`runs`, `uploads`, `docs`, `memory`, …). To cre
40
40
 
41
41
  ## 4. A browser or a remote application
42
42
 
43
- A process that is not on the daemon's machine — or a page in a browser, which has no unix sockets at all — reaches the daemon over TCP with a bearer token. There are two kinds. The **owner token** is the owner credential: whoever holds it can drive the whole surface. A **scoped token** (`crtr sys connect --app <id> --scopes …`) carries a list of scopes that caps what its holder and every run it creates may do.
44
-
45
- ### Turn the listener on, once
46
-
47
- On the machine running the daemon:
48
-
49
- ```bash
50
- crtr sys connect
51
- ```
52
-
53
- This stores a listener address and generates a token if either is missing, then prints the base URL and token before handing the daemon over to a successor that boots with the listener on. It then logs in to the selected model provider when that provider has no usable credential. Run it again and, when the listener is up and that provider is ready, it prints the credentials and changes nothing.
54
-
55
- The command returns `base_url` and `token`. Use JSON output when a program or a setup UI needs those exact fields:
56
-
57
- ```text
58
- $ crtr --json sys connect
59
- {"base_url":"http://127.0.0.1:8787","token":"<64-character bearer token>"}
60
- ```
61
-
62
- ### A token that holds less than the owner
63
-
64
- ```bash
65
- crtr sys connect --app my-app --scopes crtr:llm,crtr:act,crtr:memory:read:user
66
- ```
67
-
68
- `--scopes` requires `--app` (the app id, without the `app:` prefix) and accepts only `crtr:llm`, `crtr:act`, `crtr:schedule`, `crtr:memory:read:user`, `crtr:memory:read:app`, `crtr:memory:rw:app`, `crtr:files:read:user:.` and `crtr:files:rw:user:.`. This mints a new token for that app whose scope list is a ceiling, appends it to the same secrets store, prints it in place of the owner token, and always hands the daemon over (it reads tokens once, at boot). The ceiling is checked on every request that carries the token:
69
-
70
- - A scope-gated operation the ceiling lacks answers `403 scope_denied`. Starting or messaging a run, and creating, reviving, forking, messaging, or yielding a node, needs `crtr:act`, as do `bash`, `files`, and creating a human request or review (there is no separate scope for human requests); arming or running a cron needs `crtr:schedule`; `/v1/llm` needs `crtr:llm`. `client.memory` has no scope of its own: it reads the person's documents filtered by privacy, and a grant holding `crtr:memory:read_private:user` also sees `private` documents, and one holding `crtr:memory:manage:user` sees every level.
71
- - A run started with `scopes` outside the ceiling answers `403 scope_denied`; `details.scopes` lists the offending scopes. Omit `scopes` and the run gets the ceiling.
72
- - Owner-only operations — daemon restart, the attach viewer, broker internals, canvas prune, profile pause/resume/delete, model credential install — answer `403 owner_only` to any scoped token.
73
-
74
- What a scope does **not** do on a developer's machine: there is no OS sandbox. Scopes gate the daemon and the CLI; a run's own bash tool is ungated, and the daemon identifies a calling node by a field the caller declares, so a scope check bounds a well-behaved agent, not a hostile one. A scope the daemon does not check at any route is recorded on the run but not enforced; `sys connect` mints only the scopes listed above. There is no list or revoke verb yet; to retire a scoped token, remove it from the 0600 user secrets store and restart the daemon.
75
-
76
- ### Connect with the saved values
77
-
78
- Construct the client from the base URL and token the user pasted from `crtr sys connect`:
43
+ A process that is not on the daemon's machine — or a page in a browser, which has no unix sockets at all — reaches a daemon over TCP with a bearer token. A computer signed in with `crtr sys signin` is a fleet machine: its crtr commands go to the Northlight control plane with the person's bearer, and no local listener or owner token is created. Run a daemon with `--tcp <host:port>` and `CRTRD_TOKEN` only for your own control plane under development (`crtrd --role all` with `CRTR_DATABASE_URL` and `CRTR_DIRECTORY_URL`).
79
44
 
80
45
  ```ts
81
46
  import Crouter from '@north-light/sdk';
82
47
 
83
- const client = new Crouter({ baseURL: saved.baseURL, token: saved.token });
48
+ const client = new Crouter({ baseURL: process.env.CRTR_BASE_URL, token: process.env.CRTRD_TOKEN });
84
49
  ```
85
50
 
86
- A rejected token raises `AuthenticationError` and an unreachable listener raises `APIConnectionError`; in both cases ask the user to run `crtr sys connect` again and paste what it prints.
51
+ A rejected token raises `AuthenticationError` and an unreachable listener raises `APIConnectionError`.
87
52
 
88
53
  The root entry of the SDK is browser-safe: it imports nothing from `node:*`. The unix-socket code is reached only through a dynamic import taken when `socketPath` is set, so a browser bundle never resolves it.
89
54
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.744",
3
+ "version": "0.3.745",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -158,8 +158,8 @@
158
158
  },
159
159
  "license": "UNLICENSED",
160
160
  "dependencies": {
161
- "@north-light/identity": "0.3.744",
162
- "@north-light/plugin": "0.3.744",
161
+ "@north-light/identity": "0.3.745",
162
+ "@north-light/plugin": "0.3.745",
163
163
  "@earendil-works/chord": "1.5.2",
164
164
  "@earendil-works/pi-agent-core": "1.5.2",
165
165
  "@earendil-works/pi-ai": "1.5.2",