@north-light/cli 0.3.597 → 0.3.599
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/charges.d.ts +22 -0
- package/dist/api/dto/charges.js +1 -0
- package/dist/api/dto/modelauth.d.ts +26 -0
- package/dist/api/dto/node-outcomes.d.ts +4 -0
- package/dist/api/error-codes.d.ts +5 -0
- package/dist/api/error-codes.js +1 -1
- package/dist/builtin-memory/crouter-sdk/release-notes.md +11 -0
- package/dist/clients/attach/viewer.js +374 -374
- package/dist/commands/sys/join.js +1 -1
- package/dist/core/auth-file.d.ts +3 -11
- package/dist/core/auth-file.js +1 -1
- package/dist/core/canvas/export-sqlite.js +1 -1
- package/dist/core/canvas/person.js +7 -7
- package/dist/core/canvas/recovery.js +2 -2
- package/dist/core/canvas/schema-pg/012-charge-admission.sql +62 -0
- package/dist/core/canvas/schema-version.d.ts +1 -1
- package/dist/core/canvas/schema-version.js +1 -1
- package/dist/core/canvas/types.d.ts +3 -0
- package/dist/core/grants/hosted-endpoint.d.ts +28 -0
- package/dist/core/grants/hosted-endpoint.js +1 -0
- package/dist/core/grants/sync.js +1 -1
- package/dist/core/import/load/run.js +2 -2
- package/dist/core/import/load/stage.d.ts +1 -1
- package/dist/core/import/load/stage.js +1 -1
- package/dist/core/import/load/stores.d.ts +2 -0
- package/dist/core/import/load/stores.js +2 -2
- package/dist/core/ledger/charges.js +1 -1
- package/dist/core/ledger/check.js +1 -1
- package/dist/core/ledger/chunks.js +2 -2
- package/dist/core/ledger/read.js +1 -1
- package/dist/core/ledger/types.d.ts +8 -0
- package/dist/core/llm/owner-candidates.d.ts +17 -0
- package/dist/core/llm/owner-candidates.js +1 -0
- package/dist/core/llm/run.js +2 -2
- package/dist/core/model-auth/activations.d.ts +37 -0
- package/dist/core/model-auth/activations.js +1 -0
- package/dist/core/model-auth/flows.js +1 -1
- package/dist/core/model-auth/handoff-jti.d.ts +10 -1
- package/dist/core/model-auth/handoff-jti.js +1 -1
- package/dist/core/model-auth/key-routes.d.ts +30 -0
- package/dist/core/model-auth/key-routes.js +1 -0
- package/dist/core/model-auth/readiness.d.ts +8 -1
- package/dist/core/model-auth/readiness.js +1 -1
- package/dist/core/model-config.js +1 -1
- package/dist/core/model-routes-pool.d.ts +2 -0
- package/dist/core/model-routes-pool.js +1 -1
- package/dist/core/model-routes.d.ts +12 -3
- package/dist/core/model-routes.js +1 -1
- package/dist/core/provider-failure.d.ts +5 -0
- package/dist/core/provider-failure.js +1 -1
- package/dist/core/providers/call.js +1 -1
- package/dist/core/runtime/broker/fault-retry.js +1 -1
- package/dist/core/runtime/broker/model-adapter.d.ts +6 -1
- package/dist/core/runtime/broker/model-adapter.js +3 -3
- package/dist/core/runtime/front-door.js +8 -8
- package/dist/core/runtime/launch-target.d.ts +2 -0
- package/dist/core/runtime/launch-target.js +1 -1
- package/dist/daemon/api/app-listener.js +12 -12
- package/dist/daemon/api/handlers/llm.js +3 -3
- package/dist/daemon/api/handlers/modelauth.js +1 -1
- package/dist/daemon/api/handlers/nodes.js +1 -1
- package/dist/daemon/api/key-signin.d.ts +9 -0
- package/dist/daemon/api/key-signin.js +124 -0
- package/dist/daemon/api/principal.d.ts +8 -3
- package/dist/daemon/api/principal.js +1 -1
- package/dist/daemon/api/server.js +1 -1
- package/dist/daemon/api/vendor-signin.d.ts +28 -1
- package/dist/daemon/api/vendor-signin.js +42 -24
- package/dist/daemon/cron/authority.js +1 -1
- package/dist/daemon/crtrd.js +12 -12
- package/dist/daemon/reconcilers/broker-supervision.d.ts +2 -2
- package/dist/daemon/reconcilers/broker-supervision.js +2 -2
- package/dist/daemon/reconcilers/ledger-r2.js +6 -6
- package/docs/sdk/release-notes.md +11 -0
- package/package.json +2 -2
- package/packages/crouter-identity/package.json +1 -1
- package/runtime.lock.json +13 -13
|
@@ -1 +1 @@
|
|
|
1
|
-
var a=Object.defineProperty;var n=(e,r)=>a(e,"name",{value:r,configurable:!0});import{defineLeaf as o}from"../../core/command.js";import{existsSync as s}from"node:fs";import{join as d}from"node:path";import{pluginsDir as l}from"../../core/scope.js";import{joinDirectory as c}from"../../core/directory/join.js";import{apiSocketPath as u}from"../../core/canvas/paths.js";import{listProcessTable as h}from"../../core/canvas/pid.js";import{daemonAnswers as m}from"../../core/layout-migrate/index.js";import{envNodeId as p}from"../../shared/env.js";import{isDaemonRunning as f}from"../../daemon/pidfile.js";import{findDaemonPids as w,spawnDaemon as y,stopAllDaemons as g}from"../../daemon/manage.js";function k(){const e=h();if(e===null||(p()??"")!=="")return!0;const r=new Map(e.map(t=>[t.pid,t])),i=new Set;for(let t=process.ppid;t>1&&!i.has(t);t=r.get(t)?.ppid??0)if(i.add(t),r.get(t)?.command.includes("broker-cli"))return!0;return!1}n(k,"insideBroker");function b(){if(!(process.platform==="linux"&&s("/run/crtr/launcher.sock")))return{running:n(async()=>f()||w().length>0||await m(u()),"running"),stop:n(async()=>{await g()},"stop"),start:n(async()=>{await y()},"start"),firstSync:n(async()=>{const e=l("user"),r=Date.now()+2e4;for(;e&&Date.now()<r&&!s(d(e,"cloud","commands.json"));)await new Promise(i=>setTimeout(i,250))},"firstSync"),insideNode:k}}n(b,"daemonControl");const
|
|
1
|
+
var a=Object.defineProperty;var n=(e,r)=>a(e,"name",{value:r,configurable:!0});import{defineLeaf as o}from"../../core/command.js";import{existsSync as s}from"node:fs";import{join as d}from"node:path";import{pluginsDir as l}from"../../core/scope.js";import{joinDirectory as c}from"../../core/directory/join.js";import{apiSocketPath as u}from"../../core/canvas/paths.js";import{listProcessTable as h}from"../../core/canvas/pid.js";import{daemonAnswers as m}from"../../core/layout-migrate/index.js";import{envNodeId as p}from"../../shared/env.js";import{isDaemonRunning as f}from"../../daemon/pidfile.js";import{findDaemonPids as w,spawnDaemon as y,stopAllDaemons as g}from"../../daemon/manage.js";function k(){const e=h();if(e===null||(p()??"")!=="")return!0;const r=new Map(e.map(t=>[t.pid,t])),i=new Set;for(let t=process.ppid;t>1&&!i.has(t);t=r.get(t)?.ppid??0)if(i.add(t),r.get(t)?.command.includes("broker-cli"))return!0;return!1}n(k,"insideBroker");function b(){if(!(process.platform==="linux"&&(process.env.CRTR_LAUNCHER_SOCKET||s("/run/crtr/launcher.sock"))))return{running:n(async()=>f()||w().length>0||await m(u()),"running"),stop:n(async()=>{await g()},"stop"),start:n(async()=>{await y()},"start"),firstSync:n(async()=>{const e=l("user"),r=Date.now()+2e4;for(;e&&Date.now()<r&&!s(d(e,"cloud","commands.json"));)await new Promise(i=>setTimeout(i,250))},"firstSync"),insideNode:k}}n(b,"daemonControl");const P=o({name:"join",description:"register this runtime with its directory using an enrollment token, offline",whenToUse:"on your own computer, with a token from `<issuer>/account/machines`: run it from a plain terminal, with any viewers open. It stops the daemon, joins, and starts it again. Also at a hosted runtime's first boot, before the daemon starts, with the enrollment token provisioning passed in.",help:{name:"sys join",summary:"exchange a directory enrollment token for a new runtime client key and record the returned identity",guide:"Generates a new ES256 client key, sends only its public key to `PUT <directory>/v1/runtimes/registration` with the token as bearer, and learns the runtime id, client id, issuer, owner and URL from the answer. Only after that answer does it write the key file. It writes no settings and touches no canvas.db: the daemon's next start replaces this install's person with the owner everywhere in canvas.db, sets the user settings `runtime.issuer` and `runtime.audience` from the key file, and rewrites the legacy local person's profile grantees to `app:terminal`, all before it serves anything. On your own computer a running daemon is no obstacle: join takes a `join.lock` in the runtime directory (so no open viewer's redial can autostart a daemon while it works), registers with the directory while the daemon still serves, stops the daemon, writes the identity, and starts the daemon again, whose start applies the change. Run it from a plain terminal, not from inside a node: a node's broker dies with the daemon, so join refuses `join_inside_node` instead. Where the launcher owns the daemon (a hosted container) join keeps the offline contract and refuses `daemon_running`. Presenting the token of the stored successful registration again finishes those local writes without calling the directory. Any other token generates a new key and registers again.",params:[{kind:"flag",name:"directory",type:"string",required:!0,constraint:"Directory base URL (http or https) that minted the token."},{kind:"flag",name:"token",type:"string",required:!0,sensitive:!0,constraint:"Single-use enrollment token. Sensitive: never echoed in output or errors."},{kind:"flag",name:"name",type:"string",required:!1,constraint:"Label shown for this machine on the account page. Default: this computer's hostname."}],output:[{name:"runtime",type:"string",required:!0,constraint:"Runtime principal from the directory, `runtime:<id>`."},{name:"client_id",type:"string",required:!0,constraint:"OAuth client id registered for the new key."},{name:"issuer",type:"string",required:!0,constraint:"Canonical issuer, written to `runtime.issuer`."},{name:"owner",type:"string",required:!0,constraint:"Owner principal, `user:<id>`, that replaces this install's own person at the next daemon start."},{name:"canvas_rewrite",type:"string",required:!0,constraint:"Always `next daemon start`: when canvas.db identity fields are rewritten."},{name:"url",type:"string",required:!0,constraint:"Runtime URL, written to `runtime.audience`."},{name:"registered",type:"boolean",required:!0,constraint:"False when the token matched the stored registration and the directory was not called."},{name:"daemon",type:"string",required:!0,constraint:"`restarted` (a daemon was stopped and started on the joined settings), `started` (none was running; join started one and waited, up to 20s, for its first grant sync to install the account's provider plugins, so `crtr cloud \u2026` resolves), `not_running` (none was started: a hosted container's launcher owns its daemon), or `restart_failed` (joined, but the new daemon did not start: see `daemon_error`, then run `crtr sys daemon start`)."},{name:"daemon_error",type:"string",required:!1,constraint:"Why the new daemon did not start, with `daemon: restart_failed`."}],outputKind:"object",effects:["Holds `<runtime>/join.lock` (its pid) from the start until the daemon is back; `ensureDaemon` and `sys daemon start` (without `--force`) decline to start a daemon while a live process holds it (including a start already in flight when the join began). A lock whose holder died is reclaimed.","A running daemon is stopped (SIGTERM, then SIGKILL, plus strays) after the directory accepts the registration and before the local writes, then started again. Every broker dies with it and is revived by the new daemon. If the join fails after the stop, the daemon is started again anyway. With no daemon running join starts one anyway, because a bare `crtr cloud \u2026` is an unknown command (it never autostarts a daemon) until a daemon's grant sync has installed the provider plugins. Refuses `join_inside_node` when run from inside a node and a daemon is running; refuses `daemon_running` where a container launcher owns the daemon.","On a new token: calls the directory once; on success writes `<runtime>/secrets/runtime-client.json` (mode 0600) with the private key, registration and the token's SHA-256, replacing any earlier key file. A refused or failed call writes nothing.","Sends name, platform, crtr version, installed plugin ids and sandbox state with the public key. Before the request it writes `runtime-client.pending.json` (mode 0600); a rerun with the same token and directory reuses that key, so a lost reply is retried safely. The file is deleted on success or a refusal.","Sets `runtime.issuer` and `runtime.audience` in user settings. When the directory says this machine is not the account's default (`is_default: false`) it replaces the whole `runtime` setting with `{issuer, audience, unsandboxed: true}`: no app listener, and only `app:terminal` nodes run.","Rewrites the legacy local person's profile grantees to `app:terminal`.","At the next daemon start, before any listener, the person this install minted (or still the legacy local person) is replaced by the owner in every canvas.db column that holds a person: node, token, grant, cron, audit and usage subjects and grantees, the person's identity, and queued cron births. References to the install's local terminal grant are cleared and that local grant mirror is deleted so grant sync installs the directory's. Free text is unchanged. The start after that changes nothing."]},run:n(async e=>({...await c(e.directory,e.token,e.name||void 0,b()),canvas_rewrite:"next daemon start"}),"run")});export{k as insideBroker,P as sysJoinLeaf};
|
package/dist/core/auth-file.d.ts
CHANGED
|
@@ -1,21 +1,13 @@
|
|
|
1
1
|
import type { Credential, CredentialInfo, CredentialStore } from '@earendil-works/pi-ai';
|
|
2
2
|
type AuthFileData = Record<string, Credential>;
|
|
3
|
-
/**
|
|
4
|
-
* Resolve a stored api-key value the way pi does before handing it to a provider: a leading
|
|
5
|
-
* `!` runs the rest as a shell command (cached for the process), and `$VAR` / `${VAR}`
|
|
6
|
-
* interpolate from the credential's own env then `process.env` (`$$` and `$!` escape a
|
|
7
|
-
* literal `$`/`!`); an unset reference resolves the whole value to undefined. pi's resolver
|
|
8
|
-
* is internal to the coding agent and its credential store — which crouter replaces — is the
|
|
9
|
-
* only place it runs, so an auth.json holding `"key": "$ANTHROPIC_API_KEY"` would otherwise
|
|
10
|
-
* be sent to the provider verbatim.
|
|
11
|
-
*/
|
|
12
|
-
export declare function resolveCredentialValue(config: string, env?: Record<string, string>): string | undefined;
|
|
13
|
-
/** The api_key a model call can send for `providerId`: the stored row with its `$VAR` / `!cmd` reference resolved. Undefined when no api_key is stored or its reference does not resolve. */
|
|
3
|
+
/** The literal stored api_key a model call can send for `providerId`. Undefined when no nonempty api_key is stored. */
|
|
14
4
|
export declare function storedApiKey(providerId: string): Promise<string | undefined>;
|
|
15
5
|
/** Read all stored credentials. */
|
|
16
6
|
export declare function readAuthCredentials(): Promise<AuthFileData>;
|
|
17
7
|
/** Read one provider's stored credential. */
|
|
18
8
|
export declare function readAuthCredential(providerId: string): Promise<Credential | undefined>;
|
|
9
|
+
/** When each of `providerIds`' stored api_key row was last written (ISO), keyed by provider; providers without an api_key row are absent. No key material is opened beyond the type check. */
|
|
10
|
+
export declare function apiKeyUpdatedAt(providerIds: readonly string[]): Promise<Map<string, string>>;
|
|
19
11
|
/** Persist one provider's credential, leaving every other entry intact. */
|
|
20
12
|
export declare function setAuthCredential(providerId: string, credential: Credential): Promise<void>;
|
|
21
13
|
/** Remove one provider's credential (logout). Returns whether a row was removed. */
|
package/dist/core/auth-file.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var w=Object.defineProperty;var i=(a,e)=>w(a,"name",{value:e,configurable:!0});import{openDb as p,withCanvasWrite as l}from"./canvas/db.js";import{personIdAsync as n}from"./canvas/person.js";import{loadSecretsKey as y,open as f,seal as k}from"./secrets/index.js";const u=i((a,e)=>`model_api_keys|${a}|${e}`,"aadOf");function s(a,e){return JSON.parse(f(e.credential_sealed,e.key_id,y(),u(a,e.provider_id)))}i(s,"openRow");async function E(a,e,t,r){const{sealed:d,keyId:o}=k(JSON.stringify(r),y(),u(e,t));await a.prepare("INSERT INTO model_api_keys(person,provider_id,credential_sealed,key_id,updated_at) VALUES(?,?,?,?,?) ON CONFLICT(person,provider_id) DO UPDATE SET credential_sealed=EXCLUDED.credential_sealed,key_id=EXCLUDED.key_id,updated_at=EXCLUDED.updated_at").run(e,t,d,o,new Date().toISOString())}i(E,"put");async function L(a){const e=await new D().read(a);return e?.type==="api_key"&&e.key?e.key:void 0}i(L,"storedApiKey");async function m(){const a=await n(),e=await(await p()).prepare("SELECT provider_id,credential_sealed,key_id FROM model_api_keys WHERE person=? ORDER BY provider_id").all(a);return Object.fromEntries(e.map(t=>[t.provider_id,s(a,t)]))}i(m,"readAuthCredentials");async function O(a){const e=await n(),t=await(await p()).prepare("SELECT provider_id,credential_sealed,key_id FROM model_api_keys WHERE person=? AND provider_id=?").get(e,a);return t?s(e,t):void 0}i(O,"readAuthCredential");async function T(a){const e=await n(),t=await(await p()).prepare("SELECT provider_id,credential_sealed,key_id,updated_at FROM model_api_keys WHERE person=? ORDER BY provider_id").all(e);return new Map(t.filter(r=>a.includes(r.provider_id)&&s(e,r).type==="api_key").map(r=>[r.provider_id,r.updated_at]))}i(T,"apiKeyUpdatedAt");async function x(a,e){const t=await n();await l(r=>E(r,t,a,e))}i(x,"setAuthCredential");async function C(a){const e=await n();return(await(await p()).prepare("DELETE FROM model_api_keys WHERE person=? AND provider_id=?").run(e,a)).changes>0}i(C,"deleteAuthCredential");class D{static{i(this,"CrouterCredentialStore")}async read(e){return O(e)}async list(){return Object.entries(await m()).map(([e,t])=>({providerId:e,type:t.type}))}async modify(e,t){const r=await n();return l(async d=>{await d.exec("SET LOCAL lock_timeout = '15s'");const o=await d.prepare("SELECT provider_id,credential_sealed,key_id FROM model_api_keys WHERE person=? AND provider_id=? FOR UPDATE").get(r,e),_=o?s(r,o):void 0,c=await t(_);return c===void 0?_:(await E(d,r,e,c),c)})}async delete(e){await C(e)}}export{D as CrouterCredentialStore,T as apiKeyUpdatedAt,C as deleteAuthCredential,O as readAuthCredential,m as readAuthCredentials,x as setAuthCredential,L as storedApiKey};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var V=Object.defineProperty;var d=(i,a)=>V(i,"name",{value:a,configurable:!0});import{DatabaseSync as W}from"node:sqlite";import{existsSync as Y,mkdirSync as D,mkdtempSync as J,renameSync as X,rmSync as P}from"node:fs";import{tmpdir as Q}from"node:os";import{join as A}from"node:path";import j from"pg";import{migrate as z,MIGRATIONS as I}from"./migrations.js";import{canvasDbPath as Z}from"./paths.js";import{canvasSearchPathOptions as ee}from"./schema-version.js";import{EXPORT_MARK_KEY as F,IMPORT_MARK_KEY as te,OBJECT_COLUMNS as ne,pgColumns as se,quote as m,TABLE_ORDER as C}from"./import-sqlite.js";const oe=5e3,re=new Set(["environments","relations","schemas","charges","charge_totals","limits","viewer_attachments","reconciler_leases","environment_repos","conversation_entries","conversation_parts","charge_chunks","profiles","profile_projects","profile_defaults","scope_settings","scope_bookkeeping","scope_marketplaces","scope_plugins","person_settings","model_accounts","model_account_cooldowns","model_api_keys","model_settings","model_sign_in_flows","env_vars","import_runs","import_key_map","import_manifest","import_id_map","machine_links","machine_calls","machine_credentials","import_node_files","bodies","package_publications","usage","grantee_usage","provider_receipts"]),ae={exposures:"node, object, channel",rules:"object, position",edges:"type, src, dst",unresolved_links:"src, name",revision_parents:"child, parent",canvas_meta:"key",runtime_state:"key",message_causes:"message_id",peer_ingested:"key",peer_ingested_destinations:"key",message_sequence:"id",messages:"seq",review_comment_events:"seq",audit_rows:"id",peer_outbox:"id",app_users:"uid"},ie={objects:"id",revisions:"rev_id",watches:"watch_id"},H=new Set(["daemon_owner","schema_version","schema_min_reader","ledger_migrated",te,F]);function ce(i){const a=J(A(Q(),"crtr-export-")),s=process.env.CRTR_HOME;process.env.CRTR_HOME=a,D(A(a,"runtime","nodes"),{recursive:!0});try{const o=new W(i);return o.exec("PRAGMA journal_mode = DELETE;"),o.exec("PRAGMA foreign_keys = ON;"),z(o),o.exec("DELETE FROM canvas_meta; DELETE FROM message_sequence;"),o}finally{s===void 0?delete process.env.CRTR_HOME:process.env.CRTR_HOME=s,P(a,{recursive:!0,force:!0})}}d(ce,"createEmptyDatabase");async function Re(i,a=()=>{}){const s=Z();if(Y(s))throw new Error(`${s} already exists; refusing to overwrite it`);D(A(s,".."),{recursive:!0,mode:448});const o=`${s}.exporting-${process.pid}`,
|
|
1
|
+
var V=Object.defineProperty;var d=(i,a)=>V(i,"name",{value:a,configurable:!0});import{DatabaseSync as W}from"node:sqlite";import{existsSync as Y,mkdirSync as D,mkdtempSync as J,renameSync as X,rmSync as P}from"node:fs";import{tmpdir as Q}from"node:os";import{join as A}from"node:path";import j from"pg";import{migrate as z,MIGRATIONS as I}from"./migrations.js";import{canvasDbPath as Z}from"./paths.js";import{canvasSearchPathOptions as ee}from"./schema-version.js";import{EXPORT_MARK_KEY as F,IMPORT_MARK_KEY as te,OBJECT_COLUMNS as ne,pgColumns as se,quote as m,TABLE_ORDER as C}from"./import-sqlite.js";const oe=5e3,re=new Set(["environments","relations","schemas","charges","charge_totals","limits","viewer_attachments","reconciler_leases","environment_repos","conversation_entries","conversation_parts","charge_chunks","profiles","profile_projects","profile_defaults","scope_settings","scope_bookkeeping","scope_marketplaces","scope_plugins","person_settings","model_accounts","model_account_cooldowns","model_api_keys","model_settings","model_sign_in_flows","env_vars","import_runs","import_key_map","import_manifest","import_id_map","machine_links","machine_calls","machine_credentials","import_node_files","bodies","package_publications","credential_activations","hosted_endpoints","usage","grantee_usage","provider_receipts"]),ae={exposures:"node, object, channel",rules:"object, position",edges:"type, src, dst",unresolved_links:"src, name",revision_parents:"child, parent",canvas_meta:"key",runtime_state:"key",message_causes:"message_id",peer_ingested:"key",peer_ingested_destinations:"key",message_sequence:"id",messages:"seq",review_comment_events:"seq",audit_rows:"id",peer_outbox:"id",app_users:"uid"},ie={objects:"id",revisions:"rev_id",watches:"watch_id"},H=new Set(["daemon_owner","schema_version","schema_min_reader","ledger_migrated",te,F]);function ce(i){const a=J(A(Q(),"crtr-export-")),s=process.env.CRTR_HOME;process.env.CRTR_HOME=a,D(A(a,"runtime","nodes"),{recursive:!0});try{const o=new W(i);return o.exec("PRAGMA journal_mode = DELETE;"),o.exec("PRAGMA foreign_keys = ON;"),z(o),o.exec("DELETE FROM canvas_meta; DELETE FROM message_sequence;"),o}finally{s===void 0?delete process.env.CRTR_HOME:process.env.CRTR_HOME=s,P(a,{recursive:!0,force:!0})}}d(ce,"createEmptyDatabase");async function Re(i,a=()=>{}){const s=Z();if(Y(s))throw new Error(`${s} already exists; refusing to overwrite it`);D(A(s,".."),{recursive:!0,mode:448});const o=`${s}.exporting-${process.pid}`,_=Date.now(),t=new j.Client({connectionString:i,application_name:`crtr-export-${process.pid}`,options:ee(),types:{getTypeParser:d(((f,r)=>f===20?w=>Number(w):j.types.getTypeParser(f,r)),"getTypeParser")}});await t.connect();let u;try{if((await t.query("SELECT value FROM canvas_meta WHERE key = 'schema_version'").catch(()=>({rows:[]}))).rows.length===0)throw new Error("the Postgres database has no canvas schema; nothing to export");u=ce(o);const r=u;r.exec("PRAGMA foreign_keys = OFF;");const w=await se(t),L=[...w.keys()].filter(e=>!re.has(e)&&!C.includes(e));if(L.length>0)throw new Error(`export: Postgres tables with no export rule: ${L.join(", ")}`);await t.query("BEGIN READ ONLY ISOLATION LEVEL REPEATABLE READ");const E={};for(const[e,S]of Object.entries(ie)){const h=new Map;for(const l of(await t.query(`SELECT ${S} AS id, seq FROM ${e}`)).rows)h.set(l.id,Number(l.seq));E[e]=h}const B=E.objects;let M=0;r.exec("BEGIN");for(const e of C){const S=Date.now(),h=new Set(r.prepare(`PRAGMA table_info(${m(e)})`).all().map(n=>n.name)),l=w.get(e);if(l===void 0)throw new Error(`export: Postgres has no table ${e}`);const G=l.some(n=>n.name==="seq"),O=l.filter(n=>h.has(n.name)),K=new Set(ne[e]??[]),g=e==="objects"||e==="revisions"||e==="watches"||e==="watch_subscriptions",$=O.map(n=>n.type==="jsonb"?`${m(n.name)}::text AS ${m(n.name)}`:m(n.name));e==="watches"&&$.push("watch_id AS _watch_id"),g&&$.push("seq AS _seq");const R=O.map(n=>m(n.name)),U=r.prepare(`INSERT INTO ${m(e)} (${g?["rowid",...R]:R}) VALUES (${(g?["?",...R]:R).map(()=>"?").join(", ")})`),k=G?"seq":ae[e],b=`export_${e}`;await t.query(`DECLARE ${b} NO SCROLL CURSOR FOR SELECT ${$.join(", ")} FROM ${m(e)}${e==="canvas_meta"?` WHERE key NOT IN (${[...H].map(n=>`'${n}'`).join(", ")})`:""}${k===void 0?"":` ORDER BY ${k}`}`);let T=0;for(;;){const n=await t.query(`FETCH ${oe} FROM ${b}`);if(n.rows.length===0)break;for(const q of n.rows){const N=g?[Number(q._seq)]:[];for(const c of O){let p=q[c.name];e==="revision_parents"&&(c.name==="child"||c.name==="parent")?p=x(E.revisions,"revision",e,c.name,p):e==="watch_subscriptions"&&c.name==="watch"?p=x(E.watches,"watch",e,c.name,p):K.has(c.name)?p=x(B,"object",e,c.name,p):e==="jobs"&&(c.name==="job_dir"||c.name==="log_path")&&(p=p??""),N.push(p??null)}U.run(...N)}T+=n.rows.length}await t.query(`CLOSE ${b}`),M+=T,a(`export ${e}: ${T} rows in ${Date.now()-S} ms`)}r.exec("COMMIT"),await t.query("COMMIT");const v=r.prepare("PRAGMA foreign_key_check").all();if(v.length>0)throw new Error(`export: ${v.length} foreign key violation(s) in the exported canvas.db, first: ${JSON.stringify(v[0])}`);await pe(t,r);const y=r.prepare("PRAGMA user_version").get().user_version;if(y!==I.length)throw new Error(`export: exported canvas.db is at user_version ${y}, expected ${I.length}`);return r.close(),u=void 0,await t.query("INSERT INTO canvas_meta (key, value) VALUES ($1, $2) ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value",[F,JSON.stringify({at:new Date().toISOString(),path:s})]),X(o,s),{path:s,rows:M,ms:Date.now()-_,userVersion:y}}catch(f){await t.query("ROLLBACK").catch(()=>{});try{u?.close()}catch{}for(const r of["","-wal","-shm","-journal"])P(`${o}${r}`,{force:!0});throw f}finally{await t.end().catch(()=>{})}}d(Re,"exportPostgresToSqlite");function x(i,a,s,o,_){if(_==null)return null;const t=i.get(_);if(t===void 0)throw new Error(`export: ${s}.${o} references ${a} ${String(_)}, which was not exported (`);return t}d(x,"mapId");async function pe(i,a){const s=[];for(const o of C){const _=Number((await i.query(`SELECT count(*) AS n FROM ${m(o)}`)).rows[0].n);let t=Number(a.prepare(`SELECT count(*) AS n FROM ${m(o)}`).get().n),u=_;o==="canvas_meta"&&(u=Number((await i.query("SELECT count(*) AS n FROM canvas_meta WHERE key <> ALL($1)",[[...H]])).rows[0].n),t=Number(a.prepare("SELECT count(*) AS n FROM canvas_meta").get().n)),u!==t&&s.push(`${o}: Postgres ${u} rows, SQLite ${t}`)}if(s.length>0)throw new Error(`Postgres \u2192 SQLite export verification failed:
|
|
2
2
|
${s.join(`
|
|
3
3
|
`)}`)}d(pe,"verify");export{Re as exportPostgresToSqlite};
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
var H=Object.defineProperty;var c=(n,e)=>H(n,"name",{value:e,configurable:!0});import{randomBytes as W}from"node:crypto";import{CrtrError as
|
|
1
|
+
var H=Object.defineProperty;var c=(n,e)=>H(n,"name",{value:e,configurable:!0});import{randomBytes as W}from"node:crypto";import{CrtrError as g}from"../errors.js";import{PersonUnresolvedError as f,PersonOutsideRequestError as A,setPersonId as y,markCloudRole as v,isCloudRole as D,runAsPerson as b,personId as $,bootPersonId as k,requestPersonId as C}from"./person-state.js";import{readConfig as S}from"../config.js";import{joinedIssuer as M,joinedOwner as j}from"../directory/join.js";import{installLocalTerminalGrant as F}from"../grants/local.js";import{dropLocalGrantMirror as x}from"../grants/mirror.js";import{ownerForGrantee as G,ensureOwner as J}from"../graph/objects.js";import{canvasDatabaseUrl as q,CanvasConstraintError as B,withCanvasWrite as h}from"./db.js";import{LEGACY_LOCAL_PERSON as E,LEGACY_LOCAL_TERMINAL_GRANT as Y}from"./legacy-person.js";import{rebuildTotalsFor as z}from"../ledger/totals.js";const l="person_id",O="local_person_retired",K=/^user:[A-Za-z0-9._-]+$/,I="abcdefghijklmnopqrstuvwxyz0123456789",L=new Map;async function me(){const n=C();if(n!==void 0)return n;if(D())throw new A;const e=k();if(e!==void 0)return e;const r=await q(),t=L.get(r);if(t!==void 0)return t;const a=await Z();if(a===null)throw new f;return L.set(r,a),a}c(me,"personIdAsync");function X(){const n=W(12);let e="user:";for(let r=0;r<12;r++)e+=I[n[r]%I.length];return e}c(X,"mintPersonId");async function m(n,e){return(await n.prepare("SELECT value FROM canvas_meta WHERE key = ?").get(e))?.value??null}c(m,"readMeta");async function _(n,e,r){await n.prepare("INSERT INTO canvas_meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(e,r)}c(_,"writeMeta");async function V(){return await h(async n=>{const e=await m(n,l);if(e!==null)return{id:e,source:"stored"};const r=j();if(r!==null)return await _(n,l,r),{id:r,source:"joined"};if(S("user").runtime?.issuer){const a=await n.prepare("SELECT DISTINCT sub FROM grants").all();return a.length!==1?null:(await _(n,l,a[0].sub),{id:a[0].sub,source:"grants"})}const t=X();return await _(n,l,t),{id:t,source:"minted"}})}c(V,"resolvePerson");async function Z(){return(await V())?.id??null}c(Z,"resolvePersonId");const s=c(n=>Number(n.changes),"changes"),Q=[["nodes","sub"],["node_tokens","sub"],["grants","sub"],["crons","sub"],["audit_rows","sub"],["provider_approvals","sub"],["audit_rows","grantee"],["run_events","grantee"],["node_tokens","grantee"],["uploads","grantee"],["provider_approvals","grantee"]],ee=["profiles","profile_defaults","scope_settings","scope_bookkeeping","scope_marketplaces","scope_plugins","person_settings","model_accounts","model_account_cooldowns","model_api_keys","model_settings","model_sign_in_flows","env_vars","hosted_endpoints"],ne=[["charges","sub"],["charges","payer"],["charges","grantee"],["limits","payer"],["limits","sub"],["limits","grantee"]];function P(n,e){if(!K.test(e))throw new g("invalid_person",`${n} must be a user:<id> principal, got ${JSON.stringify(e)}`)}c(P,"assertPerson");async function re(n,e){return await n.prepare("SELECT 1 AS found FROM charge_totals WHERE payer = ? OR sub = ? OR grantee = ? UNION ALL SELECT 1 FROM charge_chunks WHERE payer = ? LIMIT 1").get(e,e,e,e)!==void 0}c(re,"namesPerson");async function U(n,e,r){if(P("from",e),P("to",r),e===r)throw new g("invalid_person","cannot substitute a person with itself");const t={};try{t.identities=s(await n.prepare("UPDATE identities SET scheme = 'user', external_id = ? WHERE scheme IN ('local-user', 'user') AND external_id = ?").run(r,e))}catch(o){throw o instanceof B?new g("person_conflict",`another person object already holds ${r}; merging two person objects is not supported (${o.message})`,void 0,{from:e,to:r}):o}t["daemon_actions.principal_sub"]=s(await n.prepare(`UPDATE daemon_actions SET adapter_json = jsonb_set(adapter_json::jsonb, '{principal,sub}', to_jsonb(?::text))::text
|
|
2
2
|
WHERE state IN ('pending', 'handed_off') AND adapter_json::jsonb ->> 'adapter' = 'cron_spawn'
|
|
3
|
-
AND adapter_json::jsonb #>> '{principal,sub}' = ?`).run(r,e));for(const[
|
|
3
|
+
AND adapter_json::jsonb #>> '{principal,sub}' = ?`).run(r,e));for(const[o,i]of Q)t[`${o}.${i}`]=s(await n.prepareUncached(`UPDATE ${o} SET ${i} = ? WHERE ${i} = ?`).run(r,e));t["idempotency_keys.grantee"]=s(await n.prepare("DELETE FROM idempotency_keys WHERE grantee = ? AND key IN (SELECT key FROM idempotency_keys WHERE grantee = ?)").run(e,r))+s(await n.prepare("UPDATE idempotency_keys SET grantee = ? WHERE grantee = ?").run(r,e));const a=e.replace(/^user:/,""),p=r.replace(/^user:/,"");t["relations.subject_id"]=s(await n.prepare(`DELETE FROM relations r WHERE r.subject_type = 'user' AND r.subject_id = ?
|
|
4
4
|
AND EXISTS (SELECT 1 FROM relations n WHERE n.subject_type = 'user' AND n.subject_id = ? AND n.resource_type = r.resource_type
|
|
5
|
-
AND n.resource_id = r.resource_id AND n.relation = r.relation AND n.subject_relation = r.subject_relation)`).run(a,p))+
|
|
6
|
-
WHERE o.type = 'node' AND i.scheme = 'local-user' AND i.external_id = '${E}'`;return(await n.prepareUncached(`${e} LIMIT 1`).get()!==void 0?
|
|
5
|
+
AND n.resource_id = r.resource_id AND n.relation = r.relation AND n.subject_relation = r.subject_relation)`).run(a,p))+s(await n.prepare("UPDATE relations SET subject_id = ? WHERE subject_type = 'user' AND subject_id = ?").run(p,a)),t["relations.written_by"]=s(await n.prepare("UPDATE relations SET written_by = ? WHERE written_by = ?").run(r,e)),t["revisions.acting_for"]=s(await n.prepare("UPDATE revisions SET acting_for = ? WHERE acting_for = ?").run(r,e));for(const[o,i]of ne)t[`${o}.${i}`]=s(await n.prepareUncached(`UPDATE ${o} SET ${i} = ? WHERE ${i} = ?`).run(r,e));for(const o of ee){const d=s(await n.prepareUncached(`DELETE FROM ${o} WHERE person = ? AND EXISTS (SELECT 1 FROM ${o} WHERE person = ?)`).run(e,r))+s(await n.prepareUncached(`UPDATE ${o} SET person = ? WHERE person = ?`).run(r,e));d!==0&&(t[`${o}.person`]=d)}const u=s(await n.prepare("UPDATE credential_activations SET person = ? WHERE person = ?").run(r,e));return u!==0&&(t["credential_activations.person"]=u),(Object.entries(t).some(([o,i])=>o.startsWith("charges.")&&i!==0)||await re(n,e))&&(await z(n,e,r),t["charge_totals.rebuilt"]=1),t}c(U,"substitutePerson");async function te(n){const e=`SELECT o.id FROM objects o JOIN identities i ON i.object = o.owner JOIN nodes n ON n.node_id = o.id
|
|
6
|
+
WHERE o.type = 'node' AND i.scheme = 'local-user' AND i.external_id = '${E}'`;return(await n.prepareUncached(`${e} LIMIT 1`).get()!==void 0?s(await n.prepareUncached(`UPDATE objects SET owner = ? WHERE id IN (${e})`).run((await G(n,"app:terminal")).id)):0)+s(await n.prepare("UPDATE node_tokens SET grantee = 'app:terminal' WHERE grantee = ?").run(E))+s(await n.prepare("UPDATE run_events SET grantee = 'app:terminal' WHERE grantee = ?").run(E))+s(await n.prepare("DELETE FROM idempotency_keys WHERE grantee = ? AND key IN (SELECT key FROM idempotency_keys WHERE grantee = 'app:terminal')").run(E))+s(await n.prepare("UPDATE idempotency_keys SET grantee = 'app:terminal' WHERE grantee = ?").run(E))}c(te,"rewriteLegacyGrantees");async function ae(n,e,r){const t=[Y,`terminal:${e}`].filter(o=>o!==r),a=t.map(()=>"?").join(", "),p={};p["nodes.grant_id"]=s(await n.prepareUncached(`UPDATE nodes SET grant_id = ? WHERE grant_id IN (${a})`).run(r,...t)),p["node_tokens.grant"]=s(await n.prepareUncached(`UPDATE node_tokens SET "grant" = ? WHERE "grant" IN (${a})`).run(r,...t)),p["crons.grant_id"]=s(await n.prepareUncached(`UPDATE crons SET grant_id = ? WHERE grant_id IN (${a})`).run(r,...t));const u=r===null?"'null'::jsonb":"to_jsonb(?::text)";return p["daemon_actions.principal_grant_id"]=s(await n.prepareUncached(`UPDATE daemon_actions SET adapter_json = jsonb_set(adapter_json::jsonb, '{principal,grant_id}', ${u})::text
|
|
7
7
|
WHERE state IN ('pending', 'handed_off') AND adapter_json::jsonb ->> 'adapter' = 'cron_spawn'
|
|
8
|
-
AND adapter_json::jsonb #>> '{principal,grant_id}' IN (${a})`).run(...r===null?[]:[r],...t)),p}c(ae,"repointGrantReferences");async function ge(){const n=await h(async e=>{const r={},t=c((
|
|
9
|
-
WHERE o.type = 'node' AND o.reception = 2 AND s.envelope_json ->> 'app' IS NULL AND i.scheme = 'app' AND i.external_id = 'app:terminal'`;if(await e.prepareUncached(`${
|
|
8
|
+
AND adapter_json::jsonb #>> '{principal,grant_id}' IN (${a})`).run(...r===null?[]:[r],...t)),p}c(ae,"repointGrantReferences");async function ge(){const n=await h(async e=>{const r={},t=c((w,T="")=>{for(const[N,R]of Object.entries(w))R!==0&&(r[T+N]=(r[T+N]??0)+R)},"add");let a=await m(e,l);if(a===null)throw new f;let p=null;const u=j();u!==null&&u!==a&&(t(await U(e,a,u),"join."),await _(e,l,u),p=a,a=u);const o=M()??S("user").runtime?.issuer,i=await m(e,"install_id");if(i===null)throw new Error("retireLocalPerson: the install id is not stored");const d=await m(e,O)!==a;if(d){t({legacy_grantees:await te(e)}),t(await U(e,E,a));const w=`SELECT o.id FROM objects o JOIN peer_stubs s ON s.object = o.id JOIN identities i ON i.object = o.owner
|
|
9
|
+
WHERE o.type = 'node' AND o.reception = 2 AND s.envelope_json ->> 'app' IS NULL AND i.scheme = 'app' AND i.external_id = 'app:terminal'`;if(await e.prepareUncached(`${w} LIMIT 1`).get()!==void 0){const T=await J(e,"person","user",a,"user");t({repaired_stubs:s(await e.prepareUncached(`UPDATE objects SET owner = ? WHERE id IN (${w})`).run(T.id))})}t({"nodes.sub_null_terminal":s(await e.prepare(`UPDATE nodes SET sub = ? WHERE sub IS NULL AND node_id IN (
|
|
10
10
|
SELECT n.node_id FROM nodes n JOIN identities i ON i.object = n.app
|
|
11
|
-
WHERE i.scheme = 'app' AND i.external_id = 'app:terminal')`).run(a))}),t(await ae(e,
|
|
11
|
+
WHERE i.scheme = 'app' AND i.external_id = 'app:terminal')`).run(a))}),t(await ae(e,i,o?null:`terminal:${i}`)),o&&t({local_grant_mirror:await x(e)}),await _(e,O,a)}return o||await F(i,a),{person:a,joinedFrom:p,retired:d,columns:r}});return y(n.person),n}c(ge,"retireLocalPerson");export{E as LEGACY_LOCAL_PERSON,A as PersonOutsideRequestError,f as PersonUnresolvedError,D as isCloudRole,v as markCloudRole,$ as personId,me as personIdAsync,V as resolvePerson,Z as resolvePersonId,ge as retireLocalPerson,b as runAsPerson,y as setPersonId,U as substitutePerson};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var se=Object.defineProperty;var o=(e,t)=>se(e,"name",{value:t,configurable:!0});import{prepared as
|
|
1
|
+
var se=Object.defineProperty;var o=(e,t)=>se(e,"name",{value:t,configurable:!0});import{prepared as p}from"../sqlite-statements.js";import{randomUUID as w}from"node:crypto";import{existsSync as f,readdirSync as de,readFileSync as ue,realpathSync as ce,statSync as _e}from"node:fs";import{join as g,resolve as pe}from"node:path";import{withCanvasWrite as E,openDb as l}from"./db.js";import{jobDir as le,nodesRoot as C}from"./paths.js";import{errorClassFromFault as B}from"../fault-classifier.js";import{parseProviderPayment as Ee,parseProviderRateLimit as fe}from"../provider-failure.js";import{emitEvent as J}from"../events/emit.js";import{operationIdContext as K,validateOperationId as Y}from"../events/operation-id.js";const $e=5*6e4,ye=500,G=["pi\u2192provider","viewer\u2194broker","relay\u2194broker","viewer\u2194crtrd","daemon\u2192node","crtr\u2192pi"],Te=[...G,"broker\u2194crtrd"],Ne=["rate-limit","overloaded","connection","auth","protocol","context-overflow","other","wedged","model-not-found"],ge=["auto","manual","fatal"],Le=["sdk","daemon","client"],me=["pending","admitted","invalidated"];function s(){return new Date().toISOString()}o(s,"now");function H(e,t){return new Set(e.prepare(`PRAGMA table_info(${t})`).all().map(({name:n})=>n))}o(H,"tableColumns");function Ae(e){const t=H(e,"executions"),n=[["turn_open_at","TEXT"],["turn_progress_at","TEXT"],["turn_closed_at","TEXT"],["turn_end_reason","TEXT CHECK (turn_end_reason IS NULL OR turn_end_reason IN ('settled', 'teardown-aborted'))"],["exit_diagnostic_json","TEXT"]];for(const[r,i]of n)t.has(r)||e.exec(`ALTER TABLE executions ADD COLUMN ${r} ${i}`)}o(Ae,"addExecutionColumns");function Se(e){e.exec(`
|
|
2
2
|
CREATE TABLE IF NOT EXISTS node_faults (
|
|
3
3
|
fault_id TEXT PRIMARY KEY,
|
|
4
4
|
node_id TEXT NOT NULL REFERENCES nodes(node_id) ON DELETE CASCADE,
|
|
@@ -23,4 +23,4 @@ CREATE TABLE IF NOT EXISTS node_faults (
|
|
|
23
23
|
);
|
|
24
24
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_node_faults_active ON node_faults(node_id) WHERE active = 1;
|
|
25
25
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_node_faults_episode ON node_faults(node_id) WHERE episode_state IS NOT NULL;
|
|
26
|
-
`)}o(Ae,"createFaultTable");function g(e,t){return typeof t=="string"&&e.includes(t)}o(g,"contains");function W(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(W,"isRecord");function q(e){if(!W(e)||typeof e.provider!="string"||e.provider===""||typeof e.model!="string"||e.model==="")return;const t=typeof e.status=="number"&&Number.isFinite(e.status)?e.status:void 0,n=typeof e.code=="string"||typeof e.code=="number"?e.code:void 0,r=typeof e.errno=="string"?e.errno:void 0,i=typeof e.body=="string"?e.body:void 0,a=Ee(e.ratelimit),d=Array.isArray(e.causes)?e.causes.flatMap(s=>{if(!W(s))return[];const E={...typeof s.message=="string"?{message:s.message}:{},...typeof s.status=="number"&&Number.isFinite(s.status)?{status:s.status}:{},...typeof s.code=="string"||typeof s.code=="number"?{code:s.code}:{},...typeof s.errno=="string"?{errno:s.errno}:{},...typeof s.body=="string"?{body:s.body}:{}};return Object.keys(E).length===0?[]:[E]}):void 0;return{provider:e.provider,model:e.model,...t===void 0?{}:{status:t},...n===void 0?{}:{code:n},...r===void 0?{}:{errno:r},...i===void 0?{}:{body:i},...d===void 0||d.length===0?{}:{causes:d},...a===void 0?{}:{ratelimit:a}}}o(q,"parseProviderError");function V(e){try{const t=JSON.parse(e);if(!g(ye,t.link)||typeof t.op!="string"||t.op===""||!g(Te,t.kind)||typeof t.message!="string"||typeof t.since!="string")return null;const n=Y(t.operation_id);if(!W(t.retry)||!g(Ne,t.retry.disposition)||t.retry.by!==void 0&&!g(ge,t.retry.by)||t.retry.attempt!==void 0&&typeof t.retry.attempt!="number"||t.retry.max!==void 0&&typeof t.retry.max!="number"||t.retry.nextAt!==void 0&&typeof t.retry.nextAt!="string"||t.anchorEntryId!==void 0&&(typeof t.anchorEntryId!="string"||t.anchorEntryId===""))return null;const r=t.providerError===void 0?void 0:q(t.providerError);return t.providerError!==void 0&&r===void 0?null:{link:t.link,op:t.op,kind:t.kind,retry:{disposition:t.retry.disposition,...t.retry.by===void 0?{}:{by:t.retry.by},...t.retry.attempt===void 0?{}:{attempt:t.retry.attempt},...t.retry.max===void 0?{}:{max:t.retry.max},...t.retry.nextAt===void 0?{}:{nextAt:t.retry.nextAt}},message:t.message,since:t.since,operation_id:n,...t.anchorEntryId===void 0?{}:{anchorEntryId:t.anchorEntryId},...r===void 0?{}:{providerError:r}}}catch{return null}}o(V,"parseLegacyFault");function Se(e){const t=pe(e);try{return ce(t)}catch{return t}}o(Se,"canonicalPath");function Re(e){try{const t=JSON.parse(e);if(!g(Le,t.state)||typeof t.sessionFile!="string"||t.sessionFile==="")return null;const n=JSON.stringify(t.fault),r=V(n);if(r===null||r.link!=="pi\u2192provider"||r.retry.disposition!=="auto"||r.retry.by!=="daemon")return null;const i=t.anchorEntryId;return i!==null&&typeof i!="string"||(r.anchorEntryId??null)!==i?null:{state:t.state,sessionFile:Se(t.sessionFile),fault:r}}catch{return null}}o(Re,"parseLegacyEpisode");function Q(e){return e!==void 0?Y(e):K.current()??K.fresh(n=>n)}o(Q,"resolveOperationId");function xe(e){return e.slice(0,fe)}o(xe,"clampMessage");function w(e){return e.link==="pi\u2192provider"&&e.retry.disposition==="auto"&&e.retry.by==="daemon"?3:e.retry.disposition==="fatal"?2:1}o(w,"faultPriority");function z(e){return{link:e.link,op:e.op,kind:e.kind,message:e.message,since:e.since,operationId:e.operation_id,anchorEntryId:e.anchorEntryId??null,retryDisposition:e.retry.disposition,retryBy:e.retry.by??null,retryAttempt:e.retry.attempt??null,retryMax:e.retry.max??null,retryNextAt:e.retry.nextAt??null,providerError:e.providerError===void 0?null:JSON.stringify(e.providerError)}}o(z,"encodeFault");function b(e){const t=e.provider_error_json,n=typeof t=="string"?q(JSON.parse(t)):void 0;if(typeof t=="string"&&n===void 0)throw new Error(`invalid provider error on stored fault ${e.fault_id}`);const r={disposition:e.retry_disposition,...e.retry_by===null?{}:{by:e.retry_by},...e.retry_attempt===null?{}:{attempt:e.retry_attempt},...e.retry_max===null?{}:{max:e.retry_max},...e.retry_next_at===null?{}:{nextAt:e.retry_next_at}};return{faultId:e.fault_id,link:e.link,op:e.op,kind:e.kind,message:e.message,since:e.since,operation_id:e.operation_id,retry:r,...e.anchor_entry_id===null?{}:{anchorEntryId:e.anchor_entry_id},...n===void 0?{}:{providerError:n},...typeof e.notified_since=="string"?{notifiedSince:e.notified_since}:{}}}o(b,"hydrateFault");async function L(e,t){const n=await e.prepare("SELECT * FROM node_faults WHERE node_id = ? AND active = 1").get(t);return n===void 0?null:b(n)}o(L,"activeFault");function P(e){if(!g(G,e.link))throw new Error(`fault link is not durable: ${e.link}`);return{link:e.link,op:e.op,kind:e.kind,retry:e.retry,message:xe(e.message),since:e.since??u(),operation_id:Q(e.operation_id),...typeof e.anchorEntryId=="string"&&e.anchorEntryId!==""?{anchorEntryId:e.anchorEntryId}:{},...e.providerError===void 0?{}:{providerError:e.providerError}}}o(P,"storedFault");function M(e,t){J({level:t.retry.disposition==="fatal"?"error":"warn",event:"fault.recorded",operation_id:t.operation_id,node_id:e,error_class:B(t),fields:{link:t.link,op:t.op,kind:t.kind,retry:t.retry,message:t.message,...t.anchorEntryId===void 0?{}:{anchor_entry_id:t.anchorEntryId},...t.providerError===void 0?{}:{provider_error:t.providerError}}})}o(M,"emitRecordedFault");const Z="INSERT INTO node_faults (fault_id, node_id, link, op, kind, message, since, operation_id, anchor_entry_id, retry_disposition, retry_by, retry_attempt, retry_max, retry_next_at, provider_error_json, active, episode_state, episode_binding_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";function ee(e,t,n,r,i){const a=z(n),d=u();return[e,t,a.link,a.op,a.kind,a.message,a.since,a.operationId,a.anchorEntryId,a.retryDisposition,a.retryBy,a.retryAttempt,a.retryMax,a.retryNextAt,a.providerError,r?1:0,i?.state??null,i?.bindingId??null,d,d]}o(ee,"faultInsertParams");async function te(e,t,n,r,i){const a=I();return await e.prepare(Z).run(...ee(a,t,n,r,i)),{...n,faultId:a}}o(te,"insertFault");async function D(e,t,n,r){const i=z(n);return await e.prepare("UPDATE node_faults SET link = ?, op = ?, kind = ?, message = ?, since = ?, operation_id = ?, anchor_entry_id = ?, retry_disposition = ?, retry_by = ?, retry_attempt = ?, retry_max = ?, retry_next_at = ?, provider_error_json = ?, episode_state = COALESCE(?, episode_state), episode_binding_id = COALESCE(?, episode_binding_id), updated_at = ? WHERE fault_id = ?").run(i.link,i.op,i.kind,i.message,i.since,i.operationId,i.anchorEntryId,i.retryDisposition,i.retryBy,i.retryAttempt,i.retryMax,i.retryNextAt,i.providerError,r?.state??null,r?.bindingId??null,u(),t),{...n,faultId:t}}o(D,"updateFault");async function U(e,t){await e.prepare("DELETE FROM node_faults WHERE fault_id = ? AND active = 0 AND episode_state IS NULL").run(t)}o(U,"deleteIfUnretained");async function ne(e,t,n,r){const i=await L(e,t);if(i===null){const a=await e.prepare("SELECT fault_id, link, kind, since, operation_id FROM node_faults WHERE node_id = ? AND active = 0 AND episode_state IS NOT NULL").get(t);return a!==void 0&&a.link===n.link&&a.kind===n.kind&&a.since===n.since&&a.operation_id===n.operation_id?(await e.prepare("UPDATE node_faults SET active = 1, updated_at = ? WHERE fault_id = ?").run(u(),a.fault_id),await D(e,a.fault_id,n)):await te(e,t,n,!0,r)}if(i.link===n.link&&i.kind===n.kind){const a=n.retry.disposition==="auto"?{...i.retry,...n.retry}:n.retry,d=i.retry.disposition===n.retry.disposition&&(n.retry.disposition!=="fatal"||i.message===n.message),s=d?i.since:n.since,E=await D(e,i.faultId,{...n,since:s,anchorEntryId:n.anchorEntryId??i.anchorEntryId,retry:a},r);return d||await e.prepare("UPDATE node_faults SET notified_since = NULL WHERE fault_id = ?").run(i.faultId),E}return i.link!==n.link&&w(i)>w(n)?null:(await e.prepare("UPDATE node_faults SET active = 0, updated_at = ? WHERE fault_id = ?").run(u(),i.faultId),await U(e,i.faultId),await te(e,t,n,!0,r))}o(ne,"replaceActiveFault");async function m(e,t,n){return(await e.prepare("SELECT binding_id FROM sessions WHERE node_id = ? AND session_id = ? AND unbound_at IS NULL").get(t,n))?.binding_id??null}o(m,"liveBinding");async function $e(e,t){return await l(async n=>{const r=u();return(await n.prepare("UPDATE executions SET turn_progress_at = ? WHERE execution_id = ? AND state != 'exited' AND turn_open_at IS NOT NULL AND turn_closed_at IS NULL").run(r,e)).changes>0?!0:(await n.prepare("UPDATE executions SET turn_open_at = ?, turn_progress_at = ?, turn_closed_at = NULL, turn_end_reason = NULL WHERE execution_id = ? AND state != 'exited'").run(r,r,e)).changes>0})}o($e,"openTurn");async function je(e){return(await(await p()).prepare("UPDATE executions SET turn_progress_at = ? WHERE execution_id = ? AND state != 'exited' AND turn_open_at IS NOT NULL AND turn_closed_at IS NULL").run(u(),e)).changes>0}o(je,"recordTurnProgress");async function Be(e,t){return await l(async n=>{const r=u(),i=(await n.prepare("UPDATE executions SET turn_closed_at = ?, turn_end_reason = ? WHERE execution_id = ? AND state != 'exited' AND turn_open_at IS NOT NULL AND turn_closed_at IS NULL").run(r,t.endReason,e)).changes>0;if(i&&t.endReason==="settled"){const a="(SELECT node_id FROM executions WHERE execution_id = ?)";t.viewerPresent===!0?await n.prepare(`UPDATE nodes SET reply_at = ?, read_at = ? WHERE node_id = ${a}`).run(r,r,e):await n.prepare(`UPDATE nodes SET reply_at = ? WHERE node_id = ${a}`).run(r,e)}return i})}o(Be,"closeTurn");async function Je(e){return(await(await p()).prepare("UPDATE nodes SET read_at = ? WHERE node_id = ?").run(u(),e)).changes>0}o(Je,"markNodeRead");function re(e){return JSON.stringify({schema:"crtr.execution-exit-diagnostic/v1",...e})}o(re,"exitDiagnosticJson");async function Ke(e,t){if(!Number.isInteger(t.consecutivePasses)||t.consecutivePasses<1||t.routes.length===0||!t.routes.every(n=>n!==""))throw new Error("invalid transport-poison verdict");return(await(await p()).prepare("UPDATE executions SET exit_diagnostic_json = ? WHERE execution_id = ? AND state != 'exited'").run(re({transport_poison:{consecutive_passes:t.consecutivePasses,routes:t.routes}}),e)).changes>0}o(Ke,"recordTransportPoisonVerdict");async function Ye(e){const t=await(await p()).prepare("SELECT exit_diagnostic_json FROM executions WHERE node_id = ? ORDER BY seq DESC LIMIT 1").get(e);if(t===void 0||t.exit_diagnostic_json===null)return null;try{const n=JSON.parse(t.exit_diagnostic_json),r=n.transport_poison;return n.schema!=="crtr.execution-exit-diagnostic/v1"||r===void 0||!Number.isInteger(r.consecutive_passes)||r.consecutive_passes<1||!Array.isArray(r.routes)||r.routes.length===0||!r.routes.every(i=>typeof i=="string"&&i!=="")?null:{consecutivePasses:r.consecutive_passes,routes:r.routes}}catch{return null}}o(Ye,"readTransportPoisonVerdict");async function Ge(e){const t=await(await p()).prepare("SELECT turn_open_at, turn_closed_at, turn_progress_at FROM executions WHERE node_id = ? AND state != 'exited'").get(e);return t===void 0?null:{busy:t.turn_open_at!==null&&t.turn_closed_at===null,progressAt:t.turn_progress_at}}o(Ge,"readLiveTurn");async function qe(e){const t=await p(),n=await t.prepare("SELECT turn_closed_at, turn_progress_at FROM executions WHERE node_id = ? AND turn_open_at IS NOT NULL ORDER BY seq DESC LIMIT 1").get(e);if(n===void 0)return null;const r=await t.prepare("SELECT turn_end_reason FROM executions WHERE node_id = ? ORDER BY seq DESC LIMIT 1").get(e);return{interrupted:n.turn_closed_at===null||r?.turn_end_reason==="teardown-aborted",progressAt:n.turn_progress_at}}o(qe,"readInterruptedTurn");async function Ve(e){return await(await p()).prepare("SELECT 1 FROM executions WHERE node_id = ? AND turn_open_at IS NOT NULL LIMIT 1").get(e)!==void 0}o(Ve,"hasAdmittedTurn");async function Qe(e,t){const n=P(t);return M(e,n),await l(async r=>await ne(r,e,n))}o(Qe,"recordFault");async function ze(e){return await l(async t=>(await t.prepare("UPDATE node_faults SET notified_since = since, updated_at = ? WHERE fault_id = ?").run(u(),e)).changes>0)}o(ze,"markFaultNotified");function Ie(e){return e.link==="pi\u2192provider"&&e.retry.disposition==="fatal"&&e.notifiedSince!==e.since}o(Ie,"isUnnotifiedFatalProviderFault");async function Ze(){return(await(await p()).prepare("SELECT f.node_id FROM node_faults f JOIN nodes n ON n.node_id = f.node_id WHERE f.active = 1 AND f.link = 'pi\u2192provider' AND f.retry_disposition = 'fatal' AND (f.notified_since IS NULL OR f.notified_since != f.since) AND n.status IN ('active', 'idle')").all()).map(e=>e.node_id)}o(Ze,"listUnnotifiedFatalFaultNodes");let X=null;function et(e){X=e}o(et,"setFatalFaultAnnouncer");async function tt(e,t){const n=await L(await p(),e);return n===null||t?.link!==void 0&&n.link!==t.link?!1:await l(async r=>{const i=await L(r,e);if(i===null||t?.link!==void 0&&i.link!==t.link)return!1;X!==null&&Ie(i)&&await X(e);const a=await r.prepare("SELECT episode_state FROM node_faults WHERE fault_id = ?").get(i.faultId);await r.prepare("UPDATE node_faults SET active = 0, updated_at = ? WHERE fault_id = ?").run(u(),i.faultId),a.episode_state==="pending"&&t?.preserveEpisode!==!0&&await r.prepare("UPDATE node_faults SET episode_state = NULL, episode_binding_id = NULL, updated_at = ? WHERE fault_id = ?").run(u(),i.faultId),await U(r,i.faultId);const d=Q();return J({level:"info",event:"fault.cleared",operation_id:d,node_id:e,error_class:B(i),fields:{cleared_fault_operation_id:i.operation_id,link:i.link,op:i.op,kind:i.kind,retry:i.retry,message:i.message,since:i.since,...i.anchorEntryId===void 0?{}:{anchor_entry_id:i.anchorEntryId}}}),!0})}o(tt,"clearFault");async function ie(e){return await L(await p(),e)}o(ie,"readFault");async function nt(e,t){const n=P(t.input);if(n.link!=="pi\u2192provider"||n.retry.disposition!=="auto"||n.retry.by!=="daemon")throw new Error("provider retry episode requires an automatic daemon provider fault");return M(e,n),await l(async r=>{const i=await m(r,e,t.sessionId);if(i===null)return null;const a=await L(r,e);if(a!==null&&(a.link!==n.link||a.kind!==n.kind)&&w(a)>w(n))return null;const d=await r.prepare("SELECT fault_id FROM node_faults WHERE node_id = ? AND episode_state IS NOT NULL").all(e);await r.prepare("UPDATE node_faults SET episode_state = NULL, episode_binding_id = NULL, updated_at = ? WHERE node_id = ? AND episode_state IS NOT NULL").run(u(),e);for(const E of d)await U(r,E.fault_id);const s=await ne(r,e,n,{state:"pending",bindingId:i});return s===null?null:(await r.prepare("UPDATE node_faults SET episode_state = ?, episode_binding_id = ?, updated_at = ? WHERE fault_id = ?").run("pending",i,u(),s.faultId),s)})}o(nt,"recordPendingEpisode");async function rt(e,t){return await l(async n=>{if(await n.prepare("SELECT 1 FROM nodes WHERE node_id = ? AND intent = 'refresh'").get(e)!==void 0)return!1;const r=await m(n,e,t.sessionId);return r===null?!1:(await n.prepare("UPDATE node_faults SET episode_state = 'admitted', retry_disposition = ?, retry_by = ?, retry_attempt = ?, retry_max = ?, retry_next_at = ?, updated_at = ? WHERE node_id = ? AND fault_id = ? AND episode_state = 'pending' AND episode_binding_id = ?").run(t.retry.disposition,t.retry.by??null,t.retry.attempt??null,t.retry.max??null,t.retry.nextAt??null,u(),e,t.faultId,r)).changes>0})}o(rt,"admitEpisode");async function it(e,t){const n=P(t.fault);return await l(async r=>{const i=await m(r,e,t.sessionId);return i===null||(await L(r,e))?.faultId!==t.faultId||await r.prepare("SELECT 1 FROM node_faults WHERE node_id = ? AND fault_id = ? AND episode_state = 'admitted' AND episode_binding_id = ?").get(e,t.faultId,i)===void 0?!1:(M(e,n),t.reopen?await D(r,t.faultId,n,{state:"pending",bindingId:i}):(await D(r,t.faultId,n),await r.prepare("UPDATE node_faults SET episode_state = NULL, episode_binding_id = NULL, updated_at = ? WHERE fault_id = ?").run(u(),t.faultId),await r.prepare("UPDATE node_faults SET notified_since = NULL WHERE fault_id = ?").run(t.faultId)),!0)})}o(it,"settleRejectedEpisode");async function ot(e,t){return await l(async n=>{const r=await m(n,e,t.sessionId);return r===null?!1:(await n.prepare("UPDATE node_faults SET episode_state = 'pending', updated_at = ? WHERE node_id = ? AND episode_state = 'admitted' AND episode_binding_id = ?").run(u(),e,r)).changes>0})}o(ot,"reopenEpisode");async function at(e,t){return await l(async n=>{const r=await m(n,e,t.sessionId);return r===null?!1:(await n.prepare("UPDATE node_faults SET episode_state = 'invalidated', updated_at = ? WHERE node_id = ? AND episode_state != 'invalidated' AND episode_state IS NOT NULL AND episode_binding_id = ?").run(u(),e,r)).changes>0})}o(at,"invalidateEpisode");async function st(e,t){return await l(async n=>{const r=await m(n,e,t.sessionId);if(r===null)return!1;const i=await n.prepare("SELECT fault_id FROM node_faults WHERE node_id = ? AND episode_binding_id = ? AND episode_state IS NOT NULL").all(e,r);if(i.length===0)return!1;await n.prepare("UPDATE node_faults SET episode_state = NULL, episode_binding_id = NULL, updated_at = ? WHERE node_id = ? AND episode_binding_id = ? AND episode_state IS NOT NULL").run(u(),e,r);for(const a of i)await U(n,a.fault_id);return!0})}o(st,"clearEpisode");async function dt(e){const t=await(await p()).prepare("SELECT f.*, s.session_id FROM node_faults f JOIN sessions s ON s.binding_id = f.episode_binding_id WHERE f.node_id = ? AND f.episode_state IS NOT NULL").get(e);return t===void 0?null:{state:t.episode_state,sessionId:t.session_id,fault:b(t)}}o(dt,"readEpisode");async function ut(){return(await(await p()).prepare("SELECT f.*, s.session_id AS bound_session_id FROM node_faults f JOIN sessions s ON s.binding_id = f.episode_binding_id WHERE f.active = 1 AND f.episode_state = 'pending' AND s.unbound_at IS NULL AND s.session_id IS NOT NULL AND f.link = 'pi\u2192provider' AND f.retry_disposition = 'auto' AND f.retry_by = 'daemon' AND f.kind IN ('connection', 'rate-limit', 'overloaded')").all()).map(t=>({nodeId:t.node_id,sessionId:t.bound_session_id,fault:b(t),updatedAt:t.updated_at,nudgedAt:t.nudged_at??null}))}o(ut,"listPendingProviderRetries");async function ct(e,t,n){return(await(await p()).prepare("UPDATE node_faults SET nudged_at = ? WHERE fault_id = ? AND active = 1 AND episode_state = 'pending' AND (nudged_at IS NULL OR nudged_at <= ?)").run(new Date(t).toISOString(),e,new Date(t-n).toISOString())).changes===1}o(ct,"claimFaultNudge");async function _t(e){const t=await ie(e)===null;return{async explanation(){if(!t)return null;const n=await ie(e);if(n===null||n.link!=="crtr\u2192pi"||n.retry.disposition!=="fatal")return null;const r=n.op.trim(),i=n.message.trim();return r===""||i===""?null:`${r}: ${i}`}}}o(_t,"beginBootFaultAttempt");function oe(e,t){try{return _e(e).mtime.toISOString()}catch{return t}}o(oe,"markerMtime");function $(e,t){if(!f(e))return null;try{return ue(e,"utf8")}catch(n){if(!t)return null;throw new Error(`cannot import recovery input ${e}: ${n.message}`)}}o($,"legacyFile");function we(e,t){return _(e,"SELECT execution_id, started_at FROM executions WHERE node_id = ? ORDER BY rowid DESC LIMIT 1").get(t)??null}o(we,"latestExecution");function De(e,t){const r=H(e,"nodes").has("launched_at")?_(e,"SELECT COALESCE(launched_at, created) AS started_at FROM nodes WHERE node_id = ?").get(t):_(e,"SELECT created AS started_at FROM nodes WHERE node_id = ?").get(t);if(r===void 0)throw new Error(`cannot import recovery witness for unknown node ${t}`);const i=I();return _(e,"INSERT INTO executions (execution_id, node_id, daemon_epoch, pid, process_identity, state, started_at, ended_at, exit_reason) VALUES (?, ?, NULL, NULL, NULL, 'exited', ?, ?, 'pre-consolidation')").run(i,t,r.started_at,r.started_at),{execution_id:i,started_at:r.started_at}}o(De,"syntheticExecution");function ae(e,t,n,r,i){const a=I();return _(e,Z).run(...ee(a,t,n,r,i)),{...n,faultId:a}}o(ae,"insertMigratedFault");function Ue(e,t,n,r){const i=_(e,"SELECT binding_id, node_id FROM sessions WHERE transcript_path = ? AND unbound_at IS NULL").get(n);if(i!==void 0){if(i.node_id!==t)throw new Error(`cannot import provider retry ${r}: transcript is live-owned by ${i.node_id}`);return i.binding_id}const a=_(e,"SELECT binding_id FROM sessions WHERE node_id = ? AND transcript_path = ? ORDER BY rowid DESC LIMIT 1").get(t,n);if(a!==void 0)return a.binding_id;const d=_(e,"SELECT created FROM nodes WHERE node_id = ?").get(t);if(d===void 0)throw new Error(`cannot import provider retry ${r}: unknown node ${t}`);const s=I();return _(e,"INSERT INTO sessions (binding_id, session_id, node_id, transcript_path, source_session_id, fork_entry_id, created_at, bound_at, unbound_at) VALUES (?, NULL, ?, ?, NULL, NULL, ?, ?, ?)").run(s,t,n,d.created,d.created,u()),s}o(Ue,"migrationBinding");function pt(e){e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'node_faults'").get()!==void 0&&(H(e,"node_faults").has("notified_since")||e.exec("ALTER TABLE node_faults ADD COLUMN notified_since TEXT"))}o(pt,"addFaultNotifiedSince");function lt(e){if(me(e),Ae(e),!f(C()))return;const t=de(C(),{withFileTypes:!0}).filter(r=>r.isDirectory()).sort((r,i)=>r.name.localeCompare(i.name)),n=_(e,"SELECT 1 FROM nodes WHERE node_id = ?");for(const r of t){const i=r.name,a=le(i),d=N(a,"busy"),s=N(a,"clean-abort"),E=N(a,"transport-poison.json"),O=N(a,"fault"),A=N(a,"provider-retry"),h=f(d),k=f(s);if(!h&&!k&&!f(E)&&!f(O)&&!f(A)||!f(N(C(),i,"meta.json"))&&n.get(i)===void 0)continue;const v=$(E,!1),S=$(O,!0),R=$(A,!0);if(!h&&!k&&v===null&&S===null&&R===null)continue;let y=we(e,i);if(y===null&&(y=De(e,i)),h){const c=oe(d,y.started_at);_(e,"UPDATE executions SET turn_open_at = ?, turn_progress_at = ?, turn_closed_at = NULL, turn_end_reason = NULL WHERE execution_id = ?").run(c,c,y.execution_id)}else if(k){const c=oe(s,y.started_at);_(e,"UPDATE executions SET turn_open_at = ?, turn_progress_at = ?, turn_closed_at = ?, turn_end_reason = 'teardown-aborted' WHERE execution_id = ?").run(c,c,c,y.execution_id)}if(v!==null)try{const c=JSON.parse(v);Number.isInteger(c.consecutivePasses)&&c.consecutivePasses>=1&&Array.isArray(c.routes)&&c.routes.length>0&&c.routes.every(j=>typeof j=="string"&&j!=="")&&_(e,"UPDATE executions SET exit_diagnostic_json = ? WHERE execution_id = ?").run(re({transport_poison:{consecutive_passes:c.consecutivePasses,routes:c.routes}}),y.execution_id)}catch{}const x=S===null?null:V(S);if(S!==null&&x===null)throw new Error(`cannot import recovery fault ${O}`);const T=R===null?null:Re(R);if(R!==null&&T===null)throw new Error(`cannot import provider retry ${A}`);let F=x===null||x.link==="broker\u2194crtrd"?null:ae(e,i,x,!0);if(T!==null){const c=Ue(e,i,T.sessionFile,A);F!==null&&F.since===T.fault.since?_(e,"UPDATE node_faults SET episode_state = ?, episode_binding_id = ?, updated_at = ? WHERE fault_id = ?").run(T.state,c,u(),F.faultId):ae(e,i,T.fault,!1,{state:T.state,bindingId:c})}}}o(lt,"migrateRecoveryWitnesses");export{Xe as FAULT_QUIET_MS,pt as addFaultNotifiedSince,rt as admitEpisode,_t as beginBootFaultAttempt,ct as claimFaultNudge,st as clearEpisode,tt as clearFault,Be as closeTurn,re as exitDiagnosticJson,Ve as hasAdmittedTurn,b as hydrateFault,at as invalidateEpisode,ut as listPendingProviderRetries,Ze as listUnnotifiedFatalFaultNodes,ze as markFaultNotified,Je as markNodeRead,lt as migrateRecoveryWitnesses,$e as openTurn,q as parseProviderError,dt as readEpisode,ie as readFault,qe as readInterruptedTurn,Ge as readLiveTurn,Ye as readTransportPoisonVerdict,Qe as recordFault,nt as recordPendingEpisode,Ke as recordTransportPoisonVerdict,je as recordTurnProgress,ot as reopenEpisode,et as setFatalFaultAnnouncer,it as settleRejectedEpisode};
|
|
26
|
+
`)}o(Se,"createFaultTable");function L(e,t){return typeof t=="string"&&e.includes(t)}o(L,"contains");function W(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(W,"isRecord");function q(e){if(!W(e)||typeof e.provider!="string"||e.provider===""||typeof e.model!="string"||e.model==="")return;const t=typeof e.status=="number"&&Number.isFinite(e.status)?e.status:void 0,n=typeof e.code=="string"||typeof e.code=="number"?e.code:void 0,r=typeof e.errno=="string"?e.errno:void 0,i=typeof e.body=="string"?e.body:void 0,a=fe(e.ratelimit),d=Ee(e.payment),_=Array.isArray(e.causes)?e.causes.flatMap(u=>{if(!W(u))return[];const N={...typeof u.message=="string"?{message:u.message}:{},...typeof u.status=="number"&&Number.isFinite(u.status)?{status:u.status}:{},...typeof u.code=="string"||typeof u.code=="number"?{code:u.code}:{},...typeof u.errno=="string"?{errno:u.errno}:{},...typeof u.body=="string"?{body:u.body}:{}};return Object.keys(N).length===0?[]:[N]}):void 0;return{provider:e.provider,model:e.model,...t===void 0?{}:{status:t},...n===void 0?{}:{code:n},...r===void 0?{}:{errno:r},...i===void 0?{}:{body:i},..._===void 0||_.length===0?{}:{causes:_},...a===void 0?{}:{ratelimit:a},...d===void 0?{}:{payment:d}}}o(q,"parseProviderError");function V(e){try{const t=JSON.parse(e);if(!L(Te,t.link)||typeof t.op!="string"||t.op===""||!L(Ne,t.kind)||typeof t.message!="string"||typeof t.since!="string")return null;const n=Y(t.operation_id);if(!W(t.retry)||!L(ge,t.retry.disposition)||t.retry.by!==void 0&&!L(Le,t.retry.by)||t.retry.attempt!==void 0&&typeof t.retry.attempt!="number"||t.retry.max!==void 0&&typeof t.retry.max!="number"||t.retry.nextAt!==void 0&&typeof t.retry.nextAt!="string"||t.anchorEntryId!==void 0&&(typeof t.anchorEntryId!="string"||t.anchorEntryId===""))return null;const r=t.providerError===void 0?void 0:q(t.providerError);return t.providerError!==void 0&&r===void 0?null:{link:t.link,op:t.op,kind:t.kind,retry:{disposition:t.retry.disposition,...t.retry.by===void 0?{}:{by:t.retry.by},...t.retry.attempt===void 0?{}:{attempt:t.retry.attempt},...t.retry.max===void 0?{}:{max:t.retry.max},...t.retry.nextAt===void 0?{}:{nextAt:t.retry.nextAt}},message:t.message,since:t.since,operation_id:n,...t.anchorEntryId===void 0?{}:{anchorEntryId:t.anchorEntryId},...r===void 0?{}:{providerError:r}}}catch{return null}}o(V,"parseLegacyFault");function Re(e){const t=pe(e);try{return ce(t)}catch{return t}}o(Re,"canonicalPath");function xe(e){try{const t=JSON.parse(e);if(!L(me,t.state)||typeof t.sessionFile!="string"||t.sessionFile==="")return null;const n=JSON.stringify(t.fault),r=V(n);if(r===null||r.link!=="pi\u2192provider"||r.retry.disposition!=="auto"||r.retry.by!=="daemon")return null;const i=t.anchorEntryId;return i!==null&&typeof i!="string"||(r.anchorEntryId??null)!==i?null:{state:t.state,sessionFile:Re(t.sessionFile),fault:r}}catch{return null}}o(xe,"parseLegacyEpisode");function Q(e){return e!==void 0?Y(e):K.current()??K.fresh(n=>n)}o(Q,"resolveOperationId");function Ie(e){return e.slice(0,ye)}o(Ie,"clampMessage");function D(e){return e.link==="pi\u2192provider"&&e.retry.disposition==="auto"&&e.retry.by==="daemon"?3:e.retry.disposition==="fatal"?2:1}o(D,"faultPriority");function z(e){return{link:e.link,op:e.op,kind:e.kind,message:e.message,since:e.since,operationId:e.operation_id,anchorEntryId:e.anchorEntryId??null,retryDisposition:e.retry.disposition,retryBy:e.retry.by??null,retryAttempt:e.retry.attempt??null,retryMax:e.retry.max??null,retryNextAt:e.retry.nextAt??null,providerError:e.providerError===void 0?null:JSON.stringify(e.providerError)}}o(z,"encodeFault");function b(e){const t=e.provider_error_json,n=typeof t=="string"?q(JSON.parse(t)):void 0;if(typeof t=="string"&&n===void 0)throw new Error(`invalid provider error on stored fault ${e.fault_id}`);const r={disposition:e.retry_disposition,...e.retry_by===null?{}:{by:e.retry_by},...e.retry_attempt===null?{}:{attempt:e.retry_attempt},...e.retry_max===null?{}:{max:e.retry_max},...e.retry_next_at===null?{}:{nextAt:e.retry_next_at}};return{faultId:e.fault_id,link:e.link,op:e.op,kind:e.kind,message:e.message,since:e.since,operation_id:e.operation_id,retry:r,...e.anchor_entry_id===null?{}:{anchorEntryId:e.anchor_entry_id},...n===void 0?{}:{providerError:n},...typeof e.notified_since=="string"?{notifiedSince:e.notified_since}:{}}}o(b,"hydrateFault");async function m(e,t){const n=await e.prepare("SELECT * FROM node_faults WHERE node_id = ? AND active = 1").get(t);return n===void 0?null:b(n)}o(m,"activeFault");function P(e){if(!L(G,e.link))throw new Error(`fault link is not durable: ${e.link}`);return{link:e.link,op:e.op,kind:e.kind,retry:e.retry,message:Ie(e.message),since:e.since??s(),operation_id:Q(e.operation_id),...typeof e.anchorEntryId=="string"&&e.anchorEntryId!==""?{anchorEntryId:e.anchorEntryId}:{},...e.providerError===void 0?{}:{providerError:e.providerError}}}o(P,"storedFault");function M(e,t){J({level:t.retry.disposition==="fatal"?"error":"warn",event:"fault.recorded",operation_id:t.operation_id,node_id:e,error_class:B(t),fields:{link:t.link,op:t.op,kind:t.kind,retry:t.retry,message:t.message,...t.anchorEntryId===void 0?{}:{anchor_entry_id:t.anchorEntryId},...t.providerError===void 0?{}:{provider_error:t.providerError}}})}o(M,"emitRecordedFault");const Z="INSERT INTO node_faults (fault_id, node_id, link, op, kind, message, since, operation_id, anchor_entry_id, retry_disposition, retry_by, retry_attempt, retry_max, retry_next_at, provider_error_json, active, episode_state, episode_binding_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";function ee(e,t,n,r,i){const a=z(n),d=s();return[e,t,a.link,a.op,a.kind,a.message,a.since,a.operationId,a.anchorEntryId,a.retryDisposition,a.retryBy,a.retryAttempt,a.retryMax,a.retryNextAt,a.providerError,r?1:0,i?.state??null,i?.bindingId??null,d,d]}o(ee,"faultInsertParams");async function te(e,t,n,r,i){const a=w();return await e.prepare(Z).run(...ee(a,t,n,r,i)),{...n,faultId:a}}o(te,"insertFault");async function U(e,t,n,r){const i=z(n);return await e.prepare("UPDATE node_faults SET link = ?, op = ?, kind = ?, message = ?, since = ?, operation_id = ?, anchor_entry_id = ?, retry_disposition = ?, retry_by = ?, retry_attempt = ?, retry_max = ?, retry_next_at = ?, provider_error_json = ?, episode_state = COALESCE(?, episode_state), episode_binding_id = COALESCE(?, episode_binding_id), updated_at = ? WHERE fault_id = ?").run(i.link,i.op,i.kind,i.message,i.since,i.operationId,i.anchorEntryId,i.retryDisposition,i.retryBy,i.retryAttempt,i.retryMax,i.retryNextAt,i.providerError,r?.state??null,r?.bindingId??null,s(),t),{...n,faultId:t}}o(U,"updateFault");async function O(e,t){await e.prepare("DELETE FROM node_faults WHERE fault_id = ? AND active = 0 AND episode_state IS NULL").run(t)}o(O,"deleteIfUnretained");async function ne(e,t,n,r){const i=await m(e,t);if(i===null){const a=await e.prepare("SELECT fault_id, link, kind, since, operation_id FROM node_faults WHERE node_id = ? AND active = 0 AND episode_state IS NOT NULL").get(t);return a!==void 0&&a.link===n.link&&a.kind===n.kind&&a.since===n.since&&a.operation_id===n.operation_id?(await e.prepare("UPDATE node_faults SET active = 1, updated_at = ? WHERE fault_id = ?").run(s(),a.fault_id),await U(e,a.fault_id,n)):await te(e,t,n,!0,r)}if(i.link===n.link&&i.kind===n.kind){const a=n.retry.disposition==="auto"?{...i.retry,...n.retry}:n.retry,d=i.retry.disposition===n.retry.disposition&&(n.retry.disposition!=="fatal"||i.message===n.message),_=d?i.since:n.since,u=await U(e,i.faultId,{...n,since:_,anchorEntryId:n.anchorEntryId??i.anchorEntryId,retry:a},r);return d||await e.prepare("UPDATE node_faults SET notified_since = NULL WHERE fault_id = ?").run(i.faultId),u}return i.link!==n.link&&D(i)>D(n)?null:(await e.prepare("UPDATE node_faults SET active = 0, updated_at = ? WHERE fault_id = ?").run(s(),i.faultId),await O(e,i.faultId),await te(e,t,n,!0,r))}o(ne,"replaceActiveFault");async function A(e,t,n){return(await e.prepare("SELECT binding_id FROM sessions WHERE node_id = ? AND session_id = ? AND unbound_at IS NULL").get(t,n))?.binding_id??null}o(A,"liveBinding");async function je(e,t){return await E(async n=>{const r=s();return(await n.prepare("UPDATE executions SET turn_progress_at = ? WHERE execution_id = ? AND state != 'exited' AND turn_open_at IS NOT NULL AND turn_closed_at IS NULL").run(r,e)).changes>0?!0:(await n.prepare("UPDATE executions SET turn_open_at = ?, turn_progress_at = ?, turn_closed_at = NULL, turn_end_reason = NULL WHERE execution_id = ? AND state != 'exited'").run(r,r,e)).changes>0})}o(je,"openTurn");async function Be(e){return(await(await l()).prepare("UPDATE executions SET turn_progress_at = ? WHERE execution_id = ? AND state != 'exited' AND turn_open_at IS NOT NULL AND turn_closed_at IS NULL").run(s(),e)).changes>0}o(Be,"recordTurnProgress");async function Je(e,t){return await E(async n=>{const r=s(),i=(await n.prepare("UPDATE executions SET turn_closed_at = ?, turn_end_reason = ? WHERE execution_id = ? AND state != 'exited' AND turn_open_at IS NOT NULL AND turn_closed_at IS NULL").run(r,t.endReason,e)).changes>0;if(i&&t.endReason==="settled"){const a="(SELECT node_id FROM executions WHERE execution_id = ?)";t.viewerPresent===!0?await n.prepare(`UPDATE nodes SET reply_at = ?, read_at = ? WHERE node_id = ${a}`).run(r,r,e):await n.prepare(`UPDATE nodes SET reply_at = ? WHERE node_id = ${a}`).run(r,e)}return i})}o(Je,"closeTurn");async function Ke(e){return(await(await l()).prepare("UPDATE nodes SET read_at = ? WHERE node_id = ?").run(s(),e)).changes>0}o(Ke,"markNodeRead");function re(e){return JSON.stringify({schema:"crtr.execution-exit-diagnostic/v1",...e})}o(re,"exitDiagnosticJson");async function Ye(e,t){if(!Number.isInteger(t.consecutivePasses)||t.consecutivePasses<1||t.routes.length===0||!t.routes.every(n=>n!==""))throw new Error("invalid transport-poison verdict");return(await(await l()).prepare("UPDATE executions SET exit_diagnostic_json = ? WHERE execution_id = ? AND state != 'exited'").run(re({transport_poison:{consecutive_passes:t.consecutivePasses,routes:t.routes}}),e)).changes>0}o(Ye,"recordTransportPoisonVerdict");async function Ge(e){const t=await(await l()).prepare("SELECT exit_diagnostic_json FROM executions WHERE node_id = ? ORDER BY seq DESC LIMIT 1").get(e);if(t===void 0||t.exit_diagnostic_json===null)return null;try{const n=JSON.parse(t.exit_diagnostic_json),r=n.transport_poison;return n.schema!=="crtr.execution-exit-diagnostic/v1"||r===void 0||!Number.isInteger(r.consecutive_passes)||r.consecutive_passes<1||!Array.isArray(r.routes)||r.routes.length===0||!r.routes.every(i=>typeof i=="string"&&i!=="")?null:{consecutivePasses:r.consecutive_passes,routes:r.routes}}catch{return null}}o(Ge,"readTransportPoisonVerdict");async function qe(e){const t=await(await l()).prepare("SELECT turn_open_at, turn_closed_at, turn_progress_at FROM executions WHERE node_id = ? AND state != 'exited'").get(e);return t===void 0?null:{busy:t.turn_open_at!==null&&t.turn_closed_at===null,progressAt:t.turn_progress_at}}o(qe,"readLiveTurn");async function Ve(e){const t=await l(),n=await t.prepare("SELECT turn_closed_at, turn_progress_at FROM executions WHERE node_id = ? AND turn_open_at IS NOT NULL ORDER BY seq DESC LIMIT 1").get(e);if(n===void 0)return null;const r=await t.prepare("SELECT turn_end_reason FROM executions WHERE node_id = ? ORDER BY seq DESC LIMIT 1").get(e);return{interrupted:n.turn_closed_at===null||r?.turn_end_reason==="teardown-aborted",progressAt:n.turn_progress_at}}o(Ve,"readInterruptedTurn");async function Qe(e){return await(await l()).prepare("SELECT 1 FROM executions WHERE node_id = ? AND turn_open_at IS NOT NULL LIMIT 1").get(e)!==void 0}o(Qe,"hasAdmittedTurn");async function ze(e,t){const n=P(t);return M(e,n),await E(async r=>await ne(r,e,n))}o(ze,"recordFault");async function Ze(e){return await E(async t=>(await t.prepare("UPDATE node_faults SET notified_since = since, updated_at = ? WHERE fault_id = ?").run(s(),e)).changes>0)}o(Ze,"markFaultNotified");function we(e){return e.link==="pi\u2192provider"&&e.retry.disposition==="fatal"&&e.notifiedSince!==e.since}o(we,"isUnnotifiedFatalProviderFault");async function et(){return(await(await l()).prepare("SELECT f.node_id FROM node_faults f JOIN nodes n ON n.node_id = f.node_id WHERE f.active = 1 AND f.link = 'pi\u2192provider' AND f.retry_disposition = 'fatal' AND (f.notified_since IS NULL OR f.notified_since != f.since) AND n.status IN ('active', 'idle')").all()).map(e=>e.node_id)}o(et,"listUnnotifiedFatalFaultNodes");let X=null;function tt(e){X=e}o(tt,"setFatalFaultAnnouncer");async function nt(e,t){const n=await m(await l(),e);return n===null||t?.link!==void 0&&n.link!==t.link?!1:await E(async r=>{const i=await m(r,e);if(i===null||t?.link!==void 0&&i.link!==t.link)return!1;X!==null&&we(i)&&await X(e);const a=await r.prepare("SELECT episode_state FROM node_faults WHERE fault_id = ?").get(i.faultId);await r.prepare("UPDATE node_faults SET active = 0, updated_at = ? WHERE fault_id = ?").run(s(),i.faultId),a.episode_state==="pending"&&t?.preserveEpisode!==!0&&await r.prepare("UPDATE node_faults SET episode_state = NULL, episode_binding_id = NULL, updated_at = ? WHERE fault_id = ?").run(s(),i.faultId),await O(r,i.faultId);const d=Q();return J({level:"info",event:"fault.cleared",operation_id:d,node_id:e,error_class:B(i),fields:{cleared_fault_operation_id:i.operation_id,link:i.link,op:i.op,kind:i.kind,retry:i.retry,message:i.message,since:i.since,...i.anchorEntryId===void 0?{}:{anchor_entry_id:i.anchorEntryId}}}),!0})}o(nt,"clearFault");async function ie(e){return await m(await l(),e)}o(ie,"readFault");async function rt(e,t){const n=P(t.input);if(n.link!=="pi\u2192provider"||n.retry.disposition!=="auto"||n.retry.by!=="daemon")throw new Error("provider retry episode requires an automatic daemon provider fault");return M(e,n),await E(async r=>{const i=await A(r,e,t.sessionId);if(i===null)return null;const a=await m(r,e);if(a!==null&&(a.link!==n.link||a.kind!==n.kind)&&D(a)>D(n))return null;const d=await r.prepare("SELECT fault_id FROM node_faults WHERE node_id = ? AND episode_state IS NOT NULL").all(e);await r.prepare("UPDATE node_faults SET episode_state = NULL, episode_binding_id = NULL, updated_at = ? WHERE node_id = ? AND episode_state IS NOT NULL").run(s(),e);for(const u of d)await O(r,u.fault_id);const _=await ne(r,e,n,{state:"pending",bindingId:i});return _===null?null:(await r.prepare("UPDATE node_faults SET episode_state = ?, episode_binding_id = ?, updated_at = ? WHERE fault_id = ?").run("pending",i,s(),_.faultId),_)})}o(rt,"recordPendingEpisode");async function it(e,t){return await E(async n=>{if(await n.prepare("SELECT 1 FROM nodes WHERE node_id = ? AND intent = 'refresh'").get(e)!==void 0)return!1;const r=await A(n,e,t.sessionId);return r===null?!1:(await n.prepare("UPDATE node_faults SET episode_state = 'admitted', retry_disposition = ?, retry_by = ?, retry_attempt = ?, retry_max = ?, retry_next_at = ?, updated_at = ? WHERE node_id = ? AND fault_id = ? AND episode_state = 'pending' AND episode_binding_id = ?").run(t.retry.disposition,t.retry.by??null,t.retry.attempt??null,t.retry.max??null,t.retry.nextAt??null,s(),e,t.faultId,r)).changes>0})}o(it,"admitEpisode");async function ot(e,t){const n=P(t.fault);return await E(async r=>{const i=await A(r,e,t.sessionId);return i===null||(await m(r,e))?.faultId!==t.faultId||await r.prepare("SELECT 1 FROM node_faults WHERE node_id = ? AND fault_id = ? AND episode_state = 'admitted' AND episode_binding_id = ?").get(e,t.faultId,i)===void 0?!1:(M(e,n),t.reopen?await U(r,t.faultId,n,{state:"pending",bindingId:i}):(await U(r,t.faultId,n),await r.prepare("UPDATE node_faults SET episode_state = NULL, episode_binding_id = NULL, updated_at = ? WHERE fault_id = ?").run(s(),t.faultId),await r.prepare("UPDATE node_faults SET notified_since = NULL WHERE fault_id = ?").run(t.faultId)),!0)})}o(ot,"settleRejectedEpisode");async function at(e,t){return await E(async n=>{const r=await A(n,e,t.sessionId);return r===null?!1:(await n.prepare("UPDATE node_faults SET episode_state = 'pending', updated_at = ? WHERE node_id = ? AND episode_state = 'admitted' AND episode_binding_id = ?").run(s(),e,r)).changes>0})}o(at,"reopenEpisode");async function st(e,t){return await E(async n=>{const r=await A(n,e,t.sessionId);return r===null?!1:(await n.prepare("UPDATE node_faults SET episode_state = 'invalidated', updated_at = ? WHERE node_id = ? AND episode_state != 'invalidated' AND episode_state IS NOT NULL AND episode_binding_id = ?").run(s(),e,r)).changes>0})}o(st,"invalidateEpisode");async function dt(e,t){return await E(async n=>{const r=await A(n,e,t.sessionId);if(r===null)return!1;const i=await n.prepare("SELECT fault_id FROM node_faults WHERE node_id = ? AND episode_binding_id = ? AND episode_state IS NOT NULL").all(e,r);if(i.length===0)return!1;await n.prepare("UPDATE node_faults SET episode_state = NULL, episode_binding_id = NULL, updated_at = ? WHERE node_id = ? AND episode_binding_id = ? AND episode_state IS NOT NULL").run(s(),e,r);for(const a of i)await O(n,a.fault_id);return!0})}o(dt,"clearEpisode");async function ut(e){const t=await(await l()).prepare("SELECT f.*, s.session_id FROM node_faults f JOIN sessions s ON s.binding_id = f.episode_binding_id WHERE f.node_id = ? AND f.episode_state IS NOT NULL").get(e);return t===void 0?null:{state:t.episode_state,sessionId:t.session_id,fault:b(t)}}o(ut,"readEpisode");async function ct(){return(await(await l()).prepare("SELECT f.*, s.session_id AS bound_session_id FROM node_faults f JOIN sessions s ON s.binding_id = f.episode_binding_id WHERE f.active = 1 AND f.episode_state = 'pending' AND s.unbound_at IS NULL AND s.session_id IS NOT NULL AND f.link = 'pi\u2192provider' AND f.retry_disposition = 'auto' AND f.retry_by = 'daemon' AND f.kind IN ('connection', 'rate-limit', 'overloaded')").all()).map(t=>({nodeId:t.node_id,sessionId:t.bound_session_id,fault:b(t),updatedAt:t.updated_at,nudgedAt:t.nudged_at??null}))}o(ct,"listPendingProviderRetries");async function _t(e,t,n){return(await(await l()).prepare("UPDATE node_faults SET nudged_at = ? WHERE fault_id = ? AND active = 1 AND episode_state = 'pending' AND (nudged_at IS NULL OR nudged_at <= ?)").run(new Date(t).toISOString(),e,new Date(t-n).toISOString())).changes===1}o(_t,"claimFaultNudge");async function pt(e){const t=await ie(e)===null;return{async explanation(){if(!t)return null;const n=await ie(e);if(n===null||n.link!=="crtr\u2192pi"||n.retry.disposition!=="fatal")return null;const r=n.op.trim(),i=n.message.trim();return r===""||i===""?null:`${r}: ${i}`}}}o(pt,"beginBootFaultAttempt");function oe(e,t){try{return _e(e).mtime.toISOString()}catch{return t}}o(oe,"markerMtime");function $(e,t){if(!f(e))return null;try{return ue(e,"utf8")}catch(n){if(!t)return null;throw new Error(`cannot import recovery input ${e}: ${n.message}`)}}o($,"legacyFile");function De(e,t){return p(e,"SELECT execution_id, started_at FROM executions WHERE node_id = ? ORDER BY rowid DESC LIMIT 1").get(t)??null}o(De,"latestExecution");function Ue(e,t){const r=H(e,"nodes").has("launched_at")?p(e,"SELECT COALESCE(launched_at, created) AS started_at FROM nodes WHERE node_id = ?").get(t):p(e,"SELECT created AS started_at FROM nodes WHERE node_id = ?").get(t);if(r===void 0)throw new Error(`cannot import recovery witness for unknown node ${t}`);const i=w();return p(e,"INSERT INTO executions (execution_id, node_id, daemon_epoch, pid, process_identity, state, started_at, ended_at, exit_reason) VALUES (?, ?, NULL, NULL, NULL, 'exited', ?, ?, 'pre-consolidation')").run(i,t,r.started_at,r.started_at),{execution_id:i,started_at:r.started_at}}o(Ue,"syntheticExecution");function ae(e,t,n,r,i){const a=w();return p(e,Z).run(...ee(a,t,n,r,i)),{...n,faultId:a}}o(ae,"insertMigratedFault");function Oe(e,t,n,r){const i=p(e,"SELECT binding_id, node_id FROM sessions WHERE transcript_path = ? AND unbound_at IS NULL").get(n);if(i!==void 0){if(i.node_id!==t)throw new Error(`cannot import provider retry ${r}: transcript is live-owned by ${i.node_id}`);return i.binding_id}const a=p(e,"SELECT binding_id FROM sessions WHERE node_id = ? AND transcript_path = ? ORDER BY rowid DESC LIMIT 1").get(t,n);if(a!==void 0)return a.binding_id;const d=p(e,"SELECT created FROM nodes WHERE node_id = ?").get(t);if(d===void 0)throw new Error(`cannot import provider retry ${r}: unknown node ${t}`);const _=w();return p(e,"INSERT INTO sessions (binding_id, session_id, node_id, transcript_path, source_session_id, fork_entry_id, created_at, bound_at, unbound_at) VALUES (?, NULL, ?, ?, NULL, NULL, ?, ?, ?)").run(_,t,n,d.created,d.created,s()),_}o(Oe,"migrationBinding");function lt(e){e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'node_faults'").get()!==void 0&&(H(e,"node_faults").has("notified_since")||e.exec("ALTER TABLE node_faults ADD COLUMN notified_since TEXT"))}o(lt,"addFaultNotifiedSince");function Et(e){if(Ae(e),Se(e),!f(C()))return;const t=de(C(),{withFileTypes:!0}).filter(r=>r.isDirectory()).sort((r,i)=>r.name.localeCompare(i.name)),n=p(e,"SELECT 1 FROM nodes WHERE node_id = ?");for(const r of t){const i=r.name,a=le(i),d=g(a,"busy"),_=g(a,"clean-abort"),u=g(a,"transport-poison.json"),N=g(a,"fault"),S=g(a,"provider-retry"),h=f(d),k=f(_);if(!h&&!k&&!f(u)&&!f(N)&&!f(S)||!f(g(C(),i,"meta.json"))&&n.get(i)===void 0)continue;const v=$(u,!1),R=$(N,!0),x=$(S,!0);if(!h&&!k&&v===null&&R===null&&x===null)continue;let y=De(e,i);if(y===null&&(y=Ue(e,i)),h){const c=oe(d,y.started_at);p(e,"UPDATE executions SET turn_open_at = ?, turn_progress_at = ?, turn_closed_at = NULL, turn_end_reason = NULL WHERE execution_id = ?").run(c,c,y.execution_id)}else if(k){const c=oe(_,y.started_at);p(e,"UPDATE executions SET turn_open_at = ?, turn_progress_at = ?, turn_closed_at = ?, turn_end_reason = 'teardown-aborted' WHERE execution_id = ?").run(c,c,c,y.execution_id)}if(v!==null)try{const c=JSON.parse(v);Number.isInteger(c.consecutivePasses)&&c.consecutivePasses>=1&&Array.isArray(c.routes)&&c.routes.length>0&&c.routes.every(j=>typeof j=="string"&&j!=="")&&p(e,"UPDATE executions SET exit_diagnostic_json = ? WHERE execution_id = ?").run(re({transport_poison:{consecutive_passes:c.consecutivePasses,routes:c.routes}}),y.execution_id)}catch{}const I=R===null?null:V(R);if(R!==null&&I===null)throw new Error(`cannot import recovery fault ${N}`);const T=x===null?null:xe(x);if(x!==null&&T===null)throw new Error(`cannot import provider retry ${S}`);let F=I===null||I.link==="broker\u2194crtrd"?null:ae(e,i,I,!0);if(T!==null){const c=Oe(e,i,T.sessionFile,S);F!==null&&F.since===T.fault.since?p(e,"UPDATE node_faults SET episode_state = ?, episode_binding_id = ?, updated_at = ? WHERE fault_id = ?").run(T.state,c,s(),F.faultId):ae(e,i,T.fault,!1,{state:T.state,bindingId:c})}}}o(Et,"migrateRecoveryWitnesses");export{$e as FAULT_QUIET_MS,lt as addFaultNotifiedSince,it as admitEpisode,pt as beginBootFaultAttempt,_t as claimFaultNudge,dt as clearEpisode,nt as clearFault,Je as closeTurn,re as exitDiagnosticJson,Qe as hasAdmittedTurn,b as hydrateFault,st as invalidateEpisode,ct as listPendingProviderRetries,et as listUnnotifiedFatalFaultNodes,Ze as markFaultNotified,Ke as markNodeRead,Et as migrateRecoveryWitnesses,je as openTurn,q as parseProviderError,ut as readEpisode,ie as readFault,Ve as readInterruptedTurn,qe as readLiveTurn,Ge as readTransportPoisonVerdict,ze as recordFault,rt as recordPendingEpisode,Ye as recordTransportPoisonVerdict,Be as recordTurnProgress,at as reopenEpisode,tt as setFatalFaultAnnouncer,ot as settleRejectedEpisode};
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
-- 012-charge-admission.sql — free trial (S2): the generic attribution columns the shared ledger needs so an external admitting
|
|
2
|
+
-- authority can mark each charge's admission and real cost, plus the two person stores the runtime keeps for the credential
|
|
3
|
+
-- activation acknowledgement and the hosted endpoint of the grant sync. One transaction, additions only: `schema_min_reader`
|
|
4
|
+
-- is not touched and stays 2. The previous build never names a new column or table. Core never interprets `admitted_as`.
|
|
5
|
+
|
|
6
|
+
-- ---------------------------------------------------------------- charge attribution
|
|
7
|
+
-- `admission`: the external admission id the charge settles under; null when nothing admitted it. `admitted_as`: the admitting
|
|
8
|
+
-- authority's opaque funding label, copied from the admission. `cost_usd`: what the call actually cost whoever funds it; null until
|
|
9
|
+
-- settled. `usd` stays the list-price amount and `billed_usd` the invoice amount.
|
|
10
|
+
ALTER TABLE charges
|
|
11
|
+
ADD COLUMN IF NOT EXISTS admission text,
|
|
12
|
+
ADD COLUMN IF NOT EXISTS admitted_as text,
|
|
13
|
+
ADD COLUMN IF NOT EXISTS cost_usd numeric(14,6),
|
|
14
|
+
ADD COLUMN IF NOT EXISTS cost_source text;
|
|
15
|
+
ALTER TABLE charges ADD CONSTRAINT charges_cost_source_check
|
|
16
|
+
CHECK (cost_source IS NULL OR cost_source IN ('vendor_usage', 'provider_receipt', 'runtime_estimate'));
|
|
17
|
+
|
|
18
|
+
CREATE INDEX IF NOT EXISTS charges_admitted ON charges(sub, admitted_as) WHERE admitted_as IS NOT NULL;
|
|
19
|
+
|
|
20
|
+
-- An admission's funding fields are set once: null may become a value, a value never changes.
|
|
21
|
+
CREATE FUNCTION charges_admission_immutable() RETURNS trigger LANGUAGE plpgsql AS $$
|
|
22
|
+
BEGIN
|
|
23
|
+
IF OLD.admission IS NOT NULL AND NEW.admission IS DISTINCT FROM OLD.admission THEN
|
|
24
|
+
RAISE EXCEPTION 'charges.admission of % is set and cannot change', OLD.id USING ERRCODE = 'check_violation';
|
|
25
|
+
END IF;
|
|
26
|
+
IF OLD.admitted_as IS NOT NULL AND NEW.admitted_as IS DISTINCT FROM OLD.admitted_as THEN
|
|
27
|
+
RAISE EXCEPTION 'charges.admitted_as of % is set and cannot change', OLD.id USING ERRCODE = 'check_violation';
|
|
28
|
+
END IF;
|
|
29
|
+
RETURN NEW;
|
|
30
|
+
END $$;
|
|
31
|
+
CREATE TRIGGER charges_admission_immutable BEFORE UPDATE ON charges
|
|
32
|
+
FOR EACH ROW WHEN (OLD.admission IS DISTINCT FROM NEW.admission OR OLD.admitted_as IS DISTINCT FROM NEW.admitted_as)
|
|
33
|
+
EXECUTE FUNCTION charges_admission_immutable();
|
|
34
|
+
|
|
35
|
+
-- No change to `charges_rollup_update`: 002's WHEN clause already fires on a changed payer, funding, sub, grantee, provider, month,
|
|
36
|
+
-- usd or billed_usd, and `charge_totals_rollup` subtracts OLD and adds NEW, so a re-attribution already moves `charge_totals`.
|
|
37
|
+
|
|
38
|
+
-- ---------------------------------------------------------------- credential activations (a person store)
|
|
39
|
+
-- One row per sign-in completion or key save the runtime must tell the directory about. `activation_id` is generated by the
|
|
40
|
+
-- runtime and stable across retries (the directory's idempotency key). `acknowledged_at` is null until the directory answered 2xx.
|
|
41
|
+
-- No credential material is stored here.
|
|
42
|
+
CREATE TABLE credential_activations (
|
|
43
|
+
activation_id text PRIMARY KEY,
|
|
44
|
+
person text NOT NULL,
|
|
45
|
+
kind text NOT NULL CHECK (kind IN ('subscription', 'api_key')),
|
|
46
|
+
provider text NOT NULL,
|
|
47
|
+
activated_at text NOT NULL,
|
|
48
|
+
acknowledged_at text,
|
|
49
|
+
attempts bigint NOT NULL DEFAULT 0,
|
|
50
|
+
last_attempt_at text
|
|
51
|
+
);
|
|
52
|
+
CREATE INDEX credential_activations_pending ON credential_activations(person, activated_at) WHERE acknowledged_at IS NULL;
|
|
53
|
+
|
|
54
|
+
-- ---------------------------------------------------------------- hosted endpoint of the grant sync (a person store)
|
|
55
|
+
-- The account-level `hosted_endpoint` and `payment_setup_url` of the latest grant sync answer for a person; both null columns
|
|
56
|
+
-- (or no row) mean the answer carried none. `hosted_endpoint_json` is the answer's object as text, as `grants.*_json` are.
|
|
57
|
+
CREATE TABLE hosted_endpoints (
|
|
58
|
+
person text PRIMARY KEY,
|
|
59
|
+
hosted_endpoint_json text,
|
|
60
|
+
payment_setup_url text,
|
|
61
|
+
synced_at text NOT NULL
|
|
62
|
+
);
|
|
@@ -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 = 12;
|
|
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=12;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};
|
|
@@ -32,6 +32,9 @@ export interface NodeOutcomeDetailV1 {
|
|
|
32
32
|
max: number;
|
|
33
33
|
};
|
|
34
34
|
respawn_failures?: number;
|
|
35
|
+
/** Present when the failure was a refused model call: the daemon's error code and, for a payment refusal, its structured reason. */
|
|
36
|
+
provider_code?: string;
|
|
37
|
+
payment?: import('../../api/dto/charges.js').PaymentRefusalDTO;
|
|
35
38
|
deadline?: {
|
|
36
39
|
deadline_at: string;
|
|
37
40
|
elapsed_ms: number;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { ModelStrength } from '../../types.js';
|
|
2
|
+
/** An inference endpoint the person's directory offers after (or instead of) their own credentials. */
|
|
3
|
+
export interface HostedEndpoint {
|
|
4
|
+
base_url: string;
|
|
5
|
+
/** The model each strength asks the endpoint for. */
|
|
6
|
+
rungs: Record<ModelStrength, string>;
|
|
7
|
+
/** True when the endpoint also follows the person's own subscriptions and keys; false when it serves only a person who has none. */
|
|
8
|
+
after_own_credentials: boolean;
|
|
9
|
+
}
|
|
10
|
+
export interface HostedEndpointState {
|
|
11
|
+
hosted_endpoint: HostedEndpoint | null;
|
|
12
|
+
payment_setup_url: string | null;
|
|
13
|
+
synced_at: string;
|
|
14
|
+
}
|
|
15
|
+
/** Parse the answer's `hosted_endpoint`; anything but null or the complete shape is a malformed answer. */
|
|
16
|
+
export declare function hostedEndpointOf(value: unknown): HostedEndpoint | null;
|
|
17
|
+
/** Parse the answer's `payment_setup_url`. */
|
|
18
|
+
export declare function paymentSetupUrlOf(value: unknown): string | null;
|
|
19
|
+
/** Replace `person`'s stored fields with one grant sync answer's. The caller names the person and runs this in the transaction that
|
|
20
|
+
* stores the answer's grants. */
|
|
21
|
+
export declare function storeHostedEndpoint(state: HostedEndpointState, person: string): Promise<void>;
|
|
22
|
+
/** The calling person's stored fields; null when no grant sync answer carried them. */
|
|
23
|
+
export declare function readHostedEndpoint(): Promise<HostedEndpointState | null>;
|
|
24
|
+
/** The hosted endpoint a model call may fall through to, or null (contract §5): an endpoint is stored, and the person has no managed
|
|
25
|
+
* subscription account and no stored key at all, or the endpoint also follows their own credentials. "Configured" counts rows that
|
|
26
|
+
* exist, so a cooling or auth-failed credential still counts. `runLlm` adds the endpoint as a route with this rule, and every gate
|
|
27
|
+
* that asks whether a person can run an agent without a credential of their own asks it too. */
|
|
28
|
+
export declare function eligibleHostedEndpoint(): Promise<HostedEndpoint | null>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var i=Object.defineProperty;var t=(n,e)=>i(n,"name",{value:e,configurable:!0});import{MODEL_STRENGTHS as s}from"../runtime/model-selection.js";import{openDb as p}from"../canvas/db.js";import{personIdAsync as a}from"../canvas/person.js";import{readAuthCredentials as _}from"../auth-file.js";import{MANAGED_PROVIDER_IDS as d}from"../managed-providers.js";import{readSubscriptionPoolRows as u}from"../subscription-state.js";function D(n){if(n===null)return null;const e=n,o=e?.rungs;if(!e||typeof e!="object"||typeof e.base_url!="string"||!URL.canParse(e.base_url)||!o||typeof o!="object"||!s.every(r=>typeof o[r]=="string"&&o[r]!=="")||typeof e.after_own_credentials!="boolean")throw new TypeError("invalid hosted_endpoint in grant sync response");return{base_url:e.base_url,rungs:Object.fromEntries(s.map(r=>[r,o[r]])),after_own_credentials:e.after_own_credentials}}t(D,"hostedEndpointOf");function O(n){if(n===null)return null;if(typeof n!="string"||!URL.canParse(n))throw new TypeError("invalid payment_setup_url in grant sync response");return n}t(O,"paymentSetupUrlOf");async function b(n,e){await(await p()).prepare("INSERT INTO hosted_endpoints(person,hosted_endpoint_json,payment_setup_url,synced_at) VALUES(?,?,?,?) ON CONFLICT(person) DO UPDATE SET hosted_endpoint_json=EXCLUDED.hosted_endpoint_json,payment_setup_url=EXCLUDED.payment_setup_url,synced_at=EXCLUDED.synced_at").run(e,n.hosted_endpoint===null?null:JSON.stringify(n.hosted_endpoint),n.payment_setup_url,n.synced_at)}t(b,"storeHostedEndpoint");async function l(){const n=await a(),e=await(await p()).prepare("SELECT hosted_endpoint_json,payment_setup_url,synced_at FROM hosted_endpoints WHERE person=?").get(n);return e?{hosted_endpoint:e.hosted_endpoint_json===null?null:JSON.parse(e.hosted_endpoint_json),payment_setup_url:e.payment_setup_url,synced_at:e.synced_at}:null}t(l,"readHostedEndpoint");async function g(){const n=(await l())?.hosted_endpoint??null;if(n===null)return null;if(!n.after_own_credentials){for(const e of d)if((await u(e)).length>0)return null;if(Object.keys(await _()).length>0)return null}return n}t(g,"eligibleHostedEndpoint");export{g as eligibleHostedEndpoint,D as hostedEndpointOf,O as paymentSetupUrlOf,l as readHostedEndpoint,b as storeHostedEndpoint};
|
package/dist/core/grants/sync.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var x=Object.defineProperty;var r=(e,n)=>x(e,"name",{value:n,configurable:!0});import{createPrivateKey as $,randomUUID as O,sign as A}from"node:crypto";import{readFileSync as P}from"node:fs";import{join as T}from"node:path";import{crtrHome as N}from"../canvas/paths.js";import{withCanvasWrite as R}from"../canvas/db.js";import{isUnsandboxedMachine as v}from"../runtime/unsandboxed.js";import{emitEvent as l}from"../events/emit.js";import{describeOutboundFailure as G,outboundFetch as k,outboundJson as b,outboundRefusal as E}from"../events/outbound.js";import{dependenciesOf as J,inferenceEndpointOf as U,replaceGrants as B,teamsOf as C}from"./mirror.js";import{onGrantSync as D}from"./on-sync.js";import{hostedEndpointOf as F,paymentSetupUrlOf as I,storeHostedEndpoint as M}from"./hosted-endpoint.js";import{adoptInstallPerson as W}from"../scoped-state/migrate.js";import{PersonOutsideRequestError as q,PersonUnresolvedError as L,personId as H,resolvePerson as z,retireLocalPerson as K,setPersonId as V}from"../canvas/person.js";const he=300;function Y(e,n){const t=Math.floor(Date.now()/1e3),o=Buffer.from(JSON.stringify({alg:"ES256",typ:"JWT",kid:e.kid})).toString("base64url"),p=Buffer.from(JSON.stringify({iss:e.client_id,sub:e.client_id,aud:n,iat:t,exp:t+300,jti:O()})).toString("base64url"),i=`${o}.${p}`,s=A("sha256",Buffer.from(i),{key:$({key:e.jwk,format:"jwk"}),dsaEncoding:"ieee-p1363"});return`${i}.${s.toString("base64url")}`}r(Y,"assertion");function y(){const e=JSON.parse(P(T(N(),"secrets","runtime-client.json"),"utf8"));if(!e.jwk||e.alg!=="ES256"||!e.kid||!e.client_id||!e.runtime||e.jwk.kid!==e.kid||e.jwk.kty!=="EC"||e.jwk.crv!=="P-256"||!e.jwk.d)throw new TypeError("invalid runtime client key");return e}r(y,"runtimeClient");function we(e=y()){return e.runtime.startsWith("runtime:")?e.runtime.slice(8):e.runtime}r(we,"runtimeId");function Q(e){return`This machine was removed from your Northlight account. To use it again, create a join token at ${e.replace(/\/$/,"")}/account/machines, and run \`crtr sys join\` from a plain terminal.`}r(Q,"machineRevokedMessage");class S extends Error{static{r(this,"MachineRevokedError")}constructor(n){super(Q(n)),this.name="MachineRevokedError"}}async function X(e,n){const t=y(),o=`${e.replace(/\/$/,"")}/token`,p=new URLSearchParams({grant_type:"client_credentials",client_id:t.client_id,client_assertion_type:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer",client_assertion:Y(t,o),...n===void 0?{}:{audience:n}}),i=await k("directory_token",o,{method:"POST",body:p,signal:AbortSignal.timeout(1e4)});if(!i.ok)throw i.status===401&&v()&&await Z(i)?new S(e):E("directory_token",o,`directory token request failed: ${i.status}`);const s=await b("directory_token",o,i);if(typeof s.access_token!="string")throw new TypeError("directory token response has no access_token");return{access_token:s.access_token,expires_at:ee(s.access_token,s.expires_in)}}r(X,"mintDirectoryToken");async function Z(e){try{return(await e.json()).error==="invalid_client"}catch{return!1}}r(Z,"isInvalidClient");function ee(e,n){if(typeof n=="number"&&Number.isFinite(n)&&n>0)return Date.now()+n*1e3;try{const t=JSON.parse(Buffer.from(e.split(".")[1]??"","base64url").toString("utf8"));if(typeof t.exp=="number")return t.exp*1e3}catch{}return Date.now()+3e5}r(ee,"tokenExpiry");function te(e,n){if(!e||typeof e!="object")throw new TypeError("invalid grant sync response");const t=e,o=n.runtime.startsWith("runtime:")?n.runtime:`runtime:${n.runtime}`;if(!(t.runtime===o||v()&&typeof t.runtime=="string"&&t.runtime.startsWith("runtime:")&&t.grantee!=="app:terminal")||typeof t.id!="string"||typeof t.sub!="string"||typeof t.grantee!="string"||!Number.isInteger(t.rev)||!Array.isArray(t.scopes)||!Array.isArray(t.resolved_scopes)||!["active","revoked","removed"].includes(t.status??"")||typeof t.synced_at!="string")throw new TypeError("invalid grant sync response");const s=e.revisions?.find(c=>c.rev===t.rev)?.approved_at;if(typeof s!="string")throw new TypeError("grant revision has no approval time");const f=t.payer==="app"?"app":"user";return{...t,spend_cap:t.spend_cap??null,expires_at:t.expires_at??null,revoked_at:t.revoked_at??null,approved_at:s,payer:f,dependencies:J(t.dependencies),inference_endpoint:f==="app"?U(t.inference_endpoint):null,run_notice_url:typeof t.run_notice_url=="string"&&t.run_notice_url!==""?t.run_notice_url:null}}r(te,"responseGrant");async function ne(){try{return{id:H(),late:null}}catch(n){if(n instanceof q)return null;if(!(n instanceof L))throw n}const e=await z();return e===null?null:{id:e.id,late:e}}r(ne,"pullPerson");async function re(e){V(e.id),await W(e.id);const n=await K();l({level:"info",event:"daemon.person.resolved",fields:{person_id:e.id,source:e.source}}),l({level:"info",event:"daemon.person.retired",fields:{person_id:n.person,retired:n.retired,columns:n.columns}})}r(re,"bindLatePerson");let _;function ve(e){return _?_(e):Promise.resolve()}r(ve,"requestGrantSync");function ke(e,n=t=>{}){let t;const o=e.replace(/\/$/,""),p=r(async()=>{const c=y(),u=await X(o),m=await k("grant_sync",`${o}/v1/runtime/grants`,{headers:{Authorization:`Bearer ${u.access_token}`},signal:AbortSignal.timeout(1e4)});if(!m.ok)throw E("grant_sync",`${o}/v1/runtime/grants`,`directory grant sync failed: ${m.status}`);const a=await b("grant_sync",`${o}/v1/runtime/grants`,m);if(!Array.isArray(a.grants)||typeof a.synced_at!="string")throw new TypeError("invalid grant sync response");const g="hosted_endpoint"in a||"payment_setup_url"in a?{hosted_endpoint:F(a.hosted_endpoint??null),payment_setup_url:I(a.payment_setup_url??null),synced_at:a.synced_at}:void 0,j=a.synced_at,h=a.grants.map(d=>te(d,c)),w=await R(async()=>{await B(h,j,o,C(a.teams));const d=await ne();return g&&d&&await M(g,d.id),d});l({level:"info",event:"daemon.grants.synced",fields:{grants:h.length,synced_at:a.synced_at}}),w?.late&&await re(w.late);try{await D(n)}catch(d){l({level:"error",event:"daemon.grants.on_sync_failed",error:d})}},"run");let i;const s=r(()=>{const c=p().catch(u=>{throw u instanceof S?l({level:"error",event:"daemon.grants.machine_revoked",error:u}):l({level:"error",event:"daemon.grants.sync_failed",error:u,fields:G(u)}),u}).finally(()=>{t===c&&(t=void 0)});return t=c,c},"start"),f=r((c={})=>t?c.fresh?(i??=t.catch(()=>{}).then(()=>(i=void 0,t??s())),i):t:s(),"sync");return _=f,f}r(ke,"createGrantSync");export{he as GRANT_SYNC_INTERVAL_S,S as MachineRevokedError,Y as assertion,ke as createGrantSync,Q as machineRevokedMessage,X as mintDirectoryToken,ve as requestGrantSync,y as runtimeClient,we as runtimeId};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var
|
|
1
|
+
var z=Object.defineProperty;var u=(e,i)=>z(e,"name",{value:i,configurable:!0});import{zstdCompressSync as Q}from"node:zlib";import{blobStore as V}from"../../blobs/index.js";import{openDb as E,withCanvasWrite as N}from"../../canvas/db.js";import{insertImportedRevisions as Y}from"../../graph/documents.js";import{getById as X}from"../../graph/objects.js";import{bundleKeys as S,decodeRows as Z,rowKeys as x,SEQ_TABLES as ee}from"../bundle/layout.js";import{readCatalog as te}from"./catalog.js";import{copyRows as ae,decodeKeys as C,encodeKeys as W}from"./copy.js";import{pruneStaged as ne,precheck as ie,renameClashingProfiles as se,rewritePaths as re,rewriteRequestPaths as oe,takeRepoSyncedDocuments as de}from"./prepare.js";import{boundSub as pe,checkSourcePerson as ce,checkStagedBlobKeys as ue,checkStagedPersons as fe,checkStagedReferences as le,checkStagedRequestKeys as me}from"./bind.js";import{deleteRunBlobs as _e,moveRunBlobs as we}from"./blobs.js";import{dropStubRows as ge,findFleetGrant as be,grantMissing as he,rewriteIds as ye,rewritePerson as Ee}from"./rewrite.js";import{dropStaging as B,ImportLaneError as w,stage as Se,stagingSchema as ve,targetSchema as Re}from"./stage.js";import{verifyRun as Oe}from"./verify.js";import{sandboxPathMap as Te,writeNodeFiles as ke}from"./path-map.js";import{allStoreKeys as Pe,readPluginsStore as je,recordImportedActivations as De,writeStores as Ie}from"./stores.js";import{publishImportedPlugins as Ae}from"./publish-plugins.js";import{COPIED_TABLES as Me}from"../bundle/layout.js";import{ClaimLostError as Ne}from"../../../daemon/reconcilers/row-claim.js";const L=10*6e4,v=u(()=>new Date().toISOString(),"now"),R=u(async(e,i)=>{await(await E()).prepare("UPDATE import_runs SET step = ? WHERE run_id = ?").run(i,e)},"setStep");async function Ce(e,i){const n=await e.get(S.source(i));if(n===null)throw new w("stage","bundle_invalid","source.json is missing");return JSON.parse(n.toString("utf8"))}u(Ce,"readSource");async function We(e,i,n,r,s,d){const t=await e.get(S.rows(n.run_id,"grants")),l=t===null?[]:Z(t),m=[];for(const a of l){const p=pe(a.sub,r,n.person,"grants.sub");await be(i,s,d,p,a.grantee)===void 0&&m.push(a.grantee)}if(m.length===0)return!0;if(n.loaded_at===void 0||n.loaded_at===null)throw new w("stage","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(n.loaded_at)>=L)throw he(m);return!1}u(We,"grantsReady");async function ot(e,i,n={}){const r=n.blobs??await V(),s=await E(),d=ve(e.run_id),t=u(async a=>{await i.assertOwned(),await R(e.run_id,a),await n.atStep?.(a)},"at");let l=e.state==="committed";const m=[];try{const a=await Ce(r,e.run_id);if(e.source_kind==="machine"&&a.installId!==e.source_install_id)throw new w("stage","bundle_invalid",`source.json names install ${a.installId}, the run is for ${e.source_install_id}`);a.installId=e.source_install_id;const p=await Re(s),b=[...Me],g=await te(s,p,[...b,"grants"]);if(!l){const f={},k=[],P=[],j=n.fleetRuntime??process.env.CRTR_RUNTIME??null;if(await ce(s,p,a.person,e.person),!await We(r,s,e,a.person,p,j)){await i.assertOwned(),await R(e.run_id,"waiting_for_grants");return}await t("publish-plugins");const y=await Ae(await je(r,e.run_id));if(y.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)>=L)throw new w("publish-plugins","directory_unavailable",`the directory did not answer for: ${y.unavailable.slice(0,10).join(", ")}; rerun the import once it is reachable`,{plugins:y.unavailable});await i.assertOwned(),await R(e.run_id,"waiting_for_directory");return}P.push(...y.refused),await t("stage");const K=await Se(s,e.run_id,a.counts,o=>x(e.run_id,o,a),o=>r.get(o));for(const[o,c]of Object.entries(K))f[o]={staged:c,inserted:0,mapped:0,dropped:0};const _={db:s,schema:d,target:p,catalog:g,sourcePerson:a.person,targetPerson:e.person,fleetRuntime:j,shippedBodies:a.shippedBodies??{}};await t("bind-staged");for(const[o,c]of Object.entries(await fe(_)))O(f,o,c);await ue(_),await t("rewrite-person"),await Ee(_),await t("prune");const U=await ne(s,d,g,a),D=a.kind==="hosted"?Te(a.pathPrefixes??[]):[];await t("rewrite-paths"),await re(s,d,D),await oe(s,d),await me(_),await se(s,d,p,a.installId,e.person),await t("rewrite-ids");const I=await ye(_);await t("drop");const F=await de(s,d,p),J=await ge(_);for(const[o,c]of Object.entries({...U}))O(f,o,c);for(const[o,c]of Object.entries(J))O(f,o,c);await le(_),await t("pre-check");const q=new Map([["messages",["seq"]],...ee.map(o=>[o,["seq"]])]);await ie(s,d,p,g,b,new Set,q),await t("blobs"),await we(s,d,r,e.run_id,m),await t("copy"),await N(async o=>{await i.assertOwned();const c=await ae({db:o,runId:e.run_id,schema:d,target:p,catalog:g,source:a,person:e.person,idMap:I,pathMap:D}),A=await He(o,e.run_id,F);A>0&&(c.inserted.revisions=(c.inserted.revisions??0)+A),await ke(o,d,e.run_id,a);const M=await Ie({db:o,blobs:r,runId:e.run_id,person:e.person,objectMap:I.object});for(const[$,G]of Object.entries(M.inserted))c.inserted[$]=G.length;return k.push(...M.unresolvedPlugins),await o.prepare("UPDATE import_runs SET counts_json = ?, loaded_at = COALESCE(loaded_at, ?) WHERE run_id = ?").run(JSON.stringify({...Le(f,c),unresolved_plugins:k,refused_plugins:P}),v(),e.run_id),c}),l=!0,await n.atStep?.("committed")}await t("verify");const h=await Oe(s,e.run_id,d,p,g,a.installId);if(await s.prepare("UPDATE import_runs SET verify_json = ? WHERE run_id = ?").run(JSON.stringify(h),e.run_id),!h.ok)throw new w("verify","verify_failed","the committed rows differ from the staged rows or an invariant failed",{differences:h.differences,invariants:h.invariants});await t("manifest");const T=S.manifest(e.run_id);await r.put(T,await Ke(e.run_id)),await B(s,e.run_id);for(const f of Pe(e.run_id))await r.delete(f);await _e(r,e.run_id),await N(async f=>{await De(f,e.run_id,e.person),await f.prepare("UPDATE import_runs SET state = 'done', step = 'done', manifest_key = ?, finished_at = ? WHERE run_id = ?").run(T,v(),e.run_id)})}catch(a){if(a instanceof Ne)throw a;const p=Be(a);if(await B(s,e.run_id).catch(()=>{}),!l)for(const b of m)await r.delete(b).catch(()=>{});await s.prepare("UPDATE import_runs SET state = 'failed', failure_json = ?, finished_at = ? WHERE run_id = ?").run(JSON.stringify(p),v(),e.run_id)}}u(ot,"processRun");function Be(e){if(e instanceof w)return{step:e.step,code:e.code,message:e.message,...e.detail===void 0?{}:{detail:e.detail}};const i=e.code;return{step:"unknown",code:typeof i=="string"?i:"import_failed",message:e instanceof Error?e.message:String(e)}}u(Be,"failureOf");function O(e,i,n){(e[i]??={staged:0,inserted:0,mapped:0,dropped:0}).dropped+=n}u(O,"addDropped");function Le(e,i){for(const[n,r]of Object.entries(i.inserted))(e[n]??={staged:0,inserted:0,mapped:0,dropped:0}).inserted=r;for(const[n,r]of Object.entries(i.mapped))(e[n]??={staged:0,inserted:0,mapped:0,dropped:0}).mapped=r;return e}u(Le,"withInserted");async function He(e,i,n){const r=new Set((await e.prepareUncached("SELECT rev_id FROM revisions WHERE rev_id IN (SELECT jsonb_array_elements_text(?::jsonb))").all(JSON.stringify(n.map(t=>t.rev_id)))).map(t=>t.rev_id)),s=n.filter(t=>!r.has(t.rev_id)),d=new Map;for(const t of n)d.set(t.document,[...d.get(t.document)??[],t]);for(const[t,l]of d){const m=await X(e,t);m!==null&&await Y(e,m,l.map(a=>({rev_id:a.rev_id,parents:a.parents,body_hash:a.body_hash,rationale:a.rationale,created_at:a.created_at})))}return await H(e,i,"revisions",s.map(t=>[t.rev_id])),await H(e,i,"revision_parents",s.flatMap(t=>t.parents.map(l=>[t.rev_id,l]))),s.length}u(He,"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,W(r)):await e.prepare("UPDATE import_manifest SET inserted_keys = ? WHERE run_id = ? AND table_name = ?").run(W([...C(s.inserted_keys),...r]),i,n)}u(H,"appendManifest");async function Ke(e){const n=await(await E()).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:C(r.inserted_keys)})).join(`
|
|
2
2
|
`)+`
|
|
3
|
-
`))}
|
|
3
|
+
`))}u(Ke,"manifestFile");export{L as GRANT_WAIT_MS,ot as processRun};
|