@north-light/cli 0.3.670 → 0.3.671

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 (75) hide show
  1. package/dist/api/client.js +1 -1
  2. package/dist/api/contract.d.ts +1 -1
  3. package/dist/api/contract.js +1 -1
  4. package/dist/api/dto/bash-jobs.d.ts +2 -0
  5. package/dist/api/dto/execution-start.d.ts +7 -0
  6. package/dist/clients/attach/viewer.js +1 -1
  7. package/dist/commands/node/bash.js +3 -3
  8. package/dist/core/bash-job-supervisor.js +3 -3
  9. package/dist/core/canvas/canvas.d.ts +10 -1
  10. package/dist/core/canvas/canvas.js +18 -18
  11. package/dist/core/canvas/schema-pg/022-create-request-lease.sql +5 -0
  12. package/dist/core/canvas/schema-pg/023-machine-calls-job-stop.sql +7 -0
  13. package/dist/core/canvas/schema-version.d.ts +1 -1
  14. package/dist/core/canvas/schema-version.js +1 -1
  15. package/dist/core/grants/sync.js +1 -1
  16. package/dist/core/runtime/broker/boot-state.d.ts +8 -0
  17. package/dist/core/runtime/broker/boot-state.js +1 -1
  18. package/dist/core/runtime/broker/cycle-start.d.ts +8 -1
  19. package/dist/core/runtime/broker/cycle-start.js +2 -2
  20. package/dist/core/runtime/broker/turn-admission.d.ts +4 -1
  21. package/dist/core/runtime/broker/turn-admission.js +1 -1
  22. package/dist/core/runtime/broker.js +1 -1
  23. package/dist/core/runtime/runner/machine/call.js +2 -2
  24. package/dist/core/runtime/runner/machine/executor.d.ts +3 -3
  25. package/dist/core/runtime/runner/machine/executor.js +1 -1
  26. package/dist/core/runtime/runner/machine/ops.d.ts +18 -1
  27. package/dist/core/runtime/runner/machine/ops.js +1 -1
  28. package/dist/daemon/api/handlers/bash-jobs.js +3 -3
  29. package/dist/daemon/api/handlers/delivery.js +1 -1
  30. package/dist/daemon/api/handlers/nodes.js +1 -1
  31. package/dist/daemon/cron/machine-fire.d.ts +3 -0
  32. package/dist/daemon/cron/machine-fire.js +1 -1
  33. package/dist/daemon/crtrd.js +16 -16
  34. package/dist/daemon/due-sources.d.ts +1 -1
  35. package/dist/daemon/due-sources.js +1 -1
  36. package/dist/daemon/due.js +7 -7
  37. package/dist/daemon/machine-daemon.js +1 -1
  38. package/dist/daemon/machine-link/job-sweep.d.ts +7 -0
  39. package/dist/daemon/machine-link/job-sweep.js +1 -1
  40. package/dist/daemon/reconcilers/bash-deadline.js +1 -1
  41. package/dist/daemon/reconcilers/machine-offline.d.ts +6 -0
  42. package/dist/daemon/reconcilers/machine-offline.js +7 -0
  43. package/dist/daemon/reconcilers/node-lifecycle/tick.js +1 -1
  44. package/dist/pi-extensions/canvas-inbox-watcher.js +2 -2
  45. package/dist/pi-extensions/canvas-stophook.js +1 -1
  46. package/package.json +3 -3
  47. package/packages/crouter-api/dist/api/client.js +1 -1
  48. package/packages/crouter-api/dist/api/contract.js +1 -1
  49. package/packages/crouter-api/dist/api/dto/execution-start.js +0 -1
  50. package/packages/crouter-api/dist/commands/node/bash.js +7 -4
  51. package/packages/crouter-api/dist/core/bash-job-supervisor.js +15 -2
  52. package/packages/crouter-api/dist/core/canvas/canvas.js +23 -2
  53. package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
  54. package/packages/crouter-api/dist/core/grants/sync.js +3 -0
  55. package/packages/crouter-api/dist/core/runtime/revive-all.js +108 -0
  56. package/packages/crouter-api/dist/core/runtime/runner/machine/call.js +1 -1
  57. package/packages/crouter-api/dist/core/runtime/runner/machine/ops.js +1 -1
  58. package/packages/crouter-api/dist/daemon/api/handlers/bash-jobs.js +13 -2
  59. package/packages/crouter-api/dist/daemon/cron/armed-context.js +140 -0
  60. package/packages/crouter-api/dist/daemon/cron/capture.js +50 -0
  61. package/packages/crouter-api/dist/daemon/cron/closed.js +108 -0
  62. package/packages/crouter-api/dist/daemon/cron/disposition.js +63 -0
  63. package/packages/crouter-api/dist/daemon/cron/ended.js +80 -0
  64. package/packages/crouter-api/dist/daemon/cron/escalation.js +136 -0
  65. package/packages/crouter-api/dist/daemon/cron/held.js +20 -0
  66. package/packages/crouter-api/dist/daemon/cron/machine-fire.js +177 -0
  67. package/packages/crouter-api/dist/daemon/cron/narrowed.js +34 -0
  68. package/packages/crouter-api/dist/daemon/cron/recurrence.js +38 -0
  69. package/packages/crouter-api/dist/daemon/cron/run-token.js +37 -0
  70. package/packages/crouter-api/dist/daemon/cron/settle.js +78 -0
  71. package/packages/crouter-api/dist/daemon/cron/sinks.js +70 -0
  72. package/packages/crouter-api/package.json +1 -1
  73. package/packages/crouter-identity/package.json +1 -1
  74. package/packages/crouter-plugin/package.json +3 -3
  75. package/runtime.lock.json +14 -14
@@ -1,6 +1,6 @@
1
- var $=Object.defineProperty;var r=(e,t)=>$(e,"name",{value:t,configurable:!0});import{envNodeId as _}from"../../shared/env.js";import{defineBranch as T,defineLeaf as h}from"../../core/command.js";import{InputError as i}from"../../core/io.js";import{ExitCode as q}from"../../types.js";import{existsSync as R,mkdirSync as D,rmSync as E,writeFileSync as w}from"node:fs";import{backgroundRunningBashJobs as I,bashJobCommandLine as N,bashJobPaths as y,formatBashElapsed as k,isSafeBashJobId as g,jobStartedAtMs as B,newBashJobId as M,tailJobLog as L}from"../../core/bash-jobs.js";import{parseDurationMs as S}from"../../core/wake.js";import{cliClient as u,getNodeOrNull as c}from"../api-client.js";import{ApiError as x}from"../../api/index.js";import{PREVIEW_RESULT_PATH_ENV as U}from"../../core/preview-result-path.js";import{contextDir as A}from"../../core/canvas/paths.js";import{nodeInPane as C}from"../surface/node/placement.js";function b(e,t){const n=e.pane??process.env.TMUX_PANE;let o=e.node;if((o===void 0||o==="")&&(o=C(n)),(o===void 0||o==="")&&(o=_()),o===void 0||o==="")throw new i({error:"no_node",message:t,next:"Run from inside a node, pass --node <id>, or --pane <pane>."});return{id:o,pane:n}}r(b,"resolveBashTarget");async function j(e,t,n){try{await u().patchBashJob(e,t,n)}catch(o){throw o instanceof x&&(o.status===404||o.status===409)?new i({error:"not_running",message:`background job ${t} for ${e} is not running`,next:"List live jobs with `crtr node bash list`."}):o}}r(j,"patchRunningJob");const J=h({name:"run",description:"start a shell command as a background job and return at once",whenToUse:"a command needs longer than one tool call \u2014 a test lane, a build, a soak \u2014 and you should be woken with its exit code instead of waiting, backgrounding with `&`, or polling a log",tier:"normal",help:{name:"node bash run",summary:"start one shell command as a background job owned by the calling node and return before it finishes",params:[{kind:"positional",name:"command",required:!0,constraint:"The shell command, run by bash from the current directory with this process\u2019s environment. The same refusals apply as for a bash tool call, judged on this command."},{kind:"flag",name:"quiet-ok",type:"bool",required:!1,constraint:"Pass for a job that legitimately sits idle \u2014 `gh run watch`, `sleep`, waiting on a lock, a `docker build` whose work runs outside the process tree \u2014 so it gets no silence messages. Omit it for anything that should be making progress."}],output:[{name:"job_id",type:"string",required:!0,constraint:"The job object\u2019s id; read or watch it with `crtr canvas`, stop it with `node bash kill`."},{name:"log_path",type:"string",required:!0,constraint:"File receiving the command\u2019s combined stdout and stderr, capped at 10 MiB."}],outputKind:"object",effects:["Works only inside a node\u2019s bash tool call; the job belongs to the calling node.","Starts the command detached from this call, so it keeps running after the call and the turn end. A `timeout` around this leaf bounds only the launch, not the job.","Records the job as a canvas object; when the command exits, its watchers (the calling node by default) get an urgent `exited` push with the exit code and log path.","Sets no cancel deadline: the job runs to completion unless stopped with `node bash kill`.","A job whose processes use almost no CPU and write to no open file for 15 minutes messages the calling node about it, again at 30 and 60 minutes, then hourly; activity restarts the schedule and nothing is stopped. `--quiet-ok` turns these messages off.","Fails, with the job id and log path, if the job could not be recorded; the command is then running but will not message the node when it exits."]},run:r(async e=>{const t=e.command,n=_(),o=process.env.CRTR_CONTEXT_DIR;if(n===void 0||n===""||o===void 0||o==="")throw new i({error:"no_node",message:"`node bash run` starts a job for the calling node and works only inside a node\u2019s bash tool",next:"Run it from a node\u2019s bash tool call."});const s=process.cwd(),{bashCommandRefusal:d}=await import("../../core/bash-guard.js"),l=d(t,s);if(l!==null)throw new i({error:"refused",message:l,next:"Run a different command."});const a=y(o,M());D(a.dir,{recursive:!0}),w(a.cmdSh,t),w(a.jobLog,""),w(a.jobBg,"");const{launchBashJobSupervisor:m}=await import("../../core/runtime/broker/bash-job-launch.js"),{[U]:p,...v}=process.env;try{await m(n,a,o,s,v)}catch(f){throw E(a.dir,{recursive:!0,force:!0}),f}try{await u().recordBackgroundedJob(n,a.jobId,{command:t}),e.quietOk===!0&&await u().patchBashJob(n,a.jobId,{quiet_ok:!0})}catch(f){throw new i({error:"job_not_recorded",message:`job ${a.jobId} is running but could not be recorded (${f.message}); it will NOT message you when it exits. Log: ${a.jobLog}`,next:`Watch it with \`tail -f ${a.jobLog}\`, or stop it with \`crtr node bash kill ${a.jobId}\`.`},q.GENERAL)}return{job_id:a.jobId,log_path:a.jobLog}},"run"),render:r(e=>`[backgrounded as job ${e.job_id}. It will interrupt you with a message when it exits. Watch: tail -f ${e.log_path} ; stop: crtr node bash kill ${e.job_id}]`,"render")}),P=h({name:"background",description:"hand the focused node\u2019s running bash command to its background job system",whenToUse:"the tmux prefix menu invokes this when a foreground bash command should stop blocking the agent immediately but keep running as a file-backed background job",tier:"hidden",help:{name:"node bash background",summary:"hand every running foreground bash command for one node to its file-backed background job system",params:[{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node whose running bash command to background. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE. The prefix menu passes this for you."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The target node."},{name:"jobs",type:"object[]",required:!0,constraint:"Per handed-off job {job_id, elapsed_ms} \u2014 the foreground elapsed time in milliseconds at the moment of handoff."}],outputKind:"object",effects:["Signals every foreground bash command currently running for the node to return from its tool call immediately while its detached supervisor keeps the command running.","Each handed-off command retains its log under the node context jobs directory and becomes a job object; when it exits, the job\u2019s watchers (its node by default) get an urgent `exited` push carrying the exit code and log path."]},run:r(async e=>{const{id:t}=b(e,"no node found for the bash handoff"),n=await c(t);if(n===null)throw new i({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=I(n.paths.context_dir),s=Date.now(),d=o.map(l=>({job_id:l.jobId,elapsed_ms:s-(B(l.jobId)??s)}));return{node_id:t,jobs:d}},"run"),render:r(e=>{const t=e.jobs;if(t.length===0)return`No foreground bash command is running for ${e.node_id}.`;const n=Math.max(...t.map(o=>o.elapsed_ms));return`Handed ${t.length} bash command(s) to the background job system for ${e.node_id} \xB7 ran ${k(n)} in the foreground.`},"render")}),O=h({name:"list",description:"list a node\u2019s live background bash jobs",whenToUse:"you need the ids, commands, and ages of your jobs that are still running",help:{name:"node bash list",summary:"read every still-running background bash job owned by one node",params:[{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node whose background jobs to list. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE."},{kind:"flag",name:"tail",type:"int",required:!1,default:0,constraint:"Include this many trailing log lines per job (0 = none). Read from the local log file, so it is available only on the machine that runs the job; elsewhere log_tail is null \u2014 use `node bash log` there."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The target node."},{name:"jobs",type:"object[]",required:!0,constraint:"Oldest-first {job_id, command, purpose, started_at, elapsed_ms, deadline_at, output_key, log_path, pgid, log_tail} for every live background job; log_path and log_tail are null when the job\u2019s log is not on this machine (a job running in a sandbox, listed from outside it), and no tail is available from here (`node bash log` reads its stored output); purpose is a human-readable label or null; deadline_at is the auto-cancel time or null for a job that runs to completion."}],outputKind:"object",effects:["Reads the node\u2019s running job rows and, for log_tail, the local log files. Changes nothing."]},run:r(async e=>{const{id:t}=b(e,"no node found for the bash job list"),n=await c(t);if(n===null)throw new i({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=Date.now(),s=Math.max(0,Math.trunc(Number(e.tail??0))),d=[n.paths.context_dir,A(n.node_id,n.grantee)],l=(await u().listBashJobs(n.node_id)).map(a=>{const m=d.map(p=>y(p,a.job_id).jobLog).find(p=>R(p))??null;return{job_id:a.job_id,command:a.command,purpose:a.purpose,started_at:a.started_at,elapsed_ms:a.elapsed_ms,deadline_at:a.deadline_at,output_key:a.output_key,log_path:m,pgid:a.pgid,log_tail:m===null?null:L(m,s)}});return{node_id:n.node_id,jobs:l}},"run"),render:r(e=>{const t=e.jobs;return t.length===0?`No background bash jobs for ${e.node_id}.`:t.map(n=>`${n.job_id} \xB7 ${k(n.elapsed_ms)} \xB7 ${N(n.command)}${n.purpose===null?"":`
1
+ var $=Object.defineProperty;var i=(e,t)=>$(e,"name",{value:t,configurable:!0});import{envNodeId as j}from"../../shared/env.js";import{defineBranch as q,defineLeaf as h}from"../../core/command.js";import{InputError as r}from"../../core/io.js";import{ExitCode as T}from"../../types.js";import{existsSync as R,mkdirSync as D,rmSync as E,writeFileSync as w}from"node:fs";import{backgroundRunningBashJobs as I,bashJobCommandLine as N,bashJobPaths as y,formatBashElapsed as k,isSafeBashJobId as g,jobStartedAtMs as B,newBashJobId as M,tailJobLog as L}from"../../core/bash-jobs.js";import{parseDurationMs as S}from"../../core/wake.js";import{cliClient as u,getNodeOrNull as c}from"../api-client.js";import{ApiError as x}from"../../api/index.js";import{PREVIEW_RESULT_PATH_ENV as U}from"../../core/preview-result-path.js";import{contextDir as C}from"../../core/canvas/paths.js";import{nodeInPane as A}from"../surface/node/placement.js";function b(e,t){const n=e.pane??process.env.TMUX_PANE;let o=e.node;if((o===void 0||o==="")&&(o=A(n)),(o===void 0||o==="")&&(o=j()),o===void 0||o==="")throw new r({error:"no_node",message:t,next:"Run from inside a node, pass --node <id>, or --pane <pane>."});return{id:o,pane:n}}i(b,"resolveBashTarget");async function _(e,t,n){try{await u().patchBashJob(e,t,n)}catch(o){throw o instanceof x&&(o.status===404||o.status===409)?new r({error:"not_running",message:`background job ${t} for ${e} is not running`,next:"List live jobs with `crtr node bash list`."}):o}}i(_,"patchRunningJob");const J=h({name:"run",description:"start a shell command as a background job and return at once",whenToUse:"a command needs longer than one tool call \u2014 a test lane, a build, a soak \u2014 and you should be woken with its exit code instead of waiting, backgrounding with `&`, or polling a log",tier:"normal",help:{name:"node bash run",summary:"start one shell command as a background job owned by the calling node and return before it finishes",params:[{kind:"positional",name:"command",required:!0,constraint:"The shell command, run by bash from the current directory with this process\u2019s environment. The same refusals apply as for a bash tool call, judged on this command."},{kind:"flag",name:"quiet-ok",type:"bool",required:!1,constraint:"Pass for a job that legitimately sits idle \u2014 `gh run watch`, `sleep`, waiting on a lock, a `docker build` whose work runs outside the process tree \u2014 so it gets no silence messages. Omit it for anything that should be making progress."}],output:[{name:"job_id",type:"string",required:!0,constraint:"The job object\u2019s id; read or watch it with `crtr canvas`, stop it with `node bash kill`."},{name:"log_path",type:"string",required:!0,constraint:"File receiving the command\u2019s combined stdout and stderr, capped at 10 MiB."}],outputKind:"object",effects:["Works only inside a node\u2019s bash tool call; the job belongs to the calling node.","Starts the command detached from this call, so it keeps running after the call and the turn end. A `timeout` around this leaf bounds only the launch, not the job.","Records the job as a canvas object; when the command exits, its watchers (the calling node by default) get an urgent `exited` push with the exit code and log path.","Sets no cancel deadline: the job runs to completion unless stopped with `node bash kill`.","A job whose processes use almost no CPU and write to no open file for 15 minutes messages the calling node about it, again at 30 and 60 minutes, then hourly; activity restarts the schedule and nothing is stopped. `--quiet-ok` turns these messages off.","Fails, with the job id and log path, if the job could not be recorded; the command is then running but will not message the node when it exits."]},run:i(async e=>{const t=e.command,n=j(),o=process.env.CRTR_CONTEXT_DIR;if(n===void 0||n===""||o===void 0||o==="")throw new r({error:"no_node",message:"`node bash run` starts a job for the calling node and works only inside a node\u2019s bash tool",next:"Run it from a node\u2019s bash tool call."});const s=process.cwd(),{bashCommandRefusal:d}=await import("../../core/bash-guard.js"),l=d(t,s);if(l!==null)throw new r({error:"refused",message:l,next:"Run a different command."});const a=y(o,M());D(a.dir,{recursive:!0}),w(a.cmdSh,t),w(a.jobLog,""),w(a.jobBg,"");const{launchBashJobSupervisor:m}=await import("../../core/runtime/broker/bash-job-launch.js"),{[U]:p,...v}=process.env;try{await m(n,a,o,s,v)}catch(f){throw E(a.dir,{recursive:!0,force:!0}),f}try{await u().recordBackgroundedJob(n,a.jobId,{command:t}),e.quietOk===!0&&await u().patchBashJob(n,a.jobId,{quiet_ok:!0})}catch(f){throw new r({error:"job_not_recorded",message:`job ${a.jobId} is running but could not be recorded (${f.message}); it will NOT message you when it exits. Log: ${a.jobLog}`,next:`Watch it with \`tail -f ${a.jobLog}\`, or stop it with \`crtr node bash kill ${a.jobId}\`.`},T.GENERAL)}return{job_id:a.jobId,log_path:a.jobLog}},"run"),render:i(e=>`[backgrounded as job ${e.job_id}. It will interrupt you with a message when it exits. Watch: tail -f ${e.log_path} ; stop: crtr node bash kill ${e.job_id}]`,"render")}),P=h({name:"background",description:"hand the focused node\u2019s running bash command to its background job system",whenToUse:"the tmux prefix menu invokes this when a foreground bash command should stop blocking the agent immediately but keep running as a file-backed background job",tier:"hidden",help:{name:"node bash background",summary:"hand every running foreground bash command for one node to its file-backed background job system",params:[{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node whose running bash command to background. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE. The prefix menu passes this for you."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The target node."},{name:"jobs",type:"object[]",required:!0,constraint:"Per handed-off job {job_id, elapsed_ms} \u2014 the foreground elapsed time in milliseconds at the moment of handoff."}],outputKind:"object",effects:["Signals every foreground bash command currently running for the node to return from its tool call immediately while its detached supervisor keeps the command running.","Each handed-off command retains its log under the node context jobs directory and becomes a job object; when it exits, the job\u2019s watchers (its node by default) get an urgent `exited` push carrying the exit code and log path."]},run:i(async e=>{const{id:t}=b(e,"no node found for the bash handoff"),n=await c(t);if(n===null)throw new r({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=I(n.paths.context_dir),s=Date.now(),d=o.map(l=>({job_id:l.jobId,elapsed_ms:s-(B(l.jobId)??s)}));return{node_id:t,jobs:d}},"run"),render:i(e=>{const t=e.jobs;if(t.length===0)return`No foreground bash command is running for ${e.node_id}.`;const n=Math.max(...t.map(o=>o.elapsed_ms));return`Handed ${t.length} bash command(s) to the background job system for ${e.node_id} \xB7 ran ${k(n)} in the foreground.`},"render")}),O=h({name:"list",description:"list a node\u2019s live background bash jobs",whenToUse:"you need the ids, commands, and ages of your jobs that are still running",help:{name:"node bash list",summary:"read every still-running background bash job owned by one node",params:[{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node whose background jobs to list. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE."},{kind:"flag",name:"tail",type:"int",required:!1,default:0,constraint:"Include this many trailing log lines per job (0 = none). Read from the local log file, so it is available only on the machine that runs the job; elsewhere log_tail is null \u2014 use `node bash log` there."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The target node."},{name:"jobs",type:"object[]",required:!0,constraint:"Oldest-first {job_id, command, purpose, started_at, elapsed_ms, deadline_at, output_key, log_path, pgid, log_tail} for every live background job; log_path and log_tail are null when the job\u2019s log is not on this machine (a job running in a sandbox, listed from outside it), and no tail is available from here (`node bash log` reads its stored output); purpose is a human-readable label or null; deadline_at is the auto-cancel time or null for a job that runs to completion."}],outputKind:"object",effects:["Reads the node\u2019s running job rows and, for log_tail, the local log files. Changes nothing."]},run:i(async e=>{const{id:t}=b(e,"no node found for the bash job list"),n=await c(t);if(n===null)throw new r({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=Date.now(),s=Math.max(0,Math.trunc(Number(e.tail??0))),d=[n.paths.context_dir,C(n.node_id,n.grantee)],l=(await u().listBashJobs(n.node_id)).map(a=>{const m=d.map(p=>y(p,a.job_id).jobLog).find(p=>R(p))??null;return{job_id:a.job_id,command:a.command,purpose:a.purpose,started_at:a.started_at,elapsed_ms:a.elapsed_ms,deadline_at:a.deadline_at,output_key:a.output_key,log_path:m,pgid:a.pgid,log_tail:m===null?null:L(m,s)}});return{node_id:n.node_id,jobs:l}},"run"),render:i(e=>{const t=e.jobs;return t.length===0?`No background bash jobs for ${e.node_id}.`:t.map(n=>`${n.job_id} \xB7 ${k(n.elapsed_ms)} \xB7 ${N(n.command)}${n.purpose===null?"":`
2
2
  purpose: ${n.purpose}`}${n.deadline_at===null?"":`
3
3
  cancels at: ${n.deadline_at}`}
4
4
  ${n.log_path===null?`log: not on this machine (its job files are not under this machine\u2019s crtr home \u2014 a sandbox or another computer); read its output with \`crtr node bash log ${n.job_id} --node ${e.node_id}\``:`log: ${n.log_path}`}`).join(`
5
- `)},"render")}),K=h({name:"log",description:"read a background bash job\u2019s output from the blob store, from any machine",whenToUse:"a job has exited or been killed, or its sandbox is gone, and you need what it printed \u2014 the wake and the job object name this command; for a job still running on this machine, `tail -f` on its log file shows more recent output",help:{name:"node bash log",summary:"read the stored output of one background bash job, last lines first bounded",params:[{kind:"positional",name:"job",required:!0,constraint:"Job id, as named by the exit wake, `node bash list` or `node bash run`. Running and finished jobs both work."},{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node owning the job. Defaults to the node in --pane, else the caller (CRTR_NODE_ID). A job another node started needs its owner here."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE."},{kind:"flag",name:"tail",type:"int",required:!1,constraint:"Return only this many trailing lines. Without it you get the last 256 KiB of output; either way at most 4 MiB."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The owning node."},{name:"job_id",type:"string",required:!0,constraint:"The job."},{name:"output",type:"string",required:!0,constraint:"The stored output, empty when the job has written nothing yet. The broker uploads a running job\u2019s output every couple of seconds, so it can trail the live log slightly."},{name:"truncated",type:"boolean",required:!0,constraint:"True when earlier output exists that the bound left out."}],outputKind:"object",effects:["Reads the output chunks the job\u2019s broker uploaded to the blob store through the daemon; never the local log file, so it works from any machine and after the job\u2019s sandbox is deleted. Needs read access to the owning node. Changes nothing."]},run:r(async e=>{const{id:t}=b(e,"no node found for the bash job"),n=await c(t);if(n===null)throw new i({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=e.job;if(!g(o))throw new i({error:"invalid_job_id",message:`invalid background job id: ${o}`,next:"Use a job id named by the exit wake or `crtr node bash list`."});const s=e.tail===void 0?void 0:Math.trunc(Number(e.tail));if(s!==void 0&&!(s>=1))throw new i({error:"invalid_args",message:"--tail must be a positive number of lines",next:"Pass --tail 50, or omit it for the last 256 KiB."});try{const d=await u().readBashJobOutput(n.node_id,o,s===void 0?{}:{tail_lines:s});return{node_id:n.node_id,job_id:d.job_id,output:d.output,truncated:d.truncated}}catch(d){throw d instanceof x&&d.code==="job_not_found"?new i({error:"job_not_found",message:`no job ${o} owned by ${n.node_id}`,next:"A job another node started needs its owner: pass --node <owner>."}):d}},"run"),render:r(e=>`${e.truncated===!0?`[earlier output omitted]
6
- `:""}${String(e.output)}`,"render")}),X=h({name:"kill",description:"stop one of a node\u2019s background bash jobs",whenToUse:"a job you started is no longer wanted or is stuck, and it should stop now",help:{name:"node bash kill",summary:"best-effort stop a background bash job and tell the owning node it was canceled",params:[{kind:"positional",name:"job",required:!0,constraint:"Job id, as reported by node bash list."},{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node owning the job. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The owning node."},{name:"signaled",type:"boolean",required:!0,constraint:"True when at least one observed supervisor-tree process received SIGTERM. For a job running on another machine it is true without any signal having been sent yet."},{name:"stop_pending_on_machine",type:"boolean",required:!0,constraint:"True when the job\u2019s process runs on another machine (an imported Mac or a sandbox): its broker there stops the whole process tree on its next report, within a few seconds, so nothing is confirmed stopped yet."}],outputKind:"object",effects:["Snapshots the supervisor\u2019s observable process tree, sends SIGTERM then SIGKILL to those processes and to the supervisor\u2019s process group, and cannot stop a descendant that detached into its own session and reparented before the snapshot. A job running on another machine (an imported Mac, a sandbox) is stopped there by its broker within a few seconds of the row ending.","Records the job\u2019s exit so it stops showing as live, and ends its job object as killed; the job\u2019s watchers (its node by default) get an urgent `killed` push."]},run:r(async e=>{const{id:t}=b(e,"no node found for the bash job"),n=await c(t);if(n===null)throw new i({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=e.job;if(!g(o))throw new i({error:"invalid_job_id",message:`invalid background job id: ${o}`,next:"Use a job id reported by `crtr node bash list`."});const s=await u().stopBashJob(n.node_id,o);return{node_id:n.node_id,signaled:s.signaled,stop_pending_on_machine:s.stop_pending_on_machine===!0}},"run"),render:r(e=>e.stop_pending_on_machine===!0?`Ended a background bash job for ${e.node_id}. Its process runs on another machine (an imported Mac or a sandbox); that machine's broker stops the whole process tree on its next report, within a few seconds. Confirm with \`ps\` there if it matters.`:`Canceled a background bash job for ${e.node_id}${e.signaled===!0?"":" (no observed job process was still running)"}.`,"render")}),W=h({name:"quiet",description:"mark a running background bash job as an expected wait so it sends no silence messages",whenToUse:"a silence message arrived for a job that is meant to sit idle",help:{name:"node bash quiet",summary:"stop silence messages for one of a node\u2019s live background bash jobs",params:[{kind:"positional",name:"job",required:!0,constraint:"Job id, as reported by node bash list or the silence message."},{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node owning the job. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The owning node."}],outputKind:"object",effects:["Marks the job\u2019s row; the daemon sends no further silence messages for it. Signals nothing."]},run:r(async e=>{const{id:t}=b(e,"no node found for the bash job"),n=await c(t);if(n===null)throw new i({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=e.job;if(!g(o))throw new i({error:"invalid_job_id",message:`invalid background job id: ${o}`,next:"Use a job id reported by `crtr node bash list`."});return await j(n.node_id,o,{quiet_ok:!0}),{node_id:n.node_id}},"run"),render:r(e=>`Background job for ${e.node_id} will send no more silence messages.`,"render")}),F=h({name:"extend",description:"claim an auto-backgrounded bash job so the daemon does not cancel it at its deadline",whenToUse:"a command that was moved to a job automatically is worth keeping past its cancel deadline \u2014 give it more time with --for, or let it run to completion with --keep",help:{name:"node bash extend",summary:"move or clear the auto-cancel deadline on one of a node\u2019s live background bash jobs",params:[{kind:"positional",name:"job",required:!0,constraint:"Job id, as reported by node bash list or the auto-background notice."},{kind:"flag",name:"for",type:"string",required:!1,constraint:"New window from now before the job is canceled, as a duration (e.g. 90s, 10m, 1h30m). Mutually exclusive with --keep; give exactly one."},{kind:"flag",name:"keep",type:"bool",required:!1,constraint:"Remove the deadline entirely so the job runs to completion. Mutually exclusive with --for; give exactly one."},{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node owning the job. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The owning node."},{name:"deadline_at",type:"string",required:!1,constraint:"The job\u2019s new auto-cancel time (ISO), or absent when --keep cleared the deadline so the job runs to completion."}],outputKind:"object",effects:["Rewrites or clears the deadline on the job\u2019s row. The daemon\u2019s deadline lane reads it on its next scan. Signals nothing."]},run:r(async e=>{const{id:t}=b(e,"no node found for the bash job"),n=await c(t);if(n===null)throw new i({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=e.job;if(!g(o))throw new i({error:"invalid_job_id",message:`invalid background job id: ${o}`,next:"Use a job id reported by `crtr node bash list`."});const s=e.for,d=e.keep===!0;if(d===(s!==void 0&&s!==""))throw new i({error:"invalid_args",message:"give exactly one of --for <duration> or --keep",next:"Extend by a window with --for 10m, or drop the deadline with --keep."});if(d)return await j(n.node_id,o,{keep:!0}),{node_id:n.node_id};const l=S(s);if(l===null||l<=0)throw new i({error:"invalid_duration",message:`not a duration: ${s}`,next:"Use a value like 90s, 10m, or 1h30m."});const a=Date.now()+l;return await j(n.node_id,o,{deadline_at_ms:a}),{node_id:n.node_id,deadline_at:new Date(a).toISOString()}},"run"),render:r(e=>e.deadline_at===void 0?`Cleared the deadline \u2014 the background job will run to completion for ${e.node_id}.`:`Background job for ${e.node_id} will be canceled at ${e.deadline_at} unless extended again.`,"render")}),ie=T({name:"bash",description:"start, list, read, stop, and extend your background bash jobs",whenToUse:"a command needs longer than one tool call \u2014 start it as a job and be woken with its exit code instead of using `&`, `nohup`, or a cron that polls a log \u2014 or you need to list, read the output of, stop, or extend the deadline of a job you already have",help:{name:"node bash",summary:"start, list, read, stop, and extend background bash jobs owned by a node",model:"Every bash call runs under a detached supervisor with its output in a log file, so a command that outlives its call keeps running as a job: a canvas object its node owns, readable and watchable with `crtr canvas`. `run` starts a job on purpose and it is never auto-canceled. A job that shows no activity for 15 minutes messages its node, and is never stopped for it. A foreground command still running after 5 minutes is moved to a job automatically, with a cancel deadline unless `extend` claims it."},children:[J,P,O,K,X,W,F]});export{ie as nodeBash};
5
+ `)},"render")}),K=h({name:"log",description:"read a background bash job\u2019s output from the blob store, from any machine",whenToUse:"a job has exited or been killed, or its sandbox is gone, and you need what it printed \u2014 the wake and the job object name this command; for a job still running on this machine, `tail -f` on its log file shows more recent output",help:{name:"node bash log",summary:"read the stored output of one background bash job, last lines first bounded",params:[{kind:"positional",name:"job",required:!0,constraint:"Job id, as named by the exit wake, `node bash list` or `node bash run`. Running and finished jobs both work."},{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node owning the job. Defaults to the node in --pane, else the caller (CRTR_NODE_ID). A job another node started needs its owner here."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE."},{kind:"flag",name:"tail",type:"int",required:!1,constraint:"Return only this many trailing lines. Without it you get the last 256 KiB of output; either way at most 4 MiB."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The owning node."},{name:"job_id",type:"string",required:!0,constraint:"The job."},{name:"output",type:"string",required:!0,constraint:"The stored output, empty when the job has written nothing yet. The broker uploads a running job\u2019s output every couple of seconds, so it can trail the live log slightly."},{name:"truncated",type:"boolean",required:!0,constraint:"True when earlier output exists that the bound left out."}],outputKind:"object",effects:["Reads the output chunks the job\u2019s broker uploaded to the blob store through the daemon; never the local log file, so it works from any machine and after the job\u2019s sandbox is deleted. Needs read access to the owning node. Changes nothing."]},run:i(async e=>{const{id:t}=b(e,"no node found for the bash job"),n=await c(t);if(n===null)throw new r({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=e.job;if(!g(o))throw new r({error:"invalid_job_id",message:`invalid background job id: ${o}`,next:"Use a job id named by the exit wake or `crtr node bash list`."});const s=e.tail===void 0?void 0:Math.trunc(Number(e.tail));if(s!==void 0&&!(s>=1))throw new r({error:"invalid_args",message:"--tail must be a positive number of lines",next:"Pass --tail 50, or omit it for the last 256 KiB."});try{const d=await u().readBashJobOutput(n.node_id,o,s===void 0?{}:{tail_lines:s});return{node_id:n.node_id,job_id:d.job_id,output:d.output,truncated:d.truncated}}catch(d){throw d instanceof x&&d.code==="job_not_found"?new r({error:"job_not_found",message:`no job ${o} owned by ${n.node_id}`,next:"A job another node started needs its owner: pass --node <owner>."}):d}},"run"),render:i(e=>`${e.truncated===!0?`[earlier output omitted]
6
+ `:""}${String(e.output)}`,"render")}),X=h({name:"kill",description:"stop one of a node\u2019s background bash jobs",whenToUse:"a job you started is no longer wanted or is stuck, and it should stop now",help:{name:"node bash kill",summary:"best-effort stop a background bash job and tell the owning node it was canceled",params:[{kind:"positional",name:"job",required:!0,constraint:"Job id, as reported by node bash list."},{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node owning the job. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The owning node."},{name:"signaled",type:"boolean",required:!0,constraint:"True when at least one observed supervisor-tree process received SIGTERM. For a job running on another machine it is true without any signal having been sent yet."},{name:"stop_pending_on_machine",type:"boolean",required:!0,constraint:"True when the job\u2019s process runs on another machine (an imported Mac or a sandbox): its broker there stops the whole process tree on its next report, within a few seconds, so nothing is confirmed stopped yet."},{name:"stop_queue_error",type:"string",required:!1,constraint:"The error when the job ended here but the stop for its machine could not be queued, so the process may still be running there; null otherwise."}],outputKind:"object",effects:["Snapshots the supervisor\u2019s observable process tree, sends SIGTERM then SIGKILL to those processes and to the supervisor\u2019s process group, and cannot stop a descendant that detached into its own session and reparented before the snapshot. A job running on another machine (an imported Mac, a sandbox) is stopped there by its broker within a few seconds of the row ending.","Records the job\u2019s exit so it stops showing as live, and ends its job object as killed; the job\u2019s watchers (its node by default) get an urgent `killed` push."]},run:i(async e=>{const{id:t}=b(e,"no node found for the bash job"),n=await c(t);if(n===null)throw new r({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=e.job;if(!g(o))throw new r({error:"invalid_job_id",message:`invalid background job id: ${o}`,next:"Use a job id reported by `crtr node bash list`."});const s=await u().stopBashJob(n.node_id,o);return{node_id:n.node_id,signaled:s.signaled,stop_pending_on_machine:s.stop_pending_on_machine===!0,...s.stop_queue_error===void 0?{}:{stop_queue_error:s.stop_queue_error}}},"run"),render:i(e=>typeof e.stop_queue_error=="string"?`Ended the background bash job for ${e.node_id}, but the stop could not be queued for its machine (${e.stop_queue_error}); the process may still be running there. Check with \`ps\` on that machine.`:e.stop_pending_on_machine===!0?`Ended a background bash job for ${e.node_id}. Its process runs on another machine (an imported Mac or a sandbox); that machine's broker stops the whole process tree on its next report, within a few seconds. Confirm with \`ps\` there if it matters.`:`Canceled a background bash job for ${e.node_id}${e.signaled===!0?"":" (no observed job process was still running)"}.`,"render")}),W=h({name:"quiet",description:"mark a running background bash job as an expected wait so it sends no silence messages",whenToUse:"a silence message arrived for a job that is meant to sit idle",help:{name:"node bash quiet",summary:"stop silence messages for one of a node\u2019s live background bash jobs",params:[{kind:"positional",name:"job",required:!0,constraint:"Job id, as reported by node bash list or the silence message."},{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node owning the job. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The owning node."}],outputKind:"object",effects:["Marks the job\u2019s row; the daemon sends no further silence messages for it. Signals nothing."]},run:i(async e=>{const{id:t}=b(e,"no node found for the bash job"),n=await c(t);if(n===null)throw new r({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=e.job;if(!g(o))throw new r({error:"invalid_job_id",message:`invalid background job id: ${o}`,next:"Use a job id reported by `crtr node bash list`."});return await _(n.node_id,o,{quiet_ok:!0}),{node_id:n.node_id}},"run"),render:i(e=>`Background job for ${e.node_id} will send no more silence messages.`,"render")}),F=h({name:"extend",description:"claim an auto-backgrounded bash job so the daemon does not cancel it at its deadline",whenToUse:"a command that was moved to a job automatically is worth keeping past its cancel deadline \u2014 give it more time with --for, or let it run to completion with --keep",help:{name:"node bash extend",summary:"move or clear the auto-cancel deadline on one of a node\u2019s live background bash jobs",params:[{kind:"positional",name:"job",required:!0,constraint:"Job id, as reported by node bash list or the auto-background notice."},{kind:"flag",name:"for",type:"string",required:!1,constraint:"New window from now before the job is canceled, as a duration (e.g. 90s, 10m, 1h30m). Mutually exclusive with --keep; give exactly one."},{kind:"flag",name:"keep",type:"bool",required:!1,constraint:"Remove the deadline entirely so the job runs to completion. Mutually exclusive with --for; give exactly one."},{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node owning the job. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The owning node."},{name:"deadline_at",type:"string",required:!1,constraint:"The job\u2019s new auto-cancel time (ISO), or absent when --keep cleared the deadline so the job runs to completion."}],outputKind:"object",effects:["Rewrites or clears the deadline on the job\u2019s row. The daemon\u2019s deadline lane reads it on its next scan. Signals nothing."]},run:i(async e=>{const{id:t}=b(e,"no node found for the bash job"),n=await c(t);if(n===null)throw new r({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=e.job;if(!g(o))throw new r({error:"invalid_job_id",message:`invalid background job id: ${o}`,next:"Use a job id reported by `crtr node bash list`."});const s=e.for,d=e.keep===!0;if(d===(s!==void 0&&s!==""))throw new r({error:"invalid_args",message:"give exactly one of --for <duration> or --keep",next:"Extend by a window with --for 10m, or drop the deadline with --keep."});if(d)return await _(n.node_id,o,{keep:!0}),{node_id:n.node_id};const l=S(s);if(l===null||l<=0)throw new r({error:"invalid_duration",message:`not a duration: ${s}`,next:"Use a value like 90s, 10m, or 1h30m."});const a=Date.now()+l;return await _(n.node_id,o,{deadline_at_ms:a}),{node_id:n.node_id,deadline_at:new Date(a).toISOString()}},"run"),render:i(e=>e.deadline_at===void 0?`Cleared the deadline \u2014 the background job will run to completion for ${e.node_id}.`:`Background job for ${e.node_id} will be canceled at ${e.deadline_at} unless extended again.`,"render")}),re=q({name:"bash",description:"start, list, read, stop, and extend your background bash jobs",whenToUse:"a command needs longer than one tool call \u2014 start it as a job and be woken with its exit code instead of using `&`, `nohup`, or a cron that polls a log \u2014 or you need to list, read the output of, stop, or extend the deadline of a job you already have",help:{name:"node bash",summary:"start, list, read, stop, and extend background bash jobs owned by a node",model:"Every bash call runs under a detached supervisor with its output in a log file, so a command that outlives its call keeps running as a job: a canvas object its node owns, readable and watchable with `crtr canvas`. `run` starts a job on purpose and it is never auto-canceled. A job that shows no activity for 15 minutes messages its node, and is never stopped for it. A foreground command still running after 5 minutes is moved to a job automatically, with a cancel deadline unless `extend` claims it."},children:[J,P,O,K,X,W,F]});export{re as nodeBash};
@@ -1,4 +1,4 @@
1
- const c=10485760,e=`
1
+ const r=10485760,e=`
2
2
  [background bash job output truncated at 10 MiB; remaining output discarded]
3
- `,t=['const fs = require("node:fs");',"const cap = 10485760;",`const marker = Buffer.from(${JSON.stringify(e)});`,"const prefixCap = cap - marker.length;",'const fd = fs.openSync(process.argv[1], "w");',"let written = 0;","let truncated = false;",'process.stdin.on("data", (chunk) => {'," if (truncated) return;"," const available = prefixCap - written;"," if (available > 0) {"," const prefix = chunk.subarray(0, available);"," fs.writeSync(fd, prefix);"," written += prefix.length;"," if (prefix.length === chunk.length) return;"," }"," fs.writeSync(fd, marker);"," truncated = true;","});",'process.stdin.on("end", () => fs.closeSync(fd));'].join(" "),s=['const fs = require("node:fs"), cp = require("node:child_process");',"const rootPid = Number(process.argv[1]), out = process.argv[3];","let logPath = process.argv[2];","try { logPath = fs.realpathSync(logPath); } catch {}","const interval = Number(process.env.CRTR_BASH_ACTIVITY_SAMPLE_MS) || 60000;",'const linux = fs.existsSync("/proc/self/stat");',"function processes() {"," const procs = new Map();"," if (linux) {",' for (const e of fs.readdirSync("/proc")) {'," if (!/^[0-9]+$/.test(e)) continue;"," try {",' const s = fs.readFileSync("/proc/" + e + "/stat", "utf8");',' const r = s.slice(s.lastIndexOf(")") + 2).split(" ");'," procs.set(Number(e), { ppid: Number(r[1]), cpu: (Number(r[11]) + Number(r[12])) / 100 });"," } catch {}"," }"," return procs;"," }",' const ps = cp.execFileSync("ps", ["-ax", "-o", "pid=,ppid=,time="], { encoding: "utf8", timeout: 5000 });',' for (const line of ps.split("\\n")) {'," const f = line.trim().split(/\\s+/);"," if (f.length < 3) continue;",' const [days, clock] = f[2].includes("-") ? f[2].split("-") : ["0", f[2]];',' const cpu = clock.split(":").reduce((t, x) => t * 60 + Number(x), 0) + Number(days) * 86400;'," if (Number.isFinite(cpu)) procs.set(Number(f[0]), { ppid: Number(f[1]), cpu });"," }"," return procs;","}","function tree(procs) {"," const cpus = new Map(), stack = [rootPid];"," while (stack.length > 0) {"," const pid = stack.pop();"," if (pid === process.pid || cpus.has(pid) || !procs.has(pid)) continue;"," cpus.set(pid, procs.get(pid).cpu);"," for (const [child, p] of procs) if (p.ppid === pid) stack.push(child);"," }"," return cpus;","}","function writableFiles(pids) {"," const files = new Set();"," if (linux) {"," for (const pid of pids) {"," let fds = [];",' try { fds = fs.readdirSync("/proc/" + pid + "/fd"); } catch {}'," for (const fd of fds) {"," try {",' const info = fs.readFileSync("/proc/" + pid + "/fdinfo/" + fd, "utf8").match(/flags:\\s*([0-7]+)/);'," if (info === null || (parseInt(info[1], 8) & 3) === 0) continue;",' files.add(fs.readlinkSync("/proc/" + pid + "/fd/" + fd));'," } catch {}"," }"," }"," return files;"," }",' const r = cp.spawnSync("lsof", ["-nP", "-w", "-F", "pfatn", "-p", pids.join(",")], { encoding: "utf8", timeout: 10000 });',' if (r.error || typeof r.stdout !== "string") return files;',' let access = "", type = "";',' for (const line of r.stdout.split("\\n")) {'," const key = line[0], value = line.slice(1);",' if (key === "f") { access = ""; type = ""; }',' else if (key === "a") access = value;',' else if (key === "t") type = value;',' else if (key === "n" && (access === "w" || access === "u") && type === "REG") files.add(value);'," }"," return files;","}","let lastActivity = Date.now(), prevAt = lastActivity, prevCpu = new Map(), watched = [logPath];","try { prevCpu = tree(processes()); } catch {}","function record() {",' fs.writeFileSync(out + ".tmp", lastActivity + " " + prevAt + "\\n" + watched.join("\\n") + "\\n");',' fs.renameSync(out + ".tmp", out);',"}","function sample() {",' try { process.kill(rootPid, 0); } catch (e) { if (e.code !== "EPERM") process.exit(0); }'," const at = Date.now();"," const cpus = tree(processes());"," let used = 0;"," for (const [pid, cpu] of cpus) used += Math.max(0, cpu - (prevCpu.get(pid) || 0));"," const paths = new Set([logPath]);"," let changed = false;"," for (const file of writableFiles([...cpus.keys()])) {"," try {"," const st = fs.statSync(file);"," if (!st.isFile()) continue;"," paths.add(fs.realpathSync(file));"," if (st.mtimeMs > prevAt) changed = true;"," } catch {}"," }"," try { if (fs.statSync(logPath).mtimeMs > prevAt) changed = true; } catch {}"," if (at - prevAt > 3 * interval) changed = true;"," if (changed || used > 0.02 * (at - prevAt) / 1000) lastActivity = at;"," watched = [...paths];"," prevAt = at;"," prevCpu = cpus;"," record();","}","record();","setInterval(() => { try { sample(); } catch {} }, interval);"].join(" "),n=['const http = require("node:http");',"const done = () => process.exit(0);",'const req = http.request({ socketPath: process.argv[1], path: "/job-exit", method: "POST", headers: { "content-type": "application/json" }, timeout: 3000 }, (res) => { res.resume(); res.on("end", done); });','req.on("error", done);','req.on("timeout", done);',"req.end(JSON.stringify({ node: process.argv[2], job: process.argv[3] }));"].join(" "),r=['"$8" -e '+JSON.stringify(s)+' "$$" "$2" "$9" &',"sampler=$!","n=$(command -v nice)",'${n:+"$n" -n "$7"} "$6" "$1" 2>&1 | "$8" -e '+JSON.stringify(t)+' "$2"',"status=${PIPESTATUS[0]}",'kill "$sampler" 2>/dev/null','echo "$status" > "$3"','if [ -n "${10:-}" ]; then "$8" -e '+JSON.stringify(n)+' "${10}" "${11:-}" "${12:-}" </dev/null >/dev/null 2>&1 & fi','mv "$4" "$5" 2>/dev/null || true'].join(`
4
- `);export{e as BACKGROUND_BASH_LOG_TRUNCATION_MARKER,r as BASH_JOB_SUPERVISOR_SCRIPT,c as MAX_BACKGROUND_BASH_LOG_BYTES};
3
+ `,t=['const fs = require("node:fs");',"const cap = 10485760;",`const marker = Buffer.from(${JSON.stringify(e)});`,"const prefixCap = cap - marker.length;",'const fd = fs.openSync(process.argv[1], "w");',"let written = 0;","let truncated = false;",'process.stdin.on("data", (chunk) => {'," if (truncated) return;"," const available = prefixCap - written;"," if (available > 0) {"," const prefix = chunk.subarray(0, available);"," fs.writeSync(fd, prefix);"," written += prefix.length;"," if (prefix.length === chunk.length) return;"," }"," fs.writeSync(fd, marker);"," truncated = true;","});",'process.stdin.on("end", () => fs.closeSync(fd));'].join(" "),s=['const fs = require("node:fs"), cp = require("node:child_process");',"const rootPid = Number(process.argv[1]), out = process.argv[3];","let logPath = process.argv[2];","try { logPath = fs.realpathSync(logPath); } catch {}","const interval = Number(process.env.CRTR_BASH_ACTIVITY_SAMPLE_MS) || 60000;",'const linux = fs.existsSync("/proc/self/stat");',"function processes() {"," const procs = new Map();"," if (linux) {",' for (const e of fs.readdirSync("/proc")) {'," if (!/^[0-9]+$/.test(e)) continue;"," try {",' const s = fs.readFileSync("/proc/" + e + "/stat", "utf8");',' const r = s.slice(s.lastIndexOf(")") + 2).split(" ");'," procs.set(Number(e), { ppid: Number(r[1]), cpu: (Number(r[11]) + Number(r[12])) / 100 });"," } catch {}"," }"," return procs;"," }",' const ps = cp.execFileSync("ps", ["-ax", "-o", "pid=,ppid=,time="], { encoding: "utf8", timeout: 5000 });',' for (const line of ps.split("\\n")) {'," const f = line.trim().split(/\\s+/);"," if (f.length < 3) continue;",' const [days, clock] = f[2].includes("-") ? f[2].split("-") : ["0", f[2]];',' const cpu = clock.split(":").reduce((t, x) => t * 60 + Number(x), 0) + Number(days) * 86400;'," if (Number.isFinite(cpu)) procs.set(Number(f[0]), { ppid: Number(f[1]), cpu });"," }"," return procs;","}","function tree(procs) {"," const cpus = new Map(), stack = [rootPid];"," while (stack.length > 0) {"," const pid = stack.pop();"," if (pid === process.pid || cpus.has(pid) || !procs.has(pid)) continue;"," cpus.set(pid, procs.get(pid).cpu);"," for (const [child, p] of procs) if (p.ppid === pid) stack.push(child);"," }"," return cpus;","}","function writableFiles(pids) {"," const files = new Set();"," if (linux) {"," for (const pid of pids) {"," let fds = [];",' try { fds = fs.readdirSync("/proc/" + pid + "/fd"); } catch {}'," for (const fd of fds) {"," try {",' const info = fs.readFileSync("/proc/" + pid + "/fdinfo/" + fd, "utf8").match(/flags:\\s*([0-7]+)/);'," if (info === null || (parseInt(info[1], 8) & 3) === 0) continue;",' files.add(fs.readlinkSync("/proc/" + pid + "/fd/" + fd));'," } catch {}"," }"," }"," return files;"," }",' const r = cp.spawnSync("lsof", ["-nP", "-w", "-F", "pfatn", "-p", pids.join(",")], { encoding: "utf8", timeout: 10000 });',' if (r.error || typeof r.stdout !== "string") return files;',' let access = "", type = "";',' for (const line of r.stdout.split("\\n")) {'," const key = line[0], value = line.slice(1);",' if (key === "f") { access = ""; type = ""; }',' else if (key === "a") access = value;',' else if (key === "t") type = value;',' else if (key === "n" && (access === "w" || access === "u") && type === "REG") files.add(value);'," }"," return files;","}","let lastActivity = Date.now(), prevAt = lastActivity, prevCpu = new Map(), watched = [logPath];","try { prevCpu = tree(processes()); } catch {}","const socket = process.argv[4], node = process.argv[5], job = process.argv[6];","const notifyEvery = Number(process.env.CRTR_BASH_ACTIVITY_NOTIFY_MS) || 300000;","let notified = lastActivity, notifiedAt = 0;","function notify() {"," if (!socket) return;"," notified = lastActivity; notifiedAt = Date.now();",' const req = require("node:http").request({ socketPath: socket, path: "/job-activity", method: "POST", headers: { "content-type": "application/json" }, timeout: 3000 }, (res) => res.resume());',' req.on("error", () => {}); req.on("timeout", () => req.destroy());'," req.end(JSON.stringify({ node, job }));","}","function record() {",' fs.writeFileSync(out + ".tmp", lastActivity + " " + prevAt + "\\n" + watched.join("\\n") + "\\n");',' fs.renameSync(out + ".tmp", out);',"}","function sample() {",' try { process.kill(rootPid, 0); } catch (e) { if (e.code !== "EPERM") process.exit(0); }'," const at = Date.now();"," const cpus = tree(processes());"," let used = 0;"," for (const [pid, cpu] of cpus) used += Math.max(0, cpu - (prevCpu.get(pid) || 0));"," const paths = new Set([logPath]);"," let changed = false;"," for (const file of writableFiles([...cpus.keys()])) {"," try {"," const st = fs.statSync(file);"," if (!st.isFile()) continue;"," paths.add(fs.realpathSync(file));"," if (st.mtimeMs > prevAt) changed = true;"," } catch {}"," }"," try { if (fs.statSync(logPath).mtimeMs > prevAt) changed = true; } catch {}"," if (at - prevAt > 3 * interval) changed = true;"," if (changed || used > 0.02 * (at - prevAt) / 1000) lastActivity = at;"," watched = [...paths];"," prevAt = at;"," prevCpu = cpus;"," record();"," if (lastActivity !== notified && at - notifiedAt >= notifyEvery) notify();","}","record();","setInterval(() => { try { sample(); } catch {} }, interval);"].join(" "),n=['const http = require("node:http");',"const done = () => process.exit(0);",'const req = http.request({ socketPath: process.argv[1], path: "/job-exit", method: "POST", headers: { "content-type": "application/json" }, timeout: 3000 }, (res) => { res.resume(); res.on("end", done); });','req.on("error", done);','req.on("timeout", done);',"req.end(JSON.stringify({ node: process.argv[2], job: process.argv[3] }));"].join(" "),o=['"$8" -e '+JSON.stringify(s)+' "$$" "$2" "$9" "${10:-}" "${11:-}" "${12:-}" &',"sampler=$!","n=$(command -v nice)",'${n:+"$n" -n "$7"} "$6" "$1" 2>&1 | "$8" -e '+JSON.stringify(t)+' "$2"',"status=${PIPESTATUS[0]}",'kill "$sampler" 2>/dev/null','echo "$status" > "$3"','if [ -n "${10:-}" ]; then "$8" -e '+JSON.stringify(n)+' "${10}" "${11:-}" "${12:-}" </dev/null >/dev/null 2>&1 & fi','mv "$4" "$5" 2>/dev/null || true'].join(`
4
+ `);export{e as BACKGROUND_BASH_LOG_TRUNCATION_MARKER,o as BASH_JOB_SUPERVISOR_SCRIPT,r as MAX_BACKGROUND_BASH_LOG_BYTES};
@@ -36,7 +36,16 @@ export declare function recordCreateRequestNode(requestKey: string, nodeId: stri
36
36
  * after a daemon restart resumes the same identity instead of minting another.
37
37
  * Only the first caller binds: two API processes holding one unbound key race
38
38
  * here, and each gets back the id the key actually names. */
39
- export declare function reserveCreateRequestNode(requestKey: string, nodeId: string): Promise<string | null>;
39
+ export declare function reserveCreateRequestNode(requestKey: string, nodeId: string, owner: string): Promise<string | null>;
40
+ /** How long a create's lease lasts without renewal; its owner renews it every {@link CREATE_LEASE_RENEW_MS}. */
41
+ export declare const CREATE_LEASE_MS = 30000;
42
+ export declare const CREATE_LEASE_RENEW_MS = 10000;
43
+ /** Take over a bound, unfinished create whose owner's lease has lapsed (or never existed). True when `owner` now holds it. */
44
+ export declare function claimCreateLease(requestKey: string, nodeId: string, owner: string): Promise<boolean>;
45
+ /** Extend the lease while `owner` still holds it. */
46
+ export declare function renewCreateLease(requestKey: string, owner: string): Promise<void>;
47
+ /** Whether another owner's lease on the key is still unexpired. */
48
+ export declare function createLeaseLive(requestKey: string): Promise<boolean>;
40
49
  export declare function completeCreateRequest(requestKey: string, nodeId: string): Promise<void>;
41
50
  /** Forget an unserved reservation after a pre-birth failure. A record that
42
51
  * names a durable node is never removed by this path. */
@@ -1,8 +1,8 @@
1
- var ue=Object.defineProperty;var i=(e,n)=>ue(e,"name",{value:n,configurable:!0});import{envNodeId as C}from"../../shared/env.js";import{lstatSync as ce,realpathSync as H,rmdirSync as le,rmSync as _e,statSync as pe}from"node:fs";import{basename as fe,dirname as M,isAbsolute as we,join as S,relative as Ee,resolve as ye,sep as me}from"node:path";import{removeTreeBeneath as P}from"../spaces/open-beneath.js";import{emitEvent as Ne}from"../events/emit.js";import{deleteNodeSandboxes as $}from"../runtime/runner/delete-sandboxes.js";import{withCanvasWrite as p,openDb as d}from"./db.js";import{conversationStore as Re,ConversationNotFoundError as Se}from"../conversation-store/index.js";import{hasUnseenWakeMail as he,UNSEEN_WAKE_MAIL_SQL as Oe}from"./deliveries.js";import{isAppRun as q}from"./app-run.js";import{registerOutcomeAction as B}from"./outcome-actions.js";import{publish as Te}from"../graph/events.js";import{nodeObject as Le}from"../graph/objects.js";import{findNodeBySessionFileSql as De}from"./sessions.js";import{hydrateFault as ge}from"./recovery.js";import{hasUnreconciledWorktree as ve,openWorktree as Ae,readWorktree as ke,worktreeFromRow as Ue}from"./worktrees.js";import{isPidAlive as xe,isPidPresent as z,recordedPidLiveness as je}from"./pid.js";import{isCloudRole as We}from"./person-state.js";import{ensureHome as be,jobDir as Ie,nodeDir as Fe,nodeRunDir as J}from"./paths.js";import{appForNode as Ce,ensureNodeDirs as He,nodeAgentDir as Me}from"./node-agent-paths.js";import{appSpace as L}from"../layout.js";import{createObject as Pe,getById as D,ownerForGrantee as $e,setObjectKind as qe,setObjectName as Be}from"../graph/objects.js";import{profileObject as ze}from"../graph/reader.js";import{writeActsFor as Y}from"../permissions/facts.js";import{CrtrError as Je}from"../errors.js";import{deleteNodeWithOwned as Ye}from"../graph/deletion.js";import{SUBTREE_ALL_IDS_SQL as Qe,SUBTREE_IDS_SQL as Ve}from"./tree.js";import{filterAsync as y,mapAsync as h}from"../async-array.js";function w(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(w,"jsonValue");async function Wn(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(Wn,"assertRunNotDeleting");async function Q(e,n,t){try{return await ze(e,n,t)}catch(a){if(a instanceof Je&&a.code==="not_found")return null;throw a}}i(Q,"profileObjectFor");async function Ke(e,n){const t=await $e(n,e.grantee??"app:terminal"),a=e.profile_id?await Q(n,e.profile_id,t):null;await Pe(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 Y(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, usage_json, deleting_at, caused_by, app) VALUES (${Array(42).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,w(e.persona_ack,"persona_ack"),w(e.review_binding,"review_binding"),w(e.launch,"launch"),w(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.usage_json??null,e.deleting_at??null,e.caused_by??null,t.id)}i(Ke,"seedRow");function V(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 ge(Object.fromEntries(n))}i(V,"faultFrom");const K=i(e=>e.turn_open_at!=null&&e.turn_closed_at==null,"turnOpen"),G=i(e=>e||We(),"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,usage_json:e.usage_json??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,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=z(n.pi_pid),a=V(e);return n.fault=a?.link==="pi\u2192provider"&&a.retry.by==="daemon"&&a.retry.disposition==="auto"&&!t?null:a,n.streaming=K(e)&&G(t),n}i(f,"rowFrom");async function g(e,n){return n??=await ke(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,cycle_pending:e.cycle_pending===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(g,"metaFrom");async function bn(e,n={}){return be(),await p(async t=>{await Ke(e,t),e.managed_worktree!==void 0&&e.managed_worktree!==null&&await Ae(e.node_id,e.managed_worktree,t),n.outcomeDelivery!==void 0&&await B(t,e.node_id,n.outcomeDelivery),await n.withinCreate?.(t,e)}),await He(e.node_id),await O(e.node_id)}i(bn,"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 g(n)}i(O,"getNode");async function In(e){if(e.length===0)return[];const n=A.map(o=>`w.${o} AS worktree_${o}`).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(o=>[o.node_id,o]));return await h(e.map(o=>a.get(o)).filter(o=>o!==void 0),async o=>await g(o,Z(o)))}i(In,"getNodes");const Ge=1440*60*1e3;function X(e){return{requestKey:e.request_key,nodeId:e.node_id,state:e.state}}i(X,"createRequestRecord");async function Fn(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:X(n)}i(Fn,"findCreateRequest");async function Cn(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+Ge);const a=await n.prepareUncached("SELECT request_key, node_id, state FROM create_requests WHERE request_key = ?").get(e);return X(a)})}i(Cn,"reserveCreateRequest");async function Hn(e=Date.now()){return Number((await(await d()).prepareUncached("DELETE FROM create_requests WHERE expires_at <= ?").run(e)).changes)}i(Hn,"pruneExpiredCreateRequests");async function Mn(e,n){await(await d()).prepareUncached("UPDATE create_requests SET node_id = ?, state = 'complete' WHERE request_key = ?").run(n,e)}i(Mn,"recordCreateRequestNode");async function Pn(e,n){const t=await d();return await t.prepareUncached("UPDATE create_requests SET node_id = ?, state = 'reserved' WHERE request_key = ? AND node_id IS NULL").run(n,e),(await t.prepareUncached("SELECT node_id FROM create_requests WHERE request_key = ?").get(e))?.node_id??null}i(Pn,"reserveCreateRequestNode");async function $n(e,n){await(await d()).prepareUncached("UPDATE create_requests SET state = 'complete' WHERE request_key = ? AND node_id = ?").run(e,n)}i($n,"completeCreateRequest");async function qn(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(qn,"abandonCreateRequest");function Bn(e){return ye(e)}i(Bn,"canonicalSessionFile");async function zn(e){const n=await De(e);return n===null?null:await O(n)}i(zn,"findNodeBySessionFile");async function Jn(e){const n=await(await d()).prepare("SELECT * FROM node_rows WHERE node_id = ?").get(e);return n?f(n):null}i(Jn,"getRow");async function Yn(e){const n=await(await d()).prepare("SELECT * FROM node_rows WHERE pane = ?").get(e);return n?f(n):null}i(Yn,"getRowByPane");async function Qn(e){return(await(await d()).prepare(`SELECT * FROM node_rows
1
+ var ce=Object.defineProperty;var i=(e,n)=>ce(e,"name",{value:n,configurable:!0});import{envNodeId as H}from"../../shared/env.js";import{lstatSync as le,realpathSync as M,rmdirSync as _e,rmSync as pe,statSync as fe}from"node:fs";import{basename as Ee,dirname as P,isAbsolute as we,join as S,relative as ye,resolve as me,sep as Ne}from"node:path";import{removeTreeBeneath as $}from"../spaces/open-beneath.js";import{emitEvent as Re}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 Se,ConversationNotFoundError as he}from"../conversation-store/index.js";import{hasUnseenWakeMail as Oe,UNSEEN_WAKE_MAIL_SQL as Le}from"./deliveries.js";import{isAppRun as B}from"./app-run.js";import{registerOutcomeAction as z}from"./outcome-actions.js";import{publish as Te}from"../graph/events.js";import{nodeObject as De}from"../graph/objects.js";import{findNodeBySessionFileSql as Ae}from"./sessions.js";import{hydrateFault as ge}from"./recovery.js";import{hasUnreconciledWorktree as ve,openWorktree as ke,readWorktree as xe,worktreeFromRow as Ue}from"./worktrees.js";import{isPidAlive as We,isPidPresent as J,recordedPidLiveness as je}from"./pid.js";import{isCloudRole as be}from"./person-state.js";import{ensureHome as Ie,jobDir as Fe,nodeDir as Ce,nodeRunDir as Y}from"./paths.js";import{appForNode as He,ensureNodeDirs as Me,nodeAgentDir as Pe}from"./node-agent-paths.js";import{appSpace as T}from"../layout.js";import{createObject as $e,getById as D,ownerForGrantee as qe,setObjectKind as Be,setObjectName as ze}from"../graph/objects.js";import{profileObject as Je}from"../graph/reader.js";import{writeActsFor as Q}from"../permissions/facts.js";import{CrtrError as Ye}from"../errors.js";import{deleteNodeWithOwned as Qe}from"../graph/deletion.js";import{SUBTREE_ALL_IDS_SQL as Ve,SUBTREE_IDS_SQL as Ke}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 bn(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(bn,"assertRunNotDeleting");async function V(e,n,t){try{return await Je(e,n,t)}catch(a){if(a instanceof Ye&&a.code==="not_found")return null;throw a}}i(V,"profileObjectFor");async function Ge(e,n){const t=await qe(n,e.grantee??"app:terminal"),a=e.profile_id?await V(n,e.profile_id,t):null;await $e(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, usage_json, deleting_at, caused_by, app) VALUES (${Array(42).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.usage_json??null,e.deleting_at??null,e.caused_by??null,t.id)}i(Ge,"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 ge(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||be(),"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,usage_json:e.usage_json??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,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 xe(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,cycle_pending:e.cycle_pending===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 In(e,n={}){return Ie(),await p(async t=>{await Ge(e,t),e.managed_worktree!==void 0&&e.managed_worktree!==null&&await ke(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 Me(e.node_id),await O(e.node_id)}i(In,"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 Fn(e){if(e.length===0)return[];const n=k.map(o=>`w.${o} AS worktree_${o}`).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(o=>[o.node_id,o]));return await h(e.map(o=>a.get(o)).filter(o=>o!==void 0),async o=>await A(o,ee(o)))}i(Fn,"getNodes");const Xe=1440*60*1e3;function Z(e){return{requestKey:e.request_key,nodeId:e.node_id,state:e.state}}i(Z,"createRequestRecord");async function Cn(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(Cn,"findCreateRequest");async function Hn(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+Xe);const a=await n.prepareUncached("SELECT request_key, node_id, state FROM create_requests WHERE request_key = ?").get(e);return Z(a)})}i(Hn,"reserveCreateRequest");async function Mn(e=Date.now()){return Number((await(await d()).prepareUncached("DELETE FROM create_requests WHERE expires_at <= ?").run(e)).changes)}i(Mn,"pruneExpiredCreateRequests");async function Pn(e,n){await(await d()).prepareUncached("UPDATE create_requests SET node_id = ?, state = 'complete' WHERE request_key = ?").run(n,e)}i(Pn,"recordCreateRequestNode");async function $n(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($n,"reserveCreateRequestNode");const g=3e4,qn=1e4;async function Bn(e,n,t){const a=Date.now(),o=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(o.changes)>0}i(Bn,"claimCreateLease");async function zn(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(zn,"renewCreateLease");async function Jn(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(Jn,"createLeaseLive");async function Yn(e,n){await(await d()).prepareUncached("UPDATE create_requests SET state = 'complete' WHERE request_key = ? AND node_id = ?").run(e,n)}i(Yn,"completeCreateRequest");async function Qn(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(Qn,"abandonCreateRequest");function Vn(e){return me(e)}i(Vn,"canonicalSessionFile");async function Kn(e){const n=await Ae(e);return n===null?null:await O(n)}i(Kn,"findNodeBySessionFile");async function Gn(e){const n=await(await d()).prepare("SELECT * FROM node_rows WHERE node_id = ?").get(e);return n?f(n):null}i(Gn,"getRow");async function Xn(e){const n=await(await d()).prepare("SELECT * FROM node_rows WHERE pane = ?").get(e);return n?f(n):null}i(Xn,"getRowByPane");async function Zn(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(Qn,"dueNodeDeadlines");async function Vn(e,n){return Number((await(await d()).prepare("UPDATE nodes SET deadline_at = ? WHERE node_id = ?").run(n,e)).changes)===1}i(Vn,"setNodeDeadline");async function Kn(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),o=t.prepare("UPDATE nodes SET deadline_at = ? WHERE node_id = ? AND deadline_at = ?");let r=0;for(const s of a){const c=Date.parse(s.deadline_at);Number.isNaN(c)||(r+=Number((await o.run(new Date(c+n).toISOString(),s.node_id,s.deadline_at)).changes))}return r})}i(Kn,"shiftProfileNodeDeadlines");function v(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(v,"sqlInput");async function Gn(e,n){const t=[],a=i((r,s=r)=>{Object.prototype.hasOwnProperty.call(n,r)&&t.push([s,v(n[r],r)])},"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",w(n.persona_ack,"persona_ack")]),Object.prototype.hasOwnProperty.call(n,"review_binding")&&t.push(["review_binding_json",w(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",w(n.scopes,"scopes")]),Object.prototype.hasOwnProperty.call(n,"launch")&&t.push(["launch_config_json",w(n.launch,"launch")]);const o=i(r=>Object.prototype.hasOwnProperty.call(n,r),"has");return await p(async r=>{const s=await D(r,e);if(s===null||s.type!=="node")throw new Error(`unknown node: ${e}`);if(o("name")&&await Be(r,s,v(n.name,"name")),o("kind")&&await qe(r,s,v(n.kind,"kind")),t.length===0)return;if(o("profile_id")){const u=await r.prepare("SELECT app FROM nodes WHERE node_id = ?").get(e),_=u?.app?await D(r,u.app):null;if(_){const E=n.profile_id?await Q(r,n.profile_id,_):null;await r.prepare("UPDATE objects SET owner = ? WHERE id = ?").run((E??_).id,e);const N=(await r.prepare("SELECT sub FROM nodes WHERE node_id = ?").get(e)).sub;E===null&&N&&await Y(r,e,N)}}if((await r.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(Gn,"updateNode");async function Xn(e,n){await(await d()).prepare("UPDATE nodes SET status = ? WHERE node_id = ?").run(n,e)}i(Xn,"setStatus");async function Zn(e,n){await(await d()).prepare("UPDATE nodes SET intent = ? WHERE node_id = ?").run(n??null,e)}i(Zn,"setIntent");async function et(e,n,t={}){if(t.outcome===void 0){const o=[],r=[];Object.prototype.hasOwnProperty.call(n,"status")&&(o.push("status = ?"),r.push(n.status??null)),Object.prototype.hasOwnProperty.call(n,"intent")&&(o.push("intent = ?"),r.push(n.intent??null)),Object.prototype.hasOwnProperty.call(n,"terminal_reason")&&(o.push("terminal_reason = ?"),r.push(n.terminal_reason??null));const s=["node_id = ?"];r.push(e),t.fromStatuses!==void 0&&(s.push(`status IN (${t.fromStatuses.map(()=>"?").join(", ")})`),r.push(...t.fromStatuses)),t.requireNoFinalReport===!0&&s.push("final_report IS NULL");const c=await(await d()).prepareUncached(`UPDATE nodes SET ${o.join(", ")} WHERE ${s.join(" AND ")}`).run(...r);return Number(c.changes)}const a=t.outcome;return await p(async o=>{const r=[],s=[];Object.prototype.hasOwnProperty.call(n,"status")&&(r.push("status = ?"),s.push(n.status??null)),Object.prototype.hasOwnProperty.call(n,"intent")&&(r.push("intent = ?"),s.push(n.intent??null)),Object.prototype.hasOwnProperty.call(n,"terminal_reason")&&(r.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");r.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 o.prepareUncached(`UPDATE nodes SET ${r.join(", ")} WHERE ${u.join(" AND ")}`).run(...s);if(Number(_.changes)===0)return 0;const E=await o.prepare("SELECT outcome_at FROM nodes WHERE node_id = ?").get(e);return(a.supersede===!0||E.outcome_at===a.at)&&a.documentJson!==null&&a.documentJson!==void 0&&await Te(o,{event:"outcome",object:await Le(o,e),actor:null,attrs:{revision:Number((await o.prepare("SELECT outcome_revision FROM nodes WHERE node_id = ?").get(e)).outcome_revision)},messageBody:JSON.parse(a.documentJson)}),Number(_.changes)})}i(et,"transitionStatusIntent");async function nt(e){return(await(await d()).prepare("SELECT final_report FROM nodes WHERE node_id = ?").get(e))?.final_report??null}i(nt,"getFinalReport");async function tt(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(tt,"clearFinalReportIfMatches");async function at(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(at,"setPresence");async function it(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(it,"recordLaunch");async function ot(e,n){await(await d()).prepare("UPDATE nodes SET last_settled_at = ? WHERE node_id = ?").run(n,e)}i(ot,"recordSettledTurn");async function rt(e,n){await(await d()).prepare("UPDATE nodes SET frozen_at = ? WHERE node_id = ?").run(n,e)}i(rt,"setFrozen");async function st(e){await(await d()).prepare("UPDATE nodes SET frozen_at = NULL WHERE node_id = ?").run(e)}i(st,"clearFrozen");async function dt(e,n){await(await d()).prepare("UPDATE nodes SET respawn_failures = ?, respawn_not_before = ? WHERE node_id = ?").run(n.failures,n.notBefore,e)}i(dt,"recordRespawnAttempt");const m="node_id NOT IN (SELECT node_id FROM warm_pool)",A=["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 Z(e){return e.worktree_state===null?null:Ue(Object.fromEntries(A.map(n=>[n,e[`worktree_${n}`]])))}i(Z,"worktreeFromProjection");async function ut(e){const n=A.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 g(a,Z(a)))}i(ut,"listNodesByProfile");async function ct(){return(await(await d()).prepare(`SELECT
4
+ ORDER BY deadline_at, created, node_id`).all(e)).map(f)}i(Zn,"dueNodeDeadlines");async function et(e,n){return Number((await(await d()).prepare("UPDATE nodes SET deadline_at = ? WHERE node_id = ?").run(n,e)).changes)===1}i(et,"setNodeDeadline");async function nt(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),o=t.prepare("UPDATE nodes SET deadline_at = ? WHERE node_id = ? AND deadline_at = ?");let r=0;for(const s of a){const c=Date.parse(s.deadline_at);Number.isNaN(c)||(r+=Number((await o.run(new Date(c+n).toISOString(),s.node_id,s.deadline_at)).changes))}return r})}i(nt,"shiftProfileNodeDeadlines");function v(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(v,"sqlInput");async function tt(e,n){const t=[],a=i((r,s=r)=>{Object.prototype.hasOwnProperty.call(n,r)&&t.push([s,v(n[r],r)])},"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 o=i(r=>Object.prototype.hasOwnProperty.call(n,r),"has");return await p(async r=>{const s=await D(r,e);if(s===null||s.type!=="node")throw new Error(`unknown node: ${e}`);if(o("name")&&await ze(r,s,v(n.name,"name")),o("kind")&&await Be(r,s,v(n.kind,"kind")),t.length===0)return;if(o("profile_id")){const u=await r.prepare("SELECT app FROM nodes WHERE node_id = ?").get(e),_=u?.app?await D(r,u.app):null;if(_){const w=n.profile_id?await V(r,n.profile_id,_):null;await r.prepare("UPDATE objects SET owner = ? WHERE id = ?").run((w??_).id,e);const N=(await r.prepare("SELECT sub FROM nodes WHERE node_id = ?").get(e)).sub;w===null&&N&&await Q(r,e,N)}}if((await r.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(tt,"updateNode");async function at(e,n){await(await d()).prepare("UPDATE nodes SET status = ? WHERE node_id = ?").run(n,e)}i(at,"setStatus");async function it(e,n){await(await d()).prepare("UPDATE nodes SET intent = ? WHERE node_id = ?").run(n??null,e)}i(it,"setIntent");async function ot(e,n,t={}){if(t.outcome===void 0){const o=[],r=[];Object.prototype.hasOwnProperty.call(n,"status")&&(o.push("status = ?"),r.push(n.status??null)),Object.prototype.hasOwnProperty.call(n,"intent")&&(o.push("intent = ?"),r.push(n.intent??null)),Object.prototype.hasOwnProperty.call(n,"terminal_reason")&&(o.push("terminal_reason = ?"),r.push(n.terminal_reason??null));const s=["node_id = ?"];r.push(e),t.fromStatuses!==void 0&&(s.push(`status IN (${t.fromStatuses.map(()=>"?").join(", ")})`),r.push(...t.fromStatuses)),t.requireNoFinalReport===!0&&s.push("final_report IS NULL");const c=await(await d()).prepareUncached(`UPDATE nodes SET ${o.join(", ")} WHERE ${s.join(" AND ")}`).run(...r);return Number(c.changes)}const a=t.outcome;return await p(async o=>{const r=[],s=[];Object.prototype.hasOwnProperty.call(n,"status")&&(r.push("status = ?"),s.push(n.status??null)),Object.prototype.hasOwnProperty.call(n,"intent")&&(r.push("intent = ?"),s.push(n.intent??null)),Object.prototype.hasOwnProperty.call(n,"terminal_reason")&&(r.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");r.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 o.prepareUncached(`UPDATE nodes SET ${r.join(", ")} WHERE ${u.join(" AND ")}`).run(...s);if(Number(_.changes)===0)return 0;const w=await o.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 Te(o,{event:"outcome",object:await De(o,e),actor:null,attrs:{revision:Number((await o.prepare("SELECT outcome_revision FROM nodes WHERE node_id = ?").get(e)).outcome_revision)},messageBody:JSON.parse(a.documentJson)}),Number(_.changes)})}i(ot,"transitionStatusIntent");async function rt(e){return(await(await d()).prepare("SELECT final_report FROM nodes WHERE node_id = ?").get(e))?.final_report??null}i(rt,"getFinalReport");async function st(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(st,"clearFinalReportIfMatches");async function dt(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(dt,"setPresence");async function ut(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(ut,"recordLaunch");async function ct(e,n){await(await d()).prepare("UPDATE nodes SET last_settled_at = ? WHERE node_id = ?").run(n,e)}i(ct,"recordSettledTurn");async function lt(e,n){await(await d()).prepare("UPDATE nodes SET frozen_at = ? WHERE node_id = ?").run(n,e)}i(lt,"setFrozen");async function _t(e){await(await d()).prepare("UPDATE nodes SET frozen_at = NULL WHERE node_id = ?").run(e)}i(_t,"clearFrozen");async function pt(e,n){await(await d()).prepare("UPDATE nodes SET respawn_failures = ?, respawn_not_before = ? WHERE node_id = ?").run(n.failures,n.notBefore,e)}i(pt,"recordRespawnAttempt");const m="node_id NOT IN (SELECT node_id FROM warm_pool)",k=["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:Ue(Object.fromEntries(k.map(n=>[n,e[`worktree_${n}`]])))}i(ee,"worktreeFromProjection");async function ft(e){const n=k.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(ft,"listNodesByProfile");async function Et(){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 ue=Object.defineProperty;var i=(e,n)=>ue(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(ct,"browseNodes");async function lt(e,n){await(await d()).prepare(`UPDATE nodes
13
+ FROM node_rows WHERE ${m} ORDER BY created`).all()).map(f)}i(Et,"browseNodes");async function wt(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(lt,"updateNodeTelemetry");async function _t(){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)}i(wt,"updateNodeTelemetry");async function yt(){return(await(await d()).prepare(`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 ue=Object.defineProperty;var i=(e,n)=>ue(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=z(t),o=V(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:o?.link==="pi\u2192provider"&&o.retry.by==="daemon"&&o.retry.disposition==="auto"&&!a?null:o,streaming:K(n)&&G(a)}})}i(_t,"graphNodes");async function Xe(e){const n=[m],t=[];if(e?.under!==void 0&&(e.underInclusive===!0?(n.push(`(node_id IN (${Qe}) OR node_id = ?)`),t.push(e.under,e.under,e.under)):(n.push(`node_id IN (${Ve})`),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,o=>`\\${o}`)}%`)),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 o=Array.isArray(e.status)?e.status:[e.status];n.push(`status IN (${o.map(()=>"?").join(",")})`),t.push(...o)}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(Xe,"listNodes");const Ze=`SELECT
27
+ FROM node_rows WHERE ${m} ORDER BY created`).all()).map(n=>{const t=n.pi_pid??null,a=J(t),o=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:o?.link==="pi\u2192provider"&&o.retry.by==="daemon"&&o.retry.disposition==="auto"&&!a?null:o,streaming:G(n)&&X(a)}})}i(yt,"graphNodes");async function Ze(e){const n=[m],t=[];if(e?.under!==void 0&&(e.underInclusive===!0?(n.push(`(node_id IN (${Ve}) OR node_id = ?)`),t.push(e.under,e.under,e.under)):(n.push(`node_id IN (${Ke})`),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,o=>`\\${o}`)}%`)),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 o=Array.isArray(e.status)?e.status:[e.status];n.push(`status IN (${o.map(()=>"?").join(",")})`),t.push(...o)}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(Ze,"listNodes");const en=`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 pt(){return await(await d()).prepare(Ze).all()}i(pt,"listTerminalPlacementResidue");const en=`WITH candidates AS MATERIALIZED (
34
+ ORDER BY created`;async function mt(){return await(await d()).prepare(en).all()}i(mt,"listTerminalPlacementResidue");const nn=`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 ue=Object.defineProperty;var i=(e,n)=>ue(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 ft(){return(await(await d()).prepare(en).all()).map(f)}i(ft,"listNodesForSupervision");const ee=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"),nn=i(e=>`(${e}.status IN ('active', 'idle') OR ${ee(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 wt(e){return await(await d()).prepare(`SELECT node_id, cwd FROM nodes WHERE ${nn("nodes")} AND node_id != ?`).all(e)}i(wt,"resumableNodeCwds");async function Et(){return(await(await d()).prepare(`SELECT v.* FROM node_rows v
49
- WHERE ${ee("v")}
50
- AND EXISTS (SELECT 1 FROM deliveries d WHERE d.destination_id = v.node_id AND ${Oe("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(Et,"listParkedResidentsWithWakeMail");async function yt(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(yt,"registerWarmSpare");async function mt(e){return(await(await d()).prepare("DELETE FROM warm_pool WHERE node_id = ?").run(e)).changes>0}i(mt,"unregisterWarmSpare");async function k(e,n){const t=`SELECT w.node_id AS node_id, w.recipe_key AS recipe_key, w.created AS created,
48
+ ORDER BY v.created`;async function Nt(){return(await(await d()).prepare(nn).all()).map(f)}i(Nt,"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"),tn=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 Rt(e){return await(await d()).prepare(`SELECT node_id, cwd FROM nodes WHERE ${tn("nodes")} AND node_id != ?`).all(e)}i(Rt,"resumableNodeCwds");async function St(){return(await(await d()).prepare(`SELECT v.* FROM node_rows v
49
+ WHERE ${ne("v")}
50
+ AND EXISTS (SELECT 1 FROM deliveries d WHERE d.destination_id = v.node_id AND ${Le("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(St,"listParkedResidentsWithWakeMail");async function ht(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(ht,"registerWarmSpare");async function Ot(e){return(await(await d()).prepare("DELETE FROM warm_pool WHERE node_id = ?").run(e)).changes>0}i(Ot,"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(o=>({node_id:o.node_id,recipe_key:o.recipe_key,created:o.created,status:o.status,pi_pid:o.pi_pid??null,pi_pid_identity:o.pi_pid_identity??null}))}i(k,"warmSpareRowsFor");async function Nt(){return await k(await d())}i(Nt,"listWarmSpares");async function Rt(e){return await(await d()).prepare("SELECT 1 FROM warm_pool WHERE node_id = ?").get(e)!==void 0}i(Rt,"isWarmSpare");function ne(e){return e.status!=="active"&&e.status!=="idle"?!1:je(e.pi_pid,e.pi_pid_identity)==="alive"}i(ne,"spareIsClaimable");async function St(e,n,t={}){return await p(async a=>{const o=(await k(a,e)).find(ne);return o===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(o.node_id,t.requestKey)).changes===0||(await a.prepare("DELETE FROM warm_pool WHERE node_id = ?").run(o.node_id)).changes===0?null:(await a.prepare("UPDATE nodes SET created = ?, deadline_at = ? WHERE node_id = ?").run(n,t.deadlineAt??null,o.node_id),t.outcomeDelivery!==void 0&&await B(a,o.node_id,t.outcomeDelivery),o.node_id)})}i(St,"claimWarmSpare");async function ht(e){return(await k(await d(),e)).filter(ne).length}i(ht,"warmSpareCount");async function Ot(e){return(await(await d()).prepare("SELECT node_id FROM nodes WHERE parent = ? ORDER BY created").all(e)).map(n=>n.node_id)}i(Ot,"childrenOf");async function Tt(){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} ORDER BY created`).all()).map(e=>({node_id:e.node_id,name:e.name,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind??null,parent:e.parent??null,created:e.created,description:e.description??null}))}i(Tt,"rosterNodes");async function Lt(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(o=>({node_id:o.node_id,recipe_key:o.recipe_key,created:o.created,status:o.status,pi_pid:o.pi_pid??null,pi_pid_identity:o.pi_pid_identity??null}))}i(x,"warmSpareRowsFor");async function Lt(){return await x(await d())}i(Lt,"listWarmSpares");async function Tt(e){return await(await d()).prepare("SELECT 1 FROM warm_pool WHERE node_id = ?").get(e)!==void 0}i(Tt,"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 Dt(e,n,t={}){return await p(async a=>{const o=(await x(a,e)).find(te);return o===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(o.node_id,t.requestKey)).changes===0||(await a.prepare("DELETE FROM warm_pool WHERE node_id = ?").run(o.node_id)).changes===0?null:(await a.prepare("UPDATE nodes SET created = ?, deadline_at = ? WHERE node_id = ?").run(n,t.deadlineAt??null,o.node_id),t.outcomeDelivery!==void 0&&await z(a,o.node_id,t.outcomeDelivery),o.node_id)})}i(Dt,"claimWarmSpare");async function At(e){return(await x(await d(),e)).filter(te).length}i(At,"warmSpareCount");async function gt(e){return(await(await d()).prepare("SELECT node_id FROM nodes WHERE parent = ? ORDER BY created").all(e)).map(n=>n.node_id)}i(gt,"childrenOf");async function vt(){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} ORDER BY created`).all()).map(e=>({node_id:e.node_id,name:e.name,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind??null,parent:e.parent??null,created:e.created,description:e.description??null}))}i(vt,"rosterNodes");async function kt(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(Lt,"listResumableRoots");export*from"./tree.js";async function Dt(e,n,t){return await p(async a=>{const o=await a.prepare("SELECT status, final_report, frozen_at FROM nodes WHERE node_id = ? FOR UPDATE").get(e);return o===void 0?{kind:"missing"}:n(o)?{kind:"terminal",status:o.status,final_report:o.final_report}:{kind:"ran",result:await t()}})}i(Dt,"withFreshTerminalGuard");async function T(e){return await ve(e)}i(T,"hasUnreconciledManagedWorktree");async function te(e,n={}){return!["done","dead","canceled"].includes(e.status)||e.pi_pid!==null||e.frozen_at!==null||await T(e.node_id)||e.node_id===C()||q(e)?!1:n.pastTtl===!0||!["crashed","stranded",null].includes(e.terminal_reason??null)}i(te,"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 AND s.transcript_path 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(L(a.grantee).conversations,a.node_id)}])).values()]}i(U,"nodeConversationIds");async function x(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:o,path:r,dir:s}of e)if(!(await t.get(o)!==void 0||await a.get(o)!==void 0)&&ce(r,{throwIfNoEntry:!1})!==void 0){if(!tn(s,r)){console.error(`[canvas] not deleting transcript outside its node's conversations directory: ${r}`);continue}try{await Re().delete(o,r)}catch(c){if(!(c instanceof Se))throw c}}}i(x,"deleteNodeConversations");function tn(e,n){try{const t=Ee(H(e),S(H(M(n)),fe(n)));return t!==""&&t!==".."&&!t.startsWith(`..${me}`)&&!we(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}i(tn,"isBeneath");async function j(e,n){const t=await D(e,n);return t===null||t.deleted_at!==null?!1:(await Ye(e,t),!0)}i(j,"deleteNodeObject");async function W(e){return{nodeId:e,app:await O(e)===null?null:await Ce(e)}}i(W,"nodeFiles");async function ae({nodeId:e,app:n}){n!==null&&P(L(n).nodes,await Me(e,n)),P(M(J(e)),J(e))}i(ae,"removeNodeAppTrees");function ie({nodeId:e}){return[Fe(e)]}i(ie,"nodeOwnedDirs");function oe({nodeId:e,app:n}){if(n!==null)try{le(S(L(n).conversations,e))}catch(t){if(!["ENOENT","ENOTEMPTY"].includes(t.code??""))throw t}}i(oe,"removeNodeConversationDir");async function b(e){await ae(e);for(const n of ie(e))_e(n,{recursive:!0,force:!0});oe(e)}i(b,"removeNodeFiles");async function re(e){const n=await $(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(re,"requireSandboxesDeleted");async function gt(e){if(await T(e))return{deleted:!1};await re([e]);const n=await W(e),t=await U([e]),a=await p(async o=>(await j(o,e),{deleted:!0}));return await x(t),await b(n),a}i(gt,"deleteNode");async function vt(e){const n=[...new Set(e)];if(n.length===0)return[];const t=await y(n,T);if(t.length>0)throw new Error(`refusing to delete nodes with unreconciled managed worktrees: ${t.join(", ")}`);await re(n);const a=await h(n,W),o=await U(n),r=n.map(()=>"?").join(","),s=(await(await d()).prepareUncached(`SELECT node_id FROM nodes WHERE node_id IN (${r}) ORDER BY created`).all(...n)).map(({node_id:u})=>u),c=await y(s,async u=>await p(async _=>await j(_,u)));await x(o);for(const u of c){const _=a[n.indexOf(u)];await F(_,async()=>await b(_))}return c}i(vt,"deleteNodes");async function At(e){const n=e.dryRun??!1,t=e.includeStale??!1,a=Date.now()-e.ttlDays*864e5,o=new Date(a).toISOString(),r=C()??"",s=await d(),c=i(l=>de(l)<a,"quiet"),u=i(l=>({node_id:l.node_id,status:l.status,created:l.created}),"toPruned"),_=await an(),E=(await y((await s.prepare(`SELECT * FROM node_rows
58
+ ORDER BY created DESC`).all(e)).map(f)}i(kt,"listResumableRoots");export*from"./tree.js";async function xt(e,n,t){return await p(async a=>{const o=await a.prepare("SELECT status, final_report, frozen_at FROM nodes WHERE node_id = ? FOR UPDATE").get(e);return o===void 0?{kind:"missing"}:n(o)?{kind:"terminal",status:o.status,final_report:o.final_report}:{kind:"ran",result:await t()}})}i(xt,"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 AND s.transcript_path 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:o,path:r,dir:s}of e)if(!(await t.get(o)!==void 0||await a.get(o)!==void 0)&&le(r,{throwIfNoEntry:!1})!==void 0){if(!an(s,r)){console.error(`[canvas] not deleting transcript outside its node's conversations directory: ${r}`);continue}try{await Se().delete(o,r)}catch(c){if(!(c instanceof he))throw c}}}i(W,"deleteNodeConversations");function an(e,n){try{const t=ye(M(e),S(M(P(n)),Ee(n)));return t!==""&&t!==".."&&!t.startsWith(`..${Ne}`)&&!we(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}i(an,"isBeneath");async function j(e,n){const t=await D(e,n);return t===null||t.deleted_at!==null?!1:(await Qe(e,t),!0)}i(j,"deleteNodeObject");async function b(e){return{nodeId:e,app:await O(e)===null?null:await He(e)}}i(b,"nodeFiles");async function ie({nodeId:e,app:n}){n!==null&&$(T(n).nodes,await Pe(e,n)),$(P(Y(e)),Y(e))}i(ie,"removeNodeAppTrees");function oe({nodeId:e}){return[Ce(e)]}i(oe,"nodeOwnedDirs");function re({nodeId:e,app:n}){if(n!==null)try{_e(S(T(n).conversations,e))}catch(t){if(!["ENOENT","ENOTEMPTY"].includes(t.code??""))throw t}}i(re,"removeNodeConversationDir");async function I(e){await ie(e);for(const n of oe(e))pe(n,{recursive:!0,force:!0});re(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 Ut(e){if(await L(e))return{deleted:!1};await se([e]);const n=await b(e),t=await U([e]),a=await p(async o=>(await j(o,e),{deleted:!0}));return await W(t),await I(n),a}i(Ut,"deleteNode");async function Wt(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,b),o=await U(n),r=n.map(()=>"?").join(","),s=(await(await d()).prepareUncached(`SELECT node_id FROM nodes WHERE node_id IN (${r}) ORDER BY created`).all(...n)).map(({node_id:u})=>u),c=await y(s,async u=>await p(async _=>await j(_,u)));await W(o);for(const u of c){const _=a[n.indexOf(u)];await C(_,async()=>await I(_))}return c}i(Wt,"deleteNodes");async function jt(e){const n=e.dryRun??!1,t=e.includeStale??!1,a=Date.now()-e.ttlDays*864e5,o=new Date(a).toISOString(),r=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
60
60
  WHERE status IN ('dead', 'done', 'canceled') AND created < ?
61
- ORDER BY created`).all(o)).map(f),async l=>await te(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(o)).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(o)).map(f),async l=>l.node_id!==r&&!xe(l.pi_pid??null)&&(l.frozen_at??null)===null&&(l.respawn_not_before??null)===null&&l.intent!=="idle-release"&&!q(l)&&!await he(l.node_id)&&!await T(l.node_id)&&c(l)&&!await e.held(l.node_id))).map(u):[],R=await I([...E,...N]);return n||R.length===0?{pruned:R,dryRun:n}:{pruned:await se(R,e.removeDirs),dryRun:n}}i(At,"pruneNodes");async function an(){const e=await(await d()).prepare(`SELECT DISTINCT d.owner AS owner FROM watches w
63
+ ORDER BY created`).all(o)).map(f),async l=>l.node_id!==r&&!We(l.pi_pid??null)&&(l.frozen_at??null)===null&&(l.respawn_not_before??null)===null&&l.intent!=="idle-release"&&!B(l)&&!await Oe(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(jt,"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(an,"ownersOfWatchedDocuments");async function I(e){const t=(await d()).prepare("SELECT node_id FROM nodes WHERE run_id = ? AND node_id != ?"),a=new Set(e.map(o=>o.node_id));return await y(e,async o=>(await t.all(o.node_id,o.node_id)).every(r=>a.has(r.node_id)))}i(I,"retainRunRootsWithMembers");async function se(e,n){const t=new Set(await $(e.map(s=>s.node_id))),a=t.size===0?e:await I(e.filter(s=>!t.has(s.node_id)));if(a.length===0)return[];const o=await h(a,async s=>await W(s.node_id)),r=await U(a.map(s=>s.node_id));for(const s of a)await p(async c=>await j(c,s.node_id));if(await x(r),n!==void 0){for(const s of o)await F(s,async()=>{await ae(s),oe(s)});return n(o.flatMap(ie)),a}for(const s of o)await F(s,async()=>await b(s));return a}i(se,"deletePrunedNodes");async function F(e,n){try{await n()}catch(t){Ne({level:"error",event:"canvas.node_files.remove_failed",error:t,fields:{node_id:e.nodeId}})}}i(F,"eachNodeBestEffort");function de(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=pe(S(Ie(e.node_id),"telemetry.json"),{throwIfNoEntry:!1});t!==void 0&&t.mtimeMs>n&&(n=t.mtimeMs)}catch{}return n}i(de,"lastActivityMs");async function kt(e){const n=e.dryRun??!1,t=await Xe(),a=await y(t,async u=>await te(u)&&!await e.held(u.node_id)),o=t.length-a.length,r=Math.max(0,e.maxNodes-o),s=a.map(u=>({row:u,recency:de(u)})).sort((u,_)=>_.recency-u.recency).slice(r).map(({row:u})=>({node_id:u.node_id,status:u.status,created:u.created})),c=await I(s);return n||c.length===0?{pruned:c,dryRun:n}:{pruned:await se(c),dryRun:n}}i(kt,"pruneToLimit");export{ee as PARKED_RESIDENT_SQL,nn as RESUMABLE_NODE_SQL,qn as abandonCreateRequest,Wn as assertRunNotDeleting,ct as browseNodes,Bn as canonicalSessionFile,Ot as childrenOf,St as claimWarmSpare,tt as clearFinalReportIfMatches,st as clearFrozen,$n as completeCreateRequest,bn as createNode,gt as deleteNode,vt as deleteNodes,Qn as dueNodeDeadlines,Fn as findCreateRequest,zn as findNodeBySessionFile,nt as getFinalReport,O as getNode,In as getNodes,Jn as getRow,Yn as getRowByPane,_t as graphNodes,te as isCollectible,Rt as isWarmSpare,de as lastActivityMs,Xe as listNodes,ut as listNodesByProfile,ft as listNodesForSupervision,Et as listParkedResidentsWithWakeMail,Lt as listResumableRoots,pt as listTerminalPlacementResidue,Nt as listWarmSpares,W as nodeFiles,en as nodesForSupervisionSql,Hn as pruneExpiredCreateRequests,At as pruneNodes,kt as pruneToLimit,Mn as recordCreateRequestNode,it as recordLaunch,dt as recordRespawnAttempt,ot as recordSettledTurn,yt as registerWarmSpare,b as removeNodeFiles,Cn as reserveCreateRequest,Pn as reserveCreateRequestNode,wt as resumableNodeCwds,Tt as rosterNodes,rt as setFrozen,Zn as setIntent,Vn as setNodeDeadline,at as setPresence,Xn as setStatus,Kn as shiftProfileNodeDeadlines,Ze as terminalPlacementResidueSql,et as transitionStatusIntent,mt as unregisterWarmSpare,Gn as updateNode,lt as updateNodeTelemetry,ht as warmSpareCount,Dt 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))}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(o=>o.node_id));return await y(e,async o=>(await t.all(o.node_id,o.node_id)).every(r=>a.has(r.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 o=await h(a,async s=>await b(s.node_id)),r=await U(a.map(s=>s.node_id));for(const s of a)await p(async c=>await j(c,s.node_id));if(await W(r),n!==void 0){for(const s of o)await C(s,async()=>{await ie(s),re(s)});return n(o.flatMap(oe)),a}for(const s of o)await C(s,async()=>await I(s));return a}i(de,"deletePrunedNodes");async function C(e,n){try{await n()}catch(t){Re({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=fe(S(Fe(e.node_id),"telemetry.json"),{throwIfNoEntry:!1});t!==void 0&&t.mtimeMs>n&&(n=t.mtimeMs)}catch{}return n}i(ue,"lastActivityMs");async function bt(e){const n=e.dryRun??!1,t=await Ze(),a=await y(t,async u=>await ae(u)&&!await e.held(u.node_id)),o=t.length-a.length,r=Math.max(0,e.maxNodes-o),s=a.map(u=>({row:u,recency:ue(u)})).sort((u,_)=>_.recency-u.recency).slice(r).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(bt,"pruneToLimit");export{g as CREATE_LEASE_MS,qn as CREATE_LEASE_RENEW_MS,ne as PARKED_RESIDENT_SQL,tn as RESUMABLE_NODE_SQL,Qn as abandonCreateRequest,bn as assertRunNotDeleting,Et as browseNodes,Vn as canonicalSessionFile,gt as childrenOf,Bn as claimCreateLease,Dt as claimWarmSpare,st as clearFinalReportIfMatches,_t as clearFrozen,Yn as completeCreateRequest,Jn as createLeaseLive,In as createNode,Ut as deleteNode,Wt as deleteNodes,Zn as dueNodeDeadlines,Cn as findCreateRequest,Kn as findNodeBySessionFile,rt as getFinalReport,O as getNode,Fn as getNodes,Gn as getRow,Xn as getRowByPane,yt as graphNodes,ae as isCollectible,Tt as isWarmSpare,ue as lastActivityMs,Ze as listNodes,ft as listNodesByProfile,Nt as listNodesForSupervision,St as listParkedResidentsWithWakeMail,kt as listResumableRoots,mt as listTerminalPlacementResidue,Lt as listWarmSpares,b as nodeFiles,nn as nodesForSupervisionSql,Mn as pruneExpiredCreateRequests,jt as pruneNodes,bt as pruneToLimit,Pn as recordCreateRequestNode,ut as recordLaunch,pt as recordRespawnAttempt,ct as recordSettledTurn,ht as registerWarmSpare,I as removeNodeFiles,zn as renewCreateLease,Hn as reserveCreateRequest,$n as reserveCreateRequestNode,Rt as resumableNodeCwds,vt as rosterNodes,lt as setFrozen,it as setIntent,et as setNodeDeadline,dt as setPresence,at as setStatus,nt as shiftProfileNodeDeadlines,en as terminalPlacementResidueSql,ot as transitionStatusIntent,Ot as unregisterWarmSpare,tt as updateNode,wt as updateNodeTelemetry,At as warmSpareCount,xt as withFreshTerminalGuard};
@@ -0,0 +1,5 @@
1
+ -- 022-create-request-lease.sql — a keyed create records which API process is building its node (`lease_owner`) and until when
2
+ -- (`lease_expires_at`, renewed while it works), so a retry waits for a live owner and resumes the create only once the lease has lapsed.
3
+ -- Additive only: `schema_min_reader` is not touched, so the previous release (version 20) still opens the result; it ignores both columns.
4
+ ALTER TABLE create_requests ADD COLUMN IF NOT EXISTS lease_owner text;
5
+ ALTER TABLE create_requests ADD COLUMN IF NOT EXISTS lease_expires_at bigint;
@@ -0,0 +1,7 @@
1
+ -- 023-machine-calls-job-stop.sql — `machine_calls.op` accepts `job.stop`: the control plane asks a Mac to stop a background job's process tree when `node bash kill`
2
+ -- or a deadline ends the job. One transaction; the CHECK only widens, as 020 did: `schema_min_reader` is not touched, so the previous release (version 22) still
3
+ -- opens the result. It never writes a `job.stop` row, and a holder on that release forwards one it claims like any other op.
4
+ ALTER TABLE machine_calls DROP CONSTRAINT IF EXISTS machine_calls_op_check;
5
+ ALTER TABLE machine_calls ADD CONSTRAINT machine_calls_op_check
6
+ CHECK (op IN ('start', 'wake', 'stop', 'status', 'status.all', 'delete', 'viewer', 'cron.run', 'cron.cancel', 'job.stop',
7
+ 'worktree.create', 'worktree.rollback', 'worktree.close', 'worktree.abandon', 'worktree.finalize', 'repo.identify'));
@@ -1,7 +1,7 @@
1
1
  /** The canvas schema version this build supports: the number of the highest delta in `schema-pg/` (the baseline
2
2
  * `schema-pg.sql` is version 1). `scripts/install-runtime.mjs` reads this module from a candidate generation to refuse
3
3
  * one below the live database's `schema_min_reader`. */
4
- export declare const CANVAS_SCHEMA_VERSION = 21;
4
+ export declare const CANVAS_SCHEMA_VERSION = 23;
5
5
  /** The Postgres schema holding the canvas tables: `CRTR_DATABASE_SCHEMA` (`crtr` in the cloud deploy). Unset or empty
6
6
  * means the role's own search_path (`public` on a Mac and on a VM). A name that is not a plain identifier is an error:
7
7
  * it is put in a `search_path` connection option. */
@@ -1 +1 @@
1
- var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=21;function _(n=process.env){const e=n.CRTR_DATABASE_SCHEMA?.trim();if(e){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw new Error(`CRTR_DATABASE_SCHEMA must be a plain identifier (letters, digits, underscore); got ${JSON.stringify(e)}`);return e}}r(_,"canvasDatabaseSchema");function h(n=process.env){return n.CRTR_SCHEMA_DATABASE_URL?.trim()||void 0}r(h,"canvasSchemaDatabaseUrl");function E(n=process.env){const e=_(n);return e===void 0?void 0:`-c search_path=${e}`}r(E,"canvasSearchPathOptions");async function v(n,e){const t=e===void 0?"canvas_meta":`"${e.replace(/"/g,'""')}".canvas_meta`;if((await n.query(`SELECT to_regclass('${t.replace(/'/g,"''")}') IS NOT NULL AS found`)).rows[0].found!==!0)return;const u=(await n.query(`SELECT key, value FROM ${t} WHERE key IN ('schema_version', 'schema_min_reader')`)).rows,o=r(c=>{const i=u.find(f=>f.key===c);if(i===void 0)return;const d=Number(i.value);if(!Number.isSafeInteger(d))throw new Error(`canvas_meta.${c} is not an integer: ${String(i.value)}`);return d},"value"),s=o("schema_version");return s===void 0?void 0:{version:s,minReader:o("schema_min_reader")??s}}r(v,"readStoredVersions");async function l(n,e,t){const a=await v(n,t);if(a!==void 0&&a.minReader>e)throw new Error(`refusing to select runtime with canvas schema ${e}: the live database requires readers at version ${a.minReader} or above (it is at ${a.version}); install a descendant build instead`)}r(l,"assertCandidateMayOpen");export{A as CANVAS_SCHEMA_VERSION,l as assertCandidateMayOpen,_ as canvasDatabaseSchema,h as canvasSchemaDatabaseUrl,E as canvasSearchPathOptions,v as readStoredVersions};
1
+ var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=23;function _(n=process.env){const e=n.CRTR_DATABASE_SCHEMA?.trim();if(e){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw new Error(`CRTR_DATABASE_SCHEMA must be a plain identifier (letters, digits, underscore); got ${JSON.stringify(e)}`);return e}}r(_,"canvasDatabaseSchema");function h(n=process.env){return n.CRTR_SCHEMA_DATABASE_URL?.trim()||void 0}r(h,"canvasSchemaDatabaseUrl");function E(n=process.env){const e=_(n);return e===void 0?void 0:`-c search_path=${e}`}r(E,"canvasSearchPathOptions");async function v(n,e){const t=e===void 0?"canvas_meta":`"${e.replace(/"/g,'""')}".canvas_meta`;if((await n.query(`SELECT to_regclass('${t.replace(/'/g,"''")}') IS NOT NULL AS found`)).rows[0].found!==!0)return;const u=(await n.query(`SELECT key, value FROM ${t} WHERE key IN ('schema_version', 'schema_min_reader')`)).rows,o=r(c=>{const i=u.find(f=>f.key===c);if(i===void 0)return;const d=Number(i.value);if(!Number.isSafeInteger(d))throw new Error(`canvas_meta.${c} is not an integer: ${String(i.value)}`);return d},"value"),s=o("schema_version");return s===void 0?void 0:{version:s,minReader:o("schema_min_reader")??s}}r(v,"readStoredVersions");async function l(n,e,t){const a=await v(n,t);if(a!==void 0&&a.minReader>e)throw new Error(`refusing to select runtime with canvas schema ${e}: the live database requires readers at version ${a.minReader} or above (it is at ${a.version}); install a descendant build instead`)}r(l,"assertCandidateMayOpen");export{A as CANVAS_SCHEMA_VERSION,l as assertCandidateMayOpen,_ as canvasDatabaseSchema,h as canvasSchemaDatabaseUrl,E as canvasSearchPathOptions,v as readStoredVersions};
@@ -1 +1 @@
1
- var x=Object.defineProperty;var r=(e,n)=>x(e,"name",{value:n,configurable:!0});import{createPrivateKey as $,randomUUID as O,sign as A}from"node:crypto";import{readFileSync as P}from"node:fs";import{join as T}from"node:path";import{crtrHome as N}from"../canvas/paths.js";import{withCanvasWrite as R}from"../canvas/db.js";import{isUnsandboxedMachine as v}from"../runtime/unsandboxed.js";import{emitEvent as f}from"../events/emit.js";import{describeOutboundFailure as G,outboundFetch as k,outboundJson as b,outboundRefusal as E}from"../events/outbound.js";import{dependenciesOf as J,inferenceEndpointOf as U,replaceGrants as B,teamsOf as C}from"./mirror.js";import{onGrantSync as D}from"./on-sync.js";import{hostedEndpointOf as F,paymentSetupUrlOf as I,storeHostedEndpoint as M}from"./hosted-endpoint.js";import{adoptInstallPerson as W}from"../scoped-state/migrate.js";import{PersonOutsideRequestError as q,PersonUnresolvedError as L,personId as H,resolvePerson as z,retireLocalPerson as K,setPersonId as V}from"../canvas/person.js";const he=300;function Y(e,n){const t=Math.floor(Date.now()/1e3),i=Buffer.from(JSON.stringify({alg:"ES256",typ:"JWT",kid:e.kid})).toString("base64url"),c=Buffer.from(JSON.stringify({iss:e.client_id,sub:e.client_id,aud:n,iat:t,exp:t+300,jti:O()})).toString("base64url"),u=`${i}.${c}`,o=A("sha256",Buffer.from(u),{key:$({key:e.jwk,format:"jwk"}),dsaEncoding:"ieee-p1363"});return`${u}.${o.toString("base64url")}`}r(Y,"assertion");function y(){const e=JSON.parse(P(T(N(),"secrets","runtime-client.json"),"utf8"));if(!e.jwk||e.alg!=="ES256"||!e.kid||!e.client_id||!e.runtime||e.jwk.kid!==e.kid||e.jwk.kty!=="EC"||e.jwk.crv!=="P-256"||!e.jwk.d)throw new TypeError("invalid runtime client key");return e}r(y,"runtimeClient");function we(e=y()){return e.runtime.startsWith("runtime:")?e.runtime.slice(8):e.runtime}r(we,"runtimeId");function Q(e){return`This machine was removed from your Northlight account. To use it again, create a join token at ${e.replace(/\/$/,"")}/account/machines, and run \`crtr sys join\` from a plain terminal.`}r(Q,"machineRevokedMessage");class S extends Error{static{r(this,"MachineRevokedError")}constructor(n){super(Q(n)),this.name="MachineRevokedError"}}async function X(e,n,t){const i=y(),c=`${e.replace(/\/$/,"")}/token`,u=new URLSearchParams({grant_type:"client_credentials",client_id:i.client_id,client_assertion_type:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer",client_assertion:Y(i,c),...n===void 0?{}:{audience:n},...t===void 0?{}:{sub:t}}),o=await k("directory_token",c,{method:"POST",body:u,signal:AbortSignal.timeout(1e4)});if(!o.ok)throw o.status===401&&v()&&await Z(o)?new S(e):E("directory_token",c,`directory token request failed: ${o.status}`);const a=await b("directory_token",c,o);if(typeof a.access_token!="string")throw new TypeError("directory token response has no access_token");return{access_token:a.access_token,expires_at:ee(a.access_token,a.expires_in)}}r(X,"mintDirectoryToken");async function Z(e){try{return(await e.json()).error==="invalid_client"}catch{return!1}}r(Z,"isInvalidClient");function ee(e,n){if(typeof n=="number"&&Number.isFinite(n)&&n>0)return Date.now()+n*1e3;try{const t=JSON.parse(Buffer.from(e.split(".")[1]??"","base64url").toString("utf8"));if(typeof t.exp=="number")return t.exp*1e3}catch{}return Date.now()+3e5}r(ee,"tokenExpiry");function te(e,n){if(!e||typeof e!="object")throw new TypeError("invalid grant sync response");const t=e,i=n.runtime.startsWith("runtime:")?n.runtime:`runtime:${n.runtime}`;if(!(t.runtime===i||v()&&typeof t.runtime=="string"&&t.runtime.startsWith("runtime:")&&t.grantee!=="app:terminal")||typeof t.id!="string"||typeof t.sub!="string"||typeof t.grantee!="string"||!Number.isInteger(t.rev)||!Array.isArray(t.scopes)||!Array.isArray(t.resolved_scopes)||!["active","revoked","removed"].includes(t.status??"")||typeof t.synced_at!="string")throw new TypeError("invalid grant sync response");const o=e.revisions?.find(d=>d.rev===t.rev)?.approved_at;if(typeof o!="string")throw new TypeError("grant revision has no approval time");const a=t.payer==="app"?"app":"user";return{...t,spend_cap:t.spend_cap??null,expires_at:t.expires_at??null,revoked_at:t.revoked_at??null,approved_at:o,payer:a,dependencies:J(t.dependencies),inference_endpoint:a==="app"?U(t.inference_endpoint):null,run_notice_url:typeof t.run_notice_url=="string"&&t.run_notice_url!==""?t.run_notice_url:null}}r(te,"responseGrant");async function ne(){try{return{id:H(),late:null}}catch(n){if(n instanceof q)return null;if(!(n instanceof L))throw n}const e=await z();return e===null?null:{id:e.id,late:e}}r(ne,"pullPerson");async function re(e){V(e.id),await W(e.id);const n=await K();f({level:"info",event:"daemon.person.resolved",fields:{person_id:e.id,source:e.source}}),f({level:"info",event:"daemon.person.retired",fields:{person_id:n.person,retired:n.retired,columns:n.columns}})}r(re,"bindLatePerson");let _;function ve(e){return _?_(e):Promise.resolve()}r(ve,"requestGrantSync");function ke(e,n=t=>{}){let t;const i=e.replace(/\/$/,""),c=r(async()=>{const d=y(),p=await X(i),m=await k("grant_sync",`${i}/v1/runtime/grants`,{headers:{Authorization:`Bearer ${p.access_token}`},signal:AbortSignal.timeout(1e4)});if(!m.ok)throw E("grant_sync",`${i}/v1/runtime/grants`,`directory grant sync failed: ${m.status}`);const s=await b("grant_sync",`${i}/v1/runtime/grants`,m);if(!Array.isArray(s.grants)||typeof s.synced_at!="string")throw new TypeError("invalid grant sync response");const g="hosted_endpoint"in s||"payment_setup_url"in s?{hosted_endpoint:F(s.hosted_endpoint??null),payment_setup_url:I(s.payment_setup_url??null),synced_at:s.synced_at}:void 0,j=s.synced_at,h=s.grants.map(l=>te(l,d)),w=await R(async()=>{await B(h,j,i,C(s.teams));const l=await ne();return g&&l&&await M(g,l.id),l});f({level:"info",event:"daemon.grants.synced",fields:{grants:h.length,synced_at:s.synced_at}}),w?.late&&await re(w.late);try{await D(n)}catch(l){f({level:"error",event:"daemon.grants.on_sync_failed",error:l})}},"run");let u;const o=r(()=>{const d=c().catch(p=>{throw p instanceof S?f({level:"error",event:"daemon.grants.machine_revoked",error:p}):f({level:"error",event:"daemon.grants.sync_failed",error:p,fields:G(p)}),p}).finally(()=>{t===d&&(t=void 0)});return t=d,d},"start"),a=r((d={})=>t?d.fresh?(u??=t.catch(()=>{}).then(()=>(u=void 0,t??o())),u):t:o(),"sync");return _=a,a}r(ke,"createGrantSync");export{he as GRANT_SYNC_INTERVAL_S,S as MachineRevokedError,Y as assertion,ke as createGrantSync,Q as machineRevokedMessage,X as mintDirectoryToken,ve as requestGrantSync,y as runtimeClient,we as runtimeId};
1
+ var $=Object.defineProperty;var r=(e,n)=>$(e,"name",{value:n,configurable:!0});import{createPrivateKey as O,randomUUID as P,sign as A}from"node:crypto";import{readFileSync as T}from"node:fs";import{join as N}from"node:path";import{crtrHome as R}from"../canvas/paths.js";import{withCanvasWrite as k}from"../canvas/db.js";import{reconcilePackages as G}from"../graph/package-reconcile.js";import{isUnsandboxedMachine as v}from"../runtime/unsandboxed.js";import{emitEvent as f}from"../events/emit.js";import{describeOutboundFailure as J,outboundFetch as b,outboundJson as E,outboundRefusal as S}from"../events/outbound.js";import{dependenciesOf as U,inferenceEndpointOf as B,replaceGrants as C,teamsOf as D}from"./mirror.js";import{onGrantSync as F}from"./on-sync.js";import{hostedEndpointOf as I,paymentSetupUrlOf as M,storeHostedEndpoint as W}from"./hosted-endpoint.js";import{adoptInstallPerson as q}from"../scoped-state/migrate.js";import{PersonOutsideRequestError as L,PersonUnresolvedError as H,personId as z,resolvePerson as K,retireLocalPerson as V,setPersonId as Y}from"../canvas/person.js";const ke=300;function Q(e,n){const t=Math.floor(Date.now()/1e3),i=Buffer.from(JSON.stringify({alg:"ES256",typ:"JWT",kid:e.kid})).toString("base64url"),c=Buffer.from(JSON.stringify({iss:e.client_id,sub:e.client_id,aud:n,iat:t,exp:t+300,jti:P()})).toString("base64url"),u=`${i}.${c}`,o=A("sha256",Buffer.from(u),{key:O({key:e.jwk,format:"jwk"}),dsaEncoding:"ieee-p1363"});return`${u}.${o.toString("base64url")}`}r(Q,"assertion");function y(){const e=JSON.parse(T(N(R(),"secrets","runtime-client.json"),"utf8"));if(!e.jwk||e.alg!=="ES256"||!e.kid||!e.client_id||!e.runtime||e.jwk.kid!==e.kid||e.jwk.kty!=="EC"||e.jwk.crv!=="P-256"||!e.jwk.d)throw new TypeError("invalid runtime client key");return e}r(y,"runtimeClient");function ve(e=y()){return e.runtime.startsWith("runtime:")?e.runtime.slice(8):e.runtime}r(ve,"runtimeId");function X(e){return`This machine was removed from your Northlight account. To use it again, create a join token at ${e.replace(/\/$/,"")}/account/machines, and run \`crtr sys join\` from a plain terminal.`}r(X,"machineRevokedMessage");class j extends Error{static{r(this,"MachineRevokedError")}constructor(n){super(X(n)),this.name="MachineRevokedError"}}async function Z(e,n,t){const i=y(),c=`${e.replace(/\/$/,"")}/token`,u=new URLSearchParams({grant_type:"client_credentials",client_id:i.client_id,client_assertion_type:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer",client_assertion:Q(i,c),...n===void 0?{}:{audience:n},...t===void 0?{}:{sub:t}}),o=await b("directory_token",c,{method:"POST",body:u,signal:AbortSignal.timeout(1e4)});if(!o.ok)throw o.status===401&&v()&&await ee(o)?new j(e):S("directory_token",c,`directory token request failed: ${o.status}`);const a=await E("directory_token",c,o);if(typeof a.access_token!="string")throw new TypeError("directory token response has no access_token");return{access_token:a.access_token,expires_at:te(a.access_token,a.expires_in)}}r(Z,"mintDirectoryToken");async function ee(e){try{return(await e.json()).error==="invalid_client"}catch{return!1}}r(ee,"isInvalidClient");function te(e,n){if(typeof n=="number"&&Number.isFinite(n)&&n>0)return Date.now()+n*1e3;try{const t=JSON.parse(Buffer.from(e.split(".")[1]??"","base64url").toString("utf8"));if(typeof t.exp=="number")return t.exp*1e3}catch{}return Date.now()+3e5}r(te,"tokenExpiry");function ne(e,n){if(!e||typeof e!="object")throw new TypeError("invalid grant sync response");const t=e,i=n.runtime.startsWith("runtime:")?n.runtime:`runtime:${n.runtime}`;if(!(t.runtime===i||v()&&typeof t.runtime=="string"&&t.runtime.startsWith("runtime:")&&t.grantee!=="app:terminal")||typeof t.id!="string"||typeof t.sub!="string"||typeof t.grantee!="string"||!Number.isInteger(t.rev)||!Array.isArray(t.scopes)||!Array.isArray(t.resolved_scopes)||!["active","revoked","removed"].includes(t.status??"")||typeof t.synced_at!="string")throw new TypeError("invalid grant sync response");const o=e.revisions?.find(d=>d.rev===t.rev)?.approved_at;if(typeof o!="string")throw new TypeError("grant revision has no approval time");const a=t.payer==="app"?"app":"user";return{...t,spend_cap:t.spend_cap??null,expires_at:t.expires_at??null,revoked_at:t.revoked_at??null,approved_at:o,payer:a,dependencies:U(t.dependencies),inference_endpoint:a==="app"?B(t.inference_endpoint):null,run_notice_url:typeof t.run_notice_url=="string"&&t.run_notice_url!==""?t.run_notice_url:null}}r(ne,"responseGrant");async function re(){try{return{id:z(),late:null}}catch(n){if(n instanceof L)return null;if(!(n instanceof H))throw n}const e=await K();return e===null?null:{id:e.id,late:e}}r(re,"pullPerson");async function oe(e){Y(e.id),await q(e.id);const n=await V();await k(async t=>await G(t)),f({level:"info",event:"daemon.person.resolved",fields:{person_id:e.id,source:e.source}}),f({level:"info",event:"daemon.person.retired",fields:{person_id:n.person,retired:n.retired,columns:n.columns}})}r(oe,"bindLatePerson");let _;function be(e){return _?_(e):Promise.resolve()}r(be,"requestGrantSync");function Ee(e,n=t=>{}){let t;const i=e.replace(/\/$/,""),c=r(async()=>{const d=y(),p=await Z(i),m=await b("grant_sync",`${i}/v1/runtime/grants`,{headers:{Authorization:`Bearer ${p.access_token}`},signal:AbortSignal.timeout(1e4)});if(!m.ok)throw S("grant_sync",`${i}/v1/runtime/grants`,`directory grant sync failed: ${m.status}`);const s=await E("grant_sync",`${i}/v1/runtime/grants`,m);if(!Array.isArray(s.grants)||typeof s.synced_at!="string")throw new TypeError("invalid grant sync response");const g="hosted_endpoint"in s||"payment_setup_url"in s?{hosted_endpoint:I(s.hosted_endpoint??null),payment_setup_url:M(s.payment_setup_url??null),synced_at:s.synced_at}:void 0,x=s.synced_at,h=s.grants.map(l=>ne(l,d)),w=await k(async()=>{await C(h,x,i,D(s.teams));const l=await re();return g&&l&&await W(g,l.id),l});f({level:"info",event:"daemon.grants.synced",fields:{grants:h.length,synced_at:s.synced_at}}),w?.late&&await oe(w.late);try{await F(n)}catch(l){f({level:"error",event:"daemon.grants.on_sync_failed",error:l})}},"run");let u;const o=r(()=>{const d=c().catch(p=>{throw p instanceof j?f({level:"error",event:"daemon.grants.machine_revoked",error:p}):f({level:"error",event:"daemon.grants.sync_failed",error:p,fields:J(p)}),p}).finally(()=>{t===d&&(t=void 0)});return t=d,d},"start"),a=r((d={})=>t?d.fresh?(u??=t.catch(()=>{}).then(()=>(u=void 0,t??o())),u):t:o(),"sync");return _=a,a}r(Ee,"createGrantSync");export{ke as GRANT_SYNC_INTERVAL_S,j as MachineRevokedError,Q as assertion,Ee as createGrantSync,X as machineRevokedMessage,Z as mintDirectoryToken,be as requestGrantSync,y as runtimeClient,ve as runtimeId};
@@ -11,4 +11,12 @@ export declare function seedExtensionState(nodeId: string, state: BrokerExtensio
11
11
  export declare function markSeededStateBound(nodeId: string): void;
12
12
  /** End the share; the next caller reads the daemon. */
13
13
  export declare function retireBootExtensionState(): void;
14
+ /** Hold the inbox watcher's claims until `releaseStartupClaims`. */
15
+ export declare function holdStartupClaims(): void;
16
+ /** Whether the inbox watcher must wait. */
17
+ export declare function startupClaimsHeld(): boolean;
18
+ /** Run `resume` once the hold is released. */
19
+ export declare function afterStartupClaimsReleased(resume: () => void): void;
20
+ /** End the hold and wake whoever waited on it. */
21
+ export declare function releaseStartupClaims(): void;
14
22
  export {};
@@ -1 +1 @@
1
- var f=Object.defineProperty;var n=(t,e)=>f(t,"name",{value:e,configurable:!0});import{brokerExtensionState as u}from"./daemon-ops.js";const h=Symbol.for("@crouton-kit/crtr:boot-extension-state");function s(){const t=globalThis;return t[h]??={}}n(s,"slot");function c(t,e,a){const o=s(),r=o.shared;if(r!==void 0&&r.nodeId===t&&(r.afterBind||!e))return r.state;const i=a(t),d={nodeId:t,afterBind:e,state:i};return o.shared=d,i.catch(()=>{o.shared===d&&(o.shared=void 0)}),i}n(c,"share");function S(t,e=u){return c(t,!1,e)}n(S,"bootExtensionState");function b(t,e=u){return c(t,!0,e)}n(b,"boundExtensionState");function p(t,e,a){s().shared={nodeId:t,afterBind:a,state:Promise.resolve(e)}}n(p,"seedExtensionState");function E(t){const e=s().shared;e?.nodeId===t&&(e.afterBind=!0)}n(E,"markSeededStateBound");function m(){s().shared=void 0}n(m,"retireBootExtensionState");export{S as bootExtensionState,b as boundExtensionState,E as markSeededStateBound,m as retireBootExtensionState,p as seedExtensionState};
1
+ var f=Object.defineProperty;var o=(t,e)=>f(t,"name",{value:e,configurable:!0});import{brokerExtensionState as l}from"./daemon-ops.js";const h=Symbol.for("@crouton-kit/crtr:boot-extension-state");function s(){const t=globalThis;return t[h]??={}}o(s,"slot");function d(t,e,i){const n=s(),r=n.shared;if(r!==void 0&&r.nodeId===t&&(r.afterBind||!e))return r.state;const u=i(t),c={nodeId:t,afterBind:e,state:u};return n.shared=c,u.catch(()=>{n.shared===c&&(n.shared=void 0)}),u}o(d,"share");function S(t,e=l){return d(t,!1,e)}o(S,"bootExtensionState");function b(t,e=l){return d(t,!0,e)}o(b,"boundExtensionState");function g(t,e,i){s().shared={nodeId:t,afterBind:i,state:Promise.resolve(e)}}o(g,"seedExtensionState");function E(t){const e=s().shared;e?.nodeId===t&&(e.afterBind=!0)}o(E,"markSeededStateBound");function k(){s().shared=void 0}o(k,"retireBootExtensionState");const p=Symbol.for("@crouton-kit/crtr:startup-claims-hold");function a(){const t=globalThis;return t[p]??={held:!1,waiting:[]}}o(a,"hold");function C(){a().held=!0}o(C,"holdStartupClaims");function w(){return a().held}o(w,"startupClaimsHeld");function B(t){a().waiting.push(t)}o(B,"afterStartupClaimsReleased");function y(){const t=a();t.held=!1;for(const e of t.waiting.splice(0))e()}o(y,"releaseStartupClaims");export{B as afterStartupClaimsReleased,S as bootExtensionState,b as boundExtensionState,C as holdStartupClaims,E as markSeededStateBound,y as releaseStartupClaims,k as retireBootExtensionState,g as seedExtensionState,w as startupClaimsHeld};
@@ -1,4 +1,5 @@
1
- import type { BrokerBearingsMode, BrokerCycleStartResultDTO } from '../../../api/dto/broker-ops.js';
1
+ import type { BrokerBearingsMode, BrokerCycleStartResultDTO, BrokerSessionBoundResultDTO } from '../../../api/dto/broker-ops.js';
2
+ import type { StartDataDTO } from '../../../api/dto/execution-start.js';
2
3
  import type { RecoveryStateDTO } from '../../../api/dto/recovery.js';
3
4
  import type { NodeAttachmentDTO } from '../../../api/dto/node-records.js';
4
5
  import type { BrokerSession } from './read-ops.js';
@@ -24,6 +25,12 @@ export declare function reviewBoundaryIdsOf(branch: Entry[]): string[];
24
25
  * start, `resume` for an in-place yield) and publish its response. Undefined when the cloud predates the route, the
25
26
  * request failed or was aborted, or the session has no id yet: the cycle then runs as before. */
26
27
  export declare function startCycle(nodeId: string, session: BrokerSession, reason: string, signal?: AbortSignal): Promise<BrokerCycleStartResultDTO | undefined>;
28
+ /** Publish the start data the launch carried (`broker-launch.json`'s `start`) as the cycle-start response, with no request. Unless `bind_pending`, the bind is not
29
+ * committed here: the broker sends `session-bound` once it listens (`bindCarriedStart`), and the stophook's session start finds nothing left to bind. */
30
+ export declare function publishCarriedStart(nodeId: string, start: StartDataDTO): BrokerCycleStartResultDTO;
31
+ /** The session-bound request of a launch that carried its start data, sent once the broker listens: the same commit `cycle-start` makes when it binds.
32
+ * Undefined when the bind is left to the stophook's session start (`bind_pending`) or nothing was carried. */
33
+ export declare function bindCarriedStart(nodeId: string, session: BrokerSession, carried: StartDataDTO | undefined): Promise<BrokerSessionBoundResultDTO | undefined>;
27
34
  /** The stophook's session start: what the cycle-start request decided about the bind, once. Absent when the request
28
35
  * was not made or this is a later session start in the same broker, which clears everything the request carried. */
29
36
  export declare function takeCycleBind(nodeId: string): {