@north-light/cli 0.3.721 → 0.3.723
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/dto/recovery.d.ts +2 -0
- package/dist/builtin-memory/internal/plugins.md +3 -3
- package/dist/clients/attach/viewer.js +1 -1
- package/dist/commands/node/inspect.js +7 -7
- package/dist/commands/pkg/browse/model.d.ts +1 -1
- package/dist/commands/profile/environment.js +2 -2
- package/dist/commands/sys/setup-core.d.ts +1 -1
- package/dist/commands/sys/setup-core.js +6 -6
- package/dist/commands/sys/setup.js +1 -1
- package/dist/core/canvas/schema-pg/032-model-cooldown-vendor-limit.sql +4 -0
- package/dist/core/canvas/schema-version.d.ts +1 -1
- package/dist/core/canvas/schema-version.js +1 -1
- package/dist/core/environment-starter-script.d.ts +1 -0
- package/dist/core/environment-starter-script.js +58 -0
- package/dist/core/llm/run.js +2 -2
- package/dist/core/managed-providers.d.ts +9 -1
- package/dist/core/preview-registry.js +3 -3
- package/dist/core/provider-failure.d.ts +2 -0
- package/dist/core/provider-failure.js +1 -1
- package/dist/core/runtime/broker/model-adapter.js +3 -3
- package/dist/core/runtime/revive.d.ts +2 -0
- package/dist/core/runtime/revive.js +2 -2
- package/dist/core/runtime/runner/blaxel/image-build.d.ts +3 -0
- package/dist/core/runtime/runner/blaxel/image-build.js +6 -6
- package/dist/core/subscription-state.d.ts +4 -4
- package/dist/core/subscription-state.js +1 -1
- package/dist/daemon/api/handlers/messages.js +2 -2
- package/dist/daemon/api/handlers/nodes.js +1 -1
- package/dist/daemon/reconcilers/broker-supervision.js +3 -3
- package/package.json +3 -3
- package/packages/crouter-api/dist/commands/node/inspect.js +2 -1
- package/packages/crouter-api/dist/commands/pkg/browse/model.js +1 -1
- package/packages/crouter-api/dist/commands/profile/environment.js +23 -5
- package/packages/crouter-api/dist/commands/sys/setup-core.js +2 -10
- package/packages/crouter-api/dist/commands/sys/setup.js +1 -1
- package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
- package/packages/crouter-api/dist/core/environment-starter-script.js +61 -0
- package/packages/crouter-api/dist/core/llm/run.js +13 -2
- package/packages/crouter-api/dist/core/preview-registry.js +1 -5
- package/packages/crouter-api/dist/core/provider-failure.js +9 -0
- package/packages/crouter-api/dist/core/runtime/broker/model-adapter.js +3 -1
- package/packages/crouter-api/dist/core/runtime/revive.js +11 -0
- package/packages/crouter-api/dist/core/runtime/runner/blaxel/image-build.js +16 -1
- package/packages/crouter-api/dist/core/subscription-state.js +26 -10
- package/packages/crouter-api/dist/daemon/reconcilers/broker-supervision.js +3 -1
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
|
@@ -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{
|
|
2
|
-
`)[0].slice(0,120)}u(
|
|
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};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var je=Object.defineProperty;var d=(e,n)=>je(e,"name",{value:n,configurable:!0});import{randomUUID as Fe}from"node:crypto";import{envProfileId as Ge}from"../../../shared/env.js";import{pausedCanvasProfiles as xe}from"../../../core/profiles/manifest.js";import{existsSync as $,realpathSync as oe,statSync as ae}from"node:fs";import{isAbsolute as W,resolve as L}from"node:path";import{appendSituationalContext as Be,formatSituationalProse as We}from"../../../core/runtime/situational-context.js";import{closeNode as Ue}from"../../../core/runtime/close.js";import{reviveNode as de}from"../../../core/runtime/revive.js";import{nowIso as U}from"../../../core/fs-utils.js";import{appPaidLaunch as Ve,assertLaunchModelRegistered as V,forkNode as Ke,resolveForkSource as se,spawnChildPrepared as Je}from"../../../core/runtime/spawn.js";import{forkSourceNode as le,newNodeId as ce}from"../../../core/runtime/nodes.js";import{abandonCreateRequest as ue,CREATE_LEASE_RENEW_MS as ze,claimCreateLease as fe,createLeaseLive as He,renewCreateLease as Ye,childrenOf as Qe,completeCreateRequest as pe,findCreateRequest as me,getNode as b,recordCreateRequestNode as Xe,reserveCreateRequest as we,reserveCreateRequestNode as Ze,listNodes as qe,recordRespawnAttempt as en,subscribersOf as nn,subscriptionsOf as he,updateNode as T}from"../../../core/canvas/canvas.js";import{armControllerWait as tn,liveControllerWaits as rn}from"../../../core/canvas/waits.js";import{withCanvasWrite as K}from"../../../core/canvas/db.js";import{markNodeRead as on}from"../../../core/canvas/recovery.js";import{nodeObject as an}from"../../../core/graph/objects.js";import{recordActedOn as dn}from"../../../core/graph/edges.js";import{publish as sn}from"../../../core/graph/events.js";import{readerFor as ln}from"../reader.js";import{relocateSessionCwd as cn,unbindSession as un}from"../../../core/canvas/sessions.js";import{ticketCountsForNodes as fn}from"../../../core/canvas/attention.js";import{isSafeNodeId as pn}from"../../../core/canvas/paths.js";import{contextDir as ye,nodeAgentDir as J}from"../../../core/canvas/node-agent-paths.js";import{checkCronBirth as mn,cronRefusalError as wn}from"../../cron/authority.js";import{cronBirthPlacement as hn}from"../../cron/armed-context.js";import{existsBeneath as yn,isAbsentOrRefused as _n,isBeneathRefusal as gn,readdirBeneath as bn}from"../../../core/spaces/open-beneath.js";import{readNodeMessagesPage as vn,readNodeSession as kn,readNodeSnapshot as Sn,transcriptMarkdown as In}from"../../../core/runtime/node-read.js";import{toolCallIds as Rn,withoutImages as _e}from"../../../core/runtime/broker-protocol.js";import{welcomeWindow as En}from"../../../core/runtime/session-cycles.js";import{assembleNodeSubject as On}from"../../../core/substrate/subject.js";import{reviveAll as An}from"../../../core/runtime/revive-all.js";import{promoteAsync as Cn,requestYieldAsync as $n,reshapeNodeAsync as z}from"../../../core/runtime/promote.js";import{recycleNode as Tn}from"../../../core/runtime/recycle.js";import{relaunchRoot as Nn}from"../../../core/runtime/reset.js";import{assertReopenGate as Pn}from"../../../core/runtime/reopen.js";import{requireCurrentExecution as Dn}from"./broker-recovery.js";import{readOutputRequest as Ln}from"../../../core/runtime/output-result.js";import{writeYieldMessage as Mn,readGoal as jn,captureGoalIfAbsent as Fn}from"../../../core/runtime/kickoff.js";import{ensureRoadmap as Gn,hasRoadmap as xn}from"../../../core/runtime/roadmap.js";import{renameWindow as Bn}from"../../../core/runtime/placement.js";import{buildLaunchSpecAsync as Wn,explicitModelIntent as Un,normalizeModel as Vn,readMergedLaunchConfigAsync as ge}from"../../../core/runtime/launch.js";import{modelRequestFromConfig as Kn}from"../../../core/model-routes.js";import{persistDormantModel as Jn,setModelLive as zn}from"../../../core/runtime/model-swap.js";import{waitForBrokerViewSocket as be}from"../../../core/runtime/view-socket.js";import{viewTransport as Hn}from"../../runs/observer.js";import{BrokerUnreachableError as Yn}from"../../../core/runtime/broker-request.js";import{boundFleet as M}from"../../../core/runtime/fleet.js";import{admitLegacyStructuredOutput as Qn}from"../../structured-requests/sidecar.js";import{assertOutputSchemaAccepted as Xn}from"../../../core/runtime/structured-output.js";import{OUTCOME_PAYLOAD_MAX_BYTES as ve}from"../../../core/canvas/types.js";import{HUMAN_ACTION_NAME_PATTERN as Zn}from"../../../core/human/action-binding.js";import{resolveHumanAction as qn}from"../../../core/human-actions.js";import{parseDurationMs as et}from"../../../core/wake.js";import{claimWarmNode as nt,refillWarmPool as ke,resumeWarmClaim as tt,warmPoolEnabled as it}from"../../../core/runtime/warm-pool.js";import{assertLaunchKind as H,isLaunchKind as rt,resolveLaunchTarget as ot}from"../../../core/runtime/launch-target.js";import{fullName as at}from"../../../core/canvas/labels.js";import{reportsForNode as Se}from"./reports.js";import{requireUsableProfile as dt}from"./profiles.js";import{assertProfileActive as st,isProfilePaused as lt,loadExactProfileManifest as ct}from"../../../core/profiles/manifest.js";import{MachineOfflineError as ut}from"../../../core/runtime/runner/machine/ops.js";import{asNodePerson as ft}from"../../reconcilers/node-lifecycle/node-person.js";import{getCron as Y}from"../../../core/canvas/crons.js";import{cronWakeOrigin as pt}from"../../../core/runtime/bearings.js";import{boundDaemonControl as mt}from"../../control.js";import{notFound as N,usage as y}from"../../../core/errors.js";import{assertScope as wt,validateScopes as Ie}from"../../../core/scopes.js";import{scopeAllowed as E}from"../../../shared/env.js";import{toCloseResultDTO as ht,toNodeDetailDTO as Q,toNodeSummaryDTO as yt,toReviveResultDTO as _t}from"../map.js";import{ApiError as p}from"../../../api/index.js";import{InputError as w}from"../../../core/io.js";import{endExecution as gt,liveExecutionForNode as X,requestExecutionStop as bt}from"../../../core/canvas/executions.js";import{runnerForExecution as vt}from"../../../core/runtime/runner/index.js";import{wakeResident as kt}from"../../reconcilers/node-lifecycle/remote-wake.js";import{isNowEligibleFault as St}from"../../../core/canvas/status-glyph.js";import{remoteEnvironmentOf as Re}from"../../../core/runtime/blaxel-environment.js";import{machineEnvironmentOfProfile as It}from"../../../core/runtime/runner/machine/environment.js";import{isCloudRole as Rt}from"../../../core/canvas/person-state.js";import{actsAsPerson as j,canReadNode as A,mayOnNode as Et,readableNodeIds as Ot,resolvedScopes as At}from"../router.js";import{forwardVerb as Ct,queryWithoutMachine as $t,relayError as Tt,unknownError as Nt,withMachine as Pt}from"../../peer/forward.js";import{fileRoot as Dt}from"../../../core/spaces/file-root.js";import{activeGrant as Lt,payerOfGrant as Mt}from"../../../core/grants/mirror.js";import{launchUsesHostedEndpoint as jt}from"../../../core/model-auth/readiness.js";import{nodeTerminalGrant as Ft}from"../../../core/grants/terminal.js";import{appRungForGrant as Gt}from"../../../core/llm/app-rungs.js";import{APP_FAMILY as xt}from"../../../core/model-routes.js";import{listProfileEnvNames as Bt}from"../../../core/profiles/env-store.js";import{hasConfiguredProviderCredential as Wt,NO_PROVIDER_CREDENTIAL_MESSAGE as Ee}from"../../../core/runtime/provider-credential-gate.js";import{filterAsync as Ut,mapAsync as Oe}from"../../../core/async-array.js";import{addStepTiming as Vt,collectStepTimings as Kt,serverTimingHeader as Jt,sinceCollectionStart as zt,timedStep as Ht}from"../../../core/step-timings.js";async function h(e){const n=await b(e);if(n===null)throw N(`unknown node: ${e}`,{received:e});return n}d(h,"requireMeta");async function Z(e){return{subscribesTo:await he(e),subscribers:await nn(e),children:await Qe(e)}}d(Z,"edgesFor");async function v(e){const n=await h(e);return await Q(n,await Z(e))}d(v,"detailOf");async function Yt(e){let n=(await Se(e)).length;try{n+=bn(await J(e),await ye(e)).length}catch(t){if(!_n(t))throw t}return n}d(Yt,"countFiles");function Qt(e){if(typeof e!="object"||e===null)throw y("a node create requires a JSON body");const n=e;if(n.kind!==void 0&&(typeof n.kind!="string"||n.kind.trim()===""))throw y("kind must be a non-empty string when provided");if(n.description!==void 0&&(typeof n.description!="string"||n.description.trim()===""))throw y("description must be a non-empty string when provided");if(n.creator!==void 0&&(typeof n.creator!="string"||n.creator.trim()===""))throw y("creator must be a non-empty node id when provided");if(n.scopes!==void 0&&Ie(n.scopes),n.isolated!==void 0&&typeof n.isolated!="boolean")throw new p(400,"invalid_request","isolated must be a boolean",{param:"isolated"});if(n.start!==void 0&&typeof n.start!="boolean")throw new p(400,"invalid_request","start must be a boolean",{param:"start"});const t=n.root_lifecycle;if(t!==void 0&&t!=="resident"&&t!=="terminal")throw y("root_lifecycle must be 'resident' or 'terminal'");if(n.request_key!==void 0&&(typeof n.request_key!="string"||n.request_key.trim()===""||n.request_key.length>128))throw y("request_key must be a non-empty string of at most 128 characters when provided");return n}d(Qt,"parseCreateBody");function Xt(e){if(e===void 0)return;const n=et(e),t=n===null?null:new Date(Date.now()+n);if(n===null||!Number.isFinite(n)||n<=0||t===null||!Number.isFinite(t.getTime()))throw new p(422,"invalid_deadline","`deadline` must be a positive representable duration");return t.toISOString()}d(Xt,"parseDeadline");function Zt(e){if(e!==void 0){if(typeof e!="object"||e===null||Array.isArray(e))throw new p(400,"invalid_request","`outcome_delivery` must be an object");if(typeof e.action!="string"||!Zn.test(e.action))throw new p(400,"invalid_request","`outcome_delivery.action` must be a declared action name");if(e.payload!==void 0){let n;try{n=JSON.stringify(e.payload)}catch{throw new p(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable")}if(n===void 0)throw new p(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable");if(Buffer.byteLength(n,"utf8")>ve)throw new p(413,"payload_too_large",`serialized payload exceeds ${ve} bytes`)}return e}}d(Zt,"parseOutcomeDelivery");function qt(e,n){const t=qn(e.action,n);if(!("kind"in t))return{actionName:e.action,argv:t.argv,cwd:t.cwd,configOrigin:t.configOrigin,...e.payload===void 0?{}:{payload:e.payload}};throw t.kind==="unknown_action"?new p(422,"unknown_action",`no action named ${e.action} is declared from ${n}`):new p(422,"invalid_action",`${e.action} is declared in ${t.configOrigin} but unusable: ${t.reason}`,{reason:t.reason,configOrigin:t.configOrigin})}d(qt,"resolveOutcomeDelivery");function ei(e,n,t){const r={kind:e.kind,cwd:t,prompt:e.prompt??""};return e.mode!==void 0&&(r.mode=e.mode),e.name!==void 0&&(r.name=e.name),e.description!==void 0&&(r.description=e.description),n!==void 0&&(r.parent=n),e.creator!==void 0&&(r.creator=e.creator),e.scopes!==void 0&&(r.scopes=e.scopes),e.isolated!==void 0&&(r.isolated=e.isolated),e.root===!0&&(r.root=!0),e.start===!0&&(r.start=!0),e.root_lifecycle!==void 0&&(r.rootLifecycle=e.root_lifecycle),(e.worktree===!0||typeof e.worktree=="string")&&(r.worktree=!0),typeof e.worktree=="string"&&(r.worktreeBase=e.worktree),e.worktree!==void 0&&(r.worktreeCwd=L(e.pin_cwd??e.cwd??t)),e.fork_from!==void 0&&(r.forkFrom=e.fork_from),e.model!==void 0&&(r.model=e.model),e.profile!==void 0&&(r.profile=e.profile),e.situational_context!==void 0&&(r.situationalContext=e.situational_context),e.node_id!==void 0&&(r.nodeId=e.node_id),r}d(ei,"buildRecipe");function ni(e,n,t){return!it()||e.prefer_warm!==!0||e.root!==!0||e.parent!=null||e.root_lifecycle==="terminal"||(e.prompt??"")!==""||e.model!==void 0||e.fork_from!==void 0||e.worktree!==void 0||e.node_id!==void 0||e.scopes!==void 0||e.isolated!==void 0?null:{kind:e.kind,mode:e.mode??"base",cwd:n,profileId:t,model:e.model??null,situationalContext:e.situational_context??null,name:e.name??null,creator:e.creator??null}}d(ni,"warmRequestFor");import{resolveCreateKind as Io}from"../../../core/runtime/launch-target.js";function Ae(e){const n=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return Kn(e.model,n,e.modelExact===!0)}d(Ae,"requestFromLaunch");function ti(e,n){if(n===null)return e;if(e.scopes===void 0)return{...e,scopes:[...n]};const t=e.scopes.filter(r=>!E(n,r));if(t.length===0)return e;throw new p(403,"scope_denied",`scopes exceed the bearer token's ceiling: ${t.join(", ")}`,{scopes:t,ceiling:n})}d(ti,"withinCeiling");async function Ce(e,n,t){const r=(await Wn(n.kind,n.mode,{lifecycle:n.lifecycle,hasManager:e.parent!==null,model:n.model,modelOverride:!0,cwd:e.cwd,profileId:e.profile_id??null,app:e.grantee??"app:terminal"})).launch;await V(Ae(r),{cwd:e.cwd,profileId:e.profile_id??null},t)}d(Ce,"assertNodeModelChangeRegistered");async function ii(e){if(!Rt()||e.app!=="app:terminal")return!1;const n=e.class==="broker"?(await b(e.node))?.profile_id??null:e.cron===null?null:(await Y(e.cron))?.profile??null;return n!==null&&await It(n)!==null}d(ii,"callerRunsOnMachine");async function $e(e,n){const t=e.principal;if(t.class!=="broker"&&t.class!=="cron"||await ii(t))return;const r=Dt({app:t.app,resolved:await At(t),launched:t.scopes},n,"read");if("root"in r)return;const i="missing"in r?r.missing:null;throw new p(403,"scope_missing",i?`the child's directory ${n} needs missing scope ${i}`:`no permission of this run names the child's directory ${n}`,void 0,void 0,i?{scope:i}:void 0)}d($e,"assertCallerReaches");const q=new Map;async function ri(e,n={},t={}){const r=performance.now(),{value:i,steps:a}=await Kt(()=>oi(e,n,t));return a.push(["total",performance.now()-r]),{...i,headers:{...i.headers??{},"server-timing":Jt(a)}}}d(ri,"handleCreate");async function oi(e,n,t){const r=ti(Qt(e.body),e.ceiling);if(e.principal.class==="broker"){const s=e.principal;if(r.prefer_warm===!0&&s.app!=="app:terminal"&&(r.prefer_warm=!1),r.parent!=null){const o=await h(r.parent);if(o.grantee!==s.app)throw new p(403,"other_app_run","cannot create a child under another app's node");if(!await A(s,o.grantee??"app:terminal",r.parent))throw N(`unknown node: ${r.parent}`,{received:r.parent})}if(r.creator!==void 0&&r.creator!==s.node)throw new p(403,"other_app_run","cannot create for another node");if(r.fork_from!==void 0){let o=null;try{o=await le(await se(r.fork_from))}catch{}if(o?.grantee!==s.app||!await A(s,o.grantee,o.node_id))throw new p(403,"other_app_run","cannot fork another app's conversation")}r.creator=s.node}if(e.principal.class==="person"&&e.principal.sub!==void 0){const s=r.fork_from===void 0?null:await le(await se(r.fork_from)).catch(()=>null);for(const o of[r.parent,r.creator,s?.node_id])if(o!=null&&await b(o)!==null&&!await Et(e.principal,"edit",o))throw N(`unknown node: ${o}`,{received:o})}if(e.principal.class==="cron"){const s=e.principal;for(const l of["parent","creator","fork_from","node_id"])if(r[l]!=null)throw new p(403,"permission_error",`a cron cannot set ${l} on a node it starts`);r.prefer_warm=!1,r.node_id=await ce(),s.isolated&&(r.isolated=!0,r.cwd=await J(r.node_id,s.app));const o=await mn({grantee:s.app,sub:s.sub,grant_id:s.grant,scopes:s.scopes,from_exec:s.from_exec},{profile:r.profile,cwd:r.cwd,pin_cwd:r.pin_cwd,kind:r.kind,model:r.model,mode:r.mode});if(!o.allowed)throw wn(o);if(r.scopes!==void 0){const l=r.scopes.find(m=>!E(o.effectiveScopes,m)||!E(s.scopes,m));if(l!==void 0)throw new p(403,"scope_missing",`scope ${l} is not held by this cron`,void 0,void 0,{scope:l})}else o.scopes!==null&&(r.scopes=o.scopes)}r.creator!==void 0&&wt(await h(r.creator),"crtr:act");const i=r.request_key?.trim();if(i===void 0||r.node_id!==void 0&&pn(r.node_id)&&await b(r.node_id)!==null&&(await me(i))?.nodeId!==r.node_id)return F(e,r,n,t);const a=q.get(i);if(a!==void 0)return a;const c=ai(e,r,i,n,t);q.set(i,c);try{return await c}finally{q.delete(i)}}d(oi,"createWithinTimings");const Te=`${process.pid}:${Fe()}`,ee="create_request_in_progress";async function Ne(e,n,t){const r=Date.now()+9e4;let i=Date.now()+1e4;for(;t!==null;){const a=await b(t);if(a!==null){if(!j(e.principal)&&!await A(e.principal,a.grantee??"app:terminal",t))throw new p(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:await v(t)}}if(await He(n)&&(i=Math.min(r,Date.now()+1e3)),Date.now()>=i||(await me(n))?.nodeId!==t)break;await new Promise(c=>setTimeout(c,100))}throw new p(409,ee,"another create with this request_key is in progress; retry it")}d(Ne,"awaitForeignCreate");async function ai(e,n,t,r,i){const a=await we(t),c=Te;if(a.nodeId!==null&&a.state==="reserved"&&await b(a.nodeId)===null&&!await fe(t,a.nodeId,c))try{return await Ne(e,t,a.nodeId)}catch(o){if(!(o instanceof p)||o.code!==ee||!await fe(t,a.nodeId,c))throw o}const s=setInterval(()=>{Ye(t,c).catch(()=>{})},ze);try{return await di(e,n,t,r,i,a)}finally{clearInterval(s)}}d(ai,"handleKeyedCreateRequest");async function di(e,n,t,r,i,a){if(a.nodeId!==null&&await b(a.nodeId)!==null){if(a.state!=="warm_claimed"){const c=await b(a.nodeId);if(!j(e.principal)&&!await A(e.principal,c.grantee??"app:terminal",a.nodeId))throw new p(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:await v(a.nodeId)}}return F(e,n,r,i,a)}try{return await F(e,n,r,i,a)}catch(c){if(c instanceof p&&c.code===ee)throw c;const s=await we(t);throw(s.nodeId===null||await b(s.nodeId)===null)&&await ue(t,s.nodeId),c}}d(di,"keyedCreateOwned");async function F(e,n,t,r,i=void 0){const a=r.deadlineAt??Xt(n.deadline),c=Zt(n.outcome_delivery),s=e.principal.class==="cron"?await hn({grantee:e.principal.app,sub:e.principal.sub,grant_id:e.principal.grant,scopes:e.principal.scopes,cron_id:e.principal.cron,origin_run_id:e.principal.origin_run,isolated:e.principal.isolated,creator:e.principal.kind==="exec"?null:(await Y(e.principal.cron))?.created_by??null},n.node_id):null;s!==null&&(n.root=s.root===!0);const o=s?.parent??n.parent??void 0;if(o==null&&n.root!==!0)throw y("a node create requires a parent (or root: true for an independent root)");let l=null;if(n.output_schema!==void 0){try{l=JSON.parse(n.output_schema)}catch{throw y("output_schema must be a JSON schema string")}if(l===null||typeof l!="object"||Array.isArray(l))throw y("output_schema must be a JSON schema object");await Xn(l)}const m=await ot(n,{validateKind:Me,...e.principal.class==="broker"||e.principal.class==="cron"?{app:e.principal.app}:{}}),{profileId:f,kind:u,cwd:_,launch:I}=m;if(n.pin_cwd!==void 0&&n.pin_cwd!==""&&n.worktree===void 0&&n.isolated!==!0&&!$(_)&&await Re(f)===null)throw new w({error:"cwd_missing",message:`cwd is not an existing directory: ${_}`,received:_,field:"cwd",next:"Pass an existing directory with --cwd."});await $e(e,_),n.worktree!==void 0&&await $e(e,L(n.pin_cwd??n.cwd??_));const k={...n,kind:u},P=c===void 0?void 0:qt(c,_),te=("grant"in e.principal?e.principal.grant:null)??(o==null?null:(await b(o))?.grant_id??null);if(await V(Ae(await Ve(I,te,n.model)),{cwd:_,profileId:f},t.modelRegistry),await Mt(te)!=="app"&&!await Wt(f===null?[]:await Bt(f))&&!await jt(m))throw new p(412,"no_provider_credential",Ee,{error:"no_provider_credential",message:Ee,next:"The person running this runtime logs a provider in with `crtr sys setup`, or stores a provider key on the profile."});let x=null;{const ie=i===void 0||i.nodeId===null||i.state==="warm_claimed"?ni(k,_,f):null,O=ie!==null&&!(n.start===!0&&await Re(f)!==null)?ie:null,B=l===null&&r.beforeBrokerLaunch===void 0?void 0:async g=>{l!==null&&await Qn(g,"terminal",l),r.beforeBrokerLaunch?.(g)};if(i?.state==="warm_claimed"&&i.nodeId!==null){const g=O===null?null:await tt(O,i.nodeId,B);if(g===null)throw await ue(i.requestKey,i.nodeId),new p(503,"create_resume_failed",`could not resume warm claim ${i.nodeId}; retry the create`);return await pe(i.requestKey,g),{status:201,body:await v(g)}}if(O!==null){const g=await nt(O,{...a===void 0?{}:{deadlineAt:a},...P===void 0?{}:{outcomeDelivery:P},...i===void 0?{}:{requestKey:i.requestKey}},B);if(g!==null)return i!==void 0&&await pe(i.requestKey,g),ke(O),{status:201,body:await v(g)};x=O}const D=i?.nodeId??n.node_id??(i===void 0?void 0:await ce());if(i!==void 0&&i.nodeId===null){const g=await Ze(i.requestKey,D,Te);if(g!==D)return await Ne(e,i.requestKey,g)}const R=ei(D===void 0?k:{...k,node_id:D},o,_);s!==null&&(s.rootLifecycle!==void 0&&(R.rootLifecycle=s.rootLifecycle),s.scopes!==void 0&&k.scopes===void 0&&(R.scopes=s.scopes),s.run!==void 0&&(R.run=s.run),s.withinCreate!==void 0&&(R.withinCreate=s.withinCreate)),a!==void 0&&(R.deadlineAt=a),P!==void 0&&(R.outcomeDelivery=P),R.readiness=n.root===!0?"await":"launch",Vt("handler_checks",zt());const re=await Je(R,B,()=>{x!==null&&ke(x)});return i!==void 0&&await Xe(i.requestKey,re.node.node_id),{status:201,body:await Ht("response_detail",()=>v(re.node.node_id))}}}d(F,"handleCreateRequest");function S(e,n){const t=e.query.getAll(n);if(t.length>1)throw y(`${n} must appear at most once`);return t[0]}d(S,"singleQueryValue");function ne(e,n){if(e!==void 0){if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1;throw y(`${n} must be true or false`)}}d(ne,"optionalBoolean");function G(e,n,t){if(e!==void 0){if(t.includes(e))return e;throw y(`${n} must be one of: ${t.join(", ")}`)}}d(G,"oneOf");function si(e){const n=new Set(["status","lifecycle","kind","mode","profile_id","profile_prefix","parent","top_level","under","under_inclusive","hanging","include"]);for(const[I]of e.query)if(!n.has(I))throw y(`unknown nodes query parameter: ${I}`);const t=G(S(e,"status"),"status",["active","idle","done","dead","canceled"]),r=G(S(e,"lifecycle"),"lifecycle",["terminal","resident"]),i=S(e,"kind"),a=G(S(e,"mode"),"mode",["base","orchestrator"]),c=S(e,"profile_id"),s=S(e,"profile_prefix"),o=S(e,"parent"),l=ne(S(e,"top_level"),"top_level"),m=S(e,"under"),f=ne(S(e,"under_inclusive"),"under_inclusive"),u=ne(S(e,"hanging"),"hanging"),_=G(S(e,"include"),"include",["activity"]);if(o!==void 0&&l===!0)throw y("parent and top_level=true cannot be combined");return{...t!==void 0?{status:t}:{},...r!==void 0?{lifecycle:r}:{},...i!==void 0?{kind:i}:{},...a!==void 0?{mode:a}:{},...c!==void 0?{profile_id:c}:{},...s!==void 0?{profile_prefix:s}:{},...o!==void 0?{parent:o}:{},...l!==void 0?{top_level:l}:{},...m!==void 0?{under:m}:{},...f!==void 0?{under_inclusive:f}:{},...u!==void 0?{hanging:u}:{},..._!==void 0?{include:_}:{}}}d(si,"parseListQuery");async function li(e){const n=si(e);let t=await qe({...n.status!==void 0?{status:n.status}:{},...n.lifecycle!==void 0?{lifecycle:n.lifecycle}:{},...n.kind!==void 0?{kind:n.kind}:{},...n.mode!==void 0?{mode:n.mode}:{},...n.profile_id!==void 0?{profileId:n.profile_id}:{},...n.profile_prefix!==void 0?{profilePrefix:n.profile_prefix}:{},...n.parent!==void 0?{parent:n.parent}:{},...n.top_level===!0?{topLevel:!0}:{},...n.under!==void 0?{under:n.under}:{},...n.under_inclusive===!0?{underInclusive:!0}:{},...n.hanging===!0?{hanging:!0}:{}});const r=await Ot(e.principal);r!==null&&(t=t.filter(o=>r.has(o.node_id)));const i=n.include==="activity"?await fn(t.map(o=>o.node_id)):null,a=t.length>0?xe():new Set,c=new Map((await rn()).map(o=>[o.nodeId,o.controllerId]));return{status:200,body:await Oe(t,async o=>{const l=await yt(o,o.profile_id!==null&&a.has(o.profile_id),c.get(o.node_id)??null);if(i!==null){const m=await Se(o.node_id);l.activity={latest_report:m[0]??null,final_report:o.final_report===null?null:m.find(f=>f.name===o.final_report)??null,pending_human_count:i[o.node_id]??0}}return l})}}d(li,"handleList");async function ci(e){const n=e.params.id,t=await Ct(e,n,{method:"GET",path:`/v1/nodes/${encodeURIComponent(n)}`,query:$t(e)});if(t.kind==="unknown")throw Nt(n,t.unreachable);if(t.kind==="remote"){if(t.status>=400)throw Tt(t.status,t.body);return{status:t.status,body:Pt(t.body,t.machine)}}return await h(n),{status:200,body:await v(n)}}d(ci,"handleDetail");async function ui(e){const n=e.params.id;await h(n);const t=await Sn(n),{start:r}=En(t.snapshot.messages,s=>JSON.stringify(_e(s,n)).length),i=t.snapshot.messages.slice(r).map(s=>_e(s,n)),a=Rn(i);return{status:200,body:{node_id:n,snapshot:{messages:i,...t.snapshot.messageIds===void 0?{}:{messageIds:t.snapshot.messageIds.slice(r)},messageVisibility:t.snapshot.messageVisibility.slice(r),turnVisibility:t.snapshot.turnVisibility,stats:t.snapshot.stats,state:t.snapshot.state,display:t.snapshot.display,...t.snapshot.queued===void 0?{}:{queued:t.snapshot.queued},...t.snapshot.toolGroupSummaries===void 0?{}:{toolGroupSummaries:Object.fromEntries(Object.entries(t.snapshot.toolGroupSummaries).filter(([s])=>a.has(s)))},...t.snapshot.turnReplies===void 0?{}:{turnReplies:t.snapshot.turnReplies},...t.snapshot.workingActivity===void 0?{}:{workingActivity:t.snapshot.workingActivity}},commands:t.commands.map(s=>({name:s.name,description:s.description,source:s.source})),captured_at:U()}}}d(ui,"handleSnapshot");async function fi(e){const n=e.params.id,t=await On(n);if(t===null)throw N(`unknown node: ${n}`,{received:n});return{status:200,body:t}}d(fi,"handleSubject");function pi(e){for(const[a]of e.query)if(a!=="cursor"&&a!=="limit")throw y(`unknown messages query parameter: ${a}`);const n=e.query.getAll("cursor"),t=e.query.getAll("limit");if(n.length>1)throw y("cursor must appear at most once");if(t.length>1)throw y("limit must appear at most once");if(t.length===0)return n.length===0?{}:{cursor:n[0]};const r=t[0],i=Number(r);if(!Number.isSafeInteger(i)||r==="")throw y("limit must be an integer from 1 through 500");return n.length===0?{limit:i}:{cursor:n[0],limit:i}}d(pi,"parseMessagesQuery");async function mi(e){const n=e.params.id,t=await vn(n,pi(e));return{status:200,body:{node_id:n,messages:t.messages,...t.messageIds===void 0?{}:{message_ids:t.messageIds},message_visibility:t.messageVisibility,next_cursor:t.nextCursor,captured_at:U()}}}d(mi,"handleMessages");async function wi(e){const n=e.params.id;await h(n);const t=await kn(n);return{status:200,body:{node_id:n,session_file:t.sessionFile,session_jsonl:t.sessionJsonl,system_prompt:t.systemPrompt,captured_at:U()}}}d(wi,"handleSession");async function hi(e){const n=e.params.id;return await h(n),{status:200,body:{node_id:n,markdown:await In(n)}}}d(hi,"handleTranscript");async function yi(e){const n=e.params.id;await h(n);const t=d(async(i,a)=>({node_id:i,label:(await b(i))?.name??i,dir:await ye(i),self:a,files:await Yt(i)}),"root"),r=await Ut([await t(n,!0),...await Oe(await he(n),async i=>await t(i.node_id,!1))],async i=>await _i(i.node_id,i.dir)||i.files>0);return{status:200,body:{node_id:n,roots:r}}}d(yi,"handleContext");async function _i(e,n){try{return yn(await J(e),n)}catch(t){if(gn(t))return!1;throw t}}d(_i,"hasDir");async function gi(e){const n=await h(e.params.id),t=e.principal.class==="broker"?e.principal.scopes:e.ceiling,r=t===null?void 0:n.scopes==null?[...t]:[...new Set([...n.scopes.filter(a=>E(t,a)),...t.filter(a=>E(n.scopes,a))])],i=await Ke(n.node_id,r,e.principal.class==="broker"?e.principal.node:void 0);return{status:201,body:await v(i.node.node_id)}}d(gi,"handleFork");const bi=1e4;async function vi(e){const n=e.params.id,t=await h(n),r=await X(n);if(r===null||r.runner!=="machine")throw new w({error:"not_hanging",message:`${n} has no live broker on a Mac \u2014 nothing to kick here.`,next:`Use \`crtr node lifecycle revive ${n} --now\` from the CLI, which kicks a local broker directly.`});if(!St(t.fault??null))throw new w({error:"not_hanging",message:`${n} is live but has no pi\u2192provider fault eligible for --now.`,next:"Use --now only on a node the canvas shows as hanging (\u26A0) with a `pi\u2192provider` fault."});if(t.streaming===!0)throw new w({error:"busy",message:`${n} is mid-turn right now (busy) \u2014 refusing to stop a working engine.`,next:"Re-check the canvas \u2014 if it is no longer marked hanging (\u26A0), nothing to do."});await bt(n,{afterTurn:!1,reason:"revive_now"});const i=await vt("machine").stop(r,{reason:"revive_now"});if(!i.confirmed)throw i.error??new Error(`stop of ${n} on its Mac was not confirmed`);return await gt(r.executionId,{reason:"revive_now"}),await de(n,{resume:!0,capacity:"refuse"}),{status:200,body:{kicked:!0}}}d(vi,"handleKick");async function ki(e){const n=e.params.id,t=await h(n),r=e.body,i=r?.resume??!0,a=r?.reopen??!1;await Pn(n,a,e.principal.class==="broker"?e.principal.node:null);const c=!i&&r?.cron_id!==void 0?await Y(r.cron_id):null,s=await X(n);if(i&&s!==null&&s.runner!=="process"&&s.state==="running"&&!lt(t.profile_id))try{await ft({node_id:n,sub:t.sub??null,profile_id:t.profile_id??null},()=>kt(s))}catch(u){if(!(u instanceof ut))throw u}const o=await de(n,{resume:i,capacity:"refuse",...c!==null?{wakeReason:await pt(c,"schedule_revive")}:{}});o.outcome!=="already-live"&&await en(n,{failures:0,notBefore:null});const l=(await b(n))?.status??"active",m=(o.launch??M().get(n)?.handle)?.exited,f=o.outcome!=="frozen"&&await be(n,m,bi);return{status:200,body:_t(n,o,l,f)}}d(ki,"handleRevive");async function Si(e){const n=e.params.id;return{status:200,body:{newNodeId:(await Nn(n))?.newNodeId??null}}}d(Si,"handleRelaunchRoot");async function Ii(e){const n=e.params.id;await h(n);const t=e.body;if(t?.caller_pid!==void 0&&(!Number.isInteger(t.caller_pid)||t.caller_pid<=0))throw y("caller_pid must be a positive integer when provided");const r=mt(),i=new Promise(c=>{e.res.once("close",()=>c())}),a=await Ue(n,{teardownAfter:i,rootEvent:t?.finish===!0?"finish":"cancel",callerPid:t?.caller_pid,...e.principal.class==="broker"?{closer:e.principal.node}:{},...r===null?{}:{registerDetached:r.registerDetached}});return{status:200,body:ht(a)}}d(Ii,"handleClose");async function Ri(e){if(!j(e.principal))throw new p(403,"permission_error","only the person marks a conversation read");const n=e.params.id;return await h(n),await on(n),{status:204}}d(Ri,"handleMarkRead");async function Ei(e){const n=e.params.id;await h(n);const t=await Tn(n);return{status:200,body:{recycled:t.recycled,finalized:t.finalized,new_root:t.newRoot,delivered:t.delivered}}}d(Ei,"handleRecycle");async function Oi(e){const n=e.params.id;return await h(n),await z(n,{lifecycle:"terminal"}),await C(e,n,["lifecycle"]),{status:200,body:await v(n)}}d(Oi,"handleDemote");async function Ai(e,n={}){const t=e.params.id,r=await h(t),i=e.body??{};i.kind!==void 0&&await H(i.kind,r.cwd,r.profile_id??null),i.model!==void 0&&await Ce(r,{kind:i.kind??r.kind,mode:"orchestrator",lifecycle:i.resident===!0?"resident":r.lifecycle,model:i.model},n.modelRegistry);const a=await Cn(t,{...i.kind!==void 0?{kind:i.kind}:{},...i.resident===!0?{resident:!0}:{},...i.model!==void 0?{model:i.model}:{}});await C(e,t,["mode",...i.kind!==void 0?["kind"]:[],...i.resident===!0?["lifecycle"]:[],...i.model!==void 0?["model"]:[]]);const c=await Q(a.meta,await Z(t));return c.roadmap_written=a.roadmapWritten,c.roadmap_ref=a.roadmapRef,c.goal_path=a.goalPath,{status:200,body:c}}d(Ai,"handlePromote");async function Ci(e){const n=e.params.id;return await h(n),{status:200,body:{request:await Ln(n)}}}d(Ci,"handleBrokerStructuredRequest");async function $i(e){const n=e.params.id,t=e.body??{};if(await Dn(n,t.expected_execution_id),typeof t.text!="string")throw new p(400,"invalid_request","text must be a string");return await h(n),{status:200,body:{captured:await Fn(n,t.text)}}}d($i,"handleBrokerGoal");async function Ti(e,n={}){const t=e.params.id,r=await h(t),i=e.body??{};i.kind!==void 0&&await H(i.kind,r.cwd,r.profile_id??null),i.model!==void 0&&await Ce(r,{kind:i.kind??r.kind,mode:i.promote===!0?"orchestrator":r.mode,lifecycle:r.lifecycle,model:i.model},n.modelRegistry);const a=i.note??"Refresh: continue against your roadmap or goal.";await Mn(t,a);const c=await $n(t,{...i.promote===!0?{promote:!0}:{},...i.kind!==void 0?{kind:i.kind}:{},...i.model!==void 0?{model:i.model}:{}});return{status:200,body:await Q(c.meta,await Z(t))}}d(Ti,"handleYield");async function Ni(e){const n=e.params.id;await h(n);const t=e.body;if(t===void 0||typeof t.controller!="string"||t.controller.trim()==="")throw y("a wait requires a controller node id");const r=await b(t.controller);if(r===null)throw N(`unknown controller: ${t.controller}`,{received:t.controller});if(r.status!=="active"&&r.status!=="idle")throw new p(422,"unprocessable",`controller ${t.controller} is ${r.status}`);return await tn(n,t.controller),{status:200,body:await v(n)}}d(Ni,"handleWait");async function Pi(e){const n=e.principal,t=await An(n.class==="broker"?async i=>i.grantee===n.app&&await A(n,i.grantee,i.node_id):n.class==="person"&&!j(n)?async i=>await A(n,i.grantee??"app:terminal",i.node_id):void 0);return{status:200,body:{revived:[...t.revived],failed:[...t.failed],frozen:[...t.frozen]}}}d(Pi,"handleReviveAll");const Di=new Set(["interrupt","steer","after-turn","next-turn"]);function Li(e){if(e===null)return null;const n=d(r=>{throw new w({error:"invalid_listen",message:r,received:e,field:"listen",next:'Send an object mapping levels "1".."10" to interrupt|steer|after-turn|next-turn (e.g. {"3":"next-turn"}), or null to reset to the global default.'})},"bad");if(typeof e!="object"||Array.isArray(e))return n("listen must be an object or null");const t=Object.entries(e);if(t.length===0)return n("listen must name at least one level");for(const[r,i]of t)/^(?:[1-9]|10)$/.test(r)||n(`listen level must be 1..10: ${r}`),(typeof i!="string"||!Di.has(i))&&n(`listen delivery must be interrupt|steer|after-turn|next-turn: ${String(i)}`);return JSON.stringify(Object.fromEntries(t))}d(Li,"listenJson");async function C(e,n,t,r){t.length===0&&r===void 0||await K(async i=>{if(r?.(i),t.length===0)return;const a=await an(i,n),c=await ln(i,e),s=c.class==="person"?c.person:c.class==="app"?c.app:c.node;await dn(i,s,a),await sn(i,{event:"configured",object:a,actor:s,attrs:{changed:t.join(",")}})})}d(C,"recordConfigured");function Pe(e){const n=M().get(e);if(n===void 0)return!1;try{return process.kill(n.pid,"SIGTERM"),!0}catch{return!1}}d(Pe,"restartLiveBroker");function De(e,n){try{return oe(e)===oe(n)}catch{return!1}}d(De,"sameDirectory");async function Mi(e,n={}){const t=e.params.id,r=e.body;let i;if(r===void 0)i={};else if(typeof r=="object"&&r!==null&&!Array.isArray(r))i=r;else throw new w({error:"cwd_invalid",message:"cwd repair requires a non-null object with a non-empty cwd string",received:r,field:"cwd",next:"Send a config patch with a non-empty absolute cwd string."});if(i.profile!==void 0){if(typeof i.profile!="string"||i.profile==="")throw new w({error:"profile_invalid",message:"profile must be a non-empty profile id or name",received:i.profile,field:"profile",next:"Send a profile id or exact name."});if(Object.keys(i).some(f=>f!=="profile"&&f!=="restart"&&i[f]!==void 0))throw new w({error:"profile_not_exclusive",message:"profile can only be combined with restart",field:"profile",next:"Send profile (and optionally restart) alone."});const o=await h(t),l=await dt(e,i.profile);st(l.profileId);const m=ct(l.profileId).manifest.grantee??"app:terminal";if(m!==(o.grantee??"app:terminal"))throw new w({error:"profile_grantee_mismatch",message:`profile ${l.profileId} belongs to ${m}, node ${t} to ${o.grantee}`,received:i.profile,field:"profile",next:"Pick a profile owned by the same app as the node."});return(o.profile_id??null)!==l.profileId&&(rt(o.kind)?(await H(o.kind,o.cwd,l.profileId),await z(t,{profileId:l.profileId})):await T(t,{profile_id:l.profileId}),await C(e,t,["profile"])),i.restart===!0&&Pe(t),{status:200,body:await v(t)}}if(Object.prototype.hasOwnProperty.call(i,"cwd")){const o=i.cwd;if(typeof o!="string"||o==="")throw new w({error:"cwd_invalid",message:"cwd must be a non-empty string",received:o,field:"cwd",next:"Send a non-empty absolute cwd string."});if(Object.keys(i).some(u=>u!=="cwd"&&u!=="keep_session"&&u!=="restart"&&i[u]!==void 0))throw new w({error:"cwd_not_exclusive",message:"cwd repair cannot be combined with another config field",received:i,field:"cwd",next:"Send cwd as the only config field."});const l=await h(t),m=$(l.cwd);if(i.keep_session===!0||m&&W(o)&&$(o)&&De(l.cwd,o)){if(!W(o))throw new w({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${o}`,received:o,field:"cwd",next:"Send an absolute path."});const u=L(o);let _=!1;try{_=ae(u).isDirectory()}catch{}if(!_)throw new w({error:"cwd_missing",message:`cwd is not an existing directory: ${u}`,received:o,field:"cwd",next:"Send an existing absolute directory."});if(m&&!De(l.cwd,u))throw new w({error:"cwd_not_same_directory",message:`${u} is not the same directory as the recorded ${l.cwd}; --keep-session only relocates an alias`,received:o,field:"cwd",next:"Drop --keep-session to repair a gone cwd, or pass the real path of the recorded directory."});if(l.managed_worktree?.state==="open")throw new w({error:"cwd_node_managed_worktree_open",message:`${t} owns an open managed worktree and cannot relocate its cwd`,received:o,field:"cwd",next:"Reconcile the managed worktree first."});const I=l.cwd;return I!==u&&(await K(async k=>{await T(t,{cwd:u}),await k.prepare("UPDATE crons SET cwd = ? WHERE anchor_node = ? AND cwd = ?").run(u,t,I),await cn(t,I,u)}),await C(e,t,["cwd"])),i.restart===!0&&Pe(t),{status:200,body:await v(t)}}if(await M().has(t)){const u=`${t} cannot repair its cwd while its broker is live`;throw new p(409,"cwd_node_live",u,{error:"cwd_node_live",message:u,received:o,field:"cwd",next:"Let the node become dormant, then retry the cwd repair."})}if(l.fork_from!=null)throw new w({error:"cwd_node_forked",message:`${t} is a fork and cannot repair its cwd; recorded cwd: ${l.cwd}`,received:o,field:"cwd",next:`Restore ${l.cwd}, then revive the fork normally.`});if(l.managed_worktree?.state==="open")throw new w({error:"cwd_node_managed_worktree_open",message:`${t} owns an open managed worktree and cannot repair its cwd`,received:o,field:"cwd",next:"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon flow."});if($(l.cwd))throw new w({error:"cwd_still_present",message:`${t} recorded cwd still exists: ${l.cwd}; cwd repair is not a relocation command`,received:o,field:"cwd",next:"This command only repairs a node whose recorded cwd is gone."});if(!W(o))throw new w({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${o}`,received:o,field:"cwd",next:"Send an absolute path."});const f=L(o);if(!$(f))throw new w({error:"cwd_missing",message:`cwd does not exist: ${f}`,received:o,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."});try{if(!ae(f).isDirectory())throw new w({error:"cwd_not_a_directory",message:`cwd is not a directory: ${f}`,received:o,field:"cwd",next:"Send an existing absolute directory."})}catch(u){throw u instanceof w?u:new w({error:"cwd_missing",message:`cwd does not exist: ${f}`,received:o,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."})}return await K(async()=>{await T(t,{cwd:f}),await un(t)}),await C(e,t,["cwd"]),{status:200,body:await v(t)}}let a=await h(t);const c=i.listen===void 0?void 0:Li(i.listen);if(i.scopes!==void 0){const o=Ie(i.scopes),l=a.grantee==="app:terminal"?await Ft(a):a.grant_id?await Lt(a.grant_id):null;if(!o.every(m=>E(a.scopes,m)&&l!==null&&E(l.resolved,m)))throw new w({error:"unknown_scope",message:"scopes may only narrow the node's current effective set",received:o,field:"scopes",next:"Send only scopes the node currently holds."});if(o.includes("crtr:act")&&!E(o,"crtr:llm"))throw new p(400,"invalid_scope","crtr:act requires crtr:llm");a=await T(t,{scopes:o})}if(i.situational_context!==void 0&&await Be(t,We(i.situational_context)),i.model!==void 0){const o=(await ge(a.cwd,a.profile_id??null,a.grantee??"app:terminal")).modelLadders,l=Un(i.model,o),m=await Gt(a.grant_id,i.model,l===void 0),f=m?{family:xt,strength:m.strength}:l,u=m?m.model:Vn(i.model,o);await V({kind:"concrete",spec:u},{cwd:a.cwd,profileId:a.profile_id??null},n.modelRegistry);const _=M();let I=!1;if(await _.isClaimed(t)&&((await X(t))?.runner==="machine"||await be(t,_.get(t)?.handle.exited))&&(I=await zn(t,u,f,await Hn(t)).then(()=>!0,k=>{if(k instanceof Yn)return!1;throw k})),!I){if(await _.isClaimed(t)){const k=`${t}'s broker did not accept the model switch; the model was not changed`;throw new p(409,"broker_not_ready",k,{error:"broker_not_ready",message:k,received:i.model,field:"model",next:"Check the node with `crtr node inspect show`, then retry the model change."})}if(!u.includes("/"))throw y(`model must resolve to a provider/id spec: ${i.model}`);await Jn(t,u,f)}a=await h(t)}if(i.kind!==void 0||i.mode!==void 0||i.lifecycle!==void 0){i.kind!==void 0&&await Me(i.kind,a.grantee??"app:terminal");const o=i.kind??a.kind,l=i.mode??a.mode,m=i.lifecycle??a.lifecycle;let f;l==="orchestrator"&&!await xn(t)&&(f=d(async()=>{const u=await jn(t);await Gn(t,u!==null&&u.trim()!==""?{goal:u.trim()}:{})},"beforePersist")),a=await z(t,{...i.kind!==void 0?{kind:o}:{},...i.mode!==void 0?{mode:l}:{},...i.lifecycle!==void 0?{lifecycle:m}:{}},f)}i.name!==void 0&&(a=await T(t,{name:i.name}),a.window&&Bn(a.window,at(a)));const s=["scopes","situational_context","model","kind","mode","lifecycle","name","listen"].filter(o=>i[o]!==void 0);return await C(e,t,s,c===void 0?void 0:async o=>{await o.prepare("UPDATE objects SET listen_json = ? WHERE id = ? AND type = 'node'").run(c,t)}),{status:200,body:await v(t)}}d(Mi,"handleConfig");async function Le(e="app:terminal"){return(await ge(process.cwd(),Ge()||null,e)).kinds}d(Le,"daemonKinds");async function Me(e,n="app:terminal"){const t=Object.keys(await Le(n));if(!t.includes(e))throw y(`unknown kind: ${e}`,{received:e,next:`Valid kinds: ${t.sort().join(", ")}.`})}d(Me,"assertKindServer");async function ji(){const e=await Le();return{status:200,body:{kinds:Object.keys(e).sort().map(t=>({kind:t,when_to_use:e[t]?.whenToUse??null,available_to:e[t]?.availableTo??null}))}}}d(ji,"handleListKinds");const vo=[{method:"POST",pattern:"/v1/nodes",scope:"crtr:act",handler:ri},{method:"GET",pattern:"/v1/nodes",handler:li},{method:"GET",pattern:"/v1/kinds",handler:d(()=>ji(),"handler")},{method:"POST",pattern:"/v1/nodes/revive-all",scope:"crtr:act",handler:Pi},{method:"GET",pattern:"/v1/nodes/:id",handler:ci},{method:"GET",pattern:"/v1/nodes/:id/snapshot",handler:ui},{method:"GET",pattern:"/v1/nodes/:id/subject",handler:fi},{method:"GET",pattern:"/v1/nodes/:id/messages",handler:mi},{method:"GET",pattern:"/v1/nodes/:id/session",handler:wi},{method:"GET",pattern:"/v1/nodes/:id/transcript",handler:hi},{method:"GET",pattern:"/v1/nodes/:id/context",handler:yi},{method:"POST",pattern:"/v1/nodes/:id/fork",scope:"crtr:act",handler:gi},{method:"POST",pattern:"/v1/nodes/:id/revive",scope:"crtr:act",handler:ki},{method:"POST",pattern:"/v1/nodes/:id/kick",scope:"crtr:act",handler:vi},{method:"POST",pattern:"/v1/nodes/:id/relaunch-root",scope:"crtr:act",handler:Si},{method:"POST",pattern:"/v1/nodes/:id/close",handler:Ii},{method:"POST",pattern:"/v1/nodes/:id/read",handler:Ri},{method:"POST",pattern:"/v1/nodes/:id/recycle",scope:"crtr:act",handler:Ei},{method:"POST",pattern:"/v1/nodes/:id/demote",scope:"crtr:act",handler:Oi},{method:"POST",pattern:"/v1/nodes/:id/promote",scope:"crtr:act",handler:Ai},{method:"POST",pattern:"/v1/nodes/:id/yield",scope:"crtr:act",handler:Ti},{method:"GET",pattern:"/v1/nodes/:id/broker/structured-request",handler:Ci},{method:"POST",pattern:"/v1/nodes/:id/broker/goal",handler:$i},{method:"POST",pattern:"/v1/nodes/:id/wait",handler:Ni},{method:"PATCH",pattern:"/v1/nodes/:id/config",handler:Mi}];export{Mi as handleConfig,ri as handleCreate,gi as handleFork,li as handleList,Ai as handlePromote,Ti as handleYield,vo as nodeRoutes,Io as resolveCreateKind};
|
|
1
|
+
var je=Object.defineProperty;var d=(e,n)=>je(e,"name",{value:n,configurable:!0});import{randomUUID as Fe}from"node:crypto";import{envProfileId as Ge}from"../../../shared/env.js";import{pausedCanvasProfiles as xe}from"../../../core/profiles/manifest.js";import{existsSync as $,realpathSync as oe,statSync as ae}from"node:fs";import{isAbsolute as W,resolve as L}from"node:path";import{appendSituationalContext as Be,formatSituationalProse as We}from"../../../core/runtime/situational-context.js";import{closeNode as Ue}from"../../../core/runtime/close.js";import{assertCheckoutNotRemoved as Ve,reviveNode as de}from"../../../core/runtime/revive.js";import{nowIso as U}from"../../../core/fs-utils.js";import{appPaidLaunch as Ke,assertLaunchModelRegistered as V,forkNode as Je,resolveForkSource as se,spawnChildPrepared as ze}from"../../../core/runtime/spawn.js";import{forkSourceNode as le,newNodeId as ce}from"../../../core/runtime/nodes.js";import{abandonCreateRequest as ue,CREATE_LEASE_RENEW_MS as He,claimCreateLease as fe,createLeaseLive as Ye,renewCreateLease as Qe,childrenOf as Xe,completeCreateRequest as pe,findCreateRequest as me,getNode as b,recordCreateRequestNode as Ze,reserveCreateRequest as we,reserveCreateRequestNode as qe,listNodes as en,recordRespawnAttempt as nn,subscribersOf as tn,subscriptionsOf as he,updateNode as T}from"../../../core/canvas/canvas.js";import{armControllerWait as rn,liveControllerWaits as on}from"../../../core/canvas/waits.js";import{withCanvasWrite as K}from"../../../core/canvas/db.js";import{markNodeRead as an}from"../../../core/canvas/recovery.js";import{nodeObject as dn}from"../../../core/graph/objects.js";import{recordActedOn as sn}from"../../../core/graph/edges.js";import{publish as ln}from"../../../core/graph/events.js";import{readerFor as cn}from"../reader.js";import{relocateSessionCwd as un,unbindSession as fn}from"../../../core/canvas/sessions.js";import{ticketCountsForNodes as pn}from"../../../core/canvas/attention.js";import{isSafeNodeId as mn}from"../../../core/canvas/paths.js";import{contextDir as ye,nodeAgentDir as J}from"../../../core/canvas/node-agent-paths.js";import{checkCronBirth as wn,cronRefusalError as hn}from"../../cron/authority.js";import{cronBirthPlacement as yn}from"../../cron/armed-context.js";import{existsBeneath as _n,isAbsentOrRefused as gn,isBeneathRefusal as bn,readdirBeneath as vn}from"../../../core/spaces/open-beneath.js";import{readNodeMessagesPage as kn,readNodeSession as Sn,readNodeSnapshot as In,transcriptMarkdown as Rn}from"../../../core/runtime/node-read.js";import{toolCallIds as En,withoutImages as _e}from"../../../core/runtime/broker-protocol.js";import{welcomeWindow as On}from"../../../core/runtime/session-cycles.js";import{assembleNodeSubject as Cn}from"../../../core/substrate/subject.js";import{reviveAll as An}from"../../../core/runtime/revive-all.js";import{promoteAsync as $n,requestYieldAsync as Tn,reshapeNodeAsync as z}from"../../../core/runtime/promote.js";import{recycleNode as Nn}from"../../../core/runtime/recycle.js";import{relaunchRoot as Pn}from"../../../core/runtime/reset.js";import{assertReopenGate as Dn}from"../../../core/runtime/reopen.js";import{requireCurrentExecution as Ln}from"./broker-recovery.js";import{readOutputRequest as Mn}from"../../../core/runtime/output-result.js";import{writeYieldMessage as jn,readGoal as Fn,captureGoalIfAbsent as Gn}from"../../../core/runtime/kickoff.js";import{ensureRoadmap as xn,hasRoadmap as Bn}from"../../../core/runtime/roadmap.js";import{renameWindow as Wn}from"../../../core/runtime/placement.js";import{buildLaunchSpecAsync as Un,explicitModelIntent as Vn,normalizeModel as Kn,readMergedLaunchConfigAsync as ge}from"../../../core/runtime/launch.js";import{modelRequestFromConfig as Jn}from"../../../core/model-routes.js";import{persistDormantModel as zn,setModelLive as Hn}from"../../../core/runtime/model-swap.js";import{waitForBrokerViewSocket as be}from"../../../core/runtime/view-socket.js";import{viewTransport as Yn}from"../../runs/observer.js";import{BrokerUnreachableError as Qn}from"../../../core/runtime/broker-request.js";import{boundFleet as M}from"../../../core/runtime/fleet.js";import{admitLegacyStructuredOutput as Xn}from"../../structured-requests/sidecar.js";import{assertOutputSchemaAccepted as Zn}from"../../../core/runtime/structured-output.js";import{OUTCOME_PAYLOAD_MAX_BYTES as ve}from"../../../core/canvas/types.js";import{HUMAN_ACTION_NAME_PATTERN as qn}from"../../../core/human/action-binding.js";import{resolveHumanAction as et}from"../../../core/human-actions.js";import{parseDurationMs as nt}from"../../../core/wake.js";import{claimWarmNode as tt,refillWarmPool as ke,resumeWarmClaim as it,warmPoolEnabled as rt}from"../../../core/runtime/warm-pool.js";import{assertLaunchKind as H,isLaunchKind as ot,resolveLaunchTarget as at}from"../../../core/runtime/launch-target.js";import{fullName as dt}from"../../../core/canvas/labels.js";import{reportsForNode as Se}from"./reports.js";import{requireUsableProfile as st}from"./profiles.js";import{assertProfileActive as lt,isProfilePaused as ct,loadExactProfileManifest as ut}from"../../../core/profiles/manifest.js";import{MachineOfflineError as ft}from"../../../core/runtime/runner/machine/ops.js";import{asNodePerson as pt}from"../../reconcilers/node-lifecycle/node-person.js";import{getCron as Y}from"../../../core/canvas/crons.js";import{cronWakeOrigin as mt}from"../../../core/runtime/bearings.js";import{boundDaemonControl as wt}from"../../control.js";import{notFound as N,usage as y}from"../../../core/errors.js";import{assertScope as ht,validateScopes as Ie}from"../../../core/scopes.js";import{scopeAllowed as E}from"../../../shared/env.js";import{toCloseResultDTO as yt,toNodeDetailDTO as Q,toNodeSummaryDTO as _t,toReviveResultDTO as gt}from"../map.js";import{ApiError as p}from"../../../api/index.js";import{InputError as w}from"../../../core/io.js";import{endExecution as bt,liveExecutionForNode as X,requestExecutionStop as vt}from"../../../core/canvas/executions.js";import{runnerForExecution as kt}from"../../../core/runtime/runner/index.js";import{wakeResident as St}from"../../reconcilers/node-lifecycle/remote-wake.js";import{isNowEligibleFault as It}from"../../../core/canvas/status-glyph.js";import{remoteEnvironmentOf as Re}from"../../../core/runtime/blaxel-environment.js";import{machineEnvironmentOfProfile as Rt}from"../../../core/runtime/runner/machine/environment.js";import{isCloudRole as Et}from"../../../core/canvas/person-state.js";import{actsAsPerson as j,canReadNode as C,mayOnNode as Ot,readableNodeIds as Ct,resolvedScopes as At}from"../router.js";import{forwardVerb as $t,queryWithoutMachine as Tt,relayError as Nt,unknownError as Pt,withMachine as Dt}from"../../peer/forward.js";import{fileRoot as Lt}from"../../../core/spaces/file-root.js";import{activeGrant as Mt,payerOfGrant as jt}from"../../../core/grants/mirror.js";import{launchUsesHostedEndpoint as Ft}from"../../../core/model-auth/readiness.js";import{nodeTerminalGrant as Gt}from"../../../core/grants/terminal.js";import{appRungForGrant as xt}from"../../../core/llm/app-rungs.js";import{APP_FAMILY as Bt}from"../../../core/model-routes.js";import{listProfileEnvNames as Wt}from"../../../core/profiles/env-store.js";import{hasConfiguredProviderCredential as Ut,NO_PROVIDER_CREDENTIAL_MESSAGE as Ee}from"../../../core/runtime/provider-credential-gate.js";import{filterAsync as Vt,mapAsync as Oe}from"../../../core/async-array.js";import{addStepTiming as Kt,collectStepTimings as Jt,serverTimingHeader as zt,sinceCollectionStart as Ht,timedStep as Yt}from"../../../core/step-timings.js";async function h(e){const n=await b(e);if(n===null)throw N(`unknown node: ${e}`,{received:e});return n}d(h,"requireMeta");async function Z(e){return{subscribesTo:await he(e),subscribers:await tn(e),children:await Xe(e)}}d(Z,"edgesFor");async function v(e){const n=await h(e);return await Q(n,await Z(e))}d(v,"detailOf");async function Qt(e){let n=(await Se(e)).length;try{n+=vn(await J(e),await ye(e)).length}catch(t){if(!gn(t))throw t}return n}d(Qt,"countFiles");function Xt(e){if(typeof e!="object"||e===null)throw y("a node create requires a JSON body");const n=e;if(n.kind!==void 0&&(typeof n.kind!="string"||n.kind.trim()===""))throw y("kind must be a non-empty string when provided");if(n.description!==void 0&&(typeof n.description!="string"||n.description.trim()===""))throw y("description must be a non-empty string when provided");if(n.creator!==void 0&&(typeof n.creator!="string"||n.creator.trim()===""))throw y("creator must be a non-empty node id when provided");if(n.scopes!==void 0&&Ie(n.scopes),n.isolated!==void 0&&typeof n.isolated!="boolean")throw new p(400,"invalid_request","isolated must be a boolean",{param:"isolated"});if(n.start!==void 0&&typeof n.start!="boolean")throw new p(400,"invalid_request","start must be a boolean",{param:"start"});const t=n.root_lifecycle;if(t!==void 0&&t!=="resident"&&t!=="terminal")throw y("root_lifecycle must be 'resident' or 'terminal'");if(n.request_key!==void 0&&(typeof n.request_key!="string"||n.request_key.trim()===""||n.request_key.length>128))throw y("request_key must be a non-empty string of at most 128 characters when provided");return n}d(Xt,"parseCreateBody");function Zt(e){if(e===void 0)return;const n=nt(e),t=n===null?null:new Date(Date.now()+n);if(n===null||!Number.isFinite(n)||n<=0||t===null||!Number.isFinite(t.getTime()))throw new p(422,"invalid_deadline","`deadline` must be a positive representable duration");return t.toISOString()}d(Zt,"parseDeadline");function qt(e){if(e!==void 0){if(typeof e!="object"||e===null||Array.isArray(e))throw new p(400,"invalid_request","`outcome_delivery` must be an object");if(typeof e.action!="string"||!qn.test(e.action))throw new p(400,"invalid_request","`outcome_delivery.action` must be a declared action name");if(e.payload!==void 0){let n;try{n=JSON.stringify(e.payload)}catch{throw new p(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable")}if(n===void 0)throw new p(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable");if(Buffer.byteLength(n,"utf8")>ve)throw new p(413,"payload_too_large",`serialized payload exceeds ${ve} bytes`)}return e}}d(qt,"parseOutcomeDelivery");function ei(e,n){const t=et(e.action,n);if(!("kind"in t))return{actionName:e.action,argv:t.argv,cwd:t.cwd,configOrigin:t.configOrigin,...e.payload===void 0?{}:{payload:e.payload}};throw t.kind==="unknown_action"?new p(422,"unknown_action",`no action named ${e.action} is declared from ${n}`):new p(422,"invalid_action",`${e.action} is declared in ${t.configOrigin} but unusable: ${t.reason}`,{reason:t.reason,configOrigin:t.configOrigin})}d(ei,"resolveOutcomeDelivery");function ni(e,n,t){const r={kind:e.kind,cwd:t,prompt:e.prompt??""};return e.mode!==void 0&&(r.mode=e.mode),e.name!==void 0&&(r.name=e.name),e.description!==void 0&&(r.description=e.description),n!==void 0&&(r.parent=n),e.creator!==void 0&&(r.creator=e.creator),e.scopes!==void 0&&(r.scopes=e.scopes),e.isolated!==void 0&&(r.isolated=e.isolated),e.root===!0&&(r.root=!0),e.start===!0&&(r.start=!0),e.root_lifecycle!==void 0&&(r.rootLifecycle=e.root_lifecycle),(e.worktree===!0||typeof e.worktree=="string")&&(r.worktree=!0),typeof e.worktree=="string"&&(r.worktreeBase=e.worktree),e.worktree!==void 0&&(r.worktreeCwd=L(e.pin_cwd??e.cwd??t)),e.fork_from!==void 0&&(r.forkFrom=e.fork_from),e.model!==void 0&&(r.model=e.model),e.profile!==void 0&&(r.profile=e.profile),e.situational_context!==void 0&&(r.situationalContext=e.situational_context),e.node_id!==void 0&&(r.nodeId=e.node_id),r}d(ni,"buildRecipe");function ti(e,n,t){return!rt()||e.prefer_warm!==!0||e.root!==!0||e.parent!=null||e.root_lifecycle==="terminal"||(e.prompt??"")!==""||e.model!==void 0||e.fork_from!==void 0||e.worktree!==void 0||e.node_id!==void 0||e.scopes!==void 0||e.isolated!==void 0?null:{kind:e.kind,mode:e.mode??"base",cwd:n,profileId:t,model:e.model??null,situationalContext:e.situational_context??null,name:e.name??null,creator:e.creator??null}}d(ti,"warmRequestFor");import{resolveCreateKind as Ro}from"../../../core/runtime/launch-target.js";function Ce(e){const n=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return Jn(e.model,n,e.modelExact===!0)}d(Ce,"requestFromLaunch");function ii(e,n){if(n===null)return e;if(e.scopes===void 0)return{...e,scopes:[...n]};const t=e.scopes.filter(r=>!E(n,r));if(t.length===0)return e;throw new p(403,"scope_denied",`scopes exceed the bearer token's ceiling: ${t.join(", ")}`,{scopes:t,ceiling:n})}d(ii,"withinCeiling");async function Ae(e,n,t){const r=(await Un(n.kind,n.mode,{lifecycle:n.lifecycle,hasManager:e.parent!==null,model:n.model,modelOverride:!0,cwd:e.cwd,profileId:e.profile_id??null,app:e.grantee??"app:terminal"})).launch;await V(Ce(r),{cwd:e.cwd,profileId:e.profile_id??null},t)}d(Ae,"assertNodeModelChangeRegistered");async function ri(e){if(!Et()||e.app!=="app:terminal")return!1;const n=e.class==="broker"?(await b(e.node))?.profile_id??null:e.cron===null?null:(await Y(e.cron))?.profile??null;return n!==null&&await Rt(n)!==null}d(ri,"callerRunsOnMachine");async function $e(e,n){const t=e.principal;if(t.class!=="broker"&&t.class!=="cron"||await ri(t))return;const r=Lt({app:t.app,resolved:await At(t),launched:t.scopes},n,"read");if("root"in r)return;const i="missing"in r?r.missing:null;throw new p(403,"scope_missing",i?`the child's directory ${n} needs missing scope ${i}`:`no permission of this run names the child's directory ${n}`,void 0,void 0,i?{scope:i}:void 0)}d($e,"assertCallerReaches");const q=new Map;async function oi(e,n={},t={}){const r=performance.now(),{value:i,steps:a}=await Jt(()=>ai(e,n,t));return a.push(["total",performance.now()-r]),{...i,headers:{...i.headers??{},"server-timing":zt(a)}}}d(oi,"handleCreate");async function ai(e,n,t){const r=ii(Xt(e.body),e.ceiling);if(e.principal.class==="broker"){const s=e.principal;if(r.prefer_warm===!0&&s.app!=="app:terminal"&&(r.prefer_warm=!1),r.parent!=null){const o=await h(r.parent);if(o.grantee!==s.app)throw new p(403,"other_app_run","cannot create a child under another app's node");if(!await C(s,o.grantee??"app:terminal",r.parent))throw N(`unknown node: ${r.parent}`,{received:r.parent})}if(r.creator!==void 0&&r.creator!==s.node)throw new p(403,"other_app_run","cannot create for another node");if(r.fork_from!==void 0){let o=null;try{o=await le(await se(r.fork_from))}catch{}if(o?.grantee!==s.app||!await C(s,o.grantee,o.node_id))throw new p(403,"other_app_run","cannot fork another app's conversation")}r.creator=s.node}if(e.principal.class==="person"&&e.principal.sub!==void 0){const s=r.fork_from===void 0?null:await le(await se(r.fork_from)).catch(()=>null);for(const o of[r.parent,r.creator,s?.node_id])if(o!=null&&await b(o)!==null&&!await Ot(e.principal,"edit",o))throw N(`unknown node: ${o}`,{received:o})}if(e.principal.class==="cron"){const s=e.principal;for(const l of["parent","creator","fork_from","node_id"])if(r[l]!=null)throw new p(403,"permission_error",`a cron cannot set ${l} on a node it starts`);r.prefer_warm=!1,r.node_id=await ce(),s.isolated&&(r.isolated=!0,r.cwd=await J(r.node_id,s.app));const o=await wn({grantee:s.app,sub:s.sub,grant_id:s.grant,scopes:s.scopes,from_exec:s.from_exec},{profile:r.profile,cwd:r.cwd,pin_cwd:r.pin_cwd,kind:r.kind,model:r.model,mode:r.mode});if(!o.allowed)throw hn(o);if(r.scopes!==void 0){const l=r.scopes.find(m=>!E(o.effectiveScopes,m)||!E(s.scopes,m));if(l!==void 0)throw new p(403,"scope_missing",`scope ${l} is not held by this cron`,void 0,void 0,{scope:l})}else o.scopes!==null&&(r.scopes=o.scopes)}r.creator!==void 0&&ht(await h(r.creator),"crtr:act");const i=r.request_key?.trim();if(i===void 0||r.node_id!==void 0&&mn(r.node_id)&&await b(r.node_id)!==null&&(await me(i))?.nodeId!==r.node_id)return F(e,r,n,t);const a=q.get(i);if(a!==void 0)return a;const c=di(e,r,i,n,t);q.set(i,c);try{return await c}finally{q.delete(i)}}d(ai,"createWithinTimings");const Te=`${process.pid}:${Fe()}`,ee="create_request_in_progress";async function Ne(e,n,t){const r=Date.now()+9e4;let i=Date.now()+1e4;for(;t!==null;){const a=await b(t);if(a!==null){if(!j(e.principal)&&!await C(e.principal,a.grantee??"app:terminal",t))throw new p(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:await v(t)}}if(await Ye(n)&&(i=Math.min(r,Date.now()+1e3)),Date.now()>=i||(await me(n))?.nodeId!==t)break;await new Promise(c=>setTimeout(c,100))}throw new p(409,ee,"another create with this request_key is in progress; retry it")}d(Ne,"awaitForeignCreate");async function di(e,n,t,r,i){const a=await we(t),c=Te;if(a.nodeId!==null&&a.state==="reserved"&&await b(a.nodeId)===null&&!await fe(t,a.nodeId,c))try{return await Ne(e,t,a.nodeId)}catch(o){if(!(o instanceof p)||o.code!==ee||!await fe(t,a.nodeId,c))throw o}const s=setInterval(()=>{Qe(t,c).catch(()=>{})},He);try{return await si(e,n,t,r,i,a)}finally{clearInterval(s)}}d(di,"handleKeyedCreateRequest");async function si(e,n,t,r,i,a){if(a.nodeId!==null&&await b(a.nodeId)!==null){if(a.state!=="warm_claimed"){const c=await b(a.nodeId);if(!j(e.principal)&&!await C(e.principal,c.grantee??"app:terminal",a.nodeId))throw new p(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:await v(a.nodeId)}}return F(e,n,r,i,a)}try{return await F(e,n,r,i,a)}catch(c){if(c instanceof p&&c.code===ee)throw c;const s=await we(t);throw(s.nodeId===null||await b(s.nodeId)===null)&&await ue(t,s.nodeId),c}}d(si,"keyedCreateOwned");async function F(e,n,t,r,i=void 0){const a=r.deadlineAt??Zt(n.deadline),c=qt(n.outcome_delivery),s=e.principal.class==="cron"?await yn({grantee:e.principal.app,sub:e.principal.sub,grant_id:e.principal.grant,scopes:e.principal.scopes,cron_id:e.principal.cron,origin_run_id:e.principal.origin_run,isolated:e.principal.isolated,creator:e.principal.kind==="exec"?null:(await Y(e.principal.cron))?.created_by??null},n.node_id):null;s!==null&&(n.root=s.root===!0);const o=s?.parent??n.parent??void 0;if(o==null&&n.root!==!0)throw y("a node create requires a parent (or root: true for an independent root)");let l=null;if(n.output_schema!==void 0){try{l=JSON.parse(n.output_schema)}catch{throw y("output_schema must be a JSON schema string")}if(l===null||typeof l!="object"||Array.isArray(l))throw y("output_schema must be a JSON schema object");await Zn(l)}const m=await at(n,{validateKind:Me,...e.principal.class==="broker"||e.principal.class==="cron"?{app:e.principal.app}:{}}),{profileId:f,kind:u,cwd:_,launch:I}=m;if(n.pin_cwd!==void 0&&n.pin_cwd!==""&&n.worktree===void 0&&n.isolated!==!0&&!$(_)&&await Re(f)===null)throw new w({error:"cwd_missing",message:`cwd is not an existing directory: ${_}`,received:_,field:"cwd",next:"Pass an existing directory with --cwd."});await $e(e,_),n.worktree!==void 0&&await $e(e,L(n.pin_cwd??n.cwd??_));const k={...n,kind:u},P=c===void 0?void 0:ei(c,_),te=("grant"in e.principal?e.principal.grant:null)??(o==null?null:(await b(o))?.grant_id??null);if(await V(Ce(await Ke(I,te,n.model)),{cwd:_,profileId:f},t.modelRegistry),await jt(te)!=="app"&&!await Ut(f===null?[]:await Wt(f))&&!await Ft(m))throw new p(412,"no_provider_credential",Ee,{error:"no_provider_credential",message:Ee,next:"The person running this runtime logs a provider in with `crtr sys setup`, or stores a provider key on the profile."});let x=null;{const ie=i===void 0||i.nodeId===null||i.state==="warm_claimed"?ti(k,_,f):null,O=ie!==null&&!(n.start===!0&&await Re(f)!==null)?ie:null,B=l===null&&r.beforeBrokerLaunch===void 0?void 0:async g=>{l!==null&&await Xn(g,"terminal",l),r.beforeBrokerLaunch?.(g)};if(i?.state==="warm_claimed"&&i.nodeId!==null){const g=O===null?null:await it(O,i.nodeId,B);if(g===null)throw await ue(i.requestKey,i.nodeId),new p(503,"create_resume_failed",`could not resume warm claim ${i.nodeId}; retry the create`);return await pe(i.requestKey,g),{status:201,body:await v(g)}}if(O!==null){const g=await tt(O,{...a===void 0?{}:{deadlineAt:a},...P===void 0?{}:{outcomeDelivery:P},...i===void 0?{}:{requestKey:i.requestKey}},B);if(g!==null)return i!==void 0&&await pe(i.requestKey,g),ke(O),{status:201,body:await v(g)};x=O}const D=i?.nodeId??n.node_id??(i===void 0?void 0:await ce());if(i!==void 0&&i.nodeId===null){const g=await qe(i.requestKey,D,Te);if(g!==D)return await Ne(e,i.requestKey,g)}const R=ni(D===void 0?k:{...k,node_id:D},o,_);s!==null&&(s.rootLifecycle!==void 0&&(R.rootLifecycle=s.rootLifecycle),s.scopes!==void 0&&k.scopes===void 0&&(R.scopes=s.scopes),s.run!==void 0&&(R.run=s.run),s.withinCreate!==void 0&&(R.withinCreate=s.withinCreate)),a!==void 0&&(R.deadlineAt=a),P!==void 0&&(R.outcomeDelivery=P),R.readiness=n.root===!0?"await":"launch",Kt("handler_checks",Ht());const re=await ze(R,B,()=>{x!==null&&ke(x)});return i!==void 0&&await Ze(i.requestKey,re.node.node_id),{status:201,body:await Yt("response_detail",()=>v(re.node.node_id))}}}d(F,"handleCreateRequest");function S(e,n){const t=e.query.getAll(n);if(t.length>1)throw y(`${n} must appear at most once`);return t[0]}d(S,"singleQueryValue");function ne(e,n){if(e!==void 0){if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1;throw y(`${n} must be true or false`)}}d(ne,"optionalBoolean");function G(e,n,t){if(e!==void 0){if(t.includes(e))return e;throw y(`${n} must be one of: ${t.join(", ")}`)}}d(G,"oneOf");function li(e){const n=new Set(["status","lifecycle","kind","mode","profile_id","profile_prefix","parent","top_level","under","under_inclusive","hanging","include"]);for(const[I]of e.query)if(!n.has(I))throw y(`unknown nodes query parameter: ${I}`);const t=G(S(e,"status"),"status",["active","idle","done","dead","canceled"]),r=G(S(e,"lifecycle"),"lifecycle",["terminal","resident"]),i=S(e,"kind"),a=G(S(e,"mode"),"mode",["base","orchestrator"]),c=S(e,"profile_id"),s=S(e,"profile_prefix"),o=S(e,"parent"),l=ne(S(e,"top_level"),"top_level"),m=S(e,"under"),f=ne(S(e,"under_inclusive"),"under_inclusive"),u=ne(S(e,"hanging"),"hanging"),_=G(S(e,"include"),"include",["activity"]);if(o!==void 0&&l===!0)throw y("parent and top_level=true cannot be combined");return{...t!==void 0?{status:t}:{},...r!==void 0?{lifecycle:r}:{},...i!==void 0?{kind:i}:{},...a!==void 0?{mode:a}:{},...c!==void 0?{profile_id:c}:{},...s!==void 0?{profile_prefix:s}:{},...o!==void 0?{parent:o}:{},...l!==void 0?{top_level:l}:{},...m!==void 0?{under:m}:{},...f!==void 0?{under_inclusive:f}:{},...u!==void 0?{hanging:u}:{},..._!==void 0?{include:_}:{}}}d(li,"parseListQuery");async function ci(e){const n=li(e);let t=await en({...n.status!==void 0?{status:n.status}:{},...n.lifecycle!==void 0?{lifecycle:n.lifecycle}:{},...n.kind!==void 0?{kind:n.kind}:{},...n.mode!==void 0?{mode:n.mode}:{},...n.profile_id!==void 0?{profileId:n.profile_id}:{},...n.profile_prefix!==void 0?{profilePrefix:n.profile_prefix}:{},...n.parent!==void 0?{parent:n.parent}:{},...n.top_level===!0?{topLevel:!0}:{},...n.under!==void 0?{under:n.under}:{},...n.under_inclusive===!0?{underInclusive:!0}:{},...n.hanging===!0?{hanging:!0}:{}});const r=await Ct(e.principal);r!==null&&(t=t.filter(o=>r.has(o.node_id)));const i=n.include==="activity"?await pn(t.map(o=>o.node_id)):null,a=t.length>0?xe():new Set,c=new Map((await on()).map(o=>[o.nodeId,o.controllerId]));return{status:200,body:await Oe(t,async o=>{const l=await _t(o,o.profile_id!==null&&a.has(o.profile_id),c.get(o.node_id)??null);if(i!==null){const m=await Se(o.node_id);l.activity={latest_report:m[0]??null,final_report:o.final_report===null?null:m.find(f=>f.name===o.final_report)??null,pending_human_count:i[o.node_id]??0}}return l})}}d(ci,"handleList");async function ui(e){const n=e.params.id,t=await $t(e,n,{method:"GET",path:`/v1/nodes/${encodeURIComponent(n)}`,query:Tt(e)});if(t.kind==="unknown")throw Pt(n,t.unreachable);if(t.kind==="remote"){if(t.status>=400)throw Nt(t.status,t.body);return{status:t.status,body:Dt(t.body,t.machine)}}return await h(n),{status:200,body:await v(n)}}d(ui,"handleDetail");async function fi(e){const n=e.params.id;await h(n);const t=await In(n),{start:r}=On(t.snapshot.messages,s=>JSON.stringify(_e(s,n)).length),i=t.snapshot.messages.slice(r).map(s=>_e(s,n)),a=En(i);return{status:200,body:{node_id:n,snapshot:{messages:i,...t.snapshot.messageIds===void 0?{}:{messageIds:t.snapshot.messageIds.slice(r)},messageVisibility:t.snapshot.messageVisibility.slice(r),turnVisibility:t.snapshot.turnVisibility,stats:t.snapshot.stats,state:t.snapshot.state,display:t.snapshot.display,...t.snapshot.queued===void 0?{}:{queued:t.snapshot.queued},...t.snapshot.toolGroupSummaries===void 0?{}:{toolGroupSummaries:Object.fromEntries(Object.entries(t.snapshot.toolGroupSummaries).filter(([s])=>a.has(s)))},...t.snapshot.turnReplies===void 0?{}:{turnReplies:t.snapshot.turnReplies},...t.snapshot.workingActivity===void 0?{}:{workingActivity:t.snapshot.workingActivity}},commands:t.commands.map(s=>({name:s.name,description:s.description,source:s.source})),captured_at:U()}}}d(fi,"handleSnapshot");async function pi(e){const n=e.params.id,t=await Cn(n);if(t===null)throw N(`unknown node: ${n}`,{received:n});return{status:200,body:t}}d(pi,"handleSubject");function mi(e){for(const[a]of e.query)if(a!=="cursor"&&a!=="limit")throw y(`unknown messages query parameter: ${a}`);const n=e.query.getAll("cursor"),t=e.query.getAll("limit");if(n.length>1)throw y("cursor must appear at most once");if(t.length>1)throw y("limit must appear at most once");if(t.length===0)return n.length===0?{}:{cursor:n[0]};const r=t[0],i=Number(r);if(!Number.isSafeInteger(i)||r==="")throw y("limit must be an integer from 1 through 500");return n.length===0?{limit:i}:{cursor:n[0],limit:i}}d(mi,"parseMessagesQuery");async function wi(e){const n=e.params.id,t=await kn(n,mi(e));return{status:200,body:{node_id:n,messages:t.messages,...t.messageIds===void 0?{}:{message_ids:t.messageIds},message_visibility:t.messageVisibility,next_cursor:t.nextCursor,captured_at:U()}}}d(wi,"handleMessages");async function hi(e){const n=e.params.id;await h(n);const t=await Sn(n);return{status:200,body:{node_id:n,session_file:t.sessionFile,session_jsonl:t.sessionJsonl,system_prompt:t.systemPrompt,captured_at:U()}}}d(hi,"handleSession");async function yi(e){const n=e.params.id;return await h(n),{status:200,body:{node_id:n,markdown:await Rn(n)}}}d(yi,"handleTranscript");async function _i(e){const n=e.params.id;await h(n);const t=d(async(i,a)=>({node_id:i,label:(await b(i))?.name??i,dir:await ye(i),self:a,files:await Qt(i)}),"root"),r=await Vt([await t(n,!0),...await Oe(await he(n),async i=>await t(i.node_id,!1))],async i=>await gi(i.node_id,i.dir)||i.files>0);return{status:200,body:{node_id:n,roots:r}}}d(_i,"handleContext");async function gi(e,n){try{return _n(await J(e),n)}catch(t){if(bn(t))return!1;throw t}}d(gi,"hasDir");async function bi(e){const n=await h(e.params.id),t=e.principal.class==="broker"?e.principal.scopes:e.ceiling,r=t===null?void 0:n.scopes==null?[...t]:[...new Set([...n.scopes.filter(a=>E(t,a)),...t.filter(a=>E(n.scopes,a))])],i=await Je(n.node_id,r,e.principal.class==="broker"?e.principal.node:void 0);return{status:201,body:await v(i.node.node_id)}}d(bi,"handleFork");const vi=1e4;async function ki(e){const n=e.params.id,t=await h(n),r=await X(n);if(r===null||r.runner!=="machine")throw new w({error:"not_hanging",message:`${n} has no live broker on a Mac \u2014 nothing to kick here.`,next:`Use \`crtr node lifecycle revive ${n} --now\` from the CLI, which kicks a local broker directly.`});if(!It(t.fault??null))throw new w({error:"not_hanging",message:`${n} is live but has no pi\u2192provider fault eligible for --now.`,next:"Use --now only on a node the canvas shows as hanging (\u26A0) with a `pi\u2192provider` fault."});if(t.streaming===!0)throw new w({error:"busy",message:`${n} is mid-turn right now (busy) \u2014 refusing to stop a working engine.`,next:"Re-check the canvas \u2014 if it is no longer marked hanging (\u26A0), nothing to do."});await vt(n,{afterTurn:!1,reason:"revive_now"});const i=await kt("machine").stop(r,{reason:"revive_now"});if(!i.confirmed)throw i.error??new Error(`stop of ${n} on its Mac was not confirmed`);return await bt(r.executionId,{reason:"revive_now"}),await de(n,{resume:!0,capacity:"refuse"}),{status:200,body:{kicked:!0}}}d(ki,"handleKick");async function Si(e){const n=e.params.id,t=await h(n),r=e.body,i=r?.resume??!0,a=r?.reopen??!1;Ve(n,t),await Dn(n,a,e.principal.class==="broker"?e.principal.node:null);const c=!i&&r?.cron_id!==void 0?await Y(r.cron_id):null,s=await X(n);if(i&&s!==null&&s.runner!=="process"&&s.state==="running"&&!ct(t.profile_id))try{await pt({node_id:n,sub:t.sub??null,profile_id:t.profile_id??null},()=>St(s))}catch(u){if(!(u instanceof ft))throw u}const o=await de(n,{resume:i,capacity:"refuse",...c!==null?{wakeReason:await mt(c,"schedule_revive")}:{}});o.outcome!=="already-live"&&await nn(n,{failures:0,notBefore:null});const l=(await b(n))?.status??"active",m=(o.launch??M().get(n)?.handle)?.exited,f=o.outcome!=="frozen"&&await be(n,m,vi);return{status:200,body:gt(n,o,l,f)}}d(Si,"handleRevive");async function Ii(e){const n=e.params.id;return{status:200,body:{newNodeId:(await Pn(n))?.newNodeId??null}}}d(Ii,"handleRelaunchRoot");async function Ri(e){const n=e.params.id;await h(n);const t=e.body;if(t?.caller_pid!==void 0&&(!Number.isInteger(t.caller_pid)||t.caller_pid<=0))throw y("caller_pid must be a positive integer when provided");const r=wt(),i=new Promise(c=>{e.res.once("close",()=>c())}),a=await Ue(n,{teardownAfter:i,rootEvent:t?.finish===!0?"finish":"cancel",callerPid:t?.caller_pid,...e.principal.class==="broker"?{closer:e.principal.node}:{},...r===null?{}:{registerDetached:r.registerDetached}});return{status:200,body:yt(a)}}d(Ri,"handleClose");async function Ei(e){if(!j(e.principal))throw new p(403,"permission_error","only the person marks a conversation read");const n=e.params.id;return await h(n),await an(n),{status:204}}d(Ei,"handleMarkRead");async function Oi(e){const n=e.params.id;await h(n);const t=await Nn(n);return{status:200,body:{recycled:t.recycled,finalized:t.finalized,new_root:t.newRoot,delivered:t.delivered}}}d(Oi,"handleRecycle");async function Ci(e){const n=e.params.id;return await h(n),await z(n,{lifecycle:"terminal"}),await A(e,n,["lifecycle"]),{status:200,body:await v(n)}}d(Ci,"handleDemote");async function Ai(e,n={}){const t=e.params.id,r=await h(t),i=e.body??{};i.kind!==void 0&&await H(i.kind,r.cwd,r.profile_id??null),i.model!==void 0&&await Ae(r,{kind:i.kind??r.kind,mode:"orchestrator",lifecycle:i.resident===!0?"resident":r.lifecycle,model:i.model},n.modelRegistry);const a=await $n(t,{...i.kind!==void 0?{kind:i.kind}:{},...i.resident===!0?{resident:!0}:{},...i.model!==void 0?{model:i.model}:{}});await A(e,t,["mode",...i.kind!==void 0?["kind"]:[],...i.resident===!0?["lifecycle"]:[],...i.model!==void 0?["model"]:[]]);const c=await Q(a.meta,await Z(t));return c.roadmap_written=a.roadmapWritten,c.roadmap_ref=a.roadmapRef,c.goal_path=a.goalPath,{status:200,body:c}}d(Ai,"handlePromote");async function $i(e){const n=e.params.id;return await h(n),{status:200,body:{request:await Mn(n)}}}d($i,"handleBrokerStructuredRequest");async function Ti(e){const n=e.params.id,t=e.body??{};if(await Ln(n,t.expected_execution_id),typeof t.text!="string")throw new p(400,"invalid_request","text must be a string");return await h(n),{status:200,body:{captured:await Gn(n,t.text)}}}d(Ti,"handleBrokerGoal");async function Ni(e,n={}){const t=e.params.id,r=await h(t),i=e.body??{};i.kind!==void 0&&await H(i.kind,r.cwd,r.profile_id??null),i.model!==void 0&&await Ae(r,{kind:i.kind??r.kind,mode:i.promote===!0?"orchestrator":r.mode,lifecycle:r.lifecycle,model:i.model},n.modelRegistry);const a=i.note??"Refresh: continue against your roadmap or goal.";await jn(t,a);const c=await Tn(t,{...i.promote===!0?{promote:!0}:{},...i.kind!==void 0?{kind:i.kind}:{},...i.model!==void 0?{model:i.model}:{}});return{status:200,body:await Q(c.meta,await Z(t))}}d(Ni,"handleYield");async function Pi(e){const n=e.params.id;await h(n);const t=e.body;if(t===void 0||typeof t.controller!="string"||t.controller.trim()==="")throw y("a wait requires a controller node id");const r=await b(t.controller);if(r===null)throw N(`unknown controller: ${t.controller}`,{received:t.controller});if(r.status!=="active"&&r.status!=="idle")throw new p(422,"unprocessable",`controller ${t.controller} is ${r.status}`);return await rn(n,t.controller),{status:200,body:await v(n)}}d(Pi,"handleWait");async function Di(e){const n=e.principal,t=await An(n.class==="broker"?async i=>i.grantee===n.app&&await C(n,i.grantee,i.node_id):n.class==="person"&&!j(n)?async i=>await C(n,i.grantee??"app:terminal",i.node_id):void 0);return{status:200,body:{revived:[...t.revived],failed:[...t.failed],frozen:[...t.frozen]}}}d(Di,"handleReviveAll");const Li=new Set(["interrupt","steer","after-turn","next-turn"]);function Mi(e){if(e===null)return null;const n=d(r=>{throw new w({error:"invalid_listen",message:r,received:e,field:"listen",next:'Send an object mapping levels "1".."10" to interrupt|steer|after-turn|next-turn (e.g. {"3":"next-turn"}), or null to reset to the global default.'})},"bad");if(typeof e!="object"||Array.isArray(e))return n("listen must be an object or null");const t=Object.entries(e);if(t.length===0)return n("listen must name at least one level");for(const[r,i]of t)/^(?:[1-9]|10)$/.test(r)||n(`listen level must be 1..10: ${r}`),(typeof i!="string"||!Li.has(i))&&n(`listen delivery must be interrupt|steer|after-turn|next-turn: ${String(i)}`);return JSON.stringify(Object.fromEntries(t))}d(Mi,"listenJson");async function A(e,n,t,r){t.length===0&&r===void 0||await K(async i=>{if(r?.(i),t.length===0)return;const a=await dn(i,n),c=await cn(i,e),s=c.class==="person"?c.person:c.class==="app"?c.app:c.node;await sn(i,s,a),await ln(i,{event:"configured",object:a,actor:s,attrs:{changed:t.join(",")}})})}d(A,"recordConfigured");function Pe(e){const n=M().get(e);if(n===void 0)return!1;try{return process.kill(n.pid,"SIGTERM"),!0}catch{return!1}}d(Pe,"restartLiveBroker");function De(e,n){try{return oe(e)===oe(n)}catch{return!1}}d(De,"sameDirectory");async function ji(e,n={}){const t=e.params.id,r=e.body;let i;if(r===void 0)i={};else if(typeof r=="object"&&r!==null&&!Array.isArray(r))i=r;else throw new w({error:"cwd_invalid",message:"cwd repair requires a non-null object with a non-empty cwd string",received:r,field:"cwd",next:"Send a config patch with a non-empty absolute cwd string."});if(i.profile!==void 0){if(typeof i.profile!="string"||i.profile==="")throw new w({error:"profile_invalid",message:"profile must be a non-empty profile id or name",received:i.profile,field:"profile",next:"Send a profile id or exact name."});if(Object.keys(i).some(f=>f!=="profile"&&f!=="restart"&&i[f]!==void 0))throw new w({error:"profile_not_exclusive",message:"profile can only be combined with restart",field:"profile",next:"Send profile (and optionally restart) alone."});const o=await h(t),l=await st(e,i.profile);lt(l.profileId);const m=ut(l.profileId).manifest.grantee??"app:terminal";if(m!==(o.grantee??"app:terminal"))throw new w({error:"profile_grantee_mismatch",message:`profile ${l.profileId} belongs to ${m}, node ${t} to ${o.grantee}`,received:i.profile,field:"profile",next:"Pick a profile owned by the same app as the node."});return(o.profile_id??null)!==l.profileId&&(ot(o.kind)?(await H(o.kind,o.cwd,l.profileId),await z(t,{profileId:l.profileId})):await T(t,{profile_id:l.profileId}),await A(e,t,["profile"])),i.restart===!0&&Pe(t),{status:200,body:await v(t)}}if(Object.prototype.hasOwnProperty.call(i,"cwd")){const o=i.cwd;if(typeof o!="string"||o==="")throw new w({error:"cwd_invalid",message:"cwd must be a non-empty string",received:o,field:"cwd",next:"Send a non-empty absolute cwd string."});if(Object.keys(i).some(u=>u!=="cwd"&&u!=="keep_session"&&u!=="restart"&&i[u]!==void 0))throw new w({error:"cwd_not_exclusive",message:"cwd repair cannot be combined with another config field",received:i,field:"cwd",next:"Send cwd as the only config field."});const l=await h(t),m=$(l.cwd);if(i.keep_session===!0||m&&W(o)&&$(o)&&De(l.cwd,o)){if(!W(o))throw new w({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${o}`,received:o,field:"cwd",next:"Send an absolute path."});const u=L(o);let _=!1;try{_=ae(u).isDirectory()}catch{}if(!_)throw new w({error:"cwd_missing",message:`cwd is not an existing directory: ${u}`,received:o,field:"cwd",next:"Send an existing absolute directory."});if(m&&!De(l.cwd,u))throw new w({error:"cwd_not_same_directory",message:`${u} is not the same directory as the recorded ${l.cwd}; --keep-session only relocates an alias`,received:o,field:"cwd",next:"Drop --keep-session to repair a gone cwd, or pass the real path of the recorded directory."});if(l.managed_worktree?.state==="open")throw new w({error:"cwd_node_managed_worktree_open",message:`${t} owns an open managed worktree and cannot relocate its cwd`,received:o,field:"cwd",next:"Reconcile the managed worktree first."});const I=l.cwd;return I!==u&&(await K(async k=>{await T(t,{cwd:u}),await k.prepare("UPDATE crons SET cwd = ? WHERE anchor_node = ? AND cwd = ?").run(u,t,I),await un(t,I,u)}),await A(e,t,["cwd"])),i.restart===!0&&Pe(t),{status:200,body:await v(t)}}if(await M().has(t)){const u=`${t} cannot repair its cwd while its broker is live`;throw new p(409,"cwd_node_live",u,{error:"cwd_node_live",message:u,received:o,field:"cwd",next:"Let the node become dormant, then retry the cwd repair."})}if(l.fork_from!=null)throw new w({error:"cwd_node_forked",message:`${t} is a fork and cannot repair its cwd; recorded cwd: ${l.cwd}`,received:o,field:"cwd",next:`Restore ${l.cwd}, then revive the fork normally.`});if(l.managed_worktree?.state==="open")throw new w({error:"cwd_node_managed_worktree_open",message:`${t} owns an open managed worktree and cannot repair its cwd`,received:o,field:"cwd",next:"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon flow."});if($(l.cwd))throw new w({error:"cwd_still_present",message:`${t} recorded cwd still exists: ${l.cwd}; cwd repair is not a relocation command`,received:o,field:"cwd",next:"This command only repairs a node whose recorded cwd is gone."});if(!W(o))throw new w({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${o}`,received:o,field:"cwd",next:"Send an absolute path."});const f=L(o);if(!$(f))throw new w({error:"cwd_missing",message:`cwd does not exist: ${f}`,received:o,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."});try{if(!ae(f).isDirectory())throw new w({error:"cwd_not_a_directory",message:`cwd is not a directory: ${f}`,received:o,field:"cwd",next:"Send an existing absolute directory."})}catch(u){throw u instanceof w?u:new w({error:"cwd_missing",message:`cwd does not exist: ${f}`,received:o,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."})}return await K(async()=>{await T(t,{cwd:f}),await fn(t)}),await A(e,t,["cwd"]),{status:200,body:await v(t)}}let a=await h(t);const c=i.listen===void 0?void 0:Mi(i.listen);if(i.scopes!==void 0){const o=Ie(i.scopes),l=a.grantee==="app:terminal"?await Gt(a):a.grant_id?await Mt(a.grant_id):null;if(!o.every(m=>E(a.scopes,m)&&l!==null&&E(l.resolved,m)))throw new w({error:"unknown_scope",message:"scopes may only narrow the node's current effective set",received:o,field:"scopes",next:"Send only scopes the node currently holds."});if(o.includes("crtr:act")&&!E(o,"crtr:llm"))throw new p(400,"invalid_scope","crtr:act requires crtr:llm");a=await T(t,{scopes:o})}if(i.situational_context!==void 0&&await Be(t,We(i.situational_context)),i.model!==void 0){const o=(await ge(a.cwd,a.profile_id??null,a.grantee??"app:terminal")).modelLadders,l=Vn(i.model,o),m=await xt(a.grant_id,i.model,l===void 0),f=m?{family:Bt,strength:m.strength}:l,u=m?m.model:Kn(i.model,o);await V({kind:"concrete",spec:u},{cwd:a.cwd,profileId:a.profile_id??null},n.modelRegistry);const _=M();let I=!1;if(await _.isClaimed(t)&&((await X(t))?.runner==="machine"||await be(t,_.get(t)?.handle.exited))&&(I=await Hn(t,u,f,await Yn(t)).then(()=>!0,k=>{if(k instanceof Qn)return!1;throw k})),!I){if(await _.isClaimed(t)){const k=`${t}'s broker did not accept the model switch; the model was not changed`;throw new p(409,"broker_not_ready",k,{error:"broker_not_ready",message:k,received:i.model,field:"model",next:"Check the node with `crtr node inspect show`, then retry the model change."})}if(!u.includes("/"))throw y(`model must resolve to a provider/id spec: ${i.model}`);await zn(t,u,f)}a=await h(t)}if(i.kind!==void 0||i.mode!==void 0||i.lifecycle!==void 0){i.kind!==void 0&&await Me(i.kind,a.grantee??"app:terminal");const o=i.kind??a.kind,l=i.mode??a.mode,m=i.lifecycle??a.lifecycle;let f;l==="orchestrator"&&!await Bn(t)&&(f=d(async()=>{const u=await Fn(t);await xn(t,u!==null&&u.trim()!==""?{goal:u.trim()}:{})},"beforePersist")),a=await z(t,{...i.kind!==void 0?{kind:o}:{},...i.mode!==void 0?{mode:l}:{},...i.lifecycle!==void 0?{lifecycle:m}:{}},f)}i.name!==void 0&&(a=await T(t,{name:i.name}),a.window&&Wn(a.window,dt(a)));const s=["scopes","situational_context","model","kind","mode","lifecycle","name","listen"].filter(o=>i[o]!==void 0);return await A(e,t,s,c===void 0?void 0:async o=>{await o.prepare("UPDATE objects SET listen_json = ? WHERE id = ? AND type = 'node'").run(c,t)}),{status:200,body:await v(t)}}d(ji,"handleConfig");async function Le(e="app:terminal"){return(await ge(process.cwd(),Ge()||null,e)).kinds}d(Le,"daemonKinds");async function Me(e,n="app:terminal"){const t=Object.keys(await Le(n));if(!t.includes(e))throw y(`unknown kind: ${e}`,{received:e,next:`Valid kinds: ${t.sort().join(", ")}.`})}d(Me,"assertKindServer");async function Fi(){const e=await Le();return{status:200,body:{kinds:Object.keys(e).sort().map(t=>({kind:t,when_to_use:e[t]?.whenToUse??null,available_to:e[t]?.availableTo??null}))}}}d(Fi,"handleListKinds");const ko=[{method:"POST",pattern:"/v1/nodes",scope:"crtr:act",handler:oi},{method:"GET",pattern:"/v1/nodes",handler:ci},{method:"GET",pattern:"/v1/kinds",handler:d(()=>Fi(),"handler")},{method:"POST",pattern:"/v1/nodes/revive-all",scope:"crtr:act",handler:Di},{method:"GET",pattern:"/v1/nodes/:id",handler:ui},{method:"GET",pattern:"/v1/nodes/:id/snapshot",handler:fi},{method:"GET",pattern:"/v1/nodes/:id/subject",handler:pi},{method:"GET",pattern:"/v1/nodes/:id/messages",handler:wi},{method:"GET",pattern:"/v1/nodes/:id/session",handler:hi},{method:"GET",pattern:"/v1/nodes/:id/transcript",handler:yi},{method:"GET",pattern:"/v1/nodes/:id/context",handler:_i},{method:"POST",pattern:"/v1/nodes/:id/fork",scope:"crtr:act",handler:bi},{method:"POST",pattern:"/v1/nodes/:id/revive",scope:"crtr:act",handler:Si},{method:"POST",pattern:"/v1/nodes/:id/kick",scope:"crtr:act",handler:ki},{method:"POST",pattern:"/v1/nodes/:id/relaunch-root",scope:"crtr:act",handler:Ii},{method:"POST",pattern:"/v1/nodes/:id/close",handler:Ri},{method:"POST",pattern:"/v1/nodes/:id/read",handler:Ei},{method:"POST",pattern:"/v1/nodes/:id/recycle",scope:"crtr:act",handler:Oi},{method:"POST",pattern:"/v1/nodes/:id/demote",scope:"crtr:act",handler:Ci},{method:"POST",pattern:"/v1/nodes/:id/promote",scope:"crtr:act",handler:Ai},{method:"POST",pattern:"/v1/nodes/:id/yield",scope:"crtr:act",handler:Ni},{method:"GET",pattern:"/v1/nodes/:id/broker/structured-request",handler:$i},{method:"POST",pattern:"/v1/nodes/:id/broker/goal",handler:Ti},{method:"POST",pattern:"/v1/nodes/:id/wait",handler:Pi},{method:"PATCH",pattern:"/v1/nodes/:id/config",handler:ji}];export{ji as handleConfig,oi as handleCreate,bi as handleFork,ci as handleList,Ai as handlePromote,Ni as handleYield,ko as nodeRoutes,Ro as resolveCreateKind};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var j=Object.defineProperty;var _=(i,e)=>j(i,"name",{value:e,configurable:!0});import{existsSync as J}from"node:fs";import{LAUNCHER_SOCKET as Q}from"../../launcher/spec.js";import{launcherRequest as X}from"../../launcher/client.js";import{execFile as Z}from"node:child_process";import{promisify as ee}from"node:util";import{getNode as S,isWarmSpare as te,subscribersOf as ne}from"../../core/canvas/index.js";import{isSafeNodeId as c}from"../../core/canvas/paths.js";import{fullName as $}from"../../core/canvas/labels.js";import{recordedPidLiveness as B}from"../../core/canvas/pid.js";import{transition as re}from"../../core/runtime/lifecycle.js";import{hasAdmittedTurn as ae,listUnnotifiedFatalFaultNodes as ie,markFaultNotified as oe,readFault as L,readLiveTurn as F,recordFault as se}from"../../core/canvas/recovery.js";import{errorClassFromFault as de}from"../../core/fault-classifier.js";import{nextFaultRetry as le}from"../../core/runtime/fault-recovery.js";import{publishNotice as W}from"../../core/runtime/close.js";import{openDb as x,withCanvasWrite as ce}from"../../core/canvas/db.js";import{getById as ue}from"../../core/graph/objects.js";import{watcherIdsOf as fe}from"../../core/graph/watches.js";import{headlessBrokerHost as pe}from"../../core/runtime/host.js";import{endExecution as me,liveExecutionForNode as N,requestExecutionStop as _e}from"../../core/canvas/executions.js";import{runnerForExecution as he}from"../../core/runtime/runner/index.js";import{emitEvent as f}from"../../core/events/emit.js";import{operationIdContext as D}from"../../core/events/operation-id.js";import{hasUnseenWakeMail as we,resetStaleExecutionMail as ke}from"../../core/canvas/deliveries.js";import{runningJobs as ge}from"../../core/graph/jobs.js";import{focusOf as ve}from"../../core/runtime/placement.js";import{hasAttachedBrokerViewers as ye}from"../api/viewer-presence.js";import{deliverLive as be}from"../../core/runtime/interactive-deliver.js";import{BrokerUnreachableError as Se}from"../../core/runtime/broker-request.js";import{formatCard as Te,PARK_SUMMARY_PROMPT as Ae}from"../../shared/generated-context.js";import{brokerThresholdsForDaemon as Ie}from"../../core/runtime/fleet.js";import{readConfig as Re}from"../../core/config.js";import{beginPendingPark as Me,clearSupervisionMark as h,consumePendingPark as T,pendingParkIds as Pe,pendingParkStartedAt as Ee,readSupervisionMark as A,writeSupervisionMark as I}from"../park-pending.js";import{shouldParkAfterSummary as $e}from"../park-activity.js";import{applyParkEvent as R,noticeUnfinishedIdle as Fe,parkVerdict as xe}from"./live-obligation.js";import{readGoal as Ne}from"../../core/runtime/kickoff.js";import{memoryDeniedRecently as De}from"../../core/runtime/memory-admission.js";import{envNoDaemonAutostart as Oe,envTestUnattendedParkMs as Ce,parkSummaryGraceMs as Be,envUnattendedParkMs as Le}from"../../shared/env.js";import{KILL_ESCALATE_MS as G,sampleBrokerTree as We,wedgeVerdict as Ge,WEDGE_QUIET_MS as O,YIELD_STALL_GRACE_MS as U,yieldStallVerdict as q}from"../../core/runtime/broker-wedge.js";const C=ee(Z);async function Ue(i){return!await ae(i)&&((await Ne(i))?.trim()??"")!==""}_(Ue,"awaitsBirthTurn");async function Y(i){const e=await N(i);return e!==null&&e.runner!=="process"&&e.state==="running"?e:null}_(Y,"remoteExecutionOf");async function qe(i){return(await F(i))?.busy===!0}_(qe,"liveBusy");async function xt(i){const e=(await F(i))?.progressAt;if(e==null)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}_(xt,"liveTurnProgressMs");function V(i,e){return e===null?null:`${i}:${e}`}_(V,"incarnationOf");async function b(i){const e=await F(i.node_id),t=e?.busy===!0&&e.progressAt!==null?Date.parse(e.progressAt):Number.NaN,r=i.launched_at===null||i.launched_at===void 0?Number.NaN:Date.parse(i.launched_at);return!Number.isFinite(t)||!Number.isFinite(r)||t<r?null:t}_(b,"busySinceForIncarnation");const Ye=5*6e4;function Ve(i,e){return i===null||i.parent!=null?!1:i.lifecycle==="terminal"?!0:(e==="cap_exhausted"||e==="payment_refused"||e==="all_routes_exhausted")&&i.run_id===i.node_id}_(Ve,"settlesOnFatalProviderFault");function He(){const i=Le();if(i!==void 0)return i;const e=Re("user").lifecycle.unattendedParkMs;return Oe()?Ce()??e:e}_(He,"unattendedParkMsForDaemon");function H(){return Be()}_(H,"parkSummaryGraceMsForDaemon");function Ke(i,e,t,r,a){const n=`Child wedged \u2014 ${i} is alive and mid-turn but has shown NO engine progress for ${e}+ minutes and `;if(t)return n+"its process is near-idle. It will NOT recover on its own \u2014 read `crtr canvas read wedged-child-on-runaway-bash` and kill the runaway SUBPROCESS (not this node) so its turn can resume with no lost context.";const s="it has no subprocess to kill (the engine itself stalled). ";return r?n+s+"The daemon did not SIGTERM the broker because its PID identity cannot be confirmed alive.":a?n+s+"The daemon sent SIGTERM to the broker and will resume a cleanly aborted session with a continuation, or start a recovery cycle if the abort cannot settle.":n+s+"The daemon attempted SIGTERM to the broker, but the signal call failed."}_(Ke,"wedgeLabel");async function K(i,e){f({level:"error",event:"broker.wedge.detected",...c(i)?{node_id:i}:{},fields:{...c(i)?{}:{affected_node_id:i},pid:e.pid,quiet_ms:e.quietForMs,cpu_percent:e.cpuPercent,has_descendants:e.hasDescendants,kick_attempted:e.kickAttempted,kicked:e.kicked,...e.kickSuppressionReason===null?{}:{kick_suppression_reason:e.kickSuppressionReason}}});try{await se(i,{link:"daemon\u2192node",op:"engine wedge",kind:"wedged",retry:{disposition:"manual"},message:e.label})}catch(t){f({level:"error",event:"broker.wedge.fault_record_failed",...c(i)?{node_id:i}:{fields:{affected_node_id:i}},error:t})}await W(i,"notice.crash",e.label,{reason:"child-wedged",child:i,quiet_ms:e.quietForMs,cpu_percent:e.cpuPercent,kick_attempted:e.kickAttempted,kicked:e.kicked,...e.kickSuppressionReason===null?{}:{kick_suppression_reason:e.kickSuppressionReason}})}_(K,"reportWedge");class Nt{static{_(this,"BrokerSupervisionReconciler")}yieldTermedAt=new Map;sampleTree;signal;lastOverCapWarnAt=Number.NEGATIVE_INFINITY;constructor(e={}){this.sampleTree=e.readTreeSample??We,this.signal=e.signal??((t,r)=>{if(process.platform==="linux"&&J(Q)){if(r!=="SIGTERM"&&r!=="SIGKILL")throw new Error(`unsupported launcher signal ${r}`);return X({operation:"stop",pid:t,signal:r}).then(()=>{})}process.kill(t,r)})}async runFleetPreamble(e){return Ie()}warnIfSaturated(e){if(e.fleet.size()<e.thresholds.warning||!e.lifecycle.acceptsDetachedWork())return;const t=D.fresh(()=>this.warnOverCapInTmux(e.fleet.size(),e.thresholds,e.frozen));e.lifecycle.registerDetached(t)}async run(e,t){const r=He();for(const a of await ie())t.held.has(a)||await D.fresh(async()=>{try{await this.handleFatalFault(a)}catch(n){f({level:"error",event:"broker.supervision.failed",...c(a)?{node_id:a}:{fields:{affected_node_id:a}},error:n})}});for(const a of t.rows){const n=a.node_id,s=t.fleet.get(n),d=s===void 0?await Y(n):null;if(s===void 0&&d===null||a.status!=="active"&&a.status!=="idle"){await h(n,"unattended_since");continue}await D.fresh(async()=>{try{s!==void 0?(await this.handleYieldStall(a,s,t.fleet,e),await this.handleWedgeDetection(a,s,t.fleet,e)):d.runner==="blaxel"&&(await this.handleRemoteYieldStall(a,d,e),await this.handleRemoteWedge(a,d,e)),await this.handleUnattendedParking(n,await S(n),s?.pid??d.pid,d,e,t,r)}catch(l){await h(n,"unattended_since"),f({level:"error",event:"broker.supervision.failed",...c(n)?{node_id:n}:{fields:{affected_node_id:n}},error:l})}})}for(const a of await Pe())await t.fleet.has(a)||await T(a);await ke(e)}async parkResetCondition(e,t,r,a){if(t.pi_session_id==null||t.pi_pid!==r||t.status==="done"||t.status==="canceled"||t.status==="dead"||t.intent!==null||(await ge(await x(),e)).length>0||await ve(e)!==null||await ye(e))return!0;const n=await L(e);return n!==null&&n.retry.disposition==="auto"&&n.retry.by==="daemon"&&(n.kind==="connection"||n.kind==="rate-limit"||n.kind==="overloaded")&&(n.retry.nextAt!==void 0||le(n,a)!==null)?!0:await we(e)}async handleUnattendedParking(e,t,r,a,n,s,d){if(await te(e)){await h(e,"unattended_since"),await T(e);return}if(t===null){await h(e,"unattended_since"),await T(e);return}const l=await this.parkResetCondition(e,t,r,n),o=await Ee(e);if(o!==void 0){if(n-o<H())return;const v=await T(e);if(v===void 0||(await h(e,"unattended_since"),!await $e(e,t,v)))return;f({level:"warn",event:"broker.park.summary_expired",...c(e)?{node_id:e}:{},fields:{...c(e)?{}:{affected_node_id:e},grace_ms:H()}}),await R(e,"park"),this.teardownBroker(e,a);return}if(l||await qe(e)||await Ue(e)){await h(e,"unattended_since");return}const p=await A(e,"unattended_since");if(p===void 0){await I(e,"unattended_since",n);return}const{event:u,heldOnlyBySubscriber:w}=await xe(e,t.lifecycle),k=u!=="cancel"&&De(t.grantee??"app:terminal",n)?0:d;if(!(n-p<k)){if(await h(e,"unattended_since"),u==="release"){await R(e,u),w&&await Fe(e),this.teardownBroker(e,a);return}if(u==="cancel"){await R(e,u),this.teardownBroker(e,a);return}if(t.grantee!==void 0&&t.grantee!=="app:terminal"){await R(e,"park"),this.teardownBroker(e,a);return}s.lifecycle.acceptsDetachedWork()&&(await Me(e,n),s.lifecycle.registerDetached(this.requestParkSummary(e,a)))}}async requestParkSummary(e,t){try{const r=await be(e,Te("park",{},Ae),{origin:{type:"runtime",kind:"park"}});f({level:"info",event:"broker.park.summary_requested",...c(e)?{node_id:e}:{},fields:{...c(e)?{}:{affected_node_id:e},route:r}})}catch(r){if(await T(e)===void 0)return;if(r instanceof Se){await R(e,"park"),this.teardownBroker(e,t);return}f({level:"error",event:"broker.park.summary_failed",...c(e)?{node_id:e}:{fields:{affected_node_id:e}},error:r})}}async warnOverCapInTmux(e,t,r){const a=Date.now();if(a-this.lastOverCapWarnAt<Ye)return;this.lastOverCapWarnAt=a;const{warning:n,automaticReviveCap:s}=t,d=r.stalled+r.waitingOnMail;f({level:"warn",event:"broker.capacity.warning",fields:{live_count:e,warning_threshold:n,hard_cap:s,frozen_stalled:r.stalled,frozen_waiting_on_mail:r.waitingOnMail}});const l=d===0?"":` \u2014 ${d} frozen (${r.stalled} stalled, ${r.waitingOnMail} waiting on mail)`,o=`\u26A0 crtrd: ${e} live brokers (warning ${n}; hard cap ${s})${l} \u2014 possible broker leak. ps -ax | grep broker-cli.js`;try{const p=await C("tmux",["list-clients","-F","#{client_name}"],{encoding:"utf8",timeout:2e3});if(typeof p.stdout!="string")return;await Promise.allSettled(p.stdout.split(`
|
|
2
|
-
`).map(async u=>{if(u!=="")try{await C("tmux",["display-message","-C","-d","10000","-c",u,o],{encoding:"utf8",timeout:2e3})}catch{try{await C("tmux",["display-message","-c",u,o],{encoding:"utf8",timeout:2e3})}catch(w){f({level:"error",event:"broker.capacity.tmux_display_failed",error:w,fields:{client:u}})}}}))}catch(p){f({level:"error",event:"broker.capacity.tmux_list_clients_failed",error:p})}}async teardownBroker(e,t){return t===null?await
|
|
3
|
-
`)[0]??"").slice(0,200),o=r.providerError,p=o===void 0?"":` Provider: ${o.provider}/${o.model}.`+(o.status===void 0?"":` HTTP status: ${o.status}.`)+(o.errno===void 0?"":` Errno: ${o.errno}.`)+(o.code===void 0?"":` Code: ${o.code}.`)+(o.body===void 0?"":` Body: ${o.body.slice(0,200)}.`)+(
|
|
1
|
+
var j=Object.defineProperty;var _=(i,e)=>j(i,"name",{value:e,configurable:!0});import{existsSync as J}from"node:fs";import{LAUNCHER_SOCKET as Q}from"../../launcher/spec.js";import{launcherRequest as X}from"../../launcher/client.js";import{execFile as Z}from"node:child_process";import{promisify as ee}from"node:util";import{getNode as S,isWarmSpare as te,subscribersOf as ne}from"../../core/canvas/index.js";import{isSafeNodeId as c}from"../../core/canvas/paths.js";import{fullName as x}from"../../core/canvas/labels.js";import{recordedPidLiveness as B}from"../../core/canvas/pid.js";import{transition as re}from"../../core/runtime/lifecycle.js";import{hasAdmittedTurn as ae,listUnnotifiedFatalFaultNodes as ie,markFaultNotified as oe,readFault as L,readLiveTurn as F,recordFault as se}from"../../core/canvas/recovery.js";import{errorClassFromFault as de}from"../../core/fault-classifier.js";import{describeVendorLimit as le}from"../../core/provider-failure.js";import{nextFaultRetry as ce}from"../../core/runtime/fault-recovery.js";import{publishNotice as W}from"../../core/runtime/close.js";import{openDb as $,withCanvasWrite as ue}from"../../core/canvas/db.js";import{getById as fe}from"../../core/graph/objects.js";import{watcherIdsOf as pe}from"../../core/graph/watches.js";import{headlessBrokerHost as me}from"../../core/runtime/host.js";import{endExecution as _e,liveExecutionForNode as N,requestExecutionStop as he}from"../../core/canvas/executions.js";import{runnerForExecution as we}from"../../core/runtime/runner/index.js";import{emitEvent as f}from"../../core/events/emit.js";import{operationIdContext as D}from"../../core/events/operation-id.js";import{hasUnseenWakeMail as ke,resetStaleExecutionMail as ge}from"../../core/canvas/deliveries.js";import{runningJobs as ve}from"../../core/graph/jobs.js";import{focusOf as ye}from"../../core/runtime/placement.js";import{hasAttachedBrokerViewers as be}from"../api/viewer-presence.js";import{deliverLive as Se}from"../../core/runtime/interactive-deliver.js";import{BrokerUnreachableError as Ae}from"../../core/runtime/broker-request.js";import{formatCard as Te,PARK_SUMMARY_PROMPT as Ie}from"../../shared/generated-context.js";import{brokerThresholdsForDaemon as Me}from"../../core/runtime/fleet.js";import{readConfig as Pe}from"../../core/config.js";import{beginPendingPark as Re,clearSupervisionMark as h,consumePendingPark as A,pendingParkIds as Ee,pendingParkStartedAt as xe,readSupervisionMark as T,writeSupervisionMark as I}from"../park-pending.js";import{shouldParkAfterSummary as Fe}from"../park-activity.js";import{applyParkEvent as M,noticeUnfinishedIdle as $e,parkVerdict as Ne}from"./live-obligation.js";import{readGoal as De}from"../../core/runtime/kickoff.js";import{memoryDeniedRecently as Oe}from"../../core/runtime/memory-admission.js";import{envNoDaemonAutostart as Ce,envTestUnattendedParkMs as Be,parkSummaryGraceMs as Le,envUnattendedParkMs as We}from"../../shared/env.js";import{KILL_ESCALATE_MS as G,sampleBrokerTree as Ge,wedgeVerdict as Ue,WEDGE_QUIET_MS as O,YIELD_STALL_GRACE_MS as U,yieldStallVerdict as q}from"../../core/runtime/broker-wedge.js";const C=ee(Z);async function qe(i){return!await ae(i)&&((await De(i))?.trim()??"")!==""}_(qe,"awaitsBirthTurn");async function Y(i){const e=await N(i);return e!==null&&e.runner!=="process"&&e.state==="running"?e:null}_(Y,"remoteExecutionOf");async function Ye(i){return(await F(i))?.busy===!0}_(Ye,"liveBusy");async function Dt(i){const e=(await F(i))?.progressAt;if(e==null)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}_(Dt,"liveTurnProgressMs");function V(i,e){return e===null?null:`${i}:${e}`}_(V,"incarnationOf");async function b(i){const e=await F(i.node_id),t=e?.busy===!0&&e.progressAt!==null?Date.parse(e.progressAt):Number.NaN,r=i.launched_at===null||i.launched_at===void 0?Number.NaN:Date.parse(i.launched_at);return!Number.isFinite(t)||!Number.isFinite(r)||t<r?null:t}_(b,"busySinceForIncarnation");const Ve=5*6e4;function He(i,e){return i===null||i.parent!=null?!1:i.lifecycle==="terminal"?!0:(e==="cap_exhausted"||e==="payment_refused"||e==="all_routes_exhausted")&&i.run_id===i.node_id}_(He,"settlesOnFatalProviderFault");function Ke(){const i=We();if(i!==void 0)return i;const e=Pe("user").lifecycle.unattendedParkMs;return Ce()?Be()??e:e}_(Ke,"unattendedParkMsForDaemon");function H(){return Le()}_(H,"parkSummaryGraceMsForDaemon");function ze(i,e,t,r,a){const n=`Child wedged \u2014 ${i} is alive and mid-turn but has shown NO engine progress for ${e}+ minutes and `;if(t)return n+"its process is near-idle. It will NOT recover on its own \u2014 read `crtr canvas read wedged-child-on-runaway-bash` and kill the runaway SUBPROCESS (not this node) so its turn can resume with no lost context.";const s="it has no subprocess to kill (the engine itself stalled). ";return r?n+s+"The daemon did not SIGTERM the broker because its PID identity cannot be confirmed alive.":a?n+s+"The daemon sent SIGTERM to the broker and will resume a cleanly aborted session with a continuation, or start a recovery cycle if the abort cannot settle.":n+s+"The daemon attempted SIGTERM to the broker, but the signal call failed."}_(ze,"wedgeLabel");async function K(i,e){f({level:"error",event:"broker.wedge.detected",...c(i)?{node_id:i}:{},fields:{...c(i)?{}:{affected_node_id:i},pid:e.pid,quiet_ms:e.quietForMs,cpu_percent:e.cpuPercent,has_descendants:e.hasDescendants,kick_attempted:e.kickAttempted,kicked:e.kicked,...e.kickSuppressionReason===null?{}:{kick_suppression_reason:e.kickSuppressionReason}}});try{await se(i,{link:"daemon\u2192node",op:"engine wedge",kind:"wedged",retry:{disposition:"manual"},message:e.label})}catch(t){f({level:"error",event:"broker.wedge.fault_record_failed",...c(i)?{node_id:i}:{fields:{affected_node_id:i}},error:t})}await W(i,"notice.crash",e.label,{reason:"child-wedged",child:i,quiet_ms:e.quietForMs,cpu_percent:e.cpuPercent,kick_attempted:e.kickAttempted,kicked:e.kicked,...e.kickSuppressionReason===null?{}:{kick_suppression_reason:e.kickSuppressionReason}})}_(K,"reportWedge");class Ot{static{_(this,"BrokerSupervisionReconciler")}yieldTermedAt=new Map;sampleTree;signal;lastOverCapWarnAt=Number.NEGATIVE_INFINITY;constructor(e={}){this.sampleTree=e.readTreeSample??Ge,this.signal=e.signal??((t,r)=>{if(process.platform==="linux"&&J(Q)){if(r!=="SIGTERM"&&r!=="SIGKILL")throw new Error(`unsupported launcher signal ${r}`);return X({operation:"stop",pid:t,signal:r}).then(()=>{})}process.kill(t,r)})}async runFleetPreamble(e){return Me()}warnIfSaturated(e){if(e.fleet.size()<e.thresholds.warning||!e.lifecycle.acceptsDetachedWork())return;const t=D.fresh(()=>this.warnOverCapInTmux(e.fleet.size(),e.thresholds,e.frozen));e.lifecycle.registerDetached(t)}async run(e,t){const r=Ke();for(const a of await ie())t.held.has(a)||await D.fresh(async()=>{try{await this.handleFatalFault(a)}catch(n){f({level:"error",event:"broker.supervision.failed",...c(a)?{node_id:a}:{fields:{affected_node_id:a}},error:n})}});for(const a of t.rows){const n=a.node_id,s=t.fleet.get(n),d=s===void 0?await Y(n):null;if(s===void 0&&d===null||a.status!=="active"&&a.status!=="idle"){await h(n,"unattended_since");continue}await D.fresh(async()=>{try{s!==void 0?(await this.handleYieldStall(a,s,t.fleet,e),await this.handleWedgeDetection(a,s,t.fleet,e)):d.runner==="blaxel"&&(await this.handleRemoteYieldStall(a,d,e),await this.handleRemoteWedge(a,d,e)),await this.handleUnattendedParking(n,await S(n),s?.pid??d.pid,d,e,t,r)}catch(l){await h(n,"unattended_since"),f({level:"error",event:"broker.supervision.failed",...c(n)?{node_id:n}:{fields:{affected_node_id:n}},error:l})}})}for(const a of await Ee())await t.fleet.has(a)||await A(a);await ge(e)}async parkResetCondition(e,t,r,a){if(t.pi_session_id==null||t.pi_pid!==r||t.status==="done"||t.status==="canceled"||t.status==="dead"||t.intent!==null||(await ve(await $(),e)).length>0||await ye(e)!==null||await be(e))return!0;const n=await L(e);return n!==null&&n.retry.disposition==="auto"&&n.retry.by==="daemon"&&(n.kind==="connection"||n.kind==="rate-limit"||n.kind==="overloaded")&&(n.retry.nextAt!==void 0||ce(n,a)!==null)?!0:await ke(e)}async handleUnattendedParking(e,t,r,a,n,s,d){if(await te(e)){await h(e,"unattended_since"),await A(e);return}if(t===null){await h(e,"unattended_since"),await A(e);return}const l=await this.parkResetCondition(e,t,r,n),o=await xe(e);if(o!==void 0){if(n-o<H())return;const v=await A(e);if(v===void 0||(await h(e,"unattended_since"),!await Fe(e,t,v)))return;f({level:"warn",event:"broker.park.summary_expired",...c(e)?{node_id:e}:{},fields:{...c(e)?{}:{affected_node_id:e},grace_ms:H()}}),await M(e,"park"),this.teardownBroker(e,a);return}if(l||await Ye(e)||await qe(e)){await h(e,"unattended_since");return}const p=await T(e,"unattended_since");if(p===void 0){await I(e,"unattended_since",n);return}const{event:u,heldOnlyBySubscriber:w}=await Ne(e,t.lifecycle),k=u!=="cancel"&&Oe(t.grantee??"app:terminal",n)?0:d;if(!(n-p<k)){if(await h(e,"unattended_since"),u==="release"){await M(e,u),w&&await $e(e),this.teardownBroker(e,a);return}if(u==="cancel"){await M(e,u),this.teardownBroker(e,a);return}if(t.grantee!==void 0&&t.grantee!=="app:terminal"){await M(e,"park"),this.teardownBroker(e,a);return}s.lifecycle.acceptsDetachedWork()&&(await Re(e,n),s.lifecycle.registerDetached(this.requestParkSummary(e,a)))}}async requestParkSummary(e,t){try{const r=await Se(e,Te("park",{},Ie),{origin:{type:"runtime",kind:"park"}});f({level:"info",event:"broker.park.summary_requested",...c(e)?{node_id:e}:{},fields:{...c(e)?{}:{affected_node_id:e},route:r}})}catch(r){if(await A(e)===void 0)return;if(r instanceof Ae){await M(e,"park"),this.teardownBroker(e,t);return}f({level:"error",event:"broker.park.summary_failed",...c(e)?{node_id:e}:{fields:{affected_node_id:e}},error:r})}}async warnOverCapInTmux(e,t,r){const a=Date.now();if(a-this.lastOverCapWarnAt<Ve)return;this.lastOverCapWarnAt=a;const{warning:n,automaticReviveCap:s}=t,d=r.stalled+r.waitingOnMail;f({level:"warn",event:"broker.capacity.warning",fields:{live_count:e,warning_threshold:n,hard_cap:s,frozen_stalled:r.stalled,frozen_waiting_on_mail:r.waitingOnMail}});const l=d===0?"":` \u2014 ${d} frozen (${r.stalled} stalled, ${r.waitingOnMail} waiting on mail)`,o=`\u26A0 crtrd: ${e} live brokers (warning ${n}; hard cap ${s})${l} \u2014 possible broker leak. ps -ax | grep broker-cli.js`;try{const p=await C("tmux",["list-clients","-F","#{client_name}"],{encoding:"utf8",timeout:2e3});if(typeof p.stdout!="string")return;await Promise.allSettled(p.stdout.split(`
|
|
2
|
+
`).map(async u=>{if(u!=="")try{await C("tmux",["display-message","-C","-d","10000","-c",u,o],{encoding:"utf8",timeout:2e3})}catch{try{await C("tmux",["display-message","-c",u,o],{encoding:"utf8",timeout:2e3})}catch(w){f({level:"error",event:"broker.capacity.tmux_display_failed",error:w,fields:{client:u}})}}}))}catch(p){f({level:"error",event:"broker.capacity.tmux_list_clients_failed",error:p})}}async teardownBroker(e,t){return t===null?await me.teardown(e):await this.stopRemote(t,"teardown")}async stopRemote(e,t){await he(e.nodeId,{afterTurn:!1,reason:t});const r=await we(e.runner).stop(e,{reason:t});return r.confirmed?await _e(e.executionId,{reason:t}):f({level:"error",event:"broker.teardown.unconfirmed",node_id:e.nodeId,error:r.error}),r}async handleRemoteYieldStall(e,t,r){const a=e.node_id;if(e.intent!=="refresh"&&e.cycle_pending!==!0||await b(e)!==null){await h(a,"stall_noticed_at");return}const n=await T(a,"stall_noticed_at");if(n===void 0){await I(a,"stall_noticed_at",r);return}q(!0,!1,r-n)==="kill"&&(await N(a))?.executionId===t.executionId&&(f({level:"warn",event:"broker.yield_stall.remote_stop",...c(a)?{node_id:a}:{},fields:{...c(a)?{}:{affected_node_id:a},execution_id:t.executionId,elapsed_ms:r-n,grace_ms:U}}),await this.stopRemote(t,"yield_stall"))}async handleRemoteWedge(e,t,r){const a=e.node_id,n=await b(e);if(n===null){await h(a,"wedge_noticed_at");return}const s=r-n;if(s<O)return;const d=await S(a);if(d===null||(await N(a))?.executionId!==t.executionId||await b(d)!==n||await T(a,"wedge_noticed_at")===n)return;await I(a,"wedge_noticed_at",n);const l=Math.round(s/6e4);await K(a,{quietForMs:s,cpuPercent:null,hasDescendants:null,kickAttempted:!1,kicked:!1,kickSuppressionReason:"remote_no_process_evidence",pid:t.pid,label:`Child wedged \u2014 ${x(d)} (${a}) runs in a sandbox and is mid-turn but has shown NO engine progress for ${l}+ minutes. The daemon cannot see its processes there, so it did not stop the broker; if it is not running a long command, interrupt or close it.`})}async handleYieldStall(e,t,r,a){const n=e.node_id,s=V(t.pid,e.pi_pid_identity);if(e.intent!=="refresh"&&e.cycle_pending!==!0||await b(e)!==null||s===null){await h(n,"stall_noticed_at"),s!==null&&this.yieldTermedAt.delete(s);return}const d=await T(n,"stall_noticed_at");if(d===void 0){await I(n,"stall_noticed_at",a);return}const l={since:d,termedAt:this.yieldTermedAt.get(s)};if(q(!0,!1,a-l.since)!=="kill")return;const o=await S(n);if(!(r.get(n)!==t||o?.pi_pid!==t.pid||o.pi_pid_identity!==e.pi_pid_identity||B(t.pid,e.pi_pid_identity)!=="alive"))if(l.termedAt===void 0){if(!await this.signalYieldStall(n,t.pid,"SIGTERM"))return;this.yieldTermedAt.set(s,a),l.termedAt=a,f({level:"warn",event:"broker.yield_stall.sigterm",...c(n)?{node_id:n}:{},fields:{...c(n)?{}:{affected_node_id:n},pid:t.pid,elapsed_ms:a-l.since,grace_ms:U}})}else a-l.termedAt>=G&&await this.signalYieldStall(n,t.pid,"SIGKILL")&&f({level:"warn",event:"broker.yield_stall.sigkill",...c(n)?{node_id:n}:{},fields:{...c(n)?{}:{affected_node_id:n},pid:t.pid,elapsed_ms:a-l.termedAt,grace_ms:G,stall_elapsed_ms:a-l.since}})}async signalYieldStall(e,t,r){try{return await this.signal(t,r),!0}catch(a){return f({level:"error",event:"broker.yield_stall.signal_failed",...c(e)?{node_id:e}:{},error:a,fields:{...c(e)?{}:{affected_node_id:e},pid:t,signal:r}}),!1}}async handleWedgeDetection(e,t,r,a){const n=e.node_id,s=V(t.pid,e.pi_pid_identity),d=await b(e);if(d===null||s===null){await h(n,"wedge_noticed_at");return}const l=a-d,o=l>=O?await this.sampleTree(t.pid):null,p=await S(n),u=p===null?null:await b(p);if(r.get(n)!==t||p===null||p.pi_pid!==t.pid||p.pi_pid_identity!==e.pi_pid_identity||u!==d)return;const w=o?.cpuPercent??null,k=o?.hasDescendants??null;if(Ue({busy:!0,quietForMs:l,cpuPercent:w,hasDescendants:k})!=="wedged"||await T(n,"wedge_noticed_at")===d)return;await I(n,"wedge_noticed_at",d);const v=x(p),E=Math.round((l??O)/6e4),g=k??!0,y=!g&&B(t.pid,e.pi_pid_identity)!=="alive"?"pid_identity_unproven":null;let P=!1,m=!1;if(!g&&y===null){P=!0;try{await this.signal(t.pid,"SIGTERM"),m=!0}catch(z){f({level:"error",event:"broker.wedge.signal_failed",...c(n)?{node_id:n}:{},error:z,fields:{...c(n)?{}:{affected_node_id:n},pid:t.pid,signal:"SIGTERM"}})}}const R=ze(`${v} (${n})`,E,g,y!==null,m);await K(n,{quietForMs:l,cpuPercent:w,hasDescendants:g,kickAttempted:P,kicked:m,kickSuppressionReason:y,pid:t.pid,label:R})}async handleFatalFault(e,t=!0){const r=await L(e);if(r===null||r.retry.disposition!=="fatal"||r.link!=="pi\u2192provider"||r.notifiedSince===r.since)return;const a=await S(e),n=await Y(e),s=a!==null?x(a):e,d=r.kind==="auth",l=(r.message.split(`
|
|
3
|
+
`)[0]??"").slice(0,200),o=r.providerError,p=o===void 0?"":` Provider: ${o.provider}/${o.model}.`+(o.status===void 0?"":` HTTP status: ${o.status}.`)+(o.errno===void 0?"":` Errno: ${o.errno}.`)+(o.code===void 0?"":` Code: ${o.code}.`)+(o.body===void 0?"":` Body: ${o.body.slice(0,200)}.`)+(r.retry.nextAt===void 0?"":` Next router probe: ${r.retry.nextAt}.`)+le(o),u=r.kind==="context-overflow",w=He(a,typeof o?.code=="string"?o.code:void 0),k=u||w,v=u?`exceeded its model context window and is now dead. Shrink the task or loaded context, or choose a larger-context model before spawning it again. Error: ${l}`:`got a non-retryable ${r.kind} error and will NOT recover on its own; `+(w?"its terminal run has failed. ":"it stays alive, and waking it clears the fault as soon as one turn completes \u2014 a wake that hits the same cause fails again. "+(d?"Its provider credential is dead \u2014 re-authenticate (`/login`, or re-auth crtr); it recovers on its next wake once the auth reloads. ":""))+`Error: ${l}.${p}`,E=u?"failed":"hit a fatal provider fault",g=new Set((await ne(e)).map(m=>m.node_id)),y=await pe(await $(),await fe(await $(),e)),P=[{relation:"Child",recipients:y.filter(m=>g.has(m))},{relation:"Watched node",recipients:y.filter(m=>!g.has(m))}];f({level:"error",event:"fault.fatal.fanout",...c(e)?{node_id:e}:{},fields:{...c(e)?{}:{affected_node_id:e},kind:r.kind,link:r.link,terminal_overflow:u,terminal_provider_fault:w}}),await ue(async()=>{for(const{relation:m,recipients:R}of P)R.length!==0&&await W(e,"notice.crash",`${m} ${E} \u2014 ${s} (${e}) ${v}`,{reason:u?"child-context-overflow":"child-fault-fatal",child:e,kind:r.kind,message:l,...o===void 0?{}:{provider_error:o}},"normal",null,R);await oe(r.faultId),t&&k&&await re(e,"crash",{reason:u?"context_overflow":o?.code==="cap_exhausted"?"cap_exhausted":"provider_fatal",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:r.message,fault_kind:r.kind,error_class:de(r).class,...typeof o?.code=="string"?{provider_code:o.code}:{},...o?.payment===void 0?{}:{payment:o.payment}}}})}),t&&k&&this.teardownBroker(e,n).then(m=>{m.confirmed||f({level:"error",event:"fault.fatal.teardown_failed",node_id:e,error:m.error??new Error("Broker teardown not confirmed")})},m=>f({level:"error",event:"fault.fatal.teardown_failed",node_id:e,error:m}))}}export{Ot as BrokerSupervisionReconciler,H as parkSummaryGraceMsForDaemon,K as reportWedge,He as settlesOnFatalProviderFault,Ke as unattendedParkMsForDaemon,ze as wedgeLabel};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.723",
|
|
4
4
|
"description": "crtr — agent runtime with memory, plugins, and marketplaces",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -158,8 +158,8 @@
|
|
|
158
158
|
},
|
|
159
159
|
"license": "UNLICENSED",
|
|
160
160
|
"dependencies": {
|
|
161
|
-
"@north-light/identity": "0.3.
|
|
162
|
-
"@north-light/plugin": "0.3.
|
|
161
|
+
"@north-light/identity": "0.3.723",
|
|
162
|
+
"@north-light/plugin": "0.3.723",
|
|
163
163
|
"@earendil-works/chord": "1.5.2",
|
|
164
164
|
"@earendil-works/pi-agent-core": "1.5.2",
|
|
165
165
|
"@earendil-works/pi-ai": "1.5.2",
|