@north-light/cli 0.3.630 → 0.3.632
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.
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/imports.d.ts +3 -1
- package/dist/core/canvas/schema-pg/016-charges-rollup-statement.sql +55 -0
- package/dist/core/canvas/schema-version.d.ts +1 -1
- package/dist/core/canvas/schema-version.js +1 -1
- package/dist/core/import/load/bind.d.ts +10 -3
- package/dist/core/import/load/bind.js +16 -14
- package/dist/core/import/load/rewrite.js +9 -9
- package/dist/core/import/load/run.js +1 -1
- package/dist/core/import/load/verify.js +8 -9
- package/dist/core/llm/run.js +2 -2
- package/package.json +2 -2
- package/packages/crouter-identity/package.json +1 -1
- package/runtime.lock.json +13 -13
package/dist/api/contract.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** The contract level this build serves and requires. Written by `scripts/contract.mjs release`; never edit by hand. */
|
|
2
|
-
export declare const CONTRACT_LEVEL = "1.
|
|
2
|
+
export declare const CONTRACT_LEVEL = "1.51";
|
|
3
3
|
/** Request header naming the one contract level the caller needs, e.g. `1.3`. Optional: absent means no check. */
|
|
4
4
|
export declare const REQUIRED_CONTRACT_HEADER = "Crouter-Required-Contract";
|
|
5
5
|
/** Response header listing the contract levels the server serves, comma-separated, one per major, e.g. `1.3`. */
|
package/dist/api/contract.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var c=Object.defineProperty;var e=(r,t)=>c(r,"name",{value:t,configurable:!0});const f="1.
|
|
1
|
+
var c=Object.defineProperty;var e=(r,t)=>c(r,"name",{value:t,configurable:!0});const f="1.51",i="Crouter-Required-Contract",p="Crouter-Contract";function l(r){const t=/^(\d+)\.(\d+)$/.exec(r.trim());return t===null?null:{major:Number(t[1]),minor:Number(t[2])}}e(l,"parseContractLevel");function a(r){return r==null?[]:r.split(",").map(t=>l(t)).filter(t=>t!==null)}e(a,"parseServedContracts");function s(r,t){const n=l(r);return n===null?!1:(typeof t=="string"||t===null||t===void 0?a(t):t).some(u=>u.major===n.major&&u.minor>=n.minor)}e(s,"contractSatisfies");function C(r,t,n={}){if(r===void 0)return null;if(l(r)===null)return{status:400,code:"invalid_request",param:i,message:`${i} must be a contract level like 1.0.`};if(s(r,t))return null;const o=r.trim();return{status:426,code:"runtime_version_unsupported",message:t===null||a(t).length===0?`The runtime did not name its contract level; the caller requires contract ${o} or later. Roll the runtime forward.`:`The runtime serves contract ${t}; the caller requires contract ${o} or later within the same major. Roll the runtime forward, or pin an SDK whose crouterContract the runtime serves.`,details:{sdk_version:(n.legacyMinimum??"").trim(),runtime_version:n.runtimeVersion??null,required_contract:o,runtime_contract:t}}}e(C,"contractRefusal");export{p as CONTRACT_HEADER,f as CONTRACT_LEVEL,i as REQUIRED_CONTRACT_HEADER,C as contractRefusal,s as contractSatisfies,l as parseContractLevel,a as parseServedContracts};
|
|
@@ -40,8 +40,10 @@ export interface ImportVerifyDTO {
|
|
|
40
40
|
count: number;
|
|
41
41
|
keys: string[];
|
|
42
42
|
}>;
|
|
43
|
-
/** Per table: manifest rows the target no longer holds because
|
|
43
|
+
/** Per table: manifest rows the target no longer holds because its maintenance removed them after the copy (run events older than the archive cutoff, memory_reads older than the 30-day retention); their staged row is not compared. */
|
|
44
44
|
archived?: Record<string, number>;
|
|
45
|
+
/** Imported revisions whose text is in neither the target nor the bundle: the source had already lost it, so the import did not (reported, not a failure). */
|
|
46
|
+
source_missing_bodies?: number;
|
|
45
47
|
invariants: Record<string, boolean>;
|
|
46
48
|
}
|
|
47
49
|
export interface ImportFailureDTO {
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
-- 016-charges-rollup-statement.sql — the `charges` INSERT rollup runs once per statement, not once per row. One transaction;
|
|
2
|
+
-- `schema_min_reader` is not touched, so the previous release (version 15) still opens the result: it never names the trigger or
|
|
3
|
+
-- the function, and `charge_totals` holds exactly the rows it held before.
|
|
4
|
+
--
|
|
5
|
+
-- Measured on the cycle-6 rehearsal database, 228,790 charges in one `INSERT … SELECT`: the per-row trigger 52.8 s (251 s on the
|
|
6
|
+
-- gate), a statement trigger 3.8 s, no trigger 3.4 s, with identical `charge_totals`. `charges_rollup_insert` upserted into
|
|
7
|
+
-- `charge_totals` once per inserted row; this one aggregates the statement's rows first and upserts once per distinct key.
|
|
8
|
+
--
|
|
9
|
+
-- The insert side below is the INSERT branch of 007's `charge_totals_rollup()`, unchanged in meaning: refused rows and `take` rows
|
|
10
|
+
-- are never rolled up; a row counts when its `billed_usd` is non-zero or it is marked `usd_rolled_by_trigger` with a non-zero `usd`;
|
|
11
|
+
-- `billed_usd` is always added, `usd` only for a marked row. The addition is commutative, so grouping changes no total. A single-row
|
|
12
|
+
-- INSERT (admission, settle) sees the same `charge_totals` after the statement as before. A statement that reads `charge_totals`
|
|
13
|
+
-- before it ends sees the rollup later than a per-row trigger would; no caller does (`writeCharge` inserts one row per statement and
|
|
14
|
+
-- the import copy recomputes `charge_totals` after its insert). `ON CONFLICT DO NOTHING` rows are not in the transition table.
|
|
15
|
+
--
|
|
16
|
+
-- `charges_rollup_update` is untouched. `charge_totals_rollup()` now serves only it, so its INSERT branch (dead after this step) is
|
|
17
|
+
-- removed and the insert rule exists once, in `charge_totals_rollup_insert()`. Its UPDATE behavior is exactly 007's: subtract the old
|
|
18
|
+
-- row, add the new one with both amounts, skipping refused and `take` rows on each side.
|
|
19
|
+
DROP TRIGGER charges_rollup_insert ON charges;
|
|
20
|
+
|
|
21
|
+
CREATE FUNCTION charge_totals_rollup_insert() RETURNS trigger LANGUAGE plpgsql AS $$
|
|
22
|
+
BEGIN
|
|
23
|
+
INSERT INTO charge_totals (month, payer, funding, sub, grantee, provider, usd, billed_usd)
|
|
24
|
+
SELECT month, payer, funding, COALESCE(sub, ''), grantee, COALESCE(provider, ''),
|
|
25
|
+
SUM(CASE WHEN usd_rolled_by_trigger THEN COALESCE(usd, 0) ELSE 0 END), SUM(COALESCE(billed_usd, 0))
|
|
26
|
+
FROM new_rows
|
|
27
|
+
WHERE refused IS NULL AND kind <> 'take'
|
|
28
|
+
AND (COALESCE(billed_usd, 0) <> 0 OR (usd_rolled_by_trigger AND COALESCE(usd, 0) <> 0))
|
|
29
|
+
GROUP BY month, payer, funding, COALESCE(sub, ''), grantee, COALESCE(provider, '')
|
|
30
|
+
ON CONFLICT (month, payer, funding, sub, grantee, provider) DO UPDATE
|
|
31
|
+
SET usd = charge_totals.usd + EXCLUDED.usd, billed_usd = charge_totals.billed_usd + EXCLUDED.billed_usd;
|
|
32
|
+
RETURN NULL;
|
|
33
|
+
END $$;
|
|
34
|
+
CREATE TRIGGER charges_rollup_insert AFTER INSERT ON charges
|
|
35
|
+
REFERENCING NEW TABLE AS new_rows
|
|
36
|
+
FOR EACH STATEMENT EXECUTE FUNCTION charge_totals_rollup_insert();
|
|
37
|
+
|
|
38
|
+
CREATE OR REPLACE FUNCTION charge_totals_rollup() RETURNS trigger LANGUAGE plpgsql AS $$
|
|
39
|
+
BEGIN
|
|
40
|
+
IF OLD.refused IS NULL AND OLD.kind <> 'take' THEN
|
|
41
|
+
INSERT INTO charge_totals (month, payer, funding, sub, grantee, provider, usd, billed_usd)
|
|
42
|
+
VALUES (OLD.month, OLD.payer, OLD.funding, COALESCE(OLD.sub, ''), OLD.grantee, COALESCE(OLD.provider, ''),
|
|
43
|
+
-COALESCE(OLD.usd, 0), -COALESCE(OLD.billed_usd, 0))
|
|
44
|
+
ON CONFLICT (month, payer, funding, sub, grantee, provider) DO UPDATE
|
|
45
|
+
SET usd = charge_totals.usd + EXCLUDED.usd, billed_usd = charge_totals.billed_usd + EXCLUDED.billed_usd;
|
|
46
|
+
END IF;
|
|
47
|
+
IF NEW.refused IS NULL AND NEW.kind <> 'take' THEN
|
|
48
|
+
INSERT INTO charge_totals (month, payer, funding, sub, grantee, provider, usd, billed_usd)
|
|
49
|
+
VALUES (NEW.month, NEW.payer, NEW.funding, COALESCE(NEW.sub, ''), NEW.grantee, COALESCE(NEW.provider, ''),
|
|
50
|
+
COALESCE(NEW.usd, 0), COALESCE(NEW.billed_usd, 0))
|
|
51
|
+
ON CONFLICT (month, payer, funding, sub, grantee, provider) DO UPDATE
|
|
52
|
+
SET usd = charge_totals.usd + EXCLUDED.usd, billed_usd = charge_totals.billed_usd + EXCLUDED.billed_usd;
|
|
53
|
+
END IF;
|
|
54
|
+
RETURN NULL;
|
|
55
|
+
END $$;
|
|
@@ -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 =
|
|
4
|
+
export declare const CANVAS_SCHEMA_VERSION = 16;
|
|
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=
|
|
1
|
+
var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=16;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};
|
|
@@ -8,9 +8,16 @@ export declare function checkSourcePerson(db: CanvasDb, target: string, source:
|
|
|
8
8
|
* (`crtr/group` relations). Returns rows dropped per table. */
|
|
9
9
|
export declare function checkStagedPersons(input: RewriteInput): Promise<Record<string, number>>;
|
|
10
10
|
/** After rewrite 2 and the drop: every reference from a staged row to a target row reaches a row the run's person owns or acts for (an app, a shipped
|
|
11
|
-
* document, the person's own object, an object with an `acts_for` fact for the person,
|
|
12
|
-
* rows name belongs to another person.
|
|
13
|
-
|
|
11
|
+
* document, the person's own object, an object with an `acts_for` fact for the person, an object this person's earlier run of the same install inserted,
|
|
12
|
+
* or anything below those that is not directly under an app), and no profile or grant the rows name belongs to another person.
|
|
13
|
+
*
|
|
14
|
+
* The earlier run's objects are the person's by construction, and a re-load must accept them: the drop step removes every staged document the target already
|
|
15
|
+
* holds, so the bundle's edges to them reach the target's rows, and a soft-deleted document of a reaped node directly under an app has no `acts_for` fact to reach. */
|
|
16
|
+
export declare function checkStagedReferences(input: RewriteInput, own: {
|
|
17
|
+
installId: string;
|
|
18
|
+
person: string;
|
|
19
|
+
runId: string;
|
|
20
|
+
}): Promise<void>;
|
|
14
21
|
/** After staging, before rewrite 1: every blob key a staged row names has the shape its row would produce and an owner (node) that is in this bundle or is the
|
|
15
22
|
* importing person's own node in the target. A key naming a node of another person is `person_mismatch`; a key of no known shape is `bundle_invalid`. Without this,
|
|
16
23
|
* the importer's own node would read, and compaction would delete, a blob of someone else's conversation. (Human requests are checked by `checkStagedRequestKeys`,
|
|
@@ -1,15 +1,17 @@
|
|
|
1
|
-
var q=Object.defineProperty;var
|
|
2
|
-
UNION ALL SELECT 'grants' FROM ${
|
|
3
|
-
UNION ALL SELECT 'nodes' FROM ${
|
|
4
|
-
WHERE adapter_json::jsonb #>> '{principal,sub}' IS NOT NULL AND adapter_json::jsonb #>> '{principal,sub}' NOT IN (?, ?) LIMIT 5`,
|
|
5
|
-
|
|
6
|
-
SELECT
|
|
7
|
-
|
|
1
|
+
var q=Object.defineProperty;var c=(a,t)=>q(a,"name",{value:t,configurable:!0});import{parseBlobKey as R}from"../bundle/blob-keys.js";import{q as f}from"./catalog.js";import{decodeKeys as J}from"./copy.js";import{objectIdColumns as P}from"./rewrite.js";import{ImportLaneError as D}from"./stage.js";const K=/^user:[A-Za-z0-9._-]+$/,C=c(a=>a.replace(/^user:/,""),"bare"),g=c((a,t)=>`${f(a)}.${f(t)}`,"sq"),N=c(async(a,t,...r)=>await a.prepareUncached(t).all(...r),"all");function I(a,t){return new D("bind","person_mismatch",a,t)}c(I,"mismatch");function te(a,t,r,l){if(a===t||a===r)return r;throw I(`${l} names ${a}, which is neither the bundle's person nor the importing person`,{where:l,value:a})}c(te,"boundSub");async function oe(a,t,r,l){if(!K.test(r))throw I(`the bundle's person ${JSON.stringify(r)} is not a user:<id> principal`,{where:"source.json person",value:r});if(r===l)return;const d=c(i=>g(t,i),"T"),o=await a.prepareUncached(`SELECT 'identities' AS tbl FROM ${d("identities")} WHERE scheme IN ('user', 'local-user') AND external_id = ?
|
|
2
|
+
UNION ALL SELECT 'grants' FROM ${d("grants")} WHERE sub = ? UNION ALL SELECT 'profiles' FROM ${d("profiles")} WHERE person = ?
|
|
3
|
+
UNION ALL SELECT 'nodes' FROM ${d("nodes")} WHERE sub = ? LIMIT 1`).get(r,r,r,r);if(o!==void 0)throw I(`the bundle's person ${r} is already a person in the target (${o.tbl}), not the importing person ${l}`,{where:`${o.tbl}`,value:r})}c(oe,"checkSourcePerson");const Y=[["nodes","sub"],["crons","sub"],["grants","sub"],["profiles","person"],["charges","sub"],["limits","sub"],["audit_rows","sub"],["provider_approvals","sub"]],B=[["charges","payer"],["limits","payer"],["audit_rows","payer"],["audit_rows","grantee"],["charges","grantee"],["run_events","grantee"],["idempotency_keys","grantee"],["uploads","grantee"],["provider_approvals","grantee"],["profiles","grantee"],["crons","grantee"]];async function ne(a){const{db:t,schema:r,sourcePerson:l,targetPerson:d}=a,o=c(p=>g(r,p),"S"),i=c((p,u)=>{throw I(`${p} names ${u.join(", ")}, who is neither the bundle's person ${l} nor the importing person ${d}`,{where:p,values:u})},"refuse");for(const[p,u]of Y){const S=await N(t,`SELECT DISTINCT ${f(u)} AS v FROM ${o(p)} WHERE ${f(u)} IS NOT NULL AND ${f(u)} <> '' AND ${f(u)} NOT IN (?, ?) LIMIT 5`,l,d);S.length>0&&i(`${p}.${u}`,S.map(O=>O.v))}for(const[p,u]of B){const S=await N(t,`SELECT DISTINCT ${f(u)} AS v FROM ${o(p)} WHERE ${f(u)} LIKE 'user:%' AND ${f(u)} NOT IN (?, ?) LIMIT 5`,l,d);S.length>0&&i(`${p}.${u}`,S.map(O=>O.v))}const h=await N(t,`SELECT DISTINCT external_id AS v FROM ${o("identities")} WHERE scheme IN ('user', 'local-user') AND external_id NOT IN (?, ?) LIMIT 5`,l,d);h.length>0&&i("identities.external_id",h.map(p=>p.v));const _=await N(t,`SELECT DISTINCT adapter_json::jsonb #>> '{principal,sub}' AS v FROM ${o("daemon_actions")}
|
|
4
|
+
WHERE adapter_json::jsonb #>> '{principal,sub}' IS NOT NULL AND adapter_json::jsonb #>> '{principal,sub}' NOT IN (?, ?) LIMIT 5`,l,d);_.length>0&&i("daemon_actions principal.sub",_.map(p=>p.v));const m=await N(t,`SELECT DISTINCT subject_id AS v FROM ${o("relations")} WHERE relation = 'acts_for' AND subject_type = 'user' AND subject_id NOT IN (?, ?) LIMIT 5`,C(l),C(d));m.length>0&&i("relations acts_for subject",m.map(p=>p.v));const $=Number((await t.prepareUncached(`DELETE FROM ${o("relations")} WHERE resource_type = 'crtr/group'`).run()).changes);return $>0?{relations:$}:{}}c(ne,"checkStagedPersons");async function z(a,t){return(await N(a,`SELECT m.inserted_keys FROM import_manifest m JOIN import_runs r ON r.run_id = m.run_id
|
|
5
|
+
WHERE m.table_name = 'objects' AND r.source_install_id = ? AND r.person = ? AND r.run_id <> ? AND r.state IN ('committed', 'done', 'failed')`,t.installId,t.person,t.runId)).flatMap(l=>J(l.inserted_keys).map(d=>d[0]))}c(z,"earlierImportedObjects");async function se(a,t){const{db:r,schema:l,target:d,catalog:o,targetPerson:i}=a,h=c(n=>g(l,n),"S"),_=c(n=>g(d,n),"T"),m=C(i);await r.exec(`CREATE TABLE ${h("_refs")} (tbl text NOT NULL, col text NOT NULL, value text NOT NULL)`);const $=[];for(const[n,E]of P(o))if(!(!o.tables.has(n)||n==="relations"))for(const b of E)!(n==="nodes"&&b==="profile_id")&&!(n==="crons"&&b==="profile")&&$.push([n,b,""]);$.push(["relations","resource_id","WHERE resource_type = 'crtr/object'"]);for(const[n,E,b]of $)await r.prepareUncached(`INSERT INTO ${h("_refs")} SELECT ?, ?, ${f(E)}::text FROM ${h(n)} ${b===""?"WHERE":`${b} AND`} ${f(E)} IS NOT NULL
|
|
6
|
+
AND ${f(E)}::text NOT IN (SELECT id FROM ${h("objects")}) AND ${f(E)}::text IN (SELECT id FROM ${_("objects")})`).run(n,E);const p=await z(r,t),u=await N(r,`WITH RECURSIVE chain(start, id) AS (
|
|
7
|
+
SELECT DISTINCT value, value FROM ${h("_refs")}
|
|
8
|
+
UNION SELECT c.start, o.owner FROM chain c JOIN ${_("objects")} o ON o.id = c.id JOIN ${_("objects")} up ON up.id = o.owner AND up.type <> 'app'),
|
|
8
9
|
ok(id) AS (
|
|
9
|
-
SELECT o.id FROM ${
|
|
10
|
-
UNION SELECT d.object FROM ${
|
|
11
|
-
UNION SELECT i.object FROM ${
|
|
12
|
-
UNION SELECT r.resource_id FROM ${
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
10
|
+
SELECT o.id FROM ${_("objects")} o WHERE o.type = 'app'
|
|
11
|
+
UNION SELECT d.object FROM ${_("documents")} d WHERE d.source_path IS NOT NULL
|
|
12
|
+
UNION SELECT i.object FROM ${_("identities")} i WHERE i.scheme IN ('user', 'local-user') AND i.external_id = ?
|
|
13
|
+
UNION SELECT r.resource_id FROM ${_("relations")} r WHERE r.resource_type = 'crtr/object' AND r.relation = 'acts_for' AND r.subject_type = 'user' AND r.subject_id = ?
|
|
14
|
+
UNION SELECT unnest(?::text[]))
|
|
15
|
+
SELECT r.tbl, r.col, r.value FROM ${h("_refs")} r
|
|
16
|
+
WHERE NOT EXISTS (SELECT 1 FROM chain c JOIN ok ON ok.id = c.id WHERE c.start = r.value) LIMIT 10`,i,m,p);if(u.length>0)throw I(`the bundle refers to objects that are not ${i}'s: ${u.map(n=>`${n.tbl}.${n.col}=${n.value}`).join(", ")}`,{references:u});const S=[["nodes","profile_id"],["crons","profile"],["profiles","id"]];for(const[n,E]of S){const b=await N(r,`SELECT DISTINCT s.${f(E)} AS v FROM ${h(n)} s JOIN ${_("profiles")} p ON p.id = s.${f(E)} WHERE p.person <> ? LIMIT 5`,i);if(b.length>0)throw I(`${n}.${E} names profiles that belong to another person: ${b.map(T=>T.v).join(", ")}`,{where:`${n}.${E}`,values:b.map(T=>T.v)})}for(const[n,E]of[["nodes","grant_id"],["crons","grant_id"]]){const b=await N(r,`SELECT DISTINCT s.${f(E)} AS v FROM ${h(n)} s JOIN ${_("grants")} g ON g.id = s.${f(E)} WHERE g.sub <> ? LIMIT 5`,i);if(b.length>0)throw I(`${n}.${E} names grants that belong to another person: ${b.map(T=>T.v).join(", ")}`,{where:`${n}.${E}`,values:b.map(T=>T.v)})}const O=await N(r,`SELECT DISTINCT d.adapter_json::jsonb #>> '{principal,grant_id}' AS v FROM ${h("daemon_actions")} d
|
|
17
|
+
JOIN ${_("grants")} g ON g.id = d.adapter_json::jsonb #>> '{principal,grant_id}' WHERE g.sub <> ? LIMIT 5`,i);if(O.length>0)throw I(`a queued action names grants that belong to another person: ${O.map(n=>n.v).join(", ")}`,{where:"daemon_actions principal.grant_id",values:O.map(n=>n.v)})}c(se,"checkStagedReferences");const k=c((a,t)=>new D("bind","bundle_invalid",a,t),"bundleInvalid");async function re(a){const{db:t,schema:r,target:l,targetPerson:d}=a,o=c(e=>g(r,e),"S"),i=new Set((await N(t,`SELECT node_id AS v FROM ${o("nodes")}`)).map(e=>e.v)),h=await N(t,`SELECT conversation_id, seq::text AS seq, blob_key FROM ${o("conversation_parts")}`),_=await N(t,`SELECT run_id, path, blob_key FROM ${o("upload_uses")} WHERE blob_key IS NOT NULL`),m=await N(t,`SELECT object, output_key FROM ${o("jobs")} WHERE output_key IS NOT NULL`),$=c(e=>e.split("/")[1]??"","jobOwner"),p=c((e,s,w,L)=>{const F=R(s);if(F===null||F.kind!==w||L!==void 0&&s!==L)throw k(`${e} holds ${JSON.stringify(s)}, which is not a ${w} blob key${L===void 0?"":` of the shape ${L}`}`,{where:e,value:s})},"shaped");for(const e of h)if(p("conversation_parts.blob_key",e.blob_key,"conversation"),e.blob_key.split("/")[2]!==e.conversation_id)throw k(`conversation_parts.blob_key ${e.blob_key} is not under its conversation ${e.conversation_id}`,{where:"conversation_parts.blob_key",value:e.blob_key});for(const e of _)p("upload_uses.blob_key",e.blob_key,"attachment");for(const e of m)p("jobs.output_key",e.output_key,"job",`jobs/${$(e.output_key)}/${e.object}/output`);const u=new Set;for(const{blob_key:e}of h){const s=R(e);s!==null&&s.kind==="conversation"&&!i.has(s.owner)&&u.add(s.owner)}for(const{blob_key:e}of _){const s=R(e);s!==null&&s.kind==="attachment"&&!i.has(s.owner)&&u.add(s.owner)}for(const{output_key:e}of m)i.has($(e))||u.add($(e));const S=new Map((u.size===0?[]:await N(t,`SELECT node_id, sub FROM ${g(l,"nodes")} WHERE node_id = ANY(?::text[])`,[...u])).map(e=>[e.node_id,e.sub])),O=c(e=>i.has(e)||S.get(e)===d,"held"),n=c(e=>!i.has(e)&&!S.has(e),"gone"),E={},b=c((e,s)=>{s>0&&(E[e]=(E[e]??0)+s)},"count"),T=c(async(e,...s)=>Number((await t.prepareUncached(e).run(...s)).changes),"drop"),H=new Set((await N(t,`SELECT DISTINCT session_id AS v FROM ${o("sessions")} WHERE session_id IS NOT NULL`)).map(e=>e.v)),v=new Map;for(const{conversation_id:e,blob_key:s}of h){const w=R(s),L=v.get(e);L!==null&&(w===null||w.kind!=="conversation"?v.set(e,null):v.set(e,[...L??[],w.owner]))}const y=[...v].filter(([e,s])=>s!==null&&!H.has(e)&&s.every(n)).map(([e])=>e);y.length>0&&(b("conversation_parts",await T(`DELETE FROM ${o("conversation_parts")} WHERE conversation_id = ANY(?::text[])`,y)),b("conversation_entries",await T(`DELETE FROM ${o("conversation_entries")} WHERE conversation_id = ANY(?::text[])`,y)));const W=new Set(y),j=c((e,s)=>{const w=R(s).owner;if(!O(w))throw I(`${e} holds ${s}, which belongs to node ${w}, who is not in the bundle`,{where:e,value:s})},"owned");for(const e of h)W.has(e.conversation_id)||j("conversation_parts.blob_key",e.blob_key);const M=_.filter(e=>{const s=R(e.blob_key);return s!==null&&s.kind==="attachment"&&n(s.owner)&&!i.has(e.run_id)});M.length>0&&b("upload_uses",await T(`DELETE FROM ${o("upload_uses")} u USING unnest(?::text[], ?::text[]) d(run_id, path) WHERE u.run_id = d.run_id AND u.path = d.path`,M.map(e=>e.run_id),M.map(e=>e.path)));const U=new Set(M);for(const e of _)U.has(e)||j("upload_uses.blob_key",e.blob_key);const A=m.filter(e=>e.output_key===`jobs/${$(e.output_key)}/${e.object}/output`&&n($(e.output_key)));A.length>0&&b("jobs",await T(`DELETE FROM ${o("jobs")} WHERE object = ANY(?::text[])`,A.map(e=>e.object)));const x=new Set(A);for(const e of m)x.has(e)||j("jobs.output_key",e.output_key);return E}c(re,"checkStagedBlobKeys");async function ae(a){const{db:t,schema:r}=a;for(const l of await N(t,`SELECT request_id, request_dir, presentation_dir, file FROM ${g(r,"human_requests")}`))for(const d of["request_dir","presentation_dir","file"]){const o=l[d];if(o===null||!o.startsWith("requests/"))continue;const i=R(o.includes("/",9)?o:`${o}/x`);if(i===null||i.kind!=="request")throw k(`human_requests.${d} holds ${JSON.stringify(o)}, which is not a request blob key`,{where:`human_requests.${d}`,value:o});if(i.owner!==l.request_id)throw I(`human_requests.${d} of ${l.request_id} holds ${o}, which belongs to request ${i.owner}`,{where:`human_requests.${d}`,value:o})}}c(ae,"checkStagedRequestKeys");export{te as boundSub,oe as checkSourcePerson,re as checkStagedBlobKeys,ne as checkStagedPersons,se as checkStagedReferences,ae as checkStagedRequestKeys};
|
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
var I=Object.defineProperty;var
|
|
2
|
-
UNION ALL SELECT 1 FROM ${a("objects")} WHERE type = 'repo' AND home_machine IS NULL AND name = ? AND id < ? LIMIT 1`).get(s.name,s.id,s.name,s.id)!==void 0&&(await p(t.db,`UPDATE ${a("objects")} SET name = ? WHERE id = ?`,`${s.name}-${s.id}`,s.id),c+=1);return c}
|
|
1
|
+
var I=Object.defineProperty;var E=(t,a)=>I(t,"name",{value:a,configurable:!0});import{createHash as M}from"node:crypto";import{ROOT_PROFILE_ID as h}from"../../profiles/manifest.js";import{substitutePerson as H}from"../../canvas/person.js";import{withCanvasWrite as W}from"../../canvas/db.js";import{ImportLaneError as w}from"./stage.js";import{q as $}from"./catalog.js";const C=[["rules","owner"],["messages","object_id"],["messages","actor_id"],["custom_objects","registered_by"],["nodes","app"],["nodes","profile_id"],["revisions","acting_app"],["relations","resource_id"],["relations","subject_id"],["crons","profile"],["profiles","environment_id"],["waits","target_id"]],F=[["nodes","grant_id"],["crons","grant_id"]],g={identities:"object",documents:"object",jobs:"object",custom_objects:"object",context_sessions:"node",rules:"object"},y=["app","person","profile","repo"];function D(t){const a=new Map,o=E((c,s)=>{a.has(c)||a.set(c,new Set),a.get(c).add(s)},"add");for(const c of t.foreignKeys)c.parent==="objects"&&c.columns.length===1&&o(c.table,c.columns[0]);for(const[c,s]of C)o(c,s);return a}E(D,"objectIdColumns");const f=E((t,a)=>`${$(t)}.${$(a)}`,"sq"),p=E(async(t,a,...o)=>Number((await t.prepareUncached(a).run(...o)).changes),"run"),_=E(async(t,a,...o)=>await t.prepareUncached(a).all(...o),"rows");async function q(t){t.sourcePerson!==t.targetPerson&&await W(async a=>{await a.exec(`SET LOCAL search_path TO ${$(t.schema)}`),await H(a,t.sourcePerson,t.targetPerson)})}E(q,"rewritePerson");async function G(t){const a=E(o=>f(t.schema,o),"S");return await p(t.db,`UPDATE ${a("identities")} SET person = '' WHERE person IS NULL`),await p(t.db,`UPDATE ${a("identities")} SET person = ? WHERE object IN (SELECT id FROM ${a("objects")} WHERE type = 'repo')`,t.targetPerson)}E(G,"scopeRepoIdentities");async function V(t){const a=E(s=>f(t.schema,s),"S"),o=E(s=>f(t.target,s),"T");let c=0;for(const s of await _(t.db,`SELECT id, name FROM ${a("objects")} WHERE type = 'repo' AND home_machine IS NULL ORDER BY id`))await t.db.prepareUncached(`SELECT 1 AS found FROM ${o("objects")} WHERE type = 'repo' AND home_machine IS NULL AND name = ? AND id <> ?
|
|
2
|
+
UNION ALL SELECT 1 FROM ${a("objects")} WHERE type = 'repo' AND home_machine IS NULL AND name = ? AND id < ? LIMIT 1`).get(s.name,s.id,s.name,s.id)!==void 0&&(await p(t.db,`UPDATE ${a("objects")} SET name = ? WHERE id = ?`,`${s.name}-${s.id}`,s.id),c+=1);return c}E(V,"renameClashingRepos");async function U(t,a,o,c,s){return o===null?void 0:(await t.prepareUncached(`SELECT id FROM ${f(a,"grants")} WHERE runtime = ? AND sub = ? AND grantee = ?`).get(o,c,s))?.id}E(U,"findFleetGrant");function x(t){return new w("id_map","grant_missing",`no grant in the target for: ${t.slice(0,10).join(", ")}; approve the app, then rerun`,{grantees:[...t]})}E(x,"grantMissing");async function P(t,a,o,c,s,n,l,N){const d=a.uniqueKeys.find(r=>r.table==="objects"&&r.name==="objects_named");if(d===void 0||d.predicate===null)throw new w("id_map","import_failed","the target has no objects_named unique index with a predicate");const T=E(r=>`(SELECT * FROM ${r} WHERE ${d.predicate}) o`,"live"),u="o.id <> ? AND o.name = ?";return await t.prepareUncached(`SELECT 1 FROM ${T(o)} WHERE o.owner IN (${s.map(()=>"?").join(", ")}) AND ${u} LIMIT 1`).get(...s,l,N)!==void 0?!0:await t.prepareUncached(`SELECT 1 FROM ${T(c)} WHERE o.owner = ? AND ${u} LIMIT 1`).get(n,l,N)!==void 0}E(P,"usesName");async function z(t,a){const{db:o,schema:c,target:s}=t,n=E(e=>f(c,e),"S"),l=E(e=>f(s,e),"T"),N={object:new Map,grant:new Map,kind:new Map};for(const[e,m]of a)N.object.set(e,m);const d=t.targetPerson.replace(/^user:/,"");for(const e of y){const m=e==="person"?"t.external_id = ?":e==="app"?"?::text IS NOT NULL":`EXISTS (SELECT 1 FROM ${l("relations")} r WHERE r.resource_type = 'crtr/object' AND r.resource_id = tobj.id AND r.relation = 'acts_for' AND r.subject_type = 'user' AND r.subject_id = ?)`,b=await _(o,`SELECT i.object AS src, t.object AS dst FROM ${n("identities")} i
|
|
3
3
|
JOIN ${n("objects")} so ON so.id = i.object AND so.type = ?
|
|
4
4
|
JOIN ${l("identities")} t ON t.scheme = i.scheme AND t.external_id = i.external_id${e==="repo"?" AND t.person = ? AND t.scheme = 'git'":""}
|
|
5
5
|
JOIN ${l("objects")} tobj ON tobj.id = t.object AND tobj.type = so.type
|
|
6
|
-
WHERE ${m}`,e,...e==="repo"?[t.targetPerson]:[],e==="person"?t.targetPerson:
|
|
7
|
-
WHERE o.owner = ? AND o.name = ? AND o.type = 'document' AND o.deleted_at IS NULL AND d.source_path IS NOT NULL`).get(N.object.get(e.owner)??e.owner,e.name);if(m!==void 0){N.object.set(e.id,m.id);continue}const b=t.shippedBodies[e.id];if(b===void 0)throw new
|
|
6
|
+
WHERE ${m}`,e,...e==="repo"?[t.targetPerson]:[],e==="person"?t.targetPerson:d);for(const{src:R,dst:O}of b)R!==O&&N.object.set(R,O)}const T=await _(o,`SELECT o.id, o.owner, o.name, o.created_at FROM ${n("objects")} o JOIN ${n("documents")} d ON d.object = o.id WHERE d.source_path IS NOT NULL ORDER BY o.id`);for(const e of T){const m=await o.prepareUncached(`SELECT o.id FROM ${l("objects")} o JOIN ${l("documents")} d ON d.object = o.id
|
|
7
|
+
WHERE o.owner = ? AND o.name = ? AND o.type = 'document' AND o.deleted_at IS NULL AND d.source_path IS NOT NULL`).get(N.object.get(e.owner)??e.owner,e.name);if(m!==void 0){N.object.set(e.id,m.id);continue}const b=t.shippedBodies[e.id];if(b===void 0)throw new w("id_map","bundle_invalid",`shipped document ${e.name} (${e.id}) has no counterpart in the target and source.json has no body for it`);const R=await o.prepareUncached(`SELECT o.id FROM ${l("objects")} o JOIN ${l("identities")} i ON i.object = o.id
|
|
8
8
|
WHERE o.type = 'person' AND i.scheme = 'user' AND i.external_id = ?
|
|
9
9
|
UNION ALL SELECT o.id FROM ${n("objects")} o JOIN ${n("identities")} i ON i.object = o.id
|
|
10
|
-
WHERE o.type = 'person' AND i.scheme = 'user' AND i.external_id = ? LIMIT 1`).get(t.targetPerson,t.targetPerson);if(R===void 0)throw new
|
|
11
|
-
VALUES ('crtr/object', ?, 'acts_for', 'user', ?, '', 'crtr', ?) ON CONFLICT DO NOTHING`,e.id,
|
|
12
|
-
FROM ${n("_idmap")} m WHERE m.kind = 'grant' AND d.adapter_json::jsonb ->> 'adapter' = 'cron_spawn' AND d.adapter_json::jsonb #>> '{principal,grant_id}' = m.source`),await p(o,`DELETE FROM ${n("objects")} WHERE id IN ${r}`),await p(o,`UPDATE ${n("objects")} SET name = ? WHERE type = 'person' AND name <> ? AND id IN (SELECT object FROM ${n("identities")} WHERE scheme = 'user' AND external_id = ?)`,
|
|
13
|
-
AND o.name <> ? AND (o.name = ? OR EXISTS (SELECT 1 FROM ${f(c,"objects")} t WHERE t.type = 'profile' AND t.name = o.name AND t.home_machine IS NULL AND t.id <> o.id))`,u,
|
|
10
|
+
WHERE o.type = 'person' AND i.scheme = 'user' AND i.external_id = ? LIMIT 1`).get(t.targetPerson,t.targetPerson);if(R===void 0)throw new w("id_map","bundle_invalid",`no person object for ${t.targetPerson}; cannot import shipped document ${e.name}`);const O=[R.id,...[...N.object].filter(([,L])=>L===R.id).map(([L])=>L)],S=E(L=>P(o,t.catalog,n("objects"),l("objects"),O,R.id,e.id,L),"named");let j=e.name;if(await S(j)){const L=await o.prepareUncached(`SELECT name FROM ${n("objects")} WHERE id = ?`).get(e.owner);j=`${e.name}-${L?.name??e.id}`,await S(j)&&(j=`${e.name}-${e.id}`)}await p(o,`UPDATE ${n("objects")} SET owner = ?, name = ? WHERE id = ?`,R.id,j,e.id),await p(o,`UPDATE ${n("rules")} SET owner = ? WHERE object = ?`,R.id,e.id),await p(o,`DELETE FROM ${n("relations")} WHERE resource_type = 'crtr/object' AND resource_id = ? AND relation = 'reader' AND subject_type = 'user' AND subject_id = '*' AND subject_relation = ''`,e.id),await p(o,`INSERT INTO ${n("relations")} (resource_type, resource_id, relation, subject_type, subject_id, subject_relation, written_by, created_at)
|
|
11
|
+
VALUES ('crtr/object', ?, 'acts_for', 'user', ?, '', 'crtr', ?) ON CONFLICT DO NOTHING`,e.id,d,e.created_at),await p(o,`UPDATE ${n("documents")} SET source_path = NULL WHERE object = ?`,e.id),await p(o,`UPDATE ${n("revisions")} r SET body_hash = ? WHERE r.document = ? AND NOT EXISTS (SELECT 1 FROM ${n("revision_parents")} p WHERE p.parent = r.rev_id)`,b,e.id)}const u=await _(o,`SELECT id, sub, grantee FROM ${n("grants")} ORDER BY id`),i=[];for(const e of u){const m=await U(o,s,t.fleetRuntime,e.sub,e.grantee);m===void 0?i.push(e.grantee):N.grant.set(e.id,m)}if(i.length>0)throw x(i);await o.exec(`CREATE TABLE ${n("_idmap")} (kind text NOT NULL, source text NOT NULL, target text NOT NULL, PRIMARY KEY (kind, source))`);for(const[e,m]of[["object",N.object],["grant",N.grant]])for(const[b,R]of m)await p(o,`INSERT INTO ${n("_idmap")} (kind, source, target) VALUES (?, ?, ?)`,e,b,R);const r=`(SELECT source FROM ${n("_idmap")} WHERE kind = 'object')`;for(const[e,m]of Object.entries(g))await p(o,`DELETE FROM ${n(e)} WHERE ${m} IN ${r}`);await p(o,`DELETE FROM ${n("revision_parents")} WHERE child IN (SELECT rev_id FROM ${n("revisions")} WHERE document IN ${r})`),await p(o,`DELETE FROM ${n("revisions")} WHERE document IN ${r}`);for(const[e,m]of D(t.catalog))if(t.catalog.tables.has(e))for(const b of m)await A(o,n(e),b,"object",n("_idmap"));for(const[e,m]of F)await A(o,n(e),m,"grant",n("_idmap"));await p(o,`UPDATE ${n("daemon_actions")} d SET adapter_json = jsonb_set(d.adapter_json::jsonb, '{principal,grant_id}', to_jsonb(m.target))::text
|
|
12
|
+
FROM ${n("_idmap")} m WHERE m.kind = 'grant' AND d.adapter_json::jsonb ->> 'adapter' = 'cron_spawn' AND d.adapter_json::jsonb #>> '{principal,grant_id}' = m.source`),await p(o,`DELETE FROM ${n("objects")} WHERE id IN ${r}`),await p(o,`UPDATE ${n("objects")} SET name = ? WHERE type = 'person' AND name <> ? AND id IN (SELECT object FROM ${n("identities")} WHERE scheme = 'user' AND external_id = ?)`,d,d,t.targetPerson);for(const{name:e}of await _(o,`SELECT k.name FROM ${n("object_kinds")} k WHERE EXISTS (SELECT 1 FROM ${l("object_kinds")} t WHERE t.name = k.name)`))N.kind.set(e,e);return await p(o,`DELETE FROM ${n("object_kinds")} k WHERE EXISTS (SELECT 1 FROM ${l("object_kinds")} t WHERE t.name = k.name)`),N}E(z,"rewriteIds");async function Q(t){const{db:a,schema:o,target:c,targetPerson:s}=t,n=new Map,l=E(async(d,...T)=>await a.prepareUncached(d).get(...T),"row"),N=E(d=>p(a,`DELETE FROM ${f(o,"profiles")} WHERE id = ?`,d),"dropStaged");for(const{id:d}of await _(a,`SELECT id FROM ${f(o,"profiles")} ORDER BY id`)){let T=d===h?await l(`SELECT id, person FROM ${f(c,"profiles")} WHERE person = ? AND name = 'root'`,s):await l(`SELECT id, person FROM ${f(c,"profiles")} WHERE id = ? AND person = ?`,d,s);if(T===void 0){if(await l(`SELECT id, person FROM ${f(c,"profiles")} WHERE id = ?`,d)===void 0&&d!==h)continue;const r=`${d.replace(/-[0-9a-f]{8}$/,"")}-${M("sha256").update(`${s}\0${d}`).digest("hex").slice(0,8)}`,e=await l(`SELECT id, person FROM ${f(c,"profiles")} WHERE id = ?`,r);if(e!==void 0&&e.person!==s)throw new w("id_map","unique_conflict",`profiles ${r} is held by another person in the target`,{table:"profiles",values:[r]});T=e??{id:r,person:s},e===void 0?await p(a,`UPDATE ${f(o,"profiles")} SET id = ? WHERE id = ?`,r,d):await N(d)}else await N(d);const u=T.id;await p(a,`UPDATE ${f(o,"objects")} o SET name = ? WHERE o.type = 'profile' AND o.id IN (SELECT object FROM ${f(o,"identities")} WHERE scheme = 'profile' AND external_id = ?)
|
|
13
|
+
AND o.name <> ? AND (o.name = ? OR EXISTS (SELECT 1 FROM ${f(c,"objects")} t WHERE t.type = 'profile' AND t.name = o.name AND t.home_machine IS NULL AND t.id <> o.id))`,u,d,u,d),await p(a,`UPDATE ${f(o,"identities")} SET external_id = ? WHERE scheme = 'profile' AND external_id = ? AND object IN (SELECT id FROM ${f(o,"objects")} WHERE type = 'profile')`,u,d),u!==d&&n.set(d,u)}return n}E(Q,"mapProfileIds");async function A(t,a,o,c,s){await p(t,`UPDATE ${a} t SET ${$(o)} = m.target FROM ${s} m WHERE m.kind = ? AND t.${$(o)} = m.source`,c)}E(A,"remap");async function Z(t){const{db:a,schema:o,target:c,catalog:s}=t,n=E(i=>f(o,i),"S"),l={},N=E((i,r)=>{r>0&&(l[i]=(l[i]??0)+r)},"count");await a.exec(`CREATE TABLE ${n("_dropped")} (tbl text NOT NULL, key text NOT NULL, PRIMARY KEY (tbl, key))`);const d=`(SELECT id FROM ${n("objects")} WHERE home_machine IS NOT NULL)`;await p(a,`INSERT INTO ${n("_dropped")} SELECT 'objects', id FROM ${n("objects")} WHERE home_machine IS NOT NULL`);for(const[i,r]of Object.entries(g))N(i,await p(a,`DELETE FROM ${n(i)} WHERE ${r} IN ${d}`));N("objects",await p(a,`DELETE FROM ${n("objects")} WHERE home_machine IS NOT NULL`));const T=new Map;for(const[i,r]of D(s))s.tables.has(i)&&i!=="messages"&&T.set(i,[...r]);const u=`(SELECT key FROM ${n("_dropped")} WHERE tbl = 'objects')`;for(;;){let i=0;const r=E(async(e,m,...b)=>{const R=s.tables.get(e).primaryKey.length===1?$(s.tables.get(e).primaryKey[0]):null;R!==null&&await p(a,`INSERT INTO ${n("_dropped")} SELECT ?, ${R}::text FROM ${n(e)} WHERE ${m} ON CONFLICT DO NOTHING`,e,...b);const O=await p(a,`DELETE FROM ${n(e)} WHERE ${m}`,...b);N(e,O),i+=O},"drop");for(const e of s.foreignKeys)e.columns.length!==1||e.parentColumns.length!==1||!t.catalog.tables.has(e.table)||await r(e.table,`${$(e.columns[0])} IN (SELECT key FROM ${n("_dropped")} WHERE tbl = ?)`,e.parent);for(const[e,m]of T)await r(e,m.map(b=>`${$(b)} IN ${u}`).join(" OR "));if(await r("audit_rows",`node_id IN ${u}`),i===0)break}for(const i of s.foreignKeys){if(i.columns.length!==1||!s.tables.has(i.table))continue;const r=$(i.columns[0]),e=$(i.parentColumns[0]),m=await _(a,`SELECT DISTINCT c.${r}::text AS value FROM ${n(i.table)} c
|
|
14
14
|
WHERE c.${r} IS NOT NULL AND NOT EXISTS (SELECT 1 FROM ${n(i.parent)} p WHERE p.${e} = c.${r})
|
|
15
|
-
AND NOT EXISTS (SELECT 1 FROM ${f(c,i.parent)} p WHERE p.${e} = c.${r}) LIMIT 10`);if(m.length>0)throw new
|
|
15
|
+
AND NOT EXISTS (SELECT 1 FROM ${f(c,i.parent)} p WHERE p.${e} = c.${r}) LIMIT 10`);if(m.length>0)throw new w("drop","bundle_invalid",`${i.table}.${i.columns[0]} names rows that exist nowhere: ${m.map(b=>b.value).join(", ")}`,{table:i.table,column:i.columns[0],values:m.map(b=>b.value)})}return l}E(Z,"dropStubRows");export{C as OBJECT_ID_COLUMNS,Z as dropStubRows,U as findFleetGrant,x as grantMissing,Q as mapProfileIds,D as objectIdColumns,V as renameClashingRepos,z as rewriteIds,q as rewritePerson,G as scopeRepoIdentities};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var z=Object.defineProperty;var c=(e,i)=>z(e,"name",{value:i,configurable:!0});import{zstdCompressSync as Q}from"node:zlib";import{blobStore as V}from"../../blobs/index.js";import{openDb as S,withCanvasWrite as M}from"../../canvas/db.js";import{insertImportedRevisions as X}from"../../graph/documents.js";import{getById as Z}from"../../graph/objects.js";import{bundleKeys as v,decodeRows as x,rowKeys as ee,SEQ_TABLES as te}from"../bundle/layout.js";import{readCatalog as ae}from"./catalog.js";import{copyRows as ne,decodeKeys as N,encodeKeys as L}from"./copy.js";import{pruneStaged as ie,precheck as se,renameClashingProfiles as re,rewriteConversationHeaders as oe,rewritePaths as de,rewriteRequestPaths as pe,takeRepoSyncedDocuments as ue}from"./prepare.js";import{boundSub as ce,checkSourcePerson as
|
|
1
|
+
var z=Object.defineProperty;var c=(e,i)=>z(e,"name",{value:i,configurable:!0});import{zstdCompressSync as Q}from"node:zlib";import{blobStore as V}from"../../blobs/index.js";import{openDb as S,withCanvasWrite as M}from"../../canvas/db.js";import{insertImportedRevisions as X}from"../../graph/documents.js";import{getById as Z}from"../../graph/objects.js";import{bundleKeys as v,decodeRows as x,rowKeys as ee,SEQ_TABLES as te}from"../bundle/layout.js";import{readCatalog as ae}from"./catalog.js";import{copyRows as ne,decodeKeys as N,encodeKeys as L}from"./copy.js";import{pruneStaged as ie,precheck as se,renameClashingProfiles as re,rewriteConversationHeaders as oe,rewritePaths as de,rewriteRequestPaths as pe,takeRepoSyncedDocuments as ue}from"./prepare.js";import{boundSub as ce,checkSourcePerson as le,checkStagedBlobKeys as fe,checkStagedPersons as _e,checkStagedReferences as me,checkStagedRequestKeys as we}from"./bind.js";import{deleteBlobs as ge,deleteRunBlobs as be,deleteRunPrefix as he,moveRunBlobs as Ee}from"./blobs.js";import{dropStubRows as ye,findFleetGrant as Se,grantMissing as ve,mapProfileIds as Re,renameClashingRepos as Oe,rewriteIds as Pe,rewritePerson as Ie,scopeRepoIdentities as Te}from"./rewrite.js";import{dropStaging as B,ImportLaneError as w,stage as ke,stagingSchema as je,targetSchema as De}from"./stage.js";import{verifyRun as Ae}from"./verify.js";import{sandboxPathMap as Ce,writeNodeFiles as Me}from"./path-map.js";import{allStoreKeys as Ne,readPluginsStore as Le,recordImportedActivations as Be,writeStores as We}from"./stores.js";import{publishImportedPlugins as He}from"./publish-plugins.js";import{COPIED_TABLES as Ke}from"../bundle/layout.js";import{ClaimLostError as Ue}from"../../../daemon/reconcilers/row-claim.js";const W=10*6e4,Fe=30*6e4,R=c(()=>new Date().toISOString(),"now"),O=c(async(e,i)=>{await(await S()).prepare("UPDATE import_runs SET step = ? WHERE run_id = ?").run(i,e)},"setStep");async function Je(e,i){const n=await e.get(v.source(i));if(n===null)throw new w("stage","bundle_invalid","source.json is missing");return JSON.parse(n.toString("utf8"))}c(Je,"readSource");async function qe(e,i,n,r,s,d){const a=await e.get(v.rows(n.run_id,"grants")),f=a===null?[]:x(a),m=[];for(const t of f){const u=ce(t.sub,r,n.person,"grants.sub");await Se(i,s,d,u,t.grantee)===void 0&&m.push(t.grantee)}if(m.length===0)return!0;if(n.loaded_at===void 0||n.loaded_at===null)throw new w("stage","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(n.loaded_at)>=W)throw ve(m);return!1}c(qe,"grantsReady");async function mt(e,i,n={}){const r=n.blobs??await V(),s=await S(),d=je(e.run_id),a=c(async t=>{await i.assertOwned(),await O(e.run_id,t),await n.atStep?.(t)},"at");let f=e.state==="committed";const m=[];try{const t=await Je(r,e.run_id);if(e.source_kind==="machine"&&t.installId!==e.source_install_id)throw new w("stage","bundle_invalid",`source.json names install ${t.installId}, the run is for ${e.source_install_id}`);t.installId=e.source_install_id;const u=await De(s),P=[...Ke],g=await ae(s,u,[...P,"grants"]);if(!f){const l={},T=[],k=[],j=n.fleetRuntime??process.env.CRTR_RUNTIME??null;if(await le(s,u,t.person,e.person),!await qe(r,s,e,t.person,u,j)){await i.assertOwned(),await O(e.run_id,"waiting_for_grants");return}await a("publish-plugins");const h=await He(await Le(r,e.run_id));if(h.unavailable.length>0){if(e.loaded_at===void 0||e.loaded_at===null)throw new w("publish-plugins","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(e.loaded_at)>=W)throw new w("publish-plugins","directory_unavailable",`the directory did not answer for: ${h.unavailable.slice(0,10).join(", ")}; rerun the import once it is reachable`,{plugins:h.unavailable});await i.assertOwned(),await O(e.run_id,"waiting_for_directory");return}k.push(...h.refused),await a("stage");const K=await ke(s,e.run_id,t.counts,o=>ee(e.run_id,o,t),o=>r.get(o));for(const[o,p]of Object.entries(K))l[o]={staged:p,inserted:0,mapped:0,dropped:0};const _={db:s,schema:d,target:u,catalog:g,sourcePerson:t.person,targetPerson:e.person,fleetRuntime:j,shippedBodies:t.shippedBodies??{}};await a("bind-staged");for(const[o,p]of Object.entries(await _e(_)))E(l,o,p);for(const[o,p]of Object.entries(await fe(_)))E(l,o,p);await a("rewrite-person"),await Ie(_),await Te(_),await a("prune");const U=await ie(s,d,g,t),y=t.kind==="hosted"?Ce(t.pathPrefixes??[]):[];await a("rewrite-paths"),await de(s,d,y),await oe(s,d,y,r,e.run_id),await pe(s,d),await we(_);const F=await Re(_);await re(s,d,u,t.installId,e.person),await a("rewrite-ids");const D=await Pe(_,F);await a("drop");const J=await ue(s,d,u),q=await ye(_);for(const[o,p]of Object.entries({...U}))E(l,o,p);for(const[o,p]of Object.entries(q))E(l,o,p);await me(_,{installId:t.installId,person:e.person,runId:e.run_id}),await Oe(_),await a("pre-check");const $=new Map([["messages",["seq"]],...te.map(o=>[o,["seq"]])]);await se(s,d,u,g,P,new Set,$),await a("blobs"),await Ee(s,d,u,e.person,r,e.run_id,m),await a("copy"),await M(async o=>{await i.assertOwned({extendLeaseMs:Fe});const p=await ne({db:o,runId:e.run_id,schema:d,target:u,catalog:g,source:t,person:e.person,idMap:D,pathMap:y}),A=await Ye(o,e.run_id,J);A>0&&(p.inserted.revisions=(p.inserted.revisions??0)+A),await Me(o,d,e.run_id,t);const C=await We({db:o,blobs:r,runId:e.run_id,person:e.person,objectMap:D.object});for(const[G,Y]of Object.entries(C.inserted))p.inserted[G]=Y.length;return T.push(...C.unresolvedPlugins),await o.prepare("UPDATE import_runs SET counts_json = ?, loaded_at = COALESCE(loaded_at, ?) WHERE run_id = ?").run(JSON.stringify({...Ge(l,p),unresolved_plugins:T,refused_plugins:k}),R(),e.run_id),p}),f=!0,await n.atStep?.("committed")}await a("verify");const b=await Ae(s,e.run_id,d,u,g,t.installId);if(await s.prepare("UPDATE import_runs SET verify_json = ? WHERE run_id = ?").run(JSON.stringify(b),e.run_id),!b.ok)throw new w("verify","verify_failed","the committed rows differ from the staged rows or an invariant failed",{differences:b.differences,invariants:b.invariants});await a("manifest");const I=v.manifest(e.run_id);await r.put(I,await ze(e.run_id)),await B(s,e.run_id);for(const l of Ne(e.run_id))await r.delete(l);await be(r,e.run_id),await M(async l=>{await Be(l,e.run_id,e.person),await l.prepare("UPDATE import_runs SET state = 'done', step = 'done', manifest_key = ?, finished_at = ? WHERE run_id = ?").run(I,R(),e.run_id)})}catch(t){if(t instanceof Ue)throw t;const u=$e(t);await B(s,e.run_id).catch(()=>{}),f||await ge(r,m,!0),await s.prepare("UPDATE import_runs SET state = 'failed', failure_json = ?, finished_at = ? WHERE run_id = ?").run(JSON.stringify(u),R(),e.run_id),await he(r,e.run_id,{keepNodeFiles:f,bestEffort:!0})}}c(mt,"processRun");function $e(e){if(e instanceof w)return{step:e.step,code:e.code,message:e.message,...e.detail===void 0?{}:{detail:e.detail}};const i=e.code;return{step:"unknown",code:typeof i=="string"?i:"import_failed",message:e instanceof Error?e.message:String(e)}}c($e,"failureOf");function E(e,i,n){(e[i]??={staged:0,inserted:0,mapped:0,dropped:0}).dropped+=n}c(E,"addDropped");function Ge(e,i){for(const[n,r]of Object.entries(i.inserted))(e[n]??={staged:0,inserted:0,mapped:0,dropped:0}).inserted=r;for(const[n,r]of Object.entries(i.mapped))(e[n]??={staged:0,inserted:0,mapped:0,dropped:0}).mapped=r;return e}c(Ge,"withInserted");async function Ye(e,i,n){const r=new Set((await e.prepareUncached("SELECT rev_id FROM revisions WHERE rev_id IN (SELECT jsonb_array_elements_text(?::jsonb))").all(JSON.stringify(n.map(a=>a.rev_id)))).map(a=>a.rev_id)),s=n.filter(a=>!r.has(a.rev_id)),d=new Map;for(const a of n)d.set(a.document,[...d.get(a.document)??[],a]);for(const[a,f]of d){const m=await Z(e,a);m!==null&&await X(e,m,f.map(t=>({rev_id:t.rev_id,parents:t.parents,body_hash:t.body_hash,rationale:t.rationale,created_at:t.created_at})))}return await H(e,i,"revisions",s.map(a=>[a.rev_id])),await H(e,i,"revision_parents",s.flatMap(a=>a.parents.map(f=>[a.rev_id,f]))),s.length}c(Ye,"arrive");async function H(e,i,n,r){if(r.length===0)return;const s=await e.prepare("SELECT inserted_keys FROM import_manifest WHERE run_id = ? AND table_name = ?").get(i,n);s===void 0?await e.prepare("INSERT INTO import_manifest (run_id, table_name, inserted_keys) VALUES (?, ?, ?)").run(i,n,L(r)):await e.prepare("UPDATE import_manifest SET inserted_keys = ? WHERE run_id = ? AND table_name = ?").run(L([...N(s.inserted_keys),...r]),i,n)}c(H,"appendManifest");async function ze(e){const n=await(await S()).prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ? ORDER BY table_name").all(e);return Q(Buffer.from(n.map(r=>JSON.stringify({table:r.table_name,keys:N(r.inserted_keys)})).join(`
|
|
2
2
|
`)+`
|
|
3
3
|
`))}c(ze,"manifestFile");export{Fe as COPY_LEASE_MS,W as GRANT_WAIT_MS,mt as processRun};
|
|
@@ -1,11 +1,10 @@
|
|
|
1
|
-
var
|
|
2
|
-
JOIN ${
|
|
3
|
-
WHERE m.tbl = 'revisions' AND (t.rev_id IS NULL OR t.document <> a.document OR t.body_hash <> a.body_hash OR t.rationale IS DISTINCT FROM a.rationale OR t.created_at <> a.created_at)`],["revision_parents",`FROM ${
|
|
4
|
-
WHERE m.tbl = 'revision_parents' AND t.child IS NULL`]]){const
|
|
5
|
-
WHERE m.tbl = ? AND t.${
|
|
6
|
-
|
|
7
|
-
WHERE m.tbl = 'revisions' AND encode(sha256(convert_to(b.text, 'UTF8')), 'hex') <> b.hash LIMIT 1`).get()===void 0;const M=await r.prepare(`SELECT 1 AS found FROM (
|
|
1
|
+
var W=Object.defineProperty;var d=(n,E)=>W(n,"name",{value:E,configurable:!0});import{KEY_MAPPED_TABLES as k}from"../bundle/layout.js";import{keyMatch as v,q as s,rowKey as H}from"./catalog.js";import{archiveCutoffs as j,BODY_TYPES as J}from"../../events/run-event-chunks.js";import{MEMORY_READS_RETENTION_MS as x}from"../../canvas/memory-reads.js";import{decodeKeys as B}from"./copy.js";const r=d((n,E)=>`${s(n)}.${s(E)}`,"sq"),Y={messages:["seq"]},q=["claimed_by","lease_expires_at"],K={worktrees:["attempts","next_attempt_at","sweep_reason","sweep_detail","sweep_last_at","sweep_observed_json"]},P=10*6e4;function C(n){const E=Date.now()+P;if(n==="run_events"){const{bodyCutoff:t,controlCutoff:O}=j(E);return`(s.ts < '${O}' OR (s.ts < '${t}' AND s.type IN (${J.map(p=>`'${p}'`).join(", ")})))`}return n==="memory_reads"?`s.at < '${new Date(E-x).toISOString()}'`:"false"}d(C,"removedByMaintenance");async function ee(n,E,t,O,p,h){const m={},l={},S=await n.prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ?").all(E);await n.exec(`DROP TABLE IF EXISTS ${s(t)}._m; CREATE TABLE ${s(t)}._m (tbl text NOT NULL, k jsonb NOT NULL)`);for(const{table_name:e,inserted_keys:a}of S){const i=p.tables.get(e);if(i===void 0)continue;const N=B(a);if(N.length===0)continue;await n.prepare(`DELETE FROM ${s(t)}._m WHERE tbl = ?`).run(e);for(let o=0;o<N.length;o+=5e3)await n.prepare(`INSERT INTO ${s(t)}._m SELECT ?, e FROM jsonb_array_elements(?::jsonb) e`).run(e,JSON.stringify(N.slice(o,o+5e3)));await n.exec(`ANALYZE ${s(t)}._m`);const f=[...i.identity,...Y[e]??[],...q,...K[e]??[]].map(o=>`'${o.replace(/'/g,"''")}'`).join(", ")||"''",I=d(o=>`to_jsonb(${o}) - ARRAY[${f}]::text[]`,"strip"),_=H(i);let $;if(e in k){const o=k[e];$=`JOIN import_key_map km ON km.source_install_id = '${h.replace(/'/g,"''")}' AND km.table_name = '${e}' AND km.target_key = m.k ->> 0
|
|
2
|
+
JOIN ${r(t,e)} s ON s.${s(o)}::text = km.source_key`}else $=`JOIN ${r(t,e)} s ON ${_.map((o,U)=>`s.${s(o)}::text = m.k ->> ${U}`).join(" AND ")}`;const F=e==="revisions"?` AND m.k ->> 0 NOT IN (SELECT rev_id FROM ${r(t,"_arr_revisions")})`:e==="revision_parents"?` AND NOT EXISTS (SELECT 1 FROM ${r(t,"_arr_parents")} a WHERE a.child = m.k ->> 0 AND a.parent = m.k ->> 1)`:"",b=`FROM ${r(t,"_m")} m LEFT JOIN ${r(O,e)} t ON ${v(i,_,"t","m.k")} ${$.replace("JOIN","LEFT JOIN")} WHERE m.tbl = '${e}'${F}`,w=`${b} AND ((t.${s(_[0])} IS NULL AND NOT (s.${s(_[0])} IS NOT NULL AND ${C(e)})) OR s.${s(_[0])} IS NULL OR (${I("t")}) <> (${I("s")}))`,y=await n.prepareUncached(`SELECT count(*) AS n, array_agg(k) FILTER (WHERE rn <= 10) AS keys FROM (SELECT m.k::text AS k, row_number() OVER () AS rn ${w}) d`).get(),D=Number(y.n);if(D>0&&(m[e]={count:D,keys:y.keys??[]}),e==="run_events"||e==="memory_reads"){const o=Number((await n.prepareUncached(`SELECT count(*) AS n ${b} AND t.${s(_[0])} IS NULL AND s.${s(_[0])} IS NOT NULL AND ${C(e)}`).get()).n);o>0&&(l[e]=o)}}for(const[e,a]of[["revisions",`FROM ${r(t,"_m")} m JOIN ${r(t,"_arr_revisions")} a ON a.rev_id = m.k ->> 0 LEFT JOIN revisions t ON t.rev_id = a.rev_id
|
|
3
|
+
WHERE m.tbl = 'revisions' AND (t.rev_id IS NULL OR t.document <> a.document OR t.body_hash <> a.body_hash OR t.rationale IS DISTINCT FROM a.rationale OR t.created_at <> a.created_at)`],["revision_parents",`FROM ${r(t,"_m")} m JOIN ${r(t,"_arr_parents")} a ON a.child = m.k ->> 0 AND a.parent = m.k ->> 1 LEFT JOIN revision_parents t ON t.child = a.child AND t.parent = a.parent
|
|
4
|
+
WHERE m.tbl = 'revision_parents' AND t.child IS NULL`]]){const i=Number((await n.prepareUncached(`SELECT count(*) AS n ${a}`).get()).n);i>0&&(m[`${e}.arrived`]={count:i,keys:[]})}const c={},A=`SELECT source AS key FROM ${r(t,"_idmap")} WHERE kind = 'object'`,M=d(e=>e==="messages"?`(${A})`:`(${A} UNION SELECT key FROM ${r(t,"_dropped")} WHERE tbl = 'objects')`,"droppedFor");let u=!1;for(const{table_name:e}of S){const a=p.tables.get(e);if(a===void 0||u||a.primaryKey.length===0)continue;const i=await n.prepareUncached("SELECT column_name FROM information_schema.columns WHERE table_schema = ? AND table_name = ? AND data_type = 'text'").all(O,e);for(const{column_name:N}of i){if(a.primaryKey.includes(N)&&e==="objects")continue;if(await n.prepareUncached(`SELECT 1 AS found FROM ${r(t,"_m")} m JOIN ${r(O,e)} t ON ${v(a,a.primaryKey,"t","m.k")}
|
|
5
|
+
WHERE m.tbl = ? AND t.${s(N)} IN ${M(e)} LIMIT 1`).get(e)!==void 0){u=!0,m[`${e}.${N}`]={count:1,keys:["holds a dropped object id"]};break}}}c.no_dropped_id=!u;const R=S.find(e=>e.table_name==="revisions");let T=!0,L=0;if(R!==void 0){const e=`FROM ${r(t,"_m")} m JOIN revisions r ON r.rev_id = m.k ->> 0 WHERE m.tbl = 'revisions' AND NOT EXISTS (SELECT 1 FROM bodies b WHERE b.hash = r.body_hash)`;T=await n.prepare(`SELECT 1 AS lost ${e} AND EXISTS (SELECT 1 FROM ${r(t,"bodies")} s WHERE s.hash = r.body_hash) LIMIT 1`).get()===void 0,L=Number((await n.prepare(`SELECT count(*) AS n ${e} AND NOT EXISTS (SELECT 1 FROM ${r(t,"bodies")} s WHERE s.hash = r.body_hash)`).get()).n)}c.revision_bodies_readable=T,c.revision_bodies_canonical=R===void 0||await n.prepare(`SELECT 1 AS wrong FROM ${r(t,"_m")} m JOIN revisions r ON r.rev_id = m.k ->> 0 JOIN bodies b ON b.hash = r.body_hash
|
|
6
|
+
WHERE m.tbl = 'revisions' AND encode(sha256(convert_to(b.text, 'UTF8')), 'hex') <> b.hash LIMIT 1`).get()===void 0;const g=await n.prepare(`SELECT 1 AS found FROM (
|
|
8
7
|
SELECT month, payer, funding, COALESCE(sub, '') AS sub, grantee, COALESCE(provider, '') AS provider, COALESCE(SUM(usd), 0) AS usd, COALESCE(SUM(billed_usd), 0) AS billed
|
|
9
|
-
FROM charges WHERE refused IS NULL AND kind <> 'take' AND (month, payer) IN (SELECT DISTINCT month, payer FROM ${
|
|
8
|
+
FROM charges WHERE refused IS NULL AND kind <> 'take' AND (month, payer) IN (SELECT DISTINCT month, payer FROM ${r(t,"charges")}) GROUP BY 1, 2, 3, 4, 5, 6) c
|
|
10
9
|
FULL JOIN charge_totals t ON t.month = c.month AND t.payer = c.payer AND t.funding = c.funding AND t.sub = c.sub AND t.grantee = c.grantee AND t.provider = c.provider
|
|
11
|
-
WHERE (COALESCE(t.month, c.month), COALESCE(t.payer, c.payer)) IN (SELECT DISTINCT month, payer FROM ${
|
|
10
|
+
WHERE (COALESCE(t.month, c.month), COALESCE(t.payer, c.payer)) IN (SELECT DISTINCT month, payer FROM ${r(t,"charges")}) AND (c.month IS NULL OR t.month IS NULL OR c.usd <> t.usd OR c.billed <> t.billed_usd) LIMIT 1`).get();return c.charge_totals_equal_recompute=g===void 0,{ok:Object.keys(m).length===0&&Object.values(c).every(Boolean),differences:m,...Object.keys(l).length>0?{archived:l}:{},...L>0?{source_missing_bodies:L}:{},invariants:c}}d(ee,"verifyRun");export{ee as verifyRun};
|
package/dist/core/llm/run.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var
|
|
1
|
+
var Je=Object.defineProperty;var l=(e,t)=>Je(e,"name",{value:t,configurable:!0});import{randomUUID as We}from"node:crypto";import{streamSimple as He}from"@earendil-works/pi-ai/compat";import{keyRouteProviders as ze,probeRouteAvailability as Xe}from"../model-routes-pool.js";import{KEY_CREDENTIAL_SOURCE as je,parseModelSpec as Ge}from"../model-routes.js";import{openModelRegistry as Ve}from"../runtime/model-registry.js";import{getProviderLabel as Ye,isInvalidRefreshTokenError as Ze}from"../managed-providers.js";import{MAX_RATE_LIMIT_COOLDOWN_MS as Me,coolingUntilFor as Se,isManagedProvider as N,markSubscriptionRateLimited as Qe,markSubscriptionSuccess as et,readSubscriptionPool as $e,retryAfterMsFromHeaders as _e,retryAfterMsFromError as tt,refreshSubscriptionCredential as nt,subscriptionNeedsSuccessWrite as ot,vendorRateLimit as rt,RefreshBusyError as it,RefreshTimeoutError as at}from"../subscription-state.js";import{describeRateLimitScope as Ce,rateLimitHeaders as st}from"../rate-limit-scope.js";import{RunError as i}from"../runs/operations.js";import{recognizeProviderError as ye}from"../provider-error-recognition.js";import{isSafetyRefusal as dt}from"./refusal.js";import{findRefusal as lt,payerOf as Ee,refusalError as ut,refusedMark as ct,writeCharge as ge}from"../ledger/index.js";import{storedApiKey as Ie}from"../auth-file.js";import{eligibleHostedEndpoint as ft,readHostedEndpoint as Oe}from"../grants/hosted-endpoint.js";import{parseProviderPayment as mt}from"../provider-failure.js";import{personIdAsync as pt}from"../canvas/person.js";import{getNode as Ne}from"../canvas/canvas.js";import{outboundToken as De}from"../providers/mint.js";import{discardFile as Te}from"../providers/token-cache.js";import{ProviderError as ht}from"../providers/errors.js";import{appCandidates as _t}from"./app-rungs.js";import{hostedRoute as yt,matchesFeatures as gt,ownerCandidates as wt}from"./owner-candidates.js";function bt(e){return typeof e=="string"||e===null||Array.isArray(e)&&e.every(t=>t&&typeof t=="object"&&(t.type==="text"&&typeof t.text=="string"||t.type==="image_url"&&typeof t.image_url?.url=="string"&&/^data:image\/(png|jpeg|gif|webp);base64,[A-Za-z0-9+/]+={0,2}$/.test(t.image_url.url)))}l(bt,"validContent");function Fe(e){return Array.isArray(e)?e.map(t=>{if(t.type==="text")return t;const[,o,a]=/^data:(image\/(?:png|jpeg|gif|webp));base64,(.*)$/.exec(t.image_url.url);return{type:"image",mimeType:o,data:a}}):e??""}l(Fe,"imageContent");function vt(e,t){const o=(e instanceof Error?e.message:String(e)).split("; stack=",1)[0],a=ye({message:o}).kind;return a!=="connection"&&a!=="connection-only"?e:new i(503,"upstream_model_unavailable",o.slice(0,500),void 0,{served_model:t})}l(vt,"refreshFailure");async function kt(e,t,o,a,s){if(o.expires>Date.now())return o.access;const M=e.getProvider(t)?.auth.oauth;if(!M)throw new i(503,"upstream_model_unavailable",`no OAuth refresh for ${t}`,void 0,{served_model:a});return(await nt(t,o.label,async(r,h)=>{const g=await M.refresh({type:"oauth",refresh:r,access:"",expires:0,...h?{clientId:h}:{}},s??new AbortController().signal).catch(R=>{throw vt(R,a)}),x=g.clientId;return{refresh:g.refresh,access:g.access,expires:g.expires,...typeof x=="string"&&x?{clientId:x}:{}}}).catch(r=>{throw r instanceof it||r instanceof at?new i(503,"upstream_model_unavailable",r.message,void 0,{served_model:a}):r})).access}l(kt,"freshSubscriptionAccess");function tn(e){if(!e||typeof e!="object"||Array.isArray(e))throw new i(400,"invalid_request","body must be an object");const t=e;if(!Array.isArray(t.messages)||!t.messages.every(o=>o&&typeof o=="object"&&["system","user","assistant","tool"].includes(o.role)&&bt(o.content)))throw new i(400,"invalid_request","messages must be chat messages","messages");if(t.messages.some(o=>["system","assistant"].includes(o.role)&&typeof o.content!="string"&&o.content!==null))throw new i(400,"invalid_request","system and assistant content must be text","messages");if(t.model!==void 0&&typeof t.model!="string")throw new i(400,"invalid_request","model must be a string","model");if(t.model_policy!==void 0&&!["exact","substitute"].includes(t.model_policy))throw new i(400,"invalid_request","invalid model_policy","model_policy");if(t.payer!==void 0&&!["user","app"].includes(t.payer))throw new i(400,"invalid_request","invalid payer","payer");if(t.reasoning_effort!==void 0&&!["minimal","low","medium","high","xhigh","max"].includes(t.reasoning_effort))throw new i(400,"invalid_request","invalid reasoning_effort","reasoning_effort");if(t.stream!==void 0&&typeof t.stream!="boolean")throw new i(400,"invalid_request","stream must be boolean","stream");if(t.tools!==void 0&&(!Array.isArray(t.tools)||!t.tools.every(o=>o?.type==="function"&&typeof o.function?.name=="string"&&o.function.name.length>0&&(o.function.description===void 0||typeof o.function.description=="string")&&(o.function.parameters===void 0||o.function.parameters!==null&&typeof o.function.parameters=="object"&&!Array.isArray(o.function.parameters)&&o.function.parameters.type==="object"))))throw new i(400,"invalid_request","invalid tools","tools");if(t.tool_choice!==void 0&&t.tool_choice!=="auto"&&t.tool_choice!=="none"&&t.tool_choice!=="required"&&(typeof t.tool_choice!="object"||t.tool_choice===null||t.tool_choice.type!=="function"||typeof t.tool_choice.function?.name!="string"))throw new i(400,"invalid_request","invalid tool_choice","tool_choice");if(t.messages.some(o=>o.role==="assistant"&&o.tool_calls!==void 0&&(!Array.isArray(o.tool_calls)||!o.tool_calls.every(a=>a&&typeof a.id=="string"&&typeof a.function?.name=="string"&&typeof a.function.arguments=="string"&&xt(a.function.arguments)))))throw new i(400,"invalid_request","invalid assistant tool_calls","messages");if(t.stop!==void 0&&!(typeof t.stop=="string"||Array.isArray(t.stop)&&t.stop.every(o=>typeof o=="string")))throw new i(400,"invalid_request","invalid stop","stop");if(t.seed!==void 0&&!Number.isSafeInteger(t.seed))throw new i(400,"invalid_request","invalid seed","seed");for(const[o,a]of[["temperature",t.temperature],["top_p",t.top_p],["max_tokens",t.max_tokens]])if(a!==void 0&&(typeof a!="number"||!Number.isFinite(a)||o==="temperature"&&(a<0||a>2)||o==="top_p"&&(a<0||a>1)||o==="max_tokens"&&(!Number.isSafeInteger(a)||a<1)))throw new i(400,"invalid_request",`invalid ${o}`,o);if(t.response_format!==void 0){const o=t.response_format;if(!o||typeof o!="object"||Array.isArray(o)||!["text","json_object","json_schema"].includes(o.type)||o.type==="json_schema"&&(typeof o.json_schema?.name!="string"||!o.json_schema.name||!o.json_schema.schema||typeof o.json_schema.schema!="object"||Array.isArray(o.json_schema.schema)))throw new i(400,"invalid_request","invalid response_format","response_format")}if(t.metadata!==void 0&&Buffer.byteLength(JSON.stringify(t.metadata)??"")>4096)throw new i(400,"invalid_request","metadata exceeds 4 KB","metadata");return t}l(tn,"parseLlmRequest");function xt(e){try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)}catch{return!1}}l(xt,"isJsonObject");function Rt(e){const t=Date.now(),o=e.messages.map(r=>r.role==="system"?{role:"system",content:r.content??"",timestamp:t}:r.role==="tool"?{role:"toolResult",toolCallId:r.tool_call_id??"",toolName:"",content:typeof r.content=="string"||r.content===null?[{type:"text",text:r.content??""}]:Fe(r.content),isError:!1,timestamp:t}:r.role==="assistant"?{role:"assistant",content:[...r.content?[{type:"text",text:r.content}]:[],...(r.tool_calls??[]).map(h=>({type:"toolCall",id:h.id,name:h.function.name,arguments:JSON.parse(h.function.arguments)}))],api:"openai-completions",provider:"openai",model:e.model??"",usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:t}:{role:"user",content:Fe(r.content),timestamp:t}),a=o.findIndex(r=>r.role!=="system"),s=o.slice(0,a<0?o.length:a).map(r=>r.content),M=s.join(`
|
|
2
2
|
|
|
3
|
-
`),K=e.tools?.map(({function:r})=>({name:r.name,description:r.description??"",parameters:r.parameters??{type:"object",properties:{}}}));return{...j?{systemPrompt:j}:{},messages:o.slice(s.length),...K?{tools:K}:{}}}l(kt,"contextOf");function xt(e){return ct(e?.payment)}l(xt,"paymentOf");function Rt(e,t){const o=e.find("anthropic",t);if(o)return o;const a=e.getAll().find(s=>s.provider==="anthropic"&&s.api==="anthropic-messages");return a?{...a,id:t,name:t}:void 0}l(Rt,"hostedModel");function qt(e,t){const{input:o,output:a,cacheRead:s,cacheWrite:j}=e.cost;return o===0&&a===0&&s===0&&j===0?null:Number.isFinite(t)&&t>=0?t:null}l(qt,"usdEquivalent");function At(e,t){return e.compat?.allowedFallbackModels?.find(a=>a.provider===e.provider&&a.model===t)}l(At,"allowedFallback");function en(e){return e?{payer:e.payer??"user",sub:e.sub,grantee:e.grantee,inference_endpoint:e.inference_endpoint??null}:void 0}l(en,"llmCallerOf");function De(e){return e instanceof mt?e.code==="server_error"?new i(503,"upstream_model_unavailable",e.message):new i(404,"model_unavailable",e.message):e}l(De,"mintFailure");const jt=/\bmodel is not supported when using Codex with a ChatGPT account\b/i;function Mt(e,t,o){if(!(e!=="openai-codex"||t===void 0||!jt.test(t)))return new i(404,"model_unavailable",t,void 0,{served_model:o})}l(Mt,"codexAccountModelRejection");function $t(e){return e.get("request-id")??e.get("x-request-id")}l($t,"vendorRequestId");async function tn(e,t,o,a,s,j,K){const r=j?.payer==="app"?j:void 0;if(e.payer==="app"&&!r)throw new i(403,"payer_not_app","this grant is not app-paid");if(e.payer==="user"&&r)throw new i(400,"invalid_request","this grant is app-paid; payer cannot be user","payer");if(r&&!r.inference_endpoint)throw new i(404,"model_unavailable",`${r.grantee} is app-paid but its grant carries no inference endpoint`);const p=r?.inference_endpoint??void 0,y=s===void 0?null:r?.sub??s.sub??await ft(),k=await Xe();let x;p?(x=pt(p,e.model,e.model_policy==="exact").flatMap((v,g)=>{const M=ze(v.model);return M?[{routeId:"app",credentialSource:"app",family:"app",strength:v.strength,...M,rank:g}]:[]}),x=x.filter(v=>_t(k,e,v))):x=await yt(k,e,a);const oe=!p&&s!==void 0&&y!==null?await ut():null,re=oe===null?void 0:ht(e,x,oe),Te=re?oe:null;re&&(x=[...x,re]);const Fe=p?new Set:Je(),ge=l(async()=>new i(429,"all_routes_exhausted","no available way to pay for this call",void 0,{payment:{reason:"nothing_left",message:"No available way to pay for this call",pay_url:(await Ce())?.payment_setup_url??null,reset_at:null}}),"nothingLeft");if(x.length===0)throw e.model_policy==="exact"?new i(400,"substitution_refused","no eligible model route is configured"):p?new i(404,"model_unavailable","no eligible model route is configured"):await ge();const U=`chatcmpl-${Ue()}`;let N=1/0,z=1/0,ie,b,ae,se;const de=l(async()=>K??(s?.node?(await Ee(s.node))?.caused_by??null:null)??(s?.run?(await Ee(s.run))?.caused_by??null:null),"causeOf");for(const v of x){const g=v.credentialSource==="hosted";if(!r&&!g&&!(await We(v,k)).authenticated)continue;const M=g?Rt(k,v.modelId):k.find(v.providerId,v.modelId);if(!M)continue;const B=g?Te.base_url:void 0,c=p?{...M,baseUrl:`${p.base_url}/${M.provider}`}:B?{...M,baseUrl:`${B}/anthropic`,compat:{...M.compat,allowedFallbackModels:void 0}}:M,h=v.providerId,X=v.credentialSource===He&&H(h),le=!r&&!g&&!X&&H(h)?await Ze(h):[],J=le.filter($=>!$.authFailure),we=J.filter($=>je($,c.id)<=Date.now()),D=X?await Se(h):Fe.has(h)?void 0:le.length?await Se(h):void 0;if(X&&D===void 0||le.length>0&&J.length===0&&D===void 0)continue;if(J.length&&!we.length&&D===void 0){const $=Math.min(...J.map(E=>je(E,c.id)));$<N&&(N=$,ae=`${c.provider}/${c.id}`);continue}const be=r||g?[void 0,void 0]:X?["key"]:J.length||D!==void 0?[...we,...D!==void 0?["key"]:[]]:[void 0];let ve=!1;for(const[$,E]of be.entries()){if(ve&&E!=="key")continue;const w=E==="key"?void 0:E,ke=E==="key",G=Date.now();let xe=w?.access;if(w&&w.expires<=Date.now()&&H(h))try{xe=await bt(k,h,w,`${c.provider}/${c.id}`,t)}catch(n){if(!Ge(n))throw n;ie??=n;continue}const Pe=kt(e),T=w||r||g||ke?void 0:await k.getApiKeyAndHeaders(c);if(T&&!T.ok)continue;const u=`${c.provider}/${c.id}`,F=e.model??u,R=g?y===null?null:{payer:y,funding:"endpoint"}:r?$e({call:"model",route:"endpoint",grantee:r.grantee}):y===null?null:$e({call:"model",route:w?"subscription":"key",sub:y});if(s!==void 0&&R!==null){const n=await st({scope:"call",payer:R.payer,funding:R.funding,sub:y,grantee:s.grantee,provider:h});if(n!==null){if(await ye({request:s.request??U,kind:"model",what:u,usd:null,payer:R.payer,funding:R.funding,sub:y,grantee:s.grantee,node:s.node??null,run:s.run??null,provider:h,causedBy:await de(),refused:lt(n)}),se??=n,E!=="key"&&be.includes("key")){ve=!0;continue}break}}let I;if(r&&p)try{I=await Ie({audience:p.base_url,sub:r.sub,grantee:r.grantee,initiating_app:r.grantee,scope:["crtr:llm"]},{signal:t})}catch(n){throw De(n)}if(B)try{I=await Ie({audience:B,sub:y,grantee:s.grantee,initiating_app:s.grantee,scope:["crtr:llm"]},{signal:t})}catch(n){throw De(n)}let P=null,Re=!1,_,W,V,S=!1,q,Y=null,A=3e4,L;const ue=[],ce=[],Z=[];let d,O;const Q=l((n,f=null)=>({id:U,object:"chat.completion.chunk",created:Math.floor(G/1e3),model:u,served_model:u,requested_model:F,substituted:F!==u&&!/^([^/]+)\/(ultra|strong|medium|light)$/.test(F),choices:[{index:0,delta:n,finish_reason:f}]}),"chunk"),ee=l(n=>{ue.push(n),o?.(n)},"emit"),Le=Be(c,Pe,{apiKey:I?.access_token??xe??(ke?D:void 0)??(T?.ok?T.apiKey:void 0),...T?.ok?{headers:T.headers}:{},signal:t,reasoning:e.reasoning_effort??v.thinkingLevel,...e.temperature!==void 0?{temperature:e.temperature}:{},...e.max_tokens!==void 0?{maxTokens:e.max_tokens}:{},...e.top_p!==void 0?{samplingParams:{top_p:e.top_p}}:{},...e.tool_choice==="none"?{toolChoice:"none"}:{},onPayload:l(n=>{if(!n||typeof n!="object")return;const f=e.tool_choice,m=f==="required"?c.api==="anthropic-messages"?{type:"any"}:"required":typeof f=="object"&&f!==null?c.api==="anthropic-messages"?{type:"tool",name:f.function.name}:f:void 0;return{...n,...m?{tool_choice:m}:{},...e.stop!==void 0?{[c.api==="anthropic-messages"?"stop_sequences":"stop"]:typeof e.stop=="string"?[e.stop]:e.stop}:{},...e.seed!==void 0?{seed:e.seed}:{},...e.response_format!==void 0?{response_format:e.response_format}:{}}},"onPayload"),fetch:l(async(n,f)=>{const m=await fetch(n,f);if(q=m.status,Y=$t(m.headers)??Y,g){if(P=m.headers.get("crtr-charge-id")?.trim()||null,m.ok&&!P)throw Re=!0,await m.body?.cancel(),new Error("The hosted endpoint omitted Crtr-Charge-Id; the call may already have been charged. Do not automatically replay it.");return m.status===402&&(V=xt(await m.clone().json().catch(()=>{}))),m}return m.status===429&&(S=!0,L=m.headers,A=he(m.headers)??15e3),m},"fetch"),onProviderStreamEvent:l(n=>{g&&n!==null&&typeof n=="object"&&"type"in n&&n.type==="message_stop"&&"crtr_charge"in n&&(_=n.crtr_charge)},"onProviderStreamEvent"),onResponse:l(n=>{!g&&n.status===429&&(S=!0,L=n.headers,A=he(n.headers)??15e3)},"onResponse")});try{for await(const n of Le)n.type==="text_delta"&&(ce.push(n.delta),ee(Q({content:n.delta}))),n.type==="thinking_delta"&&(Z.push(n.delta),ee(Q({reasoning_content:n.delta}))),n.type==="done"&&(d=n.message),n.type==="error"&&(d=n.error)}catch(n){const f=Qe(n);L===void 0&&n&&typeof n=="object"&&"headers"in n&&Object.keys(it(n.headers)).length&&(L=n.headers);const m=_e({status:n&&typeof n=="object"&&"status"in n?n.status:void 0,message:n instanceof Error?n.message:String(n)});if(r||g)O=n;else{if(!S&&m.kind!=="rate-limit")throw ue.length?new i(503,"upstream_model_unavailable",n instanceof Error?n.message:String(n),void 0,{served_model:u}):n;S=!0,A=f??A}}if(g){if(Re)throw new i(502,"upstream_refused","The hosted endpoint omitted Crtr-Charge-Id; the call may already have been charged. Do not automatically replay it.",void 0,{served_model:u});if(q===402&&V)throw new i(402,"payment_refused",V.message,void 0,{payment:V,served_model:u});if(q===401){if(I&&Oe(I.key),$===0)continue;throw new i(404,"model_unavailable",`${B} refuses this runtime's tokens`,void 0,{served_model:u})}if(O!==void 0||q!==void 0&&q>=400||d?.stopReason==="error"||d?.stopReason==="aborted"){const f=O instanceof Error?O.message:d?.errorMessage??`the inference endpoint answered ${q??"with an error"}`;throw q===403?new i(502,"upstream_refused",f,void 0,{served_model:u}):new i(503,"upstream_model_unavailable",f,void 0,{served_model:u})}if(_===null||typeof _!="object"||!("id"in _)||_.id!==P||!("served_model"in _)||typeof _.served_model!="string"||!_.served_model.trim()||!("list_usd"in _)||typeof _.list_usd!="number"||!Number.isFinite(_.list_usd)||_.list_usd<0||Number(_.list_usd.toFixed(6))!==_.list_usd)throw new i(502,"upstream_refused","The hosted endpoint returned missing or invalid final charge accounting; output and cost may already exist. Do not automatically replay this call.",void 0,{served_model:u,charge_id:P});W={id:P,served_model:_.served_model,list_usd:_.list_usd}}if(r){if(q===401){if(I&&Oe(I.key),$===0)continue;throw new i(404,"model_unavailable",`${p.base_url} refuses this runtime's tokens`,void 0,{served_model:u})}if(S&&he(L)===void 0)throw new i(503,"upstream_model_unavailable",`${u} was rate-limited without a retry-after`,void 0,{served_model:u});if(!S&&(O!==void 0||q!==void 0&&q>=500))throw new i(503,"upstream_model_unavailable",O instanceof Error?O.message:d?.errorMessage??"inference endpoint failed",void 0,{served_model:u})}if(!S&&d?.stopReason==="error"&&_e({message:d.errorMessage}).kind==="rate-limit"&&(S=!0,A=15e3),S){const n=nt(L,c.id,A),{observation:f,vendorReset:m}=n;if(A=n.retryMs,b={provider:h,model:c.id,...w?{account:w.label}:{},observation:f},console.error(`[llm] 429 from ${u}${w?` account "${w.label}"`:""}: scope=${Me(f.scope)} retry_after_ms=${A} headers=${JSON.stringify(f.headers)}`),w&&H(h)&&await Ve(h,w.label,A,G,Date.now(),f.scope),m!==void 0&&(z=Math.min(z,m)),Date.now()+Math.min(A,Ae)<N&&(N=Date.now()+Math.min(A,Ae),ae=u),ce.length||Z.length)throw new i(503,"service_unavailable","vendor rate limit after output began",void 0,{served_model:u});if(r)break;continue}const te=at(d);if(q===400&&e.tool_choice!==void 0&&e.tool_choice!=="auto"&&e.tool_choice!=="none"&&/\btool[_ ]choice\b/i.test(d?.errorMessage??"")&&/not supported|does not support|unsupported|cannot|must be auto/i.test(d?.errorMessage??""))throw new i(400,"invalid_request",d.errorMessage,"tool_choice",{served_model:u});if(d?.stopReason==="error"){const n=Mt(c.provider,d.errorMessage,u);if(n)throw n}if(!d||d.stopReason==="error"&&!te||d.stopReason==="aborted")throw new i(503,"upstream_model_unavailable",d?.errorMessage??"model request failed",void 0,{served_model:u});w&&H(h)&&tt(w,c.id)&&await Ye(h,w.label,G,c.id);const fe=d.content.filter(n=>n.type==="toolCall").map(n=>({id:n.id,type:"function",function:{name:n.name,arguments:JSON.stringify(n.arguments)}})),me=te?"content_filter":d.stopReason==="toolUse"?"tool_calls":d.stopReason==="length"?"length":"stop",pe=d.responseModel?At(c,d.responseModel):void 0,C=W?`${c.provider}/${W.served_model}`:pe?`${c.provider}/${pe.model}`:u,ne={prompt_tokens:d.usage.input,completion_tokens:d.usage.output,total_tokens:d.usage.totalTokens,cache_read_tokens:d.usage.cacheRead,cache_write_tokens:d.usage.cacheWrite,usd_equivalent:W?W.list_usd:qt(pe??c,d.usage.cost.total),served_model:C};g?s!==void 0&&R!==null&&await ye({id:P,request:s.request??U,kind:"model",what:C,usd:ne.usd_equivalent,payer:R.payer,funding:R.funding,sub:y,grantee:s.grantee,node:s.node??null,run:s.run??null,provider:h,causedBy:await de(),vendorRef:Y}):s!==void 0&&R!==null&&await ye({request:s.request??U,kind:"model",what:C,units:{input:d.usage.input,output:d.usage.output,cache_read:d.usage.cacheRead,cache_write:d.usage.cacheWrite},usd:ne.usd_equivalent,payer:R.payer,funding:R.funding,sub:y,grantee:s.grantee,node:s.node??null,run:s.run??null,provider:h,causedBy:await de(),vendorRef:Y});const qe={id:U,object:"chat.completion",created:Math.floor(G/1e3),model:C,served_model:C,requested_model:F,substituted:F!==C&&!/^([^/]+)\/(ultra|strong|medium|light)$/.test(F),choices:[{index:0,message:{role:"assistant",content:ce.join("")||null,...Z.length?{reasoning_content:Z.join("")}:{},...fe.length?{tool_calls:fe}:{},...te?{refusal:d.errorMessage??"Content filtered"}:{}},finish_reason:me}],usage:ne,...e.metadata!==void 0?{metadata:e.metadata}:{}};for(const[n,f]of fe.entries())ee(Q({tool_calls:[{index:n,...f}]}));return ee({...Q({},me),model:C,served_model:C,substituted:qe.substituted,...te?{choices:[{index:0,delta:{},finish_reason:me,message:{refusal:d.errorMessage??"Content filtered"}}]}:{},usage:ne}),{completion:qe,chunks:ue}}}throw se!==void 0?dt(se):N!==1/0?new i(429,"all_routes_exhausted","all eligible model routes are rate-limited",void 0,{payment:{reason:"nothing_left",message:"Every connected subscription and key is rate-limited or used up right now.",pay_url:(await Ce())?.payment_setup_url??null,reset_at:z===1/0?null:new Date(z).toISOString()},retry_after_s:Math.max(1,Math.ceil((N-Date.now())/1e3)),served_model:b?`${b.provider}/${b.model}`:ae,...b?{rate_limit:{provider:b.provider,model:b.model,...b.account?{account:b.account}:{},scope:Me(b.observation.scope),...b.observation.claim?{claim:b.observation.claim}:{},headers:b.observation.headers}}:{}},void 0,!0):ie!==void 0?ie:e.model_policy==="exact"?new i(400,"substitution_refused","the requested model is unavailable"):p?new i(404,"model_unavailable","no usable model route is available"):await ge()}l(tn,"runLlm");export{bt as freshSubscriptionAccess,en as llmCallerOf,Qt as parseLlmRequest,tn as runLlm,qt as usdEquivalent};
|
|
3
|
+
`),U=e.tools?.map(({function:r})=>({name:r.name,description:r.description??"",parameters:r.parameters??{type:"object",properties:{}}}));return{...M?{systemPrompt:M}:{},messages:o.slice(s.length),...U?{tools:U}:{}}}l(Rt,"contextOf");function qt(e){return mt(e?.payment)}l(qt,"paymentOf");function At(e,t){const o=e.find("anthropic",t);if(o)return o;const a=e.getAll().find(s=>s.provider==="anthropic"&&s.api==="anthropic-messages");return a?{...a,id:t,name:t}:void 0}l(At,"hostedModel");function jt(e,t){const{input:o,output:a,cacheRead:s,cacheWrite:M}=e.cost;return o===0&&a===0&&s===0&&M===0?null:Number.isFinite(t)&&t>=0?t:null}l(jt,"usdEquivalent");function Mt(e,t){return e.compat?.allowedFallbackModels?.find(a=>a.provider===e.provider&&a.model===t)}l(Mt,"allowedFallback");function nn(e){return e?{payer:e.payer??"user",sub:e.sub,grantee:e.grantee,inference_endpoint:e.inference_endpoint??null}:void 0}l(nn,"llmCallerOf");function Pe(e){return e instanceof ht?e.code==="server_error"?new i(503,"upstream_model_unavailable",e.message):new i(404,"model_unavailable",e.message):e}l(Pe,"mintFailure");const St=/\bmodel is not supported when using Codex with a ChatGPT account\b/i;function $t(e,t,o){if(!(e!=="openai-codex"||t===void 0||!St.test(t)))return new i(404,"model_unavailable",t,void 0,{served_model:o})}l($t,"codexAccountModelRejection");function Ct(e){return e.get("request-id")??e.get("x-request-id")}l(Ct,"vendorRequestId");async function on(e,t,o,a,s,M,U){const r=M?.payer==="app"?M:void 0;if(e.payer==="app"&&!r)throw new i(403,"payer_not_app","this grant is not app-paid");if(e.payer==="user"&&r)throw new i(400,"invalid_request","this grant is app-paid; payer cannot be user","payer");if(r&&!r.inference_endpoint)throw new i(404,"model_unavailable",`${r.grantee} is app-paid but its grant carries no inference endpoint`);const h=r?.inference_endpoint??void 0,g=s===void 0?null:r?.sub??s.sub??await pt(),x=await Ve();let R;h?(R=_t(h,e.model,e.model_policy==="exact").flatMap((_,w)=>{const S=Ge(_.model);return S?[{routeId:"app",credentialSource:"app",family:"app",strength:_.strength,...S,rank:w}]:[]}),R=R.filter(_=>gt(x,e,_))):R=await wt(x,e,a);const re=!h&&s!==void 0&&g!==null?await ft():null,ie=re===null?void 0:yt(e,R,re),Le=ie?re:null;ie&&(R=[...R,ie]);const Ke=h?new Set:ze(),we=l(async()=>new i(429,"all_routes_exhausted","no available way to pay for this call",void 0,{payment:{reason:"nothing_left",message:"No available way to pay for this call",pay_url:(await Oe())?.payment_setup_url??null,reset_at:null}}),"nothingLeft");if(R.length===0)throw e.model_policy==="exact"?new i(400,"substitution_refused","no eligible model route is configured"):h?new i(404,"model_unavailable","no eligible model route is configured"):await we();const B=`chatcmpl-${We()}`;let D=1/0,z=1/0,ae,v,se,de;const X=new Set,le=l(async()=>U??(s?.node?(await Ne(s.node))?.caused_by??null:null)??(s?.run?(await Ne(s.run))?.caused_by??null:null),"causeOf");for(const _ of R){const w=_.credentialSource==="hosted";if(!r&&!w&&!(await Xe(_,x)).authenticated){if(_.credentialSource!==je&&N(_.providerId)){const k=await $e(_.providerId);k.length>0&&k.every($=>$.authFailure)&&X.add(_.providerId)}continue}const S=w?At(x,_.modelId):x.find(_.providerId,_.modelId);if(!S)continue;const J=w?Le.base_url:void 0,c=h?{...S,baseUrl:`${h.base_url}/${S.provider}`}:J?{...S,baseUrl:`${J}/anthropic`,compat:{...S.compat,allowedFallbackModels:void 0}}:S,p=_.providerId,G=_.credentialSource===je&&N(p),ue=!r&&!w&&!G&&N(p)?await $e(p):[],W=ue.filter(k=>!k.authFailure),be=W.filter(k=>Se(k,c.id)<=Date.now()),T=G?await Ie(p):Ke.has(p)?void 0:ue.length?await Ie(p):void 0;if(G&&T===void 0)continue;if(ue.length>0&&W.length===0&&T===void 0){N(p)&&X.add(p);continue}if(W.length&&!be.length&&T===void 0){const k=Math.min(...W.map($=>Se($,c.id)));k<D&&(D=k,se=`${c.provider}/${c.id}`);continue}const ve=r||w?[void 0,void 0]:G?["key"]:W.length||T!==void 0?[...be,...T!==void 0?["key"]:[]]:[void 0];let ke=!1;for(const[k,$]of ve.entries()){if(ke&&$!=="key")continue;const b=$==="key"?void 0:$,xe=$==="key",V=Date.now();let Re=b?.access;if(b&&b.expires<=Date.now()&&N(p))try{Re=await kt(x,p,b,`${c.provider}/${c.id}`,t)}catch(n){if(!Ze(n))throw n;ae??=n;continue}const Ue=Rt(e),F=b||r||w||xe?void 0:await x.getApiKeyAndHeaders(c);if(F&&!F.ok)continue;const u=`${c.provider}/${c.id}`,P=e.model??u,q=w?g===null?null:{payer:g,funding:"endpoint"}:r?Ee({call:"model",route:"endpoint",grantee:r.grantee}):g===null?null:Ee({call:"model",route:b?"subscription":"key",sub:g});if(s!==void 0&&q!==null){const n=await lt({scope:"call",payer:q.payer,funding:q.funding,sub:g,grantee:s.grantee,provider:p});if(n!==null){if(await ge({request:s.request??B,kind:"model",what:u,usd:null,payer:q.payer,funding:q.funding,sub:g,grantee:s.grantee,node:s.node??null,run:s.run??null,provider:p,causedBy:await le(),refused:ct(n)}),de??=n,$!=="key"&&ve.includes("key")){ke=!0;continue}break}}let I;if(r&&h)try{I=await De({audience:h.base_url,sub:r.sub,grantee:r.grantee,initiating_app:r.grantee,scope:["crtr:llm"]},{signal:t})}catch(n){throw Pe(n)}if(J)try{I=await De({audience:J,sub:g,grantee:s.grantee,initiating_app:s.grantee,scope:["crtr:llm"]},{signal:t})}catch(n){throw Pe(n)}let L=null,qe=!1,y,H,Y,C=!1,A,Z=null,j=3e4,K;const ce=[],fe=[],Q=[];let d,O;const ee=l((n,f=null)=>({id:B,object:"chat.completion.chunk",created:Math.floor(V/1e3),model:u,served_model:u,requested_model:P,substituted:P!==u&&!/^([^/]+)\/(ultra|strong|medium|light)$/.test(P),choices:[{index:0,delta:n,finish_reason:f}]}),"chunk"),te=l(n=>{ce.push(n),o?.(n)},"emit"),Be=He(c,Ue,{apiKey:I?.access_token??Re??(xe?T:void 0)??(F?.ok?F.apiKey:void 0),...F?.ok?{headers:F.headers}:{},signal:t,reasoning:e.reasoning_effort??_.thinkingLevel,...e.temperature!==void 0?{temperature:e.temperature}:{},...e.max_tokens!==void 0?{maxTokens:e.max_tokens}:{},...e.top_p!==void 0?{samplingParams:{top_p:e.top_p}}:{},...e.tool_choice==="none"?{toolChoice:"none"}:{},onPayload:l(n=>{if(!n||typeof n!="object")return;const f=e.tool_choice,m=f==="required"?c.api==="anthropic-messages"?{type:"any"}:"required":typeof f=="object"&&f!==null?c.api==="anthropic-messages"?{type:"tool",name:f.function.name}:f:void 0;return{...n,...m?{tool_choice:m}:{},...e.stop!==void 0?{[c.api==="anthropic-messages"?"stop_sequences":"stop"]:typeof e.stop=="string"?[e.stop]:e.stop}:{},...e.seed!==void 0?{seed:e.seed}:{},...e.response_format!==void 0?{response_format:e.response_format}:{}}},"onPayload"),fetch:l(async(n,f)=>{const m=await fetch(n,f);if(A=m.status,Z=Ct(m.headers)??Z,w){if(L=m.headers.get("crtr-charge-id")?.trim()||null,m.ok&&!L)throw qe=!0,await m.body?.cancel(),new Error("The hosted endpoint omitted Crtr-Charge-Id; the call may already have been charged. Do not automatically replay it.");return m.status===402&&(Y=qt(await m.clone().json().catch(()=>{}))),m}return m.status===429&&(C=!0,K=m.headers,j=_e(m.headers)??15e3),m},"fetch"),onProviderStreamEvent:l(n=>{w&&n!==null&&typeof n=="object"&&"type"in n&&n.type==="message_stop"&&"crtr_charge"in n&&(y=n.crtr_charge)},"onProviderStreamEvent"),onResponse:l(n=>{!w&&n.status===429&&(C=!0,K=n.headers,j=_e(n.headers)??15e3)},"onResponse")});try{for await(const n of Be)n.type==="text_delta"&&(fe.push(n.delta),te(ee({content:n.delta}))),n.type==="thinking_delta"&&(Q.push(n.delta),te(ee({reasoning_content:n.delta}))),n.type==="done"&&(d=n.message),n.type==="error"&&(d=n.error)}catch(n){const f=tt(n);K===void 0&&n&&typeof n=="object"&&"headers"in n&&Object.keys(st(n.headers)).length&&(K=n.headers);const m=ye({status:n&&typeof n=="object"&&"status"in n?n.status:void 0,message:n instanceof Error?n.message:String(n)});if(r||w)O=n;else{if(!C&&m.kind!=="rate-limit")throw ce.length?new i(503,"upstream_model_unavailable",n instanceof Error?n.message:String(n),void 0,{served_model:u}):n;C=!0,j=f??j}}if(w){if(qe)throw new i(502,"upstream_refused","The hosted endpoint omitted Crtr-Charge-Id; the call may already have been charged. Do not automatically replay it.",void 0,{served_model:u});if(A===402&&Y)throw new i(402,"payment_refused",Y.message,void 0,{payment:Y,served_model:u});if(A===401){if(I&&Te(I.key),k===0)continue;throw new i(404,"model_unavailable",`${J} refuses this runtime's tokens`,void 0,{served_model:u})}if(O!==void 0||A!==void 0&&A>=400||d?.stopReason==="error"||d?.stopReason==="aborted"){const f=O instanceof Error?O.message:d?.errorMessage??`the inference endpoint answered ${A??"with an error"}`;throw A===403?new i(502,"upstream_refused",f,void 0,{served_model:u}):new i(503,"upstream_model_unavailable",f,void 0,{served_model:u})}if(y===null||typeof y!="object"||!("id"in y)||y.id!==L||!("served_model"in y)||typeof y.served_model!="string"||!y.served_model.trim()||!("list_usd"in y)||typeof y.list_usd!="number"||!Number.isFinite(y.list_usd)||y.list_usd<0||Number(y.list_usd.toFixed(6))!==y.list_usd)throw new i(502,"upstream_refused","The hosted endpoint returned missing or invalid final charge accounting; output and cost may already exist. Do not automatically replay this call.",void 0,{served_model:u,charge_id:L});H={id:L,served_model:y.served_model,list_usd:y.list_usd}}if(r){if(A===401){if(I&&Te(I.key),k===0)continue;throw new i(404,"model_unavailable",`${h.base_url} refuses this runtime's tokens`,void 0,{served_model:u})}if(C&&_e(K)===void 0)throw new i(503,"upstream_model_unavailable",`${u} was rate-limited without a retry-after`,void 0,{served_model:u});if(!C&&(O!==void 0||A!==void 0&&A>=500))throw new i(503,"upstream_model_unavailable",O instanceof Error?O.message:d?.errorMessage??"inference endpoint failed",void 0,{served_model:u})}if(!C&&d?.stopReason==="error"&&ye({message:d.errorMessage}).kind==="rate-limit"&&(C=!0,j=15e3),C){const n=rt(K,c.id,j),{observation:f,vendorReset:m}=n;if(j=n.retryMs,v={provider:p,model:c.id,...b?{account:b.label}:{},observation:f},console.error(`[llm] 429 from ${u}${b?` account "${b.label}"`:""}: scope=${Ce(f.scope)} retry_after_ms=${j} headers=${JSON.stringify(f.headers)}`),b&&N(p)&&await Qe(p,b.label,j,V,Date.now(),f.scope),m!==void 0&&(z=Math.min(z,m)),Date.now()+Math.min(j,Me)<D&&(D=Date.now()+Math.min(j,Me),se=u),fe.length||Q.length)throw new i(503,"service_unavailable","vendor rate limit after output began",void 0,{served_model:u});if(r)break;continue}const ne=dt(d);if(A===400&&e.tool_choice!==void 0&&e.tool_choice!=="auto"&&e.tool_choice!=="none"&&/\btool[_ ]choice\b/i.test(d?.errorMessage??"")&&/not supported|does not support|unsupported|cannot|must be auto/i.test(d?.errorMessage??""))throw new i(400,"invalid_request",d.errorMessage,"tool_choice",{served_model:u});if(d?.stopReason==="error"){const n=$t(c.provider,d.errorMessage,u);if(n)throw n}if(!d||d.stopReason==="error"&&!ne||d.stopReason==="aborted")throw new i(503,"upstream_model_unavailable",d?.errorMessage??"model request failed",void 0,{served_model:u});b&&N(p)&&ot(b,c.id)&&await et(p,b.label,V,c.id);const me=d.content.filter(n=>n.type==="toolCall").map(n=>({id:n.id,type:"function",function:{name:n.name,arguments:JSON.stringify(n.arguments)}})),pe=ne?"content_filter":d.stopReason==="toolUse"?"tool_calls":d.stopReason==="length"?"length":"stop",he=d.responseModel?Mt(c,d.responseModel):void 0,E=H?`${c.provider}/${H.served_model}`:he?`${c.provider}/${he.model}`:u,oe={prompt_tokens:d.usage.input,completion_tokens:d.usage.output,total_tokens:d.usage.totalTokens,cache_read_tokens:d.usage.cacheRead,cache_write_tokens:d.usage.cacheWrite,usd_equivalent:H?H.list_usd:jt(he??c,d.usage.cost.total),served_model:E};w?s!==void 0&&q!==null&&await ge({id:L,request:s.request??B,kind:"model",what:E,usd:oe.usd_equivalent,payer:q.payer,funding:q.funding,sub:g,grantee:s.grantee,node:s.node??null,run:s.run??null,provider:p,causedBy:await le(),vendorRef:Z}):s!==void 0&&q!==null&&await ge({request:s.request??B,kind:"model",what:E,units:{input:d.usage.input,output:d.usage.output,cache_read:d.usage.cacheRead,cache_write:d.usage.cacheWrite},usd:oe.usd_equivalent,payer:q.payer,funding:q.funding,sub:g,grantee:s.grantee,node:s.node??null,run:s.run??null,provider:p,causedBy:await le(),vendorRef:Z});const Ae={id:B,object:"chat.completion",created:Math.floor(V/1e3),model:E,served_model:E,requested_model:P,substituted:P!==E&&!/^([^/]+)\/(ultra|strong|medium|light)$/.test(P),choices:[{index:0,message:{role:"assistant",content:fe.join("")||null,...Q.length?{reasoning_content:Q.join("")}:{},...me.length?{tool_calls:me}:{},...ne?{refusal:d.errorMessage??"Content filtered"}:{}},finish_reason:pe}],usage:oe,...e.metadata!==void 0?{metadata:e.metadata}:{}};for(const[n,f]of me.entries())te(ee({tool_calls:[{index:n,...f}]}));return te({...ee({},pe),model:E,served_model:E,substituted:Ae.substituted,...ne?{choices:[{index:0,delta:{},finish_reason:pe,message:{refusal:d.errorMessage??"Content filtered"}}]}:{},usage:oe}),{completion:Ae,chunks:ce}}}throw de!==void 0?ut(de):D!==1/0?new i(429,"all_routes_exhausted","all eligible model routes are rate-limited",void 0,{payment:{reason:"nothing_left",message:"Every connected subscription and key is rate-limited or used up right now.",pay_url:(await Oe())?.payment_setup_url??null,reset_at:z===1/0?null:new Date(z).toISOString()},retry_after_s:Math.max(1,Math.ceil((D-Date.now())/1e3)),served_model:v?`${v.provider}/${v.model}`:se,...v?{rate_limit:{provider:v.provider,model:v.model,...v.account?{account:v.account}:{},scope:Ce(v.observation.scope),...v.observation.claim?{claim:v.observation.claim}:{},headers:v.observation.headers}}:{}},void 0,!0):ae!==void 0?ae:e.model_policy==="exact"?new i(400,"substitution_refused",X.size>0?`your ${[...X].map(Ye).join(" and ")} sign-in has expired; sign in again`:"the requested model is unavailable"):h?new i(404,"model_unavailable","no usable model route is available"):await we()}l(on,"runLlm");export{kt as freshSubscriptionAccess,nn as llmCallerOf,tn as parseLlmRequest,on as runLlm,jt as usdEquivalent};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.632",
|
|
4
4
|
"description": "crtr — agent runtime with memory, plugins, and marketplaces",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -145,7 +145,7 @@
|
|
|
145
145
|
},
|
|
146
146
|
"license": "UNLICENSED",
|
|
147
147
|
"dependencies": {
|
|
148
|
-
"@north-light/identity": "0.3.
|
|
148
|
+
"@north-light/identity": "0.3.632",
|
|
149
149
|
"@earendil-works/chord": "1.1.0",
|
|
150
150
|
"@earendil-works/pi-agent-core": "1.1.0",
|
|
151
151
|
"@earendil-works/pi-ai": "1.1.0",
|
package/runtime.lock.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.632",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "@north-light/cli",
|
|
9
|
-
"version": "0.3.
|
|
9
|
+
"version": "0.3.632",
|
|
10
10
|
"hasInstallScript": true,
|
|
11
11
|
"license": "UNLICENSED",
|
|
12
12
|
"workspaces": [
|
|
@@ -28,7 +28,7 @@
|
|
|
28
28
|
"@milkdown/preset-gfm": "^7.22.3",
|
|
29
29
|
"@milkdown/prose": "^7.22.3",
|
|
30
30
|
"@milkdown/utils": "^7.22.3",
|
|
31
|
-
"@north-light/identity": "0.3.
|
|
31
|
+
"@north-light/identity": "0.3.632",
|
|
32
32
|
"cron-parser": "^5.6.0",
|
|
33
33
|
"esbuild": "^0.27.7",
|
|
34
34
|
"jose": "^6.2.12",
|
|
@@ -11956,17 +11956,17 @@
|
|
|
11956
11956
|
},
|
|
11957
11957
|
"packages/crouter-api": {
|
|
11958
11958
|
"name": "@north-light/api",
|
|
11959
|
-
"version": "0.3.
|
|
11959
|
+
"version": "0.3.632",
|
|
11960
11960
|
"license": "UNLICENSED"
|
|
11961
11961
|
},
|
|
11962
11962
|
"packages/crouter-env-docker": {
|
|
11963
11963
|
"name": "@north-light/env-docker",
|
|
11964
|
-
"version": "0.3.
|
|
11964
|
+
"version": "0.3.632",
|
|
11965
11965
|
"license": "UNLICENSED"
|
|
11966
11966
|
},
|
|
11967
11967
|
"packages/crouter-identity": {
|
|
11968
11968
|
"name": "@north-light/identity",
|
|
11969
|
-
"version": "0.3.
|
|
11969
|
+
"version": "0.3.632",
|
|
11970
11970
|
"license": "UNLICENSED",
|
|
11971
11971
|
"dependencies": {
|
|
11972
11972
|
"jose": "^6.2.1"
|
|
@@ -11974,21 +11974,21 @@
|
|
|
11974
11974
|
},
|
|
11975
11975
|
"packages/crouter-plugin": {
|
|
11976
11976
|
"name": "@north-light/plugin",
|
|
11977
|
-
"version": "0.3.
|
|
11977
|
+
"version": "0.3.632",
|
|
11978
11978
|
"license": "UNLICENSED",
|
|
11979
11979
|
"dependencies": {
|
|
11980
|
-
"@north-light/api": "0.3.
|
|
11981
|
-
"@north-light/identity": "0.3.
|
|
11980
|
+
"@north-light/api": "0.3.632",
|
|
11981
|
+
"@north-light/identity": "0.3.632"
|
|
11982
11982
|
}
|
|
11983
11983
|
},
|
|
11984
11984
|
"packages/crouter-sdk": {
|
|
11985
11985
|
"name": "@north-light/sdk",
|
|
11986
|
-
"version": "0.3.
|
|
11986
|
+
"version": "0.3.632",
|
|
11987
11987
|
"license": "UNLICENSED",
|
|
11988
11988
|
"dependencies": {
|
|
11989
|
-
"@north-light/api": "0.3.
|
|
11990
|
-
"@north-light/identity": "0.3.
|
|
11991
|
-
"@north-light/plugin": "0.3.
|
|
11989
|
+
"@north-light/api": "0.3.632",
|
|
11990
|
+
"@north-light/identity": "0.3.632",
|
|
11991
|
+
"@north-light/plugin": "0.3.632",
|
|
11992
11992
|
"jose": "^6.2.1"
|
|
11993
11993
|
},
|
|
11994
11994
|
"bin": {
|