@north-light/cli 0.3.666 → 0.3.668
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/client.d.ts +2 -1
- package/dist/api/client.js +1 -1
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/bash-jobs.d.ts +3 -0
- package/dist/api/dto/broker-ops.d.ts +37 -0
- package/dist/api/dto/nodes.d.ts +2 -0
- package/dist/api/routes.d.ts +1 -0
- package/dist/api/routes.js +1 -1
- package/dist/builtin-memory/02-turn-lifecycle/00-ending-a-turn.md +3 -1
- package/dist/builtin-memory/04-base-worker-exploring.md +2 -2
- package/dist/clients/attach/chrome/canvas-panels.d.ts +9 -1
- package/dist/clients/attach/chrome/canvas-panels.js +1 -1
- package/dist/clients/attach/chrome/roster.js +6 -6
- package/dist/clients/attach/render/card-presentation.js +2 -2
- package/dist/clients/attach/viewer.js +499 -499
- package/dist/commands/node/bash.js +4 -4
- package/dist/commands/node.js +1 -1
- package/dist/core/bash-job-supervisor.js +3 -3
- package/dist/core/bash-jobs.js +5 -5
- package/dist/core/canvas/canvas.js +18 -18
- package/dist/core/canvas/memory-reads.js +2 -1
- package/dist/core/canvas/waits.d.ts +2 -0
- package/dist/core/canvas/waits.js +6 -6
- package/dist/core/feed/messages.d.ts +5 -2
- package/dist/core/feed/messages.js +10 -5
- package/dist/core/grants/mirror.d.ts +11 -3
- package/dist/core/grants/mirror.js +6 -4
- package/dist/core/grants/on-sync.js +1 -1
- package/dist/core/graph/events.d.ts +9 -0
- package/dist/core/graph/events.js +12 -12
- package/dist/core/graph/kinds/document.js +2 -2
- package/dist/core/graph/kinds/kind.d.ts +2 -1
- package/dist/core/graph/kinds/node.js +1 -1
- package/dist/core/graph/names.d.ts +4 -3
- package/dist/core/graph/names.js +10 -9
- package/dist/core/graph/watches.d.ts +11 -2
- package/dist/core/graph/watches.js +13 -9
- package/dist/core/human/requests.d.ts +18 -1
- package/dist/core/human/requests.js +20 -18
- package/dist/core/human/scan.d.ts +3 -2
- package/dist/core/human/scan.js +1 -1
- package/dist/core/runtime/broker/attachments-fetch.d.ts +2 -1
- package/dist/core/runtime/broker/attachments-fetch.js +1 -1
- package/dist/core/runtime/broker/bash-job-launch.js +1 -1
- package/dist/core/runtime/broker/boot-state.d.ts +5 -0
- package/dist/core/runtime/broker/boot-state.js +1 -1
- package/dist/core/runtime/broker/cycle-start.d.ts +50 -0
- package/dist/core/runtime/broker/cycle-start.js +2 -0
- package/dist/core/runtime/broker/fault-retry.js +1 -1
- package/dist/core/runtime/broker/frame-dispatch.d.ts +2 -0
- package/dist/core/runtime/broker/frame-dispatch.js +1 -1
- package/dist/core/runtime/broker/frame-memory-refs.d.ts +2 -0
- package/dist/core/runtime/broker/frame-memory-refs.js +1 -1
- package/dist/core/runtime/broker/job-reporter.d.ts +4 -2
- package/dist/core/runtime/broker/job-reporter.js +2 -2
- package/dist/core/runtime/broker/rebind.d.ts +3 -0
- package/dist/core/runtime/broker/rebind.js +1 -1
- package/dist/core/runtime/broker.js +1 -1
- package/dist/core/runtime/runner/blaxel/image-build.d.ts +3 -0
- package/dist/core/runtime/runner/blaxel/image-build.js +1 -1
- package/dist/core/runtime/runner/blaxel/release-image.d.ts +37 -0
- package/dist/core/runtime/runner/blaxel/release-image.js +3 -0
- package/dist/core/runtime/runner/blaxel/runner.d.ts +1 -1
- package/dist/core/runtime/spawn.js +2 -2
- package/dist/core/secrets/blaxel-launch.d.ts +8 -0
- package/dist/core/secrets/blaxel-launch.js +3 -3
- package/dist/core/substrate/delivery/corpus.d.ts +7 -2
- package/dist/core/substrate/delivery/corpus.js +2 -2
- package/dist/core/substrate/delivery/deliver.js +3 -3
- package/dist/core/substrate/delivery/render-boot.js +27 -27
- package/dist/core/substrate/delivery/render-event.d.ts +5 -4
- package/dist/core/substrate/delivery/render-event.js +6 -6
- package/dist/daemon/api/bridge.js +3 -3
- package/dist/daemon/api/environment-of.d.ts +4 -0
- package/dist/daemon/api/environment-of.js +3 -3
- package/dist/daemon/api/handlers/attach.js +1 -1
- package/dist/daemon/api/handlers/bash-jobs.d.ts +2 -0
- package/dist/daemon/api/handlers/bash-jobs.js +3 -3
- package/dist/daemon/api/handlers/broker-ops.js +1 -1
- package/dist/daemon/api/handlers/broker-recovery.d.ts +2 -0
- package/dist/daemon/api/handlers/broker-recovery.js +1 -1
- package/dist/daemon/api/handlers/canvas.js +6 -6
- package/dist/daemon/api/handlers/inbox.js +1 -1
- package/dist/daemon/api/handlers/node-records.d.ts +7 -0
- package/dist/daemon/api/handlers/node-records.js +1 -1
- package/dist/daemon/api/handlers/nodes.js +1 -1
- package/dist/daemon/api/map.js +2 -2
- package/dist/daemon/api/operations.js +1 -1
- package/dist/daemon/cron/authority.d.ts +3 -1
- package/dist/daemon/cron/authority.js +1 -1
- package/dist/daemon/cron/escalation.js +1 -1
- package/dist/daemon/cron/sinks.js +2 -2
- package/dist/daemon/cron-run.js +2 -2
- package/dist/daemon/crtrd.js +12 -12
- package/dist/daemon/machine-daemon.js +1 -1
- package/dist/daemon/machine-link/client.d.ts +8 -0
- package/dist/daemon/machine-link/client.js +1 -1
- package/dist/daemon/machine-link/frames.d.ts +18 -0
- package/dist/daemon/machine-link/frames.js +1 -1
- package/dist/daemon/machine-link/holder.d.ts +2 -0
- package/dist/daemon/machine-link/holder.js +5 -5
- package/dist/daemon/machine-link/job-sweep.d.ts +15 -0
- package/dist/daemon/machine-link/job-sweep.js +1 -0
- package/dist/daemon/reconcilers/action-lane.js +1 -1
- package/dist/daemon/reconcilers/bash-deadline.js +1 -1
- package/dist/pi-extensions/canvas-context-intro.js +2 -2
- package/dist/pi-extensions/canvas-doc-substrate.js +4 -4
- package/dist/pi-extensions/canvas-passive-context.d.ts +13 -10
- package/dist/pi-extensions/canvas-passive-context.js +9 -12
- package/dist/pi-extensions/canvas-recap.js +6 -6
- package/dist/pi-extensions/canvas-stophook.js +1 -1
- package/dist/pi-extensions/canvas-structured-output.js +6 -6
- package/package.json +2 -2
- package/packages/crouter-identity/package.json +1 -1
- package/runtime.lock.json +13 -13
- package/scripts/sandbox-bootstrap.sh +36 -7
- package/scripts/sandbox-start.mjs +41 -7
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
var $=Object.defineProperty;var r=(e,t)=>$(e,"name",{value:t,configurable:!0});import{envNodeId as _}from"../../shared/env.js";import{defineBranch as T,defineLeaf as h}from"../../core/command.js";import{InputError as i}from"../../core/io.js";import{ExitCode as q}from"../../types.js";import{existsSync as R,mkdirSync as D,rmSync as
|
|
1
|
+
var $=Object.defineProperty;var r=(e,t)=>$(e,"name",{value:t,configurable:!0});import{envNodeId as _}from"../../shared/env.js";import{defineBranch as T,defineLeaf as h}from"../../core/command.js";import{InputError as i}from"../../core/io.js";import{ExitCode as q}from"../../types.js";import{existsSync as R,mkdirSync as D,rmSync as E,writeFileSync as w}from"node:fs";import{backgroundRunningBashJobs as I,bashJobCommandLine as N,bashJobPaths as y,formatBashElapsed as k,isSafeBashJobId as g,jobStartedAtMs as B,newBashJobId as M,tailJobLog as L}from"../../core/bash-jobs.js";import{parseDurationMs as S}from"../../core/wake.js";import{cliClient as u,getNodeOrNull as c}from"../api-client.js";import{ApiError as x}from"../../api/index.js";import{PREVIEW_RESULT_PATH_ENV as U}from"../../core/preview-result-path.js";import{contextDir as A}from"../../core/canvas/paths.js";import{nodeInPane as C}from"../surface/node/placement.js";function b(e,t){const n=e.pane??process.env.TMUX_PANE;let o=e.node;if((o===void 0||o==="")&&(o=C(n)),(o===void 0||o==="")&&(o=_()),o===void 0||o==="")throw new i({error:"no_node",message:t,next:"Run from inside a node, pass --node <id>, or --pane <pane>."});return{id:o,pane:n}}r(b,"resolveBashTarget");async function j(e,t,n){try{await u().patchBashJob(e,t,n)}catch(o){throw o instanceof x&&(o.status===404||o.status===409)?new i({error:"not_running",message:`background job ${t} for ${e} is not running`,next:"List live jobs with `crtr node bash list`."}):o}}r(j,"patchRunningJob");const J=h({name:"run",description:"start a shell command as a background job and return at once",whenToUse:"a command needs longer than one tool call \u2014 a test lane, a build, a soak \u2014 and you should be woken with its exit code instead of waiting, backgrounding with `&`, or polling a log",tier:"normal",help:{name:"node bash run",summary:"start one shell command as a background job owned by the calling node and return before it finishes",params:[{kind:"positional",name:"command",required:!0,constraint:"The shell command, run by bash from the current directory with this process\u2019s environment. The same refusals apply as for a bash tool call, judged on this command."},{kind:"flag",name:"quiet-ok",type:"bool",required:!1,constraint:"Pass for a job that legitimately sits idle \u2014 `gh run watch`, `sleep`, waiting on a lock, a `docker build` whose work runs outside the process tree \u2014 so it gets no silence messages. Omit it for anything that should be making progress."}],output:[{name:"job_id",type:"string",required:!0,constraint:"The job object\u2019s id; read or watch it with `crtr canvas`, stop it with `node bash kill`."},{name:"log_path",type:"string",required:!0,constraint:"File receiving the command\u2019s combined stdout and stderr, capped at 10 MiB."}],outputKind:"object",effects:["Works only inside a node\u2019s bash tool call; the job belongs to the calling node.","Starts the command detached from this call, so it keeps running after the call and the turn end. A `timeout` around this leaf bounds only the launch, not the job.","Records the job as a canvas object; when the command exits, its watchers (the calling node by default) get an urgent `exited` push with the exit code and log path.","Sets no cancel deadline: the job runs to completion unless stopped with `node bash kill`.","A job whose processes use almost no CPU and write to no open file for 15 minutes messages the calling node about it, again at 30 and 60 minutes, then hourly; activity restarts the schedule and nothing is stopped. `--quiet-ok` turns these messages off.","Fails, with the job id and log path, if the job could not be recorded; the command is then running but will not message the node when it exits."]},run:r(async e=>{const t=e.command,n=_(),o=process.env.CRTR_CONTEXT_DIR;if(n===void 0||n===""||o===void 0||o==="")throw new i({error:"no_node",message:"`node bash run` starts a job for the calling node and works only inside a node\u2019s bash tool",next:"Run it from a node\u2019s bash tool call."});const s=process.cwd(),{bashCommandRefusal:d}=await import("../../core/bash-guard.js"),l=d(t,s);if(l!==null)throw new i({error:"refused",message:l,next:"Run a different command."});const a=y(o,M());D(a.dir,{recursive:!0}),w(a.cmdSh,t),w(a.jobLog,""),w(a.jobBg,"");const{launchBashJobSupervisor:m}=await import("../../core/runtime/broker/bash-job-launch.js"),{[U]:p,...v}=process.env;try{await m(n,a,o,s,v)}catch(f){throw E(a.dir,{recursive:!0,force:!0}),f}try{await u().recordBackgroundedJob(n,a.jobId,{command:t}),e.quietOk===!0&&await u().patchBashJob(n,a.jobId,{quiet_ok:!0})}catch(f){throw new i({error:"job_not_recorded",message:`job ${a.jobId} is running but could not be recorded (${f.message}); it will NOT message you when it exits. Log: ${a.jobLog}`,next:`Watch it with \`tail -f ${a.jobLog}\`, or stop it with \`crtr node bash kill ${a.jobId}\`.`},q.GENERAL)}return{job_id:a.jobId,log_path:a.jobLog}},"run"),render:r(e=>`[backgrounded as job ${e.job_id}. It will interrupt you with a message when it exits. Watch: tail -f ${e.log_path} ; stop: crtr node bash kill ${e.job_id}]`,"render")}),P=h({name:"background",description:"hand the focused node\u2019s running bash command to its background job system",whenToUse:"the tmux prefix menu invokes this when a foreground bash command should stop blocking the agent immediately but keep running as a file-backed background job",tier:"hidden",help:{name:"node bash background",summary:"hand every running foreground bash command for one node to its file-backed background job system",params:[{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node whose running bash command to background. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE. The prefix menu passes this for you."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The target node."},{name:"jobs",type:"object[]",required:!0,constraint:"Per handed-off job {job_id, elapsed_ms} \u2014 the foreground elapsed time in milliseconds at the moment of handoff."}],outputKind:"object",effects:["Signals every foreground bash command currently running for the node to return from its tool call immediately while its detached supervisor keeps the command running.","Each handed-off command retains its log under the node context jobs directory and becomes a job object; when it exits, the job\u2019s watchers (its node by default) get an urgent `exited` push carrying the exit code and log path."]},run:r(async e=>{const{id:t}=b(e,"no node found for the bash handoff"),n=await c(t);if(n===null)throw new i({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=I(n.paths.context_dir),s=Date.now(),d=o.map(l=>({job_id:l.jobId,elapsed_ms:s-(B(l.jobId)??s)}));return{node_id:t,jobs:d}},"run"),render:r(e=>{const t=e.jobs;if(t.length===0)return`No foreground bash command is running for ${e.node_id}.`;const n=Math.max(...t.map(o=>o.elapsed_ms));return`Handed ${t.length} bash command(s) to the background job system for ${e.node_id} \xB7 ran ${k(n)} in the foreground.`},"render")}),O=h({name:"list",description:"list a node\u2019s live background bash jobs",whenToUse:"you need the ids, commands, and ages of your jobs that are still running",help:{name:"node bash list",summary:"read every still-running background bash job owned by one node",params:[{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node whose background jobs to list. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE."},{kind:"flag",name:"tail",type:"int",required:!1,default:0,constraint:"Include this many trailing log lines per job (0 = none). Read from the local log file, so it is available only on the machine that runs the job; elsewhere log_tail is null \u2014 use `node bash log` there."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The target node."},{name:"jobs",type:"object[]",required:!0,constraint:"Oldest-first {job_id, command, purpose, started_at, elapsed_ms, deadline_at, output_key, log_path, pgid, log_tail} for every live background job; log_path and log_tail are null when the job\u2019s log is not on this machine (a job running in a sandbox, listed from outside it), and no tail is available from here (`node bash log` reads its stored output); purpose is a human-readable label or null; deadline_at is the auto-cancel time or null for a job that runs to completion."}],outputKind:"object",effects:["Reads the node\u2019s running job rows and, for log_tail, the local log files. Changes nothing."]},run:r(async e=>{const{id:t}=b(e,"no node found for the bash job list"),n=await c(t);if(n===null)throw new i({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=Date.now(),s=Math.max(0,Math.trunc(Number(e.tail??0))),d=[n.paths.context_dir,A(n.node_id,n.grantee)],l=(await u().listBashJobs(n.node_id)).map(a=>{const m=d.map(p=>y(p,a.job_id).jobLog).find(p=>R(p))??null;return{job_id:a.job_id,command:a.command,purpose:a.purpose,started_at:a.started_at,elapsed_ms:a.elapsed_ms,deadline_at:a.deadline_at,output_key:a.output_key,log_path:m,pgid:a.pgid,log_tail:m===null?null:L(m,s)}});return{node_id:n.node_id,jobs:l}},"run"),render:r(e=>{const t=e.jobs;return t.length===0?`No background bash jobs for ${e.node_id}.`:t.map(n=>`${n.job_id} \xB7 ${k(n.elapsed_ms)} \xB7 ${N(n.command)}${n.purpose===null?"":`
|
|
2
2
|
purpose: ${n.purpose}`}${n.deadline_at===null?"":`
|
|
3
3
|
cancels at: ${n.deadline_at}`}
|
|
4
|
-
${n.log_path===null?`log: not on this machine (
|
|
5
|
-
`)},"render")}),
|
|
6
|
-
`:""}${String(e.output)}`,"render")}),
|
|
4
|
+
${n.log_path===null?`log: not on this machine (its job files are not under this machine\u2019s crtr home \u2014 a sandbox or another computer); read its output with \`crtr node bash log ${n.job_id} --node ${e.node_id}\``:`log: ${n.log_path}`}`).join(`
|
|
5
|
+
`)},"render")}),K=h({name:"log",description:"read a background bash job\u2019s output from the blob store, from any machine",whenToUse:"a job has exited or been killed, or its sandbox is gone, and you need what it printed \u2014 the wake and the job object name this command; for a job still running on this machine, `tail -f` on its log file shows more recent output",help:{name:"node bash log",summary:"read the stored output of one background bash job, last lines first bounded",params:[{kind:"positional",name:"job",required:!0,constraint:"Job id, as named by the exit wake, `node bash list` or `node bash run`. Running and finished jobs both work."},{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node owning the job. Defaults to the node in --pane, else the caller (CRTR_NODE_ID). A job another node started needs its owner here."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE."},{kind:"flag",name:"tail",type:"int",required:!1,constraint:"Return only this many trailing lines. Without it you get the last 256 KiB of output; either way at most 4 MiB."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The owning node."},{name:"job_id",type:"string",required:!0,constraint:"The job."},{name:"output",type:"string",required:!0,constraint:"The stored output, empty when the job has written nothing yet. The broker uploads a running job\u2019s output every couple of seconds, so it can trail the live log slightly."},{name:"truncated",type:"boolean",required:!0,constraint:"True when earlier output exists that the bound left out."}],outputKind:"object",effects:["Reads the output chunks the job\u2019s broker uploaded to the blob store through the daemon; never the local log file, so it works from any machine and after the job\u2019s sandbox is deleted. Needs read access to the owning node. Changes nothing."]},run:r(async e=>{const{id:t}=b(e,"no node found for the bash job"),n=await c(t);if(n===null)throw new i({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=e.job;if(!g(o))throw new i({error:"invalid_job_id",message:`invalid background job id: ${o}`,next:"Use a job id named by the exit wake or `crtr node bash list`."});const s=e.tail===void 0?void 0:Math.trunc(Number(e.tail));if(s!==void 0&&!(s>=1))throw new i({error:"invalid_args",message:"--tail must be a positive number of lines",next:"Pass --tail 50, or omit it for the last 256 KiB."});try{const d=await u().readBashJobOutput(n.node_id,o,s===void 0?{}:{tail_lines:s});return{node_id:n.node_id,job_id:d.job_id,output:d.output,truncated:d.truncated}}catch(d){throw d instanceof x&&d.code==="job_not_found"?new i({error:"job_not_found",message:`no job ${o} owned by ${n.node_id}`,next:"A job another node started needs its owner: pass --node <owner>."}):d}},"run"),render:r(e=>`${e.truncated===!0?`[earlier output omitted]
|
|
6
|
+
`:""}${String(e.output)}`,"render")}),X=h({name:"kill",description:"stop one of a node\u2019s background bash jobs",whenToUse:"a job you started is no longer wanted or is stuck, and it should stop now",help:{name:"node bash kill",summary:"best-effort stop a background bash job and tell the owning node it was canceled",params:[{kind:"positional",name:"job",required:!0,constraint:"Job id, as reported by node bash list."},{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node owning the job. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The owning node."},{name:"signaled",type:"boolean",required:!0,constraint:"True when at least one observed supervisor-tree process received SIGTERM. For a job running on another machine it is true without any signal having been sent yet."},{name:"stop_pending_on_machine",type:"boolean",required:!0,constraint:"True when the job\u2019s process runs on another machine (an imported Mac or a sandbox): its broker there stops the whole process tree on its next report, within a few seconds, so nothing is confirmed stopped yet."}],outputKind:"object",effects:["Snapshots the supervisor\u2019s observable process tree, sends SIGTERM then SIGKILL to those processes and to the supervisor\u2019s process group, and cannot stop a descendant that detached into its own session and reparented before the snapshot. A job running on another machine (an imported Mac, a sandbox) is stopped there by its broker within a few seconds of the row ending.","Records the job\u2019s exit so it stops showing as live, and ends its job object as killed; the job\u2019s watchers (its node by default) get an urgent `killed` push."]},run:r(async e=>{const{id:t}=b(e,"no node found for the bash job"),n=await c(t);if(n===null)throw new i({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=e.job;if(!g(o))throw new i({error:"invalid_job_id",message:`invalid background job id: ${o}`,next:"Use a job id reported by `crtr node bash list`."});const s=await u().stopBashJob(n.node_id,o);return{node_id:n.node_id,signaled:s.signaled,stop_pending_on_machine:s.stop_pending_on_machine===!0}},"run"),render:r(e=>e.stop_pending_on_machine===!0?`Ended a background bash job for ${e.node_id}. Its process runs on another machine (an imported Mac or a sandbox); that machine's broker stops the whole process tree on its next report, within a few seconds. Confirm with \`ps\` there if it matters.`:`Canceled a background bash job for ${e.node_id}${e.signaled===!0?"":" (no observed job process was still running)"}.`,"render")}),W=h({name:"quiet",description:"mark a running background bash job as an expected wait so it sends no silence messages",whenToUse:"a silence message arrived for a job that is meant to sit idle",help:{name:"node bash quiet",summary:"stop silence messages for one of a node\u2019s live background bash jobs",params:[{kind:"positional",name:"job",required:!0,constraint:"Job id, as reported by node bash list or the silence message."},{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node owning the job. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The owning node."}],outputKind:"object",effects:["Marks the job\u2019s row; the daemon sends no further silence messages for it. Signals nothing."]},run:r(async e=>{const{id:t}=b(e,"no node found for the bash job"),n=await c(t);if(n===null)throw new i({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=e.job;if(!g(o))throw new i({error:"invalid_job_id",message:`invalid background job id: ${o}`,next:"Use a job id reported by `crtr node bash list`."});return await j(n.node_id,o,{quiet_ok:!0}),{node_id:n.node_id}},"run"),render:r(e=>`Background job for ${e.node_id} will send no more silence messages.`,"render")}),F=h({name:"extend",description:"claim an auto-backgrounded bash job so the daemon does not cancel it at its deadline",whenToUse:"a command that was moved to a job automatically is worth keeping past its cancel deadline \u2014 give it more time with --for, or let it run to completion with --keep",help:{name:"node bash extend",summary:"move or clear the auto-cancel deadline on one of a node\u2019s live background bash jobs",params:[{kind:"positional",name:"job",required:!0,constraint:"Job id, as reported by node bash list or the auto-background notice."},{kind:"flag",name:"for",type:"string",required:!1,constraint:"New window from now before the job is canceled, as a duration (e.g. 90s, 10m, 1h30m). Mutually exclusive with --keep; give exactly one."},{kind:"flag",name:"keep",type:"bool",required:!1,constraint:"Remove the deadline entirely so the job runs to completion. Mutually exclusive with --for; give exactly one."},{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node owning the job. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The owning node."},{name:"deadline_at",type:"string",required:!1,constraint:"The job\u2019s new auto-cancel time (ISO), or absent when --keep cleared the deadline so the job runs to completion."}],outputKind:"object",effects:["Rewrites or clears the deadline on the job\u2019s row. The daemon\u2019s deadline lane reads it on its next scan. Signals nothing."]},run:r(async e=>{const{id:t}=b(e,"no node found for the bash job"),n=await c(t);if(n===null)throw new i({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=e.job;if(!g(o))throw new i({error:"invalid_job_id",message:`invalid background job id: ${o}`,next:"Use a job id reported by `crtr node bash list`."});const s=e.for,d=e.keep===!0;if(d===(s!==void 0&&s!==""))throw new i({error:"invalid_args",message:"give exactly one of --for <duration> or --keep",next:"Extend by a window with --for 10m, or drop the deadline with --keep."});if(d)return await j(n.node_id,o,{keep:!0}),{node_id:n.node_id};const l=S(s);if(l===null||l<=0)throw new i({error:"invalid_duration",message:`not a duration: ${s}`,next:"Use a value like 90s, 10m, or 1h30m."});const a=Date.now()+l;return await j(n.node_id,o,{deadline_at_ms:a}),{node_id:n.node_id,deadline_at:new Date(a).toISOString()}},"run"),render:r(e=>e.deadline_at===void 0?`Cleared the deadline \u2014 the background job will run to completion for ${e.node_id}.`:`Background job for ${e.node_id} will be canceled at ${e.deadline_at} unless extended again.`,"render")}),ie=T({name:"bash",description:"start, list, read, stop, and extend your background bash jobs",whenToUse:"a command needs longer than one tool call \u2014 start it as a job and be woken with its exit code instead of using `&`, `nohup`, or a cron that polls a log \u2014 or you need to list, read the output of, stop, or extend the deadline of a job you already have",help:{name:"node bash",summary:"start, list, read, stop, and extend background bash jobs owned by a node",model:"Every bash call runs under a detached supervisor with its output in a log file, so a command that outlives its call keeps running as a job: a canvas object its node owns, readable and watchable with `crtr canvas`. `run` starts a job on purpose and it is never auto-canceled. A job that shows no activity for 15 minutes messages its node, and is never stopped for it. A foreground command still running after 5 minutes is moved to a job automatically, with a cancel deadline unless `extend` claims it."},children:[J,P,O,K,X,W,F]});export{ie as nodeBash};
|
package/dist/commands/node.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var t=Object.defineProperty;var e=(n
|
|
1
|
+
var t=Object.defineProperty;var e=(o,n)=>t(o,"name",{value:n,configurable:!0});import{defineBranch as a}from"../core/command.js";import{nodeNew as i}from"./node/create.js";import{nodeInspect as r,nodeFork as s}from"./node/inspect.js";import{nodeLifecycle as d,nodeConfig as c,nodePromote as h,nodeYield as m}from"./node/lifecycle.js";import{nodeMessage as l}from"./node/message.js";import{nodeWaitBranch as f}from"./node/wait.js";import{nodeSubscription as p}from"./node/subscription.js";import{nodeBash as w}from"./node/bash.js";import{pyramidSlash as u}from"./node/pyramid.js";import{nodeWorktreeBranch as g}from"./node-worktree.js";import{nodeOutcome as y}from"./node/outcome.js";function C(){return a({name:"node",slash:u,rootEntry:{concept:"a unit of the agent runtime \u2014 an agent on the canvas with its own context dir and pi vehicle. A child node starts with none of your context, spends its own full window of tokens, and you wait for its report",desc:"spawn, inspect, and navigate nodes on the canvas",useWhen:"delegating a genuinely independent subtask, or walking the subscription graph. Delegation pays when the subtask runs in parallel with your own work or would fill your window with material you do not need afterwards; do the work yourself when it is a few files or a few commands. Base nodes work hands-on; orchestrators fan out. Brief each child with the outcome, what you already know, and what to hand back. Give each child a bounded outcome distinct from your whole assignment so delegation moves work toward completion instead of recursively passing it down. Once delegated, do not duplicate the child\u2019s work; its finish wakes you. Use the help surface for the exact node contract before invoking it. For a long-running shell command, `crtr node bash -h`."},help:{name:"node",summary:"create, inspect, message, and change canvas nodes",model:"A node is one agent on the canvas. Immediate actions, durable waits, subscriptions, lifecycle changes, and scheduled crons are separate intent families; choose the family by when the effect happens and what persistent state it changes."},children:[i,s,l,f,p,y,r,d,g,c,h,m,w]})}e(C,"registerNode");export{C as registerNode};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const c=10485760,
|
|
1
|
+
const c=10485760,e=`
|
|
2
2
|
[background bash job output truncated at 10 MiB; remaining output discarded]
|
|
3
|
-
`,
|
|
4
|
-
`);export{
|
|
3
|
+
`,t=['const fs = require("node:fs");',"const cap = 10485760;",`const marker = Buffer.from(${JSON.stringify(e)});`,"const prefixCap = cap - marker.length;",'const fd = fs.openSync(process.argv[1], "w");',"let written = 0;","let truncated = false;",'process.stdin.on("data", (chunk) => {'," if (truncated) return;"," const available = prefixCap - written;"," if (available > 0) {"," const prefix = chunk.subarray(0, available);"," fs.writeSync(fd, prefix);"," written += prefix.length;"," if (prefix.length === chunk.length) return;"," }"," fs.writeSync(fd, marker);"," truncated = true;","});",'process.stdin.on("end", () => fs.closeSync(fd));'].join(" "),s=['const fs = require("node:fs"), cp = require("node:child_process");',"const rootPid = Number(process.argv[1]), out = process.argv[3];","let logPath = process.argv[2];","try { logPath = fs.realpathSync(logPath); } catch {}","const interval = Number(process.env.CRTR_BASH_ACTIVITY_SAMPLE_MS) || 60000;",'const linux = fs.existsSync("/proc/self/stat");',"function processes() {"," const procs = new Map();"," if (linux) {",' for (const e of fs.readdirSync("/proc")) {'," if (!/^[0-9]+$/.test(e)) continue;"," try {",' const s = fs.readFileSync("/proc/" + e + "/stat", "utf8");',' const r = s.slice(s.lastIndexOf(")") + 2).split(" ");'," procs.set(Number(e), { ppid: Number(r[1]), cpu: (Number(r[11]) + Number(r[12])) / 100 });"," } catch {}"," }"," return procs;"," }",' const ps = cp.execFileSync("ps", ["-ax", "-o", "pid=,ppid=,time="], { encoding: "utf8", timeout: 5000 });',' for (const line of ps.split("\\n")) {'," const f = line.trim().split(/\\s+/);"," if (f.length < 3) continue;",' const [days, clock] = f[2].includes("-") ? f[2].split("-") : ["0", f[2]];',' const cpu = clock.split(":").reduce((t, x) => t * 60 + Number(x), 0) + Number(days) * 86400;'," if (Number.isFinite(cpu)) procs.set(Number(f[0]), { ppid: Number(f[1]), cpu });"," }"," return procs;","}","function tree(procs) {"," const cpus = new Map(), stack = [rootPid];"," while (stack.length > 0) {"," const pid = stack.pop();"," if (pid === process.pid || cpus.has(pid) || !procs.has(pid)) continue;"," cpus.set(pid, procs.get(pid).cpu);"," for (const [child, p] of procs) if (p.ppid === pid) stack.push(child);"," }"," return cpus;","}","function writableFiles(pids) {"," const files = new Set();"," if (linux) {"," for (const pid of pids) {"," let fds = [];",' try { fds = fs.readdirSync("/proc/" + pid + "/fd"); } catch {}'," for (const fd of fds) {"," try {",' const info = fs.readFileSync("/proc/" + pid + "/fdinfo/" + fd, "utf8").match(/flags:\\s*([0-7]+)/);'," if (info === null || (parseInt(info[1], 8) & 3) === 0) continue;",' files.add(fs.readlinkSync("/proc/" + pid + "/fd/" + fd));'," } catch {}"," }"," }"," return files;"," }",' const r = cp.spawnSync("lsof", ["-nP", "-w", "-F", "pfatn", "-p", pids.join(",")], { encoding: "utf8", timeout: 10000 });',' if (r.error || typeof r.stdout !== "string") return files;',' let access = "", type = "";',' for (const line of r.stdout.split("\\n")) {'," const key = line[0], value = line.slice(1);",' if (key === "f") { access = ""; type = ""; }',' else if (key === "a") access = value;',' else if (key === "t") type = value;',' else if (key === "n" && (access === "w" || access === "u") && type === "REG") files.add(value);'," }"," return files;","}","let lastActivity = Date.now(), prevAt = lastActivity, prevCpu = new Map(), watched = [logPath];","try { prevCpu = tree(processes()); } catch {}","function record() {",' fs.writeFileSync(out + ".tmp", lastActivity + " " + prevAt + "\\n" + watched.join("\\n") + "\\n");',' fs.renameSync(out + ".tmp", out);',"}","function sample() {",' try { process.kill(rootPid, 0); } catch (e) { if (e.code !== "EPERM") process.exit(0); }'," const at = Date.now();"," const cpus = tree(processes());"," let used = 0;"," for (const [pid, cpu] of cpus) used += Math.max(0, cpu - (prevCpu.get(pid) || 0));"," const paths = new Set([logPath]);"," let changed = false;"," for (const file of writableFiles([...cpus.keys()])) {"," try {"," const st = fs.statSync(file);"," if (!st.isFile()) continue;"," paths.add(fs.realpathSync(file));"," if (st.mtimeMs > prevAt) changed = true;"," } catch {}"," }"," try { if (fs.statSync(logPath).mtimeMs > prevAt) changed = true; } catch {}"," if (at - prevAt > 3 * interval) changed = true;"," if (changed || used > 0.02 * (at - prevAt) / 1000) lastActivity = at;"," watched = [...paths];"," prevAt = at;"," prevCpu = cpus;"," record();","}","record();","setInterval(() => { try { sample(); } catch {} }, interval);"].join(" "),n=['const http = require("node:http");',"const done = () => process.exit(0);",'const req = http.request({ socketPath: process.argv[1], path: "/job-exit", method: "POST", headers: { "content-type": "application/json" }, timeout: 3000 }, (res) => { res.resume(); res.on("end", done); });','req.on("error", done);','req.on("timeout", done);',"req.end(JSON.stringify({ node: process.argv[2], job: process.argv[3] }));"].join(" "),r=['"$8" -e '+JSON.stringify(s)+' "$$" "$2" "$9" &',"sampler=$!","n=$(command -v nice)",'${n:+"$n" -n "$7"} "$6" "$1" 2>&1 | "$8" -e '+JSON.stringify(t)+' "$2"',"status=${PIPESTATUS[0]}",'kill "$sampler" 2>/dev/null','echo "$status" > "$3"','if [ -n "${10:-}" ]; then "$8" -e '+JSON.stringify(n)+' "${10}" "${11:-}" "${12:-}" </dev/null >/dev/null 2>&1 & fi','mv "$4" "$5" 2>/dev/null || true'].join(`
|
|
4
|
+
`);export{e as BACKGROUND_BASH_LOG_TRUNCATION_MARKER,r as BASH_JOB_SUPERVISOR_SCRIPT,c as MAX_BACKGROUND_BASH_LOG_BYTES};
|
package/dist/core/bash-jobs.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
var
|
|
2
|
-
`),[B,j]=(l??"").split(" ").map(Number);Number.isFinite(B)&&Number.isFinite(j)&&(r.activity={lastActivityMs:B,sampledAtMs:j,files:h.filter(
|
|
1
|
+
var v=Object.defineProperty;var o=(t,e)=>v(t,"name",{value:e,configurable:!0});import{randomBytes as F}from"node:crypto";import{closeSync as x,openSync as S,readSync as E,statSync as _}from"node:fs";import{dirname as p,join as a}from"node:path";import{captureTeardownSnapshot as C,isAnyPidAlive as O,isPidAlive as N,killProcessTreePids as J}from"./canvas/pid.js";import{launcherRequest as G}from"../launcher/client.js";import{LaunchRefused as z}from"../launcher/spec.js";import{createFileBeneath as P,existsBeneath as H,readTextBeneathIfExists as m,readdirBeneath as X,readFileBeneath as q,renameBeneath as K,unlinkBeneath as U,writeFileBeneath as w}from"./spaces/open-beneath.js";const W=280;function at(t){if(typeof t!="string"||/[\p{Cc}\p{Cf}]/u.test(t))return null;const e=t.trim();return e===""?null:Buffer.byteLength(e,"utf8")<=W?e:null}o(at,"normalizeBashJobPurpose");function g(t){return a(t,"jobs")}o(g,"bashJobsDir");function y(t,e){return q(p(t),e).toString("utf8")}o(y,"readJobText");function M(t){return X(p(t),g(t)).map(e=>e.name)}o(M,"jobIds");function c(t,e){return H(t.root,e)}o(c,"has");function k(t,e){try{U(t,e)}catch(n){if(n.code!=="ENOENT")throw n}}o(k,"unlinkIfPresent");function ct(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&/^[A-Za-z0-9._~-]+$/u.test(t)&&Buffer.byteLength(t,"utf8")<=128}o(ct,"isSafeBashJobId");function b(t,e){const n=a(g(t),e);return{jobId:e,root:p(t),dir:n,cmdSh:a(n,"cmd.sh"),jobLog:a(n,"job.log"),jobExit:a(n,"job.exit"),jobRun:a(n,"job.run"),jobBg:a(n,"job.bg"),jobDone:a(n,"job.done"),jobPgid:a(n,"job.pgid"),jobPgidIdentity:a(n,"job.pgid-identity"),jobActivity:a(n,"job.activity"),jobDeadline:a(n,"job.deadline"),jobReported:a(n,"job.reported")}}o(b,"bashJobPaths");function A(t,e){try{const n=Number(y(t,b(t,e).jobPgid).trim());return Number.isInteger(n)&&n>1?n:void 0}catch{return}}o(A,"readJobPgid");function L(t,e){try{const n=y(t,b(t,e).jobPgidIdentity).trim();return n===""?void 0:n}catch{return}}o(L,"readJobPgidIdentity");function ft(t,e){const n=b(t,e),r={},s=A(t,e),i=L(t,e);s!==void 0&&(r.pgid=s),i!==void 0&&(r.pgidIdentity=i);const u=m(n.root,n.jobExit);u!==null&&Number.isSafeInteger(Number(u.trim()))&&u.trim()!==""&&(r.exitCode=Number(u.trim()));const f=m(n.root,n.jobDeadline);f!==null&&f.trim()!==""&&Number.isFinite(Number(f.trim()))&&(r.deadlineMs=Number(f.trim()));const d=m(n.root,n.jobActivity);if(d!==null){const[l,...h]=d.split(`
|
|
2
|
+
`),[B,j]=(l??"").split(" ").map(Number);Number.isFinite(B)&&Number.isFinite(j)&&(r.activity={lastActivityMs:B,sampledAtMs:j,files:h.filter(I=>I!=="")})}return r}o(ft,"readJobSupervisorState");function dt(t,e){w(t.root,t.jobDeadline,`${Math.trunc(e)}
|
|
3
3
|
`)}o(dt,"writeJobDeadlineFile");function lt(t){k(t.root,t.jobDeadline)}o(lt,"clearJobDeadlineFile");function bt(t){let e;try{e=M(t)}catch{return[]}return e.filter(n=>{const r=b(t,n);try{return(c(r,r.jobRun)||c(r,r.jobBg))&&!c(r,r.jobExit)}catch{return!1}})}o(bt,"unfinishedBashJobIds");const R=10,Y=19;function $(t){return a(g(t),"niceness")}o($,"bashNicenessPath");function ht(t){try{const e=Number(y(t,$(t)).trim());return!Number.isInteger(e)||e<0||e>Y?R:e}catch{return R}}o(ht,"readBashNiceness");function pt(t,e){w(p(t),$(t),`${Math.trunc(e)}
|
|
4
|
-
`)}o(pt,"writeBashNiceness");function mt(t,e){if(e===`launcher:${t}`)return N(t);try{return process.kill(-t,0),!0}catch(n){return n.code==="EPERM"}}o(mt,"isBashJobProcessGroupAlive");function gt(t,e){if(t===void 0||e===void 0)return!1;if(e===`launcher:${t}`)return!N(t);try{return process.kill(-t,0),!1}catch(n){return n.code==="ESRCH"}}o(gt,"isBashJobProcessConfirmedGone");async function Z(t,e){const n=C(t,e);if(n.reused||n.tree.length===0)return!1;const r=[...n.tree].reverse(),s=O(r);
|
|
4
|
+
`)}o(pt,"writeBashNiceness");function mt(t,e){if(e===`launcher:${t}`)return N(t);try{return process.kill(-t,0),!0}catch(n){return n.code==="EPERM"}}o(mt,"isBashJobProcessGroupAlive");function gt(t,e){if(t===void 0||e===void 0)return!1;if(e===`launcher:${t}`)return!N(t);try{return process.kill(-t,0),!1}catch(n){return n.code==="ESRCH"}}o(gt,"isBashJobProcessConfirmedGone");async function Z(t,e){const n=C(t,e);if(n.reused||n.tree.length===0)return!1;const r=[...n.tree].reverse(),s=O(r);J(r,"SIGTERM",n.identities),await new Promise(i=>setTimeout(i,400)),J(r,"SIGKILL",n.identities);try{process.kill(-t,"SIGKILL")}catch{}return s}o(Z,"cancelBashJobProcessTree");async function D(t,e,n){if(e!==`launcher:${t}`)return await Z(t,e);if(n===void 0)throw new Error("launcher job stop requires its owning node");try{if(!("ok"in await G({operation:"stop",pid:t,nodeId:n})))throw new Error("launcher did not stop job");return!0}catch(r){if(!(r instanceof z&&r.refusal==="invalid_spec"))throw r;return!1}}o(D,"signalBashJob");async function yt(t,e,n=!1,r,s){const i=b(t,e);if(!c(i,i.dir))return{kind:"missing"};if(!c(i,i.jobBg)&&!(n&&c(i,i.jobRun))||c(i,i.jobExit))return{kind:"retired",logPath:i.jobLog};const u=A(t,e),f=L(t,e);if(u===void 0||f===void 0)return{kind:"not-stoppable",logPath:i.jobLog};const d=a(i.dir,"job.stop");try{P(i.root,d,s===void 0?"":`${s}
|
|
5
5
|
`)}catch(l){if(l.code==="EEXIST")return{kind:"retired",logPath:i.jobLog};throw l}try{const l=await D(u,f,r);try{P(i.root,i.jobExit,`143
|
|
6
6
|
`)}catch(h){if(h.code!=="EEXIST")throw h}return{kind:"stopped",signaled:l,pgid:u,logPath:i.jobLog}}catch(l){throw k(i.root,d),l}}o(yt,"stopBackgroundBashJob");function Bt(t,e){if(e<=0)return[];const n=64*1024;let r;try{const s=_(t).size,i=Math.max(0,s-n),u=Buffer.alloc(Math.min(s,n));r=S(t,"r"),E(r,u,0,u.length,i);const f=u.toString("utf8"),d=(i>0?f.slice(f.indexOf(`
|
|
7
7
|
`)+1):f).split(`
|
|
8
|
-
`);return d[d.length-1]===""&&d.pop(),d.slice(-e)}catch{return[]}finally{r!==void 0&&x(r)}}o(Bt,"tailJobLog");function jt(t){let e;try{e=S(t,"r");const n=Buffer.alloc(64*1024);let r=0,s=0;for(;;){const i=E(e,n,0,n.length,null);if(i===0)break;for(let u=0;u<i;u+=1)n[u]===10&&(r+=1);s=n[i-1]}return s!==0&&s!==10?r+1:r}catch{return 0}finally{e!==void 0&&x(e)}}o(jt,"countJobLogLines");function xt(){return`${Date.now()}-${
|
|
9
|
-
`).map(n=>n.trim()).find(n=>n!=="")??"").replace(/\s+/g," ")}o(Et,"bashJobCommandLine");function V(t){try{return
|
|
8
|
+
`);return d[d.length-1]===""&&d.pop(),d.slice(-e)}catch{return[]}finally{r!==void 0&&x(r)}}o(Bt,"tailJobLog");function jt(t){let e;try{e=S(t,"r");const n=Buffer.alloc(64*1024);let r=0,s=0;for(;;){const i=E(e,n,0,n.length,null);if(i===0)break;for(let u=0;u<i;u+=1)n[u]===10&&(r+=1);s=n[i-1]}return s!==0&&s!==10?r+1:r}catch{return 0}finally{e!==void 0&&x(e)}}o(jt,"countJobLogLines");function xt(){return`${Date.now()}-${F(4).toString("hex")}`}o(xt,"newBashJobId");function Q(t){const e=t.indexOf("-");if(e<=0||e===t.length-1)return;const n=Number(t.slice(0,e));return Number.isFinite(n)?n:void 0}o(Q,"jobStartedAtMs");function St(t){const e=Math.max(0,Math.floor(t/1e3));if(e<60)return`${e}s`;const n=Math.floor(e/60),r=e%60;if(n<60)return`${n}m ${String(r).padStart(2,"0")}s`;const s=Math.floor(n/60),i=n%60;return`${s}h ${String(i).padStart(2,"0")}m`}o(St,"formatBashElapsed");function Et(t){return(t.split(`
|
|
9
|
+
`).map(n=>n.trim()).find(n=>n!=="")??"").replace(/\s+/g," ")}o(Et,"bashJobCommandLine");function V(t){try{return K(t.root,t.jobRun,t.jobBg),"backgrounded"}catch(e){if(e.code!=="ENOENT")throw e;return c(t,t.jobBg)?"already-backgrounded":c(t,t.jobDone)?"finished":"missing"}}o(V,"backgroundBashJob");function T(t){let e;try{e=M(t)}catch{return[]}return e.flatMap(n=>{const r=b(t,n);try{return c(r,r.cmdSh)&&c(r,r.jobLog)&&c(r,r.jobRun)?[r]:[]}catch{return[]}})}o(T,"runningBashJobs");function Nt(t){let e;for(const n of T(t)){const r=Q(n.jobId);r!==void 0&&(e===void 0||r<e)&&(e=r)}return e}o(Nt,"oldestRunningBashJobStartedAtMs");function Jt(t){const e=[];for(const n of T(t))V(n)==="backgrounded"&&e.push(n);return e}o(Jt,"backgroundRunningBashJobs");export{R as DEFAULT_BASH_NICENESS,Y as MAX_BASH_NICENESS,V as backgroundBashJob,Jt as backgroundRunningBashJobs,Et as bashJobCommandLine,b as bashJobPaths,g as bashJobsDir,$ as bashNicenessPath,Z as cancelBashJobProcessTree,lt as clearJobDeadlineFile,jt as countJobLogLines,St as formatBashElapsed,gt as isBashJobProcessConfirmedGone,mt as isBashJobProcessGroupAlive,ct as isSafeBashJobId,Q as jobStartedAtMs,xt as newBashJobId,at as normalizeBashJobPurpose,Nt as oldestRunningBashJobStartedAtMs,ht as readBashNiceness,A as readJobPgid,L as readJobPgidIdentity,ft as readJobSupervisorState,D as signalBashJob,yt as stopBackgroundBashJob,Bt as tailJobLog,bt as unfinishedBashJobIds,pt as writeBashNiceness,dt as writeJobDeadlineFile};
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var se=Object.defineProperty;var i=(e,n)=>se(e,"name",{value:n,configurable:!0});import{envNodeId as C}from"../../shared/env.js";import{lstatSync as de,realpathSync as H,rmdirSync as ue,rmSync as ce,statSync as le}from"node:fs";import{basename as _e,dirname as M,isAbsolute as pe,join as S,relative as fe,resolve as Ee,sep as we}from"node:path";import{removeTreeBeneath as P}from"../spaces/open-beneath.js";import{emitEvent as ye}from"../events/emit.js";import{deleteNodeSandboxes as $}from"../runtime/runner/delete-sandboxes.js";import{withCanvasWrite as p,openDb as d}from"./db.js";import{conversationStore as me,ConversationNotFoundError as Ne}from"../conversation-store/index.js";import{hasUnseenWakeMail as Re,UNSEEN_WAKE_MAIL_SQL as Se}from"./deliveries.js";import{isAppRun as q}from"./app-run.js";import{registerOutcomeAction as B}from"./outcome-actions.js";import{publish as he}from"../graph/events.js";import{nodeObject as Oe}from"../graph/objects.js";import{findNodeBySessionFileSql as Te}from"./sessions.js";import{hydrateFault as Le}from"./recovery.js";import{hasUnreconciledWorktree as De,openWorktree as ge,readWorktree as Ae,worktreeFromRow as ve}from"./worktrees.js";import{isPidAlive as ke,isPidPresent as z,recordedPidLiveness as Ue}from"./pid.js";import{ensureHome as xe,jobDir as je,nodeDir as We,nodeRunDir as J}from"./paths.js";import{appForNode as be,ensureNodeDirs as Ie,nodeAgentDir as Fe}from"./node-agent-paths.js";import{appSpace as L}from"../layout.js";import{createObject as Ce,getById as D,ownerForGrantee as He,setObjectKind as Me,setObjectName as Pe}from"../graph/objects.js";import{profileObject as $e}from"../graph/reader.js";import{writeActsFor as Y}from"../permissions/facts.js";import{CrtrError as qe}from"../errors.js";import{deleteNodeWithOwned as Be}from"../graph/deletion.js";import{SUBTREE_ALL_IDS_SQL as ze,SUBTREE_IDS_SQL as Je}from"./tree.js";import{filterAsync as y,mapAsync as h}from"../async-array.js";function E(e,n){if(e==null)return null;const t=JSON.stringify(e);if(t===void 0)throw new TypeError(`${n} must be JSON-serializable`);return t}i(E,"jsonValue");async function kn(e,n){if((await e.prepare("SELECT deleting_at FROM nodes WHERE node_id = ?").get(n))?.deleting_at)throw new Error("run is deleting")}i(kn,"assertRunNotDeleting");async function Q(e,n,t){try{return await $e(e,n,t)}catch(a){if(a instanceof qe&&a.code==="not_found")return null;throw a}}i(Q,"profileObjectFor");async function Ye(e,n){const t=await He(n,e.grantee??"app:terminal"),a=e.profile_id?await Q(n,e.profile_id,t):null;await Ce(n,{id:e.node_id,type:"node",kind:e.kind,owner:(a??t).id,privacy:"public",name:e.name,preview:""}),a===null&&e.sub&&await Y(n,e.node_id,e.sub),await n.prepare(`INSERT INTO nodes (node_id, description, title, icon, cycles, mode, lifecycle, cwd, host_kind, profile_id, parent, spawned_by, creator, fork_from, fork_source_file, created, passive_default, cycle_pending, model_override, persona_ack_json, review_binding_json, launch_config_json, scopes_json, isolated, status, intent, final_report, finalized_at, deadline_at, "window", tmux_session, pane, sub, grant_id, client_id, metadata_json, run_id, event_cursor, usage_json, deleting_at, caused_by, app) VALUES (${Array(42).fill("?").join(", ")})`).run(e.node_id,e.description??null,e.title??null,e.icon??null,e.cycles??null,e.mode,e.lifecycle,e.cwd,e.host_kind??null,e.profile_id??null,e.parent??null,e.spawned_by??null,e.creator??null,e.fork_from??null,e.fork_source_file??null,e.created,e.passive_default===!0?1:0,e.cycle_pending===!0?1:0,e.model_override??null,E(e.persona_ack,"persona_ack"),E(e.review_binding,"review_binding"),E(e.launch,"launch"),E(e.scopes,"scopes"),e.isolated===!0?1:0,e.status??"active",e.intent??null,e.final_report??null,e.finalized_at??null,e.deadline_at??null,e.window??null,e.tmux_session??null,e.pane??null,e.sub??null,e.grant_id??null,e.client_id??null,e.metadata_json??null,e.run_id??null,e.event_cursor??null,e.usage_json??null,e.deleting_at??null,e.caused_by??null,t.id)}i(Ye,"seedRow");function V(e){if(e.fault_id==null)return null;const n=Object.entries(e).filter(([t])=>t.startsWith("fault_")).map(([t,a])=>[t==="fault_id"?t:t.slice(6),a]);return Le(Object.fromEntries(n))}i(V,"faultFrom");function f(e){const n={node_id:e.node_id,name:e.name,description:e.description??void 0,cycles:e.cycles??void 0,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind??null,profile_id:e.profile_id??null,scopes:e.scopes_json==null?null:JSON.parse(e.scopes_json),isolated:e.isolated===1,grantee:e.grantee,sub:e.sub??null,grant_id:e.grant_id??null,client_id:e.client_id??null,metadata_json:e.metadata_json??null,run_id:e.run_id??null,event_cursor:e.event_cursor??null,last_activity_at:e.last_activity_at??null,usage_json:e.usage_json??null,caused_by:e.caused_by??null,last_turn_error_json:e.last_turn_error_json??null,deleting_at:e.deleting_at??null,parent:e.parent??null,created:e.created,intent:e.intent??null,frozen_at:e.frozen_at??null,respawn_failures:e.respawn_failures??0,respawn_not_before:e.respawn_not_before??null,launched_at:e.launched_at??null,last_settled_at:e.last_settled_at??null,terminal_reason:e.terminal_reason??null,final_report:e.final_report??null,finalized_at:e.finalized_at??null,outcome_kind:e.outcome_kind??null,outcome_reason:e.outcome_reason??null,outcome_at:e.outcome_at??null,outcome_revision:e.outcome_revision??0,outcome_detail_json:e.outcome_detail_json??null,deadline_at:e.deadline_at??null,telemetry_tokens_in:e.telemetry_tokens_in??null,telemetry_context_tokens:e.telemetry_context_tokens??null,telemetry_last_activity:e.telemetry_last_activity??null,telemetry_updated_at:e.telemetry_updated_at??null,pi_pid:e.pi_pid??null,pi_pid_identity:e.pi_pid_identity??null,window:e.window??null,tmux_session:e.tmux_session??null,pane:e.pane??null,fault:null,streaming:!1},t=z(n.pi_pid),a=V(e);return n.fault=a?.link==="pi\u2192provider"&&a.retry.by==="daemon"&&a.retry.disposition==="auto"&&!t?null:a,n.streaming=e.turn_open_at!==null&&e.turn_closed_at===null&&t,n}i(f,"rowFrom");async function g(e,n){return n??=await Ae(e.node_id),{...f(e),title:e.title??void 0,icon:e.icon??void 0,spawned_by:e.spawned_by??null,creator:e.creator??null,fork_from:e.fork_from??null,fork_source_file:e.fork_source_file??null,passive_default:e.passive_default===1,cycle_pending:e.cycle_pending===1,model_override:e.model_override??null,scopes:e.scopes_json==null?null:JSON.parse(e.scopes_json),persona_ack:e.persona_ack_json==null?void 0:JSON.parse(e.persona_ack_json),review_binding:e.review_binding_json==null?void 0:JSON.parse(e.review_binding_json),launch:e.launch_config_json==null?void 0:JSON.parse(e.launch_config_json),pi_session_id:e.pi_session_id??null,pi_session_file:e.pi_session_file??null,...n===null?{}:{managed_worktree:n}}}i(g,"metaFrom");async function Un(e,n={}){return xe(),await p(async t=>{await Ye(e,t),e.managed_worktree!==void 0&&e.managed_worktree!==null&&await ge(e.node_id,e.managed_worktree,t),n.outcomeDelivery!==void 0&&await B(t,e.node_id,n.outcomeDelivery),await n.withinCreate?.(t,e)}),await Ie(e.node_id),await O(e.node_id)}i(Un,"createNode");async function O(e){const n=await(await d()).prepare("SELECT * FROM node_rows WHERE node_id = ?").get(e);return n===void 0?null:await g(n)}i(O,"getNode");async function xn(e){if(e.length===0)return[];const n=v.map(o=>`w.${o} AS worktree_${o}`).join(", "),t=await(await d()).prepareUncached(`SELECT n.*, ${n} FROM node_rows n LEFT JOIN worktrees w ON w.node_id = n.node_id WHERE n.node_id IN (${e.map(()=>"?").join(",")})`).all(...e),a=new Map(t.map(o=>[o.node_id,o]));return await h(e.map(o=>a.get(o)).filter(o=>o!==void 0),async o=>await g(o,G(o)))}i(xn,"getNodes");const Qe=1440*60*1e3;function K(e){return{requestKey:e.request_key,nodeId:e.node_id,state:e.state}}i(K,"createRequestRecord");async function jn(e){const n=await(await d()).prepareUncached("SELECT request_key, node_id, state FROM create_requests WHERE request_key = ?").get(e);return n===void 0?null:K(n)}i(jn,"findCreateRequest");async function Wn(e){return await p(async n=>{const t=Date.now();await n.prepareUncached("DELETE FROM create_requests WHERE expires_at <= ?").run(t),await n.prepareUncached("INSERT INTO create_requests (request_key, node_id, expires_at, state) VALUES (?, NULL, ?, 'reserved') ON CONFLICT (request_key) DO NOTHING").run(e,t+Qe);const a=await n.prepareUncached("SELECT request_key, node_id, state FROM create_requests WHERE request_key = ?").get(e);return K(a)})}i(Wn,"reserveCreateRequest");async function bn(e=Date.now()){return Number((await(await d()).prepareUncached("DELETE FROM create_requests WHERE expires_at <= ?").run(e)).changes)}i(bn,"pruneExpiredCreateRequests");async function In(e,n){await(await d()).prepareUncached("UPDATE create_requests SET node_id = ?, state = 'complete' WHERE request_key = ?").run(n,e)}i(In,"recordCreateRequestNode");async function Fn(e,n){const t=await d();return await t.prepareUncached("UPDATE create_requests SET node_id = ?, state = 'reserved' WHERE request_key = ? AND node_id IS NULL").run(n,e),(await t.prepareUncached("SELECT node_id FROM create_requests WHERE request_key = ?").get(e))?.node_id??null}i(Fn,"reserveCreateRequestNode");async function Cn(e,n){await(await d()).prepareUncached("UPDATE create_requests SET state = 'complete' WHERE request_key = ? AND node_id = ?").run(e,n)}i(Cn,"completeCreateRequest");async function Hn(e,n){await p(async t=>{if(n===null){await t.prepareUncached("DELETE FROM create_requests WHERE request_key = ? AND node_id IS NULL").run(e);return}await t.prepareUncached("DELETE FROM create_requests WHERE request_key = ? AND node_id = ?").run(e,n)})}i(Hn,"abandonCreateRequest");function Mn(e){return Ee(e)}i(Mn,"canonicalSessionFile");async function Pn(e){const n=await Te(e);return n===null?null:await O(n)}i(Pn,"findNodeBySessionFile");async function $n(e){const n=await(await d()).prepare("SELECT * FROM node_rows WHERE node_id = ?").get(e);return n?f(n):null}i($n,"getRow");async function qn(e){const n=await(await d()).prepare("SELECT * FROM node_rows WHERE pane = ?").get(e);return n?f(n):null}i(qn,"getRowByPane");async function Bn(e){return(await(await d()).prepare(`SELECT * FROM node_rows
|
|
1
|
+
var ue=Object.defineProperty;var i=(e,n)=>ue(e,"name",{value:n,configurable:!0});import{envNodeId as C}from"../../shared/env.js";import{lstatSync as ce,realpathSync as H,rmdirSync as le,rmSync as _e,statSync as pe}from"node:fs";import{basename as fe,dirname as M,isAbsolute as we,join as S,relative as Ee,resolve as ye,sep as me}from"node:path";import{removeTreeBeneath as P}from"../spaces/open-beneath.js";import{emitEvent as Ne}from"../events/emit.js";import{deleteNodeSandboxes as $}from"../runtime/runner/delete-sandboxes.js";import{withCanvasWrite as p,openDb as d}from"./db.js";import{conversationStore as Re,ConversationNotFoundError as Se}from"../conversation-store/index.js";import{hasUnseenWakeMail as he,UNSEEN_WAKE_MAIL_SQL as Oe}from"./deliveries.js";import{isAppRun as q}from"./app-run.js";import{registerOutcomeAction as B}from"./outcome-actions.js";import{publish as Te}from"../graph/events.js";import{nodeObject as Le}from"../graph/objects.js";import{findNodeBySessionFileSql as De}from"./sessions.js";import{hydrateFault as ge}from"./recovery.js";import{hasUnreconciledWorktree as ve,openWorktree as Ae,readWorktree as ke,worktreeFromRow as Ue}from"./worktrees.js";import{isPidAlive as xe,isPidPresent as z,recordedPidLiveness as je}from"./pid.js";import{isCloudRole as We}from"./person-state.js";import{ensureHome as be,jobDir as Ie,nodeDir as Fe,nodeRunDir as J}from"./paths.js";import{appForNode as Ce,ensureNodeDirs as He,nodeAgentDir as Me}from"./node-agent-paths.js";import{appSpace as L}from"../layout.js";import{createObject as Pe,getById as D,ownerForGrantee as $e,setObjectKind as qe,setObjectName as Be}from"../graph/objects.js";import{profileObject as ze}from"../graph/reader.js";import{writeActsFor as Y}from"../permissions/facts.js";import{CrtrError as Je}from"../errors.js";import{deleteNodeWithOwned as Ye}from"../graph/deletion.js";import{SUBTREE_ALL_IDS_SQL as Qe,SUBTREE_IDS_SQL as Ve}from"./tree.js";import{filterAsync as y,mapAsync as h}from"../async-array.js";function w(e,n){if(e==null)return null;const t=JSON.stringify(e);if(t===void 0)throw new TypeError(`${n} must be JSON-serializable`);return t}i(w,"jsonValue");async function Wn(e,n){if((await e.prepare("SELECT deleting_at FROM nodes WHERE node_id = ?").get(n))?.deleting_at)throw new Error("run is deleting")}i(Wn,"assertRunNotDeleting");async function Q(e,n,t){try{return await ze(e,n,t)}catch(a){if(a instanceof Je&&a.code==="not_found")return null;throw a}}i(Q,"profileObjectFor");async function Ke(e,n){const t=await $e(n,e.grantee??"app:terminal"),a=e.profile_id?await Q(n,e.profile_id,t):null;await Pe(n,{id:e.node_id,type:"node",kind:e.kind,owner:(a??t).id,privacy:"public",name:e.name,preview:""}),a===null&&e.sub&&await Y(n,e.node_id,e.sub),await n.prepare(`INSERT INTO nodes (node_id, description, title, icon, cycles, mode, lifecycle, cwd, host_kind, profile_id, parent, spawned_by, creator, fork_from, fork_source_file, created, passive_default, cycle_pending, model_override, persona_ack_json, review_binding_json, launch_config_json, scopes_json, isolated, status, intent, final_report, finalized_at, deadline_at, "window", tmux_session, pane, sub, grant_id, client_id, metadata_json, run_id, event_cursor, usage_json, deleting_at, caused_by, app) VALUES (${Array(42).fill("?").join(", ")})`).run(e.node_id,e.description??null,e.title??null,e.icon??null,e.cycles??null,e.mode,e.lifecycle,e.cwd,e.host_kind??null,e.profile_id??null,e.parent??null,e.spawned_by??null,e.creator??null,e.fork_from??null,e.fork_source_file??null,e.created,e.passive_default===!0?1:0,e.cycle_pending===!0?1:0,e.model_override??null,w(e.persona_ack,"persona_ack"),w(e.review_binding,"review_binding"),w(e.launch,"launch"),w(e.scopes,"scopes"),e.isolated===!0?1:0,e.status??"active",e.intent??null,e.final_report??null,e.finalized_at??null,e.deadline_at??null,e.window??null,e.tmux_session??null,e.pane??null,e.sub??null,e.grant_id??null,e.client_id??null,e.metadata_json??null,e.run_id??null,e.event_cursor??null,e.usage_json??null,e.deleting_at??null,e.caused_by??null,t.id)}i(Ke,"seedRow");function V(e){if(e.fault_id==null)return null;const n=Object.entries(e).filter(([t])=>t.startsWith("fault_")).map(([t,a])=>[t==="fault_id"?t:t.slice(6),a]);return ge(Object.fromEntries(n))}i(V,"faultFrom");const K=i(e=>e.turn_open_at!=null&&e.turn_closed_at==null,"turnOpen"),G=i(e=>e||We(),"engineLive");function f(e){const n={node_id:e.node_id,name:e.name,description:e.description??void 0,cycles:e.cycles??void 0,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind??null,profile_id:e.profile_id??null,scopes:e.scopes_json==null?null:JSON.parse(e.scopes_json),isolated:e.isolated===1,grantee:e.grantee,sub:e.sub??null,grant_id:e.grant_id??null,client_id:e.client_id??null,metadata_json:e.metadata_json??null,run_id:e.run_id??null,event_cursor:e.event_cursor??null,last_activity_at:e.last_activity_at??null,usage_json:e.usage_json??null,caused_by:e.caused_by??null,last_turn_error_json:e.last_turn_error_json??null,deleting_at:e.deleting_at??null,parent:e.parent??null,created:e.created,intent:e.intent??null,frozen_at:e.frozen_at??null,respawn_failures:e.respawn_failures??0,respawn_not_before:e.respawn_not_before??null,launched_at:e.launched_at??null,last_settled_at:e.last_settled_at??null,terminal_reason:e.terminal_reason??null,final_report:e.final_report??null,finalized_at:e.finalized_at??null,outcome_kind:e.outcome_kind??null,outcome_reason:e.outcome_reason??null,outcome_at:e.outcome_at??null,outcome_revision:e.outcome_revision??0,outcome_detail_json:e.outcome_detail_json??null,deadline_at:e.deadline_at??null,telemetry_tokens_in:e.telemetry_tokens_in??null,telemetry_context_tokens:e.telemetry_context_tokens??null,telemetry_last_activity:e.telemetry_last_activity??null,telemetry_updated_at:e.telemetry_updated_at??null,pi_pid:e.pi_pid??null,pi_pid_identity:e.pi_pid_identity??null,window:e.window??null,tmux_session:e.tmux_session??null,pane:e.pane??null,fault:null,streaming:!1},t=z(n.pi_pid),a=V(e);return n.fault=a?.link==="pi\u2192provider"&&a.retry.by==="daemon"&&a.retry.disposition==="auto"&&!t?null:a,n.streaming=K(e)&&G(t),n}i(f,"rowFrom");async function g(e,n){return n??=await ke(e.node_id),{...f(e),title:e.title??void 0,icon:e.icon??void 0,spawned_by:e.spawned_by??null,creator:e.creator??null,fork_from:e.fork_from??null,fork_source_file:e.fork_source_file??null,passive_default:e.passive_default===1,cycle_pending:e.cycle_pending===1,model_override:e.model_override??null,scopes:e.scopes_json==null?null:JSON.parse(e.scopes_json),persona_ack:e.persona_ack_json==null?void 0:JSON.parse(e.persona_ack_json),review_binding:e.review_binding_json==null?void 0:JSON.parse(e.review_binding_json),launch:e.launch_config_json==null?void 0:JSON.parse(e.launch_config_json),pi_session_id:e.pi_session_id??null,pi_session_file:e.pi_session_file??null,...n===null?{}:{managed_worktree:n}}}i(g,"metaFrom");async function bn(e,n={}){return be(),await p(async t=>{await Ke(e,t),e.managed_worktree!==void 0&&e.managed_worktree!==null&&await Ae(e.node_id,e.managed_worktree,t),n.outcomeDelivery!==void 0&&await B(t,e.node_id,n.outcomeDelivery),await n.withinCreate?.(t,e)}),await He(e.node_id),await O(e.node_id)}i(bn,"createNode");async function O(e){const n=await(await d()).prepare("SELECT * FROM node_rows WHERE node_id = ?").get(e);return n===void 0?null:await g(n)}i(O,"getNode");async function In(e){if(e.length===0)return[];const n=A.map(o=>`w.${o} AS worktree_${o}`).join(", "),t=await(await d()).prepareUncached(`SELECT n.*, ${n} FROM node_rows n LEFT JOIN worktrees w ON w.node_id = n.node_id WHERE n.node_id IN (${e.map(()=>"?").join(",")})`).all(...e),a=new Map(t.map(o=>[o.node_id,o]));return await h(e.map(o=>a.get(o)).filter(o=>o!==void 0),async o=>await g(o,Z(o)))}i(In,"getNodes");const Ge=1440*60*1e3;function X(e){return{requestKey:e.request_key,nodeId:e.node_id,state:e.state}}i(X,"createRequestRecord");async function Fn(e){const n=await(await d()).prepareUncached("SELECT request_key, node_id, state FROM create_requests WHERE request_key = ?").get(e);return n===void 0?null:X(n)}i(Fn,"findCreateRequest");async function Cn(e){return await p(async n=>{const t=Date.now();await n.prepareUncached("DELETE FROM create_requests WHERE expires_at <= ?").run(t),await n.prepareUncached("INSERT INTO create_requests (request_key, node_id, expires_at, state) VALUES (?, NULL, ?, 'reserved') ON CONFLICT (request_key) DO NOTHING").run(e,t+Ge);const a=await n.prepareUncached("SELECT request_key, node_id, state FROM create_requests WHERE request_key = ?").get(e);return X(a)})}i(Cn,"reserveCreateRequest");async function Hn(e=Date.now()){return Number((await(await d()).prepareUncached("DELETE FROM create_requests WHERE expires_at <= ?").run(e)).changes)}i(Hn,"pruneExpiredCreateRequests");async function Mn(e,n){await(await d()).prepareUncached("UPDATE create_requests SET node_id = ?, state = 'complete' WHERE request_key = ?").run(n,e)}i(Mn,"recordCreateRequestNode");async function Pn(e,n){const t=await d();return await t.prepareUncached("UPDATE create_requests SET node_id = ?, state = 'reserved' WHERE request_key = ? AND node_id IS NULL").run(n,e),(await t.prepareUncached("SELECT node_id FROM create_requests WHERE request_key = ?").get(e))?.node_id??null}i(Pn,"reserveCreateRequestNode");async function $n(e,n){await(await d()).prepareUncached("UPDATE create_requests SET state = 'complete' WHERE request_key = ? AND node_id = ?").run(e,n)}i($n,"completeCreateRequest");async function qn(e,n){await p(async t=>{if(n===null){await t.prepareUncached("DELETE FROM create_requests WHERE request_key = ? AND node_id IS NULL").run(e);return}await t.prepareUncached("DELETE FROM create_requests WHERE request_key = ? AND node_id = ?").run(e,n)})}i(qn,"abandonCreateRequest");function Bn(e){return ye(e)}i(Bn,"canonicalSessionFile");async function zn(e){const n=await De(e);return n===null?null:await O(n)}i(zn,"findNodeBySessionFile");async function Jn(e){const n=await(await d()).prepare("SELECT * FROM node_rows WHERE node_id = ?").get(e);return n?f(n):null}i(Jn,"getRow");async function Yn(e){const n=await(await d()).prepare("SELECT * FROM node_rows WHERE pane = ?").get(e);return n?f(n):null}i(Yn,"getRowByPane");async function Qn(e){return(await(await d()).prepare(`SELECT * FROM node_rows
|
|
2
2
|
WHERE deadline_at IS NOT NULL AND outcome_at IS NULL
|
|
3
3
|
AND deadline_at <= ? AND status IN ('active','idle') AND kind != 'human'
|
|
4
|
-
ORDER BY deadline_at, created, node_id`).all(e)).map(f)}i(
|
|
5
|
-
WHERE profile_id = ? AND deadline_at IS NOT NULL AND status IN ('active', 'idle')`).all(e),o=t.prepare("UPDATE nodes SET deadline_at = ? WHERE node_id = ? AND deadline_at = ?");let r=0;for(const s of a){const c=Date.parse(s.deadline_at);Number.isNaN(c)||(r+=Number((await o.run(new Date(c+n).toISOString(),s.node_id,s.deadline_at)).changes))}return r})}i(
|
|
4
|
+
ORDER BY deadline_at, created, node_id`).all(e)).map(f)}i(Qn,"dueNodeDeadlines");async function Vn(e,n){return Number((await(await d()).prepare("UPDATE nodes SET deadline_at = ? WHERE node_id = ?").run(n,e)).changes)===1}i(Vn,"setNodeDeadline");async function Kn(e,n){return!Number.isFinite(n)||n<=0?0:await p(async t=>{const a=await t.prepare(`SELECT node_id, deadline_at FROM nodes
|
|
5
|
+
WHERE profile_id = ? AND deadline_at IS NOT NULL AND status IN ('active', 'idle')`).all(e),o=t.prepare("UPDATE nodes SET deadline_at = ? WHERE node_id = ? AND deadline_at = ?");let r=0;for(const s of a){const c=Date.parse(s.deadline_at);Number.isNaN(c)||(r+=Number((await o.run(new Date(c+n).toISOString(),s.node_id,s.deadline_at)).changes))}return r})}i(Kn,"shiftProfileNodeDeadlines");function v(e,n){if(e==null)return null;if(typeof e=="string"||typeof e=="number"||typeof e=="bigint"||e instanceof Uint8Array)return e;throw new TypeError(`${n} must be a SQLite scalar`)}i(v,"sqlInput");async function Gn(e,n){const t=[],a=i((r,s=r)=>{Object.prototype.hasOwnProperty.call(n,r)&&t.push([s,v(n[r],r)])},"add");if(a("description"),a("title"),a("icon"),a("cycles"),a("mode"),a("lifecycle"),a("cwd"),a("host_kind"),a("profile_id"),a("parent"),a("spawned_by"),a("creator"),a("fork_from"),a("fork_source_file"),a("model_override"),Object.prototype.hasOwnProperty.call(n,"passive_default")&&t.push(["passive_default",n.passive_default===!0?1:0]),Object.prototype.hasOwnProperty.call(n,"cycle_pending")&&t.push(["cycle_pending",n.cycle_pending===!0?1:0]),Object.prototype.hasOwnProperty.call(n,"persona_ack")&&t.push(["persona_ack_json",w(n.persona_ack,"persona_ack")]),Object.prototype.hasOwnProperty.call(n,"review_binding")&&t.push(["review_binding_json",w(n.review_binding,"review_binding")]),Object.prototype.hasOwnProperty.call(n,"isolated"))throw new TypeError("isolated cannot change after node creation");Object.prototype.hasOwnProperty.call(n,"scopes")&&t.push(["scopes_json",w(n.scopes,"scopes")]),Object.prototype.hasOwnProperty.call(n,"launch")&&t.push(["launch_config_json",w(n.launch,"launch")]);const o=i(r=>Object.prototype.hasOwnProperty.call(n,r),"has");return await p(async r=>{const s=await D(r,e);if(s===null||s.type!=="node")throw new Error(`unknown node: ${e}`);if(o("name")&&await Be(r,s,v(n.name,"name")),o("kind")&&await qe(r,s,v(n.kind,"kind")),t.length===0)return;if(o("profile_id")){const u=await r.prepare("SELECT app FROM nodes WHERE node_id = ?").get(e),_=u?.app?await D(r,u.app):null;if(_){const E=n.profile_id?await Q(r,n.profile_id,_):null;await r.prepare("UPDATE objects SET owner = ? WHERE id = ?").run((E??_).id,e);const N=(await r.prepare("SELECT sub FROM nodes WHERE node_id = ?").get(e)).sub;E===null&&N&&await Y(r,e,N)}}if((await r.prepareUncached(`UPDATE nodes SET ${t.map(([u])=>`${u} = ?`).join(", ")} WHERE node_id = ?`).run(...t.map(([,u])=>u),e)).changes!==1)throw new Error(`unknown node: ${e}`)}),await O(e)}i(Gn,"updateNode");async function Xn(e,n){await(await d()).prepare("UPDATE nodes SET status = ? WHERE node_id = ?").run(n,e)}i(Xn,"setStatus");async function Zn(e,n){await(await d()).prepare("UPDATE nodes SET intent = ? WHERE node_id = ?").run(n??null,e)}i(Zn,"setIntent");async function et(e,n,t={}){if(t.outcome===void 0){const o=[],r=[];Object.prototype.hasOwnProperty.call(n,"status")&&(o.push("status = ?"),r.push(n.status??null)),Object.prototype.hasOwnProperty.call(n,"intent")&&(o.push("intent = ?"),r.push(n.intent??null)),Object.prototype.hasOwnProperty.call(n,"terminal_reason")&&(o.push("terminal_reason = ?"),r.push(n.terminal_reason??null));const s=["node_id = ?"];r.push(e),t.fromStatuses!==void 0&&(s.push(`status IN (${t.fromStatuses.map(()=>"?").join(", ")})`),r.push(...t.fromStatuses)),t.requireNoFinalReport===!0&&s.push("final_report IS NULL");const c=await(await d()).prepareUncached(`UPDATE nodes SET ${o.join(", ")} WHERE ${s.join(" AND ")}`).run(...r);return Number(c.changes)}const a=t.outcome;return await p(async o=>{const r=[],s=[];Object.prototype.hasOwnProperty.call(n,"status")&&(r.push("status = ?"),s.push(n.status??null)),Object.prototype.hasOwnProperty.call(n,"intent")&&(r.push("intent = ?"),s.push(n.intent??null)),Object.prototype.hasOwnProperty.call(n,"terminal_reason")&&(r.push("terminal_reason = ?"),s.push(n.terminal_reason??null));const c=i((N,R)=>a.supersede===!0?"?":`CASE WHEN outcome_at IS NULL THEN ? ELSE ${R} END`,"outcomeValue");r.push(`outcome_kind = ${c(a.kind,"outcome_kind")}`,`outcome_reason = ${c(a.reason,"outcome_reason")}`,`outcome_detail_json = ${c(a.detailJson,"outcome_detail_json")}`,`outcome_revision = ${a.supersede===!0?"outcome_revision + 1":"CASE WHEN outcome_at IS NULL THEN outcome_revision + 1 ELSE outcome_revision END"}`,`outcome_at = ${c(a.at,"outcome_at")}`),s.push(a.kind,a.reason,a.detailJson,a.at);const u=["node_id = ?"];s.push(e),t.fromStatuses!==void 0&&(u.push(`status IN (${t.fromStatuses.map(()=>"?").join(", ")})`),s.push(...t.fromStatuses)),t.requireNoFinalReport===!0&&u.push("final_report IS NULL");const _=await o.prepareUncached(`UPDATE nodes SET ${r.join(", ")} WHERE ${u.join(" AND ")}`).run(...s);if(Number(_.changes)===0)return 0;const E=await o.prepare("SELECT outcome_at FROM nodes WHERE node_id = ?").get(e);return(a.supersede===!0||E.outcome_at===a.at)&&a.documentJson!==null&&a.documentJson!==void 0&&await Te(o,{event:"outcome",object:await Le(o,e),actor:null,attrs:{revision:Number((await o.prepare("SELECT outcome_revision FROM nodes WHERE node_id = ?").get(e)).outcome_revision)},messageBody:JSON.parse(a.documentJson)}),Number(_.changes)})}i(et,"transitionStatusIntent");async function nt(e){return(await(await d()).prepare("SELECT final_report FROM nodes WHERE node_id = ?").get(e))?.final_report??null}i(nt,"getFinalReport");async function tt(e,n){return(await(await d()).prepare("UPDATE nodes SET final_report = NULL, finalized_at = NULL WHERE node_id = ? AND final_report = ?").run(e,n)).changes>0}i(tt,"clearFinalReportIfMatches");async function at(e,n){await(await d()).prepare('UPDATE nodes SET tmux_session = ?, "window" = ?, pane = ? WHERE node_id = ?').run(n.tmux_session??null,n.window??null,n.pane??null,e)}i(at,"setPresence");async function it(e,n){await(await d()).prepare("UPDATE nodes SET launched_at = ?, frozen_at = NULL, respawn_not_before = NULL WHERE node_id = ?").run(n,e)}i(it,"recordLaunch");async function ot(e,n){await(await d()).prepare("UPDATE nodes SET last_settled_at = ? WHERE node_id = ?").run(n,e)}i(ot,"recordSettledTurn");async function rt(e,n){await(await d()).prepare("UPDATE nodes SET frozen_at = ? WHERE node_id = ?").run(n,e)}i(rt,"setFrozen");async function st(e){await(await d()).prepare("UPDATE nodes SET frozen_at = NULL WHERE node_id = ?").run(e)}i(st,"clearFrozen");async function dt(e,n){await(await d()).prepare("UPDATE nodes SET respawn_failures = ?, respawn_not_before = ? WHERE node_id = ?").run(n.failures,n.notBefore,e)}i(dt,"recordRespawnAttempt");const m="node_id NOT IN (SELECT node_id FROM warm_pool)",A=["state","cleanup_state","path","branch","repo_root","base_ref","base_sha","created_at","closed_at","next_attempt_at","attempts","quarantined","sweep_reason","sweep_detail","sweep_last_at","sweep_observed_json","abandoned_json","land_intent_json","disposal_json"];function Z(e){return e.worktree_state===null?null:Ue(Object.fromEntries(A.map(n=>[n,e[`worktree_${n}`]])))}i(Z,"worktreeFromProjection");async function ut(e){const n=A.map(a=>`w.${a} AS worktree_${a}`).join(", "),t=await(await d()).prepareUncached(`SELECT n.*, ${n} FROM node_rows n LEFT JOIN worktrees w ON w.node_id = n.node_id WHERE n.profile_id = ? ORDER BY n.created`).all(e);return await h(t,async a=>await g(a,Z(a)))}i(ut,"listNodesByProfile");async function ct(){return(await(await d()).prepare(`SELECT
|
|
6
6
|
node_id, name, description, kind, mode, lifecycle, status, cwd, profile_id,
|
|
7
7
|
grantee, parent, created, frozen_at, terminal_reason, final_report,
|
|
8
8
|
telemetry_tokens_in, telemetry_updated_at, pi_pid, turn_open_at, turn_closed_at,
|
|
@@ -10,13 +10,13 @@ var se=Object.defineProperty;var i=(e,n)=>se(e,"name",{value:n,configurable:!0})
|
|
|
10
10
|
fault_operation_id, fault_anchor_entry_id, fault_retry_disposition,
|
|
11
11
|
fault_retry_by, fault_retry_attempt, fault_retry_max, fault_retry_next_at,
|
|
12
12
|
fault_provider_error_json
|
|
13
|
-
FROM node_rows WHERE ${m} ORDER BY created`).all()).map(f)}i(
|
|
13
|
+
FROM node_rows WHERE ${m} ORDER BY created`).all()).map(f)}i(ct,"browseNodes");async function lt(e,n){await(await d()).prepare(`UPDATE nodes
|
|
14
14
|
SET telemetry_tokens_in = ?,
|
|
15
15
|
telemetry_context_tokens = COALESCE(?, telemetry_context_tokens),
|
|
16
16
|
telemetry_last_activity = COALESCE(?, telemetry_last_activity),
|
|
17
17
|
telemetry_updated_at = ?
|
|
18
18
|
WHERE node_id = ?
|
|
19
|
-
AND (telemetry_updated_at IS NULL OR telemetry_updated_at < ?)`).run(n.tokensIn,n.contextTokens,n.lastActivity,n.updatedAt,e,n.updatedAt)}i(
|
|
19
|
+
AND (telemetry_updated_at IS NULL OR telemetry_updated_at < ?)`).run(n.tokensIn,n.contextTokens,n.lastActivity,n.updatedAt,e,n.updatedAt)}i(lt,"updateNodeTelemetry");async function _t(){return(await(await d()).prepare(`SELECT
|
|
20
20
|
node_id, name, description, cycles, kind, status, frozen_at,
|
|
21
21
|
telemetry_context_tokens, telemetry_last_activity,
|
|
22
22
|
pi_pid, turn_open_at, turn_closed_at,
|
|
@@ -24,14 +24,14 @@ var se=Object.defineProperty;var i=(e,n)=>se(e,"name",{value:n,configurable:!0})
|
|
|
24
24
|
fault_operation_id, fault_anchor_entry_id, fault_retry_disposition,
|
|
25
25
|
fault_retry_by, fault_retry_attempt, fault_retry_max, fault_retry_next_at,
|
|
26
26
|
fault_provider_error_json
|
|
27
|
-
FROM node_rows WHERE ${m} ORDER BY created`).all()).map(n=>{const t=n.pi_pid??null,a=z(t),o=V(n);return{node_id:n.node_id,name:n.name,description:n.description??null,cycles:n.cycles??null,kind:n.kind,status:n.status,frozen_at:n.frozen_at??null,pi_pid:t,telemetry_context_tokens:n.telemetry_context_tokens??null,telemetry_last_activity:n.telemetry_last_activity??null,fault:o?.link==="pi\u2192provider"&&o.retry.by==="daemon"&&o.retry.disposition==="auto"&&!a?null:o,streaming:n
|
|
27
|
+
FROM node_rows WHERE ${m} ORDER BY created`).all()).map(n=>{const t=n.pi_pid??null,a=z(t),o=V(n);return{node_id:n.node_id,name:n.name,description:n.description??null,cycles:n.cycles??null,kind:n.kind,status:n.status,frozen_at:n.frozen_at??null,pi_pid:t,telemetry_context_tokens:n.telemetry_context_tokens??null,telemetry_last_activity:n.telemetry_last_activity??null,fault:o?.link==="pi\u2192provider"&&o.retry.by==="daemon"&&o.retry.disposition==="auto"&&!a?null:o,streaming:K(n)&&G(a)}})}i(_t,"graphNodes");async function Xe(e){const n=[m],t=[];if(e?.under!==void 0&&(e.underInclusive===!0?(n.push(`(node_id IN (${Qe}) OR node_id = ?)`),t.push(e.under,e.under,e.under)):(n.push(`node_id IN (${Ve})`),t.push(e.under,e.under))),e?.lifecycle!==void 0&&(n.push("lifecycle = ?"),t.push(e.lifecycle)),e?.kind!==void 0&&(n.push("kind = ?"),t.push(e.kind)),e?.mode!==void 0&&(n.push("mode = ?"),t.push(e.mode)),e?.profileId!==void 0&&(n.push("profile_id = ?"),t.push(e.profileId)),e?.profilePrefix!==void 0&&(n.push("profile_id LIKE ? ESCAPE '\\'"),t.push(`${e.profilePrefix.replace(/[\\%_]/g,o=>`\\${o}`)}%`)),e?.parent!==void 0&&(n.push("parent = ?"),t.push(e.parent)),e?.topLevel===!0&&n.push("parent IS NULL"),e?.hanging===!0&&n.push("parent IS NOT NULL AND parent NOT IN (SELECT node_id FROM node_rows)"),e?.status!==void 0){const o=Array.isArray(e.status)?e.status:[e.status];n.push(`status IN (${o.map(()=>"?").join(",")})`),t.push(...o)}return e?.withRecordedPid===!0&&n.push("pi_pid IS NOT NULL"),e?.withRecordedPidOrFrozen===!0&&n.push("(pi_pid IS NOT NULL OR frozen_at IS NOT NULL)"),(await(await d()).prepareUncached(`SELECT * FROM node_rows WHERE ${n.join(" AND ")} ORDER BY created`).all(...t)).map(f)}i(Xe,"listNodes");const Ze=`SELECT
|
|
28
28
|
node_id, created, launched_at, last_settled_at, finalized_at,
|
|
29
29
|
outcome_at, last_activity_at, pane, "window", tmux_session
|
|
30
30
|
FROM nodes
|
|
31
31
|
WHERE ${m}
|
|
32
32
|
AND status IN ('done', 'canceled', 'dead')
|
|
33
33
|
AND (pane IS NOT NULL OR "window" IS NOT NULL OR tmux_session IS NOT NULL)
|
|
34
|
-
ORDER BY created`;async function
|
|
34
|
+
ORDER BY created`;async function pt(){return await(await d()).prepare(Ze).all()}i(pt,"listTerminalPlacementResidue");const en=`WITH candidates AS MATERIALIZED (
|
|
35
35
|
SELECT node_id FROM nodes WHERE status IN ('active', 'idle')
|
|
36
36
|
UNION
|
|
37
37
|
SELECT node_id FROM nodes
|
|
@@ -45,23 +45,23 @@ var se=Object.defineProperty;var i=(e,n)=>se(e,"name",{value:n,configurable:!0})
|
|
|
45
45
|
AND v.node_id NOT IN (SELECT node_id FROM warm_pool)
|
|
46
46
|
AND v.kind != 'human'
|
|
47
47
|
AND (v.status IN ('active', 'idle') OR (v.status IN ('done', 'canceled', 'dead') AND (v.pi_pid IS NOT NULL OR v.frozen_at IS NOT NULL)))
|
|
48
|
-
ORDER BY v.created`;async function
|
|
49
|
-
WHERE ${
|
|
50
|
-
AND EXISTS (SELECT 1 FROM deliveries d WHERE d.destination_id = v.node_id AND ${
|
|
51
|
-
ORDER BY v.created`).all()).map(f)}i(
|
|
48
|
+
ORDER BY v.created`;async function ft(){return(await(await d()).prepare(en).all()).map(f)}i(ft,"listNodesForSupervision");const ee=i(e=>`(${e}.status = 'done' AND ${e}.intent = 'parked' AND ${e}.lifecycle = 'resident' AND ${e}.final_report IS NULL AND ${e}.deleting_at IS NULL)`,"PARKED_RESIDENT_SQL"),nn=i(e=>`(${e}.status IN ('active', 'idle') OR ${ee(e)} OR (${e}.status IN ('done', 'canceled', 'dead') AND ${e}.frozen_at IS NOT NULL AND ${e}.final_report IS NULL))`,"RESUMABLE_NODE_SQL");async function wt(e){return await(await d()).prepare(`SELECT node_id, cwd FROM nodes WHERE ${nn("nodes")} AND node_id != ?`).all(e)}i(wt,"resumableNodeCwds");async function Et(){return(await(await d()).prepare(`SELECT v.* FROM node_rows v
|
|
49
|
+
WHERE ${ee("v")}
|
|
50
|
+
AND EXISTS (SELECT 1 FROM deliveries d WHERE d.destination_id = v.node_id AND ${Oe("d")}) AND v.kind != 'human' AND v.node_id NOT IN (SELECT node_id FROM warm_pool)
|
|
51
|
+
ORDER BY v.created`).all()).map(f)}i(Et,"listParkedResidentsWithWakeMail");async function yt(e,n){await(await d()).prepare("INSERT INTO warm_pool (node_id, recipe_key, created) VALUES (?, ?, ?) ON CONFLICT (node_id) DO UPDATE SET recipe_key = excluded.recipe_key, created = excluded.created").run(e,n,new Date().toISOString())}i(yt,"registerWarmSpare");async function mt(e){return(await(await d()).prepare("DELETE FROM warm_pool WHERE node_id = ?").run(e)).changes>0}i(mt,"unregisterWarmSpare");async function k(e,n){const t=`SELECT w.node_id AS node_id, w.recipe_key AS recipe_key, w.created AS created,
|
|
52
52
|
n.status AS status, n.pi_pid AS pi_pid, n.pi_pid_identity AS pi_pid_identity
|
|
53
|
-
FROM warm_pool w JOIN node_rows n ON n.node_id = w.node_id`+(n===void 0?"":" WHERE w.recipe_key = ?")+" ORDER BY w.created";return(n===void 0?await e.prepareUncached(t).all():await e.prepareUncached(t).all(n)).map(o=>({node_id:o.node_id,recipe_key:o.recipe_key,created:o.created,status:o.status,pi_pid:o.pi_pid??null,pi_pid_identity:o.pi_pid_identity??null}))}i(k,"warmSpareRowsFor");async function
|
|
54
|
-
FROM node_rows WHERE ${m} ORDER BY created`).all()).map(e=>({node_id:e.node_id,name:e.name,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind??null,parent:e.parent??null,created:e.created,description:e.description??null}))}i(
|
|
53
|
+
FROM warm_pool w JOIN node_rows n ON n.node_id = w.node_id`+(n===void 0?"":" WHERE w.recipe_key = ?")+" ORDER BY w.created";return(n===void 0?await e.prepareUncached(t).all():await e.prepareUncached(t).all(n)).map(o=>({node_id:o.node_id,recipe_key:o.recipe_key,created:o.created,status:o.status,pi_pid:o.pi_pid??null,pi_pid_identity:o.pi_pid_identity??null}))}i(k,"warmSpareRowsFor");async function Nt(){return await k(await d())}i(Nt,"listWarmSpares");async function Rt(e){return await(await d()).prepare("SELECT 1 FROM warm_pool WHERE node_id = ?").get(e)!==void 0}i(Rt,"isWarmSpare");function ne(e){return e.status!=="active"&&e.status!=="idle"?!1:je(e.pi_pid,e.pi_pid_identity)==="alive"}i(ne,"spareIsClaimable");async function St(e,n,t={}){return await p(async a=>{const o=(await k(a,e)).find(ne);return o===void 0||t.requestKey!==void 0&&(await a.prepareUncached("UPDATE create_requests SET node_id = ?, state = 'warm_claimed' WHERE request_key = ? AND node_id IS NULL").run(o.node_id,t.requestKey)).changes===0||(await a.prepare("DELETE FROM warm_pool WHERE node_id = ?").run(o.node_id)).changes===0?null:(await a.prepare("UPDATE nodes SET created = ?, deadline_at = ? WHERE node_id = ?").run(n,t.deadlineAt??null,o.node_id),t.outcomeDelivery!==void 0&&await B(a,o.node_id,t.outcomeDelivery),o.node_id)})}i(St,"claimWarmSpare");async function ht(e){return(await k(await d(),e)).filter(ne).length}i(ht,"warmSpareCount");async function Ot(e){return(await(await d()).prepare("SELECT node_id FROM nodes WHERE parent = ? ORDER BY created").all(e)).map(n=>n.node_id)}i(Ot,"childrenOf");async function Tt(){return(await(await d()).prepareUncached(`SELECT node_id, name, kind, mode, lifecycle, status, cwd, host_kind, parent, created, description
|
|
54
|
+
FROM node_rows WHERE ${m} ORDER BY created`).all()).map(e=>({node_id:e.node_id,name:e.name,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind??null,parent:e.parent??null,created:e.created,description:e.description??null}))}i(Tt,"rosterNodes");async function Lt(e){return(await(await d()).prepareUncached(`SELECT * FROM node_rows
|
|
55
55
|
WHERE parent IS NULL AND kind != 'human'
|
|
56
56
|
AND status IN ('active','idle') AND cwd = ?
|
|
57
57
|
AND ${m}
|
|
58
|
-
ORDER BY created DESC`).all(e)).map(f)}i(
|
|
59
|
-
AND NOT EXISTS (SELECT 1 FROM sessions s WHERE s.node_id = n.node_id) LIMIT 1`);for(const{id:o,path:r,dir:s}of e)if(!(await t.get(o)!==void 0||await a.get(o)!==void 0)&&
|
|
58
|
+
ORDER BY created DESC`).all(e)).map(f)}i(Lt,"listResumableRoots");export*from"./tree.js";async function Dt(e,n,t){return await p(async a=>{const o=await a.prepare("SELECT status, final_report, frozen_at FROM nodes WHERE node_id = ? FOR UPDATE").get(e);return o===void 0?{kind:"missing"}:n(o)?{kind:"terminal",status:o.status,final_report:o.final_report}:{kind:"ran",result:await t()}})}i(Dt,"withFreshTerminalGuard");async function T(e){return await ve(e)}i(T,"hasUnreconciledManagedWorktree");async function te(e,n={}){return!["done","dead","canceled"].includes(e.status)||e.pi_pid!==null||e.frozen_at!==null||await T(e.node_id)||e.node_id===C()||q(e)?!1:n.pastTtl===!0||!["crashed","stranded",null].includes(e.terminal_reason??null)}i(te,"isCollectible");async function U(e){if(e.length===0)return[];const n=e.map(()=>"?").join(","),t=await(await d()).prepareUncached(`SELECT s.session_id, s.transcript_path, s.node_id, n.grantee FROM sessions s JOIN node_rows n ON n.node_id = s.node_id WHERE s.node_id IN (${n}) AND s.session_id IS NOT NULL AND s.transcript_path IS NOT NULL ORDER BY s.created_at, s.seq`).all(...e);return[...new Map(t.map(a=>[a.session_id,{id:a.session_id,path:a.transcript_path,dir:S(L(a.grantee).conversations,a.node_id)}])).values()]}i(U,"nodeConversationIds");async function x(e){const n=await d(),t=n.prepare("SELECT 1 FROM sessions WHERE session_id = ? LIMIT 1"),a=n.prepare(`SELECT 1 FROM nodes n WHERE n.fork_source_file LIKE '%\\_' || ? || '.jsonl' ESCAPE '\\'
|
|
59
|
+
AND NOT EXISTS (SELECT 1 FROM sessions s WHERE s.node_id = n.node_id) LIMIT 1`);for(const{id:o,path:r,dir:s}of e)if(!(await t.get(o)!==void 0||await a.get(o)!==void 0)&&ce(r,{throwIfNoEntry:!1})!==void 0){if(!tn(s,r)){console.error(`[canvas] not deleting transcript outside its node's conversations directory: ${r}`);continue}try{await Re().delete(o,r)}catch(c){if(!(c instanceof Se))throw c}}}i(x,"deleteNodeConversations");function tn(e,n){try{const t=Ee(H(e),S(H(M(n)),fe(n)));return t!==""&&t!==".."&&!t.startsWith(`..${me}`)&&!we(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}i(tn,"isBeneath");async function j(e,n){const t=await D(e,n);return t===null||t.deleted_at!==null?!1:(await Ye(e,t),!0)}i(j,"deleteNodeObject");async function W(e){return{nodeId:e,app:await O(e)===null?null:await Ce(e)}}i(W,"nodeFiles");async function ae({nodeId:e,app:n}){n!==null&&P(L(n).nodes,await Me(e,n)),P(M(J(e)),J(e))}i(ae,"removeNodeAppTrees");function ie({nodeId:e}){return[Fe(e)]}i(ie,"nodeOwnedDirs");function oe({nodeId:e,app:n}){if(n!==null)try{le(S(L(n).conversations,e))}catch(t){if(!["ENOENT","ENOTEMPTY"].includes(t.code??""))throw t}}i(oe,"removeNodeConversationDir");async function b(e){await ae(e);for(const n of ie(e))_e(n,{recursive:!0,force:!0});oe(e)}i(b,"removeNodeFiles");async function re(e){const n=await $(e);if(n.length>0)throw new Error(`the sandbox of node(s) ${n.join(", ")} could not be deleted; the node rows are kept`)}i(re,"requireSandboxesDeleted");async function gt(e){if(await T(e))return{deleted:!1};await re([e]);const n=await W(e),t=await U([e]),a=await p(async o=>(await j(o,e),{deleted:!0}));return await x(t),await b(n),a}i(gt,"deleteNode");async function vt(e){const n=[...new Set(e)];if(n.length===0)return[];const t=await y(n,T);if(t.length>0)throw new Error(`refusing to delete nodes with unreconciled managed worktrees: ${t.join(", ")}`);await re(n);const a=await h(n,W),o=await U(n),r=n.map(()=>"?").join(","),s=(await(await d()).prepareUncached(`SELECT node_id FROM nodes WHERE node_id IN (${r}) ORDER BY created`).all(...n)).map(({node_id:u})=>u),c=await y(s,async u=>await p(async _=>await j(_,u)));await x(o);for(const u of c){const _=a[n.indexOf(u)];await F(_,async()=>await b(_))}return c}i(vt,"deleteNodes");async function At(e){const n=e.dryRun??!1,t=e.includeStale??!1,a=Date.now()-e.ttlDays*864e5,o=new Date(a).toISOString(),r=C()??"",s=await d(),c=i(l=>de(l)<a,"quiet"),u=i(l=>({node_id:l.node_id,status:l.status,created:l.created}),"toPruned"),_=await an(),E=(await y((await s.prepare(`SELECT * FROM node_rows
|
|
60
60
|
WHERE status IN ('dead', 'done', 'canceled') AND created < ?
|
|
61
|
-
ORDER BY created`).all(o)).map(f),async l=>await
|
|
61
|
+
ORDER BY created`).all(o)).map(f),async l=>await te(l,{pastTtl:!0})&&c(l)&&!_.has(l.node_id)&&!await e.held(l.node_id))).map(u),N=t?(await y((await s.prepare(`SELECT * FROM node_rows
|
|
62
62
|
WHERE status IN ('active', 'idle') AND created < ?
|
|
63
|
-
ORDER BY created`).all(o)).map(f),async l=>l.node_id!==r&&!
|
|
63
|
+
ORDER BY created`).all(o)).map(f),async l=>l.node_id!==r&&!xe(l.pi_pid??null)&&(l.frozen_at??null)===null&&(l.respawn_not_before??null)===null&&l.intent!=="idle-release"&&!q(l)&&!await he(l.node_id)&&!await T(l.node_id)&&c(l)&&!await e.held(l.node_id))).map(u):[],R=await I([...E,...N]);return n||R.length===0?{pruned:R,dryRun:n}:{pruned:await se(R,e.removeDirs),dryRun:n}}i(At,"pruneNodes");async function an(){const e=await(await d()).prepare(`SELECT DISTINCT d.owner AS owner FROM watches w
|
|
64
64
|
JOIN objects d ON d.id = w.object AND d.type = 'document' AND d.deleted_at IS NULL
|
|
65
65
|
JOIN objects o ON o.id = w.watcher AND o.deleted_at IS NULL
|
|
66
66
|
LEFT JOIN nodes n ON n.node_id = w.watcher
|
|
67
|
-
WHERE w.watcher != d.owner AND d.owner IS NOT NULL AND (n.node_id IS NULL OR n.status IN ('active', 'idle'))`).all();return new Set(e.map(n=>n.owner))}i(
|
|
67
|
+
WHERE w.watcher != d.owner AND d.owner IS NOT NULL AND (n.node_id IS NULL OR n.status IN ('active', 'idle'))`).all();return new Set(e.map(n=>n.owner))}i(an,"ownersOfWatchedDocuments");async function I(e){const t=(await d()).prepare("SELECT node_id FROM nodes WHERE run_id = ? AND node_id != ?"),a=new Set(e.map(o=>o.node_id));return await y(e,async o=>(await t.all(o.node_id,o.node_id)).every(r=>a.has(r.node_id)))}i(I,"retainRunRootsWithMembers");async function se(e,n){const t=new Set(await $(e.map(s=>s.node_id))),a=t.size===0?e:await I(e.filter(s=>!t.has(s.node_id)));if(a.length===0)return[];const o=await h(a,async s=>await W(s.node_id)),r=await U(a.map(s=>s.node_id));for(const s of a)await p(async c=>await j(c,s.node_id));if(await x(r),n!==void 0){for(const s of o)await F(s,async()=>{await ae(s),oe(s)});return n(o.flatMap(ie)),a}for(const s of o)await F(s,async()=>await b(s));return a}i(se,"deletePrunedNodes");async function F(e,n){try{await n()}catch(t){Ne({level:"error",event:"canvas.node_files.remove_failed",error:t,fields:{node_id:e.nodeId}})}}i(F,"eachNodeBestEffort");function de(e){let n=0;for(const t of[e.created,e.launched_at,e.last_settled_at,e.finalized_at,e.outcome_at,e.last_activity_at]){if(t==null)continue;const a=Date.parse(t);Number.isFinite(a)&&a>n&&(n=a)}try{const t=pe(S(Ie(e.node_id),"telemetry.json"),{throwIfNoEntry:!1});t!==void 0&&t.mtimeMs>n&&(n=t.mtimeMs)}catch{}return n}i(de,"lastActivityMs");async function kt(e){const n=e.dryRun??!1,t=await Xe(),a=await y(t,async u=>await te(u)&&!await e.held(u.node_id)),o=t.length-a.length,r=Math.max(0,e.maxNodes-o),s=a.map(u=>({row:u,recency:de(u)})).sort((u,_)=>_.recency-u.recency).slice(r).map(({row:u})=>({node_id:u.node_id,status:u.status,created:u.created})),c=await I(s);return n||c.length===0?{pruned:c,dryRun:n}:{pruned:await se(c),dryRun:n}}i(kt,"pruneToLimit");export{ee as PARKED_RESIDENT_SQL,nn as RESUMABLE_NODE_SQL,qn as abandonCreateRequest,Wn as assertRunNotDeleting,ct as browseNodes,Bn as canonicalSessionFile,Ot as childrenOf,St as claimWarmSpare,tt as clearFinalReportIfMatches,st as clearFrozen,$n as completeCreateRequest,bn as createNode,gt as deleteNode,vt as deleteNodes,Qn as dueNodeDeadlines,Fn as findCreateRequest,zn as findNodeBySessionFile,nt as getFinalReport,O as getNode,In as getNodes,Jn as getRow,Yn as getRowByPane,_t as graphNodes,te as isCollectible,Rt as isWarmSpare,de as lastActivityMs,Xe as listNodes,ut as listNodesByProfile,ft as listNodesForSupervision,Et as listParkedResidentsWithWakeMail,Lt as listResumableRoots,pt as listTerminalPlacementResidue,Nt as listWarmSpares,W as nodeFiles,en as nodesForSupervisionSql,Hn as pruneExpiredCreateRequests,At as pruneNodes,kt as pruneToLimit,Mn as recordCreateRequestNode,it as recordLaunch,dt as recordRespawnAttempt,ot as recordSettledTurn,yt as registerWarmSpare,b as removeNodeFiles,Cn as reserveCreateRequest,Pn as reserveCreateRequestNode,wt as resumableNodeCwds,Tt as rosterNodes,rt as setFrozen,Zn as setIntent,Vn as setNodeDeadline,at as setPresence,Xn as setStatus,Kn as shiftProfileNodeDeadlines,Ze as terminalPlacementResidueSql,et as transitionStatusIntent,mt as unregisterWarmSpare,Gn as updateNode,lt as updateNodeTelemetry,ht as warmSpareCount,Dt as withFreshTerminalGuard};
|
|
@@ -1 +1,2 @@
|
|
|
1
|
-
var p=Object.defineProperty;var r=(
|
|
1
|
+
var p=Object.defineProperty;var r=(t,a)=>p(t,"name",{value:a,configurable:!0});import{withCanvasWrite as m,openDb as s}from"./db.js";const c=720*60*60*1e3;async function E(t,a){await m(async o=>{const n=o.prepare("INSERT INTO memory_reads (node_id, name, scope, at, type) VALUES (?, ?, ?, ?, ?)");for(const e of a)await n.run(t,e.name,e.scope,e.at,e.type)})}r(E,"insertMemoryReads");async function R(t,a,o){if(o.length===0)return;const n=r(e=>o.map(e),"col");await t.prepare(`INSERT INTO memory_reads (node_id, name, scope, at, type)
|
|
2
|
+
SELECT ?::text, v.name, v.scope, v.at, v.type FROM unnest(?::text[], ?::text[], ?::text[], ?::text[]) WITH ORDINALITY AS v(name, scope, at, type, n) ORDER BY v.n`).run(a,n(e=>e.name),n(e=>e.scope),n(e=>e.at),n(e=>e.type))}r(R,"recordMemoryReadsIn");async function d(t,a){return await(await s()).prepare("SELECT node_id, name, scope, at, type FROM memory_reads WHERE at >= ? AND at < ? ORDER BY at").all(t,a)}r(d,"listMemoryReads");async function u(t){return Number((await(await s()).prepare("DELETE FROM memory_reads WHERE at < ?").run(new Date(t-c).toISOString())).changes)}r(u,"pruneMemoryReads");async function w(){return(await(await s()).prepare("SELECT value FROM canvas_meta WHERE key = 'memory_reads.started_at'").get())?.value??null}r(w,"memoryReadsStartedAt");export{c as MEMORY_READS_RETENTION_MS,E as insertMemoryReads,d as listMemoryReads,w as memoryReadsStartedAt,u as pruneMemoryReads,R as recordMemoryReadsIn};
|
|
@@ -9,6 +9,8 @@ export interface ControllerWait {
|
|
|
9
9
|
}
|
|
10
10
|
/** Replace a node's live controller wait while retaining the prior row as history. */
|
|
11
11
|
export declare function armControllerWait(nodeId: string, controllerId: string, now?: number): Promise<ControllerWait>;
|
|
12
|
+
/** Live controller waits for many nodes in one statement; nodes without one are absent from the map. */
|
|
13
|
+
export declare function readControllerWaits(nodeIds: readonly string[]): Promise<Map<string, ControllerWait>>;
|
|
12
14
|
export declare function readControllerWait(nodeId: string): Promise<ControllerWait | null>;
|
|
13
15
|
/** Clear only the wait that was observed for this sender; a rearm wins a race. */
|
|
14
16
|
export declare function settleMatchingControllerWait(nodeId: string, senderId: string | null, now: number, db?: CanvasDb): Promise<boolean>;
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
var w=Object.defineProperty;var n=(t,e)=>w(t,"name",{value:e,configurable:!0});import{randomBytes as c}from"node:crypto";import{withCanvasWrite as
|
|
2
|
-
VALUES (?, ?, 'controller', ?, ?, ?, NULL)`).run(
|
|
1
|
+
var w=Object.defineProperty;var n=(t,e)=>w(t,"name",{value:e,configurable:!0});import{randomBytes as c}from"node:crypto";import{withCanvasWrite as l,openDb as o}from"./db.js";function s(t){if(t.kind!=="controller")throw new Error(`wait ${t.wait_id} is not a controller wait`);return{waitId:t.wait_id,nodeId:t.node_id,controllerId:t.target_id,generation:t.generation,createdAt:t.created_at,satisfiedAt:t.satisfied_at}}n(s,"waitFrom");function _(){let t;do t=c(16).toString("hex");while(t==="00000000000000000000000000000000");return t}n(_,"newWaitId");async function p(t,e,i=Date.now()){return await l(async a=>{await a.prepare("UPDATE waits SET satisfied_at = ? WHERE node_id = ? AND kind = 'controller' AND satisfied_at IS NULL").run(i,t);const r=Number((await a.prepare("SELECT COALESCE(MAX(generation), 0) AS generation FROM waits WHERE node_id = ? AND kind = 'controller'").get(t)).generation)+1,d={wait_id:_(),node_id:t,kind:"controller",target_id:e,generation:r,created_at:i,satisfied_at:null};return await a.prepare(`INSERT INTO waits (wait_id, node_id, kind, target_id, generation, created_at, satisfied_at)
|
|
2
|
+
VALUES (?, ?, 'controller', ?, ?, ?, NULL)`).run(d.wait_id,d.node_id,d.target_id,d.generation,d.created_at),s(d)})}n(p,"armControllerWait");async function E(t){const e=new Map;if(t.length===0)return e;const i=await(await o()).prepare("SELECT * FROM waits WHERE node_id = ANY(?::text[]) AND kind = 'controller' AND satisfied_at IS NULL").all([...t]);for(const a of i)e.set(a.node_id,s(a));return e}n(E,"readControllerWaits");async function L(t){return(await E([t])).get(t)??null}n(L,"readControllerWait");async function g(t,e,i,a){if(a??=await o(),e===null)return!1;const r=await a.prepare("SELECT wait_id, generation FROM waits WHERE node_id = ? AND kind = 'controller' AND target_id = ? AND satisfied_at IS NULL").get(t,e);return r===void 0?!1:Number((await a.prepare("UPDATE waits SET satisfied_at = ? WHERE wait_id = ? AND generation = ? AND satisfied_at IS NULL").run(i,r.wait_id,r.generation)).changes)===1}n(g,"settleMatchingControllerWait");async function A(t,e,i,a){a??=await o();const r=await a.prepare(`SELECT w.wait_id, w.generation, target.status AS controller_status
|
|
3
3
|
FROM waits w LEFT JOIN nodes target ON target.node_id = w.target_id
|
|
4
|
-
WHERE w.node_id = ? AND w.kind = 'controller' AND w.target_id = ? AND w.satisfied_at IS NULL`).get(t,e);return r===void 0||r.controller_status==="active"||r.controller_status==="idle"?!1:Number((await a.prepare("UPDATE waits SET satisfied_at = ? WHERE wait_id = ? AND generation = ? AND satisfied_at IS NULL").run(i,r.wait_id,r.generation)).changes)===1}n(
|
|
4
|
+
WHERE w.node_id = ? AND w.kind = 'controller' AND w.target_id = ? AND w.satisfied_at IS NULL`).get(t,e);return r===void 0||r.controller_status==="active"||r.controller_status==="idle"?!1:Number((await a.prepare("UPDATE waits SET satisfied_at = ? WHERE wait_id = ? AND generation = ? AND satisfied_at IS NULL").run(i,r.wait_id,r.generation)).changes)===1}n(A,"settleDeadControllerWait");async function D(){return(await(await o()).prepare("SELECT * FROM waits WHERE kind = 'controller' AND satisfied_at IS NULL").all()).map(s)}n(D,"liveControllerWaits");async function S(t,e,i,a=Date.now()){await t.prepare(`INSERT INTO waits (wait_id, node_id, kind, target_id, generation, created_at, satisfied_at)
|
|
5
5
|
SELECT ?, ?, 'object', ?, 1, ?, NULL
|
|
6
|
-
WHERE NOT EXISTS (SELECT 1 FROM waits WHERE node_id = ? AND kind = 'object' AND target_id = ? AND satisfied_at IS NULL)`).run(_(),e,i,a,e,i)}n(
|
|
6
|
+
WHERE NOT EXISTS (SELECT 1 FROM waits WHERE node_id = ? AND kind = 'object' AND target_id = ? AND satisfied_at IS NULL)`).run(_(),e,i,a,e,i)}n(S,"armObjectWait");async function T(t,e,i=null,a=Date.now()){return Number(i===null?(await t.prepare("UPDATE waits SET satisfied_at = ? WHERE kind = 'object' AND target_id = ? AND satisfied_at IS NULL").run(a,e)).changes:(await t.prepare("UPDATE waits SET satisfied_at = ? WHERE kind = 'object' AND target_id = ? AND node_id = ? AND satisfied_at IS NULL").run(a,e,i)).changes)}n(T,"settleObjectWaits");async function W(t,e,i=Date.now()){return Number((await t.prepare("UPDATE waits SET satisfied_at = ? WHERE kind = 'object' AND node_id = ? AND satisfied_at IS NULL").run(i,e)).changes)}n(W,"settleNodeObjectWaits");async function R(t){return t??=await o(),(await t.prepare(`SELECT w.wait_id, w.node_id, w.target_id, w.created_at, o.type AS object_type, o.name AS object_name
|
|
7
7
|
FROM waits w JOIN objects o ON o.id = w.target_id
|
|
8
8
|
WHERE w.kind = 'object' AND w.satisfied_at IS NULL AND o.deleted_at IS NULL
|
|
9
|
-
ORDER BY w.node_id, w.created_at, w.seq`).all()).map(e=>({waitId:e.wait_id,nodeId:e.node_id,objectId:e.target_id,createdAt:e.created_at,objectType:e.object_type,objectName:e.object_name}))}n(R,"liveObjectWaitsNamed");async function
|
|
9
|
+
ORDER BY w.node_id, w.created_at, w.seq`).all()).map(e=>({waitId:e.wait_id,nodeId:e.node_id,objectId:e.target_id,createdAt:e.created_at,objectType:e.object_type,objectName:e.object_name}))}n(R,"liveObjectWaitsNamed");async function I(t){return await(await o()).prepare("SELECT 1 FROM waits WHERE node_id = ? AND kind = 'object' AND satisfied_at IS NULL LIMIT 1").get(t)!==void 0}n(I,"hasLiveObjectWait");async function O(t){return await(await o()).prepare(`SELECT 1 FROM waits w JOIN nodes target ON target.node_id = w.target_id
|
|
10
10
|
WHERE w.node_id = ? AND w.kind = 'controller' AND w.satisfied_at IS NULL
|
|
11
|
-
AND target.status IN ('active', 'idle') LIMIT 1`).get(t)!==void 0}n(
|
|
11
|
+
AND target.status IN ('active', 'idle') LIMIT 1`).get(t)!==void 0}n(O,"hasLiveControllerWait");export{p as armControllerWait,S as armObjectWait,O as hasLiveControllerWait,I as hasLiveObjectWait,D as liveControllerWaits,R as liveObjectWaitsNamed,L as readControllerWait,E as readControllerWaits,A as settleDeadControllerWait,g as settleMatchingControllerWait,W as settleNodeObjectWaits,T as settleObjectWaits};
|
|
@@ -30,7 +30,7 @@ export interface EnqueuedNodeMail {
|
|
|
30
30
|
export declare function newId(): string;
|
|
31
31
|
/** A terminal-lifecycle destination's normal or deferred mail is raised to urgent. */
|
|
32
32
|
export declare function effectiveTier(nodeId: string, urgency: InboxTier): Promise<InboxTier>;
|
|
33
|
-
export
|
|
33
|
+
export interface MessageInsert {
|
|
34
34
|
messageId?: string;
|
|
35
35
|
operationId: OperationId;
|
|
36
36
|
createdAt: string;
|
|
@@ -49,7 +49,10 @@ export declare function insertMessage(db: CanvasDb, input: {
|
|
|
49
49
|
};
|
|
50
50
|
causeMessageId?: string | null;
|
|
51
51
|
depth?: number;
|
|
52
|
-
}
|
|
52
|
+
}
|
|
53
|
+
/** Insert messages in order: one sequence bump reserving a block of numbers, one multi-row insert. */
|
|
54
|
+
export declare function insertMessages(db: CanvasDb, inputs: readonly MessageInsert[]): Promise<string[]>;
|
|
55
|
+
export declare function insertMessage(db: CanvasDb, input: MessageInsert): Promise<string>;
|
|
53
56
|
/** The message's creation time, operation id and body — an oversized inline body is clipped
|
|
54
57
|
* into `destinationNodeId`'s messages dir and referenced; with no destination it stays inline. */
|
|
55
58
|
export declare function finalizeNodeMail(input: Omit<NodeMailInput, 'wake'>, destinationNodeId: string | null): {
|