@north-light/cli 0.3.715 → 0.3.717

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,9 +1,9 @@
1
- var i=Object.defineProperty;var e=(a,t)=>i(a,"name",{value:t,configurable:!0});import{openDb as n}from"../../../core/canvas/db.js";import{apiSocketPath as c}from"../../../core/canvas/paths.js";import{currentVersion as u}from"../../../core/self-update.js";import{API_VERSION as d}from"../../../api/index.js";import{DEFAULT_INTERVAL_MS as p}from"../../supervise-cadence.js";import{isPidPresent as l}from"../../../core/canvas/pid.js";import{boundDaemonControl as r}from"../../control.js";import{dueReport as _}from"../../due.js";import{runtimeReadiness as m}from"../../readiness.js";import{processGeneration as h}from"../../../commands/sys/shared.js";const w=p;async function s(){try{return await(await n()).prepare("SELECT 1 FROM nodes LIMIT 1").get(),!0}catch{return!1}}e(s,"canvasAccessible");async function f(){const a={},t=await(await n()).prepare(`
1
+ var c=Object.defineProperty;var a=(t,e)=>c(t,"name",{value:e,configurable:!0});import{openDb as o}from"../../../core/canvas/db.js";import{apiSocketPath as d}from"../../../core/canvas/paths.js";import{currentVersion as l}from"../../../core/self-update.js";import{API_VERSION as p}from"../../../api/index.js";import{DEFAULT_INTERVAL_MS as _}from"../../supervise-cadence.js";import{isPidPresent as m}from"../../../core/canvas/pid.js";import{boundDaemonControl as u}from"../../control.js";import{dueReport as f}from"../../due.js";import{runtimeReadiness as h}from"../../readiness.js";import{processGeneration as y}from"../../../commands/sys/shared.js";import{refusal as w}from"../../../core/llm/breaker.js";const b=_;async function s(){try{return await(await o()).prepare("SELECT 1 FROM nodes LIMIT 1").get(),!0}catch{return!1}}a(s,"canvasAccessible");async function E(){const t={},e=await(await o()).prepare(`
2
2
  SELECT status, COUNT(*) AS count
3
3
  FROM node_rows
4
4
  WHERE node_id NOT IN (SELECT node_id FROM warm_pool)
5
5
  GROUP BY status
6
- `).all();for(const o of t)a[o.status]=o.count;return a}e(f,"nodeCounts");async function y(){return(await(await n()).prepare(`
6
+ `).all();for(const r of e)t[r.status]=r.count;return t}a(E,"nodeCounts");async function T(){return(await(await o()).prepare(`
7
7
  SELECT pi_pid
8
8
  FROM node_rows
9
9
  WHERE node_id NOT IN (SELECT node_id FROM warm_pool)
@@ -11,4 +11,4 @@ var i=Object.defineProperty;var e=(a,t)=>i(a,"name",{value:t,configurable:!0});i
11
11
  AND pi_pid IS NOT NULL
12
12
  AND turn_open_at IS NOT NULL
13
13
  AND turn_closed_at IS NULL
14
- `).all()).filter(t=>l(t.pi_pid)).length}e(y,"busyNodeCount");async function E(){const a=await s(),t=r()?.startupBlock()??null,o={ok:a&&t===null,daemon_up:!0,store_accessible:a,brokers_reconciled:t===null,startup_phase:t?.phase??"ready",...t===null?{}:{startup_blocked:t.message}};return{status:o.ok?200:503,body:o}}e(E,"handleHealthz");async function T(){const a=await m();return{status:a.ready?200:503,body:a}}e(T,"handleReady");async function b(a){if(!await s())throw{status:503,code:"store_unavailable",message:"canvas store is inaccessible"};return{status:200,body:{daemon_pid:process.pid,tick_interval_ms:w,node_counts:await f(),busy_node_count:await y(),listeners:{socket_path:c(),tcp:a()},runtime_version:u(),generation_id:h()?.id??null,api_version:d,startup_phase:r()?.startupBlock()?.phase??"ready"}}}e(b,"handleStatus");async function N(){if(!await s())throw{status:503,code:"store_unavailable",message:"canvas store is inaccessible"};return{status:200,body:await _()}}e(N,"handleDue");function g(a){return[{method:"GET",pattern:"/healthz",handler:e(async t=>await E(),"handler")},{method:"GET",pattern:"/v1/ready",handler:e(async t=>await T(),"handler")},{method:"GET",pattern:"/v1/status",handler:e(async t=>await b(a),"handler")},{method:"GET",pattern:"/v1/due",handler:e(async t=>await N(),"handler")}]}e(g,"healthRoutes");export{g as healthRoutes};
14
+ `).all()).filter(e=>m(e.pi_pid)).length}a(T,"busyNodeCount");async function N(t){const e=t===null?null:w(t);if(e!==null)return{status:503,headers:{"Retry-After":String(e)},body:{error:{code:"upstream_model_unavailable",message:`${t} is unavailable`,retryable:!0,retry_after_s:e}}};const r=await s(),n=u()?.startupBlock()??null,i={ok:r&&n===null,daemon_up:!0,store_accessible:r,brokers_reconciled:n===null,startup_phase:n?.phase??"ready",...n===null?{}:{startup_blocked:n.message}};return{status:i.ok?200:503,body:i}}a(N,"handleHealthz");async function R(){const t=await h();return{status:t.ready?200:503,body:t}}a(R,"handleReady");async function L(t){if(!await s())throw{status:503,code:"store_unavailable",message:"canvas store is inaccessible"};return{status:200,body:{daemon_pid:process.pid,tick_interval_ms:b,node_counts:await E(),busy_node_count:await T(),listeners:{socket_path:d(),tcp:t()},runtime_version:l(),generation_id:y()?.id??null,api_version:p,startup_phase:u()?.startupBlock()?.phase??"ready"}}}a(L,"handleStatus");async function S(){if(!await s())throw{status:503,code:"store_unavailable",message:"canvas store is inaccessible"};return{status:200,body:await f()}}a(S,"handleDue");function P(t){return[{method:"GET",pattern:"/healthz",handler:a(async e=>await N(e.query.get("model")),"handler")},{method:"GET",pattern:"/v1/ready",handler:a(async e=>await R(),"handler")},{method:"GET",pattern:"/v1/status",handler:a(async e=>await L(t),"handler")},{method:"GET",pattern:"/v1/due",handler:a(async e=>await S(),"handler")}]}a(P,"healthRoutes");export{P as healthRoutes};
@@ -1,3 +1,3 @@
1
- var S=Object.defineProperty;var s=(t,e)=>S(t,"name",{value:e,configurable:!0});import{randomUUID as g}from"node:crypto";import{MODEL_CONTEXT_BODY_MAX_BYTES as k}from"../../../core/llm/body-limits.js";import{llmCallerOf as h,parseLlmRequest as O,runLlm as T}from"../../../core/llm/run.js";import{RunError as u}from"../../../core/runs/operations.js";import{errorCodes as q}from"../../../api/error-codes.js";import{getNode as x}from"../../../core/canvas/canvas.js";import{emitEvent as R}from"../../../core/events/emit.js";import{boundedCause as I}from"../map.js";import{socketPrincipal as l}from"../server.js";import{activeGrant as N,activeGrantForApp as w,grantFor as G,grantsSource as b,payerOfGrant as L}from"../../../core/grants/mirror.js";import{parseUsageMonth as M,usageFor as $}from"../../../core/ledger/index.js";function v(t,e){if(e==="broker"||e==="person"||e===void 0||!t||typeof t!="object"||Array.isArray(t)||!("rate_limit"in t))return t;const{rate_limit:a,...n}=t;return n}s(v,"operatorDetails");const j="app:terminal";async function A(t,e){if(t?.class==="broker")return{grantee:t.app,sub:t.sub,node:t.node,run:e?.run_id??t.run};if(t?.class==="app"){const a=await b();if(a===null||a==="local")return{grantee:t.app};let n;try{n=await w(t.app)}catch{throw new u(401,"grant_revoked",`${t.app} has several active grants; a local token cannot name which user's cap applies`)}if(!n)throw new u(401,"grant_revoked",`${t.app} has no active grant`);return{grantee:t.app,sub:n.sub}}return{grantee:j}}s(A,"spendTarget");async function B(t){if(t?.class==="broker"){if(t.app==="app:terminal")return;const e=t.grant?await N(t.grant):await G(t.app,t.sub);if(!e&&await L(t.grant)==="app")throw new u(401,"grant_revoked",`${t.app}'s app-paid grant is no longer active`);return h(e&&e.grantee===t.app?e:null)}if(t?.class==="app"){const e=await b();return e===null||e==="local"?void 0:h(await w(t.app))}}s(B,"llmCaller");function E(t){const e=q[t.code];return e?e.type:t.status===429?"rate_limit_error":t.status<500?"invalid_request_error":"server_error"}s(E,"errorType");function C(t){if(t.code==="payment_refused"||t.code==="all_routes_exhausted"){const a=t.details?.payment;return a===void 0?{}:{payment:a}}if(t.code!=="cap_exhausted")return{};const e=t.details??{};return{...e.payment!==void 0?{payment:e.payment}:{},...e.limit!==void 0?{limit:e.limit}:{},...typeof e.usd=="number"?{usd:e.usd}:{},...typeof e.spend_cap=="number"?{spend_cap:e.spend_cap}:{},...typeof e.usd_equivalent=="number"?{usd_equivalent:e.usd_equivalent}:{},...typeof e.reset_at=="string"?{reset_at:e.reset_at}:{},...typeof e.user_action=="string"?{user_action:e.user_action}:{}}}s(C,"capFields");const W=[{method:"POST",pattern:"/v1/llm",scope:"crtr:llm",maxBodyBytes:k,handler:s(async({body:t,res:e,req:a,causedBy:n})=>{const f=g();e.setHeader("Request-Id",f);const y=new AbortController,_=s(()=>y.abort(),"abort");e.on("close",_);let p;try{const o=O(t),r=l(a),d=r?.class==="broker"?await x(r.node):null;if(r?.class==="broker"&&!d)throw new u(401,"unauthorized","node not found");const i={...await A(r,d??void 0),request:f},m=await T(o,y.signal,o.stream?c=>{typeof c.served_model=="string"&&(p=c.served_model),e.headersSent||e.writeHead(200,{"content-type":"application/x-ndjson; charset=utf-8","cache-control":"no-cache"}),e.write(`${JSON.stringify(c)}
2
- `)}:void 0,d?{cwd:d.cwd,profileId:d.profile_id??null}:void 0,i,await B(r),n);return o.stream?(e.headersSent||e.writeHead(200,{"content-type":"application/x-ndjson; charset=utf-8","cache-control":"no-cache"}),e.end(),{status:200}):{status:200,body:m.completion}}catch(o){o instanceof u||R({event:"api.request.failed",level:"error",error:o instanceof Error?o:new Error(String(o)),...l(a)?.class==="broker"?{node_id:l(a).node}:{},fields:{method:"POST",path:"/v1/llm"}});const r=o instanceof u?o:new u(503,"upstream_model_unavailable",I(o));if(e.headersSent){const m=r.details&&typeof r.details=="object"&&!Array.isArray(r.details)?r.details:{},c=v(p!==void 0&&typeof m.served_model!="string"?{...m,served_model:p}:r.details,l(a)?.class);return e.end(`${JSON.stringify({error:{code:r.code,message:r.message,...c===void 0?{}:{details:c},type:"server_error",origin:"runtime",retryable:r.retryable,request_id:f}})}
3
- `),{status:200}}const d=v(r.details,l(a)?.class),i=r.code==="all_routes_exhausted"?r.details.retry_after_s:void 0;return i!==void 0&&e.setHeader("Retry-After",String(i)),{status:r.status,body:{error:{code:r.code,message:r.message,...d===void 0?{}:{details:d},type:E(r),...r.param?{param:r.param}:{},origin:"runtime",retryable:r.retryable,request_id:f,...i!==void 0?{retry_after_s:i}:{},...C(r)}}}}finally{e.off("close",_)}},"handler")},{method:"GET",pattern:"/v1/usage",handler:s(async({req:t})=>{const e=g(),a={"Request-Id":e};try{const n=await A(l(t));return{status:200,headers:a,body:await $(n.grantee,M(new URL(t.url??"/","http://runtime.local").searchParams.get("month")))}}catch(n){if(!(n instanceof u))throw n;return{status:n.status,headers:a,body:{error:{code:n.code,message:n.message,type:E(n),...n.param?{param:n.param}:{},origin:"runtime",retryable:!1,request_id:e}}}}},"handler")}];export{C as capFields,W as llmRoutes,A as spendTarget};
1
+ var R=Object.defineProperty;var d=(t,e)=>R(t,"name",{value:e,configurable:!0});import{randomUUID as v}from"node:crypto";import{MODEL_CONTEXT_BODY_MAX_BYTES as T}from"../../../core/llm/body-limits.js";import{llmCallerOf as k,parseLlmRequest as x,runLlm as I}from"../../../core/llm/run.js";import{RunError as i}from"../../../core/runs/operations.js";import{errorCodes as N}from"../../../api/error-codes.js";import{getNode as $}from"../../../core/canvas/canvas.js";import{emitEvent as G}from"../../../core/events/emit.js";import{boundedCause as H}from"../map.js";import{socketPrincipal as m}from"../server.js";import{activeGrant as L,activeGrantForApp as A,grantFor as M,grantsSource as S,payerOfGrant as j}from"../../../core/grants/mirror.js";import{parseUsageMonth as B,usageFor as C}from"../../../core/ledger/index.js";import{admit as D}from"../../../core/llm/breaker.js";function E(t,e){if(e==="broker"||e==="person"||e===void 0||!t||typeof t!="object"||Array.isArray(t)||!("rate_limit"in t))return t;const{rate_limit:n,...a}=t;return a}d(E,"operatorDetails");const F="app:terminal";async function q(t,e){if(t?.class==="broker")return{grantee:t.app,sub:t.sub,node:t.node,run:e?.run_id??t.run};if(t?.class==="app"){const n=await S();if(n===null||n==="local")return{grantee:t.app};let a;try{a=await A(t.app)}catch{throw new i(401,"grant_revoked",`${t.app} has several active grants; a local token cannot name which user's cap applies`)}if(!a)throw new i(401,"grant_revoked",`${t.app} has no active grant`);return{grantee:t.app,sub:a.sub}}return{grantee:F}}d(q,"spendTarget");async function P(t){if(t?.class==="broker"){if(t.app==="app:terminal")return;const e=t.grant?await L(t.grant):await M(t.app,t.sub);if(!e&&await j(t.grant)==="app")throw new i(401,"grant_revoked",`${t.app}'s app-paid grant is no longer active`);return k(e&&e.grantee===t.app?e:null)}if(t?.class==="app"){const e=await S();return e===null||e==="local"?void 0:k(await A(t.app))}}d(P,"llmCaller");function O(t){const e=N[t.code];return e?e.type:t.status===429?"rate_limit_error":t.status<500?"invalid_request_error":"server_error"}d(O,"errorType");function U(t){if(t.code==="payment_refused"||t.code==="all_routes_exhausted"){const n=t.details?.payment;return n===void 0?{}:{payment:n}}if(t.code!=="cap_exhausted")return{};const e=t.details??{};return{...e.payment!==void 0?{payment:e.payment}:{},...e.limit!==void 0?{limit:e.limit}:{},...typeof e.usd=="number"?{usd:e.usd}:{},...typeof e.spend_cap=="number"?{spend_cap:e.spend_cap}:{},...typeof e.usd_equivalent=="number"?{usd_equivalent:e.usd_equivalent}:{},...typeof e.reset_at=="string"?{reset_at:e.reset_at}:{},...typeof e.user_action=="string"?{user_action:e.user_action}:{}}}d(U,"capFields");const ne=[{method:"POST",pattern:"/v1/llm",scope:"crtr:llm",maxBodyBytes:T,handler:d(async({body:t,res:e,req:n,causedBy:a})=>{const f=v();e.setHeader("Request-Id",f);const p=new AbortController,h=d(()=>p.abort(),"abort");e.on("close",h);let g,b,y="none",w=!1;try{const o=x(t),s=o.model===void 0?void 0:D(o.model);if(typeof s=="number")return e.setHeader("Retry-After",String(s)),{status:503,body:{error:{code:"upstream_model_unavailable",message:`${o.model} is unavailable: the gateway's breaker is open`,details:{breaker:"open"},type:"server_error",origin:"runtime",retryable:!0,request_id:f}}};b=s;const r=m(n),u=r?.class==="broker"?await $(r.node):null;if(r?.class==="broker"&&!u)throw new i(401,"unauthorized","node not found");const l={...await q(r,u??void 0),request:f};w=!0;const _=await I(o,p.signal,o.stream?c=>{typeof c.served_model=="string"&&(g=c.served_model),e.headersSent||e.writeHead(200,{"content-type":"application/x-ndjson; charset=utf-8","cache-control":"no-cache"}),e.write(`${JSON.stringify(c)}
2
+ `)}:void 0,u?{cwd:u.cwd,profileId:u.profile_id??null}:void 0,l,await P(r),a);return y=p.signal.aborted?"none":"ok",o.stream?(e.headersSent||e.writeHead(200,{"content-type":"application/x-ndjson; charset=utf-8","cache-control":"no-cache"}),e.end(),{status:200}):{status:200,body:_.completion}}catch(o){o instanceof i||G({event:"api.request.failed",level:"error",error:o instanceof Error?o:new Error(String(o)),...m(n)?.class==="broker"?{node_id:m(n).node}:{},fields:{method:"POST",path:"/v1/llm"}});const s=o instanceof i?o:new i(503,"upstream_model_unavailable",H(o));w&&s.code==="upstream_model_unavailable"&&!p.signal.aborted&&(y="fail");const r=y==="fail"&&b?.test?new i(503,s.code,s.message,s.param,{...s.details,breaker:"test"}):s;if(e.headersSent){const _=r.details&&typeof r.details=="object"&&!Array.isArray(r.details)?r.details:{},c=E(g!==void 0&&typeof _.served_model!="string"?{..._,served_model:g}:r.details,m(n)?.class);return e.end(`${JSON.stringify({error:{code:r.code,message:r.message,...c===void 0?{}:{details:c},type:"server_error",origin:"runtime",retryable:r.retryable,request_id:f}})}
3
+ `),{status:200}}const u=E(r.details,m(n)?.class),l=r.code==="all_routes_exhausted"?r.details.retry_after_s:void 0;return l!==void 0&&e.setHeader("Retry-After",String(l)),{status:r.status,body:{error:{code:r.code,message:r.message,...u===void 0?{}:{details:u},type:O(r),...r.param?{param:r.param}:{},origin:"runtime",retryable:r.retryable,request_id:f,...l!==void 0?{retry_after_s:l}:{},...U(r)}}}}finally{e.off("close",h),b?.settle(y)}},"handler")},{method:"GET",pattern:"/v1/usage",handler:d(async({req:t})=>{const e=v(),n={"Request-Id":e};try{const a=await q(m(t));return{status:200,headers:n,body:await C(a.grantee,B(new URL(t.url??"/","http://runtime.local").searchParams.get("month")))}}catch(a){if(!(a instanceof i))throw a;return{status:a.status,headers:n,body:{error:{code:a.code,message:a.message,type:O(a),...a.param?{param:a.param}:{},origin:"runtime",retryable:!1,request_id:e}}}}},"handler")}];export{U as capFields,ne as llmRoutes,q as spendTarget};
@@ -3,21 +3,19 @@ import type { FleetRegistry } from '../../core/runtime/fleet.js';
3
3
  import type { DetachedWorkLifecycle } from './broker-supervision.js';
4
4
  /** How long past its due time a pending retry may sit before the daemon
5
5
  * concludes the broker's timer is gone. A live timer fires at the due time and
6
- * finishes within seconds (network probe 3s, rewind, one admit mutation), and
6
+ * finishes within seconds (gateway question 5s, rewind, one admit mutation), and
7
7
  * the connection ladder caps its delay at 60s, so two minutes clears every
8
8
  * in-flight attempt, a tick of jitter, and a broker waking from system sleep,
9
9
  * while still resuming a stranded node without a person noticing the wait. It
10
10
  * doubles as the minimum gap between two nudges of the same fault. */
11
11
  export declare const FAULT_RETRY_STALE_GRACE_MS: number;
12
- /** The reconciler scans at most this often: its probe is a network call and a
13
- * stranded retry is not urgent to the second. */
12
+ /** The reconciler scans at most this often: a stranded retry is not urgent to the second. */
14
13
  export declare const FAULT_RETRY_SCAN_INTERVAL_MS = 15000;
15
14
  export interface FaultRetryBackstopContext {
16
15
  fleet: Pick<FleetRegistry, 'has'>;
17
16
  lifecycle: DetachedWorkLifecycle;
18
17
  }
19
18
  export interface FaultRetryBackstopDeps {
20
- probeOnline?: () => Promise<boolean>;
21
19
  list?: () => Promise<PendingProviderRetry[]>;
22
20
  busy?: (nodeId: string) => Promise<boolean>;
23
21
  }
@@ -1 +1 @@
1
- var y=Object.defineProperty;var l=(a,t)=>y(a,"name",{value:t,configurable:!0});import{filterAsync as h}from"../../core/async-array.js";import{openDb as A,withCanvasWrite as b}from"../../core/canvas/db.js";import{getNode as I}from"../../core/canvas/canvas.js";import{liveExecutionForNode as k}from"../../core/canvas/executions.js";import{claimFaultNudge as v,listPendingProviderRetries as g,readLiveTurn as E}from"../../core/canvas/recovery.js";import{probeOnline as R}from"../../core/runtime/connectivity.js";import{nextFaultRetry as N}from"../../core/runtime/fault-recovery.js";import{emitEvent as d}from"../../core/events/emit.js";import{operationIdContext as p}from"../../core/events/operation-id.js";import{isSafeNodeId as m}from"../../core/canvas/paths.js";import{runThrottledLane as L}from"./throttled-lane.js";import{asNodePerson as S}from"./node-lifecycle/node-person.js";import{wakeResident as T}from"./node-lifecycle/remote-wake.js";const u=2*6e4,F=15e3;function _(a){const{fault:t}=a;if(t.retry.nextAt!==void 0){const i=Date.parse(t.retry.nextAt);return Number.isFinite(i)?i:null}const n=Date.parse(a.updatedAt),o=N(t,n);return Number.isFinite(n)&&o!==null?n+o.delayMs:null}l(_,"dueAtMs");const x=6e4,C="fault-retry-backstop";class J{static{l(this,"FaultRetryBackstopReconciler")}deps;constructor(t={}){this.deps=t}run(t,n){if(!n.lifecycle.acceptsDetachedWork())return Promise.resolve();const o=L(C,"",t,F,x,()=>this.scan(t,n)).then(()=>{}).catch(i=>{p.fresh(()=>{d({level:"warn",event:"fault_retry_backstop.scan_failed",error:i})})});return n.lifecycle.registerDetached(o),o}async scan(t,n){const o=await(this.deps.list??g)(),i=this.deps.busy??(async e=>(await E(e))?.busy===!0),c=await h(o,async e=>{if(!await n.fleet.has(e.nodeId)||await i(e.nodeId))return!1;const r=_(e);return r===null||t<r+u?!1:e.nudgedAt===null||t-Date.parse(e.nudgedAt)>=u});if(c.length===0)return;let f;for(const e of c){if(e.fault.kind==="connection"&&(f??=await(this.deps.probeOnline??(()=>R()))(),!f)||!await n.fleet.has(e.nodeId)||await i(e.nodeId)||!await b(async()=>await v(e.fault.faultId,t,u)))continue;const r=await k(e.nodeId),s=r!==null&&r.runner!=="process"&&r.state==="running"?await I(e.nodeId):null;(r===null||s===null?"woken":await S({node_id:s.node_id,sub:s.sub??null,profile_id:s.profile_id??null},()=>T(r)).catch(w=>(d({level:"warn",event:"fault_retry_backstop.wake_failed",...m(e.nodeId)?{node_id:e.nodeId}:{},error:w}),null)))!=="lost"&&(await(await A()).prepare("SELECT pg_notify(?, ?)").get("crtr_signal",`fault_retry:${e.nodeId}`),p.fresh(()=>{d({level:"info",event:"fault_retry_backstop.nudged",...m(e.nodeId)?{node_id:e.nodeId}:{},fields:{kind:e.fault.kind,since:e.fault.since,overdue_ms:t-(_(e)??t)}})}))}}}export{F as FAULT_RETRY_SCAN_INTERVAL_MS,u as FAULT_RETRY_STALE_GRACE_MS,J as FaultRetryBackstopReconciler,_ as dueAtMs};
1
+ var y=Object.defineProperty;var d=(i,t)=>y(i,"name",{value:t,configurable:!0});import{filterAsync as w}from"../../core/async-array.js";import{openDb as h,withCanvasWrite as A}from"../../core/canvas/db.js";import{getNode as I}from"../../core/canvas/canvas.js";import{liveExecutionForNode as k}from"../../core/canvas/executions.js";import{claimFaultNudge as v,listPendingProviderRetries as b,readLiveTurn as g}from"../../core/canvas/recovery.js";import{nextFaultRetry as E}from"../../core/runtime/fault-recovery.js";import{emitEvent as l}from"../../core/events/emit.js";import{operationIdContext as f}from"../../core/events/operation-id.js";import{isSafeNodeId as p}from"../../core/canvas/paths.js";import{runThrottledLane as N}from"./throttled-lane.js";import{asNodePerson as R}from"./node-lifecycle/node-person.js";import{wakeResident as L}from"./node-lifecycle/remote-wake.js";const u=2*6e4,S=15e3;function m(i){const{fault:t}=i;if(t.retry.nextAt!==void 0){const a=Date.parse(t.retry.nextAt);return Number.isFinite(a)?a:null}const n=Date.parse(i.updatedAt),o=E(t,n);return Number.isFinite(n)&&o!==null?n+o.delayMs:null}d(m,"dueAtMs");const T=6e4,F="fault-retry-backstop";class z{static{d(this,"FaultRetryBackstopReconciler")}deps;constructor(t={}){this.deps=t}run(t,n){if(!n.lifecycle.acceptsDetachedWork())return Promise.resolve();const o=N(F,"",t,S,T,()=>this.scan(t,n)).then(()=>{}).catch(a=>{f.fresh(()=>{l({level:"warn",event:"fault_retry_backstop.scan_failed",error:a})})});return n.lifecycle.registerDetached(o),o}async scan(t,n){const o=await(this.deps.list??b)(),a=this.deps.busy??(async e=>(await g(e))?.busy===!0),c=await w(o,async e=>{if(!await n.fleet.has(e.nodeId)||await a(e.nodeId))return!1;const r=m(e);return r===null||t<r+u?!1:e.nudgedAt===null||t-Date.parse(e.nudgedAt)>=u});if(c.length!==0)for(const e of c){if(!await n.fleet.has(e.nodeId)||await a(e.nodeId)||!await A(async()=>await v(e.fault.faultId,t,u)))continue;const r=await k(e.nodeId),s=r!==null&&r.runner!=="process"&&r.state==="running"?await I(e.nodeId):null;(r===null||s===null?"woken":await R({node_id:s.node_id,sub:s.sub??null,profile_id:s.profile_id??null},()=>L(r)).catch(_=>(l({level:"warn",event:"fault_retry_backstop.wake_failed",...p(e.nodeId)?{node_id:e.nodeId}:{},error:_}),null)))!=="lost"&&(await(await h()).prepare("SELECT pg_notify(?, ?)").get("crtr_signal",`fault_retry:${e.nodeId}`),f.fresh(()=>{l({level:"info",event:"fault_retry_backstop.nudged",...p(e.nodeId)?{node_id:e.nodeId}:{},fields:{kind:e.fault.kind,since:e.fault.since,overdue_ms:t-(m(e)??t)}})}))}}}export{S as FAULT_RETRY_SCAN_INTERVAL_MS,u as FAULT_RETRY_STALE_GRACE_MS,z as FaultRetryBackstopReconciler,m as dueAtMs};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.715",
3
+ "version": "0.3.717",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -158,8 +158,8 @@
158
158
  },
159
159
  "license": "UNLICENSED",
160
160
  "dependencies": {
161
- "@north-light/identity": "0.3.715",
162
- "@north-light/plugin": "0.3.715",
161
+ "@north-light/identity": "0.3.717",
162
+ "@north-light/plugin": "0.3.717",
163
163
  "@earendil-works/chord": "1.5.2",
164
164
  "@earendil-works/pi-agent-core": "1.5.2",
165
165
  "@earendil-works/pi-ai": "1.5.2",
@@ -627,6 +627,16 @@ onConnected) {
627
627
  // The release selected on this machine, never the daemon's: a signed-in viewer's status call is answered by the server.
628
628
  const selected = selectedGeneration().generation?.id;
629
629
  if (mine !== undefined && selected !== undefined && selected !== mine && selected !== restartedFor && !lifecycle.isTornDown()) {
630
+ // The new process reads the account's settings before it paints and exits when it cannot. A welcome right after the computer
631
+ // wakes can come before its network does, so make that request first and leave the restart to a later welcome if it fails.
632
+ try {
633
+ await cliClient({ timeoutMs: 5_000 }).getSettings();
634
+ }
635
+ catch {
636
+ return;
637
+ }
638
+ if (lifecycle.isTornDown())
639
+ return;
630
640
  restartViewer({ CRTR_ATTACH_RESTARTED_FOR: selected });
631
641
  }
632
642
  };
@@ -259,11 +259,15 @@ export async function dropStubRows(input) {
259
259
  dropped[table] = (dropped[table] ?? 0) + n; };
260
260
  await db.exec(`CREATE TABLE ${S('_dropped')} (tbl text NOT NULL, key text NOT NULL, PRIMARY KEY (tbl, key))`);
261
261
  // Stub objects are the ones another machine owns (`home_machine`); they and their keyed rows are not copied.
262
- const stubs = `(SELECT id FROM ${S('objects')} WHERE home_machine IS NOT NULL)`;
263
- await run(db, `INSERT INTO ${S('_dropped')} SELECT 'objects', id FROM ${S('objects')} WHERE home_machine IS NOT NULL`);
262
+ // A staged object whose (owner, name) a live target object already holds under another id (the `objects_named` unique index) is dropped too: the target's copy is kept.
263
+ const named = catalog.uniqueKeys.find((u) => u.table === 'objects' && u.name === 'objects_named');
264
+ if (named === undefined || named.predicate === null)
265
+ throw new ImportLaneError('drop', 'import_failed', 'the target has no objects_named unique index with a predicate');
266
+ const collides = `s.id IN (SELECT s2.id FROM (SELECT * FROM ${S('objects')} WHERE ${named.predicate}) s2 JOIN (SELECT * FROM ${sq(target, 'objects')} WHERE ${named.predicate}) t ON t.owner = s2.owner AND t.name = s2.name AND t.id <> s2.id)`;
267
+ await run(db, `INSERT INTO ${S('_dropped')} SELECT 'objects', s.id FROM ${S('objects')} s WHERE s.home_machine IS NOT NULL OR ${collides}`);
264
268
  for (const [table, column] of Object.entries(OBJECT_KEYED))
265
- count(table, await run(db, `DELETE FROM ${S(table)} WHERE ${column} IN ${stubs}`));
266
- count('objects', await run(db, `DELETE FROM ${S('objects')} WHERE home_machine IS NOT NULL`));
269
+ count(table, await run(db, `DELETE FROM ${S(table)} WHERE ${column} IN (SELECT key FROM ${S('_dropped')} WHERE tbl = 'objects')`));
270
+ count('objects', await run(db, `DELETE FROM ${S('objects')} WHERE id IN (SELECT key FROM ${S('_dropped')} WHERE tbl = 'objects')`));
267
271
  // The columns that hold an object id (foreign keys onto `objects`, then the ones without one: `OBJECT_ID_COLUMNS`), the same list rewrite 2 remaps. A row naming a dropped object in
268
272
  // one of them is dropped too; ordinary text (a title, a body) that happens to equal an id is never touched. `messages` keeps the ids of stubs (I16).
269
273
  const textColumns = new Map();
@@ -197,6 +197,14 @@ function llmUrl() {
197
197
  function llmFetch() {
198
198
  return brokerApiUrl() === undefined ? socketFetch(apiSocketPath()) : globalThis.fetch;
199
199
  }
200
+ /** Before a retry, ask this broker's own gateway whether it can serve `model` now (`GET /healthz?model=`); no wait means no answer. */
201
+ export async function askGateway(model) {
202
+ const response = await llmFetch()(llmUrl().replace(/\/v1\/llm$/, `/healthz?model=${encodeURIComponent(model)}`), { signal: AbortSignal.timeout(5_000) }).catch(() => null);
203
+ if (response?.status === 200)
204
+ return { ok: true };
205
+ const seconds = response?.status === 503 ? (await response.json().catch(() => null))?.error?.retry_after_s : undefined;
206
+ return typeof seconds === 'number' ? { ok: false, waitMs: seconds * 1000, reason: `waiting for ${model}: model unavailable` } : { ok: false, reason: `waiting for ${model}: gateway not answering` };
207
+ }
200
208
  /** The real response under a deferred-head framing (`daemon/api/deferred-head.ts`): the magic line, keep-alive
201
209
  * blank lines, one JSON head line, then the body unchanged. Any other response is returned as it is. */
202
210
  export async function unwrapDeferredHead(response) {
@@ -304,7 +312,7 @@ export function streamBrokerModel(model, context, options = {}, intent, causedBy
304
312
  // stamping it as a refusal would record it as fatal and park the node.
305
313
  if (typeof seconds !== 'number' || !Number.isFinite(seconds) || seconds <= 0) {
306
314
  // Named by code, not prose: `upstream_model_unavailable` is a connection fault with automatic retry (RT-LLM-65).
307
- throw error.code === UPSTREAM_MODEL_UNAVAILABLE ? new UpstreamModelUnavailableError(error.message) : new Error(error.message);
315
+ throw error.code === UPSTREAM_MODEL_UNAVAILABLE ? new UpstreamModelUnavailableError(error.message, { cause: error.details?.breaker }) : new Error(error.message);
308
316
  }
309
317
  // A wait that outlasts what is left of the retry window cannot end in a
310
318
  // retry here, so sleeping first only delays the same failure. Fail now
@@ -337,7 +345,7 @@ export function streamBrokerModel(model, context, options = {}, intent, causedBy
337
345
  applyServedModel(message, refusalRoute(error));
338
346
  if (error.retryable !== true)
339
347
  throw new LlmRefusalError(error.message, undefined, refusalRateLimit(error), error.code, undefined, refusalPayment(error));
340
- throw error.code === UPSTREAM_MODEL_UNAVAILABLE ? new UpstreamModelUnavailableError(error.message) : new Error(error.message);
348
+ throw error.code === UPSTREAM_MODEL_UNAVAILABLE ? new UpstreamModelUnavailableError(error.message, { cause: error.details?.breaker }) : new Error(error.message);
341
349
  }
342
350
  if (chunk.served_model) {
343
351
  receivedServedModel = true;
@@ -431,8 +439,9 @@ export function streamBrokerModel(model, context, options = {}, intent, causedBy
431
439
  : []),
432
440
  ];
433
441
  }
442
+ // A breaker mark (`open` or `test`) tells the fault retry not to count this attempt.
434
443
  if (error instanceof UpstreamModelUnavailableError)
435
- message.diagnostics = [providerFailureDiagnostic({ status: 503, code: UPSTREAM_MODEL_UNAVAILABLE })];
444
+ message.diagnostics = [providerFailureDiagnostic({ status: 503, code: UPSTREAM_MODEL_UNAVAILABLE, ...(error.cause === undefined ? {} : { body: 'breaker' }) })];
436
445
  if (error instanceof ContentFilteredError && message.stopReason === 'error')
437
446
  message.rawStopReason = 'content_filter';
438
447
  stream.push({ type: 'error', reason: message.stopReason, error: message });
@@ -1,19 +1,19 @@
1
1
  const POLICIES = {
2
- connection: { kind: 'connection', gate: 'online', max: 8, baseDelayMs: 5_000, capDelayMs: 60_000, fatal: false },
3
- 'rate-limit': { kind: 'rate-limit', gate: 'time', max: 6, baseDelayMs: 30_000, capDelayMs: 5 * 60_000, fatal: false },
4
- overloaded: { kind: 'overloaded', gate: 'time', max: 6, baseDelayMs: 10_000, capDelayMs: 2 * 60_000, fatal: false },
5
- auth: { kind: 'auth', gate: 'none', max: 0, baseDelayMs: 0, capDelayMs: 0, fatal: true },
6
- protocol: { kind: 'protocol', gate: 'none', max: 0, baseDelayMs: 0, capDelayMs: 0, fatal: true },
7
- 'context-overflow': { kind: 'context-overflow', gate: 'none', max: 0, baseDelayMs: 0, capDelayMs: 0, fatal: true },
8
- other: { kind: 'other', gate: 'none', max: 0, baseDelayMs: 0, capDelayMs: 0, fatal: true },
2
+ connection: { kind: 'connection', max: 8, baseDelayMs: 5_000, capDelayMs: 60_000, fatal: false },
3
+ 'rate-limit': { kind: 'rate-limit', max: 6, baseDelayMs: 30_000, capDelayMs: 5 * 60_000, fatal: false },
4
+ overloaded: { kind: 'overloaded', max: 6, baseDelayMs: 10_000, capDelayMs: 2 * 60_000, fatal: false },
5
+ auth: { kind: 'auth', max: 0, baseDelayMs: 0, capDelayMs: 0, fatal: true },
6
+ protocol: { kind: 'protocol', max: 0, baseDelayMs: 0, capDelayMs: 0, fatal: true },
7
+ 'context-overflow': { kind: 'context-overflow', max: 0, baseDelayMs: 0, capDelayMs: 0, fatal: true },
8
+ other: { kind: 'other', max: 0, baseDelayMs: 0, capDelayMs: 0, fatal: true },
9
9
  // A wedge is a daemon-detected stall, never auto-retried — recovery is a
10
10
  // deliberate agent/operator decision (kill the runaway subprocess), not a
11
11
  // provider back-off.
12
- wedged: { kind: 'wedged', gate: 'none', max: 0, baseDelayMs: 0, capDelayMs: 0, fatal: true },
12
+ wedged: { kind: 'wedged', max: 0, baseDelayMs: 0, capDelayMs: 0, fatal: true },
13
13
  // A launch-time model resolution failure (unregistered/unauthenticated spec) —
14
14
  // never auto-retried, since retrying with the same unresolved model would just
15
15
  // fail again identically. Fixing it requires a new --model or new credentials.
16
- 'model-not-found': { kind: 'model-not-found', gate: 'none', max: 0, baseDelayMs: 0, capDelayMs: 0, fatal: true },
16
+ 'model-not-found': { kind: 'model-not-found', max: 0, baseDelayMs: 0, capDelayMs: 0, fatal: true },
17
17
  };
18
18
  export function policyFor(kind) {
19
19
  return POLICIES[kind];
@@ -23,14 +23,7 @@ function clampDelay(delayMs, capMs) {
23
23
  return 0;
24
24
  return Math.min(Math.max(1, Math.round(delayMs)), capMs);
25
25
  }
26
- function defaultOverloadedJitterMs(fault, attempt) {
27
- const seed = `${fault.link}|${fault.kind}|${fault.message}|${fault.since}|${attempt}`;
28
- let hash = 0;
29
- for (let i = 0; i < seed.length; i++) {
30
- hash = (hash * 33 + seed.charCodeAt(i)) >>> 0;
31
- }
32
- return hash % 1_000;
33
- }
26
+ /** Full jitter for connection and overloaded faults: a random delay between zero and the doubled delay, so nodes that failed together do not retry together. */
34
27
  function retryDelayMs(fault, attempt, opts) {
35
28
  const policy = policyFor(fault.kind);
36
29
  if (policy.fatal)
@@ -38,11 +31,7 @@ function retryDelayMs(fault, attempt, opts) {
38
31
  if (fault.kind === 'rate-limit' && typeof opts?.retryAfterMs === 'number' && Number.isFinite(opts.retryAfterMs)) {
39
32
  return clampDelay(opts.retryAfterMs, policy.capDelayMs);
40
33
  }
41
- const delay = policy.baseDelayMs * 2 ** Math.max(0, attempt - 1);
42
- const jitter = fault.kind === 'overloaded'
43
- ? Math.max(0, Math.round(opts?.jitterMs?.(fault, attempt) ?? defaultOverloadedJitterMs(fault, attempt)))
44
- : 0;
45
- return clampDelay(delay + jitter, policy.capDelayMs);
34
+ return clampDelay((fault.kind === 'rate-limit' ? 1 : Math.random()) * Math.min(policy.capDelayMs, policy.baseDelayMs * 2 ** Math.max(0, attempt - 1)), policy.capDelayMs);
46
35
  }
47
36
  export function nextFaultRetry(fault, now, opts) {
48
37
  const policy = policyFor(fault.kind);
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.715",
3
+ "version": "0.3.717",
4
4
  "description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "main": "./dist/api/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.715",
3
+ "version": "0.3.717",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/plugin",
3
- "version": "0.3.715",
3
+ "version": "0.3.717",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -27,8 +27,8 @@
27
27
  "postpack": "node ../../scripts/pack-minify.mjs postpack packages/crouter-plugin"
28
28
  },
29
29
  "dependencies": {
30
- "@north-light/api": "0.3.715",
31
- "@north-light/identity": "0.3.715"
30
+ "@north-light/api": "0.3.717",
31
+ "@north-light/identity": "0.3.717"
32
32
  },
33
33
  "license": "UNLICENSED",
34
34
  "publishConfig": {
package/runtime.lock.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.715",
3
+ "version": "0.3.717",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.715",
9
+ "version": "0.3.717",
10
10
  "hasInstallScript": true,
11
11
  "license": "UNLICENSED",
12
12
  "workspaces": [
@@ -28,8 +28,8 @@
28
28
  "@milkdown/preset-gfm": "^7.22.3",
29
29
  "@milkdown/prose": "^7.22.3",
30
30
  "@milkdown/utils": "^7.22.3",
31
- "@north-light/identity": "0.3.715",
32
- "@north-light/plugin": "0.3.715",
31
+ "@north-light/identity": "0.3.717",
32
+ "@north-light/plugin": "0.3.717",
33
33
  "cron-parser": "^5.6.0",
34
34
  "esbuild": "0.28.2",
35
35
  "jose": "^6.2.12",
@@ -11902,17 +11902,17 @@
11902
11902
  },
11903
11903
  "packages/crouter-api": {
11904
11904
  "name": "@north-light/api",
11905
- "version": "0.3.715",
11905
+ "version": "0.3.717",
11906
11906
  "license": "UNLICENSED"
11907
11907
  },
11908
11908
  "packages/crouter-env-docker": {
11909
11909
  "name": "@north-light/env-docker",
11910
- "version": "0.3.715",
11910
+ "version": "0.3.717",
11911
11911
  "license": "UNLICENSED"
11912
11912
  },
11913
11913
  "packages/crouter-identity": {
11914
11914
  "name": "@north-light/identity",
11915
- "version": "0.3.715",
11915
+ "version": "0.3.717",
11916
11916
  "license": "UNLICENSED",
11917
11917
  "dependencies": {
11918
11918
  "jose": "^6.2.1"
@@ -11920,21 +11920,21 @@
11920
11920
  },
11921
11921
  "packages/crouter-plugin": {
11922
11922
  "name": "@north-light/plugin",
11923
- "version": "0.3.715",
11923
+ "version": "0.3.717",
11924
11924
  "license": "UNLICENSED",
11925
11925
  "dependencies": {
11926
- "@north-light/api": "0.3.715",
11927
- "@north-light/identity": "0.3.715"
11926
+ "@north-light/api": "0.3.717",
11927
+ "@north-light/identity": "0.3.717"
11928
11928
  }
11929
11929
  },
11930
11930
  "packages/crouter-sdk": {
11931
11931
  "name": "@north-light/sdk",
11932
- "version": "0.3.715",
11932
+ "version": "0.3.717",
11933
11933
  "license": "UNLICENSED",
11934
11934
  "dependencies": {
11935
- "@north-light/api": "0.3.715",
11936
- "@north-light/identity": "0.3.715",
11937
- "@north-light/plugin": "0.3.715",
11935
+ "@north-light/api": "0.3.717",
11936
+ "@north-light/identity": "0.3.717",
11937
+ "@north-light/plugin": "0.3.717",
11938
11938
  "jose": "^6.2.1"
11939
11939
  },
11940
11940
  "bin": {