@north-light/cli 0.3.629 → 0.3.631

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.
@@ -6,9 +6,16 @@ export interface MovedBlobs {
6
6
  }
7
7
  /** `created` collects the keys this call wrote, so the caller can delete them if the run fails before its copy commits. */
8
8
  export declare function moveRunBlobs(db: CanvasDb, schema: string, target: string, person: string, blobs: BlobStore, runId: string, created: string[]): Promise<MovedBlobs>;
9
- /** Delete the keys, concurrently. With `bestEffort`, a key that cannot be deleted is skipped and the rest still go; otherwise the first failure is thrown. */
9
+ /** Delete the keys, concurrently. With `bestEffort`, a key that cannot be deleted is logged and skipped and the rest still go; otherwise the first failure is thrown. */
10
10
  export declare function deleteBlobs(blobs: BlobStore, keys: readonly string[], bestEffort?: boolean): Promise<void>;
11
11
  /** Delete every blob `moveRunBlobs` can have moved for these owners (the keys `parseBlobKey` accepts under each owner's prefixes): one paged listing per owner and kind, then the deletes, with no request per key to check. */
12
12
  export declare function deleteOwnedBlobs(blobs: BlobStore, nodes: readonly string[], requests: readonly string[]): Promise<void>;
13
13
  /** Delete the run's uploaded copies (after the run is done). */
14
14
  export declare function deleteRunBlobs(blobs: BlobStore, runId: string): Promise<void>;
15
+ /** Delete everything the run uploaded under `imports/<run>/` once the run can never be loaded again. The node-file archives are kept (`keepNodeFiles`) for a run that failed after its
16
+ * copy committed: its `import_node_files` rows stay until rollback, and a hosted node's start reads the archive. By default a storage error is thrown (rollback reports it to its caller).
17
+ * With `bestEffort`, a run whose state is already settled keeps that state: a list error is logged, and a key that cannot be deleted is logged and skipped while the rest still go. */
18
+ export declare function deleteRunPrefix(blobs: BlobStore, runId: string, options?: {
19
+ keepNodeFiles?: boolean;
20
+ bestEffort?: boolean;
21
+ }): Promise<void>;
@@ -1 +1 @@
1
- var M=Object.defineProperty;var l=(e,t)=>M(e,"name",{value:t,configurable:!0});import{R2_MAX_CONNECTIONS as T}from"../../blobs/r2.js";import{ownerBlobPrefixes as R,parseBlobKey as O,runBlobPrefix as _}from"../bundle/blob-keys.js";import{q as p}from"./catalog.js";import{ImportLaneError as E}from"./stage.js";const b=T;function v(){const e=process.env.CRTR_IMPORT_BLOB_WORKERS;if(e===void 0||e==="")return b;const t=Number(e);if(!Number.isInteger(t)||t<1||t>1024)throw new Error(`CRTR_IMPORT_BLOB_WORKERS must be an integer from 1 to 1024, got ${JSON.stringify(e)}`);return t}l(v,"workerLimit");async function w(e,t){if(e.length===0)return;let o=0,n;const i=l(async()=>{for(;n===void 0&&o<e.length;)try{await t(e[o++])}catch(a){n??={error:a}}},"worker");if(await Promise.all(Array.from({length:Math.min(v(),e.length)},i)),n!==void 0)throw n.error}l(w,"forEachBounded");async function I(e,t,o,n,i,a,c){const h={nodes:new Set((await e.prepareUncached(`SELECT node_id AS v FROM ${p(t)}.nodes UNION SELECT node_id FROM ${p(o)}.nodes WHERE sub = ?`).all(n)).map(r=>r.v)),human_requests:new Set((await e.prepareUncached(`SELECT request_id AS v FROM ${p(t)}.human_requests`).all()).map(r=>r.v))},f=_(a),u={moved:0,left:0},m=[];for(const r of await i.listObjects(f)){const s=O(r.key.slice(f.length));s===null||!h[s.ownerTable].has(s.owner)?u.left+=1:m.push(r)}const y=new Map,d=new Set(m.map(r=>r.key.slice(f.length)));return await w([...new Set([...d].map(x))],async r=>{for(const s of await i.listObjects(r))d.has(s.key)&&y.set(s.key,s)}),await w(m,async r=>{const s=r.key.slice(f.length),g=y.get(s);if(g===void 0){if(c.push(s),!await i.copy(r.key,s))throw k(r.key)}else if(!await C(i,r,g))throw new E("blobs","unique_conflict",`${s} already exists with other contents; the import does not replace it`,{key:s});u.moved+=1}),u}l(I,"moveRunBlobs");const x=l(e=>e.split("/").slice(0,2).join("/")+"/","ownerPrefix"),k=l(e=>new E("blobs","bundle_invalid",`${e} was listed and is gone`),"gone");async function C(e,t,o){if(t.size!==o.size)return!1;if(t.etag!==null&&o.etag!==null)return t.etag===o.etag;for(let n=0;n<t.size;n+=S){const i={start:n,length:Math.min(S,t.size-n)},[a,c]=await Promise.all([e.get(t.key,i),e.get(o.key,i)]);if(a===null)throw k(t.key);if(c===null||!a.equals(c))return!1}return!0}l(C,"sameObject");const S=256*1024;async function B(e,t,o=!1){await w(t,o?n=>e.delete(n).catch(()=>{}):n=>e.delete(n))}l(B,"deleteBlobs");async function $(e,t,o){const n=[...t.flatMap(a=>R("nodes",a).map(c=>({prefix:c,owner:a,table:"nodes"}))),...o.flatMap(a=>R("human_requests",a).map(c=>({prefix:c,owner:a,table:"human_requests"})))],i=[];await w(n,async({prefix:a,owner:c,table:h})=>{for(const f of await e.list(a)){const u=O(f);u!==null&&u.ownerTable===h&&u.owner===c&&i.push(f)}}),await B(e,i)}l($,"deleteOwnedBlobs");async function j(e,t){await B(e,await e.list(_(t)))}l(j,"deleteRunBlobs");export{B as deleteBlobs,$ as deleteOwnedBlobs,j as deleteRunBlobs,I as moveRunBlobs};
1
+ var B=Object.defineProperty;var l=(e,t)=>B(e,"name",{value:t,configurable:!0});import{R2_MAX_CONNECTIONS as M}from"../../blobs/r2.js";import{ownerBlobPrefixes as R,parseBlobKey as E,runBlobPrefix as O}from"../bundle/blob-keys.js";import{bundleKeys as k}from"../bundle/layout.js";import{emitEvent as v}from"../../events/emit.js";import{q as d}from"./catalog.js";import{ImportLaneError as x}from"./stage.js";const T=M;function N(){const e=process.env.CRTR_IMPORT_BLOB_WORKERS;if(e===void 0||e==="")return T;const t=Number(e);if(!Number.isInteger(t)||t<1||t>1024)throw new Error(`CRTR_IMPORT_BLOB_WORKERS must be an integer from 1 to 1024, got ${JSON.stringify(e)}`);return t}l(N,"workerLimit");async function w(e,t){if(e.length===0)return;let i=0,n;const a=l(async()=>{for(;n===void 0&&i<e.length;)try{await t(e[i++])}catch(r){n??={error:r}}},"worker");if(await Promise.all(Array.from({length:Math.min(N(),e.length)},a)),n!==void 0)throw n.error}l(w,"forEachBounded");async function U(e,t,i,n,a,r,f){const m={nodes:new Set((await e.prepareUncached(`SELECT node_id AS v FROM ${d(t)}.nodes UNION SELECT node_id FROM ${d(i)}.nodes WHERE sub = ?`).all(n)).map(o=>o.v)),human_requests:new Set((await e.prepareUncached(`SELECT request_id AS v FROM ${d(t)}.human_requests`).all()).map(o=>o.v))},c=O(r),u={moved:0,left:0},p=[];for(const o of await a.listObjects(c)){const s=E(o.key.slice(c.length));s===null||!m[s.ownerTable].has(s.owner)?u.left+=1:p.push(o)}const y=new Map,_=new Set(p.map(o=>o.key.slice(c.length)));return await w([...new Set([..._].map(C))],async o=>{for(const s of await a.listObjects(o))_.has(s.key)&&y.set(s.key,s)}),await w(p,async o=>{const s=o.key.slice(c.length),g=y.get(s);if(g===void 0){if(f.push(s),!await a.copy(o.key,s))throw S(o.key)}else if(!await P(a,o,g))throw new x("blobs","unique_conflict",`${s} already exists with other contents; the import does not replace it`,{key:s});u.moved+=1}),u}l(U,"moveRunBlobs");const C=l(e=>e.split("/").slice(0,2).join("/")+"/","ownerPrefix"),S=l(e=>new x("blobs","bundle_invalid",`${e} was listed and is gone`),"gone");async function P(e,t,i){if(t.size!==i.size)return!1;if(t.etag!==null&&i.etag!==null)return t.etag===i.etag;for(let n=0;n<t.size;n+=b){const a={start:n,length:Math.min(b,t.size-n)},[r,f]=await Promise.all([e.get(t.key,a),e.get(i.key,a)]);if(r===null)throw S(t.key);if(f===null||!r.equals(f))return!1}return!0}l(P,"sameObject");const b=256*1024;async function h(e,t,i=!1){await w(t,i?n=>e.delete(n).catch(a=>{v({level:"warn",event:"import.blob_delete_failed",error:a,fields:{key:n}})}):n=>e.delete(n))}l(h,"deleteBlobs");async function W(e,t,i){const n=[...t.flatMap(r=>R("nodes",r).map(f=>({prefix:f,owner:r,table:"nodes"}))),...i.flatMap(r=>R("human_requests",r).map(f=>({prefix:f,owner:r,table:"human_requests"})))],a=[];await w(n,async({prefix:r,owner:f,table:m})=>{for(const c of await e.list(r)){const u=E(c);u!==null&&u.ownerTable===m&&u.owner===f&&a.push(c)}}),await h(e,a)}l(W,"deleteOwnedBlobs");async function z(e,t){await h(e,await e.list(O(t)))}l(z,"deleteRunBlobs");async function I(e,t,i={}){const n=`${k.prefix(t)}node-files/`;let a;try{a=await e.list(k.prefix(t))}catch(r){if(i.bestEffort!==!0)throw r;v({level:"warn",event:"import.prefix_delete_failed",error:r,fields:{run_id:t}});return}await h(e,i.keepNodeFiles===!0?a.filter(r=>!r.startsWith(n)):a,i.bestEffort===!0)}l(I,"deleteRunPrefix");export{h as deleteBlobs,W as deleteOwnedBlobs,z as deleteRunBlobs,I as deleteRunPrefix,U as moveRunBlobs};
@@ -1,6 +1,6 @@
1
- var A=Object.defineProperty;var u=(n,d)=>A(n,"name",{value:d,configurable:!0});import{openDb as h,withCanvasWrite as D}from"../../canvas/db.js";import{bundleKeys as M}from"../bundle/layout.js";import{keyMatch as m,q as a,readCatalog as y,rowKey as S,topologicalOrder as F}from"./catalog.js";import{deleteOwnedBlobs as W}from"./blobs.js";import{decodeKeys as $}from"./copy.js";import{IMPORT_ROLLBACK_LOCK as g}from"../../graph/deletion.js";import{OBJECT_ID_COLUMNS as H}from"./rewrite.js";import{targetSchema as v}from"./stage.js";class L extends Error{static{u(this,"Refused")}}async function Z(n,d){const l=await h(),c=await l.prepare("SELECT source_install_id, source_kind, state, created_at FROM import_runs WHERE run_id = ?").get(n);if(c===void 0)throw new Error(`no import run ${n}`);if(c.state!=="done"&&c.state!=="committed"&&c.state!=="failed")throw new Error(`import run ${n} is ${c.state}, not rollbackable`);const N=(await l.prepare("SELECT blob_key FROM import_node_files WHERE blob_key LIKE ?").all(`imports/${n}/node-files/%`)).map(t=>t.blob_key),E={run_id:n,rolled_back:!1,dependents:{},deleted:{}},R={nodes:[],human_requests:[]};try{await D(async t=>{await t.prepare("SELECT pg_advisory_xact_lock(hashtext(?))").get(g);const i=await v(t),k=(await t.prepareUncached("SELECT table_name FROM information_schema.tables WHERE table_schema = ? AND table_type = 'BASE TABLE'").all(i)).map(e=>e.table_name),_=await y(t,i,k);_.tables.get("env_vars").primaryKey=["person","owner_kind","owner_id","name"],await t.exec("CREATE TEMP TABLE _rb (tbl text NOT NULL, k jsonb NOT NULL) ON COMMIT DROP");const T=await t.prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ?").all(n);for(const{table_name:e,inserted_keys:o}of T){const r=$(o);(e==="nodes"||e==="human_requests")&&R[e].push(...r.map(s=>s[0]));for(let s=0;s<r.length;s+=5e3)await t.prepare("INSERT INTO _rb SELECT ?, e FROM jsonb_array_elements(?::jsonb) e").run(e,JSON.stringify(r.slice(s,s+5e3)))}const b=new Set(T.map(e=>e.table_name));await t.exec("ANALYZE _rb");for(const e of _.foreignKeys){const o=_.tables.get(e.parent),r=_.tables.get(e.table);if(e.table==="import_node_files"||!b.has(e.parent)||o===void 0||r===void 0||e.parentColumns.join()!==o.primaryKey.join())continue;const s=b.has(e.table)?`AND NOT EXISTS (SELECT 1 FROM _rb o WHERE o.tbl = '${e.table}' AND ${m(r,S(r),"c","o.k")})`:"",p=Number((await t.prepareUncached(`SELECT count(*) AS n FROM ${a(i)}.${a(e.table)} c WHERE ${e.columns.map(C=>`c.${a(C)} IS NOT NULL`).join(" AND ")}
2
- AND EXISTS (SELECT 1 FROM _rb p WHERE p.tbl = '${e.parent}' AND ${m(r,e.columns,"c","p.k")}) ${s}`).get()).n);p>0&&(E.dependents[e.table]=(E.dependents[e.table]??0)+p)}for(const[e,o]of H){const r=_.tables.get(e);if(r===void 0||!r.columns.includes(o)||r.primaryKey.length===0)continue;const s=b.has(e)?`AND NOT EXISTS (SELECT 1 FROM _rb o WHERE o.tbl = '${e}' AND ${m(r,r.primaryKey,"c","o.k")})`:"",p=Number((await t.prepareUncached(`SELECT count(*) AS n FROM ${a(i)}.${a(e)} c WHERE c.${a(o)} IN (SELECT k ->> 0 FROM _rb WHERE tbl = 'objects') ${s}`).get()).n);p>0&&(E.dependents[`${e}.${o}`]=p)}const f=Number((await t.prepare("SELECT count(*) AS n FROM import_runs WHERE source_install_id = ? AND run_id <> ? AND created_at > ? AND (state IN ('loading', 'committed', 'done') OR (state = 'failed' AND committed_at IS NOT NULL))").get(c.source_install_id,n,c.created_at)).n);f>0&&(E.dependents.import_runs=f);const O=Number((await t.prepare("SELECT count(*) AS n FROM import_id_map m WHERE m.run_id <> ? AND m.kind = 'object' AND m.target_value IN (SELECT k ->> 0 FROM _rb WHERE tbl = 'objects')").get(n)).n);if(O>0&&(E.dependents.import_id_map=O),Object.keys(E.dependents).length>0)throw new L;const w=(await t.prepareUncached(`SELECT DISTINCT r.document FROM ${a(i)}.revisions r WHERE r.rev_id IN (SELECT k ->> 0 FROM _rb WHERE tbl = 'revisions')
3
- AND NOT EXISTS (SELECT 1 FROM _rb o WHERE o.tbl = 'objects' AND o.k ->> 0 = r.document)`).all()).map(e=>e.document);for(const e of F(_,[...b]).reverse()){const o=_.tables.get(e);if(o===void 0)continue;e==="run_events"&&await t.prepareUncached(`SELECT 1 FROM ${a(i)}.run_events t WHERE EXISTS (SELECT 1 FROM _rb k WHERE k.tbl = 'run_events' AND ${m(o,S(o),"t","k.k")}) ORDER BY t."run_id" COLLATE "C", t."sequence_number" FOR UPDATE`).all();const r=await t.prepareUncached(`DELETE FROM ${a(i)}.${a(e)} t WHERE EXISTS (SELECT 1 FROM _rb k WHERE k.tbl = '${e}' AND ${m(o,S(o),"t","k.k")})`).run();E.deleted[e]=r.changes}for(const e of w)await t.prepareUncached(`UPDATE ${a(i)}.documents d SET
1
+ var A=Object.defineProperty;var u=(n,d)=>A(n,"name",{value:d,configurable:!0});import{openDb as C,withCanvasWrite as h}from"../../canvas/db.js";import{keyMatch as l,q as a,readCatalog as D,rowKey as S,topologicalOrder as M}from"./catalog.js";import{deleteOwnedBlobs as g,deleteRunPrefix as W}from"./blobs.js";import{decodeKeys as $}from"./copy.js";import{IMPORT_ROLLBACK_LOCK as F}from"../../graph/deletion.js";import{OBJECT_ID_COLUMNS as H}from"./rewrite.js";import{targetSchema as y}from"./stage.js";class N extends Error{static{u(this,"Refused")}}async function Y(n,d){const c=await(await C()).prepare("SELECT source_install_id, source_kind, state, created_at FROM import_runs WHERE run_id = ?").get(n);if(c===void 0)throw new Error(`no import run ${n}`);if(c.state!=="done"&&c.state!=="committed"&&c.state!=="failed")throw new Error(`import run ${n} is ${c.state}, not rollbackable`);const E={run_id:n,rolled_back:!1,dependents:{},deleted:{}},R={nodes:[],human_requests:[]};try{await h(async t=>{await t.prepare("SELECT pg_advisory_xact_lock(hashtext(?))").get(F);const i=await y(t),L=(await t.prepareUncached("SELECT table_name FROM information_schema.tables WHERE table_schema = ? AND table_type = 'BASE TABLE'").all(i)).map(e=>e.table_name),_=await D(t,i,L);_.tables.get("env_vars").primaryKey=["person","owner_kind","owner_id","name"],await t.exec("CREATE TEMP TABLE _rb (tbl text NOT NULL, k jsonb NOT NULL) ON COMMIT DROP");const T=await t.prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ?").all(n);for(const{table_name:e,inserted_keys:o}of T){const r=$(o);(e==="nodes"||e==="human_requests")&&R[e].push(...r.map(s=>s[0]));for(let s=0;s<r.length;s+=5e3)await t.prepare("INSERT INTO _rb SELECT ?, e FROM jsonb_array_elements(?::jsonb) e").run(e,JSON.stringify(r.slice(s,s+5e3)))}const m=new Set(T.map(e=>e.table_name));await t.exec("ANALYZE _rb");for(const e of _.foreignKeys){const o=_.tables.get(e.parent),r=_.tables.get(e.table);if(e.table==="import_node_files"||!m.has(e.parent)||o===void 0||r===void 0||e.parentColumns.join()!==o.primaryKey.join())continue;const s=m.has(e.table)?`AND NOT EXISTS (SELECT 1 FROM _rb o WHERE o.tbl = '${e.table}' AND ${l(r,S(r),"c","o.k")})`:"",p=Number((await t.prepareUncached(`SELECT count(*) AS n FROM ${a(i)}.${a(e.table)} c WHERE ${e.columns.map(k=>`c.${a(k)} IS NOT NULL`).join(" AND ")}
2
+ AND EXISTS (SELECT 1 FROM _rb p WHERE p.tbl = '${e.parent}' AND ${l(r,e.columns,"c","p.k")}) ${s}`).get()).n);p>0&&(E.dependents[e.table]=(E.dependents[e.table]??0)+p)}for(const[e,o]of H){const r=_.tables.get(e);if(r===void 0||!r.columns.includes(o)||r.primaryKey.length===0)continue;const s=m.has(e)?`AND NOT EXISTS (SELECT 1 FROM _rb o WHERE o.tbl = '${e}' AND ${l(r,r.primaryKey,"c","o.k")})`:"",p=Number((await t.prepareUncached(`SELECT count(*) AS n FROM ${a(i)}.${a(e)} c WHERE c.${a(o)} IN (SELECT k ->> 0 FROM _rb WHERE tbl = 'objects') ${s}`).get()).n);p>0&&(E.dependents[`${e}.${o}`]=p)}const O=Number((await t.prepare("SELECT count(*) AS n FROM import_runs WHERE source_install_id = ? AND run_id <> ? AND created_at > ? AND (state IN ('loading', 'committed', 'done') OR (state = 'failed' AND committed_at IS NOT NULL))").get(c.source_install_id,n,c.created_at)).n);O>0&&(E.dependents.import_runs=O);const f=Number((await t.prepare("SELECT count(*) AS n FROM import_id_map m WHERE m.run_id <> ? AND m.kind = 'object' AND m.target_value IN (SELECT k ->> 0 FROM _rb WHERE tbl = 'objects')").get(n)).n);if(f>0&&(E.dependents.import_id_map=f),Object.keys(E.dependents).length>0)throw new N;const w=(await t.prepareUncached(`SELECT DISTINCT r.document FROM ${a(i)}.revisions r WHERE r.rev_id IN (SELECT k ->> 0 FROM _rb WHERE tbl = 'revisions')
3
+ AND NOT EXISTS (SELECT 1 FROM _rb o WHERE o.tbl = 'objects' AND o.k ->> 0 = r.document)`).all()).map(e=>e.document);for(const e of M(_,[...m]).reverse()){const o=_.tables.get(e);if(o===void 0)continue;e==="run_events"&&await t.prepareUncached(`SELECT 1 FROM ${a(i)}.run_events t WHERE EXISTS (SELECT 1 FROM _rb k WHERE k.tbl = 'run_events' AND ${l(o,S(o),"t","k.k")}) ORDER BY t."run_id" COLLATE "C", t."sequence_number" FOR UPDATE`).all();const r=await t.prepareUncached(`DELETE FROM ${a(i)}.${a(e)} t WHERE EXISTS (SELECT 1 FROM _rb k WHERE k.tbl = '${e}' AND ${l(o,S(o),"t","k.k")})`).run();E.deleted[e]=r.changes}for(const e of w)await t.prepareUncached(`UPDATE ${a(i)}.documents d SET
4
4
  heads_key = COALESCE((SELECT string_agg(r.rev_id, ',' ORDER BY r.rev_id) FROM ${a(i)}.revisions r WHERE r.document = d.object AND NOT EXISTS (SELECT 1 FROM ${a(i)}.revision_parents p WHERE p.parent = r.rev_id)), ''),
5
5
  revision = COALESCE((SELECT max(r.number) FROM ${a(i)}.revisions r WHERE r.document = d.object AND NOT EXISTS (SELECT 1 FROM ${a(i)}.revision_parents p WHERE p.parent = r.rev_id)), 0)
6
- WHERE d.object = ?`).run(e);await t.prepareUncached("DELETE FROM import_key_map km WHERE km.source_install_id = ? AND EXISTS (SELECT 1 FROM _rb r WHERE r.tbl = km.table_name AND r.k ->> 0 = km.target_key)").run(c.source_install_id),await t.prepare("DELETE FROM import_id_map WHERE run_id = ?").run(n),await t.prepare("DELETE FROM import_manifest WHERE run_id = ?").run(n),await t.prepare("UPDATE import_runs SET state = 'rolled_back', step = 'rolled_back', finished_at = ? WHERE run_id = ?").run(new Date().toISOString(),n),await U(t,c)})}catch(t){if(t instanceof L)return E;throw t}await d.delete(M.manifest(n));for(const t of N)await d.delete(t);return await W(d,R.nodes,R.human_requests),E.rolled_back=!0,E}u(Z,"rollbackRun");async function U(n,d){if(d.source_kind!=="machine")return;const l=await n.prepare("SELECT object FROM environments WHERE machine_id = ? AND kind = 'machine'").get(d.source_install_id);l!==void 0&&await n.prepare("UPDATE machine_credentials SET revoked_at = ? WHERE environment = ? AND revoked_at IS NULL").run(new Date().toISOString(),l.object)}u(U,"revokeFor");export{Z as rollbackRun};
6
+ WHERE d.object = ?`).run(e);await t.prepareUncached("DELETE FROM import_key_map km WHERE km.source_install_id = ? AND EXISTS (SELECT 1 FROM _rb r WHERE r.tbl = km.table_name AND r.k ->> 0 = km.target_key)").run(c.source_install_id),await t.prepare("DELETE FROM import_id_map WHERE run_id = ?").run(n),await t.prepare("DELETE FROM import_manifest WHERE run_id = ?").run(n),await t.prepare("UPDATE import_runs SET state = 'rolled_back', step = 'rolled_back', finished_at = ? WHERE run_id = ?").run(new Date().toISOString(),n),await v(t,c)})}catch(t){if(t instanceof N)return E;throw t}return await W(d,n),await g(d,R.nodes,R.human_requests),E.rolled_back=!0,E}u(Y,"rollbackRun");async function v(n,d){if(d.source_kind!=="machine")return;const b=await n.prepare("SELECT object FROM environments WHERE machine_id = ? AND kind = 'machine'").get(d.source_install_id);b!==void 0&&await n.prepare("UPDATE machine_credentials SET revoked_at = ? WHERE environment = ? AND revoked_at IS NULL").run(new Date().toISOString(),b.object)}u(v,"revokeFor");export{Y as rollbackRun};
@@ -1,3 +1,3 @@
1
- var z=Object.defineProperty;var u=(e,i)=>z(e,"name",{value:i,configurable:!0});import{zstdCompressSync as Q}from"node:zlib";import{blobStore as V}from"../../blobs/index.js";import{openDb as S,withCanvasWrite as M}from"../../canvas/db.js";import{insertImportedRevisions as X}from"../../graph/documents.js";import{getById as Z}from"../../graph/objects.js";import{bundleKeys as v,decodeRows as x,rowKeys as ee,SEQ_TABLES as te}from"../bundle/layout.js";import{readCatalog as ae}from"./catalog.js";import{copyRows as ne,decodeKeys as N,encodeKeys as L}from"./copy.js";import{pruneStaged as ie,precheck as se,renameClashingProfiles as re,rewriteConversationHeaders as oe,rewritePaths as de,rewriteRequestPaths as pe,takeRepoSyncedDocuments as ce}from"./prepare.js";import{boundSub as ue,checkSourcePerson as fe,checkStagedBlobKeys as le,checkStagedPersons as _e,checkStagedReferences as me,checkStagedRequestKeys as we}from"./bind.js";import{deleteBlobs as ge,deleteRunBlobs as be,moveRunBlobs as he}from"./blobs.js";import{dropStubRows as ye,findFleetGrant as Ee,grantMissing as Se,mapProfileIds as ve,renameClashingRepos as Re,rewriteIds as Oe,rewritePerson as Pe,scopeRepoIdentities as Te}from"./rewrite.js";import{dropStaging as B,ImportLaneError as w,stage as ke,stagingSchema as Ie,targetSchema as je}from"./stage.js";import{verifyRun as De}from"./verify.js";import{sandboxPathMap as Ae,writeNodeFiles as Ce}from"./path-map.js";import{allStoreKeys as Me,readPluginsStore as Ne,recordImportedActivations as Le,writeStores as Be}from"./stores.js";import{publishImportedPlugins as We}from"./publish-plugins.js";import{COPIED_TABLES as He}from"../bundle/layout.js";import{ClaimLostError as Ke}from"../../../daemon/reconcilers/row-claim.js";const W=10*6e4,Ue=30*6e4,R=u(()=>new Date().toISOString(),"now"),O=u(async(e,i)=>{await(await S()).prepare("UPDATE import_runs SET step = ? WHERE run_id = ?").run(i,e)},"setStep");async function Fe(e,i){const n=await e.get(v.source(i));if(n===null)throw new w("stage","bundle_invalid","source.json is missing");return JSON.parse(n.toString("utf8"))}u(Fe,"readSource");async function Je(e,i,n,r,s,d){const t=await e.get(v.rows(n.run_id,"grants")),_=t===null?[]:x(t),m=[];for(const a of _){const c=ue(a.sub,r,n.person,"grants.sub");await Ee(i,s,d,c,a.grantee)===void 0&&m.push(a.grantee)}if(m.length===0)return!0;if(n.loaded_at===void 0||n.loaded_at===null)throw new w("stage","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(n.loaded_at)>=W)throw Se(m);return!1}u(Je,"grantsReady");async function _t(e,i,n={}){const r=n.blobs??await V(),s=await S(),d=Ie(e.run_id),t=u(async a=>{await i.assertOwned(),await O(e.run_id,a),await n.atStep?.(a)},"at");let _=e.state==="committed";const m=[];try{const a=await Fe(r,e.run_id);if(e.source_kind==="machine"&&a.installId!==e.source_install_id)throw new w("stage","bundle_invalid",`source.json names install ${a.installId}, the run is for ${e.source_install_id}`);a.installId=e.source_install_id;const c=await je(s),P=[...He],g=await ae(s,c,[...P,"grants"]);if(!_){const f={},k=[],I=[],j=n.fleetRuntime??process.env.CRTR_RUNTIME??null;if(await fe(s,c,a.person,e.person),!await Je(r,s,e,a.person,c,j)){await i.assertOwned(),await O(e.run_id,"waiting_for_grants");return}await t("publish-plugins");const h=await We(await Ne(r,e.run_id));if(h.unavailable.length>0){if(e.loaded_at===void 0||e.loaded_at===null)throw new w("publish-plugins","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(e.loaded_at)>=W)throw new w("publish-plugins","directory_unavailable",`the directory did not answer for: ${h.unavailable.slice(0,10).join(", ")}; rerun the import once it is reachable`,{plugins:h.unavailable});await i.assertOwned(),await O(e.run_id,"waiting_for_directory");return}I.push(...h.refused),await t("stage");const K=await ke(s,e.run_id,a.counts,o=>ee(e.run_id,o,a),o=>r.get(o));for(const[o,p]of Object.entries(K))f[o]={staged:p,inserted:0,mapped:0,dropped:0};const l={db:s,schema:d,target:c,catalog:g,sourcePerson:a.person,targetPerson:e.person,fleetRuntime:j,shippedBodies:a.shippedBodies??{}};await t("bind-staged");for(const[o,p]of Object.entries(await _e(l)))y(f,o,p);for(const[o,p]of Object.entries(await le(l)))y(f,o,p);await t("rewrite-person"),await Pe(l),await Te(l),await t("prune");const U=await ie(s,d,g,a),E=a.kind==="hosted"?Ae(a.pathPrefixes??[]):[];await t("rewrite-paths"),await de(s,d,E),await oe(s,d,E,r,e.run_id),await pe(s,d),await we(l);const F=await ve(l);await re(s,d,c,a.installId,e.person),await t("rewrite-ids");const D=await Oe(l,F);await t("drop");const J=await ce(s,d,c),q=await ye(l);for(const[o,p]of Object.entries({...U}))y(f,o,p);for(const[o,p]of Object.entries(q))y(f,o,p);await me(l),await Re(l),await t("pre-check");const $=new Map([["messages",["seq"]],...te.map(o=>[o,["seq"]])]);await se(s,d,c,g,P,new Set,$),await t("blobs"),await he(s,d,c,e.person,r,e.run_id,m),await t("copy"),await M(async o=>{await i.assertOwned({extendLeaseMs:Ue});const p=await ne({db:o,runId:e.run_id,schema:d,target:c,catalog:g,source:a,person:e.person,idMap:D,pathMap:E}),A=await Ge(o,e.run_id,J);A>0&&(p.inserted.revisions=(p.inserted.revisions??0)+A),await Ce(o,d,e.run_id,a);const C=await Be({db:o,blobs:r,runId:e.run_id,person:e.person,objectMap:D.object});for(const[G,Y]of Object.entries(C.inserted))p.inserted[G]=Y.length;return k.push(...C.unresolvedPlugins),await o.prepare("UPDATE import_runs SET counts_json = ?, loaded_at = COALESCE(loaded_at, ?) WHERE run_id = ?").run(JSON.stringify({...$e(f,p),unresolved_plugins:k,refused_plugins:I}),R(),e.run_id),p}),_=!0,await n.atStep?.("committed")}await t("verify");const b=await De(s,e.run_id,d,c,g,a.installId);if(await s.prepare("UPDATE import_runs SET verify_json = ? WHERE run_id = ?").run(JSON.stringify(b),e.run_id),!b.ok)throw new w("verify","verify_failed","the committed rows differ from the staged rows or an invariant failed",{differences:b.differences,invariants:b.invariants});await t("manifest");const T=v.manifest(e.run_id);await r.put(T,await Ye(e.run_id)),await B(s,e.run_id);for(const f of Me(e.run_id))await r.delete(f);await be(r,e.run_id),await M(async f=>{await Le(f,e.run_id,e.person),await f.prepare("UPDATE import_runs SET state = 'done', step = 'done', manifest_key = ?, finished_at = ? WHERE run_id = ?").run(T,R(),e.run_id)})}catch(a){if(a instanceof Ke)throw a;const c=qe(a);await B(s,e.run_id).catch(()=>{}),_||await ge(r,m,!0),await s.prepare("UPDATE import_runs SET state = 'failed', failure_json = ?, finished_at = ? WHERE run_id = ?").run(JSON.stringify(c),R(),e.run_id)}}u(_t,"processRun");function qe(e){if(e instanceof w)return{step:e.step,code:e.code,message:e.message,...e.detail===void 0?{}:{detail:e.detail}};const i=e.code;return{step:"unknown",code:typeof i=="string"?i:"import_failed",message:e instanceof Error?e.message:String(e)}}u(qe,"failureOf");function y(e,i,n){(e[i]??={staged:0,inserted:0,mapped:0,dropped:0}).dropped+=n}u(y,"addDropped");function $e(e,i){for(const[n,r]of Object.entries(i.inserted))(e[n]??={staged:0,inserted:0,mapped:0,dropped:0}).inserted=r;for(const[n,r]of Object.entries(i.mapped))(e[n]??={staged:0,inserted:0,mapped:0,dropped:0}).mapped=r;return e}u($e,"withInserted");async function Ge(e,i,n){const r=new Set((await e.prepareUncached("SELECT rev_id FROM revisions WHERE rev_id IN (SELECT jsonb_array_elements_text(?::jsonb))").all(JSON.stringify(n.map(t=>t.rev_id)))).map(t=>t.rev_id)),s=n.filter(t=>!r.has(t.rev_id)),d=new Map;for(const t of n)d.set(t.document,[...d.get(t.document)??[],t]);for(const[t,_]of d){const m=await Z(e,t);m!==null&&await X(e,m,_.map(a=>({rev_id:a.rev_id,parents:a.parents,body_hash:a.body_hash,rationale:a.rationale,created_at:a.created_at})))}return await H(e,i,"revisions",s.map(t=>[t.rev_id])),await H(e,i,"revision_parents",s.flatMap(t=>t.parents.map(_=>[t.rev_id,_]))),s.length}u(Ge,"arrive");async function H(e,i,n,r){if(r.length===0)return;const s=await e.prepare("SELECT inserted_keys FROM import_manifest WHERE run_id = ? AND table_name = ?").get(i,n);s===void 0?await e.prepare("INSERT INTO import_manifest (run_id, table_name, inserted_keys) VALUES (?, ?, ?)").run(i,n,L(r)):await e.prepare("UPDATE import_manifest SET inserted_keys = ? WHERE run_id = ? AND table_name = ?").run(L([...N(s.inserted_keys),...r]),i,n)}u(H,"appendManifest");async function Ye(e){const n=await(await S()).prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ? ORDER BY table_name").all(e);return Q(Buffer.from(n.map(r=>JSON.stringify({table:r.table_name,keys:N(r.inserted_keys)})).join(`
1
+ var z=Object.defineProperty;var c=(e,i)=>z(e,"name",{value:i,configurable:!0});import{zstdCompressSync as Q}from"node:zlib";import{blobStore as V}from"../../blobs/index.js";import{openDb as S,withCanvasWrite as M}from"../../canvas/db.js";import{insertImportedRevisions as X}from"../../graph/documents.js";import{getById as Z}from"../../graph/objects.js";import{bundleKeys as v,decodeRows as x,rowKeys as ee,SEQ_TABLES as te}from"../bundle/layout.js";import{readCatalog as ae}from"./catalog.js";import{copyRows as ne,decodeKeys as N,encodeKeys as L}from"./copy.js";import{pruneStaged as ie,precheck as se,renameClashingProfiles as re,rewriteConversationHeaders as oe,rewritePaths as de,rewriteRequestPaths as pe,takeRepoSyncedDocuments as ue}from"./prepare.js";import{boundSub as ce,checkSourcePerson as fe,checkStagedBlobKeys as le,checkStagedPersons as _e,checkStagedReferences as me,checkStagedRequestKeys as we}from"./bind.js";import{deleteBlobs as ge,deleteRunBlobs as be,deleteRunPrefix as he,moveRunBlobs as Ee}from"./blobs.js";import{dropStubRows as ye,findFleetGrant as Se,grantMissing as ve,mapProfileIds as Re,renameClashingRepos as Oe,rewriteIds as Pe,rewritePerson as Te,scopeRepoIdentities as ke}from"./rewrite.js";import{dropStaging as B,ImportLaneError as w,stage as Ie,stagingSchema as je,targetSchema as De}from"./stage.js";import{verifyRun as Ae}from"./verify.js";import{sandboxPathMap as Ce,writeNodeFiles as Me}from"./path-map.js";import{allStoreKeys as Ne,readPluginsStore as Le,recordImportedActivations as Be,writeStores as We}from"./stores.js";import{publishImportedPlugins as He}from"./publish-plugins.js";import{COPIED_TABLES as Ke}from"../bundle/layout.js";import{ClaimLostError as Ue}from"../../../daemon/reconcilers/row-claim.js";const W=10*6e4,Fe=30*6e4,R=c(()=>new Date().toISOString(),"now"),O=c(async(e,i)=>{await(await S()).prepare("UPDATE import_runs SET step = ? WHERE run_id = ?").run(i,e)},"setStep");async function Je(e,i){const n=await e.get(v.source(i));if(n===null)throw new w("stage","bundle_invalid","source.json is missing");return JSON.parse(n.toString("utf8"))}c(Je,"readSource");async function qe(e,i,n,r,s,d){const t=await e.get(v.rows(n.run_id,"grants")),l=t===null?[]:x(t),m=[];for(const a of l){const u=ce(a.sub,r,n.person,"grants.sub");await Se(i,s,d,u,a.grantee)===void 0&&m.push(a.grantee)}if(m.length===0)return!0;if(n.loaded_at===void 0||n.loaded_at===null)throw new w("stage","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(n.loaded_at)>=W)throw ve(m);return!1}c(qe,"grantsReady");async function mt(e,i,n={}){const r=n.blobs??await V(),s=await S(),d=je(e.run_id),t=c(async a=>{await i.assertOwned(),await O(e.run_id,a),await n.atStep?.(a)},"at");let l=e.state==="committed";const m=[];try{const a=await Je(r,e.run_id);if(e.source_kind==="machine"&&a.installId!==e.source_install_id)throw new w("stage","bundle_invalid",`source.json names install ${a.installId}, the run is for ${e.source_install_id}`);a.installId=e.source_install_id;const u=await De(s),P=[...Ke],g=await ae(s,u,[...P,"grants"]);if(!l){const f={},k=[],I=[],j=n.fleetRuntime??process.env.CRTR_RUNTIME??null;if(await fe(s,u,a.person,e.person),!await qe(r,s,e,a.person,u,j)){await i.assertOwned(),await O(e.run_id,"waiting_for_grants");return}await t("publish-plugins");const h=await He(await Le(r,e.run_id));if(h.unavailable.length>0){if(e.loaded_at===void 0||e.loaded_at===null)throw new w("publish-plugins","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(e.loaded_at)>=W)throw new w("publish-plugins","directory_unavailable",`the directory did not answer for: ${h.unavailable.slice(0,10).join(", ")}; rerun the import once it is reachable`,{plugins:h.unavailable});await i.assertOwned(),await O(e.run_id,"waiting_for_directory");return}I.push(...h.refused),await t("stage");const K=await Ie(s,e.run_id,a.counts,o=>ee(e.run_id,o,a),o=>r.get(o));for(const[o,p]of Object.entries(K))f[o]={staged:p,inserted:0,mapped:0,dropped:0};const _={db:s,schema:d,target:u,catalog:g,sourcePerson:a.person,targetPerson:e.person,fleetRuntime:j,shippedBodies:a.shippedBodies??{}};await t("bind-staged");for(const[o,p]of Object.entries(await _e(_)))E(f,o,p);for(const[o,p]of Object.entries(await le(_)))E(f,o,p);await t("rewrite-person"),await Te(_),await ke(_),await t("prune");const U=await ie(s,d,g,a),y=a.kind==="hosted"?Ce(a.pathPrefixes??[]):[];await t("rewrite-paths"),await de(s,d,y),await oe(s,d,y,r,e.run_id),await pe(s,d),await we(_);const F=await Re(_);await re(s,d,u,a.installId,e.person),await t("rewrite-ids");const D=await Pe(_,F);await t("drop");const J=await ue(s,d,u),q=await ye(_);for(const[o,p]of Object.entries({...U}))E(f,o,p);for(const[o,p]of Object.entries(q))E(f,o,p);await me(_),await Oe(_),await t("pre-check");const $=new Map([["messages",["seq"]],...te.map(o=>[o,["seq"]])]);await se(s,d,u,g,P,new Set,$),await t("blobs"),await Ee(s,d,u,e.person,r,e.run_id,m),await t("copy"),await M(async o=>{await i.assertOwned({extendLeaseMs:Fe});const p=await ne({db:o,runId:e.run_id,schema:d,target:u,catalog:g,source:a,person:e.person,idMap:D,pathMap:y}),A=await Ye(o,e.run_id,J);A>0&&(p.inserted.revisions=(p.inserted.revisions??0)+A),await Me(o,d,e.run_id,a);const C=await We({db:o,blobs:r,runId:e.run_id,person:e.person,objectMap:D.object});for(const[G,Y]of Object.entries(C.inserted))p.inserted[G]=Y.length;return k.push(...C.unresolvedPlugins),await o.prepare("UPDATE import_runs SET counts_json = ?, loaded_at = COALESCE(loaded_at, ?) WHERE run_id = ?").run(JSON.stringify({...Ge(f,p),unresolved_plugins:k,refused_plugins:I}),R(),e.run_id),p}),l=!0,await n.atStep?.("committed")}await t("verify");const b=await Ae(s,e.run_id,d,u,g,a.installId);if(await s.prepare("UPDATE import_runs SET verify_json = ? WHERE run_id = ?").run(JSON.stringify(b),e.run_id),!b.ok)throw new w("verify","verify_failed","the committed rows differ from the staged rows or an invariant failed",{differences:b.differences,invariants:b.invariants});await t("manifest");const T=v.manifest(e.run_id);await r.put(T,await ze(e.run_id)),await B(s,e.run_id);for(const f of Ne(e.run_id))await r.delete(f);await be(r,e.run_id),await M(async f=>{await Be(f,e.run_id,e.person),await f.prepare("UPDATE import_runs SET state = 'done', step = 'done', manifest_key = ?, finished_at = ? WHERE run_id = ?").run(T,R(),e.run_id)})}catch(a){if(a instanceof Ue)throw a;const u=$e(a);await B(s,e.run_id).catch(()=>{}),l||await ge(r,m,!0),await s.prepare("UPDATE import_runs SET state = 'failed', failure_json = ?, finished_at = ? WHERE run_id = ?").run(JSON.stringify(u),R(),e.run_id),await he(r,e.run_id,{keepNodeFiles:l,bestEffort:!0})}}c(mt,"processRun");function $e(e){if(e instanceof w)return{step:e.step,code:e.code,message:e.message,...e.detail===void 0?{}:{detail:e.detail}};const i=e.code;return{step:"unknown",code:typeof i=="string"?i:"import_failed",message:e instanceof Error?e.message:String(e)}}c($e,"failureOf");function E(e,i,n){(e[i]??={staged:0,inserted:0,mapped:0,dropped:0}).dropped+=n}c(E,"addDropped");function Ge(e,i){for(const[n,r]of Object.entries(i.inserted))(e[n]??={staged:0,inserted:0,mapped:0,dropped:0}).inserted=r;for(const[n,r]of Object.entries(i.mapped))(e[n]??={staged:0,inserted:0,mapped:0,dropped:0}).mapped=r;return e}c(Ge,"withInserted");async function Ye(e,i,n){const r=new Set((await e.prepareUncached("SELECT rev_id FROM revisions WHERE rev_id IN (SELECT jsonb_array_elements_text(?::jsonb))").all(JSON.stringify(n.map(t=>t.rev_id)))).map(t=>t.rev_id)),s=n.filter(t=>!r.has(t.rev_id)),d=new Map;for(const t of n)d.set(t.document,[...d.get(t.document)??[],t]);for(const[t,l]of d){const m=await Z(e,t);m!==null&&await X(e,m,l.map(a=>({rev_id:a.rev_id,parents:a.parents,body_hash:a.body_hash,rationale:a.rationale,created_at:a.created_at})))}return await H(e,i,"revisions",s.map(t=>[t.rev_id])),await H(e,i,"revision_parents",s.flatMap(t=>t.parents.map(l=>[t.rev_id,l]))),s.length}c(Ye,"arrive");async function H(e,i,n,r){if(r.length===0)return;const s=await e.prepare("SELECT inserted_keys FROM import_manifest WHERE run_id = ? AND table_name = ?").get(i,n);s===void 0?await e.prepare("INSERT INTO import_manifest (run_id, table_name, inserted_keys) VALUES (?, ?, ?)").run(i,n,L(r)):await e.prepare("UPDATE import_manifest SET inserted_keys = ? WHERE run_id = ? AND table_name = ?").run(L([...N(s.inserted_keys),...r]),i,n)}c(H,"appendManifest");async function ze(e){const n=await(await S()).prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ? ORDER BY table_name").all(e);return Q(Buffer.from(n.map(r=>JSON.stringify({table:r.table_name,keys:N(r.inserted_keys)})).join(`
2
2
  `)+`
3
- `))}u(Ye,"manifestFile");export{Ue as COPY_LEASE_MS,W as GRANT_WAIT_MS,_t as processRun};
3
+ `))}c(ze,"manifestFile");export{Fe as COPY_LEASE_MS,W as GRANT_WAIT_MS,mt as processRun};
@@ -1,3 +1,3 @@
1
- var Ke=Object.defineProperty;var l=(e,t)=>Ke(e,"name",{value:t,configurable:!0});import{randomUUID as Ue}from"node:crypto";import{streamSimple as Be}from"@earendil-works/pi-ai/compat";import{keyRouteProviders as Je,probeRouteAvailability as We}from"../model-routes-pool.js";import{KEY_CREDENTIAL_SOURCE as He,parseModelSpec as ze}from"../model-routes.js";import{openModelRegistry as Xe}from"../runtime/model-registry.js";import{isInvalidRefreshTokenError as Ge}from"../managed-providers.js";import{MAX_RATE_LIMIT_COOLDOWN_MS as Ae,coolingUntilFor as je,isManagedProvider as H,markSubscriptionRateLimited as Ve,markSubscriptionSuccess as Ye,readSubscriptionPool as Ze,retryAfterMsFromHeaders as he,retryAfterMsFromError as Qe,refreshSubscriptionCredential as et,subscriptionNeedsSuccessWrite as tt,vendorRateLimit as nt,RefreshBusyError as ot,RefreshTimeoutError as rt}from"../subscription-state.js";import{describeRateLimitScope as Me,rateLimitHeaders as it}from"../rate-limit-scope.js";import{RunError as i}from"../runs/operations.js";import{recognizeProviderError as _e}from"../provider-error-recognition.js";import{isSafetyRefusal as at}from"./refusal.js";import{findRefusal as st,payerOf as $e,refusalError as dt,refusedMark as lt,writeCharge as ye}from"../ledger/index.js";import{storedApiKey as Se}from"../auth-file.js";import{eligibleHostedEndpoint as ut,readHostedEndpoint as Ce}from"../grants/hosted-endpoint.js";import{parseProviderPayment as ct}from"../provider-failure.js";import{personIdAsync as ft}from"../canvas/person.js";import{getNode as Ee}from"../canvas/canvas.js";import{outboundToken as Ie}from"../providers/mint.js";import{discardFile as Oe}from"../providers/token-cache.js";import{ProviderError as mt}from"../providers/errors.js";import{appCandidates as pt}from"./app-rungs.js";import{hostedRoute as ht,matchesFeatures as _t,ownerCandidates as yt}from"./owner-candidates.js";function gt(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(gt,"validContent");function Ne(e){return Array.isArray(e)?e.map(t=>{if(t.type==="text")return t;const[,o,a]=/^data:(image\/(?:png|jpeg|gif|webp));base64,(.*)$/.exec(t.image_url.url);return{type:"image",mimeType:o,data:a}}):e??""}l(Ne,"imageContent");function wt(e,t){const o=(e instanceof Error?e.message:String(e)).split("; stack=",1)[0],a=_e({message:o}).kind;return a!=="connection"&&a!=="connection-only"?e:new i(503,"upstream_model_unavailable",o.slice(0,500),void 0,{served_model:t})}l(wt,"refreshFailure");async function bt(e,t,o,a,s){if(o.expires>Date.now())return o.access;const j=e.getProvider(t)?.auth.oauth;if(!j)throw new i(503,"upstream_model_unavailable",`no OAuth refresh for ${t}`,void 0,{served_model:a});return(await et(t,o.label,async(r,p)=>{const y=await j.refresh({type:"oauth",refresh:r,access:"",expires:0,...p?{clientId:p}:{}},s??new AbortController().signal).catch(x=>{throw wt(x,a)}),k=y.clientId;return{refresh:y.refresh,access:y.access,expires:y.expires,...typeof k=="string"&&k?{clientId:k}:{}}}).catch(r=>{throw r instanceof ot||r instanceof rt?new i(503,"upstream_model_unavailable",r.message,void 0,{served_model:a}):r})).access}l(bt,"freshSubscriptionAccess");function Qt(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)&&gt(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(a=>a&&typeof a.id=="string"&&typeof a.function?.name=="string"&&typeof a.function.arguments=="string"&&vt(a.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,a]of[["temperature",t.temperature],["top_p",t.top_p],["max_tokens",t.max_tokens]])if(a!==void 0&&(typeof a!="number"||!Number.isFinite(a)||o==="temperature"&&(a<0||a>2)||o==="top_p"&&(a<0||a>1)||o==="max_tokens"&&(!Number.isSafeInteger(a)||a<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(Qt,"parseLlmRequest");function vt(e){try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)}catch{return!1}}l(vt,"isJsonObject");function kt(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??""}]:Ne(r.content),isError:!1,timestamp:t}:r.role==="assistant"?{role:"assistant",content:[...r.content?[{type:"text",text:r.content}]:[],...(r.tool_calls??[]).map(p=>({type:"toolCall",id:p.id,name:p.function.name,arguments:JSON.parse(p.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:Ne(r.content),timestamp:t}),a=o.findIndex(r=>r.role!=="system"),s=o.slice(0,a<0?o.length:a).map(r=>r.content),j=s.join(`
1
+ var Je=Object.defineProperty;var l=(e,t)=>Je(e,"name",{value:t,configurable:!0});import{randomUUID as We}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,a]=/^data:(image\/(?:png|jpeg|gif|webp));base64,(.*)$/.exec(t.image_url.url);return{type:"image",mimeType:o,data:a}}):e??""}l(Fe,"imageContent");function vt(e,t){const o=(e instanceof Error?e.message:String(e)).split("; stack=",1)[0],a=ye({message:o}).kind;return a!=="connection"&&a!=="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,a,s){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:a});return(await nt(t,o.label,async(r,h)=>{const g=await M.refresh({type:"oauth",refresh:r,access:"",expires:0,...h?{clientId:h}:{}},s??new AbortController().signal).catch(R=>{throw vt(R,a)}),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:a}):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(a=>a&&typeof a.id=="string"&&typeof a.function?.name=="string"&&typeof a.function.arguments=="string"&&xt(a.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,a]of[["temperature",t.temperature],["top_p",t.top_p],["max_tokens",t.max_tokens]])if(a!==void 0&&(typeof a!="number"||!Number.isFinite(a)||o==="temperature"&&(a<0||a>2)||o==="top_p"&&(a<0||a>1)||o==="max_tokens"&&(!Number.isSafeInteger(a)||a<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}),a=o.findIndex(r=>r.role!=="system"),s=o.slice(0,a<0?o.length:a).map(r=>r.content),M=s.join(`
2
2
 
3
- `),K=e.tools?.map(({function:r})=>({name:r.name,description:r.description??"",parameters:r.parameters??{type:"object",properties:{}}}));return{...j?{systemPrompt:j}:{},messages:o.slice(s.length),...K?{tools:K}:{}}}l(kt,"contextOf");function xt(e){return ct(e?.payment)}l(xt,"paymentOf");function Rt(e,t){const o=e.find("anthropic",t);if(o)return o;const a=e.getAll().find(s=>s.provider==="anthropic"&&s.api==="anthropic-messages");return a?{...a,id:t,name:t}:void 0}l(Rt,"hostedModel");function qt(e,t){const{input:o,output:a,cacheRead:s,cacheWrite:j}=e.cost;return o===0&&a===0&&s===0&&j===0?null:Number.isFinite(t)&&t>=0?t:null}l(qt,"usdEquivalent");function At(e,t){return e.compat?.allowedFallbackModels?.find(a=>a.provider===e.provider&&a.model===t)}l(At,"allowedFallback");function en(e){return e?{payer:e.payer??"user",sub:e.sub,grantee:e.grantee,inference_endpoint:e.inference_endpoint??null}:void 0}l(en,"llmCallerOf");function De(e){return e instanceof mt?e.code==="server_error"?new i(503,"upstream_model_unavailable",e.message):new i(404,"model_unavailable",e.message):e}l(De,"mintFailure");const jt=/\bmodel is not supported when using Codex with a ChatGPT account\b/i;function Mt(e,t,o){if(!(e!=="openai-codex"||t===void 0||!jt.test(t)))return new i(404,"model_unavailable",t,void 0,{served_model:o})}l(Mt,"codexAccountModelRejection");function $t(e){return e.get("request-id")??e.get("x-request-id")}l($t,"vendorRequestId");async function tn(e,t,o,a,s,j,K){const r=j?.payer==="app"?j: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 p=r?.inference_endpoint??void 0,y=s===void 0?null:r?.sub??s.sub??await ft(),k=await Xe();let x;p?(x=pt(p,e.model,e.model_policy==="exact").flatMap((v,g)=>{const M=ze(v.model);return M?[{routeId:"app",credentialSource:"app",family:"app",strength:v.strength,...M,rank:g}]:[]}),x=x.filter(v=>_t(k,e,v))):x=await yt(k,e,a);const oe=!p&&s!==void 0&&y!==null?await ut():null,re=oe===null?void 0:ht(e,x,oe),Te=re?oe:null;re&&(x=[...x,re]);const Fe=p?new Set:Je(),ge=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 Ce())?.payment_setup_url??null,reset_at:null}}),"nothingLeft");if(x.length===0)throw e.model_policy==="exact"?new i(400,"substitution_refused","no eligible model route is configured"):p?new i(404,"model_unavailable","no eligible model route is configured"):await ge();const U=`chatcmpl-${Ue()}`;let N=1/0,z=1/0,ie,b,ae,se;const de=l(async()=>K??(s?.node?(await Ee(s.node))?.caused_by??null:null)??(s?.run?(await Ee(s.run))?.caused_by??null:null),"causeOf");for(const v of x){const g=v.credentialSource==="hosted";if(!r&&!g&&!(await We(v,k)).authenticated)continue;const M=g?Rt(k,v.modelId):k.find(v.providerId,v.modelId);if(!M)continue;const B=g?Te.base_url:void 0,c=p?{...M,baseUrl:`${p.base_url}/${M.provider}`}:B?{...M,baseUrl:`${B}/anthropic`,compat:{...M.compat,allowedFallbackModels:void 0}}:M,h=v.providerId,X=v.credentialSource===He&&H(h),le=!r&&!g&&!X&&H(h)?await Ze(h):[],J=le.filter($=>!$.authFailure),we=J.filter($=>je($,c.id)<=Date.now()),D=X?await Se(h):Fe.has(h)?void 0:le.length?await Se(h):void 0;if(X&&D===void 0||le.length>0&&J.length===0&&D===void 0)continue;if(J.length&&!we.length&&D===void 0){const $=Math.min(...J.map(E=>je(E,c.id)));$<N&&(N=$,ae=`${c.provider}/${c.id}`);continue}const be=r||g?[void 0,void 0]:X?["key"]:J.length||D!==void 0?[...we,...D!==void 0?["key"]:[]]:[void 0];let ve=!1;for(const[$,E]of be.entries()){if(ve&&E!=="key")continue;const w=E==="key"?void 0:E,ke=E==="key",G=Date.now();let xe=w?.access;if(w&&w.expires<=Date.now()&&H(h))try{xe=await bt(k,h,w,`${c.provider}/${c.id}`,t)}catch(n){if(!Ge(n))throw n;ie??=n;continue}const Pe=kt(e),T=w||r||g||ke?void 0:await k.getApiKeyAndHeaders(c);if(T&&!T.ok)continue;const u=`${c.provider}/${c.id}`,F=e.model??u,R=g?y===null?null:{payer:y,funding:"endpoint"}:r?$e({call:"model",route:"endpoint",grantee:r.grantee}):y===null?null:$e({call:"model",route:w?"subscription":"key",sub:y});if(s!==void 0&&R!==null){const n=await st({scope:"call",payer:R.payer,funding:R.funding,sub:y,grantee:s.grantee,provider:h});if(n!==null){if(await ye({request:s.request??U,kind:"model",what:u,usd:null,payer:R.payer,funding:R.funding,sub:y,grantee:s.grantee,node:s.node??null,run:s.run??null,provider:h,causedBy:await de(),refused:lt(n)}),se??=n,E!=="key"&&be.includes("key")){ve=!0;continue}break}}let I;if(r&&p)try{I=await Ie({audience:p.base_url,sub:r.sub,grantee:r.grantee,initiating_app:r.grantee,scope:["crtr:llm"]},{signal:t})}catch(n){throw De(n)}if(B)try{I=await Ie({audience:B,sub:y,grantee:s.grantee,initiating_app:s.grantee,scope:["crtr:llm"]},{signal:t})}catch(n){throw De(n)}let P=null,Re=!1,_,W,V,S=!1,q,Y=null,A=3e4,L;const ue=[],ce=[],Z=[];let d,O;const Q=l((n,f=null)=>({id:U,object:"chat.completion.chunk",created:Math.floor(G/1e3),model:u,served_model:u,requested_model:F,substituted:F!==u&&!/^([^/]+)\/(ultra|strong|medium|light)$/.test(F),choices:[{index:0,delta:n,finish_reason:f}]}),"chunk"),ee=l(n=>{ue.push(n),o?.(n)},"emit"),Le=Be(c,Pe,{apiKey:I?.access_token??xe??(ke?D:void 0)??(T?.ok?T.apiKey:void 0),...T?.ok?{headers:T.headers}:{},signal:t,reasoning:e.reasoning_effort??v.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(q=m.status,Y=$t(m.headers)??Y,g){if(P=m.headers.get("crtr-charge-id")?.trim()||null,m.ok&&!P)throw Re=!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&&(V=xt(await m.clone().json().catch(()=>{}))),m}return m.status===429&&(S=!0,L=m.headers,A=he(m.headers)??15e3),m},"fetch"),onProviderStreamEvent:l(n=>{g&&n!==null&&typeof n=="object"&&"type"in n&&n.type==="message_stop"&&"crtr_charge"in n&&(_=n.crtr_charge)},"onProviderStreamEvent"),onResponse:l(n=>{!g&&n.status===429&&(S=!0,L=n.headers,A=he(n.headers)??15e3)},"onResponse")});try{for await(const n of Le)n.type==="text_delta"&&(ce.push(n.delta),ee(Q({content:n.delta}))),n.type==="thinking_delta"&&(Z.push(n.delta),ee(Q({reasoning_content:n.delta}))),n.type==="done"&&(d=n.message),n.type==="error"&&(d=n.error)}catch(n){const f=Qe(n);L===void 0&&n&&typeof n=="object"&&"headers"in n&&Object.keys(it(n.headers)).length&&(L=n.headers);const m=_e({status:n&&typeof n=="object"&&"status"in n?n.status:void 0,message:n instanceof Error?n.message:String(n)});if(r||g)O=n;else{if(!S&&m.kind!=="rate-limit")throw ue.length?new i(503,"upstream_model_unavailable",n instanceof Error?n.message:String(n),void 0,{served_model:u}):n;S=!0,A=f??A}}if(g){if(Re)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(q===402&&V)throw new i(402,"payment_refused",V.message,void 0,{payment:V,served_model:u});if(q===401){if(I&&Oe(I.key),$===0)continue;throw new i(404,"model_unavailable",`${B} refuses this runtime's tokens`,void 0,{served_model:u})}if(O!==void 0||q!==void 0&&q>=400||d?.stopReason==="error"||d?.stopReason==="aborted"){const f=O instanceof Error?O.message:d?.errorMessage??`the inference endpoint answered ${q??"with an error"}`;throw q===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(_===null||typeof _!="object"||!("id"in _)||_.id!==P||!("served_model"in _)||typeof _.served_model!="string"||!_.served_model.trim()||!("list_usd"in _)||typeof _.list_usd!="number"||!Number.isFinite(_.list_usd)||_.list_usd<0||Number(_.list_usd.toFixed(6))!==_.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:P});W={id:P,served_model:_.served_model,list_usd:_.list_usd}}if(r){if(q===401){if(I&&Oe(I.key),$===0)continue;throw new i(404,"model_unavailable",`${p.base_url} refuses this runtime's tokens`,void 0,{served_model:u})}if(S&&he(L)===void 0)throw new i(503,"upstream_model_unavailable",`${u} was rate-limited without a retry-after`,void 0,{served_model:u});if(!S&&(O!==void 0||q!==void 0&&q>=500))throw new i(503,"upstream_model_unavailable",O instanceof Error?O.message:d?.errorMessage??"inference endpoint failed",void 0,{served_model:u})}if(!S&&d?.stopReason==="error"&&_e({message:d.errorMessage}).kind==="rate-limit"&&(S=!0,A=15e3),S){const n=nt(L,c.id,A),{observation:f,vendorReset:m}=n;if(A=n.retryMs,b={provider:h,model:c.id,...w?{account:w.label}:{},observation:f},console.error(`[llm] 429 from ${u}${w?` account "${w.label}"`:""}: scope=${Me(f.scope)} retry_after_ms=${A} headers=${JSON.stringify(f.headers)}`),w&&H(h)&&await Ve(h,w.label,A,G,Date.now(),f.scope),m!==void 0&&(z=Math.min(z,m)),Date.now()+Math.min(A,Ae)<N&&(N=Date.now()+Math.min(A,Ae),ae=u),ce.length||Z.length)throw new i(503,"service_unavailable","vendor rate limit after output began",void 0,{served_model:u});if(r)break;continue}const te=at(d);if(q===400&&e.tool_choice!==void 0&&e.tool_choice!=="auto"&&e.tool_choice!=="none"&&/\btool[_ ]choice\b/i.test(d?.errorMessage??"")&&/not supported|does not support|unsupported|cannot|must be auto/i.test(d?.errorMessage??""))throw new i(400,"invalid_request",d.errorMessage,"tool_choice",{served_model:u});if(d?.stopReason==="error"){const n=Mt(c.provider,d.errorMessage,u);if(n)throw n}if(!d||d.stopReason==="error"&&!te||d.stopReason==="aborted")throw new i(503,"upstream_model_unavailable",d?.errorMessage??"model request failed",void 0,{served_model:u});w&&H(h)&&tt(w,c.id)&&await Ye(h,w.label,G,c.id);const fe=d.content.filter(n=>n.type==="toolCall").map(n=>({id:n.id,type:"function",function:{name:n.name,arguments:JSON.stringify(n.arguments)}})),me=te?"content_filter":d.stopReason==="toolUse"?"tool_calls":d.stopReason==="length"?"length":"stop",pe=d.responseModel?At(c,d.responseModel):void 0,C=W?`${c.provider}/${W.served_model}`:pe?`${c.provider}/${pe.model}`:u,ne={prompt_tokens:d.usage.input,completion_tokens:d.usage.output,total_tokens:d.usage.totalTokens,cache_read_tokens:d.usage.cacheRead,cache_write_tokens:d.usage.cacheWrite,usd_equivalent:W?W.list_usd:qt(pe??c,d.usage.cost.total),served_model:C};g?s!==void 0&&R!==null&&await ye({id:P,request:s.request??U,kind:"model",what:C,usd:ne.usd_equivalent,payer:R.payer,funding:R.funding,sub:y,grantee:s.grantee,node:s.node??null,run:s.run??null,provider:h,causedBy:await de(),vendorRef:Y}):s!==void 0&&R!==null&&await ye({request:s.request??U,kind:"model",what:C,units:{input:d.usage.input,output:d.usage.output,cache_read:d.usage.cacheRead,cache_write:d.usage.cacheWrite},usd:ne.usd_equivalent,payer:R.payer,funding:R.funding,sub:y,grantee:s.grantee,node:s.node??null,run:s.run??null,provider:h,causedBy:await de(),vendorRef:Y});const qe={id:U,object:"chat.completion",created:Math.floor(G/1e3),model:C,served_model:C,requested_model:F,substituted:F!==C&&!/^([^/]+)\/(ultra|strong|medium|light)$/.test(F),choices:[{index:0,message:{role:"assistant",content:ce.join("")||null,...Z.length?{reasoning_content:Z.join("")}:{},...fe.length?{tool_calls:fe}:{},...te?{refusal:d.errorMessage??"Content filtered"}:{}},finish_reason:me}],usage:ne,...e.metadata!==void 0?{metadata:e.metadata}:{}};for(const[n,f]of fe.entries())ee(Q({tool_calls:[{index:n,...f}]}));return ee({...Q({},me),model:C,served_model:C,substituted:qe.substituted,...te?{choices:[{index:0,delta:{},finish_reason:me,message:{refusal:d.errorMessage??"Content filtered"}}]}:{},usage:ne}),{completion:qe,chunks:ue}}}throw se!==void 0?dt(se):N!==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 Ce())?.payment_setup_url??null,reset_at:z===1/0?null:new Date(z).toISOString()},retry_after_s:Math.max(1,Math.ceil((N-Date.now())/1e3)),served_model:b?`${b.provider}/${b.model}`:ae,...b?{rate_limit:{provider:b.provider,model:b.model,...b.account?{account:b.account}:{},scope:Me(b.observation.scope),...b.observation.claim?{claim:b.observation.claim}:{},headers:b.observation.headers}}:{}},void 0,!0):ie!==void 0?ie:e.model_policy==="exact"?new i(400,"substitution_refused","the requested model is unavailable"):p?new i(404,"model_unavailable","no usable model route is available"):await ge()}l(tn,"runLlm");export{bt as freshSubscriptionAccess,en as llmCallerOf,Qt as parseLlmRequest,tn as runLlm,qt as usdEquivalent};
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(s.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 a=e.getAll().find(s=>s.provider==="anthropic"&&s.api==="anthropic-messages");return a?{...a,id:t,name:t}:void 0}l(At,"hostedModel");function jt(e,t){const{input:o,output:a,cacheRead:s,cacheWrite:M}=e.cost;return o===0&&a===0&&s===0&&M===0?null:Number.isFinite(t)&&t>=0?t:null}l(jt,"usdEquivalent");function Mt(e,t){return e.compat?.allowedFallbackModels?.find(a=>a.provider===e.provider&&a.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,a,s,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=s===void 0?null:r?.sub??s.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,a);const re=!h&&s!==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 B=`chatcmpl-${We()}`;let D=1/0,z=1/0,ae,v,se,de;const X=new Set,le=l(async()=>U??(s?.node?(await Ne(s.node))?.caused_by??null:null)??(s?.run?(await Ne(s.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 J=w?Le.base_url:void 0,c=h?{...S,baseUrl:`${h.base_url}/${S.provider}`}:J?{...S,baseUrl:`${J}/anthropic`,compat:{...S.compat,allowedFallbackModels:void 0}}:S,p=_.providerId,G=_.credentialSource===je&&N(p),ue=!r&&!w&&!G&&N(p)?await $e(p):[],W=ue.filter(k=>!k.authFailure),be=W.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&&W.length===0&&T===void 0){N(p)&&X.add(p);continue}if(W.length&&!be.length&&T===void 0){const k=Math.min(...W.map($=>Se($,c.id)));k<D&&(D=k,se=`${c.provider}/${c.id}`);continue}const ve=r||w?[void 0,void 0]:G?["key"]:W.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(s!==void 0&&q!==null){const n=await lt({scope:"call",payer:q.payer,funding:q.funding,sub:g,grantee:s.grantee,provider:p});if(n!==null){if(await ge({request:s.request??B,kind:"model",what:u,usd:null,payer:q.payer,funding:q.funding,sub:g,grantee:s.grantee,node:s.node??null,run:s.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(J)try{I=await De({audience:J,sub:g,grantee:s.grantee,initiating_app:s.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 d,O;const ee=l((n,f=null)=>({id:B,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"),Be=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 Be)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"&&(d=n.message),n.type==="error"&&(d=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",`${J} refuses this runtime's tokens`,void 0,{served_model:u})}if(O!==void 0||A!==void 0&&A>=400||d?.stopReason==="error"||d?.stopReason==="aborted"){const f=O instanceof Error?O.message:d?.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:d?.errorMessage??"inference endpoint failed",void 0,{served_model:u})}if(!C&&d?.stopReason==="error"&&ye({message:d.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(d);if(A===400&&e.tool_choice!==void 0&&e.tool_choice!=="auto"&&e.tool_choice!=="none"&&/\btool[_ ]choice\b/i.test(d?.errorMessage??"")&&/not supported|does not support|unsupported|cannot|must be auto/i.test(d?.errorMessage??""))throw new i(400,"invalid_request",d.errorMessage,"tool_choice",{served_model:u});if(d?.stopReason==="error"){const n=$t(c.provider,d.errorMessage,u);if(n)throw n}if(!d||d.stopReason==="error"&&!ne||d.stopReason==="aborted")throw new i(503,"upstream_model_unavailable",d?.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=d.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":d.stopReason==="toolUse"?"tool_calls":d.stopReason==="length"?"length":"stop",he=d.responseModel?Mt(c,d.responseModel):void 0,E=H?`${c.provider}/${H.served_model}`:he?`${c.provider}/${he.model}`:u,oe={prompt_tokens:d.usage.input,completion_tokens:d.usage.output,total_tokens:d.usage.totalTokens,cache_read_tokens:d.usage.cacheRead,cache_write_tokens:d.usage.cacheWrite,usd_equivalent:H?H.list_usd:jt(he??c,d.usage.cost.total),served_model:E};w?s!==void 0&&q!==null&&await ge({id:L,request:s.request??B,kind:"model",what:E,usd:oe.usd_equivalent,payer:q.payer,funding:q.funding,sub:g,grantee:s.grantee,node:s.node??null,run:s.run??null,provider:p,causedBy:await le(),vendorRef:Z}):s!==void 0&&q!==null&&await ge({request:s.request??B,kind:"model",what:E,units:{input:d.usage.input,output:d.usage.output,cache_read:d.usage.cacheRead,cache_write:d.usage.cacheWrite},usd:oe.usd_equivalent,payer:q.payer,funding:q.funding,sub:g,grantee:s.grantee,node:s.node??null,run:s.run??null,provider:p,causedBy:await le(),vendorRef:Z});const Ae={id:B,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:d.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:d.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};
@@ -1 +1 @@
1
- var k=Object.defineProperty;var a=(t,n)=>k(t,"name",{value:n,configurable:!0});import{randomBytes as E}from"node:crypto";import{ApiError as o}from"../../../api/errors.js";import{blobStore as f}from"../../../core/blobs/index.js";import{presignPutUrl as $,r2ConfigFromEnv as v}from"../../../core/blobs/r2.js";import{openDb as c}from"../../../core/canvas/db.js";import{bundleKeys as m}from"../../../core/import/bundle/layout.js";import{putStore as O,StoreBodyError as T,STORE_NAMES as R}from"../../../core/import/load/stores.js";import{rollbackRun as D}from"../../../core/import/load/rollback.js";import{crtrVersion as w}from"../../../shared/crtr-version.js";import{importTokenFor as N}from"../import-auth.js";const h=3600;function y(t){if(t.principal.class!=="person"||t.principal.sub===void 0)throw new o(403,"person_only","an import is made by a signed-in person");return t.principal.sub}a(y,"personOf");async function _(t,n=!1){const e=t.params.run_id??"",r=await(await c()).prepare("SELECT * FROM import_runs WHERE run_id = ?").get(e),s=t.principal;if(s.class==="import"){if(s.run===null&&!n)throw new o(403,"permission_error","the service credential starts and reads runs; the import token uploads and loads");if(r===void 0||(s.run===null?r.source_kind!=="hosted":s.run!==r.run_id))throw new o(404,"import_not_found",`no import run ${e}`);if(s.run!==null&&!n&&r.state!=="uploading"&&r.state!=="loading")throw new o(403,"import_token_expired",`import run ${r.run_id} is ${r.state}: its import token no longer works`);return r}if(r===void 0||r.person!==y(t))throw new o(404,"import_not_found",`no import run ${e}`);return r}a(_,"ownRun");function A(t,n,e){const r=t.principal;if(r.class!=="import")return y(t);if(r.run!==null)throw new o(403,"permission_error","an import token reaches only its own run");const s=n.person;if(typeof s!="string"||!/^user:.+/.test(s))throw new o(400,"invalid_body","person (user:<id>) is required");if(e!=="hosted")throw new o(400,"invalid_body","the service credential starts hosted runs only: source_kind must be hosted");return s}a(A,"startPerson");const g=a(t=>{if(t===null||typeof t!="object"||Array.isArray(t))throw new o(400,"invalid_body","the body must be a JSON object");return t},"objectBody");async function j(t){const n=g(t.body),e=A(t,n,n.source_kind),r=n.source_install_id,s=n.source_kind,u=n.release;if(typeof r!="string"||r===""||s!=="machine"&&s!=="hosted"||typeof u!="string")throw new o(400,"invalid_body","source_install_id, source_kind (machine | hosted) and release are required");if(u!==w())throw new o(409,"release_mismatch",`the source runs ${u}, the control plane accepts ${w()}`);const p=await c();let i=await p.prepare("SELECT run_id, state FROM import_runs WHERE source_install_id = ? AND state IN ('uploading', 'loading', 'committed', 'done')").get(r);if(i?.state==="uploading"){const S={step:"uploading",code:"superseded",message:`a new import run was started for install ${r} before this one asked for the load`};await p.prepare("UPDATE import_runs SET state = 'failed', failure_json = ?, finished_at = ? WHERE run_id = ? AND state = 'uploading'").run(JSON.stringify(S),new Date().toISOString(),i.run_id),i=await p.prepare("SELECT run_id, state FROM import_runs WHERE source_install_id = ? AND state IN ('uploading', 'loading', 'committed', 'done')").get(r)}if(i?.state==="done")throw new o(409,"already_imported",`install ${r} was imported by run ${i.run_id}`);if(i!==void 0)throw new o(409,"import_running",`install ${r} has an open run ${i.run_id} (${i.state})`);const d=`imp_${E(8).toString("hex")}`;await p.prepare("INSERT INTO import_runs (run_id, source_install_id, source_kind, person, release, state, created_at) VALUES (?, ?, ?, ?, ?, 'uploading', ?)").run(d,r,s,e,u,new Date().toISOString());const l=t.principal.class==="import"?N(d):null;return{status:201,body:{run_id:d,upload:{rows_prefix:m.prefix(d),url_template:`POST /v1/imports/${d}/upload-urls {"keys":[...]}`},...l===null?{}:{import_token:l}}}}a(j,"handleStart");async function P(t){const n=await _(t);if(n.state!=="uploading")throw new o(409,"import_not_uploading",`import run ${n.run_id} is ${n.state}`);const e=g(t.body).keys;if(!Array.isArray(e)||e.some(i=>typeof i!="string"))throw new o(400,"invalid_body","keys must be a list of blob keys");const r=m.prefix(n.run_id);for(const i of e)if(!(i.startsWith(r)&&!i.startsWith(`${r}stores/`)&&i!==m.manifest(n.run_id))||i.split("/").some(l=>l===""||l==="."||l===".."))throw new o(400,"invalid_key",`${i} is not a key this run may upload`);const s=v();if(s===null)throw new o(501,"upload_not_supported","this control plane keeps blobs in a directory: there is no URL to upload to");const u={};for(const i of e)u[i]=$(s,i,h);return{status:200,body:{urls:u,expires_at:new Date(Date.now()+h*1e3).toISOString()}}}a(P,"handleUploadUrls");async function I(t){const n=await _(t);if(n.state!=="uploading")throw new o(409,"import_not_uploading",`import run ${n.run_id} is ${n.state}`);const e=t.params.name;if(!R.includes(e))throw new o(404,"unknown_store",`no file store ${e}`);try{await O(await f(),n.run_id,e,t.body)}catch(r){throw r instanceof T?new o(400,"invalid_body",r.message):r}return{status:204}}a(I,"handleStore");async function U(t){const n=await _(t),e=await c();if(n.state==="uploading"){if(await(await f()).get(m.source(n.run_id))===null)throw new o(409,"bundle_invalid","source.json is not uploaded");await e.prepare("UPDATE import_runs SET state = 'loading', step = 'queued', loaded_at = ? WHERE run_id = ? AND state = 'uploading'").run(new Date().toISOString(),n.run_id)}else if(n.state!=="loading"&&n.state!=="committed"&&n.state!=="done")throw new o(409,"import_not_uploading",`import run ${n.run_id} is ${n.state}`);return{status:202,body:await b(n.run_id)}}a(U,"handleLoad");async function b(t){const n=await(await c()).prepare("SELECT * FROM import_runs WHERE run_id = ?").get(t),e=n.counts_json===null?{}:JSON.parse(n.counts_json),{unresolved_plugins:r,refused_plugins:s,...u}=e;return{run_id:n.run_id,source_install_id:n.source_install_id,source_kind:n.source_kind,person:n.person,release:n.release,state:n.state,step:n.step,counts:u,verify:n.verify_json===null?null:JSON.parse(n.verify_json),failure:n.failure_json===null?null:JSON.parse(n.failure_json),unresolved_plugins:r??[],refused_plugins:s??[],created:n.created_at,loaded:n.loaded_at,finished:n.finished_at}}a(b,"runDto");async function L(t){const n=await _(t,!0);return{status:200,body:await b(n.run_id)}}a(L,"handleGet");async function W(t){const n=await _(t),e=await D(n.run_id,await f());if(!e.rolled_back)throw new o(409,"rollback_has_dependents",`later rows depend on import run ${n.run_id}`,e.dependents);return{status:200,body:e}}a(W,"handleRollback");const X=[{method:"POST",pattern:"/v1/imports",handler:j},{method:"POST",pattern:"/v1/imports/:run_id/upload-urls",handler:P},{method:"PUT",pattern:"/v1/imports/:run_id/stores/:name",handler:I},{method:"POST",pattern:"/v1/imports/:run_id/load",handler:U},{method:"GET",pattern:"/v1/imports/:run_id",handler:L},{method:"POST",pattern:"/v1/imports/:run_id/rollback",handler:W}];export{X as importRoutes};
1
+ var k=Object.defineProperty;var a=(t,n)=>k(t,"name",{value:n,configurable:!0});import{randomBytes as E}from"node:crypto";import{ApiError as o}from"../../../api/errors.js";import{blobStore as c}from"../../../core/blobs/index.js";import{presignPutUrl as $,r2ConfigFromEnv as v}from"../../../core/blobs/r2.js";import{openDb as m}from"../../../core/canvas/db.js";import{bundleKeys as f}from"../../../core/import/bundle/layout.js";import{deleteRunPrefix as O}from"../../../core/import/load/blobs.js";import{putStore as T,StoreBodyError as R,STORE_NAMES as D}from"../../../core/import/load/stores.js";import{rollbackRun as N}from"../../../core/import/load/rollback.js";import{crtrVersion as w}from"../../../shared/crtr-version.js";import{importTokenFor as A}from"../import-auth.js";const h=3600;function y(t){if(t.principal.class!=="person"||t.principal.sub===void 0)throw new o(403,"person_only","an import is made by a signed-in person");return t.principal.sub}a(y,"personOf");async function _(t,n=!1){const e=t.params.run_id??"",r=await(await m()).prepare("SELECT * FROM import_runs WHERE run_id = ?").get(e),s=t.principal;if(s.class==="import"){if(s.run===null&&!n)throw new o(403,"permission_error","the service credential starts and reads runs; the import token uploads and loads");if(r===void 0||(s.run===null?r.source_kind!=="hosted":s.run!==r.run_id))throw new o(404,"import_not_found",`no import run ${e}`);if(s.run!==null&&!n&&r.state!=="uploading"&&r.state!=="loading")throw new o(403,"import_token_expired",`import run ${r.run_id} is ${r.state}: its import token no longer works`);return r}if(r===void 0||r.person!==y(t))throw new o(404,"import_not_found",`no import run ${e}`);return r}a(_,"ownRun");function P(t,n,e){const r=t.principal;if(r.class!=="import")return y(t);if(r.run!==null)throw new o(403,"permission_error","an import token reaches only its own run");const s=n.person;if(typeof s!="string"||!/^user:.+/.test(s))throw new o(400,"invalid_body","person (user:<id>) is required");if(e!=="hosted")throw new o(400,"invalid_body","the service credential starts hosted runs only: source_kind must be hosted");return s}a(P,"startPerson");const g=a(t=>{if(t===null||typeof t!="object"||Array.isArray(t))throw new o(400,"invalid_body","the body must be a JSON object");return t},"objectBody");async function j(t){const n=g(t.body),e=P(t,n,n.source_kind),r=n.source_install_id,s=n.source_kind,u=n.release;if(typeof r!="string"||r===""||s!=="machine"&&s!=="hosted"||typeof u!="string")throw new o(400,"invalid_body","source_install_id, source_kind (machine | hosted) and release are required");if(u!==w())throw new o(409,"release_mismatch",`the source runs ${u}, the control plane accepts ${w()}`);const p=await m();let i=await p.prepare("SELECT run_id, state FROM import_runs WHERE source_install_id = ? AND state IN ('uploading', 'loading', 'committed', 'done')").get(r);if(i?.state==="uploading"){const S={step:"uploading",code:"superseded",message:`a new import run was started for install ${r} before this one asked for the load`};await p.prepare("UPDATE import_runs SET state = 'failed', failure_json = ?, finished_at = ? WHERE run_id = ? AND state = 'uploading'").run(JSON.stringify(S),new Date().toISOString(),i.run_id),await O(await c(),i.run_id,{bestEffort:!0}),i=await p.prepare("SELECT run_id, state FROM import_runs WHERE source_install_id = ? AND state IN ('uploading', 'loading', 'committed', 'done')").get(r)}if(i?.state==="done")throw new o(409,"already_imported",`install ${r} was imported by run ${i.run_id}`);if(i!==void 0)throw new o(409,"import_running",`install ${r} has an open run ${i.run_id} (${i.state})`);const d=`imp_${E(8).toString("hex")}`;await p.prepare("INSERT INTO import_runs (run_id, source_install_id, source_kind, person, release, state, created_at) VALUES (?, ?, ?, ?, ?, 'uploading', ?)").run(d,r,s,e,u,new Date().toISOString());const l=t.principal.class==="import"?A(d):null;return{status:201,body:{run_id:d,upload:{rows_prefix:f.prefix(d),url_template:`POST /v1/imports/${d}/upload-urls {"keys":[...]}`},...l===null?{}:{import_token:l}}}}a(j,"handleStart");async function I(t){const n=await _(t);if(n.state!=="uploading")throw new o(409,"import_not_uploading",`import run ${n.run_id} is ${n.state}`);const e=g(t.body).keys;if(!Array.isArray(e)||e.some(i=>typeof i!="string"))throw new o(400,"invalid_body","keys must be a list of blob keys");const r=f.prefix(n.run_id);for(const i of e)if(!(i.startsWith(r)&&!i.startsWith(`${r}stores/`)&&i!==f.manifest(n.run_id))||i.split("/").some(l=>l===""||l==="."||l===".."))throw new o(400,"invalid_key",`${i} is not a key this run may upload`);const s=v();if(s===null)throw new o(501,"upload_not_supported","this control plane keeps blobs in a directory: there is no URL to upload to");const u={};for(const i of e)u[i]=$(s,i,h);return{status:200,body:{urls:u,expires_at:new Date(Date.now()+h*1e3).toISOString()}}}a(I,"handleUploadUrls");async function U(t){const n=await _(t);if(n.state!=="uploading")throw new o(409,"import_not_uploading",`import run ${n.run_id} is ${n.state}`);const e=t.params.name;if(!D.includes(e))throw new o(404,"unknown_store",`no file store ${e}`);try{await T(await c(),n.run_id,e,t.body)}catch(r){throw r instanceof R?new o(400,"invalid_body",r.message):r}return{status:204}}a(U,"handleStore");async function L(t){const n=await _(t),e=await m();if(n.state==="uploading"){if(await(await c()).get(f.source(n.run_id))===null)throw new o(409,"bundle_invalid","source.json is not uploaded");await e.prepare("UPDATE import_runs SET state = 'loading', step = 'queued', loaded_at = ? WHERE run_id = ? AND state = 'uploading'").run(new Date().toISOString(),n.run_id)}else if(n.state!=="loading"&&n.state!=="committed"&&n.state!=="done")throw new o(409,"import_not_uploading",`import run ${n.run_id} is ${n.state}`);return{status:202,body:await b(n.run_id)}}a(L,"handleLoad");async function b(t){const n=await(await m()).prepare("SELECT * FROM import_runs WHERE run_id = ?").get(t),e=n.counts_json===null?{}:JSON.parse(n.counts_json),{unresolved_plugins:r,refused_plugins:s,...u}=e;return{run_id:n.run_id,source_install_id:n.source_install_id,source_kind:n.source_kind,person:n.person,release:n.release,state:n.state,step:n.step,counts:u,verify:n.verify_json===null?null:JSON.parse(n.verify_json),failure:n.failure_json===null?null:JSON.parse(n.failure_json),unresolved_plugins:r??[],refused_plugins:s??[],created:n.created_at,loaded:n.loaded_at,finished:n.finished_at}}a(b,"runDto");async function W(t){const n=await _(t,!0);return{status:200,body:await b(n.run_id)}}a(W,"handleGet");async function C(t){const n=await _(t),e=await N(n.run_id,await c());if(!e.rolled_back)throw new o(409,"rollback_has_dependents",`later rows depend on import run ${n.run_id}`,e.dependents);return{status:200,body:e}}a(C,"handleRollback");const Z=[{method:"POST",pattern:"/v1/imports",handler:j},{method:"POST",pattern:"/v1/imports/:run_id/upload-urls",handler:I},{method:"PUT",pattern:"/v1/imports/:run_id/stores/:name",handler:U},{method:"POST",pattern:"/v1/imports/:run_id/load",handler:L},{method:"GET",pattern:"/v1/imports/:run_id",handler:W},{method:"POST",pattern:"/v1/imports/:run_id/rollback",handler:C}];export{Z as importRoutes};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.629",
3
+ "version": "0.3.631",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -145,7 +145,7 @@
145
145
  },
146
146
  "license": "UNLICENSED",
147
147
  "dependencies": {
148
- "@north-light/identity": "0.3.629",
148
+ "@north-light/identity": "0.3.631",
149
149
  "@earendil-works/chord": "1.1.0",
150
150
  "@earendil-works/pi-agent-core": "1.1.0",
151
151
  "@earendil-works/pi-ai": "1.1.0",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.629",
3
+ "version": "0.3.631",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
package/runtime.lock.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.629",
3
+ "version": "0.3.631",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.629",
9
+ "version": "0.3.631",
10
10
  "hasInstallScript": true,
11
11
  "license": "UNLICENSED",
12
12
  "workspaces": [
@@ -28,7 +28,7 @@
28
28
  "@milkdown/preset-gfm": "^7.22.3",
29
29
  "@milkdown/prose": "^7.22.3",
30
30
  "@milkdown/utils": "^7.22.3",
31
- "@north-light/identity": "0.3.629",
31
+ "@north-light/identity": "0.3.631",
32
32
  "cron-parser": "^5.6.0",
33
33
  "esbuild": "^0.27.7",
34
34
  "jose": "^6.2.12",
@@ -11956,17 +11956,17 @@
11956
11956
  },
11957
11957
  "packages/crouter-api": {
11958
11958
  "name": "@north-light/api",
11959
- "version": "0.3.629",
11959
+ "version": "0.3.631",
11960
11960
  "license": "UNLICENSED"
11961
11961
  },
11962
11962
  "packages/crouter-env-docker": {
11963
11963
  "name": "@north-light/env-docker",
11964
- "version": "0.3.629",
11964
+ "version": "0.3.631",
11965
11965
  "license": "UNLICENSED"
11966
11966
  },
11967
11967
  "packages/crouter-identity": {
11968
11968
  "name": "@north-light/identity",
11969
- "version": "0.3.629",
11969
+ "version": "0.3.631",
11970
11970
  "license": "UNLICENSED",
11971
11971
  "dependencies": {
11972
11972
  "jose": "^6.2.1"
@@ -11974,21 +11974,21 @@
11974
11974
  },
11975
11975
  "packages/crouter-plugin": {
11976
11976
  "name": "@north-light/plugin",
11977
- "version": "0.3.629",
11977
+ "version": "0.3.631",
11978
11978
  "license": "UNLICENSED",
11979
11979
  "dependencies": {
11980
- "@north-light/api": "0.3.629",
11981
- "@north-light/identity": "0.3.629"
11980
+ "@north-light/api": "0.3.631",
11981
+ "@north-light/identity": "0.3.631"
11982
11982
  }
11983
11983
  },
11984
11984
  "packages/crouter-sdk": {
11985
11985
  "name": "@north-light/sdk",
11986
- "version": "0.3.629",
11986
+ "version": "0.3.631",
11987
11987
  "license": "UNLICENSED",
11988
11988
  "dependencies": {
11989
- "@north-light/api": "0.3.629",
11990
- "@north-light/identity": "0.3.629",
11991
- "@north-light/plugin": "0.3.629",
11989
+ "@north-light/api": "0.3.631",
11990
+ "@north-light/identity": "0.3.631",
11991
+ "@north-light/plugin": "0.3.631",
11992
11992
  "jose": "^6.2.1"
11993
11993
  },
11994
11994
  "bin": {