@north-light/cli 0.3.500 → 0.3.502

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/api/contract.d.ts +1 -1
  2. package/dist/api/contract.js +1 -1
  3. package/dist/api/dto/grants.d.ts +2 -2
  4. package/dist/api/dto/run-events.d.ts +3 -1
  5. package/dist/builtin-memory/crouter-sdk/release-notes.md +11 -1
  6. package/dist/clients/attach/viewer.js +433 -433
  7. package/dist/core/canvas/migrations.js +1 -1
  8. package/dist/core/fault-classifier.d.ts +2 -0
  9. package/dist/core/fault-classifier.js +1 -1
  10. package/dist/core/grants/mirror.d.ts +16 -2
  11. package/dist/core/grants/mirror.js +3 -3
  12. package/dist/core/grants/sync.js +1 -1
  13. package/dist/core/llm/app-rungs.d.ts +16 -0
  14. package/dist/core/llm/app-rungs.js +1 -0
  15. package/dist/core/llm/run.d.ts +10 -1
  16. package/dist/core/llm/run.js +2 -2
  17. package/dist/core/model-routes.d.ts +2 -0
  18. package/dist/core/model-routes.js +1 -1
  19. package/dist/core/peer/ingest.d.ts +5 -1
  20. package/dist/core/peer/ingest.js +1 -1
  21. package/dist/core/peer/outbox-store.d.ts +5 -1
  22. package/dist/core/peer/outbox-store.js +5 -4
  23. package/dist/core/providers/token-cache.d.ts +1 -1
  24. package/dist/core/providers/token-cache.js +1 -1
  25. package/dist/core/runs/operations.js +5 -5
  26. package/dist/core/runtime/broker/model-adapter.js +2 -2
  27. package/dist/core/runtime/launch.d.ts +13 -1
  28. package/dist/core/runtime/launch.js +1 -1
  29. package/dist/core/runtime/spawn.d.ts +4 -1
  30. package/dist/core/runtime/spawn.js +2 -2
  31. package/dist/daemon/api/app-listener.js +13 -13
  32. package/dist/daemon/api/handlers/llm.js +3 -3
  33. package/dist/daemon/api/handlers/nodes.js +1 -1
  34. package/dist/daemon/api/handlers/runs.js +1 -1
  35. package/dist/daemon/cron/armed-context.js +1 -1
  36. package/dist/daemon/peer/outbox.js +1 -1
  37. package/dist/daemon/reconcilers/node-lifecycle/freeze-lane.js +1 -1
  38. package/dist/daemon/runs/append-section.js +2 -2
  39. package/docs/sdk/release-notes.md +11 -1
  40. package/package.json +2 -2
  41. package/packages/crouter-identity/package.json +1 -1
  42. package/runtime.lock.json +12 -12
@@ -1,12 +1,12 @@
1
- var Ne=Object.defineProperty;var m=(e,t)=>Ne(e,"name",{value:t,configurable:!0});import{prepared as w}from"../sqlite-statements.js";import{coveredByAny as ve}from"../../shared/env.js";import{createHash as J}from"node:crypto";import{ApiError as be}from"../../api/errors.js";import{CrtrError as Oe}from"../errors.js";import{isAbsolute as Y,relative as De,resolve as Me,sep as Ie,join as Te}from"node:path";import{SessionManager as Ae}from"@earendil-works/pi-coding-agent";import{covers as W}from"@north-light/identity";import{openDb as G,withCanvasWrite as L}from"../canvas/db.js";import{deleteNodeWithOwned as Le}from"../graph/deletion.js";import{getById as Ce}from"../graph/objects.js";import{repairRunConversations as X}from"../canvas/sessions.js";import{getNode as N,nodeFiles as xe,removeNodeFiles as ke,updateNode as We}from"../canvas/canvas.js";import{fullName as Fe}from"../canvas/labels.js";import{renameWindow as He}from"../runtime/placement.js";import{liveExecutionForNode as z}from"../canvas/executions.js";import{conversationStore as Q,isConversationNotFound as qe}from"../conversation-store/index.js";import{enqueueNodeMail as Ue}from"../feed/messages.js";import{newestReportBody as Pe}from"../feed/reports.js";import{ensureAppProfile as Be,loadExactProfileManifest as $e}from"../profiles/manifest.js";import{stopNodeSandboxes as V}from"../spaces/stop.js";import{BrokerUnreachableError as je}from"../runtime/broker-request.js";import{interruptLive as Je}from"../runtime/interactive-deliver.js";import{isBrokerLive as Z}from"../runtime/model-swap.js";import{newNodeId as Ye}from"../runtime/nodes.js";import{writeGoal as Ge}from"../runtime/kickoff.js";import{reviveNode as F}from"../runtime/revive.js";import{spawnChildPrepared as Xe}from"../runtime/spawn.js";import{isPortableModelToken as ze}from"../runtime/launch.js";import{parseDurationMs as Qe}from"../wake.js";import{expandModelCandidates as Ve,parseModelSpec as Ze}from"../model-routes.js";import{isolatedBrokerLauncherAvailable as Ke}from"../runtime/host.js";import{resolveRunKind as et}from"../runtime/launch-target.js";import{cycleAwareMessages as tt}from"../runtime/session-cycles.js";import{originFor as K}from"../runtime/stamp/protocol.js";import{readOutputRequest as nt,readOutputResult as ee}from"../runtime/structured-output.js";import{admitLegacyStructuredOutput as te}from"../../daemon/structured-requests/sidecar.js";import{runSchemaRepromptPending as st}from"../runtime/stop-guard.js";import{toRunOutcomeDTO as rt}from"../../daemon/api/map.js";import{openAssistantMessageStartSequence as ot}from"../../daemon/runs/observer.js";import{closeNode as ne}from"../runtime/close.js";import{parseScope as it}from"@north-light/identity";import{appendRunEvent as se,subscribeRunEvents as dt}from"./events.js";import{runActivity as at}from"./activity.js";import{cancelOpenQuestions as re,openQuestionIds as oe}from"./questions.js";import{appSpace as H}from"../layout.js";import{ensureAppSpace as ct}from"../spaces/space.js";import{assertUploadsUsable as ie,resolveStorageUrls as ut}from"../storage/attachments.js";import{storageClient as mt,storageConfig as lt}from"../storage/client.js";import{deleteUploadRow as ft,insertUploadUses as de,releaseRunUploads as _t}from"../storage/tables.js";import{abortProviderCalls as ae}from"../providers/inflight.js";const ce=m((e,t,r)=>ut(t,e,r),"defaultResolver"),pt=3e3;function wn(e){return Number(w(e,"UPDATE idempotency_keys SET grantee = 'app:terminal' WHERE grantee = 'user:local'").run().changes)}m(wn,"rewriteLocalIdempotencyGrantee");class S extends Error{static{m(this,"RunError")}status;code;param;details;scope;retryable;constructor(t,r,s,i,c,d,o=t===503){super(s),this.status=t,this.code=r,this.param=i,this.details=c,this.scope=d,this.retryable=o}}const R=m((e,t)=>new S(400,"invalid_request",e,t),"invalid"),q=m(()=>new S(404,"not_found","run not found"),"missing"),U=m(()=>({input_tokens:0,output_tokens:0,cache_read_tokens:0,cache_write_tokens:0,cost_usd:0}),"usage"),O=m(()=>G(),"db");function C(e,t,r=!1){const s=N(e);if(!s||s.parent!==null||s.run_id!==e||s.grantee!==t||!r&&s.deleting_at)throw q();return s}m(C,"ownedRun");const P=["waiting_on_user","idle","settled"];function I(e){if(e.status==="canceled"||e.status==="dead"||e.status==="done"&&e.intent!=="parked")return"settled";const t=w(O(),`SELECT 1 FROM node_rows n WHERE n.run_id = ? AND n.status = 'active' AND
1
+ var ve=Object.defineProperty;var m=(e,t)=>ve(e,"name",{value:t,configurable:!0});import{prepared as w}from"../sqlite-statements.js";import{coveredByAny as be}from"../../shared/env.js";import{createHash as G}from"node:crypto";import{ApiError as Oe}from"../../api/errors.js";import{CrtrError as De}from"../errors.js";import{isAbsolute as X,relative as Me,resolve as Ie,sep as Te,join as Ae}from"node:path";import{SessionManager as Le}from"@earendil-works/pi-coding-agent";import{covers as F}from"@north-light/identity";import{openDb as z,withCanvasWrite as C}from"../canvas/db.js";import{deleteNodeWithOwned as Ce}from"../graph/deletion.js";import{getById as xe}from"../graph/objects.js";import{repairRunConversations as Q}from"../canvas/sessions.js";import{getNode as v,nodeFiles as ke,removeNodeFiles as We,updateNode as Fe}from"../canvas/canvas.js";import{fullName as He}from"../canvas/labels.js";import{renameWindow as qe}from"../runtime/placement.js";import{liveExecutionForNode as V}from"../canvas/executions.js";import{conversationStore as Z,isConversationNotFound as Ue}from"../conversation-store/index.js";import{enqueueNodeMail as Pe}from"../feed/messages.js";import{newestReportBody as Be}from"../feed/reports.js";import{ensureAppProfile as $e,loadExactProfileManifest as je}from"../profiles/manifest.js";import{stopNodeSandboxes as K}from"../spaces/stop.js";import{BrokerUnreachableError as Je}from"../runtime/broker-request.js";import{interruptLive as Ye}from"../runtime/interactive-deliver.js";import{isBrokerLive as ee}from"../runtime/model-swap.js";import{newNodeId as Ge}from"../runtime/nodes.js";import{writeGoal as Xe}from"../runtime/kickoff.js";import{reviveNode as H}from"../runtime/revive.js";import{spawnChildPrepared as ze}from"../runtime/spawn.js";import{isPortableModelToken as Qe}from"../runtime/launch.js";import{parseDurationMs as Ve}from"../wake.js";import{expandModelCandidates as Ze,parseModelSpec as Ke}from"../model-routes.js";import{payerOfGrant as q}from"../grants/mirror.js";import{isolatedBrokerLauncherAvailable as et}from"../runtime/host.js";import{resolveRunKind as tt}from"../runtime/launch-target.js";import{cycleAwareMessages as nt}from"../runtime/session-cycles.js";import{originFor as te}from"../runtime/stamp/protocol.js";import{readOutputRequest as st,readOutputResult as ne}from"../runtime/structured-output.js";import{admitLegacyStructuredOutput as se}from"../../daemon/structured-requests/sidecar.js";import{runSchemaRepromptPending as rt}from"../runtime/stop-guard.js";import{toRunOutcomeDTO as ot}from"../../daemon/api/map.js";import{openAssistantMessageStartSequence as it}from"../../daemon/runs/observer.js";import{closeNode as re}from"../runtime/close.js";import{parseScope as dt}from"@north-light/identity";import{appendRunEvent as oe,subscribeRunEvents as at}from"./events.js";import{runActivity as ct}from"./activity.js";import{cancelOpenQuestions as ie,openQuestionIds as de}from"./questions.js";import{appSpace as U}from"../layout.js";import{ensureAppSpace as ut}from"../spaces/space.js";import{assertUploadsUsable as ae,resolveStorageUrls as mt}from"../storage/attachments.js";import{storageClient as lt,storageConfig as ft}from"../storage/client.js";import{deleteUploadRow as _t,insertUploadUses as ce,releaseRunUploads as pt}from"../storage/tables.js";import{abortProviderCalls as ue}from"../providers/inflight.js";const me=m((e,t,r)=>mt(t,e,r),"defaultResolver"),gt=3e3;function yn(e){return Number(w(e,"UPDATE idempotency_keys SET grantee = 'app:terminal' WHERE grantee = 'user:local'").run().changes)}m(yn,"rewriteLocalIdempotencyGrantee");class S extends Error{static{m(this,"RunError")}status;code;param;details;scope;retryable;constructor(t,r,n,i,c,d,o=t===503){super(n),this.status=t,this.code=r,this.param=i,this.details=c,this.scope=d,this.retryable=o}}const R=m((e,t)=>new S(400,"invalid_request",e,t),"invalid"),P=m(()=>new S(404,"not_found","run not found"),"missing"),B=m(()=>({input_tokens:0,output_tokens:0,cache_read_tokens:0,cache_write_tokens:0,cost_usd:0}),"usage"),D=m(()=>z(),"db");function x(e,t,r=!1){const n=v(e);if(!n||n.parent!==null||n.run_id!==e||n.grantee!==t||!r&&n.deleting_at)throw P();return n}m(x,"ownedRun");const $=["waiting_on_user","idle","settled"];function T(e){if(e.status==="canceled"||e.status==="dead"||e.status==="done"&&e.intent!=="parked")return"settled";const t=w(D(),`SELECT 1 FROM node_rows n WHERE n.run_id = ? AND n.status = 'active' AND
2
2
  (n.last_settled_at IS NULL OR EXISTS (
3
3
  SELECT 1 FROM run_events e WHERE e.run_id = ? AND e.node_id = n.node_id AND e.type = 'node.turn.started'
4
4
  AND e.sequence_number > COALESCE((SELECT MAX(c.sequence_number) FROM run_events c
5
5
  WHERE c.run_id = e.run_id AND c.node_id = e.node_id AND c.type = 'node.turn.completed'), 0)
6
- )) LIMIT 1`).get(e.node_id,e.node_id),r=w(O(),"SELECT 1 FROM deliveries WHERE destination_id IN (SELECT node_id FROM nodes WHERE run_id = ?) AND state IN ('armed', 'pending') AND wake = 1 LIMIT 1").get(e.node_id);return t||r||!e.last_settled_at||st(e)?"running":oe(e.node_id).length?"waiting_on_user":"idle"}m(I,"runStatus");function hn(e){const t=N(e);return t!==null&&I(t)==="running"}m(hn,"runIsRunning");function A(e){X(e.node_id),e=N(e.node_id)??e;const t=I(e),r=t==="settled"?[]:oe(e.node_id),s=Pe(e.node_id)||void 0,i=t==="settled"?rt(e):null,c=i?.kind==="result"?ee(e.node_id,e.grantee):void 0;return{run_id:e.node_id,name:e.name,status:t,...i?{outcome:i}:{},...c===void 0?{}:{result:c},...s!==void 0?{last_report:s}:{},pending_question_ids:r,...e.last_turn_error_json?{last_turn_error:JSON.parse(e.last_turn_error_json)}:{},usage:JSON.parse(e.usage_json??JSON.stringify(U())),payer:"user",scopes:e.scopes,metadata:e.metadata_json?JSON.parse(e.metadata_json):{},created_at:e.created,...t==="settled"&&e.outcome_at?{settled_at:e.outcome_at}:{},latest_sequence:(e.event_cursor??1)-1,last_activity_at:e.last_activity_at,activity:at(e.node_id,t)}}m(A,"runObject");const B=864e5,ue=255;function yn(e){if(e!==void 0){if(typeof e!="string"||!e.length||e.length>ue)throw R(`Idempotency-Key must be 1-${ue} characters`);return e}}m(yn,"idempotencyKeyOf");function x(e,t,r,s=G()){const i=w(s,"SELECT body_hash, run_id, response_json, created_at FROM idempotency_keys WHERE grantee = ? AND key = ?").get(e,t);if(!(!i||Date.now()-Date.parse(i.created_at)>=B)){if(i.body_hash!==r)throw new S(409,"idempotency_conflict","key used with a different request");return{run_id:i.run_id,response:JSON.parse(i.response_json)}}}m(x,"findIdempotent");function me(e,t,r,s,i,c,d){w(e,"DELETE FROM idempotency_keys WHERE grantee = ? AND key = ? AND created_at <= ?").run(t,r,new Date(Date.now()-B).toISOString()),w(e,"INSERT INTO idempotency_keys (grantee, key, body_hash, run_id, response_json, created_at) VALUES (?, ?, ?, ?, ?, ?)").run(t,r,s,i,JSON.stringify(c),d)}m(me,"recordIdempotent");function Rn(e=Date.now()){return L(t=>Number(w(t,"DELETE FROM idempotency_keys WHERE created_at <= ?").run(new Date(e-B).toISOString()).changes))}m(Rn,"pruneExpiredIdempotencyKeys");function le(e,t,r,s,i){const c=s.text;let d=0;return{messageId:Ue(t,{kind:"message",label:c.slice(0,120),senderNodeId:"human",senderName:r,bodyJson:i?{body:c}:{body:c,start_turn:!1},urgency:i?"normal":"deferred",wake:i?1:0,withinEnqueue:m((a,_)=>{s.uses.length&&(ie(r,s.uses,a),de(s.uses.map(({upload_id:y,path:E})=>({upload_id:y,path:E,run_id:t})),a)),d=se(a,t,t,"node.message.accepted",{message_id:_,start_turn:i}).sequence_number},"withinEnqueue")}).messageId,sequence:d}}m(le,"acceptRunMessage");class fe extends Error{static{m(this,"IdempotentReplay")}winner;constructor(t){super("idempotent replay"),this.winner=t}}const gt=1440*60*1e3;function _e(e){const t=typeof e=="string"?Qe(e):null;if(t===null||!Number.isSafeInteger(t))throw R(`deadline '${String(e)}' is not a duration; use one or more <int>[smhd] parts such as 10m or 1h30m`,"deadline");if(t<=0)throw R("deadline must be greater than zero","deadline");if(t>gt)throw R("deadline must be at most 24h","deadline");return t}m(_e,"parseRunDeadlineMs");async function Sn(e,t,r,s=ce){if(t.isolated&&!Ke())throw new S(503,"isolated_unavailable","isolated runs require the Linux root launcher","isolated");t.deadline!==void 0&&_e(t.deadline);const i=J("sha256").update(JSON.stringify(t)).digest("hex");if(r){const n=x(e.grantee,r,i);if(n){const u=C(n.run_id,e.grantee);return!u.pi_pid&&I(u)==="running"&&(t.output_schema!==void 0&&!u.outcome_at&&nt(u.node_id).state==="absent"&&ee(u.node_id,u.grantee)===void 0&&te(u.node_id,"terminal",t.output_schema),await F(u.node_id,{resume:!0,capacity:"freeze"})),n.response}}await ct(e.grantee);const c=t.profile===void 0?Be(e.grantee):$e(t.profile),d=c.manifest.grantee??"app:terminal";if(d!==e.grantee){const n=`crtr:memory:rw:${d}:profile:${c.profileId}`;if(!e.resolved.some(u=>W(u,n))||t.scopes!==null&&!t.scopes.some(u=>W(u,n)))throw new S(403,"scope_missing",`missing scope ${n}`,"profile",void 0,n)}if(t.model!==void 0){const n=t.model;if(ze(n)){if(n.includes("/")){const u=n.lastIndexOf("/"),h=n.slice(0,u),g=n.slice(u+1);if(["ultra","strong","medium","light"].includes(g)&&Ve({kind:"logical",family:h,strength:g,spec:n},H(e.grantee).files,c.profileId).every(T=>T.family!==h))throw R(`model '${n}' names a model family that is not configured in this daemon`,"model")}}else if(Ze(n)===void 0)throw R(`model '${n}' is not a strength (ultra, strong, medium, light), a family/strength, or a provider/model id`,"model")}const o=Ye(),a=Te(H(e.grantee).nodes,o);if(t.isolated&&t.cwd!==void 0){const n=De(a,Me(t.cwd));if(!Y(t.cwd)||n===".."||n.startsWith(`..${Ie}`)||Y(n))throw R("cwd must be inside the isolated root node folder","cwd")}const _=await s(o,e.grantee,t.prompt),y=_.text;let E;try{E=t.message===void 0?void 0:await s(o,e.grantee,t.message)}catch(n){throw _.cleanup(),n}let p;try{await Xe({kind:et(c),mode:"base",root:!0,rootLifecycle:"resident",readiness:"launch",cwd:t.isolated?t.cwd??a:H(e.grantee).files,profile:c.profileId,prompt:y,nodeId:o,isolated:t.isolated??!1,...t.model===void 0?{}:{model:t.model},...t.deadline===void 0?{}:{deadlineAt:new Date(Date.now()+_e(t.deadline)).toISOString()},...t.scopes===null?{}:{scopes:t.scopes},run:{grantee:e.grantee,sub:e.sub,grant_id:e.grant,client_id:e.client_id,metadata_json:JSON.stringify(t.metadata),run_id:o,event_cursor:1,usage_json:JSON.stringify(U())},withinCreate:m((n,u)=>{if(r){const g=x(e.grantee,r,i,n);if(g)throw new fe(g)}const h=_.uses;if(h.length&&(ie(e.grantee,h,n),de(h.map(({upload_id:g,path:T})=>({upload_id:g,path:T,run_id:o})),n)),Ge(o,y),p={run_id:o,node_id:o,grantee:e.grantee,grant:e.grant,rev:e.rev,scopes:t.scopes,payer:"user",status:"running",created_at:u.created,metadata:t.metadata,sequence_number:0},se(n,o,o,"run.started",{scopes:t.scopes,payer:"user",usage:U()}),E){const g=le(n,o,e.grantee,E,!1);p.message={run_id:o,message_id:g.messageId,sequence_number:g.sequence}}r&&me(n,e.grantee,r,i,o,p,u.created)},"withinCreate")},t.output_schema===void 0?void 0:n=>{te(n,"terminal",t.output_schema)})}catch(n){if(N(o)||(_.cleanup(),E?.cleanup()),n instanceof fe)return n.winner.response;if(t.model!==void 0&&n instanceof Oe&&n.code==="usage")throw R(n.message,"model");if(n instanceof be&&(n.code==="isolated_run"||n.code==="invalid_request")){const u=n.details&&typeof n.details=="object"&&"param"in n.details&&typeof n.details.param=="string"?n.details.param:void 0;throw new S(n.status,n.code,n.message,u)}throw n}if(!p)throw new Error("run creation did not commit");return p}m(Sn,"startRun");function Nn(e,t){let r;if(t.after)try{const o=JSON.parse(Buffer.from(t.after,"base64url").toString());if(!o||typeof o!="object"||!("activity"in o)||typeof o.activity!="string"||!("id"in o)||typeof o.id!="string")throw new Error("invalid cursor");r={activity:o.activity,id:o.id}}catch{throw R("invalid list cursor","after")}const i=O().prepare(`SELECT node_id, COALESCE(last_activity_at, created) AS activity FROM node_rows
6
+ )) LIMIT 1`).get(e.node_id,e.node_id),r=w(D(),"SELECT 1 FROM deliveries WHERE destination_id IN (SELECT node_id FROM nodes WHERE run_id = ?) AND state IN ('armed', 'pending') AND wake = 1 LIMIT 1").get(e.node_id),n=!e.last_settled_at&&e.status!=="done";return t||r||n||rt(e)?"running":de(e.node_id).length?"waiting_on_user":"idle"}m(T,"runStatus");function Rn(e){const t=v(e);return t!==null&&T(t)==="running"}m(Rn,"runIsRunning");function L(e){Q(e.node_id),e=v(e.node_id)??e;const t=T(e),r=t==="settled"?[]:de(e.node_id),n=Be(e.node_id)||void 0,i=t==="settled"?ot(e):null,c=i?.kind==="result"?ne(e.node_id,e.grantee):void 0;return{run_id:e.node_id,name:e.name,status:t,...i?{outcome:i}:{},...c===void 0?{}:{result:c},...n!==void 0?{last_report:n}:{},pending_question_ids:r,...e.last_turn_error_json?{last_turn_error:JSON.parse(e.last_turn_error_json)}:{},usage:JSON.parse(e.usage_json??JSON.stringify(B())),payer:q(e.grant_id),scopes:e.scopes,metadata:e.metadata_json?JSON.parse(e.metadata_json):{},created_at:e.created,...t==="settled"&&e.outcome_at?{settled_at:e.outcome_at}:{},latest_sequence:(e.event_cursor??1)-1,last_activity_at:e.last_activity_at,activity:ct(e.node_id,t)}}m(L,"runObject");const j=864e5,le=255;function Sn(e){if(e!==void 0){if(typeof e!="string"||!e.length||e.length>le)throw R(`Idempotency-Key must be 1-${le} characters`);return e}}m(Sn,"idempotencyKeyOf");function k(e,t,r,n=z()){const i=w(n,"SELECT body_hash, run_id, response_json, created_at FROM idempotency_keys WHERE grantee = ? AND key = ?").get(e,t);if(!(!i||Date.now()-Date.parse(i.created_at)>=j)){if(i.body_hash!==r)throw new S(409,"idempotency_conflict","key used with a different request");return{run_id:i.run_id,response:JSON.parse(i.response_json)}}}m(k,"findIdempotent");function fe(e,t,r,n,i,c,d){w(e,"DELETE FROM idempotency_keys WHERE grantee = ? AND key = ? AND created_at <= ?").run(t,r,new Date(Date.now()-j).toISOString()),w(e,"INSERT INTO idempotency_keys (grantee, key, body_hash, run_id, response_json, created_at) VALUES (?, ?, ?, ?, ?, ?)").run(t,r,n,i,JSON.stringify(c),d)}m(fe,"recordIdempotent");function Nn(e=Date.now()){return C(t=>Number(w(t,"DELETE FROM idempotency_keys WHERE created_at <= ?").run(new Date(e-j).toISOString()).changes))}m(Nn,"pruneExpiredIdempotencyKeys");function _e(e,t,r,n,i){const c=n.text;let d=0;return{messageId:Pe(t,{kind:"message",label:c.slice(0,120),senderNodeId:"human",senderName:r,bodyJson:i?{body:c}:{body:c,start_turn:!1},urgency:i?"normal":"deferred",wake:i?1:0,withinEnqueue:m((a,p)=>{n.uses.length&&(ae(r,n.uses,a),ce(n.uses.map(({upload_id:y,path:g})=>({upload_id:y,path:g,run_id:t})),a)),d=oe(a,t,t,"node.message.accepted",{message_id:p,start_turn:i}).sequence_number},"withinEnqueue")}).messageId,sequence:d}}m(_e,"acceptRunMessage");class pe extends Error{static{m(this,"IdempotentReplay")}winner;constructor(t){super("idempotent replay"),this.winner=t}}const Et=1440*60*1e3;function ge(e){const t=typeof e=="string"?Ve(e):null;if(t===null||!Number.isSafeInteger(t))throw R(`deadline '${String(e)}' is not a duration; use one or more <int>[smhd] parts such as 10m or 1h30m`,"deadline");if(t<=0)throw R("deadline must be greater than zero","deadline");if(t>Et)throw R("deadline must be at most 24h","deadline");return t}m(ge,"parseRunDeadlineMs");async function vn(e,t,r,n=me){if(t.isolated&&!et())throw new S(503,"isolated_unavailable","isolated runs require the Linux root launcher","isolated");t.deadline!==void 0&&ge(t.deadline);const i=G("sha256").update(JSON.stringify(t)).digest("hex");if(r){const s=k(e.grantee,r,i);if(s){const l=x(s.run_id,e.grantee);return!l.pi_pid&&T(l)==="running"&&(t.output_schema!==void 0&&!l.outcome_at&&st(l.node_id).state==="absent"&&ne(l.node_id,l.grantee)===void 0&&se(l.node_id,"terminal",t.output_schema),await H(l.node_id,{resume:!0,capacity:"freeze"})),s.response}}await ut(e.grantee);const c=t.profile===void 0?$e(e.grantee):je(t.profile),d=c.manifest.grantee??"app:terminal";if(d!==e.grantee){const s=`crtr:memory:rw:${d}:profile:${c.profileId}`;if(!e.resolved.some(l=>F(l,s))||t.scopes!==null&&!t.scopes.some(l=>F(l,s)))throw new S(403,"scope_missing",`missing scope ${s}`,"profile",void 0,s)}if(t.model!==void 0){const s=t.model;if(Qe(s)){if(s.includes("/")&&q(e.grant)!=="app"){const l=s.lastIndexOf("/"),h=s.slice(0,l),N=s.slice(l+1);if(["ultra","strong","medium","light"].includes(N)&&Ze({kind:"logical",family:h,strength:N,spec:s},U(e.grantee).files,c.profileId).every(A=>A.family!==h))throw R(`model '${s}' names a model family that is not configured in this daemon`,"model")}}else if(Ke(s)===void 0)throw R(`model '${s}' is not a strength (ultra, strong, medium, light), a family/strength, or a provider/model id`,"model")}const o=Ge(),a=Ae(U(e.grantee).nodes,o);if(t.isolated&&t.cwd!==void 0){const s=Me(a,Ie(t.cwd));if(!X(t.cwd)||s===".."||s.startsWith(`..${Te}`)||X(s))throw R("cwd must be inside the isolated root node folder","cwd")}const p=await n(o,e.grantee,t.prompt),y=p.text;let g;try{g=t.message===void 0?void 0:await n(o,e.grantee,t.message)}catch(s){throw p.cleanup(),s}const E=q(e.grant);let u;try{await ze({kind:tt(c),mode:"base",root:!0,rootLifecycle:"resident",readiness:"launch",cwd:t.isolated?t.cwd??a:U(e.grantee).files,profile:c.profileId,prompt:y,nodeId:o,isolated:t.isolated??!1,...t.model===void 0?{}:{model:t.model},...t.deadline===void 0?{}:{deadlineAt:new Date(Date.now()+ge(t.deadline)).toISOString()},...t.scopes===null?{}:{scopes:t.scopes},run:{grantee:e.grantee,sub:e.sub,grant_id:e.grant,client_id:e.client_id,metadata_json:JSON.stringify(t.metadata),run_id:o,event_cursor:1,usage_json:JSON.stringify(B())},withinCreate:m((s,l)=>{if(r){const N=k(e.grantee,r,i,s);if(N)throw new pe(N)}const h=p.uses;if(h.length&&(ae(e.grantee,h,s),ce(h.map(({upload_id:N,path:A})=>({upload_id:N,path:A,run_id:o})),s)),Xe(o,y),u={run_id:o,node_id:o,grantee:e.grantee,grant:e.grant,rev:e.rev,scopes:t.scopes,payer:E,status:"running",created_at:l.created,metadata:t.metadata,sequence_number:0},oe(s,o,o,"run.started",{scopes:t.scopes,payer:E,usage:B()}),g){const N=_e(s,o,e.grantee,g,!1);u.message={run_id:o,message_id:N.messageId,sequence_number:N.sequence}}r&&fe(s,e.grantee,r,i,o,u,l.created)},"withinCreate")},t.output_schema===void 0?void 0:s=>{se(s,"terminal",t.output_schema)})}catch(s){if(v(o)||(p.cleanup(),g?.cleanup()),s instanceof pe)return s.winner.response;if(t.model!==void 0&&s instanceof De&&s.code==="usage")throw R(s.message,"model");if(s instanceof Oe&&(s.code==="isolated_run"||s.code==="invalid_request")){const l=s.details&&typeof s.details=="object"&&"param"in s.details&&typeof s.details.param=="string"?s.details.param:void 0;throw new S(s.status,s.code,s.message,l)}throw s}if(!u)throw new Error("run creation did not commit");return u}m(vn,"startRun");function bn(e,t){let r;if(t.after)try{const o=JSON.parse(Buffer.from(t.after,"base64url").toString());if(!o||typeof o!="object"||!("activity"in o)||typeof o.activity!="string"||!("id"in o)||typeof o.id!="string")throw new Error("invalid cursor");r={activity:o.activity,id:o.id}}catch{throw R("invalid list cursor","after")}const i=D().prepare(`SELECT node_id, COALESCE(last_activity_at, created) AS activity FROM node_rows
7
7
  WHERE run_id = node_id AND deleting_at IS NULL ${e===null?"":"AND grantee = ?"}
8
- ORDER BY activity DESC, node_id DESC`).all(...e===null?[]:[e]).filter(({node_id:o})=>!t.visible||t.visible(o)).filter(({activity:o,node_id:a})=>!r||o<r.activity||o===r.activity&&a<r.id).map(o=>({root:N(o.node_id),activity:o.activity})).filter(({root:o})=>!t.status||I(o)===t.status),c=i.slice(0,t.limit),d=c.at(-1);return{runs:c.map(({root:o})=>A(o)),next:i.length>t.limit&&d?Buffer.from(JSON.stringify({activity:d.activity,id:d.root.node_id})).toString("base64url"):null}}m(Nn,"listRuns");async function vn(e,t,r){const s=C(e,t),i=m(()=>A(C(e,t)),"read");return!r||P.includes(I(s))?i():new Promise((c,d)=>{const o=m(()=>{clearTimeout(y),clearInterval(_),a();try{c(i())}catch(E){d(E)}},"finish"),a=dt(e,()=>{try{P.includes(String(i().status))&&o()}catch(E){clearTimeout(y),clearInterval(_),a(),d(E)}}),_=setInterval(()=>{P.includes(String(i().status))&&o()},250),y=setTimeout(o,r*1e3)})}m(vn,"waitRun");async function bn(e,t,r=ce,s=!0,i){const c=e.status==="canceled"||e.outcome_reason==="closed",d=e.grantee??"app:terminal",o=J("sha256").update(JSON.stringify(["run.message",e.node_id,t,s])).digest("hex"),a=m(async p=>{const n=N(e.node_id),u=w(O(),"SELECT 1 FROM deliveries WHERE message_id = ? AND state = 'pending' AND canceled_at IS NULL").get(String(p.message_id));return n&&!c&&s&&!n.pi_pid&&u&&await F(e.node_id,{resume:!0,capacity:"freeze"}),p},"replay");if(i){const p=x(d,i,o);if(p)return a(p.response)}if(c)throw new S(409,"run_settled","canceled run cannot receive a message");const _=await r(e.node_id,d,t),y=s&&e.final_report&&!e.pi_pid?(await import("../runtime/reopen.js")).commitReopenResident:void 0;let E;try{E=L(p=>{if(i){const h=x(d,i,o,p);if(h)return{replayed:h.response}}y?.(e.node_id);const n=le(p,e.node_id,d,_,s),u={run_id:e.node_id,message_id:n.messageId,sequence_number:n.sequence};return i&&me(p,d,i,o,e.node_id,u,new Date().toISOString()),{result:u}})}catch(p){throw _.cleanup(),p}return"replayed"in E?(_.cleanup(),a(E.replayed)):(s&&!e.pi_pid&&await F(e.node_id,{resume:!0,capacity:"freeze"}),E.result)}m(bn,"messageRun");async function Et(e){const t=m(()=>new S(503,"service_unavailable",`node ${e} broker was unavailable before the interrupt reached it`),"unavailable");for(let r=0;r<2;r++){const s=N(e);if(!s)throw q();if(!Z(s)){if(s.streaming)throw t();return}const i=z(e)?.executionId;try{await Je(e)==="turn"&&ae({nodes:[e]});return}catch(c){if(!(c instanceof je))throw c;const d=N(e);if(!d)throw q();if(!d.streaming)return;if(r===0&&Z(d)&&z(e)?.executionId!==i)continue;throw t()}}throw t()}m(Et,"interruptNode");async function On(e,t="stop"){const r=t==="stop"?w(O(),"SELECT node_id FROM nodes WHERE run_id = ?").all(e.node_id).map(({node_id:s})=>s):[e.node_id];return await Promise.all(r.map(s=>Et(s))),A(N(e.node_id)??e)}m(On,"interruptRun");async function Dn(e,t={}){const r=w(O(),"SELECT node_id FROM nodes WHERE run_id = ? ORDER BY created DESC").all(e.node_id).map(d=>d.node_id);ae({run:e.node_id});const s=[];if(I(e)!=="settled")s.push(...ne(e.node_id,{preserveEmpty:!0,stopReason:"run_canceled"}).closed);else for(const d of r){if(d===e.node_id)continue;const o=N(d);o&&o.status!=="done"&&o.status!=="canceled"&&o.status!=="dead"&&s.push(...ne(d,{preserveEmpty:!0,stopReason:"run_canceled"}).closed)}if(await re({run_id:e.node_id},"the run was canceled"),(await Promise.all([...new Set([e.node_id,...s])].map(d=>V(d,"run_canceled")))).some(d=>!d.confirmed))throw new S(500,"server_error","run process teardown could not be confirmed",void 0,void 0,void 0,!0);const c=N(e.node_id);return A(c??e)}m(Dn,"cancelRun");const pe=200;function Mn(e,t){if(typeof t!="string"||!t.trim())throw R("name is required","name");const r=t.trim();if(r.length>pe)throw R(`name exceeds ${pe} characters`,"name");const s=We(e.node_id,{name:r});return s.window&&He(s.window,Fe(s)),A(s)}m(Mn,"renameRun");async function In(e,t={config:lt,client:mt}){await re({run_id:e.node_id},"the run was deleted");const r=L(a=>(w(a,"UPDATE nodes SET deleting_at = COALESCE(deleting_at, ?) WHERE node_id = ?").run(new Date().toISOString(),e.node_id),w(a,"SELECT node_id FROM nodes WHERE run_id = ? ORDER BY created DESC").all(e.node_id).map(_=>_.node_id)));if((await Promise.all(r.map(a=>V(a,"run_deleted",{deleting:!0})))).some(a=>!a.confirmed))throw new S(500,"server_error","run process teardown could not be confirmed",void 0,void 0,void 0,!0);const i=r.map(a=>{const _=xe(a);if(_.app===null)throw new Error(`run node missing during deletion: ${a}`);return _}),c=w(O(),"SELECT DISTINCT session_id FROM sessions WHERE session_id IS NOT NULL AND node_id IN (SELECT node_id FROM nodes WHERE run_id = ?)").all(e.node_id);for(const{session_id:a}of c)try{Q().delete(a)}catch(_){if(!qe(_))throw _}const d=L(a=>{for(const p of r){const n=Ce(a,p);n!==null&&n.deleted_at===null&&Le(a,n)}const _=_t([e.node_id],a);w(a,"DELETE FROM run_events WHERE run_id = ?").run(e.node_id),w(a,"DELETE FROM idempotency_keys WHERE run_id = ?").run(e.node_id);const y=r.map(()=>"?").join(","),E=a.prepare(`SELECT message_id FROM messages WHERE sender_node_id IN (${y}) UNION SELECT message_id FROM deliveries WHERE destination_id IN (${y})`).all(...r,...r);a.prepare(`DELETE FROM deliveries WHERE destination_id IN (${y})`).run(...r);for(const{message_id:p}of E)w(a,"DELETE FROM messages WHERE message_id = ? AND NOT EXISTS (SELECT 1 FROM deliveries WHERE message_id = ?)").run(p,p);return _});for(const a of i)ke(a);const{notifyRunDeleted:o}=await import("./events.js");return o(e.node_id),{uploads_pending:await wt(d,t)}}m(In,"deleteRun");async function wt(e,t){if(!e.length||!t.config())return e.length;let r;try{r=t.client()}catch{return e.length}const s=new Set,i=e.map(d=>r.deleteUpload(d).then(()=>{ft(d),s.add(d)},()=>{}));let c;return await Promise.race([Promise.all(i),new Promise(d=>{c=setTimeout(d,t.budgetMs??pt),c.unref?.()})]),clearTimeout(c),e.length-s.size}m(wt,"deleteReleasedUploads");function Tn(e,t,r){C(e,t),X(e);const s=O();s.exec("BEGIN");try{const c=w(s,"SELECT node_id, parent FROM nodes WHERE run_id = ? ORDER BY CASE WHEN node_id = ? THEN 0 ELSE 1 END, created, node_id").all(e,e).map(n=>({node_id:n.node_id,parent_node_id:n.parent,conversations:w(s,"SELECT DISTINCT session_id FROM sessions WHERE node_id = ? ORDER BY created_at").all(n.node_id).map(({session_id:u})=>{const{header:h,entries:g}=Q().read(u);if(r==="entries")return{conversation_id:u,header:h,entries:g};const T=Ae.inMemory(h.cwd,void 0,[h,...g]),ge=tt(T)??[],$=new Map(g.map((f,v)=>[f.id,v])),Ee=g.filter(f=>f.type==="custom"&&f.customType==="crtr-system-prompt").map(f=>({id:f.id,message:{role:"custom",customType:"crtr-system-prompt",data:"data"in f?f.data:void 0,timestamp:f.timestamp}})),j=g.filter(f=>f.type==="custom_message"&&f.customType==="app_message").map(f=>({id:f.id,message:{role:"custom",customType:"app_message",content:"content"in f?f.content:"",timestamp:f.timestamp}})),we=n.node_id===e?g.find(f=>{if(f.type!=="message"||f.message.role!=="user")return!1;const v=K(g,f.message.timestamp);return v?.type==="runtime"&&v.kind==="kickoff"})?.id:void 0,he=[...ge.filter(({id:f})=>!j.some(v=>v.id===f)),...Ee,...j].sort((f,v)=>($.get(f.id)??Number.MAX_SAFE_INTEGER)-($.get(v.id)??Number.MAX_SAFE_INTEGER)).map(({id:f,message:v})=>{const l=v,D=l.usage,k=l.role==="user"?K(g,Number(l.timestamp)):null,ye=k?.type==="human"||f===we,M=l.role==="toolResult"?"tool_result":l.role==="bashExecution"?"bash_execution":l.role==="compactionSummary"?"compaction_summary":l.role==="branchSummary"?"branch_summary":l.role==="custom"&&l.customType==="crtr-system-prompt"?"system":l.role==="user"?ye?"user":"custom":l.role,Re=M==="custom"?l.role==="custom"?l.customType:k?.type==="runtime"?k.kind:"unknown":void 0,Se=M==="system"&&l.customType==="crtr-system-prompt"?[{type:"text",text:l.data?.text??""}]:typeof l.content=="string"?[{type:"text",text:l.content}]:Array.isArray(l.content)?l.content.map(b=>b.type==="toolCall"?{type:"tool_call",tool_call_id:b.id,name:b.name,arguments:b.arguments}:b.type==="image"?{type:"image",mime_type:b.mimeType}:b.type==="thinking"?{type:"thinking",text:b.thinking}:b):[];return{entry_id:f,role:M,...M==="custom"?{custom_type:Re}:{},time:typeof l.timestamp=="string"?l.timestamp:new Date(Number(l.timestamp??Date.now())).toISOString(),content:Se,...M==="assistant"?{model:l.model,provider:l.provider,stop_reason:l.stopReason,...l.errorMessage?{error_message:l.errorMessage}:{},...D?{usage:{input_tokens:D.input??0,output_tokens:D.output??0,cache_read_tokens:D.cacheRead??0,cache_write_tokens:D.cacheWrite??0,cost_usd:D.cost?.total??0}}:{}}:{},...M==="tool_result"?{tool_call_id:l.toolCallId,tool_name:l.toolName,is_error:l.isError}:{}}})??[];return{conversation_id:u,messages:he}})})),o=w(s,"SELECT event_cursor FROM nodes WHERE node_id = ?").get(e).event_cursor-1,a=new Map(c.map(n=>[n.node_id,ot(n.node_id)])),_=w(s,`SELECT node_id, sequence_number FROM run_events
8
+ ORDER BY activity DESC, node_id DESC`).all(...e===null?[]:[e]).filter(({node_id:o})=>!t.visible||t.visible(o)).filter(({activity:o,node_id:a})=>!r||o<r.activity||o===r.activity&&a<r.id).map(o=>({root:v(o.node_id),activity:o.activity})).filter(({root:o})=>!t.status||T(o)===t.status),c=i.slice(0,t.limit),d=c.at(-1);return{runs:c.map(({root:o})=>L(o)),next:i.length>t.limit&&d?Buffer.from(JSON.stringify({activity:d.activity,id:d.root.node_id})).toString("base64url"):null}}m(bn,"listRuns");async function On(e,t,r){const n=x(e,t),i=m(()=>L(x(e,t)),"read");return!r||$.includes(T(n))?i():new Promise((c,d)=>{const o=m(()=>{clearTimeout(y),clearInterval(p),a();try{c(i())}catch(g){d(g)}},"finish"),a=at(e,()=>{try{$.includes(String(i().status))&&o()}catch(g){clearTimeout(y),clearInterval(p),a(),d(g)}}),p=setInterval(()=>{$.includes(String(i().status))&&o()},250),y=setTimeout(o,r*1e3)})}m(On,"waitRun");async function Dn(e,t,r=me,n=!0,i){const c=e.status==="canceled"||e.outcome_reason==="closed",d=e.grantee??"app:terminal",o=G("sha256").update(JSON.stringify(["run.message",e.node_id,t,n])).digest("hex"),a=m(async E=>{const u=v(e.node_id),s=w(D(),"SELECT 1 FROM deliveries WHERE message_id = ? AND state = 'pending' AND canceled_at IS NULL").get(String(E.message_id));return u&&!c&&n&&!u.pi_pid&&s&&await H(e.node_id,{resume:!0,capacity:"freeze"}),E},"replay");if(i){const E=k(d,i,o);if(E)return a(E.response)}if(c)throw new S(409,"run_settled","canceled run cannot receive a message");const p=await r(e.node_id,d,t),y=n&&e.final_report&&!e.pi_pid?(await import("../runtime/reopen.js")).commitReopenResident:void 0;let g;try{g=C(E=>{if(i){const l=k(d,i,o,E);if(l)return{replayed:l.response}}y?.(e.node_id);const u=_e(E,e.node_id,d,p,n),s={run_id:e.node_id,message_id:u.messageId,sequence_number:u.sequence};return i&&fe(E,d,i,o,e.node_id,s,new Date().toISOString()),{result:s}})}catch(E){throw p.cleanup(),E}return"replayed"in g?(p.cleanup(),a(g.replayed)):(n&&!e.pi_pid&&await H(e.node_id,{resume:!0,capacity:"freeze"}),g.result)}m(Dn,"messageRun");async function wt(e){const t=m(()=>new S(503,"service_unavailable",`node ${e} broker was unavailable before the interrupt reached it`),"unavailable");for(let r=0;r<2;r++){const n=v(e);if(!n)throw P();if(!ee(n)){if(n.streaming)throw t();return}const i=V(e)?.executionId;try{await Ye(e)==="turn"&&ue({nodes:[e]});return}catch(c){if(!(c instanceof Je))throw c;const d=v(e);if(!d)throw P();if(!d.streaming)return;if(r===0&&ee(d)&&V(e)?.executionId!==i)continue;throw t()}}throw t()}m(wt,"interruptNode");async function Mn(e,t="stop"){const r=t==="stop"?w(D(),"SELECT node_id FROM nodes WHERE run_id = ?").all(e.node_id).map(({node_id:n})=>n):[e.node_id];return await Promise.all(r.map(n=>wt(n))),L(v(e.node_id)??e)}m(Mn,"interruptRun");async function In(e,t={}){const r=w(D(),"SELECT node_id FROM nodes WHERE run_id = ? ORDER BY created DESC").all(e.node_id).map(d=>d.node_id);ue({run:e.node_id});const n=[];if(T(e)!=="settled")n.push(...re(e.node_id,{preserveEmpty:!0,stopReason:"run_canceled"}).closed);else for(const d of r){if(d===e.node_id)continue;const o=v(d);o&&o.status!=="done"&&o.status!=="canceled"&&o.status!=="dead"&&n.push(...re(d,{preserveEmpty:!0,stopReason:"run_canceled"}).closed)}if(await ie({run_id:e.node_id},"the run was canceled"),(await Promise.all([...new Set([e.node_id,...n])].map(d=>K(d,"run_canceled")))).some(d=>!d.confirmed))throw new S(500,"server_error","run process teardown could not be confirmed",void 0,void 0,void 0,!0);const c=v(e.node_id);return L(c??e)}m(In,"cancelRun");const Ee=200;function Tn(e,t){if(typeof t!="string"||!t.trim())throw R("name is required","name");const r=t.trim();if(r.length>Ee)throw R(`name exceeds ${Ee} characters`,"name");const n=Fe(e.node_id,{name:r});return n.window&&qe(n.window,He(n)),L(n)}m(Tn,"renameRun");async function An(e,t={config:ft,client:lt}){await ie({run_id:e.node_id},"the run was deleted");const r=C(a=>(w(a,"UPDATE nodes SET deleting_at = COALESCE(deleting_at, ?) WHERE node_id = ?").run(new Date().toISOString(),e.node_id),w(a,"SELECT node_id FROM nodes WHERE run_id = ? ORDER BY created DESC").all(e.node_id).map(p=>p.node_id)));if((await Promise.all(r.map(a=>K(a,"run_deleted",{deleting:!0})))).some(a=>!a.confirmed))throw new S(500,"server_error","run process teardown could not be confirmed",void 0,void 0,void 0,!0);const i=r.map(a=>{const p=ke(a);if(p.app===null)throw new Error(`run node missing during deletion: ${a}`);return p}),c=w(D(),"SELECT DISTINCT session_id FROM sessions WHERE session_id IS NOT NULL AND node_id IN (SELECT node_id FROM nodes WHERE run_id = ?)").all(e.node_id);for(const{session_id:a}of c)try{Z().delete(a)}catch(p){if(!Ue(p))throw p}const d=C(a=>{for(const E of r){const u=xe(a,E);u!==null&&u.deleted_at===null&&Ce(a,u)}const p=pt([e.node_id],a);w(a,"DELETE FROM run_events WHERE run_id = ?").run(e.node_id),w(a,"DELETE FROM idempotency_keys WHERE run_id = ?").run(e.node_id);const y=r.map(()=>"?").join(","),g=a.prepare(`SELECT message_id FROM messages WHERE sender_node_id IN (${y}) UNION SELECT message_id FROM deliveries WHERE destination_id IN (${y})`).all(...r,...r);a.prepare(`DELETE FROM deliveries WHERE destination_id IN (${y})`).run(...r);for(const{message_id:E}of g)w(a,"DELETE FROM messages WHERE message_id = ? AND NOT EXISTS (SELECT 1 FROM deliveries WHERE message_id = ?)").run(E,E);return p});for(const a of i)We(a);const{notifyRunDeleted:o}=await import("./events.js");return o(e.node_id),{uploads_pending:await ht(d,t)}}m(An,"deleteRun");async function ht(e,t){if(!e.length||!t.config())return e.length;let r;try{r=t.client()}catch{return e.length}const n=new Set,i=e.map(d=>r.deleteUpload(d).then(()=>{_t(d),n.add(d)},()=>{}));let c;return await Promise.race([Promise.all(i),new Promise(d=>{c=setTimeout(d,t.budgetMs??gt),c.unref?.()})]),clearTimeout(c),e.length-n.size}m(ht,"deleteReleasedUploads");function Ln(e,t,r){x(e,t),Q(e);const n=D();n.exec("BEGIN");try{const c=w(n,"SELECT node_id, parent FROM nodes WHERE run_id = ? ORDER BY CASE WHEN node_id = ? THEN 0 ELSE 1 END, created, node_id").all(e,e).map(u=>({node_id:u.node_id,parent_node_id:u.parent,conversations:w(n,"SELECT DISTINCT session_id FROM sessions WHERE node_id = ? ORDER BY created_at").all(u.node_id).map(({session_id:s})=>{const{header:l,entries:h}=Z().read(s);if(r==="entries")return{conversation_id:s,header:l,entries:h};const N=Le.inMemory(l.cwd,void 0,[l,...h]),A=nt(N)??[],J=new Map(h.map((_,b)=>[_.id,b])),we=h.filter(_=>_.type==="custom"&&_.customType==="crtr-system-prompt").map(_=>({id:_.id,message:{role:"custom",customType:"crtr-system-prompt",data:"data"in _?_.data:void 0,timestamp:_.timestamp}})),Y=h.filter(_=>_.type==="custom_message"&&_.customType==="app_message").map(_=>({id:_.id,message:{role:"custom",customType:"app_message",content:"content"in _?_.content:"",timestamp:_.timestamp}})),he=u.node_id===e?h.find(_=>{if(_.type!=="message"||_.message.role!=="user")return!1;const b=te(h,_.message.timestamp);return b?.type==="runtime"&&b.kind==="kickoff"})?.id:void 0,ye=[...A.filter(({id:_})=>!Y.some(b=>b.id===_)),...we,...Y].sort((_,b)=>(J.get(_.id)??Number.MAX_SAFE_INTEGER)-(J.get(b.id)??Number.MAX_SAFE_INTEGER)).map(({id:_,message:b})=>{const f=b,M=f.usage,W=f.role==="user"?te(h,Number(f.timestamp)):null,Re=W?.type==="human"||_===he,I=f.role==="toolResult"?"tool_result":f.role==="bashExecution"?"bash_execution":f.role==="compactionSummary"?"compaction_summary":f.role==="branchSummary"?"branch_summary":f.role==="custom"&&f.customType==="crtr-system-prompt"?"system":f.role==="user"?Re?"user":"custom":f.role,Se=I==="custom"?f.role==="custom"?f.customType:W?.type==="runtime"?W.kind:"unknown":void 0,Ne=I==="system"&&f.customType==="crtr-system-prompt"?[{type:"text",text:f.data?.text??""}]:typeof f.content=="string"?[{type:"text",text:f.content}]:Array.isArray(f.content)?f.content.map(O=>O.type==="toolCall"?{type:"tool_call",tool_call_id:O.id,name:O.name,arguments:O.arguments}:O.type==="image"?{type:"image",mime_type:O.mimeType}:O.type==="thinking"?{type:"thinking",text:O.thinking}:O):[];return{entry_id:_,role:I,...I==="custom"?{custom_type:Se}:{},time:typeof f.timestamp=="string"?f.timestamp:new Date(Number(f.timestamp??Date.now())).toISOString(),content:Ne,...I==="assistant"?{model:f.model,provider:f.provider,stop_reason:f.stopReason,...f.errorMessage?{error_message:f.errorMessage}:{},...M?{usage:{input_tokens:M.input??0,output_tokens:M.output??0,cache_read_tokens:M.cacheRead??0,cache_write_tokens:M.cacheWrite??0,cost_usd:M.cost?.total??0}}:{}}:{},...I==="tool_result"?{tool_call_id:f.toolCallId,tool_name:f.toolName,is_error:f.isError}:{}}})??[];return{conversation_id:s,messages:ye}})})),o=w(n,"SELECT event_cursor FROM nodes WHERE node_id = ?").get(e).event_cursor-1,a=new Map(c.map(u=>[u.node_id,it(u.node_id)])),p=w(n,`SELECT node_id, sequence_number FROM run_events
9
9
  WHERE run_id = ? AND sequence_number <= ? AND type IN ('node.thinking.done', 'node.output_text.done', 'usage')
10
- ORDER BY sequence_number`).all(e,o);for(const n of _){const u=a.get(n.node_id);u!=null&&n.sequence_number>=u&&a.set(n.node_id,null)}const y=w(s,`SELECT node_id, sequence_number, type, body_json FROM run_events
10
+ ORDER BY sequence_number`).all(e,o);for(const u of p){const s=a.get(u.node_id);s!=null&&u.sequence_number>=s&&a.set(u.node_id,null)}const y=w(n,`SELECT node_id, sequence_number, type, body_json FROM run_events
11
11
  WHERE run_id = ? AND sequence_number <= ? AND type IN ('node.thinking.delta', 'node.output_text.delta')
12
- ORDER BY sequence_number`).all(e,o),E=new Map;for(const n of y){const u=a.get(n.node_id);if(u==null||n.sequence_number<u)continue;const h=JSON.parse(n.body_json),g=E.get(n.node_id)??{thinking:"",text:""};n.type==="node.thinking.delta"?g.thinking+=h.delta:g.text+=h.delta,E.set(n.node_id,g)}const p=c.map(n=>({...n,in_progress_message:a.get(n.node_id)==null?null:E.get(n.node_id)??{thinking:"",text:""}}));return s.exec("COMMIT"),{run_id:e,latest_sequence:o,nodes:p}}catch(i){throw s.exec("ROLLBACK"),i}}m(Tn,"traceRun");function An(e,t,r){if(t===void 0){if(!e.some(s=>W(s,"crtr:llm")))throw new S(403,"scope_missing","missing scope crtr:llm",void 0,void 0,"crtr:llm");return null}if(!Array.isArray(t)||t.some(s=>typeof s!="string"))throw R("scopes must be a list of scope strings","scopes");for(const s of t){try{it(s)}catch{throw R(`invalid scope ${s}`,"scopes")}if(/^crtr:files:(?:read|rw):app:/.test(s)&&s.split(":")[4]===r.slice(4))throw R(`own-app files cannot narrow a run: ${s}`,"scopes");if(!(/^crtr:memory:(?:read|rw):app:/.test(s)&&s.split(":")[4]===r.slice(4))&&!ve(e,s))throw new S(403,"scope_missing",`missing scope ${s}`,void 0,void 0,s)}if(!t.includes("crtr:llm"))throw new S(403,"scope_missing","missing scope crtr:llm",void 0,void 0,"crtr:llm");return t}m(An,"requestedScopes");export{B as IDEMPOTENCY_WINDOW_MS,gt as RUN_DEADLINE_MAX_MS,pt as RUN_DELETE_STORAGE_BUDGET_MS,pe as RUN_NAME_MAX,S as RunError,Dn as cancelRun,In as deleteRun,yn as idempotencyKeyOf,On as interruptRun,Nn as listRuns,bn as messageRun,C as ownedRun,_e as parseRunDeadlineMs,Rn as pruneExpiredIdempotencyKeys,Mn as renameRun,An as requestedScopes,wn as rewriteLocalIdempotencyGrantee,hn as runIsRunning,A as runObject,Sn as startRun,Tn as traceRun,vn as waitRun};
12
+ ORDER BY sequence_number`).all(e,o),g=new Map;for(const u of y){const s=a.get(u.node_id);if(s==null||u.sequence_number<s)continue;const l=JSON.parse(u.body_json),h=g.get(u.node_id)??{thinking:"",text:""};u.type==="node.thinking.delta"?h.thinking+=l.delta:h.text+=l.delta,g.set(u.node_id,h)}const E=c.map(u=>({...u,in_progress_message:a.get(u.node_id)==null?null:g.get(u.node_id)??{thinking:"",text:""}}));return n.exec("COMMIT"),{run_id:e,latest_sequence:o,nodes:E}}catch(i){throw n.exec("ROLLBACK"),i}}m(Ln,"traceRun");function Cn(e,t,r){if(t===void 0){if(!e.some(n=>F(n,"crtr:llm")))throw new S(403,"scope_missing","missing scope crtr:llm",void 0,void 0,"crtr:llm");return null}if(!Array.isArray(t)||t.some(n=>typeof n!="string"))throw R("scopes must be a list of scope strings","scopes");for(const n of t){try{dt(n)}catch{throw R(`invalid scope ${n}`,"scopes")}if(/^crtr:files:(?:read|rw):app:/.test(n)&&n.split(":")[4]===r.slice(4))throw R(`own-app files cannot narrow a run: ${n}`,"scopes");if(!(/^crtr:memory:(?:read|rw):app:/.test(n)&&n.split(":")[4]===r.slice(4))&&!be(e,n))throw new S(403,"scope_missing",`missing scope ${n}`,void 0,void 0,n)}if(!t.includes("crtr:llm"))throw new S(403,"scope_missing","missing scope crtr:llm",void 0,void 0,"crtr:llm");return t}m(Cn,"requestedScopes");export{j as IDEMPOTENCY_WINDOW_MS,Et as RUN_DEADLINE_MAX_MS,gt as RUN_DELETE_STORAGE_BUDGET_MS,Ee as RUN_NAME_MAX,S as RunError,In as cancelRun,An as deleteRun,Sn as idempotencyKeyOf,Mn as interruptRun,bn as listRuns,Dn as messageRun,x as ownedRun,ge as parseRunDeadlineMs,Nn as pruneExpiredIdempotencyKeys,Tn as renameRun,Cn as requestedScopes,yn as rewriteLocalIdempotencyGrantee,Rn as runIsRunning,L as runObject,vn as startRun,Ln as traceRun,On as waitRun};
@@ -1,2 +1,2 @@
1
- var F=Object.defineProperty;var d=(t,e)=>F(t,"name",{value:e,configurable:!0});import{setTimeout as P}from"node:timers/promises";import{createAssistantMessageEventStream as W,getCurrentSystemPrompt as j,getCurrentTools as J}from"@earendil-works/pi-ai";import{socketFetch as U}from"../../../api/node-transport.js";import{apiSocketPath as Y}from"../../canvas/paths.js";import{currentNodeToken as z}from"./node-token.js";import{envModelExact as L,envModelIntent as X}from"../../../shared/env.js";import{MODEL_CONTEXT_BODY_MAX_BYTES as k}from"../../llm/body-limits.js";import{modelRequestFromConfig as G}from"../../model-routes.js";import{parseProviderRateLimit as H,providerFailureDiagnostic as T}from"../../provider-failure.js";function de(t){t.checkAuth=async e=>t.getProvider(e)?{type:"api_key"}:void 0,t.getAvailable=async e=>t.getModels(e),t.getAvailableSnapshot=()=>t.getModels(),t.streamSimple=Z}d(de,"configureBrokerModelRuntime");const K=300,$="crtr:llm-refusal";class v extends Error{static{d(this,"LlmRefusalError")}retryAt;rateLimit;code;status;constructor(e,o,r,n,i){super(e),this.retryAt=o,this.rateLimit=r,this.code=n,this.status=i}}function O(t,e){const o=t===void 0?"the request body":`the request body (${t} bytes)`;return new Error(`request_too_large: ${o} exceeds the ${e}-byte model request limit; compact the conversation to shrink the context`)}d(O,"contextTooLargeError");function M(t){const e=t.details?.rate_limit;if(!e||typeof e!="object")return;const o=H(e);if(o===void 0)return;const{provider:r,model:n}=e;return typeof r=="string"&&r!==""&&typeof n=="string"&&n!==""?{...o,model:`${r}/${n}`}:o}d(M,"refusalRateLimit");function ue(t){for(const e of t.diagnostics??[]){if(e.type!==$)continue;const o=e.details?.retryAt;if(typeof o=="number"&&Number.isFinite(o)&&o>0)return o}}d(ue,"refusalRetryAt");class C extends Error{static{d(this,"ContentFilteredError")}}function N(t){return typeof t=="string"?t:t.map(e=>e.type==="text"?{type:"text",text:e.text}:{type:"image_url",image_url:{url:`data:${e.mimeType};base64,${e.data}`}})}d(N,"wireContent");function Q(t){const e=d(n=>n.role==="assistant"&&(n.stopReason==="error"||n.stopReason==="aborted"),"incomplete"),o=t.some(e)?t.filter(n=>!e(n)):t;let r=o.length;for(;r>0&&o[r-1]?.role==="assistant";)r--;return r===o.length?o:o.slice(0,r)}d(Q,"wireHistory");function V(t,e,o){const r=[],n=j(e.messages),i=J(e.messages);n?r.push({role:"system",content:n}):e.systemPrompt&&r.push({role:"system",content:e.systemPrompt});for(const u of Q(e.messages))u.role==="user"?r.push({role:"user",content:N(u.content)}):u.role==="toolResult"?r.push({role:"tool",content:N(u.content),tool_call_id:u.toolCallId}):u.role==="assistant"&&r.push({role:"assistant",content:u.content.filter(c=>c.type==="text").map(c=>c.text).join("")||null,tool_calls:u.content.filter(c=>c.type==="toolCall").map(c=>({id:c.id,type:"function",function:{name:c.name,arguments:JSON.stringify(c.arguments)}}))});const w=`${t.provider}/${t.id}`,y=X();return{model:G(w,y,L())?.kind==="logical"?y:w,model_policy:L()?"exact":"substitute",stream:!0,messages:r,...i.length?{tools:i.map(u=>({type:"function",function:{name:u.name,description:u.description,parameters:u.parameters}}))}:{},...o.reasoning?{reasoning_effort:o.reasoning}:{},...o.temperature!==void 0?{temperature:o.temperature}:{},...o.maxTokens!==void 0?{max_tokens:o.maxTokens}:{}}}d(V,"requestBody");function b(t,e){if(typeof e!="string")return!1;const o=e.indexOf("/");return o<1||o===e.length-1?!1:(t.provider=e.slice(0,o),t.model=e.slice(o+1),!0)}d(b,"applyServedModel");function q(t){if(t.details?.served_model!==void 0)return t.details.served_model;const e=t.details?.rate_limit;return typeof e?.provider=="string"&&typeof e.model=="string"?`${e.provider}/${e.model}`:void 0}d(q,"refusalRoute");function D(t){if(!t||typeof t!="object"||!("error"in t))throw new Error("llm returned an invalid response");const e=t.error;if(!e||typeof e.message!="string")throw new Error("llm returned an invalid refusal");return e}d(D,"parseRefusal");function Z(t,e,o={}){const r=W(),n={role:"assistant",content:[],api:t.api,provider:t.provider,model:t.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};return(async()=>{const i=z();if(!i)throw new Error("llm requires a node token");const w=JSON.stringify(V(t,e,o)),y=Buffer.byteLength(w);if(y>k)throw O(y,k);let u=0;for(;;){o.signal?.throwIfAborted();const c=await U(Y())("http://localhost/v1/llm",{method:"POST",headers:{authorization:`Bearer ${i}`,"content-type":"application/json"},body:w,signal:o.signal});if(!c.ok){const l=D(await c.json());if(c.status===413||l.code==="payload_too_large")throw O(y,k);if(b(n,q(l)),l.retryable!==!0)throw new v(l.message,void 0,M(l),l.code,c.status);const s=l.retry_after_s;if(typeof s!="number"||!Number.isFinite(s)||s<=0)throw new Error(l.message);const f=K-u;if(s>f){const p=Date.now()+s*1e3;throw new v(`${l.message} (retry after ${s}s, at ${new Date(p).toISOString()})`,p,M(l))}await P(s*1e3,void 0,{signal:o.signal}),u+=s;continue}if(!c.body)throw new Error("llm returned no stream");r.push({type:"start",partial:n});const B=c.body.getReader(),R=new TextDecoder;let h="",_="stop",E,S=!1,I=!1;const A=d(l=>{const s=JSON.parse(l);if(s.error){const a=D(s);throw b(n,q(a)),new Error(a.message)}if(s.served_model){if(I=!0,s.served_model.indexOf("/")<1)throw new Error("llm returned an invalid served_model");b(n,s.served_model)}const f=s.choices?.[0],p=f?.delta;if(p?.reasoning_content){const a=n.content.findIndex(x=>x.type==="thinking"),m=a<0?{type:"thinking",thinking:""}:n.content[a],g=a<0?n.content.push(m)-1:a;if(a<0&&r.push({type:"thinking_start",contentIndex:g,partial:n}),m.type!=="thinking")throw new Error("invalid thinking block");m.thinking+=p.reasoning_content,r.push({type:"thinking_delta",contentIndex:g,delta:p.reasoning_content,partial:n})}if(p?.content){const a=n.content.findIndex(x=>x.type==="text"),m=a<0?{type:"text",text:""}:n.content[a],g=a<0?n.content.push(m)-1:a;if(a<0&&r.push({type:"text_start",contentIndex:g,partial:n}),m.type!=="text")throw new Error("invalid text block");m.text+=p.content,r.push({type:"text_delta",contentIndex:g,delta:p.content,partial:n})}for(const a of p?.tool_calls??[]){const m={type:"toolCall",id:a.id,name:a.function.name,arguments:JSON.parse(a.function.arguments)},g=n.content.push(m)-1;r.push({type:"toolcall_start",contentIndex:g,partial:n}),r.push({type:"toolcall_end",contentIndex:g,toolCall:m,partial:n})}f?.finish_reason&&(_=f.finish_reason),f?.message?.refusal&&(E=f.message.refusal),s.usage&&(S=!0,n.usage={input:s.usage.prompt_tokens,output:s.usage.completion_tokens,cacheRead:s.usage.cache_read_tokens,cacheWrite:s.usage.cache_write_tokens,totalTokens:s.usage.total_tokens,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:typeof s.usage.usd_equivalent=="number"&&Number.isFinite(s.usage.usd_equivalent)?s.usage.usd_equivalent:0}})},"apply");for(;;){const{value:l,done:s}=await B.read();if(s)break;h+=R.decode(l,{stream:!0});let f;for(;(f=h.indexOf(`
2
- `))>=0;){const p=h.slice(0,f).trim();h=h.slice(f+1),p&&A(p)}}if(h+=R.decode(),h.trim()&&A(h.trim()),!S||!I)throw new Error("llm stream ended without usage or served_model");for(const[l,s]of n.content.entries())s.type==="text"&&r.push({type:"text_end",contentIndex:l,content:s.text,partial:n}),s.type==="thinking"&&r.push({type:"thinking_end",contentIndex:l,content:s.thinking,partial:n});if(_==="content_filter")throw new C(E??"Content filtered");if(!["stop","tool_calls","length"].includes(_))throw new Error(`llm returned unknown finish reason: ${_}`);n.stopReason=_==="tool_calls"?"toolUse":_==="length"?"length":"stop",r.push({type:"done",reason:n.stopReason,message:n}),r.end();return}})().catch(i=>{n.stopReason=o.signal?.aborted?"aborted":"error",n.errorMessage=i instanceof Error?i.message:String(i),i instanceof v&&(n.diagnostics=[{type:$,timestamp:Date.now(),...i.retryAt!==void 0?{details:{retryAt:i.retryAt}}:{}},...i.rateLimit!==void 0?[T({status:429,ratelimit:i.rateLimit})]:[],...i.rateLimit===void 0&&i.code==="cap_exhausted"?[T({status:i.status??402,code:i.code})]:[]]),i instanceof C&&n.stopReason==="error"&&(n.rawStopReason="content_filter"),r.push({type:"error",reason:n.stopReason,error:n}),r.end()}),r}d(Z,"streamBrokerModel");export{K as LLM_BROKER_RETRY_WINDOW_S,$ as LLM_REFUSAL_DIAGNOSTIC,de as configureBrokerModelRuntime,ue as refusalRetryAt,V as requestBody,Z as streamBrokerModel,Q as wireHistory};
1
+ var U=Object.defineProperty;var c=(t,e)=>U(t,"name",{value:e,configurable:!0});import{setTimeout as W}from"node:timers/promises";import{createAssistantMessageEventStream as j,getCurrentSystemPrompt as J,getCurrentTools as Y}from"@earendil-works/pi-ai";import{socketFetch as z}from"../../../api/node-transport.js";import{apiSocketPath as X}from"../../canvas/paths.js";import{currentNodeToken as G}from"./node-token.js";import{envModelExact as O,envModelIntent as H}from"../../../shared/env.js";import{MODEL_CONTEXT_BODY_MAX_BYTES as k}from"../../llm/body-limits.js";import{modelRequestFromConfig as K}from"../../model-routes.js";import{parseProviderRateLimit as V,providerFailureDiagnostic as v}from"../../provider-failure.js";import{UPSTREAM_MODEL_UNAVAILABLE as E}from"../../fault-classifier.js";function fe(t){t.checkAuth=async e=>t.getProvider(e)?{type:"api_key"}:void 0,t.getAvailable=async e=>t.getModels(e),t.getAvailableSnapshot=()=>t.getModels(),t.streamSimple=te}c(fe,"configureBrokerModelRuntime");const Q=300,$="crtr:llm-refusal";class b extends Error{static{c(this,"LlmRefusalError")}retryAt;rateLimit;code;status;constructor(e,o,r,n,i){super(e),this.retryAt=o,this.rateLimit=r,this.code=n,this.status=i}}class R extends Error{static{c(this,"UpstreamModelUnavailableError")}}function C(t,e){const o=t===void 0?"the request body":`the request body (${t} bytes)`;return new Error(`request_too_large: ${o} exceeds the ${e}-byte model request limit; compact the conversation to shrink the context`)}c(C,"contextTooLargeError");function N(t){const e=t.details?.rate_limit;if(!e||typeof e!="object")return;const o=V(e);if(o===void 0)return;const{provider:r,model:n}=e;return typeof r=="string"&&r!==""&&typeof n=="string"&&n!==""?{...o,model:`${r}/${n}`}:o}c(N,"refusalRateLimit");function me(t){for(const e of t.diagnostics??[]){if(e.type!==$)continue;const o=e.details?.retryAt;if(typeof o=="number"&&Number.isFinite(o)&&o>0)return o}}c(me,"refusalRetryAt");class D extends Error{static{c(this,"ContentFilteredError")}}function q(t){return typeof t=="string"?t:t.map(e=>e.type==="text"?{type:"text",text:e.text}:{type:"image_url",image_url:{url:`data:${e.mimeType};base64,${e.data}`}})}c(q,"wireContent");function Z(t){const e=c(n=>n.role==="assistant"&&(n.stopReason==="error"||n.stopReason==="aborted"),"incomplete"),o=t.some(e)?t.filter(n=>!e(n)):t;let r=o.length;for(;r>0&&o[r-1]?.role==="assistant";)r--;return r===o.length?o:o.slice(0,r)}c(Z,"wireHistory");function ee(t,e,o){const r=[],n=J(e.messages),i=Y(e.messages);n?r.push({role:"system",content:n}):e.systemPrompt&&r.push({role:"system",content:e.systemPrompt});for(const u of Z(e.messages))u.role==="user"?r.push({role:"user",content:q(u.content)}):u.role==="toolResult"?r.push({role:"tool",content:q(u.content),tool_call_id:u.toolCallId}):u.role==="assistant"&&r.push({role:"assistant",content:u.content.filter(d=>d.type==="text").map(d=>d.text).join("")||null,tool_calls:u.content.filter(d=>d.type==="toolCall").map(d=>({id:d.id,type:"function",function:{name:d.name,arguments:JSON.stringify(d.arguments)}}))});const w=`${t.provider}/${t.id}`,y=H();return{model:K(w,y,O())?.kind==="logical"?y:w,model_policy:O()?"exact":"substitute",stream:!0,messages:r,...i.length?{tools:i.map(u=>({type:"function",function:{name:u.name,description:u.description,parameters:u.parameters}}))}:{},...o.reasoning?{reasoning_effort:o.reasoning}:{},...o.temperature!==void 0?{temperature:o.temperature}:{},...o.maxTokens!==void 0?{max_tokens:o.maxTokens}:{}}}c(ee,"requestBody");function S(t,e){if(typeof e!="string")return!1;const o=e.indexOf("/");return o<1||o===e.length-1?!1:(t.provider=e.slice(0,o),t.model=e.slice(o+1),!0)}c(S,"applyServedModel");function B(t){if(t.details?.served_model!==void 0)return t.details.served_model;const e=t.details?.rate_limit;return typeof e?.provider=="string"&&typeof e.model=="string"?`${e.provider}/${e.model}`:void 0}c(B,"refusalRoute");function F(t){if(!t||typeof t!="object"||!("error"in t))throw new Error("llm returned an invalid response");const e=t.error;if(!e||typeof e.message!="string")throw new Error("llm returned an invalid refusal");return e}c(F,"parseRefusal");function te(t,e,o={}){const r=j(),n={role:"assistant",content:[],api:t.api,provider:t.provider,model:t.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};return(async()=>{const i=G();if(!i)throw new Error("llm requires a node token");const w=JSON.stringify(ee(t,e,o)),y=Buffer.byteLength(w);if(y>k)throw C(y,k);let u=0;for(;;){o.signal?.throwIfAborted();const d=await z(X())("http://localhost/v1/llm",{method:"POST",headers:{authorization:`Bearer ${i}`,"content-type":"application/json"},body:w,signal:o.signal});if(!d.ok){const l=F(await d.json());if(d.status===413||l.code==="payload_too_large")throw C(y,k);if(S(n,B(l)),l.retryable!==!0)throw new b(l.message,void 0,N(l),l.code,d.status);const s=l.retry_after_s;if(typeof s!="number"||!Number.isFinite(s)||s<=0)throw l.code===E?new R(l.message):new Error(l.message);const f=Q-u;if(s>f){const p=Date.now()+s*1e3;throw new b(`${l.message} (retry after ${s}s, at ${new Date(p).toISOString()})`,p,N(l))}await W(s*1e3,void 0,{signal:o.signal}),u+=s;continue}if(!d.body)throw new Error("llm returned no stream");r.push({type:"start",partial:n});const P=d.body.getReader(),A=new TextDecoder;let h="",_="stop",L,I=!1,M=!1;const T=c(l=>{const s=JSON.parse(l);if(s.error){const a=F(s);throw S(n,B(a)),a.code===E?new R(a.message):new Error(a.message)}if(s.served_model){if(M=!0,s.served_model.indexOf("/")<1)throw new Error("llm returned an invalid served_model");S(n,s.served_model)}const f=s.choices?.[0],p=f?.delta;if(p?.reasoning_content){const a=n.content.findIndex(x=>x.type==="thinking"),m=a<0?{type:"thinking",thinking:""}:n.content[a],g=a<0?n.content.push(m)-1:a;if(a<0&&r.push({type:"thinking_start",contentIndex:g,partial:n}),m.type!=="thinking")throw new Error("invalid thinking block");m.thinking+=p.reasoning_content,r.push({type:"thinking_delta",contentIndex:g,delta:p.reasoning_content,partial:n})}if(p?.content){const a=n.content.findIndex(x=>x.type==="text"),m=a<0?{type:"text",text:""}:n.content[a],g=a<0?n.content.push(m)-1:a;if(a<0&&r.push({type:"text_start",contentIndex:g,partial:n}),m.type!=="text")throw new Error("invalid text block");m.text+=p.content,r.push({type:"text_delta",contentIndex:g,delta:p.content,partial:n})}for(const a of p?.tool_calls??[]){const m={type:"toolCall",id:a.id,name:a.function.name,arguments:JSON.parse(a.function.arguments)},g=n.content.push(m)-1;r.push({type:"toolcall_start",contentIndex:g,partial:n}),r.push({type:"toolcall_end",contentIndex:g,toolCall:m,partial:n})}f?.finish_reason&&(_=f.finish_reason),f?.message?.refusal&&(L=f.message.refusal),s.usage&&(I=!0,n.usage={input:s.usage.prompt_tokens,output:s.usage.completion_tokens,cacheRead:s.usage.cache_read_tokens,cacheWrite:s.usage.cache_write_tokens,totalTokens:s.usage.total_tokens,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:typeof s.usage.usd_equivalent=="number"&&Number.isFinite(s.usage.usd_equivalent)?s.usage.usd_equivalent:0}})},"apply");for(;;){const{value:l,done:s}=await P.read();if(s)break;h+=A.decode(l,{stream:!0});let f;for(;(f=h.indexOf(`
2
+ `))>=0;){const p=h.slice(0,f).trim();h=h.slice(f+1),p&&T(p)}}if(h+=A.decode(),h.trim()&&T(h.trim()),!I||!M)throw new Error("llm stream ended without usage or served_model");for(const[l,s]of n.content.entries())s.type==="text"&&r.push({type:"text_end",contentIndex:l,content:s.text,partial:n}),s.type==="thinking"&&r.push({type:"thinking_end",contentIndex:l,content:s.thinking,partial:n});if(_==="content_filter")throw new D(L??"Content filtered");if(!["stop","tool_calls","length"].includes(_))throw new Error(`llm returned unknown finish reason: ${_}`);n.stopReason=_==="tool_calls"?"toolUse":_==="length"?"length":"stop",r.push({type:"done",reason:n.stopReason,message:n}),r.end();return}})().catch(i=>{n.stopReason=o.signal?.aborted?"aborted":"error",n.errorMessage=i instanceof Error?i.message:String(i),i instanceof b&&(n.diagnostics=[{type:$,timestamp:Date.now(),...i.retryAt!==void 0?{details:{retryAt:i.retryAt}}:{}},...i.rateLimit!==void 0?[v({status:429,ratelimit:i.rateLimit})]:[],...i.rateLimit===void 0&&i.code==="cap_exhausted"?[v({status:i.status??402,code:i.code})]:[]]),i instanceof R&&(n.diagnostics=[v({status:503,code:E})]),i instanceof D&&n.stopReason==="error"&&(n.rawStopReason="content_filter"),r.push({type:"error",reason:n.stopReason,error:n}),r.end()}),r}c(te,"streamBrokerModel");export{Q as LLM_BROKER_RETRY_WINDOW_S,$ as LLM_REFUSAL_DIAGNOSTIC,fe as configureBrokerModelRuntime,me as refusalRetryAt,ee as requestBody,te as streamBrokerModel,Z as wireHistory};
@@ -2,9 +2,21 @@ import { type MergedLaunchConfig } from '../config.js';
2
2
  import type { PiInvocation } from './invocation.js';
3
3
  export { CANVAS_EXTENSIONS, CANVAS_STOPHOOK_PATH, CANVAS_INBOX_WATCHER_PATH, CANVAS_RECAP_PATH, CANVAS_GOAL_CAPTURE_PATH, CANVAS_PASSIVE_CONTEXT_PATH, CANVAS_CONTEXT_INTRO_PATH, CANVAS_TOOL_GUIDE_PATH, CANVAS_DOC_SUBSTRATE_PATH, CANVAS_STRUCTURED_OUTPUT_PATH, CANVAS_BASH_VALVE_PATH, } from './canvas-extensions.js';
4
4
  import type { NodeMeta, LaunchSpec, Mode, Lifecycle } from '../canvas/index.js';
5
- import type { ModelIntent, ModelProvider, ScopeConfig } from '../../types.js';
5
+ import type { ModelIntent, ModelProvider, ModelStrength, ScopeConfig } from '../../types.js';
6
6
  export { OPENAI_PROVIDER_ENV, configuredLadderProviders, inferPortableModelSelection } from './model-selection.js';
7
7
  export type { PortableModelSelection } from './model-selection.js';
8
+ /** Resolve a persona/caller `model:` token to the concrete `model:thinking`
9
+ * spec pi gets via `--model`, in order:
10
+ * 1. `provider/rest` — apply strength aliases to `rest`; if `provider` is
11
+ * `anthropic`/`openai` AND `rest` is a strength, return that ladder cell
12
+ * (the word `openai` maps to the openai-codex ladder). Otherwise it is a
13
+ * concrete `provider/id` (incl. any `:thinking` suffix) → pass through.
14
+ * 2. Bare strength (incl. aliases normal/weak) → the default-provider ladder
15
+ * cell (config default provider, then CRTR_MODEL_PROVIDER, else anthropic).
16
+ * 3. Bare family alias (opus/sonnet/haiku) → the Anthropic ladder's
17
+ * strong/medium/light, ALWAYS anthropic (ignores the env/config default).
18
+ * 4. Anything else → pass through unchanged. */
19
+ export declare function modelTokenStrength(model: string): ModelStrength | null;
8
20
  /** True when `model` is a PORTABLE ladder token — a bare strength/alias
9
21
  * (`ultra`, `normal`, `opus`, …), a `<family>/<strength>` pair, or an
10
22
  * anthropic family alias — i.e. a logical preference rather than a concrete
@@ -1,3 +1,3 @@
1
1
  var b=Object.defineProperty;var s=(e,r)=>b(e,"name",{value:r,configurable:!0});import{envProfileId as _}from"../../shared/env.js";import{mkdirSync as H}from"node:fs";import{join as V}from"node:path";import{readMergedLaunchConfig as M}from"../config.js";import{fork as U}from"node:child_process";import{fileURLToPath as D}from"node:url";import{freshChildNodeExecPath as F,recheckChildNode as $}from"./branded-host.js";import{LAUNCH_SYSTEM_PROMPT as G}from"./launch-prompt.js";import{nodeEnv as K}from"./nodes.js";import{editorLabel as W}from"../canvas/index.js";import{CANVAS_EXTENSIONS as Ie,CANVAS_STOPHOOK_PATH as Oe,CANVAS_INBOX_WATCHER_PATH as ye,CANVAS_RECAP_PATH as ve,CANVAS_GOAL_CAPTURE_PATH as Le,CANVAS_PASSIVE_CONTEXT_PATH as Re,CANVAS_CONTEXT_INTRO_PATH as be,CANVAS_TOOL_GUIDE_PATH as He,CANVAS_DOC_SUBSTRATE_PATH as Ve,CANVAS_STRUCTURED_OUTPUT_PATH as Me,CANVAS_BASH_VALVE_PATH as Ue}from"./canvas-extensions.js";import{nodeRunDir as X}from"../canvas/paths.js";import{writeFileBeneath as B}from"../spaces/open-beneath.js";import{projectOutputSchema as j}from"./structured-output.js";import{CANVAS_EXTENSIONS as z,mergeCanvasExtensions as T,assertMandatoryCanvasExtensions as Y}from"./canvas-extensions.js";import{modelLadders as a,defaultProvider as E,STRENGTH_ALIASES as p,MODEL_PROVIDER_KEYS as S,MODEL_STRENGTHS as x,THINKING_SUFFIXES as Q,stripThinkingSuffix as m}from"./model-selection.js";import{OPENAI_PROVIDER_ENV as Fe,configuredLadderProviders as $e,inferPortableModelSelection as Ge}from"./model-selection.js";function P(e,r=a()){return r[e]}s(P,"ladderFor");const g={light:0,medium:1,strong:2,ultra:3};function J(e,r,n){const t=m(e);for(const o of[!0,!1]){const i=o?x:[...x].sort((c,u)=>g[c]-g[u]);for(const c of n)for(const u of i){const f=r[c][u];if(!(o?f!==e:m(f)!==t))return{provider:c,strength:u}}}return null}s(J,"findLadderCell");function C(e){const r=e.lastIndexOf("/"),n=r===-1?void 0:e.slice(0,r),t=r===-1?e:e.slice(r+1),o=p[t];return o!==void 0?o:n!==void 0&&n!=="anthropic"?null:t==="opus"?"strong":t==="sonnet"?"medium":t==="haiku"?"light":null}s(C,"modelTokenStrength");function k(e,r=a()){const n=C(e);return n!==null?n:J(A(e,r),r,S)?.strength??null}s(k,"resolvedModelStrength");function Z(e){return e==="review"||e.startsWith("review/")||e.includes("/reviewers/")}s(Z,"isReviewQualityKind");function q(e,r,n,t=a()){if(r===void 0)return n;if(!Z(e)||n===void 0)return r;const o=k(r,t),i=k(n,t);return o===null||i===null?r:g[o]<g[i]?n:r}s(q,"floorReviewModel");function N(e){if(e.includes("/")){const r=e.lastIndexOf("/"),n=e.slice(0,r),t=e.slice(r+1);return n!==""&&(p[t]!==void 0||n==="anthropic"&&(t==="opus"||t==="sonnet"||t==="haiku"))}return p[e]!==void 0||e==="opus"||e==="sonnet"||e==="haiku"}s(N,"isPortableModelToken");function w(e,r=a()){const n=C(e);if(n!==null)return e.includes("/")?{family:e.slice(0,e.lastIndexOf("/")),strength:n}:e==="opus"||e==="sonnet"||e==="haiku"?{family:"anthropic",strength:n}:{family:E(r),strength:n}}s(w,"logicalModelIntent");function _e(e,r=a()){return N(e)?w(e,r):void 0}s(_e,"explicitModelIntent");function A(e,r=a()){if(e.includes("/")){const t=e.indexOf("/"),o=e.slice(0,t),i=e.slice(t+1),c=p[i];if(c!==void 0&&(o==="anthropic"||o==="openai"))return P(o,r)[c];if(o==="anthropic"){if(i==="opus")return r.anthropic.strong;if(i==="sonnet")return r.anthropic.medium;if(i==="haiku")return r.anthropic.light}return e}const n=p[e];return n!==void 0?P(E(r),r)[n]:e==="opus"?r.anthropic.strong:e==="sonnet"?r.anthropic.medium:e==="haiku"?r.anthropic.light:e}s(A,"normalizeModel");function I(e){const r=e.lastIndexOf(":");if(r<=0)return;const n=e.slice(r+1);return Q.has(n)?n:void 0}s(I,"thinkingSuffixOf");function ee(e=S){const r=e.length>0?e:S,n=a(),t=[];for(const o of x)for(const i of r)t.push(n[i][o]);return t}s(ee,"interleavedLadderCycle");function Te(e,r=1,n){const t=ee(n),o=A(e),i=m(o),c=I(o);let u=t.findIndex(f=>m(f)===i&&I(f)===c);return u===-1&&(u=t.findIndex(f=>m(f)===i)),u===-1?t[0]:t[(u+r+t.length)%t.length]}s(Te,"nextLadderModel");function O(e,r,n,t){const o=t.kinds[e],i=t.modelLadders,c=r==="orchestrator"?o?.orchestratorModel??o?.model:o?.model,u=n.modelExact===!0?n.model:q(e,n.model,c,i),f=n.modelExact===!0||n.modelOverride===!0&&n.model!==void 0&&!N(n.model),l=n.modelExact===!0?u:u!==void 0?A(u,i):void 0,h=f?void 0:n.modelIntent??(u!==void 0?w(u,i):void 0);return{launch:{model:l,modelIntent:h,modelExact:f?!0:void 0,tools:o?.tools??[],extensions:T([...z,...o?.extensions??[]]),systemPrompt:G,env:{...n.extraEnv??{},...h?{CRTR_MODEL_INTENT:`${h.family}/${h.strength}`}:{}}},lifecycle:n.lifecycle}}s(O,"buildLaunchSpecFromMerged");function Ee(e,r,n){return O(e,r,n,M(n.cwd??process.cwd(),n.profileId!==void 0?n.profileId:_()||null))}s(Ee,"buildLaunchSpec");async function Pe(e,r,n){const t=n.cwd??process.cwd(),o=n.profileId!==void 0?n.profileId:_()||null,i=await re(t,o);return O(e,r,n,i)}s(Pe,"buildLaunchSpecAsync");const y=15e3;function ne(e,r,n){const t=r!==null?`was killed by ${r}`:`exited with code ${e}`,o=n.trim().split(`
2
2
  `).slice(-8).join(`
3
- `).slice(-1500);return`launch config subprocess ${t}${o!==""?`: ${o}`:" (no stderr output)"}`}s(ne,"describeLaunchConfigExit");class v extends Error{static{s(this,"LaunchConfigWorkerCrash")}}async function re(e,r,n={}){const t=n.execPath??await F(),o=n.workerPath??D(new URL("./launch-config-worker.js",import.meta.url));try{return await L(e,r,t,o)}catch(i){if(!(i instanceof v))throw i;const c=await $(t);if(c===t)throw i;return L(e,r,c,o)}}s(re,"readMergedLaunchConfigAsync");function L(e,r,n,t){return new Promise((o,i)=>{const c=U(t,[],{execPath:n,stdio:["ignore","ignore","pipe","ipc"],serialization:"advanced"});let u="";c.stderr?.setEncoding("utf8").on("data",d=>{u=(u+d).slice(-8192)}),c.send({cwd:e,profileId:r});let f=!1;const l=s(d=>{f||(f=!0,clearTimeout(h),c.connected&&c.disconnect(),c.killed||c.kill("SIGKILL"),d())},"finish"),h=setTimeout(()=>l(()=>i(new Error(`timed out after ${y}ms reading launch config for ${e}`))),y);c.once("message",d=>{d.error!==void 0?l(()=>i(new Error(d.error))):d.config!==void 0?l(()=>o(d.config)):l(()=>i(new Error("launch config subprocess returned no result")))}),c.once("error",d=>l(()=>i(d))),c.once("close",(d,R)=>{d!==0&&!f&&l(()=>i(new v(ne(d,R,u))))})})}s(L,"runLaunchConfigWorker");function te(e,r){try{const n=X(e);H(n,{recursive:!0});const t=V(n,"system-prompt.md");return B(n,t,r,{atomic:!0}),t}catch{return null}}s(te,"writeSystemPromptFile");function Ce(e,r={}){const n=e.launch,t=T(n?.extensions);Y(t);const o=[];for(const i of t)o.push("-e",i);if(o.push("-n",W(e)),r.forkFrom!==void 0&&r.forkFrom!=="")o.push("--fork",r.forkFrom);else{const i=r.resumeSessionPath??r.resumeSessionId;i!==void 0&&o.push("--session",i),r.newCycle===!0&&o.push("--crtr-new-cycle")}if(n?.model!==void 0&&o.push("--model",n.model),n?.modelExact===!0&&o.push("--crtr-model-exact"),n?.tools!==void 0&&n.tools.length>0&&o.push("--tools",n.tools.join(",")),n?.systemPrompt!==void 0&&n.systemPrompt!==""){const i=te(e.node_id,n.systemPrompt)??n.systemPrompt;o.push("--append-system-prompt",i)}return r.prompt!==void 0&&r.prompt!==""&&o.push(r.prompt),j(e.node_id),{argv:o,env:K(e)}}s(Ce,"buildPiArgv");function ke(e){for(const[t,o]of Object.entries(e.env))process.env[t]=o;const r={cwd:e.env.CRTR_NODE_CWD??process.cwd(),extensionPaths:[]},n=e.argv;for(let t=0;t<n.length;t++){const o=n[t];switch(o){case"-e":r.extensionPaths.push(n[++t]);break;case"-n":r.editorName=n[++t];break;case"--fork":r.forkFrom=n[++t];break;case"--session":{const i=n[++t];i.includes("/")||i.endsWith(".jsonl")?r.resumeSessionPath=i:r.resumeSessionId=i;break}case"--model":r.model=n[++t];break;case"--crtr-model-exact":r.modelExact=!0;break;case"--tools":r.tools=n[++t].split(",").filter(i=>i!=="");break;case"--append-system-prompt":r.appendSystemPromptPath=n[++t];break;case"--crtr-new-cycle":r.newCycle=!0;break;default:r.firstPrompt=o;break}}return r}s(ke,"piInvocationToSdkConfig");export{Ue as CANVAS_BASH_VALVE_PATH,be as CANVAS_CONTEXT_INTRO_PATH,Ve as CANVAS_DOC_SUBSTRATE_PATH,Ie as CANVAS_EXTENSIONS,Le as CANVAS_GOAL_CAPTURE_PATH,ye as CANVAS_INBOX_WATCHER_PATH,Re as CANVAS_PASSIVE_CONTEXT_PATH,ve as CANVAS_RECAP_PATH,Oe as CANVAS_STOPHOOK_PATH,Me as CANVAS_STRUCTURED_OUTPUT_PATH,He as CANVAS_TOOL_GUIDE_PATH,Fe as OPENAI_PROVIDER_ENV,Ee as buildLaunchSpec,Pe as buildLaunchSpecAsync,Ce as buildPiArgv,$e as configuredLadderProviders,ne as describeLaunchConfigExit,_e as explicitModelIntent,Ge as inferPortableModelSelection,ee as interleavedLadderCycle,N as isPortableModelToken,w as logicalModelIntent,Te as nextLadderModel,A as normalizeModel,ke as piInvocationToSdkConfig,re as readMergedLaunchConfigAsync};
3
+ `).slice(-1500);return`launch config subprocess ${t}${o!==""?`: ${o}`:" (no stderr output)"}`}s(ne,"describeLaunchConfigExit");class v extends Error{static{s(this,"LaunchConfigWorkerCrash")}}async function re(e,r,n={}){const t=n.execPath??await F(),o=n.workerPath??D(new URL("./launch-config-worker.js",import.meta.url));try{return await L(e,r,t,o)}catch(i){if(!(i instanceof v))throw i;const c=await $(t);if(c===t)throw i;return L(e,r,c,o)}}s(re,"readMergedLaunchConfigAsync");function L(e,r,n,t){return new Promise((o,i)=>{const c=U(t,[],{execPath:n,stdio:["ignore","ignore","pipe","ipc"],serialization:"advanced"});let u="";c.stderr?.setEncoding("utf8").on("data",d=>{u=(u+d).slice(-8192)}),c.send({cwd:e,profileId:r});let f=!1;const l=s(d=>{f||(f=!0,clearTimeout(h),c.connected&&c.disconnect(),c.killed||c.kill("SIGKILL"),d())},"finish"),h=setTimeout(()=>l(()=>i(new Error(`timed out after ${y}ms reading launch config for ${e}`))),y);c.once("message",d=>{d.error!==void 0?l(()=>i(new Error(d.error))):d.config!==void 0?l(()=>o(d.config)):l(()=>i(new Error("launch config subprocess returned no result")))}),c.once("error",d=>l(()=>i(d))),c.once("close",(d,R)=>{d!==0&&!f&&l(()=>i(new v(ne(d,R,u))))})})}s(L,"runLaunchConfigWorker");function te(e,r){try{const n=X(e);H(n,{recursive:!0});const t=V(n,"system-prompt.md");return B(n,t,r,{atomic:!0}),t}catch{return null}}s(te,"writeSystemPromptFile");function Ce(e,r={}){const n=e.launch,t=T(n?.extensions);Y(t);const o=[];for(const i of t)o.push("-e",i);if(o.push("-n",W(e)),r.forkFrom!==void 0&&r.forkFrom!=="")o.push("--fork",r.forkFrom);else{const i=r.resumeSessionPath??r.resumeSessionId;i!==void 0&&o.push("--session",i),r.newCycle===!0&&o.push("--crtr-new-cycle")}if(n?.model!==void 0&&o.push("--model",n.model),n?.modelExact===!0&&o.push("--crtr-model-exact"),n?.tools!==void 0&&n.tools.length>0&&o.push("--tools",n.tools.join(",")),n?.systemPrompt!==void 0&&n.systemPrompt!==""){const i=te(e.node_id,n.systemPrompt)??n.systemPrompt;o.push("--append-system-prompt",i)}return r.prompt!==void 0&&r.prompt!==""&&o.push(r.prompt),j(e.node_id),{argv:o,env:K(e)}}s(Ce,"buildPiArgv");function ke(e){for(const[t,o]of Object.entries(e.env))process.env[t]=o;const r={cwd:e.env.CRTR_NODE_CWD??process.cwd(),extensionPaths:[]},n=e.argv;for(let t=0;t<n.length;t++){const o=n[t];switch(o){case"-e":r.extensionPaths.push(n[++t]);break;case"-n":r.editorName=n[++t];break;case"--fork":r.forkFrom=n[++t];break;case"--session":{const i=n[++t];i.includes("/")||i.endsWith(".jsonl")?r.resumeSessionPath=i:r.resumeSessionId=i;break}case"--model":r.model=n[++t];break;case"--crtr-model-exact":r.modelExact=!0;break;case"--tools":r.tools=n[++t].split(",").filter(i=>i!=="");break;case"--append-system-prompt":r.appendSystemPromptPath=n[++t];break;case"--crtr-new-cycle":r.newCycle=!0;break;default:r.firstPrompt=o;break}}return r}s(ke,"piInvocationToSdkConfig");export{Ue as CANVAS_BASH_VALVE_PATH,be as CANVAS_CONTEXT_INTRO_PATH,Ve as CANVAS_DOC_SUBSTRATE_PATH,Ie as CANVAS_EXTENSIONS,Le as CANVAS_GOAL_CAPTURE_PATH,ye as CANVAS_INBOX_WATCHER_PATH,Re as CANVAS_PASSIVE_CONTEXT_PATH,ve as CANVAS_RECAP_PATH,Oe as CANVAS_STOPHOOK_PATH,Me as CANVAS_STRUCTURED_OUTPUT_PATH,He as CANVAS_TOOL_GUIDE_PATH,Fe as OPENAI_PROVIDER_ENV,Ee as buildLaunchSpec,Pe as buildLaunchSpecAsync,Ce as buildPiArgv,$e as configuredLadderProviders,ne as describeLaunchConfigExit,_e as explicitModelIntent,Ge as inferPortableModelSelection,ee as interleavedLadderCycle,N as isPortableModelToken,w as logicalModelIntent,C as modelTokenStrength,Te as nextLadderModel,A as normalizeModel,ke as piInvocationToSdkConfig,re as readMergedLaunchConfigAsync};
@@ -1,6 +1,6 @@
1
1
  import { type SpawnNodeOpts } from './nodes.js';
2
2
  import { type WakeOrigin } from './bearings.js';
3
- import { type NodeMeta, type Mode, type Lifecycle, type OutcomeDeliveryBinding, type ReviewBinding } from '../canvas/index.js';
3
+ import { type LaunchSpec, type NodeMeta, type Mode, type Lifecycle, type OutcomeDeliveryBinding, type ReviewBinding } from '../canvas/index.js';
4
4
  import { type ModelRegistryLike, type ModelRequest } from '../model-routes.js';
5
5
  export interface SpawnChildOpts {
6
6
  kind: string;
@@ -110,6 +110,9 @@ export declare function resolveForkSource(value: string): string;
110
110
  export declare function resolveProfileId(explicit: string | null | undefined, spawner: string | null, cwd: string, options?: {
111
111
  readOnlySelection?: boolean;
112
112
  }): Promise<string | null>;
113
+ /** Under an app-paid grant (RT-RTE-24) the node's model is the app rung resolver's choice, never the owner's ladder: the
114
+ * recipe records the rung's catalog model and the intent `app/<strength>`. A user-paid grant leaves the recipe as built. */
115
+ export declare function appPaidLaunch(launch: LaunchSpec, grantId: string | null | undefined, requested: string | undefined): LaunchSpec;
113
116
  /** Reject a permanently invalid launch recipe against the registry that will
114
117
  * serve it. Registered-but-unauthenticated/cooling requests intentionally pass
115
118
  * this authoring check so broker policy for transient availability is unchanged. */
@@ -1,3 +1,3 @@
1
- var ie=Object.defineProperty;var a=(e,o)=>ie(e,"name",{value:o,configurable:!0});import{accessSync as te,constants as de}from"node:fs";import{isAbsolute as ae,resolve as se,join as ce}from"node:path";import{appSpace as le}from"../layout.js";import{ApiError as V}from"../../api/errors.js";import{spawnNode as fe,forkSourceNode as ue,currentNodeContext as me,rootOfSpine as he,newNodeId as we,preflightNodeId as pe}from"./nodes.js";import{resolveProfileOperand as ke}from"../profiles/manifest.js";import{selectProfileForCwd as _e,selectProfileForCwdReadOnly as ve}from"../profiles/select.js";import{buildLaunchSpecAsync as X,buildPiArgv as ye}from"./launch.js";import{createManagedWorktreeAsync as ge,rollbackManagedWorktreeAsync as be}from"../worktree-mutation-async.js";import{usage as u,brokerLaunchFailed as P}from"../errors.js";import{writeGoal as xe}from"./kickoff.js";import{appendSituationalContext as Ce,formatSituationalProse as Fe}from"./situational-context.js";import{ensureRoadmap as Se}from"./roadmap.js";import{buildWakeBearings as $e}from"./bearings.js";import{encodeKickoffOrigin as Ee,KICKOFF_ORIGIN_ENV as Oe}from"./stamp/protocol.js";import{beginExecution as Re,crtrHome as Pe,getNode as f,fullName as G,jobDir as Ie,recordExecutionPid as Ne,abortExecution as D,setFrozen as Be}from"../canvas/index.js";import{contextDir as A,nodeAgentDir as L}from"../canvas/node-agent-paths.js";import{copyTreeBeneath as De}from"../spaces/open-beneath.js";import{conversationIdFromPath as I,conversationStore as x}from"../conversation-store/index.js";import{appMemoryTooSmall as Ae,boundFleet as Le,brokerThresholdsForDaemon as Te}from"./fleet.js";import{admitBrokerMemory as je}from"./memory-admission.js";import{emitEvent as Me}from"../events/emit.js";import{openViewerWindow as We,focusOf as He,windowOfPane as Ke}from"./placement.js";import{waitForBrokerViewSocket as qe}from"./placement-tmux.js";import{transition as w}from"./lifecycle.js";import{beginBootFaultAttempt as ze}from"../canvas/recovery.js";import{headlessBrokerHost as T}from"./host.js";import{ensureDaemon as Ue}from"../../daemon/manage.js";import{readConfig as Ve}from"../config.js";import{modelRequestFromConfig as Xe,unregisteredConcreteModel as Ge}from"../model-routes.js";import{openModelRegistry as Je}from"./model-registry.js";import{MODEL_SPEC_NEXT as Qe}from"./model-selection.js";import{forkNodeLedger as Ye}from"./ledger.js";import{discoverLifecycleHookRegistry as Ze}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as en}from"../command-hooks/transport/exec-lifecycle.js";function p(e){return{detail:{schema:"crtr.node-outcome-detail/v1",message:e instanceof Error?e.message:String(e)}}}a(p,"launchFailureOutcome");async function nn(e,o,d){try{return await T.launch(e,o,d)}catch(r){try{w(e,"crash",{reason:"launch_failed",outcome:p(r)})}catch{}const t=r.message;throw P(t.startsWith("[broker]")?t:`[broker] refusing to launch ${e}: ${t}`,"Inspect the cause above, fix the launch recipe or environment, then retry.")}}a(nn,"launchBrokerOrCrash");function on(e,o){try{w(e,"crash",{reason:"launch_failed",outcome:p(o)})}catch{}try{T.teardown(e)}catch{}}a(on,"crashAndTearDown");function rn(e){const o=x().list().map(({conversation_id:t,path:s})=>({id:t,path:s})),d=o.filter(t=>t.id===e),r=d.length>0?d:o.filter(t=>t.id.startsWith(e));if(r.length===0)throw u(`--fork-from '${e}': no pi session with that id found.`,{next:"Pass a live node id, a real session uuid/prefix, or an absolute .jsonl session path."});if(r.length>1)throw u(`--fork-from '${e}': ambiguous \u2014 ${r.length} sessions match that id prefix; pass the full id or the .jsonl path.`,{next:"Pass the full session uuid or an absolute .jsonl path to disambiguate."});return r[0].path}a(rn,"resolveSessionUuid");function J(e){const o=e.trim();if(o==="")throw u("--fork-from requires a node id, session file, or session uuid.",{next:"Pass a live node id, an absolute .jsonl session path, or a session uuid/prefix."});if(o.includes("/")||o.endsWith(".jsonl")){const r=I(ae(o)?o:se(process.cwd(),o));if(r===null)throw u(`--fork-from '${o}': invalid conversation path.`,{next:"Pass a conversation file path or id."});return x().header(r).path}const d=f(o);if(d!==null){const r=d.pi_session_file;if(r==null||r==="")throw u(`node ${o} has no pi session yet \u2014 it has not captured a session FILE to fork from (the broker forks a .jsonl path, not a bare id).`,{next:"Pick a node that has captured a session, or drop --fork-from."});const t=I(r);if(t===null)throw u(`node ${o} has no valid conversation id.`,{next:"Pick a node with a captured conversation."});return x().header(t).path}return rn(o)}a(J,"resolveForkSource");async function tn(e,o,d,r={}){return e===null?null:e!==void 0&&e!==""?ke(e).profileId:o!==null?f(o)?.profile_id??null:r.readOnlySelection===!0?ve(d):_e(d)}a(tn,"resolveProfileId");function Q(e){const o=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return Xe(e.model,o,e.modelExact===!0)}a(Q,"requestFromLaunch");async function Y(e,o,d){if(e===void 0||e.kind==="logical")return;const r=Ge(e,d??await Je(),o);if(r!==void 0)throw u(`model '${r.request.spec}' is not registered in this daemon.`,{received:r.request.spec,next:Qe})}a(Y,"assertLaunchModelRegistered");function dn(e,o,d){const r=e??o??null;if(!d&&r===null)throw new Error("spawnChild requires a calling node (CRTR_NODE_ID) or an explicit parent");return r}a(dn,"resolveSpawner");async function Z(e,o,d){try{Ue()}catch{}const r=me(),t=e.root===!0,s=dn(e.parent,r.nodeId??null,t),c=e.mode??"base",k=e.rootLifecycle??(t?"resident":"terminal"),ee=t&&k==="resident",j=s===null?null:f(s),ne=e.creator===void 0||e.creator===null?null:f(e.creator);e.nodeId!==void 0&&pe(e.nodeId);const _=e.forkFrom!==void 0?J(e.forkFrom):void 0,M=_===void 0?null:ue(_),N=[j,ne,M].some(l=>l?.isolated===!0||l?.run_id!=null&&f(l.run_id)?.isolated===!0);if(N&&e.isolated===!1)throw new V(403,"isolated_run","isolation cannot be turned off under an isolated run",{param:"isolated"});const S=N||e.isolated===!0;if(S&&e.worktree===!0)throw new V(400,"invalid_request","isolated nodes cannot use a worktree",{param:"worktree"});const $=e.worktree===!0,v=S||$?e.nodeId??we():e.nodeId,E=S?e.run!==void 0&&t&&!N?e.cwd:ce(le(e.run?.grantee??j?.grantee??"app:terminal").nodes,v):e.cwd,C=await tn(e.profile,s,E),W=(await X(e.kind,c,{lifecycle:k,hasManager:!t,model:e.model,modelOverride:e.model!==void 0,cwd:E,profileId:C})).launch;await Y(Q(W),{cwd:E,profileId:C});const H=M?.node_id??null;let y,O=E;try{$&&(y=await ge(e.worktreeCwd??e.cwd,v,e.worktreeBase),O=y.path);const l=$?(await X(e.kind,c,{lifecycle:k,hasManager:!t,model:e.model,modelOverride:e.model!==void 0,cwd:O,profileId:C})).launch:W;$&&await Y(Q(l),{cwd:O,profileId:C});const n=await fe({kind:e.kind,mode:c,lifecycle:k,cwd:O,name:e.name??e.kind,description:e.description,parent:t?null:s,creator:e.creator,...e.actor===void 0?{}:{actor:e.actor},forkSourceNode:H,spawnedBy:t?s??void 0:void 0,profile_id:C,...e.scopes===void 0?{}:{scopes:e.scopes},isolated:S,...e.run===void 0?{}:{run:e.run},...e.withinCreate===void 0?{}:{withinCreate:e.withinCreate},forkFrom:e.forkFrom,forkSourceFile:_,modelOverride:e.model===void 0?void 0:l.model,...y!==void 0?{managedWorktree:y}:{},...v!==void 0?{nodeId:v}:{},...e.reviewBinding===void 0?{}:{reviewBinding:e.reviewBinding},...e.deadlineAt===void 0?{}:{deadlineAt:e.deadlineAt},...e.outcomeDelivery===void 0?{}:{outcomeDelivery:e.outcomeDelivery},launch:l});if(d?.(n.node_id),e.forkFrom!==void 0)try{Ye(n.node_id,H??null)}catch(i){throw w(n.node_id,"crash",{reason:"launch_failed",outcome:p(i)}),i}if(xe(n.node_id,e.prompt),e.situationalContext!==void 0&&Ce(n.node_id,Fe(e.situationalContext)),o!==void 0)try{o(n.node_id)}catch(i){throw w(n.node_id,"crash",{reason:"launch_failed",outcome:p(i)}),i}const B=e.prompt!=="",oe=`${B&&e.wakeOrigin!==void 0?`${$e(e.wakeOrigin)}
1
+ var ae=Object.defineProperty;var a=(e,o)=>ae(e,"name",{value:o,configurable:!0});import{accessSync as se,constants as le}from"node:fs";import{isAbsolute as ce,resolve as fe,join as ue}from"node:path";import{appSpace as me}from"../layout.js";import{ApiError as q}from"../../api/errors.js";import{spawnNode as he,forkSourceNode as we,currentNodeContext as pe,rootOfSpine as ke,newNodeId as _e,preflightNodeId as ve}from"./nodes.js";import{resolveProfileOperand as ge}from"../profiles/manifest.js";import{selectProfileForCwd as ye,selectProfileForCwdReadOnly as be}from"../profiles/select.js";import{buildLaunchSpecAsync as Y,buildPiArgv as xe}from"./launch.js";import{createManagedWorktreeAsync as Ce,rollbackManagedWorktreeAsync as Ee}from"../worktree-mutation-async.js";import{usage as u,brokerLaunchFailed as I}from"../errors.js";import{writeGoal as $e}from"./kickoff.js";import{appendSituationalContext as Fe,formatSituationalProse as Oe}from"./situational-context.js";import{ensureRoadmap as Re}from"./roadmap.js";import{buildWakeBearings as Se}from"./bearings.js";import{encodeKickoffOrigin as Ie,KICKOFF_ORIGIN_ENV as Ne}from"./stamp/protocol.js";import{beginExecution as Pe,crtrHome as De,getNode as f,fullName as J,jobDir as Te,recordExecutionPid as Be,abortExecution as B,setFrozen as Le}from"../canvas/index.js";import{contextDir as L,nodeAgentDir as A}from"../canvas/node-agent-paths.js";import{copyTreeBeneath as Ae}from"../spaces/open-beneath.js";import{conversationIdFromPath as N,conversationStore as x}from"../conversation-store/index.js";import{appMemoryTooSmall as Me,boundFleet as je,brokerThresholdsForDaemon as We}from"./fleet.js";import{admitBrokerMemory as He}from"./memory-admission.js";import{emitEvent as Ke}from"../events/emit.js";import{openViewerWindow as ze,focusOf as Ge,windowOfPane as Ue}from"./placement.js";import{waitForBrokerViewSocket as Ve}from"./placement-tmux.js";import{transition as w}from"./lifecycle.js";import{beginBootFaultAttempt as Xe}from"../canvas/recovery.js";import{headlessBrokerHost as M}from"./host.js";import{ensureDaemon as qe}from"../../daemon/manage.js";import{readConfig as Ye}from"../config.js";import{modelRequestFromConfig as Je,unregisteredConcreteModel as Qe}from"../model-routes.js";import{openModelRegistry as Ze}from"./model-registry.js";import{MODEL_SPEC_NEXT as en}from"./model-selection.js";import{forkNodeLedger as nn}from"./ledger.js";import{appRungForGrant as on}from"../llm/app-rungs.js";import{APP_FAMILY as j}from"../model-routes.js";import{discoverLifecycleHookRegistry as rn}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as tn}from"../command-hooks/transport/exec-lifecycle.js";function p(e){return{detail:{schema:"crtr.node-outcome-detail/v1",message:e instanceof Error?e.message:String(e)}}}a(p,"launchFailureOutcome");async function dn(e,o,d){try{return await M.launch(e,o,d)}catch(r){try{w(e,"crash",{reason:"launch_failed",outcome:p(r)})}catch{}const t=r.message;throw I(t.startsWith("[broker]")?t:`[broker] refusing to launch ${e}: ${t}`,"Inspect the cause above, fix the launch recipe or environment, then retry.")}}a(dn,"launchBrokerOrCrash");function an(e,o){try{w(e,"crash",{reason:"launch_failed",outcome:p(o)})}catch{}try{M.teardown(e)}catch{}}a(an,"crashAndTearDown");function sn(e){const o=x().list().map(({conversation_id:t,path:s})=>({id:t,path:s})),d=o.filter(t=>t.id===e),r=d.length>0?d:o.filter(t=>t.id.startsWith(e));if(r.length===0)throw u(`--fork-from '${e}': no pi session with that id found.`,{next:"Pass a live node id, a real session uuid/prefix, or an absolute .jsonl session path."});if(r.length>1)throw u(`--fork-from '${e}': ambiguous \u2014 ${r.length} sessions match that id prefix; pass the full id or the .jsonl path.`,{next:"Pass the full session uuid or an absolute .jsonl path to disambiguate."});return r[0].path}a(sn,"resolveSessionUuid");function Q(e){const o=e.trim();if(o==="")throw u("--fork-from requires a node id, session file, or session uuid.",{next:"Pass a live node id, an absolute .jsonl session path, or a session uuid/prefix."});if(o.includes("/")||o.endsWith(".jsonl")){const r=N(ce(o)?o:fe(process.cwd(),o));if(r===null)throw u(`--fork-from '${o}': invalid conversation path.`,{next:"Pass a conversation file path or id."});return x().header(r).path}const d=f(o);if(d!==null){const r=d.pi_session_file;if(r==null||r==="")throw u(`node ${o} has no pi session yet \u2014 it has not captured a session FILE to fork from (the broker forks a .jsonl path, not a bare id).`,{next:"Pick a node that has captured a session, or drop --fork-from."});const t=N(r);if(t===null)throw u(`node ${o} has no valid conversation id.`,{next:"Pick a node with a captured conversation."});return x().header(t).path}return sn(o)}a(Q,"resolveForkSource");async function ln(e,o,d,r={}){return e===null?null:e!==void 0&&e!==""?ge(e).profileId:o!==null?f(o)?.profile_id??null:r.readOnlySelection===!0?be(d):ye(d)}a(ln,"resolveProfileId");function Z(e){const o=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return Je(e.model,o,e.modelExact===!0)}a(Z,"requestFromLaunch");function ee(e,o,d){const r=d??(e.modelIntent?`${e.modelIntent.family}/${e.modelIntent.strength}`:e.model),t=on(o,r,e.modelExact===!0);if(t===null)return e;const{CRTR_MODEL_INTENT:s,...l}=e.env??{};return{...e,model:t.model,modelIntent:{family:j,strength:t.strength},modelExact:void 0,env:{...l,CRTR_MODEL_INTENT:`${j}/${t.strength}`}}}a(ee,"appPaidLaunch");async function ne(e,o,d){if(e===void 0||e.kind==="logical"&&e.family!==j)return;const r=Qe(e.kind==="logical"?{kind:"concrete",spec:e.spec}:e,d??await Ze(),o);if(r!==void 0)throw u(`model '${r.request.spec}' is not registered in this daemon.`,{received:r.request.spec,next:en})}a(ne,"assertLaunchModelRegistered");function cn(e,o,d){const r=e??o??null;if(!d&&r===null)throw new Error("spawnChild requires a calling node (CRTR_NODE_ID) or an explicit parent");return r}a(cn,"resolveSpawner");async function oe(e,o,d){try{qe()}catch{}const r=pe(),t=e.root===!0,s=cn(e.parent,r.nodeId??null,t),l=e.mode??"base",k=e.rootLifecycle??(t?"resident":"terminal"),re=t&&k==="resident",P=s===null?null:f(s),ie=e.creator===void 0||e.creator===null?null:f(e.creator);e.nodeId!==void 0&&ve(e.nodeId);const _=e.forkFrom!==void 0?Q(e.forkFrom):void 0,W=_===void 0?null:we(_),D=[P,ie,W].some(c=>c?.isolated===!0||c?.run_id!=null&&f(c.run_id)?.isolated===!0);if(D&&e.isolated===!1)throw new q(403,"isolated_run","isolation cannot be turned off under an isolated run",{param:"isolated"});const $=D||e.isolated===!0;if($&&e.worktree===!0)throw new q(400,"invalid_request","isolated nodes cannot use a worktree",{param:"worktree"});const F=e.worktree===!0,v=$||F?e.nodeId??_e():e.nodeId,O=$?e.run!==void 0&&t&&!D?e.cwd:ue(me(e.run?.grantee??P?.grantee??"app:terminal").nodes,v):e.cwd,C=await ln(e.profile,s,O),H=e.run?.grant_id??P?.grant_id??null,K=ee((await Y(e.kind,l,{lifecycle:k,hasManager:!t,model:e.model,modelOverride:e.model!==void 0,cwd:O,profileId:C})).launch,H,e.model);await ne(Z(K),{cwd:O,profileId:C});const z=W?.node_id??null;let g,R=O;try{F&&(g=await Ce(e.worktreeCwd??e.cwd,v,e.worktreeBase),R=g.path);const c=F?ee((await Y(e.kind,l,{lifecycle:k,hasManager:!t,model:e.model,modelOverride:e.model!==void 0,cwd:R,profileId:C})).launch,H,e.model):K;F&&await ne(Z(c),{cwd:R,profileId:C});const n=await he({kind:e.kind,mode:l,lifecycle:k,cwd:R,name:e.name??e.kind,description:e.description,parent:t?null:s,creator:e.creator,...e.actor===void 0?{}:{actor:e.actor},forkSourceNode:z,spawnedBy:t?s??void 0:void 0,profile_id:C,...e.scopes===void 0?{}:{scopes:e.scopes},isolated:$,...e.run===void 0?{}:{run:e.run},...e.withinCreate===void 0?{}:{withinCreate:e.withinCreate},forkFrom:e.forkFrom,forkSourceFile:_,modelOverride:e.model===void 0?void 0:c.model,...g!==void 0?{managedWorktree:g}:{},...v!==void 0?{nodeId:v}:{},...e.reviewBinding===void 0?{}:{reviewBinding:e.reviewBinding},...e.deadlineAt===void 0?{}:{deadlineAt:e.deadlineAt},...e.outcomeDelivery===void 0?{}:{outcomeDelivery:e.outcomeDelivery},launch:c});if(d?.(n.node_id),e.forkFrom!==void 0)try{nn(n.node_id,z??null)}catch(i){throw w(n.node_id,"crash",{reason:"launch_failed",outcome:p(i)}),i}if($e(n.node_id,e.prompt),e.situationalContext!==void 0&&Fe(n.node_id,Oe(e.situationalContext)),o!==void 0)try{o(n.node_id)}catch(i){throw w(n.node_id,"crash",{reason:"launch_failed",outcome:p(i)}),i}const T=e.prompt!=="",te=`${T&&e.wakeOrigin!==void 0?`${Se(e.wakeOrigin)}
2
2
 
3
- `:""}${e.prompt}`;c==="orchestrator"&&Se(n.node_id,{goal:e.prompt.trim()}),await an(n);let K;if(_!==void 0)try{const i=I(_);if(i===null)throw new Error(`invalid fork source ${_}`);const h=x().fork(i,n.node_id);K=x().header(h).path}catch(i){throw w(n.node_id,"crash",{reason:"launch_failed",outcome:p(i)}),i}const g=ye(n,{prompt:oe,resumeSessionPath:K});if(g.env={...g.env,CRTR_SUBTREE:he(n.node_id)},B){const i=e.wakeOrigin!==void 0?{type:"runtime",kind:"wake",wake:e.wakeOrigin}:{type:"runtime",kind:"kickoff",...n.spawned_by!=null&&n.spawned_by!==""?{spawnedBy:n.spawned_by}:{}};g.env[Oe]=Ee(i)}const b=Le(),q=b.reserveSlot(n.node_id),m=q?await je(n.node_id):null;if(m?.verdict==="too_small"){b.releaseReservation(n.node_id);const i=Ae(m);throw w(n.node_id,"crash",{reason:"launch_failed",outcome:p(i)}),i}if(!q||m?.verdict==="denied")return m?.verdict==="denied"&&b.releaseReservation(n.node_id),Be(n.node_id,new Date().toISOString()),Me({level:"info",event:"broker.frozen",node_id:n.node_id,fields:m?.verdict==="denied"?{reason:"app_memory",free_bytes:m.free_bytes,needed_bytes:m.needed_bytes}:{reason:"broker_cap",live_count:b.size(),hard_cap:Te().automaticReviveCap}}),{node:f(n.node_id),frozen:!0,window:null,session:null};const re=ze(n.node_id),F=Re(n.node_id,{daemonEpoch:b.epoch()});g.env={...g.env,CRTR_EXECUTION_ID:F};let R;try{R=await nn(n.node_id,g,{cwd:n.cwd,name:G(n),resuming:!1})}catch(i){throw D(F,{reason:"launch_failed"}),i}finally{b.releaseReservation(n.node_id)}if(R.pid===null){const i=new Error(`broker host returned no pid for ${n.node_id}`);throw D(F,{reason:"launch_failed"}),w(n.node_id,"crash",{reason:"launch_failed",outcome:p(i)}),P(`failed to launch the broker engine for ${n.node_id} (${n.name}) \u2014 the node was not started.`,`Inspect canonical event diagnostics with \`crtr sys logs --node ${n.node_id}\`, then verify the pi engine can start in this environment.`)}if(Ne(F,n.node_id,R.pid)==="shutdown")throw D(F,{reason:"superseded"}),T.teardown(n.node_id),P(`broker execution was superseded for ${n.node_id}`,"Retry spawning the node.");if(ee&&e.readiness==="await"&&!await qe(n.node_id,R.exited)){const i=re.explanation();throw on(n.node_id,new Error(i??`broker view socket never bound for ${n.node_id}`)),P(i!==null?`the root broker ${n.node_id} could not start \u2014 ${i}`:`the root broker ${n.node_id} never bound its view socket \u2014 it was not started.`,i!==null?"Resolve the cause named above, then retry.":`The broker engine exited before binding its view socket. Inspect canonical event diagnostics with \`crtr sys logs --node ${n.node_id}\`, then retry.`)}let z=null,U=null;if(!t&&s!==null&&Ve("user").auto_open_child_viewers)try{const i=He(s);if(i!==null&&i.pane!==null&&i.pane!==""){const h=We(n.node_id,i.session??"",{name:G(n),cwd:e.cwd,besidePane:i.pane,waitForBroker:!0,initialWhip:B});h!==null&&h.pane!==null&&h.pane!==""&&(U=h.session,z=Ke(h.pane))}}catch{}return{node:f(n.node_id),frozen:!1,window:z,session:U}}catch(l){throw y!==void 0&&v!==void 0&&f(v)===null&&await be(y),l}}a(Z,"spawnChildPrepared");async function Vn(e){return Z(e)}a(Vn,"spawnChild");async function an(e){const o=Ze(e.cwd,e.profile_id).plans.get("node:start")??[];await en(o,{node:{id:e.node_id,name:e.name,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,cwd:e.cwd,nodeDir:L(e.node_id),contextDir:A(e.node_id),jobDir:Ie(e.node_id)},runtime:{isBirth:!0,canvasHome:Pe(),profile:e.profile_id??null}})}a(an,"invokeBirthLifecycleHooks");const sn=new Set(["initial-prompt.md","yield-message.md","result.json","jobs"]);async function Xn(e,o,d){const r=f(e);if(r===null)throw u(`unknown node: ${e}`,{received:e,next:"List nodes and pass the id of a node with a captured pi session."});const t=J(e),s=A(e);try{x().header(I(t)),te(s,de.R_OK)}catch(c){throw new Error(`cannot fork ${e}: its conversation or context is unreadable \u2014 ${c.message}`)}return Z({kind:r.kind,mode:"base",cwd:r.cwd,prompt:"",root:!0,readiness:"await",forkFrom:e,...d===void 0?{}:{actor:d},profile:r.profile_id,model:r.model_override??void 0,...o===void 0?{}:{scopes:o}},c=>{const k=A(c);De(L(e),s,L(c),k,sn)})}a(Xn,"forkNode");export{Y as assertLaunchModelRegistered,Xn as forkNode,an as invokeBirthLifecycleHooks,J as resolveForkSource,tn as resolveProfileId,dn as resolveSpawner,Vn as spawnChild,Z as spawnChildPrepared};
3
+ `:""}${e.prompt}`;l==="orchestrator"&&Re(n.node_id,{goal:e.prompt.trim()}),await fn(n);let G;if(_!==void 0)try{const i=N(_);if(i===null)throw new Error(`invalid fork source ${_}`);const h=x().fork(i,n.node_id);G=x().header(h).path}catch(i){throw w(n.node_id,"crash",{reason:"launch_failed",outcome:p(i)}),i}const y=xe(n,{prompt:te,resumeSessionPath:G});if(y.env={...y.env,CRTR_SUBTREE:ke(n.node_id)},T){const i=e.wakeOrigin!==void 0?{type:"runtime",kind:"wake",wake:e.wakeOrigin}:{type:"runtime",kind:"kickoff",...n.spawned_by!=null&&n.spawned_by!==""?{spawnedBy:n.spawned_by}:{}};y.env[Ne]=Ie(i)}const b=je(),U=b.reserveSlot(n.node_id),m=U?await He(n.node_id):null;if(m?.verdict==="too_small"){b.releaseReservation(n.node_id);const i=Me(m);throw w(n.node_id,"crash",{reason:"launch_failed",outcome:p(i)}),i}if(!U||m?.verdict==="denied")return m?.verdict==="denied"&&b.releaseReservation(n.node_id),Le(n.node_id,new Date().toISOString()),Ke({level:"info",event:"broker.frozen",node_id:n.node_id,fields:m?.verdict==="denied"?{reason:"app_memory",free_bytes:m.free_bytes,needed_bytes:m.needed_bytes}:{reason:"broker_cap",live_count:b.size(),hard_cap:We().automaticReviveCap}}),{node:f(n.node_id),frozen:!0,window:null,session:null};const de=Xe(n.node_id),E=Pe(n.node_id,{daemonEpoch:b.epoch()});y.env={...y.env,CRTR_EXECUTION_ID:E};let S;try{S=await dn(n.node_id,y,{cwd:n.cwd,name:J(n),resuming:!1})}catch(i){throw B(E,{reason:"launch_failed"}),i}finally{b.releaseReservation(n.node_id)}if(S.pid===null){const i=new Error(`broker host returned no pid for ${n.node_id}`);throw B(E,{reason:"launch_failed"}),w(n.node_id,"crash",{reason:"launch_failed",outcome:p(i)}),I(`failed to launch the broker engine for ${n.node_id} (${n.name}) \u2014 the node was not started.`,`Inspect canonical event diagnostics with \`crtr sys logs --node ${n.node_id}\`, then verify the pi engine can start in this environment.`)}if(Be(E,n.node_id,S.pid)==="shutdown")throw B(E,{reason:"superseded"}),M.teardown(n.node_id),I(`broker execution was superseded for ${n.node_id}`,"Retry spawning the node.");if(re&&e.readiness==="await"&&!await Ve(n.node_id,S.exited)){const i=de.explanation();throw an(n.node_id,new Error(i??`broker view socket never bound for ${n.node_id}`)),I(i!==null?`the root broker ${n.node_id} could not start \u2014 ${i}`:`the root broker ${n.node_id} never bound its view socket \u2014 it was not started.`,i!==null?"Resolve the cause named above, then retry.":`The broker engine exited before binding its view socket. Inspect canonical event diagnostics with \`crtr sys logs --node ${n.node_id}\`, then retry.`)}let V=null,X=null;if(!t&&s!==null&&Ye("user").auto_open_child_viewers)try{const i=Ge(s);if(i!==null&&i.pane!==null&&i.pane!==""){const h=ze(n.node_id,i.session??"",{name:J(n),cwd:e.cwd,besidePane:i.pane,waitForBroker:!0,initialWhip:T});h!==null&&h.pane!==null&&h.pane!==""&&(X=h.session,V=Ue(h.pane))}}catch{}return{node:f(n.node_id),frozen:!1,window:V,session:X}}catch(c){throw g!==void 0&&v!==void 0&&f(v)===null&&await Ee(g),c}}a(oe,"spawnChildPrepared");async function Zn(e){return oe(e)}a(Zn,"spawnChild");async function fn(e){const o=rn(e.cwd,e.profile_id).plans.get("node:start")??[];await tn(o,{node:{id:e.node_id,name:e.name,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,cwd:e.cwd,nodeDir:A(e.node_id),contextDir:L(e.node_id),jobDir:Te(e.node_id)},runtime:{isBirth:!0,canvasHome:De(),profile:e.profile_id??null}})}a(fn,"invokeBirthLifecycleHooks");const un=new Set(["initial-prompt.md","yield-message.md","result.json","jobs"]);async function eo(e,o,d){const r=f(e);if(r===null)throw u(`unknown node: ${e}`,{received:e,next:"List nodes and pass the id of a node with a captured pi session."});const t=Q(e),s=L(e);try{x().header(N(t)),se(s,le.R_OK)}catch(l){throw new Error(`cannot fork ${e}: its conversation or context is unreadable \u2014 ${l.message}`)}return oe({kind:r.kind,mode:"base",cwd:r.cwd,prompt:"",root:!0,readiness:"await",forkFrom:e,...d===void 0?{}:{actor:d},profile:r.profile_id,model:r.model_override??void 0,...o===void 0?{}:{scopes:o}},l=>{const k=L(l);Ae(A(e),s,A(l),k,un)})}a(eo,"forkNode");export{ee as appPaidLaunch,ne as assertLaunchModelRegistered,eo as forkNode,fn as invokeBirthLifecycleHooks,Q as resolveForkSource,ln as resolveProfileId,cn as resolveSpawner,Zn as spawnChild,oe as spawnChildPrepared};
@@ -1,24 +1,24 @@
1
- var z=Object.defineProperty;var s=(e,r)=>z(e,"name",{value:r,configurable:!0});import{randomUUID as F}from"node:crypto";import{createServer as G}from"node:http";import{Router as J}from"./router.js";import{toErrorBody as Y}from"./map.js";import{objectRoutes as q}from"./handlers/objects.js";import{customObjectRoutes as Q}from"./handlers/custom-objects.js";import{docRoutes as W}from"./handlers/docs.js";import{OPERATIONS as K}from"./operations.js";import{errorCodes as L}from"../../api/error-codes.js";import{MINIMUM_RUNTIME_VERSION_HEADER as Z,RUNTIME_VERSION_HEADER as ee,minimumRuntimeRefusal as te}from"../../api/runtime-version.js";import{CONTRACT_HEADER as ne,CONTRACT_LEVEL as U,REQUIRED_CONTRACT_HEADER as re,contractRefusal as ae}from"../../api/contract.js";import{crtrVersion as x}from"../../shared/crtr-version.js";import{AppPrincipalResolver as oe}from"./principal.js";import{isDaemonRoute as se,runtimeOwner as ie,servePeer as V}from"../peer/ingress.js";import{applySyncNotice as ue}from"./sync-notice.js";import{ownMachineId as de}from"../../core/peer/directory.js";import{handleRunOperation as ce,integer as le}from"./handlers/runs.js";import{parseLlmRequest as fe,runLlm as me}from"../../core/llm/run.js";import{parseUsageMonth as pe,usageFor as he}from"../../core/usage/ledger.js";import{capFields as we}from"./handlers/llm.js";import{CONTROL_BODY_MAX_BYTES as ye,MODEL_CONTEXT_BODY_MAX_BYTES as _e}from"../../core/llm/body-limits.js";import{RunError as m,runIsRunning as ve}from"../../core/runs/operations.js";import{requireRun as j}from"./router.js";import{deferHead as ge}from"./deferred-head.js";import{readRunEvents as X,registerGrantStream as Re,subscribeRunEvents as Oe}from"../../core/runs/events.js";import{activeGrant as Ee}from"../../core/grants/mirror.js";import{releaseGrantWaiters as be}from"../../core/grants/watch.js";import{runNotices as Se}from"../run-notices.js";import{handleVendorSignIn as Te,isVendorSignInPath as Ae}from"./vendor-signin.js";import{listAppProfiles as Ne}from"./handlers/app-profiles.js";import{handleTransferDownload as Ce,handleTransferOperation as Ie,TRANSFER_OPERATIONS as Pe}from"./handlers/transfer.js";import{handleQuestionOperation as ke,QUESTION_OPERATIONS as He}from"./handlers/questions.js";import{vendorStatus as Me}from"./handlers/vendor-status.js";import{handleMemoryOperation as De,MEMORY_OPERATIONS as xe}from"./handlers/memory.js";import{abortOnClose as je,callerFromApp as Be,handleProviderOperation as Je,PROVIDER_OPERATIONS as Le,providerFailure as Ue}from"./handlers/providers.js";function Ve(e){return Object.prototype.hasOwnProperty.call(L,e)?L[e]:void 0}s(Ve,"fixedRow");function Xe(e){const r=Ve(e);return r?r.type:e==="stream_gap"||e==="provider_error"||e==="runtime_version_unsupported"?"invalid_request_error":"server_error"}s(Xe,"errorType");function $e(e){if(!e||typeof e!="object"||Array.isArray(e)||!("rate_limit"in e))return e;const{rate_limit:r,...o}=e;return o}s($e,"appDetails");function D(e,r,o){const c=$e(e.details);return{error:{code:e.code,message:e.message,...c===void 0?{}:{details:c},type:Xe(e.code),...e.param?{param:e.param}:{},origin:"runtime",retryable:e.retryable||e.code==="stream_dropped",request_id:r,...o?{run_id:o}:{},...e.scope?{scope:e.scope}:{},...e.code==="unauthorized"?{user_action:"reconnect"}:{},...we(e),...e.code==="all_routes_exhausted"?{retry_after_s:e.details.retry_after_s}:{}}}}s(D,"envelope");function ze(e,r,o,c){const u=r instanceof m?r:new m(500,"server_failure","runtime request failed");if(r instanceof m||console.error("[app-listener]",r),e.headersSent&&!String(e.getHeader("Content-Type")??"").startsWith("text/event-stream")){e.destroy();return}if(e.headersSent){e.end(`event: error
2
- data: ${JSON.stringify(D(u,o,c))}
1
+ var G=Object.defineProperty;var i=(e,r)=>G(e,"name",{value:r,configurable:!0});import{randomUUID as F}from"node:crypto";import{createServer as Y}from"node:http";import{Router as J}from"./router.js";import{toErrorBody as q}from"./map.js";import{objectRoutes as Q}from"./handlers/objects.js";import{customObjectRoutes as W}from"./handlers/custom-objects.js";import{docRoutes as K}from"./handlers/docs.js";import{OPERATIONS as Z}from"./operations.js";import{errorCodes as L}from"../../api/error-codes.js";import{MINIMUM_RUNTIME_VERSION_HEADER as ee,RUNTIME_VERSION_HEADER as te,minimumRuntimeRefusal as ne}from"../../api/runtime-version.js";import{CONTRACT_HEADER as re,CONTRACT_LEVEL as U,REQUIRED_CONTRACT_HEADER as ae,contractRefusal as oe}from"../../api/contract.js";import{crtrVersion as x}from"../../shared/crtr-version.js";import{AppPrincipalResolver as ie}from"./principal.js";import{isDaemonRoute as se,runtimeOwner as ue,servePeer as V}from"../peer/ingress.js";import{applySyncNotice as de}from"./sync-notice.js";import{ownMachineId as ce}from"../../core/peer/directory.js";import{handleRunOperation as le,integer as fe}from"./handlers/runs.js";import{llmCallerOf as me,parseLlmRequest as pe,runLlm as he}from"../../core/llm/run.js";import{parseUsageMonth as we,usageFor as ye}from"../../core/usage/ledger.js";import{capFields as _e}from"./handlers/llm.js";import{CONTROL_BODY_MAX_BYTES as ge,MODEL_CONTEXT_BODY_MAX_BYTES as ve}from"../../core/llm/body-limits.js";import{RunError as l,runIsRunning as Oe}from"../../core/runs/operations.js";import{requireRun as j}from"./router.js";import{deferHead as Re}from"./deferred-head.js";import{readRunEvents as X,registerGrantStream as Ee,subscribeRunEvents as be}from"../../core/runs/events.js";import{activeGrant as $,payerOfGrant as Se}from"../../core/grants/mirror.js";function Te(e){if(Se(e)==="app")throw new l(401,"grant_revoked","this app-paid grant is no longer active");return null}i(Te,"appPaidGone");import{releaseGrantWaiters as Ae}from"../../core/grants/watch.js";import{runNotices as Ne}from"../run-notices.js";import{handleVendorSignIn as Ce,isVendorSignInPath as Pe}from"./vendor-signin.js";import{listAppProfiles as Ie}from"./handlers/app-profiles.js";import{handleTransferDownload as ke,handleTransferOperation as He,TRANSFER_OPERATIONS as Me}from"./handlers/transfer.js";import{handleQuestionOperation as De,QUESTION_OPERATIONS as xe}from"./handlers/questions.js";import{vendorStatus as je}from"./handlers/vendor-status.js";import{handleMemoryOperation as Be,MEMORY_OPERATIONS as Je}from"./handlers/memory.js";import{abortOnClose as Le,callerFromApp as Ue,handleProviderOperation as Ve,PROVIDER_OPERATIONS as Xe,providerFailure as $e}from"./handlers/providers.js";function ze(e){return Object.prototype.hasOwnProperty.call(L,e)?L[e]:void 0}i(ze,"fixedRow");function Ge(e){const r=ze(e);return r?r.type:e==="stream_gap"||e==="provider_error"||e==="runtime_version_unsupported"?"invalid_request_error":"server_error"}i(Ge,"errorType");function Fe(e){if(!e||typeof e!="object"||Array.isArray(e)||!("rate_limit"in e))return e;const{rate_limit:r,...o}=e;return o}i(Fe,"appDetails");function D(e,r,o){const f=Fe(e.details);return{error:{code:e.code,message:e.message,...f===void 0?{}:{details:f},type:Ge(e.code),...e.param?{param:e.param}:{},origin:"runtime",retryable:e.retryable||e.code==="stream_dropped",request_id:r,...o?{run_id:o}:{},...e.scope?{scope:e.scope}:{},...e.code==="unauthorized"?{user_action:"reconnect"}:{},..._e(e),...e.code==="all_routes_exhausted"?{retry_after_s:e.details.retry_after_s}:{}}}}i(D,"envelope");function Ye(e,r,o,f){const u=r instanceof l?r:new l(500,"server_failure","runtime request failed");if(r instanceof l||console.error("[app-listener]",r),e.headersSent&&!String(e.getHeader("Content-Type")??"").startsWith("text/event-stream")){e.destroy();return}if(e.headersSent){e.end(`event: error
2
+ data: ${JSON.stringify(D(u,o,f))}
3
3
 
4
- `);return}e.writeHead(u.status,{"Content-Type":"application/json; charset=utf-8","Request-Id":o,"X-Content-Type-Options":"nosniff",...u.code==="all_routes_exhausted"?{"Retry-After":String(u.details.retry_after_s)}:{}}),e.end(JSON.stringify(D(u,o,c)))}s(ze,"fail");function $(e){return Array.isArray(e)?e[0]:e}s($,"headerValue");function O(e,r,o){e.writeHead(r,{"Content-Type":"application/json; charset=utf-8"}),e.end(JSON.stringify(o))}s(O,"json");async function I(e,r=ye){const o=[];let c=0;for await(const u of e){if(c+=u.length,c>r)throw new m(400,"invalid_request","request body too large");o.push(u)}if(c)try{return JSON.parse(Buffer.concat(o).toString("utf8"))}catch{throw new m(400,"invalid_request","invalid JSON body")}}s(I,"bodyOf");function Fe(e,r){const o=e.headers["last-event-id"]??r.get("after");if(Array.isArray(o))throw new m(400,"invalid_request","invalid cursor","after");return le(o??null,"after",0,Number.MAX_SAFE_INTEGER,0)}s(Fe,"cursor");function Ge(e){return`id: ${e.sequence_number}
4
+ `);return}e.writeHead(u.status,{"Content-Type":"application/json; charset=utf-8","Request-Id":o,"X-Content-Type-Options":"nosniff",...u.code==="all_routes_exhausted"?{"Retry-After":String(u.details.retry_after_s)}:{}}),e.end(JSON.stringify(D(u,o,f)))}i(Ye,"fail");function z(e){return Array.isArray(e)?e[0]:e}i(z,"headerValue");function R(e,r,o){e.writeHead(r,{"Content-Type":"application/json; charset=utf-8"}),e.end(JSON.stringify(o))}i(R,"json");async function P(e,r=ge){const o=[];let f=0;for await(const u of e){if(f+=u.length,f>r)throw new l(400,"invalid_request","request body too large");o.push(u)}if(f)try{return JSON.parse(Buffer.concat(o).toString("utf8"))}catch{throw new l(400,"invalid_request","invalid JSON body")}}i(P,"bodyOf");function qe(e,r){const o=e.headers["last-event-id"]??r.get("after");if(Array.isArray(o))throw new l(400,"invalid_request","invalid cursor","after");return fe(o??null,"after",0,Number.MAX_SAFE_INTEGER,0)}i(qe,"cursor");function Qe(e){return`id: ${e.sequence_number}
5
5
  event: ${e.type}
6
6
  data: ${JSON.stringify(e)}
7
7
 
8
- `}s(Ge,"frame");const Ye=6e4;function qe(e,r,o,c,u,_,E,A={}){j(c,o);let v=X(o,u);if(u>v.latest_sequence)throw new m(400,"invalid_request","cursor is beyond the run","after");if(u<v.latest_sequence&&(v.earliest_sequence===null||u<v.earliest_sequence-1))throw new m(409,"stream_gap","events have expired",void 0,{earliest_sequence:v.earliest_sequence,latest_sequence:v.latest_sequence});if(r.destroyed||e.destroyed)return r.destroy(),Promise.resolve();r.writeHead(200,{"Content-Type":E==="sse"?"text/event-stream":"application/x-ndjson","Cache-Control":"no-cache","X-Accel-Buffering":"no"}),E==="sse"?r.write(`: connected
8
+ `}i(Qe,"frame");const We=6e4;function Ke(e,r,o,f,u,_,E,A={}){j(f,o);let g=X(o,u);if(u>g.latest_sequence)throw new l(400,"invalid_request","cursor is beyond the run","after");if(u<g.latest_sequence&&(g.earliest_sequence===null||u<g.earliest_sequence-1))throw new l(409,"stream_gap","events have expired",void 0,{earliest_sequence:g.earliest_sequence,latest_sequence:g.latest_sequence});if(r.destroyed||e.destroyed)return r.destroy(),Promise.resolve();r.writeHead(200,{"Content-Type":E==="sse"?"text/event-stream":"application/x-ndjson","Cache-Control":"no-cache","X-Accel-Buffering":"no"}),E==="sse"?r.write(`: connected
9
9
 
10
- `):r.flushHeaders();let w=u;const B=Se().streamOpened(o);let n=!1,t=!1,h=!1,b;const N=new Promise(f=>{b=f}),y=s(()=>{n||(n=!0,B(w),clearInterval(l),clearInterval(R),P(),H(),r.off("close",y),r.off("drain",p),r.end(),b())},"end"),p=s(()=>{h=!1,a()},"onDrain"),g=s(f=>{n||r.write(E==="sse"?`event: error
11
- data: ${JSON.stringify(D(f,_,o))}
10
+ `):r.flushHeaders();let w=u;const B=Ne().streamOpened(o);let n=!1,t=!1,h=!1,b;const N=new Promise(m=>{b=m}),y=i(()=>{n||(n=!0,B(w),clearInterval(d),clearInterval(O),I(),H(),r.off("close",y),r.off("drain",p),r.end(),b())},"end"),p=i(()=>{h=!1,a()},"onDrain"),v=i(m=>{n||r.write(E==="sse"?`event: error
11
+ data: ${JSON.stringify(D(m,_,o))}
12
12
 
13
- `:`${JSON.stringify({type:"error",...D(f,_,o)})}
14
- `),y()},"error"),a=s(()=>{if(!(n||t)){t=!0;try{if(!T()){k();return}if(j(c,o),v=X(o,w),v.backlog_count>1e3||v.backlog_bytes>32*1024*1024){g(new m(503,"stream_dropped","stream reader fell behind",void 0,{last_sequence:w}));return}for(const f of v.events){if(h)break;h=!r.write(E==="sse"?Ge(f):`${JSON.stringify(f)}
15
- `),w=f.sequence_number}}catch(f){g(f instanceof m?f:new m(500,"server_failure","stream failed"))}finally{t=!1}}},"flush"),k=s(()=>g(new m(401,"grant_revoked","grant is not active")),"revoked"),T=s(()=>"class"in c||Ee(c.grant)!==null,"grantActive"),P=Oe(o,a),H="class"in c?()=>{}:Re(c.grant,k),l=setInterval(()=>{!n&&!h&&E==="sse"&&r.write(`: keepalive
13
+ `:`${JSON.stringify({type:"error",...D(m,_,o)})}
14
+ `),y()},"error"),a=i(()=>{if(!(n||t)){t=!0;try{if(!T()){k();return}if(j(f,o),g=X(o,w),g.backlog_count>1e3||g.backlog_bytes>32*1024*1024){v(new l(503,"stream_dropped","stream reader fell behind",void 0,{last_sequence:w}));return}for(const m of g.events){if(h)break;h=!r.write(E==="sse"?Qe(m):`${JSON.stringify(m)}
15
+ `),w=m.sequence_number}}catch(m){v(m instanceof l?m:new l(500,"server_failure","stream failed"))}finally{t=!1}}},"flush"),k=i(()=>v(new l(401,"grant_revoked","grant is not active")),"revoked"),T=i(()=>"class"in f||$(f.grant)!==null,"grantActive"),I=be(o,a),H="class"in f?()=>{}:Ee(f.grant,k),d=setInterval(()=>{!n&&!h&&E==="sse"&&r.write(`: keepalive
16
16
 
17
- `)},15e3),M=A.idleMs??Ye,i=A.isRunning??ve;let S=Date.now(),d=w;const R=setInterval(()=>{if(n||E!=="sse")return;const f=Date.now();let C=!0;try{C=i(o)}catch{}if(C||w!==d){S=f,d=w;return}f-S<M||h||(r.write(`event: idle
17
+ `)},15e3),M=A.idleMs??We,s=A.isRunning??Oe;let S=Date.now(),c=w;const O=setInterval(()=>{if(n||E!=="sse")return;const m=Date.now();let C=!0;try{C=s(o)}catch{}if(C||w!==c){S=m,c=w;return}m-S<M||h||(r.write(`event: idle
18
18
  data: {}
19
19
 
20
- `),y())},A.idleCheckMs??1e3);return R.unref(),r.on("drain",p),r.on("close",y),a(),N}s(qe,"streamRunEvents");function kt(e,r,o,c={}){const u=e.listener;if(!e.issuer||!e.audience||!u?.address||!Number.isInteger(u.port)||u.port<1||u.port>65535)throw new Error("runtime issuer, audience and listener address/port are required");if(["0.0.0.0","::","[::]"].includes(u.address))throw new Error("runtime listener must bind a specific address");const _=new oe(e.issuer,e.audience,o,e.jwksUrl),E=new J,A=new Map;for(const n of K.filter(t=>t.stage!==void 0)){const t=s(()=>({status:500}),"handler");E.register({method:n.method,pattern:n.path,handler:t}),A.set(t,n)}const v=new J().registerAll(q).registerAll(Q).registerAll(W),w=G((n,t)=>{(async()=>{ge(n,t,c.deferHead);const h=F();t.setHeader("Request-Id",h),t.setHeader(ee,x()),t.setHeader(ne,U);let b;try{const N=$(n.headers[Z.toLowerCase()]),y=te(N,x())??ae($(n.headers[re.toLowerCase()]),U,{legacyMinimum:N,runtimeVersion:x()});if(y!==null)throw y.status===400?new m(400,y.code,y.message,y.param):new m(426,y.code,y.message,void 0,y.details);const p=new URL(n.url??"/","http://runtime.local");if(Ae(p.pathname)){await Te(n,t,p,_);return}const g=E.match(n.method??"GET",p.pathname),a=g?A.get(g.handler):void 0,k=a?.name==="runtime.sync-notice"||a?.name==="runtime.vendor-status";let T,P;if(!k&&n.headers.authorization!==void 0)try{T=await _.verifyCall(n.headers.authorization)}catch(i){P=i}const H={issuer:e.issuer,jwks:_.jwks,audience:s(()=>e.audience,"audience"),owner:ie,self:de,syncGrants:o,ready:s(()=>_.isReady()&&r(),"ready")};if(T?.chain[0]?.sub.startsWith("runtime:")){await V(n,t,H,T);return}if(T===void 0&&a===void 0&&await se(n.method??"GET",p.pathname)){await V(n,t,H,{status:401,code:"unauthorized",message:P===void 0?"a machine token is required":"invalid machine token"});return}if((n.method!=="GET"||p.pathname!=="/v1/health")&&(!_.isReady()||!r()))throw new m(503,"runtime_starting","runtime_starting");if(!g||!a)throw new m(404,"not_found","unknown operation");if(b=g.params.run_id,a.name==="health"){O(t,200,{status:"ok",api_version:"2026-09-23"});return}if(a.name==="runtime.sync-notice"){await ue(await _.verifySyncNotice(n.headers.authorization),o,h),t.writeHead(204),t.end();return}if(a.name==="runtime.vendor-status"){await _.verifyDirectoryRead(n.headers.authorization,"vendor_status"),O(t,200,Me());return}if(T===void 0)throw P??new m(401,"unauthorized","a directory access token is required");const l=await _.resolveVerified(T,a.scope);if(t.setHeader("Request-Id",h),b&&j(l,b,["run.message","run.interrupt","run.cancel","run.rename","run.delete"].includes(a.name),a.name==="run.delete"),a.stage==="objects"){const i=v.match(a.method,p.pathname);if(!i)throw new m(404,"not_found","unknown operation");const S={method:a.method,path:p.pathname,params:i.params,query:p.searchParams,body:await I(n,i.maxBodyBytes),ceiling:l.resolved,principal:{class:"app",app:l.grantee,scopes:l.resolved},req:n,res:t};let d;try{d=await i.handler(S)}catch(R){const{status:f,body:C}=Y(R);throw f>=500&&console.error("[app-listener]",R),new m(f,C.error.code,C.error.message,void 0,C.error.details)}if(t.headersSent)return;if(d.rawBody!==void 0||d.status===204||d.body===void 0){t.writeHead(d.status,d.headers??{}),t.end(d.rawBody);return}t.writeHead(d.status,{"Content-Type":"application/json; charset=utf-8",...d.headers??{}}),t.end(JSON.stringify(d.body));return}if(a.stream==="bytes"){await Ce(n,t,l,p.searchParams);return}if(a.stream){qe(n,t,b,l,Fe(n,p.searchParams),h,"sse",c.stream);return}if(a.name==="llm"){const i=fe(await I(n,_e)),S=new AbortController,d=s(()=>S.abort(),"abort");t.on("close",d);try{const R=await me(i,S.signal,i.stream?f=>{t.headersSent||t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache","X-Accel-Buffering":"no"}),t.write(`data: ${JSON.stringify(f)}
20
+ `),y())},A.idleCheckMs??1e3);return O.unref(),r.on("drain",p),r.on("close",y),a(),N}i(Ke,"streamRunEvents");function Dt(e,r,o,f={}){const u=e.listener;if(!e.issuer||!e.audience||!u?.address||!Number.isInteger(u.port)||u.port<1||u.port>65535)throw new Error("runtime issuer, audience and listener address/port are required");if(["0.0.0.0","::","[::]"].includes(u.address))throw new Error("runtime listener must bind a specific address");const _=new ie(e.issuer,e.audience,o,e.jwksUrl),E=new J,A=new Map;for(const n of Z.filter(t=>t.stage!==void 0)){const t=i(()=>({status:500}),"handler");E.register({method:n.method,pattern:n.path,handler:t}),A.set(t,n)}const g=new J().registerAll(Q).registerAll(W).registerAll(K),w=Y((n,t)=>{(async()=>{Re(n,t,f.deferHead);const h=F();t.setHeader("Request-Id",h),t.setHeader(te,x()),t.setHeader(re,U);let b;try{const N=z(n.headers[ee.toLowerCase()]),y=ne(N,x())??oe(z(n.headers[ae.toLowerCase()]),U,{legacyMinimum:N,runtimeVersion:x()});if(y!==null)throw y.status===400?new l(400,y.code,y.message,y.param):new l(426,y.code,y.message,void 0,y.details);const p=new URL(n.url??"/","http://runtime.local");if(Pe(p.pathname)){await Ce(n,t,p,_);return}const v=E.match(n.method??"GET",p.pathname),a=v?A.get(v.handler):void 0,k=a?.name==="runtime.sync-notice"||a?.name==="runtime.vendor-status";let T,I;if(!k&&n.headers.authorization!==void 0)try{T=await _.verifyCall(n.headers.authorization)}catch(s){I=s}const H={issuer:e.issuer,jwks:_.jwks,audience:i(()=>e.audience,"audience"),owner:ue,self:ce,syncGrants:o,ready:i(()=>_.isReady()&&r(),"ready")};if(T?.chain[0]?.sub.startsWith("runtime:")){await V(n,t,H,T);return}if(T===void 0&&a===void 0&&await se(n.method??"GET",p.pathname)){await V(n,t,H,{status:401,code:"unauthorized",message:I===void 0?"a machine token is required":"invalid machine token"});return}if((n.method!=="GET"||p.pathname!=="/v1/health")&&(!_.isReady()||!r()))throw new l(503,"runtime_starting","runtime_starting");if(!v||!a)throw new l(404,"not_found","unknown operation");if(b=v.params.run_id,a.name==="health"){R(t,200,{status:"ok",api_version:"2026-09-23"});return}if(a.name==="runtime.sync-notice"){await de(await _.verifySyncNotice(n.headers.authorization),o,h),t.writeHead(204),t.end();return}if(a.name==="runtime.vendor-status"){await _.verifyDirectoryRead(n.headers.authorization,"vendor_status"),R(t,200,je());return}if(T===void 0)throw I??new l(401,"unauthorized","a directory access token is required");const d=await _.resolveVerified(T,a.scope);if(t.setHeader("Request-Id",h),b&&j(d,b,["run.message","run.interrupt","run.cancel","run.rename","run.delete"].includes(a.name),a.name==="run.delete"),a.stage==="objects"){const s=g.match(a.method,p.pathname);if(!s)throw new l(404,"not_found","unknown operation");const S={method:a.method,path:p.pathname,params:s.params,query:p.searchParams,body:await P(n,s.maxBodyBytes),ceiling:d.resolved,principal:{class:"app",app:d.grantee,scopes:d.resolved},req:n,res:t};let c;try{c=await s.handler(S)}catch(O){const{status:m,body:C}=q(O);throw m>=500&&console.error("[app-listener]",O),new l(m,C.error.code,C.error.message,void 0,C.error.details)}if(t.headersSent)return;if(c.rawBody!==void 0||c.status===204||c.body===void 0){t.writeHead(c.status,c.headers??{}),t.end(c.rawBody);return}t.writeHead(c.status,{"Content-Type":"application/json; charset=utf-8",...c.headers??{}}),t.end(JSON.stringify(c.body));return}if(a.stream==="bytes"){await ke(n,t,d,p.searchParams);return}if(a.stream){Ke(n,t,b,d,qe(n,p.searchParams),h,"sse",f.stream);return}if(a.name==="llm"){const s=pe(await P(n,ve)),S=new AbortController,c=i(()=>S.abort(),"abort");t.on("close",c);try{const O=await he(s,S.signal,s.stream?m=>{t.headersSent||t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache","X-Accel-Buffering":"no"}),t.write(`data: ${JSON.stringify(m)}
21
21
 
22
- `)}:void 0,void 0,{grantee:l.grantee,spend_cap:l.spend_cap});i.stream?(t.headersSent||t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache","X-Accel-Buffering":"no"}),t.end(`data: [DONE]
22
+ `)}:void 0,void 0,{grantee:d.grantee,spend_cap:d.spend_cap},me($(d.grant)??Te(d.grant)));s.stream?(t.headersSent||t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache","X-Accel-Buffering":"no"}),t.end(`data: [DONE]
23
23
 
24
- `)):O(t,200,R.completion)}finally{t.off("close",d)}return}if(a.name==="usage.get"){O(t,200,he(l.grantee,l.spend_cap,pe(p.searchParams.get("month"))));return}if(a.name==="profile.list"){O(t,200,Ne(l));return}if(He.has(a.name)){const i=await ke(a.name,l,g.params.question_id,a.method==="POST"?await I(n):void 0);O(t,i.status,i.body);return}if(Le.has(a.name)){const{signal:i,release:S}=je(t);try{const d=await Je(a.name,Be(l),{params:g.params,body:a.method==="POST"?await I(n):void 0,query:p.searchParams},{requestId:h,signal:i});O(t,d.status,d.body)}catch(d){const R=Ue(d,h,!0);t.writeHead(R.status,{"Content-Type":"application/json; charset=utf-8","X-Content-Type-Options":"nosniff",...R.headers}),t.end(JSON.stringify(R.body))}finally{S()}return}if(xe.has(a.name)){const i=De(a.name,{class:"app",app:l.grantee,scopes:l.resolved},p.searchParams);O(t,i.status,i.body);return}if(Pe.has(a.name)){const i=await Ie(a,l,g.params,p.searchParams,await I(n));O(t,i.status,i.body);return}const M=await ce(a,l,b,p.searchParams,await I(n),n.headers["idempotency-key"]);O(t,M.status,M.body)}catch(N){ze(t,N,h,b)}})()});return{ready:new Promise((n,t)=>{w.once("error",t),w.listen(u.port,u.address,()=>{w.off("error",t),n()})}),close:s(async()=>{_.close(),be(),w.closeAllConnections(),await new Promise((n,t)=>w.close(h=>h?t(h):n()))},"close")}}s(kt,"createAppListener");export{Ye as RUN_STREAM_IDLE_MS,kt as createAppListener,Fe as cursor,qe as streamRunEvents};
24
+ `)):R(t,200,O.completion)}finally{t.off("close",c)}return}if(a.name==="usage.get"){R(t,200,ye(d.grantee,d.spend_cap,we(p.searchParams.get("month"))));return}if(a.name==="profile.list"){R(t,200,Ie(d));return}if(xe.has(a.name)){const s=await De(a.name,d,v.params.question_id,a.method==="POST"?await P(n):void 0);R(t,s.status,s.body);return}if(Xe.has(a.name)){const{signal:s,release:S}=Le(t);try{const c=await Ve(a.name,Ue(d),{params:v.params,body:a.method==="POST"?await P(n):void 0,query:p.searchParams},{requestId:h,signal:s});R(t,c.status,c.body)}catch(c){const O=$e(c,h,!0);t.writeHead(O.status,{"Content-Type":"application/json; charset=utf-8","X-Content-Type-Options":"nosniff",...O.headers}),t.end(JSON.stringify(O.body))}finally{S()}return}if(Je.has(a.name)){const s=Be(a.name,{class:"app",app:d.grantee,scopes:d.resolved},p.searchParams);R(t,s.status,s.body);return}if(Me.has(a.name)){const s=await He(a,d,v.params,p.searchParams,await P(n));R(t,s.status,s.body);return}const M=await le(a,d,b,p.searchParams,await P(n),n.headers["idempotency-key"]);R(t,M.status,M.body)}catch(N){Ye(t,N,h,b)}})()});return{ready:new Promise((n,t)=>{w.once("error",t),w.listen(u.port,u.address,()=>{w.off("error",t),n()})}),close:i(async()=>{_.close(),Ae(),w.closeAllConnections(),await new Promise((n,t)=>w.close(h=>h?t(h):n()))},"close")}}i(Dt,"createAppListener");export{We as RUN_STREAM_IDLE_MS,Dt as createAppListener,qe as cursor,Ke as streamRunEvents};
@@ -1,3 +1,3 @@
1
- var w=Object.defineProperty;var s=(e,t)=>w(e,"name",{value:t,configurable:!0});import{randomUUID as _}from"node:crypto";import{MODEL_CONTEXT_BODY_MAX_BYTES as v}from"../../../core/llm/body-limits.js";import{parseLlmRequest as A,runLlm as x}from"../../../core/llm/run.js";import{RunError as c}from"../../../core/runs/operations.js";import{errorCodes as S}from"../../../api/error-codes.js";import{getNode as E}from"../../../core/canvas/canvas.js";import{socketPrincipal as u}from"../server.js";import{activeGrant as R,activeGrantForApp as T,grantFor as k,grantsSource as O}from"../../../core/grants/mirror.js";import{parseUsageMonth as q,UNCAPPED_GRANTEE as I,usageFor as N}from"../../../core/usage/ledger.js";function g(e,t){if(t==="broker"||t==="person"||t===void 0||!e||typeof e!="object"||Array.isArray(e)||!("rate_limit"in e))return e;const{rate_limit:n,...a}=e;return a}s(g,"operatorDetails");function y(e){if(e?.class==="broker"){const t=e.grant?R(e.grant):k(e.app,e.sub);return{grantee:e.app,spend_cap:t&&t.grantee===e.app?t.spend_cap:null}}if(e?.class==="app"){const t=O();if(t===null||t==="local")return{grantee:e.app,spend_cap:null};let n;try{n=T(e.app)}catch{throw new c(401,"grant_revoked",`${e.app} has several active grants; a local token cannot name which user's cap applies`)}if(!n)throw new c(401,"grant_revoked",`${e.app} has no active grant`);return{grantee:e.app,spend_cap:n.spend_cap}}return{grantee:I,spend_cap:null}}s(y,"spendTarget");function h(e){const t=S[e.code];return t?t.type:e.status===429?"rate_limit_error":e.status<500?"invalid_request_error":"server_error"}s(h,"errorType");function D(e){if(e.code!=="cap_exhausted")return{};const t=e.details?.reset_at;return{...typeof t=="string"?{reset_at:t}:{},user_action:"raise_cap"}}s(D,"capFields");const C=[{method:"POST",pattern:"/v1/llm",scope:"crtr:llm",maxBodyBytes:v,handler:s(async({body:e,res:t,req:n})=>{const a=_();t.setHeader("Request-Id",a);const m=new AbortController,f=s(()=>m.abort(),"abort");t.on("close",f);let l;try{const r=A(e),o=u(n),d=o?.class==="broker"?E(o.node):null;if(o?.class==="broker"&&!d)throw new c(401,"unauthorized","node not found");const i=y(o),b=await x(r,m.signal,r.stream?p=>{typeof p.served_model=="string"&&(l=p.served_model),t.headersSent||t.writeHead(200,{"content-type":"application/x-ndjson; charset=utf-8","cache-control":"no-cache"}),t.write(`${JSON.stringify(p)}
2
- `)}:void 0,d?{cwd:d.cwd,profileId:d.profile_id??null}:void 0,i);return r.stream?(t.headersSent||t.writeHead(200,{"content-type":"application/x-ndjson; charset=utf-8","cache-control":"no-cache"}),t.end(),{status:200}):{status:200,body:b.completion}}catch(r){if(t.headersSent){const o=r instanceof c?r:new c(503,"upstream_model_unavailable","model stream failed"),d=o.details&&typeof o.details=="object"&&!Array.isArray(o.details)?o.details:{},i=g(l!==void 0&&typeof d.served_model!="string"?{...d,served_model:l}:o.details,u(n)?.class);return t.end(`${JSON.stringify({error:{code:o.code,message:o.message,...i===void 0?{}:{details:i},type:"server_error",origin:"runtime",retryable:o.retryable,request_id:a}})}
3
- `),{status:200}}if(r instanceof c){const o=g(r.details,u(n)?.class);return r.code==="all_routes_exhausted"&&t.setHeader("Retry-After",String(r.details.retry_after_s)),{status:r.status,body:{error:{code:r.code,message:r.message,...o===void 0?{}:{details:o},type:h(r),...r.param?{param:r.param}:{},origin:"runtime",retryable:r.retryable,request_id:a,...r.code==="all_routes_exhausted"?{retry_after_s:r.details.retry_after_s}:{},...D(r)}}}}throw r}finally{t.off("close",f)}},"handler")},{method:"GET",pattern:"/v1/usage",handler:s(({req:e})=>{const t=_(),n={"Request-Id":t};try{const a=y(u(e));return{status:200,headers:n,body:N(a.grantee,a.spend_cap,q(new URL(e.url??"/","http://runtime.local").searchParams.get("month")))}}catch(a){if(!(a instanceof c))throw a;return{status:a.status,headers:n,body:{error:{code:a.code,message:a.message,type:h(a),...a.param?{param:a.param}:{},origin:"runtime",retryable:!1,request_id:t}}}}},"handler")}];export{D as capFields,C as llmRoutes,y as spendTarget};
1
+ var O=Object.defineProperty;var s=(e,t)=>O(e,"name",{value:t,configurable:!0});import{randomUUID as _}from"node:crypto";import{MODEL_CONTEXT_BODY_MAX_BYTES as S}from"../../../core/llm/body-limits.js";import{llmCallerOf as g,parseLlmRequest as E,runLlm as R}from"../../../core/llm/run.js";import{RunError as d}from"../../../core/runs/operations.js";import{errorCodes as T}from"../../../api/error-codes.js";import{getNode as q}from"../../../core/canvas/canvas.js";import{socketPrincipal as l}from"../server.js";import{activeGrant as y,activeGrantForApp as h,grantFor as b,grantsSource as w,payerOfGrant as I}from"../../../core/grants/mirror.js";import{parseUsageMonth as N,UNCAPPED_GRANTEE as D,usageFor as G}from"../../../core/usage/ledger.js";function v(e,t){if(t==="broker"||t==="person"||t===void 0||!e||typeof e!="object"||Array.isArray(e)||!("rate_limit"in e))return e;const{rate_limit:o,...a}=e;return a}s(v,"operatorDetails");function A(e){if(e?.class==="broker"){const t=e.grant?y(e.grant):b(e.app,e.sub);return{grantee:e.app,spend_cap:t&&t.grantee===e.app?t.spend_cap:null}}if(e?.class==="app"){const t=w();if(t===null||t==="local")return{grantee:e.app,spend_cap:null};let o;try{o=h(e.app)}catch{throw new d(401,"grant_revoked",`${e.app} has several active grants; a local token cannot name which user's cap applies`)}if(!o)throw new d(401,"grant_revoked",`${e.app} has no active grant`);return{grantee:e.app,spend_cap:o.spend_cap}}return{grantee:D,spend_cap:null}}s(A,"spendTarget");function P(e){if(e?.class==="broker"){if(e.app==="app:terminal")return;const t=e.grant?y(e.grant):b(e.app,e.sub);if(!t&&I(e.grant)==="app")throw new d(401,"grant_revoked",`${e.app}'s app-paid grant is no longer active`);return g(t&&t.grantee===e.app?t:null)}if(e?.class==="app"){const t=w();return t===null||t==="local"?void 0:g(h(e.app))}}s(P,"llmCaller");function k(e){const t=T[e.code];return t?t.type:e.status===429?"rate_limit_error":e.status<500?"invalid_request_error":"server_error"}s(k,"errorType");function U(e){if(e.code!=="cap_exhausted")return{};const t=e.details?.reset_at;return{...typeof t=="string"?{reset_at:t}:{},user_action:"raise_cap"}}s(U,"capFields");const Y=[{method:"POST",pattern:"/v1/llm",scope:"crtr:llm",maxBodyBytes:S,handler:s(async({body:e,res:t,req:o})=>{const a=_();t.setHeader("Request-Id",a);const m=new AbortController,p=s(()=>m.abort(),"abort");t.on("close",p);let i;try{const r=E(e),n=l(o),u=n?.class==="broker"?q(n.node):null;if(n?.class==="broker"&&!u)throw new d(401,"unauthorized","node not found");const c=A(n),x=await R(r,m.signal,r.stream?f=>{typeof f.served_model=="string"&&(i=f.served_model),t.headersSent||t.writeHead(200,{"content-type":"application/x-ndjson; charset=utf-8","cache-control":"no-cache"}),t.write(`${JSON.stringify(f)}
2
+ `)}:void 0,u?{cwd:u.cwd,profileId:u.profile_id??null}:void 0,c,P(n));return r.stream?(t.headersSent||t.writeHead(200,{"content-type":"application/x-ndjson; charset=utf-8","cache-control":"no-cache"}),t.end(),{status:200}):{status:200,body:x.completion}}catch(r){if(t.headersSent){const n=r instanceof d?r:new d(503,"upstream_model_unavailable","model stream failed"),u=n.details&&typeof n.details=="object"&&!Array.isArray(n.details)?n.details:{},c=v(i!==void 0&&typeof u.served_model!="string"?{...u,served_model:i}:n.details,l(o)?.class);return t.end(`${JSON.stringify({error:{code:n.code,message:n.message,...c===void 0?{}:{details:c},type:"server_error",origin:"runtime",retryable:n.retryable,request_id:a}})}
3
+ `),{status:200}}if(r instanceof d){const n=v(r.details,l(o)?.class);return r.code==="all_routes_exhausted"&&t.setHeader("Retry-After",String(r.details.retry_after_s)),{status:r.status,body:{error:{code:r.code,message:r.message,...n===void 0?{}:{details:n},type:k(r),...r.param?{param:r.param}:{},origin:"runtime",retryable:r.retryable,request_id:a,...r.code==="all_routes_exhausted"?{retry_after_s:r.details.retry_after_s}:{},...U(r)}}}}throw r}finally{t.off("close",p)}},"handler")},{method:"GET",pattern:"/v1/usage",handler:s(({req:e})=>{const t=_(),o={"Request-Id":t};try{const a=A(l(e));return{status:200,headers:o,body:G(a.grantee,a.spend_cap,N(new URL(e.url??"/","http://runtime.local").searchParams.get("month")))}}catch(a){if(!(a instanceof d))throw a;return{status:a.status,headers:o,body:{error:{code:a.code,message:a.message,type:k(a),...a.param?{param:a.param}:{},origin:"runtime",retryable:!1,request_id:t}}}}},"handler")}];export{U as capFields,Y as llmRoutes,A as spendTarget};