@north-light/cli 0.3.790 → 0.3.791
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.
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/nodes.d.ts +0 -12
- package/dist/builtin-pi-packages/pi-crtr-extensions/extensions/memory-slash-commands.ts +3 -2
- package/dist/clients/attach/viewer.js +526 -526
- package/dist/commands/node/bash.js +1 -1
- package/dist/commands/node/inspect.js +6 -6
- package/dist/commands/node/lifecycle.js +4 -4
- package/dist/commands/node-context.js +2 -2
- package/dist/core/canvas/node-agent-paths.d.ts +5 -0
- package/dist/core/canvas/node-agent-paths.js +1 -1
- package/dist/core/canvas/paths.d.ts +3 -10
- package/dist/core/canvas/paths.js +1 -1
- package/dist/core/canvas/render-source.js +1 -1
- package/dist/core/providers/files.js +1 -1
- package/dist/core/runtime/bearings-render.d.ts +2 -2
- package/dist/core/runtime/bearings-render.js +11 -11
- package/dist/core/runtime/bearings.js +1 -1
- package/dist/core/runtime/broker/attachments-fetch.js +1 -1
- package/dist/core/runtime/broker/bash-job-launch.d.ts +0 -4
- package/dist/core/runtime/broker/bash-job-launch.js +1 -1
- package/dist/core/runtime/broker/daemon-ops.d.ts +0 -8
- package/dist/core/runtime/broker/daemon-ops.js +1 -1
- package/dist/core/runtime/broker/frame-dispatch.d.ts +1 -1
- package/dist/core/runtime/broker/frame-dispatch.js +1 -1
- package/dist/core/runtime/broker/host-path-tokens.d.ts +5 -0
- package/dist/core/runtime/broker/host-path-tokens.js +1 -0
- package/dist/core/runtime/broker-extension-render.js +2 -2
- package/dist/core/runtime/broker.js +1 -1
- package/dist/core/runtime/host.js +3 -3
- package/dist/core/runtime/kickoff.d.ts +1 -1
- package/dist/core/runtime/kickoff.js +12 -12
- package/dist/core/runtime/nodes.js +1 -1
- package/dist/core/runtime/revive.js +2 -2
- package/dist/core/runtime/runner/blaxel/runner.js +2 -2
- package/dist/core/runtime/runner/launch-env.d.ts +7 -0
- package/dist/core/runtime/runner/launch-env.js +1 -0
- package/dist/core/runtime/runner/machine/executor.js +2 -2
- package/dist/core/runtime/runner/types.d.ts +1 -0
- package/dist/core/runtime/spawn.js +2 -2
- package/dist/core/storage/attachments.d.ts +1 -1
- package/dist/core/storage/attachments.js +1 -1
- package/dist/core/storage/tables.d.ts +6 -2
- package/dist/core/storage/tables.js +4 -4
- package/dist/core/substrate/delivery/deliver.js +1 -1
- package/dist/core/substrate/delivery/render-boot.js +1 -1
- package/dist/daemon/api/handlers/bash-jobs.js +3 -3
- package/dist/daemon/api/handlers/nodes.js +1 -1
- package/dist/daemon/api/map.d.ts +1 -4
- package/dist/daemon/api/map.js +2 -2
- package/dist/daemon/cron/machine-fire.js +1 -1
- package/dist/daemon/reconcilers/bash-deadline.js +1 -1
- package/dist/pi-extensions/canvas-bash-valve.js +6 -6
- package/dist/pi-extensions/canvas-context-intro.js +2 -2
- package/dist/pi-extensions/canvas-inbox-watcher.js +2 -2
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/core/canvas/paths.js +4 -13
- package/packages/crouter-api/dist/core/runtime/broker/attachments-fetch.js +18 -2
- package/packages/crouter-api/dist/core/runtime/broker/daemon-ops.js +0 -10
- package/packages/crouter-api/dist/core/runtime/broker/host-path-tokens.js +21 -0
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
- package/scripts/sandbox-start.mjs +5 -3
|
@@ -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(),{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=[
|
|
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=[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
|
-
var A=Object.defineProperty;var h=(n,e)=>A(n,"name",{value:e,configurable:!0});import{defineBranch as
|
|
2
|
-
`),"leaf")},run:h(async n=>{const e=h(c=>{const b=n[c];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"),
|
|
3
|
-
`)};return(i.runner==="blaxel"||i.profile_id!==null&&await
|
|
4
|
-
`));const d=h((
|
|
5
|
-
`);return`${g.length} ${
|
|
1
|
+
var A=Object.defineProperty;var h=(n,e)=>A(n,"name",{value:e,configurable:!0});import{contextDir as P}from"../../core/canvas/paths.js";import{defineBranch as I,defineLeaf as $}from"../../core/command.js";import{InputError as k}from"../../core/io.js";import{requireScope as L}from"../../core/errors.js";import{isPidAlive as F}from"../../core/canvas/pid.js";import{fullName as x}from"../../core/canvas/labels.js";import{fuzzyMatch as O}from"../../core/tui/fuzzy.js";import{nodeSnapshotLeaf as C}from"../node-snapshot.js";import{nodeTranscriptLeaf as U}from"../node-transcript.js";import{nodeContextLeaf as D}from"../node-context.js";import{ApiError as E}from"../../api/index.js";import{describeVendorLimit as z}from"../../core/provider-failure.js";import{cliClient as _,cliCanvasSource as S,rethrowAsCliError as w}from"../api-client.js";import{RemoteCanvasSource as q}from"../../core/canvas/remote-canvas-source.js";import{kindsStateBlock as M,profilesStateBlock as B,resolveProfileViaDaemon as V}from"../profile/daemon-profiles.js";import{focusViewer as W,nodeInPane as K}from"../surface/node/placement.js";const G=$({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. Against the default account 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 default account 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([M(),B()])).join(`
|
|
2
|
+
`),"leaf")},run:h(async n=>{const e=h(c=>{const b=n[c];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,r=n.name,l=n.cwd,a=n.under,u=S({canvasName:n.canvas}),d=u instanceof q?m:m===void 0?void 0:(await V(m)).id,f=a!==void 0&&a!=="";if(f&&await u.getNode(a).catch(w)===null)throw new k({error:"not_found",message:`no node: ${a}`,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:a}:{}}).catch(w)).filter(c=>!(s!==void 0&&!s.includes(c.kind)||p!==void 0&&!p.includes(c.mode)||i!==void 0&&!i.includes(c.lifecycle)||d!==void 0&&c.profile_id!==d||l!==void 0&&l!==""&&c.cwd!==l)).map(c=>({...c,name:x(c)})).filter(c=>r===void 0||r===""||O(r,c.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?x(o):"(missing)",kind:o?.kind??"?",status:o?o.intent?`${o.status}/${o.intent}`:o.status:"?",active:e.active}}h(N,"enrichNeighbor");const H=$({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 default account 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=_(),r=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))),a=(await m.listCrons({created_by:e}).catch(w)).filter(t=>t.created_by===e).length,u={context_dir:P(e,i.grantee),...i.pi_session_file!==void 0?{session_file:i.pi_session_file}:{}},d=[];d.push(`List the documents it owns (reports, plans, notes): \`crtr canvas list --owner ${e}\`.`),d.push(`Browse its context dir (and its subscriptions') in nvim: \`crtr node inspect context ${e}\`.`),u.session_file&&d.push(`Read the raw conversation transcript: ${u.session_file}`),d.push(`On-disk context dir (ls/read directly): ${u.context_dir}`),a>0&&d.push(`It created ${a} pending cron(s): \`crtr cron list\`.`),r.length>0&&d.push(`Drill into a child/report: \`crtr node inspect show <node_id>\` (${r.map(t=>t.node_id).join(", ")}).`),d.push(`Full machine dump (system prompt + all telemetry): \`crtr --json node inspect show ${e}\`.`);const f={node:i,fault:i.fault??null,reports:r,managers:l,pending_crons:a,paths:u,follow_up:d.join(`
|
|
3
|
+
`)};return(i.runner==="blaxel"||i.profile_id!==null&&await m.getProfileEnvironment(i.profile_id).then(()=>!0,t=>t instanceof E&&(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)":F(s)?"alive":"dead",m=e.intent?`/${String(e.intent)}`:"",r=n.fault,l=[];l.push(`# ${x(e)} (${o})`);const a=[`- kind/mode/lifecycle: ${e.kind} / ${e.mode} / ${e.lifecycle}`,`- status: ${e.status}${m}`,...r==null?[]:[`- fault: ${String(r.kind)} / ${String(r.retry?.disposition)} since ${String(r.since)}${r.retry?.nextAt===void 0?"":`. Next router probe: ${r.retry.nextAt}.`}${z(r.providerError)}`],`- 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&&a.push(`- machine: ${u.name??u.id}`),e.parent&&a.push(`- parent: ${e.parent}`),a.push(`- creator: ${e.creator??"an external process"}`),e.waiting_for&&a.push(`- waiting for message: ${e.waiting_for}`),l.push(a.join(`
|
|
4
|
+
`));const d=h((f,g)=>{if(g.length===0)return`${f}: none`;const t=["node_id","name","kind","status","active"],y=`| ${t.join(" | ")} |`,c=`| ${t.map(()=>"---").join(" | ")} |`,b=g.map(v=>`| ${t.map(R=>String(v[R]??"").replace(/\|/g,"\\|").replace(/\n/g," ")).join(" | ")} |`).join(`
|
|
5
|
+
`);return`${g.length} ${f}:
|
|
6
6
|
|
|
7
7
|
${y}
|
|
8
8
|
${c}
|
|
9
9
|
${b}`},"table");return l.push(d("reports (down \u2014 subscriptions, usually children)",n.reports)),l.push(d("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")}),
|
|
12
|
+
`)},"render")}),pe=$({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=>{L("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=K(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 _().forkNode(s).catch(w),i=await W(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")}),he=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:[G,H,C,U,D]});export{pe as nodeFork,he as nodeInspect};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
2
|
-
`)},"render")}),ne=E({name:"close",description:"close a node + cascade-cancel its exclusive subtree",whenToUse:"you want to tear a node down WITHOUT finishing it, cascade-cancelling every descendant it exclusively owns: abandoning a line of work, killing a stuck or wrong-turn subtree, clearing a branch you no longer need. A node that never produced substantive assistant output is deleted and cannot be revived; streaming nodes and nodes with an open managed worktree are retained. Other closed nodes keep their pi session and can be revived later (`node lifecycle revive`). Use `node lifecycle recycle` instead to FINISH the agent in your pane with a final report, and `push final` when a worker should end its own work normally (Alt+C \u2192 x)",help:{name:"node lifecycle close",summary:"close a node and cascade-cancel its subtree \u2014 kill its tmux window plus those of every descendant it EXCLUSIVELY owns (down the subscription spine \u2014 the watches each manager holds on its children), mark retained nodes canceled, and leave them a notice they read on resume. A descendant still subscribed to by a manager outside the subtree is left running. A node that never produced substantive assistant output is deleted and cannot be revived; streaming nodes and nodes with an open managed worktree are retained. Other closed nodes keep their pi session and can be revived later (`crtr node lifecycle revive`)",params:[{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node to close. Defaults to the node occupying --pane (or your current pane)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane id whose node to close. Defaults to $TMUX_PANE / your current pane. The Alt+C menu passes this for you."}],output:[{name:"node_id",type:"string",required:!1,constraint:"The node that was closed \u2014 the cascade root."},{name:"count",type:"number",required:!1,constraint:"How many nodes were closed (root + cascaded descendants)."},{name:"closed_ids",type:"string[]",required:!1,constraint:"All closed node ids, kill order (leaves first, root last)."},{name:"spared",type:"string[]",required:!1,constraint:"Descendants left alive because a manager outside the subtree still subscribes to them."}],outputKind:"object",effects:["Marks retained nodes and their exclusive descendants `canceled` and clears intent (the daemon never revives a canceled node).","Deletes a non-streaming node with no substantive assistant output unless it has an open managed worktree; a deleted node cannot be revived.","Kills each closed node's tmux window; retained nodes keep their pi sessions and canvas edges for a later revive.","Appends a cancellation notice to each retained node's inbox, surfaced on its next resume."]},run:u(async e=>{const t=e.pane??process.env.TMUX_PANE;let n=e.node;if((n===void 0||n==="")&&(n=I(t)),n===void 0||n==="")throw new r({error:"no_node",message:"no node found in this pane to close",next:"Pass --node <id>, or run from inside the agent's pane."});const i=await w().closeNode(n,process.ppid>0?{caller_pid:process.ppid}:{}).catch(d=>y(d,"List nodes with `crtr node inspect list`."));return{node_id:i.root,count:i.closed.length,closed_ids:i.closed,spared:i.spared}},"run"),render:u(e=>{const t=e.spared?.length??0;return`Closed ${e.node_id} and its exclusive subtree \u2014 ${e.count} node(s) closed${t>0?`, ${t} spared (still managed from outside the subtree)`:""}.`},"render")}),j="Model change first: a running broker, including one still starting right after `node new`, switches over its socket; a dormant node persists the durable model override and launch recipe for its next revive.",pe=E({name:"config",description:"reconfigure a node's settings headlessly \u2014 model, lifecycle (terminal/resident), kind, mode, name; repair a missing cwd",whenToUse:"you want to reconfigure a node's settings headlessly after spawn \u2014 swap its model/provider, flip it terminal\u2194resident (interactable), respecialize its kind, switch base\u2194orchestrator mode, or rename it \u2014 without opening its viewer. It also repairs a dormant node whose recorded cwd is gone, starting its next revive in a fresh conversation. The durable attribute setter; reuses the same recipes a revive reads. Use `node promote` for the opinionated self-promotion path, and `node lifecycle` for teardown actions (recycle/close/demote).",help:{name:"node config",summary:"reconfigure a node's settings headlessly \u2014 model, lifecycle, kind, mode, name; repair a missing cwd",params:[{kind:"flag",name:"node",type:"string",required:!1,repeatable:!0,constraint:"Target node id. Defaults to the node in --pane, else CRTR_NODE_ID. Repeat it, or use --nodes-from, to apply a --profile or --cwd change to many nodes; a bulk run reports each node and keeps going past a failure."},{kind:"flag",name:"nodes-from",type:"string",required:!1,constraint:"File of node ids, one per line (blank lines and #-comments ignored), or `-` for stdin. Bulk form of --node; only with --profile or --cwd."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane id to resolve the node from. Defaults to $TMUX_PANE."},{kind:"flag",name:"model",type:"string",required:!1,constraint:"Durable model change. Omit unless the task or governing guidance requires a different model.",focusedHelp:{whenToUse:"Use only when intentionally changing this node\u2019s durable model because the user, task, or governing agent guidance requires a specific provider, model, capability tier, or family. Omit it to keep the current model; do not use it merely to inspect available models or experiment with a live node.",value:`Accepted durable forms: ${J}. A live broker also accepts a free-text substring matched against its loaded model registry; a dormant node cannot resolve a substring and requires a durable form.`,effects:[j,"A concrete provider/id runs exactly that model on every launch and revive. A portable provider/tier, bare tier, or family alias keeps its tier: when that model's provider is rate-limited or rejects its credential, the node moves to the next model in its route: another provider's model at the same tier first, then the configured fallback tier (strong by default)."]}},{kind:"flag",name:"lifecycle",type:"enum",choices:["terminal","resident"],required:!1,constraint:"Set lifecycle headlessly without closing the viewer. terminal owes a final and reaps when done; resident stays interactable while attached or awaiting something live."},{kind:"flag",name:"kind",type:"string",required:!1,constraint:"Persona kind. The <kinds> list below names every top-level installable kind and when to use each; a registered sub-kind is valid too by exact path but not listed here."},{kind:"flag",name:"mode",type:"enum",choices:["base","orchestrator"],required:!1,constraint:"Set persona mode headlessly. base is hands-on; orchestrator holds a roadmap and delegates. orchestrator creates your document `roadmap` if absent."},{kind:"flag",name:"name",type:"string",required:!1,constraint:"Rename the node; if the node has a live window, also rename that viewer window."},{kind:"flag",name:"nice",type:"int",required:!1,constraint:`Scheduler niceness every command this node's bash tool starts at, 0\u2013${N} (default ${F}). ${F} keeps the node's builds and test suites below the daemon, the brokers, the viewers, and the person's own shell; 0 lets them compete on equal terms with everything else on the host; ${N} makes them yield to it. Applies to the node's very next command, foreground and background alike.`},{kind:"flag",name:"listen",type:"string",required:!1,constraint:`The node's default listening configuration, as JSON mapping an event level ("1".."10") to how events at or above it reach the node: interrupt, steer, after-turn, or next-turn (e.g. '{"3":"next-turn"}' \u2014 events of level 3+ wait for its next turn and never wake it). Applies to every watch with no configuration of its own. Pass \`null\` to reset to the global default.`},{kind:"flag",name:"cwd",type:"string",required:!1,constraint:"Replacement launch directory (absolute, existing). Alone, or with --keep-session / --restart. Without --keep-session it is a repair: only a dormant, non-forked node with no open managed worktree whose recorded cwd is gone, and it clears the saved Pi session (next revive starts fresh). When the new path is the same directory as the recorded one (a symlink alias) it relocates and keeps the conversation automatically \u2014 see --keep-session."},{kind:"flag",name:"keep-session",type:"bool",required:!1,constraint:"With --cwd: assert the new path is the SAME directory as the recorded cwd and relocate WITHOUT clearing the Pi session. Needed only when the recorded path is already gone (e.g. the symlink was deleted); while it still exists the daemon verifies by realpath and refuses a different directory. Allowed for live, idle, dormant and finished nodes, forks included. Rewrites the recorded cwd and the cwd in the node's transcript header so a later resume finds it. Refused while the node owns an open managed worktree."},{kind:"flag",name:"rewrite-prefix",type:"string",required:!1,constraint:'Bulk cwd form, `OLD=NEW` (absolute paths): with several nodes, each node\'s recorded cwd that equals OLD or lies beneath it is relocated to the same place under NEW, keeping its session (as --keep-session); nodes whose cwd is elsewhere are reported as failed "not under OLD". Use instead of --cwd when the nodes sit in different subdirectories.'},{kind:"flag",name:"profile",type:"string",required:!1,constraint:"Reassign the node to this profile (id or exact name; must be an active profile of the node's app that defines the node's kind). Works for live, idle, dormant, finished and profile-less (detached) nodes. Used alone, or with --restart."},{kind:"flag",name:"restart",type:"bool",required:!1,constraint:"With --profile, or --cwd on a live node: after the change, SIGTERM the node's live broker so crtrd resumes it from the same transcript (continuing an interrupted turn) with the new profile/cwd. No effect on a node with no live broker."}],output:[{name:"node_id",type:"string",required:!1,constraint:"The reconfigured node, present for ordinary config changes."},{name:"model",type:"string",required:!1,constraint:"The resolved model, present only when --model changed it."},{name:"lifecycle",type:"string",required:!1,constraint:"The new lifecycle, present only when --lifecycle changed it."},{name:"kind",type:"string",required:!1,constraint:"The new kind, present only when --kind changed it."},{name:"mode",type:"string",required:!1,constraint:"The new mode, present only when --mode changed it."},{name:"name",type:"string",required:!1,constraint:"The new name, present only when --name changed it."},{name:"nice",type:"number",required:!1,constraint:"The new bash niceness, present only when --nice changed it."},{name:"listen",type:"object",required:!1,constraint:"The new default listening configuration (null = global default), present only when --listen changed it."},{name:"cwd",type:"string",required:!1,constraint:"The resolved replacement directory, present only after a cwd change."},{name:"session_kept",type:"boolean",required:!1,constraint:"With a cwd change: true when the node still has its Pi session bound (conversation preserved)."},{name:"profile",type:"string",required:!1,constraint:"The node's profile id after --profile."},{name:"bulk",type:"boolean",required:!1,constraint:"True for a multi-node run."},{name:"applied",type:"number",required:!1,constraint:"Bulk: nodes changed (or already in the requested state)."},{name:"failed",type:"number",required:!1,constraint:"Bulk: nodes that errored; the exit code is 1 when any did."},{name:"results",type:"array",required:!1,constraint:"Bulk: one {node_id, ok, error?} per node, in input order."}],outputKind:"object",effects:[j,"Kind, mode, and lifecycle changes rebuild the launch spec from the fresh node meta; setting mode to orchestrator creates your document `roadmap` if absent.","Name changes update the row and, when the node already has a live window, rename that viewer window to the new full name.","A cwd repair (gone recorded cwd, no --keep-session) writes only the lexically resolved cwd and clears saved Pi session pointers; the old transcript and durable node work remain untouched.","A session-keeping cwd relocation (--keep-session, or --cwd naming a symlink alias of the recorded directory) rewrites the recorded cwd and the cwd line in the header of each of the node's transcripts; the Pi session stays bound and the next revive resumes the same conversation. A LIVE broker keeps the old cwd string in its environment and tools until it restarts: it keeps working while the old path exists, so pass --restart (or revive it) BEFORE deleting an old symlink.","A profile reassignment rewrites the node's profile and rebuilds its launch recipe. Profile env, documents delivered at boot, purview and bearings are read at launch, so a LIVE broker keeps the old profile until it next restarts; --restart bounces it now. Dormant or finished nodes simply carry the new profile into their next revive. The node's deadlines and profile pause follow the new profile immediately.","A niceness change is stored with the node's own bash-job state, so it takes effect on the next command without a revive and survives one.","A listen change sets the node's default listening configuration; it never changes which watches it holds.","Every successful change publishes a `configured` event on the node (level 1) naming the changed settings, so its watchers can see it."]},helpState:{leaf:C},run:u(async e=>{const t=e.pane??process.env.TMUX_PANE,n=e.node,i=Array.isArray(n)?n:n===void 0?[]:[n],d=e.nodesFrom;if(d!==void 0){const a=d==="-"?W(0,"utf8"):W(d,"utf8");for(const A of a.split(`
|
|
3
|
-
`)){const b=A.replace(/#.*/,"").trim();b!==""&&i.push(b)}}const o=e.profile,h=e.cwd,f=e.rewritePrefix;if(i.length>1||d!==void 0||f!==void 0){if(i.length===0)throw new r({error:"no_nodes",message:"bulk config needs at least one node",next:"Pass --node ID (repeatable) or --nodes-from FILE|-."});if(o===void 0&&h===void 0&&f===void 0)throw new r({error:"bulk_unsupported",message:"several nodes are accepted only with --profile, --cwd or --rewrite-prefix",next:"Pass --profile <profile>, --cwd <dir> or --rewrite-prefix OLD=NEW with the node list."});let a;if(f!==void 0){const p=f.indexOf("="),c=p<0?"":f.slice(0,p).replace(/\/+$/,""),m=p<0?"":f.slice(p+1).replace(/\/+$/,"");if(!c.startsWith("/")||!m.startsWith("/"))throw new r({error:"bad_rewrite_prefix",message:`--rewrite-prefix must be OLD=NEW with absolute paths: ${f}`,field:"rewrite-prefix",next:"Pass e.g. --rewrite-prefix /Users/me/Code/northlight=/Users/me/Code/northlight-systems."});a=[c,m]}const A=w(),b=[];for(const p of[...new Set(i)])try{const c=o!==void 0?{profile:o}:{cwd:h??""};if(a!==void 0){const m=(await A.getNode(p)).cwd;if(m!==a[0]&&!m.startsWith(`${a[0]}/`))throw new Error(`cwd ${m} is not under ${a[0]}`);c.cwd=a[1]+m.slice(a[0].length),c.keep_session=!0}e.keepSession===!0&&(c.keep_session=!0),e.restart===!0&&(c.restart=!0),await A.patchConfig(p,c),b.push({node_id:p,ok:!0})}catch(c){let m=c instanceof Error?c.message:String(c);try{y(c)}catch(U){U instanceof Error&&(m=U.message)}b.push({node_id:p,ok:!1,error:m})}const P=b.filter(p=>!p.ok).length;return P>0&&(process.exitCode=1),{bulk:!0,applied:b.length-P,failed:P,results:b}}const _=await M({...e,node:i[0]},t),x=h;if(x!==void 0&&["model","kind","lifecycle","mode","name","nice","listen","profile"].some(a=>e[a]!==void 0))throw new r({error:"cwd_not_exclusive",message:"cwd cannot be combined with another config flag except --keep-session and --restart",field:"cwd",next:"Pass --cwd alone (plus --keep-session / --restart)."});if(o!==void 0&&["model","kind","lifecycle","mode","name","nice","listen"].some(a=>e[a]!==void 0))throw new r({error:"profile_not_exclusive",message:"profile cannot be combined with another config flag except --restart",field:"profile",next:"Pass --profile alone (plus --restart)."});if(e.keepSession===!0&&x===void 0)throw new r({error:"keep_session_needs_cwd",message:"--keep-session only applies with --cwd",field:"keep-session",next:"Pass --cwd <dir> --keep-session."});if(e.restart===!0&&x===void 0&&o===void 0)throw new r({error:"restart_needs_change",message:"--restart only applies with --profile or --cwd",field:"restart",next:"Pass --profile <profile> or --cwd <dir> with --restart."});const S=e.model?.trim();if(S==="")throw new r({error:"empty_spec",message:"a model spec is required",field:"model",next:"Run `crtr node config --model -h` and read the focused contract before retrying."});const O=e.kind?.trim(),T=e.lifecycle?.trim(),q=e.mode?.trim(),L=e.name,v=e.nice,$=e.listen?.trim();let R;if($!==void 0)try{R=JSON.parse($)}catch{throw new r({error:"invalid_listen",message:`--listen is not JSON: ${$}`,field:"listen",next:`Pass a JSON object such as '{"3":"next-turn"}', or null.`})}if(v!==void 0&&(v<0||v>N))throw new r({error:"bad_nice",message:`niceness must be between 0 and ${N}: ${v}`,field:"nice",next:`A negative niceness needs root, so pass 0\u2013${N}.`});if(T!==void 0&&T.toLowerCase()!=="terminal"&&T.toLowerCase()!=="resident")throw new r({error:"bad_lifecycle",message:`invalid lifecycle: ${T}`,field:"lifecycle",next:"Pass `terminal` or `resident`."});if(q!==void 0&&q.toLowerCase()!=="base"&&q.toLowerCase()!=="orchestrator")throw new r({error:"bad_mode",message:`invalid mode: ${q}`,field:"mode",next:"Pass `base` or `orchestrator`."});const s=[],l={};if(S!==void 0&&(l.model=S,s.push("model")),O!==void 0&&(l.kind=O,s.push("kind")),T!==void 0&&(l.lifecycle=T.toLowerCase(),s.push("lifecycle")),q!==void 0&&(l.mode=q.toLowerCase(),s.push("mode")),L!==void 0&&(l.name=L,s.push("name")),x!==void 0&&(l.cwd=x,s.push("cwd"),e.keepSession===!0&&(l.keep_session=!0),e.restart===!0&&(l.restart=!0)),o!==void 0&&(l.profile=o,s.push("profile"),e.restart===!0&&(l.restart=!0)),$!==void 0&&(l.listen=R??null,s.push("listen")),v!==void 0){const a=await w().getNode(_).catch(A=>y(A));if(
|
|
4
|
-
`)}if(e.cwd!==void 0)return`Set cwd of ${e.node_id}: ${e.cwd}${e.session_kept===!0?" (conversation kept)":""}.`;if(e.profile!==void 0)return`Reassigned ${e.node_id} to profile ${e.profile}.`;const t=[];return e.model!==void 0&&t.push(`model=${e.model}`),e.lifecycle!==void 0&&t.push(`lifecycle=${e.lifecycle}`),e.kind!==void 0&&t.push(`kind=${e.kind}`),e.mode!==void 0&&t.push(`mode=${e.mode}`),e.name!==void 0&&t.push(`name=${e.name}`),e.nice!==void 0&&t.push(`nice=${e.nice}`),e.listen!==void 0&&t.push(`listen=${JSON.stringify(e.listen)}`),`Configured ${e.node_id} \u2014 ${t.join(", ")}`},"render")}),me=E({name:"promote",description:"become an orchestrator of a chosen kind",whenToUse:"the remaining work contains independent units that can run in parallel, and the task is large enough that coordinating and integrating them will materially improve intelligence, productivity, or elapsed throughput. Become a long-lived, roadmap-holding orchestrator whose primary job is steering those children across refreshes (`node yield`). Keep sequential or tightly coupled work in base mode even when it spans phases or context windows; spawning one helper does not itself require promotion",tier:"important",help:{name:"node promote",summary:"promote yourself to an orchestrator when worthwhile parallel delegation should make coordination your primary job; task duration, sequential phases, or one helper do not qualify. Mode only \u2014 lifecycle stays as-is unless you pass --resident",params:[{kind:"flag",name:"kind",type:"string",required:!1,constraint:"Specialize as this kind of orchestrator. The <kinds> list below names every top-level installable kind and when to use each; a registered sub-kind is valid too by exact path but not listed here. For an exact composed persona list, use `crtr sys context prompt-review --list --kind <kind>` with the target kind. Defaults to your current kind. Promoting from a generic kind? CHOOSE a concrete one \u2014 it sets the orchestrator persona you revive into."},{kind:"flag",name:"resident",type:"bool",required:!1,constraint:"ALSO flip lifecycle\u2192resident: make the node interactable \u2014 it is never forced to submit a final, and unattended grace parks it after a summary turn instead, leaving it revivable fresh against its goal and roadmap. Omit to stay terminal/orchestrator (delegates + holds a roadmap, but still owes a final up the spine and reaps when done)."},{kind:"flag",name:"model",type:"enum",choices:["ultra","strong"],required:!1,constraint:"Change the model you run on, by capability tier: `ultra` (frontier \u2014 reserve for high-taste judgment or enormous work: speccing, planning something large, e2e-testing something hard to test) or `strong` (opus \u2014 regular dev work). Omit to keep your current model. An orchestrator steering work is never weaker than opus, so these are the only two choices; the change is durable across future revives."},{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node to promote. Defaults to the caller (CRTR_NODE_ID)."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The promoted node."},{name:"kind",type:"string",required:!0,constraint:"The kind it now orchestrates as."},{name:"model",type:"string",required:!1,constraint:"The model tier it now runs on, present only when you changed it with --model."},{name:"lifecycle",type:"string",required:!0,constraint:'"resident" if you passed --resident, else unchanged (typically "terminal").'},{name:"roadmap_written",type:"boolean",required:!0,constraint:"True if the `roadmap` document was created by this call."},{name:"roadmap_ref",type:"string",required:!0,constraint:"Your roadmap document (`<node>/roadmap`) \u2014 author your plan with `crtr doc edit roadmap`."},{name:"goal_path",type:"string",required:!0,constraint:"Absolute path to your goal doc (context/initial-prompt.md) \u2014 the mandate you were spawned with."}],outputKind:"object",effects:["Flips mode\u2192orchestrator + kind\u2192chosen (lifecycle unchanged unless --resident, which also flips lifecycle\u2192resident); --model durably sets the model; rewrites the launch spec to that kind's orchestrator persona; creates your document `roadmap` (rule `on: boot`, `deliver: content`) if absent.","The next model request is gated on appending and persisting your new-role guidance. If a fresh context starts first, its rebuilt baseline carries the new role."]},helpState:{leaf:C},run:u(async e=>{const t=e.node??D();if(t===void 0||t==="")throw new r({error:"no_node",message:"no node to promote (set CRTR_NODE_ID or pass --node)",next:"Run from inside a node, or pass --node <id>."});const n=e.kind,i=e.model,d=e.resident===!0,o=await w().promoteNode(t,{...n!==void 0?{kind:n}:{},...d?{resident:!0}:{},...i!==void 0?{model:i}:{}}).catch(h=>y(h));return{node_id:o.node_id,kind:o.kind,lifecycle:o.lifecycle,...i!==void 0&&o.model_override!=null?{model:o.model_override}:{},roadmap_written:o.roadmap_written??!1,roadmap_ref:o.roadmap_ref??"",goal_path:o.goal_path??""}},"run")});async function M(e,t){let n=e.node;if((n===void 0||n==="")&&(n=I(t)),(n===void 0||n==="")&&(n=D()),n===void 0||n==="")throw new r({error:"no_node",message:"no node (set CRTR_NODE_ID, pass --node, or run from the agent's pane)",next:"Run from inside a node, pass --node <id>, or --pane <pane>."});if(await K(n)===null)throw new r({error:"not_found",message:`no node: ${n}`,next:"List nodes with `crtr node inspect list`."});return n}u(M,"resolveLifecycleNode");const te=E({name:"demote",description:"demote a node to terminal in place; it stays focused and running but now owes a final; --detach also closes its viewer (broker keeps running off-screen)",whenToUse:"you are watching a resident/interactive node and want to put it on a finishing track WITHOUT disturbing it: flip it terminal IN PLACE \u2014 it keeps its viewer and your focus, keeps running, but now owes a final report up the spine and reaps when done. The friendly counterpart to `node promote`. You can also let go entirely and close its viewer so the agent finishes off-screen on its broker. Use `node lifecycle recycle` instead to FINISH it now and reboot a fresh root in its pane, and `node config --lifecycle` for the orthogonal low-level flip (incl. terminal\u2192resident)",help:{name:"node lifecycle demote",summary:"demote a node to terminal IN PLACE \u2014 it stays focused and running but now owes a final up the spine and reaps when done. Pairs with `node promote` (mode\u2191); `--detach` also closes its viewer (the broker engine keeps running off-screen)",params:[{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node to demote. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane id whose node to demote, when --node is omitted. Defaults to $TMUX_PANE. The Alt+C menu passes this for you."},{kind:"flag",name:"detach",type:"bool",required:!1,constraint:"After flipping terminal, stop foregrounding the agent by closing its viewer pane. The broker engine keeps generating off-screen and \u2014 now terminal \u2014 pushes a final up the spine when done; a later `focus` reattaches a viewer. The Alt+C \u2192 D move."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The demoted node."},{name:"detached",type:"boolean",required:!1,constraint:"True when --detach closed the agent's viewer pane (broker keeps running)."}],outputKind:"object",effects:["Flips the node's lifecycle\u2192terminal and rebuilds its launch spec so a future revive boots terminal \u2014 it stays focused and running, now owing a final up the spine.","The next model request is gated on appending and persisting the role transition. If a fresh context starts first, its rebuilt baseline carries the new lifecycle.","With --detach: closes the agent's viewer pane WITHOUT touching the broker engine \u2014 it keeps generating off-screen, reconnectable by a later `focus`."]},run:u(async e=>{const t=e.pane??process.env.TMUX_PANE,n=await M(e,t),i=await w().patchConfig(n,{lifecycle:"terminal"}).catch(o=>y(o));let d=!1;if(e.detach===!0){const o=Z(n)??t;o!==void 0&&o!==""&&G(o)&&(d=z(o))}return{node_id:i.node_id,detached:d}},"run"),render:u(e=>`Demoted ${e.node_id} \u2014 lifecycle now terminal (in place)${e.detached===!0?", viewer closed (broker still running off-screen)":""}.`,"render")}),ge=H({name:"lifecycle",description:"lifecycle actions \u2014 recycle, close, demote, or revive a node",whenToUse:"you are ending, transitioning, or bringing back one node you can name: finish the agent in your pane and reboot a fresh root (`recycle`), tear a node + its exclusive subtree down without finishing (`close`), flip a node onto a finishing track in place (`demote`), or bring a dormant node back (`revive`). To merely SET the terminal/resident attribute headlessly use `node config --lifecycle`; to FINISH from inside a node's own turn use `crtr push final`; to mass-reconnect EVERY disconnected node at once use `canvas revive --all`.",help:{name:"node lifecycle",summary:"end, transition, or revive a node \u2014 recycle the pane, close + cascade-cancel a subtree, demote to terminal in place, or revive a dormant node",model:"Lifecycle actions preserve or replace an existing node identity. Finishing is permanent, closing is revivable, demotion changes the completion obligation in place, and revival relaunches a dormant broker. Teardown cascades only through descendants exclusively managed by the affected subtree."},children:[ee,ne,te,Y]}),we=E({name:"yield",description:"refresh your context, same mode, against your roadmap or goal",whenToUse:"your context is filling but the mandate remains; refresh in the same mode, or combine the refresh with promotion when meaningful independent work can run in parallel and coordinating it should become your primary job",help:{name:"node yield",summary:"request a fresh context window against your roadmap or original goal; mode stays unchanged unless --promote is passed",guide:"The yield aborts your turn the instant this command returns: no text or tool call you planned after it will run. So anything the user is owed \u2014 an answer, a status \u2014 must already be a visible message in the conversation before you call it; never plan to reply after yielding. Before invoking: (1) If you hold a document `roadmap`, bring it current (`crtr doc edit roadmap`). It, not the yield note, carries your task into the fresh window. It has four sections: Goal (its first line is also the roadmap\u2019s preview, so set it with `--preview` whenever the goal changes), Exit criteria, Where things stand, and Working set. Keep it at your own level of abstraction. Detail below your level belongs to the node or document that holds it: link to it, don\u2019t copy it. Where things stand is present tense; delete what is done instead of marking it. Name units by what they are and how they fit, never by child node id or status: your bearings already list your children with their status. Working set holds `[[links]]`. Their previews load with the roadmap, so write no note beside a link. When a unit lands, delete its links: its evidence belongs in its report. (2) Give content its own document when it lives on a different timescale from the roadmap (exploration that outlives the current work), goes to a different reader (a brief for a child), or matters only when something specific happens. Link each such document from the Working set. Anything you had to re-derive in this window that a future window will need again belongs in a document: one you own for this task, `--owner repo` for lessons that would help others in the repo. A document that only points at other documents is not worth the extra hop. (3) Actions waiting on one specific event (\u201Cwhen X reports, send Y first\u201D) go in the yield note, not the roadmap. They are spent once they fire. (4) Send any pending human question; asks already in flight survive the refresh.",params:[{kind:"flag",name:"promote",type:"bool",required:!1,constraint:"Also become an orchestrator as you refresh. Pass only when (1) the remaining work contains independent units that can run in parallel and (2) the task is large enough that parallel execution will materially improve intelligence, productivity, or elapsed throughput after coordination and synthesis. Task length, context exhaustion, sequential phases, or one helper are not enough; keep hands-on work in base mode and yield again as needed. Promote when coordinating and integrating children becomes your primary job. Already an orchestrator? This is not an error: your mode stays orchestrator and a missing roadmap is seeded."},{kind:"flag",name:"kind",type:"string",required:!1,constraint:"Respecialize as you refresh. The <kinds> list below names every top-level available kind and when to choose it; a registered sub-kind is valid too by exact path but not listed here. Defaults to your current kind. With --promote it sets the orchestrator kind you become; without --promote it changes the kind while preserving your current mode."},{kind:"flag",name:"model",type:"enum",choices:["ultra","strong"],required:!1,constraint:"Change the model your fresh revive runs on, by capability tier: `ultra` (frontier \u2014 reserve for high-taste judgment or enormous work: speccing, planning something large, e2e-testing something hard to test) or `strong` (opus \u2014 regular dev work). Omit to keep your current model. A node steering work is never weaker than opus, so these are the only two choices; the change is durable across future revives."},{kind:"stdin",name:"message",required:!0,constraint:"A note to your future self \u2014 what you just tried, where things stand, the first move on waking, and any action waiting on a specific event: enough to continue efficiently, no more. Never describe a reply as sent unless it is visible in the conversation above this call. Your task and its state belong in the roadmap. Surfaced as <yield-message> in the next revive. Pass as a positional or pipe via heredoc."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The yielding node."},{name:"model",type:"string",required:!1,constraint:"The model tier your fresh revive will run on, present only when you changed it with --model."}],outputKind:"object",effects:["Aborts your current turn as soon as this command returns \u2014 nothing after it runs \u2014 then the daemon revives the node fresh.","--kind and/or --model durably reshape the node (kind respecialization, model change) before the refresh-revive; --promote additionally flips mode\u2192orchestrator and creates your document `roadmap` \u2014 mode is otherwise left exactly as it was."]},helpState:{leaf:C},run:u(async e=>{const t=D();if(t===void 0||t==="")throw new r({error:"no_node",message:"no node to yield (CRTR_NODE_ID unset)",next:"Run from inside a node."});const n=e.kind,i=e.model,d=e.promote===!0,o=typeof e.message=="string"?e.message.trim():"";if(o==="")throw new r({error:"empty_message",message:"a yield message is required (stdin or positional)",next:"Pass a note to your future self as an argument or pipe it on stdin."});const h=await w().yieldNode(t,{note:o,...n!==void 0?{kind:n}:{},...i!==void 0?{model:i}:{},...d?{promote:!0}:{}}).catch(f=>y(f));return{node_id:h.node_id,...i!==void 0&&h.model_override!=null?{model:h.model_override}:{}}},"run")});export{pe as nodeConfig,ge as nodeLifecycle,me as nodePromote,we as nodeYield};
|
|
1
|
+
var H=Object.defineProperty;var u=(e,t)=>H(e,"name",{value:t,configurable:!0});import{contextDir as B}from"../../core/canvas/paths.js";import{readFileSync as W}from"node:fs";import{envNodeId as D}from"../../shared/env.js";import{defineBranch as K,defineLeaf as E}from"../../core/command.js";import{InputError as r}from"../../core/io.js";import{cliClient as w,getNodeOrNull as X,rethrowAsCliError as y}from"../api-client.js";import{DEFAULT_BASH_NICENESS as F,MAX_BASH_NICENESS as N,writeBashNiceness as Y}from"../../core/bash-jobs.js";import{nodeReviveLeaf as J}from"../node-lifecycle-revive.js";import{kindsStateBlock as C}from"../profile/daemon-profiles.js";import{expandHostPathTokens as z}from"../../core/runtime/broker/host-path-tokens.js";import{MODEL_SPEC_FORMS as G}from"../../core/runtime/model-selection.js";import{closePane as V,paneExists as Q,respawnPaneSync as Z,viewerEnv as ee,viewerPaneOf as ne,nodeInPane as I}from"../surface/node/placement.js";const te=E({name:"recycle",description:"finish the agent in your pane + recycle it into a fresh root",whenToUse:"you are at an agent's pane and done with it: finish it cleanly and recycle the pane in one move \u2014 push its last message as a final report to everyone waiting on it, mark it done, then boot a fresh crtr root in the same pane to keep working. The hands-on way to end an agent and immediately start over in place. Use `node lifecycle demote` instead to put it on a finishing track IN PLACE (flip terminal, keep it running) without ending it now, `node lifecycle close` to tear a node and its subtree down WITHOUT finishing (no report, revivable), and `push final` when the agent should finish ITSELF from inside its own turn",help:{name:"node lifecycle recycle",summary:"finish the agent in your current pane and recycle the pane \u2014 push its last message as a final report to everyone waiting on it, mark it done, then boot a fresh crtr root in the same pane",params:[{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node to finish. Defaults to the node occupying --pane (or your current pane)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane id to recycle. Defaults to $TMUX_PANE / your current pane. The Alt+C menu passes this for you."}],output:[{name:"recycled",type:"boolean",required:!0,constraint:"True when the pane was recycled into a fresh root."},{name:"node_id",type:"string",required:!1,constraint:"The finished node."},{name:"new_root",type:"string",required:!1,constraint:"The fresh root node booted into the pane."}],outputKind:"object",effects:["Pushes a final report from the node (fans out to all subscribers) and marks it done.","Kills the agent's pi and respawns a fresh resident root in the same tmux pane."]},run:u(async e=>{const t=e.pane??process.env.TMUX_PANE;let n=e.node;if((n===void 0||n==="")&&(n=I(t)),n===void 0||n==="")throw new r({error:"no_node",message:"no node found in this pane to finish",next:"Pass --node <id>, or run from inside the agent's pane."});const i=await w().getNode(n).catch(f=>y(f,"List nodes with `crtr node inspect list`.")),o=(await w().recycleNode(n).catch(y)).node_id;let h=!1;return t!==void 0&&t!==""&&(h=Z({pane:t,cwd:i.cwd,env:ee(),command:"crtr"})),{recycled:h,node_id:n,new_root:o}},"run"),render:u(e=>{if(e.recycled!==!0)return e.new_root?`Finished ${e.node_id} and spawned a fresh broker root (${e.new_root}), but its viewer did not attach \u2014 the new broker did not come up. Re-focus the root to view it.`:`Recycle failed for ${e.node_id??"?"} \u2014 not in tmux, or no agent in this pane.`;const t=[`Recycled the pane \u2014 finished ${e.node_id}.`];return e.new_root&&t.push(`- new root: ${e.new_root}`),t.join(`
|
|
2
|
+
`)},"render")}),oe=E({name:"close",description:"close a node + cascade-cancel its exclusive subtree",whenToUse:"you want to tear a node down WITHOUT finishing it, cascade-cancelling every descendant it exclusively owns: abandoning a line of work, killing a stuck or wrong-turn subtree, clearing a branch you no longer need. A node that never produced substantive assistant output is deleted and cannot be revived; streaming nodes and nodes with an open managed worktree are retained. Other closed nodes keep their pi session and can be revived later (`node lifecycle revive`). Use `node lifecycle recycle` instead to FINISH the agent in your pane with a final report, and `push final` when a worker should end its own work normally (Alt+C \u2192 x)",help:{name:"node lifecycle close",summary:"close a node and cascade-cancel its subtree \u2014 kill its tmux window plus those of every descendant it EXCLUSIVELY owns (down the subscription spine \u2014 the watches each manager holds on its children), mark retained nodes canceled, and leave them a notice they read on resume. A descendant still subscribed to by a manager outside the subtree is left running. A node that never produced substantive assistant output is deleted and cannot be revived; streaming nodes and nodes with an open managed worktree are retained. Other closed nodes keep their pi session and can be revived later (`crtr node lifecycle revive`)",params:[{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node to close. Defaults to the node occupying --pane (or your current pane)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane id whose node to close. Defaults to $TMUX_PANE / your current pane. The Alt+C menu passes this for you."}],output:[{name:"node_id",type:"string",required:!1,constraint:"The node that was closed \u2014 the cascade root."},{name:"count",type:"number",required:!1,constraint:"How many nodes were closed (root + cascaded descendants)."},{name:"closed_ids",type:"string[]",required:!1,constraint:"All closed node ids, kill order (leaves first, root last)."},{name:"spared",type:"string[]",required:!1,constraint:"Descendants left alive because a manager outside the subtree still subscribes to them."}],outputKind:"object",effects:["Marks retained nodes and their exclusive descendants `canceled` and clears intent (the daemon never revives a canceled node).","Deletes a non-streaming node with no substantive assistant output unless it has an open managed worktree; a deleted node cannot be revived.","Kills each closed node's tmux window; retained nodes keep their pi sessions and canvas edges for a later revive.","Appends a cancellation notice to each retained node's inbox, surfaced on its next resume."]},run:u(async e=>{const t=e.pane??process.env.TMUX_PANE;let n=e.node;if((n===void 0||n==="")&&(n=I(t)),n===void 0||n==="")throw new r({error:"no_node",message:"no node found in this pane to close",next:"Pass --node <id>, or run from inside the agent's pane."});const i=await w().closeNode(n,process.ppid>0?{caller_pid:process.ppid}:{}).catch(d=>y(d,"List nodes with `crtr node inspect list`."));return{node_id:i.root,count:i.closed.length,closed_ids:i.closed,spared:i.spared}},"run"),render:u(e=>{const t=e.spared?.length??0;return`Closed ${e.node_id} and its exclusive subtree \u2014 ${e.count} node(s) closed${t>0?`, ${t} spared (still managed from outside the subtree)`:""}.`},"render")}),j="Model change first: a running broker, including one still starting right after `node new`, switches over its socket; a dormant node persists the durable model override and launch recipe for its next revive.",ye=E({name:"config",description:"reconfigure a node's settings headlessly \u2014 model, lifecycle (terminal/resident), kind, mode, name; repair a missing cwd",whenToUse:"you want to reconfigure a node's settings headlessly after spawn \u2014 swap its model/provider, flip it terminal\u2194resident (interactable), respecialize its kind, switch base\u2194orchestrator mode, or rename it \u2014 without opening its viewer. It also repairs a dormant node whose recorded cwd is gone, starting its next revive in a fresh conversation. The durable attribute setter; reuses the same recipes a revive reads. Use `node promote` for the opinionated self-promotion path, and `node lifecycle` for teardown actions (recycle/close/demote).",help:{name:"node config",summary:"reconfigure a node's settings headlessly \u2014 model, lifecycle, kind, mode, name; repair a missing cwd",params:[{kind:"flag",name:"node",type:"string",required:!1,repeatable:!0,constraint:"Target node id. Defaults to the node in --pane, else CRTR_NODE_ID. Repeat it, or use --nodes-from, to apply a --profile or --cwd change to many nodes; a bulk run reports each node and keeps going past a failure."},{kind:"flag",name:"nodes-from",type:"string",required:!1,constraint:"File of node ids, one per line (blank lines and #-comments ignored), or `-` for stdin. Bulk form of --node; only with --profile or --cwd."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane id to resolve the node from. Defaults to $TMUX_PANE."},{kind:"flag",name:"model",type:"string",required:!1,constraint:"Durable model change. Omit unless the task or governing guidance requires a different model.",focusedHelp:{whenToUse:"Use only when intentionally changing this node\u2019s durable model because the user, task, or governing agent guidance requires a specific provider, model, capability tier, or family. Omit it to keep the current model; do not use it merely to inspect available models or experiment with a live node.",value:`Accepted durable forms: ${G}. A live broker also accepts a free-text substring matched against its loaded model registry; a dormant node cannot resolve a substring and requires a durable form.`,effects:[j,"A concrete provider/id runs exactly that model on every launch and revive. A portable provider/tier, bare tier, or family alias keeps its tier: when that model's provider is rate-limited or rejects its credential, the node moves to the next model in its route: another provider's model at the same tier first, then the configured fallback tier (strong by default)."]}},{kind:"flag",name:"lifecycle",type:"enum",choices:["terminal","resident"],required:!1,constraint:"Set lifecycle headlessly without closing the viewer. terminal owes a final and reaps when done; resident stays interactable while attached or awaiting something live."},{kind:"flag",name:"kind",type:"string",required:!1,constraint:"Persona kind. The <kinds> list below names every top-level installable kind and when to use each; a registered sub-kind is valid too by exact path but not listed here."},{kind:"flag",name:"mode",type:"enum",choices:["base","orchestrator"],required:!1,constraint:"Set persona mode headlessly. base is hands-on; orchestrator holds a roadmap and delegates. orchestrator creates your document `roadmap` if absent."},{kind:"flag",name:"name",type:"string",required:!1,constraint:"Rename the node; if the node has a live window, also rename that viewer window."},{kind:"flag",name:"nice",type:"int",required:!1,constraint:`Scheduler niceness every command this node's bash tool starts at, 0\u2013${N} (default ${F}). ${F} keeps the node's builds and test suites below the daemon, the brokers, the viewers, and the person's own shell; 0 lets them compete on equal terms with everything else on the host; ${N} makes them yield to it. Applies to the node's very next command, foreground and background alike.`},{kind:"flag",name:"listen",type:"string",required:!1,constraint:`The node's default listening configuration, as JSON mapping an event level ("1".."10") to how events at or above it reach the node: interrupt, steer, after-turn, or next-turn (e.g. '{"3":"next-turn"}' \u2014 events of level 3+ wait for its next turn and never wake it). Applies to every watch with no configuration of its own. Pass \`null\` to reset to the global default.`},{kind:"flag",name:"cwd",type:"string",required:!1,constraint:"Replacement launch directory (absolute, existing). Alone, or with --keep-session / --restart. Without --keep-session it is a repair: only a dormant, non-forked node with no open managed worktree whose recorded cwd is gone, and it clears the saved Pi session (next revive starts fresh). When the new path is the same directory as the recorded one (a symlink alias) it relocates and keeps the conversation automatically \u2014 see --keep-session."},{kind:"flag",name:"keep-session",type:"bool",required:!1,constraint:"With --cwd: assert the new path is the SAME directory as the recorded cwd and relocate WITHOUT clearing the Pi session. Needed only when the recorded path is already gone (e.g. the symlink was deleted); while it still exists the daemon verifies by realpath and refuses a different directory. Allowed for live, idle, dormant and finished nodes, forks included. Rewrites the recorded cwd and the cwd in the node's transcript header so a later resume finds it. Refused while the node owns an open managed worktree."},{kind:"flag",name:"rewrite-prefix",type:"string",required:!1,constraint:'Bulk cwd form, `OLD=NEW` (absolute paths): with several nodes, each node\'s recorded cwd that equals OLD or lies beneath it is relocated to the same place under NEW, keeping its session (as --keep-session); nodes whose cwd is elsewhere are reported as failed "not under OLD". Use instead of --cwd when the nodes sit in different subdirectories.'},{kind:"flag",name:"profile",type:"string",required:!1,constraint:"Reassign the node to this profile (id or exact name; must be an active profile of the node's app that defines the node's kind). Works for live, idle, dormant, finished and profile-less (detached) nodes. Used alone, or with --restart."},{kind:"flag",name:"restart",type:"bool",required:!1,constraint:"With --profile, or --cwd on a live node: after the change, SIGTERM the node's live broker so crtrd resumes it from the same transcript (continuing an interrupted turn) with the new profile/cwd. No effect on a node with no live broker."}],output:[{name:"node_id",type:"string",required:!1,constraint:"The reconfigured node, present for ordinary config changes."},{name:"model",type:"string",required:!1,constraint:"The resolved model, present only when --model changed it."},{name:"lifecycle",type:"string",required:!1,constraint:"The new lifecycle, present only when --lifecycle changed it."},{name:"kind",type:"string",required:!1,constraint:"The new kind, present only when --kind changed it."},{name:"mode",type:"string",required:!1,constraint:"The new mode, present only when --mode changed it."},{name:"name",type:"string",required:!1,constraint:"The new name, present only when --name changed it."},{name:"nice",type:"number",required:!1,constraint:"The new bash niceness, present only when --nice changed it."},{name:"listen",type:"object",required:!1,constraint:"The new default listening configuration (null = global default), present only when --listen changed it."},{name:"cwd",type:"string",required:!1,constraint:"The resolved replacement directory, present only after a cwd change."},{name:"session_kept",type:"boolean",required:!1,constraint:"With a cwd change: true when the node still has its Pi session bound (conversation preserved)."},{name:"profile",type:"string",required:!1,constraint:"The node's profile id after --profile."},{name:"bulk",type:"boolean",required:!1,constraint:"True for a multi-node run."},{name:"applied",type:"number",required:!1,constraint:"Bulk: nodes changed (or already in the requested state)."},{name:"failed",type:"number",required:!1,constraint:"Bulk: nodes that errored; the exit code is 1 when any did."},{name:"results",type:"array",required:!1,constraint:"Bulk: one {node_id, ok, error?} per node, in input order."}],outputKind:"object",effects:[j,"Kind, mode, and lifecycle changes rebuild the launch spec from the fresh node meta; setting mode to orchestrator creates your document `roadmap` if absent.","Name changes update the row and, when the node already has a live window, rename that viewer window to the new full name.","A cwd repair (gone recorded cwd, no --keep-session) writes only the lexically resolved cwd and clears saved Pi session pointers; the old transcript and durable node work remain untouched.","A session-keeping cwd relocation (--keep-session, or --cwd naming a symlink alias of the recorded directory) rewrites the recorded cwd and the cwd line in the header of each of the node's transcripts; the Pi session stays bound and the next revive resumes the same conversation. A LIVE broker keeps the old cwd string in its environment and tools until it restarts: it keeps working while the old path exists, so pass --restart (or revive it) BEFORE deleting an old symlink.","A profile reassignment rewrites the node's profile and rebuilds its launch recipe. Profile env, documents delivered at boot, purview and bearings are read at launch, so a LIVE broker keeps the old profile until it next restarts; --restart bounces it now. Dormant or finished nodes simply carry the new profile into their next revive. The node's deadlines and profile pause follow the new profile immediately.","A niceness change is stored with the node's own bash-job state, so it takes effect on the next command without a revive and survives one.","A listen change sets the node's default listening configuration; it never changes which watches it holds.","Every successful change publishes a `configured` event on the node (level 1) naming the changed settings, so its watchers can see it."]},helpState:{leaf:C},run:u(async e=>{const t=e.pane??process.env.TMUX_PANE,n=e.node,i=Array.isArray(n)?n:n===void 0?[]:[n],d=e.nodesFrom;if(d!==void 0){const a=d==="-"?W(0,"utf8"):W(d,"utf8");for(const A of a.split(`
|
|
3
|
+
`)){const b=A.replace(/#.*/,"").trim();b!==""&&i.push(b)}}const o=e.profile,h=e.cwd,f=e.rewritePrefix;if(i.length>1||d!==void 0||f!==void 0){if(i.length===0)throw new r({error:"no_nodes",message:"bulk config needs at least one node",next:"Pass --node ID (repeatable) or --nodes-from FILE|-."});if(o===void 0&&h===void 0&&f===void 0)throw new r({error:"bulk_unsupported",message:"several nodes are accepted only with --profile, --cwd or --rewrite-prefix",next:"Pass --profile <profile>, --cwd <dir> or --rewrite-prefix OLD=NEW with the node list."});let a;if(f!==void 0){const p=f.indexOf("="),c=p<0?"":f.slice(0,p).replace(/\/+$/,""),m=p<0?"":f.slice(p+1).replace(/\/+$/,"");if(!c.startsWith("/")||!m.startsWith("/"))throw new r({error:"bad_rewrite_prefix",message:`--rewrite-prefix must be OLD=NEW with absolute paths: ${f}`,field:"rewrite-prefix",next:"Pass e.g. --rewrite-prefix /Users/me/Code/northlight=/Users/me/Code/northlight-systems."});a=[c,m]}const A=w(),b=[];for(const p of[...new Set(i)])try{const c=o!==void 0?{profile:o}:{cwd:h??""};if(a!==void 0){const m=(await A.getNode(p)).cwd;if(m!==a[0]&&!m.startsWith(`${a[0]}/`))throw new Error(`cwd ${m} is not under ${a[0]}`);c.cwd=a[1]+m.slice(a[0].length),c.keep_session=!0}e.keepSession===!0&&(c.keep_session=!0),e.restart===!0&&(c.restart=!0),await A.patchConfig(p,c),b.push({node_id:p,ok:!0})}catch(c){let m=c instanceof Error?c.message:String(c);try{y(c)}catch(U){U instanceof Error&&(m=U.message)}b.push({node_id:p,ok:!1,error:m})}const P=b.filter(p=>!p.ok).length;return P>0&&(process.exitCode=1),{bulk:!0,applied:b.length-P,failed:P,results:b}}const _=await M({...e,node:i[0]},t),x=h;if(x!==void 0&&["model","kind","lifecycle","mode","name","nice","listen","profile"].some(a=>e[a]!==void 0))throw new r({error:"cwd_not_exclusive",message:"cwd cannot be combined with another config flag except --keep-session and --restart",field:"cwd",next:"Pass --cwd alone (plus --keep-session / --restart)."});if(o!==void 0&&["model","kind","lifecycle","mode","name","nice","listen"].some(a=>e[a]!==void 0))throw new r({error:"profile_not_exclusive",message:"profile cannot be combined with another config flag except --restart",field:"profile",next:"Pass --profile alone (plus --restart)."});if(e.keepSession===!0&&x===void 0)throw new r({error:"keep_session_needs_cwd",message:"--keep-session only applies with --cwd",field:"keep-session",next:"Pass --cwd <dir> --keep-session."});if(e.restart===!0&&x===void 0&&o===void 0)throw new r({error:"restart_needs_change",message:"--restart only applies with --profile or --cwd",field:"restart",next:"Pass --profile <profile> or --cwd <dir> with --restart."});const S=e.model?.trim();if(S==="")throw new r({error:"empty_spec",message:"a model spec is required",field:"model",next:"Run `crtr node config --model -h` and read the focused contract before retrying."});const O=e.kind?.trim(),T=e.lifecycle?.trim(),q=e.mode?.trim(),L=e.name,v=e.nice,$=e.listen?.trim();let R;if($!==void 0)try{R=JSON.parse($)}catch{throw new r({error:"invalid_listen",message:`--listen is not JSON: ${$}`,field:"listen",next:`Pass a JSON object such as '{"3":"next-turn"}', or null.`})}if(v!==void 0&&(v<0||v>N))throw new r({error:"bad_nice",message:`niceness must be between 0 and ${N}: ${v}`,field:"nice",next:`A negative niceness needs root, so pass 0\u2013${N}.`});if(T!==void 0&&T.toLowerCase()!=="terminal"&&T.toLowerCase()!=="resident")throw new r({error:"bad_lifecycle",message:`invalid lifecycle: ${T}`,field:"lifecycle",next:"Pass `terminal` or `resident`."});if(q!==void 0&&q.toLowerCase()!=="base"&&q.toLowerCase()!=="orchestrator")throw new r({error:"bad_mode",message:`invalid mode: ${q}`,field:"mode",next:"Pass `base` or `orchestrator`."});const s=[],l={};if(S!==void 0&&(l.model=S,s.push("model")),O!==void 0&&(l.kind=O,s.push("kind")),T!==void 0&&(l.lifecycle=T.toLowerCase(),s.push("lifecycle")),q!==void 0&&(l.mode=q.toLowerCase(),s.push("mode")),L!==void 0&&(l.name=L,s.push("name")),x!==void 0&&(l.cwd=x,s.push("cwd"),e.keepSession===!0&&(l.keep_session=!0),e.restart===!0&&(l.restart=!0)),o!==void 0&&(l.profile=o,s.push("profile"),e.restart===!0&&(l.restart=!0)),$!==void 0&&(l.listen=R??null,s.push("listen")),v!==void 0){const a=await w().getNode(_).catch(A=>y(A));if(Y(B(_,a.grantee),v),s.push("nice"),s.length===1)return{node_id:_,nice:v}}if(s.length===0)throw new r({error:"no_change",message:"no config changes requested",next:"Pass at least one of --model, --lifecycle, --kind, --mode, --name, --nice, --listen, --cwd."});const g=await w().patchConfig(_,l).catch(a=>y(a,"List nodes with `crtr node inspect list`."));if(x!==void 0)return{cwd:g.cwd,node_id:_,...l.keep_session===!0||g.pi_session_id!=null?{session_kept:g.pi_session_id!=null}:{}};if(o!==void 0)return{node_id:_,profile:g.profile_id??null};const k={node_id:_};return s.includes("model")&&(k.model=g.model_override??S),s.includes("lifecycle")&&(k.lifecycle=g.lifecycle),s.includes("kind")&&(k.kind=g.kind),s.includes("mode")&&(k.mode=g.mode),s.includes("name")&&(k.name=g.name),s.includes("nice")&&(k.nice=v),s.includes("listen")&&(k.listen=l.listen),k},"run"),render:u(e=>{if(e.bulk===!0){const n=e.results;return[`Applied to ${e.applied} node(s), ${e.failed} failed.`,...n.filter(i=>!i.ok).map(i=>` FAILED ${i.node_id}: ${i.error}`)].join(`
|
|
4
|
+
`)}if(e.cwd!==void 0)return`Set cwd of ${e.node_id}: ${e.cwd}${e.session_kept===!0?" (conversation kept)":""}.`;if(e.profile!==void 0)return`Reassigned ${e.node_id} to profile ${e.profile}.`;const t=[];return e.model!==void 0&&t.push(`model=${e.model}`),e.lifecycle!==void 0&&t.push(`lifecycle=${e.lifecycle}`),e.kind!==void 0&&t.push(`kind=${e.kind}`),e.mode!==void 0&&t.push(`mode=${e.mode}`),e.name!==void 0&&t.push(`name=${e.name}`),e.nice!==void 0&&t.push(`nice=${e.nice}`),e.listen!==void 0&&t.push(`listen=${JSON.stringify(e.listen)}`),`Configured ${e.node_id} \u2014 ${t.join(", ")}`},"render")}),ve=E({name:"promote",description:"become an orchestrator of a chosen kind",whenToUse:"the remaining work contains independent units that can run in parallel, and the task is large enough that coordinating and integrating them will materially improve intelligence, productivity, or elapsed throughput. Become a long-lived, roadmap-holding orchestrator whose primary job is steering those children across refreshes (`node yield`). Keep sequential or tightly coupled work in base mode even when it spans phases or context windows; spawning one helper does not itself require promotion",tier:"important",help:{name:"node promote",summary:"promote yourself to an orchestrator when worthwhile parallel delegation should make coordination your primary job; task duration, sequential phases, or one helper do not qualify. Mode only \u2014 lifecycle stays as-is unless you pass --resident",params:[{kind:"flag",name:"kind",type:"string",required:!1,constraint:"Specialize as this kind of orchestrator. The <kinds> list below names every top-level installable kind and when to use each; a registered sub-kind is valid too by exact path but not listed here. For an exact composed persona list, use `crtr sys context prompt-review --list --kind <kind>` with the target kind. Defaults to your current kind. Promoting from a generic kind? CHOOSE a concrete one \u2014 it sets the orchestrator persona you revive into."},{kind:"flag",name:"resident",type:"bool",required:!1,constraint:"ALSO flip lifecycle\u2192resident: make the node interactable \u2014 it is never forced to submit a final, and unattended grace parks it after a summary turn instead, leaving it revivable fresh against its goal and roadmap. Omit to stay terminal/orchestrator (delegates + holds a roadmap, but still owes a final up the spine and reaps when done)."},{kind:"flag",name:"model",type:"enum",choices:["ultra","strong"],required:!1,constraint:"Change the model you run on, by capability tier: `ultra` (frontier \u2014 reserve for high-taste judgment or enormous work: speccing, planning something large, e2e-testing something hard to test) or `strong` (opus \u2014 regular dev work). Omit to keep your current model. An orchestrator steering work is never weaker than opus, so these are the only two choices; the change is durable across future revives."},{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node to promote. Defaults to the caller (CRTR_NODE_ID)."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The promoted node."},{name:"kind",type:"string",required:!0,constraint:"The kind it now orchestrates as."},{name:"model",type:"string",required:!1,constraint:"The model tier it now runs on, present only when you changed it with --model."},{name:"lifecycle",type:"string",required:!0,constraint:'"resident" if you passed --resident, else unchanged (typically "terminal").'},{name:"roadmap_written",type:"boolean",required:!0,constraint:"True if the `roadmap` document was created by this call."},{name:"roadmap_ref",type:"string",required:!0,constraint:"Your roadmap document (`<node>/roadmap`) \u2014 author your plan with `crtr doc edit roadmap`."},{name:"goal_path",type:"string",required:!0,constraint:"Absolute path to your goal doc (context/initial-prompt.md) \u2014 the mandate you were spawned with."}],outputKind:"object",effects:["Flips mode\u2192orchestrator + kind\u2192chosen (lifecycle unchanged unless --resident, which also flips lifecycle\u2192resident); --model durably sets the model; rewrites the launch spec to that kind's orchestrator persona; creates your document `roadmap` (rule `on: boot`, `deliver: content`) if absent.","The next model request is gated on appending and persisting your new-role guidance. If a fresh context starts first, its rebuilt baseline carries the new role."]},helpState:{leaf:C},run:u(async e=>{const t=e.node??D();if(t===void 0||t==="")throw new r({error:"no_node",message:"no node to promote (set CRTR_NODE_ID or pass --node)",next:"Run from inside a node, or pass --node <id>."});const n=e.kind,i=e.model,d=e.resident===!0,o=await w().promoteNode(t,{...n!==void 0?{kind:n}:{},...d?{resident:!0}:{},...i!==void 0?{model:i}:{}}).catch(h=>y(h));return{node_id:o.node_id,kind:o.kind,lifecycle:o.lifecycle,...i!==void 0&&o.model_override!=null?{model:o.model_override}:{},roadmap_written:o.roadmap_written??!1,roadmap_ref:o.roadmap_ref??"",goal_path:z(o.goal_path??"")}},"run")});async function M(e,t){let n=e.node;if((n===void 0||n==="")&&(n=I(t)),(n===void 0||n==="")&&(n=D()),n===void 0||n==="")throw new r({error:"no_node",message:"no node (set CRTR_NODE_ID, pass --node, or run from the agent's pane)",next:"Run from inside a node, pass --node <id>, or --pane <pane>."});if(await X(n)===null)throw new r({error:"not_found",message:`no node: ${n}`,next:"List nodes with `crtr node inspect list`."});return n}u(M,"resolveLifecycleNode");const ie=E({name:"demote",description:"demote a node to terminal in place; it stays focused and running but now owes a final; --detach also closes its viewer (broker keeps running off-screen)",whenToUse:"you are watching a resident/interactive node and want to put it on a finishing track WITHOUT disturbing it: flip it terminal IN PLACE \u2014 it keeps its viewer and your focus, keeps running, but now owes a final report up the spine and reaps when done. The friendly counterpart to `node promote`. You can also let go entirely and close its viewer so the agent finishes off-screen on its broker. Use `node lifecycle recycle` instead to FINISH it now and reboot a fresh root in its pane, and `node config --lifecycle` for the orthogonal low-level flip (incl. terminal\u2192resident)",help:{name:"node lifecycle demote",summary:"demote a node to terminal IN PLACE \u2014 it stays focused and running but now owes a final up the spine and reaps when done. Pairs with `node promote` (mode\u2191); `--detach` also closes its viewer (the broker engine keeps running off-screen)",params:[{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node to demote. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane id whose node to demote, when --node is omitted. Defaults to $TMUX_PANE. The Alt+C menu passes this for you."},{kind:"flag",name:"detach",type:"bool",required:!1,constraint:"After flipping terminal, stop foregrounding the agent by closing its viewer pane. The broker engine keeps generating off-screen and \u2014 now terminal \u2014 pushes a final up the spine when done; a later `focus` reattaches a viewer. The Alt+C \u2192 D move."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The demoted node."},{name:"detached",type:"boolean",required:!1,constraint:"True when --detach closed the agent's viewer pane (broker keeps running)."}],outputKind:"object",effects:["Flips the node's lifecycle\u2192terminal and rebuilds its launch spec so a future revive boots terminal \u2014 it stays focused and running, now owing a final up the spine.","The next model request is gated on appending and persisting the role transition. If a fresh context starts first, its rebuilt baseline carries the new lifecycle.","With --detach: closes the agent's viewer pane WITHOUT touching the broker engine \u2014 it keeps generating off-screen, reconnectable by a later `focus`."]},run:u(async e=>{const t=e.pane??process.env.TMUX_PANE,n=await M(e,t),i=await w().patchConfig(n,{lifecycle:"terminal"}).catch(o=>y(o));let d=!1;if(e.detach===!0){const o=ne(n)??t;o!==void 0&&o!==""&&Q(o)&&(d=V(o))}return{node_id:i.node_id,detached:d}},"run"),render:u(e=>`Demoted ${e.node_id} \u2014 lifecycle now terminal (in place)${e.detached===!0?", viewer closed (broker still running off-screen)":""}.`,"render")}),ke=K({name:"lifecycle",description:"lifecycle actions \u2014 recycle, close, demote, or revive a node",whenToUse:"you are ending, transitioning, or bringing back one node you can name: finish the agent in your pane and reboot a fresh root (`recycle`), tear a node + its exclusive subtree down without finishing (`close`), flip a node onto a finishing track in place (`demote`), or bring a dormant node back (`revive`). To merely SET the terminal/resident attribute headlessly use `node config --lifecycle`; to FINISH from inside a node's own turn use `crtr push final`; to mass-reconnect EVERY disconnected node at once use `canvas revive --all`.",help:{name:"node lifecycle",summary:"end, transition, or revive a node \u2014 recycle the pane, close + cascade-cancel a subtree, demote to terminal in place, or revive a dormant node",model:"Lifecycle actions preserve or replace an existing node identity. Finishing is permanent, closing is revivable, demotion changes the completion obligation in place, and revival relaunches a dormant broker. Teardown cascades only through descendants exclusively managed by the affected subtree."},children:[te,oe,ie,J]}),be=E({name:"yield",description:"refresh your context, same mode, against your roadmap or goal",whenToUse:"your context is filling but the mandate remains; refresh in the same mode, or combine the refresh with promotion when meaningful independent work can run in parallel and coordinating it should become your primary job",help:{name:"node yield",summary:"request a fresh context window against your roadmap or original goal; mode stays unchanged unless --promote is passed",guide:"The yield aborts your turn the instant this command returns: no text or tool call you planned after it will run. So anything the user is owed \u2014 an answer, a status \u2014 must already be a visible message in the conversation before you call it; never plan to reply after yielding. Before invoking: (1) If you hold a document `roadmap`, bring it current (`crtr doc edit roadmap`). It, not the yield note, carries your task into the fresh window. It has four sections: Goal (its first line is also the roadmap\u2019s preview, so set it with `--preview` whenever the goal changes), Exit criteria, Where things stand, and Working set. Keep it at your own level of abstraction. Detail below your level belongs to the node or document that holds it: link to it, don\u2019t copy it. Where things stand is present tense; delete what is done instead of marking it. Name units by what they are and how they fit, never by child node id or status: your bearings already list your children with their status. Working set holds `[[links]]`. Their previews load with the roadmap, so write no note beside a link. When a unit lands, delete its links: its evidence belongs in its report. (2) Give content its own document when it lives on a different timescale from the roadmap (exploration that outlives the current work), goes to a different reader (a brief for a child), or matters only when something specific happens. Link each such document from the Working set. Anything you had to re-derive in this window that a future window will need again belongs in a document: one you own for this task, `--owner repo` for lessons that would help others in the repo. A document that only points at other documents is not worth the extra hop. (3) Actions waiting on one specific event (\u201Cwhen X reports, send Y first\u201D) go in the yield note, not the roadmap. They are spent once they fire. (4) Send any pending human question; asks already in flight survive the refresh.",params:[{kind:"flag",name:"promote",type:"bool",required:!1,constraint:"Also become an orchestrator as you refresh. Pass only when (1) the remaining work contains independent units that can run in parallel and (2) the task is large enough that parallel execution will materially improve intelligence, productivity, or elapsed throughput after coordination and synthesis. Task length, context exhaustion, sequential phases, or one helper are not enough; keep hands-on work in base mode and yield again as needed. Promote when coordinating and integrating children becomes your primary job. Already an orchestrator? This is not an error: your mode stays orchestrator and a missing roadmap is seeded."},{kind:"flag",name:"kind",type:"string",required:!1,constraint:"Respecialize as you refresh. The <kinds> list below names every top-level available kind and when to choose it; a registered sub-kind is valid too by exact path but not listed here. Defaults to your current kind. With --promote it sets the orchestrator kind you become; without --promote it changes the kind while preserving your current mode."},{kind:"flag",name:"model",type:"enum",choices:["ultra","strong"],required:!1,constraint:"Change the model your fresh revive runs on, by capability tier: `ultra` (frontier \u2014 reserve for high-taste judgment or enormous work: speccing, planning something large, e2e-testing something hard to test) or `strong` (opus \u2014 regular dev work). Omit to keep your current model. A node steering work is never weaker than opus, so these are the only two choices; the change is durable across future revives."},{kind:"stdin",name:"message",required:!0,constraint:"A note to your future self \u2014 what you just tried, where things stand, the first move on waking, and any action waiting on a specific event: enough to continue efficiently, no more. Never describe a reply as sent unless it is visible in the conversation above this call. Your task and its state belong in the roadmap. Surfaced as <yield-message> in the next revive. Pass as a positional or pipe via heredoc."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The yielding node."},{name:"model",type:"string",required:!1,constraint:"The model tier your fresh revive will run on, present only when you changed it with --model."}],outputKind:"object",effects:["Aborts your current turn as soon as this command returns \u2014 nothing after it runs \u2014 then the daemon revives the node fresh.","--kind and/or --model durably reshape the node (kind respecialization, model change) before the refresh-revive; --promote additionally flips mode\u2192orchestrator and creates your document `roadmap` \u2014 mode is otherwise left exactly as it was."]},helpState:{leaf:C},run:u(async e=>{const t=D();if(t===void 0||t==="")throw new r({error:"no_node",message:"no node to yield (CRTR_NODE_ID unset)",next:"Run from inside a node."});const n=e.kind,i=e.model,d=e.promote===!0,o=typeof e.message=="string"?e.message.trim():"";if(o==="")throw new r({error:"empty_message",message:"a yield message is required (stdin or positional)",next:"Pass a note to your future self as an argument or pipe it on stdin."});const h=await w().yieldNode(t,{note:o,...n!==void 0?{kind:n}:{},...i!==void 0?{model:i}:{},...d?{promote:!0}:{}}).catch(f=>y(f));return{node_id:h.node_id,...i!==void 0&&h.model_override!=null?{model:h.model_override}:{}}},"run")});export{ye as nodeConfig,ke as nodeLifecycle,ve as nodePromote,be as nodeYield};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
2
|
-
`)},"render")});export{
|
|
1
|
+
var f=Object.defineProperty;var s=(o,n)=>f(o,"name",{value:n,configurable:!0});import{envNodeId as h}from"../shared/env.js";import{spawnSync as x}from"node:child_process";import{existsSync as l,mkdirSync as v,mkdtempSync as b,readdirSync as y,rmSync as g,symlinkSync as w}from"node:fs";import{contextDir as T}from"../core/canvas/paths.js";import{tmpdir as _}from"node:os";import{dirname as S,join as a}from"node:path";import{defineLeaf as $}from"../core/command.js";import{InputError as m}from"../core/io.js";import{nvimArgs as D,nvimAvailable as R}from"../core/nvim-launch.js";import{cliClient as p,rethrowAsCliError as C}from"./api-client.js";function u(o){return o.replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"node"}s(u,"sanitize");async function I(o){const n=await p().getContext(o),t=[];for(const e of n.roots){const r=await p().getNode(e.node_id).catch(()=>null),i=e.node_id.slice(0,8),c=e.self?`self-${u(e.label)}`:`${u(e.label)}-${i}`,d=r===null?"":T(e.node_id,r.grantee);if(!l(d)){t.push({nodeId:e.node_id,label:c,dir:`${e.node_id}/context (not on this machine)`,self:e.self,fileCount:0,contextDir:""});continue}t.push({nodeId:e.node_id,label:c,dir:S(d),self:e.self,fileCount:(()=>{try{return y(d).length}catch{return 0}})(),contextDir:d})}return t}s(I,"resolveRoots");function N(o){const n=b(a(_(),"crtr-context-"));for(const t of o){const e=t.self?`0-${t.label}`:t.label,r=a(n,e);v(r,{recursive:!0});try{l(t.contextDir)&&w(t.contextDir,a(r,"context"),"dir")}catch{}}return n}s(N,"buildSymlinkTree");const U=$({name:"context",description:"browse this node + its subscriptions\u2019 context dirs in an nvim popup",whenToUse:"you want to SEE what the nodes you subscribe to have written \u2014 open a read-only nvim file explorer over this node\u2019s context dir and every subscribed node\u2019s context dir at once (reports are documents: `crtr canvas read <node>/reports/<name>`). The /context popup shells this. Piped it prints the roster instead",help:{name:"node inspect context",summary:"open a read-only nvim file explorer over this node\u2019s context dir and those of every node it subscribes to",params:[{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node id to root on. Defaults to $CRTR_NODE_ID (the calling node)."}],output:[{name:"roots",type:"object[]",required:!0,constraint:"Resolved browse roots: {node_id, label, dir, self, files}. Returned on the piped/non-TTY path."}],outputKind:"object",effects:["TTY: builds a temp dir of labelled node dirs, symlinking each available `context` dir inside it, then execs `nvim -R` on the tree; the temp links are removed on exit (real dirs untouched).","Requires nvim on PATH (a crtr strong dependency). Missing nvim -> error with an install hint.","Non-TTY / piped: prints the resolved roster and exits 0; opens nothing."]},run:s(async o=>{const n=o.node?.trim()||h();if(n===void 0||n==="")throw new m({error:"no_node",message:"no current node: $CRTR_NODE_ID is unset and --node was not given",field:"node",next:"Run this from inside a canvas node (the /context popup does), or pass --node <id>."});let t;try{t=await I(n)}catch(i){C(i)}const e=t.map(i=>({node_id:i.nodeId,label:i.label,dir:i.dir,self:i.self,files:i.fileCount}));if(!process.stdout.isTTY)return{roots:e};if(!R())throw new m({error:"nvim_missing",message:"nvim is not on PATH \u2014 `crtr node inspect context` opens the context explorer in nvim",next:"Install Neovim (macOS: `brew install neovim`; Debian/Ubuntu: `apt install neovim`), then retry."});const r=N(t);try{x("nvim",[...D("readonly"),"."],{cwd:r,stdio:"inherit"})}finally{g(r,{recursive:!0,force:!0})}return{roots:e}},"run"),render:s(o=>{const n=o.roots??[];if(n.length===0)return"No node dirs to show (no subscriptions with written context or reports, and this node\u2019s own context dir is empty/absent).";const t=n.map(e=>{const r=e.self===!0?" (self)":"";return` ${String(e.label)}${r} ${String(e.files)} files ${String(e.dir)}`});return[`Context roots (${n.length}):`,...t].join(`
|
|
2
|
+
`)},"render")});export{U as nodeContextLeaf};
|
|
@@ -6,3 +6,8 @@ export declare function contextDir(nodeId: string, grantee?: string): Promise<st
|
|
|
6
6
|
export declare function reportsDir(nodeId: string, grantee?: string): Promise<string>;
|
|
7
7
|
export declare function interpolateNodePaths(text: string, nodeId: string): Promise<string>;
|
|
8
8
|
export declare function ensureNodeDirs(nodeId: string, grantee?: string): Promise<void>;
|
|
9
|
+
/** The node folder paths a lifecycle-hook payload names. A pod hosts no broker, so it hands out the tokens the broker host expands; any process that hosts the node names the real paths. */
|
|
10
|
+
export declare function hookNodePaths(nodeId: string): Promise<{
|
|
11
|
+
nodeDir: string;
|
|
12
|
+
contextDir: string;
|
|
13
|
+
}>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var c=Object.defineProperty;var e=(r,t)=>c(r,"name",{value:t,configurable:!0});import{areEnginesInProcess as a,isCloudRole as i}from"./person-state.js";import{join as p}from"node:path";import{envGrantee as u,envNodeId as f}from"../../shared/env.js";import{openDb as D}from"./db.js";import{nodeAgentDir as w,ensureNodeDirs as m,interpolateNodePaths as x}from"./paths.js";async function s(r){const t=u();if(f()===r&&t)return t;const o=await(await D()).prepare("SELECT grantee FROM node_rows WHERE node_id = ?").get(r);if(!o?.grantee)throw new Error(`node ${r} has no app assignment`);return o.grantee}e(s,"appForNode");async function n(r,t){return w(r,t??await s(r))}e(n,"nodeAgentDir");async function g(r,t){return p(await n(r,t),"context")}e(g,"contextDir");async function A(r,t){return p(await n(r,t),"reports")}e(A,"reportsDir");async function _(r,t){return x(r,t)}e(_,"interpolateNodePaths");async function l(r,t){i()&&!a()||m(r,t??await s(r))}e(l,"ensureNodeDirs");async function C(r){return i()&&!a()?{nodeDir:"$CRTR_NODE_DIR",contextDir:"$CRTR_CONTEXT_DIR"}:{nodeDir:await n(r),contextDir:await g(r)}}e(C,"hookNodePaths");export{s as appForNode,g as contextDir,l as ensureNodeDirs,C as hookNodePaths,_ as interpolateNodePaths,n as nodeAgentDir,A as reportsDir};
|
|
@@ -45,16 +45,9 @@ export declare const BROKER_RELAY_GENERATION = "cli-relay-generation";
|
|
|
45
45
|
/** The run's scope allow-list as a JSON array, beside `broker-launch.json`. */
|
|
46
46
|
export declare function scopesFilePath(nodeId: string): string;
|
|
47
47
|
export declare function contextDir(nodeId: string, grantee?: string): string;
|
|
48
|
-
/** Replace the literal
|
|
49
|
-
*
|
|
50
|
-
|
|
51
|
-
* env vars only expand in bash; an agent that pastes `$CRTR_CONTEXT_DIR/x.md`
|
|
52
|
-
* into the (non-expanding) Write tool creates a literal `$CRTR_CONTEXT_DIR/`
|
|
53
|
-
* dir under the project repo. The resolved absolute path works in both bash and
|
|
54
|
-
* Write, so this substitution is strictly safer. Callers must only apply it
|
|
55
|
-
* when they have a concrete node to render for (never on generic, node-less
|
|
56
|
-
* output). Pure string work — no I/O. */
|
|
57
|
-
export declare function interpolateNodePaths(text: string, nodeId: string, grantee?: string): string;
|
|
48
|
+
/** Replace the literal token `$CRTR_NODE_ID` in agent-facing doc text with the node's id. `$CRTR_CONTEXT_DIR` stays a token: only the machine hosting the
|
|
49
|
+
* node's broker knows its path, and the broker expands it (`expandHostPathTokens`) before the text reaches the model. Pure string work — no I/O. */
|
|
50
|
+
export declare function interpolateNodePaths(text: string, nodeId: string): string;
|
|
58
51
|
export declare function jobDir(nodeId: string): string;
|
|
59
52
|
export declare function nodeRunJobDir(nodeId: string): string;
|
|
60
53
|
/** Overflow store for inbox entries whose inline body exceeds the digest's
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var v=Object.defineProperty;var e=(t,n)=>v(t,"name",{value:n,configurable:!0});import{join as r}from"node:path";import{mkdirSync as c}from"node:fs";import{appSpace as f,runtimeRoot as k,socketDir as m}from"../layout.js";import{envGrantee as E,envNodeId as P}from"../../shared/env.js";import{withDirBeneath as h}from"../spaces/open-beneath.js";function i(){return k()}e(i,"crtrHome");function
|
|
1
|
+
var v=Object.defineProperty;var e=(t,n)=>v(t,"name",{value:n,configurable:!0});import{join as r}from"node:path";import{mkdirSync as c}from"node:fs";import{appSpace as f,runtimeRoot as k,socketDir as m}from"../layout.js";import{envGrantee as E,envNodeId as P}from"../../shared/env.js";import{withDirBeneath as h}from"../spaces/open-beneath.js";function i(){return k()}e(i,"crtrHome");function L(){return r(i(),"canvas.db")}e(L,"canvasDbPath");function O(){return r(i(),"on-disk-migration.lock")}e(O,"onDiskMigrationLockPath");function T(){return r(i(),"on-disk-migrations.json")}e(T,"onDiskMigrationMarkerPath");function H(t){return r(s(t),"view.sock")}e(H,"viewSocketPath");function D(){return r(i(),"nodes")}e(D,"nodesRoot");function b(){return r(i(),"reviews")}e(b,"reviewsRoot");function l(t){return p(t),r(b(),t)}e(l,"reviewDir");function C(t){return r(l(t),"result.json")}e(C,"reviewResultPath");function K(t){c(l(t),{recursive:!0,mode:448})}e(K,"ensureReviewDir");function F(){return r(m(),"api.sock")}e(F,"apiSocketPath");function G(){return r(i(),"session-list-cache.json")}e(G,"sessionListCachePath");const j=128;function w(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!/[\\/\0]/u.test(t)&&Buffer.byteLength(t,"utf8")<=j}e(w,"isSafeNodeId");function p(t){if(!w(t))throw new TypeError("node_id must be a non-empty path segment of at most 128 UTF-8 bytes")}e(p,"assertSafeNodeId");function a(t){return p(t),r(D(),t)}e(a,"nodeRecordDir");const u=a;function x(t,n){p(t);const o=n??(P()===t?E():void 0);if(!o)throw new Error(`node ${t} has no app assignment`);return r(f(o).nodes,t)}e(x,"nodeAgentDir");function g(t,n){return r(x(t,n),"home")}e(g,"isolatedNodeHome");function Y(t,n,o){return o?g(t,n):f(n).home}e(Y,"nodeHome");function s(t){return p(t),process.platform==="linux"?r(m(),"nodes",t):r(a(t),"run")}e(s,"nodeRunDir");const $="broker-released",J="cli-relay-generation";function U(t){return r(s(t),"scopes.json")}e(U,"scopesFilePath");function X(t,n){return r(x(t,n),"context")}e(X,"contextDir");function q(t,n){return t.replaceAll("$CRTR_NODE_ID",n)}e(q,"interpolateNodePaths");function N(t){return r(a(t),"job")}e(N,"jobDir");function _(t){return r(s(t),"job")}e(_,"nodeRunJobDir");function z(t){return r(u(t),"messages")}e(z,"messagesDir");function Q(t){return r(u(t),"meta.json")}e(Q,"nodeMetaPath");function V(t){return r(u(t),"inbox.jsonl")}e(V,"inboxPath");function W(t){return r(s(t),"situational-context.md")}e(W,"situationalContextPath");function Z(t){return r(u(t),"passive.jsonl")}e(Z,"passivePath");function I(t){return r(u(t),"transcript.jsonl")}e(I,"transcriptPath");function tt(t,n){const o=x(t,n);c(a(t),{recursive:!0}),c(N(t),{recursive:!0});for(const R of["context","reports","attachments","worktree"])h(f(n).nodes,r(o,R),()=>{},!0);h(s(t),_(t),()=>{},!0)}e(tt,"ensureNodeDirs");function et(){c(D(),{recursive:!0})}e(et,"ensureHome");export{J as BROKER_RELAY_GENERATION,$ as BROKER_RELEASED_MARKER,F as apiSocketPath,L as canvasDbPath,X as contextDir,i as crtrHome,et as ensureHome,tt as ensureNodeDirs,K as ensureReviewDir,V as inboxPath,q as interpolateNodePaths,w as isSafeNodeId,g as isolatedNodeHome,N as jobDir,z as messagesDir,x as nodeAgentDir,u as nodeDir,Y as nodeHome,Q as nodeMetaPath,a as nodeRecordDir,s as nodeRunDir,_ as nodeRunJobDir,D as nodesRoot,O as onDiskMigrationLockPath,T as onDiskMigrationMarkerPath,Z as passivePath,l as reviewDir,C as reviewResultPath,b as reviewsRoot,U as scopesFilePath,G as sessionListCachePath,W as situationalContextPath,I as transcriptPath,H as viewSocketPath};
|
|
@@ -4,4 +4,4 @@ var Y=Object.defineProperty;var u=(t,e)=>Y(t,"name",{value:e,configurable:!0});i
|
|
|
4
4
|
`)}u(bt,"renderForestFromSource");const E=4096;function O(t){try{const e=K(U(t),R(t,"initial-prompt.md"))?.trim()??"";return e===""?void 0:e.length>E?e.slice(0,E):e}catch{return}}u(O,"readGoalText");const F=1024;function nt(t){if(t==null)return;const e=t.tier,i=t.created,n=t.body,r=n.split(`
|
|
5
5
|
`);let s="",c=n;for(let l=0;l<r.length;l++){const o=(r[l]??"").trim();if(o!==""){s=o.startsWith("#")?o.replace(/^#+\s*/,"").trim():o,c=r.slice(l+1).join(`
|
|
6
6
|
`);break}}const a=c.replace(/\s+/g," ").trim();return{kind:e,ts:i,heading:s,body:a.length>F?a.slice(0,F):a}}u(nt,"reportPreview");const it=[262144,1<<20,4<<20],rt=65536,st=65536;async function M(t,e,i){if(t==null||t==="")return null;const n=v(t);if(n===null)return null;try{const{entries:r,tail:s}=await J(n,{head:e,tail:i});return{head:r,tail:s??r,windowed:s!==void 0}}catch(r){if(r instanceof N)return null;throw r}}u(M,"readSessionWindow");const b=8192,k=2048;async function at(t){const e=await M(t,rt,st);if(e===null)return;const i=[];let n=0;for(const s of e.windowed?[...e.head,...e.tail]:e.head){if(s.type!=="message"||s.message.role!=="user")continue;const c=D(s.message.content);if(c===""||C({role:"user",content:c})!==null)continue;const a=c.length>k?c.slice(0,k):c;if(i.push(a),n+=a.length+1,n>=b)break}if(i.length===0)return;const r=i.join(`
|
|
7
|
-
`);return r.length>b?r.slice(0,b):r}u(at,"readSessionPrompts");const j=120,z=4096;async function ot(t){let e={transcript:[]};for(const i of it){const n=await M(t,0,i);if(n===null||(e=ct(n.tail),!n.windowed||e.lastAssistant!==void 0))return e}return e}u(ot,"readSessionTail");function ct(t){const e=[];let i;for(const n of t){if(n.type!=="message")continue;const r=n.message.role;if(r!=="user"&&r!=="assistant")continue;const s=D(n.message.content);s!==""&&(r==="assistant"&&(i=s.length>k?s.slice(0,k):s),C({role:r,content:s})===null&&e.push({role:r,text:s.length>z?s.slice(0,z):s}))}return{transcript:e.length>j?e.slice(e.length-j):e,...i===void 0?{}:{lastAssistant:i}}}u(ct,"sessionTailFrom");async function vt(t){if(t==null||t==="")return!1;const e=v(t);if(e===null)return!1;let i;try{i=(await H().read(e)).entries}catch(n){if(n instanceof N)return!1;throw n}for(const n of i)if(!(n.type!=="message"||n.message.role!=="assistant")&&ut(n.message.content))return!0;return!1}u(vt,"nodeHasAssistantMessage");function ut(t){if(typeof t=="string")return t.trim()!=="";if(!Array.isArray(t))return!1;for(const e of t){if(e===null||typeof e!="object")continue;const i=e,n=(i.type??"").toLowerCase();if(n==="text"){if(typeof i.text=="string"&&i.text.trim()!=="")return!0}else if(n==="thinking"){if(typeof i.thinking=="string"&&i.thinking.trim()!=="")return!0}else return!0}return!1}u(ut,"assistantContentIsSubstantive");function D(t){if(typeof t=="string")return t.trim();if(!Array.isArray(t))return"";const e=[];for(const i of t)if(i!==null&&typeof i=="object"){const n=i;n.type==="text"&&typeof n.text=="string"&&e.push(n.text)}return e.join(" ").trim()}u(D,"extractUserText");function lt(t,e,i=!1){if(!i&&e!==null&&e!==void 0){const r=Date.parse(e);if(!Number.isNaN(r))return r}const n=Date.parse(t);return Number.isNaN(n)?0:n}u(lt,"sessionMtime");function ft(t){if(t.status!=="active")return!1;try{const e=JSON.parse(q(Q(t.node_id),R(X(t.node_id),"attach.json")).toString("utf8"));return typeof e.viewers=="number"&&e.viewers>0}catch{return!1}}u(ft,"hasLiveBrokerViewer");function dt(t,e,i){const n=t.status==="active"||t.status==="idle",r=t.fault??null;return{node_id:t.node_id,name:S(t),handle:t.name,description:t.description,status:t.status,frozen_at:t.frozen_at??null,terminal_reason:t.terminal_reason??null,kind:t.kind,mode:t.mode,ctx_tokens:i?0:t.telemetry_tokens_in??0,asks:0,cwd:t.cwd,profile_id:t.profile_id,created:t.created,lifecycle:t.lifecycle,finalized:t.final_report!=null,mtimeMs:lt(t.created,t.telemetry_updated_at,i),streaming:r===null&&n&&t.streaming===!0,hanging:r,viewed:i?!1:e.has(t.node_id)||ft(t),srcRow:t}}u(dt,"dashboardRowFromNodeRow");async function Nt(t,e,i,n){const r=t instanceof y,s=n??await t.ticketCountsForView(e).catch(()=>({})),c=new Map((i??await t.listNodes()).map(l=>[l.node_id,l]));return[e,...await t.view(e)].flatMap(l=>{const o=c.get(l);return o===void 0?[]:[{node_id:l,name:S(o),handle:o.name,description:o.description,status:o.status,frozen_at:o.frozen_at??null,terminal_reason:o.terminal_reason??null,kind:o.kind,mode:o.mode,ctx_tokens:r?0:o.telemetry_tokens_in??0,asks:s[l]??0,cwd:o.cwd,profile_id:o.profile_id,created:o.created}]})}u(Nt,"dashboardRowsFromSource");async function Rt(t,e=new Set,i=!1,n){const r=t instanceof y,s=r?new Set:e;return(n??await t.listNodes(i?{status:["active","idle"]}:void 0)).map(a=>dt(a,s,r))}u(Rt,"dashboardRowsAllFromSource");async function Tt(t,e,i){const n=e.filter(s=>s.enriched!==!0);if(n.length===0)return;const r=i??{};for(const s of n)s.asks=r[s.node_id]??0,s.enriched=!0}u(Tt,"enrichRowsFromSource");async function B(t,e,i){const n=
|
|
7
|
+
`);return r.length>b?r.slice(0,b):r}u(at,"readSessionPrompts");const j=120,z=4096;async function ot(t){let e={transcript:[]};for(const i of it){const n=await M(t,0,i);if(n===null||(e=ct(n.tail),!n.windowed||e.lastAssistant!==void 0))return e}return e}u(ot,"readSessionTail");function ct(t){const e=[];let i;for(const n of t){if(n.type!=="message")continue;const r=n.message.role;if(r!=="user"&&r!=="assistant")continue;const s=D(n.message.content);s!==""&&(r==="assistant"&&(i=s.length>k?s.slice(0,k):s),C({role:r,content:s})===null&&e.push({role:r,text:s.length>z?s.slice(0,z):s}))}return{transcript:e.length>j?e.slice(e.length-j):e,...i===void 0?{}:{lastAssistant:i}}}u(ct,"sessionTailFrom");async function vt(t){if(t==null||t==="")return!1;const e=v(t);if(e===null)return!1;let i;try{i=(await H().read(e)).entries}catch(n){if(n instanceof N)return!1;throw n}for(const n of i)if(!(n.type!=="message"||n.message.role!=="assistant")&&ut(n.message.content))return!0;return!1}u(vt,"nodeHasAssistantMessage");function ut(t){if(typeof t=="string")return t.trim()!=="";if(!Array.isArray(t))return!1;for(const e of t){if(e===null||typeof e!="object")continue;const i=e,n=(i.type??"").toLowerCase();if(n==="text"){if(typeof i.text=="string"&&i.text.trim()!=="")return!0}else if(n==="thinking"){if(typeof i.thinking=="string"&&i.thinking.trim()!=="")return!0}else return!0}return!1}u(ut,"assistantContentIsSubstantive");function D(t){if(typeof t=="string")return t.trim();if(!Array.isArray(t))return"";const e=[];for(const i of t)if(i!==null&&typeof i=="object"){const n=i;n.type==="text"&&typeof n.text=="string"&&e.push(n.text)}return e.join(" ").trim()}u(D,"extractUserText");function lt(t,e,i=!1){if(!i&&e!==null&&e!==void 0){const r=Date.parse(e);if(!Number.isNaN(r))return r}const n=Date.parse(t);return Number.isNaN(n)?0:n}u(lt,"sessionMtime");function ft(t){if(t.status!=="active")return!1;try{const e=JSON.parse(q(Q(t.node_id),R(X(t.node_id),"attach.json")).toString("utf8"));return typeof e.viewers=="number"&&e.viewers>0}catch{return!1}}u(ft,"hasLiveBrokerViewer");function dt(t,e,i){const n=t.status==="active"||t.status==="idle",r=t.fault??null;return{node_id:t.node_id,name:S(t),handle:t.name,description:t.description,status:t.status,frozen_at:t.frozen_at??null,terminal_reason:t.terminal_reason??null,kind:t.kind,mode:t.mode,ctx_tokens:i?0:t.telemetry_tokens_in??0,asks:0,cwd:t.cwd,profile_id:t.profile_id,created:t.created,lifecycle:t.lifecycle,finalized:t.final_report!=null,mtimeMs:lt(t.created,t.telemetry_updated_at,i),streaming:r===null&&n&&t.streaming===!0,hanging:r,viewed:i?!1:e.has(t.node_id)||ft(t),srcRow:t}}u(dt,"dashboardRowFromNodeRow");async function Nt(t,e,i,n){const r=t instanceof y,s=n??await t.ticketCountsForView(e).catch(()=>({})),c=new Map((i??await t.listNodes()).map(l=>[l.node_id,l]));return[e,...await t.view(e)].flatMap(l=>{const o=c.get(l);return o===void 0?[]:[{node_id:l,name:S(o),handle:o.name,description:o.description,status:o.status,frozen_at:o.frozen_at??null,terminal_reason:o.terminal_reason??null,kind:o.kind,mode:o.mode,ctx_tokens:r?0:o.telemetry_tokens_in??0,asks:s[l]??0,cwd:o.cwd,profile_id:o.profile_id,created:o.created}]})}u(Nt,"dashboardRowsFromSource");async function Rt(t,e=new Set,i=!1,n){const r=t instanceof y,s=r?new Set:e;return(n??await t.listNodes(i?{status:["active","idle"]}:void 0)).map(a=>dt(a,s,r))}u(Rt,"dashboardRowsAllFromSource");async function Tt(t,e,i){const n=e.filter(s=>s.enriched!==!0);if(n.length===0)return;const r=i??{};for(const s of n)s.asks=r[s.node_id]??0,s.enriched=!0}u(Tt,"enrichRowsFromSource");async function B(t,e,i){const n=e.srcRow?.grantee??(await t.getRow(e.node_id))?.grantee;if(!n)throw new Error(`node ${e.node_id} has no app assignment`);return Z(e.node_id,n)}u(B,"contextPathOf");async function wt(t,e,i={}){const n=i.transcript===!0&&e.transcriptLoaded!==!0;if(e.previewLoaded===!0&&!n)return e;if(t instanceof y)return e.previewLoaded=!0,n&&(e.transcript=[],e.transcriptLoaded=!0),e;const r=await t.getNode(e.node_id),s=await ot(r?.pi_session_file);return e.previewLoaded!==!0&&(e.goal??=O(await B(t,e,r)),e.lastAssistant=s.lastAssistant,e.recap=I(e.node_id),e.report=nt(await t.newestReport?.(e.node_id).catch(()=>null)),e.previewLoaded=!0),n&&(e.transcript=s.transcript,e.transcriptLoaded=!0),e}u(wt,"loadPreviewFromSource");async function At(t,e){if(e.promptsLoaded===!0)return e;if(!(t instanceof y)){const i=await t.getNode(e.node_id);e.goal??=O(await B(t,e,i)),e.prompts=await at(i?.pi_session_file)}return e.promptsLoaded=!0,e}u(At,"loadSearchTextFromSource");export{dt as dashboardRowFromNodeRow,Rt as dashboardRowsAllFromSource,Nt as dashboardRowsFromSource,Tt as enrichRowsFromSource,P as fmtCtx,wt as loadPreviewFromSource,At as loadSearchTextFromSource,vt as nodeHasAssistantMessage,O as readGoalText,at as readSessionPrompts,ot as readSessionTail,bt as renderForestFromSource,et as renderTreeFromSource,nt as reportPreview,lt as sessionMtime};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var ue=Object.defineProperty;var u=(e,t)=>ue(e,"name",{value:t,configurable:!0});import{createHash as x}from"node:crypto";import{closeSync as H,constants as le,createWriteStream as ce}from"node:fs";import{basename as fe,extname as pe,isAbsolute as he,join as F}from"node:path";import{Transform as we,Writable as _e}from"node:stream";import{pipeline as N}from"node:stream/promises";import{appSpace as W}from"../layout.js";import{RunError as T}from"../runs/operations.js";import{createFileBeneath as ge,existsBeneath as P,openBeneath as ye,removeTreeBeneath as I,setModeBeneath as me,unlinkBeneath as be,withDirBeneath as $e}from"../spaces/open-beneath.js";import{ensureAppSpace as ve}from"../spaces/space.js";import{isCloudRole as O}from"../canvas/person-state.js";import{invalidStorageName as X,storageClient as B,StorageRefused as z,UPLOAD_MAX_BYTES as j}from"../storage/client.js";import{openCallerFile as Se}from"../storage/caller-file.js";import{contentTypeFor as Ee}from"../storage/media-types.js";import{withCanvasWrite as Y}from"../canvas/db.js";import{deleteUploadUse as G,getUpload as L,insertUpload as ze,insertUploadUses as J,setUploadSize as K,uploadUseAt as Ue}from"../storage/tables.js";import{ProviderError as s}from"./errors.js";const Ae=11e4,Ce="app:terminal";function Q(e){if(e.class==="person")return e.grantee??Ce;if(!e.grantee)throw new s("server_error","provider caller has no grantee");return e.grantee}u(Q,"grantee");function Re(e){if(e.class==="person"&&e.sub)throw new s("invalid_request","the control plane cannot read files from your computer, so a file argument cannot be sent from here");return e.class==="person"?null:{app:Q(e),resolved:e.resolved??[],launched:e.class==="broker"?e.nodeScopes:null}}u(Re,"fileCaller");function m(e){return e instanceof s?e:e instanceof z?new s("storage_unavailable",`storage refused: ${e.message}`):e instanceof T&&e.code==="storage_unavailable"&&e.retryable?new s("storage_unavailable",e.message):e}u(m,"storageFailure");const S=u(e=>new s("provider_error",e,{origin:"provider"}),"providerError");function Fe(e,t,o){if(typeof o!="string"||!o||!he(o)||o.includes("\0"))throw new s("invalid_request",`${t} must be an absolute runtime path`,{param:t});let a;try{a=Se(Re(e),o)}catch(i){throw i instanceof T?i.code==="scope_missing"?new s("scope_missing",i.message,{param:t,...i.scope?{scope:i.scope}:{}}):i.code==="not_found"||i.code==="invalid_request"?new s("not_found",`no such file: ${o}`,{param:t}):i:i}try{if(a.size>j)throw new s("invalid_request",`${t} exceeds 100 MiB`,{param:t});const i=fe(a.path),n=X(i);if(n)throw new s("invalid_request",`${t}: file name cannot be sent: ${n}`,{param:t});return{param:t,file:a,name:i,mediaType:Ee(a.path)}}catch(i){throw H(a.fd),i}}u(Fe,"checkFileArgument");async function Te(e,t){try{const o=await e.createOutbound({name:t.name,size:t.file.size,media_type:t.mediaType});await e.putFileBytes(o.upload_link,t.file.fd,t.file.size,t.mediaType);const a=await e.signOutbound(o.object_id);return{param:t.param,path:t.file.path,name:t.name,object_id:o.object_id,url:a.url}}catch(o){throw m(o)}}u(Te,"copyOutbound");function Oe(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=Object.keys(e),o=e.upload_id;return t.length===1&&typeof o=="string"&&o!==""?o:null}u(Oe,"uploadRef");async function Be(e,t,o,a){if(!O())throw new s("invalid_request",`${t} must be an absolute runtime path`,{param:t});const i=await L(o);if(!i||i.delete_pending_since||i.grantee!==e.grantee||i.sub!==null&&i.sub!==(e.sub??null))throw new s("not_found",`no such upload: ${o}`,{param:t});try{const n=await a().signDownload(o);return{param:t,path:"",name:i.name,object_id:o,upload_id:o,url:n.url}}catch(n){throw n instanceof z?new s("not_found",`upload ${o} holds no bytes`,{param:t}):m(n)}}u(Be,"uploadArgument");async function V(e,t,o,a){const i=[],n=[];try{for(const r of t){if(o[r]===void 0||o[r]===null)continue;const f=Oe(o[r]);if(f!==null){n.push(await Be(e,r,f,a));continue}i.push(Fe(e,r,o[r]))}if(!i.length)return n;let c;try{c=a()}catch(r){throw m(r)}const d=[...n];for(const r of i)d.push(await Te(c,r));return d}finally{for(const c of i)H(c.file.fd)}}u(V,"copyArguments");function Z(e){const t=X(e);if(t)throw new s("server_error",`file output ${e} cannot name an upload: ${t}`)}u(Z,"checkOutputField");async function ee(e,t,o){Z(t);const a=Q(e),i="application/octet-stream";let n;try{n=await o().createResultUpload({name:t,media_type:i,max_size:j})}catch(c){throw m(c)}return await ze({upload_id:n.upload_id,grantee:a,...O()&&e.sub?{sub:e.sub}:{},name:t,media_type:i,size:j,created_at:new Date().toISOString()}),{field:t,upload_id:n.upload_id,upload_link:n.upload_link,grantee:a}}u(ee,"createResultUpload");function te(e){return e?{"Crtr-Upload-Id":e.upload_id,"Crtr-Upload-Link":e.upload_link}:{}}u(te,"uploadHeaders");function oe(e,t){const o={...e};for(const a of t)o[a.param]=a.url;return o}u(oe,"withUrls");async function et(e,t,o,a={}){const i=a.storage??B;t.output&&Z(t.output);const n=await V(e,t.params,o,i),c=t.output?await ee(e,t.output,i):null;return{arguments:oe(o,n),copies:n,upload:c,headers:te(c)}}u(et,"prepareFileCall");async function tt(e,t,o,a,i={}){const n=i.storage??B,c=[];for(const r of a.copies)try{const f=r.upload_id?await n().signDownload(r.upload_id):await n().signOutbound(r.object_id);c.push({...r,url:f.url})}catch(f){if(!(f instanceof z))throw m(f);c.push(...await V(e,[r.param],o,n))}let d=a.upload;if(d)try{const r=await n().signUploadLink(d.upload_id);d={...d,upload_link:r.upload_link}}catch(r){if(!(r instanceof z))throw m(r);r.status===404&&(d=await ee(e,t.output??d.field,n))}return{arguments:oe(o,c),copies:c,upload:d,headers:te(d)}}u(tt,"resignForRetry");const je=/^[0-9a-f]{64}$/i;function Le(e,t){if(t===1)return e;const o=pe(e);return o&&o!==e?`${e.slice(0,-o.length)}-${t}${o}`:`${e}-${t}`}u(Le,"candidate");async function ot(e,t,o,a={}){const i={result:o,file:null,cleanup:u(async()=>{},"cleanup")},n=t.upload;if(!n||!o||typeof o!="object"||Array.isArray(o))return i;const c=o,d=c[n.field];if(d==null)return i;if(typeof d!="object"||Array.isArray(d))throw S(`${n.field} must be {upload_id, size, sha256}`);const r=d;if(typeof r.upload_id!="string"||typeof r.size!="number"||!Number.isSafeInteger(r.size)||r.size<0||typeof r.sha256!="string"||!je.test(r.sha256))throw S(`${n.field} must be {upload_id, size, sha256}`);if(r.upload_id!==n.upload_id)throw S(`${n.field} names an upload other than Crtr-Upload-Id`);const f=r.size,U=r.sha256.toLowerCase(),_=AbortSignal.timeout(a.budgetMs??Ae),E=a.signal?AbortSignal.any([_,a.signal]):_;let l;try{l=await(a.storage??B)().fetchUpload(n.upload_id,E)}catch(y){throw y instanceof z?S(`${n.field} names an upload with nothing stored`):m(y)}if(l.size===null)throw l.body.destroy(),new s("storage_unavailable",`storage did not say how many bytes ${n.field} holds`);if(l.size!==f)throw l.body.destroy(),S(`${n.field} claims ${f} bytes; storage holds ${l.size}`);if(O())return await De(e,n,c,r,l,E,_);const b=n.grantee,w=e.node_id!==null,ne=await ve(b),h=w?W(b).nodes:W(b).files,R=w?F(h,e.node_id):h,A=w?F(R,"attachments"):h,ie={uid:process.getuid?.()??0,gid:ne.gid},D=w&&!P(h,R),re=w&&!D&&!P(h,A);let g=null,C=null,k=!1;const q=u(async()=>{if(!k){if(k=!0,C)try{await G(C)}catch{}if(g)try{be(h,g)}catch{}try{D?I(h,R):re&&I(h,A)}catch{}}},"cleanup");try{$e(h,A,()=>{},!0);for(let p=1;;p++){const $=F(A,Le(n.field,p));if(!await Ue($))try{ge(h,$,Buffer.alloc(0),432),g=$;break}catch(v){if(v.code!=="EEXIST")throw v}}let y=0;const M=x("sha256"),ae=new we({transform(p,$,v){y+=p.length,M.update(p),v(null,p)}}),se=ye(h,g,le.O_WRONLY);try{await N(l.body,ae,ce("",{fd:se,autoClose:!0}),{signal:E})}catch(p){throw _.aborted?new s("storage_unavailable","the file result could not be fetched within 110 s"):p instanceof T?m(p):new s("storage_unavailable",`storage stopped sending ${n.field}: ${p instanceof Error?p.message:String(p)}`)}if(y!==f)throw new s("storage_unavailable",`storage sent ${y} of ${f} bytes of ${n.field}`);if(M.digest("hex")!==U)throw S(`${n.field}: the stored bytes do not match sha256`);me(h,g,432,ie);const de=g;await Y(async p=>{const $=await L(n.upload_id,p);if(!$||$.delete_pending_since)throw new s("not_found",`${n.field}: the upload was deleted while it was fetched`);if(await K(n.upload_id,f,p),!e.run_id)return;const v=await p.prepare("SELECT deleting_at FROM nodes WHERE node_id = ?").get(e.run_id);if(!v||v.deleting_at)throw new s("not_found",`run ${e.run_id} was deleted while its file result was fetched`);C={upload_id:n.upload_id,run_id:e.run_id,path:de},await J([C],p)})}catch(y){throw l.body.destroy(),await q(),y}return{result:{...c,[n.field]:g},file:{path:g,upload_id:n.upload_id},cleanup:q}}u(ot,"resolveFileResult");async function De(e,t,o,a,i,n,c){const d=a.size,r=a.sha256.toLowerCase();if(!e.run_id)throw i.body.destroy(),new s("invalid_request","a file result needs a node to deliver it to");const f=e.run_id,U=x("sha256");let _=0;try{await N(i.body,new _e({write(l,b,w){U.update(l),_+=l.length,w()}}),{signal:n})}catch(l){throw i.body.destroy(),c.aborted?new s("storage_unavailable","the file result could not be fetched within 110 s"):new s("storage_unavailable",`storage stopped sending ${t.field}: ${l instanceof Error?l.message:String(l)}`)}if(_!==d)throw new s("storage_unavailable",`storage sent ${_} of ${d} bytes of ${t.field}`);if(U.digest("hex")!==r)throw S(`${t.field}: the stored bytes do not match sha256`);const E={upload_id:t.upload_id,run_id:f,path:`upload:${t.upload_id}`};return await Y(async l=>{const b=await L(t.upload_id,l);if(!b||b.delete_pending_since)throw new s("not_found",`${t.field}: the upload was deleted while it was checked`);const w=await l.prepare("SELECT deleting_at FROM nodes WHERE node_id = ?").get(f);if(!w||w.deleting_at)throw new s("not_found",`run ${f} was deleted while its file result was checked`);await K(t.upload_id,d,l),await J([E],l)}),{result:{...o,[t.field]:{upload_id:t.upload_id,size:d,sha256:r}},file:{path:"",upload_id:t.upload_id},cleanup:u(async()=>{try{await G(E)}catch{}},"cleanup")}}u(De,"keepCloudResult");export{Ae as FILE_RESULT_FETCH_BUDGET_MS,et as prepareFileCall,tt as resignForRetry,ot as resolveFileResult};
|
|
1
|
+
var ue=Object.defineProperty;var u=(e,t)=>ue(e,"name",{value:t,configurable:!0});import{createHash as x}from"node:crypto";import{closeSync as H,constants as le,createWriteStream as ce}from"node:fs";import{basename as fe,extname as pe,isAbsolute as he,join as F}from"node:path";import{Transform as we,Writable as _e}from"node:stream";import{pipeline as N}from"node:stream/promises";import{appSpace as W}from"../layout.js";import{RunError as T}from"../runs/operations.js";import{createFileBeneath as ge,existsBeneath as P,openBeneath as ye,removeTreeBeneath as I,setModeBeneath as me,unlinkBeneath as be,withDirBeneath as $e}from"../spaces/open-beneath.js";import{ensureAppSpace as ve}from"../spaces/space.js";import{isCloudRole as O}from"../canvas/person-state.js";import{invalidStorageName as X,storageClient as B,StorageRefused as z,UPLOAD_MAX_BYTES as j}from"../storage/client.js";import{openCallerFile as Se}from"../storage/caller-file.js";import{contentTypeFor as Ee}from"../storage/media-types.js";import{withCanvasWrite as Y}from"../canvas/db.js";import{deleteUploadUse as G,getUpload as L,insertUpload as ze,insertUploadUses as J,setUploadSize as K,uploadUseAt as Ue}from"../storage/tables.js";import{ProviderError as s}from"./errors.js";const Ae=11e4,Ce="app:terminal";function Q(e){if(e.class==="person")return e.grantee??Ce;if(!e.grantee)throw new s("server_error","provider caller has no grantee");return e.grantee}u(Q,"grantee");function Re(e){if(e.class==="person"&&e.sub)throw new s("invalid_request","the control plane cannot read files from your computer, so a file argument cannot be sent from here");return e.class==="person"?null:{app:Q(e),resolved:e.resolved??[],launched:e.class==="broker"?e.nodeScopes:null}}u(Re,"fileCaller");function m(e){return e instanceof s?e:e instanceof z?new s("storage_unavailable",`storage refused: ${e.message}`):e instanceof T&&e.code==="storage_unavailable"&&e.retryable?new s("storage_unavailable",e.message):e}u(m,"storageFailure");const S=u(e=>new s("provider_error",e,{origin:"provider"}),"providerError");function Fe(e,t,n){if(typeof n!="string"||!n||!he(n)||n.includes("\0"))throw new s("invalid_request",`${t} must be an absolute runtime path`,{param:t});let a;try{a=Se(Re(e),n)}catch(i){throw i instanceof T?i.code==="scope_missing"?new s("scope_missing",i.message,{param:t,...i.scope?{scope:i.scope}:{}}):i.code==="not_found"||i.code==="invalid_request"?new s("not_found",`no such file: ${n}`,{param:t}):i:i}try{if(a.size>j)throw new s("invalid_request",`${t} exceeds 100 MiB`,{param:t});const i=fe(a.path),o=X(i);if(o)throw new s("invalid_request",`${t}: file name cannot be sent: ${o}`,{param:t});return{param:t,file:a,name:i,mediaType:Ee(a.path)}}catch(i){throw H(a.fd),i}}u(Fe,"checkFileArgument");async function Te(e,t){try{const n=await e.createOutbound({name:t.name,size:t.file.size,media_type:t.mediaType});await e.putFileBytes(n.upload_link,t.file.fd,t.file.size,t.mediaType);const a=await e.signOutbound(n.object_id);return{param:t.param,path:t.file.path,name:t.name,object_id:n.object_id,url:a.url}}catch(n){throw m(n)}}u(Te,"copyOutbound");function Oe(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=Object.keys(e),n=e.upload_id;return t.length===1&&typeof n=="string"&&n!==""?n:null}u(Oe,"uploadRef");async function Be(e,t,n,a){if(!O())throw new s("invalid_request",`${t} must be an absolute runtime path`,{param:t});const i=await L(n);if(!i||i.delete_pending_since||i.grantee!==e.grantee||i.sub!==null&&i.sub!==(e.sub??null))throw new s("not_found",`no such upload: ${n}`,{param:t});try{const o=await a().signDownload(n);return{param:t,path:"",name:i.name,object_id:n,upload_id:n,url:o.url}}catch(o){throw o instanceof z?new s("not_found",`upload ${n} holds no bytes`,{param:t}):m(o)}}u(Be,"uploadArgument");async function V(e,t,n,a){const i=[],o=[];try{for(const r of t){if(n[r]===void 0||n[r]===null)continue;const f=Oe(n[r]);if(f!==null){o.push(await Be(e,r,f,a));continue}i.push(Fe(e,r,n[r]))}if(!i.length)return o;let c;try{c=a()}catch(r){throw m(r)}const d=[...o];for(const r of i)d.push(await Te(c,r));return d}finally{for(const c of i)H(c.file.fd)}}u(V,"copyArguments");function Z(e){const t=X(e);if(t)throw new s("server_error",`file output ${e} cannot name an upload: ${t}`)}u(Z,"checkOutputField");async function ee(e,t,n){Z(t);const a=Q(e),i="application/octet-stream";let o;try{o=await n().createResultUpload({name:t,media_type:i,max_size:j})}catch(c){throw m(c)}return await ze({upload_id:o.upload_id,grantee:a,...O()&&e.sub?{sub:e.sub}:{},name:t,media_type:i,size:j,created_at:new Date().toISOString()}),{field:t,upload_id:o.upload_id,upload_link:o.upload_link,grantee:a}}u(ee,"createResultUpload");function te(e){return e?{"Crtr-Upload-Id":e.upload_id,"Crtr-Upload-Link":e.upload_link}:{}}u(te,"uploadHeaders");function ne(e,t){const n={...e};for(const a of t)n[a.param]=a.url;return n}u(ne,"withUrls");async function et(e,t,n,a={}){const i=a.storage??B;t.output&&Z(t.output);const o=await V(e,t.params,n,i),c=t.output?await ee(e,t.output,i):null;return{arguments:ne(n,o),copies:o,upload:c,headers:te(c)}}u(et,"prepareFileCall");async function tt(e,t,n,a,i={}){const o=i.storage??B,c=[];for(const r of a.copies)try{const f=r.upload_id?await o().signDownload(r.upload_id):await o().signOutbound(r.object_id);c.push({...r,url:f.url})}catch(f){if(!(f instanceof z))throw m(f);c.push(...await V(e,[r.param],n,o))}let d=a.upload;if(d)try{const r=await o().signUploadLink(d.upload_id);d={...d,upload_link:r.upload_link}}catch(r){if(!(r instanceof z))throw m(r);r.status===404&&(d=await ee(e,t.output??d.field,o))}return{arguments:ne(n,c),copies:c,upload:d,headers:te(d)}}u(tt,"resignForRetry");const je=/^[0-9a-f]{64}$/i;function Le(e,t){if(t===1)return e;const n=pe(e);return n&&n!==e?`${e.slice(0,-n.length)}-${t}${n}`:`${e}-${t}`}u(Le,"candidate");async function nt(e,t,n,a={}){const i={result:n,file:null,cleanup:u(async()=>{},"cleanup")},o=t.upload;if(!o||!n||typeof n!="object"||Array.isArray(n))return i;const c=n,d=c[o.field];if(d==null)return i;if(typeof d!="object"||Array.isArray(d))throw S(`${o.field} must be {upload_id, size, sha256}`);const r=d;if(typeof r.upload_id!="string"||typeof r.size!="number"||!Number.isSafeInteger(r.size)||r.size<0||typeof r.sha256!="string"||!je.test(r.sha256))throw S(`${o.field} must be {upload_id, size, sha256}`);if(r.upload_id!==o.upload_id)throw S(`${o.field} names an upload other than Crtr-Upload-Id`);const f=r.size,U=r.sha256.toLowerCase(),_=AbortSignal.timeout(a.budgetMs??Ae),E=a.signal?AbortSignal.any([_,a.signal]):_;let l;try{l=await(a.storage??B)().fetchUpload(o.upload_id,E)}catch(y){throw y instanceof z?S(`${o.field} names an upload with nothing stored`):m(y)}if(l.size===null)throw l.body.destroy(),new s("storage_unavailable",`storage did not say how many bytes ${o.field} holds`);if(l.size!==f)throw l.body.destroy(),S(`${o.field} claims ${f} bytes; storage holds ${l.size}`);if(O())return await De(e,o,c,r,l,E,_);const b=o.grantee,w=e.node_id!==null,oe=await ve(b),h=w?W(b).nodes:W(b).files,A=w?F(h,e.node_id):h,C=w?F(A,"attachments"):h,ie={uid:process.getuid?.()??0,gid:oe.gid},D=w&&!P(h,A),re=w&&!D&&!P(h,C);let g=null,R=null,k=!1;const q=u(async()=>{if(!k){if(k=!0,R)try{await G(R)}catch{}if(g)try{be(h,g)}catch{}try{D?I(h,A):re&&I(h,C)}catch{}}},"cleanup");try{$e(h,C,()=>{},!0);for(let p=1;;p++){const $=F(C,Le(o.field,p));if(!await Ue($,void 0,w?{nodeId:e.node_id,nodeDir:A}:void 0))try{ge(h,$,Buffer.alloc(0),432),g=$;break}catch(v){if(v.code!=="EEXIST")throw v}}let y=0;const M=x("sha256"),ae=new we({transform(p,$,v){y+=p.length,M.update(p),v(null,p)}}),se=ye(h,g,le.O_WRONLY);try{await N(l.body,ae,ce("",{fd:se,autoClose:!0}),{signal:E})}catch(p){throw _.aborted?new s("storage_unavailable","the file result could not be fetched within 110 s"):p instanceof T?m(p):new s("storage_unavailable",`storage stopped sending ${o.field}: ${p instanceof Error?p.message:String(p)}`)}if(y!==f)throw new s("storage_unavailable",`storage sent ${y} of ${f} bytes of ${o.field}`);if(M.digest("hex")!==U)throw S(`${o.field}: the stored bytes do not match sha256`);me(h,g,432,ie);const de=g;await Y(async p=>{const $=await L(o.upload_id,p);if(!$||$.delete_pending_since)throw new s("not_found",`${o.field}: the upload was deleted while it was fetched`);if(await K(o.upload_id,f,p),!e.run_id)return;const v=await p.prepare("SELECT deleting_at FROM nodes WHERE node_id = ?").get(e.run_id);if(!v||v.deleting_at)throw new s("not_found",`run ${e.run_id} was deleted while its file result was fetched`);R={upload_id:o.upload_id,run_id:e.run_id,path:de},await J([R],p)})}catch(y){throw l.body.destroy(),await q(),y}return{result:{...c,[o.field]:g},file:{path:g,upload_id:o.upload_id},cleanup:q}}u(nt,"resolveFileResult");async function De(e,t,n,a,i,o,c){const d=a.size,r=a.sha256.toLowerCase();if(!e.run_id)throw i.body.destroy(),new s("invalid_request","a file result needs a node to deliver it to");const f=e.run_id,U=x("sha256");let _=0;try{await N(i.body,new _e({write(l,b,w){U.update(l),_+=l.length,w()}}),{signal:o})}catch(l){throw i.body.destroy(),c.aborted?new s("storage_unavailable","the file result could not be fetched within 110 s"):new s("storage_unavailable",`storage stopped sending ${t.field}: ${l instanceof Error?l.message:String(l)}`)}if(_!==d)throw new s("storage_unavailable",`storage sent ${_} of ${d} bytes of ${t.field}`);if(U.digest("hex")!==r)throw S(`${t.field}: the stored bytes do not match sha256`);const E={upload_id:t.upload_id,run_id:f,path:`upload:${t.upload_id}`};return await Y(async l=>{const b=await L(t.upload_id,l);if(!b||b.delete_pending_since)throw new s("not_found",`${t.field}: the upload was deleted while it was checked`);const w=await l.prepare("SELECT deleting_at FROM nodes WHERE node_id = ?").get(f);if(!w||w.deleting_at)throw new s("not_found",`run ${f} was deleted while its file result was checked`);await K(t.upload_id,d,l),await J([E],l)}),{result:{...n,[t.field]:{upload_id:t.upload_id,size:d,sha256:r}},file:{path:"",upload_id:t.upload_id},cleanup:u(async()=>{try{await G(E)}catch{}},"cleanup")}}u(De,"keepCloudResult");export{Ae as FILE_RESULT_FETCH_BUDGET_MS,et as prepareFileCall,tt as resignForRetry,nt as resolveFileResult};
|
|
@@ -13,7 +13,7 @@ export declare function buildProjectContextBlock(cwd: string): string;
|
|
|
13
13
|
* a sibling block) as the place for files that are not documents. Present for
|
|
14
14
|
* every node, rendered as the `## Your documents and context directory`
|
|
15
15
|
* subsection of <crtr-bearings>. */
|
|
16
|
-
export declare function contextDirNote(nodeId: string
|
|
16
|
+
export declare function contextDirNote(nodeId: string): string;
|
|
17
17
|
/** Where the node's engine and shell run, by the runner of its latest execution. A cloud sandbox is not the person's
|
|
18
18
|
* computer, so a path from their Mac (a pasted screenshot's temp file, a `/Users/...` path) does not exist there. */
|
|
19
19
|
export declare function whereYouRunNote(runner: 'process' | 'blaxel' | 'machine' | undefined): string;
|
|
@@ -34,7 +34,7 @@ export declare function orchestratorContextNote(): string;
|
|
|
34
34
|
/** The fork's context note: the fork's own context directory replaces the
|
|
35
35
|
* source's for files, and the source's documents stay the source's — a bare
|
|
36
36
|
* document name in the copied conversation now needs the source's prefix. */
|
|
37
|
-
export declare function forkContextNote(
|
|
37
|
+
export declare function forkContextNote(sourceId: string): string;
|
|
38
38
|
export interface RelativeLabelNode extends NamedNode {
|
|
39
39
|
node_id: string;
|
|
40
40
|
kind: string;
|