@north-light/cli 0.3.696 → 0.3.697

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.
@@ -1,6 +1,6 @@
1
- var $=Object.defineProperty;var i=(e,t)=>$(e,"name",{value:t,configurable:!0});import{envNodeId as j}from"../../shared/env.js";import{defineBranch as q,defineLeaf as h}from"../../core/command.js";import{InputError as r}from"../../core/io.js";import{ExitCode as T}from"../../types.js";import{existsSync as R,mkdirSync as D,rmSync as E,writeFileSync as w}from"node:fs";import{backgroundRunningBashJobs as I,bashJobCommandLine as N,bashJobPaths as y,formatBashElapsed as k,isSafeBashJobId as g,jobStartedAtMs as B,newBashJobId as M,tailJobLog as L}from"../../core/bash-jobs.js";import{parseDurationMs as S}from"../../core/wake.js";import{cliClient as u,getNodeOrNull as c}from"../api-client.js";import{ApiError as x}from"../../api/index.js";import{PREVIEW_RESULT_PATH_ENV as U}from"../../core/preview-result-path.js";import{contextDir as C}from"../../core/canvas/paths.js";import{nodeInPane as A}from"../surface/node/placement.js";function b(e,t){const n=e.pane??process.env.TMUX_PANE;let o=e.node;if((o===void 0||o==="")&&(o=A(n)),(o===void 0||o==="")&&(o=j()),o===void 0||o==="")throw new r({error:"no_node",message:t,next:"Run from inside a node, pass --node <id>, or --pane <pane>."});return{id:o,pane:n}}i(b,"resolveBashTarget");async function _(e,t,n){try{await u().patchBashJob(e,t,n)}catch(o){throw o instanceof x&&(o.status===404||o.status===409)?new r({error:"not_running",message:`background job ${t} for ${e} is not running`,next:"List live jobs with `crtr node bash list`."}):o}}i(_,"patchRunningJob");const J=h({name:"run",description:"start a shell command as a background job and return at once",whenToUse:"a command needs longer than one tool call \u2014 a test lane, a build, a soak \u2014 and you should be woken with its exit code instead of waiting, backgrounding with `&`, or polling a log",tier:"normal",help:{name:"node bash run",summary:"start one shell command as a background job owned by the calling node and return before it finishes",params:[{kind:"positional",name:"command",required:!0,constraint:"The shell command, run by bash from the current directory with this process\u2019s environment. The same refusals apply as for a bash tool call, judged on this command."},{kind:"flag",name:"quiet-ok",type:"bool",required:!1,constraint:"Pass for a job that legitimately sits idle \u2014 `gh run watch`, `sleep`, waiting on a lock, a `docker build` whose work runs outside the process tree \u2014 so it gets no silence messages. Omit it for anything that should be making progress."}],output:[{name:"job_id",type:"string",required:!0,constraint:"The job object\u2019s id; read or watch it with `crtr canvas`, stop it with `node bash kill`."},{name:"log_path",type:"string",required:!0,constraint:"File receiving the command\u2019s combined stdout and stderr, capped at 10 MiB."}],outputKind:"object",effects:["Works only inside a node\u2019s bash tool call; the job belongs to the calling node.","Starts the command detached from this call, so it keeps running after the call and the turn end. A `timeout` around this leaf bounds only the launch, not the job.","Records the job as a canvas object; when the command exits, its watchers (the calling node by default) get an urgent `exited` push with the exit code and log path.","Sets no cancel deadline: the job runs to completion unless stopped with `node bash kill`.","A job whose processes use almost no CPU and write to no open file for 15 minutes messages the calling node about it, again at 30 and 60 minutes, then hourly; activity restarts the schedule and nothing is stopped. `--quiet-ok` turns these messages off.","Fails, with the job id and log path, if the job could not be recorded; the command is then running but will not message the node when it exits."]},run:i(async e=>{const t=e.command,n=j(),o=process.env.CRTR_CONTEXT_DIR;if(n===void 0||n===""||o===void 0||o==="")throw new r({error:"no_node",message:"`node bash run` starts a job for the calling node and works only inside a node\u2019s bash tool",next:"Run it from a node\u2019s bash tool call."});const s=process.cwd(),{bashCommandRefusal:d}=await import("../../core/bash-guard.js"),l=d(t,s);if(l!==null)throw new r({error:"refused",message:l,next:"Run a different command."});const a=y(o,M());D(a.dir,{recursive:!0}),w(a.cmdSh,t),w(a.jobLog,""),w(a.jobBg,"");const{launchBashJobSupervisor:m}=await import("../../core/runtime/broker/bash-job-launch.js"),{[U]:p,...v}=process.env;try{await m(n,a,o,s,v)}catch(f){throw E(a.dir,{recursive:!0,force:!0}),f}try{await u().recordBackgroundedJob(n,a.jobId,{command:t}),e.quietOk===!0&&await u().patchBashJob(n,a.jobId,{quiet_ok:!0})}catch(f){throw new r({error:"job_not_recorded",message:`job ${a.jobId} is running but could not be recorded (${f.message}); it will NOT message you when it exits. Log: ${a.jobLog}`,next:`Watch it with \`tail -f ${a.jobLog}\`, or stop it with \`crtr node bash kill ${a.jobId}\`.`},T.GENERAL)}return{job_id:a.jobId,log_path:a.jobLog}},"run"),render:i(e=>`[backgrounded as job ${e.job_id}. It will interrupt you with a message when it exits. Watch: tail -f ${e.log_path} ; stop: crtr node bash kill ${e.job_id}]`,"render")}),P=h({name:"background",description:"hand the focused node\u2019s running bash command to its background job system",whenToUse:"the tmux prefix menu invokes this when a foreground bash command should stop blocking the agent immediately but keep running as a file-backed background job",tier:"hidden",help:{name:"node bash background",summary:"hand every running foreground bash command for one node to its file-backed background job system",params:[{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node whose running bash command to background. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE. The prefix menu passes this for you."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The target node."},{name:"jobs",type:"object[]",required:!0,constraint:"Per handed-off job {job_id, elapsed_ms} \u2014 the foreground elapsed time in milliseconds at the moment of handoff."}],outputKind:"object",effects:["Signals every foreground bash command currently running for the node to return from its tool call immediately while its detached supervisor keeps the command running.","Each handed-off command retains its log under the node context jobs directory and becomes a job object; when it exits, the job\u2019s watchers (its node by default) get an urgent `exited` push carrying the exit code and log path."]},run:i(async e=>{const{id:t}=b(e,"no node found for the bash handoff"),n=await c(t);if(n===null)throw new r({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=I(n.paths.context_dir),s=Date.now(),d=o.map(l=>({job_id:l.jobId,elapsed_ms:s-(B(l.jobId)??s)}));return{node_id:t,jobs:d}},"run"),render:i(e=>{const t=e.jobs;if(t.length===0)return`No foreground bash command is running for ${e.node_id}.`;const n=Math.max(...t.map(o=>o.elapsed_ms));return`Handed ${t.length} bash command(s) to the background job system for ${e.node_id} \xB7 ran ${k(n)} in the foreground.`},"render")}),O=h({name:"list",description:"list a node\u2019s live background bash jobs",whenToUse:"you need the ids, commands, and ages of your jobs that are still running",help:{name:"node bash list",summary:"read every still-running background bash job owned by one node",params:[{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node whose background jobs to list. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE."},{kind:"flag",name:"tail",type:"int",required:!1,default:0,constraint:"Include this many trailing log lines per job (0 = none). Read from the local log file, so it is available only on the machine that runs the job; elsewhere log_tail is null \u2014 use `node bash log` there."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The target node."},{name:"jobs",type:"object[]",required:!0,constraint:"Oldest-first {job_id, command, purpose, started_at, elapsed_ms, deadline_at, output_key, log_path, pgid, log_tail} for every live background job; log_path and log_tail are null when the job\u2019s log is not on this machine (a job running in a sandbox, listed from outside it), and no tail is available from here (`node bash log` reads its stored output); purpose is a human-readable label or null; deadline_at is the auto-cancel time or null for a job that runs to completion."}],outputKind:"object",effects:["Reads the node\u2019s running job rows and, for log_tail, the local log files. Changes nothing."]},run:i(async e=>{const{id:t}=b(e,"no node found for the bash job list"),n=await c(t);if(n===null)throw new r({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=Date.now(),s=Math.max(0,Math.trunc(Number(e.tail??0))),d=[n.paths.context_dir,C(n.node_id,n.grantee)],l=(await u().listBashJobs(n.node_id)).map(a=>{const m=d.map(p=>y(p,a.job_id).jobLog).find(p=>R(p))??null;return{job_id:a.job_id,command:a.command,purpose:a.purpose,started_at:a.started_at,elapsed_ms:a.elapsed_ms,deadline_at:a.deadline_at,output_key:a.output_key,log_path:m,pgid:a.pgid,log_tail:m===null?null:L(m,s)}});return{node_id:n.node_id,jobs:l}},"run"),render:i(e=>{const t=e.jobs;return t.length===0?`No background bash jobs for ${e.node_id}.`:t.map(n=>`${n.job_id} \xB7 ${k(n.elapsed_ms)} \xB7 ${N(n.command)}${n.purpose===null?"":`
1
+ var q=Object.defineProperty;var i=(e,t)=>q(e,"name",{value:t,configurable:!0});import{envNodeId as j}from"../../shared/env.js";import{defineBranch as T,defineLeaf as h}from"../../core/command.js";import{InputError as r}from"../../core/io.js";import{ExitCode as R}from"../../types.js";import{existsSync as D,mkdirSync as E,rmSync as I,writeFileSync as w}from"node:fs";import{backgroundRunningBashJobs as N,bashJobCommandLine as B,bashJobPaths as y,formatBashElapsed as k,isSafeBashJobId as g,jobStartedAtMs as M,newBashJobId as L,tailJobLog as S}from"../../core/bash-jobs.js";import{parseDurationMs as U}from"../../core/wake.js";import{cliClient as u,getNodeOrNull as c}from"../api-client.js";import{ApiError as x}from"../../api/index.js";import{PREVIEW_RESULT_PATH_ENV as C}from"../../core/preview-result-path.js";import{contextDir as v}from"../../core/canvas/paths.js";import{nodeInPane as A}from"../surface/node/placement.js";function b(e,t){const n=e.pane??process.env.TMUX_PANE;let o=e.node;if((o===void 0||o==="")&&(o=A(n)),(o===void 0||o==="")&&(o=j()),o===void 0||o==="")throw new r({error:"no_node",message:t,next:"Run from inside a node, pass --node <id>, or --pane <pane>."});return{id:o,pane:n}}i(b,"resolveBashTarget");async function _(e,t,n){try{await u().patchBashJob(e,t,n)}catch(o){throw o instanceof x&&(o.status===404||o.status===409)?new r({error:"not_running",message:`background job ${t} for ${e} is not running`,next:"List live jobs with `crtr node bash list`."}):o}}i(_,"patchRunningJob");const J=h({name:"run",description:"start a shell command as a background job and return at once",whenToUse:"a command needs longer than one tool call \u2014 a test lane, a build, a soak \u2014 and you should be woken with its exit code instead of waiting, backgrounding with `&`, or polling a log",tier:"normal",help:{name:"node bash run",summary:"start one shell command as a background job owned by the calling node and return before it finishes",params:[{kind:"positional",name:"command",required:!0,constraint:"The shell command, run by bash from the current directory with this process\u2019s environment. The same refusals apply as for a bash tool call, judged on this command."},{kind:"flag",name:"quiet-ok",type:"bool",required:!1,constraint:"Pass for a job that legitimately sits idle \u2014 `gh run watch`, `sleep`, waiting on a lock, a `docker build` whose work runs outside the process tree \u2014 so it gets no silence messages. Omit it for anything that should be making progress."}],output:[{name:"job_id",type:"string",required:!0,constraint:"The job object\u2019s id; read or watch it with `crtr canvas`, stop it with `node bash kill`."},{name:"log_path",type:"string",required:!0,constraint:"File receiving the command\u2019s combined stdout and stderr, capped at 10 MiB."}],outputKind:"object",effects:["Works only inside a node\u2019s bash tool call; the job belongs to the calling node.","Starts the command detached from this call, so it keeps running after the call and the turn end. A `timeout` around this leaf bounds only the launch, not the job.","Records the job as a canvas object; when the command exits, its watchers (the calling node by default) get an urgent `exited` push with the exit code and log path.","Sets no cancel deadline: the job runs to completion unless stopped with `node bash kill`.","A job whose processes use almost no CPU and write to no open file for 15 minutes messages the calling node about it, again at 30 and 60 minutes, then hourly; activity restarts the schedule and nothing is stopped. `--quiet-ok` turns these messages off.","Fails, with the job id and log path, if the job could not be recorded; the command is then running but will not message the node when it exits."]},run:i(async e=>{const t=e.command,n=j(),o=process.env.CRTR_CONTEXT_DIR;if(n===void 0||n===""||o===void 0||o==="")throw new r({error:"no_node",message:"`node bash run` starts a job for the calling node and works only inside a node\u2019s bash tool",next:"Run it from a node\u2019s bash tool call."});const s=process.cwd(),{bashCommandRefusal:d}=await import("../../core/bash-guard.js"),l=d(t,s);if(l!==null)throw new r({error:"refused",message:l,next:"Run a different command."});const a=y(o,L());E(a.dir,{recursive:!0}),w(a.cmdSh,t),w(a.jobLog,""),w(a.jobBg,"");const{launchBashJobSupervisor:m}=await import("../../core/runtime/broker/bash-job-launch.js"),{[C]:p,...$}=process.env;try{await m(n,a,o,s,$)}catch(f){throw I(a.dir,{recursive:!0,force:!0}),f}try{await u().recordBackgroundedJob(n,a.jobId,{command:t}),e.quietOk===!0&&await u().patchBashJob(n,a.jobId,{quiet_ok:!0})}catch(f){throw new r({error:"job_not_recorded",message:`job ${a.jobId} is running but could not be recorded (${f.message}); it will NOT message you when it exits. Log: ${a.jobLog}`,next:`Watch it with \`tail -f ${a.jobLog}\`, or stop it with \`crtr node bash kill ${a.jobId}\`.`},R.GENERAL)}return{job_id:a.jobId,log_path:a.jobLog}},"run"),render:i(e=>`[backgrounded as job ${e.job_id}. It will interrupt you with a message when it exits. Watch: tail -f ${e.log_path} ; stop: crtr node bash kill ${e.job_id}]`,"render")}),P=h({name:"background",description:"hand the focused node\u2019s running bash command to its background job system",whenToUse:"the tmux prefix menu invokes this when a foreground bash command should stop blocking the agent immediately but keep running as a file-backed background job",tier:"hidden",help:{name:"node bash background",summary:"hand every running foreground bash command for one node to its file-backed background job system",params:[{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node whose running bash command to background. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE. The prefix menu passes this for you."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The target node."},{name:"jobs",type:"object[]",required:!0,constraint:"Per handed-off job {job_id, elapsed_ms} \u2014 the foreground elapsed time in milliseconds at the moment of handoff."}],outputKind:"object",effects:["Signals every foreground bash command currently running for the node to return from its tool call immediately while its detached supervisor keeps the command running.","Each handed-off command retains its log under the node context jobs directory and becomes a job object; when it exits, the job\u2019s watchers (its node by default) get an urgent `exited` push carrying the exit code and log path."]},run:i(async e=>{const{id:t}=b(e,"no node found for the bash handoff"),n=await c(t);if(n===null)throw new r({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=N(v(n.node_id,n.grantee)),s=Date.now(),d=o.map(l=>({job_id:l.jobId,elapsed_ms:s-(M(l.jobId)??s)}));return{node_id:t,jobs:d}},"run"),render:i(e=>{const t=e.jobs;if(t.length===0)return`No foreground bash command is running for ${e.node_id}.`;const n=Math.max(...t.map(o=>o.elapsed_ms));return`Handed ${t.length} bash command(s) to the background job system for ${e.node_id} \xB7 ran ${k(n)} in the foreground.`},"render")}),O=h({name:"list",description:"list a node\u2019s live background bash jobs",whenToUse:"you need the ids, commands, and ages of your jobs that are still running",help:{name:"node bash list",summary:"read every still-running background bash job owned by one node",params:[{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node whose background jobs to list. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE."},{kind:"flag",name:"tail",type:"int",required:!1,default:0,constraint:"Include this many trailing log lines per job (0 = none). Read from the local log file, so it is available only on the machine that runs the job; elsewhere log_tail is null \u2014 use `node bash log` there."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The target node."},{name:"jobs",type:"object[]",required:!0,constraint:"Oldest-first {job_id, command, purpose, started_at, elapsed_ms, deadline_at, output_key, log_path, pgid, log_tail} for every live background job; log_path and log_tail are null when the job\u2019s log is not on this machine (a job running in a sandbox, listed from outside it), and no tail is available from here (`node bash log` reads its stored output); purpose is a human-readable label or null; deadline_at is the auto-cancel time or null for a job that runs to completion."}],outputKind:"object",effects:["Reads the node\u2019s running job rows and, for log_tail, the local log files. Changes nothing."]},run:i(async e=>{const{id:t}=b(e,"no node found for the bash job list"),n=await c(t);if(n===null)throw new r({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=Date.now(),s=Math.max(0,Math.trunc(Number(e.tail??0))),d=[n.paths.context_dir,v(n.node_id,n.grantee)],l=(await u().listBashJobs(n.node_id)).map(a=>{const m=d.map(p=>y(p,a.job_id).jobLog).find(p=>D(p))??null;return{job_id:a.job_id,command:a.command,purpose:a.purpose,started_at:a.started_at,elapsed_ms:a.elapsed_ms,deadline_at:a.deadline_at,output_key:a.output_key,log_path:m,pgid:a.pgid,log_tail:m===null?null:S(m,s)}});return{node_id:n.node_id,jobs:l}},"run"),render:i(e=>{const t=e.jobs;return t.length===0?`No background bash jobs for ${e.node_id}.`:t.map(n=>`${n.job_id} \xB7 ${k(n.elapsed_ms)} \xB7 ${B(n.command)}${n.purpose===null?"":`
2
2
  purpose: ${n.purpose}`}${n.deadline_at===null?"":`
3
3
  cancels at: ${n.deadline_at}`}
4
4
  ${n.log_path===null?`log: not on this machine (its job files are not under this machine\u2019s crtr home \u2014 a sandbox or another computer); read its output with \`crtr node bash log ${n.job_id} --node ${e.node_id}\``:`log: ${n.log_path}`}`).join(`
5
5
  `)},"render")}),K=h({name:"log",description:"read a background bash job\u2019s output from the blob store, from any machine",whenToUse:"a job has exited or been killed, or its sandbox is gone, and you need what it printed \u2014 the wake and the job object name this command; for a job still running on this machine, `tail -f` on its log file shows more recent output",help:{name:"node bash log",summary:"read the stored output of one background bash job, last lines first bounded",params:[{kind:"positional",name:"job",required:!0,constraint:"Job id, as named by the exit wake, `node bash list` or `node bash run`. Running and finished jobs both work."},{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node owning the job. Defaults to the node in --pane, else the caller (CRTR_NODE_ID). A job another node started needs its owner here."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE."},{kind:"flag",name:"tail",type:"int",required:!1,constraint:"Return only this many trailing lines. Without it you get the last 256 KiB of output; either way at most 4 MiB."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The owning node."},{name:"job_id",type:"string",required:!0,constraint:"The job."},{name:"output",type:"string",required:!0,constraint:"The stored output, empty when the job has written nothing yet. The broker uploads a running job\u2019s output every couple of seconds, so it can trail the live log slightly."},{name:"truncated",type:"boolean",required:!0,constraint:"True when earlier output exists that the bound left out."}],outputKind:"object",effects:["Reads the output chunks the job\u2019s broker uploaded to the blob store through the daemon; never the local log file, so it works from any machine and after the job\u2019s sandbox is deleted. Needs read access to the owning node. Changes nothing."]},run:i(async e=>{const{id:t}=b(e,"no node found for the bash job"),n=await c(t);if(n===null)throw new r({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=e.job;if(!g(o))throw new r({error:"invalid_job_id",message:`invalid background job id: ${o}`,next:"Use a job id named by the exit wake or `crtr node bash list`."});const s=e.tail===void 0?void 0:Math.trunc(Number(e.tail));if(s!==void 0&&!(s>=1))throw new r({error:"invalid_args",message:"--tail must be a positive number of lines",next:"Pass --tail 50, or omit it for the last 256 KiB."});try{const d=await u().readBashJobOutput(n.node_id,o,s===void 0?{}:{tail_lines:s});return{node_id:n.node_id,job_id:d.job_id,output:d.output,truncated:d.truncated}}catch(d){throw d instanceof x&&d.code==="job_not_found"?new r({error:"job_not_found",message:`no job ${o} owned by ${n.node_id}`,next:"A job another node started needs its owner: pass --node <owner>."}):d}},"run"),render:i(e=>`${e.truncated===!0?`[earlier output omitted]
6
- `:""}${String(e.output)}`,"render")}),X=h({name:"kill",description:"stop one of a node\u2019s background bash jobs",whenToUse:"a job you started is no longer wanted or is stuck, and it should stop now",help:{name:"node bash kill",summary:"best-effort stop a background bash job and tell the owning node it was canceled",params:[{kind:"positional",name:"job",required:!0,constraint:"Job id, as reported by node bash list."},{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node owning the job. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The owning node."},{name:"signaled",type:"boolean",required:!0,constraint:"True when at least one observed supervisor-tree process received SIGTERM. For a job running on another machine it is true without any signal having been sent yet."},{name:"stop_pending_on_machine",type:"boolean",required:!0,constraint:"True when the job\u2019s process runs on another machine (an imported Mac or a sandbox): its broker there stops the whole process tree on its next report, within a few seconds, so nothing is confirmed stopped yet."},{name:"stop_queue_error",type:"string",required:!1,constraint:"The error when the job ended here but the stop for its machine could not be queued, so the process may still be running there; null otherwise."}],outputKind:"object",effects:["Snapshots the supervisor\u2019s observable process tree, sends SIGTERM then SIGKILL to those processes and to the supervisor\u2019s process group, and cannot stop a descendant that detached into its own session and reparented before the snapshot. A job running on another machine (an imported Mac, a sandbox) is stopped there by its broker within a few seconds of the row ending.","Records the job\u2019s exit so it stops showing as live, and ends its job object as killed; the job\u2019s watchers (its node by default) get an urgent `killed` push."]},run:i(async e=>{const{id:t}=b(e,"no node found for the bash job"),n=await c(t);if(n===null)throw new r({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=e.job;if(!g(o))throw new r({error:"invalid_job_id",message:`invalid background job id: ${o}`,next:"Use a job id reported by `crtr node bash list`."});const s=await u().stopBashJob(n.node_id,o);return{node_id:n.node_id,signaled:s.signaled,stop_pending_on_machine:s.stop_pending_on_machine===!0,...s.stop_queue_error===void 0?{}:{stop_queue_error:s.stop_queue_error}}},"run"),render:i(e=>typeof e.stop_queue_error=="string"?`Ended the background bash job for ${e.node_id}, but the stop could not be queued for its machine (${e.stop_queue_error}); the process may still be running there. Check with \`ps\` on that machine.`:e.stop_pending_on_machine===!0?`Ended a background bash job for ${e.node_id}. Its process runs on another machine (an imported Mac or a sandbox); that machine's broker stops the whole process tree on its next report, within a few seconds. Confirm with \`ps\` there if it matters.`:`Canceled a background bash job for ${e.node_id}${e.signaled===!0?"":" (no observed job process was still running)"}.`,"render")}),W=h({name:"quiet",description:"mark a running background bash job as an expected wait so it sends no silence messages",whenToUse:"a silence message arrived for a job that is meant to sit idle",help:{name:"node bash quiet",summary:"stop silence messages for one of a node\u2019s live background bash jobs",params:[{kind:"positional",name:"job",required:!0,constraint:"Job id, as reported by node bash list or the silence message."},{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node owning the job. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The owning node."}],outputKind:"object",effects:["Marks the job\u2019s row; the daemon sends no further silence messages for it. Signals nothing."]},run:i(async e=>{const{id:t}=b(e,"no node found for the bash job"),n=await c(t);if(n===null)throw new r({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=e.job;if(!g(o))throw new r({error:"invalid_job_id",message:`invalid background job id: ${o}`,next:"Use a job id reported by `crtr node bash list`."});return await _(n.node_id,o,{quiet_ok:!0}),{node_id:n.node_id}},"run"),render:i(e=>`Background job for ${e.node_id} will send no more silence messages.`,"render")}),F=h({name:"extend",description:"claim an auto-backgrounded bash job so the daemon does not cancel it at its deadline",whenToUse:"a command that was moved to a job automatically is worth keeping past its cancel deadline \u2014 give it more time with --for, or let it run to completion with --keep",help:{name:"node bash extend",summary:"move or clear the auto-cancel deadline on one of a node\u2019s live background bash jobs",params:[{kind:"positional",name:"job",required:!0,constraint:"Job id, as reported by node bash list or the auto-background notice."},{kind:"flag",name:"for",type:"string",required:!1,constraint:"New window from now before the job is canceled, as a duration (e.g. 90s, 10m, 1h30m). Mutually exclusive with --keep; give exactly one."},{kind:"flag",name:"keep",type:"bool",required:!1,constraint:"Remove the deadline entirely so the job runs to completion. Mutually exclusive with --for; give exactly one."},{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node owning the job. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The owning node."},{name:"deadline_at",type:"string",required:!1,constraint:"The job\u2019s new auto-cancel time (ISO), or absent when --keep cleared the deadline so the job runs to completion."}],outputKind:"object",effects:["Rewrites or clears the deadline on the job\u2019s row. The daemon\u2019s deadline lane reads it on its next scan. Signals nothing."]},run:i(async e=>{const{id:t}=b(e,"no node found for the bash job"),n=await c(t);if(n===null)throw new r({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=e.job;if(!g(o))throw new r({error:"invalid_job_id",message:`invalid background job id: ${o}`,next:"Use a job id reported by `crtr node bash list`."});const s=e.for,d=e.keep===!0;if(d===(s!==void 0&&s!==""))throw new r({error:"invalid_args",message:"give exactly one of --for <duration> or --keep",next:"Extend by a window with --for 10m, or drop the deadline with --keep."});if(d)return await _(n.node_id,o,{keep:!0}),{node_id:n.node_id};const l=S(s);if(l===null||l<=0)throw new r({error:"invalid_duration",message:`not a duration: ${s}`,next:"Use a value like 90s, 10m, or 1h30m."});const a=Date.now()+l;return await _(n.node_id,o,{deadline_at_ms:a}),{node_id:n.node_id,deadline_at:new Date(a).toISOString()}},"run"),render:i(e=>e.deadline_at===void 0?`Cleared the deadline \u2014 the background job will run to completion for ${e.node_id}.`:`Background job for ${e.node_id} will be canceled at ${e.deadline_at} unless extended again.`,"render")}),re=q({name:"bash",description:"start, list, read, stop, and extend your background bash jobs",whenToUse:"a command needs longer than one tool call \u2014 start it as a job and be woken with its exit code instead of using `&`, `nohup`, or a cron that polls a log \u2014 or you need to list, read the output of, stop, or extend the deadline of a job you already have",help:{name:"node bash",summary:"start, list, read, stop, and extend background bash jobs owned by a node",model:"Every bash call runs under a detached supervisor with its output in a log file, so a command that outlives its call keeps running as a job: a canvas object its node owns, readable and watchable with `crtr canvas`. `run` starts a job on purpose and it is never auto-canceled. A job that shows no activity for 15 minutes messages its node, and is never stopped for it. A foreground command still running after 5 minutes is moved to a job automatically, with a cancel deadline unless `extend` claims it."},children:[J,P,O,K,X,W,F]});export{re as nodeBash};
6
+ `:""}${String(e.output)}`,"render")}),X=h({name:"kill",description:"stop one of a node\u2019s background bash jobs",whenToUse:"a job you started is no longer wanted or is stuck, and it should stop now",help:{name:"node bash kill",summary:"best-effort stop a background bash job and tell the owning node it was canceled",params:[{kind:"positional",name:"job",required:!0,constraint:"Job id, as reported by node bash list."},{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node owning the job. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The owning node."},{name:"signaled",type:"boolean",required:!0,constraint:"True when at least one observed supervisor-tree process received SIGTERM. For a job running on another machine it is true without any signal having been sent yet."},{name:"stop_pending_on_machine",type:"boolean",required:!0,constraint:"True when the job\u2019s process runs on another machine (an imported Mac or a sandbox): its broker there stops the whole process tree on its next report, within a few seconds, so nothing is confirmed stopped yet."},{name:"stop_queue_error",type:"string",required:!1,constraint:"The error when the job ended here but the stop for its machine could not be queued, so the process may still be running there; null otherwise."}],outputKind:"object",effects:["Snapshots the supervisor\u2019s observable process tree, sends SIGTERM then SIGKILL to those processes and to the supervisor\u2019s process group, and cannot stop a descendant that detached into its own session and reparented before the snapshot. A job running on another machine (an imported Mac, a sandbox) is stopped there by its broker within a few seconds of the row ending.","Records the job\u2019s exit so it stops showing as live, and ends its job object as killed; the job\u2019s watchers (its node by default) get an urgent `killed` push."]},run:i(async e=>{const{id:t}=b(e,"no node found for the bash job"),n=await c(t);if(n===null)throw new r({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=e.job;if(!g(o))throw new r({error:"invalid_job_id",message:`invalid background job id: ${o}`,next:"Use a job id reported by `crtr node bash list`."});const s=await u().stopBashJob(n.node_id,o);return{node_id:n.node_id,signaled:s.signaled,stop_pending_on_machine:s.stop_pending_on_machine===!0,...s.stop_queue_error===void 0?{}:{stop_queue_error:s.stop_queue_error}}},"run"),render:i(e=>typeof e.stop_queue_error=="string"?`Ended the background bash job for ${e.node_id}, but the stop could not be queued for its machine (${e.stop_queue_error}); the process may still be running there. Check with \`ps\` on that machine.`:e.stop_pending_on_machine===!0?`Ended a background bash job for ${e.node_id}. Its process runs on another machine (an imported Mac or a sandbox); that machine's broker stops the whole process tree on its next report, within a few seconds. Confirm with \`ps\` there if it matters.`:`Canceled a background bash job for ${e.node_id}${e.signaled===!0?"":" (no observed job process was still running)"}.`,"render")}),W=h({name:"quiet",description:"mark a running background bash job as an expected wait so it sends no silence messages",whenToUse:"a silence message arrived for a job that is meant to sit idle",help:{name:"node bash quiet",summary:"stop silence messages for one of a node\u2019s live background bash jobs",params:[{kind:"positional",name:"job",required:!0,constraint:"Job id, as reported by node bash list or the silence message."},{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node owning the job. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The owning node."}],outputKind:"object",effects:["Marks the job\u2019s row; the daemon sends no further silence messages for it. Signals nothing."]},run:i(async e=>{const{id:t}=b(e,"no node found for the bash job"),n=await c(t);if(n===null)throw new r({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=e.job;if(!g(o))throw new r({error:"invalid_job_id",message:`invalid background job id: ${o}`,next:"Use a job id reported by `crtr node bash list`."});return await _(n.node_id,o,{quiet_ok:!0}),{node_id:n.node_id}},"run"),render:i(e=>`Background job for ${e.node_id} will send no more silence messages.`,"render")}),F=h({name:"extend",description:"claim an auto-backgrounded bash job so the daemon does not cancel it at its deadline",whenToUse:"a command that was moved to a job automatically is worth keeping past its cancel deadline \u2014 give it more time with --for, or let it run to completion with --keep",help:{name:"node bash extend",summary:"move or clear the auto-cancel deadline on one of a node\u2019s live background bash jobs",params:[{kind:"positional",name:"job",required:!0,constraint:"Job id, as reported by node bash list or the auto-background notice."},{kind:"flag",name:"for",type:"string",required:!1,constraint:"New window from now before the job is canceled, as a duration (e.g. 90s, 10m, 1h30m). Mutually exclusive with --keep; give exactly one."},{kind:"flag",name:"keep",type:"bool",required:!1,constraint:"Remove the deadline entirely so the job runs to completion. Mutually exclusive with --for; give exactly one."},{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node owning the job. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The owning node."},{name:"deadline_at",type:"string",required:!1,constraint:"The job\u2019s new auto-cancel time (ISO), or absent when --keep cleared the deadline so the job runs to completion."}],outputKind:"object",effects:["Rewrites or clears the deadline on the job\u2019s row. The daemon\u2019s deadline lane reads it on its next scan. Signals nothing."]},run:i(async e=>{const{id:t}=b(e,"no node found for the bash job"),n=await c(t);if(n===null)throw new r({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=e.job;if(!g(o))throw new r({error:"invalid_job_id",message:`invalid background job id: ${o}`,next:"Use a job id reported by `crtr node bash list`."});const s=e.for,d=e.keep===!0;if(d===(s!==void 0&&s!==""))throw new r({error:"invalid_args",message:"give exactly one of --for <duration> or --keep",next:"Extend by a window with --for 10m, or drop the deadline with --keep."});if(d)return await _(n.node_id,o,{keep:!0}),{node_id:n.node_id};const l=U(s);if(l===null||l<=0)throw new r({error:"invalid_duration",message:`not a duration: ${s}`,next:"Use a value like 90s, 10m, or 1h30m."});const a=Date.now()+l;return await _(n.node_id,o,{deadline_at_ms:a}),{node_id:n.node_id,deadline_at:new Date(a).toISOString()}},"run"),render:i(e=>e.deadline_at===void 0?`Cleared the deadline \u2014 the background job will run to completion for ${e.node_id}.`:`Background job for ${e.node_id} will be canceled at ${e.deadline_at} unless extended again.`,"render")}),re=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{re as nodeBash};
@@ -57,15 +57,19 @@ export interface ViewSource {
57
57
  pause(): void;
58
58
  resume(): void;
59
59
  }
60
- /** Viewer frames, in order (a channel's view.close stays behind its data), fed into the link only while it holds fewer than
61
- * VIEW_SEND_LOW_WATER unsent bytes; anything sent on the sink directly (a call result, a view.ready) therefore goes ahead of the queue. A source is
62
- * paused while the queue is deep, so a slow link never buffers a pane stream in memory. */
60
+ /** Viewer frames, one queue per channel, fed into the link only while it holds fewer than VIEW_SEND_LOW_WATER unsent bytes; anything
61
+ * sent on the sink directly (a call result, a view.ready) therefore goes ahead of the queues. A channel's frames keep their order (its
62
+ * view.close stays behind its data). Across channels the one with the fewest queued bytes goes next: a welcome carries a node's whole
63
+ * conversation (megabytes), and on a slow uplink one shared queue held every other node's frames behind it. A channel's source is
64
+ * paused while that channel's queue is deep, so a slow link never buffers a pane stream in memory. `drop` discards a channel the
65
+ * holder closed, so its queued frames are not uploaded. */
63
66
  export declare function createViewQueue(sink: ViewSink): {
64
- push(data: string, source?: ViewSource): void;
67
+ push(data: string, source?: ViewSource, channel?: string): void;
65
68
  waiting(): {
66
69
  bytes: number;
67
70
  frames: number;
68
71
  };
72
+ drop(channel: string): void;
69
73
  forget(source: ViewSource): void;
70
74
  };
71
75
  export declare function linkUrl(apiUrl: string, environmentId: string): string;
@@ -1 +1 @@
1
- var j=Object.defineProperty;var s=(t,a)=>j(t,"name",{value:a,configurable:!0});import{randomUUID as J}from"node:crypto";import{WebSocket as v}from"ws";import{APIError as O}from"../../api/errors.js";import{emitEvent as x}from"../../core/events/emit.js";import{RUNTIME_VERSION_HEADER as W}from"../../api/runtime-version.js";import{crtrVersion as K}from"../../shared/crtr-version.js";import{connectViewSocket as q}from"../../core/runtime/view-socket.js";import{CLOSE_REVOKED as D,LINK_MAX_PAYLOAD_BYTES as F,parseFrame as Y}from"./frames.js";const $=1e3,X=6e4,z=64*1024,H=4*1024*1024,Q=1024*1024,G=8*1024*1024,Z=15e3,ee=75e3;function ne(t){const a=[];let c=0;const p=new Set,M=s(()=>{for(;a.length>0&&t.open()&&t.bufferedAmount<z;){const l=a.shift();c-=l.length,t.send(l,M)}if(c<Q&&p.size>0){for(const l of p)l.resume();p.clear()}},"pump");return{push(l,d){t.open()&&(a.push(l),c+=l.length,d!==void 0&&c>H&&(d.pause(),p.add(d)),M())},waiting:s(()=>({bytes:c,frames:a.length}),"waiting"),forget(l){p.delete(l)}}}s(ne,"createViewQueue");function te(t,a){const c=new URL(`/v1/machines/${encodeURIComponent(a)}/link`,t);return c.protocol=c.protocol==="https:"?"wss:":c.protocol==="http:"?"ws:":c.protocol,c.toString()}s(te,"linkUrl");function fe(t){const a=t.backoffMinMs??$,c=t.backoffMaxMs??X,p=t.openView??q,M=t.silenceMs??ee;let l=!1,d,_=a,k;const E=new Map,P=200,S=[],L=s(()=>{const u=d;for(;S.length>0&&u?.readyState===v.OPEN;)u.send(JSON.stringify({type:"exit",...S.shift()}))},"flushExits"),I=s((u,o)=>{x({level:"error",event:u,fields:{environment:t.environmentId},error:o})},"fault");let T;const A=s(()=>{if(l)return;if(T!==void 0){if(t.credential()===T){k=setTimeout(A,_),_=Math.min(_*2,c);return}T=void 0}const u=t.credential(),o=new v(te(t.apiUrl,t.environmentId),{headers:{authorization:`Bearer ${u}`,[W]:K()},maxPayload:F});d=o;const f=new Map,m=new Map,h=s(e=>{o.readyState===v.OPEN&&o.send(JSON.stringify(e))},"send"),g=ne({get bufferedAmount(){return o.bufferedAmount},open:s(()=>o.readyState===v.OPEN,"open"),send:s((e,n)=>o.send(e,n),"send")}),w=s((e,n)=>g.push(JSON.stringify(e),n),"sendView"),N=s(e=>Math.round(e*10)/10,"round"),R=s(async e=>{const n=t.handlers[e.op];if(n===void 0){h({type:"result",call_id:e.call_id,ok:!1,error:`this machine does not execute ${e.op}`});return}const r=new AbortController,i=s(()=>r.abort(new Error("the machine link closed")),"onClose");o.once("close",i);try{h({type:"result",call_id:e.call_id,ok:!0,value:await n(e.args,r.signal)??null})}catch(y){h({type:"result",call_id:e.call_id,ok:!1,error:y instanceof Error?y.message:String(y)})}finally{o.off("close",i)}},"runCall"),V=s(e=>{const n=p(e.node);f.set(e.channel,n);const r=performance.now();n.once("connect",()=>{const i=performance.now(),y=g.waiting(),B=o.bufferedAmount;h({type:"view.ready",channel:e.channel}),x({level:"info",event:"daemon.timing.view_ready_sent",fields:{channel:e.channel,node:e.node,open_to_connect_ms:N(i-r),queued_bytes:y.bytes,queued_frames:y.frames,link_buffered_bytes_before:B,link_buffered_bytes_after:o.bufferedAmount}})}),n.on("data",i=>w({type:"view.data",channel:e.channel,bytes:i.toString("base64")},n)),n.once("error",i=>{g.forget(n),f.delete(e.channel)&&w({type:"view.close",channel:e.channel,error:i.message})}),n.once("close",()=>{g.forget(n),f.delete(e.channel)&&w({type:"view.close",channel:e.channel})})},"openChannel"),U=s((e,n)=>{const r=f.get(e);if(r===void 0||r.write(n))return;const i=(m.get(e)??0)+n.length;if(i>G){f.delete(e),m.delete(e),r.destroy(),w({type:"view.close",channel:e,error:"the broker is not draining the viewer channel"});return}m.has(e)||r.once("drain",()=>m.delete(e)),m.set(e,i)},"writeToChannel");let b;const C=s(()=>{b!==void 0&&clearTimeout(b),b=setTimeout(()=>{x({level:"warn",event:"daemon.machine_link.silent",fields:{environment:t.environmentId}}),o.terminate()},M)},"heard");o.on("open",()=>{_=a,C(),L(),t.onOpen?.()}),o.on("ping",C),o.on("message",e=>{C();const n=Y(e);if(n!==null)try{switch(n.type){case"call":R(n);return;case"job.reported":{const r=E.get(n.id);E.delete(n.id),n.error===void 0?r?.resolve():r?.reject(new O(n.error.status,n.error.code,n.error.message));return}case"view.open":V(n);return;case"view.data":U(n.channel,Buffer.from(n.bytes,"base64"));return;case"view.close":{const r=f.get(n.channel);f.delete(n.channel),r?.destroy();return}default:return}}catch(r){I("daemon.machine_link.frame_failed",r)}}),o.on("unexpected-response",(e,n)=>{let r="";n.on("data",i=>{r+=i.toString("utf8")}).on("close",()=>{o.terminate(),I("daemon.machine_link.refused",new Error(`${n.statusCode??"no status"} ${r}`));try{n.statusCode===426&&t.onBehind?.(JSON.parse(r).error.message)}catch(i){I("daemon.machine_link.client_error",i)}})}),o.on("error",e=>I("daemon.machine_link.client_error",e)),o.on("close",e=>{b!==void 0&&clearTimeout(b);for(const n of f.values())n.destroy();f.clear(),d===o&&(d=void 0);for(const[n,r]of E)E.delete(n),r.reject(new O(503,"machine_offline","the machine link closed before the job report was answered"));l||(e===D&&(x({level:"error",event:"daemon.machine_link.revoked",fields:{environment:t.environmentId}}),T=u),k=setTimeout(A,_),_=Math.min(_*2,c))})},"connect");return A(),{stop(){l=!0,k!==void 0&&clearTimeout(k),d?.close()},connected:s(()=>d?.readyState===v.OPEN,"connected"),reportJob(u,o,f){const m=d;if(m?.readyState!==v.OPEN)return Promise.reject(new O(503,"machine_offline","the machine link is not open"));const h=J();return new Promise((g,w)=>{const N=setTimeout(()=>{E.delete(h),w(new O(504,"request_timeout","the control plane did not answer the job report"))},t.jobReportTimeoutMs??Z);E.set(h,{resolve:s(()=>{clearTimeout(N),g()},"resolve"),reject:s(R=>{clearTimeout(N),w(R)},"reject")}),m.send(JSON.stringify({type:"job.report",id:h,node:u,job:o,request:f}))})},reportExit(u){S.push(u),S.length>P&&S.shift(),L()}}}s(fe,"startMachineLink");export{Z as JOB_REPORT_TIMEOUT_MS,X as LINK_BACKOFF_MAX_MS,$ as LINK_BACKOFF_MIN_MS,ee as LINK_SILENCE_MS,G as VIEW_WRITE_LIMIT_BYTES,ne as createViewQueue,te as linkUrl,fe as startMachineLink};
1
+ var j=Object.defineProperty;var s=(t,d)=>j(t,"name",{value:d,configurable:!0});import{randomUUID as J}from"node:crypto";import{WebSocket as v}from"ws";import{APIError as O}from"../../api/errors.js";import{emitEvent as x}from"../../core/events/emit.js";import{RUNTIME_VERSION_HEADER as W}from"../../api/runtime-version.js";import{crtrVersion as q}from"../../shared/crtr-version.js";import{connectViewSocket as K}from"../../core/runtime/view-socket.js";import{CLOSE_REVOKED as D,LINK_MAX_PAYLOAD_BYTES as F,parseFrame as Y}from"./frames.js";const $=1e3,X=6e4,z=64*1024,H=4*1024*1024,Q=1024*1024,G=8*1024*1024,Z=15e3,ee=75e3;function ne(t){const d=new Map,f=s(()=>{for(;t.open()&&t.bufferedAmount<z;){let i;for(const h of d)(i===void 0||h[1].bytes<i[1].bytes)&&(i=h);if(i===void 0)return;const[u,l]=i,c=l.frames.shift();l.bytes-=c.length,l.paused!==void 0&&l.bytes<Q&&(l.paused.resume(),l.paused=void 0),l.frames.length===0&&d.delete(u),t.send(c,f)}},"pump");return{push(i,u,l=""){if(!t.open())return;const c=d.get(l)??{frames:[],bytes:0};d.set(l,c),c.frames.push(i),c.bytes+=i.length,u!==void 0&&c.paused===void 0&&c.bytes>H&&(u.pause(),c.paused=u),f()},waiting:s(()=>[...d.values()].reduce((i,u)=>({bytes:i.bytes+u.bytes,frames:i.frames+u.frames.length}),{bytes:0,frames:0}),"waiting"),drop(i){d.delete(i)},forget(i){for(const u of d.values())u.paused===i&&(u.paused=void 0)}}}s(ne,"createViewQueue");function te(t,d){const f=new URL(`/v1/machines/${encodeURIComponent(d)}/link`,t);return f.protocol=f.protocol==="https:"?"wss:":f.protocol==="http:"?"ws:":f.protocol,f.toString()}s(te,"linkUrl");function fe(t){const d=t.backoffMinMs??$,f=t.backoffMaxMs??X,i=t.openView??K,u=t.silenceMs??ee;let l=!1,c,h=d,k;const g=new Map,P=200,S=[],L=s(()=>{const m=c;for(;S.length>0&&m?.readyState===v.OPEN;)m.send(JSON.stringify({type:"exit",...S.shift()}))},"flushExits"),I=s((m,r)=>{x({level:"error",event:m,fields:{environment:t.environmentId},error:r})},"fault");let T;const A=s(()=>{if(l)return;if(T!==void 0){if(t.credential()===T){k=setTimeout(A,h),h=Math.min(h*2,f);return}T=void 0}const m=t.credential(),r=new v(te(t.apiUrl,t.environmentId),{headers:{authorization:`Bearer ${m}`,[W]:q()},maxPayload:F});c=r;const p=new Map,_=new Map,y=s(e=>{r.readyState===v.OPEN&&r.send(JSON.stringify(e))},"send"),w=ne({get bufferedAmount(){return r.bufferedAmount},open:s(()=>r.readyState===v.OPEN,"open"),send:s((e,n)=>r.send(e,n),"send")}),b=s((e,n)=>w.push(JSON.stringify(e),n,e.channel),"sendView"),N=s(e=>Math.round(e*10)/10,"round"),R=s(async e=>{const n=t.handlers[e.op];if(n===void 0){y({type:"result",call_id:e.call_id,ok:!1,error:`this machine does not execute ${e.op}`});return}const o=new AbortController,a=s(()=>o.abort(new Error("the machine link closed")),"onClose");r.once("close",a);try{y({type:"result",call_id:e.call_id,ok:!0,value:await n(e.args,o.signal)??null})}catch(E){y({type:"result",call_id:e.call_id,ok:!1,error:E instanceof Error?E.message:String(E)})}finally{r.off("close",a)}},"runCall"),V=s(e=>{const n=i(e.node);p.set(e.channel,n);const o=performance.now();n.once("connect",()=>{const a=performance.now(),E=w.waiting(),B=r.bufferedAmount;y({type:"view.ready",channel:e.channel}),x({level:"info",event:"daemon.timing.view_ready_sent",fields:{channel:e.channel,node:e.node,open_to_connect_ms:N(a-o),queued_bytes:E.bytes,queued_frames:E.frames,link_buffered_bytes_before:B,link_buffered_bytes_after:r.bufferedAmount}})}),n.on("data",a=>b({type:"view.data",channel:e.channel,bytes:a.toString("base64")},n)),n.once("error",a=>{w.forget(n),p.delete(e.channel)&&b({type:"view.close",channel:e.channel,error:a.message})}),n.once("close",()=>{w.forget(n),p.delete(e.channel)&&b({type:"view.close",channel:e.channel})})},"openChannel"),U=s((e,n)=>{const o=p.get(e);if(o===void 0||o.write(n))return;const a=(_.get(e)??0)+n.length;if(a>G){p.delete(e),_.delete(e),o.destroy(),b({type:"view.close",channel:e,error:"the broker is not draining the viewer channel"});return}_.has(e)||o.once("drain",()=>_.delete(e)),_.set(e,a)},"writeToChannel");let M;const C=s(()=>{M!==void 0&&clearTimeout(M),M=setTimeout(()=>{x({level:"warn",event:"daemon.machine_link.silent",fields:{environment:t.environmentId}}),r.terminate()},u)},"heard");r.on("open",()=>{h=d,C(),L(),t.onOpen?.()}),r.on("ping",C),r.on("message",e=>{C();const n=Y(e);if(n!==null)try{switch(n.type){case"call":R(n);return;case"job.reported":{const o=g.get(n.id);g.delete(n.id),n.error===void 0?o?.resolve():o?.reject(new O(n.error.status,n.error.code,n.error.message));return}case"view.open":V(n);return;case"view.data":U(n.channel,Buffer.from(n.bytes,"base64"));return;case"view.close":{const o=p.get(n.channel);p.delete(n.channel),o?.destroy(),w.drop(n.channel);return}default:return}}catch(o){I("daemon.machine_link.frame_failed",o)}}),r.on("unexpected-response",(e,n)=>{let o="";n.on("data",a=>{o+=a.toString("utf8")}).on("close",()=>{r.terminate(),I("daemon.machine_link.refused",new Error(`${n.statusCode??"no status"} ${o}`));try{n.statusCode===426&&t.onBehind?.(JSON.parse(o).error.message)}catch(a){I("daemon.machine_link.client_error",a)}})}),r.on("error",e=>I("daemon.machine_link.client_error",e)),r.on("close",e=>{M!==void 0&&clearTimeout(M);for(const n of p.values())n.destroy();p.clear(),c===r&&(c=void 0);for(const[n,o]of g)g.delete(n),o.reject(new O(503,"machine_offline","the machine link closed before the job report was answered"));l||(e===D&&(x({level:"error",event:"daemon.machine_link.revoked",fields:{environment:t.environmentId}}),T=m),k=setTimeout(A,h),h=Math.min(h*2,f))})},"connect");return A(),{stop(){l=!0,k!==void 0&&clearTimeout(k),c?.close()},connected:s(()=>c?.readyState===v.OPEN,"connected"),reportJob(m,r,p){const _=c;if(_?.readyState!==v.OPEN)return Promise.reject(new O(503,"machine_offline","the machine link is not open"));const y=J();return new Promise((w,b)=>{const N=setTimeout(()=>{g.delete(y),b(new O(504,"request_timeout","the control plane did not answer the job report"))},t.jobReportTimeoutMs??Z);g.set(y,{resolve:s(()=>{clearTimeout(N),w()},"resolve"),reject:s(R=>{clearTimeout(N),b(R)},"reject")}),_.send(JSON.stringify({type:"job.report",id:y,node:m,job:r,request:p}))})},reportExit(m){S.push(m),S.length>P&&S.shift(),L()}}}s(fe,"startMachineLink");export{Z as JOB_REPORT_TIMEOUT_MS,X as LINK_BACKOFF_MAX_MS,$ as LINK_BACKOFF_MIN_MS,ee as LINK_SILENCE_MS,G as VIEW_WRITE_LIMIT_BYTES,ne as createViewQueue,te as linkUrl,fe as startMachineLink};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.696",
3
+ "version": "0.3.697",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -156,8 +156,8 @@
156
156
  },
157
157
  "license": "UNLICENSED",
158
158
  "dependencies": {
159
- "@north-light/identity": "0.3.696",
160
- "@north-light/plugin": "0.3.696",
159
+ "@north-light/identity": "0.3.697",
160
+ "@north-light/plugin": "0.3.697",
161
161
  "@earendil-works/chord": "1.5.2",
162
162
  "@earendil-works/pi-agent-core": "1.5.2",
163
163
  "@earendil-works/pi-ai": "1.5.2",
@@ -136,7 +136,7 @@ const nodeBashBackground = defineLeaf({
136
136
  if (node === null) {
137
137
  throw new InputError({ error: 'not_found', message: `no node: ${id}`, next: 'List nodes with `crtr node inspect list`.' });
138
138
  }
139
- const jobs = backgroundRunningBashJobs(node.paths.context_dir);
139
+ const jobs = backgroundRunningBashJobs(contextDir(node.node_id, node.grantee));
140
140
  const now = Date.now();
141
141
  const elapsed = jobs.map((job) => ({ job_id: job.jobId, elapsed_ms: now - (jobStartedAtMs(job.jobId) ?? now) }));
142
142
  // No tmux toast. A tmux status-line message commandeers the whole client's
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.696",
3
+ "version": "0.3.697",
4
4
  "description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "main": "./dist/api/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.696",
3
+ "version": "0.3.697",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/plugin",
3
- "version": "0.3.696",
3
+ "version": "0.3.697",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -27,8 +27,8 @@
27
27
  "postpack": "node ../../scripts/pack-minify.mjs postpack packages/crouter-plugin"
28
28
  },
29
29
  "dependencies": {
30
- "@north-light/api": "0.3.696",
31
- "@north-light/identity": "0.3.696"
30
+ "@north-light/api": "0.3.697",
31
+ "@north-light/identity": "0.3.697"
32
32
  },
33
33
  "license": "UNLICENSED",
34
34
  "publishConfig": {
package/runtime.lock.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.696",
3
+ "version": "0.3.697",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.696",
9
+ "version": "0.3.697",
10
10
  "hasInstallScript": true,
11
11
  "license": "UNLICENSED",
12
12
  "workspaces": [
@@ -28,8 +28,8 @@
28
28
  "@milkdown/preset-gfm": "^7.22.3",
29
29
  "@milkdown/prose": "^7.22.3",
30
30
  "@milkdown/utils": "^7.22.3",
31
- "@north-light/identity": "0.3.696",
32
- "@north-light/plugin": "0.3.696",
31
+ "@north-light/identity": "0.3.697",
32
+ "@north-light/plugin": "0.3.697",
33
33
  "cron-parser": "^5.6.0",
34
34
  "esbuild": "0.28.2",
35
35
  "jose": "^6.2.12",
@@ -10667,17 +10667,17 @@
10667
10667
  },
10668
10668
  "packages/crouter-api": {
10669
10669
  "name": "@north-light/api",
10670
- "version": "0.3.696",
10670
+ "version": "0.3.697",
10671
10671
  "license": "UNLICENSED"
10672
10672
  },
10673
10673
  "packages/crouter-env-docker": {
10674
10674
  "name": "@north-light/env-docker",
10675
- "version": "0.3.696",
10675
+ "version": "0.3.697",
10676
10676
  "license": "UNLICENSED"
10677
10677
  },
10678
10678
  "packages/crouter-identity": {
10679
10679
  "name": "@north-light/identity",
10680
- "version": "0.3.696",
10680
+ "version": "0.3.697",
10681
10681
  "license": "UNLICENSED",
10682
10682
  "dependencies": {
10683
10683
  "jose": "^6.2.1"
@@ -10685,21 +10685,21 @@
10685
10685
  },
10686
10686
  "packages/crouter-plugin": {
10687
10687
  "name": "@north-light/plugin",
10688
- "version": "0.3.696",
10688
+ "version": "0.3.697",
10689
10689
  "license": "UNLICENSED",
10690
10690
  "dependencies": {
10691
- "@north-light/api": "0.3.696",
10692
- "@north-light/identity": "0.3.696"
10691
+ "@north-light/api": "0.3.697",
10692
+ "@north-light/identity": "0.3.697"
10693
10693
  }
10694
10694
  },
10695
10695
  "packages/crouter-sdk": {
10696
10696
  "name": "@north-light/sdk",
10697
- "version": "0.3.696",
10697
+ "version": "0.3.697",
10698
10698
  "license": "UNLICENSED",
10699
10699
  "dependencies": {
10700
- "@north-light/api": "0.3.696",
10701
- "@north-light/identity": "0.3.696",
10702
- "@north-light/plugin": "0.3.696",
10700
+ "@north-light/api": "0.3.697",
10701
+ "@north-light/identity": "0.3.697",
10702
+ "@north-light/plugin": "0.3.697",
10703
10703
  "jose": "^6.2.1"
10704
10704
  },
10705
10705
  "bin": {