@north-light/cli 0.3.712 → 0.3.714

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 (113) hide show
  1. package/dist/clients/attach/input/controller.d.ts +8 -0
  2. package/dist/clients/attach/input/controller.js +3 -3
  3. package/dist/clients/attach/input/local-files.d.ts +18 -0
  4. package/dist/clients/attach/input/local-files.js +11 -0
  5. package/dist/clients/attach/render/chat-view.d.ts +1 -1
  6. package/dist/clients/attach/render/chat-view.js +2 -2
  7. package/dist/clients/attach/session/editor-frame.d.ts +2 -2
  8. package/dist/clients/attach/session/editor-frame.js +1 -1
  9. package/dist/clients/attach/session/input-wiring.d.ts +2 -0
  10. package/dist/clients/attach/session/input-wiring.js +1 -1
  11. package/dist/clients/attach/viewer.js +526 -517
  12. package/dist/commands/node/bash.js +1 -1
  13. package/dist/commands/node/inspect.js +5 -5
  14. package/dist/core/bash-guard.d.ts +10 -0
  15. package/dist/core/bash-guard.js +4 -4
  16. package/dist/core/broker-client/client.d.ts +2 -2
  17. package/dist/core/broker-client/client.js +1 -1
  18. package/dist/core/canvas/canvas.js +1 -1
  19. package/dist/core/canvas/deliveries.js +10 -10
  20. package/dist/core/canvas/schema-pg/029-model-accounts-refresh-claim.sql +3 -0
  21. package/dist/core/canvas/schema-version.d.ts +1 -1
  22. package/dist/core/canvas/schema-version.js +1 -1
  23. package/dist/core/canvas/types.d.ts +1 -0
  24. package/dist/core/checkout-identities.js +1 -1
  25. package/dist/core/conversation-store/row-store.js +1 -1
  26. package/dist/core/graph/documents.d.ts +5 -5
  27. package/dist/core/graph/documents.js +9 -9
  28. package/dist/core/graph/kinds/custom.js +2 -2
  29. package/dist/core/graph/kinds/document.js +4 -4
  30. package/dist/core/graph/kinds/environment.js +2 -2
  31. package/dist/core/graph/kinds/job.js +2 -2
  32. package/dist/core/graph/kinds/kind.d.ts +9 -1
  33. package/dist/core/graph/kinds/live-read.d.ts +4 -2
  34. package/dist/core/graph/kinds/live-read.js +1 -1
  35. package/dist/core/graph/kinds/node.js +5 -5
  36. package/dist/core/graph/kinds/owner.js +2 -2
  37. package/dist/core/import/load/bind.d.ts +8 -0
  38. package/dist/core/import/load/bind.js +15 -15
  39. package/dist/core/import/load/prepare.d.ts +8 -1
  40. package/dist/core/import/load/prepare.js +9 -7
  41. package/dist/core/import/load/run.js +2 -2
  42. package/dist/core/llm/run.d.ts +1 -1
  43. package/dist/core/pool-credential-store.d.ts +5 -5
  44. package/dist/core/runtime/bearings-render.d.ts +3 -0
  45. package/dist/core/runtime/bearings-render.js +7 -7
  46. package/dist/core/runtime/bearings.js +5 -5
  47. package/dist/core/runtime/broker/frame-dispatch.d.ts +2 -0
  48. package/dist/core/runtime/broker/frame-dispatch.js +1 -1
  49. package/dist/core/runtime/broker/frame-read.d.ts +5 -1
  50. package/dist/core/runtime/broker/frame-read.js +1 -1
  51. package/dist/core/runtime/broker-protocol.d.ts +37 -2
  52. package/dist/core/runtime/broker-wedge.d.ts +1 -2
  53. package/dist/core/runtime/broker-wedge.js +2 -2
  54. package/dist/core/subscription-state.d.ts +3 -3
  55. package/dist/core/subscription-state.js +1 -1
  56. package/dist/daemon/api/handlers/broker-ops.js +1 -1
  57. package/dist/daemon/api/handlers/llm.js +3 -3
  58. package/dist/daemon/api/handlers/objects.js +3 -3
  59. package/dist/daemon/api/handlers/reviews.js +1 -1
  60. package/dist/daemon/api/map.d.ts +6 -0
  61. package/dist/daemon/api/map.js +1 -1
  62. package/dist/daemon/fleet.d.ts +1 -12
  63. package/dist/daemon/fleet.js +2 -2
  64. package/dist/daemon/machine-daemon.js +1 -1
  65. package/dist/daemon/machine-link/holder.js +1 -1
  66. package/dist/daemon/reconcilers/broker-supervision.js +3 -3
  67. package/dist/daemon/reconcilers/node-lifecycle/tick.js +1 -1
  68. package/dist/pi-extensions/canvas-inbox-watcher.js +2 -2
  69. package/docs/ci-runner.md +4 -4
  70. package/package.json +3 -3
  71. package/packages/crouter-api/dist/clients/attach/input/controller.js +43 -12
  72. package/packages/crouter-api/dist/clients/attach/input/local-files.js +113 -0
  73. package/packages/crouter-api/dist/clients/attach/render/chat-view.js +9 -8
  74. package/packages/crouter-api/dist/clients/attach/session/editor-frame.js +27 -8
  75. package/packages/crouter-api/dist/clients/attach/session/input-wiring.js +1 -0
  76. package/packages/crouter-api/dist/clients/attach/viewer.js +15 -0
  77. package/packages/crouter-api/dist/commands/node/bash.js +2 -2
  78. package/packages/crouter-api/dist/commands/node/inspect.js +4 -3
  79. package/packages/crouter-api/dist/core/bash-guard.js +1 -1
  80. package/packages/crouter-api/dist/core/broker-client/client.js +1 -1
  81. package/packages/crouter-api/dist/core/canvas/canvas.js +1 -1
  82. package/packages/crouter-api/dist/core/canvas/deliveries.js +1 -1
  83. package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
  84. package/packages/crouter-api/dist/core/checkout-identities.js +1 -1
  85. package/packages/crouter-api/dist/core/conversation-store/row-store.js +1 -1
  86. package/packages/crouter-api/dist/core/graph/documents.js +12 -24
  87. package/packages/crouter-api/dist/core/graph/kinds/custom.js +1 -3
  88. package/packages/crouter-api/dist/core/graph/kinds/document.js +8 -25
  89. package/packages/crouter-api/dist/core/graph/kinds/environment.js +1 -3
  90. package/packages/crouter-api/dist/core/graph/kinds/job.js +1 -3
  91. package/packages/crouter-api/dist/core/graph/kinds/node.js +1 -3
  92. package/packages/crouter-api/dist/core/graph/kinds/owner.js +1 -3
  93. package/packages/crouter-api/dist/core/import/load/prepare.js +21 -4
  94. package/packages/crouter-api/dist/core/llm/run.js +1 -1
  95. package/packages/crouter-api/dist/core/pool-credential-store.js +5 -5
  96. package/packages/crouter-api/dist/core/runtime/bearings-render.js +11 -0
  97. package/packages/crouter-api/dist/core/runtime/bearings.js +6 -2
  98. package/packages/crouter-api/dist/core/runtime/broker-wedge.js +1 -3
  99. package/packages/crouter-api/dist/core/subscription-state.js +70 -81
  100. package/packages/crouter-api/dist/daemon/api/handlers/broker-ops.js +5 -6
  101. package/packages/crouter-api/dist/daemon/api/map.js +1 -1
  102. package/packages/crouter-api/dist/daemon/machine-link/holder.js +1 -1
  103. package/packages/crouter-api/dist/daemon/reconcilers/broker-supervision.js +4 -4
  104. package/packages/crouter-api/dist/{clients/attach/chrome/git-info.js → shared/git-status.js} +5 -5
  105. package/packages/crouter-api/package.json +1 -1
  106. package/packages/crouter-identity/package.json +1 -1
  107. package/packages/crouter-plugin/package.json +3 -3
  108. package/runtime.lock.json +14 -14
  109. package/scripts/install-runtime.mjs +3 -2
  110. package/scripts/self-update.mjs +5 -1
  111. package/packages/crouter-api/dist/core/graph/kinds/live-read.js +0 -11
  112. /package/dist/{clients/attach/chrome/git-info.d.ts → shared/git-status.d.ts} +0 -0
  113. /package/dist/{clients/attach/chrome/git-info.js → shared/git-status.js} +0 -0
@@ -1,4 +1,4 @@
1
- var q=Object.defineProperty;var i=(e,t)=>q(e,"name",{value:t,configurable:!0});import{envNodeId as j}from"../../shared/env.js";import{defineBranch as T,defineLeaf as h}from"../../core/command.js";import{InputError as r}from"../../core/io.js";import{ExitCode as R}from"../../types.js";import{existsSync as D,mkdirSync as E,rmSync as I,writeFileSync as w}from"node:fs";import{backgroundRunningBashJobs as N,bashJobCommandLine as B,bashJobPaths as y,formatBashElapsed as k,isSafeBashJobId as g,jobStartedAtMs as M,newBashJobId as L,tailJobLog as S}from"../../core/bash-jobs.js";import{parseDurationMs as U}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 C}from"../../core/preview-result-path.js";import{contextDir as v}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,L());E(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"),{[C]:p,...$}=process.env;try{await m(n,a,o,s,$)}catch(f){throw I(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}\`.`},R.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=N(v(n.node_id,n.grantee)),s=Date.now(),d=o.map(l=>({job_id:l.jobId,elapsed_ms:s-(M(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,v(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=>D(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:S(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 ${B(n.command)}${n.purpose===null?"":`
1
+ var q=Object.defineProperty;var i=(e,t)=>q(e,"name",{value:t,configurable:!0});import{envNodeId as j}from"../../shared/env.js";import{defineBranch as T,defineLeaf as h}from"../../core/command.js";import{InputError as r}from"../../core/io.js";import{ExitCode as R}from"../../types.js";import{existsSync as D,mkdirSync as E,rmSync as I,writeFileSync as w}from"node:fs";import{backgroundRunningBashJobs as N,bashJobCommandLine as B,bashJobPaths as y,formatBashElapsed as k,isSafeBashJobId as g,jobStartedAtMs as M,newBashJobId as L,tailJobLog as S}from"../../core/bash-jobs.js";import{parseDurationMs as U}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 C}from"../../core/preview-result-path.js";import{contextDir as v}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(),{destructiveCommandRefusal: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,L());E(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"),{[C]:p,...$}=process.env;try{await m(n,a,o,s,$)}catch(f){throw I(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}\`.`},R.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=N(v(n.node_id,n.grantee)),s=Date.now(),d=o.map(l=>({job_id:l.jobId,elapsed_ms:s-(M(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,v(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=>D(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:S(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 ${B(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(`
@@ -1,12 +1,12 @@
1
1
  var P=Object.defineProperty;var h=(n,e)=>P(n,"name",{value:e,configurable:!0});import{defineBranch as I,defineLeaf as _}from"../../core/command.js";import{InputError as k}from"../../core/io.js";import{requireScope as O}from"../../core/errors.js";import{isPidAlive as A}from"../../core/canvas/pid.js";import{fullName as $}from"../../core/canvas/labels.js";import{fuzzyMatch as F}from"../../core/tui/fuzzy.js";import{nodeSnapshotLeaf as L}from"../node-snapshot.js";import{nodeTranscriptLeaf as C}from"../node-transcript.js";import{nodeContextLeaf as U}from"../node-context.js";import{ApiError as D}from"../../api/index.js";import{cliClient as x,cliCanvasSource as S,rethrowAsCliError as w}from"../api-client.js";import{RemoteCanvasSource as q}from"../../core/canvas/remote-canvas-source.js";import{kindsStateBlock as E,profilesStateBlock as z,resolveProfileViaDaemon as M}from"../profile/daemon-profiles.js";import{focusViewer as B,nodeInPane as W}from"../surface/node/placement.js";const K=_({name:"list",description:"list nodes on the canvas",whenToUse:"you want a flat roster of the nodes on the canvas, sliced by displayed name, status, kind, mode, lifecycle, profile, cwd, and graph scope (--under a node, for that node plus its subscription descendants). The filters AND together. Use `node inspect show` instead to drill into one node and its spine neighbors, `canvas dashboard` for the tree shape, and `canvas attention` to find nodes blocked on the user",help:{name:"node inspect list",summary:"list nodes on the canvas, filtered by any combination of attribute slices and a graph-scope (--under) that AND together",params:[{kind:"flag",name:"status",type:"string",required:!1,constraint:"Filter status (comma-separated for several; accepted values: active, idle, done, dead, canceled). NOTE: `active` means the engine process is live (never closed), NOT that the node is generating right now \u2014 an active node is usually dormant between turns. To tell working-vs-idle, check the pi session-file mtime or CPU, not status."},{kind:"flag",name:"kind",type:"string",required:!1,constraint:"Filter by persona kind (comma-separated for several). The <kinds> list below names every top-level installable kind; a registered sub-kind filters too by exact path even though it is not listed."},{kind:"flag",name:"mode",type:"string",required:!1,constraint:"Filter by mode (comma-separated for several; accepted values: base, orchestrator)."},{kind:"flag",name:"lifecycle",type:"string",required:!1,constraint:"Filter by lifecycle (comma-separated for several; accepted values: terminal, resident)."},{kind:"flag",name:"profile",type:"string",required:!1,constraint:"Filter by profile. On the local canvas, accepts a profile id or manifest name from the <profiles> list below, or a close-enough name that resolves to the nearest profile. Against a remote canvas, pass the exact profile id carried by its node rows."},{kind:"flag",name:"name",type:"string",required:!1,constraint:"Filter by the displayed node label (handle plus generated description) with the canvas browser\u2019s case-insensitive fuzzy subsequence match."},{kind:"flag",name:"cwd",type:"string",required:!1,constraint:"Filter to nodes pinned to this exact cwd (absolute path). Roster is canvas-wide (all cwds) by default."},{kind:"flag",name:"under",type:"string",required:!1,constraint:'Graph scope: restrict to this node and its subscription descendants (the sub-DAG reachable downward \u2014 its reports, theirs, \u2026). This is "one initiative / my subtree". ANDs with every attribute filter above, narrowing any of them to this subtree.'},{kind:"flag",name:"canvas",type:"string",required:!1,constraint:"Read from the named remote canvas target (see `crtr canvas config list`) instead of the local canvas. Overrides `crtr canvas use`."}],output:[{name:"nodes",type:"object[]",required:!0,constraint:"Rows include {node_id, name, kind, mode, lifecycle, status, cwd, profile_id, parent, created}. `name` is the displayed node label searched by --name and shown in canvas views. `profile_id` is the stable profile-directory id (null only for historical no-profile nodes)."}],outputKind:"object",effects:["Read-only: lists nodes through the daemon API."]},helpState:{leaf:h(async()=>(await Promise.all([E(),z()])).join(`
2
- `),"leaf")},run:h(async n=>{const e=h(d=>{const v=n[d];return v!==void 0&&v!==""?v.split(",").map(b=>b.trim()).filter(b=>b!==""):void 0},"csv"),o=e("status"),s=e("kind"),u=e("mode"),i=e("lifecycle"),m=n.profile,c=n.name,l=n.cwd,r=n.under,p=S({canvasName:n.canvas}),a=p instanceof q?m:m===void 0?void 0:(await M(m)).id,f=r!==void 0&&r!=="";if(f&&await p.getNode(r).catch(w)===null)throw new k({error:"not_found",message:`no node: ${r}`,next:"List nodes with `crtr node inspect list`, then pass a real id to --under."});return{nodes:(await p.listNodes({...o!==void 0?{status:o}:{},...f?{under:r}:{}}).catch(w)).filter(d=>!(s!==void 0&&!s.includes(d.kind)||u!==void 0&&!u.includes(d.mode)||i!==void 0&&!i.includes(d.lifecycle)||a!==void 0&&d.profile_id!==a||l!==void 0&&l!==""&&d.cwd!==l)).map(d=>({...d,name:$(d)})).filter(d=>c===void 0||c===""||F(c,d.name))}},"run")}),j=new WeakSet,T=new WeakSet;async function N(n,e){const o=await n.getNode(e.node_id).catch(w);return{node_id:e.node_id,name:o?$(o):"(missing)",kind:o?.kind??"?",status:o?o.intent?`${o.status}/${o.intent}`:o.status:"?",active:e.active}}h(N,"enrichNeighbor");const V=_({name:"show",description:"show a node + its spine neighbors and drill-in pointers",whenToUse:"you want one node in depth \u2014 the debugging entrypoint: a glanceable meta slice, named spine neighbors, a pending-cron count, and exact drill-in paths. Use `node inspect list` for the flat roster or `canvas dashboard` for the whole-tree shape",help:{name:"node inspect show",summary:"show a node in depth \u2014 meta slice, named neighbors, pending-cron count, and drill-in pointers",params:[{kind:"positional",name:"node",required:!0,constraint:"Node id."},{kind:"flag",name:"canvas",type:"string",required:!1,constraint:"Read from the named remote canvas target (see `crtr canvas config list`) instead of the local canvas. Overrides `crtr canvas use`."}],output:[{name:"node",type:"object",required:!0,constraint:"The full node meta (system prompt + every telemetry field). The render surfaces a glanceable slice; `--json` carries the complete dump."},{name:"fault",type:"object",required:!0,constraint:"The active runtime fault projection, or null: {link, kind, retry: {disposition}, since}."},{name:"reports",type:"object[]",required:!0,constraint:"Who this node subscribes to (its reports/down), each enriched with {node_id, name, kind, status, active} \u2014 these are typically its spawned children."},{name:"managers",type:"object[]",required:!0,constraint:"Who subscribes to this node (its managers/up), same enriched shape."},{name:"pending_crons",type:"number",required:!0,constraint:"How many pending crons were created by this node. Inspect with `crtr cron list`."},{name:"paths",type:"object",required:!0,constraint:"Resolved on-disk locations: {context_dir, session_file} \u2014 read these directly to debug. Reports are documents: `crtr canvas read <node>/reports/<name>`."},{name:"follow_up",type:"string",required:!0,constraint:"The concrete next commands to drill deeper."}],outputKind:"object",effects:["Read-only: reads the node, its edges, and pending crons through crtrd."],preview:{suppressOutput:!0}},run:h(async n=>{const e=n.node,o=n.canvas,s=S({canvasName:o});if(s instanceof q){const t=await s.rawShow(e);if(t===null)throw new k({error:"not_found",message:`no node: ${e}`,next:"List nodes with `crtr node inspect list --canvas <name>`."});const y={...t};return j.add(y),y}const u=await s.getNode(e).catch(t=>w(t,"List nodes with `crtr node inspect list`."));if(u===null)throw new k({error:"not_found",message:`no node: ${e}`,next:"List nodes with `crtr node inspect list`."});const i=u,m=x(),c=await Promise.all((await s.subscriptionsOf(e)).map(t=>N(s,t))),l=await Promise.all((await s.subscribersOf(e)).map(t=>N(s,t))),r=(await m.listCrons({created_by:e}).catch(w)).filter(t=>t.created_by===e).length,p={context_dir:i.paths.context_dir,...i.pi_session_file!==void 0?{session_file:i.pi_session_file}:{}},a=[];a.push(`List the documents it owns (reports, plans, notes): \`crtr canvas list --owner ${e}\`.`),a.push(`Browse its context dir (and its subscriptions') in nvim: \`crtr node inspect context ${e}\`.`),p.session_file&&a.push(`Read the raw conversation transcript: ${p.session_file}`),a.push(`On-disk context dir (ls/read directly): ${p.context_dir}`),r>0&&a.push(`It created ${r} pending cron(s): \`crtr cron list\`.`),c.length>0&&a.push(`Drill into a child/report: \`crtr node inspect show <node_id>\` (${c.map(t=>t.node_id).join(", ")}).`),a.push(`Full machine dump (system prompt + all telemetry): \`crtr --json node inspect show ${e}\`.`);const f={node:i,fault:i.fault??null,reports:c,managers:l,pending_crons:r,paths:p,follow_up:a.join(`
3
- `)};return i.profile_id!==null&&await m.getProfileEnvironment(i.profile_id).then(()=>!0,t=>t instanceof D&&t.status===400?!1:w(t))&&T.add(f),f},"run"),render:h(n=>{const e=n.node,o=String(e.node_id),s=e.pi_pid,i=j.has(n)?"remote (liveness not checked locally)":e.runner==="machine"?"on a Mac (liveness not checked locally)":T.has(n)?"in a cloud sandbox (liveness not checked locally)":A(s)?"alive":"dead",m=e.intent?`/${String(e.intent)}`:"",c=n.fault,l=[];l.push(`# ${$(e)} (${o})`);const r=[`- kind/mode/lifecycle: ${e.kind} / ${e.mode} / ${e.lifecycle}`,`- status: ${e.status}${m}`,...c==null?[]:[`- fault: ${String(c.kind)} / ${String(c.retry?.disposition)} since ${String(c.since)}`],`- broker pid: ${s??"(none)"} \u2014 ${i}`,`- cwd: ${e.cwd}`,`- host: ${e.host_kind}`+(e.profile_id?` \xB7 profile ${e.profile_id}`:""),`- cycles: ${e.cycles} \xB7 created ${e.created}`],p=e.machine;p&&r.push(`- machine: ${p.name??p.id}`),e.parent&&r.push(`- parent: ${e.parent}`),r.push(`- creator: ${e.creator??"an external process"}`),e.waiting_for&&r.push(`- waiting for message: ${e.waiting_for}`),l.push(r.join(`
4
- `));const a=h((f,g)=>{if(g.length===0)return`${f}: none`;const t=["node_id","name","kind","status","active"],y=`| ${t.join(" | ")} |`,d=`| ${t.map(()=>"---").join(" | ")} |`,v=g.map(b=>`| ${t.map(R=>String(b[R]??"").replace(/\|/g,"\\|").replace(/\n/g," ")).join(" | ")} |`).join(`
2
+ `),"leaf")},run:h(async n=>{const e=h(d=>{const b=n[d];return b!==void 0&&b!==""?b.split(",").map(v=>v.trim()).filter(v=>v!==""):void 0},"csv"),o=e("status"),s=e("kind"),p=e("mode"),i=e("lifecycle"),m=n.profile,c=n.name,l=n.cwd,r=n.under,u=S({canvasName:n.canvas}),a=u instanceof q?m:m===void 0?void 0:(await M(m)).id,f=r!==void 0&&r!=="";if(f&&await u.getNode(r).catch(w)===null)throw new k({error:"not_found",message:`no node: ${r}`,next:"List nodes with `crtr node inspect list`, then pass a real id to --under."});return{nodes:(await u.listNodes({...o!==void 0?{status:o}:{},...f?{under:r}:{}}).catch(w)).filter(d=>!(s!==void 0&&!s.includes(d.kind)||p!==void 0&&!p.includes(d.mode)||i!==void 0&&!i.includes(d.lifecycle)||a!==void 0&&d.profile_id!==a||l!==void 0&&l!==""&&d.cwd!==l)).map(d=>({...d,name:$(d)})).filter(d=>c===void 0||c===""||F(c,d.name))}},"run")}),j=new WeakSet,T=new WeakSet;async function N(n,e){const o=await n.getNode(e.node_id).catch(w);return{node_id:e.node_id,name:o?$(o):"(missing)",kind:o?.kind??"?",status:o?o.intent?`${o.status}/${o.intent}`:o.status:"?",active:e.active}}h(N,"enrichNeighbor");const V=_({name:"show",description:"show a node + its spine neighbors and drill-in pointers",whenToUse:"you want one node in depth \u2014 the debugging entrypoint: a glanceable meta slice, named spine neighbors, a pending-cron count, and exact drill-in paths. Use `node inspect list` for the flat roster or `canvas dashboard` for the whole-tree shape",help:{name:"node inspect show",summary:"show a node in depth \u2014 meta slice, named neighbors, pending-cron count, and drill-in pointers",params:[{kind:"positional",name:"node",required:!0,constraint:"Node id."},{kind:"flag",name:"canvas",type:"string",required:!1,constraint:"Read from the named remote canvas target (see `crtr canvas config list`) instead of the local canvas. Overrides `crtr canvas use`."}],output:[{name:"node",type:"object",required:!0,constraint:"The full node meta (system prompt + every telemetry field). The render surfaces a glanceable slice; `--json` carries the complete dump."},{name:"fault",type:"object",required:!0,constraint:"The active runtime fault projection, or null: {link, kind, retry: {disposition}, since}."},{name:"reports",type:"object[]",required:!0,constraint:"Who this node subscribes to (its reports/down), each enriched with {node_id, name, kind, status, active} \u2014 these are typically its spawned children."},{name:"managers",type:"object[]",required:!0,constraint:"Who subscribes to this node (its managers/up), same enriched shape."},{name:"pending_crons",type:"number",required:!0,constraint:"How many pending crons were created by this node. Inspect with `crtr cron list`."},{name:"paths",type:"object",required:!0,constraint:"Resolved on-disk locations: {context_dir, session_file} \u2014 read these directly to debug. Reports are documents: `crtr canvas read <node>/reports/<name>`."},{name:"follow_up",type:"string",required:!0,constraint:"The concrete next commands to drill deeper."}],outputKind:"object",effects:["Read-only: reads the node, its edges, and pending crons through crtrd."],preview:{suppressOutput:!0}},run:h(async n=>{const e=n.node,o=n.canvas,s=S({canvasName:o});if(s instanceof q){const t=await s.rawShow(e);if(t===null)throw new k({error:"not_found",message:`no node: ${e}`,next:"List nodes with `crtr node inspect list --canvas <name>`."});const y={...t};return j.add(y),y}const p=await s.getNode(e).catch(t=>w(t,"List nodes with `crtr node inspect list`."));if(p===null)throw new k({error:"not_found",message:`no node: ${e}`,next:"List nodes with `crtr node inspect list`."});const i=p,m=x(),c=await Promise.all((await s.subscriptionsOf(e)).map(t=>N(s,t))),l=await Promise.all((await s.subscribersOf(e)).map(t=>N(s,t))),r=(await m.listCrons({created_by:e}).catch(w)).filter(t=>t.created_by===e).length,u={context_dir:i.paths.context_dir,...i.pi_session_file!==void 0?{session_file:i.pi_session_file}:{}},a=[];a.push(`List the documents it owns (reports, plans, notes): \`crtr canvas list --owner ${e}\`.`),a.push(`Browse its context dir (and its subscriptions') in nvim: \`crtr node inspect context ${e}\`.`),u.session_file&&a.push(`Read the raw conversation transcript: ${u.session_file}`),a.push(`On-disk context dir (ls/read directly): ${u.context_dir}`),r>0&&a.push(`It created ${r} pending cron(s): \`crtr cron list\`.`),c.length>0&&a.push(`Drill into a child/report: \`crtr node inspect show <node_id>\` (${c.map(t=>t.node_id).join(", ")}).`),a.push(`Full machine dump (system prompt + all telemetry): \`crtr --json node inspect show ${e}\`.`);const f={node:i,fault:i.fault??null,reports:c,managers:l,pending_crons:r,paths:u,follow_up:a.join(`
3
+ `)};return(i.runner==="blaxel"||i.profile_id!==null&&await m.getProfileEnvironment(i.profile_id).then(()=>!0,t=>t instanceof D&&(t.status===400||t.status===404)?!1:w(t)))&&T.add(f),f},"run"),render:h(n=>{const e=n.node,o=String(e.node_id),s=e.pi_pid,i=j.has(n)?"remote (liveness not checked locally)":e.runner==="machine"?"on a Mac (liveness not checked locally)":T.has(n)?"in a cloud sandbox (liveness not checked locally)":A(s)?"alive":"dead",m=e.intent?`/${String(e.intent)}`:"",c=n.fault,l=[];l.push(`# ${$(e)} (${o})`);const r=[`- kind/mode/lifecycle: ${e.kind} / ${e.mode} / ${e.lifecycle}`,`- status: ${e.status}${m}`,...c==null?[]:[`- fault: ${String(c.kind)} / ${String(c.retry?.disposition)} since ${String(c.since)}`],`- broker pid: ${s??"(none)"} \u2014 ${i}`,`- cwd: ${e.cwd}`,`- host: ${e.host_kind}`+(e.profile_id?` \xB7 profile ${e.profile_id}`:""),`- cycles: ${e.cycles} \xB7 created ${e.created}`],u=e.machine;u&&r.push(`- machine: ${u.name??u.id}`),e.parent&&r.push(`- parent: ${e.parent}`),r.push(`- creator: ${e.creator??"an external process"}`),e.waiting_for&&r.push(`- waiting for message: ${e.waiting_for}`),l.push(r.join(`
4
+ `));const a=h((f,g)=>{if(g.length===0)return`${f}: none`;const t=["node_id","name","kind","status","active"],y=`| ${t.join(" | ")} |`,d=`| ${t.map(()=>"---").join(" | ")} |`,b=g.map(v=>`| ${t.map(R=>String(v[R]??"").replace(/\|/g,"\\|").replace(/\n/g," ")).join(" | ")} |`).join(`
5
5
  `);return`${g.length} ${f}:
6
6
 
7
7
  ${y}
8
8
  ${d}
9
- ${v}`},"table");return l.push(a("reports (down \u2014 subscriptions, usually children)",n.reports)),l.push(a("managers (up \u2014 subscribers)",n.managers)),l.push(`${n.pending_crons} pending cron(s)`),l.push(`Drill deeper:
9
+ ${b}`},"table");return l.push(a("reports (down \u2014 subscriptions, usually children)",n.reports)),l.push(a("managers (up \u2014 subscribers)",n.managers)),l.push(`${n.pending_crons} pending cron(s)`),l.push(`Drill deeper:
10
10
  ${String(n.follow_up)}`),l.join(`
11
11
 
12
- `)},"render")}),de=_({name:"fork",description:"fork a node into an independent idle root with the same conversation and durable context",whenToUse:"a conversation has already accumulated the context you want, and you want a new user-driven branch beside it without sending a prompt or inheriting any graph-management responsibility. This copies the conversation and durable context, then waits for the fork\u2019s first real user message to supply its mandate. Use `node new --fork-from` instead when spawning a managed worker with an immediate task",help:{name:"node fork",summary:"create an independent resident root from a node\u2019s conversation and durable context, with no kickoff prompt or model turn",params:[{kind:"flag",name:"node",type:"string",required:!1,constraint:"Source node id. Mutually exclusive with --pane; one of them is required."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the source node. Mutually exclusive with --node; one of them is required. The prefix menu passes this for you and the new viewer splits beside this pane."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The new independent root id."},{name:"focused",type:"boolean",required:!0,constraint:"True when a new viewer pane opened beside the caller; false outside tmux."},{name:"session",type:"string",required:!1,constraint:"The tmux session containing the new viewer, when one opened."}],outputKind:"object",effects:["Creates a resident base-mode root with the source node\u2019s copied pi conversation, cwd, profile, kind, model override, and durable context files. Top-level initial-prompt.md, yield-message.md, result.json, and the jobs/ folder of background bash jobs are omitted.","Copies no parent, subscriptions, subscribers, children, crons, worktree, situational context, or lifecycle responsibility. Sends no prompt and consumes no model turn; the first real user message becomes the fork\u2019s mandate.","Inside tmux, opens and focuses a surface-attach viewer as an even-horizontal split in the source pane\u2019s window. Outside tmux, the root is still created but no interactive fallback opens."]},run:h(async n=>{O("crtr:act","crtr node fork");const e=n.pane,o=n.node;if(o!==void 0&&e!==void 0)throw new k({error:"conflicting_target",message:"--node and --pane are mutually exclusive",next:"Pass the source node id or its viewer pane, not both."});let s=o;if(s===void 0&&e!==void 0&&(s=W(e)),s===void 0||s==="")throw new k({error:"no_node",message:"no source node was provided or found in the pane",next:"Pass --node <id>, or --pane <pane-id> for a pane showing a node."});const u=await x().forkNode(s).catch(w),i=await B(u.node_id,{cwd:u.cwd,name:u.name,...e!==void 0?{pane:e}:{},newPane:!0});return{node_id:u.node_id,focused:i.focused,session:i.session}},"run"),render:h(n=>{const e=n.focused===!0?` Viewer opened beside the source${n.session?` in session ${n.session}`:""}.`:" No viewer opened because no tmux pane was available.";return`Forked independent idle root ${n.node_id}.${e} It will make no model call until its first real user message.`},"render")}),ce=I({name:"inspect",description:"read one node \u2014 its graph position, conversation, and context dir",whenToUse:"reading everything about ONE node you can name: enumerate the roster (`list`), inspect a node and its spine neighbors (`show`), or browse its on-disk context dir (`context`). The documents a node owns are `crtr canvas list --owner <id>`. Use `canvas dashboard` instead to render the whole tree SHAPE, or `canvas attention` to find which nodes are blocked on the user",help:{name:"node inspect",summary:"read one node (or the roster) \u2014 topology, conversation, and context dir",model:"Inspection is read-only and never revives a node. The roster is the selection surface; one-node metadata points to progressively heavier views: a parsed broker snapshot, rendered conversation, or context browser."},children:[K,V,L,C,U]});export{de as nodeFork,ce as nodeInspect};
12
+ `)},"render")}),de=_({name:"fork",description:"fork a node into an independent idle root with the same conversation and durable context",whenToUse:"a conversation has already accumulated the context you want, and you want a new user-driven branch beside it without sending a prompt or inheriting any graph-management responsibility. This copies the conversation and durable context, then waits for the fork\u2019s first real user message to supply its mandate. Use `node new --fork-from` instead when spawning a managed worker with an immediate task",help:{name:"node fork",summary:"create an independent resident root from a node\u2019s conversation and durable context, with no kickoff prompt or model turn",params:[{kind:"flag",name:"node",type:"string",required:!1,constraint:"Source node id. Mutually exclusive with --pane; one of them is required."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the source node. Mutually exclusive with --node; one of them is required. The prefix menu passes this for you and the new viewer splits beside this pane."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The new independent root id."},{name:"focused",type:"boolean",required:!0,constraint:"True when a new viewer pane opened beside the caller; false outside tmux."},{name:"session",type:"string",required:!1,constraint:"The tmux session containing the new viewer, when one opened."}],outputKind:"object",effects:["Creates a resident base-mode root with the source node\u2019s copied pi conversation, cwd, profile, kind, model override, and durable context files. Top-level initial-prompt.md, yield-message.md, result.json, and the jobs/ folder of background bash jobs are omitted.","Copies no parent, subscriptions, subscribers, children, crons, worktree, situational context, or lifecycle responsibility. Sends no prompt and consumes no model turn; the first real user message becomes the fork\u2019s mandate.","Inside tmux, opens and focuses a surface-attach viewer as an even-horizontal split in the source pane\u2019s window. Outside tmux, the root is still created but no interactive fallback opens."]},run:h(async n=>{O("crtr:act","crtr node fork");const e=n.pane,o=n.node;if(o!==void 0&&e!==void 0)throw new k({error:"conflicting_target",message:"--node and --pane are mutually exclusive",next:"Pass the source node id or its viewer pane, not both."});let s=o;if(s===void 0&&e!==void 0&&(s=W(e)),s===void 0||s==="")throw new k({error:"no_node",message:"no source node was provided or found in the pane",next:"Pass --node <id>, or --pane <pane-id> for a pane showing a node."});const p=await x().forkNode(s).catch(w),i=await B(p.node_id,{cwd:p.cwd,name:p.name,...e!==void 0?{pane:e}:{},newPane:!0});return{node_id:p.node_id,focused:i.focused,session:i.session}},"run"),render:h(n=>{const e=n.focused===!0?` Viewer opened beside the source${n.session?` in session ${n.session}`:""}.`:" No viewer opened because no tmux pane was available.";return`Forked independent idle root ${n.node_id}.${e} It will make no model call until its first real user message.`},"render")}),ce=I({name:"inspect",description:"read one node \u2014 its graph position, conversation, and context dir",whenToUse:"reading everything about ONE node you can name: enumerate the roster (`list`), inspect a node and its spine neighbors (`show`), or browse its on-disk context dir (`context`). The documents a node owns are `crtr canvas list --owner <id>`. Use `canvas dashboard` instead to render the whole tree SHAPE, or `canvas attention` to find which nodes are blocked on the user",help:{name:"node inspect",summary:"read one node (or the roster) \u2014 topology, conversation, and context dir",model:"Inspection is read-only and never revives a node. The roster is the selection surface; one-node metadata points to progressively heavier views: a parsed broker snapshot, rendered conversation, or context browser."},children:[K,V,L,C,U]});export{de as nodeFork,ce as nodeInspect};
@@ -1,6 +1,16 @@
1
1
  /** Seconds a leading `sleep ...` will block for, or null when the command does
2
2
  * not open with a sleep (or its duration isn't statically knowable). */
3
3
  export declare function leadingSleepSeconds(command: string): number | null;
4
+ /** Walk the line segment by segment, carrying the variable values and working
5
+ * directory the shell itself would carry, and refuse the first destructive
6
+ * segment aimed at a protected path.
7
+ *
8
+ * Carrying that state IS the guard's core distinction. `export HOME=/tmp/x`
9
+ * as its own command changes `$HOME` for everything after it, so a later
10
+ * `rm -rf "$HOME"` is a scratch directory and runs. A `HOME=/tmp/x cmd`
11
+ * PREFIX applies to that one command only, so a later `rm -rf "$HOME"` is the
12
+ * real home — which is precisely the mistake that destroyed one. */
13
+ export declare function destructiveCommandRefusal(command: string, cwd: string, home?: string): string | null;
4
14
  /** The refusal this command earns before it runs, or null when it may run.
5
15
  * `cwd` is the directory the command will execute in. */
6
16
  export declare function bashCommandRefusal(command: string, cwd: string, home?: string): string | null;
@@ -1,18 +1,18 @@
1
- var M=Object.defineProperty;var a=(t,n)=>M(t,"name",{value:n,configurable:!0});import{homedir as z,userInfo as N}from"node:os";import{isAbsolute as T,resolve as A,sep as $}from"node:path";import{commandSegments as q,stripHeredocs as H}from"./shell-segments.js";const v=10,P={s:1,m:60,h:3600,d:86400};function V(t){const n=/^\s*sleep(\s+[^;&|\n]+)/.exec(t);if(!n)return null;let e=0;for(const r of n[1].trim().split(/\s+/)){const s=/^([0-9]*\.?[0-9]+)([smhd]?)$/.exec(r);if(!s)return null;e+=Number(s[1])*P[s[2]||"s"]}return e}a(V,"leadingSleepSeconds");function Z(t){const n=V(t);return n===null||n<=v?null:`Refused: this command starts by sleeping ${n}s, over the ${v}s inline limit.
1
+ var z=Object.defineProperty;var a=(t,n)=>z(t,"name",{value:n,configurable:!0});import{homedir as A,userInfo as N}from"node:os";import{isAbsolute as T,resolve as $,sep as R}from"node:path";import{commandSegments as q,stripHeredocs as H}from"./shell-segments.js";const v=10,P={s:1,m:60,h:3600,d:86400};function V(t){const n=/^\s*sleep(\s+[^;&|\n]+)/.exec(t);if(!n)return null;let e=0;for(const r of n[1].trim().split(/\s+/)){const s=/^([0-9]*\.?[0-9]+)([smhd]?)$/.exec(r);if(!s)return null;e+=Number(s[1])*P[s[2]||"s"]}return e}a(V,"leadingSleepSeconds");function Z(t){const n=V(t);return n===null||n<=v?null:`Refused: this command starts by sleeping ${n}s, over the ${v}s inline limit.
2
2
  Holding a live window on a clock is never how you wait here. Instead:
3
3
  - schedule the wake and end your turn: crtr cron -h (one-shot at a time, or recurring)
4
4
  - race an inbox message against a deadline: crtr node wait deadline -h
5
5
  - waiting on a command: crtr node bash run '<command>' starts it as a job and wakes you with its exit code
6
6
  - waiting on a child, a reply from the user, or any spine event: just stop \u2014 the runtime wakes you.
7
- If you truly need a short pause inline, sleep ${v}s or less.`}a(Z,"longSleepRefusal");const B=["/","/Applications","/bin","/dev","/etc","/home","/Library","/opt","/private","/private/etc","/private/tmp","/private/var","/sbin","/System","/tmp","/usr","/Users","/var","/Volumes"];function R(t,n){return t==="/"||t==="/Users"||t==="/home"||t==="/System/Volumes/Data"?"a filesystem root":t===n?"your home directory":t===`${n}/.crouter`?"the canvas home (a multi-gigabyte canvas.db, every node directory and worktree)":null}a(R,"broadSearchReason");function U(t,n,e){return B.includes(t)?"a system directory":t===n?"your home directory":t===`${n}/.crouter`?"the canvas home \u2014 every node\u2019s conversation and state":e===t||!e.startsWith(t.endsWith($)?t:t+$)?null:`a directory containing your working directory (${e})`}a(U,"protectedReason");function G(t,n){const e=N().username;return new Map([["HOME",t],["PWD",n],["USER",e],["LOGNAME",e]])}a(G,"initialVariables");function _(t,n){let e=t;if(e==="~"||e.startsWith("~/")){const r=n.get("HOME");if(r===void 0)return null;e=r+e.slice(1)}else if(e.startsWith("~"))return null;return e=e.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)/g,(r,s,o)=>n.get(s??o)??r),/[$`*?[]/.test(e)?null:e}a(_,"expandText");function y(t,n,e){const r=_(t.replace(/\/+\*?\.?$/,"")||"/",n);return r===null?null:T(r)?A(r):e===null?null:A(e,r)}a(y,"resolveTarget");function p(t,n){for(const e of n){const r=e.indexOf("=");if(r<=0)continue;const s=e.slice(0,r);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(s))continue;const o=_(e.slice(r+1),t);o===null?t.delete(s):t.set(s,o)}}a(p,"applyAssignments");const C=/^[0-9]*(&?>>?|<<?|>&|<&)/;function g(t){const n=[];let e=!1,r=!1;for(const s of t.slice(1)){if(r){r=!1;continue}const o=C.exec(s.text);if(o!==null&&!s.opaque){r=s.text===o[0];continue}if(!e&&s.text==="--"){e=!0;continue}!e&&s.text.startsWith("-")&&s.text!=="-"||n.push(s.text)}return n}a(g,"operands");function j(t){const n=new Set,e=new Set;for(const r of t.slice(1)){if(r.text==="--")break;if(r.text.startsWith("--"))e.add(r.text.slice(2));else if(r.text.startsWith("-")&&r.text.length>1)for(const s of r.text.slice(1))n.add(s)}return{letters:n,long:e}}a(j,"flagLetters");function b(t){const{letters:n,long:e}=j(t);return n.has("r")||n.has("R")||e.has("recursive")}a(b,"isRecursive");const F=/^\/dev\/r?(disk|sd[a-z]|nvme|hd[a-z]|vd[a-z]|mmcblk|md)/;function I(t){const n=[];let e=1;for(;e<t.length;){const r=t[e].text;if(r==="--"||/^-[HLPEdsx]$/.test(r))e+=1;else if(r==="-D"||r==="-O")e+=2;else if(r==="-f")e+1<t.length&&n.push(t[e+1].text),e+=2;else break}for(;e<t.length&&!t[e].text.startsWith("-");e+=1)n.push(t[e].text);return n}a(I,"findPaths");const X=new Set(["sudo","doas","command","env","nice","nohup","time","stdbuf","xargs","exec","builtin"]);function Y(t){let n=t;for(;n.length>0&&!n[0].opaque&&X.has(n[0].text);){let e=1;for(;e<n.length&&n[e].text.startsWith("-");){const r=/^-[nu]$/.test(n[e].text);e+=r?2:1}for(;e<n.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(n[e].text);)e+=1;if(e>=n.length)return[];n=n.slice(e)}return n}a(Y,"stripCommandPrefixes");function K(t){const n={targets:[],named:null},e=t[0];if(e===void 0||e.opaque)return n;const r=e.text.slice(e.text.lastIndexOf("/")+1),s=g(t);switch(r){case"rm":return b(t)?{targets:s,named:null}:n;case"mv":return s.length>=2?{targets:s.slice(0,-1),named:null}:n;case"chmod":case"chown":case"chgrp":return b(t)&&s.length>=2?{targets:s.slice(1),named:null}:n;case"find":return t.some(i=>!i.opaque&&(i.text==="-delete"||i.text==="-exec"||i.text==="-execdir"))?{targets:I(t),named:null}:n;case"dd":{const o=t.find(l=>l.text.startsWith("of="));if(o===void 0)return n;const i=o.text.slice(3);return F.test(i)?{targets:[],named:i}:i.startsWith("/dev/")?n:{targets:[i],named:null}}default:if(/^(mkfs|newfs)([.-].+)?$/.test(r))return{targets:[],named:r};if(r==="diskutil"){const o=s[0];if(o!==void 0&&/^(erase|reformat|partition|zeroDisk|randomDisk|secureErase)/i.test(o))return{targets:[],named:`diskutil ${o}`}}return n}}a(K,"destructiveTargets");const m={grep:new Set(["-e","-f","-A","-B","-C","-m","-d","-D","--regexp","--file","--max-count","--context","--after-context","--before-context","--include","--exclude","--exclude-dir","--directories","--devices","--label"]),rg:new Set(["-e","-f","-A","-B","-C","-m","-g","-t","-T","-j","-M","-E","-r","--regexp","--file","--max-count","--context","--after-context","--before-context","--glob","--iglob","--type","--type-not","--threads","--max-columns","--encoding","--replace","--max-depth","--max-filesize","--sort","--sortr","--type-add","--pre","--pre-glob","--ignore-file","--color","--colors","--engine"]),ag:new Set(["-A","-B","-C","-m","-G","-g","--depth","--ignore","--file-search-regex","--max-count","--context","--after","--before"])};function O(t,n){const e=[];let r=!1,s=!1;for(let o=1;o<t.length;o+=1){const i=t[o].text,l=C.exec(i);if(l!==null&&!t[o].opaque){i===l[0]&&(o+=1);continue}if(!s&&i==="--"){s=!0;continue}if(!s&&i.startsWith("-")&&i!=="-"){const c=i.includes("=")?i.slice(0,i.indexOf("=")):i;(c==="-e"||c==="-f"||c==="--regexp"||c==="--file"||/^-[^-]*[ef]/.test(i))&&(r=!0),!i.includes("=")&&n.has(i)&&(o+=1);continue}e.push(i)}return{words:e,patternGiven:r}}a(O,"searchOperands");function J(t){const n={roots:[],implicitCwd:!1},e=t[0];if(e===void 0||e.opaque)return n;const r=e.text.slice(e.text.lastIndexOf("/")+1),s=a(o=>{const{words:i,patternGiven:l}=O(t,o),c=l?i:i.slice(1);return{roots:c,implicitCwd:c.length===0}},"patternThenPaths");switch(r){case"grep":case"egrep":case"fgrep":return b(t)?s(m.grep):n;case"rgrep":return s(m.grep);case"rg":if(t.some(o=>o.text==="--files")){const{words:o}=O(t,m.rg);return{roots:o,implicitCwd:o.length===0}}return s(m.rg);case"ag":case"ack":return s(m.ag);case"find":{if(t.some(i=>i.text==="-maxdepth"))return n;const o=I(t);return{roots:o,implicitCwd:o.length===0}}case"du":{const o=g(t);return{roots:o,implicitCwd:o.length===0}}default:return n}}a(J,"searchRoots");function L(t,n,e){return`Refused: \`${t}\` searches ${n} recursively, which is ${e}.
7
+ If you truly need a short pause inline, sleep ${v}s or less.`}a(Z,"longSleepRefusal");const B=["/","/Applications","/bin","/dev","/etc","/home","/Library","/opt","/private","/private/etc","/private/tmp","/private/var","/sbin","/System","/tmp","/usr","/Users","/var","/Volumes"];function _(t,n){return t==="/"||t==="/Users"||t==="/home"||t==="/System/Volumes/Data"?"a filesystem root":t===n?"your home directory":t===`${n}/.crouter`?"the canvas home (a multi-gigabyte canvas.db, every node directory and worktree)":null}a(_,"broadSearchReason");function U(t,n,e){return B.includes(t)?"a system directory":t===n?"your home directory":t===`${n}/.crouter`?"the canvas home \u2014 every node\u2019s conversation and state":e===t||!e.startsWith(t.endsWith(R)?t:t+R)?null:`a directory containing your working directory (${e})`}a(U,"protectedReason");function G(t,n){const e=N().username;return new Map([["HOME",t],["PWD",n],["USER",e],["LOGNAME",e]])}a(G,"initialVariables");function C(t,n){let e=t;if(e==="~"||e.startsWith("~/")){const r=n.get("HOME");if(r===void 0)return null;e=r+e.slice(1)}else if(e.startsWith("~"))return null;return e=e.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)/g,(r,s,o)=>n.get(s??o)??r),/[$`*?[]/.test(e)?null:e}a(C,"expandText");function y(t,n,e){const r=C(t.replace(/\/+\*?\.?$/,"")||"/",n);return r===null?null:T(r)?$(r):e===null?null:$(e,r)}a(y,"resolveTarget");function p(t,n){for(const e of n){const r=e.indexOf("=");if(r<=0)continue;const s=e.slice(0,r);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(s))continue;const o=C(e.slice(r+1),t);o===null?t.delete(s):t.set(s,o)}}a(p,"applyAssignments");const I=/^[0-9]*(&?>>?|<<?|>&|<&)/;function g(t){const n=[];let e=!1,r=!1;for(const s of t.slice(1)){if(r){r=!1;continue}const o=I.exec(s.text);if(o!==null&&!s.opaque){r=s.text===o[0];continue}if(!e&&s.text==="--"){e=!0;continue}!e&&s.text.startsWith("-")&&s.text!=="-"||n.push(s.text)}return n}a(g,"operands");function j(t){const n=new Set,e=new Set;for(const r of t.slice(1)){if(r.text==="--")break;if(r.text.startsWith("--"))e.add(r.text.slice(2));else if(r.text.startsWith("-")&&r.text.length>1)for(const s of r.text.slice(1))n.add(s)}return{letters:n,long:e}}a(j,"flagLetters");function b(t){const{letters:n,long:e}=j(t);return n.has("r")||n.has("R")||e.has("recursive")}a(b,"isRecursive");const F=/^\/dev\/r?(disk|sd[a-z]|nvme|hd[a-z]|vd[a-z]|mmcblk|md)/;function O(t){const n=[];let e=1;for(;e<t.length;){const r=t[e].text;if(r==="--"||/^-[HLPEdsx]$/.test(r))e+=1;else if(r==="-D"||r==="-O")e+=2;else if(r==="-f")e+1<t.length&&n.push(t[e+1].text),e+=2;else break}for(;e<t.length&&!t[e].text.startsWith("-");e+=1)n.push(t[e].text);return n}a(O,"findPaths");const X=new Set(["sudo","doas","command","env","nice","nohup","time","stdbuf","xargs","exec","builtin"]);function Y(t){let n=t;for(;n.length>0&&!n[0].opaque&&X.has(n[0].text);){let e=1;for(;e<n.length&&n[e].text.startsWith("-");){const r=/^-[nu]$/.test(n[e].text);e+=r?2:1}for(;e<n.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(n[e].text);)e+=1;if(e>=n.length)return[];n=n.slice(e)}return n}a(Y,"stripCommandPrefixes");function K(t){const n={targets:[],named:null},e=t[0];if(e===void 0||e.opaque)return n;const r=e.text.slice(e.text.lastIndexOf("/")+1),s=g(t);switch(r){case"rm":return b(t)?{targets:s,named:null}:n;case"mv":return s.length>=2?{targets:s.slice(0,-1),named:null}:n;case"chmod":case"chown":case"chgrp":return b(t)&&s.length>=2?{targets:s.slice(1),named:null}:n;case"find":return t.some(i=>!i.opaque&&(i.text==="-delete"||i.text==="-exec"||i.text==="-execdir"))?{targets:O(t),named:null}:n;case"dd":{const o=t.find(l=>l.text.startsWith("of="));if(o===void 0)return n;const i=o.text.slice(3);return F.test(i)?{targets:[],named:i}:i.startsWith("/dev/")?n:{targets:[i],named:null}}default:if(/^(mkfs|newfs)([.-].+)?$/.test(r))return{targets:[],named:r};if(r==="diskutil"){const o=s[0];if(o!==void 0&&/^(erase|reformat|partition|zeroDisk|randomDisk|secureErase)/i.test(o))return{targets:[],named:`diskutil ${o}`}}return n}}a(K,"destructiveTargets");const m={grep:new Set(["-e","-f","-A","-B","-C","-m","-d","-D","--regexp","--file","--max-count","--context","--after-context","--before-context","--include","--exclude","--exclude-dir","--directories","--devices","--label"]),rg:new Set(["-e","-f","-A","-B","-C","-m","-g","-t","-T","-j","-M","-E","-r","--regexp","--file","--max-count","--context","--after-context","--before-context","--glob","--iglob","--type","--type-not","--threads","--max-columns","--encoding","--replace","--max-depth","--max-filesize","--sort","--sortr","--type-add","--pre","--pre-glob","--ignore-file","--color","--colors","--engine"]),ag:new Set(["-A","-B","-C","-m","-G","-g","--depth","--ignore","--file-search-regex","--max-count","--context","--after","--before"])};function L(t,n){const e=[];let r=!1,s=!1;for(let o=1;o<t.length;o+=1){const i=t[o].text,l=I.exec(i);if(l!==null&&!t[o].opaque){i===l[0]&&(o+=1);continue}if(!s&&i==="--"){s=!0;continue}if(!s&&i.startsWith("-")&&i!=="-"){const c=i.includes("=")?i.slice(0,i.indexOf("=")):i;(c==="-e"||c==="-f"||c==="--regexp"||c==="--file"||/^-[^-]*[ef]/.test(i))&&(r=!0),!i.includes("=")&&n.has(i)&&(o+=1);continue}e.push(i)}return{words:e,patternGiven:r}}a(L,"searchOperands");function J(t){const n={roots:[],implicitCwd:!1},e=t[0];if(e===void 0||e.opaque)return n;const r=e.text.slice(e.text.lastIndexOf("/")+1),s=a(o=>{const{words:i,patternGiven:l}=L(t,o),c=l?i:i.slice(1);return{roots:c,implicitCwd:c.length===0}},"patternThenPaths");switch(r){case"grep":case"egrep":case"fgrep":return b(t)?s(m.grep):n;case"rgrep":return s(m.grep);case"rg":if(t.some(o=>o.text==="--files")){const{words:o}=L(t,m.rg);return{roots:o,implicitCwd:o.length===0}}return s(m.rg);case"ag":case"ack":return s(m.ag);case"find":{if(t.some(i=>i.text==="-maxdepth"))return n;const o=O(t);return{roots:o,implicitCwd:o.length===0}}case"du":{const o=g(t);return{roots:o,implicitCwd:o.length===0}}default:return n}}a(J,"searchRoots");function k(t,n,e){return`Refused: \`${t}\` searches ${n} recursively, which is ${e}.
8
8
  A sweep that wide reads hundreds of gigabytes, starves crtrd of disk, and has crashed every open viewer on this machine before.
9
9
  Search where the answer can actually be:
10
10
  - a document (knowledge, preference, spec, report): crtr canvas search "<text>" or crtr canvas read <name> \u2014 documents live in canvas.db, never as files, so grep cannot find them.
11
11
  - code: the one repo or directory you are working in, e.g. rg -l '<text>' <repo>.
12
12
  - a node's files: its own context dir, e.g. ~/.crouter/apps/<app>/nodes/<id>/context.
13
- If you believe a whole-tree search is genuinely required, ask the user \u2014 do not work around this refusal.`}a(L,"broadSearchRefusalMessage");function Q(t,n,e){const r=G(e,n);let s=[n];for(const o of q(H(t))){const i=Y(o.tokens),l=i[0];if(l!==void 0){const c=new Map(r);p(c,o.assignments);const f=s[s.length-1];f!==void 0&&c.set("PWD",f);const{targets:W,named:S}=K(i);if(S!==null)return k(o.text,S,"a whole disk or volume \u2014 never a task boundary");for(const d of W)for(const w of s.length===0?[null]:s){const u=y(d,c,w);if(u===null)continue;const h=U(u,e,n);if(h!==null)return k(o.text,u,h)}const E=J(i),D=s.length===0?[null]:s,x=s[s.length-1];if(E.implicitCwd&&x!==void 0){const d=R(x,e);if(d!==null)return L(o.text,x,d)}for(const d of E.roots)for(const w of D){const u=y(d,c,w);if(u===null)continue;const h=R(u,e);if(h!==null)return L(o.text,u,h)}}if(!o.background){if(l===void 0)p(r,o.assignments);else if(!l.opaque&&ee.has(l.text))p(r,o.assignments),p(r,g(i));else if(!l.opaque&&l.text==="cd"){const c=g(i)[0],f=c===void 0?r.get("HOME")??null:y(c,r,s[s.length-1]??null);s=f===null?[]:[...s,f]}}}return null}a(Q,"destructiveCommandRefusal");const ee=new Set(["export","declare","typeset","readonly"]);function k(t,n,e){return`Refused: \`${t}\` targets ${n}, which is ${e}.
13
+ If you believe a whole-tree search is genuinely required, ask the user \u2014 do not work around this refusal.`}a(k,"broadSearchRefusalMessage");function Q(t,n,e=A()){const r=G(e,n);let s=[n];for(const o of q(H(t))){const i=Y(o.tokens),l=i[0];if(l!==void 0){const c=new Map(r);p(c,o.assignments);const f=s[s.length-1];f!==void 0&&c.set("PWD",f);const{targets:D,named:S}=K(i);if(S!==null)return W(o.text,S,"a whole disk or volume \u2014 never a task boundary");for(const d of D)for(const w of s.length===0?[null]:s){const u=y(d,c,w);if(u===null)continue;const h=U(u,e,n);if(h!==null)return W(o.text,u,h)}const E=J(i),M=s.length===0?[null]:s,x=s[s.length-1];if(E.implicitCwd&&x!==void 0){const d=_(x,e);if(d!==null)return k(o.text,x,d)}for(const d of E.roots)for(const w of M){const u=y(d,c,w);if(u===null)continue;const h=_(u,e);if(h!==null)return k(o.text,u,h)}}if(!o.background){if(l===void 0)p(r,o.assignments);else if(!l.opaque&&ee.has(l.text))p(r,o.assignments),p(r,g(i));else if(!l.opaque&&l.text==="cd"){const c=g(i)[0],f=c===void 0?r.get("HOME")??null:y(c,r,s[s.length-1]??null);s=f===null?[]:[...s,f]}}}return null}a(Q,"destructiveCommandRefusal");const ee=new Set(["export","declare","typeset","readonly"]);function W(t,n,e){return`Refused: \`${t}\` targets ${n}, which is ${e}.
14
14
  Nothing an agent is asked to do requires destroying that path, and it cannot be undone.
15
15
  If you meant somewhere else, name that path explicitly and run the command again. Two traps to check first:
16
16
  - a \`VAR=value cmd\` prefix applies ONLY to that one command, so a later \`$VAR\` in the same line is the SHELL's value \u2014 this is exactly how a node deleted a home directory.
17
17
  - \`~\` and \`$HOME\` are the real home directory, never a scratch dir; build scratch paths with mktemp -d and hold them in a variable of your own.
18
- If you believe this path genuinely must be destroyed, ask the user \u2014 do not work around this refusal.`}a(k,"refusalMessage");function oe(t,n,e=z()){return Z(t)??Q(t,n,e)}a(oe,"bashCommandRefusal");export{oe as bashCommandRefusal,V as leadingSleepSeconds};
18
+ If you believe this path genuinely must be destroyed, ask the user \u2014 do not work around this refusal.`}a(W,"refusalMessage");function oe(t,n,e=A()){return Z(t)??Q(t,n,e)}a(oe,"bashCommandRefusal");export{oe as bashCommandRefusal,Q as destructiveCommandRefusal,V as leadingSleepSeconds};
@@ -1,6 +1,6 @@
1
1
  import { EventEmitter } from 'node:events';
2
2
  import type { NodeRow } from '../canvas/types.js';
3
- import type { BrokerDataFrame, BrokerToClient, ClientToBroker, DequeueFrame, GetHumanForkCoordinatesFrame, GetSettingsFrame, GetTreeFrame, ListMemoryRefsFrame, ListModelsFrame, ListScopedModelsFrame, ListSessionsFrame } from '../runtime/broker-protocol.js';
3
+ import type { BrokerDataFrame, BrokerToClient, ClientToBroker, DequeueFrame, GetHumanForkCoordinatesFrame, GetSettingsFrame, GetTreeFrame, ListMemoryRefsFrame, GetGitStatusFrame, UploadFileFrame, ListModelsFrame, ListScopedModelsFrame, ListSessionsFrame } from '../runtime/broker-protocol.js';
4
4
  import { type RedialOptions, type Transport } from './transport.js';
5
5
  export { BrokerUnavailableError, type Transport } from './transport.js';
6
6
  export { SocketTransport } from './transport-socket.js';
@@ -9,7 +9,7 @@ export { RelayTransport, type RelayTarget } from './transport-relay.js';
9
9
  * {@link BrokerClient.request} mints the `id`, sends the frame, and resolves
10
10
  * with the matching `data` reply. The picker/operator code builds these; the
11
11
  * client owns the correlation token so callers never hand-roll one. */
12
- export type ReadOpRequest = Omit<ListModelsFrame, 'id'> | Omit<ListSessionsFrame, 'id'> | Omit<GetTreeFrame, 'id'> | Omit<GetSettingsFrame, 'id'> | Omit<ListScopedModelsFrame, 'id'> | Omit<DequeueFrame, 'id'> | Omit<GetHumanForkCoordinatesFrame, 'id'> | Omit<ListMemoryRefsFrame, 'id'>;
12
+ export type ReadOpRequest = Omit<ListModelsFrame, 'id'> | Omit<ListSessionsFrame, 'id'> | Omit<GetTreeFrame, 'id'> | Omit<GetSettingsFrame, 'id'> | Omit<ListScopedModelsFrame, 'id'> | Omit<DequeueFrame, 'id'> | Omit<GetHumanForkCoordinatesFrame, 'id'> | Omit<ListMemoryRefsFrame, 'id'> | Omit<GetGitStatusFrame, 'id'> | Omit<UploadFileFrame, 'id'>;
13
13
  export interface BrokerClientOptions {
14
14
  /** Where the frames go. Defaults to a {@link SocketTransport} against this
15
15
  * node's local `view.sock` — the common case. Pass a {@link RelayTransport}
@@ -1 +1 @@
1
- var c=Object.defineProperty;var s=(r,e)=>c(r,"name",{value:e,configurable:!0});import{EventEmitter as l}from"node:events";import{randomUUID as p}from"node:crypto";import{SocketTransport as a}from"./transport-socket.js";import{BrokerUnavailableError as w}from"./transport.js";import{SocketTransport as k}from"./transport-socket.js";import{RelayTransport as x}from"./transport-relay.js";const d=1e4;function E(r){return r===null||r.status==="done"&&r.final_report!=null}s(E,"reconnectShouldGiveUp");class g extends l{static{s(this,"BrokerClient")}transport;closeEmitted=!1;connected=!1;lastTransportError;pending=new Map;constructor(e,t={}){super();const n=t.transport??(e===void 0?void 0:new a(e));n!==void 0&&this.bindTransport(n)}bindTransport(e){if(this.transport!==void 0)throw new Error("BrokerClient already has a transport");this.transport=e,e.on("connect",()=>{this.closeEmitted=!1,this.connected=!0,this.lastTransportError=void 0,this.emit("connect")}),e.on("frame",t=>this.onFrame(t)),e.on("error",t=>{this.lastTransportError=t.message,this.emitError(t)}),e.on("close",()=>this.onClose())}request(e){const t=p();return new Promise((n,o)=>{if(!this.connected){o(new Error(`cannot issue '${e.type}': no live broker connection`));return}const i=setTimeout(()=>{this.pending.delete(t),o(new Error(`request '${e.type}' timed out after ${d}ms`))},d);typeof i.unref=="function"&&i.unref(),this.pending.set(t,{resolve:n,reject:o,timer:i}),this.send({...e,id:t})})}rejectAllPending(e){for(const{reject:t,timer:n}of this.pending.values())clearTimeout(n),t(new Error(e));this.pending.clear()}connect(){this.transport?.connect()}redial(e){return this.transport===void 0?Promise.reject(new Error("no node to redial yet")):this.transport.redial(e)}probe(e){return this.transport?.probe?.(e)??Promise.resolve(!0)}send(e){this.transport?.send(e)}close(){this.transport?.destroy()}onFrame(e){if(e.type==="data"){const t=typeof e.id=="string"?this.pending.get(e.id):void 0;t&&(this.pending.delete(e.id),clearTimeout(t.timer),t.resolve(e));return}if(e.type==="error"&&typeof e.id=="string"&&this.pending.has(e.id)){const t=this.pending.get(e.id);this.pending.delete(e.id),clearTimeout(t.timer),t.reject(new Error(e.message||`request failed: ${e.code}`));return}this.emit("frame",e)}onClose(){this.closeEmitted||(this.closeEmitted=!0,this.connected=!1,this.rejectAllPending(this.lastTransportError??"broker connection closed"),this.emit("close"))}emitError(e){this.listenerCount("error")>0&&this.emit("error",e)}}export{g as BrokerClient,w as BrokerUnavailableError,x as RelayTransport,k as SocketTransport,E as reconnectShouldGiveUp};
1
+ var c=Object.defineProperty;var s=(r,e)=>c(r,"name",{value:e,configurable:!0});import{EventEmitter as l}from"node:events";import{randomUUID as p}from"node:crypto";import{SocketTransport as a}from"./transport-socket.js";import{BrokerUnavailableError as b}from"./transport.js";import{SocketTransport as k}from"./transport-socket.js";import{RelayTransport as x}from"./transport-relay.js";const d=1e4;function E(r){return r===null||r.status==="done"&&r.final_report!=null}s(E,"reconnectShouldGiveUp");class g extends l{static{s(this,"BrokerClient")}transport;closeEmitted=!1;connected=!1;lastTransportError;pending=new Map;constructor(e,t={}){super();const n=t.transport??(e===void 0?void 0:new a(e));n!==void 0&&this.bindTransport(n)}bindTransport(e){if(this.transport!==void 0)throw new Error("BrokerClient already has a transport");this.transport=e,e.on("connect",()=>{this.closeEmitted=!1,this.connected=!0,this.lastTransportError=void 0,this.emit("connect")}),e.on("frame",t=>this.onFrame(t)),e.on("error",t=>{this.lastTransportError=t.message,this.emitError(t)}),e.on("close",()=>this.onClose())}request(e){const t=p();return new Promise((n,o)=>{if(!this.connected){o(new Error(`cannot issue '${e.type}': no live broker connection`));return}const i=setTimeout(()=>{this.pending.delete(t),o(new Error(`request '${e.type}' timed out after ${d}ms`))},d);typeof i.unref=="function"&&i.unref(),this.pending.set(t,{resolve:n,reject:o,timer:i}),this.send({...e,id:t})})}rejectAllPending(e){for(const{reject:t,timer:n}of this.pending.values())clearTimeout(n),t(new Error(e));this.pending.clear()}connect(){this.transport?.connect()}redial(e){return this.transport===void 0?Promise.reject(new Error("no node to redial yet")):this.transport.redial(e)}probe(e){return this.transport?.probe?.(e)??Promise.resolve(!0)}send(e){this.transport?.send(e)}close(){this.transport?.destroy()}onFrame(e){if(e.type==="data"){const t=typeof e.id=="string"?this.pending.get(e.id):void 0;t&&(this.pending.delete(e.id),clearTimeout(t.timer),t.resolve(e));return}if(e.type==="error"&&typeof e.id=="string"&&this.pending.has(e.id)){const t=this.pending.get(e.id);this.pending.delete(e.id),clearTimeout(t.timer),t.reject(Object.assign(new Error(e.message||`request failed: ${e.code}`),{code:e.code}));return}this.emit("frame",e)}onClose(){this.closeEmitted||(this.closeEmitted=!0,this.connected=!1,this.rejectAllPending(this.lastTransportError??"broker connection closed"),this.emit("close"))}emitError(e){this.listenerCount("error")>0&&this.emit("error",e)}}export{g as BrokerClient,b as BrokerUnavailableError,x as RelayTransport,k as SocketTransport,E as reconnectShouldGiveUp};
@@ -1,4 +1,4 @@
1
- var ce=Object.defineProperty;var i=(e,n)=>ce(e,"name",{value:n,configurable:!0});import{loadExactProfileManifest as le}from"../profiles/manifest.js";import{envNodeId as H}from"../../shared/env.js";import{lstatSync as _e,realpathSync as M,rmdirSync as pe,rmSync as fe,statSync as Ee}from"node:fs";import{basename as we,dirname as P,isAbsolute as ye,join as S,relative as me,resolve as Ne,sep as Re}from"node:path";import{removeTreeBeneath as $}from"../spaces/open-beneath.js";import{emitEvent as Se}from"../events/emit.js";import{deleteNodeSandboxes as q}from"../runtime/runner/delete-sandboxes.js";import{withCanvasWrite as p,openDb as d}from"./db.js";import{conversationStore as he,ConversationNotFoundError as Oe}from"../conversation-store/index.js";import{hasUnseenWakeMail as Le,UNSEEN_WAKE_MAIL_SQL as Te}from"./deliveries.js";import{isAppRun as B}from"./app-run.js";import{registerOutcomeAction as z}from"./outcome-actions.js";import{publish as De}from"../graph/events.js";import{nodeObject as Ae}from"../graph/objects.js";import{findNodeBySessionFileSql as ge}from"./sessions.js";import{hydrateFault as ke}from"./recovery.js";import{hasUnreconciledWorktree as ve,openWorktree as xe,readWorktree as Ue,worktreeFromRow as We}from"./worktrees.js";import{isPidAlive as be,isPidPresent as J,recordedPidLiveness as je}from"./pid.js";import{isCloudRole as Ie}from"./person-state.js";import{ensureHome as Fe,jobDir as Ce,nodeDir as He,nodeRunDir as Y}from"./paths.js";import{appForNode as Me,ensureNodeDirs as Pe,nodeAgentDir as $e}from"./node-agent-paths.js";import{appSpace as T}from"../layout.js";import{createObject as qe,getById as D,ownerForGrantee as Be,setObjectKind as ze,setObjectName as Je}from"../graph/objects.js";import{profileObject as Ye}from"../graph/reader.js";import{writeActsFor as Q}from"../permissions/facts.js";import{CrtrError as Qe}from"../errors.js";import{deleteNodeWithOwned as Ve}from"../graph/deletion.js";import{SUBTREE_ALL_IDS_SQL as Ke,SUBTREE_IDS_SQL as Ge}from"./tree.js";import{filterAsync as y,mapAsync as h}from"../async-array.js";function E(e,n){if(e==null)return null;const t=JSON.stringify(e);if(t===void 0)throw new TypeError(`${n} must be JSON-serializable`);return t}i(E,"jsonValue");async function Fn(e,n){if((await e.prepare("SELECT deleting_at FROM nodes WHERE node_id = ?").get(n))?.deleting_at)throw new Error("run is deleting")}i(Fn,"assertRunNotDeleting");async function V(e,n,t,a){try{return(le(n).manifest.grantee??"app:terminal")!==a?null:await Ye(e,n,t)}catch(r){if(r instanceof Qe&&r.code==="not_found")return null;throw r}}i(V,"profileObjectFor");async function Xe(e,n){const t=await Be(n,e.grantee??"app:terminal"),a=e.profile_id?await V(n,e.profile_id,t,e.grantee??"app:terminal"):null;await qe(n,{id:e.node_id,type:"node",kind:e.kind,owner:(a??t).id,privacy:"public",name:e.name,preview:""}),a===null&&e.sub&&await Q(n,e.node_id,e.sub),await n.prepare(`INSERT INTO nodes (node_id, description, title, icon, cycles, mode, lifecycle, cwd, host_kind, profile_id, parent, spawned_by, creator, fork_from, fork_source_file, created, passive_default, cycle_pending, model_override, persona_ack_json, review_binding_json, launch_config_json, scopes_json, isolated, status, intent, final_report, finalized_at, deadline_at, "window", tmux_session, pane, sub, grant_id, client_id, metadata_json, run_id, event_cursor, deleting_at, caused_by, app) VALUES (${Array(41).fill("?").join(", ")})`).run(e.node_id,e.description??null,e.title??null,e.icon??null,e.cycles??null,e.mode,e.lifecycle,e.cwd,e.host_kind??null,e.profile_id??null,e.parent??null,e.spawned_by??null,e.creator??null,e.fork_from??null,e.fork_source_file??null,e.created,e.passive_default===!0?1:0,e.cycle_pending===!0?1:0,e.model_override??null,E(e.persona_ack,"persona_ack"),E(e.review_binding,"review_binding"),E(e.launch,"launch"),E(e.scopes,"scopes"),e.isolated===!0?1:0,e.status??"active",e.intent??null,e.final_report??null,e.finalized_at??null,e.deadline_at??null,e.window??null,e.tmux_session??null,e.pane??null,e.sub??null,e.grant_id??null,e.client_id??null,e.metadata_json??null,e.run_id??null,e.event_cursor??null,e.deleting_at??null,e.caused_by??null,t.id)}i(Xe,"seedRow");function K(e){if(e.fault_id==null)return null;const n=Object.entries(e).filter(([t])=>t.startsWith("fault_")).map(([t,a])=>[t==="fault_id"?t:t.slice(6),a]);return ke(Object.fromEntries(n))}i(K,"faultFrom");const G=i(e=>e.turn_open_at!=null&&e.turn_closed_at==null,"turnOpen"),X=i(e=>e||Ie(),"engineLive");function f(e){const n={node_id:e.node_id,name:e.name,description:e.description??void 0,cycles:e.cycles??void 0,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind??null,profile_id:e.profile_id??null,scopes:e.scopes_json==null?null:JSON.parse(e.scopes_json),isolated:e.isolated===1,grantee:e.grantee,sub:e.sub??null,grant_id:e.grant_id??null,client_id:e.client_id??null,metadata_json:e.metadata_json??null,run_id:e.run_id??null,event_cursor:e.event_cursor??null,last_activity_at:e.last_activity_at??null,caused_by:e.caused_by??null,last_turn_error_json:e.last_turn_error_json??null,deleting_at:e.deleting_at??null,parent:e.parent??null,created:e.created,intent:e.intent??null,frozen_at:e.frozen_at??null,respawn_failures:e.respawn_failures??0,respawn_not_before:e.respawn_not_before??null,launched_at:e.launched_at??null,last_settled_at:e.last_settled_at??null,terminal_reason:e.terminal_reason??null,final_report:e.final_report??null,finalized_at:e.finalized_at??null,outcome_kind:e.outcome_kind??null,outcome_reason:e.outcome_reason??null,outcome_at:e.outcome_at??null,outcome_revision:e.outcome_revision??0,outcome_detail_json:e.outcome_detail_json??null,deadline_at:e.deadline_at??null,telemetry_tokens_in:e.telemetry_tokens_in??null,telemetry_context_tokens:e.telemetry_context_tokens??null,telemetry_last_activity:e.telemetry_last_activity??null,telemetry_updated_at:e.telemetry_updated_at??null,pi_pid:e.pi_pid??null,pi_pid_identity:e.pi_pid_identity??null,window:e.window??null,tmux_session:e.tmux_session??null,pane:e.pane??null,fault:null,streaming:!1},t=J(n.pi_pid),a=K(e);return n.fault=a?.link==="pi\u2192provider"&&a.retry.by==="daemon"&&a.retry.disposition==="auto"&&!t?null:a,n.streaming=G(e)&&X(t),n}i(f,"rowFrom");async function A(e,n){return n??=await Ue(e.node_id),{...f(e),title:e.title??void 0,icon:e.icon??void 0,spawned_by:e.spawned_by??null,creator:e.creator??null,fork_from:e.fork_from??null,fork_source_file:e.fork_source_file??null,passive_default:e.passive_default===1,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 Cn(e,n={}){return Fe(),await p(async t=>{await Xe(e,t),e.managed_worktree!==void 0&&e.managed_worktree!==null&&await xe(e.node_id,e.managed_worktree,t),n.outcomeDelivery!==void 0&&await z(t,e.node_id,n.outcomeDelivery),await n.withinCreate?.(t,e)}),await Pe(e.node_id),await O(e.node_id)}i(Cn,"createNode");async function O(e){const n=await(await d()).prepare("SELECT * FROM node_rows WHERE node_id = ?").get(e);return n===void 0?null:await A(n)}i(O,"getNode");async function Hn(e){if(e.length===0)return[];const n=v.map(r=>`w.${r} AS worktree_${r}`).join(", "),t=await(await d()).prepareUncached(`SELECT n.*, ${n} FROM node_rows n LEFT JOIN worktrees w ON w.node_id = n.node_id WHERE n.node_id IN (${e.map(()=>"?").join(",")})`).all(...e),a=new Map(t.map(r=>[r.node_id,r]));return await h(e.map(r=>a.get(r)).filter(r=>r!==void 0),async r=>await A(r,ee(r)))}i(Hn,"getNodes");const Ze=1440*60*1e3;function Z(e){return{requestKey:e.request_key,nodeId:e.node_id,state:e.state}}i(Z,"createRequestRecord");async function Mn(e){const n=await(await d()).prepareUncached("SELECT request_key, node_id, state FROM create_requests WHERE request_key = ?").get(e);return n===void 0?null:Z(n)}i(Mn,"findCreateRequest");async function Pn(e){return await p(async n=>{const t=Date.now();await n.prepareUncached("DELETE FROM create_requests WHERE expires_at <= ?").run(t),await n.prepareUncached("INSERT INTO create_requests (request_key, node_id, expires_at, state) VALUES (?, NULL, ?, 'reserved') ON CONFLICT (request_key) DO NOTHING").run(e,t+Ze);const a=await n.prepareUncached("SELECT request_key, node_id, state FROM create_requests WHERE request_key = ?").get(e);return Z(a)})}i(Pn,"reserveCreateRequest");async function $n(e=Date.now()){return Number((await(await d()).prepareUncached("DELETE FROM create_requests WHERE expires_at <= ?").run(e)).changes)}i($n,"pruneExpiredCreateRequests");async function qn(e,n){await(await d()).prepareUncached("UPDATE create_requests SET node_id = ?, state = 'complete' WHERE request_key = ?").run(n,e)}i(qn,"recordCreateRequestNode");async function Bn(e,n,t){const a=await d();return await a.prepareUncached("UPDATE create_requests SET node_id = ?, state = 'reserved', lease_owner = ?, lease_expires_at = ? WHERE request_key = ? AND node_id IS NULL").run(n,t,Date.now()+g,e),(await a.prepareUncached("SELECT node_id FROM create_requests WHERE request_key = ?").get(e))?.node_id??null}i(Bn,"reserveCreateRequestNode");const g=3e4,zn=1e4;async function Jn(e,n,t){const a=Date.now(),r=await(await d()).prepareUncached("UPDATE create_requests SET lease_owner = ?, lease_expires_at = ? WHERE request_key = ? AND node_id = ? AND state = 'reserved' AND (lease_expires_at IS NULL OR lease_expires_at <= ?)").run(t,a+g,e,n,a);return Number(r.changes)>0}i(Jn,"claimCreateLease");async function Yn(e,n){await(await d()).prepareUncached("UPDATE create_requests SET lease_expires_at = ? WHERE request_key = ? AND lease_owner = ?").run(Date.now()+g,e,n)}i(Yn,"renewCreateLease");async function Qn(e){const n=await(await d()).prepareUncached("SELECT lease_expires_at FROM create_requests WHERE request_key = ?").get(e);return n?.lease_expires_at!=null&&Number(n.lease_expires_at)>Date.now()}i(Qn,"createLeaseLive");async function Vn(e,n){await(await d()).prepareUncached("UPDATE create_requests SET state = 'complete' WHERE request_key = ? AND node_id = ?").run(e,n)}i(Vn,"completeCreateRequest");async function Kn(e,n){await p(async t=>{if(n===null){await t.prepareUncached("DELETE FROM create_requests WHERE request_key = ? AND node_id IS NULL").run(e);return}await t.prepareUncached("DELETE FROM create_requests WHERE request_key = ? AND node_id = ?").run(e,n)})}i(Kn,"abandonCreateRequest");function Gn(e){return Ne(e)}i(Gn,"canonicalSessionFile");async function Xn(e){const n=await ge(e);return n===null?null:await O(n)}i(Xn,"findNodeBySessionFile");async function Zn(e){const n=await(await d()).prepare("SELECT * FROM node_rows WHERE node_id = ?").get(e);return n?f(n):null}i(Zn,"getRow");async function et(e){const n=await(await d()).prepare("SELECT * FROM node_rows WHERE pane = ?").get(e);return n?f(n):null}i(et,"getRowByPane");async function nt(e){return(await(await d()).prepare(`SELECT * FROM node_rows
1
+ var ce=Object.defineProperty;var i=(e,n)=>ce(e,"name",{value:n,configurable:!0});import{loadExactProfileManifest as le}from"../profiles/manifest.js";import{envNodeId as H}from"../../shared/env.js";import{lstatSync as _e,realpathSync as M,rmdirSync as pe,rmSync as fe,statSync as Ee}from"node:fs";import{basename as we,dirname as P,isAbsolute as ye,join as S,relative as me,resolve as Ne,sep as Re}from"node:path";import{removeTreeBeneath as $}from"../spaces/open-beneath.js";import{emitEvent as Se}from"../events/emit.js";import{deleteNodeSandboxes as q}from"../runtime/runner/delete-sandboxes.js";import{withCanvasWrite as p,openDb as d}from"./db.js";import{conversationStore as he,ConversationNotFoundError as Oe}from"../conversation-store/index.js";import{hasUnseenWakeMail as Le,UNSEEN_WAKE_MAIL_SQL as Te}from"./deliveries.js";import{isAppRun as B}from"./app-run.js";import{registerOutcomeAction as z}from"./outcome-actions.js";import{publish as De}from"../graph/events.js";import{nodeObject as Ae}from"../graph/objects.js";import{findNodeBySessionFileSql as ge}from"./sessions.js";import{hydrateFault as ke}from"./recovery.js";import{hasUnreconciledWorktree as ve,openWorktree as xe,readWorktree as Ue,worktreeFromRow as We}from"./worktrees.js";import{isPidAlive as be,isPidPresent as J,recordedPidLiveness as je}from"./pid.js";import{isCloudRole as Ie}from"./person-state.js";import{ensureHome as Fe,jobDir as Ce,nodeDir as He,nodeRunDir as Y}from"./paths.js";import{appForNode as Me,ensureNodeDirs as Pe,nodeAgentDir as $e}from"./node-agent-paths.js";import{appSpace as T}from"../layout.js";import{createObject as qe,getById as D,ownerForGrantee as Be,setObjectKind as ze,setObjectName as Je}from"../graph/objects.js";import{profileObject as Ye}from"../graph/reader.js";import{writeActsFor as Q}from"../permissions/facts.js";import{CrtrError as Qe}from"../errors.js";import{deleteNodeWithOwned as Ve}from"../graph/deletion.js";import{SUBTREE_ALL_IDS_SQL as Ke,SUBTREE_IDS_SQL as Ge}from"./tree.js";import{filterAsync as y,mapAsync as h}from"../async-array.js";function E(e,n){if(e==null)return null;const t=JSON.stringify(e);if(t===void 0)throw new TypeError(`${n} must be JSON-serializable`);return t}i(E,"jsonValue");async function Fn(e,n){if((await e.prepare("SELECT deleting_at FROM nodes WHERE node_id = ?").get(n))?.deleting_at)throw new Error("run is deleting")}i(Fn,"assertRunNotDeleting");async function V(e,n,t,a){try{return(le(n).manifest.grantee??"app:terminal")!==a?null:await Ye(e,n,t)}catch(r){if(r instanceof Qe&&r.code==="not_found")return null;throw r}}i(V,"profileObjectFor");async function Xe(e,n){const t=await Be(n,e.grantee??"app:terminal"),a=e.profile_id?await V(n,e.profile_id,t,e.grantee??"app:terminal"):null;await qe(n,{id:e.node_id,type:"node",kind:e.kind,owner:(a??t).id,privacy:"public",name:e.name,preview:""}),a===null&&e.sub&&await Q(n,e.node_id,e.sub),await n.prepare(`INSERT INTO nodes (node_id, description, title, icon, cycles, mode, lifecycle, cwd, host_kind, profile_id, parent, spawned_by, creator, fork_from, fork_source_file, created, passive_default, cycle_pending, model_override, persona_ack_json, review_binding_json, launch_config_json, scopes_json, isolated, status, intent, final_report, finalized_at, deadline_at, "window", tmux_session, pane, sub, grant_id, client_id, metadata_json, run_id, event_cursor, deleting_at, caused_by, app) VALUES (${Array(41).fill("?").join(", ")})`).run(e.node_id,e.description??null,e.title??null,e.icon??null,e.cycles??null,e.mode,e.lifecycle,e.cwd,e.host_kind??null,e.profile_id??null,e.parent??null,e.spawned_by??null,e.creator??null,e.fork_from??null,e.fork_source_file??null,e.created,e.passive_default===!0?1:0,e.cycle_pending===!0?1:0,e.model_override??null,E(e.persona_ack,"persona_ack"),E(e.review_binding,"review_binding"),E(e.launch,"launch"),E(e.scopes,"scopes"),e.isolated===!0?1:0,e.status??"active",e.intent??null,e.final_report??null,e.finalized_at??null,e.deadline_at??null,e.window??null,e.tmux_session??null,e.pane??null,e.sub??null,e.grant_id??null,e.client_id??null,e.metadata_json??null,e.run_id??null,e.event_cursor??null,e.deleting_at??null,e.caused_by??null,t.id)}i(Xe,"seedRow");function K(e){if(e.fault_id==null)return null;const n=Object.entries(e).filter(([t])=>t.startsWith("fault_")).map(([t,a])=>[t==="fault_id"?t:t.slice(6),a]);return ke(Object.fromEntries(n))}i(K,"faultFrom");const G=i(e=>e.turn_open_at!=null&&e.turn_closed_at==null,"turnOpen"),X=i(e=>e||Ie(),"engineLive");function f(e){const n={node_id:e.node_id,name:e.name,description:e.description??void 0,cycles:e.cycles??void 0,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind??null,profile_id:e.profile_id??null,scopes:e.scopes_json==null?null:JSON.parse(e.scopes_json),isolated:e.isolated===1,grantee:e.grantee,sub:e.sub??null,grant_id:e.grant_id??null,client_id:e.client_id??null,metadata_json:e.metadata_json??null,run_id:e.run_id??null,event_cursor:e.event_cursor??null,last_activity_at:e.last_activity_at??null,caused_by:e.caused_by??null,last_turn_error_json:e.last_turn_error_json??null,deleting_at:e.deleting_at??null,parent:e.parent??null,created:e.created,intent:e.intent??null,cycle_pending:e.cycle_pending===1,frozen_at:e.frozen_at??null,respawn_failures:e.respawn_failures??0,respawn_not_before:e.respawn_not_before??null,launched_at:e.launched_at??null,last_settled_at:e.last_settled_at??null,terminal_reason:e.terminal_reason??null,final_report:e.final_report??null,finalized_at:e.finalized_at??null,outcome_kind:e.outcome_kind??null,outcome_reason:e.outcome_reason??null,outcome_at:e.outcome_at??null,outcome_revision:e.outcome_revision??0,outcome_detail_json:e.outcome_detail_json??null,deadline_at:e.deadline_at??null,telemetry_tokens_in:e.telemetry_tokens_in??null,telemetry_context_tokens:e.telemetry_context_tokens??null,telemetry_last_activity:e.telemetry_last_activity??null,telemetry_updated_at:e.telemetry_updated_at??null,pi_pid:e.pi_pid??null,pi_pid_identity:e.pi_pid_identity??null,window:e.window??null,tmux_session:e.tmux_session??null,pane:e.pane??null,fault:null,streaming:!1},t=J(n.pi_pid),a=K(e);return n.fault=a?.link==="pi\u2192provider"&&a.retry.by==="daemon"&&a.retry.disposition==="auto"&&!t?null:a,n.streaming=G(e)&&X(t),n}i(f,"rowFrom");async function A(e,n){return n??=await Ue(e.node_id),{...f(e),title:e.title??void 0,icon:e.icon??void 0,spawned_by:e.spawned_by??null,creator:e.creator??null,fork_from:e.fork_from??null,fork_source_file:e.fork_source_file??null,passive_default:e.passive_default===1,model_override:e.model_override??null,scopes:e.scopes_json==null?null:JSON.parse(e.scopes_json),persona_ack:e.persona_ack_json==null?void 0:JSON.parse(e.persona_ack_json),review_binding:e.review_binding_json==null?void 0:JSON.parse(e.review_binding_json),launch:e.launch_config_json==null?void 0:JSON.parse(e.launch_config_json),pi_session_id:e.pi_session_id??null,pi_session_file:e.pi_session_file??null,...n===null?{}:{managed_worktree:n}}}i(A,"metaFrom");async function Cn(e,n={}){return Fe(),await p(async t=>{await Xe(e,t),e.managed_worktree!==void 0&&e.managed_worktree!==null&&await xe(e.node_id,e.managed_worktree,t),n.outcomeDelivery!==void 0&&await z(t,e.node_id,n.outcomeDelivery),await n.withinCreate?.(t,e)}),await Pe(e.node_id),await O(e.node_id)}i(Cn,"createNode");async function O(e){const n=await(await d()).prepare("SELECT * FROM node_rows WHERE node_id = ?").get(e);return n===void 0?null:await A(n)}i(O,"getNode");async function Hn(e){if(e.length===0)return[];const n=v.map(r=>`w.${r} AS worktree_${r}`).join(", "),t=await(await d()).prepareUncached(`SELECT n.*, ${n} FROM node_rows n LEFT JOIN worktrees w ON w.node_id = n.node_id WHERE n.node_id IN (${e.map(()=>"?").join(",")})`).all(...e),a=new Map(t.map(r=>[r.node_id,r]));return await h(e.map(r=>a.get(r)).filter(r=>r!==void 0),async r=>await A(r,ee(r)))}i(Hn,"getNodes");const Ze=1440*60*1e3;function Z(e){return{requestKey:e.request_key,nodeId:e.node_id,state:e.state}}i(Z,"createRequestRecord");async function Mn(e){const n=await(await d()).prepareUncached("SELECT request_key, node_id, state FROM create_requests WHERE request_key = ?").get(e);return n===void 0?null:Z(n)}i(Mn,"findCreateRequest");async function Pn(e){return await p(async n=>{const t=Date.now();await n.prepareUncached("DELETE FROM create_requests WHERE expires_at <= ?").run(t),await n.prepareUncached("INSERT INTO create_requests (request_key, node_id, expires_at, state) VALUES (?, NULL, ?, 'reserved') ON CONFLICT (request_key) DO NOTHING").run(e,t+Ze);const a=await n.prepareUncached("SELECT request_key, node_id, state FROM create_requests WHERE request_key = ?").get(e);return Z(a)})}i(Pn,"reserveCreateRequest");async function $n(e=Date.now()){return Number((await(await d()).prepareUncached("DELETE FROM create_requests WHERE expires_at <= ?").run(e)).changes)}i($n,"pruneExpiredCreateRequests");async function qn(e,n){await(await d()).prepareUncached("UPDATE create_requests SET node_id = ?, state = 'complete' WHERE request_key = ?").run(n,e)}i(qn,"recordCreateRequestNode");async function Bn(e,n,t){const a=await d();return await a.prepareUncached("UPDATE create_requests SET node_id = ?, state = 'reserved', lease_owner = ?, lease_expires_at = ? WHERE request_key = ? AND node_id IS NULL").run(n,t,Date.now()+g,e),(await a.prepareUncached("SELECT node_id FROM create_requests WHERE request_key = ?").get(e))?.node_id??null}i(Bn,"reserveCreateRequestNode");const g=3e4,zn=1e4;async function Jn(e,n,t){const a=Date.now(),r=await(await d()).prepareUncached("UPDATE create_requests SET lease_owner = ?, lease_expires_at = ? WHERE request_key = ? AND node_id = ? AND state = 'reserved' AND (lease_expires_at IS NULL OR lease_expires_at <= ?)").run(t,a+g,e,n,a);return Number(r.changes)>0}i(Jn,"claimCreateLease");async function Yn(e,n){await(await d()).prepareUncached("UPDATE create_requests SET lease_expires_at = ? WHERE request_key = ? AND lease_owner = ?").run(Date.now()+g,e,n)}i(Yn,"renewCreateLease");async function Qn(e){const n=await(await d()).prepareUncached("SELECT lease_expires_at FROM create_requests WHERE request_key = ?").get(e);return n?.lease_expires_at!=null&&Number(n.lease_expires_at)>Date.now()}i(Qn,"createLeaseLive");async function Vn(e,n){await(await d()).prepareUncached("UPDATE create_requests SET state = 'complete' WHERE request_key = ? AND node_id = ?").run(e,n)}i(Vn,"completeCreateRequest");async function Kn(e,n){await p(async t=>{if(n===null){await t.prepareUncached("DELETE FROM create_requests WHERE request_key = ? AND node_id IS NULL").run(e);return}await t.prepareUncached("DELETE FROM create_requests WHERE request_key = ? AND node_id = ?").run(e,n)})}i(Kn,"abandonCreateRequest");function Gn(e){return Ne(e)}i(Gn,"canonicalSessionFile");async function Xn(e){const n=await ge(e);return n===null?null:await O(n)}i(Xn,"findNodeBySessionFile");async function Zn(e){const n=await(await d()).prepare("SELECT * FROM node_rows WHERE node_id = ?").get(e);return n?f(n):null}i(Zn,"getRow");async function et(e){const n=await(await d()).prepare("SELECT * FROM node_rows WHERE pane = ?").get(e);return n?f(n):null}i(et,"getRowByPane");async function nt(e){return(await(await d()).prepare(`SELECT * FROM node_rows
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
4
  ORDER BY deadline_at, created, node_id`).all(e)).map(f)}i(nt,"dueNodeDeadlines");async function tt(e,n){return Number((await(await d()).prepare("UPDATE nodes SET deadline_at = ? WHERE node_id = ?").run(n,e)).changes)===1}i(tt,"setNodeDeadline");async function at(e,n){return!Number.isFinite(n)||n<=0?0:await p(async t=>{const a=await t.prepare(`SELECT node_id, deadline_at FROM nodes
@@ -1,20 +1,20 @@
1
- var x=Object.defineProperty;var o=(e,a)=>x(e,"name",{value:a,configurable:!0});import{prepared as m}from"../sqlite-statements.js";import{existsSync as I,readFileSync as O}from"node:fs";import{randomBytes as C}from"node:crypto";import{withCanvasWrite as T,openDb as N}from"./db.js";import{CLAIM_OWNER_EXPIRED_SQL as X}from"./reconciler-leases.js";import{inboxPath as w,passivePath as R}from"./paths.js";import{withRetryBudget as M}from"./delivery-contract.js";import{emitEvent as F}from"../events/emit.js";import{mapAsync as H}from"../async-array.js";function D(e){return{deliveryId:e.delivery_id,messageId:e.message_id,destinationId:e.destination_id,urgency:e.urgency,wake:e.wake===1?1:0,state:e.state,attempts:e.attempts,nextAttemptAt:e.next_attempt_at,claimedAt:e.claimed_at,claimOwner:e.claim_owner,acknowledgedAt:e.acknowledged_at,failedAt:e.failed_at,lastFailure:e.last_failure_json===null?null:JSON.parse(e.last_failure_json),idempotencyKey:e.idempotency_key,canceledAt:e.canceled_at,createdAt:e.created_at,updatedAt:e.updated_at}}o(D,"deliveryFrom");async function L(e,a,r,d){return await e.prepare(`SELECT 1 FROM nodes n JOIN executions e ON e.node_id = n.node_id
2
- WHERE n.node_id = ? AND e.execution_id = ? AND e.state != 'exited' AND e.stop_reason IS DISTINCT FROM 'release'${d?" AND n.intent IS DISTINCT FROM 'refresh'":""}`).get(a,r)!==void 0}o(L,"executionIsLive");async function y(e,a,r,d,s,E=!1){return(await e.prepare(`SELECT d.*, m.message_id AS m_message_id, m.seq, m.operation_id, m.created_at AS message_created_at,
1
+ var x=Object.defineProperty;var o=(e,a)=>x(e,"name",{value:a,configurable:!0});import{prepared as m}from"../sqlite-statements.js";import{existsSync as I,readFileSync as D}from"node:fs";import{randomBytes as C}from"node:crypto";import{withCanvasWrite as T,openDb as N}from"./db.js";import{CLAIM_OWNER_EXPIRED_SQL as X}from"./reconciler-leases.js";import{inboxPath as y,passivePath as R}from"./paths.js";import{withRetryBudget as M}from"./delivery-contract.js";import{emitEvent as F}from"../events/emit.js";import{mapAsync as H}from"../async-array.js";function O(e){return{deliveryId:e.delivery_id,messageId:e.message_id,destinationId:e.destination_id,urgency:e.urgency,wake:e.wake===1?1:0,state:e.state,attempts:e.attempts,nextAttemptAt:e.next_attempt_at,claimedAt:e.claimed_at,claimOwner:e.claim_owner,acknowledgedAt:e.acknowledged_at,failedAt:e.failed_at,lastFailure:e.last_failure_json===null?null:JSON.parse(e.last_failure_json),idempotencyKey:e.idempotency_key,canceledAt:e.canceled_at,createdAt:e.created_at,updatedAt:e.updated_at}}o(O,"deliveryFrom");async function L(e,a,r,d){return await e.prepare(`SELECT 1 FROM nodes n JOIN executions e ON e.node_id = n.node_id
2
+ WHERE n.node_id = ? AND e.execution_id = ? AND e.state != 'exited' AND e.stop_reason IS DISTINCT FROM 'release'${d?" AND n.intent IS DISTINCT FROM 'refresh' AND n.cycle_pending = 0":""}`).get(a,r)!==void 0}o(L,"executionIsLive");async function w(e,a,r,d,s,E=!1){return(await e.prepare(`SELECT d.*, m.message_id AS m_message_id, m.seq, m.operation_id, m.created_at AS message_created_at,
3
3
  m.sender_node_id, m.sender_name, m.kind, m.label, m.body_ref, m.body_json, m.disposition
4
4
  FROM deliveries d JOIN messages m ON m.message_id = d.message_id
5
5
  WHERE d.destination_id = ? AND d.wake = ?
6
6
  ${E?"AND m.kind = 'message' AND m.body_json ->> 'start_turn' = 'false'":d===0?"AND NOT (m.kind = 'message' AND coalesce(m.body_json ->> 'start_turn', 'true') = 'false')":""}
7
7
  AND d.canceled_at IS NULL
8
8
  AND d.state = 'handed_off' AND d.claim_owner = ?
9
- ORDER BY m.seq`).all(a,d,r)).map(i=>({...D(i),message:{messageId:i.m_message_id,seq:Number(i.seq),operationId:i.operation_id,createdAt:i.message_created_at,senderNodeId:i.sender_node_id,senderName:i.sender_name,kind:i.kind,label:i.label,bodyRef:i.body_ref,bodyJson:i.body_json===null?null:JSON.parse(i.body_json),disposition:i.disposition},handoff:s?.has(i.delivery_id)===!0?"fresh":"inherited"}))}o(y,"nodeMailRows");const v=`SELECT d.delivery_id FROM deliveries d JOIN messages m ON m.message_id = d.message_id
9
+ ORDER BY m.seq`).all(a,d,r)).map(i=>({...O(i),message:{messageId:i.m_message_id,seq:Number(i.seq),operationId:i.operation_id,createdAt:i.message_created_at,senderNodeId:i.sender_node_id,senderName:i.sender_name,kind:i.kind,label:i.label,bodyRef:i.body_ref,bodyJson:i.body_json===null?null:JSON.parse(i.body_json),disposition:i.disposition},handoff:s?.has(i.delivery_id)===!0?"fresh":"inherited"}))}o(w,"nodeMailRows");const v=`SELECT d.delivery_id FROM deliveries d JOIN messages m ON m.message_id = d.message_id
10
10
  WHERE d.destination_id = ? AND d.wake = ? AND d.state = 'pending' AND d.canceled_at IS NULL
11
11
  AND NOT (d.wake = 0 AND m.kind = 'message' AND coalesce(m.body_json ->> 'start_turn', 'true') = 'false')`,W=`UPDATE deliveries SET state = 'handed_off', attempts = attempts + 1, claim_owner = ?, claimed_at = ?, updated_at = ?
12
12
  WHERE delivery_id IN (${v}) RETURNING delivery_id`;async function te(e,a,r,d=Date.now()){const s=r==="wake"?1:0;if(r==="deferred_run")return await T(async c=>{if(!await L(c,e,a,!0))return{action:"hold",deliveries:[]};const i=await c.prepare(`SELECT d.delivery_id FROM deliveries d JOIN messages m ON m.message_id = d.message_id
13
13
  WHERE d.destination_id = ? AND d.wake = 0 AND d.canceled_at IS NULL
14
14
  AND m.kind = 'message' AND m.body_json ->> 'start_turn' = 'false'
15
15
  AND (d.state = 'pending' OR (d.state = 'handed_off' AND d.claim_owner = ?))`).all(e,a),t=new Set(i.length===0?[]:(await c.prepare(`UPDATE deliveries SET state = 'handed_off', attempts = attempts + 1, claim_owner = ?, claimed_at = ?, updated_at = ?
16
- WHERE delivery_id IN (${i.map(()=>"?").join(",")}) AND state = 'pending' RETURNING delivery_id`).all(a,d,d,...i.map(n=>n.delivery_id))).map(n=>n.delivery_id));return{action:"claimed",deliveries:await y(c,e,a,0,t,!0)}});const E=await N();return!E.inTransaction&&await E.prepare(v).get(e,s)===void 0?await L(E,e,a,!0)?{action:"claimed",deliveries:await y(E,e,a,s)}:{action:"hold",deliveries:[]}:await T(async c=>{if(!await L(c,e,a,!0))return{action:"hold",deliveries:[]};const i=new Set((await c.prepare(W).all(a,d,d,e,s)).map(t=>t.delivery_id));return{action:"claimed",deliveries:await y(c,e,a,s,i)}})}o(te,"claimNodeMail");async function ae(e,a,r=Date.now()){return await T(async d=>{if(!await L(d,e,a,!1))throw new Error(`execution ${a} is not live for node ${e}`);const s=new Set((await d.prepare(`UPDATE deliveries SET state = 'handed_off', attempts = attempts + 1, claim_owner = ?, claimed_at = ?, updated_at = ?
17
- WHERE destination_id = ? AND wake = 1 AND state = 'pending' AND canceled_at IS NULL RETURNING delivery_id`).all(a,r,r,e)).map(E=>E.delivery_id));return await y(d,e,a,1,s)})}o(ae,"claimKickoffMail");function j(e){return e.state==="accepted"?{state:"acknowledged"}:e}o(j,"normalizedSettlement");async function $(e,a,r,d,s=Date.now()){const E=[],c=await T(async i=>{const n=(await i.prepare("SELECT canceled_at FROM deliveries WHERE delivery_id = ? AND next_attempt_at IS NOT NULL").get(e))?.canceled_at!=null?{state:"acknowledged"}:j(d),l=M(n,a),_=l.settlement,S=_.state==="pending"||_.state==="permanent_failed"?JSON.stringify(_.failure):null,g=_.state==="released"?"pending":_.state,p=_.state==="pending"?_.nextAttemptAt:g==="pending"?s:null,f=Number((await i.prepare(`UPDATE deliveries
16
+ WHERE delivery_id IN (${i.map(()=>"?").join(",")}) AND state = 'pending' RETURNING delivery_id`).all(a,d,d,...i.map(n=>n.delivery_id))).map(n=>n.delivery_id));return{action:"claimed",deliveries:await w(c,e,a,0,t,!0)}});const E=await N();return!E.inTransaction&&await E.prepare(v).get(e,s)===void 0?await L(E,e,a,!0)?{action:"claimed",deliveries:await w(E,e,a,s)}:{action:"hold",deliveries:[]}:await T(async c=>{if(!await L(c,e,a,!0))return{action:"hold",deliveries:[]};const i=new Set((await c.prepare(W).all(a,d,d,e,s)).map(t=>t.delivery_id));return{action:"claimed",deliveries:await w(c,e,a,s,i)}})}o(te,"claimNodeMail");async function ae(e,a,r=Date.now()){return await T(async d=>{if(!await L(d,e,a,!1))throw new Error(`execution ${a} is not live for node ${e}`);const s=new Set((await d.prepare(`UPDATE deliveries SET state = 'handed_off', attempts = attempts + 1, claim_owner = ?, claimed_at = ?, updated_at = ?
17
+ WHERE destination_id = ? AND wake = 1 AND state = 'pending' AND canceled_at IS NULL RETURNING delivery_id`).all(a,r,r,e)).map(E=>E.delivery_id));return await w(d,e,a,1,s)})}o(ae,"claimKickoffMail");function j(e){return e.state==="accepted"?{state:"acknowledged"}:e}o(j,"normalizedSettlement");async function $(e,a,r,d,s=Date.now()){const E=[],c=await T(async i=>{const n=(await i.prepare("SELECT canceled_at FROM deliveries WHERE delivery_id = ? AND next_attempt_at IS NOT NULL").get(e))?.canceled_at!=null?{state:"acknowledged"}:j(d),l=M(n,a),_=l.settlement,S=_.state==="pending"||_.state==="permanent_failed"?JSON.stringify(_.failure):null,g=_.state==="released"?"pending":_.state,p=_.state==="pending"?_.nextAttemptAt:g==="pending"?s:null,f=Number((await i.prepare(`UPDATE deliveries
18
18
  SET state = ?, next_attempt_at = ?, claimed_at = NULL, claim_owner = NULL,
19
19
  acknowledged_at = ?, failed_at = ?, last_failure_json = ?, updated_at = ?
20
20
  WHERE delivery_id = ? AND state = 'handed_off' AND attempts = ? AND claim_owner = ?`).run(g,p,g==="acknowledged"?s:null,g==="permanent_failed"?s:null,S,s,e,a,r)).changes)===1;if(f&&l.exhausted&&_.state==="permanent_failed"){const A=await i.prepare("SELECT destination_id, message_id FROM deliveries WHERE delivery_id = ?").get(e);E.push({failure:_.failure,destinationId:A.destination_id,messageId:A.message_id})}return f});for(const i of E)F({level:"error",event:"delivery.exhausted",outcome:"failed",attempt:a,fields:{delivery_id:e,destination_id:i.destinationId,message_id:i.messageId,failure:i.failure,retry:`crtr sys retry-delivery ${e}`}});return c}o($,"settleDelivery");async function ne(e,a=Date.now()){return Number((await(await N()).prepare(`UPDATE deliveries
@@ -22,13 +22,13 @@ var x=Object.defineProperty;var o=(e,a)=>x(e,"name",{value:a,configurable:!0});i
22
22
  WHERE delivery_id = ? AND state = 'permanent_failed' AND canceled_at IS NULL AND last_failure_json IS NOT NULL`).run(a,a,e)).changes)===1}o(ne,"retryFailedDelivery");async function ie(e,a,r,d=Date.now()){return await T(async s=>await L(s,e,a,!1)?{action:"acknowledged",results:await H(r,async c=>{const i=await s.prepare("SELECT 1 FROM deliveries WHERE delivery_id = ? AND destination_id = ?").get(c.deliveryId,e)!==void 0;return{deliveryId:c.deliveryId,outcome:i&&await $(c.deliveryId,c.attempts,a,{state:c.disposition},d)?c.disposition:"stale"}})}:{action:"hold",results:[]})}o(ie,"acknowledgeNodeMail");async function de(e){const a=await(await N()).prepare(`SELECT m.body_json FROM deliveries d JOIN messages m ON m.message_id = d.message_id
23
23
  WHERE d.delivery_id = ?`).get(e);return a===void 0||a.body_json===null?null:JSON.parse(a.body_json)}o(de,"messageBodyForDelivery");async function se(e){return(await(await N()).prepare(`SELECT * FROM deliveries
24
24
  WHERE state = 'pending' AND canceled_at IS NULL AND next_attempt_at <= ?
25
- ORDER BY next_attempt_at, created_at, delivery_id`).all(e)).map(D)}o(se,"duePushDeliveries");async function re(e,a,r){return await T(async d=>{const s=await d.prepare(`UPDATE deliveries AS d SET state = 'handed_off', attempts = attempts + 1, claimed_at = ?, claim_owner = ?, updated_at = ?
25
+ ORDER BY next_attempt_at, created_at, delivery_id`).all(e)).map(O)}o(se,"duePushDeliveries");async function re(e,a,r){return await T(async d=>{const s=await d.prepare(`UPDATE deliveries AS d SET state = 'handed_off', attempts = attempts + 1, claimed_at = ?, claim_owner = ?, updated_at = ?
26
26
  WHERE d.delivery_id = ? AND d.state = 'pending' AND d.canceled_at IS NULL AND d.next_attempt_at <= ?
27
27
  AND NOT EXISTS (SELECT 1 FROM deliveries old JOIN messages prior ON prior.message_id = old.message_id
28
28
  JOIN messages next ON next.message_id = d.message_id
29
29
  WHERE old.destination_id = d.destination_id AND old.delivery_id != d.delivery_id
30
30
  AND old.state = 'handed_off' AND old.canceled_at IS NOT NULL
31
- AND prior.event = 'outcome' AND next.event = 'outcome' AND prior.object_id = next.object_id)`).run(a,r,a,e,a);return Number(s.changes)===0?null:D(await d.prepare("SELECT * FROM deliveries WHERE delivery_id = ?").get(e))})}o(re,"claimPushDelivery");async function oe(e,a=!1){return await T(async r=>{const d=a?` AND ${X}`:"",s=a?[new Date(e).toISOString()]:[],E=await r.prepare(`UPDATE deliveries SET state = 'permanent_failed', next_attempt_at = NULL,
31
+ AND prior.event = 'outcome' AND next.event = 'outcome' AND prior.object_id = next.object_id)`).run(a,r,a,e,a);return Number(s.changes)===0?null:O(await d.prepare("SELECT * FROM deliveries WHERE delivery_id = ?").get(e))})}o(re,"claimPushDelivery");async function oe(e,a=!1){return await T(async r=>{const d=a?` AND ${X}`:"",s=a?[new Date(e).toISOString()]:[],E=await r.prepare(`UPDATE deliveries SET state = 'permanent_failed', next_attempt_at = NULL,
32
32
  claimed_at = NULL, claim_owner = NULL, failed_at = ?, updated_at = ?
33
33
  WHERE state = 'handed_off' AND canceled_at IS NOT NULL AND next_attempt_at IS NOT NULL${d}`).run(e,e,...s),c=await r.prepare(`UPDATE deliveries SET state = 'pending', next_attempt_at = CASE WHEN next_attempt_at IS NOT NULL THEN ?::bigint ELSE NULL END,
34
34
  claimed_at = NULL, claim_owner = NULL, updated_at = ?
@@ -39,8 +39,8 @@ var x=Object.defineProperty;var o=(e,a)=>x(e,"name",{value:a,configurable:!0});i
39
39
  AND NOT EXISTS (
40
40
  SELECT 1 FROM executions e WHERE e.node_id = d.destination_id AND e.execution_id = d.claim_owner AND e.state != 'exited'
41
41
  )`).run(e)).changes)}o(ce,"resetStaleExecutionMail");const b=o((e,a)=>`${e}.wake = 1 AND ${e}.canceled_at IS NULL AND ${e}.urgency != 'deferred' AND ${e}.state IN (${a})`,"WAKE_MAIL_SQL"),q=o(e=>b(e,"'pending', 'handed_off'"),"UNSEEN_WAKE_MAIL_SQL");async function Ee(e){return await(await N()).prepare(`SELECT 1 FROM deliveries d WHERE d.destination_id = ? AND ${q("d")} LIMIT 1`).get(e)!==void 0}o(Ee,"hasUnseenWakeMail");async function me(e,a){return await(await N()).prepare(`SELECT 1 FROM deliveries WHERE destination_id = ? AND wake = 1
42
- AND urgency != 'deferred' AND created_at >= ? LIMIT 1`).get(e,a)!==void 0}o(me,"hasWakeMailSince");async function Ne(e){return Number((await(await N()).prepare("SELECT COUNT(*) AS count FROM deliveries WHERE destination_id = ? AND acknowledged_at IS NOT NULL").get(e)).count)}o(Ne,"acknowledgedNodeMailCount");function u(){let e;do e=C(16).toString("hex");while(e==="00000000000000000000000000000000");return e}o(u,"newId");function U(e){if(!I(e))return[];const a=O(e,"utf8");return a.trim()===""?[]:a.split(`
43
- `).filter(r=>r.trim()!=="").map((r,d)=>{let s;try{s=JSON.parse(r)}catch(E){throw new Error(`invalid mailbox JSON at ${e}:${d+1}: ${E.message}`)}if(!/^(?!0{32}$)[0-9a-f]{32}$/.test(s.entry_id)||!/^(?!0{32}$)[0-9a-f]{32}$/.test(s.operation_id))throw new Error(`invalid mailbox identity at ${e}:${d+1}`);if(typeof s.ts!="string"||typeof s.label!="string")throw new Error(`incomplete mailbox entry at ${e}:${d+1}`);return s})}o(U,"readJsonLines");function J(e){return I(e)?new Set(O(e,"utf8").split(`
42
+ AND urgency != 'deferred' AND created_at >= ? LIMIT 1`).get(e,a)!==void 0}o(me,"hasWakeMailSince");async function Ne(e){return Number((await(await N()).prepare("SELECT COUNT(*) AS count FROM deliveries WHERE destination_id = ? AND acknowledged_at IS NOT NULL").get(e)).count)}o(Ne,"acknowledgedNodeMailCount");function u(){let e;do e=C(16).toString("hex");while(e==="00000000000000000000000000000000");return e}o(u,"newId");function U(e){if(!I(e))return[];const a=D(e,"utf8");return a.trim()===""?[]:a.split(`
43
+ `).filter(r=>r.trim()!=="").map((r,d)=>{let s;try{s=JSON.parse(r)}catch(E){throw new Error(`invalid mailbox JSON at ${e}:${d+1}: ${E.message}`)}if(!/^(?!0{32}$)[0-9a-f]{32}$/.test(s.entry_id)||!/^(?!0{32}$)[0-9a-f]{32}$/.test(s.operation_id))throw new Error(`invalid mailbox identity at ${e}:${d+1}`);if(typeof s.ts!="string"||typeof s.label!="string")throw new Error(`incomplete mailbox entry at ${e}:${d+1}`);return s})}o(U,"readJsonLines");function J(e){return I(e)?new Set(D(e,"utf8").split(`
44
44
  `).map(a=>a.trim()).filter(Boolean)):new Set}o(J,"readCanceled");function pe(e){e.exec(`
45
45
  CREATE TABLE IF NOT EXISTS messages (
46
46
  message_id TEXT PRIMARY KEY,
@@ -95,4 +95,4 @@ CREATE TABLE IF NOT EXISTS waits (
95
95
  );
96
96
  CREATE UNIQUE INDEX IF NOT EXISTS waits_live ON waits(node_id) WHERE satisfied_at IS NULL;
97
97
  CREATE INDEX IF NOT EXISTS waits_node ON waits(node_id);
98
- `);const a=[];for(const t of m(e,"SELECT node_id FROM nodes").all()){const n=t.node_id,l=U(w(n)),_=I(`${w(n)}.cursor`)?O(`${w(n)}.cursor`,"utf8").trim():"",S=l.findIndex(p=>p.entry_id===_),g=J(`${w(n)}.canceled`);l.forEach((p,f)=>a.push({nodeId:n,wake:1,source:"inbox",fileRank:0,physicalIndex:f,entry:p,acknowledged:S>=0&&f<=S,canceled:g.has(p.entry_id),seq:0}));for(const[p,f]of[[0,`${R(n)}.draining`],[1,R(n)]])U(f).forEach((A,h)=>a.push({nodeId:n,wake:0,source:"passive",fileRank:p,physicalIndex:h,entry:A,acknowledged:!1,canceled:!1,seq:0}))}a.sort((t,n)=>t.entry.ts.localeCompare(n.entry.ts)||t.nodeId.localeCompare(n.nodeId)||t.fileRank-n.fileRank||t.physicalIndex-n.physicalIndex),a.forEach((t,n)=>{t.seq=n+1});const r=new Map;for(const t of a){const n=`${t.nodeId}\0${t.source}`,l=r.get(n)??[];l.push(t),r.set(n,l)}for(const t of r.values()){const n=t.map(l=>l.seq).sort((l,_)=>l-_);t.sort((l,_)=>l.fileRank-_.fileRank||l.physicalIndex-_.physicalIndex).forEach((l,_)=>{l.seq=n[_]})}const d=m(e,"INSERT INTO messages (message_id, seq, operation_id, created_at, sender_node_id, sender_name, kind, label, body_ref, body_json, disposition) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"),s=m(e,"INSERT INTO deliveries (delivery_id, message_id, destination_kind, destination_id, urgency, wake, state, attempts, acknowledged_at, canceled_at, created_at, updated_at) VALUES (?, ?, 'node_inbox', ?, ?, ?, ?, 0, ?, ?, ?, ?)");for(const t of a){const n=t.entry;d.run(n.entry_id,t.seq,n.operation_id,n.ts,n.from,n.from_name??null,n.kind,n.label,n.ref??null,n.data===void 0?null:JSON.stringify(n.data),n.disposition??null);const l=Date.parse(n.ts),_=Number.isFinite(l)?l:0;s.run(u(),n.entry_id,t.nodeId,n.tier,t.wake,t.acknowledged?"acknowledged":"pending",t.acknowledged?_:null,t.canceled?_:null,_,_)}const E=m(e,"SELECT * FROM human_action_deliveries").all();for(const t of E){const n=u();d.run(n,k(e),u(),new Date(t.created_at).toISOString(),null,null,"completed",t.request_id,null,t.completion_json,null);const l=t.state==="running"?"handed_off":t.state==="accepted"?"acknowledged":t.state;m(e,"INSERT INTO deliveries (delivery_id, message_id, destination_kind, destination_id, urgency, wake, state, attempts, next_attempt_at, claimed_at, claim_owner, acknowledged_at, failed_at, last_failure_json, adapter_json, idempotency_key, created_at, updated_at) VALUES (?, ?, 'external_action', 'human_action', 'normal', 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(u(),n,l,t.attempt,t.next_attempt_at,t.claimed_at,t.claim_owner,t.accepted_at,t.permanent_failed_at,t.last_failure_json,JSON.stringify({adapter:"subprocess",argv:JSON.parse(t.argv_json),cwd:t.cwd}),`human-action:${t.request_id}`,t.created_at,t.updated_at)}const c=m(e,"SELECT * FROM node_outcome_deliveries").all();for(const t of c){const n=t.document_json===null?null:u();n!==null&&d.run(n,k(e),u(),new Date(t.created_at).toISOString(),null,null,"completed",t.node_id,null,t.document_json,null);const l=t.document_json===null?"armed":t.state==="running"?"handed_off":t.state==="accepted"?"acknowledged":t.state;m(e,"INSERT INTO deliveries (delivery_id, message_id, destination_kind, destination_id, urgency, wake, state, attempts, next_attempt_at, claimed_at, claim_owner, acknowledged_at, failed_at, last_failure_json, adapter_json, idempotency_key, created_at, updated_at) VALUES (?, ?, 'external_action', ?, 'normal', 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(u(),n,t.action_name,l,t.attempt,t.next_attempt_at,t.claimed_at,t.claim_owner,t.accepted_at,t.permanent_failed_at,t.last_failure_json,JSON.stringify({adapter:"subprocess",argv:JSON.parse(t.argv_json),cwd:t.cwd,config_origin:t.config_origin,payload:t.payload_json===null?null:JSON.parse(t.payload_json)}),`node-outcome:${t.node_id}`,t.created_at,t.updated_at)}const i=m(e,"SELECT node_id, waiting_for, waiting_for_generation FROM nodes WHERE waiting_for IS NOT NULL").all();for(const t of i)m(e,"INSERT INTO waits (wait_id, node_id, kind, target_id, generation, created_at, satisfied_at) VALUES (?, ?, 'controller', ?, ?, ?, NULL)").run(u(),t.node_id,t.waiting_for,t.waiting_for_generation,Date.now())}o(pe,"migrateMessagingState");function k(e){return Number(m(e,"SELECT COALESCE(MAX(seq), 0) AS seq FROM messages").get().seq)+1}o(k,"nextSeq");export{q as UNSEEN_WAKE_MAIL_SQL,b as WAKE_MAIL_SQL,ie as acknowledgeNodeMail,Ne as acknowledgedNodeMailCount,ae as claimKickoffMail,te as claimNodeMail,re as claimPushDelivery,D as deliveryFrom,se as duePushDeliveries,Ee as hasUnseenWakeMail,me as hasWakeMailSince,de as messageBodyForDelivery,pe as migrateMessagingState,j as normalizedSettlement,le as pushDeliveryClaimIsCurrent,_e as releaseExecutionMail,oe as resetHandedOffDeliveries,ce as resetStaleExecutionMail,ne as retryFailedDelivery,$ as settleDelivery};
98
+ `);const a=[];for(const t of m(e,"SELECT node_id FROM nodes").all()){const n=t.node_id,l=U(y(n)),_=I(`${y(n)}.cursor`)?D(`${y(n)}.cursor`,"utf8").trim():"",S=l.findIndex(p=>p.entry_id===_),g=J(`${y(n)}.canceled`);l.forEach((p,f)=>a.push({nodeId:n,wake:1,source:"inbox",fileRank:0,physicalIndex:f,entry:p,acknowledged:S>=0&&f<=S,canceled:g.has(p.entry_id),seq:0}));for(const[p,f]of[[0,`${R(n)}.draining`],[1,R(n)]])U(f).forEach((A,h)=>a.push({nodeId:n,wake:0,source:"passive",fileRank:p,physicalIndex:h,entry:A,acknowledged:!1,canceled:!1,seq:0}))}a.sort((t,n)=>t.entry.ts.localeCompare(n.entry.ts)||t.nodeId.localeCompare(n.nodeId)||t.fileRank-n.fileRank||t.physicalIndex-n.physicalIndex),a.forEach((t,n)=>{t.seq=n+1});const r=new Map;for(const t of a){const n=`${t.nodeId}\0${t.source}`,l=r.get(n)??[];l.push(t),r.set(n,l)}for(const t of r.values()){const n=t.map(l=>l.seq).sort((l,_)=>l-_);t.sort((l,_)=>l.fileRank-_.fileRank||l.physicalIndex-_.physicalIndex).forEach((l,_)=>{l.seq=n[_]})}const d=m(e,"INSERT INTO messages (message_id, seq, operation_id, created_at, sender_node_id, sender_name, kind, label, body_ref, body_json, disposition) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"),s=m(e,"INSERT INTO deliveries (delivery_id, message_id, destination_kind, destination_id, urgency, wake, state, attempts, acknowledged_at, canceled_at, created_at, updated_at) VALUES (?, ?, 'node_inbox', ?, ?, ?, ?, 0, ?, ?, ?, ?)");for(const t of a){const n=t.entry;d.run(n.entry_id,t.seq,n.operation_id,n.ts,n.from,n.from_name??null,n.kind,n.label,n.ref??null,n.data===void 0?null:JSON.stringify(n.data),n.disposition??null);const l=Date.parse(n.ts),_=Number.isFinite(l)?l:0;s.run(u(),n.entry_id,t.nodeId,n.tier,t.wake,t.acknowledged?"acknowledged":"pending",t.acknowledged?_:null,t.canceled?_:null,_,_)}const E=m(e,"SELECT * FROM human_action_deliveries").all();for(const t of E){const n=u();d.run(n,k(e),u(),new Date(t.created_at).toISOString(),null,null,"completed",t.request_id,null,t.completion_json,null);const l=t.state==="running"?"handed_off":t.state==="accepted"?"acknowledged":t.state;m(e,"INSERT INTO deliveries (delivery_id, message_id, destination_kind, destination_id, urgency, wake, state, attempts, next_attempt_at, claimed_at, claim_owner, acknowledged_at, failed_at, last_failure_json, adapter_json, idempotency_key, created_at, updated_at) VALUES (?, ?, 'external_action', 'human_action', 'normal', 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(u(),n,l,t.attempt,t.next_attempt_at,t.claimed_at,t.claim_owner,t.accepted_at,t.permanent_failed_at,t.last_failure_json,JSON.stringify({adapter:"subprocess",argv:JSON.parse(t.argv_json),cwd:t.cwd}),`human-action:${t.request_id}`,t.created_at,t.updated_at)}const c=m(e,"SELECT * FROM node_outcome_deliveries").all();for(const t of c){const n=t.document_json===null?null:u();n!==null&&d.run(n,k(e),u(),new Date(t.created_at).toISOString(),null,null,"completed",t.node_id,null,t.document_json,null);const l=t.document_json===null?"armed":t.state==="running"?"handed_off":t.state==="accepted"?"acknowledged":t.state;m(e,"INSERT INTO deliveries (delivery_id, message_id, destination_kind, destination_id, urgency, wake, state, attempts, next_attempt_at, claimed_at, claim_owner, acknowledged_at, failed_at, last_failure_json, adapter_json, idempotency_key, created_at, updated_at) VALUES (?, ?, 'external_action', ?, 'normal', 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(u(),n,t.action_name,l,t.attempt,t.next_attempt_at,t.claimed_at,t.claim_owner,t.accepted_at,t.permanent_failed_at,t.last_failure_json,JSON.stringify({adapter:"subprocess",argv:JSON.parse(t.argv_json),cwd:t.cwd,config_origin:t.config_origin,payload:t.payload_json===null?null:JSON.parse(t.payload_json)}),`node-outcome:${t.node_id}`,t.created_at,t.updated_at)}const i=m(e,"SELECT node_id, waiting_for, waiting_for_generation FROM nodes WHERE waiting_for IS NOT NULL").all();for(const t of i)m(e,"INSERT INTO waits (wait_id, node_id, kind, target_id, generation, created_at, satisfied_at) VALUES (?, ?, 'controller', ?, ?, ?, NULL)").run(u(),t.node_id,t.waiting_for,t.waiting_for_generation,Date.now())}o(pe,"migrateMessagingState");function k(e){return Number(m(e,"SELECT COALESCE(MAX(seq), 0) AS seq FROM messages").get().seq)+1}o(k,"nextSeq");export{q as UNSEEN_WAKE_MAIL_SQL,b as WAKE_MAIL_SQL,ie as acknowledgeNodeMail,Ne as acknowledgedNodeMailCount,ae as claimKickoffMail,te as claimNodeMail,re as claimPushDelivery,O as deliveryFrom,se as duePushDeliveries,Ee as hasUnseenWakeMail,me as hasWakeMailSince,de as messageBodyForDelivery,pe as migrateMessagingState,j as normalizedSettlement,le as pushDeliveryClaimIsCurrent,_e as releaseExecutionMail,oe as resetHandedOffDeliveries,ce as resetStaleExecutionMail,ne as retryFailedDelivery,$ as settleDelivery};
@@ -0,0 +1,3 @@
1
+ -- 029-model-accounts-refresh-claim.sql — `model_accounts.refresh_claimed_until`: until when one process holds the right to spend the account's refresh
2
+ -- token (NL-1135), so a refresh holds no row lock or connection across the vendor call. An added column: `schema_min_reader` is not touched.
3
+ ALTER TABLE model_accounts ADD COLUMN IF NOT EXISTS refresh_claimed_until bigint NOT NULL DEFAULT 0;
@@ -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 = 28;
4
+ export declare const CANVAS_SCHEMA_VERSION = 29;
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=28;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=29;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};
@@ -403,6 +403,7 @@ export interface NodeRow {
403
403
  created: string;
404
404
  /** Authoritative runtime columns (see NodeRuntime). */
405
405
  intent: ExitIntent;
406
+ cycle_pending?: boolean | null;
406
407
  frozen_at?: string | null;
407
408
  respawn_failures?: number;
408
409
  respawn_not_before?: string | null;
@@ -1,3 +1,3 @@
1
- var E=Object.defineProperty;var c=(t,r)=>E(t,"name",{value:r,configurable:!0});import{resolve as l}from"node:path";import{withCanvasWrite as O}from"./canvas/db.js";import{isCloudRole as p,PersonOutsideRequestError as y}from"./canvas/person-state.js";import{emitEvent as h}from"./events/emit.js";import{timedStep as v}from"./step-timings.js";import{realpathOrSelf as d}from"./fs-utils.js";import{checkoutChain as f}from"./graph/repo-sync/identity.js";import{callMachine as C}from"./runtime/runner/machine/call.js";import{machineEnvironmentOfProfile as _}from"./runtime/runner/machine/environment.js";import{MachineCallFailedError as S,MachineLostError as N,MachineOfflineError as D}from"./runtime/runner/machine/ops.js";const J={"repo.identify":c(async({dirs:t})=>{const r=performance.now(),o=await Promise.all(t.map(async e=>{const a=await f(d(l(e)));return a.every(n=>n.ok)?[e,a]:null}));return h({level:"info",event:"machine.repo_identify.timing",fields:{dirs:t.length,duration_ms:Math.round(performance.now()-r)}}),Object.fromEntries(o.filter(e=>e!==null))},"repo.identify")};async function g(t,r){const o=[...new Set(r.map(n=>l(n)))];if(o.length===0)return!0;let e;try{e=await v("repo_identify_call",()=>C(t,"repo.identify",{dirs:o}))}catch(n){if(!(n instanceof D||n instanceof N||n instanceof S))throw n;return h({level:"warn",event:"repo.identify.failed",error:n,fields:{environment:t,dirs:o.length}}),!1}const a=new Date().toISOString();return await O(async n=>{for(const s of o)e[s]!==void 0&&await n.prepare(`INSERT INTO checkout_identities (environment, dir, chain_json, observed_at) VALUES (?, ?, ?::jsonb, ?)
1
+ var E=Object.defineProperty;var c=(t,r)=>E(t,"name",{value:r,configurable:!0});import{resolve as l}from"node:path";import{withCanvasWrite as O}from"./canvas/db.js";import{isCloudRole as p,PersonOutsideRequestError as y}from"./canvas/person-state.js";import{emitEvent as h}from"./events/emit.js";import{timedStep as v}from"./step-timings.js";import{realpathOrSelf as d}from"./fs-utils.js";import{checkoutChain as f}from"./graph/repo-sync/identity.js";import{callMachine as C}from"./runtime/runner/machine/call.js";import{machineEnvironmentOfProfile as _}from"./runtime/runner/machine/environment.js";import{MachineCallFailedError as S,MachineLostError as N,MachineOfflineError as D}from"./runtime/runner/machine/ops.js";const J={"repo.identify":c(async({dirs:t})=>{const r=performance.now(),o=await Promise.all(t.map(async e=>{const a=await f(d(l(e)));return a.every(n=>n.ok)?[e,a]:null}));return h({level:"info",event:"machine.repo_identify.timing",fields:{dirs:t.length,duration_ms:Math.round(performance.now()-r)}}),Object.fromEntries(o.filter(e=>e!==null))},"repo.identify")};async function g(t,r){const o=[...new Set(r.map(n=>l(n)))].sort();if(o.length===0)return!0;let e;try{e=await v("repo_identify_call",()=>C(t,"repo.identify",{dirs:o}))}catch(n){if(!(n instanceof D||n instanceof N||n instanceof S))throw n;return h({level:"warn",event:"repo.identify.failed",error:n,fields:{environment:t,dirs:o.length}}),!1}const a=new Date().toISOString();return await O(async n=>{for(const s of o)e[s]!==void 0&&await n.prepare(`INSERT INTO checkout_identities (environment, dir, chain_json, observed_at) VALUES (?, ?, ?::jsonb, ?)
2
2
  ON CONFLICT (environment, dir) DO UPDATE SET chain_json = EXCLUDED.chain_json, observed_at = EXCLUDED.observed_at`).run(t,s,JSON.stringify(e[s]),a)}),!0}c(g,"warmMachineCheckouts");function k(t){const r=typeof t=="string"?JSON.parse(t):t;return Array.isArray(r)?r:[]}c(k,"chainOf");async function q(t,r,o){const e=l(r);return(await M(t,[e],o)).get(e)}c(q,"checkoutChainOf");async function M(t,r,o){const e=new Map,a=[...new Set(r)];if(!p()){for(const i of a)e.set(i,await f(i));return e}let n;try{n=await o()}catch(i){if(!(i instanceof y))throw i;for(const m of a)e.set(m,await f(m));return e}const s=n.replace(/^user:/,""),w=a.length===0?[]:await t.prepare(`SELECT DISTINCT ON (c.dir) c.dir, c.chain_json FROM checkout_identities c JOIN profiles p ON p.environment_id = c.environment
3
3
  WHERE p.person IN (?, ?) AND c.dir = ANY(?::text[]) ORDER BY c.dir, c.observed_at DESC`).all(s,`user:${s}`,a),u=new Map(w.map(i=>[i.dir,i.chain_json]));for(const i of a)e.set(i,u.has(i)?k(u.get(i)):await f(i));return e}c(M,"checkoutChainsOf");async function H(t,r){const o=p()&&t!=null?await _(t):null;if(o!==null){await g(o,r);return}for(const e of r)await f(d(l(e)))}c(H,"warmCheckoutDirs");export{q as checkoutChainOf,M as checkoutChainsOf,J as machineCheckoutHandlers,H as warmCheckoutDirs,g as warmMachineCheckouts};
@@ -11,5 +11,5 @@ var J=Object.defineProperty;var f=(i,e)=>J(i,"name",{value:e,configurable:!0});i
11
11
  `);_.pop();const l=Math.max(0,o-s.tail),w=(await O(n,l>0?l-1:0,o)).toString("utf8").split(`
12
12
  `);return l>0&&w.shift(),{header:t,entries:c(_.join(`
13
13
  `)),tail:c(w.join(`
14
- `)),path:r}},async header(e){const s=await E(),{header:a,path:t}=await L(e,s),r=await H(s,e);return{header:a,path:t,mtime:Date.parse(r.tail.at(-1)?.created??r.parts.at(-1).created),size:r.parts.reduce((n,o)=>n+o.bytes,0)+r.tail.reduce((n,o)=>n+o.bytes,0)}},async list(e){const a=await(await E()).prepare(`SELECT DISTINCT ON (s.session_id) s.session_id, s.node_id FROM sessions s JOIN conversation_parts p ON p.conversation_id = s.session_id WHERE s.session_id IS NOT NULL ORDER BY s.session_id, ${S}`).all(),t=[];for(const r of a){if(e&&r.node_id!==e)continue;const n=await i.header(r.session_id);t.push({conversation_id:r.session_id,node_id:r.node_id,...n})}return t.sort((r,n)=>n.mtime-r.mtime)},async replace(e,s,a){if(s.id!==e)throw new Error("replacement header id differs from conversation id");const t=await E(),r=await m(t,e);if(r.run_id)throw new Error(`run conversation ${e} is append-only; replace refused`);const n=`conversations/${r.node_id}/${e}/0-${v()}.jsonl`,o=F([s,...a]);await(await y()).put(n,o);const c=await b(async d=>{if((await m(d,e,!0)).run_id)throw new Error(`run conversation ${e} is append-only; replace refused`);const l=await h(d,e);return await d.prepare("DELETE FROM conversation_parts WHERE conversation_id = ?").run(e),await d.prepare("DELETE FROM conversation_entries WHERE conversation_id = ?").run(e),await d.prepare("INSERT INTO conversation_parts (conversation_id, seq, blob_key, bytes, entries, created) VALUES (?, 0, ?, ?, ?, ?)").run(e,n,Buffer.byteLength(o),a.length,N()),l});for(const d of c)await(await y()).delete(d.blob_key)},async fork(e,s,a,t){const r=await i.read(e);let n=r.entries;if(a!==void 0){const o=G.inMemory(r.header.cwd,void 0,[r.header,...n]);o.createBranchedSession(a),n=o.getEntries()}return(await i.create(s??(await L(e,await E())).binding?.node_id??k.get(e).node,{...r.header,id:v(),timestamp:N(),cwd:t??r.header.cwd,parentSession:r.path},n)).conversation_id},async delete(e,s){const a=await E(),t=await h(a,e);await b(async r=>{await r.prepare("DELETE FROM conversation_entries WHERE conversation_id = ?").run(e),await r.prepare("DELETE FROM conversation_parts WHERE conversation_id = ?").run(e),await r.prepare("DELETE FROM sessions WHERE session_id = ?").run(e)});for(const r of t)await(await y()).delete(r.blob_key);s&&Y(s,{force:!0})},async commit(e){return await b(async s=>{const a=await m(s,e,!0),t=await $(s,e),r=await h(s,e);if(!t.length)return r.at(-1)?.seq??0;const n=(r.at(-1)?.seq??0)+1,o=C(a.node_id,e,n),c=t.map(d=>d.body+`
14
+ `)),path:r}},async header(e){const s=await E(),{header:a,path:t}=await L(e,s),r=await H(s,e);return{header:a,path:t,mtime:Date.parse(r.tail.at(-1)?.created??r.parts.at(-1).created),size:r.parts.reduce((n,o)=>n+o.bytes,0)+r.tail.reduce((n,o)=>n+o.bytes,0)}},async list(e){const a=await(await E()).prepare(`SELECT DISTINCT ON (s.session_id) s.session_id, s.node_id FROM sessions s JOIN conversation_parts p ON p.conversation_id = s.session_id WHERE s.session_id IS NOT NULL ORDER BY s.session_id, ${S}`).all(),t=[];for(const r of a){if(e&&r.node_id!==e)continue;const n=await i.header(r.session_id);t.push({conversation_id:r.session_id,node_id:r.node_id,...n})}return t.sort((r,n)=>n.mtime-r.mtime)},async replace(e,s,a){if(s.id!==e)throw new Error("replacement header id differs from conversation id");const t=await E(),r=await m(t,e);if(r.run_id)throw new Error(`run conversation ${e} is append-only; replace refused`);const n=`conversations/${r.node_id}/${e}/0-${v()}.jsonl`,o=F([s,...a]);await(await y()).put(n,o);const c=await b(async d=>{if((await m(d,e,!0)).run_id)throw new Error(`run conversation ${e} is append-only; replace refused`);const l=await h(d,e);return await d.prepare("DELETE FROM conversation_parts WHERE conversation_id = ?").run(e),await d.prepare("DELETE FROM conversation_entries WHERE conversation_id = ?").run(e),await d.prepare("INSERT INTO conversation_parts (conversation_id, seq, blob_key, bytes, entries, created) VALUES (?, 0, ?, ?, ?, ?)").run(e,n,Buffer.byteLength(o),a.length,N()),l});for(const d of c)await(await y()).delete(d.blob_key)},async fork(e,s,a,t){const r=await i.read(e);let n=r.entries;if(a!==void 0){const o=G.inMemory(r.header.cwd,void 0,[r.header,...n]);o.createBranchedSession(a),n=o.getEntries()}return(await i.create(s??(await L(e,await E())).binding?.node_id??k.get(e).node,{...r.header,id:v(),timestamp:N(),cwd:t??r.header.cwd,parentSession:r.path},n)).conversation_id},async delete(e,s){const a=await E(),t=await h(a,e);await b(async r=>{await r.prepare("DELETE FROM sessions WHERE session_id = ?").run(e),await r.prepare("DELETE FROM conversation_entries WHERE conversation_id = ?").run(e),await r.prepare("DELETE FROM conversation_parts WHERE conversation_id = ?").run(e)});for(const r of t)await(await y()).delete(r.blob_key);s&&Y(s,{force:!0})},async commit(e){return await b(async s=>{const a=await m(s,e,!0),t=await $(s,e),r=await h(s,e);if(!t.length)return r.at(-1)?.seq??0;const n=(r.at(-1)?.seq??0)+1,o=C(a.node_id,e,n),c=t.map(d=>d.body+`
15
15
  `).join("");return await(await y()).put(o,c),process.env.CRTR_FAULT_CONVERSATION==="commit_exit_after_put"&&process.exit(1),await s.prepare("INSERT INTO conversation_parts (conversation_id, seq, blob_key, bytes, entries, created) VALUES (?, ?, ?, ?, ?, ?)").run(e,n,o,Buffer.byteLength(c),t.length,N()),await s.prepare("DELETE FROM conversation_entries WHERE conversation_id = ? AND seq <= ?").run(e,t.at(-1).seq),n})},async importLegacy(e){const a=await(await E()).prepare(`SELECT DISTINCT ON (s.session_id) s.session_id, s.node_id, s.transcript_path FROM sessions s JOIN nodes n ON n.node_id = s.node_id WHERE s.session_id IS NOT NULL AND s.transcript_path IS NOT NULL ${e?"AND n.run_id = ?":""} ORDER BY s.session_id, ${S}`).all(...e?[e]:[]);for(const t of a)await j(t.session_id,t.node_id,t.transcript_path)},recover(e){for(const s of e)s.transcript_path&&k.set(s.session_id,{node:s.node_id,path:s.transcript_path})}};return i}f(_e,"createRowStore");function Z(i,e,s){const a=i.indexOf(10);if(a<0)throw new Error(`invalid conversation header: ${e}`);const t=JSON.parse(i.subarray(0,a).toString("utf8"));if(t.type!=="session"||t.id!==e)throw new Error(`invalid conversation header: ${e}`);const r=s(t.cwd);return r===t.cwd?null:Buffer.concat([Buffer.from(JSON.stringify({...t,cwd:r})),i.subarray(a)])}f(Z,"withHeaderCwd");async function ue(i,e,s){const a=await E(),t=await m(a,i),r=(await h(a,i))[0];if(!r||r.seq!==0)return!1;const n=await(await y()).get(r.blob_key);if(!n)throw new Error(`missing conversation object: ${r.blob_key}`);const o=Z(n,i,_=>_===e?s:_);if(o===null)return!1;const c=`conversations/${t.node_id}/${i}/0-${v()}.jsonl`;await(await y()).put(c,o);const d=await b(async _=>await _.prepare("UPDATE conversation_parts SET blob_key = ?, bytes = ?, cycle_offset = CASE WHEN cycle_offset > 0 THEN cycle_offset + ? - bytes ELSE cycle_offset END WHERE conversation_id = ? AND seq = 0 AND blob_key = ? RETURNING seq").get(c,o.length,o.length,i,r.blob_key)!==void 0);if(await(await y()).delete(d?r.blob_key:c).catch(()=>{}),!d)throw new Error(`conversation header changed during relocation: ${i}`);return!0}f(ue,"relocateConversationHeader");export{_e as createRowStore,q as readAhead,ue as relocateConversationHeader,Z as withHeaderCwd};
@@ -64,6 +64,9 @@ export interface DocumentRead {
64
64
  export declare function actorOf(reader: Reader): ObjectRow;
65
65
  /** Head revisions (no child), highest number first. More than one means the document needs a merge. */
66
66
  export declare function heads(db: CanvasDb, doc: ObjectRow): Promise<Revision[]>;
67
+ export declare function headsKeyOf(revs: ReadonlyArray<{
68
+ rev_id: string;
69
+ }>): string;
67
70
  export declare function documentRecord(db: CanvasDb, doc: ObjectRow): Promise<DocumentRecord>;
68
71
  /** The `[[name]]` links a body names, in order, each once. */
69
72
  export declare function linksIn(body: string): string[];
@@ -115,12 +118,9 @@ export declare function editDocument(db: CanvasDb, reader: Reader, doc: ObjectRo
115
118
  * `acting_app`, `acting_for`) with the rationale. It descends from the highest head only, so a document that needs a merge still does. A caller
116
119
  * that held the heads before keeps holding them; one that had not read the body does not gain a read base it never earned. */
117
120
  export declare function setDocumentRecord(db: CanvasDb, reader: Reader | null, doc: ObjectRow, fields: DocumentFields, rationale?: string): Promise<ObjectRow>;
118
- /** Record that the reader holds the document's current heads: a `read` watch with that read
119
- * base, and a `read` push. Delivery's content load calls this without reading the body. */
120
- export declare function recordRead(db: CanvasDb, reader: Reader, doc: ObjectRow, reposFn?: ReposFn): Promise<void>;
121
121
  /** The document's record, each head with its body (several = needs merge) and its links under
122
- * their current names; records the read. */
123
- export declare function readDocument(db: CanvasDb, reader: Reader, doc: ObjectRow, reposFn?: ReposFn): Promise<DocumentRead>;
122
+ * their current names. Records nothing. */
123
+ export declare function readDocument(db: CanvasDb, reader: Reader, doc: ObjectRow): Promise<DocumentRead>;
124
124
  /** Every revision, newest first, with authors, rationales and parents. Records nothing. */
125
125
  export declare function history(db: CanvasDb, reader: Reader, doc: ObjectRow): Promise<Revision[]>;
126
126
  /** Rename and/or re-own a document. Only `objects` changes: links point at the id, so no body is