@north-light/cli 0.3.727 → 0.3.729

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 +1 @@
1
- export declare const STARTER_SETUP_SCRIPT = "#!/usr/bin/env bash\n# Setup script for a crtr cloud environment.\n#\n# How it runs\n# - Once per image build, as root, in /work, on Alpine Linux (use apk, not apt). Every sandbox of the profile starts from the result.\n# - Your repositories are already checked out at /work/<repo name> before this runs.\n# - The sandbox user is \"crtr\" (home /home/crtr). Files you create for it must be chowned to it.\n# - Already done for you: git, gh, curl, ripgrep, Node 24, pnpm. For every repository with a pnpm-lock.yaml, its packages are already\n# downloaded into a shared pnpm store, so `pnpm install` in a sandbox links instead of downloading.\n# - Output goes to /work/.crtr/setup.log in the image. If this script exits non-zero, sandboxes refuse to start and point at that log.\n# - The image keeps /work, /home/crtr, /usr, /etc and /lib. Anything written to /root or /tmp is lost.\n#\n# Secrets (API keys, database URLs) do not belong here: anything written by this script is baked into the image. Store them on the profile\n# instead and every sandbox gets them as environment variables:\n# printf '%s' \"<value>\" | crtr profile env set <profile> --name OPENAI_API_KEY\n#\n# Apply this file with:\n# crtr profile environment set --profile <profile> --setup-script-file ./setup.sh\n# then watch the build with `crtr profile environment show --profile <profile>` (ready when image_revision equals recipe_revision).\n#\n# Uncomment the sections you need. Delete the rest.\n\nset -euo pipefail\n\n# \u2500\u2500 1. System packages \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# Alpine package names: https://pkgs.alpinelinux.org/packages\n# apk add --no-cache build-base python3 # native npm modules (node-gyp)\n# apk add --no-cache jq sqlite # command-line tools your agents use\n# apk add --no-cache chromium # headless browser tests\n\n# \u2500\u2500 2. A local Postgres \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# Creates a database cluster owned by crtr. Section 5 starts it on the agent's first shell command.\n# apk add --no-cache postgresql postgresql-contrib\n# mkdir -p /run/postgresql && chown crtr /run/postgresql\n# su crtr -c 'initdb -D /home/crtr/pg -U postgres --auth=trust'\n\n# \u2500\u2500 3. App dependencies \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# pnpm repositories are already prepared (see above). For npm or yarn, or to install fully at build time:\n# (cd /work/<repo name> && npm ci)\n# (cd /work/<repo name> && pnpm install --frozen-lockfile)\n# Each full install can take 0.5-1.5 GB of the sandbox disk. Install only the repositories agents work in most.\n\n# \u2500\u2500 4. Global CLIs \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# npm install -g typescript tsx\n# curl -fsSL https://example.com/install.sh | sh\n\n# \u2500\u2500 5. Start services on the agent's first command \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# The agent's shell is non-interactive bash, which runs the file named by $BASH_ENV before each command. Write a start script here, then\n# set BASH_ENV on the profile: printf '%s' /home/crtr/.services-up.sh | crtr profile env set <profile> --name BASH_ENV\n# cat > /home/crtr/.services-up.sh <<'UP'\n# pg_ctl -D /home/crtr/pg status >/dev/null 2>&1 || pg_ctl -D /home/crtr/pg -o \"-k /tmp -h localhost\" -l /tmp/pg.log -w start >/dev/null 2>&1 || true\n# UP\n# chown crtr /home/crtr/.services-up.sh\n\n# \u2500\u2500 6. Seed files and config \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# cp /work/<repo name>/.env.example /work/<repo name>/.env # placeholders only; real values come from `crtr profile env`\n# chown -R crtr /work/<repo name>\n";
1
+ export declare const STARTER_SETUP_SCRIPT = "#!/usr/bin/env bash\n# Setup script for a crtr cloud environment.\n#\n# How it runs\n# - Once per image build, as root, in /work, on Alpine Linux (use apk, not apt). Every sandbox of the profile starts from the result.\n# - Your repositories are already checked out at /work/<repo name> before this runs.\n# - The sandbox user is \"crtr\" (home /home/crtr). Files you create for it must be chowned to it.\n# - Already done for you: git, gh, curl, ripgrep, Node 24, pnpm. Packages are not pre-installed: run `pnpm install` in a sandbox,\n# or install at build time below.\n# - Output goes to /work/.crtr/setup.log in the image. If this script exits non-zero, sandboxes refuse to start and point at that log.\n# - The image keeps /work, /home/crtr, /usr, /etc and /lib. Anything written to /root or /tmp is lost.\n#\n# Secrets (API keys, database URLs) do not belong here: anything written by this script is baked into the image. Store them on the profile\n# instead and every sandbox gets them as environment variables:\n# printf '%s' \"<value>\" | crtr profile env set <profile> --name OPENAI_API_KEY\n#\n# Apply this file with:\n# crtr profile environment set --profile <profile> --setup-script-file ./setup.sh\n# then watch the build with `crtr profile environment show --profile <profile>` (ready when image_revision equals recipe_revision).\n#\n# Uncomment the sections you need. Delete the rest.\n\nset -euo pipefail\n\n# \u2500\u2500 1. System packages \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# Alpine package names: https://pkgs.alpinelinux.org/packages\n# apk add --no-cache build-base python3 # native npm modules (node-gyp)\n# apk add --no-cache jq sqlite # command-line tools your agents use\n# apk add --no-cache chromium # headless browser tests\n\n# \u2500\u2500 2. A local Postgres \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# Creates a database cluster owned by crtr. Section 5 starts it on the agent's first shell command.\n# apk add --no-cache postgresql postgresql-contrib\n# mkdir -p /run/postgresql && chown crtr /run/postgresql\n# su crtr -c 'initdb -D /home/crtr/pg -U postgres --auth=trust'\n\n# \u2500\u2500 3. App dependencies \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# To install a repository's packages at build time:\n# (cd /work/<repo name> && npm ci)\n# (cd /work/<repo name> && pnpm install --frozen-lockfile)\n# Each full install can take 0.5-1.5 GB of the sandbox disk. Install only the repositories agents work in most.\n\n# \u2500\u2500 4. Global CLIs \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# npm install -g typescript tsx\n# curl -fsSL https://example.com/install.sh | sh\n\n# \u2500\u2500 5. Start services on the agent's first command \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# The agent's shell is non-interactive bash, which runs the file named by $BASH_ENV before each command. Write a start script here, then\n# set BASH_ENV on the profile: printf '%s' /home/crtr/.services-up.sh | crtr profile env set <profile> --name BASH_ENV\n# cat > /home/crtr/.services-up.sh <<'UP'\n# pg_ctl -D /home/crtr/pg status >/dev/null 2>&1 || pg_ctl -D /home/crtr/pg -o \"-k /tmp -h localhost\" -l /tmp/pg.log -w start >/dev/null 2>&1 || true\n# UP\n# chown crtr /home/crtr/.services-up.sh\n\n# \u2500\u2500 6. Seed files and config \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# cp /work/<repo name>/.env.example /work/<repo name>/.env # placeholders only; real values come from `crtr profile env`\n# chown -R crtr /work/<repo name>\n";
@@ -5,8 +5,8 @@ const e=`#!/usr/bin/env bash
5
5
  # - Once per image build, as root, in /work, on Alpine Linux (use apk, not apt). Every sandbox of the profile starts from the result.
6
6
  # - Your repositories are already checked out at /work/<repo name> before this runs.
7
7
  # - The sandbox user is "crtr" (home /home/crtr). Files you create for it must be chowned to it.
8
- # - Already done for you: git, gh, curl, ripgrep, Node 24, pnpm. For every repository with a pnpm-lock.yaml, its packages are already
9
- # downloaded into a shared pnpm store, so \`pnpm install\` in a sandbox links instead of downloading.
8
+ # - Already done for you: git, gh, curl, ripgrep, Node 24, pnpm. Packages are not pre-installed: run \`pnpm install\` in a sandbox,
9
+ # or install at build time below.
10
10
  # - Output goes to /work/.crtr/setup.log in the image. If this script exits non-zero, sandboxes refuse to start and point at that log.
11
11
  # - The image keeps /work, /home/crtr, /usr, /etc and /lib. Anything written to /root or /tmp is lost.
12
12
  #
@@ -35,7 +35,7 @@ set -euo pipefail
35
35
  # su crtr -c 'initdb -D /home/crtr/pg -U postgres --auth=trust'
36
36
 
37
37
  # \u2500\u2500 3. App dependencies \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
38
- # pnpm repositories are already prepared (see above). For npm or yarn, or to install fully at build time:
38
+ # To install a repository's packages at build time:
39
39
  # (cd /work/<repo name> && npm ci)
40
40
  # (cd /work/<repo name> && pnpm install --frozen-lockfile)
41
41
  # Each full install can take 0.5-1.5 GB of the sandbox disk. Install only the repositories agents work in most.
@@ -1 +1 @@
1
- var c=Object.defineProperty;var a=(t,e)=>c(t,"name",{value:e,configurable:!0});import{clearFinalReportIfMatches as l,getFinalReport as f,getNode as u,updateNode as p}from"../canvas/index.js";import{subscribersOf as w}from"../canvas/tree.js";import{InputError as o}from"../io.js";import{transition as m}from"./lifecycle.js";import{noticeChangedWhileDone as h}from"./ledger.js";async function s(t){return await f(t)}a(s,"currentFinalReport");function d(t,e){throw new o({error:"node_finalized",message:`${t} already submitted its canonical final result (\`crtr canvas read ${t}/${e}\`) \u2014 reviving it now would hand it a mandate it can never finish, since a second \`push final\` always errors against an already-latched node.`,next:`Re-run this exact command with --reopen to clear ${t}'s spent latch and re-task it in place.`})}a(d,"throwNodeFinalized");function g(t){throw new o({error:"not_finalized",message:`${t} is not finalized \u2014 --reopen has nothing to clear.`,next:"Drop --reopen."})}a(g,"throwNotFinalized");async function R(t){const e=await s(t);e!==null&&d(t,e)}a(R,"assertNotFinalized");async function y(t){const e=await s(t);return e===null&&g(t),e}a(y,"assertFinalizedForReopen");async function x(t,e){if(!await l(t,e))throw new o({error:"reopen_latch_changed",message:`${t}'s finalization latch changed since it was last inspected \u2014 a concurrent --reopen (or a fresh push final) already moved it, so clearing it now would risk erasing a newer canonical result.`,next:"Re-run this exact command \u2014 it will re-inspect the current state before acting."})}a(x,"commitReopen");async function F(t,e){return t==null?!1:(await w(e)).some(i=>i.node_id===t)}a(F,"isManagerOf");async function _(t,e,i){const r=await s(t);await F(i,t)||await p(t,{lifecycle:"resident"});const n=await u(t);return n!==null&&(n.status==="done"||n.status==="canceled"||n.status==="dead")&&(n.status==="done"&&n.last_settled_at!=null&&await h(t,n.last_settled_at),await m(t,"revive")),r!==null&&await x(t,e??r),r}a(_,"commitReopenResident");async function D(t,e,i){if(e){const r=await y(t);await _(t,r,i);return}await R(t)}a(D,"assertReopenGate");export{y as assertFinalizedForReopen,R as assertNotFinalized,D as assertReopenGate,x as commitReopen,_ as commitReopenResident};
1
+ var f=Object.defineProperty;var a=(t,e)=>f(t,"name",{value:e,configurable:!0});import{clearFinalReportIfMatches as u,getFinalReport as p,getNode as l,updateNode as w}from"../canvas/index.js";import{subscribersOf as m}from"../canvas/tree.js";import{InputError as s}from"../io.js";import{transition as h}from"./lifecycle.js";import{assertCheckoutNotRemoved as d}from"./revive.js";import{noticeChangedWhileDone as g}from"./ledger.js";async function c(t){return await p(t)}a(c,"currentFinalReport");function R(t,e){throw new s({error:"node_finalized",message:`${t} already submitted its canonical final result (\`crtr canvas read ${t}/${e}\`) \u2014 reviving it now would hand it a mandate it can never finish, since a second \`push final\` always errors against an already-latched node.`,next:`Re-run this exact command with --reopen to clear ${t}'s spent latch and re-task it in place.`})}a(R,"throwNodeFinalized");function y(t){throw new s({error:"not_finalized",message:`${t} is not finalized \u2014 --reopen has nothing to clear.`,next:"Drop --reopen."})}a(y,"throwNotFinalized");async function x(t){const e=await c(t);e!==null&&R(t,e)}a(x,"assertNotFinalized");async function F(t){const e=await c(t);return e===null&&y(t),e}a(F,"assertFinalizedForReopen");async function _(t,e){if(!await u(t,e))throw new s({error:"reopen_latch_changed",message:`${t}'s finalization latch changed since it was last inspected \u2014 a concurrent --reopen (or a fresh push final) already moved it, so clearing it now would risk erasing a newer canonical result.`,next:"Re-run this exact command \u2014 it will re-inspect the current state before acting."})}a(_,"commitReopen");async function v(t,e){return t==null?!1:(await m(e)).some(i=>i.node_id===t)}a(v,"isManagerOf");async function z(t,e,i){const r=await l(t);r!==null&&d(t,r);const o=await c(t);await v(i,t)||await w(t,{lifecycle:"resident"});const n=await l(t);return n!==null&&(n.status==="done"||n.status==="canceled"||n.status==="dead")&&(n.status==="done"&&n.last_settled_at!=null&&await g(t,n.last_settled_at),await h(t,"revive")),o!==null&&await _(t,e??o),o}a(z,"commitReopenResident");async function O(t,e,i){if(e){const r=await F(t);await z(t,r,i);return}await x(t)}a(O,"assertReopenGate");export{F as assertFinalizedForReopen,x as assertNotFinalized,O as assertReopenGate,_ as commitReopen,z as commitReopenResident};
@@ -111,7 +111,8 @@ export declare function assertRecordedCwdExists(nodeId: string, meta: NodeMeta):
111
111
  blaxelEnvironment: string | null;
112
112
  remoteMachine: boolean;
113
113
  }>;
114
- /** Cleanup deleted this node's managed checkout and its branch, and nothing rebuilds them: refuse on any host, before a caller changes state. */
114
+ /** Cleanup deleted this node's managed checkout and its branch, and nothing rebuilds them; its cwd now names the shared repository
115
+ * root, so a launch would edit the base checkout. Refuse on any host, before a caller changes state. */
115
116
  export declare function assertCheckoutNotRemoved(nodeId: string, meta: NodeMeta): void;
116
117
  /** The `node:start` lifecycle hooks for a node coming up: a launch, or a cycle started in a running process. */
117
118
  export declare function runNodeStartHooks(nodeId: string, meta: NodeMeta, isBirth: boolean): Promise<void>;
@@ -1,3 +1,3 @@
1
- var le=Object.defineProperty;var s=(e,r)=>le(e,"name",{value:r,configurable:!0});import{assertGranteeRunsHere as ue}from"./unsandboxed.js";import{existsSync as H}from"node:fs";import{conversationIdFromPath as _,conversationStore as d,ConversationNotFoundError as G}from"../conversation-store/index.js";import{isAbsolute as fe}from"node:path";import{findNodeBySessionFile as we,getNode as R,updateNode as F,beginExecution as he,ExecutionAlreadyLive as pe,recordExecutionPid as de,abortExecution as A,endLiveExecution as me,unbindSession as U,recordLaunch as ve,setFrozen as _e,clearFrozen as K,fullName as ye}from"../canvas/index.js";import{emitEvent as W}from"../events/emit.js";import{consumeDeadlineOnWake as ke}from"../feed/messages.js";import{isParked as J,transition as O}from"./lifecycle.js";import{publishNotice as ge}from"./close.js";import{InputError as E}from"../io.js";import{buildPiArgv as y}from"./launch.js";import{buildReviveKickoff as be,drainBearings as Re,hasRetainedReports as Ee,readGoal as x,readYieldMessage as xe,RUNTIME_RESTART_CONTINUATION as Se}from"./kickoff.js";import{readRoadmap as j}from"./roadmap.js";import{encodeKickoffOrigin as $e,KICKOFF_ORIGIN_ENV as Ce}from"./stamp/protocol.js";import{carryInitialInput as V}from"../runs/initial-input.js";import{headlessBrokerHost as Ne,brokerLaunchJson as Fe}from"./host.js";import{isCloudRole as Ae}from"../canvas/person.js";import{asNodePerson as Oe}from"../../daemon/reconcilers/node-lifecycle/node-person.js";import{processRunner as Pe}from"./runner/process.js";import{runnerForEnvironment as X}from"./runner/index.js";import{MachineOfflineError as Y}from"./runner/machine/ops.js";import{blaxelEnvironmentOf as q}from"./blaxel-environment.js";import{recordLaunchFailure as Be}from"../../daemon/reconcilers/node-lifecycle/launch-failure.js";import{acceptedRelease as Q,remoteMachineEnvironmentOf as De,checkBilledWake as Te,EnvironmentImagePending as Me,imageForWake as Le}from"../../daemon/reconcilers/node-lifecycle/remote-wake.js";import{ExecutionCapReached as ze,liveExecutionForNode as He,setExecutionLaunchJson as Ge}from"../canvas/executions.js";import{isDrained as Ue}from"../../daemon/drain.js";import{appMemoryFull as Ke,appMemoryTooSmall as We,boundFleet as Z,brokerCapReached as I,brokerThresholdsForDaemon as P}from"./fleet.js";import{admitBrokerMemory as Je}from"./memory-admission.js";import{beginBootFaultAttempt as je,clearFault as Ve,hasAdmittedTurn as Xe,readFault as Ye}from"../canvas/recovery.js";import{clearNodeLedger as ee,forkNodeLedger as qe,noticeChangedWhileDone as Qe}from"./ledger.js";import{forkSourceNode as Ze,rootOfSpine as Ie}from"./nodes.js";import{ApiError as er}from"../../api/errors.js";import{grantSnapshotMissing as rr}from"../../daemon/readiness.js";import{checkGrantActive as ir,checkStart as tr}from"./start-check.js";import{isReviewCompanionBound as nr}from"../review/companion.js";import{assertProfileActive as ar}from"../profiles/manifest.js";import{isPidAlive as or}from"../canvas/pid.js";import{crtrHome as sr,jobDir as cr}from"../canvas/paths.js";import{contextDir as lr,ensureNodeDirs as ur,nodeAgentDir as fr}from"../canvas/node-agent-paths.js";import{discoverLifecycleHookRegistry as wr}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as hr}from"../command-hooks/transport/exec-lifecycle.js";async function pr(e,r){const i=e.pi_session_file,t=i?_(i):null;if(t===null)return{};try{const n=await d().header(t);return r?{resumeSessionPath:n.path}:{resumeSessionPath:n.path,newCycle:!0}}catch(n){if(n instanceof G)return{};throw n}}s(pr,"resumeArgs");async function re(e){const r=_(e);if(r===null)return!1;try{return await d().header(r),!0}catch(i){if(i instanceof G)return!1;throw i}}s(re,"conversationExists");async function dr(e){const r=_(e);return r===null?!0:(await d().read(r)).entries.some(i=>i.type==="message")}s(dr,"sessionHasConversation");async function mr(e){const r=_(e);if(r===null)return!0;const i=(await d().header(r)).header.cwd;return typeof i!="string"||H(i)}s(mr,"sessionCwdExists");async function vr(e,r,i,t){const n=r.pi_session_file;if(!n||!await re(n))return{};const u=await we(n);return u!==null&&u.node_id!==e&&or(u.pi_pid)?{}:t&&!await mr(n)?{}:await pr(r,i)}s(vr,"resumableSessionArgs");async function _r(e){return await j(e)===null&&await xe(e)===null&&!await Ee(e)}s(_r,"isUnstartedBirth");async function fi(e){const r=await x(e);if(r!==null&&r.trim()!=="")return!0;const i=await j(e);return i!==null&&i.trim()!==""}s(fi,"hasFreshGroundState");async function wi(e,r){const i=await ie(e,r,!0);if(i.parked)throw new Error(`reviveNode: internal parked decision for activating revive ${e}`);return i.result}s(wi,"reviveNode");async function hi(e,r,i){return ie(e,{...r,viewerAttach:!0},i)}s(hi,"decideAttachRevive");async function ie(e,r,i){const t=Ae()?await R(e):null;return t===null?await te(e,r,i):await Oe({node_id:e,sub:t.sub??null,profile_id:t.profile_id??null},()=>te(e,r,i))}s(ie,"decideRevive");async function te(e,r,i){let t=await R(e);if(t===null)throw new Error(`reviveNode: unknown node ${e}`);if(t=await R(e)??t,t.run_id&&(await R(t.run_id))?.deleting_at)throw new Error("run is deleting");if(t.final_report!==null)throw new Error(`reviveNode: refusing to revive ${e} \u2014 its finalization latch is set (final_report=${t.final_report}). A final landed between the caller's reopen-gate check and this revive; re-run with --reopen if this retask is still wanted.`);ar(t.profile_id),ue(t.grantee);const n=Z(),u=t.grantee==="app:terminal"&&await rr();if(!await n.has(e)&&!await n.isClaimed(e)&&r.wakeReason!=="runtime-restart-abort"&&r.viewerAttach!==!0&&!(!i&&t.lifecycle==="resident"&&J(t))&&(await ir(t),await tr(t),await q(t.profile_id??null)!==null&&await Te(t)),await n.isClaimed(e))return await n.has(e)&&await O(e,t.intent==="refresh"?"refresh-launch":"revive"),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"already-live"}};if(!i&&t.lifecycle==="resident"&&J(t))return{parked:!0};if(u){if(r.capacity==="refuse")throw new er(503,"runtime_starting","the first grant snapshot from the directory has not committed");return await ne(e,t,{reason:"grant_snapshot"}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}const k=await Ue();if(k&&r.capacity==="refuse")throw new Error(`the daemon is drained for an import; ${e} cannot start until it ends`);const m=!k&&await n.reserveSlot(e);let o=null;if(m){try{o=await Je(e)}catch(w){throw n.releaseReservation(e),w}o.verdict!=="admitted"&&n.releaseReservation(e)}if(o?.verdict==="too_small")throw We(o);if(!m||o?.verdict==="denied"){if(r.capacity==="refuse")throw o?.verdict==="denied"?Ke(o):I(P().automaticReviveCap,await n.occupancy());return await ne(e,t,k?{reason:"drain"}:o?.verdict==="denied"?{reason:"app_memory",free_bytes:o.free_bytes,needed_bytes:o.needed_bytes}:{reason:"broker_cap",live_count:await n.occupancy(),hard_cap:P().automaticReviveCap}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}try{return{parked:!1,result:await gr(e,t,r)}}finally{n.releaseReservation(e)}}s(te,"decideReviveAsCaller");async function ne(e,r,i){r.frozen_at==null&&(await _e(e,new Date().toISOString()),await me(e,{reason:"frozen"}),W({level:"info",event:"broker.frozen",node_id:e,fields:i}))}s(ne,"freezeForWait");async function yr(e,r){const i=await q(r.profile_id??null),t=await De(r.profile_id??null)!==null;if(!(i!==null||t)&&!H(r.cwd)){const u=r.fork_from!=null?`Restore ${r.cwd}, then revive the fork normally with \`crtr node lifecycle revive ${e}\`.`:r.managed_worktree?.state==="open"?"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon recovery.":`Recreate ${r.cwd}, or repair it with \`crtr node config --cwd <path> --node ${e}\`; durable node work resumes in a fresh conversation. Then retry \`crtr node lifecycle revive ${e}\`.`;throw new E({error:"cwd_missing",message:`${e} cannot be revived \u2014 its recorded cwd no longer exists: ${r.cwd}`,next:u})}return{blaxelEnvironment:i,remoteMachine:t}}s(yr,"assertRecordedCwdExists");function pi(e,r){const i=r.managed_worktree;if(!(i?.state!=="closed"||i.cleanup!=="complete"))throw new E({error:"checkout_removed",message:`${e} cannot be revived \u2014 cleanup removed its checkout ${i.path} and branch ${i.branch}`,next:`Start a new node in ${i.repo_root}.`})}s(pi,"assertCheckoutNotRemoved");async function kr(e,r,i){const t=wr(r.cwd,r.profile_id).plans.get("node:start")??[];await hr(t,{node:{id:e,name:r.name,kind:r.kind,mode:r.mode,lifecycle:r.lifecycle,cwd:r.cwd,nodeDir:await fr(e),contextDir:await lr(e),jobDir:cr(e)},runtime:{isBirth:i,canvasHome:sr(),profile:r.profile_id??null}})}s(kr,"runNodeStartHooks");async function gr(e,r,i){const{blaxelEnvironment:t,remoteMachine:n}=await yr(e,r),u=t!==null||n;r.host_kind!=="broker"&&(await F(e,{host_kind:"broker"}),r.host_kind="broker"),r.review_binding!=null&&!await nr(e)&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await U(e),r.pi_session_id=null,r.pi_session_file=null);const m=r.fork_from!=null&&r.pi_session_id==null,o=r.fork_source_file;if(m&&(typeof o!="string"||!fe(o)))throw new E({error:"fork_source_invalid",message:`${e} cannot be revived \u2014 its resolved fork source file is missing or invalid.`,next:`Restore the node's fork source metadata, then retry \`crtr node lifecycle revive ${e}\`.`});const w=m&&typeof o=="string";if(w&&!await re(o))throw new E({error:"fork_from_missing",message:`${e} cannot be revived \u2014 its fork source no longer exists: ${o}`,next:`Restore ${o}, or update the node's fork source, then retry \`crtr node lifecycle revive ${e}\`.`});const{automaticReviveCap:ae}=P();if(t!==null){const c=await Le(t);if(c.state==="pending")throw new Me(t,c.error)}const oe=t!==null?X("blaxel"):n?X("machine"):Pe;let f;try{f=await he(e,{daemonEpoch:Z().epoch(),cap:ae,...t!==null?{runner:"blaxel",release:Q()}:n?{runner:"machine",release:Q()}:{}})}catch(c){if(c instanceof ze)throw I(c.cap,c.live);if(c instanceof pe)return{window:null,session:r.tmux_session??null,resumed:!1,outcome:"already-live"};throw c}try{r.cycles=(r.cycles??0)+1,await F(e,{cycles:r.cycles});const S=r.intent==="refresh"||r.cycle_pending===!0?!1:i.resume,p=w?{}:await vr(e,r,S,!u),g=p.resumeSessionPath!==void 0,B=g&&p.newCycle===!0,v=g&&!B,D=!g&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&await _r(e),$=v&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&!await Xe(e)&&!await dr(p.resumeSessionPath)?(await x(e))?.trim():void 0,T=$!==void 0&&$!=="",se=w||D||T,M=r.cycle_pending===!0||B;await F(e,{cycle_pending:M}),r.cycle_pending=M,!w&&!g&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await U(e),r.pi_session_id=null,r.pi_session_file=null);let l,h=null;const C=s(()=>({type:"runtime",kind:"kickoff",...r.spawned_by!=null&&r.spawned_by!==""?{spawnedBy:r.spawned_by}:{}}),"birthOrigin");if(w){const a=await x(e),N=_(o);if(N===null)throw new Error(`invalid fork source ${o}`);const ce=(await d().header(await d().fork(N,e))).path;l=y(r,{resumeSessionPath:ce,...a!=null&&a!==""?{prompt:a}:{}}),a!=null&&a!==""&&(h=C()),await qe(e,(await Ze(o))?.node_id??null)}else if(T)l=y(r,{...p,prompt:$}),h=C(),await V(l,r);else if(v)l=y(r,{...p,...i.wakeReason==="runtime-restart-abort"?{prompt:Se}:{}}),i.wakeReason==="runtime-restart-abort"&&(h={type:"runtime",kind:"restart-continuation"});else if(D){const a=(await x(e))?.trim();l=y(r,a!==void 0&&a!==""?{prompt:a}:{}),a!==void 0&&a!==""&&(h=C(),await V(l,r)),await ee(e)}else{const a=await Re(r,f);l=y(r,{...p,prompt:await be(r,a,i.wakeReason==="runtime-restart-abort"?void 0:i.wakeReason)}),r.run_id&&a.unreadMessageIds?.length&&(l.env.CRTR_KICKOFF_MESSAGE_IDS=JSON.stringify(a.unreadMessageIds)),h=i.wakeReason!==void 0&&i.wakeReason!=="runtime-restart-abort"?{type:"runtime",kind:"wake",wake:i.wakeReason}:{type:"runtime",kind:"revive",cycle:r.cycles??0},await ee(e)}l.env={...l.env,CRTR_SUBTREE:await Ie(e)},h!==null&&(l.env[Ce]=$e(h)),r.status==="done"&&r.last_settled_at!=null&&await Qe(e,r.last_settled_at),await O(e,r.intent==="refresh"?"refresh-launch":"revive"),(await Ye(e))?.op!=="conversation_write_failed"&&await Ve(e,{preserveEpisode:!0});const L=await je(e);i.recovery!==!0&&i.viewerAttach!==!0&&await ke(e),await ur(e,r.grantee),await kr(e,r,se),l.env={...l.env,CRTR_EXECUTION_ID:f};const z=await Fe(e,l,r.cwd);await Ge(f,z);let b;try{const a=await He(e);if(b=await oe.start({executionId:f,nodeId:e,attempt:a?.attempt??1,release:a?.release??"",launchJson:z,cwd:r.cwd,resuming:v}),!u&&b.pid===null)throw new Error(`broker host returned no pid for ${e}`)}catch(a){if(a instanceof Y)throw a;try{await O(e,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:a instanceof Error?a.message:String(a)}}}),await ge(e,"notice.crash",`Child crashed \u2014 ${ye(r)} (${e}) failed to relaunch and is now dead: ${a.message}
1
+ var le=Object.defineProperty;var s=(e,r)=>le(e,"name",{value:r,configurable:!0});import{assertGranteeRunsHere as ue}from"./unsandboxed.js";import{existsSync as U}from"node:fs";import{conversationIdFromPath as _,conversationStore as p,ConversationNotFoundError as K}from"../conversation-store/index.js";import{isAbsolute as fe}from"node:path";import{findNodeBySessionFile as we,getNode as R,updateNode as A,beginExecution as he,ExecutionAlreadyLive as me,recordExecutionPid as pe,abortExecution as O,endLiveExecution as de,unbindSession as W,recordLaunch as ve,setFrozen as _e,clearFrozen as P,fullName as ye}from"../canvas/index.js";import{emitEvent as J}from"../events/emit.js";import{consumeDeadlineOnWake as ke}from"../feed/messages.js";import{isParked as B,transition as E}from"./lifecycle.js";import{publishNotice as ge}from"./close.js";import{InputError as x}from"../io.js";import{buildPiArgv as y}from"./launch.js";import{buildReviveKickoff as be,drainBearings as Re,hasRetainedReports as Ee,readGoal as S,readYieldMessage as xe,RUNTIME_RESTART_CONTINUATION as Se}from"./kickoff.js";import{readRoadmap as j}from"./roadmap.js";import{encodeKickoffOrigin as $e,KICKOFF_ORIGIN_ENV as Ce}from"./stamp/protocol.js";import{carryInitialInput as V}from"../runs/initial-input.js";import{headlessBrokerHost as Ne,brokerLaunchJson as Fe}from"./host.js";import{isCloudRole as Ae}from"../canvas/person.js";import{asNodePerson as Oe}from"../../daemon/reconcilers/node-lifecycle/node-person.js";import{processRunner as Pe}from"./runner/process.js";import{runnerForEnvironment as X}from"./runner/index.js";import{MachineOfflineError as Y}from"./runner/machine/ops.js";import{blaxelEnvironmentOf as q}from"./blaxel-environment.js";import{recordLaunchFailure as Be}from"../../daemon/reconcilers/node-lifecycle/launch-failure.js";import{acceptedRelease as Q,remoteMachineEnvironmentOf as De,checkBilledWake as Te,EnvironmentImagePending as Me,imageForWake as Le}from"../../daemon/reconcilers/node-lifecycle/remote-wake.js";import{ExecutionCapReached as ze,liveExecutionForNode as He,setExecutionLaunchJson as Ge}from"../canvas/executions.js";import{isDrained as Ue}from"../../daemon/drain.js";import{appMemoryFull as Ke,appMemoryTooSmall as We,boundFleet as Z,brokerCapReached as I,brokerThresholdsForDaemon as D}from"./fleet.js";import{admitBrokerMemory as Je}from"./memory-admission.js";import{beginBootFaultAttempt as je,clearFault as Ve,hasAdmittedTurn as Xe,readFault as Ye}from"../canvas/recovery.js";import{clearNodeLedger as ee,forkNodeLedger as qe,noticeChangedWhileDone as Qe}from"./ledger.js";import{forkSourceNode as Ze,rootOfSpine as Ie}from"./nodes.js";import{ApiError as er}from"../../api/errors.js";import{grantSnapshotMissing as rr}from"../../daemon/readiness.js";import{checkGrantActive as ir,checkStart as tr}from"./start-check.js";import{isReviewCompanionBound as nr}from"../review/companion.js";import{assertProfileActive as ar}from"../profiles/manifest.js";import{isPidAlive as or}from"../canvas/pid.js";import{crtrHome as sr,jobDir as cr}from"../canvas/paths.js";import{contextDir as lr,ensureNodeDirs as ur,nodeAgentDir as fr}from"../canvas/node-agent-paths.js";import{discoverLifecycleHookRegistry as wr}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as hr}from"../command-hooks/transport/exec-lifecycle.js";async function mr(e,r){const i=e.pi_session_file,t=i?_(i):null;if(t===null)return{};try{const n=await p().header(t);return r?{resumeSessionPath:n.path}:{resumeSessionPath:n.path,newCycle:!0}}catch(n){if(n instanceof K)return{};throw n}}s(mr,"resumeArgs");async function re(e){const r=_(e);if(r===null)return!1;try{return await p().header(r),!0}catch(i){if(i instanceof K)return!1;throw i}}s(re,"conversationExists");async function pr(e){const r=_(e);return r===null?!0:(await p().read(r)).entries.some(i=>i.type==="message")}s(pr,"sessionHasConversation");async function dr(e){const r=_(e);if(r===null)return!0;const i=(await p().header(r)).header.cwd;return typeof i!="string"||U(i)}s(dr,"sessionCwdExists");async function vr(e,r,i,t){const n=r.pi_session_file;if(!n||!await re(n))return{};const u=await we(n);return u!==null&&u.node_id!==e&&or(u.pi_pid)?{}:t&&!await dr(n)?{}:await mr(r,i)}s(vr,"resumableSessionArgs");async function _r(e){return await j(e)===null&&await xe(e)===null&&!await Ee(e)}s(_r,"isUnstartedBirth");async function hi(e){const r=await S(e);if(r!==null&&r.trim()!=="")return!0;const i=await j(e);return i!==null&&i.trim()!==""}s(hi,"hasFreshGroundState");async function mi(e,r){const i=await ie(e,r,!0);if(i.parked)throw new Error(`reviveNode: internal parked decision for activating revive ${e}`);return i.result}s(mi,"reviveNode");async function pi(e,r,i){return ie(e,{...r,viewerAttach:!0},i)}s(pi,"decideAttachRevive");async function ie(e,r,i){const t=Ae()?await R(e):null;return t===null?await te(e,r,i):await Oe({node_id:e,sub:t.sub??null,profile_id:t.profile_id??null},()=>te(e,r,i))}s(ie,"decideRevive");async function te(e,r,i){let t=await R(e);if(t===null)throw new Error(`reviveNode: unknown node ${e}`);if(t=await R(e)??t,t.run_id&&(await R(t.run_id))?.deleting_at)throw new Error("run is deleting");if(t.final_report!==null)throw new Error(`reviveNode: refusing to revive ${e} \u2014 its finalization latch is set (final_report=${t.final_report}). A final landed between the caller's reopen-gate check and this revive; re-run with --reopen if this retask is still wanted.`);(i||!(t.lifecycle==="resident"&&B(t)))&&await gr(e,t),ar(t.profile_id),ue(t.grantee);const n=Z(),u=t.grantee==="app:terminal"&&await rr();if(!await n.has(e)&&!await n.isClaimed(e)&&r.wakeReason!=="runtime-restart-abort"&&r.viewerAttach!==!0&&!(!i&&t.lifecycle==="resident"&&B(t))&&(await ir(t),await tr(t),await q(t.profile_id??null)!==null&&await Te(t)),await n.isClaimed(e))return await n.has(e)&&await E(e,t.intent==="refresh"?"refresh-launch":"revive"),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"already-live"}};if(!i&&t.lifecycle==="resident"&&B(t))return{parked:!0};if(u){if(r.capacity==="refuse")throw new er(503,"runtime_starting","the first grant snapshot from the directory has not committed");return await ne(e,t,{reason:"grant_snapshot"}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}const k=await Ue();if(k&&r.capacity==="refuse")throw new Error(`the daemon is drained for an import; ${e} cannot start until it ends`);const d=!k&&await n.reserveSlot(e);let o=null;if(d){try{o=await Je(e)}catch(w){throw n.releaseReservation(e),w}o.verdict!=="admitted"&&n.releaseReservation(e)}if(o?.verdict==="too_small")throw We(o);if(!d||o?.verdict==="denied"){if(r.capacity==="refuse")throw o?.verdict==="denied"?Ke(o):I(D().automaticReviveCap,await n.occupancy());return await ne(e,t,k?{reason:"drain"}:o?.verdict==="denied"?{reason:"app_memory",free_bytes:o.free_bytes,needed_bytes:o.needed_bytes}:{reason:"broker_cap",live_count:await n.occupancy(),hard_cap:D().automaticReviveCap}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}try{return{parked:!1,result:await Rr(e,t,r)}}finally{n.releaseReservation(e)}}s(te,"decideReviveAsCaller");async function ne(e,r,i){r.frozen_at==null&&(await _e(e,new Date().toISOString()),await de(e,{reason:"frozen"}),J({level:"info",event:"broker.frozen",node_id:e,fields:i}))}s(ne,"freezeForWait");async function yr(e,r){const i=await q(r.profile_id??null),t=await De(r.profile_id??null)!==null;if(!(i!==null||t)&&!U(r.cwd)){const u=r.fork_from!=null?`Restore ${r.cwd}, then revive the fork normally with \`crtr node lifecycle revive ${e}\`.`:r.managed_worktree?.state==="open"?"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon recovery.":`Recreate ${r.cwd}, or repair it with \`crtr node config --cwd <path> --node ${e}\`; durable node work resumes in a fresh conversation. Then retry \`crtr node lifecycle revive ${e}\`.`;throw new x({error:"cwd_missing",message:`${e} cannot be revived \u2014 its recorded cwd no longer exists: ${r.cwd}`,next:u})}return{blaxelEnvironment:i,remoteMachine:t}}s(yr,"assertRecordedCwdExists");function kr(e,r){const i=r.managed_worktree;if(!(i?.state!=="closed"||i.cleanup!=="complete"))throw new x({error:"checkout_removed",message:`${e} cannot be revived \u2014 cleanup removed its checkout ${i.path} and branch ${i.branch}`,next:`Start a new node in ${i.repo_root}.`})}s(kr,"assertCheckoutNotRemoved");async function gr(e,r){try{kr(e,r)}catch(i){throw(r.status==="active"||r.status==="idle")&&(await E(e,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:i.message}}}),await P(e)),i}}s(gr,"refuseRemovedCheckout");async function br(e,r,i){const t=wr(r.cwd,r.profile_id).plans.get("node:start")??[];await hr(t,{node:{id:e,name:r.name,kind:r.kind,mode:r.mode,lifecycle:r.lifecycle,cwd:r.cwd,nodeDir:await fr(e),contextDir:await lr(e),jobDir:cr(e)},runtime:{isBirth:i,canvasHome:sr(),profile:r.profile_id??null}})}s(br,"runNodeStartHooks");async function Rr(e,r,i){const{blaxelEnvironment:t,remoteMachine:n}=await yr(e,r),u=t!==null||n;r.host_kind!=="broker"&&(await A(e,{host_kind:"broker"}),r.host_kind="broker"),r.review_binding!=null&&!await nr(e)&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await W(e),r.pi_session_id=null,r.pi_session_file=null);const d=r.fork_from!=null&&r.pi_session_id==null,o=r.fork_source_file;if(d&&(typeof o!="string"||!fe(o)))throw new x({error:"fork_source_invalid",message:`${e} cannot be revived \u2014 its resolved fork source file is missing or invalid.`,next:`Restore the node's fork source metadata, then retry \`crtr node lifecycle revive ${e}\`.`});const w=d&&typeof o=="string";if(w&&!await re(o))throw new x({error:"fork_from_missing",message:`${e} cannot be revived \u2014 its fork source no longer exists: ${o}`,next:`Restore ${o}, or update the node's fork source, then retry \`crtr node lifecycle revive ${e}\`.`});const{automaticReviveCap:ae}=D();if(t!==null){const c=await Le(t);if(c.state==="pending")throw new Me(t,c.error)}const oe=t!==null?X("blaxel"):n?X("machine"):Pe;let f;try{f=await he(e,{daemonEpoch:Z().epoch(),cap:ae,...t!==null?{runner:"blaxel",release:Q()}:n?{runner:"machine",release:Q()}:{}})}catch(c){if(c instanceof ze)throw I(c.cap,c.live);if(c instanceof me)return{window:null,session:r.tmux_session??null,resumed:!1,outcome:"already-live"};throw c}try{r.cycles=(r.cycles??0)+1,await A(e,{cycles:r.cycles});const $=r.intent==="refresh"||r.cycle_pending===!0?!1:i.resume,m=w?{}:await vr(e,r,$,!u),g=m.resumeSessionPath!==void 0,T=g&&m.newCycle===!0,v=g&&!T,M=!g&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&await _r(e),C=v&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&!await Xe(e)&&!await pr(m.resumeSessionPath)?(await S(e))?.trim():void 0,L=C!==void 0&&C!=="",se=w||M||L,z=r.cycle_pending===!0||T;await A(e,{cycle_pending:z}),r.cycle_pending=z,!w&&!g&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await W(e),r.pi_session_id=null,r.pi_session_file=null);let l,h=null;const N=s(()=>({type:"runtime",kind:"kickoff",...r.spawned_by!=null&&r.spawned_by!==""?{spawnedBy:r.spawned_by}:{}}),"birthOrigin");if(w){const a=await S(e),F=_(o);if(F===null)throw new Error(`invalid fork source ${o}`);const ce=(await p().header(await p().fork(F,e))).path;l=y(r,{resumeSessionPath:ce,...a!=null&&a!==""?{prompt:a}:{}}),a!=null&&a!==""&&(h=N()),await qe(e,(await Ze(o))?.node_id??null)}else if(L)l=y(r,{...m,prompt:C}),h=N(),await V(l,r);else if(v)l=y(r,{...m,...i.wakeReason==="runtime-restart-abort"?{prompt:Se}:{}}),i.wakeReason==="runtime-restart-abort"&&(h={type:"runtime",kind:"restart-continuation"});else if(M){const a=(await S(e))?.trim();l=y(r,a!==void 0&&a!==""?{prompt:a}:{}),a!==void 0&&a!==""&&(h=N(),await V(l,r)),await ee(e)}else{const a=await Re(r,f);l=y(r,{...m,prompt:await be(r,a,i.wakeReason==="runtime-restart-abort"?void 0:i.wakeReason)}),r.run_id&&a.unreadMessageIds?.length&&(l.env.CRTR_KICKOFF_MESSAGE_IDS=JSON.stringify(a.unreadMessageIds)),h=i.wakeReason!==void 0&&i.wakeReason!=="runtime-restart-abort"?{type:"runtime",kind:"wake",wake:i.wakeReason}:{type:"runtime",kind:"revive",cycle:r.cycles??0},await ee(e)}l.env={...l.env,CRTR_SUBTREE:await Ie(e)},h!==null&&(l.env[Ce]=$e(h)),r.status==="done"&&r.last_settled_at!=null&&await Qe(e,r.last_settled_at),await E(e,r.intent==="refresh"?"refresh-launch":"revive"),(await Ye(e))?.op!=="conversation_write_failed"&&await Ve(e,{preserveEpisode:!0});const H=await je(e);i.recovery!==!0&&i.viewerAttach!==!0&&await ke(e),await ur(e,r.grantee),await br(e,r,se),l.env={...l.env,CRTR_EXECUTION_ID:f};const G=await Fe(e,l,r.cwd);await Ge(f,G);let b;try{const a=await He(e);if(b=await oe.start({executionId:f,nodeId:e,attempt:a?.attempt??1,release:a?.release??"",launchJson:G,cwd:r.cwd,resuming:v}),!u&&b.pid===null)throw new Error(`broker host returned no pid for ${e}`)}catch(a){if(a instanceof Y)throw a;try{await E(e,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:a instanceof Error?a.message:String(a)}}}),await ge(e,"notice.crash",`Child crashed \u2014 ${ye(r)} (${e}) failed to relaunch and is now dead: ${a.message}
2
2
 
3
- It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`,{reason:"child-crashed",child:e})}catch{}throw await A(f,{reason:"launch_failed"}),new Error(`[broker] refusing to revive ${e}: ${a.message}`)}if(await ve(e,new Date().toISOString()),u)return await K(e),{window:null,session:r.tmux_session??null,resumed:v,faultExplanation:L.explanation,outcome:"launched"};if(await de(f,e,b.pid)==="shutdown")throw await A(f,{reason:"superseded"}),Ne.teardown(e),new Error(`[broker] refusing to revive ${e}: execution was superseded during launch`);return await K(e),{window:null,session:r.tmux_session??null,resumed:v,launch:b,faultExplanation:L.explanation,outcome:"launched"}}catch(c){throw c instanceof Y&&c.sent||(await A(f,{reason:"launch_failed"}),await Be(f,c).catch(S=>{W({level:"warn",event:"broker.launch_failure.unrecorded",node_id:e,error:S})})),c}}s(gr,"launchRevive");export{pi as assertCheckoutNotRemoved,yr as assertRecordedCwdExists,hi as decideAttachRevive,fi as hasFreshGroundState,pr as resumeArgs,wi as reviveNode,kr as runNodeStartHooks};
3
+ It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`,{reason:"child-crashed",child:e})}catch{}throw await O(f,{reason:"launch_failed"}),new Error(`[broker] refusing to revive ${e}: ${a.message}`)}if(await ve(e,new Date().toISOString()),u)return await P(e),{window:null,session:r.tmux_session??null,resumed:v,faultExplanation:H.explanation,outcome:"launched"};if(await pe(f,e,b.pid)==="shutdown")throw await O(f,{reason:"superseded"}),Ne.teardown(e),new Error(`[broker] refusing to revive ${e}: execution was superseded during launch`);return await P(e),{window:null,session:r.tmux_session??null,resumed:v,launch:b,faultExplanation:H.explanation,outcome:"launched"}}catch(c){throw c instanceof Y&&c.sent||(await O(f,{reason:"launch_failed"}),await Be(f,c).catch($=>{J({level:"warn",event:"broker.launch_failure.unrecorded",node_id:e,error:$})})),c}}s(Rr,"launchRevive");export{kr as assertCheckoutNotRemoved,yr as assertRecordedCwdExists,pi as decideAttachRevive,hi as hasFreshGroundState,mr as resumeArgs,mi as reviveNode,br as runNodeStartHooks};
@@ -1,8 +1,8 @@
1
- var j=Object.defineProperty;var c=(t,r)=>j(t,"name",{value:r,configurable:!0});import{spawn as q}from"node:child_process";import{constants as D,lstatSync as z,mkdirSync as W,readFileSync as J,readdirSync as X,readlinkSync as V,rmSync as Z,writeFileSync as b}from"node:fs";import{join as g,relative as Q}from"node:path";import{crc32 as tt,deflateRawSync as et}from"node:zlib";import{BlaxelApiError as rt}from"./client.js";const nt="public.ecr.aws/docker/library/node:24-alpine",ot="ghcr.io/blaxel-ai/sandbox:latest",p="crtr",B="/var/lib/crtr/recipe-pi-agent",st="blaxel.toml",it=`[build]
1
+ var j=Object.defineProperty;var c=(t,r)=>j(t,"name",{value:r,configurable:!0});import{spawn as q}from"node:child_process";import{constants as P,lstatSync as z,mkdirSync as W,readFileSync as J,readdirSync as X,readlinkSync as V,rmSync as Z,writeFileSync as b}from"node:fs";import{join as E,relative as Q}from"node:path";import{crc32 as tt,deflateRawSync as et}from"node:zlib";import{BlaxelApiError as rt}from"./client.js";const nt="public.ecr.aws/docker/library/node:24-alpine",st="ghcr.io/blaxel-ai/sandbox:latest",p="crtr",D="/var/lib/crtr/recipe-pi-agent",ot="blaxel.toml",it=`[build]
2
2
  slim = false
3
- `,at="1.1.0",_="recipe-setup.sh",ct=["@northlight-systems:registry=https://npm.pkg.github.com","//npm.pkg.github.com/:_authToken=${NODE_AUTH_TOKEN}",`store-dir=/home/${p}/.local/share/pnpm/store`],G=c(()=>`printf '%s\\n' ${ct.map(t=>`'${t}'`).join(" ")} > /home/${p}/.npmrc`,"writeRunUserNpmrc"),R="repos",U="/work/.crtr/setup.log",M="/work/.crtr/setup-failed",C="/usr/local/bin/gh",lt=["#!/bin/sh",'token=$(printf "protocol=https\\nhost=github.com\\n\\n" | git credential fill 2>/dev/null | sed -n "s/^password=//p")','[ -n "$token" ] && export GH_TOKEN="$token"','exec /usr/bin/gh "$@"'],N=c(t=>`'${t.replace(/'/g,"'\\''")}'`,"shellQuote"),pt=c(t=>(t??"").split(`
4
- `).map(r=>r.trim()).filter(r=>r!==""),"lines"),E=c((t,r)=>`RUN { ${r}; } >> ${U} 2>&1 || echo ${N(t)} "exited $?" >> ${M}`,"guarded");function ut(t,r,i=!1){const s=pt(t.pi_packages),a=t.setup_script!==null&&t.setup_script.trim()!=="",n=[`FROM ${nt}`,"RUN apk add --no-cache bash git curl ripgrep github-cli",`RUN printf '%s\\n' ${lt.map(N).join(" ")} > ${C} && chmod 755 ${C}`,`COPY --from=${ot} /sandbox-api /usr/local/bin/sandbox-api`,`RUN adduser -D -h /home/${p} -s /bin/sh ${p} && mkdir -p /work/.crtr ${B} && chown -R ${p} /work /var/lib/crtr`],e=[`${n[0]} AS build`,...i?["ARG NODE_AUTH_TOKEN"]:[],...n.slice(1),`RUN rm -f ${M} ${U}`,E("npm install -g pnpm","npm install -g pnpm && mkdir -p /var/lib/postgresql")];t.repositories.length>0&&e.push(`COPY --chown=${p} ${R}/ /work/`),s.length>0&&e.push(E("npm install pi",`npm install -g @earendil-works/pi-coding-agent@${at}`)),a&&e.push(`COPY ${_} /tmp/${_}`),e.push("WORKDIR /work"),e.push(`RUN ${G()}`);for(const o of t.repositories)e.push(`RUN if [ -f /work/${o.name}/pnpm-lock.yaml ]; then su ${p} -c 'cd /work/${o.name} && HOME=/home/${p} pnpm fetch' >> ${U} 2>&1 || echo 'pnpm fetch ${o.name} failed' >> ${U}; fi`);for(const o of s)e.push(E(`pi install ${o}`,`HOME=/var/lib/crtr PI_CODING_AGENT_DIR=${B} pi install ${N(o)}`));a&&e.push(E("setup script",`bash /tmp/${_}`)),e.push(E("finalize",`echo ${Math.trunc(r)} > /work/.crtr/recipe-revision`)),e.push("",...n);for(const o of["/work",`/home/${p}`,"/var/lib/crtr"])e.push(`COPY --from=build --chown=${p}:${p} ${o} ${o}`);for(const o of["/usr/local","/usr","/etc","/lib"])e.push(`COPY --from=build ${o} ${o}`);return e.push("COPY --from=build /var/lib/postgresql /var/lib/postgresql"),e.push("RUN if getent passwd postgres >/dev/null; then chown -R postgres:postgres /var/lib/postgresql; fi"),i&&e.push("RUN rm -f /work/.npmrc",`RUN ${G()} && chown ${p}:${p} /home/${p}/.npmrc`),e.push(`USER ${p}`,"WORKDIR /work",'ENTRYPOINT ["/usr/local/bin/sandbox-api"]',""),e.join(`
5
- `)}c(ut,"recipeDockerfile");const dt=c((t,r,i)=>new Promise((s,a)=>{const n=q("git",t,{cwd:i,env:{...process.env,...r,GIT_TERMINAL_PROMPT:"0"},stdio:["ignore","ignore","pipe"]});let e="";n.stderr.on("data",o=>{e+=o.toString()}),n.on("error",a),n.on("close",o=>{o===0?s():a(new Error(`git ${t[0]} failed (${o}): ${e.slice(0,300)}`))})}),"runGit");async function _t(t){const r=t.git??dt,i=t.packagesToken??null,s=t.cloneUrl??(n=>`https://github.com/${n}.git`);W(g(t.dir,R),{recursive:!0});const a=t.token===null?{}:{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:"http.https://github.com/.extraheader",GIT_CONFIG_VALUE_0:`AUTHORIZATION: basic ${Buffer.from(`x-access-token:${t.token}`).toString("base64")}`};for(const n of t.recipe.repositories){if(!/^[A-Za-z0-9._-]+$/.test(n.name)||n.name==="."||n.name==="..")throw new Error(`repository name ${JSON.stringify(n.name)} is not a plain directory name`);await r(["clone","--quiet","--branch",n.default_branch,s(n.github_full_name),g(R,n.name)],a,t.dir)}b(g(t.dir,st),it),b(g(t.dir,"Dockerfile"),ut(t.recipe,t.revision,i!==null)),i!==null&&b(g(t.dir,".env.build"),`NODE_AUTH_TOKEN=${i}
6
- `,{mode:384}),t.recipe.setup_script!==null&&t.recipe.setup_script.trim()!==""&&b(g(t.dir,_),t.recipe.setup_script.endsWith(`
3
+ `,at="1.1.0",_="recipe-setup.sh",ct=["@northlight-systems:registry=https://npm.pkg.github.com","//npm.pkg.github.com/:_authToken=${NODE_AUTH_TOKEN}",`store-dir=/home/${p}/.local/share/pnpm/store`],B=c(()=>`printf '%s\\n' ${ct.map(t=>`'${t}'`).join(" ")} > /home/${p}/.npmrc`,"writeRunUserNpmrc"),L="repos",G="/work/.crtr/setup.log",C="/work/.crtr/setup-failed",M="/usr/local/bin/gh",lt=["#!/bin/sh",'token=$(printf "protocol=https\\nhost=github.com\\n\\n" | git credential fill 2>/dev/null | sed -n "s/^password=//p")','[ -n "$token" ] && export GH_TOKEN="$token"','exec /usr/bin/gh "$@"'],R=c(t=>`'${t.replace(/'/g,"'\\''")}'`,"shellQuote"),pt=c(t=>(t??"").split(`
4
+ `).map(r=>r.trim()).filter(r=>r!==""),"lines"),$=c((t,r)=>`RUN { ${r}; } >> ${G} 2>&1 || echo ${R(t)} "exited $?" >> ${C}`,"guarded");function ut(t,r,i=!1){const o=pt(t.pi_packages),a=t.setup_script!==null&&t.setup_script.trim()!=="",n=[`FROM ${nt}`,"RUN apk add --no-cache bash git curl ripgrep github-cli",`RUN printf '%s\\n' ${lt.map(R).join(" ")} > ${M} && chmod 755 ${M}`,`COPY --from=${st} /sandbox-api /usr/local/bin/sandbox-api`,`RUN adduser -D -h /home/${p} -s /bin/sh ${p} && mkdir -p /work/.crtr ${D} && chown -R ${p} /work /var/lib/crtr`],e=[`${n[0]} AS build`,...i?["ARG NODE_AUTH_TOKEN"]:[],...n.slice(1),`RUN rm -f ${C} ${G}`,$("npm install -g pnpm","npm install -g pnpm && mkdir -p /var/lib/postgresql")];t.repositories.length>0&&e.push(`COPY --chown=${p} ${L}/ /work/`),o.length>0&&e.push($("npm install pi",`npm install -g @earendil-works/pi-coding-agent@${at}`)),a&&e.push(`COPY ${_} /tmp/${_}`),e.push("WORKDIR /work"),e.push(`RUN ${B()}`);for(const s of o)e.push($(`pi install ${s}`,`HOME=/var/lib/crtr PI_CODING_AGENT_DIR=${D} pi install ${R(s)}`));a&&e.push($("setup script",`bash /tmp/${_}`)),e.push($("finalize",`echo ${Math.trunc(r)} > /work/.crtr/recipe-revision`)),e.push("",...n);for(const s of["/work",`/home/${p}`,"/var/lib/crtr"])e.push(`COPY --from=build --chown=${p}:${p} ${s} ${s}`);for(const s of["/usr/local","/usr","/etc","/lib"])e.push(`COPY --from=build ${s} ${s}`);return e.push("COPY --from=build /var/lib/postgresql /var/lib/postgresql"),e.push("RUN if getent passwd postgres >/dev/null; then chown -R postgres:postgres /var/lib/postgresql; fi"),i&&e.push("RUN rm -f /work/.npmrc",`RUN ${B()} && chown ${p}:${p} /home/${p}/.npmrc`),e.push(`USER ${p}`,"WORKDIR /work",'ENTRYPOINT ["/usr/local/bin/sandbox-api"]',""),e.join(`
5
+ `)}c(ut,"recipeDockerfile");const dt=c((t,r,i)=>new Promise((o,a)=>{const n=q("git",t,{cwd:i,env:{...process.env,...r,GIT_TERMINAL_PROMPT:"0"},stdio:["ignore","ignore","pipe"]});let e="";n.stderr.on("data",s=>{e+=s.toString()}),n.on("error",a),n.on("close",s=>{s===0?o():a(new Error(`git ${t[0]} failed (${s}): ${e.slice(0,300)}`))})}),"runGit");async function _t(t){const r=t.git??dt,i=t.packagesToken??null,o=t.cloneUrl??(n=>`https://github.com/${n}.git`);W(E(t.dir,L),{recursive:!0});const a=t.token===null?{}:{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:"http.https://github.com/.extraheader",GIT_CONFIG_VALUE_0:`AUTHORIZATION: basic ${Buffer.from(`x-access-token:${t.token}`).toString("base64")}`};for(const n of t.recipe.repositories){if(!/^[A-Za-z0-9._-]+$/.test(n.name)||n.name==="."||n.name==="..")throw new Error(`repository name ${JSON.stringify(n.name)} is not a plain directory name`);await r(["clone","--quiet","--branch",n.default_branch,o(n.github_full_name),E(L,n.name)],a,t.dir)}b(E(t.dir,ot),it),b(E(t.dir,"Dockerfile"),ut(t.recipe,t.revision,i!==null)),i!==null&&b(E(t.dir,".env.build"),`NODE_AUTH_TOKEN=${i}
6
+ `,{mode:384}),t.recipe.setup_script!==null&&t.recipe.setup_script.trim()!==""&&b(E(t.dir,_),t.recipe.setup_script.endsWith(`
7
7
  `)?t.recipe.setup_script:`${t.recipe.setup_script}
8
- `)}c(_t,"prepareBuildDir");function F(t,r,i){for(const s of X(r).sort()){const a=g(r,s),n=z(a),e=Q(t,a).split("\\").join("/");n.isDirectory()?F(t,a,i):n.isSymbolicLink()?i.push({name:e,data:Buffer.from(V(a)),mode:D.S_IFLNK|511}):n.isFile()&&i.push({name:e,data:J(a),mode:D.S_IFREG|n.mode&511})}}c(F,"walk");function ft(t){const r=[];F(t,t,r);const i=[],s=[];let a=0;for(const o of r){const d=Buffer.from(o.name),$=et(o.data),I=tt(o.data),u=Buffer.alloc(30);u.writeUInt32LE(67324752,0),u.writeUInt16LE(20,4),u.writeUInt16LE(2048,6),u.writeUInt16LE(8,8),u.writeUInt32LE(33,12),u.writeUInt32LE(I,14),u.writeUInt32LE($.length,18),u.writeUInt32LE(o.data.length,22),u.writeUInt16LE(d.length,26),i.push(u,d,$);const l=Buffer.alloc(46);l.writeUInt32LE(33639248,0),l.writeUInt16LE(788,4),l.writeUInt16LE(20,6),l.writeUInt16LE(2048,8),l.writeUInt16LE(8,10),l.writeUInt32LE(33,14),l.writeUInt32LE(I,16),l.writeUInt32LE($.length,20),l.writeUInt32LE(o.data.length,24),l.writeUInt16LE(d.length,28),l.writeUInt32LE(o.mode<<16>>>0,38),l.writeUInt32LE(a,42),s.push(l,d),a+=u.length+d.length+$.length}const n=Buffer.concat(s),e=Buffer.alloc(22);return e.writeUInt32LE(101010256,0),e.writeUInt16LE(r.length,8),e.writeUInt16LE(r.length,10),e.writeUInt32LE(n.length,12),e.writeUInt32LE(a,16),Buffer.concat([...i,n,e])}c(ft,"zipDirectory");async function k(t,r,i,s,a=[]){const n=`${t.controlUrl??"https://api.blaxel.ai/v0"}${i}`,e=await(t.fetch??fetch)(n,{method:r,headers:{authorization:`Bearer ${t.apiKey}`,"x-blaxel-workspace":t.workspace,"content-type":"application/json"},...s===void 0?{}:{body:JSON.stringify(s)}}),o=await e.text();let d=null;if(o!=="")try{d=JSON.parse(o)}catch{d={raw:o}}if(!e.ok&&!a.includes(e.status))throw new rt(e.status,null,`Blaxel ${r} ${n} failed (${e.status}): ${o.slice(0,300)}`);return{status:e.status,headers:e.headers,json:d}}c(k,"api");async function H(t,r){const{status:i,json:s}=await k(t,"GET",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404]);return i===404?null:s}c(H,"getImage");async function Ut(t,r){await k(t,"DELETE",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404])}c(Ut,"deleteImage");const ht=60*6e4;async function xt(t,r,i,s={}){const a=s.sleep??(h=>new Promise(f=>setTimeout(f,h))),n=s.now??Date.now,e=n(),o=await H(t,r),d=new Set((o?.spec?.tags??[]).map(h=>h.name)),$=c(h=>(h?.metadata?.events??[]).map(f=>Date.parse(f.time??"")).filter(f=>!Number.isNaN(f)),"eventTimes"),I=Math.max(-1/0,...$(o)),l=(await k(t,"POST","/images",{resourceType:"sandbox",name:r})).headers.get("x-blaxel-upload-url");if(l===null)throw new Error(`Blaxel gave no upload URL for image ${r}`);const x=await(t.fetch??fetch)(l,{method:"PUT",headers:{"content-type":"application/zip"},body:new Uint8Array(ft(i))});if(!x.ok)throw new Error(`uploading the build context of image ${r} failed (${x.status}): ${(await x.text()).slice(0,300)}`);const T=s.timeoutMs??ht,K=e+T;let O=null;for(;;){const h=await H(t,r),f=h?.metadata?.status,y=$(h).filter(m=>m>I).sort((m,L)=>m-L);if(f==="BUILT"&&y.length>=2){O??=n();const m=(h?.spec?.tags??[]).filter(w=>w.name!==void 0),L=y[0],S=c(w=>Date.parse(w??"")>=L,"touchedSince"),A=m.filter(w=>!d.has(w.name)||S(w.createdAt)||S(w.updatedAt)),v=n()-O>=(s.tagGraceMs??6e4),P=(A.length>0?A:v?m:[]).sort((w,Y)=>(Y.updatedAt??"").localeCompare(w.updatedAt??""))[0]?.name;if(P!==void 0)return{ref:`sandbox/${r}:${P}`,buildMs:n()-e};if(v)throw new Error(`Blaxel built image ${r} but no tag appeared`)}if(f==="FAILED"||f==="TERMINATED"){const m=h?.metadata?.events??[];throw new Error(`building image ${r} ${f.toLowerCase()}: ${m[m.length-1]?.message??"no message"}`)}if(n()>K)throw new Error(`building image ${r} did not finish within ${T} ms (last status ${f??"none"})`);await a(s.pollMs??3e3)}}c(xt,"buildImage");const Lt=c(t=>`env-${t}`,"environmentImageName");function Rt(t){Z(t,{recursive:!0,force:!0})}c(Rt,"removeBuildDir");export{it as BLAXEL_TOML,st as BLAXEL_TOML_FILE,ht as BUILD_TIMEOUT_MS,C as GH_WRAPPER_PATH,nt as NODE_BASE_IMAGE,B as RECIPE_PI_AGENT_DIR,R as REPOS_DIR,p as RUN_USER,ct as RUN_USER_NPMRC,ot as SANDBOX_API_IMAGE,M as SETUP_FAILED_FILE,U as SETUP_LOG_FILE,_ as SETUP_SCRIPT_FILE,xt as buildImage,Ut as deleteImage,Lt as environmentImageName,H as getImage,_t as prepareBuildDir,ut as recipeDockerfile,Rt as removeBuildDir,ft as zipDirectory};
8
+ `)}c(_t,"prepareBuildDir");function F(t,r,i){for(const o of X(r).sort()){const a=E(r,o),n=z(a),e=Q(t,a).split("\\").join("/");n.isDirectory()?F(t,a,i):n.isSymbolicLink()?i.push({name:e,data:Buffer.from(V(a)),mode:P.S_IFLNK|511}):n.isFile()&&i.push({name:e,data:J(a),mode:P.S_IFREG|n.mode&511})}}c(F,"walk");function ht(t){const r=[];F(t,t,r);const i=[],o=[];let a=0;for(const s of r){const d=Buffer.from(s.name),g=et(s.data),I=tt(s.data),u=Buffer.alloc(30);u.writeUInt32LE(67324752,0),u.writeUInt16LE(20,4),u.writeUInt16LE(2048,6),u.writeUInt16LE(8,8),u.writeUInt32LE(33,12),u.writeUInt32LE(I,14),u.writeUInt32LE(g.length,18),u.writeUInt32LE(s.data.length,22),u.writeUInt16LE(d.length,26),i.push(u,d,g);const l=Buffer.alloc(46);l.writeUInt32LE(33639248,0),l.writeUInt16LE(788,4),l.writeUInt16LE(20,6),l.writeUInt16LE(2048,8),l.writeUInt16LE(8,10),l.writeUInt32LE(33,14),l.writeUInt32LE(I,16),l.writeUInt32LE(g.length,20),l.writeUInt32LE(s.data.length,24),l.writeUInt16LE(d.length,28),l.writeUInt32LE(s.mode<<16>>>0,38),l.writeUInt32LE(a,42),o.push(l,d),a+=u.length+d.length+g.length}const n=Buffer.concat(o),e=Buffer.alloc(22);return e.writeUInt32LE(101010256,0),e.writeUInt16LE(r.length,8),e.writeUInt16LE(r.length,10),e.writeUInt32LE(n.length,12),e.writeUInt32LE(a,16),Buffer.concat([...i,n,e])}c(ht,"zipDirectory");async function N(t,r,i,o,a=[]){const n=`${t.controlUrl??"https://api.blaxel.ai/v0"}${i}`,e=await(t.fetch??fetch)(n,{method:r,headers:{authorization:`Bearer ${t.apiKey}`,"x-blaxel-workspace":t.workspace,"content-type":"application/json"},...o===void 0?{}:{body:JSON.stringify(o)}}),s=await e.text();let d=null;if(s!=="")try{d=JSON.parse(s)}catch{d={raw:s}}if(!e.ok&&!a.includes(e.status))throw new rt(e.status,null,`Blaxel ${r} ${n} failed (${e.status}): ${s.slice(0,300)}`);return{status:e.status,headers:e.headers,json:d}}c(N,"api");async function H(t,r){const{status:i,json:o}=await N(t,"GET",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404]);return i===404?null:o}c(H,"getImage");async function Ut(t,r){await N(t,"DELETE",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404])}c(Ut,"deleteImage");const ft=60*6e4;async function xt(t,r,i,o={}){const a=o.sleep??(f=>new Promise(h=>setTimeout(h,f))),n=o.now??Date.now,e=n(),s=await H(t,r),d=new Set((s?.spec?.tags??[]).map(f=>f.name)),g=c(f=>(f?.metadata?.events??[]).map(h=>Date.parse(h.time??"")).filter(h=>!Number.isNaN(h)),"eventTimes"),I=Math.max(-1/0,...g(s)),l=(await N(t,"POST","/images",{resourceType:"sandbox",name:r})).headers.get("x-blaxel-upload-url");if(l===null)throw new Error(`Blaxel gave no upload URL for image ${r}`);const U=await(t.fetch??fetch)(l,{method:"PUT",headers:{"content-type":"application/zip"},body:new Uint8Array(ht(i))});if(!U.ok)throw new Error(`uploading the build context of image ${r} failed (${U.status}): ${(await U.text()).slice(0,300)}`);const T=o.timeoutMs??ft,K=e+T;let O=null;for(;;){const f=await H(t,r),h=f?.metadata?.status,k=g(f).filter(m=>m>I).sort((m,x)=>m-x);if(h==="BUILT"&&k.length>=2){O??=n();const m=(f?.spec?.tags??[]).filter(w=>w.name!==void 0),x=k[0],S=c(w=>Date.parse(w??"")>=x,"touchedSince"),y=m.filter(w=>!d.has(w.name)||S(w.createdAt)||S(w.updatedAt)),A=n()-O>=(o.tagGraceMs??6e4),v=(y.length>0?y:A?m:[]).sort((w,Y)=>(Y.updatedAt??"").localeCompare(w.updatedAt??""))[0]?.name;if(v!==void 0)return{ref:`sandbox/${r}:${v}`,buildMs:n()-e};if(A)throw new Error(`Blaxel built image ${r} but no tag appeared`)}if(h==="FAILED"||h==="TERMINATED"){const m=f?.metadata?.events??[];throw new Error(`building image ${r} ${h.toLowerCase()}: ${m[m.length-1]?.message??"no message"}`)}if(n()>K)throw new Error(`building image ${r} did not finish within ${T} ms (last status ${h??"none"})`);await a(o.pollMs??3e3)}}c(xt,"buildImage");const Lt=c(t=>`env-${t}`,"environmentImageName");function Rt(t){Z(t,{recursive:!0,force:!0})}c(Rt,"removeBuildDir");export{it as BLAXEL_TOML,ot as BLAXEL_TOML_FILE,ft as BUILD_TIMEOUT_MS,M as GH_WRAPPER_PATH,nt as NODE_BASE_IMAGE,D as RECIPE_PI_AGENT_DIR,L as REPOS_DIR,p as RUN_USER,ct as RUN_USER_NPMRC,st as SANDBOX_API_IMAGE,C as SETUP_FAILED_FILE,G as SETUP_LOG_FILE,_ as SETUP_SCRIPT_FILE,xt as buildImage,Ut as deleteImage,Lt as environmentImageName,H as getImage,_t as prepareBuildDir,ut as recipeDockerfile,Rt as removeBuildDir,ht as zipDirectory};
@@ -1,2 +1,2 @@
1
- var ce=Object.defineProperty;var u=(t,e)=>ce(t,"name",{value:e,configurable:!0});import{randomBytes as ue}from"node:crypto";import{claimNodeMail as le,acknowledgeNodeMail as fe}from"../../../core/canvas/deliveries.js";import{nodeMailEntry as me}from"../../../core/feed/inbox.js";import{enqueueNodeMail as D,cancelPendingNodeMail as pe}from"../../../core/feed/messages.js";import{assertCheckoutNotRemoved as ye,assertRecordedCwdExists as he,reviveNode as L}from"../../../core/runtime/revive.js";import{BrokerUnreachableError as U}from"../../../core/runtime/broker-request.js";import{isBrokerLive as q}from"../../../core/runtime/model-swap.js";import{deliverLive as we,interruptLive as be}from"../../../core/runtime/interactive-deliver.js";import{isProfilePaused as ge}from"../../../core/profiles/manifest.js";import{getNode as C,withFreshTerminalGuard as ve}from"../../../core/canvas/canvas.js";import{getById as G,nodeObject as F,ownerForGrantee as _e}from"../../../core/graph/objects.js";import{recordActedOn as ke}from"../../../core/graph/edges.js";import{recordWatch as H}from"../../../core/graph/watches.js";import{publish as V}from"../../../core/graph/events.js";import{readerFor as K}from"../reader.js";import{canRead as Se}from"../../../core/graph/access.js";import{withCanvasWrite as k}from"../../../core/canvas/db.js";import{getPendingStructuredRequestForNode as Q}from"../../../core/canvas/structured-requests.js";import{consumeDeadlineOnWake as X}from"../../../core/feed/messages.js";import{assertNotFinalized as M,assertFinalizedForReopen as Ne,commitReopenResident as E}from"../../../core/runtime/reopen.js";import{admitLegacyStructuredOutput as $e}from"../../structured-requests/sidecar.js";import{assertOutputSchemaAccepted as je}from"../../../core/runtime/structured-output.js";import{appendSituationalContext as P,formatSituationalProse as Ae}from"../../../core/runtime/situational-context.js";import{formatDataCard as Y}from"../../../shared/generated-context.js";import{hasNoNaturalCycle as Oe}from"../../../core/runtime/revive-all.js";import{recordPendingParkActivity as qe}from"../../park-pending.js";import{wantsExecution as Ce}from"../../reconcilers/node-lifecycle/wants-execution.js";import{hasFreshGroundState as xe}from"../../../core/runtime/revive.js";import{CrtrError as Re,notFound as x,usage as d}from"../../../core/errors.js";import{isStartRefusal as Fe}from"../../../core/runtime/start-check.js";import{emitEvent as Me}from"../../../core/events/emit.js";import{assertScope as Ee}from"../../../core/scopes.js";import{InputError as I}from"../../../core/io.js";import{ApiError as Pe}from"../../../api/index.js";import{describeObject as Ie,stubOf as Te}from"../../../core/peer/stubs.js";import{machineNameOf as Z}from"../../../core/peer/names.js";import{callerNode as Be,callerStub as ze,forwardVerb as ee,relayError as te,remoteStub as Je,unknownError as re,withMachine as ne}from"../../peer/forward.js";import{ownerOnly as We}from"../router.js";import{personId as De}from"../../../core/canvas/person.js";const Le=["critical","urgent","normal","deferred"];function oe(t,e){if(typeof t!="object"||t===null||Array.isArray(t))throw d(`${e} must be an object { kind, facts?, body? }`);const a=t,n=a.kind;if(typeof n!="string"||n.trim()==="")throw d(`${e}.kind is required`);if(!n.includes(":"))throw d(`${e}.kind must be namespaced (contain ':'): ${n}`);const r={kind:n},o=a.facts;if(o!==void 0){if(typeof o!="object"||o===null||Array.isArray(o))throw d(`${e}.facts must be an object of string or number values`);const c={};for(const[l,m]of Object.entries(o)){if(typeof m!="string"&&typeof m!="number")throw d(`${e}.facts.${l} must be a string or number`);c[l]=m}r.facts=c}const i=a.body;if(i!==void 0){if(typeof i!="string")throw d(`${e}.body must be a string`);r.body=i}return r}u(oe,"parseCardRequest");function ae(t,e){try{return Y(t.kind,t.facts??{},t.body??"")}catch(a){throw d(`${e}: ${a instanceof Error?a.message:String(a)}`)}}u(ae,"renderCard");function Ue(t){if(typeof t!="object"||t===null)throw d("a message requires a JSON body { body, tier?, fresh? }");const e=t,a=e.body,n=e.fresh===!0,r=e.tier,o=e.situational_context,i=e.output_schema;if(i!=null&&typeof i!="string")throw d("output_schema must be a JSON schema string");const c=typeof a=="string"&&a.trim()!=="",l=typeof o=="string"&&o.trim()!=="",m=typeof i=="string"&&i.trim()!=="",v=e.situational_card,S=e.context_cards,b=v===void 0?void 0:oe(v,"situational_card");if(S!==void 0&&!Array.isArray(S))throw d("context_cards must be an array of { kind, facts?, body? }");const p=S?.map(($,N)=>oe($,`context_cards[${N}]`));if(b!==void 0&&typeof o=="string"&&o!=="")throw d("situational_card and situational_context are mutually exclusive");const w=b!==void 0||p!==void 0&&p.length>0;if(!n&&!c&&!l&&!m&&!w)throw d("a message requires a non-empty body (or fresh: true, situational_context, a runtime card, or output_schema)");if(n&&p!==void 0&&p.length>0)throw d("context_cards cannot ride a fresh revive (no inbox entry carries them)");if(r!==void 0&&!Le.includes(r))throw d(`invalid tier: ${String(r)} (expected critical|urgent|normal|deferred)`);const f={body:typeof a=="string"?a:""};r!==void 0&&(f.tier=r),n&&(f.fresh=!0),e.reopen===!0&&(f.reopen=!0),typeof o=="string"&&(f.situational_context=o),b!==void 0&&(f.situational_card=b),p!==void 0&&(f.context_cards=p),typeof i=="string"&&(f.output_schema=i),typeof e.from=="string"&&(f.from=e.from);const y=e.delivery;if(y!==void 0&&y!=="interactive")throw d(`invalid delivery: ${String(y)} (expected interactive)`);if(y==="interactive"){if(n||f.situational_context!==void 0||f.output_schema!==void 0)throw d("interactive delivery supports a body, runtime cards, and reopen only (no fresh, situational_context, or output_schema)");if(!c)throw d("interactive delivery requires a non-empty body");if(f.tier==="deferred")throw d("interactive delivery cannot be deferred");f.delivery="interactive"}return f}u(Ue,"parseSendBody");function Ge(t){let e;try{e=JSON.parse(t)}catch{throw d("output_schema must be a JSON schema string")}if(typeof e!="object"||e===null||Array.isArray(e))throw d("output_schema must be a JSON schema object");return e}u(Ge,"parseSchema");function He(t){return t.split(`
2
- `)[0].slice(0,120)}u(He,"label");function ie(t,e){return e===null?"":Y("reopen-final-report",{report:`${t}/${e}`},"This node previously completed work. Read this final report before acting on the new instruction.")}u(ie,"previousFinalReportCard");async function Ve(t,e,a){if(a!==null&&a!=="human"&&(await G(t,a))?.type==="node"){const o=await F(t,a);return{actor:o,senderNode:o}}if(a==="human")return{actor:await _e(t,De()),senderNode:null};const n=await K(t,e);return{actor:n.class==="person"?n.person:n.class==="app"?n.app:n.node,senderNode:n.class==="node"?n.node:null}}u(Ve,"messageActor");async function se(t,e,a,n,r,o){const i=await F(t,a),{actor:c,senderNode:l}=await Ve(t,e,n),m=r===null?{}:{pointer:r};await ke(t,c,i),l!==null&&l.id!==i.id&&await H(t,l,i,"message",{endsOn:o&&r!==null?`result:${r}`:"final"}),await V(t,{event:"messaged",object:i,actor:c,attrs:{},...m}),l!==null&&await V(t,{event:"sent",object:l,actor:l,attrs:{to:i.id},...m})}u(se,"recordMessage");function Ke(t,e){return new I({error:"deferred_no_natural_cycle",message:`${t} is ${e} with no natural next cycle ahead of it \u2014 a deferred message would never be delivered.`,next:"Use --tier normal, urgent, or critical to wake it now, or --reopen (with a body or --fresh) to re-task it first."})}u(Ke,"deferredNoNaturalCycle");async function Qe(t){if(!await xe(t))throw new Pe(422,"unprocessable",`node ${t} has no goal/roadmap on disk \u2014 a fresh revive would resume amnesiac.`)}u(Qe,"assertRecoverableForFresh");function Xe(t,e){return t instanceof I?{error:t.payload.error,message:t.payload.message,next:t.payload.next,message_id:e}:t instanceof Re?{error:t.code,message:t.message,message_id:e}:Fe(t)?{error:t.code,message:t.message,message_id:e}:{error:"wake_failed",message:"the target could not be woken; see the daemon log",message_id:e}}u(Xe,"wakeFailure");async function Ye(t,e){const a=typeof t.body=="object"&&t.body!==null&&!Array.isArray(t.body)?{...t.body}:t.body;typeof a=="object"&&a!==null&&delete a.from;const n=await ee(t,e,{method:"POST",path:`/v1/nodes/${encodeURIComponent(e)}/messages`,body:a});if(n.kind==="local")return null;if(n.kind==="unknown")throw re(e,n.unreachable);if(n.status>=400)throw te(n.status,n.body);return await k(async r=>{const o=await Be(r,t);if(o===null)return;const i=n.body?.object,c=await Je(r,e,"node",n.machine.id,i);await H(r,o,c,"message",{endsOn:"final"})}),{status:n.status,body:ne(n.body,n.machine)}}u(Ye,"forwardMessage");async function Ze(t){const e=await et(t);if(t.principal.class!=="forwarded"||typeof e.body!="object"||e.body===null)return e;const a=await k(async n=>{const r=await F(n,t.params.id);return await Se(n,await K(n,t),r)?await Ie(n,r):{id:r.id,type:r.type,kind:null,name:r.id,owner:null}});return{...e,body:{...e.body,object:a}}}u(Ze,"handleMessage");async function et(t){const e=t.params.id,a=await Ye(t,e);if(a!==null)return a;const n=await C(e);if(n===null)throw x(`unknown node: ${e}`,{received:e});const r=Ue(t.body),o=r.tier??"normal",i=ge(n.profile_id);r.reopen&&ye(e,n),r.reopen&&!i&&!q(n)&&await he(e,n);const c=t.principal.class==="forwarded"?await k(async s=>(await ze(s,t))?.id??null):r.from??null;if(c!==null){const s=await C(c);s!==null&&Ee(s,"crtr:act")}const l=c===null?null:await k(async s=>{const h=await G(s,c);return h===null?null:(await Te(s,h))?.home_machine??null}),m=l===null?void 0:`${c} on ${Z(l)}`,v=t.principal.class==="broker"?t.principal.node:null,S=l===null?{}:{from_machine:Z(l)},b=r.body.trim()!=="",p=r.situational_card!==void 0?ae(r.situational_card,"situational_card"):r.situational_context!==void 0?Ae(r.situational_context.trim()):"",w=p!=="",f=(r.context_cards??[]).map((s,h)=>ae(s,`context_cards[${h}]`)),y=r.output_schema!==void 0&&r.output_schema.trim()!==""?Ge(r.output_schema):null;y!==null&&await je(y);let $=!1;const N=u(async s=>{if(!(y===null||$)){if(await Q(e)!==null)throw new I({error:"structured_request_conflict",message:`node ${e} already has a pending structured request`,next:"Wait for the current request to settle before requesting another structured result."});await $e(e,"oneoff",y,s),$=!0}},"ensureSchema");if(r.fresh){const s=r.reopen?await Ne(e):null;r.reopen||await M(e),await Qe(e),await N(),w&&await P(e,p),r.reopen&&await E(e,s,v);const h=await L(e,{resume:!1,capacity:"refuse"});return{status:201,body:{node_id:e,delivered:!1,revived:h.launch!==void 0}}}r.delivery==="interactive"&&!r.reopen&&await M(e);let T=!1,_="";if(r.delivery==="interactive"&&r.reopen&&(_=ie(e,await E(e,void 0,v)),T=!0),r.delivery==="interactive"&&await N(),r.delivery==="interactive"&&!i&&!n.run_id&&q(n))try{return w&&await P(e,p),await we(e,r.body,{cards:[..._===""?[]:[_],...w?[p]:[],...f],origin:c==="human"?{type:"human"}:{type:"runtime",kind:"inbox",entries:[{...c===null?{}:{from:c},...m===void 0?{}:{fromName:m},kind:"message",tier:o}]}}),await k(async h=>await se(h,t,e,c,null,!1)),await X(e),{status:201,body:{node_id:e,delivered:!0,revived:!1,delivered_via:"engine"}}}catch(s){if(!(s instanceof U))throw s}const B=u(async()=>{r.reopen||await M(e);const s=ue(16).toString("hex"),h=u(async O=>await se(O,t,e,c,s,y!==null),"withinEnqueue");await N(s),w&&await P(e,p),r.reopen&&!T&&(_=ie(e,await E(e,void 0,v)));const R=[..._===""?[]:[_],...f],W=R.length>0?{cards:R}:{};if(b||y!==null){const O=b?r.body:`A one-off structured-output request has been granted. Submit a result matching the requested schema with the \`submit_result\` tool (\`request_id: "${(await Q(e))?.request_id??"<request-id>"}"\`) before you stop; after it is accepted, continue normally.`;return await D(e,{senderNodeId:c,...m===void 0?{}:{senderName:m},urgency:o,wake:1,kind:"message",messageId:s,withinEnqueue:h,label:He(O),bodyJson:{body:O,...S,...w?{situational:!0}:{},...W}})}return await D(e,{senderNodeId:c,...m===void 0?{}:{senderName:m},urgency:o,wake:1,kind:"message",messageId:s,withinEnqueue:h,label:w?"(ambient context updated)":"(context delivered)",bodyJson:{...w?{situational:!0}:{},situationalOnly:!0,...W}})},"deliverImmediate"),g=await u(async()=>{if(o==="deferred"){const s=await ve(e,Oe,B);if(s.kind==="missing")throw x(`unknown node: ${e}`,{received:e});if(s.kind==="terminal")throw Ke(e,s.status);return s.result}return await B()},"deliver")();g.urgency!=="deferred"&&await k(async()=>qe(e));const j=await C(e);if(j===null)throw x(`unknown node: ${e}`,{received:e});n.frozen_at!==null&&await X(e);let z=!1,J=!1,A;if((r.reopen||j.lifecycle==="terminal"||!await Ce(j))&&g.urgency!=="deferred"&&!i&&!q(j))try{const s=await L(e,{resume:!0,capacity:"freeze"});z=s.launch!==void 0,J=s.outcome==="frozen"}catch(s){A=Xe(s,g.messageId),Me({level:"error",event:"message.wake_failed",node_id:e,error:s,fields:{message_id:g.messageId,error_code:A.error}})}return{status:201,body:{node_id:e,delivered:!0,revived:z,...J?{not_revived_reason:"capacity_frozen"}:{},...A===void 0?{}:{wake_failed:A},delivered_at:g.createdAt,...g.urgency===o?{}:{delivered_tier:g.urgency},...r.delivery==="interactive"?{delivered_via:"inbox"}:{}}}}u(et,"handleMessageHere");async function tt(t){const e=t.params.id,a=await ee(t,e,{method:"POST",path:`/v1/nodes/${encodeURIComponent(e)}/interrupt`,body:t.body});if(a.kind==="unknown")throw re(e,a.unreachable);if(a.kind==="remote"){if(a.status>=400)throw te(a.status,a.body);return{status:a.status,body:ne(a.body,a.machine)}}const n=await C(e);if(n===null)throw x(`unknown node: ${e}`,{received:e});const r=await pe(e,{senderNodeId:"human",kind:"message"});let o=!1;if(q(n))try{o=await be(e)!=="idle"}catch(c){if(!(c instanceof U))throw c}return{status:200,body:{node_id:e,outcome:o?"aborted_turn":r.length>0?"canceled_pending":"idle",aborted_turn:o,canceled_pending:r.length}}}u(tt,"handleInterrupt");function de(t){if(typeof t.body!="object"||t.body===null||Array.isArray(t.body))throw d("mail requires an object body");const e=t.body;if(typeof e.execution_id!="string"||e.execution_id.trim()==="")throw d("execution_id is required");return e}u(de,"mailBody");async function rt(t){const e=de(t),a=e.channel;if(a!=="wake"&&a!=="passive"&&a!=="deferred_run")throw d("channel must be wake, passive, or deferred_run");const n=await le(t.params.id,e.execution_id,a);return{status:200,body:{action:n.action,deliveries:n.deliveries.map(o=>({delivery_id:o.deliveryId,attempts:o.attempts,handoff:o.handoff,entry:{...me(o),seq:o.message.seq}}))}}}u(rt,"handleMailClaim");async function nt(t){const e=de(t);if(!Array.isArray(e.deliveries))throw d("deliveries must be an array");const a=e.deliveries.map(o=>{if(typeof o!="object"||o===null||Array.isArray(o))throw d("each delivery must be an object");const i=o;if(typeof i.delivery_id!="string"||i.delivery_id==="")throw d("delivery_id is required");if(!Number.isSafeInteger(i.attempts)||i.attempts<1)throw d("attempts must be a positive integer");if(i.disposition!=="acknowledged"&&i.disposition!=="released")throw d("disposition must be acknowledged or released");return{delivery_id:i.delivery_id,attempts:i.attempts,disposition:i.disposition}}),n=await fe(t.params.id,e.execution_id,a.map(o=>({deliveryId:o.delivery_id,attempts:o.attempts,disposition:o.disposition})));return{status:200,body:{action:n.action,results:n.results.map(o=>({delivery_id:o.deliveryId,outcome:o.outcome}))}}}u(nt,"handleMailAcknowledge");const Ht=We([{method:"POST",pattern:"/v1/nodes/:id/mail/claim",handler:rt},{method:"POST",pattern:"/v1/nodes/:id/mail/acknowledge",handler:nt}]),Vt=[{method:"POST",pattern:"/v1/nodes/:id/messages",scope:"crtr:act",handler:Ze},{method:"POST",pattern:"/v1/nodes/:id/interrupt",scope:"crtr:act",handler:tt}];export{Ht as brokerMailRoutes,Ze as handleMessage,Vt as messageRoutes};
1
+ var ue=Object.defineProperty;var u=(t,e)=>ue(t,"name",{value:e,configurable:!0});import{randomBytes as le}from"node:crypto";import{claimNodeMail as fe,acknowledgeNodeMail as me}from"../../../core/canvas/deliveries.js";import{nodeMailEntry as pe}from"../../../core/feed/inbox.js";import{enqueueNodeMail as D,cancelPendingNodeMail as ye}from"../../../core/feed/messages.js";import{assertCheckoutNotRemoved as L,assertRecordedCwdExists as he,reviveNode as U}from"../../../core/runtime/revive.js";import{BrokerUnreachableError as G}from"../../../core/runtime/broker-request.js";import{isBrokerLive as q}from"../../../core/runtime/model-swap.js";import{deliverLive as we,interruptLive as be}from"../../../core/runtime/interactive-deliver.js";import{isProfilePaused as ge}from"../../../core/profiles/manifest.js";import{getNode as C,withFreshTerminalGuard as ve}from"../../../core/canvas/canvas.js";import{getById as H,nodeObject as F,ownerForGrantee as _e}from"../../../core/graph/objects.js";import{recordActedOn as ke}from"../../../core/graph/edges.js";import{recordWatch as V}from"../../../core/graph/watches.js";import{publish as K}from"../../../core/graph/events.js";import{readerFor as Q}from"../reader.js";import{canRead as Se}from"../../../core/graph/access.js";import{withCanvasWrite as k}from"../../../core/canvas/db.js";import{getPendingStructuredRequestForNode as X}from"../../../core/canvas/structured-requests.js";import{consumeDeadlineOnWake as Y}from"../../../core/feed/messages.js";import{assertNotFinalized as M,assertFinalizedForReopen as Ne,commitReopenResident as E}from"../../../core/runtime/reopen.js";import{admitLegacyStructuredOutput as $e}from"../../structured-requests/sidecar.js";import{assertOutputSchemaAccepted as je}from"../../../core/runtime/structured-output.js";import{appendSituationalContext as P,formatSituationalProse as Ae}from"../../../core/runtime/situational-context.js";import{formatDataCard as Z}from"../../../shared/generated-context.js";import{hasNoNaturalCycle as Oe}from"../../../core/runtime/revive-all.js";import{recordPendingParkActivity as qe}from"../../park-pending.js";import{wantsExecution as Ce}from"../../reconcilers/node-lifecycle/wants-execution.js";import{hasFreshGroundState as xe}from"../../../core/runtime/revive.js";import{CrtrError as Re,notFound as x,usage as d}from"../../../core/errors.js";import{isStartRefusal as Fe}from"../../../core/runtime/start-check.js";import{emitEvent as Me}from"../../../core/events/emit.js";import{assertScope as Ee}from"../../../core/scopes.js";import{InputError as I}from"../../../core/io.js";import{ApiError as Pe}from"../../../api/index.js";import{describeObject as Ie,stubOf as Te}from"../../../core/peer/stubs.js";import{machineNameOf as ee}from"../../../core/peer/names.js";import{callerNode as Be,callerStub as ze,forwardVerb as te,relayError as re,remoteStub as Je,unknownError as ne,withMachine as oe}from"../../peer/forward.js";import{ownerOnly as We}from"../router.js";import{personId as De}from"../../../core/canvas/person.js";const Le=["critical","urgent","normal","deferred"];function ae(t,e){if(typeof t!="object"||t===null||Array.isArray(t))throw d(`${e} must be an object { kind, facts?, body? }`);const a=t,n=a.kind;if(typeof n!="string"||n.trim()==="")throw d(`${e}.kind is required`);if(!n.includes(":"))throw d(`${e}.kind must be namespaced (contain ':'): ${n}`);const r={kind:n},o=a.facts;if(o!==void 0){if(typeof o!="object"||o===null||Array.isArray(o))throw d(`${e}.facts must be an object of string or number values`);const c={};for(const[l,m]of Object.entries(o)){if(typeof m!="string"&&typeof m!="number")throw d(`${e}.facts.${l} must be a string or number`);c[l]=m}r.facts=c}const i=a.body;if(i!==void 0){if(typeof i!="string")throw d(`${e}.body must be a string`);r.body=i}return r}u(ae,"parseCardRequest");function ie(t,e){try{return Z(t.kind,t.facts??{},t.body??"")}catch(a){throw d(`${e}: ${a instanceof Error?a.message:String(a)}`)}}u(ie,"renderCard");function Ue(t){if(typeof t!="object"||t===null)throw d("a message requires a JSON body { body, tier?, fresh? }");const e=t,a=e.body,n=e.fresh===!0,r=e.tier,o=e.situational_context,i=e.output_schema;if(i!=null&&typeof i!="string")throw d("output_schema must be a JSON schema string");const c=typeof a=="string"&&a.trim()!=="",l=typeof o=="string"&&o.trim()!=="",m=typeof i=="string"&&i.trim()!=="",v=e.situational_card,S=e.context_cards,b=v===void 0?void 0:ae(v,"situational_card");if(S!==void 0&&!Array.isArray(S))throw d("context_cards must be an array of { kind, facts?, body? }");const p=S?.map(($,N)=>ae($,`context_cards[${N}]`));if(b!==void 0&&typeof o=="string"&&o!=="")throw d("situational_card and situational_context are mutually exclusive");const w=b!==void 0||p!==void 0&&p.length>0;if(!n&&!c&&!l&&!m&&!w)throw d("a message requires a non-empty body (or fresh: true, situational_context, a runtime card, or output_schema)");if(n&&p!==void 0&&p.length>0)throw d("context_cards cannot ride a fresh revive (no inbox entry carries them)");if(r!==void 0&&!Le.includes(r))throw d(`invalid tier: ${String(r)} (expected critical|urgent|normal|deferred)`);const f={body:typeof a=="string"?a:""};r!==void 0&&(f.tier=r),n&&(f.fresh=!0),e.reopen===!0&&(f.reopen=!0),typeof o=="string"&&(f.situational_context=o),b!==void 0&&(f.situational_card=b),p!==void 0&&(f.context_cards=p),typeof i=="string"&&(f.output_schema=i),typeof e.from=="string"&&(f.from=e.from);const y=e.delivery;if(y!==void 0&&y!=="interactive")throw d(`invalid delivery: ${String(y)} (expected interactive)`);if(y==="interactive"){if(n||f.situational_context!==void 0||f.output_schema!==void 0)throw d("interactive delivery supports a body, runtime cards, and reopen only (no fresh, situational_context, or output_schema)");if(!c)throw d("interactive delivery requires a non-empty body");if(f.tier==="deferred")throw d("interactive delivery cannot be deferred");f.delivery="interactive"}return f}u(Ue,"parseSendBody");function Ge(t){let e;try{e=JSON.parse(t)}catch{throw d("output_schema must be a JSON schema string")}if(typeof e!="object"||e===null||Array.isArray(e))throw d("output_schema must be a JSON schema object");return e}u(Ge,"parseSchema");function He(t){return t.split(`
2
+ `)[0].slice(0,120)}u(He,"label");function se(t,e){return e===null?"":Z("reopen-final-report",{report:`${t}/${e}`},"This node previously completed work. Read this final report before acting on the new instruction.")}u(se,"previousFinalReportCard");async function Ve(t,e,a){if(a!==null&&a!=="human"&&(await H(t,a))?.type==="node"){const o=await F(t,a);return{actor:o,senderNode:o}}if(a==="human")return{actor:await _e(t,De()),senderNode:null};const n=await Q(t,e);return{actor:n.class==="person"?n.person:n.class==="app"?n.app:n.node,senderNode:n.class==="node"?n.node:null}}u(Ve,"messageActor");async function de(t,e,a,n,r,o){const i=await F(t,a),{actor:c,senderNode:l}=await Ve(t,e,n),m=r===null?{}:{pointer:r};await ke(t,c,i),l!==null&&l.id!==i.id&&await V(t,l,i,"message",{endsOn:o&&r!==null?`result:${r}`:"final"}),await K(t,{event:"messaged",object:i,actor:c,attrs:{},...m}),l!==null&&await K(t,{event:"sent",object:l,actor:l,attrs:{to:i.id},...m})}u(de,"recordMessage");function Ke(t,e){return new I({error:"deferred_no_natural_cycle",message:`${t} is ${e} with no natural next cycle ahead of it \u2014 a deferred message would never be delivered.`,next:"Use --tier normal, urgent, or critical to wake it now, or --reopen (with a body or --fresh) to re-task it first."})}u(Ke,"deferredNoNaturalCycle");async function Qe(t){if(!await xe(t))throw new Pe(422,"unprocessable",`node ${t} has no goal/roadmap on disk \u2014 a fresh revive would resume amnesiac.`)}u(Qe,"assertRecoverableForFresh");function Xe(t,e){return t instanceof I?{error:t.payload.error,message:t.payload.message,next:t.payload.next,message_id:e}:t instanceof Re?{error:t.code,message:t.message,message_id:e}:Fe(t)?{error:t.code,message:t.message,message_id:e}:{error:"wake_failed",message:"the target could not be woken; see the daemon log",message_id:e}}u(Xe,"wakeFailure");async function Ye(t,e){const a=typeof t.body=="object"&&t.body!==null&&!Array.isArray(t.body)?{...t.body}:t.body;typeof a=="object"&&a!==null&&delete a.from;const n=await te(t,e,{method:"POST",path:`/v1/nodes/${encodeURIComponent(e)}/messages`,body:a});if(n.kind==="local")return null;if(n.kind==="unknown")throw ne(e,n.unreachable);if(n.status>=400)throw re(n.status,n.body);return await k(async r=>{const o=await Be(r,t);if(o===null)return;const i=n.body?.object,c=await Je(r,e,"node",n.machine.id,i);await V(r,o,c,"message",{endsOn:"final"})}),{status:n.status,body:oe(n.body,n.machine)}}u(Ye,"forwardMessage");async function Ze(t){const e=await et(t);if(t.principal.class!=="forwarded"||typeof e.body!="object"||e.body===null)return e;const a=await k(async n=>{const r=await F(n,t.params.id);return await Se(n,await Q(n,t),r)?await Ie(n,r):{id:r.id,type:r.type,kind:null,name:r.id,owner:null}});return{...e,body:{...e.body,object:a}}}u(Ze,"handleMessage");async function et(t){const e=t.params.id,a=await Ye(t,e);if(a!==null)return a;const n=await C(e);if(n===null)throw x(`unknown node: ${e}`,{received:e});const r=Ue(t.body),o=r.tier??"normal",i=ge(n.profile_id);r.reopen&&L(e,n),r.reopen&&!i&&!q(n)&&await he(e,n);const c=t.principal.class==="forwarded"?await k(async s=>(await ze(s,t))?.id??null):r.from??null;if(c!==null){const s=await C(c);s!==null&&Ee(s,"crtr:act")}const l=c===null?null:await k(async s=>{const h=await H(s,c);return h===null?null:(await Te(s,h))?.home_machine??null}),m=l===null?void 0:`${c} on ${ee(l)}`,v=t.principal.class==="broker"?t.principal.node:null,S=l===null?{}:{from_machine:ee(l)},b=r.body.trim()!=="",p=r.situational_card!==void 0?ie(r.situational_card,"situational_card"):r.situational_context!==void 0?Ae(r.situational_context.trim()):"",w=p!=="",f=(r.context_cards??[]).map((s,h)=>ie(s,`context_cards[${h}]`)),y=r.output_schema!==void 0&&r.output_schema.trim()!==""?Ge(r.output_schema):null;y!==null&&await je(y);let $=!1;const N=u(async s=>{if(!(y===null||$)){if(await X(e)!==null)throw new I({error:"structured_request_conflict",message:`node ${e} already has a pending structured request`,next:"Wait for the current request to settle before requesting another structured result."});await $e(e,"oneoff",y,s),$=!0}},"ensureSchema");if(r.fresh){L(e,n);const s=r.reopen?await Ne(e):null;r.reopen||await M(e),await Qe(e),await N(),w&&await P(e,p),r.reopen&&await E(e,s,v);const h=await U(e,{resume:!1,capacity:"refuse"});return{status:201,body:{node_id:e,delivered:!1,revived:h.launch!==void 0}}}r.delivery==="interactive"&&!r.reopen&&await M(e);let T=!1,_="";if(r.delivery==="interactive"&&r.reopen&&(_=se(e,await E(e,void 0,v)),T=!0),r.delivery==="interactive"&&await N(),r.delivery==="interactive"&&!i&&!n.run_id&&q(n))try{return w&&await P(e,p),await we(e,r.body,{cards:[..._===""?[]:[_],...w?[p]:[],...f],origin:c==="human"?{type:"human"}:{type:"runtime",kind:"inbox",entries:[{...c===null?{}:{from:c},...m===void 0?{}:{fromName:m},kind:"message",tier:o}]}}),await k(async h=>await de(h,t,e,c,null,!1)),await Y(e),{status:201,body:{node_id:e,delivered:!0,revived:!1,delivered_via:"engine"}}}catch(s){if(!(s instanceof G))throw s}const B=u(async()=>{r.reopen||await M(e);const s=le(16).toString("hex"),h=u(async O=>await de(O,t,e,c,s,y!==null),"withinEnqueue");await N(s),w&&await P(e,p),r.reopen&&!T&&(_=se(e,await E(e,void 0,v)));const R=[..._===""?[]:[_],...f],W=R.length>0?{cards:R}:{};if(b||y!==null){const O=b?r.body:`A one-off structured-output request has been granted. Submit a result matching the requested schema with the \`submit_result\` tool (\`request_id: "${(await X(e))?.request_id??"<request-id>"}"\`) before you stop; after it is accepted, continue normally.`;return await D(e,{senderNodeId:c,...m===void 0?{}:{senderName:m},urgency:o,wake:1,kind:"message",messageId:s,withinEnqueue:h,label:He(O),bodyJson:{body:O,...S,...w?{situational:!0}:{},...W}})}return await D(e,{senderNodeId:c,...m===void 0?{}:{senderName:m},urgency:o,wake:1,kind:"message",messageId:s,withinEnqueue:h,label:w?"(ambient context updated)":"(context delivered)",bodyJson:{...w?{situational:!0}:{},situationalOnly:!0,...W}})},"deliverImmediate"),g=await u(async()=>{if(o==="deferred"){const s=await ve(e,Oe,B);if(s.kind==="missing")throw x(`unknown node: ${e}`,{received:e});if(s.kind==="terminal")throw Ke(e,s.status);return s.result}return await B()},"deliver")();g.urgency!=="deferred"&&await k(async()=>qe(e));const j=await C(e);if(j===null)throw x(`unknown node: ${e}`,{received:e});n.frozen_at!==null&&await Y(e);let z=!1,J=!1,A;if((r.reopen||j.lifecycle==="terminal"||!await Ce(j))&&g.urgency!=="deferred"&&!i&&!q(j))try{const s=await U(e,{resume:!0,capacity:"freeze"});z=s.launch!==void 0,J=s.outcome==="frozen"}catch(s){A=Xe(s,g.messageId),Me({level:"error",event:"message.wake_failed",node_id:e,error:s,fields:{message_id:g.messageId,error_code:A.error}})}return{status:201,body:{node_id:e,delivered:!0,revived:z,...J?{not_revived_reason:"capacity_frozen"}:{},...A===void 0?{}:{wake_failed:A},delivered_at:g.createdAt,...g.urgency===o?{}:{delivered_tier:g.urgency},...r.delivery==="interactive"?{delivered_via:"inbox"}:{}}}}u(et,"handleMessageHere");async function tt(t){const e=t.params.id,a=await te(t,e,{method:"POST",path:`/v1/nodes/${encodeURIComponent(e)}/interrupt`,body:t.body});if(a.kind==="unknown")throw ne(e,a.unreachable);if(a.kind==="remote"){if(a.status>=400)throw re(a.status,a.body);return{status:a.status,body:oe(a.body,a.machine)}}const n=await C(e);if(n===null)throw x(`unknown node: ${e}`,{received:e});const r=await ye(e,{senderNodeId:"human",kind:"message"});let o=!1;if(q(n))try{o=await be(e)!=="idle"}catch(c){if(!(c instanceof G))throw c}return{status:200,body:{node_id:e,outcome:o?"aborted_turn":r.length>0?"canceled_pending":"idle",aborted_turn:o,canceled_pending:r.length}}}u(tt,"handleInterrupt");function ce(t){if(typeof t.body!="object"||t.body===null||Array.isArray(t.body))throw d("mail requires an object body");const e=t.body;if(typeof e.execution_id!="string"||e.execution_id.trim()==="")throw d("execution_id is required");return e}u(ce,"mailBody");async function rt(t){const e=ce(t),a=e.channel;if(a!=="wake"&&a!=="passive"&&a!=="deferred_run")throw d("channel must be wake, passive, or deferred_run");const n=await fe(t.params.id,e.execution_id,a);return{status:200,body:{action:n.action,deliveries:n.deliveries.map(o=>({delivery_id:o.deliveryId,attempts:o.attempts,handoff:o.handoff,entry:{...pe(o),seq:o.message.seq}}))}}}u(rt,"handleMailClaim");async function nt(t){const e=ce(t);if(!Array.isArray(e.deliveries))throw d("deliveries must be an array");const a=e.deliveries.map(o=>{if(typeof o!="object"||o===null||Array.isArray(o))throw d("each delivery must be an object");const i=o;if(typeof i.delivery_id!="string"||i.delivery_id==="")throw d("delivery_id is required");if(!Number.isSafeInteger(i.attempts)||i.attempts<1)throw d("attempts must be a positive integer");if(i.disposition!=="acknowledged"&&i.disposition!=="released")throw d("disposition must be acknowledged or released");return{delivery_id:i.delivery_id,attempts:i.attempts,disposition:i.disposition}}),n=await me(t.params.id,e.execution_id,a.map(o=>({deliveryId:o.delivery_id,attempts:o.attempts,disposition:o.disposition})));return{status:200,body:{action:n.action,results:n.results.map(o=>({delivery_id:o.deliveryId,outcome:o.outcome}))}}}u(nt,"handleMailAcknowledge");const Ht=We([{method:"POST",pattern:"/v1/nodes/:id/mail/claim",handler:rt},{method:"POST",pattern:"/v1/nodes/:id/mail/acknowledge",handler:nt}]),Vt=[{method:"POST",pattern:"/v1/nodes/:id/messages",scope:"crtr:act",handler:Ze},{method:"POST",pattern:"/v1/nodes/:id/interrupt",scope:"crtr:act",handler:tt}];export{Ht as brokerMailRoutes,Ze as handleMessage,Vt as messageRoutes};
@@ -1 +1 @@
1
- var je=Object.defineProperty;var d=(e,n)=>je(e,"name",{value:n,configurable:!0});import{randomUUID as Fe}from"node:crypto";import{envProfileId as Ge}from"../../../shared/env.js";import{pausedCanvasProfiles as xe}from"../../../core/profiles/manifest.js";import{existsSync as $,realpathSync as oe,statSync as ae}from"node:fs";import{isAbsolute as W,resolve as L}from"node:path";import{appendSituationalContext as Be,formatSituationalProse as We}from"../../../core/runtime/situational-context.js";import{closeNode as Ue}from"../../../core/runtime/close.js";import{assertCheckoutNotRemoved as Ve,reviveNode as de}from"../../../core/runtime/revive.js";import{nowIso as U}from"../../../core/fs-utils.js";import{appPaidLaunch as Ke,assertLaunchModelRegistered as V,forkNode as Je,resolveForkSource as se,spawnChildPrepared as ze}from"../../../core/runtime/spawn.js";import{forkSourceNode as le,newNodeId as ce}from"../../../core/runtime/nodes.js";import{abandonCreateRequest as ue,CREATE_LEASE_RENEW_MS as He,claimCreateLease as fe,createLeaseLive as Ye,renewCreateLease as Qe,childrenOf as Xe,completeCreateRequest as pe,findCreateRequest as me,getNode as b,recordCreateRequestNode as Ze,reserveCreateRequest as we,reserveCreateRequestNode as qe,listNodes as en,recordRespawnAttempt as nn,subscribersOf as tn,subscriptionsOf as he,updateNode as T}from"../../../core/canvas/canvas.js";import{armControllerWait as rn,liveControllerWaits as on}from"../../../core/canvas/waits.js";import{withCanvasWrite as K}from"../../../core/canvas/db.js";import{markNodeRead as an}from"../../../core/canvas/recovery.js";import{nodeObject as dn}from"../../../core/graph/objects.js";import{recordActedOn as sn}from"../../../core/graph/edges.js";import{publish as ln}from"../../../core/graph/events.js";import{readerFor as cn}from"../reader.js";import{relocateSessionCwd as un,unbindSession as fn}from"../../../core/canvas/sessions.js";import{ticketCountsForNodes as pn}from"../../../core/canvas/attention.js";import{isSafeNodeId as mn}from"../../../core/canvas/paths.js";import{contextDir as ye,nodeAgentDir as J}from"../../../core/canvas/node-agent-paths.js";import{checkCronBirth as wn,cronRefusalError as hn}from"../../cron/authority.js";import{cronBirthPlacement as yn}from"../../cron/armed-context.js";import{existsBeneath as _n,isAbsentOrRefused as gn,isBeneathRefusal as bn,readdirBeneath as vn}from"../../../core/spaces/open-beneath.js";import{readNodeMessagesPage as kn,readNodeSession as Sn,readNodeSnapshot as In,transcriptMarkdown as Rn}from"../../../core/runtime/node-read.js";import{toolCallIds as En,withoutImages as _e}from"../../../core/runtime/broker-protocol.js";import{welcomeWindow as On}from"../../../core/runtime/session-cycles.js";import{assembleNodeSubject as Cn}from"../../../core/substrate/subject.js";import{reviveAll as An}from"../../../core/runtime/revive-all.js";import{promoteAsync as $n,requestYieldAsync as Tn,reshapeNodeAsync as z}from"../../../core/runtime/promote.js";import{recycleNode as Nn}from"../../../core/runtime/recycle.js";import{relaunchRoot as Pn}from"../../../core/runtime/reset.js";import{assertReopenGate as Dn}from"../../../core/runtime/reopen.js";import{requireCurrentExecution as Ln}from"./broker-recovery.js";import{readOutputRequest as Mn}from"../../../core/runtime/output-result.js";import{writeYieldMessage as jn,readGoal as Fn,captureGoalIfAbsent as Gn}from"../../../core/runtime/kickoff.js";import{ensureRoadmap as xn,hasRoadmap as Bn}from"../../../core/runtime/roadmap.js";import{renameWindow as Wn}from"../../../core/runtime/placement.js";import{buildLaunchSpecAsync as Un,explicitModelIntent as Vn,normalizeModel as Kn,readMergedLaunchConfigAsync as ge}from"../../../core/runtime/launch.js";import{modelRequestFromConfig as Jn}from"../../../core/model-routes.js";import{persistDormantModel as zn,setModelLive as Hn}from"../../../core/runtime/model-swap.js";import{waitForBrokerViewSocket as be}from"../../../core/runtime/view-socket.js";import{viewTransport as Yn}from"../../runs/observer.js";import{BrokerUnreachableError as Qn}from"../../../core/runtime/broker-request.js";import{boundFleet as M}from"../../../core/runtime/fleet.js";import{admitLegacyStructuredOutput as Xn}from"../../structured-requests/sidecar.js";import{assertOutputSchemaAccepted as Zn}from"../../../core/runtime/structured-output.js";import{OUTCOME_PAYLOAD_MAX_BYTES as ve}from"../../../core/canvas/types.js";import{HUMAN_ACTION_NAME_PATTERN as qn}from"../../../core/human/action-binding.js";import{resolveHumanAction as et}from"../../../core/human-actions.js";import{parseDurationMs as nt}from"../../../core/wake.js";import{claimWarmNode as tt,refillWarmPool as ke,resumeWarmClaim as it,warmPoolEnabled as rt}from"../../../core/runtime/warm-pool.js";import{assertLaunchKind as H,isLaunchKind as ot,resolveLaunchTarget as at}from"../../../core/runtime/launch-target.js";import{fullName as dt}from"../../../core/canvas/labels.js";import{reportsForNode as Se}from"./reports.js";import{requireUsableProfile as st}from"./profiles.js";import{assertProfileActive as lt,isProfilePaused as ct,loadExactProfileManifest as ut}from"../../../core/profiles/manifest.js";import{MachineOfflineError as ft}from"../../../core/runtime/runner/machine/ops.js";import{asNodePerson as pt}from"../../reconcilers/node-lifecycle/node-person.js";import{getCron as Y}from"../../../core/canvas/crons.js";import{cronWakeOrigin as mt}from"../../../core/runtime/bearings.js";import{boundDaemonControl as wt}from"../../control.js";import{notFound as N,usage as y}from"../../../core/errors.js";import{assertScope as ht,validateScopes as Ie}from"../../../core/scopes.js";import{scopeAllowed as E}from"../../../shared/env.js";import{toCloseResultDTO as yt,toNodeDetailDTO as Q,toNodeSummaryDTO as _t,toReviveResultDTO as gt}from"../map.js";import{ApiError as p}from"../../../api/index.js";import{InputError as w}from"../../../core/io.js";import{endExecution as bt,liveExecutionForNode as X,requestExecutionStop as vt}from"../../../core/canvas/executions.js";import{runnerForExecution as kt}from"../../../core/runtime/runner/index.js";import{wakeResident as St}from"../../reconcilers/node-lifecycle/remote-wake.js";import{isNowEligibleFault as It}from"../../../core/canvas/status-glyph.js";import{remoteEnvironmentOf as Re}from"../../../core/runtime/blaxel-environment.js";import{machineEnvironmentOfProfile as Rt}from"../../../core/runtime/runner/machine/environment.js";import{isCloudRole as Et}from"../../../core/canvas/person-state.js";import{actsAsPerson as j,canReadNode as C,mayOnNode as Ot,readableNodeIds as Ct,resolvedScopes as At}from"../router.js";import{forwardVerb as $t,queryWithoutMachine as Tt,relayError as Nt,unknownError as Pt,withMachine as Dt}from"../../peer/forward.js";import{fileRoot as Lt}from"../../../core/spaces/file-root.js";import{activeGrant as Mt,payerOfGrant as jt}from"../../../core/grants/mirror.js";import{launchUsesHostedEndpoint as Ft}from"../../../core/model-auth/readiness.js";import{nodeTerminalGrant as Gt}from"../../../core/grants/terminal.js";import{appRungForGrant as xt}from"../../../core/llm/app-rungs.js";import{APP_FAMILY as Bt}from"../../../core/model-routes.js";import{listProfileEnvNames as Wt}from"../../../core/profiles/env-store.js";import{hasConfiguredProviderCredential as Ut,NO_PROVIDER_CREDENTIAL_MESSAGE as Ee}from"../../../core/runtime/provider-credential-gate.js";import{filterAsync as Vt,mapAsync as Oe}from"../../../core/async-array.js";import{addStepTiming as Kt,collectStepTimings as Jt,serverTimingHeader as zt,sinceCollectionStart as Ht,timedStep as Yt}from"../../../core/step-timings.js";async function h(e){const n=await b(e);if(n===null)throw N(`unknown node: ${e}`,{received:e});return n}d(h,"requireMeta");async function Z(e){return{subscribesTo:await he(e),subscribers:await tn(e),children:await Xe(e)}}d(Z,"edgesFor");async function v(e){const n=await h(e);return await Q(n,await Z(e))}d(v,"detailOf");async function Qt(e){let n=(await Se(e)).length;try{n+=vn(await J(e),await ye(e)).length}catch(t){if(!gn(t))throw t}return n}d(Qt,"countFiles");function Xt(e){if(typeof e!="object"||e===null)throw y("a node create requires a JSON body");const n=e;if(n.kind!==void 0&&(typeof n.kind!="string"||n.kind.trim()===""))throw y("kind must be a non-empty string when provided");if(n.description!==void 0&&(typeof n.description!="string"||n.description.trim()===""))throw y("description must be a non-empty string when provided");if(n.creator!==void 0&&(typeof n.creator!="string"||n.creator.trim()===""))throw y("creator must be a non-empty node id when provided");if(n.scopes!==void 0&&Ie(n.scopes),n.isolated!==void 0&&typeof n.isolated!="boolean")throw new p(400,"invalid_request","isolated must be a boolean",{param:"isolated"});if(n.start!==void 0&&typeof n.start!="boolean")throw new p(400,"invalid_request","start must be a boolean",{param:"start"});const t=n.root_lifecycle;if(t!==void 0&&t!=="resident"&&t!=="terminal")throw y("root_lifecycle must be 'resident' or 'terminal'");if(n.request_key!==void 0&&(typeof n.request_key!="string"||n.request_key.trim()===""||n.request_key.length>128))throw y("request_key must be a non-empty string of at most 128 characters when provided");return n}d(Xt,"parseCreateBody");function Zt(e){if(e===void 0)return;const n=nt(e),t=n===null?null:new Date(Date.now()+n);if(n===null||!Number.isFinite(n)||n<=0||t===null||!Number.isFinite(t.getTime()))throw new p(422,"invalid_deadline","`deadline` must be a positive representable duration");return t.toISOString()}d(Zt,"parseDeadline");function qt(e){if(e!==void 0){if(typeof e!="object"||e===null||Array.isArray(e))throw new p(400,"invalid_request","`outcome_delivery` must be an object");if(typeof e.action!="string"||!qn.test(e.action))throw new p(400,"invalid_request","`outcome_delivery.action` must be a declared action name");if(e.payload!==void 0){let n;try{n=JSON.stringify(e.payload)}catch{throw new p(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable")}if(n===void 0)throw new p(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable");if(Buffer.byteLength(n,"utf8")>ve)throw new p(413,"payload_too_large",`serialized payload exceeds ${ve} bytes`)}return e}}d(qt,"parseOutcomeDelivery");function ei(e,n){const t=et(e.action,n);if(!("kind"in t))return{actionName:e.action,argv:t.argv,cwd:t.cwd,configOrigin:t.configOrigin,...e.payload===void 0?{}:{payload:e.payload}};throw t.kind==="unknown_action"?new p(422,"unknown_action",`no action named ${e.action} is declared from ${n}`):new p(422,"invalid_action",`${e.action} is declared in ${t.configOrigin} but unusable: ${t.reason}`,{reason:t.reason,configOrigin:t.configOrigin})}d(ei,"resolveOutcomeDelivery");function ni(e,n,t){const r={kind:e.kind,cwd:t,prompt:e.prompt??""};return e.mode!==void 0&&(r.mode=e.mode),e.name!==void 0&&(r.name=e.name),e.description!==void 0&&(r.description=e.description),n!==void 0&&(r.parent=n),e.creator!==void 0&&(r.creator=e.creator),e.scopes!==void 0&&(r.scopes=e.scopes),e.isolated!==void 0&&(r.isolated=e.isolated),e.root===!0&&(r.root=!0),e.start===!0&&(r.start=!0),e.root_lifecycle!==void 0&&(r.rootLifecycle=e.root_lifecycle),(e.worktree===!0||typeof e.worktree=="string")&&(r.worktree=!0),typeof e.worktree=="string"&&(r.worktreeBase=e.worktree),e.worktree!==void 0&&(r.worktreeCwd=L(e.pin_cwd??e.cwd??t)),e.fork_from!==void 0&&(r.forkFrom=e.fork_from),e.model!==void 0&&(r.model=e.model),e.profile!==void 0&&(r.profile=e.profile),e.situational_context!==void 0&&(r.situationalContext=e.situational_context),e.node_id!==void 0&&(r.nodeId=e.node_id),r}d(ni,"buildRecipe");function ti(e,n,t){return!rt()||e.prefer_warm!==!0||e.root!==!0||e.parent!=null||e.root_lifecycle==="terminal"||(e.prompt??"")!==""||e.model!==void 0||e.fork_from!==void 0||e.worktree!==void 0||e.node_id!==void 0||e.scopes!==void 0||e.isolated!==void 0?null:{kind:e.kind,mode:e.mode??"base",cwd:n,profileId:t,model:e.model??null,situationalContext:e.situational_context??null,name:e.name??null,creator:e.creator??null}}d(ti,"warmRequestFor");import{resolveCreateKind as Ro}from"../../../core/runtime/launch-target.js";function Ce(e){const n=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return Jn(e.model,n,e.modelExact===!0)}d(Ce,"requestFromLaunch");function ii(e,n){if(n===null)return e;if(e.scopes===void 0)return{...e,scopes:[...n]};const t=e.scopes.filter(r=>!E(n,r));if(t.length===0)return e;throw new p(403,"scope_denied",`scopes exceed the bearer token's ceiling: ${t.join(", ")}`,{scopes:t,ceiling:n})}d(ii,"withinCeiling");async function Ae(e,n,t){const r=(await Un(n.kind,n.mode,{lifecycle:n.lifecycle,hasManager:e.parent!==null,model:n.model,modelOverride:!0,cwd:e.cwd,profileId:e.profile_id??null,app:e.grantee??"app:terminal"})).launch;await V(Ce(r),{cwd:e.cwd,profileId:e.profile_id??null},t)}d(Ae,"assertNodeModelChangeRegistered");async function ri(e){if(!Et()||e.app!=="app:terminal")return!1;const n=e.class==="broker"?(await b(e.node))?.profile_id??null:e.cron===null?null:(await Y(e.cron))?.profile??null;return n!==null&&await Rt(n)!==null}d(ri,"callerRunsOnMachine");async function $e(e,n){const t=e.principal;if(t.class!=="broker"&&t.class!=="cron"||await ri(t))return;const r=Lt({app:t.app,resolved:await At(t),launched:t.scopes},n,"read");if("root"in r)return;const i="missing"in r?r.missing:null;throw new p(403,"scope_missing",i?`the child's directory ${n} needs missing scope ${i}`:`no permission of this run names the child's directory ${n}`,void 0,void 0,i?{scope:i}:void 0)}d($e,"assertCallerReaches");const q=new Map;async function oi(e,n={},t={}){const r=performance.now(),{value:i,steps:a}=await Jt(()=>ai(e,n,t));return a.push(["total",performance.now()-r]),{...i,headers:{...i.headers??{},"server-timing":zt(a)}}}d(oi,"handleCreate");async function ai(e,n,t){const r=ii(Xt(e.body),e.ceiling);if(e.principal.class==="broker"){const s=e.principal;if(r.prefer_warm===!0&&s.app!=="app:terminal"&&(r.prefer_warm=!1),r.parent!=null){const o=await h(r.parent);if(o.grantee!==s.app)throw new p(403,"other_app_run","cannot create a child under another app's node");if(!await C(s,o.grantee??"app:terminal",r.parent))throw N(`unknown node: ${r.parent}`,{received:r.parent})}if(r.creator!==void 0&&r.creator!==s.node)throw new p(403,"other_app_run","cannot create for another node");if(r.fork_from!==void 0){let o=null;try{o=await le(await se(r.fork_from))}catch{}if(o?.grantee!==s.app||!await C(s,o.grantee,o.node_id))throw new p(403,"other_app_run","cannot fork another app's conversation")}r.creator=s.node}if(e.principal.class==="person"&&e.principal.sub!==void 0){const s=r.fork_from===void 0?null:await le(await se(r.fork_from)).catch(()=>null);for(const o of[r.parent,r.creator,s?.node_id])if(o!=null&&await b(o)!==null&&!await Ot(e.principal,"edit",o))throw N(`unknown node: ${o}`,{received:o})}if(e.principal.class==="cron"){const s=e.principal;for(const l of["parent","creator","fork_from","node_id"])if(r[l]!=null)throw new p(403,"permission_error",`a cron cannot set ${l} on a node it starts`);r.prefer_warm=!1,r.node_id=await ce(),s.isolated&&(r.isolated=!0,r.cwd=await J(r.node_id,s.app));const o=await wn({grantee:s.app,sub:s.sub,grant_id:s.grant,scopes:s.scopes,from_exec:s.from_exec},{profile:r.profile,cwd:r.cwd,pin_cwd:r.pin_cwd,kind:r.kind,model:r.model,mode:r.mode});if(!o.allowed)throw hn(o);if(r.scopes!==void 0){const l=r.scopes.find(m=>!E(o.effectiveScopes,m)||!E(s.scopes,m));if(l!==void 0)throw new p(403,"scope_missing",`scope ${l} is not held by this cron`,void 0,void 0,{scope:l})}else o.scopes!==null&&(r.scopes=o.scopes)}r.creator!==void 0&&ht(await h(r.creator),"crtr:act");const i=r.request_key?.trim();if(i===void 0||r.node_id!==void 0&&mn(r.node_id)&&await b(r.node_id)!==null&&(await me(i))?.nodeId!==r.node_id)return F(e,r,n,t);const a=q.get(i);if(a!==void 0)return a;const c=di(e,r,i,n,t);q.set(i,c);try{return await c}finally{q.delete(i)}}d(ai,"createWithinTimings");const Te=`${process.pid}:${Fe()}`,ee="create_request_in_progress";async function Ne(e,n,t){const r=Date.now()+9e4;let i=Date.now()+1e4;for(;t!==null;){const a=await b(t);if(a!==null){if(!j(e.principal)&&!await C(e.principal,a.grantee??"app:terminal",t))throw new p(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:await v(t)}}if(await Ye(n)&&(i=Math.min(r,Date.now()+1e3)),Date.now()>=i||(await me(n))?.nodeId!==t)break;await new Promise(c=>setTimeout(c,100))}throw new p(409,ee,"another create with this request_key is in progress; retry it")}d(Ne,"awaitForeignCreate");async function di(e,n,t,r,i){const a=await we(t),c=Te;if(a.nodeId!==null&&a.state==="reserved"&&await b(a.nodeId)===null&&!await fe(t,a.nodeId,c))try{return await Ne(e,t,a.nodeId)}catch(o){if(!(o instanceof p)||o.code!==ee||!await fe(t,a.nodeId,c))throw o}const s=setInterval(()=>{Qe(t,c).catch(()=>{})},He);try{return await si(e,n,t,r,i,a)}finally{clearInterval(s)}}d(di,"handleKeyedCreateRequest");async function si(e,n,t,r,i,a){if(a.nodeId!==null&&await b(a.nodeId)!==null){if(a.state!=="warm_claimed"){const c=await b(a.nodeId);if(!j(e.principal)&&!await C(e.principal,c.grantee??"app:terminal",a.nodeId))throw new p(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:await v(a.nodeId)}}return F(e,n,r,i,a)}try{return await F(e,n,r,i,a)}catch(c){if(c instanceof p&&c.code===ee)throw c;const s=await we(t);throw(s.nodeId===null||await b(s.nodeId)===null)&&await ue(t,s.nodeId),c}}d(si,"keyedCreateOwned");async function F(e,n,t,r,i=void 0){const a=r.deadlineAt??Zt(n.deadline),c=qt(n.outcome_delivery),s=e.principal.class==="cron"?await yn({grantee:e.principal.app,sub:e.principal.sub,grant_id:e.principal.grant,scopes:e.principal.scopes,cron_id:e.principal.cron,origin_run_id:e.principal.origin_run,isolated:e.principal.isolated,creator:e.principal.kind==="exec"?null:(await Y(e.principal.cron))?.created_by??null},n.node_id):null;s!==null&&(n.root=s.root===!0);const o=s?.parent??n.parent??void 0;if(o==null&&n.root!==!0)throw y("a node create requires a parent (or root: true for an independent root)");let l=null;if(n.output_schema!==void 0){try{l=JSON.parse(n.output_schema)}catch{throw y("output_schema must be a JSON schema string")}if(l===null||typeof l!="object"||Array.isArray(l))throw y("output_schema must be a JSON schema object");await Zn(l)}const m=await at(n,{validateKind:Me,...e.principal.class==="broker"||e.principal.class==="cron"?{app:e.principal.app}:{}}),{profileId:f,kind:u,cwd:_,launch:I}=m;if(n.pin_cwd!==void 0&&n.pin_cwd!==""&&n.worktree===void 0&&n.isolated!==!0&&!$(_)&&await Re(f)===null)throw new w({error:"cwd_missing",message:`cwd is not an existing directory: ${_}`,received:_,field:"cwd",next:"Pass an existing directory with --cwd."});await $e(e,_),n.worktree!==void 0&&await $e(e,L(n.pin_cwd??n.cwd??_));const k={...n,kind:u},P=c===void 0?void 0:ei(c,_),te=("grant"in e.principal?e.principal.grant:null)??(o==null?null:(await b(o))?.grant_id??null);if(await V(Ce(await Ke(I,te,n.model)),{cwd:_,profileId:f},t.modelRegistry),await jt(te)!=="app"&&!await Ut(f===null?[]:await Wt(f))&&!await Ft(m))throw new p(412,"no_provider_credential",Ee,{error:"no_provider_credential",message:Ee,next:"The person running this runtime logs a provider in with `crtr sys setup`, or stores a provider key on the profile."});let x=null;{const ie=i===void 0||i.nodeId===null||i.state==="warm_claimed"?ti(k,_,f):null,O=ie!==null&&!(n.start===!0&&await Re(f)!==null)?ie:null,B=l===null&&r.beforeBrokerLaunch===void 0?void 0:async g=>{l!==null&&await Xn(g,"terminal",l),r.beforeBrokerLaunch?.(g)};if(i?.state==="warm_claimed"&&i.nodeId!==null){const g=O===null?null:await it(O,i.nodeId,B);if(g===null)throw await ue(i.requestKey,i.nodeId),new p(503,"create_resume_failed",`could not resume warm claim ${i.nodeId}; retry the create`);return await pe(i.requestKey,g),{status:201,body:await v(g)}}if(O!==null){const g=await tt(O,{...a===void 0?{}:{deadlineAt:a},...P===void 0?{}:{outcomeDelivery:P},...i===void 0?{}:{requestKey:i.requestKey}},B);if(g!==null)return i!==void 0&&await pe(i.requestKey,g),ke(O),{status:201,body:await v(g)};x=O}const D=i?.nodeId??n.node_id??(i===void 0?void 0:await ce());if(i!==void 0&&i.nodeId===null){const g=await qe(i.requestKey,D,Te);if(g!==D)return await Ne(e,i.requestKey,g)}const R=ni(D===void 0?k:{...k,node_id:D},o,_);s!==null&&(s.rootLifecycle!==void 0&&(R.rootLifecycle=s.rootLifecycle),s.scopes!==void 0&&k.scopes===void 0&&(R.scopes=s.scopes),s.run!==void 0&&(R.run=s.run),s.withinCreate!==void 0&&(R.withinCreate=s.withinCreate)),a!==void 0&&(R.deadlineAt=a),P!==void 0&&(R.outcomeDelivery=P),R.readiness=n.root===!0?"await":"launch",Kt("handler_checks",Ht());const re=await ze(R,B,()=>{x!==null&&ke(x)});return i!==void 0&&await Ze(i.requestKey,re.node.node_id),{status:201,body:await Yt("response_detail",()=>v(re.node.node_id))}}}d(F,"handleCreateRequest");function S(e,n){const t=e.query.getAll(n);if(t.length>1)throw y(`${n} must appear at most once`);return t[0]}d(S,"singleQueryValue");function ne(e,n){if(e!==void 0){if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1;throw y(`${n} must be true or false`)}}d(ne,"optionalBoolean");function G(e,n,t){if(e!==void 0){if(t.includes(e))return e;throw y(`${n} must be one of: ${t.join(", ")}`)}}d(G,"oneOf");function li(e){const n=new Set(["status","lifecycle","kind","mode","profile_id","profile_prefix","parent","top_level","under","under_inclusive","hanging","include"]);for(const[I]of e.query)if(!n.has(I))throw y(`unknown nodes query parameter: ${I}`);const t=G(S(e,"status"),"status",["active","idle","done","dead","canceled"]),r=G(S(e,"lifecycle"),"lifecycle",["terminal","resident"]),i=S(e,"kind"),a=G(S(e,"mode"),"mode",["base","orchestrator"]),c=S(e,"profile_id"),s=S(e,"profile_prefix"),o=S(e,"parent"),l=ne(S(e,"top_level"),"top_level"),m=S(e,"under"),f=ne(S(e,"under_inclusive"),"under_inclusive"),u=ne(S(e,"hanging"),"hanging"),_=G(S(e,"include"),"include",["activity"]);if(o!==void 0&&l===!0)throw y("parent and top_level=true cannot be combined");return{...t!==void 0?{status:t}:{},...r!==void 0?{lifecycle:r}:{},...i!==void 0?{kind:i}:{},...a!==void 0?{mode:a}:{},...c!==void 0?{profile_id:c}:{},...s!==void 0?{profile_prefix:s}:{},...o!==void 0?{parent:o}:{},...l!==void 0?{top_level:l}:{},...m!==void 0?{under:m}:{},...f!==void 0?{under_inclusive:f}:{},...u!==void 0?{hanging:u}:{},..._!==void 0?{include:_}:{}}}d(li,"parseListQuery");async function ci(e){const n=li(e);let t=await en({...n.status!==void 0?{status:n.status}:{},...n.lifecycle!==void 0?{lifecycle:n.lifecycle}:{},...n.kind!==void 0?{kind:n.kind}:{},...n.mode!==void 0?{mode:n.mode}:{},...n.profile_id!==void 0?{profileId:n.profile_id}:{},...n.profile_prefix!==void 0?{profilePrefix:n.profile_prefix}:{},...n.parent!==void 0?{parent:n.parent}:{},...n.top_level===!0?{topLevel:!0}:{},...n.under!==void 0?{under:n.under}:{},...n.under_inclusive===!0?{underInclusive:!0}:{},...n.hanging===!0?{hanging:!0}:{}});const r=await Ct(e.principal);r!==null&&(t=t.filter(o=>r.has(o.node_id)));const i=n.include==="activity"?await pn(t.map(o=>o.node_id)):null,a=t.length>0?xe():new Set,c=new Map((await on()).map(o=>[o.nodeId,o.controllerId]));return{status:200,body:await Oe(t,async o=>{const l=await _t(o,o.profile_id!==null&&a.has(o.profile_id),c.get(o.node_id)??null);if(i!==null){const m=await Se(o.node_id);l.activity={latest_report:m[0]??null,final_report:o.final_report===null?null:m.find(f=>f.name===o.final_report)??null,pending_human_count:i[o.node_id]??0}}return l})}}d(ci,"handleList");async function ui(e){const n=e.params.id,t=await $t(e,n,{method:"GET",path:`/v1/nodes/${encodeURIComponent(n)}`,query:Tt(e)});if(t.kind==="unknown")throw Pt(n,t.unreachable);if(t.kind==="remote"){if(t.status>=400)throw Nt(t.status,t.body);return{status:t.status,body:Dt(t.body,t.machine)}}return await h(n),{status:200,body:await v(n)}}d(ui,"handleDetail");async function fi(e){const n=e.params.id;await h(n);const t=await In(n),{start:r}=On(t.snapshot.messages,s=>JSON.stringify(_e(s,n)).length),i=t.snapshot.messages.slice(r).map(s=>_e(s,n)),a=En(i);return{status:200,body:{node_id:n,snapshot:{messages:i,...t.snapshot.messageIds===void 0?{}:{messageIds:t.snapshot.messageIds.slice(r)},messageVisibility:t.snapshot.messageVisibility.slice(r),turnVisibility:t.snapshot.turnVisibility,stats:t.snapshot.stats,state:t.snapshot.state,display:t.snapshot.display,...t.snapshot.queued===void 0?{}:{queued:t.snapshot.queued},...t.snapshot.toolGroupSummaries===void 0?{}:{toolGroupSummaries:Object.fromEntries(Object.entries(t.snapshot.toolGroupSummaries).filter(([s])=>a.has(s)))},...t.snapshot.turnReplies===void 0?{}:{turnReplies:t.snapshot.turnReplies},...t.snapshot.workingActivity===void 0?{}:{workingActivity:t.snapshot.workingActivity}},commands:t.commands.map(s=>({name:s.name,description:s.description,source:s.source})),captured_at:U()}}}d(fi,"handleSnapshot");async function pi(e){const n=e.params.id,t=await Cn(n);if(t===null)throw N(`unknown node: ${n}`,{received:n});return{status:200,body:t}}d(pi,"handleSubject");function mi(e){for(const[a]of e.query)if(a!=="cursor"&&a!=="limit")throw y(`unknown messages query parameter: ${a}`);const n=e.query.getAll("cursor"),t=e.query.getAll("limit");if(n.length>1)throw y("cursor must appear at most once");if(t.length>1)throw y("limit must appear at most once");if(t.length===0)return n.length===0?{}:{cursor:n[0]};const r=t[0],i=Number(r);if(!Number.isSafeInteger(i)||r==="")throw y("limit must be an integer from 1 through 500");return n.length===0?{limit:i}:{cursor:n[0],limit:i}}d(mi,"parseMessagesQuery");async function wi(e){const n=e.params.id,t=await kn(n,mi(e));return{status:200,body:{node_id:n,messages:t.messages,...t.messageIds===void 0?{}:{message_ids:t.messageIds},message_visibility:t.messageVisibility,next_cursor:t.nextCursor,captured_at:U()}}}d(wi,"handleMessages");async function hi(e){const n=e.params.id;await h(n);const t=await Sn(n);return{status:200,body:{node_id:n,session_file:t.sessionFile,session_jsonl:t.sessionJsonl,system_prompt:t.systemPrompt,captured_at:U()}}}d(hi,"handleSession");async function yi(e){const n=e.params.id;return await h(n),{status:200,body:{node_id:n,markdown:await Rn(n)}}}d(yi,"handleTranscript");async function _i(e){const n=e.params.id;await h(n);const t=d(async(i,a)=>({node_id:i,label:(await b(i))?.name??i,dir:await ye(i),self:a,files:await Qt(i)}),"root"),r=await Vt([await t(n,!0),...await Oe(await he(n),async i=>await t(i.node_id,!1))],async i=>await gi(i.node_id,i.dir)||i.files>0);return{status:200,body:{node_id:n,roots:r}}}d(_i,"handleContext");async function gi(e,n){try{return _n(await J(e),n)}catch(t){if(bn(t))return!1;throw t}}d(gi,"hasDir");async function bi(e){const n=await h(e.params.id),t=e.principal.class==="broker"?e.principal.scopes:e.ceiling,r=t===null?void 0:n.scopes==null?[...t]:[...new Set([...n.scopes.filter(a=>E(t,a)),...t.filter(a=>E(n.scopes,a))])],i=await Je(n.node_id,r,e.principal.class==="broker"?e.principal.node:void 0);return{status:201,body:await v(i.node.node_id)}}d(bi,"handleFork");const vi=1e4;async function ki(e){const n=e.params.id,t=await h(n),r=await X(n);if(r===null||r.runner!=="machine")throw new w({error:"not_hanging",message:`${n} has no live broker on a Mac \u2014 nothing to kick here.`,next:`Use \`crtr node lifecycle revive ${n} --now\` from the CLI, which kicks a local broker directly.`});if(!It(t.fault??null))throw new w({error:"not_hanging",message:`${n} is live but has no pi\u2192provider fault eligible for --now.`,next:"Use --now only on a node the canvas shows as hanging (\u26A0) with a `pi\u2192provider` fault."});if(t.streaming===!0)throw new w({error:"busy",message:`${n} is mid-turn right now (busy) \u2014 refusing to stop a working engine.`,next:"Re-check the canvas \u2014 if it is no longer marked hanging (\u26A0), nothing to do."});await vt(n,{afterTurn:!1,reason:"revive_now"});const i=await kt("machine").stop(r,{reason:"revive_now"});if(!i.confirmed)throw i.error??new Error(`stop of ${n} on its Mac was not confirmed`);return await bt(r.executionId,{reason:"revive_now"}),await de(n,{resume:!0,capacity:"refuse"}),{status:200,body:{kicked:!0}}}d(ki,"handleKick");async function Si(e){const n=e.params.id,t=await h(n),r=e.body,i=r?.resume??!0,a=r?.reopen??!1;Ve(n,t),await Dn(n,a,e.principal.class==="broker"?e.principal.node:null);const c=!i&&r?.cron_id!==void 0?await Y(r.cron_id):null,s=await X(n);if(i&&s!==null&&s.runner!=="process"&&s.state==="running"&&!ct(t.profile_id))try{await pt({node_id:n,sub:t.sub??null,profile_id:t.profile_id??null},()=>St(s))}catch(u){if(!(u instanceof ft))throw u}const o=await de(n,{resume:i,capacity:"refuse",...c!==null?{wakeReason:await mt(c,"schedule_revive")}:{}});o.outcome!=="already-live"&&await nn(n,{failures:0,notBefore:null});const l=(await b(n))?.status??"active",m=(o.launch??M().get(n)?.handle)?.exited,f=o.outcome!=="frozen"&&await be(n,m,vi);return{status:200,body:gt(n,o,l,f)}}d(Si,"handleRevive");async function Ii(e){const n=e.params.id;return{status:200,body:{newNodeId:(await Pn(n))?.newNodeId??null}}}d(Ii,"handleRelaunchRoot");async function Ri(e){const n=e.params.id;await h(n);const t=e.body;if(t?.caller_pid!==void 0&&(!Number.isInteger(t.caller_pid)||t.caller_pid<=0))throw y("caller_pid must be a positive integer when provided");const r=wt(),i=new Promise(c=>{e.res.once("close",()=>c())}),a=await Ue(n,{teardownAfter:i,rootEvent:t?.finish===!0?"finish":"cancel",callerPid:t?.caller_pid,...e.principal.class==="broker"?{closer:e.principal.node}:{},...r===null?{}:{registerDetached:r.registerDetached}});return{status:200,body:yt(a)}}d(Ri,"handleClose");async function Ei(e){if(!j(e.principal))throw new p(403,"permission_error","only the person marks a conversation read");const n=e.params.id;return await h(n),await an(n),{status:204}}d(Ei,"handleMarkRead");async function Oi(e){const n=e.params.id;await h(n);const t=await Nn(n);return{status:200,body:{recycled:t.recycled,finalized:t.finalized,new_root:t.newRoot,delivered:t.delivered}}}d(Oi,"handleRecycle");async function Ci(e){const n=e.params.id;return await h(n),await z(n,{lifecycle:"terminal"}),await A(e,n,["lifecycle"]),{status:200,body:await v(n)}}d(Ci,"handleDemote");async function Ai(e,n={}){const t=e.params.id,r=await h(t),i=e.body??{};i.kind!==void 0&&await H(i.kind,r.cwd,r.profile_id??null),i.model!==void 0&&await Ae(r,{kind:i.kind??r.kind,mode:"orchestrator",lifecycle:i.resident===!0?"resident":r.lifecycle,model:i.model},n.modelRegistry);const a=await $n(t,{...i.kind!==void 0?{kind:i.kind}:{},...i.resident===!0?{resident:!0}:{},...i.model!==void 0?{model:i.model}:{}});await A(e,t,["mode",...i.kind!==void 0?["kind"]:[],...i.resident===!0?["lifecycle"]:[],...i.model!==void 0?["model"]:[]]);const c=await Q(a.meta,await Z(t));return c.roadmap_written=a.roadmapWritten,c.roadmap_ref=a.roadmapRef,c.goal_path=a.goalPath,{status:200,body:c}}d(Ai,"handlePromote");async function $i(e){const n=e.params.id;return await h(n),{status:200,body:{request:await Mn(n)}}}d($i,"handleBrokerStructuredRequest");async function Ti(e){const n=e.params.id,t=e.body??{};if(await Ln(n,t.expected_execution_id),typeof t.text!="string")throw new p(400,"invalid_request","text must be a string");return await h(n),{status:200,body:{captured:await Gn(n,t.text)}}}d(Ti,"handleBrokerGoal");async function Ni(e,n={}){const t=e.params.id,r=await h(t),i=e.body??{};i.kind!==void 0&&await H(i.kind,r.cwd,r.profile_id??null),i.model!==void 0&&await Ae(r,{kind:i.kind??r.kind,mode:i.promote===!0?"orchestrator":r.mode,lifecycle:r.lifecycle,model:i.model},n.modelRegistry);const a=i.note??"Refresh: continue against your roadmap or goal.";await jn(t,a);const c=await Tn(t,{...i.promote===!0?{promote:!0}:{},...i.kind!==void 0?{kind:i.kind}:{},...i.model!==void 0?{model:i.model}:{}});return{status:200,body:await Q(c.meta,await Z(t))}}d(Ni,"handleYield");async function Pi(e){const n=e.params.id;await h(n);const t=e.body;if(t===void 0||typeof t.controller!="string"||t.controller.trim()==="")throw y("a wait requires a controller node id");const r=await b(t.controller);if(r===null)throw N(`unknown controller: ${t.controller}`,{received:t.controller});if(r.status!=="active"&&r.status!=="idle")throw new p(422,"unprocessable",`controller ${t.controller} is ${r.status}`);return await rn(n,t.controller),{status:200,body:await v(n)}}d(Pi,"handleWait");async function Di(e){const n=e.principal,t=await An(n.class==="broker"?async i=>i.grantee===n.app&&await C(n,i.grantee,i.node_id):n.class==="person"&&!j(n)?async i=>await C(n,i.grantee??"app:terminal",i.node_id):void 0);return{status:200,body:{revived:[...t.revived],failed:[...t.failed],frozen:[...t.frozen]}}}d(Di,"handleReviveAll");const Li=new Set(["interrupt","steer","after-turn","next-turn"]);function Mi(e){if(e===null)return null;const n=d(r=>{throw new w({error:"invalid_listen",message:r,received:e,field:"listen",next:'Send an object mapping levels "1".."10" to interrupt|steer|after-turn|next-turn (e.g. {"3":"next-turn"}), or null to reset to the global default.'})},"bad");if(typeof e!="object"||Array.isArray(e))return n("listen must be an object or null");const t=Object.entries(e);if(t.length===0)return n("listen must name at least one level");for(const[r,i]of t)/^(?:[1-9]|10)$/.test(r)||n(`listen level must be 1..10: ${r}`),(typeof i!="string"||!Li.has(i))&&n(`listen delivery must be interrupt|steer|after-turn|next-turn: ${String(i)}`);return JSON.stringify(Object.fromEntries(t))}d(Mi,"listenJson");async function A(e,n,t,r){t.length===0&&r===void 0||await K(async i=>{if(r?.(i),t.length===0)return;const a=await dn(i,n),c=await cn(i,e),s=c.class==="person"?c.person:c.class==="app"?c.app:c.node;await sn(i,s,a),await ln(i,{event:"configured",object:a,actor:s,attrs:{changed:t.join(",")}})})}d(A,"recordConfigured");function Pe(e){const n=M().get(e);if(n===void 0)return!1;try{return process.kill(n.pid,"SIGTERM"),!0}catch{return!1}}d(Pe,"restartLiveBroker");function De(e,n){try{return oe(e)===oe(n)}catch{return!1}}d(De,"sameDirectory");async function ji(e,n={}){const t=e.params.id,r=e.body;let i;if(r===void 0)i={};else if(typeof r=="object"&&r!==null&&!Array.isArray(r))i=r;else throw new w({error:"cwd_invalid",message:"cwd repair requires a non-null object with a non-empty cwd string",received:r,field:"cwd",next:"Send a config patch with a non-empty absolute cwd string."});if(i.profile!==void 0){if(typeof i.profile!="string"||i.profile==="")throw new w({error:"profile_invalid",message:"profile must be a non-empty profile id or name",received:i.profile,field:"profile",next:"Send a profile id or exact name."});if(Object.keys(i).some(f=>f!=="profile"&&f!=="restart"&&i[f]!==void 0))throw new w({error:"profile_not_exclusive",message:"profile can only be combined with restart",field:"profile",next:"Send profile (and optionally restart) alone."});const o=await h(t),l=await st(e,i.profile);lt(l.profileId);const m=ut(l.profileId).manifest.grantee??"app:terminal";if(m!==(o.grantee??"app:terminal"))throw new w({error:"profile_grantee_mismatch",message:`profile ${l.profileId} belongs to ${m}, node ${t} to ${o.grantee}`,received:i.profile,field:"profile",next:"Pick a profile owned by the same app as the node."});return(o.profile_id??null)!==l.profileId&&(ot(o.kind)?(await H(o.kind,o.cwd,l.profileId),await z(t,{profileId:l.profileId})):await T(t,{profile_id:l.profileId}),await A(e,t,["profile"])),i.restart===!0&&Pe(t),{status:200,body:await v(t)}}if(Object.prototype.hasOwnProperty.call(i,"cwd")){const o=i.cwd;if(typeof o!="string"||o==="")throw new w({error:"cwd_invalid",message:"cwd must be a non-empty string",received:o,field:"cwd",next:"Send a non-empty absolute cwd string."});if(Object.keys(i).some(u=>u!=="cwd"&&u!=="keep_session"&&u!=="restart"&&i[u]!==void 0))throw new w({error:"cwd_not_exclusive",message:"cwd repair cannot be combined with another config field",received:i,field:"cwd",next:"Send cwd as the only config field."});const l=await h(t),m=$(l.cwd);if(i.keep_session===!0||m&&W(o)&&$(o)&&De(l.cwd,o)){if(!W(o))throw new w({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${o}`,received:o,field:"cwd",next:"Send an absolute path."});const u=L(o);let _=!1;try{_=ae(u).isDirectory()}catch{}if(!_)throw new w({error:"cwd_missing",message:`cwd is not an existing directory: ${u}`,received:o,field:"cwd",next:"Send an existing absolute directory."});if(m&&!De(l.cwd,u))throw new w({error:"cwd_not_same_directory",message:`${u} is not the same directory as the recorded ${l.cwd}; --keep-session only relocates an alias`,received:o,field:"cwd",next:"Drop --keep-session to repair a gone cwd, or pass the real path of the recorded directory."});if(l.managed_worktree?.state==="open")throw new w({error:"cwd_node_managed_worktree_open",message:`${t} owns an open managed worktree and cannot relocate its cwd`,received:o,field:"cwd",next:"Reconcile the managed worktree first."});const I=l.cwd;return I!==u&&(await K(async k=>{await T(t,{cwd:u}),await k.prepare("UPDATE crons SET cwd = ? WHERE anchor_node = ? AND cwd = ?").run(u,t,I),await un(t,I,u)}),await A(e,t,["cwd"])),i.restart===!0&&Pe(t),{status:200,body:await v(t)}}if(await M().has(t)){const u=`${t} cannot repair its cwd while its broker is live`;throw new p(409,"cwd_node_live",u,{error:"cwd_node_live",message:u,received:o,field:"cwd",next:"Let the node become dormant, then retry the cwd repair."})}if(l.fork_from!=null)throw new w({error:"cwd_node_forked",message:`${t} is a fork and cannot repair its cwd; recorded cwd: ${l.cwd}`,received:o,field:"cwd",next:`Restore ${l.cwd}, then revive the fork normally.`});if(l.managed_worktree?.state==="open")throw new w({error:"cwd_node_managed_worktree_open",message:`${t} owns an open managed worktree and cannot repair its cwd`,received:o,field:"cwd",next:"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon flow."});if($(l.cwd))throw new w({error:"cwd_still_present",message:`${t} recorded cwd still exists: ${l.cwd}; cwd repair is not a relocation command`,received:o,field:"cwd",next:"This command only repairs a node whose recorded cwd is gone."});if(!W(o))throw new w({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${o}`,received:o,field:"cwd",next:"Send an absolute path."});const f=L(o);if(!$(f))throw new w({error:"cwd_missing",message:`cwd does not exist: ${f}`,received:o,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."});try{if(!ae(f).isDirectory())throw new w({error:"cwd_not_a_directory",message:`cwd is not a directory: ${f}`,received:o,field:"cwd",next:"Send an existing absolute directory."})}catch(u){throw u instanceof w?u:new w({error:"cwd_missing",message:`cwd does not exist: ${f}`,received:o,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."})}return await K(async()=>{await T(t,{cwd:f}),await fn(t)}),await A(e,t,["cwd"]),{status:200,body:await v(t)}}let a=await h(t);const c=i.listen===void 0?void 0:Mi(i.listen);if(i.scopes!==void 0){const o=Ie(i.scopes),l=a.grantee==="app:terminal"?await Gt(a):a.grant_id?await Mt(a.grant_id):null;if(!o.every(m=>E(a.scopes,m)&&l!==null&&E(l.resolved,m)))throw new w({error:"unknown_scope",message:"scopes may only narrow the node's current effective set",received:o,field:"scopes",next:"Send only scopes the node currently holds."});if(o.includes("crtr:act")&&!E(o,"crtr:llm"))throw new p(400,"invalid_scope","crtr:act requires crtr:llm");a=await T(t,{scopes:o})}if(i.situational_context!==void 0&&await Be(t,We(i.situational_context)),i.model!==void 0){const o=(await ge(a.cwd,a.profile_id??null,a.grantee??"app:terminal")).modelLadders,l=Vn(i.model,o),m=await xt(a.grant_id,i.model,l===void 0),f=m?{family:Bt,strength:m.strength}:l,u=m?m.model:Kn(i.model,o);await V({kind:"concrete",spec:u},{cwd:a.cwd,profileId:a.profile_id??null},n.modelRegistry);const _=M();let I=!1;if(await _.isClaimed(t)&&((await X(t))?.runner==="machine"||await be(t,_.get(t)?.handle.exited))&&(I=await Hn(t,u,f,await Yn(t)).then(()=>!0,k=>{if(k instanceof Qn)return!1;throw k})),!I){if(await _.isClaimed(t)){const k=`${t}'s broker did not accept the model switch; the model was not changed`;throw new p(409,"broker_not_ready",k,{error:"broker_not_ready",message:k,received:i.model,field:"model",next:"Check the node with `crtr node inspect show`, then retry the model change."})}if(!u.includes("/"))throw y(`model must resolve to a provider/id spec: ${i.model}`);await zn(t,u,f)}a=await h(t)}if(i.kind!==void 0||i.mode!==void 0||i.lifecycle!==void 0){i.kind!==void 0&&await Me(i.kind,a.grantee??"app:terminal");const o=i.kind??a.kind,l=i.mode??a.mode,m=i.lifecycle??a.lifecycle;let f;l==="orchestrator"&&!await Bn(t)&&(f=d(async()=>{const u=await Fn(t);await xn(t,u!==null&&u.trim()!==""?{goal:u.trim()}:{})},"beforePersist")),a=await z(t,{...i.kind!==void 0?{kind:o}:{},...i.mode!==void 0?{mode:l}:{},...i.lifecycle!==void 0?{lifecycle:m}:{}},f)}i.name!==void 0&&(a=await T(t,{name:i.name}),a.window&&Wn(a.window,dt(a)));const s=["scopes","situational_context","model","kind","mode","lifecycle","name","listen"].filter(o=>i[o]!==void 0);return await A(e,t,s,c===void 0?void 0:async o=>{await o.prepare("UPDATE objects SET listen_json = ? WHERE id = ? AND type = 'node'").run(c,t)}),{status:200,body:await v(t)}}d(ji,"handleConfig");async function Le(e="app:terminal"){return(await ge(process.cwd(),Ge()||null,e)).kinds}d(Le,"daemonKinds");async function Me(e,n="app:terminal"){const t=Object.keys(await Le(n));if(!t.includes(e))throw y(`unknown kind: ${e}`,{received:e,next:`Valid kinds: ${t.sort().join(", ")}.`})}d(Me,"assertKindServer");async function Fi(){const e=await Le();return{status:200,body:{kinds:Object.keys(e).sort().map(t=>({kind:t,when_to_use:e[t]?.whenToUse??null,available_to:e[t]?.availableTo??null}))}}}d(Fi,"handleListKinds");const ko=[{method:"POST",pattern:"/v1/nodes",scope:"crtr:act",handler:oi},{method:"GET",pattern:"/v1/nodes",handler:ci},{method:"GET",pattern:"/v1/kinds",handler:d(()=>Fi(),"handler")},{method:"POST",pattern:"/v1/nodes/revive-all",scope:"crtr:act",handler:Di},{method:"GET",pattern:"/v1/nodes/:id",handler:ui},{method:"GET",pattern:"/v1/nodes/:id/snapshot",handler:fi},{method:"GET",pattern:"/v1/nodes/:id/subject",handler:pi},{method:"GET",pattern:"/v1/nodes/:id/messages",handler:wi},{method:"GET",pattern:"/v1/nodes/:id/session",handler:hi},{method:"GET",pattern:"/v1/nodes/:id/transcript",handler:yi},{method:"GET",pattern:"/v1/nodes/:id/context",handler:_i},{method:"POST",pattern:"/v1/nodes/:id/fork",scope:"crtr:act",handler:bi},{method:"POST",pattern:"/v1/nodes/:id/revive",scope:"crtr:act",handler:Si},{method:"POST",pattern:"/v1/nodes/:id/kick",scope:"crtr:act",handler:ki},{method:"POST",pattern:"/v1/nodes/:id/relaunch-root",scope:"crtr:act",handler:Ii},{method:"POST",pattern:"/v1/nodes/:id/close",handler:Ri},{method:"POST",pattern:"/v1/nodes/:id/read",handler:Ei},{method:"POST",pattern:"/v1/nodes/:id/recycle",scope:"crtr:act",handler:Oi},{method:"POST",pattern:"/v1/nodes/:id/demote",scope:"crtr:act",handler:Ci},{method:"POST",pattern:"/v1/nodes/:id/promote",scope:"crtr:act",handler:Ai},{method:"POST",pattern:"/v1/nodes/:id/yield",scope:"crtr:act",handler:Ni},{method:"GET",pattern:"/v1/nodes/:id/broker/structured-request",handler:$i},{method:"POST",pattern:"/v1/nodes/:id/broker/goal",handler:Ti},{method:"POST",pattern:"/v1/nodes/:id/wait",handler:Pi},{method:"PATCH",pattern:"/v1/nodes/:id/config",handler:ji}];export{ji as handleConfig,oi as handleCreate,bi as handleFork,ci as handleList,Ai as handlePromote,Ni as handleYield,ko as nodeRoutes,Ro as resolveCreateKind};
1
+ var je=Object.defineProperty;var d=(e,n)=>je(e,"name",{value:n,configurable:!0});import{randomUUID as Fe}from"node:crypto";import{envProfileId as Ge}from"../../../shared/env.js";import{pausedCanvasProfiles as xe}from"../../../core/profiles/manifest.js";import{existsSync as $,realpathSync as oe,statSync as ae}from"node:fs";import{isAbsolute as W,resolve as L}from"node:path";import{appendSituationalContext as Be,formatSituationalProse as We}from"../../../core/runtime/situational-context.js";import{closeNode as Ue}from"../../../core/runtime/close.js";import{reviveNode as de}from"../../../core/runtime/revive.js";import{nowIso as U}from"../../../core/fs-utils.js";import{appPaidLaunch as Ve,assertLaunchModelRegistered as V,forkNode as Ke,resolveForkSource as se,spawnChildPrepared as Je}from"../../../core/runtime/spawn.js";import{forkSourceNode as le,newNodeId as ce}from"../../../core/runtime/nodes.js";import{abandonCreateRequest as ue,CREATE_LEASE_RENEW_MS as ze,claimCreateLease as fe,createLeaseLive as He,renewCreateLease as Ye,childrenOf as Qe,completeCreateRequest as pe,findCreateRequest as me,getNode as b,recordCreateRequestNode as Xe,reserveCreateRequest as we,reserveCreateRequestNode as Ze,listNodes as qe,recordRespawnAttempt as en,subscribersOf as nn,subscriptionsOf as he,updateNode as T}from"../../../core/canvas/canvas.js";import{armControllerWait as tn,liveControllerWaits as rn}from"../../../core/canvas/waits.js";import{withCanvasWrite as K}from"../../../core/canvas/db.js";import{markNodeRead as on}from"../../../core/canvas/recovery.js";import{nodeObject as an}from"../../../core/graph/objects.js";import{recordActedOn as dn}from"../../../core/graph/edges.js";import{publish as sn}from"../../../core/graph/events.js";import{readerFor as ln}from"../reader.js";import{relocateSessionCwd as cn,unbindSession as un}from"../../../core/canvas/sessions.js";import{ticketCountsForNodes as fn}from"../../../core/canvas/attention.js";import{isSafeNodeId as pn}from"../../../core/canvas/paths.js";import{contextDir as ye,nodeAgentDir as J}from"../../../core/canvas/node-agent-paths.js";import{checkCronBirth as mn,cronRefusalError as wn}from"../../cron/authority.js";import{cronBirthPlacement as hn}from"../../cron/armed-context.js";import{existsBeneath as yn,isAbsentOrRefused as _n,isBeneathRefusal as gn,readdirBeneath as bn}from"../../../core/spaces/open-beneath.js";import{readNodeMessagesPage as vn,readNodeSession as kn,readNodeSnapshot as Sn,transcriptMarkdown as In}from"../../../core/runtime/node-read.js";import{toolCallIds as Rn,withoutImages as _e}from"../../../core/runtime/broker-protocol.js";import{welcomeWindow as En}from"../../../core/runtime/session-cycles.js";import{assembleNodeSubject as On}from"../../../core/substrate/subject.js";import{reviveAll as An}from"../../../core/runtime/revive-all.js";import{promoteAsync as Cn,requestYieldAsync as $n,reshapeNodeAsync as z}from"../../../core/runtime/promote.js";import{recycleNode as Tn}from"../../../core/runtime/recycle.js";import{relaunchRoot as Nn}from"../../../core/runtime/reset.js";import{assertReopenGate as Pn}from"../../../core/runtime/reopen.js";import{requireCurrentExecution as Dn}from"./broker-recovery.js";import{readOutputRequest as Ln}from"../../../core/runtime/output-result.js";import{writeYieldMessage as Mn,readGoal as jn,captureGoalIfAbsent as Fn}from"../../../core/runtime/kickoff.js";import{ensureRoadmap as Gn,hasRoadmap as xn}from"../../../core/runtime/roadmap.js";import{renameWindow as Bn}from"../../../core/runtime/placement.js";import{buildLaunchSpecAsync as Wn,explicitModelIntent as Un,normalizeModel as Vn,readMergedLaunchConfigAsync as ge}from"../../../core/runtime/launch.js";import{modelRequestFromConfig as Kn}from"../../../core/model-routes.js";import{persistDormantModel as Jn,setModelLive as zn}from"../../../core/runtime/model-swap.js";import{waitForBrokerViewSocket as be}from"../../../core/runtime/view-socket.js";import{viewTransport as Hn}from"../../runs/observer.js";import{BrokerUnreachableError as Yn}from"../../../core/runtime/broker-request.js";import{boundFleet as M}from"../../../core/runtime/fleet.js";import{admitLegacyStructuredOutput as Qn}from"../../structured-requests/sidecar.js";import{assertOutputSchemaAccepted as Xn}from"../../../core/runtime/structured-output.js";import{OUTCOME_PAYLOAD_MAX_BYTES as ve}from"../../../core/canvas/types.js";import{HUMAN_ACTION_NAME_PATTERN as Zn}from"../../../core/human/action-binding.js";import{resolveHumanAction as qn}from"../../../core/human-actions.js";import{parseDurationMs as et}from"../../../core/wake.js";import{claimWarmNode as nt,refillWarmPool as ke,resumeWarmClaim as tt,warmPoolEnabled as it}from"../../../core/runtime/warm-pool.js";import{assertLaunchKind as H,isLaunchKind as rt,resolveLaunchTarget as ot}from"../../../core/runtime/launch-target.js";import{fullName as at}from"../../../core/canvas/labels.js";import{reportsForNode as Se}from"./reports.js";import{requireUsableProfile as dt}from"./profiles.js";import{assertProfileActive as st,isProfilePaused as lt,loadExactProfileManifest as ct}from"../../../core/profiles/manifest.js";import{MachineOfflineError as ut}from"../../../core/runtime/runner/machine/ops.js";import{asNodePerson as ft}from"../../reconcilers/node-lifecycle/node-person.js";import{getCron as Y}from"../../../core/canvas/crons.js";import{cronWakeOrigin as pt}from"../../../core/runtime/bearings.js";import{boundDaemonControl as mt}from"../../control.js";import{notFound as N,usage as y}from"../../../core/errors.js";import{assertScope as wt,validateScopes as Ie}from"../../../core/scopes.js";import{scopeAllowed as E}from"../../../shared/env.js";import{toCloseResultDTO as ht,toNodeDetailDTO as Q,toNodeSummaryDTO as yt,toReviveResultDTO as _t}from"../map.js";import{ApiError as p}from"../../../api/index.js";import{InputError as w}from"../../../core/io.js";import{endExecution as gt,liveExecutionForNode as X,requestExecutionStop as bt}from"../../../core/canvas/executions.js";import{runnerForExecution as vt}from"../../../core/runtime/runner/index.js";import{wakeResident as kt}from"../../reconcilers/node-lifecycle/remote-wake.js";import{isNowEligibleFault as St}from"../../../core/canvas/status-glyph.js";import{remoteEnvironmentOf as Re}from"../../../core/runtime/blaxel-environment.js";import{machineEnvironmentOfProfile as It}from"../../../core/runtime/runner/machine/environment.js";import{isCloudRole as Rt}from"../../../core/canvas/person-state.js";import{actsAsPerson as j,canReadNode as A,mayOnNode as Et,readableNodeIds as Ot,resolvedScopes as At}from"../router.js";import{forwardVerb as Ct,queryWithoutMachine as $t,relayError as Tt,unknownError as Nt,withMachine as Pt}from"../../peer/forward.js";import{fileRoot as Dt}from"../../../core/spaces/file-root.js";import{activeGrant as Lt,payerOfGrant as Mt}from"../../../core/grants/mirror.js";import{launchUsesHostedEndpoint as jt}from"../../../core/model-auth/readiness.js";import{nodeTerminalGrant as Ft}from"../../../core/grants/terminal.js";import{appRungForGrant as Gt}from"../../../core/llm/app-rungs.js";import{APP_FAMILY as xt}from"../../../core/model-routes.js";import{listProfileEnvNames as Bt}from"../../../core/profiles/env-store.js";import{hasConfiguredProviderCredential as Wt,NO_PROVIDER_CREDENTIAL_MESSAGE as Ee}from"../../../core/runtime/provider-credential-gate.js";import{filterAsync as Ut,mapAsync as Oe}from"../../../core/async-array.js";import{addStepTiming as Vt,collectStepTimings as Kt,serverTimingHeader as Jt,sinceCollectionStart as zt,timedStep as Ht}from"../../../core/step-timings.js";async function h(e){const n=await b(e);if(n===null)throw N(`unknown node: ${e}`,{received:e});return n}d(h,"requireMeta");async function Z(e){return{subscribesTo:await he(e),subscribers:await nn(e),children:await Qe(e)}}d(Z,"edgesFor");async function v(e){const n=await h(e);return await Q(n,await Z(e))}d(v,"detailOf");async function Yt(e){let n=(await Se(e)).length;try{n+=bn(await J(e),await ye(e)).length}catch(t){if(!_n(t))throw t}return n}d(Yt,"countFiles");function Qt(e){if(typeof e!="object"||e===null)throw y("a node create requires a JSON body");const n=e;if(n.kind!==void 0&&(typeof n.kind!="string"||n.kind.trim()===""))throw y("kind must be a non-empty string when provided");if(n.description!==void 0&&(typeof n.description!="string"||n.description.trim()===""))throw y("description must be a non-empty string when provided");if(n.creator!==void 0&&(typeof n.creator!="string"||n.creator.trim()===""))throw y("creator must be a non-empty node id when provided");if(n.scopes!==void 0&&Ie(n.scopes),n.isolated!==void 0&&typeof n.isolated!="boolean")throw new p(400,"invalid_request","isolated must be a boolean",{param:"isolated"});if(n.start!==void 0&&typeof n.start!="boolean")throw new p(400,"invalid_request","start must be a boolean",{param:"start"});const t=n.root_lifecycle;if(t!==void 0&&t!=="resident"&&t!=="terminal")throw y("root_lifecycle must be 'resident' or 'terminal'");if(n.request_key!==void 0&&(typeof n.request_key!="string"||n.request_key.trim()===""||n.request_key.length>128))throw y("request_key must be a non-empty string of at most 128 characters when provided");return n}d(Qt,"parseCreateBody");function Xt(e){if(e===void 0)return;const n=et(e),t=n===null?null:new Date(Date.now()+n);if(n===null||!Number.isFinite(n)||n<=0||t===null||!Number.isFinite(t.getTime()))throw new p(422,"invalid_deadline","`deadline` must be a positive representable duration");return t.toISOString()}d(Xt,"parseDeadline");function Zt(e){if(e!==void 0){if(typeof e!="object"||e===null||Array.isArray(e))throw new p(400,"invalid_request","`outcome_delivery` must be an object");if(typeof e.action!="string"||!Zn.test(e.action))throw new p(400,"invalid_request","`outcome_delivery.action` must be a declared action name");if(e.payload!==void 0){let n;try{n=JSON.stringify(e.payload)}catch{throw new p(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable")}if(n===void 0)throw new p(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable");if(Buffer.byteLength(n,"utf8")>ve)throw new p(413,"payload_too_large",`serialized payload exceeds ${ve} bytes`)}return e}}d(Zt,"parseOutcomeDelivery");function qt(e,n){const t=qn(e.action,n);if(!("kind"in t))return{actionName:e.action,argv:t.argv,cwd:t.cwd,configOrigin:t.configOrigin,...e.payload===void 0?{}:{payload:e.payload}};throw t.kind==="unknown_action"?new p(422,"unknown_action",`no action named ${e.action} is declared from ${n}`):new p(422,"invalid_action",`${e.action} is declared in ${t.configOrigin} but unusable: ${t.reason}`,{reason:t.reason,configOrigin:t.configOrigin})}d(qt,"resolveOutcomeDelivery");function ei(e,n,t){const r={kind:e.kind,cwd:t,prompt:e.prompt??""};return e.mode!==void 0&&(r.mode=e.mode),e.name!==void 0&&(r.name=e.name),e.description!==void 0&&(r.description=e.description),n!==void 0&&(r.parent=n),e.creator!==void 0&&(r.creator=e.creator),e.scopes!==void 0&&(r.scopes=e.scopes),e.isolated!==void 0&&(r.isolated=e.isolated),e.root===!0&&(r.root=!0),e.start===!0&&(r.start=!0),e.root_lifecycle!==void 0&&(r.rootLifecycle=e.root_lifecycle),(e.worktree===!0||typeof e.worktree=="string")&&(r.worktree=!0),typeof e.worktree=="string"&&(r.worktreeBase=e.worktree),e.worktree!==void 0&&(r.worktreeCwd=L(e.pin_cwd??e.cwd??t)),e.fork_from!==void 0&&(r.forkFrom=e.fork_from),e.model!==void 0&&(r.model=e.model),e.profile!==void 0&&(r.profile=e.profile),e.situational_context!==void 0&&(r.situationalContext=e.situational_context),e.node_id!==void 0&&(r.nodeId=e.node_id),r}d(ei,"buildRecipe");function ni(e,n,t){return!it()||e.prefer_warm!==!0||e.root!==!0||e.parent!=null||e.root_lifecycle==="terminal"||(e.prompt??"")!==""||e.model!==void 0||e.fork_from!==void 0||e.worktree!==void 0||e.node_id!==void 0||e.scopes!==void 0||e.isolated!==void 0?null:{kind:e.kind,mode:e.mode??"base",cwd:n,profileId:t,model:e.model??null,situationalContext:e.situational_context??null,name:e.name??null,creator:e.creator??null}}d(ni,"warmRequestFor");import{resolveCreateKind as Io}from"../../../core/runtime/launch-target.js";function Ae(e){const n=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return Kn(e.model,n,e.modelExact===!0)}d(Ae,"requestFromLaunch");function ti(e,n){if(n===null)return e;if(e.scopes===void 0)return{...e,scopes:[...n]};const t=e.scopes.filter(r=>!E(n,r));if(t.length===0)return e;throw new p(403,"scope_denied",`scopes exceed the bearer token's ceiling: ${t.join(", ")}`,{scopes:t,ceiling:n})}d(ti,"withinCeiling");async function Ce(e,n,t){const r=(await Wn(n.kind,n.mode,{lifecycle:n.lifecycle,hasManager:e.parent!==null,model:n.model,modelOverride:!0,cwd:e.cwd,profileId:e.profile_id??null,app:e.grantee??"app:terminal"})).launch;await V(Ae(r),{cwd:e.cwd,profileId:e.profile_id??null},t)}d(Ce,"assertNodeModelChangeRegistered");async function ii(e){if(!Rt()||e.app!=="app:terminal")return!1;const n=e.class==="broker"?(await b(e.node))?.profile_id??null:e.cron===null?null:(await Y(e.cron))?.profile??null;return n!==null&&await It(n)!==null}d(ii,"callerRunsOnMachine");async function $e(e,n){const t=e.principal;if(t.class!=="broker"&&t.class!=="cron"||await ii(t))return;const r=Dt({app:t.app,resolved:await At(t),launched:t.scopes},n,"read");if("root"in r)return;const i="missing"in r?r.missing:null;throw new p(403,"scope_missing",i?`the child's directory ${n} needs missing scope ${i}`:`no permission of this run names the child's directory ${n}`,void 0,void 0,i?{scope:i}:void 0)}d($e,"assertCallerReaches");const q=new Map;async function ri(e,n={},t={}){const r=performance.now(),{value:i,steps:a}=await Kt(()=>oi(e,n,t));return a.push(["total",performance.now()-r]),{...i,headers:{...i.headers??{},"server-timing":Jt(a)}}}d(ri,"handleCreate");async function oi(e,n,t){const r=ti(Qt(e.body),e.ceiling);if(e.principal.class==="broker"){const s=e.principal;if(r.prefer_warm===!0&&s.app!=="app:terminal"&&(r.prefer_warm=!1),r.parent!=null){const o=await h(r.parent);if(o.grantee!==s.app)throw new p(403,"other_app_run","cannot create a child under another app's node");if(!await A(s,o.grantee??"app:terminal",r.parent))throw N(`unknown node: ${r.parent}`,{received:r.parent})}if(r.creator!==void 0&&r.creator!==s.node)throw new p(403,"other_app_run","cannot create for another node");if(r.fork_from!==void 0){let o=null;try{o=await le(await se(r.fork_from))}catch{}if(o?.grantee!==s.app||!await A(s,o.grantee,o.node_id))throw new p(403,"other_app_run","cannot fork another app's conversation")}r.creator=s.node}if(e.principal.class==="person"&&e.principal.sub!==void 0){const s=r.fork_from===void 0?null:await le(await se(r.fork_from)).catch(()=>null);for(const o of[r.parent,r.creator,s?.node_id])if(o!=null&&await b(o)!==null&&!await Et(e.principal,"edit",o))throw N(`unknown node: ${o}`,{received:o})}if(e.principal.class==="cron"){const s=e.principal;for(const l of["parent","creator","fork_from","node_id"])if(r[l]!=null)throw new p(403,"permission_error",`a cron cannot set ${l} on a node it starts`);r.prefer_warm=!1,r.node_id=await ce(),s.isolated&&(r.isolated=!0,r.cwd=await J(r.node_id,s.app));const o=await mn({grantee:s.app,sub:s.sub,grant_id:s.grant,scopes:s.scopes,from_exec:s.from_exec},{profile:r.profile,cwd:r.cwd,pin_cwd:r.pin_cwd,kind:r.kind,model:r.model,mode:r.mode});if(!o.allowed)throw wn(o);if(r.scopes!==void 0){const l=r.scopes.find(m=>!E(o.effectiveScopes,m)||!E(s.scopes,m));if(l!==void 0)throw new p(403,"scope_missing",`scope ${l} is not held by this cron`,void 0,void 0,{scope:l})}else o.scopes!==null&&(r.scopes=o.scopes)}r.creator!==void 0&&wt(await h(r.creator),"crtr:act");const i=r.request_key?.trim();if(i===void 0||r.node_id!==void 0&&pn(r.node_id)&&await b(r.node_id)!==null&&(await me(i))?.nodeId!==r.node_id)return F(e,r,n,t);const a=q.get(i);if(a!==void 0)return a;const c=ai(e,r,i,n,t);q.set(i,c);try{return await c}finally{q.delete(i)}}d(oi,"createWithinTimings");const Te=`${process.pid}:${Fe()}`,ee="create_request_in_progress";async function Ne(e,n,t){const r=Date.now()+9e4;let i=Date.now()+1e4;for(;t!==null;){const a=await b(t);if(a!==null){if(!j(e.principal)&&!await A(e.principal,a.grantee??"app:terminal",t))throw new p(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:await v(t)}}if(await He(n)&&(i=Math.min(r,Date.now()+1e3)),Date.now()>=i||(await me(n))?.nodeId!==t)break;await new Promise(c=>setTimeout(c,100))}throw new p(409,ee,"another create with this request_key is in progress; retry it")}d(Ne,"awaitForeignCreate");async function ai(e,n,t,r,i){const a=await we(t),c=Te;if(a.nodeId!==null&&a.state==="reserved"&&await b(a.nodeId)===null&&!await fe(t,a.nodeId,c))try{return await Ne(e,t,a.nodeId)}catch(o){if(!(o instanceof p)||o.code!==ee||!await fe(t,a.nodeId,c))throw o}const s=setInterval(()=>{Ye(t,c).catch(()=>{})},ze);try{return await di(e,n,t,r,i,a)}finally{clearInterval(s)}}d(ai,"handleKeyedCreateRequest");async function di(e,n,t,r,i,a){if(a.nodeId!==null&&await b(a.nodeId)!==null){if(a.state!=="warm_claimed"){const c=await b(a.nodeId);if(!j(e.principal)&&!await A(e.principal,c.grantee??"app:terminal",a.nodeId))throw new p(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:await v(a.nodeId)}}return F(e,n,r,i,a)}try{return await F(e,n,r,i,a)}catch(c){if(c instanceof p&&c.code===ee)throw c;const s=await we(t);throw(s.nodeId===null||await b(s.nodeId)===null)&&await ue(t,s.nodeId),c}}d(di,"keyedCreateOwned");async function F(e,n,t,r,i=void 0){const a=r.deadlineAt??Xt(n.deadline),c=Zt(n.outcome_delivery),s=e.principal.class==="cron"?await hn({grantee:e.principal.app,sub:e.principal.sub,grant_id:e.principal.grant,scopes:e.principal.scopes,cron_id:e.principal.cron,origin_run_id:e.principal.origin_run,isolated:e.principal.isolated,creator:e.principal.kind==="exec"?null:(await Y(e.principal.cron))?.created_by??null},n.node_id):null;s!==null&&(n.root=s.root===!0);const o=s?.parent??n.parent??void 0;if(o==null&&n.root!==!0)throw y("a node create requires a parent (or root: true for an independent root)");let l=null;if(n.output_schema!==void 0){try{l=JSON.parse(n.output_schema)}catch{throw y("output_schema must be a JSON schema string")}if(l===null||typeof l!="object"||Array.isArray(l))throw y("output_schema must be a JSON schema object");await Xn(l)}const m=await ot(n,{validateKind:Me,...e.principal.class==="broker"||e.principal.class==="cron"?{app:e.principal.app}:{}}),{profileId:f,kind:u,cwd:_,launch:I}=m;if(n.pin_cwd!==void 0&&n.pin_cwd!==""&&n.worktree===void 0&&n.isolated!==!0&&!$(_)&&await Re(f)===null)throw new w({error:"cwd_missing",message:`cwd is not an existing directory: ${_}`,received:_,field:"cwd",next:"Pass an existing directory with --cwd."});await $e(e,_),n.worktree!==void 0&&await $e(e,L(n.pin_cwd??n.cwd??_));const k={...n,kind:u},P=c===void 0?void 0:qt(c,_),te=("grant"in e.principal?e.principal.grant:null)??(o==null?null:(await b(o))?.grant_id??null);if(await V(Ae(await Ve(I,te,n.model)),{cwd:_,profileId:f},t.modelRegistry),await Mt(te)!=="app"&&!await Wt(f===null?[]:await Bt(f))&&!await jt(m))throw new p(412,"no_provider_credential",Ee,{error:"no_provider_credential",message:Ee,next:"The person running this runtime logs a provider in with `crtr sys setup`, or stores a provider key on the profile."});let x=null;{const ie=i===void 0||i.nodeId===null||i.state==="warm_claimed"?ni(k,_,f):null,O=ie!==null&&!(n.start===!0&&await Re(f)!==null)?ie:null,B=l===null&&r.beforeBrokerLaunch===void 0?void 0:async g=>{l!==null&&await Qn(g,"terminal",l),r.beforeBrokerLaunch?.(g)};if(i?.state==="warm_claimed"&&i.nodeId!==null){const g=O===null?null:await tt(O,i.nodeId,B);if(g===null)throw await ue(i.requestKey,i.nodeId),new p(503,"create_resume_failed",`could not resume warm claim ${i.nodeId}; retry the create`);return await pe(i.requestKey,g),{status:201,body:await v(g)}}if(O!==null){const g=await nt(O,{...a===void 0?{}:{deadlineAt:a},...P===void 0?{}:{outcomeDelivery:P},...i===void 0?{}:{requestKey:i.requestKey}},B);if(g!==null)return i!==void 0&&await pe(i.requestKey,g),ke(O),{status:201,body:await v(g)};x=O}const D=i?.nodeId??n.node_id??(i===void 0?void 0:await ce());if(i!==void 0&&i.nodeId===null){const g=await Ze(i.requestKey,D,Te);if(g!==D)return await Ne(e,i.requestKey,g)}const R=ei(D===void 0?k:{...k,node_id:D},o,_);s!==null&&(s.rootLifecycle!==void 0&&(R.rootLifecycle=s.rootLifecycle),s.scopes!==void 0&&k.scopes===void 0&&(R.scopes=s.scopes),s.run!==void 0&&(R.run=s.run),s.withinCreate!==void 0&&(R.withinCreate=s.withinCreate)),a!==void 0&&(R.deadlineAt=a),P!==void 0&&(R.outcomeDelivery=P),R.readiness=n.root===!0?"await":"launch",Vt("handler_checks",zt());const re=await Je(R,B,()=>{x!==null&&ke(x)});return i!==void 0&&await Xe(i.requestKey,re.node.node_id),{status:201,body:await Ht("response_detail",()=>v(re.node.node_id))}}}d(F,"handleCreateRequest");function S(e,n){const t=e.query.getAll(n);if(t.length>1)throw y(`${n} must appear at most once`);return t[0]}d(S,"singleQueryValue");function ne(e,n){if(e!==void 0){if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1;throw y(`${n} must be true or false`)}}d(ne,"optionalBoolean");function G(e,n,t){if(e!==void 0){if(t.includes(e))return e;throw y(`${n} must be one of: ${t.join(", ")}`)}}d(G,"oneOf");function si(e){const n=new Set(["status","lifecycle","kind","mode","profile_id","profile_prefix","parent","top_level","under","under_inclusive","hanging","include"]);for(const[I]of e.query)if(!n.has(I))throw y(`unknown nodes query parameter: ${I}`);const t=G(S(e,"status"),"status",["active","idle","done","dead","canceled"]),r=G(S(e,"lifecycle"),"lifecycle",["terminal","resident"]),i=S(e,"kind"),a=G(S(e,"mode"),"mode",["base","orchestrator"]),c=S(e,"profile_id"),s=S(e,"profile_prefix"),o=S(e,"parent"),l=ne(S(e,"top_level"),"top_level"),m=S(e,"under"),f=ne(S(e,"under_inclusive"),"under_inclusive"),u=ne(S(e,"hanging"),"hanging"),_=G(S(e,"include"),"include",["activity"]);if(o!==void 0&&l===!0)throw y("parent and top_level=true cannot be combined");return{...t!==void 0?{status:t}:{},...r!==void 0?{lifecycle:r}:{},...i!==void 0?{kind:i}:{},...a!==void 0?{mode:a}:{},...c!==void 0?{profile_id:c}:{},...s!==void 0?{profile_prefix:s}:{},...o!==void 0?{parent:o}:{},...l!==void 0?{top_level:l}:{},...m!==void 0?{under:m}:{},...f!==void 0?{under_inclusive:f}:{},...u!==void 0?{hanging:u}:{},..._!==void 0?{include:_}:{}}}d(si,"parseListQuery");async function li(e){const n=si(e);let t=await qe({...n.status!==void 0?{status:n.status}:{},...n.lifecycle!==void 0?{lifecycle:n.lifecycle}:{},...n.kind!==void 0?{kind:n.kind}:{},...n.mode!==void 0?{mode:n.mode}:{},...n.profile_id!==void 0?{profileId:n.profile_id}:{},...n.profile_prefix!==void 0?{profilePrefix:n.profile_prefix}:{},...n.parent!==void 0?{parent:n.parent}:{},...n.top_level===!0?{topLevel:!0}:{},...n.under!==void 0?{under:n.under}:{},...n.under_inclusive===!0?{underInclusive:!0}:{},...n.hanging===!0?{hanging:!0}:{}});const r=await Ot(e.principal);r!==null&&(t=t.filter(o=>r.has(o.node_id)));const i=n.include==="activity"?await fn(t.map(o=>o.node_id)):null,a=t.length>0?xe():new Set,c=new Map((await rn()).map(o=>[o.nodeId,o.controllerId]));return{status:200,body:await Oe(t,async o=>{const l=await yt(o,o.profile_id!==null&&a.has(o.profile_id),c.get(o.node_id)??null);if(i!==null){const m=await Se(o.node_id);l.activity={latest_report:m[0]??null,final_report:o.final_report===null?null:m.find(f=>f.name===o.final_report)??null,pending_human_count:i[o.node_id]??0}}return l})}}d(li,"handleList");async function ci(e){const n=e.params.id,t=await Ct(e,n,{method:"GET",path:`/v1/nodes/${encodeURIComponent(n)}`,query:$t(e)});if(t.kind==="unknown")throw Nt(n,t.unreachable);if(t.kind==="remote"){if(t.status>=400)throw Tt(t.status,t.body);return{status:t.status,body:Pt(t.body,t.machine)}}return await h(n),{status:200,body:await v(n)}}d(ci,"handleDetail");async function ui(e){const n=e.params.id;await h(n);const t=await Sn(n),{start:r}=En(t.snapshot.messages,s=>JSON.stringify(_e(s,n)).length),i=t.snapshot.messages.slice(r).map(s=>_e(s,n)),a=Rn(i);return{status:200,body:{node_id:n,snapshot:{messages:i,...t.snapshot.messageIds===void 0?{}:{messageIds:t.snapshot.messageIds.slice(r)},messageVisibility:t.snapshot.messageVisibility.slice(r),turnVisibility:t.snapshot.turnVisibility,stats:t.snapshot.stats,state:t.snapshot.state,display:t.snapshot.display,...t.snapshot.queued===void 0?{}:{queued:t.snapshot.queued},...t.snapshot.toolGroupSummaries===void 0?{}:{toolGroupSummaries:Object.fromEntries(Object.entries(t.snapshot.toolGroupSummaries).filter(([s])=>a.has(s)))},...t.snapshot.turnReplies===void 0?{}:{turnReplies:t.snapshot.turnReplies},...t.snapshot.workingActivity===void 0?{}:{workingActivity:t.snapshot.workingActivity}},commands:t.commands.map(s=>({name:s.name,description:s.description,source:s.source})),captured_at:U()}}}d(ui,"handleSnapshot");async function fi(e){const n=e.params.id,t=await On(n);if(t===null)throw N(`unknown node: ${n}`,{received:n});return{status:200,body:t}}d(fi,"handleSubject");function pi(e){for(const[a]of e.query)if(a!=="cursor"&&a!=="limit")throw y(`unknown messages query parameter: ${a}`);const n=e.query.getAll("cursor"),t=e.query.getAll("limit");if(n.length>1)throw y("cursor must appear at most once");if(t.length>1)throw y("limit must appear at most once");if(t.length===0)return n.length===0?{}:{cursor:n[0]};const r=t[0],i=Number(r);if(!Number.isSafeInteger(i)||r==="")throw y("limit must be an integer from 1 through 500");return n.length===0?{limit:i}:{cursor:n[0],limit:i}}d(pi,"parseMessagesQuery");async function mi(e){const n=e.params.id,t=await vn(n,pi(e));return{status:200,body:{node_id:n,messages:t.messages,...t.messageIds===void 0?{}:{message_ids:t.messageIds},message_visibility:t.messageVisibility,next_cursor:t.nextCursor,captured_at:U()}}}d(mi,"handleMessages");async function wi(e){const n=e.params.id;await h(n);const t=await kn(n);return{status:200,body:{node_id:n,session_file:t.sessionFile,session_jsonl:t.sessionJsonl,system_prompt:t.systemPrompt,captured_at:U()}}}d(wi,"handleSession");async function hi(e){const n=e.params.id;return await h(n),{status:200,body:{node_id:n,markdown:await In(n)}}}d(hi,"handleTranscript");async function yi(e){const n=e.params.id;await h(n);const t=d(async(i,a)=>({node_id:i,label:(await b(i))?.name??i,dir:await ye(i),self:a,files:await Yt(i)}),"root"),r=await Ut([await t(n,!0),...await Oe(await he(n),async i=>await t(i.node_id,!1))],async i=>await _i(i.node_id,i.dir)||i.files>0);return{status:200,body:{node_id:n,roots:r}}}d(yi,"handleContext");async function _i(e,n){try{return yn(await J(e),n)}catch(t){if(gn(t))return!1;throw t}}d(_i,"hasDir");async function gi(e){const n=await h(e.params.id),t=e.principal.class==="broker"?e.principal.scopes:e.ceiling,r=t===null?void 0:n.scopes==null?[...t]:[...new Set([...n.scopes.filter(a=>E(t,a)),...t.filter(a=>E(n.scopes,a))])],i=await Ke(n.node_id,r,e.principal.class==="broker"?e.principal.node:void 0);return{status:201,body:await v(i.node.node_id)}}d(gi,"handleFork");const bi=1e4;async function vi(e){const n=e.params.id,t=await h(n),r=await X(n);if(r===null||r.runner!=="machine")throw new w({error:"not_hanging",message:`${n} has no live broker on a Mac \u2014 nothing to kick here.`,next:`Use \`crtr node lifecycle revive ${n} --now\` from the CLI, which kicks a local broker directly.`});if(!St(t.fault??null))throw new w({error:"not_hanging",message:`${n} is live but has no pi\u2192provider fault eligible for --now.`,next:"Use --now only on a node the canvas shows as hanging (\u26A0) with a `pi\u2192provider` fault."});if(t.streaming===!0)throw new w({error:"busy",message:`${n} is mid-turn right now (busy) \u2014 refusing to stop a working engine.`,next:"Re-check the canvas \u2014 if it is no longer marked hanging (\u26A0), nothing to do."});await bt(n,{afterTurn:!1,reason:"revive_now"});const i=await vt("machine").stop(r,{reason:"revive_now"});if(!i.confirmed)throw i.error??new Error(`stop of ${n} on its Mac was not confirmed`);return await gt(r.executionId,{reason:"revive_now"}),await de(n,{resume:!0,capacity:"refuse"}),{status:200,body:{kicked:!0}}}d(vi,"handleKick");async function ki(e){const n=e.params.id,t=await h(n),r=e.body,i=r?.resume??!0,a=r?.reopen??!1;await Pn(n,a,e.principal.class==="broker"?e.principal.node:null);const c=!i&&r?.cron_id!==void 0?await Y(r.cron_id):null,s=await X(n);if(i&&s!==null&&s.runner!=="process"&&s.state==="running"&&!lt(t.profile_id))try{await ft({node_id:n,sub:t.sub??null,profile_id:t.profile_id??null},()=>kt(s))}catch(u){if(!(u instanceof ut))throw u}const o=await de(n,{resume:i,capacity:"refuse",...c!==null?{wakeReason:await pt(c,"schedule_revive")}:{}});o.outcome!=="already-live"&&await en(n,{failures:0,notBefore:null});const l=(await b(n))?.status??"active",m=(o.launch??M().get(n)?.handle)?.exited,f=o.outcome!=="frozen"&&await be(n,m,bi);return{status:200,body:_t(n,o,l,f)}}d(ki,"handleRevive");async function Si(e){const n=e.params.id;return{status:200,body:{newNodeId:(await Nn(n))?.newNodeId??null}}}d(Si,"handleRelaunchRoot");async function Ii(e){const n=e.params.id;await h(n);const t=e.body;if(t?.caller_pid!==void 0&&(!Number.isInteger(t.caller_pid)||t.caller_pid<=0))throw y("caller_pid must be a positive integer when provided");const r=mt(),i=new Promise(c=>{e.res.once("close",()=>c())}),a=await Ue(n,{teardownAfter:i,rootEvent:t?.finish===!0?"finish":"cancel",callerPid:t?.caller_pid,...e.principal.class==="broker"?{closer:e.principal.node}:{},...r===null?{}:{registerDetached:r.registerDetached}});return{status:200,body:ht(a)}}d(Ii,"handleClose");async function Ri(e){if(!j(e.principal))throw new p(403,"permission_error","only the person marks a conversation read");const n=e.params.id;return await h(n),await on(n),{status:204}}d(Ri,"handleMarkRead");async function Ei(e){const n=e.params.id;await h(n);const t=await Tn(n);return{status:200,body:{recycled:t.recycled,finalized:t.finalized,new_root:t.newRoot,delivered:t.delivered}}}d(Ei,"handleRecycle");async function Oi(e){const n=e.params.id;return await h(n),await z(n,{lifecycle:"terminal"}),await C(e,n,["lifecycle"]),{status:200,body:await v(n)}}d(Oi,"handleDemote");async function Ai(e,n={}){const t=e.params.id,r=await h(t),i=e.body??{};i.kind!==void 0&&await H(i.kind,r.cwd,r.profile_id??null),i.model!==void 0&&await Ce(r,{kind:i.kind??r.kind,mode:"orchestrator",lifecycle:i.resident===!0?"resident":r.lifecycle,model:i.model},n.modelRegistry);const a=await Cn(t,{...i.kind!==void 0?{kind:i.kind}:{},...i.resident===!0?{resident:!0}:{},...i.model!==void 0?{model:i.model}:{}});await C(e,t,["mode",...i.kind!==void 0?["kind"]:[],...i.resident===!0?["lifecycle"]:[],...i.model!==void 0?["model"]:[]]);const c=await Q(a.meta,await Z(t));return c.roadmap_written=a.roadmapWritten,c.roadmap_ref=a.roadmapRef,c.goal_path=a.goalPath,{status:200,body:c}}d(Ai,"handlePromote");async function Ci(e){const n=e.params.id;return await h(n),{status:200,body:{request:await Ln(n)}}}d(Ci,"handleBrokerStructuredRequest");async function $i(e){const n=e.params.id,t=e.body??{};if(await Dn(n,t.expected_execution_id),typeof t.text!="string")throw new p(400,"invalid_request","text must be a string");return await h(n),{status:200,body:{captured:await Fn(n,t.text)}}}d($i,"handleBrokerGoal");async function Ti(e,n={}){const t=e.params.id,r=await h(t),i=e.body??{};i.kind!==void 0&&await H(i.kind,r.cwd,r.profile_id??null),i.model!==void 0&&await Ce(r,{kind:i.kind??r.kind,mode:i.promote===!0?"orchestrator":r.mode,lifecycle:r.lifecycle,model:i.model},n.modelRegistry);const a=i.note??"Refresh: continue against your roadmap or goal.";await Mn(t,a);const c=await $n(t,{...i.promote===!0?{promote:!0}:{},...i.kind!==void 0?{kind:i.kind}:{},...i.model!==void 0?{model:i.model}:{}});return{status:200,body:await Q(c.meta,await Z(t))}}d(Ti,"handleYield");async function Ni(e){const n=e.params.id;await h(n);const t=e.body;if(t===void 0||typeof t.controller!="string"||t.controller.trim()==="")throw y("a wait requires a controller node id");const r=await b(t.controller);if(r===null)throw N(`unknown controller: ${t.controller}`,{received:t.controller});if(r.status!=="active"&&r.status!=="idle")throw new p(422,"unprocessable",`controller ${t.controller} is ${r.status}`);return await tn(n,t.controller),{status:200,body:await v(n)}}d(Ni,"handleWait");async function Pi(e){const n=e.principal,t=await An(n.class==="broker"?async i=>i.grantee===n.app&&await A(n,i.grantee,i.node_id):n.class==="person"&&!j(n)?async i=>await A(n,i.grantee??"app:terminal",i.node_id):void 0);return{status:200,body:{revived:[...t.revived],failed:[...t.failed],frozen:[...t.frozen]}}}d(Pi,"handleReviveAll");const Di=new Set(["interrupt","steer","after-turn","next-turn"]);function Li(e){if(e===null)return null;const n=d(r=>{throw new w({error:"invalid_listen",message:r,received:e,field:"listen",next:'Send an object mapping levels "1".."10" to interrupt|steer|after-turn|next-turn (e.g. {"3":"next-turn"}), or null to reset to the global default.'})},"bad");if(typeof e!="object"||Array.isArray(e))return n("listen must be an object or null");const t=Object.entries(e);if(t.length===0)return n("listen must name at least one level");for(const[r,i]of t)/^(?:[1-9]|10)$/.test(r)||n(`listen level must be 1..10: ${r}`),(typeof i!="string"||!Di.has(i))&&n(`listen delivery must be interrupt|steer|after-turn|next-turn: ${String(i)}`);return JSON.stringify(Object.fromEntries(t))}d(Li,"listenJson");async function C(e,n,t,r){t.length===0&&r===void 0||await K(async i=>{if(r?.(i),t.length===0)return;const a=await an(i,n),c=await ln(i,e),s=c.class==="person"?c.person:c.class==="app"?c.app:c.node;await dn(i,s,a),await sn(i,{event:"configured",object:a,actor:s,attrs:{changed:t.join(",")}})})}d(C,"recordConfigured");function Pe(e){const n=M().get(e);if(n===void 0)return!1;try{return process.kill(n.pid,"SIGTERM"),!0}catch{return!1}}d(Pe,"restartLiveBroker");function De(e,n){try{return oe(e)===oe(n)}catch{return!1}}d(De,"sameDirectory");async function Mi(e,n={}){const t=e.params.id,r=e.body;let i;if(r===void 0)i={};else if(typeof r=="object"&&r!==null&&!Array.isArray(r))i=r;else throw new w({error:"cwd_invalid",message:"cwd repair requires a non-null object with a non-empty cwd string",received:r,field:"cwd",next:"Send a config patch with a non-empty absolute cwd string."});if(i.profile!==void 0){if(typeof i.profile!="string"||i.profile==="")throw new w({error:"profile_invalid",message:"profile must be a non-empty profile id or name",received:i.profile,field:"profile",next:"Send a profile id or exact name."});if(Object.keys(i).some(f=>f!=="profile"&&f!=="restart"&&i[f]!==void 0))throw new w({error:"profile_not_exclusive",message:"profile can only be combined with restart",field:"profile",next:"Send profile (and optionally restart) alone."});const o=await h(t),l=await dt(e,i.profile);st(l.profileId);const m=ct(l.profileId).manifest.grantee??"app:terminal";if(m!==(o.grantee??"app:terminal"))throw new w({error:"profile_grantee_mismatch",message:`profile ${l.profileId} belongs to ${m}, node ${t} to ${o.grantee}`,received:i.profile,field:"profile",next:"Pick a profile owned by the same app as the node."});return(o.profile_id??null)!==l.profileId&&(rt(o.kind)?(await H(o.kind,o.cwd,l.profileId),await z(t,{profileId:l.profileId})):await T(t,{profile_id:l.profileId}),await C(e,t,["profile"])),i.restart===!0&&Pe(t),{status:200,body:await v(t)}}if(Object.prototype.hasOwnProperty.call(i,"cwd")){const o=i.cwd;if(typeof o!="string"||o==="")throw new w({error:"cwd_invalid",message:"cwd must be a non-empty string",received:o,field:"cwd",next:"Send a non-empty absolute cwd string."});if(Object.keys(i).some(u=>u!=="cwd"&&u!=="keep_session"&&u!=="restart"&&i[u]!==void 0))throw new w({error:"cwd_not_exclusive",message:"cwd repair cannot be combined with another config field",received:i,field:"cwd",next:"Send cwd as the only config field."});const l=await h(t),m=$(l.cwd);if(i.keep_session===!0||m&&W(o)&&$(o)&&De(l.cwd,o)){if(!W(o))throw new w({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${o}`,received:o,field:"cwd",next:"Send an absolute path."});const u=L(o);let _=!1;try{_=ae(u).isDirectory()}catch{}if(!_)throw new w({error:"cwd_missing",message:`cwd is not an existing directory: ${u}`,received:o,field:"cwd",next:"Send an existing absolute directory."});if(m&&!De(l.cwd,u))throw new w({error:"cwd_not_same_directory",message:`${u} is not the same directory as the recorded ${l.cwd}; --keep-session only relocates an alias`,received:o,field:"cwd",next:"Drop --keep-session to repair a gone cwd, or pass the real path of the recorded directory."});if(l.managed_worktree?.state==="open")throw new w({error:"cwd_node_managed_worktree_open",message:`${t} owns an open managed worktree and cannot relocate its cwd`,received:o,field:"cwd",next:"Reconcile the managed worktree first."});const I=l.cwd;return I!==u&&(await K(async k=>{await T(t,{cwd:u}),await k.prepare("UPDATE crons SET cwd = ? WHERE anchor_node = ? AND cwd = ?").run(u,t,I),await cn(t,I,u)}),await C(e,t,["cwd"])),i.restart===!0&&Pe(t),{status:200,body:await v(t)}}if(await M().has(t)){const u=`${t} cannot repair its cwd while its broker is live`;throw new p(409,"cwd_node_live",u,{error:"cwd_node_live",message:u,received:o,field:"cwd",next:"Let the node become dormant, then retry the cwd repair."})}if(l.fork_from!=null)throw new w({error:"cwd_node_forked",message:`${t} is a fork and cannot repair its cwd; recorded cwd: ${l.cwd}`,received:o,field:"cwd",next:`Restore ${l.cwd}, then revive the fork normally.`});if(l.managed_worktree?.state==="open")throw new w({error:"cwd_node_managed_worktree_open",message:`${t} owns an open managed worktree and cannot repair its cwd`,received:o,field:"cwd",next:"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon flow."});if($(l.cwd))throw new w({error:"cwd_still_present",message:`${t} recorded cwd still exists: ${l.cwd}; cwd repair is not a relocation command`,received:o,field:"cwd",next:"This command only repairs a node whose recorded cwd is gone."});if(!W(o))throw new w({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${o}`,received:o,field:"cwd",next:"Send an absolute path."});const f=L(o);if(!$(f))throw new w({error:"cwd_missing",message:`cwd does not exist: ${f}`,received:o,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."});try{if(!ae(f).isDirectory())throw new w({error:"cwd_not_a_directory",message:`cwd is not a directory: ${f}`,received:o,field:"cwd",next:"Send an existing absolute directory."})}catch(u){throw u instanceof w?u:new w({error:"cwd_missing",message:`cwd does not exist: ${f}`,received:o,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."})}return await K(async()=>{await T(t,{cwd:f}),await un(t)}),await C(e,t,["cwd"]),{status:200,body:await v(t)}}let a=await h(t);const c=i.listen===void 0?void 0:Li(i.listen);if(i.scopes!==void 0){const o=Ie(i.scopes),l=a.grantee==="app:terminal"?await Ft(a):a.grant_id?await Lt(a.grant_id):null;if(!o.every(m=>E(a.scopes,m)&&l!==null&&E(l.resolved,m)))throw new w({error:"unknown_scope",message:"scopes may only narrow the node's current effective set",received:o,field:"scopes",next:"Send only scopes the node currently holds."});if(o.includes("crtr:act")&&!E(o,"crtr:llm"))throw new p(400,"invalid_scope","crtr:act requires crtr:llm");a=await T(t,{scopes:o})}if(i.situational_context!==void 0&&await Be(t,We(i.situational_context)),i.model!==void 0){const o=(await ge(a.cwd,a.profile_id??null,a.grantee??"app:terminal")).modelLadders,l=Un(i.model,o),m=await Gt(a.grant_id,i.model,l===void 0),f=m?{family:xt,strength:m.strength}:l,u=m?m.model:Vn(i.model,o);await V({kind:"concrete",spec:u},{cwd:a.cwd,profileId:a.profile_id??null},n.modelRegistry);const _=M();let I=!1;if(await _.isClaimed(t)&&((await X(t))?.runner==="machine"||await be(t,_.get(t)?.handle.exited))&&(I=await zn(t,u,f,await Hn(t)).then(()=>!0,k=>{if(k instanceof Yn)return!1;throw k})),!I){if(await _.isClaimed(t)){const k=`${t}'s broker did not accept the model switch; the model was not changed`;throw new p(409,"broker_not_ready",k,{error:"broker_not_ready",message:k,received:i.model,field:"model",next:"Check the node with `crtr node inspect show`, then retry the model change."})}if(!u.includes("/"))throw y(`model must resolve to a provider/id spec: ${i.model}`);await Jn(t,u,f)}a=await h(t)}if(i.kind!==void 0||i.mode!==void 0||i.lifecycle!==void 0){i.kind!==void 0&&await Me(i.kind,a.grantee??"app:terminal");const o=i.kind??a.kind,l=i.mode??a.mode,m=i.lifecycle??a.lifecycle;let f;l==="orchestrator"&&!await xn(t)&&(f=d(async()=>{const u=await jn(t);await Gn(t,u!==null&&u.trim()!==""?{goal:u.trim()}:{})},"beforePersist")),a=await z(t,{...i.kind!==void 0?{kind:o}:{},...i.mode!==void 0?{mode:l}:{},...i.lifecycle!==void 0?{lifecycle:m}:{}},f)}i.name!==void 0&&(a=await T(t,{name:i.name}),a.window&&Bn(a.window,at(a)));const s=["scopes","situational_context","model","kind","mode","lifecycle","name","listen"].filter(o=>i[o]!==void 0);return await C(e,t,s,c===void 0?void 0:async o=>{await o.prepare("UPDATE objects SET listen_json = ? WHERE id = ? AND type = 'node'").run(c,t)}),{status:200,body:await v(t)}}d(Mi,"handleConfig");async function Le(e="app:terminal"){return(await ge(process.cwd(),Ge()||null,e)).kinds}d(Le,"daemonKinds");async function Me(e,n="app:terminal"){const t=Object.keys(await Le(n));if(!t.includes(e))throw y(`unknown kind: ${e}`,{received:e,next:`Valid kinds: ${t.sort().join(", ")}.`})}d(Me,"assertKindServer");async function ji(){const e=await Le();return{status:200,body:{kinds:Object.keys(e).sort().map(t=>({kind:t,when_to_use:e[t]?.whenToUse??null,available_to:e[t]?.availableTo??null}))}}}d(ji,"handleListKinds");const vo=[{method:"POST",pattern:"/v1/nodes",scope:"crtr:act",handler:ri},{method:"GET",pattern:"/v1/nodes",handler:li},{method:"GET",pattern:"/v1/kinds",handler:d(()=>ji(),"handler")},{method:"POST",pattern:"/v1/nodes/revive-all",scope:"crtr:act",handler:Pi},{method:"GET",pattern:"/v1/nodes/:id",handler:ci},{method:"GET",pattern:"/v1/nodes/:id/snapshot",handler:ui},{method:"GET",pattern:"/v1/nodes/:id/subject",handler:fi},{method:"GET",pattern:"/v1/nodes/:id/messages",handler:mi},{method:"GET",pattern:"/v1/nodes/:id/session",handler:wi},{method:"GET",pattern:"/v1/nodes/:id/transcript",handler:hi},{method:"GET",pattern:"/v1/nodes/:id/context",handler:yi},{method:"POST",pattern:"/v1/nodes/:id/fork",scope:"crtr:act",handler:gi},{method:"POST",pattern:"/v1/nodes/:id/revive",scope:"crtr:act",handler:ki},{method:"POST",pattern:"/v1/nodes/:id/kick",scope:"crtr:act",handler:vi},{method:"POST",pattern:"/v1/nodes/:id/relaunch-root",scope:"crtr:act",handler:Si},{method:"POST",pattern:"/v1/nodes/:id/close",handler:Ii},{method:"POST",pattern:"/v1/nodes/:id/read",handler:Ri},{method:"POST",pattern:"/v1/nodes/:id/recycle",scope:"crtr:act",handler:Ei},{method:"POST",pattern:"/v1/nodes/:id/demote",scope:"crtr:act",handler:Oi},{method:"POST",pattern:"/v1/nodes/:id/promote",scope:"crtr:act",handler:Ai},{method:"POST",pattern:"/v1/nodes/:id/yield",scope:"crtr:act",handler:Ti},{method:"GET",pattern:"/v1/nodes/:id/broker/structured-request",handler:Ci},{method:"POST",pattern:"/v1/nodes/:id/broker/goal",handler:$i},{method:"POST",pattern:"/v1/nodes/:id/wait",handler:Ni},{method:"PATCH",pattern:"/v1/nodes/:id/config",handler:Mi}];export{Mi as handleConfig,ri as handleCreate,gi as handleFork,li as handleList,Ai as handlePromote,Ti as handleYield,vo as nodeRoutes,Io as resolveCreateKind};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.727",
3
+ "version": "0.3.729",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -158,8 +158,8 @@
158
158
  },
159
159
  "license": "UNLICENSED",
160
160
  "dependencies": {
161
- "@north-light/identity": "0.3.727",
162
- "@north-light/plugin": "0.3.727",
161
+ "@north-light/identity": "0.3.729",
162
+ "@north-light/plugin": "0.3.729",
163
163
  "@earendil-works/chord": "1.5.2",
164
164
  "@earendil-works/pi-agent-core": "1.5.2",
165
165
  "@earendil-works/pi-ai": "1.5.2",
@@ -8,8 +8,8 @@ export const STARTER_SETUP_SCRIPT = `#!/usr/bin/env bash
8
8
  # - Once per image build, as root, in /work, on Alpine Linux (use apk, not apt). Every sandbox of the profile starts from the result.
9
9
  # - Your repositories are already checked out at /work/<repo name> before this runs.
10
10
  # - The sandbox user is "crtr" (home /home/crtr). Files you create for it must be chowned to it.
11
- # - Already done for you: git, gh, curl, ripgrep, Node 24, pnpm. For every repository with a pnpm-lock.yaml, its packages are already
12
- # downloaded into a shared pnpm store, so \`pnpm install\` in a sandbox links instead of downloading.
11
+ # - Already done for you: git, gh, curl, ripgrep, Node 24, pnpm. Packages are not pre-installed: run \`pnpm install\` in a sandbox,
12
+ # or install at build time below.
13
13
  # - Output goes to /work/.crtr/setup.log in the image. If this script exits non-zero, sandboxes refuse to start and point at that log.
14
14
  # - The image keeps /work, /home/crtr, /usr, /etc and /lib. Anything written to /root or /tmp is lost.
15
15
  #
@@ -38,7 +38,7 @@ set -euo pipefail
38
38
  # su crtr -c 'initdb -D /home/crtr/pg -U postgres --auth=trust'
39
39
 
40
40
  # ── 3. App dependencies ──────────────────────────────────────────────────────────────────────────────
41
- # pnpm repositories are already prepared (see above). For npm or yarn, or to install fully at build time:
41
+ # To install a repository's packages at build time:
42
42
  # (cd /work/<repo name> && npm ci)
43
43
  # (cd /work/<repo name> && pnpm install --frozen-lockfile)
44
44
  # Each full install can take 0.5-1.5 GB of the sandbox disk. Install only the repositories agents work in most.
@@ -41,6 +41,7 @@ import { clearFinalReportIfMatches, getFinalReport, getNode, updateNode } from '
41
41
  import { subscribersOf } from '../canvas/tree.js';
42
42
  import { InputError } from '../io.js';
43
43
  import { transition } from './lifecycle.js';
44
+ import { assertCheckoutNotRemoved } from './revive.js';
44
45
  import { noticeChangedWhileDone } from './ledger.js';
45
46
  async function currentFinalReport(nodeId) {
46
47
  return await getFinalReport(nodeId);
@@ -123,6 +124,10 @@ async function isManagerOf(callerNodeId, nodeId) {
123
124
  * Writing lifecycle first leaves a failed latch CAS with the canonical-final
124
125
  * pointer intact. Both writes finish before either delivery channel begins. */
125
126
  export async function commitReopenResident(nodeId, expectedFinalReport, callerNodeId) {
127
+ // A node whose managed checkout was removed can never run again: refuse before any reopen write.
128
+ const before = await getNode(nodeId);
129
+ if (before !== null)
130
+ assertCheckoutNotRemoved(nodeId, before);
126
131
  const finalReport = await currentFinalReport(nodeId);
127
132
  if (!(await isManagerOf(callerNodeId, nodeId)))
128
133
  await updateNode(nodeId, { lifecycle: 'resident' });
@@ -228,6 +228,10 @@ async function decideReviveAsCaller(nodeId, opts, wakeParked) {
228
228
  if (meta.final_report !== null) {
229
229
  throw new Error(`reviveNode: refusing to revive ${nodeId} — its finalization latch is set (final_report=${meta.final_report}). A final landed between the caller's reopen-gate check and this revive; re-run with --reopen if this retask is still wanted.`);
230
230
  }
231
+ // A removed managed checkout refuses every start, before the start checks so its reason is the one recorded. An attach that only
232
+ // looks at a parked node starts nothing; cleanup completes only after the engine exits, so no live broker is refused.
233
+ if (wakeParked || !(meta.lifecycle === 'resident' && isParked(meta)))
234
+ await refuseRemovedCheckout(nodeId, meta);
231
235
  assertProfileActive(meta.profile_id);
232
236
  // An unsandboxed machine runs terminal agents only: refuse before any lifecycle hook or other prelaunch executable runs as the app.
233
237
  assertGranteeRunsHere(meta.grantee);
@@ -368,7 +372,8 @@ export async function assertRecordedCwdExists(nodeId, meta) {
368
372
  }
369
373
  return { blaxelEnvironment, remoteMachine };
370
374
  }
371
- /** Cleanup deleted this node's managed checkout and its branch, and nothing rebuilds them: refuse on any host, before a caller changes state. */
375
+ /** Cleanup deleted this node's managed checkout and its branch, and nothing rebuilds them; its cwd now names the shared repository
376
+ * root, so a launch would edit the base checkout. Refuse on any host, before a caller changes state. */
372
377
  export function assertCheckoutNotRemoved(nodeId, meta) {
373
378
  const worktree = meta.managed_worktree;
374
379
  if (worktree?.state !== 'closed' || worktree.cleanup !== 'complete')
@@ -379,6 +384,21 @@ export function assertCheckoutNotRemoved(nodeId, meta) {
379
384
  next: `Start a new node in ${worktree.repo_root}.`,
380
385
  });
381
386
  }
387
+ /** Every start path goes through reviveNode, so this is where a removed checkout is refused. A wake that has no caller to report
388
+ * to (a tick reopen of a parked resident, a stranded or idle-released launch) leaves the row live; it is settled dead with the
389
+ * reason as its outcome, which `crtr node inspect show` prints, so the tick does not select it again. */
390
+ async function refuseRemovedCheckout(nodeId, meta) {
391
+ try {
392
+ assertCheckoutNotRemoved(nodeId, meta);
393
+ }
394
+ catch (error) {
395
+ if (meta.status === 'active' || meta.status === 'idle') {
396
+ await transition(nodeId, 'crash', { reason: 'launch_failed', outcome: { detail: { schema: 'crtr.node-outcome-detail/v1', message: error.message } } });
397
+ await clearFrozen(nodeId);
398
+ }
399
+ throw error;
400
+ }
401
+ }
382
402
  /** The `node:start` lifecycle hooks for a node coming up: a launch, or a cycle started in a running process. */
383
403
  export async function runNodeStartHooks(nodeId, meta, isBirth) {
384
404
  const lifecycleHooks = discoverLifecycleHookRegistry(meta.cwd, meta.profile_id).plans.get('node:start') ?? [];
@@ -72,13 +72,8 @@ export function recipeDockerfile(recipe, revision, packagesToken = false) {
72
72
  out.push(`COPY ${SETUP_SCRIPT_FILE} /tmp/${SETUP_SCRIPT_FILE}`);
73
73
  out.push('WORKDIR /work');
74
74
  out.push(`RUN ${writeRunUserNpmrc()}`);
75
- // Warm the image's pnpm store from each repository's lockfile, so `pnpm install` in the sandbox links instead of downloading. A failed fetch only costs that
76
- // warmth, so it is logged and never refuses the sandbox start. The fetch runs as the run user, so the repository and the store are already its own and a
77
- // setup script's `su crtr -c 'pnpm install'` can write them. No step here may `chown -R` the trees: each one rewrites every file into a new layer, and the
78
- // doubled multi-GB image kept Blaxel's build at BUILDING past the timeout. The final stage's `COPY --chown` sets ownership once.
79
- for (const repo of recipe.repositories) {
80
- out.push(`RUN if [ -f /work/${repo.name}/pnpm-lock.yaml ]; then su ${RUN_USER} -c 'cd /work/${repo.name} && HOME=/home/${RUN_USER} pnpm fetch' >> ${SETUP_LOG_FILE} 2>&1 || echo 'pnpm fetch ${repo.name} failed' >> ${SETUP_LOG_FILE}; fi`);
81
- }
75
+ // No step pre-downloads pnpm packages: a multi-GB store (nine repositories) kept Blaxel's build at BUILDING past the timeout, so `pnpm install` in a sandbox downloads.
76
+ // No step here may `chown -R` the trees either: each one rewrites every file into a new layer. The final stage's `COPY --chown` sets ownership once.
82
77
  for (const source of packages)
83
78
  out.push(guarded(`pi install ${source}`, `HOME=/var/lib/crtr PI_CODING_AGENT_DIR=${RECIPE_PI_AGENT_DIR} pi install ${shellQuote(source)}`));
84
79
  // Blaxel never reports a failed Docker step: the image stays BUILDING until the timeout, and its build log is not readable. So a failing script must not fail
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.727",
3
+ "version": "0.3.729",
4
4
  "description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "main": "./dist/api/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.727",
3
+ "version": "0.3.729",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/plugin",
3
- "version": "0.3.727",
3
+ "version": "0.3.729",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -27,8 +27,8 @@
27
27
  "postpack": "node ../../scripts/pack-minify.mjs postpack packages/crouter-plugin"
28
28
  },
29
29
  "dependencies": {
30
- "@north-light/api": "0.3.727",
31
- "@north-light/identity": "0.3.727"
30
+ "@north-light/api": "0.3.729",
31
+ "@north-light/identity": "0.3.729"
32
32
  },
33
33
  "license": "UNLICENSED",
34
34
  "publishConfig": {
package/runtime.lock.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.727",
3
+ "version": "0.3.729",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.727",
9
+ "version": "0.3.729",
10
10
  "hasInstallScript": true,
11
11
  "license": "UNLICENSED",
12
12
  "workspaces": [
@@ -28,8 +28,8 @@
28
28
  "@milkdown/preset-gfm": "^7.22.3",
29
29
  "@milkdown/prose": "^7.22.3",
30
30
  "@milkdown/utils": "^7.22.3",
31
- "@north-light/identity": "0.3.727",
32
- "@north-light/plugin": "0.3.727",
31
+ "@north-light/identity": "0.3.729",
32
+ "@north-light/plugin": "0.3.729",
33
33
  "cron-parser": "^5.6.0",
34
34
  "esbuild": "0.28.2",
35
35
  "jose": "^6.2.12",
@@ -11902,17 +11902,17 @@
11902
11902
  },
11903
11903
  "packages/crouter-api": {
11904
11904
  "name": "@north-light/api",
11905
- "version": "0.3.727",
11905
+ "version": "0.3.729",
11906
11906
  "license": "UNLICENSED"
11907
11907
  },
11908
11908
  "packages/crouter-env-docker": {
11909
11909
  "name": "@north-light/env-docker",
11910
- "version": "0.3.727",
11910
+ "version": "0.3.729",
11911
11911
  "license": "UNLICENSED"
11912
11912
  },
11913
11913
  "packages/crouter-identity": {
11914
11914
  "name": "@north-light/identity",
11915
- "version": "0.3.727",
11915
+ "version": "0.3.729",
11916
11916
  "license": "UNLICENSED",
11917
11917
  "dependencies": {
11918
11918
  "jose": "^6.2.1"
@@ -11920,21 +11920,21 @@
11920
11920
  },
11921
11921
  "packages/crouter-plugin": {
11922
11922
  "name": "@north-light/plugin",
11923
- "version": "0.3.727",
11923
+ "version": "0.3.729",
11924
11924
  "license": "UNLICENSED",
11925
11925
  "dependencies": {
11926
- "@north-light/api": "0.3.727",
11927
- "@north-light/identity": "0.3.727"
11926
+ "@north-light/api": "0.3.729",
11927
+ "@north-light/identity": "0.3.729"
11928
11928
  }
11929
11929
  },
11930
11930
  "packages/crouter-sdk": {
11931
11931
  "name": "@north-light/sdk",
11932
- "version": "0.3.727",
11932
+ "version": "0.3.729",
11933
11933
  "license": "UNLICENSED",
11934
11934
  "dependencies": {
11935
- "@north-light/api": "0.3.727",
11936
- "@north-light/identity": "0.3.727",
11937
- "@north-light/plugin": "0.3.727",
11935
+ "@north-light/api": "0.3.729",
11936
+ "@north-light/identity": "0.3.729",
11937
+ "@north-light/plugin": "0.3.729",
11938
11938
  "jose": "^6.2.1"
11939
11939
  },
11940
11940
  "bin": {