@north-light/cli 0.3.667 → 0.3.668
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/client.d.ts +2 -1
- package/dist/api/client.js +1 -1
- package/dist/api/dto/bash-jobs.d.ts +3 -0
- package/dist/api/dto/broker-ops.d.ts +37 -0
- package/dist/api/routes.d.ts +1 -0
- package/dist/api/routes.js +1 -1
- package/dist/clients/attach/render/card-presentation.js +2 -2
- package/dist/clients/attach/viewer.js +258 -258
- package/dist/commands/node/bash.js +4 -4
- package/dist/core/bash-job-supervisor.js +3 -3
- package/dist/core/bash-jobs.js +5 -5
- package/dist/core/canvas/memory-reads.js +2 -1
- package/dist/core/canvas/waits.d.ts +2 -0
- package/dist/core/canvas/waits.js +6 -6
- package/dist/core/feed/messages.d.ts +5 -2
- package/dist/core/feed/messages.js +10 -5
- package/dist/core/grants/mirror.d.ts +11 -3
- package/dist/core/grants/mirror.js +6 -4
- package/dist/core/grants/on-sync.js +1 -1
- package/dist/core/graph/events.d.ts +9 -0
- package/dist/core/graph/events.js +12 -12
- package/dist/core/graph/kinds/document.js +2 -2
- package/dist/core/graph/kinds/kind.d.ts +2 -1
- package/dist/core/graph/kinds/node.js +1 -1
- package/dist/core/graph/names.d.ts +4 -3
- package/dist/core/graph/names.js +10 -9
- package/dist/core/graph/watches.d.ts +11 -2
- package/dist/core/graph/watches.js +13 -9
- package/dist/core/human/requests.d.ts +18 -1
- package/dist/core/human/requests.js +20 -18
- package/dist/core/human/scan.d.ts +3 -2
- package/dist/core/human/scan.js +1 -1
- package/dist/core/runtime/broker/attachments-fetch.d.ts +2 -1
- package/dist/core/runtime/broker/attachments-fetch.js +1 -1
- package/dist/core/runtime/broker/bash-job-launch.js +1 -1
- package/dist/core/runtime/broker/boot-state.d.ts +5 -0
- package/dist/core/runtime/broker/boot-state.js +1 -1
- package/dist/core/runtime/broker/cycle-start.d.ts +50 -0
- package/dist/core/runtime/broker/cycle-start.js +2 -0
- package/dist/core/runtime/broker/fault-retry.js +1 -1
- package/dist/core/runtime/broker/frame-dispatch.d.ts +2 -0
- package/dist/core/runtime/broker/frame-dispatch.js +1 -1
- package/dist/core/runtime/broker/frame-memory-refs.d.ts +2 -0
- package/dist/core/runtime/broker/frame-memory-refs.js +1 -1
- package/dist/core/runtime/broker/job-reporter.d.ts +4 -2
- package/dist/core/runtime/broker/job-reporter.js +2 -2
- package/dist/core/runtime/broker/rebind.d.ts +3 -0
- package/dist/core/runtime/broker/rebind.js +1 -1
- package/dist/core/runtime/broker.js +1 -1
- package/dist/core/runtime/runner/blaxel/image-build.d.ts +3 -0
- package/dist/core/runtime/runner/blaxel/image-build.js +1 -1
- package/dist/core/runtime/runner/blaxel/release-image.d.ts +37 -0
- package/dist/core/runtime/runner/blaxel/release-image.js +3 -0
- package/dist/core/runtime/runner/blaxel/runner.d.ts +1 -1
- package/dist/core/runtime/spawn.js +2 -2
- package/dist/core/secrets/blaxel-launch.d.ts +8 -0
- package/dist/core/secrets/blaxel-launch.js +3 -3
- package/dist/core/substrate/delivery/corpus.d.ts +7 -2
- package/dist/core/substrate/delivery/corpus.js +2 -2
- package/dist/core/substrate/delivery/deliver.js +3 -3
- package/dist/core/substrate/delivery/render-boot.js +27 -27
- package/dist/core/substrate/delivery/render-event.d.ts +5 -4
- package/dist/core/substrate/delivery/render-event.js +6 -6
- package/dist/daemon/api/bridge.js +3 -3
- package/dist/daemon/api/environment-of.d.ts +4 -0
- package/dist/daemon/api/environment-of.js +3 -3
- package/dist/daemon/api/handlers/attach.js +1 -1
- package/dist/daemon/api/handlers/bash-jobs.d.ts +2 -0
- package/dist/daemon/api/handlers/bash-jobs.js +3 -3
- package/dist/daemon/api/handlers/broker-ops.js +1 -1
- package/dist/daemon/api/handlers/broker-recovery.d.ts +2 -0
- package/dist/daemon/api/handlers/broker-recovery.js +1 -1
- package/dist/daemon/api/handlers/canvas.js +6 -6
- package/dist/daemon/api/handlers/inbox.js +1 -1
- package/dist/daemon/api/handlers/node-records.d.ts +7 -0
- package/dist/daemon/api/handlers/node-records.js +1 -1
- package/dist/daemon/api/handlers/nodes.js +1 -1
- package/dist/daemon/api/map.js +2 -2
- package/dist/daemon/api/operations.js +1 -1
- package/dist/daemon/cron/authority.d.ts +3 -1
- package/dist/daemon/cron/authority.js +1 -1
- package/dist/daemon/cron/escalation.js +1 -1
- package/dist/daemon/cron/sinks.js +2 -2
- package/dist/daemon/cron-run.js +2 -2
- package/dist/daemon/crtrd.js +12 -12
- package/dist/daemon/machine-daemon.js +1 -1
- package/dist/daemon/machine-link/client.d.ts +8 -0
- package/dist/daemon/machine-link/client.js +1 -1
- package/dist/daemon/machine-link/frames.d.ts +18 -0
- package/dist/daemon/machine-link/frames.js +1 -1
- package/dist/daemon/machine-link/holder.d.ts +2 -0
- package/dist/daemon/machine-link/holder.js +5 -5
- package/dist/daemon/machine-link/job-sweep.d.ts +15 -0
- package/dist/daemon/machine-link/job-sweep.js +1 -0
- package/dist/daemon/reconcilers/action-lane.js +1 -1
- package/dist/daemon/reconcilers/bash-deadline.js +1 -1
- package/dist/pi-extensions/canvas-context-intro.js +2 -2
- package/dist/pi-extensions/canvas-doc-substrate.js +4 -4
- package/dist/pi-extensions/canvas-passive-context.d.ts +13 -10
- package/dist/pi-extensions/canvas-passive-context.js +9 -12
- package/dist/pi-extensions/canvas-recap.js +6 -6
- package/dist/pi-extensions/canvas-stophook.js +1 -1
- package/dist/pi-extensions/canvas-structured-output.js +6 -6
- package/package.json +2 -2
- package/packages/crouter-identity/package.json +1 -1
- package/runtime.lock.json +13 -13
- package/scripts/sandbox-bootstrap.sh +36 -7
- package/scripts/sandbox-start.mjs +41 -7
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
var $=Object.defineProperty;var r=(e,t)=>$(e,"name",{value:t,configurable:!0});import{envNodeId as _}from"../../shared/env.js";import{defineBranch as T,defineLeaf as h}from"../../core/command.js";import{InputError as i}from"../../core/io.js";import{ExitCode as q}from"../../types.js";import{existsSync as R,mkdirSync as D,rmSync as
|
|
1
|
+
var $=Object.defineProperty;var r=(e,t)=>$(e,"name",{value:t,configurable:!0});import{envNodeId as _}from"../../shared/env.js";import{defineBranch as T,defineLeaf as h}from"../../core/command.js";import{InputError as i}from"../../core/io.js";import{ExitCode as q}from"../../types.js";import{existsSync as R,mkdirSync as D,rmSync as E,writeFileSync as w}from"node:fs";import{backgroundRunningBashJobs as I,bashJobCommandLine as N,bashJobPaths as y,formatBashElapsed as k,isSafeBashJobId as g,jobStartedAtMs as B,newBashJobId as M,tailJobLog as L}from"../../core/bash-jobs.js";import{parseDurationMs as S}from"../../core/wake.js";import{cliClient as u,getNodeOrNull as c}from"../api-client.js";import{ApiError as x}from"../../api/index.js";import{PREVIEW_RESULT_PATH_ENV as U}from"../../core/preview-result-path.js";import{contextDir as A}from"../../core/canvas/paths.js";import{nodeInPane as C}from"../surface/node/placement.js";function b(e,t){const n=e.pane??process.env.TMUX_PANE;let o=e.node;if((o===void 0||o==="")&&(o=C(n)),(o===void 0||o==="")&&(o=_()),o===void 0||o==="")throw new i({error:"no_node",message:t,next:"Run from inside a node, pass --node <id>, or --pane <pane>."});return{id:o,pane:n}}r(b,"resolveBashTarget");async function j(e,t,n){try{await u().patchBashJob(e,t,n)}catch(o){throw o instanceof x&&(o.status===404||o.status===409)?new i({error:"not_running",message:`background job ${t} for ${e} is not running`,next:"List live jobs with `crtr node bash list`."}):o}}r(j,"patchRunningJob");const J=h({name:"run",description:"start a shell command as a background job and return at once",whenToUse:"a command needs longer than one tool call \u2014 a test lane, a build, a soak \u2014 and you should be woken with its exit code instead of waiting, backgrounding with `&`, or polling a log",tier:"normal",help:{name:"node bash run",summary:"start one shell command as a background job owned by the calling node and return before it finishes",params:[{kind:"positional",name:"command",required:!0,constraint:"The shell command, run by bash from the current directory with this process\u2019s environment. The same refusals apply as for a bash tool call, judged on this command."},{kind:"flag",name:"quiet-ok",type:"bool",required:!1,constraint:"Pass for a job that legitimately sits idle \u2014 `gh run watch`, `sleep`, waiting on a lock, a `docker build` whose work runs outside the process tree \u2014 so it gets no silence messages. Omit it for anything that should be making progress."}],output:[{name:"job_id",type:"string",required:!0,constraint:"The job object\u2019s id; read or watch it with `crtr canvas`, stop it with `node bash kill`."},{name:"log_path",type:"string",required:!0,constraint:"File receiving the command\u2019s combined stdout and stderr, capped at 10 MiB."}],outputKind:"object",effects:["Works only inside a node\u2019s bash tool call; the job belongs to the calling node.","Starts the command detached from this call, so it keeps running after the call and the turn end. A `timeout` around this leaf bounds only the launch, not the job.","Records the job as a canvas object; when the command exits, its watchers (the calling node by default) get an urgent `exited` push with the exit code and log path.","Sets no cancel deadline: the job runs to completion unless stopped with `node bash kill`.","A job whose processes use almost no CPU and write to no open file for 15 minutes messages the calling node about it, again at 30 and 60 minutes, then hourly; activity restarts the schedule and nothing is stopped. `--quiet-ok` turns these messages off.","Fails, with the job id and log path, if the job could not be recorded; the command is then running but will not message the node when it exits."]},run:r(async e=>{const t=e.command,n=_(),o=process.env.CRTR_CONTEXT_DIR;if(n===void 0||n===""||o===void 0||o==="")throw new i({error:"no_node",message:"`node bash run` starts a job for the calling node and works only inside a node\u2019s bash tool",next:"Run it from a node\u2019s bash tool call."});const s=process.cwd(),{bashCommandRefusal:d}=await import("../../core/bash-guard.js"),l=d(t,s);if(l!==null)throw new i({error:"refused",message:l,next:"Run a different command."});const a=y(o,M());D(a.dir,{recursive:!0}),w(a.cmdSh,t),w(a.jobLog,""),w(a.jobBg,"");const{launchBashJobSupervisor:m}=await import("../../core/runtime/broker/bash-job-launch.js"),{[U]:p,...v}=process.env;try{await m(n,a,o,s,v)}catch(f){throw E(a.dir,{recursive:!0,force:!0}),f}try{await u().recordBackgroundedJob(n,a.jobId,{command:t}),e.quietOk===!0&&await u().patchBashJob(n,a.jobId,{quiet_ok:!0})}catch(f){throw new i({error:"job_not_recorded",message:`job ${a.jobId} is running but could not be recorded (${f.message}); it will NOT message you when it exits. Log: ${a.jobLog}`,next:`Watch it with \`tail -f ${a.jobLog}\`, or stop it with \`crtr node bash kill ${a.jobId}\`.`},q.GENERAL)}return{job_id:a.jobId,log_path:a.jobLog}},"run"),render:r(e=>`[backgrounded as job ${e.job_id}. It will interrupt you with a message when it exits. Watch: tail -f ${e.log_path} ; stop: crtr node bash kill ${e.job_id}]`,"render")}),P=h({name:"background",description:"hand the focused node\u2019s running bash command to its background job system",whenToUse:"the tmux prefix menu invokes this when a foreground bash command should stop blocking the agent immediately but keep running as a file-backed background job",tier:"hidden",help:{name:"node bash background",summary:"hand every running foreground bash command for one node to its file-backed background job system",params:[{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node whose running bash command to background. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE. The prefix menu passes this for you."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The target node."},{name:"jobs",type:"object[]",required:!0,constraint:"Per handed-off job {job_id, elapsed_ms} \u2014 the foreground elapsed time in milliseconds at the moment of handoff."}],outputKind:"object",effects:["Signals every foreground bash command currently running for the node to return from its tool call immediately while its detached supervisor keeps the command running.","Each handed-off command retains its log under the node context jobs directory and becomes a job object; when it exits, the job\u2019s watchers (its node by default) get an urgent `exited` push carrying the exit code and log path."]},run:r(async e=>{const{id:t}=b(e,"no node found for the bash handoff"),n=await c(t);if(n===null)throw new i({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=I(n.paths.context_dir),s=Date.now(),d=o.map(l=>({job_id:l.jobId,elapsed_ms:s-(B(l.jobId)??s)}));return{node_id:t,jobs:d}},"run"),render:r(e=>{const t=e.jobs;if(t.length===0)return`No foreground bash command is running for ${e.node_id}.`;const n=Math.max(...t.map(o=>o.elapsed_ms));return`Handed ${t.length} bash command(s) to the background job system for ${e.node_id} \xB7 ran ${k(n)} in the foreground.`},"render")}),O=h({name:"list",description:"list a node\u2019s live background bash jobs",whenToUse:"you need the ids, commands, and ages of your jobs that are still running",help:{name:"node bash list",summary:"read every still-running background bash job owned by one node",params:[{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node whose background jobs to list. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE."},{kind:"flag",name:"tail",type:"int",required:!1,default:0,constraint:"Include this many trailing log lines per job (0 = none). Read from the local log file, so it is available only on the machine that runs the job; elsewhere log_tail is null \u2014 use `node bash log` there."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The target node."},{name:"jobs",type:"object[]",required:!0,constraint:"Oldest-first {job_id, command, purpose, started_at, elapsed_ms, deadline_at, output_key, log_path, pgid, log_tail} for every live background job; log_path and log_tail are null when the job\u2019s log is not on this machine (a job running in a sandbox, listed from outside it), and no tail is available from here (`node bash log` reads its stored output); purpose is a human-readable label or null; deadline_at is the auto-cancel time or null for a job that runs to completion."}],outputKind:"object",effects:["Reads the node\u2019s running job rows and, for log_tail, the local log files. Changes nothing."]},run:r(async e=>{const{id:t}=b(e,"no node found for the bash job list"),n=await c(t);if(n===null)throw new i({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=Date.now(),s=Math.max(0,Math.trunc(Number(e.tail??0))),d=[n.paths.context_dir,A(n.node_id,n.grantee)],l=(await u().listBashJobs(n.node_id)).map(a=>{const m=d.map(p=>y(p,a.job_id).jobLog).find(p=>R(p))??null;return{job_id:a.job_id,command:a.command,purpose:a.purpose,started_at:a.started_at,elapsed_ms:a.elapsed_ms,deadline_at:a.deadline_at,output_key:a.output_key,log_path:m,pgid:a.pgid,log_tail:m===null?null:L(m,s)}});return{node_id:n.node_id,jobs:l}},"run"),render:r(e=>{const t=e.jobs;return t.length===0?`No background bash jobs for ${e.node_id}.`:t.map(n=>`${n.job_id} \xB7 ${k(n.elapsed_ms)} \xB7 ${N(n.command)}${n.purpose===null?"":`
|
|
2
2
|
purpose: ${n.purpose}`}${n.deadline_at===null?"":`
|
|
3
3
|
cancels at: ${n.deadline_at}`}
|
|
4
|
-
${n.log_path===null?`log: not on this machine (
|
|
5
|
-
`)},"render")}),
|
|
6
|
-
`:""}${String(e.output)}`,"render")}),
|
|
4
|
+
${n.log_path===null?`log: not on this machine (its job files are not under this machine\u2019s crtr home \u2014 a sandbox or another computer); read its output with \`crtr node bash log ${n.job_id} --node ${e.node_id}\``:`log: ${n.log_path}`}`).join(`
|
|
5
|
+
`)},"render")}),K=h({name:"log",description:"read a background bash job\u2019s output from the blob store, from any machine",whenToUse:"a job has exited or been killed, or its sandbox is gone, and you need what it printed \u2014 the wake and the job object name this command; for a job still running on this machine, `tail -f` on its log file shows more recent output",help:{name:"node bash log",summary:"read the stored output of one background bash job, last lines first bounded",params:[{kind:"positional",name:"job",required:!0,constraint:"Job id, as named by the exit wake, `node bash list` or `node bash run`. Running and finished jobs both work."},{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node owning the job. Defaults to the node in --pane, else the caller (CRTR_NODE_ID). A job another node started needs its owner here."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE."},{kind:"flag",name:"tail",type:"int",required:!1,constraint:"Return only this many trailing lines. Without it you get the last 256 KiB of output; either way at most 4 MiB."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The owning node."},{name:"job_id",type:"string",required:!0,constraint:"The job."},{name:"output",type:"string",required:!0,constraint:"The stored output, empty when the job has written nothing yet. The broker uploads a running job\u2019s output every couple of seconds, so it can trail the live log slightly."},{name:"truncated",type:"boolean",required:!0,constraint:"True when earlier output exists that the bound left out."}],outputKind:"object",effects:["Reads the output chunks the job\u2019s broker uploaded to the blob store through the daemon; never the local log file, so it works from any machine and after the job\u2019s sandbox is deleted. Needs read access to the owning node. Changes nothing."]},run:r(async e=>{const{id:t}=b(e,"no node found for the bash job"),n=await c(t);if(n===null)throw new i({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=e.job;if(!g(o))throw new i({error:"invalid_job_id",message:`invalid background job id: ${o}`,next:"Use a job id named by the exit wake or `crtr node bash list`."});const s=e.tail===void 0?void 0:Math.trunc(Number(e.tail));if(s!==void 0&&!(s>=1))throw new i({error:"invalid_args",message:"--tail must be a positive number of lines",next:"Pass --tail 50, or omit it for the last 256 KiB."});try{const d=await u().readBashJobOutput(n.node_id,o,s===void 0?{}:{tail_lines:s});return{node_id:n.node_id,job_id:d.job_id,output:d.output,truncated:d.truncated}}catch(d){throw d instanceof x&&d.code==="job_not_found"?new i({error:"job_not_found",message:`no job ${o} owned by ${n.node_id}`,next:"A job another node started needs its owner: pass --node <owner>."}):d}},"run"),render:r(e=>`${e.truncated===!0?`[earlier output omitted]
|
|
6
|
+
`:""}${String(e.output)}`,"render")}),X=h({name:"kill",description:"stop one of a node\u2019s background bash jobs",whenToUse:"a job you started is no longer wanted or is stuck, and it should stop now",help:{name:"node bash kill",summary:"best-effort stop a background bash job and tell the owning node it was canceled",params:[{kind:"positional",name:"job",required:!0,constraint:"Job id, as reported by node bash list."},{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node owning the job. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The owning node."},{name:"signaled",type:"boolean",required:!0,constraint:"True when at least one observed supervisor-tree process received SIGTERM. For a job running on another machine it is true without any signal having been sent yet."},{name:"stop_pending_on_machine",type:"boolean",required:!0,constraint:"True when the job\u2019s process runs on another machine (an imported Mac or a sandbox): its broker there stops the whole process tree on its next report, within a few seconds, so nothing is confirmed stopped yet."}],outputKind:"object",effects:["Snapshots the supervisor\u2019s observable process tree, sends SIGTERM then SIGKILL to those processes and to the supervisor\u2019s process group, and cannot stop a descendant that detached into its own session and reparented before the snapshot. A job running on another machine (an imported Mac, a sandbox) is stopped there by its broker within a few seconds of the row ending.","Records the job\u2019s exit so it stops showing as live, and ends its job object as killed; the job\u2019s watchers (its node by default) get an urgent `killed` push."]},run:r(async e=>{const{id:t}=b(e,"no node found for the bash job"),n=await c(t);if(n===null)throw new i({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=e.job;if(!g(o))throw new i({error:"invalid_job_id",message:`invalid background job id: ${o}`,next:"Use a job id reported by `crtr node bash list`."});const s=await u().stopBashJob(n.node_id,o);return{node_id:n.node_id,signaled:s.signaled,stop_pending_on_machine:s.stop_pending_on_machine===!0}},"run"),render:r(e=>e.stop_pending_on_machine===!0?`Ended a background bash job for ${e.node_id}. Its process runs on another machine (an imported Mac or a sandbox); that machine's broker stops the whole process tree on its next report, within a few seconds. Confirm with \`ps\` there if it matters.`:`Canceled a background bash job for ${e.node_id}${e.signaled===!0?"":" (no observed job process was still running)"}.`,"render")}),W=h({name:"quiet",description:"mark a running background bash job as an expected wait so it sends no silence messages",whenToUse:"a silence message arrived for a job that is meant to sit idle",help:{name:"node bash quiet",summary:"stop silence messages for one of a node\u2019s live background bash jobs",params:[{kind:"positional",name:"job",required:!0,constraint:"Job id, as reported by node bash list or the silence message."},{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node owning the job. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The owning node."}],outputKind:"object",effects:["Marks the job\u2019s row; the daemon sends no further silence messages for it. Signals nothing."]},run:r(async e=>{const{id:t}=b(e,"no node found for the bash job"),n=await c(t);if(n===null)throw new i({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=e.job;if(!g(o))throw new i({error:"invalid_job_id",message:`invalid background job id: ${o}`,next:"Use a job id reported by `crtr node bash list`."});return await j(n.node_id,o,{quiet_ok:!0}),{node_id:n.node_id}},"run"),render:r(e=>`Background job for ${e.node_id} will send no more silence messages.`,"render")}),F=h({name:"extend",description:"claim an auto-backgrounded bash job so the daemon does not cancel it at its deadline",whenToUse:"a command that was moved to a job automatically is worth keeping past its cancel deadline \u2014 give it more time with --for, or let it run to completion with --keep",help:{name:"node bash extend",summary:"move or clear the auto-cancel deadline on one of a node\u2019s live background bash jobs",params:[{kind:"positional",name:"job",required:!0,constraint:"Job id, as reported by node bash list or the auto-background notice."},{kind:"flag",name:"for",type:"string",required:!1,constraint:"New window from now before the job is canceled, as a duration (e.g. 90s, 10m, 1h30m). Mutually exclusive with --keep; give exactly one."},{kind:"flag",name:"keep",type:"bool",required:!1,constraint:"Remove the deadline entirely so the job runs to completion. Mutually exclusive with --for; give exactly one."},{kind:"flag",name:"node",type:"string",required:!1,constraint:"Node owning the job. Defaults to the node in --pane, else the caller (CRTR_NODE_ID)."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the target node, when --node is omitted. Defaults to $TMUX_PANE."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The owning node."},{name:"deadline_at",type:"string",required:!1,constraint:"The job\u2019s new auto-cancel time (ISO), or absent when --keep cleared the deadline so the job runs to completion."}],outputKind:"object",effects:["Rewrites or clears the deadline on the job\u2019s row. The daemon\u2019s deadline lane reads it on its next scan. Signals nothing."]},run:r(async e=>{const{id:t}=b(e,"no node found for the bash job"),n=await c(t);if(n===null)throw new i({error:"not_found",message:`no node: ${t}`,next:"List nodes with `crtr node inspect list`."});const o=e.job;if(!g(o))throw new i({error:"invalid_job_id",message:`invalid background job id: ${o}`,next:"Use a job id reported by `crtr node bash list`."});const s=e.for,d=e.keep===!0;if(d===(s!==void 0&&s!==""))throw new i({error:"invalid_args",message:"give exactly one of --for <duration> or --keep",next:"Extend by a window with --for 10m, or drop the deadline with --keep."});if(d)return await j(n.node_id,o,{keep:!0}),{node_id:n.node_id};const l=S(s);if(l===null||l<=0)throw new i({error:"invalid_duration",message:`not a duration: ${s}`,next:"Use a value like 90s, 10m, or 1h30m."});const a=Date.now()+l;return await j(n.node_id,o,{deadline_at_ms:a}),{node_id:n.node_id,deadline_at:new Date(a).toISOString()}},"run"),render:r(e=>e.deadline_at===void 0?`Cleared the deadline \u2014 the background job will run to completion for ${e.node_id}.`:`Background job for ${e.node_id} will be canceled at ${e.deadline_at} unless extended again.`,"render")}),ie=T({name:"bash",description:"start, list, read, stop, and extend your background bash jobs",whenToUse:"a command needs longer than one tool call \u2014 start it as a job and be woken with its exit code instead of using `&`, `nohup`, or a cron that polls a log \u2014 or you need to list, read the output of, stop, or extend the deadline of a job you already have",help:{name:"node bash",summary:"start, list, read, stop, and extend background bash jobs owned by a node",model:"Every bash call runs under a detached supervisor with its output in a log file, so a command that outlives its call keeps running as a job: a canvas object its node owns, readable and watchable with `crtr canvas`. `run` starts a job on purpose and it is never auto-canceled. A job that shows no activity for 15 minutes messages its node, and is never stopped for it. A foreground command still running after 5 minutes is moved to a job automatically, with a cancel deadline unless `extend` claims it."},children:[J,P,O,K,X,W,F]});export{ie as nodeBash};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const c=10485760,
|
|
1
|
+
const c=10485760,e=`
|
|
2
2
|
[background bash job output truncated at 10 MiB; remaining output discarded]
|
|
3
|
-
`,
|
|
4
|
-
`);export{
|
|
3
|
+
`,t=['const fs = require("node:fs");',"const cap = 10485760;",`const marker = Buffer.from(${JSON.stringify(e)});`,"const prefixCap = cap - marker.length;",'const fd = fs.openSync(process.argv[1], "w");',"let written = 0;","let truncated = false;",'process.stdin.on("data", (chunk) => {'," if (truncated) return;"," const available = prefixCap - written;"," if (available > 0) {"," const prefix = chunk.subarray(0, available);"," fs.writeSync(fd, prefix);"," written += prefix.length;"," if (prefix.length === chunk.length) return;"," }"," fs.writeSync(fd, marker);"," truncated = true;","});",'process.stdin.on("end", () => fs.closeSync(fd));'].join(" "),s=['const fs = require("node:fs"), cp = require("node:child_process");',"const rootPid = Number(process.argv[1]), out = process.argv[3];","let logPath = process.argv[2];","try { logPath = fs.realpathSync(logPath); } catch {}","const interval = Number(process.env.CRTR_BASH_ACTIVITY_SAMPLE_MS) || 60000;",'const linux = fs.existsSync("/proc/self/stat");',"function processes() {"," const procs = new Map();"," if (linux) {",' for (const e of fs.readdirSync("/proc")) {'," if (!/^[0-9]+$/.test(e)) continue;"," try {",' const s = fs.readFileSync("/proc/" + e + "/stat", "utf8");',' const r = s.slice(s.lastIndexOf(")") + 2).split(" ");'," procs.set(Number(e), { ppid: Number(r[1]), cpu: (Number(r[11]) + Number(r[12])) / 100 });"," } catch {}"," }"," return procs;"," }",' const ps = cp.execFileSync("ps", ["-ax", "-o", "pid=,ppid=,time="], { encoding: "utf8", timeout: 5000 });',' for (const line of ps.split("\\n")) {'," const f = line.trim().split(/\\s+/);"," if (f.length < 3) continue;",' const [days, clock] = f[2].includes("-") ? f[2].split("-") : ["0", f[2]];',' const cpu = clock.split(":").reduce((t, x) => t * 60 + Number(x), 0) + Number(days) * 86400;'," if (Number.isFinite(cpu)) procs.set(Number(f[0]), { ppid: Number(f[1]), cpu });"," }"," return procs;","}","function tree(procs) {"," const cpus = new Map(), stack = [rootPid];"," while (stack.length > 0) {"," const pid = stack.pop();"," if (pid === process.pid || cpus.has(pid) || !procs.has(pid)) continue;"," cpus.set(pid, procs.get(pid).cpu);"," for (const [child, p] of procs) if (p.ppid === pid) stack.push(child);"," }"," return cpus;","}","function writableFiles(pids) {"," const files = new Set();"," if (linux) {"," for (const pid of pids) {"," let fds = [];",' try { fds = fs.readdirSync("/proc/" + pid + "/fd"); } catch {}'," for (const fd of fds) {"," try {",' const info = fs.readFileSync("/proc/" + pid + "/fdinfo/" + fd, "utf8").match(/flags:\\s*([0-7]+)/);'," if (info === null || (parseInt(info[1], 8) & 3) === 0) continue;",' files.add(fs.readlinkSync("/proc/" + pid + "/fd/" + fd));'," } catch {}"," }"," }"," return files;"," }",' const r = cp.spawnSync("lsof", ["-nP", "-w", "-F", "pfatn", "-p", pids.join(",")], { encoding: "utf8", timeout: 10000 });',' if (r.error || typeof r.stdout !== "string") return files;',' let access = "", type = "";',' for (const line of r.stdout.split("\\n")) {'," const key = line[0], value = line.slice(1);",' if (key === "f") { access = ""; type = ""; }',' else if (key === "a") access = value;',' else if (key === "t") type = value;',' else if (key === "n" && (access === "w" || access === "u") && type === "REG") files.add(value);'," }"," return files;","}","let lastActivity = Date.now(), prevAt = lastActivity, prevCpu = new Map(), watched = [logPath];","try { prevCpu = tree(processes()); } catch {}","function record() {",' fs.writeFileSync(out + ".tmp", lastActivity + " " + prevAt + "\\n" + watched.join("\\n") + "\\n");',' fs.renameSync(out + ".tmp", out);',"}","function sample() {",' try { process.kill(rootPid, 0); } catch (e) { if (e.code !== "EPERM") process.exit(0); }'," const at = Date.now();"," const cpus = tree(processes());"," let used = 0;"," for (const [pid, cpu] of cpus) used += Math.max(0, cpu - (prevCpu.get(pid) || 0));"," const paths = new Set([logPath]);"," let changed = false;"," for (const file of writableFiles([...cpus.keys()])) {"," try {"," const st = fs.statSync(file);"," if (!st.isFile()) continue;"," paths.add(fs.realpathSync(file));"," if (st.mtimeMs > prevAt) changed = true;"," } catch {}"," }"," try { if (fs.statSync(logPath).mtimeMs > prevAt) changed = true; } catch {}"," if (at - prevAt > 3 * interval) changed = true;"," if (changed || used > 0.02 * (at - prevAt) / 1000) lastActivity = at;"," watched = [...paths];"," prevAt = at;"," prevCpu = cpus;"," record();","}","record();","setInterval(() => { try { sample(); } catch {} }, interval);"].join(" "),n=['const http = require("node:http");',"const done = () => process.exit(0);",'const req = http.request({ socketPath: process.argv[1], path: "/job-exit", method: "POST", headers: { "content-type": "application/json" }, timeout: 3000 }, (res) => { res.resume(); res.on("end", done); });','req.on("error", done);','req.on("timeout", done);',"req.end(JSON.stringify({ node: process.argv[2], job: process.argv[3] }));"].join(" "),r=['"$8" -e '+JSON.stringify(s)+' "$$" "$2" "$9" &',"sampler=$!","n=$(command -v nice)",'${n:+"$n" -n "$7"} "$6" "$1" 2>&1 | "$8" -e '+JSON.stringify(t)+' "$2"',"status=${PIPESTATUS[0]}",'kill "$sampler" 2>/dev/null','echo "$status" > "$3"','if [ -n "${10:-}" ]; then "$8" -e '+JSON.stringify(n)+' "${10}" "${11:-}" "${12:-}" </dev/null >/dev/null 2>&1 & fi','mv "$4" "$5" 2>/dev/null || true'].join(`
|
|
4
|
+
`);export{e as BACKGROUND_BASH_LOG_TRUNCATION_MARKER,r as BASH_JOB_SUPERVISOR_SCRIPT,c as MAX_BACKGROUND_BASH_LOG_BYTES};
|
package/dist/core/bash-jobs.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
var
|
|
2
|
-
`),[B,j]=(l??"").split(" ").map(Number);Number.isFinite(B)&&Number.isFinite(j)&&(r.activity={lastActivityMs:B,sampledAtMs:j,files:h.filter(
|
|
1
|
+
var v=Object.defineProperty;var o=(t,e)=>v(t,"name",{value:e,configurable:!0});import{randomBytes as F}from"node:crypto";import{closeSync as x,openSync as S,readSync as E,statSync as _}from"node:fs";import{dirname as p,join as a}from"node:path";import{captureTeardownSnapshot as C,isAnyPidAlive as O,isPidAlive as N,killProcessTreePids as J}from"./canvas/pid.js";import{launcherRequest as G}from"../launcher/client.js";import{LaunchRefused as z}from"../launcher/spec.js";import{createFileBeneath as P,existsBeneath as H,readTextBeneathIfExists as m,readdirBeneath as X,readFileBeneath as q,renameBeneath as K,unlinkBeneath as U,writeFileBeneath as w}from"./spaces/open-beneath.js";const W=280;function at(t){if(typeof t!="string"||/[\p{Cc}\p{Cf}]/u.test(t))return null;const e=t.trim();return e===""?null:Buffer.byteLength(e,"utf8")<=W?e:null}o(at,"normalizeBashJobPurpose");function g(t){return a(t,"jobs")}o(g,"bashJobsDir");function y(t,e){return q(p(t),e).toString("utf8")}o(y,"readJobText");function M(t){return X(p(t),g(t)).map(e=>e.name)}o(M,"jobIds");function c(t,e){return H(t.root,e)}o(c,"has");function k(t,e){try{U(t,e)}catch(n){if(n.code!=="ENOENT")throw n}}o(k,"unlinkIfPresent");function ct(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&/^[A-Za-z0-9._~-]+$/u.test(t)&&Buffer.byteLength(t,"utf8")<=128}o(ct,"isSafeBashJobId");function b(t,e){const n=a(g(t),e);return{jobId:e,root:p(t),dir:n,cmdSh:a(n,"cmd.sh"),jobLog:a(n,"job.log"),jobExit:a(n,"job.exit"),jobRun:a(n,"job.run"),jobBg:a(n,"job.bg"),jobDone:a(n,"job.done"),jobPgid:a(n,"job.pgid"),jobPgidIdentity:a(n,"job.pgid-identity"),jobActivity:a(n,"job.activity"),jobDeadline:a(n,"job.deadline"),jobReported:a(n,"job.reported")}}o(b,"bashJobPaths");function A(t,e){try{const n=Number(y(t,b(t,e).jobPgid).trim());return Number.isInteger(n)&&n>1?n:void 0}catch{return}}o(A,"readJobPgid");function L(t,e){try{const n=y(t,b(t,e).jobPgidIdentity).trim();return n===""?void 0:n}catch{return}}o(L,"readJobPgidIdentity");function ft(t,e){const n=b(t,e),r={},s=A(t,e),i=L(t,e);s!==void 0&&(r.pgid=s),i!==void 0&&(r.pgidIdentity=i);const u=m(n.root,n.jobExit);u!==null&&Number.isSafeInteger(Number(u.trim()))&&u.trim()!==""&&(r.exitCode=Number(u.trim()));const f=m(n.root,n.jobDeadline);f!==null&&f.trim()!==""&&Number.isFinite(Number(f.trim()))&&(r.deadlineMs=Number(f.trim()));const d=m(n.root,n.jobActivity);if(d!==null){const[l,...h]=d.split(`
|
|
2
|
+
`),[B,j]=(l??"").split(" ").map(Number);Number.isFinite(B)&&Number.isFinite(j)&&(r.activity={lastActivityMs:B,sampledAtMs:j,files:h.filter(I=>I!=="")})}return r}o(ft,"readJobSupervisorState");function dt(t,e){w(t.root,t.jobDeadline,`${Math.trunc(e)}
|
|
3
3
|
`)}o(dt,"writeJobDeadlineFile");function lt(t){k(t.root,t.jobDeadline)}o(lt,"clearJobDeadlineFile");function bt(t){let e;try{e=M(t)}catch{return[]}return e.filter(n=>{const r=b(t,n);try{return(c(r,r.jobRun)||c(r,r.jobBg))&&!c(r,r.jobExit)}catch{return!1}})}o(bt,"unfinishedBashJobIds");const R=10,Y=19;function $(t){return a(g(t),"niceness")}o($,"bashNicenessPath");function ht(t){try{const e=Number(y(t,$(t)).trim());return!Number.isInteger(e)||e<0||e>Y?R:e}catch{return R}}o(ht,"readBashNiceness");function pt(t,e){w(p(t),$(t),`${Math.trunc(e)}
|
|
4
|
-
`)}o(pt,"writeBashNiceness");function mt(t,e){if(e===`launcher:${t}`)return N(t);try{return process.kill(-t,0),!0}catch(n){return n.code==="EPERM"}}o(mt,"isBashJobProcessGroupAlive");function gt(t,e){if(t===void 0||e===void 0)return!1;if(e===`launcher:${t}`)return!N(t);try{return process.kill(-t,0),!1}catch(n){return n.code==="ESRCH"}}o(gt,"isBashJobProcessConfirmedGone");async function Z(t,e){const n=C(t,e);if(n.reused||n.tree.length===0)return!1;const r=[...n.tree].reverse(),s=O(r);
|
|
4
|
+
`)}o(pt,"writeBashNiceness");function mt(t,e){if(e===`launcher:${t}`)return N(t);try{return process.kill(-t,0),!0}catch(n){return n.code==="EPERM"}}o(mt,"isBashJobProcessGroupAlive");function gt(t,e){if(t===void 0||e===void 0)return!1;if(e===`launcher:${t}`)return!N(t);try{return process.kill(-t,0),!1}catch(n){return n.code==="ESRCH"}}o(gt,"isBashJobProcessConfirmedGone");async function Z(t,e){const n=C(t,e);if(n.reused||n.tree.length===0)return!1;const r=[...n.tree].reverse(),s=O(r);J(r,"SIGTERM",n.identities),await new Promise(i=>setTimeout(i,400)),J(r,"SIGKILL",n.identities);try{process.kill(-t,"SIGKILL")}catch{}return s}o(Z,"cancelBashJobProcessTree");async function D(t,e,n){if(e!==`launcher:${t}`)return await Z(t,e);if(n===void 0)throw new Error("launcher job stop requires its owning node");try{if(!("ok"in await G({operation:"stop",pid:t,nodeId:n})))throw new Error("launcher did not stop job");return!0}catch(r){if(!(r instanceof z&&r.refusal==="invalid_spec"))throw r;return!1}}o(D,"signalBashJob");async function yt(t,e,n=!1,r,s){const i=b(t,e);if(!c(i,i.dir))return{kind:"missing"};if(!c(i,i.jobBg)&&!(n&&c(i,i.jobRun))||c(i,i.jobExit))return{kind:"retired",logPath:i.jobLog};const u=A(t,e),f=L(t,e);if(u===void 0||f===void 0)return{kind:"not-stoppable",logPath:i.jobLog};const d=a(i.dir,"job.stop");try{P(i.root,d,s===void 0?"":`${s}
|
|
5
5
|
`)}catch(l){if(l.code==="EEXIST")return{kind:"retired",logPath:i.jobLog};throw l}try{const l=await D(u,f,r);try{P(i.root,i.jobExit,`143
|
|
6
6
|
`)}catch(h){if(h.code!=="EEXIST")throw h}return{kind:"stopped",signaled:l,pgid:u,logPath:i.jobLog}}catch(l){throw k(i.root,d),l}}o(yt,"stopBackgroundBashJob");function Bt(t,e){if(e<=0)return[];const n=64*1024;let r;try{const s=_(t).size,i=Math.max(0,s-n),u=Buffer.alloc(Math.min(s,n));r=S(t,"r"),E(r,u,0,u.length,i);const f=u.toString("utf8"),d=(i>0?f.slice(f.indexOf(`
|
|
7
7
|
`)+1):f).split(`
|
|
8
|
-
`);return d[d.length-1]===""&&d.pop(),d.slice(-e)}catch{return[]}finally{r!==void 0&&x(r)}}o(Bt,"tailJobLog");function jt(t){let e;try{e=S(t,"r");const n=Buffer.alloc(64*1024);let r=0,s=0;for(;;){const i=E(e,n,0,n.length,null);if(i===0)break;for(let u=0;u<i;u+=1)n[u]===10&&(r+=1);s=n[i-1]}return s!==0&&s!==10?r+1:r}catch{return 0}finally{e!==void 0&&x(e)}}o(jt,"countJobLogLines");function xt(){return`${Date.now()}-${
|
|
9
|
-
`).map(n=>n.trim()).find(n=>n!=="")??"").replace(/\s+/g," ")}o(Et,"bashJobCommandLine");function V(t){try{return
|
|
8
|
+
`);return d[d.length-1]===""&&d.pop(),d.slice(-e)}catch{return[]}finally{r!==void 0&&x(r)}}o(Bt,"tailJobLog");function jt(t){let e;try{e=S(t,"r");const n=Buffer.alloc(64*1024);let r=0,s=0;for(;;){const i=E(e,n,0,n.length,null);if(i===0)break;for(let u=0;u<i;u+=1)n[u]===10&&(r+=1);s=n[i-1]}return s!==0&&s!==10?r+1:r}catch{return 0}finally{e!==void 0&&x(e)}}o(jt,"countJobLogLines");function xt(){return`${Date.now()}-${F(4).toString("hex")}`}o(xt,"newBashJobId");function Q(t){const e=t.indexOf("-");if(e<=0||e===t.length-1)return;const n=Number(t.slice(0,e));return Number.isFinite(n)?n:void 0}o(Q,"jobStartedAtMs");function St(t){const e=Math.max(0,Math.floor(t/1e3));if(e<60)return`${e}s`;const n=Math.floor(e/60),r=e%60;if(n<60)return`${n}m ${String(r).padStart(2,"0")}s`;const s=Math.floor(n/60),i=n%60;return`${s}h ${String(i).padStart(2,"0")}m`}o(St,"formatBashElapsed");function Et(t){return(t.split(`
|
|
9
|
+
`).map(n=>n.trim()).find(n=>n!=="")??"").replace(/\s+/g," ")}o(Et,"bashJobCommandLine");function V(t){try{return K(t.root,t.jobRun,t.jobBg),"backgrounded"}catch(e){if(e.code!=="ENOENT")throw e;return c(t,t.jobBg)?"already-backgrounded":c(t,t.jobDone)?"finished":"missing"}}o(V,"backgroundBashJob");function T(t){let e;try{e=M(t)}catch{return[]}return e.flatMap(n=>{const r=b(t,n);try{return c(r,r.cmdSh)&&c(r,r.jobLog)&&c(r,r.jobRun)?[r]:[]}catch{return[]}})}o(T,"runningBashJobs");function Nt(t){let e;for(const n of T(t)){const r=Q(n.jobId);r!==void 0&&(e===void 0||r<e)&&(e=r)}return e}o(Nt,"oldestRunningBashJobStartedAtMs");function Jt(t){const e=[];for(const n of T(t))V(n)==="backgrounded"&&e.push(n);return e}o(Jt,"backgroundRunningBashJobs");export{R as DEFAULT_BASH_NICENESS,Y as MAX_BASH_NICENESS,V as backgroundBashJob,Jt as backgroundRunningBashJobs,Et as bashJobCommandLine,b as bashJobPaths,g as bashJobsDir,$ as bashNicenessPath,Z as cancelBashJobProcessTree,lt as clearJobDeadlineFile,jt as countJobLogLines,St as formatBashElapsed,gt as isBashJobProcessConfirmedGone,mt as isBashJobProcessGroupAlive,ct as isSafeBashJobId,Q as jobStartedAtMs,xt as newBashJobId,at as normalizeBashJobPurpose,Nt as oldestRunningBashJobStartedAtMs,ht as readBashNiceness,A as readJobPgid,L as readJobPgidIdentity,ft as readJobSupervisorState,D as signalBashJob,yt as stopBackgroundBashJob,Bt as tailJobLog,bt as unfinishedBashJobIds,pt as writeBashNiceness,dt as writeJobDeadlineFile};
|
|
@@ -1 +1,2 @@
|
|
|
1
|
-
var p=Object.defineProperty;var r=(
|
|
1
|
+
var p=Object.defineProperty;var r=(t,a)=>p(t,"name",{value:a,configurable:!0});import{withCanvasWrite as m,openDb as s}from"./db.js";const c=720*60*60*1e3;async function E(t,a){await m(async o=>{const n=o.prepare("INSERT INTO memory_reads (node_id, name, scope, at, type) VALUES (?, ?, ?, ?, ?)");for(const e of a)await n.run(t,e.name,e.scope,e.at,e.type)})}r(E,"insertMemoryReads");async function R(t,a,o){if(o.length===0)return;const n=r(e=>o.map(e),"col");await t.prepare(`INSERT INTO memory_reads (node_id, name, scope, at, type)
|
|
2
|
+
SELECT ?::text, v.name, v.scope, v.at, v.type FROM unnest(?::text[], ?::text[], ?::text[], ?::text[]) WITH ORDINALITY AS v(name, scope, at, type, n) ORDER BY v.n`).run(a,n(e=>e.name),n(e=>e.scope),n(e=>e.at),n(e=>e.type))}r(R,"recordMemoryReadsIn");async function d(t,a){return await(await s()).prepare("SELECT node_id, name, scope, at, type FROM memory_reads WHERE at >= ? AND at < ? ORDER BY at").all(t,a)}r(d,"listMemoryReads");async function u(t){return Number((await(await s()).prepare("DELETE FROM memory_reads WHERE at < ?").run(new Date(t-c).toISOString())).changes)}r(u,"pruneMemoryReads");async function w(){return(await(await s()).prepare("SELECT value FROM canvas_meta WHERE key = 'memory_reads.started_at'").get())?.value??null}r(w,"memoryReadsStartedAt");export{c as MEMORY_READS_RETENTION_MS,E as insertMemoryReads,d as listMemoryReads,w as memoryReadsStartedAt,u as pruneMemoryReads,R as recordMemoryReadsIn};
|
|
@@ -9,6 +9,8 @@ export interface ControllerWait {
|
|
|
9
9
|
}
|
|
10
10
|
/** Replace a node's live controller wait while retaining the prior row as history. */
|
|
11
11
|
export declare function armControllerWait(nodeId: string, controllerId: string, now?: number): Promise<ControllerWait>;
|
|
12
|
+
/** Live controller waits for many nodes in one statement; nodes without one are absent from the map. */
|
|
13
|
+
export declare function readControllerWaits(nodeIds: readonly string[]): Promise<Map<string, ControllerWait>>;
|
|
12
14
|
export declare function readControllerWait(nodeId: string): Promise<ControllerWait | null>;
|
|
13
15
|
/** Clear only the wait that was observed for this sender; a rearm wins a race. */
|
|
14
16
|
export declare function settleMatchingControllerWait(nodeId: string, senderId: string | null, now: number, db?: CanvasDb): Promise<boolean>;
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
var w=Object.defineProperty;var n=(t,e)=>w(t,"name",{value:e,configurable:!0});import{randomBytes as c}from"node:crypto";import{withCanvasWrite as
|
|
2
|
-
VALUES (?, ?, 'controller', ?, ?, ?, NULL)`).run(
|
|
1
|
+
var w=Object.defineProperty;var n=(t,e)=>w(t,"name",{value:e,configurable:!0});import{randomBytes as c}from"node:crypto";import{withCanvasWrite as l,openDb as o}from"./db.js";function s(t){if(t.kind!=="controller")throw new Error(`wait ${t.wait_id} is not a controller wait`);return{waitId:t.wait_id,nodeId:t.node_id,controllerId:t.target_id,generation:t.generation,createdAt:t.created_at,satisfiedAt:t.satisfied_at}}n(s,"waitFrom");function _(){let t;do t=c(16).toString("hex");while(t==="00000000000000000000000000000000");return t}n(_,"newWaitId");async function p(t,e,i=Date.now()){return await l(async a=>{await a.prepare("UPDATE waits SET satisfied_at = ? WHERE node_id = ? AND kind = 'controller' AND satisfied_at IS NULL").run(i,t);const r=Number((await a.prepare("SELECT COALESCE(MAX(generation), 0) AS generation FROM waits WHERE node_id = ? AND kind = 'controller'").get(t)).generation)+1,d={wait_id:_(),node_id:t,kind:"controller",target_id:e,generation:r,created_at:i,satisfied_at:null};return await a.prepare(`INSERT INTO waits (wait_id, node_id, kind, target_id, generation, created_at, satisfied_at)
|
|
2
|
+
VALUES (?, ?, 'controller', ?, ?, ?, NULL)`).run(d.wait_id,d.node_id,d.target_id,d.generation,d.created_at),s(d)})}n(p,"armControllerWait");async function E(t){const e=new Map;if(t.length===0)return e;const i=await(await o()).prepare("SELECT * FROM waits WHERE node_id = ANY(?::text[]) AND kind = 'controller' AND satisfied_at IS NULL").all([...t]);for(const a of i)e.set(a.node_id,s(a));return e}n(E,"readControllerWaits");async function L(t){return(await E([t])).get(t)??null}n(L,"readControllerWait");async function g(t,e,i,a){if(a??=await o(),e===null)return!1;const r=await a.prepare("SELECT wait_id, generation FROM waits WHERE node_id = ? AND kind = 'controller' AND target_id = ? AND satisfied_at IS NULL").get(t,e);return r===void 0?!1:Number((await a.prepare("UPDATE waits SET satisfied_at = ? WHERE wait_id = ? AND generation = ? AND satisfied_at IS NULL").run(i,r.wait_id,r.generation)).changes)===1}n(g,"settleMatchingControllerWait");async function A(t,e,i,a){a??=await o();const r=await a.prepare(`SELECT w.wait_id, w.generation, target.status AS controller_status
|
|
3
3
|
FROM waits w LEFT JOIN nodes target ON target.node_id = w.target_id
|
|
4
|
-
WHERE w.node_id = ? AND w.kind = 'controller' AND w.target_id = ? AND w.satisfied_at IS NULL`).get(t,e);return r===void 0||r.controller_status==="active"||r.controller_status==="idle"?!1:Number((await a.prepare("UPDATE waits SET satisfied_at = ? WHERE wait_id = ? AND generation = ? AND satisfied_at IS NULL").run(i,r.wait_id,r.generation)).changes)===1}n(
|
|
4
|
+
WHERE w.node_id = ? AND w.kind = 'controller' AND w.target_id = ? AND w.satisfied_at IS NULL`).get(t,e);return r===void 0||r.controller_status==="active"||r.controller_status==="idle"?!1:Number((await a.prepare("UPDATE waits SET satisfied_at = ? WHERE wait_id = ? AND generation = ? AND satisfied_at IS NULL").run(i,r.wait_id,r.generation)).changes)===1}n(A,"settleDeadControllerWait");async function D(){return(await(await o()).prepare("SELECT * FROM waits WHERE kind = 'controller' AND satisfied_at IS NULL").all()).map(s)}n(D,"liveControllerWaits");async function S(t,e,i,a=Date.now()){await t.prepare(`INSERT INTO waits (wait_id, node_id, kind, target_id, generation, created_at, satisfied_at)
|
|
5
5
|
SELECT ?, ?, 'object', ?, 1, ?, NULL
|
|
6
|
-
WHERE NOT EXISTS (SELECT 1 FROM waits WHERE node_id = ? AND kind = 'object' AND target_id = ? AND satisfied_at IS NULL)`).run(_(),e,i,a,e,i)}n(
|
|
6
|
+
WHERE NOT EXISTS (SELECT 1 FROM waits WHERE node_id = ? AND kind = 'object' AND target_id = ? AND satisfied_at IS NULL)`).run(_(),e,i,a,e,i)}n(S,"armObjectWait");async function T(t,e,i=null,a=Date.now()){return Number(i===null?(await t.prepare("UPDATE waits SET satisfied_at = ? WHERE kind = 'object' AND target_id = ? AND satisfied_at IS NULL").run(a,e)).changes:(await t.prepare("UPDATE waits SET satisfied_at = ? WHERE kind = 'object' AND target_id = ? AND node_id = ? AND satisfied_at IS NULL").run(a,e,i)).changes)}n(T,"settleObjectWaits");async function W(t,e,i=Date.now()){return Number((await t.prepare("UPDATE waits SET satisfied_at = ? WHERE kind = 'object' AND node_id = ? AND satisfied_at IS NULL").run(i,e)).changes)}n(W,"settleNodeObjectWaits");async function R(t){return t??=await o(),(await t.prepare(`SELECT w.wait_id, w.node_id, w.target_id, w.created_at, o.type AS object_type, o.name AS object_name
|
|
7
7
|
FROM waits w JOIN objects o ON o.id = w.target_id
|
|
8
8
|
WHERE w.kind = 'object' AND w.satisfied_at IS NULL AND o.deleted_at IS NULL
|
|
9
|
-
ORDER BY w.node_id, w.created_at, w.seq`).all()).map(e=>({waitId:e.wait_id,nodeId:e.node_id,objectId:e.target_id,createdAt:e.created_at,objectType:e.object_type,objectName:e.object_name}))}n(R,"liveObjectWaitsNamed");async function
|
|
9
|
+
ORDER BY w.node_id, w.created_at, w.seq`).all()).map(e=>({waitId:e.wait_id,nodeId:e.node_id,objectId:e.target_id,createdAt:e.created_at,objectType:e.object_type,objectName:e.object_name}))}n(R,"liveObjectWaitsNamed");async function I(t){return await(await o()).prepare("SELECT 1 FROM waits WHERE node_id = ? AND kind = 'object' AND satisfied_at IS NULL LIMIT 1").get(t)!==void 0}n(I,"hasLiveObjectWait");async function O(t){return await(await o()).prepare(`SELECT 1 FROM waits w JOIN nodes target ON target.node_id = w.target_id
|
|
10
10
|
WHERE w.node_id = ? AND w.kind = 'controller' AND w.satisfied_at IS NULL
|
|
11
|
-
AND target.status IN ('active', 'idle') LIMIT 1`).get(t)!==void 0}n(
|
|
11
|
+
AND target.status IN ('active', 'idle') LIMIT 1`).get(t)!==void 0}n(O,"hasLiveControllerWait");export{p as armControllerWait,S as armObjectWait,O as hasLiveControllerWait,I as hasLiveObjectWait,D as liveControllerWaits,R as liveObjectWaitsNamed,L as readControllerWait,E as readControllerWaits,A as settleDeadControllerWait,g as settleMatchingControllerWait,W as settleNodeObjectWaits,T as settleObjectWaits};
|
|
@@ -30,7 +30,7 @@ export interface EnqueuedNodeMail {
|
|
|
30
30
|
export declare function newId(): string;
|
|
31
31
|
/** A terminal-lifecycle destination's normal or deferred mail is raised to urgent. */
|
|
32
32
|
export declare function effectiveTier(nodeId: string, urgency: InboxTier): Promise<InboxTier>;
|
|
33
|
-
export
|
|
33
|
+
export interface MessageInsert {
|
|
34
34
|
messageId?: string;
|
|
35
35
|
operationId: OperationId;
|
|
36
36
|
createdAt: string;
|
|
@@ -49,7 +49,10 @@ export declare function insertMessage(db: CanvasDb, input: {
|
|
|
49
49
|
};
|
|
50
50
|
causeMessageId?: string | null;
|
|
51
51
|
depth?: number;
|
|
52
|
-
}
|
|
52
|
+
}
|
|
53
|
+
/** Insert messages in order: one sequence bump reserving a block of numbers, one multi-row insert. */
|
|
54
|
+
export declare function insertMessages(db: CanvasDb, inputs: readonly MessageInsert[]): Promise<string[]>;
|
|
55
|
+
export declare function insertMessage(db: CanvasDb, input: MessageInsert): Promise<string>;
|
|
53
56
|
/** The message's creation time, operation id and body — an oversized inline body is clipped
|
|
54
57
|
* into `destinationNodeId`'s messages dir and referenced; with no destination it stays inline. */
|
|
55
58
|
export declare function finalizeNodeMail(input: Omit<NodeMailInput, 'wake'>, destinationNodeId: string | null): {
|
|
@@ -1,8 +1,13 @@
|
|
|
1
|
-
var
|
|
1
|
+
var w=Object.defineProperty;var s=(t,e)=>w(t,"name",{value:e,configurable:!0});import{randomBytes as v,randomUUID as b}from"node:crypto";import{join as E}from"node:path";import{cancelCronsOnWake as N}from"../canvas/crons.js";import{withCanvasWrite as c,openDb as I}from"../canvas/db.js";import{getRow as x}from"../canvas/canvas.js";import{messagesDir as h}from"../canvas/paths.js";import{settleDeadControllerWait as k,settleMatchingControllerWait as R}from"../canvas/waits.js";import{generateOperationId as S,operationIdContext as D,validateOperationId as T}from"../events/operation-id.js";import{clipBody as O}from"../../shared/inbox-entry-body.js";function y(){let t;do t=v(16).toString("hex");while(t==="00000000000000000000000000000000");return t}s(y,"newId");function A(t,e){const r=JSON.stringify(t);if(r===void 0)throw new TypeError(`${e} must be JSON-serializable`);return r}s(A,"stringify");async function L(t,e){return e!=="normal"&&e!=="deferred"?e:(await x(t))?.lifecycle==="terminal"?"urgent":e}s(L,"effectiveTier");function C(t,e){return E(h(t),`${e.replace(/[^0-9]/g,"")}-${b().slice(0,6)}.md`)}s(C,"overflowBodyPath");function M(t){if(typeof t!="object"||t===null)return"";const e=t.body;return typeof e=="string"?e.trim():""}s(M,"inlineBody");async function W(t,e){if(e.length===0)return[];const r=e.map(n=>n.messageId??y()),i=Number((await t.prepare("UPDATE message_sequence SET seq = seq + ? WHERE id = 1 RETURNING seq").get(e.length)).seq)-e.length+1,a=s(n=>e.map((o,u)=>n(o,u)),"col");return await t.prepare(`INSERT INTO messages
|
|
2
2
|
(message_id, seq, operation_id, created_at, sender_node_id, sender_name, kind, label, body_ref, body_json, disposition,
|
|
3
3
|
event, object_id, level, actor_id, cause_message_id, depth)
|
|
4
|
-
|
|
4
|
+
SELECT v.message_id, v.seq::bigint, v.operation_id, v.created_at, v.sender_node_id, v.sender_name, v.kind, v.label, v.body_ref, v.body_json::jsonb, v.disposition,
|
|
5
|
+
v.event, v.object_id, v.level::bigint, v.actor_id, v.cause_message_id, v.depth::bigint
|
|
6
|
+
FROM unnest(?::text[], ?::text[], ?::text[], ?::text[], ?::text[], ?::text[], ?::text[], ?::text[], ?::text[], ?::text[],
|
|
7
|
+
?::text[], ?::text[], ?::text[], ?::text[], ?::text[], ?::text[], ?::text[]) WITH ORDINALITY
|
|
8
|
+
AS v(message_id, seq, operation_id, created_at, sender_node_id, sender_name, kind, label, body_ref, body_json, disposition,
|
|
9
|
+
event, object_id, level, actor_id, cause_message_id, depth, n) ORDER BY v.n`).run(r,a((n,o)=>String(i+o)),a(n=>n.operationId),a(n=>n.createdAt),a(n=>n.senderNodeId),a(n=>n.senderName),a(n=>n.kind),a(n=>n.label),a(n=>n.bodyRef),a(n=>n.bodyJson===void 0?null:A(n.bodyJson,"message body")),a(n=>n.disposition),a(n=>n.event?.event??null),a(n=>n.event?.objectId??null),a(n=>n.event===void 0?null:String(n.event.level)),a(n=>n.event?.actorId??null),a(n=>n.causeMessageId??null),a(n=>String(n.depth??0))),r}s(W,"insertMessages");async function _(t,e){return(await W(t,[e]))[0]}s(_,"insertMessage");async function f(t,e,r,d,i,a,n){const o=y();return await t.prepare(`INSERT INTO deliveries
|
|
5
10
|
(delivery_id, message_id, destination_id, urgency, wake, state, idempotency_key, created_at, updated_at)
|
|
6
|
-
VALUES (?, ?, ?, ?, ?, 'pending', ?, ?, ?)`).run(
|
|
7
|
-
FROM deliveries d JOIN messages m ON m.message_id = d.message_id WHERE d.idempotency_key = ?`).get(e.idempotencyKey);if(l!==void 0)return{messageId:l.message_id,deliveryId:l.delivery_id,urgency:l.urgency,createdAt:l.created_at}}const
|
|
8
|
-
WHERE w.node_id = ? AND w.kind = 'controller' AND w.target_id = ? AND w.satisfied_at IS NULL`).get(
|
|
11
|
+
VALUES (?, ?, ?, ?, ?, 'pending', ?, ?, ?)`).run(o,e,r,d,i,n??null,a,a),o}s(f,"insertNodeDelivery");function g(t,e){const r=new Date().toISOString(),d=t.operationId===void 0?D.current()??S():T(t.operationId);let i=t.bodyRef??null,a=t.bodyJson;if(i===null&&e!==null&&t.senderNodeId!=="human"){const n=M(a),o=O(n);o.clipped&&(i=C(e,r),a={...a,body:o.text,body_full:n})}return{createdAt:r,operationId:d,bodyRef:i,bodyJson:a}}s(g,"finalizeNodeMail");async function j(t,e){const r=g(e,t);return await c(async d=>{const i=await d.prepare("SELECT run_id FROM nodes WHERE node_id = ?").get(t);if(i?.run_id&&(await d.prepare("SELECT deleting_at FROM nodes WHERE node_id = ?").get(i.run_id))?.deleting_at)throw new Error("run is deleting");if(e.idempotencyKey!==void 0){const l=await d.prepare(`SELECT d.delivery_id, d.message_id, d.urgency, m.created_at
|
|
12
|
+
FROM deliveries d JOIN messages m ON m.message_id = d.message_id WHERE d.idempotency_key = ?`).get(e.idempotencyKey);if(l!==void 0)return{messageId:l.message_id,deliveryId:l.delivery_id,urgency:l.urgency,createdAt:l.created_at}}const a=Date.now(),n=await L(t,e.urgency),o=await _(d,{messageId:e.messageId,operationId:r.operationId,createdAt:r.createdAt,senderNodeId:e.senderNodeId??null,senderName:e.senderName??null,kind:e.kind,label:e.label,bodyRef:r.bodyRef,bodyJson:r.bodyJson,disposition:e.disposition??null}),u=await f(d,o,t,n,e.wake,a,e.idempotencyKey);return await R(t,e.senderNodeId??null,a,d),await e.withinEnqueue?.(d,o),e.wake===1&&n!=="deferred"&&await p(t),{messageId:o,deliveryId:u,urgency:n,createdAt:r.createdAt}})}s(j,"enqueueNodeMail");function z(t){switch(t){case"interrupt":return{urgency:"critical",wake:1};case"steer":return{urgency:"urgent",wake:1};case"after-turn":return{urgency:"normal",wake:1};case"next-turn":return{urgency:"deferred",wake:0}}}s(z,"listenDeliveryTier");async function m(t,e,r){const d={kind:"update",label:r.label??"notice",bodyJson:{body:r.body},urgency:r.tier,wake:r.wake},i=g(d,e),a=Date.now(),n=await _(t,{operationId:i.operationId,createdAt:i.createdAt,senderNodeId:null,senderName:null,kind:d.kind,label:d.label,bodyRef:i.bodyRef,bodyJson:i.bodyJson,disposition:null}),o=await f(t,n,e,r.tier,r.wake,a);return{messageId:n,deliveryId:o,urgency:r.tier,createdAt:i.createdAt}}s(m,"insertNodeNotice");async function p(t){await c(async e=>{for(const r of await N(t))await m(e,t,{body:`Your cron ${r.name}, next scheduled for ${r.fire_at}, was canceled by this wake. Re-create it if you still need it.`,label:"cron canceled",tier:"normal",wake:1})})}s(p,"consumeDeadlineOnWake");async function G(t,e,r){const d=await m(t,e,r);return r.wake===1&&r.tier!=="deferred"&&await p(e),d}s(G,"queueNodeNotice");async function V(t,e=Date.now()){return Number((await(await I()).prepare("UPDATE deliveries SET canceled_at = ?, updated_at = ? WHERE delivery_id = ? AND canceled_at IS NULL").run(e,e,t)).changes)===1}s(V,"cancelDelivery");async function Q(t,e={}){return await c(async r=>{const d=["d.destination_id = ?","d.canceled_at IS NULL","d.state IN ('pending', 'handed_off')"],i=[t];e.senderNodeId!==void 0&&(d.push("m.sender_node_id IS NOT DISTINCT FROM ?"),i.push(e.senderNodeId)),e.kind!==void 0&&(d.push("m.kind = ?"),i.push(e.kind));const a=await r.prepareUncached(`SELECT d.delivery_id FROM deliveries d JOIN messages m ON m.message_id = d.message_id WHERE ${d.join(" AND ")}`).all(...i);if(a.length===0)return[];const n=Date.now();return await r.prepareUncached(`UPDATE deliveries SET canceled_at = ?, updated_at = ? WHERE delivery_id IN (${a.map(()=>"?").join(",")})`).run(n,n,...a.map(o=>o.delivery_id)),a.map(o=>o.delivery_id)})}s(Q,"cancelPendingNodeMail");async function X(t,e){return await c(async r=>{const d=Date.now(),i=await r.prepare(`SELECT target.status AS controller_status FROM waits w LEFT JOIN nodes target ON target.node_id = w.target_id
|
|
13
|
+
WHERE w.node_id = ? AND w.kind = 'controller' AND w.target_id = ? AND w.satisfied_at IS NULL`).get(t,e);if(i===void 0||i.controller_status==="active"||i.controller_status==="idle")return null;const a=await j(t,{kind:"urgent",label:"declared controller is no longer live",bodyJson:{body:`Controller ${e} is no longer live; the declared message wait was cleared.`},urgency:"urgent",wake:1});if(!await k(t,e,d,r))throw new Error(`controller wait changed while notifying ${t}`);return a})}s(X,"enqueueControllerDeathNotice");export{V as cancelDelivery,Q as cancelPendingNodeMail,p as consumeDeadlineOnWake,L as effectiveTier,X as enqueueControllerDeathNotice,j as enqueueNodeMail,g as finalizeNodeMail,_ as insertMessage,W as insertMessages,z as listenDeliveryTier,y as newId,G as queueNodeNotice};
|
|
@@ -64,7 +64,7 @@ export declare function localGrants(): Promise<GrantRecord[]>;
|
|
|
64
64
|
export declare function otherLiveGrantOfApp(app: string, sub: string): Promise<boolean>;
|
|
65
65
|
/** Every provider id a scope of an active grant's resolved set names: a
|
|
66
66
|
* `<id>:<group>` string whose id is not `crtr` (the runtime's own namespace). */
|
|
67
|
-
export declare function providerIdsFromGrants(grants: readonly GrantRecord[]): string[];
|
|
67
|
+
export declare function providerIdsFromGrants(grants: readonly Pick<GrantRecord, 'status' | 'resolved_scopes'>[]): string[];
|
|
68
68
|
/** The provider ids an active grant this machine acts on names: `providerIdsFromGrants(localGrants())`, computed in the database. On a cloud
|
|
69
69
|
* role the mirror holds every person's grants and each resolved scope list runs to hundreds of kilobytes, so loading and parsing the
|
|
70
70
|
* whole mirror held up every request behind it; this returns one short row per provider. A row whose computed columns lag its
|
|
@@ -73,6 +73,9 @@ export declare function providerIdsFromGrants(grants: readonly GrantRecord[]): s
|
|
|
73
73
|
export declare function activeProviderIds(): Promise<string[]>;
|
|
74
74
|
/** Whether this machine acts on any active grant (`localGrants()` holds one), read without loading a row. */
|
|
75
75
|
export declare function anyActiveGrant(): Promise<boolean>;
|
|
76
|
+
/** Whether any active grant of `sub` this machine acts on names the app `id`: its resolved set holds a `<id>:…` scope, in any mode.
|
|
77
|
+
* Read in the database for the reason `activeProviderIds` is. */
|
|
78
|
+
export declare function activeGrantNamesApp(sub: string, id: string): Promise<boolean>;
|
|
76
79
|
/** The `sub` of every mirrored grant, whatever its status: who the grants are for, without reading their scopes. A row whose
|
|
77
80
|
* computed columns lag its revision is left out, as `allGrants()` leaves it out. */
|
|
78
81
|
export declare function grantSubs(): Promise<string[]>;
|
|
@@ -97,8 +100,13 @@ export declare function activeGrantsOfPerson(person: string): Promise<ActiveGran
|
|
|
97
100
|
* acting for one person reads `grantsOfPerson`, and a pass over every person reads `activeProviderIds`, `anyActiveGrant`, `grantSubs`
|
|
98
101
|
* or `activeGrants`. */
|
|
99
102
|
export declare function allGrants(): Promise<GrantRecord[]>;
|
|
100
|
-
/** `person`'s (`user:<id>`) mirrored grants, whatever their status.
|
|
101
|
-
|
|
103
|
+
/** What `providers.ts` reads of `person`'s (`user:<id>`) mirrored grants, whatever their status: who, whether active, and the resolved scopes.
|
|
104
|
+
* The consent scope list, dependencies and inference endpoint stay in the database (a grant row runs to about 18 KB). The consent
|
|
105
|
+
* list is only tested for presence, so a row whose computed columns lag its revision still reads as no grant, as `record()` reads it
|
|
106
|
+
* (`computedFor`). Not shared, because it needs the wide columns: `record()` also drops a row whose `scopes_json`, `dependencies_json` or
|
|
107
|
+
* `inference_endpoint_json` fails to parse or validate. `replaceGrants`, the only writer, stores `JSON.stringify` of lists it validated, so
|
|
108
|
+
* none of the three can be malformed in practice; if one were, this returns the grant and `record()` would not. */
|
|
109
|
+
export declare function grantsOfPerson(person: string): Promise<Array<Pick<GrantRecord, 'sub' | 'status' | 'resolved_scopes'>>>;
|
|
102
110
|
/** Whether a grant's `expires_at` has passed. An unparsable time reads as expired (fail closed). */
|
|
103
111
|
export declare function grantExpired(grant: Pick<GrantRecord, 'expires_at'>): boolean;
|
|
104
112
|
/** The active form of a grant record read earlier, or null when it is not active, is past `expires_at`, or is unparsable. */
|
|
@@ -1,9 +1,11 @@
|
|
|
1
|
-
var R=Object.defineProperty;var
|
|
1
|
+
var R=Object.defineProperty;var t=(e,r)=>R(e,"name",{value:r,configurable:!0});import{createHash as D}from"node:crypto";import{parseScope as L}from"@north-light/identity";import{openDb as p,withCanvasWrite as N}from"../canvas/db.js";import{isUnsandboxedMachine as T}from"../runtime/unsandboxed.js";import{replaceWrittenBy as I,userSubject as C}from"../permissions/facts.js";import{GROUP_TYPE as $}from"../permissions/builtin.js";const M=["not_started","pending","ready","failed","unavailable"],k=["ultra","strong","medium","light"];function E(){const e=process.env.CRTR_RUNTIME;return e?{sql:" AND runtime = ?",args:[e]}:{sql:"",args:[]}}t(E,"runtimeScope");async function i(e,r,n=[]){const s=E();return await(await p()).prepare(`SELECT ${e} FROM grants WHERE (${r})${s.sql}`).all(...n,...s.args)}t(i,"grantRows");async function u(e,r,n=[]){return(await i(e,r,n))[0]}t(u,"grantRow");function U(e){return!/\u0000|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/.test(e)}t(U,"jsonbSafe");function l(e){if(!Array.isArray(e))throw new TypeError("grant scopes must be a list");return e.map(r=>{if(!r||typeof r!="object"||typeof r.scope!="string"||!U(r.scope)||!["always","ask"].includes(r.mode))throw new TypeError("invalid grant scope entry");return{scope:r.scope,mode:r.mode}})}t(l,"entries");function F(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{state:r,message:n,next:s,step:a}=e;return typeof r!="string"||!M.includes(r)||n!==void 0&&typeof n!="string"||a!==void 0&&typeof a!="string"||typeof s!="string"||!s?null:{state:r,...n===void 0?{}:{message:n},next:s,...a===void 0?{}:{step:a}}}t(F,"dependencyOf");function O(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const r={};for(const[n,s]of Object.entries(e)){const a=F(s);a&&(r[n]=a)}return r}t(O,"dependenciesOf");function G(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{base_url:r,rungs:n}=e;if(typeof r!="string"||!r||!n||typeof n!="object"||Array.isArray(n))return null;const s={};for(const a of k){const o=n[a];typeof o=="string"&&o&&(s[a]=o)}return Object.keys(s).length?{base_url:r.replace(/\/+$/,""),rungs:s}:null}t(G,"inferenceEndpointOf");function A(e,r,n,s){return r===e&&n&&s}t(A,"computedFor");function f(e){if(!A(e.rev,e.computed_rev,e.scopes_json!==null,e.resolved_scopes_json!==null))throw new TypeError("grant columns are not computed for this revision");return{id:e.id,runtime:e.runtime,sub:e.sub,grantee:e.grantee,rev:e.rev,scopes:l(JSON.parse(e.scopes_json)),resolved_scopes:l(JSON.parse(e.resolved_scopes_json)),spend_cap:e.spend_cap,expires_at:e.expires_at,status:e.status,revoked_at:e.revoked_at,approved_at:e.approved_at,payer:e.payer,dependencies:O(JSON.parse(e.dependencies_json??"{}")),run_notice_url:e.run_notice_url??null,inference_endpoint:e.inference_endpoint_json?G(JSON.parse(e.inference_endpoint_json)):null,synced_at:e.synced_at??""}}t(f,"record");function d(e){if(!e||e.status!=="active")return null;try{return q(f(e))}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}t(d,"active");function _(e){return e.grantee!=="app:terminal"&&T()}t(_,"mirrorOnly");async function ne(){return(await J()).filter(e=>!_(e))}t(ne,"localGrants");async function te(e,r){return!_({grantee:e})&&await u("1","grantee = ? AND sub <> ? AND status <> 'removed'",[e,r])!==void 0}t(te,"otherLiveGrantOfApp");const y="[A-Za-z0-9_-]{1,64}",H=new RegExp(`^(${y}):(${y})$`);function W(e){const r=new Set;for(const n of e)if(n.status==="active")for(const{scope:s}of n.resolved_scopes){const a=H.exec(s);a&&a[1]!=="crtr"&&r.add(a[1])}return[...r].sort()}t(W,"providerIdsFromGrants");async function se(){const e=E();return(await(await p()).prepare(`SELECT DISTINCT m[1] AS id FROM (
|
|
2
2
|
SELECT DISTINCT e->>'scope' AS scope FROM grants
|
|
3
3
|
CROSS JOIN LATERAL jsonb_array_elements(CASE WHEN jsonb_typeof(resolved_scopes_json::jsonb) = 'array' THEN resolved_scopes_json::jsonb ELSE '[]' END) e
|
|
4
|
-
WHERE ${
|
|
4
|
+
WHERE ${m}${x()}${e.sql}) s
|
|
5
5
|
CROSS JOIN LATERAL regexp_match(s.scope, '^(${y}):${y}$') m
|
|
6
|
-
WHERE m[1] <> 'crtr'`).all(...e.args)).map(
|
|
6
|
+
WHERE m[1] <> 'crtr'`).all(...e.args)).map(n=>n.id).sort()}t(se,"activeProviderIds");async function ae(){const e=E();return await(await p()).prepare(`SELECT 1 FROM grants WHERE ${m}${x()}${e.sql} LIMIT 1`).get(...e.args)!==void 0}t(ae,"anyActiveGrant");async function oe(e,r){return await u("1",`sub = ? AND ${m}${x()} AND EXISTS (
|
|
7
|
+
SELECT 1 FROM jsonb_array_elements(CASE WHEN jsonb_typeof(resolved_scopes_json::jsonb) = 'array' THEN resolved_scopes_json::jsonb ELSE '[]' END) e
|
|
8
|
+
WHERE starts_with(e->>'scope', ?))`,[e,`${r}:`])!==void 0}t(oe,"activeGrantNamesApp");const m="status = 'active' AND computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL",P="computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL";function x(){return T()?" AND grantee = 'app:terminal'":""}t(x,"localOnly");async function ce(){return(await i("DISTINCT sub",P)).map(e=>e.sub)}t(ce,"grantSubs");async function ie(e){return j(e===void 0?await i("*","status = 'active'"):await i("*","sub = ? AND status = 'active'",[e]))}t(ie,"activeGrants");async function ue(e){const r=await i("*","sub = ? AND status = 'active'",[e]);return new Set(W(r.flatMap(n=>{try{return[f(n)]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})))}t(ue,"grantedProviderIds");function pe(e,r){return e.source_marketplace===null&&e.source_path===null&&r.has(e.name)}t(pe,"isProviderBundleRow");async function de(e){return(await i("*","sub = ? AND status = 'active'",[e])).flatMap(n=>{const s=d(n);return s===null?[]:[s]})}t(de,"activeGrantsOfPerson");async function J(){return j(await i("*","true"))}t(J,"allGrants");async function le(e){return(await i("sub, status, rev, computed_rev, resolved_scopes_json, scopes_json IS NOT NULL AS has_scopes","sub = ?",[e])).flatMap(n=>{if(!A(n.rev,n.computed_rev,n.has_scopes,n.resolved_scopes_json!==null))return[];try{return[{sub:n.sub,status:n.status,resolved_scopes:l(JSON.parse(n.resolved_scopes_json))}]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})}t(le,"grantsOfPerson");function j(e){return e.flatMap(r=>{try{return[f(r)]}catch(n){if(n instanceof TypeError||n instanceof SyntaxError)return[];throw n}})}t(j,"records");function V(e){return e.expires_at!==null&&!(Date.parse(e.expires_at)>Date.now())}t(V,"grantExpired");function q(e){if(e.status!=="active"||V(e))return null;try{const r=e.resolved_scopes.map(({scope:n})=>L(n));return{...e,resolved:e.resolved_scopes.flatMap(({mode:n},s)=>n==="always"?[r[s]]:[])}}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}t(q,"activeRecord");function S(e){return Array.isArray(e)?`[${e.map(S).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().filter(r=>e[r]!==void 0).map(r=>`${JSON.stringify(r)}:${S(e[r])}`).join(",")}}`:JSON.stringify(e)??"null"}t(S,"canonicalJson");function fe(e){const r={rev:e.rev,resolved_scopes:e.resolved_scopes,spend_cap:e.spend_cap,payer:e.payer,dependencies:e.dependencies??{},...e.inference_endpoint?{inference_endpoint:e.inference_endpoint}:{}};return D("sha256").update(S(r)).digest("base64url").slice(0,22)}t(fe,"grantVersion");async function _e(e){return!!await u("1","id = ?",[e])}t(_e,"hasGrant");async function ye(e){return await u("rev, status","id = ?",[e])??null}t(ye,"grantSyncState");async function ve(e,r){return await u("rev, status","grantee = ? AND sub = ?",[e,r])??null}t(ve,"grantSyncStateFor");async function B(e){const r=await u("*","id = ?",[e]);if(!r)return null;try{return f(r)}catch(n){if(n instanceof TypeError||n instanceof SyntaxError)return null;throw n}}t(B,"grantRecord");async function ge(e){const r=await u("*","id = ?",[e]);if(!r)return{standing:"inactive",rev:null,sub:null,grantee:null,status:null,removal_done_at:null,record:null};const n={rev:r.rev,sub:r.sub,grantee:r.grantee,status:r.status,removal_done_at:r.removal_done_at??null};if(r.status!=="active")return{...n,standing:"inactive",record:null};if(r.computed_rev!==r.rev)return{...n,standing:"lagging",record:null};const s=d(r);return s===null?{...n,standing:"inactive",record:null}:{...n,standing:"active",record:s}}t(ge,"grantStanding");async function Ee(e){return(await i("id",e)).map(r=>r.id)}t(Ee,"grantIdsWhere");async function me(e){return(e?(await B(e))?.payer:null)??"user"}t(me,"payerOfGrant");async function X(e){return d(await u("*","id = ?",[e]))}t(X,"activeGrant");async function xe(e,r){return d(await u("*","grantee = ? AND sub = ?",[e,r]))}t(xe,"grantFor");async function Se(e){if(_({grantee:e}))return null;const r=await i("*","grantee = ? AND status = 'active'",[e]);if(r.length>1)throw new Error(`multiple active grants for ${e}`);return d(r[0])}t(Se,"activeGrantForApp");async function Ne(e){const r=await X(e);return r&&r.run_notice_url&&!_(r)?{url:r.run_notice_url,sub:r.sub,grantee:r.grantee}:null}t(Ne,"runNoticeTarget");async function Te(e){const r=await i("*","grantee = 'app:terminal' AND sub = ? AND status = 'active'",[e]);if(r.length>1)throw new Error(`multiple active terminal grants for ${e}`);return d(r[0])}t(Te,"terminalGrant");async function Oe(){return(await(await p()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value??null}t(Oe,"grantsSource");async function Ae(e){return(await(await p()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value===e}t(Ae,"hasSyncedGrants");async function je(e){return(await e.prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value!=="local"?0:(await e.prepare("DELETE FROM runtime_state WHERE key = 'grants_source'").run(),Number((await e.prepare("DELETE FROM grants").run()).changes))}t(je,"dropLocalGrantMirror");async function be(){return await N(async e=>Number((await e.prepare("UPDATE grants SET computed_rev = rev WHERE computed_rev IS NULL AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL").run()).changes))}t(be,"backfillComputedRev");function we(e){if(e===void 0)return[];if(!Array.isArray(e))throw new TypeError("invalid grant sync response");return e.map(r=>{const{team:n,members:s}=r??{};if(typeof n!="string"||!/^team:\S+$/.test(n)||!Array.isArray(s)||s.some(a=>typeof a!="string"||!/^user:[^\s*]+$/.test(a)))throw new TypeError("invalid grant sync response");return{team:n,members:s}})}t(we,"teamsOf");async function he(e,r,n,s=[]){const a=new Set;for(const o of e){if(a.has(o.id)||!o.id||!o.runtime||!o.sub||!o.grantee||!Number.isInteger(o.rev)||!["active","revoked","removed"].includes(o.status))throw new TypeError("invalid grant sync response");a.add(o.id),l(o.scopes),l(o.resolved_scopes)}await N(async o=>{let v=0;const g=[...a];v+=Number((await(g.length?o.prepareUncached(`DELETE FROM grants WHERE id NOT IN (${g.map(()=>"?").join(",")})`).run(...g):o.prepareUncached("DELETE FROM grants").run())).changes);const b=o.prepare(`INSERT INTO grants
|
|
7
9
|
(id, runtime, sub, grantee, rev, scopes_json, resolved_scopes_json, spend_cap, expires_at,
|
|
8
10
|
status, revoked_at, approved_at, payer, dependencies_json, run_notice_url, inference_endpoint_json, synced_at, computed_rev)
|
|
9
11
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
@@ -17,4 +19,4 @@ var R=Object.defineProperty;var n=(e,r)=>R(e,"name",{value:r,configurable:!0});i
|
|
|
17
19
|
grants.run_notice_url, grants.inference_endpoint_json, grants.computed_rev)
|
|
18
20
|
IS DISTINCT FROM (excluded.runtime, excluded.sub, excluded.grantee, excluded.rev, excluded.scopes_json, excluded.resolved_scopes_json,
|
|
19
21
|
excluded.spend_cap, excluded.expires_at, excluded.status, excluded.revoked_at, excluded.approved_at, excluded.payer,
|
|
20
|
-
excluded.dependencies_json, excluded.run_notice_url, excluded.inference_endpoint_json, excluded.computed_rev)`);for(const c of e)
|
|
22
|
+
excluded.dependencies_json, excluded.run_notice_url, excluded.inference_endpoint_json, excluded.computed_rev)`);for(const c of e)v+=Number((await b.run(c.id,c.runtime,c.sub,c.grantee,c.rev,JSON.stringify(c.scopes),JSON.stringify(c.resolved_scopes),c.spend_cap,c.expires_at,c.status,c.revoked_at,c.approved_at,c.payer,JSON.stringify(O(c.dependencies)),c.run_notice_url??null,c.inference_endpoint?JSON.stringify(c.inference_endpoint):null,c.synced_at,c.rev)).changes);await I(o,"directory",$,"member",s.flatMap(({team:c,members:w})=>w.map(h=>({resourceId:c,subject:C(h)})))),await o.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_source', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(n),v>0&&await o.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_generation', '1') ON CONFLICT(key) DO UPDATE SET value = CAST(CAST(runtime_state.value AS INTEGER) + 1 AS TEXT)").run()})}t(he,"replaceGrants");async function Re(){const e=await(await p()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_generation'").get();return e?Number(e.value):0}t(Re,"grantsGeneration");export{X as activeGrant,Se as activeGrantForApp,oe as activeGrantNamesApp,ie as activeGrants,de as activeGrantsOfPerson,se as activeProviderIds,q as activeRecord,J as allGrants,ae as anyActiveGrant,be as backfillComputedRev,O as dependenciesOf,je as dropLocalGrantMirror,V as grantExpired,xe as grantFor,Ee as grantIdsWhere,B as grantRecord,ge as grantStanding,ce as grantSubs,ye as grantSyncState,ve as grantSyncStateFor,fe as grantVersion,ue as grantedProviderIds,Re as grantsGeneration,le as grantsOfPerson,Oe as grantsSource,_e as hasGrant,Ae as hasSyncedGrants,G as inferenceEndpointOf,pe as isProviderBundleRow,ne as localGrants,_ as mirrorOnly,te as otherLiveGrantOfApp,me as payerOfGrant,W as providerIdsFromGrants,he as replaceGrants,Ne as runNoticeTarget,E as runtimeScope,we as teamsOf,Te as terminalGrant};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var b=Object.defineProperty;var d=(t,e)=>b(t,"name",{value:e,configurable:!0});import{relative as x,sep as _}from"node:path";import{runningJobs as y}from"../graph/jobs.js";import{appSpace as h}from"../layout.js";import{getNode as l,recordSettledTurn as S}from"../canvas/index.js";import{transition as E}from"../runtime/lifecycle.js";import{openDb as m}from"../canvas/db.js";import{emitEvent as w}from"../events/emit.js";import{grantedMounts as R,isGrantedSource as k,mountAllowed as I}from"../spaces/mounts.js";import{permissionsForRun as g}from"../spaces/permissions.js";import{stopNodeSandboxes as P}from"../spaces/stop.js";import{activeGrantForApp as A}from"./mirror.js";import{launcherPresent as C,listSandboxes as F,stopSandboxPid as M}from"./sandboxes.js";import{checkCronFire as N}from"../../daemon/cron/authority.js";import{cronExecutionFor as O}from"../../daemon/cron/live-runs.js";import{cronExecutionsReady as T}from"../../daemon/cron/run-socket.js";import{flatMapAsync as W}from"../async-array.js";import{personId as D}from"../canvas/person.js";async function v(){return new Map((await(await m()).prepare("SELECT uid, app, status FROM app_users").all()).map(t=>[t.uid,{app:t.app,status:t.status}]))}d(v,"appUserOwners");async function G(t,e){e??=await v();const n=e.get(t.uid),p=t.nodeId.startsWith("cron-"),a=p?O(t.nodeId.slice(5)):void 0;if(p&&(a===void 0||!n))return"permission_revoked";let o=null;if(a!==void 0&&n.status==="active"){const i=await N({grantee:a.grantee,sub:a.sub,grant_id:a.grantId,scopes:a.scopes});if(!i.allowed)return a.refusal??={reason:i.reason,message:i.message},"permission_revoked";o=i.scopes}if(!n||n.app==="app:terminal")return null;if(n.status!=="active")return"app_removed";const s=await l(t.nodeId);try{let i;if(a!==void 0)i=await g(a.grantee,a.sub,a.grantId,o);else if(s&&s.grantee===n.app)i=await g(n.app,s.sub??D(),s.grant_id??null,s.scopes??null);else{const r=await A(n.app);if(!r)return"permission_revoked";i=await g(n.app,r.sub,r.id,null)}const c=R(i),u=h(n.app).root;return t.mounts.every(r=>{const f=x(u,r.source);return f===""||f!==".."&&!f.startsWith(`..${_}`)&&!f.startsWith(_)||!k(n.app,r.source)||I(r,c)})?null:"permission_revoked"}catch{return"permission_revoked"}}d(G,"exceeds");async function L(t){const e=await l(t);if(!e)return;(e.status==="active"||e.status==="idle")&&await E(t,"release");const n=new Date().toISOString();await S(t,n),e.run_id&&e.run_id!==t&&await(await m()).prepare("UPDATE nodes SET last_settled_at = COALESCE(last_settled_at, ?) WHERE node_id = ?").run(n,e.run_id)}d(L,"afterRevocationStop");async function U(t){const e=new Set,n=await l(t);n?.pi_pid!=null&&e.add(n.pi_pid);for(const p of await y(await m(),t))p.pgid!==null&&e.add(p.pgid);return e}d(U,"nodePids");async function $(){if(!C())return{completion:Promise.resolve()};await T();const t=await F(),e=await v(),n=await W(t,async o=>{const s=await G(o,e);return s?[{sandbox:o,reason:s}]:[]}),p=[],a=new Map;for(const o of n){w({level:"info",event:"daemon.grants.sandbox_stop",fields:{sandbox_node:o.sandbox.nodeId,pid:o.sandbox.pid,grantee:e.get(o.sandbox.uid).app,reason:o.reason}});const s=a.get(o.sandbox.nodeId)??[];s.push(o),a.set(o.sandbox.nodeId,s)}for(const[o,s]of a){const i=await l(o),c=i?await U(o):new Set,u=i!==null&&s.some(({sandbox:r})=>c.has(r.pid));p.push((async()=>{if(u){const r=await P(o,"permission_revoked",{holdRecovery:!0,after:d(()=>L(o),"after")});if(!r.confirmed)throw r.error??new Error(`stop of ${o} was not confirmed`)}for(const{sandbox:r}of s)(!u||!c.has(r.pid))&&await M(r.pid)})().catch(r=>{w({level:"error",event:"daemon.grants.sandbox_stop_failed",...i?{node_id:o}:{fields:{sandbox_node:o}},error:r})}))}return{completion:Promise.all(p).then(()=>{})}}d($,"sweepSandboxes");async function ie(t=e=>{}){try{const{completion:e}=await $();t(e)}catch(e){w({level:"error",event:"daemon.grants.sweep_failed",error:e})}}d(ie,"onGrantSync");export{L as afterRevocationStop,G as exceeds,ie as onGrantSync,$ as sweepSandboxes};
|
|
@@ -47,3 +47,12 @@ export declare function publish(db: CanvasDb, input: CanvasEvent, reposFn?: Repo
|
|
|
47
47
|
message_id: string | null;
|
|
48
48
|
depth: number;
|
|
49
49
|
}>;
|
|
50
|
+
/** `publish` for several events in one pass, in order, with the same per-event filters and the same result for each.
|
|
51
|
+
* Candidate rows, the in-repo test, watcher rows, stubs and each watcher's read check are set queries over all events; messages
|
|
52
|
+
* go in through `insertMessages` and receivers are enqueued per message. An event that supersedes flushes the messages before it
|
|
53
|
+
* first, so it sees the deliveries the earlier events queued. */
|
|
54
|
+
export declare function publishMany(db: CanvasDb, inputs: readonly CanvasEvent[], reposFn?: ReposFn): Promise<Array<{
|
|
55
|
+
delivered: number;
|
|
56
|
+
message_id: string | null;
|
|
57
|
+
depth: number;
|
|
58
|
+
}>>;
|