@north-light/cli 0.3.666 → 0.3.668
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/client.d.ts +2 -1
- package/dist/api/client.js +1 -1
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/bash-jobs.d.ts +3 -0
- package/dist/api/dto/broker-ops.d.ts +37 -0
- package/dist/api/dto/nodes.d.ts +2 -0
- package/dist/api/routes.d.ts +1 -0
- package/dist/api/routes.js +1 -1
- package/dist/builtin-memory/02-turn-lifecycle/00-ending-a-turn.md +3 -1
- package/dist/builtin-memory/04-base-worker-exploring.md +2 -2
- package/dist/clients/attach/chrome/canvas-panels.d.ts +9 -1
- package/dist/clients/attach/chrome/canvas-panels.js +1 -1
- package/dist/clients/attach/chrome/roster.js +6 -6
- package/dist/clients/attach/render/card-presentation.js +2 -2
- package/dist/clients/attach/viewer.js +499 -499
- package/dist/commands/node/bash.js +4 -4
- package/dist/commands/node.js +1 -1
- package/dist/core/bash-job-supervisor.js +3 -3
- package/dist/core/bash-jobs.js +5 -5
- package/dist/core/canvas/canvas.js +18 -18
- package/dist/core/canvas/memory-reads.js +2 -1
- package/dist/core/canvas/waits.d.ts +2 -0
- package/dist/core/canvas/waits.js +6 -6
- package/dist/core/feed/messages.d.ts +5 -2
- package/dist/core/feed/messages.js +10 -5
- package/dist/core/grants/mirror.d.ts +11 -3
- package/dist/core/grants/mirror.js +6 -4
- package/dist/core/grants/on-sync.js +1 -1
- package/dist/core/graph/events.d.ts +9 -0
- package/dist/core/graph/events.js +12 -12
- package/dist/core/graph/kinds/document.js +2 -2
- package/dist/core/graph/kinds/kind.d.ts +2 -1
- package/dist/core/graph/kinds/node.js +1 -1
- package/dist/core/graph/names.d.ts +4 -3
- package/dist/core/graph/names.js +10 -9
- package/dist/core/graph/watches.d.ts +11 -2
- package/dist/core/graph/watches.js +13 -9
- package/dist/core/human/requests.d.ts +18 -1
- package/dist/core/human/requests.js +20 -18
- package/dist/core/human/scan.d.ts +3 -2
- package/dist/core/human/scan.js +1 -1
- package/dist/core/runtime/broker/attachments-fetch.d.ts +2 -1
- package/dist/core/runtime/broker/attachments-fetch.js +1 -1
- package/dist/core/runtime/broker/bash-job-launch.js +1 -1
- package/dist/core/runtime/broker/boot-state.d.ts +5 -0
- package/dist/core/runtime/broker/boot-state.js +1 -1
- package/dist/core/runtime/broker/cycle-start.d.ts +50 -0
- package/dist/core/runtime/broker/cycle-start.js +2 -0
- package/dist/core/runtime/broker/fault-retry.js +1 -1
- package/dist/core/runtime/broker/frame-dispatch.d.ts +2 -0
- package/dist/core/runtime/broker/frame-dispatch.js +1 -1
- package/dist/core/runtime/broker/frame-memory-refs.d.ts +2 -0
- package/dist/core/runtime/broker/frame-memory-refs.js +1 -1
- package/dist/core/runtime/broker/job-reporter.d.ts +4 -2
- package/dist/core/runtime/broker/job-reporter.js +2 -2
- package/dist/core/runtime/broker/rebind.d.ts +3 -0
- package/dist/core/runtime/broker/rebind.js +1 -1
- package/dist/core/runtime/broker.js +1 -1
- package/dist/core/runtime/runner/blaxel/image-build.d.ts +3 -0
- package/dist/core/runtime/runner/blaxel/image-build.js +1 -1
- package/dist/core/runtime/runner/blaxel/release-image.d.ts +37 -0
- package/dist/core/runtime/runner/blaxel/release-image.js +3 -0
- package/dist/core/runtime/runner/blaxel/runner.d.ts +1 -1
- package/dist/core/runtime/spawn.js +2 -2
- package/dist/core/secrets/blaxel-launch.d.ts +8 -0
- package/dist/core/secrets/blaxel-launch.js +3 -3
- package/dist/core/substrate/delivery/corpus.d.ts +7 -2
- package/dist/core/substrate/delivery/corpus.js +2 -2
- package/dist/core/substrate/delivery/deliver.js +3 -3
- package/dist/core/substrate/delivery/render-boot.js +27 -27
- package/dist/core/substrate/delivery/render-event.d.ts +5 -4
- package/dist/core/substrate/delivery/render-event.js +6 -6
- package/dist/daemon/api/bridge.js +3 -3
- package/dist/daemon/api/environment-of.d.ts +4 -0
- package/dist/daemon/api/environment-of.js +3 -3
- package/dist/daemon/api/handlers/attach.js +1 -1
- package/dist/daemon/api/handlers/bash-jobs.d.ts +2 -0
- package/dist/daemon/api/handlers/bash-jobs.js +3 -3
- package/dist/daemon/api/handlers/broker-ops.js +1 -1
- package/dist/daemon/api/handlers/broker-recovery.d.ts +2 -0
- package/dist/daemon/api/handlers/broker-recovery.js +1 -1
- package/dist/daemon/api/handlers/canvas.js +6 -6
- package/dist/daemon/api/handlers/inbox.js +1 -1
- package/dist/daemon/api/handlers/node-records.d.ts +7 -0
- package/dist/daemon/api/handlers/node-records.js +1 -1
- package/dist/daemon/api/handlers/nodes.js +1 -1
- package/dist/daemon/api/map.js +2 -2
- package/dist/daemon/api/operations.js +1 -1
- package/dist/daemon/cron/authority.d.ts +3 -1
- package/dist/daemon/cron/authority.js +1 -1
- package/dist/daemon/cron/escalation.js +1 -1
- package/dist/daemon/cron/sinks.js +2 -2
- package/dist/daemon/cron-run.js +2 -2
- package/dist/daemon/crtrd.js +12 -12
- package/dist/daemon/machine-daemon.js +1 -1
- package/dist/daemon/machine-link/client.d.ts +8 -0
- package/dist/daemon/machine-link/client.js +1 -1
- package/dist/daemon/machine-link/frames.d.ts +18 -0
- package/dist/daemon/machine-link/frames.js +1 -1
- package/dist/daemon/machine-link/holder.d.ts +2 -0
- package/dist/daemon/machine-link/holder.js +5 -5
- package/dist/daemon/machine-link/job-sweep.d.ts +15 -0
- package/dist/daemon/machine-link/job-sweep.js +1 -0
- package/dist/daemon/reconcilers/action-lane.js +1 -1
- package/dist/daemon/reconcilers/bash-deadline.js +1 -1
- package/dist/pi-extensions/canvas-context-intro.js +2 -2
- package/dist/pi-extensions/canvas-doc-substrate.js +4 -4
- package/dist/pi-extensions/canvas-passive-context.d.ts +13 -10
- package/dist/pi-extensions/canvas-passive-context.js +9 -12
- package/dist/pi-extensions/canvas-recap.js +6 -6
- package/dist/pi-extensions/canvas-stophook.js +1 -1
- package/dist/pi-extensions/canvas-structured-output.js +6 -6
- package/package.json +2 -2
- package/packages/crouter-identity/package.json +1 -1
- package/runtime.lock.json +13 -13
- package/scripts/sandbox-bootstrap.sh +36 -7
- package/scripts/sandbox-start.mjs +41 -7
|
@@ -1,15 +1,19 @@
|
|
|
1
|
-
var
|
|
1
|
+
var I=Object.defineProperty;var i=(t,e)=>I(t,"name",{value:e,configurable:!0});import{permits as j,resolveReader as x}from"../permissions/evaluator.js";import{receiverForObject as k}from"./receivers.js";import{getById as m}from"./objects.js";import{randomUUID as R}from"node:crypto";import{mapAsync as v}from"../async-array.js";const O=["spawn","job-start","ask"],W=["report.final","report.result","notice.>"];function A(t){return JSON.stringify(Object.fromEntries(t.map(e=>[String(e.threshold),e.delivery])))}i(A,"configToJson");function H(t){const e=JSON.parse(t);return Object.entries(e).map(([n,r])=>({threshold:Number(n),delivery:r})).sort((n,r)=>r.threshold-n.threshold)}i(H,"configFromJson");async function b(t,e,n){return await t.prepare("SELECT * FROM watches WHERE watcher = ? AND object = ?").get(e.id,n.id)}i(b,"watchRow");async function y(t,e){return await t.prepare("SELECT * FROM watch_subscriptions WHERE watch = ? ORDER BY seq").all(e)}i(y,"subsOf");async function S(t,e){const n=await y(t,e);if(n.length===0){await t.prepare("DELETE FROM watches WHERE watch_id = ?").run(e);return}const r=n.some(s=>O.includes(s.started_by))?1:0;await t.prepare("UPDATE watches SET in_tree = ? WHERE watch_id = ? AND in_tree != ?").run(r,e,r)}i(S,"settle");function L(t,e){return t==="message"?W:e.patterns?.length?e.patterns:[">"]}i(L,"defaultPatterns");async function F(t,e){if(e.length===0)return;for(const{watcher:a,start:c}of e){if(c==="fork")throw new Error("recordWatch: fork watches are made by copyWatchesForFork");if(a.type.includes(".")&&!await k(t,a))throw new Error(`custom object ${a.id} has no receiver`)}const n=new Date().toISOString(),r=new Map;for(const{watcher:a,object:c,opts:h}of e){const _=`${a.id}\0${c.id}`,u=r.get(_)??{watcher:a.id,object:c.id,readHeadsKey:null,linkApp:null};u.readHeadsKey=h?.readHeadsKey??u.readHeadsKey,u.linkApp=h?.linkApp?.id??u.linkApp,r.set(_,u)}const s=[...r.entries()],o=i(a=>s.map(([,c])=>a(c)),"col"),w=await t.prepare(`INSERT INTO watches (watch_id, watcher, object, in_tree, read_heads_key, created_at, link_app)
|
|
2
|
+
SELECT v.id, v.watcher, v.object, 0, v.rhk, ?::text, v.link
|
|
3
|
+
FROM unnest(?::text[], ?::text[], ?::text[], ?::text[], ?::text[]) WITH ORDINALITY AS v(id, watcher, object, rhk, link, n) ORDER BY v.n
|
|
2
4
|
ON CONFLICT (watcher, object) DO UPDATE SET read_heads_key = COALESCE(excluded.read_heads_key, watches.read_heads_key),
|
|
3
|
-
link_app = COALESCE(excluded.link_app, watches.link_app)
|
|
4
|
-
|
|
5
|
+
link_app = COALESCE(excluded.link_app, watches.link_app)
|
|
6
|
+
RETURNING watch_id, watcher, object, in_tree`).all(n,s.map(()=>R()),o(a=>a.watcher),o(a=>a.object),o(a=>a.readHeadsKey),o(a=>a.linkApp)),p=new Map(w.map(a=>[`${a.watcher}\0${a.object}`,{id:a.watch_id,inTree:Number(a.in_tree),subs:[]}]));for(const a of await t.prepare("SELECT watch, pattern, ends_on, started_by FROM watch_subscriptions WHERE watch = ANY(?::text[]) ORDER BY seq").all(w.map(c=>c.watch_id)))for(const c of p.values())c.id===a.watch&&c.subs.push(a);const d=[];for(const{watcher:a,object:c,start:h,opts:_={}}of e){const u=p.get(`${a.id}\0${c.id}`),N=h==="message"?_.endsOn??"final":null,D=O.includes(h);for(const T of L(h,_))u.subs.some(f=>f.pattern===T&&(f.ends_on===null||f.ends_on===N)&&(!D||O.includes(f.started_by)))||(u.subs.push({pattern:T,ends_on:N,started_by:h}),d.push([u.id,T,_.filter===void 0?null:JSON.stringify(_.filter),_.config?A(_.config):null,h,N]))}if(d.length>0){const a=i(c=>d.map(h=>h[c]),"sub");await t.prepare(`INSERT INTO watch_subscriptions (subscription_id, watch, pattern, filter_json, config_json, started_by, ends_on, created_at)
|
|
7
|
+
SELECT v.id, v.watch, v.pattern, v.filter_json, v.config_json, v.started_by, v.ends_on, ?::text
|
|
8
|
+
FROM unnest(?::text[], ?::text[], ?::text[], ?::text[], ?::text[], ?::text[], ?::text[]) WITH ORDINALITY AS v(id, watch, pattern, filter_json, config_json, started_by, ends_on, n) ORDER BY v.n`).run(n,d.map(()=>R()),a(0),a(1),a(2),a(3),a(4),a(5))}const E=[...p.values()].filter(a=>a.subs.length===0).map(a=>a.id),l=[...p.values()].filter(a=>a.subs.length>0&&a.inTree!==(a.subs.some(c=>O.includes(c.started_by))?1:0));E.length>0&&await t.prepare("DELETE FROM watches WHERE watch_id = ANY(?::text[])").run(E),l.length>0&&await t.prepare("UPDATE watches w SET in_tree = v.in_tree::bigint FROM unnest(?::text[], ?::text[]) AS v(id, in_tree) WHERE w.watch_id = v.id").run(l.map(a=>a.id),l.map(a=>String(a.inTree===1?0:1)))}i(F,"recordWatches");async function P(t,e,n,r,s={}){await F(t,[{watcher:e,object:n,start:r,opts:s}])}i(P,"recordWatch");async function G(t,e,n,r){await t.prepare("UPDATE watches SET link_app = ? WHERE watcher = ? AND object = ?").run(r.id,e.id,n.id)}i(G,"markLinkWatch");async function K(t,e,n,r){const s=await b(t,e,n);s&&(r===void 0?await t.prepare("DELETE FROM watch_subscriptions WHERE watch = ?").run(s.watch_id):typeof r=="string"?await t.prepare("DELETE FROM watch_subscriptions WHERE watch = ? AND pattern = ?").run(s.watch_id,r):await t.prepare("DELETE FROM watch_subscriptions WHERE watch = ? AND started_by = ?").run(s.watch_id,r.startedBy),await S(t,s.watch_id))}i(K,"unwatch");async function V(t,e,n,r,s){const o=await b(t,e,n),w=o?(await t.prepare("UPDATE watch_subscriptions SET config_json = ? WHERE watch = ? AND pattern = ?").run(s?A(s):null,o.watch_id,r)).changes:0;if(Number(w)===0)throw new Error(`${e.id} has no subscription ${r} on ${n.id}`)}i(V,"setSubscriptionConfig");async function z(t,e,n){const r=typeof n=="string"?await t.prepare(`DELETE FROM watch_subscriptions WHERE started_by = 'message'
|
|
5
9
|
AND watch IN (SELECT watch_id FROM watches WHERE object = ?) RETURNING watch`).all(e.id):await t.prepare(`DELETE FROM watch_subscriptions WHERE started_by = 'message' AND ends_on = ?
|
|
6
|
-
AND watch IN (SELECT watch_id FROM watches WHERE object = ?) RETURNING watch`).all(`result:${
|
|
7
|
-
WHERE w.${
|
|
10
|
+
AND watch IN (SELECT watch_id FROM watches WHERE object = ?) RETURNING watch`).all(`result:${n.result}`,e.id);for(const s of new Set(r.map(o=>o.watch)))await S(t,s)}i(z,"endMessageSubscriptions");async function C(t,e){const n=await m(t,e.watcher),r=await m(t,e.object);return!n||!r?null:{watch_id:e.watch_id,watcher:n,object:r,in_tree:e.in_tree===1,read_heads_key:e.read_heads_key,created_at:e.created_at,subscriptions:(await y(t,e.watch_id)).map(s=>({subscription_id:s.subscription_id,pattern:s.pattern,started_by:s.started_by,ends_on:s.ends_on,created_at:s.created_at,filter:s.filter_json===null?null:JSON.parse(s.filter_json),config:s.config_json===null?null:H(s.config_json)}))}}i(C,"hydrate");async function g(t,e,n,r){const s=await x(t,e),o=await j(t,s,"read","wr"),w=await j(t,s,"read","ob"),p=await t.prepareUncached(`SELECT w.* FROM watches w JOIN objects wr ON wr.id = w.watcher JOIN objects ob ON ob.id = w.object
|
|
11
|
+
WHERE w.${n} = ? AND ${o.sql} AND ${w.sql} ORDER BY w.seq`).all(r,...o.params,...w.params);return(await v(p,async d=>await C(t,d))).filter(d=>d!==null)}i(g,"visible");async function Q(t,e,n){return await g(t,e,"watcher",n.id)}i(Q,"watchesOf");async function X(t,e,n){return await g(t,e,"object",n.id)}i(X,"watchersOf");async function Z(t,e){return(await t.prepare("SELECT o.id FROM watches w JOIN objects o ON o.id = w.watcher WHERE w.object = ? ORDER BY w.seq").all(e.id)).map(n=>n.id)}i(Z,"watcherIdsOf");async function tt(t,e){return await t.prepare(`WITH RECURSIVE walk(id) AS (
|
|
8
12
|
SELECT CAST(? AS text)
|
|
9
13
|
UNION
|
|
10
14
|
SELECT w.watcher FROM walk JOIN watches w ON w.object = walk.id AND w.in_tree = 1
|
|
11
15
|
) SELECT o.* FROM walk JOIN objects o ON o.id = walk.id
|
|
12
|
-
WHERE o.type = 'node' AND o.id != ?`).all(e.id,e.id)}i(
|
|
13
|
-
WHERE w.object = ? AND w.in_tree = 1 ORDER BY w.seq`).all(e.id)}i(
|
|
14
|
-
VALUES (?, ?, ?, ?, ?, 'fork', ?, ?)`);for(const
|
|
15
|
-
ON CONFLICT (watcher, object) DO NOTHING`).run(
|
|
16
|
+
WHERE o.type = 'node' AND o.id != ?`).all(e.id,e.id)}i(tt,"ancestors");async function et(t,e){return await t.prepare(`SELECT o.* FROM watches w JOIN objects o ON o.id = w.watcher
|
|
17
|
+
WHERE w.object = ? AND w.in_tree = 1 ORDER BY w.seq`).all(e.id)}i(et,"treeWatchersOf");async function at(t,e,n){const r=new Date().toISOString(),s=await t.prepare("SELECT * FROM watches WHERE watcher = ?").all(e.id),o=t.prepare(`INSERT INTO watch_subscriptions (subscription_id, watch, pattern, filter_json, config_json, started_by, ends_on, created_at)
|
|
18
|
+
VALUES (?, ?, ?, ?, ?, 'fork', ?, ?)`);for(const w of s){if(w.object===n.id)continue;await t.prepare(`INSERT INTO watches (watch_id, watcher, object, in_tree, read_heads_key, created_at) VALUES (?, ?, ?, 0, ?, ?)
|
|
19
|
+
ON CONFLICT (watcher, object) DO NOTHING`).run(R(),n.id,w.object,w.read_heads_key,r);const p=await b(t,n,{id:w.object}),d=await y(t,p.watch_id);for(const E of await y(t,w.watch_id))d.some(l=>l.pattern===E.pattern&&l.ends_on===E.ends_on)||await o.run(R(),p.watch_id,E.pattern,E.filter_json,E.config_json,E.ends_on,r);await S(t,p.watch_id)}}i(at,"copyWatchesForFork");export{tt as ancestors,H as configFromJson,A as configToJson,at as copyWatchesForFork,z as endMessageSubscriptions,G as markLinkWatch,P as recordWatch,F as recordWatches,V as setSubscriptionConfig,et as treeWatchersOf,K as unwatch,Z as watcherIdsOf,X as watchersOf,Q as watchesOf};
|
|
@@ -123,8 +123,24 @@ export declare function listRequests(filter?: {
|
|
|
123
123
|
state?: HumanRequestState;
|
|
124
124
|
requester_node_id?: string;
|
|
125
125
|
file?: string;
|
|
126
|
-
page_source_node_id?: string;
|
|
127
126
|
}): Promise<HumanRequestRecord[]>;
|
|
127
|
+
/** The columns a page summary reads (`pageSummary` in scan.ts); every other column, anchor bytes and feedback included, stays in the database. */
|
|
128
|
+
export type PageSummaryRow = Pick<HumanRequestRecord, 'request_id' | 'inbox_ticket_id' | 'request_dir' | 'state' | 'outcome' | 'inbox_listed' | 'settleable' | 'title' | 'subtitle' | 'specification_json' | 'result_json' | 'created_at'>;
|
|
129
|
+
/** The summary state a page shows. `PAGE_STATE_SQL` is the same rule over the columns, built from the same outcome list. */
|
|
130
|
+
export declare function pageSummaryState(request: Pick<HumanRequestRecord, 'state' | 'settleable' | 'outcome'>): 'pending' | 'passive' | 'canceled' | 'resolved';
|
|
131
|
+
declare const PAGE_STATE_SQL: {
|
|
132
|
+
readonly pending: "state <> 'settled' AND settleable = 1";
|
|
133
|
+
readonly passive: "state <> 'settled' AND settleable <> 1";
|
|
134
|
+
readonly canceled: `state = 'settled' AND outcome IN (${string})`;
|
|
135
|
+
readonly resolved: `state = 'settled' AND (outcome IS NULL OR outcome NOT IN (${string}))`;
|
|
136
|
+
};
|
|
137
|
+
export type PageSummaryState = keyof typeof PAGE_STATE_SQL;
|
|
138
|
+
/** Page requests in `created_at` order, narrowed to the summary columns. History belongs to manifest.source.nodeId, which can differ
|
|
139
|
+
* from requester_node_id on imported or independently published pages. */
|
|
140
|
+
export declare function listPageSummaryRows(filter?: {
|
|
141
|
+
source_node_id?: string;
|
|
142
|
+
summary_state?: PageSummaryState;
|
|
143
|
+
}): Promise<PageSummaryRow[]>;
|
|
128
144
|
/** A preflight preserves the old map-before-filter error for malformed page results. */
|
|
129
145
|
export declare function hasPageResultException(): Promise<boolean>;
|
|
130
146
|
export declare function firstInvalidPageSpecification(): Promise<Pick<HumanRequestRecord, 'request_id' | 'specification_json'> | null>;
|
|
@@ -154,3 +170,4 @@ export declare function readAnchorBase(requestId: string): Promise<{
|
|
|
154
170
|
} | null>;
|
|
155
171
|
export declare function replaceAnchorBaseLocked(db: CanvasDb, requestId: string, bytes: Buffer, sha256: string): Promise<void>;
|
|
156
172
|
export declare function migrateHumanRequestsState(db: DatabaseSync): void;
|
|
173
|
+
export {};
|
|
@@ -1,54 +1,56 @@
|
|
|
1
|
-
var
|
|
2
|
-
`),i.syncFile(u),i.syncDirectory(n),i.syncDirectory(s),i.syncDirectory(e),i.syncDirectory(se()),n}r(oe,"publishPageRevision");async function
|
|
3
|
-
`),await
|
|
1
|
+
var ye=Object.defineProperty;var r=(e,t)=>ye(e,"name",{value:t,configurable:!0});import{prepared as l}from"../sqlite-statements.js";import{createHash as ge,randomBytes as I}from"node:crypto";import{existsSync as y,mkdirSync as R,readFileSync as Y,readdirSync as Ne,realpathSync as L,statSync as be,writeFileSync as he}from"node:fs";import{basename as C,join as _}from"node:path";import{z as d}from"zod";import{crtrHome as G,isSafeNodeId as Te,nodesRoot as q}from"../canvas/paths.js";import{withCanvasWrite as z,openDb as c}from"../canvas/db.js";import{syncDirectory as qe,syncFile as Se}from"../fs-utils.js";import{newNodeId as we}from"../runtime/nodes.js";import{pageManifestPath as Z,pageModulePath as ee,pagePath as te}from"./convention.js";import{preparePageSource as Ae}from"./page-authoring.js";import{pageAwaitsResponse as Re,pageDeliverySchema as De,pageIsNoticeSql as ve,validatePageManifest as ne}from"./page-schema.js";import{appendWaitingOnUser as Oe}from"../runs/questions.js";import{isCloudRole as Ie}from"../canvas/person.js";import{REQUEST_BLOB_PREFIX as Le,isBlobRequestPath as ie,writeRequestFile as U}from"./request-files.js";function x(e){return e===1||e===!0}r(x,"bool");function re(e){return{request_id:e.request_id,kind:e.kind,inbox_ticket_id:e.inbox_ticket_id,request_dir:e.request_dir,presentation_dir:e.presentation_dir,requester_node_id:e.requester_node_id,companion_node_id:e.companion_node_id,idempotency_key:e.idempotency_key,state:e.state,outcome:e.outcome,inbox_listed:x(e.inbox_listed),settleable:x(e.settleable),title:e.title,subtitle:e.subtitle,file:e.file,specification_json:e.specification_json,action_json:e.action_json,progress_json:e.progress_json,feedback_json:e.feedback_json,result_json:e.result_json,anchor_base_sha256:e.anchor_base_sha256,anchor_base_bytes:e.anchor_base_bytes===null?null:Buffer.from(e.anchor_base_bytes),created_at:e.created_at,opened_at:e.opened_at,submit_requested_at:e.submit_requested_at,settled_at:e.settled_at,settlement_delivery_id:e.settlement_delivery_id,action_delivery_id:e.action_delivery_id,submit_note_delivery_id:e.submit_note_delivery_id,projected_at:e.projected_at,projection_error:e.projection_error,companion_retired_at:e.companion_retired_at,updated_at:e.updated_at}}r(re,"recordFromRow");async function b(e,t,...i){const s=await e.prepareUncached(`SELECT * FROM human_requests WHERE ${t}`).get(...i);return s===void 0?null:re(s)}r(b,"one");async function h(e,t,i=[],s="created_at ASC, request_id ASC"){return(await e.prepareUncached(`SELECT * FROM human_requests WHERE ${t} ORDER BY ${s}`).all(...i)).map(re)}r(h,"many");function se(){return _(G(),"requests")}r(se,"humanRequestsRoot");function P(e){if(!Te(e))throw new TypeError(`request_id must be a safe path segment: ${e}`);if(Ie())return`${Le}${e}`;const t=se();return R(t,{recursive:!0,mode:448}),_(L(t),e)}r(P,"requestDir");function $(){return I(32).toString("hex")}r($,"randomTicketId");function H(e,t){return ge("sha256").update(`${L(e)}\0${t}`,"utf8").digest("hex")}r(H,"legacyTicketId");const xe={writeFile(e,t){he(e,t,{flag:"wx",mode:384})},syncFile:Se,syncDirectory:qe};function je(e){return _(e,"revisions")}r(je,"revisionRoot");function oe(e,t,i=xe){R(e,{recursive:!0,mode:448});const s=je(e);R(s,{recursive:!0,mode:448});const n=_(s,I(16).toString("hex"));R(n,{mode:448});const o=te(n,t.manifest.dialect);if(i.writeFile(o,t.document),i.syncFile(o),t.manifest.dialect==="jsx"){const a=ee(n);i.writeFile(a,t.module),i.syncFile(a)}const u=Z(n);return i.writeFile(u,`${JSON.stringify(t.manifest,null,2)}
|
|
2
|
+
`),i.syncFile(u),i.syncDirectory(n),i.syncDirectory(s),i.syncDirectory(e),i.syncDirectory(se()),n}r(oe,"publishPageRevision");async function ke(e,t){if(!ie(e))return oe(e,t);const i=`${e}/revisions/${I(16).toString("hex")}`;return await U(Z(i),`${JSON.stringify(t.manifest,null,2)}
|
|
3
|
+
`),await U(te(i,t.manifest.dialect),t.document),t.manifest.dialect==="jsx"&&await U(ee(i),t.module),i}r(ke,"publishPageRevisionTo");function pt(e){if(e.kind!=="page"||e.presentation_dir===null)throw new Error(`page request has no selected presentation: ${e.request_id}`);return e.presentation_dir}r(pt,"presentationDir");async function mt(e){const t=e.request_id??await we(),i=P(t),s=await ke(i,e.prepared),n=new Date().toISOString(),o=e.prepared.manifest;return await z(async u=>{await u.prepare(`
|
|
4
4
|
INSERT INTO human_requests (
|
|
5
5
|
request_id, kind, inbox_ticket_id, request_dir, presentation_dir, requester_node_id, state, inbox_listed,
|
|
6
6
|
settleable, title, subtitle, specification_json, action_json, created_at, updated_at
|
|
7
7
|
) VALUES (?, 'page', ?, ?, ?, ?, 'open', ?, ?, ?, ?, ?, ?, ?, ?)
|
|
8
|
-
`).run(t,e.inbox_ticket_id
|
|
8
|
+
`).run(t,e.inbox_ticket_id??$(),i,s,e.requester_node_id??null,o.delivery.inbox?1:0,o.delivery.inbox||o.delivery.reply?1:0,o.title,o.subtitle??null,JSON.stringify(o),e.action_json??null,n,n);const a=await b(u,"request_id = ?",t);if(a===null)throw new Error(`page request insert did not produce a row: ${t}`);return await Oe(u,a),a})}r(mt,"createPageRequest");async function ft(e){return await z(async t=>{const i=await t.prepare(`
|
|
9
9
|
INSERT INTO human_requests (
|
|
10
10
|
request_id, kind, inbox_ticket_id, request_dir, requester_node_id, companion_node_id,
|
|
11
11
|
idempotency_key, state, inbox_listed, settleable, title, subtitle, file,
|
|
12
12
|
specification_json, anchor_base_sha256, anchor_base_bytes, created_at, updated_at
|
|
13
13
|
) VALUES (?, 'review', ?, ?, ?, ?, ?, 'binding', ?, 1, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
14
14
|
ON CONFLICT(idempotency_key) DO NOTHING
|
|
15
|
-
`).run(e.request_id
|
|
16
|
-
AND n.run_id IS NOT NULL AND n.grantee IS NOT NULL AND n.grantee <> 'app:terminal'))`;async function
|
|
15
|
+
`).run(e.request_id,$(),e.request_dir,e.requester_node_id,e.companion_node_id,e.idempotency_key,e.inbox_listed?1:0,e.title??C(e.file),e.subtitle??null,e.file,JSON.stringify(e.specification),e.anchor_base_sha256,e.anchor_base_bytes,e.created_at,e.created_at),s=await b(t,"idempotency_key = ?",e.idempotency_key);if(s===null)throw new Error(`review binding insert did not produce a row: ${e.idempotency_key}`);return{request_id:s.request_id,won:i.changes>0}})}r(ft,"commitBindingRequest");async function Et(e){return await b(await c(),"request_id = ?",e)}r(Et,"getRequest");async function yt(e){return await b(await c(),"inbox_ticket_id = ?",e)}r(yt,"getRequestByInboxTicket");async function gt(e){let t=e;if(!ie(e))try{t=L(e)}catch{}return await b(await c(),"request_dir = ?",t)}r(gt,"getRequestByDirectory");async function Nt(e){return await b(await c(),"companion_node_id = ? AND state <> 'binding'",e)}r(Nt,"getRequestByCompanion");async function bt(e){return await b(await c(),"idempotency_key = ?",e)}r(bt,"getRequestByIdempotencyKey");const Ce=r(e=>`COALESCE(${e}.requester_node_id, CASE WHEN ${e}.kind = 'page' AND ${ve(`${e}.specification_json`)} THEN ${e}.specification_json #>> '{source,nodeId}' END)`,"askingNodeSql"),ae=`NOT (kind = 'page' AND EXISTS (SELECT 1 FROM node_rows n WHERE n.node_id = ${Ce("human_requests")}
|
|
16
|
+
AND n.run_id IS NOT NULL AND n.grantee IS NOT NULL AND n.grantee <> 'app:terminal'))`;async function ht(){return await h(await c(),`state = 'open' AND inbox_listed = 1 AND ${ae}`,[],"created_at DESC, request_id DESC")}r(ht,"listOpenInboxRequests");async function Tt(){return(await h(await c(),`state = 'open' AND requester_node_id IS NOT NULL AND ((inbox_listed = 1 AND ${ae}) OR (kind = 'page' AND inbox_listed = 0 AND settleable = 1))`,[],"created_at ASC, request_id ASC")).filter(e=>e.inbox_listed||Re(JSON.parse(e.specification_json)))}r(Tt,"listPendingAsks");async function Ue(e){return await h(await c(),"state = 'open' AND requester_node_id = ?",[e],"created_at DESC, request_id DESC")}r(Ue,"openRequestsByRequester");async function qt(e){return(await Ue(e)).some(t=>t.kind==="review"?!0:JSON.parse(t.specification_json).delivery?.reply===!0)}r(qt,"hasOpenReplyBearingRequestByRequester");async function St(){return await h(await c(),"state = 'open' AND inbox_listed = 1 AND requester_node_id IS NOT NULL",[],"created_at DESC, request_id DESC")}r(St,"listOpenReplyBearingRequests");async function wt(){return await h(await c(),"kind = 'review' AND state = 'binding'")}r(wt,"listBindingRequests");async function At(){return await h(await c(),"kind = 'review' AND state = 'open' AND submit_requested_at IS NOT NULL")}r(At,"listSubmitRequestedRequests");async function Rt(){return await h(await c(),"kind = 'review' AND state = 'settled' AND projected_at IS NULL")}r(Rt,"listUnprojectedReviews");async function Dt(e={}){const t=["true"],i=[];for(const[s,n]of Object.entries(e))n!==void 0&&(t.push(`${s} = ?`),i.push(n));return await h(await c(),t.join(" AND "),i)}r(Dt,"listRequests");const de=["canceled","dismissed"],ce=de.map(e=>`'${e}'`).join(", ");function vt(e){return e.state!=="settled"?e.settleable?"pending":"passive":e.outcome!==null&&de.includes(e.outcome)?"canceled":"resolved"}r(vt,"pageSummaryState");const Pe={pending:"state <> 'settled' AND settleable = 1",passive:"state <> 'settled' AND settleable <> 1",canceled:`state = 'settled' AND outcome IN (${ce})`,resolved:`state = 'settled' AND (outcome IS NULL OR outcome NOT IN (${ce}))`};async function Ot(e={}){const t=["kind = 'page'"],i=[];return e.source_node_id!==void 0&&(t.push("specification_json #>> '{source,nodeId}' = ?"),i.push(e.source_node_id)),e.summary_state!==void 0&&t.push(Pe[e.summary_state]),(await(await c()).prepareUncached(`
|
|
17
|
+
SELECT request_id, inbox_ticket_id, request_dir, state, outcome, inbox_listed, settleable, title, subtitle, specification_json, result_json, created_at
|
|
18
|
+
FROM human_requests WHERE ${t.join(" AND ")} ORDER BY created_at ASC, request_id ASC`).all(...i)).map(n=>({...n,inbox_listed:x(n.inbox_listed),settleable:x(n.settleable)}))}r(Ot,"listPageSummaryRows");async function It(){return await(await c()).prepare(`
|
|
17
19
|
SELECT 1 FROM human_requests
|
|
18
20
|
WHERE kind = 'page' AND result_json IS NOT NULL
|
|
19
21
|
AND (result_json ->> 'kind') = 'page'
|
|
20
22
|
AND jsonb_typeof(result_json -> 'summary') IS DISTINCT FROM 'string'
|
|
21
23
|
LIMIT 1
|
|
22
|
-
`).get()!==void 0}r(
|
|
24
|
+
`).get()!==void 0}r(It,"hasPageResultException");async function Lt(){return await(await c()).prepare(`
|
|
23
25
|
SELECT request_id, specification_json FROM human_requests
|
|
24
26
|
WHERE kind = 'page' AND jsonb_typeof(specification_json) <> 'object'
|
|
25
27
|
ORDER BY created_at ASC, request_id ASC LIMIT 1
|
|
26
|
-
`).get()??null}r(
|
|
28
|
+
`).get()??null}r(Lt,"firstInvalidPageSpecification");async function xt(e,t){return(await(await c()).prepare("UPDATE human_requests SET state = 'open', opened_at = ?, updated_at = ? WHERE request_id = ? AND state = 'binding'").run(t,t,e)).changes>0}r(xt,"openRequest");async function jt(e,t,i){return(await(await c()).prepare(`
|
|
27
29
|
UPDATE human_requests SET state = 'settled', outcome = 'canceled', result_json = ?, settled_at = ?, updated_at = ?
|
|
28
30
|
WHERE request_id = ? AND kind = 'review' AND state = 'binding'
|
|
29
|
-
`).run(JSON.stringify({schema:"humanloop.cancel/v1",kind:"canceled",canceledAt:t,reason:i}),t,t,e)).changes>0}r(
|
|
31
|
+
`).run(JSON.stringify({schema:"humanloop.cancel/v1",kind:"canceled",canceledAt:t,reason:i}),t,t,e)).changes>0}r(jt,"cancelBindingRequest");async function kt(e,t){return(await(await c()).prepare("UPDATE human_requests SET submit_requested_at = ?, updated_at = ? WHERE request_id = ? AND kind = 'review' AND state = 'open' AND submit_requested_at IS NULL").run(t,t,e)).changes>0}r(kt,"requestSubmit");async function Ct(e,t){return(await e.prepare(`
|
|
30
32
|
UPDATE human_requests SET state = 'settled', outcome = ?, result_json = ?, settled_at = ?,
|
|
31
33
|
progress_json = NULL, updated_at = ?
|
|
32
34
|
WHERE request_id = ? AND state = 'open'
|
|
33
|
-
`).run(t.outcome,t.result_json,t.settled_at,t.settled_at,t.request_id)).changes===0?null:await
|
|
35
|
+
`).run(t.outcome,t.result_json,t.settled_at,t.settled_at,t.request_id)).changes===0?null:await b(e,"request_id = ?",t.request_id)}r(Ct,"settleRequestLocked");async function Ut(e,t,i){await e.prepare("UPDATE human_requests SET settlement_delivery_id = ?, action_delivery_id = ?, updated_at = ? WHERE request_id = ?").run(i.settlement_delivery_id??null,i.action_delivery_id??null,new Date().toISOString(),t)}r(Ut,"setSettlementDeliveryMarksLocked");async function Pt(e,t,i){return(await e.prepare("UPDATE human_requests SET submit_note_delivery_id = ?, updated_at = ? WHERE request_id = ? AND state = 'open' AND submit_note_delivery_id IS NULL").run(i,new Date().toISOString(),t)).changes>0}r(Pt,"setSubmitNoteDeliveryLocked");async function $t(e,t){return(await(await c()).prepare(`
|
|
34
36
|
UPDATE human_requests SET presentation_dir = ?, specification_json = ?, title = ?, subtitle = ?, inbox_listed = ?, settleable = ?, updated_at = ?
|
|
35
37
|
WHERE request_id = ? AND kind = 'page' AND state = 'open'
|
|
36
|
-
`).run(t.presentation_dir,t.specification_json,t.title,t.subtitle,t.inbox_listed?1:0,t.settleable?1:0,new Date().toISOString(),e)).changes>0}r(
|
|
38
|
+
`).run(t.presentation_dir,t.specification_json,t.title,t.subtitle,t.inbox_listed?1:0,t.settleable?1:0,new Date().toISOString(),e)).changes>0}r($t,"revisePageRequest");async function Ht(e,t){return(await(await c()).prepare(`
|
|
37
39
|
UPDATE human_requests SET progress_json = ?, updated_at = ?
|
|
38
40
|
WHERE inbox_ticket_id = ? AND kind = 'page' AND state = 'open' AND settleable = 1
|
|
39
|
-
`).run(JSON.stringify({kind:"page",responses:t,savedAt:new Date().toISOString()}),new Date().toISOString(),e)).changes>0}r(
|
|
41
|
+
`).run(JSON.stringify({kind:"page",responses:t,savedAt:new Date().toISOString()}),new Date().toISOString(),e)).changes>0}r(Ht,"writeProgress");async function Mt(e,t){await(await c()).prepare("UPDATE human_requests SET projected_at = ?, projection_error = NULL, updated_at = ? WHERE request_id = ?").run(t,t,e)}r(Mt,"markProjected");async function Ft(e,t){await(await c()).prepare("UPDATE human_requests SET projection_error = ?, updated_at = ? WHERE request_id = ? AND projected_at IS NULL").run(t,new Date().toISOString(),e)}r(Ft,"markProjectionError");async function Xt(e,t){await(await c()).prepare("UPDATE human_requests SET companion_retired_at = ?, updated_at = ? WHERE request_id = ? AND companion_retired_at IS NULL").run(t,t,e)}r(Xt,"markCompanionRetired");async function Wt(e){const t=await(await c()).prepare("SELECT anchor_base_bytes, anchor_base_sha256 FROM human_requests WHERE request_id = ?").get(e);return t===void 0||t.anchor_base_bytes===null||t.anchor_base_sha256===null?null:{bytes:Buffer.from(t.anchor_base_bytes),sha256:t.anchor_base_sha256}}r(Wt,"readAnchorBase");async function Jt(e,t,i,s){await e.prepare("UPDATE human_requests SET anchor_base_bytes = ?, anchor_base_sha256 = ?, updated_at = ? WHERE request_id = ?").run(i,s,new Date().toISOString(),t)}r(Jt,"replaceAnchorBaseLocked");function $e(e){if(typeof e!="object"||e===null)throw new Error("result is not an object");const t=e;return t.kind==="canceled"?{outcome:t.disposition==="dismissed"?"dismissed":"canceled",settledAt:String(t.canceledAt)}:{outcome:"answered",settledAt:String(t.completedAt)}}r($e,"legacyPageResult");function A(e){try{return JSON.parse(Y(e,"utf8"))}catch(t){throw new Error(`corrupt required input: ${e}`,{cause:t})}}r(A,"readJson");function M(){return I(16).toString("hex")}r(M,"migrationId");function He(e){return Number(l(e,"SELECT COALESCE(MAX(seq), 0) AS seq FROM messages").get().seq)+1}r(He,"nextMessageSeq");function Me(e,t,i,s){return(s==="page"?l(e,`SELECT d.delivery_id FROM deliveries d JOIN messages m ON m.message_id = d.message_id
|
|
40
42
|
WHERE d.destination_kind = 'node_inbox' AND d.destination_id = ? AND m.sender_node_id = ?
|
|
41
43
|
AND m.disposition IN ('human-answer', 'human-canceled') LIMIT 1`).get(i,t):l(e,`SELECT d.delivery_id FROM deliveries d JOIN messages m ON m.message_id = d.message_id
|
|
42
|
-
WHERE d.destination_kind = 'node_inbox' AND d.destination_id = ? AND m.body_json LIKE ? LIMIT 1`).get(i,`%"review_id":"${t}"%`))?.delivery_id??null}r(
|
|
44
|
+
WHERE d.destination_kind = 'node_inbox' AND d.destination_id = ? AND m.body_json LIKE ? LIMIT 1`).get(i,`%"review_id":"${t}"%`))?.delivery_id??null}r(Me,"importedTerminalDelivery");function ue(e,t,i){if(t===null||i===null)return!1;const s=l(e,"SELECT status, final_report FROM nodes WHERE node_id = ?").get(t);return s?.status==="canceled"||i==="approved"&&s?.status==="done"&&s.final_report!==null}r(ue,"companionRetirementProven");function le(e){if(typeof e!="object"||e===null)return"no reason was given";const t=e.reason;return typeof t=="string"&&t!==""?t:"no reason was given"}r(le,"migratedCancellationReason");function Fe(e,t){const i=e.outcome==="canceled"||e.outcome==="dismissed";return[e.kind==="review"?i?`Review ${e.requestId} was canceled \u2014 ${le(t)}.`:`Review ${e.requestId} was approved by the user.`:i?`Human request ${e.requestId} was canceled \u2014 ${le(t)}.`:`Human request ${e.requestId} was answered.`,...e.kind==="review"?[`The review result is at ${e.requestDir}/result.json.`]:[],`Result:
|
|
43
45
|
${JSON.stringify(t,null,2)}`].join(`
|
|
44
46
|
|
|
45
|
-
`)}r(
|
|
47
|
+
`)}r(Fe,"migratedTerminalBody");function Xe(e,t){const i=M(),s=M(),n=Date.parse(t.settledAt),o=Number.isFinite(n)?n:0,u=t.outcome==="answered"||t.outcome==="approved"?"human-answer":"human-canceled",a=JSON.parse(t.resultJson),p=Fe(t,a);return l(e,`INSERT INTO messages
|
|
46
48
|
(message_id, seq, operation_id, created_at, sender_node_id, sender_name, kind, label, body_ref, body_json, disposition)
|
|
47
|
-
VALUES (?, ?, ?, ?, NULL, 'crtrd', 'completed', ?, NULL, ?, ?)`).run(i,
|
|
49
|
+
VALUES (?, ?, ?, ?, NULL, 'crtrd', 'completed', ?, NULL, ?, ?)`).run(i,He(e),M(),t.settledAt,p.split(`
|
|
48
50
|
`,1)[0],JSON.stringify({body:p,result:a}),u),l(e,`INSERT INTO deliveries
|
|
49
51
|
(delivery_id, message_id, destination_kind, destination_id, urgency, wake, state, attempts, created_at, updated_at)
|
|
50
|
-
VALUES (?, ?, 'node_inbox', ?, 'normal', 1, 'pending', 0, ?, ?)`).run(s,i,t.requesterNodeId,o,o),s}r(
|
|
51
|
-
`}r(
|
|
52
|
+
VALUES (?, ?, 'node_inbox', ?, 'normal', 1, 'pending', 0, ?, ?)`).run(s,i,t.requesterNodeId,o,o),s}r(Xe,"createMigratedTerminalDelivery");function _e(e,t){if(t.requesterNodeId===null||t.outcome===null||t.resultJson===null||t.settledAt===null)return null;const i=Me(e,t.requestId,t.requesterNodeId,t.kind);return i!==null?i:t.deliveredAt!==null&&t.deliveredAt!==void 0?null:Xe(e,{requestId:t.requestId,requesterNodeId:t.requesterNodeId,kind:t.kind,outcome:t.outcome,resultJson:t.resultJson,settledAt:t.settledAt,requestDir:t.requestDir})}r(_e,"terminalDeliveryMark");const We=d.object({sessionName:d.string().optional(),askedBy:d.string().optional(),blockedSince:d.string().optional(),profileName:d.string().optional(),nodeId:d.string().optional()}).strict(),Je=d.object({id:d.string().regex(/^[A-Za-z0-9_-]{1,64}$/).optional(),kind:d.string().min(1),step:d.number().int().nonnegative(),config:d.record(d.string(),d.unknown()),unvalidated:d.literal(!0).optional(),display:d.literal(!0).optional()}).strict(),Be=d.object({schema:d.literal("crtr.page/v1"),dialect:d.enum(["md","html","jsx"]),title:d.string().trim().min(1),subtitle:d.string().optional(),placement:d.enum(["inline","panel"]),document:d.enum(["page.md","page.html","page.tsx"]),steps:d.number().int().positive(),slots:d.array(Je),source:We.optional()}).strict().superRefine((e,t)=>{const i=e.dialect==="md"?"page.md":e.dialect==="html"?"page.html":"page.tsx";e.document!==i&&t.addIssue({code:"custom",path:["document"],message:"document must agree with dialect"}),e.dialect==="md"&&e.steps!==1&&t.addIssue({code:"custom",path:["steps"],message:"md pages have exactly one step"})});function Ke(e){if(e.source===void 0)return;const{blockedSince:t,...i}=e.source,s={...i,...t!==void 0&&d.string().datetime({offset:!0}).safeParse(t).success?{emittedAt:t}:{}};return Object.keys(s).length===0?void 0:s}r(Ke,"legacyPresentationSource");function Qe(e,t,i){return`export default function LegacyPage() { return <Page title={${JSON.stringify(e)}}${t===void 0?"":` subtitle={${JSON.stringify(t)}}`}><pre>{${JSON.stringify(i)}}</pre></Page>; }
|
|
53
|
+
`}r(Qe,"legacyReplayDocument");function pe(e){return Array.isArray(e.slots)?{...e,slots:e.slots.map(t=>{if(typeof t!="object"||t===null||Array.isArray(t))return t;const i=t;if(i.kind!=="text"||typeof i.config!="object"||i.config===null||Array.isArray(i.config))return t;const{editable:s,...n}=i.config;return{...i,config:n}})}:e}r(pe,"withoutLegacyTextEditable");function Ve(e,t){const i=_(e,"page.json"),s=Be.safeParse(t);if(!s.success)throw new Error(s.error.message);const n=s.data,o=Ke(n),u={placement:n.placement,inbox:!0,reply:n.source?.blockedSince!==void 0};ne(pe({schema:"crtr.page/v2",dialect:"jsx",title:n.title,...n.subtitle===void 0?{}:{subtitle:n.subtitle},delivery:u,document:"page.tsx",steps:n.steps,slots:n.slots,...o===void 0?{}:{source:o}}));const a=_(e,n.document);if(!y(a))throw new Error(`corrupt required input: ${a}`);const p=Y(a,"utf8"),f=Ae({dialect:"jsx",document:Qe(n.title,n.subtitle,p),source:o,delivery:u});if(o!==void 0)return f;const{source:E,...g}=f.manifest;return{...f,manifest:g}}r(Ve,"migrateLegacyPage");function Bt(e){e.exec(`
|
|
52
54
|
CREATE TABLE human_requests (
|
|
53
55
|
request_id TEXT PRIMARY KEY, kind TEXT NOT NULL CHECK (kind IN ('page','review')),
|
|
54
56
|
inbox_ticket_id TEXT NOT NULL UNIQUE, request_dir TEXT NOT NULL, presentation_dir TEXT,
|
|
@@ -77,4 +79,4 @@ ${JSON.stringify(t,null,2)}`].join(`
|
|
|
77
79
|
progress_json, feedback_json, result_json, anchor_base_sha256, anchor_base_bytes, created_at, opened_at,
|
|
78
80
|
submit_requested_at, settled_at, settlement_delivery_id, action_delivery_id, projected_at, projection_error,
|
|
79
81
|
companion_retired_at, updated_at
|
|
80
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);if(l(e,"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'reviews'").get()!==void 0){const s=l(e,"SELECT * FROM reviews").all();for(const n of s){const o=n.state,u=o==="approved"||o==="canceled",a=o==="canceled"&&n.result_json===null?JSON.stringify({schema:"humanloop.cancel/v1",kind:"canceled",canceledAt:n.canceled_at,...n.cancel_reason===""||n.cancel_reason===null?{}:{reason:n.cancel_reason},...n.cancel_actor===null?{}:{actor:n.cancel_actor}}):n.result_json;if(u&&a===null)throw new Error(`corrupt required input: reviews/${n.review_id} has no terminal result`);const p=n.bridge_node_id===null?_(
|
|
82
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);if(l(e,"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'reviews'").get()!==void 0){const s=l(e,"SELECT * FROM reviews").all();for(const n of s){const o=n.state,u=o==="approved"||o==="canceled",a=o==="canceled"&&n.result_json===null?JSON.stringify({schema:"humanloop.cancel/v1",kind:"canceled",canceledAt:n.canceled_at,...n.cancel_reason===""||n.cancel_reason===null?{}:{reason:n.cancel_reason},...n.cancel_actor===null?{}:{actor:n.cancel_actor}}):n.result_json;if(u&&a===null)throw new Error(`corrupt required input: reviews/${n.review_id} has no terminal result`);const p=n.bridge_node_id===null?_(G(),"reviews",n.review_id):_(q(),n.bridge_node_id),f={origin_kind:n.origin_kind,bridge_node_id:n.bridge_node_id,origin_session_file:n.origin_session_file,origin_session_id:n.origin_session_id,origin_leaf_id:n.origin_leaf_id,model_spec:n.model_spec,branch_file:n.branch_file,baseline_sha256:n.baseline_sha256,baseline_bytes:n.baseline_bytes,captured_at:n.captured_at,output_path:n.output_path},E=u?o==="approved"?"approved":"canceled":null,g=u?o==="approved"?n.approved_at:n.canceled_at:null,S=_e(e,{requestId:n.review_id,requesterNodeId:n.origin_node_id,kind:"review",outcome:E,resultJson:a,settledAt:g,requestDir:p,deliveredAt:n.delivered_at}),D=ue(e,n.companion_node_id,E)?g:null;t.run(n.review_id,"review",n.origin_kind==="ticket"?H(q(),C(p)):$(),p,null,n.origin_node_id,n.companion_node_id,n.idempotency_key,u?"settled":o,E,n.origin_kind==="ticket"?1:0,1,C(n.file),n.subtitle,n.file,JSON.stringify(f),null,null,null,a,n.anchor_base_sha256,n.anchor_base_bytes,n.created,n.opened_at,n.submit_requested_at,g,S,null,n.projected_at,n.projection_error,D,n.created)}e.exec("DROP TABLE reviews")}for(const s of y(q())?Ne(q(),{withFileTypes:!0}):[]){if(!s.isDirectory())continue;const n=_(q(),s.name),o=_(n,"page.json"),u=_(n,"review.json");if(!y(o)){if(y(u))continue;continue}if(l(e,"SELECT 1 FROM human_requests WHERE request_id = ?").get(s.name)!==void 0)continue;let a,p,f,E;try{const m=A(o);if(typeof m!="object"||m===null||Array.isArray(m))throw new Error("page manifest must be an object");a=m,a.schema==="crtr.page/v1"?(p=Ve(n,m),a=p.manifest):a.schema==="crtr.page/v2"&&(a=pe(a));const w=De.safeParse(a.delivery);if(typeof a.title!="string"||!w.success)throw new Error(w.success?"page title must be a string":w.error.message);E=w.data,f=ne(a)}catch(m){const w=m instanceof Error&&m.cause instanceof Error?m.cause.message:m instanceof Error?m.message:String(m);console.warn(`skipping legacy page ${o}: ${w}`);continue}let g=L(n);p!==void 0&&(g=oe(P(s.name),p));const S=f.source,D=_(n,"response.json"),v=y(D)?A(D):null,N=v===null?null:$e(v),me=l(e,"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'deliveries'").get()===void 0?null:l(e,"SELECT delivery_id FROM deliveries WHERE idempotency_key = ?").get(`human-action:${H(q(),s.name)}`),F=_(n,"action.json"),X=_(n,"progress.json"),j=_(n,"feedback-comments.json"),k=_(n,"reply-route.json"),T=y(j)?A(j):null;if(T!==null&&(typeof T!="object"||typeof T.companionNodeId<"u"&&typeof T.companionNodeId!="string"))throw new Error(`corrupt required input: ${j}`);const O=y(k)?A(k):null;if(O!==null&&(typeof O!="object"||typeof O.bridge_node_id!="string"))throw new Error(`corrupt required input: ${k}`);const W=O?.bridge_node_id,J=(typeof W!="string"||l(e,"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'nodes'").get()===void 0?null:l(e,"SELECT parent FROM nodes WHERE node_id = ?").get(W))?.parent??(typeof S?.nodeId=="string"?S.nodeId:null),B=T?.companionNodeId,K=typeof S?.emittedAt=="string"?S.emittedAt:be(o).mtime.toISOString(),Q=v===null?null:JSON.stringify(v),fe=_e(e,{requestId:s.name,requesterNodeId:J,kind:"page",outcome:N?.outcome??null,resultJson:Q,settledAt:N?.settledAt??null,requestDir:n}),Ee=ue(e,B??null,N?.outcome??null)?N?.settledAt??null:null,V=P(s.name);R(V,{recursive:!0,mode:448}),t.run(s.name,"page",H(q(),s.name),V,g,J,B??null,null,N===null?"open":"settled",N?.outcome??null,E.inbox?1:0,E.inbox||E.reply?1:0,f.title,f.subtitle??null,null,JSON.stringify(f),y(F)?JSON.stringify(A(F)):null,y(X)&&N===null?JSON.stringify(A(X)):null,T===null?null:JSON.stringify(T),Q,null,null,K,null,null,N?.settledAt??null,fe,me?.delivery_id??null,null,null,Ee,K)}const i=l(e,"SELECT request_id FROM human_requests WHERE state = 'settled' AND result_json IS NULL").get();if(i!==void 0)throw new Error(`human request migration produced terminal row without result: ${i.request_id}`);if(l(e,"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'review_comments'").get()!==void 0){const s=l(e,"SELECT review_id FROM review_comments WHERE review_id NOT IN (SELECT request_id FROM human_requests WHERE kind = 'review') LIMIT 1").get();if(s!==void 0)throw new Error(`review comment has no migrated review request: ${s.review_id}`)}}r(Bt,"migrateHumanRequestsState");export{ae as NOT_OTHER_APP_QUESTION,Ce as askingNodeSql,jt as cancelBindingRequest,ft as commitBindingRequest,mt as createPageRequest,Lt as firstInvalidPageSpecification,Et as getRequest,Nt as getRequestByCompanion,gt as getRequestByDirectory,bt as getRequestByIdempotencyKey,yt as getRequestByInboxTicket,qt as hasOpenReplyBearingRequestByRequester,It as hasPageResultException,se as humanRequestsRoot,wt as listBindingRequests,ht as listOpenInboxRequests,St as listOpenReplyBearingRequests,Ot as listPageSummaryRows,Tt as listPendingAsks,Dt as listRequests,At as listSubmitRequestedRequests,Rt as listUnprojectedReviews,Xt as markCompanionRetired,Mt as markProjected,Ft as markProjectionError,Bt as migrateHumanRequestsState,xt as openRequest,Ue as openRequestsByRequester,vt as pageSummaryState,pt as presentationDir,oe as publishPageRevision,ke as publishPageRevisionTo,Wt as readAnchorBase,Jt as replaceAnchorBaseLocked,P as requestDir,kt as requestSubmit,$t as revisePageRequest,Ut as setSettlementDeliveryMarksLocked,Pt as setSubmitNoteDeliveryLocked,Ct as settleRequestLocked,Ht as writeProgress};
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { PageTicketSummary, TicketSummary } from './types.js';
|
|
2
|
+
import { type PageSummaryState } from './requests.js';
|
|
2
3
|
/** SQL-backed inbox discovery. Files in request_dir are presentation projections only. */
|
|
3
4
|
export declare function scanInbox(): Promise<TicketSummary[]>;
|
|
4
5
|
export type PageHistoryEntry = PageTicketSummary;
|
|
5
|
-
/** SQL-backed page history, including terminal requests. */
|
|
6
|
-
export declare function scanPageHistory(nodeId?: string): Promise<PageHistoryEntry[]>;
|
|
6
|
+
/** SQL-backed page history, including terminal requests. `state` narrows the read in SQL: a polling viewer asks for `pending` only. */
|
|
7
|
+
export declare function scanPageHistory(nodeId?: string, state?: PageSummaryState): Promise<PageHistoryEntry[]>;
|
package/dist/core/human/scan.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var l=Object.defineProperty;var
|
|
1
|
+
var l=Object.defineProperty;var o=(t,e)=>l(t,"name",{value:e,configurable:!0});import{pageAwaitsResponse as p,pageOverviewActions as u}from"./page-schema.js";import{firstInvalidPageSpecification as m,hasPageResultException as f,listOpenInboxRequests as _,listPageSummaryRows as g,pageSummaryState as w}from"./requests.js";function r(t){try{const e=JSON.parse(t.specification_json);if(typeof e!="object"||e===null)throw new Error("not an object");return e}catch(e){throw new Error(`corrupt human request specification: ${t.request_id}`,{cause:e})}}o(r,"specification");function s(t){const e=r(t),{recommendedOptions:n,fastAction:i}=u(e),a=t.result_json===null?null:JSON.parse(t.result_json),c=w(t);return{dir:t.request_dir,id:t.request_id,inboxTicketId:t.inbox_ticket_id,kind:"page",title:t.title,subtitle:t.subtitle??"",dialect:e.dialect,placement:e.delivery.placement,inbox:t.inbox_listed,steps:e.steps,slotKinds:e.slots.map(d=>d.kind),awaitsResponse:p(e),source:e.source??{},emittedAt:typeof e.source?.emittedAt=="string"?e.source.emittedAt:t.created_at,recommendedOptions:n,...i===void 0||c!=="pending"?{}:{fastAction:i},state:c,...a?.kind==="page"?{answerDigest:a.summary.replace(/\s+/g," ").trim()}:{}}}o(s,"pageSummary");function k(t){const e=r(t),n={nodeId:t.requester_node_id??void 0};return{dir:t.request_dir,id:t.request_id,inboxTicketId:t.inbox_ticket_id,kind:"review",title:t.title,subtitle:t.subtitle??"",file:t.file??"",output:typeof e.output_path=="string"?e.output_path:`${t.request_dir}/result.json`,source:n,blockedSince:t.created_at}}o(k,"reviewSummary");async function S(){return(await _()).map(t=>t.kind==="page"?s(t):k(t)).sort((t,e)=>(e.kind==="page"?e.emittedAt:e.blockedSince).localeCompare(t.kind==="page"?t.emittedAt:t.blockedSince)||t.id.localeCompare(e.id))}o(S,"scanInbox");async function A(t,e){const n=(t!==void 0||e!==void 0)&&(await m()!==null||await f());return(await g(n?{}:{source_node_id:t,summary_state:e})).map(s).filter(i=>!n||(t===void 0||i.source.nodeId===t)&&(e===void 0||i.state===e)).sort((i,a)=>Date.parse(i.emittedAt)-Date.parse(a.emittedAt)||i.id.localeCompare(a.id))}o(A,"scanPageHistory");export{S as scanInbox,A as scanPageHistory};
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
import type { NodeAttachmentDTO } from '../../../api/dto/node-records.js';
|
|
1
2
|
/** Download every attachment of this node's run that is not already on the broker's disk (D98). The control plane puts
|
|
2
3
|
* each fetched upload in the blob store and records it on the run; the files are written where the run's prompt names
|
|
3
4
|
* them. Run before the broker hands the agent a prompt or mail. A failed download throws: the agent must not be told
|
|
4
5
|
* of a path that holds nothing. */
|
|
5
|
-
export declare function fetchRunAttachments(nodeId: string): Promise<void>;
|
|
6
|
+
export declare function fetchRunAttachments(nodeId: string, listed?: NodeAttachmentDTO[]): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var s=Object.defineProperty;var i=(a,e)=>s(a,"name",{value:e,configurable:!0});import{existsSync as m,mkdirSync as h,renameSync as p,writeFileSync as f}from"node:fs";import{dirname as l}from"node:path";import{daemonClient as y}from"./daemon-ops.js";async function A(a,e){const n=y(),o=e??(await n.listNodeAttachments(a)).attachments;for(const t of o){if(m(t.path))continue;const r=await n.readNodeAttachment(a,t.sha256);h(l(t.path),{recursive:!0});const c=`${t.path}.partial`;f(c,r),p(c,t.path)}}i(A,"fetchRunAttachments");export{A as fetchRunAttachments};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var h=Object.defineProperty;var n=(o,r)=>h(o,"name",{value:r,configurable:!0});import{spawn as l}from"node:child_process";import{writeFileSync as s}from"node:fs";import{BASH_JOB_SUPERVISOR_SCRIPT as j}from"../../bash-job-supervisor.js";import{readBashNiceness as g}from"../../bash-jobs.js";import{capturePidIdentities as S}from"../../canvas/pid.js";import{apiSocketPath as y}from"../../canvas/paths.js";import{readMachineConfig as P}from"../../../daemon/machine-link/config.js";import{freshChildNodeExecPath as I}from"../branded-host.js";import{resolveAdmittedHostCommand as w}from"../spawn-env.js";import{brokerApiUrl as u,startBrokerBashJob as B}from"./daemon-ops.js";function x(){return process.platform==="linux"&&u()===void 0}n(x,"bashJobsUseLauncher");function A(o,r){if(u()!==void 0)return[];try{if(P()===void 0)return[]}catch{return[]}return[y(),o,r]}n(A,"exitNotifyArgs");async function $(o,r,a,d,c){const b=await I();if(x()){const{pid:e}=await B(o,{job_id:r.jobId,cwd:d,env:c});return{pgid:e,identity:`launcher:${e}`}}const m=w("bash",c,d),t=l(m,["-c",j,"--",r.cmdSh,r.jobLog,r.jobExit,r.jobRun,r.jobDone,m,String(g(a)),b,r.jobActivity,...A(o,r.jobId)],{cwd:d,detached:!0,stdio:"ignore",env:c}),i=await new Promise((e,p)=>{t.once("error",p),t.pid!==void 0&&e(t.pid)});t.unref();const f=S([i])?.get(i);if(f===void 0){try{process.kill(-i,"SIGKILL")}catch{}throw new Error(`bash job ${r.jobId} started without a process identity`)}return s(r.jobPgid,String(i)),s(r.jobPgidIdentity,f),{pgid:i,identity:f}}n($,"launchBashJobSupervisor");export{x as bashJobsUseLauncher,$ as launchBashJobSupervisor};
|
|
@@ -4,6 +4,11 @@ type ExtensionStateReader = (nodeId: string) => Promise<BrokerExtensionStateDTO>
|
|
|
4
4
|
export declare function bootExtensionState(nodeId: string, read?: ExtensionStateReader): Promise<BrokerExtensionStateDTO>;
|
|
5
5
|
/** The extension state after session bind: one fresh daemon read, shared. */
|
|
6
6
|
export declare function boundExtensionState(nodeId: string, read?: ExtensionStateReader): Promise<BrokerExtensionStateDTO>;
|
|
7
|
+
/** Share the state the cycle-start response carried instead of reading it: `afterBind` is true when that request
|
|
8
|
+
* committed the session bind, and false for a review companion whose bind is still pending. */
|
|
9
|
+
export declare function seedExtensionState(nodeId: string, state: BrokerExtensionStateDTO, afterBind: boolean): void;
|
|
10
|
+
/** A pending bind has now been committed: the seeded share stands as the after-bind state. */
|
|
11
|
+
export declare function markSeededStateBound(nodeId: string): void;
|
|
7
12
|
/** End the share; the next caller reads the daemon. */
|
|
8
13
|
export declare function retireBootExtensionState(): void;
|
|
9
14
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var f=Object.defineProperty;var n=(t,e)=>f(t,"name",{value:e,configurable:!0});import{brokerExtensionState as u}from"./daemon-ops.js";const h=Symbol.for("@crouton-kit/crtr:boot-extension-state");function s(){const t=globalThis;return t[h]??={}}n(s,"slot");function c(t,e,a){const o=s(),r=o.shared;if(r!==void 0&&r.nodeId===t&&(r.afterBind||!e))return r.state;const i=a(t),d={nodeId:t,afterBind:e,state:i};return o.shared=d,i.catch(()=>{o.shared===d&&(o.shared=void 0)}),i}n(c,"share");function S(t,e=u){return c(t,!1,e)}n(S,"bootExtensionState");function b(t,e=u){return c(t,!0,e)}n(b,"boundExtensionState");function p(t,e,a){s().shared={nodeId:t,afterBind:a,state:Promise.resolve(e)}}n(p,"seedExtensionState");function E(t){const e=s().shared;e?.nodeId===t&&(e.afterBind=!0)}n(E,"markSeededStateBound");function m(){s().shared=void 0}n(m,"retireBootExtensionState");export{S as bootExtensionState,b as boundExtensionState,E as markSeededStateBound,m as retireBootExtensionState,p as seedExtensionState};
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import type { BrokerBearingsMode, BrokerCycleStartResultDTO } from '../../../api/dto/broker-ops.js';
|
|
2
|
+
import type { RecoveryStateDTO } from '../../../api/dto/recovery.js';
|
|
3
|
+
import type { NodeAttachmentDTO } from '../../../api/dto/node-records.js';
|
|
4
|
+
import type { BrokerSession } from './read-ops.js';
|
|
5
|
+
interface Entry {
|
|
6
|
+
type?: string;
|
|
7
|
+
role?: string;
|
|
8
|
+
customType?: string;
|
|
9
|
+
content?: string | Array<{
|
|
10
|
+
type: string;
|
|
11
|
+
text?: string;
|
|
12
|
+
}>;
|
|
13
|
+
details?: {
|
|
14
|
+
nodeId?: string;
|
|
15
|
+
reviewId?: string;
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
/** What the active branch holds of the context-intro baseline: none (`fresh`), another node's copied in by a fork
|
|
19
|
+
* (`inherited`), or this node's own (`present`). The match is exact on the node id the block was stamped with. */
|
|
20
|
+
export declare function bearingsModeOf(branch: Entry[], nodeId: string): BrokerBearingsMode;
|
|
21
|
+
/** Review markers present in a session branch. Pi owns this fact; crtrd compares it with the node's review binding. */
|
|
22
|
+
export declare function reviewBoundaryIdsOf(branch: Entry[]): string[];
|
|
23
|
+
/** Send the cycle-start request for the session just built (`reason` is the session start's: `startup` for a process
|
|
24
|
+
* start, `resume` for an in-place yield) and publish its response. Undefined when the cloud predates the route, the
|
|
25
|
+
* request failed or was aborted, or the session has no id yet: the cycle then runs as before. */
|
|
26
|
+
export declare function startCycle(nodeId: string, session: BrokerSession, reason: string, signal?: AbortSignal): Promise<BrokerCycleStartResultDTO | undefined>;
|
|
27
|
+
/** The stophook's session start: what the cycle-start request decided about the bind, once. Absent when the request
|
|
28
|
+
* was not made or this is a later session start in the same broker, which clears everything the request carried. */
|
|
29
|
+
export declare function takeCycleBind(nodeId: string): {
|
|
30
|
+
action: BrokerCycleStartResultDTO['action'];
|
|
31
|
+
bindPending: boolean;
|
|
32
|
+
} | undefined;
|
|
33
|
+
/** The bearings the cycle-start request rendered, once. */
|
|
34
|
+
export declare function takeCycleBoot(nodeId: string): {
|
|
35
|
+
content: string;
|
|
36
|
+
inherited?: boolean;
|
|
37
|
+
} | undefined;
|
|
38
|
+
/** The first system-prompt block the cycle-start request rendered, once, for the first model request right after the cycle starts. */
|
|
39
|
+
export declare function takeCycleSystemPrompt(nodeId: string): string | undefined;
|
|
40
|
+
/** The pending structured-output request as of the cycle start, once, for the first model request right after the cycle
|
|
41
|
+
* starts. `{ request: null }` means nothing was pending; absent when the request was not made, the cloud did not send
|
|
42
|
+
* it, it was already taken, or the first model request came later. */
|
|
43
|
+
export declare function takeCycleStructuredRequest(nodeId: string): {
|
|
44
|
+
request: Exclude<BrokerCycleStartResultDTO['structured_request'], undefined>;
|
|
45
|
+
} | undefined;
|
|
46
|
+
/** The provider-retry recovery state as of the cycle start, once: the startup recovery check's read. */
|
|
47
|
+
export declare function takeCycleRecovery(nodeId: string): RecoveryStateDTO | undefined;
|
|
48
|
+
/** The run's attachments as of the cycle start, once: the first prompt's listing. */
|
|
49
|
+
export declare function takeCycleAttachments(nodeId: string): NodeAttachmentDTO[] | undefined;
|
|
50
|
+
export {};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var m=Object.defineProperty;var r=(t,e)=>m(t,"name",{value:e,configurable:!0});import{emitEvent as y}from"../../events/emit.js";import{ApiError as l}from"../../../api/errors.js";import{CONTEXT_INTRO_CUSTOM_TYPE as b,REVIEW_BOUNDARY_CUSTOM_TYPE as g}from"../../../shared/generated-context.js";import{daemonClient as _,brokerExecutionId as k}from"./daemon-ops.js";import{seedExtensionState as T}from"./boot-state.js";function x(t){const e=t.content;return typeof e=="string"?e:Array.isArray(e)?e.filter(n=>typeof n?.text=="string").map(n=>n.text).join(`
|
|
2
|
+
`):""}r(x,"entryText");function I(t,e){const n=t.filter(o=>o.type==="custom_message"&&o.customType===b);return n.some(o=>o.details?.nodeId===e||x(o).includes(e))?"present":n.length>0?"inherited":"fresh"}r(I,"bearingsModeOf");function S(t){const e=new Set;for(const n of t)(n.role==="custom"||n.type==="custom_message")&&n.customType===g&&typeof n.details?.reviewId=="string"&&e.add(n.details.reviewId);return[...e]}r(S,"reviewBoundaryIdsOf");const p=6e4,h=Symbol.for("@crouton-kit/crtr:cycle-start");function d(){const t=globalThis;return t[h]??={}}r(d,"slot");function v(t){return t instanceof l&&t.status===404&&/no route for/.test(t.message)}r(v,"isMissingRoute");async function B(t,e,n,o){d().started=void 0;const i=e.sessionManager,u=i.getSessionId?.();if(typeof u!="string"||u==="")return;const c=i.getBranch(),a=i.getSessionFile?.();let s;try{s=await _().cycleStartBroker(t,{executionId:k(),piSessionId:u,sessionFile:typeof a=="string"&&a!==""?a:null,pid:process.pid,reason:n,reviewBoundaryIds:S(c),bearings:I(c,t)},o===void 0?void 0:{signal:o})}catch(f){!v(f)&&o?.aborted!==!0&&y({event:"broker.daemon.operation.failed",level:"error",node_id:t,error:f,fields:{operation:"cycle_start"}});return}return d().started={nodeId:t,response:s,bindTaken:!1,boot:s.boot,systemPrompt:s.system_prompt,structured:{taken:!1},startedAt:Date.now()},s.action==="none"&&s.state!==void 0&&T(t,s.state,s.bind_pending!==!0),s}r(B,"startCycle");function P(t){const e=d(),n=e.started;if(!(n===void 0||n.nodeId!==t)){if(n.bindTaken){e.started=void 0;return}return n.bindTaken=!0,{action:n.response.action,bindPending:n.response.bind_pending===!0}}}r(P,"takeCycleBind");function M(t){const e=d().started;if(e===void 0||e.nodeId!==t)return;const n=e.boot;return e.boot=void 0,n}r(M,"takeCycleBoot");function D(t){const e=d().started;if(e===void 0||e.nodeId!==t)return;const n=e.systemPrompt;return e.systemPrompt=void 0,Date.now()-e.startedAt<=p?n:void 0}r(D,"takeCycleSystemPrompt");function q(t){const e=d().started;if(!(e===void 0||e.nodeId!==t||e.structured.taken||e.response.structured_request===void 0))return e.structured.taken=!0,Date.now()-e.startedAt<=p?{request:e.response.structured_request}:void 0}r(q,"takeCycleStructuredRequest");function N(t){const e=d().started;if(e===void 0||e.nodeId!==t||e.response.recovery===void 0)return;const n=e.response.recovery;return e.response={...e.response,recovery:void 0},n}r(N,"takeCycleRecovery");function U(t){const e=d().started;if(e===void 0||e.nodeId!==t||e.response.attachments===void 0)return;const n=e.response.attachments;return e.response={...e.response,attachments:void 0},n}r(U,"takeCycleAttachments");export{I as bearingsModeOf,S as reviewBoundaryIdsOf,B as startCycle,U as takeCycleAttachments,P as takeCycleBind,M as takeCycleBoot,N as takeCycleRecovery,q as takeCycleStructuredRequest,D as takeCycleSystemPrompt};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var pe=Object.defineProperty;var m=(r,e)=>pe(r,"name",{value:e,configurable:!0});import{envModelIntent as B,envNodeCwd as Y,envProfileId as j}from"../../../shared/env.js";import{isContextOverflow as q}from"@earendil-works/pi-ai";import{classify as T}from"../../fault-classifier.js";import{isDaemonTransportApiError as V}from"../../../api/errors.js";import{isModelNotFoundError as he,isProviderUnconfiguredError as me}from"../fault.js";import{brokerRecovery as ge,daemonClient as X,mutateBrokerFault as J,mutateBrokerProviderRetry as I}from"./daemon-ops.js";import{extractCoolingDeadline as ye}from"../managed-provider-cooling.js";import{extractProviderFailureDetails as ve}from"../../provider-failure.js";import{expandModelCandidates as K,KEY_CREDENTIAL_SOURCE as we,modelRequestFromConfig as z}from"../../model-routes.js";import{operationIdContext as H}from"../../events/operation-id.js";import{emitEvent as F}from"../../events/emit.js";import{CONNECTION_FAULT_RECOVERY_BODY as Fe,PROVIDER_FAULT_RECOVERY_BODY as ke,RUN_CONNECTION_FAULT_RETRY_BODY as be,formatCard as Q,formatModelFallbackRecovery as Ie}from"../../../shared/generated-context.js";import{markFatalOnExhaust as Z,nextFaultRetry as C,policyFor as ee}from"../fault-recovery.js";import{parseModelSpec as te}from"../model-selection.js";import{endedByAbort as ne}from"../session-cycles.js";import{isManagedProvider as ie,resolveProviderCandidates as _e}from"../../subscription-state.js";import{announceMessageOrigin as re}from"../stamp/channel.js";import{LLM_REFUSAL_DIAGNOSTIC as Ee,refusalRetryAt as Re}from"./model-adapter.js";import{isSafetyRefusal as se}from"../../llm/refusal.js";const Se=2147483647,oe=3e4;function Ae(r,e,t){const n=Date.parse(r);return!Number.isFinite(n)||t+e-n>oe}m(Ae,"runTurnRetryExpired");class _ extends Error{static{m(this,"StaleOutcome")}}const Me=1e3,xe=3e4;function Te(r,e){return r!=="connection"?ke:e?be:Fe}m(Te,"retryCardBody");function R(r){return{link:r.link,op:r.op,kind:r.kind,retry:r.retry,message:r.message,since:r.since,operation_id:r.operation_id,...r.anchor_entry_id===void 0?{}:{anchorEntryId:r.anchor_entry_id},...r.provider_error===void 0?{}:{providerError:r.provider_error}}}m(R,"policyFault");function ae(r){return r instanceof Error?r.message:String(r)}m(ae,"errorText");function de(r){return V(r)||T("pi\u2192provider",r).disposition==="auto"}m(de,"isTransientRejection");function O(r){return{link:r.link,op:r.op,kind:r.kind,retry:r.retry,message:r.message,...r.operation_id===void 0?{}:{operation_id:r.operation_id},...r.since===void 0?{}:{since:r.since},...r.anchorEntryId===void 0?{}:{anchor_entry_id:r.anchorEntryId},...r.providerError===void 0?{}:{provider_error:r.providerError}}}m(O,"faultInput");function le(r,e){const t=m(n=>`${n.providerId}/${n.modelId}`===e.modelSpec,"onLiveModel");return(r.find(n=>t(n)&&n.thinkingLevel===e.thinkingLevel)??r.find(t))?.rank}m(le,"liveRouteRank");function ue(r){const e=T("pi\u2192provider",r),t=r.diagnostics?.some(n=>n.type===Ee)??!1;return{classified:e,disposition:t?"fatal":e.disposition}}m(ue,"settledProviderFault");function et(r,e){if(r.stopReason!=="error"||ne(r)||se(r)||q(r,e))return!1;const{classified:t,disposition:n}=ue(r);return n==="auto"&&(t.kind==="connection"||t.kind==="rate-limit"||t.kind==="overloaded")}m(et,"willDaemonRetry");const Ce=/does not support assistant message prefill|conversation must end with a user message/i;function Oe(r,e){return e&&Ce.test(r)}m(Oe,"isPrefillRejectionDuringEpisode");class tt{static{m(this,"FaultRetry")}deps;timer=null;failedRetryRoutes=new Set;notFoundModels=new Set;providerFallbackInFlight=null;notFoundFallbackInFlight=null;stagedCapacityFailure=null;agentStarts=0;constructor(e){this.deps=e}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}reset(){this.clearTimer(),this.deps.turnEnds?.abandon(),this.providerFallbackInFlight=null,this.notFoundFallbackInFlight=null,this.stagedCapacityFailure=null}fallbackInFlight(){return this.providerFallbackInFlight!==null||this.notFoundFallbackInFlight!==null}async faultIsFatal(){const e=(await this.state()).fault;return e!==null&&e.link==="pi\u2192provider"&&e.retry.disposition==="fatal"}abandonTurnEnd(){this.deps.turnEnds?.abandon()}state(){return ge(this.deps.nodeId)}async recordFault(e){return(await J(this.deps.nodeId,{op:"record",input:e})).fault}async clearFault(e,t=!1){await J(this.deps.nodeId,{op:"clear",...e===void 0?{}:{link:e},...t?{preserve_episode:!0}:{}})}sessionId(e){const t=e.sessionManager.getSessionId?.();return typeof t=="string"&&t!==""?t:null}async clearEpisode(e){const t=this.sessionId(e);t!==null&&await I(this.deps.nodeId,{op:"clear",session_id:t})}onEvent(e){e.type==="agent_start"&&this.agentStarts++,this.maybeSwitchProviderForRetry(e),this.maybeFallbackOnUnusableModel(e)}isActiveAutoFault(e){return e===null||e.retry.disposition!=="auto"||e.retry.by!=="daemon"?!1:e.kind==="connection"||e.kind==="rate-limit"||e.kind==="overloaded"}async publishSettledProviderFault(e){const t={agentEnd:e.stagedProviderAgentEnd,watchdogAbort:e.stagedWatchdogAbort,refreshAbort:e.stagedRefreshAbort,overflowFailure:e.stagedOverflowFailure,capacityFailure:this.stagedCapacityFailure?.generation===e?this.stagedCapacityFailure:null};this.stagedCapacityFailure=null,e.stagedProviderAgentEnd=null,e.stagedWatchdogAbort=!1,e.stagedRefreshAbort=!1,e.stagedOverflowFailure=null;const n=this.agentStarts,i=m(()=>{if(this.deps.installedGeneration()!==e||this.agentStarts!==n)throw new _},"assertCurrent");try{await this.retryWhileDaemonUnreachable("settled turn fault write",()=>this.recordStagedOutcome(e,t,i),i)}catch(s){if(!(s instanceof _))throw s}}async retryWhileDaemonUnreachable(e,t,n){let i=Me;for(;;){try{await t();return}catch(s){if(!V(s))throw s;F({level:"warn",event:"broker.runtime.diagnostic",fields:{message:`${e} waiting for the daemon: ${s.message}`}})}await new Promise(s=>setTimeout(s,i)),i=Math.min(i*2,xe),n()}}async recordStagedOutcome(e,t,n){const{agentEnd:i,watchdogAbort:s,refreshAbort:a,overflowFailure:c,capacityFailure:f}=t,o=e.session,d=m(async k=>{n(),await this.clearEpisode(k)},"clearEpisode"),g=m(async k=>{n(),await this.recordFault(k)},"recordFault"),y=m(async(k,fe)=>{n(),await this.recordPendingProviderFault(k,fe)},"recordPendingProviderFault"),u=await this.state(),p=u.fault,v=u.episode,b=this.sessionId(o),w=this.isActiveAutoFault(p)&&p.link==="pi\u2192provider"?p:v?.state==="admitted"&&v.session_id===b&&this.isActiveAutoFault(v.fault)?v.fault:null,h=w===null?null:{since:w.since,anchorEntryId:w.anchor_entry_id,attempt:w.retry.attempt},l=[...Array.isArray(i?.messages)?i.messages:[]].reverse().find(k=>typeof k=="object"&&k!==null&&k.role==="assistant");if(f!==null||c!==null){await d(o),await g({link:"pi\u2192provider",op:"context overflow recovery",kind:"context-overflow",retry:{disposition:"fatal"},message:f?.errorMessage??c.errorMessage,anchor_entry_id:o.sessionManager.getLeafId?.()??void 0});return}if(s&&l?.stopReason==="aborted"){await y(o,{link:"pi\u2192provider",op:"generation turn",kind:"connection",retry:{disposition:"auto",by:"daemon",...h?.attempt!==void 0?{attempt:h.attempt}:{}},message:typeof l.errorMessage=="string"?l.errorMessage:"engine error (no errorMessage recorded)",...h!==null?{since:h.since}:{},anchor_entry_id:this.retryAnchor(o,h?.anchorEntryId)});return}if(l?.stopReason!=="error"){l!==void 0&&await d(o);return}if(a){await d(o);return}if(se(l)){await d(o);return}const A=typeof l.errorMessage=="string"?l.errorMessage:"engine error (no errorMessage recorded)";if(ne({stopReason:"error",errorMessage:A})){await d(o);return}const E=q(l,o.model?.contextWindow),M=ue(l),$=h!==null&&M.disposition!=="auto"&&Oe(A,!0),ce=$?{kind:"connection",disposition:"auto"}:M.classified,S=$?"auto":M.disposition,D=ye(l),L=Re(l),N=ve(l),G=typeof l.provider=="string"&&l.provider!==""?l.provider:o.model?.provider,U=typeof l.model=="string"&&l.model!==""?l.model:o.model?.id,W=N===void 0||G===void 0||U===void 0?void 0:{provider:G,model:U,...N};E&&await d(o);const x={link:"pi\u2192provider",op:"generation turn",kind:E?"context-overflow":ce.kind,retry:E?{disposition:"fatal"}:S==="auto"?{disposition:"auto",by:"daemon",...D!==void 0?{nextAt:new Date(D).toISOString()}:{},...h?.attempt!==void 0?{attempt:h.attempt}:{}}:{disposition:S,...L!==void 0?{nextAt:new Date(L).toISOString()}:{}},message:A,...!E&&S==="auto"&&h!==null?{since:h.since}:{},anchor_entry_id:!E&&S==="auto"?this.retryAnchor(o,h?.anchorEntryId):o.sessionManager.getLeafId?.()??void 0,...W===void 0?{}:{provider_error:W}};x.retry.disposition==="auto"?await y(o,x):(await d(o),await g(x))}retryAnchor(e,t){const n=e.sessionManager.getLeafId?.()??void 0;return t!==void 0&&!this.hasProgressPastAnchor(e,t)?t:n}async recoverOnStartup(){const e=this.deps.installedGeneration();if(e===void 0)return"none";const t=(await this.state()).episode,n=this.sessionId(e.session);if(this.deps.cfg.newCycle===!0)return t!==null&&n!==null&&t.session_id===n&&await I(this.deps.nodeId,{op:"invalidate",session_id:n}),"none";if(t===null||n===null||t.session_id!==n)return"none";if(t.state==="admitted")if(t.fault.anchor_entry_id!==void 0&&!this.hasProgressPastAnchor(e.session,t.fault.anchor_entry_id)){if(!(await I(this.deps.nodeId,{op:"reopen",session_id:n})).applied)return"none"}else return await this.clearEpisode(e.session),"none";else if(t.state!=="pending")return"none";await this.recordFault(O(R(t.fault)));const i=await this.schedule();return i==="armed"?"retry-armed":i==="exhausted"?"fatal":"none"}hasProgressPastAnchor(e,t){const n=e.sessionManager.getBranch(),i=n.findIndex(a=>a.id===t);return(i===-1?n:n.slice(i+1)).some(a=>{if(a.type!=="message")return!1;const{message:c}=a;return c.role==="toolResult"?!0:c.role==="assistant"&&Array.isArray(c.content)&&c.content.length>0})}async schedule(){const e=this.deps.installedGeneration(),t=this.deps.currentSession();if(t.isStreaming||this.timer!==null)return this.timer!==null?"armed":"none";if(e===void 0)return this.abandonTurnEnd(),"none";const n=await this.state(),i=n.fault;if(!this.isActiveAutoFault(i)||this.sessionId(t)!==null&&!this.pendingEpisodeMatches(t,i,n))return this.clearTimer(),this.abandonTurnEnd(),"none";const s=Date.now(),a=this.faultRetryDelayMs(i,s);return a!==null&&this.deps.turnEnds?.holding()===!0&&Ae(i.since,a,s)?(await this.endRunTurnOnFault(t,i,a),"none"):a!==null?(this.clearAndArmFaultRetry(a,e),this.timer!==null?"armed":"none"):(this.abandonTurnEnd(),i.retry.nextAt!==void 0||this.deps.installedGeneration()!==e||this.deps.currentSession()!==t||t.isStreaming?"none":(await this.settleExhausted(t,i),"exhausted"))}async settleExhausted(e,t){await this.recordFault(O(Z(R(t)))),await this.clearEpisode(e)}async endRunTurnOnFault(e,t,n){this.clearTimer(),this.abandonTurnEnd(),F({level:"info",event:"broker.runtime.diagnostic",fields:{message:`run turn completed on provider fault: ${t.kind} retry in ${n}ms is past the ${oe}ms turn window (since ${t.since}, attempt ${t.retry.attempt??0})`}}),await this.clearEpisode(e),await this.clearFault("pi\u2192provider")}async rearmIfStranded(){if(this.timer!==null||this.deps.installedGeneration()===void 0)return;const e=this.deps.currentSession();if(e.isStreaming)return;const t=await this.state();!this.isActiveAutoFault(t.fault)||!this.pendingEpisodeMatches(e,t.fault,t)||await this.schedule()}maybeSwitchProviderForRetry(e){if(e.type!=="auto_retry_start")return;const t=T("pi\u2192provider",e.errorMessage??"").kind;if(t!=="rate-limit"&&t!=="connection"||this.providerFallbackInFlight!==null||this.deps.cfg.modelExact===!0)return;const n=this.deps.installedGeneration();if(n===void 0)return;const i=this.deps.currentSession(),s=this.deps.currentServices(),a=this.deps.formatModelSpec(i.model,i.thinkingLevel);if(a===null)return;const c=z(this.deps.cfg.model,B(),!1);if(c===void 0)return;const f=te(a),o=(async()=>{const d=await K(c,Y()??this.deps.cfg.cwd,j()),g=le(d,f),y=g===void 0?{route:void 0,capacityExhausted:!1}:await this.nextEligibleFallbackRoute(d.slice(g+1),this.deps.registryOf(s),i.getContextUsage()?.tokens,b=>!this.failedRetryRoutes.has(b.routeId));if(y.route===void 0){y.capacityExhausted&&(this.stageCapacityFailure(n,i),queueMicrotask(()=>{this.deps.installedGeneration()===n&&this.deps.currentSession()===i&&i.abortRetry()}));return}const u=y.route,p=this.deps.registryOf(s).find(u.providerId,u.modelId);if(!p||(await i.setModel(p),this.deps.installedGeneration()!==n||this.deps.currentSession()!==i))return;const v=`${u.providerId}/${u.modelId}`===f.modelSpec?f.thinkingLevel:u.thinkingLevel;i.setThinkingLevel(v??"off"),this.failedRetryRoutes.add(u.routeId),await this.deps.broadcastModelChanged(!1)})().catch(d=>{F({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`provider route fallback failed: ${d instanceof Error?d.message:String(d)}`}})}).finally(()=>{this.deps.installedGeneration()===n&&(this.providerFallbackInFlight=null)});this.providerFallbackInFlight=o}maybeFallbackOnUnusableModel(e){if(e.type!=="message_end"||e.message.role!=="assistant"||e.message.stopReason!=="error")return;const t=me(e.message.errorMessage??"");if(!t&&!he(e.message.errorMessage??"")||this.deps.cfg.modelExact===!0||this.notFoundFallbackInFlight!==null)return;const n=this.deps.installedGeneration();if(n===void 0)return;const i=this.deps.currentSession(),s=this.deps.currentServices(),a=this.deps.formatModelSpec(i.model,i.thinkingLevel);if(a===null)return;const c=te(a);this.notFoundModels.add(c.modelSpec);const f=z(this.deps.cfg.model,B(),!1),o=(async()=>{const d=f?await K(f,Y()??this.deps.cfg.cwd,j()):[],g=le(d,c),y=g===void 0?{route:void 0,capacityExhausted:!1}:await this.nextEligibleFallbackRoute(d.slice(g+1),this.deps.registryOf(s),i.getContextUsage()?.tokens,h=>!this.notFoundModels.has(`${h.providerId}/${h.modelId}`));if(y.route===void 0){y.capacityExhausted&&this.stageCapacityFailure(n,i);return}const u=y.route,p=`${u.providerId}/${u.modelId}${u.thinkingLevel?`:${u.thinkingLevel}`:""}`,v=this.deps.registryOf(s).find(u.providerId,u.modelId);if(v===void 0){F({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`${t?"unconfigured-provider":"not_found"} fallback skipped: ${p} is not registered`}});return}if(await i.setModel(v),this.deps.installedGeneration()!==n||this.deps.currentSession()!==i)return;i.setThinkingLevel(u.thinkingLevel??"off"),await this.deps.broadcastModelChanged();const b=this.deps.formatModelSpec(i.model,i.thinkingLevel)??p;if(F({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`${t?"unconfigured-provider":"not_found"} fallback: ${a} unavailable \u2192 ${b}; re-driving turn`}}),await i.agent.waitForIdle(),this.deps.installedGeneration()!==n||this.deps.currentSession()!==i)return;t&&await this.clearFault("pi\u2192provider");const w=Q("recovery",{},Ie(a,b,t?"credential":"not-found"));re(w,{type:"runtime",kind:"recovery"}),await this.deps.turnAdmission.admit(h=>H.fresh(()=>i.prompt(w,{preflightResult:h})))})().catch(d=>{F({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`${t?"unconfigured-provider":"not_found"} fallback failed: ${d instanceof Error?d.message:String(d)}`}})}).finally(()=>{this.deps.installedGeneration()===n&&(this.notFoundFallbackInFlight=null)});this.notFoundFallbackInFlight=o}async nextEligibleFallbackRoute(e,t,n,i){let s=0,a=0;for(const c of e){if(!i(c)||_e([{...c,...await this.routeAvailability(c,t),automaticFallback:!0}]).candidates.length===0)continue;const f=t.find(c.providerId,c.modelId);if(f!==void 0){if(s++,this.targetCannotFitContext(f.contextWindow,n)){a++;continue}return{route:c,capacityExhausted:!1}}}return{route:void 0,capacityExhausted:s>0&&s===a}}async routeAvailability(e,t){const n=t.find(e.providerId,e.modelId);if(n===void 0)return{registered:!1,authenticated:!1};if(e.credentialSource===we&&ie(e.providerId))return{registered:!0,authenticated:(await X().listModelAuth()).keys.some(a=>a.provider===e.providerId)};if(!ie(e.providerId))return{registered:!0,authenticated:t.hasConfiguredAuth(n)};const i=await X().getModelAuthReadiness({model:`${e.providerId}/${e.modelId}`}),s=i.rate_limited_until==null?void 0:Date.parse(i.rate_limited_until);return{registered:!0,authenticated:i.credential==="ready",...s!==void 0&&s>Date.now()?{coolingUntil:s}:{}}}targetCannotFitContext(e,t){return Number.isFinite(e)&&Number.isFinite(t)&&e<t}stageCapacityFailure(e,t){const n=t.getContextUsage()?.tokens;this.stagedCapacityFailure={generation:e,errorMessage:Number.isFinite(n)?`All available fallback models have context windows smaller than the current conversation (${n} tokens).`:"All available fallback models have context windows smaller than the current conversation."}}async recordPendingProviderFault(e,t){const n=this.sessionId(e);if(n===null){await this.recordFault(t);return}await I(this.deps.nodeId,{op:"record-pending",session_id:n,input:t})}pendingEpisodeMatches(e,t,n){const i=this.sessionId(e),s=n.episode;return i!==null&&s!==null&&s.state==="pending"&&s.session_id===i&&s.fault.fault_id===t.fault_id}faultRetryDelayMs(e,t){if(e.retry.nextAt!==void 0){const n=Date.parse(e.retry.nextAt)-t;return Number.isFinite(n)?Math.max(0,n):null}return C(R(e),t)?.delayMs??null}clearAndArmFaultRetry(e,t){if(this.deps.installedGeneration()!==t)return;this.clearTimer();const n=Math.min(Math.max(0,e),Se),i=Math.max(0,e-n);this.timer=setTimeout(()=>{if(this.timer=null,this.deps.installedGeneration()===t){if(i>0){this.clearAndArmFaultRetry(i,t);return}this.runFaultRetry().catch(s=>{this.abandonTurnEnd(),F({level:"warn",event:"broker.runtime.diagnostic",fields:{message:`fault retry fire failed: ${s instanceof Error?s.message:String(s)}`}})})}},n),typeof this.timer.unref=="function"&&this.timer.unref()}async runFaultRetry(){await this.attemptFaultRetry()===void 0&&this.abandonTurnEnd()}async attemptFaultRetry(){const e=this.deps.installedGeneration();if(e===void 0)return;const t=e.session;if(t.isStreaming)return;const n=(await this.state()).fault;if(!this.isActiveAutoFault(n))return;let i=n;if(n.kind==="connection"&&this.deps.turnEnds===void 0){const u=await this.deps.retryProbe();if(this.deps.installedGeneration()!==e||this.deps.currentSession()!==t||t.isStreaming)return;const p=(await this.state()).fault;if(!this.isActiveAutoFault(p)||p.since!==n.since)return;if(!u)return this.clearAndArmFaultRetry(ee(p.kind).baseDelayMs,e),"rearmed";i=p}const s=this.deps.turnEnds!==void 0,a=i.retry.attempt??0,c=ee(i.kind),f=a>=c.max?null:C(R(i),Date.now());if(f===null){await this.settleExhausted(t,i);return}if(this.deps.installedGeneration()!==e||this.deps.currentSession()!==t)return;let o,d;const g=await this.deps.turnAdmission.admit(async u=>{const p=(await this.state()).fault;if(this.deps.installedGeneration()!==e||this.deps.currentSession()!==t||t.isStreaming||!this.isActiveAutoFault(p)||p.since!==i.since){u();return}const v=this.sessionId(t);if(v===null){u();return}if(!(await I(this.deps.nodeId,{op:"admit",session_id:v,fault_id:p.fault_id,retry:f.fault.retry})).applied){u();return}const w=i.anchor_entry_id;if(w!==void 0&&(t.sessionManager.getLeafId?.()??null)!==w&&!this.hasProgressPastAnchor(t,w))try{const l=await t.navigateTree(w);if(this.deps.installedGeneration()!==e||this.deps.currentSession()!==t){u();return}l.cancelled||this.deps.reWelcomeAll()}catch(l){F({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`fault retry rewind skipped: ${l instanceof Error?l.message:String(l)}`}})}const h=Q("recovery",s?{attempt:f.attempt}:{attempt:f.attempt,max:f.max},Te(i.kind,s));re(h,{type:"runtime",kind:"recovery"}),this.deps.turnEnds?.beginRecovery();const P=this.agentStarts;try{await H.fresh(()=>t.prompt(h,{preflightResult:u}))}catch(l){o={error:l,faultId:p.fault_id,startsBefore:P},de(l)||(d={code:"model_error",message:`recovery prompt rejected: ${ae(l)}`});return}finally{this.deps.turnEnds?.recoveryReturned(d)}return"prompted"});if(o===void 0)return g;const y=await this.settleRejectedRecoveryPrompt(e,t,o);if(y==="stale")throw o.error;return y==="rearmed"?"rearmed":void 0}async settleRejectedRecoveryPrompt(e,t,n){const i=this.sessionId(t);if(i===null)return"stale";const s=m(()=>{if(this.deps.installedGeneration()!==e||this.deps.currentSession()!==t||t.isStreaming||this.agentStarts!==n.startsBefore)throw new _},"assertCurrent"),a=ae(n.error),c=de(n.error);try{let f;return await this.retryWhileDaemonUnreachable("rejected recovery prompt settlement",async()=>{s();const{episode:o}=await this.state();if(s(),o===null||o.state!=="admitted"||o.session_id!==i||o.fault.fault_id!==n.faultId)throw new _;const d=R(o.fault),g=c&&this.deps.turnEnds===void 0?C(d,Date.now()):null,y=g===null?Z(c?d:{...d,kind:"other",message:`recovery prompt rejected: ${a}`}):{...d,retry:{...d.retry,nextAt:g.nextAt}};if(s(),!(await I(this.deps.nodeId,{op:"settle-rejected",session_id:i,fault_id:n.faultId,reopen:g!==null,input:O(y)})).applied)throw new _;f=g?.nextAt},s),f===void 0?(F({level:"warn",event:"broker.runtime.diagnostic",fields:{message:`recovery prompt rejected, ending the retry episode: ${a}`}}),"ended"):(F({level:"warn",event:"broker.runtime.diagnostic",fields:{message:`recovery prompt rejected before any turn started, retrying at ${f}: ${a}`}}),await this.schedule(),"rearmed")}catch(f){if(!(f instanceof _))throw f;return"stale"}}}export{tt as FaultRetry,oe as RUN_TURN_RETRY_WINDOW_MS,Oe as isPrefillRejectionDuringEpisode,Te as retryCardBody,Ae as runTurnRetryExpired,ue as settledProviderFault,et as willDaemonRetry};
|
|
1
|
+
var pe=Object.defineProperty;var m=(r,e)=>pe(r,"name",{value:e,configurable:!0});import{envModelIntent as B,envNodeCwd as Y,envProfileId as j}from"../../../shared/env.js";import{isContextOverflow as q}from"@earendil-works/pi-ai";import{classify as C}from"../../fault-classifier.js";import{isDaemonTransportApiError as V}from"../../../api/errors.js";import{isModelNotFoundError as he,isProviderUnconfiguredError as me}from"../fault.js";import{takeCycleRecovery as ge}from"./cycle-start.js";import{brokerRecovery as ye,daemonClient as X,mutateBrokerFault as J,mutateBrokerProviderRetry as I}from"./daemon-ops.js";import{extractCoolingDeadline as ve}from"../managed-provider-cooling.js";import{extractProviderFailureDetails as we}from"../../provider-failure.js";import{expandModelCandidates as K,KEY_CREDENTIAL_SOURCE as Fe,modelRequestFromConfig as z}from"../../model-routes.js";import{operationIdContext as H}from"../../events/operation-id.js";import{emitEvent as F}from"../../events/emit.js";import{CONNECTION_FAULT_RECOVERY_BODY as ke,PROVIDER_FAULT_RECOVERY_BODY as be,RUN_CONNECTION_FAULT_RETRY_BODY as Ie,formatCard as Q,formatModelFallbackRecovery as _e}from"../../../shared/generated-context.js";import{markFatalOnExhaust as Z,nextFaultRetry as T,policyFor as ee}from"../fault-recovery.js";import{parseModelSpec as te}from"../model-selection.js";import{endedByAbort as ne}from"../session-cycles.js";import{isManagedProvider as ie,resolveProviderCandidates as Ee}from"../../subscription-state.js";import{announceMessageOrigin as re}from"../stamp/channel.js";import{LLM_REFUSAL_DIAGNOSTIC as Re,refusalRetryAt as Se}from"./model-adapter.js";import{isSafetyRefusal as se}from"../../llm/refusal.js";const Ae=2147483647,oe=3e4;function Me(r,e,t){const n=Date.parse(r);return!Number.isFinite(n)||t+e-n>oe}m(Me,"runTurnRetryExpired");class _ extends Error{static{m(this,"StaleOutcome")}}const xe=1e3,Ce=3e4;function Te(r,e){return r!=="connection"?be:e?Ie:ke}m(Te,"retryCardBody");function R(r){return{link:r.link,op:r.op,kind:r.kind,retry:r.retry,message:r.message,since:r.since,operation_id:r.operation_id,...r.anchor_entry_id===void 0?{}:{anchorEntryId:r.anchor_entry_id},...r.provider_error===void 0?{}:{providerError:r.provider_error}}}m(R,"policyFault");function ae(r){return r instanceof Error?r.message:String(r)}m(ae,"errorText");function de(r){return V(r)||C("pi\u2192provider",r).disposition==="auto"}m(de,"isTransientRejection");function O(r){return{link:r.link,op:r.op,kind:r.kind,retry:r.retry,message:r.message,...r.operation_id===void 0?{}:{operation_id:r.operation_id},...r.since===void 0?{}:{since:r.since},...r.anchorEntryId===void 0?{}:{anchor_entry_id:r.anchorEntryId},...r.providerError===void 0?{}:{provider_error:r.providerError}}}m(O,"faultInput");function le(r,e){const t=m(n=>`${n.providerId}/${n.modelId}`===e.modelSpec,"onLiveModel");return(r.find(n=>t(n)&&n.thinkingLevel===e.thinkingLevel)??r.find(t))?.rank}m(le,"liveRouteRank");function ue(r){const e=C("pi\u2192provider",r),t=r.diagnostics?.some(n=>n.type===Re)??!1;return{classified:e,disposition:t?"fatal":e.disposition}}m(ue,"settledProviderFault");function nt(r,e){if(r.stopReason!=="error"||ne(r)||se(r)||q(r,e))return!1;const{classified:t,disposition:n}=ue(r);return n==="auto"&&(t.kind==="connection"||t.kind==="rate-limit"||t.kind==="overloaded")}m(nt,"willDaemonRetry");const Oe=/does not support assistant message prefill|conversation must end with a user message/i;function Pe(r,e){return e&&Oe.test(r)}m(Pe,"isPrefillRejectionDuringEpisode");class it{static{m(this,"FaultRetry")}deps;timer=null;failedRetryRoutes=new Set;notFoundModels=new Set;providerFallbackInFlight=null;notFoundFallbackInFlight=null;stagedCapacityFailure=null;agentStarts=0;constructor(e){this.deps=e}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}reset(){this.clearTimer(),this.deps.turnEnds?.abandon(),this.providerFallbackInFlight=null,this.notFoundFallbackInFlight=null,this.stagedCapacityFailure=null}fallbackInFlight(){return this.providerFallbackInFlight!==null||this.notFoundFallbackInFlight!==null}async faultIsFatal(){const e=(await this.state()).fault;return e!==null&&e.link==="pi\u2192provider"&&e.retry.disposition==="fatal"}abandonTurnEnd(){this.deps.turnEnds?.abandon()}state(){return ye(this.deps.nodeId)}async recordFault(e){return(await J(this.deps.nodeId,{op:"record",input:e})).fault}async clearFault(e,t=!1){await J(this.deps.nodeId,{op:"clear",...e===void 0?{}:{link:e},...t?{preserve_episode:!0}:{}})}sessionId(e){const t=e.sessionManager.getSessionId?.();return typeof t=="string"&&t!==""?t:null}async clearEpisode(e){const t=this.sessionId(e);t!==null&&await I(this.deps.nodeId,{op:"clear",session_id:t})}onEvent(e){e.type==="agent_start"&&this.agentStarts++,this.maybeSwitchProviderForRetry(e),this.maybeFallbackOnUnusableModel(e)}isActiveAutoFault(e){return e===null||e.retry.disposition!=="auto"||e.retry.by!=="daemon"?!1:e.kind==="connection"||e.kind==="rate-limit"||e.kind==="overloaded"}async publishSettledProviderFault(e){const t={agentEnd:e.stagedProviderAgentEnd,watchdogAbort:e.stagedWatchdogAbort,refreshAbort:e.stagedRefreshAbort,overflowFailure:e.stagedOverflowFailure,capacityFailure:this.stagedCapacityFailure?.generation===e?this.stagedCapacityFailure:null};this.stagedCapacityFailure=null,e.stagedProviderAgentEnd=null,e.stagedWatchdogAbort=!1,e.stagedRefreshAbort=!1,e.stagedOverflowFailure=null;const n=this.agentStarts,i=m(()=>{if(this.deps.installedGeneration()!==e||this.agentStarts!==n)throw new _},"assertCurrent");try{await this.retryWhileDaemonUnreachable("settled turn fault write",()=>this.recordStagedOutcome(e,t,i),i)}catch(s){if(!(s instanceof _))throw s}}async retryWhileDaemonUnreachable(e,t,n){let i=xe;for(;;){try{await t();return}catch(s){if(!V(s))throw s;F({level:"warn",event:"broker.runtime.diagnostic",fields:{message:`${e} waiting for the daemon: ${s.message}`}})}await new Promise(s=>setTimeout(s,i)),i=Math.min(i*2,Ce),n()}}async recordStagedOutcome(e,t,n){const{agentEnd:i,watchdogAbort:s,refreshAbort:a,overflowFailure:c,capacityFailure:f}=t,o=e.session,d=m(async k=>{n(),await this.clearEpisode(k)},"clearEpisode"),g=m(async k=>{n(),await this.recordFault(k)},"recordFault"),y=m(async(k,fe)=>{n(),await this.recordPendingProviderFault(k,fe)},"recordPendingProviderFault"),u=await this.state(),p=u.fault,v=u.episode,b=this.sessionId(o),w=this.isActiveAutoFault(p)&&p.link==="pi\u2192provider"?p:v?.state==="admitted"&&v.session_id===b&&this.isActiveAutoFault(v.fault)?v.fault:null,h=w===null?null:{since:w.since,anchorEntryId:w.anchor_entry_id,attempt:w.retry.attempt},l=[...Array.isArray(i?.messages)?i.messages:[]].reverse().find(k=>typeof k=="object"&&k!==null&&k.role==="assistant");if(f!==null||c!==null){await d(o),await g({link:"pi\u2192provider",op:"context overflow recovery",kind:"context-overflow",retry:{disposition:"fatal"},message:f?.errorMessage??c.errorMessage,anchor_entry_id:o.sessionManager.getLeafId?.()??void 0});return}if(s&&l?.stopReason==="aborted"){await y(o,{link:"pi\u2192provider",op:"generation turn",kind:"connection",retry:{disposition:"auto",by:"daemon",...h?.attempt!==void 0?{attempt:h.attempt}:{}},message:typeof l.errorMessage=="string"?l.errorMessage:"engine error (no errorMessage recorded)",...h!==null?{since:h.since}:{},anchor_entry_id:this.retryAnchor(o,h?.anchorEntryId)});return}if(l?.stopReason!=="error"){l!==void 0&&await d(o);return}if(a){await d(o);return}if(se(l)){await d(o);return}const A=typeof l.errorMessage=="string"?l.errorMessage:"engine error (no errorMessage recorded)";if(ne({stopReason:"error",errorMessage:A})){await d(o);return}const E=q(l,o.model?.contextWindow),M=ue(l),$=h!==null&&M.disposition!=="auto"&&Pe(A,!0),ce=$?{kind:"connection",disposition:"auto"}:M.classified,S=$?"auto":M.disposition,D=ve(l),L=Se(l),N=we(l),G=typeof l.provider=="string"&&l.provider!==""?l.provider:o.model?.provider,U=typeof l.model=="string"&&l.model!==""?l.model:o.model?.id,W=N===void 0||G===void 0||U===void 0?void 0:{provider:G,model:U,...N};E&&await d(o);const x={link:"pi\u2192provider",op:"generation turn",kind:E?"context-overflow":ce.kind,retry:E?{disposition:"fatal"}:S==="auto"?{disposition:"auto",by:"daemon",...D!==void 0?{nextAt:new Date(D).toISOString()}:{},...h?.attempt!==void 0?{attempt:h.attempt}:{}}:{disposition:S,...L!==void 0?{nextAt:new Date(L).toISOString()}:{}},message:A,...!E&&S==="auto"&&h!==null?{since:h.since}:{},anchor_entry_id:!E&&S==="auto"?this.retryAnchor(o,h?.anchorEntryId):o.sessionManager.getLeafId?.()??void 0,...W===void 0?{}:{provider_error:W}};x.retry.disposition==="auto"?await y(o,x):(await d(o),await g(x))}retryAnchor(e,t){const n=e.sessionManager.getLeafId?.()??void 0;return t!==void 0&&!this.hasProgressPastAnchor(e,t)?t:n}async recoverOnStartup(){const e=this.deps.installedGeneration();if(e===void 0)return"none";const t=(ge(this.deps.nodeId)??await this.state()).episode,n=this.sessionId(e.session);if(this.deps.cfg.newCycle===!0)return t!==null&&n!==null&&t.session_id===n&&await I(this.deps.nodeId,{op:"invalidate",session_id:n}),"none";if(t===null||n===null||t.session_id!==n)return"none";if(t.state==="admitted")if(t.fault.anchor_entry_id!==void 0&&!this.hasProgressPastAnchor(e.session,t.fault.anchor_entry_id)){if(!(await I(this.deps.nodeId,{op:"reopen",session_id:n})).applied)return"none"}else return await this.clearEpisode(e.session),"none";else if(t.state!=="pending")return"none";await this.recordFault(O(R(t.fault)));const i=await this.schedule();return i==="armed"?"retry-armed":i==="exhausted"?"fatal":"none"}hasProgressPastAnchor(e,t){const n=e.sessionManager.getBranch(),i=n.findIndex(a=>a.id===t);return(i===-1?n:n.slice(i+1)).some(a=>{if(a.type!=="message")return!1;const{message:c}=a;return c.role==="toolResult"?!0:c.role==="assistant"&&Array.isArray(c.content)&&c.content.length>0})}async schedule(){const e=this.deps.installedGeneration(),t=this.deps.currentSession();if(t.isStreaming||this.timer!==null)return this.timer!==null?"armed":"none";if(e===void 0)return this.abandonTurnEnd(),"none";const n=await this.state(),i=n.fault;if(!this.isActiveAutoFault(i)||this.sessionId(t)!==null&&!this.pendingEpisodeMatches(t,i,n))return this.clearTimer(),this.abandonTurnEnd(),"none";const s=Date.now(),a=this.faultRetryDelayMs(i,s);return a!==null&&this.deps.turnEnds?.holding()===!0&&Me(i.since,a,s)?(await this.endRunTurnOnFault(t,i,a),"none"):a!==null?(this.clearAndArmFaultRetry(a,e),this.timer!==null?"armed":"none"):(this.abandonTurnEnd(),i.retry.nextAt!==void 0||this.deps.installedGeneration()!==e||this.deps.currentSession()!==t||t.isStreaming?"none":(await this.settleExhausted(t,i),"exhausted"))}async settleExhausted(e,t){await this.recordFault(O(Z(R(t)))),await this.clearEpisode(e)}async endRunTurnOnFault(e,t,n){this.clearTimer(),this.abandonTurnEnd(),F({level:"info",event:"broker.runtime.diagnostic",fields:{message:`run turn completed on provider fault: ${t.kind} retry in ${n}ms is past the ${oe}ms turn window (since ${t.since}, attempt ${t.retry.attempt??0})`}}),await this.clearEpisode(e),await this.clearFault("pi\u2192provider")}async rearmIfStranded(){if(this.timer!==null||this.deps.installedGeneration()===void 0)return;const e=this.deps.currentSession();if(e.isStreaming)return;const t=await this.state();!this.isActiveAutoFault(t.fault)||!this.pendingEpisodeMatches(e,t.fault,t)||await this.schedule()}maybeSwitchProviderForRetry(e){if(e.type!=="auto_retry_start")return;const t=C("pi\u2192provider",e.errorMessage??"").kind;if(t!=="rate-limit"&&t!=="connection"||this.providerFallbackInFlight!==null||this.deps.cfg.modelExact===!0)return;const n=this.deps.installedGeneration();if(n===void 0)return;const i=this.deps.currentSession(),s=this.deps.currentServices(),a=this.deps.formatModelSpec(i.model,i.thinkingLevel);if(a===null)return;const c=z(this.deps.cfg.model,B(),!1);if(c===void 0)return;const f=te(a),o=(async()=>{const d=await K(c,Y()??this.deps.cfg.cwd,j()),g=le(d,f),y=g===void 0?{route:void 0,capacityExhausted:!1}:await this.nextEligibleFallbackRoute(d.slice(g+1),this.deps.registryOf(s),i.getContextUsage()?.tokens,b=>!this.failedRetryRoutes.has(b.routeId));if(y.route===void 0){y.capacityExhausted&&(this.stageCapacityFailure(n,i),queueMicrotask(()=>{this.deps.installedGeneration()===n&&this.deps.currentSession()===i&&i.abortRetry()}));return}const u=y.route,p=this.deps.registryOf(s).find(u.providerId,u.modelId);if(!p||(await i.setModel(p),this.deps.installedGeneration()!==n||this.deps.currentSession()!==i))return;const v=`${u.providerId}/${u.modelId}`===f.modelSpec?f.thinkingLevel:u.thinkingLevel;i.setThinkingLevel(v??"off"),this.failedRetryRoutes.add(u.routeId),await this.deps.broadcastModelChanged(!1)})().catch(d=>{F({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`provider route fallback failed: ${d instanceof Error?d.message:String(d)}`}})}).finally(()=>{this.deps.installedGeneration()===n&&(this.providerFallbackInFlight=null)});this.providerFallbackInFlight=o}maybeFallbackOnUnusableModel(e){if(e.type!=="message_end"||e.message.role!=="assistant"||e.message.stopReason!=="error")return;const t=me(e.message.errorMessage??"");if(!t&&!he(e.message.errorMessage??"")||this.deps.cfg.modelExact===!0||this.notFoundFallbackInFlight!==null)return;const n=this.deps.installedGeneration();if(n===void 0)return;const i=this.deps.currentSession(),s=this.deps.currentServices(),a=this.deps.formatModelSpec(i.model,i.thinkingLevel);if(a===null)return;const c=te(a);this.notFoundModels.add(c.modelSpec);const f=z(this.deps.cfg.model,B(),!1),o=(async()=>{const d=f?await K(f,Y()??this.deps.cfg.cwd,j()):[],g=le(d,c),y=g===void 0?{route:void 0,capacityExhausted:!1}:await this.nextEligibleFallbackRoute(d.slice(g+1),this.deps.registryOf(s),i.getContextUsage()?.tokens,h=>!this.notFoundModels.has(`${h.providerId}/${h.modelId}`));if(y.route===void 0){y.capacityExhausted&&this.stageCapacityFailure(n,i);return}const u=y.route,p=`${u.providerId}/${u.modelId}${u.thinkingLevel?`:${u.thinkingLevel}`:""}`,v=this.deps.registryOf(s).find(u.providerId,u.modelId);if(v===void 0){F({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`${t?"unconfigured-provider":"not_found"} fallback skipped: ${p} is not registered`}});return}if(await i.setModel(v),this.deps.installedGeneration()!==n||this.deps.currentSession()!==i)return;i.setThinkingLevel(u.thinkingLevel??"off"),await this.deps.broadcastModelChanged();const b=this.deps.formatModelSpec(i.model,i.thinkingLevel)??p;if(F({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`${t?"unconfigured-provider":"not_found"} fallback: ${a} unavailable \u2192 ${b}; re-driving turn`}}),await i.agent.waitForIdle(),this.deps.installedGeneration()!==n||this.deps.currentSession()!==i)return;t&&await this.clearFault("pi\u2192provider");const w=Q("recovery",{},_e(a,b,t?"credential":"not-found"));re(w,{type:"runtime",kind:"recovery"}),await this.deps.turnAdmission.admit(h=>H.fresh(()=>i.prompt(w,{preflightResult:h})))})().catch(d=>{F({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`${t?"unconfigured-provider":"not_found"} fallback failed: ${d instanceof Error?d.message:String(d)}`}})}).finally(()=>{this.deps.installedGeneration()===n&&(this.notFoundFallbackInFlight=null)});this.notFoundFallbackInFlight=o}async nextEligibleFallbackRoute(e,t,n,i){let s=0,a=0;for(const c of e){if(!i(c)||Ee([{...c,...await this.routeAvailability(c,t),automaticFallback:!0}]).candidates.length===0)continue;const f=t.find(c.providerId,c.modelId);if(f!==void 0){if(s++,this.targetCannotFitContext(f.contextWindow,n)){a++;continue}return{route:c,capacityExhausted:!1}}}return{route:void 0,capacityExhausted:s>0&&s===a}}async routeAvailability(e,t){const n=t.find(e.providerId,e.modelId);if(n===void 0)return{registered:!1,authenticated:!1};if(e.credentialSource===Fe&&ie(e.providerId))return{registered:!0,authenticated:(await X().listModelAuth()).keys.some(a=>a.provider===e.providerId)};if(!ie(e.providerId))return{registered:!0,authenticated:t.hasConfiguredAuth(n)};const i=await X().getModelAuthReadiness({model:`${e.providerId}/${e.modelId}`}),s=i.rate_limited_until==null?void 0:Date.parse(i.rate_limited_until);return{registered:!0,authenticated:i.credential==="ready",...s!==void 0&&s>Date.now()?{coolingUntil:s}:{}}}targetCannotFitContext(e,t){return Number.isFinite(e)&&Number.isFinite(t)&&e<t}stageCapacityFailure(e,t){const n=t.getContextUsage()?.tokens;this.stagedCapacityFailure={generation:e,errorMessage:Number.isFinite(n)?`All available fallback models have context windows smaller than the current conversation (${n} tokens).`:"All available fallback models have context windows smaller than the current conversation."}}async recordPendingProviderFault(e,t){const n=this.sessionId(e);if(n===null){await this.recordFault(t);return}await I(this.deps.nodeId,{op:"record-pending",session_id:n,input:t})}pendingEpisodeMatches(e,t,n){const i=this.sessionId(e),s=n.episode;return i!==null&&s!==null&&s.state==="pending"&&s.session_id===i&&s.fault.fault_id===t.fault_id}faultRetryDelayMs(e,t){if(e.retry.nextAt!==void 0){const n=Date.parse(e.retry.nextAt)-t;return Number.isFinite(n)?Math.max(0,n):null}return T(R(e),t)?.delayMs??null}clearAndArmFaultRetry(e,t){if(this.deps.installedGeneration()!==t)return;this.clearTimer();const n=Math.min(Math.max(0,e),Ae),i=Math.max(0,e-n);this.timer=setTimeout(()=>{if(this.timer=null,this.deps.installedGeneration()===t){if(i>0){this.clearAndArmFaultRetry(i,t);return}this.runFaultRetry().catch(s=>{this.abandonTurnEnd(),F({level:"warn",event:"broker.runtime.diagnostic",fields:{message:`fault retry fire failed: ${s instanceof Error?s.message:String(s)}`}})})}},n),typeof this.timer.unref=="function"&&this.timer.unref()}async runFaultRetry(){await this.attemptFaultRetry()===void 0&&this.abandonTurnEnd()}async attemptFaultRetry(){const e=this.deps.installedGeneration();if(e===void 0)return;const t=e.session;if(t.isStreaming)return;const n=(await this.state()).fault;if(!this.isActiveAutoFault(n))return;let i=n;if(n.kind==="connection"&&this.deps.turnEnds===void 0){const u=await this.deps.retryProbe();if(this.deps.installedGeneration()!==e||this.deps.currentSession()!==t||t.isStreaming)return;const p=(await this.state()).fault;if(!this.isActiveAutoFault(p)||p.since!==n.since)return;if(!u)return this.clearAndArmFaultRetry(ee(p.kind).baseDelayMs,e),"rearmed";i=p}const s=this.deps.turnEnds!==void 0,a=i.retry.attempt??0,c=ee(i.kind),f=a>=c.max?null:T(R(i),Date.now());if(f===null){await this.settleExhausted(t,i);return}if(this.deps.installedGeneration()!==e||this.deps.currentSession()!==t)return;let o,d;const g=await this.deps.turnAdmission.admit(async u=>{const p=(await this.state()).fault;if(this.deps.installedGeneration()!==e||this.deps.currentSession()!==t||t.isStreaming||!this.isActiveAutoFault(p)||p.since!==i.since){u();return}const v=this.sessionId(t);if(v===null){u();return}if(!(await I(this.deps.nodeId,{op:"admit",session_id:v,fault_id:p.fault_id,retry:f.fault.retry})).applied){u();return}const w=i.anchor_entry_id;if(w!==void 0&&(t.sessionManager.getLeafId?.()??null)!==w&&!this.hasProgressPastAnchor(t,w))try{const l=await t.navigateTree(w);if(this.deps.installedGeneration()!==e||this.deps.currentSession()!==t){u();return}l.cancelled||this.deps.reWelcomeAll()}catch(l){F({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`fault retry rewind skipped: ${l instanceof Error?l.message:String(l)}`}})}const h=Q("recovery",s?{attempt:f.attempt}:{attempt:f.attempt,max:f.max},Te(i.kind,s));re(h,{type:"runtime",kind:"recovery"}),this.deps.turnEnds?.beginRecovery();const P=this.agentStarts;try{await H.fresh(()=>t.prompt(h,{preflightResult:u}))}catch(l){o={error:l,faultId:p.fault_id,startsBefore:P},de(l)||(d={code:"model_error",message:`recovery prompt rejected: ${ae(l)}`});return}finally{this.deps.turnEnds?.recoveryReturned(d)}return"prompted"});if(o===void 0)return g;const y=await this.settleRejectedRecoveryPrompt(e,t,o);if(y==="stale")throw o.error;return y==="rearmed"?"rearmed":void 0}async settleRejectedRecoveryPrompt(e,t,n){const i=this.sessionId(t);if(i===null)return"stale";const s=m(()=>{if(this.deps.installedGeneration()!==e||this.deps.currentSession()!==t||t.isStreaming||this.agentStarts!==n.startsBefore)throw new _},"assertCurrent"),a=ae(n.error),c=de(n.error);try{let f;return await this.retryWhileDaemonUnreachable("rejected recovery prompt settlement",async()=>{s();const{episode:o}=await this.state();if(s(),o===null||o.state!=="admitted"||o.session_id!==i||o.fault.fault_id!==n.faultId)throw new _;const d=R(o.fault),g=c&&this.deps.turnEnds===void 0?T(d,Date.now()):null,y=g===null?Z(c?d:{...d,kind:"other",message:`recovery prompt rejected: ${a}`}):{...d,retry:{...d.retry,nextAt:g.nextAt}};if(s(),!(await I(this.deps.nodeId,{op:"settle-rejected",session_id:i,fault_id:n.faultId,reopen:g!==null,input:O(y)})).applied)throw new _;f=g?.nextAt},s),f===void 0?(F({level:"warn",event:"broker.runtime.diagnostic",fields:{message:`recovery prompt rejected, ending the retry episode: ${a}`}}),"ended"):(F({level:"warn",event:"broker.runtime.diagnostic",fields:{message:`recovery prompt rejected before any turn started, retrying at ${f}: ${a}`}}),await this.schedule(),"rearmed")}catch(f){if(!(f instanceof _))throw f;return"stale"}}}export{it as FaultRetry,oe as RUN_TURN_RETRY_WINDOW_MS,Pe as isPrefillRejectionDuringEpisode,Te as retryCardBody,Me as runTurnRetryExpired,ue as settledProviderFault,nt as willDaemonRetry};
|
|
@@ -59,6 +59,8 @@ export declare function createFrameDispatchContext(deps: FrameDispatchDeps): {
|
|
|
59
59
|
notifyTurnAccepted: () => void;
|
|
60
60
|
pendingPromptDispatches: () => number;
|
|
61
61
|
resetForSession: () => void;
|
|
62
|
+
/** A new cycle's memory names: the response's, or a fresh read when the cycle-start request gave none. */
|
|
63
|
+
refreshMemoryNames: (names: import("./frame-memory-refs.js").ComposerNames | undefined) => Promise<void>;
|
|
62
64
|
};
|
|
63
65
|
/** The socket listener calls this explicit dispatcher for every decoded client frame. */
|
|
64
66
|
export declare function handleFrame(ctx: FrameDispatchContext, client: BrokerClient, frame: ClientToBroker): void;
|