@north-light/cli 0.3.730 → 0.3.732

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 (68) hide show
  1. package/dist/api/client.d.ts +3 -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/errors.d.ts +5 -0
  6. package/dist/api/errors.js +1 -1
  7. package/dist/builtin-memory/northlight-apps/get-started.md +4 -4
  8. package/dist/clients/attach/overlays/graph.d.ts +2 -0
  9. package/dist/clients/attach/overlays/graph.js +1 -1
  10. package/dist/clients/attach/viewer.js +500 -500
  11. package/dist/commands/sys/daemon.js +1 -1
  12. package/dist/commands/sys/import/move.d.ts +2 -0
  13. package/dist/commands/sys/import/move.js +9 -7
  14. package/dist/commands/sys/join.js +1 -1
  15. package/dist/commands/sys/signin.js +2 -2
  16. package/dist/core/canvas/canvas.d.ts +1 -1
  17. package/dist/core/canvas/canvas.js +16 -16
  18. package/dist/core/canvas/history.d.ts +1 -1
  19. package/dist/core/canvas/history.js +8 -8
  20. package/dist/core/canvas/tree.d.ts +4 -0
  21. package/dist/core/canvas/tree.js +6 -6
  22. package/dist/core/conversation-store/row-store.js +13 -13
  23. package/dist/core/directory/join.d.ts +6 -26
  24. package/dist/core/directory/join.js +1 -1
  25. package/dist/core/environment-starter-script.d.ts +1 -1
  26. package/dist/core/environment-starter-script.js +4 -1
  27. package/dist/core/grants/sync.js +1 -1
  28. package/dist/core/model-auth/activations.js +1 -1
  29. package/dist/core/providers/call.js +1 -1
  30. package/dist/core/runtime/runner/blaxel/image-build.d.ts +3 -0
  31. package/dist/core/runtime/runner/blaxel/image-build.js +6 -6
  32. package/dist/core/storage/client.js +2 -2
  33. package/dist/daemon/api/bridge.js +2 -2
  34. package/dist/daemon/api/handlers/canvas.js +5 -5
  35. package/dist/daemon/api/handlers/shares.js +1 -1
  36. package/dist/daemon/crtrd.js +8 -8
  37. package/dist/daemon/manage.d.ts +2 -7
  38. package/dist/daemon/manage.js +3 -3
  39. package/dist/pi-extensions/canvas-inbox-watcher.js +2 -2
  40. package/docs/apps/get-started.md +4 -4
  41. package/docs/cli/join-northlight.md +16 -22
  42. package/package.json +3 -3
  43. package/packages/crouter-api/dist/api/client.js +4 -3
  44. package/packages/crouter-api/dist/api/contract.js +1 -1
  45. package/packages/crouter-api/dist/api/errors.js +11 -0
  46. package/packages/crouter-api/dist/clients/attach/overlays/graph.js +18 -1
  47. package/packages/crouter-api/dist/commands/sys/daemon.js +1 -3
  48. package/packages/crouter-api/dist/commands/sys/import/move.js +12 -0
  49. package/packages/crouter-api/dist/commands/sys/join.js +5 -37
  50. package/packages/crouter-api/dist/commands/sys/signin.js +6 -4
  51. package/packages/crouter-api/dist/core/canvas/canvas.js +7 -3
  52. package/packages/crouter-api/dist/core/canvas/history.js +3 -3
  53. package/packages/crouter-api/dist/core/canvas/tree.js +20 -0
  54. package/packages/crouter-api/dist/core/conversation-store/row-store.js +7 -2
  55. package/packages/crouter-api/dist/core/directory/join.js +35 -86
  56. package/packages/crouter-api/dist/core/environment-starter-script.js +4 -1
  57. package/packages/crouter-api/dist/core/grants/sync.js +1 -1
  58. package/packages/crouter-api/dist/core/providers/call.js +1 -1
  59. package/packages/crouter-api/dist/core/runtime/runner/blaxel/image-build.js +4 -1
  60. package/packages/crouter-api/dist/core/storage/client.js +1 -1
  61. package/packages/crouter-api/dist/daemon/manage.js +2 -16
  62. package/packages/crouter-api/package.json +1 -1
  63. package/packages/crouter-identity/package.json +1 -1
  64. package/packages/crouter-plugin/package.json +3 -3
  65. package/runtime.lock.json +14 -14
  66. package/dist/core/directory/join-lock.d.ts +0 -13
  67. package/dist/core/directory/join-lock.js +0 -1
  68. package/packages/crouter-api/dist/core/directory/join-lock.js +0 -61
@@ -1 +1 @@
1
- var f=Object.defineProperty;var o=(n,t)=>f(n,"name",{value:t,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{localClient as w}from"../../api/node-transport.js";import{defineSysBranch as x}from"./branch.js";import{selectedGeneration as I}from"./shared.js";const D=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."},{kind:"flag",name:"force",type:"bool",required:!1,default:!1,constraint:"Start even while `crtr sys join` holds the daemon down. Joining then fails `daemon_running`; use only to clear a join that is stuck."}],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:["Refuses `join_in_progress` while a live `crtr sys join` holds the daemon down, unless `--force`. `sys daemon restart` and `ensureDaemon` stand down the same way.","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",ignoreJoinLock:n.force===!0})}catch(t){throw t instanceof b?new d({error:"daemon_not_prepared",message:t.message,next:"Stop the live daemon, then start a new one with `crtr sys daemon start --prepare` before setup."}):t}},"run")}),S=100;async function E(n,t){const e=Date.now(),r=e+t;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()-e};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(S,Math.max(0,r-Date.now()))))}throw new d({error:"await_timeout",message:`daemon did not reach ${n} within ${t}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 t=n.timeout,e=y(t);if(e===null||e<=0)throw new d({error:"invalid_duration",message:`not a positive duration: ${t}`,received:t,field:"timeout",next:"Use a positive duration such as 90s, 5m, or 1h30m."});return E(n.phase,e)},"run")}),P=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 w({autostart:!1}).admitDaemon(),"run")});async function A(){try{return(await w({autostart:!1}).status()).generation_id??void 0}catch{return}}o(A,"servingGenerationId");const j=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 t=h();if(!(t!==null&&m(t)))return{running:!1};try{const r=await l(),s=await A(),i=I().generation?.id;return{running:!0,serving:r.ok,pid:t,...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:t,probe_error:v(r)}}},"run")}),M=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 t=T({local:!0});if(!k()){const e=await p();return{restarted:!1,started:e.started,...e.pid!==void 0?{pid:e.pid}:{},...e.existing_pid!==void 0?{pid:e.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 e=h();e!==null&&await c(e);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 e=await t.restartDaemon();return{restarted:e.accepted,pid:e.predecessor_pid,grace_ms:e.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(e){throw new d({error:"daemon_restart_failed",message:`the daemon did not accept a handover: ${e.message}`,next:"Run `crtr sys daemon status` to inspect the daemon."})}},"run")}),U=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 t=h(),e=t!==null&&m(t);try{let r=!1;e&&(r=await c(t)==="killed");const s=_(null);return!e&&s.length===0?{stopped:!1}:{stopped:!0,...e?{pid:t}:{},...s.length>0?{strays_killed:s}:{},...r?{force_killed:!0}:{}}}catch(r){throw new d({error:"daemon_stop_failed",message:`failed to stop daemon${e?` pid ${t}`:""}: ${r.message}`,next:"Run `crtr sys daemon status` to inspect the daemon before retrying."})}},"run")}),L=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:[D,R,P,M,j,U]});function J(){return x([L])}o(J,"registerDaemonControlSys");export{L as daemonBranch,J as registerDaemonControlSys};
1
+ var f=Object.defineProperty;var o=(a,t)=>f(a,"name",{value:t,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{localClient as w}from"../../api/node-transport.js";import{defineSysBranch as x}from"./branch.js";import{selectedGeneration as I}from"./shared.js";const D=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 a=>{try{return await p({targetPhase:a.prepare===!0?"prepared":"ready"})}catch(t){throw t instanceof b?new d({error:"daemon_not_prepared",message:t.message,next:"Stop the live daemon, then start a new one with `crtr sys daemon start --prepare` before setup."}):t}},"run")}),S=100;async function E(a,t){const e=Date.now(),n=e+t;let s="initializing",i="the daemon socket was not reachable";for(;Date.now()<n;){try{const r=await l(Math.min(1e3,Math.max(1,n-Date.now())));if(s=r.startup_phase,i=r.startup_blocked??`daemon is ${r.startup_phase}`,r.startup_phase==="blocked")throw new d({error:"startup_blocked",message:r.startup_blocked??"daemon startup is blocked",received:r.startup_phase,field:"phase",next:"Repair the reported blocker paths with `crtr sys migrate`, then retry the await."});if(r.startup_phase===a)return{startup_phase:a,waited_ms:Date.now()-e};if(a==="prepared"&&r.startup_phase==="ready")throw new d({error:"await_missed_phase",message:"daemon is already ready and cannot return to prepared in this process",received:r.startup_phase,field:"phase",next:"Start a new daemon with `crtr sys daemon start --prepare` before awaiting prepared."})}catch(r){if(r instanceof d)throw r;i=r instanceof Error?r.message:String(r)}await new Promise(r=>setTimeout(r,Math.min(S,Math.max(0,n-Date.now()))))}throw new d({error:"await_timeout",message:`daemon did not reach ${a} within ${t}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 P=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 a=>{const t=a.timeout,e=y(t);if(e===null||e<=0)throw new d({error:"invalid_duration",message:`not a positive duration: ${t}`,received:t,field:"timeout",next:"Use a positive duration such as 90s, 5m, or 1h30m."});return E(a.phase,e)},"run")}),R=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 a=>await w({autostart:!1}).admitDaemon(),"run")});async function A(){try{return(await w({autostart:!1}).status()).generation_id??void 0}catch{return}}o(A,"servingGenerationId");const M=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 a=>{const t=h();if(!(t!==null&&m(t)))return{running:!1};try{const n=await l(),s=await A(),i=I().generation?.id;return{running:!0,serving:n.ok,pid:t,...n.startup_phase===void 0?{}:{startup_phase:n.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(n){return{running:!0,serving:!1,pid:t,probe_error:v(n)}}},"run")}),U=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 a=>{const t=T({local:!0});if(!k()){const e=await p();return{restarted:!1,started:e.started,...e.pid!==void 0?{pid:e.pid}:{},...e.existing_pid!==void 0?{pid:e.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 e=h();e!==null&&await c(e);const n=await p(),s=n.pid??n.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 e=await t.restartDaemon();return{restarted:e.accepted,pid:e.predecessor_pid,grace_ms:e.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(e){throw new d({error:"daemon_restart_failed",message:`the daemon did not accept a handover: ${e.message}`,next:"Run `crtr sys daemon status` to inspect the daemon."})}},"run")}),K=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 a=>{const t=h(),e=t!==null&&m(t);try{let n=!1;e&&(n=await c(t)==="killed");const s=_(null);return!e&&s.length===0?{stopped:!1}:{stopped:!0,...e?{pid:t}:{},...s.length>0?{strays_killed:s}:{},...n?{force_killed:!0}:{}}}catch(n){throw new d({error:"daemon_stop_failed",message:`failed to stop daemon${e?` pid ${t}`:""}: ${n.message}`,next:"Run `crtr sys daemon status` to inspect the daemon before retrying."})}},"run")}),L=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:[D,P,R,U,M,K]});function Y(){return x([L])}o(Y,"registerDaemonControlSys");export{L as daemonBranch,Y as registerDaemonControlSys};
@@ -26,6 +26,8 @@ export declare function exportRun(kind: 'machine' | 'hosted', cloud: ImportCloud
26
26
  * link is up), then the machine credential (re-minted with `rotate` when an earlier attempt already minted one), `machine.json`, a restart of
27
27
  * crtrd in machine role, and the move record's deletion. Safe to repeat. */
28
28
  export declare function finishMove(move: MoveRecord): Promise<void>;
29
+ /** Register this computer as a directory runtime under the person's sign-in, unless it already is one. Runs before the machine-role daemon starts, so it finds the key. A refusal is printed, not thrown, so the move still finishes against a directory that does not accept it yet. */
30
+ export declare function registerThisMac(directoryUrl: string): Promise<void>;
29
31
  /** Move this computer into the signed-in person's account. Before the cloud run reaches `done`, any failure undoes the move: the drain ends, the
30
32
  * sign-in is revoked and deleted, the move record goes, and `notify` (a node) is told through the local daemon. After `done` the move record says
31
33
  * `committed` and activation is retried three times over a minute; still failing, the record, the sign-in and the drain stay for `crtr sys signin`. */
@@ -1,8 +1,10 @@
1
- var W=Object.defineProperty;var d=(e,t)=>W(e,"name",{value:t,configurable:!0});import{mkdtempSync as X,readFileSync as L,readdirSync as A,rmSync as Q}from"node:fs";import{tmpdir as Z}from"node:os";import{join as g}from"node:path";import{CrtrError as s,general as tt}from"../../../core/errors.js";import{ExitCode as h}from"../../../types.js";import{cliClient as R}from"../../api-client.js";import{ImportCloud as T,STORE_FILE as et,STORE_ORDER as rt}from"../../../core/import/export/cloud.js";import{Uploader as nt,localObjects as F,reviewSourceObject as ot}from"../../../core/import/export/files.js";import{BODIES_TABLE as P,bundleKeys as x}from"../../../core/import/bundle/layout.js";import{crtrVersion as it}from"../../../shared/crtr-version.js";import{nodeArchive as at}from"../../../core/import/export/archive.js";import{buildSourceJson as st}from"../../../core/import/export/source.js";import{runDaemonBodiesDump as ct,runDaemonImportDump as dt,runDaemonInstallId as lt,spawnDaemon as ut,stopAllDaemons as ft}from"../../../daemon/manage.js";import{deleteMoveRecord as U,moveUnfinishedError as mt,readMachineConfig as wt,readMoveRecord as D,writeMachineConfig as pt,writeMachineCredential as ht,writeMoveRecord as M}from"../../../daemon/machine-link/config.js";import{notifyMoveFinished as gt}from"../../../daemon/machine-link/move-notify.js";import{controlPlaneUrl as _t,forgetSignIn as yt,personAccount as B,personBearer as b,readPersonCredential as Et,signIn as $t,signOut as vt}from"../../../core/directory/person-credential.js";import{NORTHLIGHT_DIRECTORY_URL as St}from"../../../core/directory/issuer.js";import{isPidAlive as j}from"../../../core/canvas/pid.js";const _=d(e=>new Promise(t=>setTimeout(t,e)),"sleep");function Qt(){return wt()?.directoryUrl??Et()?.directoryUrl??St}d(Qt,"defaultDirectoryUrl");async function J(e){let t="the daemon still reports a drain";for(let r=1;r<=3;r++){try{if((await e.endDaemonDrain()).drained===!1)return}catch(n){t=n instanceof Error?n.message:String(n)}r<3&&await _(1e3)}throw new s("drain_not_ended",`the local daemon's pause could not be confirmed ended: ${t}`,h.GENERAL,{next:"Run `crtr sys import resume`."})}d(J,"endDrainConfirmed");async function Ut(e,t){e||await J(t)}d(Ut,"settleDrainAtEnd");const It=3e4;async function Nt(e,t,r){let n=2e3;for(;;){let i;try{i=await e.get(t)}catch(c){const l=c instanceof s?c.details?.status:void 0;if(c instanceof s&&(c.code==="not_signed_in"||typeof l=="number"&&l<500&&l!==408&&l!==429))throw new s("move_outcome_unknown",`could not confirm whether Northlight finished loading this computer's records: ${c.message}`,h.GENERAL,{next:"Run `crtr sys signin` to settle the move."});process.stderr.write(`waiting for Northlight: ${c instanceof Error?c.message:String(c)}
2
- `),await _(n),n=Math.min(n*2,It);continue}if(n=2e3,i.state==="done")return;if(i.state==="failed"||i.state==="rolled_back")throw tt(`the import failed at ${i.failure?.step??i.step??"an unknown step"}: ${i.failure?.message??i.state}`,{code:i.failure?.code??"import_failed"});if(i.state==="uploading"&&r!==void 0)throw r;await _(2e3)}}d(Nt,"awaitRunOutcome");async function At(e,t,r,n,i=()=>{},c=()=>{}){let l=Date.now();const o=d((f,m)=>{const p=Date.now(),S=`${f}=${((p-l)/1e3).toFixed(1)}s`;n.timings.push(S),process.stderr.write(`${f} ${((p-l)/1e3).toFixed(1)}s
3
- `),l=p,n.name=m},"next"),u=X(g(Z(),"crtr-import-")),v=R({local:!0});let y=!1,I=!1,E=!1,$;try{n.name="start";const{installId:f}=await lt(),m=r===void 0?await t.start({source_install_id:f,source_kind:e,release:it()}):{run_id:r};i(m.run_id),n.name="blobs";const p=new nt(t,m.run_id,a=>process.stderr.write(`${a}
4
- `));await p.upload(F()),await ct(u);const S=new Set,O=d(async(a,w)=>{await p.uploadBytes(x.rowPart(m.run_id,a,w.replace(/\.jsonl\.zst$/,"")),L(g(u,"rows",a,w))),S.add(`${a}/${w}`)},"uploadPart");for(const a of A(g(u,"rows",P)))await O(P,a);o("blobs","drain"),y=!0,await v.drainDaemon({settle_limit_ms:6e5}),o("drain","dump"),await p.upload(F());const N=await dt(u,e),k=[];for(const a of N.requests){const w=ot(a.id,a.dir,a.file);w!==null&&k.push(w)}await p.upload(k),o("dump","upload");for(const a of A(g(u,"rows")))for(const w of A(g(u,"rows",a)))S.has(`${a}/${w}`)||await O(a,w);const C=[];if(e==="hosted")for(const a of N.runningNodes){const{data:w,prefixes:K}=await at(a);C.push(...K),await p.uploadBytes(x.nodeFiles(m.run_id,a.node),w)}await p.uploadBytes(x.source(m.run_id),Buffer.from(JSON.stringify(st(N.source,C))));const z=JSON.parse(L(g(u,et),"utf8"));for(const a of rt)await t.putStore(m.run_id,a,z[a]);o("upload","load"),E=!0;let G;try{await t.load(m.run_id)}catch(a){G=a}try{await Nt(t,m.run_id,G)}catch(a){throw a instanceof s&&a.code==="move_outcome_unknown"||(E=!1),a}return E=!1,I=!0,o("load","restart"),m.run_id}catch(f){throw $=f,f}finally{if(Q(u,{recursive:!0,force:!0}),!I&&!E&&c(),y&&!E)try{await Ut(I,v)}catch(f){if($===void 0)throw f;const m=f instanceof s?f.code:"drain_not_ended";throw new s(m,`${$ instanceof Error?$.message:String($)} (and ${f instanceof Error?f.message:String(f)})`,h.GENERAL,{next:"Run `crtr sys import resume`."})}}}d(At,"exportRun");async function Rt(e){await gt(e);const t=new T(e.apiUrl,()=>b(e.directoryUrl));let r;try{r=await t.machineCredential(e.runId)}catch(n){if(!(n instanceof s)||n.details?.code!=="credential_exists")throw n;r=await t.machineCredential(e.runId,!0)}ht(r.credential),pt({apiUrl:e.apiUrl,environmentId:r.environment_id,runId:e.runId,directoryUrl:e.directoryUrl,account:e.account}),await ft(),await ut(),U()}d(Rt,"finishMove");const V=3,Tt=3e4;async function Zt(e){const t={name:"sign-in",timings:[]};let r,n="",i;try{const o=await B(e.directoryUrl),u=e.apiUrl??await _t(e.directoryUrl),v=new T(u,()=>b(e.directoryUrl));i={apiUrl:u,directoryUrl:e.directoryUrl,account:o,notify:e.notify,notified:!1,pid:process.pid},await At("machine",v,void 0,t,y=>{n=y,M({...i,runId:y,state:"running"})},U)}catch(o){throw o instanceof s&&o.code==="move_outcome_unknown"?o:await H(t.name,o,e.notify)}r={...i,runId:n,state:"committed"},M(r);let c;const l=Date.now();for(let o=1;o<=V;o++)try{return await Rt(r),t.timings.push(`restart=${((Date.now()-l)/1e3).toFixed(1)}s`),process.stderr.write(`restart ${((Date.now()-l)/1e3).toFixed(1)}s
1
+ var W=Object.defineProperty;var d=(e,t)=>W(e,"name",{value:t,configurable:!0});import{mkdtempSync as X,readFileSync as L,readdirSync as T,rmSync as Q}from"node:fs";import{tmpdir as Z}from"node:os";import{join as g}from"node:path";import{CrtrError as s,general as tt}from"../../../core/errors.js";import{ExitCode as h}from"../../../types.js";import{cliClient as x}from"../../api-client.js";import{ImportCloud as A,STORE_FILE as et,STORE_ORDER as rt}from"../../../core/import/export/cloud.js";import{Uploader as nt,localObjects as F,reviewSourceObject as ot}from"../../../core/import/export/files.js";import{BODIES_TABLE as P,bundleKeys as M}from"../../../core/import/bundle/layout.js";import{crtrVersion as it}from"../../../shared/crtr-version.js";import{nodeArchive as at}from"../../../core/import/export/archive.js";import{buildSourceJson as st}from"../../../core/import/export/source.js";import{runDaemonBodiesDump as ct,runDaemonImportDump as dt,runDaemonInstallId as lt,spawnDaemon as ut,stopAllDaemons as ft}from"../../../daemon/manage.js";import{deleteMoveRecord as U,moveUnfinishedError as mt,readMachineConfig as wt,readMoveRecord as D,writeMachineConfig as pt,writeMachineCredential as ht,writeMoveRecord as b}from"../../../daemon/machine-link/config.js";import{notifyMoveFinished as gt}from"../../../daemon/machine-link/move-notify.js";import{registerSignedInMac as yt}from"../../../core/directory/join.js";import{controlPlaneUrl as _t,forgetSignIn as Et,personAccount as B,personBearer as I,readPersonCredential as $t,signIn as St,signOut as vt}from"../../../core/directory/person-credential.js";import{NORTHLIGHT_DIRECTORY_URL as Ut}from"../../../core/directory/issuer.js";import{isPidAlive as j}from"../../../core/canvas/pid.js";const y=d(e=>new Promise(t=>setTimeout(t,e)),"sleep");function ee(){return wt()?.directoryUrl??$t()?.directoryUrl??Ut}d(ee,"defaultDirectoryUrl");async function J(e){let t="the daemon still reports a drain";for(let r=1;r<=3;r++){try{if((await e.endDaemonDrain()).drained===!1)return}catch(n){t=n instanceof Error?n.message:String(n)}r<3&&await y(1e3)}throw new s("drain_not_ended",`the local daemon's pause could not be confirmed ended: ${t}`,h.GENERAL,{next:"Run `crtr sys import resume`."})}d(J,"endDrainConfirmed");async function It(e,t){e||await J(t)}d(It,"settleDrainAtEnd");const Nt=3e4;async function Rt(e,t,r){let n=2e3;for(;;){let i;try{i=await e.get(t)}catch(c){const l=c instanceof s?c.details?.status:void 0;if(c instanceof s&&(c.code==="not_signed_in"||typeof l=="number"&&l<500&&l!==408&&l!==429))throw new s("move_outcome_unknown",`could not confirm whether Northlight finished loading this computer's records: ${c.message}`,h.GENERAL,{next:"Run `crtr sys signin` to settle the move."});process.stderr.write(`waiting for Northlight: ${c instanceof Error?c.message:String(c)}
2
+ `),await y(n),n=Math.min(n*2,Nt);continue}if(n=2e3,i.state==="done")return;if(i.state==="failed"||i.state==="rolled_back")throw tt(`the import failed at ${i.failure?.step??i.step??"an unknown step"}: ${i.failure?.message??i.state}`,{code:i.failure?.code??"import_failed"});if(i.state==="uploading"&&r!==void 0)throw r;await y(2e3)}}d(Rt,"awaitRunOutcome");async function Tt(e,t,r,n,i=()=>{},c=()=>{}){let l=Date.now();const o=d((f,m)=>{const p=Date.now(),v=`${f}=${((p-l)/1e3).toFixed(1)}s`;n.timings.push(v),process.stderr.write(`${f} ${((p-l)/1e3).toFixed(1)}s
3
+ `),l=p,n.name=m},"next"),u=X(g(Z(),"crtr-import-")),S=x({local:!0});let _=!1,N=!1,E=!1,$;try{n.name="start";const{installId:f}=await lt(),m=r===void 0?await t.start({source_install_id:f,source_kind:e,release:it()}):{run_id:r};i(m.run_id),n.name="blobs";const p=new nt(t,m.run_id,a=>process.stderr.write(`${a}
4
+ `));await p.upload(F()),await ct(u);const v=new Set,O=d(async(a,w)=>{await p.uploadBytes(M.rowPart(m.run_id,a,w.replace(/\.jsonl\.zst$/,"")),L(g(u,"rows",a,w))),v.add(`${a}/${w}`)},"uploadPart");for(const a of T(g(u,"rows",P)))await O(P,a);o("blobs","drain"),_=!0,await S.drainDaemon({settle_limit_ms:6e5}),o("drain","dump"),await p.upload(F());const R=await dt(u,e),k=[];for(const a of R.requests){const w=ot(a.id,a.dir,a.file);w!==null&&k.push(w)}await p.upload(k),o("dump","upload");for(const a of T(g(u,"rows")))for(const w of T(g(u,"rows",a)))v.has(`${a}/${w}`)||await O(a,w);const C=[];if(e==="hosted")for(const a of R.runningNodes){const{data:w,prefixes:K}=await at(a);C.push(...K),await p.uploadBytes(M.nodeFiles(m.run_id,a.node),w)}await p.uploadBytes(M.source(m.run_id),Buffer.from(JSON.stringify(st(R.source,C))));const z=JSON.parse(L(g(u,et),"utf8"));for(const a of rt)await t.putStore(m.run_id,a,z[a]);o("upload","load"),E=!0;let G;try{await t.load(m.run_id)}catch(a){G=a}try{await Rt(t,m.run_id,G)}catch(a){throw a instanceof s&&a.code==="move_outcome_unknown"||(E=!1),a}return E=!1,N=!0,o("load","restart"),m.run_id}catch(f){throw $=f,f}finally{if(Q(u,{recursive:!0,force:!0}),!N&&!E&&c(),_&&!E)try{await It(N,S)}catch(f){if($===void 0)throw f;const m=f instanceof s?f.code:"drain_not_ended";throw new s(m,`${$ instanceof Error?$.message:String($)} (and ${f instanceof Error?f.message:String(f)})`,h.GENERAL,{next:"Run `crtr sys import resume`."})}}}d(Tt,"exportRun");async function xt(e){await gt(e);const t=new A(e.apiUrl,()=>I(e.directoryUrl));let r;try{r=await t.machineCredential(e.runId)}catch(n){if(!(n instanceof s)||n.details?.code!=="credential_exists")throw n;r=await t.machineCredential(e.runId,!0)}ht(r.credential),pt({apiUrl:e.apiUrl,environmentId:r.environment_id,runId:e.runId,directoryUrl:e.directoryUrl,account:e.account}),await At(e.directoryUrl),await ft(),await ut(),U()}d(xt,"finishMove");async function At(e){try{await yt(e,await I(e))}catch(t){process.stderr.write(`this computer was not registered with the directory: ${t instanceof Error?t.message:String(t)}
5
+ Run \`crtr sys signin\` again to register it.
6
+ `)}}d(At,"registerThisMac");const V=3,Mt=3e4;async function re(e){const t={name:"sign-in",timings:[]};let r,n="",i;try{const o=await B(e.directoryUrl),u=e.apiUrl??await _t(e.directoryUrl),S=new A(u,()=>I(e.directoryUrl));i={apiUrl:u,directoryUrl:e.directoryUrl,account:o,notify:e.notify,notified:!1,pid:process.pid},await Tt("machine",S,void 0,t,_=>{n=_,b({...i,runId:_,state:"running"})},U)}catch(o){throw o instanceof s&&o.code==="move_outcome_unknown"?o:await H(t.name,o,e.notify)}r={...i,runId:n,state:"committed"},b(r);let c;const l=Date.now();for(let o=1;o<=V;o++)try{return await xt(r),t.timings.push(`restart=${((Date.now()-l)/1e3).toFixed(1)}s`),process.stderr.write(`restart ${((Date.now()-l)/1e3).toFixed(1)}s
5
7
  `),{runId:r.runId,account:r.account.display,timings:t.timings.join(" ")}}catch(u){c=u,process.stderr.write(`switch-over attempt ${o} failed: ${u instanceof Error?u.message:String(u)}
6
- `),o<V&&await _(Tt),r=D()??r}throw mt(c instanceof Error?c.message:String(c))}d(Zt,"runMove");async function H(e,t,r){const n=t instanceof Error?t.message:String(t),i=t instanceof s&&t.code==="drain_not_ended"?"crtr is still local, but its pause could not be ended: run `crtr sys import resume`":"crtr is still local and working as before",c=`The move to Northlight failed at ${e}: ${n}. ${i}.`,l=await q(c,r),o=t instanceof s&&t.code!=="error"?t.code:t instanceof s&&typeof t.details?.code=="string"?t.details.code:"move_failed";return new s(o,`the move to Northlight failed at ${e}: ${n}. ${i}, and ${Y(l)}`,h.GENERAL)}d(H,"undoMove");const Y=d(e=>e===void 0?"this computer is signed out.":`this computer's sign-in was removed here but could not be revoked at Northlight (${e}); revoke it on your Northlight account page.`,"signedOutText");async function q(e,t){U();let r;try{await vt()}catch(n){yt(),r=n instanceof Error?n.message:String(n),process.stderr.write(`could not revoke the sign-in at Northlight: ${r}
7
- `)}if(t===null)return r;try{await R({local:!0}).sendMessage(t,{from:null,body:`${e} Tell the person the move failed.${r===void 0?"":` ${Y(r)}`}`})}catch(n){process.stderr.write(`could not message ${t}: ${n instanceof Error?n.message:String(n)}
8
- `)}return r}d(q,"dropMove");async function xt(e){const t=D();if(t===void 0||t.state==="activated")return;const r=d(async()=>{await $t(t.directoryUrl,e,{accept:d(async o=>o.account.id===t.account.id?void 0:new s("signin_other_account",`This computer's move belongs to the Northlight account ${t.account.display}. Sign in to that account.`,h.USAGE),"accept")})},"signBackIn");if(t.state==="committed"){if(e!==void 0)try{await B(t.directoryUrl)}catch(o){if(!(o instanceof s&&o.code==="not_signed_in"))throw o;await r()}return t}if(t.pid>0&&j(t.pid))throw new s("move_running",`a move to Northlight is already running (process ${t.pid}).`,h.USAGE,{next:"Wait for it to finish; the node that asked is messaged when it does."});const n=d(()=>new T(t.apiUrl,()=>b(t.directoryUrl)).get(t.runId),"ask");let i;try{i=await n()}catch(o){if(!(o instanceof s&&o.code==="not_signed_in")||e===void 0)throw o;await r(),i=await n()}if(i.state==="done"){const o={...t,state:"committed"};return M(o),o}if(i.state==="loading"||i.state==="committed")throw new s("move_running","Northlight is still loading this computer's records from an earlier move.",h.USAGE,{next:"Retry in a minute."});if(i.state!=="failed"&&i.state!=="rolled_back"&&i.state!=="uploading")throw new s("move_outcome_unknown","Northlight did not report a settled outcome for this move.",h.GENERAL,{next:"Run `crtr sys signin` to settle the move."});const c=i.failure?.step??"an earlier step",l=i.failure==null?"the process that was moving this computer stopped before Northlight had the records":i.failure.message;U();try{await J(R({local:!0}))}catch(o){throw await H(c,new s("drain_not_ended",`${l} (and ${o instanceof Error?o.message:String(o)})`,h.GENERAL),t.notify)}await q(`The move to Northlight failed at ${c}: ${l}. crtr is still local and working as before.`,t.notify)}d(xt,"settleEarlierMove");const Dt=6e4,Mt=5e3;async function te(e,t){for(await _(Mt);!e();){const r=D();if(r===void 0||r.state!=="running"||r.pid>0&&j(r.pid))return;try{await xt();return}catch(n){if(t(n),n instanceof s&&n.code==="not_signed_in")return}await _(Dt)}}d(te,"settleMoveAtDaemonStart");export{Qt as defaultDirectoryUrl,J as endDrainConfirmed,At as exportRun,Rt as finishMove,Zt as runMove,Ut as settleDrainAtEnd,xt as settleEarlierMove,te as settleMoveAtDaemonStart};
8
+ `),o<V&&await y(Mt),r=D()??r}throw mt(c instanceof Error?c.message:String(c))}d(re,"runMove");async function H(e,t,r){const n=t instanceof Error?t.message:String(t),i=t instanceof s&&t.code==="drain_not_ended"?"crtr is still local, but its pause could not be ended: run `crtr sys import resume`":"crtr is still local and working as before",c=`The move to Northlight failed at ${e}: ${n}. ${i}.`,l=await q(c,r),o=t instanceof s&&t.code!=="error"?t.code:t instanceof s&&typeof t.details?.code=="string"?t.details.code:"move_failed";return new s(o,`the move to Northlight failed at ${e}: ${n}. ${i}, and ${Y(l)}`,h.GENERAL)}d(H,"undoMove");const Y=d(e=>e===void 0?"this computer is signed out.":`this computer's sign-in was removed here but could not be revoked at Northlight (${e}); revoke it on your Northlight account page.`,"signedOutText");async function q(e,t){U();let r;try{await vt()}catch(n){Et(),r=n instanceof Error?n.message:String(n),process.stderr.write(`could not revoke the sign-in at Northlight: ${r}
9
+ `)}if(t===null)return r;try{await x({local:!0}).sendMessage(t,{from:null,body:`${e} Tell the person the move failed.${r===void 0?"":` ${Y(r)}`}`})}catch(n){process.stderr.write(`could not message ${t}: ${n instanceof Error?n.message:String(n)}
10
+ `)}return r}d(q,"dropMove");async function Dt(e){const t=D();if(t===void 0||t.state==="activated")return;const r=d(async()=>{await St(t.directoryUrl,e,{accept:d(async o=>o.account.id===t.account.id?void 0:new s("signin_other_account",`This computer's move belongs to the Northlight account ${t.account.display}. Sign in to that account.`,h.USAGE),"accept")})},"signBackIn");if(t.state==="committed"){if(e!==void 0)try{await B(t.directoryUrl)}catch(o){if(!(o instanceof s&&o.code==="not_signed_in"))throw o;await r()}return t}if(t.pid>0&&j(t.pid))throw new s("move_running",`a move to Northlight is already running (process ${t.pid}).`,h.USAGE,{next:"Wait for it to finish; the node that asked is messaged when it does."});const n=d(()=>new A(t.apiUrl,()=>I(t.directoryUrl)).get(t.runId),"ask");let i;try{i=await n()}catch(o){if(!(o instanceof s&&o.code==="not_signed_in")||e===void 0)throw o;await r(),i=await n()}if(i.state==="done"){const o={...t,state:"committed"};return b(o),o}if(i.state==="loading"||i.state==="committed")throw new s("move_running","Northlight is still loading this computer's records from an earlier move.",h.USAGE,{next:"Retry in a minute."});if(i.state!=="failed"&&i.state!=="rolled_back"&&i.state!=="uploading")throw new s("move_outcome_unknown","Northlight did not report a settled outcome for this move.",h.GENERAL,{next:"Run `crtr sys signin` to settle the move."});const c=i.failure?.step??"an earlier step",l=i.failure==null?"the process that was moving this computer stopped before Northlight had the records":i.failure.message;U();try{await J(x({local:!0}))}catch(o){throw await H(c,new s("drain_not_ended",`${l} (and ${o instanceof Error?o.message:String(o)})`,h.GENERAL),t.notify)}await q(`The move to Northlight failed at ${c}: ${l}. crtr is still local and working as before.`,t.notify)}d(Dt,"settleEarlierMove");const bt=6e4,Ot=5e3;async function ne(e,t){for(await y(Ot);!e();){const r=D();if(r===void 0||r.state!=="running"||r.pid>0&&j(r.pid))return;try{await Dt();return}catch(n){if(t(n),n instanceof s&&n.code==="not_signed_in")return}await y(bt)}}d(ne,"settleMoveAtDaemonStart");export{ee as defaultDirectoryUrl,J as endDrainConfirmed,Tt as exportRun,xt as finishMove,At as registerThisMac,re as runMove,It as settleDrainAtEnd,Dt as settleEarlierMove,ne as settleMoveAtDaemonStart};
@@ -1 +1 @@
1
- var a=Object.defineProperty;var n=(e,r)=>a(e,"name",{value:r,configurable:!0});import{defineLeaf as o}from"../../core/command.js";import{existsSync as s}from"node:fs";import{join as d}from"node:path";import{pluginsDir as l}from"../../core/scope.js";import{joinDirectory as c}from"../../core/directory/join.js";import{apiSocketPath as u}from"../../core/canvas/paths.js";import{listProcessTable as h}from"../../core/canvas/pid.js";import{daemonAnswers as m}from"../../core/layout-migrate/index.js";import{envNodeId as p}from"../../shared/env.js";import{isDaemonRunning as f}from"../../daemon/pidfile.js";import{findDaemonPids as w,spawnDaemon as y,stopAllDaemons as g}from"../../daemon/manage.js";function k(){const e=h();if(e===null||(p()??"")!=="")return!0;const r=new Map(e.map(t=>[t.pid,t])),i=new Set;for(let t=process.ppid;t>1&&!i.has(t);t=r.get(t)?.ppid??0)if(i.add(t),r.get(t)?.command.includes("broker-cli"))return!0;return!1}n(k,"insideBroker");function b(){if(!(process.platform==="linux"&&(process.env.CRTR_LAUNCHER_SOCKET||s("/run/crtr/launcher.sock"))))return{running:n(async()=>f()||w().length>0||await m(u()),"running"),stop:n(async()=>{await g()},"stop"),start:n(async()=>{await y()},"start"),firstSync:n(async()=>{const e=l("user"),r=Date.now()+2e4;for(;e&&Date.now()<r&&!s(d(e,"cloud","commands.json"));)await new Promise(i=>setTimeout(i,250))},"firstSync"),insideNode:k}}n(b,"daemonControl");const P=o({name:"join",description:"register this runtime with its directory using an enrollment token, offline",whenToUse:"on your own computer, with a token from `<issuer>/account/machines`: run it from a plain terminal, with any viewers open. It stops the daemon, joins, and starts it again. Also at a hosted runtime's first boot, before the daemon starts, with the enrollment token provisioning passed in.",help:{name:"sys join",summary:"exchange a directory enrollment token for a new runtime client key and record the returned identity",guide:"Generates a new ES256 client key, sends only its public key to `PUT <directory>/v1/runtimes/registration` with the token as bearer, and learns the runtime id, client id, issuer, owner and URL from the answer. Only after that answer does it write the key file. It writes no settings and touches no canvas.db: the daemon's next start replaces this install's person with the owner everywhere in canvas.db, sets the user settings `runtime.issuer` and `runtime.audience` from the key file, and rewrites the legacy local person's profile grantees to `app:terminal`, all before it serves anything. On your own computer a running daemon is no obstacle: join takes a `join.lock` in the runtime directory (so no open viewer's redial can autostart a daemon while it works), registers with the directory while the daemon still serves, stops the daemon, writes the identity, and starts the daemon again, whose start applies the change. Run it from a plain terminal, not from inside a node: a node's broker dies with the daemon, so join refuses `join_inside_node` instead. Where the launcher owns the daemon (a hosted container) join keeps the offline contract and refuses `daemon_running`. Presenting the token of the stored successful registration again finishes those local writes without calling the directory. Any other token generates a new key and registers again.",params:[{kind:"flag",name:"directory",type:"string",required:!0,constraint:"Directory base URL (http or https) that minted the token."},{kind:"flag",name:"token",type:"string",required:!0,sensitive:!0,constraint:"Single-use enrollment token. Sensitive: never echoed in output or errors."},{kind:"flag",name:"name",type:"string",required:!1,constraint:"Label shown for this machine on the account page. Default: this computer's hostname."}],output:[{name:"runtime",type:"string",required:!0,constraint:"Runtime principal from the directory, `runtime:<id>`."},{name:"client_id",type:"string",required:!0,constraint:"OAuth client id registered for the new key."},{name:"issuer",type:"string",required:!0,constraint:"Canonical issuer, written to `runtime.issuer`."},{name:"owner",type:"string",required:!0,constraint:"Owner principal, `user:<id>`, that replaces this install's own person at the next daemon start."},{name:"canvas_rewrite",type:"string",required:!0,constraint:"Always `next daemon start`: when canvas.db identity fields are rewritten."},{name:"url",type:"string",required:!0,constraint:"Runtime URL, written to `runtime.audience`."},{name:"registered",type:"boolean",required:!0,constraint:"False when the token matched the stored registration and the directory was not called."},{name:"daemon",type:"string",required:!0,constraint:"`restarted` (a daemon was stopped and started on the joined settings), `started` (none was running; join started one and waited, up to 20s, for its first grant sync to install the account's provider plugins, so `crtr cloud \u2026` resolves), `not_running` (none was started: a hosted container's launcher owns its daemon), or `restart_failed` (joined, but the new daemon did not start: see `daemon_error`, then run `crtr sys daemon start`)."},{name:"daemon_error",type:"string",required:!1,constraint:"Why the new daemon did not start, with `daemon: restart_failed`."}],outputKind:"object",effects:["Holds `<runtime>/join.lock` (its pid) from the start until the daemon is back; `ensureDaemon` and `sys daemon start` (without `--force`) decline to start a daemon while a live process holds it (including a start already in flight when the join began). A lock whose holder died is reclaimed.","A running daemon is stopped (SIGTERM, then SIGKILL, plus strays) after the directory accepts the registration and before the local writes, then started again. Every broker dies with it and is revived by the new daemon. If the join fails after the stop, the daemon is started again anyway. With no daemon running join starts one anyway, because a bare `crtr cloud \u2026` is an unknown command (it never autostarts a daemon) until a daemon's grant sync has installed the provider plugins. Refuses `join_inside_node` when run from inside a node and a daemon is running; refuses `daemon_running` where a container launcher owns the daemon.","On a new token: calls the directory once; on success writes `<runtime>/secrets/runtime-client.json` (mode 0600) with the private key, registration and the token's SHA-256, replacing any earlier key file. A refused or failed call writes nothing.","Sends name, platform, crtr version, installed plugin ids and sandbox state with the public key. Before the request it writes `runtime-client.pending.json` (mode 0600); a rerun with the same token and directory reuses that key, so a lost reply is retried safely. The file is deleted on success or a refusal.","Sets `runtime.issuer` and `runtime.audience` in user settings. When the directory says this machine is not the account's default (`is_default: false`) it replaces the whole `runtime` setting with `{issuer, audience, unsandboxed: true}`: no app listener, and only `app:terminal` nodes run.","Rewrites the legacy local person's profile grantees to `app:terminal`.","At the next daemon start, before any listener, the person this install minted (or still the legacy local person) is replaced by the owner in every canvas.db column that holds a person: node, token, grant, cron, audit and usage subjects and grantees, the person's identity, and queued cron births. References to the install's local terminal grant are cleared and that local grant mirror is deleted so grant sync installs the directory's. Free text is unchanged. The start after that changes nothing."]},run:n(async e=>({...await c(e.directory,e.token,e.name||void 0,b()),canvas_rewrite:"next daemon start"}),"run")});export{k as insideBroker,P as sysJoinLeaf};
1
+ var s=Object.defineProperty;var r=(t,n)=>s(t,"name",{value:n,configurable:!0});import{defineLeaf as a}from"../../core/command.js";import{joinDirectory as o}from"../../core/directory/join.js";import{listProcessTable as d}from"../../core/canvas/pid.js";import{envNodeId as u}from"../../shared/env.js";function y(){const t=d();if(t===null||(u()??"")!=="")return!0;const n=new Map(t.map(e=>[e.pid,e])),i=new Set;for(let e=process.ppid;e>1&&!i.has(e);e=n.get(e)?.ppid??0)if(i.add(e),n.get(e)?.command.includes("broker-cli"))return!0;return!1}r(y,"insideBroker");const f=a({name:"join",description:"register a hosted runtime with its directory using the provisioning enrollment token, before its daemon starts",whenToUse:"only at a hosted runtime's first boot, before the daemon starts, with the enrollment token provisioning passed in. A person's own computer registers through `crtr sys signin`.",help:{name:"sys join",summary:"exchange a directory enrollment token for a new runtime client key and record the returned identity",guide:"Generates a new ES256 client key, sends only its public key to `PUT <directory>/v1/runtimes/registration` with the token as bearer, and learns the runtime id, client id, issuer, owner and URL from the answer. Only after that answer does it write the key file. It writes no settings and touches no canvas.db: the daemon's next start replaces this install's person with the owner everywhere in canvas.db and sets `runtime.issuer` and `runtime.audience` from the key file. It never touches a daemon: while one answers it refuses `daemon_running`. Presenting the token of the stored successful registration again finishes without calling the directory. Any other token generates a new key and registers again.",params:[{kind:"flag",name:"directory",type:"string",required:!0,constraint:"Directory base URL (http or https) that minted the token."},{kind:"flag",name:"token",type:"string",required:!0,sensitive:!0,constraint:"Single-use enrollment token. Sensitive: never echoed in output or errors."},{kind:"flag",name:"name",type:"string",required:!1,constraint:"Label shown for this machine on the account page. Default: this computer's hostname."}],output:[{name:"runtime",type:"string",required:!0,constraint:"Runtime principal from the directory, `runtime:<id>`."},{name:"client_id",type:"string",required:!0,constraint:"OAuth client id registered for the new key."},{name:"issuer",type:"string",required:!0,constraint:"Canonical issuer, written to `runtime.issuer`."},{name:"owner",type:"string",required:!0,constraint:"Owner principal, `user:<id>`, that replaces this install's own person at the next daemon start."},{name:"canvas_rewrite",type:"string",required:!0,constraint:"Always `next daemon start`: when canvas.db identity fields are rewritten."},{name:"url",type:"string",required:!0,constraint:"Runtime URL, written to `runtime.audience`."},{name:"registered",type:"boolean",required:!0,constraint:"False when the token matched the stored registration and the directory was not called."}],outputKind:"object",effects:["On a new token: calls the directory once; on success writes `<runtime>/secrets/runtime-client.json` (mode 0600) with the private key, registration and the token's SHA-256, replacing any earlier key file. A refused or failed call writes nothing.","Sends name, platform, crtr version, installed plugin ids and sandbox state with the public key. Before the request it writes `runtime-client.pending.json` (mode 0600); a rerun with the same token and directory reuses that key, so a lost reply is retried safely. The file is deleted on success or a refusal.","At the next daemon start, before any listener, the person this install minted is replaced by the owner in every canvas.db column that holds a person, and the legacy local person's profile grantees become `app:terminal`."]},run:r(async t=>({...await o(t.directory,t.token,t.name||void 0),canvas_rewrite:"next daemon start"}),"run")});export{y as insideBroker,f as sysJoinLeaf};
@@ -1,2 +1,2 @@
1
- var y=Object.defineProperty;var o=(e,n)=>y(e,"name",{value:n,configurable:!0});import{spawn as c}from"node:child_process";import{mkdirSync as k,openSync as _}from"node:fs";import{dirname as d,join as b}from"node:path";import{defineLeaf as h}from"../../core/command.js";import{CrtrError as u}from"../../core/errors.js";import{signIn as m,signOut as T}from"../../core/directory/person-credential.js";import{moveRecordPath as N,readMachineConfig as l}from"../../daemon/machine-link/config.js";import{sanitizedDaemonEnv as S,spawnDaemon as p,stopAllDaemons as g}from"../../daemon/manage.js";import{northlightUnreachable as U}from"../../core/directory/reach.js";import{envNodeId as A}from"../../shared/env.js";import{ExitCode as f}from"../../types.js";import{insideBroker as v}from"./join.js";import{cliClient as C}from"../api-client.js";import{defaultDirectoryUrl as $,finishMove as O,runMove as R,settleEarlierMove as I}from"./import/move.js";import{WAIT_FOR_PID_ENV as P}from"./import/start.js";function E(e){const[n,t]=process.platform==="darwin"?["open",[e]]:["xdg-open",[e]];try{c(n,t,{stdio:"ignore",detached:!0}).on("error",()=>{}).unref()}catch{}}o(E,"openBrowser");function a(e){process.stderr.write(`Confirm this code at ${e.verificationUri}: ${e.userCode}
2
- `),E(e.complete)}o(a,"showSignIn");function x(e){return async n=>{let t;try{t=await fetch(new URL(`/v1/imports/${e.runId}`,e.apiUrl),{headers:{authorization:`Bearer ${n.bearer}`},signal:AbortSignal.timeout(3e4)})}catch(r){return U(r,e.apiUrl)}if(!t.ok)return t.status===404?new u("signin_other_account",`This computer's crtr belongs to the Northlight account ${e.account?.display??"it was moved into"}. Sign in to that account.`,f.USAGE):new u("signin_unchecked",`the control plane did not say which account owns this computer (HTTP ${t.status}); nothing was written.`,f.GENERAL,{next:"Retry `crtr sys signin`."})}}o(x,"sameAccountOnly");function w(e){const n=b(d(N()),"move.log");k(d(n),{recursive:!0});const t=_(n,"a",384),r=S();for(const s of["CRTR_API_SOCKET","CRTR_API_TOKEN","CRTR_API_URL"])delete r[s];r[P]=String(process.pid);const i=[...process.execArgv,process.argv[1],"sys","import","start","--kind","machine",...e===void 0?[]:["--notify",e]];c(process.execPath,i,{detached:!0,stdio:["ignore",t,t],env:r}).unref()}o(w,"startDetachedMove");const D=o(e=>`Signed in as ${e}. crtr is now moving this computer's records to Northlight; every agent here pauses for seconds to minutes. End your turn now; this conversation carries on when the move finishes.`,"MOVING"),ee=h({name:"signin",description:"sign this computer's crtr in to the person's Northlight account",whenToUse:"the person agreed to sign in to Northlight (a Northlight command needs the account, or they asked), or a command answered `not_signed_in` or `move_unfinished`",help:{name:"sys signin",summary:"pair this computer with the person's Northlight account in the browser, then move this computer's records into it",guide:"Prints a code and opens the directory's confirm page; the person signs in or signs up there if asked, checks the code and clicks Allow. The command waits for that. On a computer whose records are still local it then moves them into the account: run from a terminal it prints each step and returns when done; run from inside a node it returns at once and the node is messaged when the move finishes or fails. A computer already moved accepts only the account it moved into. For an unfinished move (`move_unfinished`), it checks the account's move result and finishes the switch-over if the records arrived. If the stored sign-in is missing or revoked, it first pairs only the account recorded for that move. Until the result is known, agents remain paused. The sign-in ends after 90 days without use, when revoked on the account page, or with `crtr sys signout`.",params:[{kind:"flag",name:"directory-url",type:"string",required:!1,constraint:"Directory base URL (http or https). Default: the one in `runtime/machine.json`, else the stored sign-in's, else Northlight's."}],output:[{name:"account",type:"string",required:!0,constraint:"The account this computer is now signed in as."},{name:"moved",type:"boolean",required:!1,constraint:"Present when this command moved the records, or finished an earlier move's switch-over."},{name:"moving",type:"boolean",required:!1,constraint:"Present when the move runs on in its own process (run from inside a node): end the turn; the node is messaged when it finishes or fails."}],outputKind:"object",effects:["Calls the directory (`POST /v1/developer/logins`, then polls `/v1/developer/logins/poll`) and, once approved, writes `runtime/secrets/person-credential` (0600) and replaces the cached bearer. A declined, abandoned or refused sign-in writes nothing and leaves an existing sign-in as it was.","On a computer whose records are local: the move of `crtr sys import start --kind machine` (drains the daemon, uploads, restarts it in machine role); a move confirmed failed before the account holds the records ends the drain and signs this computer out again. If the account's result is unknown, the move record and drain remain for recovery. From inside a node it runs as a detached process logging to `runtime/import/move.log`.","On a moved computer: restarts the daemon so it reconnects to Northlight."]},run:o(async e=>{const n=e.directoryUrl===void 0?$():String(e.directoryUrl),t=await I(a);if(t!==void 0)return v()?(w(void 0),{account:t.account.display,moving:!0}):(await O(t),{account:t.account.display,moved:!0});const r=l();if(r!==void 0){const{account:s}=await m(n,a,{accept:x(r)});return await g(),await p(),{account:s}}const{account:i}=await m(n,a);return v()?(w(A()),{account:i,moving:!0}):(await R({directoryUrl:n,notify:null}),{account:i,moved:!0})},"run"),render:o(e=>e.moving===!0?`<signin account="${e.account}" moving="true">${D(String(e.account))}</signin>`:`<signin account="${e.account}"${e.moved===!0?' moved="true"':""}/>`,"render")});async function q(){return await g(),await p(),(await C({local:!0}).healthz()).signed_in===!1}o(q,"stopMovedComputer");const te=h({name:"signout",description:"sign this computer's crtr out, revoke its credential, and stop its agents",whenToUse:"this computer should stop acting as the person on Northlight, or its stored sign-in may have leaked",help:{name:"sys signout",summary:"revoke the stored credential, delete it from this computer, and on a moved computer stop every agent and cron here",params:[],output:[{name:"signed_out",type:"boolean",required:!0,constraint:"False when no sign-in was stored."},{name:"revoked",type:"boolean",required:!0,constraint:"True when the directory ended the credential now; false when it was already ended or none was stored."},{name:"stopped",type:"boolean",required:!0,constraint:"True when this computer's records are in Northlight and its agents and running crons have stopped; false on a computer whose records are local, where nothing else is tied to the sign-in."}],outputKind:"object",effects:["Calls `POST /v1/developer/token/revoke` with the stored secret, then deletes `runtime/secrets/person-credential` and `person-bearer.json`. A bearer already issued stays valid for at most 5 minutes.","On a computer whose records are in Northlight: restarts the daemon, which stops every agent and running cron here and takes no new work until `crtr sys signin`; agents keep their mail on Northlight and wake after it. Commands answer `not_signed_in`."]},run:o(async()=>{const{signedOut:e,revoked:n}=await T(),t=l()===void 0?!1:await q();return{signed_out:e,revoked:n,stopped:t}},"run"),render:o(e=>`<signout signed_out="${e.signed_out}" revoked="${e.revoked}" stopped="${e.stopped}"/>`,"render")});export{a as showSignIn,ee as sysSigninLeaf,te as sysSignoutLeaf};
1
+ var y=Object.defineProperty;var r=(e,n)=>y(e,"name",{value:n,configurable:!0});import{spawn as c}from"node:child_process";import{mkdirSync as k,openSync as _}from"node:fs";import{dirname as d,join as b}from"node:path";import{defineLeaf as h}from"../../core/command.js";import{CrtrError as u}from"../../core/errors.js";import{signIn as m,signOut as T}from"../../core/directory/person-credential.js";import{moveRecordPath as N,readMachineConfig as l}from"../../daemon/machine-link/config.js";import{sanitizedDaemonEnv as U,spawnDaemon as p,stopAllDaemons as g}from"../../daemon/manage.js";import{northlightUnreachable as S}from"../../core/directory/reach.js";import{envNodeId as A}from"../../shared/env.js";import{ExitCode as f}from"../../types.js";import{insideBroker as v}from"./join.js";import{cliClient as C}from"../api-client.js";import{defaultDirectoryUrl as O,finishMove as $,registerThisMac as P,runMove as R,settleEarlierMove as E}from"./import/move.js";import{WAIT_FOR_PID_ENV as I}from"./import/start.js";function x(e){const[n,t]=process.platform==="darwin"?["open",[e]]:["xdg-open",[e]];try{c(n,t,{stdio:"ignore",detached:!0}).on("error",()=>{}).unref()}catch{}}r(x,"openBrowser");function a(e){process.stderr.write(`Confirm this code at ${e.verificationUri}: ${e.userCode}
2
+ `),x(e.complete)}r(a,"showSignIn");function D(e){return async n=>{let t;try{t=await fetch(new URL(`/v1/imports/${e.runId}`,e.apiUrl),{headers:{authorization:`Bearer ${n.bearer}`},signal:AbortSignal.timeout(3e4)})}catch(o){return S(o,e.apiUrl)}if(!t.ok)return t.status===404?new u("signin_other_account",`This computer's crtr belongs to the Northlight account ${e.account?.display??"it was moved into"}. Sign in to that account.`,f.USAGE):new u("signin_unchecked",`the control plane did not say which account owns this computer (HTTP ${t.status}); nothing was written.`,f.GENERAL,{next:"Retry `crtr sys signin`."})}}r(D,"sameAccountOnly");function w(e){const n=b(d(N()),"move.log");k(d(n),{recursive:!0});const t=_(n,"a",384),o=U();for(const s of["CRTR_API_SOCKET","CRTR_API_TOKEN","CRTR_API_URL"])delete o[s];o[I]=String(process.pid);const i=[...process.execArgv,process.argv[1],"sys","import","start","--kind","machine",...e===void 0?[]:["--notify",e]];c(process.execPath,i,{detached:!0,stdio:["ignore",t,t],env:o}).unref()}r(w,"startDetachedMove");const M=r(e=>`Signed in as ${e}. crtr is now moving this computer's records to Northlight; every agent here pauses for seconds to minutes. End your turn now; this conversation carries on when the move finishes.`,"MOVING"),te=h({name:"signin",description:"sign this computer's crtr in to the person's Northlight account and register it as one of their machines",whenToUse:"the person agreed to sign in to Northlight (a Northlight command needs the account, or they asked), or a command answered `not_signed_in` or `move_unfinished`",help:{name:"sys signin",summary:"pair this computer with the person's Northlight account in the browser, move this computer's records into it, and register it with the directory",guide:"Prints a code and opens the directory's confirm page; the person signs in or signs up there if asked, checks the code and clicks Allow. The command waits for that. On a computer whose records are still local it then moves them into the account: run from a terminal it prints each step and returns when done; run from inside a node it returns at once and the node is messaged when the move finishes or fails. A computer already moved accepts only the account it moved into. For an unfinished move (`move_unfinished`), it checks the account's move result and finishes the switch-over if the records arrived. If the stored sign-in is missing or revoked, it first pairs only the account recorded for that move. Until the result is known, agents remain paused. Once the records are in the account the computer is also registered as one of the account's machines: a signing key is made here (the private key never leaves this computer) and only its public half goes to the directory, under the same sign-in. A computer already registered keeps its registration; one signed in earlier without it is registered by running this again. The sign-in ends after 90 days without use, when revoked on the account page, or with `crtr sys signout`.",params:[{kind:"flag",name:"directory-url",type:"string",required:!1,constraint:"Directory base URL (http or https). Default: the one in `runtime/machine.json`, else the stored sign-in's, else Northlight's."}],output:[{name:"account",type:"string",required:!0,constraint:"The account this computer is now signed in as."},{name:"moved",type:"boolean",required:!1,constraint:"Present when this command moved the records, or finished an earlier move's switch-over."},{name:"moving",type:"boolean",required:!1,constraint:"Present when the move runs on in its own process (run from inside a node): end the turn; the node is messaged when it finishes or fails."}],outputKind:"object",effects:["Calls the directory (`POST /v1/developer/logins`, then polls `/v1/developer/logins/poll`) and, once approved, writes `runtime/secrets/person-credential` (0600) and replaces the cached bearer. A declined, abandoned or refused sign-in writes nothing and leaves an existing sign-in as it was.","On a computer whose records are local: the move of `crtr sys import start --kind machine` (drains the daemon, uploads, restarts it in machine role); a move confirmed failed before the account holds the records ends the drain and signs this computer out again. If the account's result is unknown, the move record and drain remain for recovery. From inside a node it runs as a detached process logging to `runtime/import/move.log`.","On a moved computer: restarts the daemon so it reconnects to Northlight.","Unless this computer is already registered: calls `PUT <directory>/v1/runtimes/registration` with the sign-in bearer and a new public ES256 key, then writes `runtime/secrets/runtime-client.json` (0600) holding the private key and the returned runtime identity."]},run:r(async e=>{const n=e.directoryUrl===void 0?O():String(e.directoryUrl),t=await E(a);if(t!==void 0)return v()?(w(void 0),{account:t.account.display,moving:!0}):(await $(t),{account:t.account.display,moved:!0});const o=l();if(o!==void 0){const{account:s}=await m(n,a,{accept:D(o)});return await P(n),await g(),await p(),{account:s}}const{account:i}=await m(n,a);return v()?(w(A()),{account:i,moving:!0}):(await R({directoryUrl:n,notify:null}),{account:i,moved:!0})},"run"),render:r(e=>e.moving===!0?`<signin account="${e.account}" moving="true">${M(String(e.account))}</signin>`:`<signin account="${e.account}"${e.moved===!0?' moved="true"':""}/>`,"render")});async function q(){return await g(),await p(),(await C({local:!0}).healthz()).signed_in===!1}r(q,"stopMovedComputer");const ne=h({name:"signout",description:"sign this computer's crtr out, revoke its credential, and stop its agents",whenToUse:"this computer should stop acting as the person on Northlight, or its stored sign-in may have leaked",help:{name:"sys signout",summary:"revoke the stored credential, delete it from this computer, and on a moved computer stop every agent and cron here",params:[],output:[{name:"signed_out",type:"boolean",required:!0,constraint:"False when no sign-in was stored."},{name:"revoked",type:"boolean",required:!0,constraint:"True when the directory ended the credential now; false when it was already ended or none was stored."},{name:"stopped",type:"boolean",required:!0,constraint:"True when this computer's records are in Northlight and its agents and running crons have stopped; false on a computer whose records are local, where nothing else is tied to the sign-in."}],outputKind:"object",effects:["Calls `POST /v1/developer/token/revoke` with the stored secret, then deletes `runtime/secrets/person-credential` and `person-bearer.json`. A bearer already issued stays valid for at most 5 minutes.","On a computer whose records are in Northlight: restarts the daemon, which stops every agent and running cron here and takes no new work until `crtr sys signin`; agents keep their mail on Northlight and wake after it. Commands answer `not_signed_in`."]},run:r(async()=>{const{signedOut:e,revoked:n}=await T(),t=l()===void 0?!1:await q();return{signed_out:e,revoked:n,stopped:t}},"run"),render:r(e=>`<signout signed_out="${e.signed_out}" revoked="${e.revoked}" stopped="${e.stopped}"/>`,"render")});export{a as showSignIn,te as sysSigninLeaf,ne as sysSignoutLeaf};
@@ -155,7 +155,7 @@ export interface GraphNodeRow {
155
155
  /** Stored fields the attach graph displays, plus the two live execution cues it
156
156
  * needs. This keeps the interactive graph off the full node-summary projection
157
157
  * and its unused runtime, outcome, and placement fields. */
158
- export declare function graphNodes(): Promise<GraphNodeRow[]>;
158
+ export declare function graphNodes(ids?: readonly string[]): Promise<GraphNodeRow[]>;
159
159
  export interface ListNodesFilter {
160
160
  status?: NodeStatus | NodeStatus[];
161
161
  withRecordedPid?: boolean;
@@ -1,8 +1,8 @@
1
- var ce=Object.defineProperty;var i=(e,n)=>ce(e,"name",{value:n,configurable:!0});import{loadExactProfileManifest as le}from"../profiles/manifest.js";import{envNodeId as H}from"../../shared/env.js";import{lstatSync as _e,realpathSync as M,rmdirSync as pe,rmSync as fe,statSync as Ee}from"node:fs";import{basename as we,dirname as P,isAbsolute as ye,join as S,relative as me,resolve as Ne,sep as Re}from"node:path";import{removeTreeBeneath as $}from"../spaces/open-beneath.js";import{emitEvent as Se}from"../events/emit.js";import{deleteNodeSandboxes as q}from"../runtime/runner/delete-sandboxes.js";import{withCanvasWrite as p,openDb as d}from"./db.js";import{conversationStore as he,ConversationNotFoundError as Oe}from"../conversation-store/index.js";import{hasUnseenWakeMail as Le,UNSEEN_WAKE_MAIL_SQL as Te}from"./deliveries.js";import{isAppRun as B}from"./app-run.js";import{registerOutcomeAction as z}from"./outcome-actions.js";import{publish as De}from"../graph/events.js";import{nodeObject as Ae}from"../graph/objects.js";import{findNodeBySessionFileSql as ge}from"./sessions.js";import{hydrateFault as ke}from"./recovery.js";import{hasUnreconciledWorktree as ve,openWorktree as xe,readWorktree as Ue,worktreeFromRow as We}from"./worktrees.js";import{isPidAlive as be,isPidPresent as J,recordedPidLiveness as je}from"./pid.js";import{isCloudRole as Ie}from"./person-state.js";import{ensureHome as Fe,jobDir as Ce,nodeDir as He,nodeRunDir as Y}from"./paths.js";import{appForNode as Me,ensureNodeDirs as Pe,nodeAgentDir as $e}from"./node-agent-paths.js";import{appSpace as T}from"../layout.js";import{createObject as qe,getById as D,ownerForGrantee as Be,setObjectKind as ze,setObjectName as Je}from"../graph/objects.js";import{profileObject as Ye}from"../graph/reader.js";import{writeActsFor as Q}from"../permissions/facts.js";import{CrtrError as Qe}from"../errors.js";import{deleteNodeWithOwned as Ve}from"../graph/deletion.js";import{SUBTREE_ALL_IDS_SQL as Ke,SUBTREE_IDS_SQL as Ge}from"./tree.js";import{filterAsync as y,mapAsync as h}from"../async-array.js";function E(e,n){if(e==null)return null;const t=JSON.stringify(e);if(t===void 0)throw new TypeError(`${n} must be JSON-serializable`);return t}i(E,"jsonValue");async function Fn(e,n){if((await e.prepare("SELECT deleting_at FROM nodes WHERE node_id = ?").get(n))?.deleting_at)throw new Error("run is deleting")}i(Fn,"assertRunNotDeleting");async function V(e,n,t,a){try{return(le(n).manifest.grantee??"app:terminal")!==a?null:await Ye(e,n,t)}catch(r){if(r instanceof Qe&&r.code==="not_found")return null;throw r}}i(V,"profileObjectFor");async function Xe(e,n){const t=await Be(n,e.grantee??"app:terminal"),a=e.profile_id?await V(n,e.profile_id,t,e.grantee??"app:terminal"):null;await qe(n,{id:e.node_id,type:"node",kind:e.kind,owner:(a??t).id,privacy:"public",name:e.name,preview:""}),a===null&&e.sub&&await Q(n,e.node_id,e.sub),await n.prepare(`INSERT INTO nodes (node_id, description, title, icon, cycles, mode, lifecycle, cwd, host_kind, profile_id, parent, spawned_by, creator, fork_from, fork_source_file, created, passive_default, cycle_pending, model_override, persona_ack_json, review_binding_json, launch_config_json, scopes_json, isolated, status, intent, final_report, finalized_at, deadline_at, "window", tmux_session, pane, sub, grant_id, client_id, metadata_json, run_id, event_cursor, deleting_at, caused_by, app) VALUES (${Array(41).fill("?").join(", ")})`).run(e.node_id,e.description??null,e.title??null,e.icon??null,e.cycles??null,e.mode,e.lifecycle,e.cwd,e.host_kind??null,e.profile_id??null,e.parent??null,e.spawned_by??null,e.creator??null,e.fork_from??null,e.fork_source_file??null,e.created,e.passive_default===!0?1:0,e.cycle_pending===!0?1:0,e.model_override??null,E(e.persona_ack,"persona_ack"),E(e.review_binding,"review_binding"),E(e.launch,"launch"),E(e.scopes,"scopes"),e.isolated===!0?1:0,e.status??"active",e.intent??null,e.final_report??null,e.finalized_at??null,e.deadline_at??null,e.window??null,e.tmux_session??null,e.pane??null,e.sub??null,e.grant_id??null,e.client_id??null,e.metadata_json??null,e.run_id??null,e.event_cursor??null,e.deleting_at??null,e.caused_by??null,t.id)}i(Xe,"seedRow");function K(e){if(e.fault_id==null)return null;const n=Object.entries(e).filter(([t])=>t.startsWith("fault_")).map(([t,a])=>[t==="fault_id"?t:t.slice(6),a]);return ke(Object.fromEntries(n))}i(K,"faultFrom");const G=i(e=>e.turn_open_at!=null&&e.turn_closed_at==null,"turnOpen"),X=i(e=>e||Ie(),"engineLive");function f(e){const n={node_id:e.node_id,name:e.name,description:e.description??void 0,cycles:e.cycles??void 0,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind??null,profile_id:e.profile_id??null,scopes:e.scopes_json==null?null:JSON.parse(e.scopes_json),isolated:e.isolated===1,grantee:e.grantee,sub:e.sub??null,grant_id:e.grant_id??null,client_id:e.client_id??null,metadata_json:e.metadata_json??null,run_id:e.run_id??null,event_cursor:e.event_cursor??null,last_activity_at:e.last_activity_at??null,caused_by:e.caused_by??null,last_turn_error_json:e.last_turn_error_json??null,deleting_at:e.deleting_at??null,parent:e.parent??null,created:e.created,intent:e.intent??null,cycle_pending:e.cycle_pending===1,frozen_at:e.frozen_at??null,respawn_failures:e.respawn_failures??0,respawn_not_before:e.respawn_not_before??null,launched_at:e.launched_at??null,last_settled_at:e.last_settled_at??null,terminal_reason:e.terminal_reason??null,final_report:e.final_report??null,finalized_at:e.finalized_at??null,outcome_kind:e.outcome_kind??null,outcome_reason:e.outcome_reason??null,outcome_at:e.outcome_at??null,outcome_revision:e.outcome_revision??0,outcome_detail_json:e.outcome_detail_json??null,deadline_at:e.deadline_at??null,telemetry_tokens_in:e.telemetry_tokens_in??null,telemetry_context_tokens:e.telemetry_context_tokens??null,telemetry_last_activity:e.telemetry_last_activity??null,telemetry_updated_at:e.telemetry_updated_at??null,pi_pid:e.pi_pid??null,pi_pid_identity:e.pi_pid_identity??null,window:e.window??null,tmux_session:e.tmux_session??null,pane:e.pane??null,fault:null,streaming:!1},t=J(n.pi_pid),a=K(e);return n.fault=a?.link==="pi\u2192provider"&&a.retry.by==="daemon"&&a.retry.disposition==="auto"&&!t?null:a,n.streaming=G(e)&&X(t),n}i(f,"rowFrom");async function A(e,n){return n??=await Ue(e.node_id),{...f(e),title:e.title??void 0,icon:e.icon??void 0,spawned_by:e.spawned_by??null,creator:e.creator??null,fork_from:e.fork_from??null,fork_source_file:e.fork_source_file??null,passive_default:e.passive_default===1,model_override:e.model_override??null,scopes:e.scopes_json==null?null:JSON.parse(e.scopes_json),persona_ack:e.persona_ack_json==null?void 0:JSON.parse(e.persona_ack_json),review_binding:e.review_binding_json==null?void 0:JSON.parse(e.review_binding_json),launch:e.launch_config_json==null?void 0:JSON.parse(e.launch_config_json),pi_session_id:e.pi_session_id??null,pi_session_file:e.pi_session_file??null,...n===null?{}:{managed_worktree:n}}}i(A,"metaFrom");async function Cn(e,n={}){return Fe(),await p(async t=>{await Xe(e,t),e.managed_worktree!==void 0&&e.managed_worktree!==null&&await xe(e.node_id,e.managed_worktree,t),n.outcomeDelivery!==void 0&&await z(t,e.node_id,n.outcomeDelivery),await n.withinCreate?.(t,e)}),await Pe(e.node_id),await O(e.node_id)}i(Cn,"createNode");async function O(e){const n=await(await d()).prepare("SELECT * FROM node_rows WHERE node_id = ?").get(e);return n===void 0?null:await A(n)}i(O,"getNode");async function Hn(e){if(e.length===0)return[];const n=v.map(r=>`w.${r} AS worktree_${r}`).join(", "),t=await(await d()).prepareUncached(`SELECT n.*, ${n} FROM node_rows n LEFT JOIN worktrees w ON w.node_id = n.node_id WHERE n.node_id IN (${e.map(()=>"?").join(",")})`).all(...e),a=new Map(t.map(r=>[r.node_id,r]));return await h(e.map(r=>a.get(r)).filter(r=>r!==void 0),async r=>await A(r,ee(r)))}i(Hn,"getNodes");const Ze=1440*60*1e3;function Z(e){return{requestKey:e.request_key,nodeId:e.node_id,state:e.state}}i(Z,"createRequestRecord");async function Mn(e){const n=await(await d()).prepareUncached("SELECT request_key, node_id, state FROM create_requests WHERE request_key = ?").get(e);return n===void 0?null:Z(n)}i(Mn,"findCreateRequest");async function Pn(e){return await p(async n=>{const t=Date.now();await n.prepareUncached("DELETE FROM create_requests WHERE expires_at <= ?").run(t),await n.prepareUncached("INSERT INTO create_requests (request_key, node_id, expires_at, state) VALUES (?, NULL, ?, 'reserved') ON CONFLICT (request_key) DO NOTHING").run(e,t+Ze);const a=await n.prepareUncached("SELECT request_key, node_id, state FROM create_requests WHERE request_key = ?").get(e);return Z(a)})}i(Pn,"reserveCreateRequest");async function $n(e=Date.now()){return Number((await(await d()).prepareUncached("DELETE FROM create_requests WHERE expires_at <= ?").run(e)).changes)}i($n,"pruneExpiredCreateRequests");async function qn(e,n){await(await d()).prepareUncached("UPDATE create_requests SET node_id = ?, state = 'complete' WHERE request_key = ?").run(n,e)}i(qn,"recordCreateRequestNode");async function Bn(e,n,t){const a=await d();return await a.prepareUncached("UPDATE create_requests SET node_id = ?, state = 'reserved', lease_owner = ?, lease_expires_at = ? WHERE request_key = ? AND node_id IS NULL").run(n,t,Date.now()+g,e),(await a.prepareUncached("SELECT node_id FROM create_requests WHERE request_key = ?").get(e))?.node_id??null}i(Bn,"reserveCreateRequestNode");const g=3e4,zn=1e4;async function Jn(e,n,t){const a=Date.now(),r=await(await d()).prepareUncached("UPDATE create_requests SET lease_owner = ?, lease_expires_at = ? WHERE request_key = ? AND node_id = ? AND state = 'reserved' AND (lease_expires_at IS NULL OR lease_expires_at <= ?)").run(t,a+g,e,n,a);return Number(r.changes)>0}i(Jn,"claimCreateLease");async function Yn(e,n){await(await d()).prepareUncached("UPDATE create_requests SET lease_expires_at = ? WHERE request_key = ? AND lease_owner = ?").run(Date.now()+g,e,n)}i(Yn,"renewCreateLease");async function Qn(e){const n=await(await d()).prepareUncached("SELECT lease_expires_at FROM create_requests WHERE request_key = ?").get(e);return n?.lease_expires_at!=null&&Number(n.lease_expires_at)>Date.now()}i(Qn,"createLeaseLive");async function Vn(e,n){await(await d()).prepareUncached("UPDATE create_requests SET state = 'complete' WHERE request_key = ? AND node_id = ?").run(e,n)}i(Vn,"completeCreateRequest");async function Kn(e,n){await p(async t=>{if(n===null){await t.prepareUncached("DELETE FROM create_requests WHERE request_key = ? AND node_id IS NULL").run(e);return}await t.prepareUncached("DELETE FROM create_requests WHERE request_key = ? AND node_id = ?").run(e,n)})}i(Kn,"abandonCreateRequest");function Gn(e){return Ne(e)}i(Gn,"canonicalSessionFile");async function Xn(e){const n=await ge(e);return n===null?null:await O(n)}i(Xn,"findNodeBySessionFile");async function Zn(e){const n=await(await d()).prepare("SELECT * FROM node_rows WHERE node_id = ?").get(e);return n?f(n):null}i(Zn,"getRow");async function et(e){const n=await(await d()).prepare("SELECT * FROM node_rows WHERE pane = ?").get(e);return n?f(n):null}i(et,"getRowByPane");async function nt(e){return(await(await d()).prepare(`SELECT * FROM node_rows
1
+ var ce=Object.defineProperty;var r=(e,n)=>ce(e,"name",{value:n,configurable:!0});import{loadExactProfileManifest as le}from"../profiles/manifest.js";import{envNodeId as H}from"../../shared/env.js";import{lstatSync as _e,realpathSync as M,rmdirSync as pe,rmSync as fe,statSync as Ee}from"node:fs";import{basename as we,dirname as P,isAbsolute as ye,join as S,relative as me,resolve as Ne,sep as Re}from"node:path";import{removeTreeBeneath as $}from"../spaces/open-beneath.js";import{emitEvent as Se}from"../events/emit.js";import{deleteNodeSandboxes as q}from"../runtime/runner/delete-sandboxes.js";import{withCanvasWrite as p,openDb as d}from"./db.js";import{conversationStore as he,ConversationNotFoundError as Oe}from"../conversation-store/index.js";import{hasUnseenWakeMail as Le,UNSEEN_WAKE_MAIL_SQL as Te}from"./deliveries.js";import{isAppRun as B}from"./app-run.js";import{registerOutcomeAction as z}from"./outcome-actions.js";import{publish as De}from"../graph/events.js";import{nodeObject as Ae}from"../graph/objects.js";import{findNodeBySessionFileSql as ge}from"./sessions.js";import{hydrateFault as ke}from"./recovery.js";import{hasUnreconciledWorktree as ve,openWorktree as xe,readWorktree as Ue,worktreeFromRow as We}from"./worktrees.js";import{isPidAlive as be,isPidPresent as J,recordedPidLiveness as je}from"./pid.js";import{isCloudRole as Ie}from"./person-state.js";import{ensureHome as Fe,jobDir as Ce,nodeDir as He,nodeRunDir as Y}from"./paths.js";import{appForNode as Me,ensureNodeDirs as Pe,nodeAgentDir as $e}from"./node-agent-paths.js";import{appSpace as T}from"../layout.js";import{createObject as qe,getById as D,ownerForGrantee as Be,setObjectKind as ze,setObjectName as Je}from"../graph/objects.js";import{profileObject as Ye}from"../graph/reader.js";import{writeActsFor as Q}from"../permissions/facts.js";import{CrtrError as Qe}from"../errors.js";import{deleteNodeWithOwned as Ve}from"../graph/deletion.js";import{SUBTREE_ALL_IDS_SQL as Ke,SUBTREE_IDS_SQL as Ge}from"./tree.js";import{filterAsync as y,mapAsync as h}from"../async-array.js";function E(e,n){if(e==null)return null;const t=JSON.stringify(e);if(t===void 0)throw new TypeError(`${n} must be JSON-serializable`);return t}r(E,"jsonValue");async function Fn(e,n){if((await e.prepare("SELECT deleting_at FROM nodes WHERE node_id = ?").get(n))?.deleting_at)throw new Error("run is deleting")}r(Fn,"assertRunNotDeleting");async function V(e,n,t,a){try{return(le(n).manifest.grantee??"app:terminal")!==a?null:await Ye(e,n,t)}catch(i){if(i instanceof Qe&&i.code==="not_found")return null;throw i}}r(V,"profileObjectFor");async function Xe(e,n){const t=await Be(n,e.grantee??"app:terminal"),a=e.profile_id?await V(n,e.profile_id,t,e.grantee??"app:terminal"):null;await qe(n,{id:e.node_id,type:"node",kind:e.kind,owner:(a??t).id,privacy:"public",name:e.name,preview:""}),a===null&&e.sub&&await Q(n,e.node_id,e.sub),await n.prepare(`INSERT INTO nodes (node_id, description, title, icon, cycles, mode, lifecycle, cwd, host_kind, profile_id, parent, spawned_by, creator, fork_from, fork_source_file, created, passive_default, cycle_pending, model_override, persona_ack_json, review_binding_json, launch_config_json, scopes_json, isolated, status, intent, final_report, finalized_at, deadline_at, "window", tmux_session, pane, sub, grant_id, client_id, metadata_json, run_id, event_cursor, deleting_at, caused_by, app) VALUES (${Array(41).fill("?").join(", ")})`).run(e.node_id,e.description??null,e.title??null,e.icon??null,e.cycles??null,e.mode,e.lifecycle,e.cwd,e.host_kind??null,e.profile_id??null,e.parent??null,e.spawned_by??null,e.creator??null,e.fork_from??null,e.fork_source_file??null,e.created,e.passive_default===!0?1:0,e.cycle_pending===!0?1:0,e.model_override??null,E(e.persona_ack,"persona_ack"),E(e.review_binding,"review_binding"),E(e.launch,"launch"),E(e.scopes,"scopes"),e.isolated===!0?1:0,e.status??"active",e.intent??null,e.final_report??null,e.finalized_at??null,e.deadline_at??null,e.window??null,e.tmux_session??null,e.pane??null,e.sub??null,e.grant_id??null,e.client_id??null,e.metadata_json??null,e.run_id??null,e.event_cursor??null,e.deleting_at??null,e.caused_by??null,t.id)}r(Xe,"seedRow");function K(e){if(e.fault_id==null)return null;const n=Object.entries(e).filter(([t])=>t.startsWith("fault_")).map(([t,a])=>[t==="fault_id"?t:t.slice(6),a]);return ke(Object.fromEntries(n))}r(K,"faultFrom");const G=r(e=>e.turn_open_at!=null&&e.turn_closed_at==null,"turnOpen"),X=r(e=>e||Ie(),"engineLive");function f(e){const n={node_id:e.node_id,name:e.name,description:e.description??void 0,cycles:e.cycles??void 0,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind??null,profile_id:e.profile_id??null,scopes:e.scopes_json==null?null:JSON.parse(e.scopes_json),isolated:e.isolated===1,grantee:e.grantee,sub:e.sub??null,grant_id:e.grant_id??null,client_id:e.client_id??null,metadata_json:e.metadata_json??null,run_id:e.run_id??null,event_cursor:e.event_cursor??null,last_activity_at:e.last_activity_at??null,caused_by:e.caused_by??null,last_turn_error_json:e.last_turn_error_json??null,deleting_at:e.deleting_at??null,parent:e.parent??null,created:e.created,intent:e.intent??null,cycle_pending:e.cycle_pending===1,frozen_at:e.frozen_at??null,respawn_failures:e.respawn_failures??0,respawn_not_before:e.respawn_not_before??null,launched_at:e.launched_at??null,last_settled_at:e.last_settled_at??null,terminal_reason:e.terminal_reason??null,final_report:e.final_report??null,finalized_at:e.finalized_at??null,outcome_kind:e.outcome_kind??null,outcome_reason:e.outcome_reason??null,outcome_at:e.outcome_at??null,outcome_revision:e.outcome_revision??0,outcome_detail_json:e.outcome_detail_json??null,deadline_at:e.deadline_at??null,telemetry_tokens_in:e.telemetry_tokens_in??null,telemetry_context_tokens:e.telemetry_context_tokens??null,telemetry_last_activity:e.telemetry_last_activity??null,telemetry_updated_at:e.telemetry_updated_at??null,pi_pid:e.pi_pid??null,pi_pid_identity:e.pi_pid_identity??null,window:e.window??null,tmux_session:e.tmux_session??null,pane:e.pane??null,fault:null,streaming:!1},t=J(n.pi_pid),a=K(e);return n.fault=a?.link==="pi\u2192provider"&&a.retry.by==="daemon"&&a.retry.disposition==="auto"&&!t?null:a,n.streaming=G(e)&&X(t),n}r(f,"rowFrom");async function A(e,n){return n??=await Ue(e.node_id),{...f(e),title:e.title??void 0,icon:e.icon??void 0,spawned_by:e.spawned_by??null,creator:e.creator??null,fork_from:e.fork_from??null,fork_source_file:e.fork_source_file??null,passive_default:e.passive_default===1,model_override:e.model_override??null,scopes:e.scopes_json==null?null:JSON.parse(e.scopes_json),persona_ack:e.persona_ack_json==null?void 0:JSON.parse(e.persona_ack_json),review_binding:e.review_binding_json==null?void 0:JSON.parse(e.review_binding_json),launch:e.launch_config_json==null?void 0:JSON.parse(e.launch_config_json),pi_session_id:e.pi_session_id??null,pi_session_file:e.pi_session_file??null,...n===null?{}:{managed_worktree:n}}}r(A,"metaFrom");async function Cn(e,n={}){return Fe(),await p(async t=>{await Xe(e,t),e.managed_worktree!==void 0&&e.managed_worktree!==null&&await xe(e.node_id,e.managed_worktree,t),n.outcomeDelivery!==void 0&&await z(t,e.node_id,n.outcomeDelivery),await n.withinCreate?.(t,e)}),await Pe(e.node_id),await O(e.node_id)}r(Cn,"createNode");async function O(e){const n=await(await d()).prepare("SELECT * FROM node_rows WHERE node_id = ?").get(e);return n===void 0?null:await A(n)}r(O,"getNode");async function Hn(e){if(e.length===0)return[];const n=v.map(i=>`w.${i} AS worktree_${i}`).join(", "),t=await(await d()).prepareUncached(`SELECT n.*, ${n} FROM node_rows n LEFT JOIN worktrees w ON w.node_id = n.node_id WHERE n.node_id IN (${e.map(()=>"?").join(",")})`).all(...e),a=new Map(t.map(i=>[i.node_id,i]));return await h(e.map(i=>a.get(i)).filter(i=>i!==void 0),async i=>await A(i,ee(i)))}r(Hn,"getNodes");const Ze=1440*60*1e3;function Z(e){return{requestKey:e.request_key,nodeId:e.node_id,state:e.state}}r(Z,"createRequestRecord");async function Mn(e){const n=await(await d()).prepareUncached("SELECT request_key, node_id, state FROM create_requests WHERE request_key = ?").get(e);return n===void 0?null:Z(n)}r(Mn,"findCreateRequest");async function Pn(e){return await p(async n=>{const t=Date.now();await n.prepareUncached("DELETE FROM create_requests WHERE expires_at <= ?").run(t),await n.prepareUncached("INSERT INTO create_requests (request_key, node_id, expires_at, state) VALUES (?, NULL, ?, 'reserved') ON CONFLICT (request_key) DO NOTHING").run(e,t+Ze);const a=await n.prepareUncached("SELECT request_key, node_id, state FROM create_requests WHERE request_key = ?").get(e);return Z(a)})}r(Pn,"reserveCreateRequest");async function $n(e=Date.now()){return Number((await(await d()).prepareUncached("DELETE FROM create_requests WHERE expires_at <= ?").run(e)).changes)}r($n,"pruneExpiredCreateRequests");async function qn(e,n){await(await d()).prepareUncached("UPDATE create_requests SET node_id = ?, state = 'complete' WHERE request_key = ?").run(n,e)}r(qn,"recordCreateRequestNode");async function Bn(e,n,t){const a=await d();return await a.prepareUncached("UPDATE create_requests SET node_id = ?, state = 'reserved', lease_owner = ?, lease_expires_at = ? WHERE request_key = ? AND node_id IS NULL").run(n,t,Date.now()+g,e),(await a.prepareUncached("SELECT node_id FROM create_requests WHERE request_key = ?").get(e))?.node_id??null}r(Bn,"reserveCreateRequestNode");const g=3e4,zn=1e4;async function Jn(e,n,t){const a=Date.now(),i=await(await d()).prepareUncached("UPDATE create_requests SET lease_owner = ?, lease_expires_at = ? WHERE request_key = ? AND node_id = ? AND state = 'reserved' AND (lease_expires_at IS NULL OR lease_expires_at <= ?)").run(t,a+g,e,n,a);return Number(i.changes)>0}r(Jn,"claimCreateLease");async function Yn(e,n){await(await d()).prepareUncached("UPDATE create_requests SET lease_expires_at = ? WHERE request_key = ? AND lease_owner = ?").run(Date.now()+g,e,n)}r(Yn,"renewCreateLease");async function Qn(e){const n=await(await d()).prepareUncached("SELECT lease_expires_at FROM create_requests WHERE request_key = ?").get(e);return n?.lease_expires_at!=null&&Number(n.lease_expires_at)>Date.now()}r(Qn,"createLeaseLive");async function Vn(e,n){await(await d()).prepareUncached("UPDATE create_requests SET state = 'complete' WHERE request_key = ? AND node_id = ?").run(e,n)}r(Vn,"completeCreateRequest");async function Kn(e,n){await p(async t=>{if(n===null){await t.prepareUncached("DELETE FROM create_requests WHERE request_key = ? AND node_id IS NULL").run(e);return}await t.prepareUncached("DELETE FROM create_requests WHERE request_key = ? AND node_id = ?").run(e,n)})}r(Kn,"abandonCreateRequest");function Gn(e){return Ne(e)}r(Gn,"canonicalSessionFile");async function Xn(e){const n=await ge(e);return n===null?null:await O(n)}r(Xn,"findNodeBySessionFile");async function Zn(e){const n=await(await d()).prepare("SELECT * FROM node_rows WHERE node_id = ?").get(e);return n?f(n):null}r(Zn,"getRow");async function et(e){const n=await(await d()).prepare("SELECT * FROM node_rows WHERE pane = ?").get(e);return n?f(n):null}r(et,"getRowByPane");async function nt(e){return(await(await d()).prepare(`SELECT * FROM node_rows
2
2
  WHERE deadline_at IS NOT NULL AND outcome_at IS NULL
3
3
  AND deadline_at <= ? AND status IN ('active','idle') AND kind != 'human'
4
- ORDER BY deadline_at, created, node_id`).all(e)).map(f)}i(nt,"dueNodeDeadlines");async function tt(e,n){return Number((await(await d()).prepare("UPDATE nodes SET deadline_at = ? WHERE node_id = ?").run(n,e)).changes)===1}i(tt,"setNodeDeadline");async function at(e,n){return!Number.isFinite(n)||n<=0?0:await p(async t=>{const a=await t.prepare(`SELECT node_id, deadline_at FROM nodes
5
- WHERE profile_id = ? AND deadline_at IS NOT NULL AND status IN ('active', 'idle')`).all(e),r=t.prepare("UPDATE nodes SET deadline_at = ? WHERE node_id = ? AND deadline_at = ?");let o=0;for(const s of a){const c=Date.parse(s.deadline_at);Number.isNaN(c)||(o+=Number((await r.run(new Date(c+n).toISOString(),s.node_id,s.deadline_at)).changes))}return o})}i(at,"shiftProfileNodeDeadlines");function k(e,n){if(e==null)return null;if(typeof e=="string"||typeof e=="number"||typeof e=="bigint"||e instanceof Uint8Array)return e;throw new TypeError(`${n} must be a SQLite scalar`)}i(k,"sqlInput");async function it(e,n){const t=[],a=i((o,s=o)=>{Object.prototype.hasOwnProperty.call(n,o)&&t.push([s,k(n[o],o)])},"add");if(a("description"),a("title"),a("icon"),a("cycles"),a("mode"),a("lifecycle"),a("cwd"),a("host_kind"),a("profile_id"),a("parent"),a("spawned_by"),a("creator"),a("fork_from"),a("fork_source_file"),a("model_override"),Object.prototype.hasOwnProperty.call(n,"passive_default")&&t.push(["passive_default",n.passive_default===!0?1:0]),Object.prototype.hasOwnProperty.call(n,"cycle_pending")&&t.push(["cycle_pending",n.cycle_pending===!0?1:0]),Object.prototype.hasOwnProperty.call(n,"persona_ack")&&t.push(["persona_ack_json",E(n.persona_ack,"persona_ack")]),Object.prototype.hasOwnProperty.call(n,"review_binding")&&t.push(["review_binding_json",E(n.review_binding,"review_binding")]),Object.prototype.hasOwnProperty.call(n,"isolated"))throw new TypeError("isolated cannot change after node creation");Object.prototype.hasOwnProperty.call(n,"scopes")&&t.push(["scopes_json",E(n.scopes,"scopes")]),Object.prototype.hasOwnProperty.call(n,"launch")&&t.push(["launch_config_json",E(n.launch,"launch")]);const r=i(o=>Object.prototype.hasOwnProperty.call(n,o),"has");return await p(async o=>{const s=await D(o,e);if(s===null||s.type!=="node")throw new Error(`unknown node: ${e}`);if(r("name")&&await Je(o,s,k(n.name,"name")),r("kind")&&await ze(o,s,k(n.kind,"kind")),t.length===0)return;if(r("profile_id")){const u=await o.prepare("SELECT app FROM nodes WHERE node_id = ?").get(e),_=u?.app?await D(o,u.app):null;if(_){const w=n.profile_id?await V(o,n.profile_id,_,`app:${_.name}`):null;await o.prepare("UPDATE objects SET owner = ? WHERE id = ?").run((w??_).id,e);const N=(await o.prepare("SELECT sub FROM nodes WHERE node_id = ?").get(e)).sub;w===null&&N&&await Q(o,e,N)}}if((await o.prepareUncached(`UPDATE nodes SET ${t.map(([u])=>`${u} = ?`).join(", ")} WHERE node_id = ?`).run(...t.map(([,u])=>u),e)).changes!==1)throw new Error(`unknown node: ${e}`)}),await O(e)}i(it,"updateNode");async function rt(e,n){await(await d()).prepare("UPDATE nodes SET status = ? WHERE node_id = ?").run(n,e)}i(rt,"setStatus");async function ot(e,n){await(await d()).prepare("UPDATE nodes SET intent = ? WHERE node_id = ?").run(n??null,e)}i(ot,"setIntent");async function st(e,n,t={}){if(t.outcome===void 0){const r=[],o=[];Object.prototype.hasOwnProperty.call(n,"status")&&(r.push("status = ?"),o.push(n.status??null)),Object.prototype.hasOwnProperty.call(n,"intent")&&(r.push("intent = ?"),o.push(n.intent??null)),Object.prototype.hasOwnProperty.call(n,"terminal_reason")&&(r.push("terminal_reason = ?"),o.push(n.terminal_reason??null));const s=["node_id = ?"];o.push(e),t.fromStatuses!==void 0&&(s.push(`status IN (${t.fromStatuses.map(()=>"?").join(", ")})`),o.push(...t.fromStatuses)),t.requireNoFinalReport===!0&&s.push("final_report IS NULL");const c=await(await d()).prepareUncached(`UPDATE nodes SET ${r.join(", ")} WHERE ${s.join(" AND ")}`).run(...o);return Number(c.changes)}const a=t.outcome;return await p(async r=>{const o=[],s=[];Object.prototype.hasOwnProperty.call(n,"status")&&(o.push("status = ?"),s.push(n.status??null)),Object.prototype.hasOwnProperty.call(n,"intent")&&(o.push("intent = ?"),s.push(n.intent??null)),Object.prototype.hasOwnProperty.call(n,"terminal_reason")&&(o.push("terminal_reason = ?"),s.push(n.terminal_reason??null));const c=i((N,R)=>a.supersede===!0?"?":`CASE WHEN outcome_at IS NULL THEN ? ELSE ${R} END`,"outcomeValue");o.push(`outcome_kind = ${c(a.kind,"outcome_kind")}`,`outcome_reason = ${c(a.reason,"outcome_reason")}`,`outcome_detail_json = ${c(a.detailJson,"outcome_detail_json")}`,`outcome_revision = ${a.supersede===!0?"outcome_revision + 1":"CASE WHEN outcome_at IS NULL THEN outcome_revision + 1 ELSE outcome_revision END"}`,`outcome_at = ${c(a.at,"outcome_at")}`),s.push(a.kind,a.reason,a.detailJson,a.at);const u=["node_id = ?"];s.push(e),t.fromStatuses!==void 0&&(u.push(`status IN (${t.fromStatuses.map(()=>"?").join(", ")})`),s.push(...t.fromStatuses)),t.requireNoFinalReport===!0&&u.push("final_report IS NULL");const _=await r.prepareUncached(`UPDATE nodes SET ${o.join(", ")} WHERE ${u.join(" AND ")}`).run(...s);if(Number(_.changes)===0)return 0;const w=await r.prepare("SELECT outcome_at FROM nodes WHERE node_id = ?").get(e);return(a.supersede===!0||w.outcome_at===a.at)&&a.documentJson!==null&&a.documentJson!==void 0&&await De(r,{event:"outcome",object:await Ae(r,e),actor:null,attrs:{revision:Number((await r.prepare("SELECT outcome_revision FROM nodes WHERE node_id = ?").get(e)).outcome_revision)},messageBody:JSON.parse(a.documentJson)}),Number(_.changes)})}i(st,"transitionStatusIntent");async function dt(e){return(await(await d()).prepare("SELECT final_report FROM nodes WHERE node_id = ?").get(e))?.final_report??null}i(dt,"getFinalReport");async function ut(e,n){return(await(await d()).prepare("UPDATE nodes SET final_report = NULL, finalized_at = NULL WHERE node_id = ? AND final_report = ?").run(e,n)).changes>0}i(ut,"clearFinalReportIfMatches");async function ct(e,n){await(await d()).prepare('UPDATE nodes SET tmux_session = ?, "window" = ?, pane = ? WHERE node_id = ?').run(n.tmux_session??null,n.window??null,n.pane??null,e)}i(ct,"setPresence");async function lt(e,n){await(await d()).prepare("UPDATE nodes SET launched_at = ?, frozen_at = NULL, respawn_not_before = NULL WHERE node_id = ?").run(n,e)}i(lt,"recordLaunch");async function _t(e,n){await(await d()).prepare("UPDATE nodes SET last_settled_at = ? WHERE node_id = ?").run(n,e)}i(_t,"recordSettledTurn");async function pt(e,n){await(await d()).prepare("UPDATE nodes SET frozen_at = ? WHERE node_id = ?").run(n,e)}i(pt,"setFrozen");async function ft(e){await(await d()).prepare("UPDATE nodes SET frozen_at = NULL WHERE node_id = ?").run(e)}i(ft,"clearFrozen");async function Et(e,n){await(await d()).prepare("UPDATE nodes SET respawn_failures = ?, respawn_not_before = ? WHERE node_id = ?").run(n.failures,n.notBefore,e)}i(Et,"recordRespawnAttempt");const m="node_id NOT IN (SELECT node_id FROM warm_pool)",v=["state","cleanup_state","path","branch","repo_root","base_ref","base_sha","created_at","closed_at","next_attempt_at","attempts","quarantined","sweep_reason","sweep_detail","sweep_last_at","sweep_observed_json","abandoned_json","land_intent_json","disposal_json"];function ee(e){return e.worktree_state===null?null:We(Object.fromEntries(v.map(n=>[n,e[`worktree_${n}`]])))}i(ee,"worktreeFromProjection");async function wt(e){const n=v.map(a=>`w.${a} AS worktree_${a}`).join(", "),t=await(await d()).prepareUncached(`SELECT n.*, ${n} FROM node_rows n LEFT JOIN worktrees w ON w.node_id = n.node_id WHERE n.profile_id = ? ORDER BY n.created`).all(e);return await h(t,async a=>await A(a,ee(a)))}i(wt,"listNodesByProfile");async function yt(){return(await(await d()).prepare(`SELECT
4
+ ORDER BY deadline_at, created, node_id`).all(e)).map(f)}r(nt,"dueNodeDeadlines");async function tt(e,n){return Number((await(await d()).prepare("UPDATE nodes SET deadline_at = ? WHERE node_id = ?").run(n,e)).changes)===1}r(tt,"setNodeDeadline");async function at(e,n){return!Number.isFinite(n)||n<=0?0:await p(async t=>{const a=await t.prepare(`SELECT node_id, deadline_at FROM nodes
5
+ WHERE profile_id = ? AND deadline_at IS NOT NULL AND status IN ('active', 'idle')`).all(e),i=t.prepare("UPDATE nodes SET deadline_at = ? WHERE node_id = ? AND deadline_at = ?");let o=0;for(const s of a){const c=Date.parse(s.deadline_at);Number.isNaN(c)||(o+=Number((await i.run(new Date(c+n).toISOString(),s.node_id,s.deadline_at)).changes))}return o})}r(at,"shiftProfileNodeDeadlines");function k(e,n){if(e==null)return null;if(typeof e=="string"||typeof e=="number"||typeof e=="bigint"||e instanceof Uint8Array)return e;throw new TypeError(`${n} must be a SQLite scalar`)}r(k,"sqlInput");async function it(e,n){const t=[],a=r((o,s=o)=>{Object.prototype.hasOwnProperty.call(n,o)&&t.push([s,k(n[o],o)])},"add");if(a("description"),a("title"),a("icon"),a("cycles"),a("mode"),a("lifecycle"),a("cwd"),a("host_kind"),a("profile_id"),a("parent"),a("spawned_by"),a("creator"),a("fork_from"),a("fork_source_file"),a("model_override"),Object.prototype.hasOwnProperty.call(n,"passive_default")&&t.push(["passive_default",n.passive_default===!0?1:0]),Object.prototype.hasOwnProperty.call(n,"cycle_pending")&&t.push(["cycle_pending",n.cycle_pending===!0?1:0]),Object.prototype.hasOwnProperty.call(n,"persona_ack")&&t.push(["persona_ack_json",E(n.persona_ack,"persona_ack")]),Object.prototype.hasOwnProperty.call(n,"review_binding")&&t.push(["review_binding_json",E(n.review_binding,"review_binding")]),Object.prototype.hasOwnProperty.call(n,"isolated"))throw new TypeError("isolated cannot change after node creation");Object.prototype.hasOwnProperty.call(n,"scopes")&&t.push(["scopes_json",E(n.scopes,"scopes")]),Object.prototype.hasOwnProperty.call(n,"launch")&&t.push(["launch_config_json",E(n.launch,"launch")]);const i=r(o=>Object.prototype.hasOwnProperty.call(n,o),"has");return await p(async o=>{const s=await D(o,e);if(s===null||s.type!=="node")throw new Error(`unknown node: ${e}`);if(i("name")&&await Je(o,s,k(n.name,"name")),i("kind")&&await ze(o,s,k(n.kind,"kind")),t.length===0)return;if(i("profile_id")){const u=await o.prepare("SELECT app FROM nodes WHERE node_id = ?").get(e),_=u?.app?await D(o,u.app):null;if(_){const w=n.profile_id?await V(o,n.profile_id,_,`app:${_.name}`):null;await o.prepare("UPDATE objects SET owner = ? WHERE id = ?").run((w??_).id,e);const N=(await o.prepare("SELECT sub FROM nodes WHERE node_id = ?").get(e)).sub;w===null&&N&&await Q(o,e,N)}}if((await o.prepareUncached(`UPDATE nodes SET ${t.map(([u])=>`${u} = ?`).join(", ")} WHERE node_id = ?`).run(...t.map(([,u])=>u),e)).changes!==1)throw new Error(`unknown node: ${e}`)}),await O(e)}r(it,"updateNode");async function rt(e,n){await(await d()).prepare("UPDATE nodes SET status = ? WHERE node_id = ?").run(n,e)}r(rt,"setStatus");async function ot(e,n){await(await d()).prepare("UPDATE nodes SET intent = ? WHERE node_id = ?").run(n??null,e)}r(ot,"setIntent");async function st(e,n,t={}){if(t.outcome===void 0){const i=[],o=[];Object.prototype.hasOwnProperty.call(n,"status")&&(i.push("status = ?"),o.push(n.status??null)),Object.prototype.hasOwnProperty.call(n,"intent")&&(i.push("intent = ?"),o.push(n.intent??null)),Object.prototype.hasOwnProperty.call(n,"terminal_reason")&&(i.push("terminal_reason = ?"),o.push(n.terminal_reason??null));const s=["node_id = ?"];o.push(e),t.fromStatuses!==void 0&&(s.push(`status IN (${t.fromStatuses.map(()=>"?").join(", ")})`),o.push(...t.fromStatuses)),t.requireNoFinalReport===!0&&s.push("final_report IS NULL");const c=await(await d()).prepareUncached(`UPDATE nodes SET ${i.join(", ")} WHERE ${s.join(" AND ")}`).run(...o);return Number(c.changes)}const a=t.outcome;return await p(async i=>{const o=[],s=[];Object.prototype.hasOwnProperty.call(n,"status")&&(o.push("status = ?"),s.push(n.status??null)),Object.prototype.hasOwnProperty.call(n,"intent")&&(o.push("intent = ?"),s.push(n.intent??null)),Object.prototype.hasOwnProperty.call(n,"terminal_reason")&&(o.push("terminal_reason = ?"),s.push(n.terminal_reason??null));const c=r((N,R)=>a.supersede===!0?"?":`CASE WHEN outcome_at IS NULL THEN ? ELSE ${R} END`,"outcomeValue");o.push(`outcome_kind = ${c(a.kind,"outcome_kind")}`,`outcome_reason = ${c(a.reason,"outcome_reason")}`,`outcome_detail_json = ${c(a.detailJson,"outcome_detail_json")}`,`outcome_revision = ${a.supersede===!0?"outcome_revision + 1":"CASE WHEN outcome_at IS NULL THEN outcome_revision + 1 ELSE outcome_revision END"}`,`outcome_at = ${c(a.at,"outcome_at")}`),s.push(a.kind,a.reason,a.detailJson,a.at);const u=["node_id = ?"];s.push(e),t.fromStatuses!==void 0&&(u.push(`status IN (${t.fromStatuses.map(()=>"?").join(", ")})`),s.push(...t.fromStatuses)),t.requireNoFinalReport===!0&&u.push("final_report IS NULL");const _=await i.prepareUncached(`UPDATE nodes SET ${o.join(", ")} WHERE ${u.join(" AND ")}`).run(...s);if(Number(_.changes)===0)return 0;const w=await i.prepare("SELECT outcome_at FROM nodes WHERE node_id = ?").get(e);return(a.supersede===!0||w.outcome_at===a.at)&&a.documentJson!==null&&a.documentJson!==void 0&&await De(i,{event:"outcome",object:await Ae(i,e),actor:null,attrs:{revision:Number((await i.prepare("SELECT outcome_revision FROM nodes WHERE node_id = ?").get(e)).outcome_revision)},messageBody:JSON.parse(a.documentJson)}),Number(_.changes)})}r(st,"transitionStatusIntent");async function dt(e){return(await(await d()).prepare("SELECT final_report FROM nodes WHERE node_id = ?").get(e))?.final_report??null}r(dt,"getFinalReport");async function ut(e,n){return(await(await d()).prepare("UPDATE nodes SET final_report = NULL, finalized_at = NULL WHERE node_id = ? AND final_report = ?").run(e,n)).changes>0}r(ut,"clearFinalReportIfMatches");async function ct(e,n){await(await d()).prepare('UPDATE nodes SET tmux_session = ?, "window" = ?, pane = ? WHERE node_id = ?').run(n.tmux_session??null,n.window??null,n.pane??null,e)}r(ct,"setPresence");async function lt(e,n){await(await d()).prepare("UPDATE nodes SET launched_at = ?, frozen_at = NULL, respawn_not_before = NULL WHERE node_id = ?").run(n,e)}r(lt,"recordLaunch");async function _t(e,n){await(await d()).prepare("UPDATE nodes SET last_settled_at = ? WHERE node_id = ?").run(n,e)}r(_t,"recordSettledTurn");async function pt(e,n){await(await d()).prepare("UPDATE nodes SET frozen_at = ? WHERE node_id = ?").run(n,e)}r(pt,"setFrozen");async function ft(e){await(await d()).prepare("UPDATE nodes SET frozen_at = NULL WHERE node_id = ?").run(e)}r(ft,"clearFrozen");async function Et(e,n){await(await d()).prepare("UPDATE nodes SET respawn_failures = ?, respawn_not_before = ? WHERE node_id = ?").run(n.failures,n.notBefore,e)}r(Et,"recordRespawnAttempt");const m="node_id NOT IN (SELECT node_id FROM warm_pool)",v=["state","cleanup_state","path","branch","repo_root","base_ref","base_sha","created_at","closed_at","next_attempt_at","attempts","quarantined","sweep_reason","sweep_detail","sweep_last_at","sweep_observed_json","abandoned_json","land_intent_json","disposal_json"];function ee(e){return e.worktree_state===null?null:We(Object.fromEntries(v.map(n=>[n,e[`worktree_${n}`]])))}r(ee,"worktreeFromProjection");async function wt(e){const n=v.map(a=>`w.${a} AS worktree_${a}`).join(", "),t=await(await d()).prepareUncached(`SELECT n.*, ${n} FROM node_rows n LEFT JOIN worktrees w ON w.node_id = n.node_id WHERE n.profile_id = ? ORDER BY n.created`).all(e);return await h(t,async a=>await A(a,ee(a)))}r(wt,"listNodesByProfile");async function yt(){return(await(await d()).prepare(`SELECT
6
6
  node_id, name, description, kind, mode, lifecycle, status, cwd, profile_id,
7
7
  grantee, parent, created, frozen_at, terminal_reason, final_report,
8
8
  telemetry_tokens_in, telemetry_updated_at, pi_pid, turn_open_at, turn_closed_at,
@@ -10,13 +10,13 @@ var ce=Object.defineProperty;var i=(e,n)=>ce(e,"name",{value:n,configurable:!0})
10
10
  fault_operation_id, fault_anchor_entry_id, fault_retry_disposition,
11
11
  fault_retry_by, fault_retry_attempt, fault_retry_max, fault_retry_next_at,
12
12
  fault_provider_error_json
13
- FROM node_rows WHERE ${m} ORDER BY created`).all()).map(f)}i(yt,"browseNodes");async function mt(e,n){await(await d()).prepare(`UPDATE nodes
13
+ FROM node_rows WHERE ${m} ORDER BY created`).all()).map(f)}r(yt,"browseNodes");async function mt(e,n){await(await d()).prepare(`UPDATE nodes
14
14
  SET telemetry_tokens_in = ?,
15
15
  telemetry_context_tokens = COALESCE(?, telemetry_context_tokens),
16
16
  telemetry_last_activity = COALESCE(?, telemetry_last_activity),
17
17
  telemetry_updated_at = ?
18
18
  WHERE node_id = ?
19
- AND (telemetry_updated_at IS NULL OR telemetry_updated_at < ?)`).run(n.tokensIn,n.contextTokens,n.lastActivity,n.updatedAt,e,n.updatedAt)}i(mt,"updateNodeTelemetry");async function Nt(){return(await(await d()).prepare(`SELECT
19
+ AND (telemetry_updated_at IS NULL OR telemetry_updated_at < ?)`).run(n.tokensIn,n.contextTokens,n.lastActivity,n.updatedAt,e,n.updatedAt)}r(mt,"updateNodeTelemetry");async function Nt(e){const n=await d(),t=`SELECT
20
20
  node_id, name, description, cycles, kind, status, frozen_at,
21
21
  telemetry_context_tokens, telemetry_last_activity,
22
22
  pi_pid, turn_open_at, turn_closed_at,
@@ -24,14 +24,14 @@ var ce=Object.defineProperty;var i=(e,n)=>ce(e,"name",{value:n,configurable:!0})
24
24
  fault_operation_id, fault_anchor_entry_id, fault_retry_disposition,
25
25
  fault_retry_by, fault_retry_attempt, fault_retry_max, fault_retry_next_at,
26
26
  fault_provider_error_json
27
- FROM node_rows WHERE ${m} ORDER BY created`).all()).map(n=>{const t=n.pi_pid??null,a=J(t),r=K(n);return{node_id:n.node_id,name:n.name,description:n.description??null,cycles:n.cycles??null,kind:n.kind,status:n.status,frozen_at:n.frozen_at??null,pi_pid:t,telemetry_context_tokens:n.telemetry_context_tokens??null,telemetry_last_activity:n.telemetry_last_activity??null,fault:r?.link==="pi\u2192provider"&&r.retry.by==="daemon"&&r.retry.disposition==="auto"&&!a?null:r,streaming:G(n)&&X(a)}})}i(Nt,"graphNodes");async function en(e){const n=[m],t=[];if(e?.under!==void 0&&(e.underInclusive===!0?(n.push(`(node_id IN (${Ke}) OR node_id = ?)`),t.push(e.under,e.under,e.under)):(n.push(`node_id IN (${Ge})`),t.push(e.under,e.under))),e?.lifecycle!==void 0&&(n.push("lifecycle = ?"),t.push(e.lifecycle)),e?.kind!==void 0&&(n.push("kind = ?"),t.push(e.kind)),e?.mode!==void 0&&(n.push("mode = ?"),t.push(e.mode)),e?.profileId!==void 0&&(n.push("profile_id = ?"),t.push(e.profileId)),e?.profilePrefix!==void 0&&(n.push("profile_id LIKE ? ESCAPE '\\'"),t.push(`${e.profilePrefix.replace(/[\\%_]/g,r=>`\\${r}`)}%`)),e?.parent!==void 0&&(n.push("parent = ?"),t.push(e.parent)),e?.topLevel===!0&&n.push("parent IS NULL"),e?.hanging===!0&&n.push("parent IS NOT NULL AND parent NOT IN (SELECT node_id FROM node_rows)"),e?.status!==void 0){const r=Array.isArray(e.status)?e.status:[e.status];n.push(`status IN (${r.map(()=>"?").join(",")})`),t.push(...r)}return e?.withRecordedPid===!0&&n.push("pi_pid IS NOT NULL"),e?.withRecordedPidOrFrozen===!0&&n.push("(pi_pid IS NOT NULL OR frozen_at IS NOT NULL)"),(await(await d()).prepareUncached(`SELECT * FROM node_rows WHERE ${n.join(" AND ")} ORDER BY created`).all(...t)).map(f)}i(en,"listNodes");const nn=`SELECT
27
+ FROM node_rows WHERE ${m}${e===void 0?"":" AND node_id = ANY(?::text[])"} ORDER BY created`;return(e===void 0?await n.prepare(t).all():await n.prepareUncached(t).all([...e])).map(i=>{const o=i.pi_pid??null,s=J(o),c=K(i);return{node_id:i.node_id,name:i.name,description:i.description??null,cycles:i.cycles??null,kind:i.kind,status:i.status,frozen_at:i.frozen_at??null,pi_pid:o,telemetry_context_tokens:i.telemetry_context_tokens??null,telemetry_last_activity:i.telemetry_last_activity??null,fault:c?.link==="pi\u2192provider"&&c.retry.by==="daemon"&&c.retry.disposition==="auto"&&!s?null:c,streaming:G(i)&&X(s)}})}r(Nt,"graphNodes");async function en(e){const n=[m],t=[];if(e?.under!==void 0&&(e.underInclusive===!0?(n.push(`(node_id IN (${Ke}) OR node_id = ?)`),t.push(e.under,e.under,e.under)):(n.push(`node_id IN (${Ge})`),t.push(e.under,e.under))),e?.lifecycle!==void 0&&(n.push("lifecycle = ?"),t.push(e.lifecycle)),e?.kind!==void 0&&(n.push("kind = ?"),t.push(e.kind)),e?.mode!==void 0&&(n.push("mode = ?"),t.push(e.mode)),e?.profileId!==void 0&&(n.push("profile_id = ?"),t.push(e.profileId)),e?.profilePrefix!==void 0&&(n.push("profile_id LIKE ? ESCAPE '\\'"),t.push(`${e.profilePrefix.replace(/[\\%_]/g,i=>`\\${i}`)}%`)),e?.parent!==void 0&&(n.push("parent = ?"),t.push(e.parent)),e?.topLevel===!0&&n.push("parent IS NULL"),e?.hanging===!0&&n.push("parent IS NOT NULL AND parent NOT IN (SELECT node_id FROM node_rows)"),e?.status!==void 0){const i=Array.isArray(e.status)?e.status:[e.status];n.push(`status IN (${i.map(()=>"?").join(",")})`),t.push(...i)}return e?.withRecordedPid===!0&&n.push("pi_pid IS NOT NULL"),e?.withRecordedPidOrFrozen===!0&&n.push("(pi_pid IS NOT NULL OR frozen_at IS NOT NULL)"),(await(await d()).prepareUncached(`SELECT * FROM node_rows WHERE ${n.join(" AND ")} ORDER BY created`).all(...t)).map(f)}r(en,"listNodes");const nn=`SELECT
28
28
  node_id, created, launched_at, last_settled_at, finalized_at,
29
29
  outcome_at, last_activity_at, pane, "window", tmux_session
30
30
  FROM nodes
31
31
  WHERE ${m}
32
32
  AND status IN ('done', 'canceled', 'dead')
33
33
  AND (pane IS NOT NULL OR "window" IS NOT NULL OR tmux_session IS NOT NULL)
34
- ORDER BY created`;async function Rt(){return await(await d()).prepare(nn).all()}i(Rt,"listTerminalPlacementResidue");const tn=`WITH candidates AS MATERIALIZED (
34
+ ORDER BY created`;async function Rt(){return await(await d()).prepare(nn).all()}r(Rt,"listTerminalPlacementResidue");const tn=`WITH candidates AS MATERIALIZED (
35
35
  SELECT node_id FROM nodes WHERE status IN ('active', 'idle')
36
36
  UNION
37
37
  SELECT node_id FROM nodes
@@ -45,23 +45,23 @@ var ce=Object.defineProperty;var i=(e,n)=>ce(e,"name",{value:n,configurable:!0})
45
45
  AND v.node_id NOT IN (SELECT node_id FROM warm_pool)
46
46
  AND v.kind != 'human'
47
47
  AND (v.status IN ('active', 'idle') OR (v.status IN ('done', 'canceled', 'dead') AND (v.pi_pid IS NOT NULL OR v.frozen_at IS NOT NULL)))
48
- ORDER BY v.created`;async function St(){return(await(await d()).prepare(tn).all()).map(f)}i(St,"listNodesForSupervision");const ne=i(e=>`(${e}.status = 'done' AND ${e}.intent = 'parked' AND ${e}.lifecycle = 'resident' AND ${e}.final_report IS NULL AND ${e}.deleting_at IS NULL)`,"PARKED_RESIDENT_SQL"),an=i(e=>`(${e}.status IN ('active', 'idle') OR ${ne(e)} OR (${e}.status IN ('done', 'canceled', 'dead') AND ${e}.frozen_at IS NOT NULL AND ${e}.final_report IS NULL))`,"RESUMABLE_NODE_SQL");async function ht(e){return await(await d()).prepare(`SELECT node_id, cwd FROM nodes WHERE ${an("nodes")} AND node_id != ?`).all(e)}i(ht,"resumableNodeCwds");async function Ot(){return(await(await d()).prepare(`SELECT v.* FROM node_rows v
48
+ ORDER BY v.created`;async function St(){return(await(await d()).prepare(tn).all()).map(f)}r(St,"listNodesForSupervision");const ne=r(e=>`(${e}.status = 'done' AND ${e}.intent = 'parked' AND ${e}.lifecycle = 'resident' AND ${e}.final_report IS NULL AND ${e}.deleting_at IS NULL)`,"PARKED_RESIDENT_SQL"),an=r(e=>`(${e}.status IN ('active', 'idle') OR ${ne(e)} OR (${e}.status IN ('done', 'canceled', 'dead') AND ${e}.frozen_at IS NOT NULL AND ${e}.final_report IS NULL))`,"RESUMABLE_NODE_SQL");async function ht(e){return await(await d()).prepare(`SELECT node_id, cwd FROM nodes WHERE ${an("nodes")} AND node_id != ?`).all(e)}r(ht,"resumableNodeCwds");async function Ot(){return(await(await d()).prepare(`SELECT v.* FROM node_rows v
49
49
  WHERE ${ne("v")}
50
50
  AND EXISTS (SELECT 1 FROM deliveries d WHERE d.destination_id = v.node_id AND ${Te("d")}) AND v.kind != 'human' AND v.node_id NOT IN (SELECT node_id FROM warm_pool)
51
- ORDER BY v.created`).all()).map(f)}i(Ot,"listParkedResidentsWithWakeMail");async function Lt(e,n){await(await d()).prepare("INSERT INTO warm_pool (node_id, recipe_key, created) VALUES (?, ?, ?) ON CONFLICT (node_id) DO UPDATE SET recipe_key = excluded.recipe_key, created = excluded.created").run(e,n,new Date().toISOString())}i(Lt,"registerWarmSpare");async function Tt(e){return(await(await d()).prepare("DELETE FROM warm_pool WHERE node_id = ?").run(e)).changes>0}i(Tt,"unregisterWarmSpare");async function x(e,n){const t=`SELECT w.node_id AS node_id, w.recipe_key AS recipe_key, w.created AS created,
51
+ ORDER BY v.created`).all()).map(f)}r(Ot,"listParkedResidentsWithWakeMail");async function Lt(e,n){await(await d()).prepare("INSERT INTO warm_pool (node_id, recipe_key, created) VALUES (?, ?, ?) ON CONFLICT (node_id) DO UPDATE SET recipe_key = excluded.recipe_key, created = excluded.created").run(e,n,new Date().toISOString())}r(Lt,"registerWarmSpare");async function Tt(e){return(await(await d()).prepare("DELETE FROM warm_pool WHERE node_id = ?").run(e)).changes>0}r(Tt,"unregisterWarmSpare");async function x(e,n){const t=`SELECT w.node_id AS node_id, w.recipe_key AS recipe_key, w.created AS created,
52
52
  n.status AS status, n.pi_pid AS pi_pid, n.pi_pid_identity AS pi_pid_identity
53
- FROM warm_pool w JOIN node_rows n ON n.node_id = w.node_id`+(n===void 0?"":" WHERE w.recipe_key = ?")+" ORDER BY w.created";return(n===void 0?await e.prepareUncached(t).all():await e.prepareUncached(t).all(n)).map(r=>({node_id:r.node_id,recipe_key:r.recipe_key,created:r.created,status:r.status,pi_pid:r.pi_pid??null,pi_pid_identity:r.pi_pid_identity??null}))}i(x,"warmSpareRowsFor");async function Dt(){return await x(await d())}i(Dt,"listWarmSpares");async function At(e){return await(await d()).prepare("SELECT 1 FROM warm_pool WHERE node_id = ?").get(e)!==void 0}i(At,"isWarmSpare");function te(e){return e.status!=="active"&&e.status!=="idle"?!1:je(e.pi_pid,e.pi_pid_identity)==="alive"}i(te,"spareIsClaimable");async function gt(e,n,t={}){return await p(async a=>{const r=(await x(a,e)).find(te);return r===void 0||t.requestKey!==void 0&&(await a.prepareUncached("UPDATE create_requests SET node_id = ?, state = 'warm_claimed' WHERE request_key = ? AND node_id IS NULL").run(r.node_id,t.requestKey)).changes===0||(await a.prepare("DELETE FROM warm_pool WHERE node_id = ?").run(r.node_id)).changes===0?null:(await a.prepare("UPDATE nodes SET created = ?, deadline_at = ? WHERE node_id = ?").run(n,t.deadlineAt??null,r.node_id),t.outcomeDelivery!==void 0&&await z(a,r.node_id,t.outcomeDelivery),r.node_id)})}i(gt,"claimWarmSpare");async function kt(e){return(await x(await d(),e)).filter(te).length}i(kt,"warmSpareCount");async function vt(e){return(await(await d()).prepare("SELECT node_id FROM nodes WHERE parent = ? ORDER BY created").all(e)).map(n=>n.node_id)}i(vt,"childrenOf");async function xt(e){return(await(await d()).prepareUncached(`SELECT node_id, name, kind, mode, lifecycle, status, cwd, host_kind, parent, created, description
54
- FROM node_rows WHERE ${m}${e===void 0?"":" AND node_id = ANY(?::text[])"} ORDER BY created`).all(...e===void 0?[]:[[...e]])).map(n=>({node_id:n.node_id,name:n.name,kind:n.kind,mode:n.mode,lifecycle:n.lifecycle,status:n.status,cwd:n.cwd,host_kind:n.host_kind??null,parent:n.parent??null,created:n.created,description:n.description??null}))}i(xt,"rosterNodes");async function Ut(e){return(await(await d()).prepareUncached(`SELECT * FROM node_rows
53
+ FROM warm_pool w JOIN node_rows n ON n.node_id = w.node_id`+(n===void 0?"":" WHERE w.recipe_key = ?")+" ORDER BY w.created";return(n===void 0?await e.prepareUncached(t).all():await e.prepareUncached(t).all(n)).map(i=>({node_id:i.node_id,recipe_key:i.recipe_key,created:i.created,status:i.status,pi_pid:i.pi_pid??null,pi_pid_identity:i.pi_pid_identity??null}))}r(x,"warmSpareRowsFor");async function Dt(){return await x(await d())}r(Dt,"listWarmSpares");async function At(e){return await(await d()).prepare("SELECT 1 FROM warm_pool WHERE node_id = ?").get(e)!==void 0}r(At,"isWarmSpare");function te(e){return e.status!=="active"&&e.status!=="idle"?!1:je(e.pi_pid,e.pi_pid_identity)==="alive"}r(te,"spareIsClaimable");async function gt(e,n,t={}){return await p(async a=>{const i=(await x(a,e)).find(te);return i===void 0||t.requestKey!==void 0&&(await a.prepareUncached("UPDATE create_requests SET node_id = ?, state = 'warm_claimed' WHERE request_key = ? AND node_id IS NULL").run(i.node_id,t.requestKey)).changes===0||(await a.prepare("DELETE FROM warm_pool WHERE node_id = ?").run(i.node_id)).changes===0?null:(await a.prepare("UPDATE nodes SET created = ?, deadline_at = ? WHERE node_id = ?").run(n,t.deadlineAt??null,i.node_id),t.outcomeDelivery!==void 0&&await z(a,i.node_id,t.outcomeDelivery),i.node_id)})}r(gt,"claimWarmSpare");async function kt(e){return(await x(await d(),e)).filter(te).length}r(kt,"warmSpareCount");async function vt(e){return(await(await d()).prepare("SELECT node_id FROM nodes WHERE parent = ? ORDER BY created").all(e)).map(n=>n.node_id)}r(vt,"childrenOf");async function xt(e){return(await(await d()).prepareUncached(`SELECT node_id, name, kind, mode, lifecycle, status, cwd, host_kind, parent, created, description
54
+ FROM node_rows WHERE ${m}${e===void 0?"":" AND node_id = ANY(?::text[])"} ORDER BY created`).all(...e===void 0?[]:[[...e]])).map(n=>({node_id:n.node_id,name:n.name,kind:n.kind,mode:n.mode,lifecycle:n.lifecycle,status:n.status,cwd:n.cwd,host_kind:n.host_kind??null,parent:n.parent??null,created:n.created,description:n.description??null}))}r(xt,"rosterNodes");async function Ut(e){return(await(await d()).prepareUncached(`SELECT * FROM node_rows
55
55
  WHERE parent IS NULL AND kind != 'human'
56
56
  AND status IN ('active','idle') AND cwd = ?
57
57
  AND ${m}
58
- ORDER BY created DESC`).all(e)).map(f)}i(Ut,"listResumableRoots");export*from"./tree.js";async function Wt(e,n,t){return await p(async a=>{const r=await a.prepare("SELECT status, final_report, frozen_at FROM nodes WHERE node_id = ? FOR UPDATE").get(e);return r===void 0?{kind:"missing"}:n(r)?{kind:"terminal",status:r.status,final_report:r.final_report}:{kind:"ran",result:await t()}})}i(Wt,"withFreshTerminalGuard");async function L(e){return await ve(e)}i(L,"hasUnreconciledManagedWorktree");async function ae(e,n={}){return!["done","dead","canceled"].includes(e.status)||e.pi_pid!==null||e.frozen_at!==null||await L(e.node_id)||e.node_id===H()||B(e)?!1:n.pastTtl===!0||!["crashed","stranded",null].includes(e.terminal_reason??null)}i(ae,"isCollectible");async function U(e){if(e.length===0)return[];const n=e.map(()=>"?").join(","),t=await(await d()).prepareUncached(`SELECT s.session_id, s.transcript_path, s.node_id, n.grantee FROM sessions s JOIN node_rows n ON n.node_id = s.node_id WHERE s.node_id IN (${n}) AND s.session_id IS NOT NULL ORDER BY s.created_at, s.seq`).all(...e);return[...new Map(t.map(a=>[a.session_id,{id:a.session_id,path:a.transcript_path,dir:S(T(a.grantee).conversations,a.node_id)}])).values()]}i(U,"nodeConversationIds");async function W(e){const n=await d(),t=n.prepare("SELECT 1 FROM sessions WHERE session_id = ? LIMIT 1"),a=n.prepare(`SELECT 1 FROM nodes n WHERE n.fork_source_file LIKE '%\\_' || ? || '.jsonl' ESCAPE '\\'
59
- AND NOT EXISTS (SELECT 1 FROM sessions s WHERE s.node_id = n.node_id) LIMIT 1`);for(const{id:r,path:o,dir:s}of e){if(await t.get(r)!==void 0||await a.get(r)!==void 0)continue;const c=o!==null&&_e(o,{throwIfNoEntry:!1})!==void 0&&rn(s,o)?o:void 0;try{await he().delete(r,c)}catch(u){if(!(u instanceof Oe))throw u}}}i(W,"deleteNodeConversations");function rn(e,n){try{const t=me(M(e),S(M(P(n)),we(n)));return t!==""&&t!==".."&&!t.startsWith(`..${Re}`)&&!ye(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}i(rn,"isBeneath");async function b(e,n){const t=await D(e,n);return t===null||t.deleted_at!==null?!1:(await Ve(e,t),!0)}i(b,"deleteNodeObject");async function j(e){return{nodeId:e,app:await O(e)===null?null:await Me(e)}}i(j,"nodeFiles");async function ie({nodeId:e,app:n}){n!==null&&$(T(n).nodes,await $e(e,n)),$(P(Y(e)),Y(e))}i(ie,"removeNodeAppTrees");function re({nodeId:e}){return[He(e)]}i(re,"nodeOwnedDirs");function oe({nodeId:e,app:n}){if(n!==null)try{pe(S(T(n).conversations,e))}catch(t){if(!["ENOENT","ENOTEMPTY"].includes(t.code??""))throw t}}i(oe,"removeNodeConversationDir");async function I(e){await ie(e);for(const n of re(e))fe(n,{recursive:!0,force:!0});oe(e)}i(I,"removeNodeFiles");async function se(e){const n=await q(e);if(n.length>0)throw new Error(`the sandbox of node(s) ${n.join(", ")} could not be deleted; the node rows are kept`)}i(se,"requireSandboxesDeleted");async function bt(e){if(await L(e))return{deleted:!1};await se([e]);const n=await j(e),t=await U([e]),a=await p(async r=>(await b(r,e),{deleted:!0}));return await W(t),await I(n),a}i(bt,"deleteNode");async function jt(e){const n=[...new Set(e)];if(n.length===0)return[];const t=await y(n,L);if(t.length>0)throw new Error(`refusing to delete nodes with unreconciled managed worktrees: ${t.join(", ")}`);await se(n);const a=await h(n,j),r=await U(n),o=n.map(()=>"?").join(","),s=(await(await d()).prepareUncached(`SELECT node_id FROM nodes WHERE node_id IN (${o}) ORDER BY created`).all(...n)).map(({node_id:u})=>u),c=await y(s,async u=>await p(async _=>await b(_,u)));await W(r);for(const u of c){const _=a[n.indexOf(u)];await C(_,async()=>await I(_))}return c}i(jt,"deleteNodes");async function It(e){const n=e.dryRun??!1,t=e.includeStale??!1,a=Date.now()-e.ttlDays*864e5,r=new Date(a).toISOString(),o=H()??"",s=await d(),c=i(l=>ue(l)<a,"quiet"),u=i(l=>({node_id:l.node_id,status:l.status,created:l.created}),"toPruned"),_=await on(),w=(await y((await s.prepare(`SELECT * FROM node_rows
58
+ ORDER BY created DESC`).all(e)).map(f)}r(Ut,"listResumableRoots");export*from"./tree.js";async function Wt(e,n,t){return await p(async a=>{const i=await a.prepare("SELECT status, final_report, frozen_at FROM nodes WHERE node_id = ? FOR UPDATE").get(e);return i===void 0?{kind:"missing"}:n(i)?{kind:"terminal",status:i.status,final_report:i.final_report}:{kind:"ran",result:await t()}})}r(Wt,"withFreshTerminalGuard");async function L(e){return await ve(e)}r(L,"hasUnreconciledManagedWorktree");async function ae(e,n={}){return!["done","dead","canceled"].includes(e.status)||e.pi_pid!==null||e.frozen_at!==null||await L(e.node_id)||e.node_id===H()||B(e)?!1:n.pastTtl===!0||!["crashed","stranded",null].includes(e.terminal_reason??null)}r(ae,"isCollectible");async function U(e){if(e.length===0)return[];const n=e.map(()=>"?").join(","),t=await(await d()).prepareUncached(`SELECT s.session_id, s.transcript_path, s.node_id, n.grantee FROM sessions s JOIN node_rows n ON n.node_id = s.node_id WHERE s.node_id IN (${n}) AND s.session_id IS NOT NULL ORDER BY s.created_at, s.seq`).all(...e);return[...new Map(t.map(a=>[a.session_id,{id:a.session_id,path:a.transcript_path,dir:S(T(a.grantee).conversations,a.node_id)}])).values()]}r(U,"nodeConversationIds");async function W(e){const n=await d(),t=n.prepare("SELECT 1 FROM sessions WHERE session_id = ? LIMIT 1"),a=n.prepare(`SELECT 1 FROM nodes n WHERE n.fork_source_file LIKE '%\\_' || ? || '.jsonl' ESCAPE '\\'
59
+ AND NOT EXISTS (SELECT 1 FROM sessions s WHERE s.node_id = n.node_id) LIMIT 1`);for(const{id:i,path:o,dir:s}of e){if(await t.get(i)!==void 0||await a.get(i)!==void 0)continue;const c=o!==null&&_e(o,{throwIfNoEntry:!1})!==void 0&&rn(s,o)?o:void 0;try{await he().delete(i,c)}catch(u){if(!(u instanceof Oe))throw u}}}r(W,"deleteNodeConversations");function rn(e,n){try{const t=me(M(e),S(M(P(n)),we(n)));return t!==""&&t!==".."&&!t.startsWith(`..${Re}`)&&!ye(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}r(rn,"isBeneath");async function b(e,n){const t=await D(e,n);return t===null||t.deleted_at!==null?!1:(await Ve(e,t),!0)}r(b,"deleteNodeObject");async function j(e){return{nodeId:e,app:await O(e)===null?null:await Me(e)}}r(j,"nodeFiles");async function ie({nodeId:e,app:n}){n!==null&&$(T(n).nodes,await $e(e,n)),$(P(Y(e)),Y(e))}r(ie,"removeNodeAppTrees");function re({nodeId:e}){return[He(e)]}r(re,"nodeOwnedDirs");function oe({nodeId:e,app:n}){if(n!==null)try{pe(S(T(n).conversations,e))}catch(t){if(!["ENOENT","ENOTEMPTY"].includes(t.code??""))throw t}}r(oe,"removeNodeConversationDir");async function I(e){await ie(e);for(const n of re(e))fe(n,{recursive:!0,force:!0});oe(e)}r(I,"removeNodeFiles");async function se(e){const n=await q(e);if(n.length>0)throw new Error(`the sandbox of node(s) ${n.join(", ")} could not be deleted; the node rows are kept`)}r(se,"requireSandboxesDeleted");async function bt(e){if(await L(e))return{deleted:!1};await se([e]);const n=await j(e),t=await U([e]),a=await p(async i=>(await b(i,e),{deleted:!0}));return await W(t),await I(n),a}r(bt,"deleteNode");async function jt(e){const n=[...new Set(e)];if(n.length===0)return[];const t=await y(n,L);if(t.length>0)throw new Error(`refusing to delete nodes with unreconciled managed worktrees: ${t.join(", ")}`);await se(n);const a=await h(n,j),i=await U(n),o=n.map(()=>"?").join(","),s=(await(await d()).prepareUncached(`SELECT node_id FROM nodes WHERE node_id IN (${o}) ORDER BY created`).all(...n)).map(({node_id:u})=>u),c=await y(s,async u=>await p(async _=>await b(_,u)));await W(i);for(const u of c){const _=a[n.indexOf(u)];await C(_,async()=>await I(_))}return c}r(jt,"deleteNodes");async function It(e){const n=e.dryRun??!1,t=e.includeStale??!1,a=Date.now()-e.ttlDays*864e5,i=new Date(a).toISOString(),o=H()??"",s=await d(),c=r(l=>ue(l)<a,"quiet"),u=r(l=>({node_id:l.node_id,status:l.status,created:l.created}),"toPruned"),_=await on(),w=(await y((await s.prepare(`SELECT * FROM node_rows
60
60
  WHERE status IN ('dead', 'done', 'canceled') AND created < ?
61
- ORDER BY created`).all(r)).map(f),async l=>await ae(l,{pastTtl:!0})&&c(l)&&!_.has(l.node_id)&&!await e.held(l.node_id))).map(u),N=t?(await y((await s.prepare(`SELECT * FROM node_rows
61
+ ORDER BY created`).all(i)).map(f),async l=>await ae(l,{pastTtl:!0})&&c(l)&&!_.has(l.node_id)&&!await e.held(l.node_id))).map(u),N=t?(await y((await s.prepare(`SELECT * FROM node_rows
62
62
  WHERE status IN ('active', 'idle') AND created < ?
63
- ORDER BY created`).all(r)).map(f),async l=>l.node_id!==o&&!be(l.pi_pid??null)&&(l.frozen_at??null)===null&&(l.respawn_not_before??null)===null&&l.intent!=="idle-release"&&!B(l)&&!await Le(l.node_id)&&!await L(l.node_id)&&c(l)&&!await e.held(l.node_id))).map(u):[],R=await F([...w,...N]);return n||R.length===0?{pruned:R,dryRun:n}:{pruned:await de(R,e.removeDirs),dryRun:n}}i(It,"pruneNodes");async function on(){const e=await(await d()).prepare(`SELECT DISTINCT d.owner AS owner FROM watches w
63
+ ORDER BY created`).all(i)).map(f),async l=>l.node_id!==o&&!be(l.pi_pid??null)&&(l.frozen_at??null)===null&&(l.respawn_not_before??null)===null&&l.intent!=="idle-release"&&!B(l)&&!await Le(l.node_id)&&!await L(l.node_id)&&c(l)&&!await e.held(l.node_id))).map(u):[],R=await F([...w,...N]);return n||R.length===0?{pruned:R,dryRun:n}:{pruned:await de(R,e.removeDirs),dryRun:n}}r(It,"pruneNodes");async function on(){const e=await(await d()).prepare(`SELECT DISTINCT d.owner AS owner FROM watches w
64
64
  JOIN objects d ON d.id = w.object AND d.type = 'document' AND d.deleted_at IS NULL
65
65
  JOIN objects o ON o.id = w.watcher AND o.deleted_at IS NULL
66
66
  LEFT JOIN nodes n ON n.node_id = w.watcher
67
- WHERE w.watcher != d.owner AND d.owner IS NOT NULL AND (n.node_id IS NULL OR n.status IN ('active', 'idle'))`).all();return new Set(e.map(n=>n.owner))}i(on,"ownersOfWatchedDocuments");async function F(e){const t=(await d()).prepare("SELECT node_id FROM nodes WHERE run_id = ? AND node_id != ?"),a=new Set(e.map(r=>r.node_id));return await y(e,async r=>(await t.all(r.node_id,r.node_id)).every(o=>a.has(o.node_id)))}i(F,"retainRunRootsWithMembers");async function de(e,n){const t=new Set(await q(e.map(s=>s.node_id))),a=t.size===0?e:await F(e.filter(s=>!t.has(s.node_id)));if(a.length===0)return[];const r=await h(a,async s=>await j(s.node_id)),o=await U(a.map(s=>s.node_id));for(const s of a)await p(async c=>await b(c,s.node_id));if(await W(o),n!==void 0){for(const s of r)await C(s,async()=>{await ie(s),oe(s)});return n(r.flatMap(re)),a}for(const s of r)await C(s,async()=>await I(s));return a}i(de,"deletePrunedNodes");async function C(e,n){try{await n()}catch(t){Se({level:"error",event:"canvas.node_files.remove_failed",error:t,fields:{node_id:e.nodeId}})}}i(C,"eachNodeBestEffort");function ue(e){let n=0;for(const t of[e.created,e.launched_at,e.last_settled_at,e.finalized_at,e.outcome_at,e.last_activity_at]){if(t==null)continue;const a=Date.parse(t);Number.isFinite(a)&&a>n&&(n=a)}try{const t=Ee(S(Ce(e.node_id),"telemetry.json"),{throwIfNoEntry:!1});t!==void 0&&t.mtimeMs>n&&(n=t.mtimeMs)}catch{}return n}i(ue,"lastActivityMs");async function Ft(e){const n=e.dryRun??!1,t=await en(),a=await y(t,async u=>await ae(u)&&!await e.held(u.node_id)),r=t.length-a.length,o=Math.max(0,e.maxNodes-r),s=a.map(u=>({row:u,recency:ue(u)})).sort((u,_)=>_.recency-u.recency).slice(o).map(({row:u})=>({node_id:u.node_id,status:u.status,created:u.created})),c=await F(s);return n||c.length===0?{pruned:c,dryRun:n}:{pruned:await de(c),dryRun:n}}i(Ft,"pruneToLimit");export{g as CREATE_LEASE_MS,zn as CREATE_LEASE_RENEW_MS,ne as PARKED_RESIDENT_SQL,an as RESUMABLE_NODE_SQL,Kn as abandonCreateRequest,Fn as assertRunNotDeleting,yt as browseNodes,Gn as canonicalSessionFile,vt as childrenOf,Jn as claimCreateLease,gt as claimWarmSpare,ut as clearFinalReportIfMatches,ft as clearFrozen,Vn as completeCreateRequest,Qn as createLeaseLive,Cn as createNode,bt as deleteNode,jt as deleteNodes,nt as dueNodeDeadlines,Mn as findCreateRequest,Xn as findNodeBySessionFile,dt as getFinalReport,O as getNode,Hn as getNodes,Zn as getRow,et as getRowByPane,Nt as graphNodes,ae as isCollectible,At as isWarmSpare,ue as lastActivityMs,en as listNodes,wt as listNodesByProfile,St as listNodesForSupervision,Ot as listParkedResidentsWithWakeMail,Ut as listResumableRoots,Rt as listTerminalPlacementResidue,Dt as listWarmSpares,j as nodeFiles,tn as nodesForSupervisionSql,$n as pruneExpiredCreateRequests,It as pruneNodes,Ft as pruneToLimit,qn as recordCreateRequestNode,lt as recordLaunch,Et as recordRespawnAttempt,_t as recordSettledTurn,Lt as registerWarmSpare,I as removeNodeFiles,Yn as renewCreateLease,Pn as reserveCreateRequest,Bn as reserveCreateRequestNode,ht as resumableNodeCwds,xt as rosterNodes,pt as setFrozen,ot as setIntent,tt as setNodeDeadline,ct as setPresence,rt as setStatus,at as shiftProfileNodeDeadlines,nn as terminalPlacementResidueSql,st as transitionStatusIntent,Tt as unregisterWarmSpare,it as updateNode,mt as updateNodeTelemetry,kt as warmSpareCount,Wt as withFreshTerminalGuard};
67
+ WHERE w.watcher != d.owner AND d.owner IS NOT NULL AND (n.node_id IS NULL OR n.status IN ('active', 'idle'))`).all();return new Set(e.map(n=>n.owner))}r(on,"ownersOfWatchedDocuments");async function F(e){const t=(await d()).prepare("SELECT node_id FROM nodes WHERE run_id = ? AND node_id != ?"),a=new Set(e.map(i=>i.node_id));return await y(e,async i=>(await t.all(i.node_id,i.node_id)).every(o=>a.has(o.node_id)))}r(F,"retainRunRootsWithMembers");async function de(e,n){const t=new Set(await q(e.map(s=>s.node_id))),a=t.size===0?e:await F(e.filter(s=>!t.has(s.node_id)));if(a.length===0)return[];const i=await h(a,async s=>await j(s.node_id)),o=await U(a.map(s=>s.node_id));for(const s of a)await p(async c=>await b(c,s.node_id));if(await W(o),n!==void 0){for(const s of i)await C(s,async()=>{await ie(s),oe(s)});return n(i.flatMap(re)),a}for(const s of i)await C(s,async()=>await I(s));return a}r(de,"deletePrunedNodes");async function C(e,n){try{await n()}catch(t){Se({level:"error",event:"canvas.node_files.remove_failed",error:t,fields:{node_id:e.nodeId}})}}r(C,"eachNodeBestEffort");function ue(e){let n=0;for(const t of[e.created,e.launched_at,e.last_settled_at,e.finalized_at,e.outcome_at,e.last_activity_at]){if(t==null)continue;const a=Date.parse(t);Number.isFinite(a)&&a>n&&(n=a)}try{const t=Ee(S(Ce(e.node_id),"telemetry.json"),{throwIfNoEntry:!1});t!==void 0&&t.mtimeMs>n&&(n=t.mtimeMs)}catch{}return n}r(ue,"lastActivityMs");async function Ft(e){const n=e.dryRun??!1,t=await en(),a=await y(t,async u=>await ae(u)&&!await e.held(u.node_id)),i=t.length-a.length,o=Math.max(0,e.maxNodes-i),s=a.map(u=>({row:u,recency:ue(u)})).sort((u,_)=>_.recency-u.recency).slice(o).map(({row:u})=>({node_id:u.node_id,status:u.status,created:u.created})),c=await F(s);return n||c.length===0?{pruned:c,dryRun:n}:{pruned:await de(c),dryRun:n}}r(Ft,"pruneToLimit");export{g as CREATE_LEASE_MS,zn as CREATE_LEASE_RENEW_MS,ne as PARKED_RESIDENT_SQL,an as RESUMABLE_NODE_SQL,Kn as abandonCreateRequest,Fn as assertRunNotDeleting,yt as browseNodes,Gn as canonicalSessionFile,vt as childrenOf,Jn as claimCreateLease,gt as claimWarmSpare,ut as clearFinalReportIfMatches,ft as clearFrozen,Vn as completeCreateRequest,Qn as createLeaseLive,Cn as createNode,bt as deleteNode,jt as deleteNodes,nt as dueNodeDeadlines,Mn as findCreateRequest,Xn as findNodeBySessionFile,dt as getFinalReport,O as getNode,Hn as getNodes,Zn as getRow,et as getRowByPane,Nt as graphNodes,ae as isCollectible,At as isWarmSpare,ue as lastActivityMs,en as listNodes,wt as listNodesByProfile,St as listNodesForSupervision,Ot as listParkedResidentsWithWakeMail,Ut as listResumableRoots,Rt as listTerminalPlacementResidue,Dt as listWarmSpares,j as nodeFiles,tn as nodesForSupervisionSql,$n as pruneExpiredCreateRequests,It as pruneNodes,Ft as pruneToLimit,qn as recordCreateRequestNode,lt as recordLaunch,Et as recordRespawnAttempt,_t as recordSettledTurn,Lt as registerWarmSpare,I as removeNodeFiles,Yn as renewCreateLease,Pn as reserveCreateRequest,Bn as reserveCreateRequestNode,ht as resumableNodeCwds,xt as rosterNodes,pt as setFrozen,ot as setIntent,tt as setNodeDeadline,ct as setPresence,rt as setStatus,at as shiftProfileNodeDeadlines,nn as terminalPlacementResidueSql,st as transitionStatusIntent,Tt as unregisterWarmSpare,it as updateNode,mt as updateNodeTelemetry,kt as warmSpareCount,Wt as withFreshTerminalGuard};
@@ -95,7 +95,7 @@ export interface ResolvedRef {
95
95
  /** Rendered body. */
96
96
  body: string;
97
97
  /** The verbatim record (session bytes or jsonl line); null for an inbox entry. */
98
- raw: string | null;
98
+ raw: (() => Promise<string | null>) | null;
99
99
  path: string | null;
100
100
  }
101
101
  /** Resolve a `<node-id>:inbox/<n>`, `<node-id>:session` or
@@ -1,14 +1,14 @@
1
- var S=Object.defineProperty;var d=(n,s)=>S(n,"name",{value:s,configurable:!0});import{envNodeId as M}from"../../shared/env.js";import{getNode as p,listNodes as j,view as v}from"./canvas.js";import{openDb as E}from"./db.js";import{readTextIfExists as O}from"../fs-utils.js";import{conversationIdFromPath as y,conversationStore as g,ConversationNotFoundError as I}from"../conversation-store/index.js";import{reportBodyByName as C}from"../feed/reports.js";import{readStamps as A}from"../runtime/stamp/protocol.js";import{forEachAsync as B}from"../async-array.js";const nn=["human","inbox","wake","revive","restart-continuation","stop-guard","park","recovery","context-nudge","kickoff","unknown"],en=["user","assistant","toolResult"];async function R(){const n=M();if(n!==void 0&&n!==""){const s=await p(n);if(s!==null)return s.cwd}return process.cwd()}d(R,"callerCwd");function x(n){const s=Date.parse(n);return Number.isNaN(s)?0:s}d(x,"toMs");async function k(n){return(await(await E()).prepare(`SELECT m.created_at, m.sender_node_id, d.urgency, m.kind, m.label, m.body_ref, m.body_json
1
+ var S=Object.defineProperty;var a=(n,s)=>S(n,"name",{value:s,configurable:!0});import{envNodeId as M}from"../../shared/env.js";import{getNode as p,listNodes as j,view as v}from"./canvas.js";import{openDb as E}from"./db.js";import{readTextIfExists as O}from"../fs-utils.js";import{conversationIdFromPath as y,conversationStore as g,ConversationNotFoundError as I}from"../conversation-store/index.js";import{reportBodyByName as C}from"../feed/reports.js";import{readStamps as A}from"../runtime/stamp/protocol.js";import{forEachAsync as B}from"../async-array.js";const nn=["human","inbox","wake","revive","restart-continuation","stop-guard","park","recovery","context-nudge","kickoff","unknown"],en=["user","assistant","toolResult"];async function R(){const n=M();if(n!==void 0&&n!==""){const s=await p(n);if(s!==null)return s.cwd}return process.cwd()}a(R,"callerCwd");function x(n){const s=Date.parse(n);return Number.isNaN(s)?0:s}a(x,"toMs");async function k(n){return(await(await E()).prepare(`SELECT m.created_at, m.sender_node_id, d.urgency, m.kind, m.label, m.body_ref, m.body_json
2
2
  FROM deliveries d JOIN messages m ON m.message_id = d.message_id
3
3
  WHERE d.destination_id = ? AND d.wake = 1
4
- ORDER BY m.seq, d.created_at, d.delivery_id`).all(n)).map(e=>({ts:e.created_at,from:e.sender_node_id,tier:e.urgency,kind:e.kind,label:e.label,ref:e.body_ref,data:e.body_json===null?null:JSON.parse(e.body_json)}))}d(k,"allInboxEntries");async function _(n){const s=[`from: ${n.from??"system"}`,`tier: ${n.tier}`].join(`
5
- `),e=`[${n.kind}] ${n.label}`,t=typeof n.data=="object"&&n.data!==null&&!Array.isArray(n.data)?n.data.body:void 0,i=typeof t=="string"?t.trim():"",o=typeof t=="string",r=typeof n.data=="object"&&n.data!==null&&!Array.isArray(n.data)?n.data.body_full:void 0,c=n.ref!==null?o?typeof r=="string"?r:O(n.ref)??"":await C(n.ref)??"":i,u=c!==""&&c!==n.label,a=[s,e];return n.ref!==null&&a.push(`ref: ${n.ref}`),u&&a.push(c),a.join(`
4
+ ORDER BY m.seq, d.created_at, d.delivery_id`).all(n)).map(e=>({ts:e.created_at,from:e.sender_node_id,tier:e.urgency,kind:e.kind,label:e.label,ref:e.body_ref,data:e.body_json===null?null:JSON.parse(e.body_json)}))}a(k,"allInboxEntries");async function _(n){const s=[`from: ${n.from??"system"}`,`tier: ${n.tier}`].join(`
5
+ `),e=`[${n.kind}] ${n.label}`,t=typeof n.data=="object"&&n.data!==null&&!Array.isArray(n.data)?n.data.body:void 0,i=typeof t=="string"?t.trim():"",o=typeof t=="string",r=typeof n.data=="object"&&n.data!==null&&!Array.isArray(n.data)?n.data.body_full:void 0,c=n.ref!==null?o?typeof r=="string"?r:O(n.ref)??"":await C(n.ref)??"":i,u=c!==""&&c!==n.label,d=[s,e];return n.ref!==null&&d.push(`ref: ${n.ref}`),u&&d.push(c),d.join(`
6
6
 
7
- `)}d(_,"inboxEntryBody");async function D(n,s,e,t){const i=`inbox/${String(t).padStart(6,"0")}`,o=await _(e),r={ref:`${n.node_id}:${i}`,nodeId:n.node_id,relpath:i,source:"inbox",ts:e.ts,tsMs:x(e.ts),title:`[${e.kind}] from ${e.from??"system"}: ${e.label}`,nodeName:n.name,nodeKind:n.kind,nodeStatus:n.status,nodeCwd:n.cwd,nodeDesc:s,loadBody:d(()=>o,"loadBody"),origin:"inbox"};return typeof e.from=="string"&&e.from!==""&&(r.from=e.from),r}d(D,"inboxArtifact");async function N(n){const s=(await p(n))?.pi_session_file,e=typeof s=="string"?y(s):null;if(e===null)return null;try{return(await g().header(e)).path}catch(t){if(t instanceof I)return null;throw t}}d(N,"resolveSessionFile");function T(n){if(typeof n=="string")return n;if(!Array.isArray(n))return"";const s=[];for(const e of n){if(e===null||typeof e!="object")continue;const t=e;t.type==="text"&&typeof t.text=="string"?s.push(t.text):t.type==="toolCall"&&s.push(`Tool: ${typeof t.name=="string"?t.name:"call"}`)}return s.join(`
8
- `)}d(T,"textFromBlocks");function F(n){return n==null?"unknown":n.type==="human"?"human":n.kind}d(F,"originToken");function L(n){if(n==null||n.type!=="runtime")return;const s=n.entries;if(s===void 0||s.length===0)return;const e=new Set;for(const t of s){const i=t.fromName??t.from;typeof i=="string"&&i!==""&&e.add(i)}return e.size===0?void 0:[...e].join(", ")}d(L,"sendersOf");async function $(n){const s=await N(n);if(s===null)return[];const e=(await g().read(y(s))).entries,t=new Map;for(const o of A(e)){if(o.kind!=="message")continue;const r=o.payload;typeof r.msgTs=="number"&&t.set(r.msgTs,r.origin)}const i=[];for(const o of e){if(o===null||typeof o!="object")continue;const r=o;if(r.type!=="message")continue;const c=r.message;if(c===null||typeof c!="object")continue;const u=c,a=typeof u.role=="string"?u.role:"";if(a==="")continue;const f=typeof u.timestamp=="number"?u.timestamp:void 0,l=typeof r.timestamp=="string"?r.timestamp:f!==void 0?new Date(f).toISOString():"",m=T(u.content),b={index:i.length,role:a,text:m,ts:l,tsMs:f??x(l)};if(a==="user"){const w=f!==void 0&&t.has(f)?t.get(f):null;b.origin=F(w);const h=L(w);h!==void 0&&(b.from=h)}i.push(b)}return i}d($,"sessionMessages");async function J(n,s){const e=(await g().read(y(n))).entries;let t=0;for(const i of e){if(i.type!=="message")continue;const o=i.message;if(!(o===null||typeof o!="object"||typeof o.role!="string")){if(t===s)return JSON.stringify(i);t++}}return null}d(J,"rawSessionLine");function K(n,s,e){const t=`session/${String(e.index).padStart(6,"0")}`,i=e.text.split(`
9
- `).map(r=>r.trim()).find(r=>r!=="")??"",o={ref:`${n.node_id}:${t}`,nodeId:n.node_id,relpath:t,source:"transcript",ts:e.ts,tsMs:e.tsMs,title:`[${e.role}] ${i.length>80?`${i.slice(0,80)}\u2026`:i}`,nodeName:n.name,nodeKind:n.kind,nodeStatus:n.status,nodeCwd:n.cwd,nodeDesc:s,loadBody:d(()=>e.text,"loadBody"),role:e.role};return e.origin!==void 0&&(o.origin=e.origin),e.from!==void 0&&(o.from=e.from),o}d(K,"transcriptArtifact");async function W(n){return(await p(n))?.description??""}d(W,"nodeDescOf");async function tn(n,s){const e=await P(n),t=s.kinds,i=s.statuses,o=e.filter(a=>!(t!==void 0&&t.length>0&&!t.includes(a.kind)||i!==void 0&&i.length>0&&!i.includes(a.status))),r=s.types!==void 0&&s.types.length>0?s.types:["inbox"],c=new Set(r),u=[];for(const a of o){const f=await W(a.node_id);if(c.has("inbox")&&await B(await k(a.node_id),async(l,m)=>u.push(await D(a,f,l,m))),c.has("transcript"))for(const l of await $(a.node_id))u.push(K(a,f,l))}return u.filter(a=>s.sinceMs!==void 0&&a.tsMs<s.sinceMs||s.untilMs!==void 0&&a.tsMs>s.untilMs?!1:G(a,s))}d(tn,"buildCorpus");function G(n,s){const{origins:e,roles:t,from:i}=s;return!(e!==void 0&&e.length>0&&(n.origin===void 0||!e.includes(n.origin))||t!==void 0&&t.length>0&&(n.role===void 0||!t.includes(n.role))||i!==void 0&&i!==""&&(n.from===void 0||!n.from.toLowerCase().includes(i.toLowerCase())))}d(G,"matchesMessageFilters");function sn(n,s){const e=new Map;for(const t of n){let i;switch(s){case"origin":i=t.origin;break;case"role":i=t.role;break;case"node":i=`${t.nodeName} (${t.nodeId})`;break;case"kind":i=t.nodeKind;break;case"type":i=t.source;break;case"day":i=t.ts.slice(0,10)||void 0;break}i===void 0||i===""||e.set(i,(e.get(i)??0)+1)}return[...e.entries()].map(([t,i])=>({key:t,count:i})).sort((t,i)=>i.count-t.count||t.key.localeCompare(i.key))}d(sn,"groupCorpus");async function P(n){const s=await j(),e=new Map(s.map(i=>[i.node_id,i]));if(n.nodes!==void 0&&n.nodes.length>0)return n.nodes.map(i=>e.get(i)).filter(i=>i!==void 0);if(n.under!==void 0&&n.under!=="")return[n.under,...await v(n.under)].map(o=>e.get(o)).filter(o=>o!==void 0);if(n.allCwds===!0)return s;const t=n.cwd!==void 0&&n.cwd!==""?n.cwd:await R();return s.filter(i=>i.cwd===t)}d(P,"scopedRows");async function on(n){const s=n.indexOf(":");if(s===-1)return null;const e=n.slice(0,s),t=n.slice(s+1),i=await p(e);if(i===null)return null;if(t.startsWith("inbox/")){const o=Number(t.slice(6)),r=(await k(e))[o];return r===void 0?null:{nodeId:e,relpath:t,source:"inbox",ts:r.ts,nodeName:i.name,body:await _(r),raw:null,path:null}}if(t==="session"||t.startsWith("session/")){const o=await N(e);if(o===null)return null;const r=await $(e);if(t==="session"){const a=r.map(f=>`## ${f.role}${f.origin!==void 0?` (origin: ${f.origin})`:""}
7
+ `)}a(_,"inboxEntryBody");async function D(n,s,e,t){const i=`inbox/${String(t).padStart(6,"0")}`,o=await _(e),r={ref:`${n.node_id}:${i}`,nodeId:n.node_id,relpath:i,source:"inbox",ts:e.ts,tsMs:x(e.ts),title:`[${e.kind}] from ${e.from??"system"}: ${e.label}`,nodeName:n.name,nodeKind:n.kind,nodeStatus:n.status,nodeCwd:n.cwd,nodeDesc:s,loadBody:a(()=>o,"loadBody"),origin:"inbox"};return typeof e.from=="string"&&e.from!==""&&(r.from=e.from),r}a(D,"inboxArtifact");async function N(n){const s=(await p(n))?.pi_session_file,e=typeof s=="string"?y(s):null;if(e===null)return null;try{return(await g().header(e)).path}catch(t){if(t instanceof I)return null;throw t}}a(N,"resolveSessionFile");function T(n){if(typeof n=="string")return n;if(!Array.isArray(n))return"";const s=[];for(const e of n){if(e===null||typeof e!="object")continue;const t=e;t.type==="text"&&typeof t.text=="string"?s.push(t.text):t.type==="toolCall"&&s.push(`Tool: ${typeof t.name=="string"?t.name:"call"}`)}return s.join(`
8
+ `)}a(T,"textFromBlocks");function F(n){return n==null?"unknown":n.type==="human"?"human":n.kind}a(F,"originToken");function L(n){if(n==null||n.type!=="runtime")return;const s=n.entries;if(s===void 0||s.length===0)return;const e=new Set;for(const t of s){const i=t.fromName??t.from;typeof i=="string"&&i!==""&&e.add(i)}return e.size===0?void 0:[...e].join(", ")}a(L,"sendersOf");async function $(n){const s=await N(n);if(s===null)return[];const e=(await g().read(y(s))).entries,t=new Map;for(const o of A(e)){if(o.kind!=="message")continue;const r=o.payload;typeof r.msgTs=="number"&&t.set(r.msgTs,r.origin)}const i=[];for(const o of e){if(o===null||typeof o!="object")continue;const r=o;if(r.type!=="message")continue;const c=r.message;if(c===null||typeof c!="object")continue;const u=c,d=typeof u.role=="string"?u.role:"";if(d==="")continue;const f=typeof u.timestamp=="number"?u.timestamp:void 0,l=typeof r.timestamp=="string"?r.timestamp:f!==void 0?new Date(f).toISOString():"",m=T(u.content),b={index:i.length,role:d,text:m,ts:l,tsMs:f??x(l)};if(d==="user"){const w=f!==void 0&&t.has(f)?t.get(f):null;b.origin=F(w);const h=L(w);h!==void 0&&(b.from=h)}i.push(b)}return i}a($,"sessionMessages");async function J(n,s){const e=(await g().read(y(n))).entries;let t=0;for(const i of e){if(i.type!=="message")continue;const o=i.message;if(!(o===null||typeof o!="object"||typeof o.role!="string")){if(t===s)return JSON.stringify(i);t++}}return null}a(J,"rawSessionLine");function K(n,s,e){const t=`session/${String(e.index).padStart(6,"0")}`,i=e.text.split(`
9
+ `).map(r=>r.trim()).find(r=>r!=="")??"",o={ref:`${n.node_id}:${t}`,nodeId:n.node_id,relpath:t,source:"transcript",ts:e.ts,tsMs:e.tsMs,title:`[${e.role}] ${i.length>80?`${i.slice(0,80)}\u2026`:i}`,nodeName:n.name,nodeKind:n.kind,nodeStatus:n.status,nodeCwd:n.cwd,nodeDesc:s,loadBody:a(()=>e.text,"loadBody"),role:e.role};return e.origin!==void 0&&(o.origin=e.origin),e.from!==void 0&&(o.from=e.from),o}a(K,"transcriptArtifact");async function W(n){return(await p(n))?.description??""}a(W,"nodeDescOf");async function tn(n,s){const e=await P(n),t=s.kinds,i=s.statuses,o=e.filter(d=>!(t!==void 0&&t.length>0&&!t.includes(d.kind)||i!==void 0&&i.length>0&&!i.includes(d.status))),r=s.types!==void 0&&s.types.length>0?s.types:["inbox"],c=new Set(r),u=[];for(const d of o){const f=await W(d.node_id);if(c.has("inbox")&&await B(await k(d.node_id),async(l,m)=>u.push(await D(d,f,l,m))),c.has("transcript"))for(const l of await $(d.node_id))u.push(K(d,f,l))}return u.filter(d=>s.sinceMs!==void 0&&d.tsMs<s.sinceMs||s.untilMs!==void 0&&d.tsMs>s.untilMs?!1:G(d,s))}a(tn,"buildCorpus");function G(n,s){const{origins:e,roles:t,from:i}=s;return!(e!==void 0&&e.length>0&&(n.origin===void 0||!e.includes(n.origin))||t!==void 0&&t.length>0&&(n.role===void 0||!t.includes(n.role))||i!==void 0&&i!==""&&(n.from===void 0||!n.from.toLowerCase().includes(i.toLowerCase())))}a(G,"matchesMessageFilters");function sn(n,s){const e=new Map;for(const t of n){let i;switch(s){case"origin":i=t.origin;break;case"role":i=t.role;break;case"node":i=`${t.nodeName} (${t.nodeId})`;break;case"kind":i=t.nodeKind;break;case"type":i=t.source;break;case"day":i=t.ts.slice(0,10)||void 0;break}i===void 0||i===""||e.set(i,(e.get(i)??0)+1)}return[...e.entries()].map(([t,i])=>({key:t,count:i})).sort((t,i)=>i.count-t.count||t.key.localeCompare(i.key))}a(sn,"groupCorpus");async function P(n){const s=await j(),e=new Map(s.map(i=>[i.node_id,i]));if(n.nodes!==void 0&&n.nodes.length>0)return n.nodes.map(i=>e.get(i)).filter(i=>i!==void 0);if(n.under!==void 0&&n.under!=="")return[n.under,...await v(n.under)].map(o=>e.get(o)).filter(o=>o!==void 0);if(n.allCwds===!0)return s;const t=n.cwd!==void 0&&n.cwd!==""?n.cwd:await R();return s.filter(i=>i.cwd===t)}a(P,"scopedRows");async function on(n){const s=n.indexOf(":");if(s===-1)return null;const e=n.slice(0,s),t=n.slice(s+1),i=await p(e);if(i===null)return null;if(t.startsWith("inbox/")){const o=Number(t.slice(6)),r=(await k(e))[o];return r===void 0?null:{nodeId:e,relpath:t,source:"inbox",ts:r.ts,nodeName:i.name,body:await _(r),raw:null,path:null}}if(t==="session"||t.startsWith("session/")){const o=await N(e);if(o===null)return null;const r=await $(e);if(t==="session"){const d=r.map(f=>`## ${f.role}${f.origin!==void 0?` (origin: ${f.origin})`:""}
10
10
 
11
11
  ${f.text}`).join(`
12
12
 
13
- `);return{nodeId:e,relpath:t,source:"transcript",ts:r[r.length-1]?.ts??i.created,nodeName:i.name,body:a,raw:await(async()=>{const{header:f,entries:l}=await g().read(y(o));return[f,...l].map(m=>`${JSON.stringify(m)}
14
- `).join("")})(),path:o}}const c=Number(t.slice(8)),u=r[c];return u===void 0?null:{nodeId:e,relpath:t,source:"transcript",ts:u.ts,nodeName:i.name,body:u.text,raw:await J(o,c),path:o}}return null}d(on,"resolveRef");export{en as MESSAGE_ROLES,nn as ORIGIN_TOKENS,tn as buildCorpus,R as callerCwd,sn as groupCorpus,on as resolveRef};
13
+ `);return{nodeId:e,relpath:t,source:"transcript",ts:r[r.length-1]?.ts??i.created,nodeName:i.name,body:d,raw:a(async()=>{const{header:f,entries:l}=await g().read(y(o));return[f,...l].map(m=>`${JSON.stringify(m)}
14
+ `).join("")},"raw"),path:o}}const c=Number(t.slice(8)),u=r[c];return u===void 0?null:{nodeId:e,relpath:t,source:"transcript",ts:u.ts,nodeName:i.name,body:u.text,raw:a(()=>J(o,c),"raw"),path:o}}return null}a(on,"resolveRef");export{en as MESSAGE_ROLES,nn as ORIGIN_TOKENS,tn as buildCorpus,R as callerCwd,sn as groupCorpus,on as resolveRef};