@north-light/cli 0.3.721 → 0.3.722
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/dto/recovery.d.ts +2 -0
- package/dist/clients/attach/viewer.js +281 -281
- package/dist/commands/node/inspect.js +7 -7
- 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/llm/run.js +2 -2
- package/dist/core/managed-providers.d.ts +9 -1
- 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/core/canvas/schema-version.js +1 -1
- package/packages/crouter-api/dist/core/llm/run.js +13 -2
- 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,12 +1,12 @@
|
|
|
1
|
-
var P=Object.defineProperty;var h=(n,e)=>P(n,"name",{value:e,configurable:!0});import{defineBranch as
|
|
2
|
-
`),"leaf")},run:h(async n=>{const e=h(
|
|
3
|
-
`)};return(i.runner==="blaxel"||i.profile_id!==null&&await m.getProfileEnvironment(i.profile_id).then(()=>!0,t=>t instanceof
|
|
4
|
-
`));const
|
|
1
|
+
var P=Object.defineProperty;var h=(n,e)=>P(n,"name",{value:e,configurable:!0});import{defineBranch as A,defineLeaf as $}from"../../core/command.js";import{InputError as k}from"../../core/io.js";import{requireScope as I}from"../../core/errors.js";import{isPidAlive as L}from"../../core/canvas/pid.js";import{fullName as x}from"../../core/canvas/labels.js";import{fuzzyMatch as O}from"../../core/tui/fuzzy.js";import{nodeSnapshotLeaf as F}from"../node-snapshot.js";import{nodeTranscriptLeaf as C}from"../node-transcript.js";import{nodeContextLeaf as U}from"../node-context.js";import{ApiError as E}from"../../api/index.js";import{describeVendorLimit as D}from"../../core/provider-failure.js";import{cliClient as _,cliCanvasSource as S,rethrowAsCliError as w}from"../api-client.js";import{RemoteCanvasSource as q}from"../../core/canvas/remote-canvas-source.js";import{kindsStateBlock as z,profilesStateBlock as M,resolveProfileViaDaemon as B}from"../profile/daemon-profiles.js";import{focusViewer as V,nodeInPane as W}from"../surface/node/placement.js";const K=$({name:"list",description:"list nodes on the canvas",whenToUse:"you want a flat roster of the nodes on the canvas, sliced by displayed name, status, kind, mode, lifecycle, profile, cwd, and graph scope (--under a node, for that node plus its subscription descendants). The filters AND together. Use `node inspect show` instead to drill into one node and its spine neighbors, `canvas dashboard` for the tree shape, and `canvas attention` to find nodes blocked on the user",help:{name:"node inspect list",summary:"list nodes on the canvas, filtered by any combination of attribute slices and a graph-scope (--under) that AND together",params:[{kind:"flag",name:"status",type:"string",required:!1,constraint:"Filter status (comma-separated for several; accepted values: active, idle, done, dead, canceled). NOTE: `active` means the engine process is live (never closed), NOT that the node is generating right now \u2014 an active node is usually dormant between turns. To tell working-vs-idle, check the pi session-file mtime or CPU, not status."},{kind:"flag",name:"kind",type:"string",required:!1,constraint:"Filter by persona kind (comma-separated for several). The <kinds> list below names every top-level installable kind; a registered sub-kind filters too by exact path even though it is not listed."},{kind:"flag",name:"mode",type:"string",required:!1,constraint:"Filter by mode (comma-separated for several; accepted values: base, orchestrator)."},{kind:"flag",name:"lifecycle",type:"string",required:!1,constraint:"Filter by lifecycle (comma-separated for several; accepted values: terminal, resident)."},{kind:"flag",name:"profile",type:"string",required:!1,constraint:"Filter by profile. On the local canvas, accepts a profile id or manifest name from the <profiles> list below, or a close-enough name that resolves to the nearest profile. Against a remote canvas, pass the exact profile id carried by its node rows."},{kind:"flag",name:"name",type:"string",required:!1,constraint:"Filter by the displayed node label (handle plus generated description) with the canvas browser\u2019s case-insensitive fuzzy subsequence match."},{kind:"flag",name:"cwd",type:"string",required:!1,constraint:"Filter to nodes pinned to this exact cwd (absolute path). Roster is canvas-wide (all cwds) by default."},{kind:"flag",name:"under",type:"string",required:!1,constraint:'Graph scope: restrict to this node and its subscription descendants (the sub-DAG reachable downward \u2014 its reports, theirs, \u2026). This is "one initiative / my subtree". ANDs with every attribute filter above, narrowing any of them to this subtree.'},{kind:"flag",name:"canvas",type:"string",required:!1,constraint:"Read from the named remote canvas target (see `crtr canvas config list`) instead of the local canvas. Overrides `crtr canvas use`."}],output:[{name:"nodes",type:"object[]",required:!0,constraint:"Rows include {node_id, name, kind, mode, lifecycle, status, cwd, profile_id, parent, created}. `name` is the displayed node label searched by --name and shown in canvas views. `profile_id` is the stable profile-directory id (null only for historical no-profile nodes)."}],outputKind:"object",effects:["Read-only: lists nodes through the daemon API."]},helpState:{leaf:h(async()=>(await Promise.all([z(),M()])).join(`
|
|
2
|
+
`),"leaf")},run:h(async n=>{const e=h(c=>{const b=n[c];return b!==void 0&&b!==""?b.split(",").map(v=>v.trim()).filter(v=>v!==""):void 0},"csv"),o=e("status"),s=e("kind"),p=e("mode"),i=e("lifecycle"),m=n.profile,r=n.name,l=n.cwd,a=n.under,u=S({canvasName:n.canvas}),d=u instanceof q?m:m===void 0?void 0:(await B(m)).id,f=a!==void 0&&a!=="";if(f&&await u.getNode(a).catch(w)===null)throw new k({error:"not_found",message:`no node: ${a}`,next:"List nodes with `crtr node inspect list`, then pass a real id to --under."});return{nodes:(await u.listNodes({...o!==void 0?{status:o}:{},...f?{under:a}:{}}).catch(w)).filter(c=>!(s!==void 0&&!s.includes(c.kind)||p!==void 0&&!p.includes(c.mode)||i!==void 0&&!i.includes(c.lifecycle)||d!==void 0&&c.profile_id!==d||l!==void 0&&l!==""&&c.cwd!==l)).map(c=>({...c,name:x(c)})).filter(c=>r===void 0||r===""||O(r,c.name))}},"run")}),j=new WeakSet,T=new WeakSet;async function N(n,e){const o=await n.getNode(e.node_id).catch(w);return{node_id:e.node_id,name:o?x(o):"(missing)",kind:o?.kind??"?",status:o?o.intent?`${o.status}/${o.intent}`:o.status:"?",active:e.active}}h(N,"enrichNeighbor");const G=$({name:"show",description:"show a node + its spine neighbors and drill-in pointers",whenToUse:"you want one node in depth \u2014 the debugging entrypoint: a glanceable meta slice, named spine neighbors, a pending-cron count, and exact drill-in paths. Use `node inspect list` for the flat roster or `canvas dashboard` for the whole-tree shape",help:{name:"node inspect show",summary:"show a node in depth \u2014 meta slice, named neighbors, pending-cron count, and drill-in pointers",params:[{kind:"positional",name:"node",required:!0,constraint:"Node id."},{kind:"flag",name:"canvas",type:"string",required:!1,constraint:"Read from the named remote canvas target (see `crtr canvas config list`) instead of the local canvas. Overrides `crtr canvas use`."}],output:[{name:"node",type:"object",required:!0,constraint:"The full node meta (system prompt + every telemetry field). The render surfaces a glanceable slice; `--json` carries the complete dump."},{name:"fault",type:"object",required:!0,constraint:"The active runtime fault projection, or null: {link, kind, retry: {disposition}, since}."},{name:"reports",type:"object[]",required:!0,constraint:"Who this node subscribes to (its reports/down), each enriched with {node_id, name, kind, status, active} \u2014 these are typically its spawned children."},{name:"managers",type:"object[]",required:!0,constraint:"Who subscribes to this node (its managers/up), same enriched shape."},{name:"pending_crons",type:"number",required:!0,constraint:"How many pending crons were created by this node. Inspect with `crtr cron list`."},{name:"paths",type:"object",required:!0,constraint:"Resolved on-disk locations: {context_dir, session_file} \u2014 read these directly to debug. Reports are documents: `crtr canvas read <node>/reports/<name>`."},{name:"follow_up",type:"string",required:!0,constraint:"The concrete next commands to drill deeper."}],outputKind:"object",effects:["Read-only: reads the node, its edges, and pending crons through crtrd."],preview:{suppressOutput:!0}},run:h(async n=>{const e=n.node,o=n.canvas,s=S({canvasName:o});if(s instanceof q){const t=await s.rawShow(e);if(t===null)throw new k({error:"not_found",message:`no node: ${e}`,next:"List nodes with `crtr node inspect list --canvas <name>`."});const y={...t};return j.add(y),y}const p=await s.getNode(e).catch(t=>w(t,"List nodes with `crtr node inspect list`."));if(p===null)throw new k({error:"not_found",message:`no node: ${e}`,next:"List nodes with `crtr node inspect list`."});const i=p,m=_(),r=await Promise.all((await s.subscriptionsOf(e)).map(t=>N(s,t))),l=await Promise.all((await s.subscribersOf(e)).map(t=>N(s,t))),a=(await m.listCrons({created_by:e}).catch(w)).filter(t=>t.created_by===e).length,u={context_dir:i.paths.context_dir,...i.pi_session_file!==void 0?{session_file:i.pi_session_file}:{}},d=[];d.push(`List the documents it owns (reports, plans, notes): \`crtr canvas list --owner ${e}\`.`),d.push(`Browse its context dir (and its subscriptions') in nvim: \`crtr node inspect context ${e}\`.`),u.session_file&&d.push(`Read the raw conversation transcript: ${u.session_file}`),d.push(`On-disk context dir (ls/read directly): ${u.context_dir}`),a>0&&d.push(`It created ${a} pending cron(s): \`crtr cron list\`.`),r.length>0&&d.push(`Drill into a child/report: \`crtr node inspect show <node_id>\` (${r.map(t=>t.node_id).join(", ")}).`),d.push(`Full machine dump (system prompt + all telemetry): \`crtr --json node inspect show ${e}\`.`);const f={node:i,fault:i.fault??null,reports:r,managers:l,pending_crons:a,paths:u,follow_up:d.join(`
|
|
3
|
+
`)};return(i.runner==="blaxel"||i.profile_id!==null&&await m.getProfileEnvironment(i.profile_id).then(()=>!0,t=>t instanceof E&&(t.status===400||t.status===404)?!1:w(t)))&&T.add(f),f},"run"),render:h(n=>{const e=n.node,o=String(e.node_id),s=e.pi_pid,i=j.has(n)?"remote (liveness not checked locally)":e.runner==="machine"?"on a Mac (liveness not checked locally)":T.has(n)?"in a cloud sandbox (liveness not checked locally)":L(s)?"alive":"dead",m=e.intent?`/${String(e.intent)}`:"",r=n.fault,l=[];l.push(`# ${x(e)} (${o})`);const a=[`- kind/mode/lifecycle: ${e.kind} / ${e.mode} / ${e.lifecycle}`,`- status: ${e.status}${m}`,...r==null?[]:[`- fault: ${String(r.kind)} / ${String(r.retry?.disposition)} since ${String(r.since)}${r.retry?.nextAt===void 0?"":`. Next router probe: ${r.retry.nextAt}.`}${D(r.providerError)}`],`- broker pid: ${s??"(none)"} \u2014 ${i}`,`- cwd: ${e.cwd}`,`- host: ${e.host_kind}`+(e.profile_id?` \xB7 profile ${e.profile_id}`:""),`- cycles: ${e.cycles} \xB7 created ${e.created}`],u=e.machine;u&&a.push(`- machine: ${u.name??u.id}`),e.parent&&a.push(`- parent: ${e.parent}`),a.push(`- creator: ${e.creator??"an external process"}`),e.waiting_for&&a.push(`- waiting for message: ${e.waiting_for}`),l.push(a.join(`
|
|
4
|
+
`));const d=h((f,g)=>{if(g.length===0)return`${f}: none`;const t=["node_id","name","kind","status","active"],y=`| ${t.join(" | ")} |`,c=`| ${t.map(()=>"---").join(" | ")} |`,b=g.map(v=>`| ${t.map(R=>String(v[R]??"").replace(/\|/g,"\\|").replace(/\n/g," ")).join(" | ")} |`).join(`
|
|
5
5
|
`);return`${g.length} ${f}:
|
|
6
6
|
|
|
7
7
|
${y}
|
|
8
|
-
${
|
|
9
|
-
${b}`},"table");return l.push(
|
|
8
|
+
${c}
|
|
9
|
+
${b}`},"table");return l.push(d("reports (down \u2014 subscriptions, usually children)",n.reports)),l.push(d("managers (up \u2014 subscribers)",n.managers)),l.push(`${n.pending_crons} pending cron(s)`),l.push(`Drill deeper:
|
|
10
10
|
${String(n.follow_up)}`),l.join(`
|
|
11
11
|
|
|
12
|
-
`)},"render")}),
|
|
12
|
+
`)},"render")}),le=$({name:"fork",description:"fork a node into an independent idle root with the same conversation and durable context",whenToUse:"a conversation has already accumulated the context you want, and you want a new user-driven branch beside it without sending a prompt or inheriting any graph-management responsibility. This copies the conversation and durable context, then waits for the fork\u2019s first real user message to supply its mandate. Use `node new --fork-from` instead when spawning a managed worker with an immediate task",help:{name:"node fork",summary:"create an independent resident root from a node\u2019s conversation and durable context, with no kickoff prompt or model turn",params:[{kind:"flag",name:"node",type:"string",required:!1,constraint:"Source node id. Mutually exclusive with --pane; one of them is required."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the source node. Mutually exclusive with --node; one of them is required. The prefix menu passes this for you and the new viewer splits beside this pane."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The new independent root id."},{name:"focused",type:"boolean",required:!0,constraint:"True when a new viewer pane opened beside the caller; false outside tmux."},{name:"session",type:"string",required:!1,constraint:"The tmux session containing the new viewer, when one opened."}],outputKind:"object",effects:["Creates a resident base-mode root with the source node\u2019s copied pi conversation, cwd, profile, kind, model override, and durable context files. Top-level initial-prompt.md, yield-message.md, result.json, and the jobs/ folder of background bash jobs are omitted.","Copies no parent, subscriptions, subscribers, children, crons, worktree, situational context, or lifecycle responsibility. Sends no prompt and consumes no model turn; the first real user message becomes the fork\u2019s mandate.","Inside tmux, opens and focuses a surface-attach viewer as an even-horizontal split in the source pane\u2019s window. Outside tmux, the root is still created but no interactive fallback opens."]},run:h(async n=>{I("crtr:act","crtr node fork");const e=n.pane,o=n.node;if(o!==void 0&&e!==void 0)throw new k({error:"conflicting_target",message:"--node and --pane are mutually exclusive",next:"Pass the source node id or its viewer pane, not both."});let s=o;if(s===void 0&&e!==void 0&&(s=W(e)),s===void 0||s==="")throw new k({error:"no_node",message:"no source node was provided or found in the pane",next:"Pass --node <id>, or --pane <pane-id> for a pane showing a node."});const p=await _().forkNode(s).catch(w),i=await V(p.node_id,{cwd:p.cwd,name:p.name,...e!==void 0?{pane:e}:{},newPane:!0});return{node_id:p.node_id,focused:i.focused,session:i.session}},"run"),render:h(n=>{const e=n.focused===!0?` Viewer opened beside the source${n.session?` in session ${n.session}`:""}.`:" No viewer opened because no tmux pane was available.";return`Forked independent idle root ${n.node_id}.${e} It will make no model call until its first real user message.`},"render")}),ue=A({name:"inspect",description:"read one node \u2014 its graph position, conversation, and context dir",whenToUse:"reading everything about ONE node you can name: enumerate the roster (`list`), inspect a node and its spine neighbors (`show`), or browse its on-disk context dir (`context`). The documents a node owns are `crtr canvas list --owner <id>`. Use `canvas dashboard` instead to render the whole tree SHAPE, or `canvas attention` to find which nodes are blocked on the user",help:{name:"node inspect",summary:"read one node (or the roster) \u2014 topology, conversation, and context dir",model:"Inspection is read-only and never revives a node. The roster is the selection surface; one-node metadata points to progressively heavier views: a parsed broker snapshot, rendered conversation, or context browser."},children:[K,G,F,C,U]});export{le as nodeFork,ue as nodeInspect};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
-- 032-model-cooldown-vendor-limit.sql — each cooldown keeps the vendor 429 observation that set it (NL-310): the reset the vendor named,
|
|
2
|
+
-- the window claim, safe rate-limit headers and the model, so a later refusal from a cooling pool still reports them. Added columns only.
|
|
3
|
+
ALTER TABLE model_accounts ADD COLUMN IF NOT EXISTS vendor_limit_json text;
|
|
4
|
+
ALTER TABLE model_account_cooldowns ADD COLUMN IF NOT EXISTS vendor_limit_json text;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/** The canvas schema version this build supports: the number of the highest delta in `schema-pg/` (the baseline
|
|
2
2
|
* `schema-pg.sql` is version 1). `scripts/install-runtime.mjs` reads this module from a candidate generation to refuse
|
|
3
3
|
* one below the live database's `schema_min_reader`. */
|
|
4
|
-
export declare const CANVAS_SCHEMA_VERSION =
|
|
4
|
+
export declare const CANVAS_SCHEMA_VERSION = 32;
|
|
5
5
|
/** The Postgres schema holding the canvas tables: `CRTR_DATABASE_SCHEMA` (`crtr` in the cloud deploy). Unset or empty
|
|
6
6
|
* means the role's own search_path (`public` on a Mac and on a VM). A name that is not a plain identifier is an error:
|
|
7
7
|
* it is put in a `search_path` connection option. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=
|
|
1
|
+
var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=32;function _(n=process.env){const e=n.CRTR_DATABASE_SCHEMA?.trim();if(e){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw new Error(`CRTR_DATABASE_SCHEMA must be a plain identifier (letters, digits, underscore); got ${JSON.stringify(e)}`);return e}}r(_,"canvasDatabaseSchema");function h(n=process.env){return n.CRTR_SCHEMA_DATABASE_URL?.trim()||void 0}r(h,"canvasSchemaDatabaseUrl");function E(n=process.env){const e=_(n);return e===void 0?void 0:`-c search_path=${e}`}r(E,"canvasSearchPathOptions");async function v(n,e){const t=e===void 0?"canvas_meta":`"${e.replace(/"/g,'""')}".canvas_meta`;if((await n.query(`SELECT to_regclass('${t.replace(/'/g,"''")}') IS NOT NULL AS found`)).rows[0].found!==!0)return;const u=(await n.query(`SELECT key, value FROM ${t} WHERE key IN ('schema_version', 'schema_min_reader')`)).rows,o=r(c=>{const i=u.find(f=>f.key===c);if(i===void 0)return;const d=Number(i.value);if(!Number.isSafeInteger(d))throw new Error(`canvas_meta.${c} is not an integer: ${String(i.value)}`);return d},"value"),s=o("schema_version");return s===void 0?void 0:{version:s,minReader:o("schema_min_reader")??s}}r(v,"readStoredVersions");async function l(n,e,t){const a=await v(n,t);if(a!==void 0&&a.minReader>e)throw new Error(`refusing to select runtime with canvas schema ${e}: the live database requires readers at version ${a.minReader} or above (it is at ${a.version}); install a descendant build instead`)}r(l,"assertCandidateMayOpen");export{A as CANVAS_SCHEMA_VERSION,l as assertCandidateMayOpen,_ as canvasDatabaseSchema,h as canvasSchemaDatabaseUrl,E as canvasSearchPathOptions,v as readStoredVersions};
|
package/dist/core/llm/run.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var Be=Object.defineProperty;var l=(e,t)=>Be(e,"name",{value:t,configurable:!0});import{randomUUID as Je}from"node:crypto";import{streamSimple as He}from"@earendil-works/pi-ai/compat";import{keyRouteProviders as ze,probeRouteAvailability as Xe}from"../model-routes-pool.js";import{KEY_CREDENTIAL_SOURCE as je,parseModelSpec as Ge}from"../model-routes.js";import{openModelRegistry as Ve}from"../runtime/model-registry.js";import{getProviderLabel as Ye,isInvalidRefreshTokenError as Ze}from"../managed-providers.js";import{MAX_RATE_LIMIT_COOLDOWN_MS as Me,coolingUntilFor as Se,isManagedProvider as N,markSubscriptionRateLimited as Qe,markSubscriptionSuccess as et,readSubscriptionPool as $e,retryAfterMsFromHeaders as
|
|
1
|
+
var Be=Object.defineProperty;var l=(e,t)=>Be(e,"name",{value:t,configurable:!0});import{randomUUID as Je}from"node:crypto";import{streamSimple as He}from"@earendil-works/pi-ai/compat";import{keyRouteProviders as ze,probeRouteAvailability as Xe}from"../model-routes-pool.js";import{KEY_CREDENTIAL_SOURCE as je,parseModelSpec as Ge}from"../model-routes.js";import{openModelRegistry as Ve}from"../runtime/model-registry.js";import{getProviderLabel as Ye,isInvalidRefreshTokenError as Ze}from"../managed-providers.js";import{MAX_RATE_LIMIT_COOLDOWN_MS as Me,coolingUntilFor as Se,isManagedProvider as N,markSubscriptionRateLimited as Qe,markSubscriptionSuccess as et,readSubscriptionPool as $e,retryAfterMsFromHeaders as ye,retryAfterMsFromError as tt,refreshSubscriptionCredential as nt,subscriptionNeedsSuccessWrite as ot,vendorRateLimit as rt,RefreshBusyError as it,RefreshTimeoutError as at}from"../subscription-state.js";import{describeRateLimitScope as Ce,modelCooldownFamily as st,rateLimitHeaders as dt}from"../rate-limit-scope.js";import{RunError as i}from"../runs/operations.js";import{recognizeProviderError as ge}from"../provider-error-recognition.js";import{isSafetyRefusal as lt}from"./refusal.js";import{findRefusal as ut,payerOf as Ee,refusalError as ct,refusedMark as ft,writeCharge as we}from"../ledger/index.js";import{storedApiKey as Ie}from"../auth-file.js";import{eligibleHostedEndpoint as mt,readHostedEndpoint as Oe}from"../grants/hosted-endpoint.js";import{parseProviderPayment as pt}from"../provider-failure.js";import{personIdAsync as ht}from"../canvas/person.js";import{getNode as De}from"../canvas/canvas.js";import{outboundToken as Ne}from"../providers/mint.js";import{discardFile as Fe}from"../providers/token-cache.js";import{ProviderError as _t}from"../providers/errors.js";import{appCandidates as yt}from"./app-rungs.js";import{hostedRoute as gt,matchesFeatures as wt,ownerCandidates as bt}from"./owner-candidates.js";function vt(e){return typeof e=="string"||e===null||Array.isArray(e)&&e.every(t=>t&&typeof t=="object"&&(t.type==="text"&&typeof t.text=="string"||t.type==="image_url"&&typeof t.image_url?.url=="string"&&/^data:image\/(png|jpeg|gif|webp);base64,[A-Za-z0-9+/]+={0,2}$/.test(t.image_url.url)))}l(vt,"validContent");function Le(e){return Array.isArray(e)?e.map(t=>{if(t.type==="text")return t;const[,o,s]=/^data:(image\/(?:png|jpeg|gif|webp));base64,(.*)$/.exec(t.image_url.url);return{type:"image",mimeType:o,data:s}}):e??""}l(Le,"imageContent");function kt(e,t){const o=(e instanceof Error?e.message:String(e)).split("; stack=",1)[0],s=ge({message:o}).kind;return s!=="connection"&&s!=="connection-only"?e:new i(503,"upstream_model_unavailable",o.slice(0,500),void 0,{served_model:t})}l(kt,"refreshFailure");async function xt(e,t,o,s,d){if(o.expires>Date.now())return o.access;const S=e.getProvider(t)?.auth.oauth;if(!S)throw new i(503,"upstream_model_unavailable",`no OAuth refresh for ${t}`,void 0,{served_model:s});return(await nt(t,o.label,async(r,_)=>{const w=await S.refresh({type:"oauth",refresh:r,access:"",expires:0,..._?{clientId:_}:{}},d??new AbortController().signal).catch(R=>{throw kt(R,s)}),x=w.clientId;return{refresh:w.refresh,access:w.access,expires:w.expires,...typeof x=="string"&&x?{clientId:x}:{}}}).catch(r=>{throw r instanceof it||r instanceof at?new i(503,"upstream_model_unavailable",r.message,void 0,{served_model:s}):r})).access}l(xt,"freshSubscriptionAccess");function nn(e){if(!e||typeof e!="object"||Array.isArray(e))throw new i(400,"invalid_request","body must be an object");const t=e;if(!Array.isArray(t.messages)||!t.messages.every(o=>o&&typeof o=="object"&&["system","user","assistant","tool"].includes(o.role)&&vt(o.content)))throw new i(400,"invalid_request","messages must be chat messages","messages");if(t.messages.some(o=>["system","assistant"].includes(o.role)&&typeof o.content!="string"&&o.content!==null))throw new i(400,"invalid_request","system and assistant content must be text","messages");if(t.model!==void 0&&typeof t.model!="string")throw new i(400,"invalid_request","model must be a string","model");if(t.model_policy!==void 0&&!["exact","substitute"].includes(t.model_policy))throw new i(400,"invalid_request","invalid model_policy","model_policy");if(t.payer!==void 0&&!["user","app"].includes(t.payer))throw new i(400,"invalid_request","invalid payer","payer");if(t.reasoning_effort!==void 0&&!["minimal","low","medium","high","xhigh","max"].includes(t.reasoning_effort))throw new i(400,"invalid_request","invalid reasoning_effort","reasoning_effort");if(t.stream!==void 0&&typeof t.stream!="boolean")throw new i(400,"invalid_request","stream must be boolean","stream");if(t.tools!==void 0&&(!Array.isArray(t.tools)||!t.tools.every(o=>o?.type==="function"&&typeof o.function?.name=="string"&&o.function.name.length>0&&(o.function.description===void 0||typeof o.function.description=="string")&&(o.function.parameters===void 0||o.function.parameters!==null&&typeof o.function.parameters=="object"&&!Array.isArray(o.function.parameters)&&o.function.parameters.type==="object"))))throw new i(400,"invalid_request","invalid tools","tools");if(t.tool_choice!==void 0&&t.tool_choice!=="auto"&&t.tool_choice!=="none"&&t.tool_choice!=="required"&&(typeof t.tool_choice!="object"||t.tool_choice===null||t.tool_choice.type!=="function"||typeof t.tool_choice.function?.name!="string"))throw new i(400,"invalid_request","invalid tool_choice","tool_choice");if(t.messages.some(o=>o.role==="assistant"&&o.tool_calls!==void 0&&(!Array.isArray(o.tool_calls)||!o.tool_calls.every(s=>s&&typeof s.id=="string"&&typeof s.function?.name=="string"&&typeof s.function.arguments=="string"&&Rt(s.function.arguments)))))throw new i(400,"invalid_request","invalid assistant tool_calls","messages");if(t.stop!==void 0&&!(typeof t.stop=="string"||Array.isArray(t.stop)&&t.stop.every(o=>typeof o=="string")))throw new i(400,"invalid_request","invalid stop","stop");if(t.seed!==void 0&&!Number.isSafeInteger(t.seed))throw new i(400,"invalid_request","invalid seed","seed");for(const[o,s]of[["temperature",t.temperature],["top_p",t.top_p],["max_tokens",t.max_tokens]])if(s!==void 0&&(typeof s!="number"||!Number.isFinite(s)||o==="temperature"&&(s<0||s>2)||o==="top_p"&&(s<0||s>1)||o==="max_tokens"&&(!Number.isSafeInteger(s)||s<1)))throw new i(400,"invalid_request",`invalid ${o}`,o);if(t.response_format!==void 0){const o=t.response_format;if(!o||typeof o!="object"||Array.isArray(o)||!["text","json_object","json_schema"].includes(o.type)||o.type==="json_schema"&&(typeof o.json_schema?.name!="string"||!o.json_schema.name||!o.json_schema.schema||typeof o.json_schema.schema!="object"||Array.isArray(o.json_schema.schema)))throw new i(400,"invalid_request","invalid response_format","response_format")}if(t.metadata!==void 0&&Buffer.byteLength(JSON.stringify(t.metadata)??"")>4096)throw new i(400,"invalid_request","metadata exceeds 4 KB","metadata");return t}l(nn,"parseLlmRequest");function Rt(e){try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)}catch{return!1}}l(Rt,"isJsonObject");function qt(e){const t=Date.now(),o=e.messages.map(r=>r.role==="system"?{role:"system",content:r.content??"",timestamp:t}:r.role==="tool"?{role:"toolResult",toolCallId:r.tool_call_id??"",toolName:"",content:typeof r.content=="string"||r.content===null?[{type:"text",text:r.content??""}]:Le(r.content),isError:!1,timestamp:t}:r.role==="assistant"?{role:"assistant",content:[...r.content?[{type:"text",text:r.content}]:[],...(r.tool_calls??[]).map(_=>({type:"toolCall",id:_.id,name:_.function.name,arguments:JSON.parse(_.function.arguments)}))],api:"openai-completions",provider:"openai",model:e.model??"",usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:t}:{role:"user",content:Le(r.content),timestamp:t}),s=o.findIndex(r=>r.role!=="system"),d=o.slice(0,s<0?o.length:s).map(r=>r.content),S=d.join(`
|
|
2
2
|
|
|
3
|
-
`),U=e.tools?.map(({function:r})=>({name:r.name,description:r.description??"",parameters:r.parameters??{type:"object",properties:{}}}));return{...M?{systemPrompt:M}:{},messages:o.slice(d.length),...U?{tools:U}:{}}}l(Rt,"contextOf");function qt(e){return mt(e?.payment)}l(qt,"paymentOf");function At(e,t){const o=e.find("anthropic",t);if(o)return o;const s=e.getAll().find(d=>d.provider==="anthropic"&&d.api==="anthropic-messages");return s?{...s,id:t,name:t}:void 0}l(At,"hostedModel");function jt(e,t){const{input:o,output:s,cacheRead:d,cacheWrite:M}=e.cost;return o===0&&s===0&&d===0&&M===0?null:Number.isFinite(t)&&t>=0?t:null}l(jt,"usdEquivalent");function Mt(e,t){return e.compat?.allowedFallbackModels?.find(s=>s.provider===e.provider&&s.model===t)}l(Mt,"allowedFallback");function nn(e){return e?{payer:e.payer??"user",sub:e.sub,grantee:e.grantee,inference_endpoint:e.inference_endpoint??null}:void 0}l(nn,"llmCallerOf");function Pe(e){return e instanceof ht?e.code==="server_error"?new i(503,"upstream_model_unavailable",e.message):new i(404,"model_unavailable",e.message):e}l(Pe,"mintFailure");const St=/\bmodel is not supported when using Codex with a ChatGPT account\b/i;function $t(e,t,o){if(!(e!=="openai-codex"||t===void 0||!St.test(t)))return new i(404,"model_unavailable",t,void 0,{served_model:o})}l($t,"codexAccountModelRejection");function Ct(e){return e.get("request-id")??e.get("x-request-id")}l(Ct,"vendorRequestId");async function on(e,t,o,s,d,M,U){const r=M?.payer==="app"?M:void 0;if(e.payer==="app"&&!r)throw new i(403,"payer_not_app","this grant is not app-paid");if(e.payer==="user"&&r)throw new i(400,"invalid_request","this grant is app-paid; payer cannot be user","payer");if(r&&!r.inference_endpoint)throw new i(404,"model_unavailable",`${r.grantee} is app-paid but its grant carries no inference endpoint`);const h=r?.inference_endpoint??void 0,g=d===void 0?null:r?.sub??d.sub??await pt(),x=await Ve();let R;h?(R=_t(h,e.model,e.model_policy==="exact").flatMap((_,w)=>{const S=Ge(_.model);return S?[{routeId:"app",credentialSource:"app",family:"app",strength:_.strength,...S,rank:w}]:[]}),R=R.filter(_=>gt(x,e,_))):R=await wt(x,e,s);const re=!h&&d!==void 0&&g!==null?await ft():null,ie=re===null?void 0:yt(e,R,re),Le=ie?re:null;ie&&(R=[...R,ie]);const Ke=h?new Set:ze(),we=l(async()=>new i(429,"all_routes_exhausted","no available way to pay for this call",void 0,{payment:{reason:"nothing_left",message:"No available way to pay for this call",pay_url:(await Oe())?.payment_setup_url??null,reset_at:null}}),"nothingLeft");if(R.length===0)throw e.model_policy==="exact"?new i(400,"substitution_refused","no eligible model route is configured"):h?new i(404,"model_unavailable","no eligible model route is configured"):await we();const W=`chatcmpl-${Je()}`;let D=1/0,z=1/0,ae,v,se,de;const X=new Set,le=l(async()=>U??(d?.node?(await Ne(d.node))?.caused_by??null:null)??(d?.run?(await Ne(d.run))?.caused_by??null:null),"causeOf");for(const _ of R){const w=_.credentialSource==="hosted";if(!r&&!w&&!(await Xe(_,x)).authenticated){if(_.credentialSource!==je&&N(_.providerId)){const k=await $e(_.providerId);k.length>0&&k.every($=>$.authFailure)&&X.add(_.providerId)}continue}const S=w?At(x,_.modelId):x.find(_.providerId,_.modelId);if(!S)continue;const B=w?Le.base_url:void 0,c=h?{...S,baseUrl:`${h.base_url}/${S.provider}`}:B?{...S,baseUrl:`${B}/anthropic`,compat:{...S.compat,allowedFallbackModels:void 0}}:S,p=_.providerId,G=_.credentialSource===je&&N(p),ue=!r&&!w&&!G&&N(p)?await $e(p):[],J=ue.filter(k=>!k.authFailure),be=J.filter(k=>Se(k,c.id)<=Date.now()),T=G?await Ie(p):Ke.has(p)?void 0:ue.length?await Ie(p):void 0;if(G&&T===void 0)continue;if(ue.length>0&&J.length===0&&T===void 0){N(p)&&X.add(p);continue}if(J.length&&!be.length&&T===void 0){const k=Math.min(...J.map($=>Se($,c.id)));k<D&&(D=k,se=`${c.provider}/${c.id}`);continue}const ve=r||w?[void 0,void 0]:G?["key"]:J.length||T!==void 0?[...be,...T!==void 0?["key"]:[]]:[void 0];let ke=!1;for(const[k,$]of ve.entries()){if(ke&&$!=="key")continue;const b=$==="key"?void 0:$,xe=$==="key",V=Date.now();let Re=b?.access;if(b&&b.expires<=Date.now()&&N(p))try{Re=await kt(x,p,b,`${c.provider}/${c.id}`,t)}catch(n){if(!Ze(n))throw n;ae??=n;continue}const Ue=Rt(e),F=b||r||w||xe?void 0:await x.getApiKeyAndHeaders(c);if(F&&!F.ok)continue;const u=`${c.provider}/${c.id}`,P=e.model??u,q=w?g===null?null:{payer:g,funding:"endpoint"}:r?Ee({call:"model",route:"endpoint",grantee:r.grantee}):g===null?null:Ee({call:"model",route:b?"subscription":"key",sub:g});if(d!==void 0&&q!==null){const n=await lt({scope:"call",payer:q.payer,funding:q.funding,sub:g,grantee:d.grantee,provider:p});if(n!==null){if(await ge({request:d.request??W,kind:"model",what:u,usd:null,payer:q.payer,funding:q.funding,sub:g,grantee:d.grantee,node:d.node??null,run:d.run??null,provider:p,causedBy:await le(),refused:ct(n)}),de??=n,$!=="key"&&ve.includes("key")){ke=!0;continue}break}}let I;if(r&&h)try{I=await De({audience:h.base_url,sub:r.sub,grantee:r.grantee,initiating_app:r.grantee,scope:["crtr:llm"]},{signal:t})}catch(n){throw Pe(n)}if(B)try{I=await De({audience:B,sub:g,grantee:d.grantee,initiating_app:d.grantee,scope:["crtr:llm"]},{signal:t})}catch(n){throw Pe(n)}let L=null,qe=!1,y,H,Y,C=!1,A,Z=null,j=3e4,K;const ce=[],fe=[],Q=[];let a,O;const ee=l((n,f=null)=>({id:W,object:"chat.completion.chunk",created:Math.floor(V/1e3),model:u,served_model:u,requested_model:P,substituted:P!==u&&!/^([^/]+)\/(ultra|strong|medium|light)$/.test(P),choices:[{index:0,delta:n,finish_reason:f}]}),"chunk"),te=l(n=>{ce.push(n),o?.(n)},"emit"),We=He(c,Ue,{apiKey:I?.access_token??Re??(xe?T:void 0)??(F?.ok?F.apiKey:void 0),...F?.ok?{headers:F.headers}:{},signal:t,reasoning:e.reasoning_effort??_.thinkingLevel,...e.temperature!==void 0?{temperature:e.temperature}:{},...e.max_tokens!==void 0?{maxTokens:e.max_tokens}:{},...e.top_p!==void 0?{samplingParams:{top_p:e.top_p}}:{},...e.tool_choice==="none"?{toolChoice:"none"}:{},onPayload:l(n=>{if(!n||typeof n!="object")return;const f=e.tool_choice,m=f==="required"?c.api==="anthropic-messages"?{type:"any"}:"required":typeof f=="object"&&f!==null?c.api==="anthropic-messages"?{type:"tool",name:f.function.name}:f:void 0;return{...n,...m?{tool_choice:m}:{},...e.stop!==void 0?{[c.api==="anthropic-messages"?"stop_sequences":"stop"]:typeof e.stop=="string"?[e.stop]:e.stop}:{},...e.seed!==void 0?{seed:e.seed}:{},...e.response_format!==void 0?{response_format:e.response_format}:{}}},"onPayload"),fetch:l(async(n,f)=>{const m=await fetch(n,f);if(A=m.status,Z=Ct(m.headers)??Z,w){if(L=m.headers.get("crtr-charge-id")?.trim()||null,m.ok&&!L)throw qe=!0,await m.body?.cancel(),new Error("The hosted endpoint omitted Crtr-Charge-Id; the call may already have been charged. Do not automatically replay it.");return m.status===402&&(Y=qt(await m.clone().json().catch(()=>{}))),m}return m.status===429&&(C=!0,K=m.headers,j=_e(m.headers)??15e3),m},"fetch"),onProviderStreamEvent:l(n=>{w&&n!==null&&typeof n=="object"&&"type"in n&&n.type==="message_stop"&&"crtr_charge"in n&&(y=n.crtr_charge)},"onProviderStreamEvent"),onResponse:l(n=>{!w&&n.status===429&&(C=!0,K=n.headers,j=_e(n.headers)??15e3)},"onResponse")});try{for await(const n of We)n.type==="text_delta"&&(fe.push(n.delta),te(ee({content:n.delta}))),n.type==="thinking_delta"&&(Q.push(n.delta),te(ee({reasoning_content:n.delta}))),n.type==="done"&&(a=n.message),n.type==="error"&&(a=n.error)}catch(n){const f=tt(n);K===void 0&&n&&typeof n=="object"&&"headers"in n&&Object.keys(st(n.headers)).length&&(K=n.headers);const m=ye({status:n&&typeof n=="object"&&"status"in n?n.status:void 0,message:n instanceof Error?n.message:String(n)});if(r||w)O=n;else{if(!C&&m.kind!=="rate-limit")throw ce.length?new i(503,"upstream_model_unavailable",n instanceof Error?n.message:String(n),void 0,{served_model:u}):n;C=!0,j=f??j}}if(w){if(qe)throw new i(502,"upstream_refused","The hosted endpoint omitted Crtr-Charge-Id; the call may already have been charged. Do not automatically replay it.",void 0,{served_model:u});if(A===402&&Y)throw new i(402,"payment_refused",Y.message,void 0,{payment:Y,served_model:u});if(A===401){if(I&&Te(I.key),k===0)continue;throw new i(404,"model_unavailable",`${B} refuses this runtime's tokens`,void 0,{served_model:u})}if(O!==void 0||A!==void 0&&A>=400||a?.stopReason==="error"||a?.stopReason==="aborted"){const f=O instanceof Error?O.message:a?.errorMessage??`the inference endpoint answered ${A??"with an error"}`;throw A===403?new i(502,"upstream_refused",f,void 0,{served_model:u}):new i(503,"upstream_model_unavailable",f,void 0,{served_model:u})}if(y===null||typeof y!="object"||!("id"in y)||y.id!==L||!("served_model"in y)||typeof y.served_model!="string"||!y.served_model.trim()||!("list_usd"in y)||typeof y.list_usd!="number"||!Number.isFinite(y.list_usd)||y.list_usd<0||Number(y.list_usd.toFixed(6))!==y.list_usd)throw new i(502,"upstream_refused","The hosted endpoint returned missing or invalid final charge accounting; output and cost may already exist. Do not automatically replay this call.",void 0,{served_model:u,charge_id:L});H={id:L,served_model:y.served_model,list_usd:y.list_usd}}if(r){if(A===401){if(I&&Te(I.key),k===0)continue;throw new i(404,"model_unavailable",`${h.base_url} refuses this runtime's tokens`,void 0,{served_model:u})}if(C&&_e(K)===void 0)throw new i(503,"upstream_model_unavailable",`${u} was rate-limited without a retry-after`,void 0,{served_model:u});if(!C&&(O!==void 0||A!==void 0&&A>=500))throw new i(503,"upstream_model_unavailable",O instanceof Error?O.message:a?.errorMessage??"inference endpoint failed",void 0,{served_model:u})}if(!C&&a?.stopReason==="error"&&ye({message:a.errorMessage}).kind==="rate-limit"&&(C=!0,j=15e3),C){const n=rt(K,c.id,j),{observation:f,vendorReset:m}=n;if(j=n.retryMs,v={provider:p,model:c.id,...b?{account:b.label}:{},observation:f},console.error(`[llm] 429 from ${u}${b?` account "${b.label}"`:""}: scope=${Ce(f.scope)} retry_after_ms=${j} headers=${JSON.stringify(f.headers)}`),b&&N(p)&&await Qe(p,b.label,j,V,Date.now(),f.scope),m!==void 0&&(z=Math.min(z,m)),Date.now()+Math.min(j,Me)<D&&(D=Date.now()+Math.min(j,Me),se=u),fe.length||Q.length)throw new i(503,"service_unavailable","vendor rate limit after output began",void 0,{served_model:u});if(r)break;continue}const ne=dt(a);if(A===400&&e.tool_choice!==void 0&&e.tool_choice!=="auto"&&e.tool_choice!=="none"&&/\btool[_ ]choice\b/i.test(a?.errorMessage??"")&&/not supported|does not support|unsupported|cannot|must be auto/i.test(a?.errorMessage??""))throw new i(400,"invalid_request",a.errorMessage,"tool_choice",{served_model:u});if(a?.stopReason==="error"){const n=$t(c.provider,a.errorMessage,u);if(n)throw n}if(!a||a.stopReason==="error"&&!ne||a.stopReason==="aborted")throw new i(503,"upstream_model_unavailable",a?.errorMessage??"model request failed",void 0,{served_model:u});b&&N(p)&&ot(b,c.id)&&await et(p,b.label,V,c.id);const me=a.content.filter(n=>n.type==="toolCall").map(n=>({id:n.id,type:"function",function:{name:n.name,arguments:JSON.stringify(n.arguments)}})),pe=ne?"content_filter":a.stopReason==="toolUse"?"tool_calls":a.stopReason==="length"?"length":"stop",he=a.responseModel?Mt(c,a.responseModel):void 0,E=H?`${c.provider}/${H.served_model}`:he?`${c.provider}/${he.model}`:u,oe={prompt_tokens:a.usage.input,completion_tokens:a.usage.output,total_tokens:a.usage.totalTokens,cache_read_tokens:a.usage.cacheRead,cache_write_tokens:a.usage.cacheWrite,usd_equivalent:H?H.list_usd:jt(he??c,a.usage.cost.total),served_model:E};w?d!==void 0&&q!==null&&await ge({id:L,request:d.request??W,kind:"model",what:E,units:{input:a.usage.input,output:a.usage.output,cache_read:a.usage.cacheRead,cache_write:a.usage.cacheWrite},usd:oe.usd_equivalent,payer:q.payer,funding:q.funding,sub:g,grantee:d.grantee,node:d.node??null,run:d.run??null,provider:p,causedBy:await le(),vendorRef:Z}):d!==void 0&&q!==null&&await ge({request:d.request??W,kind:"model",what:E,units:{input:a.usage.input,output:a.usage.output,cache_read:a.usage.cacheRead,cache_write:a.usage.cacheWrite},usd:oe.usd_equivalent,payer:q.payer,funding:q.funding,sub:g,grantee:d.grantee,node:d.node??null,run:d.run??null,provider:p,causedBy:await le(),vendorRef:Z});const Ae={id:W,object:"chat.completion",created:Math.floor(V/1e3),model:E,served_model:E,requested_model:P,substituted:P!==E&&!/^([^/]+)\/(ultra|strong|medium|light)$/.test(P),choices:[{index:0,message:{role:"assistant",content:fe.join("")||null,...Q.length?{reasoning_content:Q.join("")}:{},...me.length?{tool_calls:me}:{},...ne?{refusal:a.errorMessage??"Content filtered"}:{}},finish_reason:pe}],usage:oe,...e.metadata!==void 0?{metadata:e.metadata}:{}};for(const[n,f]of me.entries())te(ee({tool_calls:[{index:n,...f}]}));return te({...ee({},pe),model:E,served_model:E,substituted:Ae.substituted,...ne?{choices:[{index:0,delta:{},finish_reason:pe,message:{refusal:a.errorMessage??"Content filtered"}}]}:{},usage:oe}),{completion:Ae,chunks:ce}}}throw de!==void 0?ut(de):D!==1/0?new i(429,"all_routes_exhausted","all eligible model routes are rate-limited",void 0,{payment:{reason:"nothing_left",message:"Every connected subscription and key is rate-limited or used up right now.",pay_url:(await Oe())?.payment_setup_url??null,reset_at:z===1/0?null:new Date(z).toISOString()},retry_after_s:Math.max(1,Math.ceil((D-Date.now())/1e3)),served_model:v?`${v.provider}/${v.model}`:se,...v?{rate_limit:{provider:v.provider,model:v.model,...v.account?{account:v.account}:{},scope:Ce(v.observation.scope),...v.observation.claim?{claim:v.observation.claim}:{},headers:v.observation.headers}}:{}},void 0,!0):ae!==void 0?ae:e.model_policy==="exact"?new i(400,"substitution_refused",X.size>0?`your ${[...X].map(Ye).join(" and ")} sign-in has expired; sign in again`:"the requested model is unavailable"):h?new i(404,"model_unavailable","no usable model route is available"):await we()}l(on,"runLlm");export{kt as freshSubscriptionAccess,nn as llmCallerOf,tn as parseLlmRequest,on as runLlm,jt as usdEquivalent};
|
|
3
|
+
`),J=e.tools?.map(({function:r})=>({name:r.name,description:r.description??"",parameters:r.parameters??{type:"object",properties:{}}}));return{...S?{systemPrompt:S}:{},messages:o.slice(d.length),...J?{tools:J}:{}}}l(qt,"contextOf");function At(e){return pt(e?.payment)}l(At,"paymentOf");function jt(e,t){const o=e.find("anthropic",t);if(o)return o;const s=e.getAll().find(d=>d.provider==="anthropic"&&d.api==="anthropic-messages");return s?{...s,id:t,name:t}:void 0}l(jt,"hostedModel");function Mt(e,t){const{input:o,output:s,cacheRead:d,cacheWrite:S}=e.cost;return o===0&&s===0&&d===0&&S===0?null:Number.isFinite(t)&&t>=0?t:null}l(Mt,"usdEquivalent");function St(e,t){return e.compat?.allowedFallbackModels?.find(s=>s.provider===e.provider&&s.model===t)}l(St,"allowedFallback");function on(e){return e?{payer:e.payer??"user",sub:e.sub,grantee:e.grantee,inference_endpoint:e.inference_endpoint??null}:void 0}l(on,"llmCallerOf");function Te(e){return e instanceof _t?e.code==="server_error"?new i(503,"upstream_model_unavailable",e.message):new i(404,"model_unavailable",e.message):e}l(Te,"mintFailure");const $t=/\bmodel is not supported when using Codex with a ChatGPT account\b/i;function Ct(e,t,o){if(!(e!=="openai-codex"||t===void 0||!$t.test(t)))return new i(404,"model_unavailable",t,void 0,{served_model:o})}l(Ct,"codexAccountModelRejection");function Et(e){return e.get("request-id")??e.get("x-request-id")}l(Et,"vendorRequestId");async function rn(e,t,o,s,d,S,J){const r=S?.payer==="app"?S:void 0;if(e.payer==="app"&&!r)throw new i(403,"payer_not_app","this grant is not app-paid");if(e.payer==="user"&&r)throw new i(400,"invalid_request","this grant is app-paid; payer cannot be user","payer");if(r&&!r.inference_endpoint)throw new i(404,"model_unavailable",`${r.grantee} is app-paid but its grant carries no inference endpoint`);const _=r?.inference_endpoint??void 0,w=d===void 0?null:r?.sub??d.sub??await ht(),x=await Ve();let R;_?(R=yt(_,e.model,e.model_policy==="exact").flatMap((y,b)=>{const $=Ge(y.model);return $?[{routeId:"app",credentialSource:"app",family:"app",strength:y.strength,...$,rank:b}]:[]}),R=R.filter(y=>wt(x,e,y))):R=await bt(x,e,s);const ie=!_&&d!==void 0&&w!==null?await mt():null,ae=ie===null?void 0:gt(e,R,ie),Pe=ae?ie:null;ae&&(R=[...R,ae]);const Ue=_?new Set:ze(),be=l(async()=>new i(429,"all_routes_exhausted","no available way to pay for this call",void 0,{payment:{reason:"nothing_left",message:"No available way to pay for this call",pay_url:(await Oe())?.payment_setup_url??null,reset_at:null}}),"nothingLeft");if(R.length===0)throw e.model_policy==="exact"?new i(400,"substitution_refused","no eligible model route is configured"):_?new i(404,"model_unavailable","no eligible model route is configured"):await be();const H=`chatcmpl-${Je()}`;let F=1/0,L=1/0,se,v,de,le;const G=new Set,ue=l(async()=>J??(d?.node?(await De(d.node))?.caused_by??null:null)??(d?.run?(await De(d.run))?.caused_by??null:null),"causeOf");for(const y of R){const b=y.credentialSource==="hosted";if(!r&&!b&&!(await Xe(y,x)).authenticated){if(y.credentialSource!==je&&N(y.providerId)){const k=await $e(y.providerId);k.length>0&&k.every(q=>q.authFailure)&&G.add(y.providerId)}continue}const $=b?jt(x,y.modelId):x.find(y.providerId,y.modelId);if(!$)continue;const z=b?Pe.base_url:void 0,u=_?{...$,baseUrl:`${_.base_url}/${$.provider}`}:z?{...$,baseUrl:`${z}/anthropic`,compat:{...$.compat,allowedFallbackModels:void 0}}:$,h=y.providerId,V=y.credentialSource===je&&N(h),ce=!r&&!b&&!V&&N(h)?await $e(h):[],T=ce.filter(k=>!k.authFailure),ve=T.filter(k=>Se(k,u.id)<=Date.now()),P=V?await Ie(h):Ue.has(h)?void 0:ce.length?await Ie(h):void 0;if(V&&P===void 0)continue;if(ce.length>0&&T.length===0&&P===void 0){N(h)&&G.add(h);continue}if(T.length&&!ve.length&&P===void 0){const k=Math.min(...T.map(c=>Se(c,u.id)));k<F&&(F=k,de=`${u.provider}/${u.id}`);const q=st(u.id);for(const c of T){const C=q!==void 0&&(c.modelCooldowns?.[q]??0)>Date.now()?c.vendorLimits?.[q]:c.rateLimitedUntil>Date.now()?c.vendorLimits?.account:void 0;C!==void 0&&(C.vendorReset!==void 0&&C.vendorReset>Date.now()&&(L=Math.min(L,C.vendorReset)),v??={provider:h,model:C.model,account:c.label,observation:C.observation})}continue}const ke=r||b?[void 0,void 0]:V?["key"]:T.length||P!==void 0?[...ve,...P!==void 0?["key"]:[]]:[void 0];let xe=!1;for(const[k,q]of ke.entries()){if(xe&&q!=="key")continue;const c=q==="key"?void 0:q,C=q==="key",Y=Date.now();let Re=c?.access;if(c&&c.expires<=Date.now()&&N(h))try{Re=await xt(x,h,c,`${u.provider}/${u.id}`,t)}catch(n){if(!Ze(n))throw n;se??=n;continue}const Ke=qt(e),U=c||r||b||C?void 0:await x.getApiKeyAndHeaders(u);if(U&&!U.ok)continue;const f=`${u.provider}/${u.id}`,K=e.model??f,A=b?w===null?null:{payer:w,funding:"endpoint"}:r?Ee({call:"model",route:"endpoint",grantee:r.grantee}):w===null?null:Ee({call:"model",route:c?"subscription":"key",sub:w});if(d!==void 0&&A!==null){const n=await ut({scope:"call",payer:A.payer,funding:A.funding,sub:w,grantee:d.grantee,provider:h});if(n!==null){if(await we({request:d.request??H,kind:"model",what:f,usd:null,payer:A.payer,funding:A.funding,sub:w,grantee:d.grantee,node:d.node??null,run:d.run??null,provider:h,causedBy:await ue(),refused:ft(n)}),le??=n,q!=="key"&&ke.includes("key")){xe=!0;continue}break}}let O;if(r&&_)try{O=await Ne({audience:_.base_url,sub:r.sub,grantee:r.grantee,initiating_app:r.grantee,scope:["crtr:llm"]},{signal:t})}catch(n){throw Te(n)}if(z)try{O=await Ne({audience:z,sub:w,grantee:d.grantee,initiating_app:d.grantee,scope:["crtr:llm"]},{signal:t})}catch(n){throw Te(n)}let W=null,qe=!1,g,X,Z,E=!1,j,Q=null,M=3e4,B;const fe=[],me=[],ee=[];let a,D;const te=l((n,m=null)=>({id:H,object:"chat.completion.chunk",created:Math.floor(Y/1e3),model:f,served_model:f,requested_model:K,substituted:K!==f&&!/^([^/]+)\/(ultra|strong|medium|light)$/.test(K),choices:[{index:0,delta:n,finish_reason:m}]}),"chunk"),ne=l(n=>{fe.push(n),o?.(n)},"emit"),We=He(u,Ke,{apiKey:O?.access_token??Re??(C?P:void 0)??(U?.ok?U.apiKey:void 0),...U?.ok?{headers:U.headers}:{},signal:t,reasoning:e.reasoning_effort??y.thinkingLevel,...e.temperature!==void 0?{temperature:e.temperature}:{},...e.max_tokens!==void 0?{maxTokens:e.max_tokens}:{},...e.top_p!==void 0?{samplingParams:{top_p:e.top_p}}:{},...e.tool_choice==="none"?{toolChoice:"none"}:{},onPayload:l(n=>{if(!n||typeof n!="object")return;const m=e.tool_choice,p=m==="required"?u.api==="anthropic-messages"?{type:"any"}:"required":typeof m=="object"&&m!==null?u.api==="anthropic-messages"?{type:"tool",name:m.function.name}:m:void 0;return{...n,...p?{tool_choice:p}:{},...e.stop!==void 0?{[u.api==="anthropic-messages"?"stop_sequences":"stop"]:typeof e.stop=="string"?[e.stop]:e.stop}:{},...e.seed!==void 0?{seed:e.seed}:{},...e.response_format!==void 0?{response_format:e.response_format}:{}}},"onPayload"),fetch:l(async(n,m)=>{const p=await fetch(n,m);if(j=p.status,Q=Et(p.headers)??Q,b){if(W=p.headers.get("crtr-charge-id")?.trim()||null,p.ok&&!W)throw qe=!0,await p.body?.cancel(),new Error("The hosted endpoint omitted Crtr-Charge-Id; the call may already have been charged. Do not automatically replay it.");return p.status===402&&(Z=At(await p.clone().json().catch(()=>{}))),p}return p.status===429&&(E=!0,B=p.headers,M=ye(p.headers)??15e3),p},"fetch"),onProviderStreamEvent:l(n=>{b&&n!==null&&typeof n=="object"&&"type"in n&&n.type==="message_stop"&&"crtr_charge"in n&&(g=n.crtr_charge)},"onProviderStreamEvent"),onResponse:l(n=>{!b&&n.status===429&&(E=!0,B=n.headers,M=ye(n.headers)??15e3)},"onResponse")});try{for await(const n of We)n.type==="text_delta"&&(me.push(n.delta),ne(te({content:n.delta}))),n.type==="thinking_delta"&&(ee.push(n.delta),ne(te({reasoning_content:n.delta}))),n.type==="done"&&(a=n.message),n.type==="error"&&(a=n.error)}catch(n){const m=tt(n);B===void 0&&n&&typeof n=="object"&&"headers"in n&&Object.keys(dt(n.headers)).length&&(B=n.headers);const p=ge({status:n&&typeof n=="object"&&"status"in n?n.status:void 0,message:n instanceof Error?n.message:String(n)});if(r||b)D=n;else{if(!E&&p.kind!=="rate-limit")throw fe.length?new i(503,"upstream_model_unavailable",n instanceof Error?n.message:String(n),void 0,{served_model:f}):n;E=!0,M=m??M}}if(b){if(qe)throw new i(502,"upstream_refused","The hosted endpoint omitted Crtr-Charge-Id; the call may already have been charged. Do not automatically replay it.",void 0,{served_model:f});if(j===402&&Z)throw new i(402,"payment_refused",Z.message,void 0,{payment:Z,served_model:f});if(j===401){if(O&&Fe(O.key),k===0)continue;throw new i(404,"model_unavailable",`${z} refuses this runtime's tokens`,void 0,{served_model:f})}if(D!==void 0||j!==void 0&&j>=400||a?.stopReason==="error"||a?.stopReason==="aborted"){const m=D instanceof Error?D.message:a?.errorMessage??`the inference endpoint answered ${j??"with an error"}`;throw j===403?new i(502,"upstream_refused",m,void 0,{served_model:f}):new i(503,"upstream_model_unavailable",m,void 0,{served_model:f})}if(g===null||typeof g!="object"||!("id"in g)||g.id!==W||!("served_model"in g)||typeof g.served_model!="string"||!g.served_model.trim()||!("list_usd"in g)||typeof g.list_usd!="number"||!Number.isFinite(g.list_usd)||g.list_usd<0||Number(g.list_usd.toFixed(6))!==g.list_usd)throw new i(502,"upstream_refused","The hosted endpoint returned missing or invalid final charge accounting; output and cost may already exist. Do not automatically replay this call.",void 0,{served_model:f,charge_id:W});X={id:W,served_model:g.served_model,list_usd:g.list_usd}}if(r){if(j===401){if(O&&Fe(O.key),k===0)continue;throw new i(404,"model_unavailable",`${_.base_url} refuses this runtime's tokens`,void 0,{served_model:f})}if(E&&ye(B)===void 0)throw new i(503,"upstream_model_unavailable",`${f} was rate-limited without a retry-after`,void 0,{served_model:f});if(!E&&(D!==void 0||j!==void 0&&j>=500))throw new i(503,"upstream_model_unavailable",D instanceof Error?D.message:a?.errorMessage??"inference endpoint failed",void 0,{served_model:f})}if(!E&&a?.stopReason==="error"&&ge({message:a.errorMessage}).kind==="rate-limit"&&(E=!0,M=15e3),E){const n=rt(B,u.id,M),{observation:m,vendorReset:p}=n;if(M=n.retryMs,v={provider:h,model:u.id,...c?{account:c.label}:{},observation:m},console.error(`[llm] 429 from ${f}${c?` account "${c.label}"`:""}: scope=${Ce(m.scope)} retry_after_ms=${M} headers=${JSON.stringify(m.headers)}`),c&&N(h)&&await Qe(h,c.label,M,Y,Date.now(),m.scope,{model:u.id,...p!==void 0?{vendorReset:p}:{},observation:m}),p!==void 0&&(L=Math.min(L,p)),Date.now()+Math.min(M,Me)<F&&(F=Date.now()+Math.min(M,Me),de=f),me.length||ee.length)throw new i(503,"service_unavailable","vendor rate limit after output began",void 0,{served_model:f});if(r)break;continue}const oe=lt(a);if(j===400&&e.tool_choice!==void 0&&e.tool_choice!=="auto"&&e.tool_choice!=="none"&&/\btool[_ ]choice\b/i.test(a?.errorMessage??"")&&/not supported|does not support|unsupported|cannot|must be auto/i.test(a?.errorMessage??""))throw new i(400,"invalid_request",a.errorMessage,"tool_choice",{served_model:f});if(a?.stopReason==="error"){const n=Ct(u.provider,a.errorMessage,f);if(n)throw n}if(!a||a.stopReason==="error"&&!oe||a.stopReason==="aborted")throw new i(503,"upstream_model_unavailable",a?.errorMessage??"model request failed",void 0,{served_model:f});c&&N(h)&&ot(c,u.id)&&await et(h,c.label,Y,u.id);const pe=a.content.filter(n=>n.type==="toolCall").map(n=>({id:n.id,type:"function",function:{name:n.name,arguments:JSON.stringify(n.arguments)}})),he=oe?"content_filter":a.stopReason==="toolUse"?"tool_calls":a.stopReason==="length"?"length":"stop",_e=a.responseModel?St(u,a.responseModel):void 0,I=X?`${u.provider}/${X.served_model}`:_e?`${u.provider}/${_e.model}`:f,re={prompt_tokens:a.usage.input,completion_tokens:a.usage.output,total_tokens:a.usage.totalTokens,cache_read_tokens:a.usage.cacheRead,cache_write_tokens:a.usage.cacheWrite,usd_equivalent:X?X.list_usd:Mt(_e??u,a.usage.cost.total),served_model:I};b?d!==void 0&&A!==null&&await we({id:W,request:d.request??H,kind:"model",what:I,units:{input:a.usage.input,output:a.usage.output,cache_read:a.usage.cacheRead,cache_write:a.usage.cacheWrite},usd:re.usd_equivalent,payer:A.payer,funding:A.funding,sub:w,grantee:d.grantee,node:d.node??null,run:d.run??null,provider:h,causedBy:await ue(),vendorRef:Q}):d!==void 0&&A!==null&&await we({request:d.request??H,kind:"model",what:I,units:{input:a.usage.input,output:a.usage.output,cache_read:a.usage.cacheRead,cache_write:a.usage.cacheWrite},usd:re.usd_equivalent,payer:A.payer,funding:A.funding,sub:w,grantee:d.grantee,node:d.node??null,run:d.run??null,provider:h,causedBy:await ue(),vendorRef:Q});const Ae={id:H,object:"chat.completion",created:Math.floor(Y/1e3),model:I,served_model:I,requested_model:K,substituted:K!==I&&!/^([^/]+)\/(ultra|strong|medium|light)$/.test(K),choices:[{index:0,message:{role:"assistant",content:me.join("")||null,...ee.length?{reasoning_content:ee.join("")}:{},...pe.length?{tool_calls:pe}:{},...oe?{refusal:a.errorMessage??"Content filtered"}:{}},finish_reason:he}],usage:re,...e.metadata!==void 0?{metadata:e.metadata}:{}};for(const[n,m]of pe.entries())ne(te({tool_calls:[{index:n,...m}]}));return ne({...te({},he),model:I,served_model:I,substituted:Ae.substituted,...oe?{choices:[{index:0,delta:{},finish_reason:he,message:{refusal:a.errorMessage??"Content filtered"}}]}:{},usage:re}),{completion:Ae,chunks:fe}}}throw le!==void 0?ct(le):F!==1/0?new i(429,"all_routes_exhausted","all eligible model routes are rate-limited",void 0,{payment:{reason:"nothing_left",message:"Every connected subscription and key is rate-limited or used up right now.",pay_url:(await Oe())?.payment_setup_url??null,reset_at:L===1/0?null:new Date(L).toISOString()},retry_after_s:Math.max(1,Math.ceil((F-Date.now())/1e3)),served_model:v?`${v.provider}/${v.model}`:de,...v?{rate_limit:{provider:v.provider,model:v.model,...v.account?{account:v.account}:{},scope:Ce(v.observation.scope),...v.observation.claim?{claim:v.observation.claim}:{},headers:v.observation.headers}}:{}},void 0,!0):se!==void 0?se:e.model_policy==="exact"?new i(400,"substitution_refused",G.size>0?`your ${[...G].map(Ye).join(" and ")} sign-in has expired; sign in again`:"the requested model is unavailable"):_?new i(404,"model_unavailable","no usable model route is available"):await be()}l(rn,"runLlm");export{xt as freshSubscriptionAccess,on as llmCallerOf,nn as parseLlmRequest,rn as runLlm,Mt as usdEquivalent};
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type RateLimitObservation } from './rate-limit-scope.js';
|
|
1
2
|
export declare const ANTHROPIC_PROVIDER_ID = "anthropic";
|
|
2
3
|
export declare const OPENAI_CODEX_PROVIDER_ID = "openai-codex";
|
|
3
4
|
/** pi's built-in `openai` provider signed in with a ChatGPT account (dynamic OAuth client). Distinct from Codex: its own pool, credential file and sign-in. */
|
|
@@ -12,7 +13,7 @@ export type RotationConfig = {
|
|
|
12
13
|
defaultFallbackStrength?: ModelStrength;
|
|
13
14
|
revertWhenAvailable?: boolean;
|
|
14
15
|
};
|
|
15
|
-
/** `rateLimitedUntil` cools the whole account; `modelCooldowns` cools one model family on it (family → epoch ms, stored rows including expired ones). Read both through `coolingUntilFor`. */
|
|
16
|
+
/** `rateLimitedUntil` cools the whole account; `modelCooldowns` cools one model family on it (family → epoch ms, stored rows including expired ones). Read both through `coolingUntilFor`. `vendorLimits` holds each cooldown's vendor observation, keyed `account` or the family. */
|
|
16
17
|
export type SubscriptionCredential = {
|
|
17
18
|
label: string;
|
|
18
19
|
refresh: string;
|
|
@@ -25,6 +26,13 @@ export type SubscriptionCredential = {
|
|
|
25
26
|
accountId?: string;
|
|
26
27
|
clientId?: string;
|
|
27
28
|
modelCooldowns?: Record<string, number>;
|
|
29
|
+
vendorLimits?: Record<string, VendorLimit>;
|
|
30
|
+
};
|
|
31
|
+
/** What the vendor's 429 said when a cooldown was recorded: the model it answered, the reset the vendor itself named (epoch ms, never the capped cooldown) and the parsed safe observation. */
|
|
32
|
+
export type VendorLimit = {
|
|
33
|
+
model: string;
|
|
34
|
+
vendorReset?: number;
|
|
35
|
+
observation: RateLimitObservation;
|
|
28
36
|
};
|
|
29
37
|
export type ProviderCandidate = {
|
|
30
38
|
providerId: string;
|
|
@@ -39,6 +39,8 @@ export declare function normalizeProviderFailure(error: unknown, observed?: {
|
|
|
39
39
|
}): NormalizedProviderFailure;
|
|
40
40
|
/** The stable diagnostic carrier for normalized provider error facts on an assistant error message. */
|
|
41
41
|
export declare function providerFailureDiagnostic(details: ProviderFailureDetails): AssistantMessageDiagnostic;
|
|
42
|
+
/** Plain text for a fault's vendor facts: the earliest known vendor reset (across the pool), then the last 429's window with its own account and model. Never pairs the aggregate reset with that window. */
|
|
43
|
+
export declare function describeVendorLimit(details: Pick<ProviderFailureDetails, 'payment' | 'ratelimit'> | undefined): string;
|
|
42
44
|
/** Strictly parse a recorded payment refusal: a known reason and a message, nothing else trusted. */
|
|
43
45
|
export declare function parseProviderPayment(value: unknown): PaymentRefusalDTO | undefined;
|
|
44
46
|
/** Strictly parse a recorded rate-limit block: string headers only, capped, unknown keys dropped. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var h=Object.defineProperty;var d=(e,n)=>h(e,"name",{value:n,configurable:!0});import{isRecord as A}from"../shared/predicates.js";import{PAYMENT_REFUSAL_REASONS as E}from"../api/dto/charges.js";const g="crtr:provider-failure",I=8;function o(e){return typeof e=="string"&&e.trim()!==""?e.trim():void 0}d(o,"text");function c(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}d(c,"status");function m(e){return typeof e=="string"||typeof e=="number"?e:void 0}d(m,"code");function s(e){return A(e)?e:void 0}d(s,"record");function y(e){const n=o(e.errorMessage)??o(e.message)??o(e.reason)??o(e.statusText),t={...n===void 0?{}:{message:n},...c(e.status)===void 0?{}:{status:c(e.status)},...m(e.code)===void 0?{}:{code:m(e.code)},...o(e.errno)===void 0?{}:{errno:o(e.errno)},...o(e.body)===void 0?{}:{body:o(e.body)}};return Object.keys(t).length===0?void 0:t}d(y,"failureCause");function M(e,n={}){const t=s(e),r=t===void 0?void 0:y(t),i=[],u=new Set([e]);let a=t===void 0?void 0:s(t.cause);for(;a!==void 0&&!u.has(a)&&i.length<I;){u.add(a);const f=y(a);f!==void 0&&i.push(f),a=s(a.cause)}return{message:r?.message??(e instanceof Error?e.message:void 0)??String(e??"Provider request failed"),...(n.status??r?.status)===void 0?{}:{status:n.status??r?.status},...r?.code===void 0?{}:{code:r.code},...r?.errno===void 0?{}:{errno:r.errno},...r?.body===void 0?{}:{body:r.body},...i.length===0?{}:{causes:i}}}d(M,"normalizeProviderFailure");function P(e){return{type:g,timestamp:Date.now(),details:w(e)}}d(P,"providerFailureDiagnostic");function w(e){const n=b(e);if(e.causes!==void 0&&(n.causes=e.causes.map(b)),e.ratelimit!==void 0){const t={headers:{...e.ratelimit.headers}};e.ratelimit.scope!==void 0&&(t.scope=e.ratelimit.scope),e.ratelimit.claim!==void 0&&(t.claim=e.ratelimit.claim),e.ratelimit.account!==void 0&&(t.account=e.ratelimit.account),e.ratelimit.model!==void 0&&(t.model=e.ratelimit.model),n.ratelimit=t}return e.payment!==void 0&&(n.payment={reason:e.payment.reason,message:e.payment.message,pay_url:e.payment.pay_url,reset_at:e.payment.reset_at}),n}d(w,"jsonDetails");const R=48,S=256,L=new Set(E);function N(e){const n=e?.payment?.reset_at?` Earliest known vendor reset: ${e.payment.reset_at}.`:"",t=e?.ratelimit;if(t===void 0)return n;const r=t.headers["anthropic-ratelimit-unified-reset"];return`${n} Rate limit: ${t.scope??"account"}${t.claim===void 0?"":` (${t.claim})`}${t.account===void 0?"":` on account ${t.account}`}${t.model===void 0?"":` for ${t.model}`}${r===void 0||!Number(r)?"":`, that window resets ${new Date(Number(r)*1e3).toISOString()}`}.`}d(N,"describeVendorLimit");function l(e){const n=s(e);if(!(n===void 0||typeof n.reason!="string"||!L.has(n.reason)||typeof n.message!="string"))return{reason:n.reason,message:n.message,pay_url:typeof n.pay_url=="string"?n.pay_url:null,reset_at:typeof n.reset_at=="string"?n.reset_at:null}}d(l,"parseProviderPayment");function _(e){const n=s(e),t=s(n?.headers);if(n===void 0||t===void 0)return;const r={};for(const[i,u]of Object.entries(t)){if(Object.keys(r).length>=R)break;typeof u=="string"&&(r[i.toLowerCase()]=u.slice(0,S))}return{...o(n.scope)===void 0?{}:{scope:o(n.scope)},...o(n.claim)===void 0?{}:{claim:o(n.claim)},...o(n.account)===void 0?{}:{account:o(n.account)},...o(n.model)===void 0?{}:{model:o(n.model)},headers:r}}d(_,"parseProviderRateLimit");function b(e){const n={};return e.message!==void 0&&(n.message=e.message),e.status!==void 0&&(n.status=e.status),e.code!==void 0&&(n.code=e.code),e.errno!==void 0&&(n.errno=e.errno),e.body!==void 0&&(n.body=e.body),n}d(b,"jsonCause");function T(e){const n=s(e)?.diagnostics;if(Array.isArray(n))for(const t of n){const r=s(t);if(r?.type!==g)continue;const i=s(r.details);if(i===void 0)continue;const u=Array.isArray(i.causes)?i.causes.flatMap(a=>{const p=s(a),f=p===void 0?void 0:y(p);return f===void 0?[]:[f]}):void 0;return{...c(i.status)===void 0?{}:{status:c(i.status)},...m(i.code)===void 0?{}:{code:m(i.code)},...o(i.errno)===void 0?{}:{errno:o(i.errno)},...o(i.body)===void 0?{}:{body:o(i.body)},...u===void 0||u.length===0?{}:{causes:u},..._(i.ratelimit)===void 0?{}:{ratelimit:_(i.ratelimit)},...l(i.payment)===void 0?{}:{payment:l(i.payment)}}}}d(T,"providerFailureDetails");function O(e){return T(e)}d(O,"extractProviderFailureDetails");export{g as PROVIDER_FAILURE_DIAGNOSTIC,N as describeVendorLimit,O as extractProviderFailureDetails,M as normalizeProviderFailure,l as parseProviderPayment,_ as parseProviderRateLimit,P as providerFailureDiagnostic};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var K=Object.defineProperty;var f=(e,t)=>K(e,"name",{value:t,configurable:!0});import{setTimeout as Q}from"node:timers/promises";import{createAssistantMessageEventStream as V,getCurrentSystemPrompt as Z,getCurrentTools as ee}from"@earendil-works/pi-ai";import{socketFetch as te}from"../../../api/node-transport.js";import{DEFER_HEAD_REQUEST_HEADER as ne,DEFERRED_HEAD_CONTENT_TYPE as re,DEFERRED_HEAD_MAGIC as oe}from"../../../daemon/api/deferred-head.js";import{apiSocketPath as se}from"../../canvas/paths.js";import{northlightUnreachable as ae}from"../../directory/reach.js";import{currentNodeToken as ie}from"./node-token.js";import{brokerApiUrl as
|
|
2
|
-
`!==oe)throw new Error("deferred head response has no magic line");
|
|
3
|
-
`))>=0;){const h=_.slice(0,g).trim();_=_.slice(g+1),h&&F(h)}}if(_+=C.decode(),_.trim()&&F(_.trim()),!P||!U)throw new Error("llm stream ended without usage or served_model");for(const[
|
|
1
|
+
var K=Object.defineProperty;var f=(e,t)=>K(e,"name",{value:t,configurable:!0});import{setTimeout as Q}from"node:timers/promises";import{createAssistantMessageEventStream as V,getCurrentSystemPrompt as Z,getCurrentTools as ee}from"@earendil-works/pi-ai";import{socketFetch as te}from"../../../api/node-transport.js";import{DEFER_HEAD_REQUEST_HEADER as ne,DEFERRED_HEAD_CONTENT_TYPE as re,DEFERRED_HEAD_MAGIC as oe}from"../../../daemon/api/deferred-head.js";import{apiSocketPath as se}from"../../canvas/paths.js";import{northlightUnreachable as ae}from"../../directory/reach.js";import{currentNodeToken as ie}from"./node-token.js";import{brokerApiUrl as $}from"./daemon-ops.js";import{currentCausedBy as de}from"./turn-cause.js";import{envModelExact as L,envModelIntent as q,envNodeCwd as ce,envProfileId as le}from"../../../shared/env.js";import{MODEL_CONTEXT_BODY_MAX_BYTES as v}from"../../llm/body-limits.js";import{APP_FAMILY as ue,expandModelCandidates as fe,llmModelFor as pe,modelRequestFromConfig as me}from"../../model-routes.js";import{parseProviderPayment as he,parseProviderRateLimit as ge,providerFailureDiagnostic as B}from"../../provider-failure.js";import{UPSTREAM_MODEL_UNAVAILABLE as I}from"../../fault-classifier.js";function Fe(e,t,n){e.checkAuth=async d=>e.getProvider(d)?{type:"api_key"}:void 0,e.getAvailable=async d=>e.getModels(d),e.getAvailableSnapshot=()=>e.getModels(),e.streamSimple=(d,c,a)=>Ee(d,c,a,t,n)}f(Fe,"configureBrokerModelRuntime");const ye=300,H="crtr:llm-refusal";class R extends Error{static{f(this,"LlmRefusalError")}retryAt;rateLimit;code;status;payment;constructor(t,n,d,c,a,r){super(t),this.retryAt=n,this.rateLimit=d,this.code=c,this.status=a,this.payment=r}}class E extends Error{static{f(this,"UpstreamModelUnavailableError")}}function T(e,t){const n=e===void 0?"the request body":`the request body (${e} bytes)`;return new Error(`request_too_large: ${n} exceeds the ${t}-byte model request limit; compact the conversation to shrink the context`)}f(T,"contextTooLargeError");function M(e){const t=e.details?.rate_limit;if(!t||typeof t!="object")return;const n=ge(t);if(n===void 0)return;const{provider:d,model:c}=t;return typeof d=="string"&&d!==""&&typeof c=="string"&&c!==""?{...n,model:`${d}/${c}`}:n}f(M,"refusalRateLimit");function qe(e){for(const t of e.diagnostics??[]){if(t.type!==H)continue;const n=t.details?.retryAt;if(typeof n=="number"&&Number.isFinite(n)&&n>0)return n}}f(qe,"refusalRetryAt");class j extends Error{static{f(this,"ContentFilteredError")}}function A(e){return he(e.details?.payment)}f(A,"refusalPayment");function W(e){return typeof e=="string"?e:e.map(t=>t.type==="text"?{type:"text",text:t.text}:{type:"image_url",image_url:{url:`data:${t.mimeType};base64,${t.data}`}})}f(W,"wireContent");function we(e){const t=f(c=>c.role==="assistant"&&(c.stopReason==="error"||c.stopReason==="aborted"),"incomplete"),n=e.some(t)?e.filter(c=>!t(c)):e;let d=n.length;for(;d>0&&n[d-1]?.role==="assistant";)d--;return d===n.length?n:n.slice(0,d)}f(we,"wireHistory");async function _e(e,t){const n=L()?void 0:me(`${e.provider}/${e.id}`,t,!1);if(n?.kind!=="logical"||n.family===ue)return new Set;const d=await fe(n,ce(),le());return new Set(d.flatMap(c=>c.strength===n.strength&&c.providerId===e.provider&&c.modelId===e.id&&c.thinkingLevel!==void 0?[c.thinkingLevel]:[]))}f(_e,"launchThinkingLevels");function xe(e,t,n,d,c=new Set){const a=[],r=Z(t.messages),s=ee(t.messages);r?a.push({role:"system",content:r}):t.systemPrompt&&a.push({role:"system",content:t.systemPrompt});for(const l of we(t.messages))l.role==="user"?a.push({role:"user",content:W(l.content)}):l.role==="toolResult"?a.push({role:"tool",content:W(l.content),tool_call_id:l.toolCallId}):l.role==="assistant"&&a.push({role:"assistant",content:l.content.filter(p=>p.type==="text").map(p=>p.text).join("")||null,tool_calls:l.content.filter(p=>p.type==="toolCall").map(p=>({id:p.id,type:"function",function:{name:p.name,arguments:JSON.stringify(p.arguments)}}))});const b=`${e.provider}/${e.id}`,w=d??q();return{model:pe(b,w,L()),model_policy:L()?"exact":"substitute",stream:!0,messages:a,...s.length?{tools:s.map(l=>({type:"function",function:{name:l.name,description:l.description,parameters:l.parameters}}))}:{},...n.reasoning&&!c.has(n.reasoning)?{reasoning_effort:n.reasoning}:{},...n.temperature!==void 0?{temperature:n.temperature}:{},...n.maxTokens!==void 0?{max_tokens:n.maxTokens}:{}}}f(xe,"requestBody");function D(e,t){if(typeof t!="string")return!1;const n=t.indexOf("/");return n<1||n===t.length-1?!1:(e.provider=t.slice(0,n),e.model=t.slice(n+1),!0)}f(D,"applyServedModel");function J(e){if(e.details?.served_model!==void 0)return e.details.served_model;const t=e.details?.rate_limit;return typeof t?.provider=="string"&&typeof t.model=="string"?`${t.provider}/${t.model}`:void 0}f(J,"refusalRoute");function Y(e){if(!e||typeof e!="object"||!("error"in e))throw new Error("llm returned an invalid response");const t=e.error;if(!t||typeof t.message!="string")throw new Error("llm returned an invalid refusal");return t}f(Y,"parseRefusal");function z(e){try{return JSON.parse(e)}catch{throw new E(`llm returned a non-JSON answer: ${e.slice(0,120)}`)}}f(z,"parseAnswer");function O(){const e=$();return e===void 0?"http://localhost/v1/llm":new URL("/v1/llm",e).toString()}f(O,"llmUrl");function G(){return $()===void 0?te(se()):globalThis.fetch}f(G,"llmFetch");async function Be(e){const t=await G()(O().replace(/\/v1\/llm$/,`/healthz?model=${encodeURIComponent(e)}`),{signal:AbortSignal.timeout(5e3)}).catch(()=>null);if(t?.status===200)return{ok:!0};const n=t?.status===503?(await t.json().catch(()=>null))?.error?.retry_after_s:void 0;return typeof n=="number"?{ok:!1,waitMs:n*1e3,reason:`waiting for ${e}: model unavailable`}:{ok:!1,reason:`waiting for ${e}: gateway not answering`}}f(Be,"askGateway");async function be(e){if(!e.headers.get("content-type")?.startsWith(re))return e;if(!e.body)throw new Error("deferred head response has no body");const t=e.body.getReader();let n=new Uint8Array(0),d=!1;for(;;){const c=n.indexOf(10);if(c<0){const{value:l,done:p}=await t.read();if(p)throw new Error("deferred head response ended before its head");const m=new Uint8Array(n.length+l.length);m.set(n),m.set(l,n.length),n=m;continue}const a=new TextDecoder().decode(n.subarray(0,c)).trim();if(n=n.subarray(c+1),!d){if(`${a}
|
|
2
|
+
`!==oe)throw new Error("deferred head response has no magic line");d=!0;continue}if(a==="")continue;const r=JSON.parse(a),s=new Headers;for(const[l,p]of Object.entries(r.headers))for(const m of Array.isArray(p)?p:[p])s.append(l,m);const b=n,w=new ReadableStream({start(l){b.length>0&&l.enqueue(b)},async pull(l){const{value:p,done:m}=await t.read();m?l.close():l.enqueue(p)},cancel(l){return t.cancel(l)}});return new Response(r.status===204?null:w,{status:r.status,headers:s})}}f(be,"unwrapDeferredHead");function ke(e){const t=e??de();return t===void 0?{}:{"crtr-caused-by":t}}f(ke,"causedByHeader");function Ee(e,t,n={},d,c){const a=V(),r={role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};return(async()=>{const s=ie();if(!s)throw new Error("llm requires a node token");const b=JSON.stringify(xe(e,t,n,d,await _e(e,d??q()))),w=Buffer.byteLength(b);if(w>v)throw T(w,v);let l=0;for(;;){n.signal?.throwIfAborted();const p=await G()(O(),{method:"POST",headers:{authorization:`Bearer ${s}`,"content-type":"application/json",[ne]:"1",...ke(c)},body:b,signal:n.signal}).catch(u=>{const o=O();throw $()===void 0||n.signal?.aborted?u:new E(ae(u,o).message)}),m=await be(p);if(!m.ok){if(m.status===413)throw T(w,v);const u=Y(z(await m.text()));if(u.code==="payload_too_large")throw T(w,v);if(D(r,J(u)),u.retryable!==!0)throw new R(u.message,void 0,M(u),u.code,m.status,A(u));const o=u.retry_after_s;if(typeof o!="number"||!Number.isFinite(o)||o<=0)throw u.code===I?new E(u.message,{cause:u.details?.breaker}):new Error(u.message);const g=ye-l;if(o>g){const h=Date.now()+o*1e3,i=A(u)?.reset_at;throw new R(`${u.message} (retry after ${o}s, at ${new Date(h).toISOString()}: the router's next probe${i?`; earliest known vendor reset ${i}`:""})`,h,M(u),u.code,m.status,A(u))}await Q(o*1e3,void 0,{signal:n.signal}),l+=o;continue}if(!m.body)throw new Error("llm returned no stream");a.push({type:"start",partial:r});const X=m.body.getReader(),C=new TextDecoder;let _="",k="stop",N,P=!1,U=!1;const F=f(u=>{const o=z(u);if(o.error){const i=Y(o);throw D(r,J(i)),i.retryable!==!0?new R(i.message,void 0,M(i),i.code,void 0,A(i)):i.code===I?new E(i.message,{cause:i.details?.breaker}):new Error(i.message)}if(o.served_model){if(U=!0,o.served_model.indexOf("/")<1)throw new Error("llm returned an invalid served_model");D(r,o.served_model)}const g=o.choices?.[0],h=g?.delta;if(h?.reasoning_content){const i=r.content.findIndex(S=>S.type==="thinking"),y=i<0?{type:"thinking",thinking:""}:r.content[i],x=i<0?r.content.push(y)-1:i;if(i<0&&a.push({type:"thinking_start",contentIndex:x,partial:r}),y.type!=="thinking")throw new Error("invalid thinking block");y.thinking+=h.reasoning_content,a.push({type:"thinking_delta",contentIndex:x,delta:h.reasoning_content,partial:r})}if(h?.content){const i=r.content.findIndex(S=>S.type==="text"),y=i<0?{type:"text",text:""}:r.content[i],x=i<0?r.content.push(y)-1:i;if(i<0&&a.push({type:"text_start",contentIndex:x,partial:r}),y.type!=="text")throw new Error("invalid text block");y.text+=h.content,a.push({type:"text_delta",contentIndex:x,delta:h.content,partial:r})}for(const i of h?.tool_calls??[]){const y={type:"toolCall",id:i.id,name:i.function.name,arguments:JSON.parse(i.function.arguments)},x=r.content.push(y)-1;a.push({type:"toolcall_start",contentIndex:x,partial:r}),a.push({type:"toolcall_end",contentIndex:x,toolCall:y,partial:r})}g?.finish_reason&&(k=g.finish_reason),g?.message?.refusal&&(N=g.message.refusal),o.usage&&(P=!0,r.usage={input:o.usage.prompt_tokens,output:o.usage.completion_tokens,cacheRead:o.usage.cache_read_tokens,cacheWrite:o.usage.cache_write_tokens,totalTokens:o.usage.total_tokens,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:typeof o.usage.usd_equivalent=="number"&&Number.isFinite(o.usage.usd_equivalent)?o.usage.usd_equivalent:0}})},"apply");for(;;){const{value:u,done:o}=await X.read();if(o)break;_+=C.decode(u,{stream:!0});let g;for(;(g=_.indexOf(`
|
|
3
|
+
`))>=0;){const h=_.slice(0,g).trim();_=_.slice(g+1),h&&F(h)}}if(_+=C.decode(),_.trim()&&F(_.trim()),!P||!U)throw new Error("llm stream ended without usage or served_model");for(const[u,o]of r.content.entries())o.type==="text"&&a.push({type:"text_end",contentIndex:u,content:o.text,partial:r}),o.type==="thinking"&&a.push({type:"thinking_end",contentIndex:u,content:o.thinking,partial:r});if(k==="content_filter")throw new j(N??"Content filtered");if(!["stop","tool_calls","length"].includes(k))throw new Error(`llm returned unknown finish reason: ${k}`);r.stopReason=k==="tool_calls"?"toolUse":k==="length"?"length":"stop",a.push({type:"done",reason:r.stopReason,message:r}),a.end();return}})().catch(s=>{r.stopReason=n.signal?.aborted?"aborted":"error",r.errorMessage=s instanceof Error?s.message:String(s),s instanceof R&&(r.diagnostics=[{type:H,timestamp:Date.now(),...s.retryAt!==void 0?{details:{retryAt:s.retryAt}}:{}},...s.rateLimit!==void 0||s.code==="cap_exhausted"||s.code==="payment_refused"||s.payment!==void 0?[B({status:s.rateLimit!==void 0?429:s.status??402,...s.code===void 0?{}:{code:s.code},...s.rateLimit===void 0?{}:{ratelimit:s.rateLimit},...s.payment===void 0?{}:{payment:s.payment}})]:[]]),s instanceof E&&(r.diagnostics=[B({status:503,code:I,...s.cause===void 0?{}:{body:"breaker"}})]),s instanceof j&&r.stopReason==="error"&&(r.rawStopReason="content_filter"),a.push({type:"error",reason:r.stopReason,error:r}),a.end()}),a}f(Ee,"streamBrokerModel");export{ye as LLM_BROKER_RETRY_WINDOW_S,H as LLM_REFUSAL_DIAGNOSTIC,Be as askGateway,Fe as configureBrokerModelRuntime,_e as launchThinkingLevels,qe as refusalRetryAt,xe as requestBody,Ee as streamBrokerModel,be as unwrapDeferredHead,we as wireHistory};
|
|
@@ -111,6 +111,8 @@ export declare function assertRecordedCwdExists(nodeId: string, meta: NodeMeta):
|
|
|
111
111
|
blaxelEnvironment: string | null;
|
|
112
112
|
remoteMachine: boolean;
|
|
113
113
|
}>;
|
|
114
|
+
/** Cleanup deleted this node's managed checkout and its branch, and nothing rebuilds them: refuse on any host, before a caller changes state. */
|
|
115
|
+
export declare function assertCheckoutNotRemoved(nodeId: string, meta: NodeMeta): void;
|
|
114
116
|
/** The `node:start` lifecycle hooks for a node coming up: a launch, or a cycle started in a running process. */
|
|
115
117
|
export declare function runNodeStartHooks(nodeId: string, meta: NodeMeta, isBirth: boolean): Promise<void>;
|
|
116
118
|
export {};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var ce=Object.defineProperty;var s=(e,r)=>ce(e,"name",{value:r,configurable:!0});import{assertGranteeRunsHere as ue}from"./unsandboxed.js";import{existsSync as H}from"node:fs";import{conversationIdFromPath as _,conversationStore as m,ConversationNotFoundError as G}from"../conversation-store/index.js";import{isAbsolute as fe}from"node:path";import{findNodeBySessionFile as we,getNode as R,updateNode as N,beginExecution as he,ExecutionAlreadyLive as pe,recordExecutionPid as me,abortExecution as F,endLiveExecution as de,unbindSession as U,recordLaunch as ve,setFrozen as _e,clearFrozen as K,fullName as ye}from"../canvas/index.js";import{emitEvent as W}from"../events/emit.js";import{consumeDeadlineOnWake as ke}from"../feed/messages.js";import{isParked as J,transition as A}from"./lifecycle.js";import{publishNotice as ge}from"./close.js";import{InputError as O}from"../io.js";import{buildPiArgv as y}from"./launch.js";import{buildReviveKickoff as be,drainBearings as Re,hasRetainedReports as Ee,readGoal as E,readYieldMessage as xe,RUNTIME_RESTART_CONTINUATION as Se}from"./kickoff.js";import{readRoadmap as j}from"./roadmap.js";import{encodeKickoffOrigin as Ce,KICKOFF_ORIGIN_ENV as $e}from"./stamp/protocol.js";import{carryInitialInput as V}from"../runs/initial-input.js";import{headlessBrokerHost as Ne,brokerLaunchJson as Fe}from"./host.js";import{isCloudRole as Ae}from"../canvas/person.js";import{asNodePerson as Oe}from"../../daemon/reconcilers/node-lifecycle/node-person.js";import{processRunner as Pe}from"./runner/process.js";import{runnerForEnvironment as X}from"./runner/index.js";import{MachineOfflineError as Y}from"./runner/machine/ops.js";import{blaxelEnvironmentOf as q}from"./blaxel-environment.js";import{recordLaunchFailure as Be}from"../../daemon/reconcilers/node-lifecycle/launch-failure.js";import{acceptedRelease as Q,remoteMachineEnvironmentOf as De,checkBilledWake as Te,EnvironmentImagePending as Me,imageForWake as Le}from"../../daemon/reconcilers/node-lifecycle/remote-wake.js";import{ExecutionCapReached as ze,liveExecutionForNode as He,setExecutionLaunchJson as Ge}from"../canvas/executions.js";import{isDrained as Ue}from"../../daemon/drain.js";import{appMemoryFull as Ke,appMemoryTooSmall as We,boundFleet as Z,brokerCapReached as I,brokerThresholdsForDaemon as P}from"./fleet.js";import{admitBrokerMemory as Je}from"./memory-admission.js";import{beginBootFaultAttempt as je,clearFault as Ve,hasAdmittedTurn as Xe,readFault as Ye}from"../canvas/recovery.js";import{clearNodeLedger as ee,forkNodeLedger as qe,noticeChangedWhileDone as Qe}from"./ledger.js";import{forkSourceNode as Ze,rootOfSpine as Ie}from"./nodes.js";import{ApiError as er}from"../../api/errors.js";import{grantSnapshotMissing as rr}from"../../daemon/readiness.js";import{checkGrantActive as ir,checkStart as tr}from"./start-check.js";import{isReviewCompanionBound as nr}from"../review/companion.js";import{assertProfileActive as ar}from"../profiles/manifest.js";import{isPidAlive as or}from"../canvas/pid.js";import{crtrHome as sr,jobDir as lr}from"../canvas/paths.js";import{contextDir as cr,ensureNodeDirs as ur,nodeAgentDir as fr}from"../canvas/node-agent-paths.js";import{discoverLifecycleHookRegistry as wr}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as hr}from"../command-hooks/transport/exec-lifecycle.js";async function pr(e,r){const i=e.pi_session_file,t=i?_(i):null;if(t===null)return{};try{const n=await m().header(t);return r?{resumeSessionPath:n.path}:{resumeSessionPath:n.path,newCycle:!0}}catch(n){if(n instanceof G)return{};throw n}}s(pr,"resumeArgs");async function re(e){const r=_(e);if(r===null)return!1;try{return await m().header(r),!0}catch(i){if(i instanceof G)return!1;throw i}}s(re,"conversationExists");async function mr(e){const r=_(e);return r===null?!0:(await m().read(r)).entries.some(i=>i.type==="message")}s(mr,"sessionHasConversation");async function dr(e){const r=_(e);if(r===null)return!0;const i=(await m().header(r)).header.cwd;return typeof i!="string"||H(i)}s(dr,"sessionCwdExists");async function vr(e,r,i,t){const n=r.pi_session_file;if(!n||!await re(n))return{};const u=await we(n);return u!==null&&u.node_id!==e&&or(u.pi_pid)?{}:t&&!await dr(n)?{}:await pr(r,i)}s(vr,"resumableSessionArgs");async function _r(e){return await j(e)===null&&await xe(e)===null&&!await Ee(e)}s(_r,"isUnstartedBirth");async function fi(e){const r=await E(e);if(r!==null&&r.trim()!=="")return!0;const i=await j(e);return i!==null&&i.trim()!==""}s(fi,"hasFreshGroundState");async function wi(e,r){const i=await ie(e,r,!0);if(i.parked)throw new Error(`reviveNode: internal parked decision for activating revive ${e}`);return i.result}s(wi,"reviveNode");async function hi(e,r,i){return ie(e,{...r,viewerAttach:!0},i)}s(hi,"decideAttachRevive");async function ie(e,r,i){const t=Ae()?await R(e):null;return t===null?await te(e,r,i):await Oe({node_id:e,sub:t.sub??null,profile_id:t.profile_id??null},()=>te(e,r,i))}s(ie,"decideRevive");async function te(e,r,i){let t=await R(e);if(t===null)throw new Error(`reviveNode: unknown node ${e}`);if(t=await R(e)??t,t.run_id&&(await R(t.run_id))?.deleting_at)throw new Error("run is deleting");if(t.final_report!==null)throw new Error(`reviveNode: refusing to revive ${e} \u2014 its finalization latch is set (final_report=${t.final_report}). A final landed between the caller's reopen-gate check and this revive; re-run with --reopen if this retask is still wanted.`);ar(t.profile_id),ue(t.grantee);const n=Z(),u=t.grantee==="app:terminal"&&await rr();if(!await n.has(e)&&!await n.isClaimed(e)&&r.wakeReason!=="runtime-restart-abort"&&r.viewerAttach!==!0&&!(!i&&t.lifecycle==="resident"&&J(t))&&(await ir(t),await tr(t),await q(t.profile_id??null)!==null&&await Te(t)),await n.isClaimed(e))return await n.has(e)&&await A(e,t.intent==="refresh"?"refresh-launch":"revive"),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"already-live"}};if(!i&&t.lifecycle==="resident"&&J(t))return{parked:!0};if(u){if(r.capacity==="refuse")throw new er(503,"runtime_starting","the first grant snapshot from the directory has not committed");return await ne(e,t,{reason:"grant_snapshot"}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}const k=await Ue();if(k&&r.capacity==="refuse")throw new Error(`the daemon is drained for an import; ${e} cannot start until it ends`);const d=!k&&await n.reserveSlot(e);let o=null;if(d){try{o=await Je(e)}catch(w){throw n.releaseReservation(e),w}o.verdict!=="admitted"&&n.releaseReservation(e)}if(o?.verdict==="too_small")throw We(o);if(!d||o?.verdict==="denied"){if(r.capacity==="refuse")throw o?.verdict==="denied"?Ke(o):I(P().automaticReviveCap,await n.occupancy());return await ne(e,t,k?{reason:"drain"}:o?.verdict==="denied"?{reason:"app_memory",free_bytes:o.free_bytes,needed_bytes:o.needed_bytes}:{reason:"broker_cap",live_count:await n.occupancy(),hard_cap:P().automaticReviveCap}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}try{return{parked:!1,result:await gr(e,t,r)}}finally{n.releaseReservation(e)}}s(te,"decideReviveAsCaller");async function ne(e,r,i){r.frozen_at==null&&(await _e(e,new Date().toISOString()),await de(e,{reason:"frozen"}),W({level:"info",event:"broker.frozen",node_id:e,fields:i}))}s(ne,"freezeForWait");async function yr(e,r){const i=await q(r.profile_id??null),t=await De(r.profile_id??null)!==null;if(!(i!==null||t)&&!H(r.cwd)){const u=r.fork_from!=null?`Restore ${r.cwd}, then revive the fork normally with \`crtr node lifecycle revive ${e}\`.`:r.managed_worktree?.state==="open"?"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon recovery.":`Recreate ${r.cwd}, or repair it with \`crtr node config --cwd <path> --node ${e}\`; durable node work resumes in a fresh conversation. Then retry \`crtr node lifecycle revive ${e}\`.`;throw new O({error:"cwd_missing",message:`${e} cannot be revived \u2014 its recorded cwd no longer exists: ${r.cwd}`,next:u})}return{blaxelEnvironment:i,remoteMachine:t}}s(yr,"assertRecordedCwdExists");async function kr(e,r,i){const t=wr(r.cwd,r.profile_id).plans.get("node:start")??[];await hr(t,{node:{id:e,name:r.name,kind:r.kind,mode:r.mode,lifecycle:r.lifecycle,cwd:r.cwd,nodeDir:await fr(e),contextDir:await cr(e),jobDir:lr(e)},runtime:{isBirth:i,canvasHome:sr(),profile:r.profile_id??null}})}s(kr,"runNodeStartHooks");async function gr(e,r,i){const{blaxelEnvironment:t,remoteMachine:n}=await yr(e,r),u=t!==null||n;r.host_kind!=="broker"&&(await N(e,{host_kind:"broker"}),r.host_kind="broker"),r.review_binding!=null&&!await nr(e)&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await U(e),r.pi_session_id=null,r.pi_session_file=null);const d=r.fork_from!=null&&r.pi_session_id==null,o=r.fork_source_file;if(d&&(typeof o!="string"||!fe(o)))throw new O({error:"fork_source_invalid",message:`${e} cannot be revived \u2014 its resolved fork source file is missing or invalid.`,next:`Restore the node's fork source metadata, then retry \`crtr node lifecycle revive ${e}\`.`});const w=d&&typeof o=="string";if(w&&!await re(o))throw new O({error:"fork_from_missing",message:`${e} cannot be revived \u2014 its fork source no longer exists: ${o}`,next:`Restore ${o}, or update the node's fork source, then retry \`crtr node lifecycle revive ${e}\`.`});const{automaticReviveCap:ae}=P();if(t!==null){const l=await Le(t);if(l.state==="pending")throw new Me(t,l.error)}const oe=t!==null?X("blaxel"):n?X("machine"):Pe;let f;try{f=await he(e,{daemonEpoch:Z().epoch(),cap:ae,...t!==null?{runner:"blaxel",release:Q()}:n?{runner:"machine",release:Q()}:{}})}catch(l){if(l instanceof ze)throw I(l.cap,l.live);if(l instanceof pe)return{window:null,session:r.tmux_session??null,resumed:!1,outcome:"already-live"};throw l}try{r.cycles=(r.cycles??0)+1,await N(e,{cycles:r.cycles});const x=r.intent==="refresh"||r.cycle_pending===!0?!1:i.resume,p=w?{}:await vr(e,r,x,!u),g=p.resumeSessionPath!==void 0,B=g&&p.newCycle===!0,v=g&&!B,D=!g&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&await _r(e),S=v&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&!await Xe(e)&&!await mr(p.resumeSessionPath)?(await E(e))?.trim():void 0,T=S!==void 0&&S!=="",se=w||D||T,M=r.cycle_pending===!0||B;await N(e,{cycle_pending:M}),r.cycle_pending=M,!w&&!g&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await U(e),r.pi_session_id=null,r.pi_session_file=null);let c,h=null;const C=s(()=>({type:"runtime",kind:"kickoff",...r.spawned_by!=null&&r.spawned_by!==""?{spawnedBy:r.spawned_by}:{}}),"birthOrigin");if(w){const a=await E(e),$=_(o);if($===null)throw new Error(`invalid fork source ${o}`);const le=(await m().header(await m().fork($,e))).path;c=y(r,{resumeSessionPath:le,...a!=null&&a!==""?{prompt:a}:{}}),a!=null&&a!==""&&(h=C()),await qe(e,(await Ze(o))?.node_id??null)}else if(T)c=y(r,{...p,prompt:S}),h=C(),await V(c,r);else if(v)c=y(r,{...p,...i.wakeReason==="runtime-restart-abort"?{prompt:Se}:{}}),i.wakeReason==="runtime-restart-abort"&&(h={type:"runtime",kind:"restart-continuation"});else if(D){const a=(await E(e))?.trim();c=y(r,a!==void 0&&a!==""?{prompt:a}:{}),a!==void 0&&a!==""&&(h=C(),await V(c,r)),await ee(e)}else{const a=await Re(r,f);c=y(r,{...p,prompt:await be(r,a,i.wakeReason==="runtime-restart-abort"?void 0:i.wakeReason)}),r.run_id&&a.unreadMessageIds?.length&&(c.env.CRTR_KICKOFF_MESSAGE_IDS=JSON.stringify(a.unreadMessageIds)),h=i.wakeReason!==void 0&&i.wakeReason!=="runtime-restart-abort"?{type:"runtime",kind:"wake",wake:i.wakeReason}:{type:"runtime",kind:"revive",cycle:r.cycles??0},await ee(e)}c.env={...c.env,CRTR_SUBTREE:await Ie(e)},h!==null&&(c.env[$e]=Ce(h)),r.status==="done"&&r.last_settled_at!=null&&await Qe(e,r.last_settled_at),await A(e,r.intent==="refresh"?"refresh-launch":"revive"),(await Ye(e))?.op!=="conversation_write_failed"&&await Ve(e,{preserveEpisode:!0});const L=await je(e);i.recovery!==!0&&i.viewerAttach!==!0&&await ke(e),await ur(e,r.grantee),await kr(e,r,se),c.env={...c.env,CRTR_EXECUTION_ID:f};const z=await Fe(e,c,r.cwd);await Ge(f,z);let b;try{const a=await He(e);if(b=await oe.start({executionId:f,nodeId:e,attempt:a?.attempt??1,release:a?.release??"",launchJson:z,cwd:r.cwd,resuming:v}),!u&&b.pid===null)throw new Error(`broker host returned no pid for ${e}`)}catch(a){if(a instanceof Y)throw a;try{await A(e,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:a instanceof Error?a.message:String(a)}}}),await ge(e,"notice.crash",`Child crashed \u2014 ${ye(r)} (${e}) failed to relaunch and is now dead: ${a.message}
|
|
1
|
+
var le=Object.defineProperty;var s=(e,r)=>le(e,"name",{value:r,configurable:!0});import{assertGranteeRunsHere as ue}from"./unsandboxed.js";import{existsSync as H}from"node:fs";import{conversationIdFromPath as _,conversationStore as d,ConversationNotFoundError as G}from"../conversation-store/index.js";import{isAbsolute as fe}from"node:path";import{findNodeBySessionFile as we,getNode as R,updateNode as F,beginExecution as he,ExecutionAlreadyLive as pe,recordExecutionPid as de,abortExecution as A,endLiveExecution as me,unbindSession as U,recordLaunch as ve,setFrozen as _e,clearFrozen as K,fullName as ye}from"../canvas/index.js";import{emitEvent as W}from"../events/emit.js";import{consumeDeadlineOnWake as ke}from"../feed/messages.js";import{isParked as J,transition as O}from"./lifecycle.js";import{publishNotice as ge}from"./close.js";import{InputError as E}from"../io.js";import{buildPiArgv as y}from"./launch.js";import{buildReviveKickoff as be,drainBearings as Re,hasRetainedReports as Ee,readGoal as x,readYieldMessage as xe,RUNTIME_RESTART_CONTINUATION as Se}from"./kickoff.js";import{readRoadmap as j}from"./roadmap.js";import{encodeKickoffOrigin as $e,KICKOFF_ORIGIN_ENV as Ce}from"./stamp/protocol.js";import{carryInitialInput as V}from"../runs/initial-input.js";import{headlessBrokerHost as Ne,brokerLaunchJson as Fe}from"./host.js";import{isCloudRole as Ae}from"../canvas/person.js";import{asNodePerson as Oe}from"../../daemon/reconcilers/node-lifecycle/node-person.js";import{processRunner as Pe}from"./runner/process.js";import{runnerForEnvironment as X}from"./runner/index.js";import{MachineOfflineError as Y}from"./runner/machine/ops.js";import{blaxelEnvironmentOf as q}from"./blaxel-environment.js";import{recordLaunchFailure as Be}from"../../daemon/reconcilers/node-lifecycle/launch-failure.js";import{acceptedRelease as Q,remoteMachineEnvironmentOf as De,checkBilledWake as Te,EnvironmentImagePending as Me,imageForWake as Le}from"../../daemon/reconcilers/node-lifecycle/remote-wake.js";import{ExecutionCapReached as ze,liveExecutionForNode as He,setExecutionLaunchJson as Ge}from"../canvas/executions.js";import{isDrained as Ue}from"../../daemon/drain.js";import{appMemoryFull as Ke,appMemoryTooSmall as We,boundFleet as Z,brokerCapReached as I,brokerThresholdsForDaemon as P}from"./fleet.js";import{admitBrokerMemory as Je}from"./memory-admission.js";import{beginBootFaultAttempt as je,clearFault as Ve,hasAdmittedTurn as Xe,readFault as Ye}from"../canvas/recovery.js";import{clearNodeLedger as ee,forkNodeLedger as qe,noticeChangedWhileDone as Qe}from"./ledger.js";import{forkSourceNode as Ze,rootOfSpine as Ie}from"./nodes.js";import{ApiError as er}from"../../api/errors.js";import{grantSnapshotMissing as rr}from"../../daemon/readiness.js";import{checkGrantActive as ir,checkStart as tr}from"./start-check.js";import{isReviewCompanionBound as nr}from"../review/companion.js";import{assertProfileActive as ar}from"../profiles/manifest.js";import{isPidAlive as or}from"../canvas/pid.js";import{crtrHome as sr,jobDir as cr}from"../canvas/paths.js";import{contextDir as lr,ensureNodeDirs as ur,nodeAgentDir as fr}from"../canvas/node-agent-paths.js";import{discoverLifecycleHookRegistry as wr}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as hr}from"../command-hooks/transport/exec-lifecycle.js";async function pr(e,r){const i=e.pi_session_file,t=i?_(i):null;if(t===null)return{};try{const n=await d().header(t);return r?{resumeSessionPath:n.path}:{resumeSessionPath:n.path,newCycle:!0}}catch(n){if(n instanceof G)return{};throw n}}s(pr,"resumeArgs");async function re(e){const r=_(e);if(r===null)return!1;try{return await d().header(r),!0}catch(i){if(i instanceof G)return!1;throw i}}s(re,"conversationExists");async function dr(e){const r=_(e);return r===null?!0:(await d().read(r)).entries.some(i=>i.type==="message")}s(dr,"sessionHasConversation");async function mr(e){const r=_(e);if(r===null)return!0;const i=(await d().header(r)).header.cwd;return typeof i!="string"||H(i)}s(mr,"sessionCwdExists");async function vr(e,r,i,t){const n=r.pi_session_file;if(!n||!await re(n))return{};const u=await we(n);return u!==null&&u.node_id!==e&&or(u.pi_pid)?{}:t&&!await mr(n)?{}:await pr(r,i)}s(vr,"resumableSessionArgs");async function _r(e){return await j(e)===null&&await xe(e)===null&&!await Ee(e)}s(_r,"isUnstartedBirth");async function fi(e){const r=await x(e);if(r!==null&&r.trim()!=="")return!0;const i=await j(e);return i!==null&&i.trim()!==""}s(fi,"hasFreshGroundState");async function wi(e,r){const i=await ie(e,r,!0);if(i.parked)throw new Error(`reviveNode: internal parked decision for activating revive ${e}`);return i.result}s(wi,"reviveNode");async function hi(e,r,i){return ie(e,{...r,viewerAttach:!0},i)}s(hi,"decideAttachRevive");async function ie(e,r,i){const t=Ae()?await R(e):null;return t===null?await te(e,r,i):await Oe({node_id:e,sub:t.sub??null,profile_id:t.profile_id??null},()=>te(e,r,i))}s(ie,"decideRevive");async function te(e,r,i){let t=await R(e);if(t===null)throw new Error(`reviveNode: unknown node ${e}`);if(t=await R(e)??t,t.run_id&&(await R(t.run_id))?.deleting_at)throw new Error("run is deleting");if(t.final_report!==null)throw new Error(`reviveNode: refusing to revive ${e} \u2014 its finalization latch is set (final_report=${t.final_report}). A final landed between the caller's reopen-gate check and this revive; re-run with --reopen if this retask is still wanted.`);ar(t.profile_id),ue(t.grantee);const n=Z(),u=t.grantee==="app:terminal"&&await rr();if(!await n.has(e)&&!await n.isClaimed(e)&&r.wakeReason!=="runtime-restart-abort"&&r.viewerAttach!==!0&&!(!i&&t.lifecycle==="resident"&&J(t))&&(await ir(t),await tr(t),await q(t.profile_id??null)!==null&&await Te(t)),await n.isClaimed(e))return await n.has(e)&&await O(e,t.intent==="refresh"?"refresh-launch":"revive"),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"already-live"}};if(!i&&t.lifecycle==="resident"&&J(t))return{parked:!0};if(u){if(r.capacity==="refuse")throw new er(503,"runtime_starting","the first grant snapshot from the directory has not committed");return await ne(e,t,{reason:"grant_snapshot"}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}const k=await Ue();if(k&&r.capacity==="refuse")throw new Error(`the daemon is drained for an import; ${e} cannot start until it ends`);const m=!k&&await n.reserveSlot(e);let o=null;if(m){try{o=await Je(e)}catch(w){throw n.releaseReservation(e),w}o.verdict!=="admitted"&&n.releaseReservation(e)}if(o?.verdict==="too_small")throw We(o);if(!m||o?.verdict==="denied"){if(r.capacity==="refuse")throw o?.verdict==="denied"?Ke(o):I(P().automaticReviveCap,await n.occupancy());return await ne(e,t,k?{reason:"drain"}:o?.verdict==="denied"?{reason:"app_memory",free_bytes:o.free_bytes,needed_bytes:o.needed_bytes}:{reason:"broker_cap",live_count:await n.occupancy(),hard_cap:P().automaticReviveCap}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}try{return{parked:!1,result:await gr(e,t,r)}}finally{n.releaseReservation(e)}}s(te,"decideReviveAsCaller");async function ne(e,r,i){r.frozen_at==null&&(await _e(e,new Date().toISOString()),await me(e,{reason:"frozen"}),W({level:"info",event:"broker.frozen",node_id:e,fields:i}))}s(ne,"freezeForWait");async function yr(e,r){const i=await q(r.profile_id??null),t=await De(r.profile_id??null)!==null;if(!(i!==null||t)&&!H(r.cwd)){const u=r.fork_from!=null?`Restore ${r.cwd}, then revive the fork normally with \`crtr node lifecycle revive ${e}\`.`:r.managed_worktree?.state==="open"?"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon recovery.":`Recreate ${r.cwd}, or repair it with \`crtr node config --cwd <path> --node ${e}\`; durable node work resumes in a fresh conversation. Then retry \`crtr node lifecycle revive ${e}\`.`;throw new E({error:"cwd_missing",message:`${e} cannot be revived \u2014 its recorded cwd no longer exists: ${r.cwd}`,next:u})}return{blaxelEnvironment:i,remoteMachine:t}}s(yr,"assertRecordedCwdExists");function pi(e,r){const i=r.managed_worktree;if(!(i?.state!=="closed"||i.cleanup!=="complete"||r.cwd!==i.path))throw new E({error:"checkout_removed",message:`${e} cannot be revived \u2014 cleanup removed its checkout ${i.path} and branch ${i.branch}`,next:`Start a new node in ${i.repo_root}.`})}s(pi,"assertCheckoutNotRemoved");async function kr(e,r,i){const t=wr(r.cwd,r.profile_id).plans.get("node:start")??[];await hr(t,{node:{id:e,name:r.name,kind:r.kind,mode:r.mode,lifecycle:r.lifecycle,cwd:r.cwd,nodeDir:await fr(e),contextDir:await lr(e),jobDir:cr(e)},runtime:{isBirth:i,canvasHome:sr(),profile:r.profile_id??null}})}s(kr,"runNodeStartHooks");async function gr(e,r,i){const{blaxelEnvironment:t,remoteMachine:n}=await yr(e,r),u=t!==null||n;r.host_kind!=="broker"&&(await F(e,{host_kind:"broker"}),r.host_kind="broker"),r.review_binding!=null&&!await nr(e)&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await U(e),r.pi_session_id=null,r.pi_session_file=null);const m=r.fork_from!=null&&r.pi_session_id==null,o=r.fork_source_file;if(m&&(typeof o!="string"||!fe(o)))throw new E({error:"fork_source_invalid",message:`${e} cannot be revived \u2014 its resolved fork source file is missing or invalid.`,next:`Restore the node's fork source metadata, then retry \`crtr node lifecycle revive ${e}\`.`});const w=m&&typeof o=="string";if(w&&!await re(o))throw new E({error:"fork_from_missing",message:`${e} cannot be revived \u2014 its fork source no longer exists: ${o}`,next:`Restore ${o}, or update the node's fork source, then retry \`crtr node lifecycle revive ${e}\`.`});const{automaticReviveCap:ae}=P();if(t!==null){const c=await Le(t);if(c.state==="pending")throw new Me(t,c.error)}const oe=t!==null?X("blaxel"):n?X("machine"):Pe;let f;try{f=await he(e,{daemonEpoch:Z().epoch(),cap:ae,...t!==null?{runner:"blaxel",release:Q()}:n?{runner:"machine",release:Q()}:{}})}catch(c){if(c instanceof ze)throw I(c.cap,c.live);if(c instanceof pe)return{window:null,session:r.tmux_session??null,resumed:!1,outcome:"already-live"};throw c}try{r.cycles=(r.cycles??0)+1,await F(e,{cycles:r.cycles});const S=r.intent==="refresh"||r.cycle_pending===!0?!1:i.resume,p=w?{}:await vr(e,r,S,!u),g=p.resumeSessionPath!==void 0,B=g&&p.newCycle===!0,v=g&&!B,D=!g&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&await _r(e),$=v&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&!await Xe(e)&&!await dr(p.resumeSessionPath)?(await x(e))?.trim():void 0,T=$!==void 0&&$!=="",se=w||D||T,M=r.cycle_pending===!0||B;await F(e,{cycle_pending:M}),r.cycle_pending=M,!w&&!g&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await U(e),r.pi_session_id=null,r.pi_session_file=null);let l,h=null;const C=s(()=>({type:"runtime",kind:"kickoff",...r.spawned_by!=null&&r.spawned_by!==""?{spawnedBy:r.spawned_by}:{}}),"birthOrigin");if(w){const a=await x(e),N=_(o);if(N===null)throw new Error(`invalid fork source ${o}`);const ce=(await d().header(await d().fork(N,e))).path;l=y(r,{resumeSessionPath:ce,...a!=null&&a!==""?{prompt:a}:{}}),a!=null&&a!==""&&(h=C()),await qe(e,(await Ze(o))?.node_id??null)}else if(T)l=y(r,{...p,prompt:$}),h=C(),await V(l,r);else if(v)l=y(r,{...p,...i.wakeReason==="runtime-restart-abort"?{prompt:Se}:{}}),i.wakeReason==="runtime-restart-abort"&&(h={type:"runtime",kind:"restart-continuation"});else if(D){const a=(await x(e))?.trim();l=y(r,a!==void 0&&a!==""?{prompt:a}:{}),a!==void 0&&a!==""&&(h=C(),await V(l,r)),await ee(e)}else{const a=await Re(r,f);l=y(r,{...p,prompt:await be(r,a,i.wakeReason==="runtime-restart-abort"?void 0:i.wakeReason)}),r.run_id&&a.unreadMessageIds?.length&&(l.env.CRTR_KICKOFF_MESSAGE_IDS=JSON.stringify(a.unreadMessageIds)),h=i.wakeReason!==void 0&&i.wakeReason!=="runtime-restart-abort"?{type:"runtime",kind:"wake",wake:i.wakeReason}:{type:"runtime",kind:"revive",cycle:r.cycles??0},await ee(e)}l.env={...l.env,CRTR_SUBTREE:await Ie(e)},h!==null&&(l.env[Ce]=$e(h)),r.status==="done"&&r.last_settled_at!=null&&await Qe(e,r.last_settled_at),await O(e,r.intent==="refresh"?"refresh-launch":"revive"),(await Ye(e))?.op!=="conversation_write_failed"&&await Ve(e,{preserveEpisode:!0});const L=await je(e);i.recovery!==!0&&i.viewerAttach!==!0&&await ke(e),await ur(e,r.grantee),await kr(e,r,se),l.env={...l.env,CRTR_EXECUTION_ID:f};const z=await Fe(e,l,r.cwd);await Ge(f,z);let b;try{const a=await He(e);if(b=await oe.start({executionId:f,nodeId:e,attempt:a?.attempt??1,release:a?.release??"",launchJson:z,cwd:r.cwd,resuming:v}),!u&&b.pid===null)throw new Error(`broker host returned no pid for ${e}`)}catch(a){if(a instanceof Y)throw a;try{await O(e,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:a instanceof Error?a.message:String(a)}}}),await ge(e,"notice.crash",`Child crashed \u2014 ${ye(r)} (${e}) failed to relaunch and is now dead: ${a.message}
|
|
2
2
|
|
|
3
|
-
It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`,{reason:"child-crashed",child:e})}catch{}throw await
|
|
3
|
+
It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`,{reason:"child-crashed",child:e})}catch{}throw await A(f,{reason:"launch_failed"}),new Error(`[broker] refusing to revive ${e}: ${a.message}`)}if(await ve(e,new Date().toISOString()),u)return await K(e),{window:null,session:r.tmux_session??null,resumed:v,faultExplanation:L.explanation,outcome:"launched"};if(await de(f,e,b.pid)==="shutdown")throw await A(f,{reason:"superseded"}),Ne.teardown(e),new Error(`[broker] refusing to revive ${e}: execution was superseded during launch`);return await K(e),{window:null,session:r.tmux_session??null,resumed:v,launch:b,faultExplanation:L.explanation,outcome:"launched"}}catch(c){throw c instanceof Y&&c.sent||(await A(f,{reason:"launch_failed"}),await Be(f,c).catch(S=>{W({level:"warn",event:"broker.launch_failure.unrecorded",node_id:e,error:S})})),c}}s(gr,"launchRevive");export{pi as assertCheckoutNotRemoved,yr as assertRecordedCwdExists,hi as decideAttachRevive,fi as hasFreshGroundState,pr as resumeArgs,wi as reviveNode,kr as runNodeStartHooks};
|
|
@@ -22,6 +22,9 @@ export declare const RECIPE_PI_AGENT_DIR = "/var/lib/crtr/recipe-pi-agent";
|
|
|
22
22
|
export declare const BLAXEL_TOML_FILE = "blaxel.toml";
|
|
23
23
|
export declare const BLAXEL_TOML = "[build]\nslim = false\n";
|
|
24
24
|
export declare const SETUP_SCRIPT_FILE = "recipe-setup.sh";
|
|
25
|
+
/** The run user's npmrc. pnpm 12 ignores an env-expanded `_authToken` in a repository's `.npmrc`, so the GitHub Packages auth line lives here; it names the
|
|
26
|
+
* variable, never its value. `store-dir` pins one pnpm store in the image that every repository's `pnpm install` links from. */
|
|
27
|
+
export declare const RUN_USER_NPMRC: string[];
|
|
25
28
|
export declare const REPOS_DIR = "repos";
|
|
26
29
|
/** Where the image keeps the setup script's output, and its exit status when it failed. `sandbox-start.mjs` reads both (it derives them from `/work/.crtr`). */
|
|
27
30
|
export declare const SETUP_LOG_FILE = "/work/.crtr/setup.log";
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var
|
|
1
|
+
var j=Object.defineProperty;var c=(t,r)=>j(t,"name",{value:r,configurable:!0});import{spawn as q}from"node:child_process";import{constants as D,lstatSync as z,mkdirSync as W,readFileSync as J,readdirSync as X,readlinkSync as V,rmSync as Z,writeFileSync as b}from"node:fs";import{join as g,relative as Q}from"node:path";import{crc32 as tt,deflateRawSync as et}from"node:zlib";import{BlaxelApiError as rt}from"./client.js";const nt="public.ecr.aws/docker/library/node:24-alpine",ot="ghcr.io/blaxel-ai/sandbox:latest",p="crtr",B="/var/lib/crtr/recipe-pi-agent",st="blaxel.toml",it=`[build]
|
|
2
2
|
slim = false
|
|
3
|
-
`,
|
|
4
|
-
`).map(r=>r.trim()).filter(r=>r!==""),"lines")
|
|
5
|
-
`)}c(
|
|
6
|
-
`,{mode:384}),t.recipe.setup_script!==null&&t.recipe.setup_script.trim()!==""&&b(
|
|
3
|
+
`,at="1.1.0",_="recipe-setup.sh",ct=["@northlight-systems:registry=https://npm.pkg.github.com","//npm.pkg.github.com/:_authToken=${NODE_AUTH_TOKEN}",`store-dir=/home/${p}/.local/share/pnpm/store`],G=c(()=>`printf '%s\\n' ${ct.map(t=>`'${t}'`).join(" ")} > /home/${p}/.npmrc`,"writeRunUserNpmrc"),R="repos",U="/work/.crtr/setup.log",M="/work/.crtr/setup-failed",C="/usr/local/bin/gh",lt=["#!/bin/sh",'token=$(printf "protocol=https\\nhost=github.com\\n\\n" | git credential fill 2>/dev/null | sed -n "s/^password=//p")','[ -n "$token" ] && export GH_TOKEN="$token"','exec /usr/bin/gh "$@"'],N=c(t=>`'${t.replace(/'/g,"'\\''")}'`,"shellQuote"),pt=c(t=>(t??"").split(`
|
|
4
|
+
`).map(r=>r.trim()).filter(r=>r!==""),"lines"),E=c((t,r)=>`RUN { ${r}; } >> ${U} 2>&1 || echo ${N(t)} "exited $?" >> ${M}`,"guarded");function ut(t,r,i=!1){const s=pt(t.pi_packages),a=t.setup_script!==null&&t.setup_script.trim()!=="",n=[`FROM ${nt}`,"RUN apk add --no-cache bash git curl ripgrep github-cli",`RUN printf '%s\\n' ${lt.map(N).join(" ")} > ${C} && chmod 755 ${C}`,`COPY --from=${ot} /sandbox-api /usr/local/bin/sandbox-api`,`RUN adduser -D -h /home/${p} -s /bin/sh ${p} && mkdir -p /work/.crtr ${B} && chown -R ${p} /work /var/lib/crtr`],e=[`${n[0]} AS build`,...i?["ARG NODE_AUTH_TOKEN"]:[],...n.slice(1),`RUN rm -f ${M} ${U}`,E("npm install -g pnpm","npm install -g pnpm && mkdir -p /var/lib/postgresql")];t.repositories.length>0&&e.push(`COPY --chown=${p} ${R}/ /work/`),s.length>0&&e.push(E("npm install pi",`npm install -g @earendil-works/pi-coding-agent@${at}`)),a&&e.push(`COPY ${_} /tmp/${_}`),e.push("WORKDIR /work"),e.push(`RUN ${G()}`);for(const o of t.repositories)e.push(`RUN if [ -f /work/${o.name}/pnpm-lock.yaml ]; then cd /work/${o.name} && HOME=/home/${p} pnpm fetch >> ${U} 2>&1 || echo 'pnpm fetch ${o.name} failed' >> ${U}; fi`);for(const o of s)e.push(E(`pi install ${o}`,`HOME=/var/lib/crtr PI_CODING_AGENT_DIR=${B} pi install ${N(o)}`));a&&e.push(E("setup script",`bash /tmp/${_}`)),e.push(E("finalize",`echo ${Math.trunc(r)} > /work/.crtr/recipe-revision && chown -R ${p} /work /home/${p} /var/lib/crtr`)),e.push("",...n);for(const o of["/work",`/home/${p}`,"/var/lib/crtr"])e.push(`COPY --from=build --chown=${p}:${p} ${o} ${o}`);for(const o of["/usr/local","/usr","/etc","/lib"])e.push(`COPY --from=build ${o} ${o}`);return e.push("COPY --from=build /var/lib/postgresql /var/lib/postgresql"),e.push("RUN if getent passwd postgres >/dev/null; then chown -R postgres:postgres /var/lib/postgresql; fi"),i&&e.push("RUN rm -f /work/.npmrc",`RUN ${G()} && chown ${p}:${p} /home/${p}/.npmrc`),e.push(`USER ${p}`,"WORKDIR /work",'ENTRYPOINT ["/usr/local/bin/sandbox-api"]',""),e.join(`
|
|
5
|
+
`)}c(ut,"recipeDockerfile");const dt=c((t,r,i)=>new Promise((s,a)=>{const n=q("git",t,{cwd:i,env:{...process.env,...r,GIT_TERMINAL_PROMPT:"0"},stdio:["ignore","ignore","pipe"]});let e="";n.stderr.on("data",o=>{e+=o.toString()}),n.on("error",a),n.on("close",o=>{o===0?s():a(new Error(`git ${t[0]} failed (${o}): ${e.slice(0,300)}`))})}),"runGit");async function _t(t){const r=t.git??dt,i=t.packagesToken??null,s=t.cloneUrl??(n=>`https://github.com/${n}.git`);W(g(t.dir,R),{recursive:!0});const a=t.token===null?{}:{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:"http.https://github.com/.extraheader",GIT_CONFIG_VALUE_0:`AUTHORIZATION: basic ${Buffer.from(`x-access-token:${t.token}`).toString("base64")}`};for(const n of t.recipe.repositories){if(!/^[A-Za-z0-9._-]+$/.test(n.name)||n.name==="."||n.name==="..")throw new Error(`repository name ${JSON.stringify(n.name)} is not a plain directory name`);await r(["clone","--quiet","--branch",n.default_branch,s(n.github_full_name),g(R,n.name)],a,t.dir)}b(g(t.dir,st),it),b(g(t.dir,"Dockerfile"),ut(t.recipe,t.revision,i!==null)),i!==null&&b(g(t.dir,".env.build"),`NODE_AUTH_TOKEN=${i}
|
|
6
|
+
`,{mode:384}),t.recipe.setup_script!==null&&t.recipe.setup_script.trim()!==""&&b(g(t.dir,_),t.recipe.setup_script.endsWith(`
|
|
7
7
|
`)?t.recipe.setup_script:`${t.recipe.setup_script}
|
|
8
|
-
`)}c(
|
|
8
|
+
`)}c(_t,"prepareBuildDir");function F(t,r,i){for(const s of X(r).sort()){const a=g(r,s),n=z(a),e=Q(t,a).split("\\").join("/");n.isDirectory()?F(t,a,i):n.isSymbolicLink()?i.push({name:e,data:Buffer.from(V(a)),mode:D.S_IFLNK|511}):n.isFile()&&i.push({name:e,data:J(a),mode:D.S_IFREG|n.mode&511})}}c(F,"walk");function ht(t){const r=[];F(t,t,r);const i=[],s=[];let a=0;for(const o of r){const d=Buffer.from(o.name),$=et(o.data),I=tt(o.data),u=Buffer.alloc(30);u.writeUInt32LE(67324752,0),u.writeUInt16LE(20,4),u.writeUInt16LE(2048,6),u.writeUInt16LE(8,8),u.writeUInt32LE(33,12),u.writeUInt32LE(I,14),u.writeUInt32LE($.length,18),u.writeUInt32LE(o.data.length,22),u.writeUInt16LE(d.length,26),i.push(u,d,$);const l=Buffer.alloc(46);l.writeUInt32LE(33639248,0),l.writeUInt16LE(788,4),l.writeUInt16LE(20,6),l.writeUInt16LE(2048,8),l.writeUInt16LE(8,10),l.writeUInt32LE(33,14),l.writeUInt32LE(I,16),l.writeUInt32LE($.length,20),l.writeUInt32LE(o.data.length,24),l.writeUInt16LE(d.length,28),l.writeUInt32LE(o.mode<<16>>>0,38),l.writeUInt32LE(a,42),s.push(l,d),a+=u.length+d.length+$.length}const n=Buffer.concat(s),e=Buffer.alloc(22);return e.writeUInt32LE(101010256,0),e.writeUInt16LE(r.length,8),e.writeUInt16LE(r.length,10),e.writeUInt32LE(n.length,12),e.writeUInt32LE(a,16),Buffer.concat([...i,n,e])}c(ht,"zipDirectory");async function k(t,r,i,s,a=[]){const n=`${t.controlUrl??"https://api.blaxel.ai/v0"}${i}`,e=await(t.fetch??fetch)(n,{method:r,headers:{authorization:`Bearer ${t.apiKey}`,"x-blaxel-workspace":t.workspace,"content-type":"application/json"},...s===void 0?{}:{body:JSON.stringify(s)}}),o=await e.text();let d=null;if(o!=="")try{d=JSON.parse(o)}catch{d={raw:o}}if(!e.ok&&!a.includes(e.status))throw new rt(e.status,null,`Blaxel ${r} ${n} failed (${e.status}): ${o.slice(0,300)}`);return{status:e.status,headers:e.headers,json:d}}c(k,"api");async function H(t,r){const{status:i,json:s}=await k(t,"GET",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404]);return i===404?null:s}c(H,"getImage");async function Ut(t,r){await k(t,"DELETE",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404])}c(Ut,"deleteImage");const ft=60*6e4;async function xt(t,r,i,s={}){const a=s.sleep??(f=>new Promise(h=>setTimeout(h,f))),n=s.now??Date.now,e=n(),o=await H(t,r),d=new Set((o?.spec?.tags??[]).map(f=>f.name)),$=c(f=>(f?.metadata?.events??[]).map(h=>Date.parse(h.time??"")).filter(h=>!Number.isNaN(h)),"eventTimes"),I=Math.max(-1/0,...$(o)),l=(await k(t,"POST","/images",{resourceType:"sandbox",name:r})).headers.get("x-blaxel-upload-url");if(l===null)throw new Error(`Blaxel gave no upload URL for image ${r}`);const x=await(t.fetch??fetch)(l,{method:"PUT",headers:{"content-type":"application/zip"},body:new Uint8Array(ht(i))});if(!x.ok)throw new Error(`uploading the build context of image ${r} failed (${x.status}): ${(await x.text()).slice(0,300)}`);const T=s.timeoutMs??ft,K=e+T;let O=null;for(;;){const f=await H(t,r),h=f?.metadata?.status,y=$(f).filter(m=>m>I).sort((m,L)=>m-L);if(h==="BUILT"&&y.length>=2){O??=n();const m=(f?.spec?.tags??[]).filter(w=>w.name!==void 0),L=y[0],S=c(w=>Date.parse(w??"")>=L,"touchedSince"),A=m.filter(w=>!d.has(w.name)||S(w.createdAt)||S(w.updatedAt)),v=n()-O>=(s.tagGraceMs??6e4),P=(A.length>0?A:v?m:[]).sort((w,Y)=>(Y.updatedAt??"").localeCompare(w.updatedAt??""))[0]?.name;if(P!==void 0)return{ref:`sandbox/${r}:${P}`,buildMs:n()-e};if(v)throw new Error(`Blaxel built image ${r} but no tag appeared`)}if(h==="FAILED"||h==="TERMINATED"){const m=f?.metadata?.events??[];throw new Error(`building image ${r} ${h.toLowerCase()}: ${m[m.length-1]?.message??"no message"}`)}if(n()>K)throw new Error(`building image ${r} did not finish within ${T} ms (last status ${h??"none"})`);await a(s.pollMs??3e3)}}c(xt,"buildImage");const Lt=c(t=>`env-${t}`,"environmentImageName");function Rt(t){Z(t,{recursive:!0,force:!0})}c(Rt,"removeBuildDir");export{it as BLAXEL_TOML,st as BLAXEL_TOML_FILE,ft as BUILD_TIMEOUT_MS,C as GH_WRAPPER_PATH,nt as NODE_BASE_IMAGE,B as RECIPE_PI_AGENT_DIR,R as REPOS_DIR,p as RUN_USER,ct as RUN_USER_NPMRC,ot as SANDBOX_API_IMAGE,M as SETUP_FAILED_FILE,U as SETUP_LOG_FILE,_ as SETUP_SCRIPT_FILE,xt as buildImage,Ut as deleteImage,Lt as environmentImageName,H as getImage,_t as prepareBuildDir,ut as recipeDockerfile,Rt as removeBuildDir,ht as zipDirectory};
|