@north-light/cli 0.3.720 → 0.3.722

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 (60) hide show
  1. package/dist/api/contract.d.ts +1 -1
  2. package/dist/api/contract.js +1 -1
  3. package/dist/api/dto/recovery.d.ts +2 -0
  4. package/dist/builtin-memory/crouter-sdk/release-notes.md +6 -0
  5. package/dist/cli.js +8 -8
  6. package/dist/clients/attach/viewer.js +314 -314
  7. package/dist/commands/api-client.d.ts +2 -0
  8. package/dist/commands/api-client.js +2 -2
  9. package/dist/commands/node/inspect.js +7 -7
  10. package/dist/commands/profile/environment.js +2 -2
  11. package/dist/core/canvas/schema-pg/031-environment-pull-request-write-default.sql +2 -0
  12. package/dist/core/canvas/schema-pg/032-model-cooldown-vendor-limit.sql +4 -0
  13. package/dist/core/canvas/schema-version.d.ts +1 -1
  14. package/dist/core/canvas/schema-version.js +1 -1
  15. package/dist/core/environments.js +1 -1
  16. package/dist/core/graph/reader.js +1 -1
  17. package/dist/core/import/load/open-grants.d.ts +1 -0
  18. package/dist/core/import/load/open-grants.js +1 -0
  19. package/dist/core/import/load/run.d.ts +3 -1
  20. package/dist/core/import/load/run.js +2 -2
  21. package/dist/core/llm/run.js +2 -2
  22. package/dist/core/managed-providers.d.ts +9 -1
  23. package/dist/core/provider-failure.d.ts +2 -0
  24. package/dist/core/provider-failure.js +1 -1
  25. package/dist/core/runtime/broker/model-adapter.js +3 -3
  26. package/dist/core/runtime/revive.d.ts +2 -0
  27. package/dist/core/runtime/revive.js +2 -2
  28. package/dist/core/runtime/runner/blaxel/image-build.d.ts +3 -0
  29. package/dist/core/runtime/runner/blaxel/image-build.js +6 -6
  30. package/dist/core/subscription-state.d.ts +4 -4
  31. package/dist/core/subscription-state.js +1 -1
  32. package/dist/daemon/api/handlers/messages.js +2 -2
  33. package/dist/daemon/api/handlers/nodes.js +1 -1
  34. package/dist/daemon/api/handlers/profiles.js +1 -1
  35. package/dist/daemon/api/operations.js +1 -1
  36. package/dist/daemon/api/router.d.ts +4 -0
  37. package/dist/daemon/api/router.js +1 -1
  38. package/dist/daemon/reconcilers/broker-supervision.js +3 -3
  39. package/docs/sdk/release-notes.md +6 -0
  40. package/package.json +3 -3
  41. package/packages/crouter-api/dist/api/contract.js +1 -1
  42. package/packages/crouter-api/dist/commands/api-client.js +3 -1
  43. package/packages/crouter-api/dist/commands/node/inspect.js +2 -1
  44. package/packages/crouter-api/dist/commands/profile/environment.js +2 -2
  45. package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
  46. package/packages/crouter-api/dist/core/environments.js +1 -1
  47. package/packages/crouter-api/dist/core/graph/reader.js +3 -3
  48. package/packages/crouter-api/dist/core/llm/run.js +13 -2
  49. package/packages/crouter-api/dist/core/provider-failure.js +9 -0
  50. package/packages/crouter-api/dist/core/runtime/broker/model-adapter.js +3 -1
  51. package/packages/crouter-api/dist/core/runtime/revive.js +11 -0
  52. package/packages/crouter-api/dist/core/runtime/runner/blaxel/image-build.js +16 -1
  53. package/packages/crouter-api/dist/core/subscription-state.js +26 -10
  54. package/packages/crouter-api/dist/daemon/api/operations.js +2 -2
  55. package/packages/crouter-api/dist/daemon/api/router.js +1 -1
  56. package/packages/crouter-api/dist/daemon/reconcilers/broker-supervision.js +3 -1
  57. package/packages/crouter-api/package.json +1 -1
  58. package/packages/crouter-identity/package.json +1 -1
  59. package/packages/crouter-plugin/package.json +3 -3
  60. package/runtime.lock.json +14 -14
@@ -1 +1 @@
1
- var A=Object.defineProperty;var d=(e,n)=>A(e,"name",{value:n,configurable:!0});import{isRecord as h}from"../shared/predicates.js";import{PAYMENT_REFUSAL_REASONS as E}from"../api/dto/charges.js";const g="crtr:provider-failure",I=8;function i(e){return typeof e=="string"&&e.trim()!==""?e.trim():void 0}d(i,"text");function c(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}d(c,"status");function m(e){return typeof e=="string"||typeof e=="number"?e:void 0}d(m,"code");function s(e){return h(e)?e:void 0}d(s,"record");function y(e){const n=i(e.errorMessage)??i(e.message)??i(e.reason)??i(e.statusText),r={...n===void 0?{}:{message:n},...c(e.status)===void 0?{}:{status:c(e.status)},...m(e.code)===void 0?{}:{code:m(e.code)},...i(e.errno)===void 0?{}:{errno:i(e.errno)},...i(e.body)===void 0?{}:{body:i(e.body)}};return Object.keys(r).length===0?void 0:r}d(y,"failureCause");function D(e,n={}){const r=s(e),o=r===void 0?void 0:y(r),t=[],u=new Set([e]);let f=r===void 0?void 0:s(r.cause);for(;f!==void 0&&!u.has(f)&&t.length<I;){u.add(f);const a=y(f);a!==void 0&&t.push(a),f=s(f.cause)}return{message:o?.message??(e instanceof Error?e.message:void 0)??String(e??"Provider request failed"),...(n.status??o?.status)===void 0?{}:{status:n.status??o?.status},...o?.code===void 0?{}:{code:o.code},...o?.errno===void 0?{}:{errno:o.errno},...o?.body===void 0?{}:{body:o.body},...t.length===0?{}:{causes:t}}}d(D,"normalizeProviderFailure");function F(e){return{type:g,timestamp:Date.now(),details:R(e)}}d(F,"providerFailureDiagnostic");function R(e){const n=b(e);if(e.causes!==void 0&&(n.causes=e.causes.map(b)),e.ratelimit!==void 0){const r={headers:{...e.ratelimit.headers}};e.ratelimit.scope!==void 0&&(r.scope=e.ratelimit.scope),e.ratelimit.claim!==void 0&&(r.claim=e.ratelimit.claim),e.ratelimit.account!==void 0&&(r.account=e.ratelimit.account),e.ratelimit.model!==void 0&&(r.model=e.ratelimit.model),n.ratelimit=r}return e.payment!==void 0&&(n.payment={reason:e.payment.reason,message:e.payment.message,pay_url:e.payment.pay_url,reset_at:e.payment.reset_at}),n}d(R,"jsonDetails");const T=48,L=256,S=new Set(E);function l(e){const n=s(e);if(!(n===void 0||typeof n.reason!="string"||!S.has(n.reason)||typeof n.message!="string"))return{reason:n.reason,message:n.message,pay_url:typeof n.pay_url=="string"?n.pay_url:null,reset_at:typeof n.reset_at=="string"?n.reset_at:null}}d(l,"parseProviderPayment");function _(e){const n=s(e),r=s(n?.headers);if(n===void 0||r===void 0)return;const o={};for(const[t,u]of Object.entries(r)){if(Object.keys(o).length>=T)break;typeof u=="string"&&(o[t.toLowerCase()]=u.slice(0,L))}return{...i(n.scope)===void 0?{}:{scope:i(n.scope)},...i(n.claim)===void 0?{}:{claim:i(n.claim)},...i(n.account)===void 0?{}:{account:i(n.account)},...i(n.model)===void 0?{}:{model:i(n.model)},headers:o}}d(_,"parseProviderRateLimit");function b(e){const n={};return e.message!==void 0&&(n.message=e.message),e.status!==void 0&&(n.status=e.status),e.code!==void 0&&(n.code=e.code),e.errno!==void 0&&(n.errno=e.errno),e.body!==void 0&&(n.body=e.body),n}d(b,"jsonCause");function x(e){const n=s(e)?.diagnostics;if(Array.isArray(n))for(const r of n){const o=s(r);if(o?.type!==g)continue;const t=s(o.details);if(t===void 0)continue;const u=Array.isArray(t.causes)?t.causes.flatMap(f=>{const p=s(f),a=p===void 0?void 0:y(p);return a===void 0?[]:[a]}):void 0;return{...c(t.status)===void 0?{}:{status:c(t.status)},...m(t.code)===void 0?{}:{code:m(t.code)},...i(t.errno)===void 0?{}:{errno:i(t.errno)},...i(t.body)===void 0?{}:{body:i(t.body)},...u===void 0||u.length===0?{}:{causes:u},..._(t.ratelimit)===void 0?{}:{ratelimit:_(t.ratelimit)},...l(t.payment)===void 0?{}:{payment:l(t.payment)}}}}d(x,"providerFailureDetails");function O(e){return x(e)}d(O,"extractProviderFailureDetails");export{g as PROVIDER_FAILURE_DIAGNOSTIC,O as extractProviderFailureDetails,D as normalizeProviderFailure,l as parseProviderPayment,_ as parseProviderRateLimit,F as providerFailureDiagnostic};
1
+ var h=Object.defineProperty;var d=(e,n)=>h(e,"name",{value:n,configurable:!0});import{isRecord as A}from"../shared/predicates.js";import{PAYMENT_REFUSAL_REASONS as E}from"../api/dto/charges.js";const g="crtr:provider-failure",I=8;function o(e){return typeof e=="string"&&e.trim()!==""?e.trim():void 0}d(o,"text");function c(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}d(c,"status");function m(e){return typeof e=="string"||typeof e=="number"?e:void 0}d(m,"code");function s(e){return A(e)?e:void 0}d(s,"record");function y(e){const n=o(e.errorMessage)??o(e.message)??o(e.reason)??o(e.statusText),t={...n===void 0?{}:{message:n},...c(e.status)===void 0?{}:{status:c(e.status)},...m(e.code)===void 0?{}:{code:m(e.code)},...o(e.errno)===void 0?{}:{errno:o(e.errno)},...o(e.body)===void 0?{}:{body:o(e.body)}};return Object.keys(t).length===0?void 0:t}d(y,"failureCause");function M(e,n={}){const t=s(e),r=t===void 0?void 0:y(t),i=[],u=new Set([e]);let a=t===void 0?void 0:s(t.cause);for(;a!==void 0&&!u.has(a)&&i.length<I;){u.add(a);const f=y(a);f!==void 0&&i.push(f),a=s(a.cause)}return{message:r?.message??(e instanceof Error?e.message:void 0)??String(e??"Provider request failed"),...(n.status??r?.status)===void 0?{}:{status:n.status??r?.status},...r?.code===void 0?{}:{code:r.code},...r?.errno===void 0?{}:{errno:r.errno},...r?.body===void 0?{}:{body:r.body},...i.length===0?{}:{causes:i}}}d(M,"normalizeProviderFailure");function P(e){return{type:g,timestamp:Date.now(),details:w(e)}}d(P,"providerFailureDiagnostic");function w(e){const n=b(e);if(e.causes!==void 0&&(n.causes=e.causes.map(b)),e.ratelimit!==void 0){const t={headers:{...e.ratelimit.headers}};e.ratelimit.scope!==void 0&&(t.scope=e.ratelimit.scope),e.ratelimit.claim!==void 0&&(t.claim=e.ratelimit.claim),e.ratelimit.account!==void 0&&(t.account=e.ratelimit.account),e.ratelimit.model!==void 0&&(t.model=e.ratelimit.model),n.ratelimit=t}return e.payment!==void 0&&(n.payment={reason:e.payment.reason,message:e.payment.message,pay_url:e.payment.pay_url,reset_at:e.payment.reset_at}),n}d(w,"jsonDetails");const R=48,S=256,L=new Set(E);function N(e){const n=e?.payment?.reset_at?` Earliest known vendor reset: ${e.payment.reset_at}.`:"",t=e?.ratelimit;if(t===void 0)return n;const r=t.headers["anthropic-ratelimit-unified-reset"];return`${n} Rate limit: ${t.scope??"account"}${t.claim===void 0?"":` (${t.claim})`}${t.account===void 0?"":` on account ${t.account}`}${t.model===void 0?"":` for ${t.model}`}${r===void 0||!Number(r)?"":`, that window resets ${new Date(Number(r)*1e3).toISOString()}`}.`}d(N,"describeVendorLimit");function l(e){const n=s(e);if(!(n===void 0||typeof n.reason!="string"||!L.has(n.reason)||typeof n.message!="string"))return{reason:n.reason,message:n.message,pay_url:typeof n.pay_url=="string"?n.pay_url:null,reset_at:typeof n.reset_at=="string"?n.reset_at:null}}d(l,"parseProviderPayment");function _(e){const n=s(e),t=s(n?.headers);if(n===void 0||t===void 0)return;const r={};for(const[i,u]of Object.entries(t)){if(Object.keys(r).length>=R)break;typeof u=="string"&&(r[i.toLowerCase()]=u.slice(0,S))}return{...o(n.scope)===void 0?{}:{scope:o(n.scope)},...o(n.claim)===void 0?{}:{claim:o(n.claim)},...o(n.account)===void 0?{}:{account:o(n.account)},...o(n.model)===void 0?{}:{model:o(n.model)},headers:r}}d(_,"parseProviderRateLimit");function b(e){const n={};return e.message!==void 0&&(n.message=e.message),e.status!==void 0&&(n.status=e.status),e.code!==void 0&&(n.code=e.code),e.errno!==void 0&&(n.errno=e.errno),e.body!==void 0&&(n.body=e.body),n}d(b,"jsonCause");function T(e){const n=s(e)?.diagnostics;if(Array.isArray(n))for(const t of n){const r=s(t);if(r?.type!==g)continue;const i=s(r.details);if(i===void 0)continue;const u=Array.isArray(i.causes)?i.causes.flatMap(a=>{const p=s(a),f=p===void 0?void 0:y(p);return f===void 0?[]:[f]}):void 0;return{...c(i.status)===void 0?{}:{status:c(i.status)},...m(i.code)===void 0?{}:{code:m(i.code)},...o(i.errno)===void 0?{}:{errno:o(i.errno)},...o(i.body)===void 0?{}:{body:o(i.body)},...u===void 0||u.length===0?{}:{causes:u},..._(i.ratelimit)===void 0?{}:{ratelimit:_(i.ratelimit)},...l(i.payment)===void 0?{}:{payment:l(i.payment)}}}}d(T,"providerFailureDetails");function O(e){return T(e)}d(O,"extractProviderFailureDetails");export{g as PROVIDER_FAILURE_DIAGNOSTIC,N as describeVendorLimit,O as extractProviderFailureDetails,M as normalizeProviderFailure,l as parseProviderPayment,_ as parseProviderRateLimit,P as providerFailureDiagnostic};
@@ -1,3 +1,3 @@
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};
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 $}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 d=>e.getProvider(d)?{type:"api_key"}:void 0,e.getAvailable=async d=>e.getModels(d),e.getAvailableSnapshot=()=>e.getModels(),e.streamSimple=(d,c,a)=>Ee(d,c,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,d,c,a,r){super(t),this.retryAt=n,this.rateLimit=d,this.code=c,this.status=a,this.payment=r}}class E 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 M(e){const t=e.details?.rate_limit;if(!t||typeof t!="object")return;const n=ge(t);if(n===void 0)return;const{provider:d,model:c}=t;return typeof d=="string"&&d!==""&&typeof c=="string"&&c!==""?{...n,model:`${d}/${c}`}:n}f(M,"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 A(e){return he(e.details?.payment)}f(A,"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(c=>c.role==="assistant"&&(c.stopReason==="error"||c.stopReason==="aborted"),"incomplete"),n=e.some(t)?e.filter(c=>!t(c)):e;let d=n.length;for(;d>0&&n[d-1]?.role==="assistant";)d--;return d===n.length?n:n.slice(0,d)}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 d=await fe(n,ce(),le());return new Set(d.flatMap(c=>c.strength===n.strength&&c.providerId===e.provider&&c.modelId===e.id&&c.thinkingLevel!==void 0?[c.thinkingLevel]:[]))}f(_e,"launchThinkingLevels");function xe(e,t,n,d,c=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 l of we(t.messages))l.role==="user"?a.push({role:"user",content:W(l.content)}):l.role==="toolResult"?a.push({role:"tool",content:W(l.content),tool_call_id:l.toolCallId}):l.role==="assistant"&&a.push({role:"assistant",content:l.content.filter(p=>p.type==="text").map(p=>p.text).join("")||null,tool_calls:l.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=d??q();return{model:pe(b,w,L()),model_policy:L()?"exact":"substitute",stream:!0,messages:a,...s.length?{tools:s.map(l=>({type:"function",function:{name:l.name,description:l.description,parameters:l.parameters}}))}:{},...n.reasoning&&!c.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 E(`llm returned a non-JSON answer: ${e.slice(0,120)}`)}}f(z,"parseAnswer");function O(){const e=$();return e===void 0?"http://localhost/v1/llm":new URL("/v1/llm",e).toString()}f(O,"llmUrl");function G(){return $()===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),d=!1;for(;;){const c=n.indexOf(10);if(c<0){const{value:l,done:p}=await t.read();if(p)throw new Error("deferred head response ended before its head");const m=new Uint8Array(n.length+l.length);m.set(n),m.set(l,n.length),n=m;continue}const a=new TextDecoder().decode(n.subarray(0,c)).trim();if(n=n.subarray(c+1),!d){if(`${a}
2
+ `!==oe)throw new Error("deferred head response has no magic line");d=!0;continue}if(a==="")continue;const r=JSON.parse(a),s=new Headers;for(const[l,p]of Object.entries(r.headers))for(const m of Array.isArray(p)?p:[p])s.append(l,m);const b=n,w=new ReadableStream({start(l){b.length>0&&l.enqueue(b)},async pull(l){const{value:p,done:m}=await t.read();m?l.close():l.enqueue(p)},cancel(l){return t.cancel(l)}});return new Response(r.status===204?null:w,{status:r.status,headers:s})}}f(be,"unwrapDeferredHead");function ke(e){const t=e??de();return t===void 0?{}:{"crtr-caused-by":t}}f(ke,"causedByHeader");function Ee(e,t,n={},d,c){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,d,await _e(e,d??q()))),w=Buffer.byteLength(b);if(w>v)throw T(w,v);let l=0;for(;;){n.signal?.throwIfAborted();const p=await G()(O(),{method:"POST",headers:{authorization:`Bearer ${s}`,"content-type":"application/json",[ne]:"1",...ke(c)},body:b,signal:n.signal}).catch(u=>{const o=O();throw $()===void 0||n.signal?.aborted?u:new E(ae(u,o).message)}),m=await be(p);if(!m.ok){if(m.status===413)throw T(w,v);const u=Y(z(await m.text()));if(u.code==="payload_too_large")throw T(w,v);if(D(r,J(u)),u.retryable!==!0)throw new R(u.message,void 0,M(u),u.code,m.status,A(u));const o=u.retry_after_s;if(typeof o!="number"||!Number.isFinite(o)||o<=0)throw u.code===I?new E(u.message,{cause:u.details?.breaker}):new Error(u.message);const g=ye-l;if(o>g){const h=Date.now()+o*1e3,i=A(u)?.reset_at;throw new R(`${u.message} (retry after ${o}s, at ${new Date(h).toISOString()}: the router's next probe${i?`; earliest known vendor reset ${i}`:""})`,h,M(u),u.code,m.status,A(u))}await Q(o*1e3,void 0,{signal:n.signal}),l+=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 _="",k="stop",N,P=!1,U=!1;const F=f(u=>{const o=z(u);if(o.error){const i=Y(o);throw D(r,J(i)),i.retryable!==!0?new R(i.message,void 0,M(i),i.code,void 0,A(i)):i.code===I?new E(i.message,{cause:i.details?.breaker}):new Error(i.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 i=r.content.findIndex(S=>S.type==="thinking"),y=i<0?{type:"thinking",thinking:""}:r.content[i],x=i<0?r.content.push(y)-1:i;if(i<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 i=r.content.findIndex(S=>S.type==="text"),y=i<0?{type:"text",text:""}:r.content[i],x=i<0?r.content.push(y)-1:i;if(i<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 i of h?.tool_calls??[]){const y={type:"toolCall",id:i.id,name:i.function.name,arguments:JSON.parse(i.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&&(k=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:u,done:o}=await X.read();if(o)break;_+=C.decode(u,{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[u,o]of r.content.entries())o.type==="text"&&a.push({type:"text_end",contentIndex:u,content:o.text,partial:r}),o.type==="thinking"&&a.push({type:"thinking_end",contentIndex:u,content:o.thinking,partial:r});if(k==="content_filter")throw new j(N??"Content filtered");if(!["stop","tool_calls","length"].includes(k))throw new Error(`llm returned unknown finish reason: ${k}`);r.stopReason=k==="tool_calls"?"toolUse":k==="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 E&&(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(Ee,"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,Ee as streamBrokerModel,be as unwrapDeferredHead,we as wireHistory};
@@ -111,6 +111,8 @@ export declare function assertRecordedCwdExists(nodeId: string, meta: NodeMeta):
111
111
  blaxelEnvironment: string | null;
112
112
  remoteMachine: boolean;
113
113
  }>;
114
+ /** Cleanup deleted this node's managed checkout and its branch, and nothing rebuilds them: refuse on any host, before a caller changes state. */
115
+ export declare function assertCheckoutNotRemoved(nodeId: string, meta: NodeMeta): void;
114
116
  /** The `node:start` lifecycle hooks for a node coming up: a launch, or a cycle started in a running process. */
115
117
  export declare function runNodeStartHooks(nodeId: string, meta: NodeMeta, isBirth: boolean): Promise<void>;
116
118
  export {};
@@ -1,3 +1,3 @@
1
- var ce=Object.defineProperty;var s=(e,r)=>ce(e,"name",{value:r,configurable:!0});import{assertGranteeRunsHere as ue}from"./unsandboxed.js";import{existsSync as H}from"node:fs";import{conversationIdFromPath as _,conversationStore as m,ConversationNotFoundError as G}from"../conversation-store/index.js";import{isAbsolute as fe}from"node:path";import{findNodeBySessionFile as we,getNode as R,updateNode as N,beginExecution as he,ExecutionAlreadyLive as pe,recordExecutionPid as me,abortExecution as F,endLiveExecution as de,unbindSession as U,recordLaunch as ve,setFrozen as _e,clearFrozen as K,fullName as ye}from"../canvas/index.js";import{emitEvent as W}from"../events/emit.js";import{consumeDeadlineOnWake as ke}from"../feed/messages.js";import{isParked as J,transition as A}from"./lifecycle.js";import{publishNotice as ge}from"./close.js";import{InputError as O}from"../io.js";import{buildPiArgv as y}from"./launch.js";import{buildReviveKickoff as be,drainBearings as Re,hasRetainedReports as Ee,readGoal as E,readYieldMessage as xe,RUNTIME_RESTART_CONTINUATION as Se}from"./kickoff.js";import{readRoadmap as j}from"./roadmap.js";import{encodeKickoffOrigin as Ce,KICKOFF_ORIGIN_ENV as $e}from"./stamp/protocol.js";import{carryInitialInput as V}from"../runs/initial-input.js";import{headlessBrokerHost as Ne,brokerLaunchJson as Fe}from"./host.js";import{isCloudRole as Ae}from"../canvas/person.js";import{asNodePerson as Oe}from"../../daemon/reconcilers/node-lifecycle/node-person.js";import{processRunner as Pe}from"./runner/process.js";import{runnerForEnvironment as X}from"./runner/index.js";import{MachineOfflineError as Y}from"./runner/machine/ops.js";import{blaxelEnvironmentOf as q}from"./blaxel-environment.js";import{recordLaunchFailure as Be}from"../../daemon/reconcilers/node-lifecycle/launch-failure.js";import{acceptedRelease as Q,remoteMachineEnvironmentOf as De,checkBilledWake as Te,EnvironmentImagePending as Me,imageForWake as Le}from"../../daemon/reconcilers/node-lifecycle/remote-wake.js";import{ExecutionCapReached as ze,liveExecutionForNode as He,setExecutionLaunchJson as Ge}from"../canvas/executions.js";import{isDrained as Ue}from"../../daemon/drain.js";import{appMemoryFull as Ke,appMemoryTooSmall as We,boundFleet as Z,brokerCapReached as I,brokerThresholdsForDaemon as P}from"./fleet.js";import{admitBrokerMemory as Je}from"./memory-admission.js";import{beginBootFaultAttempt as je,clearFault as Ve,hasAdmittedTurn as Xe,readFault as Ye}from"../canvas/recovery.js";import{clearNodeLedger as ee,forkNodeLedger as qe,noticeChangedWhileDone as Qe}from"./ledger.js";import{forkSourceNode as Ze,rootOfSpine as Ie}from"./nodes.js";import{ApiError as er}from"../../api/errors.js";import{grantSnapshotMissing as rr}from"../../daemon/readiness.js";import{checkGrantActive as ir,checkStart as tr}from"./start-check.js";import{isReviewCompanionBound as nr}from"../review/companion.js";import{assertProfileActive as ar}from"../profiles/manifest.js";import{isPidAlive as or}from"../canvas/pid.js";import{crtrHome as sr,jobDir as lr}from"../canvas/paths.js";import{contextDir as cr,ensureNodeDirs as ur,nodeAgentDir as fr}from"../canvas/node-agent-paths.js";import{discoverLifecycleHookRegistry as wr}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as hr}from"../command-hooks/transport/exec-lifecycle.js";async function pr(e,r){const i=e.pi_session_file,t=i?_(i):null;if(t===null)return{};try{const n=await m().header(t);return r?{resumeSessionPath:n.path}:{resumeSessionPath:n.path,newCycle:!0}}catch(n){if(n instanceof G)return{};throw n}}s(pr,"resumeArgs");async function re(e){const r=_(e);if(r===null)return!1;try{return await m().header(r),!0}catch(i){if(i instanceof G)return!1;throw i}}s(re,"conversationExists");async function mr(e){const r=_(e);return r===null?!0:(await m().read(r)).entries.some(i=>i.type==="message")}s(mr,"sessionHasConversation");async function dr(e){const r=_(e);if(r===null)return!0;const i=(await m().header(r)).header.cwd;return typeof i!="string"||H(i)}s(dr,"sessionCwdExists");async function vr(e,r,i,t){const n=r.pi_session_file;if(!n||!await re(n))return{};const u=await we(n);return u!==null&&u.node_id!==e&&or(u.pi_pid)?{}:t&&!await dr(n)?{}:await pr(r,i)}s(vr,"resumableSessionArgs");async function _r(e){return await j(e)===null&&await xe(e)===null&&!await Ee(e)}s(_r,"isUnstartedBirth");async function fi(e){const r=await E(e);if(r!==null&&r.trim()!=="")return!0;const i=await j(e);return i!==null&&i.trim()!==""}s(fi,"hasFreshGroundState");async function wi(e,r){const i=await ie(e,r,!0);if(i.parked)throw new Error(`reviveNode: internal parked decision for activating revive ${e}`);return i.result}s(wi,"reviveNode");async function hi(e,r,i){return ie(e,{...r,viewerAttach:!0},i)}s(hi,"decideAttachRevive");async function ie(e,r,i){const t=Ae()?await R(e):null;return t===null?await te(e,r,i):await Oe({node_id:e,sub:t.sub??null,profile_id:t.profile_id??null},()=>te(e,r,i))}s(ie,"decideRevive");async function te(e,r,i){let t=await R(e);if(t===null)throw new Error(`reviveNode: unknown node ${e}`);if(t=await R(e)??t,t.run_id&&(await R(t.run_id))?.deleting_at)throw new Error("run is deleting");if(t.final_report!==null)throw new Error(`reviveNode: refusing to revive ${e} \u2014 its finalization latch is set (final_report=${t.final_report}). A final landed between the caller's reopen-gate check and this revive; re-run with --reopen if this retask is still wanted.`);ar(t.profile_id),ue(t.grantee);const n=Z(),u=t.grantee==="app:terminal"&&await rr();if(!await n.has(e)&&!await n.isClaimed(e)&&r.wakeReason!=="runtime-restart-abort"&&r.viewerAttach!==!0&&!(!i&&t.lifecycle==="resident"&&J(t))&&(await ir(t),await tr(t),await q(t.profile_id??null)!==null&&await Te(t)),await n.isClaimed(e))return await n.has(e)&&await A(e,t.intent==="refresh"?"refresh-launch":"revive"),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"already-live"}};if(!i&&t.lifecycle==="resident"&&J(t))return{parked:!0};if(u){if(r.capacity==="refuse")throw new er(503,"runtime_starting","the first grant snapshot from the directory has not committed");return await ne(e,t,{reason:"grant_snapshot"}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}const k=await Ue();if(k&&r.capacity==="refuse")throw new Error(`the daemon is drained for an import; ${e} cannot start until it ends`);const d=!k&&await n.reserveSlot(e);let o=null;if(d){try{o=await Je(e)}catch(w){throw n.releaseReservation(e),w}o.verdict!=="admitted"&&n.releaseReservation(e)}if(o?.verdict==="too_small")throw We(o);if(!d||o?.verdict==="denied"){if(r.capacity==="refuse")throw o?.verdict==="denied"?Ke(o):I(P().automaticReviveCap,await n.occupancy());return await ne(e,t,k?{reason:"drain"}:o?.verdict==="denied"?{reason:"app_memory",free_bytes:o.free_bytes,needed_bytes:o.needed_bytes}:{reason:"broker_cap",live_count:await n.occupancy(),hard_cap:P().automaticReviveCap}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}try{return{parked:!1,result:await gr(e,t,r)}}finally{n.releaseReservation(e)}}s(te,"decideReviveAsCaller");async function ne(e,r,i){r.frozen_at==null&&(await _e(e,new Date().toISOString()),await de(e,{reason:"frozen"}),W({level:"info",event:"broker.frozen",node_id:e,fields:i}))}s(ne,"freezeForWait");async function yr(e,r){const i=await q(r.profile_id??null),t=await De(r.profile_id??null)!==null;if(!(i!==null||t)&&!H(r.cwd)){const u=r.fork_from!=null?`Restore ${r.cwd}, then revive the fork normally with \`crtr node lifecycle revive ${e}\`.`:r.managed_worktree?.state==="open"?"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon recovery.":`Recreate ${r.cwd}, or repair it with \`crtr node config --cwd <path> --node ${e}\`; durable node work resumes in a fresh conversation. Then retry \`crtr node lifecycle revive ${e}\`.`;throw new O({error:"cwd_missing",message:`${e} cannot be revived \u2014 its recorded cwd no longer exists: ${r.cwd}`,next:u})}return{blaxelEnvironment:i,remoteMachine:t}}s(yr,"assertRecordedCwdExists");async function kr(e,r,i){const t=wr(r.cwd,r.profile_id).plans.get("node:start")??[];await hr(t,{node:{id:e,name:r.name,kind:r.kind,mode:r.mode,lifecycle:r.lifecycle,cwd:r.cwd,nodeDir:await fr(e),contextDir:await cr(e),jobDir:lr(e)},runtime:{isBirth:i,canvasHome:sr(),profile:r.profile_id??null}})}s(kr,"runNodeStartHooks");async function gr(e,r,i){const{blaxelEnvironment:t,remoteMachine:n}=await yr(e,r),u=t!==null||n;r.host_kind!=="broker"&&(await N(e,{host_kind:"broker"}),r.host_kind="broker"),r.review_binding!=null&&!await nr(e)&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await U(e),r.pi_session_id=null,r.pi_session_file=null);const d=r.fork_from!=null&&r.pi_session_id==null,o=r.fork_source_file;if(d&&(typeof o!="string"||!fe(o)))throw new O({error:"fork_source_invalid",message:`${e} cannot be revived \u2014 its resolved fork source file is missing or invalid.`,next:`Restore the node's fork source metadata, then retry \`crtr node lifecycle revive ${e}\`.`});const w=d&&typeof o=="string";if(w&&!await re(o))throw new O({error:"fork_from_missing",message:`${e} cannot be revived \u2014 its fork source no longer exists: ${o}`,next:`Restore ${o}, or update the node's fork source, then retry \`crtr node lifecycle revive ${e}\`.`});const{automaticReviveCap:ae}=P();if(t!==null){const l=await Le(t);if(l.state==="pending")throw new Me(t,l.error)}const oe=t!==null?X("blaxel"):n?X("machine"):Pe;let f;try{f=await he(e,{daemonEpoch:Z().epoch(),cap:ae,...t!==null?{runner:"blaxel",release:Q()}:n?{runner:"machine",release:Q()}:{}})}catch(l){if(l instanceof ze)throw I(l.cap,l.live);if(l instanceof pe)return{window:null,session:r.tmux_session??null,resumed:!1,outcome:"already-live"};throw l}try{r.cycles=(r.cycles??0)+1,await N(e,{cycles:r.cycles});const x=r.intent==="refresh"||r.cycle_pending===!0?!1:i.resume,p=w?{}:await vr(e,r,x,!u),g=p.resumeSessionPath!==void 0,B=g&&p.newCycle===!0,v=g&&!B,D=!g&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&await _r(e),S=v&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&!await Xe(e)&&!await mr(p.resumeSessionPath)?(await E(e))?.trim():void 0,T=S!==void 0&&S!=="",se=w||D||T,M=r.cycle_pending===!0||B;await N(e,{cycle_pending:M}),r.cycle_pending=M,!w&&!g&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await U(e),r.pi_session_id=null,r.pi_session_file=null);let c,h=null;const C=s(()=>({type:"runtime",kind:"kickoff",...r.spawned_by!=null&&r.spawned_by!==""?{spawnedBy:r.spawned_by}:{}}),"birthOrigin");if(w){const a=await E(e),$=_(o);if($===null)throw new Error(`invalid fork source ${o}`);const le=(await m().header(await m().fork($,e))).path;c=y(r,{resumeSessionPath:le,...a!=null&&a!==""?{prompt:a}:{}}),a!=null&&a!==""&&(h=C()),await qe(e,(await Ze(o))?.node_id??null)}else if(T)c=y(r,{...p,prompt:S}),h=C(),await V(c,r);else if(v)c=y(r,{...p,...i.wakeReason==="runtime-restart-abort"?{prompt:Se}:{}}),i.wakeReason==="runtime-restart-abort"&&(h={type:"runtime",kind:"restart-continuation"});else if(D){const a=(await E(e))?.trim();c=y(r,a!==void 0&&a!==""?{prompt:a}:{}),a!==void 0&&a!==""&&(h=C(),await V(c,r)),await ee(e)}else{const a=await Re(r,f);c=y(r,{...p,prompt:await be(r,a,i.wakeReason==="runtime-restart-abort"?void 0:i.wakeReason)}),r.run_id&&a.unreadMessageIds?.length&&(c.env.CRTR_KICKOFF_MESSAGE_IDS=JSON.stringify(a.unreadMessageIds)),h=i.wakeReason!==void 0&&i.wakeReason!=="runtime-restart-abort"?{type:"runtime",kind:"wake",wake:i.wakeReason}:{type:"runtime",kind:"revive",cycle:r.cycles??0},await ee(e)}c.env={...c.env,CRTR_SUBTREE:await Ie(e)},h!==null&&(c.env[$e]=Ce(h)),r.status==="done"&&r.last_settled_at!=null&&await Qe(e,r.last_settled_at),await A(e,r.intent==="refresh"?"refresh-launch":"revive"),(await Ye(e))?.op!=="conversation_write_failed"&&await Ve(e,{preserveEpisode:!0});const L=await je(e);i.recovery!==!0&&i.viewerAttach!==!0&&await ke(e),await ur(e,r.grantee),await kr(e,r,se),c.env={...c.env,CRTR_EXECUTION_ID:f};const z=await Fe(e,c,r.cwd);await Ge(f,z);let b;try{const a=await He(e);if(b=await oe.start({executionId:f,nodeId:e,attempt:a?.attempt??1,release:a?.release??"",launchJson:z,cwd:r.cwd,resuming:v}),!u&&b.pid===null)throw new Error(`broker host returned no pid for ${e}`)}catch(a){if(a instanceof Y)throw a;try{await A(e,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:a instanceof Error?a.message:String(a)}}}),await ge(e,"notice.crash",`Child crashed \u2014 ${ye(r)} (${e}) failed to relaunch and is now dead: ${a.message}
1
+ var le=Object.defineProperty;var s=(e,r)=>le(e,"name",{value:r,configurable:!0});import{assertGranteeRunsHere as ue}from"./unsandboxed.js";import{existsSync as H}from"node:fs";import{conversationIdFromPath as _,conversationStore as d,ConversationNotFoundError as G}from"../conversation-store/index.js";import{isAbsolute as fe}from"node:path";import{findNodeBySessionFile as we,getNode as R,updateNode as F,beginExecution as he,ExecutionAlreadyLive as pe,recordExecutionPid as de,abortExecution as A,endLiveExecution as me,unbindSession as U,recordLaunch as ve,setFrozen as _e,clearFrozen as K,fullName as ye}from"../canvas/index.js";import{emitEvent as W}from"../events/emit.js";import{consumeDeadlineOnWake as ke}from"../feed/messages.js";import{isParked as J,transition as O}from"./lifecycle.js";import{publishNotice as ge}from"./close.js";import{InputError as E}from"../io.js";import{buildPiArgv as y}from"./launch.js";import{buildReviveKickoff as be,drainBearings as Re,hasRetainedReports as Ee,readGoal as x,readYieldMessage as xe,RUNTIME_RESTART_CONTINUATION as Se}from"./kickoff.js";import{readRoadmap as j}from"./roadmap.js";import{encodeKickoffOrigin as $e,KICKOFF_ORIGIN_ENV as Ce}from"./stamp/protocol.js";import{carryInitialInput as V}from"../runs/initial-input.js";import{headlessBrokerHost as Ne,brokerLaunchJson as Fe}from"./host.js";import{isCloudRole as Ae}from"../canvas/person.js";import{asNodePerson as Oe}from"../../daemon/reconcilers/node-lifecycle/node-person.js";import{processRunner as Pe}from"./runner/process.js";import{runnerForEnvironment as X}from"./runner/index.js";import{MachineOfflineError as Y}from"./runner/machine/ops.js";import{blaxelEnvironmentOf as q}from"./blaxel-environment.js";import{recordLaunchFailure as Be}from"../../daemon/reconcilers/node-lifecycle/launch-failure.js";import{acceptedRelease as Q,remoteMachineEnvironmentOf as De,checkBilledWake as Te,EnvironmentImagePending as Me,imageForWake as Le}from"../../daemon/reconcilers/node-lifecycle/remote-wake.js";import{ExecutionCapReached as ze,liveExecutionForNode as He,setExecutionLaunchJson as Ge}from"../canvas/executions.js";import{isDrained as Ue}from"../../daemon/drain.js";import{appMemoryFull as Ke,appMemoryTooSmall as We,boundFleet as Z,brokerCapReached as I,brokerThresholdsForDaemon as P}from"./fleet.js";import{admitBrokerMemory as Je}from"./memory-admission.js";import{beginBootFaultAttempt as je,clearFault as Ve,hasAdmittedTurn as Xe,readFault as Ye}from"../canvas/recovery.js";import{clearNodeLedger as ee,forkNodeLedger as qe,noticeChangedWhileDone as Qe}from"./ledger.js";import{forkSourceNode as Ze,rootOfSpine as Ie}from"./nodes.js";import{ApiError as er}from"../../api/errors.js";import{grantSnapshotMissing as rr}from"../../daemon/readiness.js";import{checkGrantActive as ir,checkStart as tr}from"./start-check.js";import{isReviewCompanionBound as nr}from"../review/companion.js";import{assertProfileActive as ar}from"../profiles/manifest.js";import{isPidAlive as or}from"../canvas/pid.js";import{crtrHome as sr,jobDir as cr}from"../canvas/paths.js";import{contextDir as lr,ensureNodeDirs as ur,nodeAgentDir as fr}from"../canvas/node-agent-paths.js";import{discoverLifecycleHookRegistry as wr}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as hr}from"../command-hooks/transport/exec-lifecycle.js";async function pr(e,r){const i=e.pi_session_file,t=i?_(i):null;if(t===null)return{};try{const n=await d().header(t);return r?{resumeSessionPath:n.path}:{resumeSessionPath:n.path,newCycle:!0}}catch(n){if(n instanceof G)return{};throw n}}s(pr,"resumeArgs");async function re(e){const r=_(e);if(r===null)return!1;try{return await d().header(r),!0}catch(i){if(i instanceof G)return!1;throw i}}s(re,"conversationExists");async function dr(e){const r=_(e);return r===null?!0:(await d().read(r)).entries.some(i=>i.type==="message")}s(dr,"sessionHasConversation");async function mr(e){const r=_(e);if(r===null)return!0;const i=(await d().header(r)).header.cwd;return typeof i!="string"||H(i)}s(mr,"sessionCwdExists");async function vr(e,r,i,t){const n=r.pi_session_file;if(!n||!await re(n))return{};const u=await we(n);return u!==null&&u.node_id!==e&&or(u.pi_pid)?{}:t&&!await mr(n)?{}:await pr(r,i)}s(vr,"resumableSessionArgs");async function _r(e){return await j(e)===null&&await xe(e)===null&&!await Ee(e)}s(_r,"isUnstartedBirth");async function fi(e){const r=await x(e);if(r!==null&&r.trim()!=="")return!0;const i=await j(e);return i!==null&&i.trim()!==""}s(fi,"hasFreshGroundState");async function wi(e,r){const i=await ie(e,r,!0);if(i.parked)throw new Error(`reviveNode: internal parked decision for activating revive ${e}`);return i.result}s(wi,"reviveNode");async function hi(e,r,i){return ie(e,{...r,viewerAttach:!0},i)}s(hi,"decideAttachRevive");async function ie(e,r,i){const t=Ae()?await R(e):null;return t===null?await te(e,r,i):await Oe({node_id:e,sub:t.sub??null,profile_id:t.profile_id??null},()=>te(e,r,i))}s(ie,"decideRevive");async function te(e,r,i){let t=await R(e);if(t===null)throw new Error(`reviveNode: unknown node ${e}`);if(t=await R(e)??t,t.run_id&&(await R(t.run_id))?.deleting_at)throw new Error("run is deleting");if(t.final_report!==null)throw new Error(`reviveNode: refusing to revive ${e} \u2014 its finalization latch is set (final_report=${t.final_report}). A final landed between the caller's reopen-gate check and this revive; re-run with --reopen if this retask is still wanted.`);ar(t.profile_id),ue(t.grantee);const n=Z(),u=t.grantee==="app:terminal"&&await rr();if(!await n.has(e)&&!await n.isClaimed(e)&&r.wakeReason!=="runtime-restart-abort"&&r.viewerAttach!==!0&&!(!i&&t.lifecycle==="resident"&&J(t))&&(await ir(t),await tr(t),await q(t.profile_id??null)!==null&&await Te(t)),await n.isClaimed(e))return await n.has(e)&&await O(e,t.intent==="refresh"?"refresh-launch":"revive"),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"already-live"}};if(!i&&t.lifecycle==="resident"&&J(t))return{parked:!0};if(u){if(r.capacity==="refuse")throw new er(503,"runtime_starting","the first grant snapshot from the directory has not committed");return await ne(e,t,{reason:"grant_snapshot"}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}const k=await Ue();if(k&&r.capacity==="refuse")throw new Error(`the daemon is drained for an import; ${e} cannot start until it ends`);const m=!k&&await n.reserveSlot(e);let o=null;if(m){try{o=await Je(e)}catch(w){throw n.releaseReservation(e),w}o.verdict!=="admitted"&&n.releaseReservation(e)}if(o?.verdict==="too_small")throw We(o);if(!m||o?.verdict==="denied"){if(r.capacity==="refuse")throw o?.verdict==="denied"?Ke(o):I(P().automaticReviveCap,await n.occupancy());return await ne(e,t,k?{reason:"drain"}:o?.verdict==="denied"?{reason:"app_memory",free_bytes:o.free_bytes,needed_bytes:o.needed_bytes}:{reason:"broker_cap",live_count:await n.occupancy(),hard_cap:P().automaticReviveCap}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}try{return{parked:!1,result:await gr(e,t,r)}}finally{n.releaseReservation(e)}}s(te,"decideReviveAsCaller");async function ne(e,r,i){r.frozen_at==null&&(await _e(e,new Date().toISOString()),await me(e,{reason:"frozen"}),W({level:"info",event:"broker.frozen",node_id:e,fields:i}))}s(ne,"freezeForWait");async function yr(e,r){const i=await q(r.profile_id??null),t=await De(r.profile_id??null)!==null;if(!(i!==null||t)&&!H(r.cwd)){const u=r.fork_from!=null?`Restore ${r.cwd}, then revive the fork normally with \`crtr node lifecycle revive ${e}\`.`:r.managed_worktree?.state==="open"?"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon recovery.":`Recreate ${r.cwd}, or repair it with \`crtr node config --cwd <path> --node ${e}\`; durable node work resumes in a fresh conversation. Then retry \`crtr node lifecycle revive ${e}\`.`;throw new E({error:"cwd_missing",message:`${e} cannot be revived \u2014 its recorded cwd no longer exists: ${r.cwd}`,next:u})}return{blaxelEnvironment:i,remoteMachine:t}}s(yr,"assertRecordedCwdExists");function pi(e,r){const i=r.managed_worktree;if(!(i?.state!=="closed"||i.cleanup!=="complete"||r.cwd!==i.path))throw new E({error:"checkout_removed",message:`${e} cannot be revived \u2014 cleanup removed its checkout ${i.path} and branch ${i.branch}`,next:`Start a new node in ${i.repo_root}.`})}s(pi,"assertCheckoutNotRemoved");async function kr(e,r,i){const t=wr(r.cwd,r.profile_id).plans.get("node:start")??[];await hr(t,{node:{id:e,name:r.name,kind:r.kind,mode:r.mode,lifecycle:r.lifecycle,cwd:r.cwd,nodeDir:await fr(e),contextDir:await lr(e),jobDir:cr(e)},runtime:{isBirth:i,canvasHome:sr(),profile:r.profile_id??null}})}s(kr,"runNodeStartHooks");async function gr(e,r,i){const{blaxelEnvironment:t,remoteMachine:n}=await yr(e,r),u=t!==null||n;r.host_kind!=="broker"&&(await F(e,{host_kind:"broker"}),r.host_kind="broker"),r.review_binding!=null&&!await nr(e)&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await U(e),r.pi_session_id=null,r.pi_session_file=null);const m=r.fork_from!=null&&r.pi_session_id==null,o=r.fork_source_file;if(m&&(typeof o!="string"||!fe(o)))throw new E({error:"fork_source_invalid",message:`${e} cannot be revived \u2014 its resolved fork source file is missing or invalid.`,next:`Restore the node's fork source metadata, then retry \`crtr node lifecycle revive ${e}\`.`});const w=m&&typeof o=="string";if(w&&!await re(o))throw new E({error:"fork_from_missing",message:`${e} cannot be revived \u2014 its fork source no longer exists: ${o}`,next:`Restore ${o}, or update the node's fork source, then retry \`crtr node lifecycle revive ${e}\`.`});const{automaticReviveCap:ae}=P();if(t!==null){const c=await Le(t);if(c.state==="pending")throw new Me(t,c.error)}const oe=t!==null?X("blaxel"):n?X("machine"):Pe;let f;try{f=await he(e,{daemonEpoch:Z().epoch(),cap:ae,...t!==null?{runner:"blaxel",release:Q()}:n?{runner:"machine",release:Q()}:{}})}catch(c){if(c instanceof ze)throw I(c.cap,c.live);if(c instanceof pe)return{window:null,session:r.tmux_session??null,resumed:!1,outcome:"already-live"};throw c}try{r.cycles=(r.cycles??0)+1,await F(e,{cycles:r.cycles});const S=r.intent==="refresh"||r.cycle_pending===!0?!1:i.resume,p=w?{}:await vr(e,r,S,!u),g=p.resumeSessionPath!==void 0,B=g&&p.newCycle===!0,v=g&&!B,D=!g&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&await _r(e),$=v&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&!await Xe(e)&&!await dr(p.resumeSessionPath)?(await x(e))?.trim():void 0,T=$!==void 0&&$!=="",se=w||D||T,M=r.cycle_pending===!0||B;await F(e,{cycle_pending:M}),r.cycle_pending=M,!w&&!g&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await U(e),r.pi_session_id=null,r.pi_session_file=null);let l,h=null;const C=s(()=>({type:"runtime",kind:"kickoff",...r.spawned_by!=null&&r.spawned_by!==""?{spawnedBy:r.spawned_by}:{}}),"birthOrigin");if(w){const a=await x(e),N=_(o);if(N===null)throw new Error(`invalid fork source ${o}`);const ce=(await d().header(await d().fork(N,e))).path;l=y(r,{resumeSessionPath:ce,...a!=null&&a!==""?{prompt:a}:{}}),a!=null&&a!==""&&(h=C()),await qe(e,(await Ze(o))?.node_id??null)}else if(T)l=y(r,{...p,prompt:$}),h=C(),await V(l,r);else if(v)l=y(r,{...p,...i.wakeReason==="runtime-restart-abort"?{prompt:Se}:{}}),i.wakeReason==="runtime-restart-abort"&&(h={type:"runtime",kind:"restart-continuation"});else if(D){const a=(await x(e))?.trim();l=y(r,a!==void 0&&a!==""?{prompt:a}:{}),a!==void 0&&a!==""&&(h=C(),await V(l,r)),await ee(e)}else{const a=await Re(r,f);l=y(r,{...p,prompt:await be(r,a,i.wakeReason==="runtime-restart-abort"?void 0:i.wakeReason)}),r.run_id&&a.unreadMessageIds?.length&&(l.env.CRTR_KICKOFF_MESSAGE_IDS=JSON.stringify(a.unreadMessageIds)),h=i.wakeReason!==void 0&&i.wakeReason!=="runtime-restart-abort"?{type:"runtime",kind:"wake",wake:i.wakeReason}:{type:"runtime",kind:"revive",cycle:r.cycles??0},await ee(e)}l.env={...l.env,CRTR_SUBTREE:await Ie(e)},h!==null&&(l.env[Ce]=$e(h)),r.status==="done"&&r.last_settled_at!=null&&await Qe(e,r.last_settled_at),await O(e,r.intent==="refresh"?"refresh-launch":"revive"),(await Ye(e))?.op!=="conversation_write_failed"&&await Ve(e,{preserveEpisode:!0});const L=await je(e);i.recovery!==!0&&i.viewerAttach!==!0&&await ke(e),await ur(e,r.grantee),await kr(e,r,se),l.env={...l.env,CRTR_EXECUTION_ID:f};const z=await Fe(e,l,r.cwd);await Ge(f,z);let b;try{const a=await He(e);if(b=await oe.start({executionId:f,nodeId:e,attempt:a?.attempt??1,release:a?.release??"",launchJson:z,cwd:r.cwd,resuming:v}),!u&&b.pid===null)throw new Error(`broker host returned no pid for ${e}`)}catch(a){if(a instanceof Y)throw a;try{await O(e,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:a instanceof Error?a.message:String(a)}}}),await ge(e,"notice.crash",`Child crashed \u2014 ${ye(r)} (${e}) failed to relaunch and is now dead: ${a.message}
2
2
 
3
- It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`,{reason:"child-crashed",child:e})}catch{}throw await F(f,{reason:"launch_failed"}),new Error(`[broker] refusing to revive ${e}: ${a.message}`)}if(await ve(e,new Date().toISOString()),u)return await K(e),{window:null,session:r.tmux_session??null,resumed:v,faultExplanation:L.explanation,outcome:"launched"};if(await me(f,e,b.pid)==="shutdown")throw await F(f,{reason:"superseded"}),Ne.teardown(e),new Error(`[broker] refusing to revive ${e}: execution was superseded during launch`);return await K(e),{window:null,session:r.tmux_session??null,resumed:v,launch:b,faultExplanation:L.explanation,outcome:"launched"}}catch(l){throw l instanceof Y&&l.sent||(await F(f,{reason:"launch_failed"}),await Be(f,l).catch(x=>{W({level:"warn",event:"broker.launch_failure.unrecorded",node_id:e,error:x})})),l}}s(gr,"launchRevive");export{yr as assertRecordedCwdExists,hi as decideAttachRevive,fi as hasFreshGroundState,pr as resumeArgs,wi as reviveNode,kr as runNodeStartHooks};
3
+ It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`,{reason:"child-crashed",child:e})}catch{}throw await A(f,{reason:"launch_failed"}),new Error(`[broker] refusing to revive ${e}: ${a.message}`)}if(await ve(e,new Date().toISOString()),u)return await K(e),{window:null,session:r.tmux_session??null,resumed:v,faultExplanation:L.explanation,outcome:"launched"};if(await de(f,e,b.pid)==="shutdown")throw await A(f,{reason:"superseded"}),Ne.teardown(e),new Error(`[broker] refusing to revive ${e}: execution was superseded during launch`);return await K(e),{window:null,session:r.tmux_session??null,resumed:v,launch:b,faultExplanation:L.explanation,outcome:"launched"}}catch(c){throw c instanceof Y&&c.sent||(await A(f,{reason:"launch_failed"}),await Be(f,c).catch(S=>{W({level:"warn",event:"broker.launch_failure.unrecorded",node_id:e,error:S})})),c}}s(gr,"launchRevive");export{pi as assertCheckoutNotRemoved,yr as assertRecordedCwdExists,hi as decideAttachRevive,fi as hasFreshGroundState,pr as resumeArgs,wi as reviveNode,kr as runNodeStartHooks};
@@ -22,6 +22,9 @@ export declare const RECIPE_PI_AGENT_DIR = "/var/lib/crtr/recipe-pi-agent";
22
22
  export declare const BLAXEL_TOML_FILE = "blaxel.toml";
23
23
  export declare const BLAXEL_TOML = "[build]\nslim = false\n";
24
24
  export declare const SETUP_SCRIPT_FILE = "recipe-setup.sh";
25
+ /** The run user's npmrc. pnpm 12 ignores an env-expanded `_authToken` in a repository's `.npmrc`, so the GitHub Packages auth line lives here; it names the
26
+ * variable, never its value. `store-dir` pins one pnpm store in the image that every repository's `pnpm install` links from. */
27
+ export declare const RUN_USER_NPMRC: string[];
25
28
  export declare const REPOS_DIR = "repos";
26
29
  /** Where the image keeps the setup script's output, and its exit status when it failed. `sandbox-start.mjs` reads both (it derives them from `/work/.crtr`). */
27
30
  export declare const SETUP_LOG_FILE = "/work/.crtr/setup.log";
@@ -1,8 +1,8 @@
1
- var Y=Object.defineProperty;var c=(t,r)=>Y(t,"name",{value:r,configurable:!0});import{spawn as j}from"node:child_process";import{constants as P,lstatSync as q,mkdirSync as z,readFileSync as W,readdirSync as J,readlinkSync as X,rmSync as V,writeFileSync as b}from"node:fs";import{join as E,relative as Z}from"node:path";import{crc32 as Q,deflateRawSync as tt}from"node:zlib";import{BlaxelApiError as et}from"./client.js";const rt="public.ecr.aws/docker/library/node:24-alpine",nt="ghcr.io/blaxel-ai/sandbox:latest",f="crtr",D="/var/lib/crtr/recipe-pi-agent",ot="blaxel.toml",st=`[build]
1
+ var j=Object.defineProperty;var c=(t,r)=>j(t,"name",{value:r,configurable:!0});import{spawn as q}from"node:child_process";import{constants as D,lstatSync as z,mkdirSync as W,readFileSync as J,readdirSync as X,readlinkSync as V,rmSync as Z,writeFileSync as b}from"node:fs";import{join as g,relative as Q}from"node:path";import{crc32 as tt,deflateRawSync as et}from"node:zlib";import{BlaxelApiError as rt}from"./client.js";const nt="public.ecr.aws/docker/library/node:24-alpine",ot="ghcr.io/blaxel-ai/sandbox:latest",p="crtr",B="/var/lib/crtr/recipe-pi-agent",st="blaxel.toml",it=`[build]
2
2
  slim = false
3
- `,it="1.1.0",_="recipe-setup.sh",L="repos",B="/work/.crtr/setup.log",G="/work/.crtr/setup-failed",C="/usr/local/bin/gh",at=["#!/bin/sh",'token=$(printf "protocol=https\\nhost=github.com\\n\\n" | git credential fill 2>/dev/null | sed -n "s/^password=//p")','[ -n "$token" ] && export GH_TOKEN="$token"','exec /usr/bin/gh "$@"'],R=c(t=>`'${t.replace(/'/g,"'\\''")}'`,"shellQuote"),ct=c(t=>(t??"").split(`
4
- `).map(r=>r.trim()).filter(r=>r!==""),"lines"),$=c((t,r)=>`RUN { ${r}; } >> ${B} 2>&1 || echo ${R(t)} "exited $?" >> ${G}`,"guarded");function lt(t,r,i=!1){const s=ct(t.pi_packages),a=t.setup_script!==null&&t.setup_script.trim()!=="",n=[`FROM ${rt}`,"RUN apk add --no-cache bash git curl ripgrep github-cli",`RUN printf '%s\\n' ${at.map(R).join(" ")} > ${C} && chmod 755 ${C}`,`COPY --from=${nt} /sandbox-api /usr/local/bin/sandbox-api`,`RUN adduser -D -h /home/${f} -s /bin/sh ${f} && mkdir -p /work/.crtr ${D} && chown -R ${f} /work /var/lib/crtr`],e=[`${n[0]} AS build`,...i?["ARG NODE_AUTH_TOKEN"]:[],...n.slice(1),`RUN rm -f ${G} ${B}`,$("npm install -g pnpm","npm install -g pnpm && mkdir -p /var/lib/postgresql")];t.repositories.length>0&&e.push(`COPY --chown=${f} ${L}/ /work/`),s.length>0&&e.push($("npm install pi",`npm install -g @earendil-works/pi-coding-agent@${it}`)),a&&e.push(`COPY ${_} /tmp/${_}`),e.push("WORKDIR /work");for(const o of s)e.push($(`pi install ${o}`,`HOME=/var/lib/crtr PI_CODING_AGENT_DIR=${D} pi install ${R(o)}`));a&&e.push($("setup script",`bash /tmp/${_}`)),e.push($("finalize",`echo ${Math.trunc(r)} > /work/.crtr/recipe-revision && chown -R ${f} /work /home/${f} /var/lib/crtr`)),e.push("",...n);for(const o of["/work",`/home/${f}`,"/var/lib/crtr"])e.push(`COPY --from=build --chown=${f}:${f} ${o} ${o}`);for(const o of["/usr/local","/usr","/etc","/lib"])e.push(`COPY --from=build ${o} ${o}`);return e.push("COPY --from=build /var/lib/postgresql /var/lib/postgresql"),e.push("RUN if getent passwd postgres >/dev/null; then chown -R postgres:postgres /var/lib/postgresql; fi"),i&&e.push(`RUN rm -f /work/.npmrc /home/${f}/.npmrc`),e.push(`USER ${f}`,"WORKDIR /work",'ENTRYPOINT ["/usr/local/bin/sandbox-api"]',""),e.join(`
5
- `)}c(lt,"recipeDockerfile");const pt=c((t,r,i)=>new Promise((s,a)=>{const n=j("git",t,{cwd:i,env:{...process.env,...r,GIT_TERMINAL_PROMPT:"0"},stdio:["ignore","ignore","pipe"]});let e="";n.stderr.on("data",o=>{e+=o.toString()}),n.on("error",a),n.on("close",o=>{o===0?s():a(new Error(`git ${t[0]} failed (${o}): ${e.slice(0,300)}`))})}),"runGit");async function It(t){const r=t.git??pt,i=t.packagesToken??null,s=t.cloneUrl??(n=>`https://github.com/${n}.git`);z(E(t.dir,L),{recursive:!0});const a=t.token===null?{}:{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:"http.https://github.com/.extraheader",GIT_CONFIG_VALUE_0:`AUTHORIZATION: basic ${Buffer.from(`x-access-token:${t.token}`).toString("base64")}`};for(const n of t.recipe.repositories){if(!/^[A-Za-z0-9._-]+$/.test(n.name)||n.name==="."||n.name==="..")throw new Error(`repository name ${JSON.stringify(n.name)} is not a plain directory name`);await r(["clone","--quiet","--branch",n.default_branch,s(n.github_full_name),E(L,n.name)],a,t.dir)}b(E(t.dir,ot),st),b(E(t.dir,"Dockerfile"),lt(t.recipe,t.revision,i!==null)),i!==null&&b(E(t.dir,".env.build"),`NODE_AUTH_TOKEN=${i}
6
- `,{mode:384}),t.recipe.setup_script!==null&&t.recipe.setup_script.trim()!==""&&b(E(t.dir,_),t.recipe.setup_script.endsWith(`
3
+ `,at="1.1.0",_="recipe-setup.sh",ct=["@northlight-systems:registry=https://npm.pkg.github.com","//npm.pkg.github.com/:_authToken=${NODE_AUTH_TOKEN}",`store-dir=/home/${p}/.local/share/pnpm/store`],G=c(()=>`printf '%s\\n' ${ct.map(t=>`'${t}'`).join(" ")} > /home/${p}/.npmrc`,"writeRunUserNpmrc"),R="repos",U="/work/.crtr/setup.log",M="/work/.crtr/setup-failed",C="/usr/local/bin/gh",lt=["#!/bin/sh",'token=$(printf "protocol=https\\nhost=github.com\\n\\n" | git credential fill 2>/dev/null | sed -n "s/^password=//p")','[ -n "$token" ] && export GH_TOKEN="$token"','exec /usr/bin/gh "$@"'],N=c(t=>`'${t.replace(/'/g,"'\\''")}'`,"shellQuote"),pt=c(t=>(t??"").split(`
4
+ `).map(r=>r.trim()).filter(r=>r!==""),"lines"),E=c((t,r)=>`RUN { ${r}; } >> ${U} 2>&1 || echo ${N(t)} "exited $?" >> ${M}`,"guarded");function ut(t,r,i=!1){const s=pt(t.pi_packages),a=t.setup_script!==null&&t.setup_script.trim()!=="",n=[`FROM ${nt}`,"RUN apk add --no-cache bash git curl ripgrep github-cli",`RUN printf '%s\\n' ${lt.map(N).join(" ")} > ${C} && chmod 755 ${C}`,`COPY --from=${ot} /sandbox-api /usr/local/bin/sandbox-api`,`RUN adduser -D -h /home/${p} -s /bin/sh ${p} && mkdir -p /work/.crtr ${B} && chown -R ${p} /work /var/lib/crtr`],e=[`${n[0]} AS build`,...i?["ARG NODE_AUTH_TOKEN"]:[],...n.slice(1),`RUN rm -f ${M} ${U}`,E("npm install -g pnpm","npm install -g pnpm && mkdir -p /var/lib/postgresql")];t.repositories.length>0&&e.push(`COPY --chown=${p} ${R}/ /work/`),s.length>0&&e.push(E("npm install pi",`npm install -g @earendil-works/pi-coding-agent@${at}`)),a&&e.push(`COPY ${_} /tmp/${_}`),e.push("WORKDIR /work"),e.push(`RUN ${G()}`);for(const o of t.repositories)e.push(`RUN if [ -f /work/${o.name}/pnpm-lock.yaml ]; then cd /work/${o.name} && HOME=/home/${p} pnpm fetch >> ${U} 2>&1 || echo 'pnpm fetch ${o.name} failed' >> ${U}; fi`);for(const o of s)e.push(E(`pi install ${o}`,`HOME=/var/lib/crtr PI_CODING_AGENT_DIR=${B} pi install ${N(o)}`));a&&e.push(E("setup script",`bash /tmp/${_}`)),e.push(E("finalize",`echo ${Math.trunc(r)} > /work/.crtr/recipe-revision && chown -R ${p} /work /home/${p} /var/lib/crtr`)),e.push("",...n);for(const o of["/work",`/home/${p}`,"/var/lib/crtr"])e.push(`COPY --from=build --chown=${p}:${p} ${o} ${o}`);for(const o of["/usr/local","/usr","/etc","/lib"])e.push(`COPY --from=build ${o} ${o}`);return e.push("COPY --from=build /var/lib/postgresql /var/lib/postgresql"),e.push("RUN if getent passwd postgres >/dev/null; then chown -R postgres:postgres /var/lib/postgresql; fi"),i&&e.push("RUN rm -f /work/.npmrc",`RUN ${G()} && chown ${p}:${p} /home/${p}/.npmrc`),e.push(`USER ${p}`,"WORKDIR /work",'ENTRYPOINT ["/usr/local/bin/sandbox-api"]',""),e.join(`
5
+ `)}c(ut,"recipeDockerfile");const dt=c((t,r,i)=>new Promise((s,a)=>{const n=q("git",t,{cwd:i,env:{...process.env,...r,GIT_TERMINAL_PROMPT:"0"},stdio:["ignore","ignore","pipe"]});let e="";n.stderr.on("data",o=>{e+=o.toString()}),n.on("error",a),n.on("close",o=>{o===0?s():a(new Error(`git ${t[0]} failed (${o}): ${e.slice(0,300)}`))})}),"runGit");async function _t(t){const r=t.git??dt,i=t.packagesToken??null,s=t.cloneUrl??(n=>`https://github.com/${n}.git`);W(g(t.dir,R),{recursive:!0});const a=t.token===null?{}:{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:"http.https://github.com/.extraheader",GIT_CONFIG_VALUE_0:`AUTHORIZATION: basic ${Buffer.from(`x-access-token:${t.token}`).toString("base64")}`};for(const n of t.recipe.repositories){if(!/^[A-Za-z0-9._-]+$/.test(n.name)||n.name==="."||n.name==="..")throw new Error(`repository name ${JSON.stringify(n.name)} is not a plain directory name`);await r(["clone","--quiet","--branch",n.default_branch,s(n.github_full_name),g(R,n.name)],a,t.dir)}b(g(t.dir,st),it),b(g(t.dir,"Dockerfile"),ut(t.recipe,t.revision,i!==null)),i!==null&&b(g(t.dir,".env.build"),`NODE_AUTH_TOKEN=${i}
6
+ `,{mode:384}),t.recipe.setup_script!==null&&t.recipe.setup_script.trim()!==""&&b(g(t.dir,_),t.recipe.setup_script.endsWith(`
7
7
  `)?t.recipe.setup_script:`${t.recipe.setup_script}
8
- `)}c(It,"prepareBuildDir");function M(t,r,i){for(const s of J(r).sort()){const a=E(r,s),n=q(a),e=Z(t,a).split("\\").join("/");n.isDirectory()?M(t,a,i):n.isSymbolicLink()?i.push({name:e,data:Buffer.from(X(a)),mode:P.S_IFLNK|511}):n.isFile()&&i.push({name:e,data:W(a),mode:P.S_IFREG|n.mode&511})}}c(M,"walk");function dt(t){const r=[];M(t,t,r);const i=[],s=[];let a=0;for(const o of r){const d=Buffer.from(o.name),g=tt(o.data),I=Q(o.data),p=Buffer.alloc(30);p.writeUInt32LE(67324752,0),p.writeUInt16LE(20,4),p.writeUInt16LE(2048,6),p.writeUInt16LE(8,8),p.writeUInt32LE(33,12),p.writeUInt32LE(I,14),p.writeUInt32LE(g.length,18),p.writeUInt32LE(o.data.length,22),p.writeUInt16LE(d.length,26),i.push(p,d,g);const l=Buffer.alloc(46);l.writeUInt32LE(33639248,0),l.writeUInt16LE(788,4),l.writeUInt16LE(20,6),l.writeUInt16LE(2048,8),l.writeUInt16LE(8,10),l.writeUInt32LE(33,14),l.writeUInt32LE(I,16),l.writeUInt32LE(g.length,20),l.writeUInt32LE(o.data.length,24),l.writeUInt16LE(d.length,28),l.writeUInt32LE(o.mode<<16>>>0,38),l.writeUInt32LE(a,42),s.push(l,d),a+=p.length+d.length+g.length}const n=Buffer.concat(s),e=Buffer.alloc(22);return e.writeUInt32LE(101010256,0),e.writeUInt16LE(r.length,8),e.writeUInt16LE(r.length,10),e.writeUInt32LE(n.length,12),e.writeUInt32LE(a,16),Buffer.concat([...i,n,e])}c(dt,"zipDirectory");async function T(t,r,i,s,a=[]){const n=`${t.controlUrl??"https://api.blaxel.ai/v0"}${i}`,e=await(t.fetch??fetch)(n,{method:r,headers:{authorization:`Bearer ${t.apiKey}`,"x-blaxel-workspace":t.workspace,"content-type":"application/json"},...s===void 0?{}:{body:JSON.stringify(s)}}),o=await e.text();let d=null;if(o!=="")try{d=JSON.parse(o)}catch{d={raw:o}}if(!e.ok&&!a.includes(e.status))throw new et(e.status,null,`Blaxel ${r} ${n} failed (${e.status}): ${o.slice(0,300)}`);return{status:e.status,headers:e.headers,json:d}}c(T,"api");async function F(t,r){const{status:i,json:s}=await T(t,"GET",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404]);return i===404?null:s}c(F,"getImage");async function bt(t,r){await T(t,"DELETE",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404])}c(bt,"deleteImage");const ut=60*6e4;async function _t(t,r,i,s={}){const a=s.sleep??(h=>new Promise(u=>setTimeout(u,h))),n=s.now??Date.now,e=n(),o=await F(t,r),d=new Set((o?.spec?.tags??[]).map(h=>h.name)),g=c(h=>(h?.metadata?.events??[]).map(u=>Date.parse(u.time??"")).filter(u=>!Number.isNaN(u)),"eventTimes"),I=Math.max(-1/0,...g(o)),l=(await T(t,"POST","/images",{resourceType:"sandbox",name:r})).headers.get("x-blaxel-upload-url");if(l===null)throw new Error(`Blaxel gave no upload URL for image ${r}`);const x=await(t.fetch??fetch)(l,{method:"PUT",headers:{"content-type":"application/zip"},body:new Uint8Array(dt(i))});if(!x.ok)throw new Error(`uploading the build context of image ${r} failed (${x.status}): ${(await x.text()).slice(0,300)}`);const N=s.timeoutMs??ut,H=e+N;let O=null;for(;;){const h=await F(t,r),u=h?.metadata?.status,k=g(h).filter(m=>m>I).sort((m,U)=>m-U);if(u==="BUILT"&&k.length>=2){O??=n();const m=(h?.spec?.tags??[]).filter(w=>w.name!==void 0),U=k[0],S=c(w=>Date.parse(w??"")>=U,"touchedSince"),A=m.filter(w=>!d.has(w.name)||S(w.createdAt)||S(w.updatedAt)),v=n()-O>=(s.tagGraceMs??6e4),y=(A.length>0?A:v?m:[]).sort((w,K)=>(K.updatedAt??"").localeCompare(w.updatedAt??""))[0]?.name;if(y!==void 0)return{ref:`sandbox/${r}:${y}`,buildMs:n()-e};if(v)throw new Error(`Blaxel built image ${r} but no tag appeared`)}if(u==="FAILED"||u==="TERMINATED"){const m=h?.metadata?.events??[];throw new Error(`building image ${r} ${u.toLowerCase()}: ${m[m.length-1]?.message??"no message"}`)}if(n()>H)throw new Error(`building image ${r} did not finish within ${N} ms (last status ${u??"none"})`);await a(s.pollMs??3e3)}}c(_t,"buildImage");const xt=c(t=>`env-${t}`,"environmentImageName");function Ut(t){V(t,{recursive:!0,force:!0})}c(Ut,"removeBuildDir");export{st as BLAXEL_TOML,ot as BLAXEL_TOML_FILE,ut as BUILD_TIMEOUT_MS,C as GH_WRAPPER_PATH,rt as NODE_BASE_IMAGE,D as RECIPE_PI_AGENT_DIR,L as REPOS_DIR,f as RUN_USER,nt as SANDBOX_API_IMAGE,G as SETUP_FAILED_FILE,B as SETUP_LOG_FILE,_ as SETUP_SCRIPT_FILE,_t as buildImage,bt as deleteImage,xt as environmentImageName,F as getImage,It as prepareBuildDir,lt as recipeDockerfile,Ut as removeBuildDir,dt as zipDirectory};
8
+ `)}c(_t,"prepareBuildDir");function F(t,r,i){for(const s of X(r).sort()){const a=g(r,s),n=z(a),e=Q(t,a).split("\\").join("/");n.isDirectory()?F(t,a,i):n.isSymbolicLink()?i.push({name:e,data:Buffer.from(V(a)),mode:D.S_IFLNK|511}):n.isFile()&&i.push({name:e,data:J(a),mode:D.S_IFREG|n.mode&511})}}c(F,"walk");function ht(t){const r=[];F(t,t,r);const i=[],s=[];let a=0;for(const o of r){const d=Buffer.from(o.name),$=et(o.data),I=tt(o.data),u=Buffer.alloc(30);u.writeUInt32LE(67324752,0),u.writeUInt16LE(20,4),u.writeUInt16LE(2048,6),u.writeUInt16LE(8,8),u.writeUInt32LE(33,12),u.writeUInt32LE(I,14),u.writeUInt32LE($.length,18),u.writeUInt32LE(o.data.length,22),u.writeUInt16LE(d.length,26),i.push(u,d,$);const l=Buffer.alloc(46);l.writeUInt32LE(33639248,0),l.writeUInt16LE(788,4),l.writeUInt16LE(20,6),l.writeUInt16LE(2048,8),l.writeUInt16LE(8,10),l.writeUInt32LE(33,14),l.writeUInt32LE(I,16),l.writeUInt32LE($.length,20),l.writeUInt32LE(o.data.length,24),l.writeUInt16LE(d.length,28),l.writeUInt32LE(o.mode<<16>>>0,38),l.writeUInt32LE(a,42),s.push(l,d),a+=u.length+d.length+$.length}const n=Buffer.concat(s),e=Buffer.alloc(22);return e.writeUInt32LE(101010256,0),e.writeUInt16LE(r.length,8),e.writeUInt16LE(r.length,10),e.writeUInt32LE(n.length,12),e.writeUInt32LE(a,16),Buffer.concat([...i,n,e])}c(ht,"zipDirectory");async function k(t,r,i,s,a=[]){const n=`${t.controlUrl??"https://api.blaxel.ai/v0"}${i}`,e=await(t.fetch??fetch)(n,{method:r,headers:{authorization:`Bearer ${t.apiKey}`,"x-blaxel-workspace":t.workspace,"content-type":"application/json"},...s===void 0?{}:{body:JSON.stringify(s)}}),o=await e.text();let d=null;if(o!=="")try{d=JSON.parse(o)}catch{d={raw:o}}if(!e.ok&&!a.includes(e.status))throw new rt(e.status,null,`Blaxel ${r} ${n} failed (${e.status}): ${o.slice(0,300)}`);return{status:e.status,headers:e.headers,json:d}}c(k,"api");async function H(t,r){const{status:i,json:s}=await k(t,"GET",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404]);return i===404?null:s}c(H,"getImage");async function Ut(t,r){await k(t,"DELETE",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404])}c(Ut,"deleteImage");const ft=60*6e4;async function xt(t,r,i,s={}){const a=s.sleep??(f=>new Promise(h=>setTimeout(h,f))),n=s.now??Date.now,e=n(),o=await H(t,r),d=new Set((o?.spec?.tags??[]).map(f=>f.name)),$=c(f=>(f?.metadata?.events??[]).map(h=>Date.parse(h.time??"")).filter(h=>!Number.isNaN(h)),"eventTimes"),I=Math.max(-1/0,...$(o)),l=(await k(t,"POST","/images",{resourceType:"sandbox",name:r})).headers.get("x-blaxel-upload-url");if(l===null)throw new Error(`Blaxel gave no upload URL for image ${r}`);const x=await(t.fetch??fetch)(l,{method:"PUT",headers:{"content-type":"application/zip"},body:new Uint8Array(ht(i))});if(!x.ok)throw new Error(`uploading the build context of image ${r} failed (${x.status}): ${(await x.text()).slice(0,300)}`);const T=s.timeoutMs??ft,K=e+T;let O=null;for(;;){const f=await H(t,r),h=f?.metadata?.status,y=$(f).filter(m=>m>I).sort((m,L)=>m-L);if(h==="BUILT"&&y.length>=2){O??=n();const m=(f?.spec?.tags??[]).filter(w=>w.name!==void 0),L=y[0],S=c(w=>Date.parse(w??"")>=L,"touchedSince"),A=m.filter(w=>!d.has(w.name)||S(w.createdAt)||S(w.updatedAt)),v=n()-O>=(s.tagGraceMs??6e4),P=(A.length>0?A:v?m:[]).sort((w,Y)=>(Y.updatedAt??"").localeCompare(w.updatedAt??""))[0]?.name;if(P!==void 0)return{ref:`sandbox/${r}:${P}`,buildMs:n()-e};if(v)throw new Error(`Blaxel built image ${r} but no tag appeared`)}if(h==="FAILED"||h==="TERMINATED"){const m=f?.metadata?.events??[];throw new Error(`building image ${r} ${h.toLowerCase()}: ${m[m.length-1]?.message??"no message"}`)}if(n()>K)throw new Error(`building image ${r} did not finish within ${T} ms (last status ${h??"none"})`);await a(s.pollMs??3e3)}}c(xt,"buildImage");const Lt=c(t=>`env-${t}`,"environmentImageName");function Rt(t){Z(t,{recursive:!0,force:!0})}c(Rt,"removeBuildDir");export{it as BLAXEL_TOML,st as BLAXEL_TOML_FILE,ft as BUILD_TIMEOUT_MS,C as GH_WRAPPER_PATH,nt as NODE_BASE_IMAGE,B as RECIPE_PI_AGENT_DIR,R as REPOS_DIR,p as RUN_USER,ct as RUN_USER_NPMRC,ot as SANDBOX_API_IMAGE,M as SETUP_FAILED_FILE,U as SETUP_LOG_FILE,_ as SETUP_SCRIPT_FILE,xt as buildImage,Ut as deleteImage,Lt as environmentImageName,H as getImage,_t as prepareBuildDir,ut as recipeDockerfile,Rt as removeBuildDir,ht as zipDirectory};
@@ -1,6 +1,6 @@
1
1
  import { type CanvasDb } from './canvas/db.js';
2
2
  import { type RateLimitObservation, type RateLimitScope } from './rate-limit-scope.js';
3
- import { type ManagedProviderId, type RotationConfig, type SubscriptionCredential } from './managed-providers.js';
3
+ import { type ManagedProviderId, type RotationConfig, type SubscriptionCredential, type VendorLimit } from './managed-providers.js';
4
4
  export * from './managed-providers.js';
5
5
  /** One `model_accounts` row without its sealed tokens. */
6
6
  type ProviderRow = {
@@ -42,7 +42,7 @@ export declare const aadOf: (person: string, provider: string, id: string, part:
42
42
  /** Every managed provider's pool for the person in two statements (accounts, cooldowns), tokens opened. A provider with no account is absent. */
43
43
  export declare function readAllSubscriptionPools(): Promise<Map<ManagedProviderId, SubscriptionCredential[]>>;
44
44
  export declare function insertAccount(db: CanvasDb, person: string, provider: ManagedProviderId, row: ProviderRow, entry: StoredCredential): Promise<void>;
45
- export declare function upsertModelCooldown(db: CanvasDb, person: string, provider: string, accountId: string, family: string, until: number, rateLimitedAt: number): Promise<void>;
45
+ export declare function upsertModelCooldown(db: CanvasDb, person: string, provider: string, accountId: string, family: string, until: number, rateLimitedAt: number, vendorLimit?: VendorLimit): Promise<void>;
46
46
  export declare function readSubscriptionPool(provider: ManagedProviderId): Promise<SubscriptionCredential[]>;
47
47
  /** The pool with each account's row id: the stable handle a caller outside the process removes an account by. */
48
48
  export declare function readSubscriptionPoolRows(provider: ManagedProviderId): Promise<Array<{
@@ -62,8 +62,8 @@ export declare function removeAllManagedAccounts(provider: ManagedProviderId): P
62
62
  export declare function removeManagedProvider(provider: ManagedProviderId, label?: string): Promise<SubscriptionCredential[]>;
63
63
  export declare function promoteSubscription(provider: ManagedProviderId, ref: string): Promise<SubscriptionCredential[]>;
64
64
  export declare function markSubscriptionAttempt(provider: ManagedProviderId, ref: string, attemptAt?: number): Promise<SubscriptionCredential[]>;
65
- /** Record a 429 on an account. `scope` defaults to the whole account; a model scope cools only that family on this account, and a 429 older than the newest one already recorded for the same scope is ignored. */
66
- export declare function markSubscriptionRateLimited(provider: ManagedProviderId, ref: string, retryAfterMs: number, attemptAt?: number, rateLimitedAt?: number, scope?: RateLimitScope): Promise<SubscriptionCredential[]>;
65
+ /** Record a 429 on an account. `scope` defaults to the whole account; a model scope cools only that family on this account, and a 429 older than the newest one already recorded for the same scope is ignored. `vendorLimit` replaces that cooldown's stored vendor observation. */
66
+ export declare function markSubscriptionRateLimited(provider: ManagedProviderId, ref: string, retryAfterMs: number, attemptAt?: number, rateLimitedAt?: number, scope?: RateLimitScope, vendorLimit?: VendorLimit): Promise<SubscriptionCredential[]>;
67
67
  /** A call on `modelId` succeeded: clear the account-wide cooldown and auth failure, and that model family's cooldown, unless a newer 429 for the same scope landed after `attemptAt` began. */
68
68
  export declare function markSubscriptionSuccess(provider: ManagedProviderId, ref: string, attemptAt?: number, modelId?: string): Promise<SubscriptionCredential[]>;
69
69
  /** What a vendor 429 asks of the account that received it, parsed once from its headers. The wait is `current` when the caller already holds one, else the vendor's Retry-After, else `defaultMs`; with no Retry-After, a rejected window's reset lengthens it to the window. `vendorReset` is the reset the vendor itself named (Retry-After or the window), never a default. */
@@ -1 +1 @@
1
- var ut=Object.defineProperty;var l=(t,a)=>ut(t,"name",{value:a,configurable:!0});import{createHash as mt,randomUUID as x}from"node:crypto";import{setTimeout as ft}from"node:timers/promises";import{brokerConfigSnapshot as _t}from"./config.js";import{openDb as N,withCanvasWrite as B}from"./canvas/db.js";import{personIdAsync as b}from"./canvas/person.js";import{loadSecretsKey as G,open as J,seal as U}from"./secrets/index.js";import{classifyRateLimit as pt,modelCooldownFamily as ht}from"./rate-limit-scope.js";import{REFRESH_BUSY_PHRASE as At,REFRESH_TIMEOUT_PHRASE as wt}from"./provider-error-recognition.js";import{registerRotationReader as Et}from"./model-routes.js";import{coolingUntilFor as bt,retryAfterMsFromHeaders as yt,getProviderLabel as p,isInvalidRefreshTokenError as Q,DuplicateSubscriptionError as $,ANTHROPIC_PROVIDER_ID as Rt,MAX_RATE_LIMIT_COOLDOWN_MS as j,INVALID_REFRESH_TOKEN_BACKOFF_MS as Z}from"./managed-providers.js";export*from"./managed-providers.js";const v="strong";function tt(t){return t==="ultra"||t==="strong"||t==="medium"||t==="light"?t:void 0}l(tt,"normalizeStrength");function f(t){return t.toLowerCase()}l(f,"key");function V(t){return typeof t=="string"&&t.trim()?t.trim():void 0}l(V,"optionalString");function Lt(t){const a=typeof t.label=="string"?t.label.trim():"",e=typeof t.refresh=="string"?t.refresh.trim():"",n=typeof t.access=="string"?t.access.trim():"",i=Number(t.expires);if(!a||!e||!n||!Number.isFinite(i))return;const r=V(t.accountId),s=V(t.clientId);return{label:a,refresh:e,access:n,expires:i,rateLimitedUntil:Number.isFinite(Number(t.rateLimitedUntil))?Number(t.rateLimitedUntil):0,lastAttemptAt:Number.isFinite(Number(t.lastAttemptAt))?Number(t.lastAttemptAt):0,lastRateLimitedAt:Number.isFinite(Number(t.lastRateLimitedAt))?Number(t.lastRateLimitedAt):0,...t.authFailure==="invalid_grant"?{authFailure:"invalid_grant"}:{},...r?{accountId:r}:{},...s?{clientId:s}:{},...et(t.modelCooldowns)?{modelCooldowns:et(t.modelCooldowns)}:{}}}l(Lt,"credential");function et(t){if(!t||typeof t!="object"||Array.isArray(t))return;const a=Object.entries(t).filter(([e,n])=>e.trim()!==""&&Number.isFinite(Number(n))).map(([e,n])=>[e,Number(n)]);return a.length?Object.fromEntries(a):void 0}l(et,"modelCooldowns");function D(t,a){if(!a.label?.trim())throw new Error(`${p(t)} subscription label cannot be empty`);const e=Lt(a);if(!e)throw new Error(`Refusing to persist incomplete ${p(t)} subscription "${a.label.trim()}"; pool rows require both OAuth tokens.`);return e}l(D,"assertCredential");function at(t,a){const e=t.accountId?.trim(),n=a.accountId?.trim();return!!(e&&n&&e!==n)}l(at,"differentAccount");function A(t){return t.accountId?.trim()||(t.refresh.trim()?`refresh:${mt("sha256").update(t.refresh.trim()).digest("hex")}`:void 0)}l(A,"identity");function gt(t,a){const e=V(a);return e?{...t,clientId:e}:t}l(gt,"withClientId");function It(t,a,e){const n=e.refresh?.trim()??"",i=e.access?.trim()??"",r=Number(e.expires);if(!n||!i||!Number.isFinite(r))throw new Error(`${p(t)} subscription "${a}" returned an incomplete credential; the stored credential was left unchanged.`);return{refresh:n,access:i,expires:r}}l(It,"assertTokens");const nt=1e4,it=15e3,xt="15s";class Nt extends Error{static{l(this,"RefreshBusyError")}constructor(a,e){super(`${p(a)} subscription "${e}" ${At}; treating it as cooling for this call`),this.name="RefreshBusyError"}}class Dt extends Error{static{l(this,"RefreshTimeoutError")}constructor(a){super(`${p(a)} ${wt} ${nt} ms`),this.name="RefreshTimeoutError"}}const O="id,label,label_key,position,last_attempt_at,last_rate_limited_at,rate_limited_until,auth_failure,refresh_sealed,access_sealed,expires,vendor_account_id,client_id,key_id",I=l((t,a,e,n)=>`model_accounts|${t}|${a}|${e}|${n}`,"aadOf");function L(t){return{refresh:t.refresh,access:t.access,expires:t.expires,...t.accountId?{accountId:t.accountId}:{},...t.clientId?{clientId:t.clientId}:{}}}l(L,"stored");function St(t,a){return{providerId:t,id:a.id,label:a.label,labelKey:a.label_key,position:a.position,lastAttemptAt:a.last_attempt_at,lastRateLimitedAt:a.last_rate_limited_at,rateLimitedUntil:a.rate_limited_until,...a.auth_failure?{authFailure:a.auth_failure}:{}}}l(St,"rowOf");function C(t,a,e,n=[]){if(!e.refresh_sealed||!e.access_sealed||e.expires===null||!e.key_id)throw new Error(`managed ${a} account ${e.id} has no credential record`);const i=G(),r=J(e.refresh_sealed,e.key_id,i,I(t,a,e.id,"refresh")),s=J(e.access_sealed,e.key_id,i,I(t,a,e.id,"access")),o=St(a,e),c={label:o.label,refresh:r,access:s,expires:e.expires,rateLimitedUntil:o.authFailure||!o.lastRateLimitedAt?o.rateLimitedUntil:Math.min(o.rateLimitedUntil,o.lastRateLimitedAt+j),lastAttemptAt:o.lastAttemptAt,lastRateLimitedAt:o.lastRateLimitedAt,...o.authFailure?{authFailure:o.authFailure}:{},...e.vendor_account_id?{accountId:e.vendor_account_id}:{},...e.client_id?{clientId:e.client_id}:{},...n.length?{modelCooldowns:Object.fromEntries(n.map(u=>[u.family,u.lastRateLimitedAt?Math.min(u.rateLimitedUntil,u.lastRateLimitedAt+j):u.rateLimitedUntil]))}:{}};return{row:o,entry:c}}l(C,"toPublic");function rt(t){const a=new Map;for(const e of t){const n=a.get(e.account_id)??[];n.push({family:e.family,rateLimitedUntil:e.rate_limited_until,lastRateLimitedAt:e.last_rate_limited_at}),a.set(e.account_id,n)}return a}l(rt,"groupCooldowns");async function S(t,a,e){return rt(await t.prepare("SELECT account_id,family,rate_limited_until,last_rate_limited_at FROM model_account_cooldowns WHERE person=? AND provider_id=? ORDER BY family").all(a,e))}l(S,"loadCooldowns");async function M(t,a,e,n=!1){const i=await t.prepare(`SELECT ${O} FROM model_accounts WHERE person=? AND provider_id=? ORDER BY position${n?" FOR UPDATE":""}`).all(a,e),r=await S(t,a,e);return i.map(s=>C(a,e,s,r.get(s.id)))}l(M,"loadPool");async function Zt(){const t=await b(),a=await N(),e=await a.prepare(`SELECT provider_id,${O} FROM model_accounts WHERE person=? ORDER BY provider_id,position`).all(t),n=rt(await a.prepare("SELECT account_id,family,rate_limited_until,last_rate_limited_at FROM model_account_cooldowns WHERE person=? ORDER BY family").all(t)),i=new Map;for(const r of e){const s=i.get(r.provider_id)??[];s.push(C(t,r.provider_id,r,n.get(r.id)).entry),i.set(r.provider_id,s)}return i}l(Zt,"readAllSubscriptionPools");async function Y(t){await t.exec(`SET LOCAL lock_timeout = '${xt}'`)}l(Y,"setLockTimeout");async function Tt(t,a,e,n){const i=n.trim().toLowerCase(),r=Number.parseInt(i,10),s=Number.isFinite(r)&&String(r)===i&&r>=1,o=await t.prepare(`SELECT ${O} FROM model_accounts WHERE person=? AND provider_id=? AND ${s?"position=?":"label_key=?"} FOR UPDATE`).get(a,e,s?r-1:i);if(o)return C(a,e,o,(await S(t,a,e)).get(o.id))}l(Tt,"lockedAccount");async function y(t,a){const e=await b();return B(async n=>(await Y(n),await n.prepare("SELECT pg_advisory_xact_lock(hashtext(?))").get(`model_accounts|${e}|${t}`),a({db:n,person:e,rows:await M(n,e,t,!0)})))}l(y,"locked");async function k(t,a,e,n,i){const r=G(),s=U(i.refresh,r,I(a,e,n.id,"refresh")),o=U(i.access,r,I(a,e,n.id,"access"));await t.prepare("INSERT INTO model_accounts(person,provider_id,id,label,label_key,position,last_attempt_at,last_rate_limited_at,rate_limited_until,auth_failure,refresh_sealed,access_sealed,expires,vendor_account_id,client_id,key_id) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)").run(a,e,n.id,n.label,n.labelKey,n.position,n.lastAttemptAt,n.lastRateLimitedAt,n.rateLimitedUntil,n.authFailure??null,s.sealed,o.sealed,i.expires,i.accountId??null,i.clientId??null,s.keyId)}l(k,"insertAccount");async function X(t,a,e,n,i,r){const s=G(),o=U(i.refresh,s,I(a,e,n,"refresh")),c=U(i.access,s,I(a,e,n,"access"));return(await t.prepare(`UPDATE model_accounts SET refresh_sealed=?,access_sealed=?,expires=?,vendor_account_id=?,client_id=?,key_id=?,refresh_claimed_until=0 WHERE person=? AND provider_id=? AND id=?${r?" AND refresh_sealed=?":""}`).run(o.sealed,c.sealed,i.expires,i.accountId??null,i.clientId??null,o.keyId,a,e,n,...r?[r]:[])).changes===1}l(X,"setCredential");async function E(t,a,e){await t.prepare("UPDATE model_accounts SET label=?,label_key=?,position=?,last_attempt_at=?,last_rate_limited_at=?,rate_limited_until=?,auth_failure=? WHERE person=? AND provider_id=? AND id=?").run(e.label,e.labelKey,e.position,e.lastAttemptAt,e.lastRateLimitedAt,e.rateLimitedUntil,e.authFailure??null,a,e.providerId,e.id)}l(E,"updateHealth");async function st(t,a,e,n,i,r,s){await t.prepare("INSERT INTO model_account_cooldowns(person,provider_id,account_id,family,rate_limited_until,last_rate_limited_at) VALUES(?,?,?,?,?,?) ON CONFLICT(person,provider_id,account_id,family) DO UPDATE SET rate_limited_until=excluded.rate_limited_until,last_rate_limited_at=excluded.last_rate_limited_at").run(a,e,n,i,r,s)}l(st,"upsertModelCooldown");async function T(t,a,e,n){n===void 0?await t.prepare("DELETE FROM model_account_cooldowns WHERE person=? AND provider_id=?").run(a,e):await t.prepare("DELETE FROM model_account_cooldowns WHERE person=? AND provider_id=? AND account_id=?").run(a,e,n)}l(T,"deleteModelCooldowns");const R=l(async({db:t,person:a},e)=>(await M(t,a,e)).map(({entry:n})=>n),"publicPool");function Ft(t,a){let e;return Promise.race([a,new Promise((n,i)=>{e=setTimeout(()=>i(new Dt(t)),nt)})]).finally(()=>clearTimeout(e))}l(Ft,"withExchangeTimeout");async function H(t){return(await Ut(t)).map(({entry:a})=>a)}l(H,"readSubscriptionPool");async function Ut(t){const a=await b();return(await M(await N(),a,t)).map(({row:e,entry:n})=>({id:e.id,entry:n}))}l(Ut,"readSubscriptionPoolRows");async function vt(t,a){return y(t,async e=>{const{db:n,person:i,rows:r}=e,s=a.map(u=>D(t,u)),o=s.map((u,d)=>({entry:u,id:r[d]?.row.id??x()})),c=await S(n,i,t);await n.prepare("DELETE FROM model_accounts WHERE person=? AND provider_id=?").run(i,t),await T(n,i,t);for(const[u,{entry:d,id:_}]of o.entries()){await k(n,i,t,{providerId:t,id:_,label:d.label,labelKey:f(d.label),position:u,lastAttemptAt:d.lastAttemptAt,lastRateLimitedAt:d.lastRateLimitedAt,rateLimitedUntil:d.rateLimitedUntil,...d.authFailure?{authFailure:d.authFailure}:{}},L(d));for(const[m,h]of Object.entries(d.modelCooldowns??{}))await st(n,i,t,_,m,h,c.get(_)?.find(F=>F.family===m)?.lastRateLimitedAt??d.lastRateLimitedAt)}return s})}l(vt,"writeSubscriptionPool");function W(t,a){const e=a.trim().toLowerCase(),n=Number.parseInt(e,10);return Number.isFinite(n)&&String(n)===e&&n>=1&&n<=t.length?n-1:t.findIndex(({entry:i})=>f(i.label)===e)}l(W,"resolve");const P=l((t,a)=>new $(`This ${p(t)} account is already added as \u201C${a}\u201D \u2014 it shares the same quota, so a second slot adds no redundancy.`),"duplicateAccount");async function $t(t,a){const e=D(t,a);return y(t,async n=>{const{db:i,person:r,rows:s}=n;if(s.some(({entry:u})=>f(u.label)===f(e.label)))throw new $(`${p(t)} subscription already exists: ${e.label}`);const o=A(e),c=s.find(({entry:u})=>A(u)===o);if(o&&c)throw P(t,c.entry.label);return await k(i,r,t,{providerId:t,id:x(),label:e.label,labelKey:f(e.label),position:s.length,lastAttemptAt:e.lastAttemptAt,lastRateLimitedAt:e.lastRateLimitedAt,rateLimitedUntil:e.rateLimitedUntil,...e.authFailure?{authFailure:e.authFailure}:{}},L(e)),R(n,t)})}l($t,"addSubscription");async function te(t,a){const e=D(t,a);return(await H(t)).find(i=>f(i.label)===f(e.label))?Ot(t,e):$t(t,e)}l(te,"upsertSubscription");async function Ot(t,a){const e=D(t,a);return y(t,async n=>{const{db:i,person:r,rows:s}=n,o=s.findIndex(({entry:m})=>f(m.label)===f(e.label)),c=s[o],u=s.find(({entry:m},h)=>h!==o&&A(m)===A(e));if(A(e)&&u)throw P(t,u.entry.label);if(!c)return await k(i,r,t,{providerId:t,id:x(),label:e.label,labelKey:f(e.label),position:s.length,lastAttemptAt:e.lastAttemptAt,lastRateLimitedAt:e.lastRateLimitedAt,rateLimitedUntil:e.rateLimitedUntil},L(e)),R(n,t);const d=c.row,_=e.lastRateLimitedAt>=d.lastRateLimitedAt;return await X(i,r,t,d.id,L(e)),await E(i,r,{...d,authFailure:void 0,label:e.label,labelKey:f(e.label),lastAttemptAt:Math.max(d.lastAttemptAt,e.lastAttemptAt),lastRateLimitedAt:_?e.lastRateLimitedAt:d.lastRateLimitedAt,rateLimitedUntil:_?e.rateLimitedUntil:d.rateLimitedUntil}),at(c.entry,e)&&await T(i,r,t,d.id),R(n,t)})}l(Ot,"upsertSubscriptionWithUniqueAccount");async function ee(t,a,e){return y(t,async n=>{const{db:i,person:r,rows:s}=n,o=W(s,a);if(o<0)throw new Error(`Unknown ${p(t)} subscription: ${a}`);const c=e.trim();if(!c)throw new Error(`${p(t)} subscription label cannot be empty`);if(s.some((u,d)=>d!==o&&f(u.entry.label)===f(c)))throw new $(`${p(t)} subscription already exists: ${c}`);return await E(i,r,{...s[o].row,label:c,labelKey:f(c)}),R(n,t)})}l(ee,"renameSubscription");async function q(t,a,e){return y(t,async n=>{const{db:i,person:r,rows:s}=n,o=a(s);if(o<0)throw new Error(`Unknown ${p(t)} subscription: ${e}`);const c=s[o].row;return await i.prepare("DELETE FROM model_accounts WHERE person=? AND provider_id=? AND id=?").run(r,t,c.id),await T(i,r,t,c.id),R(n,t)})}l(q,"remove");async function Ct(t,a){return q(t,e=>W(e,a),a)}l(Ct,"removeManagedAccount");async function ae(t,a){return q(t,e=>e.findIndex(({row:n})=>n.id===a),a)}l(ae,"removeManagedAccountById");async function ne(t,a){return q(t,e=>W(e,a),a)}l(ne,"removeSubscription");async function Mt(t){return y(t,async({db:a,person:e,rows:n})=>(await a.prepare("DELETE FROM model_accounts WHERE person=? AND provider_id=?").run(e,t),await T(a,e,t),n.length))}l(Mt,"removeAllManagedAccounts");async function ie(t,a){return a===void 0?(await Mt(t),[]):Ct(t,a)}l(ie,"removeManagedProvider");async function re(t,a){return y(t,async e=>{const{db:n,person:i,rows:r}=e,s=W(r,a);if(s<0)throw new Error(`Unknown ${p(t)} subscription: ${a}`);const o=[r[s],...r.filter((c,u)=>u!==s)];for(const[c,u]of o.entries())await E(n,i,{...u.row,position:c});return R(e,t)})}l(re,"promoteSubscription");async function K(t,a,e){const n=await b();return await B(async i=>{await Y(i);const r=await Tt(i,n,t,a);if(!r)throw new Error(`Unknown ${p(t)} subscription: ${a}`);await e(i,n,r.row)}),H(t)}l(K,"healthWrite");async function se(t,a,e=Date.now()){return K(t,a,(n,i,r)=>E(n,i,{...r,lastAttemptAt:Math.max(r.lastAttemptAt,e)}))}l(se,"markSubscriptionAttempt");async function oe(t,a,e,n=Date.now(),i=Date.now(),r={kind:"account"}){return e=Math.min(Math.max(0,e),j),K(t,a,async(s,o,c)=>{if(r.kind==="account"){if(i<c.lastRateLimitedAt)return;await E(s,o,{...c,lastAttemptAt:Math.max(c.lastAttemptAt,n),lastRateLimitedAt:i,rateLimitedUntil:i+e});return}await E(s,o,{...c,lastAttemptAt:Math.max(c.lastAttemptAt,n)});const u=(await S(s,o,t)).get(c.id)?.find(d=>d.family===r.family);u&&i<u.lastRateLimitedAt||await st(s,o,t,c.id,r.family,i+e,i)})}l(oe,"markSubscriptionRateLimited");async function le(t,a,e=Date.now(),n){const i=ht(n);return K(t,a,async(r,s,o)=>{if(e>=o.lastRateLimitedAt&&await E(r,s,{...o,authFailure:void 0,lastAttemptAt:Math.max(o.lastAttemptAt,e),rateLimitedUntil:0}),i===void 0)return;const c=(await S(r,s,t)).get(o.id)?.find(u=>u.family===i);c&&e>=c.lastRateLimitedAt&&await r.prepare("DELETE FROM model_account_cooldowns WHERE person=? AND provider_id=? AND account_id=? AND family=?").run(s,t,o.id,i)})}l(le,"markSubscriptionSuccess");async function kt(t,a,e){const n=Date.now();await E(t,a,{...e,authFailure:"invalid_grant",lastAttemptAt:Math.max(e.lastAttemptAt,n),rateLimitedUntil:Math.max(e.rateLimitedUntil,n+Z)})}l(kt,"recordInvalidGrant");function ce(t,a,e,n=15e3,i=Date.now()){const r=yt(t),s=pt(t,a,i),o=e??r??n;return r!==void 0?{retryMs:o,vendorReset:i+o,observation:s}:{retryMs:s.resetAt!==void 0?Math.max(o,s.resetAt-i):o,vendorReset:s.resetAt,observation:s}}l(ce,"vendorRateLimit");async function de(t,a){return K(t,a,(e,n,i)=>kt(e,n,i))}l(de,"markSubscriptionAuthFailure");async function ot(t,a,e,n){const i=await b(),r=await N(),s=Date.now()+it;for(;;){const o=Date.now(),c=await r.prepare(`UPDATE model_accounts SET refresh_claimed_until=? WHERE person=? AND provider_id=? AND label_key=? AND expires<=? AND auth_failure IS NULL AND refresh_claimed_until<=? RETURNING ${O}`).get(o+it,i,t,f(a),e?o:Number.MAX_SAFE_INTEGER,o);if(c)try{const d=C(i,t,c);let _;try{_=await Ft(t,n(d.entry))}catch(h){throw Q(h)&&await r.prepare("UPDATE model_accounts SET auth_failure=?,last_attempt_at=GREATEST(last_attempt_at,?),rate_limited_until=GREATEST(rate_limited_until,?) WHERE person=? AND provider_id=? AND id=? AND refresh_sealed=?").run("invalid_grant",Date.now(),Date.now()+Z,i,t,c.id,c.refresh_sealed),h}if(!_)return d.entry;const m=gt(It(t,d.entry.label,_),_.clientId??d.entry.clientId);if(await X(r,i,t,c.id,L({...d.entry,...m}),c.refresh_sealed))return{...d.entry,...m};continue}finally{await r.prepare("UPDATE model_accounts SET refresh_claimed_until=0 WHERE person=? AND provider_id=? AND id=?").run(i,t,c.id).catch(()=>{})}const u=(await M(r,i,t)).find(({entry:d})=>f(d.label)===f(a));if(!u)throw new Error(`${p(t)} subscription "${a}" no longer exists`);if(u.row.authFailure)throw new Error(`${p(t)} subscription "${u.entry.label}" refresh refused with status=400 invalid_grant; it needs a new sign-in`);if(e&&u.entry.expires>o)return u.entry;if(Date.now()>=s)throw new Nt(t,u.entry.label);await ft(500)}}l(ot,"refreshAccount");async function ue(t,a,e){return ot(t,a,!0,n=>e(n.refresh,n.clientId))}l(ue,"refreshSubscriptionCredential");async function me(t,a,e){const n=new Set;let i;for(;;){const r=a((await H(t)).filter(({label:s})=>!n.has(s)));if(!r){if(i)throw i;return}n.add(r.label);try{return await ot(t,r.label,!1,e)}catch(s){if(!Q(s))throw s;i=s}}}l(me,"modifyElectedSubscription");async function Ht(t,a){const e=a.accountId?.trim(),n=a.email?.trim();if(t!==Rt)return{...e?{accountId:e}:{},...n?{email:n}:{}};try{const i=await fetch("https://api.anthropic.com/api/oauth/profile",{headers:{Authorization:`Bearer ${a.access}`,Accept:"application/json"},signal:AbortSignal.timeout(3e3)});if(!i.ok)return e?{accountId:e}:{};const r=await i.json(),s=typeof r.account?.uuid=="string"&&r.account.uuid.trim()?r.account.uuid.trim():void 0,o=typeof r.account?.email=="string"&&r.account.email.trim()?r.account.email.trim():void 0;return{...s?{accountId:s}:{},...o?{email:o}:{}}}catch{return e?{accountId:e}:{}}}l(Ht,"enrichManagedLoginIdentity");async function fe(t,a,e){const n=await Ht(t,e);return y(t,async i=>{const{db:r,person:s,rows:o}=i,c=e.autoLabel?void 0:a?.trim(),u=A({refresh:e.refresh,accountId:n.accountId}),d=(c?o.find(({entry:w})=>f(w.label)===f(c)):void 0)??o.find(({entry:w})=>A(w)===u);let _=d?.entry.label??c;if(!_&&e.autoLabel){const w=n.email||a?.trim()||`Account ${o.length+1}`;_=w;for(let g=2;o.some(({entry:dt})=>f(dt.label)===f(_));g++)_=`${w} (${g})`}if(!_)throw new Error(`${p(t)} subscription label cannot be empty`);const m=D(t,{label:_,refresh:e.refresh,access:e.access,expires:e.expires,...n.accountId?{accountId:n.accountId}:{},...e.clientId?{clientId:e.clientId}:{},rateLimitedUntil:0,lastAttemptAt:Date.now(),lastRateLimitedAt:e.lastRateLimitedAt});if(!d){if(o.some(({entry:g})=>f(g.label)===f(m.label)))throw new $(`${p(t)} subscription already exists: ${m.label}`);const w=o.find(({entry:g})=>A(g)===A(m));if(A(m)&&w)throw P(t,w.entry.label);return await k(r,s,t,{providerId:t,id:x(),label:m.label,labelKey:f(m.label),position:o.length,lastAttemptAt:m.lastAttemptAt,lastRateLimitedAt:m.lastRateLimitedAt,rateLimitedUntil:m.rateLimitedUntil},L(m)),R(i,t)}const h=d.row,F=o.find(({entry:w})=>w.label!==d.entry.label&&A(w)===A(m));if(A(m)&&F)throw P(t,F.entry.label);const z=m.lastRateLimitedAt>=h.lastRateLimitedAt;return await X(r,s,t,h.id,L(m)),await E(r,s,{...h,authFailure:void 0,lastAttemptAt:Math.max(h.lastAttemptAt,m.lastAttemptAt),lastRateLimitedAt:z?m.lastRateLimitedAt:h.lastRateLimitedAt,rateLimitedUntil:z?0:h.rateLimitedUntil}),at(d.entry,m)&&await T(r,s,t,h.id),R(i,t)})}l(fe,"commitManagedLogin");const lt=new Map;function ct(t){return{defaultFallbackStrength:tt(t?.default_fallback_strength)??v,revertWhenAvailable:t?.revert_when_available===void 0||t.revert_when_available===null?!0:!!t.revert_when_available}}l(ct,"rotationFromRow");async function Wt(){const t=await b(),a=ct(await(await N()).prepare("SELECT default_fallback_strength,revert_when_available FROM model_settings WHERE person=?").get(t));return lt.set(t,a),a}l(Wt,"loadRotationConfig"),Et(()=>Pt());async function Pt(){const t=_t();return t?t.rotation:Wt()}l(Pt,"readRotationConfig");async function _e(t){const a=await b(),e=await B(async n=>{await Y(n),await n.prepare("INSERT INTO model_settings(person) VALUES(?) ON CONFLICT(person) DO NOTHING").run(a);const i=ct(await n.prepare("SELECT default_fallback_strength,revert_when_available FROM model_settings WHERE person=? FOR UPDATE").get(a)),r={defaultFallbackStrength:tt(t.defaultFallbackStrength)??i.defaultFallbackStrength??v,revertWhenAvailable:t.revertWhenAvailable??i.revertWhenAvailable??!0};return await n.prepare("UPDATE model_settings SET default_fallback_strength=?,revert_when_available=?,revision=revision+1 WHERE person=?").run(r.defaultFallbackStrength,r.revertWhenAvailable?1:0,a),r});return lt.set(a,e),e}l(_e,"writeRotationConfig");async function pe(){const t=await b();return(await(await N()).prepare("INSERT INTO model_settings(person,openai_device_id) VALUES(?,?) ON CONFLICT(person) DO UPDATE SET openai_device_id=COALESCE(model_settings.openai_device_id,EXCLUDED.openai_device_id) RETURNING openai_device_id").get(t,x())).openai_device_id}l(pe,"openAIDeviceId");async function he(t,a=Date.now(),e){const n=await H(t),i=n.filter(s=>s.authFailure===void 0&&bt(s,e)<=a),r=p(t);return i.length===0?`${r} pool exhausted`:`${r} ${i[0]?.label??t} (${i.length}/${n.length} ready)`}l(he,"formatStatusLine");export{nt as REFRESH_EXCHANGE_TIMEOUT_MS,Nt as RefreshBusyError,Dt as RefreshTimeoutError,I as aadOf,$t as addSubscription,fe as commitManagedLogin,Ht as enrichManagedLoginIdentity,he as formatStatusLine,k as insertAccount,Wt as loadRotationConfig,se as markSubscriptionAttempt,de as markSubscriptionAuthFailure,oe as markSubscriptionRateLimited,le as markSubscriptionSuccess,me as modifyElectedSubscription,pe as openAIDeviceId,re as promoteSubscription,Zt as readAllSubscriptionPools,Pt as readRotationConfig,H as readSubscriptionPool,Ut as readSubscriptionPoolRows,ue as refreshSubscriptionCredential,Mt as removeAllManagedAccounts,Ct as removeManagedAccount,ae as removeManagedAccountById,ie as removeManagedProvider,ne as removeSubscription,ee as renameSubscription,st as upsertModelCooldown,te as upsertSubscription,Ot as upsertSubscriptionWithUniqueAccount,ce as vendorRateLimit,_e as writeRotationConfig,vt as writeSubscriptionPool};
1
+ var ft=Object.defineProperty;var l=(t,n)=>ft(t,"name",{value:n,configurable:!0});import{createHash as _t,randomUUID as x}from"node:crypto";import{setTimeout as pt}from"node:timers/promises";import{brokerConfigSnapshot as At}from"./config.js";import{openDb as N,withCanvasWrite as Y}from"./canvas/db.js";import{personIdAsync as b}from"./canvas/person.js";import{loadSecretsKey as X,open as v,seal as U}from"./secrets/index.js";import{classifyRateLimit as ht,modelCooldownFamily as wt}from"./rate-limit-scope.js";import{REFRESH_BUSY_PHRASE as Et,REFRESH_TIMEOUT_PHRASE as bt}from"./provider-error-recognition.js";import{registerRotationReader as yt}from"./model-routes.js";import{coolingUntilFor as Rt,retryAfterMsFromHeaders as Lt,getProviderLabel as p,isInvalidRefreshTokenError as tt,DuplicateSubscriptionError as O,ANTHROPIC_PROVIDER_ID as gt,MAX_RATE_LIMIT_COOLDOWN_MS as q,INVALID_REFRESH_TOKEN_BACKOFF_MS as et}from"./managed-providers.js";export*from"./managed-providers.js";const nt="strong";function at(t){return t==="ultra"||t==="strong"||t==="medium"||t==="light"?t:void 0}l(at,"normalizeStrength");function f(t){return t.toLowerCase()}l(f,"key");function z(t){return typeof t=="string"&&t.trim()?t.trim():void 0}l(z,"optionalString");function It(t){const n=typeof t.label=="string"?t.label.trim():"",e=typeof t.refresh=="string"?t.refresh.trim():"",a=typeof t.access=="string"?t.access.trim():"",i=Number(t.expires);if(!n||!e||!a||!Number.isFinite(i))return;const r=z(t.accountId),s=z(t.clientId);return{label:n,refresh:e,access:a,expires:i,rateLimitedUntil:Number.isFinite(Number(t.rateLimitedUntil))?Number(t.rateLimitedUntil):0,lastAttemptAt:Number.isFinite(Number(t.lastAttemptAt))?Number(t.lastAttemptAt):0,lastRateLimitedAt:Number.isFinite(Number(t.lastRateLimitedAt))?Number(t.lastRateLimitedAt):0,...t.authFailure==="invalid_grant"?{authFailure:"invalid_grant"}:{},...r?{accountId:r}:{},...s?{clientId:s}:{},...it(t.modelCooldowns)?{modelCooldowns:it(t.modelCooldowns)}:{}}}l(It,"credential");function it(t){if(!t||typeof t!="object"||Array.isArray(t))return;const n=Object.entries(t).filter(([e,a])=>e.trim()!==""&&Number.isFinite(Number(a))).map(([e,a])=>[e,Number(a)]);return n.length?Object.fromEntries(n):void 0}l(it,"modelCooldowns");function D(t,n){if(!n.label?.trim())throw new Error(`${p(t)} subscription label cannot be empty`);const e=It(n);if(!e)throw new Error(`Refusing to persist incomplete ${p(t)} subscription "${n.label.trim()}"; pool rows require both OAuth tokens.`);return e}l(D,"assertCredential");function $(t,n){const e=t.accountId?.trim(),a=n.accountId?.trim();return!!(e&&a&&e!==a)}l($,"differentAccount");function h(t){return t.accountId?.trim()||(t.refresh.trim()?`refresh:${_t("sha256").update(t.refresh.trim()).digest("hex")}`:void 0)}l(h,"identity");function xt(t,n){const e=z(n);return e?{...t,clientId:e}:t}l(xt,"withClientId");function Nt(t,n,e){const a=e.refresh?.trim()??"",i=e.access?.trim()??"",r=Number(e.expires);if(!a||!i||!Number.isFinite(r))throw new Error(`${p(t)} subscription "${n}" returned an incomplete credential; the stored credential was left unchanged.`);return{refresh:a,access:i,expires:r}}l(Nt,"assertTokens");const rt=1e4,st=15e3,Dt="15s";class St extends Error{static{l(this,"RefreshBusyError")}constructor(n,e){super(`${p(n)} subscription "${e}" ${Et}; treating it as cooling for this call`),this.name="RefreshBusyError"}}class Tt extends Error{static{l(this,"RefreshTimeoutError")}constructor(n){super(`${p(n)} ${bt} ${rt} ms`),this.name="RefreshTimeoutError"}}const C="id,label,label_key,position,last_attempt_at,last_rate_limited_at,rate_limited_until,auth_failure,refresh_sealed,access_sealed,expires,vendor_account_id,client_id,key_id,vendor_limit_json",I=l((t,n,e,a)=>`model_accounts|${t}|${n}|${e}|${a}`,"aadOf");function L(t){return{refresh:t.refresh,access:t.access,expires:t.expires,...t.accountId?{accountId:t.accountId}:{},...t.clientId?{clientId:t.clientId}:{}}}l(L,"stored");function Ft(t,n){return{providerId:t,id:n.id,label:n.label,labelKey:n.label_key,position:n.position,lastAttemptAt:n.last_attempt_at,lastRateLimitedAt:n.last_rate_limited_at,rateLimitedUntil:n.rate_limited_until,...n.auth_failure?{authFailure:n.auth_failure}:{}}}l(Ft,"rowOf");function M(t,n,e,a=[]){if(!e.refresh_sealed||!e.access_sealed||e.expires===null||!e.key_id)throw new Error(`managed ${n} account ${e.id} has no credential record`);const i=X(),r=v(e.refresh_sealed,e.key_id,i,I(t,n,e.id,"refresh")),s=v(e.access_sealed,e.key_id,i,I(t,n,e.id,"access")),o=Ft(n,e),d=Object.fromEntries([...k(e.vendor_limit_json)?[["account",k(e.vendor_limit_json)]]:[],...a.flatMap(c=>c.vendorLimit?[[c.family,c.vendorLimit]]:[])]),u={label:o.label,refresh:r,access:s,expires:e.expires,rateLimitedUntil:o.authFailure||!o.lastRateLimitedAt?o.rateLimitedUntil:Math.min(o.rateLimitedUntil,o.lastRateLimitedAt+q),lastAttemptAt:o.lastAttemptAt,lastRateLimitedAt:o.lastRateLimitedAt,...o.authFailure?{authFailure:o.authFailure}:{},...e.vendor_account_id?{accountId:e.vendor_account_id}:{},...e.client_id?{clientId:e.client_id}:{},...a.length?{modelCooldowns:Object.fromEntries(a.map(c=>[c.family,c.lastRateLimitedAt?Math.min(c.rateLimitedUntil,c.lastRateLimitedAt+q):c.rateLimitedUntil]))}:{},...Object.keys(d).length?{vendorLimits:d}:{}};return{row:o,entry:u}}l(M,"toPublic");function k(t){try{return t?JSON.parse(t):void 0}catch{return}}l(k,"vendorLimitOf");function ot(t){const n=new Map;for(const e of t){const a=n.get(e.account_id)??[];a.push({family:e.family,rateLimitedUntil:e.rate_limited_until,lastRateLimitedAt:e.last_rate_limited_at,...k(e.vendor_limit_json)?{vendorLimit:k(e.vendor_limit_json)}:{}}),n.set(e.account_id,a)}return n}l(ot,"groupCooldowns");async function S(t,n,e){return ot(await t.prepare("SELECT account_id,family,rate_limited_until,last_rate_limited_at,vendor_limit_json FROM model_account_cooldowns WHERE person=? AND provider_id=? ORDER BY family").all(n,e))}l(S,"loadCooldowns");async function H(t,n,e,a=!1){const i=await t.prepare(`SELECT ${C} FROM model_accounts WHERE person=? AND provider_id=? ORDER BY position${a?" FOR UPDATE":""}`).all(n,e),r=await S(t,n,e);return i.map(s=>M(n,e,s,r.get(s.id)))}l(H,"loadPool");async function te(){const t=await b(),n=await N(),e=await n.prepare(`SELECT provider_id,${C} FROM model_accounts WHERE person=? ORDER BY provider_id,position`).all(t),a=ot(await n.prepare("SELECT account_id,family,rate_limited_until,last_rate_limited_at,vendor_limit_json FROM model_account_cooldowns WHERE person=? ORDER BY family").all(t)),i=new Map;for(const r of e){const s=i.get(r.provider_id)??[];s.push(M(t,r.provider_id,r,a.get(r.id)).entry),i.set(r.provider_id,s)}return i}l(te,"readAllSubscriptionPools");async function J(t){await t.exec(`SET LOCAL lock_timeout = '${Dt}'`)}l(J,"setLockTimeout");async function Ut(t,n,e,a){const i=a.trim().toLowerCase(),r=Number.parseInt(i,10),s=Number.isFinite(r)&&String(r)===i&&r>=1,o=await t.prepare(`SELECT ${C} FROM model_accounts WHERE person=? AND provider_id=? AND ${s?"position=?":"label_key=?"} FOR UPDATE`).get(n,e,s?r-1:i);if(o)return M(n,e,o,(await S(t,n,e)).get(o.id))}l(Ut,"lockedAccount");async function y(t,n){const e=await b();return Y(async a=>(await J(a),await a.prepare("SELECT pg_advisory_xact_lock(hashtext(?))").get(`model_accounts|${e}|${t}`),n({db:a,person:e,rows:await H(a,e,t,!0)})))}l(y,"locked");async function W(t,n,e,a,i){const r=X(),s=U(i.refresh,r,I(n,e,a.id,"refresh")),o=U(i.access,r,I(n,e,a.id,"access"));await t.prepare("INSERT INTO model_accounts(person,provider_id,id,label,label_key,position,last_attempt_at,last_rate_limited_at,rate_limited_until,auth_failure,refresh_sealed,access_sealed,expires,vendor_account_id,client_id,key_id) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)").run(n,e,a.id,a.label,a.labelKey,a.position,a.lastAttemptAt,a.lastRateLimitedAt,a.rateLimitedUntil,a.authFailure??null,s.sealed,o.sealed,i.expires,i.accountId??null,i.clientId??null,s.keyId)}l(W,"insertAccount");async function Q(t,n,e,a,i,r){const s=X(),o=U(i.refresh,s,I(n,e,a,"refresh")),d=U(i.access,s,I(n,e,a,"access"));return(await t.prepare(`UPDATE model_accounts SET refresh_sealed=?,access_sealed=?,expires=?,vendor_account_id=?,client_id=?,key_id=?,refresh_claimed_until=0 WHERE person=? AND provider_id=? AND id=?${r?" AND refresh_sealed=?":""}`).run(o.sealed,d.sealed,i.expires,i.accountId??null,i.clientId??null,o.keyId,n,e,a,...r?[r]:[])).changes===1}l(Q,"setCredential");async function E(t,n,e){await t.prepare("UPDATE model_accounts SET label=?,label_key=?,position=?,last_attempt_at=?,last_rate_limited_at=?,rate_limited_until=?,auth_failure=? WHERE person=? AND provider_id=? AND id=?").run(e.label,e.labelKey,e.position,e.lastAttemptAt,e.lastRateLimitedAt,e.rateLimitedUntil,e.authFailure??null,n,e.providerId,e.id)}l(E,"updateHealth");async function lt(t,n,e,a,i,r,s,o){await t.prepare("INSERT INTO model_account_cooldowns(person,provider_id,account_id,family,rate_limited_until,last_rate_limited_at,vendor_limit_json) VALUES(?,?,?,?,?,?,?) ON CONFLICT(person,provider_id,account_id,family) DO UPDATE SET rate_limited_until=excluded.rate_limited_until,last_rate_limited_at=excluded.last_rate_limited_at,vendor_limit_json=excluded.vendor_limit_json").run(n,e,a,i,r,s,o?JSON.stringify(o):null)}l(lt,"upsertModelCooldown");async function P(t,n,e,a){await t.prepare("UPDATE model_accounts SET vendor_limit_json=? WHERE person=? AND provider_id=? AND id=?").run(a?JSON.stringify(a):null,n,e.providerId,e.id)}l(P,"setAccountVendorLimit");async function T(t,n,e,a){a===void 0?await t.prepare("DELETE FROM model_account_cooldowns WHERE person=? AND provider_id=?").run(n,e):await t.prepare("DELETE FROM model_account_cooldowns WHERE person=? AND provider_id=? AND account_id=?").run(n,e,a)}l(T,"deleteModelCooldowns");const R=l(async({db:t,person:n},e)=>(await H(t,n,e)).map(({entry:a})=>a),"publicPool");function Ot(t,n){let e;return Promise.race([n,new Promise((a,i)=>{e=setTimeout(()=>i(new Tt(t)),rt)})]).finally(()=>clearTimeout(e))}l(Ot,"withExchangeTimeout");async function j(t){return(await $t(t)).map(({entry:n})=>n)}l(j,"readSubscriptionPool");async function $t(t){const n=await b();return(await H(await N(),n,t)).map(({row:e,entry:a})=>({id:e.id,entry:a}))}l($t,"readSubscriptionPoolRows");async function ee(t,n){return y(t,async e=>{const{db:a,person:i,rows:r}=e,s=n.map(u=>D(t,u)),o=s.map((u,c)=>({entry:u,id:r[c]?.row.id??x()})),d=await S(a,i,t);await a.prepare("DELETE FROM model_accounts WHERE person=? AND provider_id=?").run(i,t),await T(a,i,t);for(const[u,{entry:c,id:_}]of o.entries()){await W(a,i,t,{providerId:t,id:_,label:c.label,labelKey:f(c.label),position:u,lastAttemptAt:c.lastAttemptAt,lastRateLimitedAt:c.lastRateLimitedAt,rateLimitedUntil:c.rateLimitedUntil,...c.authFailure?{authFailure:c.authFailure}:{}},L(c));for(const[m,A]of Object.entries(c.modelCooldowns??{}))await lt(a,i,t,_,m,A,d.get(_)?.find(F=>F.family===m)?.lastRateLimitedAt??c.lastRateLimitedAt)}return s})}l(ee,"writeSubscriptionPool");function K(t,n){const e=n.trim().toLowerCase(),a=Number.parseInt(e,10);return Number.isFinite(a)&&String(a)===e&&a>=1&&a<=t.length?a-1:t.findIndex(({entry:i})=>f(i.label)===e)}l(K,"resolve");const B=l((t,n)=>new O(`This ${p(t)} account is already added as \u201C${n}\u201D \u2014 it shares the same quota, so a second slot adds no redundancy.`),"duplicateAccount");async function Ct(t,n){const e=D(t,n);return y(t,async a=>{const{db:i,person:r,rows:s}=a;if(s.some(({entry:u})=>f(u.label)===f(e.label)))throw new O(`${p(t)} subscription already exists: ${e.label}`);const o=h(e),d=s.find(({entry:u})=>h(u)===o);if(o&&d)throw B(t,d.entry.label);return await W(i,r,t,{providerId:t,id:x(),label:e.label,labelKey:f(e.label),position:s.length,lastAttemptAt:e.lastAttemptAt,lastRateLimitedAt:e.lastRateLimitedAt,rateLimitedUntil:e.rateLimitedUntil,...e.authFailure?{authFailure:e.authFailure}:{}},L(e)),R(a,t)})}l(Ct,"addSubscription");async function ne(t,n){const e=D(t,n);return(await j(t)).find(i=>f(i.label)===f(e.label))?Mt(t,e):Ct(t,e)}l(ne,"upsertSubscription");async function Mt(t,n){const e=D(t,n);return y(t,async a=>{const{db:i,person:r,rows:s}=a,o=s.findIndex(({entry:m})=>f(m.label)===f(e.label)),d=s[o],u=s.find(({entry:m},A)=>A!==o&&h(m)===h(e));if(h(e)&&u)throw B(t,u.entry.label);if(!d)return await W(i,r,t,{providerId:t,id:x(),label:e.label,labelKey:f(e.label),position:s.length,lastAttemptAt:e.lastAttemptAt,lastRateLimitedAt:e.lastRateLimitedAt,rateLimitedUntil:e.rateLimitedUntil},L(e)),R(a,t);const c=d.row,_=e.lastRateLimitedAt>=c.lastRateLimitedAt;return await Q(i,r,t,c.id,L(e)),await E(i,r,{...c,authFailure:void 0,label:e.label,labelKey:f(e.label),lastAttemptAt:Math.max(c.lastAttemptAt,e.lastAttemptAt),lastRateLimitedAt:_?e.lastRateLimitedAt:c.lastRateLimitedAt,rateLimitedUntil:_?e.rateLimitedUntil:c.rateLimitedUntil}),(_||$(d.entry,e))&&await P(i,r,c,void 0),$(d.entry,e)&&await T(i,r,t,c.id),R(a,t)})}l(Mt,"upsertSubscriptionWithUniqueAccount");async function ae(t,n,e){return y(t,async a=>{const{db:i,person:r,rows:s}=a,o=K(s,n);if(o<0)throw new Error(`Unknown ${p(t)} subscription: ${n}`);const d=e.trim();if(!d)throw new Error(`${p(t)} subscription label cannot be empty`);if(s.some((u,c)=>c!==o&&f(u.entry.label)===f(d)))throw new O(`${p(t)} subscription already exists: ${d}`);return await E(i,r,{...s[o].row,label:d,labelKey:f(d)}),R(a,t)})}l(ae,"renameSubscription");async function Z(t,n,e){return y(t,async a=>{const{db:i,person:r,rows:s}=a,o=n(s);if(o<0)throw new Error(`Unknown ${p(t)} subscription: ${e}`);const d=s[o].row;return await i.prepare("DELETE FROM model_accounts WHERE person=? AND provider_id=? AND id=?").run(r,t,d.id),await T(i,r,t,d.id),R(a,t)})}l(Z,"remove");async function kt(t,n){return Z(t,e=>K(e,n),n)}l(kt,"removeManagedAccount");async function ie(t,n){return Z(t,e=>e.findIndex(({row:a})=>a.id===n),n)}l(ie,"removeManagedAccountById");async function re(t,n){return Z(t,e=>K(e,n),n)}l(re,"removeSubscription");async function Ht(t){return y(t,async({db:n,person:e,rows:a})=>(await n.prepare("DELETE FROM model_accounts WHERE person=? AND provider_id=?").run(e,t),await T(n,e,t),a.length))}l(Ht,"removeAllManagedAccounts");async function se(t,n){return n===void 0?(await Ht(t),[]):kt(t,n)}l(se,"removeManagedProvider");async function oe(t,n){return y(t,async e=>{const{db:a,person:i,rows:r}=e,s=K(r,n);if(s<0)throw new Error(`Unknown ${p(t)} subscription: ${n}`);const o=[r[s],...r.filter((d,u)=>u!==s)];for(const[d,u]of o.entries())await E(a,i,{...u.row,position:d});return R(e,t)})}l(oe,"promoteSubscription");async function G(t,n,e){const a=await b();return await Y(async i=>{await J(i);const r=await Ut(i,a,t,n);if(!r)throw new Error(`Unknown ${p(t)} subscription: ${n}`);await e(i,a,r.row)}),j(t)}l(G,"healthWrite");async function le(t,n,e=Date.now()){return G(t,n,(a,i,r)=>E(a,i,{...r,lastAttemptAt:Math.max(r.lastAttemptAt,e)}))}l(le,"markSubscriptionAttempt");async function ce(t,n,e,a=Date.now(),i=Date.now(),r={kind:"account"},s){return e=Math.min(Math.max(0,e),q),G(t,n,async(o,d,u)=>{if(r.kind==="account"){if(i<u.lastRateLimitedAt)return;await E(o,d,{...u,lastAttemptAt:Math.max(u.lastAttemptAt,a),lastRateLimitedAt:i,rateLimitedUntil:i+e}),await P(o,d,u,s);return}await E(o,d,{...u,lastAttemptAt:Math.max(u.lastAttemptAt,a)});const c=(await S(o,d,t)).get(u.id)?.find(_=>_.family===r.family);c&&i<c.lastRateLimitedAt||await lt(o,d,t,u.id,r.family,i+e,i,s)})}l(ce,"markSubscriptionRateLimited");async function de(t,n,e=Date.now(),a){const i=wt(a);return G(t,n,async(r,s,o)=>{if(e>=o.lastRateLimitedAt&&(await E(r,s,{...o,authFailure:void 0,lastAttemptAt:Math.max(o.lastAttemptAt,e),rateLimitedUntil:0}),await P(r,s,o,void 0)),i===void 0)return;const d=(await S(r,s,t)).get(o.id)?.find(u=>u.family===i);d&&e>=d.lastRateLimitedAt&&await r.prepare("DELETE FROM model_account_cooldowns WHERE person=? AND provider_id=? AND account_id=? AND family=?").run(s,t,o.id,i)})}l(de,"markSubscriptionSuccess");async function Wt(t,n,e){const a=Date.now();await E(t,n,{...e,authFailure:"invalid_grant",lastAttemptAt:Math.max(e.lastAttemptAt,a),rateLimitedUntil:Math.max(e.rateLimitedUntil,a+et)})}l(Wt,"recordInvalidGrant");function ue(t,n,e,a=15e3,i=Date.now()){const r=Lt(t),s=ht(t,n,i),o=e??r??a;return r!==void 0?{retryMs:o,vendorReset:i+o,observation:s}:{retryMs:s.resetAt!==void 0?Math.max(o,s.resetAt-i):o,vendorReset:s.resetAt,observation:s}}l(ue,"vendorRateLimit");async function me(t,n){return G(t,n,(e,a,i)=>Wt(e,a,i))}l(me,"markSubscriptionAuthFailure");async function ct(t,n,e,a){const i=await b(),r=await N(),s=Date.now()+st;for(;;){const o=Date.now(),d=await r.prepare(`UPDATE model_accounts SET refresh_claimed_until=? WHERE person=? AND provider_id=? AND label_key=? AND expires<=? AND auth_failure IS NULL AND refresh_claimed_until<=? RETURNING ${C}`).get(o+st,i,t,f(n),e?o:Number.MAX_SAFE_INTEGER,o);if(d)try{const c=M(i,t,d);let _;try{_=await Ot(t,a(c.entry))}catch(A){throw tt(A)&&await r.prepare("UPDATE model_accounts SET auth_failure=?,last_attempt_at=GREATEST(last_attempt_at,?),rate_limited_until=GREATEST(rate_limited_until,?) WHERE person=? AND provider_id=? AND id=? AND refresh_sealed=?").run("invalid_grant",Date.now(),Date.now()+et,i,t,d.id,d.refresh_sealed),A}if(!_)return c.entry;const m=xt(Nt(t,c.entry.label,_),_.clientId??c.entry.clientId);if(await Q(r,i,t,d.id,L({...c.entry,...m}),d.refresh_sealed))return{...c.entry,...m};continue}finally{await r.prepare("UPDATE model_accounts SET refresh_claimed_until=0 WHERE person=? AND provider_id=? AND id=?").run(i,t,d.id).catch(()=>{})}const u=(await H(r,i,t)).find(({entry:c})=>f(c.label)===f(n));if(!u)throw new Error(`${p(t)} subscription "${n}" no longer exists`);if(u.row.authFailure)throw new Error(`${p(t)} subscription "${u.entry.label}" refresh refused with status=400 invalid_grant; it needs a new sign-in`);if(e&&u.entry.expires>o)return u.entry;if(Date.now()>=s)throw new St(t,u.entry.label);await pt(500)}}l(ct,"refreshAccount");async function fe(t,n,e){return ct(t,n,!0,a=>e(a.refresh,a.clientId))}l(fe,"refreshSubscriptionCredential");async function _e(t,n,e){const a=new Set;let i;for(;;){const r=n((await j(t)).filter(({label:s})=>!a.has(s)));if(!r){if(i)throw i;return}a.add(r.label);try{return await ct(t,r.label,!1,e)}catch(s){if(!tt(s))throw s;i=s}}}l(_e,"modifyElectedSubscription");async function Pt(t,n){const e=n.accountId?.trim(),a=n.email?.trim();if(t!==gt)return{...e?{accountId:e}:{},...a?{email:a}:{}};try{const i=await fetch("https://api.anthropic.com/api/oauth/profile",{headers:{Authorization:`Bearer ${n.access}`,Accept:"application/json"},signal:AbortSignal.timeout(3e3)});if(!i.ok)return e?{accountId:e}:{};const r=await i.json(),s=typeof r.account?.uuid=="string"&&r.account.uuid.trim()?r.account.uuid.trim():void 0,o=typeof r.account?.email=="string"&&r.account.email.trim()?r.account.email.trim():void 0;return{...s?{accountId:s}:{},...o?{email:o}:{}}}catch{return e?{accountId:e}:{}}}l(Pt,"enrichManagedLoginIdentity");async function pe(t,n,e){const a=await Pt(t,e);return y(t,async i=>{const{db:r,person:s,rows:o}=i,d=e.autoLabel?void 0:n?.trim(),u=h({refresh:e.refresh,accountId:a.accountId}),c=(d?o.find(({entry:w})=>f(w.label)===f(d)):void 0)??o.find(({entry:w})=>h(w)===u);let _=c?.entry.label??d;if(!_&&e.autoLabel){const w=a.email||n?.trim()||`Account ${o.length+1}`;_=w;for(let g=2;o.some(({entry:mt})=>f(mt.label)===f(_));g++)_=`${w} (${g})`}if(!_)throw new Error(`${p(t)} subscription label cannot be empty`);const m=D(t,{label:_,refresh:e.refresh,access:e.access,expires:e.expires,...a.accountId?{accountId:a.accountId}:{},...e.clientId?{clientId:e.clientId}:{},rateLimitedUntil:0,lastAttemptAt:Date.now(),lastRateLimitedAt:e.lastRateLimitedAt});if(!c){if(o.some(({entry:g})=>f(g.label)===f(m.label)))throw new O(`${p(t)} subscription already exists: ${m.label}`);const w=o.find(({entry:g})=>h(g)===h(m));if(h(m)&&w)throw B(t,w.entry.label);return await W(r,s,t,{providerId:t,id:x(),label:m.label,labelKey:f(m.label),position:o.length,lastAttemptAt:m.lastAttemptAt,lastRateLimitedAt:m.lastRateLimitedAt,rateLimitedUntil:m.rateLimitedUntil},L(m)),R(i,t)}const A=c.row,F=o.find(({entry:w})=>w.label!==c.entry.label&&h(w)===h(m));if(h(m)&&F)throw B(t,F.entry.label);const V=m.lastRateLimitedAt>=A.lastRateLimitedAt;return await Q(r,s,t,A.id,L(m)),await E(r,s,{...A,authFailure:void 0,lastAttemptAt:Math.max(A.lastAttemptAt,m.lastAttemptAt),lastRateLimitedAt:V?m.lastRateLimitedAt:A.lastRateLimitedAt,rateLimitedUntil:V?0:A.rateLimitedUntil}),(V||$(c.entry,m))&&await P(r,s,A,void 0),$(c.entry,m)&&await T(r,s,t,A.id),R(i,t)})}l(pe,"commitManagedLogin");const dt=new Map;function ut(t){return{defaultFallbackStrength:at(t?.default_fallback_strength)??nt,revertWhenAvailable:t?.revert_when_available===void 0||t.revert_when_available===null?!0:!!t.revert_when_available}}l(ut,"rotationFromRow");async function jt(){const t=await b(),n=ut(await(await N()).prepare("SELECT default_fallback_strength,revert_when_available FROM model_settings WHERE person=?").get(t));return dt.set(t,n),n}l(jt,"loadRotationConfig"),yt(()=>Kt());async function Kt(){const t=At();return t?t.rotation:jt()}l(Kt,"readRotationConfig");async function Ae(t){const n=await b(),e=await Y(async a=>{await J(a),await a.prepare("INSERT INTO model_settings(person) VALUES(?) ON CONFLICT(person) DO NOTHING").run(n);const i=ut(await a.prepare("SELECT default_fallback_strength,revert_when_available FROM model_settings WHERE person=? FOR UPDATE").get(n)),r={defaultFallbackStrength:at(t.defaultFallbackStrength)??i.defaultFallbackStrength??nt,revertWhenAvailable:t.revertWhenAvailable??i.revertWhenAvailable??!0};return await a.prepare("UPDATE model_settings SET default_fallback_strength=?,revert_when_available=?,revision=revision+1 WHERE person=?").run(r.defaultFallbackStrength,r.revertWhenAvailable?1:0,n),r});return dt.set(n,e),e}l(Ae,"writeRotationConfig");async function he(){const t=await b();return(await(await N()).prepare("INSERT INTO model_settings(person,openai_device_id) VALUES(?,?) ON CONFLICT(person) DO UPDATE SET openai_device_id=COALESCE(model_settings.openai_device_id,EXCLUDED.openai_device_id) RETURNING openai_device_id").get(t,x())).openai_device_id}l(he,"openAIDeviceId");async function we(t,n=Date.now(),e){const a=await j(t),i=a.filter(s=>s.authFailure===void 0&&Rt(s,e)<=n),r=p(t);return i.length===0?`${r} pool exhausted`:`${r} ${i[0]?.label??t} (${i.length}/${a.length} ready)`}l(we,"formatStatusLine");export{rt as REFRESH_EXCHANGE_TIMEOUT_MS,St as RefreshBusyError,Tt as RefreshTimeoutError,I as aadOf,Ct as addSubscription,pe as commitManagedLogin,Pt as enrichManagedLoginIdentity,we as formatStatusLine,W as insertAccount,jt as loadRotationConfig,le as markSubscriptionAttempt,me as markSubscriptionAuthFailure,ce as markSubscriptionRateLimited,de as markSubscriptionSuccess,_e as modifyElectedSubscription,he as openAIDeviceId,oe as promoteSubscription,te as readAllSubscriptionPools,Kt as readRotationConfig,j as readSubscriptionPool,$t as readSubscriptionPoolRows,fe as refreshSubscriptionCredential,Ht as removeAllManagedAccounts,kt as removeManagedAccount,ie as removeManagedAccountById,se as removeManagedProvider,re as removeSubscription,ae as renameSubscription,lt as upsertModelCooldown,ne as upsertSubscription,Mt as upsertSubscriptionWithUniqueAccount,ue as vendorRateLimit,Ae as writeRotationConfig,ee as writeSubscriptionPool};
@@ -1,2 +1,2 @@
1
- var ce=Object.defineProperty;var u=(t,e)=>ce(t,"name",{value:e,configurable:!0});import{randomBytes as ue}from"node:crypto";import{claimNodeMail as le,acknowledgeNodeMail as fe}from"../../../core/canvas/deliveries.js";import{nodeMailEntry as me}from"../../../core/feed/inbox.js";import{enqueueNodeMail as D,cancelPendingNodeMail as pe}from"../../../core/feed/messages.js";import{assertRecordedCwdExists as ye,reviveNode as L}from"../../../core/runtime/revive.js";import{BrokerUnreachableError as U}from"../../../core/runtime/broker-request.js";import{isBrokerLive as q}from"../../../core/runtime/model-swap.js";import{deliverLive as he,interruptLive as we}from"../../../core/runtime/interactive-deliver.js";import{isProfilePaused as be}from"../../../core/profiles/manifest.js";import{getNode as C,withFreshTerminalGuard as ge}from"../../../core/canvas/canvas.js";import{getById as G,nodeObject as F,ownerForGrantee as ve}from"../../../core/graph/objects.js";import{recordActedOn as _e}from"../../../core/graph/edges.js";import{recordWatch as H}from"../../../core/graph/watches.js";import{publish as V}from"../../../core/graph/events.js";import{readerFor as K}from"../reader.js";import{canRead as ke}from"../../../core/graph/access.js";import{withCanvasWrite as k}from"../../../core/canvas/db.js";import{getPendingStructuredRequestForNode as Q}from"../../../core/canvas/structured-requests.js";import{consumeDeadlineOnWake as X}from"../../../core/feed/messages.js";import{assertNotFinalized as M,assertFinalizedForReopen as Se,commitReopenResident as E}from"../../../core/runtime/reopen.js";import{admitLegacyStructuredOutput as $e}from"../../structured-requests/sidecar.js";import{assertOutputSchemaAccepted as Ne}from"../../../core/runtime/structured-output.js";import{appendSituationalContext as P,formatSituationalProse as je}from"../../../core/runtime/situational-context.js";import{formatDataCard as Y}from"../../../shared/generated-context.js";import{hasNoNaturalCycle as Ae}from"../../../core/runtime/revive-all.js";import{recordPendingParkActivity as Oe}from"../../park-pending.js";import{wantsExecution as qe}from"../../reconcilers/node-lifecycle/wants-execution.js";import{hasFreshGroundState as Ce}from"../../../core/runtime/revive.js";import{CrtrError as xe,notFound as x,usage as d}from"../../../core/errors.js";import{isStartRefusal as Re}from"../../../core/runtime/start-check.js";import{emitEvent as Fe}from"../../../core/events/emit.js";import{assertScope as Me}from"../../../core/scopes.js";import{InputError as I}from"../../../core/io.js";import{ApiError as Ee}from"../../../api/index.js";import{describeObject as Pe,stubOf as Ie}from"../../../core/peer/stubs.js";import{machineNameOf as Z}from"../../../core/peer/names.js";import{callerNode as Te,callerStub as Be,forwardVerb as ee,relayError as te,remoteStub as ze,unknownError as re,withMachine as ne}from"../../peer/forward.js";import{ownerOnly as Je}from"../router.js";import{personId as We}from"../../../core/canvas/person.js";const De=["critical","urgent","normal","deferred"];function oe(t,e){if(typeof t!="object"||t===null||Array.isArray(t))throw d(`${e} must be an object { kind, facts?, body? }`);const a=t,n=a.kind;if(typeof n!="string"||n.trim()==="")throw d(`${e}.kind is required`);if(!n.includes(":"))throw d(`${e}.kind must be namespaced (contain ':'): ${n}`);const r={kind:n},o=a.facts;if(o!==void 0){if(typeof o!="object"||o===null||Array.isArray(o))throw d(`${e}.facts must be an object of string or number values`);const c={};for(const[l,m]of Object.entries(o)){if(typeof m!="string"&&typeof m!="number")throw d(`${e}.facts.${l} must be a string or number`);c[l]=m}r.facts=c}const i=a.body;if(i!==void 0){if(typeof i!="string")throw d(`${e}.body must be a string`);r.body=i}return r}u(oe,"parseCardRequest");function ae(t,e){try{return Y(t.kind,t.facts??{},t.body??"")}catch(a){throw d(`${e}: ${a instanceof Error?a.message:String(a)}`)}}u(ae,"renderCard");function Le(t){if(typeof t!="object"||t===null)throw d("a message requires a JSON body { body, tier?, fresh? }");const e=t,a=e.body,n=e.fresh===!0,r=e.tier,o=e.situational_context,i=e.output_schema;if(i!=null&&typeof i!="string")throw d("output_schema must be a JSON schema string");const c=typeof a=="string"&&a.trim()!=="",l=typeof o=="string"&&o.trim()!=="",m=typeof i=="string"&&i.trim()!=="",v=e.situational_card,S=e.context_cards,b=v===void 0?void 0:oe(v,"situational_card");if(S!==void 0&&!Array.isArray(S))throw d("context_cards must be an array of { kind, facts?, body? }");const p=S?.map((N,$)=>oe(N,`context_cards[${$}]`));if(b!==void 0&&typeof o=="string"&&o!=="")throw d("situational_card and situational_context are mutually exclusive");const w=b!==void 0||p!==void 0&&p.length>0;if(!n&&!c&&!l&&!m&&!w)throw d("a message requires a non-empty body (or fresh: true, situational_context, a runtime card, or output_schema)");if(n&&p!==void 0&&p.length>0)throw d("context_cards cannot ride a fresh revive (no inbox entry carries them)");if(r!==void 0&&!De.includes(r))throw d(`invalid tier: ${String(r)} (expected critical|urgent|normal|deferred)`);const f={body:typeof a=="string"?a:""};r!==void 0&&(f.tier=r),n&&(f.fresh=!0),e.reopen===!0&&(f.reopen=!0),typeof o=="string"&&(f.situational_context=o),b!==void 0&&(f.situational_card=b),p!==void 0&&(f.context_cards=p),typeof i=="string"&&(f.output_schema=i),typeof e.from=="string"&&(f.from=e.from);const y=e.delivery;if(y!==void 0&&y!=="interactive")throw d(`invalid delivery: ${String(y)} (expected interactive)`);if(y==="interactive"){if(n||f.situational_context!==void 0||f.output_schema!==void 0)throw d("interactive delivery supports a body, runtime cards, and reopen only (no fresh, situational_context, or output_schema)");if(!c)throw d("interactive delivery requires a non-empty body");if(f.tier==="deferred")throw d("interactive delivery cannot be deferred");f.delivery="interactive"}return f}u(Le,"parseSendBody");function Ue(t){let e;try{e=JSON.parse(t)}catch{throw d("output_schema must be a JSON schema string")}if(typeof e!="object"||e===null||Array.isArray(e))throw d("output_schema must be a JSON schema object");return e}u(Ue,"parseSchema");function Ge(t){return t.split(`
2
- `)[0].slice(0,120)}u(Ge,"label");function ie(t,e){return e===null?"":Y("reopen-final-report",{report:`${t}/${e}`},"This node previously completed work. Read this final report before acting on the new instruction.")}u(ie,"previousFinalReportCard");async function He(t,e,a){if(a!==null&&a!=="human"&&(await G(t,a))?.type==="node"){const o=await F(t,a);return{actor:o,senderNode:o}}if(a==="human")return{actor:await ve(t,We()),senderNode:null};const n=await K(t,e);return{actor:n.class==="person"?n.person:n.class==="app"?n.app:n.node,senderNode:n.class==="node"?n.node:null}}u(He,"messageActor");async function se(t,e,a,n,r,o){const i=await F(t,a),{actor:c,senderNode:l}=await He(t,e,n),m=r===null?{}:{pointer:r};await _e(t,c,i),l!==null&&l.id!==i.id&&await H(t,l,i,"message",{endsOn:o&&r!==null?`result:${r}`:"final"}),await V(t,{event:"messaged",object:i,actor:c,attrs:{},...m}),l!==null&&await V(t,{event:"sent",object:l,actor:l,attrs:{to:i.id},...m})}u(se,"recordMessage");function Ve(t,e){return new I({error:"deferred_no_natural_cycle",message:`${t} is ${e} with no natural next cycle ahead of it \u2014 a deferred message would never be delivered.`,next:"Use --tier normal, urgent, or critical to wake it now, or --reopen (with a body or --fresh) to re-task it first."})}u(Ve,"deferredNoNaturalCycle");async function Ke(t){if(!await Ce(t))throw new Ee(422,"unprocessable",`node ${t} has no goal/roadmap on disk \u2014 a fresh revive would resume amnesiac.`)}u(Ke,"assertRecoverableForFresh");function Qe(t,e){return t instanceof I?{error:t.payload.error,message:t.payload.message,next:t.payload.next,message_id:e}:t instanceof xe?{error:t.code,message:t.message,message_id:e}:Re(t)?{error:t.code,message:t.message,message_id:e}:{error:"wake_failed",message:"the target could not be woken; see the daemon log",message_id:e}}u(Qe,"wakeFailure");async function Xe(t,e){const a=typeof t.body=="object"&&t.body!==null&&!Array.isArray(t.body)?{...t.body}:t.body;typeof a=="object"&&a!==null&&delete a.from;const n=await ee(t,e,{method:"POST",path:`/v1/nodes/${encodeURIComponent(e)}/messages`,body:a});if(n.kind==="local")return null;if(n.kind==="unknown")throw re(e,n.unreachable);if(n.status>=400)throw te(n.status,n.body);return await k(async r=>{const o=await Te(r,t);if(o===null)return;const i=n.body?.object,c=await ze(r,e,"node",n.machine.id,i);await H(r,o,c,"message",{endsOn:"final"})}),{status:n.status,body:ne(n.body,n.machine)}}u(Xe,"forwardMessage");async function Ye(t){const e=await Ze(t);if(t.principal.class!=="forwarded"||typeof e.body!="object"||e.body===null)return e;const a=await k(async n=>{const r=await F(n,t.params.id);return await ke(n,await K(n,t),r)?await Pe(n,r):{id:r.id,type:r.type,kind:null,name:r.id,owner:null}});return{...e,body:{...e.body,object:a}}}u(Ye,"handleMessage");async function Ze(t){const e=t.params.id,a=await Xe(t,e);if(a!==null)return a;const n=await C(e);if(n===null)throw x(`unknown node: ${e}`,{received:e});const r=Le(t.body),o=r.tier??"normal",i=be(n.profile_id);r.reopen&&!i&&!q(n)&&await ye(e,n);const c=t.principal.class==="forwarded"?await k(async s=>(await Be(s,t))?.id??null):r.from??null;if(c!==null){const s=await C(c);s!==null&&Me(s,"crtr:act")}const l=c===null?null:await k(async s=>{const h=await G(s,c);return h===null?null:(await Ie(s,h))?.home_machine??null}),m=l===null?void 0:`${c} on ${Z(l)}`,v=t.principal.class==="broker"?t.principal.node:null,S=l===null?{}:{from_machine:Z(l)},b=r.body.trim()!=="",p=r.situational_card!==void 0?ae(r.situational_card,"situational_card"):r.situational_context!==void 0?je(r.situational_context.trim()):"",w=p!=="",f=(r.context_cards??[]).map((s,h)=>ae(s,`context_cards[${h}]`)),y=r.output_schema!==void 0&&r.output_schema.trim()!==""?Ue(r.output_schema):null;y!==null&&await Ne(y);let N=!1;const $=u(async s=>{if(!(y===null||N)){if(await Q(e)!==null)throw new I({error:"structured_request_conflict",message:`node ${e} already has a pending structured request`,next:"Wait for the current request to settle before requesting another structured result."});await $e(e,"oneoff",y,s),N=!0}},"ensureSchema");if(r.fresh){const s=r.reopen?await Se(e):null;r.reopen||await M(e),await Ke(e),await $(),w&&await P(e,p),r.reopen&&await E(e,s,v);const h=await L(e,{resume:!1,capacity:"refuse"});return{status:201,body:{node_id:e,delivered:!1,revived:h.launch!==void 0}}}r.delivery==="interactive"&&!r.reopen&&await M(e);let T=!1,_="";if(r.delivery==="interactive"&&r.reopen&&(_=ie(e,await E(e,void 0,v)),T=!0),r.delivery==="interactive"&&await $(),r.delivery==="interactive"&&!i&&!n.run_id&&q(n))try{return w&&await P(e,p),await he(e,r.body,{cards:[..._===""?[]:[_],...w?[p]:[],...f],origin:c==="human"?{type:"human"}:{type:"runtime",kind:"inbox",entries:[{...c===null?{}:{from:c},...m===void 0?{}:{fromName:m},kind:"message",tier:o}]}}),await k(async h=>await se(h,t,e,c,null,!1)),await X(e),{status:201,body:{node_id:e,delivered:!0,revived:!1,delivered_via:"engine"}}}catch(s){if(!(s instanceof U))throw s}const B=u(async()=>{r.reopen||await M(e);const s=ue(16).toString("hex"),h=u(async O=>await se(O,t,e,c,s,y!==null),"withinEnqueue");await $(s),w&&await P(e,p),r.reopen&&!T&&(_=ie(e,await E(e,void 0,v)));const R=[..._===""?[]:[_],...f],W=R.length>0?{cards:R}:{};if(b||y!==null){const O=b?r.body:`A one-off structured-output request has been granted. Submit a result matching the requested schema with the \`submit_result\` tool (\`request_id: "${(await Q(e))?.request_id??"<request-id>"}"\`) before you stop; after it is accepted, continue normally.`;return await D(e,{senderNodeId:c,...m===void 0?{}:{senderName:m},urgency:o,wake:1,kind:"message",messageId:s,withinEnqueue:h,label:Ge(O),bodyJson:{body:O,...S,...w?{situational:!0}:{},...W}})}return await D(e,{senderNodeId:c,...m===void 0?{}:{senderName:m},urgency:o,wake:1,kind:"message",messageId:s,withinEnqueue:h,label:w?"(ambient context updated)":"(context delivered)",bodyJson:{...w?{situational:!0}:{},situationalOnly:!0,...W}})},"deliverImmediate"),g=await u(async()=>{if(o==="deferred"){const s=await ge(e,Ae,B);if(s.kind==="missing")throw x(`unknown node: ${e}`,{received:e});if(s.kind==="terminal")throw Ve(e,s.status);return s.result}return await B()},"deliver")();g.urgency!=="deferred"&&await k(async()=>Oe(e));const j=await C(e);if(j===null)throw x(`unknown node: ${e}`,{received:e});n.frozen_at!==null&&await X(e);let z=!1,J=!1,A;if((r.reopen||j.lifecycle==="terminal"||!await qe(j))&&g.urgency!=="deferred"&&!i&&!q(j))try{const s=await L(e,{resume:!0,capacity:"freeze"});z=s.launch!==void 0,J=s.outcome==="frozen"}catch(s){A=Qe(s,g.messageId),Fe({level:"error",event:"message.wake_failed",node_id:e,error:s,fields:{message_id:g.messageId,error_code:A.error}})}return{status:201,body:{node_id:e,delivered:!0,revived:z,...J?{not_revived_reason:"capacity_frozen"}:{},...A===void 0?{}:{wake_failed:A},delivered_at:g.createdAt,...g.urgency===o?{}:{delivered_tier:g.urgency},...r.delivery==="interactive"?{delivered_via:"inbox"}:{}}}}u(Ze,"handleMessageHere");async function et(t){const e=t.params.id,a=await ee(t,e,{method:"POST",path:`/v1/nodes/${encodeURIComponent(e)}/interrupt`,body:t.body});if(a.kind==="unknown")throw re(e,a.unreachable);if(a.kind==="remote"){if(a.status>=400)throw te(a.status,a.body);return{status:a.status,body:ne(a.body,a.machine)}}const n=await C(e);if(n===null)throw x(`unknown node: ${e}`,{received:e});const r=await pe(e,{senderNodeId:"human",kind:"message"});let o=!1;if(q(n))try{o=await we(e)!=="idle"}catch(c){if(!(c instanceof U))throw c}return{status:200,body:{node_id:e,outcome:o?"aborted_turn":r.length>0?"canceled_pending":"idle",aborted_turn:o,canceled_pending:r.length}}}u(et,"handleInterrupt");function de(t){if(typeof t.body!="object"||t.body===null||Array.isArray(t.body))throw d("mail requires an object body");const e=t.body;if(typeof e.execution_id!="string"||e.execution_id.trim()==="")throw d("execution_id is required");return e}u(de,"mailBody");async function tt(t){const e=de(t),a=e.channel;if(a!=="wake"&&a!=="passive"&&a!=="deferred_run")throw d("channel must be wake, passive, or deferred_run");const n=await le(t.params.id,e.execution_id,a);return{status:200,body:{action:n.action,deliveries:n.deliveries.map(o=>({delivery_id:o.deliveryId,attempts:o.attempts,handoff:o.handoff,entry:{...me(o),seq:o.message.seq}}))}}}u(tt,"handleMailClaim");async function rt(t){const e=de(t);if(!Array.isArray(e.deliveries))throw d("deliveries must be an array");const a=e.deliveries.map(o=>{if(typeof o!="object"||o===null||Array.isArray(o))throw d("each delivery must be an object");const i=o;if(typeof i.delivery_id!="string"||i.delivery_id==="")throw d("delivery_id is required");if(!Number.isSafeInteger(i.attempts)||i.attempts<1)throw d("attempts must be a positive integer");if(i.disposition!=="acknowledged"&&i.disposition!=="released")throw d("disposition must be acknowledged or released");return{delivery_id:i.delivery_id,attempts:i.attempts,disposition:i.disposition}}),n=await fe(t.params.id,e.execution_id,a.map(o=>({deliveryId:o.delivery_id,attempts:o.attempts,disposition:o.disposition})));return{status:200,body:{action:n.action,results:n.results.map(o=>({delivery_id:o.deliveryId,outcome:o.outcome}))}}}u(rt,"handleMailAcknowledge");const Gt=Je([{method:"POST",pattern:"/v1/nodes/:id/mail/claim",handler:tt},{method:"POST",pattern:"/v1/nodes/:id/mail/acknowledge",handler:rt}]),Ht=[{method:"POST",pattern:"/v1/nodes/:id/messages",scope:"crtr:act",handler:Ye},{method:"POST",pattern:"/v1/nodes/:id/interrupt",scope:"crtr:act",handler:et}];export{Gt as brokerMailRoutes,Ye as handleMessage,Ht as messageRoutes};
1
+ var ce=Object.defineProperty;var u=(t,e)=>ce(t,"name",{value:e,configurable:!0});import{randomBytes as ue}from"node:crypto";import{claimNodeMail as le,acknowledgeNodeMail as fe}from"../../../core/canvas/deliveries.js";import{nodeMailEntry as me}from"../../../core/feed/inbox.js";import{enqueueNodeMail as D,cancelPendingNodeMail as pe}from"../../../core/feed/messages.js";import{assertCheckoutNotRemoved as ye,assertRecordedCwdExists as he,reviveNode as L}from"../../../core/runtime/revive.js";import{BrokerUnreachableError as U}from"../../../core/runtime/broker-request.js";import{isBrokerLive as q}from"../../../core/runtime/model-swap.js";import{deliverLive as we,interruptLive as be}from"../../../core/runtime/interactive-deliver.js";import{isProfilePaused as ge}from"../../../core/profiles/manifest.js";import{getNode as C,withFreshTerminalGuard as ve}from"../../../core/canvas/canvas.js";import{getById as G,nodeObject as F,ownerForGrantee as _e}from"../../../core/graph/objects.js";import{recordActedOn as ke}from"../../../core/graph/edges.js";import{recordWatch as H}from"../../../core/graph/watches.js";import{publish as V}from"../../../core/graph/events.js";import{readerFor as K}from"../reader.js";import{canRead as Se}from"../../../core/graph/access.js";import{withCanvasWrite as k}from"../../../core/canvas/db.js";import{getPendingStructuredRequestForNode as Q}from"../../../core/canvas/structured-requests.js";import{consumeDeadlineOnWake as X}from"../../../core/feed/messages.js";import{assertNotFinalized as M,assertFinalizedForReopen as Ne,commitReopenResident as E}from"../../../core/runtime/reopen.js";import{admitLegacyStructuredOutput as $e}from"../../structured-requests/sidecar.js";import{assertOutputSchemaAccepted as je}from"../../../core/runtime/structured-output.js";import{appendSituationalContext as P,formatSituationalProse as Ae}from"../../../core/runtime/situational-context.js";import{formatDataCard as Y}from"../../../shared/generated-context.js";import{hasNoNaturalCycle as Oe}from"../../../core/runtime/revive-all.js";import{recordPendingParkActivity as qe}from"../../park-pending.js";import{wantsExecution as Ce}from"../../reconcilers/node-lifecycle/wants-execution.js";import{hasFreshGroundState as xe}from"../../../core/runtime/revive.js";import{CrtrError as Re,notFound as x,usage as d}from"../../../core/errors.js";import{isStartRefusal as Fe}from"../../../core/runtime/start-check.js";import{emitEvent as Me}from"../../../core/events/emit.js";import{assertScope as Ee}from"../../../core/scopes.js";import{InputError as I}from"../../../core/io.js";import{ApiError as Pe}from"../../../api/index.js";import{describeObject as Ie,stubOf as Te}from"../../../core/peer/stubs.js";import{machineNameOf as Z}from"../../../core/peer/names.js";import{callerNode as Be,callerStub as ze,forwardVerb as ee,relayError as te,remoteStub as Je,unknownError as re,withMachine as ne}from"../../peer/forward.js";import{ownerOnly as We}from"../router.js";import{personId as De}from"../../../core/canvas/person.js";const Le=["critical","urgent","normal","deferred"];function oe(t,e){if(typeof t!="object"||t===null||Array.isArray(t))throw d(`${e} must be an object { kind, facts?, body? }`);const a=t,n=a.kind;if(typeof n!="string"||n.trim()==="")throw d(`${e}.kind is required`);if(!n.includes(":"))throw d(`${e}.kind must be namespaced (contain ':'): ${n}`);const r={kind:n},o=a.facts;if(o!==void 0){if(typeof o!="object"||o===null||Array.isArray(o))throw d(`${e}.facts must be an object of string or number values`);const c={};for(const[l,m]of Object.entries(o)){if(typeof m!="string"&&typeof m!="number")throw d(`${e}.facts.${l} must be a string or number`);c[l]=m}r.facts=c}const i=a.body;if(i!==void 0){if(typeof i!="string")throw d(`${e}.body must be a string`);r.body=i}return r}u(oe,"parseCardRequest");function ae(t,e){try{return Y(t.kind,t.facts??{},t.body??"")}catch(a){throw d(`${e}: ${a instanceof Error?a.message:String(a)}`)}}u(ae,"renderCard");function Ue(t){if(typeof t!="object"||t===null)throw d("a message requires a JSON body { body, tier?, fresh? }");const e=t,a=e.body,n=e.fresh===!0,r=e.tier,o=e.situational_context,i=e.output_schema;if(i!=null&&typeof i!="string")throw d("output_schema must be a JSON schema string");const c=typeof a=="string"&&a.trim()!=="",l=typeof o=="string"&&o.trim()!=="",m=typeof i=="string"&&i.trim()!=="",v=e.situational_card,S=e.context_cards,b=v===void 0?void 0:oe(v,"situational_card");if(S!==void 0&&!Array.isArray(S))throw d("context_cards must be an array of { kind, facts?, body? }");const p=S?.map(($,N)=>oe($,`context_cards[${N}]`));if(b!==void 0&&typeof o=="string"&&o!=="")throw d("situational_card and situational_context are mutually exclusive");const w=b!==void 0||p!==void 0&&p.length>0;if(!n&&!c&&!l&&!m&&!w)throw d("a message requires a non-empty body (or fresh: true, situational_context, a runtime card, or output_schema)");if(n&&p!==void 0&&p.length>0)throw d("context_cards cannot ride a fresh revive (no inbox entry carries them)");if(r!==void 0&&!Le.includes(r))throw d(`invalid tier: ${String(r)} (expected critical|urgent|normal|deferred)`);const f={body:typeof a=="string"?a:""};r!==void 0&&(f.tier=r),n&&(f.fresh=!0),e.reopen===!0&&(f.reopen=!0),typeof o=="string"&&(f.situational_context=o),b!==void 0&&(f.situational_card=b),p!==void 0&&(f.context_cards=p),typeof i=="string"&&(f.output_schema=i),typeof e.from=="string"&&(f.from=e.from);const y=e.delivery;if(y!==void 0&&y!=="interactive")throw d(`invalid delivery: ${String(y)} (expected interactive)`);if(y==="interactive"){if(n||f.situational_context!==void 0||f.output_schema!==void 0)throw d("interactive delivery supports a body, runtime cards, and reopen only (no fresh, situational_context, or output_schema)");if(!c)throw d("interactive delivery requires a non-empty body");if(f.tier==="deferred")throw d("interactive delivery cannot be deferred");f.delivery="interactive"}return f}u(Ue,"parseSendBody");function Ge(t){let e;try{e=JSON.parse(t)}catch{throw d("output_schema must be a JSON schema string")}if(typeof e!="object"||e===null||Array.isArray(e))throw d("output_schema must be a JSON schema object");return e}u(Ge,"parseSchema");function He(t){return t.split(`
2
+ `)[0].slice(0,120)}u(He,"label");function ie(t,e){return e===null?"":Y("reopen-final-report",{report:`${t}/${e}`},"This node previously completed work. Read this final report before acting on the new instruction.")}u(ie,"previousFinalReportCard");async function Ve(t,e,a){if(a!==null&&a!=="human"&&(await G(t,a))?.type==="node"){const o=await F(t,a);return{actor:o,senderNode:o}}if(a==="human")return{actor:await _e(t,De()),senderNode:null};const n=await K(t,e);return{actor:n.class==="person"?n.person:n.class==="app"?n.app:n.node,senderNode:n.class==="node"?n.node:null}}u(Ve,"messageActor");async function se(t,e,a,n,r,o){const i=await F(t,a),{actor:c,senderNode:l}=await Ve(t,e,n),m=r===null?{}:{pointer:r};await ke(t,c,i),l!==null&&l.id!==i.id&&await H(t,l,i,"message",{endsOn:o&&r!==null?`result:${r}`:"final"}),await V(t,{event:"messaged",object:i,actor:c,attrs:{},...m}),l!==null&&await V(t,{event:"sent",object:l,actor:l,attrs:{to:i.id},...m})}u(se,"recordMessage");function Ke(t,e){return new I({error:"deferred_no_natural_cycle",message:`${t} is ${e} with no natural next cycle ahead of it \u2014 a deferred message would never be delivered.`,next:"Use --tier normal, urgent, or critical to wake it now, or --reopen (with a body or --fresh) to re-task it first."})}u(Ke,"deferredNoNaturalCycle");async function Qe(t){if(!await xe(t))throw new Pe(422,"unprocessable",`node ${t} has no goal/roadmap on disk \u2014 a fresh revive would resume amnesiac.`)}u(Qe,"assertRecoverableForFresh");function Xe(t,e){return t instanceof I?{error:t.payload.error,message:t.payload.message,next:t.payload.next,message_id:e}:t instanceof Re?{error:t.code,message:t.message,message_id:e}:Fe(t)?{error:t.code,message:t.message,message_id:e}:{error:"wake_failed",message:"the target could not be woken; see the daemon log",message_id:e}}u(Xe,"wakeFailure");async function Ye(t,e){const a=typeof t.body=="object"&&t.body!==null&&!Array.isArray(t.body)?{...t.body}:t.body;typeof a=="object"&&a!==null&&delete a.from;const n=await ee(t,e,{method:"POST",path:`/v1/nodes/${encodeURIComponent(e)}/messages`,body:a});if(n.kind==="local")return null;if(n.kind==="unknown")throw re(e,n.unreachable);if(n.status>=400)throw te(n.status,n.body);return await k(async r=>{const o=await Be(r,t);if(o===null)return;const i=n.body?.object,c=await Je(r,e,"node",n.machine.id,i);await H(r,o,c,"message",{endsOn:"final"})}),{status:n.status,body:ne(n.body,n.machine)}}u(Ye,"forwardMessage");async function Ze(t){const e=await et(t);if(t.principal.class!=="forwarded"||typeof e.body!="object"||e.body===null)return e;const a=await k(async n=>{const r=await F(n,t.params.id);return await Se(n,await K(n,t),r)?await Ie(n,r):{id:r.id,type:r.type,kind:null,name:r.id,owner:null}});return{...e,body:{...e.body,object:a}}}u(Ze,"handleMessage");async function et(t){const e=t.params.id,a=await Ye(t,e);if(a!==null)return a;const n=await C(e);if(n===null)throw x(`unknown node: ${e}`,{received:e});const r=Ue(t.body),o=r.tier??"normal",i=ge(n.profile_id);r.reopen&&ye(e,n),r.reopen&&!i&&!q(n)&&await he(e,n);const c=t.principal.class==="forwarded"?await k(async s=>(await ze(s,t))?.id??null):r.from??null;if(c!==null){const s=await C(c);s!==null&&Ee(s,"crtr:act")}const l=c===null?null:await k(async s=>{const h=await G(s,c);return h===null?null:(await Te(s,h))?.home_machine??null}),m=l===null?void 0:`${c} on ${Z(l)}`,v=t.principal.class==="broker"?t.principal.node:null,S=l===null?{}:{from_machine:Z(l)},b=r.body.trim()!=="",p=r.situational_card!==void 0?ae(r.situational_card,"situational_card"):r.situational_context!==void 0?Ae(r.situational_context.trim()):"",w=p!=="",f=(r.context_cards??[]).map((s,h)=>ae(s,`context_cards[${h}]`)),y=r.output_schema!==void 0&&r.output_schema.trim()!==""?Ge(r.output_schema):null;y!==null&&await je(y);let $=!1;const N=u(async s=>{if(!(y===null||$)){if(await Q(e)!==null)throw new I({error:"structured_request_conflict",message:`node ${e} already has a pending structured request`,next:"Wait for the current request to settle before requesting another structured result."});await $e(e,"oneoff",y,s),$=!0}},"ensureSchema");if(r.fresh){const s=r.reopen?await Ne(e):null;r.reopen||await M(e),await Qe(e),await N(),w&&await P(e,p),r.reopen&&await E(e,s,v);const h=await L(e,{resume:!1,capacity:"refuse"});return{status:201,body:{node_id:e,delivered:!1,revived:h.launch!==void 0}}}r.delivery==="interactive"&&!r.reopen&&await M(e);let T=!1,_="";if(r.delivery==="interactive"&&r.reopen&&(_=ie(e,await E(e,void 0,v)),T=!0),r.delivery==="interactive"&&await N(),r.delivery==="interactive"&&!i&&!n.run_id&&q(n))try{return w&&await P(e,p),await we(e,r.body,{cards:[..._===""?[]:[_],...w?[p]:[],...f],origin:c==="human"?{type:"human"}:{type:"runtime",kind:"inbox",entries:[{...c===null?{}:{from:c},...m===void 0?{}:{fromName:m},kind:"message",tier:o}]}}),await k(async h=>await se(h,t,e,c,null,!1)),await X(e),{status:201,body:{node_id:e,delivered:!0,revived:!1,delivered_via:"engine"}}}catch(s){if(!(s instanceof U))throw s}const B=u(async()=>{r.reopen||await M(e);const s=ue(16).toString("hex"),h=u(async O=>await se(O,t,e,c,s,y!==null),"withinEnqueue");await N(s),w&&await P(e,p),r.reopen&&!T&&(_=ie(e,await E(e,void 0,v)));const R=[..._===""?[]:[_],...f],W=R.length>0?{cards:R}:{};if(b||y!==null){const O=b?r.body:`A one-off structured-output request has been granted. Submit a result matching the requested schema with the \`submit_result\` tool (\`request_id: "${(await Q(e))?.request_id??"<request-id>"}"\`) before you stop; after it is accepted, continue normally.`;return await D(e,{senderNodeId:c,...m===void 0?{}:{senderName:m},urgency:o,wake:1,kind:"message",messageId:s,withinEnqueue:h,label:He(O),bodyJson:{body:O,...S,...w?{situational:!0}:{},...W}})}return await D(e,{senderNodeId:c,...m===void 0?{}:{senderName:m},urgency:o,wake:1,kind:"message",messageId:s,withinEnqueue:h,label:w?"(ambient context updated)":"(context delivered)",bodyJson:{...w?{situational:!0}:{},situationalOnly:!0,...W}})},"deliverImmediate"),g=await u(async()=>{if(o==="deferred"){const s=await ve(e,Oe,B);if(s.kind==="missing")throw x(`unknown node: ${e}`,{received:e});if(s.kind==="terminal")throw Ke(e,s.status);return s.result}return await B()},"deliver")();g.urgency!=="deferred"&&await k(async()=>qe(e));const j=await C(e);if(j===null)throw x(`unknown node: ${e}`,{received:e});n.frozen_at!==null&&await X(e);let z=!1,J=!1,A;if((r.reopen||j.lifecycle==="terminal"||!await Ce(j))&&g.urgency!=="deferred"&&!i&&!q(j))try{const s=await L(e,{resume:!0,capacity:"freeze"});z=s.launch!==void 0,J=s.outcome==="frozen"}catch(s){A=Xe(s,g.messageId),Me({level:"error",event:"message.wake_failed",node_id:e,error:s,fields:{message_id:g.messageId,error_code:A.error}})}return{status:201,body:{node_id:e,delivered:!0,revived:z,...J?{not_revived_reason:"capacity_frozen"}:{},...A===void 0?{}:{wake_failed:A},delivered_at:g.createdAt,...g.urgency===o?{}:{delivered_tier:g.urgency},...r.delivery==="interactive"?{delivered_via:"inbox"}:{}}}}u(et,"handleMessageHere");async function tt(t){const e=t.params.id,a=await ee(t,e,{method:"POST",path:`/v1/nodes/${encodeURIComponent(e)}/interrupt`,body:t.body});if(a.kind==="unknown")throw re(e,a.unreachable);if(a.kind==="remote"){if(a.status>=400)throw te(a.status,a.body);return{status:a.status,body:ne(a.body,a.machine)}}const n=await C(e);if(n===null)throw x(`unknown node: ${e}`,{received:e});const r=await pe(e,{senderNodeId:"human",kind:"message"});let o=!1;if(q(n))try{o=await be(e)!=="idle"}catch(c){if(!(c instanceof U))throw c}return{status:200,body:{node_id:e,outcome:o?"aborted_turn":r.length>0?"canceled_pending":"idle",aborted_turn:o,canceled_pending:r.length}}}u(tt,"handleInterrupt");function de(t){if(typeof t.body!="object"||t.body===null||Array.isArray(t.body))throw d("mail requires an object body");const e=t.body;if(typeof e.execution_id!="string"||e.execution_id.trim()==="")throw d("execution_id is required");return e}u(de,"mailBody");async function rt(t){const e=de(t),a=e.channel;if(a!=="wake"&&a!=="passive"&&a!=="deferred_run")throw d("channel must be wake, passive, or deferred_run");const n=await le(t.params.id,e.execution_id,a);return{status:200,body:{action:n.action,deliveries:n.deliveries.map(o=>({delivery_id:o.deliveryId,attempts:o.attempts,handoff:o.handoff,entry:{...me(o),seq:o.message.seq}}))}}}u(rt,"handleMailClaim");async function nt(t){const e=de(t);if(!Array.isArray(e.deliveries))throw d("deliveries must be an array");const a=e.deliveries.map(o=>{if(typeof o!="object"||o===null||Array.isArray(o))throw d("each delivery must be an object");const i=o;if(typeof i.delivery_id!="string"||i.delivery_id==="")throw d("delivery_id is required");if(!Number.isSafeInteger(i.attempts)||i.attempts<1)throw d("attempts must be a positive integer");if(i.disposition!=="acknowledged"&&i.disposition!=="released")throw d("disposition must be acknowledged or released");return{delivery_id:i.delivery_id,attempts:i.attempts,disposition:i.disposition}}),n=await fe(t.params.id,e.execution_id,a.map(o=>({deliveryId:o.delivery_id,attempts:o.attempts,disposition:o.disposition})));return{status:200,body:{action:n.action,results:n.results.map(o=>({delivery_id:o.deliveryId,outcome:o.outcome}))}}}u(nt,"handleMailAcknowledge");const Ht=We([{method:"POST",pattern:"/v1/nodes/:id/mail/claim",handler:rt},{method:"POST",pattern:"/v1/nodes/:id/mail/acknowledge",handler:nt}]),Vt=[{method:"POST",pattern:"/v1/nodes/:id/messages",scope:"crtr:act",handler:Ze},{method:"POST",pattern:"/v1/nodes/:id/interrupt",scope:"crtr:act",handler:tt}];export{Ht as brokerMailRoutes,Ze as handleMessage,Vt as messageRoutes};