@north-light/cli 0.3.750 → 0.3.751

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/builtin-memory/crouter-sdk/release-notes.md +10 -0
  2. package/dist/core/canvas/schema-pg/037-grant-principals.sql +50 -0
  3. package/dist/core/canvas/schema-version.d.ts +1 -1
  4. package/dist/core/canvas/schema-version.js +1 -1
  5. package/dist/core/grants/local.js +1 -1
  6. package/dist/core/grants/mirror.d.ts +11 -3
  7. package/dist/core/grants/mirror.js +12 -12
  8. package/dist/core/grants/shadow.js +1 -1
  9. package/dist/core/grants/sync.js +1 -1
  10. package/dist/core/ledger/payer.d.ts +4 -4
  11. package/dist/core/ledger/payer.js +1 -1
  12. package/dist/core/llm/app-rungs.js +1 -1
  13. package/dist/core/llm/run.d.ts +2 -2
  14. package/dist/core/llm/run.js +2 -2
  15. package/dist/core/runtime/start-check.js +1 -1
  16. package/dist/daemon/api/app-listener.js +12 -12
  17. package/dist/daemon/api/handlers/git-credential.js +1 -1
  18. package/dist/daemon/api/handlers/runs.js +1 -1
  19. package/dist/daemon/api/principal.d.ts +11 -5
  20. package/dist/daemon/api/principal.js +1 -1
  21. package/docs/ci-runner.md +1 -1
  22. package/docs/sdk/release-notes.md +10 -0
  23. package/package.json +3 -3
  24. package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
  25. package/packages/crouter-api/dist/core/grants/local.js +1 -1
  26. package/packages/crouter-api/dist/core/grants/mirror.js +35 -11
  27. package/packages/crouter-api/dist/core/grants/shadow.js +4 -2
  28. package/packages/crouter-api/dist/core/grants/sync.js +5 -4
  29. package/packages/crouter-api/dist/core/ledger/payer.js +8 -3
  30. package/packages/crouter-api/dist/core/llm/app-rungs.js +2 -2
  31. package/packages/crouter-api/dist/core/llm/run.js +3 -2
  32. package/packages/crouter-api/dist/core/runtime/start-check.js +2 -2
  33. package/packages/crouter-api/dist/daemon/api/handlers/git-credential.js +12 -2
  34. package/packages/crouter-api/dist/daemon/api/principal.js +26 -7
  35. package/packages/crouter-api/package.json +1 -1
  36. package/packages/crouter-identity/dist/index.d.ts +4 -2
  37. package/packages/crouter-identity/dist/index.js +31 -12
  38. package/packages/crouter-identity/package.json +1 -1
  39. package/packages/crouter-plugin/dist/serve.js +4 -1
  40. package/packages/crouter-plugin/dist/verify.js +36 -8
  41. package/packages/crouter-plugin/package.json +3 -3
  42. package/runtime.lock.json +14 -14
@@ -9,6 +9,16 @@ when-and-why-to-read: When you need Release notes, this knowledge should be read
9
9
 
10
10
  Changes to `@north-light/sdk` that can change what an existing app sees. Newest first.
11
11
 
12
+ ## 0.3.751
13
+
14
+ ### Call tokens may name any principal
15
+
16
+ The identity verifier accepts an `app:<id>` or `app:<id>/<path>` subject, and an app link with no grant when that app owns the subject's namespace (`chain[i].owner`). Strings that are not `user:`, `app:` or an app path are refused.
17
+
18
+ ### The daemon resolves owner tokens and exchanged person tokens
19
+
20
+ A token whose only link is an owner link now resolves to a caller holding the app's declared scopes and no grant (`grant` and `rev` are null). Operations that read or stream a grant (`grant.get`, `llm.*`) answer 403 `permission_error` to it. A grant-bearing `user:` link on an exchanged token resolves like an app link, with the person as the caller.
21
+
12
22
  ## 0.3.721
13
23
 
14
24
  ### `inferenceEndpoint` serves an app that pays for its own model calls (`billing: 'app'`)
@@ -0,0 +1,50 @@
1
+ -- 037-grant-principals.sql — a grant can name a grantee subtree (`grantee_prefix`), its payer is a principal, and it can narrow to resources; the spend cap sits on the payer.
2
+
3
+ -- A wildcard row stores `grantee = '*'` (the column stays NOT NULL, the (runtime, sub, grantee) unique index is unchanged) and the prefix it covers in `grantee_prefix`.
4
+ ALTER TABLE grants ADD COLUMN grantee_prefix text;
5
+ ALTER TABLE grants ADD CONSTRAINT grants_wildcard_check CHECK ((grantee = '*') = (grantee_prefix IS NOT NULL));
6
+ CREATE UNIQUE INDEX idx_grants_runtime_sub_grantee_prefix ON grants(runtime, sub, grantee_prefix) WHERE grantee_prefix IS NOT NULL;
7
+
8
+ -- `payer` held `'user'` or `'app'`; it now holds the principal that pays: `'user'` is the grant's `sub`, `'app'` its `grantee`.
9
+ UPDATE grants SET payer = sub WHERE payer = 'user';
10
+ UPDATE grants SET payer = grantee WHERE payer = 'app';
11
+
12
+ CREATE TABLE grant_resources (
13
+ grant_id text NOT NULL REFERENCES grants(id) ON DELETE CASCADE,
14
+ service text NOT NULL,
15
+ resource_kind text NOT NULL,
16
+ resource_id text NOT NULL,
17
+ PRIMARY KEY (grant_id, service, resource_kind, resource_id)
18
+ );
19
+
20
+ DROP TRIGGER crtr_sig_grant_upd ON grants;
21
+ CREATE TRIGGER crtr_sig_grant_upd AFTER UPDATE OF
22
+ id, runtime, sub, grantee, grantee_prefix, rev, scopes_json, resolved_scopes_json, spend_cap, expires_at, status, revoked_at,
23
+ approved_at, payer, synced_at, dependencies_json, run_notice_url, inference_endpoint_json, created_at,
24
+ computed_rev, app_pays_until_vendor
25
+ ON grants FOR EACH ROW EXECUTE FUNCTION crtr_signal_grant();
26
+
27
+ -- The cap is the payer's: an active capped grant limits its payer (`sub` when none) for its grantee. As before, a grant its own grantee pays (the app's endpoint pays) and `app:terminal`'s have none.
28
+ CREATE OR REPLACE FUNCTION crtr_grant_limit() RETURNS trigger LANGUAGE plpgsql AS $$
29
+ BEGIN
30
+ IF TG_OP = 'DELETE' THEN
31
+ DELETE FROM limits WHERE source = 'grant_sync' AND id = 'grant:' || OLD.id;
32
+ RETURN OLD;
33
+ END IF;
34
+ IF NEW.status = 'active' AND NEW.spend_cap IS NOT NULL AND NEW.payer IS DISTINCT FROM NEW.grantee AND NEW.grantee <> 'app:terminal' THEN
35
+ INSERT INTO limits (id, payer, grantee, usd_per_month, source, updated_at)
36
+ VALUES ('grant:' || NEW.id, COALESCE(NEW.payer, NEW.sub), NEW.grantee, NEW.spend_cap::numeric, 'grant_sync',
37
+ to_char(now() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"'))
38
+ ON CONFLICT (id) DO UPDATE SET payer = EXCLUDED.payer, funding = NULL, grantee = EXCLUDED.grantee, provider = NULL, sub = NULL,
39
+ account = NULL, usd_per_month = EXCLUDED.usd_per_month, source = 'grant_sync', updated_at = EXCLUDED.updated_at
40
+ WHERE limits.source = 'grant_sync';
41
+ ELSE
42
+ DELETE FROM limits WHERE source = 'grant_sync' AND id = 'grant:' || NEW.id;
43
+ END IF;
44
+ RETURN NULL;
45
+ END $$;
46
+ -- Rows already mirrored get their limit under the new rule on the next sync write; rebuild them now.
47
+ UPDATE grants SET spend_cap = spend_cap WHERE spend_cap IS NOT NULL;
48
+
49
+ -- Version 36 reads `payer = 'app'` to mean app-paid; it would read an app-paid grant's principal payer as owner-paid, so it is refused.
50
+ INSERT INTO canvas_meta (key, value) VALUES ('schema_min_reader', '37') ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value;
@@ -1,7 +1,7 @@
1
1
  /** The canvas schema version this build supports: the number of the highest delta in `schema-pg/` (the baseline
2
2
  * `schema-pg.sql` is version 1). `scripts/install-runtime.mjs` reads this module from a candidate generation to refuse
3
3
  * one below the live database's `schema_min_reader`. */
4
- export declare const CANVAS_SCHEMA_VERSION = 36;
4
+ export declare const CANVAS_SCHEMA_VERSION = 37;
5
5
  /** The Postgres schema holding the canvas tables: `CRTR_DATABASE_SCHEMA` (`crtr` in the cloud deploy). Unset or empty
6
6
  * means the role's own search_path (`public` on a Mac and on a VM). A name that is not a plain identifier is an error:
7
7
  * it is put in a `search_path` connection option. */
@@ -1 +1 @@
1
- var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=36;function _(n=process.env){const e=n.CRTR_DATABASE_SCHEMA?.trim();if(e){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw new Error(`CRTR_DATABASE_SCHEMA must be a plain identifier (letters, digits, underscore); got ${JSON.stringify(e)}`);return e}}r(_,"canvasDatabaseSchema");function h(n=process.env){return n.CRTR_SCHEMA_DATABASE_URL?.trim()||void 0}r(h,"canvasSchemaDatabaseUrl");function E(n=process.env){const e=_(n);return e===void 0?void 0:`-c search_path=${e}`}r(E,"canvasSearchPathOptions");async function v(n,e){const t=e===void 0?"canvas_meta":`"${e.replace(/"/g,'""')}".canvas_meta`;if((await n.query(`SELECT to_regclass('${t.replace(/'/g,"''")}') IS NOT NULL AS found`)).rows[0].found!==!0)return;const u=(await n.query(`SELECT key, value FROM ${t} WHERE key IN ('schema_version', 'schema_min_reader')`)).rows,o=r(c=>{const i=u.find(f=>f.key===c);if(i===void 0)return;const d=Number(i.value);if(!Number.isSafeInteger(d))throw new Error(`canvas_meta.${c} is not an integer: ${String(i.value)}`);return d},"value"),s=o("schema_version");return s===void 0?void 0:{version:s,minReader:o("schema_min_reader")??s}}r(v,"readStoredVersions");async function l(n,e,t){const a=await v(n,t);if(a!==void 0&&a.minReader>e)throw new Error(`refusing to select runtime with canvas schema ${e}: the live database requires readers at version ${a.minReader} or above (it is at ${a.version}); install a descendant build instead`)}r(l,"assertCandidateMayOpen");export{A as CANVAS_SCHEMA_VERSION,l as assertCandidateMayOpen,_ as canvasDatabaseSchema,h as canvasSchemaDatabaseUrl,E as canvasSearchPathOptions,v as readStoredVersions};
1
+ var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=37;function _(n=process.env){const e=n.CRTR_DATABASE_SCHEMA?.trim();if(e){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw new Error(`CRTR_DATABASE_SCHEMA must be a plain identifier (letters, digits, underscore); got ${JSON.stringify(e)}`);return e}}r(_,"canvasDatabaseSchema");function h(n=process.env){return n.CRTR_SCHEMA_DATABASE_URL?.trim()||void 0}r(h,"canvasSchemaDatabaseUrl");function E(n=process.env){const e=_(n);return e===void 0?void 0:`-c search_path=${e}`}r(E,"canvasSearchPathOptions");async function v(n,e){const t=e===void 0?"canvas_meta":`"${e.replace(/"/g,'""')}".canvas_meta`;if((await n.query(`SELECT to_regclass('${t.replace(/'/g,"''")}') IS NOT NULL AS found`)).rows[0].found!==!0)return;const u=(await n.query(`SELECT key, value FROM ${t} WHERE key IN ('schema_version', 'schema_min_reader')`)).rows,o=r(c=>{const i=u.find(f=>f.key===c);if(i===void 0)return;const d=Number(i.value);if(!Number.isSafeInteger(d))throw new Error(`canvas_meta.${c} is not an integer: ${String(i.value)}`);return d},"value"),s=o("schema_version");return s===void 0?void 0:{version:s,minReader:o("schema_min_reader")??s}}r(v,"readStoredVersions");async function l(n,e,t){const a=await v(n,t);if(a!==void 0&&a.minReader>e)throw new Error(`refusing to select runtime with canvas schema ${e}: the live database requires readers at version ${a.minReader} or above (it is at ${a.version}); install a descendant build instead`)}r(l,"assertCandidateMayOpen");export{A as CANVAS_SCHEMA_VERSION,l as assertCandidateMayOpen,_ as canvasDatabaseSchema,h as canvasSchemaDatabaseUrl,E as canvasSearchPathOptions,v as readStoredVersions};
@@ -1 +1 @@
1
- var u=Object.defineProperty;var i=(r,t)=>u(r,"name",{value:t,configurable:!0});import{withCanvasWrite as p}from"../canvas/db.js";import{replaceGrants as m}from"./mirror.js";const a=["crtr:llm","crtr:act","crtr:schedule","crtr:memory:rw:user","crtr:memory:manage:user","crtr:files:rw:user:."].map(r=>({scope:r,mode:"always"}));async function g(r,t){const n=`terminal:${r}`,o=JSON.stringify(a);if(await p(async c=>{const l=await c.prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get(),e=await c.prepare("SELECT id, runtime, sub, grantee, status, scopes_json, resolved_scopes_json FROM grants").all();return l?.value==="local"&&e.length===1&&e[0].id===n&&e[0].runtime===r&&e[0].sub===t&&e[0].grantee==="app:terminal"&&e[0].status==="active"&&e[0].scopes_json===o&&e[0].resolved_scopes_json===o}))return;const s=new Date().toISOString();await m([{id:n,runtime:r,sub:t,grantee:"app:terminal",rev:1,scopes:a,resolved_scopes:a,spend_cap:null,expires_at:null,status:"active",revoked_at:null,approved_at:s,payer:"user",dependencies:{},synced_at:s}],s,"local")}i(g,"installLocalTerminalGrant");export{g as installLocalTerminalGrant};
1
+ var u=Object.defineProperty;var i=(r,t)=>u(r,"name",{value:t,configurable:!0});import{withCanvasWrite as p}from"../canvas/db.js";import{replaceGrants as m}from"./mirror.js";const a=["crtr:llm","crtr:act","crtr:schedule","crtr:memory:rw:user","crtr:memory:manage:user","crtr:files:rw:user:."].map(r=>({scope:r,mode:"always"}));async function g(r,t){const n=`terminal:${r}`,c=JSON.stringify(a);if(await p(async o=>{const l=await o.prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get(),e=await o.prepare("SELECT id, runtime, sub, grantee, status, scopes_json, resolved_scopes_json FROM grants").all();return l?.value==="local"&&e.length===1&&e[0].id===n&&e[0].runtime===r&&e[0].sub===t&&e[0].grantee==="app:terminal"&&e[0].status==="active"&&e[0].scopes_json===c&&e[0].resolved_scopes_json===c}))return;const s=new Date().toISOString();await m([{id:n,runtime:r,sub:t,grantee:"app:terminal",rev:1,scopes:a,resolved_scopes:a,spend_cap:null,expires_at:null,status:"active",revoked_at:null,approved_at:s,payer:t,dependencies:{},synced_at:s}],s,"local")}i(g,"installLocalTerminalGrant");export{g as installLocalTerminalGrant};
@@ -17,6 +17,8 @@ export interface GrantRecord {
17
17
  runtime: string;
18
18
  sub: string;
19
19
  grantee: string;
20
+ /** A wildcard grant (`grantee = '*'`): the grantee-principal prefix it covers; null on an exact grant. */
21
+ grantee_prefix?: string | null;
20
22
  rev: number;
21
23
  scopes: GrantScope[];
22
24
  resolved_scopes: GrantScope[];
@@ -25,15 +27,20 @@ export interface GrantRecord {
25
27
  status: 'active' | 'revoked' | 'removed';
26
28
  revoked_at: string | null;
27
29
  approved_at: string | null;
28
- payer: 'user' | 'app' | null;
30
+ /** The principal that pays: the grant's `sub` for an owner-paid grant, its `grantee` for an app-paid one. Null reads as `sub`. */
31
+ payer: string | null;
29
32
  /** The directory's setup entry (`{ state, message?, next, step? }`) per setup id the grantee requires. Absent (an older directory) reads as `{}`. */
30
33
  dependencies?: GrantDependencies;
31
34
  /** The grantee's registered run-notice endpoint (https), or null: runs of this grant send no notice. */
32
35
  run_notice_url?: string | null;
33
- /** The endpoint of an app-paid grant (`payer: 'app'`); null on a user-paid grant or one the directory sent no valid endpoint for. */
36
+ /** The endpoint of an app-paid grant (its payer is an app namespace root); null on a grant that app does not pay or one the directory sent no valid endpoint for. */
34
37
  inference_endpoint?: InferenceEndpoint | null;
35
38
  synced_at: string;
36
39
  }
40
+ /** The payer a mirrored grant carries, as a principal. The directory's older `'user'` (the grant's `sub`) and `'app'` (its `grantee`) read as those principals; anything else must parse as a principal. */
41
+ export declare function principalPayer(payer: unknown, sub: string, grantee: string): string;
42
+ /** Whether the app's inference endpoint pays for this grant's model calls: its payer is an `app:` namespace root. */
43
+ export declare function endpointPays(grant: Pick<GrantRecord, 'payer'>): boolean;
37
44
  export interface ActiveGrant extends GrantRecord {
38
45
  resolved: Scope[];
39
46
  }
@@ -147,9 +154,10 @@ export interface GrantStanding {
147
154
  export declare function grantStanding(grantId: string): Promise<GrantStanding>;
148
155
  /** Ids of the grants in `status` (this runtime's), for a catch-up pass. */
149
156
  export declare function grantIdsWhere(where: string): Promise<string[]>;
150
- /** Who a grant's model calls are charged to: `app` only for a mirrored grant the directory marked app-paid, else the person. */
157
+ /** Who a grant's model calls are charged to: `app` only when the app's endpoint pays (`endpointPays`), else the person. */
151
158
  export declare function payerOfGrant(grantId: string | null | undefined): Promise<'user' | 'app'>;
152
159
  export declare function activeGrant(grantId: string): Promise<ActiveGrant | null>;
160
+ /** `sub`'s active grant to `grantee`: the exact row, else the wildcard row whose `grantee_prefix` is the longest prefix of `grantee`. The `'*'` sentinel never matches as an exact grantee. */
153
161
  export declare function grantFor(grantee: string, sub: string): Promise<ActiveGrant | null>;
154
162
  /** The app's own active grant on this machine. Null for a mirror-only grant: an
155
163
  * unsandboxed machine runs no app, so a fanned-out hosted grant is never "the
@@ -1,24 +1,24 @@
1
- var I=Object.defineProperty;var n=(e,t)=>I(e,"name",{value:t,configurable:!0});import{createHash as L}from"node:crypto";import{parseScope as C}from"@north-light/identity";import{openDb as p,withCanvasWrite as T}from"../canvas/db.js";import{isUnsandboxedMachine as A}from"../runtime/unsandboxed.js";import{replaceWrittenBy as j,userSubject as M}from"../permissions/facts.js";import{GROUP_TYPE as _,OBJECT_TYPE as F}from"../permissions/builtin.js";import{shadowCheck as $}from"./shadow.js";const k=["not_started","pending","ready","failed","unavailable"],U=["ultra","strong","medium","light"];function m(){const e=process.env.CRTR_RUNTIME;return e?{sql:" AND runtime = ?",args:[e]}:{sql:"",args:[]}}n(m,"runtimeScope");async function i(e,t,r=[]){const s=m();return await(await p()).prepare(`SELECT ${e} FROM grants WHERE (${t})${s.sql}`).all(...r,...s.args)}n(i,"grantRows");async function u(e,t,r=[]){return(await i(e,t,r))[0]}n(u,"grantRow");function G(e){return!/\u0000|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/.test(e)}n(G,"jsonbSafe");function l(e){if(!Array.isArray(e))throw new TypeError("grant scopes must be a list");return e.map(t=>{if(!t||typeof t!="object"||typeof t.scope!="string"||!G(t.scope)||!["always","ask"].includes(t.mode))throw new TypeError("invalid grant scope entry");return{scope:t.scope,mode:t.mode}})}n(l,"entries");function H(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{state:t,message:r,next:s,step:o}=e;return typeof t!="string"||!k.includes(t)||r!==void 0&&typeof r!="string"||o!==void 0&&typeof o!="string"||typeof s!="string"||!s?null:{state:t,...r===void 0?{}:{message:r},next:s,...o===void 0?{}:{step:o}}}n(H,"dependencyOf");function O(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t={};for(const[r,s]of Object.entries(e)){const o=H(s);o&&(t[r]=o)}return t}n(O,"dependenciesOf");function W(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{base_url:t,rungs:r}=e;if(typeof t!="string"||!t||!r||typeof r!="object"||Array.isArray(r))return null;const s={};for(const o of U){const a=r[o];typeof a=="string"&&a&&(s[o]=a)}return Object.keys(s).length?{base_url:t.replace(/\/+$/,""),rungs:s}:null}n(W,"inferenceEndpointOf");function b(e,t,r,s){return t===e&&r&&s}n(b,"computedFor");function f(e){if(!b(e.rev,e.computed_rev,e.scopes_json!==null,e.resolved_scopes_json!==null))throw new TypeError("grant columns are not computed for this revision");return{id:e.id,runtime:e.runtime,sub:e.sub,grantee:e.grantee,rev:e.rev,scopes:l(JSON.parse(e.scopes_json)),resolved_scopes:l(JSON.parse(e.resolved_scopes_json)),spend_cap:e.spend_cap,expires_at:e.expires_at,status:e.status,revoked_at:e.revoked_at,approved_at:e.approved_at,payer:e.payer,dependencies:O(JSON.parse(e.dependencies_json??"{}")),run_notice_url:e.run_notice_url??null,inference_endpoint:e.inference_endpoint_json?W(JSON.parse(e.inference_endpoint_json)):null,synced_at:e.synced_at??""}}n(f,"record");function d(e){if(!e||e.status!=="active")return null;try{const t=X(f(e));return t!==null&&$(t),t}catch(t){if(t instanceof TypeError||t instanceof SyntaxError)return null;throw t}}n(d,"active");function y(e){return e.grantee!=="app:terminal"&&A()}n(y,"mirrorOnly");async function ie(){return(await q()).filter(e=>!y(e))}n(ie,"localGrants");async function ue(e,t){return!y({grantee:e})&&await u("1","grantee = ? AND sub <> ? AND status <> 'removed'",[e,t])!==void 0}n(ue,"otherLiveGrantOfApp");const E="[A-Za-z0-9_-]{1,64}",P=new RegExp(`^(${E}):(${E})$`);function J(e){const t=new Set;for(const r of e)if(r.status==="active")for(const{scope:s}of r.resolved_scopes){const o=P.exec(s);o&&o[1]!=="crtr"&&t.add(o[1])}return[...t].sort()}n(J,"providerIdsFromGrants");async function pe(){const e=m();return(await(await p()).prepare(`SELECT DISTINCT m[1] AS id FROM (
1
+ var L=Object.defineProperty;var n=(e,r)=>L(e,"name",{value:r,configurable:!0});import{createHash as C}from"node:crypto";import{parsePrincipal as T,parseScope as M}from"@north-light/identity";import{openDb as d,withCanvasWrite as A}from"../canvas/db.js";import{isUnsandboxedMachine as O}from"../runtime/unsandboxed.js";import{replaceWrittenBy as j,userSubject as F}from"../permissions/facts.js";import{GROUP_TYPE as f,OBJECT_TYPE as $}from"../permissions/builtin.js";import{shadowCheck as k}from"./shadow.js";const U=["not_started","pending","ready","failed","unavailable"],P=["ultra","strong","medium","light"];function G(e,r,t){if(e==null||e==="user")return r;if(e==="app")return t;if(typeof e!="string"||T(e)===null)throw new TypeError("invalid grant payer");return e}n(G,"principalPayer");function H(e){const r=e.payer===null?null:T(e.payer);return r!==null&&r.kind==="app"&&r.path.length===0}n(H,"endpointPays");function x(){const e=process.env.CRTR_RUNTIME;return e?{sql:" AND runtime = ?",args:[e]}:{sql:"",args:[]}}n(x,"runtimeScope");async function i(e,r,t=[]){const s=x();return await(await d()).prepare(`SELECT ${e} FROM grants WHERE (${r})${s.sql}`).all(...t,...s.args)}n(i,"grantRows");async function u(e,r,t=[]){return(await i(e,r,t))[0]}n(u,"grantRow");function W(e){return!/\u0000|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/.test(e)}n(W,"jsonbSafe");function l(e){if(!Array.isArray(e))throw new TypeError("grant scopes must be a list");return e.map(r=>{if(!r||typeof r!="object"||typeof r.scope!="string"||!W(r.scope)||!["always","ask"].includes(r.mode))throw new TypeError("invalid grant scope entry");return{scope:r.scope,mode:r.mode}})}n(l,"entries");function J(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{state:r,message:t,next:s,step:o}=e;return typeof r!="string"||!U.includes(r)||t!==void 0&&typeof t!="string"||o!==void 0&&typeof o!="string"||typeof s!="string"||!s?null:{state:r,...t===void 0?{}:{message:t},next:s,...o===void 0?{}:{step:o}}}n(J,"dependencyOf");function w(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const r={};for(const[t,s]of Object.entries(e)){const o=J(s);o&&(r[t]=o)}return r}n(w,"dependenciesOf");function V(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{base_url:r,rungs:t}=e;if(typeof r!="string"||!r||!t||typeof t!="object"||Array.isArray(t))return null;const s={};for(const o of P){const a=t[o];typeof a=="string"&&a&&(s[o]=a)}return Object.keys(s).length?{base_url:r.replace(/\/+$/,""),rungs:s}:null}n(V,"inferenceEndpointOf");function b(e,r,t,s){return r===e&&t&&s}n(b,"computedFor");function _(e){if(!b(e.rev,e.computed_rev,e.scopes_json!==null,e.resolved_scopes_json!==null))throw new TypeError("grant columns are not computed for this revision");return{id:e.id,runtime:e.runtime,sub:e.sub,grantee:e.grantee,grantee_prefix:e.grantee_prefix??null,rev:e.rev,scopes:l(JSON.parse(e.scopes_json)),resolved_scopes:l(JSON.parse(e.resolved_scopes_json)),spend_cap:e.spend_cap,expires_at:e.expires_at,status:e.status,revoked_at:e.revoked_at,approved_at:e.approved_at,payer:e.payer,dependencies:w(JSON.parse(e.dependencies_json??"{}")),run_notice_url:e.run_notice_url??null,inference_endpoint:e.inference_endpoint_json?V(JSON.parse(e.inference_endpoint_json)):null,synced_at:e.synced_at??""}}n(_,"record");function p(e){if(!e||e.status!=="active")return null;try{const r=Z(_(e));return r!==null&&k(r),r}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}n(p,"active");function y(e){return e.grantee!=="app:terminal"&&O()}n(y,"mirrorOnly");async function de(){return(await Y()).filter(e=>!y(e))}n(de,"localGrants");async function le(e,r){return!y({grantee:e})&&await u("1","grantee = ? AND sub <> ? AND status <> 'removed'",[e,r])!==void 0}n(le,"otherLiveGrantOfApp");const g="[A-Za-z0-9_-]{1,64}",q=new RegExp(`^(${g}):(${g})$`);function B(e){const r=new Set;for(const t of e)if(t.status==="active")for(const{scope:s}of t.resolved_scopes){const o=q.exec(s);o&&o[1]!=="crtr"&&r.add(o[1])}return[...r].sort()}n(B,"providerIdsFromGrants");async function fe(){const e=x();return(await(await d()).prepare(`SELECT DISTINCT m[1] AS id FROM (
2
2
  SELECT DISTINCT e->>'scope' AS scope FROM (
3
- SELECT t::jsonb AS j FROM (SELECT DISTINCT resolved_scopes_json AS t FROM grants WHERE ${x}${S()}${e.sql}) d OFFSET 0) p
3
+ SELECT t::jsonb AS j FROM (SELECT DISTINCT resolved_scopes_json AS t FROM grants WHERE ${m}${N()}${e.sql}) d OFFSET 0) p
4
4
  CROSS JOIN LATERAL jsonb_array_elements(CASE WHEN jsonb_typeof(p.j) = 'array' THEN p.j ELSE '[]' END) e) s
5
- CROSS JOIN LATERAL regexp_match(s.scope, '^(${E}):${E}$') m
6
- WHERE m[1] <> 'crtr'`).all(...e.args)).map(r=>r.id).sort()}n(pe,"activeProviderIds");async function de(){const e=m();return await(await p()).prepare(`SELECT 1 FROM grants WHERE ${x}${S()}${e.sql} LIMIT 1`).get(...e.args)!==void 0}n(de,"anyActiveGrant");async function le(e,t){return await u("1",`sub = ? AND ${x}${S()} AND EXISTS (
5
+ CROSS JOIN LATERAL regexp_match(s.scope, '^(${g}):${g}$') m
6
+ WHERE m[1] <> 'crtr'`).all(...e.args)).map(t=>t.id).sort()}n(fe,"activeProviderIds");async function _e(){const e=x();return await(await d()).prepare(`SELECT 1 FROM grants WHERE ${m}${N()}${e.sql} LIMIT 1`).get(...e.args)!==void 0}n(_e,"anyActiveGrant");async function ye(e,r){return await u("1",`sub = ? AND ${m}${N()} AND EXISTS (
7
7
  SELECT 1 FROM jsonb_array_elements(CASE WHEN jsonb_typeof(resolved_scopes_json::jsonb) = 'array' THEN resolved_scopes_json::jsonb ELSE '[]' END) e
8
- WHERE starts_with(e->>'scope', ?))`,[e,`${t}:`])!==void 0}n(le,"activeGrantNamesApp");const x="status = 'active' AND computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL",V="computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL";function S(){return A()?" AND grantee = 'app:terminal'":""}n(S,"localOnly");async function _e(){return(await i("DISTINCT sub",V)).map(e=>e.sub)}n(_e,"grantSubs");async function fe(e){return w(e===void 0?await i("*","status = 'active'"):await i("*","sub = ? AND status = 'active'",[e]))}n(fe,"activeGrants");async function ye(e){const t=await i("*","sub = ? AND status = 'active'",[e]);return new Set(J(t.flatMap(r=>{try{return[f(r)]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})))}n(ye,"grantedProviderIds");function Ee(e,t){return e.source_marketplace===null&&e.source_path===null&&t.has(e.name)}n(Ee,"isProviderBundleRow");async function ge(e){return(await i("*","sub = ? AND status = 'active'",[e])).flatMap(r=>{const s=d(r);return s===null?[]:[s]})}n(ge,"activeGrantsOfPerson");async function q(){return w(await i("*","true"))}n(q,"allGrants");async function ve(e){return(await i("sub, status, rev, computed_rev, resolved_scopes_json, scopes_json IS NOT NULL AS has_scopes","sub = ?",[e])).flatMap(r=>{if(!b(r.rev,r.computed_rev,r.has_scopes,r.resolved_scopes_json!==null))return[];try{return[{sub:r.sub,status:r.status,resolved_scopes:l(JSON.parse(r.resolved_scopes_json))}]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})}n(ve,"grantsOfPerson");function w(e){return e.flatMap(t=>{try{return[f(t)]}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return[];throw r}})}n(w,"records");function B(e){return e.expires_at!==null&&!(Date.parse(e.expires_at)>Date.now())}n(B,"grantExpired");function X(e){if(e.status!=="active"||B(e))return null;try{const t=e.resolved_scopes.map(({scope:r})=>C(r));return{...e,resolved:e.resolved_scopes.flatMap(({mode:r},s)=>r==="always"?[t[s]]:[])}}catch(t){if(t instanceof TypeError||t instanceof SyntaxError)return null;throw t}}n(X,"activeRecord");function N(e){return Array.isArray(e)?`[${e.map(N).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().filter(t=>e[t]!==void 0).map(t=>`${JSON.stringify(t)}:${N(e[t])}`).join(",")}}`:JSON.stringify(e)??"null"}n(N,"canonicalJson");function me(e){const t={rev:e.rev,resolved_scopes:e.resolved_scopes,spend_cap:e.spend_cap,payer:e.payer,dependencies:e.dependencies??{},...e.inference_endpoint?{inference_endpoint:e.inference_endpoint}:{}};return L("sha256").update(N(t)).digest("base64url").slice(0,22)}n(me,"grantVersion");async function xe(e){return!!await u("1","id = ?",[e])}n(xe,"hasGrant");async function Se(e){return await u("rev, status","id = ?",[e])??null}n(Se,"grantSyncState");async function Ne(e,t){return await u("rev, status","grantee = ? AND sub = ?",[e,t])??null}n(Ne,"grantSyncStateFor");async function Y(e){const t=await u("*","id = ?",[e]);if(!t)return null;try{return f(t)}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}n(Y,"grantRecord");async function Te(e){const t=await u("*","id = ?",[e]);if(!t)return{standing:"inactive",rev:null,sub:null,grantee:null,status:null,removal_done_at:null,record:null};const r={rev:t.rev,sub:t.sub,grantee:t.grantee,status:t.status,removal_done_at:t.removal_done_at??null};if(t.status!=="active")return{...r,standing:"inactive",record:null};if(t.computed_rev!==t.rev)return{...r,standing:"lagging",record:null};const s=d(t);return s===null?{...r,standing:"inactive",record:null}:{...r,standing:"active",record:s}}n(Te,"grantStanding");async function Ae(e){return(await i("id",e)).map(t=>t.id)}n(Ae,"grantIdsWhere");async function je(e){return(e?(await Y(e))?.payer:null)??"user"}n(je,"payerOfGrant");async function z(e){return d(await u("*","id = ?",[e]))}n(z,"activeGrant");async function Oe(e,t){return d(await u("*","grantee = ? AND sub = ?",[e,t]))}n(Oe,"grantFor");async function be(e){if(y({grantee:e}))return null;const t=await i("*","grantee = ? AND status = 'active'",[e]);if(t.length>1)throw new Error(`multiple active grants for ${e}`);return d(t[0])}n(be,"activeGrantForApp");async function we(e){const t=await z(e);return t&&t.run_notice_url&&!y(t)?{url:t.run_notice_url,sub:t.sub,grantee:t.grantee}:null}n(we,"runNoticeTarget");async function Re(e){const t=await i("*","grantee = 'app:terminal' AND sub = ? AND status = 'active'",[e]);if(t.length>1)throw new Error(`multiple active terminal grants for ${e}`);return d(t[0])}n(Re,"terminalGrant");async function he(){return(await(await p()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value??null}n(he,"grantsSource");async function De(e){return(await(await p()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value===e}n(De,"hasSyncedGrants");async function Ie(e){return(await e.prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value!=="local"?0:(await e.prepare("DELETE FROM runtime_state WHERE key = 'grants_source'").run(),Number((await e.prepare("DELETE FROM grants").run()).changes))}n(Ie,"dropLocalGrantMirror");async function Le(){return await T(async e=>Number((await e.prepare("UPDATE grants SET computed_rev = rev WHERE computed_rev IS NULL AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL").run()).changes))}n(Le,"backfillComputedRev");function Ce(e){if(e===void 0)return[];if(!Array.isArray(e))throw new TypeError("invalid grant sync response");const t=[];for(const r of e){const{team:s,members:o}=r??{};if(!(typeof s!="string"||!/^team:\S+$/.test(s))){if(!Array.isArray(o)||o.some(a=>typeof a!="string"||!/^user:[^\s*]+$/.test(a)))throw new TypeError("invalid grant sync response");t.push({team:s,members:o})}}return t}n(Ce,"teamsOf");async function Me(e,t,r,s=[]){const o=new Set;for(const a of e){if(o.has(a.id)||!a.id||!a.runtime||!a.sub||!a.grantee||!Number.isInteger(a.rev)||!["active","revoked","removed"].includes(a.status))throw new TypeError("invalid grant sync response");o.add(a.id),l(a.scopes),l(a.resolved_scopes)}await T(async a=>{let g=0;const v=[...o];g+=Number((await(v.length?a.prepareUncached(`DELETE FROM grants WHERE id NOT IN (${v.map(()=>"?").join(",")})`).run(...v):a.prepareUncached("DELETE FROM grants").run())).changes);const R=a.prepare(`INSERT INTO grants
9
- (id, runtime, sub, grantee, rev, scopes_json, resolved_scopes_json, spend_cap, expires_at,
8
+ WHERE starts_with(e->>'scope', ?))`,[e,`${r}:`])!==void 0}n(ye,"activeGrantNamesApp");const m="status = 'active' AND computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL",X="computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL";function N(){return O()?" AND grantee = 'app:terminal'":""}n(N,"localOnly");async function ge(){return(await i("DISTINCT sub",X)).map(e=>e.sub)}n(ge,"grantSubs");async function Ee(e){return h(e===void 0?await i("*","status = 'active'"):await i("*","sub = ? AND status = 'active'",[e]))}n(Ee,"activeGrants");async function ve(e){const r=await i("*","sub = ? AND status = 'active'",[e]);return new Set(B(r.flatMap(t=>{try{return[_(t)]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})))}n(ve,"grantedProviderIds");function xe(e,r){return e.source_marketplace===null&&e.source_path===null&&r.has(e.name)}n(xe,"isProviderBundleRow");async function me(e){return(await i("*","sub = ? AND status = 'active'",[e])).flatMap(t=>{const s=p(t);return s===null?[]:[s]})}n(me,"activeGrantsOfPerson");async function Y(){return h(await i("*","true"))}n(Y,"allGrants");async function Ne(e){return(await i("sub, status, rev, computed_rev, resolved_scopes_json, scopes_json IS NOT NULL AS has_scopes","sub = ?",[e])).flatMap(t=>{if(!b(t.rev,t.computed_rev,t.has_scopes,t.resolved_scopes_json!==null))return[];try{return[{sub:t.sub,status:t.status,resolved_scopes:l(JSON.parse(t.resolved_scopes_json))}]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})}n(Ne,"grantsOfPerson");function h(e){return e.flatMap(r=>{try{return[_(r)]}catch(t){if(t instanceof TypeError||t instanceof SyntaxError)return[];throw t}})}n(h,"records");function z(e){return e.expires_at!==null&&!(Date.parse(e.expires_at)>Date.now())}n(z,"grantExpired");function Z(e){if(e.status!=="active"||z(e))return null;try{const r=e.resolved_scopes.map(({scope:t})=>M(t));return{...e,resolved:e.resolved_scopes.flatMap(({mode:t},s)=>t==="always"?[r[s]]:[])}}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}n(Z,"activeRecord");function S(e){return Array.isArray(e)?`[${e.map(S).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().filter(r=>e[r]!==void 0).map(r=>`${JSON.stringify(r)}:${S(e[r])}`).join(",")}}`:JSON.stringify(e)??"null"}n(S,"canonicalJson");function Se(e){const r={rev:e.rev,resolved_scopes:e.resolved_scopes,spend_cap:e.spend_cap,payer:e.payer,dependencies:e.dependencies??{},...e.inference_endpoint?{inference_endpoint:e.inference_endpoint}:{}};return C("sha256").update(S(r)).digest("base64url").slice(0,22)}n(Se,"grantVersion");async function Te(e){return!!await u("1","id = ?",[e])}n(Te,"hasGrant");async function Ae(e){return await u("rev, status","id = ?",[e])??null}n(Ae,"grantSyncState");async function Oe(e,r){return await u("rev, status","grantee = ? AND sub = ?",[e,r])??null}n(Oe,"grantSyncStateFor");async function K(e){const r=await u("*","id = ?",[e]);if(!r)return null;try{return _(r)}catch(t){if(t instanceof TypeError||t instanceof SyntaxError)return null;throw t}}n(K,"grantRecord");async function je(e){const r=await u("*","id = ?",[e]);if(!r)return{standing:"inactive",rev:null,sub:null,grantee:null,status:null,removal_done_at:null,record:null};const t={rev:r.rev,sub:r.sub,grantee:r.grantee,status:r.status,removal_done_at:r.removal_done_at??null};if(r.status!=="active")return{...t,standing:"inactive",record:null};if(r.computed_rev!==r.rev)return{...t,standing:"lagging",record:null};const s=p(r);return s===null?{...t,standing:"inactive",record:null}:{...t,standing:"active",record:s}}n(je,"grantStanding");async function we(e){return(await i("id",e)).map(r=>r.id)}n(we,"grantIdsWhere");async function be(e){const r=e?await K(e):null;return r!==null&&H(r)?"app":"user"}n(be,"payerOfGrant");async function Q(e){return p(await u("*","id = ?",[e]))}n(Q,"activeGrant");async function he(e,r){const t=await u("*","grantee = ? AND grantee_prefix IS NULL AND sub = ?",[e,r]);if(t)return p(t);const s=await i("*","sub = ? AND grantee_prefix IS NOT NULL AND starts_with(?, grantee_prefix)",[r,e]);return s.sort((o,a)=>a.grantee_prefix.length-o.grantee_prefix.length),p(s[0])}n(he,"grantFor");async function Re(e){if(y({grantee:e}))return null;const r=await i("*","grantee = ? AND status = 'active'",[e]);if(r.length>1)throw new Error(`multiple active grants for ${e}`);return p(r[0])}n(Re,"activeGrantForApp");async function De(e){const r=await Q(e);return r&&r.run_notice_url&&!y(r)?{url:r.run_notice_url,sub:r.sub,grantee:r.grantee}:null}n(De,"runNoticeTarget");async function Ie(e){const r=await i("*","grantee = 'app:terminal' AND sub = ? AND status = 'active'",[e]);if(r.length>1)throw new Error(`multiple active terminal grants for ${e}`);return p(r[0])}n(Ie,"terminalGrant");async function Le(){return(await(await d()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value??null}n(Le,"grantsSource");async function Ce(e){return(await(await d()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value===e}n(Ce,"hasSyncedGrants");async function Me(e){return(await e.prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value!=="local"?0:(await e.prepare("DELETE FROM runtime_state WHERE key = 'grants_source'").run(),Number((await e.prepare("DELETE FROM grants").run()).changes))}n(Me,"dropLocalGrantMirror");async function Fe(){return await A(async e=>Number((await e.prepare("UPDATE grants SET computed_rev = rev WHERE computed_rev IS NULL AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL").run()).changes))}n(Fe,"backfillComputedRev");function $e(e){if(e===void 0)return[];if(!Array.isArray(e))throw new TypeError("invalid grant sync response");const r=[];for(const t of e){const{team:s,members:o}=t??{};if(!(typeof s!="string"||!/^team:\S+$/.test(s))){if(!Array.isArray(o)||o.some(a=>typeof a!="string"||!/^user:[^\s*]+$/.test(a)))throw new TypeError("invalid grant sync response");r.push({team:s,members:o})}}return r}n($e,"teamsOf");async function ke(e,r,t,s=[]){const o=new Set;for(const a of e){if(o.has(a.id)||!a.id||!a.runtime||!a.sub||!a.grantee||!Number.isInteger(a.rev)||!["active","revoked","removed"].includes(a.status))throw new TypeError("invalid grant sync response");if(a.grantee==="*"!=(a.grantee_prefix!=null))throw new TypeError("invalid grant sync response");o.add(a.id),l(a.scopes),l(a.resolved_scopes)}await A(async a=>{let E=0;const v=[...o];E+=Number((await(v.length?a.prepareUncached(`DELETE FROM grants WHERE id NOT IN (${v.map(()=>"?").join(",")})`).run(...v):a.prepareUncached("DELETE FROM grants").run())).changes);const R=a.prepare(`INSERT INTO grants
9
+ (id, runtime, sub, grantee, grantee_prefix, rev, scopes_json, resolved_scopes_json, spend_cap, expires_at,
10
10
  status, revoked_at, approved_at, payer, dependencies_json, run_notice_url, inference_endpoint_json, synced_at, computed_rev)
11
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
12
- ON CONFLICT (id) DO UPDATE SET runtime = excluded.runtime, sub = excluded.sub, grantee = excluded.grantee, rev = excluded.rev,
11
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
12
+ ON CONFLICT (id) DO UPDATE SET runtime = excluded.runtime, sub = excluded.sub, grantee = excluded.grantee, grantee_prefix = excluded.grantee_prefix, rev = excluded.rev,
13
13
  scopes_json = excluded.scopes_json, resolved_scopes_json = excluded.resolved_scopes_json, spend_cap = excluded.spend_cap,
14
14
  expires_at = excluded.expires_at, status = excluded.status, revoked_at = excluded.revoked_at, approved_at = excluded.approved_at,
15
15
  payer = excluded.payer, dependencies_json = excluded.dependencies_json, run_notice_url = excluded.run_notice_url,
16
16
  inference_endpoint_json = excluded.inference_endpoint_json, synced_at = excluded.synced_at, computed_rev = excluded.computed_rev
17
- WHERE (grants.runtime, grants.sub, grants.grantee, grants.rev, grants.scopes_json, grants.resolved_scopes_json, grants.spend_cap,
17
+ WHERE (grants.runtime, grants.sub, grants.grantee, grants.grantee_prefix, grants.rev, grants.scopes_json, grants.resolved_scopes_json, grants.spend_cap,
18
18
  grants.expires_at, grants.status, grants.revoked_at, grants.approved_at, grants.payer, grants.dependencies_json,
19
19
  grants.run_notice_url, grants.inference_endpoint_json, grants.computed_rev)
20
- IS DISTINCT FROM (excluded.runtime, excluded.sub, excluded.grantee, excluded.rev, excluded.scopes_json, excluded.resolved_scopes_json,
20
+ IS DISTINCT FROM (excluded.runtime, excluded.sub, excluded.grantee, excluded.grantee_prefix, excluded.rev, excluded.scopes_json, excluded.resolved_scopes_json,
21
21
  excluded.spend_cap, excluded.expires_at, excluded.status, excluded.revoked_at, excluded.approved_at, excluded.payer,
22
- excluded.dependencies_json, excluded.run_notice_url, excluded.inference_endpoint_json, excluded.computed_rev)`);for(const c of e)g+=Number((await R.run(c.id,c.runtime,c.sub,c.grantee,c.rev,JSON.stringify(c.scopes),JSON.stringify(c.resolved_scopes),c.spend_cap,c.expires_at,c.status,c.revoked_at,c.approved_at,c.payer,JSON.stringify(O(c.dependencies)),c.run_notice_url??null,c.inference_endpoint?JSON.stringify(c.inference_endpoint):null,c.synced_at,c.rev)).changes);await j(a,"directory",_,"member",s.flatMap(({team:c,members:h})=>h.map(D=>({resourceId:c,subject:M(D)})))),await Q(a),await a.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_source', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(r),g>0&&await a.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_generation', '1') ON CONFLICT(key) DO UPDATE SET value = CAST(CAST(runtime_state.value AS INTEGER) + 1 AS TEXT)").run()})}n(Me,"replaceGrants");const Z=["editor","messenger","user_of"],K="app-admin";async function Q(e){const r=(await e.prepare(`SELECT o.id AS object, r.subject_type, r.subject_id FROM objects o
22
+ excluded.dependencies_json, excluded.run_notice_url, excluded.inference_endpoint_json, excluded.computed_rev)`);for(const c of e)E+=Number((await R.run(c.id,c.runtime,c.sub,c.grantee,c.grantee_prefix??null,c.rev,JSON.stringify(c.scopes),JSON.stringify(c.resolved_scopes),c.spend_cap,c.expires_at,c.status,c.revoked_at,c.approved_at,G(c.payer,c.sub,c.grantee),JSON.stringify(w(c.dependencies)),c.run_notice_url??null,c.inference_endpoint?JSON.stringify(c.inference_endpoint):null,c.synced_at,c.rev)).changes);await j(a,"directory",f,"member",s.flatMap(({team:c,members:D})=>D.map(I=>({resourceId:c,subject:F(I)})))),await te(a),await a.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_source', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t),E>0&&await a.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_generation', '1') ON CONFLICT(key) DO UPDATE SET value = CAST(CAST(runtime_state.value AS INTEGER) + 1 AS TEXT)").run()})}n(ke,"replaceGrants");const ee=["editor","messenger","user_of"],re="app-admin";async function te(e){const t=(await e.prepare(`SELECT o.id AS object, r.subject_type, r.subject_id FROM objects o
23
23
  JOIN relations r ON r.resource_type = 'app' AND r.resource_id = o.name AND r.relation = 'admin' AND r.subject_type IN ('user', ?)
24
- WHERE o.type = 'app' AND o.deleted_at IS NULL`).all(_)).map(s=>({resourceId:s.object,subject:s.subject_type===_?{type:_,id:s.subject_id,relation:"member"}:{type:"user",id:s.subject_id,relation:""}}));for(const s of Z)await j(e,K,F,s,r)}n(Q,"reconcileAppAdminFacts");async function Fe(){const e=await(await p()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_generation'").get();return e?Number(e.value):0}n(Fe,"grantsGeneration");export{K as APP_ADMIN_WRITER,z as activeGrant,be as activeGrantForApp,le as activeGrantNamesApp,fe as activeGrants,ge as activeGrantsOfPerson,pe as activeProviderIds,X as activeRecord,q as allGrants,de as anyActiveGrant,Le as backfillComputedRev,N as canonicalJson,O as dependenciesOf,Ie as dropLocalGrantMirror,B as grantExpired,Oe as grantFor,Ae as grantIdsWhere,Y as grantRecord,Te as grantStanding,_e as grantSubs,Se as grantSyncState,Ne as grantSyncStateFor,me as grantVersion,ye as grantedProviderIds,Fe as grantsGeneration,ve as grantsOfPerson,he as grantsSource,xe as hasGrant,De as hasSyncedGrants,W as inferenceEndpointOf,Ee as isProviderBundleRow,ie as localGrants,y as mirrorOnly,ue as otherLiveGrantOfApp,je as payerOfGrant,J as providerIdsFromGrants,Q as reconcileAppAdminFacts,Me as replaceGrants,we as runNoticeTarget,m as runtimeScope,Ce as teamsOf,Re as terminalGrant};
24
+ WHERE o.type = 'app' AND o.deleted_at IS NULL`).all(f)).map(s=>({resourceId:s.object,subject:s.subject_type===f?{type:f,id:s.subject_id,relation:"member"}:{type:"user",id:s.subject_id,relation:""}}));for(const s of ee)await j(e,re,$,s,t)}n(te,"reconcileAppAdminFacts");async function Ue(){const e=await(await d()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_generation'").get();return e?Number(e.value):0}n(Ue,"grantsGeneration");export{re as APP_ADMIN_WRITER,Q as activeGrant,Re as activeGrantForApp,ye as activeGrantNamesApp,Ee as activeGrants,me as activeGrantsOfPerson,fe as activeProviderIds,Z as activeRecord,Y as allGrants,_e as anyActiveGrant,Fe as backfillComputedRev,S as canonicalJson,w as dependenciesOf,Me as dropLocalGrantMirror,H as endpointPays,z as grantExpired,he as grantFor,we as grantIdsWhere,K as grantRecord,je as grantStanding,ge as grantSubs,Ae as grantSyncState,Oe as grantSyncStateFor,Se as grantVersion,ve as grantedProviderIds,Ue as grantsGeneration,Ne as grantsOfPerson,Le as grantsSource,Te as hasGrant,Ce as hasSyncedGrants,V as inferenceEndpointOf,xe as isProviderBundleRow,de as localGrants,y as mirrorOnly,le as otherLiveGrantOfApp,be as payerOfGrant,G as principalPayer,B as providerIdsFromGrants,te as reconcileAppAdminFacts,ke as replaceGrants,De as runNoticeTarget,x as runtimeScope,$e as teamsOf,Ie as terminalGrant};
@@ -1 +1 @@
1
- var S=Object.defineProperty;var a=(e,r)=>S(e,"name",{value:r,configurable:!0});import{directoryIssuer as $}from"../directory/issuer.js";import{outboundFetch as v}from"../events/outbound.js";import{warn as u}from"../output.js";import{canonicalJson as m}from"./mirror.js";let _=5e3;function O(e){_=e}a(O,"setShadowTtl");const k=512,A=["status","scopes","resolved_scopes","spend_cap","payer","dependencies","run_notice_url","inference_endpoint"];function R(){i.clear()}a(R,"resetShadowCache");const i=new Map,f=new Map,t={agree:0,disagree:0,lagging:0,error:0};async function M(e,r,n){const{mintDirectoryToken:s}=await import("./sync.js"),o=await s(e),g=n?`&epochs=${n.epochs.global},${n.epochs.sub}`:"",y=`${e}/v1/runtime/grant-answers?sub=${encodeURIComponent(r)}${g}`,d=await v("grant_shadow",y,{headers:{Authorization:`Bearer ${o.access_token}`},signal:AbortSignal.timeout(1e4)});if(!d.ok)throw new Error(`grant-answers ${d.status}`);const l=await d.json();if(l.unchanged){if(!n)throw new Error("grant-answers said unchanged to a caller holding nothing");return{...n,epochs:l.epochs,checkedAt:Date.now()}}return{epochs:l.epochs,grants:new Map((l.grants??[]).map(w=>[String(w.id),w])),checkedAt:Date.now()}}a(M,"fetchAnswer");async function x(e,r){const n=i.get(r);if(n&&Date.now()-n.checkedAt<_)return n;const s=f.get(r);if(s)return s;const o=M(e,r,n).then(g=>(i.delete(r),i.set(r,g),i.size>k&&i.delete(i.keys().next().value),g)).finally(()=>f.delete(r));return f.set(r,o),o}a(x,"answerFor");const h=new Set;async function T(){await Promise.all([...h])}a(T,"shadowIdle");async function C(e){const r=$();if(r===null)return;const n=(await x(r,e.sub)).grants.get(e.id);if(!n){t.disagree++,u(`grant_shadow disagree ${JSON.stringify({grant:e.id,sub:e.sub,fields:["missing"]})}`);return}if(n.rev!==e.rev){t.lagging++;return}const s=A.filter(o=>m(n[o]??null)!==m(e[o]??null));if(s.length===0){t.agree++;return}t.disagree++,u(`grant_shadow disagree ${JSON.stringify({grant:e.id,sub:e.sub,rev:e.rev,fields:s})}`)}a(C,"compare");let p,c={agree:0,disagree:0,lagging:0,error:0};function b(){p||(p=setInterval(()=>{const e={agree:t.agree-c.agree,disagree:t.disagree-c.disagree,lagging:t.lagging-c.lagging,error:t.error-c.error};c={...t},e.agree+e.disagree+e.lagging+e.error>0&&u(`grant_shadow_summary ${JSON.stringify({window_s:60,...e})}`)},6e4),p.unref())}a(b,"startSummary");function U(e){if(!process.env.CRTR_RUNTIME)return;b();const r=C(e).catch(n=>{t.error++,u(`grant_shadow error ${JSON.stringify({grant:e.id,message:n instanceof Error?n.message:String(n)})}`)}).finally(()=>h.delete(r));h.add(r)}a(U,"shadowCheck");export{R as resetShadowCache,O as setShadowTtl,U as shadowCheck,t as shadowCounts,T as shadowIdle};
1
+ var S=Object.defineProperty;var a=(e,r)=>S(e,"name",{value:r,configurable:!0});import{directoryIssuer as v}from"../directory/issuer.js";import{outboundFetch as $}from"../events/outbound.js";import{warn as u}from"../output.js";import{canonicalJson as m,principalPayer as k}from"./mirror.js";let y=5e3;function R(e){y=e}a(R,"setShadowTtl");const A=512,M=["status","scopes","resolved_scopes","spend_cap","payer","dependencies","run_notice_url","inference_endpoint"];function T(){o.clear()}a(T,"resetShadowCache");const o=new Map,f=new Map,t={agree:0,disagree:0,lagging:0,error:0};async function b(e,r,n){const{mintDirectoryToken:c}=await import("./sync.js"),s=await c(e),i=n?`&epochs=${n.epochs.global},${n.epochs.sub}`:"",_=`${e}/v1/runtime/grant-answers?sub=${encodeURIComponent(r)}${i}`,d=await $("grant_shadow",_,{headers:{Authorization:`Bearer ${s.access_token}`},signal:AbortSignal.timeout(1e4)});if(!d.ok)throw new Error(`grant-answers ${d.status}`);const l=await d.json();if(l.unchanged){if(!n)throw new Error("grant-answers said unchanged to a caller holding nothing");return{...n,epochs:l.epochs,checkedAt:Date.now()}}return{epochs:l.epochs,grants:new Map((l.grants??[]).map(w=>[String(w.id),w])),checkedAt:Date.now()}}a(b,"fetchAnswer");async function x(e,r){const n=o.get(r);if(n&&Date.now()-n.checkedAt<y)return n;const c=f.get(r);if(c)return c;const s=b(e,r,n).then(i=>(o.delete(r),o.set(r,i),o.size>A&&o.delete(o.keys().next().value),i)).finally(()=>f.delete(r));return f.set(r,s),s}a(x,"answerFor");const p=new Set;async function P(){await Promise.all([...p])}a(P,"shadowIdle");async function C(e){const r=v();if(r===null)return;const n=(await x(r,e.sub)).grants.get(e.id);if(!n){t.disagree++,u(`grant_shadow disagree ${JSON.stringify({grant:e.id,sub:e.sub,fields:["missing"]})}`);return}if(n.rev!==e.rev){t.lagging++;return}const c={...n,payer:k(n.payer,e.sub,e.grantee)},s=M.filter(i=>m(c[i]??null)!==m(e[i]??null));if(s.length===0){t.agree++;return}t.disagree++,u(`grant_shadow disagree ${JSON.stringify({grant:e.id,sub:e.sub,rev:e.rev,fields:s})}`)}a(C,"compare");let h,g={agree:0,disagree:0,lagging:0,error:0};function D(){h||(h=setInterval(()=>{const e={agree:t.agree-g.agree,disagree:t.disagree-g.disagree,lagging:t.lagging-g.lagging,error:t.error-g.error};g={...t},e.agree+e.disagree+e.lagging+e.error>0&&u(`grant_shadow_summary ${JSON.stringify({window_s:60,...e})}`)},6e4),h.unref())}a(D,"startSummary");function U(e){if(!process.env.CRTR_RUNTIME)return;D();const r=C(e).catch(n=>{t.error++,u(`grant_shadow error ${JSON.stringify({grant:e.id,message:n instanceof Error?n.message:String(n)})}`)}).finally(()=>p.delete(r));p.add(r)}a(U,"shadowCheck");export{T as resetShadowCache,R as setShadowTtl,U as shadowCheck,t as shadowCounts,P as shadowIdle};
@@ -1 +1 @@
1
- var O=Object.defineProperty;var r=(e,n)=>O(e,"name",{value:n,configurable:!0});import{createPrivateKey as P,randomUUID as $,sign as A}from"node:crypto";import{readFileSync as T}from"node:fs";import{join as N}from"node:path";import{crtrHome as R}from"../canvas/paths.js";import{withCanvasWrite as v}from"../canvas/db.js";import{reconcilePackages as G}from"../graph/package-reconcile.js";import{isUnsandboxedMachine as k}from"../runtime/unsandboxed.js";import{emitEvent as f}from"../events/emit.js";import{describeOutboundFailure as J,outboundFetch as b,outboundJson as E,outboundRefusal as S}from"../events/outbound.js";import{dependenciesOf as U,inferenceEndpointOf as B,replaceGrants as C,teamsOf as D}from"./mirror.js";import{onGrantSync as F}from"./on-sync.js";import{hostedEndpointOf as I,paymentSetupUrlOf as M,storeHostedEndpoint as W}from"./hosted-endpoint.js";import{adoptInstallPerson as q}from"../scoped-state/migrate.js";import{PersonOutsideRequestError as L,PersonUnresolvedError as H,personId as z,resolvePerson as K,retireLocalPerson as V,setPersonId as Y}from"../canvas/person.js";const ve=300;function Q(e,n){const t=Math.floor(Date.now()/1e3),i=Buffer.from(JSON.stringify({alg:"ES256",typ:"JWT",kid:e.kid})).toString("base64url"),c=Buffer.from(JSON.stringify({iss:e.client_id,sub:e.client_id,aud:n,iat:t,exp:t+300,jti:$()})).toString("base64url"),u=`${i}.${c}`,o=A("sha256",Buffer.from(u),{key:P({key:e.jwk,format:"jwk"}),dsaEncoding:"ieee-p1363"});return`${u}.${o.toString("base64url")}`}r(Q,"assertion");function y(){const e=JSON.parse(T(N(R(),"secrets","runtime-client.json"),"utf8"));if(!e.jwk||e.alg!=="ES256"||!e.kid||!e.client_id||!e.runtime||e.jwk.kid!==e.kid||e.jwk.kty!=="EC"||e.jwk.crv!=="P-256"||!e.jwk.d)throw new TypeError("invalid runtime client key");return e}r(y,"runtimeClient");function ke(e=y()){return e.runtime.startsWith("runtime:")?e.runtime.slice(8):e.runtime}r(ke,"runtimeId");function X(e){return"This machine was removed from your Northlight account. To use it again, run `crtr sys signin`."}r(X,"machineRevokedMessage");class x extends Error{static{r(this,"MachineRevokedError")}constructor(n){super(X(n)),this.name="MachineRevokedError"}}async function Z(e,n,t){const i=y(),c=`${e.replace(/\/$/,"")}/token`,u=new URLSearchParams({grant_type:"client_credentials",client_id:i.client_id,client_assertion_type:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer",client_assertion:Q(i,c),...n===void 0?{}:{audience:n},...t===void 0?{}:{sub:t}}),o=await b("directory_token",c,{method:"POST",body:u,signal:AbortSignal.timeout(1e4)});if(!o.ok)throw o.status===401&&k()&&await ee(o)?new x(e):S("directory_token",c,`directory token request failed: ${o.status}`);const a=await E("directory_token",c,o);if(typeof a.access_token!="string")throw new TypeError("directory token response has no access_token");return{access_token:a.access_token,expires_at:te(a.access_token,a.expires_in)}}r(Z,"mintDirectoryToken");async function ee(e){try{return(await e.json()).error==="invalid_client"}catch{return!1}}r(ee,"isInvalidClient");function te(e,n){if(typeof n=="number"&&Number.isFinite(n)&&n>0)return Date.now()+n*1e3;try{const t=JSON.parse(Buffer.from(e.split(".")[1]??"","base64url").toString("utf8"));if(typeof t.exp=="number")return t.exp*1e3}catch{}return Date.now()+3e5}r(te,"tokenExpiry");function ne(e,n){if(!e||typeof e!="object")throw new TypeError("invalid grant sync response");const t=e,i=n.runtime.startsWith("runtime:")?n.runtime:`runtime:${n.runtime}`;if(!(t.runtime===i||k()&&typeof t.runtime=="string"&&t.runtime.startsWith("runtime:")&&t.grantee!=="app:terminal")||typeof t.id!="string"||typeof t.sub!="string"||typeof t.grantee!="string"||!Number.isInteger(t.rev)||!Array.isArray(t.scopes)||!Array.isArray(t.resolved_scopes)||!["active","revoked","removed"].includes(t.status??"")||typeof t.synced_at!="string")throw new TypeError("invalid grant sync response");const o=e.revisions?.find(d=>d.rev===t.rev)?.approved_at;if(typeof o!="string")throw new TypeError("grant revision has no approval time");const a=t.payer==="app"?"app":"user";return{...t,spend_cap:t.spend_cap??null,expires_at:t.expires_at??null,revoked_at:t.revoked_at??null,approved_at:o,payer:a,dependencies:U(t.dependencies),inference_endpoint:a==="app"?B(t.inference_endpoint):null,run_notice_url:typeof t.run_notice_url=="string"&&t.run_notice_url!==""?t.run_notice_url:null}}r(ne,"responseGrant");async function re(){try{return{id:z(),late:null}}catch(n){if(n instanceof L)return null;if(!(n instanceof H))throw n}const e=await K();return e===null?null:{id:e.id,late:e}}r(re,"pullPerson");async function oe(e){Y(e.id),await q(e.id);const n=await V();await v(async t=>await G(t)),f({level:"info",event:"daemon.person.resolved",fields:{person_id:e.id,source:e.source}}),f({level:"info",event:"daemon.person.retired",fields:{person_id:n.person,retired:n.retired,columns:n.columns}})}r(oe,"bindLatePerson");let _;function be(e){return _?_(e):Promise.resolve()}r(be,"requestGrantSync");function Ee(e,n=t=>{}){let t;const i=e.replace(/\/$/,""),c=r(async()=>{const d=y(),p=await Z(i),m=await b("grant_sync",`${i}/v1/runtime/grants`,{headers:{Authorization:`Bearer ${p.access_token}`},signal:AbortSignal.timeout(1e4)});if(!m.ok)throw S("grant_sync",`${i}/v1/runtime/grants`,`directory grant sync failed: ${m.status}`);const s=await E("grant_sync",`${i}/v1/runtime/grants`,m);if(!Array.isArray(s.grants)||typeof s.synced_at!="string")throw new TypeError("invalid grant sync response");const g="hosted_endpoint"in s||"payment_setup_url"in s?{hosted_endpoint:I(s.hosted_endpoint??null),payment_setup_url:M(s.payment_setup_url??null),synced_at:s.synced_at}:void 0,j=s.synced_at,h=s.grants.map(l=>ne(l,d)),w=await v(async()=>{await C(h,j,i,D(s.teams));const l=await re();return g&&l&&await W(g,l.id),l});f({level:"info",event:"daemon.grants.synced",fields:{grants:h.length,synced_at:s.synced_at}}),w?.late&&await oe(w.late);try{await F(n)}catch(l){f({level:"error",event:"daemon.grants.on_sync_failed",error:l})}},"run");let u;const o=r(()=>{const d=c().catch(p=>{throw p instanceof x?f({level:"error",event:"daemon.grants.machine_revoked",error:p}):f({level:"error",event:"daemon.grants.sync_failed",error:p,fields:J(p)}),p}).finally(()=>{t===d&&(t=void 0)});return t=d,d},"start"),a=r((d={})=>t?d.fresh?(u??=t.catch(()=>{}).then(()=>(u=void 0,t??o())),u):t:o(),"sync");return _=a,a}r(Ee,"createGrantSync");export{ve as GRANT_SYNC_INTERVAL_S,x as MachineRevokedError,Q as assertion,Ee as createGrantSync,X as machineRevokedMessage,Z as mintDirectoryToken,be as requestGrantSync,y as runtimeClient,ke as runtimeId};
1
+ var j=Object.defineProperty;var r=(e,n)=>j(e,"name",{value:n,configurable:!0});import{createPrivateKey as O,randomUUID as $,sign as A}from"node:crypto";import{readFileSync as T}from"node:fs";import{join as N}from"node:path";import{crtrHome as R}from"../canvas/paths.js";import{withCanvasWrite as v}from"../canvas/db.js";import{reconcilePackages as G}from"../graph/package-reconcile.js";import{isUnsandboxedMachine as k}from"../runtime/unsandboxed.js";import{emitEvent as f}from"../events/emit.js";import{describeOutboundFailure as J,outboundFetch as b,outboundJson as E,outboundRefusal as S}from"../events/outbound.js";import{dependenciesOf as U,endpointPays as B,inferenceEndpointOf as C,principalPayer as D,replaceGrants as F,teamsOf as I}from"./mirror.js";import{onGrantSync as M}from"./on-sync.js";import{hostedEndpointOf as W,paymentSetupUrlOf as q,storeHostedEndpoint as L}from"./hosted-endpoint.js";import{adoptInstallPerson as H}from"../scoped-state/migrate.js";import{PersonOutsideRequestError as z,PersonUnresolvedError as K,personId as V,resolvePerson as Y,retireLocalPerson as Q,setPersonId as X}from"../canvas/person.js";const be=300;function Z(e,n){const t=Math.floor(Date.now()/1e3),i=Buffer.from(JSON.stringify({alg:"ES256",typ:"JWT",kid:e.kid})).toString("base64url"),c=Buffer.from(JSON.stringify({iss:e.client_id,sub:e.client_id,aud:n,iat:t,exp:t+300,jti:$()})).toString("base64url"),u=`${i}.${c}`,o=A("sha256",Buffer.from(u),{key:O({key:e.jwk,format:"jwk"}),dsaEncoding:"ieee-p1363"});return`${u}.${o.toString("base64url")}`}r(Z,"assertion");function y(){const e=JSON.parse(T(N(R(),"secrets","runtime-client.json"),"utf8"));if(!e.jwk||e.alg!=="ES256"||!e.kid||!e.client_id||!e.runtime||e.jwk.kid!==e.kid||e.jwk.kty!=="EC"||e.jwk.crv!=="P-256"||!e.jwk.d)throw new TypeError("invalid runtime client key");return e}r(y,"runtimeClient");function Ee(e=y()){return e.runtime.startsWith("runtime:")?e.runtime.slice(8):e.runtime}r(Ee,"runtimeId");function ee(e){return"This machine was removed from your Northlight account. To use it again, run `crtr sys signin`."}r(ee,"machineRevokedMessage");class x extends Error{static{r(this,"MachineRevokedError")}constructor(n){super(ee(n)),this.name="MachineRevokedError"}}async function te(e,n,t){const i=y(),c=`${e.replace(/\/$/,"")}/token`,u=new URLSearchParams({grant_type:"client_credentials",client_id:i.client_id,client_assertion_type:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer",client_assertion:Z(i,c),...n===void 0?{}:{audience:n},...t===void 0?{}:{sub:t}}),o=await b("directory_token",c,{method:"POST",body:u,signal:AbortSignal.timeout(1e4)});if(!o.ok)throw o.status===401&&k()&&await ne(o)?new x(e):S("directory_token",c,`directory token request failed: ${o.status}`);const a=await E("directory_token",c,o);if(typeof a.access_token!="string")throw new TypeError("directory token response has no access_token");return{access_token:a.access_token,expires_at:re(a.access_token,a.expires_in)}}r(te,"mintDirectoryToken");async function ne(e){try{return(await e.json()).error==="invalid_client"}catch{return!1}}r(ne,"isInvalidClient");function re(e,n){if(typeof n=="number"&&Number.isFinite(n)&&n>0)return Date.now()+n*1e3;try{const t=JSON.parse(Buffer.from(e.split(".")[1]??"","base64url").toString("utf8"));if(typeof t.exp=="number")return t.exp*1e3}catch{}return Date.now()+3e5}r(re,"tokenExpiry");function oe(e,n){if(!e||typeof e!="object")throw new TypeError("invalid grant sync response");const t=e,i=n.runtime.startsWith("runtime:")?n.runtime:`runtime:${n.runtime}`;if(!(t.runtime===i||k()&&typeof t.runtime=="string"&&t.runtime.startsWith("runtime:")&&t.grantee!=="app:terminal")||typeof t.id!="string"||typeof t.sub!="string"||typeof t.grantee!="string"||!Number.isInteger(t.rev)||!Array.isArray(t.scopes)||!Array.isArray(t.resolved_scopes)||!["active","revoked","removed"].includes(t.status??"")||typeof t.synced_at!="string")throw new TypeError("invalid grant sync response");const o=e.revisions?.find(d=>d.rev===t.rev)?.approved_at;if(typeof o!="string")throw new TypeError("grant revision has no approval time");const a=D(t.payer,t.sub,t.grantee);return{...t,spend_cap:t.spend_cap??null,expires_at:t.expires_at??null,grantee_prefix:typeof t.grantee_prefix=="string"?t.grantee_prefix:null,revoked_at:t.revoked_at??null,approved_at:o,payer:a,dependencies:U(t.dependencies),inference_endpoint:B({payer:a})?C(t.inference_endpoint):null,run_notice_url:typeof t.run_notice_url=="string"&&t.run_notice_url!==""?t.run_notice_url:null}}r(oe,"responseGrant");async function ie(){try{return{id:V(),late:null}}catch(n){if(n instanceof z)return null;if(!(n instanceof K))throw n}const e=await Y();return e===null?null:{id:e.id,late:e}}r(ie,"pullPerson");async function se(e){X(e.id),await H(e.id);const n=await Q();await v(async t=>await G(t)),f({level:"info",event:"daemon.person.resolved",fields:{person_id:e.id,source:e.source}}),f({level:"info",event:"daemon.person.retired",fields:{person_id:n.person,retired:n.retired,columns:n.columns}})}r(se,"bindLatePerson");let _;function Se(e){return _?_(e):Promise.resolve()}r(Se,"requestGrantSync");function xe(e,n=t=>{}){let t;const i=e.replace(/\/$/,""),c=r(async()=>{const d=y(),p=await te(i),m=await b("grant_sync",`${i}/v1/runtime/grants`,{headers:{Authorization:`Bearer ${p.access_token}`},signal:AbortSignal.timeout(1e4)});if(!m.ok)throw S("grant_sync",`${i}/v1/runtime/grants`,`directory grant sync failed: ${m.status}`);const s=await E("grant_sync",`${i}/v1/runtime/grants`,m);if(!Array.isArray(s.grants)||typeof s.synced_at!="string")throw new TypeError("invalid grant sync response");const g="hosted_endpoint"in s||"payment_setup_url"in s?{hosted_endpoint:W(s.hosted_endpoint??null),payment_setup_url:q(s.payment_setup_url??null),synced_at:s.synced_at}:void 0,P=s.synced_at,h=s.grants.map(l=>oe(l,d)),w=await v(async()=>{await F(h,P,i,I(s.teams));const l=await ie();return g&&l&&await L(g,l.id),l});f({level:"info",event:"daemon.grants.synced",fields:{grants:h.length,synced_at:s.synced_at}}),w?.late&&await se(w.late);try{await M(n)}catch(l){f({level:"error",event:"daemon.grants.on_sync_failed",error:l})}},"run");let u;const o=r(()=>{const d=c().catch(p=>{throw p instanceof x?f({level:"error",event:"daemon.grants.machine_revoked",error:p}):f({level:"error",event:"daemon.grants.sync_failed",error:p,fields:J(p)}),p}).finally(()=>{t===d&&(t=void 0)});return t=d,d},"start"),a=r((d={})=>t?d.fresh?(u??=t.catch(()=>{}).then(()=>(u=void 0,t??o())),u):t:o(),"sync");return _=a,a}r(xe,"createGrantSync");export{be as GRANT_SYNC_INTERVAL_S,x as MachineRevokedError,Z as assertion,xe as createGrantSync,ee as machineRevokedMessage,te as mintDirectoryToken,Se as requestGrantSync,y as runtimeClient,Ee as runtimeId};
@@ -18,16 +18,16 @@ export type PayerCall = (
18
18
  route: 'subscription' | 'key';
19
19
  sub: string;
20
20
  }
21
- /** A tool call over HTTP: the outbound token's `payer` claim (`app:<id>` when the app pays, else the person). Both are `bill`: the app's holder is invoiced for an app-paid call. */
21
+ /** A tool call over HTTP: the outbound token's `payer` claim, any principal. It is always `bill`; `sub` is used only when the claim is absent. */
22
22
  | {
23
23
  call: 'tool';
24
- tokenPayer: string;
24
+ tokenPayer: string | null | undefined;
25
25
  sub: string;
26
26
  }
27
- /** The payer of a node's model calls, for the start check: `app:<grantee>` when the grant is app-paid, else the person. */
27
+ /** The payer of a node's model calls, for the start check: the grant's principal payer. With none, the grantee's namespace owner when `sub` is in that namespace, else `sub`. */
28
28
  | {
29
29
  call: 'start';
30
- grantPayer: 'user' | 'app' | null | undefined;
30
+ grantPayer: string | null | undefined;
31
31
  sub: string;
32
32
  grantee: string;
33
33
  }) & {
@@ -1 +1 @@
1
- var t=Object.defineProperty;var r=(n,e)=>t(n,"name",{value:e,configurable:!0});function p(n){const e=i(n);return n.environmentPayer?{payer:n.environmentPayer,funding:e.funding}:e}r(p,"payerOf");function i(n){switch(n.call){case"model":return n.route==="endpoint"?{payer:n.grantee,funding:"endpoint"}:{payer:n.sub,funding:n.route};case"tool":return n.tokenPayer.startsWith("app:")?{payer:n.tokenPayer,funding:"bill"}:{payer:n.sub,funding:"bill"};case"start":return n.grantPayer==="app"?{payer:n.grantee,funding:"endpoint"}:{payer:n.sub,funding:"bill"}}}r(i,"fundedBy");export{p as payerOf};
1
+ var t=Object.defineProperty;var r=(n,e)=>t(n,"name",{value:e,configurable:!0});import{endpointPays as i}from"../grants/mirror.js";import{isNamespaceOwner as u}from"../grants/owner.js";function a(n){const e=o(n);return n.environmentPayer?{payer:n.environmentPayer,funding:e.funding}:e}r(a,"payerOf");function o(n){switch(n.call){case"model":return n.route==="endpoint"?{payer:n.grantee,funding:"endpoint"}:{payer:n.sub,funding:n.route};case"tool":return{payer:n.tokenPayer||n.sub,funding:"bill"};case"start":return n.grantPayer?{payer:n.grantPayer,funding:i({payer:n.grantPayer})?"endpoint":"bill"}:{payer:u(n.grantee,n.sub)?n.grantee:n.sub,funding:"bill"}}}r(o,"fundedBy");export{a as payerOf};
@@ -1 +1 @@
1
- var h=Object.defineProperty;var s=(e,r)=>h(e,"name",{value:r,configurable:!0});import{defaultModelLaddersConfig as b}from"../../types.js";import{MODEL_STRENGTHS as w,stripThinkingSuffix as u}from"../runtime/model-selection.js";import{modelTokenStrength as O}from"../runtime/launch.js";import{RunError as d}from"../runs/operations.js";import{grantRecord as x}from"../grants/mirror.js";const o=w;function p(e,r){const t=o.indexOf(r);return o.filter(n=>e.rungs[n]!==void 0).sort((n,i)=>Math.abs(o.indexOf(n)-t)-Math.abs(o.indexOf(i)-t)||o.indexOf(n)-o.indexOf(i)).map(n=>({strength:n,model:e.rungs[n]}))}s(p,"rungsByDistance");function l(e,r){const t=p(e,r)[0];if(t===void 0)throw new d(404,"model_unavailable","the app's inference endpoint declares no rung");return t}s(l,"rungAt");function g(e,r,t=!1){if(r===void 0||r==="")return l(e,"strong");const n=O(r)??void 0;if(n!==void 0)return l(e,n);const i=u(r),f=o.find(a=>e.rungs[a]===i);if(f!==void 0)return{strength:f,model:`${e.rungs[f]}${t?r.slice(i.length):""}`};if(t)throw new d(400,"substitution_refused",`model '${r}' is not one of this app's inference rungs`);const c=b(),m=[...Object.entries(c.anthropic),...Object.entries(c.openai)].find(([,a])=>u(a)===i);return l(e,m?.[0]??"strong")}s(g,"resolveAppRung");function $(e,r,t=!1){const n=g(e,r,t);if(t)return[n];const i=p(e,n.strength).filter(f=>f.strength!==n.strength);return[n,...i]}s($,"appCandidates");async function v(e,r,t=!1){const n=e?await x(e):null;if(n?.payer!=="app")return null;if(!n.inference_endpoint)throw new d(404,"model_unavailable",`${n.grantee} is app-paid but its grant carries no inference endpoint`);const i=g(n.inference_endpoint,r,t);return t?i:{...i,model:u(i.model)}}s(v,"appRungForGrant");export{$ as appCandidates,v as appRungForGrant,g as resolveAppRung,l as rungAt};
1
+ var h=Object.defineProperty;var s=(e,r)=>h(e,"name",{value:r,configurable:!0});import{defaultModelLaddersConfig as b}from"../../types.js";import{MODEL_STRENGTHS as w,stripThinkingSuffix as u}from"../runtime/model-selection.js";import{modelTokenStrength as O}from"../runtime/launch.js";import{RunError as d}from"../runs/operations.js";import{endpointPays as x,grantRecord as R}from"../grants/mirror.js";const o=w;function g(e,r){const t=o.indexOf(r);return o.filter(n=>e.rungs[n]!==void 0).sort((n,i)=>Math.abs(o.indexOf(n)-t)-Math.abs(o.indexOf(i)-t)||o.indexOf(n)-o.indexOf(i)).map(n=>({strength:n,model:e.rungs[n]}))}s(g,"rungsByDistance");function l(e,r){const t=g(e,r)[0];if(t===void 0)throw new d(404,"model_unavailable","the app's inference endpoint declares no rung");return t}s(l,"rungAt");function p(e,r,t=!1){if(r===void 0||r==="")return l(e,"strong");const n=O(r)??void 0;if(n!==void 0)return l(e,n);const i=u(r),f=o.find(a=>e.rungs[a]===i);if(f!==void 0)return{strength:f,model:`${e.rungs[f]}${t?r.slice(i.length):""}`};if(t)throw new d(400,"substitution_refused",`model '${r}' is not one of this app's inference rungs`);const c=b(),m=[...Object.entries(c.anthropic),...Object.entries(c.openai)].find(([,a])=>u(a)===i);return l(e,m?.[0]??"strong")}s(p,"resolveAppRung");function v(e,r,t=!1){const n=p(e,r,t);if(t)return[n];const i=g(e,n.strength).filter(f=>f.strength!==n.strength);return[n,...i]}s(v,"appCandidates");async function y(e,r,t=!1){const n=e?await R(e):null;if(!n||!x(n))return null;if(!n.inference_endpoint)throw new d(404,"model_unavailable",`${n.grantee} is app-paid but its grant carries no inference endpoint`);const i=p(n.inference_endpoint,r,t);return t?i:{...i,model:u(i.model)}}s(y,"appRungForGrant");export{v as appCandidates,y as appRungForGrant,p as resolveAppRung,l as rungAt};
@@ -1,7 +1,7 @@
1
1
  import { type ThinkingLevel } from '@earendil-works/pi-ai/compat';
2
2
  import { openModelRegistry } from '../runtime/model-registry.js';
3
3
  import { type ManagedProviderId, type SubscriptionCredential } from '../managed-providers.js';
4
- import type { GrantRecord, InferenceEndpoint } from '../grants/mirror.js';
4
+ import { type GrantRecord, type InferenceEndpoint } from '../grants/mirror.js';
5
5
  type WireContent = string | null | Array<{
6
6
  type: 'text';
7
7
  text: string;
@@ -70,7 +70,7 @@ export declare function usdEquivalent(model: {
70
70
  }, total: number): number | null;
71
71
  /** Who the call is made for: the caller's grant decides the payer (RT-RTE-12). A caller with no grant (the person) is user-paid. */
72
72
  export interface LlmCaller {
73
- payer: 'user' | 'app';
73
+ payer: string | null;
74
74
  sub: string;
75
75
  grantee: string;
76
76
  inference_endpoint: InferenceEndpoint | null;
@@ -1,3 +1,3 @@
1
- var Je=Object.defineProperty;var l=(e,t)=>Je(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 Me,parseModelSpec as Ve}from"../model-routes.js";import{openModelRegistry as Ye}from"../runtime/model-registry.js";import{getProviderLabel as Ze,isInvalidRefreshTokenError as Qe}from"../managed-providers.js";import{MAX_RATE_LIMIT_COOLDOWN_MS as Se,coolingUntilFor as $e,isManagedProvider as N,markSubscriptionRateLimited as et,markSubscriptionSuccess as tt,readSubscriptionPool as Ce,retryAfterMsFromHeaders as ge,retryAfterMsFromError as nt,refreshSubscriptionCredential as ot,subscriptionNeedsSuccessWrite as rt,vendorRateLimit as it,RefreshBusyError as at,RefreshTimeoutError as st}from"../subscription-state.js";import{describeRateLimitScope as Ee,modelCooldownFamily as dt,rateLimitHeaders as lt}from"../rate-limit-scope.js";import{RunError as i}from"../runs/operations.js";import{recognizeProviderError as we}from"../provider-error-recognition.js";import{isSafetyRefusal as ut}from"./refusal.js";import{findRefusal as ct,payerOf as Ie,refusalError as ft,refusedMark as mt,writeCharge as be}from"../ledger/index.js";import{storedApiKey as Oe}from"../auth-file.js";import{eligibleHostedEndpoint as pt,readHostedEndpoint as De}from"../grants/hosted-endpoint.js";import{parseProviderPayment as ht}from"../provider-failure.js";import{personIdAsync as _t}from"../canvas/person.js";import{getNode as Ne}from"../canvas/canvas.js";import{outboundToken as Fe}from"../providers/mint.js";import{discardFile as Le}from"../providers/token-cache.js";import{ProviderError as yt}from"../providers/errors.js";import{appCandidates as gt}from"./app-rungs.js";import{hostedRoute as wt,matchesFeatures as bt,ownerCandidates as vt}from"./owner-candidates.js";function kt(e){return typeof e=="string"||e===null||Array.isArray(e)&&e.every(t=>t&&typeof t=="object"&&(t.type==="text"&&typeof t.text=="string"||t.type==="image_url"&&typeof t.image_url?.url=="string"&&/^data:image\/(png|jpeg|gif|webp);base64,[A-Za-z0-9+/]+={0,2}$/.test(t.image_url.url)))}l(kt,"validContent");function Pe(e){return Array.isArray(e)?e.map(t=>{if(t.type==="text")return t;const[,o,s]=/^data:(image\/(?:png|jpeg|gif|webp));base64,(.*)$/.exec(t.image_url.url);return{type:"image",mimeType:o,data:s}}):e??""}l(Pe,"imageContent");function xt(e,t){const o=(e instanceof Error?e.message:String(e)).split("; stack=",1)[0],s=we({message:o}).kind;return s!=="connection"&&s!=="connection-only"?e:new i(503,"upstream_model_unavailable",o.slice(0,500),void 0,{served_model:t})}l(xt,"refreshFailure");async function Rt(e,t,o,s,d){if(o.expires>Date.now())return o.access;const S=e.getProvider(t)?.auth.oauth;if(!S)throw new i(503,"upstream_model_unavailable",`no OAuth refresh for ${t}`,void 0,{served_model:s});return(await ot(t,o.label,async(r,_)=>{const w=await S.refresh({type:"oauth",refresh:r,access:"",expires:0,..._?{clientId:_}:{}},d??new AbortController().signal).catch(R=>{throw xt(R,s)}),x=w.clientId;return{refresh:w.refresh,access:w.access,expires:w.expires,...typeof x=="string"&&x?{clientId:x}:{}}}).catch(r=>{throw r instanceof at||r instanceof st?new i(503,"upstream_model_unavailable",r.message,void 0,{served_model:s}):r})).access}l(Rt,"freshSubscriptionAccess");function on(e){if(!e||typeof e!="object"||Array.isArray(e))throw new i(400,"invalid_request","body must be an object");const t=e;if(!Array.isArray(t.messages)||!t.messages.every(o=>o&&typeof o=="object"&&["system","user","assistant","tool"].includes(o.role)&&kt(o.content)))throw new i(400,"invalid_request","messages must be chat messages","messages");if(t.messages.some(o=>["system","assistant"].includes(o.role)&&typeof o.content!="string"&&o.content!==null))throw new i(400,"invalid_request","system and assistant content must be text","messages");if(t.model!==void 0&&typeof t.model!="string")throw new i(400,"invalid_request","model must be a string","model");if(t.model_policy!==void 0&&!["exact","substitute"].includes(t.model_policy))throw new i(400,"invalid_request","invalid model_policy","model_policy");if(t.payer!==void 0&&!["user","app"].includes(t.payer))throw new i(400,"invalid_request","invalid payer","payer");if(t.reasoning_effort!==void 0&&!["minimal","low","medium","high","xhigh","max"].includes(t.reasoning_effort))throw new i(400,"invalid_request","invalid reasoning_effort","reasoning_effort");if(t.stream!==void 0&&typeof t.stream!="boolean")throw new i(400,"invalid_request","stream must be boolean","stream");if(t.tools!==void 0&&(!Array.isArray(t.tools)||!t.tools.every(o=>o?.type==="function"&&typeof o.function?.name=="string"&&o.function.name.length>0&&(o.function.description===void 0||typeof o.function.description=="string")&&(o.function.parameters===void 0||o.function.parameters!==null&&typeof o.function.parameters=="object"&&!Array.isArray(o.function.parameters)&&o.function.parameters.type==="object"))))throw new i(400,"invalid_request","invalid tools","tools");if(t.tool_choice!==void 0&&t.tool_choice!=="auto"&&t.tool_choice!=="none"&&t.tool_choice!=="required"&&(typeof t.tool_choice!="object"||t.tool_choice===null||t.tool_choice.type!=="function"||typeof t.tool_choice.function?.name!="string"))throw new i(400,"invalid_request","invalid tool_choice","tool_choice");if(t.messages.some(o=>o.role==="assistant"&&o.tool_calls!==void 0&&(!Array.isArray(o.tool_calls)||!o.tool_calls.every(s=>s&&typeof s.id=="string"&&typeof s.function?.name=="string"&&typeof s.function.arguments=="string"&&qt(s.function.arguments)))))throw new i(400,"invalid_request","invalid assistant tool_calls","messages");if(t.stop!==void 0&&!(typeof t.stop=="string"||Array.isArray(t.stop)&&t.stop.every(o=>typeof o=="string")))throw new i(400,"invalid_request","invalid stop","stop");if(t.seed!==void 0&&!Number.isSafeInteger(t.seed))throw new i(400,"invalid_request","invalid seed","seed");for(const[o,s]of[["temperature",t.temperature],["top_p",t.top_p],["max_tokens",t.max_tokens]])if(s!==void 0&&(typeof s!="number"||!Number.isFinite(s)||o==="temperature"&&(s<0||s>2)||o==="top_p"&&(s<0||s>1)||o==="max_tokens"&&(!Number.isSafeInteger(s)||s<1)))throw new i(400,"invalid_request",`invalid ${o}`,o);if(t.response_format!==void 0){const o=t.response_format;if(!o||typeof o!="object"||Array.isArray(o)||!["text","json_object","json_schema"].includes(o.type)||o.type==="json_schema"&&(typeof o.json_schema?.name!="string"||!o.json_schema.name||!o.json_schema.schema||typeof o.json_schema.schema!="object"||Array.isArray(o.json_schema.schema)))throw new i(400,"invalid_request","invalid response_format","response_format")}if(t.metadata!==void 0&&Buffer.byteLength(JSON.stringify(t.metadata)??"")>4096)throw new i(400,"invalid_request","metadata exceeds 4 KB","metadata");return t}l(on,"parseLlmRequest");function qt(e){try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)}catch{return!1}}l(qt,"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??""}]:Pe(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:Pe(r.content),timestamp:t}),s=o.findIndex(r=>r.role!=="system"),d=o.slice(0,s<0?o.length:s).map(r=>r.content),S=d.join(`
1
+ var Je=Object.defineProperty;var l=(e,t)=>Je(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 Me,parseModelSpec as Ve}from"../model-routes.js";import{openModelRegistry as Ye}from"../runtime/model-registry.js";import{getProviderLabel as Ze,isInvalidRefreshTokenError as Qe}from"../managed-providers.js";import{MAX_RATE_LIMIT_COOLDOWN_MS as Se,coolingUntilFor as $e,isManagedProvider as N,markSubscriptionRateLimited as et,markSubscriptionSuccess as tt,readSubscriptionPool as Ce,retryAfterMsFromHeaders as ge,retryAfterMsFromError as nt,refreshSubscriptionCredential as ot,subscriptionNeedsSuccessWrite as rt,vendorRateLimit as it,RefreshBusyError as at,RefreshTimeoutError as st}from"../subscription-state.js";import{describeRateLimitScope as Ee,modelCooldownFamily as dt,rateLimitHeaders as lt}from"../rate-limit-scope.js";import{RunError as i}from"../runs/operations.js";import{recognizeProviderError as we}from"../provider-error-recognition.js";import{isSafetyRefusal as ut}from"./refusal.js";import{findRefusal as ct,payerOf as Ie,refusalError as ft,refusedMark as mt,writeCharge as be}from"../ledger/index.js";import{storedApiKey as Oe}from"../auth-file.js";import{eligibleHostedEndpoint as pt,readHostedEndpoint as De}from"../grants/hosted-endpoint.js";import{parseProviderPayment as ht}from"../provider-failure.js";import{personIdAsync as _t}from"../canvas/person.js";import{getNode as Ne}from"../canvas/canvas.js";import{endpointPays as yt}from"../grants/mirror.js";import{outboundToken as Pe}from"../providers/mint.js";import{discardFile as Fe}from"../providers/token-cache.js";import{ProviderError as gt}from"../providers/errors.js";import{appCandidates as wt}from"./app-rungs.js";import{hostedRoute as bt,matchesFeatures as vt,ownerCandidates as kt}from"./owner-candidates.js";function xt(e){return typeof e=="string"||e===null||Array.isArray(e)&&e.every(t=>t&&typeof t=="object"&&(t.type==="text"&&typeof t.text=="string"||t.type==="image_url"&&typeof t.image_url?.url=="string"&&/^data:image\/(png|jpeg|gif|webp);base64,[A-Za-z0-9+/]+={0,2}$/.test(t.image_url.url)))}l(xt,"validContent");function Le(e){return Array.isArray(e)?e.map(t=>{if(t.type==="text")return t;const[,o,s]=/^data:(image\/(?:png|jpeg|gif|webp));base64,(.*)$/.exec(t.image_url.url);return{type:"image",mimeType:o,data:s}}):e??""}l(Le,"imageContent");function Rt(e,t){const o=(e instanceof Error?e.message:String(e)).split("; stack=",1)[0],s=we({message:o}).kind;return s!=="connection"&&s!=="connection-only"?e:new i(503,"upstream_model_unavailable",o.slice(0,500),void 0,{served_model:t})}l(Rt,"refreshFailure");async function qt(e,t,o,s,d){if(o.expires>Date.now())return o.access;const x=e.getProvider(t)?.auth.oauth;if(!x)throw new i(503,"upstream_model_unavailable",`no OAuth refresh for ${t}`,void 0,{served_model:s});return(await ot(t,o.label,async(r,_)=>{const w=await x.refresh({type:"oauth",refresh:r,access:"",expires:0,..._?{clientId:_}:{}},d??new AbortController().signal).catch(q=>{throw Rt(q,s)}),R=w.clientId;return{refresh:w.refresh,access:w.access,expires:w.expires,...typeof R=="string"&&R?{clientId:R}:{}}}).catch(r=>{throw r instanceof at||r instanceof st?new i(503,"upstream_model_unavailable",r.message,void 0,{served_model:s}):r})).access}l(qt,"freshSubscriptionAccess");function an(e){if(!e||typeof e!="object"||Array.isArray(e))throw new i(400,"invalid_request","body must be an object");const t=e;if(!Array.isArray(t.messages)||!t.messages.every(o=>o&&typeof o=="object"&&["system","user","assistant","tool"].includes(o.role)&&xt(o.content)))throw new i(400,"invalid_request","messages must be chat messages","messages");if(t.messages.some(o=>["system","assistant"].includes(o.role)&&typeof o.content!="string"&&o.content!==null))throw new i(400,"invalid_request","system and assistant content must be text","messages");if(t.model!==void 0&&typeof t.model!="string")throw new i(400,"invalid_request","model must be a string","model");if(t.model_policy!==void 0&&!["exact","substitute"].includes(t.model_policy))throw new i(400,"invalid_request","invalid model_policy","model_policy");if(t.payer!==void 0&&!["user","app"].includes(t.payer))throw new i(400,"invalid_request","invalid payer","payer");if(t.reasoning_effort!==void 0&&!["minimal","low","medium","high","xhigh","max"].includes(t.reasoning_effort))throw new i(400,"invalid_request","invalid reasoning_effort","reasoning_effort");if(t.stream!==void 0&&typeof t.stream!="boolean")throw new i(400,"invalid_request","stream must be boolean","stream");if(t.tools!==void 0&&(!Array.isArray(t.tools)||!t.tools.every(o=>o?.type==="function"&&typeof o.function?.name=="string"&&o.function.name.length>0&&(o.function.description===void 0||typeof o.function.description=="string")&&(o.function.parameters===void 0||o.function.parameters!==null&&typeof o.function.parameters=="object"&&!Array.isArray(o.function.parameters)&&o.function.parameters.type==="object"))))throw new i(400,"invalid_request","invalid tools","tools");if(t.tool_choice!==void 0&&t.tool_choice!=="auto"&&t.tool_choice!=="none"&&t.tool_choice!=="required"&&(typeof t.tool_choice!="object"||t.tool_choice===null||t.tool_choice.type!=="function"||typeof t.tool_choice.function?.name!="string"))throw new i(400,"invalid_request","invalid tool_choice","tool_choice");if(t.messages.some(o=>o.role==="assistant"&&o.tool_calls!==void 0&&(!Array.isArray(o.tool_calls)||!o.tool_calls.every(s=>s&&typeof s.id=="string"&&typeof s.function?.name=="string"&&typeof s.function.arguments=="string"&&At(s.function.arguments)))))throw new i(400,"invalid_request","invalid assistant tool_calls","messages");if(t.stop!==void 0&&!(typeof t.stop=="string"||Array.isArray(t.stop)&&t.stop.every(o=>typeof o=="string")))throw new i(400,"invalid_request","invalid stop","stop");if(t.seed!==void 0&&!Number.isSafeInteger(t.seed))throw new i(400,"invalid_request","invalid seed","seed");for(const[o,s]of[["temperature",t.temperature],["top_p",t.top_p],["max_tokens",t.max_tokens]])if(s!==void 0&&(typeof s!="number"||!Number.isFinite(s)||o==="temperature"&&(s<0||s>2)||o==="top_p"&&(s<0||s>1)||o==="max_tokens"&&(!Number.isSafeInteger(s)||s<1)))throw new i(400,"invalid_request",`invalid ${o}`,o);if(t.response_format!==void 0){const o=t.response_format;if(!o||typeof o!="object"||Array.isArray(o)||!["text","json_object","json_schema"].includes(o.type)||o.type==="json_schema"&&(typeof o.json_schema?.name!="string"||!o.json_schema.name||!o.json_schema.schema||typeof o.json_schema.schema!="object"||Array.isArray(o.json_schema.schema)))throw new i(400,"invalid_request","invalid response_format","response_format")}if(t.metadata!==void 0&&Buffer.byteLength(JSON.stringify(t.metadata)??"")>4096)throw new i(400,"invalid_request","metadata exceeds 4 KB","metadata");return t}l(an,"parseLlmRequest");function At(e){try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)}catch{return!1}}l(At,"isJsonObject");function jt(e){const t=Date.now(),o=e.messages.map(r=>r.role==="system"?{role:"system",content:r.content??"",timestamp:t}:r.role==="tool"?{role:"toolResult",toolCallId:r.tool_call_id??"",toolName:"",content:typeof r.content=="string"||r.content===null?[{type:"text",text:r.content??""}]:Le(r.content),isError:!1,timestamp:t}:r.role==="assistant"?{role:"assistant",content:[...r.content?[{type:"text",text:r.content}]:[],...(r.tool_calls??[]).map(_=>({type:"toolCall",id:_.id,name:_.function.name,arguments:JSON.parse(_.function.arguments)}))],api:"openai-completions",provider:"openai",model:e.model??"",usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:t}:{role:"user",content:Le(r.content),timestamp:t}),s=o.findIndex(r=>r.role!=="system"),d=o.slice(0,s<0?o.length:s).map(r=>r.content),x=d.join(`
2
2
 
3
- `),J=e.tools?.map(({function:r})=>({name:r.name,description:r.description??"",parameters:r.parameters??{type:"object",properties:{}}}));return{...S?{systemPrompt:S}:{},messages:o.slice(d.length),...J?{tools:J}:{}}}l(At,"contextOf");function jt(e){return ht(e?.payment)}l(jt,"paymentOf");function Mt(e,t){const o=e.find("anthropic",t);if(o)return o;const s=e.getAll().find(d=>d.provider==="anthropic"&&d.api==="anthropic-messages");return s?{...s,id:t,name:t}:void 0}l(Mt,"hostedModel");function St(e,t){const{input:o,output:s,cacheRead:d,cacheWrite:S}=e.cost;return o===0&&s===0&&d===0&&S===0?null:Number.isFinite(t)&&t>=0?t:null}l(St,"usdEquivalent");function $t(e,t){return e.compat?.allowedFallbackModels?.find(s=>s.provider===e.provider&&s.model===t)}l($t,"allowedFallback");function rn(e){return e?{payer:e.payer??"user",sub:e.sub,grantee:e.grantee,inference_endpoint:e.inference_endpoint??null}:void 0}l(rn,"llmCallerOf");function Te(e){return e instanceof yt?e.code==="server_error"?new i(503,"upstream_model_unavailable",e.message):new i(404,"model_unavailable",e.message):e}l(Te,"mintFailure");const Ct=/\bmodel is not supported when using Codex with a ChatGPT account\b/i;function Et(e,t,o){if(!(e!=="openai-codex"||t===void 0||!Ct.test(t)))return new i(404,"model_unavailable",t,void 0,{served_model:o})}l(Et,"codexAccountModelRejection");function It(e){return e.get("request-id")??e.get("x-request-id")}l(It,"vendorRequestId");async function an(e,t,o,s,d,S,J){const r=S?.payer==="app"?S:void 0;if(e.payer==="app"&&!r)throw new i(403,"payer_not_app","this grant is not app-paid");if(e.payer==="user"&&r)throw new i(400,"invalid_request","this grant is app-paid; payer cannot be user","payer");if(r&&!r.inference_endpoint)throw new i(404,"model_unavailable",`${r.grantee} is app-paid but its grant carries no inference endpoint`);const _=r?.inference_endpoint??void 0,w=d===void 0?null:r?.sub??d.sub??await _t(),x=await Ye();let R;_?(R=gt(_,e.model,e.model_policy==="exact").flatMap((y,b)=>{const $=Ve(y.model);return $?[{routeId:"app",credentialSource:"app",family:"app",strength:y.strength,...$,rank:b}]:[]}),R=R.filter(y=>bt(x,e,y))):R=await vt(x,e,s);const ie=!_&&d!==void 0&&w!==null?await pt():null,ae=ie===null?void 0:wt(e,R,ie),Ue=ae?ie:null;ae&&(R=[...R,ae]);const Ke=_?new Set:Xe(),ve=l(async()=>new i(429,"all_routes_exhausted","no available way to pay for this call",void 0,{payment:{reason:"nothing_left",message:"No available way to pay for this call",pay_url:(await De())?.payment_setup_url??null,reset_at:null}}),"nothingLeft");if(R.length===0)throw e.model_policy==="exact"?new i(400,"substitution_refused","no eligible model route is configured"):_?new i(404,"model_unavailable","no eligible model route is configured"):await ve();const H=`chatcmpl-${He()}`;let F=1/0,L=1/0,se,v,de,le;const G=new Set,ue=l(async()=>J??(d?.node?(await Ne(d.node))?.caused_by??null:null)??(d?.run?(await Ne(d.run))?.caused_by??null:null),"causeOf");for(const y of R){const b=y.credentialSource==="hosted";if(!r&&!b&&!(await Ge(y,x)).authenticated){if(y.credentialSource!==Me&&N(y.providerId)){const k=await Ce(y.providerId);k.length>0&&k.every(q=>q.authFailure)&&G.add(y.providerId)}continue}const $=b?Mt(x,y.modelId):x.find(y.providerId,y.modelId);if(!$)continue;const z=b?Ue.base_url:void 0,u=_?{...$,baseUrl:`${_.base_url}/${$.provider}`}:z?{...$,baseUrl:`${z}/anthropic`,compat:{...$.compat,allowedFallbackModels:void 0}}:$,h=y.providerId,V=y.credentialSource===Me&&N(h),ce=!r&&!b&&!V&&N(h)?await Ce(h):[],P=ce.filter(k=>!k.authFailure),ke=P.filter(k=>$e(k,u.id)<=Date.now()),T=V?await Oe(h):Ke.has(h)?void 0:ce.length?await Oe(h):void 0;if(V&&T===void 0)continue;if(ce.length>0&&P.length===0&&T===void 0){N(h)&&G.add(h);continue}if(P.length&&!ke.length&&T===void 0){const k=Math.min(...P.map(c=>$e(c,u.id)));k<F&&(F=k,de=`${u.provider}/${u.id}`);const q=dt(u.id);for(const c of P){const C=q!==void 0&&(c.modelCooldowns?.[q]??0)>Date.now()?c.vendorLimits?.[q]:c.rateLimitedUntil>Date.now()?c.vendorLimits?.account:void 0;C!==void 0&&(C.vendorReset!==void 0&&C.vendorReset>Date.now()&&(L=Math.min(L,C.vendorReset)),v??={provider:h,model:C.model,account:c.label,observation:C.observation})}continue}const xe=r||b?[void 0,void 0]:V?["key"]:P.length||T!==void 0?[...ke,...T!==void 0?["key"]:[]]:[void 0];let Re=!1;for(const[k,q]of xe.entries()){if(Re&&q!=="key")continue;const c=q==="key"?void 0:q,C=q==="key",Y=Date.now();let qe=c?.access;if(c&&c.expires<=Date.now()&&N(h))try{qe=await Rt(x,h,c,`${u.provider}/${u.id}`,t)}catch(n){if(!Qe(n))throw n;se??=n;continue}const We=At(e),U=c||r||b||C?void 0:await x.getApiKeyAndHeaders(u);if(U&&!U.ok)continue;const f=`${u.provider}/${u.id}`,K=e.model??f,fe=d?.environmentPayer,A=b?w===null?null:{payer:fe??w,funding:"endpoint"}:r?Ie({call:"model",route:"endpoint",grantee:r.grantee,environmentPayer:fe}):w===null?null:Ie({call:"model",route:c?"subscription":"key",sub:w,environmentPayer:fe});if(d!==void 0&&A!==null){const n=await ct({scope:"call",payer:A.payer,funding:A.funding,sub:w,grantee:d.grantee,provider:h});if(n!==null){if(await be({request:d.request??H,kind:"model",what:f,usd:null,payer:A.payer,funding:A.funding,sub:w,grantee:d.grantee,node:d.node??null,run:d.run??null,provider:h,causedBy:await ue(),refused:mt(n)}),le??=n,q!=="key"&&xe.includes("key")){Re=!0;continue}break}}let O;if(r&&_)try{O=await Fe({audience:_.base_url,sub:r.sub,grantee:r.grantee,initiating_app:r.grantee,scope:["crtr:llm"]},{signal:t})}catch(n){throw Te(n)}if(z)try{O=await Fe({audience:z,sub:w,grantee:d.grantee,initiating_app:d.grantee,scope:["crtr:llm"]},{signal:t})}catch(n){throw Te(n)}let W=null,Ae=!1,g,X,Z,E=!1,j,Q=null,M=3e4,B;const me=[],pe=[],ee=[];let a,D;const te=l((n,m=null)=>({id:H,object:"chat.completion.chunk",created:Math.floor(Y/1e3),model:f,served_model:f,requested_model:K,substituted:K!==f&&!/^([^/]+)\/(ultra|strong|medium|light)$/.test(K),choices:[{index:0,delta:n,finish_reason:m}]}),"chunk"),ne=l(n=>{me.push(n),o?.(n)},"emit"),Be=ze(u,We,{apiKey:O?.access_token??qe??(C?T:void 0)??(U?.ok?U.apiKey:void 0),...U?.ok?{headers:U.headers}:{},signal:t,reasoning:e.reasoning_effort??y.thinkingLevel,...e.temperature!==void 0?{temperature:e.temperature}:{},...e.max_tokens!==void 0?{maxTokens:e.max_tokens}:{},...e.top_p!==void 0?{samplingParams:{top_p:e.top_p}}:{},...e.tool_choice==="none"?{toolChoice:"none"}:{},onPayload:l(n=>{if(!n||typeof n!="object")return;const m=e.tool_choice,p=m==="required"?u.api==="anthropic-messages"?{type:"any"}:"required":typeof m=="object"&&m!==null?u.api==="anthropic-messages"?{type:"tool",name:m.function.name}:m:void 0;return{...n,...p?{tool_choice:p}:{},...e.stop!==void 0?{[u.api==="anthropic-messages"?"stop_sequences":"stop"]:typeof e.stop=="string"?[e.stop]:e.stop}:{},...e.seed!==void 0?{seed:e.seed}:{},...e.response_format!==void 0?{response_format:e.response_format}:{}}},"onPayload"),fetch:l(async(n,m)=>{const p=await fetch(n,m);if(j=p.status,Q=It(p.headers)??Q,b){if(W=p.headers.get("crtr-charge-id")?.trim()||null,p.ok&&!W)throw Ae=!0,await p.body?.cancel(),new Error("The hosted endpoint omitted Crtr-Charge-Id; the call may already have been charged. Do not automatically replay it.");return p.status===402&&(Z=jt(await p.clone().json().catch(()=>{}))),p}return p.status===429&&(E=!0,B=p.headers,M=ge(p.headers)??15e3),p},"fetch"),onProviderStreamEvent:l(n=>{b&&n!==null&&typeof n=="object"&&"type"in n&&n.type==="message_stop"&&"crtr_charge"in n&&(g=n.crtr_charge)},"onProviderStreamEvent"),onResponse:l(n=>{!b&&n.status===429&&(E=!0,B=n.headers,M=ge(n.headers)??15e3)},"onResponse")});try{for await(const n of Be)n.type==="text_delta"&&(pe.push(n.delta),ne(te({content:n.delta}))),n.type==="thinking_delta"&&(ee.push(n.delta),ne(te({reasoning_content:n.delta}))),n.type==="done"&&(a=n.message),n.type==="error"&&(a=n.error)}catch(n){const m=nt(n);B===void 0&&n&&typeof n=="object"&&"headers"in n&&Object.keys(lt(n.headers)).length&&(B=n.headers);const p=we({status:n&&typeof n=="object"&&"status"in n?n.status:void 0,message:n instanceof Error?n.message:String(n)});if(r||b)D=n;else{if(!E&&p.kind!=="rate-limit")throw me.length?new i(503,"upstream_model_unavailable",n instanceof Error?n.message:String(n),void 0,{served_model:f}):n;E=!0,M=m??M}}if(b){if(Ae)throw new i(502,"upstream_refused","The hosted endpoint omitted Crtr-Charge-Id; the call may already have been charged. Do not automatically replay it.",void 0,{served_model:f});if(j===402&&Z)throw new i(402,"payment_refused",Z.message,void 0,{payment:Z,served_model:f});if(j===401){if(O&&Le(O.key),k===0)continue;throw new i(404,"model_unavailable",`${z} refuses this runtime's tokens`,void 0,{served_model:f})}if(D!==void 0||j!==void 0&&j>=400||a?.stopReason==="error"||a?.stopReason==="aborted"){const m=D instanceof Error?D.message:a?.errorMessage??`the inference endpoint answered ${j??"with an error"}`;throw j===403?new i(502,"upstream_refused",m,void 0,{served_model:f}):new i(503,"upstream_model_unavailable",m,void 0,{served_model:f})}if(g===null||typeof g!="object"||!("id"in g)||g.id!==W||!("served_model"in g)||typeof g.served_model!="string"||!g.served_model.trim()||!("list_usd"in g)||typeof g.list_usd!="number"||!Number.isFinite(g.list_usd)||g.list_usd<0||Number(g.list_usd.toFixed(6))!==g.list_usd)throw new i(502,"upstream_refused","The hosted endpoint returned missing or invalid final charge accounting; output and cost may already exist. Do not automatically replay this call.",void 0,{served_model:f,charge_id:W});X={id:W,served_model:g.served_model,list_usd:g.list_usd}}if(r){if(j===401){if(O&&Le(O.key),k===0)continue;throw new i(404,"model_unavailable",`${_.base_url} refuses this runtime's tokens`,void 0,{served_model:f})}if(E&&ge(B)===void 0)throw new i(503,"upstream_model_unavailable",`${f} was rate-limited without a retry-after`,void 0,{served_model:f});if(!E&&(D!==void 0||j!==void 0&&j>=500))throw new i(503,"upstream_model_unavailable",D instanceof Error?D.message:a?.errorMessage??"inference endpoint failed",void 0,{served_model:f})}if(!E&&a?.stopReason==="error"&&we({message:a.errorMessage}).kind==="rate-limit"&&(E=!0,M=15e3),E){const n=it(B,u.id,M),{observation:m,vendorReset:p}=n;if(M=n.retryMs,v={provider:h,model:u.id,...c?{account:c.label}:{},observation:m},console.error(`[llm] 429 from ${f}${c?` account "${c.label}"`:""}: scope=${Ee(m.scope)} retry_after_ms=${M} headers=${JSON.stringify(m.headers)}`),c&&N(h)&&await et(h,c.label,M,Y,Date.now(),m.scope,{model:u.id,...p!==void 0?{vendorReset:p}:{},observation:m}),p!==void 0&&(L=Math.min(L,p)),Date.now()+Math.min(M,Se)<F&&(F=Date.now()+Math.min(M,Se),de=f),pe.length||ee.length)throw new i(503,"service_unavailable","vendor rate limit after output began",void 0,{served_model:f});if(r)break;continue}const oe=ut(a);if(j===400&&e.tool_choice!==void 0&&e.tool_choice!=="auto"&&e.tool_choice!=="none"&&/\btool[_ ]choice\b/i.test(a?.errorMessage??"")&&/not supported|does not support|unsupported|cannot|must be auto/i.test(a?.errorMessage??""))throw new i(400,"invalid_request",a.errorMessage,"tool_choice",{served_model:f});if(a?.stopReason==="error"){const n=Et(u.provider,a.errorMessage,f);if(n)throw n}if(!a||a.stopReason==="error"&&!oe||a.stopReason==="aborted")throw new i(503,"upstream_model_unavailable",a?.errorMessage??"model request failed",void 0,{served_model:f});c&&N(h)&&rt(c,u.id)&&await tt(h,c.label,Y,u.id);const he=a.content.filter(n=>n.type==="toolCall").map(n=>({id:n.id,type:"function",function:{name:n.name,arguments:JSON.stringify(n.arguments)}})),_e=oe?"content_filter":a.stopReason==="toolUse"?"tool_calls":a.stopReason==="length"?"length":"stop",ye=a.responseModel?$t(u,a.responseModel):void 0,I=X?`${u.provider}/${X.served_model}`:ye?`${u.provider}/${ye.model}`:f,re={prompt_tokens:a.usage.input,completion_tokens:a.usage.output,total_tokens:a.usage.totalTokens,cache_read_tokens:a.usage.cacheRead,cache_write_tokens:a.usage.cacheWrite,usd_equivalent:X?X.list_usd:St(ye??u,a.usage.cost.total),served_model:I};b?d!==void 0&&A!==null&&await be({id:W,request:d.request??H,kind:"model",what:I,units:{input:a.usage.input,output:a.usage.output,cache_read:a.usage.cacheRead,cache_write:a.usage.cacheWrite},usd:re.usd_equivalent,payer:A.payer,funding:A.funding,sub:w,grantee:d.grantee,node:d.node??null,run:d.run??null,provider:h,causedBy:await ue(),vendorRef:Q}):d!==void 0&&A!==null&&await be({request:d.request??H,kind:"model",what:I,units:{input:a.usage.input,output:a.usage.output,cache_read:a.usage.cacheRead,cache_write:a.usage.cacheWrite},usd:re.usd_equivalent,payer:A.payer,funding:A.funding,sub:w,grantee:d.grantee,node:d.node??null,run:d.run??null,provider:h,causedBy:await ue(),vendorRef:Q});const je={id:H,object:"chat.completion",created:Math.floor(Y/1e3),model:I,served_model:I,requested_model:K,substituted:K!==I&&!/^([^/]+)\/(ultra|strong|medium|light)$/.test(K),choices:[{index:0,message:{role:"assistant",content:pe.join("")||null,...ee.length?{reasoning_content:ee.join("")}:{},...he.length?{tool_calls:he}:{},...oe?{refusal:a.errorMessage??"Content filtered"}:{}},finish_reason:_e}],usage:re,...e.metadata!==void 0?{metadata:e.metadata}:{}};for(const[n,m]of he.entries())ne(te({tool_calls:[{index:n,...m}]}));return ne({...te({},_e),model:I,served_model:I,substituted:je.substituted,...oe?{choices:[{index:0,delta:{},finish_reason:_e,message:{refusal:a.errorMessage??"Content filtered"}}]}:{},usage:re}),{completion:je,chunks:me}}}throw le!==void 0?ft(le):F!==1/0?new i(429,"all_routes_exhausted","all eligible model routes are rate-limited",void 0,{payment:{reason:"nothing_left",message:"Every connected subscription and key is rate-limited or used up right now.",pay_url:(await De())?.payment_setup_url??null,reset_at:L===1/0?null:new Date(L).toISOString()},retry_after_s:Math.max(1,Math.ceil((F-Date.now())/1e3)),served_model:v?`${v.provider}/${v.model}`:de,...v?{rate_limit:{provider:v.provider,model:v.model,...v.account?{account:v.account}:{},scope:Ee(v.observation.scope),...v.observation.claim?{claim:v.observation.claim}:{},headers:v.observation.headers}}:{}},void 0,!0):se!==void 0?se:e.model_policy==="exact"?new i(400,"substitution_refused",G.size>0?`your ${[...G].map(Ze).join(" and ")} sign-in has expired; sign in again`:"the requested model is unavailable"):_?new i(404,"model_unavailable","no usable model route is available"):await ve()}l(an,"runLlm");export{Rt as freshSubscriptionAccess,rn as llmCallerOf,on as parseLlmRequest,an as runLlm,St as usdEquivalent};
3
+ `),J=e.tools?.map(({function:r})=>({name:r.name,description:r.description??"",parameters:r.parameters??{type:"object",properties:{}}}));return{...x?{systemPrompt:x}:{},messages:o.slice(d.length),...J?{tools:J}:{}}}l(jt,"contextOf");function Mt(e){return ht(e?.payment)}l(Mt,"paymentOf");function St(e,t){const o=e.find("anthropic",t);if(o)return o;const s=e.getAll().find(d=>d.provider==="anthropic"&&d.api==="anthropic-messages");return s?{...s,id:t,name:t}:void 0}l(St,"hostedModel");function $t(e,t){const{input:o,output:s,cacheRead:d,cacheWrite:x}=e.cost;return o===0&&s===0&&d===0&&x===0?null:Number.isFinite(t)&&t>=0?t:null}l($t,"usdEquivalent");function Ct(e,t){return e.compat?.allowedFallbackModels?.find(s=>s.provider===e.provider&&s.model===t)}l(Ct,"allowedFallback");function sn(e){return e?{payer:e.payer,sub:e.sub,grantee:e.grantee,inference_endpoint:e.inference_endpoint??null}:void 0}l(sn,"llmCallerOf");function Te(e){return e instanceof gt?e.code==="server_error"?new i(503,"upstream_model_unavailable",e.message):new i(404,"model_unavailable",e.message):e}l(Te,"mintFailure");const Et=/\bmodel is not supported when using Codex with a ChatGPT account\b/i;function It(e,t,o){if(!(e!=="openai-codex"||t===void 0||!Et.test(t)))return new i(404,"model_unavailable",t,void 0,{served_model:o})}l(It,"codexAccountModelRejection");function Ot(e){return e.get("request-id")??e.get("x-request-id")}l(Ot,"vendorRequestId");async function dn(e,t,o,s,d,x,J){const r=x&&yt(x)?x:void 0;if(e.payer==="app"&&!r)throw new i(403,"payer_not_app","this grant is not app-paid");if(e.payer==="user"&&r)throw new i(400,"invalid_request","this grant is app-paid; payer cannot be user","payer");if(r&&!r.inference_endpoint)throw new i(404,"model_unavailable",`${r.grantee} is app-paid but its grant carries no inference endpoint`);const _=r?.inference_endpoint??void 0,w=d===void 0?null:r?.sub??d.sub??await _t(),R=await Ye();let q;_?(q=wt(_,e.model,e.model_policy==="exact").flatMap((y,b)=>{const $=Ve(y.model);return $?[{routeId:"app",credentialSource:"app",family:"app",strength:y.strength,...$,rank:b}]:[]}),q=q.filter(y=>vt(R,e,y))):q=await kt(R,e,s);const ie=!_&&d!==void 0&&w!==null?await pt():null,ae=ie===null?void 0:bt(e,q,ie),Ue=ae?ie:null;ae&&(q=[...q,ae]);const Ke=_?new Set:Xe(),ve=l(async()=>new i(429,"all_routes_exhausted","no available way to pay for this call",void 0,{payment:{reason:"nothing_left",message:"No available way to pay for this call",pay_url:(await De())?.payment_setup_url??null,reset_at:null}}),"nothingLeft");if(q.length===0)throw e.model_policy==="exact"?new i(400,"substitution_refused","no eligible model route is configured"):_?new i(404,"model_unavailable","no eligible model route is configured"):await ve();const H=`chatcmpl-${He()}`;let P=1/0,F=1/0,se,v,de,le;const G=new Set,ue=l(async()=>J??(d?.node?(await Ne(d.node))?.caused_by??null:null)??(d?.run?(await Ne(d.run))?.caused_by??null:null),"causeOf");for(const y of q){const b=y.credentialSource==="hosted";if(!r&&!b&&!(await Ge(y,R)).authenticated){if(y.credentialSource!==Me&&N(y.providerId)){const k=await Ce(y.providerId);k.length>0&&k.every(A=>A.authFailure)&&G.add(y.providerId)}continue}const $=b?St(R,y.modelId):R.find(y.providerId,y.modelId);if(!$)continue;const z=b?Ue.base_url:void 0,u=_?{...$,baseUrl:`${_.base_url}/${$.provider}`}:z?{...$,baseUrl:`${z}/anthropic`,compat:{...$.compat,allowedFallbackModels:void 0}}:$,h=y.providerId,V=y.credentialSource===Me&&N(h),ce=!r&&!b&&!V&&N(h)?await Ce(h):[],L=ce.filter(k=>!k.authFailure),ke=L.filter(k=>$e(k,u.id)<=Date.now()),T=V?await Oe(h):Ke.has(h)?void 0:ce.length?await Oe(h):void 0;if(V&&T===void 0)continue;if(ce.length>0&&L.length===0&&T===void 0){N(h)&&G.add(h);continue}if(L.length&&!ke.length&&T===void 0){const k=Math.min(...L.map(c=>$e(c,u.id)));k<P&&(P=k,de=`${u.provider}/${u.id}`);const A=dt(u.id);for(const c of L){const C=A!==void 0&&(c.modelCooldowns?.[A]??0)>Date.now()?c.vendorLimits?.[A]:c.rateLimitedUntil>Date.now()?c.vendorLimits?.account:void 0;C!==void 0&&(C.vendorReset!==void 0&&C.vendorReset>Date.now()&&(F=Math.min(F,C.vendorReset)),v??={provider:h,model:C.model,account:c.label,observation:C.observation})}continue}const xe=r||b?[void 0,void 0]:V?["key"]:L.length||T!==void 0?[...ke,...T!==void 0?["key"]:[]]:[void 0];let Re=!1;for(const[k,A]of xe.entries()){if(Re&&A!=="key")continue;const c=A==="key"?void 0:A,C=A==="key",Y=Date.now();let qe=c?.access;if(c&&c.expires<=Date.now()&&N(h))try{qe=await qt(R,h,c,`${u.provider}/${u.id}`,t)}catch(n){if(!Qe(n))throw n;se??=n;continue}const We=jt(e),U=c||r||b||C?void 0:await R.getApiKeyAndHeaders(u);if(U&&!U.ok)continue;const f=`${u.provider}/${u.id}`,K=e.model??f,fe=d?.environmentPayer,j=b?w===null?null:{payer:fe??w,funding:"endpoint"}:r?Ie({call:"model",route:"endpoint",grantee:r.grantee,environmentPayer:fe}):w===null?null:Ie({call:"model",route:c?"subscription":"key",sub:w,environmentPayer:fe});if(d!==void 0&&j!==null){const n=await ct({scope:"call",payer:j.payer,funding:j.funding,sub:w,grantee:d.grantee,provider:h});if(n!==null){if(await be({request:d.request??H,kind:"model",what:f,usd:null,payer:j.payer,funding:j.funding,sub:w,grantee:d.grantee,node:d.node??null,run:d.run??null,provider:h,causedBy:await ue(),refused:mt(n)}),le??=n,A!=="key"&&xe.includes("key")){Re=!0;continue}break}}let O;if(r&&_)try{O=await Pe({audience:_.base_url,sub:r.sub,grantee:r.grantee,initiating_app:r.grantee,scope:["crtr:llm"]},{signal:t})}catch(n){throw Te(n)}if(z)try{O=await Pe({audience:z,sub:w,grantee:d.grantee,initiating_app:d.grantee,scope:["crtr:llm"]},{signal:t})}catch(n){throw Te(n)}let W=null,Ae=!1,g,X,Z,E=!1,M,Q=null,S=3e4,B;const me=[],pe=[],ee=[];let a,D;const te=l((n,m=null)=>({id:H,object:"chat.completion.chunk",created:Math.floor(Y/1e3),model:f,served_model:f,requested_model:K,substituted:K!==f&&!/^([^/]+)\/(ultra|strong|medium|light)$/.test(K),choices:[{index:0,delta:n,finish_reason:m}]}),"chunk"),ne=l(n=>{me.push(n),o?.(n)},"emit"),Be=ze(u,We,{apiKey:O?.access_token??qe??(C?T:void 0)??(U?.ok?U.apiKey:void 0),...U?.ok?{headers:U.headers}:{},signal:t,reasoning:e.reasoning_effort??y.thinkingLevel,...e.temperature!==void 0?{temperature:e.temperature}:{},...e.max_tokens!==void 0?{maxTokens:e.max_tokens}:{},...e.top_p!==void 0?{samplingParams:{top_p:e.top_p}}:{},...e.tool_choice==="none"?{toolChoice:"none"}:{},onPayload:l(n=>{if(!n||typeof n!="object")return;const m=e.tool_choice,p=m==="required"?u.api==="anthropic-messages"?{type:"any"}:"required":typeof m=="object"&&m!==null?u.api==="anthropic-messages"?{type:"tool",name:m.function.name}:m:void 0;return{...n,...p?{tool_choice:p}:{},...e.stop!==void 0?{[u.api==="anthropic-messages"?"stop_sequences":"stop"]:typeof e.stop=="string"?[e.stop]:e.stop}:{},...e.seed!==void 0?{seed:e.seed}:{},...e.response_format!==void 0?{response_format:e.response_format}:{}}},"onPayload"),fetch:l(async(n,m)=>{const p=await fetch(n,m);if(M=p.status,Q=Ot(p.headers)??Q,b){if(W=p.headers.get("crtr-charge-id")?.trim()||null,p.ok&&!W)throw Ae=!0,await p.body?.cancel(),new Error("The hosted endpoint omitted Crtr-Charge-Id; the call may already have been charged. Do not automatically replay it.");return p.status===402&&(Z=Mt(await p.clone().json().catch(()=>{}))),p}return p.status===429&&(E=!0,B=p.headers,S=ge(p.headers)??15e3),p},"fetch"),onProviderStreamEvent:l(n=>{b&&n!==null&&typeof n=="object"&&"type"in n&&n.type==="message_stop"&&"crtr_charge"in n&&(g=n.crtr_charge)},"onProviderStreamEvent"),onResponse:l(n=>{!b&&n.status===429&&(E=!0,B=n.headers,S=ge(n.headers)??15e3)},"onResponse")});try{for await(const n of Be)n.type==="text_delta"&&(pe.push(n.delta),ne(te({content:n.delta}))),n.type==="thinking_delta"&&(ee.push(n.delta),ne(te({reasoning_content:n.delta}))),n.type==="done"&&(a=n.message),n.type==="error"&&(a=n.error)}catch(n){const m=nt(n);B===void 0&&n&&typeof n=="object"&&"headers"in n&&Object.keys(lt(n.headers)).length&&(B=n.headers);const p=we({status:n&&typeof n=="object"&&"status"in n?n.status:void 0,message:n instanceof Error?n.message:String(n)});if(r||b)D=n;else{if(!E&&p.kind!=="rate-limit")throw me.length?new i(503,"upstream_model_unavailable",n instanceof Error?n.message:String(n),void 0,{served_model:f}):n;E=!0,S=m??S}}if(b){if(Ae)throw new i(502,"upstream_refused","The hosted endpoint omitted Crtr-Charge-Id; the call may already have been charged. Do not automatically replay it.",void 0,{served_model:f});if(M===402&&Z)throw new i(402,"payment_refused",Z.message,void 0,{payment:Z,served_model:f});if(M===401){if(O&&Fe(O.key),k===0)continue;throw new i(404,"model_unavailable",`${z} refuses this runtime's tokens`,void 0,{served_model:f})}if(D!==void 0||M!==void 0&&M>=400||a?.stopReason==="error"||a?.stopReason==="aborted"){const m=D instanceof Error?D.message:a?.errorMessage??`the inference endpoint answered ${M??"with an error"}`;throw M===403?new i(502,"upstream_refused",m,void 0,{served_model:f}):new i(503,"upstream_model_unavailable",m,void 0,{served_model:f})}if(g===null||typeof g!="object"||!("id"in g)||g.id!==W||!("served_model"in g)||typeof g.served_model!="string"||!g.served_model.trim()||!("list_usd"in g)||typeof g.list_usd!="number"||!Number.isFinite(g.list_usd)||g.list_usd<0||Number(g.list_usd.toFixed(6))!==g.list_usd)throw new i(502,"upstream_refused","The hosted endpoint returned missing or invalid final charge accounting; output and cost may already exist. Do not automatically replay this call.",void 0,{served_model:f,charge_id:W});X={id:W,served_model:g.served_model,list_usd:g.list_usd}}if(r){if(M===401){if(O&&Fe(O.key),k===0)continue;throw new i(404,"model_unavailable",`${_.base_url} refuses this runtime's tokens`,void 0,{served_model:f})}if(E&&ge(B)===void 0)throw new i(503,"upstream_model_unavailable",`${f} was rate-limited without a retry-after`,void 0,{served_model:f});if(!E&&(D!==void 0||M!==void 0&&M>=500))throw new i(503,"upstream_model_unavailable",D instanceof Error?D.message:a?.errorMessage??"inference endpoint failed",void 0,{served_model:f})}if(!E&&a?.stopReason==="error"&&we({message:a.errorMessage}).kind==="rate-limit"&&(E=!0,S=15e3),E){const n=it(B,u.id,S),{observation:m,vendorReset:p}=n;if(S=n.retryMs,v={provider:h,model:u.id,...c?{account:c.label}:{},observation:m},console.error(`[llm] 429 from ${f}${c?` account "${c.label}"`:""}: scope=${Ee(m.scope)} retry_after_ms=${S} headers=${JSON.stringify(m.headers)}`),c&&N(h)&&await et(h,c.label,S,Y,Date.now(),m.scope,{model:u.id,...p!==void 0?{vendorReset:p}:{},observation:m}),p!==void 0&&(F=Math.min(F,p)),Date.now()+Math.min(S,Se)<P&&(P=Date.now()+Math.min(S,Se),de=f),pe.length||ee.length)throw new i(503,"service_unavailable","vendor rate limit after output began",void 0,{served_model:f});if(r)break;continue}const oe=ut(a);if(M===400&&e.tool_choice!==void 0&&e.tool_choice!=="auto"&&e.tool_choice!=="none"&&/\btool[_ ]choice\b/i.test(a?.errorMessage??"")&&/not supported|does not support|unsupported|cannot|must be auto/i.test(a?.errorMessage??""))throw new i(400,"invalid_request",a.errorMessage,"tool_choice",{served_model:f});if(a?.stopReason==="error"){const n=It(u.provider,a.errorMessage,f);if(n)throw n}if(!a||a.stopReason==="error"&&!oe||a.stopReason==="aborted")throw new i(503,"upstream_model_unavailable",a?.errorMessage??"model request failed",void 0,{served_model:f});c&&N(h)&&rt(c,u.id)&&await tt(h,c.label,Y,u.id);const he=a.content.filter(n=>n.type==="toolCall").map(n=>({id:n.id,type:"function",function:{name:n.name,arguments:JSON.stringify(n.arguments)}})),_e=oe?"content_filter":a.stopReason==="toolUse"?"tool_calls":a.stopReason==="length"?"length":"stop",ye=a.responseModel?Ct(u,a.responseModel):void 0,I=X?`${u.provider}/${X.served_model}`:ye?`${u.provider}/${ye.model}`:f,re={prompt_tokens:a.usage.input,completion_tokens:a.usage.output,total_tokens:a.usage.totalTokens,cache_read_tokens:a.usage.cacheRead,cache_write_tokens:a.usage.cacheWrite,usd_equivalent:X?X.list_usd:$t(ye??u,a.usage.cost.total),served_model:I};b?d!==void 0&&j!==null&&await be({id:W,request:d.request??H,kind:"model",what:I,units:{input:a.usage.input,output:a.usage.output,cache_read:a.usage.cacheRead,cache_write:a.usage.cacheWrite},usd:re.usd_equivalent,payer:j.payer,funding:j.funding,sub:w,grantee:d.grantee,node:d.node??null,run:d.run??null,provider:h,causedBy:await ue(),vendorRef:Q}):d!==void 0&&j!==null&&await be({request:d.request??H,kind:"model",what:I,units:{input:a.usage.input,output:a.usage.output,cache_read:a.usage.cacheRead,cache_write:a.usage.cacheWrite},usd:re.usd_equivalent,payer:j.payer,funding:j.funding,sub:w,grantee:d.grantee,node:d.node??null,run:d.run??null,provider:h,causedBy:await ue(),vendorRef:Q});const je={id:H,object:"chat.completion",created:Math.floor(Y/1e3),model:I,served_model:I,requested_model:K,substituted:K!==I&&!/^([^/]+)\/(ultra|strong|medium|light)$/.test(K),choices:[{index:0,message:{role:"assistant",content:pe.join("")||null,...ee.length?{reasoning_content:ee.join("")}:{},...he.length?{tool_calls:he}:{},...oe?{refusal:a.errorMessage??"Content filtered"}:{}},finish_reason:_e}],usage:re,...e.metadata!==void 0?{metadata:e.metadata}:{}};for(const[n,m]of he.entries())ne(te({tool_calls:[{index:n,...m}]}));return ne({...te({},_e),model:I,served_model:I,substituted:je.substituted,...oe?{choices:[{index:0,delta:{},finish_reason:_e,message:{refusal:a.errorMessage??"Content filtered"}}]}:{},usage:re}),{completion:je,chunks:me}}}throw le!==void 0?ft(le):P!==1/0?new i(429,"all_routes_exhausted","all eligible model routes are rate-limited",void 0,{payment:{reason:"nothing_left",message:"Every connected subscription and key is rate-limited or used up right now.",pay_url:(await De())?.payment_setup_url??null,reset_at:F===1/0?null:new Date(F).toISOString()},retry_after_s:Math.max(1,Math.ceil((P-Date.now())/1e3)),served_model:v?`${v.provider}/${v.model}`:de,...v?{rate_limit:{provider:v.provider,model:v.model,...v.account?{account:v.account}:{},scope:Ee(v.observation.scope),...v.observation.claim?{claim:v.observation.claim}:{},headers:v.observation.headers}}:{}},void 0,!0):se!==void 0?se:e.model_policy==="exact"?new i(400,"substitution_refused",G.size>0?`your ${[...G].map(Ze).join(" and ")} sign-in has expired; sign in again`:"the requested model is unavailable"):_?new i(404,"model_unavailable","no usable model route is available"):await ve()}l(dn,"runLlm");export{qt as freshSubscriptionAccess,sn as llmCallerOf,an as parseLlmRequest,dn as runLlm,$t as usdEquivalent};
@@ -1 +1 @@
1
- var o=Object.defineProperty;var n=(t,a)=>o(t,"name",{value:a,configurable:!0});import{check as s,environmentPayerOfProfile as l,findRefusal as p,payerOf as u}from"../ledger/index.js";import{RunError as r}from"../runs/operations.js";import{grantStanding as f,payerOfGrant as d}from"../grants/mirror.js";import{callerTerminalGrant as m}from"../grants/terminal.js";async function i(t){const a=t.grantee??"app:terminal",e=t.sub??(a==="app:terminal"?(await m())?.sub:void 0)??null;if(e===null)return null;const c=await d(t.grant_id);return{scope:"start",payer:u({call:"start",grantPayer:c,sub:e,grantee:a,environmentPayer:await l(t.profile_id)}).payer,sub:e,grantee:a}}n(i,"startCandidateOf");async function w(t){const a=await i(t);a!==null&&await s(a)}n(w,"checkStart");async function O(t){if(!t.grant_id||(t.grantee??"app:terminal")==="app:terminal")return;const a=await f(t.grant_id);if(a.standing==="inactive"&&a.status!==null)throw new r(401,"grant_revoked","the node's grant is not active")}n(O,"checkGrantActive");async function P(t){const a=await i(t);return a===null?null:await p(a)}n(P,"startRefusal");function R(t){return t instanceof r&&(t.code==="cap_exhausted"||t.code==="grant_revoked")}n(R,"isStartRefusal");export{O as checkGrantActive,w as checkStart,R as isStartRefusal,i as startCandidateOf,P as startRefusal};
1
+ var o=Object.defineProperty;var n=(t,a)=>o(t,"name",{value:a,configurable:!0});import{check as s,environmentPayerOfProfile as l,findRefusal as u,payerOf as p}from"../ledger/index.js";import{RunError as e}from"../runs/operations.js";import{grantRecord as d,grantStanding as f}from"../grants/mirror.js";import{callerTerminalGrant as g}from"../grants/terminal.js";async function i(t){const a=t.grantee??"app:terminal",r=t.sub??(a==="app:terminal"?(await g())?.sub:void 0)??null;if(r===null)return null;const c=t.grant_id?(await d(t.grant_id))?.payer:null;return{scope:"start",payer:p({call:"start",grantPayer:c,sub:r,grantee:a,environmentPayer:await l(t.profile_id)}).payer,sub:r,grantee:a}}n(i,"startCandidateOf");async function R(t){const a=await i(t);a!==null&&await s(a)}n(R,"checkStart");async function w(t){if(!t.grant_id||(t.grantee??"app:terminal")==="app:terminal")return;const a=await f(t.grant_id);if(a.standing==="inactive"&&a.status!==null)throw new e(401,"grant_revoked","the node's grant is not active")}n(w,"checkGrantActive");async function P(t){const a=await i(t);return a===null?null:await u(a)}n(P,"startRefusal");function b(t){return t instanceof e&&(t.code==="cap_exhausted"||t.code==="grant_revoked")}n(b,"isStartRefusal");export{w as checkGrantActive,R as checkStart,b as isStartRefusal,i as startCandidateOf,P as startRefusal};