@north-light/cli 0.3.720 → 0.3.722

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/dist/api/contract.d.ts +1 -1
  2. package/dist/api/contract.js +1 -1
  3. package/dist/api/dto/recovery.d.ts +2 -0
  4. package/dist/builtin-memory/crouter-sdk/release-notes.md +6 -0
  5. package/dist/cli.js +8 -8
  6. package/dist/clients/attach/viewer.js +314 -314
  7. package/dist/commands/api-client.d.ts +2 -0
  8. package/dist/commands/api-client.js +2 -2
  9. package/dist/commands/node/inspect.js +7 -7
  10. package/dist/commands/profile/environment.js +2 -2
  11. package/dist/core/canvas/schema-pg/031-environment-pull-request-write-default.sql +2 -0
  12. package/dist/core/canvas/schema-pg/032-model-cooldown-vendor-limit.sql +4 -0
  13. package/dist/core/canvas/schema-version.d.ts +1 -1
  14. package/dist/core/canvas/schema-version.js +1 -1
  15. package/dist/core/environments.js +1 -1
  16. package/dist/core/graph/reader.js +1 -1
  17. package/dist/core/import/load/open-grants.d.ts +1 -0
  18. package/dist/core/import/load/open-grants.js +1 -0
  19. package/dist/core/import/load/run.d.ts +3 -1
  20. package/dist/core/import/load/run.js +2 -2
  21. package/dist/core/llm/run.js +2 -2
  22. package/dist/core/managed-providers.d.ts +9 -1
  23. package/dist/core/provider-failure.d.ts +2 -0
  24. package/dist/core/provider-failure.js +1 -1
  25. package/dist/core/runtime/broker/model-adapter.js +3 -3
  26. package/dist/core/runtime/revive.d.ts +2 -0
  27. package/dist/core/runtime/revive.js +2 -2
  28. package/dist/core/runtime/runner/blaxel/image-build.d.ts +3 -0
  29. package/dist/core/runtime/runner/blaxel/image-build.js +6 -6
  30. package/dist/core/subscription-state.d.ts +4 -4
  31. package/dist/core/subscription-state.js +1 -1
  32. package/dist/daemon/api/handlers/messages.js +2 -2
  33. package/dist/daemon/api/handlers/nodes.js +1 -1
  34. package/dist/daemon/api/handlers/profiles.js +1 -1
  35. package/dist/daemon/api/operations.js +1 -1
  36. package/dist/daemon/api/router.d.ts +4 -0
  37. package/dist/daemon/api/router.js +1 -1
  38. package/dist/daemon/reconcilers/broker-supervision.js +3 -3
  39. package/docs/sdk/release-notes.md +6 -0
  40. package/package.json +3 -3
  41. package/packages/crouter-api/dist/api/contract.js +1 -1
  42. package/packages/crouter-api/dist/commands/api-client.js +3 -1
  43. package/packages/crouter-api/dist/commands/node/inspect.js +2 -1
  44. package/packages/crouter-api/dist/commands/profile/environment.js +2 -2
  45. package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
  46. package/packages/crouter-api/dist/core/environments.js +1 -1
  47. package/packages/crouter-api/dist/core/graph/reader.js +3 -3
  48. package/packages/crouter-api/dist/core/llm/run.js +13 -2
  49. package/packages/crouter-api/dist/core/provider-failure.js +9 -0
  50. package/packages/crouter-api/dist/core/runtime/broker/model-adapter.js +3 -1
  51. package/packages/crouter-api/dist/core/runtime/revive.js +11 -0
  52. package/packages/crouter-api/dist/core/runtime/runner/blaxel/image-build.js +16 -1
  53. package/packages/crouter-api/dist/core/subscription-state.js +26 -10
  54. package/packages/crouter-api/dist/daemon/api/operations.js +2 -2
  55. package/packages/crouter-api/dist/daemon/api/router.js +1 -1
  56. package/packages/crouter-api/dist/daemon/reconcilers/broker-supervision.js +3 -1
  57. package/packages/crouter-api/package.json +1 -1
  58. package/packages/crouter-identity/package.json +1 -1
  59. package/packages/crouter-plugin/package.json +3 -3
  60. package/runtime.lock.json +14 -14
@@ -34,6 +34,8 @@ export declare const COLD_START_DIAGNOSTIC_TAIL_BYTES = 4096;
34
34
  * contract — a missing/unreadable/empty log yields `undefined` so the base
35
35
  * message is used unchanged. */
36
36
  export declare function readColdStartDiagnostic(): string | undefined;
37
+ /** True when this CLI calls the control plane with a cron's run token; such a process never holds the person's settings. */
38
+ export declare const usesRunToken: () => boolean;
37
39
  /** Where a `crtr` process outside a node reaches the control plane instead of a local daemon: a machine cron's run token goes to
38
40
  * `CRTR_API_URL`; an imported Mac (`runtime/machine.json`) goes to its `apiUrl` with the signed-in person's bearer. Neither: undefined,
39
41
  * and the local socket is used. `CRTR_API_SOCKET` (inside a node) is checked by the caller first and is never remote. */
@@ -1,4 +1,4 @@
1
- var T=Object.defineProperty;var a=(r,t)=>T(r,"name",{value:t,configurable:!0});import{closeSync as N,existsSync as E,fstatSync as A,openSync as O,readFileSync as m,readSync as x}from"node:fs";import{dirname as I,join as l}from"node:path";import{gunzipSync as M}from"node:zlib";import{CrtrClient as p,ApiError as u}from"../api/index.js";import{localClient as f}from"../api/node-transport.js";import{northlightFetch as F,notSignedIn as D,readPersonCredential as P}from"../core/directory/person-credential.js";import{isMoveCommitted as U,moveUnfinishedError as k,readMachineConfig as w}from"../daemon/machine-link/config.js";import{northlightUnreachable as L}from"../core/directory/reach.js";import{apiErrorToCliError as _}from"../core/io.js";import{autostartDisabled as b,daemonAutostartStartupFailure as K,ensureDaemon as B}from"../daemon/manage.js";import{DAEMON_STARTUP_WINDOW_MS as g}from"../daemon/startup-policy.js";import{readState as W}from"../core/config.js";import{resolveRemoteCanvasTarget as j}from"../core/remote-canvas-target.js";import{RemoteCanvasSource as G}from"../core/canvas/remote-canvas-source.js";import{BROKER_RELEASED_MARKER as z,BROKER_RELAY_GENERATION as V,crtrHome as q}from"../core/canvas/paths.js";import{envTestNodeSocketWindowMs as H,isSandboxedNode as Y,providerProjectionOverBrokerRelay as $}from"../shared/env.js";import{CrtrError as v,ownerOnly as J}from"../core/errors.js";import{ExitCode as y}from"../types.js";function d(r){return{...r,fault:r.fault??null}}a(d,"withRowFault");function X(r,t){throw r instanceof u?_(r,t):r}a(X,"rethrowAsCliError");async function Nt(r){try{return await S().getNode(r)}catch(t){if(t instanceof u&&t.status===404)return null;X(t)}}a(Nt,"getNodeOrNull");const Q="crtr_run_",Z=4096,tt=20;function et(){let r;try{r=O(l(q(),"crtrd.log"),"r");const{size:t}=A(r),e=Math.max(0,t-Z),s=t-e;if(s<=0)return;const n=Buffer.alloc(s);x(r,n,0,s,e);const o=n.toString("utf8").split(`
1
+ var T=Object.defineProperty;var a=(r,t)=>T(r,"name",{value:t,configurable:!0});import{closeSync as E,existsSync as N,fstatSync as A,openSync as O,readFileSync as m,readSync as x}from"node:fs";import{dirname as I,join as l}from"node:path";import{gunzipSync as M}from"node:zlib";import{CrtrClient as p,ApiError as u}from"../api/index.js";import{localClient as f}from"../api/node-transport.js";import{northlightFetch as P,notSignedIn as F,readPersonCredential as U}from"../core/directory/person-credential.js";import{isMoveCommitted as D,moveUnfinishedError as k,readMachineConfig as w}from"../daemon/machine-link/config.js";import{northlightUnreachable as K}from"../core/directory/reach.js";import{apiErrorToCliError as _}from"../core/io.js";import{autostartDisabled as b,daemonAutostartStartupFailure as L,ensureDaemon as B}from"../daemon/manage.js";import{DAEMON_STARTUP_WINDOW_MS as C}from"../daemon/startup-policy.js";import{readState as W}from"../core/config.js";import{resolveRemoteCanvasTarget as j}from"../core/remote-canvas-target.js";import{RemoteCanvasSource as G}from"../core/canvas/remote-canvas-source.js";import{BROKER_RELEASED_MARKER as z,BROKER_RELAY_GENERATION as V,crtrHome as q}from"../core/canvas/paths.js";import{envTestNodeSocketWindowMs as H,isSandboxedNode as Y,providerProjectionOverBrokerRelay as $}from"../shared/env.js";import{CrtrError as g,ownerOnly as J}from"../core/errors.js";import{ExitCode as v}from"../types.js";function d(r){return{...r,fault:r.fault??null}}a(d,"withRowFault");function X(r,t){throw r instanceof u?_(r,t):r}a(X,"rethrowAsCliError");async function Nt(r){try{return await y().getNode(r)}catch(t){if(t instanceof u&&t.status===404)return null;X(t)}}a(Nt,"getNodeOrNull");const Q="crtr_run_",Z=4096,tt=20;function et(){let r;try{r=O(l(q(),"crtrd.log"),"r");const{size:t}=A(r),e=Math.max(0,t-Z),s=t-e;if(s<=0)return;const n=Buffer.alloc(s);x(r,n,0,s,e);const o=n.toString("utf8").split(`
2
2
  `).filter(c=>c.trim()!=="").slice(-tt).join(`
3
3
  `).trim();return o===""?void 0:`crtrd.log (tail):
4
- ${o}`}catch{return}finally{if(r!==void 0)try{N(r)}catch{}}}a(et,"readColdStartDiagnostic");function nt(){if(process.env.CRTR_API_SOCKET)return;const r=process.env.CRTR_API_TOKEN,t=process.env.CRTR_API_URL;if(r!==void 0&&r.startsWith(Q)&&t)return{client:a(i=>new p({baseUrl:t,headers:{authorization:`Bearer ${r}`},...i!==void 0?{timeoutMs:i}:{}}),"client")};const e=w();if(e===void 0)return;if(P()===void 0)throw D("this computer is imported into Northlight, so crtr needs your sign-in");const s=F(e.directoryUrl,e.apiUrl),n=a((i,o)=>s(i,o).catch(c=>{throw c instanceof v?C(c):c}),"authed");return{client:a(i=>st(new p({baseUrl:e.apiUrl,fetch:n,...i!==void 0?{timeoutMs:i}:{}}),e.apiUrl),"client")}}a(nt,"remoteTarget");function rt(){return!!process.env.CRTR_API_SOCKET&&(w()!==void 0||$())}a(rt,"relayReachesControlPlane");function st(r,t){return new Proxy(r,{get(e,s){const n=Reflect.get(e,s,e);return typeof n!="function"?n:(...i)=>{const o=n.apply(e,i);return o instanceof Promise?o.catch(c=>{throw c instanceof u&&c.code==="request_timeout"?C(L(c,t)):c}):o}}})}a(st,"unreachableOnTimeout");function C(r){const t=typeof r.details?.next=="string"?r.details.next:void 0;return new u(r.exitCode===y.NETWORK?503:401,r.code,r.message,{error:r.code,message:r.message,...t===void 0?{}:{next:t}})}a(C,"asApiError");function it(){return U()?k():void 0}a(it,"moveUnfinished");function S(r){if(r?.local!==!0){const s=it();if(s!==void 0)throw s}if(r?.local===!0&&rt())throw new v("no_local_daemon","this node reaches Northlight's shared control plane, not a daemon on this computer",y.USAGE,{next:"Ask the person to run this in their own terminal on this computer."});const t=r?.local===!0?void 0:nt();if(t!==void 0)return t.client(r?.timeoutMs);const e=process.env.CRTR_API_SOCKET;if(e){const s=a(()=>{if(!E(e))try{const i=I(e),o=m(l(i,z),"utf8"),c=m(l(i,V),"utf8");if(o===c&&o!=="")return new u(503,"broker_released","This node's broker has been released, so crtr commands from its background jobs are not available.")}catch(i){if(i.code!=="ENOENT")throw i}},"availabilityFailure"),n=s();if(n!==void 0)throw _(n,"Run the command from the node's own turn instead.");return f({autostart:!1,availabilityFailure:s,coldStartPollWindowMs:(b()?H():void 0)??g,...r?.timeoutMs!==void 0?{timeoutMs:r.timeoutMs}:{}})}return b()?f({autostart:!1,...r?.timeoutMs!==void 0?{timeoutMs:r.timeoutMs}:{}}):f({...r?.timeoutMs!==void 0?{timeoutMs:r.timeoutMs}:{},onColdSocket:a(async()=>{B()},"onColdSocket"),coldStartDiagnostic:et,coldStartFailure:K,coldStartPollWindowMs:g})}a(S,"cliClient");const ot=2e3;class R{static{a(this,"ApiCanvasSource")}client;rosterCache=null;rosterInFlight=null;constructor(t=S()){this.client=t}async roster(){const t=Date.now();return this.rosterCache!==null&&t-this.rosterCache.at<ot?this.rosterCache.index:this.rosterInFlight!==null?this.rosterInFlight:(this.rosterInFlight=this.client.canvasRoster().then(e=>{const s={snapshot:e,subscriptions:new Map,subscribers:new Map};for(const n of e.edges){const i={node_id:n.to_id,active:n.active,created:n.created},o={node_id:n.from_id,active:n.active,created:n.created},c=s.subscriptions.get(n.from_id);c===void 0?s.subscriptions.set(n.from_id,[i]):c.push(i);const h=s.subscribers.get(n.to_id);h===void 0?s.subscribers.set(n.to_id,[o]):h.push(o)}return this.rosterCache={at:Date.now(),index:s},s}).finally(()=>{this.rosterInFlight=null}),this.rosterInFlight)}async orNull(t){try{return await t()}catch(e){if(e instanceof u&&e.status===404)return null;throw e}}async getNode(t){const e=await this.orNull(()=>this.client.getNode(t));return e===null?null:d(e)}async getRow(t){const e=await this.orNull(()=>this.client.getNode(t));return e===null?null:d(e)}async listNodes(t){const e=t?.status,s=t?.under===void 0?{}:{under:t.under,under_inclusive:!0};let n;if(Array.isArray(e)){const i=new Set(e);n=(await this.client.listNodes(s)).filter(c=>i.has(c.status))}else n=await this.client.listNodes({...e!==void 0?{status:e}:{},...s});return n.map(i=>d(i))}async browseSnapshot(){const t=await this.client.canvasBrowseCompressed(),e=JSON.parse(M(t).toString("utf8")),s={subscriptions:new Map,subscribers:new Map};for(const n of e.edges){const i=s.subscriptions.get(n.from_id)??[];i.push({node_id:n.to_id,active:n.active,created:n.created}),s.subscriptions.set(n.from_id,i);const o=s.subscribers.get(n.to_id)??[];o.push({node_id:n.from_id,active:n.active,created:n.created}),s.subscribers.set(n.to_id,o)}return this.rosterCache={at:Date.now(),index:s},e.nodes.map(n=>d(n))}async panelView(t){return await this.client.canvasView(t)}async panelRoster(){const t=await this.roster();return t.snapshot!==void 0?t.snapshot:(this.rosterCache=null,(await this.roster()).snapshot)}async subscriptionsOf(t){return this.roster().then(e=>e.subscriptions.get(t)??[])}async subscribersOf(t){return this.roster().then(e=>e.subscribers.get(t)??[])}async view(t){const e=new Set([t]),s=[],n=(await this.subscriptionsOf(t)).map(i=>i.node_id);for(;n.length>0;){const i=n.shift();if(!e.has(i)){e.add(i),s.push(i);for(const o of await this.subscriptionsOf(i))e.has(o.node_id)||n.push(o.node_id)}}return s}async ticketCountsForNodes(t){return(await this.client.attentionCounts([...t])).counts}async ticketCountsForView(t){return this.ticketCountsForNodes([t,...await this.view(t)])}async newestReport(t){return(await this.client.getReports(t,{limit:1}))[0]??null}async hasActiveLiveSubscription(t){const e=(await this.subscriptionsOf(t)).filter(s=>s.active);for(const s of e){const n=await this.getRow(s.node_id);if(n&&(n.status==="active"||n.status==="idle"))return!0}return!1}}function Et(r,t=Y()){const e=r?.scope??"user";if(t){if(r?.canvasName!==void 0)throw J("--canvas selects the person's remote canvas targets, which an app's node cannot reach","Omit --canvas; this node reads its own runtime's canvas.");return new R}const s=r?.canvasName??W(e).activeCanvas??null;if(!s)return new R;const{previewEndpoint:n,relayToken:i}=j(s,e);return new G(n,i)}a(Et,"cliCanvasSource");export{R as ApiCanvasSource,Z as COLD_START_DIAGNOSTIC_TAIL_BYTES,Et as cliCanvasSource,S as cliClient,Nt as getNodeOrNull,it as moveUnfinished,et as readColdStartDiagnostic,rt as relayReachesControlPlane,nt as remoteTarget,X as rethrowAsCliError};
4
+ ${o}`}catch{return}finally{if(r!==void 0)try{E(r)}catch{}}}a(et,"readColdStartDiagnostic");const nt=a(()=>!process.env.CRTR_API_SOCKET&&!!process.env.CRTR_API_URL&&!!process.env.CRTR_API_TOKEN?.startsWith(Q),"usesRunToken");function rt(){if(process.env.CRTR_API_SOCKET)return;const r=process.env.CRTR_API_TOKEN,t=process.env.CRTR_API_URL;if(nt()&&r&&t)return{client:a(i=>new p({baseUrl:t,headers:{authorization:`Bearer ${r}`},...i!==void 0?{timeoutMs:i}:{}}),"client")};const e=w();if(e===void 0)return;if(U()===void 0)throw F("this computer is imported into Northlight, so crtr needs your sign-in");const s=P(e.directoryUrl,e.apiUrl),n=a((i,o)=>s(i,o).catch(c=>{throw c instanceof g?R(c):c}),"authed");return{client:a(i=>it(new p({baseUrl:e.apiUrl,fetch:n,...i!==void 0?{timeoutMs:i}:{}}),e.apiUrl),"client")}}a(rt,"remoteTarget");function st(){return!!process.env.CRTR_API_SOCKET&&(w()!==void 0||$())}a(st,"relayReachesControlPlane");function it(r,t){return new Proxy(r,{get(e,s){const n=Reflect.get(e,s,e);return typeof n!="function"?n:(...i)=>{const o=n.apply(e,i);return o instanceof Promise?o.catch(c=>{throw c instanceof u&&c.code==="request_timeout"?R(K(c,t)):c}):o}}})}a(it,"unreachableOnTimeout");function R(r){const t=typeof r.details?.next=="string"?r.details.next:void 0;return new u(r.exitCode===v.NETWORK?503:401,r.code,r.message,{error:r.code,message:r.message,...t===void 0?{}:{next:t}})}a(R,"asApiError");function ot(){return D()?k():void 0}a(ot,"moveUnfinished");function y(r){if(r?.local!==!0){const s=ot();if(s!==void 0)throw s}if(r?.local===!0&&st())throw new g("no_local_daemon","this node reaches Northlight's shared control plane, not a daemon on this computer",v.USAGE,{next:"Ask the person to run this in their own terminal on this computer."});const t=r?.local===!0?void 0:rt();if(t!==void 0)return t.client(r?.timeoutMs);const e=process.env.CRTR_API_SOCKET;if(e){const s=a(()=>{if(!N(e))try{const i=I(e),o=m(l(i,z),"utf8"),c=m(l(i,V),"utf8");if(o===c&&o!=="")return new u(503,"broker_released","This node's broker has been released, so crtr commands from its background jobs are not available.")}catch(i){if(i.code!=="ENOENT")throw i}},"availabilityFailure"),n=s();if(n!==void 0)throw _(n,"Run the command from the node's own turn instead.");return f({autostart:!1,availabilityFailure:s,coldStartPollWindowMs:(b()?H():void 0)??C,...r?.timeoutMs!==void 0?{timeoutMs:r.timeoutMs}:{}})}return b()?f({autostart:!1,...r?.timeoutMs!==void 0?{timeoutMs:r.timeoutMs}:{}}):f({...r?.timeoutMs!==void 0?{timeoutMs:r.timeoutMs}:{},onColdSocket:a(async()=>{B()},"onColdSocket"),coldStartDiagnostic:et,coldStartFailure:L,coldStartPollWindowMs:C})}a(y,"cliClient");const at=2e3;class S{static{a(this,"ApiCanvasSource")}client;rosterCache=null;rosterInFlight=null;constructor(t=y()){this.client=t}async roster(){const t=Date.now();return this.rosterCache!==null&&t-this.rosterCache.at<at?this.rosterCache.index:this.rosterInFlight!==null?this.rosterInFlight:(this.rosterInFlight=this.client.canvasRoster().then(e=>{const s={snapshot:e,subscriptions:new Map,subscribers:new Map};for(const n of e.edges){const i={node_id:n.to_id,active:n.active,created:n.created},o={node_id:n.from_id,active:n.active,created:n.created},c=s.subscriptions.get(n.from_id);c===void 0?s.subscriptions.set(n.from_id,[i]):c.push(i);const h=s.subscribers.get(n.to_id);h===void 0?s.subscribers.set(n.to_id,[o]):h.push(o)}return this.rosterCache={at:Date.now(),index:s},s}).finally(()=>{this.rosterInFlight=null}),this.rosterInFlight)}async orNull(t){try{return await t()}catch(e){if(e instanceof u&&e.status===404)return null;throw e}}async getNode(t){const e=await this.orNull(()=>this.client.getNode(t));return e===null?null:d(e)}async getRow(t){const e=await this.orNull(()=>this.client.getNode(t));return e===null?null:d(e)}async listNodes(t){const e=t?.status,s=t?.under===void 0?{}:{under:t.under,under_inclusive:!0};let n;if(Array.isArray(e)){const i=new Set(e);n=(await this.client.listNodes(s)).filter(c=>i.has(c.status))}else n=await this.client.listNodes({...e!==void 0?{status:e}:{},...s});return n.map(i=>d(i))}async browseSnapshot(){const t=await this.client.canvasBrowseCompressed(),e=JSON.parse(M(t).toString("utf8")),s={subscriptions:new Map,subscribers:new Map};for(const n of e.edges){const i=s.subscriptions.get(n.from_id)??[];i.push({node_id:n.to_id,active:n.active,created:n.created}),s.subscriptions.set(n.from_id,i);const o=s.subscribers.get(n.to_id)??[];o.push({node_id:n.from_id,active:n.active,created:n.created}),s.subscribers.set(n.to_id,o)}return this.rosterCache={at:Date.now(),index:s},e.nodes.map(n=>d(n))}async panelView(t){return await this.client.canvasView(t)}async panelRoster(){const t=await this.roster();return t.snapshot!==void 0?t.snapshot:(this.rosterCache=null,(await this.roster()).snapshot)}async subscriptionsOf(t){return this.roster().then(e=>e.subscriptions.get(t)??[])}async subscribersOf(t){return this.roster().then(e=>e.subscribers.get(t)??[])}async view(t){const e=new Set([t]),s=[],n=(await this.subscriptionsOf(t)).map(i=>i.node_id);for(;n.length>0;){const i=n.shift();if(!e.has(i)){e.add(i),s.push(i);for(const o of await this.subscriptionsOf(i))e.has(o.node_id)||n.push(o.node_id)}}return s}async ticketCountsForNodes(t){return(await this.client.attentionCounts([...t])).counts}async ticketCountsForView(t){return this.ticketCountsForNodes([t,...await this.view(t)])}async newestReport(t){return(await this.client.getReports(t,{limit:1}))[0]??null}async hasActiveLiveSubscription(t){const e=(await this.subscriptionsOf(t)).filter(s=>s.active);for(const s of e){const n=await this.getRow(s.node_id);if(n&&(n.status==="active"||n.status==="idle"))return!0}return!1}}function At(r,t=Y()){const e=r?.scope??"user";if(t){if(r?.canvasName!==void 0)throw J("--canvas selects the person's remote canvas targets, which an app's node cannot reach","Omit --canvas; this node reads its own runtime's canvas.");return new S}const s=r?.canvasName??W(e).activeCanvas??null;if(!s)return new S;const{previewEndpoint:n,relayToken:i}=j(s,e);return new G(n,i)}a(At,"cliCanvasSource");export{S as ApiCanvasSource,Z as COLD_START_DIAGNOSTIC_TAIL_BYTES,At as cliCanvasSource,y as cliClient,Nt as getNodeOrNull,ot as moveUnfinished,et as readColdStartDiagnostic,st as relayReachesControlPlane,rt as remoteTarget,X as rethrowAsCliError,nt as usesRunToken};
@@ -1,12 +1,12 @@
1
- var P=Object.defineProperty;var h=(n,e)=>P(n,"name",{value:e,configurable:!0});import{defineBranch as I,defineLeaf as _}from"../../core/command.js";import{InputError as k}from"../../core/io.js";import{requireScope as O}from"../../core/errors.js";import{isPidAlive as A}from"../../core/canvas/pid.js";import{fullName as $}from"../../core/canvas/labels.js";import{fuzzyMatch as F}from"../../core/tui/fuzzy.js";import{nodeSnapshotLeaf as L}from"../node-snapshot.js";import{nodeTranscriptLeaf as C}from"../node-transcript.js";import{nodeContextLeaf as U}from"../node-context.js";import{ApiError as D}from"../../api/index.js";import{cliClient as x,cliCanvasSource as S,rethrowAsCliError as w}from"../api-client.js";import{RemoteCanvasSource as q}from"../../core/canvas/remote-canvas-source.js";import{kindsStateBlock as E,profilesStateBlock as z,resolveProfileViaDaemon as M}from"../profile/daemon-profiles.js";import{focusViewer as B,nodeInPane as W}from"../surface/node/placement.js";const K=_({name:"list",description:"list nodes on the canvas",whenToUse:"you want a flat roster of the nodes on the canvas, sliced by displayed name, status, kind, mode, lifecycle, profile, cwd, and graph scope (--under a node, for that node plus its subscription descendants). The filters AND together. Use `node inspect show` instead to drill into one node and its spine neighbors, `canvas dashboard` for the tree shape, and `canvas attention` to find nodes blocked on the user",help:{name:"node inspect list",summary:"list nodes on the canvas, filtered by any combination of attribute slices and a graph-scope (--under) that AND together",params:[{kind:"flag",name:"status",type:"string",required:!1,constraint:"Filter status (comma-separated for several; accepted values: active, idle, done, dead, canceled). NOTE: `active` means the engine process is live (never closed), NOT that the node is generating right now \u2014 an active node is usually dormant between turns. To tell working-vs-idle, check the pi session-file mtime or CPU, not status."},{kind:"flag",name:"kind",type:"string",required:!1,constraint:"Filter by persona kind (comma-separated for several). The <kinds> list below names every top-level installable kind; a registered sub-kind filters too by exact path even though it is not listed."},{kind:"flag",name:"mode",type:"string",required:!1,constraint:"Filter by mode (comma-separated for several; accepted values: base, orchestrator)."},{kind:"flag",name:"lifecycle",type:"string",required:!1,constraint:"Filter by lifecycle (comma-separated for several; accepted values: terminal, resident)."},{kind:"flag",name:"profile",type:"string",required:!1,constraint:"Filter by profile. On the local canvas, accepts a profile id or manifest name from the <profiles> list below, or a close-enough name that resolves to the nearest profile. Against a remote canvas, pass the exact profile id carried by its node rows."},{kind:"flag",name:"name",type:"string",required:!1,constraint:"Filter by the displayed node label (handle plus generated description) with the canvas browser\u2019s case-insensitive fuzzy subsequence match."},{kind:"flag",name:"cwd",type:"string",required:!1,constraint:"Filter to nodes pinned to this exact cwd (absolute path). Roster is canvas-wide (all cwds) by default."},{kind:"flag",name:"under",type:"string",required:!1,constraint:'Graph scope: restrict to this node and its subscription descendants (the sub-DAG reachable downward \u2014 its reports, theirs, \u2026). This is "one initiative / my subtree". ANDs with every attribute filter above, narrowing any of them to this subtree.'},{kind:"flag",name:"canvas",type:"string",required:!1,constraint:"Read from the named remote canvas target (see `crtr canvas config list`) instead of the local canvas. Overrides `crtr canvas use`."}],output:[{name:"nodes",type:"object[]",required:!0,constraint:"Rows include {node_id, name, kind, mode, lifecycle, status, cwd, profile_id, parent, created}. `name` is the displayed node label searched by --name and shown in canvas views. `profile_id` is the stable profile-directory id (null only for historical no-profile nodes)."}],outputKind:"object",effects:["Read-only: lists nodes through the daemon API."]},helpState:{leaf:h(async()=>(await Promise.all([E(),z()])).join(`
2
- `),"leaf")},run:h(async n=>{const e=h(d=>{const b=n[d];return b!==void 0&&b!==""?b.split(",").map(v=>v.trim()).filter(v=>v!==""):void 0},"csv"),o=e("status"),s=e("kind"),p=e("mode"),i=e("lifecycle"),m=n.profile,c=n.name,l=n.cwd,r=n.under,u=S({canvasName:n.canvas}),a=u instanceof q?m:m===void 0?void 0:(await M(m)).id,f=r!==void 0&&r!=="";if(f&&await u.getNode(r).catch(w)===null)throw new k({error:"not_found",message:`no node: ${r}`,next:"List nodes with `crtr node inspect list`, then pass a real id to --under."});return{nodes:(await u.listNodes({...o!==void 0?{status:o}:{},...f?{under:r}:{}}).catch(w)).filter(d=>!(s!==void 0&&!s.includes(d.kind)||p!==void 0&&!p.includes(d.mode)||i!==void 0&&!i.includes(d.lifecycle)||a!==void 0&&d.profile_id!==a||l!==void 0&&l!==""&&d.cwd!==l)).map(d=>({...d,name:$(d)})).filter(d=>c===void 0||c===""||F(c,d.name))}},"run")}),j=new WeakSet,T=new WeakSet;async function N(n,e){const o=await n.getNode(e.node_id).catch(w);return{node_id:e.node_id,name:o?$(o):"(missing)",kind:o?.kind??"?",status:o?o.intent?`${o.status}/${o.intent}`:o.status:"?",active:e.active}}h(N,"enrichNeighbor");const V=_({name:"show",description:"show a node + its spine neighbors and drill-in pointers",whenToUse:"you want one node in depth \u2014 the debugging entrypoint: a glanceable meta slice, named spine neighbors, a pending-cron count, and exact drill-in paths. Use `node inspect list` for the flat roster or `canvas dashboard` for the whole-tree shape",help:{name:"node inspect show",summary:"show a node in depth \u2014 meta slice, named neighbors, pending-cron count, and drill-in pointers",params:[{kind:"positional",name:"node",required:!0,constraint:"Node id."},{kind:"flag",name:"canvas",type:"string",required:!1,constraint:"Read from the named remote canvas target (see `crtr canvas config list`) instead of the local canvas. Overrides `crtr canvas use`."}],output:[{name:"node",type:"object",required:!0,constraint:"The full node meta (system prompt + every telemetry field). The render surfaces a glanceable slice; `--json` carries the complete dump."},{name:"fault",type:"object",required:!0,constraint:"The active runtime fault projection, or null: {link, kind, retry: {disposition}, since}."},{name:"reports",type:"object[]",required:!0,constraint:"Who this node subscribes to (its reports/down), each enriched with {node_id, name, kind, status, active} \u2014 these are typically its spawned children."},{name:"managers",type:"object[]",required:!0,constraint:"Who subscribes to this node (its managers/up), same enriched shape."},{name:"pending_crons",type:"number",required:!0,constraint:"How many pending crons were created by this node. Inspect with `crtr cron list`."},{name:"paths",type:"object",required:!0,constraint:"Resolved on-disk locations: {context_dir, session_file} \u2014 read these directly to debug. Reports are documents: `crtr canvas read <node>/reports/<name>`."},{name:"follow_up",type:"string",required:!0,constraint:"The concrete next commands to drill deeper."}],outputKind:"object",effects:["Read-only: reads the node, its edges, and pending crons through crtrd."],preview:{suppressOutput:!0}},run:h(async n=>{const e=n.node,o=n.canvas,s=S({canvasName:o});if(s instanceof q){const t=await s.rawShow(e);if(t===null)throw new k({error:"not_found",message:`no node: ${e}`,next:"List nodes with `crtr node inspect list --canvas <name>`."});const y={...t};return j.add(y),y}const p=await s.getNode(e).catch(t=>w(t,"List nodes with `crtr node inspect list`."));if(p===null)throw new k({error:"not_found",message:`no node: ${e}`,next:"List nodes with `crtr node inspect list`."});const i=p,m=x(),c=await Promise.all((await s.subscriptionsOf(e)).map(t=>N(s,t))),l=await Promise.all((await s.subscribersOf(e)).map(t=>N(s,t))),r=(await m.listCrons({created_by:e}).catch(w)).filter(t=>t.created_by===e).length,u={context_dir:i.paths.context_dir,...i.pi_session_file!==void 0?{session_file:i.pi_session_file}:{}},a=[];a.push(`List the documents it owns (reports, plans, notes): \`crtr canvas list --owner ${e}\`.`),a.push(`Browse its context dir (and its subscriptions') in nvim: \`crtr node inspect context ${e}\`.`),u.session_file&&a.push(`Read the raw conversation transcript: ${u.session_file}`),a.push(`On-disk context dir (ls/read directly): ${u.context_dir}`),r>0&&a.push(`It created ${r} pending cron(s): \`crtr cron list\`.`),c.length>0&&a.push(`Drill into a child/report: \`crtr node inspect show <node_id>\` (${c.map(t=>t.node_id).join(", ")}).`),a.push(`Full machine dump (system prompt + all telemetry): \`crtr --json node inspect show ${e}\`.`);const f={node:i,fault:i.fault??null,reports:c,managers:l,pending_crons:r,paths:u,follow_up:a.join(`
3
- `)};return(i.runner==="blaxel"||i.profile_id!==null&&await m.getProfileEnvironment(i.profile_id).then(()=>!0,t=>t instanceof D&&(t.status===400||t.status===404)?!1:w(t)))&&T.add(f),f},"run"),render:h(n=>{const e=n.node,o=String(e.node_id),s=e.pi_pid,i=j.has(n)?"remote (liveness not checked locally)":e.runner==="machine"?"on a Mac (liveness not checked locally)":T.has(n)?"in a cloud sandbox (liveness not checked locally)":A(s)?"alive":"dead",m=e.intent?`/${String(e.intent)}`:"",c=n.fault,l=[];l.push(`# ${$(e)} (${o})`);const r=[`- kind/mode/lifecycle: ${e.kind} / ${e.mode} / ${e.lifecycle}`,`- status: ${e.status}${m}`,...c==null?[]:[`- fault: ${String(c.kind)} / ${String(c.retry?.disposition)} since ${String(c.since)}`],`- broker pid: ${s??"(none)"} \u2014 ${i}`,`- cwd: ${e.cwd}`,`- host: ${e.host_kind}`+(e.profile_id?` \xB7 profile ${e.profile_id}`:""),`- cycles: ${e.cycles} \xB7 created ${e.created}`],u=e.machine;u&&r.push(`- machine: ${u.name??u.id}`),e.parent&&r.push(`- parent: ${e.parent}`),r.push(`- creator: ${e.creator??"an external process"}`),e.waiting_for&&r.push(`- waiting for message: ${e.waiting_for}`),l.push(r.join(`
4
- `));const a=h((f,g)=>{if(g.length===0)return`${f}: none`;const t=["node_id","name","kind","status","active"],y=`| ${t.join(" | ")} |`,d=`| ${t.map(()=>"---").join(" | ")} |`,b=g.map(v=>`| ${t.map(R=>String(v[R]??"").replace(/\|/g,"\\|").replace(/\n/g," ")).join(" | ")} |`).join(`
1
+ var P=Object.defineProperty;var h=(n,e)=>P(n,"name",{value:e,configurable:!0});import{defineBranch as A,defineLeaf as $}from"../../core/command.js";import{InputError as k}from"../../core/io.js";import{requireScope as I}from"../../core/errors.js";import{isPidAlive as L}from"../../core/canvas/pid.js";import{fullName as x}from"../../core/canvas/labels.js";import{fuzzyMatch as O}from"../../core/tui/fuzzy.js";import{nodeSnapshotLeaf as F}from"../node-snapshot.js";import{nodeTranscriptLeaf as C}from"../node-transcript.js";import{nodeContextLeaf as U}from"../node-context.js";import{ApiError as E}from"../../api/index.js";import{describeVendorLimit as D}from"../../core/provider-failure.js";import{cliClient as _,cliCanvasSource as S,rethrowAsCliError as w}from"../api-client.js";import{RemoteCanvasSource as q}from"../../core/canvas/remote-canvas-source.js";import{kindsStateBlock as z,profilesStateBlock as M,resolveProfileViaDaemon as B}from"../profile/daemon-profiles.js";import{focusViewer as V,nodeInPane as W}from"../surface/node/placement.js";const K=$({name:"list",description:"list nodes on the canvas",whenToUse:"you want a flat roster of the nodes on the canvas, sliced by displayed name, status, kind, mode, lifecycle, profile, cwd, and graph scope (--under a node, for that node plus its subscription descendants). The filters AND together. Use `node inspect show` instead to drill into one node and its spine neighbors, `canvas dashboard` for the tree shape, and `canvas attention` to find nodes blocked on the user",help:{name:"node inspect list",summary:"list nodes on the canvas, filtered by any combination of attribute slices and a graph-scope (--under) that AND together",params:[{kind:"flag",name:"status",type:"string",required:!1,constraint:"Filter status (comma-separated for several; accepted values: active, idle, done, dead, canceled). NOTE: `active` means the engine process is live (never closed), NOT that the node is generating right now \u2014 an active node is usually dormant between turns. To tell working-vs-idle, check the pi session-file mtime or CPU, not status."},{kind:"flag",name:"kind",type:"string",required:!1,constraint:"Filter by persona kind (comma-separated for several). The <kinds> list below names every top-level installable kind; a registered sub-kind filters too by exact path even though it is not listed."},{kind:"flag",name:"mode",type:"string",required:!1,constraint:"Filter by mode (comma-separated for several; accepted values: base, orchestrator)."},{kind:"flag",name:"lifecycle",type:"string",required:!1,constraint:"Filter by lifecycle (comma-separated for several; accepted values: terminal, resident)."},{kind:"flag",name:"profile",type:"string",required:!1,constraint:"Filter by profile. On the local canvas, accepts a profile id or manifest name from the <profiles> list below, or a close-enough name that resolves to the nearest profile. Against a remote canvas, pass the exact profile id carried by its node rows."},{kind:"flag",name:"name",type:"string",required:!1,constraint:"Filter by the displayed node label (handle plus generated description) with the canvas browser\u2019s case-insensitive fuzzy subsequence match."},{kind:"flag",name:"cwd",type:"string",required:!1,constraint:"Filter to nodes pinned to this exact cwd (absolute path). Roster is canvas-wide (all cwds) by default."},{kind:"flag",name:"under",type:"string",required:!1,constraint:'Graph scope: restrict to this node and its subscription descendants (the sub-DAG reachable downward \u2014 its reports, theirs, \u2026). This is "one initiative / my subtree". ANDs with every attribute filter above, narrowing any of them to this subtree.'},{kind:"flag",name:"canvas",type:"string",required:!1,constraint:"Read from the named remote canvas target (see `crtr canvas config list`) instead of the local canvas. Overrides `crtr canvas use`."}],output:[{name:"nodes",type:"object[]",required:!0,constraint:"Rows include {node_id, name, kind, mode, lifecycle, status, cwd, profile_id, parent, created}. `name` is the displayed node label searched by --name and shown in canvas views. `profile_id` is the stable profile-directory id (null only for historical no-profile nodes)."}],outputKind:"object",effects:["Read-only: lists nodes through the daemon API."]},helpState:{leaf:h(async()=>(await Promise.all([z(),M()])).join(`
2
+ `),"leaf")},run:h(async n=>{const e=h(c=>{const b=n[c];return b!==void 0&&b!==""?b.split(",").map(v=>v.trim()).filter(v=>v!==""):void 0},"csv"),o=e("status"),s=e("kind"),p=e("mode"),i=e("lifecycle"),m=n.profile,r=n.name,l=n.cwd,a=n.under,u=S({canvasName:n.canvas}),d=u instanceof q?m:m===void 0?void 0:(await B(m)).id,f=a!==void 0&&a!=="";if(f&&await u.getNode(a).catch(w)===null)throw new k({error:"not_found",message:`no node: ${a}`,next:"List nodes with `crtr node inspect list`, then pass a real id to --under."});return{nodes:(await u.listNodes({...o!==void 0?{status:o}:{},...f?{under:a}:{}}).catch(w)).filter(c=>!(s!==void 0&&!s.includes(c.kind)||p!==void 0&&!p.includes(c.mode)||i!==void 0&&!i.includes(c.lifecycle)||d!==void 0&&c.profile_id!==d||l!==void 0&&l!==""&&c.cwd!==l)).map(c=>({...c,name:x(c)})).filter(c=>r===void 0||r===""||O(r,c.name))}},"run")}),j=new WeakSet,T=new WeakSet;async function N(n,e){const o=await n.getNode(e.node_id).catch(w);return{node_id:e.node_id,name:o?x(o):"(missing)",kind:o?.kind??"?",status:o?o.intent?`${o.status}/${o.intent}`:o.status:"?",active:e.active}}h(N,"enrichNeighbor");const G=$({name:"show",description:"show a node + its spine neighbors and drill-in pointers",whenToUse:"you want one node in depth \u2014 the debugging entrypoint: a glanceable meta slice, named spine neighbors, a pending-cron count, and exact drill-in paths. Use `node inspect list` for the flat roster or `canvas dashboard` for the whole-tree shape",help:{name:"node inspect show",summary:"show a node in depth \u2014 meta slice, named neighbors, pending-cron count, and drill-in pointers",params:[{kind:"positional",name:"node",required:!0,constraint:"Node id."},{kind:"flag",name:"canvas",type:"string",required:!1,constraint:"Read from the named remote canvas target (see `crtr canvas config list`) instead of the local canvas. Overrides `crtr canvas use`."}],output:[{name:"node",type:"object",required:!0,constraint:"The full node meta (system prompt + every telemetry field). The render surfaces a glanceable slice; `--json` carries the complete dump."},{name:"fault",type:"object",required:!0,constraint:"The active runtime fault projection, or null: {link, kind, retry: {disposition}, since}."},{name:"reports",type:"object[]",required:!0,constraint:"Who this node subscribes to (its reports/down), each enriched with {node_id, name, kind, status, active} \u2014 these are typically its spawned children."},{name:"managers",type:"object[]",required:!0,constraint:"Who subscribes to this node (its managers/up), same enriched shape."},{name:"pending_crons",type:"number",required:!0,constraint:"How many pending crons were created by this node. Inspect with `crtr cron list`."},{name:"paths",type:"object",required:!0,constraint:"Resolved on-disk locations: {context_dir, session_file} \u2014 read these directly to debug. Reports are documents: `crtr canvas read <node>/reports/<name>`."},{name:"follow_up",type:"string",required:!0,constraint:"The concrete next commands to drill deeper."}],outputKind:"object",effects:["Read-only: reads the node, its edges, and pending crons through crtrd."],preview:{suppressOutput:!0}},run:h(async n=>{const e=n.node,o=n.canvas,s=S({canvasName:o});if(s instanceof q){const t=await s.rawShow(e);if(t===null)throw new k({error:"not_found",message:`no node: ${e}`,next:"List nodes with `crtr node inspect list --canvas <name>`."});const y={...t};return j.add(y),y}const p=await s.getNode(e).catch(t=>w(t,"List nodes with `crtr node inspect list`."));if(p===null)throw new k({error:"not_found",message:`no node: ${e}`,next:"List nodes with `crtr node inspect list`."});const i=p,m=_(),r=await Promise.all((await s.subscriptionsOf(e)).map(t=>N(s,t))),l=await Promise.all((await s.subscribersOf(e)).map(t=>N(s,t))),a=(await m.listCrons({created_by:e}).catch(w)).filter(t=>t.created_by===e).length,u={context_dir:i.paths.context_dir,...i.pi_session_file!==void 0?{session_file:i.pi_session_file}:{}},d=[];d.push(`List the documents it owns (reports, plans, notes): \`crtr canvas list --owner ${e}\`.`),d.push(`Browse its context dir (and its subscriptions') in nvim: \`crtr node inspect context ${e}\`.`),u.session_file&&d.push(`Read the raw conversation transcript: ${u.session_file}`),d.push(`On-disk context dir (ls/read directly): ${u.context_dir}`),a>0&&d.push(`It created ${a} pending cron(s): \`crtr cron list\`.`),r.length>0&&d.push(`Drill into a child/report: \`crtr node inspect show <node_id>\` (${r.map(t=>t.node_id).join(", ")}).`),d.push(`Full machine dump (system prompt + all telemetry): \`crtr --json node inspect show ${e}\`.`);const f={node:i,fault:i.fault??null,reports:r,managers:l,pending_crons:a,paths:u,follow_up:d.join(`
3
+ `)};return(i.runner==="blaxel"||i.profile_id!==null&&await m.getProfileEnvironment(i.profile_id).then(()=>!0,t=>t instanceof E&&(t.status===400||t.status===404)?!1:w(t)))&&T.add(f),f},"run"),render:h(n=>{const e=n.node,o=String(e.node_id),s=e.pi_pid,i=j.has(n)?"remote (liveness not checked locally)":e.runner==="machine"?"on a Mac (liveness not checked locally)":T.has(n)?"in a cloud sandbox (liveness not checked locally)":L(s)?"alive":"dead",m=e.intent?`/${String(e.intent)}`:"",r=n.fault,l=[];l.push(`# ${x(e)} (${o})`);const a=[`- kind/mode/lifecycle: ${e.kind} / ${e.mode} / ${e.lifecycle}`,`- status: ${e.status}${m}`,...r==null?[]:[`- fault: ${String(r.kind)} / ${String(r.retry?.disposition)} since ${String(r.since)}${r.retry?.nextAt===void 0?"":`. Next router probe: ${r.retry.nextAt}.`}${D(r.providerError)}`],`- broker pid: ${s??"(none)"} \u2014 ${i}`,`- cwd: ${e.cwd}`,`- host: ${e.host_kind}`+(e.profile_id?` \xB7 profile ${e.profile_id}`:""),`- cycles: ${e.cycles} \xB7 created ${e.created}`],u=e.machine;u&&a.push(`- machine: ${u.name??u.id}`),e.parent&&a.push(`- parent: ${e.parent}`),a.push(`- creator: ${e.creator??"an external process"}`),e.waiting_for&&a.push(`- waiting for message: ${e.waiting_for}`),l.push(a.join(`
4
+ `));const d=h((f,g)=>{if(g.length===0)return`${f}: none`;const t=["node_id","name","kind","status","active"],y=`| ${t.join(" | ")} |`,c=`| ${t.map(()=>"---").join(" | ")} |`,b=g.map(v=>`| ${t.map(R=>String(v[R]??"").replace(/\|/g,"\\|").replace(/\n/g," ")).join(" | ")} |`).join(`
5
5
  `);return`${g.length} ${f}:
6
6
 
7
7
  ${y}
8
- ${d}
9
- ${b}`},"table");return l.push(a("reports (down \u2014 subscriptions, usually children)",n.reports)),l.push(a("managers (up \u2014 subscribers)",n.managers)),l.push(`${n.pending_crons} pending cron(s)`),l.push(`Drill deeper:
8
+ ${c}
9
+ ${b}`},"table");return l.push(d("reports (down \u2014 subscriptions, usually children)",n.reports)),l.push(d("managers (up \u2014 subscribers)",n.managers)),l.push(`${n.pending_crons} pending cron(s)`),l.push(`Drill deeper:
10
10
  ${String(n.follow_up)}`),l.join(`
11
11
 
12
- `)},"render")}),de=_({name:"fork",description:"fork a node into an independent idle root with the same conversation and durable context",whenToUse:"a conversation has already accumulated the context you want, and you want a new user-driven branch beside it without sending a prompt or inheriting any graph-management responsibility. This copies the conversation and durable context, then waits for the fork\u2019s first real user message to supply its mandate. Use `node new --fork-from` instead when spawning a managed worker with an immediate task",help:{name:"node fork",summary:"create an independent resident root from a node\u2019s conversation and durable context, with no kickoff prompt or model turn",params:[{kind:"flag",name:"node",type:"string",required:!1,constraint:"Source node id. Mutually exclusive with --pane; one of them is required."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the source node. Mutually exclusive with --node; one of them is required. The prefix menu passes this for you and the new viewer splits beside this pane."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The new independent root id."},{name:"focused",type:"boolean",required:!0,constraint:"True when a new viewer pane opened beside the caller; false outside tmux."},{name:"session",type:"string",required:!1,constraint:"The tmux session containing the new viewer, when one opened."}],outputKind:"object",effects:["Creates a resident base-mode root with the source node\u2019s copied pi conversation, cwd, profile, kind, model override, and durable context files. Top-level initial-prompt.md, yield-message.md, result.json, and the jobs/ folder of background bash jobs are omitted.","Copies no parent, subscriptions, subscribers, children, crons, worktree, situational context, or lifecycle responsibility. Sends no prompt and consumes no model turn; the first real user message becomes the fork\u2019s mandate.","Inside tmux, opens and focuses a surface-attach viewer as an even-horizontal split in the source pane\u2019s window. Outside tmux, the root is still created but no interactive fallback opens."]},run:h(async n=>{O("crtr:act","crtr node fork");const e=n.pane,o=n.node;if(o!==void 0&&e!==void 0)throw new k({error:"conflicting_target",message:"--node and --pane are mutually exclusive",next:"Pass the source node id or its viewer pane, not both."});let s=o;if(s===void 0&&e!==void 0&&(s=W(e)),s===void 0||s==="")throw new k({error:"no_node",message:"no source node was provided or found in the pane",next:"Pass --node <id>, or --pane <pane-id> for a pane showing a node."});const p=await x().forkNode(s).catch(w),i=await B(p.node_id,{cwd:p.cwd,name:p.name,...e!==void 0?{pane:e}:{},newPane:!0});return{node_id:p.node_id,focused:i.focused,session:i.session}},"run"),render:h(n=>{const e=n.focused===!0?` Viewer opened beside the source${n.session?` in session ${n.session}`:""}.`:" No viewer opened because no tmux pane was available.";return`Forked independent idle root ${n.node_id}.${e} It will make no model call until its first real user message.`},"render")}),ce=I({name:"inspect",description:"read one node \u2014 its graph position, conversation, and context dir",whenToUse:"reading everything about ONE node you can name: enumerate the roster (`list`), inspect a node and its spine neighbors (`show`), or browse its on-disk context dir (`context`). The documents a node owns are `crtr canvas list --owner <id>`. Use `canvas dashboard` instead to render the whole tree SHAPE, or `canvas attention` to find which nodes are blocked on the user",help:{name:"node inspect",summary:"read one node (or the roster) \u2014 topology, conversation, and context dir",model:"Inspection is read-only and never revives a node. The roster is the selection surface; one-node metadata points to progressively heavier views: a parsed broker snapshot, rendered conversation, or context browser."},children:[K,V,L,C,U]});export{de as nodeFork,ce as nodeInspect};
12
+ `)},"render")}),le=$({name:"fork",description:"fork a node into an independent idle root with the same conversation and durable context",whenToUse:"a conversation has already accumulated the context you want, and you want a new user-driven branch beside it without sending a prompt or inheriting any graph-management responsibility. This copies the conversation and durable context, then waits for the fork\u2019s first real user message to supply its mandate. Use `node new --fork-from` instead when spawning a managed worker with an immediate task",help:{name:"node fork",summary:"create an independent resident root from a node\u2019s conversation and durable context, with no kickoff prompt or model turn",params:[{kind:"flag",name:"node",type:"string",required:!1,constraint:"Source node id. Mutually exclusive with --pane; one of them is required."},{kind:"flag",name:"pane",type:"string",required:!1,constraint:"tmux pane showing the source node. Mutually exclusive with --node; one of them is required. The prefix menu passes this for you and the new viewer splits beside this pane."}],output:[{name:"node_id",type:"string",required:!0,constraint:"The new independent root id."},{name:"focused",type:"boolean",required:!0,constraint:"True when a new viewer pane opened beside the caller; false outside tmux."},{name:"session",type:"string",required:!1,constraint:"The tmux session containing the new viewer, when one opened."}],outputKind:"object",effects:["Creates a resident base-mode root with the source node\u2019s copied pi conversation, cwd, profile, kind, model override, and durable context files. Top-level initial-prompt.md, yield-message.md, result.json, and the jobs/ folder of background bash jobs are omitted.","Copies no parent, subscriptions, subscribers, children, crons, worktree, situational context, or lifecycle responsibility. Sends no prompt and consumes no model turn; the first real user message becomes the fork\u2019s mandate.","Inside tmux, opens and focuses a surface-attach viewer as an even-horizontal split in the source pane\u2019s window. Outside tmux, the root is still created but no interactive fallback opens."]},run:h(async n=>{I("crtr:act","crtr node fork");const e=n.pane,o=n.node;if(o!==void 0&&e!==void 0)throw new k({error:"conflicting_target",message:"--node and --pane are mutually exclusive",next:"Pass the source node id or its viewer pane, not both."});let s=o;if(s===void 0&&e!==void 0&&(s=W(e)),s===void 0||s==="")throw new k({error:"no_node",message:"no source node was provided or found in the pane",next:"Pass --node <id>, or --pane <pane-id> for a pane showing a node."});const p=await _().forkNode(s).catch(w),i=await V(p.node_id,{cwd:p.cwd,name:p.name,...e!==void 0?{pane:e}:{},newPane:!0});return{node_id:p.node_id,focused:i.focused,session:i.session}},"run"),render:h(n=>{const e=n.focused===!0?` Viewer opened beside the source${n.session?` in session ${n.session}`:""}.`:" No viewer opened because no tmux pane was available.";return`Forked independent idle root ${n.node_id}.${e} It will make no model call until its first real user message.`},"render")}),ue=A({name:"inspect",description:"read one node \u2014 its graph position, conversation, and context dir",whenToUse:"reading everything about ONE node you can name: enumerate the roster (`list`), inspect a node and its spine neighbors (`show`), or browse its on-disk context dir (`context`). The documents a node owns are `crtr canvas list --owner <id>`. Use `canvas dashboard` instead to render the whole tree SHAPE, or `canvas attention` to find which nodes are blocked on the user",help:{name:"node inspect",summary:"read one node (or the roster) \u2014 topology, conversation, and context dir",model:"Inspection is read-only and never revives a node. The roster is the selection surface; one-node metadata points to progressively heavier views: a parsed broker snapshot, rendered conversation, or context browser."},children:[K,G,F,C,U]});export{le as nodeFork,ue as nodeInspect};
@@ -1,2 +1,2 @@
1
- var g=Object.defineProperty;var n=(e,r)=>g(e,"name",{value:r,configurable:!0});import{readFileSync as w}from"node:fs";import{resolve as y}from"node:path";import{defineLeaf as p,defineBranch as b}from"../../core/command.js";import{usage as m}from"../../core/errors.js";import{cliClient as u}from"../api-client.js";import{resolveProfileViaDaemon as c}from"./daemon-profiles.js";const d={kind:"flag",name:"profile",type:"string",required:!0,constraint:"Profile id or manifest name; a close-enough name resolves to the nearest profile, reported on stderr."},f=[{name:"profile_id",type:"string",required:!0,constraint:"Stable profile id."},{name:"repositories",type:"string[]",required:!0,constraint:"`owner/name` in checkout order; the first is where nodes start (`/work/<name>`)."},{name:"setup_script",type:"string",required:!1,constraint:"The script the image build runs; null when none."},{name:"pi_packages",type:"string",required:!1,constraint:"pi package sources, one per line; null when none."},{name:"memory_mb",type:"number",required:!0,constraint:"Memory of new sandboxes: 2048, 4096 or 8192."},{name:"allow_pull_request_write",type:"boolean",required:!0,constraint:"Whether sandboxes may merge pull requests: their GitHub credential carries pull_requests write besides contents write."},{name:"recipe_revision",type:"number",required:!0,constraint:"Raised by one each time the recipe changes."},{name:"image_revision",type:"number",required:!1,constraint:"The recipe revision the current image was built from; the image is ready when it equals recipe_revision. Null before the first build."},{name:"image_error",type:"string",required:!1,constraint:"Why the last image build failed; null when it did not."}];function h(e){const{environment_id:r,...t}=e;return t}n(h,"output");const k=p({name:"show",description:"show a cloud profile's recipe, memory and image state",whenToUse:"checking what a dev profile builds and runs in, or whether the image for its latest recipe is ready (`image_revision` equals `recipe_revision`).",help:{name:"profile environment show",summary:"a cloud profile's environment: repositories, setup script, pi packages, memory and image build state",params:[d],output:[...f],outputKind:"object",effects:["Read-only. Refuses a profile that does not run in a cloud environment."]},run:n(async e=>{const{id:r}=await c(e.profile);return h(await u().getProfileEnvironment(r))},"run")}),v=p({name:"set",description:"change a cloud profile's repositories, setup script, pi packages, memory or pull request merging",whenToUse:"a dev profile needs other repositories, a setup script for its image (run as root in the build, working directory `/work`), pi packages, or more memory. A flag left out keeps its value.",help:{name:"profile environment set",summary:"change a cloud profile's environment recipe or memory",params:[d,{kind:"flag",name:"repo",type:"string",required:!1,repeatable:!0,constraint:"GitHub repository `owner/name` (repeat per repository); replaces the whole list. The GitHub App must be installed on each."},{kind:"flag",name:"setup-script-file",type:"path",required:!1,constraint:"File holding the setup script the image build runs as root."},{kind:"flag",name:"pi-package",type:"string",required:!1,repeatable:!0,constraint:"pi package source (repeat per package); replaces the whole list."},{kind:"flag",name:"allow-pull-request-write",type:"bool",required:!1,constraint:"Pass it to let the sandboxes merge pull requests (their GitHub credential adds pull_requests write); `--no-allow-pull-request-write` returns to contents write only. Takes effect on the next credential a sandbox fetches; builds no image."},{kind:"flag",name:"memory",type:"int",required:!1,constraint:"Sandbox memory in GB: 2, 4 or 8. Reaches sandboxes created after the change; a running sandbox keeps its memory."}],output:[...f],outputKind:"object",effects:["A changed recipe raises `recipe_revision`, and the daemon builds a new image for it; check `profile environment show`. A recipe identical to the stored one changes nothing."]},run:n(async e=>{const{id:r}=await c(e.profile),t=e.repo,s=e.setupScriptFile,o=e.piPackage,i=e.memory,a=e.allowPullRequestWrite;if(i!==void 0&&![2,4,8].includes(i))throw m("`--memory` is 2, 4 or 8 (GB).");const l={...t!==void 0&&t.length>0?{repositories:t}:{},...s!==void 0?{setup_script:w(y(s),"utf8")}:{},...o!==void 0&&o.length>0?{pi_packages:o.join(`
2
- `)}:{},...i!==void 0?{memory_mb:i*1024}:{},...a!==void 0?{allow_pull_request_write:a}:{}};if(Object.keys(l).length===0)throw m("pass at least one of `--repo`, `--setup-script-file`, `--pi-package`, `--memory`, `--allow-pull-request-write`.");return h(await u().setProfileEnvironment(r,l))},"run")}),A=b({name:"environment",description:"a cloud profile's recipe (repositories, setup script, pi packages) and sandbox memory",whenToUse:"viewing or changing what a cloud dev profile's sandboxes are built from and how much memory they get.",help:{name:"profile environment",summary:"a cloud profile's environment recipe and memory",model:"A cloud profile runs its nodes in Blaxel sandboxes. Its environment holds the recipe the sandbox image is built from; changing the recipe makes the daemon build a new image, and new sandboxes use it. Memory applies to new sandboxes only."},children:[k,v]});export{A as environmentBranch};
1
+ var g=Object.defineProperty;var i=(e,r)=>g(e,"name",{value:r,configurable:!0});import{readFileSync as y}from"node:fs";import{resolve as w}from"node:path";import{defineLeaf as p,defineBranch as b}from"../../core/command.js";import{usage as u}from"../../core/errors.js";import{cliClient as m}from"../api-client.js";import{resolveProfileViaDaemon as c}from"./daemon-profiles.js";const d={kind:"flag",name:"profile",type:"string",required:!0,constraint:"Profile id or manifest name; a close-enough name resolves to the nearest profile, reported on stderr."},f=[{name:"profile_id",type:"string",required:!0,constraint:"Stable profile id."},{name:"repositories",type:"string[]",required:!0,constraint:"`owner/name` in checkout order; the first is where nodes start (`/work/<name>`)."},{name:"setup_script",type:"string",required:!1,constraint:"The script the image build runs; null when none."},{name:"pi_packages",type:"string",required:!1,constraint:"pi package sources, one per line; null when none."},{name:"memory_mb",type:"number",required:!0,constraint:"Memory of new sandboxes: 2048, 4096 or 8192."},{name:"allow_pull_request_write",type:"boolean",required:!0,constraint:"Whether sandboxes may open and merge pull requests: their GitHub credential carries pull_requests write besides contents write. On by default."},{name:"recipe_revision",type:"number",required:!0,constraint:"Raised by one each time the recipe changes."},{name:"image_revision",type:"number",required:!1,constraint:"The recipe revision the current image was built from; the image is ready when it equals recipe_revision. Null before the first build."},{name:"image_error",type:"string",required:!1,constraint:"Why the last image build failed; null when it did not."}];function h(e){const{environment_id:r,...n}=e;return n}i(h,"output");const k=p({name:"show",description:"show a cloud profile's recipe, memory and image state",whenToUse:"checking what a dev profile builds and runs in, or whether the image for its latest recipe is ready (`image_revision` equals `recipe_revision`).",help:{name:"profile environment show",summary:"a cloud profile's environment: repositories, setup script, pi packages, memory and image build state",params:[d],output:[...f],outputKind:"object",effects:["Read-only. Refuses a profile that does not run in a cloud environment."]},run:i(async e=>{const{id:r}=await c(e.profile);return h(await m().getProfileEnvironment(r))},"run")}),q=p({name:"set",description:"change a cloud profile's repositories, setup script, pi packages, memory or pull request merging",whenToUse:"a dev profile needs other repositories, a setup script for its image (run as root in the build, working directory `/work`), pi packages, or more memory. A flag left out keeps its value.",help:{name:"profile environment set",summary:"change a cloud profile's environment recipe or memory",params:[d,{kind:"flag",name:"repo",type:"string",required:!1,repeatable:!0,constraint:"GitHub repository `owner/name` (repeat per repository); replaces the whole list. The GitHub App must be installed on each."},{kind:"flag",name:"setup-script-file",type:"path",required:!1,constraint:"File holding the setup script the image build runs as root."},{kind:"flag",name:"pi-package",type:"string",required:!1,repeatable:!0,constraint:"pi package source (repeat per package); replaces the whole list."},{kind:"flag",name:"allow-pull-request-write",type:"bool",required:!1,constraint:"On by default: sandboxes may open and merge pull requests (their GitHub credential carries pull_requests write). `--no-allow-pull-request-write` drops to contents write only, so sandboxes can push branches but not open pull requests. Takes effect on the next credential a sandbox fetches; builds no image."},{kind:"flag",name:"memory",type:"int",required:!1,constraint:"Sandbox memory in GB: 2, 4 or 8. Reaches sandboxes created after the change; a running sandbox keeps its memory."}],output:[...f],outputKind:"object",effects:["A changed recipe raises `recipe_revision`, and the daemon builds a new image for it; check `profile environment show`. A recipe identical to the stored one changes nothing."]},run:i(async e=>{const{id:r}=await c(e.profile),n=e.repo,s=e.setupScriptFile,o=e.piPackage,t=e.memory,a=e.allowPullRequestWrite;if(t!==void 0&&![2,4,8].includes(t))throw u("`--memory` is 2, 4 or 8 (GB).");const l={...n!==void 0&&n.length>0?{repositories:n}:{},...s!==void 0?{setup_script:y(w(s),"utf8")}:{},...o!==void 0&&o.length>0?{pi_packages:o.join(`
2
+ `)}:{},...t!==void 0?{memory_mb:t*1024}:{},...a!==void 0?{allow_pull_request_write:a}:{}};if(Object.keys(l).length===0)throw u("pass at least one of `--repo`, `--setup-script-file`, `--pi-package`, `--memory`, `--allow-pull-request-write`.");return h(await m().setProfileEnvironment(r,l))},"run")}),A=b({name:"environment",description:"a cloud profile's recipe (repositories, setup script, pi packages) and sandbox memory",whenToUse:"viewing or changing what a cloud dev profile's sandboxes are built from and how much memory they get.",help:{name:"profile environment",summary:"a cloud profile's environment recipe and memory",model:"A cloud profile runs its nodes in Blaxel sandboxes. Its environment holds the recipe the sandbox image is built from; changing the recipe makes the daemon build a new image, and new sandboxes use it. Memory applies to new sandboxes only."},children:[k,q]});export{A as environmentBranch};
@@ -0,0 +1,2 @@
1
+ -- 031-environment-pull-request-write-default.sql — cloud environments open pull requests by default: every existing environment gets `allow_pull_request_write = true` (030 gave them false only as the column default, never as a choice). The column default stays false, because a delta may not change a default old writers rely on; new cloud environments write true explicitly.
2
+ UPDATE environments SET allow_pull_request_write = true;
@@ -0,0 +1,4 @@
1
+ -- 032-model-cooldown-vendor-limit.sql — each cooldown keeps the vendor 429 observation that set it (NL-310): the reset the vendor named,
2
+ -- the window claim, safe rate-limit headers and the model, so a later refusal from a cooling pool still reports them. Added columns only.
3
+ ALTER TABLE model_accounts ADD COLUMN IF NOT EXISTS vendor_limit_json text;
4
+ ALTER TABLE model_account_cooldowns ADD COLUMN IF NOT EXISTS vendor_limit_json text;
@@ -1,7 +1,7 @@
1
1
  /** The canvas schema version this build supports: the number of the highest delta in `schema-pg/` (the baseline
2
2
  * `schema-pg.sql` is version 1). `scripts/install-runtime.mjs` reads this module from a candidate generation to refuse
3
3
  * one below the live database's `schema_min_reader`. */
4
- export declare const CANVAS_SCHEMA_VERSION = 30;
4
+ export declare const CANVAS_SCHEMA_VERSION = 32;
5
5
  /** The Postgres schema holding the canvas tables: `CRTR_DATABASE_SCHEMA` (`crtr` in the cloud deploy). Unset or empty
6
6
  * means the role's own search_path (`public` on a Mac and on a VM). A name that is not a plain identifier is an error:
7
7
  * it is put in a `search_path` connection option. */
@@ -1 +1 @@
1
- var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=30;function _(n=process.env){const e=n.CRTR_DATABASE_SCHEMA?.trim();if(e){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw new Error(`CRTR_DATABASE_SCHEMA must be a plain identifier (letters, digits, underscore); got ${JSON.stringify(e)}`);return e}}r(_,"canvasDatabaseSchema");function h(n=process.env){return n.CRTR_SCHEMA_DATABASE_URL?.trim()||void 0}r(h,"canvasSchemaDatabaseUrl");function E(n=process.env){const e=_(n);return e===void 0?void 0:`-c search_path=${e}`}r(E,"canvasSearchPathOptions");async function v(n,e){const t=e===void 0?"canvas_meta":`"${e.replace(/"/g,'""')}".canvas_meta`;if((await n.query(`SELECT to_regclass('${t.replace(/'/g,"''")}') IS NOT NULL AS found`)).rows[0].found!==!0)return;const u=(await n.query(`SELECT key, value FROM ${t} WHERE key IN ('schema_version', 'schema_min_reader')`)).rows,o=r(c=>{const i=u.find(f=>f.key===c);if(i===void 0)return;const d=Number(i.value);if(!Number.isSafeInteger(d))throw new Error(`canvas_meta.${c} is not an integer: ${String(i.value)}`);return d},"value"),s=o("schema_version");return s===void 0?void 0:{version:s,minReader:o("schema_min_reader")??s}}r(v,"readStoredVersions");async function l(n,e,t){const a=await v(n,t);if(a!==void 0&&a.minReader>e)throw new Error(`refusing to select runtime with canvas schema ${e}: the live database requires readers at version ${a.minReader} or above (it is at ${a.version}); install a descendant build instead`)}r(l,"assertCandidateMayOpen");export{A as CANVAS_SCHEMA_VERSION,l as assertCandidateMayOpen,_ as canvasDatabaseSchema,h as canvasSchemaDatabaseUrl,E as canvasSearchPathOptions,v as readStoredVersions};
1
+ var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=32;function _(n=process.env){const e=n.CRTR_DATABASE_SCHEMA?.trim();if(e){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw new Error(`CRTR_DATABASE_SCHEMA must be a plain identifier (letters, digits, underscore); got ${JSON.stringify(e)}`);return e}}r(_,"canvasDatabaseSchema");function h(n=process.env){return n.CRTR_SCHEMA_DATABASE_URL?.trim()||void 0}r(h,"canvasSchemaDatabaseUrl");function E(n=process.env){const e=_(n);return e===void 0?void 0:`-c search_path=${e}`}r(E,"canvasSearchPathOptions");async function v(n,e){const t=e===void 0?"canvas_meta":`"${e.replace(/"/g,'""')}".canvas_meta`;if((await n.query(`SELECT to_regclass('${t.replace(/'/g,"''")}') IS NOT NULL AS found`)).rows[0].found!==!0)return;const u=(await n.query(`SELECT key, value FROM ${t} WHERE key IN ('schema_version', 'schema_min_reader')`)).rows,o=r(c=>{const i=u.find(f=>f.key===c);if(i===void 0)return;const d=Number(i.value);if(!Number.isSafeInteger(d))throw new Error(`canvas_meta.${c} is not an integer: ${String(i.value)}`);return d},"value"),s=o("schema_version");return s===void 0?void 0:{version:s,minReader:o("schema_min_reader")??s}}r(v,"readStoredVersions");async function l(n,e,t){const a=await v(n,t);if(a!==void 0&&a.minReader>e)throw new Error(`refusing to select runtime with canvas schema ${e}: the live database requires readers at version ${a.minReader} or above (it is at ${a.version}); install a descendant build instead`)}r(l,"assertCandidateMayOpen");export{A as CANVAS_SCHEMA_VERSION,l as assertCandidateMayOpen,_ as canvasDatabaseSchema,h as canvasSchemaDatabaseUrl,E as canvasSearchPathOptions,v as readStoredVersions};
@@ -1 +1 @@
1
- var f=Object.defineProperty;var a=(e,n)=>f(e,"name",{value:n,configurable:!0});import{openDb as l,withCanvasWrite as c}from"./canvas/db.js";import{createObject as p,ensureOwner as u,ownerForGrantee as w}from"./graph/objects.js";import{writeActsFor as s}from"./permissions/facts.js";import{isCloudRole as v,personIdAsync as E}from"./canvas/person.js";import{writeEnvironmentRecipe as h}from"./environment-recipe.js";import{setCloudProfileWriter as I}from"./profiles/manifest.js";let o=null;async function O(e){const n=new Date().toISOString(),t=await c(async i=>{const r=await i.prepare("SELECT object FROM environments WHERE machine_id = ?").get(e);if(r!==void 0)return await i.prepare("UPDATE environments SET last_seen_at = ? WHERE machine_id = ?").run(n,e),{environmentId:r.object,created:!1};const d=await w(i,"app:terminal"),m=await p(i,{type:"environment",kind:"machine",owner:d.id,privacy:"public",name:e,preview:"machine"});return v()||await s(i,m.id,await E()),await i.prepare("INSERT INTO environments (object, kind, machine_id, last_seen_at) VALUES (?, 'machine', ?, ?)").run(m.id,e,n),{environmentId:m.id,created:!0}});return o={environmentId:t.environmentId,machineId:e},t}a(O,"registerMachineEnvironment");async function _(e,n){const t=await w(e,n.grantee),i=await u(e,"profile","profile",n.profileId,n.profileId,t),r=await p(e,{type:"environment",kind:"blaxel",owner:i.id,privacy:"private",name:n.profileId,preview:"blaxel"});return await s(e,r.id,n.person),await e.prepare("INSERT INTO environments (object, kind, machine_id, memory_mb, last_seen_at) VALUES (?, 'blaxel', NULL, ?, ?)").run(r.id,n.memoryMb??2048,new Date().toISOString()),n.recipe!==void 0&&await h(e,r.id,n.recipe),r.id}a(_,"createProfileBlaxelEnvironment");async function A(e){o!==null&&await(await l()).prepare("UPDATE environments SET last_seen_at = ? WHERE machine_id = ?").run(e,o.machineId)}a(A,"touchMachineEnvironment");function D(){if(o===null)throw new Error("the machine environment is not registered yet");return o.environmentId}a(D,"machineEnvironmentId"),I((e,n)=>c(async t=>{await n(await _(t,e))}));export{_ as createProfileBlaxelEnvironment,D as machineEnvironmentId,O as registerMachineEnvironment,A as touchMachineEnvironment};
1
+ var u=Object.defineProperty;var a=(e,n)=>u(e,"name",{value:n,configurable:!0});import{openDb as d,withCanvasWrite as c}from"./canvas/db.js";import{createObject as p,ensureOwner as f,ownerForGrantee as w}from"./graph/objects.js";import{writeActsFor as s}from"./permissions/facts.js";import{isCloudRole as v,personIdAsync as E}from"./canvas/person.js";import{writeEnvironmentRecipe as h}from"./environment-recipe.js";import{setCloudProfileWriter as _}from"./profiles/manifest.js";let o=null;async function O(e){const n=new Date().toISOString(),t=await c(async r=>{const i=await r.prepare("SELECT object FROM environments WHERE machine_id = ?").get(e);if(i!==void 0)return await r.prepare("UPDATE environments SET last_seen_at = ? WHERE machine_id = ?").run(n,e),{environmentId:i.object,created:!1};const l=await w(r,"app:terminal"),m=await p(r,{type:"environment",kind:"machine",owner:l.id,privacy:"public",name:e,preview:"machine"});return v()||await s(r,m.id,await E()),await r.prepare("INSERT INTO environments (object, kind, machine_id, last_seen_at) VALUES (?, 'machine', ?, ?)").run(m.id,e,n),{environmentId:m.id,created:!0}});return o={environmentId:t.environmentId,machineId:e},t}a(O,"registerMachineEnvironment");async function I(e,n){const t=await w(e,n.grantee),r=await f(e,"profile","profile",n.profileId,n.profileId,t),i=await p(e,{type:"environment",kind:"blaxel",owner:r.id,privacy:"private",name:n.profileId,preview:"blaxel"});return await s(e,i.id,n.person),await e.prepare("INSERT INTO environments (object, kind, machine_id, memory_mb, allow_pull_request_write, last_seen_at) VALUES (?, 'blaxel', NULL, ?, true, ?)").run(i.id,n.memoryMb??2048,new Date().toISOString()),n.recipe!==void 0&&await h(e,i.id,n.recipe),i.id}a(I,"createProfileBlaxelEnvironment");async function A(e){o!==null&&await(await d()).prepare("UPDATE environments SET last_seen_at = ? WHERE machine_id = ?").run(e,o.machineId)}a(A,"touchMachineEnvironment");function D(){if(o===null)throw new Error("the machine environment is not registered yet");return o.environmentId}a(D,"machineEnvironmentId"),_((e,n)=>c(async t=>{await n(await I(t,e))}));export{I as createProfileBlaxelEnvironment,D as machineEnvironmentId,O as registerMachineEnvironment,A as touchMachineEnvironment};
@@ -1,3 +1,3 @@
1
1
  var W=Object.defineProperty;var s=(o,e)=>W(o,"name",{value:e,configurable:!0});import{coveredByAny as _,isSandboxedNode as $}from"../../shared/env.js";import{projectPaths as D}from"../../api/dto/profiles.js";import{existsSync as N}from"node:fs";import{CrtrError as B}from"../errors.js";import{getCachedProfile as v}from"../scoped-state/person-store.js";import{parseScope as C}from"@north-light/identity";import{activeGrant as x,grantFor as A,runtimeScope as J}from"../grants/mirror.js";import{withCanvasWrite as P}from"../canvas/db.js";import{ApiError as k}from"../../api/errors.js";import{pluginAppToken as G}from"../secrets.js";import{loadExactProfileManifest as q}from"../profiles/manifest.js";import{ensureOwner as L,getById as U,nodeObject as Y,ownerForGrantee as z,profileHandle as K}from"./objects.js";import{personId as Q,personIdAsync as V}from"../canvas/person.js";import{OBJECT_TYPE as X}from"../permissions/builtin.js";import{warmCheckoutDirs as M}from"../checkout-identities.js";import{fillProfileProjectRepo as Z}from"../profiles/manifest.js";import{emitEvent as I}from"../events/emit.js";import{isCloudRole as R}from"../canvas/person-state.js";import{loadReadAccess as ee,readableAmong as oe,prefetchRepoReads as te,reposForCwd as ne,warmCheckoutIdentities as b}from"./repo-sync/repos.js";async function T(o,e,t,r,n,a){const l=t===null?[]:n.projects(t),p=l.length===0?void 0:a??await V(),c=p===void 0?void 0:await ee(o,p);c!==void 0&&p!==void 0&&await te(o,p,[e,...l.flatMap(i=>i.path!==void 0&&(R()||N(i.path))?[i.path]:[])],c);const d=l.flatMap(i=>i.repo===void 0?[]:[i.repo]),f=p===void 0?new Set:await oe(o,p,d,c),g=await r(e,a,c),w=new Set(g.map(i=>i.repo.id)),E=[],m=[];for(const i of l){if(i.repo!==void 0&&!w.has(i.repo)){const u=await n.object(i.repo);u!==null&&u.type==="repo"&&u.deleted_at===null&&f.has(u.id)&&(w.add(u.id),E.push(u))}if(i.path===void 0||!R()&&!N(i.path))continue;let y;try{y=await r(i.path,a,c)}catch(u){if(u instanceof B&&u.code==="git-lookup-failed")continue;throw u}for(const u of y)w.has(u.repo.id)||(w.add(u.repo.id),E.push(u.repo),m.push(u))}return{repos:g.map(i=>i.repo),checkouts:g,projectRepos:E,projectCheckouts:m}}s(T,"viewRepos");async function Ce(o,e){const t=await o.prepare("SELECT cwd, profile_id FROM nodes WHERE node_id = ?").get(e);if(t===void 0)return;const r=t.profile_id?D(j(o).projects(t.profile_id)):[];if(R()){await re(t.profile_id,[t.cwd,...r]);return}await b(t.cwd);for(const n of r)N(n)&&await b(n)}s(Ce,"warmNodeRepos");async function re(o,e){if(await M(o,e),o!==null){for(const t of v(o)?.manifest.projects??[])if(!(t.path===void 0||t.repo!==void 0))try{const r=(await P(async n=>await ne(n,t.path)))[0];r!==void 0&&await Z(o,t.path,r.id)}catch(r){I({level:"warn",event:"repo.identify.fill_failed",error:r,fields:{profile:o,path:t.path}})}}}s(re,"warmCloudNodeCheckouts");async function xe(o,e,t){if(!R()){for(const n of t)await b(n);return}const r=e===void 0?void 0:await o.prepare("SELECT profile_id FROM nodes WHERE node_id = ?").get(e);await M(r?.profile_id,t)}s(xe,"warmNodeDirs");async function Ae(o,e,t){if(e.class==="anonymous")throw new Error("a publish token cannot read as a principal");if(e.class==="person")return{class:"person",person:await F(o)};if(e.class==="app")return{class:"app",app:await S(o,e.app),scopes:e.scopes,...e.sub===void 0?{}:{sub:e.sub}};if(e.class==="machine"||e.class==="import")throw new Error(`a ${e.class} token cannot read as a principal`);if(e.class==="forwarded"){if(e.actor.kind==="person")return{class:"person",person:await F(o)};const p=await A(e.actor.app,e.sub);if(!p)throw new k(403,"app_not_granted",`${e.actor.app} holds no active grant for ${e.sub} on this machine`);const c=e.actor.node_scopes;return{class:"app",app:await S(o,e.actor.app),place:e.actor.place,launched:c,scopes:c===null?p.resolved:c.filter(d=>_(p.resolved,d))}}if(e.class==="cron"){const p=e.grant?(await x(e.grant))?.resolved??[]:[],c=e.scopes;return{class:"app",app:await S(o,e.app),scopes:c===null?p:c.filter(d=>_(p,d)),launched:c,place:{run:e.origin_run??"",isolated:e.isolated}}}const r=j(o),n=await Y(o,e.node),a=await o.prepare("SELECT cwd, profile_id, app FROM nodes WHERE node_id = ?").get(e.node),l=a.app===null?null:await r.object(a.app);if(!l)throw new Error(`node ${e.node} has no app`);return{class:"node",node:n,app:l,scopes:await H(e.app,e.sub,e.grant,e.scopes,r),launched:e.scopes,cwd:a.cwd,...await T(o,a.cwd,a.profile_id,t,r,e.sub||void 0),profile:a.profile_id===null?null:await r.profile(a.profile_id,l)}}s(Ae,"readerFor");async function ae(o,e,t,r=j(o),n=!1){const a=await o.prepare("SELECT o.* FROM objects o WHERE o.id = ? AND o.type = 'node'").get(e),l=await o.prepare(`SELECT (SELECT external_id FROM identities WHERE object = nodes.app) AS grantee,
2
- sub, grant_id, scopes_json, cwd, profile_id, app FROM nodes WHERE node_id = ?`).get(e);if(!a||!l)throw new Error(`no node ${e}`);const{grantee:p,sub:c,grant_id:d,scopes_json:f,cwd:g,profile_id:w,app:E}=l,m=E===null?null:await r.object(E);if(!m)throw new Error(`node ${e} has no app`);const i=f===null?null:JSON.parse(f);return{class:"node",node:a,app:m,scopes:await H(p,c??"",d,i,r,n),launched:i,cwd:g,...await T(o,g,w,t,r,c||void 0),profile:w===null?null:await r.profile(w,m)}}s(ae,"readerForNode");class se extends Error{static{s(this,"NoOwningAppError")}constructor(){super("no terminal app or person object"),this.name="NoOwningAppError"}}async function Le(o,e,t=async()=>[],r=j(o)){const n=await o.prepare("SELECT envelope_json FROM peer_stubs WHERE object = ?").get(e.id);if(n!==void 0)return await pe(o,e,n.envelope_json===null?null:JSON.parse(n.envelope_json),r);if(e.type==="node")return await ae(o,e.id,t,r,!0);const a=e.owner===null?null:await r.object(e.owner);if(!a)throw new Error(`watcher ${e.id} has no owner`);const p=(a.type==="app"?a:a.type==="profile"&&a.owner!==null?await r.object(a.owner):null)??await o.prepare("SELECT o.* FROM identities i JOIN objects o ON o.id = i.object WHERE i.external_id = 'app:terminal' AND i.scheme = 'app'").get()??await o.prepare("SELECT * FROM objects WHERE type = 'person' AND name = 'user' AND home_machine IS NULL").get();if(!p)throw new se;const c=(await o.prepare("SELECT external_id FROM identities WHERE object = ? AND scheme = 'app'").get(p.id))?.external_id??"app:terminal",d=J(),f=await o.prepare(`SELECT sub, resolved_scopes_json FROM grants WHERE grantee = ? AND status = 'active'${d.sql}`).all(c,...d.args),g=s(h=>JSON.parse(h.resolved_scopes_json).filter(O=>O.mode==="always").map(O=>C(O.scope)),"always"),w=f.length>1&&a.type==="app"?new Set((await o.prepare("SELECT subject_id FROM relations WHERE resource_type = ? AND resource_id = ? AND relation = 'acts_for' AND subject_type = 'user'").all(X,e.id)).map(h=>h.subject_id)):null,E=w===null?void 0:f.find(h=>w.has(h.sub.replace(/^user:/,"")))?.sub,m=E===void 0?null:await r.grantFor(c,E),i=a.type==="person"?null:f.length===0?r.pluginScopes(c):f.length===1?g(f[0]):m?.resolved??null,u=(a.type==="person"?(await o.prepare("SELECT external_id FROM identities WHERE object = ? AND scheme = 'user'").get(a.id))?.external_id:void 0)??(f.length===1?f[0].sub:m?.sub);return{class:"object",object:e,node:e,owner:a,app:p,scopes:i,...u===void 0?{}:{sub:u},repos:a.type==="repo"?[a]:[]}}s(Le,"readerForObject");async function Me(o,e,t){const r=(await o.prepare("SELECT external_id FROM identities WHERE object = ? AND scheme = 'app'").get(e.id))?.external_id;if(r===void 0)return null;const n=await o.prepare("SELECT resolved_scopes_json FROM grants WHERE grantee = ? AND status = 'active'").all(r);return n.length===0?t.pluginScopes(r):n.length>1?null:JSON.parse(n[0].resolved_scopes_json).filter(a=>a.mode==="always").map(a=>C(a.scope))}s(Me,"appScopesNow");async function pe(o,e,t,r){const n=await F(o);if(t!==null&&t.app===null)return{class:"object",object:e,node:e,owner:n,app:n,scopes:null,repos:[]};const a=t?.app==null?null:await S(o,t.app),l=t?.app==null?null:await r.grantFor(t.app,t.sub),p=t===null||l===null?null:t.node_scopes===null?l.resolved:t.node_scopes.filter(d=>_(l.resolved,d)),c=a??(e.owner===null?n:await r.object(e.owner)??n);return{class:"object",object:e,node:e,owner:c,app:c,scopes:p,launched:t?.node_scopes??null,repos:[],...t?.place==null?{}:{place:t.place}}}s(pe,"readerForStub");function j(o){return{grantById:x,grantFor:A,pluginScopes:s(e=>G(e.replace(/^app:/,""))?.scopes??null,"pluginScopes"),object:s(async e=>await U(o,e),"object"),profile:s(async(e,t)=>await ce(o,e,t),"profile"),projects:s(e=>$()?[]:v(e)?.manifest.projects??[],"projects")}}s(j,"liveLookups");function Te(o){const e=j(o),t=new Map,r=s((n,a)=>(t.has(n)||t.set(n,a()),t.get(n)),"memo");return{grantById:s(n=>r(`g\0${n}`,()=>e.grantById(n)),"grantById"),grantFor:s((n,a)=>r(`a\0${n}\0${a}`,()=>e.grantFor(n,a)),"grantFor"),pluginScopes:s(n=>r(`t\0${n}`,()=>e.pluginScopes(n)),"pluginScopes"),object:s(async n=>await r(`o\0${n}`,async()=>await e.object(n)),"object"),profile:s(async(n,a)=>await r(`p\0${n}\0${a.id}`,async()=>await e.profile(n,a)),"profile"),projects:s(n=>r(`j\0${n}`,()=>e.projects(n)),"projects")}}s(Te,"publishLookups");async function H(o,e,t,r,n,a=!1){const l=t?await n.grantById(t):await n.grantFor(o,e),p=l&&l.grantee===o?l.resolved:null;if(p===null){if(a)return null;throw new Error(`the grant of ${o} is not active`)}return r===null?p:r.filter(c=>_(p,c))}s(H,"nodeScopes");async function F(o){return await z(o,Q())}s(F,"personObject");async function S(o,e){return await L(o,"app","app",e,e.replace(/^app:/,""))}s(S,"appObject");async function ce(o,e,t){return await o.prepare(`SELECT o.* FROM identities i JOIN objects o ON o.id = i.object
2
+ sub, grant_id, scopes_json, cwd, profile_id, app FROM nodes WHERE node_id = ?`).get(e);if(!a||!l)throw new Error(`no node ${e}`);const{grantee:p,sub:c,grant_id:d,scopes_json:f,cwd:g,profile_id:w,app:E}=l,m=E===null?null:await r.object(E);if(!m)throw new Error(`node ${e} has no app`);const i=f===null?null:JSON.parse(f);return{class:"node",node:a,app:m,scopes:await H(p,c??"",d,i,r,n),launched:i,cwd:g,...await T(o,g,w,t,r,c||void 0),profile:w===null?null:await r.profile(w,m)}}s(ae,"readerForNode");class se extends Error{static{s(this,"NoOwningAppError")}constructor(){super("no terminal app or person object"),this.name="NoOwningAppError"}}async function Le(o,e,t=async()=>[],r=j(o)){const n=await o.prepare("SELECT envelope_json FROM peer_stubs WHERE object = ?").get(e.id);if(n!==void 0)return await pe(o,e,n.envelope_json===null?null:JSON.parse(n.envelope_json),r);if(e.type==="node")return await ae(o,e.id,t,r,!0);const a=e.owner===null?null:await r.object(e.owner);if(!a)throw new Error(`watcher ${e.id} has no owner`);const p=(a.type==="app"?a:a.type==="profile"&&a.owner!==null?await r.object(a.owner):null)??await o.prepare("SELECT o.* FROM identities i JOIN objects o ON o.id = i.object WHERE i.external_id = 'app:terminal' AND i.scheme = 'app'").get()??await o.prepare("SELECT * FROM objects WHERE type = 'person' AND name = 'user' AND home_machine IS NULL").get();if(!p)throw new se;const c=(await o.prepare("SELECT external_id FROM identities WHERE object = ? AND scheme = 'app'").get(p.id))?.external_id??"app:terminal",d=J(),f=await o.prepare(`SELECT sub, resolved_scopes_json FROM grants WHERE grantee = ? AND status = 'active'${d.sql}`).all(c,...d.args),g=s(h=>JSON.parse(h.resolved_scopes_json).filter(O=>O.mode==="always").map(O=>C(O.scope)),"always"),w=f.length>1&&(a.type==="app"||a.type==="repo")?new Set((await o.prepare("SELECT subject_id FROM relations WHERE resource_type = ? AND resource_id = ? AND relation = 'acts_for' AND subject_type = 'user'").all(X,a.type==="repo"?a.id:e.id)).map(h=>h.subject_id)):null,E=w===null?void 0:f.find(h=>w.has(h.sub.replace(/^user:/,"")))?.sub,m=E===void 0?null:await r.grantFor(c,E),i=a.type==="person"?null:f.length===0?r.pluginScopes(c):f.length===1?g(f[0]):m?.resolved??null,u=(a.type==="person"?(await o.prepare("SELECT external_id FROM identities WHERE object = ? AND scheme = 'user'").get(a.id))?.external_id:void 0)??(f.length===1?f[0].sub:m?.sub);return{class:"object",object:e,node:e,owner:a,app:p,scopes:i,...u===void 0?{}:{sub:u},repos:a.type==="repo"?[a]:[]}}s(Le,"readerForObject");async function Me(o,e,t){const r=(await o.prepare("SELECT external_id FROM identities WHERE object = ? AND scheme = 'app'").get(e.id))?.external_id;if(r===void 0)return null;const n=await o.prepare("SELECT resolved_scopes_json FROM grants WHERE grantee = ? AND status = 'active'").all(r);return n.length===0?t.pluginScopes(r):n.length>1?null:JSON.parse(n[0].resolved_scopes_json).filter(a=>a.mode==="always").map(a=>C(a.scope))}s(Me,"appScopesNow");async function pe(o,e,t,r){const n=await F(o);if(t!==null&&t.app===null)return{class:"object",object:e,node:e,owner:n,app:n,scopes:null,repos:[]};const a=t?.app==null?null:await S(o,t.app),l=t?.app==null?null:await r.grantFor(t.app,t.sub),p=t===null||l===null?null:t.node_scopes===null?l.resolved:t.node_scopes.filter(d=>_(l.resolved,d)),c=a??(e.owner===null?n:await r.object(e.owner)??n);return{class:"object",object:e,node:e,owner:c,app:c,scopes:p,launched:t?.node_scopes??null,repos:[],...t?.place==null?{}:{place:t.place}}}s(pe,"readerForStub");function j(o){return{grantById:x,grantFor:A,pluginScopes:s(e=>G(e.replace(/^app:/,""))?.scopes??null,"pluginScopes"),object:s(async e=>await U(o,e),"object"),profile:s(async(e,t)=>await ce(o,e,t),"profile"),projects:s(e=>$()?[]:v(e)?.manifest.projects??[],"projects")}}s(j,"liveLookups");function Te(o){const e=j(o),t=new Map,r=s((n,a)=>(t.has(n)||t.set(n,a()),t.get(n)),"memo");return{grantById:s(n=>r(`g\0${n}`,()=>e.grantById(n)),"grantById"),grantFor:s((n,a)=>r(`a\0${n}\0${a}`,()=>e.grantFor(n,a)),"grantFor"),pluginScopes:s(n=>r(`t\0${n}`,()=>e.pluginScopes(n)),"pluginScopes"),object:s(async n=>await r(`o\0${n}`,async()=>await e.object(n)),"object"),profile:s(async(n,a)=>await r(`p\0${n}\0${a.id}`,async()=>await e.profile(n,a)),"profile"),projects:s(n=>r(`j\0${n}`,()=>e.projects(n)),"projects")}}s(Te,"publishLookups");async function H(o,e,t,r,n,a=!1){const l=t?await n.grantById(t):await n.grantFor(o,e),p=l&&l.grantee===o?l.resolved:null;if(p===null){if(a)return null;throw new Error(`the grant of ${o} is not active`)}return r===null?p:r.filter(c=>_(p,c))}s(H,"nodeScopes");async function F(o){return await z(o,Q())}s(F,"personObject");async function S(o,e){return await L(o,"app","app",e,e.replace(/^app:/,""))}s(S,"appObject");async function ce(o,e,t){return await o.prepare(`SELECT o.* FROM identities i JOIN objects o ON o.id = i.object
3
3
  WHERE i.scheme = 'profile' AND i.external_id = ?`).get(e)??await L(o,"profile","profile",e,K(e,q(e).manifest.name),t)}s(ce,"profileObject");export{se as NoOwningAppError,Me as appScopesNow,j as liveLookups,ce as profileObject,Te as publishLookups,Ae as readerFor,ae as readerForNode,Le as readerForObject,T as viewRepos,re as warmCloudNodeCheckouts,xe as warmNodeDirs,Ce as warmNodeRepos};
@@ -0,0 +1 @@
1
+ export declare function openImportGrants(runId: string): Promise<void>;
@@ -0,0 +1 @@
1
+ var a=Object.defineProperty;var s=(o,t)=>a(o,"name",{value:t,configurable:!0});import{directoryIssuer as c}from"../../directory/issuer.js";import{outboundFetch as p}from"../../events/outbound.js";import{mintDirectoryToken as m}from"../../grants/sync.js";import{ImportLaneError as n}from"./stage.js";async function y(o){const t=c();if(t===null)throw new n("open-grants","directory_refused","the directory is not configured, so the person's grants cannot be copied onto the fleet runtime");const i=`${t}/v1/runtime/imports/${encodeURIComponent(o)}/open`;let r;try{const e=await m(t);r=await p("import_open_grants",i,{method:"POST",headers:{Authorization:`Bearer ${e.access_token}`},signal:AbortSignal.timeout(12e4)})}catch(e){throw new n("open-grants","directory_refused",`the directory could not be asked to copy the grants: ${e instanceof Error?e.message:String(e)}`)}if(!r.ok)throw new n("open-grants","directory_refused",`the directory refused to copy the person's grants onto the fleet runtime: ${r.status}`)}s(y,"openImportGrants");export{y as openImportGrants};
@@ -13,10 +13,12 @@ export interface RunOptions {
13
13
  blobs?: BlobStore;
14
14
  /** The control plane's fleet runtime principal, the key of the directory's grants (`CRTR_RUNTIME`). */
15
15
  fleetRuntime?: string | null;
16
+ /** Asks the directory to copy the person's grants onto the fleet runtime; default is the directory's `POST /v1/runtime/imports/:run/open`. */
17
+ openGrants?: (runId: string) => Promise<void>;
16
18
  /** Test hook: called when a step is reached, before it runs. A throw there is that step failing. */
17
19
  atStep?: (step: string) => void | Promise<void>;
18
20
  }
19
- /** How long a loading run waits for the directory to copy the person's grants onto the fleet runtime before it fails `grant_missing` (design-import-fleet-grants G10). */
21
+ /** How long a loading run waits for an unreachable directory to answer for its plugins before it fails `directory_unavailable`. */
20
22
  export declare const GRANT_WAIT_MS: number;
21
23
  /** How far the copy transaction moves the run's lease ahead: renewals cannot land while it holds the row. Copy is bounded by the pause budget of 10 minutes. */
22
24
  export declare const COPY_LEASE_MS: number;
@@ -1,3 +1,3 @@
1
- var X=Object.defineProperty;var m=(e,s)=>X(e,"name",{value:s,configurable:!0});import{zstdCompressSync as Z}from"node:zlib";import{blobStore as x}from"../../blobs/index.js";import{openDb as v,withCanvasWrite as M}from"../../canvas/db.js";import{runAsPerson as ee}from"../../canvas/person.js";import{insertImportedRevisions as te}from"../../graph/documents.js";import{getById as ae}from"../../graph/objects.js";import{bundleKeys as N,decodeRows as ne,rowKeys as L,SEQ_TABLES as ie}from"../bundle/layout.js";import{readCatalog as se}from"./catalog.js";import{copyRows as re,decodeKeys as B,encodeKeys as W}from"./copy.js";import{pruneStaged as oe,precheck as de,renameClashingLegacyCharges as pe,renameClashingProfiles as ue,rewriteConversationHeaders as ce,rewritePaths as le,rewriteRequestPaths as fe,takeRepoSyncedDocuments as me}from"./prepare.js";import{boundSub as _e,dropRefusedMessages as we,checkSourcePerson as ge,checkStagedBlobKeys as be,checkStagedPersons as he,checkStagedReferences as ye,checkStagedRequestKeys as Ee}from"./bind.js";import{deleteBlobs as Se,deleteRunBlobs as ve,deleteRunPrefix as Re,moveRunBlobs as Oe}from"./blobs.js";import{dropStubRows as Ie,findFleetGrant as Pe,grantMissing as Te,mapProfileIds as je,renameClashingRepos as ke,rewriteIds as De,rewritePerson as Ce,scopeRepoIdentities as Ae}from"./rewrite.js";import{dropStaging as H,ImportLaneError as g,stage as Me,stagingSchema as Ne,targetSchema as Le}from"./stage.js";import{verifyRun as Be}from"./verify.js";import{sandboxPathMap as We,writeNodeFiles as He}from"./path-map.js";import{allStoreKeys as Ke,readPluginsStore as Ue,recordImportedActivations as Fe,writeStores as Je}from"./stores.js";import{publishImportedPlugins as qe}from"./publish-plugins.js";import{COPIED_TABLES as $e}from"../bundle/layout.js";import{emitEvent as Ge}from"../../events/emit.js";import{ClaimLostError as Ye}from"../../../daemon/reconcilers/row-claim.js";const K=10*6e4,ze=30*6e4,R=m(()=>new Date().toISOString(),"now"),O=m(async(e,s)=>{await(await v()).prepare("UPDATE import_runs SET step = ? WHERE run_id = ?").run(s,e)},"setStep");async function Qe(e,s){const t=await e.get(N.source(s));if(t===null)throw new g("stage","bundle_invalid","source.json is missing");const a=JSON.parse(t.toString("utf8"));if(typeof a.rowParts!="object"||a.rowParts===null)throw new g("stage","bundle_invalid","source.json names no row parts");return a}m(Qe,"readSource");async function Ve(e,s,t,a,n,p){const o=[];for(const l of L(t.run_id,"grants",a)){const f=await e.get(l);if(f===null)throw new g("stage","bundle_invalid",`row file ${l} is missing`);o.push(...ne(f))}const d=[];for(const l of o){const f=_e(l.sub,a.person,t.person,"grants.sub");await Pe(s,n,p,f,l.grantee)===void 0&&d.push(l.grantee)}if(d.length===0)return!0;if(t.loaded_at===void 0||t.loaded_at===null)throw new g("stage","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(t.loaded_at)>=K)throw Te(d);return!1}m(Ve,"grantsReady");async function vt(e,s,t={}){const a=t.blobs??await x(),n=await v(),p=Ne(e.run_id);let o="start";const d=m(async i=>{o=i,await s.assertOwned(),await O(e.run_id,i),await t.atStep?.(i)},"at");let l=e.state==="committed";const f=[];try{const i=await Qe(a,e.run_id);if(e.source_kind==="machine"&&i.installId!==e.source_install_id)throw new g("stage","bundle_invalid",`source.json names install ${i.installId}, the run is for ${e.source_install_id}`);i.installId=e.source_install_id;const c=await Le(n),I=[...$e],b=await se(n,c,[...I,"grants"]);if(!l){const _={},T=[],j=[],k=t.fleetRuntime??process.env.CRTR_RUNTIME??null;if(await ge(n,c,i.person,e.person),!await Ve(a,n,e,i,c,k)){await s.assertOwned(),await O(e.run_id,"waiting_for_grants");return}await d("publish-plugins");const F=await Ue(a,e.run_id),E=await ee(e.person,()=>qe(F));if(E.unavailable.length>0){if(e.loaded_at===void 0||e.loaded_at===null)throw new g("publish-plugins","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(e.loaded_at)>=K)throw new g("publish-plugins","directory_unavailable",`the directory did not answer for: ${E.unavailable.slice(0,10).join(", ")}; rerun the import once it is reachable`,{plugins:E.unavailable});await s.assertOwned(),await O(e.run_id,"waiting_for_directory");return}j.push(...E.refused),await d("stage");const J=await Me(n,e.run_id,i.counts,r=>L(e.run_id,r,i),r=>a.get(r));for(const[r,u]of Object.entries(J))_[r]={staged:u,inserted:0,mapped:0,dropped:0};const w={db:n,schema:p,target:c,catalog:b,sourcePerson:i.person,targetPerson:e.person,fleetRuntime:k,shippedBodies:i.shippedBodies??{}};await d("bind-staged");for(const[r,u]of Object.entries(await he(w)))h(_,r,u);for(const[r,u]of Object.entries(await be(w)))h(_,r,u);await d("rewrite-person"),await Ce(w),await Ae(w),await d("prune");const q=await oe(n,p,b,i),S=i.kind==="hosted"?We(i.pathPrefixes??[]):[];await d("rewrite-paths"),await le(n,p,S),await ce(n,p,S,a,e.run_id),await fe(n,p),await Ee(w);const $=await je(w);await ue(n,p,c,i.installId,e.person),await d("rewrite-ids");const D=await De(w,$);await d("drop");const G=await me(n,p,c),Y=await Ie(w);for(const[r,u]of Object.entries({...q}))h(_,r,u);for(const[r,u]of Object.entries(Y))h(_,r,u);for(const[r,u]of Object.entries(await we(w,{installId:i.installId,person:e.person,runId:e.run_id})))h(_,r,u);await ye(w,{installId:i.installId,person:e.person,runId:e.run_id}),await ke(w),await pe(n,p,c,i.installId),await d("pre-check");const z=new Map([["messages",["seq"]],...ie.map(r=>[r,["seq"]])]);await de(n,p,c,b,I,new Set,z),await d("blobs"),await Oe(n,p,c,e.person,a,e.run_id,f),await d("copy"),await M(async r=>{await s.assertOwned({extendLeaseMs:ze});const u=await re({db:r,runId:e.run_id,schema:p,target:c,catalog:b,source:i,person:e.person,idMap:D,pathMap:S}),C=await xe(r,e.run_id,G);C>0&&(u.inserted.revisions=(u.inserted.revisions??0)+C),await He(r,p,e.run_id,i);const A=await Je({db:r,blobs:a,runId:e.run_id,person:e.person,objectMap:D.object});for(const[Q,V]of Object.entries(A.inserted))u.inserted[Q]=V.length;return T.push(...A.unresolvedPlugins),await r.prepare("UPDATE import_runs SET counts_json = ?, loaded_at = COALESCE(loaded_at, ?) WHERE run_id = ?").run(JSON.stringify({...Ze(_,u),unresolved_plugins:T,refused_plugins:j}),R(),e.run_id),u}),l=!0,await t.atStep?.("committed")}await d("verify");const y=await Be(n,e.run_id,p,c,b,i.installId);if(await n.prepare("UPDATE import_runs SET verify_json = ? WHERE run_id = ?").run(JSON.stringify(y),e.run_id),!y.ok)throw new g("verify","verify_failed","the committed rows differ from the staged rows or an invariant failed",{differences:y.differences,invariants:y.invariants});await d("manifest");const P=N.manifest(e.run_id);await a.put(P,await et(e.run_id)),await H(n,e.run_id);for(const _ of Ke(e.run_id))await a.delete(_);await ve(a,e.run_id),await M(async _=>{await Fe(_,e.run_id,e.person),await _.prepare("UPDATE import_runs SET state = 'done', step = 'done', manifest_key = ?, finished_at = ? WHERE run_id = ?").run(P,R(),e.run_id)})}catch(i){if(i instanceof Ye)throw i;const c=Xe(i,o);Ge({level:"error",event:"import.run.failed",error:i,fields:{run_id:e.run_id,step:c.step,code:c.code}}),await H(n,e.run_id).catch(()=>{}),l||await Se(a,f,!0),await n.prepare("UPDATE import_runs SET state = 'failed', failure_json = ?, finished_at = ? WHERE run_id = ?").run(JSON.stringify(c),R(),e.run_id),await Re(a,e.run_id,{keepNodeFiles:l,bestEffort:!0})}}m(vt,"processRun");function Xe(e,s){if(e instanceof g)return{step:e.step,code:e.code,message:e.message,...e.detail===void 0?{}:{detail:e.detail}};const t=e.code;return{step:s,code:typeof t=="string"?t:"import_failed",message:e instanceof Error?e.message:String(e)}}m(Xe,"failureOf");function h(e,s,t){(e[s]??={staged:0,inserted:0,mapped:0,dropped:0}).dropped+=t}m(h,"addDropped");function Ze(e,s){for(const[t,a]of Object.entries(s.inserted))(e[t]??={staged:0,inserted:0,mapped:0,dropped:0}).inserted=a;for(const[t,a]of Object.entries(s.mapped))(e[t]??={staged:0,inserted:0,mapped:0,dropped:0}).mapped=a;return e}m(Ze,"withInserted");async function xe(e,s,t){const a=new Set((await e.prepareUncached("SELECT rev_id FROM revisions WHERE rev_id IN (SELECT jsonb_array_elements_text(?::jsonb))").all(JSON.stringify(t.map(o=>o.rev_id)))).map(o=>o.rev_id)),n=t.filter(o=>!a.has(o.rev_id)),p=new Map;for(const o of t)p.set(o.document,[...p.get(o.document)??[],o]);for(const[o,d]of p){const l=await ae(e,o);l!==null&&await te(e,l,d.map(f=>({rev_id:f.rev_id,parents:f.parents,body_hash:f.body_hash,rationale:f.rationale,created_at:f.created_at})))}return await U(e,s,"revisions",n.map(o=>[o.rev_id])),await U(e,s,"revision_parents",n.flatMap(o=>o.parents.map(d=>[o.rev_id,d]))),n.length}m(xe,"arrive");async function U(e,s,t,a){if(a.length===0)return;const n=await e.prepare("SELECT inserted_keys FROM import_manifest WHERE run_id = ? AND table_name = ?").get(s,t);n===void 0?await e.prepare("INSERT INTO import_manifest (run_id, table_name, inserted_keys) VALUES (?, ?, ?)").run(s,t,W(a)):await e.prepare("UPDATE import_manifest SET inserted_keys = ? WHERE run_id = ? AND table_name = ?").run(W([...B(n.inserted_keys),...a]),s,t)}m(U,"appendManifest");async function et(e){const t=await(await v()).prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ? ORDER BY table_name").all(e);return Z(Buffer.from(t.map(a=>JSON.stringify({table:a.table_name,keys:B(a.inserted_keys)})).join(`
1
+ var V=Object.defineProperty;var l=(e,s)=>V(e,"name",{value:s,configurable:!0});import{zstdCompressSync as X}from"node:zlib";import{blobStore as Z}from"../../blobs/index.js";import{openDb as v,withCanvasWrite as D}from"../../canvas/db.js";import{runAsPerson as x}from"../../canvas/person.js";import{insertImportedRevisions as ee}from"../../graph/documents.js";import{getById as te}from"../../graph/objects.js";import{bundleKeys as M,decodeRows as ne,rowKeys as N,SEQ_TABLES as ae}from"../bundle/layout.js";import{readCatalog as ie}from"./catalog.js";import{copyRows as se,decodeKeys as L,encodeKeys as B}from"./copy.js";import{pruneStaged as re,precheck as oe,renameClashingLegacyCharges as de,renameClashingProfiles as pe,rewriteConversationHeaders as ue,rewritePaths as ce,rewriteRequestPaths as le,takeRepoSyncedDocuments as fe}from"./prepare.js";import{boundSub as me,dropRefusedMessages as _e,checkSourcePerson as we,checkStagedBlobKeys as ge,checkStagedPersons as be,checkStagedReferences as he,checkStagedRequestKeys as ye}from"./bind.js";import{deleteBlobs as Ee,deleteRunBlobs as Se,deleteRunPrefix as ve,moveRunBlobs as Re}from"./blobs.js";import{dropStubRows as Ie,findFleetGrant as Oe,grantMissing as Pe,mapProfileIds as Te,renameClashingRepos as je,rewriteIds as ke,rewritePerson as Ce,scopeRepoIdentities as Ae}from"./rewrite.js";import{dropStaging as W,ImportLaneError as g,stage as De,stagingSchema as Me,targetSchema as Ne}from"./stage.js";import{verifyRun as Le}from"./verify.js";import{sandboxPathMap as Be,writeNodeFiles as We}from"./path-map.js";import{allStoreKeys as He,readPluginsStore as Ke,recordImportedActivations as Ue,writeStores as Fe}from"./stores.js";import{openImportGrants as Je}from"./open-grants.js";import{publishImportedPlugins as Ge}from"./publish-plugins.js";import{COPIED_TABLES as qe}from"../bundle/layout.js";import{emitEvent as $e}from"../../events/emit.js";import{ClaimLostError as Ye}from"../../../daemon/reconcilers/row-claim.js";const ze=10*6e4,Qe=30*6e4,R=l(()=>new Date().toISOString(),"now"),H=l(async(e,s)=>{await(await v()).prepare("UPDATE import_runs SET step = ? WHERE run_id = ?").run(s,e)},"setStep");async function Ve(e,s){const a=await e.get(M.source(s));if(a===null)throw new g("stage","bundle_invalid","source.json is missing");const n=JSON.parse(a.toString("utf8"));if(typeof n.rowParts!="object"||n.rowParts===null)throw new g("stage","bundle_invalid","source.json names no row parts");return n}l(Ve,"readSource");async function Xe(e,s,a,n,i,p,d){const o=[];for(const t of N(a.run_id,"grants",n)){const u=await e.get(t);if(u===null)throw new g("stage","bundle_invalid",`row file ${t} is missing`);o.push(...ne(u))}if(o.length===0)return;const w=o.map(t=>({sub:me(t.sub,n.person,a.person,"grants.sub"),grantee:t.grantee}));await d(a.run_id);const f=[];for(const t of w)await Oe(s,i,p,t.sub,t.grantee)===void 0&&f.push(t.grantee);if(f.length>0)throw Pe(f)}l(Xe,"ensureGrants");async function It(e,s,a={}){const n=a.blobs??await Z(),i=await v(),p=Me(e.run_id);let d="start";const o=l(async t=>{d=t,await s.assertOwned(),await H(e.run_id,t),await a.atStep?.(t)},"at");let w=e.state==="committed";const f=[];try{const t=await Ve(n,e.run_id);if(e.source_kind==="machine"&&t.installId!==e.source_install_id)throw new g("stage","bundle_invalid",`source.json names install ${t.installId}, the run is for ${e.source_install_id}`);t.installId=e.source_install_id;const u=await Ne(i),I=[...qe],b=await ie(i,u,[...I,"grants"]);if(!w){const m={},P=[],T=[],j=a.fleetRuntime??process.env.CRTR_RUNTIME??null;await we(i,u,t.person,e.person),await o("open-grants"),await Xe(n,i,e,t,u,j,a.openGrants??Je),await o("publish-plugins");const U=await Ke(n,e.run_id),E=await x(e.person,()=>Ge(U));if(E.unavailable.length>0){if(e.loaded_at===void 0||e.loaded_at===null)throw new g("publish-plugins","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(e.loaded_at)>=ze)throw new g("publish-plugins","directory_unavailable",`the directory did not answer for: ${E.unavailable.slice(0,10).join(", ")}; rerun the import once it is reachable`,{plugins:E.unavailable});await s.assertOwned(),await H(e.run_id,"waiting_for_directory");return}T.push(...E.refused),await o("stage");const F=await De(i,e.run_id,t.counts,r=>N(e.run_id,r,t),r=>n.get(r));for(const[r,c]of Object.entries(F))m[r]={staged:c,inserted:0,mapped:0,dropped:0};const _={db:i,schema:p,target:u,catalog:b,sourcePerson:t.person,targetPerson:e.person,fleetRuntime:j,shippedBodies:t.shippedBodies??{}};await o("bind-staged");for(const[r,c]of Object.entries(await be(_)))h(m,r,c);for(const[r,c]of Object.entries(await ge(_)))h(m,r,c);await o("rewrite-person"),await Ce(_),await Ae(_),await o("prune");const J=await re(i,p,b,t),S=t.kind==="hosted"?Be(t.pathPrefixes??[]):[];await o("rewrite-paths"),await ce(i,p,S),await ue(i,p,S,n,e.run_id),await le(i,p),await ye(_);const G=await Te(_);await pe(i,p,u,t.installId,e.person),await o("rewrite-ids");const k=await ke(_,G);await o("drop");const q=await fe(i,p,u),$=await Ie(_);for(const[r,c]of Object.entries({...J}))h(m,r,c);for(const[r,c]of Object.entries($))h(m,r,c);for(const[r,c]of Object.entries(await _e(_,{installId:t.installId,person:e.person,runId:e.run_id})))h(m,r,c);await he(_,{installId:t.installId,person:e.person,runId:e.run_id}),await je(_),await de(i,p,u,t.installId),await o("pre-check");const Y=new Map([["messages",["seq"]],...ae.map(r=>[r,["seq"]])]);await oe(i,p,u,b,I,new Set,Y),await o("blobs"),await Re(i,p,u,e.person,n,e.run_id,f),await o("copy"),await D(async r=>{await s.assertOwned({extendLeaseMs:Qe});const c=await se({db:r,runId:e.run_id,schema:p,target:u,catalog:b,source:t,person:e.person,idMap:k,pathMap:S}),C=await et(r,e.run_id,q);C>0&&(c.inserted.revisions=(c.inserted.revisions??0)+C),await We(r,p,e.run_id,t);const A=await Fe({db:r,blobs:n,runId:e.run_id,person:e.person,objectMap:k.object});for(const[z,Q]of Object.entries(A.inserted))c.inserted[z]=Q.length;return P.push(...A.unresolvedPlugins),await r.prepare("UPDATE import_runs SET counts_json = ?, loaded_at = COALESCE(loaded_at, ?) WHERE run_id = ?").run(JSON.stringify({...xe(m,c),unresolved_plugins:P,refused_plugins:T}),R(),e.run_id),c}),w=!0,await a.atStep?.("committed")}await o("verify");const y=await Le(i,e.run_id,p,u,b,t.installId);if(await i.prepare("UPDATE import_runs SET verify_json = ? WHERE run_id = ?").run(JSON.stringify(y),e.run_id),!y.ok)throw new g("verify","verify_failed","the committed rows differ from the staged rows or an invariant failed",{differences:y.differences,invariants:y.invariants});await o("manifest");const O=M.manifest(e.run_id);await n.put(O,await tt(e.run_id)),await W(i,e.run_id);for(const m of He(e.run_id))await n.delete(m);await Se(n,e.run_id),await D(async m=>{await Ue(m,e.run_id,e.person),await m.prepare("UPDATE import_runs SET state = 'done', step = 'done', manifest_key = ?, finished_at = ? WHERE run_id = ?").run(O,R(),e.run_id)})}catch(t){if(t instanceof Ye)throw t;const u=Ze(t,d);$e({level:"error",event:"import.run.failed",error:t,fields:{run_id:e.run_id,step:u.step,code:u.code}}),await W(i,e.run_id).catch(()=>{}),w||await Ee(n,f,!0),await i.prepare("UPDATE import_runs SET state = 'failed', failure_json = ?, finished_at = ? WHERE run_id = ?").run(JSON.stringify(u),R(),e.run_id),await ve(n,e.run_id,{keepNodeFiles:w,bestEffort:!0})}}l(It,"processRun");function Ze(e,s){if(e instanceof g)return{step:e.step,code:e.code,message:e.message,...e.detail===void 0?{}:{detail:e.detail}};const a=e.code;return{step:s,code:typeof a=="string"?a:"import_failed",message:e instanceof Error?e.message:String(e)}}l(Ze,"failureOf");function h(e,s,a){(e[s]??={staged:0,inserted:0,mapped:0,dropped:0}).dropped+=a}l(h,"addDropped");function xe(e,s){for(const[a,n]of Object.entries(s.inserted))(e[a]??={staged:0,inserted:0,mapped:0,dropped:0}).inserted=n;for(const[a,n]of Object.entries(s.mapped))(e[a]??={staged:0,inserted:0,mapped:0,dropped:0}).mapped=n;return e}l(xe,"withInserted");async function et(e,s,a){const n=new Set((await e.prepareUncached("SELECT rev_id FROM revisions WHERE rev_id IN (SELECT jsonb_array_elements_text(?::jsonb))").all(JSON.stringify(a.map(d=>d.rev_id)))).map(d=>d.rev_id)),i=a.filter(d=>!n.has(d.rev_id)),p=new Map;for(const d of a)p.set(d.document,[...p.get(d.document)??[],d]);for(const[d,o]of p){const w=await te(e,d);w!==null&&await ee(e,w,o.map(f=>({rev_id:f.rev_id,parents:f.parents,body_hash:f.body_hash,rationale:f.rationale,created_at:f.created_at})))}return await K(e,s,"revisions",i.map(d=>[d.rev_id])),await K(e,s,"revision_parents",i.flatMap(d=>d.parents.map(o=>[d.rev_id,o]))),i.length}l(et,"arrive");async function K(e,s,a,n){if(n.length===0)return;const i=await e.prepare("SELECT inserted_keys FROM import_manifest WHERE run_id = ? AND table_name = ?").get(s,a);i===void 0?await e.prepare("INSERT INTO import_manifest (run_id, table_name, inserted_keys) VALUES (?, ?, ?)").run(s,a,B(n)):await e.prepare("UPDATE import_manifest SET inserted_keys = ? WHERE run_id = ? AND table_name = ?").run(B([...L(i.inserted_keys),...n]),s,a)}l(K,"appendManifest");async function tt(e){const a=await(await v()).prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ? ORDER BY table_name").all(e);return X(Buffer.from(a.map(n=>JSON.stringify({table:n.table_name,keys:L(n.inserted_keys)})).join(`
2
2
  `)+`
3
- `))}m(et,"manifestFile");export{ze as COPY_LEASE_MS,K as GRANT_WAIT_MS,vt as processRun};
3
+ `))}l(tt,"manifestFile");export{Qe as COPY_LEASE_MS,ze as GRANT_WAIT_MS,It as processRun};
@@ -1,3 +1,3 @@
1
- var Be=Object.defineProperty;var l=(e,t)=>Be(e,"name",{value:t,configurable:!0});import{randomUUID as Je}from"node:crypto";import{streamSimple as He}from"@earendil-works/pi-ai/compat";import{keyRouteProviders as ze,probeRouteAvailability as Xe}from"../model-routes-pool.js";import{KEY_CREDENTIAL_SOURCE as je,parseModelSpec as Ge}from"../model-routes.js";import{openModelRegistry as Ve}from"../runtime/model-registry.js";import{getProviderLabel as Ye,isInvalidRefreshTokenError as Ze}from"../managed-providers.js";import{MAX_RATE_LIMIT_COOLDOWN_MS as Me,coolingUntilFor as Se,isManagedProvider as N,markSubscriptionRateLimited as Qe,markSubscriptionSuccess as et,readSubscriptionPool as $e,retryAfterMsFromHeaders as _e,retryAfterMsFromError as tt,refreshSubscriptionCredential as nt,subscriptionNeedsSuccessWrite as ot,vendorRateLimit as rt,RefreshBusyError as it,RefreshTimeoutError as at}from"../subscription-state.js";import{describeRateLimitScope as Ce,rateLimitHeaders as st}from"../rate-limit-scope.js";import{RunError as i}from"../runs/operations.js";import{recognizeProviderError as ye}from"../provider-error-recognition.js";import{isSafetyRefusal as dt}from"./refusal.js";import{findRefusal as lt,payerOf as Ee,refusalError as ut,refusedMark as ct,writeCharge as ge}from"../ledger/index.js";import{storedApiKey as Ie}from"../auth-file.js";import{eligibleHostedEndpoint as ft,readHostedEndpoint as Oe}from"../grants/hosted-endpoint.js";import{parseProviderPayment as mt}from"../provider-failure.js";import{personIdAsync as pt}from"../canvas/person.js";import{getNode as Ne}from"../canvas/canvas.js";import{outboundToken as De}from"../providers/mint.js";import{discardFile as Te}from"../providers/token-cache.js";import{ProviderError as ht}from"../providers/errors.js";import{appCandidates as _t}from"./app-rungs.js";import{hostedRoute as yt,matchesFeatures as gt,ownerCandidates as wt}from"./owner-candidates.js";function bt(e){return typeof e=="string"||e===null||Array.isArray(e)&&e.every(t=>t&&typeof t=="object"&&(t.type==="text"&&typeof t.text=="string"||t.type==="image_url"&&typeof t.image_url?.url=="string"&&/^data:image\/(png|jpeg|gif|webp);base64,[A-Za-z0-9+/]+={0,2}$/.test(t.image_url.url)))}l(bt,"validContent");function Fe(e){return Array.isArray(e)?e.map(t=>{if(t.type==="text")return t;const[,o,s]=/^data:(image\/(?:png|jpeg|gif|webp));base64,(.*)$/.exec(t.image_url.url);return{type:"image",mimeType:o,data:s}}):e??""}l(Fe,"imageContent");function vt(e,t){const o=(e instanceof Error?e.message:String(e)).split("; stack=",1)[0],s=ye({message:o}).kind;return s!=="connection"&&s!=="connection-only"?e:new i(503,"upstream_model_unavailable",o.slice(0,500),void 0,{served_model:t})}l(vt,"refreshFailure");async function kt(e,t,o,s,d){if(o.expires>Date.now())return o.access;const M=e.getProvider(t)?.auth.oauth;if(!M)throw new i(503,"upstream_model_unavailable",`no OAuth refresh for ${t}`,void 0,{served_model:s});return(await nt(t,o.label,async(r,h)=>{const g=await M.refresh({type:"oauth",refresh:r,access:"",expires:0,...h?{clientId:h}:{}},d??new AbortController().signal).catch(R=>{throw vt(R,s)}),x=g.clientId;return{refresh:g.refresh,access:g.access,expires:g.expires,...typeof x=="string"&&x?{clientId:x}:{}}}).catch(r=>{throw r instanceof it||r instanceof at?new i(503,"upstream_model_unavailable",r.message,void 0,{served_model:s}):r})).access}l(kt,"freshSubscriptionAccess");function tn(e){if(!e||typeof e!="object"||Array.isArray(e))throw new i(400,"invalid_request","body must be an object");const t=e;if(!Array.isArray(t.messages)||!t.messages.every(o=>o&&typeof o=="object"&&["system","user","assistant","tool"].includes(o.role)&&bt(o.content)))throw new i(400,"invalid_request","messages must be chat messages","messages");if(t.messages.some(o=>["system","assistant"].includes(o.role)&&typeof o.content!="string"&&o.content!==null))throw new i(400,"invalid_request","system and assistant content must be text","messages");if(t.model!==void 0&&typeof t.model!="string")throw new i(400,"invalid_request","model must be a string","model");if(t.model_policy!==void 0&&!["exact","substitute"].includes(t.model_policy))throw new i(400,"invalid_request","invalid model_policy","model_policy");if(t.payer!==void 0&&!["user","app"].includes(t.payer))throw new i(400,"invalid_request","invalid payer","payer");if(t.reasoning_effort!==void 0&&!["minimal","low","medium","high","xhigh","max"].includes(t.reasoning_effort))throw new i(400,"invalid_request","invalid reasoning_effort","reasoning_effort");if(t.stream!==void 0&&typeof t.stream!="boolean")throw new i(400,"invalid_request","stream must be boolean","stream");if(t.tools!==void 0&&(!Array.isArray(t.tools)||!t.tools.every(o=>o?.type==="function"&&typeof o.function?.name=="string"&&o.function.name.length>0&&(o.function.description===void 0||typeof o.function.description=="string")&&(o.function.parameters===void 0||o.function.parameters!==null&&typeof o.function.parameters=="object"&&!Array.isArray(o.function.parameters)&&o.function.parameters.type==="object"))))throw new i(400,"invalid_request","invalid tools","tools");if(t.tool_choice!==void 0&&t.tool_choice!=="auto"&&t.tool_choice!=="none"&&t.tool_choice!=="required"&&(typeof t.tool_choice!="object"||t.tool_choice===null||t.tool_choice.type!=="function"||typeof t.tool_choice.function?.name!="string"))throw new i(400,"invalid_request","invalid tool_choice","tool_choice");if(t.messages.some(o=>o.role==="assistant"&&o.tool_calls!==void 0&&(!Array.isArray(o.tool_calls)||!o.tool_calls.every(s=>s&&typeof s.id=="string"&&typeof s.function?.name=="string"&&typeof s.function.arguments=="string"&&xt(s.function.arguments)))))throw new i(400,"invalid_request","invalid assistant tool_calls","messages");if(t.stop!==void 0&&!(typeof t.stop=="string"||Array.isArray(t.stop)&&t.stop.every(o=>typeof o=="string")))throw new i(400,"invalid_request","invalid stop","stop");if(t.seed!==void 0&&!Number.isSafeInteger(t.seed))throw new i(400,"invalid_request","invalid seed","seed");for(const[o,s]of[["temperature",t.temperature],["top_p",t.top_p],["max_tokens",t.max_tokens]])if(s!==void 0&&(typeof s!="number"||!Number.isFinite(s)||o==="temperature"&&(s<0||s>2)||o==="top_p"&&(s<0||s>1)||o==="max_tokens"&&(!Number.isSafeInteger(s)||s<1)))throw new i(400,"invalid_request",`invalid ${o}`,o);if(t.response_format!==void 0){const o=t.response_format;if(!o||typeof o!="object"||Array.isArray(o)||!["text","json_object","json_schema"].includes(o.type)||o.type==="json_schema"&&(typeof o.json_schema?.name!="string"||!o.json_schema.name||!o.json_schema.schema||typeof o.json_schema.schema!="object"||Array.isArray(o.json_schema.schema)))throw new i(400,"invalid_request","invalid response_format","response_format")}if(t.metadata!==void 0&&Buffer.byteLength(JSON.stringify(t.metadata)??"")>4096)throw new i(400,"invalid_request","metadata exceeds 4 KB","metadata");return t}l(tn,"parseLlmRequest");function xt(e){try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)}catch{return!1}}l(xt,"isJsonObject");function Rt(e){const t=Date.now(),o=e.messages.map(r=>r.role==="system"?{role:"system",content:r.content??"",timestamp:t}:r.role==="tool"?{role:"toolResult",toolCallId:r.tool_call_id??"",toolName:"",content:typeof r.content=="string"||r.content===null?[{type:"text",text:r.content??""}]:Fe(r.content),isError:!1,timestamp:t}:r.role==="assistant"?{role:"assistant",content:[...r.content?[{type:"text",text:r.content}]:[],...(r.tool_calls??[]).map(h=>({type:"toolCall",id:h.id,name:h.function.name,arguments:JSON.parse(h.function.arguments)}))],api:"openai-completions",provider:"openai",model:e.model??"",usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:t}:{role:"user",content:Fe(r.content),timestamp:t}),s=o.findIndex(r=>r.role!=="system"),d=o.slice(0,s<0?o.length:s).map(r=>r.content),M=d.join(`
1
+ var Be=Object.defineProperty;var l=(e,t)=>Be(e,"name",{value:t,configurable:!0});import{randomUUID as Je}from"node:crypto";import{streamSimple as He}from"@earendil-works/pi-ai/compat";import{keyRouteProviders as ze,probeRouteAvailability as Xe}from"../model-routes-pool.js";import{KEY_CREDENTIAL_SOURCE as je,parseModelSpec as Ge}from"../model-routes.js";import{openModelRegistry as Ve}from"../runtime/model-registry.js";import{getProviderLabel as Ye,isInvalidRefreshTokenError as Ze}from"../managed-providers.js";import{MAX_RATE_LIMIT_COOLDOWN_MS as Me,coolingUntilFor as Se,isManagedProvider as N,markSubscriptionRateLimited as Qe,markSubscriptionSuccess as et,readSubscriptionPool as $e,retryAfterMsFromHeaders as ye,retryAfterMsFromError as tt,refreshSubscriptionCredential as nt,subscriptionNeedsSuccessWrite as ot,vendorRateLimit as rt,RefreshBusyError as it,RefreshTimeoutError as at}from"../subscription-state.js";import{describeRateLimitScope as Ce,modelCooldownFamily as st,rateLimitHeaders as dt}from"../rate-limit-scope.js";import{RunError as i}from"../runs/operations.js";import{recognizeProviderError as ge}from"../provider-error-recognition.js";import{isSafetyRefusal as lt}from"./refusal.js";import{findRefusal as ut,payerOf as Ee,refusalError as ct,refusedMark as ft,writeCharge as we}from"../ledger/index.js";import{storedApiKey as Ie}from"../auth-file.js";import{eligibleHostedEndpoint as mt,readHostedEndpoint as Oe}from"../grants/hosted-endpoint.js";import{parseProviderPayment as pt}from"../provider-failure.js";import{personIdAsync as ht}from"../canvas/person.js";import{getNode as De}from"../canvas/canvas.js";import{outboundToken as Ne}from"../providers/mint.js";import{discardFile as Fe}from"../providers/token-cache.js";import{ProviderError as _t}from"../providers/errors.js";import{appCandidates as yt}from"./app-rungs.js";import{hostedRoute as gt,matchesFeatures as wt,ownerCandidates as bt}from"./owner-candidates.js";function vt(e){return typeof e=="string"||e===null||Array.isArray(e)&&e.every(t=>t&&typeof t=="object"&&(t.type==="text"&&typeof t.text=="string"||t.type==="image_url"&&typeof t.image_url?.url=="string"&&/^data:image\/(png|jpeg|gif|webp);base64,[A-Za-z0-9+/]+={0,2}$/.test(t.image_url.url)))}l(vt,"validContent");function Le(e){return Array.isArray(e)?e.map(t=>{if(t.type==="text")return t;const[,o,s]=/^data:(image\/(?:png|jpeg|gif|webp));base64,(.*)$/.exec(t.image_url.url);return{type:"image",mimeType:o,data:s}}):e??""}l(Le,"imageContent");function kt(e,t){const o=(e instanceof Error?e.message:String(e)).split("; stack=",1)[0],s=ge({message:o}).kind;return s!=="connection"&&s!=="connection-only"?e:new i(503,"upstream_model_unavailable",o.slice(0,500),void 0,{served_model:t})}l(kt,"refreshFailure");async function xt(e,t,o,s,d){if(o.expires>Date.now())return o.access;const S=e.getProvider(t)?.auth.oauth;if(!S)throw new i(503,"upstream_model_unavailable",`no OAuth refresh for ${t}`,void 0,{served_model:s});return(await nt(t,o.label,async(r,_)=>{const w=await S.refresh({type:"oauth",refresh:r,access:"",expires:0,..._?{clientId:_}:{}},d??new AbortController().signal).catch(R=>{throw kt(R,s)}),x=w.clientId;return{refresh:w.refresh,access:w.access,expires:w.expires,...typeof x=="string"&&x?{clientId:x}:{}}}).catch(r=>{throw r instanceof it||r instanceof at?new i(503,"upstream_model_unavailable",r.message,void 0,{served_model:s}):r})).access}l(xt,"freshSubscriptionAccess");function nn(e){if(!e||typeof e!="object"||Array.isArray(e))throw new i(400,"invalid_request","body must be an object");const t=e;if(!Array.isArray(t.messages)||!t.messages.every(o=>o&&typeof o=="object"&&["system","user","assistant","tool"].includes(o.role)&&vt(o.content)))throw new i(400,"invalid_request","messages must be chat messages","messages");if(t.messages.some(o=>["system","assistant"].includes(o.role)&&typeof o.content!="string"&&o.content!==null))throw new i(400,"invalid_request","system and assistant content must be text","messages");if(t.model!==void 0&&typeof t.model!="string")throw new i(400,"invalid_request","model must be a string","model");if(t.model_policy!==void 0&&!["exact","substitute"].includes(t.model_policy))throw new i(400,"invalid_request","invalid model_policy","model_policy");if(t.payer!==void 0&&!["user","app"].includes(t.payer))throw new i(400,"invalid_request","invalid payer","payer");if(t.reasoning_effort!==void 0&&!["minimal","low","medium","high","xhigh","max"].includes(t.reasoning_effort))throw new i(400,"invalid_request","invalid reasoning_effort","reasoning_effort");if(t.stream!==void 0&&typeof t.stream!="boolean")throw new i(400,"invalid_request","stream must be boolean","stream");if(t.tools!==void 0&&(!Array.isArray(t.tools)||!t.tools.every(o=>o?.type==="function"&&typeof o.function?.name=="string"&&o.function.name.length>0&&(o.function.description===void 0||typeof o.function.description=="string")&&(o.function.parameters===void 0||o.function.parameters!==null&&typeof o.function.parameters=="object"&&!Array.isArray(o.function.parameters)&&o.function.parameters.type==="object"))))throw new i(400,"invalid_request","invalid tools","tools");if(t.tool_choice!==void 0&&t.tool_choice!=="auto"&&t.tool_choice!=="none"&&t.tool_choice!=="required"&&(typeof t.tool_choice!="object"||t.tool_choice===null||t.tool_choice.type!=="function"||typeof t.tool_choice.function?.name!="string"))throw new i(400,"invalid_request","invalid tool_choice","tool_choice");if(t.messages.some(o=>o.role==="assistant"&&o.tool_calls!==void 0&&(!Array.isArray(o.tool_calls)||!o.tool_calls.every(s=>s&&typeof s.id=="string"&&typeof s.function?.name=="string"&&typeof s.function.arguments=="string"&&Rt(s.function.arguments)))))throw new i(400,"invalid_request","invalid assistant tool_calls","messages");if(t.stop!==void 0&&!(typeof t.stop=="string"||Array.isArray(t.stop)&&t.stop.every(o=>typeof o=="string")))throw new i(400,"invalid_request","invalid stop","stop");if(t.seed!==void 0&&!Number.isSafeInteger(t.seed))throw new i(400,"invalid_request","invalid seed","seed");for(const[o,s]of[["temperature",t.temperature],["top_p",t.top_p],["max_tokens",t.max_tokens]])if(s!==void 0&&(typeof s!="number"||!Number.isFinite(s)||o==="temperature"&&(s<0||s>2)||o==="top_p"&&(s<0||s>1)||o==="max_tokens"&&(!Number.isSafeInteger(s)||s<1)))throw new i(400,"invalid_request",`invalid ${o}`,o);if(t.response_format!==void 0){const o=t.response_format;if(!o||typeof o!="object"||Array.isArray(o)||!["text","json_object","json_schema"].includes(o.type)||o.type==="json_schema"&&(typeof o.json_schema?.name!="string"||!o.json_schema.name||!o.json_schema.schema||typeof o.json_schema.schema!="object"||Array.isArray(o.json_schema.schema)))throw new i(400,"invalid_request","invalid response_format","response_format")}if(t.metadata!==void 0&&Buffer.byteLength(JSON.stringify(t.metadata)??"")>4096)throw new i(400,"invalid_request","metadata exceeds 4 KB","metadata");return t}l(nn,"parseLlmRequest");function Rt(e){try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)}catch{return!1}}l(Rt,"isJsonObject");function qt(e){const t=Date.now(),o=e.messages.map(r=>r.role==="system"?{role:"system",content:r.content??"",timestamp:t}:r.role==="tool"?{role:"toolResult",toolCallId:r.tool_call_id??"",toolName:"",content:typeof r.content=="string"||r.content===null?[{type:"text",text:r.content??""}]:Le(r.content),isError:!1,timestamp:t}:r.role==="assistant"?{role:"assistant",content:[...r.content?[{type:"text",text:r.content}]:[],...(r.tool_calls??[]).map(_=>({type:"toolCall",id:_.id,name:_.function.name,arguments:JSON.parse(_.function.arguments)}))],api:"openai-completions",provider:"openai",model:e.model??"",usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:t}:{role:"user",content:Le(r.content),timestamp:t}),s=o.findIndex(r=>r.role!=="system"),d=o.slice(0,s<0?o.length:s).map(r=>r.content),S=d.join(`
2
2
 
3
- `),U=e.tools?.map(({function:r})=>({name:r.name,description:r.description??"",parameters:r.parameters??{type:"object",properties:{}}}));return{...M?{systemPrompt:M}:{},messages:o.slice(d.length),...U?{tools:U}:{}}}l(Rt,"contextOf");function qt(e){return mt(e?.payment)}l(qt,"paymentOf");function At(e,t){const o=e.find("anthropic",t);if(o)return o;const s=e.getAll().find(d=>d.provider==="anthropic"&&d.api==="anthropic-messages");return s?{...s,id:t,name:t}:void 0}l(At,"hostedModel");function jt(e,t){const{input:o,output:s,cacheRead:d,cacheWrite:M}=e.cost;return o===0&&s===0&&d===0&&M===0?null:Number.isFinite(t)&&t>=0?t:null}l(jt,"usdEquivalent");function Mt(e,t){return e.compat?.allowedFallbackModels?.find(s=>s.provider===e.provider&&s.model===t)}l(Mt,"allowedFallback");function nn(e){return e?{payer:e.payer??"user",sub:e.sub,grantee:e.grantee,inference_endpoint:e.inference_endpoint??null}:void 0}l(nn,"llmCallerOf");function Pe(e){return e instanceof ht?e.code==="server_error"?new i(503,"upstream_model_unavailable",e.message):new i(404,"model_unavailable",e.message):e}l(Pe,"mintFailure");const St=/\bmodel is not supported when using Codex with a ChatGPT account\b/i;function $t(e,t,o){if(!(e!=="openai-codex"||t===void 0||!St.test(t)))return new i(404,"model_unavailable",t,void 0,{served_model:o})}l($t,"codexAccountModelRejection");function Ct(e){return e.get("request-id")??e.get("x-request-id")}l(Ct,"vendorRequestId");async function on(e,t,o,s,d,M,U){const r=M?.payer==="app"?M:void 0;if(e.payer==="app"&&!r)throw new i(403,"payer_not_app","this grant is not app-paid");if(e.payer==="user"&&r)throw new i(400,"invalid_request","this grant is app-paid; payer cannot be user","payer");if(r&&!r.inference_endpoint)throw new i(404,"model_unavailable",`${r.grantee} is app-paid but its grant carries no inference endpoint`);const h=r?.inference_endpoint??void 0,g=d===void 0?null:r?.sub??d.sub??await pt(),x=await Ve();let R;h?(R=_t(h,e.model,e.model_policy==="exact").flatMap((_,w)=>{const S=Ge(_.model);return S?[{routeId:"app",credentialSource:"app",family:"app",strength:_.strength,...S,rank:w}]:[]}),R=R.filter(_=>gt(x,e,_))):R=await wt(x,e,s);const re=!h&&d!==void 0&&g!==null?await ft():null,ie=re===null?void 0:yt(e,R,re),Le=ie?re:null;ie&&(R=[...R,ie]);const Ke=h?new Set:ze(),we=l(async()=>new i(429,"all_routes_exhausted","no available way to pay for this call",void 0,{payment:{reason:"nothing_left",message:"No available way to pay for this call",pay_url:(await Oe())?.payment_setup_url??null,reset_at:null}}),"nothingLeft");if(R.length===0)throw e.model_policy==="exact"?new i(400,"substitution_refused","no eligible model route is configured"):h?new i(404,"model_unavailable","no eligible model route is configured"):await we();const W=`chatcmpl-${Je()}`;let D=1/0,z=1/0,ae,v,se,de;const X=new Set,le=l(async()=>U??(d?.node?(await Ne(d.node))?.caused_by??null:null)??(d?.run?(await Ne(d.run))?.caused_by??null:null),"causeOf");for(const _ of R){const w=_.credentialSource==="hosted";if(!r&&!w&&!(await Xe(_,x)).authenticated){if(_.credentialSource!==je&&N(_.providerId)){const k=await $e(_.providerId);k.length>0&&k.every($=>$.authFailure)&&X.add(_.providerId)}continue}const S=w?At(x,_.modelId):x.find(_.providerId,_.modelId);if(!S)continue;const B=w?Le.base_url:void 0,c=h?{...S,baseUrl:`${h.base_url}/${S.provider}`}:B?{...S,baseUrl:`${B}/anthropic`,compat:{...S.compat,allowedFallbackModels:void 0}}:S,p=_.providerId,G=_.credentialSource===je&&N(p),ue=!r&&!w&&!G&&N(p)?await $e(p):[],J=ue.filter(k=>!k.authFailure),be=J.filter(k=>Se(k,c.id)<=Date.now()),T=G?await Ie(p):Ke.has(p)?void 0:ue.length?await Ie(p):void 0;if(G&&T===void 0)continue;if(ue.length>0&&J.length===0&&T===void 0){N(p)&&X.add(p);continue}if(J.length&&!be.length&&T===void 0){const k=Math.min(...J.map($=>Se($,c.id)));k<D&&(D=k,se=`${c.provider}/${c.id}`);continue}const ve=r||w?[void 0,void 0]:G?["key"]:J.length||T!==void 0?[...be,...T!==void 0?["key"]:[]]:[void 0];let ke=!1;for(const[k,$]of ve.entries()){if(ke&&$!=="key")continue;const b=$==="key"?void 0:$,xe=$==="key",V=Date.now();let Re=b?.access;if(b&&b.expires<=Date.now()&&N(p))try{Re=await kt(x,p,b,`${c.provider}/${c.id}`,t)}catch(n){if(!Ze(n))throw n;ae??=n;continue}const Ue=Rt(e),F=b||r||w||xe?void 0:await x.getApiKeyAndHeaders(c);if(F&&!F.ok)continue;const u=`${c.provider}/${c.id}`,P=e.model??u,q=w?g===null?null:{payer:g,funding:"endpoint"}:r?Ee({call:"model",route:"endpoint",grantee:r.grantee}):g===null?null:Ee({call:"model",route:b?"subscription":"key",sub:g});if(d!==void 0&&q!==null){const n=await lt({scope:"call",payer:q.payer,funding:q.funding,sub:g,grantee:d.grantee,provider:p});if(n!==null){if(await ge({request:d.request??W,kind:"model",what:u,usd:null,payer:q.payer,funding:q.funding,sub:g,grantee:d.grantee,node:d.node??null,run:d.run??null,provider:p,causedBy:await le(),refused:ct(n)}),de??=n,$!=="key"&&ve.includes("key")){ke=!0;continue}break}}let I;if(r&&h)try{I=await De({audience:h.base_url,sub:r.sub,grantee:r.grantee,initiating_app:r.grantee,scope:["crtr:llm"]},{signal:t})}catch(n){throw Pe(n)}if(B)try{I=await De({audience:B,sub:g,grantee:d.grantee,initiating_app:d.grantee,scope:["crtr:llm"]},{signal:t})}catch(n){throw Pe(n)}let L=null,qe=!1,y,H,Y,C=!1,A,Z=null,j=3e4,K;const ce=[],fe=[],Q=[];let a,O;const ee=l((n,f=null)=>({id:W,object:"chat.completion.chunk",created:Math.floor(V/1e3),model:u,served_model:u,requested_model:P,substituted:P!==u&&!/^([^/]+)\/(ultra|strong|medium|light)$/.test(P),choices:[{index:0,delta:n,finish_reason:f}]}),"chunk"),te=l(n=>{ce.push(n),o?.(n)},"emit"),We=He(c,Ue,{apiKey:I?.access_token??Re??(xe?T:void 0)??(F?.ok?F.apiKey:void 0),...F?.ok?{headers:F.headers}:{},signal:t,reasoning:e.reasoning_effort??_.thinkingLevel,...e.temperature!==void 0?{temperature:e.temperature}:{},...e.max_tokens!==void 0?{maxTokens:e.max_tokens}:{},...e.top_p!==void 0?{samplingParams:{top_p:e.top_p}}:{},...e.tool_choice==="none"?{toolChoice:"none"}:{},onPayload:l(n=>{if(!n||typeof n!="object")return;const f=e.tool_choice,m=f==="required"?c.api==="anthropic-messages"?{type:"any"}:"required":typeof f=="object"&&f!==null?c.api==="anthropic-messages"?{type:"tool",name:f.function.name}:f:void 0;return{...n,...m?{tool_choice:m}:{},...e.stop!==void 0?{[c.api==="anthropic-messages"?"stop_sequences":"stop"]:typeof e.stop=="string"?[e.stop]:e.stop}:{},...e.seed!==void 0?{seed:e.seed}:{},...e.response_format!==void 0?{response_format:e.response_format}:{}}},"onPayload"),fetch:l(async(n,f)=>{const m=await fetch(n,f);if(A=m.status,Z=Ct(m.headers)??Z,w){if(L=m.headers.get("crtr-charge-id")?.trim()||null,m.ok&&!L)throw qe=!0,await m.body?.cancel(),new Error("The hosted endpoint omitted Crtr-Charge-Id; the call may already have been charged. Do not automatically replay it.");return m.status===402&&(Y=qt(await m.clone().json().catch(()=>{}))),m}return m.status===429&&(C=!0,K=m.headers,j=_e(m.headers)??15e3),m},"fetch"),onProviderStreamEvent:l(n=>{w&&n!==null&&typeof n=="object"&&"type"in n&&n.type==="message_stop"&&"crtr_charge"in n&&(y=n.crtr_charge)},"onProviderStreamEvent"),onResponse:l(n=>{!w&&n.status===429&&(C=!0,K=n.headers,j=_e(n.headers)??15e3)},"onResponse")});try{for await(const n of We)n.type==="text_delta"&&(fe.push(n.delta),te(ee({content:n.delta}))),n.type==="thinking_delta"&&(Q.push(n.delta),te(ee({reasoning_content:n.delta}))),n.type==="done"&&(a=n.message),n.type==="error"&&(a=n.error)}catch(n){const f=tt(n);K===void 0&&n&&typeof n=="object"&&"headers"in n&&Object.keys(st(n.headers)).length&&(K=n.headers);const m=ye({status:n&&typeof n=="object"&&"status"in n?n.status:void 0,message:n instanceof Error?n.message:String(n)});if(r||w)O=n;else{if(!C&&m.kind!=="rate-limit")throw ce.length?new i(503,"upstream_model_unavailable",n instanceof Error?n.message:String(n),void 0,{served_model:u}):n;C=!0,j=f??j}}if(w){if(qe)throw new i(502,"upstream_refused","The hosted endpoint omitted Crtr-Charge-Id; the call may already have been charged. Do not automatically replay it.",void 0,{served_model:u});if(A===402&&Y)throw new i(402,"payment_refused",Y.message,void 0,{payment:Y,served_model:u});if(A===401){if(I&&Te(I.key),k===0)continue;throw new i(404,"model_unavailable",`${B} refuses this runtime's tokens`,void 0,{served_model:u})}if(O!==void 0||A!==void 0&&A>=400||a?.stopReason==="error"||a?.stopReason==="aborted"){const f=O instanceof Error?O.message:a?.errorMessage??`the inference endpoint answered ${A??"with an error"}`;throw A===403?new i(502,"upstream_refused",f,void 0,{served_model:u}):new i(503,"upstream_model_unavailable",f,void 0,{served_model:u})}if(y===null||typeof y!="object"||!("id"in y)||y.id!==L||!("served_model"in y)||typeof y.served_model!="string"||!y.served_model.trim()||!("list_usd"in y)||typeof y.list_usd!="number"||!Number.isFinite(y.list_usd)||y.list_usd<0||Number(y.list_usd.toFixed(6))!==y.list_usd)throw new i(502,"upstream_refused","The hosted endpoint returned missing or invalid final charge accounting; output and cost may already exist. Do not automatically replay this call.",void 0,{served_model:u,charge_id:L});H={id:L,served_model:y.served_model,list_usd:y.list_usd}}if(r){if(A===401){if(I&&Te(I.key),k===0)continue;throw new i(404,"model_unavailable",`${h.base_url} refuses this runtime's tokens`,void 0,{served_model:u})}if(C&&_e(K)===void 0)throw new i(503,"upstream_model_unavailable",`${u} was rate-limited without a retry-after`,void 0,{served_model:u});if(!C&&(O!==void 0||A!==void 0&&A>=500))throw new i(503,"upstream_model_unavailable",O instanceof Error?O.message:a?.errorMessage??"inference endpoint failed",void 0,{served_model:u})}if(!C&&a?.stopReason==="error"&&ye({message:a.errorMessage}).kind==="rate-limit"&&(C=!0,j=15e3),C){const n=rt(K,c.id,j),{observation:f,vendorReset:m}=n;if(j=n.retryMs,v={provider:p,model:c.id,...b?{account:b.label}:{},observation:f},console.error(`[llm] 429 from ${u}${b?` account "${b.label}"`:""}: scope=${Ce(f.scope)} retry_after_ms=${j} headers=${JSON.stringify(f.headers)}`),b&&N(p)&&await Qe(p,b.label,j,V,Date.now(),f.scope),m!==void 0&&(z=Math.min(z,m)),Date.now()+Math.min(j,Me)<D&&(D=Date.now()+Math.min(j,Me),se=u),fe.length||Q.length)throw new i(503,"service_unavailable","vendor rate limit after output began",void 0,{served_model:u});if(r)break;continue}const ne=dt(a);if(A===400&&e.tool_choice!==void 0&&e.tool_choice!=="auto"&&e.tool_choice!=="none"&&/\btool[_ ]choice\b/i.test(a?.errorMessage??"")&&/not supported|does not support|unsupported|cannot|must be auto/i.test(a?.errorMessage??""))throw new i(400,"invalid_request",a.errorMessage,"tool_choice",{served_model:u});if(a?.stopReason==="error"){const n=$t(c.provider,a.errorMessage,u);if(n)throw n}if(!a||a.stopReason==="error"&&!ne||a.stopReason==="aborted")throw new i(503,"upstream_model_unavailable",a?.errorMessage??"model request failed",void 0,{served_model:u});b&&N(p)&&ot(b,c.id)&&await et(p,b.label,V,c.id);const me=a.content.filter(n=>n.type==="toolCall").map(n=>({id:n.id,type:"function",function:{name:n.name,arguments:JSON.stringify(n.arguments)}})),pe=ne?"content_filter":a.stopReason==="toolUse"?"tool_calls":a.stopReason==="length"?"length":"stop",he=a.responseModel?Mt(c,a.responseModel):void 0,E=H?`${c.provider}/${H.served_model}`:he?`${c.provider}/${he.model}`:u,oe={prompt_tokens:a.usage.input,completion_tokens:a.usage.output,total_tokens:a.usage.totalTokens,cache_read_tokens:a.usage.cacheRead,cache_write_tokens:a.usage.cacheWrite,usd_equivalent:H?H.list_usd:jt(he??c,a.usage.cost.total),served_model:E};w?d!==void 0&&q!==null&&await ge({id:L,request:d.request??W,kind:"model",what:E,units:{input:a.usage.input,output:a.usage.output,cache_read:a.usage.cacheRead,cache_write:a.usage.cacheWrite},usd:oe.usd_equivalent,payer:q.payer,funding:q.funding,sub:g,grantee:d.grantee,node:d.node??null,run:d.run??null,provider:p,causedBy:await le(),vendorRef:Z}):d!==void 0&&q!==null&&await ge({request:d.request??W,kind:"model",what:E,units:{input:a.usage.input,output:a.usage.output,cache_read:a.usage.cacheRead,cache_write:a.usage.cacheWrite},usd:oe.usd_equivalent,payer:q.payer,funding:q.funding,sub:g,grantee:d.grantee,node:d.node??null,run:d.run??null,provider:p,causedBy:await le(),vendorRef:Z});const Ae={id:W,object:"chat.completion",created:Math.floor(V/1e3),model:E,served_model:E,requested_model:P,substituted:P!==E&&!/^([^/]+)\/(ultra|strong|medium|light)$/.test(P),choices:[{index:0,message:{role:"assistant",content:fe.join("")||null,...Q.length?{reasoning_content:Q.join("")}:{},...me.length?{tool_calls:me}:{},...ne?{refusal:a.errorMessage??"Content filtered"}:{}},finish_reason:pe}],usage:oe,...e.metadata!==void 0?{metadata:e.metadata}:{}};for(const[n,f]of me.entries())te(ee({tool_calls:[{index:n,...f}]}));return te({...ee({},pe),model:E,served_model:E,substituted:Ae.substituted,...ne?{choices:[{index:0,delta:{},finish_reason:pe,message:{refusal:a.errorMessage??"Content filtered"}}]}:{},usage:oe}),{completion:Ae,chunks:ce}}}throw de!==void 0?ut(de):D!==1/0?new i(429,"all_routes_exhausted","all eligible model routes are rate-limited",void 0,{payment:{reason:"nothing_left",message:"Every connected subscription and key is rate-limited or used up right now.",pay_url:(await Oe())?.payment_setup_url??null,reset_at:z===1/0?null:new Date(z).toISOString()},retry_after_s:Math.max(1,Math.ceil((D-Date.now())/1e3)),served_model:v?`${v.provider}/${v.model}`:se,...v?{rate_limit:{provider:v.provider,model:v.model,...v.account?{account:v.account}:{},scope:Ce(v.observation.scope),...v.observation.claim?{claim:v.observation.claim}:{},headers:v.observation.headers}}:{}},void 0,!0):ae!==void 0?ae:e.model_policy==="exact"?new i(400,"substitution_refused",X.size>0?`your ${[...X].map(Ye).join(" and ")} sign-in has expired; sign in again`:"the requested model is unavailable"):h?new i(404,"model_unavailable","no usable model route is available"):await we()}l(on,"runLlm");export{kt as freshSubscriptionAccess,nn as llmCallerOf,tn as parseLlmRequest,on as runLlm,jt as usdEquivalent};
3
+ `),J=e.tools?.map(({function:r})=>({name:r.name,description:r.description??"",parameters:r.parameters??{type:"object",properties:{}}}));return{...S?{systemPrompt:S}:{},messages:o.slice(d.length),...J?{tools:J}:{}}}l(qt,"contextOf");function At(e){return pt(e?.payment)}l(At,"paymentOf");function jt(e,t){const o=e.find("anthropic",t);if(o)return o;const s=e.getAll().find(d=>d.provider==="anthropic"&&d.api==="anthropic-messages");return s?{...s,id:t,name:t}:void 0}l(jt,"hostedModel");function Mt(e,t){const{input:o,output:s,cacheRead:d,cacheWrite:S}=e.cost;return o===0&&s===0&&d===0&&S===0?null:Number.isFinite(t)&&t>=0?t:null}l(Mt,"usdEquivalent");function St(e,t){return e.compat?.allowedFallbackModels?.find(s=>s.provider===e.provider&&s.model===t)}l(St,"allowedFallback");function on(e){return e?{payer:e.payer??"user",sub:e.sub,grantee:e.grantee,inference_endpoint:e.inference_endpoint??null}:void 0}l(on,"llmCallerOf");function Te(e){return e instanceof _t?e.code==="server_error"?new i(503,"upstream_model_unavailable",e.message):new i(404,"model_unavailable",e.message):e}l(Te,"mintFailure");const $t=/\bmodel is not supported when using Codex with a ChatGPT account\b/i;function Ct(e,t,o){if(!(e!=="openai-codex"||t===void 0||!$t.test(t)))return new i(404,"model_unavailable",t,void 0,{served_model:o})}l(Ct,"codexAccountModelRejection");function Et(e){return e.get("request-id")??e.get("x-request-id")}l(Et,"vendorRequestId");async function rn(e,t,o,s,d,S,J){const r=S?.payer==="app"?S:void 0;if(e.payer==="app"&&!r)throw new i(403,"payer_not_app","this grant is not app-paid");if(e.payer==="user"&&r)throw new i(400,"invalid_request","this grant is app-paid; payer cannot be user","payer");if(r&&!r.inference_endpoint)throw new i(404,"model_unavailable",`${r.grantee} is app-paid but its grant carries no inference endpoint`);const _=r?.inference_endpoint??void 0,w=d===void 0?null:r?.sub??d.sub??await ht(),x=await Ve();let R;_?(R=yt(_,e.model,e.model_policy==="exact").flatMap((y,b)=>{const $=Ge(y.model);return $?[{routeId:"app",credentialSource:"app",family:"app",strength:y.strength,...$,rank:b}]:[]}),R=R.filter(y=>wt(x,e,y))):R=await bt(x,e,s);const ie=!_&&d!==void 0&&w!==null?await mt():null,ae=ie===null?void 0:gt(e,R,ie),Pe=ae?ie:null;ae&&(R=[...R,ae]);const Ue=_?new Set:ze(),be=l(async()=>new i(429,"all_routes_exhausted","no available way to pay for this call",void 0,{payment:{reason:"nothing_left",message:"No available way to pay for this call",pay_url:(await Oe())?.payment_setup_url??null,reset_at:null}}),"nothingLeft");if(R.length===0)throw e.model_policy==="exact"?new i(400,"substitution_refused","no eligible model route is configured"):_?new i(404,"model_unavailable","no eligible model route is configured"):await be();const H=`chatcmpl-${Je()}`;let F=1/0,L=1/0,se,v,de,le;const G=new Set,ue=l(async()=>J??(d?.node?(await De(d.node))?.caused_by??null:null)??(d?.run?(await De(d.run))?.caused_by??null:null),"causeOf");for(const y of R){const b=y.credentialSource==="hosted";if(!r&&!b&&!(await Xe(y,x)).authenticated){if(y.credentialSource!==je&&N(y.providerId)){const k=await $e(y.providerId);k.length>0&&k.every(q=>q.authFailure)&&G.add(y.providerId)}continue}const $=b?jt(x,y.modelId):x.find(y.providerId,y.modelId);if(!$)continue;const z=b?Pe.base_url:void 0,u=_?{...$,baseUrl:`${_.base_url}/${$.provider}`}:z?{...$,baseUrl:`${z}/anthropic`,compat:{...$.compat,allowedFallbackModels:void 0}}:$,h=y.providerId,V=y.credentialSource===je&&N(h),ce=!r&&!b&&!V&&N(h)?await $e(h):[],T=ce.filter(k=>!k.authFailure),ve=T.filter(k=>Se(k,u.id)<=Date.now()),P=V?await Ie(h):Ue.has(h)?void 0:ce.length?await Ie(h):void 0;if(V&&P===void 0)continue;if(ce.length>0&&T.length===0&&P===void 0){N(h)&&G.add(h);continue}if(T.length&&!ve.length&&P===void 0){const k=Math.min(...T.map(c=>Se(c,u.id)));k<F&&(F=k,de=`${u.provider}/${u.id}`);const q=st(u.id);for(const c of T){const C=q!==void 0&&(c.modelCooldowns?.[q]??0)>Date.now()?c.vendorLimits?.[q]:c.rateLimitedUntil>Date.now()?c.vendorLimits?.account:void 0;C!==void 0&&(C.vendorReset!==void 0&&C.vendorReset>Date.now()&&(L=Math.min(L,C.vendorReset)),v??={provider:h,model:C.model,account:c.label,observation:C.observation})}continue}const ke=r||b?[void 0,void 0]:V?["key"]:T.length||P!==void 0?[...ve,...P!==void 0?["key"]:[]]:[void 0];let xe=!1;for(const[k,q]of ke.entries()){if(xe&&q!=="key")continue;const c=q==="key"?void 0:q,C=q==="key",Y=Date.now();let Re=c?.access;if(c&&c.expires<=Date.now()&&N(h))try{Re=await xt(x,h,c,`${u.provider}/${u.id}`,t)}catch(n){if(!Ze(n))throw n;se??=n;continue}const Ke=qt(e),U=c||r||b||C?void 0:await x.getApiKeyAndHeaders(u);if(U&&!U.ok)continue;const f=`${u.provider}/${u.id}`,K=e.model??f,A=b?w===null?null:{payer:w,funding:"endpoint"}:r?Ee({call:"model",route:"endpoint",grantee:r.grantee}):w===null?null:Ee({call:"model",route:c?"subscription":"key",sub:w});if(d!==void 0&&A!==null){const n=await ut({scope:"call",payer:A.payer,funding:A.funding,sub:w,grantee:d.grantee,provider:h});if(n!==null){if(await we({request:d.request??H,kind:"model",what:f,usd:null,payer:A.payer,funding:A.funding,sub:w,grantee:d.grantee,node:d.node??null,run:d.run??null,provider:h,causedBy:await ue(),refused:ft(n)}),le??=n,q!=="key"&&ke.includes("key")){xe=!0;continue}break}}let O;if(r&&_)try{O=await Ne({audience:_.base_url,sub:r.sub,grantee:r.grantee,initiating_app:r.grantee,scope:["crtr:llm"]},{signal:t})}catch(n){throw Te(n)}if(z)try{O=await Ne({audience:z,sub:w,grantee:d.grantee,initiating_app:d.grantee,scope:["crtr:llm"]},{signal:t})}catch(n){throw Te(n)}let W=null,qe=!1,g,X,Z,E=!1,j,Q=null,M=3e4,B;const fe=[],me=[],ee=[];let a,D;const te=l((n,m=null)=>({id:H,object:"chat.completion.chunk",created:Math.floor(Y/1e3),model:f,served_model:f,requested_model:K,substituted:K!==f&&!/^([^/]+)\/(ultra|strong|medium|light)$/.test(K),choices:[{index:0,delta:n,finish_reason:m}]}),"chunk"),ne=l(n=>{fe.push(n),o?.(n)},"emit"),We=He(u,Ke,{apiKey:O?.access_token??Re??(C?P:void 0)??(U?.ok?U.apiKey:void 0),...U?.ok?{headers:U.headers}:{},signal:t,reasoning:e.reasoning_effort??y.thinkingLevel,...e.temperature!==void 0?{temperature:e.temperature}:{},...e.max_tokens!==void 0?{maxTokens:e.max_tokens}:{},...e.top_p!==void 0?{samplingParams:{top_p:e.top_p}}:{},...e.tool_choice==="none"?{toolChoice:"none"}:{},onPayload:l(n=>{if(!n||typeof n!="object")return;const m=e.tool_choice,p=m==="required"?u.api==="anthropic-messages"?{type:"any"}:"required":typeof m=="object"&&m!==null?u.api==="anthropic-messages"?{type:"tool",name:m.function.name}:m:void 0;return{...n,...p?{tool_choice:p}:{},...e.stop!==void 0?{[u.api==="anthropic-messages"?"stop_sequences":"stop"]:typeof e.stop=="string"?[e.stop]:e.stop}:{},...e.seed!==void 0?{seed:e.seed}:{},...e.response_format!==void 0?{response_format:e.response_format}:{}}},"onPayload"),fetch:l(async(n,m)=>{const p=await fetch(n,m);if(j=p.status,Q=Et(p.headers)??Q,b){if(W=p.headers.get("crtr-charge-id")?.trim()||null,p.ok&&!W)throw qe=!0,await p.body?.cancel(),new Error("The hosted endpoint omitted Crtr-Charge-Id; the call may already have been charged. Do not automatically replay it.");return p.status===402&&(Z=At(await p.clone().json().catch(()=>{}))),p}return p.status===429&&(E=!0,B=p.headers,M=ye(p.headers)??15e3),p},"fetch"),onProviderStreamEvent:l(n=>{b&&n!==null&&typeof n=="object"&&"type"in n&&n.type==="message_stop"&&"crtr_charge"in n&&(g=n.crtr_charge)},"onProviderStreamEvent"),onResponse:l(n=>{!b&&n.status===429&&(E=!0,B=n.headers,M=ye(n.headers)??15e3)},"onResponse")});try{for await(const n of We)n.type==="text_delta"&&(me.push(n.delta),ne(te({content:n.delta}))),n.type==="thinking_delta"&&(ee.push(n.delta),ne(te({reasoning_content:n.delta}))),n.type==="done"&&(a=n.message),n.type==="error"&&(a=n.error)}catch(n){const m=tt(n);B===void 0&&n&&typeof n=="object"&&"headers"in n&&Object.keys(dt(n.headers)).length&&(B=n.headers);const p=ge({status:n&&typeof n=="object"&&"status"in n?n.status:void 0,message:n instanceof Error?n.message:String(n)});if(r||b)D=n;else{if(!E&&p.kind!=="rate-limit")throw fe.length?new i(503,"upstream_model_unavailable",n instanceof Error?n.message:String(n),void 0,{served_model:f}):n;E=!0,M=m??M}}if(b){if(qe)throw new i(502,"upstream_refused","The hosted endpoint omitted Crtr-Charge-Id; the call may already have been charged. Do not automatically replay it.",void 0,{served_model:f});if(j===402&&Z)throw new i(402,"payment_refused",Z.message,void 0,{payment:Z,served_model:f});if(j===401){if(O&&Fe(O.key),k===0)continue;throw new i(404,"model_unavailable",`${z} refuses this runtime's tokens`,void 0,{served_model:f})}if(D!==void 0||j!==void 0&&j>=400||a?.stopReason==="error"||a?.stopReason==="aborted"){const m=D instanceof Error?D.message:a?.errorMessage??`the inference endpoint answered ${j??"with an error"}`;throw j===403?new i(502,"upstream_refused",m,void 0,{served_model:f}):new i(503,"upstream_model_unavailable",m,void 0,{served_model:f})}if(g===null||typeof g!="object"||!("id"in g)||g.id!==W||!("served_model"in g)||typeof g.served_model!="string"||!g.served_model.trim()||!("list_usd"in g)||typeof g.list_usd!="number"||!Number.isFinite(g.list_usd)||g.list_usd<0||Number(g.list_usd.toFixed(6))!==g.list_usd)throw new i(502,"upstream_refused","The hosted endpoint returned missing or invalid final charge accounting; output and cost may already exist. Do not automatically replay this call.",void 0,{served_model:f,charge_id:W});X={id:W,served_model:g.served_model,list_usd:g.list_usd}}if(r){if(j===401){if(O&&Fe(O.key),k===0)continue;throw new i(404,"model_unavailable",`${_.base_url} refuses this runtime's tokens`,void 0,{served_model:f})}if(E&&ye(B)===void 0)throw new i(503,"upstream_model_unavailable",`${f} was rate-limited without a retry-after`,void 0,{served_model:f});if(!E&&(D!==void 0||j!==void 0&&j>=500))throw new i(503,"upstream_model_unavailable",D instanceof Error?D.message:a?.errorMessage??"inference endpoint failed",void 0,{served_model:f})}if(!E&&a?.stopReason==="error"&&ge({message:a.errorMessage}).kind==="rate-limit"&&(E=!0,M=15e3),E){const n=rt(B,u.id,M),{observation:m,vendorReset:p}=n;if(M=n.retryMs,v={provider:h,model:u.id,...c?{account:c.label}:{},observation:m},console.error(`[llm] 429 from ${f}${c?` account "${c.label}"`:""}: scope=${Ce(m.scope)} retry_after_ms=${M} headers=${JSON.stringify(m.headers)}`),c&&N(h)&&await Qe(h,c.label,M,Y,Date.now(),m.scope,{model:u.id,...p!==void 0?{vendorReset:p}:{},observation:m}),p!==void 0&&(L=Math.min(L,p)),Date.now()+Math.min(M,Me)<F&&(F=Date.now()+Math.min(M,Me),de=f),me.length||ee.length)throw new i(503,"service_unavailable","vendor rate limit after output began",void 0,{served_model:f});if(r)break;continue}const oe=lt(a);if(j===400&&e.tool_choice!==void 0&&e.tool_choice!=="auto"&&e.tool_choice!=="none"&&/\btool[_ ]choice\b/i.test(a?.errorMessage??"")&&/not supported|does not support|unsupported|cannot|must be auto/i.test(a?.errorMessage??""))throw new i(400,"invalid_request",a.errorMessage,"tool_choice",{served_model:f});if(a?.stopReason==="error"){const n=Ct(u.provider,a.errorMessage,f);if(n)throw n}if(!a||a.stopReason==="error"&&!oe||a.stopReason==="aborted")throw new i(503,"upstream_model_unavailable",a?.errorMessage??"model request failed",void 0,{served_model:f});c&&N(h)&&ot(c,u.id)&&await et(h,c.label,Y,u.id);const pe=a.content.filter(n=>n.type==="toolCall").map(n=>({id:n.id,type:"function",function:{name:n.name,arguments:JSON.stringify(n.arguments)}})),he=oe?"content_filter":a.stopReason==="toolUse"?"tool_calls":a.stopReason==="length"?"length":"stop",_e=a.responseModel?St(u,a.responseModel):void 0,I=X?`${u.provider}/${X.served_model}`:_e?`${u.provider}/${_e.model}`:f,re={prompt_tokens:a.usage.input,completion_tokens:a.usage.output,total_tokens:a.usage.totalTokens,cache_read_tokens:a.usage.cacheRead,cache_write_tokens:a.usage.cacheWrite,usd_equivalent:X?X.list_usd:Mt(_e??u,a.usage.cost.total),served_model:I};b?d!==void 0&&A!==null&&await we({id:W,request:d.request??H,kind:"model",what:I,units:{input:a.usage.input,output:a.usage.output,cache_read:a.usage.cacheRead,cache_write:a.usage.cacheWrite},usd:re.usd_equivalent,payer:A.payer,funding:A.funding,sub:w,grantee:d.grantee,node:d.node??null,run:d.run??null,provider:h,causedBy:await ue(),vendorRef:Q}):d!==void 0&&A!==null&&await we({request:d.request??H,kind:"model",what:I,units:{input:a.usage.input,output:a.usage.output,cache_read:a.usage.cacheRead,cache_write:a.usage.cacheWrite},usd:re.usd_equivalent,payer:A.payer,funding:A.funding,sub:w,grantee:d.grantee,node:d.node??null,run:d.run??null,provider:h,causedBy:await ue(),vendorRef:Q});const Ae={id:H,object:"chat.completion",created:Math.floor(Y/1e3),model:I,served_model:I,requested_model:K,substituted:K!==I&&!/^([^/]+)\/(ultra|strong|medium|light)$/.test(K),choices:[{index:0,message:{role:"assistant",content:me.join("")||null,...ee.length?{reasoning_content:ee.join("")}:{},...pe.length?{tool_calls:pe}:{},...oe?{refusal:a.errorMessage??"Content filtered"}:{}},finish_reason:he}],usage:re,...e.metadata!==void 0?{metadata:e.metadata}:{}};for(const[n,m]of pe.entries())ne(te({tool_calls:[{index:n,...m}]}));return ne({...te({},he),model:I,served_model:I,substituted:Ae.substituted,...oe?{choices:[{index:0,delta:{},finish_reason:he,message:{refusal:a.errorMessage??"Content filtered"}}]}:{},usage:re}),{completion:Ae,chunks:fe}}}throw le!==void 0?ct(le):F!==1/0?new i(429,"all_routes_exhausted","all eligible model routes are rate-limited",void 0,{payment:{reason:"nothing_left",message:"Every connected subscription and key is rate-limited or used up right now.",pay_url:(await Oe())?.payment_setup_url??null,reset_at:L===1/0?null:new Date(L).toISOString()},retry_after_s:Math.max(1,Math.ceil((F-Date.now())/1e3)),served_model:v?`${v.provider}/${v.model}`:de,...v?{rate_limit:{provider:v.provider,model:v.model,...v.account?{account:v.account}:{},scope:Ce(v.observation.scope),...v.observation.claim?{claim:v.observation.claim}:{},headers:v.observation.headers}}:{}},void 0,!0):se!==void 0?se:e.model_policy==="exact"?new i(400,"substitution_refused",G.size>0?`your ${[...G].map(Ye).join(" and ")} sign-in has expired; sign in again`:"the requested model is unavailable"):_?new i(404,"model_unavailable","no usable model route is available"):await be()}l(rn,"runLlm");export{xt as freshSubscriptionAccess,on as llmCallerOf,nn as parseLlmRequest,rn as runLlm,Mt as usdEquivalent};
@@ -1,3 +1,4 @@
1
+ import { type RateLimitObservation } from './rate-limit-scope.js';
1
2
  export declare const ANTHROPIC_PROVIDER_ID = "anthropic";
2
3
  export declare const OPENAI_CODEX_PROVIDER_ID = "openai-codex";
3
4
  /** pi's built-in `openai` provider signed in with a ChatGPT account (dynamic OAuth client). Distinct from Codex: its own pool, credential file and sign-in. */
@@ -12,7 +13,7 @@ export type RotationConfig = {
12
13
  defaultFallbackStrength?: ModelStrength;
13
14
  revertWhenAvailable?: boolean;
14
15
  };
15
- /** `rateLimitedUntil` cools the whole account; `modelCooldowns` cools one model family on it (family → epoch ms, stored rows including expired ones). Read both through `coolingUntilFor`. */
16
+ /** `rateLimitedUntil` cools the whole account; `modelCooldowns` cools one model family on it (family → epoch ms, stored rows including expired ones). Read both through `coolingUntilFor`. `vendorLimits` holds each cooldown's vendor observation, keyed `account` or the family. */
16
17
  export type SubscriptionCredential = {
17
18
  label: string;
18
19
  refresh: string;
@@ -25,6 +26,13 @@ export type SubscriptionCredential = {
25
26
  accountId?: string;
26
27
  clientId?: string;
27
28
  modelCooldowns?: Record<string, number>;
29
+ vendorLimits?: Record<string, VendorLimit>;
30
+ };
31
+ /** What the vendor's 429 said when a cooldown was recorded: the model it answered, the reset the vendor itself named (epoch ms, never the capped cooldown) and the parsed safe observation. */
32
+ export type VendorLimit = {
33
+ model: string;
34
+ vendorReset?: number;
35
+ observation: RateLimitObservation;
28
36
  };
29
37
  export type ProviderCandidate = {
30
38
  providerId: string;
@@ -39,6 +39,8 @@ export declare function normalizeProviderFailure(error: unknown, observed?: {
39
39
  }): NormalizedProviderFailure;
40
40
  /** The stable diagnostic carrier for normalized provider error facts on an assistant error message. */
41
41
  export declare function providerFailureDiagnostic(details: ProviderFailureDetails): AssistantMessageDiagnostic;
42
+ /** Plain text for a fault's vendor facts: the earliest known vendor reset (across the pool), then the last 429's window with its own account and model. Never pairs the aggregate reset with that window. */
43
+ export declare function describeVendorLimit(details: Pick<ProviderFailureDetails, 'payment' | 'ratelimit'> | undefined): string;
42
44
  /** Strictly parse a recorded payment refusal: a known reason and a message, nothing else trusted. */
43
45
  export declare function parseProviderPayment(value: unknown): PaymentRefusalDTO | undefined;
44
46
  /** Strictly parse a recorded rate-limit block: string headers only, capped, unknown keys dropped. */