@north-light/cli 0.3.741 → 0.3.743
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/clients/attach/viewer.js +295 -295
- package/dist/core/import/load/copy.d.ts +2 -0
- package/dist/core/import/load/copy.js +9 -9
- package/dist/core/import/load/prepare.d.ts +9 -1
- package/dist/core/import/load/prepare.js +11 -11
- package/dist/core/import/load/rollback.js +7 -6
- package/dist/core/import/load/run.js +2 -2
- package/dist/core/import/load/verify.js +8 -8
- package/dist/daemon/machine-daemon.js +1 -1
- package/dist/daemon/manage.d.ts +5 -5
- package/dist/daemon/manage.js +3 -3
- package/package.json +3 -3
- package/packages/crouter-api/dist/core/import/load/copy.js +18 -1
- package/packages/crouter-api/dist/core/import/load/prepare.js +16 -3
- package/packages/crouter-api/dist/daemon/manage.js +36 -25
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
|
@@ -25,3 +25,5 @@ export interface CopyInput {
|
|
|
25
25
|
export declare const copyOrder: (catalog: Catalog) => string[];
|
|
26
26
|
/** Must run inside `withCanvasWrite`. */
|
|
27
27
|
export declare function copyRows(input: CopyInput): Promise<CopyResult>;
|
|
28
|
+
/** Adds keys to a table's manifest row, creating it when the copy inserted no row of that table. */
|
|
29
|
+
export declare function appendManifest(tx: CanvasDb, runId: string, table: string, keys: string[][]): Promise<void>;
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
var
|
|
2
|
-
SELECT s.${s(
|
|
3
|
-
FROM (SELECT * FROM ${
|
|
4
|
-
ins AS (INSERT INTO ${
|
|
1
|
+
var H=Object.defineProperty;var o=(n,t)=>H(n,"name",{value:t,configurable:!0});import{zstdCompressSync as x,zstdDecompressSync as j}from"node:zlib";import{BODIES_TABLE as C,COPIED_TABLES as W,KEY_MAPPED_TABLES as A}from"../bundle/layout.js";import{q as s,rowKey as v,topologicalOrder as q}from"./catalog.js";import{fillEnvironments as B}from"./prepare.js";import{ImportLaneError as b}from"./stage.js";const k=o((n,t)=>`${s(n)}.${s(t)}`,"sq"),h=o(n=>x(Buffer.from(JSON.stringify(n))),"encodeKeys"),M=o(n=>JSON.parse(j(n).toString("utf8")),"decodeKeys"),D=new Map;async function Z(n){const t=await n.prepare("SELECT run_id FROM import_runs WHERE state = 'committed' OR (state = 'failed' AND committed_at IS NOT NULL)").all(),i=new Set;for(const{run_id:E}of t){let c=D.get(E);if(c===void 0){const l=await n.prepare("SELECT inserted_keys FROM import_manifest WHERE run_id = ? AND table_name = 'nodes'").get(E);if(l===void 0)continue;c=new Set(M(l.inserted_keys).map(T=>T[0])),D.set(E,c)}for(const l of c)i.add(l)}return i}o(Z,"nodesAwaitingVerify");const G=o(n=>q(n,W),"copyOrder");async function Q(n){const{db:t,runId:i,schema:E,target:c,catalog:l,source:T}=n,p=o(e=>k(E,e),"S"),m=o(e=>k(c,e),"T"),f={inserted:{},mapped:{}},R=o(async(e,r)=>{f.inserted[e]=r.length,await t.prepare("INSERT INTO import_manifest (run_id, table_name, inserted_keys) VALUES (?, ?, ?)").run(i,e,h(r))},"manifest");for(const[e,r]of Object.entries(A)){const d=l.tables.get(e).columns.filter(_=>_!==r),S=await t.prepareUncached(`WITH src AS MATERIALIZED (
|
|
2
|
+
SELECT s.${s(r)}::text AS source_key, nextval(pg_get_serial_sequence(?, ?)::regclass) AS target_key, ${d.map(_=>`s.${s(_)}`).join(", ")}
|
|
3
|
+
FROM (SELECT * FROM ${p(e)} ORDER BY ${s(r)}::bigint) s),
|
|
4
|
+
ins AS (INSERT INTO ${m(e)} (${s(r)}, ${d.map(s).join(", ")}) SELECT target_key, ${d.map(s).join(", ")} FROM src RETURNING 1),
|
|
5
5
|
km AS (INSERT INTO import_key_map (source_install_id, table_name, source_key, target_key) SELECT ?, ?, source_key, target_key::text FROM src RETURNING target_key)
|
|
6
|
-
SELECT target_key FROM km ORDER BY target_key::bigint`).all(
|
|
7
|
-
WHERE m.source_install_id = ? AND m.table_name = 'review_comment_events' AND m.source_key = c.created_seq::text`).run(
|
|
8
|
-
ORDER BY ${
|
|
6
|
+
SELECT target_key FROM km ORDER BY target_key::bigint`).all(m(e),r,T.installId,e);await R(e,S.map(_=>[_.target_key]))}await t.prepareUncached(`UPDATE ${p("review_comments")} c SET created_seq = m.target_key::bigint FROM import_key_map m
|
|
7
|
+
WHERE m.source_install_id = ? AND m.table_name = 'review_comment_events' AND m.source_key = c.created_seq::text`).run(T.installId);const g=G(l);await t.exec(`CREATE TABLE IF NOT EXISTS ${p("_filled")} (tbl text NOT NULL, k jsonb NOT NULL)`);const N=[];for(const e of g){if(e in A)continue;if(e==="profiles"){if(g.indexOf("identities")>g.indexOf("profiles"))throw new b("copy","bundle_invalid","identities must be copied before profiles");N.push(...await B(t,E,c,T,n.person))}const r=l.tables.get(e),u=Number((await t.prepareUncached(`SELECT count(*) AS n FROM ${p(e)}`).get()).n);if(u===0){f.inserted[e]=0;continue}const d=v(r),S=r.columns.filter(a=>!r.identity.includes(a)),_=r.identity.length>0?r.identity.map(a=>`s.${s(a)}`).join(", "):d.map(a=>`s.${s(a)}`).join(", ");let L=S.map(a=>`s.${s(a)}`),I="";if(e==="messages"){const a=`NOT EXISTS (SELECT 1 FROM ${m("messages")} t WHERE t.message_id = s.message_id)`,O=Number((await t.prepareUncached(`SELECT count(*) AS n FROM ${p("messages")} s WHERE ${a}`).get()).n);if(I=` WHERE ${a}`,O===0){f.inserted[e]=0,await R(e,[]);continue}const F=Number((await t.prepare("UPDATE message_sequence SET seq = seq + ? WHERE id = 1 RETURNING seq").get(O)).seq);L=S.map(w=>w==="seq"?`${F-O} + row_number() OVER (ORDER BY s.seq)`:`s.${s(w)}`)}const U=d.map(a=>`${s(a)}::text`).join(", "),$=r.primaryKey.length===0;$&&(I=` WHERE NOT EXISTS (SELECT 1 FROM ${m(e)} t WHERE ${d.map(a=>`t.${s(a)} IS NOT DISTINCT FROM s.${s(a)}`).join(" AND ")})`);const y=await t.prepareUncached(`INSERT INTO ${m(e)} (${S.map(s).join(", ")}) SELECT ${L.join(", ")} FROM ${p(e)} s${I}
|
|
8
|
+
ORDER BY ${_}${$?"":` ON CONFLICT (${d.map(s).join(", ")}) DO NOTHING`} RETURNING ${U}`).all();if(e===C){const a=await t.prepareUncached(`SELECT s.hash FROM ${p(e)} s JOIN ${m(e)} t ON t.hash = s.hash WHERE t.text IS DISTINCT FROM s.text LIMIT 10`).all();if(a.length>0)throw new b("copy","unique_conflict",`the target holds other text under body ${a[0].hash}; its boot repair has not rekeyed that row`,{table:e,hashes:a.map(O=>O.hash)})}e===C?f.inserted[e]=y.length:await R(e,y.map(a=>Object.values(a))),f.mapped[e]=u-y.length}for(const e of N)await t.prepare(`INSERT INTO ${p("_filled")} VALUES (?, ?::jsonb)`).run(e.table,JSON.stringify(e.key));for(const e of new Set(N.map(r=>r.table)))await P(t,i,e,N.filter(r=>r.table===e).map(r=>r.key));await t.prepareUncached(`DELETE FROM ${m("charge_totals")} t WHERE (t.month, t.payer) IN (SELECT DISTINCT month, payer FROM ${p("charges")})`).run(),await t.prepareUncached(`INSERT INTO ${m("charge_totals")} (month, payer, funding, sub, grantee, provider, usd, billed_usd)
|
|
9
9
|
SELECT month, payer, funding, COALESCE(sub, ''), grantee, COALESCE(provider, ''), COALESCE(SUM(usd), 0), COALESCE(SUM(billed_usd), 0)
|
|
10
|
-
FROM ${
|
|
11
|
-
GROUP BY month, payer, funding, COALESCE(sub, ''), grantee, COALESCE(provider, '')`).run();for(const[e,
|
|
10
|
+
FROM ${m("charges")} WHERE refused IS NULL AND kind <> 'take' AND (month, payer) IN (SELECT DISTINCT month, payer FROM ${p("charges")})
|
|
11
|
+
GROUP BY month, payer, funding, COALESCE(sub, ''), grantee, COALESCE(provider, '')`).run();for(const[e,r]of[["object",n.idMap.object],["grant",n.idMap.grant],["kind",n.idMap.kind]])for(const[u,d]of r)await t.prepare("INSERT INTO import_id_map (run_id, kind, source_value, target_value) VALUES (?, ?, ?, ?) ON CONFLICT DO NOTHING").run(i,e,u,d);for(const e of n.pathMap)await t.prepare("INSERT INTO import_id_map (run_id, kind, source_value, target_value) VALUES (?, 'path', ?, ?) ON CONFLICT DO NOTHING").run(i,e.from,e.to);return await t.prepare("UPDATE import_runs SET state = 'committed', committed_at = ?, step = 'copy' WHERE run_id = ?").run(new Date().toISOString(),i),f}o(Q,"copyRows");async function P(n,t,i,E){if(E.length===0)return;const c=await n.prepare("SELECT inserted_keys FROM import_manifest WHERE run_id = ? AND table_name = ?").get(t,i);c===void 0?await n.prepare("INSERT INTO import_manifest (run_id, table_name, inserted_keys) VALUES (?, ?, ?)").run(t,i,h(E)):await n.prepare("UPDATE import_manifest SET inserted_keys = ? WHERE run_id = ? AND table_name = ?").run(h([...M(c.inserted_keys),...E]),t,i)}o(P,"appendManifest");export{P as appendManifest,G as copyOrder,Q as copyRows,M as decodeKeys,h as encodeKeys,Z as nodesAwaitingVerify};
|
|
@@ -36,9 +36,17 @@ export declare function dropExistingWatches(db: CanvasDb, schema: string, target
|
|
|
36
36
|
watches: number;
|
|
37
37
|
watch_subscriptions: number;
|
|
38
38
|
}>;
|
|
39
|
+
/** A staged idempotency key whose (grantee, key) the target already holds is already imported (a hosted person's runs the control plane has since served): it is dropped, the target's
|
|
40
|
+
* row stands, so the copy never inserts it and verify never compares it. Only this key is skipped; any other difference still fails. Returns the dropped rows. Runs before the pre-check. */
|
|
41
|
+
export declare function dropExistingIdempotencyKeys(db: CanvasDb, schema: string, target: string): Promise<number>;
|
|
42
|
+
/** The rows `fillEnvironments` created, as manifest keys per table, so rollback removes them and verify (which has no staged row for them) skips them. */
|
|
43
|
+
export interface FilledRow {
|
|
44
|
+
table: string;
|
|
45
|
+
key: string[];
|
|
46
|
+
}
|
|
39
47
|
/** Fill: a staged profile with no environment gets the source's machine environment (a Mac) or the person's Blaxel environment (hosted, created if
|
|
40
48
|
* absent). Runs in the copy transaction: it writes target objects. */
|
|
41
|
-
export declare function fillEnvironments(tx: CanvasDb, schema: string, target: string, source: SourceJson, person: string): Promise<
|
|
49
|
+
export declare function fillEnvironments(tx: CanvasDb, schema: string, target: string, source: SourceJson, person: string): Promise<FilledRow[]>;
|
|
42
50
|
/** Staged edits that need nothing from the target but its key map: limits the directory or an operator wrote stay out, a hosted source's own
|
|
43
51
|
* machine environment is marked for the drop step, claims of the old runtime's lanes are cleared, and rows of the identity-keyed tables already in
|
|
44
52
|
* `import_key_map` are not staged again. Returns the rows removed per table. */
|
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
var D=Object.defineProperty;var E=(
|
|
2
|
-
AND split_part(blob_key, '/', 2) IN (SELECT node_id FROM ${a("nodes")} WHERE status IN ('active', 'idle'))`).all();let c=0;for(const{conversation_id:r,blob_key:
|
|
1
|
+
var D=Object.defineProperty;var E=(t,s)=>D(t,"name",{value:s,configurable:!0});import{createProfileBlaxelEnvironment as U}from"../../environments.js";import{KEY_MAPPED_TABLES as v,mapPath as S}from"../bundle/layout.js";import{ImportLaneError as N}from"./stage.js";import{withHeaderCwd as H}from"../../conversation-store/row-store.js";import{runBlobKey as M}from"../bundle/blob-keys.js";import{q as l}from"./catalog.js";const d=E((t,s)=>`${l(t)}.${l(s)}`,"sq");async function K(t,s,o){if(o.length===0)return 0;const e=E(c=>d(s,c),"S"),i=`(SELECT node_id FROM ${e("nodes")} WHERE status IN ('active', 'idle'))`;let a=0;const p=E(async(c,r,n,$=!1)=>{const R=await t.prepareUncached(`SELECT ${l(r)}::text AS value FROM ${e(c)} WHERE ${n} AND ${l(r)} IS NOT NULL`).all();for(const{value:f}of R){const T=$?g(f,o):S(o,f);T!==f&&(await t.prepareUncached(`UPDATE ${e(c)} SET ${l(r)} = ? WHERE ${l(r)}::text = ? AND ${n}`).run(T,f),a+=1)}},"apply");return await p("nodes","cwd",`node_id IN ${i}`),await p("worktrees","path",`node_id IN ${i}`),await p("worktrees","repo_root",`node_id IN ${i}`),await p("crons","cwd",`anchor_node IN ${i}`),await p("provider_approvals","prepared_files","TRUE",!0),await p("upload_uses","path",`run_id IN ${i}`),a}E(K,"rewritePaths");async function B(t,s,o,e,i){if(o.length===0)return 0;const a=E(r=>d(s,r),"S"),p=await t.prepareUncached(`SELECT conversation_id, blob_key FROM ${a("conversation_parts")} WHERE seq = 0
|
|
2
|
+
AND split_part(blob_key, '/', 2) IN (SELECT node_id FROM ${a("nodes")} WHERE status IN ('active', 'idle'))`).all();let c=0;for(const{conversation_id:r,blob_key:n}of p){const $=M(i,n),R=await e.get($);if(R===null)throw new N("rewrite-paths","bundle_invalid",`${$} is missing: the header of conversation ${r} cannot be rewritten`);const f=H(R,r,T=>S(o,T));f!==null&&(await e.put($,f),c+=1),await t.prepareUncached(`UPDATE ${a("conversation_parts")} SET bytes = ?, cycle_offset = NULL WHERE conversation_id = ? AND seq = 0`).run((f??R).length,r)}return c}E(B,"rewriteConversationHeaders");async function J(t,s){const o=d(s,"human_requests"),e=E(a=>`CASE WHEN ${a} IS NULL OR ${a} NOT LIKE '/%' THEN ${a}
|
|
3
3
|
WHEN rtrim(${a}, '/') = rtrim(request_dir, '/') THEN 'requests/' || request_id
|
|
4
4
|
WHEN ${a} LIKE rtrim(request_dir, '/') || '/%' THEN 'requests/' || request_id || '/' || substr(${a}, length(rtrim(request_dir, '/')) + 2)
|
|
5
|
-
ELSE 'requests/' || request_id || '/source/' || regexp_replace(${a}, '^.*/', '') END`,"moved"),i=await
|
|
6
|
-
request_dir = CASE WHEN request_dir LIKE '/%' THEN 'requests/' || request_id ELSE request_dir END`).run();return Number(i.changes)}E(J,"rewriteRequestPaths");function
|
|
7
|
-
WHERE o.type = 'profile' AND o.name = ?`).get(r.id,r.name),$=await
|
|
8
|
-
WHERE s.id LIKE 'legacy:%' AND t.id = s.id AND (s.payer IS DISTINCT FROM t.payer OR s.units IS DISTINCT FROM t.units OR s.usd IS DISTINCT FROM t.usd)`).run(e);return Number(i.changes)}E(X,"renameClashingLegacyCharges");async function G(
|
|
9
|
-
CREATE TABLE ${e("_arr_parents")} AS SELECT p.* FROM ${e("revision_parents")} p WHERE p.child IN (SELECT rev_id FROM ${e("revisions")} WHERE document IN ${i})`);const a=await
|
|
5
|
+
ELSE 'requests/' || request_id || '/source/' || regexp_replace(${a}, '^.*/', '') END`,"moved"),i=await t.prepareUncached(`UPDATE ${o} SET file = ${e("file")}, presentation_dir = ${e("presentation_dir")},
|
|
6
|
+
request_dir = CASE WHEN request_dir LIKE '/%' THEN 'requests/' || request_id ELSE request_dir END`).run();return Number(i.changes)}E(J,"rewriteRequestPaths");function g(t,s){const o=E(e=>typeof e=="string"?S(s,e):Array.isArray(e)?e.map(o):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([i,a])=>[i,o(a)])):e,"walk");try{return JSON.stringify(o(JSON.parse(t)))}catch{return S(s,t)}}E(g,"rewriteJsonPaths");async function Y(t,s,o,e,i){const a=E(r=>d(s,r),"S"),p=await t.prepareUncached(`SELECT id, name FROM ${a("profiles")} ORDER BY id`).all();let c=0;for(const r of p){const n=await t.prepareUncached(`SELECT o.id FROM ${a("objects")} o JOIN ${a("identities")} i ON i.object = o.id AND i.scheme = 'profile' AND i.external_id = ?
|
|
7
|
+
WHERE o.type = 'profile' AND o.name = ?`).get(r.id,r.name),$=await t.prepareUncached(`SELECT 1 AS found FROM ${d(o,"profiles")} WHERE person = ? AND name = ? AND id <> ?`).get(i,r.name,r.id),R=n===void 0?void 0:await t.prepareUncached(`SELECT 1 AS found FROM ${d(o,"objects")} WHERE type = 'profile' AND home_machine IS NULL AND name = ? AND id <> ?`).get(r.name,n.id);if($===void 0&&R===void 0)continue;const f=`${r.name}-${e}`;await t.prepareUncached(`UPDATE ${a("profiles")} SET name = ? WHERE id = ?`).run(f,r.id),n!==void 0&&await t.prepareUncached(`UPDATE ${a("objects")} SET name = ? WHERE id = ?`).run(f,n.id),c+=1}return c}E(Y,"renameClashingProfiles");async function X(t,s,o,e){const i=await t.prepareUncached(`UPDATE ${d(s,"charges")} s SET id = s.id || ':install-' || ?::text FROM ${d(o,"charges")} t
|
|
8
|
+
WHERE s.id LIKE 'legacy:%' AND t.id = s.id AND (s.payer IS DISTINCT FROM t.payer OR s.units IS DISTINCT FROM t.units OR s.usd IS DISTINCT FROM t.usd)`).run(e);return Number(i.changes)}E(X,"renameClashingLegacyCharges");async function G(t,s,o){const e=`FROM ${d(o,"watches")} t WHERE t.watcher = s.watcher AND t.object = s.object`,i=await t.prepareUncached(`DELETE FROM ${d(s,"watch_subscriptions")} u USING ${d(s,"watches")} s WHERE u.watch = s.watch_id AND EXISTS (SELECT 1 ${e})`).run(),a=await t.prepareUncached(`DELETE FROM ${d(s,"watches")} s WHERE EXISTS (SELECT 1 ${e})`).run();return{watches:Number(a.changes),watch_subscriptions:Number(i.changes)}}E(G,"dropExistingWatches");async function z(t,s,o){const e=await t.prepareUncached(`DELETE FROM ${d(s,"idempotency_keys")} s WHERE EXISTS (SELECT 1 FROM ${d(o,"idempotency_keys")} t WHERE t.grantee = s.grantee AND t.key = s.key)`).run();return Number(e.changes)}E(z,"dropExistingIdempotencyKeys");async function Q(t,s,o,e,i){const a=E(r=>d(s,r),"S"),p=[],c=await t.prepareUncached(`SELECT id, grantee FROM ${a("profiles")} WHERE environment_id IS NULL ORDER BY id`).all();for(const r of c){let n=e.kind==="machine"?e.environmentObject??null:null;if(e.kind==="hosted"){const $=await t.prepareUncached(`SELECT environment_id FROM ${d(o,"profiles")} WHERE id = ?`).get(r.id);if($?.environment_id!=null)n=$.environment_id;else{n=await U(t,{profileId:r.id,grantee:r.grantee??"app:terminal",person:i}),p.push({table:"objects",key:[n]},{table:"environments",key:[n]});for(const R of await t.prepareUncached("SELECT resource_type, resource_id, relation, subject_type, subject_id, subject_relation FROM relations WHERE resource_id = ?").all(n))p.push({table:"relations",key:[R.resource_type,R.resource_id,R.relation,R.subject_type,R.subject_id,R.subject_relation]})}}if(n===null)throw new N("fill","bundle_invalid",`profile ${r.id} has no environment and the source names none`);await t.prepareUncached(`UPDATE ${a("profiles")} SET environment_id = ? WHERE id = ?`).run(n,r.id)}return p}E(Q,"fillEnvironments");async function V(t,s,o,e){const i=E(c=>d(s,c),"S"),a={},p=E(async(c,r,...n)=>{const $=Number((await t.prepareUncached(r).run(...n)).changes);$>0&&(a[c]=(a[c]??0)+$)},"del");await p("limits",`DELETE FROM ${i("limits")} WHERE source <> 'person'`),e.kind==="hosted"&&(await t.prepareUncached(`UPDATE ${i("profiles")} SET environment_id = NULL WHERE environment_id IN (SELECT object FROM ${i("environments")})`).run(),await t.prepareUncached(`UPDATE ${i("objects")} SET home_machine = 'import-hosted-source' WHERE id IN (SELECT object FROM ${i("environments")})`).run());for(const[c,r]of Object.entries(v))await p(c,`DELETE FROM ${i(c)} WHERE ${l(r)}::text IN (SELECT source_key FROM import_key_map WHERE source_install_id = ? AND table_name = ?)`,e.installId,c);for(const c of o.tables.values())c.columns.includes("claimed_by")&&c.columns.includes("lease_expires_at")&&await t.prepareUncached(`UPDATE ${i(c.name)} SET claimed_by = NULL, lease_expires_at = NULL WHERE claimed_by IS NOT NULL OR lease_expires_at IS NOT NULL`).run();return a}E(V,"pruneStaged");async function Z(t,s,o){const e=E(p=>d(s,p),"S"),i=`(SELECT d.object FROM ${e("documents")} d WHERE EXISTS (SELECT 1 FROM ${d(o,"documents")} t WHERE t.object = d.object))`;await t.exec(`CREATE TABLE ${e("_arr_revisions")} AS SELECT r.* FROM ${e("revisions")} r WHERE r.document IN ${i};
|
|
9
|
+
CREATE TABLE ${e("_arr_parents")} AS SELECT p.* FROM ${e("revision_parents")} p WHERE p.child IN (SELECT rev_id FROM ${e("revisions")} WHERE document IN ${i})`);const a=await t.prepareUncached(`SELECT r.document, r.rev_id, r.body_hash, r.rationale, r.created_at,
|
|
10
10
|
COALESCE((SELECT array_agg(p.parent) FROM ${e("revision_parents")} p WHERE p.child = r.rev_id), ARRAY[]::text[]) AS parents
|
|
11
|
-
FROM ${e("revisions")} r WHERE r.document IN ${i} ORDER BY r.document, r.number`).all();return await
|
|
12
|
-
FROM (SELECT * FROM ${
|
|
13
|
-
FROM (SELECT ctid AS row_id, * FROM ${
|
|
14
|
-
FROM ${
|
|
11
|
+
FROM ${e("revisions")} r WHERE r.document IN ${i} ORDER BY r.document, r.number`).all();return await t.prepareUncached(`DELETE FROM ${e("revision_parents")} WHERE child IN (SELECT rev_id FROM ${e("revisions")} WHERE document IN ${i})`).run(),await t.prepareUncached(`DELETE FROM ${e("revisions")} WHERE document IN ${i}`).run(),await t.prepareUncached(`DELETE FROM ${e("objects")} WHERE id IN ${i}`).run(),await t.prepareUncached(`DELETE FROM ${e("documents")} WHERE object IN ${i}`).run(),a.map(p=>({...p}))}E(Z,"takeRepoSyncedDocuments");const C={edges:["created_at"],relations:["created_at"]},b={charges:["payer","units","usd"]};async function ee(t,s,o,e,i,a,p){const c=E(n=>[...p.get(n)??[],...n==="profiles"?["environment_id"]:[],...C[n]??[],"claimed_by","lease_expires_at"],"ignored"),r=[];for(const n of i){const $=e.tables.get(n);if($===void 0||a.has(n)||$.primaryKey.length===0)continue;const R=$.primaryKey,f=R.some(u=>$.identity.includes(u)),T=R.map(u=>`s.${l(u)} = t.${l(u)}`).join(" AND "),y=f?"TRUE":R.map(u=>`s.${l(u)} IS DISTINCT FROM t.${l(u)}`).join(" OR "),I=new Set([...$.identity,...p.get(n)??[]]);for(const u of e.uniqueKeys.filter(h=>h.table===n&&!h.columns.every(_=>I.has(_)))){const h=u.predicate===null?"":` WHERE ${u.predicate}`,_=u.columns.map(m=>`s.${l(m)} = t.${l(m)}`).join(" AND "),O=await t.prepareUncached(`SELECT ${u.columns.map(m=>`s.${l(m)}::text`).join(" || ',' || ")} AS value
|
|
12
|
+
FROM (SELECT * FROM ${d(s,n)}${h}) s JOIN (SELECT * FROM ${d(o,n)}${h}) t ON ${_} AND (${y}) LIMIT 10`).all();O.length>0&&r.push({table:n,key:u.name,values:O.map(m=>m.value)});const A=f?"TRUE":R.map(m=>`a.${l(m)} IS DISTINCT FROM b.${l(m)}`).join(" OR "),L=await t.prepareUncached(`SELECT DISTINCT ${u.columns.map(m=>`a.${l(m)}::text`).join(" || ',' || ")} AS value
|
|
13
|
+
FROM (SELECT ctid AS row_id, * FROM ${d(s,n)}${h}) a JOIN (SELECT ctid AS row_id, * FROM ${d(s,n)}${h}) b ON ${u.columns.map(m=>`a.${l(m)} = b.${l(m)}`).join(" AND ")} AND a.row_id < b.row_id AND (${A}) LIMIT 10`).all();L.length>0&&r.push({table:n,key:u.name,values:L.map(m=>m.value),staged:!0})}const w=$.columns.filter(u=>!$.identity.includes(u)&&!c(n).includes(u)&&(b[n]?.includes(u)??!0));if(w.length>0&&!f){const u=w.map(_=>`s.${l(_)} IS DISTINCT FROM t.${l(_)}`).join(" OR "),h=await t.prepareUncached(`SELECT ${R.map(_=>`s.${l(_)}::text`).join(" || ',' || ")} AS value
|
|
14
|
+
FROM ${d(s,n)} s JOIN ${d(o,n)} t ON ${T} WHERE ${u} LIMIT 10`).all();h.length>0&&r.push({table:n,key:"primary key payload",values:h.map(_=>_.value)})}}if(r.length>0){const n=r[0];throw new N("pre-check","unique_conflict",`${n.table} ${n.key} collides ${n.staged===!0?"within the bundle":"with the target"}: ${n.values.join(", ")}`,{collisions:r})}}E(ee,"precheck");export{z as dropExistingIdempotencyKeys,G as dropExistingWatches,Q as fillEnvironments,ee as precheck,V as pruneStaged,X as renameClashingLegacyCharges,Y as renameClashingProfiles,B as rewriteConversationHeaders,K as rewritePaths,J as rewriteRequestPaths,Z as takeRepoSyncedDocuments};
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
var
|
|
2
|
-
AND EXISTS (SELECT 1 FROM _rb
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
1
|
+
var A=Object.defineProperty;var b=(a,_)=>A(a,"name",{value:_,configurable:!0});import{openDb as k,withCanvasWrite as D}from"../../canvas/db.js";import{keyMatch as m,q as r,readCatalog as M,rowKey as u,topologicalOrder as h}from"./catalog.js";import{deleteOwnedBlobs as F,deleteRunPrefix as W}from"./blobs.js";import{decodeKeys as H}from"./copy.js";import{IMPORT_ROLLBACK_LOCK as $}from"../../graph/deletion.js";import{OBJECT_ID_COLUMNS as y}from"./rewrite.js";import{targetSchema as g}from"./stage.js";class N extends Error{static{b(this,"Refused")}}const v=new Set(["machine_credentials","machine_links"]);async function J(a,_){const E=await(await k()).prepare("SELECT source_install_id, source_kind, state, created_at, committed_at FROM import_runs WHERE run_id = ?").get(a);if(E===void 0)throw new Error(`no import run ${a}`);if(E.state!=="done"&&E.state!=="committed"&&E.state!=="failed")throw new Error(`import run ${a} is ${E.state}, not rollbackable`);const s={run_id:a,rolled_back:!1,dependents:{},deleted:{}},T={nodes:[],human_requests:[]};try{await D(async t=>{await t.prepare("SELECT pg_advisory_xact_lock(hashtext(?))").get($);const o=await g(t),f=(await t.prepareUncached("SELECT table_name FROM information_schema.tables WHERE table_schema = ? AND table_type = 'BASE TABLE'").all(o)).map(e=>e.table_name),d=await M(t,o,f);d.tables.get("env_vars").primaryKey=["person","owner_kind","owner_id","name"],await t.exec("CREATE TEMP TABLE _rb (tbl text NOT NULL, k jsonb NOT NULL) ON COMMIT DROP");const L=await t.prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ?").all(a);for(const{table_name:e,inserted_keys:i}of L){const n=H(i);(e==="nodes"||e==="human_requests")&&T[e].push(...n.map(c=>c[0]));for(let c=0;c<n.length;c+=5e3)await t.prepare("INSERT INTO _rb SELECT ?, e FROM jsonb_array_elements(?::jsonb) e").run(e,JSON.stringify(n.slice(c,c+5e3)))}E.committed_at!==null&&(await t.prepareUncached(`CREATE TEMP TABLE _fill ON COMMIT DROP AS SELECT o.id FROM ${r(o)}.objects o WHERE o.type = 'environment' AND o.kind = 'blaxel' AND o.created_at >= ? AND o.created_at <= ?
|
|
2
|
+
AND o.owner IN (SELECT k ->> 0 FROM _rb WHERE tbl = 'objects') AND NOT EXISTS (SELECT 1 FROM _rb x WHERE x.tbl = 'objects' AND x.k ->> 0 = o.id)`).run(E.created_at,E.committed_at),await t.exec("INSERT INTO _rb SELECT 'objects', jsonb_build_array(id) FROM _fill"),await t.exec(`INSERT INTO _rb SELECT 'environments', jsonb_build_array(e.object) FROM ${r(o)}.environments e WHERE e.object IN (SELECT id FROM _fill)`),await t.exec(`INSERT INTO _rb SELECT 'relations', jsonb_build_array(r.resource_type, r.resource_id, r.relation, r.subject_type, r.subject_id, r.subject_relation) FROM ${r(o)}.relations r WHERE r.resource_id IN (SELECT id FROM _fill)`));const p=new Set((await t.prepareUncached("SELECT DISTINCT tbl FROM _rb").all()).map(e=>e.tbl));await t.exec("ANALYZE _rb");for(const e of d.foreignKeys){const i=d.tables.get(e.parent),n=d.tables.get(e.table);if(e.table==="import_node_files"||v.has(e.table)||!p.has(e.parent)||i===void 0||n===void 0||e.parentColumns.join()!==i.primaryKey.join())continue;const c=p.has(e.table)?`AND NOT EXISTS (SELECT 1 FROM _rb o WHERE o.tbl = '${e.table}' AND ${m(n,u(n),"c","o.k")})`:"",l=Number((await t.prepareUncached(`SELECT count(*) AS n FROM ${r(o)}.${r(e.table)} c WHERE ${e.columns.map(w=>`c.${r(w)} IS NOT NULL`).join(" AND ")}
|
|
3
|
+
AND EXISTS (SELECT 1 FROM _rb p WHERE p.tbl = '${e.parent}' AND ${m(n,e.columns,"c","p.k")}) ${c}`).get()).n);l>0&&(s.dependents[e.table]=(s.dependents[e.table]??0)+l)}for(const[e,i]of y){const n=d.tables.get(e);if(n===void 0||!n.columns.includes(i)||n.primaryKey.length===0)continue;const c=p.has(e)?`AND NOT EXISTS (SELECT 1 FROM _rb o WHERE o.tbl = '${e}' AND ${m(n,n.primaryKey,"c","o.k")})`:"",l=Number((await t.prepareUncached(`SELECT count(*) AS n FROM ${r(o)}.${r(e)} c WHERE c.${r(i)} IN (SELECT k ->> 0 FROM _rb WHERE tbl = 'objects') ${c}`).get()).n);l>0&&(s.dependents[`${e}.${i}`]=l)}const S=Number((await t.prepare("SELECT count(*) AS n FROM import_runs WHERE source_install_id = ? AND run_id <> ? AND created_at > ? AND (state IN ('loading', 'committed', 'done') OR (state = 'failed' AND committed_at IS NOT NULL))").get(E.source_install_id,a,E.created_at)).n);S>0&&(s.dependents.import_runs=S);const O=Number((await t.prepare("SELECT count(*) AS n FROM import_id_map m WHERE m.run_id <> ? AND m.kind = 'object' AND m.target_value IN (SELECT k ->> 0 FROM _rb WHERE tbl = 'objects')").get(a)).n);if(O>0&&(s.dependents.import_id_map=O),Object.keys(s.dependents).length>0)throw new N;const C=(await t.prepareUncached(`SELECT DISTINCT r.document FROM ${r(o)}.revisions r WHERE r.rev_id IN (SELECT k ->> 0 FROM _rb WHERE tbl = 'revisions')
|
|
4
|
+
AND NOT EXISTS (SELECT 1 FROM _rb o WHERE o.tbl = 'objects' AND o.k ->> 0 = r.document)`).all()).map(e=>e.document);for(const e of h(d,[...p]).reverse()){const i=d.tables.get(e);if(i===void 0)continue;e==="run_events"&&await t.prepareUncached(`SELECT 1 FROM ${r(o)}.run_events t WHERE EXISTS (SELECT 1 FROM _rb k WHERE k.tbl = 'run_events' AND ${m(i,u(i),"t","k.k")}) ORDER BY t."run_id" COLLATE "C", t."sequence_number" FOR UPDATE`).all();const n=await t.prepareUncached(`DELETE FROM ${r(o)}.${r(e)} t WHERE EXISTS (SELECT 1 FROM _rb k WHERE k.tbl = '${e}' AND ${m(i,u(i),"t","k.k")})`).run();s.deleted[e]=n.changes}for(const e of C)await t.prepareUncached(`UPDATE ${r(o)}.documents d SET
|
|
5
|
+
heads_key = COALESCE((SELECT string_agg(r.rev_id, ',' ORDER BY r.rev_id) FROM ${r(o)}.revisions r WHERE r.document = d.object AND NOT EXISTS (SELECT 1 FROM ${r(o)}.revision_parents p WHERE p.parent = r.rev_id)), ''),
|
|
6
|
+
revision = COALESCE((SELECT max(r.number) FROM ${r(o)}.revisions r WHERE r.document = d.object AND NOT EXISTS (SELECT 1 FROM ${r(o)}.revision_parents p WHERE p.parent = r.rev_id)), 0)
|
|
7
|
+
WHERE d.object = ?`).run(e);await t.prepareUncached("DELETE FROM import_key_map km WHERE km.source_install_id = ? AND EXISTS (SELECT 1 FROM _rb r WHERE r.tbl = km.table_name AND r.k ->> 0 = km.target_key)").run(E.source_install_id),await t.prepare("DELETE FROM import_id_map WHERE run_id = ?").run(a),await t.prepare("DELETE FROM import_manifest WHERE run_id = ?").run(a),await t.prepare("UPDATE import_runs SET state = 'rolled_back', step = 'rolled_back', finished_at = ? WHERE run_id = ?").run(new Date().toISOString(),a),await I(t,E)})}catch(t){if(t instanceof N)return s;throw t}return await W(_,a),await F(_,T.nodes,T.human_requests),s.rolled_back=!0,s}b(J,"rollbackRun");async function I(a,_){if(_.source_kind!=="machine")return;const R=await a.prepare("SELECT object FROM environments WHERE machine_id = ? AND kind = 'machine'").get(_.source_install_id);R!==void 0&&await a.prepare("UPDATE machine_credentials SET revoked_at = ? WHERE environment = ? AND revoked_at IS NULL").run(new Date().toISOString(),R.object)}b(I,"revokeFor");export{J as rollbackRun};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var
|
|
1
|
+
var Q=Object.defineProperty;var m=(e,r)=>Q(e,"name",{value:r,configurable:!0});import{zstdCompressSync as V}from"node:zlib";import{blobStore as X}from"../../blobs/index.js";import{openDb as E,withCanvasWrite as D}from"../../canvas/db.js";import{runAsPerson as A}from"../../canvas/person.js";import{insertImportedRevisions as Z}from"../../graph/documents.js";import{getById as x}from"../../graph/objects.js";import{bundleKeys as B,decodeRows as ee,rowKeys as L,SEQ_TABLES as te}from"../bundle/layout.js";import{readCatalog as ae}from"./catalog.js";import{appendManifest as N,copyRows as ne,decodeKeys as ie}from"./copy.js";import{pruneStaged as se,precheck as re,dropExistingIdempotencyKeys as oe,dropExistingWatches as de,renameClashingLegacyCharges as pe,renameClashingProfiles as ce,rewriteConversationHeaders as ue,rewritePaths as le,rewriteRequestPaths as fe,takeRepoSyncedDocuments as me}from"./prepare.js";import{boundSub as _e,dropRefusedMessages as we,checkSourcePerson as ge,checkStagedBlobKeys as be,checkStagedPersons as he,checkStagedReferences as ye,checkStagedRequestKeys as Se}from"./bind.js";import{deleteBlobs as ve,deleteRunBlobs as Ee,deleteRunPrefix as Re,moveRunBlobs as Ie}from"./blobs.js";import{dropStubRows as Oe,findFleetGrant as Pe,grantMissing as je,mapProfileIds as ke,renameClashingRepos as Te,rewriteIds as Ce,rewritePerson as Me,scopeRepoIdentities as De}from"./rewrite.js";import{dropStaging as W,ImportLaneError as g,stage as Ae,stagingSchema as Be,targetSchema as Le}from"./stage.js";import{verifyRun as Ne}from"./verify.js";import{sandboxPathMap as We,writeNodeFiles as Ke}from"./path-map.js";import{allStoreKeys as He,readPluginsStore as Ue,recordImportedActivations as Fe,writeStores as Je}from"./stores.js";import{openImportGrants as Ge}from"./open-grants.js";import{publishImportedPlugins as qe}from"./publish-plugins.js";import{COPIED_TABLES as $e}from"../bundle/layout.js";import{emitEvent as Ye}from"../../events/emit.js";import{ClaimLostError as ze}from"../../../daemon/reconcilers/row-claim.js";const Qe=10*6e4,Ve=30*6e4,R=m(()=>new Date().toISOString(),"now"),K=m(async(e,r)=>{await(await E()).prepare("UPDATE import_runs SET step = ? WHERE run_id = ?").run(r,e)},"setStep");async function Xe(e,r){const i=await e.get(B.source(r));if(i===null)throw new g("stage","bundle_invalid","source.json is missing");const a=JSON.parse(i.toString("utf8"));if(typeof a.rowParts!="object"||a.rowParts===null)throw new g("stage","bundle_invalid","source.json names no row parts");return a}m(Xe,"readSource");async function Ze(e,r,i,a,n,d,p){const o=[];for(const t of L(i.run_id,"grants",a)){const c=await e.get(t);if(c===null)throw new g("stage","bundle_invalid",`row file ${t} is missing`);o.push(...ee(c))}if(o.length===0)return;const w=o.map(t=>({sub:_e(t.sub,a.person,i.person,"grants.sub"),grantee:t.grantee}));await p(i.run_id);const f=[];for(const t of w)await Pe(r,n,d,t.sub,t.grantee)===void 0&&f.push(t.grantee);if(f.length>0)throw je(f)}m(Ze,"ensureGrants");async function Ot(e,r,i={}){const a=i.blobs??await X(),n=await E(),d=Be(e.run_id);let p="start";const o=m(async t=>{p=t,await r.assertOwned(),await K(e.run_id,t),await i.atStep?.(t)},"at");let w=e.state==="committed";const f=[];try{const t=await Xe(a,e.run_id);if(e.source_kind==="machine"&&t.installId!==e.source_install_id)throw new g("stage","bundle_invalid",`source.json names install ${t.installId}, the run is for ${e.source_install_id}`);t.installId=e.source_install_id;const c=await Le(n),I=[...$e],h=await ae(n,c,[...I,"grants"]);if(!w){const l={},P=[],j=[],k=i.fleetRuntime??process.env.CRTR_RUNTIME??null;await ge(n,c,t.person,e.person),await o("open-grants"),await Ze(a,n,e,t,c,k,i.openGrants??Ge),await o("publish-plugins");const H=await Ue(a,e.run_id),S=await A(e.person,()=>qe(H));if(S.unavailable.length>0){if(e.loaded_at===void 0||e.loaded_at===null)throw new g("publish-plugins","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(e.loaded_at)>=Qe)throw new g("publish-plugins","directory_unavailable",`the directory did not answer for: ${S.unavailable.slice(0,10).join(", ")}; rerun the import once it is reachable`,{plugins:S.unavailable});await r.assertOwned(),await K(e.run_id,"waiting_for_directory");return}j.push(...S.refused),await o("stage");const U=await Ae(n,e.run_id,t.counts,s=>L(e.run_id,s,t),s=>a.get(s));for(const[s,u]of Object.entries(U))l[s]={staged:u,inserted:0,mapped:0,dropped:0};const _={db:n,schema:d,target:c,catalog:h,sourcePerson:t.person,targetPerson:e.person,fleetRuntime:k,shippedBodies:t.shippedBodies??{}};await o("bind-staged");for(const[s,u]of Object.entries(await he(_)))b(l,s,u);for(const[s,u]of Object.entries(await be(_)))b(l,s,u);await o("rewrite-person"),await Me(_),await De(_),await o("prune");const F=await se(n,d,h,t),v=t.kind==="hosted"?We(t.pathPrefixes??[]):[];await o("rewrite-paths"),await le(n,d,v),await ue(n,d,v,a,e.run_id),await fe(n,d),await Se(_);const J=await ke(_);await ce(n,d,c,t.installId,e.person),await o("rewrite-ids");const T=await Ce(_,J);await o("drop");const G=await me(n,d,c),q=await Oe(_);for(const[s,u]of Object.entries({...F}))b(l,s,u);for(const[s,u]of Object.entries(q))b(l,s,u);for(const[s,u]of Object.entries(await we(_,{installId:t.installId,person:e.person,runId:e.run_id})))b(l,s,u);await ye(_,{installId:t.installId,person:e.person,runId:e.run_id}),await Te(_),await pe(n,d,c,t.installId);for(const[s,u]of Object.entries(await de(n,d,c)))b(l,s,u);b(l,"idempotency_keys",await oe(n,d,c)),await o("pre-check");const $=new Map([["messages",["seq"]],...te.map(s=>[s,["seq"]])]);await re(n,d,c,h,I,new Set,$),await o("blobs"),await Ie(n,d,c,e.person,a,e.run_id,f),await o("copy"),await A(e.person,()=>D(async s=>{await r.assertOwned({extendLeaseMs:Ve});const u=await ne({db:s,runId:e.run_id,schema:d,target:c,catalog:h,source:t,person:e.person,idMap:T,pathMap:v}),C=await tt(s,e.run_id,G);C>0&&(u.inserted.revisions=(u.inserted.revisions??0)+C),await Ke(s,d,e.run_id,t);const M=await Je({db:s,blobs:a,runId:e.run_id,person:e.person,objectMap:T.object});for(const[Y,z]of Object.entries(M.inserted))u.inserted[Y]=z.length;return P.push(...M.unresolvedPlugins),await s.prepare("UPDATE import_runs SET counts_json = ?, loaded_at = COALESCE(loaded_at, ?) WHERE run_id = ?").run(JSON.stringify({...et(l,u),unresolved_plugins:P,refused_plugins:j}),R(),e.run_id),u})),w=!0,await i.atStep?.("committed")}await o("verify");const y=await Ne(n,e.run_id,d,c,h,t.installId);if(await n.prepare("UPDATE import_runs SET verify_json = ? WHERE run_id = ?").run(JSON.stringify(y),e.run_id),!y.ok)throw new g("verify","verify_failed","the committed rows differ from the staged rows or an invariant failed",{differences:y.differences,invariants:y.invariants});await o("manifest");const O=B.manifest(e.run_id);await a.put(O,await at(e.run_id)),await W(n,e.run_id);for(const l of He(e.run_id))await a.delete(l);await Ee(a,e.run_id),await D(async l=>{await Fe(l,e.run_id,e.person),await l.prepare("UPDATE import_runs SET state = 'done', step = 'done', manifest_key = ?, finished_at = ? WHERE run_id = ?").run(O,R(),e.run_id)})}catch(t){if(t instanceof ze)throw t;const c=xe(t,p);Ye({level:"error",event:"import.run.failed",error:t,fields:{run_id:e.run_id,step:c.step,code:c.code}}),await W(n,e.run_id).catch(()=>{}),w||await ve(a,f,!0),await n.prepare("UPDATE import_runs SET state = 'failed', failure_json = ?, finished_at = ? WHERE run_id = ?").run(JSON.stringify(c),R(),e.run_id),await Re(a,e.run_id,{keepNodeFiles:w,bestEffort:!0})}}m(Ot,"processRun");function xe(e,r){if(e instanceof g)return{step:e.step,code:e.code,message:e.message,...e.detail===void 0?{}:{detail:e.detail}};const i=e.code;return{step:r,code:typeof i=="string"?i:"import_failed",message:e instanceof Error?e.message:String(e)}}m(xe,"failureOf");function b(e,r,i){(e[r]??={staged:0,inserted:0,mapped:0,dropped:0}).dropped+=i}m(b,"addDropped");function et(e,r){for(const[i,a]of Object.entries(r.inserted))(e[i]??={staged:0,inserted:0,mapped:0,dropped:0}).inserted=a;for(const[i,a]of Object.entries(r.mapped))(e[i]??={staged:0,inserted:0,mapped:0,dropped:0}).mapped=a;return e}m(et,"withInserted");async function tt(e,r,i){const a=new Set((await e.prepareUncached("SELECT rev_id FROM revisions WHERE rev_id IN (SELECT jsonb_array_elements_text(?::jsonb))").all(JSON.stringify(i.map(p=>p.rev_id)))).map(p=>p.rev_id)),n=i.filter(p=>!a.has(p.rev_id)),d=new Map;for(const p of i)d.set(p.document,[...d.get(p.document)??[],p]);for(const[p,o]of d){const w=await x(e,p);w!==null&&await Z(e,w,o.map(f=>({rev_id:f.rev_id,parents:f.parents,body_hash:f.body_hash,rationale:f.rationale,created_at:f.created_at})))}return await N(e,r,"revisions",n.map(p=>[p.rev_id])),await N(e,r,"revision_parents",n.flatMap(p=>p.parents.map(o=>[p.rev_id,o]))),n.length}m(tt,"arrive");async function at(e){const i=await(await E()).prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ? ORDER BY table_name").all(e);return V(Buffer.from(i.map(a=>JSON.stringify({table:a.table_name,keys:ie(a.inserted_keys)})).join(`
|
|
2
2
|
`)+`
|
|
3
|
-
`))}
|
|
3
|
+
`))}m(at,"manifestFile");export{Ve as COPY_LEASE_MS,Qe as GRANT_WAIT_MS,Ot as processRun};
|
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
var j=Object.defineProperty;var
|
|
2
|
-
JOIN ${o(e,t)} s ON s.${r(i)}::text = km.source_key`}else
|
|
1
|
+
var j=Object.defineProperty;var $=(n,N)=>j(n,"name",{value:N,configurable:!0});import{KEY_MAPPED_TABLES as v}from"../bundle/layout.js";import{keyMatch as h,q as r,rowKey as W}from"./catalog.js";import{archiveCutoffs as H,BODY_TYPES as J}from"../../events/run-event-chunks.js";import{MEMORY_READS_RETENTION_MS as x}from"../../canvas/memory-reads.js";import{PURGE_RETENTION_MS as B}from"../../storage/purge.js";import{decodeKeys as Y}from"./copy.js";const o=$((n,N)=>`${r(n)}.${r(N)}`,"sq"),P={messages:["seq"]},K=["claimed_by","lease_expires_at"],X={worktrees:["attempts","next_attempt_at","sweep_reason","sweep_detail","sweep_last_at","sweep_observed_json"]},q=10*6e4;function M(n,N,e,c,s,m=[]){if(e==="objects")return`${c}."id" IN (${s})`;if(m.includes(e))return"false";const a=[];e==="object_kinds"&&a.push(`${c}."owner" IN (${s})`);for(const E of n.foreignKeys){if(E.table!==e||!E.cascade||E.columns.length!==1)continue;const S=`${c}.${r(E.columns[0])}`;if(E.parent==="objects"){a.push(`${S} IN (${s})`);continue}const O=M(n,N,E.parent,"p",s,[...m,e]);O!=="false"&&a.push(`${S} IN (SELECT p.${r(E.parentColumns[0])} FROM ${o(N,E.parent)} p WHERE ${O})`)}return a.length===0?"false":`(${a.join(" OR ")})`}$(M,"removedWithPurgedObject");function I(n,N,e){const c=Date.now()+q,s=[];if(e==="run_events"){const{bodyCutoff:E,controlCutoff:S}=H(c);s.push(`(s.ts < '${S}' OR (s.ts < '${E}' AND s.type IN (${J.map(O=>`'${O}'`).join(", ")})))`)}e==="memory_reads"&&s.push(`s.at < '${new Date(c-x).toISOString()}'`);const m=`SELECT o.id FROM ${o(N,"objects")} o WHERE o.deleted_at IS NOT NULL AND (o.type = 'node' OR o.deleted_at < '${new Date(c-B).toISOString()}')`,a=M(n,N,e,"s",m);return a!=="false"&&s.push(a),s.length===0?"false":`(${s.join(" OR ")})`}$(I,"removedByMaintenance");async function oe(n,N,e,c,s,m){const a={},E={},S=await n.prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ?").all(N);await n.exec(`CREATE TABLE IF NOT EXISTS ${r(e)}._filled (tbl text NOT NULL, k jsonb NOT NULL)`),await n.exec(`DROP TABLE IF EXISTS ${r(e)}._m; CREATE TABLE ${r(e)}._m (tbl text NOT NULL, k jsonb NOT NULL)`);for(const{table_name:t,inserted_keys:d}of S){const _=s.tables.get(t);if(_===void 0)continue;const u=Y(d);if(u.length===0)continue;await n.prepare(`DELETE FROM ${r(e)}._m WHERE tbl = ?`).run(t);for(let i=0;i<u.length;i+=5e3)await n.prepare(`INSERT INTO ${r(e)}._m SELECT ?, e FROM jsonb_array_elements(?::jsonb) e`).run(t,JSON.stringify(u.slice(i,i+5e3)));await n.exec(`ANALYZE ${r(e)}._m`);const T=[..._.identity,...P[t]??[],...K,...X[t]??[]].map(i=>`'${i.replace(/'/g,"''")}'`).join(", ")||"''",l=$(i=>`to_jsonb(${i}) - ARRAY[${T}]::text[]`,"strip"),p=W(_);let A;if(t in v){const i=v[t];A=`JOIN import_key_map km ON km.source_install_id = '${m.replace(/'/g,"''")}' AND km.table_name = '${t}' AND km.target_key = m.k ->> 0
|
|
2
|
+
JOIN ${o(e,t)} s ON s.${r(i)}::text = km.source_key`}else A=`JOIN ${o(e,t)} s ON ${p.map((i,w)=>`s.${r(i)}::text = m.k ->> ${w}`).join(" AND ")}`;const F=` AND NOT EXISTS (SELECT 1 FROM ${o(e,"_filled")} f WHERE f.tbl = '${t}' AND f.k = m.k)`+(t==="revisions"?` AND m.k ->> 0 NOT IN (SELECT rev_id FROM ${o(e,"_arr_revisions")})`:t==="revision_parents"?` AND NOT EXISTS (SELECT 1 FROM ${o(e,"_arr_parents")} a WHERE a.child = m.k ->> 0 AND a.parent = m.k ->> 1)`:""),k=`FROM ${o(e,"_m")} m LEFT JOIN ${o(c,t)} t ON ${h(_,p,"t","m.k")} ${A.replace("JOIN","LEFT JOIN")} WHERE m.tbl = '${t}'${F}`,U=`${k} AND ((t.${r(p[0])} IS NULL AND NOT (s.${r(p[0])} IS NOT NULL AND ${I(s,e,t)})) OR s.${r(p[0])} IS NULL OR (${l("t")}) <> (${l("s")}))`,D=await n.prepareUncached(`SELECT count(*) AS n, array_agg(k) FILTER (WHERE rn <= 10) AS keys FROM (SELECT m.k::text AS k, row_number() OVER () AS rn ${U}) d`).get(),C=Number(D.n);if(C>0&&(a[t]={count:C,keys:D.keys??[]}),I(s,e,t)!=="false"){const i=Number((await n.prepareUncached(`SELECT count(*) AS n ${k} AND t.${r(p[0])} IS NULL AND s.${r(p[0])} IS NOT NULL AND ${I(s,e,t)}`).get()).n);i>0&&(E[t]=i)}}for(const[t,d]of[["revisions",`FROM ${o(e,"_m")} m JOIN ${o(e,"_arr_revisions")} a ON a.rev_id = m.k ->> 0 LEFT JOIN revisions t ON t.rev_id = a.rev_id
|
|
3
3
|
WHERE m.tbl = 'revisions' AND (t.rev_id IS NULL OR t.document <> a.document OR t.body_hash <> a.body_hash OR t.rationale IS DISTINCT FROM a.rationale OR t.created_at <> a.created_at)`],["revision_parents",`FROM ${o(e,"_m")} m JOIN ${o(e,"_arr_parents")} a ON a.child = m.k ->> 0 AND a.parent = m.k ->> 1 LEFT JOIN revision_parents t ON t.child = a.child AND t.parent = a.parent
|
|
4
|
-
WHERE m.tbl = 'revision_parents' AND t.child IS NULL`]]){const
|
|
5
|
-
INSERT INTO ${
|
|
6
|
-
UNION ALL SELECT key, false FROM ${o(e,"_dropped")} WHERE tbl = 'objects') u GROUP BY key; ANALYZE ${
|
|
7
|
-
CROSS JOIN LATERAL (VALUES ${
|
|
8
|
-
WHERE m.tbl = ? GROUP BY v.col ORDER BY v.col`).all(t);for(const{col:
|
|
4
|
+
WHERE m.tbl = 'revision_parents' AND t.child IS NULL`]]){const _=Number((await n.prepareUncached(`SELECT count(*) AS n ${d}`).get()).n);_>0&&(a[`${t}.arrived`]={count:_,keys:[]})}const O={},R=o(e,"_ids");await n.exec(`DROP TABLE IF EXISTS ${R}; CREATE TABLE ${R} (key text PRIMARY KEY, mapped boolean NOT NULL);
|
|
5
|
+
INSERT INTO ${R} SELECT key, bool_or(mapped) FROM (SELECT source AS key, true AS mapped FROM ${o(e,"_idmap")} WHERE kind = 'object'
|
|
6
|
+
UNION ALL SELECT key, false FROM ${o(e,"_dropped")} WHERE tbl = 'objects') u GROUP BY key; ANALYZE ${R}`);let L=!1;for(const{table_name:t}of S){const d=s.tables.get(t);if(d===void 0||L||d.primaryKey.length===0)continue;const _=(await n.prepareUncached("SELECT column_name FROM information_schema.columns WHERE table_schema = ? AND table_name = ? AND data_type = 'text'").all(c,t)).map(l=>l.column_name).filter(l=>!(d.primaryKey.includes(l)&&t==="objects"));if(_.length===0)continue;const u=_.map(l=>`('${l.replace(/'/g,"''")}', t.${r(l)})`).join(", "),T=await n.prepareUncached(`SELECT v.col AS col, count(*) AS n FROM ${o(e,"_m")} m JOIN ${o(c,t)} t ON ${h(d,d.primaryKey,"t","m.k")}
|
|
7
|
+
CROSS JOIN LATERAL (VALUES ${u}) v(col, val) JOIN ${R} i ON i.key = v.val${t==="messages"?" AND i.mapped":""}
|
|
8
|
+
WHERE m.tbl = ? GROUP BY v.col ORDER BY v.col`).all(t);for(const{col:l,n:p}of T)L=!0,a[`${t}.${l}`]={count:Number(p),keys:["holds a dropped object id"]}}O.no_dropped_id=!L;const b=S.find(t=>t.table_name==="revisions");let y=!0,f=0;if(b!==void 0){const t=`FROM ${o(e,"_m")} m JOIN revisions r ON r.rev_id = m.k ->> 0 WHERE m.tbl = 'revisions' AND NOT EXISTS (SELECT 1 FROM bodies b WHERE b.hash = r.body_hash)`;y=await n.prepare(`SELECT 1 AS lost ${t} AND EXISTS (SELECT 1 FROM ${o(e,"bodies")} s WHERE s.hash = r.body_hash) LIMIT 1`).get()===void 0,f=Number((await n.prepare(`SELECT count(*) AS n ${t} AND NOT EXISTS (SELECT 1 FROM ${o(e,"bodies")} s WHERE s.hash = r.body_hash)`).get()).n)}O.revision_bodies_readable=y,O.revision_bodies_canonical=b===void 0||await n.prepare(`SELECT 1 AS wrong FROM ${o(e,"_m")} m JOIN revisions r ON r.rev_id = m.k ->> 0 JOIN bodies b ON b.hash = r.body_hash
|
|
9
9
|
WHERE m.tbl = 'revisions' AND encode(sha256(convert_to(b.text, 'UTF8')), 'hex') <> b.hash LIMIT 1`).get()===void 0;const g=await n.prepare(`SELECT 1 AS found FROM (
|
|
10
10
|
SELECT month, payer, funding, COALESCE(sub, '') AS sub, grantee, COALESCE(provider, '') AS provider, COALESCE(SUM(usd), 0) AS usd, COALESCE(SUM(billed_usd), 0) AS billed
|
|
11
11
|
FROM charges WHERE refused IS NULL AND kind <> 'take' AND (month, payer) IN (SELECT DISTINCT month, payer FROM ${o(e,"charges")}) GROUP BY 1, 2, 3, 4, 5, 6) c
|
|
12
12
|
FULL JOIN charge_totals t ON t.month = c.month AND t.payer = c.payer AND t.funding = c.funding AND t.sub = c.sub AND t.grantee = c.grantee AND t.provider = c.provider
|
|
13
|
-
WHERE (COALESCE(t.month, c.month), COALESCE(t.payer, c.payer)) IN (SELECT DISTINCT month, payer FROM ${o(e,"charges")}) AND (c.month IS NULL OR t.month IS NULL OR c.usd <> t.usd OR c.billed <> t.billed_usd) LIMIT 1`).get();return O.charge_totals_equal_recompute=g===void 0,{ok:Object.keys(a).length===0&&Object.values(O).every(Boolean),differences:a,...Object.keys(E).length>0?{archived:E}:{},...f>0?{source_missing_bodies:f}:{},invariants:O}}
|
|
13
|
+
WHERE (COALESCE(t.month, c.month), COALESCE(t.payer, c.payer)) IN (SELECT DISTINCT month, payer FROM ${o(e,"charges")}) AND (c.month IS NULL OR t.month IS NULL OR c.usd <> t.usd OR c.billed <> t.billed_usd) LIMIT 1`).get();return O.charge_totals_equal_recompute=g===void 0,{ok:Object.keys(a).length===0&&Object.values(O).every(Boolean),differences:a,...Object.keys(E).length>0?{archived:E}:{},...f>0?{source_missing_bodies:f}:{},invariants:O}}$(oe,"verifyRun");export{oe as verifyRun};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var A=Object.defineProperty;var r=(t,i)=>A(t,"name",{value:i,configurable:!0});import{chmodSync as N,closeSync as Y,existsSync as F,mkdirSync as k,openSync as L,unlinkSync as G,writeFileSync as J,rmSync as R}from"node:fs";import{createServer as X}from"node:http";import{dirname as K,join as z}from"node:path";import{spawn as V}from"node:child_process";import{SELF_UPDATE_SCRIPT as W}from"../core/self-update.js";import{apiSocketPath as $,crtrHome as b}from"../core/canvas/paths.js";import{bindDaemonEventSource as Q}from"../core/events/source.js";import{emitEvent as d}from"../core/events/emit.js";import{brokerCommandDeclaresCanvasHome as Z}from"../core/runtime/broker-ownership.js";import{createMachineExecutor as q,findBrokers as ee,stopAllBrokers as ne}from"../core/runtime/runner/machine/executor.js";import{machineCheckoutHandlers as te}from"../core/checkout-identities.js";import{machineWorktreeHandlers as oe}from"../core/worktree-machine.js";import{readPersonCredential as re}from"../core/directory/person-credential.js";import{socketDir as ie}from"../core/layout.js";import{isDaemonRunning as ae,pidfilePath as I,readPidfile as se}from"./pidfile.js";import{spawnDaemon as ce}from"./manage.js";import{cancelMachineCron as de,runMachineCron as me,stopOrphanedMachineCrons as le}from"./cron/machine-exec.js";import{startMachineLink as fe}from"./machine-link/client.js";import{deleteMoveRecord as P,readMachineConfig as pe,readMachineCredential as C,readMoveRecord as ue,writeMoveRecord as he}from"./machine-link/config.js";import{jobExitReporting as ve,stopMachineJob as _e}from"./machine-link/job-sweep.js";import{notifyMoveFinished as we}from"./machine-link/move-notify.js";import{machineSupervision as ye,SUPERVISION_TICK_MS as Se}from"./machine-supervision.js";import{startBrokerMemoryCap as Ie}from"./broker-memory-cap.js";const D=10*6e4,ge=3e4,Ee=75;let g=0;function Me(t,i){if(Date.now()-g<D||!/^\d+\.\d+\.\d+$/.test(t))return;g=Date.now(),d({level:"warn",event:"daemon.machine.updating",fields:{release:t}});const s=L(z(b(),"crtrd.err"),"a"),n=V(process.execPath,[W,"--version",t],{stdio:["ignore",s,s]});Y(s),n.on("error",a=>d({level:"error",event:"daemon.machine.update_failed",fields:{release:t},error:a})),n.on("exit",a=>{if(a===Ee){g=Date.now()-D+ge;return}if(a!==0){d({level:"error",event:"daemon.machine.update_failed",fields:{release:t,exit_code:a}});return}i()})}r(Me,"updateToRelease");const O=1024;function Te(t,i){return{ok:!0,daemon_up:!0,store_accessible:!1,brokers_reconciled:!1,link_connected:t,signed_in:i,startup_phase:t?"ready":"recovering"}}r(Te,"machineHealth");async function en(){const t=pe();if(t===void 0)throw new Error("crtrd --role machine needs runtime/machine.json: this install has not been imported as a machine");const i=re()!==void 0;if(i&&C(),ae())throw new Error("a crtrd is already running for this home");Q(),i||(await ne(),await le(),d({level:"info",event:"daemon.machine.signed_out",fields:{environment:t.environmentId}})),k(ie(),{recursive:!0,mode:493});const s=$();F(s)&&G(s);let n;const a=ve(()=>n),c=X((e,o)=>{const m=(e.url??"").split("?")[0];if(e.method==="POST"&&(m==="/job-exit"||m==="/job-activity")){const T=[];let S=0;e.on("data",l=>{S+=l.length,S<=O&&T.push(l)}),e.on("end",()=>{if(S>O){o.writeHead(413),o.end();return}let l={};try{l=JSON.parse(Buffer.concat(T).toString("utf8"))}catch{}const x=typeof l.node=="string"&&typeof l.job=="string";o.writeHead(x?202:400,{"content-type":"application/json; charset=utf-8"}),o.end("{}"),x&&(m==="/job-exit"?a.notice:a.activity)(l.node,l.job)});return}const M=(e.method??"GET")==="GET"&&(e.url??"/").split("?")[0]==="/healthz";o.writeHead(M?200:404,{"content-type":"application/json; charset=utf-8"}),o.end(JSON.stringify(M?Te(n?.connected()===!0,i):{error:{code:"not_found",message:"a machine-role crtrd serves only /healthz",origin:"runtime"}}))});await new Promise((e,o)=>{c.once("error",o),c.listen(s,()=>{c.off("error",o),N(s,384),e()})}),k(K(I()),{recursive:!0}),J(I(),String(process.pid),"utf8");let f;t.runId!==void 0&&await Re(t.runId,i,()=>f!==void 0);const u=new Set,v=new Set;let _=!1;const p=q({apiUrl:t.apiUrl,environmentId:t.environmentId,onExit:r(e=>n?.reportExit(e),"onExit")}),j=r(async(e,o)=>{u.add(e.executionId);for(const m of v)m.add(e.executionId);try{return await p.start(e,o)}finally{u.delete(e.executionId)}},"start");n=i?fe({apiUrl:t.apiUrl,environmentId:t.environmentId,credential:C,onOpen:r(()=>{a.onOpen(),_=!0},"onOpen"),onBehind:r(e=>Me(e,U),"onBehind"),handlers:{start:j,wake:p.wake,stop:p.stop,status:p.status,delete:p.delete,viewer:p.viewer,"cron.run":me,"cron.cancel":de,"job.stop":r(e=>_e(e),"job.stop"),...oe,...te}}):void 0;const E=n===void 0?void 0:ye({link:n,brokers:r(async()=>{const e=new Set(u);v.add(e);const o=await ee().finally(()=>v.delete(e));return _&&(_=!1,n?.reportRunning([...new Set([...e,...o.filter(m=>Z(m.command,b())).map(m=>m.execution)])])),o},"brokers"),stop:r((e,o)=>p.stop({execution:{executionId:e,nodeId:o,attempt:0},options:{reason:"yield_stall"}}),"stop")});let w=!1;const B=E===void 0?void 0:setInterval(()=>{w||(w=!0,E(Date.now()).catch(e=>d({level:"error",event:"daemon.machine.supervision_failed",error:e})).finally(()=>{w=!1}))},Se),H=Ie();d({level:"info",event:"daemon.machine.started",fields:{environment:t.environmentId}});const y=r(()=>f??=(async()=>{n?.stop(),clearInterval(B),H(),await new Promise(e=>{c.close(()=>e()),c.closeAllConnections()}),se()===process.pid&&(R(s,{force:!0}),R(I(),{force:!0})),process.off("SIGINT",h),process.off("SIGTERM",h)})(),"teardown"),U=r(async()=>{if(f===void 0){await y();try{const e=await ce();d({level:"info",event:"daemon.machine.replaced",fields:{successor_pid:e.pid??e.existing_pid??null}}),process.exit(0)}catch(e){d({level:"error",event:"daemon.machine.successor_failed",error:e}),process.exit(1)}}},"replaceSelf"),h=r(()=>{y().then(()=>process.exit(0),()=>process.exit(1))},"onSignal");return process.on("SIGINT",h),process.on("SIGTERM",h),y}r(en,"runMachineDaemon");const xe=5e3,ke=3e5;async function Re(t,i,s){let n;try{n=ue()}catch(c){d({level:"warn",event:"daemon.machine.move_record_unreadable",fields:{error:c.message}});return}if(n===void 0||n.state==="running"||n.runId!==t)return;if(n.notified||n.notify===null){P();return}if(n.state==="committed"&&(n={...n,state:"activated"},he(n)),!i)return;const a=n;(async()=>{let c=xe;for(;;){try{await we(a),P();return}catch(f){d({level:"warn",event:"daemon.machine.move_notify_failed",fields:{node:a.notify??"",error:f.message}})}if(await new Promise(f=>{setTimeout(f,c).unref()}),s())return;c=Math.min(c*2,ke)}})()}r(Re,"settleFinishedMove");export{Te as machineHealth,en as runMachineDaemon};
|
package/dist/daemon/manage.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type HealthDTO, type StartupPhaseDTO } from '../api/index.js';
|
|
2
2
|
import type { DumpResult } from '../core/import/export/dump.js';
|
|
3
|
-
/**
|
|
3
|
+
/** Non-`CRTR_*` env keys that must NEVER reach the daemon process. Restarting crtrd is
|
|
4
4
|
* overwhelmingly done from inside an agent node's own bash tool (`crtr sys
|
|
5
5
|
* daemon stop && start`), which inherits that node's FULL env — its identity
|
|
6
6
|
* (`CRTR_NODE_ID`/`CRTR_KIND`/…, the `nodeEnv()` shape in `core/runtime/
|
|
@@ -15,10 +15,10 @@ import type { DumpResult } from '../core/import/export/dump.js';
|
|
|
15
15
|
* relaunch it ever attempts, for its whole lifetime — the 2026-07-06 diagnosis
|
|
16
16
|
* root cause behind 19 nodes killed with "failed to relaunch and is now dead". */
|
|
17
17
|
export declare const DAEMON_ENV_STRIP_KEYS: readonly string[];
|
|
18
|
-
/**
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
*
|
|
18
|
+
/** Whether a daemon process inherits this env name. */
|
|
19
|
+
export declare function daemonKeepsEnv(key: string): boolean;
|
|
20
|
+
/** A copy of `process.env` for a daemon process: the ordinary host env and the operator `CRTR_*` settings pass; every
|
|
21
|
+
* per-execution `CRTR_*` name and every `DAEMON_ENV_STRIP_KEYS` entry is dropped. */
|
|
22
22
|
export declare function sanitizedDaemonEnv(): NodeJS.ProcessEnv;
|
|
23
23
|
/** A crtrd declares its owning canvas in argv, so ownership is an exact match
|
|
24
24
|
* on this process's canvas home. Untagged daemons retain their own
|
package/dist/daemon/manage.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var
|
|
2
|
-
`).at(-1)??"";return JSON.parse(u)}o(
|
|
3
|
-
${r}`),this.name="DaemonExitedBeforeReadyError",this.stderrTail=r}}class
|
|
1
|
+
var q=Object.defineProperty;var o=(t,e)=>q(t,"name",{value:e,configurable:!0});import{spawn as K,execFileSync as J}from"node:child_process";import{createRequire as Q}from"node:module";import{dirname as N,join as T}from"node:path";import{fileURLToPath as Z,pathToFileURL as I}from"node:url";import{existsSync as F,lstatSync as tt,mkdirSync as et,openSync as H,closeSync as G,fstatSync as W,readSync as rt}from"node:fs";import{crtrHome as S}from"../core/canvas/paths.js";import{listProcessTable as nt}from"../core/canvas/pid.js";import{bindDaemonEventSource as ot,eventSource as at}from"../core/events/source.js";import{hostExecPath as y}from"../core/runtime/branded-host.js";import{isDaemonRunning as it,readPidfile as w,isPidAlive as R}from"./pidfile.js";import{DAEMON_STARTUP_WINDOW_MS as V}from"./startup-policy.js";import{computerIsUnset as st,readMachineConfig as ct}from"./machine-link/config.js";import{exclusiveLockOwnerPid as ut}from"../core/exclusive-lock.js";import{onDiskMigrationLockPath as lt}from"../core/canvas/paths.js";import{envNoDaemonAutostart as _t}from"../shared/env.js";import{waitForDaemonAvailability as dt}from"../api/index.js";import{localClient as pt}from"../api/node-transport.js";const Rt=["TMUX","TMUX_PANE","NODE_OPTIONS"],ft=new Set(["CRTR_HOME","CRTR_RUNTIME_HOME","CRTR_PIDFILE","CRTR_RUNTIME","CRTR_INSTALL_ID","CRTR_LOG","CRTR_DEBUG","CRTR_DEBUG_PID_LIVENESS","CRTR_TIMING","CRTR_TIMING_PROC","CRTR_NO_DAEMON_AUTOSTART","CRTR_NO_AUTO_UPDATE","CRTR_NO_AUTO_INIT","CRTR_NO_EXPORTS","CRTR_LAYOUT_REFUSE","CRTR_POSTGRES_HOME","CRTR_DATABASE_URL","CRTR_DATABASE_SCHEMA","CRTR_DATABASE_POOL_MAX","CRTR_SCHEMA_DATABASE_URL","CRTR_DOCUMENT_PORT","CRTR_LAUNCHER_SOCKET","CRTR_API_ADDRESS","CRTR_DIRECTORY_URL","CRTR_PUBLIC_API_URL","CRTR_CANVAS_URL","CRTR_CANVAS_CLIENT_ID","CRTR_CANVAS_JWK_FILE","CRTR_SECRETS_KEY","CRTR_IMPORT_SERVICE_TOKEN","CRTR_PACKAGES_TOKEN","CRTR_FEEDBACK_ENDPOINT","CRTR_FEEDBACK_TOKEN","CRTR_SUPPORT_REPO","CRTR_BRANDED_HOST","CRTR_CODESIGN_IDENTITY","CRTR_PLUGIN_REVALIDATE_TTL_MS","CRTR_IMPORT_BLOB_WORKERS","CRTR_MAX_LIVE_BROKERS","CRTR_WARN_LIVE_BROKERS","CRTR_BROKER_RSS_CAP_MB","CRTR_UNATTENDED_PARK_MS","CRTR_WARM_POOL","CRTR_STREAM_WATCHDOG_MS","CRTR_CONVERSATION_COMMIT_DEADLINE_MS","CRTR_NAME_MODEL","CRTR_MODEL_PROVIDER","CRTR_BROKER_SIGNAL_LONG_PROOF"]),mt=["CRTR_DB_","CRTR_BOOT_","CRTR_R2_","CRTR_LEDGER_","CRTR_BASH_","CRTR_WATCHER_","CRTR_RECAP_","CRTR_MODEL_AUTH_","CRTR_TEST_","CRTR_FAULT_"];function ht(t){return Rt.includes(t)?!1:t.startsWith("CRTR_")?ft.has(t)||mt.some(e=>t.startsWith(e)):!0}o(ht,"daemonKeepsEnv");function g(){const t={};for(const[e,r]of Object.entries(process.env))ht(e)&&(t[e]=r);return t}o(g,"sanitizedDaemonEnv");function Et(){for(let t=N(Z(import.meta.url));;t=N(t)){if(F(T(t,"bin","runtime-generation-manifest.mjs")))return t;if(N(t)===t)throw new Error(`cannot locate the crouter generation root from ${import.meta.url}`)}}o(Et,"generationRoot");async function P(){const t=Et(),e=I(T(t,"bin","runtime-generation-manifest.mjs")).href,{runtimeHome:r}=await import(e);try{tt(T(r(),"selected"))}catch(u){if(u.code!=="ENOENT")throw u;return["--conditions","crtr-src","--import",I(Q(import.meta.url).resolve("tsx/esm")).href,T(t,"src","daemon","crtrd-cli.ts")]}const n=I(T(t,"bin","runtime-selector.mjs")).href,{tryResolveRuntime:a}=await import(n),s=a("daemon");if(!s.ok)throw new Error(`cannot resolve the selected runtime generation's daemon entry: ${s.error}`);return[s.runtime.entryPath]}o(P,"resolveDaemonLaunch");function Tt(t,e){return t.includes(` --canvas-home ${e} `)||t.endsWith(` --canvas-home ${e}`)}o(Tt,"daemonCommandDeclaresCanvasHome");function wt(){const t=nt();if(t===null)return[];const e=S(),r=[];for(const{pid:n,command:a}of t)a.includes("daemon/crtrd")&&Tt(a,e)&&n!==process.pid&&r.push(n);return r}o(wt,"findDaemonPids");function Dt(t){const e=wt().filter(n=>n!==t);for(const n of e)try{process.kill(n,"SIGTERM")}catch{}if(e.length===0)return e;const r=Date.now()+2e3;for(;Date.now()<r&&e.some(n=>R(n));)J("sleep",["0.1"]);for(const n of e)if(R(n))try{process.kill(n,"SIGKILL")}catch{}return e}o(Dt,"sweepStrayDaemons");async function Qt(){const t=process.execve;if(t===void 0)throw new Error(`this Node.js ${process.version} runtime cannot replace PID 1 with the successor daemon`);const e=y(),r=await P();return t(e,[e,...r,"--canvas-home",S()],g())}o(Qt,"execDaemon");async function C(t){const e=await P(),r=K(y(),[...e,...t],{stdio:["ignore","pipe","pipe"],env:g()});let n="",a="";r.stdout.setEncoding("utf8").on("data",c=>{n+=c}),r.stderr.setEncoding("utf8").on("data",c=>{a+=c});const s=await new Promise((c,d)=>{r.once("error",d),r.once("close",f=>c(f))});if(s!==0)throw new Error(a.trim()||`the ${t[0]} process exited with code ${s}`);const u=n.trim().split(`
|
|
2
|
+
`).at(-1)??"";return JSON.parse(u)}o(C,"runDaemonEntry");function Zt(){return C(["export-sqlite"])}o(Zt,"runDaemonExportSqlite");function te(t,e){return C(["import-dump",t,e])}o(te,"runDaemonImportDump");function ee(t){return C(["import-dump",t,"bodies"])}o(ee,"runDaemonBodiesDump");function re(){return C(["import-dump","","install-id"])}o(re,"runDaemonInstallId");const j=2e4,L=10,v=1e3;async function b(t=v){const e=Math.min(t,v);return pt({autostart:!1,timeoutMs:e}).probeHealthz(e)}o(b,"probeDaemonHealth");function St(t){const e=t instanceof Error?t.message:String(t);if(typeof t!="object"||t===null)return e;const r=t.code,n=t.cause,a=typeof r=="string"?r:n?.code;return typeof a=="string"&&!e.includes(a)?`${e}: ${a}`:e}o(St,"probeErrorMessage");async function X(t=v){const e=await b(t);if(e.startup_phase==="blocked"){const r=w()??process.pid;throw new O(r,e.startup_blocked??"daemon startup is blocked")}if(!e.ok)throw new Error(e.startup_blocked??"crtrd health check reported not ready")}o(X,"probeDaemonServing");async function ne(){try{return await X(),!0}catch{return!1}}o(ne,"isDaemonServing");function U(t){return new Promise(e=>{setTimeout(e,t)})}o(U,"sleepMs");class k extends Error{static{o(this,"DaemonExitedBeforeReadyError")}stderrTail;constructor(e,r){super(r===""?e:`${e}
|
|
3
|
+
${r}`),this.name="DaemonExitedBeforeReadyError",this.stderrTail=r}}class Y extends Error{static{o(this,"DaemonLaunchError")}constructor(e){super(e instanceof Error?e.message:String(e),{cause:e}),this.name="DaemonLaunchError"}}class O extends Error{static{o(this,"DaemonStartupBlockedError")}constructor(e,r){super(`daemon ${e} is running but normal startup is blocked: ${r}`),this.name="DaemonStartupBlockedError"}}class B extends Error{static{o(this,"DaemonNotPreparedError")}constructor(e,r){super(r===void 0?`daemon ${e} is serving but did not report the prepared startup phase`:`daemon ${e} reported startup phase ${r}, not prepared`),this.name="DaemonNotPreparedError"}}async function At(t,e=V,r={},n="ready"){const a=r.readPidfile??w,s=r.isPidAlive??R,u=r.childExited,c=r.isDaemonServing,d=r.probeDaemonServing??(async h=>{if(c!==void 0){if(await c())return;throw new Error("crtrd health check reported not ready")}await X(h)}),f=r.probeDaemonHealth??b,D=r.sleepMs??U,i=r.now??Date.now;let p=null,l=null;return await dt({windowMs:e,pollIntervalMs:L,now:i,sleep:D,retry:o(h=>h!==l,"retry"),probe:o(async h=>{const m=a();if(m===null||!s(m)){const _=u?.();throw _!=null&&(_.signal!==null?l=new k(`daemon ${t} exited before becoming ready (by ${_.signal})`,r.childStderrTail?.()??""):_.code!==0&&(l=new k(`daemon ${t} exited before becoming ready (with exit code ${_.code??"?"})`,r.childStderrTail?.()??"")),l!==null)?l:new Error(`daemon ${t} has no live pidfile owner`)}if(n==="ready"){try{await d(h)}catch(_){throw _ instanceof O&&(l=_),_}p=m;return}const E=await f(h);if(E.startup_phase==="prepared"){p=m;return}throw E.startup_phase==="blocked"?(l=new O(m,E.startup_blocked??"on-disk migration is blocked"),l):E.startup_phase==="ready"?(l=new B(m,E.startup_phase),l):new Error(`daemon ${m} is ${E.startup_phase??"not reporting a startup phase"}; waiting for prepared`)},"probe")}),p===t?null:p}o(At,"verifyDaemonStartup");async function Ct(t,e=j,r={}){const n=r.readPidfile??w,a=r.isPidAlive??R,s=r.sleepMs??U,u=r.now??Date.now,c=u()+e;for(;u()<=c;){if(!a(t)&&n()!==t)return;await s(L)}throw new Error(`daemon ${t} did not exit and release its pidfile within ${e}ms`)}o(Ct,"waitForDaemonExit");const Ot=2e3,xt=5e3;async function z(t,e=j,r={}){const n=r.isPidAlive??R,a=r.sleepMs??U,s=r.now??Date.now;try{process.kill(t,"SIGTERM")}catch{}try{return await Ct(t,e,r),"terminated"}catch{}try{process.kill(t,"SIGKILL")}catch{}const u=s()+Ot;for(;s()<=u;){if(!n(t))return"killed";await a(L)}throw new Error(`daemon ${t} survived both SIGTERM and SIGKILL`)}o(z,"stopDaemonProcess");async function oe(){const t=w(),e=t!==null&&R(t),r=e&&await z(t)==="killed",n=Dt(null);return{stopped:e||n.length>0,...e?{pid:t}:{},strays_killed:n,force_killed:r}}o(oe,"stopAllDaemons");function Mt(t,e,r=2048){let n;try{n=H(t,"r");const{size:a}=W(n),s=Math.max(e,a-r),u=a-s;if(u<=0)return"";const c=Buffer.alloc(u);return rt(n,c,0,u,s),c.toString("utf8").trim()}catch{return""}finally{if(n!==void 0)try{G(n)}catch{}}}o(Mt,"readLogTailFrom");async function Nt(t={}){if(process.platform==="linux"&&F("/run/crtr/launcher.sock")&&!R(w()??-1)&&ct()===void 0)throw new Error("crtrd is managed by the root launcher; it cannot self-daemonize");const e=t.targetPhase??"ready",r=w();if(r!==null&&R(r))try{const i=await b();if(e==="prepared"){if(i.startup_phase==="prepared")return{started:!1,existing_pid:r,startup_phase:i.startup_phase};throw new B(r,i.startup_phase)}return i.ok?{started:!1,existing_pid:r,...i.startup_phase===void 0?{}:{startup_phase:i.startup_phase}}:{started:!1,existing_pid:r,running:!0,serving:!1,probe_error:i.startup_blocked??"crtrd health check reported not ready",...i.startup_phase===void 0?{}:{startup_phase:i.startup_phase}}}catch(i){if(i instanceof B)throw i;return{started:!1,existing_pid:r,running:!0,serving:!1,probe_error:St(i)}}et(S(),{recursive:!0});const n=await P().catch(i=>{throw new Y(i)}),a=T(S(),"crtrd.err"),s=H(a,"a"),u=(()=>{try{return W(s).size}catch{return 0}})();at()===void 0&&ot();const c=K(y(),[...n,"--canvas-home",S(),...e==="prepared"?["--prepare"]:[]],{detached:!0,stdio:["ignore",s,s],env:g()});G(s);const d=c.pid;if(d===void 0)throw new Error("daemon spawn did not return a pid");let f=null;c.once("exit",(i,p)=>{f={code:i,signal:p}}),c.unref();let D;try{D=await At(d,V,{childExited:o(()=>f,"childExited"),childStderrTail:o(()=>Mt(a,u),"childStderrTail")},e)}catch(i){const p=ut(lt())===d;if(f===null&&!p&&!(i instanceof O))try{await z(d,xt)}catch{}throw i}return D!==null?{started:!1,existing_pid:D,startup_phase:e}:{started:!0,pid:d,startup_phase:e}}o(Nt,"spawnDaemon");function It(){return _t()||process.argv.includes("--no-autostart")}o(It,"autostartDisabled");const yt=5e3,gt=6e4;let $=!1,A,x=0,M=0;function Pt(t){return Math.min(yt*2**(t-1),gt)}o(Pt,"autostartBackoffMs");function Lt(){A=void 0,x=0,M=0}o(Lt,"resetDaemonAutostart");function ae(){return A}o(ae,"daemonAutostartStartupFailure");function ie(t={}){const e=t.isDaemonRunning??it,r=t.spawnDaemon??Nt,n=t.now??Date.now;if(!It()&&!(!t.spawnDaemon&&st())&&!$&&!(n()<M)){if(e()){Lt();return}A=void 0,$=!0,r().then(()=>{A=void 0,x=0,M=0},a=>{(a instanceof k||a instanceof Y)&&(A=a.message),x+=1,M=n()+Pt(x)}).finally(()=>{$=!1})}}o(ie,"ensureDaemon");export{Rt as DAEMON_ENV_STRIP_KEYS,k as DaemonExitedBeforeReadyError,Y as DaemonLaunchError,B as DaemonNotPreparedError,O as DaemonStartupBlockedError,It as autostartDisabled,ae as daemonAutostartStartupFailure,Tt as daemonCommandDeclaresCanvasHome,ht as daemonKeepsEnv,ie as ensureDaemon,Qt as execDaemon,wt as findDaemonPids,ne as isDaemonServing,b as probeDaemonHealth,X as probeDaemonServing,St as probeErrorMessage,Lt as resetDaemonAutostart,ee as runDaemonBodiesDump,Zt as runDaemonExportSqlite,te as runDaemonImportDump,re as runDaemonInstallId,g as sanitizedDaemonEnv,Nt as spawnDaemon,oe as stopAllDaemons,z as stopDaemonProcess,Dt as sweepStrayDaemons,At as verifyDaemonStartup,Ct as waitForDaemonExit};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.743",
|
|
4
4
|
"description": "crtr — agent runtime with memory, plugins, and marketplaces",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -158,8 +158,8 @@
|
|
|
158
158
|
},
|
|
159
159
|
"license": "UNLICENSED",
|
|
160
160
|
"dependencies": {
|
|
161
|
-
"@north-light/identity": "0.3.
|
|
162
|
-
"@north-light/plugin": "0.3.
|
|
161
|
+
"@north-light/identity": "0.3.743",
|
|
162
|
+
"@north-light/plugin": "0.3.743",
|
|
163
163
|
"@earendil-works/chord": "1.5.2",
|
|
164
164
|
"@earendil-works/pi-agent-core": "1.5.2",
|
|
165
165
|
"@earendil-works/pi-ai": "1.5.2",
|