@north-light/cli 0.3.695 → 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.
- package/dist/clients/attach/session/connection.js +1 -1
- package/dist/clients/attach/viewer.js +374 -374
- package/dist/commands/node/bash.js +2 -2
- package/dist/core/broker-client/transport-relay.d.ts +12 -1
- package/dist/core/broker-client/transport-relay.js +1 -1
- package/dist/core/runtime/runner/machine/executor.d.ts +0 -3
- package/dist/core/runtime/runner/machine/executor.js +1 -1
- package/dist/core/runtime/runner/machine/machine-executor.test.js +2 -2
- package/dist/core/runtime/runner/machine/ops.d.ts +5 -6
- package/dist/core/runtime/runner/machine/runner.d.ts +3 -0
- package/dist/core/runtime/runner/machine/runner.js +1 -1
- package/dist/daemon/api/bridge.js +4 -4
- package/dist/daemon/api/handlers/attach.js +1 -1
- package/dist/daemon/machine-daemon.js +1 -1
- package/dist/daemon/machine-link/client.d.ts +10 -4
- package/dist/daemon/machine-link/client.js +1 -1
- package/dist/daemon/machine-link/forward.d.ts +2 -4
- package/dist/daemon/machine-link/forward.js +1 -1
- package/dist/daemon/machine-link/holder.js +5 -5
- package/dist/daemon/reconcilers/node-lifecycle/machine-sweep.d.ts +1 -1
- package/dist/daemon/reconcilers/node-lifecycle/machine-sweep.js +2 -2
- package/package.json +3 -3
- package/packages/crouter-api/dist/clients/attach/session/connection.js +37 -24
- package/packages/crouter-api/dist/commands/node/bash.js +1 -1
- package/packages/crouter-api/dist/core/broker-client/transport-relay.js +24 -7
- package/packages/crouter-api/dist/core/runtime/runner/machine/runner.js +10 -8
- package/packages/crouter-api/dist/daemon/machine-link/forward.js +12 -11
- package/packages/crouter-api/dist/daemon/machine-link/holder.js +5 -0
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
- package/scripts/self-update.mjs +7 -3
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
var
|
|
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=
|
|
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};
|
|
@@ -20,10 +20,15 @@ export interface LocalRelayTarget {
|
|
|
20
20
|
export declare class RelayTransport extends EventEmitter implements Transport {
|
|
21
21
|
private readonly nodeId;
|
|
22
22
|
private readonly target;
|
|
23
|
+
/** Whether the first dial wakes an exact parked resident; every redial does. */
|
|
24
|
+
private wakeParked;
|
|
23
25
|
private ws;
|
|
24
26
|
private closeEmitted;
|
|
25
|
-
constructor(nodeId: string, target: RelayTarget | LocalRelayTarget
|
|
27
|
+
constructor(nodeId: string, target: RelayTarget | LocalRelayTarget,
|
|
28
|
+
/** Whether the first dial wakes an exact parked resident; every redial does. */
|
|
29
|
+
wakeParked?: boolean);
|
|
26
30
|
private refusal;
|
|
31
|
+
private refusalError;
|
|
27
32
|
private get url();
|
|
28
33
|
private dial;
|
|
29
34
|
connect(): void;
|
|
@@ -46,5 +51,11 @@ export declare class RelayTransport extends EventEmitter implements Transport {
|
|
|
46
51
|
* with no listener throws, and this transport must never throw uncaught. */
|
|
47
52
|
private emitError;
|
|
48
53
|
}
|
|
54
|
+
/** The status, code and message of a refused upgrade's `{error:{code,message}}` body, for a caller that shows the refusal as the API error it is. */
|
|
55
|
+
export interface Refusal {
|
|
56
|
+
status: number;
|
|
57
|
+
code: string;
|
|
58
|
+
message: string;
|
|
59
|
+
}
|
|
49
60
|
/** `409 broker_not_ready: <message>` from a refused upgrade's `{error:{code,message}}` body. */
|
|
50
61
|
export declare function refusalMessage(status: number | undefined, body: string): string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var d=Object.defineProperty;var a=(s,e)=>d(s,"name",{value:e,configurable:!0});import{EventEmitter as l}from"node:events";import{WebSocket as h}from"ws";import{classify as f}from"../fault-classifier.js";import{AttachRefusedError as u,BrokerUnavailableError as m}from"./transport.js";function g(s,e,t){if("socketPath"in s)return`ws+unix://${s.socketPath}:/v1/nodes/${encodeURIComponent(e)}/attach?revive=0`;const r=new URL(s.previewEndpoint);return r.protocol=r.protocol==="http:"?"ws:":"wss:",r.pathname=`/v1/nodes/${encodeURIComponent(e)}/attach`,r.search=t?"?wakeParked=1":"",r.hash="",r.toString()}a(g,"relayUrl");class O extends l{static{a(this,"RelayTransport")}nodeId;target;wakeParked;ws;closeEmitted=!1;constructor(e,t,r=!0){super(),this.nodeId=e,this.target=t,this.wakeParked=r}refusal;refusalError;get url(){return g(this.target,this.nodeId,this.wakeParked)}dial(){const e=new h(this.url,{..."relayToken"in this.target?{headers:{authorization:`Bearer ${this.target.relayToken}`}}:{},perMessageDeflate:!1});return e.on("unexpected-response",(t,r)=>{let o="";r.on("data",n=>{o.length<2048&&(o+=n.toString())}),r.on("end",()=>{this.refusal=w(r.statusCode,o),this.refusalError=p(r.statusCode,o),e.terminate()})}),this.ws=e,e}connect(){const e=this.dial();e.on("open",()=>{this.emit("connect")}),e.on("message",t=>this.onMessage(t)),e.on("error",t=>this.onError(t)),e.on("close",(t,r)=>this.onClose(t,r.toString()))}redial(e){return this.wakeParked=!0,this.destroy(),this.closeEmitted=!1,new Promise((t,r)=>{const o=this.dial();let n=!1;o.on("open",()=>{n||(n=!0,this.emit("connect"),t())}),o.on("message",i=>this.onMessage(i)),o.on("error",i=>{if(n){this.onError(i);return}n=!0;try{o.terminate()}catch{}r(this.refusal===void 0?i:Object.assign(new Error(this.refusal),{refusal:this.refusalError}))}),o.on("close",(i,c)=>{n&&this.onClose(i,c.toString())})})}send(e){const t=this.ws;if(!(t===void 0||t.readyState!==h.OPEN))try{t.send(JSON.stringify(e))}catch{}}destroy(){const e=this.ws;if(e!==void 0&&e.readyState<=h.OPEN)try{e.close(1e3)}catch{}}onMessage(e){let t;try{t=JSON.parse(e.toString())}catch{return}this.emit("frame",t)}onError(e){this.emitError(Object.assign(new Error(`relay transport error: ${this.refusal??e.message}`),{refusal:this.refusalError}))}onClose(e,t){if(this.closeEmitted)return;this.closeEmitted=!0;const r=f("viewer\u2194broker",{code:e,reason:t}),o=e===1008||r.kind==="protocol"||e===1011&&(/^no running broker/.test(t)||/^no node /.test(t));e===1008?this.emitError(new u(this.nodeId,t)):o&&this.emitError(new m(this.nodeId)),this.emit("close")}emitError(e){this.listenerCount("error")>0&&this.emit("error",e)}}function p(s,e){try{const t=JSON.parse(e).error;if(s!==void 0&&typeof t?.code=="string")return{status:s,code:t.code,message:typeof t.message=="string"?t.message:""}}catch{}}a(p,"refusalOf");function w(s,e){try{const t=JSON.parse(e).error;if(typeof t?.code=="string")return`attach refused (${s??"?"} ${t.code}): ${typeof t.message=="string"?t.message:""}`}catch{}return`attach refused (${s??"?"})`}a(w,"refusalMessage");export{O as RelayTransport,w as refusalMessage};
|
|
@@ -23,9 +23,6 @@ export declare function findBrokers(): Promise<Array<{
|
|
|
23
23
|
node: string;
|
|
24
24
|
command: string;
|
|
25
25
|
}>>;
|
|
26
|
-
/** Reads the start bundle. A transient failure (connection error, timeout, 502/503/504) is asked again with doubling backoff until the budget above is spent, so a brief
|
|
27
|
-
* control-plane restart does not end the launch; any other non-2xx answer is permanent and fails at once with its status. The link dropping (`signal`) ends the wait. */
|
|
28
|
-
export declare function fetchBundle(apiUrl: string, executionId: string, token: string, signal?: AbortSignal): Promise<StartBundleDTO>;
|
|
29
26
|
/** The recipe's `-e` extension paths name files of the control plane's install (`/opt/crouter/runtime/generations/...`), and its release may ship a different
|
|
30
27
|
* set of canvas extensions than this install. So the mandatory canvas extensions are this install's complete list (`mergeCanvasExtensions`), whatever the recipe
|
|
31
28
|
* carried of them; the recipe's own extensions are kept and must exist on this machine, or the launch is refused. Every other argument is the recipe's. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var $=Object.defineProperty;var c=(n,r)=>$(n,"name",{value:r,configurable:!0});import{spawn as B}from"node:child_process";import{closeSync as j,existsSync as w,mkdirSync as b,openSync as K,statSync as J}from"node:fs";import{rm as V}from"node:fs/promises";import{basename as O,dirname as N,join as I}from"node:path";import{fileURLToPath as X}from"node:url";import{emitEvent as W}from"../../../events/emit.js";import{contextDir as Y,jobDir as q,nodeRunDir as P,crtrHome as M,viewSocketPath as z}from"../../../canvas/paths.js";import{captureTeardownSnapshot as Q,isAnyPidAlive as Z,killProcessTreePids as D,listProcessTableAsync as g}from"../../../canvas/pid.js";import{scopesFilePath as L}from"../../../canvas/paths.js";import{writeFileBeneath as A}from"../../../spaces/open-beneath.js";import{FRONT_DOOR_ENV as ee}from"../../front-door-env.js";import{brokerCommandDeclaresCanvasHome as ne}from"../../broker-ownership.js";import{isShippedCanvasExtension as oe}from"../../../canvas/extensions.js";import{CANVAS_EXTENSIONS as te,mergeCanvasExtensions as re}from"../../canvas-extensions.js";import{layoutRoot as ie,runtimeRoot as ce}from"../../../layout.js";import{composeAppProcessEnv as se,overlayBrokerEnv as ae}from"../../spawn-env.js";const k=c(()=>I(N(X(import.meta.url)),"..","..","broker-cli.js"),"brokerEntry"),G=c(n=>{if(n!==void 0)try{process.kill(-n,"SIGKILL")}catch{}},"killGroup"),de=c(n=>new Promise(r=>setTimeout(r,n)),"sleep");async function x(){const n=[],r=await g();if(r===null)throw new Error("the process table could not be read, so which brokers are running is unknown");for(const{pid:t,command:e}of r){const o=/broker-cli\.js .*--epoch (\S+) (\S+)\s*$/.exec(e);o!==null&&n.push({pid:t,execution:o[1],node:o[2],command:e})}return n}c(x,"findBrokers");const ue=["CRTR_HOME","CRTR_RUNTIME_HOME"];function H(n,r){const t={...n};for(const e of ue)delete t[e];return t.CRTR_CONTEXT_DIR!==void 0&&(t.CRTR_CONTEXT_DIR=Y(r.id,t.CRTR_GRANTEE??r.app)),t.CRTR_SCOPES_FILE!==void 0&&(t.CRTR_SCOPES_FILE=L(r.id)),t}c(H,"localLaunchEnv");function fe(n){const r=c(i=>O(i).replace(/\.[jt]s$/,""),"stem"),t=new Set(te.map(r)),e=c(i=>oe(i)||O(N(i))==="pi-extensions"&&(t.has(r(i))||r(i).startsWith("canvas-")&&!w(i)),"shipped"),o=[],s=[];for(let i=0;i<n.length;i++)if(n[i]==="-e"&&n[i+1]!==void 0){const d=n[++i];if(e(d))continue;if(!w(d))throw new Error(`extension ${d} does not exist on this machine`);s.push(d)}else o.push(n[i]);return[...re(s).flatMap(i=>["-e",i]),...o]}c(fe,"localExtensionArgv");function le(n,r,t){const e=JSON.parse(n);return JSON.stringify({...e,argv:fe(e.argv),env:H(e.env??{},r),...t===void 0?{}:{start:t}})}c(le,"machineLaunchRecipe");function pe(n,r,t){const e=n.launch,o=ae({argv:[],env:H(e.env??{},n.node)},se(n.node.cwd,null,n.node.app,n.machine_env??{},{}));return Object.assign(o,{CRTR_HOME:ie(),CRTR_RUNTIME_HOME:process.env.CRTR_RUNTIME_HOME??ce(),CRTR_API_URL:r.apiUrl,CRTR_EXECUTION_ID:t,CRTR_ENVIRONMENT_ID:r.environmentId,CRTR_VIEW_WSS:"0",[ee]:"1"})}c(pe,"machineBrokerEnv");async function U(n,r,t){const{tree:e,identities:o}=Q(n,null,t);if(o===null)return{confirmed:!1,error:`the process tree of broker ${n} could not be read, so shutdown cannot be confirmed`};const s=c(async(i,d)=>{for(let l=0;Z(i);l+=100){if(l>=d)return!1;await de(100)}return!0},"waitUntilDead");try{process.kill(n,"SIGTERM")}catch{}return await s([n],r),D(e,"SIGTERM",o),await s(e,2e3)?{confirmed:!0}:(D(e,"SIGKILL",o),await s(e,5e3)?{confirmed:!0}:{confirmed:!1,error:`broker process tree of ${n} survived SIGKILL`})}c(U,"stopBroker");async function Pe(n=1e4){const t=(await Promise.all((await x()).filter(e=>ne(e.command,M())).map(e=>U(e.pid,n)))).filter(e=>!e.confirmed);if(t.length>0)throw new Error(t.map(e=>e.error??"a broker did not stop").join("; "))}c(Pe,"stopAllBrokers");function Me(n){const r=(n.stopGraceS??10)*1e3,t=c(async e=>(await x()).find(o=>o.execution===e),"brokerOf");return{async start(e,o){const s={};let i=performance.now();const d=c(a=>{const u=performance.now();s[a]=Math.round((u-i)*10)/10,i=u},"stepDone"),l=await t(e.executionId);if(d("process_lookup"),l!==void 0)return{pid:l.pid,timings:s};if(o?.throwIfAborted(),!w(e.cwd)||!J(e.cwd).isDirectory())throw new Error(`the node's cwd ${e.cwd} is not a directory on this machine`);if(!w(k()))throw new Error(`the broker entry ${k()} does not exist`);if(e.bundle===void 0)throw new Error("the control plane carried no start bundle: it runs an older release than this Mac");const{bundle:E}=e,T=E.launch,m=P(e.nodeId);b(m,{recursive:!0}),A(m,I(m,"broker-launch.json"),le(e.launchJson,E.node,e.start),{atomic:!0,mode:384}),T.env?.CRTR_SCOPES_FILE!==void 0&&A(m,L(e.nodeId),JSON.stringify(T.scopes??[]),{atomic:!0});const S=q(e.nodeId);b(S,{recursive:!0});const R=K(I(S,"broker.log"),"a"),y=pe(E,n,e.executionId);delete y.CRTR_NODE_TOKEN,d("file_writes");try{o?.throwIfAborted();const a=B(process.execPath,[k(),"--canvas-home",M(),"--epoch",e.executionId,e.nodeId],{cwd:e.cwd,detached:!0,stdio:["ignore",R,R,"pipe"],env:y});let u,v=!1;const C=c(()=>{u!==void 0&&n.onExit?.({execution:e.executionId,node:e.nodeId,...u})},"report");a.once("exit",(_,f)=>{u={code:_,signal:f},v&&C()});const p=a.stdio[3];if(p==null||!("end"in p))throw G(a.pid),new Error("broker token pipe did not open");const F=await new Promise((_,f)=>{a.once("error",f),a.once("spawn",()=>{a.off("error",f),p.once("error",h=>{G(a.pid),f(h)}),p.end(e.nodeToken,h=>{h?f(h):_(a.pid)})})});return v=!0,C(),a.unref(),d("spawn_and_token_pipe"),W({level:"info",event:"machine.start.timing",node_id:e.nodeId,fields:{execution:e.executionId,...s}}),{pid:F,timings:s}}finally{j(R)}},async wake({execution:e}){const o=await t(e.executionId);if(o===void 0)return"no_broker";try{return process.kill(o.pid,"SIGUSR1"),"signalled"}catch(s){if(s.code==="ESRCH")return"no_broker";throw s}},async stop({execution:e,options:o}){const s=await t(e.executionId);return s===void 0?{confirmed:!0}:await U(s.pid,r,o.excludePid)},async status({execution:e}){const o=await t(e.executionId);return o===void 0?{state:"gone"}:{state:"running",pid:o.pid}},async"status.all"(e){return{running:(await x()).map(o=>({execution:o.execution,pid:o.pid}))}},async delete({nodeId:e}){return await V(P(e),{recursive:!0,force:!0}),null},async viewer({execution:e}){return{kind:"unix",path:z(e.nodeId)}}}}c(Me,"createMachineExecutor");export{Me as createMachineExecutor,x as findBrokers,fe as localExtensionArgv,pe as machineBrokerEnv,le as machineLaunchRecipe,Pe as stopAllBrokers};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var N=Object.defineProperty;var u=(n,o)=>N(n,"name",{value:o,configurable:!0});import{after as q,before as x,test as
|
|
1
|
+
var N=Object.defineProperty;var u=(n,o)=>N(n,"name",{value:o,configurable:!0});import{after as q,before as x,test as m}from"node:test";import t from"node:assert/strict";import{spawn as y}from"node:child_process";import{mkdirSync as f,mkdtempSync as E,readFileSync as P,rmSync as v,writeFileSync as _}from"node:fs";import{tmpdir as w}from"node:os";import{join as p}from"node:path";import{EventEmitter as A}from"node:events";import{Readable as k}from"node:stream";import{createNode as D}from"../../../canvas/canvas.js";import{closeDb as H,openDb as T}from"../../../canvas/db.js";import{isPidAlive as R}from"../../../canvas/pid.js";import{bindPerson as M,installTerminalGrant as L,useEmptyPersonSettings as F}from"../../../__tests__/helpers/person.js";import{setAppEnvVar as O}from"../../../profiles/app-env-store.js";import{setProfileEnvVar as S}from"../../../profiles/env-store.js";import{createProfile as U}from"../../../profiles/manifest.js";import{putEnvRow as j}from"../../../secrets/env-rows.js";import{appSpace as V}from"../../../layout.js";import{executionStartRoutes as G}from"../../../../daemon/api/handlers/execution-start.js";import{Router as J}from"../../../../daemon/api/router.js";import{contextDir as C,scopesFilePath as g}from"../../../canvas/paths.js";import{layoutRoot as $,runtimeRoot as X}from"../../../layout.js";import{CANVAS_EXTENSIONS as d}from"../../canvas-extensions.js";import{createMachineExecutor as K,localExtensionArgv as B,machineBrokerEnv as h,machineLaunchRecipe as I}from"./executor.js";let l;const Y={HOME:process.env.HOME,CRTR_HOME:process.env.CRTR_HOME};x(()=>{process.env.HOME=l=E(p(w(),"crtr-machine-exec-")),process.env.CRTR_HOME=p(l,".crouter"),f(process.env.CRTR_HOME,{recursive:!0})}),q(async()=>{await H(),v(l,{recursive:!0,force:!0});for(const[n,o]of Object.entries(Y))o===void 0?delete process.env[n]:process.env[n]=o});async function z(n,o){const i=new J().registerAll(G),a=Object.assign(k.from([]),{method:"GET",url:`/v1/executions/${o}/start`,headers:{}});let r="";const e=Object.assign(new A,{headersSent:!1,writableEnded:!1,writableFinished:!1});return e.setHeader=()=>e,e.writeHead=()=>(e.headersSent=!0,e),e.end=s=>(s&&(r+=s),e.writableEnded=!0,e.writableFinished=!0,e),await i.handle(a,e,null,n),JSON.parse(r)}u(z,"bundleFor"),m("a machine broker gets the profile, app and deployment rows, the app pi dir and the launch env, with the process runner's precedence",async()=>{await F(),await T();const n=await L(),o=(await U("machine-env")).profileId;await O("app:terminal","SHARED","from-app",n),await O("app:terminal","APP_SECRET","app-secret",n),await S(o,"SHARED","from-profile",n),await S(o,"PROFILE_VAR","profile-value",n),await j({person:null,kind:"deployment",id:"_deployment"},"DEPLOY_VAR","deploy-value");const i=p(l,"work");f(i,{recursive:!0}),await D({node_id:"m1",name:"m1",created:new Date().toISOString(),cwd:i,kind:"general",mode:"base",lifecycle:"resident",status:"active",parent:null,profile_id:o,grantee:"app:terminal"}),await(await T()).prepare("INSERT INTO executions (execution_id, node_id, state, started_at, launch_json, runner) VALUES ('em1', 'm1', 'launching', 't', ?, 'machine')").run(JSON.stringify({argv:["x"],env:{LAUNCH_VAR:"launch",CRTR_NODE_ID:"m1"}}));const a={class:"broker",app:"app:terminal",node:"m1",run:null,uid:process.getuid?.()??0,sub:await M(),grant:null,client_id:null,scopes:null},r=await z(a,"em1");t.equal(r.machine_env?.APP_SECRET,"app-secret");const e=h(r,{apiUrl:"http://cloud.invalid",environmentId:"env1"},"em1");t.equal(e.APP_SECRET,"app-secret"),t.equal(e.PROFILE_VAR,"profile-value"),t.equal(e.DEPLOY_VAR,"deploy-value"),t.equal(e.SHARED,"from-profile","the profile's row wins over the app's"),t.equal(e.LAUNCH_VAR,"launch"),t.equal(e.PI_CODING_AGENT_DIR,p(V("app:terminal").home,".pi","agent")),t.equal(e.CRTR_API_URL,"http://cloud.invalid"),t.equal(e.CRTR_EXECUTION_ID,"em1"),t.doesNotThrow(()=>h({...r,node:{...r.node,profile:"profile-the-mac-does-not-hold"}},{apiUrl:"http://cloud.invalid",environmentId:"env1"},"em1")),t.equal(e.GITHUB_TOKEN,void 0)}),m("stop ends the broker and the detached command it left behind, and confirms both gone",async()=>{const n=E(p(w(),"crtr-machine-stop-")),o=p(n,"child.pid"),i=p(n,"broker-cli.js");_(i,`const { spawn } = require('node:child_process');
|
|
2
2
|
const c = spawn('sleep', ['300'], { detached: true, stdio: 'ignore' }); c.unref();
|
|
3
3
|
require('node:fs').writeFileSync(${JSON.stringify(o)}, String(c.pid));
|
|
4
|
-
setInterval(() => {}, 1000);`);const a=
|
|
4
|
+
setInterval(() => {}, 1000);`);const a=y(process.execPath,[i,"--canvas-home",n,"--epoch","exec-stop-1","node-stop-1"],{detached:!0,stdio:"ignore"});a.unref();try{let r=0;for(let c=0;c<100&&r===0;c++)try{r=Number(P(o,"utf8"))}catch{await new Promise(b=>setTimeout(b,50))}t.ok(r>0&&R(r),"the detached child is running");const e=K({apiUrl:"http://cloud.invalid",environmentId:"env1",stopGraceS:3});t.ok((await e["status.all"]({})).running.some(c=>c.execution==="exec-stop-1"&&c.pid===a.pid),"status.all lists the running broker");const s=await e.stop({execution:{executionId:"exec-stop-1",nodeId:"node-stop-1"},options:{reason:"test"}});t.deepEqual(s,{confirmed:!0}),t.equal(R(a.pid),!1,"the broker is gone"),t.equal(R(r),!1,"the detached child is gone")}finally{try{process.kill(-a.pid,"SIGKILL")}catch{}v(n,{recursive:!0,force:!0})}}),m("a bundle the control plane built on its Linux layout starts a broker on this machine's own home, runtime, context, scopes and extension paths",()=>{const n={CRTR_HOME:"/work/crtr",CRTR_RUNTIME_HOME:"/opt/crouter/runtime",CRTR_CONTEXT_DIR:"/work/crtr/apps/terminal/nodes/m2/context",CRTR_SCOPES_FILE:"/work/crtr/runtime/nodes/m2/run/scopes.json",CRTR_NODE_ID:"m2",CRTR_KIND:"general",CRTR_GRANTEE:"app:terminal",CRTR_PROFILE_ID:"p-1"},i={launch:{argv:[...d.flatMap(e=>["-e",`/opt/crouter/runtime/generations/96276ec4/dist/pi-extensions/${e.split("/").pop()}`]),"-n","m2"],env:n,scopes:["a:b"]},node:{id:"m2",app:"app:terminal",cwd:l,profile:null},machine_env:{APP_SECRET:"s"}},a=h(i,{apiUrl:"http://cloud.invalid",environmentId:"env1"},"em2");t.equal(a.CRTR_HOME,$()),t.equal(a.CRTR_RUNTIME_HOME,process.env.CRTR_RUNTIME_HOME??X()),t.equal(a.CRTR_CONTEXT_DIR,C("m2","app:terminal")),t.equal(a.CRTR_SCOPES_FILE,g("m2")),t.equal(a.CRTR_NODE_ID,"m2"),t.equal(a.CRTR_PROFILE_ID,"p-1"),t.equal(a.APP_SECRET,"s");for(const[e,s]of Object.entries(a))t.ok(!/\/work\/crtr|\/opt\/crouter/.test(s??""),`${e} names a control plane path: ${s}`);const r=JSON.parse(I(JSON.stringify(i.launch),i.node));t.deepEqual(r.argv.filter((e,s)=>r.argv[s-1]==="-e"),d),t.equal(r.argv.at(-1),"m2"),t.equal(r.env.CRTR_HOME,void 0),t.equal(r.env.CRTR_CONTEXT_DIR,C("m2","app:terminal")),t.equal(r.env.CRTR_SCOPES_FILE,g("m2")),t.deepEqual(r.scopes,["a:b"]),t.ok(!/\/work\/crtr|\/opt\/crouter/.test(JSON.stringify(r))),t.throws(()=>I(JSON.stringify({argv:["-e","/opt/crouter/runtime/generations/x/custom.js"],env:{}}),{id:"m2",app:"app:terminal"}),/does not exist on this machine/)}),m("the broker's mandatory extensions are this install's complete list, whatever set the control plane's release shipped",()=>{const n=u(e=>["-e",`/opt/crouter/runtime/generations/old/dist/pi-extensions/${e}.js`],"server"),o=p(l,"custom-ext.js");_(o,"");const i=[...d,o].flatMap(e=>["-e",e]),r=[...d.map(e=>e.split("/").pop().replace(/\.[jt]s$/,"")).slice(1).flatMap(n),...n("canvas-retired-hook"),"-e",o,"-n","label","prompt text"];t.deepEqual(B(r),[...i,"-n","label","prompt text"])});
|
|
@@ -12,15 +12,14 @@ export type MachineOp = (typeof MACHINE_OPS)[number];
|
|
|
12
12
|
* the UPDATE that finishes any call (answered, failed, lost or offline) sets `args_json` to '{}', and a requeue from `sent` to `pending` keeps it. A row nothing finishes (its awaiter died and no link ever claims it) keeps its arguments: no code deletes `machine_calls` rows. */
|
|
13
13
|
export type MachineStartArgs = RunnerStartInput & {
|
|
14
14
|
nodeToken: string;
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
/** The start data written into `broker-launch.json` for the broker; absent, the broker asks `cycle-start` as before. */
|
|
15
|
+
bundle: StartBundleDTO;
|
|
16
|
+
/** The start data written into `broker-launch.json` for the broker; absent, the broker asks `cycle-start`. */
|
|
18
17
|
start?: StartDataDTO;
|
|
19
18
|
};
|
|
20
|
-
/** `timings` are the Mac's own step durations in ms inside `executor.start
|
|
19
|
+
/** `timings` are the Mac's own step durations in ms inside `executor.start`. */
|
|
21
20
|
export interface MachineStartResult {
|
|
22
21
|
pid: number | null;
|
|
23
|
-
timings
|
|
22
|
+
timings: Record<string, number>;
|
|
24
23
|
}
|
|
25
24
|
export interface MachineWakeArgs {
|
|
26
25
|
execution: RunnerExecution;
|
|
@@ -33,7 +32,7 @@ export interface MachineStatusArgs {
|
|
|
33
32
|
execution: RunnerExecution;
|
|
34
33
|
}
|
|
35
34
|
/** Every broker running on the machine, from one scan of its process table: the control plane's timed check of all its executions
|
|
36
|
-
* there in one call.
|
|
35
|
+
* there in one call. */
|
|
37
36
|
export type MachineStatusAllArgs = Record<string, never>;
|
|
38
37
|
export interface MachineStatusAllResult {
|
|
39
38
|
running: Array<{
|
|
@@ -1,9 +1,12 @@
|
|
|
1
|
+
import type { StartBundleDTO } from '../../../../api/index.js';
|
|
1
2
|
import type { Runner, RunnerStartInput } from '../types.js';
|
|
2
3
|
export interface MachineRunnerDeps {
|
|
3
4
|
/** The machine environment a node runs in. Default: the node's profile's `environment_id`, which must be kind `machine`. */
|
|
4
5
|
environmentOf?(nodeId: string): Promise<string>;
|
|
5
6
|
/** Mints the execution's node token (the execution must be `launching` and have none). Default: `mintNodeToken`. */
|
|
6
7
|
mintToken?(input: RunnerStartInput): Promise<string>;
|
|
8
|
+
/** The start bundle the `start` call carries. Default: `buildStartBundle` for the node, as create-and-start builds it. */
|
|
9
|
+
bundle?(input: RunnerStartInput): Promise<StartBundleDTO>;
|
|
7
10
|
}
|
|
8
11
|
/** The machine environment of a node's profile, or null when the profile points at no machine environment. */
|
|
9
12
|
export declare function machineEnvironmentOfNode(nodeId: string): Promise<string | null>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var m=Object.defineProperty;var i=(r,e)=>m(r,"name",{value:e,configurable:!0});import{getNode as f}from"../../../canvas/canvas.js";import{openDb as w}from"../../../canvas/db.js";import{personIdAsync as l}from"../../../canvas/person.js";import{mintExecutionToken as u}from"../../../canvas/node-tokens.js";import{callMachine as d}from"./call.js";import{machineEnvironmentOfProfile as h}from"./environment.js";import{MachineLostError as p,MachineOfflineError as E}from"./ops.js";async function y(r){const e=await(await w()).prepare("SELECT profile_id FROM nodes WHERE node_id = ?").get(r);return e?.profile_id==null?null:await h(e.profile_id)}i(y,"machineEnvironmentOfNode");const I=i(async r=>{const e=await y(r);if(e===null)throw new Error(`node ${r} has no machine environment`);return e},"defaultEnvironmentOf"),v=i(async r=>{const{buildStartBundle:e}=await import("../../../../daemon/api/handlers/execution-start.js"),n=await f(r.nodeId);return await e({nodeId:r.nodeId,app:n?.grantee??"app:terminal",sub:n?.sub??await l(),launchJson:r.launchJson,runner:"machine"})},"defaultBundle"),s=i(r=>r instanceof Error?r:new Error(String(r)),"asError");function S(r={}){const e=r.environmentOf??I;return{kind:"machine",async start(n){const a=await e(n.nodeId),t=await(r.bundle??v)(n),c=await(r.mintToken??(o=>u(o.executionId,o.nodeId)))(n);try{return{pid:(await d(a,"start",{...n,nodeToken:c,bundle:t})).pid,exited:null}}catch(o){throw o instanceof p?new E(a,o.message,!0):o}},async wake(n){return await d(await e(n.nodeId),"wake",{execution:n})},async stop(n,a){try{const t=await d(await e(n.nodeId),"stop",{execution:n,options:a});return t.error===void 0?{confirmed:t.confirmed}:{confirmed:t.confirmed,error:new Error(t.error)}}catch(t){return{confirmed:!1,error:s(t)}}},async status(n){try{return await d(await e(n.nodeId),"status",{execution:n})}catch(a){return{state:"unknown",error:s(a).message}}},async delete(n){await d(await e(n),"delete",{nodeId:n})},async viewerAddress(n){return{kind:"machine",environmentId:await e(n.nodeId),nodeId:n.nodeId}}}}i(S,"createMachineRunner");export{S as createMachineRunner,y as machineEnvironmentOfNode};
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var
|
|
1
|
+
var re=Object.defineProperty;var i=(r,e)=>re(r,"name",{value:e,configurable:!0});import{WebSocketServer as te}from"ws";import{general as ne}from"../../core/errors.js";import{toErrorBody as ie}from"./map.js";import{isSafeNodeId as D,viewSocketPath as oe}from"../../core/canvas/paths.js";import{getNode as U}from"../../core/canvas/index.js";import{requestPersonId as ae,runAsPerson as ce}from"../../core/canvas/person-state.js";import{BROKER_READ_CAPS as se,CLIENT_READ_CAPS as fe,FrameDecoder as le,FrameOverflowError as ue}from"../../core/runtime/broker-protocol.js";import{emitEvent as A}from"../../core/events/emit.js";import{addStepTiming as de}from"../../core/step-timings.js";import{markAt as me,timedSpan as T,withLoggedStepTimings as he}from"../../core/logged-step-timings.js";import{classify as O}from"../../core/fault-classifier.js";import{clearFault as E,markNodeRead as pe,recordFault as V}from"../../core/canvas/recovery.js";import{decideAttachRevive as we}from"../../core/runtime/revive.js";import{connectViewSocket as ye,connectWssView as ke,probeViewSocket as ve,waitForBrokerViewSocket as ge,waitForWssView as L}from"../../core/runtime/view-socket.js";import{liveExecutionForNode as _e,recordExecutionAwake as be}from"../../core/canvas/executions.js";import{settleSandboxBeforeWake as Ae}from"../reconcilers/ledger-sandbox.js";import{runnerForExecution as Ee}from"../../core/runtime/runner/index.js";import{isBeneathRefusal as Se}from"../../core/spaces/open-beneath.js";import{openMachineView as xe,waitForMachineView as H}from"../machine-link/forward.js";import{attachViewer as J,detachViewer as Re,holdViewerForRedial as $e,presentViewer as Be}from"./viewer-presence.js";const j=3e4,Ce=new te({noServer:!0,maxPayload:se.maxLineBytes}),Te=25e3,Oe=6e4;function Ve(r,e=Te,a=Oe){let n=!0,c=!1,m=Date.now();const h=i(()=>{n=!0},"acknowledge"),u=i(()=>{c||(c=!0,clearInterval(v),r.off("pong",h))},"stop");r.on("pong",h);const v=setInterval(()=>{if(Date.now()-m>a){n=!0;return}if(!n){u(),r.terminate();return}n=!1;try{r.ping()}catch{u(),r.terminate()}},e);return v.unref(),{stop:u,noteActivity:i(()=>{m=Date.now()},"noteActivity")}}i(Ve,"startRemoteAttachHeartbeat");function N(r){const e=Buffer.from(r,"utf8");return e.byteLength<=123?r:e.subarray(0,123).toString("utf8")}i(N,"clampReason");function k(r,e,a,n,c){de("refused_status",e);const m=JSON.stringify({error:{code:n,message:c,origin:"runtime"}}),h=`HTTP/1.1 ${e} ${a}\r
|
|
2
2
|
content-type: application/json; charset=utf-8\r
|
|
3
|
-
content-length: ${Buffer.byteLength(
|
|
3
|
+
content-length: ${Buffer.byteLength(m)}\r
|
|
4
4
|
connection: close\r
|
|
5
5
|
\r
|
|
6
|
-
`+
|
|
6
|
+
`+m;try{r.end(h)}catch{try{r.destroy()}catch{}}}i(k,"refuseUpgrade");function q(r,e){const{status:a,body:n}=ie(e);k(r,a,"Refused",n.error.code,n.error.message)}i(q,"refuseWithError");function Ne(r){if(new URL(r.url??"/","http://127.0.0.1").searchParams.get("revive")==="0")return!0;const a=r.headers["x-crtr-attach-revive"];return(Array.isArray(a)?a[0]:a)==="0"}i(Ne,"reviveOptedOut");function Pe(r){return new URL(r.url??"/","http://127.0.0.1").searchParams.get("wakeParked")==="1"}i(Pe,"wakeParkedRequested");function K(r){return r===1e3||r===1001||r===1005}i(K,"isCleanViewerClose");function w(r,e,a){a.catch(n=>A({level:"error",event:e,node_id:r,error:n}))}i(w,"detach");async function Q(r){const e=await _e(r);return e===null||e.runner==="process"?{kind:"unix",path:oe(r)}:(e.runner==="blaxel"&&e.idleAt!==null&&(await Ae(e.executionId,Date.now()),await be(e.executionId)),Ee(e.runner).viewerAddress(e))}i(Q,"brokerViewAddress");function Fe(r,e){return e.kind==="machine"?xe(e.environmentId,r):e.kind==="wss"?ke(e.url,e.headers):ye(r)}i(Fe,"connectBrokerView");function Me(r,e,a){return e.kind==="wss"?L(e.url,e.headers,void 0,a):ve(r,a)}i(Me,"probeBrokerView");async function We(r,e,a,n,c){const m=[];let h=i(t=>{m.push(t)},"relayMessage");if(r.on("message",t=>h(t)),!D(e)){c?.destroy();try{r.close(1008,N(`invalid node id: ${e}`))}catch{}return}if(await U(e)===null){c?.destroy();try{r.close(1011,N(`no node ${e}`))}catch{}return}const u=performance.now();await E(e,{link:"viewer\u2194crtrd"});const v=performance.now(),o=c??Fe(e,a),f=i(()=>Math.round((performance.now()-v)*10)/10,"sinceOpen"),g=i(t=>{A({level:"info",event:"daemon.timing.bridge_channel",node_id:e,fields:{step:t,address_kind:a.kind,since_open_ms:f(),since_bridge_start_ms:Math.round((performance.now()-u)*10)/10}})},"bridgeMark");c===void 0&&g("channel_opened");const _=new le(fe);let y=!1,S=!1,x,P=!1,F=!1,$="controller",M=Promise.resolve(),R=!1;const B=[];let C=!1;const W=i(()=>{c===void 0&&g("channel_connected"),P=!0,!y&&R&&w(e,"daemon.bridge.presence_failed",J(e,r)),w(e,"daemon.bridge.connect_failed",E(e,{link:"relay\u2194broker"}))},"onBrokerConnect");c===void 0&&o.on("connect",W);const p=i((t,l,s=!1)=>{if(!y){if(y=!0,w(e,"daemon.bridge.presence_failed",s?$e(e,r):Re(e,r)),x?.stop(),!o.destroyed)try{o.destroy()}catch{}try{r.close(t,N(l))}catch{}}},"teardown");x=Ve(r);const z=i(async t=>{x?.noteActivity();let l;try{l=_.push(t)}catch(s){const d=s instanceof ue?`broker sent an oversized frame (${s.message})`:`failed to decode a broker frame for ${e}`;p(1009,d);return}B.push(...l),C||await G()},"onData"),G=i(async()=>{C=!0;try{for(;B.length>0&&!y;){const t=B.splice(0);let l;try{l=await n($)}catch(d){A({level:"error",event:"daemon.bridge.attach_recheck_failed",node_id:e,error:d}),p(1011,"revoked");return}if(y)return;if(!l){p(1008,"revoked");return}let s=!1;for(const d of t)r.readyState===r.OPEN&&(r.send(JSON.stringify(d)),d?.type==="welcome"&&(s=!0,g("welcome_forwarded")));if(R&&s)try{await Be(e,r)&&await pe(e)}catch(d){A({level:"warn",event:"daemon.bridge.present_failed",node_id:e,error:d})}}}finally{C=!1}},"drainOutbound");o.on("data",t=>w(e,"daemon.bridge.data_failed",z(t)));const X=i(async t=>{const l=t.code==="ECONNREFUSED"||t.code==="ENOENT"?`no running broker for ${e}`:`view socket error for ${e}: ${t.message}`;try{const s=O("relay\u2194broker",t);await V(e,{link:"relay\u2194broker",op:"bridge socket",kind:s.kind,retry:{disposition:"manual"},message:t.message})}finally{p(1011,l,!0)}},"onSocketError");o.on("error",t=>w(e,"daemon.bridge.socket_error_failed",X(t)));const Y=i(async t=>{if(!(y||t))try{await E(e,{link:"relay\u2194broker"})}finally{p(1e3,"broker socket closed",!0)}},"onSocketClose");o.on("close",t=>w(e,"daemon.bridge.socket_close_failed",Y(t)));const Z=i(async(t,l)=>{const s=l.toString("utf8");if(y){K(t)&&await E(e,{link:"viewer\u2194crtrd"});return}try{if(K(t))await E(e,{link:"viewer\u2194crtrd"});else if(!S){S=!0;const d=O("viewer\u2194crtrd",{code:t,reason:s});await V(e,{link:"viewer\u2194crtrd",op:"remote attach websocket",kind:d.kind,retry:{disposition:"auto"},message:s||`remote attach closed (${t})`})}}finally{p(t,s||`remote attach closed (${t})`)}},"onWsClose");r.on("close",(t,l)=>w(e,"daemon.bridge.ws_close_failed",Z(t,l)));const I=i(async()=>{try{if(!S){S=!0;const t=O("viewer\u2194crtrd",{code:1006,reason:"remote attach websocket error"});await V(e,{link:"viewer\u2194crtrd",op:"remote attach websocket",kind:t.kind,retry:{disposition:"auto"},message:"remote attach websocket error"})}}finally{p(1011,"remote attach websocket error")}},"onWsError");r.on("error",()=>w(e,"daemon.bridge.ws_error_failed",I())),h=i(t=>{if(y||o.destroyed)return;x?.noteActivity();const s=(Array.isArray(t)?Buffer.concat(t):Buffer.isBuffer(t)?t:Buffer.from(new Uint8Array(t))).toString("utf8");if(!F)try{const b=JSON.parse(s);b?.type==="hello"&&(g("hello_received"),F=!0,$=b.role==="observer"?"observer":"controller",R=b.attends!==!1,R&&P&&w(e,"daemon.bridge.presence_failed",J(e,r)))}catch{}const d=s.endsWith(`
|
|
7
7
|
`)?s:s+`
|
|
8
|
-
`,
|
|
8
|
+
`,ee=i(()=>{try{o.write(d)}catch{}},"write");M=M.then(async()=>{y||(await n($)?ee():p(1008,"revoked"))}).catch(b=>{A({level:"error",event:"daemon.bridge.attach_recheck_failed",node_id:e,error:b}),p(1011,"revoked")})},"relayMessage");for(const t of m.splice(0))h(t);c!==void 0&&(c.destroyed?p(1011,`no running broker for ${e}`,!0):W())}i(We,"bridgeConnection");async function cr(r,e,a,n,c){await he("attach_upgrade",{node:n},r,()=>De(r,e,a,n,c))}i(cr,"handleAttachUpgrade");async function De(r,e,a,n,c){const m=ae(),h=m===void 0?c:o=>ce(m,()=>c(o));e.on("error",()=>{});let u,v=!1;try{if(!D(n)){k(e,400,"Bad Request","invalid_node_id",`invalid node id: ${n}`);return}if(await T("admission",async()=>await U(n)===null)){k(e,404,"Not Found","node_not_found",`no node ${n}`);return}let o;if(Ne(r)){o=await Q(n);let f;if(o.kind==="machine"?(u=await H(o.environmentId,n,void 0,250)??void 0,f=u!==void 0):f=await Me(n,o,o.kind==="wss"?j:250),!f){k(e,409,"Conflict","node_dormant",`node ${n} is dormant and revive was opted out (?revive=0)`);return}}else{let f;try{const _=await T("revive_decision",async()=>await we(n,{resume:!0,capacity:"refuse"},Pe(r)));if(_.parked){k(e,409,"Conflict","node_dormant",`node ${n} is parked; attach with ?wakeParked=1 to wake it`);return}f=_.result.launch?.exited}catch(_){q(e,_);return}if(o=await T("address_lookup",async()=>await Q(n)),o.kind==="machine"&&(u=await H(o.environmentId,n,f,j)??void 0),!(o.kind==="machine"?u!==void 0:o.kind==="wss"?await L(o.url,o.headers,f):await ge(n,f))){o.kind==="machine"?q(e,ne(`the broker for ${n} on its machine did not accept a viewer after revive`)):k(e,409,"Conflict","broker_not_ready",`broker view socket for ${n} did not become listenable after revive`);return}}if(e.destroyed)return;me("upgrading"),Ce.handleUpgrade(r,e,a,f=>{v=!0,w(n,"daemon.bridge.connection_failed",We(f,n,o,h,u).catch(g=>{throw u?.destroy(),g}))})}catch(o){const f=o instanceof Error?o.message:String(o);if(Se(o)){k(e,400,"Bad Request","invalid_request",f);return}k(e,500,"Internal Server Error","internal",`attach upgrade failed: ${f}`)}finally{v||u?.destroy()}}i(De,"attachUpgrade");export{Te as REMOTE_ATTACH_HEARTBEAT_MS,Oe as REMOTE_ATTACH_QUIET_MS,cr as handleAttachUpgrade,K as isCleanViewerClose,k as refuseUpgrade,Ve as startRemoteAttachHeartbeat};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var p=Object.defineProperty;var o=(e,t)=>p(e,"name",{value:t,configurable:!0});import{getNode as v}from"../../../core/canvas/canvas.js";import{decideAttachRevive as k}from"../../../core/runtime/revive.js";import{viewSocketPath as h}from"../../../core/canvas/paths.js";import{waitForBrokerViewSocket as y}from"../../../core/runtime/placement-tmux.js";import{liveExecutionForNode as b}from"../../../core/canvas/executions.js";import{runnerForExecution as P}from"../../../core/runtime/runner/index.js";import{markAt as g,timedSpan as u,withLoggedStepTimings as A}from"../../../core/logged-step-timings.js";import{notFound as S,usage as i}from"../../../core/errors.js";import{mayOnNode as d,ownerOnly as _}from"../router.js";function N(e){if(e==null)return{resume:!0,revive:!0,wakeParked:!0};if(typeof e!="object")throw i("attach body must be a JSON object { resume?, revive?, wakeParked? }");const t=e.resume,r=e.revive,a=e.wakeParked;if(t!==void 0&&typeof t!="boolean")throw i("resume must be a boolean");if(r!==void 0&&typeof r!="boolean")throw i("revive must be a boolean");if(a!==void 0&&typeof a!="boolean")throw i("wakeParked must be a boolean");return{resume:t??!0,revive:r??!0,wakeParked:a??!0}}o(N,"parseAttachBody");async function F(e,t,r){return t==="controller"?await d(e,"message",r):await d(e,"read",r)?!0:t==="either"&&await d(e,"message",r)}o(F,"mayAttachNode");async function O(e){return await A("attach_post",{node:e.params.id},e.req,async()=>{const t=await E(e);return g("response_ready"),t})}o(O,"handleAttach");async function E(e){const t=e.params.id;if(await u("admission",async()=>await v(t)===null||!await F(e.principal,"either",t)))throw S(`unknown node: ${t}`,{received:t});const{resume:r,revive:a,wakeParked:l}=N(e.body);let m=!1,c=!1,f=!1;if(a){const n=await u("revive_decision",async()=>await k(t,{resume:r,capacity:"refuse"},l));if(f=n.parked,!n.parked){m=n.result.launch!==void 0,c=n.result.resumed;const s=await u("address_lookup",async()=>await b(t)),w=s===null?null:await P(s.runner).viewerAddress(s);(w===null||w.kind==="unix")&&await y(t)}}return{status:200,body:{node_id:t,socket_path:h(t),revived:m,resumed:c,parked:f}}}o(E,"attachEnsure");const C=_([{method:"POST",pattern:"/v1/nodes/:id/attach",handler:O}]);export{C as attachRoutes,F as mayAttachNode};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var x=Object.defineProperty;var s=(e,r)=>x(e,"name",{value:r,configurable:!0});import{chmodSync as j,closeSync as O,existsSync as D,mkdirSync as g,openSync as C,unlinkSync as F,writeFileSync as H,rmSync as M}from"node:fs";import{createServer as U}from"node:http";import{dirname as E,join as I}from"node:path";import{spawn as Y}from"node:child_process";import{SELF_UPDATE_SCRIPT as T}from"../core/self-update.js";import{apiSocketPath as A,crtrHome as B}from"../core/canvas/paths.js";import{bindDaemonEventSource as G}from"../core/events/source.js";import{emitEvent as l}from"../core/events/emit.js";import{createMachineExecutor as N,stopAllBrokers as $}from"../core/runtime/runner/machine/executor.js";import{machineCheckoutHandlers as J}from"../core/checkout-identities.js";import{machineWorktreeHandlers as X}from"../core/worktree-machine.js";import{readPersonCredential as z}from"../core/directory/person-credential.js";import{socketDir as L}from"../core/layout.js";import{isDaemonRunning as W,pidfilePath as v,readPidfile as K}from"./pidfile.js";import{cancelMachineCron as Q,runMachineCron as V,stopOrphanedMachineCrons as Z}from"./cron/machine-exec.js";import{startMachineLink as q}from"./machine-link/client.js";import{deleteMoveRecord as b,readMachineConfig as ee,readMachineCredential as R,readMoveRecord as ne,writeMoveRecord as te}from"./machine-link/config.js";import{jobExitReporting as re,stopMachineJob as oe}from"./machine-link/job-sweep.js";import{notifyMoveFinished as ie}from"./machine-link/move-notify.js";const ae=10*6e4;let k=0;function se(e){if(Date.now()-k<ae||!/^\d+\.\d+\.\d+$/.test(e))return;k=Date.now(),l({level:"warn",event:"daemon.machine.updating",fields:{release:e}});const r=I(E(T),"..","bin","crtr"),o=C(I(B(),"crtrd.err"),"a");Y("/bin/sh",["-c",'"$0" "$1" --version "$2" && "$0" "$3" sys daemon restart',process.execPath,T,e,r],{detached:!0,stdio:["ignore",o,o]}).unref(),O(o)}s(se,"updateToRelease");const P=1024;function ce(e,r){return{ok:!0,daemon_up:!0,store_accessible:!1,brokers_reconciled:!1,link_connected:e,signed_in:r,startup_phase:e?"ready":"recovering"}}s(ce,"machineHealth");async function Oe(){const e=ee();if(e===void 0)throw new Error("crtrd --role machine needs runtime/machine.json: this install has not been imported as a machine");const r=z()!==void 0;if(r&&R(),W())throw new Error("a crtrd is already running for this home");G(),r||(await $(),await Z(),l({level:"info",event:"daemon.machine.signed_out",fields:{environment:e.environmentId}})),g(L(),{recursive:!0,mode:493});const o=A();D(o)&&F(o);let n;const m=re(()=>n),i=U((t,a)=>{const u=(t.url??"").split("?")[0];if(t.method==="POST"&&(u==="/job-exit"||u==="/job-activity")){const _=[];let h=0;t.on("data",d=>{h+=d.length,h<=P&&_.push(d)}),t.on("end",()=>{if(h>P){a.writeHead(413),a.end();return}let d={};try{d=JSON.parse(Buffer.concat(_).toString("utf8"))}catch{}const S=typeof d.node=="string"&&typeof d.job=="string";a.writeHead(S?202:400,{"content-type":"application/json; charset=utf-8"}),a.end("{}"),S&&(u==="/job-exit"?m.notice:m.activity)(d.node,d.job)});return}const w=(t.method??"GET")==="GET"&&(t.url??"/").split("?")[0]==="/healthz";a.writeHead(w?200:404,{"content-type":"application/json; charset=utf-8"}),a.end(JSON.stringify(w?ce(n?.connected()===!0,r):{error:{code:"not_found",message:"a machine-role crtrd serves only /healthz",origin:"runtime"}}))});await new Promise((t,a)=>{i.once("error",a),i.listen(o,()=>{i.off("error",a),j(o,384),t()})}),g(E(v()),{recursive:!0}),H(v(),String(process.pid),"utf8");let f;await fe(e.runId,r,()=>f!==void 0);const c=N({apiUrl:e.apiUrl,environmentId:e.environmentId,onExit:s(t=>n?.reportExit(t),"onExit")});n=r?q({apiUrl:e.apiUrl,environmentId:e.environmentId,credential:R,onOpen:m.onOpen,onBehind:se,handlers:{start:c.start,wake:c.wake,stop:c.stop,status:c.status,"status.all":c["status.all"],delete:c.delete,viewer:c.viewer,"cron.run":V,"cron.cancel":Q,"job.stop":s(t=>oe(t),"job.stop"),...X,...J}}):void 0,l({level:"info",event:"daemon.machine.started",fields:{environment:e.environmentId}});const y=s(()=>f??=(async()=>{n?.stop(),await new Promise(t=>{i.close(()=>t()),i.closeAllConnections()}),K()===process.pid&&(M(o,{force:!0}),M(v(),{force:!0})),process.off("SIGINT",p),process.off("SIGTERM",p)})(),"teardown"),p=s(()=>{y().then(()=>process.exit(0),()=>process.exit(1))},"onSignal");return process.on("SIGINT",p),process.on("SIGTERM",p),y}s(Oe,"runMachineDaemon");const de=5e3,me=3e5;async function fe(e,r,o){let n;try{n=ne()}catch(i){l({level:"warn",event:"daemon.machine.move_record_unreadable",fields:{error:i.message}});return}if(n===void 0||n.state==="running"||n.runId!==e)return;if(n.notified||n.notify===null){b();return}if(n.state==="committed"&&(n={...n,state:"activated"},te(n)),!r)return;const m=n;(async()=>{let i=de;for(;;){try{await ie(m),b();return}catch(f){l({level:"warn",event:"daemon.machine.move_notify_failed",fields:{node:m.notify??"",error:f.message}})}if(await new Promise(f=>{setTimeout(f,i).unref()}),o())return;i=Math.min(i*2,me)}})()}s(fe,"settleFinishedMove");export{ce as machineHealth,Oe as runMachineDaemon};
|
|
@@ -30,6 +30,8 @@ export interface MachineLinkOptions {
|
|
|
30
30
|
jobReportTimeoutMs?: number;
|
|
31
31
|
/** Called each time the link opens, including the first: the caller's recovery pass for what happened while it was closed. */
|
|
32
32
|
onOpen?: () => void;
|
|
33
|
+
/** Called when the control plane refuses the link (426) because this Mac is on an older release; the argument is the control plane's release. */
|
|
34
|
+
onBehind?: (release: string) => void;
|
|
33
35
|
}
|
|
34
36
|
export interface MachineLink {
|
|
35
37
|
stop(): void;
|
|
@@ -55,15 +57,19 @@ export interface ViewSource {
|
|
|
55
57
|
pause(): void;
|
|
56
58
|
resume(): void;
|
|
57
59
|
}
|
|
58
|
-
/** Viewer frames,
|
|
59
|
-
*
|
|
60
|
-
*
|
|
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. */
|
|
61
66
|
export declare function createViewQueue(sink: ViewSink): {
|
|
62
|
-
push(data: string, source?: ViewSource): void;
|
|
67
|
+
push(data: string, source?: ViewSource, channel?: string): void;
|
|
63
68
|
waiting(): {
|
|
64
69
|
bytes: number;
|
|
65
70
|
frames: number;
|
|
66
71
|
};
|
|
72
|
+
drop(channel: string): void;
|
|
67
73
|
forget(source: ViewSource): void;
|
|
68
74
|
};
|
|
69
75
|
export declare function linkUrl(apiUrl: string, environmentId: string): string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var j=Object.defineProperty;var
|
|
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};
|