@north-light/crouter 0.3.355 → 0.3.357
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/dto/delivery.d.ts +13 -3
- package/dist/api/dto/objects.d.ts +24 -22
- package/dist/api/dto/objects.js +1 -1
- package/dist/clients/attach/session/document-links.js +1 -1
- package/dist/clients/attach/viewer.js +829 -755
- package/dist/commands/canvas/list.js +3 -3
- package/dist/commands/canvas/read.d.ts +2 -4
- package/dist/commands/canvas/read.js +3 -5
- package/dist/commands/canvas/search.js +1 -1
- package/dist/commands/sys/context/admin/actions.js +1 -1
- package/dist/commands/sys/sync-deps.js +1 -1
- package/dist/commands/sys/sync-shared.js +1 -1
- package/dist/core/canvas/daemon-actions.d.ts +43 -0
- package/dist/core/canvas/daemon-actions.js +26 -0
- package/dist/core/canvas/deliveries.d.ts +1 -0
- package/dist/core/canvas/deliveries.js +1 -1
- package/dist/core/canvas/migrations.js +106 -46
- package/dist/core/feed/messages.d.ts +2 -20
- package/dist/core/feed/messages.js +6 -10
- package/dist/core/graph/events.d.ts +10 -5
- package/dist/core/graph/events.js +5 -5
- package/dist/core/graph/jobs.js +2 -2
- package/dist/core/graph/kinds/document.d.ts +19 -0
- package/dist/core/graph/kinds/document.js +5 -0
- package/dist/core/graph/kinds/dto.d.ts +5 -0
- package/dist/core/graph/kinds/dto.js +1 -0
- package/dist/core/graph/kinds/job.d.ts +2 -0
- package/dist/core/graph/kinds/job.js +2 -0
- package/dist/core/graph/kinds/kind.d.ts +39 -0
- package/dist/core/graph/kinds/kind.js +1 -0
- package/dist/core/graph/kinds/node.d.ts +2 -0
- package/dist/core/graph/kinds/node.js +4 -0
- package/dist/core/graph/kinds/owner.d.ts +2 -0
- package/dist/core/graph/kinds/owner.js +2 -0
- package/dist/core/graph/kinds/registry.d.ts +8 -0
- package/dist/core/graph/kinds/registry.js +1 -0
- package/dist/core/graph/kinds/render.d.ts +9 -0
- package/dist/core/graph/kinds/render.js +1 -0
- package/dist/core/graph/objects.d.ts +5 -4
- package/dist/core/graph/objects.js +5 -5
- package/dist/core/graph/types.d.ts +6 -5
- package/dist/core/providers/errors.d.ts +97 -0
- package/dist/core/providers/errors.js +1 -0
- package/dist/core/runtime/broker-protocol.d.ts +2 -7
- package/dist/daemon/api/app-listener.js +12 -12
- package/dist/daemon/api/handlers/human-requests.js +1 -1
- package/dist/daemon/api/handlers/objects.js +2 -5
- package/dist/daemon/api/handlers/providers.d.ts +69 -0
- package/dist/daemon/api/handlers/providers.js +1 -0
- package/dist/daemon/api/operations.js +1 -1
- package/dist/daemon/api/server.js +1 -1
- package/dist/daemon/cron/settle.js +1 -1
- package/dist/daemon/cron/sinks.d.ts +3 -3
- package/dist/daemon/cron/sinks.js +2 -2
- package/dist/daemon/crtrd.js +6 -6
- package/dist/daemon/human/finish.js +6 -6
- package/dist/daemon/human/settle.d.ts +2 -3
- package/dist/daemon/human/settle.js +1 -1
- package/dist/daemon/reconcilers/action-lane.d.ts +8 -0
- package/dist/daemon/reconcilers/action-lane.js +1 -0
- package/dist/daemon/reconcilers/delivery-lane.d.ts +1 -1
- package/dist/daemon/reconcilers/delivery-lane.js +1 -1
- package/package.json +2 -2
- package/packages/crouter-identity/package.json +1 -1
- package/runtime.lock.json +11 -11
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var Ee=Object.defineProperty;var o=(e,
|
|
1
|
+
var Ee=Object.defineProperty;var o=(e,t)=>Ee(e,"name",{value:t,configurable:!0});import{randomBytes as Te}from"node:crypto";import{parseScope as ie}from"@north-light/crouter-identity";import{importNodeSqlAuthority as se,recreateNodeRowsView as re}from"./node-sql-migration.js";import{migrateRecoveryWitnesses as ae}from"./recovery.js";import{migrateMessagingState as de}from"./deliveries.js";import{migrateHumanRequestsState as _e}from"../human/requests.js";import{existsSync as p,readFileSync as C,readdirSync as U,realpathSync as Ne,statSync as ce}from"node:fs";import{basename as Le,join as y,resolve as H}from"node:path";import{isSafeNodeId as ue,nodesRoot as X,nodeMetaPath as f}from"./paths.js";import{convertLegacyEdges as le}from"../../migrations/004-canvas-documents/legacy-edges.js";import{customExtensionPaths as pe}from"./extensions.js";import{readMetaObject as P,updateJsonFileDurably as Y,withMetaLock as Ae,writeMetaObjectLocked as Oe}from"./meta-file.js";function Re(e){e.exec(`
|
|
2
2
|
CREATE TABLE IF NOT EXISTS nodes (
|
|
3
3
|
node_id TEXT PRIMARY KEY,
|
|
4
4
|
name TEXT NOT NULL,
|
|
@@ -23,7 +23,7 @@ CREATE TABLE IF NOT EXISTS edges (
|
|
|
23
23
|
CREATE INDEX IF NOT EXISTS idx_edges_to ON edges(type, to_id);
|
|
24
24
|
CREATE INDEX IF NOT EXISTS idx_edges_from ON edges(type, from_id);
|
|
25
25
|
CREATE INDEX IF NOT EXISTS idx_nodes_status ON nodes(status);
|
|
26
|
-
`)}o(Re,"baselineSchema");function
|
|
26
|
+
`)}o(Re,"baselineSchema");function h(e,t){return new Set(e.prepare(`PRAGMA table_info(${t})`).all().map(n=>n.name))}o(h,"tableColumns");function W(e,t,n,E){t.has(n)||(e.exec(E),t.add(n))}o(W,"addColumnIfMissing");function L(e){return h(e,"nodes")}o(L,"nodeColumns");const r=W;function Ie(e){const t=L(e);r(e,t,"intent","ALTER TABLE nodes ADD COLUMN intent TEXT;"),r(e,t,"pi_pid","ALTER TABLE nodes ADD COLUMN pi_pid INTEGER;"),r(e,t,"window","ALTER TABLE nodes ADD COLUMN window TEXT;"),r(e,t,"tmux_session","ALTER TABLE nodes ADD COLUMN tmux_session TEXT;")}o(Ie,"addRuntimeColumns");function me(e){const t=X();if(!p(t))return;const n=e.prepare('UPDATE nodes SET intent = ?, pi_pid = ?, "window" = ?, tmux_session = ? WHERE node_id = ?');for(const E of U(t)){const s=f(E);if(!p(s))continue;let T;try{T=JSON.parse(C(s,"utf8"))}catch{continue}n.run(T.intent??null,T.pi_pid??null,T.window??null,T.tmux_session??null,E)}}o(me,"backfillRuntime");function Xe(e){if(!(e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'edges'").get()!==void 0)){e.exec(`
|
|
27
27
|
CREATE TABLE edges (
|
|
28
28
|
type TEXT NOT NULL,
|
|
29
29
|
from_id TEXT NOT NULL,
|
|
@@ -36,7 +36,7 @@ CREATE TABLE edges (
|
|
|
36
36
|
);
|
|
37
37
|
CREATE INDEX IF NOT EXISTS idx_edges_to ON edges(type, to_id);
|
|
38
38
|
CREATE INDEX IF NOT EXISTS idx_edges_from ON edges(type, from_id);
|
|
39
|
-
`);return}e.exec("PRAGMA foreign_keys = OFF;");try{const
|
|
39
|
+
`);return}e.exec("PRAGMA foreign_keys = OFF;");try{const n=e.prepare(`SELECT COUNT(*) AS n FROM edges
|
|
40
40
|
WHERE from_id IN (SELECT node_id FROM nodes)
|
|
41
41
|
AND to_id IN (SELECT node_id FROM nodes)`).get().n;e.exec("BEGIN");try{e.exec(`
|
|
42
42
|
CREATE TABLE edges_new (
|
|
@@ -57,14 +57,14 @@ DROP TABLE edges;
|
|
|
57
57
|
ALTER TABLE edges_new RENAME TO edges;
|
|
58
58
|
CREATE INDEX IF NOT EXISTS idx_edges_to ON edges(type, to_id);
|
|
59
59
|
CREATE INDEX IF NOT EXISTS idx_edges_from ON edges(type, from_id);
|
|
60
|
-
`);const E=e.prepare("SELECT COUNT(*) AS n FROM edges").get().n;if(E!==
|
|
60
|
+
`);const E=e.prepare("SELECT COUNT(*) AS n FROM edges").get().n;if(E!==n)throw new Error(`edges FK rebuild lost rows: expected ${n} non-orphan edge(s), got ${E}`);const s=e.prepare("PRAGMA foreign_key_check").all();if(s.length>0)throw new Error(`edges FK rebuild left ${s.length} foreign-key violation(s)`);e.exec("COMMIT")}catch(E){throw e.exec("ROLLBACK"),E}}finally{e.exec("PRAGMA foreign_keys = ON;")}}o(Xe,"edgesForeignKeyCascade");function fe(e){const t=L(e);r(e,t,"pane","ALTER TABLE nodes ADD COLUMN pane TEXT;")}o(fe,"addPaneColumn");function Ce(e){e.exec(`
|
|
61
61
|
CREATE TABLE IF NOT EXISTS focuses (
|
|
62
62
|
focus_id TEXT PRIMARY KEY, -- stable internal id for the viewport
|
|
63
63
|
pane TEXT, -- the durable %pane_id realizing the focus
|
|
64
64
|
session TEXT, -- derived cache of the user session (reconciled from pane)
|
|
65
65
|
node_id TEXT NOT NULL UNIQUE -- the node shown; UNIQUE \u2192 a node occupies <=1 focus
|
|
66
66
|
);
|
|
67
|
-
`)}o(
|
|
67
|
+
`)}o(Ce,"addFocusesTable");function Ue(e){e.exec(`
|
|
68
68
|
CREATE TABLE IF NOT EXISTS wakeups (
|
|
69
69
|
wakeup_id TEXT PRIMARY KEY,
|
|
70
70
|
node_id TEXT, -- TARGET + node-anchored cancel anchor; NULL = canvas-detached
|
|
@@ -80,7 +80,7 @@ CREATE INDEX IF NOT EXISTS idx_wakeups_fire ON wakeups(fire_at);
|
|
|
80
80
|
CREATE INDEX IF NOT EXISTS idx_wakeups_node ON wakeups(node_id); -- by-node cancel / list
|
|
81
81
|
CREATE INDEX IF NOT EXISTS idx_wakeups_owner ON wakeups(owner_id); -- by-owner reap (ruling A)
|
|
82
82
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_wakeups_deadline ON wakeups(node_id) WHERE kind = 'deadline';
|
|
83
|
-
`)}o(
|
|
83
|
+
`)}o(Ue,"appendWakeupsTable");function Se(e){e.exec(`
|
|
84
84
|
CREATE TABLE IF NOT EXISTS triggers (
|
|
85
85
|
trigger_id TEXT PRIMARY KEY,
|
|
86
86
|
owner_id TEXT NOT NULL,
|
|
@@ -131,12 +131,12 @@ SELECT
|
|
|
131
131
|
FROM wakeups;
|
|
132
132
|
|
|
133
133
|
DROP TABLE wakeups;
|
|
134
|
-
`)}o(Se,"migrateWakeupsToTriggers");function De(e){const
|
|
134
|
+
`)}o(Se,"migrateWakeupsToTriggers");function De(e){const t=L(e);r(e,t,"host_kind","ALTER TABLE nodes ADD COLUMN host_kind TEXT;")}o(De,"addHostKindColumn");function ge(e){e.exec(`
|
|
135
135
|
CREATE TABLE IF NOT EXISTS canvas_meta (
|
|
136
136
|
key TEXT PRIMARY KEY,
|
|
137
137
|
value TEXT NOT NULL
|
|
138
138
|
);
|
|
139
|
-
`)}o(ge,"addCanvasMetaTable");function
|
|
139
|
+
`)}o(ge,"addCanvasMetaTable");function we(e){const t=L(e);r(e,t,"profile_id","ALTER TABLE nodes ADD COLUMN profile_id TEXT;")}o(we,"addProfileIdColumn");function ye(e){const t=L(e);r(e,t,"pi_pid_identity","ALTER TABLE nodes ADD COLUMN pi_pid_identity TEXT;")}o(ye,"addPidIdentityColumn");function he(e){const t=L(e);r(e,t,"waiting_for","ALTER TABLE nodes ADD COLUMN waiting_for TEXT;")}o(he,"addMessageWaitColumn");function K(e){const t=L(e);if(t.size===0)return;r(e,t,"final_report","ALTER TABLE nodes ADD COLUMN final_report TEXT;"),r(e,t,"finalized_at","ALTER TABLE nodes ADD COLUMN finalized_at TEXT;");const n=e.prepare("SELECT node_id FROM nodes WHERE status = 'done' AND final_report IS NULL").all(),E=e.prepare("UPDATE nodes SET final_report = ?, finalized_at = ? WHERE node_id = ? AND final_report IS NULL");for(const{node_id:s}of n){const T=y(X(),s,"reports");if(!p(T))continue;let i=null;for(const a of U(T))if(a.endsWith(".md"))try{const d=C(y(T,a),"utf8"),_=/^---\nnode: [^\n]+\nkind: final\nts: ([^\n]+)\n---\n/.exec(d);if(_===null||Number.isNaN(Date.parse(_[1])))continue;const N={name:a,ts:_[1]};(i===null||N.ts>i.ts||N.ts===i.ts&&N.name>i.name)&&(i=N)}catch{}i!==null&&E.run(i.name,i.ts,s)}}o(K,"addCanonicalFinalColumns");function ve(e){const t=X();if(p(t))for(const n of U(t)){const E=f(n);p(E)&&Y(E,s=>{const T=s.launch;if(typeof T!="object"||T===null||Array.isArray(T))return!1;const i=T.extensions;if(!Array.isArray(i)||!i.every(d=>typeof d=="string"))return!1;const a=pe(i);return a.length===i.length?!1:(T.extensions=a,!0)})}}o(ve,"normalizePersistedLaunchExtensions");function xe(e){const t=L(e);r(e,t,"waiting_for_generation","ALTER TABLE nodes ADD COLUMN waiting_for_generation INTEGER NOT NULL DEFAULT 0;")}o(xe,"addMessageWaitGenerationColumn");function Fe(e){e.exec(`
|
|
140
140
|
CREATE TABLE IF NOT EXISTS consult_outbox (
|
|
141
141
|
node_id TEXT PRIMARY KEY, -- legacy work node id
|
|
142
142
|
dir TEXT NOT NULL, -- legacy ticket directory
|
|
@@ -150,7 +150,7 @@ CREATE INDEX IF NOT EXISTS idx_consult_outbox_status ON consult_outbox(status);
|
|
|
150
150
|
CREATE INDEX IF NOT EXISTS idx_consult_outbox_dir ON consult_outbox(dir);
|
|
151
151
|
CREATE INDEX IF NOT EXISTS idx_consult_outbox_dir_request_status ON consult_outbox(dir, request_id, status);
|
|
152
152
|
CREATE INDEX IF NOT EXISTS idx_consult_outbox_dir_status ON consult_outbox(dir, status);
|
|
153
|
-
`)}o(Fe,"addHumanWorkOutboxTable");function ke(e){const
|
|
153
|
+
`)}o(Fe,"addHumanWorkOutboxTable");function ke(e){const t=h(e,"consult_outbox"),n=o((E,s)=>W(e,t,E,s),"add");n("work_kind","ALTER TABLE consult_outbox ADD COLUMN work_kind TEXT NOT NULL DEFAULT 'follow_up';"),n("interaction_id","ALTER TABLE consult_outbox ADD COLUMN interaction_id TEXT;"),n("generation_id","ALTER TABLE consult_outbox ADD COLUMN generation_id TEXT;"),n("interaction_snapshot","ALTER TABLE consult_outbox ADD COLUMN interaction_snapshot TEXT;"),n("handler_command","ALTER TABLE consult_outbox ADD COLUMN handler_command TEXT;"),n("handler_args_json","ALTER TABLE consult_outbox ADD COLUMN handler_args_json TEXT;"),n("claim_token","ALTER TABLE consult_outbox ADD COLUMN claim_token TEXT;"),e.exec(`
|
|
154
154
|
CREATE INDEX IF NOT EXISTS idx_consult_outbox_human_work_status ON consult_outbox(work_kind, status);
|
|
155
155
|
CREATE INDEX IF NOT EXISTS idx_consult_outbox_human_work_dir_status ON consult_outbox(dir, work_kind, status);
|
|
156
156
|
CREATE INDEX IF NOT EXISTS idx_consult_outbox_human_work_request_status ON consult_outbox(dir, request_id, work_kind, status);
|
|
@@ -158,7 +158,7 @@ CREATE UNIQUE INDEX IF NOT EXISTS idx_consult_outbox_visual_request ON consult_o
|
|
|
158
158
|
`)}o(ke,"addHumanWorkColumns");function Me(e){e.exec(`
|
|
159
159
|
CREATE INDEX IF NOT EXISTS idx_nodes_parent ON nodes(parent);
|
|
160
160
|
CREATE INDEX IF NOT EXISTS idx_nodes_created ON nodes(created);
|
|
161
|
-
`)}o(Me,"addNodeParentCreatedIndexes");function
|
|
161
|
+
`)}o(Me,"addNodeParentCreatedIndexes");function je(e){e.exec(`
|
|
162
162
|
CREATE TABLE IF NOT EXISTS crons (
|
|
163
163
|
cron_id TEXT PRIMARY KEY,
|
|
164
164
|
name TEXT NOT NULL, -- agent-legible label; how it shows in list
|
|
@@ -213,38 +213,38 @@ CREATE TABLE IF NOT EXISTS cron_runs ( -- bounded ring, last 20 p
|
|
|
213
213
|
FOREIGN KEY (cron_id) REFERENCES crons(cron_id) ON DELETE CASCADE
|
|
214
214
|
);
|
|
215
215
|
CREATE INDEX IF NOT EXISTS idx_cron_runs_cron ON cron_runs(cron_id, started);
|
|
216
|
-
`)}o(
|
|
217
|
-
`).includes(E))return E;
|
|
218
|
-
${
|
|
219
|
-
${E}`}o($,"heredocCommand");function be(e){if(typeof e!="string")return{};try{const
|
|
216
|
+
`)}o(je,"addCronsTables");function R(e){return`'${e.replace(/'/g,`'"'"'`)}'`}o(R,"shellSingleQuote");function Be(e,t){let n=0;for(;;){const E=`${t}_${n}`;if(!e.split(`
|
|
217
|
+
`).includes(E))return E;n++}}o(Be,"uniqueHeredocDelimiter");function $(e,t,n){const E=Be(t,n);return`${e} <<'${E}'
|
|
218
|
+
${t}
|
|
219
|
+
${E}`}o($,"heredocCommand");function be(e){if(typeof e!="string")return{};try{const t=JSON.parse(e);return typeof t!="object"||t===null||Array.isArray(t)?{}:t}catch{return{}}}o(be,"migrationPayload");function l(e,t,n){const E=e[t];if(typeof E!="string"||E.trim()==="")throw new Error(`trigger ${n} payload requires non-empty ${t}`);return E}o(l,"requiredString");function S(e,t){const n=e[t];return typeof n=="string"&&n.trim()!==""?n:void 0}o(S,"optionalString");function I(e,t){const n=e[t];return typeof n=="string"&&n.trim()!==""?n:void 0}o(I,"optionalColumn");function q(e,t,n,E){return $(`crtr node message send --to ${R(e)} --tier ${R(t)}`,n,`CRTR_MIGRATED_${E.replace(/[^A-Za-z0-9]/g,"_")}`)}o(q,"migratedMessageCommand");function Ge(e,t){return`printf '%s\\n' "$CRTR_GATE_STDOUT" | crtr node message send --to ${R(e)} --tier ${R(t)}`}o(Ge,"migratedGateStdoutMessageCommand");function He(e,t){const n=[`crtr node new --kind ${R(l(e,"kind",t))}`],E=[["mode","mode"],["cwd","cwd"],["name","name"],["parent","parent"],["worktreeBase","worktree"],["forkFrom","fork-from"],["model","model"],["profile","profile"],["situationalContext","situational-context"]];for(const[T,i]of E){const a=S(e,T);a!==void 0&&n.push(`--${i} ${R(a)}`)}e.root===!0&&n.push("--root");const s=l(e,"prompt",t);return $(n.join(" "),s,`CRTR_MIGRATED_${t.replace(/[^A-Za-z0-9]/g,"_")}`)}o(He,"migratedSpawnCommand");const J="migration.v22.skipped";function Pe(e){const t=e.prepare("SELECT cwd FROM nodes WHERE parent IS NULL ORDER BY created LIMIT 1").get();return(t!==void 0?I(t,"cwd"):void 0)??process.cwd()}o(Pe,"ambientMigrationCwd");function Ye(e){let t;try{t=e.prepare("SELECT eval_pid FROM triggers WHERE eval_state = 'running' AND eval_pid IS NOT NULL").all()}catch{return}for(const n of t){const E=n.eval_pid;if(!(typeof E!="number"||!Number.isInteger(E)||E<=1))try{process.kill(-E,"SIGTERM")}catch{}}}o(Ye,"reapRunningPredicateEvaluations");function We(e){const t=[],n=e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'triggers'").get()!==void 0;n&&Ye(e);let E=[];if(n)try{E=e.prepare("SELECT * FROM triggers ORDER BY created, trigger_id").all()}catch(i){t.push({trigger_id:"<unreadable table>",reason:`triggers table could not be read: ${i instanceof Error?i.message:String(i)}`})}const s=Pe(e),T=e.prepare(`
|
|
220
220
|
INSERT OR REPLACE INTO crons (
|
|
221
221
|
cron_id, name, created_by, command, fire_at, recur, tz, expires_at,
|
|
222
222
|
anchor_node, cancel_on_wake, cwd, env_json, profile, scope,
|
|
223
223
|
run_timeout_s, overlap, on_output, sink, tier, created, updated
|
|
224
|
-
) VALUES (?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, NULL, ?, 'profile', ?, 'skip', 'on-failure', '{}', ?, ?, ?)`);for(const i of E){const a=I(i,"trigger_id");if(a===void 0){
|
|
224
|
+
) VALUES (?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, NULL, ?, 'profile', ?, 'skip', 'on-failure', '{}', ?, ?, ?)`);for(const i of E){const a=I(i,"trigger_id");if(a===void 0){t.push({trigger_id:"<unidentified row>",reason:"row carries no trigger_id"});continue}try{Ke(e,T,i,a,s)}catch(d){t.push({trigger_id:a,reason:d instanceof Error?d.message:String(d)})}}t.length>0&&(e.prepare("INSERT INTO canvas_meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(J,JSON.stringify(t)),console.warn(`[canvas migration v22] ${t.length} retired schedule(s) could not be converted to crons and were dropped; see canvas_meta['${J}']: `+t.map(i=>`${i.trigger_id} (${i.reason})`).join("; "))),e.exec(`
|
|
225
225
|
DROP INDEX IF EXISTS idx_triggers_fire;
|
|
226
226
|
DROP INDEX IF EXISTS idx_triggers_node;
|
|
227
227
|
DROP INDEX IF EXISTS idx_triggers_owner;
|
|
228
228
|
DROP INDEX IF EXISTS idx_triggers_eval;
|
|
229
229
|
DROP INDEX IF EXISTS idx_triggers_deadline;
|
|
230
230
|
DROP TABLE IF EXISTS triggers;
|
|
231
|
-
`)}o(We,"migrateTriggersToCrons");function Ke(e,n,
|
|
232
|
-
${
|
|
231
|
+
`)}o(We,"migrateTriggersToCrons");function Ke(e,t,n,E,s){const T=l(n,"owner_id",E),i=e.prepare("SELECT cwd, profile_id FROM nodes WHERE node_id = ?").get(T),a=(i===void 0?void 0:I(i,"cwd"))??s,d=i===void 0?null:I(i,"profile_id")??null,_=I(n,"node_id")??null,N=l(n,"action",E),c=l(n,"action_mode",E),u=l(n,"trigger_type",E),m=be(n.payload),B=I(n,"created")??new Date().toISOString(),g=c==="deadline_message"?"urgent":S(m,"tier")??"normal",x=S(m,"label");let A,w,b=!1;if(N==="msg"&&(c==="inbox_message"||c==="deadline_message")){if(_===null)throw new Error("has no message target");const O=S(m,"body");O!==void 0?A=q(_,g,O,E):u==="when"?(b=!0,A=Ge(_,g)):A=q(_,g,x??"Scheduled message (no body was recorded when this schedule was armed).",E),w=x??(c==="deadline_message"?"deadline":"scheduled message")}else if(N==="msg"&&c==="fresh_revive"){if(_===null)throw new Error("has no revive target");A=`crtr node lifecycle revive ${R(_)} --fresh`,w=x??"scheduled fresh revive"}else if(N==="new"&&c==="node_birth")A=He(m,E),w=S(m,"name")??`scheduled ${l(m,"kind",E)} node`;else throw new Error(`has unsupported action ${N}/${c}`);let F,k,G=null;if(u==="when"){F=l(n,"next_eval_at",E),k=l(n,"eval_every",E),G=I(n,"timeout_at")??null;const O=l(n,"when_script",E);A=`${b?`if ! CRTR_GATE_STDOUT="$(
|
|
232
|
+
${O}
|
|
233
233
|
)"; then`:`if ! (
|
|
234
|
-
${
|
|
234
|
+
${O}
|
|
235
235
|
); then`}
|
|
236
236
|
exit 0
|
|
237
237
|
fi
|
|
238
238
|
{
|
|
239
|
-
${
|
|
240
|
-
} && crtr cron cancel "$CRTR_CRON_ID"`}else if(u==="at"||u==="every"||u==="until")
|
|
239
|
+
${A}
|
|
240
|
+
} && crtr cron cancel "$CRTR_CRON_ID"`}else if(u==="at"||u==="every"||u==="until")F=l(n,"fire_at",E),k=u==="every"?l(n,"recur",E):null;else throw new Error(`has unknown timing type ${u}`);if(c==="deadline_message"&&_!==null){const O=e.prepare("SELECT cron_id FROM crons WHERE anchor_node = ? AND cancel_on_wake = 1 AND cron_id <> ?").get(_,E);if(O!==void 0)throw new Error(`node ${_} already has a migrated deadline (${String(O.cron_id)}); only one is allowed`)}t.run(E,w,T,A,F,k,G,_,c==="deadline_message"?1:0,a,d,300,g,B,B)}o(Ke,"convertTriggerRow");function $e(e){const t=h(e,"crons");t.size===0||t.has("run_pid_identity")||e.exec("ALTER TABLE crons ADD COLUMN run_pid_identity TEXT;")}o($e,"addCronRunPidIdentityColumn");function qe(e){const t=h(e,"crons");t.size!==0&&(t.has("run_out_of_band")||e.exec("ALTER TABLE crons ADD COLUMN run_out_of_band INTEGER NOT NULL DEFAULT 0;"),t.has("queued")&&e.exec("ALTER TABLE crons DROP COLUMN queued;"))}o(qe,"addCronOutOfBandColumn");function Je(e){e.exec(`
|
|
241
241
|
CREATE TABLE IF NOT EXISTS warm_pool (
|
|
242
242
|
node_id TEXT PRIMARY KEY REFERENCES nodes(node_id) ON DELETE CASCADE,
|
|
243
243
|
recipe_key TEXT NOT NULL, -- frozen launch tuple this spare was minted for
|
|
244
244
|
created TEXT NOT NULL -- ISO 8601, mint time (oldest spare claimed first)
|
|
245
245
|
);
|
|
246
246
|
CREATE INDEX IF NOT EXISTS idx_warm_pool_recipe ON warm_pool(recipe_key, created);
|
|
247
|
-
`)}o(
|
|
247
|
+
`)}o(Je,"addWarmPoolTable");function Qe(e){const t=e.prepare("SELECT node_id, dir, root, request_id, work_kind, status, final_report, updated_at FROM consult_outbox").all();e.exec(`
|
|
248
248
|
CREATE TABLE consult_outbox_new (
|
|
249
249
|
node_id TEXT PRIMARY KEY,
|
|
250
250
|
ticket_node_id TEXT NOT NULL,
|
|
@@ -254,9 +254,9 @@ CREATE TABLE consult_outbox_new (
|
|
|
254
254
|
final_report TEXT,
|
|
255
255
|
updated_at TEXT NOT NULL
|
|
256
256
|
);
|
|
257
|
-
`);const
|
|
257
|
+
`);const n=e.prepare(`
|
|
258
258
|
INSERT INTO consult_outbox_new (node_id, ticket_node_id, request_id, work_kind, status, final_report, updated_at)
|
|
259
|
-
VALUES (?, ?, ?, ?, ?, ?, ?)`);let E=0;for(const s of
|
|
259
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`);let E=0;for(const s of t){const T=Le(s.dir);if(!(s.root===H(s.root)&&s.dir===y(s.root,T))||!ue(T)){E+=1;continue}n.run(s.node_id,T,s.request_id,s.work_kind,s.status,s.final_report,s.updated_at)}E>0&&console.warn(`[canvas migration v26] dropped ${E} consult_outbox row(s) whose legacy ticket path cannot safely map to a ticket node id`),e.exec(`
|
|
260
260
|
DROP TABLE consult_outbox;
|
|
261
261
|
ALTER TABLE consult_outbox_new RENAME TO consult_outbox;
|
|
262
262
|
|
|
@@ -265,7 +265,7 @@ CREATE INDEX IF NOT EXISTS idx_consult_outbox_human_work_status ON consult_outbo
|
|
|
265
265
|
CREATE INDEX IF NOT EXISTS idx_consult_outbox_ticket_status ON consult_outbox(ticket_node_id, work_kind, status);
|
|
266
266
|
CREATE INDEX IF NOT EXISTS idx_consult_outbox_ticket_request_status ON consult_outbox(ticket_node_id, request_id, work_kind, status);
|
|
267
267
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_consult_outbox_visual_request ON consult_outbox(ticket_node_id, request_id, work_kind) WHERE work_kind = 'visual';
|
|
268
|
-
`)}o(
|
|
268
|
+
`)}o(Qe,"narrowHumanWorkOutbox");function ze(e){e.exec(`
|
|
269
269
|
CREATE TABLE IF NOT EXISTS reviews (
|
|
270
270
|
review_id TEXT PRIMARY KEY,
|
|
271
271
|
idempotency_key TEXT NOT NULL UNIQUE,
|
|
@@ -309,7 +309,7 @@ CREATE INDEX IF NOT EXISTS idx_reviews_state ON reviews(state);
|
|
|
309
309
|
CREATE INDEX IF NOT EXISTS idx_reviews_origin ON reviews(origin_node_id);
|
|
310
310
|
CREATE INDEX IF NOT EXISTS idx_reviews_file ON reviews(file);
|
|
311
311
|
CREATE INDEX IF NOT EXISTS idx_reviews_bridge ON reviews(bridge_node_id);
|
|
312
|
-
`)}o(
|
|
312
|
+
`)}o(ze,"addReviewsTable");function Ve(e){e.exec(`
|
|
313
313
|
CREATE TABLE IF NOT EXISTS review_comments (
|
|
314
314
|
comment_id TEXT PRIMARY KEY,
|
|
315
315
|
review_id TEXT NOT NULL,
|
|
@@ -357,10 +357,10 @@ CREATE INDEX IF NOT EXISTS idx_review_comment_events_comment_seq
|
|
|
357
357
|
`)}o(Ve,"addReviewCommentTables");function Ze(e){e.exec(`
|
|
358
358
|
ALTER TABLE review_comments
|
|
359
359
|
ADD COLUMN anchor_state TEXT NOT NULL DEFAULT 'live' CHECK (anchor_state IN ('live', 'detached'));
|
|
360
|
-
`)}o(Ze,"addReviewCommentAnchorState");function
|
|
360
|
+
`)}o(Ze,"addReviewCommentAnchorState");function et(e){e.exec("DROP TABLE IF EXISTS consult_outbox")}o(et,"dropConsultOutbox");function tt(e){e.exec("ALTER TABLE reviews ADD COLUMN submit_requested_at TEXT")}o(tt,"addReviewSubmitRequested");function nt(e){e.exec(`
|
|
361
361
|
ALTER TABLE crons ADD COLUMN held INTEGER NOT NULL DEFAULT 0;
|
|
362
362
|
ALTER TABLE crons ADD COLUMN last_poke_at TEXT;
|
|
363
|
-
`)}o(
|
|
363
|
+
`)}o(nt,"addCronHeldColumns");function ot(e){e.exec(`
|
|
364
364
|
CREATE TABLE human_action_deliveries (
|
|
365
365
|
request_id TEXT PRIMARY KEY,
|
|
366
366
|
state TEXT NOT NULL,
|
|
@@ -378,18 +378,18 @@ CREATE TABLE human_action_deliveries (
|
|
|
378
378
|
updated_at INTEGER NOT NULL
|
|
379
379
|
);
|
|
380
380
|
CREATE INDEX idx_human_action_deliveries_due ON human_action_deliveries(state, next_attempt_at);
|
|
381
|
-
`)}o(
|
|
381
|
+
`)}o(ot,"addHumanActionDeliveries");function Et(e){const t=L(e);r(e,t,"pi_session_file","ALTER TABLE nodes ADD COLUMN pi_session_file TEXT;");for(const n of U(X(),{withFileTypes:!0}))if(n.isDirectory())try{const E=JSON.parse(C(f(n.name),"utf8"));typeof E.pi_session_file=="string"&&e.prepare("UPDATE nodes SET pi_session_file = ? WHERE node_id = ?").run(E.pi_session_file,n.name)}catch{}e.exec("CREATE INDEX IF NOT EXISTS idx_nodes_pi_session_file ON nodes(pi_session_file);")}o(Et,"addNodeSessionFileIndex");function Q(e,t){const n=o(a=>{const d=H(a);return p(d)?Ne(d):d},"canonical"),E=e.prepare("UPDATE nodes SET pi_session_file = ? WHERE node_id = ?");e.exec("DROP INDEX IF EXISTS idx_nodes_pi_session_file;");const s=e.prepare("SELECT node_id FROM nodes ORDER BY created ASC, node_id ASC").all();for(const{node_id:a}of s){const d=f(a);if(P(d)===null){E.run(null,a);continue}const _=Ae(d,()=>{const N=P(d);if(N===null)throw new Error(`node ${a} session metadata changed during ownership migration`);if(typeof N.pi_session_file!="string")return null;const c=N.pi_session_file,u=n(c);return u!==c&&(N.pi_session_file=u,Oe(d,N)),u});E.run(_,a)}const T=e.prepare(`
|
|
382
382
|
SELECT pi_session_file
|
|
383
383
|
FROM nodes
|
|
384
384
|
WHERE pi_session_file IS NOT NULL
|
|
385
385
|
GROUP BY pi_session_file
|
|
386
386
|
HAVING COUNT(*) > 1
|
|
387
|
-
`).all();if(!
|
|
387
|
+
`).all();if(!t&&T.length>0){const a=T.map(({pi_session_file:d})=>d).join(", ");throw new Error(`cannot restore unique Pi session ownership: authoritative metadata has concurrent claimants for ${a}`)}const i=e.prepare("UPDATE nodes SET pi_session_file = NULL WHERE node_id = ?");for(const{pi_session_file:a}of T){const d=e.prepare(`
|
|
388
388
|
SELECT node_id
|
|
389
389
|
FROM nodes
|
|
390
390
|
WHERE pi_session_file = ?
|
|
391
391
|
ORDER BY created ASC, node_id ASC
|
|
392
|
-
`).all(a);for(const{node_id:
|
|
392
|
+
`).all(a);for(const{node_id:_}of d.slice(1)){if(!Y(f(_),c=>{const u=c.pi_session_file;if(typeof u!="string"||n(u)!==a)throw new Error(`node ${_} session metadata changed during ownership migration`);return c.pi_session_id=null,c.pi_session_file=null,!0}))throw new Error(`node ${_} session metadata changed during ownership migration`);i.run(_)}}e.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_nodes_pi_session_file ON nodes(pi_session_file);")}o(Q,"reconcileNodeSessionFileOwners");function Tt(e){Q(e,!0)}o(Tt,"makeNodeSessionFileUnique");function it(e){Q(e,!1)}o(it,"repairNodeSessionFileUniqueIndex");function st(e){const t=L(e);r(e,t,"frozen_at","ALTER TABLE nodes ADD COLUMN frozen_at TEXT;"),r(e,t,"respawn_failures","ALTER TABLE nodes ADD COLUMN respawn_failures INTEGER NOT NULL DEFAULT 0;"),r(e,t,"respawn_not_before","ALTER TABLE nodes ADD COLUMN respawn_not_before TEXT;"),r(e,t,"launched_at","ALTER TABLE nodes ADD COLUMN launched_at TEXT;"),r(e,t,"last_settled_at","ALTER TABLE nodes ADD COLUMN last_settled_at TEXT;"),r(e,t,"terminal_reason","ALTER TABLE nodes ADD COLUMN terminal_reason TEXT;"),e.exec(`
|
|
393
393
|
UPDATE nodes SET terminal_reason = CASE
|
|
394
394
|
WHEN status = 'done' AND final_report IS NOT NULL THEN 'finalized'
|
|
395
395
|
WHEN status = 'done' AND intent = 'parked' THEN 'parked'
|
|
@@ -398,7 +398,7 @@ UPDATE nodes SET terminal_reason = CASE
|
|
|
398
398
|
WHEN status = 'dead' THEN 'crashed'
|
|
399
399
|
END
|
|
400
400
|
WHERE status IN ('done','canceled','dead') AND terminal_reason IS NULL;
|
|
401
|
-
`)}o(
|
|
401
|
+
`)}o(st,"addNodeLifecycleColumns");function rt(e){const t=L(e);r(e,t,"description","ALTER TABLE nodes ADD COLUMN description TEXT;"),r(e,t,"cycles","ALTER TABLE nodes ADD COLUMN cycles INTEGER;");const n=X();if(!p(n))return;const E=e.prepare("UPDATE nodes SET description = ?, cycles = ? WHERE node_id = ?");for(const s of U(n)){const T=f(s);if(!p(T))continue;let i;try{i=JSON.parse(C(T,"utf8"))}catch{continue}const a=typeof i.description=="string"?i.description:null,d=typeof i.cycles=="number"?i.cycles:null;E.run(a,d,s)}}o(rt,"addNodeLabelColumns");function at(e){const t=L(e);r(e,t,"outcome_kind","ALTER TABLE nodes ADD COLUMN outcome_kind TEXT;"),r(e,t,"outcome_reason","ALTER TABLE nodes ADD COLUMN outcome_reason TEXT;"),r(e,t,"outcome_at","ALTER TABLE nodes ADD COLUMN outcome_at TEXT;"),r(e,t,"outcome_revision","ALTER TABLE nodes ADD COLUMN outcome_revision INTEGER NOT NULL DEFAULT 0;"),r(e,t,"outcome_detail_json","ALTER TABLE nodes ADD COLUMN outcome_detail_json TEXT;"),r(e,t,"deadline_at","ALTER TABLE nodes ADD COLUMN deadline_at TEXT;"),e.exec(`
|
|
402
402
|
CREATE TABLE IF NOT EXISTS node_outcome_deliveries (
|
|
403
403
|
node_id TEXT PRIMARY KEY,
|
|
404
404
|
state TEXT NOT NULL,
|
|
@@ -431,17 +431,17 @@ UPDATE nodes SET outcome_kind='failure',
|
|
|
431
431
|
outcome_reason=COALESCE(terminal_reason,'crashed'),
|
|
432
432
|
outcome_at=COALESCE(finalized_at, created), outcome_revision=1
|
|
433
433
|
WHERE final_report IS NULL AND status IN ('done','dead','canceled') AND outcome_at IS NULL;
|
|
434
|
-
`)}o(
|
|
434
|
+
`)}o(at,"addNodeOutcomeAndDeadline");function dt(e){const t=L(e);r(e,t,"telemetry_tokens_in","ALTER TABLE nodes ADD COLUMN telemetry_tokens_in INTEGER;"),r(e,t,"telemetry_context_tokens","ALTER TABLE nodes ADD COLUMN telemetry_context_tokens INTEGER;"),r(e,t,"telemetry_last_activity","ALTER TABLE nodes ADD COLUMN telemetry_last_activity TEXT;"),r(e,t,"telemetry_updated_at","ALTER TABLE nodes ADD COLUMN telemetry_updated_at TEXT;");const n=e.prepare(`UPDATE nodes
|
|
435
435
|
SET telemetry_tokens_in = ?, telemetry_context_tokens = ?,
|
|
436
436
|
telemetry_last_activity = ?, telemetry_updated_at = ?
|
|
437
|
-
WHERE node_id = ?`);for(const{node_id:E}of e.prepare("SELECT node_id FROM nodes").all()){const s=
|
|
437
|
+
WHERE node_id = ?`);for(const{node_id:E}of e.prepare("SELECT node_id FROM nodes").all()){const s=y(X(),E,"job","telemetry.json");if(p(s))try{const T=JSON.parse(C(s,"utf8")),i=typeof T.tokens_in=="number"&&Number.isFinite(T.tokens_in)?T.tokens_in:null,a=typeof T.context_tokens=="number"&&Number.isFinite(T.context_tokens)?T.context_tokens:null,d=typeof T.last_activity=="string"?T.last_activity:null,_=ce(s).mtime.toISOString();n.run(i,a,d,_,E)}catch{}}}o(dt,"addNodeTelemetryColumns");function _t(e){e.exec(`
|
|
438
438
|
CREATE INDEX IF NOT EXISTS deliveries_external_due_order
|
|
439
439
|
ON deliveries(state, next_attempt_at, created_at, delivery_id)
|
|
440
440
|
WHERE destination_kind = 'external_action' AND canceled_at IS NULL;
|
|
441
441
|
DROP INDEX IF EXISTS deliveries_external_due;
|
|
442
442
|
CREATE INDEX IF NOT EXISTS idx_nodes_parent_created ON nodes(parent, created);
|
|
443
443
|
CREATE INDEX IF NOT EXISTS idx_edges_type_created ON edges(type, created);
|
|
444
|
-
`)}o(
|
|
444
|
+
`)}o(_t,"addRecurringLaneIndexes");function Nt(e){re(e)}o(Nt,"projectLiveNodeState");function ct(e){r(e,L(e),"scopes_json","ALTER TABLE nodes ADD COLUMN scopes_json TEXT;")}o(ct,"addNodeScopes");function Lt(e){const t=L(e);r(e,t,"grantee","ALTER TABLE nodes ADD COLUMN grantee TEXT NOT NULL DEFAULT 'user:local';"),r(e,t,"sub","ALTER TABLE nodes ADD COLUMN sub TEXT;"),r(e,t,"grant_id","ALTER TABLE nodes ADD COLUMN grant_id TEXT;"),r(e,t,"client_id","ALTER TABLE nodes ADD COLUMN client_id TEXT;"),r(e,t,"metadata_json","ALTER TABLE nodes ADD COLUMN metadata_json TEXT;"),r(e,t,"run_id","ALTER TABLE nodes ADD COLUMN run_id TEXT;"),r(e,t,"event_cursor","ALTER TABLE nodes ADD COLUMN event_cursor INTEGER;"),r(e,t,"usage_json","ALTER TABLE nodes ADD COLUMN usage_json TEXT;"),r(e,t,"deleting_at","ALTER TABLE nodes ADD COLUMN deleting_at TEXT;"),e.exec(`
|
|
445
445
|
ALTER TABLE sessions ADD COLUMN event_offset INTEGER;
|
|
446
446
|
CREATE INDEX idx_nodes_run_id ON nodes(run_id);
|
|
447
447
|
-- Child nodes may be pruned while their root run and event history remain.
|
|
@@ -466,10 +466,10 @@ CREATE INDEX IF NOT EXISTS idx_edges_type_created ON edges(type, created);
|
|
|
466
466
|
PRIMARY KEY (grantee, key)
|
|
467
467
|
);
|
|
468
468
|
CREATE INDEX idx_idempotency_keys_created_at ON idempotency_keys(created_at);
|
|
469
|
-
`)}o(
|
|
469
|
+
`)}o(Lt,"addRunFoundation");function ut(e){e.exec("ALTER TABLE nodes ADD COLUMN last_activity_at TEXT;"),e.exec(`UPDATE nodes SET last_activity_at = (
|
|
470
470
|
SELECT e.ts FROM run_events e WHERE e.run_id = nodes.node_id
|
|
471
471
|
ORDER BY e.sequence_number DESC LIMIT 1
|
|
472
|
-
) WHERE run_id = node_id`)}o(
|
|
472
|
+
) WHERE run_id = node_id`)}o(ut,"addRunLastActivity");function lt(e){e.exec(`
|
|
473
473
|
CREATE TABLE grants (
|
|
474
474
|
id TEXT PRIMARY KEY, runtime TEXT NOT NULL, sub TEXT NOT NULL, grantee TEXT NOT NULL,
|
|
475
475
|
rev INTEGER NOT NULL, scopes_json TEXT NOT NULL, resolved_scopes_json TEXT NOT NULL,
|
|
@@ -478,13 +478,13 @@ CREATE INDEX IF NOT EXISTS idx_edges_type_created ON edges(type, created);
|
|
|
478
478
|
);
|
|
479
479
|
CREATE UNIQUE INDEX idx_grants_grantee_sub ON grants(grantee, sub);
|
|
480
480
|
CREATE TABLE runtime_state (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
|
481
|
-
`)}o(
|
|
481
|
+
`)}o(lt,"addGrantMirror");function pt(e){e.exec("UPDATE nodes SET grantee = 'app:terminal' WHERE grantee = 'user:local';")}o(pt,"migrateTerminalGrantees");function At(e){const t={llm:"crtr:llm",act:"crtr:act",schedule:"crtr:schedule","memory:read":"crtr:memory:read:user","memory:write":"crtr:memory:rw:user"},n=e.prepare("SELECT node_id, scopes_json FROM nodes WHERE scopes_json IS NOT NULL").all(),E=e.prepare("UPDATE nodes SET scopes_json = ? WHERE node_id = ?");for(const s of n){const T=JSON.parse(s.scopes_json);if(!Array.isArray(T))throw new Error(`invalid launched scopes for node ${s.node_id}`);const i=[];for(const a of T){if(typeof a!="string")continue;const d=t[a]??a;try{ie(d),i.push(d)}catch(_){if(!(_ instanceof TypeError))throw _}}E.run(JSON.stringify([...new Set(i)]),s.node_id)}}o(At,"migrateLaunchedScopes");function Ot(e){e.exec(`CREATE TABLE node_tokens (
|
|
482
482
|
broker_process_id TEXT PRIMARY KEY REFERENCES executions(execution_id) ON DELETE CASCADE,
|
|
483
483
|
node_id TEXT NOT NULL REFERENCES nodes(node_id) ON DELETE CASCADE,
|
|
484
484
|
token_hash TEXT NOT NULL UNIQUE, grantee TEXT NOT NULL, uid INTEGER NOT NULL,
|
|
485
485
|
sub TEXT NOT NULL, grant TEXT, client_id TEXT, scopes_json TEXT,
|
|
486
486
|
issued_at TEXT NOT NULL, revoked_at TEXT
|
|
487
|
-
);`)}o(
|
|
487
|
+
);`)}o(Ot,"addNodeTokens");function v(e,t){return e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(t)!==void 0}o(v,"hasTable");function M(e,t,n){return e.prepare(`PRAGMA table_info(${t})`).all().some(E=>E.name===n)}o(M,"hasColumn");function z(e){v(e,"memory_reads")||e.exec(`CREATE TABLE memory_reads (
|
|
488
488
|
node_id TEXT NOT NULL REFERENCES nodes(node_id) ON DELETE CASCADE,
|
|
489
489
|
name TEXT NOT NULL,
|
|
490
490
|
scope TEXT NOT NULL,
|
|
@@ -493,12 +493,12 @@ CREATE INDEX IF NOT EXISTS idx_edges_type_created ON edges(type, created);
|
|
|
493
493
|
);
|
|
494
494
|
CREATE INDEX idx_memory_reads_at ON memory_reads(at);
|
|
495
495
|
CREATE INDEX idx_memory_reads_node ON memory_reads(node_id);
|
|
496
|
-
INSERT OR IGNORE INTO canvas_meta(key, value) VALUES ('memory_reads.started_at', strftime('%Y-%m-%dT%H:%M:%fZ','now'));`)}o(
|
|
496
|
+
INSERT OR IGNORE INTO canvas_meta(key, value) VALUES ('memory_reads.started_at', strftime('%Y-%m-%dT%H:%M:%fZ','now'));`)}o(z,"addMemoryReads");function V(e){M(e,"sessions","indexed_entry_id")||e.exec("ALTER TABLE sessions ADD COLUMN indexed_entry_id TEXT; ALTER TABLE sessions ADD COLUMN input_ids_json TEXT NOT NULL DEFAULT '[]';")}o(V,"addConversationIndex");function Z(e){v(e,"app_users")||e.exec(`CREATE TABLE app_users (
|
|
497
497
|
app TEXT PRIMARY KEY, uid INTEGER NOT NULL UNIQUE,
|
|
498
498
|
created TEXT NOT NULL, status TEXT NOT NULL CHECK (status IN ('active', 'retired'))
|
|
499
499
|
);`)}o(Z,"addAppUsers");function ee(e){M(e,"crons","grantee")||(e.exec("ALTER TABLE crons ADD COLUMN grantee TEXT NOT NULL DEFAULT 'app:terminal'"),e.exec(`UPDATE crons SET grantee = COALESCE(
|
|
500
500
|
(SELECT COALESCE(nodes.grantee, 'app:terminal') FROM nodes WHERE nodes.node_id = crons.anchor_node),
|
|
501
|
-
'app:terminal') WHERE anchor_node IS NOT NULL`))}o(ee,"addCronGrantee");function
|
|
501
|
+
'app:terminal') WHERE anchor_node IS NOT NULL`))}o(ee,"addCronGrantee");function Rt(e){z(e),V(e),Z(e),ee(e)}o(Rt,"convergeSharedVersions");function It(e){(e.prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'app_users'").get()?.sql??"").includes("'removed'")||e.exec(`CREATE TABLE app_users_new (
|
|
502
502
|
uid INTEGER PRIMARY KEY, app TEXT NOT NULL,
|
|
503
503
|
created TEXT NOT NULL, status TEXT NOT NULL CHECK (status IN ('active', 'removed')),
|
|
504
504
|
removed_at TEXT
|
|
@@ -508,7 +508,7 @@ CREATE INDEX IF NOT EXISTS idx_edges_type_created ON edges(type, created);
|
|
|
508
508
|
CASE status WHEN 'active' THEN NULL ELSE created END FROM app_users;
|
|
509
509
|
DROP TABLE app_users;
|
|
510
510
|
ALTER TABLE app_users_new RENAME TO app_users;
|
|
511
|
-
CREATE UNIQUE INDEX idx_app_users_active_app ON app_users(app) WHERE status = 'active';`)}o(
|
|
511
|
+
CREATE UNIQUE INDEX idx_app_users_active_app ON app_users(app) WHERE status = 'active';`)}o(It,"appUsersRemoved");function te(e){v(e,"objects")||(e.exec(`
|
|
512
512
|
CREATE TABLE objects (
|
|
513
513
|
rowid INTEGER PRIMARY KEY,
|
|
514
514
|
id TEXT NOT NULL UNIQUE,
|
|
@@ -630,11 +630,11 @@ CREATE INDEX IF NOT EXISTS idx_edges_type_created ON edges(type, created);
|
|
|
630
630
|
ALTER TABLE messages ADD COLUMN object_id TEXT;
|
|
631
631
|
ALTER TABLE messages ADD COLUMN level INTEGER;
|
|
632
632
|
ALTER TABLE messages ADD COLUMN actor_id TEXT;
|
|
633
|
-
`),
|
|
634
|
-
WHERE NOT EXISTS (SELECT 1 FROM identities i WHERE i.external_id = n.grantee AND i.scheme IN ('app', 'local-user'))`).all();for(const{grantee:T}of s){let i;if(T==="user:local")i={type:"person",scheme:"local-user",handle:"user"};else if(/^app:[a-z0-9][a-z0-9._-]*$/.test(T))i={type:"app",scheme:"app",handle:T.slice(4)};else throw new Error(`canvas objects migration: node grantee ${JSON.stringify(T)} is neither app:<name> nor user:local`);const{rowid:a}=
|
|
633
|
+
`),ne(e),e.exec("ANALYZE"))}o(te,"canvasObjectsSchema");function ne(e){const t=new Date().toISOString(),n=e.prepare("INSERT INTO objects (id, type, kind, owner, privacy, name, preview, created_at) VALUES (?, ?, NULL, NULL, 'public', ?, '', ?) RETURNING rowid"),E=e.prepare("INSERT INTO identities (object, scheme, external_id) VALUES (?, ?, ?)"),s=e.prepare(`SELECT DISTINCT n.grantee FROM nodes n
|
|
634
|
+
WHERE NOT EXISTS (SELECT 1 FROM identities i WHERE i.external_id = n.grantee AND i.scheme IN ('app', 'local-user'))`).all();for(const{grantee:T}of s){let i;if(T==="user:local")i={type:"person",scheme:"local-user",handle:"user"};else if(/^app:[a-z0-9][a-z0-9._-]*$/.test(T))i={type:"app",scheme:"app",handle:T.slice(4)};else throw new Error(`canvas objects migration: node grantee ${JSON.stringify(T)} is neither app:<name> nor user:local`);const{rowid:a}=n.get(`${Date.now().toString(36)}-${Te(4).toString("hex")}`,i.type,i.handle,t);E.run(a,i.scheme,T)}e.exec(`INSERT INTO objects (id, type, kind, owner, privacy, name, preview, created_at)
|
|
635
635
|
SELECT n.node_id, 'node', n.kind, i.object, 'public', n.name, '', n.created
|
|
636
636
|
FROM nodes n JOIN identities i ON i.external_id = n.grantee AND i.scheme IN ('app', 'local-user')
|
|
637
|
-
WHERE NOT EXISTS (SELECT 1 FROM objects o WHERE o.id = n.node_id)`)}o(
|
|
637
|
+
WHERE NOT EXISTS (SELECT 1 FROM objects o WHERE o.id = n.node_id)`)}o(ne,"copyNodesIntoObjects");function mt(e){if(te(e),!M(e,"nodes","name"))return;ne(e);const t=e.prepare("SELECT COUNT(*) AS n FROM nodes WHERE node_id NOT IN (SELECT id FROM objects)").get();if(t.n>0)throw new Error(`canvasObjectsCut: ${t.n} node(s) have no objects row`);e.exec(`
|
|
638
638
|
ALTER TABLE edges RENAME TO legacy_edges;
|
|
639
639
|
CREATE TABLE edges (
|
|
640
640
|
type TEXT NOT NULL CHECK (type IN ('acted-on','links-to')),
|
|
@@ -682,7 +682,7 @@ CREATE INDEX IF NOT EXISTS idx_edges_type_created ON edges(type, created);
|
|
|
682
682
|
LEFT JOIN sessions s ON s.node_id = n.node_id AND s.unbound_at IS NULL
|
|
683
683
|
LEFT JOIN node_faults f ON f.node_id = n.node_id AND f.active = 1;
|
|
684
684
|
ANALYZE;
|
|
685
|
-
`)}o(
|
|
685
|
+
`)}o(mt,"canvasObjectsCut");function Xt(e){e.exec(`CREATE TABLE IF NOT EXISTS uploads (
|
|
686
686
|
upload_id TEXT PRIMARY KEY, grantee TEXT NOT NULL, name TEXT NOT NULL, media_type TEXT NOT NULL,
|
|
687
687
|
size INTEGER NOT NULL, created_at TEXT NOT NULL, delete_pending_since TEXT
|
|
688
688
|
);
|
|
@@ -698,4 +698,64 @@ CREATE INDEX IF NOT EXISTS idx_edges_type_created ON edges(type, created);
|
|
|
698
698
|
url TEXT NOT NULL, created_by TEXT NOT NULL, created_at TEXT NOT NULL, expires_at TEXT,
|
|
699
699
|
status TEXT NOT NULL CHECK (status IN ('on', 'off')), object_deleted_at TEXT
|
|
700
700
|
);
|
|
701
|
-
CREATE INDEX IF NOT EXISTS idx_shares_created_by ON shares(created_by);`)}o(
|
|
701
|
+
CREATE INDEX IF NOT EXISTS idx_shares_created_by ON shares(created_by);`)}o(Xt,"addFileTransfer");function ft(e){e.exec(`CREATE TABLE IF NOT EXISTS daemon_actions (
|
|
702
|
+
action_id TEXT PRIMARY KEY,
|
|
703
|
+
adapter_json TEXT NOT NULL,
|
|
704
|
+
body_json TEXT,
|
|
705
|
+
idempotency_key TEXT NOT NULL UNIQUE,
|
|
706
|
+
state TEXT NOT NULL CHECK (state IN ('pending', 'handed_off', 'acknowledged', 'permanent_failed')),
|
|
707
|
+
attempts INTEGER NOT NULL DEFAULT 0 CHECK (attempts >= 0),
|
|
708
|
+
next_attempt_at INTEGER,
|
|
709
|
+
claimed_at INTEGER,
|
|
710
|
+
claim_owner TEXT,
|
|
711
|
+
acknowledged_at INTEGER,
|
|
712
|
+
failed_at INTEGER,
|
|
713
|
+
last_failure_json TEXT,
|
|
714
|
+
canceled_at INTEGER,
|
|
715
|
+
created_at INTEGER NOT NULL,
|
|
716
|
+
updated_at INTEGER NOT NULL
|
|
717
|
+
);
|
|
718
|
+
CREATE INDEX IF NOT EXISTS daemon_actions_due ON daemon_actions(state, next_attempt_at, created_at, action_id) WHERE canceled_at IS NULL;
|
|
719
|
+
CREATE TEMP TABLE moved_actions AS
|
|
720
|
+
SELECT delivery_id, message_id FROM deliveries
|
|
721
|
+
WHERE destination_kind = 'external_action' AND adapter_json IS NOT NULL
|
|
722
|
+
AND (json_extract(adapter_json, '$.adapter') IN ('cron_spawn', 'cron_human') OR idempotency_key LIKE 'human-action:%');
|
|
723
|
+
INSERT OR IGNORE INTO daemon_actions
|
|
724
|
+
(action_id, adapter_json, body_json, idempotency_key, state, attempts, next_attempt_at, claimed_at, claim_owner,
|
|
725
|
+
acknowledged_at, failed_at, last_failure_json, canceled_at, created_at, updated_at)
|
|
726
|
+
SELECT d.delivery_id, d.adapter_json, m.body_json, COALESCE(d.idempotency_key, 'delivery:' || d.delivery_id),
|
|
727
|
+
CASE WHEN d.state = 'armed' THEN 'pending' ELSE d.state END, d.attempts,
|
|
728
|
+
CASE WHEN d.state = 'armed' THEN COALESCE(d.next_attempt_at, d.updated_at) ELSE d.next_attempt_at END,
|
|
729
|
+
d.claimed_at, d.claim_owner, d.acknowledged_at, d.failed_at, d.last_failure_json, d.canceled_at, d.created_at, d.updated_at
|
|
730
|
+
FROM deliveries d JOIN moved_actions ma ON ma.delivery_id = d.delivery_id
|
|
731
|
+
LEFT JOIN messages m ON m.message_id = d.message_id;
|
|
732
|
+
UPDATE human_requests
|
|
733
|
+
SET action_delivery_id = (SELECT a.action_id FROM daemon_actions a WHERE a.idempotency_key = 'human-action:' || human_requests.inbox_ticket_id)
|
|
734
|
+
WHERE action_delivery_id IS NOT NULL
|
|
735
|
+
AND EXISTS (SELECT 1 FROM daemon_actions a WHERE a.idempotency_key = 'human-action:' || human_requests.inbox_ticket_id);
|
|
736
|
+
DELETE FROM deliveries WHERE delivery_id IN (SELECT delivery_id FROM moved_actions);
|
|
737
|
+
DELETE FROM messages
|
|
738
|
+
WHERE message_id IN (SELECT message_id FROM moved_actions WHERE message_id IS NOT NULL)
|
|
739
|
+
AND NOT EXISTS (SELECT 1 FROM deliveries d WHERE d.message_id = messages.message_id);
|
|
740
|
+
DROP TABLE moved_actions;`)}o(ft,"moveDaemonActions");function Ct(e){if(v(e,"objects")){e.exec("PRAGMA foreign_keys = OFF;");try{e.exec("BEGIN IMMEDIATE");try{const t=e.prepare("SELECT COUNT(*) AS n FROM objects").get().n,n=e.prepare("SELECT name, sql FROM sqlite_master WHERE type = 'view' AND sql LIKE '%objects%'").all();for(const T of n)e.exec(`DROP VIEW "${T.name}"`);e.exec(`
|
|
741
|
+
CREATE TABLE objects_new (
|
|
742
|
+
rowid INTEGER PRIMARY KEY,
|
|
743
|
+
id TEXT NOT NULL UNIQUE,
|
|
744
|
+
type TEXT NOT NULL,
|
|
745
|
+
kind TEXT,
|
|
746
|
+
owner INTEGER REFERENCES objects(rowid),
|
|
747
|
+
privacy TEXT NOT NULL DEFAULT 'public' CHECK (privacy IN ('public','friends','private')),
|
|
748
|
+
name TEXT NOT NULL,
|
|
749
|
+
preview TEXT NOT NULL DEFAULT '',
|
|
750
|
+
created_at TEXT NOT NULL,
|
|
751
|
+
deleted_at TEXT
|
|
752
|
+
);
|
|
753
|
+
INSERT INTO objects_new (rowid, id, type, kind, owner, privacy, name, preview, created_at, deleted_at)
|
|
754
|
+
SELECT rowid, id, type, kind, owner, privacy, name, preview, created_at, deleted_at FROM objects;
|
|
755
|
+
DROP TABLE objects;
|
|
756
|
+
ALTER TABLE objects_new RENAME TO objects;
|
|
757
|
+
CREATE UNIQUE INDEX objects_doc_name ON objects(owner, name) WHERE type = 'document' AND deleted_at IS NULL;
|
|
758
|
+
CREATE UNIQUE INDEX objects_handle ON objects(type, name) WHERE type IN ('person','app','repo','profile');
|
|
759
|
+
CREATE INDEX objects_owner_type ON objects(owner, type, kind);
|
|
760
|
+
CREATE INDEX objects_type_kind ON objects(type, kind);
|
|
761
|
+
`);for(const T of n)e.exec(T.sql);const E=e.prepare("SELECT COUNT(*) AS n FROM objects").get().n;if(E!==t)throw new Error(`objects rebuild lost rows: expected ${t}, got ${E}`);const s=e.prepare("PRAGMA foreign_key_check").all();if(s.length>0)throw new Error(`objects rebuild left ${s.length} foreign-key violation(s)`);e.exec("COMMIT")}catch(t){throw e.exec("ROLLBACK"),t}}finally{e.exec("PRAGMA foreign_keys = ON;")}}}o(Ct,"objectsWithoutTypeCheck");const D=[Re,Ie,me,Xe,fe,Ce,Ue,De,Se,ge,we,ye,he,K,ve,K,xe,Fe,ke,Me,je,We,$e,qe,Je,Qe,ze,Ve,Ze,et,tt,nt,ot,Et,st,Tt,it,rt,at,e=>{se(e),ae(e),de(e),_e(e)},_t,Nt,dt,ct,Lt,ut,lt,Ot,pt,At,z,V,Z,ee,Rt,It,te,mt,le,Xt,ft,Ct],Ut=new Set([3,61]);function j(e){return e.prepare("PRAGMA user_version").get().user_version}o(j,"currentUserVersion");function oe(e,t){D[t](e),e.exec(`PRAGMA user_version = ${t+1}`)}o(oe,"applyMigration");function Ht(e){const t=j(e);if(t>D.length)throw new Error(`unsupported canvas schema version ${t} (latest supported ${D.length})`);if(t===D.length)return;const n=e.prepare("PRAGMA busy_timeout").get().timeout;e.exec("PRAGMA busy_timeout = 60000;");try{St(e)}finally{e.exec(`PRAGMA busy_timeout = ${n};`)}}o(Ht,"migrate");function St(e){for(;;){const t=j(e);if(t>=D.length)return;if(e.isTransaction||Ut.has(t)){oe(e,t);continue}e.exec("BEGIN IMMEDIATE");try{j(e)===t&&oe(e,t),e.exec("COMMIT")}catch(n){try{e.exec("ROLLBACK")}catch{}throw n}}}o(St,"runPendingMigrations");export{D as MIGRATIONS,Ht as migrate};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { DatabaseSync } from 'node:sqlite';
|
|
2
|
-
import type {
|
|
2
|
+
import type { Level, ListenDelivery } from '../graph/types.js';
|
|
3
3
|
import { type InboxDisposition, type InboxKind, type InboxTier } from './inbox.js';
|
|
4
4
|
export type { InboxDisposition, InboxKind, InboxTier } from './inbox.js';
|
|
5
5
|
export interface NodeMailInput {
|
|
@@ -20,32 +20,16 @@ export interface NodeMailInput {
|
|
|
20
20
|
/** Runs with the mail insert, before the transaction commits. */
|
|
21
21
|
withinEnqueue?: (db: DatabaseSync, messageId: string) => void;
|
|
22
22
|
}
|
|
23
|
-
export interface ExternalActionAdapter {
|
|
24
|
-
adapter: 'subprocess' | 'cron_spawn' | 'cron_human';
|
|
25
|
-
[key: string]: unknown;
|
|
26
|
-
}
|
|
27
|
-
export interface ExternalActionInput {
|
|
28
|
-
destinationId: string;
|
|
29
|
-
adapter: ExternalActionAdapter;
|
|
30
|
-
bodyJson: unknown;
|
|
31
|
-
idempotencyKey: string;
|
|
32
|
-
label?: string;
|
|
33
|
-
kind?: InboxKind;
|
|
34
|
-
}
|
|
35
23
|
export interface EnqueuedNodeMail {
|
|
36
24
|
messageId: string;
|
|
37
25
|
deliveryId: string;
|
|
38
26
|
urgency: InboxTier;
|
|
39
27
|
createdAt: string;
|
|
40
28
|
}
|
|
41
|
-
export interface EnqueuedExternalAction {
|
|
42
|
-
messageId: string;
|
|
43
|
-
deliveryId: string;
|
|
44
|
-
}
|
|
45
29
|
/** Insert one immutable message and one node-inbox obligation into the caller's write transaction. */
|
|
46
30
|
export declare function enqueueNodeMail(destinationNodeId: string, input: NodeMailInput): EnqueuedNodeMail;
|
|
47
31
|
export interface EventMailInput extends Omit<NodeMailInput, 'wake' | 'urgency' | 'idempotencyKey' | 'withinEnqueue'> {
|
|
48
|
-
event:
|
|
32
|
+
event: string;
|
|
49
33
|
objectId: string;
|
|
50
34
|
level: Level;
|
|
51
35
|
actorId: string | null;
|
|
@@ -76,8 +60,6 @@ export declare function queueNodeNotice(db: DatabaseSync, nodeId: string, notice
|
|
|
76
60
|
tier: InboxTier;
|
|
77
61
|
wake: 0 | 1;
|
|
78
62
|
}): EnqueuedNodeMail;
|
|
79
|
-
/** Insert one frozen external-action obligation. A duplicate idempotency key returns its original identity. */
|
|
80
|
-
export declare function enqueueExternalAction(input: ExternalActionInput): EnqueuedExternalAction;
|
|
81
63
|
/** Retract an obligation without fabricating a terminal receipt. */
|
|
82
64
|
export declare function cancelDelivery(deliveryId: string, now?: number): boolean;
|
|
83
65
|
export declare function cancelPendingNodeMail(nodeId: string, select?: {
|
|
@@ -1,14 +1,10 @@
|
|
|
1
|
-
var
|
|
1
|
+
var S=Object.defineProperty;var l=(r,e)=>S(r,"name",{value:e,configurable:!0});import{existsSync as A,mkdirSync as h,renameSync as R,writeFileSync as D}from"node:fs";import{randomBytes as T,randomUUID as O}from"node:crypto";import{join as L}from"node:path";import{cancelCronsOnWake as f}from"../canvas/crons.js";import{withCanvasWrite as y}from"../canvas/db.js";import{getRow as C}from"../canvas/canvas.js";import{messagesDir as x}from"../canvas/paths.js";import{syncDirectory as M,syncFile as J}from"../fs-utils.js";import{settleDeadControllerWait as W,settleMatchingControllerWait as w}from"../canvas/waits.js";import{generateOperationId as U,operationIdContext as j,validateOperationId as F}from"../events/operation-id.js";import{clipBody as $}from"../../shared/inbox-entry-body.js";function g(){let r;do r=T(16).toString("hex");while(r==="00000000000000000000000000000000");return r}l(g,"newId");function q(r,e){const n=JSON.stringify(r);if(n===void 0)throw new TypeError(`${e} must be JSON-serializable`);return n}l(q,"stringify");function N(r,e){return e!=="normal"&&e!=="deferred"?e:C(r)?.lifecycle==="terminal"?"urgent":e}l(N,"effectiveTier");function H(r,e,n){const d=x(r);A(d)||h(d,{recursive:!0});const t=e.replace(/[^0-9]/g,""),o=L(d,`${t}-${O().slice(0,6)}.md`),a=`${o}.tmp`;return D(a,n,"utf8"),J(a),R(a,o),M(d),o}l(H,"writeMessageBody");function P(r){if(typeof r!="object"||r===null)return"";const e=r.body;return typeof e=="string"?e.trim():""}l(P,"inlineBody");function _(r,e){const n=e.messageId??g(),d=Number(r.prepare("SELECT COALESCE(MAX(seq), 0) AS seq FROM messages").get().seq)+1;return r.prepare(`INSERT INTO messages
|
|
2
2
|
(message_id, seq, operation_id, created_at, sender_node_id, sender_name, kind, label, body_ref, body_json, disposition,
|
|
3
3
|
event, object_id, level, actor_id)
|
|
4
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(n,d,e.operationId,e.createdAt,e.senderNodeId,e.senderName,e.kind,e.label,e.bodyRef,e.bodyJson===void 0?null:
|
|
4
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(n,d,e.operationId,e.createdAt,e.senderNodeId,e.senderName,e.kind,e.label,e.bodyRef,e.bodyJson===void 0?null:q(e.bodyJson,"message body"),e.disposition,e.event?.event??null,e.event?.objectId??null,e.event?.level??null,e.event?.actorId??null),n}l(_,"insertMessage");function E(r,e,n,d,t,o,a){const s=g();return r.prepare(`INSERT INTO deliveries
|
|
5
5
|
(delivery_id, message_id, destination_kind, destination_id, urgency, wake, state, idempotency_key, created_at, updated_at)
|
|
6
|
-
VALUES (?, ?, 'node_inbox', ?, ?, ?, 'pending', ?, ?, ?)`).run(
|
|
7
|
-
FROM deliveries d JOIN messages m ON m.message_id = d.message_id WHERE d.idempotency_key = ?`).get(e.idempotencyKey);if(c!==void 0)return{messageId:c.message_id,deliveryId:c.delivery_id,urgency:c.urgency,createdAt:c.created_at}}const o=Date.now(),
|
|
6
|
+
VALUES (?, ?, 'node_inbox', ?, ?, ?, 'pending', ?, ?, ?)`).run(s,e,n,d,t,a??null,o,o),s}l(E,"insertNodeDelivery");function I(r,e){const n=new Date().toISOString(),d=r.operationId===void 0?j.current()??U():F(r.operationId);let t=r.bodyRef??null,o=r.bodyJson;if(t===null&&r.senderNodeId!=="human"){const a=P(o),s=$(a);s.clipped&&(t=H(e,n,a),o={...o,body:s.text})}return{createdAt:n,operationId:d,bodyRef:t,bodyJson:o}}l(I,"finalizeNodeMail");function B(r,e){const n=I(e,r);return y(d=>{const t=d.prepare("SELECT run_id FROM nodes WHERE node_id = ?").get(r);if(t?.run_id&&d.prepare("SELECT deleting_at FROM nodes WHERE node_id = ?").get(t.run_id)?.deleting_at)throw new Error("run is deleting");if(e.idempotencyKey!==void 0){const c=d.prepare(`SELECT d.delivery_id, d.message_id, d.urgency, m.created_at
|
|
7
|
+
FROM deliveries d JOIN messages m ON m.message_id = d.message_id WHERE d.idempotency_key = ?`).get(e.idempotencyKey);if(c!==void 0)return{messageId:c.message_id,deliveryId:c.delivery_id,urgency:c.urgency,createdAt:c.created_at}}const o=Date.now(),a=N(r,e.urgency),s=_(d,{messageId:e.messageId,operationId:n.operationId,createdAt:n.createdAt,senderNodeId:e.senderNodeId??null,senderName:e.senderName??null,kind:e.kind,label:e.label,bodyRef:n.bodyRef,bodyJson:n.bodyJson,disposition:e.disposition??null}),m=E(d,s,r,a,e.wake,o,e.idempotencyKey);return w(r,e.senderNodeId??null,o,d),e.withinEnqueue?.(d,s),e.wake===1&&a!=="deferred"&&f(r),{messageId:s,deliveryId:m,urgency:a,createdAt:n.createdAt}})}l(B,"enqueueNodeMail");function te(r){switch(r){case"interrupt":return{urgency:"critical",wake:1};case"steer":return{urgency:"urgent",wake:1};case"after-turn":return{urgency:"normal",wake:1};case"next-turn":return{urgency:"deferred",wake:0}}}l(te,"listenDeliveryTier");function oe(r,e,n){if(n.length===0)return[];const d=I({...e,urgency:"normal"},n[0].nodeId),t=Date.now(),o=_(r,{messageId:e.messageId,operationId:d.operationId,createdAt:d.createdAt,senderNodeId:e.senderNodeId??null,senderName:e.senderName??null,kind:e.kind,label:e.label,bodyRef:d.bodyRef,bodyJson:d.bodyJson,disposition:e.disposition??null,event:{event:e.event,objectId:e.objectId,level:e.level,actorId:e.actorId}}),a=e.event.startsWith("report.")||e.event.startsWith("notice."),s=e.senderNodeId??null,m=n.map(i=>i.nodeId),c=`(${m.map(()=>"?").join(",")})`,v=s===null?new Set:new Set(r.prepare(`SELECT DISTINCT node_id FROM waits WHERE kind = 'controller' AND target_id = ? AND satisfied_at IS NULL AND node_id IN ${c}`).all(s,...m).map(i=>i.node_id)),k=new Set(r.prepare(`SELECT DISTINCT anchor_node FROM crons WHERE cancel_on_wake = 1 AND anchor_node IN ${c}`).all(...m).map(i=>i.anchor_node)),b=r.prepare(`INSERT INTO deliveries
|
|
8
8
|
(delivery_id, message_id, destination_kind, destination_id, urgency, wake, state, idempotency_key, created_at, updated_at)
|
|
9
|
-
VALUES (?, ?, 'node_inbox', ?, ?, ?, 'pending', NULL, ?, ?)`);return n.map(
|
|
10
|
-
|
|
11
|
-
adapter_json, idempotency_key, created_at, updated_at)
|
|
12
|
-
VALUES (?, ?, 'external_action', ?, 'normal', 0, 'pending', ?, ?, ?, ?, ?)
|
|
13
|
-
ON CONFLICT(idempotency_key) WHERE idempotency_key IS NOT NULL DO NOTHING`).run(o,t,r.destinationId,d,v(r.adapter,"external action adapter"),r.idempotencyKey,d,d);if(Number(i.changes)===1)return{messageId:t,deliveryId:o};const a=e.prepare("SELECT delivery_id, message_id FROM deliveries WHERE idempotency_key = ?").get(r.idempotencyKey);if(a===void 0)throw new Error(`external action idempotency winner disappeared: ${r.idempotencyKey}`);return{messageId:a.message_id,deliveryId:a.delivery_id}})}l(ie,"enqueueExternalAction");function se(r,e=Date.now()){return m(n=>Number(n.prepare("UPDATE deliveries SET canceled_at = ?, updated_at = ? WHERE delivery_id = ? AND canceled_at IS NULL").run(e,e,r).changes)===1)}l(se,"cancelDelivery");function le(r,e={}){return m(n=>{const d=["d.destination_kind = 'node_inbox'","d.destination_id = ?","d.canceled_at IS NULL","d.state IN ('pending', 'handed_off')"],t=[r];e.senderNodeId!==void 0&&(d.push("m.sender_node_id IS ?"),t.push(e.senderNodeId)),e.kind!==void 0&&(d.push("m.kind = ?"),t.push(e.kind));const o=n.prepare(`SELECT d.delivery_id FROM deliveries d JOIN messages m ON m.message_id = d.message_id WHERE ${d.join(" AND ")}`).all(...t);if(o.length===0)return[];const i=Date.now();return n.prepare(`UPDATE deliveries SET canceled_at = ?, updated_at = ? WHERE delivery_id IN (${o.map(()=>"?").join(",")})`).run(i,i,...o.map(a=>a.delivery_id)),o.map(a=>a.delivery_id)})}l(le,"cancelPendingNodeMail");function ce(r,e){return m(n=>{const d=Date.now(),t=n.prepare(`SELECT target.status AS controller_status FROM waits w LEFT JOIN nodes target ON target.node_id = w.target_id
|
|
14
|
-
WHERE w.node_id = ? AND w.kind = 'controller' AND w.target_id = ? AND w.satisfied_at IS NULL`).get(r,e);if(t===void 0||t.controller_status==="active"||t.controller_status==="idle")return null;const o=P(r,{kind:"urgent",label:"declared controller is no longer live",bodyJson:{body:`Controller ${e} is no longer live; the declared message wait was cleared.`},urgency:"urgent",wake:1});if(!H(r,e,d,n))throw new Error(`controller wait changed while notifying ${r}`);return o})}l(ce,"enqueueControllerDeathNotice");export{se as cancelDelivery,le as cancelPendingNodeMail,ce as enqueueControllerDeathNotice,ie as enqueueExternalAction,P as enqueueNodeMail,oe as insertEventMail,te as listenDeliveryTier,ae as queueNodeNotice};
|
|
9
|
+
VALUES (?, ?, 'node_inbox', ?, ?, ?, 'pending', NULL, ?, ?)`);return n.map(i=>{const u=a?N(i.nodeId,i.urgency):i.urgency,p=g();return b.run(p,o,i.nodeId,u,i.wake,t,t),v.has(i.nodeId)&&w(i.nodeId,s,t,r),i.wake===1&&u!=="deferred"&&k.has(i.nodeId)&&f(i.nodeId),{destinationNodeId:i.nodeId,messageId:o,deliveryId:p,urgency:u,createdAt:d.createdAt}})}l(oe,"insertEventMail");function ae(r,e,n){const d={kind:"update",label:n.label??"notice",bodyJson:{body:n.body},urgency:n.tier,wake:n.wake},t=I(d,e),o=Date.now(),a=_(r,{operationId:t.operationId,createdAt:t.createdAt,senderNodeId:null,senderName:null,kind:d.kind,label:d.label,bodyRef:t.bodyRef,bodyJson:t.bodyJson,disposition:null}),s=E(r,a,e,n.tier,n.wake,o);return n.wake===1&&n.tier!=="deferred"&&f(e),{messageId:a,deliveryId:s,urgency:n.tier,createdAt:t.createdAt}}l(ae,"queueNodeNotice");function se(r,e=Date.now()){return y(n=>Number(n.prepare("UPDATE deliveries SET canceled_at = ?, updated_at = ? WHERE delivery_id = ? AND canceled_at IS NULL").run(e,e,r).changes)===1)}l(se,"cancelDelivery");function ie(r,e={}){return y(n=>{const d=["d.destination_kind = 'node_inbox'","d.destination_id = ?","d.canceled_at IS NULL","d.state IN ('pending', 'handed_off')"],t=[r];e.senderNodeId!==void 0&&(d.push("m.sender_node_id IS ?"),t.push(e.senderNodeId)),e.kind!==void 0&&(d.push("m.kind = ?"),t.push(e.kind));const o=n.prepare(`SELECT d.delivery_id FROM deliveries d JOIN messages m ON m.message_id = d.message_id WHERE ${d.join(" AND ")}`).all(...t);if(o.length===0)return[];const a=Date.now();return n.prepare(`UPDATE deliveries SET canceled_at = ?, updated_at = ? WHERE delivery_id IN (${o.map(()=>"?").join(",")})`).run(a,a,...o.map(s=>s.delivery_id)),o.map(s=>s.delivery_id)})}l(ie,"cancelPendingNodeMail");function le(r,e){return y(n=>{const d=Date.now(),t=n.prepare(`SELECT target.status AS controller_status FROM waits w LEFT JOIN nodes target ON target.node_id = w.target_id
|
|
10
|
+
WHERE w.node_id = ? AND w.kind = 'controller' AND w.target_id = ? AND w.satisfied_at IS NULL`).get(r,e);if(t===void 0||t.controller_status==="active"||t.controller_status==="idle")return null;const o=B(r,{kind:"urgent",label:"declared controller is no longer live",bodyJson:{body:`Controller ${e} is no longer live; the declared message wait was cleared.`},urgency:"urgent",wake:1});if(!W(r,e,d,n))throw new Error(`controller wait changed while notifying ${r}`);return o})}l(le,"enqueueControllerDeathNotice");export{se as cancelDelivery,ie as cancelPendingNodeMail,le as enqueueControllerDeathNotice,B as enqueueNodeMail,oe as insertEventMail,te as listenDeliveryTier,ae as queueNodeNotice};
|