@north-light/cli 0.3.491 → 0.3.493
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/command-manifest/index.d.ts +1 -0
- package/dist/api/command-manifest/index.js +1 -1
- package/dist/api/command-manifest/object-kinds.d.ts +20 -0
- package/dist/api/command-manifest/object-kinds.js +1 -0
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/lifecycle.d.ts +8 -0
- package/dist/builtin-memory/crouter-plugin/deploying.md +22 -0
- package/dist/builtin-memory/crouter-sdk/client.md +1 -1
- package/dist/builtin-memory/crouter-sdk/release-notes.md +35 -1
- package/dist/builtin-memory/crouter-sdk/resources.md +2 -2
- package/dist/builtin-memory/northlight-apps/concepts/connections.md +17 -0
- package/dist/builtin-memory/northlight-apps/errors.md +2 -0
- package/dist/clients/attach/viewer.js +429 -429
- package/dist/commands/node-lifecycle-revive.js +1 -1
- package/dist/core/graph/access.d.ts +3 -0
- package/dist/core/graph/access.js +3 -3
- package/dist/core/plugin-objects-manifest.d.ts +2 -16
- package/dist/core/plugin-objects-manifest.js +1 -1
- package/dist/core/runtime/view-socket.d.ts +3 -4
- package/dist/core/runtime/view-socket.js +1 -1
- package/dist/daemon/api/handlers/nodes.js +1 -1
- package/dist/daemon/api/map.d.ts +1 -1
- package/dist/daemon/api/map.js +1 -1
- package/docs/apps/concepts/connections.md +17 -0
- package/docs/apps/errors.md +2 -0
- package/docs/plugin/deploying.md +22 -0
- package/docs/sdk/client.md +1 -1
- package/docs/sdk/release-notes.md +35 -1
- package/docs/sdk/resources.md +2 -2
- package/package.json +2 -2
- package/packages/crouter-identity/package.json +1 -1
- package/runtime.lock.json +12 -12
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var v=Object.defineProperty;var d=(e,r)=>v(e,"name",{value:r,configurable:!0});import{defineLeaf as w}from"../core/command.js";import{InputError as t}from"../core/io.js";import{requireScope as g}from"../core/errors.js";import{cliClient as p,rethrowAsCliError as u}from"./api-client.js";import{recordedPidLiveness as k}from"../core/canvas/pid.js";import{fullName as y}from"../core/canvas/labels.js";import{faultNeedsYou as b}from"../core/canvas/status-glyph.js";function x(e){return e===null||e.link!=="pi\u2192provider"?!1:b(e)?!0:e.retry.by==="daemon"}d(x,"isNowEligibleFault");const G=w({name:"revive",description:"reopen a window for a done/idle/dead/canceled node",whenToUse:"you want to bring a dormant node back yourself \u2014 reopen a window for one that is done, idle, dead, or canceled: resume a node you closed with `node lifecycle close`, reopen a finished worker for a follow-up, or restart a crashed one now instead of waiting. It resumes the saved conversation by default, or can restart the node clean. You rarely need this for crashes \u2014 the daemon auto-revives those; reach for it to bring a node back on demand, to revive a canceled node the daemon will never touch on its own, or to kick a hanging one early (--now). To mass-reconnect EVERY disconnected node at once (after a reboot, a killed login/tmux session, or the daemon being down a while), use `canvas revive --all` instead",help:{name:"node lifecycle revive",summary:"relaunch a node's broker engine (resuming its saved conversation), or kick a hanging one (--now)",params:[{kind:"positional",name:"node",required:!0,constraint:"Node id to revive."},{kind:"flag",name:"fresh",type:"bool",required:!1,default:!1,constraint:"When set, do NOT do a true resume. If the node already has a session `.jsonl`, this instead CYCLES it in place \u2014 reuses that SAME file, resets the tree leaf, and roots a fresh `crtr-cycle` branch (a clean-context restart that still carries the file's history, output `resumed:false`). Only when no `.jsonl` exists yet does this start a genuinely brand-new session (also `resumed:false`). Default (no --fresh): a true resume \u2014 replays the existing `.jsonl` as-is (`resumed:true`)."},{kind:"flag",name:"now",type:"bool",required:!1,default:!1,constraint:'On-demand kick of an active-fault node (parked on a `pi\u2192provider` fault, broker still alive). Its broker pid is alive, so an ordinary revive no-ops (double-launch guard) \u2014 --now SIGTERMs the live broker instead, so the daemon\'s crash\u2192grace\u2192resume path brings it back in ~20s. Valid for a live `pi\u2192provider` fault that is either a daemon-owned auto retry (kicks it early), or ANY fault the canvas dashboard flags "needs you" (e.g. exhausted retries, an auth fault you just fixed) \u2014 that disposition otherwise has no recovery verb. Mutually exclusive with --fresh.'},{kind:"flag",name:"reopen",type:"bool",required:!1,default:!1,constraint:"Clear a latched node's finalization latch (final_report/finalized_at only \u2014 the old report file and every delivered feed event are untouched) before reviving it. Rejected against a node that is not finalized. Mutually exclusive with --now."}],output:[{name:"resumed",type:"boolean",required:!1,constraint:"True ONLY for a true resume (the existing `.jsonl` replayed as-is). False for a --fresh revive, whether that landed as an in-place CYCLE (an existing `.jsonl` reused with a fresh `crtr-cycle` branch \u2014 pi is still told --session, but this is not a resume) or a genuinely fresh launch (no `.jsonl` existed). Absent for a --now kick."},{name:"ready",type:"boolean",required:!1,constraint:"True when the daemon saw the node's view.sock accept a connection within ~10s of the revive \u2014 the node is attachable. It does not show the task was delivered or the model is making progress. False when it did not (still starting, broker exited, or no free broker slot). Absent for a --now kick, and when the daemon predates this field (readiness unknown)."},{name:"kicked",type:"boolean",required:!1,constraint:"True when --now SIGTERM'd the hanging node's live broker (the daemon resumes it on the saved session within ~20s). Absent for an ordinary revive."},{name:"message",type:"string",required:!1,constraint:"Kick confirmation naming the signalled node, pid, and the daemon's ~20s resume handoff. Present only for --now."}],outputKind:"object",effects:["Launches the node's detached headless broker engine (no tmux window).","Updates the node's canvas record: status=active, intent=null.","Waits up to ~10s for the daemon to see the broker's view.sock accept a connection, so `ready:true` means a caller can attach on return.","--now: SIGTERMs the live broker instead of launching anything (the daemon's own crash-grace path resumes it)."]},run:d(async e=>{g("crtr:act","crtr node lifecycle revive");const r=e.now??!1,o=e.node,l=e.fresh??!1,c=e.reopen??!1;if(r&&c)throw new t({error:"conflicting_args",message:"`--now` kicks a LIVE broker (nothing to reopen \u2014 a finalized node has no live broker); `--reopen` is meaningless there.",next:"Run `crtr node lifecycle revive <node> --now` on a hanging node, or `crtr node lifecycle revive <node> --reopen` (no --now) to re-task a finalized one."});if(r&&l)throw new t({error:"conflicting_args",message:"`--now` kicks a live hanging broker (SIGTERM \u2192 daemon resumes the SAVED session); `--fresh` is meaningless there.",next:"Run `crtr node lifecycle revive <node> --now` (resumes), or `crtr node lifecycle revive <node> --fresh` (no --now) to relaunch clean."});const h=p();if(r){let n;try{n=await h.getNode(o)}catch(m){u(m)}const i=n.pi_pid,f=n.fault??null;if(i==null||k(i,n.pi_pid_identity??null)!=="alive")throw new t({error:"not_hanging",message:`${o} has no live broker \u2014 nothing to kick. --now is for a HANGING node (live broker parked on an active fault).`,next:"Revive a dormant node with `crtr node lifecycle revive "+o+"` (no --now)."});if(!x(f))throw new t({error:"not_hanging",message:`${o} is live but has no pi\u2192provider fault eligible for --now (either healthy, or a client-owned retry / non-provider fault already being handled elsewhere) \u2014 --now refuses to SIGTERM a node that isn't stuck on a kickable provider fault.`,next:"Use --now only on a node the canvas shows as hanging (\u26A0) with a `pi\u2192provider` fault. For a routine relaunch, omit --now."});if(n.streaming===!0)throw new t({error:"busy",message:`${o} is mid-turn right now (busy) \u2014 --now refuses to SIGTERM a working engine; it has recovered on its own.`,next:"Re-check the canvas \u2014 if it's no longer marked hanging (\u26A0), nothing to do."});try{process.kill(i,"SIGTERM")}catch{}return{kicked:!0,message:`Sent SIGTERM to ${y(n)} (${o}, pid ${i}). The daemon will resume it on the saved session within ~20s (crash\u2192grace\u2192resume).`}}const s=process.env.CRTR_CRON_ID;let a;try{a=await h.reviveNode(o,{resume:!l,reopen:c,...s!==void 0&&s!==""?{cron_id:s}:{}})}catch(n){u(n)}return{resumed:a.resumed,...a.ready!==void 0?{ready:a.ready}:{}}},"run")});export{x as isNowEligibleFault,G as nodeReviveLeaf};
|
|
@@ -15,6 +15,9 @@ export declare function isShipped(db: DatabaseSync, object: ObjectRow): boolean;
|
|
|
15
15
|
export declare function toolApps(db: DatabaseSync, reader: Reader): ObjectRow[];
|
|
16
16
|
/** May `reader` use any of `app`'s tool groups? v0: every run may use every installed plugin's tools. */
|
|
17
17
|
export declare function mayUseTools(_db: DatabaseSync, _reader: Reader, app: ObjectRow): boolean;
|
|
18
|
+
/** Whether `scopes` hold a provider-group scope `<provider>:<group>` of `app`: what a run needs to call that app's provider commands
|
|
19
|
+
* (`requireGroup`). The provider id is the app's client id. */
|
|
20
|
+
export declare function holdsProviderGroup(db: DatabaseSync, scopes: readonly string[], app: ObjectRow): boolean;
|
|
18
21
|
/** Whether this reader may register, publish or watch as an object owned by `owner`. */
|
|
19
22
|
export declare function mayActAs(db: DatabaseSync, reader: Reader, owner: ObjectRow): boolean;
|
|
20
23
|
/** Run confinement for a node acting on a custom object of its app (Silas, 2026-09-30):
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var
|
|
1
|
+
var R=Object.defineProperty;var s=(n,t)=>R(n,"name",{value:t,configurable:!0});import{prepared as f}from"../sqlite-statements.js";import{covers as O}from"@north-light/identity";import{objectPlace as x,runPlace as N,runsSeeEachOther as g}from"../runs/confinement.js";import{missingOwnMemoryScope as E}from"./spaces/own-memory.js";import{SPACES as L,identityOf as u}from"./spaces/index.js";import{insideRepo as C}from"./spaces/repo.js";function T(n,t){return f(n,`WITH RECURSIVE chain(rowid, depth) AS (
|
|
2
2
|
SELECT owner, 1 FROM objects WHERE rowid = ? AND owner IS NOT NULL
|
|
3
3
|
UNION ALL
|
|
4
4
|
SELECT o.owner, c.depth + 1 FROM objects o JOIN chain c ON o.rowid = c.rowid WHERE o.owner IS NOT NULL
|
|
5
|
-
) SELECT o.* FROM chain c CROSS JOIN objects o WHERE o.rowid = c.rowid ORDER BY c.depth`).all(t.rowid)}s(T,"ownerChain");function
|
|
5
|
+
) SELECT o.* FROM chain c CROSS JOIN objects o WHERE o.rowid = c.rowid ORDER BY c.depth`).all(t.rowid)}s(T,"ownerChain");function J(n,t){return c(n,t).space}s(J,"spaceOf");function c(n,t){const e=T(n,t),p=e.length?e[e.length-1]:t,o=L[p.type];if(!o)throw new Error(`${t.type} ${t.id} has no space: its owner chain ends at ${p.type} ${p.id}`);const r=e.length?[...e.slice(0,-1).reverse(),t]:[];return{space:p,path:r,impl:o}}s(c,"locate");function m(n,t){return t.type!=="document"?!1:f(n,"SELECT source_path FROM documents WHERE object = ?").get(t.rowid)?.source_path!=null}s(m,"isShipped");function B(n,t){return f(n,`SELECT a.* FROM objects a WHERE a.type = 'app' AND a.deleted_at IS NULL AND EXISTS (
|
|
6
6
|
SELECT 1 FROM objects o JOIN documents d ON d.object = o.rowid
|
|
7
7
|
WHERE o.owner = a.rowid AND o.type = 'document' AND o.deleted_at IS NULL AND d.source_path IS NOT NULL)
|
|
8
|
-
ORDER BY a.name = 'crtr', a.name`).all().filter(p=>h(
|
|
8
|
+
ORDER BY a.name = 'crtr', a.name`).all().filter(p=>h(n,t,p))}s(B,"toolApps");function h(n,t,e){return e.type==="app"}s(h,"mayUseTools");const A=s(n=>n.class!=="app"||n.place!==void 0,"isRun");function I(n,t,e){const p=`${u(n,e).external_id.replace(/^app:/,"")}:`;return t.some(o=>o.startsWith(p)&&!o.slice(p.length).includes(":"))}s(I,"holdsProviderGroup");function _(n,t,e){return t.class==="person"?!0:t.class==="object"?t.owner.rowid===e.rowid:t.class==="app"?t.app.rowid===e.rowid||e.type==="profile"&&e.owner===t.app.rowid:t.app.rowid===e.rowid||e.type==="profile"&&t.profile?.rowid===e.rowid||e.type==="repo"&&C(n,t,e,"rw")}s(_,"mayActAs");function M(n,t,e){if(t.class!=="node"&&!(t.class==="app"&&t.place!==void 0))return!0;const p=t.class==="app"?t.place:N(t.node.id,n);if(p===null)return!0;const o=x(e.rowid,n);return o===null?!p.isolated:g(p,o)}s(M,"customReachable");const w=s(n=>n.type.includes("."),"isCustom");function Y(n,t,e){return d(n,c(n,t),t,e)}s(Y,"objectsTargets");function d(n,{space:t,path:e},p,o){const r=[];if(t.type==="person")r.push("user");else if(t.type==="app"&&e.length>0){const i=e[0];if(i.type==="profile")e.length>1&&r.push(`profile:${u(n,i).external_id}`);else if(i.type==="node"||w(i)){const l=u(n,t).external_id;l!==o&&r.push(l)}}return p.type==="node"&&r.push("node"),r}s(d,"targetsOf");function a(n,t,e,p,o){if(t.class==="person"||t.scopes===null)return!1;const r=t.scopes;if(r.length===0||p.space.type==="app"&&t.app.rowid===p.space.rowid)return!1;const i=u(n,t.app).external_id;return d(n,p,o,i).some(l=>{const y=`crtr:objects:${e}:${l}`;return r.some(S=>O(S,y))})}s(a,"holdsInLocated");function U(n,t,e,p){return t.class==="person"||t.scopes===null?!1:a(n,t,e,c(n,p),p)}s(U,"holdsObjectsScope");function z(n,t,e,p,o){const r=p.owner===null?null:n.prepare("SELECT * FROM objects WHERE rowid = ?").get(p.owner)??null;if(r===null)return!1;const i={class:"app",app:t,scopes:e??[]};return _(n,i,r)?e===null||U(n,i,"link",o):!1}s(z,"linkAuthorizes");function G(n,t,e){return W(n,e)(t)}s(G,"canRead");function W(n,t){let e=null,p=null;return o=>{if(o.class==="person")return!0;if(e??=c(n,t),e.space.type==="app"&&e.path.length>0){if(p??=m(n,t),p&&h(n,o,e.space))return!0;if(w(t)){if(o.app.rowid===e.space.rowid&&!M(n,o,t))return!1;if(o.app.rowid!==e.space.rowid&&o.scopes!==null&&h(n,o,e.space)&&(t.privacy==="public"||A(o)&&I(n,o.scopes,e.space)))return!0}}return a(n,o,"read",e,t)||o.class==="object"&&w(o.object)&&a(n,o,"watch",e,t)?!0:e.impl.canRead(n,o,e.space,e.path,t)}}s(W,"readCheck");function V(n,t,e){if(m(n,e))return!1;const p=c(n,e);if(a(n,t,"write",p,e))return!0;const{space:o,path:r,impl:i}=p;return i.canChange(n,t,o,r,e)}s(V,"canChange");function X(n,t,e,p){if(t.class==="person")return null;const{space:o,path:r}=c(n,e);return o.type==="app"&&t.app.rowid===o.rowid?E(n,t,o,r,e,p):null}s(X,"missingMemoryScope");function q(n,t,e,p){if(t.class==="person")return null;const o=c(n,e),{space:r}=o;return r.type!=="app"||t.app.rowid!==r.rowid?null:E(n,t,r,o.path.length===0?[e]:[...o.path],null,p)}s(q,"missingMemoryScopeUnder");export{V as canChange,G as canRead,M as customReachable,U as holdsObjectsScope,I as holdsProviderGroup,m as isShipped,z as linkAuthorizes,_ as mayActAs,h as mayUseTools,X as missingMemoryScope,q as missingMemoryScopeUnder,Y as objectsTargets,T as ownerChain,W as readCheck,J as spaceOf,B as toolApps};
|
|
@@ -1,21 +1,7 @@
|
|
|
1
1
|
import type { DeclLeaf, DeclNode } from '../api/command-manifest/schema.js';
|
|
2
|
+
import { KIND, LOCAL, RESERVED_KIND_ROOTS, MAX_KIND_EVENTS, MIN_EVENT_LEVEL, MAX_EVENT_LEVEL, eventCatalogReasons, objectBlocksShapeReasons, objectKindReadReasons } from '../api/command-manifest/object-kinds.js';
|
|
2
3
|
import type { PluginManifest } from '../types.js';
|
|
3
|
-
|
|
4
|
-
* The `object_kinds` and `scopes` blocks of a plugin manifest (`plugin.json`, `bundle.json`) and the one
|
|
5
|
-
* validator every install, update, enable, provider-bundle and reconcile path shares. Canvas-free by
|
|
6
|
-
* design: the CLI and the bundle parser import it, so it must not reach `node:sqlite` or the canvas.
|
|
7
|
-
*/
|
|
8
|
-
export declare const KIND: RegExp;
|
|
9
|
-
export declare const LOCAL: RegExp;
|
|
10
|
-
/** A kind's first segment may not be one of the built-in object types. */
|
|
11
|
-
export declare const RESERVED_KIND_ROOTS: readonly string[];
|
|
12
|
-
export declare const MAX_KIND_EVENTS = 64;
|
|
13
|
-
export declare const MIN_EVENT_LEVEL = 1;
|
|
14
|
-
export declare const MAX_EVENT_LEVEL = 10;
|
|
15
|
-
/** Reasons a catalog (`events` map) is invalid; shared with `registerCustomObject`. */
|
|
16
|
-
export declare function eventCatalogReasons(events: unknown, where: string): string[];
|
|
17
|
-
/** The JSON shape of both blocks of a raw manifest record, independent of the plugin's name and commands. */
|
|
18
|
-
export declare function objectBlocksShapeReasons(record: Record<string, unknown>): string[];
|
|
4
|
+
export { KIND, LOCAL, RESERVED_KIND_ROOTS, MAX_KIND_EVENTS, MIN_EVENT_LEVEL, MAX_EVENT_LEVEL, eventCatalogReasons, objectBlocksShapeReasons, objectKindReadReasons };
|
|
19
5
|
/**
|
|
20
6
|
* The full check. `leafPaths` holds the space-joined path of every leaf below the plugin's root command
|
|
21
7
|
* (`page read` for plugin `search`'s leaf `search page read`); `streamingLeafPaths` holds those declared `rest.streaming: true`.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var l=Object.defineProperty;var r=(e,n)=>l(e,"name",{value:n,configurable:!0});import{parseScope as h}from"@north-light/identity";import{KIND as g,LOCAL as k,RESERVED_KIND_ROOTS as b,MAX_KIND_EVENTS as E,MIN_EVENT_LEVEL as j,MAX_EVENT_LEVEL as _,eventCatalogReasons as S,objectBlocksShapeReasons as a,objectKindReadReasons as f}from"../api/command-manifest/object-kinds.js";const w=/^crtr:objects:(?:read|watch|link|write):/;function L(e,n){const t=a(e);if(t.length>0)return t;const{name:c,leafPaths:p,streamingLeafPaths:s}=n;for(const[o,u]of Object.entries(e.object_kinds??{}))o.split(".")[0]!==c&&t.push(`object_kinds ${JSON.stringify(o)} must start with the plugin name "${c}."`),t.push(...f(o,u,c,p,s));const i=e.scopes??[];e.scopes!==void 0&&e.provider!==void 0&&t.push("scopes is for local plugins; a provider gets its scopes from directory consent");for(const o of i){try{h(o)}catch{t.push(`scope ${JSON.stringify(o)} is not a recognized scope`);continue}w.test(o)?o.endsWith(`:app:${c}`)&&t.push(`scope ${JSON.stringify(o)} names the plugin's own space; an app needs no scope for its own objects`):t.push(`scope ${JSON.stringify(o)} must be crtr:objects:<read|watch|link|write>:<target>`)}return t}r(L,"objectBlocksReasons");function m(e){return e.object_kinds!==void 0||e.scopes!==void 0}r(m,"declaresObjectBlocks");function y(e){return e.provider!==void 0?!1:Object.keys(e.object_kinds??{}).length>0||(e.scopes?.length??0)>0||e.transport?.kind==="http"}r(y,"needsAppToken");function P(e,n){return d(e,n,()=>!0)}r(P,"leafPathsBelowRoot");function V(e,n){return d(e,n,t=>"rest"in t&&t.rest.streaming===!0)}r(V,"streamingLeafPathsBelowRoot");function d(e,n,t){const c=new Set,p=r((s,i)=>{if(s.kind==="leaf")t(s)&&c.add([...i,s.name].join(" "));else for(const o of s.children)p(o,[...i,s.name])},"walk");for(const s of n)if(s.name===e&&s.kind==="branch")for(const i of s.children)p(i,[]);return c}r(d,"collectLeafPaths");export{g as KIND,k as LOCAL,_ as MAX_EVENT_LEVEL,E as MAX_KIND_EVENTS,j as MIN_EVENT_LEVEL,b as RESERVED_KIND_ROOTS,m as declaresObjectBlocks,S as eventCatalogReasons,P as leafPathsBelowRoot,y as needsAppToken,L as objectBlocksReasons,a as objectBlocksShapeReasons,f as objectKindReadReasons,V as streamingLeafPathsBelowRoot};
|
|
@@ -10,12 +10,11 @@ export declare function connectViewSocket(nodeId: string): Socket;
|
|
|
10
10
|
* `timeoutMs`. A view.sock that is a symlink rejects with the refusal, so no
|
|
11
11
|
* wait reads a planted link as a broker that is still starting. */
|
|
12
12
|
export declare function probeViewSocket(nodeId: string, timeoutMs: number): Promise<boolean>;
|
|
13
|
-
/** Bounded retry for the revive leaf, which has no launch handle to observe. */
|
|
14
|
-
export declare function waitForViewSocketReady(nodeId: string): Promise<boolean>;
|
|
15
13
|
/** Wait for a launched broker's view.sock, failing fast when its launch handle
|
|
16
14
|
* exits. `exited` remains optional for existing callers that only need the same
|
|
17
|
-
* bounded readiness deadline without a handle
|
|
15
|
+
* bounded readiness deadline without a handle; `waitMs` shortens that deadline
|
|
16
|
+
* for a caller holding an HTTP request open. */
|
|
18
17
|
export declare function waitForBrokerViewSocket(nodeId: string, exited?: Promise<{
|
|
19
18
|
code: number | null;
|
|
20
19
|
signal: NodeJS.Signals | null;
|
|
21
|
-
}
|
|
20
|
+
}>, waitMs?: number): Promise<boolean>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var w=Object.defineProperty;var a=(t,e)=>w(t,"name",{value:e,configurable:!0});import{createConnection as p,Socket as S}from"node:net";import{nodeRunDir as _,viewSocketPath as h}from"../canvas/paths.js";import{isBeneathRefusal as x,socketBeneath as E}from"../spaces/open-beneath.js";const u=3e4,l=100,B=u;function m(t){return new Promise(e=>{setTimeout(e,t)})}a(m,"sleep");function d(t){let e;try{e=E(_(t),h(t))}catch(c){const n=new S;return process.nextTick(()=>n.destroy(c)),n}const i=p(e.path);return i.once("connect",e.release),i.once("close",e.release),i}a(d,"connectViewSocket");function O(t,e){return new Promise((i,c)=>{let n=!1,r=null;const s=a(o=>{n||(n=!0,r!==null&&r.destroy(),o instanceof Error?c(o):i(o))},"finish");r=d(t),r.once("connect",()=>s(!0)),r.once("error",o=>s(x(o)?o:!1)),r.setTimeout(e,()=>s(!1))})}a(O,"probeViewSocket");async function C(t,e,i=u){const c=Date.now()+i,n=e?.then(()=>"exit");for(;Date.now()<=c;){const r=Math.max(0,c-Date.now()),s=O(t,Math.min(l,r)).then(f=>f?"ready":"retry"),o=n===void 0?await s:await Promise.race([s,n]);if(o==="ready")return!0;if(o==="exit")return!1;if(n!==void 0){if(await Promise.race([m(l).then(()=>"sleep"),n])==="exit")return!1}else await m(l)}return!1}a(C,"waitForBrokerViewSocket");export{B as BROKER_VIEW_SOCKET_WAIT_MS,d as connectViewSocket,O as probeViewSocket,C as waitForBrokerViewSocket};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var Se=Object.defineProperty;var a=(e,t)=>Se(e,"name",{value:t,configurable:!0});import{prepared as X}from"../../../core/sqlite-statements.js";import{envProfileId as Re}from"../../../shared/env.js";import{pausedCanvasProfiles as Oe}from"../../../core/profiles/manifest.js";import{existsSync as N,realpathSync as Z,statSync as q}from"node:fs";import{isAbsolute as F,resolve as T}from"node:path";import{appendSituationalContext as Ie,formatSituationalProse as $e}from"../../../core/runtime/situational-context.js";import{closeNode as Ce}from"../../../core/runtime/close.js";import{reviveNode as Ae}from"../../../core/runtime/revive.js";import{nowIso as G}from"../../../core/fs-utils.js";import{assertLaunchModelRegistered as B,forkNode as Ne,resolveForkSource as Te,spawnChildPrepared as Ee}from"../../../core/runtime/spawn.js";import{forkSourceNode as Pe,newNodeId as ee}from"../../../core/runtime/nodes.js";import{abandonCreateRequest as ne,childrenOf as De,completeCreateRequest as te,findCreateRequest as je,getNode as k,recordCreateRequestNode as Le,reserveCreateRequest as oe,reserveCreateRequestNode as Me,listNodes as re,recordRespawnAttempt as Fe,subscribersOf as Ge,subscriptionsOf as ie,setMessageWait as Be,updateNode as A}from"../../../core/canvas/canvas.js";import{subtreeIds as Ke}from"../../../core/canvas/nav-model.js";import{withCanvasWrite as K}from"../../../core/canvas/db.js";import{nodeObject as xe}from"../../../core/graph/objects.js";import{recordActedOn as We}from"../../../core/graph/edges.js";import{publish as Ve}from"../../../core/graph/events.js";import{readerFor as Je}from"../reader.js";import{relocateSessionCwd as ze,unbindSession as Ue}from"../../../core/canvas/sessions.js";import{ticketCountsForNodes as He}from"../../../core/canvas/attention.js";import{isSafeNodeId as Ye}from"../../../core/canvas/paths.js";import{contextDir as de,nodeAgentDir as x}from"../../../core/canvas/node-agent-paths.js";import{checkCronBirth as Qe}from"../../cron/authority.js";import{cronBirthPlacement as Xe}from"../../cron/armed-context.js";import{existsBeneath as Ze,isAbsentOrRefused as qe,isBeneathRefusal as en,readdirBeneath as nn}from"../../../core/spaces/open-beneath.js";import{readNodeMessagesPage as tn,readNodeSession as on,readNodeSnapshot as rn,transcriptMarkdown as dn}from"../../../core/runtime/node-read.js";import{assembleNodeSubject as sn}from"../../../core/substrate/subject.js";import{reviveAll as an}from"../../../core/runtime/revive-all.js";import{promoteAsync as ln,requestYieldAsync as cn,reshapeNodeAsync as W}from"../../../core/runtime/promote.js";import{recycleNode as fn}from"../../../core/runtime/recycle.js";import{relaunchRoot as un}from"../../../core/runtime/reset.js";import{assertReopenGate as pn}from"../../../core/runtime/reopen.js";import{writeYieldMessage as mn,readGoal as hn}from"../../../core/runtime/kickoff.js";import{ensureRoadmap as wn,hasRoadmap as yn}from"../../../core/runtime/roadmap.js";import{renameWindow as _n}from"../../../core/runtime/placement.js";import{buildLaunchSpecAsync as gn,explicitModelIntent as bn,normalizeModel as vn,readMergedLaunchConfigAsync as se}from"../../../core/runtime/launch.js";import{modelRequestFromConfig as kn}from"../../../core/model-routes.js";import{persistDormantModel as Sn,setModelLive as Rn}from"../../../core/runtime/model-swap.js";import{waitForBrokerViewSocket as On}from"../../../core/runtime/view-socket.js";import{BrokerUnreachableError as In}from"../../../core/runtime/broker-request.js";import{boundFleet as V}from"../../../core/runtime/fleet.js";import{admitLegacyStructuredOutput as $n}from"../../structured-requests/sidecar.js";import{assertOutputSchemaAccepted as Cn}from"../../../core/runtime/structured-output.js";import{OUTCOME_PAYLOAD_MAX_BYTES as ae}from"../../../core/canvas/types.js";import{HUMAN_ACTION_NAME_PATTERN as An}from"../../../core/human/action-binding.js";import{resolveHumanAction as Nn}from"../../../core/human-actions.js";import{parseDurationMs as Tn}from"../../../core/wake.js";import{claimWarmNode as En,refillWarmPool as le,resumeWarmClaim as Pn,warmPoolEnabled as Dn}from"../../../core/runtime/warm-pool.js";import{assertLaunchKind as J,isLaunchKind as jn,resolveLaunchTarget as Ln}from"../../../core/runtime/launch-target.js";import{fullName as Mn}from"../../../core/canvas/labels.js";import{reportsForNode as ce}from"./reports.js";import{requireUsableProfile as Fn}from"./profiles.js";import{assertProfileActive as Gn,loadExactProfileManifest as Bn}from"../../../core/profiles/manifest.js";import{getCron as fe}from"../../../core/canvas/crons.js";import{cronWakeOrigin as Kn}from"../../../core/runtime/bearings.js";import{boundDaemonControl as xn}from"../../control.js";import{notFound as E,usage as h}from"../../../core/errors.js";import{assertScope as Wn,validateScopes as ue}from"../../../core/scopes.js";import{scopeAllowed as O}from"../../../shared/env.js";import{toCloseResultDTO as Vn,toNodeDetailDTO as z,toNodeSummaryDTO as Jn,toReviveResultDTO as zn}from"../map.js";import{ApiError as m}from"../../../api/index.js";import{InputError as w}from"../../../core/io.js";import{brokerMayReach as U,canReadNode as pe,resolvedScopes as Un}from"../router.js";import{forwardVerb as Hn,queryWithoutMachine as Yn,relayError as Qn,unknownError as Xn,withMachine as Zn}from"../../peer/forward.js";import{fileRoot as qn}from"../../../core/spaces/file-root.js";import{activeGrant as et,terminalGrant as nt}from"../../../core/grants/mirror.js";import{readConfig as tt}from"../../../core/config.js";import{hasConfiguredProviderCredential as ot,NO_PROVIDER_CREDENTIAL_MESSAGE as me}from"../../../core/runtime/provider-credential-gate.js";function y(e){const t=k(e);if(t===null)throw E(`unknown node: ${e}`,{received:e});return t}a(y,"requireMeta");function H(e){return{subscribesTo:ie(e),subscribers:Ge(e),children:De(e)}}a(H,"edgesFor");function g(e){const t=y(e);return z(t,H(e))}a(g,"detailOf");function rt(e){let t=ce(e).length;try{t+=nn(x(e),de(e)).length}catch(n){if(!qe(n))throw n}return t}a(rt,"countFiles");function it(e){if(typeof e!="object"||e===null)throw h("a node create requires a JSON body");const t=e;if(t.kind!==void 0&&(typeof t.kind!="string"||t.kind.trim()===""))throw h("kind must be a non-empty string when provided");if(t.description!==void 0&&(typeof t.description!="string"||t.description.trim()===""))throw h("description must be a non-empty string when provided");if(t.creator!==void 0&&(typeof t.creator!="string"||t.creator.trim()===""))throw h("creator must be a non-empty node id when provided");if(t.scopes!==void 0&&ue(t.scopes),t.isolated!==void 0&&typeof t.isolated!="boolean")throw new m(400,"invalid_request","isolated must be a boolean",{param:"isolated"});const n=t.root_lifecycle;if(n!==void 0&&n!=="resident"&&n!=="terminal")throw h("root_lifecycle must be 'resident' or 'terminal'");if(t.request_key!==void 0&&(typeof t.request_key!="string"||t.request_key.trim()===""||t.request_key.length>128))throw h("request_key must be a non-empty string of at most 128 characters when provided");return t}a(it,"parseCreateBody");function dt(e){if(e===void 0)return;const t=Tn(e),n=t===null?null:new Date(Date.now()+t);if(t===null||!Number.isFinite(t)||t<=0||n===null||!Number.isFinite(n.getTime()))throw new m(422,"invalid_deadline","`deadline` must be a positive representable duration");return n.toISOString()}a(dt,"parseDeadline");function st(e){if(e!==void 0){if(typeof e!="object"||e===null||Array.isArray(e))throw new m(400,"invalid_request","`outcome_delivery` must be an object");if(typeof e.action!="string"||!An.test(e.action))throw new m(400,"invalid_request","`outcome_delivery.action` must be a declared action name");if(e.payload!==void 0){let t;try{t=JSON.stringify(e.payload)}catch{throw new m(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable")}if(t===void 0)throw new m(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable");if(Buffer.byteLength(t,"utf8")>ae)throw new m(413,"payload_too_large",`serialized payload exceeds ${ae} bytes`)}return e}}a(st,"parseOutcomeDelivery");function at(e,t){const n=Nn(e.action,t);if(!("kind"in n))return{actionName:e.action,argv:n.argv,cwd:n.cwd,configOrigin:n.configOrigin,...e.payload===void 0?{}:{payload:e.payload}};throw n.kind==="unknown_action"?new m(422,"unknown_action",`no action named ${e.action} is declared from ${t}`):new m(422,"invalid_action",`${e.action} is declared in ${n.configOrigin} but unusable: ${n.reason}`,{reason:n.reason,configOrigin:n.configOrigin})}a(at,"resolveOutcomeDelivery");function lt(e,t,n){const r={kind:e.kind,cwd:n,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),t!==void 0&&(r.parent=t),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.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=T(e.pin_cwd??e.cwd??n)),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}a(lt,"buildRecipe");function ct(e,t,n){return!Dn()||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:t,profileId:n,model:e.model??null,situationalContext:e.situational_context??null,name:e.name??null,creator:e.creator??null}}a(ct,"warmRequestFor");import{resolveCreateKind as rr}from"../../../core/runtime/launch-target.js";function he(e){const t=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return kn(e.model,t,e.modelExact===!0)}a(he,"requestFromLaunch");function ft(e,t){if(t===null)return e;if(e.scopes===void 0)return{...e,scopes:[...t]};const n=e.scopes.filter(r=>!O(t,r));if(n.length===0)return e;throw new m(403,"scope_denied",`scopes exceed the bearer token's ceiling: ${n.join(", ")}`,{scopes:n,ceiling:t})}a(ft,"withinCeiling");async function we(e,t,n){const r=(await gn(t.kind,t.mode,{lifecycle:t.lifecycle,hasManager:e.parent!==null,model:t.model,modelOverride:!0,cwd:e.cwd,profileId:e.profile_id??null})).launch;await B(he(r),{cwd:e.cwd,profileId:e.profile_id??null},n)}a(we,"assertNodeModelChangeRegistered");function ye(e,t){const n=e.principal;if(n.class!=="broker"&&n.class!=="cron")return;const r=qn({app:n.app,resolved:Un(n),launched:n.scopes},t,"read");if("root"in r)return;const o="missing"in r?r.missing:null;throw new m(403,"scope_missing",o?`the child's directory ${t} needs missing scope ${o}`:`no permission of this run names the child's directory ${t}`,void 0,void 0,o?{scope:o}:void 0)}a(ye,"assertCallerReaches");const Y=new Map;async function ut(e,t={},n={}){const r=ft(it(e.body),e.ceiling);if(e.principal.class==="broker"){const c=e.principal;if(r.prefer_warm===!0&&c.app!=="app:terminal"&&(r.prefer_warm=!1),r.parent!=null){const i=y(r.parent);if(i.grantee!==c.app)throw new m(403,"other_app_run","cannot create a child under another app's node");if(!U(c,r.parent,i.grantee??"app:terminal"))throw E(`unknown node: ${r.parent}`,{received:r.parent})}if(r.creator!==void 0&&r.creator!==c.node)throw new m(403,"other_app_run","cannot create for another node");if(r.fork_from!==void 0){let i=null;try{i=Pe(Te(r.fork_from))}catch{}if(i?.grantee!==c.app||!U(c,i.node_id,i.grantee))throw new m(403,"other_app_run","cannot fork another app's conversation")}r.creator=c.node}if(e.principal.class==="cron"){const c=e.principal;for(const l of["parent","creator","fork_from","node_id"])if(r[l]!=null)throw new m(403,"permission_error",`a cron cannot set ${l} on a node it starts`);r.prefer_warm=!1;const i=Qe({grantee:c.app,sub:c.sub,grant_id:c.grant,scopes:c.scopes});if(!i.allowed)throw new m(i.reason==="scope_missing"?403:401,i.reason==="scope_missing"?"scope_missing":"grant_revoked",i.message);if(r.scopes!==void 0){const l=r.scopes.find(p=>!O(i.effectiveScopes,p)||!O(c.scopes,p));if(l!==void 0)throw new m(403,"scope_missing",`scope ${l} is not held by this cron`,void 0,void 0,{scope:l})}else c.scopes!==null&&(r.scopes=[...c.scopes]);r.node_id=ee(),c.isolated&&(r.isolated=!0,r.cwd=x(r.node_id,c.app))}r.creator!==void 0&&Wn(y(r.creator),"crtr:act");const o=r.request_key?.trim();if(o===void 0||r.node_id!==void 0&&Ye(r.node_id)&&k(r.node_id)!==null&&je(o)?.nodeId!==r.node_id)return P(e,r,t,n);const d=Y.get(o);if(d!==void 0)return d;const s=pt(e,r,o,t,n);Y.set(o,s);try{return await s}finally{Y.delete(o)}}a(ut,"handleCreate");async function pt(e,t,n,r,o){const d=oe(n);if(d.nodeId!==null&&k(d.nodeId)!==null){if(d.state!=="warm_claimed"){const s=k(d.nodeId);if(e.principal.class!=="person"&&!pe(e.principal,s.grantee??"app:terminal",d.nodeId))throw new m(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:g(d.nodeId)}}return P(e,t,r,o,d)}try{return await P(e,t,r,o,d)}catch(s){const c=oe(n);throw(c.nodeId===null||k(c.nodeId)===null)&&ne(n,c.nodeId),s}}a(pt,"handleKeyedCreateRequest");async function P(e,t,n,r,o=void 0){const d=r.deadlineAt??dt(t.deadline),s=st(t.outcome_delivery),c=e.principal.class==="cron"?Xe({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:fe(e.principal.cron)?.created_by??null},t.node_id):null;c!==null&&(t.root=c.root===!0);const i=c?.parent??t.parent??void 0;if(i==null&&t.root!==!0)throw h("a node create requires a parent (or root: true for an independent root)");let l=null;if(t.output_schema!==void 0){try{l=JSON.parse(t.output_schema)}catch{throw h("output_schema must be a JSON schema string")}if(l===null||typeof l!="object"||Array.isArray(l))throw h("output_schema must be a JSON schema object");await Cn(l)}const{profileId:p,kind:u,cwd:f,launch:_}=await Ln(t,{validateKind:ke});ye(e,f),t.worktree!==void 0&&ye(e,T(t.pin_cwd??t.cwd??f));const S={...t,kind:u},I=s===void 0?void 0:at(s,f);if(await B(he(_),{cwd:f,profileId:p},n.modelRegistry),!await ot(p))throw new m(412,"no_provider_credential",me,{error:"no_provider_credential",message:me,next:"The person running this runtime logs a provider in with `crtr sys setup`, or stores a provider key on the profile."});let j=null;{const $=o===void 0||o.nodeId===null||o.state==="warm_claimed"?ct(S,f,p):null,L=l===null&&r.beforeBrokerLaunch===void 0?void 0:v=>{l!==null&&$n(v,"terminal",l),r.beforeBrokerLaunch?.(v)};if(o?.state==="warm_claimed"&&o.nodeId!==null){const v=$===null?null:await Pn($,o.nodeId,L);if(v===null)throw ne(o.requestKey,o.nodeId),new m(503,"create_resume_failed",`could not resume warm claim ${o.nodeId}; retry the create`);return te(o.requestKey,v),{status:201,body:g(v)}}if($!==null){const v=await En($,{...d===void 0?{}:{deadlineAt:d},...I===void 0?{}:{outcomeDelivery:I},...o===void 0?{}:{requestKey:o.requestKey}},L);if(v!==null)return o!==void 0&&te(o.requestKey,v),le($),{status:201,body:g(v)};j=$}const M=o?.nodeId??t.node_id??(o===void 0?void 0:ee());o!==void 0&&o.nodeId===null&&Me(o.requestKey,M);const R=lt(M===void 0?S:{...S,node_id:M},i,f);c!==null&&(c.rootLifecycle!==void 0&&(R.rootLifecycle=c.rootLifecycle),c.scopes!==void 0&&S.scopes===void 0&&(R.scopes=c.scopes),c.run!==void 0&&(R.run=c.run),c.withinCreate!==void 0&&(R.withinCreate=c.withinCreate)),d!==void 0&&(R.deadlineAt=d),I!==void 0&&(R.outcomeDelivery=I),R.readiness=t.root===!0?"await":"launch";const Q=await Ee(R,L,()=>{j!==null&&le(j)});return o!==void 0&&Le(o.requestKey,Q.node.node_id),{status:201,body:g(Q.node.node_id)}}}a(P,"handleCreateRequest");function b(e,t){const n=e.query.getAll(t);if(n.length>1)throw h(`${t} must appear at most once`);return n[0]}a(b,"singleQueryValue");function _e(e,t){if(e!==void 0){if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1;throw h(`${t} must be true or false`)}}a(_e,"optionalBoolean");function D(e,t,n){if(e!==void 0){if(n.includes(e))return e;throw h(`${t} must be one of: ${n.join(", ")}`)}}a(D,"oneOf");function mt(e){const t=new Set(["status","lifecycle","kind","mode","profile_id","profile_prefix","parent","top_level","under","hanging","include"]);for(const[_]of e.query)if(!t.has(_))throw h(`unknown nodes query parameter: ${_}`);const n=D(b(e,"status"),"status",["active","idle","done","dead","canceled"]),r=D(b(e,"lifecycle"),"lifecycle",["terminal","resident"]),o=b(e,"kind"),d=D(b(e,"mode"),"mode",["base","orchestrator"]),s=b(e,"profile_id"),c=b(e,"profile_prefix"),i=b(e,"parent"),l=_e(b(e,"top_level"),"top_level"),p=b(e,"under"),u=_e(b(e,"hanging"),"hanging"),f=D(b(e,"include"),"include",["activity"]);if(i!==void 0&&l===!0)throw h("parent and top_level=true cannot be combined");return{...n!==void 0?{status:n}:{},...r!==void 0?{lifecycle:r}:{},...o!==void 0?{kind:o}:{},...d!==void 0?{mode:d}:{},...s!==void 0?{profile_id:s}:{},...c!==void 0?{profile_prefix:c}:{},...i!==void 0?{parent:i}:{},...l!==void 0?{top_level:l}:{},...p!==void 0?{under:p}:{},...u!==void 0?{hanging:u}:{},...f!==void 0?{include:f}:{}}}a(mt,"parseListQuery");function ht(e){const t=mt(e);let n=t.status!==void 0?re({status:t.status}):re();if(e.principal.class!=="person"&&(n=n.filter(s=>pe(e.principal,s.grantee??"app:terminal",s.node_id))),t.lifecycle!==void 0&&(n=n.filter(s=>s.lifecycle===t.lifecycle)),t.kind!==void 0&&(n=n.filter(s=>s.kind===t.kind)),t.mode!==void 0&&(n=n.filter(s=>s.mode===t.mode)),t.profile_id!==void 0&&(n=n.filter(s=>s.profile_id===t.profile_id)),t.profile_prefix!==void 0&&(n=n.filter(s=>s.profile_id?.startsWith(t.profile_prefix))),t.parent!==void 0&&(n=n.filter(s=>s.parent===t.parent)),t.top_level===!0&&(n=n.filter(s=>s.parent===null)),t.under!==void 0){const s=new Set(Ke(t.under));n=n.filter(c=>s.has(c.node_id))}t.hanging===!0&&(n=n.filter(s=>s.parent!==null&&k(s.parent)===null));const r=t.include==="activity"?He(n.map(s=>s.node_id)):null,o=n.length>0?Oe():new Set;return{status:200,body:n.map(s=>{const c=Jn(s,s.profile_id!==null&&o.has(s.profile_id));if(r!==null){const i=ce(s.node_id);c.activity={latest_report:i[0]??null,final_report:s.final_report===null?null:i.find(l=>l.name===s.final_report)??null,pending_human_count:r[s.node_id]??0}}return c})}}a(ht,"handleList");async function wt(e){const t=e.params.id,n=await Hn(e,t,{method:"GET",path:`/v1/nodes/${encodeURIComponent(t)}`,query:Yn(e)});if(n.kind==="unknown")throw Xn(t,n.unreachable);if(n.kind==="remote"){if(n.status>=400)throw Qn(n.status,n.body);return{status:n.status,body:Zn(n.body,n.machine)}}return y(t),{status:200,body:g(t)}}a(wt,"handleDetail");async function yt(e){const t=e.params.id;y(t);const n=await rn(t);return{status:200,body:{node_id:t,snapshot:{messages:n.snapshot.messages,...n.snapshot.messageIds===void 0?{}:{messageIds:n.snapshot.messageIds},messageVisibility:n.snapshot.messageVisibility,turnVisibility:n.snapshot.turnVisibility,stats:n.snapshot.stats,state:n.snapshot.state,display:n.snapshot.display,...n.snapshot.queued===void 0?{}:{queued:n.snapshot.queued},...n.snapshot.toolGroupSummaries===void 0?{}:{toolGroupSummaries:n.snapshot.toolGroupSummaries},...n.snapshot.turnReplies===void 0?{}:{turnReplies:n.snapshot.turnReplies},...n.snapshot.workingActivity===void 0?{}:{workingActivity:n.snapshot.workingActivity}},commands:n.commands.map(o=>({name:o.name,description:o.description,source:o.source})),captured_at:G()}}}a(yt,"handleSnapshot");async function _t(e){const t=e.params.id,n=sn(t);if(n===null)throw E(`unknown node: ${t}`,{received:t});return{status:200,body:n}}a(_t,"handleSubject");function gt(e){for(const[d]of e.query)if(d!=="cursor"&&d!=="limit")throw h(`unknown messages query parameter: ${d}`);const t=e.query.getAll("cursor"),n=e.query.getAll("limit");if(t.length>1)throw h("cursor must appear at most once");if(n.length>1)throw h("limit must appear at most once");if(n.length===0)return t.length===0?{}:{cursor:t[0]};const r=n[0],o=Number(r);if(!Number.isSafeInteger(o)||r==="")throw h("limit must be an integer from 1 through 500");return t.length===0?{limit:o}:{cursor:t[0],limit:o}}a(gt,"parseMessagesQuery");async function bt(e){const t=e.params.id,n=await tn(t,gt(e));return{status:200,body:{node_id:t,messages:n.messages,...n.messageIds===void 0?{}:{message_ids:n.messageIds},message_visibility:n.messageVisibility,next_cursor:n.nextCursor,captured_at:G()}}}a(bt,"handleMessages");function vt(e){const t=e.params.id;y(t);const n=on(t);return{status:200,body:{node_id:t,session_file:n.sessionFile,session_jsonl:n.sessionJsonl,system_prompt:n.systemPrompt,captured_at:G()}}}a(vt,"handleSession");async function kt(e){const t=e.params.id;return y(t),{status:200,body:{node_id:t,markdown:await dn(t)}}}a(kt,"handleTranscript");function St(e){const t=e.params.id;y(t);const n=a((o,d)=>({node_id:o,label:k(o)?.name??o,dir:de(o),self:d,files:rt(o)}),"root"),r=[n(t,!0),...ie(t).map(o=>n(o.node_id,!1))].filter(o=>Rt(o.node_id,o.dir)||o.files>0);return{status:200,body:{node_id:t,roots:r}}}a(St,"handleContext");function Rt(e,t){try{return Ze(x(e),t)}catch(n){if(en(n))return!1;throw n}}a(Rt,"hasDir");async function Ot(e){const t=y(e.params.id),n=e.principal.class==="broker"?e.principal.scopes:e.ceiling,r=n===null?void 0:t.scopes==null?[...n]:[...new Set([...t.scopes.filter(d=>O(n,d)),...n.filter(d=>O(t.scopes,d))])],o=await Ne(t.node_id,r,e.principal.class==="broker"?e.principal.node:void 0);return{status:201,body:g(o.node.node_id)}}a(Ot,"handleFork");async function It(e){const t=e.params.id;y(t);const n=e.body,r=n?.resume??!0,o=n?.reopen??!1;pn(t,o);const d=!r&&n?.cron_id!==void 0?fe(n.cron_id):null,s=await Ae(t,{resume:r,capacity:"refuse",...d!==null?{wakeReason:Kn(d,"schedule_revive")}:{}});s.outcome!=="already-live"&&Fe(t,{failures:0,notBefore:null});const c=k(t)?.status??"active";return{status:200,body:zn(t,s,c)}}a(It,"handleRevive");async function $t(e){const t=e.params.id;return{status:200,body:{newNodeId:(await un(t))?.newNodeId??null}}}a($t,"handleRelaunchRoot");function Ct(e){const t=e.params.id;y(t);const n=e.body;if(n?.caller_pid!==void 0&&(!Number.isInteger(n.caller_pid)||n.caller_pid<=0))throw h("caller_pid must be a positive integer when provided");const r=xn(),o=Ce(t,{rootEvent:n?.finish===!0?"finish":"cancel",callerPid:n?.caller_pid,...e.principal.class==="broker"?{closer:e.principal.node}:{},...r===null?{}:{registerDetached:r.registerDetached}});return{status:200,body:Vn(o)}}a(Ct,"handleClose");async function At(e){const t=e.params.id;y(t);const n=await fn(t);return{status:200,body:{recycled:n.recycled,finalized:n.finalized,new_root:n.newRoot,delivered:n.delivered}}}a(At,"handleRecycle");async function Nt(e){const t=e.params.id;return y(t),await W(t,{lifecycle:"terminal"}),C(e,t,["lifecycle"]),{status:200,body:g(t)}}a(Nt,"handleDemote");async function Tt(e,t={}){const n=e.params.id,r=y(n),o=e.body??{};o.kind!==void 0&&await J(o.kind,r.cwd,r.profile_id??null),o.model!==void 0&&await we(r,{kind:o.kind??r.kind,mode:"orchestrator",lifecycle:o.resident===!0?"resident":r.lifecycle,model:o.model},t.modelRegistry);const d=await ln(n,{...o.kind!==void 0?{kind:o.kind}:{},...o.resident===!0?{resident:!0}:{},...o.model!==void 0?{model:o.model}:{}});C(e,n,["mode",...o.kind!==void 0?["kind"]:[],...o.resident===!0?["lifecycle"]:[],...o.model!==void 0?["model"]:[]]);const s=z(d.meta,H(n));return s.roadmap_written=d.roadmapWritten,s.roadmap_ref=d.roadmapRef,s.goal_path=d.goalPath,{status:200,body:s}}a(Tt,"handlePromote");async function Et(e,t={}){const n=e.params.id,r=y(n),o=e.body??{};o.kind!==void 0&&await J(o.kind,r.cwd,r.profile_id??null),o.model!==void 0&&await we(r,{kind:o.kind??r.kind,mode:o.promote===!0?"orchestrator":r.mode,lifecycle:r.lifecycle,model:o.model},t.modelRegistry);const d=o.note??"Refresh: continue against your roadmap or goal.";mn(n,d);const s=await cn(n,{...o.promote===!0?{promote:!0}:{},...o.kind!==void 0?{kind:o.kind}:{},...o.model!==void 0?{model:o.model}:{}});return{status:200,body:z(s.meta,H(n))}}a(Et,"handleYield");function Pt(e){const t=e.params.id;y(t);const n=e.body;if(n===void 0||typeof n.controller!="string"||n.controller.trim()==="")throw h("a wait requires a controller node id");const r=k(n.controller);if(r===null)throw E(`unknown controller: ${n.controller}`,{received:n.controller});if(r.status!=="active"&&r.status!=="idle")throw new m(422,"unprocessable",`controller ${n.controller} is ${r.status}`);return Be(t,n.controller),{status:200,body:g(t)}}a(Pt,"handleWait");async function Dt(e){const t=e.principal,n=await an(t.class==="broker"?o=>o.grantee===t.app&&U(t,o.node_id,o.grantee):void 0);return{status:200,body:{revived:[...n.revived],failed:[...n.failed],frozen:[...n.frozen]}}}a(Dt,"handleReviveAll");const jt=new Set(["interrupt","steer","after-turn","next-turn"]);function Lt(e){if(e===null)return null;const t=a(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 t("listen must be an object or null");const n=Object.entries(e);if(n.length===0)return t("listen must name at least one level");for(const[r,o]of n)/^(?:[1-9]|10)$/.test(r)||t(`listen level must be 1..10: ${r}`),(typeof o!="string"||!jt.has(o))&&t(`listen delivery must be interrupt|steer|after-turn|next-turn: ${String(o)}`);return JSON.stringify(Object.fromEntries(n))}a(Lt,"listenJson");function C(e,t,n,r){n.length===0&&r===void 0||K(o=>{if(r?.(o),n.length===0)return;const d=xe(o,t),s=Je(o,e),c=s.class==="person"?s.person:s.class==="app"?s.app:s.node;We(o,c,d),Ve(o,{event:"configured",object:d,actor:c,attrs:{changed:n.join(",")}})})}a(C,"recordConfigured");function ge(e){const t=V().get(e);if(t===void 0)return!1;try{return process.kill(t.pid,"SIGTERM"),!0}catch{return!1}}a(ge,"restartLiveBroker");function be(e,t){try{return Z(e)===Z(t)}catch{return!1}}a(be,"sameDirectory");async function Mt(e,t={}){const n=e.params.id,r=e.body;let o;if(r===void 0)o={};else if(typeof r=="object"&&r!==null&&!Array.isArray(r))o=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(o.profile!==void 0){if(typeof o.profile!="string"||o.profile==="")throw new w({error:"profile_invalid",message:"profile must be a non-empty profile id or name",received:o.profile,field:"profile",next:"Send a profile id or exact name."});if(Object.keys(o).some(u=>u!=="profile"&&u!=="restart"&&o[u]!==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 i=y(n),l=Fn(e,o.profile);Gn(l.profileId);const p=Bn(l.profileId).manifest.grantee??"app:terminal";if(p!==(i.grantee??"app:terminal"))throw new w({error:"profile_grantee_mismatch",message:`profile ${l.profileId} belongs to ${p}, node ${n} to ${i.grantee}`,received:o.profile,field:"profile",next:"Pick a profile owned by the same app as the node."});return(i.profile_id??null)!==l.profileId&&(jn(i.kind)?(await J(i.kind,i.cwd,l.profileId),await W(n,{profileId:l.profileId})):A(n,{profile_id:l.profileId}),C(e,n,["profile"])),o.restart===!0&&ge(n),{status:200,body:g(n)}}if(Object.prototype.hasOwnProperty.call(o,"cwd")){const i=o.cwd;if(typeof i!="string"||i==="")throw new w({error:"cwd_invalid",message:"cwd must be a non-empty string",received:i,field:"cwd",next:"Send a non-empty absolute cwd string."});if(Object.keys(o).some(f=>f!=="cwd"&&f!=="keep_session"&&f!=="restart"&&o[f]!==void 0))throw new w({error:"cwd_not_exclusive",message:"cwd repair cannot be combined with another config field",received:o,field:"cwd",next:"Send cwd as the only config field."});const l=y(n),p=N(l.cwd);if(o.keep_session===!0||p&&F(i)&&N(i)&&be(l.cwd,i)){if(!F(i))throw new w({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${i}`,received:i,field:"cwd",next:"Send an absolute path."});const f=T(i);let _=!1;try{_=q(f).isDirectory()}catch{}if(!_)throw new w({error:"cwd_missing",message:`cwd is not an existing directory: ${f}`,received:i,field:"cwd",next:"Send an existing absolute directory."});if(p&&!be(l.cwd,f))throw new w({error:"cwd_not_same_directory",message:`${f} is not the same directory as the recorded ${l.cwd}; --keep-session only relocates an alias`,received:i,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:`${n} owns an open managed worktree and cannot relocate its cwd`,received:i,field:"cwd",next:"Reconcile the managed worktree first."});const S=l.cwd;return S!==f&&(K(I=>{A(n,{cwd:f}),X(I,"UPDATE crons SET cwd = ? WHERE anchor_node = ? AND cwd = ?").run(f,n,S),ze(n,S,f)}),C(e,n,["cwd"])),o.restart===!0&&ge(n),{status:200,body:g(n)}}if(V().has(n)){const f=`${n} cannot repair its cwd while its broker is live`;throw new m(409,"cwd_node_live",f,{error:"cwd_node_live",message:f,received:i,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:`${n} is a fork and cannot repair its cwd; recorded cwd: ${l.cwd}`,received:i,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:`${n} owns an open managed worktree and cannot repair its cwd`,received:i,field:"cwd",next:"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon flow."});if(N(l.cwd))throw new w({error:"cwd_still_present",message:`${n} recorded cwd still exists: ${l.cwd}; cwd repair is not a relocation command`,received:i,field:"cwd",next:"This command only repairs a node whose recorded cwd is gone."});if(!F(i))throw new w({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${i}`,received:i,field:"cwd",next:"Send an absolute path."});const u=T(i);if(!N(u))throw new w({error:"cwd_missing",message:`cwd does not exist: ${u}`,received:i,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."});try{if(!q(u).isDirectory())throw new w({error:"cwd_not_a_directory",message:`cwd is not a directory: ${u}`,received:i,field:"cwd",next:"Send an existing absolute directory."})}catch(f){throw f instanceof w?f:new w({error:"cwd_missing",message:`cwd does not exist: ${u}`,received:i,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."})}return K(()=>{A(n,{cwd:u}),Ue(n)}),C(e,n,["cwd"]),{status:200,body:g(n)}}let d=y(n);const s=o.listen===void 0?void 0:Lt(o.listen);if(o.scopes!==void 0){const i=ue(o.scopes),l=d.grantee==="app:terminal"?nt():d.grant_id?et(d.grant_id):null,p=d.grantee==="app:terminal"&&!tt("user").runtime?.issuer;if(!i.every(u=>O(d.scopes,u)&&(l?O(l.resolved,u):p)))throw new w({error:"unknown_scope",message:"scopes may only narrow the node's current effective set",received:i,field:"scopes",next:"Send only scopes the node currently holds."});if(i.includes("crtr:act")&&!O(i,"crtr:llm"))throw new m(400,"invalid_scope","crtr:act requires crtr:llm");d=A(n,{scopes:i})}if(o.situational_context!==void 0&&Ie(n,$e(o.situational_context)),o.model!==void 0){const i=(await se(d.cwd,d.profile_id??null)).modelLadders,l=bn(o.model,i),p=vn(o.model,i);await B({kind:"concrete",spec:p},{cwd:d.cwd,profileId:d.profile_id??null},t.modelRegistry);const u=V();let f=!1;if(u.isClaimed(n)&&await On(n,u.get(n)?.handle.exited)&&(f=await Rn(n,p,l).then(()=>!0,_=>{if(_ instanceof In)return!1;throw _})),!f){if(u.isClaimed(n)){const _=`${n}'s broker did not accept the model switch; the model was not changed`;throw new m(409,"broker_not_ready",_,{error:"broker_not_ready",message:_,received:o.model,field:"model",next:"Check the node with `crtr node show`, then retry the model change."})}if(!p.includes("/"))throw h(`model must resolve to a provider/id spec: ${o.model}`);Sn(n,p,l)}d=y(n)}if(o.kind!==void 0||o.mode!==void 0||o.lifecycle!==void 0){o.kind!==void 0&&await ke(o.kind);const i=o.kind??d.kind,l=o.mode??d.mode,p=o.lifecycle??d.lifecycle;let u;l==="orchestrator"&&!yn(n)&&(u=a(()=>{const f=hn(n);wn(n,f!==null&&f.trim()!==""?{goal:f.trim()}:{})},"beforePersist")),d=await W(n,{...o.kind!==void 0?{kind:i}:{},...o.mode!==void 0?{mode:l}:{},...o.lifecycle!==void 0?{lifecycle:p}:{}},u)}o.name!==void 0&&(d=A(n,{name:o.name}),d.window&&_n(d.window,Mn(d)));const c=["scopes","situational_context","model","kind","mode","lifecycle","name","listen"].filter(i=>o[i]!==void 0);return C(e,n,c,s===void 0?void 0:i=>{X(i,"UPDATE objects SET listen_json = ? WHERE id = ? AND type = 'node'").run(s,n)}),{status:200,body:g(n)}}a(Mt,"handleConfig");async function ve(){return(await se(process.cwd(),Re()||null)).kinds}a(ve,"daemonKinds");async function ke(e){const t=Object.keys(await ve());if(!t.includes(e))throw h(`unknown kind: ${e}`,{received:e,next:`Valid kinds: ${t.sort().join(", ")}.`})}a(ke,"assertKindServer");async function Ft(){const e=await ve();return{status:200,body:{kinds:Object.keys(e).sort().map(n=>({kind:n,when_to_use:e[n]?.whenToUse??null,available_to:e[n]?.availableTo??null}))}}}a(Ft,"handleListKinds");const nr=[{method:"POST",pattern:"/v1/nodes",scope:"crtr:act",handler:ut},{method:"GET",pattern:"/v1/nodes",handler:ht},{method:"GET",pattern:"/v1/kinds",handler:a(()=>Ft(),"handler")},{method:"POST",pattern:"/v1/nodes/revive-all",scope:"crtr:act",handler:Dt},{method:"GET",pattern:"/v1/nodes/:id",handler:wt},{method:"GET",pattern:"/v1/nodes/:id/snapshot",handler:yt},{method:"GET",pattern:"/v1/nodes/:id/subject",handler:_t},{method:"GET",pattern:"/v1/nodes/:id/messages",handler:bt},{method:"GET",pattern:"/v1/nodes/:id/session",handler:vt},{method:"GET",pattern:"/v1/nodes/:id/transcript",handler:kt},{method:"GET",pattern:"/v1/nodes/:id/context",handler:St},{method:"POST",pattern:"/v1/nodes/:id/fork",scope:"crtr:act",handler:Ot},{method:"POST",pattern:"/v1/nodes/:id/revive",scope:"crtr:act",handler:It},{method:"POST",pattern:"/v1/nodes/:id/relaunch-root",scope:"crtr:act",handler:$t},{method:"POST",pattern:"/v1/nodes/:id/close",handler:Ct},{method:"POST",pattern:"/v1/nodes/:id/recycle",scope:"crtr:act",handler:At},{method:"POST",pattern:"/v1/nodes/:id/demote",scope:"crtr:act",handler:Nt},{method:"POST",pattern:"/v1/nodes/:id/promote",scope:"crtr:act",handler:Tt},{method:"POST",pattern:"/v1/nodes/:id/yield",scope:"crtr:act",handler:Et},{method:"POST",pattern:"/v1/nodes/:id/wait",handler:Pt},{method:"PATCH",pattern:"/v1/nodes/:id/config",handler:Mt}];export{Mt as handleConfig,ut as handleCreate,Ot as handleFork,ht as handleList,Tt as handlePromote,Et as handleYield,nr as nodeRoutes,rr as resolveCreateKind};
|
|
1
|
+
var Re=Object.defineProperty;var a=(e,t)=>Re(e,"name",{value:t,configurable:!0});import{prepared as X}from"../../../core/sqlite-statements.js";import{envProfileId as Oe}from"../../../shared/env.js";import{pausedCanvasProfiles as Ie}from"../../../core/profiles/manifest.js";import{existsSync as N,realpathSync as Z,statSync as q}from"node:fs";import{isAbsolute as G,resolve as T}from"node:path";import{appendSituationalContext as $e,formatSituationalProse as Ae}from"../../../core/runtime/situational-context.js";import{closeNode as Ce}from"../../../core/runtime/close.js";import{reviveNode as Ne}from"../../../core/runtime/revive.js";import{nowIso as B}from"../../../core/fs-utils.js";import{assertLaunchModelRegistered as x,forkNode as Te,resolveForkSource as Ee,spawnChildPrepared as Pe}from"../../../core/runtime/spawn.js";import{forkSourceNode as De,newNodeId as ee}from"../../../core/runtime/nodes.js";import{abandonCreateRequest as ne,childrenOf as je,completeCreateRequest as te,findCreateRequest as Le,getNode as k,recordCreateRequestNode as Me,reserveCreateRequest as oe,reserveCreateRequestNode as Fe,listNodes as re,recordRespawnAttempt as Ge,subscribersOf as Be,subscriptionsOf as ie,setMessageWait as xe,updateNode as C}from"../../../core/canvas/canvas.js";import{subtreeIds as Ke}from"../../../core/canvas/nav-model.js";import{withCanvasWrite as K}from"../../../core/canvas/db.js";import{nodeObject as We}from"../../../core/graph/objects.js";import{recordActedOn as Ve}from"../../../core/graph/edges.js";import{publish as ze}from"../../../core/graph/events.js";import{readerFor as Je}from"../reader.js";import{relocateSessionCwd as Ue,unbindSession as Ye}from"../../../core/canvas/sessions.js";import{ticketCountsForNodes as He}from"../../../core/canvas/attention.js";import{isSafeNodeId as Qe}from"../../../core/canvas/paths.js";import{contextDir as de,nodeAgentDir as W}from"../../../core/canvas/node-agent-paths.js";import{checkCronBirth as Xe}from"../../cron/authority.js";import{cronBirthPlacement as Ze}from"../../cron/armed-context.js";import{existsBeneath as qe,isAbsentOrRefused as en,isBeneathRefusal as nn,readdirBeneath as tn}from"../../../core/spaces/open-beneath.js";import{readNodeMessagesPage as on,readNodeSession as rn,readNodeSnapshot as dn,transcriptMarkdown as sn}from"../../../core/runtime/node-read.js";import{assembleNodeSubject as an}from"../../../core/substrate/subject.js";import{reviveAll as ln}from"../../../core/runtime/revive-all.js";import{promoteAsync as cn,requestYieldAsync as fn,reshapeNodeAsync as V}from"../../../core/runtime/promote.js";import{recycleNode as un}from"../../../core/runtime/recycle.js";import{relaunchRoot as pn}from"../../../core/runtime/reset.js";import{assertReopenGate as mn}from"../../../core/runtime/reopen.js";import{writeYieldMessage as hn,readGoal as wn}from"../../../core/runtime/kickoff.js";import{ensureRoadmap as yn,hasRoadmap as _n}from"../../../core/runtime/roadmap.js";import{renameWindow as gn}from"../../../core/runtime/placement.js";import{buildLaunchSpecAsync as bn,explicitModelIntent as vn,normalizeModel as kn,readMergedLaunchConfigAsync as se}from"../../../core/runtime/launch.js";import{modelRequestFromConfig as Sn}from"../../../core/model-routes.js";import{persistDormantModel as Rn,setModelLive as On}from"../../../core/runtime/model-swap.js";import{waitForBrokerViewSocket as ae}from"../../../core/runtime/view-socket.js";import{BrokerUnreachableError as In}from"../../../core/runtime/broker-request.js";import{boundFleet as E}from"../../../core/runtime/fleet.js";import{admitLegacyStructuredOutput as $n}from"../../structured-requests/sidecar.js";import{assertOutputSchemaAccepted as An}from"../../../core/runtime/structured-output.js";import{OUTCOME_PAYLOAD_MAX_BYTES as le}from"../../../core/canvas/types.js";import{HUMAN_ACTION_NAME_PATTERN as Cn}from"../../../core/human/action-binding.js";import{resolveHumanAction as Nn}from"../../../core/human-actions.js";import{parseDurationMs as Tn}from"../../../core/wake.js";import{claimWarmNode as En,refillWarmPool as ce,resumeWarmClaim as Pn,warmPoolEnabled as Dn}from"../../../core/runtime/warm-pool.js";import{assertLaunchKind as z,isLaunchKind as jn,resolveLaunchTarget as Ln}from"../../../core/runtime/launch-target.js";import{fullName as Mn}from"../../../core/canvas/labels.js";import{reportsForNode as fe}from"./reports.js";import{requireUsableProfile as Fn}from"./profiles.js";import{assertProfileActive as Gn,loadExactProfileManifest as Bn}from"../../../core/profiles/manifest.js";import{getCron as ue}from"../../../core/canvas/crons.js";import{cronWakeOrigin as xn}from"../../../core/runtime/bearings.js";import{boundDaemonControl as Kn}from"../../control.js";import{notFound as P,usage as h}from"../../../core/errors.js";import{assertScope as Wn,validateScopes as pe}from"../../../core/scopes.js";import{scopeAllowed as O}from"../../../shared/env.js";import{toCloseResultDTO as Vn,toNodeDetailDTO as J,toNodeSummaryDTO as zn,toReviveResultDTO as Jn}from"../map.js";import{ApiError as m}from"../../../api/index.js";import{InputError as w}from"../../../core/io.js";import{brokerMayReach as U,canReadNode as me,resolvedScopes as Un}from"../router.js";import{forwardVerb as Yn,queryWithoutMachine as Hn,relayError as Qn,unknownError as Xn,withMachine as Zn}from"../../peer/forward.js";import{fileRoot as qn}from"../../../core/spaces/file-root.js";import{activeGrant as et,terminalGrant as nt}from"../../../core/grants/mirror.js";import{readConfig as tt}from"../../../core/config.js";import{hasConfiguredProviderCredential as ot,NO_PROVIDER_CREDENTIAL_MESSAGE as he}from"../../../core/runtime/provider-credential-gate.js";function y(e){const t=k(e);if(t===null)throw P(`unknown node: ${e}`,{received:e});return t}a(y,"requireMeta");function Y(e){return{subscribesTo:ie(e),subscribers:Be(e),children:je(e)}}a(Y,"edgesFor");function g(e){const t=y(e);return J(t,Y(e))}a(g,"detailOf");function rt(e){let t=fe(e).length;try{t+=tn(W(e),de(e)).length}catch(n){if(!en(n))throw n}return t}a(rt,"countFiles");function it(e){if(typeof e!="object"||e===null)throw h("a node create requires a JSON body");const t=e;if(t.kind!==void 0&&(typeof t.kind!="string"||t.kind.trim()===""))throw h("kind must be a non-empty string when provided");if(t.description!==void 0&&(typeof t.description!="string"||t.description.trim()===""))throw h("description must be a non-empty string when provided");if(t.creator!==void 0&&(typeof t.creator!="string"||t.creator.trim()===""))throw h("creator must be a non-empty node id when provided");if(t.scopes!==void 0&&pe(t.scopes),t.isolated!==void 0&&typeof t.isolated!="boolean")throw new m(400,"invalid_request","isolated must be a boolean",{param:"isolated"});const n=t.root_lifecycle;if(n!==void 0&&n!=="resident"&&n!=="terminal")throw h("root_lifecycle must be 'resident' or 'terminal'");if(t.request_key!==void 0&&(typeof t.request_key!="string"||t.request_key.trim()===""||t.request_key.length>128))throw h("request_key must be a non-empty string of at most 128 characters when provided");return t}a(it,"parseCreateBody");function dt(e){if(e===void 0)return;const t=Tn(e),n=t===null?null:new Date(Date.now()+t);if(t===null||!Number.isFinite(t)||t<=0||n===null||!Number.isFinite(n.getTime()))throw new m(422,"invalid_deadline","`deadline` must be a positive representable duration");return n.toISOString()}a(dt,"parseDeadline");function st(e){if(e!==void 0){if(typeof e!="object"||e===null||Array.isArray(e))throw new m(400,"invalid_request","`outcome_delivery` must be an object");if(typeof e.action!="string"||!Cn.test(e.action))throw new m(400,"invalid_request","`outcome_delivery.action` must be a declared action name");if(e.payload!==void 0){let t;try{t=JSON.stringify(e.payload)}catch{throw new m(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable")}if(t===void 0)throw new m(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable");if(Buffer.byteLength(t,"utf8")>le)throw new m(413,"payload_too_large",`serialized payload exceeds ${le} bytes`)}return e}}a(st,"parseOutcomeDelivery");function at(e,t){const n=Nn(e.action,t);if(!("kind"in n))return{actionName:e.action,argv:n.argv,cwd:n.cwd,configOrigin:n.configOrigin,...e.payload===void 0?{}:{payload:e.payload}};throw n.kind==="unknown_action"?new m(422,"unknown_action",`no action named ${e.action} is declared from ${t}`):new m(422,"invalid_action",`${e.action} is declared in ${n.configOrigin} but unusable: ${n.reason}`,{reason:n.reason,configOrigin:n.configOrigin})}a(at,"resolveOutcomeDelivery");function lt(e,t,n){const r={kind:e.kind,cwd:n,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),t!==void 0&&(r.parent=t),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.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=T(e.pin_cwd??e.cwd??n)),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}a(lt,"buildRecipe");function ct(e,t,n){return!Dn()||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:t,profileId:n,model:e.model??null,situationalContext:e.situational_context??null,name:e.name??null,creator:e.creator??null}}a(ct,"warmRequestFor");import{resolveCreateKind as ir}from"../../../core/runtime/launch-target.js";function we(e){const t=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return Sn(e.model,t,e.modelExact===!0)}a(we,"requestFromLaunch");function ft(e,t){if(t===null)return e;if(e.scopes===void 0)return{...e,scopes:[...t]};const n=e.scopes.filter(r=>!O(t,r));if(n.length===0)return e;throw new m(403,"scope_denied",`scopes exceed the bearer token's ceiling: ${n.join(", ")}`,{scopes:n,ceiling:t})}a(ft,"withinCeiling");async function ye(e,t,n){const r=(await bn(t.kind,t.mode,{lifecycle:t.lifecycle,hasManager:e.parent!==null,model:t.model,modelOverride:!0,cwd:e.cwd,profileId:e.profile_id??null})).launch;await x(we(r),{cwd:e.cwd,profileId:e.profile_id??null},n)}a(ye,"assertNodeModelChangeRegistered");function _e(e,t){const n=e.principal;if(n.class!=="broker"&&n.class!=="cron")return;const r=qn({app:n.app,resolved:Un(n),launched:n.scopes},t,"read");if("root"in r)return;const o="missing"in r?r.missing:null;throw new m(403,"scope_missing",o?`the child's directory ${t} needs missing scope ${o}`:`no permission of this run names the child's directory ${t}`,void 0,void 0,o?{scope:o}:void 0)}a(_e,"assertCallerReaches");const H=new Map;async function ut(e,t={},n={}){const r=ft(it(e.body),e.ceiling);if(e.principal.class==="broker"){const c=e.principal;if(r.prefer_warm===!0&&c.app!=="app:terminal"&&(r.prefer_warm=!1),r.parent!=null){const i=y(r.parent);if(i.grantee!==c.app)throw new m(403,"other_app_run","cannot create a child under another app's node");if(!U(c,r.parent,i.grantee??"app:terminal"))throw P(`unknown node: ${r.parent}`,{received:r.parent})}if(r.creator!==void 0&&r.creator!==c.node)throw new m(403,"other_app_run","cannot create for another node");if(r.fork_from!==void 0){let i=null;try{i=De(Ee(r.fork_from))}catch{}if(i?.grantee!==c.app||!U(c,i.node_id,i.grantee))throw new m(403,"other_app_run","cannot fork another app's conversation")}r.creator=c.node}if(e.principal.class==="cron"){const c=e.principal;for(const l of["parent","creator","fork_from","node_id"])if(r[l]!=null)throw new m(403,"permission_error",`a cron cannot set ${l} on a node it starts`);r.prefer_warm=!1;const i=Xe({grantee:c.app,sub:c.sub,grant_id:c.grant,scopes:c.scopes});if(!i.allowed)throw new m(i.reason==="scope_missing"?403:401,i.reason==="scope_missing"?"scope_missing":"grant_revoked",i.message);if(r.scopes!==void 0){const l=r.scopes.find(p=>!O(i.effectiveScopes,p)||!O(c.scopes,p));if(l!==void 0)throw new m(403,"scope_missing",`scope ${l} is not held by this cron`,void 0,void 0,{scope:l})}else c.scopes!==null&&(r.scopes=[...c.scopes]);r.node_id=ee(),c.isolated&&(r.isolated=!0,r.cwd=W(r.node_id,c.app))}r.creator!==void 0&&Wn(y(r.creator),"crtr:act");const o=r.request_key?.trim();if(o===void 0||r.node_id!==void 0&&Qe(r.node_id)&&k(r.node_id)!==null&&Le(o)?.nodeId!==r.node_id)return D(e,r,t,n);const s=H.get(o);if(s!==void 0)return s;const d=pt(e,r,o,t,n);H.set(o,d);try{return await d}finally{H.delete(o)}}a(ut,"handleCreate");async function pt(e,t,n,r,o){const s=oe(n);if(s.nodeId!==null&&k(s.nodeId)!==null){if(s.state!=="warm_claimed"){const d=k(s.nodeId);if(e.principal.class!=="person"&&!me(e.principal,d.grantee??"app:terminal",s.nodeId))throw new m(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:g(s.nodeId)}}return D(e,t,r,o,s)}try{return await D(e,t,r,o,s)}catch(d){const c=oe(n);throw(c.nodeId===null||k(c.nodeId)===null)&&ne(n,c.nodeId),d}}a(pt,"handleKeyedCreateRequest");async function D(e,t,n,r,o=void 0){const s=r.deadlineAt??dt(t.deadline),d=st(t.outcome_delivery),c=e.principal.class==="cron"?Ze({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:ue(e.principal.cron)?.created_by??null},t.node_id):null;c!==null&&(t.root=c.root===!0);const i=c?.parent??t.parent??void 0;if(i==null&&t.root!==!0)throw h("a node create requires a parent (or root: true for an independent root)");let l=null;if(t.output_schema!==void 0){try{l=JSON.parse(t.output_schema)}catch{throw h("output_schema must be a JSON schema string")}if(l===null||typeof l!="object"||Array.isArray(l))throw h("output_schema must be a JSON schema object");await An(l)}const{profileId:p,kind:u,cwd:f,launch:_}=await Ln(t,{validateKind:Se});_e(e,f),t.worktree!==void 0&&_e(e,T(t.pin_cwd??t.cwd??f));const S={...t,kind:u},I=d===void 0?void 0:at(d,f);if(await x(we(_),{cwd:f,profileId:p},n.modelRegistry),!await ot(p))throw new m(412,"no_provider_credential",he,{error:"no_provider_credential",message:he,next:"The person running this runtime logs a provider in with `crtr sys setup`, or stores a provider key on the profile."});let L=null;{const $=o===void 0||o.nodeId===null||o.state==="warm_claimed"?ct(S,f,p):null,M=l===null&&r.beforeBrokerLaunch===void 0?void 0:v=>{l!==null&&$n(v,"terminal",l),r.beforeBrokerLaunch?.(v)};if(o?.state==="warm_claimed"&&o.nodeId!==null){const v=$===null?null:await Pn($,o.nodeId,M);if(v===null)throw ne(o.requestKey,o.nodeId),new m(503,"create_resume_failed",`could not resume warm claim ${o.nodeId}; retry the create`);return te(o.requestKey,v),{status:201,body:g(v)}}if($!==null){const v=await En($,{...s===void 0?{}:{deadlineAt:s},...I===void 0?{}:{outcomeDelivery:I},...o===void 0?{}:{requestKey:o.requestKey}},M);if(v!==null)return o!==void 0&&te(o.requestKey,v),ce($),{status:201,body:g(v)};L=$}const F=o?.nodeId??t.node_id??(o===void 0?void 0:ee());o!==void 0&&o.nodeId===null&&Fe(o.requestKey,F);const R=lt(F===void 0?S:{...S,node_id:F},i,f);c!==null&&(c.rootLifecycle!==void 0&&(R.rootLifecycle=c.rootLifecycle),c.scopes!==void 0&&S.scopes===void 0&&(R.scopes=c.scopes),c.run!==void 0&&(R.run=c.run),c.withinCreate!==void 0&&(R.withinCreate=c.withinCreate)),s!==void 0&&(R.deadlineAt=s),I!==void 0&&(R.outcomeDelivery=I),R.readiness=t.root===!0?"await":"launch";const Q=await Pe(R,M,()=>{L!==null&&ce(L)});return o!==void 0&&Me(o.requestKey,Q.node.node_id),{status:201,body:g(Q.node.node_id)}}}a(D,"handleCreateRequest");function b(e,t){const n=e.query.getAll(t);if(n.length>1)throw h(`${t} must appear at most once`);return n[0]}a(b,"singleQueryValue");function ge(e,t){if(e!==void 0){if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1;throw h(`${t} must be true or false`)}}a(ge,"optionalBoolean");function j(e,t,n){if(e!==void 0){if(n.includes(e))return e;throw h(`${t} must be one of: ${n.join(", ")}`)}}a(j,"oneOf");function mt(e){const t=new Set(["status","lifecycle","kind","mode","profile_id","profile_prefix","parent","top_level","under","hanging","include"]);for(const[_]of e.query)if(!t.has(_))throw h(`unknown nodes query parameter: ${_}`);const n=j(b(e,"status"),"status",["active","idle","done","dead","canceled"]),r=j(b(e,"lifecycle"),"lifecycle",["terminal","resident"]),o=b(e,"kind"),s=j(b(e,"mode"),"mode",["base","orchestrator"]),d=b(e,"profile_id"),c=b(e,"profile_prefix"),i=b(e,"parent"),l=ge(b(e,"top_level"),"top_level"),p=b(e,"under"),u=ge(b(e,"hanging"),"hanging"),f=j(b(e,"include"),"include",["activity"]);if(i!==void 0&&l===!0)throw h("parent and top_level=true cannot be combined");return{...n!==void 0?{status:n}:{},...r!==void 0?{lifecycle:r}:{},...o!==void 0?{kind:o}:{},...s!==void 0?{mode:s}:{},...d!==void 0?{profile_id:d}:{},...c!==void 0?{profile_prefix:c}:{},...i!==void 0?{parent:i}:{},...l!==void 0?{top_level:l}:{},...p!==void 0?{under:p}:{},...u!==void 0?{hanging:u}:{},...f!==void 0?{include:f}:{}}}a(mt,"parseListQuery");function ht(e){const t=mt(e);let n=t.status!==void 0?re({status:t.status}):re();if(e.principal.class!=="person"&&(n=n.filter(d=>me(e.principal,d.grantee??"app:terminal",d.node_id))),t.lifecycle!==void 0&&(n=n.filter(d=>d.lifecycle===t.lifecycle)),t.kind!==void 0&&(n=n.filter(d=>d.kind===t.kind)),t.mode!==void 0&&(n=n.filter(d=>d.mode===t.mode)),t.profile_id!==void 0&&(n=n.filter(d=>d.profile_id===t.profile_id)),t.profile_prefix!==void 0&&(n=n.filter(d=>d.profile_id?.startsWith(t.profile_prefix))),t.parent!==void 0&&(n=n.filter(d=>d.parent===t.parent)),t.top_level===!0&&(n=n.filter(d=>d.parent===null)),t.under!==void 0){const d=new Set(Ke(t.under));n=n.filter(c=>d.has(c.node_id))}t.hanging===!0&&(n=n.filter(d=>d.parent!==null&&k(d.parent)===null));const r=t.include==="activity"?He(n.map(d=>d.node_id)):null,o=n.length>0?Ie():new Set;return{status:200,body:n.map(d=>{const c=zn(d,d.profile_id!==null&&o.has(d.profile_id));if(r!==null){const i=fe(d.node_id);c.activity={latest_report:i[0]??null,final_report:d.final_report===null?null:i.find(l=>l.name===d.final_report)??null,pending_human_count:r[d.node_id]??0}}return c})}}a(ht,"handleList");async function wt(e){const t=e.params.id,n=await Yn(e,t,{method:"GET",path:`/v1/nodes/${encodeURIComponent(t)}`,query:Hn(e)});if(n.kind==="unknown")throw Xn(t,n.unreachable);if(n.kind==="remote"){if(n.status>=400)throw Qn(n.status,n.body);return{status:n.status,body:Zn(n.body,n.machine)}}return y(t),{status:200,body:g(t)}}a(wt,"handleDetail");async function yt(e){const t=e.params.id;y(t);const n=await dn(t);return{status:200,body:{node_id:t,snapshot:{messages:n.snapshot.messages,...n.snapshot.messageIds===void 0?{}:{messageIds:n.snapshot.messageIds},messageVisibility:n.snapshot.messageVisibility,turnVisibility:n.snapshot.turnVisibility,stats:n.snapshot.stats,state:n.snapshot.state,display:n.snapshot.display,...n.snapshot.queued===void 0?{}:{queued:n.snapshot.queued},...n.snapshot.toolGroupSummaries===void 0?{}:{toolGroupSummaries:n.snapshot.toolGroupSummaries},...n.snapshot.turnReplies===void 0?{}:{turnReplies:n.snapshot.turnReplies},...n.snapshot.workingActivity===void 0?{}:{workingActivity:n.snapshot.workingActivity}},commands:n.commands.map(o=>({name:o.name,description:o.description,source:o.source})),captured_at:B()}}}a(yt,"handleSnapshot");async function _t(e){const t=e.params.id,n=an(t);if(n===null)throw P(`unknown node: ${t}`,{received:t});return{status:200,body:n}}a(_t,"handleSubject");function gt(e){for(const[s]of e.query)if(s!=="cursor"&&s!=="limit")throw h(`unknown messages query parameter: ${s}`);const t=e.query.getAll("cursor"),n=e.query.getAll("limit");if(t.length>1)throw h("cursor must appear at most once");if(n.length>1)throw h("limit must appear at most once");if(n.length===0)return t.length===0?{}:{cursor:t[0]};const r=n[0],o=Number(r);if(!Number.isSafeInteger(o)||r==="")throw h("limit must be an integer from 1 through 500");return t.length===0?{limit:o}:{cursor:t[0],limit:o}}a(gt,"parseMessagesQuery");async function bt(e){const t=e.params.id,n=await on(t,gt(e));return{status:200,body:{node_id:t,messages:n.messages,...n.messageIds===void 0?{}:{message_ids:n.messageIds},message_visibility:n.messageVisibility,next_cursor:n.nextCursor,captured_at:B()}}}a(bt,"handleMessages");function vt(e){const t=e.params.id;y(t);const n=rn(t);return{status:200,body:{node_id:t,session_file:n.sessionFile,session_jsonl:n.sessionJsonl,system_prompt:n.systemPrompt,captured_at:B()}}}a(vt,"handleSession");async function kt(e){const t=e.params.id;return y(t),{status:200,body:{node_id:t,markdown:await sn(t)}}}a(kt,"handleTranscript");function St(e){const t=e.params.id;y(t);const n=a((o,s)=>({node_id:o,label:k(o)?.name??o,dir:de(o),self:s,files:rt(o)}),"root"),r=[n(t,!0),...ie(t).map(o=>n(o.node_id,!1))].filter(o=>Rt(o.node_id,o.dir)||o.files>0);return{status:200,body:{node_id:t,roots:r}}}a(St,"handleContext");function Rt(e,t){try{return qe(W(e),t)}catch(n){if(nn(n))return!1;throw n}}a(Rt,"hasDir");async function Ot(e){const t=y(e.params.id),n=e.principal.class==="broker"?e.principal.scopes:e.ceiling,r=n===null?void 0:t.scopes==null?[...n]:[...new Set([...t.scopes.filter(s=>O(n,s)),...n.filter(s=>O(t.scopes,s))])],o=await Te(t.node_id,r,e.principal.class==="broker"?e.principal.node:void 0);return{status:201,body:g(o.node.node_id)}}a(Ot,"handleFork");const It=1e4;async function $t(e){const t=e.params.id;y(t);const n=e.body,r=n?.resume??!0,o=n?.reopen??!1;mn(t,o);const s=!r&&n?.cron_id!==void 0?ue(n.cron_id):null,d=await Ne(t,{resume:r,capacity:"refuse",...s!==null?{wakeReason:xn(s,"schedule_revive")}:{}});d.outcome!=="already-live"&&Ge(t,{failures:0,notBefore:null});const c=k(t)?.status??"active",i=(d.launch??E().get(t)?.handle)?.exited,l=d.outcome!=="frozen"&&await ae(t,i,It);return{status:200,body:Jn(t,d,c,l)}}a($t,"handleRevive");async function At(e){const t=e.params.id;return{status:200,body:{newNodeId:(await pn(t))?.newNodeId??null}}}a(At,"handleRelaunchRoot");function Ct(e){const t=e.params.id;y(t);const n=e.body;if(n?.caller_pid!==void 0&&(!Number.isInteger(n.caller_pid)||n.caller_pid<=0))throw h("caller_pid must be a positive integer when provided");const r=Kn(),o=Ce(t,{rootEvent:n?.finish===!0?"finish":"cancel",callerPid:n?.caller_pid,...e.principal.class==="broker"?{closer:e.principal.node}:{},...r===null?{}:{registerDetached:r.registerDetached}});return{status:200,body:Vn(o)}}a(Ct,"handleClose");async function Nt(e){const t=e.params.id;y(t);const n=await un(t);return{status:200,body:{recycled:n.recycled,finalized:n.finalized,new_root:n.newRoot,delivered:n.delivered}}}a(Nt,"handleRecycle");async function Tt(e){const t=e.params.id;return y(t),await V(t,{lifecycle:"terminal"}),A(e,t,["lifecycle"]),{status:200,body:g(t)}}a(Tt,"handleDemote");async function Et(e,t={}){const n=e.params.id,r=y(n),o=e.body??{};o.kind!==void 0&&await z(o.kind,r.cwd,r.profile_id??null),o.model!==void 0&&await ye(r,{kind:o.kind??r.kind,mode:"orchestrator",lifecycle:o.resident===!0?"resident":r.lifecycle,model:o.model},t.modelRegistry);const s=await cn(n,{...o.kind!==void 0?{kind:o.kind}:{},...o.resident===!0?{resident:!0}:{},...o.model!==void 0?{model:o.model}:{}});A(e,n,["mode",...o.kind!==void 0?["kind"]:[],...o.resident===!0?["lifecycle"]:[],...o.model!==void 0?["model"]:[]]);const d=J(s.meta,Y(n));return d.roadmap_written=s.roadmapWritten,d.roadmap_ref=s.roadmapRef,d.goal_path=s.goalPath,{status:200,body:d}}a(Et,"handlePromote");async function Pt(e,t={}){const n=e.params.id,r=y(n),o=e.body??{};o.kind!==void 0&&await z(o.kind,r.cwd,r.profile_id??null),o.model!==void 0&&await ye(r,{kind:o.kind??r.kind,mode:o.promote===!0?"orchestrator":r.mode,lifecycle:r.lifecycle,model:o.model},t.modelRegistry);const s=o.note??"Refresh: continue against your roadmap or goal.";hn(n,s);const d=await fn(n,{...o.promote===!0?{promote:!0}:{},...o.kind!==void 0?{kind:o.kind}:{},...o.model!==void 0?{model:o.model}:{}});return{status:200,body:J(d.meta,Y(n))}}a(Pt,"handleYield");function Dt(e){const t=e.params.id;y(t);const n=e.body;if(n===void 0||typeof n.controller!="string"||n.controller.trim()==="")throw h("a wait requires a controller node id");const r=k(n.controller);if(r===null)throw P(`unknown controller: ${n.controller}`,{received:n.controller});if(r.status!=="active"&&r.status!=="idle")throw new m(422,"unprocessable",`controller ${n.controller} is ${r.status}`);return xe(t,n.controller),{status:200,body:g(t)}}a(Dt,"handleWait");async function jt(e){const t=e.principal,n=await ln(t.class==="broker"?o=>o.grantee===t.app&&U(t,o.node_id,o.grantee):void 0);return{status:200,body:{revived:[...n.revived],failed:[...n.failed],frozen:[...n.frozen]}}}a(jt,"handleReviveAll");const Lt=new Set(["interrupt","steer","after-turn","next-turn"]);function Mt(e){if(e===null)return null;const t=a(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 t("listen must be an object or null");const n=Object.entries(e);if(n.length===0)return t("listen must name at least one level");for(const[r,o]of n)/^(?:[1-9]|10)$/.test(r)||t(`listen level must be 1..10: ${r}`),(typeof o!="string"||!Lt.has(o))&&t(`listen delivery must be interrupt|steer|after-turn|next-turn: ${String(o)}`);return JSON.stringify(Object.fromEntries(n))}a(Mt,"listenJson");function A(e,t,n,r){n.length===0&&r===void 0||K(o=>{if(r?.(o),n.length===0)return;const s=We(o,t),d=Je(o,e),c=d.class==="person"?d.person:d.class==="app"?d.app:d.node;Ve(o,c,s),ze(o,{event:"configured",object:s,actor:c,attrs:{changed:n.join(",")}})})}a(A,"recordConfigured");function be(e){const t=E().get(e);if(t===void 0)return!1;try{return process.kill(t.pid,"SIGTERM"),!0}catch{return!1}}a(be,"restartLiveBroker");function ve(e,t){try{return Z(e)===Z(t)}catch{return!1}}a(ve,"sameDirectory");async function Ft(e,t={}){const n=e.params.id,r=e.body;let o;if(r===void 0)o={};else if(typeof r=="object"&&r!==null&&!Array.isArray(r))o=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(o.profile!==void 0){if(typeof o.profile!="string"||o.profile==="")throw new w({error:"profile_invalid",message:"profile must be a non-empty profile id or name",received:o.profile,field:"profile",next:"Send a profile id or exact name."});if(Object.keys(o).some(u=>u!=="profile"&&u!=="restart"&&o[u]!==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 i=y(n),l=Fn(e,o.profile);Gn(l.profileId);const p=Bn(l.profileId).manifest.grantee??"app:terminal";if(p!==(i.grantee??"app:terminal"))throw new w({error:"profile_grantee_mismatch",message:`profile ${l.profileId} belongs to ${p}, node ${n} to ${i.grantee}`,received:o.profile,field:"profile",next:"Pick a profile owned by the same app as the node."});return(i.profile_id??null)!==l.profileId&&(jn(i.kind)?(await z(i.kind,i.cwd,l.profileId),await V(n,{profileId:l.profileId})):C(n,{profile_id:l.profileId}),A(e,n,["profile"])),o.restart===!0&&be(n),{status:200,body:g(n)}}if(Object.prototype.hasOwnProperty.call(o,"cwd")){const i=o.cwd;if(typeof i!="string"||i==="")throw new w({error:"cwd_invalid",message:"cwd must be a non-empty string",received:i,field:"cwd",next:"Send a non-empty absolute cwd string."});if(Object.keys(o).some(f=>f!=="cwd"&&f!=="keep_session"&&f!=="restart"&&o[f]!==void 0))throw new w({error:"cwd_not_exclusive",message:"cwd repair cannot be combined with another config field",received:o,field:"cwd",next:"Send cwd as the only config field."});const l=y(n),p=N(l.cwd);if(o.keep_session===!0||p&&G(i)&&N(i)&&ve(l.cwd,i)){if(!G(i))throw new w({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${i}`,received:i,field:"cwd",next:"Send an absolute path."});const f=T(i);let _=!1;try{_=q(f).isDirectory()}catch{}if(!_)throw new w({error:"cwd_missing",message:`cwd is not an existing directory: ${f}`,received:i,field:"cwd",next:"Send an existing absolute directory."});if(p&&!ve(l.cwd,f))throw new w({error:"cwd_not_same_directory",message:`${f} is not the same directory as the recorded ${l.cwd}; --keep-session only relocates an alias`,received:i,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:`${n} owns an open managed worktree and cannot relocate its cwd`,received:i,field:"cwd",next:"Reconcile the managed worktree first."});const S=l.cwd;return S!==f&&(K(I=>{C(n,{cwd:f}),X(I,"UPDATE crons SET cwd = ? WHERE anchor_node = ? AND cwd = ?").run(f,n,S),Ue(n,S,f)}),A(e,n,["cwd"])),o.restart===!0&&be(n),{status:200,body:g(n)}}if(E().has(n)){const f=`${n} cannot repair its cwd while its broker is live`;throw new m(409,"cwd_node_live",f,{error:"cwd_node_live",message:f,received:i,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:`${n} is a fork and cannot repair its cwd; recorded cwd: ${l.cwd}`,received:i,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:`${n} owns an open managed worktree and cannot repair its cwd`,received:i,field:"cwd",next:"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon flow."});if(N(l.cwd))throw new w({error:"cwd_still_present",message:`${n} recorded cwd still exists: ${l.cwd}; cwd repair is not a relocation command`,received:i,field:"cwd",next:"This command only repairs a node whose recorded cwd is gone."});if(!G(i))throw new w({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${i}`,received:i,field:"cwd",next:"Send an absolute path."});const u=T(i);if(!N(u))throw new w({error:"cwd_missing",message:`cwd does not exist: ${u}`,received:i,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."});try{if(!q(u).isDirectory())throw new w({error:"cwd_not_a_directory",message:`cwd is not a directory: ${u}`,received:i,field:"cwd",next:"Send an existing absolute directory."})}catch(f){throw f instanceof w?f:new w({error:"cwd_missing",message:`cwd does not exist: ${u}`,received:i,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."})}return K(()=>{C(n,{cwd:u}),Ye(n)}),A(e,n,["cwd"]),{status:200,body:g(n)}}let s=y(n);const d=o.listen===void 0?void 0:Mt(o.listen);if(o.scopes!==void 0){const i=pe(o.scopes),l=s.grantee==="app:terminal"?nt():s.grant_id?et(s.grant_id):null,p=s.grantee==="app:terminal"&&!tt("user").runtime?.issuer;if(!i.every(u=>O(s.scopes,u)&&(l?O(l.resolved,u):p)))throw new w({error:"unknown_scope",message:"scopes may only narrow the node's current effective set",received:i,field:"scopes",next:"Send only scopes the node currently holds."});if(i.includes("crtr:act")&&!O(i,"crtr:llm"))throw new m(400,"invalid_scope","crtr:act requires crtr:llm");s=C(n,{scopes:i})}if(o.situational_context!==void 0&&$e(n,Ae(o.situational_context)),o.model!==void 0){const i=(await se(s.cwd,s.profile_id??null)).modelLadders,l=vn(o.model,i),p=kn(o.model,i);await x({kind:"concrete",spec:p},{cwd:s.cwd,profileId:s.profile_id??null},t.modelRegistry);const u=E();let f=!1;if(u.isClaimed(n)&&await ae(n,u.get(n)?.handle.exited)&&(f=await On(n,p,l).then(()=>!0,_=>{if(_ instanceof In)return!1;throw _})),!f){if(u.isClaimed(n)){const _=`${n}'s broker did not accept the model switch; the model was not changed`;throw new m(409,"broker_not_ready",_,{error:"broker_not_ready",message:_,received:o.model,field:"model",next:"Check the node with `crtr node show`, then retry the model change."})}if(!p.includes("/"))throw h(`model must resolve to a provider/id spec: ${o.model}`);Rn(n,p,l)}s=y(n)}if(o.kind!==void 0||o.mode!==void 0||o.lifecycle!==void 0){o.kind!==void 0&&await Se(o.kind);const i=o.kind??s.kind,l=o.mode??s.mode,p=o.lifecycle??s.lifecycle;let u;l==="orchestrator"&&!_n(n)&&(u=a(()=>{const f=wn(n);yn(n,f!==null&&f.trim()!==""?{goal:f.trim()}:{})},"beforePersist")),s=await V(n,{...o.kind!==void 0?{kind:i}:{},...o.mode!==void 0?{mode:l}:{},...o.lifecycle!==void 0?{lifecycle:p}:{}},u)}o.name!==void 0&&(s=C(n,{name:o.name}),s.window&&gn(s.window,Mn(s)));const c=["scopes","situational_context","model","kind","mode","lifecycle","name","listen"].filter(i=>o[i]!==void 0);return A(e,n,c,d===void 0?void 0:i=>{X(i,"UPDATE objects SET listen_json = ? WHERE id = ? AND type = 'node'").run(d,n)}),{status:200,body:g(n)}}a(Ft,"handleConfig");async function ke(){return(await se(process.cwd(),Oe()||null)).kinds}a(ke,"daemonKinds");async function Se(e){const t=Object.keys(await ke());if(!t.includes(e))throw h(`unknown kind: ${e}`,{received:e,next:`Valid kinds: ${t.sort().join(", ")}.`})}a(Se,"assertKindServer");async function Gt(){const e=await ke();return{status:200,body:{kinds:Object.keys(e).sort().map(n=>({kind:n,when_to_use:e[n]?.whenToUse??null,available_to:e[n]?.availableTo??null}))}}}a(Gt,"handleListKinds");const tr=[{method:"POST",pattern:"/v1/nodes",scope:"crtr:act",handler:ut},{method:"GET",pattern:"/v1/nodes",handler:ht},{method:"GET",pattern:"/v1/kinds",handler:a(()=>Gt(),"handler")},{method:"POST",pattern:"/v1/nodes/revive-all",scope:"crtr:act",handler:jt},{method:"GET",pattern:"/v1/nodes/:id",handler:wt},{method:"GET",pattern:"/v1/nodes/:id/snapshot",handler:yt},{method:"GET",pattern:"/v1/nodes/:id/subject",handler:_t},{method:"GET",pattern:"/v1/nodes/:id/messages",handler:bt},{method:"GET",pattern:"/v1/nodes/:id/session",handler:vt},{method:"GET",pattern:"/v1/nodes/:id/transcript",handler:kt},{method:"GET",pattern:"/v1/nodes/:id/context",handler:St},{method:"POST",pattern:"/v1/nodes/:id/fork",scope:"crtr:act",handler:Ot},{method:"POST",pattern:"/v1/nodes/:id/revive",scope:"crtr:act",handler:$t},{method:"POST",pattern:"/v1/nodes/:id/relaunch-root",scope:"crtr:act",handler:At},{method:"POST",pattern:"/v1/nodes/:id/close",handler:Ct},{method:"POST",pattern:"/v1/nodes/:id/recycle",scope:"crtr:act",handler:Nt},{method:"POST",pattern:"/v1/nodes/:id/demote",scope:"crtr:act",handler:Tt},{method:"POST",pattern:"/v1/nodes/:id/promote",scope:"crtr:act",handler:Et},{method:"POST",pattern:"/v1/nodes/:id/yield",scope:"crtr:act",handler:Pt},{method:"POST",pattern:"/v1/nodes/:id/wait",handler:Dt},{method:"PATCH",pattern:"/v1/nodes/:id/config",handler:Ft}];export{Ft as handleConfig,ut as handleCreate,Ot as handleFork,ht as handleList,Et as handlePromote,Pt as handleYield,tr as nodeRoutes,ir as resolveCreateKind};
|
package/dist/daemon/api/map.d.ts
CHANGED
|
@@ -80,7 +80,7 @@ export declare function toNodeDetailDTO(meta: NodeMeta, edges: NodeEdgesInput):
|
|
|
80
80
|
* actually happened — the double-revive no-op (already-alive) returns without a
|
|
81
81
|
* `launch` handle, so its absence is the "nothing relaunched" signal. `status`
|
|
82
82
|
* is the caller's post-revive row read. */
|
|
83
|
-
export declare function toReviveResultDTO(nodeId: string, result: ReviveResult, status: NodeStatusDTO): ReviveResultDTO;
|
|
83
|
+
export declare function toReviveResultDTO(nodeId: string, result: ReviveResult, status: NodeStatusDTO, ready: boolean): ReviveResultDTO;
|
|
84
84
|
/** Project a `closeNode` cascade result. Field names align 1:1. */
|
|
85
85
|
export declare function toCloseResultDTO(result: CloseNodeResult): CloseResultDTO;
|
|
86
86
|
/** Project a feed `push` result into a push-report result. `transitioned` is
|
package/dist/daemon/api/map.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var g=Object.defineProperty;var r=(e,t)=>g(e,"name",{value:t,configurable:!0});import{join as h}from"node:path";import{readOutputResult as b}from"../../core/runtime/structured-output.js";import{ReviewOperationError as _}from"../../core/review/types.js";import{cronSinkDisplay as y}from"../../core/canvas/crons.js";import{isProfilePaused as c,profileDir as x,sanitizeProfileMetadata as O}from"../../core/profiles/manifest.js";import{nodeMetaPath as D,transcriptPath as T,viewSocketPath as E}from"../../core/canvas/paths.js";import{appForNode as f,contextDir as S,nodeAgentDir as A}from"../../core/canvas/node-agent-paths.js";import{FinalizationError as R}from"../../core/feed/feed.js";import{NodeIdConflictError as z}from"../../core/runtime/nodes.js";import{ScopeDeniedError as N}from"../../core/scopes.js";import{isBeneathRefusal as C}from"../../core/spaces/open-beneath.js";import{CrtrError as s}from"../../core/errors.js";import{WorktreeError as j}from"../../core/worktree.js";import{ApiError as q}from"../../api/errors.js";import{RunError as l}from"../../core/runs/operations.js";import{ExitCode as o}from"../../types.js";function ce(e,t){const{report:n}=e;return{stores:n.stores.map(i=>({root:i.root,owner:{...i.owner},docs:i.docs,...i.skipped===void 0?{}:{skipped:i.skipped}})),counts:n.counts,rewrites:n.rewrites,dropped_fields:n.droppedFields,skipped:n.skipped,resolutions:n.resolutions.map(i=>({kind:i.kind,message:i.message,paths:i.paths})),blockers:e.blockers.map(i=>({kind:i.kind,message:i.message,paths:i.paths})),dryRun:e.dryRun,pending:e.pending,resumed:t.resumed,...t.resumeError===void 0?{}:{resume_error:t.resumeError}}}r(ce,"toMigrateStateDTO");function F(e,t){try{return b(e,t)??null}catch{return null}}r(F,"readStructuredResult");function I(e){return e.outcome_at===null||e.outcome_at===void 0||e.outcome_kind===null||e.outcome_kind===void 0||e.outcome_reason===null||e.outcome_reason===void 0?null:{kind:e.outcome_kind,reason:e.outcome_reason,settled_at:e.outcome_at}}r(I,"toNodeOutcomeSummaryDTO");function p(e){if(e.outcome_at===null||e.outcome_at===void 0||e.outcome_kind===null||e.outcome_kind===void 0||e.outcome_reason===null||e.outcome_reason===void 0)return null;let t=null;if(e.outcome_detail_json!==null&&e.outcome_detail_json!==void 0)try{t=JSON.parse(e.outcome_detail_json)}catch{t=null}const n=e.final_report??null,i={node_id:e.node_id,revision:e.outcome_revision??1,settled_at:e.outcome_at,final_report:n===null?null:`${e.node_id}/${n}`,structured_result:e.outcome_kind==="result"?F(e.node_id,e.grantee):null,detail:t};return e.outcome_kind==="result"?{...i,kind:"result",reason:e.outcome_reason,declined:null}:e.outcome_reason==="declined"?{...i,kind:"failure",reason:"declined",declined:t?.declined??null}:{...i,kind:"failure",reason:e.outcome_reason,declined:null}}r(p,"toNodeOutcomeDTO");function fe(e){const t=p(e);return t===null||t.reason==="parked"?null:t.kind==="result"||t.reason==="finished"?{...t,kind:"result",reason:"finalized",declined:null}:t.reason==="declined"?{...t,reason:"declined",details:t.declined}:t.reason==="deadline_exceeded"?{...t,reason:"deadline_exceeded",declined:null}:t.reason==="cap_exhausted"?{...t,reason:"cap_exhausted",declined:null}:t.reason==="closed"||t.reason==="stranded"||t.reason==="retired"?{...t,reason:"canceled",declined:null}:{...t,reason:"runtime_error",declined:null,details:{crouter_reason:t.reason}}}r(fe,"toRunOutcomeDTO");function pe(e){const t=e.lastFailure;return{node_id:e.nodeId,state:e.state,action:e.actionName,attempt:e.attempt,next_attempt_at:e.nextAttemptAt===0?null:new Date(e.nextAttemptAt).toISOString(),accepted_at:e.acceptedAt===null?null:new Date(e.acceptedAt).toISOString(),permanent_failed_at:e.permanentFailedAt===null?null:new Date(e.permanentFailedAt).toISOString(),last_failure:t===null?null:{kind:t.kind,...t.exitCode===void 0?{}:{exit_code:t.exitCode},...t.signal===void 0?{}:{signal:t.signal},...t.message===void 0?{}:{message:t.message}},created_at:new Date(e.createdAt).toISOString(),updated_at:new Date(e.updatedAt).toISOString()}}r(pe,"toOutcomeDeliveryDTO");function me(e){return{node_id:e.node_id,name:e.name,description:e.description,cycles:e.cycles,kind:e.kind,status:e.status,frozen_at:e.frozen_at,pi_pid:e.pi_pid,telemetry_context_tokens:e.telemetry_context_tokens,telemetry_last_activity:e.telemetry_last_activity,fault:e.fault&&e.fault.link!=="broker\u2194crtrd"?{...e.fault,link:e.fault.link}:null,streaming:e.streaming}}r(me,"toGraphNodeDTO");function ve(e,t=c(e.profile_id)){return{node_id:e.node_id,name:e.name,description:e.description,cycles:e.cycles,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind,profile_id:e.profile_id,scopes:e.scopes,isolated:e.isolated,grantee:e.grantee??f(e.node_id),profile_paused:t,parent:e.parent,created:e.created,intent:e.intent,waiting_for:e.waiting_for,frozen_at:e.frozen_at??null,terminal_reason:e.terminal_reason??null,pi_pid:e.pi_pid,pi_pid_identity:e.pi_pid_identity,window:e.window,tmux_session:e.tmux_session,pane:e.pane,final_report:e.final_report??null,finalized_at:e.finalized_at??null,deadline_at:e.deadline_at??null,telemetry_tokens_in:e.telemetry_tokens_in??null,telemetry_context_tokens:e.telemetry_context_tokens??null,telemetry_last_activity:e.telemetry_last_activity??null,telemetry_updated_at:e.telemetry_updated_at??null,outcome:I(e),fault:e.fault&&e.fault.link!=="broker\u2194crtrd"?{...e.fault,link:e.fault.link}:null,streaming:e.streaming??!1}}r(ve,"toNodeSummaryDTO");function P(e,t){return{parent:e.parent??null,spawned_by:e.spawned_by??null,subscribes_to:t.subscribesTo.map(n=>n.node_id),subscribers:t.subscribers.map(n=>n.node_id),children:[...t.children]}}r(P,"toNodeEdgesDTO");function U(e,t){return{node_dir:A(e,t),context_dir:S(e,t),meta_path:D(e),transcript_path:T(e),view_socket:E(e)}}r(U,"toNodePathsDTO");function G(e){const t={state:e.state,path:e.path,branch:e.branch,repo_root:e.repo_root,base_ref:e.base_ref,base_sha:e.base_sha,created:e.created};return e.cleanup!==void 0&&(t.cleanup=e.cleanup),e.closed!==void 0&&(t.closed=e.closed),e.abandoned!==void 0&&(t.abandoned={...e.abandoned}),t}r(G,"toNodeWorktreeDTO");function ke(e,t){const n=f(e.node_id),i={node_id:e.node_id,name:e.name,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind??null,profile_id:e.profile_id??null,scopes:e.scopes??null,isolated:e.isolated===!0,grantee:n,profile_paused:c(e.profile_id),parent:e.parent??null,created:e.created,intent:e.intent??null,waiting_for:e.waiting_for??null,frozen_at:e.frozen_at??null,terminal_reason:e.terminal_reason??null,pi_pid:e.pi_pid??null,pi_pid_identity:e.pi_pid_identity??null,window:e.window??null,tmux_session:e.tmux_session??null,pane:e.pane??null,final_report:e.final_report??null,finalized_at:e.finalized_at??null,deadline_at:e.deadline_at??null,telemetry_tokens_in:e.telemetry_tokens_in??null,telemetry_context_tokens:e.telemetry_context_tokens??null,telemetry_last_activity:e.telemetry_last_activity??null,telemetry_updated_at:e.telemetry_updated_at??null,outcome:p(e),fault:e.fault&&e.fault.link!=="broker\u2194crtrd"?{...e.fault,link:e.fault.link}:null,streaming:e.streaming??!1,creator:e.creator??null,edges:P(e,t),paths:U(e.node_id,n)};return e.description!==void 0&&(i.description=e.description),e.title!==void 0&&(i.title=e.title),e.icon!==void 0&&(i.icon=e.icon),e.cycles!==void 0&&(i.cycles=e.cycles),i.context_tokens=e.telemetry_context_tokens??e.telemetry_tokens_in??null,e.pi_session_id!==void 0&&(i.pi_session_id=e.pi_session_id??null),i.model_override=e.model_override??null,e.pi_session_file!==void 0&&(i.pi_session_file=e.pi_session_file??null),e.review_binding!==void 0&&(i.review_binding=e.review_binding===null?null:{...e.review_binding.kind===void 0?{}:{kind:e.review_binding.kind},review_id:e.review_binding.review_id,origin_node_id:e.review_binding.origin_node_id,branch_file:e.review_binding.branch_file,target_file:e.review_binding.target_file}),e.managed_worktree!=null&&(i.worktree=G(e.managed_worktree)),i}r(ke,"toNodeDetailDTO");function ge(e,t,n){return{node_id:e,revived:t.launch!==void 0,resumed:t.resumed,status:n,outcome:t.outcome}}r(ge,"toReviveResultDTO");function he(e){return{root:e.root,closed:[...e.closed],spared:[...e.spared]}}r(he,"toCloseResultDTO");function be(e,t,n){const i={report:e.report,notified:[...e.deliveredTo]};return t!==void 0&&(i.transitioned=t),n!==void 0&&(i.worktree_auto_dropped=!0,i.worktree_auto_dropped_path=n),i}r(be,"toReportResultDTO");function ye(e){return{node_id:e.node_id,active:e.active,created:e.created}}r(ye,"toSubscriptionDTO");function M(e){if(e===null||e==="")return[];try{const t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?Object.keys(t):[]}catch{return[]}}r(M,"envKeys");function xe(e,t){return{cron_id:e.cron_id,name:e.name,created_by:e.created_by,command:e.command,grant_id:e.grant_id,scopes:e.scopes,origin_run_id:e.origin_run_id,isolated:e.isolated,fire_at:e.fire_at,recur:e.recur,tz:e.tz,expires_at:e.expires_at,anchor_node:e.anchor_node,cancel_on_wake:e.cancel_on_wake,cwd:e.cwd,profile:e.profile,scope:e.scope,env_keys:M(e.env_json),run_timeout_s:e.run_timeout_s,overlap:e.overlap,on_output:e.on_output,sink:y(e.sink),tier:e.tier,state:e.state,held:e.held,run_state:e.run_state,last_run:t==null?null:{finished:t.finished,exit_code:t.exit_code,delivered:t.delivered},created:e.created,updated:e.updated}}r(xe,"toCronDTO");function Oe(e){return{run_id:e.run_id,started:e.started,finished:e.finished,duration_ms:e.duration_ms,exit_code:e.exit_code,stdout_head:e.stdout_head,stderr_head:e.stderr_head,delivered:e.delivered}}r(Oe,"toCronRunDTO");function De(e){return{id:e.profileId,app:e.manifest.grantee??"app:terminal",name:e.manifest.name,projects:e.manifest.projects.map(t=>({...t})),delivery_limits:{...e.manifest.delivery_limits},paused_at:e.manifest.paused_at,default_kind:e.manifest.default_kind??"general",metadata:O(e.manifest.metadata),default_dir:null,created_at:e.manifest.created_at,last_used_at:e.manifest.last_used_at,profile_path:x(e.profileId)}}r(De,"toProfileDTO");function m(e,t={}){const n={review_id:e.review_id,origin_kind:e.origin_kind,origin_node_id:e.origin_node_id,review_dir:e.review_dir,companion_node_id:e.companion_node_id,file:e.file,state:e.state,created:e.created,source_missing:e.source_missing,anchor_base_sha256:e.anchor_base_sha256};return e.document_name!==null&&(n.document=e.document_name),e.opened_at!==null&&(n.opened_at=e.opened_at),e.submit_requested_at!==null&&(n.submit_requested_at=e.submit_requested_at),e.approved_at!==null&&(n.approved_at=e.approved_at),e.changed!==null&&(n.changed=e.changed),e.comments_total!==null&&(n.comments_total=e.comments_total),e.comments_unresolved!==null&&(n.comments_unresolved=e.comments_unresolved),e.canceled_at!==null&&(n.canceled_at=e.canceled_at),e.cancel_reason!==null&&(n.cancel_reason=e.cancel_reason),e.cancel_actor!==null&&(n.cancel_actor=e.cancel_actor),t.result_path!==void 0&&(n.result_path=t.result_path),e.delivery_error!==null&&(n.delivery_error=e.delivery_error),e.projection_error!==null&&(n.projection_error=e.projection_error),n}r(m,"toReviewDTO");function Te(e){return{comment_id:e.comment_id,review_id:e.review_id,status:e.status,revision:e.revision,text:e.text,anchor:{...e.anchor},anchor_state:e.anchor_state,anchor_line_text:e.anchor_line_text,anchor_doc_hash:e.anchor_doc_hash,author:{kind:e.author.kind,...e.author.node_id===null?{}:{node_id:e.author.node_id}},updated_by:{kind:e.updated_by.kind,...e.updated_by.node_id===null?{}:{node_id:e.updated_by.node_id}},created_at:e.created_at,updated_at:e.updated_at,...e.resolved_at===null?{}:{resolved_at:e.resolved_at},...e.deleted_at===null?{}:{deleted_at:e.deleted_at},created_seq:e.created_seq}}r(Te,"toReviewCommentDTO");function B(e){return{id:e.id,quote:e.quote,...e.context===void 0?{}:{context:e.context},note:e.note,status:e.status,created_at:e.createdAt,...e.resolvedAt===void 0?{}:{resolved_at:e.resolvedAt}}}r(B,"toPageFeedbackCommentDTO");function Ee(e){return{companion_node_id:e.companionNodeId??null,open_count:e.comments.filter(t=>t.status==="open").length,comments:e.comments.map(B)}}r(Ee,"toPageFeedbackDTO");function Se(e){return{seq:e.seq,review_id:e.review_id,comment_id:e.comment_id,kind:e.kind,state_change:e.state_change===1,revision_after:e.revision_after,actor:{kind:e.actor.kind,...e.actor.node_id===null?{}:{node_id:e.actor.node_id}},at:e.at,operation_id:e.operation_id,...e.payload===void 0?{}:{payload:e.payload}}}r(Se,"toReviewCommentEventDTO");function Ae(e){return{file:e.file,submitted:e.submitted,approved:e.approved,comments:e.comments.map(n=>({...n})),submittedAt:e.submittedAt,savedAt:e.savedAt,reviewId:e.review_id,changed:e.changed,baselineSha256:e.baseline_sha256,approvedSha256:e.approved_sha256,companionNodeId:e.companion_node_id,commentsTotal:e.comments_total,commentsUnresolved:e.comments_unresolved}}r(Ae,"toFeedbackResultDTO");const L=!0,W=Object.freeze({review_origin_missing:{status:400,code:"review_origin_unavailable"},review_origin_unforkable:{status:400,code:"review_origin_unavailable"},review_branch_unavailable:{status:409,code:"review_branch_unavailable"},branch_lost:{status:409,code:"review_branch_unavailable"},review_companion_unbound:{status:409,code:"review_companion_unbound"},review_bridge_unsubscribed:{status:409,code:"review_bridge_unavailable"},review_target_unreviewable:{status:400,code:"review_file_unreadable"},source_unreadable:{status:409,code:"review_source_unreadable"},delivery_unroutable:{status:409,code:"review_delivery_unroutable"},unknown_review:{status:404,code:"unknown_review"},review_terminal:{status:409,code:"review_terminal_conflict"},review_required:{status:400,code:"review_required"},stale_document:{status:409,code:"stale_document"},stale_revision:{status:409,code:"stale_revision"},unknown_comment:{status:404,code:"unknown_comment"},comment_deleted:{status:409,code:"comment_deleted"},invalid_anchor:{status:400,code:"invalid_anchor"},anchor_out_of_range:{status:400,code:"anchor_out_of_range"},text_too_long:{status:400,code:"text_too_long"},comment_limit_reached:{status:409,code:"comment_limit_reached"},stale_comment:{status:409,code:"stale_comment"},range_batch_incomplete:{status:409,code:"range_batch_incomplete"},range_batch_stale:{status:409,code:"range_batch_stale"}});function $(e){const t=v(e);if(typeof t=="object"&&t!==null&&typeof t.status=="number"&&typeof t.code=="string")return{status:t.status,code:t.code};if(t instanceof R)return t.code==="unknown_node"?{status:404,code:"node_not_found"}:t.code==="already_finalized"?{status:409,code:"already_finalized"}:{status:409,code:"finalization_forbidden"};if(t instanceof z)return{status:409,code:"node_id_exists"};if(t instanceof N)return{status:403,code:"scope_denied"};if(C(t))return{status:400,code:"invalid_request"};if(t instanceof _)return W[t.code];if(t instanceof s)return["kind_owned","name_taken","hop_limit","not_a_queue"].includes(t.code)?{status:409,code:t.code}:t.code==="invalid_publish_token"?{status:401,code:t.code}:t.code==="forbidden"||t.code==="argv_forbidden"||t.code==="scope_missing"?{status:403,code:t.code}:{status:H(t.exitCode),code:t.code};if(t instanceof Error){const n=t.message;if(/unknown node/i.test(n))return{status:404,code:"node_not_found"};if(/finalization latch/i.test(n))return{status:409,code:"already_finalized"};if(/illegal lifecycle transition/i.test(n))return{status:409,code:"illegal_transition"}}return{status:500,code:"internal"}}r($,"errorToStatus");function v(e){if(!(e instanceof j))return e;const t=e.code==="unknown_node"?o.NOT_FOUND:o.GENERAL,n={error:e.code,message:e.message,next:e.next};return e.detail!==void 0&&(n.received=e.detail),new s(e.code,e.message,t,n)}r(v,"normalizeThrow");function K(e){if(e.code!=="review_terminal")return e.detail;const{review:t,...n}=e.detail;return{...n,review:V(t)}}r(K,"reviewErrorDetails");function V(e){return e.state!=="approved"?m(e):m(e,{result_path:h(e.review_dir,"result.json")})}r(V,"terminalConflictReviewDTO");function H(e){switch(e){case o.NOT_FOUND:return 404;case o.USAGE:return 400;case o.AMBIGUOUS:return 400;case o.NETWORK:return 503;case o.GENERAL:return 400;default:return 500}}r(H,"statusForExitCode");function J(e){const n=(e instanceof Error?e.message:String(e)).split(`
|
|
1
|
+
var g=Object.defineProperty;var r=(e,t)=>g(e,"name",{value:t,configurable:!0});import{join as h}from"node:path";import{readOutputResult as b}from"../../core/runtime/structured-output.js";import{ReviewOperationError as _}from"../../core/review/types.js";import{cronSinkDisplay as y}from"../../core/canvas/crons.js";import{isProfilePaused as c,profileDir as x,sanitizeProfileMetadata as O}from"../../core/profiles/manifest.js";import{nodeMetaPath as D,transcriptPath as T,viewSocketPath as E}from"../../core/canvas/paths.js";import{appForNode as f,contextDir as S,nodeAgentDir as A}from"../../core/canvas/node-agent-paths.js";import{FinalizationError as R}from"../../core/feed/feed.js";import{NodeIdConflictError as z}from"../../core/runtime/nodes.js";import{ScopeDeniedError as N}from"../../core/scopes.js";import{isBeneathRefusal as C}from"../../core/spaces/open-beneath.js";import{CrtrError as s}from"../../core/errors.js";import{WorktreeError as j}from"../../core/worktree.js";import{ApiError as q}from"../../api/errors.js";import{RunError as l}from"../../core/runs/operations.js";import{ExitCode as o}from"../../types.js";function ce(e,t){const{report:n}=e;return{stores:n.stores.map(i=>({root:i.root,owner:{...i.owner},docs:i.docs,...i.skipped===void 0?{}:{skipped:i.skipped}})),counts:n.counts,rewrites:n.rewrites,dropped_fields:n.droppedFields,skipped:n.skipped,resolutions:n.resolutions.map(i=>({kind:i.kind,message:i.message,paths:i.paths})),blockers:e.blockers.map(i=>({kind:i.kind,message:i.message,paths:i.paths})),dryRun:e.dryRun,pending:e.pending,resumed:t.resumed,...t.resumeError===void 0?{}:{resume_error:t.resumeError}}}r(ce,"toMigrateStateDTO");function F(e,t){try{return b(e,t)??null}catch{return null}}r(F,"readStructuredResult");function I(e){return e.outcome_at===null||e.outcome_at===void 0||e.outcome_kind===null||e.outcome_kind===void 0||e.outcome_reason===null||e.outcome_reason===void 0?null:{kind:e.outcome_kind,reason:e.outcome_reason,settled_at:e.outcome_at}}r(I,"toNodeOutcomeSummaryDTO");function p(e){if(e.outcome_at===null||e.outcome_at===void 0||e.outcome_kind===null||e.outcome_kind===void 0||e.outcome_reason===null||e.outcome_reason===void 0)return null;let t=null;if(e.outcome_detail_json!==null&&e.outcome_detail_json!==void 0)try{t=JSON.parse(e.outcome_detail_json)}catch{t=null}const n=e.final_report??null,i={node_id:e.node_id,revision:e.outcome_revision??1,settled_at:e.outcome_at,final_report:n===null?null:`${e.node_id}/${n}`,structured_result:e.outcome_kind==="result"?F(e.node_id,e.grantee):null,detail:t};return e.outcome_kind==="result"?{...i,kind:"result",reason:e.outcome_reason,declined:null}:e.outcome_reason==="declined"?{...i,kind:"failure",reason:"declined",declined:t?.declined??null}:{...i,kind:"failure",reason:e.outcome_reason,declined:null}}r(p,"toNodeOutcomeDTO");function fe(e){const t=p(e);return t===null||t.reason==="parked"?null:t.kind==="result"||t.reason==="finished"?{...t,kind:"result",reason:"finalized",declined:null}:t.reason==="declined"?{...t,reason:"declined",details:t.declined}:t.reason==="deadline_exceeded"?{...t,reason:"deadline_exceeded",declined:null}:t.reason==="cap_exhausted"?{...t,reason:"cap_exhausted",declined:null}:t.reason==="closed"||t.reason==="stranded"||t.reason==="retired"?{...t,reason:"canceled",declined:null}:{...t,reason:"runtime_error",declined:null,details:{crouter_reason:t.reason}}}r(fe,"toRunOutcomeDTO");function pe(e){const t=e.lastFailure;return{node_id:e.nodeId,state:e.state,action:e.actionName,attempt:e.attempt,next_attempt_at:e.nextAttemptAt===0?null:new Date(e.nextAttemptAt).toISOString(),accepted_at:e.acceptedAt===null?null:new Date(e.acceptedAt).toISOString(),permanent_failed_at:e.permanentFailedAt===null?null:new Date(e.permanentFailedAt).toISOString(),last_failure:t===null?null:{kind:t.kind,...t.exitCode===void 0?{}:{exit_code:t.exitCode},...t.signal===void 0?{}:{signal:t.signal},...t.message===void 0?{}:{message:t.message}},created_at:new Date(e.createdAt).toISOString(),updated_at:new Date(e.updatedAt).toISOString()}}r(pe,"toOutcomeDeliveryDTO");function me(e){return{node_id:e.node_id,name:e.name,description:e.description,cycles:e.cycles,kind:e.kind,status:e.status,frozen_at:e.frozen_at,pi_pid:e.pi_pid,telemetry_context_tokens:e.telemetry_context_tokens,telemetry_last_activity:e.telemetry_last_activity,fault:e.fault&&e.fault.link!=="broker\u2194crtrd"?{...e.fault,link:e.fault.link}:null,streaming:e.streaming}}r(me,"toGraphNodeDTO");function ve(e,t=c(e.profile_id)){return{node_id:e.node_id,name:e.name,description:e.description,cycles:e.cycles,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind,profile_id:e.profile_id,scopes:e.scopes,isolated:e.isolated,grantee:e.grantee??f(e.node_id),profile_paused:t,parent:e.parent,created:e.created,intent:e.intent,waiting_for:e.waiting_for,frozen_at:e.frozen_at??null,terminal_reason:e.terminal_reason??null,pi_pid:e.pi_pid,pi_pid_identity:e.pi_pid_identity,window:e.window,tmux_session:e.tmux_session,pane:e.pane,final_report:e.final_report??null,finalized_at:e.finalized_at??null,deadline_at:e.deadline_at??null,telemetry_tokens_in:e.telemetry_tokens_in??null,telemetry_context_tokens:e.telemetry_context_tokens??null,telemetry_last_activity:e.telemetry_last_activity??null,telemetry_updated_at:e.telemetry_updated_at??null,outcome:I(e),fault:e.fault&&e.fault.link!=="broker\u2194crtrd"?{...e.fault,link:e.fault.link}:null,streaming:e.streaming??!1}}r(ve,"toNodeSummaryDTO");function P(e,t){return{parent:e.parent??null,spawned_by:e.spawned_by??null,subscribes_to:t.subscribesTo.map(n=>n.node_id),subscribers:t.subscribers.map(n=>n.node_id),children:[...t.children]}}r(P,"toNodeEdgesDTO");function U(e,t){return{node_dir:A(e,t),context_dir:S(e,t),meta_path:D(e),transcript_path:T(e),view_socket:E(e)}}r(U,"toNodePathsDTO");function G(e){const t={state:e.state,path:e.path,branch:e.branch,repo_root:e.repo_root,base_ref:e.base_ref,base_sha:e.base_sha,created:e.created};return e.cleanup!==void 0&&(t.cleanup=e.cleanup),e.closed!==void 0&&(t.closed=e.closed),e.abandoned!==void 0&&(t.abandoned={...e.abandoned}),t}r(G,"toNodeWorktreeDTO");function ke(e,t){const n=f(e.node_id),i={node_id:e.node_id,name:e.name,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind??null,profile_id:e.profile_id??null,scopes:e.scopes??null,isolated:e.isolated===!0,grantee:n,profile_paused:c(e.profile_id),parent:e.parent??null,created:e.created,intent:e.intent??null,waiting_for:e.waiting_for??null,frozen_at:e.frozen_at??null,terminal_reason:e.terminal_reason??null,pi_pid:e.pi_pid??null,pi_pid_identity:e.pi_pid_identity??null,window:e.window??null,tmux_session:e.tmux_session??null,pane:e.pane??null,final_report:e.final_report??null,finalized_at:e.finalized_at??null,deadline_at:e.deadline_at??null,telemetry_tokens_in:e.telemetry_tokens_in??null,telemetry_context_tokens:e.telemetry_context_tokens??null,telemetry_last_activity:e.telemetry_last_activity??null,telemetry_updated_at:e.telemetry_updated_at??null,outcome:p(e),fault:e.fault&&e.fault.link!=="broker\u2194crtrd"?{...e.fault,link:e.fault.link}:null,streaming:e.streaming??!1,creator:e.creator??null,edges:P(e,t),paths:U(e.node_id,n)};return e.description!==void 0&&(i.description=e.description),e.title!==void 0&&(i.title=e.title),e.icon!==void 0&&(i.icon=e.icon),e.cycles!==void 0&&(i.cycles=e.cycles),i.context_tokens=e.telemetry_context_tokens??e.telemetry_tokens_in??null,e.pi_session_id!==void 0&&(i.pi_session_id=e.pi_session_id??null),i.model_override=e.model_override??null,e.pi_session_file!==void 0&&(i.pi_session_file=e.pi_session_file??null),e.review_binding!==void 0&&(i.review_binding=e.review_binding===null?null:{...e.review_binding.kind===void 0?{}:{kind:e.review_binding.kind},review_id:e.review_binding.review_id,origin_node_id:e.review_binding.origin_node_id,branch_file:e.review_binding.branch_file,target_file:e.review_binding.target_file}),e.managed_worktree!=null&&(i.worktree=G(e.managed_worktree)),i}r(ke,"toNodeDetailDTO");function ge(e,t,n,i){return{node_id:e,revived:t.launch!==void 0,resumed:t.resumed,status:n,outcome:t.outcome,ready:i}}r(ge,"toReviveResultDTO");function he(e){return{root:e.root,closed:[...e.closed],spared:[...e.spared]}}r(he,"toCloseResultDTO");function be(e,t,n){const i={report:e.report,notified:[...e.deliveredTo]};return t!==void 0&&(i.transitioned=t),n!==void 0&&(i.worktree_auto_dropped=!0,i.worktree_auto_dropped_path=n),i}r(be,"toReportResultDTO");function ye(e){return{node_id:e.node_id,active:e.active,created:e.created}}r(ye,"toSubscriptionDTO");function M(e){if(e===null||e==="")return[];try{const t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?Object.keys(t):[]}catch{return[]}}r(M,"envKeys");function xe(e,t){return{cron_id:e.cron_id,name:e.name,created_by:e.created_by,command:e.command,grant_id:e.grant_id,scopes:e.scopes,origin_run_id:e.origin_run_id,isolated:e.isolated,fire_at:e.fire_at,recur:e.recur,tz:e.tz,expires_at:e.expires_at,anchor_node:e.anchor_node,cancel_on_wake:e.cancel_on_wake,cwd:e.cwd,profile:e.profile,scope:e.scope,env_keys:M(e.env_json),run_timeout_s:e.run_timeout_s,overlap:e.overlap,on_output:e.on_output,sink:y(e.sink),tier:e.tier,state:e.state,held:e.held,run_state:e.run_state,last_run:t==null?null:{finished:t.finished,exit_code:t.exit_code,delivered:t.delivered},created:e.created,updated:e.updated}}r(xe,"toCronDTO");function Oe(e){return{run_id:e.run_id,started:e.started,finished:e.finished,duration_ms:e.duration_ms,exit_code:e.exit_code,stdout_head:e.stdout_head,stderr_head:e.stderr_head,delivered:e.delivered}}r(Oe,"toCronRunDTO");function De(e){return{id:e.profileId,app:e.manifest.grantee??"app:terminal",name:e.manifest.name,projects:e.manifest.projects.map(t=>({...t})),delivery_limits:{...e.manifest.delivery_limits},paused_at:e.manifest.paused_at,default_kind:e.manifest.default_kind??"general",metadata:O(e.manifest.metadata),default_dir:null,created_at:e.manifest.created_at,last_used_at:e.manifest.last_used_at,profile_path:x(e.profileId)}}r(De,"toProfileDTO");function m(e,t={}){const n={review_id:e.review_id,origin_kind:e.origin_kind,origin_node_id:e.origin_node_id,review_dir:e.review_dir,companion_node_id:e.companion_node_id,file:e.file,state:e.state,created:e.created,source_missing:e.source_missing,anchor_base_sha256:e.anchor_base_sha256};return e.document_name!==null&&(n.document=e.document_name),e.opened_at!==null&&(n.opened_at=e.opened_at),e.submit_requested_at!==null&&(n.submit_requested_at=e.submit_requested_at),e.approved_at!==null&&(n.approved_at=e.approved_at),e.changed!==null&&(n.changed=e.changed),e.comments_total!==null&&(n.comments_total=e.comments_total),e.comments_unresolved!==null&&(n.comments_unresolved=e.comments_unresolved),e.canceled_at!==null&&(n.canceled_at=e.canceled_at),e.cancel_reason!==null&&(n.cancel_reason=e.cancel_reason),e.cancel_actor!==null&&(n.cancel_actor=e.cancel_actor),t.result_path!==void 0&&(n.result_path=t.result_path),e.delivery_error!==null&&(n.delivery_error=e.delivery_error),e.projection_error!==null&&(n.projection_error=e.projection_error),n}r(m,"toReviewDTO");function Te(e){return{comment_id:e.comment_id,review_id:e.review_id,status:e.status,revision:e.revision,text:e.text,anchor:{...e.anchor},anchor_state:e.anchor_state,anchor_line_text:e.anchor_line_text,anchor_doc_hash:e.anchor_doc_hash,author:{kind:e.author.kind,...e.author.node_id===null?{}:{node_id:e.author.node_id}},updated_by:{kind:e.updated_by.kind,...e.updated_by.node_id===null?{}:{node_id:e.updated_by.node_id}},created_at:e.created_at,updated_at:e.updated_at,...e.resolved_at===null?{}:{resolved_at:e.resolved_at},...e.deleted_at===null?{}:{deleted_at:e.deleted_at},created_seq:e.created_seq}}r(Te,"toReviewCommentDTO");function B(e){return{id:e.id,quote:e.quote,...e.context===void 0?{}:{context:e.context},note:e.note,status:e.status,created_at:e.createdAt,...e.resolvedAt===void 0?{}:{resolved_at:e.resolvedAt}}}r(B,"toPageFeedbackCommentDTO");function Ee(e){return{companion_node_id:e.companionNodeId??null,open_count:e.comments.filter(t=>t.status==="open").length,comments:e.comments.map(B)}}r(Ee,"toPageFeedbackDTO");function Se(e){return{seq:e.seq,review_id:e.review_id,comment_id:e.comment_id,kind:e.kind,state_change:e.state_change===1,revision_after:e.revision_after,actor:{kind:e.actor.kind,...e.actor.node_id===null?{}:{node_id:e.actor.node_id}},at:e.at,operation_id:e.operation_id,...e.payload===void 0?{}:{payload:e.payload}}}r(Se,"toReviewCommentEventDTO");function Ae(e){return{file:e.file,submitted:e.submitted,approved:e.approved,comments:e.comments.map(n=>({...n})),submittedAt:e.submittedAt,savedAt:e.savedAt,reviewId:e.review_id,changed:e.changed,baselineSha256:e.baseline_sha256,approvedSha256:e.approved_sha256,companionNodeId:e.companion_node_id,commentsTotal:e.comments_total,commentsUnresolved:e.comments_unresolved}}r(Ae,"toFeedbackResultDTO");const L=!0,W=Object.freeze({review_origin_missing:{status:400,code:"review_origin_unavailable"},review_origin_unforkable:{status:400,code:"review_origin_unavailable"},review_branch_unavailable:{status:409,code:"review_branch_unavailable"},branch_lost:{status:409,code:"review_branch_unavailable"},review_companion_unbound:{status:409,code:"review_companion_unbound"},review_bridge_unsubscribed:{status:409,code:"review_bridge_unavailable"},review_target_unreviewable:{status:400,code:"review_file_unreadable"},source_unreadable:{status:409,code:"review_source_unreadable"},delivery_unroutable:{status:409,code:"review_delivery_unroutable"},unknown_review:{status:404,code:"unknown_review"},review_terminal:{status:409,code:"review_terminal_conflict"},review_required:{status:400,code:"review_required"},stale_document:{status:409,code:"stale_document"},stale_revision:{status:409,code:"stale_revision"},unknown_comment:{status:404,code:"unknown_comment"},comment_deleted:{status:409,code:"comment_deleted"},invalid_anchor:{status:400,code:"invalid_anchor"},anchor_out_of_range:{status:400,code:"anchor_out_of_range"},text_too_long:{status:400,code:"text_too_long"},comment_limit_reached:{status:409,code:"comment_limit_reached"},stale_comment:{status:409,code:"stale_comment"},range_batch_incomplete:{status:409,code:"range_batch_incomplete"},range_batch_stale:{status:409,code:"range_batch_stale"}});function $(e){const t=v(e);if(typeof t=="object"&&t!==null&&typeof t.status=="number"&&typeof t.code=="string")return{status:t.status,code:t.code};if(t instanceof R)return t.code==="unknown_node"?{status:404,code:"node_not_found"}:t.code==="already_finalized"?{status:409,code:"already_finalized"}:{status:409,code:"finalization_forbidden"};if(t instanceof z)return{status:409,code:"node_id_exists"};if(t instanceof N)return{status:403,code:"scope_denied"};if(C(t))return{status:400,code:"invalid_request"};if(t instanceof _)return W[t.code];if(t instanceof s)return["kind_owned","name_taken","hop_limit","not_a_queue"].includes(t.code)?{status:409,code:t.code}:t.code==="invalid_publish_token"?{status:401,code:t.code}:t.code==="forbidden"||t.code==="argv_forbidden"||t.code==="scope_missing"?{status:403,code:t.code}:{status:H(t.exitCode),code:t.code};if(t instanceof Error){const n=t.message;if(/unknown node/i.test(n))return{status:404,code:"node_not_found"};if(/finalization latch/i.test(n))return{status:409,code:"already_finalized"};if(/illegal lifecycle transition/i.test(n))return{status:409,code:"illegal_transition"}}return{status:500,code:"internal"}}r($,"errorToStatus");function v(e){if(!(e instanceof j))return e;const t=e.code==="unknown_node"?o.NOT_FOUND:o.GENERAL,n={error:e.code,message:e.message,next:e.next};return e.detail!==void 0&&(n.received=e.detail),new s(e.code,e.message,t,n)}r(v,"normalizeThrow");function K(e){if(e.code!=="review_terminal")return e.detail;const{review:t,...n}=e.detail;return{...n,review:V(t)}}r(K,"reviewErrorDetails");function V(e){return e.state!=="approved"?m(e):m(e,{result_path:h(e.review_dir,"result.json")})}r(V,"terminalConflictReviewDTO");function H(e){switch(e){case o.NOT_FOUND:return 404;case o.USAGE:return 400;case o.AMBIGUOUS:return 400;case o.NETWORK:return 503;case o.GENERAL:return 400;default:return 500}}r(H,"statusForExitCode");function J(e){const n=(e instanceof Error?e.message:String(e)).split(`
|
|
2
2
|
`,1)[0].trim();return n===""?"internal error":n.length>500?`${n.slice(0,497)}\u2026`:n}r(J,"boundedCause");function Re(e){const t=v(e),{status:n,code:i}=$(t);if(n>=500){const a={error:{code:i,message:J(t)}};return t instanceof l&&(a.error.origin="runtime",a.error.retryable=t.retryable),{status:n,body:a}}const k=t instanceof Error?t.message:String(t),u=t instanceof _?K(t):(t instanceof s||t instanceof q||t instanceof l)&&t.details!==void 0?t.details:void 0,d={error:{code:i,message:k}};return u!==void 0&&(d.error.details=u),t instanceof l&&(t.param&&(d.error.param=t.param),t.scope&&(d.error.scope=t.scope),d.error.origin="runtime",d.error.retryable=t.retryable),{status:n,body:d}}r(Re,"toErrorBody");export{W as REVIEW_ERROR_MAP,$ as errorToStatus,he as toCloseResultDTO,xe as toCronDTO,Oe as toCronRunDTO,Re as toErrorBody,Ae as toFeedbackResultDTO,me as toGraphNodeDTO,ce as toMigrateStateDTO,ke as toNodeDetailDTO,P as toNodeEdgesDTO,p as toNodeOutcomeDTO,I as toNodeOutcomeSummaryDTO,U as toNodePathsDTO,ve as toNodeSummaryDTO,G as toNodeWorktreeDTO,pe as toOutcomeDeliveryDTO,B as toPageFeedbackCommentDTO,Ee as toPageFeedbackDTO,De as toProfileDTO,be as toReportResultDTO,Te as toReviewCommentDTO,Se as toReviewCommentEventDTO,m as toReviewDTO,ge as toReviveResultDTO,fe as toRunOutcomeDTO,ye as toSubscriptionDTO};
|
|
@@ -97,6 +97,23 @@ await oauth.refreshIdleConnections({olderThanMs: 30 * 24 * 60 * 60 * 1000});
|
|
|
97
97
|
|
|
98
98
|
It refreshes every connection last saved before the cutoff, through the store's lock, and returns `{refreshed, refused, failures}`. A refused connection goes through `onRefusal` and is removed. `failures` holds connections that could not be refreshed and are still stored; the next run retries them. The SDK starts no timer. The store needs `listStale(before)`, which both `MemoryConnectionStore` and `PostgresConnectionStore` have.
|
|
99
99
|
|
|
100
|
+
## Acting without a sign-in
|
|
101
|
+
|
|
102
|
+
A server that acts for a person on their hosted runtime, for example to publish events to the objects they watch, uses `oauth.appClient(userId)` instead of `oauth.client(userId)`. It stores no connection and refreshes nothing: the SDK signs a `client_credentials` request with your app's key for `sub=user:<id>`, and the directory answers a token and the person's `runtimeUrl`.
|
|
103
|
+
|
|
104
|
+
```ts
|
|
105
|
+
const runtime = await oauth.appClient('user:o1');
|
|
106
|
+
await runtime.customObjects.publish(ref, {event: 'changed', body: '…'});
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
It needs the app registered with the `app_token_for_user` operation, and an active grant from the person. The token is cached per person until a minute before it expires, the client mints a new one on expiry and once after a `401`, and concurrent callers share one mint. It returns the same `AppClient` as `oauth.client`, so `customObjects` (`register`, `publish`, `unregister`) and `canvas` (`watch`, `unwatch`) are available and the owner-daemon namespaces are not.
|
|
110
|
+
|
|
111
|
+
| Error | Code | Means |
|
|
112
|
+
|---|---|---|
|
|
113
|
+
| `NoHostedRuntimeError` | `no_hosted_runtime` (409) | The person has no hosted runtime. Not retryable. |
|
|
114
|
+
| `NotGrantedError` | `not_granted` (409) | The person has no active grant for your app, so they have not signed in to it. Not retryable. |
|
|
115
|
+
| any error with `retryable: true` | `runtime_provisioning` (503), a directory 5xx or a 429 | Try again later. |
|
|
116
|
+
|
|
100
117
|
## Signing in a visitor
|
|
101
118
|
|
|
102
119
|
A person who only needs to be recognized, not connected, signs in with identity only: request `openid`, optionally with `email` and `profile`, and no runtime scope. Finish with `exchangeIdentity`, not `exchangeCode`. An `Identity` is not a connection: no runtime URL, grant or refresh token, nothing goes in the store, and you keep your own session. To act for that person later, send them through `authorizeUrl` again with the runtime scopes you need.
|
package/docs/apps/errors.md
CHANGED
|
@@ -20,6 +20,8 @@ Codes the SDK raises itself are listed in `sdkErrorCodes`, and `CrouterError.cod
|
|
|
20
20
|
| `oauth_nonce_missing` | `exchangeIdentity` was called without the `nonce` from `authorizeUrl`. | Save the nonce in the visitor's session and pass it back. |
|
|
21
21
|
| `oauth_state_mismatch` | The callback's `state` was missing or differed from the saved one. | Refuse the callback. |
|
|
22
22
|
| `not_connected` | `oauth.client(userId)` or a refresh found no stored connection for that person. | Show "sign in again". |
|
|
23
|
+
| `no_hosted_runtime` (409, `NoHostedRuntimeError`) | `oauth.appClient(userId)`: the person has no hosted runtime to act on. Not retryable. | Skip them, or ask them to set up a hosted runtime. |
|
|
24
|
+
| `not_granted` (409, `NotGrantedError`) | `oauth.appClient(userId)`: the person has no active grant for your app. Not retryable. | Send them through sign-in ([Connections](/docs/concepts/connections#acting-without-a-sign-in)). |
|
|
23
25
|
| `refusal_handler_reentry` | An `onRefusal` handler called `oauth.client` (or a refresh) for the person whose connection it is handling. | Don't call the runtime for `refusal.userId` inside the handler. |
|
|
24
26
|
| `unauthorized` (401, `AuthenticationError`) | The directory refused your app's client assertion (`invalid_client`) on `exchangeCode`, a refresh or `revoke`, including a refresh inside a client from `oauth.client(userId)`. The message names the key id (`kid`) you signed with and asks whether that key's public JWK is registered. `details` is `{oauth_error: 'invalid_client', kid}`, or `key_thumbprint` instead of `kid` for a key with no `kid`. | Check that the key's public JWK is on the app's **Sign-in** tab ([Manage your app](/docs/guides/manage-your-app)). |
|
|
25
27
|
| `run_idle`, `waiting_on_user` | `runs.parse`: the run stopped without submitting, or waits on a question and you passed no `onQuestion`. | See [Typed results](/docs/guides/typed-results#stopping-without-a-result-run_idle). |
|
package/docs/plugin/deploying.md
CHANGED
|
@@ -116,6 +116,28 @@ Crtr-Caller: node=<id>; machine=<id>; profile=<id>; run=<id>
|
|
|
116
116
|
|
|
117
117
|
The fields appear in that order. A field with no value is left out, and a call with none omits the header. A service uses `node` to link the calling node to an object it owns. The value comes from crtrd's view of the caller; a manifest cannot set `Crtr-Caller`, `Crtr-Signature` or `Crtr-Request-Id`.
|
|
118
118
|
|
|
119
|
+
### Object kinds and the calling node
|
|
120
|
+
|
|
121
|
+
A plugin written with the kit declares canvas object kinds in `definePlugin({objectKinds})` instead of writing `object_kinds` by hand. Each key is the kind's name relative to the plugin (`repo`), lowercase letters, digits and `-`, with no `.`:
|
|
122
|
+
|
|
123
|
+
```ts
|
|
124
|
+
definePlugin({
|
|
125
|
+
name: 'github',
|
|
126
|
+
objectKinds: {
|
|
127
|
+
repo: {
|
|
128
|
+
description: 'A GitHub repository',
|
|
129
|
+
events: { 'pr-opened': { level: 5 }, 'ci-failed': { level: 8, supersedes: true } },
|
|
130
|
+
read: { command: ['repo', 'read'] },
|
|
131
|
+
},
|
|
132
|
+
},
|
|
133
|
+
commands: { /* … */ },
|
|
134
|
+
});
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
The served `bundle.json` carries `object_kinds` with each key prefixed `<providerId>.<name>`: `providerId` is the `auth.providerId` the handler was given, else the plugin name, the same value used in scope names. `definePlugin` throws `PluginDefinitionError` for a name with a `.` or capitals, a blank description, more than 64 events, a level outside 1-10, or a `read.command` that is not a non-streaming leaf of the plugin. Building the bundle throws when the prefixed kind is one crouter would refuse (a provider id with capitals or `_`, or a reserved first segment such as `repo` or `report`).
|
|
138
|
+
|
|
139
|
+
Every leaf's `ctx.caller.crtr` carries the calling node, parsed from `Crtr-Caller` by `parseCrtrCaller(header)` (also exported): `{ node?, machine?, profile?, run? }`, each field present only when the header carried it, and `crtr` itself absent when it carried none. **The header is asserted by the calling runtime, not verified:** the bearer token does not cover it. It tells you which of the verified `sub`'s nodes made the call, for example to link that node to an object. Never authorize on it; authorize on `ctx.caller.sub`.
|
|
140
|
+
|
|
119
141
|
### `Crtr-Signature`
|
|
120
142
|
|
|
121
143
|
crtrd signs a call to a local plugin when the plugin holds a token and the request goes to the origin of its installed endpoint. Any other URL gets `Crtr-Caller` and no signature.
|
package/docs/sdk/client.md
CHANGED
|
@@ -54,7 +54,7 @@ There is one request path. The client issues every request through the Web `fetc
|
|
|
54
54
|
|
|
55
55
|
## Autostart
|
|
56
56
|
|
|
57
|
-
With `autostart` on (the default for a socket), a request that finds a cold socket runs `crtr sys daemon start`, waits for the daemon to serve, and retries the request once. This is what makes `npm i -g
|
|
57
|
+
With `autostart` on (the default for a socket), a request that finds a cold socket runs `crtr sys daemon start`, waits for the daemon to serve, and retries the request once. This is what makes `npm i -g @north-light/cli` followed by `new Crouter()` work on a machine that has never run the daemon.
|
|
58
58
|
|
|
59
59
|
Autostart is Node-only and applies only to the socket transport. A `baseURL` client cannot start a daemon it may not even share a machine with, so `autostart` defaults to `false` there; setting it to `true` on a `baseURL` client throws `CrouterError` (`autostart is only valid for the local socket transport`).
|
|
60
60
|
|