@north-light/cli 0.3.716 → 0.3.718

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.
Files changed (42) hide show
  1. package/dist/api/node-transport.js +1 -1
  2. package/dist/builtin-memory/internal/nodes-and-canvas.md +2 -2
  3. package/dist/clients/attach/viewer.js +251 -251
  4. package/dist/core/conversation-store/client-worker.js +1 -1
  5. package/dist/core/grants/mirror.d.ts +3 -1
  6. package/dist/core/grants/mirror.js +3 -3
  7. package/dist/core/llm/breaker.d.ts +9 -0
  8. package/dist/core/llm/breaker.js +1 -0
  9. package/dist/core/runtime/bearings.d.ts +4 -1
  10. package/dist/core/runtime/bearings.js +7 -7
  11. package/dist/core/runtime/broker/cli-relay.js +1 -1
  12. package/dist/core/runtime/broker/fault-retry.d.ts +4 -1
  13. package/dist/core/runtime/broker/fault-retry.js +1 -1
  14. package/dist/core/runtime/broker/model-adapter.d.ts +9 -0
  15. package/dist/core/runtime/broker/model-adapter.js +3 -3
  16. package/dist/core/runtime/broker.js +1 -1
  17. package/dist/core/runtime/connectivity.d.ts +1 -2
  18. package/dist/core/runtime/deliver-live.js +1 -1
  19. package/dist/core/runtime/fault-recovery.d.ts +0 -3
  20. package/dist/core/runtime/fault-recovery.js +1 -1
  21. package/dist/core/substrate/delivery/deliver.d.ts +5 -0
  22. package/dist/core/substrate/delivery/deliver.js +3 -3
  23. package/dist/daemon/api/handlers/broker-ops.js +1 -1
  24. package/dist/daemon/api/handlers/delivery.js +1 -1
  25. package/dist/daemon/api/handlers/health.js +3 -3
  26. package/dist/daemon/api/handlers/llm.js +3 -3
  27. package/dist/daemon/reconcilers/fault-retry-backstop.d.ts +2 -4
  28. package/dist/daemon/reconcilers/fault-retry-backstop.js +1 -1
  29. package/package.json +3 -3
  30. package/packages/crouter-api/dist/api/node-transport.js +5 -1
  31. package/packages/crouter-api/dist/clients/attach/viewer.js +10 -0
  32. package/packages/crouter-api/dist/core/grants/mirror.js +11 -6
  33. package/packages/crouter-api/dist/core/runtime/bearings.js +10 -4
  34. package/packages/crouter-api/dist/core/runtime/broker/model-adapter.js +12 -3
  35. package/packages/crouter-api/dist/core/runtime/deliver-live.js +3 -2
  36. package/packages/crouter-api/dist/core/runtime/fault-recovery.js +11 -22
  37. package/packages/crouter-api/dist/core/substrate/delivery/deliver.js +12 -2
  38. package/packages/crouter-api/dist/daemon/api/handlers/broker-ops.js +13 -12
  39. package/packages/crouter-api/package.json +1 -1
  40. package/packages/crouter-identity/package.json +1 -1
  41. package/packages/crouter-plugin/package.json +3 -3
  42. package/runtime.lock.json +14 -14
@@ -1 +1 @@
1
- var E=Object.defineProperty;var s=(e,t)=>E(e,"name",{value:t,configurable:!0});import{parentPort as M,workerData as N}from"node:worker_threads";import{request as v}from"node:http";import{request as $}from"node:https";const{address:l,token:b}=N,r=[],m=new Set;let w=!1,d=0,c=500,y;const I=Number(process.env.CRTR_CONVERSATION_COMMIT_DEADLINE_MS??15*6e4),k=process.env.CRTR_NODE_DEADLINE_AT?Date.parse(process.env.CRTR_NODE_DEADLINE_AT):1/0,O=s(()=>Math.max(1e3,Math.min(6e4,k-Date.now())),"requestTimeoutMs");function P(e){return new Promise(t=>setTimeout(t,e))}s(P,"wait");function _(e){return new Promise(t=>{const i=`/v1${e.path}`,n=l.startsWith("http")?new URL(l.replace(/\/$/,"")+i):null,u=e.data===void 0?void 0:JSON.stringify(e.data);let g=!1;const f=s(o=>{g||(g=!0,t(o))},"finish"),T=s(o=>{const D=[];o.on("data",h=>D.push(h)),o.on("aborted",()=>f({error:"conversation store response ended before completion"})),o.on("error",h=>f({error:h.message})),o.on("end",()=>f({status:o.statusCode,body:Buffer.concat(D).toString("utf8"),path:o.headers["x-conversation-path"],tail:o.headers["x-conversation-tail"]}))},"onResponse"),a=n?(n.protocol==="https:"?$:v)(n,{method:e.method},T):v({socketPath:l,path:i,method:e.method},T);a.on("error",o=>f({error:o.message})),a.setTimeout(O(),()=>{f({error:"conversation store request timed out"}),a.destroy()}),e.reply?.on("message",o=>{o==="cancel"&&a.destroy()}),b&&a.setHeader("authorization",`Bearer ${b}`),u!==void 0?(a.setHeader("content-type","application/json"),a.end(u)):a.end()})}s(_,"send");function p(e,t){e.reply?.postMessage(t),e.signal&&(Atomics.store(new Int32Array(e.signal),0,1),Atomics.notify(new Int32Array(e.signal),0)),e.reply?.close()}s(p,"answer");function q(e){y=e;for(const t of r.splice(0))t.kind!=="append"&&p(t,{error:`conversation_write_failed: ${e}`});d=0,c=500}s(q,"giveUp");const A=s(e=>!!e.error||!e.status||e.status>=400,"failed");async function R(e){if(d||(d=Date.now()),Date.now()-d>=I||Date.now()>=k){q(e);return}await P(c),c=Math.min(c*2,3e4)}s(R,"backoff");async function S(){if(!w){w=!0;try{for(;r.length;){const e=r[0];if(e.kind==="append"){const t=[];for(;r[t.length]?.kind==="append"&&r[t.length]?.path===e.path;)t.push(r[t.length]);const i=t.flatMap(u=>u.data.entries),n=await _({method:"POST",path:e.path,data:{entries:i}});if(A(n)){await R(n.error??n.body??`HTTP ${n.status}`);continue}d=0,c=500,m.add(e.path.replace(/\/entries$/,"")),r.splice(0,t.length);continue}if(e.kind==="flush"){if(y){p(e,{error:`conversation_write_failed: ${y}`}),r.shift();continue}let t;for(const i of m){const n=await _({method:"POST",path:`${i}/commit`});if(A(n)){t=n.error??n.body??`HTTP ${n.status}`;break}m.delete(i)}if(t){await R(t);continue}d=0,c=500,p(e,{status:200}),r.shift();continue}p(e,await _(e)),r.shift()}}finally{w=!1}}}s(S,"drain"),M?.on("message",e=>{r.push(e),S()});
1
+ var E=Object.defineProperty;var s=(e,t)=>E(e,"name",{value:t,configurable:!0});import{parentPort as M,workerData as N}from"node:worker_threads";import{request as v}from"node:http";import{request as $}from"node:https";const{address:l,token:b}=N,r=[],m=new Set;let w=!1,d=0,c=500,y;const I=Number(process.env.CRTR_CONVERSATION_COMMIT_DEADLINE_MS??15*6e4),k=process.env.CRTR_NODE_DEADLINE_AT?Date.parse(process.env.CRTR_NODE_DEADLINE_AT):1/0,O=s(()=>Math.max(1e3,Math.min(6e4,k-Date.now())),"requestTimeoutMs");function P(e){return new Promise(t=>setTimeout(t,e))}s(P,"wait");function g(e){return new Promise(t=>{const i=`/v1${e.path}`,n=l.startsWith("http")?new URL(l.replace(/\/$/,"")+i):null,u=e.data===void 0?void 0:JSON.stringify(e.data);let _=!1;const f=s(o=>{_||(_=!0,t(o))},"finish"),T=s(o=>{const D=[];o.on("data",h=>D.push(h)),o.on("aborted",()=>f({error:"conversation store response ended before completion"})),o.on("error",h=>f({error:h.message})),o.on("end",()=>f({status:o.statusCode,body:Buffer.concat(D).toString("utf8"),path:o.headers["x-conversation-path"],tail:o.headers["x-conversation-tail"]}))},"onResponse"),a=n?(n.protocol==="https:"?$:v)(n,{method:e.method},T):v({socketPath:l,path:i,method:e.method,agent:!1},T);a.on("error",o=>f({error:o.message})),a.setTimeout(O(),()=>{f({error:"conversation store request timed out"}),a.destroy()}),e.reply?.on("message",o=>{o==="cancel"&&a.destroy()}),b&&a.setHeader("authorization",`Bearer ${b}`),u!==void 0?(a.setHeader("content-type","application/json"),a.end(u)):a.end()})}s(g,"send");function p(e,t){e.reply?.postMessage(t),e.signal&&(Atomics.store(new Int32Array(e.signal),0,1),Atomics.notify(new Int32Array(e.signal),0)),e.reply?.close()}s(p,"answer");function q(e){y=e;for(const t of r.splice(0))t.kind!=="append"&&p(t,{error:`conversation_write_failed: ${e}`});d=0,c=500}s(q,"giveUp");const A=s(e=>!!e.error||!e.status||e.status>=400,"failed");async function R(e){if(d||(d=Date.now()),Date.now()-d>=I||Date.now()>=k){q(e);return}await P(c),c=Math.min(c*2,3e4)}s(R,"backoff");async function S(){if(!w){w=!0;try{for(;r.length;){const e=r[0];if(e.kind==="append"){const t=[];for(;r[t.length]?.kind==="append"&&r[t.length]?.path===e.path;)t.push(r[t.length]);const i=t.flatMap(u=>u.data.entries),n=await g({method:"POST",path:e.path,data:{entries:i}});if(A(n)){await R(n.error??n.body??`HTTP ${n.status}`);continue}d=0,c=500,m.add(e.path.replace(/\/entries$/,"")),r.splice(0,t.length);continue}if(e.kind==="flush"){if(y){p(e,{error:`conversation_write_failed: ${y}`}),r.shift();continue}let t;for(const i of m){const n=await g({method:"POST",path:`${i}/commit`});if(A(n)){t=n.error??n.body??`HTTP ${n.status}`;break}m.delete(i)}if(t){await R(t);continue}d=0,c=500,p(e,{status:200}),r.shift();continue}p(e,await g(e)),r.shift()}}finally{w=!1}}}s(S,"drain"),M?.on("message",e=>{r.push(e),S()});
@@ -180,7 +180,9 @@ export interface TeamRecord {
180
180
  team: string;
181
181
  members: string[];
182
182
  }
183
- /** The `teams` a grant sync answer carried; absent (an unjoined install, an older directory) reads as none. */
183
+ /** The `teams` a grant sync answer carried; absent (an unjoined install, an older directory) reads as none. Team
184
+ * membership is advisory next to the grants the same answer carries, so an entry that is not a directory team
185
+ * (`team:<id>`, e.g. a canvas group row echoed back) is dropped rather than failing the sync. */
184
186
  export declare function teamsOf(value: unknown): TeamRecord[];
185
187
  /** Replace the mirror with `grants` and the `written_by = 'directory'` team `member` facts with `teams`, in one transaction. The
186
188
  * ledger's `grant:<id>` limit rows follow from the `grants` trigger `crtr_grant_limit` (schema delta 002). */
@@ -1,11 +1,11 @@
1
- var h=Object.defineProperty;var t=(e,r)=>h(e,"name",{value:r,configurable:!0});import{createHash as D}from"node:crypto";import{parseScope as L}from"@north-light/identity";import{openDb as p,withCanvasWrite as T}from"../canvas/db.js";import{isUnsandboxedMachine as N}from"../runtime/unsandboxed.js";import{replaceWrittenBy as I,userSubject as C}from"../permissions/facts.js";import{GROUP_TYPE as M}from"../permissions/builtin.js";const $=["not_started","pending","ready","failed","unavailable"],F=["ultra","strong","medium","light"];function v(){const e=process.env.CRTR_RUNTIME;return e?{sql:" AND runtime = ?",args:[e]}:{sql:"",args:[]}}t(v,"runtimeScope");async function i(e,r,n=[]){const s=v();return await(await p()).prepare(`SELECT ${e} FROM grants WHERE (${r})${s.sql}`).all(...n,...s.args)}t(i,"grantRows");async function u(e,r,n=[]){return(await i(e,r,n))[0]}t(u,"grantRow");function k(e){return!/\u0000|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/.test(e)}t(k,"jsonbSafe");function l(e){if(!Array.isArray(e))throw new TypeError("grant scopes must be a list");return e.map(r=>{if(!r||typeof r!="object"||typeof r.scope!="string"||!k(r.scope)||!["always","ask"].includes(r.mode))throw new TypeError("invalid grant scope entry");return{scope:r.scope,mode:r.mode}})}t(l,"entries");function U(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{state:r,message:n,next:s,step:a}=e;return typeof r!="string"||!$.includes(r)||n!==void 0&&typeof n!="string"||a!==void 0&&typeof a!="string"||typeof s!="string"||!s?null:{state:r,...n===void 0?{}:{message:n},next:s,...a===void 0?{}:{step:a}}}t(U,"dependencyOf");function O(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const r={};for(const[n,s]of Object.entries(e)){const a=U(s);a&&(r[n]=a)}return r}t(O,"dependenciesOf");function G(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{base_url:r,rungs:n}=e;if(typeof r!="string"||!r||!n||typeof n!="object"||Array.isArray(n))return null;const s={};for(const a of F){const o=n[a];typeof o=="string"&&o&&(s[a]=o)}return Object.keys(s).length?{base_url:r.replace(/\/+$/,""),rungs:s}:null}t(G,"inferenceEndpointOf");function A(e,r,n,s){return r===e&&n&&s}t(A,"computedFor");function f(e){if(!A(e.rev,e.computed_rev,e.scopes_json!==null,e.resolved_scopes_json!==null))throw new TypeError("grant columns are not computed for this revision");return{id:e.id,runtime:e.runtime,sub:e.sub,grantee:e.grantee,rev:e.rev,scopes:l(JSON.parse(e.scopes_json)),resolved_scopes:l(JSON.parse(e.resolved_scopes_json)),spend_cap:e.spend_cap,expires_at:e.expires_at,status:e.status,revoked_at:e.revoked_at,approved_at:e.approved_at,payer:e.payer,dependencies:O(JSON.parse(e.dependencies_json??"{}")),run_notice_url:e.run_notice_url??null,inference_endpoint:e.inference_endpoint_json?G(JSON.parse(e.inference_endpoint_json)):null,synced_at:e.synced_at??""}}t(f,"record");function d(e){if(!e||e.status!=="active")return null;try{return q(f(e))}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}t(d,"active");function _(e){return e.grantee!=="app:terminal"&&N()}t(_,"mirrorOnly");async function ne(){return(await J()).filter(e=>!_(e))}t(ne,"localGrants");async function te(e,r){return!_({grantee:e})&&await u("1","grantee = ? AND sub <> ? AND status <> 'removed'",[e,r])!==void 0}t(te,"otherLiveGrantOfApp");const y="[A-Za-z0-9_-]{1,64}",H=new RegExp(`^(${y}):(${y})$`);function W(e){const r=new Set;for(const n of e)if(n.status==="active")for(const{scope:s}of n.resolved_scopes){const a=H.exec(s);a&&a[1]!=="crtr"&&r.add(a[1])}return[...r].sort()}t(W,"providerIdsFromGrants");async function se(){const e=v();return(await(await p()).prepare(`SELECT DISTINCT m[1] AS id FROM (
1
+ var R=Object.defineProperty;var t=(e,r)=>R(e,"name",{value:r,configurable:!0});import{createHash as D}from"node:crypto";import{parseScope as L}from"@north-light/identity";import{openDb as p,withCanvasWrite as T}from"../canvas/db.js";import{isUnsandboxedMachine as N}from"../runtime/unsandboxed.js";import{replaceWrittenBy as I,userSubject as C}from"../permissions/facts.js";import{GROUP_TYPE as M}from"../permissions/builtin.js";const $=["not_started","pending","ready","failed","unavailable"],F=["ultra","strong","medium","light"];function v(){const e=process.env.CRTR_RUNTIME;return e?{sql:" AND runtime = ?",args:[e]}:{sql:"",args:[]}}t(v,"runtimeScope");async function i(e,r,n=[]){const s=v();return await(await p()).prepare(`SELECT ${e} FROM grants WHERE (${r})${s.sql}`).all(...n,...s.args)}t(i,"grantRows");async function u(e,r,n=[]){return(await i(e,r,n))[0]}t(u,"grantRow");function k(e){return!/\u0000|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/.test(e)}t(k,"jsonbSafe");function l(e){if(!Array.isArray(e))throw new TypeError("grant scopes must be a list");return e.map(r=>{if(!r||typeof r!="object"||typeof r.scope!="string"||!k(r.scope)||!["always","ask"].includes(r.mode))throw new TypeError("invalid grant scope entry");return{scope:r.scope,mode:r.mode}})}t(l,"entries");function U(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{state:r,message:n,next:s,step:o}=e;return typeof r!="string"||!$.includes(r)||n!==void 0&&typeof n!="string"||o!==void 0&&typeof o!="string"||typeof s!="string"||!s?null:{state:r,...n===void 0?{}:{message:n},next:s,...o===void 0?{}:{step:o}}}t(U,"dependencyOf");function O(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const r={};for(const[n,s]of Object.entries(e)){const o=U(s);o&&(r[n]=o)}return r}t(O,"dependenciesOf");function G(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{base_url:r,rungs:n}=e;if(typeof r!="string"||!r||!n||typeof n!="object"||Array.isArray(n))return null;const s={};for(const o of F){const a=n[o];typeof a=="string"&&a&&(s[o]=a)}return Object.keys(s).length?{base_url:r.replace(/\/+$/,""),rungs:s}:null}t(G,"inferenceEndpointOf");function A(e,r,n,s){return r===e&&n&&s}t(A,"computedFor");function f(e){if(!A(e.rev,e.computed_rev,e.scopes_json!==null,e.resolved_scopes_json!==null))throw new TypeError("grant columns are not computed for this revision");return{id:e.id,runtime:e.runtime,sub:e.sub,grantee:e.grantee,rev:e.rev,scopes:l(JSON.parse(e.scopes_json)),resolved_scopes:l(JSON.parse(e.resolved_scopes_json)),spend_cap:e.spend_cap,expires_at:e.expires_at,status:e.status,revoked_at:e.revoked_at,approved_at:e.approved_at,payer:e.payer,dependencies:O(JSON.parse(e.dependencies_json??"{}")),run_notice_url:e.run_notice_url??null,inference_endpoint:e.inference_endpoint_json?G(JSON.parse(e.inference_endpoint_json)):null,synced_at:e.synced_at??""}}t(f,"record");function d(e){if(!e||e.status!=="active")return null;try{return q(f(e))}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}t(d,"active");function _(e){return e.grantee!=="app:terminal"&&N()}t(_,"mirrorOnly");async function ne(){return(await J()).filter(e=>!_(e))}t(ne,"localGrants");async function te(e,r){return!_({grantee:e})&&await u("1","grantee = ? AND sub <> ? AND status <> 'removed'",[e,r])!==void 0}t(te,"otherLiveGrantOfApp");const y="[A-Za-z0-9_-]{1,64}",H=new RegExp(`^(${y}):(${y})$`);function W(e){const r=new Set;for(const n of e)if(n.status==="active")for(const{scope:s}of n.resolved_scopes){const o=H.exec(s);o&&o[1]!=="crtr"&&r.add(o[1])}return[...r].sort()}t(W,"providerIdsFromGrants");async function se(){const e=v();return(await(await p()).prepare(`SELECT DISTINCT m[1] AS id FROM (
2
2
  SELECT DISTINCT e->>'scope' AS scope FROM (
3
3
  SELECT t::jsonb AS j FROM (SELECT DISTINCT resolved_scopes_json AS t FROM grants WHERE ${m}${x()}${e.sql}) d OFFSET 0) p
4
4
  CROSS JOIN LATERAL jsonb_array_elements(CASE WHEN jsonb_typeof(p.j) = 'array' THEN p.j ELSE '[]' END) e) s
5
5
  CROSS JOIN LATERAL regexp_match(s.scope, '^(${y}):${y}$') m
6
6
  WHERE m[1] <> 'crtr'`).all(...e.args)).map(n=>n.id).sort()}t(se,"activeProviderIds");async function ae(){const e=v();return await(await p()).prepare(`SELECT 1 FROM grants WHERE ${m}${x()}${e.sql} LIMIT 1`).get(...e.args)!==void 0}t(ae,"anyActiveGrant");async function oe(e,r){return await u("1",`sub = ? AND ${m}${x()} AND EXISTS (
7
7
  SELECT 1 FROM jsonb_array_elements(CASE WHEN jsonb_typeof(resolved_scopes_json::jsonb) = 'array' THEN resolved_scopes_json::jsonb ELSE '[]' END) e
8
- WHERE starts_with(e->>'scope', ?))`,[e,`${r}:`])!==void 0}t(oe,"activeGrantNamesApp");const m="status = 'active' AND computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL",P="computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL";function x(){return N()?" AND grantee = 'app:terminal'":""}t(x,"localOnly");async function ce(){return(await i("DISTINCT sub",P)).map(e=>e.sub)}t(ce,"grantSubs");async function ie(e){return j(e===void 0?await i("*","status = 'active'"):await i("*","sub = ? AND status = 'active'",[e]))}t(ie,"activeGrants");async function ue(e){const r=await i("*","sub = ? AND status = 'active'",[e]);return new Set(W(r.flatMap(n=>{try{return[f(n)]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})))}t(ue,"grantedProviderIds");function pe(e,r){return e.source_marketplace===null&&e.source_path===null&&r.has(e.name)}t(pe,"isProviderBundleRow");async function de(e){return(await i("*","sub = ? AND status = 'active'",[e])).flatMap(n=>{const s=d(n);return s===null?[]:[s]})}t(de,"activeGrantsOfPerson");async function J(){return j(await i("*","true"))}t(J,"allGrants");async function le(e){return(await i("sub, status, rev, computed_rev, resolved_scopes_json, scopes_json IS NOT NULL AS has_scopes","sub = ?",[e])).flatMap(n=>{if(!A(n.rev,n.computed_rev,n.has_scopes,n.resolved_scopes_json!==null))return[];try{return[{sub:n.sub,status:n.status,resolved_scopes:l(JSON.parse(n.resolved_scopes_json))}]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})}t(le,"grantsOfPerson");function j(e){return e.flatMap(r=>{try{return[f(r)]}catch(n){if(n instanceof TypeError||n instanceof SyntaxError)return[];throw n}})}t(j,"records");function V(e){return e.expires_at!==null&&!(Date.parse(e.expires_at)>Date.now())}t(V,"grantExpired");function q(e){if(e.status!=="active"||V(e))return null;try{const r=e.resolved_scopes.map(({scope:n})=>L(n));return{...e,resolved:e.resolved_scopes.flatMap(({mode:n},s)=>n==="always"?[r[s]]:[])}}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}t(q,"activeRecord");function S(e){return Array.isArray(e)?`[${e.map(S).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().filter(r=>e[r]!==void 0).map(r=>`${JSON.stringify(r)}:${S(e[r])}`).join(",")}}`:JSON.stringify(e)??"null"}t(S,"canonicalJson");function fe(e){const r={rev:e.rev,resolved_scopes:e.resolved_scopes,spend_cap:e.spend_cap,payer:e.payer,dependencies:e.dependencies??{},...e.inference_endpoint?{inference_endpoint:e.inference_endpoint}:{}};return D("sha256").update(S(r)).digest("base64url").slice(0,22)}t(fe,"grantVersion");async function _e(e){return!!await u("1","id = ?",[e])}t(_e,"hasGrant");async function ye(e){return await u("rev, status","id = ?",[e])??null}t(ye,"grantSyncState");async function Ee(e,r){return await u("rev, status","grantee = ? AND sub = ?",[e,r])??null}t(Ee,"grantSyncStateFor");async function B(e){const r=await u("*","id = ?",[e]);if(!r)return null;try{return f(r)}catch(n){if(n instanceof TypeError||n instanceof SyntaxError)return null;throw n}}t(B,"grantRecord");async function ge(e){const r=await u("*","id = ?",[e]);if(!r)return{standing:"inactive",rev:null,sub:null,grantee:null,status:null,removal_done_at:null,record:null};const n={rev:r.rev,sub:r.sub,grantee:r.grantee,status:r.status,removal_done_at:r.removal_done_at??null};if(r.status!=="active")return{...n,standing:"inactive",record:null};if(r.computed_rev!==r.rev)return{...n,standing:"lagging",record:null};const s=d(r);return s===null?{...n,standing:"inactive",record:null}:{...n,standing:"active",record:s}}t(ge,"grantStanding");async function ve(e){return(await i("id",e)).map(r=>r.id)}t(ve,"grantIdsWhere");async function me(e){return(e?(await B(e))?.payer:null)??"user"}t(me,"payerOfGrant");async function X(e){return d(await u("*","id = ?",[e]))}t(X,"activeGrant");async function xe(e,r){return d(await u("*","grantee = ? AND sub = ?",[e,r]))}t(xe,"grantFor");async function Se(e){if(_({grantee:e}))return null;const r=await i("*","grantee = ? AND status = 'active'",[e]);if(r.length>1)throw new Error(`multiple active grants for ${e}`);return d(r[0])}t(Se,"activeGrantForApp");async function Te(e){const r=await X(e);return r&&r.run_notice_url&&!_(r)?{url:r.run_notice_url,sub:r.sub,grantee:r.grantee}:null}t(Te,"runNoticeTarget");async function Ne(e){const r=await i("*","grantee = 'app:terminal' AND sub = ? AND status = 'active'",[e]);if(r.length>1)throw new Error(`multiple active terminal grants for ${e}`);return d(r[0])}t(Ne,"terminalGrant");async function Oe(){return(await(await p()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value??null}t(Oe,"grantsSource");async function Ae(e){return(await(await p()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value===e}t(Ae,"hasSyncedGrants");async function je(e){return(await e.prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value!=="local"?0:(await e.prepare("DELETE FROM runtime_state WHERE key = 'grants_source'").run(),Number((await e.prepare("DELETE FROM grants").run()).changes))}t(je,"dropLocalGrantMirror");async function we(){return await T(async e=>Number((await e.prepare("UPDATE grants SET computed_rev = rev WHERE computed_rev IS NULL AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL").run()).changes))}t(we,"backfillComputedRev");function be(e){if(e===void 0)return[];if(!Array.isArray(e))throw new TypeError("invalid grant sync response");return e.map(r=>{const{team:n,members:s}=r??{};if(typeof n!="string"||!/^team:\S+$/.test(n)||!Array.isArray(s)||s.some(a=>typeof a!="string"||!/^user:[^\s*]+$/.test(a)))throw new TypeError("invalid grant sync response");return{team:n,members:s}})}t(be,"teamsOf");async function Re(e,r,n,s=[]){const a=new Set;for(const o of e){if(a.has(o.id)||!o.id||!o.runtime||!o.sub||!o.grantee||!Number.isInteger(o.rev)||!["active","revoked","removed"].includes(o.status))throw new TypeError("invalid grant sync response");a.add(o.id),l(o.scopes),l(o.resolved_scopes)}await T(async o=>{let E=0;const g=[...a];E+=Number((await(g.length?o.prepareUncached(`DELETE FROM grants WHERE id NOT IN (${g.map(()=>"?").join(",")})`).run(...g):o.prepareUncached("DELETE FROM grants").run())).changes);const w=o.prepare(`INSERT INTO grants
8
+ WHERE starts_with(e->>'scope', ?))`,[e,`${r}:`])!==void 0}t(oe,"activeGrantNamesApp");const m="status = 'active' AND computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL",P="computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL";function x(){return N()?" AND grantee = 'app:terminal'":""}t(x,"localOnly");async function ce(){return(await i("DISTINCT sub",P)).map(e=>e.sub)}t(ce,"grantSubs");async function ie(e){return j(e===void 0?await i("*","status = 'active'"):await i("*","sub = ? AND status = 'active'",[e]))}t(ie,"activeGrants");async function ue(e){const r=await i("*","sub = ? AND status = 'active'",[e]);return new Set(W(r.flatMap(n=>{try{return[f(n)]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})))}t(ue,"grantedProviderIds");function pe(e,r){return e.source_marketplace===null&&e.source_path===null&&r.has(e.name)}t(pe,"isProviderBundleRow");async function de(e){return(await i("*","sub = ? AND status = 'active'",[e])).flatMap(n=>{const s=d(n);return s===null?[]:[s]})}t(de,"activeGrantsOfPerson");async function J(){return j(await i("*","true"))}t(J,"allGrants");async function le(e){return(await i("sub, status, rev, computed_rev, resolved_scopes_json, scopes_json IS NOT NULL AS has_scopes","sub = ?",[e])).flatMap(n=>{if(!A(n.rev,n.computed_rev,n.has_scopes,n.resolved_scopes_json!==null))return[];try{return[{sub:n.sub,status:n.status,resolved_scopes:l(JSON.parse(n.resolved_scopes_json))}]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})}t(le,"grantsOfPerson");function j(e){return e.flatMap(r=>{try{return[f(r)]}catch(n){if(n instanceof TypeError||n instanceof SyntaxError)return[];throw n}})}t(j,"records");function V(e){return e.expires_at!==null&&!(Date.parse(e.expires_at)>Date.now())}t(V,"grantExpired");function q(e){if(e.status!=="active"||V(e))return null;try{const r=e.resolved_scopes.map(({scope:n})=>L(n));return{...e,resolved:e.resolved_scopes.flatMap(({mode:n},s)=>n==="always"?[r[s]]:[])}}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}t(q,"activeRecord");function S(e){return Array.isArray(e)?`[${e.map(S).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().filter(r=>e[r]!==void 0).map(r=>`${JSON.stringify(r)}:${S(e[r])}`).join(",")}}`:JSON.stringify(e)??"null"}t(S,"canonicalJson");function fe(e){const r={rev:e.rev,resolved_scopes:e.resolved_scopes,spend_cap:e.spend_cap,payer:e.payer,dependencies:e.dependencies??{},...e.inference_endpoint?{inference_endpoint:e.inference_endpoint}:{}};return D("sha256").update(S(r)).digest("base64url").slice(0,22)}t(fe,"grantVersion");async function _e(e){return!!await u("1","id = ?",[e])}t(_e,"hasGrant");async function ye(e){return await u("rev, status","id = ?",[e])??null}t(ye,"grantSyncState");async function Ee(e,r){return await u("rev, status","grantee = ? AND sub = ?",[e,r])??null}t(Ee,"grantSyncStateFor");async function B(e){const r=await u("*","id = ?",[e]);if(!r)return null;try{return f(r)}catch(n){if(n instanceof TypeError||n instanceof SyntaxError)return null;throw n}}t(B,"grantRecord");async function ge(e){const r=await u("*","id = ?",[e]);if(!r)return{standing:"inactive",rev:null,sub:null,grantee:null,status:null,removal_done_at:null,record:null};const n={rev:r.rev,sub:r.sub,grantee:r.grantee,status:r.status,removal_done_at:r.removal_done_at??null};if(r.status!=="active")return{...n,standing:"inactive",record:null};if(r.computed_rev!==r.rev)return{...n,standing:"lagging",record:null};const s=d(r);return s===null?{...n,standing:"inactive",record:null}:{...n,standing:"active",record:s}}t(ge,"grantStanding");async function ve(e){return(await i("id",e)).map(r=>r.id)}t(ve,"grantIdsWhere");async function me(e){return(e?(await B(e))?.payer:null)??"user"}t(me,"payerOfGrant");async function X(e){return d(await u("*","id = ?",[e]))}t(X,"activeGrant");async function xe(e,r){return d(await u("*","grantee = ? AND sub = ?",[e,r]))}t(xe,"grantFor");async function Se(e){if(_({grantee:e}))return null;const r=await i("*","grantee = ? AND status = 'active'",[e]);if(r.length>1)throw new Error(`multiple active grants for ${e}`);return d(r[0])}t(Se,"activeGrantForApp");async function Te(e){const r=await X(e);return r&&r.run_notice_url&&!_(r)?{url:r.run_notice_url,sub:r.sub,grantee:r.grantee}:null}t(Te,"runNoticeTarget");async function Ne(e){const r=await i("*","grantee = 'app:terminal' AND sub = ? AND status = 'active'",[e]);if(r.length>1)throw new Error(`multiple active terminal grants for ${e}`);return d(r[0])}t(Ne,"terminalGrant");async function Oe(){return(await(await p()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value??null}t(Oe,"grantsSource");async function Ae(e){return(await(await p()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value===e}t(Ae,"hasSyncedGrants");async function je(e){return(await e.prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value!=="local"?0:(await e.prepare("DELETE FROM runtime_state WHERE key = 'grants_source'").run(),Number((await e.prepare("DELETE FROM grants").run()).changes))}t(je,"dropLocalGrantMirror");async function we(){return await T(async e=>Number((await e.prepare("UPDATE grants SET computed_rev = rev WHERE computed_rev IS NULL AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL").run()).changes))}t(we,"backfillComputedRev");function be(e){if(e===void 0)return[];if(!Array.isArray(e))throw new TypeError("invalid grant sync response");const r=[];for(const n of e){const{team:s,members:o}=n??{};if(!(typeof s!="string"||!/^team:\S+$/.test(s))){if(!Array.isArray(o)||o.some(a=>typeof a!="string"||!/^user:[^\s*]+$/.test(a)))throw new TypeError("invalid grant sync response");r.push({team:s,members:o})}}return r}t(be,"teamsOf");async function he(e,r,n,s=[]){const o=new Set;for(const a of e){if(o.has(a.id)||!a.id||!a.runtime||!a.sub||!a.grantee||!Number.isInteger(a.rev)||!["active","revoked","removed"].includes(a.status))throw new TypeError("invalid grant sync response");o.add(a.id),l(a.scopes),l(a.resolved_scopes)}await T(async a=>{let E=0;const g=[...o];E+=Number((await(g.length?a.prepareUncached(`DELETE FROM grants WHERE id NOT IN (${g.map(()=>"?").join(",")})`).run(...g):a.prepareUncached("DELETE FROM grants").run())).changes);const w=a.prepare(`INSERT INTO grants
9
9
  (id, runtime, sub, grantee, rev, scopes_json, resolved_scopes_json, spend_cap, expires_at,
10
10
  status, revoked_at, approved_at, payer, dependencies_json, run_notice_url, inference_endpoint_json, synced_at, computed_rev)
11
11
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
@@ -19,4 +19,4 @@ var h=Object.defineProperty;var t=(e,r)=>h(e,"name",{value:r,configurable:!0});i
19
19
  grants.run_notice_url, grants.inference_endpoint_json, grants.computed_rev)
20
20
  IS DISTINCT FROM (excluded.runtime, excluded.sub, excluded.grantee, excluded.rev, excluded.scopes_json, excluded.resolved_scopes_json,
21
21
  excluded.spend_cap, excluded.expires_at, excluded.status, excluded.revoked_at, excluded.approved_at, excluded.payer,
22
- excluded.dependencies_json, excluded.run_notice_url, excluded.inference_endpoint_json, excluded.computed_rev)`);for(const c of e)E+=Number((await w.run(c.id,c.runtime,c.sub,c.grantee,c.rev,JSON.stringify(c.scopes),JSON.stringify(c.resolved_scopes),c.spend_cap,c.expires_at,c.status,c.revoked_at,c.approved_at,c.payer,JSON.stringify(O(c.dependencies)),c.run_notice_url??null,c.inference_endpoint?JSON.stringify(c.inference_endpoint):null,c.synced_at,c.rev)).changes);await I(o,"directory",M,"member",s.flatMap(({team:c,members:b})=>b.map(R=>({resourceId:c,subject:C(R)})))),await o.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_source', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(n),E>0&&await o.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_generation', '1') ON CONFLICT(key) DO UPDATE SET value = CAST(CAST(runtime_state.value AS INTEGER) + 1 AS TEXT)").run()})}t(Re,"replaceGrants");async function he(){const e=await(await p()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_generation'").get();return e?Number(e.value):0}t(he,"grantsGeneration");export{X as activeGrant,Se as activeGrantForApp,oe as activeGrantNamesApp,ie as activeGrants,de as activeGrantsOfPerson,se as activeProviderIds,q as activeRecord,J as allGrants,ae as anyActiveGrant,we as backfillComputedRev,O as dependenciesOf,je as dropLocalGrantMirror,V as grantExpired,xe as grantFor,ve as grantIdsWhere,B as grantRecord,ge as grantStanding,ce as grantSubs,ye as grantSyncState,Ee as grantSyncStateFor,fe as grantVersion,ue as grantedProviderIds,he as grantsGeneration,le as grantsOfPerson,Oe as grantsSource,_e as hasGrant,Ae as hasSyncedGrants,G as inferenceEndpointOf,pe as isProviderBundleRow,ne as localGrants,_ as mirrorOnly,te as otherLiveGrantOfApp,me as payerOfGrant,W as providerIdsFromGrants,Re as replaceGrants,Te as runNoticeTarget,v as runtimeScope,be as teamsOf,Ne as terminalGrant};
22
+ excluded.dependencies_json, excluded.run_notice_url, excluded.inference_endpoint_json, excluded.computed_rev)`);for(const c of e)E+=Number((await w.run(c.id,c.runtime,c.sub,c.grantee,c.rev,JSON.stringify(c.scopes),JSON.stringify(c.resolved_scopes),c.spend_cap,c.expires_at,c.status,c.revoked_at,c.approved_at,c.payer,JSON.stringify(O(c.dependencies)),c.run_notice_url??null,c.inference_endpoint?JSON.stringify(c.inference_endpoint):null,c.synced_at,c.rev)).changes);await I(a,"directory",M,"member",s.flatMap(({team:c,members:b})=>b.map(h=>({resourceId:c,subject:C(h)})))),await a.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_source', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(n),E>0&&await a.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_generation', '1') ON CONFLICT(key) DO UPDATE SET value = CAST(CAST(runtime_state.value AS INTEGER) + 1 AS TEXT)").run()})}t(he,"replaceGrants");async function Re(){const e=await(await p()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_generation'").get();return e?Number(e.value):0}t(Re,"grantsGeneration");export{X as activeGrant,Se as activeGrantForApp,oe as activeGrantNamesApp,ie as activeGrants,de as activeGrantsOfPerson,se as activeProviderIds,q as activeRecord,J as allGrants,ae as anyActiveGrant,we as backfillComputedRev,O as dependenciesOf,je as dropLocalGrantMirror,V as grantExpired,xe as grantFor,ve as grantIdsWhere,B as grantRecord,ge as grantStanding,ce as grantSubs,ye as grantSyncState,Ee as grantSyncStateFor,fe as grantVersion,ue as grantedProviderIds,Re as grantsGeneration,le as grantsOfPerson,Oe as grantsSource,_e as hasGrant,Ae as hasSyncedGrants,G as inferenceEndpointOf,pe as isProviderBundleRow,ne as localGrants,_ as mirrorOnly,te as otherLiveGrantOfApp,me as payerOfGrant,W as providerIdsFromGrants,he as replaceGrants,Te as runNoticeTarget,v as runtimeScope,be as teamsOf,Ne as terminalGrant};
@@ -0,0 +1,9 @@
1
+ export type Outcome = 'ok' | 'fail' | 'none';
2
+ export type Ticket = {
3
+ test: boolean;
4
+ settle: (outcome: Outcome, now?: number) => void;
5
+ };
6
+ /** Seconds to wait (full jitter, 1 s or more) while `model` is refused, else null. Never creates an entry. */
7
+ export declare function refusal(model: string, now?: number): number | null;
8
+ /** A ticket to settle once when the call ends, or the seconds to wait when the breaker refuses. */
9
+ export declare function admit(model: string, now?: number): Ticket | number;
@@ -0,0 +1 @@
1
+ var c=Object.defineProperty;var r=(n,s)=>c(n,"name",{value:s,configurable:!0});const S=6e4,g=1e4,p=3e5,l=new Map;function w(n,s=Date.now()){const e=l.get(n);return e===void 0||e.openUntil===null||s>=e.openUntil&&!e.testing?null:Math.max(1,Math.ceil(Math.random()*e.waitMs/1e3))}r(w,"refusal");function T(n,s=Date.now()){const e=w(n,s);if(e!==null)return e;const i=l.get(n),M=i?.openUntil!=null;M&&(i.testing=!0);let f=!1;return{test:M,settle:r((o,a=Date.now())=>{if(f)return;if(f=!0,M){o==="ok"?l.delete(n):o==="fail"&&Object.assign(i,{waitMs:Math.min(3e5,2*i.waitMs),openUntil:a+Math.min(3e5,2*i.waitMs)}),i.testing=!1;return}if(o==="none")return;const t=l.get(n)??{outcomes:[],inRow:0,openUntil:null,waitMs:1e4,testing:!1};l.set(n,t),t.outcomes=[...t.outcomes.filter(u=>a-u.at<6e4),{at:a,ok:o==="ok"}];const _=t.outcomes.filter(u=>!u.ok).length;t.inRow=o==="ok"?0:t.inRow+1,t.openUntil===null&&(_>=3&&_*2>=t.outcomes.length||t.inRow>=3)&&Object.assign(t,{openUntil:a+1e4,waitMs:1e4})},"settle")}}r(T,"admit");export{T as admit,w as refusal};
@@ -47,10 +47,13 @@ export declare function cronWakeOrigin(c: Cron, kind: WakeOrigin['kind']): Promi
47
47
  * carry the signal, and a raw ISO instant is noise an agent cannot cheaply turn
48
48
  * into an elapsed delta. */
49
49
  export declare function buildWakeBearings(origin: WakeOrigin): string;
50
+ /** The `<project_context>` snapshot of the node's cwd: it spawns git and tmux and reads this host's disk, so a caller builds it BEFORE
51
+ * opening the delivery transaction and passes it in as `projectContext`; '' when the node's engine does not run on this host. */
52
+ export declare function projectContextForNode(nodeId: string): Promise<string>;
50
53
  /** The bearings on the row-backed delivery engine: the knowledge catalog and
51
54
  * the workspace-open documents render against `ctx`'s ledger; `delivered`
52
55
  * lists what they delivered, for the caller to record. */
53
- export declare function buildContextBearings(nodeId: string, ctx: RenderContext): Promise<{
56
+ export declare function buildContextBearings(nodeId: string, ctx: RenderContext, projectContext: string): Promise<{
54
57
  content: string;
55
58
  delivered: DeliveredDoc[];
56
59
  }>;
@@ -1,7 +1,7 @@
1
- var g=Object.defineProperty;var i=(e,r)=>g(e,"name",{value:r,configurable:!0});import{getNode as s,latestExecutionForNode as N,fullName as w,isSafeNodeId as v,subscriptionsOf as x}from"../canvas/index.js";import{cadenceDisplay as _}from"../wake.js";import{renderKnowledge as Y,renderWorkspaceOpen as $}from"../substrate/delivery/render-boot.js";import{situationalContextEnvelope as C}from"./situational-context.js";import{statusRank as f}from"../canvas/node-order.js";import{buildProjectContextBlock as p,contextDirNote as h,orchestratorContextNote as m,whereYouRunNote as S,profileNote as E,renderGraphMap as O,buildIdentityAssertion as R,worktreeNote as A}from"./bearings-render.js";import{mapAsync as j}from"../async-array.js";import{CONTEXT_INTRO_CUSTOM_TYPE as re}from"../../shared/generated-context.js";async function B(e,r){const n=r!==void 0?r:await s(e);return n===null?"":E(n.cwd,n.profile_id)}i(B,"profileNote");async function T(e,r){const n=[],t=new Set([e]);let o=r.parent??null;for(;o!==null&&o!==""&&!t.has(o);){t.add(o);const a=await s(o);if(a===null)break;n.unshift(a),o=a.parent??null}return n}i(T,"ancestorTrunk");const J=5;async function W(e){return(await j(await x(e),async r=>await s(r.node_id))).filter(r=>r!==null&&r.kind!=="human").sort((r,n)=>f(r.status)-f(n.status))}i(W,"childNodes");async function D(e,r){const n=r!==void 0?r:await s(e);if(n===null)return"";const t=await T(e,n),o=await W(e);return O(e,n.kind,n.mode,t,o)}i(D,"buildGraphMap");async function H(e,r){const n=r?.fork_from,t=n!=null&&n!==""&&v(n)?await s(n):null,o=t!==null?`${n} ("${w(t)}")`:n??"";return R(e,r?.kind??"general",r?.mode??"base",n,o)}i(H,"buildIdentityAssertion");function L(e){return e.ownerId===null||e.ownerId===""?"an unknown node":e.ownerName!==void 0?`node ${e.ownerId} ("${e.ownerName}")`:`node ${e.ownerId} (now gone)`}i(L,"armerPhrase");async function Q(e,r){const n=e.created_by!=null?await s(e.created_by):null;return{kind:r,ownerId:e.created_by,...n!==null?{ownerName:w(n)}:{},armedAt:e.created,recur:e.recur}}i(Q,"cronWakeOrigin");function V(e){const r=e.recur!==null&&e.recur!==void 0&&e.recur!=="",n=r?_(e.recur):null;if(e.kind==="schedule_revive")return`<crtr-wake>
2
- ${r?`A SCHEDULE woke you, not a message \u2014 a recurring cron firing ${n} revived you fresh. Nothing new happened on the canvas and nobody is waiting on a reply: the clock came round. Re-read your bearings below, do this cycle's pass of the standing job, and stop.`:"A SCHEDULE woke you, not a message \u2014 a one-shot cron armed to fire now revived you fresh. Nothing new happened on the canvas and nobody is waiting on a reply: the time you were waiting for arrived. Re-read your bearings below and continue from there."}
3
- </crtr-wake>`;const t=L(e);return`<crtr-wake>
4
- ${r?`You were BORN by a scheduled wake, not spawned on demand \u2014 a recurring spawn-cron armed by ${t}, firing ${n}. The runtime re-births a fresh node like you on this cadence whether or not earlier runs survived: you are one run of a standing job, not a one-off, and you inherit nothing from prior runs but this task. Your task follows.`:`You were BORN by a scheduled wake, not spawned on demand \u2014 a one-shot deferred birth armed by ${t} to fire now. You are its only run, not a recurring job. Your task follows.`}
5
- </crtr-wake>`}i(V,"buildWakeBearings");function M(e){return A(e?.managed_worktree)}i(M,"managedWorktreeNote");async function P(e,r,n){const t=await s(e),o=await N(e),a=["<crtr-bearings>",await H(e,t)],u=S(o?.runner);u!==""&&a.push("","## Where you run",u);const c=await D(e,t);c!==""&&a.push("","## Your place in the canvas",c),a.push("","## Your documents and context directory",h(e,t?.grantee));const d=await B(e,t);d!==""&&a.push("",d);const l=M(t);l!==""&&a.push("","## Your managed worktree",l),t?.mode==="orchestrator"&&a.push("",m()),a.push("</crtr-bearings>");const y=await C(e)??"",b=t?.cwd!==void 0&&o?.runner==="process"?p(t.cwd):"";return[a.join(`
6
- `),r,n,y,b].filter(k=>k!=="").join(`
7
- `)}i(P,"bearingsShell");async function Z(e,r){const n=await Y(r),t=await $(r);return{content:await P(e,n.content,t.content),delivered:[...n.delivered,...t.delivered]}}i(Z,"buildContextBearings");export{re as CONTEXT_INTRO_CUSTOM_TYPE,Z as buildContextBearings,D as buildGraphMap,p as buildProjectContextBlock,V as buildWakeBearings,h as contextDirNote,Q as cronWakeOrigin,m as orchestratorContextNote,B as profileNote};
1
+ var g=Object.defineProperty;var a=(e,n)=>g(e,"name",{value:n,configurable:!0});import{getNode as s,latestExecutionForNode as f,fullName as p,isSafeNodeId as v,subscriptionsOf as x}from"../canvas/index.js";import{cadenceDisplay as _}from"../wake.js";import{renderKnowledge as Y,renderWorkspaceOpen as $}from"../substrate/delivery/render-boot.js";import{situationalContextEnvelope as C}from"./situational-context.js";import{statusRank as h}from"../canvas/node-order.js";import{buildProjectContextBlock as m,contextDirNote as y,orchestratorContextNote as b,whereYouRunNote as S,profileNote as E,renderGraphMap as O,buildIdentityAssertion as R,worktreeNote as A}from"./bearings-render.js";import{mapAsync as j}from"../async-array.js";import{CONTEXT_INTRO_CUSTOM_TYPE as te}from"../../shared/generated-context.js";async function B(e,n){const r=n!==void 0?n:await s(e);return r===null?"":E(r.cwd,r.profile_id)}a(B,"profileNote");async function T(e,n){const r=[],o=new Set([e]);let t=n.parent??null;for(;t!==null&&t!==""&&!o.has(t);){o.add(t);const u=await s(t);if(u===null)break;r.unshift(u),t=u.parent??null}return r}a(T,"ancestorTrunk");const J=5;async function W(e){return(await j(await x(e),async n=>await s(n.node_id))).filter(n=>n!==null&&n.kind!=="human").sort((n,r)=>h(n.status)-h(r.status))}a(W,"childNodes");async function D(e,n){const r=n!==void 0?n:await s(e);if(r===null)return"";const o=await T(e,r),t=await W(e);return O(e,r.kind,r.mode,o,t)}a(D,"buildGraphMap");async function H(e,n){const r=n?.fork_from,o=r!=null&&r!==""&&v(r)?await s(r):null,t=o!==null?`${r} ("${p(o)}")`:r??"";return R(e,n?.kind??"general",n?.mode??"base",r,t)}a(H,"buildIdentityAssertion");function L(e){return e.ownerId===null||e.ownerId===""?"an unknown node":e.ownerName!==void 0?`node ${e.ownerId} ("${e.ownerName}")`:`node ${e.ownerId} (now gone)`}a(L,"armerPhrase");async function Q(e,n){const r=e.created_by!=null?await s(e.created_by):null;return{kind:n,ownerId:e.created_by,...r!==null?{ownerName:p(r)}:{},armedAt:e.created,recur:e.recur}}a(Q,"cronWakeOrigin");function V(e){const n=e.recur!==null&&e.recur!==void 0&&e.recur!=="",r=n?_(e.recur):null;if(e.kind==="schedule_revive")return`<crtr-wake>
2
+ ${n?`A SCHEDULE woke you, not a message \u2014 a recurring cron firing ${r} revived you fresh. Nothing new happened on the canvas and nobody is waiting on a reply: the clock came round. Re-read your bearings below, do this cycle's pass of the standing job, and stop.`:"A SCHEDULE woke you, not a message \u2014 a one-shot cron armed to fire now revived you fresh. Nothing new happened on the canvas and nobody is waiting on a reply: the time you were waiting for arrived. Re-read your bearings below and continue from there."}
3
+ </crtr-wake>`;const o=L(e);return`<crtr-wake>
4
+ ${n?`You were BORN by a scheduled wake, not spawned on demand \u2014 a recurring spawn-cron armed by ${o}, firing ${r}. The runtime re-births a fresh node like you on this cadence whether or not earlier runs survived: you are one run of a standing job, not a one-off, and you inherit nothing from prior runs but this task. Your task follows.`:`You were BORN by a scheduled wake, not spawned on demand \u2014 a one-shot deferred birth armed by ${o} to fire now. You are its only run, not a recurring job. Your task follows.`}
5
+ </crtr-wake>`}a(V,"buildWakeBearings");function M(e){return A(e?.managed_worktree)}a(M,"managedWorktreeNote");async function F(e,n,r,o){const t=await s(e),u=await f(e),i=["<crtr-bearings>",await H(e,t)],c=S(u?.runner);c!==""&&i.push("","## Where you run",c);const d=await D(e,t);d!==""&&i.push("","## Your place in the canvas",d),i.push("","## Your documents and context directory",y(e,t?.grantee));const l=await B(e,t);l!==""&&i.push("",l);const w=M(t);w!==""&&i.push("","## Your managed worktree",w),t?.mode==="orchestrator"&&i.push("",b()),i.push("</crtr-bearings>");const k=await C(e)??"";return[i.join(`
6
+ `),n,r,k,o].filter(N=>N!=="").join(`
7
+ `)}a(F,"bearingsShell");async function Z(e){const n=await s(e),r=await f(e);return n?.cwd!==void 0&&r?.runner==="process"?m(n.cwd):""}a(Z,"projectContextForNode");async function ee(e,n,r){const o=await Y(n),t=await $(n);return{content:await F(e,o.content,t.content,r),delivered:[...o.delivered,...t.delivered]}}a(ee,"buildContextBearings");export{te as CONTEXT_INTRO_CUSTOM_TYPE,ee as buildContextBearings,D as buildGraphMap,m as buildProjectContextBlock,V as buildWakeBearings,y as contextDirNote,Q as cronWakeOrigin,b as orchestratorContextNote,B as profileNote,Z as projectContextForNode};
@@ -1 +1 @@
1
- var b=Object.defineProperty;var p=(c,f)=>b(c,"name",{value:f,configurable:!0});import{createServer as _,request as y}from"node:http";import{request as k}from"node:https";import{chmodSync as v,existsSync as R,rmSync as A,unlinkSync as E}from"node:fs";import{join as u}from"node:path";import{apiSocketPath as B,BROKER_RELEASED_MARKER as C,BROKER_RELAY_GENERATION as O,nodeRunDir as S}from"../../canvas/paths.js";import{writeFileBeneath as N}from"../../spaces/open-beneath.js";import{currentCausedBy as U}from"./turn-cause.js";import{brokerApiUrl as q}from"./daemon-ops.js";import{northlightUnreachable as x}from"../../directory/reach.js";async function F(c,f){const o=u(S(c),"cli.sock"),d=q(),w=p((r,e,t,i)=>{if(d===void 0)return y({socketPath:B(),path:r,method:e,headers:t},i);const s=new URL(r??"/",d);return delete t.host,(s.protocol==="https:"?k:y)(s,{method:e,headers:t},i)},"forward"),a=_((r,e)=>{const t={...r.headers,authorization:`Bearer ${f}`},i=U();i!==void 0&&t["crtr-caused-by"]===void 0&&(t["crtr-caused-by"]=i),delete t.connection;const s=w(r.url,r.method,t,n=>{e.writeHead(n.statusCode??502,n.headers),n.pipe(e)});s.on("error",n=>{if(e.headersSent||e.writeHead(503,{"content-type":"application/json"}),d===void 0)return void e.end(JSON.stringify({error:{code:"daemon_unavailable",message:n.message}}));const m=x(n,d);e.end(JSON.stringify({error:{code:m.code,message:m.message,retryable:!0,details:m.details}}))}),r.pipe(s),e.on("close",()=>s.destroy())});R(o)&&E(o),await new Promise((r,e)=>{a.once("error",e),a.listen(o,()=>{a.off("error",e),r()})}),v(o,384);const l=S(c),h=process.env.CRTR_EXECUTION_ID;if(!h)throw new Error("broker relay has no execution id");return N(l,u(l,O),h,{atomic:!0}),A(u(l,C),{force:!0}),{path:o,close(){a.closeAllConnections(),a.close(),R(o)&&E(o)}}}p(F,"serveCliRelay");export{F as serveCliRelay};
1
+ var b=Object.defineProperty;var p=(c,f)=>b(c,"name",{value:f,configurable:!0});import{createServer as _,request as y}from"node:http";import{request as k}from"node:https";import{chmodSync as v,existsSync as R,rmSync as A,unlinkSync as E}from"node:fs";import{join as u}from"node:path";import{apiSocketPath as B,BROKER_RELEASED_MARKER as C,BROKER_RELAY_GENERATION as O,nodeRunDir as S}from"../../canvas/paths.js";import{writeFileBeneath as N}from"../../spaces/open-beneath.js";import{currentCausedBy as U}from"./turn-cause.js";import{brokerApiUrl as q}from"./daemon-ops.js";import{northlightUnreachable as x}from"../../directory/reach.js";async function F(c,f){const o=u(S(c),"cli.sock"),d=q(),w=p((r,e,t,i)=>{if(d===void 0)return y({socketPath:B(),path:r,method:e,headers:t,agent:!1},i);const s=new URL(r??"/",d);return delete t.host,(s.protocol==="https:"?k:y)(s,{method:e,headers:t},i)},"forward"),a=_((r,e)=>{const t={...r.headers,authorization:`Bearer ${f}`},i=U();i!==void 0&&t["crtr-caused-by"]===void 0&&(t["crtr-caused-by"]=i),delete t.connection;const s=w(r.url,r.method,t,n=>{e.writeHead(n.statusCode??502,n.headers),n.pipe(e)});s.on("error",n=>{if(e.headersSent||e.writeHead(503,{"content-type":"application/json"}),d===void 0)return void e.end(JSON.stringify({error:{code:"daemon_unavailable",message:n.message}}));const m=x(n,d);e.end(JSON.stringify({error:{code:m.code,message:m.message,retryable:!0,details:m.details}}))}),r.pipe(s),e.on("close",()=>s.destroy())});R(o)&&E(o),await new Promise((r,e)=>{a.once("error",e),a.listen(o,()=>{a.off("error",e),r()})}),v(o,384);const l=S(c),h=process.env.CRTR_EXECUTION_ID;if(!h)throw new Error("broker relay has no execution id");return N(l,u(l,O),h,{atomic:!0}),A(u(l,C),{force:!0}),{path:o,close(){a.closeAllConnections(),a.close(),R(o)&&E(o)}}}p(F,"serveCliRelay");export{F as serveCliRelay};
@@ -8,6 +8,7 @@ import type { BrokerToClient } from '../broker-protocol.js';
8
8
  import type { BrokerSession } from './read-ops.js';
9
9
  import type { SubscriptionGeneration } from './rebind.js';
10
10
  import type { TurnAdmissionGate } from './turn-admission.js';
11
+ import { type GatewayAnswer } from './model-adapter.js';
11
12
  import type { RunTurnEnds } from './run-turn-end.js';
12
13
  /** How long a run node's turn may stay open on in-episode provider retries,
13
14
  * measured from the episode's first failure. An app waits on the turn's
@@ -23,7 +24,7 @@ export declare function retryCardBody(kind: RecoveryFaultDTO['kind'], isRun: boo
23
24
  type FaultRetryDeps = {
24
25
  nodeId: string;
25
26
  cfg: BrokerSdkConfig;
26
- retryProbe: () => Promise<boolean>;
27
+ retryProbe: () => Promise<GatewayAnswer>;
27
28
  currentSession: () => BrokerSession;
28
29
  currentServices: () => AgentSessionServices;
29
30
  installedGeneration: () => SubscriptionGeneration | undefined;
@@ -62,6 +63,8 @@ export declare class FaultRetry {
62
63
  private notFoundFallbackInFlight;
63
64
  private stagedCapacityFailure;
64
65
  private agentStarts;
66
+ /** Answers in a row that were not yes, for the broker's own doubling wait when the gateway does not answer. */
67
+ private unanswered;
65
68
  constructor(deps: FaultRetryDeps);
66
69
  clearTimer(): void;
67
70
  reset(): void;
@@ -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 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};
1
+ var fe=Object.defineProperty;var m=(i,e)=>fe(i,"name",{value:e,configurable:!0});import{envModelIntent as Y,envNodeCwd as j,envProfileId as q}from"../../../shared/env.js";import{isContextOverflow as V}from"@earendil-works/pi-ai";import{classify as O}from"../../fault-classifier.js";import{isDaemonTransportApiError as X}from"../../../api/errors.js";import{isModelNotFoundError as pe,isProviderUnconfiguredError as he}from"../fault.js";import{takeCycleRecovery as me}from"./cycle-start.js";import{brokerRecovery as ge,daemonClient as J,mutateBrokerFault as K,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 z,KEY_CREDENTIAL_SOURCE as we,modelRequestFromConfig as H}from"../../model-routes.js";import{operationIdContext as Q}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 Z,formatModelFallbackRecovery as Ie}from"../../../shared/generated-context.js";import{markFatalOnExhaust as ee,nextFaultRetry as P,policyFor as _e}from"../fault-recovery.js";import{parseModelSpec as te}from"../model-selection.js";import{endedByAbort as ne}from"../session-cycles.js";import{isManagedProvider as re,resolveProviderCandidates as Ee}from"../../subscription-state.js";import{announceMessageOrigin as ie}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,ae=3e4;function Me(i,e,t){const n=Date.parse(i);return!Number.isFinite(n)||t+e-n>ae}m(Me,"runTurnRetryExpired");class _ extends Error{static{m(this,"StaleOutcome")}}const xe=1e3,Ce=3e4;function Te(i,e){return i!=="connection"?ke:e?be:Fe}m(Te,"retryCardBody");function E(i){return{link:i.link,op:i.op,kind:i.kind,retry:i.retry,message:i.message,since:i.since,operation_id:i.operation_id,...i.anchor_entry_id===void 0?{}:{anchorEntryId:i.anchor_entry_id},...i.provider_error===void 0?{}:{providerError:i.provider_error}}}m(E,"policyFault");function $(i){return i instanceof Error?i.message:String(i)}m($,"errorText");function oe(i){return X(i)||O("pi\u2192provider",i).disposition==="auto"}m(oe,"isTransientRejection");function A(i){return{link:i.link,op:i.op,kind:i.kind,retry:i.retry,message:i.message,...i.operation_id===void 0?{}:{operation_id:i.operation_id},...i.since===void 0?{}:{since:i.since},...i.anchorEntryId===void 0?{}:{anchor_entry_id:i.anchorEntryId},...i.providerError===void 0?{}:{provider_error:i.providerError}}}m(A,"faultInput");function de(i,e){const t=m(n=>`${n.providerId}/${n.modelId}`===e.modelSpec,"onLiveModel");return(i.find(n=>t(n)&&n.thinkingLevel===e.thinkingLevel)??i.find(t))?.rank}m(de,"liveRouteRank");function le(i){const e=O("pi\u2192provider",i),t=i.diagnostics?.some(n=>n.type===Re)??!1;return{classified:e,disposition:t?"fatal":e.disposition}}m(le,"settledProviderFault");function nt(i,e){if(i.stopReason!=="error"||ne(i)||se(i)||V(i,e))return!1;const{classified:t,disposition:n}=le(i);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(i,e){return e&&Oe.test(i)}m(Pe,"isPrefillRejectionDuringEpisode");class rt{static{m(this,"FaultRetry")}deps;timer=null;failedRetryRoutes=new Set;notFoundModels=new Set;providerFallbackInFlight=null;notFoundFallbackInFlight=null;stagedCapacityFailure=null;agentStarts=0;unanswered=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 K(this.deps.nodeId,{op:"record",input:e})).fault}async clearFault(e,t=!1){await K(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,r=m(()=>{if(this.deps.installedGeneration()!==e||this.agentStarts!==n)throw new _},"assertCurrent");try{await this.retryWhileDaemonUnreachable("settled turn fault write",()=>this.recordStagedOutcome(e,t,r),r)}catch(s){if(!(s instanceof _))throw s}}async retryWhileDaemonUnreachable(e,t,n){let r=xe;for(;;){try{await t();return}catch(s){if(!X(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,r)),r=Math.min(r*2,Ce),n()}}async recordStagedOutcome(e,t,n){const{agentEnd:r,watchdogAbort:s,refreshAbort:o,overflowFailure:c,capacityFailure:f}=t,a=e.session,d=m(async b=>{n(),await this.clearEpisode(b)},"clearEpisode"),y=m(async b=>{n(),await this.recordFault(b)},"recordFault"),v=m(async(b,ce)=>{n(),await this.recordPendingProviderFault(b,ce)},"recordPendingProviderFault"),l=await this.state(),p=l.fault,g=l.episode,k=this.sessionId(a),w=this.isActiveAutoFault(p)&&p.link==="pi\u2192provider"?p:g?.state==="admitted"&&g.session_id===k&&this.isActiveAutoFault(g.fault)?g.fault:null,h=w===null?null:{since:w.since,anchorEntryId:w.anchor_entry_id,attempt:w.retry.attempt},u=[...Array.isArray(r?.messages)?r.messages:[]].reverse().find(b=>typeof b=="object"&&b!==null&&b.role==="assistant");if(f!==null||c!==null){await d(a),await y({link:"pi\u2192provider",op:"context overflow recovery",kind:"context-overflow",retry:{disposition:"fatal"},message:f?.errorMessage??c.errorMessage,anchor_entry_id:a.sessionManager.getLeafId?.()??void 0});return}if(s&&u?.stopReason==="aborted"){await v(a,{link:"pi\u2192provider",op:"generation turn",kind:"connection",retry:{disposition:"auto",by:"daemon",...h?.attempt!==void 0?{attempt:h.attempt}:{}},message:typeof u.errorMessage=="string"?u.errorMessage:"engine error (no errorMessage recorded)",...h!==null?{since:h.since}:{},anchor_entry_id:this.retryAnchor(a,h?.anchorEntryId)});return}if(u?.stopReason!=="error"){u!==void 0&&await d(a);return}if(o){await d(a);return}if(se(u)){await d(a);return}const M=typeof u.errorMessage=="string"?u.errorMessage:"engine error (no errorMessage recorded)";if(ne({stopReason:"error",errorMessage:M})){await d(a);return}const R=V(u,a.model?.contextWindow),x=le(u),L=h!==null&&x.disposition!=="auto"&&Pe(M,!0),ue=L?{kind:"connection",disposition:"auto"}:x.classified,S=L?"auto":x.disposition,N=ye(u),G=Se(u),C=ve(u),U=typeof u.provider=="string"&&u.provider!==""?u.provider:a.model?.provider,W=typeof u.model=="string"&&u.model!==""?u.model:a.model?.id,B=C===void 0||U===void 0||W===void 0?void 0:{provider:U,model:W,...C};R&&await d(a);const T={link:"pi\u2192provider",op:"generation turn",kind:R?"context-overflow":ue.kind,retry:R?{disposition:"fatal"}:S==="auto"?{disposition:"auto",by:"daemon",...N!==void 0?{nextAt:new Date(N).toISOString()}:{},...h?.attempt!==void 0?{attempt:C?.body==="breaker"&&g?.state==="admitted"?Math.max(0,h.attempt-1):h.attempt}:{}}:{disposition:S,...G!==void 0?{nextAt:new Date(G).toISOString()}:{}},message:M,...!R&&S==="auto"&&h!==null?{since:h.since}:{},anchor_entry_id:!R&&S==="auto"?this.retryAnchor(a,h?.anchorEntryId):a.sessionManager.getLeafId?.()??void 0,...B===void 0?{}:{provider_error:B}};T.retry.disposition==="auto"?await v(a,T):(await d(a),await y(T))}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=(me(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(A(E(t.fault)));const r=await this.schedule();return r==="armed"?"retry-armed":r==="exhausted"?"fatal":"none"}hasProgressPastAnchor(e,t){const n=e.sessionManager.getBranch(),r=n.findIndex(o=>o.id===t);return(r===-1?n:n.slice(r+1)).some(o=>{if(o.type!=="message")return!1;const{message:c}=o;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(),r=n.fault;if(!this.isActiveAutoFault(r)||this.sessionId(t)!==null&&!this.pendingEpisodeMatches(t,r,n))return this.clearTimer(),this.abandonTurnEnd(),"none";const s=Date.now(),o=this.faultRetryDelayMs(r,s);return o!==null&&this.deps.turnEnds?.holding()===!0&&Me(r.since,o,s)?(await this.endRunTurnOnFault(t,r,o),"none"):o!==null?(this.clearAndArmFaultRetry(o,e),this.timer!==null?"armed":"none"):(this.abandonTurnEnd(),r.retry.nextAt!==void 0||this.deps.installedGeneration()!==e||this.deps.currentSession()!==t||t.isStreaming?"none":(await this.settleExhausted(t,r),"exhausted"))}async settleExhausted(e,t){await this.recordFault(A(ee(E(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 ${ae}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=O("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 r=this.deps.currentSession(),s=this.deps.currentServices(),o=this.deps.formatModelSpec(r.model,r.thinkingLevel);if(o===null)return;const c=H(this.deps.cfg.model,Y(),!1);if(c===void 0)return;const f=te(o),a=(async()=>{const d=await z(c,j()??this.deps.cfg.cwd,q()),y=de(d,f),v=y===void 0?{route:void 0,capacityExhausted:!1}:await this.nextEligibleFallbackRoute(d.slice(y+1),this.deps.registryOf(s),r.getContextUsage()?.tokens,k=>!this.failedRetryRoutes.has(k.routeId));if(v.route===void 0){v.capacityExhausted&&(this.stageCapacityFailure(n,r),queueMicrotask(()=>{this.deps.installedGeneration()===n&&this.deps.currentSession()===r&&r.abortRetry()}));return}const l=v.route,p=this.deps.registryOf(s).find(l.providerId,l.modelId);if(!p||(await r.setModel(p),this.deps.installedGeneration()!==n||this.deps.currentSession()!==r))return;const g=`${l.providerId}/${l.modelId}`===f.modelSpec?f.thinkingLevel:l.thinkingLevel;r.setThinkingLevel(g??"off"),this.failedRetryRoutes.add(l.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=a}maybeFallbackOnUnusableModel(e){if(e.type!=="message_end"||e.message.role!=="assistant"||e.message.stopReason!=="error")return;const t=he(e.message.errorMessage??"");if(!t&&!pe(e.message.errorMessage??"")||this.deps.cfg.modelExact===!0||this.notFoundFallbackInFlight!==null)return;const n=this.deps.installedGeneration();if(n===void 0)return;const r=this.deps.currentSession(),s=this.deps.currentServices(),o=this.deps.formatModelSpec(r.model,r.thinkingLevel);if(o===null)return;const c=te(o);this.notFoundModels.add(c.modelSpec);const f=H(this.deps.cfg.model,Y(),!1),a=(async()=>{const d=f?await z(f,j()??this.deps.cfg.cwd,q()):[],y=de(d,c),v=y===void 0?{route:void 0,capacityExhausted:!1}:await this.nextEligibleFallbackRoute(d.slice(y+1),this.deps.registryOf(s),r.getContextUsage()?.tokens,h=>!this.notFoundModels.has(`${h.providerId}/${h.modelId}`));if(v.route===void 0){v.capacityExhausted&&this.stageCapacityFailure(n,r);return}const l=v.route,p=`${l.providerId}/${l.modelId}${l.thinkingLevel?`:${l.thinkingLevel}`:""}`,g=this.deps.registryOf(s).find(l.providerId,l.modelId);if(g===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 r.setModel(g),this.deps.installedGeneration()!==n||this.deps.currentSession()!==r)return;r.setThinkingLevel(l.thinkingLevel??"off"),await this.deps.broadcastModelChanged();const k=this.deps.formatModelSpec(r.model,r.thinkingLevel)??p;if(F({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`${t?"unconfigured-provider":"not_found"} fallback: ${o} unavailable \u2192 ${k}; re-driving turn`}}),await r.agent.waitForIdle(),this.deps.installedGeneration()!==n||this.deps.currentSession()!==r)return;t&&await this.clearFault("pi\u2192provider");const w=Z("recovery",{},Ie(o,k,t?"credential":"not-found"));ie(w,{type:"runtime",kind:"recovery"}),await this.deps.turnAdmission.admit(h=>Q.fresh(()=>r.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=a}async nextEligibleFallbackRoute(e,t,n,r){let s=0,o=0;for(const c of e){if(!r(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)){o++;continue}return{route:c,capacityExhausted:!1}}}return{route:void 0,capacityExhausted:s>0&&s===o}}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&&re(e.providerId))return{registered:!0,authenticated:(await J().listModelAuth()).keys.some(o=>o.provider===e.providerId)};if(!re(e.providerId))return{registered:!0,authenticated:t.hasConfiguredAuth(n)};const r=await J().getModelAuthReadiness({model:`${e.providerId}/${e.modelId}`}),s=r.rate_limited_until==null?void 0:Date.parse(r.rate_limited_until);return{registered:!0,authenticated:r.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 r=this.sessionId(e),s=n.episode;return r!==null&&s!==null&&s.state==="pending"&&s.session_id===r&&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 P(E(e),t)?.delayMs??null}clearAndArmFaultRetry(e,t){if(this.deps.installedGeneration()!==t)return;this.clearTimer();const n=Math.min(Math.max(0,e),Ae),r=Math.max(0,e-n);this.timer=setTimeout(()=>{if(this.timer=null,this.deps.installedGeneration()===t){if(r>0){this.clearAndArmFaultRetry(r,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 r=n;if(n.kind==="connection"&&this.deps.turnEnds===void 0){const l=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(this.unanswered=l.ok?0:this.unanswered+1,!l.ok){const g=l.waitMs??Math.random()*Math.min(3e5,5e3*2**(this.unanswered-1));return await this.recordPendingProviderFault(t,{...A(E(p)),message:l.reason,retry:{...p.retry,nextAt:new Date(Date.now()+g).toISOString()}}).catch(k=>F({level:"warn",event:"broker.runtime.diagnostic",fields:{message:`fault wait write failed: ${$(k)}`}})),this.clearAndArmFaultRetry(g,e),"rearmed"}r=p}const s=this.deps.turnEnds!==void 0,o=r.retry.attempt??0,c=_e(r.kind),f=o>=c.max?null:P(E(r),Date.now());if(f===null){await this.settleExhausted(t,r);return}if(this.deps.installedGeneration()!==e||this.deps.currentSession()!==t)return;let a,d;const y=await this.deps.turnAdmission.admit(async l=>{const p=(await this.state()).fault;if(this.deps.installedGeneration()!==e||this.deps.currentSession()!==t||t.isStreaming||!this.isActiveAutoFault(p)||p.since!==r.since){l();return}const g=this.sessionId(t);if(g===null){l();return}if(!(await I(this.deps.nodeId,{op:"admit",session_id:g,fault_id:p.fault_id,retry:f.fault.retry})).applied){l();return}const w=r.anchor_entry_id;if(w!==void 0&&(t.sessionManager.getLeafId?.()??null)!==w&&!this.hasProgressPastAnchor(t,w))try{const u=await t.navigateTree(w);if(this.deps.installedGeneration()!==e||this.deps.currentSession()!==t){l();return}u.cancelled||this.deps.reWelcomeAll()}catch(u){F({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`fault retry rewind skipped: ${u instanceof Error?u.message:String(u)}`}})}const h=Z("recovery",s?{attempt:f.attempt}:{attempt:f.attempt,max:f.max},Te(r.kind,s));ie(h,{type:"runtime",kind:"recovery"}),this.deps.turnEnds?.beginRecovery();const D=this.agentStarts;try{await Q.fresh(()=>t.prompt(h,{preflightResult:l}))}catch(u){a={error:u,faultId:p.fault_id,startsBefore:D},oe(u)||(d={code:"model_error",message:`recovery prompt rejected: ${$(u)}`});return}finally{this.deps.turnEnds?.recoveryReturned(d)}return"prompted"});if(a===void 0)return y;const v=await this.settleRejectedRecoveryPrompt(e,t,a);if(v==="stale")throw a.error;return v==="rearmed"?"rearmed":void 0}async settleRejectedRecoveryPrompt(e,t,n){const r=this.sessionId(t);if(r===null)return"stale";const s=m(()=>{if(this.deps.installedGeneration()!==e||this.deps.currentSession()!==t||t.isStreaming||this.agentStarts!==n.startsBefore)throw new _},"assertCurrent"),o=$(n.error),c=oe(n.error);try{let f;return await this.retryWhileDaemonUnreachable("rejected recovery prompt settlement",async()=>{s();const{episode:a}=await this.state();if(s(),a===null||a.state!=="admitted"||a.session_id!==r||a.fault.fault_id!==n.faultId)throw new _;const d=E(a.fault),y=c&&this.deps.turnEnds===void 0?P(d,Date.now()):null,v=y===null?ee(c?d:{...d,kind:"other",message:`recovery prompt rejected: ${o}`}):{...d,retry:{...d.retry,nextAt:y.nextAt}};if(s(),!(await I(this.deps.nodeId,{op:"settle-rejected",session_id:r,fault_id:n.faultId,reopen:y!==null,input:A(v)})).applied)throw new _;f=y?.nextAt},s),f===void 0?(F({level:"warn",event:"broker.runtime.diagnostic",fields:{message:`recovery prompt rejected, ending the retry episode: ${o}`}}),"ended"):(F({level:"warn",event:"broker.runtime.diagnostic",fields:{message:`recovery prompt rejected before any turn started, retrying at ${f}: ${o}`}}),await this.schedule(),"rearmed")}catch(f){if(!(f instanceof _))throw f;return"stale"}}}export{rt as FaultRetry,ae as RUN_TURN_RETRY_WINDOW_MS,Pe as isPrefillRejectionDuringEpisode,Te as retryCardBody,Me as runTurnRetryExpired,le as settledProviderFault,nt as willDaemonRetry};
@@ -26,6 +26,15 @@ export declare function wireHistory(messages: Context['messages']): Context['mes
26
26
  * resolver supplies no level, so a suffix on its model is an exact request's effort and must ride along. */
27
27
  export declare function launchThinkingLevels(model: Model<any>, intent: string | undefined): Promise<ReadonlySet<string>>;
28
28
  export declare function requestBody(model: Model<any>, context: Context, options: ModelsSimpleStreamOptions, intentOverride?: string, launchThinking?: ReadonlySet<string>): Record<string, unknown>;
29
+ export type GatewayAnswer = {
30
+ ok: true;
31
+ } | {
32
+ ok: false;
33
+ waitMs?: number;
34
+ reason: string;
35
+ };
36
+ /** Before a retry, ask this broker's own gateway whether it can serve `model` now (`GET /healthz?model=`); no wait means no answer. */
37
+ export declare function askGateway(model: string): Promise<GatewayAnswer>;
29
38
  /** The real response under a deferred-head framing (`daemon/api/deferred-head.ts`): the magic line, keep-alive
30
39
  * blank lines, one JSON head line, then the body unchanged. Any other response is returned as it is. */
31
40
  export declare function unwrapDeferredHead(response: Response): Promise<Response>;
@@ -1,3 +1,3 @@
1
- var X=Object.defineProperty;var f=(e,t)=>X(e,"name",{value:t,configurable:!0});import{setTimeout as K}from"node:timers/promises";import{createAssistantMessageEventStream as Q,getCurrentSystemPrompt as V,getCurrentTools as Z}from"@earendil-works/pi-ai";import{socketFetch as ee}from"../../../api/node-transport.js";import{DEFER_HEAD_REQUEST_HEADER as te,DEFERRED_HEAD_CONTENT_TYPE as ne,DEFERRED_HEAD_MAGIC as re}from"../../../daemon/api/deferred-head.js";import{apiSocketPath as oe}from"../../canvas/paths.js";import{northlightUnreachable as se}from"../../directory/reach.js";import{currentNodeToken as ie}from"./node-token.js";import{brokerApiUrl as S}from"./daemon-ops.js";import{currentCausedBy as ae}from"./turn-cause.js";import{envModelExact as L,envModelIntent as U,envNodeCwd as de,envProfileId as ce}from"../../../shared/env.js";import{MODEL_CONTEXT_BODY_MAX_BYTES as k}from"../../llm/body-limits.js";import{APP_FAMILY as le,expandModelCandidates as ue,llmModelFor as fe,modelRequestFromConfig as pe}from"../../model-routes.js";import{parseProviderPayment as me,parseProviderRateLimit as he,providerFailureDiagnostic as q}from"../../provider-failure.js";import{UPSTREAM_MODEL_UNAVAILABLE as T}from"../../fault-classifier.js";function Ue(e,t,n){e.checkAuth=async a=>e.getProvider(a)?{type:"api_key"}:void 0,e.getAvailable=async a=>e.getModels(a),e.getAvailableSnapshot=()=>e.getModels(),e.streamSimple=(a,d,s)=>ve(a,d,s,t,n)}f(Ue,"configureBrokerModelRuntime");const ge=300,B="crtr:llm-refusal";class R extends Error{static{f(this,"LlmRefusalError")}retryAt;rateLimit;code;status;payment;constructor(t,n,a,d,s,r){super(t),this.retryAt=n,this.rateLimit=a,this.code=d,this.status=s,this.payment=r}}class v extends Error{static{f(this,"UpstreamModelUnavailableError")}}function I(e,t){const n=e===void 0?"the request body":`the request body (${e} bytes)`;return new Error(`request_too_large: ${n} exceeds the ${t}-byte model request limit; compact the conversation to shrink the context`)}f(I,"contextTooLargeError");function D(e){const t=e.details?.rate_limit;if(!t||typeof t!="object")return;const n=he(t);if(n===void 0)return;const{provider:a,model:d}=t;return typeof a=="string"&&a!==""&&typeof d=="string"&&d!==""?{...n,model:`${a}/${d}`}:n}f(D,"refusalRateLimit");function qe(e){for(const t of e.diagnostics??[]){if(t.type!==B)continue;const n=t.details?.retryAt;if(typeof n=="number"&&Number.isFinite(n)&&n>0)return n}}f(qe,"refusalRetryAt");class H extends Error{static{f(this,"ContentFilteredError")}}function M(e){return me(e.details?.payment)}f(M,"refusalPayment");function W(e){return typeof e=="string"?e:e.map(t=>t.type==="text"?{type:"text",text:t.text}:{type:"image_url",image_url:{url:`data:${t.mimeType};base64,${t.data}`}})}f(W,"wireContent");function ye(e){const t=f(d=>d.role==="assistant"&&(d.stopReason==="error"||d.stopReason==="aborted"),"incomplete"),n=e.some(t)?e.filter(d=>!t(d)):e;let a=n.length;for(;a>0&&n[a-1]?.role==="assistant";)a--;return a===n.length?n:n.slice(0,a)}f(ye,"wireHistory");async function we(e,t){const n=L()?void 0:pe(`${e.provider}/${e.id}`,t,!1);if(n?.kind!=="logical"||n.family===le)return new Set;const a=await ue(n,de(),ce());return new Set(a.flatMap(d=>d.strength===n.strength&&d.providerId===e.provider&&d.modelId===e.id&&d.thinkingLevel!==void 0?[d.thinkingLevel]:[]))}f(we,"launchThinkingLevels");function _e(e,t,n,a,d=new Set){const s=[],r=V(t.messages),i=Z(t.messages);r?s.push({role:"system",content:r}):t.systemPrompt&&s.push({role:"system",content:t.systemPrompt});for(const c of ye(t.messages))c.role==="user"?s.push({role:"user",content:W(c.content)}):c.role==="toolResult"?s.push({role:"tool",content:W(c.content),tool_call_id:c.toolCallId}):c.role==="assistant"&&s.push({role:"assistant",content:c.content.filter(p=>p.type==="text").map(p=>p.text).join("")||null,tool_calls:c.content.filter(p=>p.type==="toolCall").map(p=>({id:p.id,type:"function",function:{name:p.name,arguments:JSON.stringify(p.arguments)}}))});const E=`${e.provider}/${e.id}`,w=a??U();return{model:fe(E,w,L()),model_policy:L()?"exact":"substitute",stream:!0,messages:s,...i.length?{tools:i.map(c=>({type:"function",function:{name:c.name,description:c.description,parameters:c.parameters}}))}:{},...n.reasoning&&!d.has(n.reasoning)?{reasoning_effort:n.reasoning}:{},...n.temperature!==void 0?{temperature:n.temperature}:{},...n.maxTokens!==void 0?{max_tokens:n.maxTokens}:{}}}f(_e,"requestBody");function O(e,t){if(typeof t!="string")return!1;const n=t.indexOf("/");return n<1||n===t.length-1?!1:(e.provider=t.slice(0,n),e.model=t.slice(n+1),!0)}f(O,"applyServedModel");function j(e){if(e.details?.served_model!==void 0)return e.details.served_model;const t=e.details?.rate_limit;return typeof t?.provider=="string"&&typeof t.model=="string"?`${t.provider}/${t.model}`:void 0}f(j,"refusalRoute");function J(e){if(!e||typeof e!="object"||!("error"in e))throw new Error("llm returned an invalid response");const t=e.error;if(!t||typeof t.message!="string")throw new Error("llm returned an invalid refusal");return t}f(J,"parseRefusal");function Y(e){try{return JSON.parse(e)}catch{throw new v(`llm returned a non-JSON answer: ${e.slice(0,120)}`)}}f(Y,"parseAnswer");function z(){const e=S();return e===void 0?"http://localhost/v1/llm":new URL("/v1/llm",e).toString()}f(z,"llmUrl");function xe(){return S()===void 0?ee(oe()):globalThis.fetch}f(xe,"llmFetch");async function Ee(e){if(!e.headers.get("content-type")?.startsWith(ne))return e;if(!e.body)throw new Error("deferred head response has no body");const t=e.body.getReader();let n=new Uint8Array(0),a=!1;for(;;){const d=n.indexOf(10);if(d<0){const{value:c,done:p}=await t.read();if(p)throw new Error("deferred head response ended before its head");const m=new Uint8Array(n.length+c.length);m.set(n),m.set(c,n.length),n=m;continue}const s=new TextDecoder().decode(n.subarray(0,d)).trim();if(n=n.subarray(d+1),!a){if(`${s}
2
- `!==re)throw new Error("deferred head response has no magic line");a=!0;continue}if(s==="")continue;const r=JSON.parse(s),i=new Headers;for(const[c,p]of Object.entries(r.headers))for(const m of Array.isArray(p)?p:[p])i.append(c,m);const E=n,w=new ReadableStream({start(c){E.length>0&&c.enqueue(E)},async pull(c){const{value:p,done:m}=await t.read();m?c.close():c.enqueue(p)},cancel(c){return t.cancel(c)}});return new Response(r.status===204?null:w,{status:r.status,headers:i})}}f(Ee,"unwrapDeferredHead");function be(e){const t=e??ae();return t===void 0?{}:{"crtr-caused-by":t}}f(be,"causedByHeader");function ve(e,t,n={},a,d){const s=Q(),r={role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};return(async()=>{const i=ie();if(!i)throw new Error("llm requires a node token");const E=JSON.stringify(_e(e,t,n,a,await we(e,a??U()))),w=Buffer.byteLength(E);if(w>k)throw I(w,k);let c=0;for(;;){n.signal?.throwIfAborted();const p=await xe()(z(),{method:"POST",headers:{authorization:`Bearer ${i}`,"content-type":"application/json",[te]:"1",...be(d)},body:E,signal:n.signal}).catch(l=>{const o=z();throw S()===void 0||n.signal?.aborted?l:new v(se(l,o).message)}),m=await Ee(p);if(!m.ok){if(m.status===413)throw I(w,k);const l=J(Y(await m.text()));if(l.code==="payload_too_large")throw I(w,k);if(O(r,j(l)),l.retryable!==!0)throw new R(l.message,void 0,D(l),l.code,m.status,M(l));const o=l.retry_after_s;if(typeof o!="number"||!Number.isFinite(o)||o<=0)throw l.code===T?new v(l.message):new Error(l.message);const g=ge-c;if(o>g){const h=Date.now()+o*1e3;throw new R(`${l.message} (retry after ${o}s, at ${new Date(h).toISOString()})`,h,D(l),l.code,m.status,M(l))}await K(o*1e3,void 0,{signal:n.signal}),c+=o;continue}if(!m.body)throw new Error("llm returned no stream");s.push({type:"start",partial:r});const G=m.body.getReader(),$=new TextDecoder;let _="",b="stop",C,N=!1,P=!1;const F=f(l=>{const o=Y(l);if(o.error){const u=J(o);throw O(r,j(u)),u.retryable!==!0?new R(u.message,void 0,D(u),u.code,void 0,M(u)):u.code===T?new v(u.message):new Error(u.message)}if(o.served_model){if(P=!0,o.served_model.indexOf("/")<1)throw new Error("llm returned an invalid served_model");O(r,o.served_model)}const g=o.choices?.[0],h=g?.delta;if(h?.reasoning_content){const u=r.content.findIndex(A=>A.type==="thinking"),y=u<0?{type:"thinking",thinking:""}:r.content[u],x=u<0?r.content.push(y)-1:u;if(u<0&&s.push({type:"thinking_start",contentIndex:x,partial:r}),y.type!=="thinking")throw new Error("invalid thinking block");y.thinking+=h.reasoning_content,s.push({type:"thinking_delta",contentIndex:x,delta:h.reasoning_content,partial:r})}if(h?.content){const u=r.content.findIndex(A=>A.type==="text"),y=u<0?{type:"text",text:""}:r.content[u],x=u<0?r.content.push(y)-1:u;if(u<0&&s.push({type:"text_start",contentIndex:x,partial:r}),y.type!=="text")throw new Error("invalid text block");y.text+=h.content,s.push({type:"text_delta",contentIndex:x,delta:h.content,partial:r})}for(const u of h?.tool_calls??[]){const y={type:"toolCall",id:u.id,name:u.function.name,arguments:JSON.parse(u.function.arguments)},x=r.content.push(y)-1;s.push({type:"toolcall_start",contentIndex:x,partial:r}),s.push({type:"toolcall_end",contentIndex:x,toolCall:y,partial:r})}g?.finish_reason&&(b=g.finish_reason),g?.message?.refusal&&(C=g.message.refusal),o.usage&&(N=!0,r.usage={input:o.usage.prompt_tokens,output:o.usage.completion_tokens,cacheRead:o.usage.cache_read_tokens,cacheWrite:o.usage.cache_write_tokens,totalTokens:o.usage.total_tokens,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:typeof o.usage.usd_equivalent=="number"&&Number.isFinite(o.usage.usd_equivalent)?o.usage.usd_equivalent:0}})},"apply");for(;;){const{value:l,done:o}=await G.read();if(o)break;_+=$.decode(l,{stream:!0});let g;for(;(g=_.indexOf(`
3
- `))>=0;){const h=_.slice(0,g).trim();_=_.slice(g+1),h&&F(h)}}if(_+=$.decode(),_.trim()&&F(_.trim()),!N||!P)throw new Error("llm stream ended without usage or served_model");for(const[l,o]of r.content.entries())o.type==="text"&&s.push({type:"text_end",contentIndex:l,content:o.text,partial:r}),o.type==="thinking"&&s.push({type:"thinking_end",contentIndex:l,content:o.thinking,partial:r});if(b==="content_filter")throw new H(C??"Content filtered");if(!["stop","tool_calls","length"].includes(b))throw new Error(`llm returned unknown finish reason: ${b}`);r.stopReason=b==="tool_calls"?"toolUse":b==="length"?"length":"stop",s.push({type:"done",reason:r.stopReason,message:r}),s.end();return}})().catch(i=>{r.stopReason=n.signal?.aborted?"aborted":"error",r.errorMessage=i instanceof Error?i.message:String(i),i instanceof R&&(r.diagnostics=[{type:B,timestamp:Date.now(),...i.retryAt!==void 0?{details:{retryAt:i.retryAt}}:{}},...i.rateLimit!==void 0||i.code==="cap_exhausted"||i.code==="payment_refused"||i.payment!==void 0?[q({status:i.rateLimit!==void 0?429:i.status??402,...i.code===void 0?{}:{code:i.code},...i.rateLimit===void 0?{}:{ratelimit:i.rateLimit},...i.payment===void 0?{}:{payment:i.payment}})]:[]]),i instanceof v&&(r.diagnostics=[q({status:503,code:T})]),i instanceof H&&r.stopReason==="error"&&(r.rawStopReason="content_filter"),s.push({type:"error",reason:r.stopReason,error:r}),s.end()}),s}f(ve,"streamBrokerModel");export{ge as LLM_BROKER_RETRY_WINDOW_S,B as LLM_REFUSAL_DIAGNOSTIC,Ue as configureBrokerModelRuntime,we as launchThinkingLevels,qe as refusalRetryAt,_e as requestBody,ve as streamBrokerModel,Ee as unwrapDeferredHead,ye as wireHistory};
1
+ var K=Object.defineProperty;var f=(e,t)=>K(e,"name",{value:t,configurable:!0});import{setTimeout as Q}from"node:timers/promises";import{createAssistantMessageEventStream as V,getCurrentSystemPrompt as Z,getCurrentTools as ee}from"@earendil-works/pi-ai";import{socketFetch as te}from"../../../api/node-transport.js";import{DEFER_HEAD_REQUEST_HEADER as ne,DEFERRED_HEAD_CONTENT_TYPE as re,DEFERRED_HEAD_MAGIC as oe}from"../../../daemon/api/deferred-head.js";import{apiSocketPath as se}from"../../canvas/paths.js";import{northlightUnreachable as ae}from"../../directory/reach.js";import{currentNodeToken as ie}from"./node-token.js";import{brokerApiUrl as S}from"./daemon-ops.js";import{currentCausedBy as de}from"./turn-cause.js";import{envModelExact as L,envModelIntent as q,envNodeCwd as ce,envProfileId as le}from"../../../shared/env.js";import{MODEL_CONTEXT_BODY_MAX_BYTES as v}from"../../llm/body-limits.js";import{APP_FAMILY as ue,expandModelCandidates as fe,llmModelFor as pe,modelRequestFromConfig as me}from"../../model-routes.js";import{parseProviderPayment as he,parseProviderRateLimit as ge,providerFailureDiagnostic as B}from"../../provider-failure.js";import{UPSTREAM_MODEL_UNAVAILABLE as I}from"../../fault-classifier.js";function Fe(e,t,n){e.checkAuth=async i=>e.getProvider(i)?{type:"api_key"}:void 0,e.getAvailable=async i=>e.getModels(i),e.getAvailableSnapshot=()=>e.getModels(),e.streamSimple=(i,d,a)=>ke(i,d,a,t,n)}f(Fe,"configureBrokerModelRuntime");const ye=300,H="crtr:llm-refusal";class R extends Error{static{f(this,"LlmRefusalError")}retryAt;rateLimit;code;status;payment;constructor(t,n,i,d,a,r){super(t),this.retryAt=n,this.rateLimit=i,this.code=d,this.status=a,this.payment=r}}class k extends Error{static{f(this,"UpstreamModelUnavailableError")}}function T(e,t){const n=e===void 0?"the request body":`the request body (${e} bytes)`;return new Error(`request_too_large: ${n} exceeds the ${t}-byte model request limit; compact the conversation to shrink the context`)}f(T,"contextTooLargeError");function $(e){const t=e.details?.rate_limit;if(!t||typeof t!="object")return;const n=ge(t);if(n===void 0)return;const{provider:i,model:d}=t;return typeof i=="string"&&i!==""&&typeof d=="string"&&d!==""?{...n,model:`${i}/${d}`}:n}f($,"refusalRateLimit");function qe(e){for(const t of e.diagnostics??[]){if(t.type!==H)continue;const n=t.details?.retryAt;if(typeof n=="number"&&Number.isFinite(n)&&n>0)return n}}f(qe,"refusalRetryAt");class j extends Error{static{f(this,"ContentFilteredError")}}function M(e){return he(e.details?.payment)}f(M,"refusalPayment");function W(e){return typeof e=="string"?e:e.map(t=>t.type==="text"?{type:"text",text:t.text}:{type:"image_url",image_url:{url:`data:${t.mimeType};base64,${t.data}`}})}f(W,"wireContent");function we(e){const t=f(d=>d.role==="assistant"&&(d.stopReason==="error"||d.stopReason==="aborted"),"incomplete"),n=e.some(t)?e.filter(d=>!t(d)):e;let i=n.length;for(;i>0&&n[i-1]?.role==="assistant";)i--;return i===n.length?n:n.slice(0,i)}f(we,"wireHistory");async function _e(e,t){const n=L()?void 0:me(`${e.provider}/${e.id}`,t,!1);if(n?.kind!=="logical"||n.family===ue)return new Set;const i=await fe(n,ce(),le());return new Set(i.flatMap(d=>d.strength===n.strength&&d.providerId===e.provider&&d.modelId===e.id&&d.thinkingLevel!==void 0?[d.thinkingLevel]:[]))}f(_e,"launchThinkingLevels");function xe(e,t,n,i,d=new Set){const a=[],r=Z(t.messages),s=ee(t.messages);r?a.push({role:"system",content:r}):t.systemPrompt&&a.push({role:"system",content:t.systemPrompt});for(const c of we(t.messages))c.role==="user"?a.push({role:"user",content:W(c.content)}):c.role==="toolResult"?a.push({role:"tool",content:W(c.content),tool_call_id:c.toolCallId}):c.role==="assistant"&&a.push({role:"assistant",content:c.content.filter(p=>p.type==="text").map(p=>p.text).join("")||null,tool_calls:c.content.filter(p=>p.type==="toolCall").map(p=>({id:p.id,type:"function",function:{name:p.name,arguments:JSON.stringify(p.arguments)}}))});const b=`${e.provider}/${e.id}`,w=i??q();return{model:pe(b,w,L()),model_policy:L()?"exact":"substitute",stream:!0,messages:a,...s.length?{tools:s.map(c=>({type:"function",function:{name:c.name,description:c.description,parameters:c.parameters}}))}:{},...n.reasoning&&!d.has(n.reasoning)?{reasoning_effort:n.reasoning}:{},...n.temperature!==void 0?{temperature:n.temperature}:{},...n.maxTokens!==void 0?{max_tokens:n.maxTokens}:{}}}f(xe,"requestBody");function D(e,t){if(typeof t!="string")return!1;const n=t.indexOf("/");return n<1||n===t.length-1?!1:(e.provider=t.slice(0,n),e.model=t.slice(n+1),!0)}f(D,"applyServedModel");function J(e){if(e.details?.served_model!==void 0)return e.details.served_model;const t=e.details?.rate_limit;return typeof t?.provider=="string"&&typeof t.model=="string"?`${t.provider}/${t.model}`:void 0}f(J,"refusalRoute");function Y(e){if(!e||typeof e!="object"||!("error"in e))throw new Error("llm returned an invalid response");const t=e.error;if(!t||typeof t.message!="string")throw new Error("llm returned an invalid refusal");return t}f(Y,"parseRefusal");function z(e){try{return JSON.parse(e)}catch{throw new k(`llm returned a non-JSON answer: ${e.slice(0,120)}`)}}f(z,"parseAnswer");function O(){const e=S();return e===void 0?"http://localhost/v1/llm":new URL("/v1/llm",e).toString()}f(O,"llmUrl");function G(){return S()===void 0?te(se()):globalThis.fetch}f(G,"llmFetch");async function Be(e){const t=await G()(O().replace(/\/v1\/llm$/,`/healthz?model=${encodeURIComponent(e)}`),{signal:AbortSignal.timeout(5e3)}).catch(()=>null);if(t?.status===200)return{ok:!0};const n=t?.status===503?(await t.json().catch(()=>null))?.error?.retry_after_s:void 0;return typeof n=="number"?{ok:!1,waitMs:n*1e3,reason:`waiting for ${e}: model unavailable`}:{ok:!1,reason:`waiting for ${e}: gateway not answering`}}f(Be,"askGateway");async function be(e){if(!e.headers.get("content-type")?.startsWith(re))return e;if(!e.body)throw new Error("deferred head response has no body");const t=e.body.getReader();let n=new Uint8Array(0),i=!1;for(;;){const d=n.indexOf(10);if(d<0){const{value:c,done:p}=await t.read();if(p)throw new Error("deferred head response ended before its head");const m=new Uint8Array(n.length+c.length);m.set(n),m.set(c,n.length),n=m;continue}const a=new TextDecoder().decode(n.subarray(0,d)).trim();if(n=n.subarray(d+1),!i){if(`${a}
2
+ `!==oe)throw new Error("deferred head response has no magic line");i=!0;continue}if(a==="")continue;const r=JSON.parse(a),s=new Headers;for(const[c,p]of Object.entries(r.headers))for(const m of Array.isArray(p)?p:[p])s.append(c,m);const b=n,w=new ReadableStream({start(c){b.length>0&&c.enqueue(b)},async pull(c){const{value:p,done:m}=await t.read();m?c.close():c.enqueue(p)},cancel(c){return t.cancel(c)}});return new Response(r.status===204?null:w,{status:r.status,headers:s})}}f(be,"unwrapDeferredHead");function Ee(e){const t=e??de();return t===void 0?{}:{"crtr-caused-by":t}}f(Ee,"causedByHeader");function ke(e,t,n={},i,d){const a=V(),r={role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};return(async()=>{const s=ie();if(!s)throw new Error("llm requires a node token");const b=JSON.stringify(xe(e,t,n,i,await _e(e,i??q()))),w=Buffer.byteLength(b);if(w>v)throw T(w,v);let c=0;for(;;){n.signal?.throwIfAborted();const p=await G()(O(),{method:"POST",headers:{authorization:`Bearer ${s}`,"content-type":"application/json",[ne]:"1",...Ee(d)},body:b,signal:n.signal}).catch(l=>{const o=O();throw S()===void 0||n.signal?.aborted?l:new k(ae(l,o).message)}),m=await be(p);if(!m.ok){if(m.status===413)throw T(w,v);const l=Y(z(await m.text()));if(l.code==="payload_too_large")throw T(w,v);if(D(r,J(l)),l.retryable!==!0)throw new R(l.message,void 0,$(l),l.code,m.status,M(l));const o=l.retry_after_s;if(typeof o!="number"||!Number.isFinite(o)||o<=0)throw l.code===I?new k(l.message,{cause:l.details?.breaker}):new Error(l.message);const g=ye-c;if(o>g){const h=Date.now()+o*1e3;throw new R(`${l.message} (retry after ${o}s, at ${new Date(h).toISOString()})`,h,$(l),l.code,m.status,M(l))}await Q(o*1e3,void 0,{signal:n.signal}),c+=o;continue}if(!m.body)throw new Error("llm returned no stream");a.push({type:"start",partial:r});const X=m.body.getReader(),C=new TextDecoder;let _="",E="stop",N,P=!1,U=!1;const F=f(l=>{const o=z(l);if(o.error){const u=Y(o);throw D(r,J(u)),u.retryable!==!0?new R(u.message,void 0,$(u),u.code,void 0,M(u)):u.code===I?new k(u.message,{cause:u.details?.breaker}):new Error(u.message)}if(o.served_model){if(U=!0,o.served_model.indexOf("/")<1)throw new Error("llm returned an invalid served_model");D(r,o.served_model)}const g=o.choices?.[0],h=g?.delta;if(h?.reasoning_content){const u=r.content.findIndex(A=>A.type==="thinking"),y=u<0?{type:"thinking",thinking:""}:r.content[u],x=u<0?r.content.push(y)-1:u;if(u<0&&a.push({type:"thinking_start",contentIndex:x,partial:r}),y.type!=="thinking")throw new Error("invalid thinking block");y.thinking+=h.reasoning_content,a.push({type:"thinking_delta",contentIndex:x,delta:h.reasoning_content,partial:r})}if(h?.content){const u=r.content.findIndex(A=>A.type==="text"),y=u<0?{type:"text",text:""}:r.content[u],x=u<0?r.content.push(y)-1:u;if(u<0&&a.push({type:"text_start",contentIndex:x,partial:r}),y.type!=="text")throw new Error("invalid text block");y.text+=h.content,a.push({type:"text_delta",contentIndex:x,delta:h.content,partial:r})}for(const u of h?.tool_calls??[]){const y={type:"toolCall",id:u.id,name:u.function.name,arguments:JSON.parse(u.function.arguments)},x=r.content.push(y)-1;a.push({type:"toolcall_start",contentIndex:x,partial:r}),a.push({type:"toolcall_end",contentIndex:x,toolCall:y,partial:r})}g?.finish_reason&&(E=g.finish_reason),g?.message?.refusal&&(N=g.message.refusal),o.usage&&(P=!0,r.usage={input:o.usage.prompt_tokens,output:o.usage.completion_tokens,cacheRead:o.usage.cache_read_tokens,cacheWrite:o.usage.cache_write_tokens,totalTokens:o.usage.total_tokens,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:typeof o.usage.usd_equivalent=="number"&&Number.isFinite(o.usage.usd_equivalent)?o.usage.usd_equivalent:0}})},"apply");for(;;){const{value:l,done:o}=await X.read();if(o)break;_+=C.decode(l,{stream:!0});let g;for(;(g=_.indexOf(`
3
+ `))>=0;){const h=_.slice(0,g).trim();_=_.slice(g+1),h&&F(h)}}if(_+=C.decode(),_.trim()&&F(_.trim()),!P||!U)throw new Error("llm stream ended without usage or served_model");for(const[l,o]of r.content.entries())o.type==="text"&&a.push({type:"text_end",contentIndex:l,content:o.text,partial:r}),o.type==="thinking"&&a.push({type:"thinking_end",contentIndex:l,content:o.thinking,partial:r});if(E==="content_filter")throw new j(N??"Content filtered");if(!["stop","tool_calls","length"].includes(E))throw new Error(`llm returned unknown finish reason: ${E}`);r.stopReason=E==="tool_calls"?"toolUse":E==="length"?"length":"stop",a.push({type:"done",reason:r.stopReason,message:r}),a.end();return}})().catch(s=>{r.stopReason=n.signal?.aborted?"aborted":"error",r.errorMessage=s instanceof Error?s.message:String(s),s instanceof R&&(r.diagnostics=[{type:H,timestamp:Date.now(),...s.retryAt!==void 0?{details:{retryAt:s.retryAt}}:{}},...s.rateLimit!==void 0||s.code==="cap_exhausted"||s.code==="payment_refused"||s.payment!==void 0?[B({status:s.rateLimit!==void 0?429:s.status??402,...s.code===void 0?{}:{code:s.code},...s.rateLimit===void 0?{}:{ratelimit:s.rateLimit},...s.payment===void 0?{}:{payment:s.payment}})]:[]]),s instanceof k&&(r.diagnostics=[B({status:503,code:I,...s.cause===void 0?{}:{body:"breaker"}})]),s instanceof j&&r.stopReason==="error"&&(r.rawStopReason="content_filter"),a.push({type:"error",reason:r.stopReason,error:r}),a.end()}),a}f(ke,"streamBrokerModel");export{ye as LLM_BROKER_RETRY_WINDOW_S,H as LLM_REFUSAL_DIAGNOSTIC,Be as askGateway,Fe as configureBrokerModelRuntime,_e as launchThinkingLevels,qe as refusalRetryAt,xe as requestBody,ke as streamBrokerModel,be as unwrapDeferredHead,we as wireHistory};