@north-light/cli 0.3.661 → 0.3.663

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 (35) hide show
  1. package/dist/api/contract.d.ts +1 -1
  2. package/dist/api/contract.js +1 -1
  3. package/dist/api/dto/run-events.d.ts +13 -0
  4. package/dist/builtin-memory/northlight-apps/guides/stream-a-run.md +2 -0
  5. package/dist/clients/attach/viewer.js +1 -1
  6. package/dist/core/canvas/schema-pg/020-machine-calls-status-all.sql +8 -0
  7. package/dist/core/canvas/schema-version.d.ts +1 -1
  8. package/dist/core/canvas/schema-version.js +1 -1
  9. package/dist/core/runs/operations.js +9 -7
  10. package/dist/core/runtime/runner/machine/call.js +2 -2
  11. package/dist/core/runtime/runner/machine/executor.d.ts +7 -0
  12. package/dist/core/runtime/runner/machine/executor.js +1 -1
  13. package/dist/core/runtime/runner/machine/machine-executor.test.js +2 -2
  14. package/dist/core/runtime/runner/machine/ops.d.ts +14 -1
  15. package/dist/core/runtime/runner/machine/ops.js +1 -1
  16. package/dist/daemon/broker-signals/bus.d.ts +3 -2
  17. package/dist/daemon/broker-signals/bus.js +1 -1
  18. package/dist/daemon/crtrd.d.ts +4 -0
  19. package/dist/daemon/crtrd.js +12 -12
  20. package/dist/daemon/machine-daemon.js +1 -1
  21. package/dist/daemon/machine-link/client.d.ts +9 -0
  22. package/dist/daemon/machine-link/client.js +1 -1
  23. package/dist/daemon/machine-link/frames.d.ts +8 -0
  24. package/dist/daemon/machine-link/frames.js +1 -1
  25. package/dist/daemon/machine-link/holder.d.ts +11 -0
  26. package/dist/daemon/machine-link/holder.js +4 -4
  27. package/dist/daemon/reconcilers/grant-effects.js +1 -1
  28. package/dist/daemon/reconcilers/node-lifecycle/machine-sweep.d.ts +5 -0
  29. package/dist/daemon/reconcilers/node-lifecycle/machine-sweep.js +4 -0
  30. package/dist/daemon/reconcilers/node-lifecycle/tick.d.ts +3 -0
  31. package/dist/daemon/reconcilers/node-lifecycle/tick.js +1 -1
  32. package/docs/apps/guides/stream-a-run.md +2 -0
  33. package/package.json +2 -2
  34. package/packages/crouter-identity/package.json +1 -1
  35. package/runtime.lock.json +13 -13
@@ -1,19 +1,19 @@
1
- var ar=Object.defineProperty;var s=(e,c)=>ar(e,"name",{value:c,configurable:!0});import{applyBootSettings as sr}from"./boot-settings.js";import{startPeerOutbox as cr}from"./peer/outbox.js";import{reportMachineStatus as lr}from"../core/peer/directory.js";import{createPeerRelay as dr}from"./peer/relay-service.js";import{writeFileSync as mr,readFileSync as pr,rmSync as fr,mkdirSync as Re,existsSync as R,unlinkSync as Pe,chmodSync as Ee}from"node:fs";import{createServer as Y}from"node:http";import{dirname as ur}from"node:path";import{envCrtrdTcp as Ie,envDocumentPort as hr}from"../shared/env.js";import{openCanvasConversationStore as wr,serveCanvasConversationStore as vr}from"../core/canvas/sessions.js";import{installConversationStore as gr}from"../core/conversation-store/index.js";import{pollRunObservers as Sr}from"./runs/observer.js";import{randomBytes as xe}from"node:crypto";import{apiSocketPath as De,crtrHome as yr}from"../core/canvas/paths.js";import{activeAppUsers as _r}from"../core/spaces/users.js";import{ensureAppSpace as br,ensureUserFiles as kr}from"../core/spaces/space.js";import{LAUNCHER_SOCKET as D}from"../launcher/spec.js";import{launcherRequest as A}from"../launcher/client.js";import{installLauncherEventSink as Rr}from"./launcher-events.js";import{initializeEmptyLayout as Pr,layoutNeedsMigration as Er,socketDir as Te}from"../core/layout.js";import{migrateLooseKeys as Ir}from"../core/layout-migrate/loose-keys.js";import{relocateProfileFolders as xr}from"../core/profiles/relocate.js";import{getNode as Dr,listNodesForSupervision as Ce,listParkedResidentsWithWakeMail as Tr,setFrozen as Le}from"../core/canvas/index.js";import{createApiServer as Cr,closeServer as $e}from"./api/server.js";import{Router as Lr}from"./api/router.js";import{healthRoutes as $r}from"./api/handlers/health.js";import{createDocumentListener as Ar}from"./api/document-listener.js";import{documentSecret as Nr}from"./api/document-secret.js";import{createAppListener as Mr}from"./api/app-listener.js";import{registerMachineEnvironment as Gr}from"../core/environments.js";import{registerBlaxelRunnerFromEnv as Or}from"../core/secrets/blaxel-register.js";import{markCloudRole as Fr,resolvePerson as Br,retireLocalPerson as Hr,setPersonId as jr}from"../core/canvas/person.js";import{backfillNodeApps as Ae,runPermissionsBoot as zr}from"../core/permissions/boot.js";import{startRunNotices as Ur}from"./run-notices.js";import{startGrantEffects as qr}from"./reconcilers/grant-effects.js";import{syncPackages as Wr}from"../core/packages/directory-sync.js";import{startActivationDelivery as Jr}from"../core/model-auth/activations.js";import{createGrantSync as Kr,GRANT_SYNC_INTERVAL_S as Ne}from"../core/grants/sync.js";import{sweepSandboxes as Vr}from"../core/grants/on-sync.js";import{rebuildCronExecutions as Yr}from"./cron/run-socket.js";import{hasSyncedGrants as Qr}from"../core/grants/mirror.js";import{readConfig as de}from"../core/config.js";import{reconcileUndeliveredTickets as Xr}from"./human/sweep.js";import{resetHandedOffDeliveries as Zr}from"../core/canvas/deliveries.js";import{resetHandedOffDaemonActions as et}from"../core/canvas/daemon-actions.js";import{sweepReviews as rt}from"./review/sweep.js";import{pidfilePath as me}from"./pidfile.js";import{rendererWarning as tt}from"../core/runtime/package-health.js";import{DEFAULT_INTERVAL_MS as nt}from"./supervise-cadence.js";import{createResumeDetector as ot}from"./resume-detector.js";import{setFatalFaultAnnouncer as it}from"../core/canvas/recovery.js";import{BrokerSupervisionReconciler as at}from"./reconcilers/broker-supervision.js";import{ControllerDeathReconciler as st}from"./reconcilers/controller-death.js";import{NodeLifecycleReconciler as ct}from"./reconcilers/node-lifecycle/tick.js";import{NodeDeadlineReconciler as lt}from"./reconcilers/node-deadline.js";import{CronLaneReconciler as dt}from"./reconcilers/cron-lane.js";import{DeliveryLaneReconciler as mt}from"./reconcilers/delivery-lane.js";import{ActionLaneReconciler as pt}from"./reconcilers/action-lane.js";import{endLiveExecution as ft,migrateLegacyExecutionIdentities as ut}from"../core/canvas/executions.js";import{revokePriorEpochNodeTokens as ht}from"../core/canvas/node-tokens.js";import{PendingReviewSubmitReconciler as wt}from"./reconcilers/pending-review-submit.js";import{StorageMaintenanceReconciler as vt}from"./reconcilers/storage-maintenance.js";import{StorageDueWorkReconciler as gt}from"./reconcilers/storage-due-work.js";import{PurgeDueWorkReconciler as St}from"./reconcilers/purge-due-work.js";import{assertLedgerEnv as yt}from"../core/ledger/rates.js";import{LedgerSandboxReconciler as _t}from"./reconcilers/ledger-sandbox.js";import{LedgerStorageReconciler as bt}from"./reconcilers/ledger-storage.js";import{LedgerR2Reconciler as kt}from"./reconcilers/ledger-r2.js";import{importedNodesHeld as Me}from"./reconcilers/live-obligation.js";import{ImportLaneReconciler as Rt}from"./reconcilers/import-lane.js";import{BashDeadlineReconciler as Pt}from"./reconcilers/bash-deadline.js";import{FaultRetryBackstopReconciler as Et}from"./reconcilers/fault-retry-backstop.js";import{StructuredRequestReconciler as It}from"./reconcilers/structured-request-lane.js";import{RecipeImageReconciler as xt,subscribeImageBuilt as Dt}from"./reconcilers/recipe-image.js";import{reconcileStructuredRequestSidecars as Tt}from"./structured-requests/boot.js";import{captureLivenessSnapshot as Ge,capturePidCommand as Ct,captureTeardownSnapshot as Oe,isPidAlive as Lt,isAnyPidAlive as Fe,killProcessTreePids as Be}from"../core/canvas/pid.js";import{bindFleet as $t,boundFleet as At}from"../core/runtime/fleet.js";import{bindDaemonControl as Nt,clearDaemonControl as Mt}from"./control.js";import{execDaemon as Gt,spawnDaemon as Ot}from"./manage.js";import{reconcileAndMigrateBoot as Ft}from"../core/canvas/boot.js";import{resolveInstallId as Bt}from"../core/canvas/install-id.js";import{setInstallId as Ht}from"../core/runtime/nodes.js";import{claimDaemonOwnership as jt,daemonOwnershipApplies as zt,daemonOwnershipClaimed as Ut,releaseDaemonOwnership as He}from"../core/canvas/daemon-owner.js";import{canvasDatabaseUrl as qt,closeAllDbs as pe,openDb as je,withCanvasWrite as fe}from"../core/canvas/db.js";import{importSqliteCanvasIfPresent as Wt}from"../core/canvas/import-sqlite.js";import{ensurePostgres as Jt,ensurePostgresHealthy as Kt,stopPostgres as Vt,withPostgresStartLock as Yt}from"./postgres/index.js";import{brokerSignalBus as H}from"./broker-signals/bus.js";import{brokerSignalStreams as Qt}from"./api/handlers/broker-signals.js";import{setRequestsStartRunObservers as Xt}from"./api/handlers/broker-ops.js";import{reconcilePackages as Zt}from"../core/graph/package-reconcile.js";import{migrateAppInstalls as en}from"../core/scoped-state/migrate-app-installs.js";import{publish as rn,readBuiltinSnapshot as tn}from"../core/graph/package-publish.js";import{startRepoSync as nn}from"../core/graph/repo-sync/index.js";import{prewarmRecentRecipes as on,reapStaleSpares as an}from"../core/runtime/warm-pool.js";import{DaemonFleet as sn}from"./fleet.js";import{copyNodeFilesToRows as cn}from"../core/runtime/first-boot-rows.js";import{BOOT_MIGRATIONS as ln}from"./boot-migrations.js";import{emitEvent as m}from"../core/events/emit.js";import{operationIdContext as _}from"../core/events/operation-id.js";import{bindDaemonEventSource as dn}from"../core/events/source.js";import{activateCanvasImport as mn,MigrationBlockedError as pn,runForcedCanvasImport as fn}from"../migrations/activation.js";import{adoptInstallPerson as un,convertLegacyScopedStore as hn,personStoresCopied as wn}from"../core/scoped-state/migrate.js";import{readLegacyUserSnapshot as vn}from"../core/scoped-state/legacy-profiles.js";import{heldPersons as ze,installPreludeSnapshot as gn}from"../core/scoped-state/person-store.js";import{loadPersonSettings as Ue}from"../core/scoped-state/person-rows.js";import{userScopeRoot as qe}from"../core/scope.js";import{brokerCommandDeclaresCanvasHome as ue}from"../core/runtime/broker-ownership.js";import{brokerCommandDeclaresCanvasHome as Qi}from"../core/runtime/broker-ownership.js";function he(e){return/ --epoch (\S+) /.exec(e)?.[1]??null}s(he,"brokerCommandEpoch");const Sn=5e3,We=150;async function yn(e){const c=Ge();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 u=yr(),p=[];for(const[r,l]of c.processes){const y=l.command;if(l.zombie||!y.includes("broker-cli.js")||!ue(y,u)||he(y)===e)continue;const P=y.trim().split(/\s+/).at(-1)??"";P===""||P.endsWith("broker-cli.js")||p.push({pid:r,nodeId:P})}let v=0;const i=[];for(const r of p){const l=Ct(r.pid);if(l===null||!l.includes("broker-cli.js")||!ue(l,u)||he(l)===e||l.trim().split(/\s+/).at(-1)!==r.nodeId)continue;const y=Oe(r.pid,null);if(!y.reused){try{process.platform==="linux"&&R(D)?await A({operation:"stop",pid:r.pid}):process.kill(r.pid,"SIGTERM")}catch{continue}v++,i.push({pid:r.pid,snap:y})}}const h=Date.now()+Sn;for(;Date.now()<h&&i.some(r=>Fe(r.snap.tree.length>0?r.snap.tree:[r.pid]));)await new Promise(r=>setTimeout(r,We));let g=0;for(const r of i){const l=r.snap.tree.length>0?r.snap.tree:[r.pid];Fe(l)&&(process.platform==="linux"&&R(D)?await A({operation:"stop",pid:r.pid}):Be(l,"SIGKILL",r.snap.identities),g++)}g>0&&await new Promise(r=>setTimeout(r,We));const d=Ge();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 f=[];for(const[r,l]of d.processes){const y=l.command;l.zombie||!y.includes("broker-cli.js")||ue(y,u)&&he(y)!==e&&f.push(r)}if(f.length>0)throw new Error(`prior-epoch broker census could not prove termination of pid(s): ${f.join(", ")}`);m({level:"info",event:"daemon.census.completed",fields:{prior_epoch_brokers:p.length,sigtermed:v,sigkilled:g}})}s(yn,"reapPriorEpochBrokers");const _n=5e3;async function bn(e){const c=Array.from(e.entries());if(c.length===0)return;for(const[i]of c){const h=(await Dr(i))?.status;(h==="active"||h==="idle")&&await Le(i,new Date().toISOString())}const u=c.map(([,i])=>({pid:i.pid,snap:Oe(i.pid,null),exited:i.handle.exited}));for(const i of u)if(!i.snap.reused)try{process.platform==="linux"&&R(D)?await A({operation:"stop",pid:i.pid}):process.kill(i.pid,"SIGTERM")}catch{}const p=new Promise(i=>{setTimeout(i,_n).unref()});await Promise.allSettled(u.map(i=>Promise.race([i.exited.then(()=>{}),p])));const v=[];for(const i of u)Lt(i.pid)&&(process.platform==="linux"&&R(D)?await A({operation:"stop",pid:i.pid}):Be(i.snap.tree.length>0?i.snap.tree:[i.pid],"SIGKILL",i.snap.identities),v.push(i));await Promise.all(v.map(i=>i.exited));for(const[i]of c)await ft(i,{reason:"daemon-teardown"});m({level:"info",event:"daemon.fleet_teardown.completed",fields:{brokers:u.length,sigkilled:v.length}})}s(bn,"teardownFleet");function Je(){Re(ur(me()),{recursive:!0}),mr(me(),String(process.pid),"utf8")}s(Je,"writePidfile");function Ke(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}s(Ke,"isMissingPathError");function Ve(e){const c=me();let u;try{u=pr(c,"utf8")}catch(p){if(Ke(p))return;throw p}if(u.trim()!==String(e))throw new Error(`daemon readiness mirror does not name this invocation (expected pid ${e})`);try{fr(c)}catch(p){if(Ke(p))return;throw p}}s(Ve,"removeOwnedPidfileMirror");const kn={acceptsDetachedWork:s(()=>!0,"acceptsDetachedWork"),registerDetached:s(e=>{e.catch(()=>{})},"registerDetached")},Q=new at;it(e=>Q.handleFatalFault(e,!1));const Rn=new st,Pn=new ct,En=new lt,In=new dt,xn=new mt,Dn=new pt,Tn=new wt,Cn=new vt,Ln=new gt,$n=new St,An=new _t,Nn=new bt,Mn=new kt,Gn=new Rt,On=new Pt,Fn=new Et,Bn=new It,Hn=new xt;async function jn(e=Date.now(),c=kn){const u=At(),p=await Q.runFleetPreamble(u);let v,i,h;try{i=await Me();const d=(await Ce()).filter(r=>!i.has(r.node_id));v=d.filter(r=>r.status==="active"||r.status==="idle"),h=d.filter(r=>r.status==="done"||r.status==="canceled"||r.status==="dead");const f=new Set(h.map(r=>r.node_id));h.push(...(await Tr()).filter(r=>!f.has(r.node_id)&&!i.has(r.node_id)))}catch(d){m({level:"error",event:"canvas.node_list.failed",error:d});return}await Q.run(e,{rows:v,fleet:u,lifecycle:c,held:i}),await Rn.run(e,{rows:v,held:i});const g=await Pn.run(e,{rows:[...v,...h],fleet:u});await En.run(e,i),await Bn.run(e,i),await Hn.run(e,{lifecycle:c}),await In.run(e,{lifecycle:c,held:i}),await xn.run(e,{lifecycle:c}),await Dn.run(e,{lifecycle:c}),await Tn.run(e,{lifecycle:c}),await Cn.run(e,{lifecycle:c,fleet:u,held:i}),Ln.run(e,{lifecycle:c}),$n.run(e,{lifecycle:c}),An.run(e,{lifecycle:c}),Nn.run(e,{lifecycle:c}),Mn.run(e,{lifecycle:c}),Gn.run(e,{lifecycle:c}),await Sr(),Fn.run(e,{fleet:u,lifecycle:c}),await On.run(e,{rows:v}),Q.warnIfSaturated({fleet:u,lifecycle:c,thresholds:p,frozen:g})}s(jn,"superviseTick");function j(e){return e===void 0||e==="reconcile"}s(j,"roleRunsLanes");function N(e){return e===void 0||e==="api"}s(N,"roleServesRequests");const zn=66e4;function Un(e){const c=new Lr().registerAll($r(()=>null).filter(r=>r.pattern==="/healthz")),u=s((r,l)=>{const y=(r.url??"/").split("?")[0];if((r.method??"GET").toUpperCase()==="GET"&&y==="/healthz"){c.handle(r,l,null,{class:"person"});return}l.writeHead(404,{"content-type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:{code:"not_found",message:"this process serves only /healthz",origin:"runtime"}}))},"handler"),p=De();R(p)&&Pe(p);const v=Y(u),i=new Promise((r,l)=>{v.once("error",l),v.listen(p,()=>{v.off("error",l),Ee(p,384),r()})});let h,g=null;const d=e.tcp??Ie()??de("user").api.tcp;if(d!==void 0&&d!==""){const r=/^(.*):(\d+)$/.exec(d.trim());if(r===null||Number(r[2])>65535)throw new Error(`invalid reconcile probe TCP address: ${d}`);const l=Y(u);l.on("error",y=>m({event:"api.server.failed",level:"error",error:y})),l.listen(Number(r[2]),r[1]===""?"0.0.0.0":r[1],()=>{g=`${r[1]===""?"0.0.0.0":r[1]}:${r[2]}`}),h=l}let f=!1;return{ready:i,tcpAddress:s(()=>g,"tcpAddress"),async close(r={}){if(!f){f=!0,await Promise.all([$e(v,new Set,r.graceMs),h===void 0?Promise.resolve():$e(h,new Set,r.graceMs)]);try{R(p)&&Pe(p)}catch{}}}}}s(Un,"createProbeServer");const qn="daemon is draining for shutdown and admits no new work";async function Wn(e){Re(Te(),{recursive:!0,mode:493}),process.platform==="linux"&&Ee(Te(),493);const c=De();if(R(c))throw new Error(`layout refusal cannot bind occupied socket: ${c}`);const u=Y((d,f)=>{if(d.method==="GET"&&d.url==="/healthz"){f.writeHead(200,{"content-type":"application/json; charset=utf-8"}),f.end(JSON.stringify({ok:!1,daemon_up:!0,store_accessible:!1,brokers_reconciled:!1,startup_phase:"blocked",startup_blocked:"layout_migration_required"}));return}f.writeHead(503,{"content-type":"application/json; charset=utf-8"}),f.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,f)=>{u.once("error",f),u.listen(c,()=>{u.off("error",f),d()})});let p;const v=e.tcp??Ie();if(v){const d=/^(.*):(\d+)$/.exec(v);if(!d||Number(d[2])>65535)throw new Error(`invalid refusal TCP address: ${v}`);const f=Y(u.listeners("request")[0]);await new Promise((r,l)=>{f.once("error",l),f.listen(Number(d[2]),d[1],()=>{f.off("error",l),r()})}),p=f}Je();let i;const h=s(()=>(i??=(async()=>{u.closeAllConnections(),p?.closeAllConnections(),await Promise.all([u,p].filter(d=>d!==void 0).map(d=>new Promise((f,r)=>d.close(l=>l?r(l):f())))),Ve(process.pid),process.off("SIGINT",g),process.off("SIGTERM",g)})(),i),"cleanup"),g=s(()=>{h().then(()=>process.exit(0),d=>{process.stderr.write(`[crtrd] layout refusal cleanup failed: ${String(d)}
2
- `),process.exit(1)})},"onSignal");return process.on("SIGINT",g),process.on("SIGTERM",g),h}s(Wn,"serveLayoutRefusal");async function Jn(e={}){if(e.role==="machine")return(await import("./machine-daemon.js")).runMachineDaemon();if(Er())return Wn(e);Pr();const c=s(n=>{process.stderr.write(`[crtrd] ${n}
3
- `)},"logPostgres"),u=!!process.env.CRTR_TEST_PG_URL,p=zt(e.role);Xt(j(e.role));const v=s(async()=>p?await jt(xe(16).toString("hex")):{claimed:!0,claim:{pid:process.pid,pid_identity:"",token:xe(16).toString("hex")}},"claimOwnership"),{database:i,ownership:h}=u?{database:{url:await qt()},ownership:await v()}:await Yt(async()=>({database:await Jt({log:c,startLockHeld:!0}),ownership:await v()}));if(!h.claimed){if(h.reason==="incumbent_alive")process.stderr.write(`[crtrd] already running (pid ${h.incumbentPid??"?"})
1
+ var lr=Object.defineProperty;var s=(e,c)=>lr(e,"name",{value:c,configurable:!0});import{applyBootSettings as dr}from"./boot-settings.js";import{startPeerOutbox as mr}from"./peer/outbox.js";import{reportMachineStatus as pr}from"../core/peer/directory.js";import{createPeerRelay as fr}from"./peer/relay-service.js";import{writeFileSync as ur,readFileSync as hr,rmSync as wr,mkdirSync as Ee,existsSync as R,unlinkSync as Ie,chmodSync as xe}from"node:fs";import{createServer as Q}from"node:http";import{dirname as vr}from"node:path";import{envCrtrdTcp as De,envDocumentPort as gr}from"../shared/env.js";import{openCanvasConversationStore as yr,serveCanvasConversationStore as Sr}from"../core/canvas/sessions.js";import{installConversationStore as _r}from"../core/conversation-store/index.js";import{pollRunObservers as br}from"./runs/observer.js";import{randomBytes as Te}from"node:crypto";import{apiSocketPath as Ce,crtrHome as kr}from"../core/canvas/paths.js";import{activeAppUsers as Rr}from"../core/spaces/users.js";import{ensureAppSpace as Pr,ensureUserFiles as Er}from"../core/spaces/space.js";import{LAUNCHER_SOCKET as D}from"../launcher/spec.js";import{launcherRequest as A}from"../launcher/client.js";import{installLauncherEventSink as Ir}from"./launcher-events.js";import{initializeEmptyLayout as xr,layoutNeedsMigration as Dr,socketDir as Le}from"../core/layout.js";import{migrateLooseKeys as Tr}from"../core/layout-migrate/loose-keys.js";import{relocateProfileFolders as Cr}from"../core/profiles/relocate.js";import{getNode as Lr,getRow as $r,listNodesForSupervision as $e,listParkedResidentsWithWakeMail as Ar,setFrozen as Ae}from"../core/canvas/index.js";import{createApiServer as Nr,closeServer as Ne}from"./api/server.js";import{Router as Mr}from"./api/router.js";import{healthRoutes as Gr}from"./api/handlers/health.js";import{createDocumentListener as Or}from"./api/document-listener.js";import{documentSecret as Fr}from"./api/document-secret.js";import{createAppListener as Br}from"./api/app-listener.js";import{registerMachineEnvironment as Hr}from"../core/environments.js";import{registerBlaxelRunnerFromEnv as jr}from"../core/secrets/blaxel-register.js";import{markCloudRole as zr,resolvePerson as Ur,retireLocalPerson as qr,setPersonId as Wr}from"../core/canvas/person.js";import{backfillNodeApps as Me,runPermissionsBoot as Jr}from"../core/permissions/boot.js";import{startRunNotices as Kr}from"./run-notices.js";import{startGrantEffects as Vr}from"./reconcilers/grant-effects.js";import{syncPackages as Yr}from"../core/packages/directory-sync.js";import{startActivationDelivery as Qr}from"../core/model-auth/activations.js";import{createGrantSync as Xr,GRANT_SYNC_INTERVAL_S as Ge}from"../core/grants/sync.js";import{sweepSandboxes as Zr}from"../core/grants/on-sync.js";import{rebuildCronExecutions as et}from"./cron/run-socket.js";import{hasSyncedGrants as rt}from"../core/grants/mirror.js";import{readConfig as me}from"../core/config.js";import{reconcileUndeliveredTickets as tt}from"./human/sweep.js";import{resetHandedOffDeliveries as nt}from"../core/canvas/deliveries.js";import{resetHandedOffDaemonActions as ot}from"../core/canvas/daemon-actions.js";import{sweepReviews as it}from"./review/sweep.js";import{pidfilePath as pe}from"./pidfile.js";import{rendererWarning as at}from"../core/runtime/package-health.js";import{DEFAULT_INTERVAL_MS as st}from"./supervise-cadence.js";import{createResumeDetector as ct}from"./resume-detector.js";import{setFatalFaultAnnouncer as lt}from"../core/canvas/recovery.js";import{BrokerSupervisionReconciler as dt}from"./reconcilers/broker-supervision.js";import{ControllerDeathReconciler as mt}from"./reconcilers/controller-death.js";import{NodeLifecycleReconciler as pt}from"./reconcilers/node-lifecycle/tick.js";import{NodeDeadlineReconciler as ft}from"./reconcilers/node-deadline.js";import{CronLaneReconciler as ut}from"./reconcilers/cron-lane.js";import{DeliveryLaneReconciler as ht}from"./reconcilers/delivery-lane.js";import{ActionLaneReconciler as wt}from"./reconcilers/action-lane.js";import{endLiveExecution as vt,hasObservedExit as gt,latestExecutionForNode as yt,migrateLegacyExecutionIdentities as St}from"../core/canvas/executions.js";import{revokePriorEpochNodeTokens as _t}from"../core/canvas/node-tokens.js";import{PendingReviewSubmitReconciler as bt}from"./reconcilers/pending-review-submit.js";import{StorageMaintenanceReconciler as kt}from"./reconcilers/storage-maintenance.js";import{StorageDueWorkReconciler as Rt}from"./reconcilers/storage-due-work.js";import{PurgeDueWorkReconciler as Pt}from"./reconcilers/purge-due-work.js";import{assertLedgerEnv as Et}from"../core/ledger/rates.js";import{LedgerSandboxReconciler as It}from"./reconcilers/ledger-sandbox.js";import{LedgerStorageReconciler as xt}from"./reconcilers/ledger-storage.js";import{LedgerR2Reconciler as Dt}from"./reconcilers/ledger-r2.js";import{importedNodesHeld as fe}from"./reconcilers/live-obligation.js";import{ImportLaneReconciler as Tt}from"./reconcilers/import-lane.js";import{BashDeadlineReconciler as Ct}from"./reconcilers/bash-deadline.js";import{FaultRetryBackstopReconciler as Lt}from"./reconcilers/fault-retry-backstop.js";import{StructuredRequestReconciler as $t}from"./reconcilers/structured-request-lane.js";import{RecipeImageReconciler as At,subscribeImageBuilt as Nt}from"./reconcilers/recipe-image.js";import{reconcileStructuredRequestSidecars as Mt}from"./structured-requests/boot.js";import{captureLivenessSnapshot as Oe,capturePidCommand as Gt,captureTeardownSnapshot as Fe,isPidAlive as Ot,isAnyPidAlive as Be,killProcessTreePids as He}from"../core/canvas/pid.js";import{bindFleet as Ft,boundFleet as je}from"../core/runtime/fleet.js";import{bindDaemonControl as Bt,clearDaemonControl as Ht}from"./control.js";import{execDaemon as jt,spawnDaemon as zt}from"./manage.js";import{reconcileAndMigrateBoot as Ut}from"../core/canvas/boot.js";import{resolveInstallId as qt}from"../core/canvas/install-id.js";import{setInstallId as Wt}from"../core/runtime/nodes.js";import{claimDaemonOwnership as Jt,daemonOwnershipApplies as Kt,daemonOwnershipClaimed as Vt,releaseDaemonOwnership as ze}from"../core/canvas/daemon-owner.js";import{canvasDatabaseUrl as Yt,closeAllDbs as ue,openDb as Ue,withCanvasWrite as he}from"../core/canvas/db.js";import{importSqliteCanvasIfPresent as Qt}from"../core/canvas/import-sqlite.js";import{ensurePostgres as Xt,ensurePostgresHealthy as Zt,stopPostgres as en,withPostgresStartLock as rn}from"./postgres/index.js";import{brokerSignalBus as N}from"./broker-signals/bus.js";import{brokerSignalStreams as tn}from"./api/handlers/broker-signals.js";import{setRequestsStartRunObservers as nn}from"./api/handlers/broker-ops.js";import{reconcilePackages as on}from"../core/graph/package-reconcile.js";import{migrateAppInstalls as an}from"../core/scoped-state/migrate-app-installs.js";import{publish as sn,readBuiltinSnapshot as cn}from"../core/graph/package-publish.js";import{startRepoSync as ln}from"../core/graph/repo-sync/index.js";import{prewarmRecentRecipes as dn,reapStaleSpares as mn}from"../core/runtime/warm-pool.js";import{DaemonFleet as pn}from"./fleet.js";import{copyNodeFilesToRows as fn}from"../core/runtime/first-boot-rows.js";import{BOOT_MIGRATIONS as un}from"./boot-migrations.js";import{emitEvent as p}from"../core/events/emit.js";import{operationIdContext as _}from"../core/events/operation-id.js";import{bindDaemonEventSource as hn}from"../core/events/source.js";import{activateCanvasImport as wn,MigrationBlockedError as vn,runForcedCanvasImport as gn}from"../migrations/activation.js";import{adoptInstallPerson as yn,convertLegacyScopedStore as Sn,personStoresCopied as _n}from"../core/scoped-state/migrate.js";import{readLegacyUserSnapshot as bn}from"../core/scoped-state/legacy-profiles.js";import{heldPersons as qe,installPreludeSnapshot as kn}from"../core/scoped-state/person-store.js";import{loadPersonSettings as We}from"../core/scoped-state/person-rows.js";import{userScopeRoot as Je}from"../core/scope.js";import{brokerCommandDeclaresCanvasHome as we}from"../core/runtime/broker-ownership.js";import{brokerCommandDeclaresCanvasHome as ta}from"../core/runtime/broker-ownership.js";function ve(e){return/ --epoch (\S+) /.exec(e)?.[1]??null}s(ve,"brokerCommandEpoch");const Rn=5e3,Ke=150;async function Pn(e){const c=Oe();if(c===null)throw p({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness"}}),new Error("prior-epoch broker census could not capture the process table");const f=kr(),d=[];for(const[r,l]of c.processes){const S=l.command;if(l.zombie||!S.includes("broker-cli.js")||!we(S,f)||ve(S)===e)continue;const P=S.trim().split(/\s+/).at(-1)??"";P===""||P.endsWith("broker-cli.js")||d.push({pid:r,nodeId:P})}let v=0;const i=[];for(const r of d){const l=Gt(r.pid);if(l===null||!l.includes("broker-cli.js")||!we(l,f)||ve(l)===e||l.trim().split(/\s+/).at(-1)!==r.nodeId)continue;const S=Fe(r.pid,null);if(!S.reused){try{process.platform==="linux"&&R(D)?await A({operation:"stop",pid:r.pid}):process.kill(r.pid,"SIGTERM")}catch{continue}v++,i.push({pid:r.pid,snap:S})}}const h=Date.now()+Rn;for(;Date.now()<h&&i.some(r=>Be(r.snap.tree.length>0?r.snap.tree:[r.pid]));)await new Promise(r=>setTimeout(r,Ke));let g=0;for(const r of i){const l=r.snap.tree.length>0?r.snap.tree:[r.pid];Be(l)&&(process.platform==="linux"&&R(D)?await A({operation:"stop",pid:r.pid}):He(l,"SIGKILL",r.snap.identities),g++)}g>0&&await new Promise(r=>setTimeout(r,Ke));const m=Oe();if(m===null)throw p({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness",stage:"final"}}),new Error("prior-epoch broker census could not capture the final process table");const u=[];for(const[r,l]of m.processes){const S=l.command;l.zombie||!S.includes("broker-cli.js")||we(S,f)&&ve(S)!==e&&u.push(r)}if(u.length>0)throw new Error(`prior-epoch broker census could not prove termination of pid(s): ${u.join(", ")}`);p({level:"info",event:"daemon.census.completed",fields:{prior_epoch_brokers:d.length,sigtermed:v,sigkilled:g}})}s(Pn,"reapPriorEpochBrokers");const En=5e3;async function In(e){const c=Array.from(e.entries());if(c.length===0)return;for(const[i]of c){const h=(await Lr(i))?.status;(h==="active"||h==="idle")&&await Ae(i,new Date().toISOString())}const f=c.map(([,i])=>({pid:i.pid,snap:Fe(i.pid,null),exited:i.handle.exited}));for(const i of f)if(!i.snap.reused)try{process.platform==="linux"&&R(D)?await A({operation:"stop",pid:i.pid}):process.kill(i.pid,"SIGTERM")}catch{}const d=new Promise(i=>{setTimeout(i,En).unref()});await Promise.allSettled(f.map(i=>Promise.race([i.exited.then(()=>{}),d])));const v=[];for(const i of f)Ot(i.pid)&&(process.platform==="linux"&&R(D)?await A({operation:"stop",pid:i.pid}):He(i.snap.tree.length>0?i.snap.tree:[i.pid],"SIGKILL",i.snap.identities),v.push(i));await Promise.all(v.map(i=>i.exited));for(const[i]of c)await vt(i,{reason:"daemon-teardown"});p({level:"info",event:"daemon.fleet_teardown.completed",fields:{brokers:f.length,sigkilled:v.length}})}s(In,"teardownFleet");function Ve(){Ee(vr(pe()),{recursive:!0}),ur(pe(),String(process.pid),"utf8")}s(Ve,"writePidfile");function Ye(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}s(Ye,"isMissingPathError");function Qe(e){const c=pe();let f;try{f=hr(c,"utf8")}catch(d){if(Ye(d))return;throw d}if(f.trim()!==String(e))throw new Error(`daemon readiness mirror does not name this invocation (expected pid ${e})`);try{wr(c)}catch(d){if(Ye(d))return;throw d}}s(Qe,"removeOwnedPidfileMirror");const xn={acceptsDetachedWork:s(()=>!0,"acceptsDetachedWork"),registerDetached:s(e=>{e.catch(()=>{})},"registerDetached")},X=new dt;lt(e=>X.handleFatalFault(e,!1));const Dn=new mt,Xe=new pt,Tn=new ft,Cn=new ut,Ln=new ht,$n=new wt,An=new bt,Nn=new kt,Mn=new Rt,Gn=new Pt,On=new It,Fn=new xt,Bn=new Dt,Hn=new Tt,jn=new Ct,zn=new Lt,Un=new $t,qn=new At;async function Wn(e=Date.now(),c=xn){const f=je(),d=await X.runFleetPreamble(f);let v,i,h;try{i=await fe();const m=(await $e()).filter(r=>!i.has(r.node_id));v=m.filter(r=>r.status==="active"||r.status==="idle"),h=m.filter(r=>r.status==="done"||r.status==="canceled"||r.status==="dead");const u=new Set(h.map(r=>r.node_id));h.push(...(await Ar()).filter(r=>!u.has(r.node_id)&&!i.has(r.node_id)))}catch(m){p({level:"error",event:"canvas.node_list.failed",error:m});return}await X.run(e,{rows:v,fleet:f,lifecycle:c,held:i}),await Dn.run(e,{rows:v,held:i});const g=await Xe.run(e,{rows:[...v,...h],fleet:f});await Tn.run(e,i),await Un.run(e,i),await qn.run(e,{lifecycle:c}),await Cn.run(e,{lifecycle:c,held:i}),await Ln.run(e,{lifecycle:c}),await $n.run(e,{lifecycle:c}),await An.run(e,{lifecycle:c}),await Nn.run(e,{lifecycle:c,fleet:f,held:i}),Mn.run(e,{lifecycle:c}),Gn.run(e,{lifecycle:c}),On.run(e,{lifecycle:c}),Fn.run(e,{lifecycle:c}),Bn.run(e,{lifecycle:c}),Hn.run(e,{lifecycle:c}),await br(),zn.run(e,{fleet:f,lifecycle:c}),await jn.run(e,{rows:v}),X.warnIfSaturated({fleet:f,lifecycle:c,thresholds:d,frozen:g})}s(Wn,"superviseTick");async function Jn(e,c=Date.now()){if((await fe()).has(e))return;const f=await yt(e);if(f===null||!gt(f))return;const d=await $r(e);d===null||d.kind==="human"||await Xe.runNode(c,d,je())}s(Jn,"exitedNodePass");function j(e){return e===void 0||e==="reconcile"}s(j,"roleRunsLanes");function M(e){return e===void 0||e==="api"}s(M,"roleServesRequests");const Kn=66e4;function Vn(e){const c=new Mr().registerAll(Gr(()=>null).filter(r=>r.pattern==="/healthz")),f=s((r,l)=>{const S=(r.url??"/").split("?")[0];if((r.method??"GET").toUpperCase()==="GET"&&S==="/healthz"){c.handle(r,l,null,{class:"person"});return}l.writeHead(404,{"content-type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:{code:"not_found",message:"this process serves only /healthz",origin:"runtime"}}))},"handler"),d=Ce();R(d)&&Ie(d);const v=Q(f),i=new Promise((r,l)=>{v.once("error",l),v.listen(d,()=>{v.off("error",l),xe(d,384),r()})});let h,g=null;const m=e.tcp??De()??me("user").api.tcp;if(m!==void 0&&m!==""){const r=/^(.*):(\d+)$/.exec(m.trim());if(r===null||Number(r[2])>65535)throw new Error(`invalid reconcile probe TCP address: ${m}`);const l=Q(f);l.on("error",S=>p({event:"api.server.failed",level:"error",error:S})),l.listen(Number(r[2]),r[1]===""?"0.0.0.0":r[1],()=>{g=`${r[1]===""?"0.0.0.0":r[1]}:${r[2]}`}),h=l}let u=!1;return{ready:i,tcpAddress:s(()=>g,"tcpAddress"),async close(r={}){if(!u){u=!0,await Promise.all([Ne(v,new Set,r.graceMs),h===void 0?Promise.resolve():Ne(h,new Set,r.graceMs)]);try{R(d)&&Ie(d)}catch{}}}}}s(Vn,"createProbeServer");const Yn="daemon is draining for shutdown and admits no new work";async function Qn(e){Ee(Le(),{recursive:!0,mode:493}),process.platform==="linux"&&xe(Le(),493);const c=Ce();if(R(c))throw new Error(`layout refusal cannot bind occupied socket: ${c}`);const f=Q((m,u)=>{if(m.method==="GET"&&m.url==="/healthz"){u.writeHead(200,{"content-type":"application/json; charset=utf-8"}),u.end(JSON.stringify({ok:!1,daemon_up:!0,store_accessible:!1,brokers_reconciled:!1,startup_phase:"blocked",startup_blocked:"layout_migration_required"}));return}u.writeHead(503,{"content-type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:{code:"layout_migration_required",message:"run crtr sys migrate while the runtime is offline",type:"server_error",origin:"runtime",retryable:!1}}))});await new Promise((m,u)=>{f.once("error",u),f.listen(c,()=>{f.off("error",u),m()})});let d;const v=e.tcp??De();if(v){const m=/^(.*):(\d+)$/.exec(v);if(!m||Number(m[2])>65535)throw new Error(`invalid refusal TCP address: ${v}`);const u=Q(f.listeners("request")[0]);await new Promise((r,l)=>{u.once("error",l),u.listen(Number(m[2]),m[1],()=>{u.off("error",l),r()})}),d=u}Ve();let i;const h=s(()=>(i??=(async()=>{f.closeAllConnections(),d?.closeAllConnections(),await Promise.all([f,d].filter(m=>m!==void 0).map(m=>new Promise((u,r)=>m.close(l=>l?r(l):u())))),Qe(process.pid),process.off("SIGINT",g),process.off("SIGTERM",g)})(),i),"cleanup"),g=s(()=>{h().then(()=>process.exit(0),m=>{process.stderr.write(`[crtrd] layout refusal cleanup failed: ${String(m)}
2
+ `),process.exit(1)})},"onSignal");return process.on("SIGINT",g),process.on("SIGTERM",g),h}s(Qn,"serveLayoutRefusal");async function Xn(e={}){if(e.role==="machine")return(await import("./machine-daemon.js")).runMachineDaemon();if(Dr())return Qn(e);xr();const c=s(n=>{process.stderr.write(`[crtrd] ${n}
3
+ `)},"logPostgres"),f=!!process.env.CRTR_TEST_PG_URL,d=Kt(e.role);nn(j(e.role));const v=s(async()=>d?await Jt(Te(16).toString("hex")):{claimed:!0,claim:{pid:process.pid,pid_identity:"",token:Te(16).toString("hex")}},"claimOwnership"),{database:i,ownership:h}=f?{database:{url:await Yt()},ownership:await v()}:await rn(async()=>({database:await Xt({log:c,startLockHeld:!0}),ownership:await v()}));if(!h.claimed){if(h.reason==="incumbent_alive")process.stderr.write(`[crtrd] already running (pid ${h.incumbentPid??"?"})
4
4
  `);else{const n=[h.incumbentPid!==void 0?`pid ${h.incumbentPid}`:void 0,h.verdict!==void 0?`verdict ${h.verdict}`:void 0].filter(w=>w!==void 0),a=n.length>0?` (${n.join(", ")})`:"";process.stderr.write(`[crtrd] claim lost: ${h.reason}${a}
5
- `),h.reason==="own_identity_indeterminate"&&process.stderr.write("[crtrd] cannot read its own process identity. crouter needs /proc on Linux, or the `ps` command elsewhere (Debian/Ubuntu: apt-get install procps).\n"),(h.reason==="own_identity_indeterminate"||h.reason==="incumbent_malformed")&&(process.exitCode=1)}return async()=>{}}const g=h.claim;let d=null,f=null,r=null,l=null,y,P="";try{p&&await yn(g.token);for(const t of xr())process.stderr.write(`[crtrd] ${t}
6
- `);for(const t of await Ir())process.stderr.write(`[crtrd] ${t}
7
- `);await je(),await Wt(i.url,c);const n=e.role===void 0&&!await wn();let a=null;n&&(hn({kind:"user",root:qe()}),a=vn(qe())),e.role===void 0&&gn(a??{profiles:[],defaults:{},settings:{},state:{},apps:{}}),await H.listen(i.url);const w=s(t=>{Ue(t).catch(o=>m({level:"error",event:"daemon.settings.reload_failed",error:o}))},"reloadPerson");if(y=await H.subscribe(t=>{ze().includes(t)&&w(t)},{kinds:["settings"],onListenStart:s(()=>{for(const t of ze())w(t)},"onListenStart")}),e.role!==void 0&&Fr(),e.role!==void 0){let t;try{t=tn()}catch(b){m({level:"error",event:"daemon.packages.snapshot_failed",error:b})}const o=await fe(async b=>(await Ae(b),t===void 0?void 0:await rn(b,t,"release")));l=await fe(async b=>await en(b));for(const b of o?.invalid??[])process.stderr.write(`[crtrd] package file is not a document: ${b.path}: ${b.error}
8
- `)}else{const t=await fe(async o=>(await Ae(o),await Zt(o)));for(const o of t.conflicts)process.stderr.write(`[crtrd] plugin documents not reconciled: ${o.message}
5
+ `),h.reason==="own_identity_indeterminate"&&process.stderr.write("[crtrd] cannot read its own process identity. crouter needs /proc on Linux, or the `ps` command elsewhere (Debian/Ubuntu: apt-get install procps).\n"),(h.reason==="own_identity_indeterminate"||h.reason==="incumbent_malformed")&&(process.exitCode=1)}return async()=>{}}const g=h.claim;let m=null,u=null,r=null,l=null,S,P="";try{d&&await Pn(g.token);for(const t of Cr())process.stderr.write(`[crtrd] ${t}
6
+ `);for(const t of await Tr())process.stderr.write(`[crtrd] ${t}
7
+ `);await Ue(),await Qt(i.url,c);const n=e.role===void 0&&!await _n();let a=null;n&&(Sn({kind:"user",root:Je()}),a=bn(Je())),e.role===void 0&&kn(a??{profiles:[],defaults:{},settings:{},state:{},apps:{}}),await N.listen(i.url);const w=s(t=>{We(t).catch(o=>p({level:"error",event:"daemon.settings.reload_failed",error:o}))},"reloadPerson");if(S=await N.subscribe(t=>{qe().includes(t)&&w(t)},{kinds:["settings"],onListenStart:s(()=>{for(const t of qe())w(t)},"onListenStart")}),e.role!==void 0&&zr(),e.role!==void 0){let t;try{t=cn()}catch(b){p({level:"error",event:"daemon.packages.snapshot_failed",error:b})}const o=await he(async b=>(await Me(b),t===void 0?void 0:await sn(b,t,"release")));l=await he(async b=>await an(b));for(const b of o?.invalid??[])process.stderr.write(`[crtrd] package file is not a document: ${b.path}: ${b.error}
8
+ `)}else{const t=await he(async o=>(await Me(o),await on(o)));for(const o of t.conflicts)process.stderr.write(`[crtrd] plugin documents not reconciled: ${o.message}
9
9
  `);for(const o of t.invalid)process.stderr.write(`[crtrd] package file is not a document: ${o.path}: ${o.error}
10
10
  `);for(const o of t.quarantined)process.stderr.write(`[crtrd] plugin "${o.name}" has a damaged ${o.file} (${o.reason}); ${o.movedTo!==void 0?`moved to ${o.movedTo}`:"left in place and skipped"}
11
11
  `);for(const o of t.kinds.refused)process.stderr.write(`[crtrd] plugin "${o.plugin}" kind ${o.kind} not registered: ${o.message}
12
12
  `);for(const o of t.kinds.invalid)process.stderr.write(`[crtrd] plugin "${o.plugin}" declares invalid object kinds or scopes; no kinds registered and no app token: ${o.error}
13
- `)}if(P=await Bt(),Ht(P),e.role===void 0&&(d=await Br(),d!==null)){if(jr(d.id),await un(d.id),process.platform==="darwin"){const{readConfig:t,updateConfig:o}=await import("../core/config.js");if(t("user").paths?.user_files===void 0){const{homedir:b}=await import("node:os");await o("user",ke=>{ke.paths??={},ke.paths.user_files??=b()})}}f=await Hr(),f.joinedFrom!==null&&await Ue(f.person),await sr(),r=await zr()}if(process.platform==="linux"&&R(D)&&(Rr(),await A({operation:"users.sync",users:await _r()})),p){await ht(g.token);const t=await cn();Object.values(t).some(o=>o>0)&&process.stderr.write(`[crtrd] node files copied into rows: ${JSON.stringify(t)}
14
- `)}}catch(n){await H.close();try{if(p){const{released:a}=await He(g);if(!a)throw new Error("daemon ownership claim was not released")}await pe()}catch(a){throw new AggregateError([n,a],"daemon startup failed and cleanup also failed")}throw n}let T=!0,X,z=Promise.resolve(),Z=!1,U,ee,re,C;const q=new Set;let te=!1,we=!1,E,L,ne,W=!1,J,M,G,O,F,oe,ie,ae,se;const Ye=ot();let I,S={phase:"initializing",message:"daemon startup is running the canvas import and normal services are unavailable",blockerPaths:[]},$="initial startup activation",Qe=null;function Xe(){return S.phase==="ready"?null:{phase:S.phase,message:S.message,blockerPaths:S.blockerPaths}}s(Xe,"startupBlock");function k(n){q.add(n),n.finally(()=>{q.delete(n)}).catch(()=>{})}s(k,"registerDetached");const ve={acceptsDetachedWork:s(()=>T,"acceptsDetachedWork"),registerDetached:k};j(e.role)&&await nn(ve,je);async function Ze(){try{T=!1,Qt.close(),ee?.(),ee=void 0,re?.(),y?.(),re=void 0,ae?.(),ae=void 0,await H.close(),U!==void 0&&(clearInterval(U),U=void 0),G!==void 0&&(clearInterval(G),G=void 0),O!==void 0&&(clearInterval(O),O=void 0),se?.(),se=void 0;let n;do n=z,await n;while(n!==z);for(;q.size>0;)await Promise.allSettled([...q]);if(C!==void 0&&(p&&await bn(C),await C.exitsSettled(),C.dispose()),ne!==void 0&&await ne.close(),L!==void 0&&!W&&(W=!0,await L.close()),oe?.(),oe=void 0,ie?.(),ie=void 0,F!==void 0){const a=F;F=void 0,await a.stop()}if(M!==void 0){const a=M;M=void 0,await a.close()}if(J!==void 0){const a=J;J=void 0,await a.close()}if(te||(Ve(process.pid),te=!0),te&&!we){if(p){const{released:a}=await He(g);if(!a)throw new Error("daemon ownership claim was not released")}we=!0,await pe()}}finally{Mt(),process.off("SIGINT",ye),process.off("SIGTERM",_e),process.off("exit",be)}}s(Ze,"cleanupAttempt");const K=1e3;let ge=!1;function er(){if(e.role!==void 0)throw new Error(`a ${e.role} daemon never hands over to a successor: its orchestrator replaces it`);return ge?{graceMs:K}:(ge=!0,_.fresh(()=>{m({level:"info",event:"daemon.handover.armed",fields:{pid:process.pid,grace_ms:K}})}),setTimeout(()=>{rr()},K),{graceMs:K})}s(er,"requestHandover");async function rr(){try{await x()}catch(n){const a=n instanceof Error?n.stack??n.message:String(n);process.stderr.write(`[crtrd] handover cleanup failed:
13
+ `)}if(P=await qt(),Wt(P),e.role===void 0&&(m=await Ur(),m!==null)){if(Wr(m.id),await yn(m.id),process.platform==="darwin"){const{readConfig:t,updateConfig:o}=await import("../core/config.js");if(t("user").paths?.user_files===void 0){const{homedir:b}=await import("node:os");await o("user",Pe=>{Pe.paths??={},Pe.paths.user_files??=b()})}}u=await qr(),u.joinedFrom!==null&&await We(u.person),await dr(),r=await Jr()}if(process.platform==="linux"&&R(D)&&(Ir(),await A({operation:"users.sync",users:await Rr()})),d){await _t(g.token);const t=await fn();Object.values(t).some(o=>o>0)&&process.stderr.write(`[crtrd] node files copied into rows: ${JSON.stringify(t)}
14
+ `)}}catch(n){await N.close();try{if(d){const{released:a}=await ze(g);if(!a)throw new Error("daemon ownership claim was not released")}await ue()}catch(a){throw new AggregateError([n,a],"daemon startup failed and cleanup also failed")}throw n}let T=!0,Z,z=Promise.resolve(),ee=!1,U,re,te,ne,C;const q=new Set;let oe=!1,ge=!1,E,L,ie,W=!1,J,G,O,F,B,ae,se,ce,le;const Ze=ct();let I,y={phase:"initializing",message:"daemon startup is running the canvas import and normal services are unavailable",blockerPaths:[]},$="initial startup activation",er=null;function rr(){return y.phase==="ready"?null:{phase:y.phase,message:y.message,blockerPaths:y.blockerPaths}}s(rr,"startupBlock");function k(n){q.add(n),n.finally(()=>{q.delete(n)}).catch(()=>{})}s(k,"registerDetached");const ye={acceptsDetachedWork:s(()=>T,"acceptsDetachedWork"),registerDetached:k};j(e.role)&&await ln(ye,Ue);async function tr(){try{T=!1,tn.close(),re?.(),re=void 0,te?.(),S?.(),te=void 0,ne?.(),ne=void 0,ce?.(),ce=void 0,await N.close(),U!==void 0&&(clearInterval(U),U=void 0),O!==void 0&&(clearInterval(O),O=void 0),F!==void 0&&(clearInterval(F),F=void 0),le?.(),le=void 0;let n;do n=z,await n;while(n!==z);for(;q.size>0;)await Promise.allSettled([...q]);if(C!==void 0&&(d&&await In(C),await C.exitsSettled(),C.dispose()),ie!==void 0&&await ie.close(),L!==void 0&&!W&&(W=!0,await L.close()),ae?.(),ae=void 0,se?.(),se=void 0,B!==void 0){const a=B;B=void 0,await a.stop()}if(G!==void 0){const a=G;G=void 0,await a.close()}if(J!==void 0){const a=J;J=void 0,await a.close()}if(oe||(Qe(process.pid),oe=!0),oe&&!ge){if(d){const{released:a}=await ze(g);if(!a)throw new Error("daemon ownership claim was not released")}ge=!0,await ue()}}finally{Ht(),process.off("SIGINT",be),process.off("SIGTERM",ke),process.off("exit",Re)}}s(tr,"cleanupAttempt");const K=1e3;let Se=!1;function nr(){if(e.role!==void 0)throw new Error(`a ${e.role} daemon never hands over to a successor: its orchestrator replaces it`);return Se?{graceMs:K}:(Se=!0,_.fresh(()=>{p({level:"info",event:"daemon.handover.armed",fields:{pid:process.pid,grace_ms:K}})}),setTimeout(()=>{or()},K),{graceMs:K})}s(nr,"requestHandover");async function or(){try{await x()}catch(n){const a=n instanceof Error?n.stack??n.message:String(n);process.stderr.write(`[crtrd] handover cleanup failed:
15
15
  ${a}
16
- `),process.exit(1)}try{process.platform==="linux"&&R(D)&&(await A({operation:"daemon.handover"}),process.exit(0)),process.pid===1&&await Gt();const n=await Ot({waitForJoinLock:!0});_.fresh(()=>{m({level:"info",event:"daemon.handover.completed",fields:{predecessor_pid:process.pid,successor_pid:n.pid??n.existing_pid??null,spawned:n.started}})})}catch(n){_.fresh(()=>{m({level:"error",event:"daemon.handover.successor_failed",error:n})});const a=n instanceof Error?n.message:String(n);process.stderr.write(`[crtrd] handover successor failed to start: ${a}
17
- `),process.exit(1)}process.exit(0)}s(rr,"performHandover");function x(){if(E!==void 0)return E;const n=Ze();return E=n,n.then(()=>{E===n&&(E=void 0)},()=>{E===n&&(E=void 0)}),n}s(x,"requestCleanup");async function tr(){S={phase:"initializing",message:qn,blockerPaths:[]},L!==void 0&&!W&&(W=!0,await L.close({graceMs:zn}))}s(tr,"drainApi");async function Se(n){try{n==="SIGTERM"&&e.role==="api"&&await tr(),await x(),await Vt({claimed:s(async()=>{try{return p&&await Ut()}finally{await pe()}},"claimed")}),process.exit(0)}catch(a){process.exitCode=1;const w=a instanceof Error?a.stack??`${a.name}: ${a.message}`:String(a);process.stderr.write(`[crtrd] ${n} cleanup failed:
16
+ `),process.exit(1)}try{process.platform==="linux"&&R(D)&&(await A({operation:"daemon.handover"}),process.exit(0)),process.pid===1&&await jt();const n=await zt({waitForJoinLock:!0});_.fresh(()=>{p({level:"info",event:"daemon.handover.completed",fields:{predecessor_pid:process.pid,successor_pid:n.pid??n.existing_pid??null,spawned:n.started}})})}catch(n){_.fresh(()=>{p({level:"error",event:"daemon.handover.successor_failed",error:n})});const a=n instanceof Error?n.message:String(n);process.stderr.write(`[crtrd] handover successor failed to start: ${a}
17
+ `),process.exit(1)}process.exit(0)}s(or,"performHandover");function x(){if(E!==void 0)return E;const n=tr();return E=n,n.then(()=>{E===n&&(E=void 0)},()=>{E===n&&(E=void 0)}),n}s(x,"requestCleanup");async function ir(){y={phase:"initializing",message:Yn,blockerPaths:[]},L!==void 0&&!W&&(W=!0,await L.close({graceMs:Kn}))}s(ir,"drainApi");async function _e(n){try{n==="SIGTERM"&&e.role==="api"&&await ir(),await x(),await en({claimed:s(async()=>{try{return d&&await Vt()}finally{await ue()}},"claimed")}),process.exit(0)}catch(a){process.exitCode=1;const w=a instanceof Error?a.stack??`${a.name}: ${a.message}`:String(a);process.stderr.write(`[crtrd] ${n} cleanup failed:
18
18
  ${w}
19
- `),process.exit(1)}}s(Se,"handleSignal");function ye(){Se("SIGINT")}s(ye,"onSigint");function _e(){Se("SIGTERM")}s(_e,"onSigterm");function be(){x().catch(()=>{})}s(be,"onExit");async function ce(n){T&&(z=z.then(n).then(()=>{},a=>{_.fresh(()=>{m({level:"error",event:"daemon.lane_job.failed",error:a})})}))}s(ce,"enqueue");async function V(){!T||Z||(Ye.check()&&I&&(m({level:"info",event:"daemon.resume.detected"}),k(I().catch(()=>{}))),Z=!0,await ce(async()=>{if(Z=!1,!!T)try{u||await Kt({log:c}),await jn(Date.now(),ve)}catch(n){_.fresh(()=>{m({level:"error",event:"daemon.tick.failed",error:n})})}}))}s(V,"enqueueTick");let B=null;async function nr(){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 n=S.phase==="prepared";try{return await le(),S={phase:"ready",message:"",blockerPaths:[]},n?{admitted:!0,already_admitted:!1,startup_phase:"ready"}:{admitted:!1,already_admitted:!0,startup_phase:"ready"}}catch(a){throw B=a,{status:500,code:"admission_failed",message:`daemon admission failed: ${a instanceof Error?a.message:String(a)}`}}}s(nr,"admitStartup");async function or(n){if($!==null)throw{status:409,code:"migration_in_progress",message:`the canvas import is already running (${$})`};$="repair";try{const a=await fn({dryRun:n.dryRun});if(n.dryRun||a.pending||S.phase!=="blocked")return{result:a,resumed:!1};if(e.prepare)return S={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]},{result:a,resumed:!1};try{return await le(),S={phase:"ready",message:"",blockerPaths:[]},{result:a,resumed:!0}}catch(w){const t=w instanceof Error?w.message:String(w);return setTimeout(()=>{x().catch(()=>{})},1e3),{result:a,resumed:!1,resumeError:t}}}finally{$=null}}s(or,"repairMigrations");async function ir(){X=e.intervalMs??nt;const n=g.token;C=new sn({epoch:n,enqueue:ce}),$t(C),S={phase:"recovering",message:"daemon startup recovery is running and normal services are unavailable",blockerPaths:[]},_.fresh(()=>{m({level:"info",event:"daemon.started",fields:{pid:process.pid,interval_ms:X}})});const a=P;_.fresh(()=>{m({level:"info",event:"daemon.install_id.resolved",fields:{install_id:a}})});const w=await Gr(a);if(_.fresh(()=>{m({level:"info",event:"daemon.environment.registered",fields:{environment_id:w.environmentId,created:w.created}})}),_.fresh(()=>{let t;try{t=tt()}catch{return}t!==null&&m({level:"warn",event:"daemon.startup.warning",fields:{stage:"termrender",warning:t.slice(0,2048)}})}),yt(),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&&Or(),!j(e.role)){S={phase:"ready",message:"",blockerPaths:[]};return}if(await _.fresh(async()=>{await rt(),await Xr(),await Zr(Date.now()),await et(Date.now())}),e.role===void 0&&await _.fresh(async()=>{const{reconcile:t,migrated:o}=await Ft(ut);t.changed&&m({level:"info",event:"daemon.boot_change.reconciled",fields:{cleared_count:t.cleared.length,same_boot_proven:t.sameBootProven}}),o.length>0&&m({level:"info",event:"daemon.pid_identity.migrated",fields:{migrated_count:o.length}})}),await _.fresh(async()=>{const t=await Me();for(const o of await Ce())t.has(o.node_id)||o.status!=="active"||o.pi_pid!=null||o.frozen_at!=null||o.respawn_not_before!=null||(await Le(o.node_id,new Date().toISOString()),m({level:"warn",event:"daemon.startup.launch_debt_recorded",node_id:o.node_id}))}),await _.fresh(async()=>{await Tt();for(const t of ln){const o=await t.apply();o.changed&&m({level:"info",event:"daemon.boot_migration.applied",fields:{migration:t.id,...o.summary}})}}),k(Yr()),I){const t=s(()=>{k(I().catch(()=>{})),k(lr().then(o=>F?.observe(o)).then(()=>{},o=>{m({level:"warn",event:"daemon.peer.status_failed",error:o})}))},"refresh");k(Vr().then(({completion:o})=>o).catch(o=>{m({level:"error",event:"daemon.grants.sweep_failed",error:o})})),t(),G=setInterval(t,Ne*1e3),G.unref(),se=cr({joined:!0,register:k})}await ce(async()=>{await an(),await on()}),U=setInterval(()=>{V().catch(t=>m({level:"error",event:"daemon.tick.failed",error:t}))},X),ee=await Dt(()=>{V().catch(t=>m({level:"error",event:"daemon.tick.failed",error:t}))}),re=await H.subscribe(()=>{V().catch(t=>m({level:"error",event:"daemon.tick.failed",error:t}))},{kinds:["spend_limits"]}),await V(),e.role===void 0&&import("../commands/sys/import/move.js").then(({settleMoveAtDaemonStart:t})=>t(()=>!T,o=>m({level:"warn",event:"daemon.move.settle_failed",error:o}))).catch(t=>m({level:"warn",event:"daemon.move.settle_failed",error:t}))}s(ir,"completeStartup");function le(){return Qe??=ir().catch(n=>{throw S={phase:"initializing",message:"daemon startup recovery failed and normal services are unavailable",blockerPaths:[]},n})}s(le,"resumeStartup");try{process.on("SIGINT",ye),process.on("SIGTERM",_e),process.on("exit",be),dn(),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}}),r!==null&&m({level:"info",event:"daemon.permissions.boot",fields:{...r}}),f!==null&&m({level:"info",event:"daemon.person.retired",fields:{person_id:f.person,joined_from:f.joinedFrom,retired:f.retired,columns:f.columns}}),N(e.role)?J=await vr():gr(wr());const n=g.token;Nt({epoch:n,requestHandover:er,registerDetached:k,startupBlock:Xe,admitStartup:nr,repairMigrations:or}),Je(),L=N(e.role)?Cr({tcp:e.tcp}):Un(e),await L.ready;const a=hr()??de("user").document_port;if(N(e.role)){const t=Ar(a,Nr());try{await t.ready,ne=t}catch(o){m({level:"warn",event:"daemon.document_listener.bind_failed",fields:{port:a,error:o instanceof Error?o.message:String(o)}})}}const w=de("user").runtime;if(w?.issuer&&(I=Kr(w.issuer,k),w.unsandboxed===!0&&(F=dr({syncGrants:I}))),e.role==="api"){const t=s(()=>k(Wr().catch(o=>{m({level:"error",event:"daemon.packages.sync_failed",error:o})})),"packageTick");t(),O=setInterval(t,Ne*1e3),O.unref()}if(N(e.role)&&(oe=await Ur()),j(e.role)&&(ie=Jr()),ae=await qr({serves:N(e.role),runsLanes:j(e.role)}),w?.unsandboxed===!0&&w.listener!==void 0&&m({level:"warn",event:"daemon.app_listener.refused_unsandboxed",fields:{reason:"runtime.unsandboxed is set; runtime.listener is ignored"}}),N(e.role)&&w!==void 0&&w.listener!==void 0&&w.unsandboxed!==!0&&(M=await Mr(w,async()=>await Qr(w.issuer.replace(/\/$/,"")),I),await M.ready),e.role===void 0)try{await mn()}catch(t){if($=null,t instanceof pn)return S={phase:"blocked",message:t.message,blockerPaths:t.blockerPaths},x;throw t}process.platform==="linux"&&R(D)&&(kr(),await br("app:terminal"));try{e.prepare?S={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]}:(await le(),S={phase:"ready",message:"",blockerPaths:[]})}finally{$=null}return x}catch(n){try{await x()}catch(a){throw new AggregateError([n,a],"daemon startup failed and cleanup also failed")}throw n}}s(Jn,"runDaemon");var Ki=Jn;export{zn as API_DRAIN_GRACE_MS,Qi as brokerCommandDeclaresCanvasHome,he as brokerCommandEpoch,Ki as default,j as roleRunsLanes,N as roleServesRequests,Jn as runDaemon,jn as superviseTick,bn as teardownFleet};
19
+ `),process.exit(1)}}s(_e,"handleSignal");function be(){_e("SIGINT")}s(be,"onSigint");function ke(){_e("SIGTERM")}s(ke,"onSigterm");function Re(){x().catch(()=>{})}s(Re,"onExit");async function V(n){T&&(z=z.then(n).then(()=>{},a=>{_.fresh(()=>{p({level:"error",event:"daemon.lane_job.failed",error:a})})}))}s(V,"enqueue");async function Y(){!T||ee||(Ze.check()&&I&&(p({level:"info",event:"daemon.resume.detected"}),k(I().catch(()=>{}))),ee=!0,await V(async()=>{if(ee=!1,!!T)try{f||await Zt({log:c}),await Wn(Date.now(),ye)}catch(n){_.fresh(()=>{p({level:"error",event:"daemon.tick.failed",error:n})})}}))}s(Y,"enqueueTick");let H=null;async function ar(){if(H!==null)throw{status:500,code:"admission_failed",message:`daemon admission previously failed: ${H instanceof Error?H.message:String(H)}`};if(y.phase==="ready")return{admitted:!1,already_admitted:!0,startup_phase:"ready"};if(y.phase!=="prepared"&&y.phase!=="recovering")throw{status:409,code:"not_prepared",message:y.message};const n=y.phase==="prepared";try{return await de(),y={phase:"ready",message:"",blockerPaths:[]},n?{admitted:!0,already_admitted:!1,startup_phase:"ready"}:{admitted:!1,already_admitted:!0,startup_phase:"ready"}}catch(a){throw H=a,{status:500,code:"admission_failed",message:`daemon admission failed: ${a instanceof Error?a.message:String(a)}`}}}s(ar,"admitStartup");async function sr(n){if($!==null)throw{status:409,code:"migration_in_progress",message:`the canvas import is already running (${$})`};$="repair";try{const a=await gn({dryRun:n.dryRun});if(n.dryRun||a.pending||y.phase!=="blocked")return{result:a,resumed:!1};if(e.prepare)return y={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]},{result:a,resumed:!1};try{return await de(),y={phase:"ready",message:"",blockerPaths:[]},{result:a,resumed:!0}}catch(w){const t=w instanceof Error?w.message:String(w);return setTimeout(()=>{x().catch(()=>{})},1e3),{result:a,resumed:!1,resumeError:t}}}finally{$=null}}s(sr,"repairMigrations");async function cr(){Z=e.intervalMs??st;const n=g.token;C=new pn({epoch:n,enqueue:V}),Ft(C),y={phase:"recovering",message:"daemon startup recovery is running and normal services are unavailable",blockerPaths:[]},_.fresh(()=>{p({level:"info",event:"daemon.started",fields:{pid:process.pid,interval_ms:Z}})});const a=P;_.fresh(()=>{p({level:"info",event:"daemon.install_id.resolved",fields:{install_id:a}})});const w=await Hr(a);if(_.fresh(()=>{p({level:"info",event:"daemon.environment.registered",fields:{environment_id:w.environmentId,created:w.created}})}),_.fresh(()=>{let t;try{t=at()}catch{return}t!==null&&p({level:"warn",event:"daemon.startup.warning",fields:{stage:"termrender",warning:t.slice(0,2048)}})}),Et(),e.role!==void 0&&!process.env.CRTR_DIRECTORY_URL)throw new Error("CRTR_DIRECTORY_URL must be set on a cloud role (--role api|reconcile): it names the directory this deployment mints tokens against");if(e.role!==void 0&&jr(),!j(e.role)){y={phase:"ready",message:"",blockerPaths:[]};return}if(await _.fresh(async()=>{await it(),await tt(),await nt(Date.now()),await ot(Date.now())}),e.role===void 0&&await _.fresh(async()=>{const{reconcile:t,migrated:o}=await Ut(St);t.changed&&p({level:"info",event:"daemon.boot_change.reconciled",fields:{cleared_count:t.cleared.length,same_boot_proven:t.sameBootProven}}),o.length>0&&p({level:"info",event:"daemon.pid_identity.migrated",fields:{migrated_count:o.length}})}),await _.fresh(async()=>{const t=await fe();for(const o of await $e())t.has(o.node_id)||o.status!=="active"||o.pi_pid!=null||o.frozen_at!=null||o.respawn_not_before!=null||(await Ae(o.node_id,new Date().toISOString()),p({level:"warn",event:"daemon.startup.launch_debt_recorded",node_id:o.node_id}))}),await _.fresh(async()=>{await Mt();for(const t of un){const o=await t.apply();o.changed&&p({level:"info",event:"daemon.boot_migration.applied",fields:{migration:t.id,...o.summary}})}}),k(et()),I){const t=s(()=>{k(I().catch(()=>{})),k(pr().then(o=>B?.observe(o)).then(()=>{},o=>{p({level:"warn",event:"daemon.peer.status_failed",error:o})}))},"refresh");k(Zr().then(({completion:o})=>o).catch(o=>{p({level:"error",event:"daemon.grants.sweep_failed",error:o})})),t(),O=setInterval(t,Ge*1e3),O.unref(),le=mr({joined:!0,register:k})}await V(async()=>{await mn(),await dn()}),U=setInterval(()=>{Y().catch(t=>p({level:"error",event:"daemon.tick.failed",error:t}))},Z),re=await Nt(()=>{Y().catch(t=>p({level:"error",event:"daemon.tick.failed",error:t}))}),te=await N.subscribe(()=>{Y().catch(t=>p({level:"error",event:"daemon.tick.failed",error:t}))},{kinds:["spend_limits"]}),ne=await N.subscribe(t=>{V(()=>_.fresh(()=>Jn(t)))},{kinds:["execution_exit"]}),await Y(),e.role===void 0&&import("../commands/sys/import/move.js").then(({settleMoveAtDaemonStart:t})=>t(()=>!T,o=>p({level:"warn",event:"daemon.move.settle_failed",error:o}))).catch(t=>p({level:"warn",event:"daemon.move.settle_failed",error:t}))}s(cr,"completeStartup");function de(){return er??=cr().catch(n=>{throw y={phase:"initializing",message:"daemon startup recovery failed and normal services are unavailable",blockerPaths:[]},n})}s(de,"resumeStartup");try{process.on("SIGINT",be),process.on("SIGTERM",ke),process.on("exit",Re),hn(),m!==null&&p({level:"info",event:"daemon.person.resolved",fields:{person_id:m.id,source:m.source}}),l!==null&&!l.alreadyDone&&p({level:"info",event:"daemon.packages.install_migration_done",fields:{moved:l.moved,discarded:l.discarded,people:l.people}}),r!==null&&p({level:"info",event:"daemon.permissions.boot",fields:{...r}}),u!==null&&p({level:"info",event:"daemon.person.retired",fields:{person_id:u.person,joined_from:u.joinedFrom,retired:u.retired,columns:u.columns}}),M(e.role)?J=await Sr():_r(yr());const n=g.token;Bt({epoch:n,requestHandover:nr,registerDetached:k,startupBlock:rr,admitStartup:ar,repairMigrations:sr}),Ve(),L=M(e.role)?Nr({tcp:e.tcp}):Vn(e),await L.ready;const a=gr()??me("user").document_port;if(M(e.role)){const t=Or(a,Fr());try{await t.ready,ie=t}catch(o){p({level:"warn",event:"daemon.document_listener.bind_failed",fields:{port:a,error:o instanceof Error?o.message:String(o)}})}}const w=me("user").runtime;if(w?.issuer&&(I=Xr(w.issuer,k),w.unsandboxed===!0&&(B=fr({syncGrants:I}))),e.role==="api"){const t=s(()=>k(Yr().catch(o=>{p({level:"error",event:"daemon.packages.sync_failed",error:o})})),"packageTick");t(),F=setInterval(t,Ge*1e3),F.unref()}if(M(e.role)&&(ae=await Kr()),j(e.role)&&(se=Qr()),ce=await Vr({serves:M(e.role),runsLanes:j(e.role)}),w?.unsandboxed===!0&&w.listener!==void 0&&p({level:"warn",event:"daemon.app_listener.refused_unsandboxed",fields:{reason:"runtime.unsandboxed is set; runtime.listener is ignored"}}),M(e.role)&&w!==void 0&&w.listener!==void 0&&w.unsandboxed!==!0&&(G=await Br(w,async()=>await rt(w.issuer.replace(/\/$/,"")),I),await G.ready),e.role===void 0)try{await wn()}catch(t){if($=null,t instanceof vn)return y={phase:"blocked",message:t.message,blockerPaths:t.blockerPaths},x;throw t}process.platform==="linux"&&R(D)&&(Er(),await Pr("app:terminal"));try{e.prepare?y={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]}:(await de(),y={phase:"ready",message:"",blockerPaths:[]})}finally{$=null}return x}catch(n){try{await x()}catch(a){throw new AggregateError([n,a],"daemon startup failed and cleanup also failed")}throw n}}s(Xn,"runDaemon");var Zi=Xn;export{Kn as API_DRAIN_GRACE_MS,ta as brokerCommandDeclaresCanvasHome,ve as brokerCommandEpoch,Zi as default,Jn as exitedNodePass,j as roleRunsLanes,M as roleServesRequests,Xn as runDaemon,Wn as superviseTick,In as teardownFleet};
@@ -1 +1 @@
1
- var _=Object.defineProperty;var c=(e,n)=>_(e,"name",{value:n,configurable:!0});import{chmodSync as M,existsSync as S,mkdirSync as h,unlinkSync as g,writeFileSync as I,rmSync as v}from"node:fs";import{createServer as k}from"node:http";import{dirname as T}from"node:path";import{apiSocketPath as E}from"../core/canvas/paths.js";import{bindDaemonEventSource as R}from"../core/events/source.js";import{emitEvent as f}from"../core/events/emit.js";import{createMachineExecutor as P,stopAllBrokers as x}from"../core/runtime/runner/machine/executor.js";import{machineWorktreeHandlers as C}from"../core/worktree-machine.js";import{readPersonCredential as F}from"../core/directory/person-credential.js";import{socketDir as G}from"../core/layout.js";import{isDaemonRunning as b,pidfilePath as u,readPidfile as N}from"./pidfile.js";import{cancelMachineCron as D,runMachineCron as O,stopOrphanedMachineCrons as U}from"./cron/machine-exec.js";import{startMachineLink as Y}from"./machine-link/client.js";import{deleteMoveRecord as w,readMachineConfig as A,readMachineCredential as y,readMoveRecord as H,writeMoveRecord as z}from"./machine-link/config.js";import{notifyMoveFinished as j}from"./machine-link/move-notify.js";function B(e,n){return{ok:!0,daemon_up:!0,store_accessible:!1,brokers_reconciled:!1,link_connected:e,signed_in:n,startup_phase:e?"ready":"recovering"}}c(B,"machineHealth");async function de(){const e=A();if(e===void 0)throw new Error("crtrd --role machine needs runtime/machine.json: this install has not been imported as a machine");const n=F()!==void 0;if(n&&y(),b())throw new Error("a crtrd is already running for this home");R(),n||(await x(),await U(),f({level:"info",event:"daemon.machine.signed_out",fields:{environment:e.environmentId}})),h(G(),{recursive:!0,mode:493});const a=E();S(a)&&g(a);let r;const t=k((s,d)=>{const p=(s.method??"GET")==="GET"&&(s.url??"/").split("?")[0]==="/healthz";d.writeHead(p?200:404,{"content-type":"application/json; charset=utf-8"}),d.end(JSON.stringify(p?B(r?.connected()===!0,n):{error:{code:"not_found",message:"a machine-role crtrd serves only /healthz",origin:"runtime"}}))});await new Promise((s,d)=>{t.once("error",d),t.listen(a,()=>{t.off("error",d),M(a,384),s()})}),h(T(u()),{recursive:!0}),I(u(),String(process.pid),"utf8");let i;await W(e.runId,n,()=>i!==void 0);const o=P({apiUrl:e.apiUrl,environmentId:e.environmentId});r=n?Y({apiUrl:e.apiUrl,environmentId:e.environmentId,credential:y,handlers:{start:o.start,wake:o.wake,stop:o.stop,status:o.status,delete:o.delete,viewer:o.viewer,"cron.run":O,"cron.cancel":D,...C}}):void 0,f({level:"info",event:"daemon.machine.started",fields:{environment:e.environmentId}});const l=c(()=>i??=(async()=>{r?.stop(),await new Promise(s=>{t.close(()=>s()),t.closeAllConnections()}),N()===process.pid&&(v(a,{force:!0}),v(u(),{force:!0})),process.off("SIGINT",m),process.off("SIGTERM",m)})(),"teardown"),m=c(()=>{l().then(()=>process.exit(0),()=>process.exit(1))},"onSignal");return process.on("SIGINT",m),process.on("SIGTERM",m),l}c(de,"runMachineDaemon");const J=5e3,L=3e5;async function W(e,n,a){let r;try{r=H()}catch(i){f({level:"warn",event:"daemon.machine.move_record_unreadable",fields:{error:i.message}});return}if(r===void 0||r.state==="running"||r.runId!==e)return;if(r.notified||r.notify===null){w();return}if(r.state==="committed"&&(r={...r,state:"activated"},z(r)),!n)return;const t=r;(async()=>{let i=J;for(;;){try{await j(t),w();return}catch(o){f({level:"warn",event:"daemon.machine.move_notify_failed",fields:{node:t.notify??"",error:o.message}})}if(await new Promise(o=>{setTimeout(o,i).unref()}),a())return;i=Math.min(i*2,L)}})()}c(W,"settleFinishedMove");export{B as machineHealth,de as runMachineDaemon};
1
+ var _=Object.defineProperty;var c=(r,n)=>_(r,"name",{value:n,configurable:!0});import{chmodSync as M,existsSync as S,mkdirSync as h,unlinkSync as g,writeFileSync as I,rmSync as v}from"node:fs";import{createServer as k}from"node:http";import{dirname as E}from"node:path";import{apiSocketPath as T}from"../core/canvas/paths.js";import{bindDaemonEventSource as R}from"../core/events/source.js";import{emitEvent as l}from"../core/events/emit.js";import{createMachineExecutor as x,stopAllBrokers as P}from"../core/runtime/runner/machine/executor.js";import{machineWorktreeHandlers as C}from"../core/worktree-machine.js";import{readPersonCredential as F}from"../core/directory/person-credential.js";import{socketDir as G}from"../core/layout.js";import{isDaemonRunning as b,pidfilePath as u,readPidfile as N}from"./pidfile.js";import{cancelMachineCron as D,runMachineCron as O,stopOrphanedMachineCrons as U}from"./cron/machine-exec.js";import{startMachineLink as Y}from"./machine-link/client.js";import{deleteMoveRecord as w,readMachineConfig as A,readMachineCredential as y,readMoveRecord as H,writeMoveRecord as z}from"./machine-link/config.js";import{notifyMoveFinished as j}from"./machine-link/move-notify.js";function B(r,n){return{ok:!0,daemon_up:!0,store_accessible:!1,brokers_reconciled:!1,link_connected:r,signed_in:n,startup_phase:r?"ready":"recovering"}}c(B,"machineHealth");async function de(){const r=A();if(r===void 0)throw new Error("crtrd --role machine needs runtime/machine.json: this install has not been imported as a machine");const n=F()!==void 0;if(n&&y(),b())throw new Error("a crtrd is already running for this home");R(),n||(await P(),await U(),l({level:"info",event:"daemon.machine.signed_out",fields:{environment:r.environmentId}})),h(G(),{recursive:!0,mode:493});const s=T();S(s)&&g(s);let e;const o=k((a,d)=>{const p=(a.method??"GET")==="GET"&&(a.url??"/").split("?")[0]==="/healthz";d.writeHead(p?200:404,{"content-type":"application/json; charset=utf-8"}),d.end(JSON.stringify(p?B(e?.connected()===!0,n):{error:{code:"not_found",message:"a machine-role crtrd serves only /healthz",origin:"runtime"}}))});await new Promise((a,d)=>{o.once("error",d),o.listen(s,()=>{o.off("error",d),M(s,384),a()})}),h(E(u()),{recursive:!0}),I(u(),String(process.pid),"utf8");let i;await W(r.runId,n,()=>i!==void 0);const t=x({apiUrl:r.apiUrl,environmentId:r.environmentId,onExit:c(a=>e?.reportExit(a),"onExit")});e=n?Y({apiUrl:r.apiUrl,environmentId:r.environmentId,credential:y,handlers:{start:t.start,wake:t.wake,stop:t.stop,status:t.status,"status.all":t["status.all"],delete:t.delete,viewer:t.viewer,"cron.run":O,"cron.cancel":D,...C}}):void 0,l({level:"info",event:"daemon.machine.started",fields:{environment:r.environmentId}});const f=c(()=>i??=(async()=>{e?.stop(),await new Promise(a=>{o.close(()=>a()),o.closeAllConnections()}),N()===process.pid&&(v(s,{force:!0}),v(u(),{force:!0})),process.off("SIGINT",m),process.off("SIGTERM",m)})(),"teardown"),m=c(()=>{f().then(()=>process.exit(0),()=>process.exit(1))},"onSignal");return process.on("SIGINT",m),process.on("SIGTERM",m),f}c(de,"runMachineDaemon");const J=5e3,L=3e5;async function W(r,n,s){let e;try{e=H()}catch(i){l({level:"warn",event:"daemon.machine.move_record_unreadable",fields:{error:i.message}});return}if(e===void 0||e.state==="running"||e.runId!==r)return;if(e.notified||e.notify===null){w();return}if(e.state==="committed"&&(e={...e,state:"activated"},z(e)),!n)return;const o=e;(async()=>{let i=J;for(;;){try{await j(o),w();return}catch(t){l({level:"warn",event:"daemon.machine.move_notify_failed",fields:{node:o.notify??"",error:t.message}})}if(await new Promise(t=>{setTimeout(t,i).unref()}),s())return;i=Math.min(i*2,L)}})()}c(W,"settleFinishedMove");export{B as machineHealth,de as runMachineDaemon};
@@ -28,6 +28,15 @@ export interface MachineLinkOptions {
28
28
  export interface MachineLink {
29
29
  stop(): void;
30
30
  connected(): boolean;
31
+ /** Tell the control plane a broker exited. Sent now when the link is open, else when it next opens: the cloud's timed status check
32
+ * also finds the exit, so a report lost with this process costs only the delay. */
33
+ reportExit(exit: BrokerExit): void;
34
+ }
35
+ export interface BrokerExit {
36
+ execution: string;
37
+ node: string;
38
+ code: number | null;
39
+ signal: string | null;
31
40
  }
32
41
  export interface ViewSink {
33
42
  readonly bufferedAmount: number;
@@ -1 +1 @@
1
- var O=Object.defineProperty;var r=(t,l)=>O(t,"name",{value:l,configurable:!0});import{WebSocket as g}from"ws";import{emitEvent as b}from"../../core/events/emit.js";import{connectViewSocket as C}from"../../core/runtime/view-socket.js";import{CLOSE_REVOKED as V,LINK_MAX_PAYLOAD_BYTES as B,parseFrame as W}from"./frames.js";const K=1e3,P=6e4,R=64*1024,U=4*1024*1024,F=1024*1024,Y=8*1024*1024,D=75e3;function $(t){const l=[];let s=0;const u=new Set,w=r(()=>{for(;l.length>0&&t.open()&&t.bufferedAmount<R;){const i=l.shift();s-=i.length,t.send(i,w)}if(s<F&&u.size>0){for(const i of u)i.resume();u.clear()}},"pump");return{push(i,a){t.open()&&(l.push(i),s+=i.length,a!==void 0&&s>U&&(a.pause(),u.add(a)),w())},forget(i){u.delete(i)}}}r($,"createViewQueue");function q(t,l){const s=new URL(`/v1/machines/${encodeURIComponent(l)}/link`,t);return s.protocol=s.protocol==="https:"?"wss:":s.protocol==="http:"?"ws:":s.protocol,s.toString()}r(q,"linkUrl");function G(t){const l=t.backoffMinMs??K,s=t.backoffMaxMs??P,u=t.openView??C,w=t.silenceMs??D;let i=!1,a,f=l,v;const A=r((E,o)=>{b({level:"error",event:E,fields:{environment:t.environmentId},error:o})},"fault");let y;const S=r(()=>{if(i)return;if(y!==void 0){if(t.credential()===y){v=setTimeout(S,f),f=Math.min(f*2,s);return}y=void 0}const E=t.credential(),o=new g(q(t.apiUrl,t.environmentId),{headers:{authorization:`Bearer ${E}`},maxPayload:B});a=o;const d=new Map,h=new Map,M=r(e=>{o.readyState===g.OPEN&&o.send(JSON.stringify(e))},"send"),k=$({get bufferedAmount(){return o.bufferedAmount},open:r(()=>o.readyState===g.OPEN,"open"),send:r((e,n)=>o.send(e,n),"send")}),p=r((e,n)=>k.push(JSON.stringify(e),n),"sendView"),L=r(async e=>{const n=t.handlers[e.op];if(n===void 0){M({type:"result",call_id:e.call_id,ok:!1,error:`this machine does not execute ${e.op}`});return}const c=new AbortController,_=r(()=>c.abort(new Error("the machine link closed")),"onClose");o.once("close",_);try{M({type:"result",call_id:e.call_id,ok:!0,value:await n(e.args,c.signal)??null})}catch(T){M({type:"result",call_id:e.call_id,ok:!1,error:T instanceof Error?T.message:String(T)})}finally{o.off("close",_)}},"runCall"),N=r(e=>{const n=u(e.node);d.set(e.channel,n),n.once("connect",()=>p({type:"view.ready",channel:e.channel})),n.on("data",c=>p({type:"view.data",channel:e.channel,bytes:c.toString("base64")},n)),n.once("error",c=>{k.forget(n),d.delete(e.channel)&&p({type:"view.close",channel:e.channel,error:c.message})}),n.once("close",()=>{k.forget(n),d.delete(e.channel)&&p({type:"view.close",channel:e.channel})})},"openChannel"),x=r((e,n)=>{const c=d.get(e);if(c===void 0||c.write(n))return;const _=(h.get(e)??0)+n.length;if(_>Y){d.delete(e),h.delete(e),c.destroy(),p({type:"view.close",channel:e,error:"the broker is not draining the viewer channel"});return}h.has(e)||c.once("drain",()=>h.delete(e)),h.set(e,_)},"writeToChannel");let m;const I=r(()=>{m!==void 0&&clearTimeout(m),m=setTimeout(()=>{b({level:"warn",event:"daemon.machine_link.silent",fields:{environment:t.environmentId}}),o.terminate()},w)},"heard");o.on("open",()=>{f=l,I()}),o.on("ping",I),o.on("message",e=>{I();const n=W(e);if(n!==null)try{switch(n.type){case"call":L(n);return;case"view.open":N(n);return;case"view.data":x(n.channel,Buffer.from(n.bytes,"base64"));return;case"view.close":{const c=d.get(n.channel);d.delete(n.channel),c?.destroy();return}default:return}}catch(c){A("daemon.machine_link.frame_failed",c)}}),o.on("error",e=>A("daemon.machine_link.client_error",e)),o.on("close",e=>{m!==void 0&&clearTimeout(m);for(const n of d.values())n.destroy();d.clear(),a===o&&(a=void 0),!i&&(e===V&&(b({level:"error",event:"daemon.machine_link.revoked",fields:{environment:t.environmentId}}),y=E),v=setTimeout(S,f),f=Math.min(f*2,s))})},"connect");return S(),{stop(){i=!0,v!==void 0&&clearTimeout(v),a?.close()},connected:r(()=>a?.readyState===g.OPEN,"connected")}}r(G,"startMachineLink");export{P as LINK_BACKOFF_MAX_MS,K as LINK_BACKOFF_MIN_MS,D as LINK_SILENCE_MS,Y as VIEW_WRITE_LIMIT_BYTES,$ as createViewQueue,q as linkUrl,G as startMachineLink};
1
+ var B=Object.defineProperty;var o=(t,l)=>B(t,"name",{value:l,configurable:!0});import{WebSocket as v}from"ws";import{emitEvent as x}from"../../core/events/emit.js";import{connectViewSocket as W}from"../../core/runtime/view-socket.js";import{CLOSE_REVOKED as K,LINK_MAX_PAYLOAD_BYTES as P,parseFrame as U}from"./frames.js";const R=1e3,F=6e4,Y=64*1024,X=4*1024*1024,D=1024*1024,J=8*1024*1024,$=75e3;function q(t){const l=[];let c=0;const f=new Set,y=o(()=>{for(;l.length>0&&t.open()&&t.bufferedAmount<Y;){const i=l.shift();c-=i.length,t.send(i,y)}if(c<D&&f.size>0){for(const i of f)i.resume();f.clear()}},"pump");return{push(i,a){t.open()&&(l.push(i),c+=i.length,a!==void 0&&c>X&&(a.pause(),f.add(a)),y())},forget(i){f.delete(i)}}}o(q,"createViewQueue");function z(t,l){const c=new URL(`/v1/machines/${encodeURIComponent(l)}/link`,t);return c.protocol=c.protocol==="https:"?"wss:":c.protocol==="http:"?"ws:":c.protocol,c.toString()}o(z,"linkUrl");function ee(t){const l=t.backoffMinMs??R,c=t.backoffMaxMs??F,f=t.openView??W,y=t.silenceMs??$;let i=!1,a,h=l,g;const b=200,p=[],A=o(()=>{const d=a;for(;p.length>0&&d?.readyState===v.OPEN;)d.send(JSON.stringify({type:"exit",...p.shift()}))},"flushExits"),O=o((d,r)=>{x({level:"error",event:d,fields:{environment:t.environmentId},error:r})},"fault");let S;const M=o(()=>{if(i)return;if(S!==void 0){if(t.credential()===S){g=setTimeout(M,h),h=Math.min(h*2,c);return}S=void 0}const d=t.credential(),r=new v(z(t.apiUrl,t.environmentId),{headers:{authorization:`Bearer ${d}`},maxPayload:P});a=r;const u=new Map,m=new Map,k=o(e=>{r.readyState===v.OPEN&&r.send(JSON.stringify(e))},"send"),I=q({get bufferedAmount(){return r.bufferedAmount},open:o(()=>r.readyState===v.OPEN,"open"),send:o((e,n)=>r.send(e,n),"send")}),_=o((e,n)=>I.push(JSON.stringify(e),n),"sendView"),L=o(async e=>{const n=t.handlers[e.op];if(n===void 0){k({type:"result",call_id:e.call_id,ok:!1,error:`this machine does not execute ${e.op}`});return}const s=new AbortController,E=o(()=>s.abort(new Error("the machine link closed")),"onClose");r.once("close",E);try{k({type:"result",call_id:e.call_id,ok:!0,value:await n(e.args,s.signal)??null})}catch(T){k({type:"result",call_id:e.call_id,ok:!1,error:T instanceof Error?T.message:String(T)})}finally{r.off("close",E)}},"runCall"),C=o(e=>{const n=f(e.node);u.set(e.channel,n),n.once("connect",()=>_({type:"view.ready",channel:e.channel})),n.on("data",s=>_({type:"view.data",channel:e.channel,bytes:s.toString("base64")},n)),n.once("error",s=>{I.forget(n),u.delete(e.channel)&&_({type:"view.close",channel:e.channel,error:s.message})}),n.once("close",()=>{I.forget(n),u.delete(e.channel)&&_({type:"view.close",channel:e.channel})})},"openChannel"),V=o((e,n)=>{const s=u.get(e);if(s===void 0||s.write(n))return;const E=(m.get(e)??0)+n.length;if(E>J){u.delete(e),m.delete(e),s.destroy(),_({type:"view.close",channel:e,error:"the broker is not draining the viewer channel"});return}m.has(e)||s.once("drain",()=>m.delete(e)),m.set(e,E)},"writeToChannel");let w;const N=o(()=>{w!==void 0&&clearTimeout(w),w=setTimeout(()=>{x({level:"warn",event:"daemon.machine_link.silent",fields:{environment:t.environmentId}}),r.terminate()},y)},"heard");r.on("open",()=>{h=l,N(),A()}),r.on("ping",N),r.on("message",e=>{N();const n=U(e);if(n!==null)try{switch(n.type){case"call":L(n);return;case"view.open":C(n);return;case"view.data":V(n.channel,Buffer.from(n.bytes,"base64"));return;case"view.close":{const s=u.get(n.channel);u.delete(n.channel),s?.destroy();return}default:return}}catch(s){O("daemon.machine_link.frame_failed",s)}}),r.on("error",e=>O("daemon.machine_link.client_error",e)),r.on("close",e=>{w!==void 0&&clearTimeout(w);for(const n of u.values())n.destroy();u.clear(),a===r&&(a=void 0),!i&&(e===K&&(x({level:"error",event:"daemon.machine_link.revoked",fields:{environment:t.environmentId}}),S=d),g=setTimeout(M,h),h=Math.min(h*2,c))})},"connect");return M(),{stop(){i=!0,g!==void 0&&clearTimeout(g),a?.close()},connected:o(()=>a?.readyState===v.OPEN,"connected"),reportExit(d){p.push(d),p.length>b&&p.shift(),A()}}}o(ee,"startMachineLink");export{F as LINK_BACKOFF_MAX_MS,R as LINK_BACKOFF_MIN_MS,$ as LINK_SILENCE_MS,J as VIEW_WRITE_LIMIT_BYTES,q as createViewQueue,z as linkUrl,ee as startMachineLink};
@@ -19,6 +19,14 @@ export type MachineFrame =
19
19
  ok: false;
20
20
  error: string;
21
21
  }
22
+ /** Mac → holder: a broker this machine spawned exited (the cloud's `Fleet.onChildExit`). */
23
+ | {
24
+ type: 'exit';
25
+ execution: string;
26
+ node: string;
27
+ code: number | null;
28
+ signal: string | null;
29
+ }
22
30
  /** holder → Mac: open a viewer channel to `node`'s view.sock. */
23
31
  | {
24
32
  type: 'view.open';
@@ -1 +1 @@
1
- var o=Object.defineProperty;var l=(r,t)=>o(r,"name",{value:t,configurable:!0});const a=33554432,f=4001,i=4003;function p(r){const t=Array.isArray(r)?Buffer.concat(r):Buffer.isBuffer(r)?r:Buffer.from(new Uint8Array(r));try{const e=JSON.parse(t.toString("utf8"));if(typeof e!="object"||e===null)return null;const n=l((...u)=>u.every(c=>typeof e[c]=="string"),"strings");switch(e.type){case"call":return n("call_id","op")?e:null;case"result":return n("call_id")&&(e.ok===!0||e.ok===!1&&n("error"))?e:null;case"view.open":return n("channel","node")?e:null;case"view.ready":case"view.close":return n("channel")?e:null;case"view.data":return n("channel","bytes")?e:null;default:return null}}catch{return null}}l(p,"parseFrame");export{i as CLOSE_REVOKED,f as CLOSE_SUPERSEDED,a as LINK_MAX_PAYLOAD_BYTES,p as parseFrame};
1
+ var o=Object.defineProperty;var l=(n,t)=>o(n,"name",{value:t,configurable:!0});const f=33554432,i=4001,p=4003,s=l(n=>n===null||typeof n=="number","nullableNumber");function y(n){const t=Array.isArray(n)?Buffer.concat(n):Buffer.isBuffer(n)?n:Buffer.from(new Uint8Array(n));try{const e=JSON.parse(t.toString("utf8"));if(typeof e!="object"||e===null)return null;const r=l((...u)=>u.every(c=>typeof e[c]=="string"),"strings");switch(e.type){case"call":return r("call_id","op")?e:null;case"result":return r("call_id")&&(e.ok===!0||e.ok===!1&&r("error"))?e:null;case"exit":return r("execution","node")&&s(e.code)&&(e.signal===null||typeof e.signal=="string")?e:null;case"view.open":return r("channel","node")?e:null;case"view.ready":case"view.close":return r("channel")?e:null;case"view.data":return r("channel","bytes")?e:null;default:return null}}catch{return null}}l(y,"parseFrame");export{p as CLOSE_REVOKED,i as CLOSE_SUPERSEDED,f as LINK_MAX_PAYLOAD_BYTES,y as parseFrame};
@@ -46,6 +46,17 @@ export declare class HeldLink extends EventEmitter {
46
46
  private onMessage;
47
47
  private teardown;
48
48
  }
49
+ /** A broker exit the Mac reported: what `Fleet.onChildExit` does for a local child. Only a live machine execution of this node whose profile
50
+ * runs in this link's environment is ended, so a machine cannot end another machine's executions. The lane processes hear
51
+ * `execution_exit:<node>` and run the node-lifecycle pass for that node at once. The execution of a node held by an import is left to the
52
+ * import, and a broker exiting because a stop was requested on it (the stopper decides the row's next state, or the next tick does)
53
+ * ends its execution without a signal. */
54
+ export declare function recordMachineBrokerExit(environmentId: string, exit: {
55
+ execution: string;
56
+ node: string;
57
+ code: number | null;
58
+ signal: string | null;
59
+ }): Promise<boolean>;
49
60
  /** A viewer channel to one node's view.sock on the Mac, as the relay's broker-side link. */
50
61
  export declare class MachineViewLink extends EventEmitter implements BrokerViewLink {
51
62
  private readonly link;
@@ -1,9 +1,9 @@
1
- var N=Object.defineProperty;var s=(i,e)=>N(i,"name",{value:e,configurable:!0});import{EventEmitter as u}from"node:events";import{hostname as k}from"node:os";import{randomUUID as R}from"node:crypto";import{WebSocket as T,WebSocketServer as I}from"ws";import{openDb as r}from"../../core/canvas/db.js";import{emitEvent as _}from"../../core/events/emit.js";import{brokerSignalBus as L}from"../broker-signals/bus.js";import{verifyMachineCredential as E}from"./credential.js";import{CLOSE_REVOKED as y,CLOSE_SUPERSEDED as p,LINK_MAX_PAYLOAD_BYTES as O,parseFrame as b}from"./frames.js";const U=45e3,C=15e3,x=3e4,M=1e3,w=10,P=new I({noServer:!0,maxPayload:O}),c=new Map,H="unroutable:";let g;const q=s(i=>{g=i},"setApiAddress"),W=s(()=>process.env.CRTR_API_ADDRESS??g??`${H}${k()}:${process.pid}`,"apiAddress"),m=s(()=>new Date(Date.now()+U).toISOString(),"lease");class F extends u{static{s(this,"HeldLink")}environmentId;generation;ws;token;timers=[];unsubscribe;claiming=!1;closed=!1;alive=!0;channels=new Map;constructor(e,t,n,a){super(),this.environmentId=e,this.generation=t,this.ws=n,this.token=a}start(){const{ws:e}=this;e.on("message",t=>{this.onMessage(t).catch(n=>this.fault("daemon.machine_link.frame_failed",n))}),e.on("pong",()=>{this.alive=!0}),e.on("close",()=>{this.teardown().catch(t=>this.fault("daemon.machine_link.teardown_failed",t))}),e.on("error",()=>{}),this.timers.push(setInterval(()=>{this.renew().catch(t=>this.fault("daemon.machine_link.renew_failed",t))},C)),this.timers.push(setInterval(()=>{if(!this.alive){e.terminate();return}this.alive=!1;try{e.ping()}catch{}},x)),this.timers.push(setInterval(()=>{this.claim().catch(t=>this.fault("daemon.machine_link.claim_failed",t))},M)),L.subscribe(t=>{t===this.environmentId&&this.claim().catch(n=>this.fault("daemon.machine_link.claim_failed",n))},{kinds:["machine"],onListenStart:s(()=>{this.claim().catch(t=>this.fault("daemon.machine_link.claim_failed",t))},"onListenStart")}).then(t=>{this.closed?t():this.unsubscribe=t})}fault(e,t){_({level:"error",event:e,fields:{environment:this.environmentId},error:t})}send(e){return this.ws.readyState!==T.OPEN?!1:(this.ws.send(JSON.stringify(e)),!0)}async renew(){if(this.closed)return;const e=await r(),t=m();if((await e.prepare("UPDATE machine_links SET lease_expires_at = ? WHERE environment = ? AND generation = ?").run(t,this.environmentId,this.generation)).changes===0){this.ws.close(p,"superseded");return}await e.prepare("UPDATE machine_calls SET lease_expires_at = ? WHERE environment = ? AND state = 'sent' AND claimed_generation = ?").run(t,this.environmentId,this.generation),await e.prepare("UPDATE environments SET last_seen_at = ? WHERE object = ?").run(new Date().toISOString(),this.environmentId),await this.credentialValid()||this.ws.close(y,"revoked")}async credentialValid(){return await E(this.environmentId,this.token)}async claim(){if(!(this.closed||this.claiming)){this.claiming=!0;try{for(;;){const e=await(await r()).prepare(`UPDATE machine_calls SET state = 'sent', claimed_generation = ?, lease_expires_at = ?
1
+ var N=Object.defineProperty;var s=(i,e)=>N(i,"name",{value:e,configurable:!0});import{importedNodesHeld as k}from"../reconcilers/live-obligation.js";import{EventEmitter as _}from"node:events";import{hostname as R}from"node:os";import{randomUUID as T}from"node:crypto";import{WebSocket as L,WebSocketServer as I}from"ws";import{openDb as r}from"../../core/canvas/db.js";import{emitEvent as m}from"../../core/events/emit.js";import{endExecution as y,recordExecutionExit as O}from"../../core/canvas/executions.js";import{machineEnvironmentOfNode as b}from"../../core/runtime/runner/machine/runner.js";import{brokerSignalBus as x}from"../broker-signals/bus.js";import{verifyMachineCredential as E}from"./credential.js";import{CLOSE_REVOKED as C,CLOSE_SUPERSEDED as p,LINK_MAX_PAYLOAD_BYTES as M,parseFrame as U}from"./frames.js";const H=45e3,P=15e3,W=3e4,F=1e3,w=10,B=new I({noServer:!0,maxPayload:M}),c=new Map,$="unroutable:";let g;const oe=s(i=>{g=i},"setApiAddress"),K=s(()=>process.env.CRTR_API_ADDRESS??g??`${$}${R()}:${process.pid}`,"apiAddress"),u=s(()=>new Date(Date.now()+H).toISOString(),"lease");class X extends _{static{s(this,"HeldLink")}environmentId;generation;ws;token;timers=[];unsubscribe;claiming=!1;closed=!1;alive=!0;channels=new Map;constructor(e,n,t,a){super(),this.environmentId=e,this.generation=n,this.ws=t,this.token=a}start(){const{ws:e}=this;e.on("message",n=>{this.onMessage(n).catch(t=>this.fault("daemon.machine_link.frame_failed",t))}),e.on("pong",()=>{this.alive=!0}),e.on("close",()=>{this.teardown().catch(n=>this.fault("daemon.machine_link.teardown_failed",n))}),e.on("error",()=>{}),this.timers.push(setInterval(()=>{this.renew().catch(n=>this.fault("daemon.machine_link.renew_failed",n))},P)),this.timers.push(setInterval(()=>{if(!this.alive){e.terminate();return}this.alive=!1;try{e.ping()}catch{}},W)),this.timers.push(setInterval(()=>{this.claim().catch(n=>this.fault("daemon.machine_link.claim_failed",n))},F)),x.subscribe(n=>{n===this.environmentId&&this.claim().catch(t=>this.fault("daemon.machine_link.claim_failed",t))},{kinds:["machine"],onListenStart:s(()=>{this.claim().catch(n=>this.fault("daemon.machine_link.claim_failed",n))},"onListenStart")}).then(n=>{this.closed?n():this.unsubscribe=n})}fault(e,n){m({level:"error",event:e,fields:{environment:this.environmentId},error:n})}send(e){return this.ws.readyState!==L.OPEN?!1:(this.ws.send(JSON.stringify(e)),!0)}async renew(){if(this.closed)return;const e=await r(),n=u();if((await e.prepare("UPDATE machine_links SET lease_expires_at = ? WHERE environment = ? AND generation = ?").run(n,this.environmentId,this.generation)).changes===0){this.ws.close(p,"superseded");return}await e.prepare("UPDATE machine_calls SET lease_expires_at = ? WHERE environment = ? AND state = 'sent' AND claimed_generation = ?").run(n,this.environmentId,this.generation),await e.prepare("UPDATE environments SET last_seen_at = ? WHERE object = ?").run(new Date().toISOString(),this.environmentId),await this.credentialValid()||this.ws.close(C,"revoked")}async credentialValid(){return await E(this.environmentId,this.token)}async claim(){if(!(this.closed||this.claiming)){this.claiming=!0;try{for(;;){const e=await(await r()).prepare(`UPDATE machine_calls SET state = 'sent', claimed_generation = ?, lease_expires_at = ?
2
2
  WHERE call_id IN (SELECT call_id FROM machine_calls WHERE environment = ? AND state = 'pending'
3
3
  AND EXISTS (SELECT 1 FROM machine_links WHERE environment = ? AND generation = ?)
4
4
  ORDER BY created_at FOR UPDATE SKIP LOCKED LIMIT ${w})
5
- RETURNING call_id, op, args_json`).all(this.generation,m(),this.environmentId,this.environmentId,this.generation),t=!this.closed&&await this.isCurrentGeneration();for(const n of e)t?this.send({type:"call",call_id:n.call_id,op:n.op,args:JSON.parse(n.args_json)})||await this.failCall(n.call_id,"machine_offline","link closed before the call was sent",!1):await this.release(n.call_id);if(e.length<w)return}}finally{this.claiming=!1}}}async failCall(e,t,n,a){await this.settle(e,"failed",{code:t,message:n,sent:a},!1)}async isCurrentGeneration(){return await(await r()).prepare("SELECT 1 AS live FROM machine_links WHERE environment = ? AND generation = ?").get(this.environmentId,this.generation)!==void 0}async release(e){await(await r()).prepare("UPDATE machine_calls SET state = 'pending', claimed_generation = NULL, lease_expires_at = NULL WHERE call_id = ? AND state = 'sent' AND claimed_generation = ?").run(e,this.generation)}async settle(e,t,n,a){await B(e,t,n,this.environmentId,this.generation,a)}async onMessage(e){const t=b(e);if(t!==null)switch(t.type){case"result":t.ok?await this.settle(t.call_id,"done",t.value??null,!0):await this.settle(t.call_id,"failed",{code:"machine_call_failed",message:t.error},!0);return;case"view.ready":this.channels.get(t.channel)?.emit("connect");return;case"view.data":this.channels.get(t.channel)?.emit("data",Buffer.from(t.bytes,"base64"));return;case"view.close":this.channels.get(t.channel)?.finish(t.error);return;default:return}}async teardown(){if(this.closed)return;this.closed=!0;for(const n of this.timers)clearInterval(n);this.unsubscribe?.(),c.get(this.environmentId)===this&&c.delete(this.environmentId);for(const n of[...this.channels.values()])n.finish("machine link closed");const e=await r(),t=await e.prepare("SELECT call_id FROM machine_calls WHERE environment = ? AND state = 'sent' AND claimed_generation = ?").all(this.environmentId,this.generation);for(const{call_id:n}of t)await this.failCall(n,"machine_offline","link dropped before the result",!0);await e.prepare("DELETE FROM machine_links WHERE environment = ? AND generation = ?").run(this.environmentId,this.generation)}}async function B(i,e,t,n,a,l){const o=await r();(await o.prepare(`UPDATE machine_calls SET state = ?, result_json = ?, finished_at = ?
5
+ RETURNING call_id, op, args_json`).all(this.generation,u(),this.environmentId,this.environmentId,this.generation),n=!this.closed&&await this.isCurrentGeneration();for(const t of e)n?this.send({type:"call",call_id:t.call_id,op:t.op,args:JSON.parse(t.args_json)})||await this.failCall(t.call_id,"machine_offline","link closed before the call was sent",!1):await this.release(t.call_id);if(e.length<w)return}}finally{this.claiming=!1}}}async failCall(e,n,t,a){await this.settle(e,"failed",{code:n,message:t,sent:a},!1)}async isCurrentGeneration(){return await(await r()).prepare("SELECT 1 AS live FROM machine_links WHERE environment = ? AND generation = ?").get(this.environmentId,this.generation)!==void 0}async release(e){await(await r()).prepare("UPDATE machine_calls SET state = 'pending', claimed_generation = NULL, lease_expires_at = NULL WHERE call_id = ? AND state = 'sent' AND claimed_generation = ?").run(e,this.generation)}async settle(e,n,t,a){await j(e,n,t,this.environmentId,this.generation,a)}async onMessage(e){const n=U(e);if(n!==null)switch(n.type){case"result":n.ok?await this.settle(n.call_id,"done",n.value??null,!0):await this.settle(n.call_id,"failed",{code:"machine_call_failed",message:n.error},!0);return;case"exit":await G(this.environmentId,n);return;case"view.ready":this.channels.get(n.channel)?.emit("connect");return;case"view.data":this.channels.get(n.channel)?.emit("data",Buffer.from(n.bytes,"base64"));return;case"view.close":this.channels.get(n.channel)?.finish(n.error);return;default:return}}async teardown(){if(this.closed)return;this.closed=!0;for(const t of this.timers)clearInterval(t);this.unsubscribe?.(),c.get(this.environmentId)===this&&c.delete(this.environmentId);for(const t of[...this.channels.values()])t.finish("machine link closed");const e=await r(),n=await e.prepare("SELECT call_id FROM machine_calls WHERE environment = ? AND state = 'sent' AND claimed_generation = ?").all(this.environmentId,this.generation);for(const{call_id:t}of n)await this.failCall(t,"machine_offline","link dropped before the result",!0);await e.prepare("DELETE FROM machine_links WHERE environment = ? AND generation = ?").run(this.environmentId,this.generation)}}async function j(i,e,n,t,a,o){const l=await r();(await l.prepare(`UPDATE machine_calls SET state = ?, result_json = ?, finished_at = ?
6
6
  WHERE call_id = ? AND environment = ? AND claimed_generation = ? AND state = 'sent'
7
- ${l?"AND EXISTS (SELECT 1 FROM machine_links WHERE environment = ? AND generation = ?)":""}`).run(e,JSON.stringify(t),new Date().toISOString(),i,n,a,...l?[n,a]:[])).changes>0&&await o.prepare("SELECT pg_notify(?, ?)").get("crtr_signal",`machine_call:${i}`)}s(B,"withNotify");class ee extends u{static{s(this,"MachineViewLink")}link;ended=!1;failed=!1;channel=R();constructor(e,t){super(),this.link=e,e.channels.set(this.channel,this),e.send({type:"view.open",channel:this.channel,node:t})||queueMicrotask(()=>this.finish("machine link closed"))}get destroyed(){return this.ended}write(e){return!this.ended&&this.link.send({type:"view.data",channel:this.channel,bytes:Buffer.from(e).toString("base64")})}destroy(){return this.ended||(this.link.send({type:"view.close",channel:this.channel}),this.finish(void 0)),this}finish(e){this.ended||(this.ended=!0,this.link.channels.delete(this.channel),e!==void 0&&!this.failed&&(this.failed=!0,this.emit("error",Object.assign(new Error(e),{code:"ECONNRESET"}))),this.emit("close",this.failed))}}const te=s(i=>c.get(i)??null,"heldLinkOf"),K=/^\/v1\/machines\/([A-Za-z0-9_-]+)\/link$/;function ne(i){const e=K.exec(new URL(i.url??"/","http://runtime.local").pathname);return e===null?null:e[1]}s(ne,"machineLinkEnvironment");async function ie(i,e,t,n){const a=i.headers.authorization,l=/^Bearer (\S+)$/.exec(Array.isArray(a)?a[0]??"":a??"")?.[1];if(l===void 0||!await E(n,l))return{status:401,text:"Unauthorized",code:"unauthorized",message:"machine credential refused"};const o=new Date().toISOString(),h=await r(),v=await h.prepare(`INSERT INTO machine_links (environment, generation, api_address, connected_at, lease_expires_at) VALUES (?, 1, ?, ?, ?)
7
+ ${o?"AND EXISTS (SELECT 1 FROM machine_links WHERE environment = ? AND generation = ?)":""}`).run(e,JSON.stringify(n),new Date().toISOString(),i,t,a,...o?[t,a]:[])).changes>0&&await l.prepare("SELECT pg_notify(?, ?)").get("crtr_signal",`machine_call:${i}`)}s(j,"withNotify");async function G(i,e){const n=await r(),t=await n.prepare("SELECT stop_requested_at, stop_reason FROM executions WHERE execution_id = ? AND node_id = ? AND runner = 'machine' AND state != 'exited'").get(e.execution,e.node);return t===void 0||await b(e.node)!==i||(await k()).has(e.node)||(await O(e.execution,{code:e.code,signal:e.signal}),!await y(e.execution,{reason:"exited"}))?!1:(t.stop_requested_at===null&&t.stop_reason===null&&await n.prepare("SELECT pg_notify(?, ?)").get("crtr_signal",`execution_exit:${e.node}`),m({level:"info",event:"broker.exit.reported",node_id:e.node,fields:{environment:i,code:e.code,signal:e.signal}}),!0)}s(G,"recordMachineBrokerExit");class le extends _{static{s(this,"MachineViewLink")}link;ended=!1;failed=!1;channel=T();constructor(e,n){super(),this.link=e,e.channels.set(this.channel,this),e.send({type:"view.open",channel:this.channel,node:n})||queueMicrotask(()=>this.finish("machine link closed"))}get destroyed(){return this.ended}write(e){return!this.ended&&this.link.send({type:"view.data",channel:this.channel,bytes:Buffer.from(e).toString("base64")})}destroy(){return this.ended||(this.link.send({type:"view.close",channel:this.channel}),this.finish(void 0)),this}finish(e){this.ended||(this.ended=!0,this.link.channels.delete(this.channel),e!==void 0&&!this.failed&&(this.failed=!0,this.emit("error",Object.assign(new Error(e),{code:"ECONNRESET"}))),this.emit("close",this.failed))}}const ce=s(i=>c.get(i)??null,"heldLinkOf"),V=/^\/v1\/machines\/([A-Za-z0-9_-]+)\/link$/;function de(i){const e=V.exec(new URL(i.url??"/","http://runtime.local").pathname);return e===null?null:e[1]}s(de,"machineLinkEnvironment");async function he(i,e,n,t){const a=i.headers.authorization,o=/^Bearer (\S+)$/.exec(Array.isArray(a)?a[0]??"":a??"")?.[1];if(o===void 0||!await E(t,o))return{status:401,text:"Unauthorized",code:"unauthorized",message:"machine credential refused"};const l=new Date().toISOString(),d=await r(),v=await d.prepare(`INSERT INTO machine_links (environment, generation, api_address, connected_at, lease_expires_at) VALUES (?, 1, ?, ?, ?)
8
8
  ON CONFLICT (environment) DO UPDATE SET generation = machine_links.generation + 1, api_address = EXCLUDED.api_address, connected_at = EXCLUDED.connected_at, lease_expires_at = EXCLUDED.lease_expires_at
9
- RETURNING generation`).get(n,W(),o,m());await h.prepare("UPDATE environments SET last_seen_at = ? WHERE object = ?").run(o,n);const f=Number(v.generation);return e.destroyed?(await h.prepare("DELETE FROM machine_links WHERE environment = ? AND generation = ?").run(n,f),null):(P.handleUpgrade(i,e,t,S=>{const d=new F(n,f,S,l),D=c.get(n);c.set(n,d),D?.ws.close(p,"superseded"),d.start(),d.claim().catch(A=>_({level:"error",event:"daemon.machine_link.claim_failed",fields:{environment:n},error:A}))}),null)}s(ie,"handleMachineLinkUpgrade");export{F as HeldLink,U as LINK_LEASE_MS,x as LINK_PING_MS,C as LINK_RENEW_MS,ee as MachineViewLink,H as UNROUTABLE_PREFIX,W as apiAddress,ie as handleMachineLinkUpgrade,te as heldLinkOf,ne as machineLinkEnvironment,q as setApiAddress};
9
+ RETURNING generation`).get(t,K(),l,u());await d.prepare("UPDATE environments SET last_seen_at = ? WHERE object = ?").run(l,t);const f=Number(v.generation);return e.destroyed?(await d.prepare("DELETE FROM machine_links WHERE environment = ? AND generation = ?").run(t,f),null):(B.handleUpgrade(i,e,n,S=>{const h=new X(t,f,S,o),D=c.get(t);c.set(t,h),D?.ws.close(p,"superseded"),h.start(),h.claim().catch(A=>m({level:"error",event:"daemon.machine_link.claim_failed",fields:{environment:t},error:A}))}),null)}s(he,"handleMachineLinkUpgrade");export{X as HeldLink,H as LINK_LEASE_MS,W as LINK_PING_MS,P as LINK_RENEW_MS,le as MachineViewLink,$ as UNROUTABLE_PREFIX,K as apiAddress,he as handleMachineLinkUpgrade,ce as heldLinkOf,de as machineLinkEnvironment,G as recordMachineBrokerExit,oe as setApiAddress};
@@ -1 +1 @@
1
- var L=Object.defineProperty;var o=(t,e)=>L(t,"name",{value:e,configurable:!0});import{canvasPoolSize as T,openDb as v}from"../../core/canvas/db.js";import{isCloudRole as x}from"../../core/canvas/person.js";import{endLiveExecution as O,liveExecutionForNode as D}from"../../core/canvas/executions.js";import{emitEvent as d}from"../../core/events/emit.js";import{afterRevocationStop as M}from"../../core/grants/on-sync.js";import{allGrants as h,grantIdsWhere as y,grantStanding as E,mirrorOnly as R}from"../../core/grants/mirror.js";import{removeApp as A,removePersonData as P}from"../../core/grants/remove.js";import{wakeAllGrantWaiters as G,wakeGrantWaiters as C}from"../../core/grants/watch.js";import{discardOrphanedTokens as g,discardTokensForGrant as F}from"../../core/providers/token-cache.js";import{isUnsandboxedMachine as W}from"../../core/runtime/unsandboxed.js";import{runnerForExecution as U}from"../../core/runtime/runner/index.js";import{closeGrantStreams as B,heldGrantIds as $}from"../../core/runs/events.js";import{stopNodeSandboxes as H}from"../../core/spaces/stop.js";import{brokerSignalBus as J}from"../broker-signals/bus.js";import{withRowClaim as z}from"./row-claim.js";const K=6e4,V=o(()=>Math.max(1,Math.floor(T()/3)),"grantSlotLimit");let _=0;const b=[];async function X(t){for(;_>=V();)await new Promise(e=>{b.push(e)});_+=1;try{return await t()}finally{_-=1,b.shift()?.()}}o(X,"withGrantSlot");const Y=3e4,j=5;function m(t,e,r){d({level:"error",event:`daemon.grants.${t}`,error:e,fields:r})}o(m,"failed");function q(t,e,r){try{const n=e.sub===null||e.grantee===null?g(r):F({sub:e.sub,grantee:e.grantee,active:e.standing==="active"},r);n.tokens>0&&d({level:"info",event:"daemon.grants.outbound_tokens_discarded",fields:{grant:t,tokens:n.tokens}})}catch(n){m("outbound_tokens_discard_failed",n,{grant:t})}}o(q,"discardTokens");async function N(){try{await(await import("../../core/providers/bundles.js")).syncProviderBundles()}catch(t){d({level:"error",event:"daemon.providers.bundle_sync_failed",error:t})}}o(N,"reconcileProviderBundles");async function Q(t,e){if(C(t),e.standing==="inactive"){const r=B(t);r>0&&d({level:"info",event:"daemon.grants.streams_closed",fields:{grant:t,grantee:e.grantee,streams:r}})}await N()}o(Q,"serveEffects");async function Z(t,e){const r=await z("nodes",t,K,async n=>{const a=await D(t);if(a===null)return;await n.assertOwned(),d({level:"info",event:"daemon.grants.node_stop",node_id:t,fields:{grant:e,execution_id:a.executionId}});const c=o(async()=>{await n.assertOwned(),await O(t,{reason:"permission_revoked"}),await M(t)},"finish");if(a.runner==="process"){const w=await H(t,"permission_revoked",{holdRecovery:!0,after:c});if(!w.confirmed)throw w.error??new Error(`stop of ${t} was not confirmed`);return}const u=await U(a.runner).stop(a,{reason:"permission_revoked"});if(!u.confirmed)throw u.error??new Error(`stop of ${t} was not confirmed`);await c()},{waitForLock:!0})}o(Z,"stopRevokedNode");async function I(t,e){if(!(e.grantee!==null&&R({grantee:e.grantee}))){if(e.standing==="inactive"){const r=await(await v()).prepare("SELECT DISTINCT n.node_id FROM nodes n JOIN executions e ON e.node_id = n.node_id AND e.state != 'exited' WHERE n.grant_id = ?").all(t);for(const{node_id:n}of r)try{await Z(n,t)}catch(a){m("node_stop_failed",a,{grant:t,node_id:n})}}if(e.status==="removed"&&e.removal_done_at===null&&e.grantee!==null&&e.sub!==null)try{e.grantee!=="app:terminal"?await A(e.grantee,e.sub):x()?await P(e.grantee,e.sub):d({level:"info",event:"daemon.grants.removal_settled_without_cleanup",fields:{grant:t,grantee:e.grantee,sub:e.sub}}),await(await v()).prepare("UPDATE grants SET removal_done_at = ? WHERE id = ? AND rev = ? AND removal_done_at IS NULL").run(new Date().toISOString(),t,e.rev)}catch(r){m("removal_failed",r,{grant:t,grantee:e.grantee})}}}o(I,"laneEffects");async function ee(t,e,r){let n;await X(async()=>{const a=await E(e);q(e,a,r??await h()),t.serves&&(n=Q(e,a)),t.runsLanes&&a.standing!=="lagging"&&await I(e,a)}),await n}o(ee,"applyGrantEffects");async function te(t){const e=new Set;if(t.serves)for(const n of $())e.add(n);if(t.runsLanes){const n=await(await v()).prepare("SELECT DISTINCT n.grant_id FROM nodes n JOIN executions e ON e.node_id = n.node_id AND e.state != 'exited' WHERE n.grant_id IS NOT NULL").all();for(const{grant_id:a}of n)e.add(a)}const r=[];for(const n of e)(await E(n)).status===null&&r.push(n);return r}o(te,"goneGrantIds");async function Se(t,e={}){const r=new Map,n=o((s,l)=>{const i=(r.get(s)??Promise.resolve()).then(()=>ee(t,s,l)).catch(f=>m("effects_failed",f,{grant:s})).finally(()=>{r.get(s)===i&&r.delete(s)});return r.set(s,i),i},"run"),a=o(async()=>{const s=t.serves?N():void 0;try{t.serves&&G();const l=await h();g(l);const i=new Set(await y(`status <> 'active' OR expires_at <= '${new Date().toISOString()}'`));for(const f of await te(t))i.add(f);await Promise.all([...i].map(f=>n(f,l)))}catch(l){m("catch_up_failed",l,{})}await s},"catchUp"),c=new Map;let u=!1;const w=o(async()=>{if(!u){u=!0;try{const s=new Set(await y(`status = 'removed' AND removal_done_at IS NULL${W()?" AND grantee = 'app:terminal'":""}`));for(const i of c.keys())s.has(i)||c.delete(i);const l=[...s].filter(i=>!r.has(i)&&(c.get(i)?.notBefore??0)<=Date.now());await Promise.all(l.map(async i=>{await n(i);const f=(c.get(i)?.failures??0)+1;c.set(i,{failures:f,notBefore:Date.now()+S*2**Math.min(f,j)})}))}catch(s){m("removal_sweep_failed",s,{})}finally{u=!1}}},"sweepRemovals"),S=e.sweepMs??Y,p=t.runsLanes?setInterval(()=>{w()},S):void 0;p?.unref();const k=await J.subscribe(s=>{n(s)},{kinds:["grant"],onListenStart:o(()=>{a()},"onListenStart")});return()=>{p!==void 0&&clearInterval(p),k()}}o(Se,"startGrantEffects");export{ee as applyGrantEffects,Se as startGrantEffects};
1
+ var L=Object.defineProperty;var a=(t,e)=>L(t,"name",{value:e,configurable:!0});import{canvasPoolSize as T,openDb as v}from"../../core/canvas/db.js";import{isCloudRole as x}from"../../core/canvas/person.js";import{endLiveExecution as O,liveExecutionForNode as R}from"../../core/canvas/executions.js";import{emitEvent as m}from"../../core/events/emit.js";import{afterRevocationStop as D}from"../../core/grants/on-sync.js";import{allGrants as y,grantIdsWhere as S,grantStanding as E,mirrorOnly as M}from"../../core/grants/mirror.js";import{removeApp as A,removePersonData as P}from"../../core/grants/remove.js";import{wakeAllGrantWaiters as G,wakeGrantWaiters as C}from"../../core/grants/watch.js";import{discardOrphanedTokens as g,discardTokensForGrant as F}from"../../core/providers/token-cache.js";import{isUnsandboxedMachine as W}from"../../core/runtime/unsandboxed.js";import{runnerForExecution as U}from"../../core/runtime/runner/index.js";import{closeGrantStreams as B,heldGrantIds as $}from"../../core/runs/events.js";import{stopNodeSandboxes as H}from"../../core/spaces/stop.js";import{holdRecovery as J}from"../../core/runtime/recovery-hold.js";import{brokerSignalBus as z}from"../broker-signals/bus.js";import{withRowClaim as K}from"./row-claim.js";const V=6e4,X=a(()=>Math.max(1,Math.floor(T()/3)),"grantSlotLimit");let _=0;const b=[];async function Y(t){for(;_>=X();)await new Promise(e=>{b.push(e)});_+=1;try{return await t()}finally{_-=1,b.shift()?.()}}a(Y,"withGrantSlot");const j=3e4,q=5;function w(t,e,r){m({level:"error",event:`daemon.grants.${t}`,error:e,fields:r})}a(w,"failed");function Q(t,e,r){try{const n=e.sub===null||e.grantee===null?g(r):F({sub:e.sub,grantee:e.grantee,active:e.standing==="active"},r);n.tokens>0&&m({level:"info",event:"daemon.grants.outbound_tokens_discarded",fields:{grant:t,tokens:n.tokens}})}catch(n){w("outbound_tokens_discard_failed",n,{grant:t})}}a(Q,"discardTokens");async function N(){try{await(await import("../../core/providers/bundles.js")).syncProviderBundles()}catch(t){m({level:"error",event:"daemon.providers.bundle_sync_failed",error:t})}}a(N,"reconcileProviderBundles");async function Z(t,e){if(C(t),e.standing==="inactive"){const r=B(t);r>0&&m({level:"info",event:"daemon.grants.streams_closed",fields:{grant:t,grantee:e.grantee,streams:r}})}await N()}a(Z,"serveEffects");async function I(t,e){const r=await K("nodes",t,V,async n=>{const o=await R(t);if(o===null)return;await n.assertOwned(),m({level:"info",event:"daemon.grants.node_stop",node_id:t,fields:{grant:e,execution_id:o.executionId}});const c=a(async()=>{await n.assertOwned(),await O(t,{reason:"permission_revoked"}),await D(t)},"finish");if(o.runner==="process"){const u=await H(t,"permission_revoked",{holdRecovery:!0,after:c});if(!u.confirmed)throw u.error??new Error(`stop of ${t} was not confirmed`);return}const d=await J(t);if(d!==null)try{const u=await U(o.runner).stop(o,{reason:"permission_revoked"});if(!u.confirmed)throw u.error??new Error(`stop of ${t} was not confirmed`);await c()}finally{await d.release()}},{waitForLock:!0})}a(I,"stopRevokedNode");async function ee(t,e){if(!(e.grantee!==null&&M({grantee:e.grantee}))){if(e.standing==="inactive"){const r=await(await v()).prepare("SELECT DISTINCT n.node_id FROM nodes n JOIN executions e ON e.node_id = n.node_id AND e.state != 'exited' WHERE n.grant_id = ?").all(t);for(const{node_id:n}of r)try{await I(n,t)}catch(o){w("node_stop_failed",o,{grant:t,node_id:n})}}if(e.status==="removed"&&e.removal_done_at===null&&e.grantee!==null&&e.sub!==null)try{e.grantee!=="app:terminal"?await A(e.grantee,e.sub):x()?await P(e.grantee,e.sub):m({level:"info",event:"daemon.grants.removal_settled_without_cleanup",fields:{grant:t,grantee:e.grantee,sub:e.sub}}),await(await v()).prepare("UPDATE grants SET removal_done_at = ? WHERE id = ? AND rev = ? AND removal_done_at IS NULL").run(new Date().toISOString(),t,e.rev)}catch(r){w("removal_failed",r,{grant:t,grantee:e.grantee})}}}a(ee,"laneEffects");async function te(t,e,r){let n;await Y(async()=>{const o=await E(e);Q(e,o,r??await y()),t.serves&&(n=Z(e,o)),t.runsLanes&&o.standing!=="lagging"&&await ee(e,o)}),await n}a(te,"applyGrantEffects");async function re(t){const e=new Set;if(t.serves)for(const n of $())e.add(n);if(t.runsLanes){const n=await(await v()).prepare("SELECT DISTINCT n.grant_id FROM nodes n JOIN executions e ON e.node_id = n.node_id AND e.state != 'exited' WHERE n.grant_id IS NOT NULL").all();for(const{grant_id:o}of n)e.add(o)}const r=[];for(const n of e)(await E(n)).status===null&&r.push(n);return r}a(re,"goneGrantIds");async function Se(t,e={}){const r=new Map,n=a((s,l)=>{const i=(r.get(s)??Promise.resolve()).then(()=>te(t,s,l)).catch(f=>w("effects_failed",f,{grant:s})).finally(()=>{r.get(s)===i&&r.delete(s)});return r.set(s,i),i},"run"),o=a(async()=>{const s=t.serves?N():void 0;try{t.serves&&G();const l=await y();g(l);const i=new Set(await S(`status <> 'active' OR expires_at <= '${new Date().toISOString()}'`));for(const f of await re(t))i.add(f);await Promise.all([...i].map(f=>n(f,l)))}catch(l){w("catch_up_failed",l,{})}await s},"catchUp"),c=new Map;let d=!1;const u=a(async()=>{if(!d){d=!0;try{const s=new Set(await S(`status = 'removed' AND removal_done_at IS NULL${W()?" AND grantee = 'app:terminal'":""}`));for(const i of c.keys())s.has(i)||c.delete(i);const l=[...s].filter(i=>!r.has(i)&&(c.get(i)?.notBefore??0)<=Date.now());await Promise.all(l.map(async i=>{await n(i);const f=(c.get(i)?.failures??0)+1;c.set(i,{failures:f,notBefore:Date.now()+h*2**Math.min(f,q)})}))}catch(s){w("removal_sweep_failed",s,{})}finally{d=!1}}},"sweepRemovals"),h=e.sweepMs??j,p=t.runsLanes?setInterval(()=>{u()},h):void 0;p?.unref();const k=await z.subscribe(s=>{n(s)},{kinds:["grant"],onListenStart:a(()=>{o()},"onListenStart")});return()=>{p!==void 0&&clearInterval(p),k()}}a(Se,"startGrantEffects");export{te as applyGrantEffects,Se as startGrantEffects};
@@ -0,0 +1,5 @@
1
+ /** Ends each `running` machine execution whose machine reports no broker for it. The rows are read before the call, so a broker that
2
+ * started after the scan is never judged by it (its execution was not yet `running`). An environment whose call fails (offline, lost)
3
+ * is left as it is. A machine on a release before `status.all` is asked per execution with `status`, as before. A node held by an
4
+ * import is left to the import. Returns the nodes whose execution this call ended, so the caller can re-read their rows. */
5
+ export declare function endGoneMachineExecutions(): Promise<ReadonlySet<string>>;
@@ -0,0 +1,4 @@
1
+ var s=Object.defineProperty;var c=(n,o)=>s(n,"name",{value:o,configurable:!0});import{openDb as l}from"../../../core/canvas/db.js";import{endExecution as m,liveExecutionForNode as f}from"../../../core/canvas/executions.js";import{emitEvent as d}from"../../../core/events/emit.js";import{callMachine as u}from"../../../core/runtime/runner/machine/call.js";import{MachineCallFailedError as p,MachineOfflineError as x}from"../../../core/runtime/runner/machine/ops.js";import{importedNodesHeld as h}from"../live-obligation.js";import{endRemoteExecutionIfGone as w}from"./remote-wake.js";async function I(){const n=new Set;let o,a;try{a=await h(),o=await(await l()).prepare(`SELECT x.execution_id, x.node_id, e.object AS environment
2
+ FROM executions x JOIN nodes n ON n.node_id = x.node_id JOIN profiles p ON p.id = n.profile_id
3
+ JOIN environments e ON e.object = p.environment_id AND e.kind = 'machine'
4
+ WHERE x.state = 'running' AND x.runner = 'machine'`).all()}catch(e){return d({level:"error",event:"execution.machine_check_failed",error:e}),n}const i=new Map;for(const e of o)a.has(e.node_id)||i.set(e.environment,[...i.get(e.environment)??[],e]);return await Promise.all([...i].map(async([e,t])=>{try{await _(e,t,n)}catch(r){d({level:r instanceof x?"debug":"warn",event:"execution.machine_check_failed",fields:{environment:e},error:r})}})),n}c(I,"endGoneMachineExecutions");async function _(n,o,a){let i;try{i=new Set((await u(n,"status.all",{})).running.map(e=>e.execution))}catch(e){if(!(e instanceof p&&e.message.includes("does not execute status.all")))throw e;for(const{node_id:t}of o){const r=await f(t);r?.state==="running"&&r.runner==="machine"&&await w(r)&&a.add(t)}return}for(const{execution_id:e,node_id:t}of o)i.has(e)||await m(e,{reason:"lost"})&&(a.add(t),d({level:"warn",event:"execution.lost",node_id:t}))}c(_,"endGoneOn");export{I as endGoneMachineExecutions};
@@ -17,6 +17,9 @@ export declare function isLaunchInFlight(row: Pick<NodeRow, 'created' | 'launche
17
17
  export declare class NodeLifecycleReconciler {
18
18
  private readonly freezeLane;
19
19
  run(now: number, ctx: NodeLifecycleContext): Promise<FrozenCounts>;
20
+ /** The pass for one node whose broker exit was just reported (`execution_exit`), so its relaunch does not wait for the next tick. */
21
+ runNode(now: number, row: NodeRow, fleet: FleetRegistry): Promise<void>;
22
+ private pass;
20
23
  private classifyRow;
21
24
  private thawMark;
22
25
  /** An idle row with no wake-worthy inbox entry still needs the lifecycle
@@ -1 +1 @@
1
- var g=Object.defineProperty;var o=(s,i)=>g(s,"name",{value:i,configurable:!0});import{clearFrozen as P,getNode as z}from"../../../core/canvas/index.js";import{isSafeNodeId as L}from"../../../core/canvas/paths.js";import{recordedPidLiveness as x}from"../../../core/canvas/pid.js";import{endExecution as v,hasAbsorbedProfilePauseStop as N,hasObservedExit as M,latestExecutionForNode as w,liveExecutionForNode as c}from"../../../core/canvas/executions.js";import{emitEvent as I}from"../../../core/events/emit.js";import{operationIdContext as D}from"../../../core/events/operation-id.js";import{readInterruptedTurn as F}from"../../../core/canvas/recovery.js";import{isProfilePaused as d}from"../../../core/profiles/manifest.js";import{isRecoveryHeld as E}from"../../../core/runtime/recovery-hold.js";import{hasUnseenWakeMail as p}from"../../../core/canvas/deliveries.js";import{hasIdleReleaseIntent as A,isParkedResident as C}from"../../../core/runtime/lifecycle.js";import{classifyDeadNode as S}from"../../fleet.js";import{applyParkEvent as T,hasPendingWake as U,parkEvent as W}from"../live-obligation.js";import{FreezeLaneReconciler as B}from"./freeze-lane.js";import{isInBackoff as k}from"./respawn-policy.js";import{asNodePerson as G,NodePersonUnresolvedError as R}from"./node-person.js";import{handleTerminatingRow as H}from"./terminating.js";import{wantsExecution as O}from"./wants-execution.js";import{enactRequestedStops as q}from"./requested-stops.js";import{endRemoteExecutionIfGone as j,recoverLaunching as J,wakeResident as K}from"./remote-wake.js";import{isDrained as Q}from"../../drain.js";function V(s){return s.status==="done"||s.status==="canceled"||s.status==="dead"}o(V,"isTerminal");const X=12e4;function Y(s,i,e){const n=Math.max(...[s.created,s.launched_at].map(r=>r==null?0:Date.parse(r)||0));return n>0&&i-n<X&&e?.state!=="exited"}o(Y,"isLaunchInFlight");async function b(s){const i=await c(s);return i!==null&&i.state==="running"&&i.pid!=null&&x(i.pid,i.processIdentity)==="dead"?i:null}o(b,"executionWithDeadPid");class we{static{o(this,"NodeLifecycleReconciler")}freezeLane=new B;async run(i,e){const n=[];await q(i);for(const r of e.rows)await D.fresh(async()=>{try{await G(r,()=>this.classifyRow(i,r,e,n))}catch(t){const l=r.node_id;I({level:t instanceof R?"warn":"error",event:t instanceof R?"node.lifecycle.person_unresolved":"node.lifecycle.classify_failed",...L(l)?{node_id:l}:{fields:{affected_node_id:l}},error:t})}});return await Q()?{stalled:0,waitingOnMail:0}:this.freezeLane.run(i,{fleet:e.fleet,candidates:n})}async classifyRow(i,e,n,r){const t=e.node_id;if(V(e)){if(H(e,await n.fleet.has(t)))return;if(C(e)&&!await n.fleet.has(t)&&!d(e.profile_id)&&!await E(t)&&!k(e,i)&&await p(t)){r.push({row:e,enact:"reopen"});return}if(e.pi_pid!=null){const a=await b(t);a!==null&&await v(a.executionId,{reason:"observed-dead"})}e.frozen_at!=null&&(e.final_report!=null||e.status==="dead"?await P(t):r.push({row:e,enact:"thaw"}));return}if(await n.fleet.has(t)){const a=await c(t);if(a?.runner!==void 0&&a.runner!=="process"&&a.state==="running"&&!d(e.profile_id)&&await p(t)){if(await K(a)==="lost")return}else a?.runner!==void 0&&a.runner!=="process"&&a.state==="running"&&await j(a);if(await n.fleet.has(t)){d(e.profile_id)?await n.fleet.interruptForProfilePause(t):await this.thawMark(e);return}}if(await J(t,i))return;if(d(e.profile_id)){await this.freezeLane.endEpisode(t);return}if(await E(t))return;const l=e.pi_pid==null?await w(t):null,f=l!==null&&M(l),m=l!==null&&!f&&N(l),h=e.pi_pid!=null?await b(t):null,_=f||m||h!==null;if(_&&!await n.fleet.hasProfilePauseInterruption(t)){const a=h??l;a!==null&&await v(a.executionId,{reason:"observed-dead"});const y=await c(t);if(y!==null&&y.executionId!==a?.executionId)return}if(!await O(e)){await this.thawMark(e),await this.settleParked(e);return}if(k(e,i))return;if(e.status==="idle"&&A(e)&&await p(t)){r.push({row:e,enact:"idle-release"});return}if(e.pi_pid==null&&(!f||e.frozen_at!=null)&&!m){if(e.respawn_not_before!=null){r.push({row:e,enact:"policy"});return}if(e.frozen_at!=null){r.push({row:e,enact:"thaw"});return}if(await n.fleet.isClaimed(t)||Y(e,i,await w(t)))return;I({level:"warn",event:"node.lifecycle.stranded_launch",node_id:t}),r.push({row:e,enact:"thaw"});return}if(!_)return;const u=S(await z(t),(await F(t))?.interrupted===!0,await U(t));if(u==="respawn-fresh"||u==="respawn-cycle"||u==="respawn-resume"){r.push({row:e,enact:"policy"});return}await n.fleet.applyDeadRowPolicy(t),await this.thawMark(e)}async thawMark(i){i.frozen_at!=null&&await P(i.node_id)}async settleParked(i){if(i.status!=="idle")return;await this.freezeLane.endEpisode(i.node_id);const e=await W(i.node_id,i.lifecycle);e!=="release"&&await T(i.node_id,e)}}export{X as LAUNCH_GRACE_MS,we as NodeLifecycleReconciler,Y as isLaunchInFlight};
1
+ var g=Object.defineProperty;var l=(s,a)=>g(s,"name",{value:a,configurable:!0});import{clearFrozen as w,getNode as z,getRow as L}from"../../../core/canvas/index.js";import{isSafeNodeId as N}from"../../../core/canvas/paths.js";import{recordedPidLiveness as x}from"../../../core/canvas/pid.js";import{endExecution as P,hasAbsorbedProfilePauseStop as M,hasObservedExit as D,latestExecutionForNode as v,liveExecutionForNode as c}from"../../../core/canvas/executions.js";import{emitEvent as E}from"../../../core/events/emit.js";import{operationIdContext as F}from"../../../core/events/operation-id.js";import{readInterruptedTurn as A}from"../../../core/canvas/recovery.js";import{isProfilePaused as d}from"../../../core/profiles/manifest.js";import{isRecoveryHeld as I}from"../../../core/runtime/recovery-hold.js";import{hasUnseenWakeMail as p}from"../../../core/canvas/deliveries.js";import{hasIdleReleaseIntent as C,isParkedResident as S}from"../../../core/runtime/lifecycle.js";import{classifyDeadNode as G}from"../../fleet.js";import{applyParkEvent as T,hasPendingWake as U,parkEvent as W}from"../live-obligation.js";import{FreezeLaneReconciler as B}from"./freeze-lane.js";import{isInBackoff as R}from"./respawn-policy.js";import{asNodePerson as H,NodePersonUnresolvedError as k}from"./node-person.js";import{handleTerminatingRow as O}from"./terminating.js";import{wantsExecution as q}from"./wants-execution.js";import{enactRequestedStops as j}from"./requested-stops.js";import{endRemoteExecutionIfGone as J,recoverLaunching as K,wakeResident as Q}from"./remote-wake.js";import{endGoneMachineExecutions as V}from"./machine-sweep.js";import{isDrained as X}from"../../drain.js";function Y(s){return s.status==="done"||s.status==="canceled"||s.status==="dead"}l(Y,"isTerminal");const Z=12e4;function $(s,a,e){const i=Math.max(...[s.created,s.launched_at].map(n=>n==null?0:Date.parse(n)||0));return i>0&&a-i<Z&&e?.state!=="exited"}l($,"isLaunchInFlight");async function b(s){const a=await c(s);return a!==null&&a.state==="running"&&a.pid!=null&&x(a.pid,a.processIdentity)==="dead"?a:null}l(b,"executionWithDeadPid");class Re{static{l(this,"NodeLifecycleReconciler")}freezeLane=new B;async run(a,e){await j(a);const i=await V();if(i.size===0)return await this.pass(a,e);const n=await Promise.all(e.rows.map(async t=>i.has(t.node_id)?await L(t.node_id)??t:t));return await this.pass(a,{...e,rows:n})}async runNode(a,e,i){await this.pass(a,{rows:[e],fleet:i})}async pass(a,e){const i=[];for(const n of e.rows)await F.fresh(async()=>{try{await H(n,()=>this.classifyRow(a,n,e,i))}catch(t){const o=n.node_id;E({level:t instanceof k?"warn":"error",event:t instanceof k?"node.lifecycle.person_unresolved":"node.lifecycle.classify_failed",...N(o)?{node_id:o}:{fields:{affected_node_id:o}},error:t})}});return await X()?{stalled:0,waitingOnMail:0}:this.freezeLane.run(a,{fleet:e.fleet,candidates:i})}async classifyRow(a,e,i,n){const t=e.node_id;if(Y(e)){if(O(e,await i.fleet.has(t)))return;if(S(e)&&!await i.fleet.has(t)&&!d(e.profile_id)&&!await I(t)&&!R(e,a)&&await p(t)){n.push({row:e,enact:"reopen"});return}if(e.pi_pid!=null){const r=await b(t);r!==null&&await P(r.executionId,{reason:"observed-dead"})}e.frozen_at!=null&&(e.final_report!=null||e.status==="dead"?await w(t):n.push({row:e,enact:"thaw"}));return}if(await i.fleet.has(t)){const r=await c(t);if(r?.runner!==void 0&&r.runner!=="process"&&r.state==="running"&&!d(e.profile_id)&&await p(t)){if(await Q(r)==="lost")return}else r?.runner==="blaxel"&&r.state==="running"&&await J(r);if(await i.fleet.has(t)){d(e.profile_id)?await i.fleet.interruptForProfilePause(t):await this.thawMark(e);return}}if(await K(t,a))return;if(d(e.profile_id)){await this.freezeLane.endEpisode(t);return}if(await I(t))return;const o=e.pi_pid==null?await v(t):null,f=o!==null&&D(o),m=o!==null&&!f&&M(o),h=e.pi_pid!=null?await b(t):null,_=f||m||h!==null;if(_&&!await i.fleet.hasProfilePauseInterruption(t)){const r=h??o;r!==null&&await P(r.executionId,{reason:"observed-dead"});const y=await c(t);if(y!==null&&y.executionId!==r?.executionId)return}if(!await q(e)){await this.thawMark(e),await this.settleParked(e);return}if(R(e,a))return;if(e.status==="idle"&&C(e)&&await p(t)){n.push({row:e,enact:"idle-release"});return}if(e.pi_pid==null&&(!f||e.frozen_at!=null)&&!m){if(e.respawn_not_before!=null){n.push({row:e,enact:"policy"});return}if(e.frozen_at!=null){n.push({row:e,enact:"thaw"});return}if(await i.fleet.isClaimed(t)||$(e,a,await v(t)))return;E({level:"warn",event:"node.lifecycle.stranded_launch",node_id:t}),n.push({row:e,enact:"thaw"});return}if(!_)return;const u=G(await z(t),(await A(t))?.interrupted===!0,await U(t));if(u==="respawn-fresh"||u==="respawn-cycle"||u==="respawn-resume"){n.push({row:e,enact:"policy"});return}await i.fleet.applyDeadRowPolicy(t),await this.thawMark(e)}async thawMark(a){a.frozen_at!=null&&await w(a.node_id)}async settleParked(a){if(a.status!=="idle")return;await this.freezeLane.endEpisode(a.node_id);const e=await W(a.node_id,a.lifecycle);e!=="release"&&await T(a.node_id,e)}}export{Z as LAUNCH_GRACE_MS,Re as NodeLifecycleReconciler,$ as isLaunchInFlight};
@@ -32,6 +32,8 @@ The four `stream.*` records are notices from the forwarder, not run events. They
32
32
 
33
33
  When the page reloads mid-reply, or you get `stream_gap`, read `runs.trace(runId)` through your server and show each node's `in_progress_message` (`{thinking, text}` or `null`) as that node's open message. Then resume `runs.events(runId, {after: trace.latest_sequence})`, or forward with that cursor. Do not use a cursor from a separate `runs.get`.
34
34
 
35
+ `trace.files` lists the files the run's agents handed over (`crtr push file`): `{file_id, node_id, name, media_type, size, sequence_number, ts}`, ordered by `sequence_number`, only those at or before `latest_sequence`. Place each by `ts` among the messages, and ignore a live `file.sent` event whose `sequence_number` is already listed. Reach the bytes with `files.link(file_id)`.
36
+
35
37
  Keep appending new deltas to the open message, but replace its thinking or text with the complete content repeated by `node.thinking.done` or `node.output_text.done`. That shows the message from its beginning without duplicating content. `runs.get` and every `runs.list` entry carry `latest_sequence` and `last_activity_at`; a cursor equal to `latest_sequence` is not a gap even when older events have expired.
36
38
 
37
39
  ## Follow the reply to one message
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.661",
3
+ "version": "0.3.663",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -149,7 +149,7 @@
149
149
  },
150
150
  "license": "UNLICENSED",
151
151
  "dependencies": {
152
- "@north-light/identity": "0.3.661",
152
+ "@north-light/identity": "0.3.663",
153
153
  "@earendil-works/chord": "1.5.2",
154
154
  "@earendil-works/pi-agent-core": "1.5.2",
155
155
  "@earendil-works/pi-ai": "1.5.2",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.661",
3
+ "version": "0.3.663",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",