@north-light/cli 0.3.754 → 0.3.756

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/dist/api/client.d.ts +1 -2
  2. package/dist/api/client.js +3 -3
  3. package/dist/api/contract.d.ts +1 -1
  4. package/dist/api/contract.js +1 -1
  5. package/dist/api/dto/health.d.ts +0 -54
  6. package/dist/api/routes.d.ts +0 -1
  7. package/dist/api/routes.js +1 -1
  8. package/dist/build-root.d.ts +0 -3
  9. package/dist/build-root.js +1 -1
  10. package/dist/builtin-memory/crouter-sdk/release-notes.md +6 -0
  11. package/dist/builtin-memory/internal/storage-tiers.md +1 -1
  12. package/dist/cli.js +8 -9
  13. package/dist/clients/attach/viewer.js +481 -481
  14. package/dist/commands/sys/branch.js +1 -1
  15. package/dist/commands/sys/daemon.js +1 -1
  16. package/dist/commands/sys.js +1 -1
  17. package/dist/core/bootstrap.js +1 -1
  18. package/dist/core/canvas/boot.d.ts +0 -25
  19. package/dist/core/canvas/boot.js +1 -1
  20. package/dist/core/canvas/executions.d.ts +0 -3
  21. package/dist/core/canvas/executions.js +1 -1
  22. package/dist/core/canvas/pid.d.ts +0 -10
  23. package/dist/core/canvas/pid.js +5 -5
  24. package/dist/core/directory/join.js +1 -1
  25. package/dist/core/grants/mirror.d.ts +0 -5
  26. package/dist/core/grants/mirror.js +6 -6
  27. package/dist/core/grants/sync.js +1 -1
  28. package/dist/core/human/page-schema.d.ts +1 -1
  29. package/dist/core/io.js +4 -4
  30. package/dist/core/layout.d.ts +0 -2
  31. package/dist/core/layout.js +2 -2
  32. package/dist/core/runs/operations.js +7 -7
  33. package/dist/core/scoped-state/db.js +2 -2
  34. package/dist/daemon/api/handlers/daemon.js +1 -1
  35. package/dist/daemon/api/handlers/nodes.js +1 -1
  36. package/dist/daemon/api/map.d.ts +1 -6
  37. package/dist/daemon/api/map.js +2 -2
  38. package/dist/daemon/api/operations.js +1 -1
  39. package/dist/daemon/api/server.js +1 -1
  40. package/dist/daemon/control.d.ts +0 -8
  41. package/dist/daemon/crtrd.js +18 -20
  42. package/dist/daemon/manage.js +3 -3
  43. package/docs/sdk/release-notes.md +6 -0
  44. package/package.json +3 -3
  45. package/packages/crouter-api/dist/api/client.js +0 -3
  46. package/packages/crouter-api/dist/api/contract.js +1 -1
  47. package/packages/crouter-api/dist/api/routes.js +0 -1
  48. package/packages/crouter-api/dist/build-root.js +0 -9
  49. package/packages/crouter-api/dist/commands/sys/branch.js +1 -1
  50. package/packages/crouter-api/dist/commands/sys/daemon.js +1 -1
  51. package/packages/crouter-api/dist/commands/sys.js +1 -2
  52. package/packages/crouter-api/dist/core/canvas/executions.js +1 -17
  53. package/packages/crouter-api/dist/core/canvas/pid.js +0 -16
  54. package/packages/crouter-api/dist/core/directory/join.js +18 -1
  55. package/packages/crouter-api/dist/core/grants/mirror.js +0 -7
  56. package/packages/crouter-api/dist/core/grants/sync.js +2 -2
  57. package/packages/crouter-api/dist/core/io.js +0 -5
  58. package/packages/crouter-api/dist/core/layout.js +2 -19
  59. package/packages/crouter-api/dist/core/runs/operations.js +6 -0
  60. package/packages/crouter-api/dist/daemon/api/map.js +0 -16
  61. package/packages/crouter-api/dist/daemon/api/operations.js +0 -1
  62. package/packages/crouter-api/dist/daemon/manage.js +1 -1
  63. package/packages/crouter-api/package.json +1 -1
  64. package/packages/crouter-identity/package.json +1 -1
  65. package/packages/crouter-plugin/package.json +3 -3
  66. package/runtime.lock.json +14 -14
  67. package/dist/commands/sys/migrate.d.ts +0 -1
  68. package/dist/commands/sys/migrate.js +0 -1
  69. package/dist/core/feed/inbox-migrate.d.ts +0 -11
  70. package/dist/core/feed/inbox-migrate.js +0 -3
  71. package/dist/core/graph/bodies-boot-copy.d.ts +0 -28
  72. package/dist/core/graph/bodies-boot-copy.js +0 -1
  73. package/dist/core/layout-migrate/index.d.ts +0 -38
  74. package/dist/core/layout-migrate/index.js +0 -4
  75. package/dist/core/layout-migrate/loose-keys.d.ts +0 -2
  76. package/dist/core/layout-migrate/loose-keys.js +0 -1
  77. package/dist/core/layout-migrate/paths.d.ts +0 -30
  78. package/dist/core/layout-migrate/paths.js +0 -1
  79. package/dist/core/layout-migrate/stored-paths.d.ts +0 -9
  80. package/dist/core/layout-migrate/stored-paths.js +0 -11
  81. package/dist/core/layout-migrate/stores.d.ts +0 -30
  82. package/dist/core/layout-migrate/stores.js +0 -3
  83. package/dist/core/scoped-state/migrate.d.ts +0 -15
  84. package/dist/core/scoped-state/migrate.js +0 -3
  85. package/dist/daemon/boot-migrations.d.ts +0 -14
  86. package/dist/daemon/boot-migrations.js +0 -1
  87. package/dist/migrations/004-canvas-documents/apply.d.ts +0 -8
  88. package/dist/migrations/004-canvas-documents/apply.js +0 -1
  89. package/dist/migrations/004-canvas-documents/index.d.ts +0 -16
  90. package/dist/migrations/004-canvas-documents/index.js +0 -2
  91. package/dist/migrations/004-canvas-documents/legacy/discover.d.ts +0 -16
  92. package/dist/migrations/004-canvas-documents/legacy/discover.js +0 -1
  93. package/dist/migrations/004-canvas-documents/legacy/history.d.ts +0 -5
  94. package/dist/migrations/004-canvas-documents/legacy/history.js +0 -2
  95. package/dist/migrations/004-canvas-documents/legacy/nested.d.ts +0 -7
  96. package/dist/migrations/004-canvas-documents/legacy/nested.js +0 -1
  97. package/dist/migrations/004-canvas-documents/legacy/parse.d.ts +0 -14
  98. package/dist/migrations/004-canvas-documents/legacy/parse.js +0 -1
  99. package/dist/migrations/004-canvas-documents/legacy/types.d.ts +0 -91
  100. package/dist/migrations/004-canvas-documents/legacy/types.js +0 -0
  101. package/dist/migrations/004-canvas-documents/plan.d.ts +0 -102
  102. package/dist/migrations/004-canvas-documents/plan.js +0 -3
  103. package/dist/migrations/004-canvas-documents/pointers.d.ts +0 -23
  104. package/dist/migrations/004-canvas-documents/pointers.js +0 -4
  105. package/dist/migrations/activation.d.ts +0 -17
  106. package/dist/migrations/activation.js +0 -2
  107. package/packages/crouter-api/dist/commands/sys/migrate.js +0 -79
  108. package/packages/crouter-api/dist/core/layout-migrate/index.js +0 -523
  109. package/packages/crouter-api/dist/core/layout-migrate/paths.js +0 -118
  110. package/packages/crouter-api/dist/core/layout-migrate/stored-paths.js +0 -424
  111. package/packages/crouter-api/dist/core/layout-migrate/stores.js +0 -543
  112. package/packages/crouter-api/dist/core/locked-file.js +0 -121
  113. package/packages/crouter-api/dist/core/scoped-state/db.js +0 -271
  114. package/packages/crouter-api/dist/core/scoped-state/legacy-profiles.js +0 -65
  115. package/packages/crouter-api/dist/core/scoped-state/migrate.js +0 -332
  116. package/packages/crouter-api/dist/core/scoped-state/schema.js +0 -52
  117. package/packages/crouter-api/dist/migrations/004-canvas-documents/apply.js +0 -113
  118. package/packages/crouter-api/dist/migrations/004-canvas-documents/index.js +0 -89
  119. package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/discover.js +0 -251
  120. package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/history.js +0 -37
  121. package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/nested.js +0 -37
  122. package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/parse.js +0 -24
  123. package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/types.js +0 -3
  124. package/packages/crouter-api/dist/migrations/004-canvas-documents/plan.js +0 -410
  125. package/packages/crouter-api/dist/migrations/004-canvas-documents/pointers.js +0 -95
  126. package/packages/crouter-api/dist/migrations/activation.js +0 -46
@@ -1 +1 @@
1
- var o=Object.defineProperty;var t=(e,n)=>o(e,"name",{value:n,configurable:!0});import{defineBranch as r}from"../../core/command.js";const i={concept:"crtr configuration, diagnostics, and self-management",desc:"settings, config, connect, setup, tutorial, doctor, context, sync, migrate, join, update, version, feedback, logs, retry-delivery, support, limits, daemon",useWhen:"managing the crtr installation, inspecting diagnostics, operating the crtrd supervisor process, or registering a hosted runtime with its directory before first boot"},s={name:"sys",summary:"crtr system configuration, settings, diagnostics, and self-management",model:"Configuration and settings own durable behavior; diagnostics and support observe it. Setup, migration, sync, and update change installed or generated state, and join registers a stopped runtime with its directory from an enrollment token, while daemon control owns the supervisor lifecycle."};function d(e){return r({name:"sys",rootEntry:i,help:{...s},children:e})}t(d,"defineSysBranch");export{d as defineSysBranch};
1
+ var o=Object.defineProperty;var t=(e,n)=>o(e,"name",{value:n,configurable:!0});import{defineBranch as r}from"../../core/command.js";const i={concept:"crtr configuration, diagnostics, and self-management",desc:"settings, config, connect, setup, tutorial, doctor, context, sync, join, update, version, feedback, logs, retry-delivery, support, limits, daemon",useWhen:"managing the crtr installation, inspecting diagnostics, operating the crtrd supervisor process, or registering a hosted runtime with its directory before first boot"},s={name:"sys",summary:"crtr system configuration, settings, diagnostics, and self-management",model:"Configuration and settings own durable behavior; diagnostics and support observe it. Setup, migration, sync, and update change installed or generated state, and join registers a stopped runtime with its directory from an enrollment token, while daemon control owns the supervisor lifecycle."};function d(e){return r({name:"sys",rootEntry:i,help:{...s},children:e})}t(d,"defineSysBranch");export{d as defineSysBranch};
@@ -1 +1 @@
1
- var w=Object.defineProperty;var o=(n,e)=>w(n,"name",{value:e,configurable:!0});import{defineLeaf as u,defineBranch as g}from"../../core/command.js";import{InputError as d}from"../../core/io.js";import{parseDurationMs as y}from"../../core/wake.js";import{DaemonNotPreparedError as b,probeDaemonHealth as l,probeErrorMessage as v,spawnDaemon as p,stopDaemonProcess as c,sweepStrayDaemons as _}from"../../daemon/manage.js";import{isDaemonRunning as k,readPidfile as h,isPidAlive as m}from"../../daemon/pidfile.js";import{cliClient as T}from"../api-client.js";import{readMachineConfig as q}from"../../daemon/machine-link/config.js";import{apiSocketPath as x}from"../../core/canvas/paths.js";import{localClient as f}from"../../api/node-transport.js";import{defineSysBranch as I}from"./branch.js";import{selectedGeneration as D}from"./shared.js";const S=u({name:"start",description:"start the daemon in the background",whenToUse:"bringing the crtrd supervisor up for the first time in a session so node window-exits get handled (no-op only when its Unix API socket already serves)",help:{name:"sys daemon start",summary:"start the crtrd supervisor daemon in the background (no-op only if its Unix API socket serves)",params:[{kind:"flag",name:"prepare",type:"bool",required:!1,constraint:"Hold normal daemon work after storage preparation until `sys daemon admit`; omit for ordinary startup."}],output:[{name:"started",type:"boolean",required:!0,constraint:"True when a new daemon process was spawned; false when one was already running."},{name:"pid",type:"number",required:!1,constraint:"PID of the newly spawned daemon."},{name:"existing_pid",type:"number",required:!1,constraint:"PID of the already-running daemon (when started=false)."},{name:"running",type:"boolean",required:!1,constraint:"True only when a live pidfile owner does not serve its Unix API socket."},{name:"serving",type:"boolean",required:!1,constraint:"False only when a live pidfile owner does not answer /healthz."},{name:"probe_error",type:"string",required:!1,constraint:"The final /healthz probe failure when a live owner missed readiness."},{name:"startup_phase",type:"string",required:!1,constraint:"The observed daemon phase when it was reachable."}],outputKind:"object",effects:["Spawns dist/daemon/crtrd-cli.js detached + unref'd; it outlives this process.","Writes a pidfile at CRTR_PIDFILE if set, otherwise crtrHome()/crtrd.pid."]},run:o(async n=>{try{return await p({targetPhase:n.prepare===!0?"prepared":"ready"})}catch(e){throw e instanceof b?new d({error:"daemon_not_prepared",message:e.message,next:"Stop the live daemon, then start a new one with `crtr sys daemon start --prepare` before setup."}):e}},"run")}),P=100;async function E(n,e){const t=Date.now(),r=t+e;let s="initializing",i="the daemon socket was not reachable";for(;Date.now()<r;){try{const a=await l(Math.min(1e3,Math.max(1,r-Date.now())));if(s=a.startup_phase,i=a.startup_blocked??`daemon is ${a.startup_phase}`,a.startup_phase==="blocked")throw new d({error:"startup_blocked",message:a.startup_blocked??"daemon startup is blocked",received:a.startup_phase,field:"phase",next:"Repair the reported blocker paths with `crtr sys migrate`, then retry the await."});if(a.startup_phase===n)return{startup_phase:n,waited_ms:Date.now()-t};if(n==="prepared"&&a.startup_phase==="ready")throw new d({error:"await_missed_phase",message:"daemon is already ready and cannot return to prepared in this process",received:a.startup_phase,field:"phase",next:"Start a new daemon with `crtr sys daemon start --prepare` before awaiting prepared."})}catch(a){if(a instanceof d)throw a;i=a instanceof Error?a.message:String(a)}await new Promise(a=>setTimeout(a,Math.min(P,Math.max(0,r-Date.now()))))}throw new d({error:"await_timeout",message:`daemon did not reach ${n} within ${e}ms (last phase: ${s}; last observation: ${i})`,received:s,field:"phase",next:"Inspect `crtr sys daemon status` and resolve any reported startup blocker before retrying."})}o(E,"awaitDaemonPhase");const R=u({name:"await",description:"wait for a daemon startup phase",whenToUse:"a caller started or was given a daemon that must reach prepared or ready before its next step.",help:{name:"sys daemon await",summary:"wait for the running daemon to report one startup phase",params:[{kind:"flag",name:"phase",type:"enum",choices:["prepared","ready"],required:!0,constraint:"The phase that permits the caller\u2019s next step."},{kind:"flag",name:"timeout",type:"string",required:!1,default:"5m",constraint:"Maximum wait as a positive duration such as 90s, 5m, or 1h30m."}],output:[{name:"startup_phase",type:"string",required:!0,constraint:"The requested phase."},{name:"waited_ms",type:"number",required:!0,constraint:"Elapsed wall-clock time before the phase was observed."}],outputKind:"object",effects:["Read-only: polls /healthz until the requested phase is observed or the caller-bounded timeout expires."]},run:o(async n=>{const e=n.timeout,t=y(e);if(t===null||t<=0)throw new d({error:"invalid_duration",message:`not a positive duration: ${e}`,received:e,field:"timeout",next:"Use a positive duration such as 90s, 5m, or 1h30m."});return E(n.phase,t)},"run")}),A=u({name:"admit",description:"admit normal work after daemon preparation",whenToUse:"the caller has completed its setup against a prepared daemon and is ready for normal daemon work to start.",help:{name:"sys daemon admit",summary:"ask a prepared daemon to start normal services",params:[],output:[{name:"admitted",type:"boolean",required:!0,constraint:"True only when this request began admission."},{name:"already_admitted",type:"boolean",required:!0,constraint:"True when admission had already begun or completed."},{name:"startup_phase",type:"string",required:!0,constraint:"The phase after admission settles."}],outputKind:"object",effects:["Starts normal daemon services when the daemon is prepared."]},run:o(async n=>await f({autostart:!1}).admitDaemon(),"run")});async function M(n){if(n.generation_id!==void 0)return n.generation_id??void 0;try{return(await f({autostart:!1,socketPath:x()}).status()).generation_id??void 0}catch{return}}o(M,"servingGenerationId");const U=u({name:"status",description:"check whether the daemon is running",whenToUse:"operator/dev diagnostic \u2014 probing whether the crtrd supervisor process is alive while troubleshooting revive/supervision behavior",help:{name:"sys daemon status",summary:"check whether the crtrd supervisor daemon is currently running",params:[],output:[{name:"running",type:"boolean",required:!0,constraint:"True when the daemon pidfile owner is alive."},{name:"serving",type:"boolean",required:!1,constraint:"True when the live daemon answers /healthz; false when one probe does not."},{name:"pid",type:"number",required:!1,constraint:"PID of the running daemon."},{name:"probe_error",type:"string",required:!1,constraint:"The failed /healthz observation when the live owner did not answer."},{name:"startup_phase",type:"string",required:!1,constraint:"The observed daemon startup phase when the socket answered."},{name:"serving_generation",type:"string",required:!1,constraint:"Id of the runtime generation the daemon process was launched from. Absent when the daemon reports none (it predates the field, or runs from a development checkout) or its status could not be read."},{name:"selected_generation",type:"string",required:!1,constraint:"Id of the selected runtime generation. Absent when none is selected or it cannot be read."},{name:"generation_drift",type:"string",required:!1,constraint:"`none` when the serving and selected generation ids are equal; `differs` when they are not, meaning the daemon runs older bytes than the install selected until `sys daemon restart`; `unknown` when either id is absent. Never `none` on missing evidence."}],outputKind:"object",effects:["Read-only: reads the pidfile, probes the pid, and requests /healthz and /v1/status without autostart."]},run:o(async n=>{const e=h();if(!(e!==null&&m(e)))return{running:!1};try{const r=await l(),s=await M(r),i=D().generation?.id;return{running:!0,serving:r.ok,pid:e,...r.startup_phase===void 0?{}:{startup_phase:r.startup_phase},...s===void 0?{}:{serving_generation:s},...i===void 0?{}:{selected_generation:i},generation_drift:s===void 0||i===void 0?"unknown":s===i?"none":"differs"}}catch(r){return{running:!0,serving:!1,pid:e,probe_error:v(r)}}},"run")}),K=u({name:"restart",description:"put the selected runtime generation in service via a daemon-owned handover",whenToUse:"adopting a newly installed runtime generation \u2014 the routine restart. Use this instead of stop+start: the daemon answers before it hands over, so a caller running inside a node (whose broker the handover tears down) still gets a settled result and is resumed automatically.",help:{name:"sys daemon restart",summary:"ask the running daemon to replace itself with a successor on the selected runtime generation",params:[],output:[{name:"restarted",type:"boolean",required:!0,constraint:"True when a running daemon accepted the handover. False when none was running \u2014 one was started instead."},{name:"started",type:"boolean",required:!1,constraint:"True when no daemon was running and this call started one (restarted=false)."},{name:"pid",type:"number",required:!1,constraint:"The daemon that accepted the handover, or the one just started."},{name:"grace_ms",type:"number",required:!1,constraint:"How long the daemon waits after answering before teardown begins."},{name:"note",type:"string",required:!1,constraint:"What happens next to the calling node. Read it before acting on an interrupted turn."}],outputKind:"object",effects:["The daemon acknowledges immediately, then after a short grace tears its whole broker fleet down, releases its claim, spawns a successor on the runtime generation currently selected, and exits.","Each torn-down broker hands its foreground bash commands to the file-backed background job system; they keep running and report completion by urgent inbox message.","Every node it tore down \u2014 including the caller \u2014 is resolved by the successor through the ordinary row-driven supervision tick.","The calling process is killed as part of that teardown, AFTER this result is returned."]},run:o(async n=>{const e=T({local:!0});if(!k()){const t=await p();return{restarted:!1,started:t.started,...t.pid!==void 0?{pid:t.pid}:{},...t.existing_pid!==void 0?{pid:t.existing_pid}:{},note:"No daemon was running, so there was nothing to hand over; one was started on the selected runtime generation."}}if(q()!==void 0){const t=h();t!==null&&await c(t);const r=await p(),s=r.pid??r.existing_pid;return{restarted:!0,...s!==void 0?{pid:s}:{},note:"Machine-role daemon replaced on the selected runtime generation. Its brokers kept running; no node was interrupted."}}try{const t=await e.restartDaemon();return{restarted:t.accepted,pid:t.predecessor_pid,grace_ms:t.grace_ms,note:"Handover accepted. If you are running inside a node, your broker is about to be torn down and resumed on the new generation \u2014 THIS RESTART ALREADY SUCCEEDED. When your turn resumes with this result in the transcript, do not re-run it."}}catch(t){throw new d({error:"daemon_restart_failed",message:`the daemon did not accept a handover: ${t.message}`,next:"Run `crtr sys daemon status` to inspect the daemon."})}},"run")}),L=u({name:"stop",description:"stop the running daemon",whenToUse:"shutting the crtrd supervisor down for good, ending auto-revival of nodes on window exit. Not the way to pick up a new runtime generation \u2014 `restart` is, because stopping kills every broker of this epoch, including the caller's own, so this command cannot report its result to an agent that runs it.",help:{name:"sys daemon stop",summary:"stop the crtrd supervisor daemon and confirm it exited",params:[],output:[{name:"stopped",type:"boolean",required:!0,constraint:"True when a daemon (recorded or stray) was found and killed. False when none was running."},{name:"pid",type:"number",required:!1,constraint:"The recorded pidfile pid that exited (when one was recorded and alive)."},{name:"strays_killed",type:"array",required:!1,constraint:"PIDs of stray crtrd daemons (alive but not in the pidfile) swept alongside the recorded one \u2014 the backstop against a daemon that survived a prior stop."},{name:"force_killed",type:"boolean",required:!1,constraint:"True when the recorded daemon ignored SIGTERM and had to be SIGKILLed."}],outputKind:"object",effects:["Sends SIGTERM to the recorded pid and waits for it to exit and release its pidfile, escalating to SIGKILL if it does not.","Then sweeps any OTHER live crtrd daemon process (SIGTERM, escalating to SIGKILL after 2s) so a stray daemon orphaned from the pidfile cannot keep supervising."]},run:o(async n=>{const e=h(),t=e!==null&&m(e);try{let r=!1;t&&(r=await c(e)==="killed");const s=_(null);return!t&&s.length===0?{stopped:!1}:{stopped:!0,...t?{pid:e}:{},...s.length>0?{strays_killed:s}:{},...r?{force_killed:!0}:{}}}catch(r){throw new d({error:"daemon_stop_failed",message:`failed to stop daemon${t?` pid ${e}`:""}: ${r.message}`,next:"Run `crtr sys daemon status` to inspect the daemon before retrying."})}},"run")}),j=g({name:"daemon",description:"manage the crtrd supervisor process",whenToUse:"managing the crtrd supervisor that auto-revives nodes on window exit \u2014 start it, restart it onto a new runtime generation, check its status, or stop it",help:{name:"sys daemon",summary:"manage the crtrd canvas supervisor daemon",model:"crtrd is a thin background daemon that polls active+idle nodes and acts on window exit: crashed windows become dead; refresh-yield windows get a fresh respawn. It holds no orchestration logic \u2014 just process supervision. These are operator/dev self-management, not something a normal agent turn needs to check. Picking up a newly installed runtime generation is `restart` (a handover the daemon performs on itself); `stop` is the terminal one, and it kills the caller along with the rest of the fleet."},children:[S,R,A,K,U,L]});function Q(){return I([j])}o(Q,"registerDaemonControlSys");export{j as daemonBranch,Q as registerDaemonControlSys};
1
+ var w=Object.defineProperty;var o=(n,e)=>w(n,"name",{value:e,configurable:!0});import{defineLeaf as u,defineBranch as g}from"../../core/command.js";import{InputError as d}from"../../core/io.js";import{parseDurationMs as y}from"../../core/wake.js";import{DaemonNotPreparedError as b,probeDaemonHealth as l,probeErrorMessage as v,spawnDaemon as p,stopDaemonProcess as c,sweepStrayDaemons as _}from"../../daemon/manage.js";import{isDaemonRunning as k,readPidfile as h,isPidAlive as m}from"../../daemon/pidfile.js";import{cliClient as T}from"../api-client.js";import{readMachineConfig as q}from"../../daemon/machine-link/config.js";import{apiSocketPath as x}from"../../core/canvas/paths.js";import{localClient as f}from"../../api/node-transport.js";import{defineSysBranch as I}from"./branch.js";import{selectedGeneration as D}from"./shared.js";const S=u({name:"start",description:"start the daemon in the background",whenToUse:"bringing the crtrd supervisor up for the first time in a session so node window-exits get handled (no-op only when its Unix API socket already serves)",help:{name:"sys daemon start",summary:"start the crtrd supervisor daemon in the background (no-op only if its Unix API socket serves)",params:[{kind:"flag",name:"prepare",type:"bool",required:!1,constraint:"Hold normal daemon work after storage preparation until `sys daemon admit`; omit for ordinary startup."}],output:[{name:"started",type:"boolean",required:!0,constraint:"True when a new daemon process was spawned; false when one was already running."},{name:"pid",type:"number",required:!1,constraint:"PID of the newly spawned daemon."},{name:"existing_pid",type:"number",required:!1,constraint:"PID of the already-running daemon (when started=false)."},{name:"running",type:"boolean",required:!1,constraint:"True only when a live pidfile owner does not serve its Unix API socket."},{name:"serving",type:"boolean",required:!1,constraint:"False only when a live pidfile owner does not answer /healthz."},{name:"probe_error",type:"string",required:!1,constraint:"The final /healthz probe failure when a live owner missed readiness."},{name:"startup_phase",type:"string",required:!1,constraint:"The observed daemon phase when it was reachable."}],outputKind:"object",effects:["Spawns dist/daemon/crtrd-cli.js detached + unref'd; it outlives this process.","Writes a pidfile at CRTR_PIDFILE if set, otherwise crtrHome()/crtrd.pid."]},run:o(async n=>{try{return await p({targetPhase:n.prepare===!0?"prepared":"ready"})}catch(e){throw e instanceof b?new d({error:"daemon_not_prepared",message:e.message,next:"Stop the live daemon, then start a new one with `crtr sys daemon start --prepare` before setup."}):e}},"run")}),P=100;async function E(n,e){const t=Date.now(),r=t+e;let s="initializing",i="the daemon socket was not reachable";for(;Date.now()<r;){try{const a=await l(Math.min(1e3,Math.max(1,r-Date.now())));if(s=a.startup_phase,i=a.startup_blocked??`daemon is ${a.startup_phase}`,a.startup_phase==="blocked")throw new d({error:"startup_blocked",message:a.startup_blocked??"daemon startup is blocked",received:a.startup_phase,field:"phase",next:"Fix the reported blocker, then retry the await."});if(a.startup_phase===n)return{startup_phase:n,waited_ms:Date.now()-t};if(n==="prepared"&&a.startup_phase==="ready")throw new d({error:"await_missed_phase",message:"daemon is already ready and cannot return to prepared in this process",received:a.startup_phase,field:"phase",next:"Start a new daemon with `crtr sys daemon start --prepare` before awaiting prepared."})}catch(a){if(a instanceof d)throw a;i=a instanceof Error?a.message:String(a)}await new Promise(a=>setTimeout(a,Math.min(P,Math.max(0,r-Date.now()))))}throw new d({error:"await_timeout",message:`daemon did not reach ${n} within ${e}ms (last phase: ${s}; last observation: ${i})`,received:s,field:"phase",next:"Inspect `crtr sys daemon status` and resolve any reported startup blocker before retrying."})}o(E,"awaitDaemonPhase");const R=u({name:"await",description:"wait for a daemon startup phase",whenToUse:"a caller started or was given a daemon that must reach prepared or ready before its next step.",help:{name:"sys daemon await",summary:"wait for the running daemon to report one startup phase",params:[{kind:"flag",name:"phase",type:"enum",choices:["prepared","ready"],required:!0,constraint:"The phase that permits the caller\u2019s next step."},{kind:"flag",name:"timeout",type:"string",required:!1,default:"5m",constraint:"Maximum wait as a positive duration such as 90s, 5m, or 1h30m."}],output:[{name:"startup_phase",type:"string",required:!0,constraint:"The requested phase."},{name:"waited_ms",type:"number",required:!0,constraint:"Elapsed wall-clock time before the phase was observed."}],outputKind:"object",effects:["Read-only: polls /healthz until the requested phase is observed or the caller-bounded timeout expires."]},run:o(async n=>{const e=n.timeout,t=y(e);if(t===null||t<=0)throw new d({error:"invalid_duration",message:`not a positive duration: ${e}`,received:e,field:"timeout",next:"Use a positive duration such as 90s, 5m, or 1h30m."});return E(n.phase,t)},"run")}),A=u({name:"admit",description:"admit normal work after daemon preparation",whenToUse:"the caller has completed its setup against a prepared daemon and is ready for normal daemon work to start.",help:{name:"sys daemon admit",summary:"ask a prepared daemon to start normal services",params:[],output:[{name:"admitted",type:"boolean",required:!0,constraint:"True only when this request began admission."},{name:"already_admitted",type:"boolean",required:!0,constraint:"True when admission had already begun or completed."},{name:"startup_phase",type:"string",required:!0,constraint:"The phase after admission settles."}],outputKind:"object",effects:["Starts normal daemon services when the daemon is prepared."]},run:o(async n=>await f({autostart:!1}).admitDaemon(),"run")});async function M(n){if(n.generation_id!==void 0)return n.generation_id??void 0;try{return(await f({autostart:!1,socketPath:x()}).status()).generation_id??void 0}catch{return}}o(M,"servingGenerationId");const U=u({name:"status",description:"check whether the daemon is running",whenToUse:"operator/dev diagnostic \u2014 probing whether the crtrd supervisor process is alive while troubleshooting revive/supervision behavior",help:{name:"sys daemon status",summary:"check whether the crtrd supervisor daemon is currently running",params:[],output:[{name:"running",type:"boolean",required:!0,constraint:"True when the daemon pidfile owner is alive."},{name:"serving",type:"boolean",required:!1,constraint:"True when the live daemon answers /healthz; false when one probe does not."},{name:"pid",type:"number",required:!1,constraint:"PID of the running daemon."},{name:"probe_error",type:"string",required:!1,constraint:"The failed /healthz observation when the live owner did not answer."},{name:"startup_phase",type:"string",required:!1,constraint:"The observed daemon startup phase when the socket answered."},{name:"serving_generation",type:"string",required:!1,constraint:"Id of the runtime generation the daemon process was launched from. Absent when the daemon reports none (it predates the field, or runs from a development checkout) or its status could not be read."},{name:"selected_generation",type:"string",required:!1,constraint:"Id of the selected runtime generation. Absent when none is selected or it cannot be read."},{name:"generation_drift",type:"string",required:!1,constraint:"`none` when the serving and selected generation ids are equal; `differs` when they are not, meaning the daemon runs older bytes than the install selected until `sys daemon restart`; `unknown` when either id is absent. Never `none` on missing evidence."}],outputKind:"object",effects:["Read-only: reads the pidfile, probes the pid, and requests /healthz and /v1/status without autostart."]},run:o(async n=>{const e=h();if(!(e!==null&&m(e)))return{running:!1};try{const r=await l(),s=await M(r),i=D().generation?.id;return{running:!0,serving:r.ok,pid:e,...r.startup_phase===void 0?{}:{startup_phase:r.startup_phase},...s===void 0?{}:{serving_generation:s},...i===void 0?{}:{selected_generation:i},generation_drift:s===void 0||i===void 0?"unknown":s===i?"none":"differs"}}catch(r){return{running:!0,serving:!1,pid:e,probe_error:v(r)}}},"run")}),K=u({name:"restart",description:"put the selected runtime generation in service via a daemon-owned handover",whenToUse:"adopting a newly installed runtime generation \u2014 the routine restart. Use this instead of stop+start: the daemon answers before it hands over, so a caller running inside a node (whose broker the handover tears down) still gets a settled result and is resumed automatically.",help:{name:"sys daemon restart",summary:"ask the running daemon to replace itself with a successor on the selected runtime generation",params:[],output:[{name:"restarted",type:"boolean",required:!0,constraint:"True when a running daemon accepted the handover. False when none was running \u2014 one was started instead."},{name:"started",type:"boolean",required:!1,constraint:"True when no daemon was running and this call started one (restarted=false)."},{name:"pid",type:"number",required:!1,constraint:"The daemon that accepted the handover, or the one just started."},{name:"grace_ms",type:"number",required:!1,constraint:"How long the daemon waits after answering before teardown begins."},{name:"note",type:"string",required:!1,constraint:"What happens next to the calling node. Read it before acting on an interrupted turn."}],outputKind:"object",effects:["The daemon acknowledges immediately, then after a short grace tears its whole broker fleet down, releases its claim, spawns a successor on the runtime generation currently selected, and exits.","Each torn-down broker hands its foreground bash commands to the file-backed background job system; they keep running and report completion by urgent inbox message.","Every node it tore down \u2014 including the caller \u2014 is resolved by the successor through the ordinary row-driven supervision tick.","The calling process is killed as part of that teardown, AFTER this result is returned."]},run:o(async n=>{const e=T({local:!0});if(!k()){const t=await p();return{restarted:!1,started:t.started,...t.pid!==void 0?{pid:t.pid}:{},...t.existing_pid!==void 0?{pid:t.existing_pid}:{},note:"No daemon was running, so there was nothing to hand over; one was started on the selected runtime generation."}}if(q()!==void 0){const t=h();t!==null&&await c(t);const r=await p(),s=r.pid??r.existing_pid;return{restarted:!0,...s!==void 0?{pid:s}:{},note:"Machine-role daemon replaced on the selected runtime generation. Its brokers kept running; no node was interrupted."}}try{const t=await e.restartDaemon();return{restarted:t.accepted,pid:t.predecessor_pid,grace_ms:t.grace_ms,note:"Handover accepted. If you are running inside a node, your broker is about to be torn down and resumed on the new generation \u2014 THIS RESTART ALREADY SUCCEEDED. When your turn resumes with this result in the transcript, do not re-run it."}}catch(t){throw new d({error:"daemon_restart_failed",message:`the daemon did not accept a handover: ${t.message}`,next:"Run `crtr sys daemon status` to inspect the daemon."})}},"run")}),L=u({name:"stop",description:"stop the running daemon",whenToUse:"shutting the crtrd supervisor down for good, ending auto-revival of nodes on window exit. Not the way to pick up a new runtime generation \u2014 `restart` is, because stopping kills every broker of this epoch, including the caller's own, so this command cannot report its result to an agent that runs it.",help:{name:"sys daemon stop",summary:"stop the crtrd supervisor daemon and confirm it exited",params:[],output:[{name:"stopped",type:"boolean",required:!0,constraint:"True when a daemon (recorded or stray) was found and killed. False when none was running."},{name:"pid",type:"number",required:!1,constraint:"The recorded pidfile pid that exited (when one was recorded and alive)."},{name:"strays_killed",type:"array",required:!1,constraint:"PIDs of stray crtrd daemons (alive but not in the pidfile) swept alongside the recorded one \u2014 the backstop against a daemon that survived a prior stop."},{name:"force_killed",type:"boolean",required:!1,constraint:"True when the recorded daemon ignored SIGTERM and had to be SIGKILLed."}],outputKind:"object",effects:["Sends SIGTERM to the recorded pid and waits for it to exit and release its pidfile, escalating to SIGKILL if it does not.","Then sweeps any OTHER live crtrd daemon process (SIGTERM, escalating to SIGKILL after 2s) so a stray daemon orphaned from the pidfile cannot keep supervising."]},run:o(async n=>{const e=h(),t=e!==null&&m(e);try{let r=!1;t&&(r=await c(e)==="killed");const s=_(null);return!t&&s.length===0?{stopped:!1}:{stopped:!0,...t?{pid:e}:{},...s.length>0?{strays_killed:s}:{},...r?{force_killed:!0}:{}}}catch(r){throw new d({error:"daemon_stop_failed",message:`failed to stop daemon${t?` pid ${e}`:""}: ${r.message}`,next:"Run `crtr sys daemon status` to inspect the daemon before retrying."})}},"run")}),j=g({name:"daemon",description:"manage the crtrd supervisor process",whenToUse:"managing the crtrd supervisor that auto-revives nodes on window exit \u2014 start it, restart it onto a new runtime generation, check its status, or stop it",help:{name:"sys daemon",summary:"manage the crtrd canvas supervisor daemon",model:"crtrd is a thin background daemon that polls active+idle nodes and acts on window exit: crashed windows become dead; refresh-yield windows get a fresh respawn. It holds no orchestration logic \u2014 just process supervision. These are operator/dev self-management, not something a normal agent turn needs to check. Picking up a newly installed runtime generation is `restart` (a handover the daemon performs on itself); `stop` is the terminal one, and it kills the caller along with the rest of the fleet."},children:[S,R,A,K,U,L]});function Q(){return I([j])}o(Q,"registerDaemonControlSys");export{j as daemonBranch,Q as registerDaemonControlSys};
@@ -1 +1 @@
1
- var s=Object.defineProperty;var r=(o,m)=>s(o,"name",{value:m,configurable:!0});import{defineSysBranch as t}from"./sys/branch.js";import{configBranch as f}from"./sys/config.js";import{sysEnvBranch as i}from"./sys/env.js";import{daemonBranch as e}from"./sys/daemon.js";import{sysDoctorLeaf as a}from"./sys/doctor.js";import{sysFeedbackLeaf as p}from"./sys/feedback.js";import{sysLogsLeaf as n}from"./sys/logs.js";import{sysRetryDeliveryLeaf as y}from"./sys/retry-delivery.js";import{sysWorktreesLeaf as c}from"./sys/worktrees.js";import{sysSpacesLeaf as L}from"./sys/spaces.js";import{sysLimitsBranch as h}from"./sys/limits.js";import{sysSpendBranch as B}from"./sys/spend.js";import{sysSettingsLeaf as S}from"./sys/settings.js";import{sysSetupLeaf as g}from"./sys/setup.js";import{tutorialBranch as u}from"./sys/tutorial/branch.js";import{supportBranch as d}from"./sys/support.js";import{contextBranch as k}from"./sys/context.js";import{sysSyncBranch as D}from"./sys/sync.js";import{sysMigrateLeaf as l}from"./sys/migrate.js";import{sysJoinLeaf as v}from"./sys/join.js";import{sysImportBranch as x}from"./sys/import/start.js";import{sysMachineBranch as M}from"./sys/machine/rotate.js";import{sysDesktopBranch as b}from"./sys/desktop.js";import{sysSigninLeaf as E,sysSignoutLeaf as F}from"./sys/signin.js";import{sysUpdateLeaf as I,sysVersionLeaf as J}from"./sys/update.js";function sr(){return t([S,f,i,g,u,a,k,p,n,c,y,L,h,B,d,I,J,l,v,D,x,M,E,F,b,e])}r(sr,"registerSys");export{sr as registerSys};
1
+ var s=Object.defineProperty;var r=(o,m)=>s(o,"name",{value:m,configurable:!0});import{defineSysBranch as t}from"./sys/branch.js";import{configBranch as f}from"./sys/config.js";import{sysEnvBranch as i}from"./sys/env.js";import{daemonBranch as e}from"./sys/daemon.js";import{sysDoctorLeaf as p}from"./sys/doctor.js";import{sysFeedbackLeaf as a}from"./sys/feedback.js";import{sysLogsLeaf as n}from"./sys/logs.js";import{sysRetryDeliveryLeaf as y}from"./sys/retry-delivery.js";import{sysWorktreesLeaf as c}from"./sys/worktrees.js";import{sysSpacesLeaf as L}from"./sys/spaces.js";import{sysLimitsBranch as h}from"./sys/limits.js";import{sysSpendBranch as B}from"./sys/spend.js";import{sysSettingsLeaf as S}from"./sys/settings.js";import{sysSetupLeaf as g}from"./sys/setup.js";import{tutorialBranch as u}from"./sys/tutorial/branch.js";import{supportBranch as d}from"./sys/support.js";import{contextBranch as k}from"./sys/context.js";import{sysSyncBranch as D}from"./sys/sync.js";import{sysJoinLeaf as l}from"./sys/join.js";import{sysImportBranch as v}from"./sys/import/start.js";import{sysMachineBranch as x}from"./sys/machine/rotate.js";import{sysDesktopBranch as b}from"./sys/desktop.js";import{sysSigninLeaf as E,sysSignoutLeaf as F}from"./sys/signin.js";import{sysUpdateLeaf as I,sysVersionLeaf as J}from"./sys/update.js";function or(){return t([S,f,i,g,u,p,k,a,n,c,y,L,h,B,d,I,J,l,D,v,x,E,F,b,e])}r(or,"registerSys");export{or as registerSys};
@@ -1,2 +1,2 @@
1
- var i=Object.defineProperty;var t=(e,r)=>i(e,"name",{value:r,configurable:!0});import{homedir as s}from"node:os";import{join as c,relative as p,sep as f}from"node:path";import{appsRoot as u}from"./layout.js";import{findProjectScopeRoot as m,userScopeRoot as a}from"./scope.js";import{ensureScopeInitialized as S}from"./config.js";import{CRTR_DIR_NAME as d}from"../types.js";import{envDebug as h}from"../shared/env.js";const l=new Set(["help","--help","-h","--version","-v"]);function R(e){const r=e[2];return r===void 0||r==="sys"&&e[3]==="migrate"?!0:l.has(r)}t(R,"shouldSkipForArgv");async function T(e){try{if(process.env.CRTR_NO_AUTO_INIT==="1"||R(e)||m()!==null)return;const r=process.cwd();if(r===s())return;const o=p(u(),r).split(f);if(o.length===2&&o[1]==="home")return;const n=c(r,d);if(n===a())return;await S("project",n)}catch(r){if(h()){const o=r instanceof Error?r.message:String(r);process.stderr.write(`crtr: project-init error: ${o}
1
+ var i=Object.defineProperty;var t=(o,r)=>i(o,"name",{value:r,configurable:!0});import{homedir as s}from"node:os";import{join as c,relative as p,sep as f}from"node:path";import{appsRoot as m}from"./layout.js";import{findProjectScopeRoot as u,userScopeRoot as a}from"./scope.js";import{ensureScopeInitialized as S}from"./config.js";import{CRTR_DIR_NAME as d}from"../types.js";import{envDebug as h}from"../shared/env.js";const l=new Set(["help","--help","-h","--version","-v"]);function R(o){const r=o[2];return r===void 0?!0:l.has(r)}t(R,"shouldSkipForArgv");async function T(o){try{if(process.env.CRTR_NO_AUTO_INIT==="1"||R(o)||u()!==null)return;const r=process.cwd();if(r===s())return;const e=p(m(),r).split(f);if(e.length===2&&e[1]==="home")return;const n=c(r,d);if(n===a())return;await S("project",n)}catch(r){if(h()){const e=r instanceof Error?r.message:String(r);process.stderr.write(`crtr: project-init error: ${e}
2
2
  `)}}}t(T,"ensureProjectScope");export{T as ensureProjectScope};
@@ -65,28 +65,3 @@ export interface BootReconcileResult {
65
65
  * `current` defaults to the real identity; tests inject a synthetic one against
66
66
  * an isolated CRTR_HOME to simulate a boot change without a real reboot. */
67
67
  export declare function reconcileBootLiveness(current?: BootIdentity): Promise<BootReconcileResult>;
68
- /** The one-time execution-identity migration, injected into the startup
69
- * composition. In production this is `migrateLegacyExecutionIdentities` from
70
- * executions.ts. It remains injected so tests can exercise this composition
71
- * without reaching process inspection. */
72
- export type MigrateLegacyExecutionIdentities = (captureIdentity?: (pid: number) => string | undefined) => Promise<{
73
- migrated: string[];
74
- }>;
75
- export interface BootStartupResult {
76
- /** The pid-liveness reconciliation result (boot-change sweep + provenance). */
77
- reconcile: BootReconcileResult;
78
- /** node_ids whose legacy identity baseline was migrated — empty when the
79
- * provenance gate skipped the sweep. */
80
- migrated: string[];
81
- }
82
- /** The daemon's one-time startup boot composition, the single source of truth
83
- * for its ORDERING and GATE: reconcile pid liveness FIRST (clearing any pids
84
- * recorded before this boot), then run the legacy identity migration ONLY when
85
- * reconciliation positively PROVED same-boot provenance (`sameBootProven`).
86
- * Both `runDaemon` and the migration-gate regression tests call this, so a
87
- * revert that inverts the gate, drops it, or reorders migration ahead of
88
- * reconciliation is caught here rather than only in a test-side duplicate.
89
- *
90
- * `migrate` is injected (see `MigrateLegacyPidIdentities`); `current` and
91
- * `captureIdentity` pass through to the two steps for test injection. */
92
- export declare function reconcileAndMigrateBoot(migrate: MigrateLegacyExecutionIdentities, current?: BootIdentity, captureIdentity?: (pid: number) => string | undefined): Promise<BootStartupResult>;
@@ -1 +1 @@
1
- var l=Object.defineProperty;var n=(t,o)=>l(t,"name",{value:o,configurable:!0});import{uptime as p}from"node:os";import{withCanvasWrite as f}from"./db.js";import{readKernelBootId as E}from"./boot-id.js";import{readKernelBootId as S}from"./boot-id.js";const b=6e4;function I(t=Date.now()){return{bootId:E(),bootEpochMs:t-Math.round(p()*1e3)}}n(I,"currentBootIdentity");function h(t,o){return o===null?!1:t.bootId!==null&&o.bootId!==null?t.bootId!==o.bootId:Math.abs(t.bootEpochMs-o.bootEpochMs)>b}n(h,"bootChanged");function m(t,o){return o!==null&&t.bootId!==null&&o.bootId!==null&&t.bootId===o.bootId}n(m,"bootProvenSame");const s="boot_identity";async function x(t){const o=await t.prepare("SELECT value FROM canvas_meta WHERE key = ?").get(s);if(o===void 0)return null;try{const e=JSON.parse(o.value);return typeof e.bootEpochMs!="number"?null:{bootId:typeof e.bootId=="string"?e.bootId:null,bootEpochMs:e.bootEpochMs}}catch{return null}}n(x,"readBootMarker");async function u(t,o){await t.prepareUncached("INSERT INTO canvas_meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(s,JSON.stringify(o))}n(u,"writeBootMarker");async function _(t=I()){return f(async o=>{const e=await x(o);if(!h(t,e)){e===null&&await u(o,t);const r=m(t,e);return{changed:!1,cleared:[],sameBootProven:r}}const a=await o.prepare("SELECT execution_id, node_id FROM executions WHERE state != 'exited'").all(),i=o.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exit_reason = 'boot-change' WHERE execution_id = ? AND state != 'exited'"),c=[],d=new Date().toISOString();for(const r of a)(await i.run(d,r.execution_id)).changes>0&&c.push(r.node_id);return await u(o,t),{changed:!0,cleared:c,sameBootProven:!1}})}n(_,"reconcileBootLiveness");async function g(t,o,e){const a=await _(o),i=a.sameBootProven?(await t(e)).migrated:[];return{reconcile:a,migrated:i}}n(g,"reconcileAndMigrateBoot");export{h as bootChanged,m as bootProvenSame,I as currentBootIdentity,S as readKernelBootId,g as reconcileAndMigrateBoot,_ as reconcileBootLiveness};
1
+ var l=Object.defineProperty;var n=(t,o)=>l(t,"name",{value:o,configurable:!0});import{uptime as p}from"node:os";import{withCanvasWrite as E}from"./db.js";import{readKernelBootId as f}from"./boot-id.js";import{readKernelBootId as w}from"./boot-id.js";const b=6e4;function I(t=Date.now()){return{bootId:f(),bootEpochMs:t-Math.round(p()*1e3)}}n(I,"currentBootIdentity");function h(t,o){return o===null?!1:t.bootId!==null&&o.bootId!==null?t.bootId!==o.bootId:Math.abs(t.bootEpochMs-o.bootEpochMs)>b}n(h,"bootChanged");function _(t,o){return o!==null&&t.bootId!==null&&o.bootId!==null&&t.bootId===o.bootId}n(_,"bootProvenSame");const i="boot_identity";async function x(t){const o=await t.prepare("SELECT value FROM canvas_meta WHERE key = ?").get(i);if(o===void 0)return null;try{const e=JSON.parse(o.value);return typeof e.bootEpochMs!="number"?null:{bootId:typeof e.bootId=="string"?e.bootId:null,bootEpochMs:e.bootEpochMs}}catch{return null}}n(x,"readBootMarker");async function s(t,o){await t.prepareUncached("INSERT INTO canvas_meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(i,JSON.stringify(o))}n(s,"writeBootMarker");async function v(t=I()){return E(async o=>{const e=await x(o);if(!h(t,e)){e===null&&await s(o,t);const a=_(t,e);return{changed:!1,cleared:[],sameBootProven:a}}const u=await o.prepare("SELECT execution_id, node_id FROM executions WHERE state != 'exited'").all(),c=o.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exit_reason = 'boot-change' WHERE execution_id = ? AND state != 'exited'"),r=[],d=new Date().toISOString();for(const a of u)(await c.run(d,a.execution_id)).changes>0&&r.push(a.node_id);return await s(o,t),{changed:!0,cleared:r,sameBootProven:!1}})}n(v,"reconcileBootLiveness");export{h as bootChanged,_ as bootProvenSame,I as currentBootIdentity,w as readKernelBootId,v as reconcileBootLiveness};
@@ -77,9 +77,6 @@ export declare function abortExecution(executionId: string, input: {
77
77
  export declare function endLiveExecution(nodeId: string, input: {
78
78
  reason: ExecutionEndReason;
79
79
  }): Promise<boolean>;
80
- export declare function migrateLegacyExecutionIdentities(captureIdentity?: (pid: number) => string | undefined): Promise<{
81
- migrated: string[];
82
- }>;
83
80
  /** Records a stop request on the node's live execution; the first request's time and reason stand. */
84
81
  export declare function requestExecutionStop(nodeId: string, input: {
85
82
  afterTurn: boolean;
@@ -1 +1 @@
1
- var D=Object.defineProperty;var a=(e,t)=>D(e,"name",{value:t,configurable:!0});import{randomUUID as g}from"node:crypto";import{openDb as r,withCanvasWrite as _}from"./db.js";import{capturePidIdentities as R,captureLivenessSnapshot as m,identitiesMatch as y,recordedPidLiveness as O,isBootScopedIdentity as C,isLegacyTicksIdentity as U}from"./pid.js";import{existsSync as P,readFileSync as W}from"node:fs";import{LAUNCHER_SOCKET as H}from"../../launcher/spec.js";import{revokeNodeTokens as x}from"./node-tokens.js";import{clearPendingParkIn as l}from"../../daemon/park-pending.js";import{deleteSandboxOfEndedNode as w}from"../runtime/runner/delete-sandboxes.js";function d(){return new Date().toISOString()}a(d,"now");function N(e){return{executionId:e.execution_id,nodeId:e.node_id,daemonEpoch:e.daemon_epoch??null,pid:e.pid??null,processIdentity:e.process_identity??null,state:e.state,startedAt:e.started_at,endedAt:e.ended_at??null,exitReason:e.exit_reason??null,runner:e.runner,attempt:Number(e.attempt),release:e.release??null,heartbeatAt:e.heartbeat_at??null,awakeSince:e.awake_since??null,idleAt:e.idle_at??null,exitedAt:e.exited_at??null,launchJson:e.launch_json??null,stopRequestedAt:e.stop_requested_at??null,stopAfterTurn:Number(e.stop_after_turn)===1,stopReason:e.stop_reason??null}}a(N,"hydrate");async function J(e){const t=await(await r()).prepare("SELECT * FROM executions WHERE node_id = ? AND state != 'exited'").get(e);return t===void 0?null:N(t)}a(J,"liveExecutionForNode");class F extends Error{static{a(this,"ExecutionCapReached")}cap;live;constructor(t,n){super(`no broker slot is free \u2014 ${n} live executions at the cap of ${t}.`),this.cap=t,this.live=n,this.name="ExecutionCapReached"}}class b extends Error{static{a(this,"ExecutionAlreadyLive")}nodeId;executionId;constructor(t,n){super(`${t} already has a live execution ${n}.`),this.nodeId=t,this.executionId=n,this.name="ExecutionAlreadyLive"}}const v=7340001;async function G(e,t){return await _(async n=>{const i=d();if(!await n.prepare("SELECT node_id FROM nodes WHERE node_id = ? FOR UPDATE").get(e))throw new Error(`cannot begin execution: missing node ${e}`);if(t.cap!==void 0){await n.prepare(`SELECT pg_advisory_xact_lock(${v})`).get();const u=Number((await n.prepare("SELECT COUNT(*) AS n FROM executions WHERE state != 'exited' AND node_id != ?").get(e)).n);if(u>=t.cap)throw new F(t.cap,u)}const s=(await n.prepare("SELECT execution_id, runner, daemon_epoch, state, pid, process_identity FROM executions WHERE node_id = ? AND state != 'exited'").all(e)).find(u=>u.runner!=="process"||t.daemonEpoch!==null&&u.daemon_epoch===t.daemonEpoch&&(u.state==="launching"||O(u.pid,u.process_identity,m())!=="dead"));if(s!==void 0)throw new b(e,s.execution_id);(await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = 'superseded' WHERE node_id = ? AND state != 'exited'").run(i,i,e)).changes>0&&await l(n,e),await x(n,"node_id",e,i),await n.prepare("UPDATE nodes SET sandbox_deleted_at = NULL WHERE node_id = ? AND sandbox_deleted_at IS NOT NULL").run(e);const p=g(),E=t.attempt??Number((await n.prepare("SELECT COALESCE(MAX(attempt), 0) + 1 AS next FROM executions WHERE node_id = ?").get(e)).next);return await n.prepare("INSERT INTO executions (execution_id, node_id, daemon_epoch, pid, process_identity, state, started_at, ended_at, exit_reason, runner, attempt, release, launch_json) VALUES (?, ?, ?, NULL, NULL, 'launching', ?, NULL, NULL, ?, ?, ?, ?)").run(p,e,t.daemonEpoch,i,t.runner??"process",E,t.release??null,t.launchJson??null),p})}a(G,"beginExecution");async function V(e,t){const n=await(await r()).prepare("UPDATE executions SET launch_json = ? WHERE execution_id = ? AND state = 'launching'").run(t,e);if(Number(n.changes)!==1)throw new Error(`cannot set launch recipe for execution ${e}: no launching execution`)}a(V,"setExecutionLaunchJson");async function z(e){const t=await(await r()).prepare("UPDATE executions SET idle_at = ? WHERE execution_id = ? AND state = 'running' AND idle_at IS NULL").run(d(),e);return Number(t.changes)===1}a(z,"recordExecutionIdle");async function Q(e){await(await r()).prepare("UPDATE executions SET awake_since = ?, idle_at = NULL WHERE execution_id = ? AND state = 'running'").run(d(),e)}a(Q,"recordExecutionAwake");async function Z(e,t,n){const i=R([n])?.get(n)??null;return await _(async o=>{if((await o.prepare("UPDATE executions SET pid = ?, process_identity = ?, state = 'running', awake_since = ? WHERE execution_id = ? AND node_id = ? AND state = 'launching'").run(n,i,d(),e,t)).changes>0)return"recorded";const s=await o.prepare("SELECT pid FROM executions WHERE execution_id = ? AND node_id = ? AND state = 'running'").get(e,t);if(s?.pid===n)return"recorded";if(process.platform==="linux"&&P(H)&&s?.pid!=null){const S=m(),p=[s.pid];for(let E=0;E<p.length;E++)p.push(...S?.childrenOf.get(p[E])??[]);if(p.includes(n))return"recorded";for(const E of p)try{const u=W(`/proc/${E}/status`,"utf8"),h=/^NSpid:\s*(.+)$/m.exec(u)?.[1]?.trim().split(/\s+/).map(Number)??[];if(h.length>1&&h.at(-1)===n)return"recorded"}catch{}}return"shutdown"})}a(Z,"recordExecutionPid");async function I(e,t){return await _(async n=>{const i=d(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE execution_id = ? AND state != 'exited' RETURNING node_id").get(i,i,t.reason,e);return await x(n,"broker_process_id",e,i),o!==void 0&&(await l(n,o.node_id),w(o.node_id)),o!==void 0})}a(I,"endExecution");async function ee(e,t){return await _(async n=>{const i=d(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE execution_id = ? AND state = 'launching' RETURNING node_id").get(i,i,t.reason,e);return o===void 0?!1:(await x(n,"broker_process_id",e,i),await l(n,o.node_id),!0)})}a(ee,"endLaunchingExecution");async function te(e,t){return await I(e,t)}a(te,"abortExecution");async function ne(e,t){return await _(async n=>{const i=d(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE node_id = ? AND state != 'exited'").run(i,i,t.reason,e);return await x(n,"node_id",e,i),Number(o.changes)>0&&(await l(n,e),w(e)),Number(o.changes)===1})}a(ne,"endLiveExecution");async function ae(e=t=>R([t])?.get(t)){const t=await r(),n=await t.prepare("SELECT execution_id, pid, process_identity FROM executions WHERE state = 'running' AND pid IS NOT NULL AND process_identity IS NOT NULL").all(),i=t.prepare("UPDATE executions SET process_identity = ? WHERE execution_id = ? AND pid = ? AND process_identity = ? AND state = 'running'"),o=[];for(const c of n){if(!U(c.process_identity))continue;const s=e(c.pid);s===void 0||!C(s)||!y(s,c.process_identity)||(await i.run(s,c.execution_id,c.pid,c.process_identity)).changes>0&&o.push(c.execution_id)}return{migrated:o}}a(ae,"migrateLegacyExecutionIdentities");async function ie(e,t){const n=await(await r()).prepare("UPDATE executions SET stop_requested_at = COALESCE(stop_requested_at, ?), stop_after_turn = CASE WHEN stop_requested_at IS NULL THEN ? ELSE stop_after_turn END, stop_reason = COALESCE(stop_reason, ?) WHERE node_id = ? AND state != 'exited'").run(d(),t.afterTurn?1:0,t.reason,e);return Number(n.changes)>0}a(ie,"requestExecutionStop");async function oe(e){return(await(await r()).prepare("SELECT * FROM executions WHERE state != 'exited' AND stop_requested_at IS NOT NULL AND stop_requested_at <= ? ORDER BY stop_requested_at").all(e)).map(N)}a(oe,"executionsWithStopRequestedBefore");async function L(e){const t=await(await r()).prepare("SELECT * FROM executions WHERE node_id = ? ORDER BY started_at DESC, attempt DESC LIMIT 1").get(e);return t===void 0?null:N(t)}a(L,"latestExecutionForNode");async function re(e){return await(await r()).prepare("SELECT 1 AS x FROM executions WHERE node_id = ? AND state = 'running' AND runner != 'process'").get(e)!==void 0}a(re,"hasRunningRemoteExecution");async function se(e,t){return await(await r()).prepare("SELECT 1 AS x FROM executions WHERE node_id = ? AND state = 'launching' AND (runner != 'process' OR daemon_epoch = ?)").get(e,t)!==void 0}a(se,"hasLaunchingExecution");async function ce(e){const t=await(await r()).prepare("SELECT node_id FROM executions WHERE state != 'exited' AND runner = 'process' AND daemon_epoch = ?").all(e);return new Set(t.map(n=>n.node_id))}a(ce,"liveProcessExecutionNodeIds");async function ue(){const e=await(await r()).prepare("SELECT node_id FROM executions WHERE state != 'exited'").all();return new Set(e.map(t=>t.node_id))}a(ue,"liveExecutionNodeIds");const A="profile_pause",T="profile_pause_absorbed";async function de(e){await(await r()).prepare("UPDATE executions SET stop_requested_at = COALESCE(stop_requested_at, ?), stop_reason = ? WHERE node_id = ? AND state != 'exited'").run(d(),A,e)}a(de,"markProfilePauseStop");async function pe(e){return(await L(e))?.stopReason===A}a(pe,"hasProfilePauseStop");async function Ee(e){const t=await(await r()).prepare("UPDATE executions SET stop_reason = ? WHERE execution_id = (SELECT execution_id FROM executions WHERE node_id = ? ORDER BY started_at DESC, attempt DESC LIMIT 1) AND stop_reason = ?").run(T,e,A);return Number(t.changes)>0}a(Ee,"absorbProfilePauseStop");function _e(e){return e.stopReason===T}a(_e,"hasAbsorbedProfilePauseStop");const f="exited:";async function xe(e,t){const n=t.oomKilled===!0?"out_of_memory":`${f}${t.code??""}:${t.signal??""}`;await(await r()).prepare("UPDATE executions SET exit_reason = ? WHERE execution_id = ? AND exit_reason IS NULL").run(n,e)}a(xe,"recordExecutionExit");function le(e){const t=e.exitReason;return t!=null&&(t==="out_of_memory"||t.startsWith(f))}a(le,"hasObservedExit");async function fe(e){const t=await L(e),n=t?.exitReason;if(t===null||n==null)return;const i=n==="out_of_memory";if(!i&&!n.startsWith(f))return;const o=await(await r()).prepare("UPDATE executions SET exit_reason = 'exit_handled' WHERE execution_id = ? AND exit_reason = ?").run(t.executionId,n);if(Number(o.changes)===0)return;if(i)return{code:null,signal:null,oomKilled:!0};const[c,s]=n.slice(f.length).split(":");return{code:c===""?null:Number(c),signal:s===""?null:s}}a(fe,"takeObservedExit");export{b as ExecutionAlreadyLive,F as ExecutionCapReached,A as PROFILE_PAUSE_STOP_REASON,te as abortExecution,Ee as absorbProfilePauseStop,G as beginExecution,I as endExecution,ee as endLaunchingExecution,ne as endLiveExecution,oe as executionsWithStopRequestedBefore,_e as hasAbsorbedProfilePauseStop,se as hasLaunchingExecution,le as hasObservedExit,pe as hasProfilePauseStop,re as hasRunningRemoteExecution,L as latestExecutionForNode,J as liveExecutionForNode,ue as liveExecutionNodeIds,ce as liveProcessExecutionNodeIds,de as markProfilePauseStop,ae as migrateLegacyExecutionIdentities,Q as recordExecutionAwake,xe as recordExecutionExit,z as recordExecutionIdle,Z as recordExecutionPid,ie as requestExecutionStop,V as setExecutionLaunchJson,fe as takeObservedExit};
1
+ var L=Object.defineProperty;var a=(e,t)=>L(e,"name",{value:t,configurable:!0});import{randomUUID as D}from"node:crypto";import{openDb as r,withCanvasWrite as p}from"./db.js";import{capturePidIdentities as g,captureLivenessSnapshot as R,recordedPidLiveness as y}from"./pid.js";import{existsSync as C,readFileSync as O}from"node:fs";import{LAUNCHER_SOCKET as P}from"../../launcher/spec.js";import{revokeNodeTokens as x}from"./node-tokens.js";import{clearPendingParkIn as l}from"../../daemon/park-pending.js";import{deleteSandboxOfEndedNode as m}from"../runtime/runner/delete-sandboxes.js";function u(){return new Date().toISOString()}a(u,"now");function A(e){return{executionId:e.execution_id,nodeId:e.node_id,daemonEpoch:e.daemon_epoch??null,pid:e.pid??null,processIdentity:e.process_identity??null,state:e.state,startedAt:e.started_at,endedAt:e.ended_at??null,exitReason:e.exit_reason??null,runner:e.runner,attempt:Number(e.attempt),release:e.release??null,heartbeatAt:e.heartbeat_at??null,awakeSince:e.awake_since??null,idleAt:e.idle_at??null,exitedAt:e.exited_at??null,launchJson:e.launch_json??null,stopRequestedAt:e.stop_requested_at??null,stopAfterTurn:Number(e.stop_after_turn)===1,stopReason:e.stop_reason??null}}a(A,"hydrate");async function X(e){const t=await(await r()).prepare("SELECT * FROM executions WHERE node_id = ? AND state != 'exited'").get(e);return t===void 0?null:A(t)}a(X,"liveExecutionForNode");class U extends Error{static{a(this,"ExecutionCapReached")}cap;live;constructor(t,n){super(`no broker slot is free \u2014 ${n} live executions at the cap of ${t}.`),this.cap=t,this.live=n,this.name="ExecutionCapReached"}}class W extends Error{static{a(this,"ExecutionAlreadyLive")}nodeId;executionId;constructor(t,n){super(`${t} already has a live execution ${n}.`),this.nodeId=t,this.executionId=n,this.name="ExecutionAlreadyLive"}}const H=7340001;async function Y(e,t){return await p(async n=>{const i=u();if(!await n.prepare("SELECT node_id FROM nodes WHERE node_id = ? FOR UPDATE").get(e))throw new Error(`cannot begin execution: missing node ${e}`);if(t.cap!==void 0){await n.prepare(`SELECT pg_advisory_xact_lock(${H})`).get();const s=Number((await n.prepare("SELECT COUNT(*) AS n FROM executions WHERE state != 'exited' AND node_id != ?").get(e)).n);if(s>=t.cap)throw new U(t.cap,s)}const c=(await n.prepare("SELECT execution_id, runner, daemon_epoch, state, pid, process_identity FROM executions WHERE node_id = ? AND state != 'exited'").all(e)).find(s=>s.runner!=="process"||t.daemonEpoch!==null&&s.daemon_epoch===t.daemonEpoch&&(s.state==="launching"||y(s.pid,s.process_identity,R())!=="dead"));if(c!==void 0)throw new W(e,c.execution_id);(await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = 'superseded' WHERE node_id = ? AND state != 'exited'").run(i,i,e)).changes>0&&await l(n,e),await x(n,"node_id",e,i),await n.prepare("UPDATE nodes SET sandbox_deleted_at = NULL WHERE node_id = ? AND sandbox_deleted_at IS NOT NULL").run(e);const d=D(),E=t.attempt??Number((await n.prepare("SELECT COALESCE(MAX(attempt), 0) + 1 AS next FROM executions WHERE node_id = ?").get(e)).next);return await n.prepare("INSERT INTO executions (execution_id, node_id, daemon_epoch, pid, process_identity, state, started_at, ended_at, exit_reason, runner, attempt, release, launch_json) VALUES (?, ?, ?, NULL, NULL, 'launching', ?, NULL, NULL, ?, ?, ?, ?)").run(d,e,t.daemonEpoch,i,t.runner??"process",E,t.release??null,t.launchJson??null),d})}a(Y,"beginExecution");async function j(e,t){const n=await(await r()).prepare("UPDATE executions SET launch_json = ? WHERE execution_id = ? AND state = 'launching'").run(t,e);if(Number(n.changes)!==1)throw new Error(`cannot set launch recipe for execution ${e}: no launching execution`)}a(j,"setExecutionLaunchJson");async function J(e){const t=await(await r()).prepare("UPDATE executions SET idle_at = ? WHERE execution_id = ? AND state = 'running' AND idle_at IS NULL").run(u(),e);return Number(t.changes)===1}a(J,"recordExecutionIdle");async function G(e){await(await r()).prepare("UPDATE executions SET awake_since = ?, idle_at = NULL WHERE execution_id = ? AND state = 'running'").run(u(),e)}a(G,"recordExecutionAwake");async function V(e,t,n){const i=g([n])?.get(n)??null;return await p(async o=>{if((await o.prepare("UPDATE executions SET pid = ?, process_identity = ?, state = 'running', awake_since = ? WHERE execution_id = ? AND node_id = ? AND state = 'launching'").run(n,i,u(),e,t)).changes>0)return"recorded";const c=await o.prepare("SELECT pid FROM executions WHERE execution_id = ? AND node_id = ? AND state = 'running'").get(e,t);if(c?.pid===n)return"recorded";if(process.platform==="linux"&&C(P)&&c?.pid!=null){const S=R(),d=[c.pid];for(let E=0;E<d.length;E++)d.push(...S?.childrenOf.get(d[E])??[]);if(d.includes(n))return"recorded";for(const E of d)try{const s=O(`/proc/${E}/status`,"utf8"),h=/^NSpid:\s*(.+)$/m.exec(s)?.[1]?.trim().split(/\s+/).map(Number)??[];if(h.length>1&&h.at(-1)===n)return"recorded"}catch{}}return"shutdown"})}a(V,"recordExecutionPid");async function F(e,t){return await p(async n=>{const i=u(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE execution_id = ? AND state != 'exited' RETURNING node_id").get(i,i,t.reason,e);return await x(n,"broker_process_id",e,i),o!==void 0&&(await l(n,o.node_id),m(o.node_id)),o!==void 0})}a(F,"endExecution");async function z(e,t){return await p(async n=>{const i=u(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE execution_id = ? AND state = 'launching' RETURNING node_id").get(i,i,t.reason,e);return o===void 0?!1:(await x(n,"broker_process_id",e,i),await l(n,o.node_id),!0)})}a(z,"endLaunchingExecution");async function Q(e,t){return await F(e,t)}a(Q,"abortExecution");async function Z(e,t){return await p(async n=>{const i=u(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE node_id = ? AND state != 'exited'").run(i,i,t.reason,e);return await x(n,"node_id",e,i),Number(o.changes)>0&&(await l(n,e),m(e)),Number(o.changes)===1})}a(Z,"endLiveExecution");async function ee(e,t){const n=await(await r()).prepare("UPDATE executions SET stop_requested_at = COALESCE(stop_requested_at, ?), stop_after_turn = CASE WHEN stop_requested_at IS NULL THEN ? ELSE stop_after_turn END, stop_reason = COALESCE(stop_reason, ?) WHERE node_id = ? AND state != 'exited'").run(u(),t.afterTurn?1:0,t.reason,e);return Number(n.changes)>0}a(ee,"requestExecutionStop");async function te(e){return(await(await r()).prepare("SELECT * FROM executions WHERE state != 'exited' AND stop_requested_at IS NOT NULL AND stop_requested_at <= ? ORDER BY stop_requested_at").all(e)).map(A)}a(te,"executionsWithStopRequestedBefore");async function w(e){const t=await(await r()).prepare("SELECT * FROM executions WHERE node_id = ? ORDER BY started_at DESC, attempt DESC LIMIT 1").get(e);return t===void 0?null:A(t)}a(w,"latestExecutionForNode");async function ne(e){return await(await r()).prepare("SELECT 1 AS x FROM executions WHERE node_id = ? AND state = 'running' AND runner != 'process'").get(e)!==void 0}a(ne,"hasRunningRemoteExecution");async function ae(e,t){return await(await r()).prepare("SELECT 1 AS x FROM executions WHERE node_id = ? AND state = 'launching' AND (runner != 'process' OR daemon_epoch = ?)").get(e,t)!==void 0}a(ae,"hasLaunchingExecution");async function ie(e){const t=await(await r()).prepare("SELECT node_id FROM executions WHERE state != 'exited' AND runner = 'process' AND daemon_epoch = ?").all(e);return new Set(t.map(n=>n.node_id))}a(ie,"liveProcessExecutionNodeIds");async function oe(){const e=await(await r()).prepare("SELECT node_id FROM executions WHERE state != 'exited'").all();return new Set(e.map(t=>t.node_id))}a(oe,"liveExecutionNodeIds");const N="profile_pause",T="profile_pause_absorbed";async function re(e){await(await r()).prepare("UPDATE executions SET stop_requested_at = COALESCE(stop_requested_at, ?), stop_reason = ? WHERE node_id = ? AND state != 'exited'").run(u(),N,e)}a(re,"markProfilePauseStop");async function se(e){return(await w(e))?.stopReason===N}a(se,"hasProfilePauseStop");async function ce(e){const t=await(await r()).prepare("UPDATE executions SET stop_reason = ? WHERE execution_id = (SELECT execution_id FROM executions WHERE node_id = ? ORDER BY started_at DESC, attempt DESC LIMIT 1) AND stop_reason = ?").run(T,e,N);return Number(t.changes)>0}a(ce,"absorbProfilePauseStop");function ue(e){return e.stopReason===T}a(ue,"hasAbsorbedProfilePauseStop");const f="exited:";async function de(e,t){const n=t.oomKilled===!0?"out_of_memory":`${f}${t.code??""}:${t.signal??""}`;await(await r()).prepare("UPDATE executions SET exit_reason = ? WHERE execution_id = ? AND exit_reason IS NULL").run(n,e)}a(de,"recordExecutionExit");function Ee(e){const t=e.exitReason;return t!=null&&(t==="out_of_memory"||t.startsWith(f))}a(Ee,"hasObservedExit");async function pe(e){const t=await w(e),n=t?.exitReason;if(t===null||n==null)return;const i=n==="out_of_memory";if(!i&&!n.startsWith(f))return;const o=await(await r()).prepare("UPDATE executions SET exit_reason = 'exit_handled' WHERE execution_id = ? AND exit_reason = ?").run(t.executionId,n);if(Number(o.changes)===0)return;if(i)return{code:null,signal:null,oomKilled:!0};const[_,c]=n.slice(f.length).split(":");return{code:_===""?null:Number(_),signal:c===""?null:c}}a(pe,"takeObservedExit");export{W as ExecutionAlreadyLive,U as ExecutionCapReached,N as PROFILE_PAUSE_STOP_REASON,Q as abortExecution,ce as absorbProfilePauseStop,Y as beginExecution,F as endExecution,z as endLaunchingExecution,Z as endLiveExecution,te as executionsWithStopRequestedBefore,ue as hasAbsorbedProfilePauseStop,ae as hasLaunchingExecution,Ee as hasObservedExit,se as hasProfilePauseStop,ne as hasRunningRemoteExecution,w as latestExecutionForNode,X as liveExecutionForNode,oe as liveExecutionNodeIds,ie as liveProcessExecutionNodeIds,re as markProfilePauseStop,G as recordExecutionAwake,de as recordExecutionExit,J as recordExecutionIdle,V as recordExecutionPid,ee as requestExecutionStop,j as setExecutionLaunchJson,pe as takeObservedExit};
@@ -115,16 +115,6 @@ export declare function killProcessGroup(pid: number, signal?: NodeJS.Signals):
115
115
  * no-boot_id host is not hammered with a synchronous throwing read on every
116
116
  * identity composition. `now` is injectable for tests. */
117
117
  export declare function makeBootIdCache(read: () => string | null, now?: () => number, negativeTtlMs?: number): () => string | null;
118
- /** Is `identity` a LEGACY (pre-boot-scoped) baseline — a `<lstart>#<ticks>` row
119
- * whose base is NOT a boot_id UUID but which DOES carry ticks? These are the
120
- * rows the one-time startup migration re-records once this platform can
121
- * compose boot-scoped identities (see `migrateLegacyPidIdentities`). */
122
- export declare function isLegacyTicksIdentity(identity: string): boolean;
123
- /** Is `identity` a NEW-format boot-scoped baseline — `<bootId>#<ticks>` with a
124
- * real boot_id UUID base AND ticks? The startup migration only re-records a
125
- * legacy row when the pid's CURRENT identity comes out in this shape (i.e. the
126
- * platform now composes new-format), never otherwise. */
127
- export declare function isBootScopedIdentity(identity: string): boolean;
128
118
  /** Compose the stable, BOOT-SCOPED process-identity fingerprint used
129
119
  * everywhere in this module. ALWAYS used to build an identity string, never a
130
120
  * raw field directly, so every identity captured anywhere (launch-time
@@ -1,5 +1,5 @@
1
- var K=Object.defineProperty;var s=(n,e)=>K(n,"name",{value:e,configurable:!0});import{execFile as X,spawn as q,spawnSync as g}from"node:child_process";import{readFileSync as h,readdirSync as W,statSync as Q}from"node:fs";import{readFile as T}from"node:fs/promises";import{readKernelBootId as v}from"./boot-id.js";function Y(n){if(p())return D(n);try{const e=g("ps",["-o","stat=","-p",String(n)],{encoding:"utf8",timeout:2e3});if(e.error!=null||e.signal!=null||typeof e.stdout!="string"||typeof e.stderr=="string"&&e.stderr.trim()!=="")return"unknown";const t=e.stdout.trim();return t===""?"gone":t.charAt(0)==="Z"?"zombie":"live"}catch{return"unknown"}}s(Y,"psProcessState");function y(n){if(n==null)return!1;try{process.kill(n,0)}catch(t){return t.code==="EPERM"}const e=Y(n);return e!=="zombie"&&e!=="gone"}s(y,"isPidAlive");function mn(n){if(n==null)return!1;try{return process.kill(n,0),!0}catch(e){return e.code==="EPERM"}}s(mn,"isPidPresent");const S=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function w(n){const e=n.indexOf("#");if(e===-1)return{base:n,ticks:void 0};const t=n.slice(e+1);return{base:n.slice(0,e),ticks:/^\d+$/.test(t)?t:void 0}}s(w,"splitIdentity");function k(n,e){const t=w(n),r=w(e);return t.ticks!==void 0&&r.ticks!==void 0?S.test(t.base)&&S.test(r.base)?t.base===r.base&&t.ticks===r.ticks:t.ticks===r.ticks:t.base===r.base}s(k,"identitiesMatch");function gn(n,e,t){const r=!!process.env.CRTR_DEBUG_PID_LIVENESS;if(n==null)return"dead";if(t===null)return r&&m(n,!1,e,"probe-null","ps snapshot failed \u2192 indeterminate","indeterminate"),"indeterminate";const o=t?.processes.get(n),i=t===void 0?y(n):o!==void 0&&!o.zombie;if(!i)return r&&m(n,i,e,t===void 0?"no-probe":"no-entry","process absent/zombie \u2192 dead","dead"),"dead";if(e==null)return r&&m(n,i,e,"no-probe","no baseline \u2192 trust process presence","alive"),"alive";let u;if(t===void 0){const l=V([n]);if(l==null)return r&&m(n,i,e,"probe-null","ps probe failed \u2192 indeterminate","indeterminate"),"indeterminate";if(u=l.get(n),u===void 0)return r&&m(n,i,e,"no-entry","no identity row for pid (race) \u2192 dead","dead"),"dead"}else u=o.identity;const c=k(u,e);return r&&m(n,i,e,"value",c?"identity matches expected \u2192 alive":"identity differs from expected \u2192 REUSED \u2192 dead",c?"alive":"dead",u),c?"alive":"dead"}s(gn,"recordedPidLiveness");function m(n,e,t,r,o,i,u){const c=[`pid=${String(n)}`,`isPidAlive=${e}`,`expectedIdentity=${t===void 0?"undefined":t===null?"null":JSON.stringify(t)}`,`capturePidIdentities=${r}${r==="value"?`(${JSON.stringify(u)})`:""}`,`branch=${JSON.stringify(o)}`,`returned=${i}`];process.stderr.write(`[recordedPidLiveness] ${c.join(" ")}
2
- `)}s(m,"logPidLivenessDecision");function nn(n,e="SIGTERM"){if(!(!Number.isInteger(n)||n<=0))try{process.kill(-n,e)}catch{}}s(nn,"killProcessGroup");function en(n){try{const e=h(`/proc/${n}/stat`,"utf8"),t=e.lastIndexOf(")");if(t===-1)return null;const o=e.slice(t+2).trim().split(/\s+/)[19];return o!==void 0&&/^\d+$/.test(o)?o:null}catch{return null}}s(en,"procStartTicks");const tn=6e4;function rn(n,e=Date.now,t=tn){let r=null,o=0;return()=>{if(r!==null)return r;const i=e();if(i<o)return null;const u=n();return u!==null?r=u:(o=i+t,null)}}s(rn,"makeBootIdCache");const A=rn(v);function bn(n){const{base:e,ticks:t}=w(n);return t!==void 0&&!S.test(e)}s(bn,"isLegacyTicksIdentity");function hn(n){const{base:e,ticks:t}=w(n);return t!==void 0&&S.test(e)}s(hn,"isBootScopedIdentity");function M(n,e,t={}){const r=t.ticks!==void 0?t.ticks:en(n);return r===null?e:`${(t.bootId!==void 0?t.bootId:A())??e}#${r}`}s(M,"composeIdentity");const R=["-Ao","pid=,ppid=,pgid=,stat=,lstart=,command="],_=2e3;function I(){if(p())return x();let n;try{const e=g("ps",[...R],{encoding:"utf8",timeout:_,maxBuffer:8388608});if(e.status!==0||typeof e.stdout!="string")return null;n=e.stdout}catch{return null}return J(n)}s(I,"captureLivenessSnapshot");async function yn(){if(p())return j();const n=await new Promise(e=>{let t;try{t=q("ps",[...R])}catch{return e(null)}let r="",o=!1;const i=s(c=>{o||(o=!0,clearTimeout(u),e(c))},"settle"),u=setTimeout(()=>{try{t.kill("SIGKILL")}catch{}i(null)},_);u.unref?.(),t.stdout.on("data",c=>r+=c.toString()),t.stderr.on("data",()=>{}),t.on("error",()=>i(null)),t.on("close",c=>i(c===0?r:null))});return n===null?null:J(n)}s(yn,"captureLivenessSnapshotAsync");function B(n){const e=n.indexOf("("),t=n.lastIndexOf(")");if(e===-1||t===-1||t<e)return null;const r=n.slice(t+2).trim().split(/\s+/),o=r[0],i=Number(r[1]),u=Number(r[2]),c=r[19];return o===void 0||o===""||!Number.isInteger(i)||i<0||!Number.isInteger(u)||u<0||c===void 0||!/^\d+$/.test(c)?null:{comm:n.slice(e+1,t),state:o,ppid:i,pgid:u,starttime:c}}s(B,"parseProcStat");function L(n,e){const t=n.replace(/\0+$/,"").split("\0").join(" ").trim();return t===""?`[${e}]`:t}s(L,"procCommandLine");let $;function p(){return $===void 0&&($=process.platform==="linux"&&v()!==null&&on(process.pid)!==null),$}s(p,"procfsUsable");const a={root:"/proc",bootId:s(()=>A(),"bootId")};function on(n,e=a){const t=b(n,e);return t==="unreadable"||t==="denied"||t==="gone"?null:t}s(on,"procStatOf");function b(n,e=a){let t;try{t=h(`${e.root}/${n}/stat`,"utf8")}catch(r){return N(r)}return B(t)??"unreadable"}s(b,"readProcStat");function N(n){const e=n.code;return e==="ENOENT"||e==="ESRCH"?"gone":e==="EACCES"||e==="EPERM"?"denied":"unreadable"}s(N,"classifyProcReadError");function sn(n,e){const t=e.selfUid!==void 0?e.selfUid():process.getuid?.()??null;if(t===null)return"own-or-unknown";try{return Q(`${e.root}/${n}`).uid===t?"own-or-unknown":"foreign"}catch(r){return N(r)==="gone"?"gone":"own-or-unknown"}}s(sn,"procOwnership");function C(n,e,t){return n==="gone"?"skip":n==="unreadable"||sn(e,t)==="own-or-unknown"?"fail":"skip"}s(C,"scanDisposition");function z(n,e=a){const t=e.bootId();return t===null?null:`${t}#${n.starttime}`}s(z,"procIdentity");function D(n,e=a){const t=b(n,e);return t==="gone"?"gone":t==="denied"||t==="unreadable"?"unknown":t.state==="Z"||t.state==="X"?"zombie":"live"}s(D,"procProcessState");function G(n,e=a){const t=new Map;for(const r of n){const o=b(r,e);if(o==="gone")continue;if(o==="unreadable"||o==="denied")return null;const i=z(o,e);if(i===null)return null;t.set(r,i)}return t}s(G,"procIdentities");function H(n,e=a){const t=b(n,e);if(t==="gone"||t==="unreadable"||t==="denied")return null;try{const r=L(h(`${e.root}/${n}/cmdline`,"utf8"),t.comm);return r===""?null:r}catch{return null}}s(H,"procCommand");function U(n,e,t,r,o){const i=z(r,n);if(i===null)return!1;e.processes.set(t,{zombie:r.state==="Z"||r.state==="X",pgid:r.pgid,identity:i,command:L(o,r.comm)});const u=e.childrenOf.get(r.ppid);return u===void 0?e.childrenOf.set(r.ppid,[t]):u.push(t),!0}s(U,"addProcfsRow");function F(n){try{return W(n).filter(e=>/^\d+$/.test(e)).map(Number).filter(e=>e>0)}catch{return null}}s(F,"procPids");function x(n=a){const e=F(n.root);if(e===null)return null;const t={processes:new Map,childrenOf:new Map};for(const r of e){const o=b(r,n);if(o==="gone"||o==="denied"||o==="unreadable"){if(C(o==="gone"?"gone":o,r,n)==="skip")continue;return null}let i="";try{i=h(`${n.root}/${r}/cmdline`,"utf8")}catch(u){const c=u.code;if(c==="ENOENT"||c==="ESRCH")continue}if(!U(n,t,r,o,i))return null}return t}s(x,"readProcfsSnapshot");async function j(n=a){const e=F(n.root);if(e===null)return null;const t={processes:new Map,childrenOf:new Map},r=64;for(let o=0;o<e.length;o+=r){const i=e.slice(o,o+r),u=await Promise.all(i.map(async c=>{try{const l=B(await T(`${n.root}/${c}/stat`,"utf8"));if(l===null)return"failed";const f=await T(`${n.root}/${c}/cmdline`,"utf8").catch(d=>{if(d.code==="ENOENT"||d.code==="ESRCH")throw d;return""});return{pid:c,stat:l,cmdline:f}}catch(l){return C(N(l),c,n)==="skip"?"gone":"failed"}}));for(const c of u)if(c!=="gone"&&(c==="failed"||!U(n,t,c.pid,c.stat,c.cmdline)))return null}return t}s(j,"readProcfsSnapshotAsync");function un(){if(p()){const n=x();if(n===null)return null;const e=new Map;for(const[t,r]of n.childrenOf)for(const o of r)e.set(o,t);return[...n.processes].map(([t,r])=>({pid:t,ppid:e.get(t)??0,command:r.command}))}try{const n=g("ps",["-ax","-o","pid=,ppid=,command="],{encoding:"utf8",timeout:2e3,maxBuffer:8388608});return n.status!==0||typeof n.stdout!="string"?null:Z(n.stdout)}catch{return null}}s(un,"listProcessTable");function Z(n){const e=[];for(const t of n.split(`
3
- `)){const r=/^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(t);r!==null&&e.push({pid:Number(r[1]),ppid:Number(r[2]),command:r[3].trim()})}return e}s(Z,"parseProcessTable");async function Sn(n=1e4){return p()?un():await new Promise(e=>{try{X("ps",["-ax","-o","pid=,ppid=,command="],{encoding:"utf8",timeout:n,maxBuffer:8*1024*1024},(t,r)=>{e(t===null&&typeof r=="string"?Z(r):null)})}catch{e(null)}})}s(Sn,"listProcessTableAsync");const wn={procIdentities:G,procProcessState:D,procCommand:H,readProcfsSnapshot:x,readProcfsSnapshotAsync:j};function J(n){const e=new Map,t=new Map;for(const r of n.split(`
4
- `)){const o=r.trim();if(o==="")continue;const i=/^(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(\S+(?:\s+\S+){4})\s+(.+)$/.exec(o);if(i===null)continue;const u=Number(i[1]),c=Number(i[2]),l=Number(i[3]),f=i[4],d=i[5],E=i[6].trim();if(!Number.isInteger(u)||u<=0||!Number.isInteger(c)||c<0||E==="")continue;e.set(u,{zombie:f.startsWith("Z"),pgid:l,identity:M(u,d),command:E});const O=t.get(c);O===void 0?t.set(c,[u]):O.push(u)}return{processes:e,childrenOf:t}}s(J,"parseLivenessTable");function P(n,e){const t=[],r=new Set([n]),o=[...e.get(n)??[]];for(;o.length>0;){const i=o.shift();if(r.has(i))continue;r.add(i),t.push(i);const u=e.get(i);u!==void 0&&o.push(...u)}return t}s(P,"descendantPidsFrom");function cn(n){if(!Number.isInteger(n)||n<=0)return[];const e=I();return e===null?[]:P(n,e.childrenOf)}s(cn,"descendantPids");function kn(n){const e=I();return e===null?null:[...e.processes].filter(([,t])=>t.pgid===n&&!t.zombie).map(([t])=>t)}s(kn,"pidsInProcessGroup");function V(n){const e=n.filter(r=>Number.isInteger(r)&&r>0),t=new Map;if(e.length===0)return t;if(p())return G(e);try{const r=g("ps",["-o","pid=,lstart=","-p",e.join(",")],{encoding:"utf8",timeout:2e3});if(r.error!=null||r.signal!=null||typeof r.stdout!="string"||typeof r.stderr=="string"&&r.stderr.trim()!=="")return null;for(const o of r.stdout.split(`
5
- `)){const i=o.trim();if(i==="")continue;const u=i.indexOf(" ");if(u===-1)continue;const c=Number(i.slice(0,u)),l=i.slice(u+1).trim();!Number.isInteger(c)||c<=0||l===""||t.set(c,M(c,l))}return t}catch{return null}}s(V,"capturePidIdentities");function In(n){if(!Number.isInteger(n)||n<=0)return null;if(p())return H(n);try{const e=g("ps",["-o","command=","-p",String(n)],{encoding:"utf8",timeout:2e3});if(e.status!==0||typeof e.stdout!="string")return null;const t=e.stdout.trim();return t===""?null:t}catch{return null}}s(In,"capturePidCommand");function $n(n,e,t){if(!Number.isInteger(n)||n<=0)return{tree:[],identities:null,reused:!1};const r=I();if(r===null)return{tree:[n],identities:null,reused:!1};const o=r.processes.get(n)?.identity;if(e!=null&&o!==void 0&&!k(o,e))return{tree:[],identities:null,reused:!0};const u=t!==void 0&&Number.isInteger(t)&&t>0?new Set([t,...P(t,r.childrenOf)]):void 0,c=[n,...P(n,r.childrenOf)].filter(f=>!u?.has(f)),l=new Map;for(const f of c){const d=r.processes.get(f)?.identity;d!==void 0&&l.set(f,d)}return{tree:c,identities:l,reused:!1}}s($n,"captureTeardownSnapshot");function Nn(n,e="SIGTERM",t){const r=t!=null?V(n):void 0;for(const o of n){if(t!=null&&r!=null){const i=t.get(o),u=r.get(o);if(i!==void 0&&u!==void 0&&!k(u,i))continue}if(nn(o,e),!(!Number.isInteger(o)||o<=0))try{process.kill(o,e)}catch{}}}s(Nn,"killProcessTreePids");function xn(n){return y(n)?!0:cn(n).some(e=>y(e))}s(xn,"isProcessTreeAlive");function Pn(n){return n.some(e=>y(e))}s(Pn,"isAnyPidAlive");export{I as captureLivenessSnapshot,yn as captureLivenessSnapshotAsync,In as capturePidCommand,V as capturePidIdentities,$n as captureTeardownSnapshot,M as composeIdentity,cn as descendantPids,k as identitiesMatch,Pn as isAnyPidAlive,hn as isBootScopedIdentity,bn as isLegacyTicksIdentity,y as isPidAlive,mn as isPidPresent,xn as isProcessTreeAlive,nn as killProcessGroup,Nn as killProcessTreePids,un as listProcessTable,Sn as listProcessTableAsync,rn as makeBootIdCache,B as parseProcStat,kn as pidsInProcessGroup,L as procCommandLine,wn as procfsBackendForTest,x as readProcfsSnapshot,j as readProcfsSnapshotAsync,gn as recordedPidLiveness};
1
+ var K=Object.defineProperty;var s=(n,e)=>K(n,"name",{value:e,configurable:!0});import{execFile as X,spawn as q,spawnSync as g}from"node:child_process";import{readFileSync as h,readdirSync as W,statSync as Q}from"node:fs";import{readFile as E}from"node:fs/promises";import{readKernelBootId as O}from"./boot-id.js";function Y(n){if(p())return D(n);try{const e=g("ps",["-o","stat=","-p",String(n)],{encoding:"utf8",timeout:2e3});if(e.error!=null||e.signal!=null||typeof e.stdout!="string"||typeof e.stderr=="string"&&e.stderr.trim()!=="")return"unknown";const t=e.stdout.trim();return t===""?"gone":t.charAt(0)==="Z"?"zombie":"live"}catch{return"unknown"}}s(Y,"psProcessState");function y(n){if(n==null)return!1;try{process.kill(n,0)}catch(t){return t.code==="EPERM"}const e=Y(n);return e!=="zombie"&&e!=="gone"}s(y,"isPidAlive");function mn(n){if(n==null)return!1;try{return process.kill(n,0),!0}catch(e){return e.code==="EPERM"}}s(mn,"isPidPresent");const T=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function v(n){const e=n.indexOf("#");if(e===-1)return{base:n,ticks:void 0};const t=n.slice(e+1);return{base:n.slice(0,e),ticks:/^\d+$/.test(t)?t:void 0}}s(v,"splitIdentity");function S(n,e){const t=v(n),r=v(e);return t.ticks!==void 0&&r.ticks!==void 0?T.test(t.base)&&T.test(r.base)?t.base===r.base&&t.ticks===r.ticks:t.ticks===r.ticks:t.base===r.base}s(S,"identitiesMatch");function gn(n,e,t){const r=!!process.env.CRTR_DEBUG_PID_LIVENESS;if(n==null)return"dead";if(t===null)return r&&m(n,!1,e,"probe-null","ps snapshot failed \u2192 indeterminate","indeterminate"),"indeterminate";const o=t?.processes.get(n),i=t===void 0?y(n):o!==void 0&&!o.zombie;if(!i)return r&&m(n,i,e,t===void 0?"no-probe":"no-entry","process absent/zombie \u2192 dead","dead"),"dead";if(e==null)return r&&m(n,i,e,"no-probe","no baseline \u2192 trust process presence","alive"),"alive";let u;if(t===void 0){const l=V([n]);if(l==null)return r&&m(n,i,e,"probe-null","ps probe failed \u2192 indeterminate","indeterminate"),"indeterminate";if(u=l.get(n),u===void 0)return r&&m(n,i,e,"no-entry","no identity row for pid (race) \u2192 dead","dead"),"dead"}else u=o.identity;const c=S(u,e);return r&&m(n,i,e,"value",c?"identity matches expected \u2192 alive":"identity differs from expected \u2192 REUSED \u2192 dead",c?"alive":"dead",u),c?"alive":"dead"}s(gn,"recordedPidLiveness");function m(n,e,t,r,o,i,u){const c=[`pid=${String(n)}`,`isPidAlive=${e}`,`expectedIdentity=${t===void 0?"undefined":t===null?"null":JSON.stringify(t)}`,`capturePidIdentities=${r}${r==="value"?`(${JSON.stringify(u)})`:""}`,`branch=${JSON.stringify(o)}`,`returned=${i}`];process.stderr.write(`[recordedPidLiveness] ${c.join(" ")}
2
+ `)}s(m,"logPidLivenessDecision");function nn(n,e="SIGTERM"){if(!(!Number.isInteger(n)||n<=0))try{process.kill(-n,e)}catch{}}s(nn,"killProcessGroup");function en(n){try{const e=h(`/proc/${n}/stat`,"utf8"),t=e.lastIndexOf(")");if(t===-1)return null;const o=e.slice(t+2).trim().split(/\s+/)[19];return o!==void 0&&/^\d+$/.test(o)?o:null}catch{return null}}s(en,"procStartTicks");const tn=6e4;function rn(n,e=Date.now,t=tn){let r=null,o=0;return()=>{if(r!==null)return r;const i=e();if(i<o)return null;const u=n();return u!==null?r=u:(o=i+t,null)}}s(rn,"makeBootIdCache");const A=rn(O);function M(n,e,t={}){const r=t.ticks!==void 0?t.ticks:en(n);return r===null?e:`${(t.bootId!==void 0?t.bootId:A())??e}#${r}`}s(M,"composeIdentity");const R=["-Ao","pid=,ppid=,pgid=,stat=,lstart=,command="],_=2e3;function w(){if(p())return $();let n;try{const e=g("ps",[...R],{encoding:"utf8",timeout:_,maxBuffer:8388608});if(e.status!==0||typeof e.stdout!="string")return null;n=e.stdout}catch{return null}return J(n)}s(w,"captureLivenessSnapshot");async function bn(){if(p())return j();const n=await new Promise(e=>{let t;try{t=q("ps",[...R])}catch{return e(null)}let r="",o=!1;const i=s(c=>{o||(o=!0,clearTimeout(u),e(c))},"settle"),u=setTimeout(()=>{try{t.kill("SIGKILL")}catch{}i(null)},_);u.unref?.(),t.stdout.on("data",c=>r+=c.toString()),t.stderr.on("data",()=>{}),t.on("error",()=>i(null)),t.on("close",c=>i(c===0?r:null))});return n===null?null:J(n)}s(bn,"captureLivenessSnapshotAsync");function B(n){const e=n.indexOf("("),t=n.lastIndexOf(")");if(e===-1||t===-1||t<e)return null;const r=n.slice(t+2).trim().split(/\s+/),o=r[0],i=Number(r[1]),u=Number(r[2]),c=r[19];return o===void 0||o===""||!Number.isInteger(i)||i<0||!Number.isInteger(u)||u<0||c===void 0||!/^\d+$/.test(c)?null:{comm:n.slice(e+1,t),state:o,ppid:i,pgid:u,starttime:c}}s(B,"parseProcStat");function C(n,e){const t=n.replace(/\0+$/,"").split("\0").join(" ").trim();return t===""?`[${e}]`:t}s(C,"procCommandLine");let k;function p(){return k===void 0&&(k=process.platform==="linux"&&O()!==null&&on(process.pid)!==null),k}s(p,"procfsUsable");const a={root:"/proc",bootId:s(()=>A(),"bootId")};function on(n,e=a){const t=b(n,e);return t==="unreadable"||t==="denied"||t==="gone"?null:t}s(on,"procStatOf");function b(n,e=a){let t;try{t=h(`${e.root}/${n}/stat`,"utf8")}catch(r){return I(r)}return B(t)??"unreadable"}s(b,"readProcStat");function I(n){const e=n.code;return e==="ENOENT"||e==="ESRCH"?"gone":e==="EACCES"||e==="EPERM"?"denied":"unreadable"}s(I,"classifyProcReadError");function sn(n,e){const t=e.selfUid!==void 0?e.selfUid():process.getuid?.()??null;if(t===null)return"own-or-unknown";try{return Q(`${e.root}/${n}`).uid===t?"own-or-unknown":"foreign"}catch(r){return I(r)==="gone"?"gone":"own-or-unknown"}}s(sn,"procOwnership");function L(n,e,t){return n==="gone"?"skip":n==="unreadable"||sn(e,t)==="own-or-unknown"?"fail":"skip"}s(L,"scanDisposition");function z(n,e=a){const t=e.bootId();return t===null?null:`${t}#${n.starttime}`}s(z,"procIdentity");function D(n,e=a){const t=b(n,e);return t==="gone"?"gone":t==="denied"||t==="unreadable"?"unknown":t.state==="Z"||t.state==="X"?"zombie":"live"}s(D,"procProcessState");function G(n,e=a){const t=new Map;for(const r of n){const o=b(r,e);if(o==="gone")continue;if(o==="unreadable"||o==="denied")return null;const i=z(o,e);if(i===null)return null;t.set(r,i)}return t}s(G,"procIdentities");function H(n,e=a){const t=b(n,e);if(t==="gone"||t==="unreadable"||t==="denied")return null;try{const r=C(h(`${e.root}/${n}/cmdline`,"utf8"),t.comm);return r===""?null:r}catch{return null}}s(H,"procCommand");function U(n,e,t,r,o){const i=z(r,n);if(i===null)return!1;e.processes.set(t,{zombie:r.state==="Z"||r.state==="X",pgid:r.pgid,identity:i,command:C(o,r.comm)});const u=e.childrenOf.get(r.ppid);return u===void 0?e.childrenOf.set(r.ppid,[t]):u.push(t),!0}s(U,"addProcfsRow");function F(n){try{return W(n).filter(e=>/^\d+$/.test(e)).map(Number).filter(e=>e>0)}catch{return null}}s(F,"procPids");function $(n=a){const e=F(n.root);if(e===null)return null;const t={processes:new Map,childrenOf:new Map};for(const r of e){const o=b(r,n);if(o==="gone"||o==="denied"||o==="unreadable"){if(L(o==="gone"?"gone":o,r,n)==="skip")continue;return null}let i="";try{i=h(`${n.root}/${r}/cmdline`,"utf8")}catch(u){const c=u.code;if(c==="ENOENT"||c==="ESRCH")continue}if(!U(n,t,r,o,i))return null}return t}s($,"readProcfsSnapshot");async function j(n=a){const e=F(n.root);if(e===null)return null;const t={processes:new Map,childrenOf:new Map},r=64;for(let o=0;o<e.length;o+=r){const i=e.slice(o,o+r),u=await Promise.all(i.map(async c=>{try{const l=B(await E(`${n.root}/${c}/stat`,"utf8"));if(l===null)return"failed";const f=await E(`${n.root}/${c}/cmdline`,"utf8").catch(d=>{if(d.code==="ENOENT"||d.code==="ESRCH")throw d;return""});return{pid:c,stat:l,cmdline:f}}catch(l){return L(I(l),c,n)==="skip"?"gone":"failed"}}));for(const c of u)if(c!=="gone"&&(c==="failed"||!U(n,t,c.pid,c.stat,c.cmdline)))return null}return t}s(j,"readProcfsSnapshotAsync");function un(){if(p()){const n=$();if(n===null)return null;const e=new Map;for(const[t,r]of n.childrenOf)for(const o of r)e.set(o,t);return[...n.processes].map(([t,r])=>({pid:t,ppid:e.get(t)??0,command:r.command}))}try{const n=g("ps",["-ax","-o","pid=,ppid=,command="],{encoding:"utf8",timeout:2e3,maxBuffer:8388608});return n.status!==0||typeof n.stdout!="string"?null:Z(n.stdout)}catch{return null}}s(un,"listProcessTable");function Z(n){const e=[];for(const t of n.split(`
3
+ `)){const r=/^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(t);r!==null&&e.push({pid:Number(r[1]),ppid:Number(r[2]),command:r[3].trim()})}return e}s(Z,"parseProcessTable");async function hn(n=1e4){return p()?un():await new Promise(e=>{try{X("ps",["-ax","-o","pid=,ppid=,command="],{encoding:"utf8",timeout:n,maxBuffer:8*1024*1024},(t,r)=>{e(t===null&&typeof r=="string"?Z(r):null)})}catch{e(null)}})}s(hn,"listProcessTableAsync");const yn={procIdentities:G,procProcessState:D,procCommand:H,readProcfsSnapshot:$,readProcfsSnapshotAsync:j};function J(n){const e=new Map,t=new Map;for(const r of n.split(`
4
+ `)){const o=r.trim();if(o==="")continue;const i=/^(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(\S+(?:\s+\S+){4})\s+(.+)$/.exec(o);if(i===null)continue;const u=Number(i[1]),c=Number(i[2]),l=Number(i[3]),f=i[4],d=i[5],x=i[6].trim();if(!Number.isInteger(u)||u<=0||!Number.isInteger(c)||c<0||x==="")continue;e.set(u,{zombie:f.startsWith("Z"),pgid:l,identity:M(u,d),command:x});const P=t.get(c);P===void 0?t.set(c,[u]):P.push(u)}return{processes:e,childrenOf:t}}s(J,"parseLivenessTable");function N(n,e){const t=[],r=new Set([n]),o=[...e.get(n)??[]];for(;o.length>0;){const i=o.shift();if(r.has(i))continue;r.add(i),t.push(i);const u=e.get(i);u!==void 0&&o.push(...u)}return t}s(N,"descendantPidsFrom");function cn(n){if(!Number.isInteger(n)||n<=0)return[];const e=w();return e===null?[]:N(n,e.childrenOf)}s(cn,"descendantPids");function Sn(n){const e=w();return e===null?null:[...e.processes].filter(([,t])=>t.pgid===n&&!t.zombie).map(([t])=>t)}s(Sn,"pidsInProcessGroup");function V(n){const e=n.filter(r=>Number.isInteger(r)&&r>0),t=new Map;if(e.length===0)return t;if(p())return G(e);try{const r=g("ps",["-o","pid=,lstart=","-p",e.join(",")],{encoding:"utf8",timeout:2e3});if(r.error!=null||r.signal!=null||typeof r.stdout!="string"||typeof r.stderr=="string"&&r.stderr.trim()!=="")return null;for(const o of r.stdout.split(`
5
+ `)){const i=o.trim();if(i==="")continue;const u=i.indexOf(" ");if(u===-1)continue;const c=Number(i.slice(0,u)),l=i.slice(u+1).trim();!Number.isInteger(c)||c<=0||l===""||t.set(c,M(c,l))}return t}catch{return null}}s(V,"capturePidIdentities");function wn(n){if(!Number.isInteger(n)||n<=0)return null;if(p())return H(n);try{const e=g("ps",["-o","command=","-p",String(n)],{encoding:"utf8",timeout:2e3});if(e.status!==0||typeof e.stdout!="string")return null;const t=e.stdout.trim();return t===""?null:t}catch{return null}}s(wn,"capturePidCommand");function kn(n,e,t){if(!Number.isInteger(n)||n<=0)return{tree:[],identities:null,reused:!1};const r=w();if(r===null)return{tree:[n],identities:null,reused:!1};const o=r.processes.get(n)?.identity;if(e!=null&&o!==void 0&&!S(o,e))return{tree:[],identities:null,reused:!0};const u=t!==void 0&&Number.isInteger(t)&&t>0?new Set([t,...N(t,r.childrenOf)]):void 0,c=[n,...N(n,r.childrenOf)].filter(f=>!u?.has(f)),l=new Map;for(const f of c){const d=r.processes.get(f)?.identity;d!==void 0&&l.set(f,d)}return{tree:c,identities:l,reused:!1}}s(kn,"captureTeardownSnapshot");function In(n,e="SIGTERM",t){const r=t!=null?V(n):void 0;for(const o of n){if(t!=null&&r!=null){const i=t.get(o),u=r.get(o);if(i!==void 0&&u!==void 0&&!S(u,i))continue}if(nn(o,e),!(!Number.isInteger(o)||o<=0))try{process.kill(o,e)}catch{}}}s(In,"killProcessTreePids");function $n(n){return y(n)?!0:cn(n).some(e=>y(e))}s($n,"isProcessTreeAlive");function Nn(n){return n.some(e=>y(e))}s(Nn,"isAnyPidAlive");export{w as captureLivenessSnapshot,bn as captureLivenessSnapshotAsync,wn as capturePidCommand,V as capturePidIdentities,kn as captureTeardownSnapshot,M as composeIdentity,cn as descendantPids,S as identitiesMatch,Nn as isAnyPidAlive,y as isPidAlive,mn as isPidPresent,$n as isProcessTreeAlive,nn as killProcessGroup,In as killProcessTreePids,un as listProcessTable,hn as listProcessTableAsync,rn as makeBootIdCache,B as parseProcStat,Sn as pidsInProcessGroup,C as procCommandLine,yn as procfsBackendForTest,$ as readProcfsSnapshot,j as readProcfsSnapshotAsync,gn as recordedPidLiveness};
@@ -1 +1 @@
1
- var E=Object.defineProperty;var n=(r,e)=>E(r,"name",{value:e,configurable:!0});import{createHash as J,generateKeyPairSync as U,randomUUID as D}from"node:crypto";import{existsSync as I,mkdirSync as R,readdirSync as O,rmSync as x}from"node:fs";import{hostname as S}from"node:os";import{join as _}from"node:path";import{InputError as f}from"../io.js";import{network as d}from"../errors.js";import{secretsDir as g}from"../layout.js";import{apiSocketPath as A}from"../canvas/paths.js";import{daemonAnswers as K}from"../layout-migrate/index.js";import{atomicWriteJson as b,readJsonIfExists as w}from"../fs-utils.js";import{launcherPresent as L}from"../grants/sandboxes.js";import{crtrVersion as N}from"../../shared/crtr-version.js";import{pluginsDir as q}from"../scope.js";function m(){return _(g(),"runtime-client.json")}n(m,"clientPath");function h(r){if(typeof r!="string")return!1;try{const{protocol:e}=new URL(r);return e==="http:"||e==="https:"}catch{return!1}}n(h,"isUrl");function y(r){const e=r??{},{runtime:o,client_id:i,issuer:u,owner:s,url:t}=e;if(typeof o!="string"||!/^runtime:.+/.test(o)||typeof i!="string"||i===""||!h(u)||typeof s!="string"||!/^user:.+/.test(s)||!h(t))throw d("directory registration answer is missing runtime, client_id, issuer, owner, or url");const{machine_id:c,is_default:a}=e;return{runtime:o,client_id:i,issuer:u,owner:s,url:t,...typeof c=="string"?{machine_id:c}:{},...typeof a=="boolean"?{is_default:a}:{}}}n(y,"registration");function l(){return _(g(),"runtime-client.pending.json")}n(l,"pendingPath");function C(){try{const r=q("user");return!r||!I(r)?[]:O(r,{withFileTypes:!0}).filter(e=>e.isDirectory()&&!e.name.startsWith(".")).map(e=>e.name).sort()}catch{return[]}}n(C,"installedPluginIds");async function T(r,e,o,i,u){const s=`${r.replace(/\/$/,"")}/v1/runtimes/registration`;let t;try{t=await fetch(s,{method:"PUT",headers:{authorization:`Bearer ${e}`,"content-type":"application/json"},body:JSON.stringify({jwk:o,name:i,platform:`${process.platform}-${process.arch}`,crtr_version:N(),plugins:C(),sandboxed:L()}),signal:AbortSignal.timeout(3e4)})}catch(a){throw d(`directory registration request to ${s} failed: ${a instanceof Error?a.message:String(a)}`)}const c=await t.text();if(!t.ok)throw t.status<500&&x(l(),{force:!0}),new f({error:"join_refused",message:`directory refused the registration: ${t.status} ${c.slice(0,500)}`,next:u});try{return y(JSON.parse(c))}catch(a){throw a instanceof SyntaxError?d("directory registration answer is not JSON"):a}}n(T,"register");function p(){const r=w(m());if(r?.token_sha256===void 0)return null;const{owner:e}=r;if(typeof e!="string"||!/^user:.+/.test(e))throw new Error(`${m()} was written by join but has a missing or invalid owner`);return r}n(p,"readJoined");function or(){return p()?.owner??null}n(or,"joinedOwner");function sr(){return p()?.issuer??null}n(sr,"joinedIssuer");function ar(){const r=p();return r===null?null:y(r)}n(ar,"joinedClient");function W(r){return new f({error:"daemon_running",message:`cannot register while a daemon answers on ${r}`,next:"Stop the daemon that owns this volume, then run `crtr sys join` again."})}n(W,"daemonRunningError");async function z(r,e,o,i,u){const s=w(m());if(s?.token_sha256===i)return{joined:y(s),registered:!1};R(g(),{recursive:!0,mode:448});let t=w(l());if(t?.token_sha256!==i||t.directory!==r||!t.jwk||!t.public_jwk){const{privateKey:P,publicKey:$}=U("ec",{namedCurve:"P-256"}),j=D();t={token_sha256:i,directory:r,jwk:{...P.export({format:"jwk"}),kid:j,alg:"ES256",use:"sig"},public_jwk:{...$.export({format:"jwk"}),kid:j,alg:"ES256",use:"sig"}},b(l(),t,{mode:384})}const{jwk:c,public_jwk:a}=t,k=await T(r,e,a,o,u);return{joined:k,registered:!0,client:{jwk:c,kid:c.kid,alg:"ES256",...k,token_sha256:i}}}n(z,"obtainRegistration");function B(r){if(!h(r))throw new f({error:"invalid_directory",message:"directory must be an http or https URL",received:r,field:"directory",next:"Pass the directory base URL, for example https://directory.example."})}n(B,"requireDirectory");async function v(r,e,o,i){if(B(r),e==="")throw new f({error:"invalid_token",message:"credential is empty",field:"token",next:"Pass the enrollment token provisioning supplied."});const{joined:u,registered:s,client:t}=await z(r,e,o,J("sha256").update(e).digest("hex"),i);return t&&(b(m(),t,{mode:384}),x(l(),{force:!0})),{...u,registered:s}}n(v,"registerAndStore");async function ur(r,e,o=S()){const i=A();if(await K(i))throw W(i);return v(r,e,o,"Provisioning must supply a new enrollment token; they are single-use and expire after 10 minutes.")}n(ur,"joinDirectory");async function cr(r,e){return p()!==null?null:v(r,e,S(),"Run `crtr sys signin` again.")}n(cr,"registerSignedInMac");export{C as installedPluginIds,ur as joinDirectory,ar as joinedClient,sr as joinedIssuer,or as joinedOwner,cr as registerSignedInMac};
1
+ var v=Object.defineProperty;var o=(e,r)=>v(e,"name",{value:r,configurable:!0});import{createHash as U,generateKeyPairSync as D,randomUUID as J}from"node:crypto";import{existsSync as N,mkdirSync as R,readdirSync as I,rmSync as x}from"node:fs";import{request as O}from"node:http";import{hostname as S}from"node:os";import{join as _}from"node:path";import{InputError as m}from"../io.js";import{network as l}from"../errors.js";import{secretsDir as g}from"../layout.js";import{apiSocketPath as q}from"../canvas/paths.js";import{atomicWriteJson as b,readJsonIfExists as h}from"../fs-utils.js";import{launcherPresent as T}from"../grants/sandboxes.js";import{crtrVersion as A}from"../../shared/crtr-version.js";import{pluginsDir as C}from"../scope.js";function f(){return _(g(),"runtime-client.json")}o(f,"clientPath");function w(e){if(typeof e!="string")return!1;try{const{protocol:r}=new URL(e);return r==="http:"||r==="https:"}catch{return!1}}o(w,"isUrl");function y(e){const r=e??{},{runtime:i,client_id:t,issuer:u,owner:s,url:n}=r;if(typeof i!="string"||!/^runtime:.+/.test(i)||typeof t!="string"||t===""||!w(u)||typeof s!="string"||!/^user:.+/.test(s)||!w(n))throw l("directory registration answer is missing runtime, client_id, issuer, owner, or url");const{machine_id:c,is_default:a}=r;return{runtime:i,client_id:t,issuer:u,owner:s,url:n,...typeof c=="string"?{machine_id:c}:{},...typeof a=="boolean"?{is_default:a}:{}}}o(y,"registration");function d(){return _(g(),"runtime-client.pending.json")}o(d,"pendingPath");function K(){try{const e=C("user");return!e||!N(e)?[]:I(e,{withFileTypes:!0}).filter(r=>r.isDirectory()&&!r.name.startsWith(".")).map(r=>r.name).sort()}catch{return[]}}o(K,"installedPluginIds");async function L(e,r,i,t,u){const s=`${e.replace(/\/$/,"")}/v1/runtimes/registration`;let n;try{n=await fetch(s,{method:"PUT",headers:{authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({jwk:i,name:t,platform:`${process.platform}-${process.arch}`,crtr_version:A(),plugins:K(),sandboxed:T()}),signal:AbortSignal.timeout(3e4)})}catch(a){throw l(`directory registration request to ${s} failed: ${a instanceof Error?a.message:String(a)}`)}const c=await n.text();if(!n.ok)throw n.status<500&&x(d(),{force:!0}),new m({error:"join_refused",message:`directory refused the registration: ${n.status} ${c.slice(0,500)}`,next:u});try{return y(JSON.parse(c))}catch(a){throw a instanceof SyntaxError?l("directory registration answer is not JSON"):a}}o(L,"register");function p(){const e=h(f());if(e?.token_sha256===void 0)return null;const{owner:r}=e;if(typeof r!="string"||!/^user:.+/.test(r))throw new Error(`${f()} was written by join but has a missing or invalid owner`);return e}o(p,"readJoined");function se(){return p()?.owner??null}o(se,"joinedOwner");function ae(){return p()?.issuer??null}o(ae,"joinedIssuer");function ue(){const e=p();return e===null?null:y(e)}o(ue,"joinedClient");function z(e){return new m({error:"daemon_running",message:`cannot register while a daemon answers on ${e}`,next:"Stop the daemon that owns this volume, then run `crtr sys join` again."})}o(z,"daemonRunningError");async function F(e,r,i,t,u){const s=h(f());if(s?.token_sha256===t)return{joined:y(s),registered:!1};R(g(),{recursive:!0,mode:448});let n=h(d());if(n?.token_sha256!==t||n.directory!==e||!n.jwk||!n.public_jwk){const{privateKey:P,publicKey:$}=D("ec",{namedCurve:"P-256"}),j=J();n={token_sha256:t,directory:e,jwk:{...P.export({format:"jwk"}),kid:j,alg:"ES256",use:"sig"},public_jwk:{...$.export({format:"jwk"}),kid:j,alg:"ES256",use:"sig"}},b(d(),n,{mode:384})}const{jwk:c,public_jwk:a}=n,k=await L(e,r,a,i,u);return{joined:k,registered:!0,client:{jwk:c,kid:c.kid,alg:"ES256",...k,token_sha256:t}}}o(F,"obtainRegistration");function W(e){if(!w(e))throw new m({error:"invalid_directory",message:"directory must be an http or https URL",received:e,field:"directory",next:"Pass the directory base URL, for example https://directory.example."})}o(W,"requireDirectory");async function E(e,r,i,t){if(W(e),r==="")throw new m({error:"invalid_token",message:"credential is empty",field:"token",next:"Pass the enrollment token provisioning supplied."});const{joined:u,registered:s,client:n}=await F(e,r,i,U("sha256").update(r).digest("hex"),t);return n&&(b(f(),n,{mode:384}),x(d(),{force:!0})),{...u,registered:s}}o(E,"registerAndStore");function B(e){return new Promise(r=>{const i=O({socketPath:e,path:"/healthz",method:"GET",timeout:1e3},t=>{t.resume(),r(!0)});i.on("timeout",()=>i.destroy(new Error("daemon probe timed out"))),i.on("error",t=>{t.code==="ENOENT"||t.code==="ECONNREFUSED"?r(!1):r(!0)}),i.end()})}o(B,"daemonAnswers");async function ce(e,r,i=S()){const t=q();if(await B(t))throw z(t);return E(e,r,i,"Provisioning must supply a new enrollment token; they are single-use and expire after 10 minutes.")}o(ce,"joinDirectory");async function me(e,r){return p()!==null?null:E(e,r,S(),"Run `crtr sys signin` again.")}o(me,"registerSignedInMac");export{K as installedPluginIds,ce as joinDirectory,ue as joinedClient,ae as joinedIssuer,se as joinedOwner,me as registerSignedInMac};
@@ -179,11 +179,6 @@ export declare function hasSyncedGrants(source: string): Promise<boolean>;
179
179
  * the install's person full local scopes and is not the directory's. Delete it so no
180
180
  * grant exists until grant sync installs the directory's mirror. */
181
181
  export declare function dropLocalGrantMirror(db: CanvasDb): Promise<number>;
182
- /** Mark rows a build older than C-D2 wrote as computed for their revision. That build computed every column locally in the same
183
- * write but never set `computed_rev`, so its rows are complete; left NULL they read as no grant until the next successful
184
- * sync rewrites them, and the terminal grant then refuses every launch (NL-550). A directory-written row with lagging
185
- * columns has NULL scopes, so it is never matched. Returns the rows changed. */
186
- export declare function backfillComputedRev(): Promise<number>;
187
182
  /** The directory response is complete; commit it or keep the prior snapshot intact. */
188
183
  /** A directory team the runtime's owner belongs to: `team` is `team:<id>`, `members` are `user:<id>`. */
189
184
  export interface TeamRecord {
@@ -1,11 +1,11 @@
1
- var L=Object.defineProperty;var n=(e,r)=>L(e,"name",{value:r,configurable:!0});import{createHash as C}from"node:crypto";import{parsePrincipal as T,parseScope as M}from"@north-light/identity";import{openDb as d,withCanvasWrite as A}from"../canvas/db.js";import{isUnsandboxedMachine as O}from"../runtime/unsandboxed.js";import{replaceWrittenBy as j,userSubject as F}from"../permissions/facts.js";import{GROUP_TYPE as f,OBJECT_TYPE as $}from"../permissions/builtin.js";import{shadowCheck as k}from"./shadow.js";const U=["not_started","pending","ready","failed","unavailable"],P=["ultra","strong","medium","light"];function G(e,r,t){if(e==null||e==="user")return r;if(e==="app")return t;if(typeof e!="string"||T(e)===null)throw new TypeError("invalid grant payer");return e}n(G,"principalPayer");function H(e){const r=e.payer===null?null:T(e.payer);return r!==null&&r.kind==="app"&&r.path.length===0}n(H,"endpointPays");function x(){const e=process.env.CRTR_RUNTIME;return e?{sql:" AND runtime = ?",args:[e]}:{sql:"",args:[]}}n(x,"runtimeScope");async function i(e,r,t=[]){const s=x();return await(await d()).prepare(`SELECT ${e} FROM grants WHERE (${r})${s.sql}`).all(...t,...s.args)}n(i,"grantRows");async function u(e,r,t=[]){return(await i(e,r,t))[0]}n(u,"grantRow");function W(e){return!/\u0000|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/.test(e)}n(W,"jsonbSafe");function l(e){if(!Array.isArray(e))throw new TypeError("grant scopes must be a list");return e.map(r=>{if(!r||typeof r!="object"||typeof r.scope!="string"||!W(r.scope)||!["always","ask"].includes(r.mode))throw new TypeError("invalid grant scope entry");return{scope:r.scope,mode:r.mode}})}n(l,"entries");function J(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{state:r,message:t,next:s,step:o}=e;return typeof r!="string"||!U.includes(r)||t!==void 0&&typeof t!="string"||o!==void 0&&typeof o!="string"||typeof s!="string"||!s?null:{state:r,...t===void 0?{}:{message:t},next:s,...o===void 0?{}:{step:o}}}n(J,"dependencyOf");function w(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const r={};for(const[t,s]of Object.entries(e)){const o=J(s);o&&(r[t]=o)}return r}n(w,"dependenciesOf");function V(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{base_url:r,rungs:t}=e;if(typeof r!="string"||!r||!t||typeof t!="object"||Array.isArray(t))return null;const s={};for(const o of P){const a=t[o];typeof a=="string"&&a&&(s[o]=a)}return Object.keys(s).length?{base_url:r.replace(/\/+$/,""),rungs:s}:null}n(V,"inferenceEndpointOf");function b(e,r,t,s){return r===e&&t&&s}n(b,"computedFor");function _(e){if(!b(e.rev,e.computed_rev,e.scopes_json!==null,e.resolved_scopes_json!==null))throw new TypeError("grant columns are not computed for this revision");return{id:e.id,runtime:e.runtime,sub:e.sub,grantee:e.grantee,grantee_prefix:e.grantee_prefix??null,rev:e.rev,scopes:l(JSON.parse(e.scopes_json)),resolved_scopes:l(JSON.parse(e.resolved_scopes_json)),spend_cap:e.spend_cap,expires_at:e.expires_at,status:e.status,revoked_at:e.revoked_at,approved_at:e.approved_at,payer:e.payer,dependencies:w(JSON.parse(e.dependencies_json??"{}")),run_notice_url:e.run_notice_url??null,inference_endpoint:e.inference_endpoint_json?V(JSON.parse(e.inference_endpoint_json)):null,synced_at:e.synced_at??""}}n(_,"record");function p(e){if(!e||e.status!=="active")return null;try{const r=Z(_(e));return r!==null&&k(r),r}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}n(p,"active");function y(e){return e.grantee!=="app:terminal"&&O()}n(y,"mirrorOnly");async function de(){return(await Y()).filter(e=>!y(e))}n(de,"localGrants");async function le(e,r){return!y({grantee:e})&&await u("1","grantee = ? AND sub <> ? AND status <> 'removed'",[e,r])!==void 0}n(le,"otherLiveGrantOfApp");const g="[A-Za-z0-9_-]{1,64}",q=new RegExp(`^(${g}):(${g})$`);function B(e){const r=new Set;for(const t of e)if(t.status==="active")for(const{scope:s}of t.resolved_scopes){const o=q.exec(s);o&&o[1]!=="crtr"&&r.add(o[1])}return[...r].sort()}n(B,"providerIdsFromGrants");async function fe(){const e=x();return(await(await d()).prepare(`SELECT DISTINCT m[1] AS id FROM (
1
+ var I=Object.defineProperty;var n=(e,r)=>I(e,"name",{value:r,configurable:!0});import{createHash as L}from"node:crypto";import{parsePrincipal as T,parseScope as C}from"@north-light/identity";import{openDb as d,withCanvasWrite as M}from"../canvas/db.js";import{isUnsandboxedMachine as A}from"../runtime/unsandboxed.js";import{replaceWrittenBy as O,userSubject as F}from"../permissions/facts.js";import{GROUP_TYPE as f,OBJECT_TYPE as $}from"../permissions/builtin.js";import{shadowCheck as k}from"./shadow.js";const U=["not_started","pending","ready","failed","unavailable"],P=["ultra","strong","medium","light"];function G(e,r,t){if(e==null||e==="user")return r;if(e==="app")return t;if(typeof e!="string"||T(e)===null)throw new TypeError("invalid grant payer");return e}n(G,"principalPayer");function H(e){const r=e.payer===null?null:T(e.payer);return r!==null&&r.kind==="app"&&r.path.length===0}n(H,"endpointPays");function x(){const e=process.env.CRTR_RUNTIME;return e?{sql:" AND runtime = ?",args:[e]}:{sql:"",args:[]}}n(x,"runtimeScope");async function c(e,r,t=[]){const s=x();return await(await d()).prepare(`SELECT ${e} FROM grants WHERE (${r})${s.sql}`).all(...t,...s.args)}n(c,"grantRows");async function u(e,r,t=[]){return(await c(e,r,t))[0]}n(u,"grantRow");function W(e){return!/\u0000|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/.test(e)}n(W,"jsonbSafe");function l(e){if(!Array.isArray(e))throw new TypeError("grant scopes must be a list");return e.map(r=>{if(!r||typeof r!="object"||typeof r.scope!="string"||!W(r.scope)||!["always","ask"].includes(r.mode))throw new TypeError("invalid grant scope entry");return{scope:r.scope,mode:r.mode}})}n(l,"entries");function J(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{state:r,message:t,next:s,step:o}=e;return typeof r!="string"||!U.includes(r)||t!==void 0&&typeof t!="string"||o!==void 0&&typeof o!="string"||typeof s!="string"||!s?null:{state:r,...t===void 0?{}:{message:t},next:s,...o===void 0?{}:{step:o}}}n(J,"dependencyOf");function j(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const r={};for(const[t,s]of Object.entries(e)){const o=J(s);o&&(r[t]=o)}return r}n(j,"dependenciesOf");function V(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{base_url:r,rungs:t}=e;if(typeof r!="string"||!r||!t||typeof t!="object"||Array.isArray(t))return null;const s={};for(const o of P){const a=t[o];typeof a=="string"&&a&&(s[o]=a)}return Object.keys(s).length?{base_url:r.replace(/\/+$/,""),rungs:s}:null}n(V,"inferenceEndpointOf");function w(e,r,t,s){return r===e&&t&&s}n(w,"computedFor");function _(e){if(!w(e.rev,e.computed_rev,e.scopes_json!==null,e.resolved_scopes_json!==null))throw new TypeError("grant columns are not computed for this revision");return{id:e.id,runtime:e.runtime,sub:e.sub,grantee:e.grantee,grantee_prefix:e.grantee_prefix??null,rev:e.rev,scopes:l(JSON.parse(e.scopes_json)),resolved_scopes:l(JSON.parse(e.resolved_scopes_json)),spend_cap:e.spend_cap,expires_at:e.expires_at,status:e.status,revoked_at:e.revoked_at,approved_at:e.approved_at,payer:e.payer,dependencies:j(JSON.parse(e.dependencies_json??"{}")),run_notice_url:e.run_notice_url??null,inference_endpoint:e.inference_endpoint_json?V(JSON.parse(e.inference_endpoint_json)):null,synced_at:e.synced_at??""}}n(_,"record");function p(e){if(!e||e.status!=="active")return null;try{const r=Z(_(e));return r!==null&&k(r),r}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}n(p,"active");function y(e){return e.grantee!=="app:terminal"&&A()}n(y,"mirrorOnly");async function de(){return(await Y()).filter(e=>!y(e))}n(de,"localGrants");async function le(e,r){return!y({grantee:e})&&await u("1","grantee = ? AND sub <> ? AND status <> 'removed'",[e,r])!==void 0}n(le,"otherLiveGrantOfApp");const g="[A-Za-z0-9_-]{1,64}",q=new RegExp(`^(${g}):(${g})$`);function B(e){const r=new Set;for(const t of e)if(t.status==="active")for(const{scope:s}of t.resolved_scopes){const o=q.exec(s);o&&o[1]!=="crtr"&&r.add(o[1])}return[...r].sort()}n(B,"providerIdsFromGrants");async function fe(){const e=x();return(await(await d()).prepare(`SELECT DISTINCT m[1] AS id FROM (
2
2
  SELECT DISTINCT e->>'scope' AS scope FROM (
3
- SELECT t::jsonb AS j FROM (SELECT DISTINCT resolved_scopes_json AS t FROM grants WHERE ${m}${N()}${e.sql}) d OFFSET 0) p
3
+ SELECT t::jsonb AS j FROM (SELECT DISTINCT resolved_scopes_json AS t FROM grants WHERE ${m}${S()}${e.sql}) d OFFSET 0) p
4
4
  CROSS JOIN LATERAL jsonb_array_elements(CASE WHEN jsonb_typeof(p.j) = 'array' THEN p.j ELSE '[]' END) e) s
5
5
  CROSS JOIN LATERAL regexp_match(s.scope, '^(${g}):${g}$') m
6
- WHERE m[1] <> 'crtr'`).all(...e.args)).map(t=>t.id).sort()}n(fe,"activeProviderIds");async function _e(){const e=x();return await(await d()).prepare(`SELECT 1 FROM grants WHERE ${m}${N()}${e.sql} LIMIT 1`).get(...e.args)!==void 0}n(_e,"anyActiveGrant");async function ye(e,r){return await u("1",`sub = ? AND ${m}${N()} AND EXISTS (
6
+ WHERE m[1] <> 'crtr'`).all(...e.args)).map(t=>t.id).sort()}n(fe,"activeProviderIds");async function _e(){const e=x();return await(await d()).prepare(`SELECT 1 FROM grants WHERE ${m}${S()}${e.sql} LIMIT 1`).get(...e.args)!==void 0}n(_e,"anyActiveGrant");async function ye(e,r){return await u("1",`sub = ? AND ${m}${S()} AND EXISTS (
7
7
  SELECT 1 FROM jsonb_array_elements(CASE WHEN jsonb_typeof(resolved_scopes_json::jsonb) = 'array' THEN resolved_scopes_json::jsonb ELSE '[]' END) e
8
- WHERE starts_with(e->>'scope', ?))`,[e,`${r}:`])!==void 0}n(ye,"activeGrantNamesApp");const m="status = 'active' AND computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL",X="computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL";function N(){return O()?" AND grantee = 'app:terminal'":""}n(N,"localOnly");async function ge(){return(await i("DISTINCT sub",X)).map(e=>e.sub)}n(ge,"grantSubs");async function Ee(e){return h(e===void 0?await i("*","status = 'active'"):await i("*","sub = ? AND status = 'active'",[e]))}n(Ee,"activeGrants");async function ve(e){const r=await i("*","sub = ? AND status = 'active'",[e]);return new Set(B(r.flatMap(t=>{try{return[_(t)]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})))}n(ve,"grantedProviderIds");function xe(e,r){return e.source_marketplace===null&&e.source_path===null&&r.has(e.name)}n(xe,"isProviderBundleRow");async function me(e){return(await i("*","sub = ? AND status = 'active'",[e])).flatMap(t=>{const s=p(t);return s===null?[]:[s]})}n(me,"activeGrantsOfPerson");async function Y(){return h(await i("*","true"))}n(Y,"allGrants");async function Ne(e){return(await i("sub, status, rev, computed_rev, resolved_scopes_json, scopes_json IS NOT NULL AS has_scopes","sub = ?",[e])).flatMap(t=>{if(!b(t.rev,t.computed_rev,t.has_scopes,t.resolved_scopes_json!==null))return[];try{return[{sub:t.sub,status:t.status,resolved_scopes:l(JSON.parse(t.resolved_scopes_json))}]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})}n(Ne,"grantsOfPerson");function h(e){return e.flatMap(r=>{try{return[_(r)]}catch(t){if(t instanceof TypeError||t instanceof SyntaxError)return[];throw t}})}n(h,"records");function z(e){return e.expires_at!==null&&!(Date.parse(e.expires_at)>Date.now())}n(z,"grantExpired");function Z(e){if(e.status!=="active"||z(e))return null;try{const r=e.resolved_scopes.map(({scope:t})=>M(t));return{...e,resolved:e.resolved_scopes.flatMap(({mode:t},s)=>t==="always"?[r[s]]:[])}}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}n(Z,"activeRecord");function S(e){return Array.isArray(e)?`[${e.map(S).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().filter(r=>e[r]!==void 0).map(r=>`${JSON.stringify(r)}:${S(e[r])}`).join(",")}}`:JSON.stringify(e)??"null"}n(S,"canonicalJson");function Se(e){const r={rev:e.rev,resolved_scopes:e.resolved_scopes,spend_cap:e.spend_cap,payer:e.payer,dependencies:e.dependencies??{},...e.inference_endpoint?{inference_endpoint:e.inference_endpoint}:{}};return C("sha256").update(S(r)).digest("base64url").slice(0,22)}n(Se,"grantVersion");async function Te(e){return!!await u("1","id = ?",[e])}n(Te,"hasGrant");async function Ae(e){return await u("rev, status","id = ?",[e])??null}n(Ae,"grantSyncState");async function Oe(e,r){return await u("rev, status","grantee = ? AND sub = ?",[e,r])??null}n(Oe,"grantSyncStateFor");async function K(e){const r=await u("*","id = ?",[e]);if(!r)return null;try{return _(r)}catch(t){if(t instanceof TypeError||t instanceof SyntaxError)return null;throw t}}n(K,"grantRecord");async function je(e){const r=await u("*","id = ?",[e]);if(!r)return{standing:"inactive",rev:null,sub:null,grantee:null,status:null,removal_done_at:null,record:null};const t={rev:r.rev,sub:r.sub,grantee:r.grantee,status:r.status,removal_done_at:r.removal_done_at??null};if(r.status!=="active")return{...t,standing:"inactive",record:null};if(r.computed_rev!==r.rev)return{...t,standing:"lagging",record:null};const s=p(r);return s===null?{...t,standing:"inactive",record:null}:{...t,standing:"active",record:s}}n(je,"grantStanding");async function we(e){return(await i("id",e)).map(r=>r.id)}n(we,"grantIdsWhere");async function be(e){const r=e?await K(e):null;return r!==null&&H(r)?"app":"user"}n(be,"payerOfGrant");async function Q(e){return p(await u("*","id = ?",[e]))}n(Q,"activeGrant");async function he(e,r){const t=await u("*","grantee = ? AND grantee_prefix IS NULL AND sub = ?",[e,r]);if(t)return p(t);const s=await i("*","sub = ? AND grantee_prefix IS NOT NULL AND starts_with(?, grantee_prefix)",[r,e]);return s.sort((o,a)=>a.grantee_prefix.length-o.grantee_prefix.length),p(s[0])}n(he,"grantFor");async function Re(e){if(y({grantee:e}))return null;const r=await i("*","grantee = ? AND status = 'active'",[e]);if(r.length>1)throw new Error(`multiple active grants for ${e}`);return p(r[0])}n(Re,"activeGrantForApp");async function De(e){const r=await Q(e);return r&&r.run_notice_url&&!y(r)?{url:r.run_notice_url,sub:r.sub,grantee:r.grantee}:null}n(De,"runNoticeTarget");async function Ie(e){const r=await i("*","grantee = 'app:terminal' AND sub = ? AND status = 'active'",[e]);if(r.length>1)throw new Error(`multiple active terminal grants for ${e}`);return p(r[0])}n(Ie,"terminalGrant");async function Le(){return(await(await d()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value??null}n(Le,"grantsSource");async function Ce(e){return(await(await d()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value===e}n(Ce,"hasSyncedGrants");async function Me(e){return(await e.prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value!=="local"?0:(await e.prepare("DELETE FROM runtime_state WHERE key = 'grants_source'").run(),Number((await e.prepare("DELETE FROM grants").run()).changes))}n(Me,"dropLocalGrantMirror");async function Fe(){return await A(async e=>Number((await e.prepare("UPDATE grants SET computed_rev = rev WHERE computed_rev IS NULL AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL").run()).changes))}n(Fe,"backfillComputedRev");function $e(e){if(e===void 0)return[];if(!Array.isArray(e))throw new TypeError("invalid grant sync response");const r=[];for(const t of e){const{team:s,members:o}=t??{};if(!(typeof s!="string"||!/^team:\S+$/.test(s))){if(!Array.isArray(o)||o.some(a=>typeof a!="string"||!/^user:[^\s*]+$/.test(a)))throw new TypeError("invalid grant sync response");r.push({team:s,members:o})}}return r}n($e,"teamsOf");async function ke(e,r,t,s=[]){const o=new Set;for(const a of e){if(o.has(a.id)||!a.id||!a.runtime||!a.sub||!a.grantee||!Number.isInteger(a.rev)||!["active","revoked","removed"].includes(a.status))throw new TypeError("invalid grant sync response");if(a.grantee==="*"!=(a.grantee_prefix!=null))throw new TypeError("invalid grant sync response");o.add(a.id),l(a.scopes),l(a.resolved_scopes)}await A(async a=>{let E=0;const v=[...o];E+=Number((await(v.length?a.prepareUncached(`DELETE FROM grants WHERE id NOT IN (${v.map(()=>"?").join(",")})`).run(...v):a.prepareUncached("DELETE FROM grants").run())).changes);const R=a.prepare(`INSERT INTO grants
8
+ WHERE starts_with(e->>'scope', ?))`,[e,`${r}:`])!==void 0}n(ye,"activeGrantNamesApp");const m="status = 'active' AND computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL",X="computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL";function S(){return A()?" AND grantee = 'app:terminal'":""}n(S,"localOnly");async function ge(){return(await c("DISTINCT sub",X)).map(e=>e.sub)}n(ge,"grantSubs");async function Ee(e){return b(e===void 0?await c("*","status = 'active'"):await c("*","sub = ? AND status = 'active'",[e]))}n(Ee,"activeGrants");async function ve(e){const r=await c("*","sub = ? AND status = 'active'",[e]);return new Set(B(r.flatMap(t=>{try{return[_(t)]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})))}n(ve,"grantedProviderIds");function xe(e,r){return e.source_marketplace===null&&e.source_path===null&&r.has(e.name)}n(xe,"isProviderBundleRow");async function me(e){return(await c("*","sub = ? AND status = 'active'",[e])).flatMap(t=>{const s=p(t);return s===null?[]:[s]})}n(me,"activeGrantsOfPerson");async function Y(){return b(await c("*","true"))}n(Y,"allGrants");async function Se(e){return(await c("sub, status, rev, computed_rev, resolved_scopes_json, scopes_json IS NOT NULL AS has_scopes","sub = ?",[e])).flatMap(t=>{if(!w(t.rev,t.computed_rev,t.has_scopes,t.resolved_scopes_json!==null))return[];try{return[{sub:t.sub,status:t.status,resolved_scopes:l(JSON.parse(t.resolved_scopes_json))}]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})}n(Se,"grantsOfPerson");function b(e){return e.flatMap(r=>{try{return[_(r)]}catch(t){if(t instanceof TypeError||t instanceof SyntaxError)return[];throw t}})}n(b,"records");function z(e){return e.expires_at!==null&&!(Date.parse(e.expires_at)>Date.now())}n(z,"grantExpired");function Z(e){if(e.status!=="active"||z(e))return null;try{const r=e.resolved_scopes.map(({scope:t})=>C(t));return{...e,resolved:e.resolved_scopes.flatMap(({mode:t},s)=>t==="always"?[r[s]]:[])}}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}n(Z,"activeRecord");function N(e){return Array.isArray(e)?`[${e.map(N).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().filter(r=>e[r]!==void 0).map(r=>`${JSON.stringify(r)}:${N(e[r])}`).join(",")}}`:JSON.stringify(e)??"null"}n(N,"canonicalJson");function Ne(e){const r={rev:e.rev,resolved_scopes:e.resolved_scopes,spend_cap:e.spend_cap,payer:e.payer,dependencies:e.dependencies??{},...e.inference_endpoint?{inference_endpoint:e.inference_endpoint}:{}};return L("sha256").update(N(r)).digest("base64url").slice(0,22)}n(Ne,"grantVersion");async function Te(e){return!!await u("1","id = ?",[e])}n(Te,"hasGrant");async function Ae(e){return await u("rev, status","id = ?",[e])??null}n(Ae,"grantSyncState");async function Oe(e,r){return await u("rev, status","grantee = ? AND sub = ?",[e,r])??null}n(Oe,"grantSyncStateFor");async function K(e){const r=await u("*","id = ?",[e]);if(!r)return null;try{return _(r)}catch(t){if(t instanceof TypeError||t instanceof SyntaxError)return null;throw t}}n(K,"grantRecord");async function je(e){const r=await u("*","id = ?",[e]);if(!r)return{standing:"inactive",rev:null,sub:null,grantee:null,status:null,removal_done_at:null,record:null};const t={rev:r.rev,sub:r.sub,grantee:r.grantee,status:r.status,removal_done_at:r.removal_done_at??null};if(r.status!=="active")return{...t,standing:"inactive",record:null};if(r.computed_rev!==r.rev)return{...t,standing:"lagging",record:null};const s=p(r);return s===null?{...t,standing:"inactive",record:null}:{...t,standing:"active",record:s}}n(je,"grantStanding");async function we(e){return(await c("id",e)).map(r=>r.id)}n(we,"grantIdsWhere");async function be(e){const r=e?await K(e):null;return r!==null&&H(r)?"app":"user"}n(be,"payerOfGrant");async function Q(e){return p(await u("*","id = ?",[e]))}n(Q,"activeGrant");async function he(e,r){const t=await u("*","grantee = ? AND grantee_prefix IS NULL AND sub = ?",[e,r]);if(t)return p(t);const s=await c("*","sub = ? AND grantee_prefix IS NOT NULL AND starts_with(?, grantee_prefix)",[r,e]);return s.sort((o,a)=>a.grantee_prefix.length-o.grantee_prefix.length),p(s[0])}n(he,"grantFor");async function Re(e){if(y({grantee:e}))return null;const r=await c("*","grantee = ? AND status = 'active'",[e]);if(r.length>1)throw new Error(`multiple active grants for ${e}`);return p(r[0])}n(Re,"activeGrantForApp");async function De(e){const r=await Q(e);return r&&r.run_notice_url&&!y(r)?{url:r.run_notice_url,sub:r.sub,grantee:r.grantee}:null}n(De,"runNoticeTarget");async function Ie(e){const r=await c("*","grantee = 'app:terminal' AND sub = ? AND status = 'active'",[e]);if(r.length>1)throw new Error(`multiple active terminal grants for ${e}`);return p(r[0])}n(Ie,"terminalGrant");async function Le(){return(await(await d()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value??null}n(Le,"grantsSource");async function Ce(e){return(await(await d()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value===e}n(Ce,"hasSyncedGrants");async function Me(e){return(await e.prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value!=="local"?0:(await e.prepare("DELETE FROM runtime_state WHERE key = 'grants_source'").run(),Number((await e.prepare("DELETE FROM grants").run()).changes))}n(Me,"dropLocalGrantMirror");function Fe(e){if(e===void 0)return[];if(!Array.isArray(e))throw new TypeError("invalid grant sync response");const r=[];for(const t of e){const{team:s,members:o}=t??{};if(!(typeof s!="string"||!/^team:\S+$/.test(s))){if(!Array.isArray(o)||o.some(a=>typeof a!="string"||!/^user:[^\s*]+$/.test(a)))throw new TypeError("invalid grant sync response");r.push({team:s,members:o})}}return r}n(Fe,"teamsOf");async function $e(e,r,t,s=[]){const o=new Set;for(const a of e){if(o.has(a.id)||!a.id||!a.runtime||!a.sub||!a.grantee||!Number.isInteger(a.rev)||!["active","revoked","removed"].includes(a.status))throw new TypeError("invalid grant sync response");if(a.grantee==="*"!=(a.grantee_prefix!=null))throw new TypeError("invalid grant sync response");o.add(a.id),l(a.scopes),l(a.resolved_scopes)}await M(async a=>{let E=0;const v=[...o];E+=Number((await(v.length?a.prepareUncached(`DELETE FROM grants WHERE id NOT IN (${v.map(()=>"?").join(",")})`).run(...v):a.prepareUncached("DELETE FROM grants").run())).changes);const h=a.prepare(`INSERT INTO grants
9
9
  (id, runtime, sub, grantee, grantee_prefix, rev, scopes_json, resolved_scopes_json, spend_cap, expires_at,
10
10
  status, revoked_at, approved_at, payer, dependencies_json, run_notice_url, inference_endpoint_json, synced_at, computed_rev)
11
11
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
@@ -19,6 +19,6 @@ var L=Object.defineProperty;var n=(e,r)=>L(e,"name",{value:r,configurable:!0});i
19
19
  grants.run_notice_url, grants.inference_endpoint_json, grants.computed_rev)
20
20
  IS DISTINCT FROM (excluded.runtime, excluded.sub, excluded.grantee, excluded.grantee_prefix, excluded.rev, excluded.scopes_json, excluded.resolved_scopes_json,
21
21
  excluded.spend_cap, excluded.expires_at, excluded.status, excluded.revoked_at, excluded.approved_at, excluded.payer,
22
- excluded.dependencies_json, excluded.run_notice_url, excluded.inference_endpoint_json, excluded.computed_rev)`);for(const c of e)E+=Number((await R.run(c.id,c.runtime,c.sub,c.grantee,c.grantee_prefix??null,c.rev,JSON.stringify(c.scopes),JSON.stringify(c.resolved_scopes),c.spend_cap,c.expires_at,c.status,c.revoked_at,c.approved_at,G(c.payer,c.sub,c.grantee),JSON.stringify(w(c.dependencies)),c.run_notice_url??null,c.inference_endpoint?JSON.stringify(c.inference_endpoint):null,c.synced_at,c.rev)).changes);await j(a,"directory",f,"member",s.flatMap(({team:c,members:D})=>D.map(I=>({resourceId:c,subject:F(I)})))),await te(a),await a.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_source', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t),E>0&&await a.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_generation', '1') ON CONFLICT(key) DO UPDATE SET value = CAST(CAST(runtime_state.value AS INTEGER) + 1 AS TEXT)").run()})}n(ke,"replaceGrants");const ee=["editor","messenger","user_of"],re="app-admin";async function te(e){const t=(await e.prepare(`SELECT o.id AS object, r.subject_type, r.subject_id FROM objects o
22
+ excluded.dependencies_json, excluded.run_notice_url, excluded.inference_endpoint_json, excluded.computed_rev)`);for(const i of e)E+=Number((await h.run(i.id,i.runtime,i.sub,i.grantee,i.grantee_prefix??null,i.rev,JSON.stringify(i.scopes),JSON.stringify(i.resolved_scopes),i.spend_cap,i.expires_at,i.status,i.revoked_at,i.approved_at,G(i.payer,i.sub,i.grantee),JSON.stringify(j(i.dependencies)),i.run_notice_url??null,i.inference_endpoint?JSON.stringify(i.inference_endpoint):null,i.synced_at,i.rev)).changes);await O(a,"directory",f,"member",s.flatMap(({team:i,members:R})=>R.map(D=>({resourceId:i,subject:F(D)})))),await te(a),await a.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_source', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t),E>0&&await a.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_generation', '1') ON CONFLICT(key) DO UPDATE SET value = CAST(CAST(runtime_state.value AS INTEGER) + 1 AS TEXT)").run()})}n($e,"replaceGrants");const ee=["editor","messenger","user_of"],re="app-admin";async function te(e){const t=(await e.prepare(`SELECT o.id AS object, r.subject_type, r.subject_id FROM objects o
23
23
  JOIN relations r ON r.resource_type = 'app' AND r.resource_id = o.name AND r.relation = 'admin' AND r.subject_type IN ('user', ?)
24
- WHERE o.type = 'app' AND o.deleted_at IS NULL`).all(f)).map(s=>({resourceId:s.object,subject:s.subject_type===f?{type:f,id:s.subject_id,relation:"member"}:{type:"user",id:s.subject_id,relation:""}}));for(const s of ee)await j(e,re,$,s,t)}n(te,"reconcileAppAdminFacts");async function Ue(){const e=await(await d()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_generation'").get();return e?Number(e.value):0}n(Ue,"grantsGeneration");export{re as APP_ADMIN_WRITER,Q as activeGrant,Re as activeGrantForApp,ye as activeGrantNamesApp,Ee as activeGrants,me as activeGrantsOfPerson,fe as activeProviderIds,Z as activeRecord,Y as allGrants,_e as anyActiveGrant,Fe as backfillComputedRev,S as canonicalJson,w as dependenciesOf,Me as dropLocalGrantMirror,H as endpointPays,z as grantExpired,he as grantFor,we as grantIdsWhere,K as grantRecord,je as grantStanding,ge as grantSubs,Ae as grantSyncState,Oe as grantSyncStateFor,Se as grantVersion,ve as grantedProviderIds,Ue as grantsGeneration,Ne as grantsOfPerson,Le as grantsSource,Te as hasGrant,Ce as hasSyncedGrants,V as inferenceEndpointOf,xe as isProviderBundleRow,de as localGrants,y as mirrorOnly,le as otherLiveGrantOfApp,be as payerOfGrant,G as principalPayer,B as providerIdsFromGrants,te as reconcileAppAdminFacts,ke as replaceGrants,De as runNoticeTarget,x as runtimeScope,$e as teamsOf,Ie as terminalGrant};
24
+ WHERE o.type = 'app' AND o.deleted_at IS NULL`).all(f)).map(s=>({resourceId:s.object,subject:s.subject_type===f?{type:f,id:s.subject_id,relation:"member"}:{type:"user",id:s.subject_id,relation:""}}));for(const s of ee)await O(e,re,$,s,t)}n(te,"reconcileAppAdminFacts");async function ke(){const e=await(await d()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_generation'").get();return e?Number(e.value):0}n(ke,"grantsGeneration");export{re as APP_ADMIN_WRITER,Q as activeGrant,Re as activeGrantForApp,ye as activeGrantNamesApp,Ee as activeGrants,me as activeGrantsOfPerson,fe as activeProviderIds,Z as activeRecord,Y as allGrants,_e as anyActiveGrant,N as canonicalJson,j as dependenciesOf,Me as dropLocalGrantMirror,H as endpointPays,z as grantExpired,he as grantFor,we as grantIdsWhere,K as grantRecord,je as grantStanding,ge as grantSubs,Ae as grantSyncState,Oe as grantSyncStateFor,Ne as grantVersion,ve as grantedProviderIds,ke as grantsGeneration,Se as grantsOfPerson,Le as grantsSource,Te as hasGrant,Ce as hasSyncedGrants,V as inferenceEndpointOf,xe as isProviderBundleRow,de as localGrants,y as mirrorOnly,le as otherLiveGrantOfApp,be as payerOfGrant,G as principalPayer,B as providerIdsFromGrants,te as reconcileAppAdminFacts,$e as replaceGrants,De as runNoticeTarget,x as runtimeScope,Fe as teamsOf,Ie as terminalGrant};
@@ -1 +1 @@
1
- var j=Object.defineProperty;var r=(e,n)=>j(e,"name",{value:n,configurable:!0});import{createPrivateKey as O,randomUUID as $,sign as A}from"node:crypto";import{readFileSync as T}from"node:fs";import{join as N}from"node:path";import{crtrHome as R}from"../canvas/paths.js";import{withCanvasWrite as v}from"../canvas/db.js";import{reconcilePackages as G}from"../graph/package-reconcile.js";import{isUnsandboxedMachine as k}from"../runtime/unsandboxed.js";import{emitEvent as f}from"../events/emit.js";import{describeOutboundFailure as J,outboundFetch as b,outboundJson as E,outboundRefusal as S}from"../events/outbound.js";import{dependenciesOf as U,endpointPays as B,inferenceEndpointOf as C,principalPayer as D,replaceGrants as F,teamsOf as I}from"./mirror.js";import{onGrantSync as M}from"./on-sync.js";import{hostedEndpointOf as W,paymentSetupUrlOf as q,storeHostedEndpoint as L}from"./hosted-endpoint.js";import{adoptInstallPerson as H}from"../scoped-state/migrate.js";import{PersonOutsideRequestError as z,PersonUnresolvedError as K,personId as V,resolvePerson as Y,retireLocalPerson as Q,setPersonId as X}from"../canvas/person.js";const be=300;function Z(e,n){const t=Math.floor(Date.now()/1e3),i=Buffer.from(JSON.stringify({alg:"ES256",typ:"JWT",kid:e.kid})).toString("base64url"),c=Buffer.from(JSON.stringify({iss:e.client_id,sub:e.client_id,aud:n,iat:t,exp:t+300,jti:$()})).toString("base64url"),u=`${i}.${c}`,o=A("sha256",Buffer.from(u),{key:O({key:e.jwk,format:"jwk"}),dsaEncoding:"ieee-p1363"});return`${u}.${o.toString("base64url")}`}r(Z,"assertion");function y(){const e=JSON.parse(T(N(R(),"secrets","runtime-client.json"),"utf8"));if(!e.jwk||e.alg!=="ES256"||!e.kid||!e.client_id||!e.runtime||e.jwk.kid!==e.kid||e.jwk.kty!=="EC"||e.jwk.crv!=="P-256"||!e.jwk.d)throw new TypeError("invalid runtime client key");return e}r(y,"runtimeClient");function Ee(e=y()){return e.runtime.startsWith("runtime:")?e.runtime.slice(8):e.runtime}r(Ee,"runtimeId");function ee(e){return"This machine was removed from your Northlight account. To use it again, run `crtr sys signin`."}r(ee,"machineRevokedMessage");class x extends Error{static{r(this,"MachineRevokedError")}constructor(n){super(ee(n)),this.name="MachineRevokedError"}}async function te(e,n,t){const i=y(),c=`${e.replace(/\/$/,"")}/token`,u=new URLSearchParams({grant_type:"client_credentials",client_id:i.client_id,client_assertion_type:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer",client_assertion:Z(i,c),...n===void 0?{}:{audience:n},...t===void 0?{}:{sub:t}}),o=await b("directory_token",c,{method:"POST",body:u,signal:AbortSignal.timeout(1e4)});if(!o.ok)throw o.status===401&&k()&&await ne(o)?new x(e):S("directory_token",c,`directory token request failed: ${o.status}`);const a=await E("directory_token",c,o);if(typeof a.access_token!="string")throw new TypeError("directory token response has no access_token");return{access_token:a.access_token,expires_at:re(a.access_token,a.expires_in)}}r(te,"mintDirectoryToken");async function ne(e){try{return(await e.json()).error==="invalid_client"}catch{return!1}}r(ne,"isInvalidClient");function re(e,n){if(typeof n=="number"&&Number.isFinite(n)&&n>0)return Date.now()+n*1e3;try{const t=JSON.parse(Buffer.from(e.split(".")[1]??"","base64url").toString("utf8"));if(typeof t.exp=="number")return t.exp*1e3}catch{}return Date.now()+3e5}r(re,"tokenExpiry");function oe(e,n){if(!e||typeof e!="object")throw new TypeError("invalid grant sync response");const t=e,i=n.runtime.startsWith("runtime:")?n.runtime:`runtime:${n.runtime}`;if(!(t.runtime===i||k()&&typeof t.runtime=="string"&&t.runtime.startsWith("runtime:")&&t.grantee!=="app:terminal")||typeof t.id!="string"||typeof t.sub!="string"||typeof t.grantee!="string"||!Number.isInteger(t.rev)||!Array.isArray(t.scopes)||!Array.isArray(t.resolved_scopes)||!["active","revoked","removed"].includes(t.status??"")||typeof t.synced_at!="string")throw new TypeError("invalid grant sync response");const o=e.revisions?.find(d=>d.rev===t.rev)?.approved_at;if(typeof o!="string")throw new TypeError("grant revision has no approval time");const a=D(t.payer,t.sub,t.grantee);return{...t,spend_cap:t.spend_cap??null,expires_at:t.expires_at??null,grantee_prefix:typeof t.grantee_prefix=="string"?t.grantee_prefix:null,revoked_at:t.revoked_at??null,approved_at:o,payer:a,dependencies:U(t.dependencies),inference_endpoint:B({payer:a})?C(t.inference_endpoint):null,run_notice_url:typeof t.run_notice_url=="string"&&t.run_notice_url!==""?t.run_notice_url:null}}r(oe,"responseGrant");async function ie(){try{return{id:V(),late:null}}catch(n){if(n instanceof z)return null;if(!(n instanceof K))throw n}const e=await Y();return e===null?null:{id:e.id,late:e}}r(ie,"pullPerson");async function se(e){X(e.id),await H(e.id);const n=await Q();await v(async t=>await G(t)),f({level:"info",event:"daemon.person.resolved",fields:{person_id:e.id,source:e.source}}),f({level:"info",event:"daemon.person.retired",fields:{person_id:n.person,retired:n.retired,columns:n.columns}})}r(se,"bindLatePerson");let _;function Se(e){return _?_(e):Promise.resolve()}r(Se,"requestGrantSync");function xe(e,n=t=>{}){let t;const i=e.replace(/\/$/,""),c=r(async()=>{const d=y(),p=await te(i),m=await b("grant_sync",`${i}/v1/runtime/grants`,{headers:{Authorization:`Bearer ${p.access_token}`},signal:AbortSignal.timeout(1e4)});if(!m.ok)throw S("grant_sync",`${i}/v1/runtime/grants`,`directory grant sync failed: ${m.status}`);const s=await E("grant_sync",`${i}/v1/runtime/grants`,m);if(!Array.isArray(s.grants)||typeof s.synced_at!="string")throw new TypeError("invalid grant sync response");const g="hosted_endpoint"in s||"payment_setup_url"in s?{hosted_endpoint:W(s.hosted_endpoint??null),payment_setup_url:q(s.payment_setup_url??null),synced_at:s.synced_at}:void 0,P=s.synced_at,h=s.grants.map(l=>oe(l,d)),w=await v(async()=>{await F(h,P,i,I(s.teams));const l=await ie();return g&&l&&await L(g,l.id),l});f({level:"info",event:"daemon.grants.synced",fields:{grants:h.length,synced_at:s.synced_at}}),w?.late&&await se(w.late);try{await M(n)}catch(l){f({level:"error",event:"daemon.grants.on_sync_failed",error:l})}},"run");let u;const o=r(()=>{const d=c().catch(p=>{throw p instanceof x?f({level:"error",event:"daemon.grants.machine_revoked",error:p}):f({level:"error",event:"daemon.grants.sync_failed",error:p,fields:J(p)}),p}).finally(()=>{t===d&&(t=void 0)});return t=d,d},"start"),a=r((d={})=>t?d.fresh?(u??=t.catch(()=>{}).then(()=>(u=void 0,t??o())),u):t:o(),"sync");return _=a,a}r(xe,"createGrantSync");export{be as GRANT_SYNC_INTERVAL_S,x as MachineRevokedError,Z as assertion,xe as createGrantSync,ee as machineRevokedMessage,te as mintDirectoryToken,Se as requestGrantSync,y as runtimeClient,Ee as runtimeId};
1
+ var j=Object.defineProperty;var r=(e,n)=>j(e,"name",{value:n,configurable:!0});import{createPrivateKey as O,randomUUID as $,sign as A}from"node:crypto";import{readFileSync as T}from"node:fs";import{join as N}from"node:path";import{crtrHome as R}from"../canvas/paths.js";import{withCanvasWrite as v}from"../canvas/db.js";import{reconcilePackages as G}from"../graph/package-reconcile.js";import{isUnsandboxedMachine as k}from"../runtime/unsandboxed.js";import{emitEvent as f}from"../events/emit.js";import{describeOutboundFailure as J,outboundFetch as b,outboundJson as E,outboundRefusal as S}from"../events/outbound.js";import{dependenciesOf as U,endpointPays as B,inferenceEndpointOf as C,principalPayer as D,replaceGrants as F,teamsOf as M}from"./mirror.js";import{loadPersonSettings as W}from"../scoped-state/person-rows.js";import{onGrantSync as q}from"./on-sync.js";import{hostedEndpointOf as I,paymentSetupUrlOf as L,storeHostedEndpoint as H}from"./hosted-endpoint.js";import{PersonOutsideRequestError as z,PersonUnresolvedError as K,personId as V,resolvePerson as Y,retireLocalPerson as Q,setPersonId as X}from"../canvas/person.js";const be=300;function Z(e,n){const t=Math.floor(Date.now()/1e3),i=Buffer.from(JSON.stringify({alg:"ES256",typ:"JWT",kid:e.kid})).toString("base64url"),c=Buffer.from(JSON.stringify({iss:e.client_id,sub:e.client_id,aud:n,iat:t,exp:t+300,jti:$()})).toString("base64url"),u=`${i}.${c}`,o=A("sha256",Buffer.from(u),{key:O({key:e.jwk,format:"jwk"}),dsaEncoding:"ieee-p1363"});return`${u}.${o.toString("base64url")}`}r(Z,"assertion");function y(){const e=JSON.parse(T(N(R(),"secrets","runtime-client.json"),"utf8"));if(!e.jwk||e.alg!=="ES256"||!e.kid||!e.client_id||!e.runtime||e.jwk.kid!==e.kid||e.jwk.kty!=="EC"||e.jwk.crv!=="P-256"||!e.jwk.d)throw new TypeError("invalid runtime client key");return e}r(y,"runtimeClient");function Ee(e=y()){return e.runtime.startsWith("runtime:")?e.runtime.slice(8):e.runtime}r(Ee,"runtimeId");function ee(e){return"This machine was removed from your Northlight account. To use it again, run `crtr sys signin`."}r(ee,"machineRevokedMessage");class x extends Error{static{r(this,"MachineRevokedError")}constructor(n){super(ee(n)),this.name="MachineRevokedError"}}async function te(e,n,t){const i=y(),c=`${e.replace(/\/$/,"")}/token`,u=new URLSearchParams({grant_type:"client_credentials",client_id:i.client_id,client_assertion_type:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer",client_assertion:Z(i,c),...n===void 0?{}:{audience:n},...t===void 0?{}:{sub:t}}),o=await b("directory_token",c,{method:"POST",body:u,signal:AbortSignal.timeout(1e4)});if(!o.ok)throw o.status===401&&k()&&await ne(o)?new x(e):S("directory_token",c,`directory token request failed: ${o.status}`);const a=await E("directory_token",c,o);if(typeof a.access_token!="string")throw new TypeError("directory token response has no access_token");return{access_token:a.access_token,expires_at:re(a.access_token,a.expires_in)}}r(te,"mintDirectoryToken");async function ne(e){try{return(await e.json()).error==="invalid_client"}catch{return!1}}r(ne,"isInvalidClient");function re(e,n){if(typeof n=="number"&&Number.isFinite(n)&&n>0)return Date.now()+n*1e3;try{const t=JSON.parse(Buffer.from(e.split(".")[1]??"","base64url").toString("utf8"));if(typeof t.exp=="number")return t.exp*1e3}catch{}return Date.now()+3e5}r(re,"tokenExpiry");function oe(e,n){if(!e||typeof e!="object")throw new TypeError("invalid grant sync response");const t=e,i=n.runtime.startsWith("runtime:")?n.runtime:`runtime:${n.runtime}`;if(!(t.runtime===i||k()&&typeof t.runtime=="string"&&t.runtime.startsWith("runtime:")&&t.grantee!=="app:terminal")||typeof t.id!="string"||typeof t.sub!="string"||typeof t.grantee!="string"||!Number.isInteger(t.rev)||!Array.isArray(t.scopes)||!Array.isArray(t.resolved_scopes)||!["active","revoked","removed"].includes(t.status??"")||typeof t.synced_at!="string")throw new TypeError("invalid grant sync response");const o=e.revisions?.find(d=>d.rev===t.rev)?.approved_at;if(typeof o!="string")throw new TypeError("grant revision has no approval time");const a=D(t.payer,t.sub,t.grantee);return{...t,spend_cap:t.spend_cap??null,expires_at:t.expires_at??null,grantee_prefix:typeof t.grantee_prefix=="string"?t.grantee_prefix:null,revoked_at:t.revoked_at??null,approved_at:o,payer:a,dependencies:U(t.dependencies),inference_endpoint:B({payer:a})?C(t.inference_endpoint):null,run_notice_url:typeof t.run_notice_url=="string"&&t.run_notice_url!==""?t.run_notice_url:null}}r(oe,"responseGrant");async function ie(){try{return{id:V(),late:null}}catch(n){if(n instanceof z)return null;if(!(n instanceof K))throw n}const e=await Y();return e===null?null:{id:e.id,late:e}}r(ie,"pullPerson");async function se(e){X(e.id),await W(e.id);const n=await Q();await v(async t=>await G(t)),f({level:"info",event:"daemon.person.resolved",fields:{person_id:e.id,source:e.source}}),f({level:"info",event:"daemon.person.retired",fields:{person_id:n.person,retired:n.retired,columns:n.columns}})}r(se,"bindLatePerson");let _;function Se(e){return _?_(e):Promise.resolve()}r(Se,"requestGrantSync");function xe(e,n=t=>{}){let t;const i=e.replace(/\/$/,""),c=r(async()=>{const d=y(),p=await te(i),m=await b("grant_sync",`${i}/v1/runtime/grants`,{headers:{Authorization:`Bearer ${p.access_token}`},signal:AbortSignal.timeout(1e4)});if(!m.ok)throw S("grant_sync",`${i}/v1/runtime/grants`,`directory grant sync failed: ${m.status}`);const s=await E("grant_sync",`${i}/v1/runtime/grants`,m);if(!Array.isArray(s.grants)||typeof s.synced_at!="string")throw new TypeError("invalid grant sync response");const g="hosted_endpoint"in s||"payment_setup_url"in s?{hosted_endpoint:I(s.hosted_endpoint??null),payment_setup_url:L(s.payment_setup_url??null),synced_at:s.synced_at}:void 0,P=s.synced_at,h=s.grants.map(l=>oe(l,d)),w=await v(async()=>{await F(h,P,i,M(s.teams));const l=await ie();return g&&l&&await H(g,l.id),l});f({level:"info",event:"daemon.grants.synced",fields:{grants:h.length,synced_at:s.synced_at}}),w?.late&&await se(w.late);try{await q(n)}catch(l){f({level:"error",event:"daemon.grants.on_sync_failed",error:l})}},"run");let u;const o=r(()=>{const d=c().catch(p=>{throw p instanceof x?f({level:"error",event:"daemon.grants.machine_revoked",error:p}):f({level:"error",event:"daemon.grants.sync_failed",error:p,fields:J(p)}),p}).finally(()=>{t===d&&(t=void 0)});return t=d,d},"start"),a=r((d={})=>t?d.fresh?(u??=t.catch(()=>{}).then(()=>(u=void 0,t??o())),u):t:o(),"sync");return _=a,a}r(xe,"createGrantSync");export{be as GRANT_SYNC_INTERVAL_S,x as MachineRevokedError,Z as assertion,xe as createGrantSync,ee as machineRevokedMessage,te as mintDirectoryToken,Se as requestGrantSync,y as runtimeClient,Ee as runtimeId};
@@ -186,8 +186,8 @@ export declare const chartDataRowsSchema: z.ZodArray<z.ZodRecord<z.ZodString, z.
186
186
  export declare const chartConfigSchema: z.ZodObject<{
187
187
  kind: z.ZodEnum<{
188
188
  line: "line";
189
- area: "area";
190
189
  bar: "bar";
190
+ area: "area";
191
191
  }>;
192
192
  x: z.ZodString;
193
193
  y: z.ZodArray<z.ZodObject<{