@north-light/cli 0.3.696 → 0.3.698

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};
@@ -1 +1 @@
1
- var p=Object.defineProperty;var l=(n,t)=>p(n,"name",{value:t,configurable:!0});import{ModelRegistry as h}from"@earendil-works/pi-coding-agent";import{boundaryRootedTree as f}from"../session-visibility.js";import{isUnknownModel as M}from"../model-selection.js";import{BUILTIN_SLASH_COMMANDS as b}from"../pi-vendored.js";import{isDeterministicCommandExpansion as y}from"../command-expansion.js";import{registrationChatSurface as S,templateChatSurface as k}from"../command-surface.js";function m(n){return new h(n.modelRuntime)}l(m,"registryOf");const u=l(n=>n===void 0||M(n)?null:{provider:n.provider,id:n.id},"toModelRef"),T=l(n=>`${n.provider}/${n.id}`,"modelKey");function E(n){const t=[];for(const e of b)t.push({name:e.name,description:e.description,source:"builtin",gatewayCapable:!1});try{for(const e of n.extensionRunner.getRegisteredCommands()){const o=e.expansion;t.push({name:e.invocationName,description:e.description??"",source:"command",...y(o)?{expansion:o}:{},...S(e)})}}catch{}try{for(const e of n.promptTemplates)t.push({name:e.name,description:e.description,source:"template",template:e.content,...k(e)})}catch{}return t}l(E,"buildCommandList");function A(n,t,e){return{type:"data",id:n,kind:"list_memory_refs",refs:t,engineLeadingCommandNames:e}}l(A,"buildListMemoryRefsData");function R(n,t){const e=m(t);let o=[];try{o=e.getAvailable().map(T)}catch{}return{type:"data",id:n,kind:"list_models",models:e.getAll(),current:u(t.model),availableIds:o,scopedModels:t.scopedModels.map(a=>({model:a.model,thinkingLevel:a.thinkingLevel})),enabledModelIds:t.settingsManager.getEnabledModels()??null}}l(R,"buildListModelsData");function P(n,t){return{type:"data",id:n,kind:"list_scoped_models",allModels:m(t).getAll(),enabledModelIds:t.settingsManager.getEnabledModels()??null}}l(P,"buildScopedModelsData");function F(n,t,e){const o=t.sessionManager,a=e!==void 0?f(o.getTree(),e):o.getTree(),r=new Set,s=l(d=>{for(const c of d)r.add(c.entry.id),s(c.children)},"collectEntryIds");s(a);const g=t.getUserMessagesForForking().filter(d=>r.has(d.entryId)).map(d=>({id:d.entryId,text:d.text,timestamp:o.getEntry(d.entryId)?.timestamp})),i=o.getLeafId();return{type:"data",id:n,kind:"get_tree",tree:a,currentLeafId:i!==null&&r.has(i)?i:null,forkPoints:g}}l(F,"buildGetTreeData");function _(n,t){const e=t.settingsManager;let o=[];try{o=t.resourceLoader.getThemes().themes.map(i=>i.name??"").filter(i=>i!=="")}catch{}const a=e.getDefaultProvider(),r=e.getDefaultModel();let s=[];try{s=t.modelRuntime.getAvailableSnapshot()}catch{}const g={autoCompact:t.autoCompactionEnabled,defaultModel:a&&r?`${a}/${r}`:"not set",availableDefaultModels:s,showImages:e.getShowImages(),imageWidthCells:e.getImageWidthCells(),autoResizeImages:e.getImageAutoResize(),blockImages:e.getBlockImages(),enableSkillCommands:e.getEnableSkillCommands(),steeringMode:t.steeringMode,followUpMode:t.followUpMode,transport:e.getTransport(),httpIdleTimeoutMs:e.getHttpIdleTimeoutMs(),thinkingLevel:t.thinkingLevel,availableThinkingLevels:t.getAvailableThinkingLevels(),modelThinkingLevels:e.getAllModelThinkingLevels(),currentTheme:e.getTheme()??"",terminalTheme:"dark",availableThemes:o,hideThinkingBlock:e.getHideThinkingBlock(),mermaidRenderingMode:e.getMermaidRenderingMode(),collapseChangelog:e.getCollapseChangelog(),enableInstallTelemetry:e.getEnableInstallTelemetry(),doubleEscapeAction:e.getDoubleEscapeAction(),treeFilterMode:e.getTreeFilterMode(),showHardwareCursor:e.getShowHardwareCursor(),editorPaddingX:e.getEditorPaddingX(),autocompleteMaxVisible:e.getAutocompleteMaxVisible(),quietStartup:e.getQuietStartup(),clearOnShrink:e.getClearOnShrink(),showTerminalProgress:e.getShowTerminalProgress(),tuiMode:e.getTuiMode(),fullscreenExitOutput:e.getFullscreenExitOutput(),fullscreenScrollbar:e.getFullscreenScrollbar(),fullscreenCopyOnSelect:e.getFullscreenCopyOnSelect(),fullscreenWheelScrollLines:e.getFullscreenWheelScrollLines(),warnings:e.getWarnings(),defaultProjectTrust:e.getDefaultProjectTrust(),showCacheMissNotices:e.getShowCacheMissNotices(),cacheWarmingMode:e.getCacheWarmingMode(),outputPad:e.getOutputPad(),sessionShareDestination:e.getSessionShareDestination(),autoRetry:t.autoRetryEnabled,model:u(t.model)};return{type:"data",id:n,kind:"get_settings",settings:g}}l(_,"buildSettingsData");function O(n,t,e,o){const a=e.sessionManager;return(t==="all"?o.listAll():o.listDir(a.getCwd())).then(r=>({type:"data",id:n,kind:"list_sessions",scope:t,sessions:r,currentSessionFile:e.sessionFile}))}l(O,"buildSessionsData");export{E as buildCommandList,F as buildGetTreeData,A as buildListMemoryRefsData,R as buildListModelsData,P as buildScopedModelsData,O as buildSessionsData,_ as buildSettingsData,T as modelKey};
1
+ var M=Object.defineProperty;var a=(n,t)=>M(n,"name",{value:t,configurable:!0});import{ModelRegistry as b}from"@earendil-works/pi-coding-agent";import{boundaryRootedTree as y}from"../session-visibility.js";import{isUnknownModel as S}from"../model-selection.js";import{BUILTIN_SLASH_COMMANDS as T}from"../pi-vendored.js";import{isDeterministicCommandExpansion as k}from"../command-expansion.js";import{registrationChatSurface as C,templateChatSurface as I}from"../command-surface.js";function p(n){return new b(n.modelRuntime)}a(p,"registryOf");const h=a(n=>n===void 0||S(n)?null:{provider:n.provider,id:n.id},"toModelRef"),v=a(n=>`${n.provider}/${n.id}`,"modelKey");function P(n){const t=[];for(const e of T)t.push({name:e.name,description:e.description,source:"builtin",gatewayCapable:!1});try{for(const e of n.extensionRunner.getRegisteredCommands()){const l=e.expansion;t.push({name:e.invocationName,description:e.description??"",source:"command",...k(l)?{expansion:l}:{},...C(e)})}}catch{}try{for(const e of n.promptTemplates)t.push({name:e.name,description:e.description,source:"template",template:e.content,...I(e)})}catch{}return t}a(P,"buildCommandList");function F(n,t,e){return{type:"data",id:n,kind:"list_memory_refs",refs:t,engineLeadingCommandNames:e}}a(F,"buildListMemoryRefsData");function O(n,t){const e=p(t);let l=[];try{l=e.getAvailable().map(v)}catch{}return{type:"data",id:n,kind:"list_models",models:e.getAll(),current:h(t.model),availableIds:l,scopedModels:t.scopedModels.map(o=>({model:o.model,thinkingLevel:o.thinkingLevel})),enabledModelIds:t.settingsManager.getEnabledModels()??null}}a(O,"buildListModelsData");function _(n,t){return{type:"data",id:n,kind:"list_scoped_models",allModels:p(t).getAll(),enabledModelIds:t.settingsManager.getEnabledModels()??null}}a(_,"buildScopedModelsData");function W(n,t,e){const l=t.sessionManager,o=e!==void 0?y(l.getTree(),e):l.getTree(),r=new Set,s=a(i=>i.map(c=>{r.add(c.entry.id);const{entry:g}=c,f=g.type==="message"&&g.message.role==="toolResult"?{...g,message:{...g.message,content:[],details:void 0}}:g;return{...c,entry:f,children:s(c.children)}}),"withoutToolOutput"),u=s(o),d=t.getUserMessagesForForking().filter(i=>r.has(i.entryId)).map(i=>({id:i.entryId,text:i.text,timestamp:l.getEntry(i.entryId)?.timestamp})),m=l.getLeafId();return{type:"data",id:n,kind:"get_tree",tree:u,currentLeafId:m!==null&&r.has(m)?m:null,forkPoints:d}}a(W,"buildGetTreeData");function H(n,t){const e=t.settingsManager;let l=[];try{l=t.resourceLoader.getThemes().themes.map(d=>d.name??"").filter(d=>d!=="")}catch{}const o=e.getDefaultProvider(),r=e.getDefaultModel();let s=[];try{s=t.modelRuntime.getAvailableSnapshot()}catch{}const u={autoCompact:t.autoCompactionEnabled,defaultModel:o&&r?`${o}/${r}`:"not set",availableDefaultModels:s,showImages:e.getShowImages(),imageWidthCells:e.getImageWidthCells(),autoResizeImages:e.getImageAutoResize(),blockImages:e.getBlockImages(),enableSkillCommands:e.getEnableSkillCommands(),steeringMode:t.steeringMode,followUpMode:t.followUpMode,transport:e.getTransport(),httpIdleTimeoutMs:e.getHttpIdleTimeoutMs(),thinkingLevel:t.thinkingLevel,availableThinkingLevels:t.getAvailableThinkingLevels(),modelThinkingLevels:e.getAllModelThinkingLevels(),currentTheme:e.getTheme()??"",terminalTheme:"dark",availableThemes:l,hideThinkingBlock:e.getHideThinkingBlock(),mermaidRenderingMode:e.getMermaidRenderingMode(),collapseChangelog:e.getCollapseChangelog(),enableInstallTelemetry:e.getEnableInstallTelemetry(),doubleEscapeAction:e.getDoubleEscapeAction(),treeFilterMode:e.getTreeFilterMode(),showHardwareCursor:e.getShowHardwareCursor(),editorPaddingX:e.getEditorPaddingX(),autocompleteMaxVisible:e.getAutocompleteMaxVisible(),quietStartup:e.getQuietStartup(),clearOnShrink:e.getClearOnShrink(),showTerminalProgress:e.getShowTerminalProgress(),tuiMode:e.getTuiMode(),fullscreenExitOutput:e.getFullscreenExitOutput(),fullscreenScrollbar:e.getFullscreenScrollbar(),fullscreenCopyOnSelect:e.getFullscreenCopyOnSelect(),fullscreenWheelScrollLines:e.getFullscreenWheelScrollLines(),warnings:e.getWarnings(),defaultProjectTrust:e.getDefaultProjectTrust(),showCacheMissNotices:e.getShowCacheMissNotices(),cacheWarmingMode:e.getCacheWarmingMode(),outputPad:e.getOutputPad(),sessionShareDestination:e.getSessionShareDestination(),autoRetry:t.autoRetryEnabled,model:h(t.model)};return{type:"data",id:n,kind:"get_settings",settings:u}}a(H,"buildSettingsData");function N(n,t,e,l){const o=e.sessionManager;return(t==="all"?l.listAll():l.listDir(o.getCwd())).then(r=>({type:"data",id:n,kind:"list_sessions",scope:t,sessions:r,currentSessionFile:e.sessionFile}))}a(N,"buildSessionsData");export{P as buildCommandList,W as buildGetTreeData,F as buildListMemoryRefsData,O as buildListModelsData,_ as buildScopedModelsData,N as buildSessionsData,H as buildSettingsData,v as modelKey};
@@ -1,3 +1,3 @@
1
- var Fe=Object.defineProperty;var l=(e,t)=>Fe(e,"name",{value:t,configurable:!0});import{ApiError as y}from"../../../api/errors.js";import{PRIVACY_LEVELS_DTO as Ae}from"../../../api/dto/objects.js";import{openDb as N,withCanvasWrite as v}from"../../../core/canvas/db.js";import{actorOf as ae}from"../../../core/graph/documents.js";import{readerForObject as C,readerFor as We}from"../../../core/graph/reader.js";import{resolveName as Le,stubsNamed as Pe,unwrapRef as ie}from"../../../core/graph/names.js";import{canRead as D,holdsObjectsScope as Ce,spaceOf as De}from"../../../core/graph/access.js";import{customReachable as Me,mayActAs as re}from"../../../core/graph/custom.js";import{customObjectRef as oe,authorizeCustom as se,fenceArgv as J}from"./custom-objects.js";import{edgesOf as Ge}from"../../../core/graph/edges.js";import{publish as B}from"../../../core/graph/events.js";import{objectDTO as Ue}from"../../../core/graph/kinds/dto.js";import{isKind as He,kindNames as ze,kindOf as K}from"../../../core/graph/kinds/registry.js";import{listObjects as Ve,searchObjects as ue}from"../../../core/graph/objects.js";import{checkoutsForCwd as Je}from"../../../core/graph/repo-sync/repos.js";import{recordWatch as M,unwatch as Be,watchersOf as Ke,watchesOf as Ze}from"../../../core/graph/watches.js";import{armObjectWaitForWatch as G,settleObjectWaitForUnwatch as Qe}from"../../../core/graph/object-waits.js";import{readerFor as T,resolveRef as Z,warmReaderRepos as R}from"../reader.js";import{readDelegationFor as ce,runReadLeaf as Ye}from"../../plugin-objects/read-leaf.js";import{invalidRequest as U,isRecord as q}from"./validate.js";import{callerNode as le,callerStub as Q,forwardNamed as Xe,forwardVerb as fe,originates as de,queryWithoutMachine as H,relayError as z,remoteStub as xe,unknownError as we,forwarding as P,withMachine as Y}from"../../peer/forward.js";import{getById as I}from"../../../core/graph/objects.js";import{ensureNodeStub as et,isStub as X,stubOf as tt,withKindDecl as $}from"../../../core/peer/stubs.js";import{isUnreachable as nt}from"../../../core/peer/client.js";import{normalizeMachineId as F}from"../../../core/peer/directory.js";import{mapAsync as at}from"../../../core/async-array.js";const A=l(async e=>async(t,n)=>await Je(e,t,n),"reposFnFor");async function g(e,t){return{...await Ue(e,t),...t.type==="document"?{schema_type:t.schema_type??null}:{}}}l(g,"objectDTO");async function it(e,t){const n=t.filter(r=>r.type==="document").map(r=>r.id),a=new Map;if(n.length===0)return a;const i=await e.prepareUncached(`SELECT object, extensions_json FROM documents WHERE object IN (${n.map(()=>"?").join(", ")})`).all(...n);for(const r of i)r.extensions_json!==null&&a.set(r.object,JSON.parse(r.extensions_json));return a}l(it,"extensionsOf");async function me(e,t){const n=await it(e,t);return await at(t,async a=>({...await g(e,a),...await(await K(e,a.type)).listItem?.(e,a),...a.type==="document"?{extensions:n.get(a.id)??{}}:{}}))}l(me,"listItems");function rt(e){return`no object named ${e} on this runtime; it may be on another runtime, or the name may be misspelled`}l(rt,"remoteMessage");async function pe(e,t,n){try{return await S(e,t,n)}catch(a){if(a instanceof y&&a.code==="not_found"&&!a.details?.deleted)return null;throw a}}l(pe,"ownerFilter");async function S(e,t,n){const a=await Z(e,t,n);if("remote"in a)throw new y(404,"not_found",rt(a.remote),{next:"Check the name with `crtr canvas search`."});if("deleted"in a)throw new y(404,"not_found",`${a.deleted.name} is deleted`,{id:a.deleted.id,deleted:!0});return a}l(S,"liveRef");const O=l(e=>decodeURIComponent(e.params.ref),"refParam"),he=l(e=>{const t=ie(e),n=t.indexOf("/");return n>0?t.slice(0,n):t},"idOf");async function ye(e){const t=await I(await N(),he(e));return t!==null&&await X(await N(),t)?t.id:null}l(ye,"stubIdOf");async function ot(e,t){const n=await ye(e);return n!==null?{stub:n,hit:!0}:(await R(t.principal),await v(async a=>{try{const i=await T(a,t),r=l(async()=>{const s=await Pe(a,i,e);if(s.length>1)throw new y(409,"ambiguous_name",`'${e}' names more than one remote object`,{candidates:s.map(c=>c.id),next:"Read one by its object id."});return{stub:s[0]?.id??null,hit:!1}},"named");let o;try{o=await Z(a,i,e)}catch(s){if(s instanceof y&&s.code==="not_found")return await r();throw s}if("remote"in o)return await r();if("deleted"in o){const s=await r();return s.stub===null?{stub:null,hit:!0}:s}return{stub:await X(a,o)?o.id:null,hit:!0}}catch(i){if(i instanceof y&&i.code==="ambiguous_name")throw i;return{stub:null,hit:!1}}}))}l(ot,"resolvedLocally");async function x(e,t,n){const a=await ot(t,e);if(a.stub!==null)return fe(e,a.stub,n);if(a.hit||!de(e.principal))return{kind:"local"};const i=await fe(e,he(t),n);return i.kind==="local"&&ie(t).includes("/")?Xe(e,n,{method:"GET",path:V(t),query:H(e)}):i}l(x,"forwardRef");const V=l(e=>`/v1/objects/${encodeURIComponent(e)}`,"objectPath");async function be(e,t,n,a,i){const r=t?.object;!r?.id||!r.type||await v(async o=>{const s=await le(o,e);if(s===null)return;const c=await xe(o,r.id,r.type,n,{kind:r.kind??null,name:r.name??r.id,...r.preview===void 0?{}:{preview:r.preview},owner:r.owner??null,...r.kind_decl===void 0?{}:{kind_decl:r.kind_decl},...r.privacy===void 0?{}:{privacy:r.privacy}});await M(o,s,c,a,i===void 0?{}:{patterns:i}),a==="ask"&&await G(o,s,c)})}l(be,"watchRemote");async function st(e){const t=O(e),n=["1","true"].includes(e.query.get("fields")??""),a=await x(e,t,{method:"GET",path:V(t),query:H(e)});if(a.kind==="unknown")return{state:"unknown",ref:t,unreachable:a.unreachable};if(a.kind==="remote"){if(a.status>=400)throw z(a.status,a.body);return await be(e,a.body,a.machine.id,"read"),Y(a.body,a.machine)}const i=l(async s=>{const c=await Q(s,e);return c===null?await T(s,e):await C(s,c,await A(s))},"readerOf");await R(e.principal);const r=await v(async s=>{const c=await i(s),u=await Z(s,c,t);if("remote"in u)return{state:"remote",remote:u.remote};if("deleted"in u)return{state:"deleted",deleted:await g(s,u.deleted)};const f=await ce(s,u);if(f!==null)return{delegate:f,hitId:u.id};const{data:w,text:b}=await(await K(s,u.type)).read(s,c,u,{fields:n,reposFn:await A(s)});return{state:"object",type:u.type,object:await $(s,u,await g(s,u)),text:b,data:w}});if(!("delegate"in r))return r;const o=await Ye(r.delegate,e.principal);return await R(e.principal),await v(async s=>{const c=await i(s),u=await I(s,r.hitId);if(u===null)throw new y(404,"not_found","object not found");if(u.deleted_at!==null)return{state:"deleted",deleted:await g(s,u)};if(!await D(s,c,u))throw new y(404,"not_found","object not found");const{data:f,text:w}=await(await K(s,u.type)).read(s,c,u,{fields:n,reposFn:await A(s)});return await ce(s,u)===null?{state:"object",type:u.type,object:await $(s,u,await g(s,u)),text:w,data:f}:{state:"object",type:u.type,object:await $(s,u,await g(s,u)),text:"markdown"in o?o.markdown:`${w}
2
- content unavailable: ${o.unavailable}`,data:{...f,content:"markdown"in o?"live":"unavailable"}}})}l(st,"read");function ee(e,t,n,a){if(e!=null){if(!n.includes(e)){a.push({field:t,problem:`must be one of ${n.join(", ")}`,received:e});return}return e}}l(ee,"oneOf");async function ge(e,t,n){if(t!=null){if(typeof t!="string"||!await He(e,t)){n.push({field:"type",problem:`must be a kind: one of ${(await ze(e)).join(", ")}`,received:t});return}return t}}l(ge,"kindName");function je(e,t,n,a){if(e==null)return a;const i=Number(e);return!Number.isInteger(i)||i<1||i>100?(n.push({field:t,problem:"must be an integer from 1 to 100",received:e}),a):i}l(je,"limitOf");function _e(e,t){if(e==null)return;let n=e;if(typeof e=="string")try{n=JSON.parse(e)}catch{n=null}if(!q(n)||Object.values(n).some(a=>!q(a))){t.push({field:"extensions",problem:'must be an object of objects, e.g. {"firstlight":{"state":"active"}}',received:e});return}return n}l(_e,"extensionsParam");function ke(e,t){if(e!=null){if(typeof e!="string"||e===""){t.push({field:"schema_type",problem:"must be a non-empty string",received:e});return}return e}}l(ke,"schemaTypeParam");async function ve(e){const t=e.query,n=[],a=await ge(await N(),t.get("type"),n),i=ee(t.get("privacy"),"privacy",Ae,n),r=je(t.get("limit"),"limit",n,50),o=t.get("cursor");o!==null&&!/^\d+$/.test(o)&&n.push({field:"cursor",problem:"is not a cursor from a previous page",received:o});const s=t.get("deleted");s!==null&&!["0","1","true","false"].includes(s)&&n.push({field:"deleted",problem:"must be true or false",received:s});const c=t.get("shared");c!==null&&!["0","1","true","false"].includes(c)&&n.push({field:"shared",problem:"must be true or false",received:c});const u=_e(t.get("extensions"),n),f=ke(t.get("schema_type"),n);return n.length>0&&U("object list request",n),await R(e.principal),await v(async w=>{const b=await T(w,e),j={...a?{type:a}:{},...i?{privacy:i}:{},...t.get("kind")!==null?{kind:t.get("kind")}:{},...s==="1"||s==="true"?{deleted:!0}:{},...c==="1"||c==="true"?{shared:!0}:{},...u?{extensions:u}:{},...f?{schemaType:f}:{},...t.get("name")!==null?{namePrefix:t.get("name")}:{}},k=t.get("owner");if(k!==null){const m=await pe(w,b,k);if(m===null)return{items:[],next_cursor:null};j.owner=m}const p=await Ve(w,b,j,{limit:r,after_seq:o===null?0:Number(o)}),d=p.at(-1);return{items:await me(w,p),next_cursor:p.length===r&&d?String(d.seq):null}})}l(ve,"listLocal");const ut={ms:3e4},ct="self",te=l((e,t)=>e.map(n=>({...n,machine:t})),"labelItems");async function Oe(e,t,n,a){const i=P.current;try{const r=await i.call(t.id,{method:"GET",path:"/v1/objects",query:n},await i.envelope(e.principal),a);if(nt(r))return{state:"unreachable",items:[],next:null};if(r.status===426)return{state:"too_old",items:[],next:null};const o=r.body;return r.status!==200||!Array.isArray(o?.items)?{state:"unreachable",items:[],next:null}:{state:"ok",items:te(o.items,t),next:o.next_cursor??null}}catch{return{state:"unreachable",items:[],next:null}}}l(Oe,"remotePage");async function lt(e){const t=new Promise(n=>e.addEventListener("abort",()=>n(null),{once:!0}));return Promise.race([P.current.machines().catch(()=>null),t])}l(lt,"machinesWithin");async function ft(e){const t=e.query.get("machine");if(!de(e.principal)||!P.current.joined()||t===ct)return await ve(Ee(e));const a=P.current.self(),i=t!==null&&F(t)!==a,r=i?null:await ve(Ee(e)),o=new AbortController,s=setTimeout(()=>o.abort(),ut.ms);s.unref?.();try{const c=await lt(o.signal);if(c===null){if(i)throw new y(503,"runtime_unreachable",`The directory did not answer, so ${F(t)} cannot be listed.`,{machine:F(t)});return r}const u=l(d=>({id:d,name:c.find(m=>m.machine_id===d)?.name??d}),"labelOf"),f=u(a),w=c.filter(d=>d.machine_id!==a&&d.kind!=="device"),b=H(e);if(t!==null){if(!i)return{items:te(r.items,f),next_cursor:r.next_cursor,machines:[{machine_id:a,name:f.name,state:"ok",more:r.next_cursor!==null}]};const d=F(t);if(!w.some(L=>L.machine_id===d))throw new y(404,"not_found",`no machine ${d} on your account`,{machine:d});const m=await Oe(e,u(d),b,o.signal);return{items:m.items,next_cursor:m.next,machines:[{machine_id:d,name:u(d).name,state:m.state,more:m.next!==null}]}}const{cursor:j,...k}=b,p=await Promise.all(w.map(d=>Oe(e,u(d.machine_id),k,o.signal)));return{items:[...te(r.items,f),...p.flatMap(d=>d.items)],next_cursor:r.next_cursor,machines:[{machine_id:a,name:f.name,state:"ok",more:r.next_cursor!==null},...w.map((d,m)=>({machine_id:d.machine_id,name:d.name,state:p[m].state,more:p[m].next!==null}))]}}finally{clearTimeout(s)}}l(ft,"list");function Ee(e){const t=new URLSearchParams(e.query);return t.delete("machine"),{...e,query:t}}l(Ee,"withoutMachine");async function dt(e){const t=[],n=q(e.body)?e.body:{};q(e.body)||t.push({field:"body",problem:"must be an object",received:e.body});const a=n.text;(typeof a!="string"||a.trim()==="")&&t.push({field:"text",problem:"is required",received:a});const i=n.grep;if(i!==void 0)if(typeof i!="string")t.push({field:"grep",problem:"must be a regular expression string",received:i});else try{new RegExp(i)}catch(h){t.push({field:"grep",problem:`is not a valid regular expression: ${h.message}`,received:i})}n.body!==void 0&&typeof n.body!="boolean"&&t.push({field:"body",problem:"must be a boolean",received:n.body});const r=await ge(await N(),n.type,t);n.kind!==void 0&&typeof n.kind!="string"&&t.push({field:"kind",problem:"must be a string",received:n.kind}),n.owner!==void 0&&typeof n.owner!="string"&&t.push({field:"owner",problem:"must be a string",received:n.owner});const o=je(n.limit,"limit",t,50),s=_e(n.extensions,t),c=ke(n.schema_type,t);t.length>0&&U("object search request",t),await R(e.principal);const u=await v(async h=>{const _=await T(h,e),$e=typeof n.owner=="string"?await pe(h,_,n.owner):null;return{reader:_,owner:$e}}),{reader:f,owner:w}=u;if(typeof n.owner=="string"&&w===null)return{items:[]};const b={...s?{extensions:s}:{},...c?{schemaType:c}:{},...r?{type:r}:{},...typeof n.kind=="string"?{kind:n.kind}:{},...w?{owner:w}:{}},j=await N(),k=await ue(j,f,{text:a,body:n.body===!0||typeof i=="string",...b}),p=new Set(k.map(h=>h.object.id)),m=(typeof i=="string"?(await ue(j,f,{text:i,grep:!0,...b})).filter(h=>p.has(h.object.id)):k).slice(0,o),L=await me(j,m.map(h=>h.object));return{items:m.map((h,_)=>({object:L[_],...h.line!==void 0?{matches:[{line:h.line,text:h.text??""}]}:{}}))}}l(dt,"search");const Te=["interrupt","steer","after-turn","next-turn"],wt=/^(\*|>|[A-Za-z0-9_-]+)(\.(\*|>|[A-Za-z0-9_-]+))*$/;function mt(e,t){if(e!==void 0){if(!Array.isArray(e)||e.length===0||e.some(n=>typeof n!="string"||!wt.test(n)||n.includes(">")&&!n.endsWith(">"))){t.push({field:"patterns",problem:"must be a non-empty list of event patterns (dot-separated words, `*` for one word, a final `>` for the rest)",received:e});return}return e}}l(mt,"patternsOf");function pt(e,t){if(e===void 0)return;if(!q(e)||Object.keys(e).length===0){t.push({field:"config",problem:"must map levels 1-10 to a delivery",received:e});return}const n=[];for(const[a,i]of Object.entries(e)){const r=Number(a);!Number.isInteger(r)||r<1||r>10?t.push({field:`config.${a}`,problem:"level must be an integer from 1 to 10"}):Te.includes(i)?n.push({threshold:r,delivery:i}):t.push({field:`config.${a}`,problem:`delivery must be one of ${Te.join(", ")}`,received:i})}return n.sort((a,i)=>i.threshold-a.threshold)}l(pt,"configOf");async function Re(e){const t=await ye(e);if(t!==null)throw new y(400,"invalid_request",`${t} lives on another machine; an explicit watcher cannot watch it from here`,{id:t})}l(Re,"refuseStubWatch");async function ne(e,t){const n=await I(e,t)??await(async()=>{const a=await Le(e,await We(e,{class:"person"},async()=>[]),t);return"object"in a?a.object:null})();return n===null||n.deleted_at!==null||!(n.type.includes(".")||n.type==="node")?null:n}l(ne,"findWatcher");const E=l(()=>{throw new y(404,"not_found","watcher not found")},"watcherNotFound");async function qe(e,t,n){if(typeof t!="string"||n===void 0||n===null)return null;if(typeof n!="string")throw new y(400,"invalid_request","invalid watcher_machine");if(await ne(e,t)!==null)return null;const a=P.current;let i;try{i=await a.machines()}catch{throw new y(503,"runtime_unreachable","The directory did not answer, so the watcher machine cannot be checked.")}const r=F(n);return(r===a.self()||!i.some(o=>F(o.machine_id)===r))&&E(),r}l(qe,"remoteWatcherMachine");async function Ne(e,t,n,a){if(t.publishToken||t.principal.class==="anonymous")return E();const i=await T(e,t);if(i.class==="person")return E();let r;try{r=await S(e,i,a)}catch{return E()}const o=r.owner===null?null:await I(e,r.owner);return o===null||!await re(e,i,o)||!await Ce(e,i,"link",n)||(await De(e,n)).id===i.app.id&&!(await D(e,i,n)&&await D(e,await C(e,n),r))?E():(await J(e,t,n),{actor:i.app,object:r})}l(Ne,"linkWatcher");async function Ie(e,t,n){if(t.publishToken)return!0;if(t.principal.class==="anonymous"||!n.type.includes("."))return!1;const a=await T(e,t),i=n.owner===null?null:await I(e,n.owner);return i!==null&&await re(e,a,i)&&await Me(e,a,n)}l(Ie,"ownsWatcher");async function ht(e){const t=O(e),n=q(e.body)?e.body:{};if(typeof n.watcher=="string"&&await Re(t),typeof n.watcher!="string"){const i=await x(e,t,{method:"POST",path:`${V(t)}/watch`,body:e.body});if(i.kind==="unknown")throw we(t,i.unreachable);if(i.kind==="remote"){if(i.status>=400)throw z(i.status,i.body);const r=i.body.patterns;return await be(e,i.body,i.machine.id,"ask",r),Y(i.body,i.machine)}}const a=await qe(await N(),n.watcher,n.watcher_machine);return await yt(e,a)}l(ht,"watch");async function yt(e,t=null){const n=[],a=e.body===void 0?{}:q(e.body)?e.body:(n.push({field:"body",problem:"must be an object"}),{}),i=mt(a.patterns,n),r=pt(a.config,n);return a.filter!==void 0&&!q(a.filter)&&n.push({field:"filter",problem:"must be an object",received:a.filter}),a.watcher!==void 0&&typeof a.watcher!="string"&&n.push({field:"watcher",problem:"must be a custom-object ref",received:a.watcher}),a.watcher_machine!==void 0&&typeof a.watcher_machine!="string"&&n.push({field:"watcher_machine",problem:"must be a machine id",received:a.watcher_machine}),n.length>0&&U("watch request",n),await R(e.principal),await v(async o=>{const s=typeof a.watcher=="string";if((e.publishToken||e.principal.class==="anonymous")&&!s)throw new y(404,"not_found","watcher not found");const c=i??[">"],u={patterns:c,...r?{config:r}:{},...a.filter!==void 0?{filter:a.filter}:{}};if(s){const j=a.watcher,k=t===null?null:await bt(o,e,j,t),p=k??(e.publishToken?await oe(o,j):await ne(o,j));if(p===null)return E();if(k===null&&await Ie(o,e,p)){const L=await se(o,e,p);await J(o,e,p);const h=await C(o,p),_=await S(o,h,O(e));if(!await D(o,h,_))throw new y(404,"not_found","object not found");return await M(o,p,_,"act",u),await G(o,p,_),await B(o,{event:"watched",object:_,actor:L,attrs:{}},await A(o)),{object:await $(o,_,await g(o,_)),patterns:c}}const{actor:d,object:m}=await Ne(o,e,p,O(e));return await M(o,p,m,"act",{...u,linkApp:d}),await G(o,p,m),await B(o,{event:"watched",object:m,actor:d,attrs:{}},await A(o)),{object:await $(o,m,await g(o,m)),patterns:c}}const f=await T(o,e),w=await Q(o,e)??ae(f),b=await S(o,f,O(e));return await M(o,w,b,"ask",u),await G(o,w,b),await B(o,{event:"watched",object:b,actor:w,attrs:{}},await A(o)),{object:await $(o,b,await g(o,b)),patterns:c}})}l(yt,"watchLocal");async function bt(e,t,n,a){return t.publishToken||t.principal.class==="anonymous"?E():await et(e,n,a)}l(bt,"ensureNodeStubFor");async function Se(e,t,n,a){const i=l(async()=>(await e.prepare(`SELECT count(*) AS n FROM watch_subscriptions s JOIN watches w ON w.watch_id = s.watch
3
- WHERE w.watcher = ? AND w.object = ?`).get(t.id,n.id)).n,"count"),r=await i();await Be(e,t,n,a??void 0);const o=await i();return o===0&&await Qe(e,t,n),{object:await g(e,n),removed:r-o}}l(Se,"dropWatch");async function gt(e){const t=O(e);if(e.query.get("watcher")&&await Re(t),!e.query.get("watcher")){const a=await x(e,t,{method:"DELETE",path:`${V(t)}/watch`,query:H(e)});if(a.kind==="unknown")throw we(t,a.unreachable);if(a.kind==="remote"){const i=a.status===404?a.body.error?.details:void 0,r=i?.deleted===!0?i.id:void 0;if(a.status>=400&&r===void 0)throw z(a.status,a.body);const o=r??a.body.object?.id,s=await v(async c=>{const u=await le(c,e),f=o===void 0?null:await I(c,o);return u===null||f===null||!await X(c,f)?null:await Se(c,u,f,e.query.get("pattern"))});if(r!==void 0){if(s===null)throw z(a.status,a.body);return{...s,machine:a.machine}}return Y(a.body,a.machine)}}const n=await qe(await N(),e.query.get("watcher")??void 0,e.query.get("watcher_machine")??void 0);return await jt(e,n)}l(gt,"unwatchRoute");async function jt(e,t=null){const n=e.query.get("pattern"),a=e.query.get("watcher");return await R(e.principal),await v(async i=>{if((e.publishToken||e.principal.class==="anonymous")&&!a)throw new y(404,"not_found","watcher not found");const r=l(async(c,u)=>await Se(i,c,u,n),"drop");if(a){const c=t===null?null:await(async()=>{const f=await I(i,a);return f!==null&&await tt(i,f)!==null?f:null})();if(t!==null&&c===null)return E();const u=c??(e.publishToken?await oe(i,a):await ne(i,a));return u===null?E():c===null&&await Ie(i,e,u)?(await se(i,e,u),await J(i,e,u),await r(u,await S(i,await C(i,u),O(e)))):await r(u,(await Ne(i,e,u,O(e))).object)}const o=await T(i,e),s=await Q(i,e)??ae(o);return await r(s,await S(i,o,O(e)))})}l(jt,"unwatchLocal");async function _t(e){const t=[],n=ee(e.query.get("type"),"type",["acted-on","links-to","watches"],t),a=ee(e.query.get("direction"),"direction",["out","in"],t);return t.length>0&&U("edges request",t),await R(e.principal),await v(async i=>{const r=await T(i,e),o=await S(i,r,O(e)),s=[];if(n!=="watches")for(const c of await Ge(i,r,o,{...n?{type:n}:{},direction:a??"both"}))s.push({type:c.type,src:await g(i,c.src),dst:await g(i,c.dst),...c.written_as?{written_as:c.written_as}:{}});if(n===void 0||n==="watches"){const c=[...a!=="in"?await Ze(i,r,o):[],...a!=="out"?await Ke(i,r,o):[]];for(const u of c)s.push({type:"watches",src:await g(i,u.watcher),dst:await g(i,u.object)})}return{items:s}})}l(_t,"edges");const W=l(e=>async t=>({status:200,body:await e(t)}),"ok"),Zt=[{method:"POST",pattern:"/v1/objects/search",handler:W(dt)},{method:"GET",pattern:"/v1/objects/:ref/edges",handler:W(_t)},{method:"POST",pattern:"/v1/objects/:ref/watch",handler:W(ht)},{method:"DELETE",pattern:"/v1/objects/:ref/watch",handler:W(gt)},{method:"GET",pattern:"/v1/objects/:ref",handler:W(st)},{method:"GET",pattern:"/v1/objects",handler:W(ft)}];export{ut as listBudget,Zt as objectRoutes,ot as resolvedLocally};
1
+ var Fe=Object.defineProperty;var u=(e,t)=>Fe(e,"name",{value:t,configurable:!0});import{ApiError as h}from"../../../api/errors.js";import{PRIVACY_LEVELS_DTO as Ae}from"../../../api/dto/objects.js";import{openDb as N,withCanvasWrite as v}from"../../../core/canvas/db.js";import{actorOf as ie}from"../../../core/graph/documents.js";import{readerForObject as C,readerFor as We}from"../../../core/graph/reader.js";import{resolveName as Le,stubsNamed as Pe,unwrapRef as re}from"../../../core/graph/names.js";import{canRead as D,holdsObjectsScope as Ce,spaceOf as De}from"../../../core/graph/access.js";import{customReachable as Me,mayActAs as oe}from"../../../core/graph/custom.js";import{customObjectRef as se,authorizeCustom as ce,fenceArgv as J}from"./custom-objects.js";import{edgesOf as Ge}from"../../../core/graph/edges.js";import{publish as B}from"../../../core/graph/events.js";import{objectDTO as Ue}from"../../../core/graph/kinds/dto.js";import{isKind as He,kindNames as ze,kindOf as K}from"../../../core/graph/kinds/registry.js";import{listObjects as Ve,searchObjects as ue}from"../../../core/graph/objects.js";import{checkoutsForCwd as Je}from"../../../core/graph/repo-sync/repos.js";import{recordWatch as M,unwatch as Be,watchersOf as Ke,watchesOf as Ze}from"../../../core/graph/watches.js";import{armObjectWaitForWatch as G,settleObjectWaitForUnwatch as Qe}from"../../../core/graph/object-waits.js";import{readerFor as T,resolveRef as Z,warmReaderRepos as R}from"../reader.js";import{readDelegationFor as le,runReadLeaf as Ye}from"../../plugin-objects/read-leaf.js";import{invalidRequest as U,isRecord as q}from"./validate.js";import{callerNode as fe,callerStub as Q,forwardNamed as Xe,forwardVerb as de,originates as we,queryWithoutMachine as H,relayError as z,remoteStub as xe,unknownError as me,forwarding as P,withMachine as Y}from"../../peer/forward.js";import{getById as I}from"../../../core/graph/objects.js";import{ensureNodeStub as et,isStub as X,stubOf as tt,withKindDecl as $}from"../../../core/peer/stubs.js";import{isUnreachable as nt}from"../../../core/peer/client.js";import{normalizeMachineId as F}from"../../../core/peer/directory.js";import{mapAsync as at}from"../../../core/async-array.js";const A=u(async e=>async(t,n)=>await Je(e,t,n),"reposFnFor");async function j(e,t){return{...await Ue(e,t),...t.type==="document"?{schema_type:t.schema_type??null}:{}}}u(j,"objectDTO");async function it(e,t){const n=t.filter(r=>r.type==="document").map(r=>r.id),a=new Map;if(n.length===0)return a;const i=await e.prepareUncached(`SELECT object, extensions_json FROM documents WHERE object IN (${n.map(()=>"?").join(", ")})`).all(...n);for(const r of i)r.extensions_json!==null&&a.set(r.object,JSON.parse(r.extensions_json));return a}u(it,"extensionsOf");async function pe(e,t){const n=await it(e,t);return await at(t,async a=>({...await j(e,a),...await(await K(e,a.type)).listItem?.(e,a),...a.type==="document"?{extensions:n.get(a.id)??{}}:{}}))}u(pe,"listItems");function rt(e){return`no object named ${e} on this runtime; it may be on another runtime, or the name may be misspelled`}u(rt,"remoteMessage");async function he(e,t,n){try{return await S(e,t,n)}catch(a){if(a instanceof h&&a.code==="not_found"&&!a.details?.deleted)return null;throw a}}u(he,"ownerFilter");async function S(e,t,n){const a=await Z(e,t,n);if("remote"in a)throw new h(404,"not_found",rt(a.remote),{next:"Check the name with `crtr canvas search`."});if("deleted"in a)throw new h(404,"not_found",`${a.deleted.name} is deleted`,{id:a.deleted.id,deleted:!0});return a}u(S,"liveRef");const O=u(e=>decodeURIComponent(e.params.ref),"refParam"),ye=u(e=>{const t=re(e),n=t.indexOf("/");return n>0?t.slice(0,n):t},"idOf");async function x(e){const t=await I(await N(),ye(e));return t!==null&&await X(await N(),t)?t.id:null}u(x,"stubIdOf");async function ot(e,t){const n=await x(e);return n!==null?{stub:n,hit:!0}:(await R(t.principal),await v(async a=>{try{const i=await T(a,t),r=u(async()=>{const s=await Pe(a,i,e);if(s.length>1)throw new h(409,"ambiguous_name",`'${e}' names more than one remote object`,{candidates:s.map(c=>c.id),next:"Read one by its object id."});return{stub:s[0]?.id??null,hit:!1}},"named");let o;try{o=await Z(a,i,e)}catch(s){if(s instanceof h&&s.code==="not_found")return await r();throw s}if("remote"in o)return await r();if("deleted"in o){const s=await r();return s.stub===null?{stub:null,hit:!0}:s}return{stub:await X(a,o)?o.id:null,hit:!0}}catch(i){if(i instanceof h&&i.code==="ambiguous_name")throw i;return{stub:null,hit:!1}}}))}u(ot,"resolvedLocally");async function ee(e,t,n){const a=await ot(t,e);if(a.stub!==null)return de(e,a.stub,n);if(a.hit||!we(e.principal))return{kind:"local"};const i=await de(e,ye(t),n);return i.kind==="local"&&re(t).includes("/")?Xe(e,n,{method:"GET",path:V(t),query:H(e)}):i}u(ee,"forwardRef");const V=u(e=>`/v1/objects/${encodeURIComponent(e)}`,"objectPath");async function be(e,t,n,a,i){const r=t?.object;!r?.id||!r.type||await v(async o=>{const s=await fe(o,e);if(s===null)return;const c=await xe(o,r.id,r.type,n,{kind:r.kind??null,name:r.name??r.id,...r.preview===void 0?{}:{preview:r.preview},owner:r.owner??null,...r.kind_decl===void 0?{}:{kind_decl:r.kind_decl},...r.privacy===void 0?{}:{privacy:r.privacy}});await M(o,s,c,a,i===void 0?{}:{patterns:i}),a==="ask"&&await G(o,s,c)})}u(be,"watchRemote");async function st(e){const t=O(e),n=["1","true"].includes(e.query.get("fields")??""),a=u(async s=>{const c=await Q(s,e);return c===null?await T(s,e):await C(s,c,await A(s))},"readerOf"),i=u(async s=>(await R(e.principal),await v(async c=>{const l=await a(c),f=await Z(c,l,t).catch(g=>{if(s||g instanceof h&&g.code==="ambiguous_name")throw g;return null});if(f===null||!s&&!("id"in f))return null;if("remote"in f)return{state:"remote",remote:f.remote};if("deleted"in f)return{state:"deleted",deleted:await j(c,f.deleted)};const w=await le(c,f);if(w!==null)return{delegate:w,hitId:f.id};const{data:b,text:_}=await(await K(c,f.type)).read(c,l,f,{fields:n,reposFn:await A(c)});return{state:"object",type:f.type,object:await $(c,f,await j(c,f)),text:_,data:b}})),"local"),r=(await x(t)===null?await i(!1):null)??await ee(e,t,{method:"GET",path:V(t),query:H(e)}).then(async s=>{if(s.kind==="local")return await i(!0);if(s.kind==="unknown")return{state:"unknown",ref:t,unreachable:s.unreachable};if(s.status>=400)throw z(s.status,s.body);return await be(e,s.body,s.machine.id,"read").then(()=>Y(s.body,s.machine))});if(!("delegate"in r))return r;const o=await Ye(r.delegate,e.principal);return await R(e.principal),await v(async s=>{const c=await a(s),l=await I(s,r.hitId);if(l===null)throw new h(404,"not_found","object not found");if(l.deleted_at!==null)return{state:"deleted",deleted:await j(s,l)};if(!await D(s,c,l))throw new h(404,"not_found","object not found");const{data:f,text:w}=await(await K(s,l.type)).read(s,c,l,{fields:n,reposFn:await A(s)});return await le(s,l)===null?{state:"object",type:l.type,object:await $(s,l,await j(s,l)),text:w,data:f}:{state:"object",type:l.type,object:await $(s,l,await j(s,l)),text:"markdown"in o?o.markdown:`${w}
2
+ content unavailable: ${o.unavailable}`,data:{...f,content:"markdown"in o?"live":"unavailable"}}})}u(st,"read");function te(e,t,n,a){if(e!=null){if(!n.includes(e)){a.push({field:t,problem:`must be one of ${n.join(", ")}`,received:e});return}return e}}u(te,"oneOf");async function ge(e,t,n){if(t!=null){if(typeof t!="string"||!await He(e,t)){n.push({field:"type",problem:`must be a kind: one of ${(await ze(e)).join(", ")}`,received:t});return}return t}}u(ge,"kindName");function je(e,t,n,a){if(e==null)return a;const i=Number(e);return!Number.isInteger(i)||i<1||i>100?(n.push({field:t,problem:"must be an integer from 1 to 100",received:e}),a):i}u(je,"limitOf");function _e(e,t){if(e==null)return;let n=e;if(typeof e=="string")try{n=JSON.parse(e)}catch{n=null}if(!q(n)||Object.values(n).some(a=>!q(a))){t.push({field:"extensions",problem:'must be an object of objects, e.g. {"firstlight":{"state":"active"}}',received:e});return}return n}u(_e,"extensionsParam");function ke(e,t){if(e!=null){if(typeof e!="string"||e===""){t.push({field:"schema_type",problem:"must be a non-empty string",received:e});return}return e}}u(ke,"schemaTypeParam");async function ve(e){const t=e.query,n=[],a=await ge(await N(),t.get("type"),n),i=te(t.get("privacy"),"privacy",Ae,n),r=je(t.get("limit"),"limit",n,50),o=t.get("cursor");o!==null&&!/^\d+$/.test(o)&&n.push({field:"cursor",problem:"is not a cursor from a previous page",received:o});const s=t.get("deleted");s!==null&&!["0","1","true","false"].includes(s)&&n.push({field:"deleted",problem:"must be true or false",received:s});const c=t.get("shared");c!==null&&!["0","1","true","false"].includes(c)&&n.push({field:"shared",problem:"must be true or false",received:c});const l=_e(t.get("extensions"),n),f=ke(t.get("schema_type"),n);return n.length>0&&U("object list request",n),await R(e.principal),await v(async w=>{const b=await T(w,e),_={...a?{type:a}:{},...i?{privacy:i}:{},...t.get("kind")!==null?{kind:t.get("kind")}:{},...s==="1"||s==="true"?{deleted:!0}:{},...c==="1"||c==="true"?{shared:!0}:{},...l?{extensions:l}:{},...f?{schemaType:f}:{},...t.get("name")!==null?{namePrefix:t.get("name")}:{}},g=t.get("owner");if(g!==null){const m=await he(w,b,g);if(m===null)return{items:[],next_cursor:null};_.owner=m}const p=await Ve(w,b,_,{limit:r,after_seq:o===null?0:Number(o)}),d=p.at(-1);return{items:await pe(w,p),next_cursor:p.length===r&&d?String(d.seq):null}})}u(ve,"listLocal");const ct={ms:3e4},ut="self",ne=u((e,t)=>e.map(n=>({...n,machine:t})),"labelItems");async function Oe(e,t,n,a){const i=P.current;try{const r=await i.call(t.id,{method:"GET",path:"/v1/objects",query:n},await i.envelope(e.principal),a);if(nt(r))return{state:"unreachable",items:[],next:null};if(r.status===426)return{state:"too_old",items:[],next:null};const o=r.body;return r.status!==200||!Array.isArray(o?.items)?{state:"unreachable",items:[],next:null}:{state:"ok",items:ne(o.items,t),next:o.next_cursor??null}}catch{return{state:"unreachable",items:[],next:null}}}u(Oe,"remotePage");async function lt(e){const t=new Promise(n=>e.addEventListener("abort",()=>n(null),{once:!0}));return Promise.race([P.current.machines().catch(()=>null),t])}u(lt,"machinesWithin");async function ft(e){const t=e.query.get("machine");if(!we(e.principal)||!P.current.joined()||t===ut)return await ve(Ee(e));const a=P.current.self(),i=t!==null&&F(t)!==a,r=i?null:await ve(Ee(e)),o=new AbortController,s=setTimeout(()=>o.abort(),ct.ms);s.unref?.();try{const c=await lt(o.signal);if(c===null){if(i)throw new h(503,"runtime_unreachable",`The directory did not answer, so ${F(t)} cannot be listed.`,{machine:F(t)});return r}const l=u(d=>({id:d,name:c.find(m=>m.machine_id===d)?.name??d}),"labelOf"),f=l(a),w=c.filter(d=>d.machine_id!==a&&d.kind!=="device"),b=H(e);if(t!==null){if(!i)return{items:ne(r.items,f),next_cursor:r.next_cursor,machines:[{machine_id:a,name:f.name,state:"ok",more:r.next_cursor!==null}]};const d=F(t);if(!w.some(L=>L.machine_id===d))throw new h(404,"not_found",`no machine ${d} on your account`,{machine:d});const m=await Oe(e,l(d),b,o.signal);return{items:m.items,next_cursor:m.next,machines:[{machine_id:d,name:l(d).name,state:m.state,more:m.next!==null}]}}const{cursor:_,...g}=b,p=await Promise.all(w.map(d=>Oe(e,l(d.machine_id),g,o.signal)));return{items:[...ne(r.items,f),...p.flatMap(d=>d.items)],next_cursor:r.next_cursor,machines:[{machine_id:a,name:f.name,state:"ok",more:r.next_cursor!==null},...w.map((d,m)=>({machine_id:d.machine_id,name:d.name,state:p[m].state,more:p[m].next!==null}))]}}finally{clearTimeout(s)}}u(ft,"list");function Ee(e){const t=new URLSearchParams(e.query);return t.delete("machine"),{...e,query:t}}u(Ee,"withoutMachine");async function dt(e){const t=[],n=q(e.body)?e.body:{};q(e.body)||t.push({field:"body",problem:"must be an object",received:e.body});const a=n.text;(typeof a!="string"||a.trim()==="")&&t.push({field:"text",problem:"is required",received:a});const i=n.grep;if(i!==void 0)if(typeof i!="string")t.push({field:"grep",problem:"must be a regular expression string",received:i});else try{new RegExp(i)}catch(y){t.push({field:"grep",problem:`is not a valid regular expression: ${y.message}`,received:i})}n.body!==void 0&&typeof n.body!="boolean"&&t.push({field:"body",problem:"must be a boolean",received:n.body});const r=await ge(await N(),n.type,t);n.kind!==void 0&&typeof n.kind!="string"&&t.push({field:"kind",problem:"must be a string",received:n.kind}),n.owner!==void 0&&typeof n.owner!="string"&&t.push({field:"owner",problem:"must be a string",received:n.owner});const o=je(n.limit,"limit",t,50),s=_e(n.extensions,t),c=ke(n.schema_type,t);t.length>0&&U("object search request",t),await R(e.principal);const l=await v(async y=>{const k=await T(y,e),$e=typeof n.owner=="string"?await he(y,k,n.owner):null;return{reader:k,owner:$e}}),{reader:f,owner:w}=l;if(typeof n.owner=="string"&&w===null)return{items:[]};const b={...s?{extensions:s}:{},...c?{schemaType:c}:{},...r?{type:r}:{},...typeof n.kind=="string"?{kind:n.kind}:{},...w?{owner:w}:{}},_=await N(),g=await ue(_,f,{text:a,body:n.body===!0||typeof i=="string",...b}),p=new Set(g.map(y=>y.object.id)),m=(typeof i=="string"?(await ue(_,f,{text:i,grep:!0,...b})).filter(y=>p.has(y.object.id)):g).slice(0,o),L=await pe(_,m.map(y=>y.object));return{items:m.map((y,k)=>({object:L[k],...y.line!==void 0?{matches:[{line:y.line,text:y.text??""}]}:{}}))}}u(dt,"search");const Te=["interrupt","steer","after-turn","next-turn"],wt=/^(\*|>|[A-Za-z0-9_-]+)(\.(\*|>|[A-Za-z0-9_-]+))*$/;function mt(e,t){if(e!==void 0){if(!Array.isArray(e)||e.length===0||e.some(n=>typeof n!="string"||!wt.test(n)||n.includes(">")&&!n.endsWith(">"))){t.push({field:"patterns",problem:"must be a non-empty list of event patterns (dot-separated words, `*` for one word, a final `>` for the rest)",received:e});return}return e}}u(mt,"patternsOf");function pt(e,t){if(e===void 0)return;if(!q(e)||Object.keys(e).length===0){t.push({field:"config",problem:"must map levels 1-10 to a delivery",received:e});return}const n=[];for(const[a,i]of Object.entries(e)){const r=Number(a);!Number.isInteger(r)||r<1||r>10?t.push({field:`config.${a}`,problem:"level must be an integer from 1 to 10"}):Te.includes(i)?n.push({threshold:r,delivery:i}):t.push({field:`config.${a}`,problem:`delivery must be one of ${Te.join(", ")}`,received:i})}return n.sort((a,i)=>i.threshold-a.threshold)}u(pt,"configOf");async function Re(e){const t=await x(e);if(t!==null)throw new h(400,"invalid_request",`${t} lives on another machine; an explicit watcher cannot watch it from here`,{id:t})}u(Re,"refuseStubWatch");async function ae(e,t){const n=await I(e,t)??await(async()=>{const a=await Le(e,await We(e,{class:"person"},async()=>[]),t);return"object"in a?a.object:null})();return n===null||n.deleted_at!==null||!(n.type.includes(".")||n.type==="node")?null:n}u(ae,"findWatcher");const E=u(()=>{throw new h(404,"not_found","watcher not found")},"watcherNotFound");async function qe(e,t,n){if(typeof t!="string"||n===void 0||n===null)return null;if(typeof n!="string")throw new h(400,"invalid_request","invalid watcher_machine");if(await ae(e,t)!==null)return null;const a=P.current;let i;try{i=await a.machines()}catch{throw new h(503,"runtime_unreachable","The directory did not answer, so the watcher machine cannot be checked.")}const r=F(n);return(r===a.self()||!i.some(o=>F(o.machine_id)===r))&&E(),r}u(qe,"remoteWatcherMachine");async function Ne(e,t,n,a){if(t.publishToken||t.principal.class==="anonymous")return E();const i=await T(e,t);if(i.class==="person")return E();let r;try{r=await S(e,i,a)}catch{return E()}const o=r.owner===null?null:await I(e,r.owner);return o===null||!await oe(e,i,o)||!await Ce(e,i,"link",n)||(await De(e,n)).id===i.app.id&&!(await D(e,i,n)&&await D(e,await C(e,n),r))?E():(await J(e,t,n),{actor:i.app,object:r})}u(Ne,"linkWatcher");async function Ie(e,t,n){if(t.publishToken)return!0;if(t.principal.class==="anonymous"||!n.type.includes("."))return!1;const a=await T(e,t),i=n.owner===null?null:await I(e,n.owner);return i!==null&&await oe(e,a,i)&&await Me(e,a,n)}u(Ie,"ownsWatcher");async function ht(e){const t=O(e),n=q(e.body)?e.body:{};if(typeof n.watcher=="string"&&await Re(t),typeof n.watcher!="string"){const i=await ee(e,t,{method:"POST",path:`${V(t)}/watch`,body:e.body});if(i.kind==="unknown")throw me(t,i.unreachable);if(i.kind==="remote"){if(i.status>=400)throw z(i.status,i.body);const r=i.body.patterns;return await be(e,i.body,i.machine.id,"ask",r),Y(i.body,i.machine)}}const a=await qe(await N(),n.watcher,n.watcher_machine);return await yt(e,a)}u(ht,"watch");async function yt(e,t=null){const n=[],a=e.body===void 0?{}:q(e.body)?e.body:(n.push({field:"body",problem:"must be an object"}),{}),i=mt(a.patterns,n),r=pt(a.config,n);return a.filter!==void 0&&!q(a.filter)&&n.push({field:"filter",problem:"must be an object",received:a.filter}),a.watcher!==void 0&&typeof a.watcher!="string"&&n.push({field:"watcher",problem:"must be a custom-object ref",received:a.watcher}),a.watcher_machine!==void 0&&typeof a.watcher_machine!="string"&&n.push({field:"watcher_machine",problem:"must be a machine id",received:a.watcher_machine}),n.length>0&&U("watch request",n),await R(e.principal),await v(async o=>{const s=typeof a.watcher=="string";if((e.publishToken||e.principal.class==="anonymous")&&!s)throw new h(404,"not_found","watcher not found");const c=i??[">"],l={patterns:c,...r?{config:r}:{},...a.filter!==void 0?{filter:a.filter}:{}};if(s){const _=a.watcher,g=t===null?null:await bt(o,e,_,t),p=g??(e.publishToken?await se(o,_):await ae(o,_));if(p===null)return E();if(g===null&&await Ie(o,e,p)){const L=await ce(o,e,p);await J(o,e,p);const y=await C(o,p),k=await S(o,y,O(e));if(!await D(o,y,k))throw new h(404,"not_found","object not found");return await M(o,p,k,"act",l),await G(o,p,k),await B(o,{event:"watched",object:k,actor:L,attrs:{}},await A(o)),{object:await $(o,k,await j(o,k)),patterns:c}}const{actor:d,object:m}=await Ne(o,e,p,O(e));return await M(o,p,m,"act",{...l,linkApp:d}),await G(o,p,m),await B(o,{event:"watched",object:m,actor:d,attrs:{}},await A(o)),{object:await $(o,m,await j(o,m)),patterns:c}}const f=await T(o,e),w=await Q(o,e)??ie(f),b=await S(o,f,O(e));return await M(o,w,b,"ask",l),await G(o,w,b),await B(o,{event:"watched",object:b,actor:w,attrs:{}},await A(o)),{object:await $(o,b,await j(o,b)),patterns:c}})}u(yt,"watchLocal");async function bt(e,t,n,a){return t.publishToken||t.principal.class==="anonymous"?E():await et(e,n,a)}u(bt,"ensureNodeStubFor");async function Se(e,t,n,a){const i=u(async()=>(await e.prepare(`SELECT count(*) AS n FROM watch_subscriptions s JOIN watches w ON w.watch_id = s.watch
3
+ WHERE w.watcher = ? AND w.object = ?`).get(t.id,n.id)).n,"count"),r=await i();await Be(e,t,n,a??void 0);const o=await i();return o===0&&await Qe(e,t,n),{object:await j(e,n),removed:r-o}}u(Se,"dropWatch");async function gt(e){const t=O(e);if(e.query.get("watcher")&&await Re(t),!e.query.get("watcher")){const a=await ee(e,t,{method:"DELETE",path:`${V(t)}/watch`,query:H(e)});if(a.kind==="unknown")throw me(t,a.unreachable);if(a.kind==="remote"){const i=a.status===404?a.body.error?.details:void 0,r=i?.deleted===!0?i.id:void 0;if(a.status>=400&&r===void 0)throw z(a.status,a.body);const o=r??a.body.object?.id,s=await v(async c=>{const l=await fe(c,e),f=o===void 0?null:await I(c,o);return l===null||f===null||!await X(c,f)?null:await Se(c,l,f,e.query.get("pattern"))});if(r!==void 0){if(s===null)throw z(a.status,a.body);return{...s,machine:a.machine}}return Y(a.body,a.machine)}}const n=await qe(await N(),e.query.get("watcher")??void 0,e.query.get("watcher_machine")??void 0);return await jt(e,n)}u(gt,"unwatchRoute");async function jt(e,t=null){const n=e.query.get("pattern"),a=e.query.get("watcher");return await R(e.principal),await v(async i=>{if((e.publishToken||e.principal.class==="anonymous")&&!a)throw new h(404,"not_found","watcher not found");const r=u(async(c,l)=>await Se(i,c,l,n),"drop");if(a){const c=t===null?null:await(async()=>{const f=await I(i,a);return f!==null&&await tt(i,f)!==null?f:null})();if(t!==null&&c===null)return E();const l=c??(e.publishToken?await se(i,a):await ae(i,a));return l===null?E():c===null&&await Ie(i,e,l)?(await ce(i,e,l),await J(i,e,l),await r(l,await S(i,await C(i,l),O(e)))):await r(l,(await Ne(i,e,l,O(e))).object)}const o=await T(i,e),s=await Q(i,e)??ie(o);return await r(s,await S(i,o,O(e)))})}u(jt,"unwatchLocal");async function _t(e){const t=[],n=te(e.query.get("type"),"type",["acted-on","links-to","watches"],t),a=te(e.query.get("direction"),"direction",["out","in"],t);return t.length>0&&U("edges request",t),await R(e.principal),await v(async i=>{const r=await T(i,e),o=await S(i,r,O(e)),s=[];if(n!=="watches")for(const c of await Ge(i,r,o,{...n?{type:n}:{},direction:a??"both"}))s.push({type:c.type,src:await j(i,c.src),dst:await j(i,c.dst),...c.written_as?{written_as:c.written_as}:{}});if(n===void 0||n==="watches"){const c=[...a!=="in"?await Ze(i,r,o):[],...a!=="out"?await Ke(i,r,o):[]];for(const l of c)s.push({type:"watches",src:await j(i,l.watcher),dst:await j(i,l.object)})}return{items:s}})}u(_t,"edges");const W=u(e=>async t=>({status:200,body:await e(t)}),"ok"),Zt=[{method:"POST",pattern:"/v1/objects/search",handler:W(dt)},{method:"GET",pattern:"/v1/objects/:ref/edges",handler:W(_t)},{method:"POST",pattern:"/v1/objects/:ref/watch",handler:W(ht)},{method:"DELETE",pattern:"/v1/objects/:ref/watch",handler:W(gt)},{method:"GET",pattern:"/v1/objects/:ref",handler:W(st)},{method:"GET",pattern:"/v1/objects",handler:W(ft)}];export{ct as listBudget,Zt as objectRoutes,ot as resolvedLocally};
@@ -1,21 +1,21 @@
1
- var cr=Object.defineProperty;var s=(e,l)=>cr(e,"name",{value:l,configurable:!0});import{applyBootSettings as lr}from"./boot-settings.js";import{startPeerOutbox as dr}from"./peer/outbox.js";import{reportMachineStatus as mr}from"../core/peer/directory.js";import{createPeerRelay as pr}from"./peer/relay-service.js";import{writeFileSync as fr,readFileSync as ur,rmSync as hr,mkdirSync as Ie,existsSync as P,unlinkSync as xe,chmodSync as De}from"node:fs";import{createServer as Y}from"node:http";import{dirname as wr}from"node:path";import{envCrtrdTcp as Te,envDocumentPort as vr}from"../shared/env.js";import{openCanvasConversationStore as gr,serveCanvasConversationStore as yr}from"../core/canvas/sessions.js";import{installConversationStore as Sr}from"../core/conversation-store/index.js";import{pollRunObservers as _r}from"./runs/observer.js";import{randomBytes as Ce}from"node:crypto";import{apiSocketPath as Le,crtrHome as br}from"../core/canvas/paths.js";import{activeAppUsers as kr}from"../core/spaces/users.js";import{ensureAppSpace as Rr,ensureUserFiles as Pr}from"../core/spaces/space.js";import{LAUNCHER_SOCKET as C}from"../launcher/spec.js";import{launcherRequest as A}from"../launcher/client.js";import{installLauncherEventSink as Er}from"./launcher-events.js";import{initializeEmptyLayout as Ir,layoutNeedsMigration as xr,socketDir as $e}from"../core/layout.js";import{migrateLooseKeys as Dr}from"../core/layout-migrate/loose-keys.js";import{relocateProfileFolders as Tr}from"../core/profiles/relocate.js";import{getNode as Cr,getRow as Lr,listNodesForSupervision as Ae,listParkedResidentsWithWakeMail as $r,setFrozen as Ne}from"../core/canvas/index.js";import{createApiServer as Ar,closeServer as Me}from"./api/server.js";import{Router as Nr}from"./api/router.js";import{healthRoutes as Mr}from"./api/handlers/health.js";import{createDocumentListener as Or}from"./api/document-listener.js";import{documentSecret as Gr}from"./api/document-secret.js";import{createAppListener as Fr}from"./api/app-listener.js";import{registerMachineEnvironment as Br}from"../core/environments.js";import{registerBlaxelRunnerFromEnv as Hr}from"../core/secrets/blaxel-register.js";import{markCloudRole as jr,resolvePerson as zr,retireLocalPerson as Ur,setPersonId as qr}from"../core/canvas/person.js";import{backfillNodeApps as Oe,runPermissionsBoot as Wr}from"../core/permissions/boot.js";import{startRunNotices as Jr}from"./run-notices.js";import{startGrantEffects as Kr}from"./reconcilers/grant-effects.js";import{syncPackages as Vr}from"../core/packages/directory-sync.js";import{startActivationDelivery as Yr}from"../core/model-auth/activations.js";import{createGrantSync as Qr,GRANT_SYNC_INTERVAL_S as Ge}from"../core/grants/sync.js";import{sweepSandboxes as Xr}from"../core/grants/on-sync.js";import{rebuildCronExecutions as Zr}from"./cron/run-socket.js";import{hasSyncedGrants as et}from"../core/grants/mirror.js";import{readConfig as me}from"../core/config.js";import{reconcileUndeliveredTickets as rt}from"./human/sweep.js";import{resetHandedOffDeliveries as tt}from"../core/canvas/deliveries.js";import{resetHandedOffDaemonActions as nt}from"../core/canvas/daemon-actions.js";import{sweepReviews as ot}from"./review/sweep.js";import{pidfilePath as pe}from"./pidfile.js";import{rendererWarning as it}from"../core/runtime/package-health.js";import{DEFAULT_INTERVAL_MS as at}from"./supervise-cadence.js";import{createResumeDetector as st}from"./resume-detector.js";import{setFatalFaultAnnouncer as ct}from"../core/canvas/recovery.js";import{BrokerSupervisionReconciler as lt}from"./reconcilers/broker-supervision.js";import{MachineOfflineReconciler as dt}from"./reconcilers/machine-offline.js";import{ControllerDeathReconciler as mt}from"./reconcilers/controller-death.js";import{NodeLifecycleReconciler as pt}from"./reconcilers/node-lifecycle/tick.js";import{NodeDeadlineReconciler as ft}from"./reconcilers/node-deadline.js";import{CronLaneReconciler as ut}from"./reconcilers/cron-lane.js";import{DeliveryLaneReconciler as ht}from"./reconcilers/delivery-lane.js";import{ActionLaneReconciler as wt}from"./reconcilers/action-lane.js";import{endLiveExecution as vt,hasObservedExit as gt,latestExecutionForNode as yt,migrateLegacyExecutionIdentities as St}from"../core/canvas/executions.js";import{revokePriorEpochNodeTokens as _t}from"../core/canvas/node-tokens.js";import{PendingReviewSubmitReconciler as bt}from"./reconcilers/pending-review-submit.js";import{StorageMaintenanceReconciler as kt}from"./reconcilers/storage-maintenance.js";import{StorageDueWorkReconciler as Rt}from"./reconcilers/storage-due-work.js";import{GroupInviteExpiryReconciler as Pt}from"./reconcilers/group-invite-expiry.js";import{PurgeDueWorkReconciler as Et}from"./reconcilers/purge-due-work.js";import{assertLedgerEnv as It}from"../core/ledger/rates.js";import{IdleSandboxReconciler as xt}from"./reconcilers/idle-sandbox.js";import{LedgerSandboxReconciler as Dt}from"./reconcilers/ledger-sandbox.js";import{LedgerStorageReconciler as Tt}from"./reconcilers/ledger-storage.js";import{LedgerR2Reconciler as Ct}from"./reconcilers/ledger-r2.js";import{importedNodesHeld as fe}from"./reconcilers/live-obligation.js";import{ImportLaneReconciler as Lt}from"./reconcilers/import-lane.js";import{BashDeadlineReconciler as $t}from"./reconcilers/bash-deadline.js";import{FaultRetryBackstopReconciler as At}from"./reconcilers/fault-retry-backstop.js";import{StructuredRequestReconciler as Nt}from"./reconcilers/structured-request-lane.js";import{RecipeImageReconciler as Mt,subscribeImageBuilt as Ot}from"./reconcilers/recipe-image.js";import{reconcileStructuredRequestSidecars as Gt}from"./structured-requests/boot.js";import{captureLivenessSnapshot as Fe,capturePidCommand as Ft,captureTeardownSnapshot as Be,isPidAlive as Bt,isAnyPidAlive as He,killProcessTreePids as je}from"../core/canvas/pid.js";import{bindFleet as Ht,boundFleet as ze}from"../core/runtime/fleet.js";import{bindDaemonControl as jt,clearDaemonControl as zt}from"./control.js";import{execDaemon as Ut,spawnDaemon as qt}from"./manage.js";import{reconcileAndMigrateBoot as Wt}from"../core/canvas/boot.js";import{resolveInstallId as Jt}from"../core/canvas/install-id.js";import{setInstallId as Kt}from"../core/runtime/nodes.js";import{claimDaemonOwnership as Vt,daemonOwnershipApplies as Yt,daemonOwnershipClaimed as Qt,releaseDaemonOwnership as Ue}from"../core/canvas/daemon-owner.js";import{canvasDatabaseUrl as Xt,closeAllDbs as ue,openDb as Zt,withCanvasWrite as he}from"../core/canvas/db.js";import{importSqliteCanvasIfPresent as en}from"../core/canvas/import-sqlite.js";import{ensurePostgres as rn,ensurePostgresHealthy as tn,stopPostgres as nn,withPostgresStartLock as on}from"./postgres/index.js";import{brokerSignalBus as N}from"./broker-signals/bus.js";import{brokerSignalStreams as an}from"./api/handlers/broker-signals.js";import{setRequestsStartRunObservers as sn}from"./api/handlers/broker-ops.js";import{reconcilePackages as cn}from"../core/graph/package-reconcile.js";import{migrateAppInstalls as ln}from"../core/scoped-state/migrate-app-installs.js";import{publish as dn,readBuiltinSnapshot as mn}from"../core/graph/package-publish.js";import{prewarmRecentRecipes as pn,reapStaleSpares as fn}from"../core/runtime/warm-pool.js";import{DaemonFleet as un}from"./fleet.js";import{copyNodeFilesToRows as hn}from"../core/runtime/first-boot-rows.js";import{BOOT_MIGRATIONS as wn}from"./boot-migrations.js";import{emitEvent as m}from"../core/events/emit.js";import{operationIdContext as k}from"../core/events/operation-id.js";import{bindDaemonEventSource as vn}from"../core/events/source.js";import{activateCanvasImport as gn,MigrationBlockedError as yn,runForcedCanvasImport as Sn}from"../migrations/activation.js";import{adoptInstallPerson as _n,convertLegacyScopedStore as bn,personStoresCopied as kn}from"../core/scoped-state/migrate.js";import{readLegacyUserSnapshot as Rn}from"../core/scoped-state/legacy-profiles.js";import{heldPersons as qe,installPreludeSnapshot as Pn}from"../core/scoped-state/person-store.js";import{loadPersonSettings as we}from"../core/scoped-state/person-rows.js";import{userScopeRoot as We}from"../core/scope.js";import{brokerCommandDeclaresCanvasHome as ve}from"../core/runtime/broker-ownership.js";import{brokerCommandDeclaresCanvasHome as la}from"../core/runtime/broker-ownership.js";function ge(e){return/ --epoch (\S+) /.exec(e)?.[1]??null}s(ge,"brokerCommandEpoch");const En=5e3,Je=150;async function In(e){const l=Fe();if(l===null)throw m({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness"}}),new Error("prior-epoch broker census could not capture the process table");const f=br(),p=[];for(const[i,c]of l.processes){const w=c.command;if(c.zombie||!w.includes("broker-cli.js")||!ve(w,f)||ge(w)===e)continue;const b=w.trim().split(/\s+/).at(-1)??"";b===""||b.endsWith("broker-cli.js")||p.push({pid:i,nodeId:b})}let g=0;const o=[];for(const i of p){const c=Ft(i.pid);if(c===null||!c.includes("broker-cli.js")||!ve(c,f)||ge(c)===e||c.trim().split(/\s+/).at(-1)!==i.nodeId)continue;const w=Be(i.pid,null);if(!w.reused){try{process.platform==="linux"&&P(C)?await A({operation:"stop",pid:i.pid}):process.kill(i.pid,"SIGTERM")}catch{continue}g++,o.push({pid:i.pid,snap:w})}}const h=Date.now()+En;for(;Date.now()<h&&o.some(i=>He(i.snap.tree.length>0?i.snap.tree:[i.pid]));)await new Promise(i=>setTimeout(i,Je));let y=0;for(const i of o){const c=i.snap.tree.length>0?i.snap.tree:[i.pid];He(c)&&(process.platform==="linux"&&P(C)?await A({operation:"stop",pid:i.pid}):je(c,"SIGKILL",i.snap.identities),y++)}y>0&&await new Promise(i=>setTimeout(i,Je));const d=Fe();if(d===null)throw m({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness",stage:"final"}}),new Error("prior-epoch broker census could not capture the final process table");const u=[];for(const[i,c]of d.processes){const w=c.command;c.zombie||!w.includes("broker-cli.js")||ve(w,f)&&ge(w)!==e&&u.push(i)}if(u.length>0)throw new Error(`prior-epoch broker census could not prove termination of pid(s): ${u.join(", ")}`);m({level:"info",event:"daemon.census.completed",fields:{prior_epoch_brokers:p.length,sigtermed:g,sigkilled:y}})}s(In,"reapPriorEpochBrokers");const xn=5e3;async function Dn(e){const l=Array.from(e.entries());if(l.length===0)return;for(const[o]of l){const h=(await Cr(o))?.status;(h==="active"||h==="idle")&&await Ne(o,new Date().toISOString())}const f=l.map(([,o])=>({pid:o.pid,snap:Be(o.pid,null),exited:o.handle.exited}));for(const o of f)if(!o.snap.reused)try{process.platform==="linux"&&P(C)?await A({operation:"stop",pid:o.pid}):process.kill(o.pid,"SIGTERM")}catch{}const p=new Promise(o=>{setTimeout(o,xn).unref()});await Promise.allSettled(f.map(o=>Promise.race([o.exited.then(()=>{}),p])));const g=[];for(const o of f)Bt(o.pid)&&(process.platform==="linux"&&P(C)?await A({operation:"stop",pid:o.pid}):je(o.snap.tree.length>0?o.snap.tree:[o.pid],"SIGKILL",o.snap.identities),g.push(o));await Promise.all(g.map(o=>o.exited));for(const[o]of l)await vt(o,{reason:"daemon-teardown"});m({level:"info",event:"daemon.fleet_teardown.completed",fields:{brokers:f.length,sigkilled:g.length}})}s(Dn,"teardownFleet");function ye(e=null){Ie(wr(pe()),{recursive:!0}),fr(pe(),e===null?String(process.pid):`${process.pid}
2
- ${e}`,"utf8")}s(ye,"writePidfile");function Ke(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}s(Ke,"isMissingPathError");function Ve(e){const l=pe();let f;try{f=ur(l,"utf8")}catch(p){if(Ke(p))return;throw p}if(f.split(`
3
- `,1)[0].trim()!==String(e))throw new Error(`daemon readiness mirror does not name this invocation (expected pid ${e})`);try{hr(l)}catch(p){if(Ke(p))return;throw p}}s(Ve,"removeOwnedPidfileMirror");const Tn={acceptsDetachedWork:s(()=>!0,"acceptsDetachedWork"),registerDetached:s(e=>{e.catch(()=>{})},"registerDetached")},Q=new lt;ct(e=>Q.handleFatalFault(e,!1));const Cn=new mt,Ln=new dt,Ye=new pt,$n=new ft,An=new ut,Nn=new ht,Mn=new wt,On=new bt,Gn=new kt,Fn=new Rt,Bn=new Et,Hn=new Pt,jn=new Dt,zn=new xt,Un=new Tt,qn=new Ct,Wn=new Lt,Jn=new $t,Kn=new At,Vn=new Nt,Yn=new Mt;async function Qn(e=Date.now(),l=Tn){const f=ze(),p=await Q.runFleetPreamble(f);let g,o,h;try{o=await fe();const d=(await Ae()).filter(i=>!o.has(i.node_id));g=d.filter(i=>i.status==="active"||i.status==="idle"),h=d.filter(i=>i.status==="done"||i.status==="canceled"||i.status==="dead");const u=new Set(h.map(i=>i.node_id));h.push(...(await $r()).filter(i=>!u.has(i.node_id)&&!o.has(i.node_id)))}catch(d){m({level:"error",event:"canvas.node_list.failed",error:d});return}await Q.run(e,{rows:g,fleet:f,lifecycle:l,held:o}),await Cn.run(e,{rows:g,held:o}),await Ln.run(e);const y=await Ye.run(e,{rows:[...g,...h],fleet:f});await $n.run(e,o),await Vn.run(e,o),await Yn.run(e,{lifecycle:l}),await An.run(e,{lifecycle:l,held:o}),await Nn.run(e,{lifecycle:l}),await Mn.run(e,{lifecycle:l}),await On.run(e,{lifecycle:l}),await Gn.run(e,{lifecycle:l,fleet:f,held:o}),Fn.run(e,{lifecycle:l}),Bn.run(e,{lifecycle:l}),Hn.run(e,{lifecycle:l}),jn.run(e,{lifecycle:l}),zn.run(e,{lifecycle:l}),Un.run(e,{lifecycle:l}),qn.run(e,{lifecycle:l}),Wn.run(e,{lifecycle:l}),await _r(),Kn.run(e,{fleet:f,lifecycle:l}),await Jn.run(e,{rows:g}),Q.warnIfSaturated({fleet:f,lifecycle:l,thresholds:p,frozen:y})}s(Qn,"superviseTick");async function Xn(e,l=Date.now()){if((await fe()).has(e))return;const f=await yt(e);if(f===null||!gt(f))return;const p=await Lr(e);p===null||p.kind==="human"||await Ye.runNode(l,p,ze())}s(Xn,"exitedNodePass");function X(e){return e===void 0||e==="reconcile"}s(X,"roleRunsLanes");function M(e){return e===void 0||e==="api"}s(M,"roleServesRequests");const Zn=66e4;function eo(e){const l=new Nr().registerAll(Mr(()=>null).filter(c=>c.pattern==="/healthz")),f=s((c,w)=>{const b=(c.url??"/").split("?")[0];if((c.method??"GET").toUpperCase()==="GET"&&b==="/healthz"){l.handle(c,w,null,{class:"person"});return}w.writeHead(404,{"content-type":"application/json; charset=utf-8"}),w.end(JSON.stringify({error:{code:"not_found",message:"this process serves only /healthz",origin:"runtime"}}))},"handler"),p=Le();P(p)&&xe(p);const g=Y(f),o=new Promise((c,w)=>{g.once("error",w),g.listen(p,()=>{g.off("error",w),De(p,384),c()})});let h,y=null,d=o;const u=e.tcp??Te()??me("user").api.tcp;if(u!==void 0&&u!==""){const c=/^(.*):(\d+)$/.exec(u.trim());if(c===null||Number(c[2])>65535)throw new Error(`invalid reconcile probe TCP address: ${u}`);const w=Y(f);w.on("error",b=>m({event:"api.server.failed",level:"error",error:b})),d=o.then(()=>new Promise(b=>{w.once("error",()=>b()),w.listen(Number(c[2]),c[1]===""?"0.0.0.0":c[1],()=>{const E=w.address();y=`${E.address}:${E.port}`,b()})})),h=w}let i=!1;return{ready:d,tcpAddress:s(()=>y,"tcpAddress"),async close(c={}){if(!i){i=!0,await Promise.all([Me(g,new Set,c.graceMs),h===void 0?Promise.resolve():Me(h,new Set,c.graceMs)]);try{P(p)&&xe(p)}catch{}}}}}s(eo,"createProbeServer");const ro="daemon is draining for shutdown and admits no new work";async function to(e){Ie($e(),{recursive:!0,mode:493}),process.platform==="linux"&&De($e(),493);const l=Le();if(P(l))throw new Error(`layout refusal cannot bind occupied socket: ${l}`);const f=Y((d,u)=>{if(d.method==="GET"&&d.url==="/healthz"){u.writeHead(200,{"content-type":"application/json; charset=utf-8"}),u.end(JSON.stringify({ok:!1,daemon_up:!0,store_accessible:!1,brokers_reconciled:!1,startup_phase:"blocked",startup_blocked:"layout_migration_required"}));return}u.writeHead(503,{"content-type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:{code:"layout_migration_required",message:"run crtr sys migrate while the runtime is offline",type:"server_error",origin:"runtime",retryable:!1}}))});await new Promise((d,u)=>{f.once("error",u),f.listen(l,()=>{f.off("error",u),d()})});let p;const g=e.tcp??Te();if(g){const d=/^(.*):(\d+)$/.exec(g);if(!d||Number(d[2])>65535)throw new Error(`invalid refusal TCP address: ${g}`);const u=Y(f.listeners("request")[0]);await new Promise((i,c)=>{u.once("error",c),u.listen(Number(d[2]),d[1],()=>{u.off("error",c),i()})}),p=u}ye();let o;const h=s(()=>(o??=(async()=>{f.closeAllConnections(),p?.closeAllConnections(),await Promise.all([f,p].filter(d=>d!==void 0).map(d=>new Promise((u,i)=>d.close(c=>c?i(c):u())))),Ve(process.pid),process.off("SIGINT",y),process.off("SIGTERM",y)})(),o),"cleanup"),y=s(()=>{h().then(()=>process.exit(0),d=>{process.stderr.write(`[crtrd] layout refusal cleanup failed: ${String(d)}
1
+ var cr=Object.defineProperty;var s=(e,l)=>cr(e,"name",{value:l,configurable:!0});import{applyBootSettings as lr}from"./boot-settings.js";import{startPeerOutbox as dr}from"./peer/outbox.js";import{reportMachineStatus as pr}from"../core/peer/directory.js";import{createPeerRelay as mr}from"./peer/relay-service.js";import{writeFileSync as fr,readFileSync as ur,rmSync as hr,mkdirSync as Ie,existsSync as P,unlinkSync as xe,chmodSync as De}from"node:fs";import{createServer as Y}from"node:http";import{dirname as wr}from"node:path";import{envCrtrdTcp as Te,envDocumentPort as vr}from"../shared/env.js";import{openCanvasConversationStore as gr,serveCanvasConversationStore as yr}from"../core/canvas/sessions.js";import{installConversationStore as Sr}from"../core/conversation-store/index.js";import{pollRunObservers as _r}from"./runs/observer.js";import{randomBytes as Ce}from"node:crypto";import{apiSocketPath as Le,crtrHome as br}from"../core/canvas/paths.js";import{activeAppUsers as kr}from"../core/spaces/users.js";import{ensureAppSpace as Rr,ensureUserFiles as Pr}from"../core/spaces/space.js";import{LAUNCHER_SOCKET as C}from"../launcher/spec.js";import{launcherRequest as N}from"../launcher/client.js";import{installLauncherEventSink as Er}from"./launcher-events.js";import{initializeEmptyLayout as Ir,layoutNeedsMigration as xr,socketDir as $e}from"../core/layout.js";import{migrateLooseKeys as Dr}from"../core/layout-migrate/loose-keys.js";import{relocateProfileFolders as Tr}from"../core/profiles/relocate.js";import{getNode as Cr,getRow as Lr,listNodesForSupervision as Ae,listParkedResidentsWithWakeMail as $r,setFrozen as Ne}from"../core/canvas/index.js";import{createApiServer as Ar,closeServer as Me}from"./api/server.js";import{Router as Nr}from"./api/router.js";import{healthRoutes as Mr}from"./api/handlers/health.js";import{createDocumentListener as Or}from"./api/document-listener.js";import{documentSecret as Gr}from"./api/document-secret.js";import{createAppListener as Fr}from"./api/app-listener.js";import{registerMachineEnvironment as Br}from"../core/environments.js";import{registerBlaxelRunnerFromEnv as Hr}from"../core/secrets/blaxel-register.js";import{markCloudRole as jr,resolvePerson as zr,retireLocalPerson as Ur,setPersonId as qr}from"../core/canvas/person.js";import{backfillNodeApps as Oe,runPermissionsBoot as Wr}from"../core/permissions/boot.js";import{startRunNotices as Jr}from"./run-notices.js";import{startGrantEffects as Kr}from"./reconcilers/grant-effects.js";import{syncPackages as Vr}from"../core/packages/directory-sync.js";import{startActivationDelivery as Yr}from"../core/model-auth/activations.js";import{createGrantSync as Qr,GRANT_SYNC_INTERVAL_S as Ge}from"../core/grants/sync.js";import{sweepSandboxes as Xr}from"../core/grants/on-sync.js";import{rebuildCronExecutions as Zr}from"./cron/run-socket.js";import{hasSyncedGrants as et}from"../core/grants/mirror.js";import{readConfig as me}from"../core/config.js";import{reconcileUndeliveredTickets as rt}from"./human/sweep.js";import{resetHandedOffDeliveries as tt}from"../core/canvas/deliveries.js";import{resetHandedOffDaemonActions as nt}from"../core/canvas/daemon-actions.js";import{sweepReviews as ot}from"./review/sweep.js";import{pidfilePath as fe}from"./pidfile.js";import{rendererWarning as it}from"../core/runtime/package-health.js";import{DEFAULT_INTERVAL_MS as at}from"./supervise-cadence.js";import{createResumeDetector as st}from"./resume-detector.js";import{setFatalFaultAnnouncer as ct}from"../core/canvas/recovery.js";import{BrokerSupervisionReconciler as lt}from"./reconcilers/broker-supervision.js";import{MachineOfflineReconciler as dt}from"./reconcilers/machine-offline.js";import{ControllerDeathReconciler as pt}from"./reconcilers/controller-death.js";import{NodeLifecycleReconciler as mt}from"./reconcilers/node-lifecycle/tick.js";import{NodeDeadlineReconciler as ft}from"./reconcilers/node-deadline.js";import{CronLaneReconciler as ut}from"./reconcilers/cron-lane.js";import{DeliveryLaneReconciler as ht}from"./reconcilers/delivery-lane.js";import{ActionLaneReconciler as wt}from"./reconcilers/action-lane.js";import{endLiveExecution as vt,hasObservedExit as gt,latestExecutionForNode as yt,migrateLegacyExecutionIdentities as St}from"../core/canvas/executions.js";import{revokePriorEpochNodeTokens as _t}from"../core/canvas/node-tokens.js";import{PendingReviewSubmitReconciler as bt}from"./reconcilers/pending-review-submit.js";import{StorageMaintenanceReconciler as kt}from"./reconcilers/storage-maintenance.js";import{StorageDueWorkReconciler as Rt}from"./reconcilers/storage-due-work.js";import{GroupInviteExpiryReconciler as Pt}from"./reconcilers/group-invite-expiry.js";import{PurgeDueWorkReconciler as Et}from"./reconcilers/purge-due-work.js";import{assertLedgerEnv as It}from"../core/ledger/rates.js";import{IdleSandboxReconciler as xt}from"./reconcilers/idle-sandbox.js";import{LedgerSandboxReconciler as Dt}from"./reconcilers/ledger-sandbox.js";import{LedgerStorageReconciler as Tt}from"./reconcilers/ledger-storage.js";import{LedgerR2Reconciler as Ct}from"./reconcilers/ledger-r2.js";import{importedNodesHeld as ue}from"./reconcilers/live-obligation.js";import{ImportLaneReconciler as Lt}from"./reconcilers/import-lane.js";import{BashDeadlineReconciler as $t}from"./reconcilers/bash-deadline.js";import{FaultRetryBackstopReconciler as At}from"./reconcilers/fault-retry-backstop.js";import{StructuredRequestReconciler as Nt}from"./reconcilers/structured-request-lane.js";import{RecipeImageReconciler as Mt,subscribeImageBuilt as Ot}from"./reconcilers/recipe-image.js";import{reconcileStructuredRequestSidecars as Gt}from"./structured-requests/boot.js";import{captureLivenessSnapshot as Fe,capturePidCommand as Ft,captureTeardownSnapshot as Be,isPidAlive as Bt,isAnyPidAlive as He,killProcessTreePids as je}from"../core/canvas/pid.js";import{bindFleet as Ht,boundFleet as ze}from"../core/runtime/fleet.js";import{bindDaemonControl as jt,clearDaemonControl as zt}from"./control.js";import{execDaemon as Ut,spawnDaemon as qt}from"./manage.js";import{reconcileAndMigrateBoot as Wt}from"../core/canvas/boot.js";import{resolveInstallId as Jt}from"../core/canvas/install-id.js";import{setInstallId as Kt}from"../core/runtime/nodes.js";import{claimDaemonOwnership as Vt,daemonOwnershipApplies as Yt,daemonOwnershipClaimed as Qt,releaseDaemonOwnership as Ue}from"../core/canvas/daemon-owner.js";import{canvasDatabaseUrl as Xt,closeAllDbs as he,openDb as Zt,withCanvasWrite as we}from"../core/canvas/db.js";import{importSqliteCanvasIfPresent as en}from"../core/canvas/import-sqlite.js";import{ensurePostgres as rn,ensurePostgresHealthy as tn,stopPostgres as nn,withPostgresStartLock as on}from"./postgres/index.js";import{brokerSignalBus as M}from"./broker-signals/bus.js";import{brokerSignalStreams as an}from"./api/handlers/broker-signals.js";import{setRequestsStartRunObservers as sn}from"./api/handlers/broker-ops.js";import{reconcilePackages as cn}from"../core/graph/package-reconcile.js";import{migrateAppInstalls as ln}from"../core/scoped-state/migrate-app-installs.js";import{publish as dn,readBuiltinSnapshot as pn}from"../core/graph/package-publish.js";import{prewarmRecentRecipes as mn,reapStaleSpares as fn}from"../core/runtime/warm-pool.js";import{DaemonFleet as un}from"./fleet.js";import{copyNodeFilesToRows as hn}from"../core/runtime/first-boot-rows.js";import{BOOT_MIGRATIONS as wn}from"./boot-migrations.js";import{emitEvent as p}from"../core/events/emit.js";import{operationIdContext as k}from"../core/events/operation-id.js";import{bindDaemonEventSource as vn}from"../core/events/source.js";import{activateCanvasImport as gn,MigrationBlockedError as yn,runForcedCanvasImport as Sn}from"../migrations/activation.js";import{adoptInstallPerson as _n,convertLegacyScopedStore as bn,personStoresCopied as kn}from"../core/scoped-state/migrate.js";import{readLegacyUserSnapshot as Rn}from"../core/scoped-state/legacy-profiles.js";import{heldPersons as qe,installPreludeSnapshot as Pn}from"../core/scoped-state/person-store.js";import{loadPersonSettings as ve}from"../core/scoped-state/person-rows.js";import{userScopeRoot as We}from"../core/scope.js";import{brokerCommandDeclaresCanvasHome as ge}from"../core/runtime/broker-ownership.js";import{brokerCommandDeclaresCanvasHome as la}from"../core/runtime/broker-ownership.js";function ye(e){return/ --epoch (\S+) /.exec(e)?.[1]??null}s(ye,"brokerCommandEpoch");const En=5e3,Je=150;async function In(e){const l=Fe();if(l===null)throw p({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness"}}),new Error("prior-epoch broker census could not capture the process table");const f=br(),m=[];for(const[i,c]of l.processes){const w=c.command;if(c.zombie||!w.includes("broker-cli.js")||!ge(w,f)||ye(w)===e)continue;const b=w.trim().split(/\s+/).at(-1)??"";b===""||b.endsWith("broker-cli.js")||m.push({pid:i,nodeId:b})}let g=0;const o=[];for(const i of m){const c=Ft(i.pid);if(c===null||!c.includes("broker-cli.js")||!ge(c,f)||ye(c)===e||c.trim().split(/\s+/).at(-1)!==i.nodeId)continue;const w=Be(i.pid,null);if(!w.reused){try{process.platform==="linux"&&P(C)?await N({operation:"stop",pid:i.pid}):process.kill(i.pid,"SIGTERM")}catch{continue}g++,o.push({pid:i.pid,snap:w})}}const h=Date.now()+En;for(;Date.now()<h&&o.some(i=>He(i.snap.tree.length>0?i.snap.tree:[i.pid]));)await new Promise(i=>setTimeout(i,Je));let y=0;for(const i of o){const c=i.snap.tree.length>0?i.snap.tree:[i.pid];He(c)&&(process.platform==="linux"&&P(C)?await N({operation:"stop",pid:i.pid}):je(c,"SIGKILL",i.snap.identities),y++)}y>0&&await new Promise(i=>setTimeout(i,Je));const d=Fe();if(d===null)throw p({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness",stage:"final"}}),new Error("prior-epoch broker census could not capture the final process table");const u=[];for(const[i,c]of d.processes){const w=c.command;c.zombie||!w.includes("broker-cli.js")||ge(w,f)&&ye(w)!==e&&u.push(i)}if(u.length>0)throw new Error(`prior-epoch broker census could not prove termination of pid(s): ${u.join(", ")}`);p({level:"info",event:"daemon.census.completed",fields:{prior_epoch_brokers:m.length,sigtermed:g,sigkilled:y}})}s(In,"reapPriorEpochBrokers");const xn=5e3;async function Dn(e){const l=Array.from(e.entries());if(l.length===0)return;for(const[o]of l){const h=(await Cr(o))?.status;(h==="active"||h==="idle")&&await Ne(o,new Date().toISOString())}const f=l.map(([,o])=>({pid:o.pid,snap:Be(o.pid,null),exited:o.handle.exited}));for(const o of f)if(!o.snap.reused)try{process.platform==="linux"&&P(C)?await N({operation:"stop",pid:o.pid}):process.kill(o.pid,"SIGTERM")}catch{}const m=new Promise(o=>{setTimeout(o,xn).unref()});await Promise.allSettled(f.map(o=>Promise.race([o.exited.then(()=>{}),m])));const g=[];for(const o of f)Bt(o.pid)&&(process.platform==="linux"&&P(C)?await N({operation:"stop",pid:o.pid}):je(o.snap.tree.length>0?o.snap.tree:[o.pid],"SIGKILL",o.snap.identities),g.push(o));await Promise.all(g.map(o=>o.exited));for(const[o]of l)await vt(o,{reason:"daemon-teardown"});p({level:"info",event:"daemon.fleet_teardown.completed",fields:{brokers:f.length,sigkilled:g.length}})}s(Dn,"teardownFleet");function Q(...e){Ie(wr(fe()),{recursive:!0}),fr(fe(),[process.pid,...e].join(`
2
+ `),"utf8")}s(Q,"writePidfile");function Ke(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}s(Ke,"isMissingPathError");function Ve(e){const l=fe();let f;try{f=ur(l,"utf8")}catch(m){if(Ke(m))return;throw m}if(f.split(`
3
+ `,1)[0].trim()!==String(e))throw new Error(`daemon readiness mirror does not name this invocation (expected pid ${e})`);try{hr(l)}catch(m){if(Ke(m))return;throw m}}s(Ve,"removeOwnedPidfileMirror");const Tn={acceptsDetachedWork:s(()=>!0,"acceptsDetachedWork"),registerDetached:s(e=>{e.catch(()=>{})},"registerDetached")},X=new lt;ct(e=>X.handleFatalFault(e,!1));const Cn=new pt,Ln=new dt,Ye=new mt,$n=new ft,An=new ut,Nn=new ht,Mn=new wt,On=new bt,Gn=new kt,Fn=new Rt,Bn=new Et,Hn=new Pt,jn=new Dt,zn=new xt,Un=new Tt,qn=new Ct,Wn=new Lt,Jn=new $t,Kn=new At,Vn=new Nt,Yn=new Mt;async function Qn(e=Date.now(),l=Tn){const f=ze(),m=await X.runFleetPreamble(f);let g,o,h;try{o=await ue();const d=(await Ae()).filter(i=>!o.has(i.node_id));g=d.filter(i=>i.status==="active"||i.status==="idle"),h=d.filter(i=>i.status==="done"||i.status==="canceled"||i.status==="dead");const u=new Set(h.map(i=>i.node_id));h.push(...(await $r()).filter(i=>!u.has(i.node_id)&&!o.has(i.node_id)))}catch(d){p({level:"error",event:"canvas.node_list.failed",error:d});return}await X.run(e,{rows:g,fleet:f,lifecycle:l,held:o}),await Cn.run(e,{rows:g,held:o}),await Ln.run(e);const y=await Ye.run(e,{rows:[...g,...h],fleet:f});await $n.run(e,o),await Vn.run(e,o),await Yn.run(e,{lifecycle:l}),await An.run(e,{lifecycle:l,held:o}),await Nn.run(e,{lifecycle:l}),await Mn.run(e,{lifecycle:l}),await On.run(e,{lifecycle:l}),await Gn.run(e,{lifecycle:l,fleet:f,held:o}),Fn.run(e,{lifecycle:l}),Bn.run(e,{lifecycle:l}),Hn.run(e,{lifecycle:l}),jn.run(e,{lifecycle:l}),zn.run(e,{lifecycle:l}),Un.run(e,{lifecycle:l}),qn.run(e,{lifecycle:l}),Wn.run(e,{lifecycle:l}),await _r(),Kn.run(e,{fleet:f,lifecycle:l}),await Jn.run(e,{rows:g}),X.warnIfSaturated({fleet:f,lifecycle:l,thresholds:m,frozen:y})}s(Qn,"superviseTick");async function Xn(e,l=Date.now()){if((await ue()).has(e))return;const f=await yt(e);if(f===null||!gt(f))return;const m=await Lr(e);m===null||m.kind==="human"||await Ye.runNode(l,m,ze())}s(Xn,"exitedNodePass");function Z(e){return e===void 0||e==="reconcile"}s(Z,"roleRunsLanes");function O(e){return e===void 0||e==="api"}s(O,"roleServesRequests");const Zn=66e4;function eo(e){const l=new Nr().registerAll(Mr(()=>null).filter(c=>c.pattern==="/healthz")),f=s((c,w)=>{const b=(c.url??"/").split("?")[0];if((c.method??"GET").toUpperCase()==="GET"&&b==="/healthz"){l.handle(c,w,null,{class:"person"});return}w.writeHead(404,{"content-type":"application/json; charset=utf-8"}),w.end(JSON.stringify({error:{code:"not_found",message:"this process serves only /healthz",origin:"runtime"}}))},"handler"),m=Le();P(m)&&xe(m);const g=Y(f),o=new Promise((c,w)=>{g.once("error",w),g.listen(m,()=>{g.off("error",w),De(m,384),c()})});let h,y=null,d=o;const u=e.tcp??Te()??me("user").api.tcp;if(u!==void 0&&u!==""){const c=/^(.*):(\d+)$/.exec(u.trim());if(c===null||Number(c[2])>65535)throw new Error(`invalid reconcile probe TCP address: ${u}`);const w=Y(f);w.on("error",b=>p({event:"api.server.failed",level:"error",error:b})),d=o.then(()=>new Promise(b=>{w.once("error",()=>b()),w.listen(Number(c[2]),c[1]===""?"0.0.0.0":c[1],()=>{const E=w.address();y=`${E.address}:${E.port}`,b()})})),h=w}let i=!1;return{ready:d,tcpAddress:s(()=>y,"tcpAddress"),async close(c={}){if(!i){i=!0,await Promise.all([Me(g,new Set,c.graceMs),h===void 0?Promise.resolve():Me(h,new Set,c.graceMs)]);try{P(m)&&xe(m)}catch{}}}}}s(eo,"createProbeServer");const ro="daemon is draining for shutdown and admits no new work";async function to(e){Ie($e(),{recursive:!0,mode:493}),process.platform==="linux"&&De($e(),493);const l=Le();if(P(l))throw new Error(`layout refusal cannot bind occupied socket: ${l}`);const f=Y((d,u)=>{if(d.method==="GET"&&d.url==="/healthz"){u.writeHead(200,{"content-type":"application/json; charset=utf-8"}),u.end(JSON.stringify({ok:!1,daemon_up:!0,store_accessible:!1,brokers_reconciled:!1,startup_phase:"blocked",startup_blocked:"layout_migration_required"}));return}u.writeHead(503,{"content-type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:{code:"layout_migration_required",message:"run crtr sys migrate while the runtime is offline",type:"server_error",origin:"runtime",retryable:!1}}))});await new Promise((d,u)=>{f.once("error",u),f.listen(l,()=>{f.off("error",u),d()})});let m;const g=e.tcp??Te();if(g){const d=/^(.*):(\d+)$/.exec(g);if(!d||Number(d[2])>65535)throw new Error(`invalid refusal TCP address: ${g}`);const u=Y(f.listeners("request")[0]);await new Promise((i,c)=>{u.once("error",c),u.listen(Number(d[2]),d[1],()=>{u.off("error",c),i()})}),m=u}Q();let o;const h=s(()=>(o??=(async()=>{f.closeAllConnections(),m?.closeAllConnections(),await Promise.all([f,m].filter(d=>d!==void 0).map(d=>new Promise((u,i)=>d.close(c=>c?i(c):u())))),Ve(process.pid),process.off("SIGINT",y),process.off("SIGTERM",y)})(),o),"cleanup"),y=s(()=>{h().then(()=>process.exit(0),d=>{process.stderr.write(`[crtrd] layout refusal cleanup failed: ${String(d)}
4
4
  `),process.exit(1)})},"onSignal");return process.on("SIGINT",y),process.on("SIGTERM",y),h}s(to,"serveLayoutRefusal");async function no(e={}){if(e.role==="machine")return(await import("./machine-daemon.js")).runMachineDaemon();if(xr())return to(e);Ir();const l=s(t=>{process.stderr.write(`[crtrd] ${t}
5
- `)},"logPostgres"),f=!!process.env.CRTR_TEST_PG_URL,p=Yt(e.role);sn(X(e.role));const g=s(async()=>p?await Vt(Ce(16).toString("hex")):{claimed:!0,claim:{pid:process.pid,pid_identity:"",token:Ce(16).toString("hex")}},"claimOwnership"),{database:o,ownership:h}=f?{database:{url:await Xt()},ownership:await g()}:await on(async()=>({database:await rn({log:l,startLockHeld:!0}),ownership:await g()}));if(!h.claimed){if(h.reason==="incumbent_alive")process.stderr.write(`[crtrd] already running (pid ${h.incumbentPid??"?"})
5
+ `)},"logPostgres"),f=!!process.env.CRTR_TEST_PG_URL,m=Yt(e.role);sn(Z(e.role));const g=s(async()=>m?await Vt(Ce(16).toString("hex")):{claimed:!0,claim:{pid:process.pid,pid_identity:"",token:Ce(16).toString("hex")}},"claimOwnership"),{database:o,ownership:h}=f?{database:{url:await Xt()},ownership:await g()}:await on(async()=>({database:await rn({log:l,startLockHeld:!0}),ownership:await g()}));if(!h.claimed){if(h.reason==="incumbent_alive")process.stderr.write(`[crtrd] already running (pid ${h.incumbentPid??"?"})
6
6
  `);else{const t=[h.incumbentPid!==void 0?`pid ${h.incumbentPid}`:void 0,h.verdict!==void 0?`verdict ${h.verdict}`:void 0].filter(v=>v!==void 0),a=t.length>0?` (${t.join(", ")})`:"";process.stderr.write(`[crtrd] claim lost: ${h.reason}${a}
7
- `),h.reason==="own_identity_indeterminate"&&process.stderr.write("[crtrd] cannot read its own process identity. crouter needs /proc on Linux, or the `ps` command elsewhere (Debian/Ubuntu: apt-get install procps).\n"),(h.reason==="own_identity_indeterminate"||h.reason==="incumbent_malformed")&&(process.exitCode=1)}return async()=>{}}const y=h.claim;let d=null,u=null,i=null,c=null,w,b="";try{p&&await In(y.token);for(const r of Tr())process.stderr.write(`[crtrd] ${r}
7
+ `),h.reason==="own_identity_indeterminate"&&process.stderr.write("[crtrd] cannot read its own process identity. crouter needs /proc on Linux, or the `ps` command elsewhere (Debian/Ubuntu: apt-get install procps).\n"),(h.reason==="own_identity_indeterminate"||h.reason==="incumbent_malformed")&&(process.exitCode=1)}return async()=>{}}const y=h.claim;let d=null,u=null,i=null,c=null,w,b="";try{m&&await In(y.token);for(const r of Tr())process.stderr.write(`[crtrd] ${r}
8
8
  `);for(const r of await Dr())process.stderr.write(`[crtrd] ${r}
9
- `);await Zt(),await en(o.url,l);const t=e.role===void 0&&!await kn();let a=null;t&&(bn({kind:"user",root:We()}),a=Rn(We())),e.role===void 0&&Pn(a??{profiles:[],defaults:{},settings:{},state:{},apps:{}}),await N.listen(o.url);const v=s(r=>{we(r).catch(n=>m({level:"error",event:"daemon.settings.reload_failed",error:n}))},"reloadPerson");if(w=await N.subscribe(r=>{qe().includes(r)&&v(r)},{kinds:["settings"],onListenStart:s(()=>{for(const r of qe())v(r)},"onListenStart")}),e.role!==void 0&&jr(),e.role!==void 0){let r;try{r=mn()}catch(_){m({level:"error",event:"daemon.packages.snapshot_failed",error:_})}const n=await he(async _=>(await Oe(_),r===void 0?void 0:await dn(_,r,"release")));c=await he(async _=>await ln(_));for(const _ of n?.invalid??[])process.stderr.write(`[crtrd] package file is not a document: ${_.path}: ${_.error}
10
- `)}else{d=await zr(),d!==null&&(qr(d.id),await we(d.id));const r=await he(async n=>(await Oe(n),d===null?null:await cn(n)));if(r!==null){for(const n of r.conflicts)process.stderr.write(`[crtrd] plugin documents not reconciled: ${n.message}
9
+ `);await Zt(),await en(o.url,l);const t=e.role===void 0&&!await kn();let a=null;t&&(bn({kind:"user",root:We()}),a=Rn(We())),e.role===void 0&&Pn(a??{profiles:[],defaults:{},settings:{},state:{},apps:{}}),await M.listen(o.url);const v=s(r=>{ve(r).catch(n=>p({level:"error",event:"daemon.settings.reload_failed",error:n}))},"reloadPerson");if(w=await M.subscribe(r=>{qe().includes(r)&&v(r)},{kinds:["settings"],onListenStart:s(()=>{for(const r of qe())v(r)},"onListenStart")}),e.role!==void 0&&jr(),e.role!==void 0){let r;try{r=pn()}catch(_){p({level:"error",event:"daemon.packages.snapshot_failed",error:_})}const n=await we(async _=>(await Oe(_),r===void 0?void 0:await dn(_,r,"release")));c=await we(async _=>await ln(_));for(const _ of n?.invalid??[])process.stderr.write(`[crtrd] package file is not a document: ${_.path}: ${_.error}
10
+ `)}else{d=await zr(),d!==null&&(qr(d.id),await ve(d.id));const r=await we(async n=>(await Oe(n),d===null?null:await cn(n)));if(r!==null){for(const n of r.conflicts)process.stderr.write(`[crtrd] plugin documents not reconciled: ${n.message}
11
11
  `);for(const n of r.invalid)process.stderr.write(`[crtrd] package file is not a document: ${n.path}: ${n.error}
12
12
  `);for(const n of r.quarantined)process.stderr.write(`[crtrd] plugin "${n.name}" has a damaged ${n.file} (${n.reason}); ${n.movedTo!==void 0?`moved to ${n.movedTo}`:"left in place and skipped"}
13
13
  `);for(const n of r.kinds.refused)process.stderr.write(`[crtrd] plugin "${n.plugin}" kind ${n.kind} not registered: ${n.message}
14
14
  `);for(const n of r.kinds.invalid)process.stderr.write(`[crtrd] plugin "${n.plugin}" declares invalid object kinds or scopes; no kinds registered and no app token: ${n.error}
15
- `)}}if(b=await Jt(),Kt(b),e.role===void 0&&d!==null){if(await _n(d.id),process.platform==="darwin"){const{readConfig:r,updateConfig:n}=await import("../core/config.js");if(r("user").paths?.user_files===void 0){const{homedir:_}=await import("node:os");await n("user",Ee=>{Ee.paths??={},Ee.paths.user_files??=_()})}}u=await Ur(),u.joinedFrom!==null&&await we(u.person),await lr(),i=await Wr()}if(process.platform==="linux"&&P(C)&&(Er(),await A({operation:"users.sync",users:await kr()})),p){await _t(y.token);const r=await hn();Object.values(r).some(n=>n>0)&&process.stderr.write(`[crtrd] node files copied into rows: ${JSON.stringify(r)}
16
- `)}}catch(t){await N.close();try{if(p){const{released:a}=await Ue(y);if(!a)throw new Error("daemon ownership claim was not released")}await ue()}catch(a){throw new AggregateError([t,a],"daemon startup failed and cleanup also failed")}throw t}let E=!0,Z,j=Promise.resolve(),ee=!1,z,re,te,ne,L;const U=new Set;let oe=!1,Se=!1,I,x,ie,q=!1,W,O,G,F,B,ae,se,ce,le;const Qe=st();let D,S={phase:"initializing",message:"daemon startup is running the canvas import and normal services are unavailable",blockerPaths:[]},$="initial startup activation",Xe=null;function Ze(){return S.phase==="ready"?null:{phase:S.phase,message:S.message,blockerPaths:S.blockerPaths}}s(Ze,"startupBlock");function R(t){U.add(t),t.finally(()=>{U.delete(t)}).catch(()=>{})}s(R,"registerDetached");const er={acceptsDetachedWork:s(()=>E,"acceptsDetachedWork"),registerDetached:R};async function rr(){try{E=!1,an.close(),re?.(),re=void 0,te?.(),w?.(),te=void 0,ne?.(),ne=void 0,ce?.(),ce=void 0,await N.close(),z!==void 0&&(clearInterval(z),z=void 0),G!==void 0&&(clearInterval(G),G=void 0),F!==void 0&&(clearInterval(F),F=void 0),le?.(),le=void 0;let t;do t=j,await t;while(t!==j);for(;U.size>0;)await Promise.allSettled([...U]);if(L!==void 0&&(p&&await Dn(L),await L.exitsSettled(),L.dispose()),ie!==void 0&&await ie.close(),x!==void 0&&!q&&(q=!0,await x.close()),ae?.(),ae=void 0,se?.(),se=void 0,B!==void 0){const a=B;B=void 0,await a.stop()}if(O!==void 0){const a=O;O=void 0,await a.close()}if(W!==void 0){const a=W;W=void 0,await a.close()}if(oe||(Ve(process.pid),oe=!0),oe&&!Se){if(p){const{released:a}=await Ue(y);if(!a)throw new Error("daemon ownership claim was not released")}Se=!0,await ue()}}finally{zt(),process.off("SIGINT",ke),process.off("SIGTERM",Re),process.off("exit",Pe)}}s(rr,"cleanupAttempt");const J=1e3;let _e=!1;function tr(){if(e.role!==void 0)throw new Error(`a ${e.role} daemon never hands over to a successor: its orchestrator replaces it`);return _e?{graceMs:J}:(_e=!0,k.fresh(()=>{m({level:"info",event:"daemon.handover.armed",fields:{pid:process.pid,grace_ms:J}})}),setTimeout(()=>{nr()},J),{graceMs:J})}s(tr,"requestHandover");async function nr(){try{await T()}catch(t){const a=t instanceof Error?t.stack??t.message:String(t);process.stderr.write(`[crtrd] handover cleanup failed:
15
+ `)}}if(b=await Jt(),Kt(b),e.role===void 0&&d!==null){if(await _n(d.id),process.platform==="darwin"){const{readConfig:r,updateConfig:n}=await import("../core/config.js");if(r("user").paths?.user_files===void 0){const{homedir:_}=await import("node:os");await n("user",Ee=>{Ee.paths??={},Ee.paths.user_files??=_()})}}u=await Ur(),u.joinedFrom!==null&&await ve(u.person),await lr(),i=await Wr()}if(process.platform==="linux"&&P(C)&&(Er(),await N({operation:"users.sync",users:await kr()})),m){await _t(y.token);const r=await hn();Object.values(r).some(n=>n>0)&&process.stderr.write(`[crtrd] node files copied into rows: ${JSON.stringify(r)}
16
+ `)}}catch(t){await M.close();try{if(m){const{released:a}=await Ue(y);if(!a)throw new Error("daemon ownership claim was not released")}await he()}catch(a){throw new AggregateError([t,a],"daemon startup failed and cleanup also failed")}throw t}let E=!0,ee,j=Promise.resolve(),re=!1,z,te,ne,oe,L;const U=new Set;let ie=!1,Se=!1,x,I,ae,q=!1,W,$,G,F,B,se,ce,le,de;const Qe=st();let D,S={phase:"initializing",message:"daemon startup is running the canvas import and normal services are unavailable",blockerPaths:[]},A="initial startup activation",Xe=null;function Ze(){return S.phase==="ready"?null:{phase:S.phase,message:S.message,blockerPaths:S.blockerPaths}}s(Ze,"startupBlock");function R(t){U.add(t),t.finally(()=>{U.delete(t)}).catch(()=>{})}s(R,"registerDetached");const er={acceptsDetachedWork:s(()=>E,"acceptsDetachedWork"),registerDetached:R};async function rr(){try{E=!1,an.close(),te?.(),te=void 0,ne?.(),w?.(),ne=void 0,oe?.(),oe=void 0,le?.(),le=void 0,await M.close(),z!==void 0&&(clearInterval(z),z=void 0),G!==void 0&&(clearInterval(G),G=void 0),F!==void 0&&(clearInterval(F),F=void 0),de?.(),de=void 0;let t;do t=j,await t;while(t!==j);for(;U.size>0;)await Promise.allSettled([...U]);if(L!==void 0&&(m&&await Dn(L),await L.exitsSettled(),L.dispose()),ae!==void 0&&await ae.close(),I!==void 0&&!q&&(q=!0,await I.close()),se?.(),se=void 0,ce?.(),ce=void 0,B!==void 0){const a=B;B=void 0,await a.stop()}if($!==void 0){const a=$;$=void 0,await a.close()}if(W!==void 0){const a=W;W=void 0,await a.close()}if(ie||(Ve(process.pid),ie=!0),ie&&!Se){if(m){const{released:a}=await Ue(y);if(!a)throw new Error("daemon ownership claim was not released")}Se=!0,await he()}}finally{zt(),process.off("SIGINT",ke),process.off("SIGTERM",Re),process.off("exit",Pe)}}s(rr,"cleanupAttempt");const J=1e3;let _e=!1;function tr(){if(e.role!==void 0)throw new Error(`a ${e.role} daemon never hands over to a successor: its orchestrator replaces it`);return _e?{graceMs:J}:(_e=!0,k.fresh(()=>{p({level:"info",event:"daemon.handover.armed",fields:{pid:process.pid,grace_ms:J}})}),setTimeout(()=>{nr()},J),{graceMs:J})}s(tr,"requestHandover");async function nr(){try{await T()}catch(t){const a=t instanceof Error?t.stack??t.message:String(t);process.stderr.write(`[crtrd] handover cleanup failed:
17
17
  ${a}
18
- `),process.exit(1)}try{process.platform==="linux"&&P(C)&&(await A({operation:"daemon.handover"}),process.exit(0)),process.pid===1&&await Ut();const t=await qt({waitForJoinLock:!0});k.fresh(()=>{m({level:"info",event:"daemon.handover.completed",fields:{predecessor_pid:process.pid,successor_pid:t.pid??t.existing_pid??null,spawned:t.started}})})}catch(t){k.fresh(()=>{m({level:"error",event:"daemon.handover.successor_failed",error:t})});const a=t instanceof Error?t.message:String(t);process.stderr.write(`[crtrd] handover successor failed to start: ${a}
19
- `),process.exit(1)}process.exit(0)}s(nr,"performHandover");function T(){if(I!==void 0)return I;const t=rr();return I=t,t.then(()=>{I===t&&(I=void 0)},()=>{I===t&&(I=void 0)}),t}s(T,"requestCleanup");async function or(){S={phase:"initializing",message:ro,blockerPaths:[]},x!==void 0&&!q&&(q=!0,await x.close({graceMs:Zn}))}s(or,"drainApi");async function be(t){try{t==="SIGTERM"&&e.role==="api"&&await or(),await T(),await nn({claimed:s(async()=>{try{return p&&await Qt()}finally{await ue()}},"claimed")}),process.exit(0)}catch(a){process.exitCode=1;const v=a instanceof Error?a.stack??`${a.name}: ${a.message}`:String(a);process.stderr.write(`[crtrd] ${t} cleanup failed:
18
+ `),process.exit(1)}try{process.platform==="linux"&&P(C)&&(await N({operation:"daemon.handover"}),process.exit(0)),process.pid===1&&await Ut();const t=await qt({waitForJoinLock:!0});k.fresh(()=>{p({level:"info",event:"daemon.handover.completed",fields:{predecessor_pid:process.pid,successor_pid:t.pid??t.existing_pid??null,spawned:t.started}})})}catch(t){k.fresh(()=>{p({level:"error",event:"daemon.handover.successor_failed",error:t})});const a=t instanceof Error?t.message:String(t);process.stderr.write(`[crtrd] handover successor failed to start: ${a}
19
+ `),process.exit(1)}process.exit(0)}s(nr,"performHandover");function T(){if(x!==void 0)return x;const t=rr();return x=t,t.then(()=>{x===t&&(x=void 0)},()=>{x===t&&(x=void 0)}),t}s(T,"requestCleanup");async function or(){S={phase:"initializing",message:ro,blockerPaths:[]},I!==void 0&&!q&&(q=!0,await I.close({graceMs:Zn}))}s(or,"drainApi");async function be(t){try{t==="SIGTERM"&&e.role==="api"&&await or(),await T(),await nn({claimed:s(async()=>{try{return m&&await Qt()}finally{await he()}},"claimed")}),process.exit(0)}catch(a){process.exitCode=1;const v=a instanceof Error?a.stack??`${a.name}: ${a.message}`:String(a);process.stderr.write(`[crtrd] ${t} cleanup failed:
20
20
  ${v}
21
- `),process.exit(1)}}s(be,"handleSignal");function ke(){be("SIGINT")}s(ke,"onSigint");function Re(){be("SIGTERM")}s(Re,"onSigterm");function Pe(){T().catch(()=>{})}s(Pe,"onExit");async function K(t){E&&(j=j.then(t).then(()=>{},a=>{k.fresh(()=>{m({level:"error",event:"daemon.lane_job.failed",error:a})})}))}s(K,"enqueue");async function V(){!E||ee||(Qe.check()&&D&&(m({level:"info",event:"daemon.resume.detected"}),R(D().catch(()=>{}))),ee=!0,await K(async()=>{if(ee=!1,!!E)try{f||await tn({log:l}),await Qn(Date.now(),er)}catch(t){k.fresh(()=>{m({level:"error",event:"daemon.tick.failed",error:t})})}}))}s(V,"enqueueTick");let H=null;async function ir(){if(H!==null)throw{status:500,code:"admission_failed",message:`daemon admission previously failed: ${H instanceof Error?H.message:String(H)}`};if(S.phase==="ready")return{admitted:!1,already_admitted:!0,startup_phase:"ready"};if(S.phase!=="prepared"&&S.phase!=="recovering")throw{status:409,code:"not_prepared",message:S.message};const t=S.phase==="prepared";try{return await de(),S={phase:"ready",message:"",blockerPaths:[]},t?{admitted:!0,already_admitted:!1,startup_phase:"ready"}:{admitted:!1,already_admitted:!0,startup_phase:"ready"}}catch(a){throw H=a,{status:500,code:"admission_failed",message:`daemon admission failed: ${a instanceof Error?a.message:String(a)}`}}}s(ir,"admitStartup");async function ar(t){if($!==null)throw{status:409,code:"migration_in_progress",message:`the canvas import is already running (${$})`};$="repair";try{const a=await Sn({dryRun:t.dryRun});if(t.dryRun||a.pending||S.phase!=="blocked")return{result:a,resumed:!1};if(e.prepare)return S={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]},{result:a,resumed:!1};try{return await de(),S={phase:"ready",message:"",blockerPaths:[]},{result:a,resumed:!0}}catch(v){const r=v instanceof Error?v.message:String(v);return setTimeout(()=>{T().catch(()=>{})},1e3),{result:a,resumed:!1,resumeError:r}}}finally{$=null}}s(ar,"repairMigrations");async function sr(){Z=e.intervalMs??at;const t=y.token;L=new un({epoch:t,enqueue:K}),Ht(L),S={phase:"recovering",message:"daemon startup recovery is running and normal services are unavailable",blockerPaths:[]},k.fresh(()=>{m({level:"info",event:"daemon.started",fields:{pid:process.pid,interval_ms:Z}})});const a=b;k.fresh(()=>{m({level:"info",event:"daemon.install_id.resolved",fields:{install_id:a}})});const v=await Br(a);if(k.fresh(()=>{m({level:"info",event:"daemon.environment.registered",fields:{environment_id:v.environmentId,created:v.created}})}),k.fresh(()=>{let r;try{r=it()}catch{return}r!==null&&m({level:"warn",event:"daemon.startup.warning",fields:{stage:"termrender",warning:r.slice(0,2048)}})}),It(),e.role!==void 0&&!process.env.CRTR_DIRECTORY_URL)throw new Error("CRTR_DIRECTORY_URL must be set on a cloud role (--role api|reconcile): it names the directory this deployment mints tokens against");if(e.role!==void 0&&Hr(),!X(e.role)){S={phase:"ready",message:"",blockerPaths:[]};return}if(await k.fresh(async()=>{await ot(),await rt(),await tt(Date.now()),await nt(Date.now())}),e.role===void 0&&await k.fresh(async()=>{const{reconcile:r,migrated:n}=await Wt(St);r.changed&&m({level:"info",event:"daemon.boot_change.reconciled",fields:{cleared_count:r.cleared.length,same_boot_proven:r.sameBootProven}}),n.length>0&&m({level:"info",event:"daemon.pid_identity.migrated",fields:{migrated_count:n.length}})}),await k.fresh(async()=>{const r=await fe();for(const n of await Ae())r.has(n.node_id)||n.status!=="active"||n.pi_pid!=null||n.frozen_at!=null||n.respawn_not_before!=null||(await Ne(n.node_id,new Date().toISOString()),m({level:"warn",event:"daemon.startup.launch_debt_recorded",node_id:n.node_id}))}),await k.fresh(async()=>{await Gt();for(const r of wn){const n=await r.apply();n.changed&&m({level:"info",event:"daemon.boot_migration.applied",fields:{migration:r.id,...n.summary}})}}),R(Zr()),D){const r=s(()=>{R(D().catch(()=>{})),R(mr().then(n=>B?.observe(n)).then(()=>{},n=>{m({level:"warn",event:"daemon.peer.status_failed",error:n})}))},"refresh");R(Xr().then(({completion:n})=>n).catch(n=>{m({level:"error",event:"daemon.grants.sweep_failed",error:n})})),r(),G=setInterval(r,Ge*1e3),G.unref(),le=dr({joined:!0,register:R})}await K(async()=>{await fn(),await pn()}),z=setInterval(()=>{V().catch(r=>m({level:"error",event:"daemon.tick.failed",error:r}))},Z),re=await Ot(()=>{V().catch(r=>m({level:"error",event:"daemon.tick.failed",error:r}))}),te=await N.subscribe(()=>{V().catch(r=>m({level:"error",event:"daemon.tick.failed",error:r}))},{kinds:["spend_limits"]}),ne=await N.subscribe(r=>{K(()=>k.fresh(()=>Xn(r)))},{kinds:["execution_exit"]}),await V(),e.role===void 0&&import("../commands/sys/import/move.js").then(({settleMoveAtDaemonStart:r})=>r(()=>!E,n=>m({level:"warn",event:"daemon.move.settle_failed",error:n}))).catch(r=>m({level:"warn",event:"daemon.move.settle_failed",error:r}))}s(sr,"completeStartup");function de(){return Xe??=sr().catch(t=>{throw S={phase:"initializing",message:"daemon startup recovery failed and normal services are unavailable",blockerPaths:[]},t})}s(de,"resumeStartup");try{process.on("SIGINT",ke),process.on("SIGTERM",Re),process.on("exit",Pe),vn(),d!==null&&m({level:"info",event:"daemon.person.resolved",fields:{person_id:d.id,source:d.source}}),c!==null&&!c.alreadyDone&&m({level:"info",event:"daemon.packages.install_migration_done",fields:{moved:c.moved,discarded:c.discarded,people:c.people}}),i!==null&&m({level:"info",event:"daemon.permissions.boot",fields:{...i}}),u!==null&&m({level:"info",event:"daemon.person.retired",fields:{person_id:u.person,joined_from:u.joinedFrom,retired:u.retired,columns:u.columns}}),M(e.role)?W=await yr():Sr(gr());const t=y.token;jt({epoch:t,requestHandover:tr,registerDetached:R,startupBlock:Ze,admitStartup:ir,repairMigrations:ar}),ye(),x=M(e.role)?Ar({tcp:e.tcp}):eo(e),await x.ready,ye(x.tcpAddress());const a=vr()??me("user").document_port;if(M(e.role)){const r=Or(a,Gr());try{await r.ready,ie=r}catch(n){m({level:"warn",event:"daemon.document_listener.bind_failed",fields:{port:a,error:n instanceof Error?n.message:String(n)}})}}const v=me("user").runtime;if(v?.issuer&&(D=Qr(v.issuer,R),v.unsandboxed===!0&&(B=pr({syncGrants:D}))),e.role==="api"){const r=s(()=>R(import("../core/providers/bundles.js").then(_=>_.syncProviderBundles()).catch(_=>{m({level:"error",event:"daemon.providers.bundle_sync_failed",error:_})})),"bundleTick"),n=s(()=>{R(Vr().catch(_=>{m({level:"error",event:"daemon.packages.sync_failed",error:_})})),r()},"packageTick");n(),F=setInterval(n,Ge*1e3),F.unref()}if(M(e.role)&&(ae=await Jr()),X(e.role)&&(se=Yr()),ce=await Kr({serves:M(e.role),runsLanes:X(e.role)}),v?.unsandboxed===!0&&v.listener!==void 0&&m({level:"warn",event:"daemon.app_listener.refused_unsandboxed",fields:{reason:"runtime.unsandboxed is set; runtime.listener is ignored"}}),M(e.role)&&v!==void 0&&v.listener!==void 0&&v.unsandboxed!==!0&&(O=await Fr(v,async()=>await et(v.issuer.replace(/\/$/,"")),D),await O.ready),e.role===void 0)try{await gn()}catch(r){if($=null,r instanceof yn)return S={phase:"blocked",message:r.message,blockerPaths:r.blockerPaths},T;throw r}process.platform==="linux"&&P(C)&&(Pr(),await Rr("app:terminal"));try{e.prepare?S={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]}:(await de(),S={phase:"ready",message:"",blockerPaths:[]})}finally{$=null}return T}catch(t){try{await T()}catch(a){throw new AggregateError([t,a],"daemon startup failed and cleanup also failed")}throw t}}s(no,"runDaemon");var aa=no;export{Zn as API_DRAIN_GRACE_MS,la as brokerCommandDeclaresCanvasHome,ge as brokerCommandEpoch,aa as default,Xn as exitedNodePass,X as roleRunsLanes,M as roleServesRequests,no as runDaemon,Qn as superviseTick,Dn as teardownFleet};
21
+ `),process.exit(1)}}s(be,"handleSignal");function ke(){be("SIGINT")}s(ke,"onSigint");function Re(){be("SIGTERM")}s(Re,"onSigterm");function Pe(){T().catch(()=>{})}s(Pe,"onExit");async function K(t){E&&(j=j.then(t).then(()=>{},a=>{k.fresh(()=>{p({level:"error",event:"daemon.lane_job.failed",error:a})})}))}s(K,"enqueue");async function V(){!E||re||(Qe.check()&&D&&(p({level:"info",event:"daemon.resume.detected"}),R(D().catch(()=>{}))),re=!0,await K(async()=>{if(re=!1,!!E)try{f||await tn({log:l}),await Qn(Date.now(),er)}catch(t){k.fresh(()=>{p({level:"error",event:"daemon.tick.failed",error:t})})}}))}s(V,"enqueueTick");let H=null;async function ir(){if(H!==null)throw{status:500,code:"admission_failed",message:`daemon admission previously failed: ${H instanceof Error?H.message:String(H)}`};if(S.phase==="ready")return{admitted:!1,already_admitted:!0,startup_phase:"ready"};if(S.phase!=="prepared"&&S.phase!=="recovering")throw{status:409,code:"not_prepared",message:S.message};const t=S.phase==="prepared";try{return await pe(),S={phase:"ready",message:"",blockerPaths:[]},t?{admitted:!0,already_admitted:!1,startup_phase:"ready"}:{admitted:!1,already_admitted:!0,startup_phase:"ready"}}catch(a){throw H=a,{status:500,code:"admission_failed",message:`daemon admission failed: ${a instanceof Error?a.message:String(a)}`}}}s(ir,"admitStartup");async function ar(t){if(A!==null)throw{status:409,code:"migration_in_progress",message:`the canvas import is already running (${A})`};A="repair";try{const a=await Sn({dryRun:t.dryRun});if(t.dryRun||a.pending||S.phase!=="blocked")return{result:a,resumed:!1};if(e.prepare)return S={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]},{result:a,resumed:!1};try{return await pe(),S={phase:"ready",message:"",blockerPaths:[]},{result:a,resumed:!0}}catch(v){const r=v instanceof Error?v.message:String(v);return setTimeout(()=>{T().catch(()=>{})},1e3),{result:a,resumed:!1,resumeError:r}}}finally{A=null}}s(ar,"repairMigrations");async function sr(){ee=e.intervalMs??at;const t=y.token;L=new un({epoch:t,enqueue:K}),Ht(L),S={phase:"recovering",message:"daemon startup recovery is running and normal services are unavailable",blockerPaths:[]},k.fresh(()=>{p({level:"info",event:"daemon.started",fields:{pid:process.pid,interval_ms:ee}})});const a=b;k.fresh(()=>{p({level:"info",event:"daemon.install_id.resolved",fields:{install_id:a}})});const v=await Br(a);if(k.fresh(()=>{p({level:"info",event:"daemon.environment.registered",fields:{environment_id:v.environmentId,created:v.created}})}),k.fresh(()=>{let r;try{r=it()}catch{return}r!==null&&p({level:"warn",event:"daemon.startup.warning",fields:{stage:"termrender",warning:r.slice(0,2048)}})}),It(),e.role!==void 0&&!process.env.CRTR_DIRECTORY_URL)throw new Error("CRTR_DIRECTORY_URL must be set on a cloud role (--role api|reconcile): it names the directory this deployment mints tokens against");if(e.role!==void 0&&Hr(),!Z(e.role)){S={phase:"ready",message:"",blockerPaths:[]};return}if(await k.fresh(async()=>{await ot(),await rt(),await tt(Date.now()),await nt(Date.now())}),e.role===void 0&&await k.fresh(async()=>{const{reconcile:r,migrated:n}=await Wt(St);r.changed&&p({level:"info",event:"daemon.boot_change.reconciled",fields:{cleared_count:r.cleared.length,same_boot_proven:r.sameBootProven}}),n.length>0&&p({level:"info",event:"daemon.pid_identity.migrated",fields:{migrated_count:n.length}})}),await k.fresh(async()=>{const r=await ue();for(const n of await Ae())r.has(n.node_id)||n.status!=="active"||n.pi_pid!=null||n.frozen_at!=null||n.respawn_not_before!=null||(await Ne(n.node_id,new Date().toISOString()),p({level:"warn",event:"daemon.startup.launch_debt_recorded",node_id:n.node_id}))}),await k.fresh(async()=>{await Gt();for(const r of wn){const n=await r.apply();n.changed&&p({level:"info",event:"daemon.boot_migration.applied",fields:{migration:r.id,...n.summary}})}}),R(Zr()),D){const r=s(()=>{R(D().catch(()=>{})),R(pr().then(n=>B?.observe(n)).then(()=>{},n=>{p({level:"warn",event:"daemon.peer.status_failed",error:n})}))},"refresh");R(Xr().then(({completion:n})=>n).catch(n=>{p({level:"error",event:"daemon.grants.sweep_failed",error:n})})),r(),G=setInterval(r,Ge*1e3),G.unref(),de=dr({joined:!0,register:R})}await K(async()=>{await fn(),await mn()}),z=setInterval(()=>{V().catch(r=>p({level:"error",event:"daemon.tick.failed",error:r}))},ee),te=await Ot(()=>{V().catch(r=>p({level:"error",event:"daemon.tick.failed",error:r}))}),ne=await M.subscribe(()=>{V().catch(r=>p({level:"error",event:"daemon.tick.failed",error:r}))},{kinds:["spend_limits"]}),oe=await M.subscribe(r=>{K(()=>k.fresh(()=>Xn(r)))},{kinds:["execution_exit"]}),await V(),e.role===void 0&&import("../commands/sys/import/move.js").then(({settleMoveAtDaemonStart:r})=>r(()=>!E,n=>p({level:"warn",event:"daemon.move.settle_failed",error:n}))).catch(r=>p({level:"warn",event:"daemon.move.settle_failed",error:r}))}s(sr,"completeStartup");function pe(){return Xe??=sr().catch(t=>{throw S={phase:"initializing",message:"daemon startup recovery failed and normal services are unavailable",blockerPaths:[]},t})}s(pe,"resumeStartup");try{process.on("SIGINT",ke),process.on("SIGTERM",Re),process.on("exit",Pe),vn(),d!==null&&p({level:"info",event:"daemon.person.resolved",fields:{person_id:d.id,source:d.source}}),c!==null&&!c.alreadyDone&&p({level:"info",event:"daemon.packages.install_migration_done",fields:{moved:c.moved,discarded:c.discarded,people:c.people}}),i!==null&&p({level:"info",event:"daemon.permissions.boot",fields:{...i}}),u!==null&&p({level:"info",event:"daemon.person.retired",fields:{person_id:u.person,joined_from:u.joinedFrom,retired:u.retired,columns:u.columns}}),O(e.role)?W=await yr():Sr(gr());const t=y.token;jt({epoch:t,requestHandover:tr,registerDetached:R,startupBlock:Ze,admitStartup:ir,repairMigrations:ar}),Q(),I=O(e.role)?Ar({tcp:e.tcp}):eo(e),await I.ready,Q(I.tcpAddress()??"");const a=vr()??me("user").document_port;if(O(e.role)){const r=Or(a,Gr());try{await r.ready,ae=r}catch(n){p({level:"warn",event:"daemon.document_listener.bind_failed",fields:{port:a,error:n instanceof Error?n.message:String(n)}})}}const v=me("user").runtime;if(v?.issuer&&(D=Qr(v.issuer,R),v.unsandboxed===!0&&(B=mr({syncGrants:D}))),e.role==="api"){const r=s(()=>R(import("../core/providers/bundles.js").then(_=>_.syncProviderBundles()).catch(_=>{p({level:"error",event:"daemon.providers.bundle_sync_failed",error:_})})),"bundleTick"),n=s(()=>{R(Vr().catch(_=>{p({level:"error",event:"daemon.packages.sync_failed",error:_})})),r()},"packageTick");n(),F=setInterval(n,Ge*1e3),F.unref()}if(O(e.role)&&(se=await Jr()),Z(e.role)&&(ce=Yr()),le=await Kr({serves:O(e.role),runsLanes:Z(e.role)}),v?.unsandboxed===!0&&v.listener!==void 0&&p({level:"warn",event:"daemon.app_listener.refused_unsandboxed",fields:{reason:"runtime.unsandboxed is set; runtime.listener is ignored"}}),O(e.role)&&v!==void 0&&v.listener!==void 0&&v.unsandboxed!==!0&&($=await Fr(v,async()=>await et(v.issuer.replace(/\/$/,"")),D),await $.ready,Q(I.tcpAddress()??"",`${v.listener.address}:${$.port()}`)),e.role===void 0)try{await gn()}catch(r){if(A=null,r instanceof yn)return S={phase:"blocked",message:r.message,blockerPaths:r.blockerPaths},T;throw r}process.platform==="linux"&&P(C)&&(Pr(),await Rr("app:terminal"));try{e.prepare?S={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]}:(await pe(),S={phase:"ready",message:"",blockerPaths:[]})}finally{A=null}return T}catch(t){try{await T()}catch(a){throw new AggregateError([t,a],"daemon startup failed and cleanup also failed")}throw t}}s(no,"runDaemon");var aa=no;export{Zn as API_DRAIN_GRACE_MS,la as brokerCommandDeclaresCanvasHome,ye as brokerCommandEpoch,aa as default,Xn as exitedNodePass,Z as roleRunsLanes,O as roleServesRequests,no as runDaemon,Qn as superviseTick,Dn as teardownFleet};
@@ -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.698",
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.698",
160
+ "@north-light/plugin": "0.3.698",
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",