@north-light/cli 0.3.598 → 0.3.599

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/dist/api/contract.d.ts +1 -1
  2. package/dist/api/contract.js +1 -1
  3. package/dist/api/dto/charges.d.ts +22 -0
  4. package/dist/api/dto/charges.js +1 -0
  5. package/dist/api/dto/modelauth.d.ts +26 -0
  6. package/dist/api/dto/node-outcomes.d.ts +4 -0
  7. package/dist/api/error-codes.d.ts +5 -0
  8. package/dist/api/error-codes.js +1 -1
  9. package/dist/builtin-memory/crouter-sdk/release-notes.md +11 -0
  10. package/dist/clients/attach/viewer.js +374 -374
  11. package/dist/commands/sys/join.js +1 -1
  12. package/dist/core/auth-file.d.ts +3 -11
  13. package/dist/core/auth-file.js +1 -1
  14. package/dist/core/canvas/export-sqlite.js +1 -1
  15. package/dist/core/canvas/person.js +7 -7
  16. package/dist/core/canvas/recovery.js +2 -2
  17. package/dist/core/canvas/schema-pg/012-charge-admission.sql +62 -0
  18. package/dist/core/canvas/schema-version.d.ts +1 -1
  19. package/dist/core/canvas/schema-version.js +1 -1
  20. package/dist/core/canvas/types.d.ts +3 -0
  21. package/dist/core/grants/hosted-endpoint.d.ts +28 -0
  22. package/dist/core/grants/hosted-endpoint.js +1 -0
  23. package/dist/core/grants/sync.js +1 -1
  24. package/dist/core/import/load/run.js +2 -2
  25. package/dist/core/import/load/stage.d.ts +1 -1
  26. package/dist/core/import/load/stage.js +1 -1
  27. package/dist/core/import/load/stores.d.ts +2 -0
  28. package/dist/core/import/load/stores.js +2 -2
  29. package/dist/core/ledger/charges.js +1 -1
  30. package/dist/core/ledger/check.js +1 -1
  31. package/dist/core/ledger/chunks.js +2 -2
  32. package/dist/core/ledger/read.js +1 -1
  33. package/dist/core/ledger/types.d.ts +8 -0
  34. package/dist/core/llm/owner-candidates.d.ts +17 -0
  35. package/dist/core/llm/owner-candidates.js +1 -0
  36. package/dist/core/llm/run.js +2 -2
  37. package/dist/core/model-auth/activations.d.ts +37 -0
  38. package/dist/core/model-auth/activations.js +1 -0
  39. package/dist/core/model-auth/flows.js +1 -1
  40. package/dist/core/model-auth/handoff-jti.d.ts +10 -1
  41. package/dist/core/model-auth/handoff-jti.js +1 -1
  42. package/dist/core/model-auth/key-routes.d.ts +30 -0
  43. package/dist/core/model-auth/key-routes.js +1 -0
  44. package/dist/core/model-auth/readiness.d.ts +8 -1
  45. package/dist/core/model-auth/readiness.js +1 -1
  46. package/dist/core/model-config.js +1 -1
  47. package/dist/core/model-routes-pool.d.ts +2 -0
  48. package/dist/core/model-routes-pool.js +1 -1
  49. package/dist/core/model-routes.d.ts +12 -3
  50. package/dist/core/model-routes.js +1 -1
  51. package/dist/core/provider-failure.d.ts +5 -0
  52. package/dist/core/provider-failure.js +1 -1
  53. package/dist/core/providers/call.js +1 -1
  54. package/dist/core/runtime/broker/fault-retry.js +1 -1
  55. package/dist/core/runtime/broker/model-adapter.d.ts +6 -1
  56. package/dist/core/runtime/broker/model-adapter.js +3 -3
  57. package/dist/core/runtime/front-door.js +8 -8
  58. package/dist/core/runtime/launch-target.d.ts +2 -0
  59. package/dist/core/runtime/launch-target.js +1 -1
  60. package/dist/daemon/api/app-listener.js +12 -12
  61. package/dist/daemon/api/handlers/llm.js +3 -3
  62. package/dist/daemon/api/handlers/modelauth.js +1 -1
  63. package/dist/daemon/api/handlers/nodes.js +1 -1
  64. package/dist/daemon/api/key-signin.d.ts +9 -0
  65. package/dist/daemon/api/key-signin.js +124 -0
  66. package/dist/daemon/api/principal.d.ts +8 -3
  67. package/dist/daemon/api/principal.js +1 -1
  68. package/dist/daemon/api/server.js +1 -1
  69. package/dist/daemon/api/vendor-signin.d.ts +28 -1
  70. package/dist/daemon/api/vendor-signin.js +42 -24
  71. package/dist/daemon/cron/authority.js +1 -1
  72. package/dist/daemon/crtrd.js +12 -12
  73. package/dist/daemon/reconcilers/broker-supervision.d.ts +2 -2
  74. package/dist/daemon/reconcilers/broker-supervision.js +2 -2
  75. package/dist/daemon/reconcilers/ledger-r2.js +6 -6
  76. package/docs/sdk/release-notes.md +11 -0
  77. package/package.json +2 -2
  78. package/packages/crouter-identity/package.json +1 -1
  79. package/runtime.lock.json +13 -13
@@ -1,6 +1,6 @@
1
1
  import type { CanvasDb } from '../../canvas/db.js';
2
2
  /** Tables `substitutePerson` and `rebuildTotalsFor` read or write that the bundle does not dump: staged empty. */
3
- export declare const EMPTY_STAGED_TABLES: readonly ["node_tokens", "charge_chunks", "charge_totals", "profile_defaults", "scope_settings", "scope_bookkeeping", "scope_marketplaces", "scope_plugins", "person_settings", "model_accounts", "model_account_cooldowns", "model_api_keys", "model_settings", "model_sign_in_flows", "env_vars"];
3
+ export declare const EMPTY_STAGED_TABLES: readonly ["node_tokens", "charge_chunks", "charge_totals", "profile_defaults", "scope_settings", "scope_bookkeeping", "scope_marketplaces", "scope_plugins", "person_settings", "model_accounts", "model_account_cooldowns", "model_api_keys", "model_settings", "model_sign_in_flows", "env_vars", "hosted_endpoints", "credential_activations"];
4
4
  export declare const stagingSchema: (run: string) => string;
5
5
  /** The target schema's name (the transaction's current schema). */
6
6
  export declare function targetSchema(db: CanvasDb): Promise<string>;
@@ -1 +1 @@
1
- var m=Object.defineProperty;var a=(t,s)=>m(t,"name",{value:s,configurable:!0});import{BODIES_TABLE as L,DUMPED_TABLES as E,rowLines as x}from"../bundle/layout.js";import{hashOf as T}from"../../graph/bodies.js";const A=["node_tokens","charge_chunks","charge_totals","profile_defaults","scope_settings","scope_bookkeeping","scope_marketplaces","scope_plugins","person_settings","model_accounts","model_account_cooldowns","model_api_keys","model_settings","model_sign_in_flows","env_vars"],y=16*1024*1024,I=2e3,$=a(t=>`import_${t.replace(/[^A-Za-z0-9_]/g,"_")}`,"stagingSchema"),n=a(t=>`"${t.replace(/"/g,'""')}"`,"q");async function C(t){return(await t.prepare("SELECT current_schema() AS s").get()).s}a(C,"targetSchema");async function D(t,s){await t.exec(`DROP SCHEMA IF EXISTS ${n($(s))} CASCADE`)}a(D,"dropStaging");async function U(t,s,e,i,f){const l=$(s),S=await C(t);await D(t,s),await t.exec(`CREATE SCHEMA ${n(l)}`);const _={};for(const o of[...E,...A])await t.exec(`CREATE UNLOGGED TABLE ${n(l)}.${n(o)} (LIKE ${n(S)}.${n(o)} INCLUDING DEFAULTS)`);for(const o of E){let p=0;for(const d of i(o)){const u=await f(d);if(u===null){if((e[o]??0)!==0)throw c(`row file ${d} is missing`);continue}let r=[],g=0;const w=a(async()=>{r.length!==0&&(await t.prepareUncached(`INSERT INTO ${n(l)}.${n(o)} SELECT * FROM json_populate_recordset(NULL::${n(l)}.${n(o)}, ?::json)`).run(`[${r.join(",")}]`),p+=r.length,r=[],g=0)},"insert");for await(const h of x(u)){if(!h.startsWith("{"))throw c(`row file ${d} has a line that is not a JSON object`);o===L&&N(d,h),r.length>0&&(r.length>=I||g+h.length>y)&&await w(),r.push(h),g+=h.length}await w()}if(p!==(e[o]??0))throw c(`row file for ${o} has ${p} rows; source.json says ${e[o]??0}`);_[o]=p}return _}a(U,"stage");function N(t,s){const e=JSON.parse(s);if(typeof e.hash!="string"||typeof e.text!="string")throw c(`row file ${t} has a bodies row without a hash and a text`);if(e.text.includes("\0"))throw c(`body ${e.hash} in ${t} holds a NUL character; export the source again after its daemon has been upgraded and restarted`);const i=T(e.text);if(i!==e.hash)throw c(`body ${e.hash} in ${t} does not hash to its key (its text hashes to ${i}); export the source again after its daemon has been upgraded and restarted`)}a(N,"checkBodyLine");class O extends Error{static{a(this,"ImportLaneError")}step;code;detail;constructor(s,e,i,f){super(i),this.step=s,this.code=e,this.detail=f}}function c(t){return new O("stage","bundle_invalid",t)}a(c,"bundleInvalid");export{A as EMPTY_STAGED_TABLES,O as ImportLaneError,D as dropStaging,U as stage,$ as stagingSchema,C as targetSchema};
1
+ var m=Object.defineProperty;var a=(t,s)=>m(t,"name",{value:s,configurable:!0});import{BODIES_TABLE as L,DUMPED_TABLES as E,rowLines as x}from"../bundle/layout.js";import{hashOf as T}from"../../graph/bodies.js";const A=["node_tokens","charge_chunks","charge_totals","profile_defaults","scope_settings","scope_bookkeeping","scope_marketplaces","scope_plugins","person_settings","model_accounts","model_account_cooldowns","model_api_keys","model_settings","model_sign_in_flows","env_vars","hosted_endpoints","credential_activations"],y=16*1024*1024,I=2e3,$=a(t=>`import_${t.replace(/[^A-Za-z0-9_]/g,"_")}`,"stagingSchema"),n=a(t=>`"${t.replace(/"/g,'""')}"`,"q");async function C(t){return(await t.prepare("SELECT current_schema() AS s").get()).s}a(C,"targetSchema");async function D(t,s){await t.exec(`DROP SCHEMA IF EXISTS ${n($(s))} CASCADE`)}a(D,"dropStaging");async function U(t,s,e,i,f){const l=$(s),S=await C(t);await D(t,s),await t.exec(`CREATE SCHEMA ${n(l)}`);const g={};for(const o of[...E,...A])await t.exec(`CREATE UNLOGGED TABLE ${n(l)}.${n(o)} (LIKE ${n(S)}.${n(o)} INCLUDING DEFAULTS)`);for(const o of E){let d=0;for(const p of i(o)){const u=await f(p);if(u===null){if((e[o]??0)!==0)throw c(`row file ${p} is missing`);continue}let r=[],_=0;const w=a(async()=>{r.length!==0&&(await t.prepareUncached(`INSERT INTO ${n(l)}.${n(o)} SELECT * FROM json_populate_recordset(NULL::${n(l)}.${n(o)}, ?::json)`).run(`[${r.join(",")}]`),d+=r.length,r=[],_=0)},"insert");for await(const h of x(u)){if(!h.startsWith("{"))throw c(`row file ${p} has a line that is not a JSON object`);o===L&&N(p,h),r.length>0&&(r.length>=I||_+h.length>y)&&await w(),r.push(h),_+=h.length}await w()}if(d!==(e[o]??0))throw c(`row file for ${o} has ${d} rows; source.json says ${e[o]??0}`);g[o]=d}return g}a(U,"stage");function N(t,s){const e=JSON.parse(s);if(typeof e.hash!="string"||typeof e.text!="string")throw c(`row file ${t} has a bodies row without a hash and a text`);if(e.text.includes("\0"))throw c(`body ${e.hash} in ${t} holds a NUL character; export the source again after its daemon has been upgraded and restarted`);const i=T(e.text);if(i!==e.hash)throw c(`body ${e.hash} in ${t} does not hash to its key (its text hashes to ${i}); export the source again after its daemon has been upgraded and restarted`)}a(N,"checkBodyLine");class O extends Error{static{a(this,"ImportLaneError")}step;code;detail;constructor(s,e,i,f){super(i),this.step=s,this.code=e,this.detail=f}}function c(t){return new O("stage","bundle_invalid",t)}a(c,"bundleInvalid");export{A as EMPTY_STAGED_TABLES,O as ImportLaneError,D as dropStaging,U as stage,$ as stagingSchema,C as targetSchema};
@@ -29,3 +29,5 @@ export interface StoreResult {
29
29
  }
30
30
  /** Must run inside the copy transaction (after the profile rows exist). */
31
31
  export declare function writeStores(input: StoreInput): Promise<StoreResult>;
32
+ /** Record the copy's credentials with stable ids; any failure aborts the transaction that marks the verified import done. */
33
+ export declare function recordImportedActivations(db: CanvasDb, runId: string, person: string): Promise<void>;
@@ -1,2 +1,2 @@
1
- var U=Object.defineProperty;var l=(o,r)=>U(o,"name",{value:r,configurable:!0});import{loadSecretsKey as y,open as C,seal as k}from"../../secrets/index.js";import{insertAccount as j,upsertModelCooldown as D}from"../../subscription-state.js";import{validateEnvVarName as F,isReservedEnvName as V}from"../../env-name.js";import{encodeKeys as x}from"./copy.js";import{compareInstallOwners as M}from"../../scoped-state/migrate-app-installs.js";const W=["auth","credentials","env","settings","plugins"],h=l((o,r)=>`imports/${o}/stores/${r}.sealed`,"storeKey"),$=l((o,r)=>`import_store|${o}|${r}`,"aadOf");async function z(o,r,d,i){if(i===null||typeof i!="object"||Array.isArray(i))throw new K(`the ${d} store must be a JSON object`);const{sealed:a,keyId:m}=k(JSON.stringify(i),y(),$(r,d));await o.put(h(r,d),Buffer.concat([Buffer.from(`${m}
2
- `),a]))}l(z,"putStore");class K extends Error{static{l(this,"StoreBodyError")}}async function S(o,r,d){const i=await o.get(h(r,d));if(i===null)return null;const a=i.indexOf(10);return JSON.parse(C(i.subarray(a+1),i.subarray(0,a).toString("utf8"),y(),$(r,d)))}l(S,"readStore");const Q=l((o,r)=>S(o,r,"plugins"),"readPluginsStore"),P=l(o=>o.source_marketplace!=null,"hasFleetSource"),Y=l(o=>W.map(r=>h(o,r)),"allStoreKeys");async function Z(o){const{db:r,blobs:d,runId:i,person:a}=o,m=l(e=>o.objectMap.get(e)??e,"mapId"),w=l(e=>e.startsWith("profile:")?`profile:${m(e.slice(8))}`:e,"mapOwner"),E={},T=[],N=l((e,n)=>{(E[e]??=[]).push(n)},"record"),f=l(async(e,n,s,p)=>{await r.prepareUncached(`${n} ON CONFLICT DO NOTHING RETURNING 1 AS ok`).get(...s)!==void 0&&N(e,p)},"insert"),b=y(),A=new Date().toISOString(),u=await S(d,i,"credentials");if(u!==null){for(const e of u.accounts)if(await r.prepare("SELECT 1 FROM model_accounts WHERE person = ? AND provider_id = ? AND (id = ? OR label_key = ?)").get(a,e.provider,e.id,e.labelKey)===void 0){await j(r,a,e.provider,{providerId:e.provider,id:e.id,label:e.label,labelKey:e.labelKey,position:e.position,lastAttemptAt:e.lastAttemptAt,lastRateLimitedAt:e.lastRateLimitedAt,rateLimitedUntil:e.rateLimitedUntil,...e.authFailure?{authFailure:e.authFailure}:{}},{refresh:e.refresh,access:e.access,expires:e.expires,...e.accountId?{accountId:e.accountId}:{},...e.clientId?{clientId:e.clientId}:{}}),N("model_accounts",[a,e.provider,e.id]);for(const s of e.cooldowns)await D(r,a,e.provider,e.id,s.family,s.until,s.at),N("model_account_cooldowns",[a,e.provider,e.id,s.family])}u.rotation!==void 0&&await f("model_settings","INSERT INTO model_settings (person, default_fallback_strength, revert_when_available) VALUES (?, ?, ?)",[a,u.rotation.defaultFallbackStrength,u.rotation.revertWhenAvailable===null?null:u.rotation.revertWhenAvailable?1:0],[a]),u.openaiDeviceId!==void 0&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(u.openaiDeviceId)&&await r.prepare("INSERT INTO model_settings (person, openai_device_id) VALUES (?, ?) ON CONFLICT (person) DO UPDATE SET openai_device_id = COALESCE(model_settings.openai_device_id, EXCLUDED.openai_device_id)").run(a,u.openaiDeviceId.toLowerCase())}const L=await S(d,i,"auth");if(L!==null)for(const[e,n]of Object.entries(L.apiKeys)){const{sealed:s,keyId:p}=k(JSON.stringify(n),b,`model_api_keys|${a}|${e}`);await f("model_api_keys","INSERT INTO model_api_keys (person, provider_id, credential_sealed, key_id, updated_at) VALUES (?, ?, ?, ?, ?)",[a,e,s,p,A],[a,e])}const R=await S(d,i,"env");if(R!==null)for(const[e,n]of Object.entries(R.profiles)){const s=m(e);for(const[p,t]of Object.entries(n)){if(!F(p).isValid||V(p)||typeof t!="string"||t.includes("\0"))continue;const{sealed:c,keyId:_}=k(t,b,`env_vars|${a}|profile|${s}|${p}`);await f("env_vars","INSERT INTO env_vars (person, owner_kind, owner_id, name, value_sealed, key_id, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[a,"profile",s,p,c,_,A],[a,"profile",s,p])}}const O=await S(d,i,"settings");if(O!==null){for(const[e,n]of Object.entries(O.settings))await f("scope_settings","INSERT INTO scope_settings (person, owner_key, raw_json) VALUES (?, ?, ?)",[a,w(e),JSON.stringify(n)],[a,w(e)]);for(const[e,n]of Object.entries(O.state))await f("scope_bookkeeping","INSERT INTO scope_bookkeeping (person, owner_key, last_self_check, active_canvas) VALUES (?, ?, ?, ?)",[a,w(e),n.last_self_check??null,n.activeCanvas??null],[a,w(e)]);for(const[e,n]of Object.entries(O.profileProjects)){const s=m(e);if(await r.prepare("SELECT 1 FROM profile_projects WHERE profile_id = ?").get(s)!==void 0)continue;let p=0;for(const t of n)await f("profile_projects","INSERT INTO profile_projects (profile_id, path, position) VALUES (?, ?, ?)",[s,t,p++],[s,t])}for(const[e,n]of Object.entries(O.defaults))await f("profile_defaults","INSERT INTO profile_defaults (person, directory, profile_id) VALUES (?, ?, ?)",[a,e,m(n)],[a,e])}const v=await S(d,i,"plugins");if(v!==null){const e=l(async t=>{if(t.startsWith("app:"))return t;if(t==="user")return"app:terminal";if(!t.startsWith("profile:"))throw new Error(`unsupported install owner in the bundle: ${t}`);return(await r.prepare("SELECT grantee FROM profiles WHERE id = ?").get(m(t.slice(8))))?.grantee??"app:terminal"},"appOf"),n=new Map;for(const t of new Set([...v.marketplaces,...v.plugins].map(c=>c.owner)))t.startsWith("profile:")&&n.set(t,(await r.prepare("SELECT last_used_at FROM profiles WHERE id = ?").get(m(t.slice(8))))?.last_used_at??"");const s=l(t=>[...t].sort((c,_)=>M(w(c.owner),n.get(c.owner)??"",w(_.owner),n.get(_.owner)??"")),"byProfileFirst"),p=new Map;for(const t of s(v.marketplaces)){const c=await e(t.owner),_=new Map((await r.prepare("SELECT name, url FROM scope_marketplaces WHERE person = ? AND owner_key = ?").all(a,c)).map(I=>[I.name,I.url]));let g=t.name;for(let I=2;_.has(g)&&_.get(g)!==(t.url??null);I+=1)g=`${t.name}-${I}`;p.set(`${t.owner}\0${t.name}`,g),await f("scope_marketplaces","INSERT INTO scope_marketplaces (person, owner_key, name, last_updated, url, ref, installed_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[a,c,g,t.last_updated??null,t.url??null,t.ref??null,t.installed_at??null],[a,c,g])}for(const t of s(v.plugins)){if(!P(t)){T.push(`${t.owner}:${t.name}`);continue}const c=await e(t.owner),_=t.source_marketplace==null?null:p.get(`${t.owner}\0${t.source_marketplace}`)??t.source_marketplace;await f("scope_plugins","INSERT INTO scope_plugins (person, owner_key, name, last_updated, etag, checked_at, enabled, source_marketplace, version, source_path) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[a,c,t.name,t.last_updated??null,t.etag??null,t.checked_at??null,t.enabled?1:0,_,t.version??null,t.source_path??null],[a,c,t.name])}(E.scope_plugins??[]).length+(E.scope_marketplaces??[]).length>0&&await f("person_settings","INSERT INTO person_settings (person, plugins_revision) VALUES (?, 1)",[a],[a])}for(const[e,n]of Object.entries(E))await r.prepare("INSERT INTO import_manifest (run_id, table_name, inserted_keys) VALUES (?, ?, ?) ON CONFLICT (run_id, table_name) DO UPDATE SET inserted_keys = EXCLUDED.inserted_keys").run(i,e,x(n));return Object.keys(E).length>0&&await r.prepare("SELECT pg_notify('crtr_signal', ?)").get(`settings:${a}`),{inserted:E,unresolvedPlugins:T}}l(Z,"writeStores");export{W as STORE_NAMES,K as StoreBodyError,Y as allStoreKeys,P as hasFleetSource,z as putStore,Q as readPluginsStore,h as storeKey,Z as writeStores};
1
+ var C=Object.defineProperty;var l=(n,o)=>C(n,"name",{value:o,configurable:!0});import{createHash as U}from"node:crypto";import{loadSecretsKey as I,open as j,seal as h}from"../../secrets/index.js";import{insertAccount as D,upsertModelCooldown as F}from"../../subscription-state.js";import{validateEnvVarName as x,isReservedEnvName as V}from"../../env-name.js";import{decodeKeys as M,encodeKeys as W}from"./copy.js";import{compareInstallOwners as K}from"../../scoped-state/migrate-app-installs.js";import{recordCredentialActivation as H}from"../../model-auth/activations.js";const P=["auth","credentials","env","settings","plugins"],T=l((n,o)=>`imports/${n}/stores/${o}.sealed`,"storeKey"),$=l((n,o)=>`import_store|${n}|${o}`,"aadOf");async function te(n,o,c,i){if(i===null||typeof i!="object"||Array.isArray(i))throw new J(`the ${c} store must be a JSON object`);const{sealed:a,keyId:_}=h(JSON.stringify(i),I(),$(o,c));await n.put(T(o,c),Buffer.concat([Buffer.from(`${_}
2
+ `),a]))}l(te,"putStore");class J extends Error{static{l(this,"StoreBodyError")}}async function v(n,o,c){const i=await n.get(T(o,c));if(i===null)return null;const a=i.indexOf(10);return JSON.parse(j(i.subarray(a+1),i.subarray(0,a).toString("utf8"),I(),$(o,c)))}l(v,"readStore");const ae=l((n,o)=>v(n,o,"plugins"),"readPluginsStore"),B=l(n=>n.source_marketplace!=null,"hasFleetSource"),oe=l(n=>P.map(o=>T(n,o)),"allStoreKeys");async function re(n){const{db:o,blobs:c,runId:i,person:a}=n,_=l(e=>n.objectMap.get(e)??e,"mapId"),p=l(e=>e.startsWith("profile:")?`profile:${_(e.slice(8))}`:e,"mapOwner"),f={},g=[],y=l((e,r)=>{(f[e]??=[]).push(r)},"record"),m=l(async(e,r,s,d)=>{await o.prepareUncached(`${r} ON CONFLICT DO NOTHING RETURNING 1 AS ok`).get(...s)!==void 0&&y(e,d)},"insert"),b=I(),A=new Date().toISOString(),w=await v(c,i,"credentials");if(w!==null){for(const e of w.accounts)if(await o.prepare("SELECT 1 FROM model_accounts WHERE person = ? AND provider_id = ? AND (id = ? OR label_key = ?)").get(a,e.provider,e.id,e.labelKey)===void 0){await D(o,a,e.provider,{providerId:e.provider,id:e.id,label:e.label,labelKey:e.labelKey,position:e.position,lastAttemptAt:e.lastAttemptAt,lastRateLimitedAt:e.lastRateLimitedAt,rateLimitedUntil:e.rateLimitedUntil,...e.authFailure?{authFailure:e.authFailure}:{}},{refresh:e.refresh,access:e.access,expires:e.expires,...e.accountId?{accountId:e.accountId}:{},...e.clientId?{clientId:e.clientId}:{}}),y("model_accounts",[a,e.provider,e.id]);for(const s of e.cooldowns)await F(o,a,e.provider,e.id,s.family,s.until,s.at),y("model_account_cooldowns",[a,e.provider,e.id,s.family])}w.rotation!==void 0&&await m("model_settings","INSERT INTO model_settings (person, default_fallback_strength, revert_when_available) VALUES (?, ?, ?)",[a,w.rotation.defaultFallbackStrength,w.rotation.revertWhenAvailable===null?null:w.rotation.revertWhenAvailable?1:0],[a]),w.openaiDeviceId!==void 0&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(w.openaiDeviceId)&&await o.prepare("INSERT INTO model_settings (person, openai_device_id) VALUES (?, ?) ON CONFLICT (person) DO UPDATE SET openai_device_id = COALESCE(model_settings.openai_device_id, EXCLUDED.openai_device_id)").run(a,w.openaiDeviceId.toLowerCase())}const R=await v(c,i,"auth");if(R!==null)for(const[e,r]of Object.entries(R.apiKeys)){const{sealed:s,keyId:d}=h(JSON.stringify(r),b,`model_api_keys|${a}|${e}`);await m("model_api_keys","INSERT INTO model_api_keys (person, provider_id, credential_sealed, key_id, updated_at) VALUES (?, ?, ?, ?, ?)",[a,e,s,d,A],[a,e])}const L=await v(c,i,"env");if(L!==null)for(const[e,r]of Object.entries(L.profiles)){const s=_(e);for(const[d,t]of Object.entries(r)){if(!x(d).isValid||V(d)||typeof t!="string"||t.includes("\0"))continue;const{sealed:u,keyId:E}=h(t,b,`env_vars|${a}|profile|${s}|${d}`);await m("env_vars","INSERT INTO env_vars (person, owner_kind, owner_id, name, value_sealed, key_id, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[a,"profile",s,d,u,E,A],[a,"profile",s,d])}}const O=await v(c,i,"settings");if(O!==null){for(const[e,r]of Object.entries(O.settings))await m("scope_settings","INSERT INTO scope_settings (person, owner_key, raw_json) VALUES (?, ?, ?)",[a,p(e),JSON.stringify(r)],[a,p(e)]);for(const[e,r]of Object.entries(O.state))await m("scope_bookkeeping","INSERT INTO scope_bookkeeping (person, owner_key, last_self_check, active_canvas) VALUES (?, ?, ?, ?)",[a,p(e),r.last_self_check??null,r.activeCanvas??null],[a,p(e)]);for(const[e,r]of Object.entries(O.profileProjects)){const s=_(e);if(await o.prepare("SELECT 1 FROM profile_projects WHERE profile_id = ?").get(s)!==void 0)continue;let d=0;for(const t of r)await m("profile_projects","INSERT INTO profile_projects (profile_id, path, position) VALUES (?, ?, ?)",[s,t,d++],[s,t])}for(const[e,r]of Object.entries(O.defaults))await m("profile_defaults","INSERT INTO profile_defaults (person, directory, profile_id) VALUES (?, ?, ?)",[a,e,_(r)],[a,e])}const k=await v(c,i,"plugins");if(k!==null){const e=l(async t=>{if(t.startsWith("app:"))return t;if(t==="user")return"app:terminal";if(!t.startsWith("profile:"))throw new Error(`unsupported install owner in the bundle: ${t}`);return(await o.prepare("SELECT grantee FROM profiles WHERE id = ?").get(_(t.slice(8))))?.grantee??"app:terminal"},"appOf"),r=new Map;for(const t of new Set([...k.marketplaces,...k.plugins].map(u=>u.owner)))t.startsWith("profile:")&&r.set(t,(await o.prepare("SELECT last_used_at FROM profiles WHERE id = ?").get(_(t.slice(8))))?.last_used_at??"");const s=l(t=>[...t].sort((u,E)=>K(p(u.owner),r.get(u.owner)??"",p(E.owner),r.get(E.owner)??"")),"byProfileFirst"),d=new Map;for(const t of s(k.marketplaces)){const u=await e(t.owner),E=new Map((await o.prepare("SELECT name, url FROM scope_marketplaces WHERE person = ? AND owner_key = ?").all(a,u)).map(N=>[N.name,N.url]));let S=t.name;for(let N=2;E.has(S)&&E.get(S)!==(t.url??null);N+=1)S=`${t.name}-${N}`;d.set(`${t.owner}\0${t.name}`,S),await m("scope_marketplaces","INSERT INTO scope_marketplaces (person, owner_key, name, last_updated, url, ref, installed_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[a,u,S,t.last_updated??null,t.url??null,t.ref??null,t.installed_at??null],[a,u,S])}for(const t of s(k.plugins)){if(!B(t)){g.push(`${t.owner}:${t.name}`);continue}const u=await e(t.owner),E=t.source_marketplace==null?null:d.get(`${t.owner}\0${t.source_marketplace}`)??t.source_marketplace;await m("scope_plugins","INSERT INTO scope_plugins (person, owner_key, name, last_updated, etag, checked_at, enabled, source_marketplace, version, source_path) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[a,u,t.name,t.last_updated??null,t.etag??null,t.checked_at??null,t.enabled?1:0,E,t.version??null,t.source_path??null],[a,u,t.name])}(f.scope_plugins??[]).length+(f.scope_marketplaces??[]).length>0&&await m("person_settings","INSERT INTO person_settings (person, plugins_revision) VALUES (?, 1)",[a],[a])}for(const[e,r]of Object.entries(f))await o.prepare("INSERT INTO import_manifest (run_id, table_name, inserted_keys) VALUES (?, ?, ?) ON CONFLICT (run_id, table_name) DO UPDATE SET inserted_keys = EXCLUDED.inserted_keys").run(i,e,W(r));return Object.keys(f).length>0&&await o.prepare("SELECT pg_notify('crtr_signal', ?)").get(`settings:${a}`),{inserted:f,unresolvedPlugins:g}}l(re,"writeStores");async function ne(n,o,c){const i=await n.prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ? AND table_name IN ('model_accounts', 'model_api_keys')").all(o),a=l(p=>i.filter(f=>f.table_name===p).flatMap(f=>M(f.inserted_keys)),"keys"),_=[...[...new Set(a("model_accounts").map(p=>p[1]))].map(p=>({kind:"subscription",provider:p})),...a("model_api_keys").map(p=>({kind:"api_key",provider:p[1]}))];for(const{kind:p,provider:f}of _){const g=U("sha256").update(JSON.stringify([o,p,f])).digest("hex"),y=`${g.slice(0,8)}-${g.slice(8,12)}-4${g.slice(13,16)}-8${g.slice(17,20)}-${g.slice(20,32)}`;await H(c,p,f,y)}}l(ne,"recordImportedActivations");export{P as STORE_NAMES,J as StoreBodyError,oe as allStoreKeys,B as hasFleetSource,te as putStore,ae as readPluginsStore,ne as recordImportedActivations,T as storeKey,re as writeStores};
@@ -1 +1 @@
1
- var m=Object.defineProperty;var t=(e,r)=>m(e,"name",{value:r,configurable:!0});import{randomUUID as y}from"node:crypto";import{withCanvasWrite as S}from"../canvas/db.js";import{takePercent as k}from"./rates.js";import{usageMonth as w}from"./months.js";const U=t((e,r)=>`receipt:${e}:${r}`,"receiptChargeId"),c="id, request, at, month, kind, what, units, usd, payer, funding, sub, grantee, node, run, provider, caused_by, vendor_ref, refused, account, billed_usd, usd_rolled_by_trigger",i="?, ?, ?, ?, ?, ?, ?::jsonb, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?::jsonb, ?, ?, true";async function _(e){const r=e.at??new Date,n=e.refused??null,s=e.id??y(),f=w(r),o=n?0:e.usd,a=k();return await S(async d=>{const u=t((g,O,N,h,I)=>[g,e.request??null,r.toISOString(),f,O,N,e.units==null?null:JSON.stringify(e.units),h,e.payer,I,e.sub??null,e.grantee,e.node??null,e.run??null,e.provider??null,e.causedBy??null,e.vendorRef??null,n===null?null:JSON.stringify(n),e.account??null,e.billedUsd??null],"row");if((await d.prepare(`INSERT INTO charges (${c}) VALUES (${i}) ON CONFLICT (id) DO NOTHING`).run(...u(s,e.kind,e.what,o,e.funding))).changes===0)return{written:!1,id:s,takeId:null};let l=null;return a>0&&n===null&&(e.kind==="model"||e.kind==="tool")&&o!==null&&o>0&&(l=`take:${s}`,await d.prepare(`INSERT INTO charges (${c}) VALUES (${i}) ON CONFLICT (id) DO NOTHING`).run(...u(l,"take",e.what,o*a/100,"take"))),{written:!0,id:s,takeId:l}})}t(_,"writeCharge");function D(e){const r=t(n=>typeof n=="string"?JSON.parse(n):typeof n=="object"?n:null,"json");return{...e,units:r(e.units),refused:r(e.refused)}}t(D,"chargeOf");export{D as chargeOf,U as receiptChargeId,_ as writeCharge};
1
+ var I=Object.defineProperty;var t=(e,r)=>I(e,"name",{value:r,configurable:!0});import{randomUUID as y}from"node:crypto";import{withCanvasWrite as S}from"../canvas/db.js";import{takePercent as k}from"./rates.js";import{usageMonth as w}from"./months.js";const E=t((e,r)=>`receipt:${e}:${r}`,"receiptChargeId"),c="id, request, at, month, kind, what, units, usd, payer, funding, sub, grantee, node, run, provider, caused_by, vendor_ref, refused, account, billed_usd, admission, admitted_as, cost_usd, cost_source, usd_rolled_by_trigger",i="?, ?, ?, ?, ?, ?, ?::jsonb, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?::jsonb, ?, ?, ?, ?, ?, ?, true";async function U(e){const r=e.at??new Date,n=e.refused??null,s=e.id??y(),f=w(r),l=n?0:e.usd,a=k();return await S(async d=>{const u=t((g,O,N,m,h)=>[g,e.request??null,r.toISOString(),f,O,N,e.units==null?null:JSON.stringify(e.units),m,e.payer,h,e.sub??null,e.grantee,e.node??null,e.run??null,e.provider??null,e.causedBy??null,e.vendorRef??null,n===null?null:JSON.stringify(n),e.account??null,e.billedUsd??null,null,null,null,null],"row");if((await d.prepare(`INSERT INTO charges (${c}) VALUES (${i}) ON CONFLICT (id) DO NOTHING`).run(...u(s,e.kind,e.what,l,e.funding))).changes===0)return{written:!1,id:s,takeId:null};let o=null;return a>0&&n===null&&(e.kind==="model"||e.kind==="tool")&&l!==null&&l>0&&(o=`take:${s}`,await d.prepare(`INSERT INTO charges (${c}) VALUES (${i}) ON CONFLICT (id) DO NOTHING`).run(...u(o,"take",e.what,l*a/100,"take"))),{written:!0,id:s,takeId:o}})}t(U,"writeCharge");function D(e){const r=t(n=>typeof n=="string"?JSON.parse(n):typeof n=="object"?n:null,"json");return{...e,units:r(e.units),refused:r(e.refused)}}t(D,"chargeOf");export{D as chargeOf,E as receiptChargeId,U as writeCharge};
@@ -1 +1 @@
1
- var i=Object.defineProperty;var r=(n,t)=>i(n,"name",{value:t,configurable:!0});import{openDb as u}from"../canvas/db.js";import{RunError as s}from"../runs/operations.js";import{usageMonth as c}from"./months.js";async function a(n,t=new Date){const e={...n,month:c(t)},o=await(await u()).prepare("SELECT ledger_check(?::jsonb) AS refusal").get(JSON.stringify(e));return typeof o?.refusal=="string"?JSON.parse(o.refusal):o?.refusal??null}r(a,"findRefusal");function d(n){return n==="grant_sync"?"raise_cap":n==="person"?"clear_limit":void 0}r(d,"userActionOf");function p(n){const{limit:t}=n,e=d(t.source);return new s(402,"cap_exhausted",`${t.payer??t.account} reached its monthly limit (${t.id})`,void 0,{limit:{id:t.id,payer:t.payer,account:t.account,filters:{account:t.account,funding:t.funding,grantee:t.grantee,provider:t.provider,sub:t.sub},usd_per_month:t.usd_per_month,source:t.source},usd:n.usd,reset_at:n.reset_at,spend_cap:t.usd_per_month,usd_equivalent:n.usd,...e===void 0?{}:{user_action:e}})}r(p,"refusalError");async function g(n,t){const e=await a(n,t);if(e!==null)throw p(e)}r(g,"check");const y=r(n=>({limit:n.limit.id,reason:`${n.limit.payer??n.limit.account} reached ${n.limit.usd_per_month} USD this month (spent ${n.usd})`}),"refusedMark");export{g as check,a as findRefusal,p as refusalError,y as refusedMark,d as userActionOf};
1
+ var o=Object.defineProperty;var r=(e,t)=>o(e,"name",{value:t,configurable:!0});import{openDb as s}from"../canvas/db.js";import{RunError as a}from"../runs/operations.js";import{usageMonth as u}from"./months.js";async function c(e,t=new Date){const n={...e,month:u(t)},i=await(await s()).prepare("SELECT ledger_check(?::jsonb) AS refusal").get(JSON.stringify(n));return typeof i?.refusal=="string"?JSON.parse(i.refusal):i?.refusal??null}r(c,"findRefusal");function p(e){return e==="grant_sync"?"raise_cap":e==="person"?"clear_limit":void 0}r(p,"userActionOf");function d(e){const{limit:t}=e,n=p(t.source);return new a(402,"cap_exhausted",`${t.payer??t.account} reached its monthly limit (${t.id})`,void 0,{limit:{id:t.id,payer:t.payer,account:t.account,filters:{account:t.account,funding:t.funding,grantee:t.grantee,provider:t.provider,sub:t.sub},usd_per_month:t.usd_per_month,source:t.source},usd:e.usd,reset_at:e.reset_at,spend_cap:t.usd_per_month,usd_equivalent:e.usd,...n===void 0?{}:{user_action:n},...t.source==="grant_sync"?{payment:{reason:"app_limit",message:"This app reached its monthly spending limit for your account",pay_url:null,reset_at:e.reset_at}}:{}})}r(d,"refusalError");async function y(e,t){const n=await c(e,t);if(n!==null)throw d(n)}r(y,"check");const g=r(e=>({limit:e.limit.id,reason:`${e.limit.payer??e.limit.account} reached ${e.limit.usd_per_month} USD this month (spent ${e.usd})`}),"refusedMark");export{y as check,c as findRefusal,d as refusalError,g as refusedMark,p as userActionOf};
@@ -1,2 +1,2 @@
1
- var f=Object.defineProperty;var u=(t,e)=>f(t,"name",{value:e,configurable:!0});import{zstdDecompressSync as l}from"node:zlib";import{blobStore as h}from"../blobs/index.js";import{openDb as b}from"../canvas/db.js";import{chargeOf as p}from"./charges.js";const g=["id","request","at","month","kind","what","units","usd","payer","funding","sub","grantee","node","run","provider","caused_by","vendor_ref","refused","account","billed_usd"];class _{static{u(this,"ChunkRows")}byMonth=new Map;all;rows(e){if(e===void 0)return this.all??=this.load(void 0);let n=this.byMonth.get(e);return n===void 0&&(n=this.load(e),this.byMonth.set(e,n)),n}async load(e){const n=await(await b()).prepareUncached(`SELECT blob_key FROM charge_chunks${e===void 0?"":" WHERE month = ?"} ORDER BY month, payer`).all(...e===void 0?[]:[e]);if(n.length===0)return[];const d=await h(),r=[];for(const{blob_key:o}of n){const s=await d.get(o);if(s===null)throw new Error(`charge chunk ${o} is recorded in charge_chunks but its blob is missing`);for(const i of l(s).toString("utf8").split(`
2
- `)){if(i==="")continue;const c=JSON.parse(i);r.push(p(Object.fromEntries(g.map(a=>[a,c[a]??null]))))}}return r}}export{_ as ChunkRows};
1
+ var f=Object.defineProperty;var u=(n,e)=>f(n,"name",{value:e,configurable:!0});import{zstdDecompressSync as l}from"node:zlib";import{blobStore as h}from"../blobs/index.js";import{openDb as b}from"../canvas/db.js";import{chargeOf as p}from"./charges.js";const m=["id","request","at","month","kind","what","units","usd","payer","funding","sub","grantee","node","run","provider","caused_by","vendor_ref","refused","account","billed_usd","admission","admitted_as","cost_usd","cost_source"];class E{static{u(this,"ChunkRows")}byMonth=new Map;all;rows(e){if(e===void 0)return this.all??=this.load(void 0);let t=this.byMonth.get(e);return t===void 0&&(t=this.load(e),this.byMonth.set(e,t)),t}async load(e){const t=await(await b()).prepareUncached(`SELECT blob_key FROM charge_chunks${e===void 0?"":" WHERE month = ?"} ORDER BY month, payer`).all(...e===void 0?[]:[e]);if(t.length===0)return[];const d=await h(),o=[];for(const{blob_key:r}of t){const s=await d.get(r);if(s===null)throw new Error(`charge chunk ${r} is recorded in charge_chunks but its blob is missing`);for(const i of l(s).toString("utf8").split(`
2
+ `)){if(i==="")continue;const c=JSON.parse(i);o.push(p(Object.fromEntries(m.map(a=>[a,c[a]??null]))))}}return o}}export{E as ChunkRows};
@@ -1,2 +1,2 @@
1
- var O=Object.defineProperty;var d=(n,e)=>O(n,"name",{value:e,configurable:!0});import{openDb as m}from"../canvas/db.js";import{subjectSet as S}from"../permissions/evaluator.js";import{RunError as E}from"../runs/operations.js";import{appsHeldBy as A}from"./account.js";import{chargeOf as R}from"./charges.js";import{ChunkRows as w}from"./chunks.js";import{listLimits as N}from"./limits.js";import{resetAt as L,usageMonth as g}from"./months.js";const b="id, request, at, month, kind, what, units, usd, payer, funding, sub, grantee, node, run, provider, caused_by, vendor_ref, refused, account, billed_usd";async function J(n,e=g(),s){const o=await m(),p=await o.prepare(`SELECT payer, what, kind, units, usd FROM charges
1
+ var O=Object.defineProperty;var d=(n,e)=>O(n,"name",{value:e,configurable:!0});import{openDb as m}from"../canvas/db.js";import{subjectSet as S}from"../permissions/evaluator.js";import{RunError as E}from"../runs/operations.js";import{appsHeldBy as A}from"./account.js";import{chargeOf as R}from"./charges.js";import{ChunkRows as w}from"./chunks.js";import{listLimits as N}from"./limits.js";import{resetAt as L,usageMonth as g}from"./months.js";const b="id, request, at, month, kind, what, units, usd, payer, funding, sub, grantee, node, run, provider, caused_by, vendor_ref, refused, account, billed_usd, admission, admitted_as, cost_usd, cost_source";async function J(n,e=g(),s){const o=await m(),p=await o.prepare(`SELECT payer, what, kind, units, usd FROM charges
2
2
  WHERE grantee = ? AND month = ? AND refused IS NULL AND kind <> 'take'${s===void 0?"":" AND sub = ?"}`).all(...s===void 0?[n,e]:[n,e,s]);for(const r of await new w().rows(e))r.grantee===n&&(s===void 0||r.sub===s)&&r.refused===null&&r.kind!=="take"&&p.push(r);const f=d(r=>{const a=new Map;for(const u of p){if(u.kind!=="model"||!u.payer.startsWith(r))continue;const h=u.units===null?{}:typeof u.units=="string"?JSON.parse(u.units):u.units,i=a.get(u.what)??{served_model:u.what,input_tokens:0,output_tokens:0,usd_equivalent:null};i.input_tokens+=h.input??0,i.output_tokens+=h.output??0,u.usd!==null&&(i.usd_equivalent=(i.usd_equivalent??0)+Number(u.usd)),a.set(u.what,i)}return[...a.values()].sort((u,h)=>u.served_model<h.served_model?-1:1)},"byModel"),c=d(r=>p.filter(a=>a.payer.startsWith(r)).reduce((a,u)=>a+Number(u.usd??0),0),"sum"),t=await o.prepare(`SELECT usd_per_month FROM limits WHERE source = 'grant_sync' AND grantee = ? AND payer LIKE 'user:%' AND funding IS NULL AND provider IS NULL${s===void 0?"":" AND payer = ?"} ORDER BY id LIMIT 1`).get(...s===void 0?[n]:[n,s]);return{grantee:n,month:e,usd_equivalent:c("user:"),by_model:f("user:"),app_paid:{usd_equivalent:c("app:"),by_model:f("app:")},spend_cap:t===void 0?null:Number(t.usd_per_month),reset_at:L(e)}}d(J,"usageFor");const D=/^(message|request|cron_run|run):(.+)$/;async function M(n,e){const s=D.exec(n);if(s===null)return{sql:"id = ?",params:[n],test:d(t=>t.id===n,"test")};if(s[1]==="message"||s[1]==="cron_run")return{sql:"caused_by = ?",params:[n],test:d(t=>t.caused_by===n,"test")};if(s[1]==="request")return{sql:"(request = ? OR caused_by = ?)",params:[s[2],n],test:d(t=>t.request===s[2]||t.caused_by===n,"test")};const o=s[2],p=await m(),f=new Set((await p.prepare("SELECT DISTINCT request FROM charges WHERE run = ? AND request IS NOT NULL").all(o)).map(t=>t.request));for(const t of await e.rows())t.run===o&&t.request!==null&&f.add(t.request);const c=new Set([o]);if(f.size>0){const t=await p.prepare("SELECT n.run_id FROM nodes n WHERE n.run_id IS NOT NULL AND n.node_id = n.run_id AND n.caused_by = ANY(?::text[])").all([...f].map(r=>`request:${r}`));for(const r of t)c.add(r.run_id)}return{sql:"run = ANY(?::text[])",params:[[...c]],test:d(t=>t.run!==null&&c.has(t.run),"test")}}d(M,"referenceMatch");function v(n){return"person"in n?{sql:"(sub = ? OR payer = ? OR account = ?)",params:[n.person,n.person,n.person]}:n.sub===void 0?{sql:"(grantee = ? OR payer = ?)",params:[n.app,n.app]}:{sql:"((grantee = ? OR payer = ?) AND sub = ?)",params:[n.app,n.app,n.sub]}}d(v,"readerCondition");const _=d((n,e)=>"person"in e?n.sub===e.person||n.payer===e.person||n.account===e.person:(n.grantee===e.app||n.payer===e.app)&&(e.sub===void 0||n.sub===e.sub),"mayRead");async function C(n,e,s){const o=await m(),p=new Map,f=d(async c=>{const t=c.caused_by;if(t===null||!t.startsWith("request:"))return;const r=t.slice(8),a=[...(await o.prepare(`SELECT ${b} FROM charges WHERE request = ? AND id <> ?`).all(r,c.id)).map(R),...(await s.rows()).filter(u=>u.request===r&&u.id!==c.id)].sort(q);return a.find(u=>_(u,e))??a[0]},"parentOf");for(const c of n){let t=c;for(let r=0;t!==void 0&&!_(t,e)&&r<64;r+=1)t=await f(t);t!==void 0&&_(t,e)&&p.set(t.id,t)}return[...p.values()]}d(C,"visibleChain");const q=d((n,e)=>n.at<e.at?-1:n.at>e.at?1:n.id<e.id?-1:n.id>e.id?1:0,"byAtId"),T=d(n=>Buffer.from(JSON.stringify([n.at,n.id]),"utf8").toString("base64url"),"encodeCursor");function k(n){try{const e=JSON.parse(Buffer.from(n,"base64url").toString("utf8"));if(Array.isArray(e)&&e.length===2&&typeof e[0]=="string"&&typeof e[1]=="string")return[e[0],e[1]]}catch{}throw new E(400,"invalid_request","cursor must be a `next` value from a previous page","after")}d(k,"decodeCursor");async function P(n={}){const e=Math.min(Math.max(Math.trunc(n.limit??1e3),1),1e4),s=new w,o=[],p=[],f=[];let c;if(n.under!==void 0){const i=await M(n.under,s);o.push(i.sql),p.push(...i.params),f.push(i.test),n.month!==void 0&&(o.push("month = ?"),p.push(n.month),f.push(l=>l.month===n.month),c=n.month)}else{const i=n.month??g();o.push("month = ?"),p.push(i),c=i}if(n.under===void 0&&n.reader!==void 0){const i=v(n.reader);o.push(i.sql),p.push(...i.params);const l=n.reader;f.push(y=>_(y,l))}if(n.after!==void 0){const[i,l]=k(n.after);o.push("(at, id) > (?, ?)"),p.push(i,l),f.push(y=>y.at>i||y.at===i&&y.id>l)}const t=(await(await m()).prepare(`SELECT ${b} FROM charges WHERE ${o.join(" AND ")} ORDER BY at, id LIMIT ${e+1}`).all(...p)).map(R),r=(await s.rows(c)).filter(i=>f.every(l=>l(i))),a=[...t,...r].sort(q).slice(0,e+1),u=a.slice(0,e);return{charges:n.under!==void 0&&n.reader!==void 0?await C(u,n.reader,s):u,next:a.length>e?T(u[e-1]):null}}d(P,"listCharges");async function I(n){const e=await m(),{groupIds:s}=await S(e,n.slice(5));return[n,...await A(e,[n,...s])]}d(I,"payersOf");async function j(n=g(),e){const s=await m(),o=e===void 0?void 0:await I(e),p=o===void 0?"":" AND payer = ANY(?::text[])",f=o===void 0?[n]:[n,o],c=await s.prepare(`SELECT payer, SUM(usd) AS usd FROM charge_totals WHERE month = ?${p} GROUP BY payer ORDER BY payer`).all(...f),t=await s.prepare(`SELECT payer, funding, SUM(usd) AS usd FROM charge_totals WHERE month = ?${p} GROUP BY payer, funding ORDER BY payer, funding`).all(...f),r=o===void 0?await N():(await N()).filter(a=>a.payer!==null&&o.includes(a.payer)||a.account===e);return{month:n,by_payer:c.map(a=>({payer:a.payer,usd:Number(a.usd)})),by_funding:t.map(a=>({payer:a.payer,funding:a.funding,usd:Number(a.usd)})),limits:r}}d(j,"monthTotals");function z(n){if(n.length===0||n.length>512)throw new E(400,"invalid_request","under must be a reference or a charge id","under");return n}d(z,"assertReference");export{z as assertReference,P as listCharges,j as monthTotals,I as payersOf,J as usageFor};
@@ -1,5 +1,6 @@
1
1
  export type ChargeKind = 'model' | 'tool' | 'sandbox' | 'job' | 'storage' | 'take';
2
2
  export type Funding = 'bill' | 'subscription' | 'key' | 'endpoint' | 'take' | 'legacy';
3
+ export type CostSource = 'vendor_usage' | 'provider_receipt' | 'runtime_estimate';
3
4
  export type LimitSource = 'grant_sync' | 'person' | 'operator' | 'billing' | 'card';
4
5
  /** Why the check refused a call: the limit's id and a sentence. Stored on the refused row. */
5
6
  export interface RefusedMark {
@@ -29,6 +30,13 @@ export interface Charge {
29
30
  refused: RefusedMark | null;
30
31
  account: string | null;
31
32
  billed_usd: number | null;
33
+ /** The external admission id this charge settles under; null when nothing admitted it. */
34
+ admission: string | null;
35
+ /** The admitting authority's opaque funding label; core never interprets it. */
36
+ admitted_as: string | null;
37
+ /** What the call actually cost whoever funds it; null until settled. */
38
+ cost_usd: number | null;
39
+ cost_source: CostSource | null;
32
40
  }
33
41
  /** What a site hands `writeCharge`. */
34
42
  export interface ChargeInput {
@@ -0,0 +1,17 @@
1
+ import type { LlmRequest } from './run.js';
2
+ import { type MergedLaunchConfig } from '../config.js';
3
+ import { type ModelRequest, type RoutedCandidate } from '../model-routes.js';
4
+ import { openModelRegistry } from '../runtime/model-registry.js';
5
+ export declare function requestFor(model: string | undefined, policy: LlmRequest['model_policy'], cwd?: string, profileId?: string | null, config?: MergedLaunchConfig): ModelRequest;
6
+ /** Whether the catalog model behind `candidate` can serve the request's features (reasoning, seed, response format, stop). */
7
+ export declare function matchesFeatures(registry: Awaited<ReturnType<typeof openModelRegistry>>, input: OwnerCandidateInput, candidate: RoutedCandidate): boolean;
8
+ type OwnerCandidateInput = Pick<LlmRequest, 'model' | 'model_policy' | 'reasoning_effort' | 'seed' | 'response_format' | 'stop'>;
9
+ /** The candidates the person's own ladders and routes give a request, before any credential is probed. */
10
+ export declare function ownerCandidates(registry: Awaited<ReturnType<typeof openModelRegistry>>, input: OwnerCandidateInput, target?: {
11
+ cwd: string;
12
+ profileId: string | null;
13
+ }, config?: MergedLaunchConfig): Promise<RoutedCandidate[]>;
14
+ /** Whether a call adds the hosted endpoint as its last route (contract §5): never for an exact call, and never without an owner
15
+ * candidate to name the rung. `runLlm` asks it, and so does every gate that asks whether a launch can run without a credential of its own. */
16
+ export declare function hostedRouteApplies(policy: LlmRequest['model_policy'], candidates: readonly RoutedCandidate[]): boolean;
17
+ export {};
@@ -0,0 +1 @@
1
+ var k=Object.defineProperty;var a=(r,o)=>k(r,"name",{value:o,configurable:!0});import{readMergedLaunchConfig as g}from"../config.js";import{APP_FAMILY as v,expandModelCandidates as h,parseModelSpec as w}from"../model-routes.js";function y(r,o,d,l,t){const f=a(()=>{const e=t??g(d,l),c=Object.values({...e.modelRoutes??{},...e.legacyModelRoutes??{}});return c.length?[e.modelLadders.defaultProvider,...e.modelRouting?.familyOrder??[],...c.map(s=>s.family)].find(s=>c.some(m=>m.family===s)):e.modelLadders.defaultProvider??"anthropic"},"ownerFamily");if(!r){const e=f();return{kind:"logical",family:e,strength:"strong",spec:`${e}/strong`}}const n=/^([^/]+)\/(ultra|strong|medium|light)$/.exec(r);if(n){if(n[1]===v){const e=f();return{kind:"logical",family:e,strength:n[2],spec:`${e}/${n[2]}`}}return{kind:"logical",family:n[1],strength:n[2],spec:r}}return{kind:o==="exact"?"exact":"concrete",spec:r}}a(y,"requestFor");const x=a(r=>r.unrouted!==!0,"configured");function I(r,o,d){const l=r.find(d.providerId,d.modelId);return l!==void 0&&(!o.reasoning_effort||l.reasoning)&&(o.seed===void 0&&o.response_format===void 0||l.api==="openai-completions")&&(o.stop===void 0||["openai-completions","anthropic-messages"].includes(l.api))}a(I,"matchesFeatures");async function b(r,o,d,l){const t=y(o.model,o.model_policy,d?.cwd,d?.profileId,l),f=(await h(t.kind==="exact"?{kind:"concrete",spec:t.spec}:t,d?.cwd,d?.profileId,l)).filter(x);let n;if(t.kind==="logical")n=o.model_policy==="exact"?f.filter(e=>e.family===t.family&&e.strength===t.strength).slice(0,1):f;else{const e=w(t.spec),c=f.filter(s=>s.providerId===e?.providerId&&s.modelId===e.modelId&&(o.model_policy!=="exact"||s.thinkingLevel===e.thinkingLevel)&&I(r,o,s));if(o.model_policy==="exact")n=c.slice(0,1);else if(c.length)n=c;else{const s=l??g(d?.cwd,d?.profileId),p=[...Object.values(s.modelRoutes??{}).flatMap(i=>Object.entries(i.models)),...[s.modelLadders.anthropic,s.modelLadders.openai].flatMap(i=>Object.entries(i))].find(([,i])=>i===t.spec)?.[0],u=y(void 0,"substitute",d?.cwd,d?.profileId,l);n=p&&u.kind==="logical"?(await h({...u,strength:p,spec:t.spec},d?.cwd,d?.profileId,l)).filter(i=>x(i)&&i.strength===p):[]}}return n.filter(e=>I(r,o,e))}a(b,"ownerCandidates");function C(r,o){return r!=="exact"&&o.length>0}a(C,"hostedRouteApplies");export{C as hostedRouteApplies,I as matchesFeatures,b as ownerCandidates,y as requestFor};
@@ -1,3 +1,3 @@
1
- var Oe=Object.defineProperty;var c=(e,t)=>Oe(e,"name",{value:t,configurable:!0});import{randomUUID as Se}from"node:crypto";import{streamSimple as Le}from"@earendil-works/pi-ai/compat";import{probeRouteAvailability as Ee}from"../model-routes-pool.js";import{APP_FAMILY as Fe,expandModelCandidates as _e,parseModelSpec as ye}from"../model-routes.js";import{readMergedLaunchConfig as ge}from"../config.js";import{openModelRegistry as Ne}from"../runtime/model-registry.js";import{MAX_RATE_LIMIT_COOLDOWN_MS as we,coolingUntilFor as be,isManagedProvider as Y,markSubscriptionRateLimited as De,markSubscriptionSuccess as Pe,readSubscriptionPool as Te,retryAfterMsFromHeaders as Z,retryAfterMsFromError as Je,refreshSubscriptionCredential as Ke,subscriptionNeedsSuccessWrite as We,RefreshBusyError as Ue,RefreshTimeoutError as Be}from"../subscription-state.js";import{classifyRateLimit as He,describeRateLimitScope as ve,rateLimitHeaders as ze}from"../rate-limit-scope.js";import{RunError as s}from"../runs/operations.js";import{recognizeProviderError as le}from"../provider-error-recognition.js";import{isSafetyRefusal as Xe}from"./refusal.js";import{findRefusal as Ge,payerOf as ke,refusalError as Ye,refusedMark as Ze,writeCharge as xe}from"../ledger/index.js";import{storedApiKey as Qe}from"../auth-file.js";import{personIdAsync as Ve}from"../canvas/person.js";import{getNode as qe}from"../canvas/canvas.js";import{outboundToken as et}from"../providers/mint.js";import{discardFile as tt}from"../providers/token-cache.js";import{ProviderError as nt}from"../providers/errors.js";import{appCandidates as ot}from"./app-rungs.js";function rt(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)))}c(rt,"validContent");function Ae(e){return Array.isArray(e)?e.map(t=>{if(t.type==="text")return t;const[,o,i]=/^data:(image\/(?:png|jpeg|gif|webp));base64,(.*)$/.exec(t.image_url.url);return{type:"image",mimeType:o,data:i}}):e??""}c(Ae,"imageContent");function it(e,t){const o=(e instanceof Error?e.message:String(e)).split("; stack=",1)[0],i=le({message:o}).kind;return i!=="connection"&&i!=="connection-only"?e:new s(503,"upstream_model_unavailable",o.slice(0,500),void 0,{served_model:t})}c(it,"refreshFailure");function Lt(e){if(!e||typeof e!="object"||Array.isArray(e))throw new s(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)&&rt(o.content)))throw new s(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 s(400,"invalid_request","system and assistant content must be text","messages");if(t.model!==void 0&&typeof t.model!="string")throw new s(400,"invalid_request","model must be a string","model");if(t.model_policy!==void 0&&!["exact","substitute"].includes(t.model_policy))throw new s(400,"invalid_request","invalid model_policy","model_policy");if(t.payer!==void 0&&!["user","app"].includes(t.payer))throw new s(400,"invalid_request","invalid payer","payer");if(t.reasoning_effort!==void 0&&!["minimal","low","medium","high","xhigh","max"].includes(t.reasoning_effort))throw new s(400,"invalid_request","invalid reasoning_effort","reasoning_effort");if(t.stream!==void 0&&typeof t.stream!="boolean")throw new s(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 s(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 s(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(i=>i&&typeof i.id=="string"&&typeof i.function?.name=="string"&&typeof i.function.arguments=="string"&&st(i.function.arguments)))))throw new s(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 s(400,"invalid_request","invalid stop","stop");if(t.seed!==void 0&&!Number.isSafeInteger(t.seed))throw new s(400,"invalid_request","invalid seed","seed");for(const[o,i]of[["temperature",t.temperature],["top_p",t.top_p],["max_tokens",t.max_tokens]])if(i!==void 0&&(typeof i!="number"||!Number.isFinite(i)||o==="temperature"&&(i<0||i>2)||o==="top_p"&&(i<0||i>1)||o==="max_tokens"&&(!Number.isSafeInteger(i)||i<1)))throw new s(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 s(400,"invalid_request","invalid response_format","response_format")}if(t.metadata!==void 0&&Buffer.byteLength(JSON.stringify(t.metadata)??"")>4096)throw new s(400,"invalid_request","metadata exceeds 4 KB","metadata");return t}c(Lt,"parseLlmRequest");function st(e){try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)}catch{return!1}}c(st,"isJsonObject");function at(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??""}]:Ae(r.content),isError:!1,timestamp:t}:r.role==="assistant"?{role:"assistant",content:[...r.content?[{type:"text",text:r.content}]:[],...(r.tool_calls??[]).map(_=>({type:"toolCall",id:_.id,name:_.function.name,arguments:JSON.parse(_.function.arguments)}))],api:"openai-completions",provider:"openai",model:e.model??"",usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:t}:{role:"user",content:Ae(r.content),timestamp:t}),i=o.findIndex(r=>r.role!=="system"),l=o.slice(0,i<0?o.length:i).map(r=>r.content),w=l.join(`
1
+ var We=Object.defineProperty;var c=(e,t)=>We(e,"name",{value:t,configurable:!0});import{randomUUID as He}from"node:crypto";import{streamSimple as ze}from"@earendil-works/pi-ai/compat";import{keyRouteProviders as Xe,probeRouteAvailability as Ge}from"../model-routes-pool.js";import{KEY_CREDENTIAL_SOURCE as Ve,parseModelSpec as $e}from"../model-routes.js";import{openModelRegistry as Ye}from"../runtime/model-registry.js";import{isInvalidRefreshTokenError as Ze}from"../managed-providers.js";import{MAX_RATE_LIMIT_COOLDOWN_MS as Ce,coolingUntilFor as Se,isManagedProvider as W,markSubscriptionRateLimited as Qe,markSubscriptionSuccess as et,readSubscriptionPool as tt,retryAfterMsFromHeaders as H,retryAfterMsFromError as nt,refreshSubscriptionCredential as ot,subscriptionNeedsSuccessWrite as rt,RefreshBusyError as it,RefreshTimeoutError as at}from"../subscription-state.js";import{classifyRateLimit as st,describeRateLimitScope as Ee,rateLimitHeaders as dt}from"../rate-limit-scope.js";import{RunError as r}from"../runs/operations.js";import{recognizeProviderError as ye}from"../provider-error-recognition.js";import{isSafetyRefusal as lt}from"./refusal.js";import{findRefusal as ut,payerOf as Ie,refusalError as ct,refusedMark as ft,writeCharge as ge}from"../ledger/index.js";import{storedApiKey as Oe}from"../auth-file.js";import{eligibleHostedEndpoint as mt,readHostedEndpoint as De}from"../grants/hosted-endpoint.js";import{parseProviderPayment as pt}from"../provider-failure.js";import{personIdAsync as ht}from"../canvas/person.js";import{getNode as Ne}from"../canvas/canvas.js";import{outboundToken as Te}from"../providers/mint.js";import{discardFile as Fe}from"../providers/token-cache.js";import{ProviderError as _t}from"../providers/errors.js";import{appCandidates as yt}from"./app-rungs.js";import{hostedRouteApplies as gt,matchesFeatures as wt,ownerCandidates as bt}from"./owner-candidates.js";function vt(e){return typeof e=="string"||e===null||Array.isArray(e)&&e.every(t=>t&&typeof t=="object"&&(t.type==="text"&&typeof t.text=="string"||t.type==="image_url"&&typeof t.image_url?.url=="string"&&/^data:image\/(png|jpeg|gif|webp);base64,[A-Za-z0-9+/]+={0,2}$/.test(t.image_url.url)))}c(vt,"validContent");function Pe(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??""}c(Pe,"imageContent");function kt(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 r(503,"upstream_model_unavailable",o.slice(0,500),void 0,{served_model:t})}c(kt,"refreshFailure");function nn(e){if(!e||typeof e!="object"||Array.isArray(e))throw new r(400,"invalid_request","body must be an object");const t=e;if(!Array.isArray(t.messages)||!t.messages.every(o=>o&&typeof o=="object"&&["system","user","assistant","tool"].includes(o.role)&&vt(o.content)))throw new r(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 r(400,"invalid_request","system and assistant content must be text","messages");if(t.model!==void 0&&typeof t.model!="string")throw new r(400,"invalid_request","model must be a string","model");if(t.model_policy!==void 0&&!["exact","substitute"].includes(t.model_policy))throw new r(400,"invalid_request","invalid model_policy","model_policy");if(t.payer!==void 0&&!["user","app"].includes(t.payer))throw new r(400,"invalid_request","invalid payer","payer");if(t.reasoning_effort!==void 0&&!["minimal","low","medium","high","xhigh","max"].includes(t.reasoning_effort))throw new r(400,"invalid_request","invalid reasoning_effort","reasoning_effort");if(t.stream!==void 0&&typeof t.stream!="boolean")throw new r(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 r(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 r(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 r(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 r(400,"invalid_request","invalid stop","stop");if(t.seed!==void 0&&!Number.isSafeInteger(t.seed))throw new r(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 r(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 r(400,"invalid_request","invalid response_format","response_format")}if(t.metadata!==void 0&&Buffer.byteLength(JSON.stringify(t.metadata)??"")>4096)throw new r(400,"invalid_request","metadata exceeds 4 KB","metadata");return t}c(nn,"parseLlmRequest");function xt(e){try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)}catch{return!1}}c(xt,"isJsonObject");function Rt(e){const t=Date.now(),o=e.messages.map(i=>i.role==="system"?{role:"system",content:i.content??"",timestamp:t}:i.role==="tool"?{role:"toolResult",toolCallId:i.tool_call_id??"",toolName:"",content:typeof i.content=="string"||i.content===null?[{type:"text",text:i.content??""}]:Pe(i.content),isError:!1,timestamp:t}:i.role==="assistant"?{role:"assistant",content:[...i.content?[{type:"text",text:i.content}]:[],...(i.tool_calls??[]).map(_=>({type:"toolCall",id:_.id,name:_.function.name,arguments:JSON.parse(_.function.arguments)}))],api:"openai-completions",provider:"openai",model:e.model??"",usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:t}:{role:"user",content:Pe(i.content),timestamp:t}),a=o.findIndex(i=>i.role!=="system"),d=o.slice(0,a<0?o.length:a).map(i=>i.content),S=d.join(`
2
2
 
3
- `),h=e.tools?.map(({function:r})=>({name:r.name,description:r.description??"",parameters:r.parameters??{type:"object",properties:{}}}));return{...w?{systemPrompt:w}:{},messages:o.slice(l.length),...h?{tools:h}:{}}}c(at,"contextOf");function Me(e,t,o,i){const l=c(()=>{const h=ge(o,i),r=Object.values({...h.modelRoutes??{},...h.legacyModelRoutes??{}});return r.length?[h.modelLadders.defaultProvider,...h.modelRouting?.familyOrder??[],...r.map(_=>_.family)].find(_=>r.some($=>$.family===_)):h.modelLadders.defaultProvider??"anthropic"},"ownerFamily");if(!e){const h=l();return{kind:"logical",family:h,strength:"strong",spec:`${h}/strong`}}const w=/^([^/]+)\/(ultra|strong|medium|light)$/.exec(e);if(w){if(w[1]===Fe){const h=l();return{kind:"logical",family:h,strength:w[2],spec:`${h}/${w[2]}`}}return{kind:"logical",family:w[1],strength:w[2],spec:e}}return{kind:t==="exact"?"exact":"concrete",spec:e}}c(Me,"requestFor");function dt(e,t){const{input:o,output:i,cacheRead:l,cacheWrite:w}=e.cost;return o===0&&i===0&&l===0&&w===0?null:Number.isFinite(t)&&t>=0?t:null}c(dt,"usdEquivalent");function lt(e,t){return e.compat?.allowedFallbackModels?.find(i=>i.provider===e.provider&&i.model===t)}c(lt,"allowedFallback");function Et(e){return e?{payer:e.payer??"user",sub:e.sub,grantee:e.grantee,inference_endpoint:e.inference_endpoint??null}:void 0}c(Et,"llmCallerOf");function ct(e){return e instanceof nt?e.code==="server_error"?new s(503,"upstream_model_unavailable",e.message):new s(404,"model_unavailable",e.message):e}c(ct,"mintFailure");const ut=/\bmodel is not supported when using Codex with a ChatGPT account\b/i;function ft(e,t,o){if(!(e!=="openai-codex"||t===void 0||!ut.test(t)))return new s(404,"model_unavailable",t,void 0,{served_model:o})}c(ft,"codexAccountModelRejection");function mt(e){return e.get("request-id")??e.get("x-request-id")}c(mt,"vendorRequestId");async function Ft(e,t,o,i,l,w,h){const r=w?.payer==="app"?w:void 0;if(e.payer==="app"&&!r)throw new s(403,"payer_not_app","this grant is not app-paid");if(e.payer==="user"&&r)throw new s(400,"invalid_request","this grant is app-paid; payer cannot be user","payer");if(r&&!r.inference_endpoint)throw new s(404,"model_unavailable",`${r.grantee} is app-paid but its grant carries no inference endpoint`);const _=r?.inference_endpoint??void 0,$=l===void 0?null:r?.sub??l.sub??await Ve(),N=await Ne(),ce=c(u=>u.unrouted!==!0,"configured"),ue=c(u=>{const y=N.find(u.providerId,u.modelId);return y!==void 0&&(!e.reasoning_effort||y.reasoning)&&(e.seed===void 0&&e.response_format===void 0||y.api==="openai-completions")&&(e.stop===void 0||["openai-completions","anthropic-messages"].includes(y.api))},"matchesFeatures"),je=c(async()=>{const u=Me(e.model,e.model_policy,i?.cwd,i?.profileId),y=(await _e(u.kind==="exact"?{kind:"concrete",spec:u.spec}:u,i?.cwd,i?.profileId)).filter(ce);let a;if(u.kind==="logical")a=e.model_policy==="exact"?y.filter(f=>f.family===u.family&&f.strength===u.strength).slice(0,1):y;else{const f=ye(u.spec),L=y.filter(k=>k.providerId===f?.providerId&&k.modelId===f.modelId&&(e.model_policy!=="exact"||k.thinkingLevel===f.thinkingLevel)&&ue(k));if(e.model_policy==="exact")a=L.slice(0,1);else if(L.length)a=L;else{const k=ge(i?.cwd,i?.profileId),M=[...Object.values(k.modelRoutes??{}).flatMap(x=>Object.entries(x.models)),...[k.modelLadders.anthropic,k.modelLadders.openai].flatMap(x=>Object.entries(x))].find(([,x])=>x===u.spec)?.[0],D=Me(void 0,"substitute",i?.cwd,i?.profileId);a=M&&D.kind==="logical"?(await _e({...D,strength:M,spec:u.spec},i?.cwd,i?.profileId)).filter(x=>ce(x)&&x.strength===M):[]}}return a},"ownerCandidates");let O;if(_?O=ot(_,e.model,e.model_policy==="exact").flatMap((u,y)=>{const a=ye(u.model);return a?[{routeId:"app",credentialSource:"app",family:"app",strength:u.strength,...a,rank:y}]:[]}):O=await je(),O=O.filter(ue),O.length===0)throw e.model_policy==="exact"?new s(400,"substitution_refused","no eligible model route is configured"):new s(404,"model_unavailable","no eligible model route is configured");const J=`chatcmpl-${Se()}`;let S=1/0,v,Q,V;const fe=c(async()=>h??(l?.node?(await qe(l.node))?.caused_by??null:null)??(l?.run?(await qe(l.run))?.caused_by??null:null),"causeOf");for(const u of O){if(!r&&!(await Ee(u,N)).authenticated)continue;const y=N.find(u.providerId,u.modelId);if(!y)continue;const a=_?{...y,baseUrl:`${_.base_url}/${y.provider}`}:y,f=u.providerId,L=!r&&Y(f)?await Te(f):[],k=L.filter(j=>!j.authFailure),ee=k.filter(j=>be(j,a.id)<=Date.now()),M=L.length?await Qe(f):void 0;if(k.length&&!ee.length&&M===void 0){const j=Math.min(...k.map(I=>be(I,a.id)));j<S&&(S=j,Q=`${a.provider}/${a.id}`);continue}const D=r?[void 0,void 0]:k.length||M!==void 0?[...ee,...M!==void 0?["key"]:[]]:[void 0];let x=!1;for(const[j,I]of D.entries()){if(x&&I!=="key")continue;const g=I==="key"?void 0:I,me=I==="key",K=Date.now();let pe=g?.access;if(g&&g.expires<=Date.now()&&Y(f)){const n=N.getProvider(f)?.auth.oauth;if(!n)throw new s(503,"upstream_model_unavailable",`no OAuth refresh for ${f}`,void 0,{served_model:`${a.provider}/${a.id}`});pe=(await Ke(f,g.label,async(m,he)=>{const G=await n.refresh({type:"oauth",refresh:m,access:"",expires:0,...he?{clientId:he}:{}},t??new AbortController().signal).catch(Ce=>{throw it(Ce,`${a.provider}/${a.id}`)}),de=G.clientId;return{refresh:G.refresh,access:G.access,expires:G.expires,...typeof de=="string"&&de?{clientId:de}:{}}}).catch(m=>{throw m instanceof Ue||m instanceof Be?new s(503,"upstream_model_unavailable",m.message,void 0,{served_model:`${a.provider}/${a.id}`}):m})).access}const Re=at(e),E=g||r||me?void 0:await N.getApiKeyAndHeaders(a);if(E&&!E.ok)continue;const p=`${a.provider}/${a.id}`,F=e.model??p,R=r?ke({call:"model",route:"endpoint",grantee:r.grantee}):$===null?null:ke({call:"model",route:g?"subscription":"key",sub:$});if(l!==void 0&&R!==null){const n=await Ge({scope:"call",payer:R.payer,funding:R.funding,sub:$,grantee:l.grantee,provider:f});if(n!==null){if(await xe({request:l.request??J,kind:"model",what:p,usd:null,payer:R.payer,funding:R.funding,sub:$,grantee:l.grantee,node:l.node??null,run:l.run??null,provider:f,causedBy:await fe(),refused:Ze(n)}),V??=n,I!=="key"&&D.includes("key")){x=!0;continue}break}}let W;if(r&&_)try{W=await et({audience:_.base_url,sub:r.sub,grantee:r.grantee,initiating_app:r.grantee,scope:["crtr:llm"]},{signal:t})}catch(n){throw ct(n)}let A=!1,P,te=null,q=3e4,C;const ne=[],oe=[],U=[];let d,B;const H=c((n,b=null)=>({id:J,object:"chat.completion.chunk",created:Math.floor(K/1e3),model:p,served_model:p,requested_model:F,substituted:F!==p&&!/^([^/]+)\/(ultra|strong|medium|light)$/.test(F),choices:[{index:0,delta:n,finish_reason:b}]}),"chunk"),z=c(n=>{ne.push(n),o?.(n)},"emit"),$e=Le(a,Re,{apiKey:W?.access_token??pe??(me?M:void 0)??(E?.ok?E.apiKey:void 0),...E?.ok?{headers:E.headers}:{},signal:t,reasoning:e.reasoning_effort??u.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:c(n=>{if(!n||typeof n!="object")return;const b=e.tool_choice,m=b==="required"?a.api==="anthropic-messages"?{type:"any"}:"required":typeof b=="object"&&b!==null?a.api==="anthropic-messages"?{type:"tool",name:b.function.name}:b:void 0;return{...n,...m?{tool_choice:m}:{},...e.stop!==void 0?{[a.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:c(async(n,b)=>{const m=await fetch(n,b);return P=m.status,te=mt(m.headers)??te,m.status===429&&(A=!0,C=m.headers,q=Z(m.headers)??15e3),m},"fetch"),onResponse:c(n=>{n.status===429&&(A=!0,C=n.headers,q=Z(n.headers)??15e3)},"onResponse")});try{for await(const n of $e)n.type==="text_delta"&&(oe.push(n.delta),z(H({content:n.delta}))),n.type==="thinking_delta"&&(U.push(n.delta),z(H({reasoning_content:n.delta}))),n.type==="done"&&(d=n.message),n.type==="error"&&(d=n.error)}catch(n){const b=Je(n);C===void 0&&n&&typeof n=="object"&&"headers"in n&&Object.keys(ze(n.headers)).length&&(C=n.headers);const m=le({status:n&&typeof n=="object"&&"status"in n?n.status:void 0,message:n instanceof Error?n.message:String(n)});if(r)B=n;else{if(!A&&m.kind!=="rate-limit")throw ne.length?new s(503,"upstream_model_unavailable",n instanceof Error?n.message:String(n),void 0,{served_model:p}):n;A=!0,q=b??q}}if(r){if(P===401){if(W&&tt(W.key),j===0)continue;throw new s(404,"model_unavailable",`${_.base_url} refuses this runtime's tokens`,void 0,{served_model:p})}if(A&&Z(C)===void 0)throw new s(503,"upstream_model_unavailable",`${p} was rate-limited without a retry-after`,void 0,{served_model:p});if(!A&&(B!==void 0||P!==void 0&&P>=500))throw new s(503,"upstream_model_unavailable",B instanceof Error?B.message:d?.errorMessage??"inference endpoint failed",void 0,{served_model:p})}if(!A&&d?.stopReason==="error"&&le({message:d.errorMessage}).kind==="rate-limit"&&(A=!0,q=15e3),A){const n=He(C,a.id);if(Z(C)===void 0&&n.resetAt!==void 0&&(q=Math.max(q,n.resetAt-Date.now())),v={provider:f,model:a.id,...g?{account:g.label}:{},observation:n},console.error(`[llm] 429 from ${p}${g?` account "${g.label}"`:""}: scope=${ve(n.scope)} retry_after_ms=${q} headers=${JSON.stringify(n.headers)}`),g&&Y(f)&&await De(f,g.label,q,K,Date.now(),n.scope),Date.now()+Math.min(q,we)<S&&(S=Date.now()+Math.min(q,we),Q=p),oe.length||U.length)throw new s(503,"service_unavailable","vendor rate limit after output began",void 0,{served_model:p});if(r)break;continue}const X=Xe(d);if(P===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 s(400,"invalid_request",d.errorMessage,"tool_choice",{served_model:p});if(d?.stopReason==="error"){const n=ft(a.provider,d.errorMessage,p);if(n)throw n}if(!d||d.stopReason==="error"&&!X||d.stopReason==="aborted")throw new s(503,"upstream_model_unavailable",d?.errorMessage??"model request failed",void 0,{served_model:p});g&&Y(f)&&We(g,a.id)&&await Pe(f,g.label,K,a.id);const re=d.content.filter(n=>n.type==="toolCall").map(n=>({id:n.id,type:"function",function:{name:n.name,arguments:JSON.stringify(n.arguments)}})),ie=X?"content_filter":d.stopReason==="toolUse"?"tool_calls":d.stopReason==="length"?"length":"stop",se=d.responseModel?lt(a,d.responseModel):void 0,T=se?`${a.provider}/${se.model}`:p,ae={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:dt(se??a,d.usage.cost.total),served_model:T};l!==void 0&&R!==null&&await xe({request:l.request??J,kind:"model",what:T,units:{input:d.usage.input,output:d.usage.output,cache_read:d.usage.cacheRead,cache_write:d.usage.cacheWrite},usd:ae.usd_equivalent,payer:R.payer,funding:R.funding,sub:$,grantee:l.grantee,node:l.node??null,run:l.run??null,provider:f,causedBy:await fe(),vendorRef:te});const Ie={id:J,object:"chat.completion",created:Math.floor(K/1e3),model:T,served_model:T,requested_model:F,substituted:F!==T&&!/^([^/]+)\/(ultra|strong|medium|light)$/.test(F),choices:[{index:0,message:{role:"assistant",content:oe.join("")||null,...U.length?{reasoning_content:U.join("")}:{},...re.length?{tool_calls:re}:{},...X?{refusal:d.errorMessage??"Content filtered"}:{}},finish_reason:ie}],usage:ae,...e.metadata!==void 0?{metadata:e.metadata}:{}};for(const[n,b]of re.entries())z(H({tool_calls:[{index:n,...b}]}));return z({...H({},ie),...X?{choices:[{index:0,delta:{},finish_reason:ie,message:{refusal:d.errorMessage??"Content filtered"}}]}:{},usage:ae}),{completion:Ie,chunks:ne}}}throw V!==void 0?Ye(V):S!==1/0?new s(429,"all_routes_exhausted","all eligible model routes are rate-limited",void 0,{retry_after_s:Math.max(1,Math.ceil((S-Date.now())/1e3)),served_model:v?`${v.provider}/${v.model}`:Q,...v?{rate_limit:{provider:v.provider,model:v.model,...v.account?{account:v.account}:{},scope:ve(v.observation.scope),...v.observation.claim?{claim:v.observation.claim}:{},headers:v.observation.headers}}:{}},void 0,!0):e.model_policy==="exact"?new s(400,"substitution_refused","the requested model is unavailable"):new s(404,"model_unavailable","no usable model route is available")}c(Ft,"runLlm");export{Et as llmCallerOf,Lt as parseLlmRequest,Ft as runLlm};
3
+ `),z=e.tools?.map(({function:i})=>({name:i.name,description:i.description??"",parameters:i.parameters??{type:"object",properties:{}}}));return{...S?{systemPrompt:S}:{},messages:o.slice(d.length),...z?{tools:z}:{}}}c(Rt,"contextOf");function At(e){return pt(e?.payment)}c(At,"paymentOf");function qt(e,t){const o=e.find("anthropic",t);if(o)return o;const a=e.getAll().find(d=>d.provider==="anthropic"&&d.api==="anthropic-messages");return a?{...a,id:t,name:t}:void 0}c(qt,"hostedModel");function jt(e,t){const{input:o,output:a,cacheRead:d,cacheWrite:S}=e.cost;return o===0&&a===0&&d===0&&S===0?null:Number.isFinite(t)&&t>=0?t:null}c(jt,"usdEquivalent");function Mt(e,t){return e.compat?.allowedFallbackModels?.find(a=>a.provider===e.provider&&a.model===t)}c(Mt,"allowedFallback");function on(e){return e?{payer:e.payer??"user",sub:e.sub,grantee:e.grantee,inference_endpoint:e.inference_endpoint??null}:void 0}c(on,"llmCallerOf");function Le(e){return e instanceof _t?e.code==="server_error"?new r(503,"upstream_model_unavailable",e.message):new r(404,"model_unavailable",e.message):e}c(Le,"mintFailure");const $t=/\bmodel is not supported when using Codex with a ChatGPT account\b/i;function Ct(e,t,o){if(!(e!=="openai-codex"||t===void 0||!$t.test(t)))return new r(404,"model_unavailable",t,void 0,{served_model:o})}c(Ct,"codexAccountModelRejection");function St(e){return e.get("request-id")??e.get("x-request-id")}c(St,"vendorRequestId");function Et(e,t,o){const a=$e(`anthropic/${o.rungs[e]}`);return a?{routeId:"hosted",credentialSource:"hosted",family:"hosted",strength:e,...a,rank:t}:void 0}c(Et,"hostedCandidate");async function rn(e,t,o,a,d,S,z){const i=S?.payer==="app"?S:void 0;if(e.payer==="app"&&!i)throw new r(403,"payer_not_app","this grant is not app-paid");if(e.payer==="user"&&i)throw new r(400,"invalid_request","this grant is app-paid; payer cannot be user","payer");if(i&&!i.inference_endpoint)throw new r(404,"model_unavailable",`${i.grantee} is app-paid but its grant carries no inference endpoint`);const _=i?.inference_endpoint??void 0,A=d===void 0?null:i?.sub??d.sub??await ht(),E=await Ye();let k;_?(k=yt(_,e.model,e.model_policy==="exact").flatMap((b,y)=>{const q=$e(b.model);return q?[{routeId:"app",credentialSource:"app",family:"app",strength:b.strength,...q,rank:y}]:[]}),k=k.filter(b=>wt(E,e,b))):k=await bt(E,e,a);const ie=!_&&d!==void 0&&A!==null&&gt(e.model_policy,k)?await mt():null,we=ie===null?void 0:Et(k[0].strength,k.length,ie);we&&(k=[...k,we]);const Ke=_?new Set:Xe(),be=c(async()=>new r(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 De())?.payment_setup_url??null,reset_at:null}}),"nothingLeft");if(k.length===0)throw e.model_policy==="exact"?new r(400,"substitution_refused","no eligible model route is configured"):_?new r(404,"model_unavailable","no eligible model route is configured"):await be();const K=`chatcmpl-${He()}`;let N=1/0,X=1/0,ae,w,se,de;const le=c(async()=>z??(d?.node?(await Ne(d.node))?.caused_by??null:null)??(d?.run?(await Ne(d.run))?.caused_by??null:null),"causeOf");for(const b of k){const y=b.credentialSource==="hosted";if(!i&&!y&&!(await Ge(b,E)).authenticated)continue;const q=y?qt(E,b.modelId):E.find(b.providerId,b.modelId);if(!q)continue;const U=y?ie.base_url:void 0,u=_?{...q,baseUrl:`${_.base_url}/${q.provider}`}:U?{...q,baseUrl:`${U}/anthropic`,compat:{...q.compat,allowedFallbackModels:void 0}}:q,p=b.providerId,G=b.credentialSource===Ve&&W(p),ue=!i&&!y&&!G&&W(p)?await tt(p):[],B=ue.filter(j=>!j.authFailure),ve=B.filter(j=>Se(j,u.id)<=Date.now()),T=G?await Oe(p):Ke.has(p)?void 0:ue.length?await Oe(p):void 0;if(G&&T===void 0||ue.length>0&&B.length===0&&T===void 0)continue;if(B.length&&!ve.length&&T===void 0){const j=Math.min(...B.map(I=>Se(I,u.id)));j<N&&(N=j,se=`${u.provider}/${u.id}`);continue}const ke=i||y?[void 0,void 0]:G?["key"]:B.length||T!==void 0?[...ve,...T!==void 0?["key"]:[]]:[void 0];let xe=!1;for(const[j,I]of ke.entries()){if(xe&&I!=="key")continue;const g=I==="key"?void 0:I,Re=I==="key",V=Date.now();let Ae=g?.access;if(g&&g.expires<=Date.now()&&W(p)){const n=E.getProvider(p)?.auth.oauth;if(!n)throw new r(503,"upstream_model_unavailable",`no OAuth refresh for ${p}`,void 0,{served_model:`${u.provider}/${u.id}`});let m;try{m=await ot(p,g.label,async(l,Me)=>{const re=await n.refresh({type:"oauth",refresh:l,access:"",expires:0,...Me?{clientId:Me}:{}},t??new AbortController().signal).catch(Je=>{throw kt(Je,`${u.provider}/${u.id}`)}),_e=re.clientId;return{refresh:re.refresh,access:re.access,expires:re.expires,...typeof _e=="string"&&_e?{clientId:_e}:{}}}).catch(l=>{throw l instanceof it||l instanceof at?new r(503,"upstream_model_unavailable",l.message,void 0,{served_model:`${u.provider}/${u.id}`}):l})}catch(l){if(!Ze(l))throw l;ae??=l;continue}Ae=m.access}const Ue=Rt(e),F=g||i||y||Re?void 0:await E.getApiKeyAndHeaders(u);if(F&&!F.ok)continue;const f=`${u.provider}/${u.id}`,P=e.model??f,x=y?A===null?null:{payer:A,funding:"endpoint"}:i?Ie({call:"model",route:"endpoint",grantee:i.grantee}):A===null?null:Ie({call:"model",route:g?"subscription":"key",sub:A});if(d!==void 0&&x!==null){const n=await ut({scope:"call",payer:x.payer,funding:x.funding,sub:A,grantee:d.grantee,provider:p});if(n!==null){if(await ge({request:d.request??K,kind:"model",what:f,usd:null,payer:x.payer,funding:x.funding,sub:A,grantee:d.grantee,node:d.node??null,run:d.run??null,provider:p,causedBy:await le(),refused:ft(n)}),de??=n,I!=="key"&&ke.includes("key")){xe=!0;continue}break}}let O;if(i&&_)try{O=await Te({audience:_.base_url,sub:i.sub,grantee:i.grantee,initiating_app:i.grantee,scope:["crtr:llm"]},{signal:t})}catch(n){throw Le(n)}if(U)try{O=await Te({audience:U,sub:A,grantee:d.grantee,initiating_app:d.grantee,scope:["crtr:llm"]},{signal:t})}catch(n){throw Le(n)}let L=null,qe=!1,h,J,Y,M=!1,R,Z=null,v=3e4,$;const ce=[],fe=[],Q=[];let s,D;const ee=c((n,m=null)=>({id:K,object:"chat.completion.chunk",created:Math.floor(V/1e3),model:f,served_model:f,requested_model:P,substituted:P!==f&&!/^([^/]+)\/(ultra|strong|medium|light)$/.test(P),choices:[{index:0,delta:n,finish_reason:m}]}),"chunk"),te=c(n=>{ce.push(n),o?.(n)},"emit"),Be=ze(u,Ue,{apiKey:O?.access_token??Ae??(Re?T:void 0)??(F?.ok?F.apiKey:void 0),...F?.ok?{headers:F.headers}:{},signal:t,reasoning:e.reasoning_effort??b.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:c(n=>{if(!n||typeof n!="object")return;const m=e.tool_choice,l=m==="required"?u.api==="anthropic-messages"?{type:"any"}:"required":typeof m=="object"&&m!==null?u.api==="anthropic-messages"?{type:"tool",name:m.function.name}:m:void 0;return{...n,...l?{tool_choice:l}:{},...e.stop!==void 0?{[u.api==="anthropic-messages"?"stop_sequences":"stop"]:typeof e.stop=="string"?[e.stop]:e.stop}:{},...e.seed!==void 0?{seed:e.seed}:{},...e.response_format!==void 0?{response_format:e.response_format}:{}}},"onPayload"),fetch:c(async(n,m)=>{const l=await fetch(n,m);if(R=l.status,Z=St(l.headers)??Z,y){if(L=l.headers.get("crtr-charge-id")?.trim()||null,l.ok&&!L)throw qe=!0,await l.body?.cancel(),new Error("The hosted endpoint omitted Crtr-Charge-Id; the call may already have been charged. Do not automatically replay it.");return l.status===402&&(Y=At(await l.clone().json().catch(()=>{}))),l}return l.status===429&&(M=!0,$=l.headers,v=H(l.headers)??15e3),l},"fetch"),onProviderStreamEvent:c(n=>{y&&n!==null&&typeof n=="object"&&"type"in n&&n.type==="message_stop"&&"crtr_charge"in n&&(h=n.crtr_charge)},"onProviderStreamEvent"),onResponse:c(n=>{!y&&n.status===429&&(M=!0,$=n.headers,v=H(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"&&(s=n.message),n.type==="error"&&(s=n.error)}catch(n){const m=nt(n);$===void 0&&n&&typeof n=="object"&&"headers"in n&&Object.keys(dt(n.headers)).length&&($=n.headers);const l=ye({status:n&&typeof n=="object"&&"status"in n?n.status:void 0,message:n instanceof Error?n.message:String(n)});if(i||y)D=n;else{if(!M&&l.kind!=="rate-limit")throw ce.length?new r(503,"upstream_model_unavailable",n instanceof Error?n.message:String(n),void 0,{served_model:f}):n;M=!0,v=m??v}}if(y){if(qe)throw new r(502,"upstream_refused","The hosted endpoint omitted Crtr-Charge-Id; the call may already have been charged. Do not automatically replay it.",void 0,{served_model:f});if(R===402&&Y)throw new r(402,"payment_refused",Y.message,void 0,{payment:Y,served_model:f});if(R===401){if(O&&Fe(O.key),j===0)continue;throw new r(404,"model_unavailable",`${U} refuses this runtime's tokens`,void 0,{served_model:f})}if(D!==void 0||R!==void 0&&R>=400||s?.stopReason==="error"||s?.stopReason==="aborted"){const m=D instanceof Error?D.message:s?.errorMessage??`the inference endpoint answered ${R??"with an error"}`;throw R===403?new r(502,"upstream_refused",m,void 0,{served_model:f}):new r(503,"upstream_model_unavailable",m,void 0,{served_model:f})}if(h===null||typeof h!="object"||!("id"in h)||h.id!==L||!("served_model"in h)||typeof h.served_model!="string"||!h.served_model.trim()||!("list_usd"in h)||typeof h.list_usd!="number"||!Number.isFinite(h.list_usd)||h.list_usd<0||Number(h.list_usd.toFixed(6))!==h.list_usd)throw new r(502,"upstream_refused","The hosted endpoint returned missing or invalid final charge accounting; output and cost may already exist. Do not automatically replay this call.",void 0,{served_model:f,charge_id:L});J={id:L,served_model:h.served_model,list_usd:h.list_usd}}if(i){if(R===401){if(O&&Fe(O.key),j===0)continue;throw new r(404,"model_unavailable",`${_.base_url} refuses this runtime's tokens`,void 0,{served_model:f})}if(M&&H($)===void 0)throw new r(503,"upstream_model_unavailable",`${f} was rate-limited without a retry-after`,void 0,{served_model:f});if(!M&&(D!==void 0||R!==void 0&&R>=500))throw new r(503,"upstream_model_unavailable",D instanceof Error?D.message:s?.errorMessage??"inference endpoint failed",void 0,{served_model:f})}if(!M&&s?.stopReason==="error"&&ye({message:s.errorMessage}).kind==="rate-limit"&&(M=!0,v=15e3),M){const n=st($,u.id),m=H($)!==void 0?Date.now()+v:n.resetAt;if(H($)===void 0&&n.resetAt!==void 0&&(v=Math.max(v,n.resetAt-Date.now())),w={provider:p,model:u.id,...g?{account:g.label}:{},observation:n},console.error(`[llm] 429 from ${f}${g?` account "${g.label}"`:""}: scope=${Ee(n.scope)} retry_after_ms=${v} headers=${JSON.stringify(n.headers)}`),g&&W(p)&&await Qe(p,g.label,v,V,Date.now(),n.scope),m!==void 0&&(X=Math.min(X,m)),Date.now()+Math.min(v,Ce)<N&&(N=Date.now()+Math.min(v,Ce),se=f),fe.length||Q.length)throw new r(503,"service_unavailable","vendor rate limit after output began",void 0,{served_model:f});if(i)break;continue}const ne=lt(s);if(R===400&&e.tool_choice!==void 0&&e.tool_choice!=="auto"&&e.tool_choice!=="none"&&/\btool[_ ]choice\b/i.test(s?.errorMessage??"")&&/not supported|does not support|unsupported|cannot|must be auto/i.test(s?.errorMessage??""))throw new r(400,"invalid_request",s.errorMessage,"tool_choice",{served_model:f});if(s?.stopReason==="error"){const n=Ct(u.provider,s.errorMessage,f);if(n)throw n}if(!s||s.stopReason==="error"&&!ne||s.stopReason==="aborted")throw new r(503,"upstream_model_unavailable",s?.errorMessage??"model request failed",void 0,{served_model:f});g&&W(p)&&rt(g,u.id)&&await et(p,g.label,V,u.id);const me=s.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":s.stopReason==="toolUse"?"tool_calls":s.stopReason==="length"?"length":"stop",he=s.responseModel?Mt(u,s.responseModel):void 0,C=J?`${u.provider}/${J.served_model}`:he?`${u.provider}/${he.model}`:f,oe={prompt_tokens:s.usage.input,completion_tokens:s.usage.output,total_tokens:s.usage.totalTokens,cache_read_tokens:s.usage.cacheRead,cache_write_tokens:s.usage.cacheWrite,usd_equivalent:J?J.list_usd:jt(he??u,s.usage.cost.total),served_model:C};y?d!==void 0&&x!==null&&await ge({id:L,request:d.request??K,kind:"model",what:C,usd:oe.usd_equivalent,payer:x.payer,funding:x.funding,sub:A,grantee:d.grantee,node:d.node??null,run:d.run??null,provider:p,causedBy:await le(),vendorRef:Z}):d!==void 0&&x!==null&&await ge({request:d.request??K,kind:"model",what:C,units:{input:s.usage.input,output:s.usage.output,cache_read:s.usage.cacheRead,cache_write:s.usage.cacheWrite},usd:oe.usd_equivalent,payer:x.payer,funding:x.funding,sub:A,grantee:d.grantee,node:d.node??null,run:d.run??null,provider:p,causedBy:await le(),vendorRef:Z});const je={id:K,object:"chat.completion",created:Math.floor(V/1e3),model:C,served_model:C,requested_model:P,substituted:P!==C&&!/^([^/]+)\/(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:s.errorMessage??"Content filtered"}:{}},finish_reason:pe}],usage:oe,...e.metadata!==void 0?{metadata:e.metadata}:{}};for(const[n,m]of me.entries())te(ee({tool_calls:[{index:n,...m}]}));return te({...ee({},pe),model:C,served_model:C,substituted:je.substituted,...ne?{choices:[{index:0,delta:{},finish_reason:pe,message:{refusal:s.errorMessage??"Content filtered"}}]}:{},usage:oe}),{completion:je,chunks:ce}}}throw de!==void 0?ct(de):N!==1/0?new r(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 De())?.payment_setup_url??null,reset_at:X===1/0?null:new Date(X).toISOString()},retry_after_s:Math.max(1,Math.ceil((N-Date.now())/1e3)),served_model:w?`${w.provider}/${w.model}`:se,...w?{rate_limit:{provider:w.provider,model:w.model,...w.account?{account:w.account}:{},scope:Ee(w.observation.scope),...w.observation.claim?{claim:w.observation.claim}:{},headers:w.observation.headers}}:{}},void 0,!0):ae!==void 0?ae:e.model_policy==="exact"?new r(400,"substitution_refused","the requested model is unavailable"):_?new r(404,"model_unavailable","no usable model route is available"):await be()}c(rn,"runLlm");export{on as llmCallerOf,nn as parseLlmRequest,rn as runLlm};
@@ -0,0 +1,37 @@
1
+ export type ActivationKind = 'subscription' | 'api_key';
2
+ /** The directory's answer: whether this activation closed a trial. */
3
+ export type ActivationTrial = 'closed' | 'not_active';
4
+ export type ActivationAck = {
5
+ status: 'acknowledged';
6
+ trial: ActivationTrial;
7
+ } | {
8
+ status: 'pending';
9
+ };
10
+ /** First retry waits this long; each further failure doubles it, up to `MAX_BACKOFF_MS`. */
11
+ export declare const BASE_BACKOFF_MS = 5000;
12
+ export declare const MAX_BACKOFF_MS: number;
13
+ /** Record an activation for the calling person and start delivering it once the surrounding transaction (if any) commits. Null when the runtime has joined no directory: there is
14
+ * nobody to tell, so no row is kept. `id` lets a caller that must know the id before the save (the key page) choose it. */
15
+ export declare function recordActivation(input: {
16
+ kind: ActivationKind;
17
+ provider: string;
18
+ id?: string;
19
+ idempotent?: boolean;
20
+ }): Promise<string | null>;
21
+ /** Record an activation for `person` from code that runs outside that person's request: a sign-in finished by the daemon's own poll
22
+ * or the sign-in page, or credentials an import copied in. Loads the person's settings first when this process does not hold them,
23
+ * because they say whether the runtime has a directory. Same answer as `recordActivation`. */
24
+ export declare function recordCredentialActivation(person: string, kind: ActivationKind, provider: string, id?: string): Promise<string | null>;
25
+ /** Whether an activation row with this id exists. */
26
+ export declare function activationRecorded(activationId: string): Promise<boolean>;
27
+ /** One delivery attempt, shared by concurrent callers for the same id. Resolves with the directory's `trial` answer and marks the
28
+ * row acknowledged; rejects (row stays pending) on any failure. An already-acknowledged row is delivered again when asked: the
29
+ * directory answers a duplicate identically, which is how a caller after a restart learns `trial`. */
30
+ export declare function deliverActivation(activationId: string): Promise<ActivationTrial>;
31
+ /** Wait up to `waitMs` for the directory to acknowledge `activationId` (starting an attempt now unless one is running). The answer
32
+ * is `pending` when the attempt fails or outlasts the wait; the sweep keeps retrying either way. */
33
+ export declare function awaitActivationAck(activationId: string, waitMs?: number): Promise<ActivationAck>;
34
+ /** Retry every pending activation whose backoff has elapsed; returns how many attempts it started. */
35
+ export declare function sweepActivations(now?: number): Promise<number>;
36
+ /** The daemon's retry loop over pending activations. Returns its stop. */
37
+ export declare function startActivationDelivery(intervalMs?: number): () => void;
@@ -0,0 +1 @@
1
+ var v=Object.defineProperty;var n=(t,e)=>v(t,"name",{value:e,configurable:!0});import{randomUUID as f}from"node:crypto";import{afterCommit as m,openDb as d}from"../canvas/db.js";import{personIdAsync as w,runAsPerson as E}from"../canvas/person.js";import{personHasSnapshot as S}from"../scoped-state/person-store.js";import{loadPersonSettings as h}from"../scoped-state/person-rows.js";import{directoryIssuer as u}from"../directory/issuer.js";import{emitEvent as p}from"../events/emit.js";import{describeOutboundFailure as y,outboundFetch as A,outboundJson as g,outboundRefusal as k}from"../events/outbound.js";import{mintDirectoryToken as T}from"../grants/sync.js";const O=5e3,D=10*6e4,R=5e3,N=1e4,s=new Map;async function b(t){if(u()===null)return null;const e=await w(),a=t.id??f();return await(await d()).prepare(`INSERT INTO credential_activations(activation_id,person,kind,provider,activated_at) VALUES(?,?,?,?,?)${t.idempotent?" ON CONFLICT (activation_id) DO NOTHING":""}`).run(a,e,t.kind,t.provider,new Date().toISOString()),m(()=>{_(a).catch(()=>{})}),a}n(b,"recordActivation");async function K(t,e,a,i){return E(t,async()=>(S()||await h(t),b({kind:e,provider:a,id:i,idempotent:i!==void 0})))}n(K,"recordCredentialActivation");async function V(t){return await(await d()).prepare("SELECT 1 FROM credential_activations WHERE activation_id=?").get(t)!==void 0}n(V,"activationRecorded");function M(t){return Math.min(D,O*2**Math.max(0,t-1))}n(M,"backoffMs");function _(t){let e=s.get(t);return e||(e=C(t).finally(()=>s.delete(t)),s.set(t,e)),e}n(_,"deliverActivation");async function C(t){const e=u();if(e===null)throw new Error("credential activation needs a directory-connected runtime");const a=await d(),i=await a.prepare("SELECT activation_id,person,kind,provider,activated_at FROM credential_activations WHERE activation_id=?").get(t);if(!i)throw new Error(`no credential activation ${t}`);await a.prepare("UPDATE credential_activations SET attempts=attempts+1, last_attempt_at=? WHERE activation_id=?").run(new Date().toISOString(),t);const r=`${e}/v1/runtime/credential-activations`;try{const o=await T(e),l=await A("credential_activation",r,{method:"POST",headers:{Authorization:`Bearer ${o.access_token}`,"Content-Type":"application/json"},body:JSON.stringify({activation_id:i.activation_id,user_id:i.person,kind:i.kind,provider:i.provider,activated_at:i.activated_at}),signal:AbortSignal.timeout(1e4)});if(!l.ok)throw k("credential_activation",r,`directory refused the credential activation: ${l.status}`);const c=await g("credential_activation",r,l);if(c.trial!=="closed"&&c.trial!=="not_active")throw new TypeError(`directory answered the credential activation without a trial state: ${JSON.stringify(c.trial)}`);return await a.prepare("UPDATE credential_activations SET acknowledged_at=? WHERE activation_id=? AND acknowledged_at IS NULL").run(new Date().toISOString(),t),p({level:"info",event:"model_auth.activation.acknowledged",fields:{activation_id:t,kind:i.kind,provider:i.provider,trial:c.trial}}),c.trial}catch(o){throw p({level:"warn",event:"model_auth.activation.delivery_failed",error:o,fields:{activation_id:t,...y(o)}}),o}}n(C,"attempt");async function j(t,e=N){let a;const i=new Promise(r=>{a=setTimeout(()=>r({status:"pending"}),e)});try{return await Promise.race([_(t).then(r=>({status:"acknowledged",trial:r}),()=>({status:"pending"})),i])}finally{clearTimeout(a)}}n(j,"awaitActivationAck");async function F(t=Date.now()){if(u()===null)return 0;const e=await(await d()).prepare("SELECT activation_id,attempts,last_attempt_at FROM credential_activations WHERE acknowledged_at IS NULL ORDER BY activated_at").all();let a=0;for(const i of e)s.has(i.activation_id)||i.last_attempt_at!==null&&Date.parse(i.last_attempt_at)+M(Number(i.attempts))>t||(_(i.activation_id).catch(()=>{}),a++);return a}n(F,"sweepActivations");function z(t=R){let e=!1;const a=n(()=>{e||(e=!0,F().catch(r=>p({level:"error",event:"model_auth.activation.sweep_failed",error:r})).finally(()=>{e=!1}))},"tick"),i=setInterval(a,t);return i.unref(),a(),()=>clearInterval(i)}n(z,"startActivationDelivery");export{O as BASE_BACKOFF_MS,D as MAX_BACKOFF_MS,V as activationRecorded,j as awaitActivationAck,_ as deliverActivation,b as recordActivation,K as recordCredentialActivation,z as startActivationDelivery,F as sweepActivations};
@@ -1 +1 @@
1
- var le=Object.defineProperty;var o=(e,t)=>le(e,"name",{value:t,configurable:!0});import{createHash as V,randomBytes as B,randomUUID as _e}from"node:crypto";import{createServer as fe}from"node:http";import{RunError as p}from"../runs/operations.js";import{openDb as R}from"../canvas/db.js";import{isCloudRole as ge,personIdAsync as O,runAsPerson as me}from"../canvas/person.js";import{loadSecretsKey as U,open as W,seal as we}from"../secrets/index.js";import{describeOutboundFailure as ye}from"../events/outbound.js";import{ANTHROPIC_PROVIDER_ID as m,OPENAI_CHATGPT_PROVIDER_ID as w,OPENAI_CODEX_PROVIDER_ID as K,commitManagedLogin as ve,openAIDeviceId as be,readSubscriptionPool as $}from"../subscription-state.js";const X=900,Y="9d1c250a-e61b-44d9-88ed-5944d1962f5e",Ae="https://claude.ai/oauth/authorize",Z="https://console.anthropic.com/oauth/code/callback",Q={port:53692,path:"/callback",redirect:"http://localhost:53692/callback"},xe="org:create_api_key user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload",M="app_EMoamEEZ73f0CkXaXp7hrann",Pe="https://auth.openai.com/codex/device",ee="https://auth.openai.com/deviceauth/callback",te={port:1455,path:"/auth/callback",redirect:"http://localhost:1455/auth/callback"},Se="openid profile email offline_access",Ee=900,ne="https://api.openai.com/auth",Te="dynamic_agent_client",ke="crtr",Re="https://auth.openai.com/api/accounts/authorize",re="https://api.openai.com/v1",b={port:1455,path:"/auth/callback",redirect:"http://127.0.0.1:1455/auth/callback"},F="chatgpt.tokens.use.direct",Oe=`openid profile email offline_access resource.invoke ${F}`,Ce=180*1e3,Ie=o(()=>process.env.CRTR_MODEL_AUTH_ANTHROPIC_TOKEN_URL||"https://platform.claude.com/v1/oauth/token","anthropicTokenUrl"),C=o(()=>(process.env.CRTR_MODEL_AUTH_OPENAI_BASE||"https://auth.openai.com").replace(/\/$/,""),"openaiBase");class A extends p{static{o(this,"VendorSignInError")}category;step;url;httpStatus;constructor(t,n,r,a,i,s){super(502,"upstream_refused",a),this.category=t,this.step=n,this.url=r,this.httpStatus=s,i!==void 0&&(this.cause=i)}logFields(){return{category:this.category,...this.httpStatus===void 0?{}:{http_status:this.httpStatus},...ye(this.cause??this,{step:this.step,url:this.url})}}}async function x(e,t,n){try{return await fetch(t,n)}catch(r){throw new A("network",e,t,`could not reach ${new URL(t).host}${new URL(t).pathname}: ${r instanceof Error?r.message:String(r)}`,r)}}o(x,"vendorFetch");async function P(e,t,n){let r;try{r=await n.text()}catch(a){throw new A("network",e,t,`connection to ${new URL(t).host}${new URL(t).pathname} dropped while reading the answer: ${a instanceof Error?a.message:String(a)}`,a)}try{return JSON.parse(r)}catch{throw f(e,t,`${new URL(t).host}${new URL(t).pathname} answered with a body that is not JSON`,n.status)}}o(P,"vendorJson");const f=o((e,t,n,r)=>new A("refused",e,t,n,void 0,r),"refusal"),g=new Map,S=new Map,I=o((e,t)=>`${e}|${t}`,"providerKey"),H=o((e,t)=>`model_sign_in_flows|${e}|${t}`,"flowAad"),ie=o(e=>V("sha256").update(`state:${e}`).digest("hex").slice(0,32),"openaiState"),L=o(()=>ge(),"rowsAreShared");async function Le(e){if(!L())return;const t=e.person,{sealed:n,keyId:r}=we(JSON.stringify({verifier:e.verifier,...e.label?{label:e.label}:{},...e.jti?{jti:e.jti}:{}}),U(),H(t,e.id)),a=await R();await a.prepare("DELETE FROM model_sign_in_flows WHERE person = ? AND expires_at < ?").run(t,new Date().toISOString()),await a.prepare("INSERT INTO model_sign_in_flows (flow_id, provider, person, verifier_sealed, key_id, expires_at) VALUES (?, ?, ?, ?, ?, ?)").run(e.id,e.provider,t,n,r,new Date(e.expiresAt).toISOString())}o(Le,"writeFlowRow");async function De(e){if(!L())return;const t=await O(),n=await(await R()).prepare("SELECT provider, verifier_sealed, key_id, expires_at FROM model_sign_in_flows WHERE flow_id = ? AND person = ?").get(e,t);if(!n||Date.parse(n.expires_at)<=Date.now())return;const r=JSON.parse(W(n.verifier_sealed,n.key_id,U(),H(t,e))),a=n.provider;if(a!==m&&a!==w)return;const i={id:e,person:t,provider:a,kind:a===m?"code_page":"redirect_paste",state:a===m?r.verifier:ie(r.verifier),verifier:r.verifier,redirectUri:a===m?Z:b.redirect,expiresAt:Date.parse(n.expires_at),status:"pending",...r.jti?{jti:r.jti}:{},...r.label?{label:r.label}:{},lastRateLimitedAt:Math.max(0,...(await $(a)).map(s=>s.lastRateLimitedAt)),abort:new AbortController,timer:setTimeout(()=>_(i,"expired","the sign-in expired"),Math.max(0,Date.parse(n.expires_at)-Date.now())),waiters:new Set,exchanging:!1};return i.timer.unref(),i}o(De,"readFlowRow");function G(e){return e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}o(G,"base64url");function Ne(){const e=G(B(32));return{verifier:e,challenge:G(V("sha256").update(e).digest())}}o(Ne,"pkce");const ae="openai-chatgpt";function oe(e){if(e==="openai")return K;if(e===ae)return w;if(e===m||e===K)return e;throw new p(400,"invalid_request","provider must be anthropic, openai-codex, or openai-chatgpt","provider")}o(oe,"managedProvider");function et(e){return e===w?ae:e}o(et,"modelAuthApiProvider");function tt(e){return oe(e)}o(tt,"modelAuthProvider");function _(e,t,n,r){if(e.status==="pending"){e.status=t,n!==void 0&&(e.message=n),r instanceof A&&(e.failure=r),clearTimeout(e.timer),e.abort.abort(),e.server?.close(),e.server?.closeIdleConnections(),S.get(I(e.person,e.provider))===e.id&&S.delete(I(e.person,e.provider)),L()&&R().then(async a=>{await a.prepare("DELETE FROM model_sign_in_flows WHERE flow_id = ? AND person = ?").run(e.id,e.person)}).catch(()=>{});for(const a of e.waiters)a();e.waiters.clear(),setTimeout(()=>{g.get(e.id)===e&&g.delete(e.id)},6e4).unref()}}o(_,"settle");async function j(e,t){if(e.status!=="pending")throw new Error("the sign-in ended before the credential was written");await me(e.person,()=>ve(e.provider,e.label,{access:t.access,refresh:t.refresh,expires:t.expires,...t.accountId?{accountId:t.accountId}:{},...t.clientId?{clientId:t.clientId}:{},...t.email?{email:t.email}:{},lastRateLimitedAt:e.lastRateLimitedAt,autoLabel:e.label===void 0}))}o(j,"writeCredential");async function se(e,t,n){const r=Ie(),a=await x("token_exchange",r,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({grant_type:"authorization_code",client_id:Y,code:t,state:n,redirect_uri:e.redirectUri,code_verifier:e.verifier}),signal:AbortSignal.any([e.abort.signal,AbortSignal.timeout(3e4)])});if(!a.ok)throw f("token_exchange",r,`Anthropic token exchange failed (${a.status})`,a.status);const i=await P("token_exchange",r,a);if(typeof i.access_token!="string"||typeof i.refresh_token!="string"||typeof i.expires_in!="number"||!Number.isFinite(i.expires_in))throw f("token_exchange",r,"Anthropic token exchange returned no credential");await j(e,{access:i.access_token,refresh:i.refresh_token,expires:Date.now()+i.expires_in*1e3-300*1e3})}o(se,"exchangeAnthropic");function Ue(e){const t=e.split(".")[1];let n;try{n=JSON.parse(Buffer.from(t??"","base64url").toString("utf8"))[ne]?.chatgpt_account_id}catch{n=void 0}if(typeof n!="string"||n==="")throw new Error("OpenAI token carries no ChatGPT account id");return n}o(Ue,"openaiAccountId");async function ce(e,t,n,r){const a=`${C()}/oauth/token`,i=await x("token_exchange",a,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:M,code:t,code_verifier:n,redirect_uri:r}),signal:AbortSignal.any([e.abort.signal,AbortSignal.timeout(3e4)])});if(!i.ok)throw f("token_exchange",a,`OpenAI token exchange failed (${i.status})`,i.status);const s=await P("token_exchange",a,i);if(typeof s.access_token!="string"||typeof s.refresh_token!="string"||typeof s.expires_in!="number")throw f("token_exchange",a,"OpenAI token exchange returned no credential");await j(e,{access:s.access_token,refresh:s.refresh_token,expires:Date.now()+s.expires_in*1e3,accountId:Ue(s.access_token)})}o(ce,"exchangeOpenAI");function de(e){try{const t=JSON.parse(Buffer.from(e?.split(".")[1]??"","base64url").toString("utf8"));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}catch{return}}o(de,"jwtPayload");function $e(...e){for(const t of e){const n=de(t)?.[ne];if(typeof n?.chatgpt_account_id=="string"&&n.chatgpt_account_id)return n.chatgpt_account_id}}o($e,"chatgptAccountId");function ue(e,t){const n=e.searchParams.get("error");if(n)throw new p(400,"invalid_request",`ChatGPT authorization failed: ${n}`,"input");const r=e.searchParams.get("code");if(!r)throw new p(400,"invalid_request","the redirect URL has no authorization code","input");if(e.searchParams.get("state")!==t)throw new p(400,"invalid_request","the pasted redirect URL belongs to a different sign-in","state");const a=e.searchParams.get("client_id")?.trim();if(!a)throw new p(400,"invalid_request","the redirect URL carries no issued client id","input");return{code:r,clientId:a}}o(ue,"chatgptCallback");async function pe(e,t,n){const r=`${C()}/api/accounts/oauth/token`,a=await x("token_exchange",r,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:n,code:t,code_verifier:e.verifier,redirect_uri:e.redirectUri,resource:re}),signal:AbortSignal.any([e.abort.signal,AbortSignal.timeout(3e4)])});if(!a.ok)throw f("token_exchange",r,`ChatGPT token exchange failed (${a.status})`,a.status);const i=await P("token_exchange",r,a);if(typeof i.access_token!="string"||!i.access_token||typeof i.refresh_token!="string"||!i.refresh_token||typeof i.expires_in!="number"||!Number.isFinite(i.expires_in)||i.expires_in<=0||typeof i.id_token!="string"||!i.id_token)throw f("token_exchange",r,"ChatGPT token exchange returned no credential");if(!(typeof i.scope=="string"?i.scope.trim().split(/\s+/):[]).includes(F))throw f("token_exchange",r,`ChatGPT sign-in did not grant ${F}`);const l=$e(i.access_token,i.id_token),d=de(i.id_token)?.email;await j(e,{access:i.access_token,refresh:i.refresh_token,expires:Date.now()+i.expires_in*1e3-Ce,clientId:n,...l?{accountId:l}:{},...typeof d=="string"&&d?{email:d}:{}})}o(pe,"exchangeChatGPT");function Me(e,t){return new Promise((n,r)=>{if(t.aborted){r(new Error("flow ended"));return}const a=o(()=>{clearTimeout(i),r(new Error("flow ended"))},"onAbort"),i=setTimeout(()=>{t.removeEventListener("abort",a),n()},e);t.addEventListener("abort",a,{once:!0})})}o(Me,"sleep");async function Fe(e,t){const n=Math.min(e.expiresAt,Date.now()+Ee*1e3);let r=Math.max(1e3,Math.floor(t.intervalS*1e3));try{for(;Date.now()<n&&(await Me(Math.min(r,Math.max(0,n-Date.now())),e.abort.signal),!(Date.now()>=n));){const a=`${C()}/api/accounts/deviceauth/token`,i=await x("poll",a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_auth_id:t.deviceAuthId,user_code:t.userCode}),signal:AbortSignal.any([e.abort.signal,AbortSignal.timeout(3e4)])});if(i.ok){const d=await P("poll",a,i);if(typeof d.authorization_code!="string"||typeof d.code_verifier!="string")throw f("poll",a,"OpenAI device approval returned no code");await ce(e,d.authorization_code,d.code_verifier,ee),_(e,"connected");return}if(i.status===403||i.status===404)continue;let s;try{s=await i.text()}catch(d){throw new A("network","poll",a,`connection to ${new URL(a).host}${new URL(a).pathname} dropped while reading the answer: ${d instanceof Error?d.message:String(d)}`,d)}let l;try{const d=JSON.parse(s).error;l=typeof d=="object"&&d!==null?d.code:d}catch{l=void 0}if(l!=="deviceauth_authorization_pending"){if(l==="slow_down"){r+=5e3;continue}throw f("poll",a,`OpenAI device sign-in failed (${i.status})`,i.status)}}_(e,"expired","the OpenAI code expired")}catch(a){e.status==="pending"&&_(e,"failed",a instanceof Error?a.message:String(a),a)}}o(Fe,"pollDevice");function q(e,t){const n=fe((r,a)=>{const i=new URL(r.url??"/","http://localhost"),s=o((c,v)=>{a.writeHead(c,{"Content-Type":"text/plain; charset=utf-8",Connection:"close"}),a.end(v)},"reply");if(i.pathname!==t.path){s(404,"Not found.");return}const l=i.searchParams.get("code");if(i.searchParams.get("state")!==e.state||!l){s(400,"Sign-in could not be completed: state mismatch or missing code.");return}let d="";if(e.provider===w)try{d=ue(i,e.state).clientId}catch(c){s(400,`Sign-in could not be completed: ${c instanceof Error?c.message:String(c)}.`);return}if(e.status!=="pending"||e.exchanging){s(409,"This sign-in has already finished.");return}e.exchanging=!0,(e.provider===m?se(e,l,e.state):e.provider===w?pe(e,l,d):ce(e,l,e.verifier,e.redirectUri)).then(()=>{s(200,"Signed in. You can close this window."),_(e,"connected")},c=>{s(502,"The vendor refused the sign-in."),_(e,"failed",c instanceof Error?c.message:String(c),c)})});return e.server=n,new Promise((r,a)=>{n.once("error",i=>a(new p(409,"conflict",`cannot listen on localhost:${t.port} for the vendor redirect (${i.code??i.message})`,"redirect"))),n.listen(t.port,"127.0.0.1",()=>r())})}o(q,"listenLoopback");async function nt(e){const t=oe(e.provider);if(e.redirect!==void 0&&e.redirect!=="loopback")throw new p(400,"invalid_request",'redirect must be "loopback" when present',"redirect");if(e.label!==void 0&&typeof e.label!="string")throw new p(400,"invalid_request","label must be a string when present","label");const n=typeof e.label=="string"&&e.label.trim()?e.label.trim():void 0,r=await O(),a=Math.max(0,...(await $(t)).map(h=>h.lastRateLimitedAt)),i=S.get(I(r,t));if(i!==void 0){const h=g.get(i);h&&_(h,"failed","replaced by a newer sign-in")}const{verifier:s,challenge:l}=Ne(),d=e.redirect==="loopback",N=Date.now()+X*1e3,c={id:_e(),person:r,provider:t,kind:d?"loopback":t===m?"code_page":t===w?"redirect_paste":"device",state:t===m?s:ie(s),verifier:s,redirectUri:t===m?d?Q.redirect:Z:t===w?b.redirect:d?te.redirect:ee,expiresAt:N,status:"pending",...e.jti?{jti:e.jti}:{},...n?{label:n}:{},lastRateLimitedAt:a,abort:new AbortController,timer:setTimeout(()=>_(c,"expired","the sign-in expired"),X*1e3),waiters:new Set,exchanging:!1};c.timer.unref(),he(c),await Le(c);const v=o(()=>new p(409,"conflict","a newer sign-in for this provider replaced this one","provider"),"replacedDuringStart"),E={flow_id:c.id,provider:t,expires_at:new Date(N).toISOString()};try{if(t===m){const u=new URLSearchParams;if(u.set("code","true"),u.set("client_id",Y),u.set("response_type","code"),u.set("redirect_uri",c.redirectUri),u.set("scope",xe),u.set("code_challenge",l),u.set("code_challenge_method","S256"),u.set("state",c.state),d&&await q(c,Q),c.status!=="pending")throw v();return{...E,url:`${Ae}?${u.toString()}`,instructions:d?"Sign in to Claude in your browser; this finishes by itself.":"Sign in to Claude, then copy the code Claude shows and paste it here."}}if(t===w){const u=new URL(Re);if(u.search=new URLSearchParams({client_id:Te,agent_name_hint:ke,ext_agent_host_id:`urn:uuid:${await be()}`,response_type:"code",redirect_uri:c.redirectUri,resource:re,scope:Oe,state:c.state,code_challenge:l,code_challenge_method:"S256",nonce:G(B(32))}).toString(),d&&await q(c,b),c.status!=="pending")throw v();return{...E,url:u.toString(),instructions:d?"Sign in with ChatGPT in your browser; this finishes by itself. If it does not, paste the final redirect URL here.":`Sign in with ChatGPT, then copy the full URL your browser lands on (it starts with ${b.redirect} and may show a connection error) and paste it here.`}}if(d){const u=new URL("https://auth.openai.com/oauth/authorize");if(u.searchParams.set("response_type","code"),u.searchParams.set("client_id",M),u.searchParams.set("redirect_uri",c.redirectUri),u.searchParams.set("scope",Se),u.searchParams.set("code_challenge",l),u.searchParams.set("code_challenge_method","S256"),u.searchParams.set("state",c.state),u.searchParams.set("id_token_add_organizations","true"),u.searchParams.set("codex_cli_simplified_flow","true"),u.searchParams.set("originator","pi"),await q(c,te),c.status!=="pending")throw v();return{...E,url:u.toString(),instructions:"Sign in to ChatGPT in your browser; this finishes by itself."}}const h=`${C()}/api/accounts/deviceauth/usercode`,T=await x("device_code_start",h,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:M}),signal:AbortSignal.timeout(3e4)});if(!T.ok)throw f("device_code_start",h,`OpenAI refused to issue a device code (${T.status})`,T.status);const y=await P("device_code_start",h,T),k=typeof y.interval=="string"?Number(y.interval.trim()):y.interval;if(typeof y.device_auth_id!="string"||typeof y.user_code!="string"||typeof k!="number"||!Number.isFinite(k)||k<0)throw f("device_code_start",h,"OpenAI returned an invalid device code");if(c.status!=="pending")throw v();return Fe(c,{deviceAuthId:y.device_auth_id,userCode:y.user_code,intervalS:k}),{...E,url:Pe,user_code:y.user_code,instructions:"Open the link, sign in to ChatGPT, and enter the code. The code expires in 15 minutes."}}catch(h){throw _(c,"failed",h instanceof Error?h.message:String(h),h),g.delete(c.id),h instanceof p?h:new p(502,"upstream_refused",`vendor sign-in could not start: ${h instanceof Error?h.message:String(h)}`)}}o(nt,"startModelAuthFlow");async function D(e){const t=g.get(e);return t&&t.person===await O()?t:void 0}o(D,"ownFlow");function he(e){g.set(e.id,e),S.set(I(e.person,e.provider),e.id)}o(he,"register");async function rt(e){const t=await D(e);if(t)return _(t,"failed","cancelled"),J(t)}o(rt,"cancelModelAuthFlow");function He(e){const t=e.trim();if(!t)return{};try{const n=new URL(t);return{code:n.searchParams.get("code")??void 0,state:n.searchParams.get("state")??void 0}}catch{}if(t.includes("#")){const[n,r]=t.split("#",2);return{code:n,state:r}}if(t.includes("code=")){const n=new URLSearchParams(t);return{code:n.get("code")??void 0,state:n.get("state")??void 0}}return{code:t}}o(He,"parseCodeInput");async function Ge(e){let t=typeof e=="string"?await D(e):void 0;if(!t&&typeof e=="string"&&!g.has(e)&&(t=await De(e),t&&he(t)),!t||t.status!=="pending")throw new p(400,"invalid_request","no in-flight sign-in has this flow_id","flow_id");return t}o(Ge,"pendingFlow");async function it(e,t){const n=await Ge(e);if(n.provider===w)return je(n,t);if(n.kind!=="code_page")throw new p(400,"invalid_request","this sign-in completes without a pasted code","flow_id");if(n.exchanging)throw new p(400,"invalid_request","this sign-in is already being completed","flow_id");if(typeof t!="string")throw new p(400,"invalid_request","input must be the code Claude shows","input");const{code:r,state:a}=He(t);if(!r)throw new p(400,"invalid_request","input must be the code Claude shows","input");if(a!==void 0&&a!==n.state)throw new p(400,"invalid_request","the pasted code belongs to a different sign-in","state");n.exchanging=!0;try{await se(n,r,a??n.state)}catch(i){throw _(n,"failed",i instanceof Error?i.message:String(i),i),new p(502,"upstream_refused","Anthropic refused the code")}return _(n,"connected"),{flow_id:n.id,provider:n.provider,status:"connected"}}o(it,"completeModelAuthFlow");async function je(e,t){if(e.exchanging)throw new p(400,"invalid_request","this sign-in is already being completed","flow_id");const n=new URL(b.redirect);let r;try{r=typeof t=="string"?new URL(t.trim()):void 0}catch{r=void 0}if(!r||r.origin!==n.origin||r.pathname!==n.pathname)throw new p(400,"invalid_request",`input must be the full redirect URL starting with ${b.redirect}`,"input");const{code:a,clientId:i}=ue(r,e.state);e.exchanging=!0;try{await pe(e,a,i)}catch(s){throw _(e,"failed",s instanceof Error?s.message:String(s),s),new p(502,"upstream_refused","OpenAI refused the ChatGPT sign-in")}return _(e,"connected"),{flow_id:e.id,provider:e.provider,status:"connected"}}o(je,"completeChatGPTFlow");function J(e){return{flow_id:e.id,provider:e.provider,status:e.status,...e.message?{message:e.message}:{},...e.jti?{jti:e.jti}:{}}}o(J,"view");async function z(e){if(!L())return;const t=await O(),n=await(await R()).prepare("SELECT provider, verifier_sealed, key_id, expires_at FROM model_sign_in_flows WHERE flow_id = ? AND person = ?").get(e,t);if(!n||Date.parse(n.expires_at)<=Date.now())return;const r=JSON.parse(W(n.verifier_sealed,n.key_id,U(),H(t,e)));return{flow_id:e,provider:n.provider,status:"pending",...r.jti?{jti:r.jti}:{}}}o(z,"pendingRowView");async function at(e){const t=await D(e);return t?J(t):g.has(e)?void 0:await z(e)}o(at,"readModelAuthFlow");function ot(e){const t=g.get(e);return t?.status==="expired"?{category:"expired",fields:{category:"expired"}}:t?.failure?{category:t.failure.category,step:t.failure.step,fields:t.failure.logFields()}:{category:"runtime",fields:{category:"runtime"}}}o(ot,"modelAuthFlowFailure");async function st(e,t,n){const r=await D(e);return r?(r.status==="pending"&&t>0&&!n?.aborted&&await new Promise(a=>{const i=o(()=>{clearTimeout(s),n?.removeEventListener("abort",i),r.waiters.delete(i),a()},"done"),s=setTimeout(i,t);n?.addEventListener("abort",i,{once:!0}),r.waiters.add(i)}),J(r)):g.has(e)?void 0:await Je(e,t,n)}o(st,"waitModelAuthFlow");const qe=1e3;async function Je(e,t,n){const r=await z(e);if(!r)return;const a=Date.now()+t;for(;!n?.aborted&&Date.now()<a&&(await new Promise(i=>setTimeout(i,Math.min(qe,Math.max(0,a-Date.now())))),!n?.aborted);)if(!await z(e)){const i=(await $(r.provider)).length>0;return{...r,status:i?"connected":"failed"}}return r}o(Je,"waitRowFlow");function ct(){for(const e of g.values())_(e,"failed","reset");g.clear(),S.clear()}o(ct,"resetModelAuthFlowsForTest");export{X as MODEL_AUTH_FLOW_TTL_S,ae as OPENAI_CHATGPT_API_PROVIDER,A as VendorSignInError,rt as cancelModelAuthFlow,it as completeModelAuthFlow,et as modelAuthApiProvider,ot as modelAuthFlowFailure,tt as modelAuthProvider,at as readModelAuthFlow,ct as resetModelAuthFlowsForTest,nt as startModelAuthFlow,st as waitModelAuthFlow};
1
+ var le=Object.defineProperty;var o=(e,t)=>le(e,"name",{value:t,configurable:!0});import{createHash as V,randomBytes as B,randomUUID as _e}from"node:crypto";import{createServer as fe}from"node:http";import{RunError as p}from"../runs/operations.js";import{recordCredentialActivation as ge}from"./activations.js";import{linkHandoffActivation as me}from"./handoff-jti.js";import{openDb as R}from"../canvas/db.js";import{isCloudRole as we,personIdAsync as O,runAsPerson as ye}from"../canvas/person.js";import{loadSecretsKey as U,open as W,seal as ve}from"../secrets/index.js";import{describeOutboundFailure as Ae}from"../events/outbound.js";import{ANTHROPIC_PROVIDER_ID as m,OPENAI_CHATGPT_PROVIDER_ID as w,OPENAI_CODEX_PROVIDER_ID as K,commitManagedLogin as be,openAIDeviceId as xe,readSubscriptionPool as $}from"../subscription-state.js";const X=900,Y="9d1c250a-e61b-44d9-88ed-5944d1962f5e",Pe="https://claude.ai/oauth/authorize",Z="https://console.anthropic.com/oauth/code/callback",Q={port:53692,path:"/callback",redirect:"http://localhost:53692/callback"},Se="org:create_api_key user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload",M="app_EMoamEEZ73f0CkXaXp7hrann",Ee="https://auth.openai.com/codex/device",ee="https://auth.openai.com/deviceauth/callback",te={port:1455,path:"/auth/callback",redirect:"http://localhost:1455/auth/callback"},Te="openid profile email offline_access",ke=900,ne="https://api.openai.com/auth",Re="dynamic_agent_client",Oe="crtr",Ce="https://auth.openai.com/api/accounts/authorize",re="https://api.openai.com/v1",A={port:1455,path:"/auth/callback",redirect:"http://127.0.0.1:1455/auth/callback"},H="chatgpt.tokens.use.direct",Ie=`openid profile email offline_access resource.invoke ${H}`,Le=180*1e3,De=o(()=>process.env.CRTR_MODEL_AUTH_ANTHROPIC_TOKEN_URL||"https://platform.claude.com/v1/oauth/token","anthropicTokenUrl"),C=o(()=>(process.env.CRTR_MODEL_AUTH_OPENAI_BASE||"https://auth.openai.com").replace(/\/$/,""),"openaiBase");class b extends p{static{o(this,"VendorSignInError")}category;step;url;httpStatus;constructor(t,n,r,a,i,s){super(502,"upstream_refused",a),this.category=t,this.step=n,this.url=r,this.httpStatus=s,i!==void 0&&(this.cause=i)}logFields(){return{category:this.category,...this.httpStatus===void 0?{}:{http_status:this.httpStatus},...Ae(this.cause??this,{step:this.step,url:this.url})}}}async function x(e,t,n){try{return await fetch(t,n)}catch(r){throw new b("network",e,t,`could not reach ${new URL(t).host}${new URL(t).pathname}: ${r instanceof Error?r.message:String(r)}`,r)}}o(x,"vendorFetch");async function P(e,t,n){let r;try{r=await n.text()}catch(a){throw new b("network",e,t,`connection to ${new URL(t).host}${new URL(t).pathname} dropped while reading the answer: ${a instanceof Error?a.message:String(a)}`,a)}try{return JSON.parse(r)}catch{throw f(e,t,`${new URL(t).host}${new URL(t).pathname} answered with a body that is not JSON`,n.status)}}o(P,"vendorJson");const f=o((e,t,n,r)=>new b("refused",e,t,n,void 0,r),"refusal"),g=new Map,S=new Map,I=o((e,t)=>`${e}|${t}`,"providerKey"),F=o((e,t)=>`model_sign_in_flows|${e}|${t}`,"flowAad"),ie=o(e=>V("sha256").update(`state:${e}`).digest("hex").slice(0,32),"openaiState"),L=o(()=>we(),"rowsAreShared");async function Ne(e){if(!L())return;const t=e.person,{sealed:n,keyId:r}=ve(JSON.stringify({verifier:e.verifier,...e.label?{label:e.label}:{},...e.jti?{jti:e.jti}:{}}),U(),F(t,e.id)),a=await R();await a.prepare("DELETE FROM model_sign_in_flows WHERE person = ? AND expires_at < ?").run(t,new Date().toISOString()),await a.prepare("INSERT INTO model_sign_in_flows (flow_id, provider, person, verifier_sealed, key_id, expires_at) VALUES (?, ?, ?, ?, ?, ?)").run(e.id,e.provider,t,n,r,new Date(e.expiresAt).toISOString())}o(Ne,"writeFlowRow");async function Ue(e){if(!L())return;const t=await O(),n=await(await R()).prepare("SELECT provider, verifier_sealed, key_id, expires_at FROM model_sign_in_flows WHERE flow_id = ? AND person = ?").get(e,t);if(!n||Date.parse(n.expires_at)<=Date.now())return;const r=JSON.parse(W(n.verifier_sealed,n.key_id,U(),F(t,e))),a=n.provider;if(a!==m&&a!==w)return;const i={id:e,person:t,provider:a,kind:a===m?"code_page":"redirect_paste",state:a===m?r.verifier:ie(r.verifier),verifier:r.verifier,redirectUri:a===m?Z:A.redirect,expiresAt:Date.parse(n.expires_at),status:"pending",...r.jti?{jti:r.jti}:{},...r.label?{label:r.label}:{},lastRateLimitedAt:Math.max(0,...(await $(a)).map(s=>s.lastRateLimitedAt)),abort:new AbortController,timer:setTimeout(()=>_(i,"expired","the sign-in expired"),Math.max(0,Date.parse(n.expires_at)-Date.now())),waiters:new Set,exchanging:!1};return i.timer.unref(),i}o(Ue,"readFlowRow");function G(e){return e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}o(G,"base64url");function $e(){const e=G(B(32));return{verifier:e,challenge:G(V("sha256").update(e).digest())}}o($e,"pkce");const ae="openai-chatgpt";function oe(e){if(e==="openai")return K;if(e===ae)return w;if(e===m||e===K)return e;throw new p(400,"invalid_request","provider must be anthropic, openai-codex, or openai-chatgpt","provider")}o(oe,"managedProvider");function it(e){return e===w?ae:e}o(it,"modelAuthApiProvider");function at(e){return oe(e)}o(at,"modelAuthProvider");function _(e,t,n,r){if(e.status==="pending"){e.status=t,n!==void 0&&(e.message=n),r instanceof b&&(e.failure=r),clearTimeout(e.timer),e.abort.abort(),e.server?.close(),e.server?.closeIdleConnections(),S.get(I(e.person,e.provider))===e.id&&S.delete(I(e.person,e.provider)),L()&&R().then(async a=>{await a.prepare("DELETE FROM model_sign_in_flows WHERE flow_id = ? AND person = ?").run(e.id,e.person)}).catch(()=>{});for(const a of e.waiters)a();e.waiters.clear(),setTimeout(()=>{g.get(e.id)===e&&g.delete(e.id)},6e4).unref()}}o(_,"settle");async function j(e,t){if(e.status!=="pending")throw new Error("the sign-in ended before the credential was written");await ye(e.person,()=>be(e.provider,e.label,{access:t.access,refresh:t.refresh,expires:t.expires,...t.accountId?{accountId:t.accountId}:{},...t.clientId?{clientId:t.clientId}:{},...t.email?{email:t.email}:{},lastRateLimitedAt:e.lastRateLimitedAt,autoLabel:e.label===void 0}));const n=await ge(e.person,"subscription",e.provider);n!==null&&e.jti!==void 0&&await me(e.jti,n)}o(j,"writeCredential");async function se(e,t,n){const r=De(),a=await x("token_exchange",r,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({grant_type:"authorization_code",client_id:Y,code:t,state:n,redirect_uri:e.redirectUri,code_verifier:e.verifier}),signal:AbortSignal.any([e.abort.signal,AbortSignal.timeout(3e4)])});if(!a.ok)throw f("token_exchange",r,`Anthropic token exchange failed (${a.status})`,a.status);const i=await P("token_exchange",r,a);if(typeof i.access_token!="string"||typeof i.refresh_token!="string"||typeof i.expires_in!="number"||!Number.isFinite(i.expires_in))throw f("token_exchange",r,"Anthropic token exchange returned no credential");await j(e,{access:i.access_token,refresh:i.refresh_token,expires:Date.now()+i.expires_in*1e3-300*1e3})}o(se,"exchangeAnthropic");function Me(e){const t=e.split(".")[1];let n;try{n=JSON.parse(Buffer.from(t??"","base64url").toString("utf8"))[ne]?.chatgpt_account_id}catch{n=void 0}if(typeof n!="string"||n==="")throw new Error("OpenAI token carries no ChatGPT account id");return n}o(Me,"openaiAccountId");async function ce(e,t,n,r){const a=`${C()}/oauth/token`,i=await x("token_exchange",a,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:M,code:t,code_verifier:n,redirect_uri:r}),signal:AbortSignal.any([e.abort.signal,AbortSignal.timeout(3e4)])});if(!i.ok)throw f("token_exchange",a,`OpenAI token exchange failed (${i.status})`,i.status);const s=await P("token_exchange",a,i);if(typeof s.access_token!="string"||typeof s.refresh_token!="string"||typeof s.expires_in!="number")throw f("token_exchange",a,"OpenAI token exchange returned no credential");await j(e,{access:s.access_token,refresh:s.refresh_token,expires:Date.now()+s.expires_in*1e3,accountId:Me(s.access_token)})}o(ce,"exchangeOpenAI");function de(e){try{const t=JSON.parse(Buffer.from(e?.split(".")[1]??"","base64url").toString("utf8"));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}catch{return}}o(de,"jwtPayload");function He(...e){for(const t of e){const n=de(t)?.[ne];if(typeof n?.chatgpt_account_id=="string"&&n.chatgpt_account_id)return n.chatgpt_account_id}}o(He,"chatgptAccountId");function ue(e,t){const n=e.searchParams.get("error");if(n)throw new p(400,"invalid_request",`ChatGPT authorization failed: ${n}`,"input");const r=e.searchParams.get("code");if(!r)throw new p(400,"invalid_request","the redirect URL has no authorization code","input");if(e.searchParams.get("state")!==t)throw new p(400,"invalid_request","the pasted redirect URL belongs to a different sign-in","state");const a=e.searchParams.get("client_id")?.trim();if(!a)throw new p(400,"invalid_request","the redirect URL carries no issued client id","input");return{code:r,clientId:a}}o(ue,"chatgptCallback");async function pe(e,t,n){const r=`${C()}/api/accounts/oauth/token`,a=await x("token_exchange",r,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:n,code:t,code_verifier:e.verifier,redirect_uri:e.redirectUri,resource:re}),signal:AbortSignal.any([e.abort.signal,AbortSignal.timeout(3e4)])});if(!a.ok)throw f("token_exchange",r,`ChatGPT token exchange failed (${a.status})`,a.status);const i=await P("token_exchange",r,a);if(typeof i.access_token!="string"||!i.access_token||typeof i.refresh_token!="string"||!i.refresh_token||typeof i.expires_in!="number"||!Number.isFinite(i.expires_in)||i.expires_in<=0||typeof i.id_token!="string"||!i.id_token)throw f("token_exchange",r,"ChatGPT token exchange returned no credential");if(!(typeof i.scope=="string"?i.scope.trim().split(/\s+/):[]).includes(H))throw f("token_exchange",r,`ChatGPT sign-in did not grant ${H}`);const l=He(i.access_token,i.id_token),d=de(i.id_token)?.email;await j(e,{access:i.access_token,refresh:i.refresh_token,expires:Date.now()+i.expires_in*1e3-Le,clientId:n,...l?{accountId:l}:{},...typeof d=="string"&&d?{email:d}:{}})}o(pe,"exchangeChatGPT");function Fe(e,t){return new Promise((n,r)=>{if(t.aborted){r(new Error("flow ended"));return}const a=o(()=>{clearTimeout(i),r(new Error("flow ended"))},"onAbort"),i=setTimeout(()=>{t.removeEventListener("abort",a),n()},e);t.addEventListener("abort",a,{once:!0})})}o(Fe,"sleep");async function Ge(e,t){const n=Math.min(e.expiresAt,Date.now()+ke*1e3);let r=Math.max(1e3,Math.floor(t.intervalS*1e3));try{for(;Date.now()<n&&(await Fe(Math.min(r,Math.max(0,n-Date.now())),e.abort.signal),!(Date.now()>=n));){const a=`${C()}/api/accounts/deviceauth/token`,i=await x("poll",a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_auth_id:t.deviceAuthId,user_code:t.userCode}),signal:AbortSignal.any([e.abort.signal,AbortSignal.timeout(3e4)])});if(i.ok){const d=await P("poll",a,i);if(typeof d.authorization_code!="string"||typeof d.code_verifier!="string")throw f("poll",a,"OpenAI device approval returned no code");await ce(e,d.authorization_code,d.code_verifier,ee),_(e,"connected");return}if(i.status===403||i.status===404)continue;let s;try{s=await i.text()}catch(d){throw new b("network","poll",a,`connection to ${new URL(a).host}${new URL(a).pathname} dropped while reading the answer: ${d instanceof Error?d.message:String(d)}`,d)}let l;try{const d=JSON.parse(s).error;l=typeof d=="object"&&d!==null?d.code:d}catch{l=void 0}if(l!=="deviceauth_authorization_pending"){if(l==="slow_down"){r+=5e3;continue}throw f("poll",a,`OpenAI device sign-in failed (${i.status})`,i.status)}}_(e,"expired","the OpenAI code expired")}catch(a){e.status==="pending"&&_(e,"failed",a instanceof Error?a.message:String(a),a)}}o(Ge,"pollDevice");function q(e,t){const n=fe((r,a)=>{const i=new URL(r.url??"/","http://localhost"),s=o((c,v)=>{a.writeHead(c,{"Content-Type":"text/plain; charset=utf-8",Connection:"close"}),a.end(v)},"reply");if(i.pathname!==t.path){s(404,"Not found.");return}const l=i.searchParams.get("code");if(i.searchParams.get("state")!==e.state||!l){s(400,"Sign-in could not be completed: state mismatch or missing code.");return}let d="";if(e.provider===w)try{d=ue(i,e.state).clientId}catch(c){s(400,`Sign-in could not be completed: ${c instanceof Error?c.message:String(c)}.`);return}if(e.status!=="pending"||e.exchanging){s(409,"This sign-in has already finished.");return}e.exchanging=!0,(e.provider===m?se(e,l,e.state):e.provider===w?pe(e,l,d):ce(e,l,e.verifier,e.redirectUri)).then(()=>{s(200,"Signed in. You can close this window."),_(e,"connected")},c=>{s(502,"The vendor refused the sign-in."),_(e,"failed",c instanceof Error?c.message:String(c),c)})});return e.server=n,new Promise((r,a)=>{n.once("error",i=>a(new p(409,"conflict",`cannot listen on localhost:${t.port} for the vendor redirect (${i.code??i.message})`,"redirect"))),n.listen(t.port,"127.0.0.1",()=>r())})}o(q,"listenLoopback");async function ot(e){const t=oe(e.provider);if(e.redirect!==void 0&&e.redirect!=="loopback")throw new p(400,"invalid_request",'redirect must be "loopback" when present',"redirect");if(e.label!==void 0&&typeof e.label!="string")throw new p(400,"invalid_request","label must be a string when present","label");const n=typeof e.label=="string"&&e.label.trim()?e.label.trim():void 0,r=await O(),a=Math.max(0,...(await $(t)).map(h=>h.lastRateLimitedAt)),i=S.get(I(r,t));if(i!==void 0){const h=g.get(i);h&&_(h,"failed","replaced by a newer sign-in")}const{verifier:s,challenge:l}=$e(),d=e.redirect==="loopback",N=Date.now()+X*1e3,c={id:_e(),person:r,provider:t,kind:d?"loopback":t===m?"code_page":t===w?"redirect_paste":"device",state:t===m?s:ie(s),verifier:s,redirectUri:t===m?d?Q.redirect:Z:t===w?A.redirect:d?te.redirect:ee,expiresAt:N,status:"pending",...e.jti?{jti:e.jti}:{},...n?{label:n}:{},lastRateLimitedAt:a,abort:new AbortController,timer:setTimeout(()=>_(c,"expired","the sign-in expired"),X*1e3),waiters:new Set,exchanging:!1};c.timer.unref(),he(c),await Ne(c);const v=o(()=>new p(409,"conflict","a newer sign-in for this provider replaced this one","provider"),"replacedDuringStart"),E={flow_id:c.id,provider:t,expires_at:new Date(N).toISOString()};try{if(t===m){const u=new URLSearchParams;if(u.set("code","true"),u.set("client_id",Y),u.set("response_type","code"),u.set("redirect_uri",c.redirectUri),u.set("scope",Se),u.set("code_challenge",l),u.set("code_challenge_method","S256"),u.set("state",c.state),d&&await q(c,Q),c.status!=="pending")throw v();return{...E,url:`${Pe}?${u.toString()}`,instructions:d?"Sign in to Claude in your browser; this finishes by itself.":"Sign in to Claude, then copy the code Claude shows and paste it here."}}if(t===w){const u=new URL(Ce);if(u.search=new URLSearchParams({client_id:Re,agent_name_hint:Oe,ext_agent_host_id:`urn:uuid:${await xe()}`,response_type:"code",redirect_uri:c.redirectUri,resource:re,scope:Ie,state:c.state,code_challenge:l,code_challenge_method:"S256",nonce:G(B(32))}).toString(),d&&await q(c,A),c.status!=="pending")throw v();return{...E,url:u.toString(),instructions:d?"Sign in with ChatGPT in your browser; this finishes by itself. If it does not, paste the final redirect URL here.":`Sign in with ChatGPT, then copy the full URL your browser lands on (it starts with ${A.redirect} and may show a connection error) and paste it here.`}}if(d){const u=new URL("https://auth.openai.com/oauth/authorize");if(u.searchParams.set("response_type","code"),u.searchParams.set("client_id",M),u.searchParams.set("redirect_uri",c.redirectUri),u.searchParams.set("scope",Te),u.searchParams.set("code_challenge",l),u.searchParams.set("code_challenge_method","S256"),u.searchParams.set("state",c.state),u.searchParams.set("id_token_add_organizations","true"),u.searchParams.set("codex_cli_simplified_flow","true"),u.searchParams.set("originator","pi"),await q(c,te),c.status!=="pending")throw v();return{...E,url:u.toString(),instructions:"Sign in to ChatGPT in your browser; this finishes by itself."}}const h=`${C()}/api/accounts/deviceauth/usercode`,T=await x("device_code_start",h,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:M}),signal:AbortSignal.timeout(3e4)});if(!T.ok)throw f("device_code_start",h,`OpenAI refused to issue a device code (${T.status})`,T.status);const y=await P("device_code_start",h,T),k=typeof y.interval=="string"?Number(y.interval.trim()):y.interval;if(typeof y.device_auth_id!="string"||typeof y.user_code!="string"||typeof k!="number"||!Number.isFinite(k)||k<0)throw f("device_code_start",h,"OpenAI returned an invalid device code");if(c.status!=="pending")throw v();return Ge(c,{deviceAuthId:y.device_auth_id,userCode:y.user_code,intervalS:k}),{...E,url:Ee,user_code:y.user_code,instructions:"Open the link, sign in to ChatGPT, and enter the code. The code expires in 15 minutes."}}catch(h){throw _(c,"failed",h instanceof Error?h.message:String(h),h),g.delete(c.id),h instanceof p?h:new p(502,"upstream_refused",`vendor sign-in could not start: ${h instanceof Error?h.message:String(h)}`)}}o(ot,"startModelAuthFlow");async function D(e){const t=g.get(e);return t&&t.person===await O()?t:void 0}o(D,"ownFlow");function he(e){g.set(e.id,e),S.set(I(e.person,e.provider),e.id)}o(he,"register");async function st(e){const t=await D(e);if(t)return _(t,"failed","cancelled"),J(t)}o(st,"cancelModelAuthFlow");function je(e){const t=e.trim();if(!t)return{};try{const n=new URL(t);return{code:n.searchParams.get("code")??void 0,state:n.searchParams.get("state")??void 0}}catch{}if(t.includes("#")){const[n,r]=t.split("#",2);return{code:n,state:r}}if(t.includes("code=")){const n=new URLSearchParams(t);return{code:n.get("code")??void 0,state:n.get("state")??void 0}}return{code:t}}o(je,"parseCodeInput");async function qe(e){let t=typeof e=="string"?await D(e):void 0;if(!t&&typeof e=="string"&&!g.has(e)&&(t=await Ue(e),t&&he(t)),!t||t.status!=="pending")throw new p(400,"invalid_request","no in-flight sign-in has this flow_id","flow_id");return t}o(qe,"pendingFlow");async function ct(e,t){const n=await qe(e);if(n.provider===w)return Je(n,t);if(n.kind!=="code_page")throw new p(400,"invalid_request","this sign-in completes without a pasted code","flow_id");if(n.exchanging)throw new p(400,"invalid_request","this sign-in is already being completed","flow_id");if(typeof t!="string")throw new p(400,"invalid_request","input must be the code Claude shows","input");const{code:r,state:a}=je(t);if(!r)throw new p(400,"invalid_request","input must be the code Claude shows","input");if(a!==void 0&&a!==n.state)throw new p(400,"invalid_request","the pasted code belongs to a different sign-in","state");n.exchanging=!0;try{await se(n,r,a??n.state)}catch(i){throw _(n,"failed",i instanceof Error?i.message:String(i),i),new p(502,"upstream_refused","Anthropic refused the code")}return _(n,"connected"),{flow_id:n.id,provider:n.provider,status:"connected"}}o(ct,"completeModelAuthFlow");async function Je(e,t){if(e.exchanging)throw new p(400,"invalid_request","this sign-in is already being completed","flow_id");const n=new URL(A.redirect);let r;try{r=typeof t=="string"?new URL(t.trim()):void 0}catch{r=void 0}if(!r||r.origin!==n.origin||r.pathname!==n.pathname)throw new p(400,"invalid_request",`input must be the full redirect URL starting with ${A.redirect}`,"input");const{code:a,clientId:i}=ue(r,e.state);e.exchanging=!0;try{await pe(e,a,i)}catch(s){throw _(e,"failed",s instanceof Error?s.message:String(s),s),new p(502,"upstream_refused","OpenAI refused the ChatGPT sign-in")}return _(e,"connected"),{flow_id:e.id,provider:e.provider,status:"connected"}}o(Je,"completeChatGPTFlow");function J(e){return{flow_id:e.id,provider:e.provider,status:e.status,...e.message?{message:e.message}:{},...e.jti?{jti:e.jti}:{}}}o(J,"view");async function z(e){if(!L())return;const t=await O(),n=await(await R()).prepare("SELECT provider, verifier_sealed, key_id, expires_at FROM model_sign_in_flows WHERE flow_id = ? AND person = ?").get(e,t);if(!n||Date.parse(n.expires_at)<=Date.now())return;const r=JSON.parse(W(n.verifier_sealed,n.key_id,U(),F(t,e)));return{flow_id:e,provider:n.provider,status:"pending",...r.jti?{jti:r.jti}:{}}}o(z,"pendingRowView");async function dt(e){const t=await D(e);return t?J(t):g.has(e)?void 0:await z(e)}o(dt,"readModelAuthFlow");function ut(e){const t=g.get(e);return t?.status==="expired"?{category:"expired",fields:{category:"expired"}}:t?.failure?{category:t.failure.category,step:t.failure.step,fields:t.failure.logFields()}:{category:"runtime",fields:{category:"runtime"}}}o(ut,"modelAuthFlowFailure");async function pt(e,t,n){const r=await D(e);return r?(r.status==="pending"&&t>0&&!n?.aborted&&await new Promise(a=>{const i=o(()=>{clearTimeout(s),n?.removeEventListener("abort",i),r.waiters.delete(i),a()},"done"),s=setTimeout(i,t);n?.addEventListener("abort",i,{once:!0}),r.waiters.add(i)}),J(r)):g.has(e)?void 0:await Ve(e,t,n)}o(pt,"waitModelAuthFlow");const ze=1e3;async function Ve(e,t,n){const r=await z(e);if(!r)return;const a=Date.now()+t;for(;!n?.aborted&&Date.now()<a&&(await new Promise(i=>setTimeout(i,Math.min(ze,Math.max(0,a-Date.now())))),!n?.aborted);)if(!await z(e)){const i=(await $(r.provider)).length>0;return{...r,status:i?"connected":"failed"}}return r}o(Ve,"waitRowFlow");function ht(){for(const e of g.values())_(e,"failed","reset");g.clear(),S.clear()}o(ht,"resetModelAuthFlowsForTest");export{X as MODEL_AUTH_FLOW_TTL_S,ae as OPENAI_CHATGPT_API_PROVIDER,b as VendorSignInError,st as cancelModelAuthFlow,ct as completeModelAuthFlow,it as modelAuthApiProvider,ut as modelAuthFlowFailure,at as modelAuthProvider,dt as readModelAuthFlow,ht as resetModelAuthFlowsForTest,ot as startModelAuthFlow,pt as waitModelAuthFlow};
@@ -1,3 +1,12 @@
1
1
  export declare function handoffJtiConsumed(jti: string): Promise<boolean>;
2
- /** Record `jti` as consumed until `exp`; false when it already was. Expired rows are pruned on every write. */
2
+ /** Record `jti` as consumed until `exp`; false when it already was. Expired rows, and the activation links of jtis no longer
3
+ * held, are pruned on every write. */
3
4
  export declare function consumeHandoffJti(jti: string, exp: number): Promise<boolean>;
5
+ /** Give a consumed `jti` back, with its activation link: the save it was consumed for recorded no activation, so the person may
6
+ * try again. */
7
+ export declare function releaseHandoffJti(jti: string): Promise<void>;
8
+ /** Link a consumed key handoff to the activation id its save will record, before the save, so a retry with the same handoff (even
9
+ * one racing the save) waits on that activation instead of saving again. */
10
+ export declare function linkHandoffActivation(jti: string, activationId: string): Promise<void>;
11
+ /** The activation a consumed key handoff's save recorded; undefined when this handoff saved nothing. */
12
+ export declare function handoffActivation(jti: string): Promise<string | undefined>;
@@ -1 +1 @@
1
- var u=Object.defineProperty;var n=(e,a)=>u(e,"name",{value:a,configurable:!0});import{openDb as r}from"../canvas/db.js";const t="handoff_jti|";async function s(e){const a=await(await r()).prepare("SELECT value FROM canvas_meta WHERE key = ?").get(`${t}${e}`);return a!==void 0&&Number(a.value)>Date.now()/1e3}n(s,"handoffJtiConsumed");async function f(e,a){const o=await r();await o.prepare("DELETE FROM canvas_meta WHERE key LIKE ? AND CAST(value AS DOUBLE PRECISION) <= ?").run(`${t}%`,Date.now()/1e3);const{changes:E}=await o.prepare("INSERT INTO canvas_meta (key, value) VALUES (?, ?) ON CONFLICT (key) DO NOTHING").run(`${t}${e}`,String(a));return E>0}n(f,"consumeHandoffJti");export{f as consumeHandoffJti,s as handoffJtiConsumed};
1
+ var c=Object.defineProperty;var n=(a,e)=>c(a,"name",{value:e,configurable:!0});import{openDb as t}from"../canvas/db.js";const r="handoff_jti|",E="handoff_activation|";async function u(a){const e=await(await t()).prepare("SELECT value FROM canvas_meta WHERE key = ?").get(`${r}${a}`);return e!==void 0&&Number(e.value)>Date.now()/1e3}n(u,"handoffJtiConsumed");async function T(a,e){const o=await t();await o.prepare("DELETE FROM canvas_meta WHERE key LIKE ? AND CAST(value AS DOUBLE PRECISION) <= ?").run(`${r}%`,Date.now()/1e3),await o.prepare(`DELETE FROM canvas_meta WHERE key LIKE ? AND NOT EXISTS (SELECT 1 FROM canvas_meta j WHERE j.key = CAST(? AS TEXT) || substr(canvas_meta.key, ${E.length+1}))`).run(`${E}%`,r);const{changes:i}=await o.prepare("INSERT INTO canvas_meta (key, value) VALUES (?, ?) ON CONFLICT (key) DO NOTHING").run(`${r}${a}`,String(e));return i>0}n(T,"consumeHandoffJti");async function p(a){await(await t()).prepare("DELETE FROM canvas_meta WHERE key IN (?, ?)").run(`${r}${a}`,`${E}${a}`)}n(p,"releaseHandoffJti");async function O(a,e){await(await t()).prepare("INSERT INTO canvas_meta (key, value) VALUES (?, ?) ON CONFLICT (key) DO NOTHING").run(`${E}${a}`,e)}n(O,"linkHandoffActivation");async function v(a){return await u(a)?(await(await t()).prepare("SELECT value FROM canvas_meta WHERE key = ?").get(`${E}${a}`))?.value:void 0}n(v,"handoffActivation");export{T as consumeHandoffJti,v as handoffActivation,u as handoffJtiConsumed,O as linkHandoffActivation,p as releaseHandoffJti};
@@ -0,0 +1,30 @@
1
+ import type { ModelStrength } from '../../types.js';
2
+ /** Providers a key can be saved for with a strength mapping (pi-ai provider ids). */
3
+ export declare const KEY_ROUTE_PROVIDERS: readonly ["anthropic", "openai", "openrouter", "moonshotai"];
4
+ export type KeyRouteProvider = typeof KEY_ROUTE_PROVIDERS[number];
5
+ /** A key save the caller got wrong; the message names what. */
6
+ export declare class KeyRouteError extends Error {
7
+ constructor(message: string);
8
+ }
9
+ export declare function isKeyRouteProvider(provider: string): provider is KeyRouteProvider;
10
+ export declare function keyRouteId(provider: string): string;
11
+ /** The models of `provider` a key route may name: registered chat models, all of which take tools. */
12
+ export declare function keyRouteModels(provider: KeyRouteProvider): Promise<Array<{
13
+ id: string;
14
+ name: string;
15
+ }>>;
16
+ /** Check a strength mapping: all four strengths, each `<provider>/<model-id>` of a registered chat model of `provider`. */
17
+ export declare function validateKeyRouteModels(provider: string, models: unknown): Promise<Record<ModelStrength, string>>;
18
+ /** Save `apiKey` for `provider`, its strength mapping and the activation as one transaction: a key never exists without its route
19
+ * and its activation row. Returns the activation id (null when the runtime has joined no directory: there is nobody to tell, so no row is kept). A failed save reloads the person's settings, because the route write refreshes the cache before the commit. */
20
+ export declare function saveKeyRoute(provider: string, apiKey: string, models: unknown, activationId?: string): Promise<{
21
+ activationId: string | null;
22
+ }>;
23
+ /** Remove a provider's key route (its key is removed by the caller). */
24
+ export declare function removeKeyRoute(provider: string): Promise<void>;
25
+ /** Every saved key with its strength mapping, without key material. `added_at` is when the key row was last written. */
26
+ export declare function listKeyRoutes(): Promise<Array<{
27
+ provider: string;
28
+ models: Record<ModelStrength, string>;
29
+ added_at: string;
30
+ }>>;
@@ -0,0 +1 @@
1
+ var R=Object.defineProperty;var r=(t,o)=>R(t,"name",{value:o,configurable:!0});import{MODEL_STRENGTHS as f}from"../runtime/model-selection.js";import{apiKeyUpdatedAt as $,setAuthCredential as E}from"../auth-file.js";import{persistModelRoute as p,readConfig as h}from"../config.js";import{KEY_CREDENTIAL_SOURCE as y}from"../model-routes.js";import{openModelRegistry as w}from"../runtime/model-registry.js";import{userScopeRoot as g}from"../scope.js";import{withCanvasWrite as K}from"../canvas/db.js";import{personIdAsync as k}from"../canvas/person.js";import{loadPersonSettings as x}from"../scoped-state/person-rows.js";import{recordActivation as A}from"./activations.js";const d=["anthropic","openai","openrouter","moonshotai"];class u extends Error{static{r(this,"KeyRouteError")}constructor(o){super(o),this.name="KeyRouteError"}}function S(t){return d.includes(t)}r(S,"isKeyRouteProvider");function m(t){return`${y}:${t}`}r(m,"keyRouteId");async function W(t){return(await w()).getAll().filter(e=>e.provider===t&&e.type==="chat").map(e=>({id:e.id,name:e.name}))}r(W,"keyRouteModels");async function _(t,o){if(!S(t))throw new u(`keys with a model mapping are accepted for ${d.join(", ")}, not ${t}`);if(o===null||typeof o!="object"||Array.isArray(o))throw new u("`models` must be an object with ultra, strong, medium and light");const e=o;for(const n of Object.keys(e))if(!f.includes(n))throw new u(`models.${n} is not a strength`);const i=f.filter(n=>e[n]===void 0);if(i.length>0)throw new u(`models is missing ${i.map(n=>`\`${n}\``).join(", ")}`);const a=await w(),s={};for(const n of f){const c=e[n];if(typeof c!="string"||!c.startsWith(`${t}/`)||c.length===t.length+1)throw new u(`models.${n} must be ${t}/<model-id>`);const l=a.find(t,c.slice(t.length+1));if(l===void 0||l.type!=="chat")throw new u(`models.${n}: ${c} is not a ${t} model that takes tools`);s[n]=c}return s}r(_,"validateKeyRouteModels");async function Y(t,o,e,i){const a=await _(t,e),s=await k();try{return await K(async()=>(await E(t,{type:"api_key",key:o}),await p(g(),m(t),{family:t,credentialSource:y,providerId:t,models:a}),{activationId:await A({kind:"api_key",provider:t,id:i})}))}catch(n){throw await x(s),n}}r(Y,"saveKeyRoute");async function G(t){h("user").modelRoutes?.[m(t)]!==void 0&&await p(g(),m(t),void 0)}r(G,"removeKeyRoute");async function H(){const t=h("user").modelRoutes??{},o=await I(),e=[];for(const i of d){const a=t[m(i)],s=o.get(i);a?.credentialSource!==y||s===void 0||e.push({provider:i,models:{...a.models},added_at:s})}return e}r(H,"listKeyRoutes");async function I(){return $([...d])}r(I,"readKeyTimes");export{d as KEY_ROUTE_PROVIDERS,u as KeyRouteError,S as isKeyRouteProvider,m as keyRouteId,W as keyRouteModels,H as listKeyRoutes,G as removeKeyRoute,Y as saveKeyRoute,_ as validateKeyRouteModels};