@north-light/cli 0.3.709 → 0.3.711
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/clients/attach/input/capabilities.js +1 -1
- package/dist/clients/attach/input/controller.d.ts +1 -1
- package/dist/clients/attach/input/controller.js +2 -2
- package/dist/clients/attach/render/chat-view.d.ts +13 -2
- package/dist/clients/attach/render/chat-view.js +2 -2
- package/dist/clients/attach/session/input-wiring.d.ts +2 -2
- package/dist/clients/attach/session/layout-record.d.ts +15 -0
- package/dist/clients/attach/session/layout-record.js +1 -0
- package/dist/clients/attach/session/reconnect.d.ts +8 -1
- package/dist/clients/attach/session/reconnect.js +1 -1
- package/dist/clients/attach/session/teardown.d.ts +2 -0
- package/dist/clients/attach/session/teardown.js +3 -3
- package/dist/clients/attach/slash/dispatch.js +2 -2
- package/dist/clients/attach/slash/recover.d.ts +10 -0
- package/dist/clients/attach/slash/recover.js +3 -0
- package/dist/clients/attach/viewer.js +520 -516
- package/dist/commands/human/prompts.js +1 -1
- package/dist/commands/human/request.js +1 -1
- package/dist/commands/sys/doctor.js +1 -1
- package/dist/commands/sys/tutorial/scenario.js +2 -2
- package/dist/core/broker-client/client.d.ts +2 -0
- package/dist/core/broker-client/client.js +1 -1
- package/dist/core/broker-client/transport-relay.d.ts +6 -0
- package/dist/core/broker-client/transport-relay.js +1 -1
- package/dist/core/broker-client/transport.d.ts +4 -0
- package/dist/core/canvas/daemon-actions.d.ts +1 -1
- package/dist/core/canvas/daemon-actions.js +7 -7
- package/dist/core/canvas/deliveries.d.ts +1 -1
- package/dist/core/canvas/deliveries.js +21 -21
- package/dist/core/canvas/executions.d.ts +1 -1
- package/dist/core/canvas/executions.js +1 -1
- package/dist/core/canvas/managed-worktree-sweep-candidates.d.ts +2 -2
- package/dist/core/canvas/managed-worktree-sweep-candidates.js +5 -3
- package/dist/core/canvas/reconciler-leases.d.ts +4 -0
- package/dist/core/canvas/reconciler-leases.js +5 -5
- package/dist/core/canvas/schema-pg/028-machine-calls-worktree-sweep.sql +6 -0
- package/dist/core/canvas/schema-version.d.ts +1 -1
- package/dist/core/canvas/schema-version.js +1 -1
- package/dist/core/conversation-store/client.js +2 -2
- package/dist/core/conversation-store/index.d.ts +5 -2
- package/dist/core/conversation-store/row-store.js +14 -12
- package/dist/core/graph/package-docs.js +5 -5
- package/dist/core/graph/package-publish.js +4 -3
- package/dist/core/human/requests.js +19 -19
- package/dist/core/import/load/run.js +2 -2
- package/dist/core/runtime/broker/client-registry.d.ts +1 -1
- package/dist/core/runtime/broker/client-registry.js +1 -1
- package/dist/core/runtime/broker/turn-replies.js +3 -1
- package/dist/core/runtime/broker-protocol.d.ts +4 -4
- package/dist/core/runtime/broker-protocol.js +3 -3
- package/dist/core/runtime/broker-request.d.ts +2 -0
- package/dist/core/runtime/broker-request.js +1 -1
- package/dist/core/runtime/broker.js +1 -1
- package/dist/core/runtime/model-swap.d.ts +2 -1
- package/dist/core/runtime/model-swap.js +1 -1
- package/dist/core/runtime/placement-tmux.d.ts +2 -1
- package/dist/core/runtime/placement-tmux.js +1 -1
- package/dist/core/runtime/runner/machine/call.js +2 -2
- package/dist/core/runtime/runner/machine/ops.d.ts +11 -1
- package/dist/core/runtime/runner/machine/ops.js +1 -1
- package/dist/core/runtime/session-cycles.d.ts +21 -0
- package/dist/core/runtime/session-cycles.js +1 -1
- package/dist/core/runtime/tmux-driver.d.ts +7 -0
- package/dist/core/runtime/tmux-driver.js +6 -6
- package/dist/core/worktree-machine.d.ts +4 -1
- package/dist/core/worktree-machine.js +1 -1
- package/dist/core/worktree-sweep.d.ts +14 -3
- package/dist/core/worktree-sweep.js +4 -4
- package/dist/daemon/api/app-listener.js +1 -1
- package/dist/daemon/api/handlers/charges.d.ts +1 -1
- package/dist/daemon/api/handlers/charges.js +1 -1
- package/dist/daemon/api/handlers/conversations.js +4 -3
- package/dist/daemon/api/handlers/environments.d.ts +1 -1
- package/dist/daemon/api/handlers/environments.js +1 -1
- package/dist/daemon/api/handlers/limits.js +1 -1
- package/dist/daemon/api/handlers/nodes.js +1 -1
- package/dist/daemon/api/operations.js +1 -1
- package/dist/daemon/api/router.js +1 -1
- package/dist/daemon/cron/live-runs.d.ts +3 -0
- package/dist/daemon/cron/live-runs.js +1 -1
- package/dist/daemon/cron/machine-fire.js +1 -1
- package/dist/daemon/crtrd.js +12 -12
- package/dist/daemon/due-sources.d.ts +1 -1
- package/dist/daemon/due-sources.js +1 -1
- package/dist/daemon/due.js +7 -7
- package/dist/daemon/fleet.d.ts +1 -1
- package/dist/daemon/fleet.js +4 -4
- package/dist/daemon/human/finish.js +3 -3
- package/dist/daemon/human/settle.js +1 -1
- package/dist/daemon/reconcilers/action-lane.js +1 -1
- package/dist/daemon/reconcilers/delivery-lane.js +2 -2
- package/dist/daemon/reconcilers/grant-effects.js +1 -1
- package/dist/daemon/reconcilers/managed-worktree-sweep.js +1 -1
- package/dist/daemon/reconcilers/node-lifecycle/requested-stops.js +2 -2
- package/dist/daemon/runs/observer.d.ts +4 -0
- package/dist/daemon/runs/observer.js +1 -1
- package/dist/pi-extensions/canvas-inbox-watcher.js +1 -1
- package/package.json +4 -3
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/clients/attach/input/capabilities.js +1 -0
- package/packages/crouter-api/dist/clients/attach/input/controller.js +2 -2
- package/packages/crouter-api/dist/clients/attach/render/chat-view.js +40 -3
- package/packages/crouter-api/dist/clients/attach/session/layout-record.js +52 -0
- package/packages/crouter-api/dist/clients/attach/session/reconnect.js +41 -2
- package/packages/crouter-api/dist/clients/attach/session/teardown.js +2 -0
- package/packages/crouter-api/dist/clients/attach/slash/dispatch.js +12 -0
- package/packages/crouter-api/dist/clients/attach/slash/recover.js +133 -0
- package/packages/crouter-api/dist/clients/attach/viewer.js +24 -5
- package/packages/crouter-api/dist/commands/human/prompts.js +11 -18
- package/packages/crouter-api/dist/commands/human/request.js +3 -0
- package/packages/crouter-api/dist/commands/sys/doctor.js +17 -0
- package/packages/crouter-api/dist/commands/sys/tutorial/scenario.js +1 -0
- package/packages/crouter-api/dist/core/broker-client/client.js +4 -0
- package/packages/crouter-api/dist/core/broker-client/transport-relay.js +45 -0
- package/packages/crouter-api/dist/core/canvas/daemon-actions.js +3 -2
- package/packages/crouter-api/dist/core/canvas/deliveries.js +7 -3
- package/packages/crouter-api/dist/core/canvas/executions.js +8 -7
- package/packages/crouter-api/dist/core/canvas/reconciler-leases.js +4 -0
- package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
- package/packages/crouter-api/dist/core/conversation-store/client.js +1 -1
- package/packages/crouter-api/dist/core/conversation-store/row-store.js +14 -1
- package/packages/crouter-api/dist/core/graph/package-docs.js +8 -3
- package/packages/crouter-api/dist/core/graph/package-publish.js +8 -1
- package/packages/crouter-api/dist/core/human/requests.js +2 -2
- package/packages/crouter-api/dist/core/runtime/broker-ownership.js +6 -0
- package/packages/crouter-api/dist/core/runtime/broker-protocol.js +4 -4
- package/packages/crouter-api/dist/core/runtime/broker-request.js +1 -1
- package/packages/crouter-api/dist/core/runtime/model-swap.js +2 -1
- package/packages/crouter-api/dist/core/runtime/placement-tmux.js +3 -3
- package/packages/crouter-api/dist/core/runtime/runner/machine/call.js +1 -1
- package/packages/crouter-api/dist/core/runtime/runner/machine/executor.js +235 -0
- package/packages/crouter-api/dist/core/runtime/runner/machine/ops.js +1 -1
- package/packages/crouter-api/dist/core/runtime/session-cycles.js +90 -8
- package/packages/crouter-api/dist/core/runtime/tmux-driver.js +11 -0
- package/packages/crouter-api/dist/core/worktree-machine.js +20 -0
- package/packages/crouter-api/dist/core/worktree-sweep.js +439 -0
- package/packages/crouter-api/dist/daemon/api/operations.js +3 -3
- package/packages/crouter-api/dist/daemon/api/router.js +1 -4
- package/packages/crouter-api/dist/daemon/cron/live-runs.js +4 -5
- package/packages/crouter-api/dist/daemon/cron/machine-fire.js +3 -3
- package/packages/crouter-api/dist/daemon/human/finish.js +2 -1
- package/packages/crouter-api/dist/daemon/human/settle.js +1 -6
- package/packages/crouter-api/dist/daemon/runs/observer.js +1 -1
- 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
- package/scripts/install-runtime.mjs +18 -1
- package/scripts/lib/install-source.mjs +49 -0
- package/dist/daemon/reconcilers/idle-sandbox.d.ts +0 -18
- package/dist/daemon/reconcilers/idle-sandbox.js +0 -7
|
@@ -26,6 +26,7 @@ import { BUILTIN_SLASH_COMMANDS } from '../../../core/runtime/pi-vendored.js';
|
|
|
26
26
|
import { surfaceTmuxStyleArgs } from '../../../core/runtime/surface-bg.js';
|
|
27
27
|
import { crouterMenuTmuxArgs } from '../../../core/runtime/tmux-bindings.js';
|
|
28
28
|
import { viewerOperationForSlash } from '../input/capabilities.js';
|
|
29
|
+
import { formatReport, recover } from './recover.js';
|
|
29
30
|
import { shellQuote } from '../../../shared/shell-quote.js';
|
|
30
31
|
/** Canvas slash-commands — implemented NATIVE in the viewer, the ONLY live host:
|
|
31
32
|
* the broker binds mode:'rpc', so broker pi-extensions never run their
|
|
@@ -49,6 +50,7 @@ export const CANVAS_SLASH_COMMANDS = [
|
|
|
49
50
|
{ name: 'mcp', description: 'MCP servers — status from the adapter’s config/cache; Enter (or /mcp <server>) connects, reconnects, or re-auths' },
|
|
50
51
|
{ name: 'rename', description: 'Rename this node everywhere — node row, viewer window, session chip, tmux pane: /rename <name>' },
|
|
51
52
|
{ name: 'color', description: 'Color this node — tmux pane outline + name chip: /color <color> (red, blue, #rrggbb, …) or /color none' },
|
|
53
|
+
{ name: 'recover', description: 'After a crash or reboot: revive every disconnected node and rebuild the tmux viewer panes that were open' },
|
|
52
54
|
{ name: 'mouse', description: 'Toggle mouse wheel scrolling and drag-select — off restores tmux drag-select and copy-mode mouse' },
|
|
53
55
|
{ name: 'copy-message', description: 'Copy the newest message visible in the transcript viewport' },
|
|
54
56
|
{ name: 'copy-tool', description: 'Copy the newest tool call output' },
|
|
@@ -407,6 +409,16 @@ function dispatchCanvasCommand(name, arg, ctx) {
|
|
|
407
409
|
else
|
|
408
410
|
ctx.notify('Verbosity is not wired into this viewer');
|
|
409
411
|
return true;
|
|
412
|
+
case 'recover':
|
|
413
|
+
if (arg)
|
|
414
|
+
return usage(ctx, '/recover — no argument');
|
|
415
|
+
if (process.env['TMUX'] === undefined) {
|
|
416
|
+
ctx.notify('/recover needs tmux');
|
|
417
|
+
return true;
|
|
418
|
+
}
|
|
419
|
+
ctx.notify('Recovering — reviving nodes and rebuilding panes…');
|
|
420
|
+
recover().then((report) => ctx.notify(formatReport(report)), (err) => ctx.notify(`recover failed: ${err instanceof Error ? err.message : String(err)}`));
|
|
421
|
+
return true;
|
|
410
422
|
case 'mouse':
|
|
411
423
|
// Viewer-local render state only — no frame, no CLI, no node mutation.
|
|
412
424
|
if (ctx.onToggleMouse)
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
// slash/recover.ts — `/recover`: after a crash or reboot, revive every disconnected node and rebuild the
|
|
2
|
+
// tmux viewer layout. The layout comes from the per-viewer records in session/layout-record.ts; when none
|
|
3
|
+
// exist it falls back to the nodes whose viewers the daemon logged opening in the last hour.
|
|
4
|
+
import { existsSync, statSync, openSync, readSync, closeSync } from 'node:fs';
|
|
5
|
+
import { spawnSync } from 'node:child_process';
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
import { routes } from '../../../api/index.js';
|
|
8
|
+
import { cliClient } from '../../../commands/api-client.js';
|
|
9
|
+
import { runtimeRoot } from '../../../core/layout.js';
|
|
10
|
+
import { liveViewerPanes } from '../../../core/runtime/tmux-driver.js';
|
|
11
|
+
import { openViewerPane, selectLayout } from '../../../core/runtime/placement-tmux.js';
|
|
12
|
+
import { readLayoutRecords } from '../session/layout-record.js';
|
|
13
|
+
const LOG_TAIL_BYTES = 8 * 1024 * 1024;
|
|
14
|
+
const FALLBACK_WINDOW_MS = 60 * 60_000;
|
|
15
|
+
/** Node ids of viewers the daemon logged opening within the last hour, oldest first. */
|
|
16
|
+
function recentViewOpens(now) {
|
|
17
|
+
const path = join(runtimeRoot(), 'crtrd.log');
|
|
18
|
+
if (!existsSync(path))
|
|
19
|
+
return [];
|
|
20
|
+
const size = statSync(path).size;
|
|
21
|
+
const start = Math.max(0, size - LOG_TAIL_BYTES);
|
|
22
|
+
const buf = Buffer.alloc(size - start);
|
|
23
|
+
const fd = openSync(path, 'r');
|
|
24
|
+
try {
|
|
25
|
+
readSync(fd, buf, 0, buf.length, start);
|
|
26
|
+
}
|
|
27
|
+
finally {
|
|
28
|
+
closeSync(fd);
|
|
29
|
+
}
|
|
30
|
+
const ids = [];
|
|
31
|
+
for (const line of buf.toString('utf8').split('\n')) {
|
|
32
|
+
if (!line.includes('daemon.timing.view_open_received'))
|
|
33
|
+
continue;
|
|
34
|
+
try {
|
|
35
|
+
const e = JSON.parse(line);
|
|
36
|
+
if (e.event === 'daemon.timing.view_open_received' && e.node_id !== undefined && now - Date.parse(e.ts) <= FALLBACK_WINDOW_MS && !ids.includes(e.node_id))
|
|
37
|
+
ids.push(e.node_id);
|
|
38
|
+
}
|
|
39
|
+
catch { /* partial first line of the tail */ }
|
|
40
|
+
}
|
|
41
|
+
return ids;
|
|
42
|
+
}
|
|
43
|
+
/** `<canvas>\t<node>` for every running cloud viewer on this Mac. A cloud viewer leaves no tmux pane tag, so its process is the evidence. */
|
|
44
|
+
function runningCloudViewers() {
|
|
45
|
+
const out = spawnSync('ps', ['-axo', 'command'], { encoding: 'utf8' }).stdout ?? '';
|
|
46
|
+
const found = new Set();
|
|
47
|
+
for (const line of out.split('\n')) {
|
|
48
|
+
const m = /surface\s+attach\s+to\s+(\S+)(?:\s+--observer)?\s+--canvas\s+'?([^'\s]+)'?/.exec(line);
|
|
49
|
+
if (m !== null)
|
|
50
|
+
found.add(`${m[2]}\t${m[1]}`);
|
|
51
|
+
}
|
|
52
|
+
return found;
|
|
53
|
+
}
|
|
54
|
+
export async function recover(now = Date.now()) {
|
|
55
|
+
const client = cliClient();
|
|
56
|
+
const result = await client.request('POST', routes.reviveAll());
|
|
57
|
+
const failedIds = new Set(result.failed.map((f) => f.node_id));
|
|
58
|
+
const report = {
|
|
59
|
+
revived: result.revived.length,
|
|
60
|
+
failed: result.failed.map((f) => `${f.node_id}: ${f.error}`),
|
|
61
|
+
frozen: result.frozen.length, panes: 0, skipped: 0, source: 'none',
|
|
62
|
+
};
|
|
63
|
+
let records = readLayoutRecords();
|
|
64
|
+
if (records.length > 0)
|
|
65
|
+
report.source = 'snapshot';
|
|
66
|
+
else {
|
|
67
|
+
const nodes = recentViewOpens(now);
|
|
68
|
+
if (nodes.length > 0)
|
|
69
|
+
report.source = 'recent views';
|
|
70
|
+
// One session per project directory, one window per node.
|
|
71
|
+
records = [];
|
|
72
|
+
for (const nodeId of nodes)
|
|
73
|
+
records.push({ nodeId, session: '', windowIndex: records.length, windowName: '', paneIndex: 0, cwd: '', pane: '' });
|
|
74
|
+
}
|
|
75
|
+
const viewed = new Set(liveViewerPanes().map((p) => p.nodeId));
|
|
76
|
+
const cloudViewed = runningCloudViewers();
|
|
77
|
+
const targets = [];
|
|
78
|
+
for (const rec of records) {
|
|
79
|
+
if (rec.canvas !== undefined) {
|
|
80
|
+
// A cloud node kept running through the local crash: only its viewer pane needs reopening, and this Mac's daemon cannot read its status.
|
|
81
|
+
if (cloudViewed.has(`${rec.canvas}\t${rec.nodeId}`)) {
|
|
82
|
+
report.skipped++;
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
targets.push({ ...rec, windowName: rec.windowName === '' ? rec.nodeId : rec.windowName, cwd: rec.cwd === '' ? process.cwd() : rec.cwd });
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
if (viewed.has(rec.nodeId) || failedIds.has(rec.nodeId)) {
|
|
89
|
+
report.skipped++;
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
try {
|
|
93
|
+
const node = await client.getNode(rec.nodeId);
|
|
94
|
+
if (node.status === 'done' || node.status === 'canceled' || node.final_report != null) {
|
|
95
|
+
report.skipped++;
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
const cwd = rec.cwd === '' ? node.cwd : rec.cwd;
|
|
99
|
+
const session = rec.session === '' ? (cwd.split('/').filter(Boolean).pop() ?? 'crtr') : rec.session;
|
|
100
|
+
targets.push({ ...rec, cwd, session, windowName: rec.windowName === '' ? node.name : rec.windowName });
|
|
101
|
+
}
|
|
102
|
+
catch {
|
|
103
|
+
report.skipped++;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
targets.sort((a, b) => a.session.localeCompare(b.session) || a.windowIndex - b.windowIndex || a.paneIndex - b.paneIndex);
|
|
107
|
+
const firstPane = new Map();
|
|
108
|
+
for (const t of targets) {
|
|
109
|
+
const key = `${t.session}\t${t.windowIndex}`;
|
|
110
|
+
const beside = firstPane.get(key);
|
|
111
|
+
const opened = openViewerPane(t.nodeId, t.session, { name: t.windowName, cwd: t.cwd, waitForBroker: t.canvas === undefined, ...(t.canvas === undefined ? {} : { canvas: t.canvas }), ...(beside === undefined ? {} : { besidePane: beside }) });
|
|
112
|
+
if (opened === null) {
|
|
113
|
+
report.failed.push(`${t.nodeId}: tmux refused to open a pane`);
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
if (beside === undefined)
|
|
117
|
+
firstPane.set(key, opened.pane);
|
|
118
|
+
else if (opened.window !== null)
|
|
119
|
+
selectLayout(opened.window, 'even-horizontal');
|
|
120
|
+
report.panes++;
|
|
121
|
+
}
|
|
122
|
+
return report;
|
|
123
|
+
}
|
|
124
|
+
export function formatReport(r) {
|
|
125
|
+
const parts = [`revived ${r.revived}`, `${r.panes} pane${r.panes === 1 ? '' : 's'} recreated (${r.source})`];
|
|
126
|
+
if (r.frozen > 0)
|
|
127
|
+
parts.push(`${r.frozen} waiting for broker slots`);
|
|
128
|
+
if (r.skipped > 0)
|
|
129
|
+
parts.push(`${r.skipped} skipped (already viewed, finished, or not revivable)`);
|
|
130
|
+
if (r.failed.length > 0)
|
|
131
|
+
parts.push(`${r.failed.length} failed: ${r.failed.join('; ')}`);
|
|
132
|
+
return `Recovered — ${parts.join(', ')}`;
|
|
133
|
+
}
|
|
@@ -63,6 +63,7 @@ import { createLayout } from './session/layout.js';
|
|
|
63
63
|
import { createEditorInventory } from './session/editor-inventory.js';
|
|
64
64
|
import { createFrecencyStore } from './input/completion-frecency.js';
|
|
65
65
|
import { createNodeIdentity } from './session/identity.js';
|
|
66
|
+
import { removeLayoutRecord, writeLayoutRecord } from './session/layout-record.js';
|
|
66
67
|
import { createPaneTag } from './session/pane-tag.js';
|
|
67
68
|
import { launchProfileFileSearch, relatedNodes } from './session/profile-files.js';
|
|
68
69
|
import { createSessionStateSync } from './session/state-sync.js';
|
|
@@ -454,10 +455,12 @@ onConnected) {
|
|
|
454
455
|
// True once nothing is held any more: delivered at the first welcome, or handed to a parked node's wake path.
|
|
455
456
|
let settled = false;
|
|
456
457
|
const sendToBroker = (frame) => {
|
|
457
|
-
if (welcomed)
|
|
458
|
-
socket.send(frame);
|
|
459
|
-
else
|
|
458
|
+
if (!welcomed) {
|
|
460
459
|
heldFrames.push(frame);
|
|
460
|
+
return;
|
|
461
|
+
}
|
|
462
|
+
socket.send(frame);
|
|
463
|
+
reconnect.probe();
|
|
461
464
|
};
|
|
462
465
|
const onFirstWelcome = () => {
|
|
463
466
|
welcomed = true;
|
|
@@ -487,7 +490,7 @@ onConnected) {
|
|
|
487
490
|
if (userConfig.whip_mode)
|
|
488
491
|
whipAnimation.play();
|
|
489
492
|
},
|
|
490
|
-
onMessageSent: (text) => chatView.addPendingSend(text),
|
|
493
|
+
onMessageSent: (text, viaSocket) => chatView.addPendingSend(text, viaSocket),
|
|
491
494
|
send: sendToBroker,
|
|
492
495
|
frecency,
|
|
493
496
|
});
|
|
@@ -671,6 +674,8 @@ onConnected) {
|
|
|
671
674
|
(observer ? ' --observer' : '') +
|
|
672
675
|
(canvasName !== undefined ? ` --canvas ${quoteIfNeeded(canvasName)}` : ''),
|
|
673
676
|
tagPane: paneTag.pane,
|
|
677
|
+
forgetLayout: () => { if (ctx.nodeId !== '')
|
|
678
|
+
removeLayoutRecord(ctx.nodeId, paneTag.pane(), canvasName); },
|
|
674
679
|
});
|
|
675
680
|
const teardown = lifecycle.teardown;
|
|
676
681
|
let startupFailure;
|
|
@@ -698,8 +703,17 @@ onConnected) {
|
|
|
698
703
|
chatView.settleRun();
|
|
699
704
|
sync.patchLocal({ isStreaming: false });
|
|
700
705
|
},
|
|
706
|
+
onReconnecting: () => chatView.setPendingUndelivered(true),
|
|
707
|
+
// A message sent on a connection that had already died never reached the broker: send it again now that one answers.
|
|
708
|
+
onReconnected: (snapshot) => {
|
|
709
|
+
for (const text of chatView.unconfirmedSends(snapshot))
|
|
710
|
+
socket.send({ type: 'prompt', text });
|
|
711
|
+
chatView.setPendingUndelivered(false);
|
|
712
|
+
},
|
|
701
713
|
});
|
|
702
714
|
paneTag.set();
|
|
715
|
+
if (ctx.nodeId !== '')
|
|
716
|
+
writeLayoutRecord(ctx.nodeId, paneTag.pane(), meta.cwd, canvasName);
|
|
703
717
|
// 5. Lay out and paint; the broker connection follows (`dialBroker`).
|
|
704
718
|
layout.mount();
|
|
705
719
|
// Synchronous with tui.start(): the caller's screen gives the terminal back and the viewer takes it in the same tick, with no cooked-mode gap.
|
|
@@ -804,8 +818,12 @@ onConnected) {
|
|
|
804
818
|
detachHint: () => detachHint(crouterBindings),
|
|
805
819
|
hasExclusiveSurface: () => surfaceHost.hasFullPaneSurface(),
|
|
806
820
|
setPaneFocused: (focused) => {
|
|
807
|
-
if (focused)
|
|
821
|
+
if (focused) {
|
|
808
822
|
paneTag.stamp();
|
|
823
|
+
if (ctx.nodeId !== '')
|
|
824
|
+
writeLayoutRecord(ctx.nodeId, paneTag.pane(), meta.cwd, canvasName);
|
|
825
|
+
reconnect.probe();
|
|
826
|
+
}
|
|
809
827
|
paneFocus.setPaneFocused(focused);
|
|
810
828
|
tui.requestRender();
|
|
811
829
|
},
|
|
@@ -894,6 +912,7 @@ onConnected) {
|
|
|
894
912
|
// Text sent while the dial was still running has no broker to hold it: deliver it as the wake message a parked viewer's own sends use.
|
|
895
913
|
// An engine command (`/x`, `!x`) is refused as a later parked submission is, and returned to the editor.
|
|
896
914
|
settled = true;
|
|
915
|
+
chatView.stopResendingPendingSends();
|
|
897
916
|
const refused = [];
|
|
898
917
|
for (const frame of heldFrames.splice(0)) {
|
|
899
918
|
if (!('text' in frame))
|
|
@@ -240,14 +240,18 @@ export function humanSend(pageSurface = false) {
|
|
|
240
240
|
const responseBearing = prepared.manifest.slots.some(isResponseBearingSlot);
|
|
241
241
|
const delivery = deliveryFrom(input, responseBearing, lifecycle);
|
|
242
242
|
prepared.manifest = submitAuthoredPage(() => validateAuthoredPageManifest({ ...prepared.manifest, delivery }, productKinds));
|
|
243
|
+
const originNodeId = askingNode();
|
|
244
|
+
if (delivery.reply && (originNodeId === null || originNodeId === '')) {
|
|
245
|
+
throw new InputError({ error: 'no_requester', message: 'a response-bearing page must be sent from a crouter node', field: 'page', next: 'Run `crtr human send` from the node that should receive the answer.' });
|
|
246
|
+
}
|
|
247
|
+
const created = await cliClient().createHumanRequest({
|
|
248
|
+
page: { dialect: prepared.manifest.dialect, source: prepared.document },
|
|
249
|
+
delivery,
|
|
250
|
+
source: prepared.manifest.source,
|
|
251
|
+
requester_node_id: originNodeId || null,
|
|
252
|
+
creator_cwd: process.cwd(),
|
|
253
|
+
});
|
|
243
254
|
if (!delivery.reply) {
|
|
244
|
-
const created = await cliClient().createHumanRequest({
|
|
245
|
-
page: { dialect: prepared.manifest.dialect, source: prepared.document },
|
|
246
|
-
delivery,
|
|
247
|
-
source: prepared.manifest.source,
|
|
248
|
-
requester_node_id: null,
|
|
249
|
-
creator_cwd: process.cwd(),
|
|
250
|
-
});
|
|
251
255
|
const dir = created.request_dir;
|
|
252
256
|
// A page with no reply route carries no response-bearing components, so what the
|
|
253
257
|
// follow-up must get right is where the person will meet it and how it
|
|
@@ -264,17 +268,6 @@ export function humanSend(pageSurface = false) {
|
|
|
264
268
|
: 'Published as passive page content with no inbox or response lifecycle.';
|
|
265
269
|
return { page_id: created.request_id, dir, ...delivery, follow_up: followUp };
|
|
266
270
|
}
|
|
267
|
-
const originNodeId = askingNode();
|
|
268
|
-
if (originNodeId === null || originNodeId === '') {
|
|
269
|
-
throw new InputError({ error: 'no_requester', message: 'a response-bearing page must be sent from a crouter node', field: 'page', next: 'Run `crtr human send` from the node that should receive the answer.' });
|
|
270
|
-
}
|
|
271
|
-
const created = await cliClient().createHumanRequest({
|
|
272
|
-
page: { dialect: prepared.manifest.dialect, source: prepared.document },
|
|
273
|
-
delivery,
|
|
274
|
-
source: prepared.manifest.source,
|
|
275
|
-
requester_node_id: originNodeId,
|
|
276
|
-
creator_cwd: process.cwd(),
|
|
277
|
-
});
|
|
278
271
|
return { page_id: created.request_id, dir: created.request_dir, ...delivery, follow_up: queuedFollowUp() };
|
|
279
272
|
}
|
|
280
273
|
finally {
|
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
// document to a local command. Every leaf is a thin typed call on crtrd; the
|
|
6
6
|
// daemon owns validation, settlement, and delivery.
|
|
7
7
|
import { existsSync, readFileSync } from 'node:fs';
|
|
8
|
+
import { envNodeId } from '../../shared/env.js';
|
|
8
9
|
import { defineBranch, defineLeaf } from '../../core/command.js';
|
|
9
10
|
import { InputError } from '../../core/io.js';
|
|
10
11
|
import { cliClient, rethrowAsCliError } from '../api-client.js';
|
|
@@ -119,6 +120,8 @@ const createLeaf = defineLeaf({
|
|
|
119
120
|
const body = readJsonFile(path, 'request-file', 'the create object');
|
|
120
121
|
if (body['creator_cwd'] === undefined)
|
|
121
122
|
body['creator_cwd'] = process.cwd();
|
|
123
|
+
if (body['requester_node_id'] === undefined)
|
|
124
|
+
body['requester_node_id'] = envNodeId() ?? null;
|
|
122
125
|
try {
|
|
123
126
|
const created = await cliClient().createHumanRequest(body);
|
|
124
127
|
return {
|
|
@@ -2,6 +2,7 @@ import { envGrantee, envProfileId } from '../../shared/env.js';
|
|
|
2
2
|
import { requiredPluginEnv } from '../../core/plugin-env.js';
|
|
3
3
|
import { createHash } from 'node:crypto';
|
|
4
4
|
import { lstat, readFile, readdir, readlink } from 'node:fs/promises';
|
|
5
|
+
import { readFileSync } from 'node:fs';
|
|
5
6
|
import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
6
7
|
import { defineLeaf } from '../../core/command.js';
|
|
7
8
|
import { normalizeRequires, readConfig, updateConfig } from '../../core/config.js';
|
|
@@ -385,6 +386,21 @@ function runNerdFontCheck() {
|
|
|
385
386
|
...(plan.command ? { command: plan.command } : {}),
|
|
386
387
|
});
|
|
387
388
|
}
|
|
389
|
+
/** Where the generation was installed from (`<id>.source.json` beside it, written by install-runtime). */
|
|
390
|
+
function installSourceCheck(label, generation) {
|
|
391
|
+
const name = `runtime:${label}:source`;
|
|
392
|
+
let source;
|
|
393
|
+
try {
|
|
394
|
+
source = JSON.parse(readFileSync(join(dirname(generation.root), `${generation.id}.source.json`), 'utf8'));
|
|
395
|
+
}
|
|
396
|
+
catch {
|
|
397
|
+
return pass('canvas', name, 'not recorded (installed from a package, or before install sources were recorded)');
|
|
398
|
+
}
|
|
399
|
+
const where = `${source.branch ?? '?'} @ ${source.commit?.slice(0, 9) ?? '?'} from ${source.checkout ?? '?'}${source.node ? ` by node ${source.node}` : ''}, ${source.installedAt ?? ''}`;
|
|
400
|
+
if (source.unlanded === undefined || source.unlanded.length === 0)
|
|
401
|
+
return pass('canvas', name, `origin/main: ${where}`);
|
|
402
|
+
return failCheck('canvas', name, `unlanded code is installed (${source.unlanded.join('; ')}): ${where}. Land it and reinstall from origin/main.`);
|
|
403
|
+
}
|
|
388
404
|
async function generationChecks(label, lookup, allowAbsent) {
|
|
389
405
|
if (lookup.generation === null) {
|
|
390
406
|
const message = lookup.error ?? 'no runtime generation';
|
|
@@ -396,6 +412,7 @@ async function generationChecks(label, lookup, allowAbsent) {
|
|
|
396
412
|
if (!shape.ok)
|
|
397
413
|
return [failCheck('canvas', `runtime:${label}:manifest`, shape.error)];
|
|
398
414
|
results.push(pass('canvas', `runtime:${label}:manifest`, `${generation.id} ${generation.manifest.packageVersion}`));
|
|
415
|
+
results.push(installSourceCheck(label, generation));
|
|
399
416
|
try {
|
|
400
417
|
await verifySealed(generation.root);
|
|
401
418
|
results.push(pass('canvas', `runtime:${label}:sealing`, 'generation tree is sealed and contained'));
|
|
@@ -207,6 +207,7 @@ async function startPendingAsk(record, parent) {
|
|
|
207
207
|
page: { dialect: 'jsx', source: DEMO_PAGE },
|
|
208
208
|
delivery: { placement: 'inline', inbox: true, reply: false },
|
|
209
209
|
source: { askedBy: 'crtr sys tutorial', sessionName: 'tutorial', nodeId: parent },
|
|
210
|
+
requester_node_id: parent,
|
|
210
211
|
creator_cwd: process.cwd(),
|
|
211
212
|
}).catch(rethrowAsCliError);
|
|
212
213
|
await appendScenarioId('pending-ask', 'requests', created.request_id);
|
|
@@ -130,6 +130,10 @@ export class BrokerClient extends EventEmitter {
|
|
|
130
130
|
return Promise.reject(new Error('no node to redial yet'));
|
|
131
131
|
return this.transport.redial(options);
|
|
132
132
|
}
|
|
133
|
+
/** Check that the connection still answers; see {@link Transport.probe}. True for a transport that has no probe. */
|
|
134
|
+
probe(timeoutMs) {
|
|
135
|
+
return this.transport?.probe?.(timeoutMs) ?? Promise.resolve(true);
|
|
136
|
+
}
|
|
133
137
|
/** Encode + send one client→broker frame. No-op on a dead/absent
|
|
134
138
|
* connection; never throws. */
|
|
135
139
|
send(frame) {
|
|
@@ -27,6 +27,8 @@ function relayUrl(target, nodeId, wakeParked) {
|
|
|
27
27
|
url.hash = '';
|
|
28
28
|
return url.toString();
|
|
29
29
|
}
|
|
30
|
+
/** A frame or pong heard this recently already shows the connection answers, so a probe sends nothing. */
|
|
31
|
+
const PROBE_FRESH_MS = 1_000;
|
|
30
32
|
export class RelayTransport extends EventEmitter {
|
|
31
33
|
nodeId;
|
|
32
34
|
target;
|
|
@@ -43,6 +45,9 @@ export class RelayTransport extends EventEmitter {
|
|
|
43
45
|
}
|
|
44
46
|
refusal;
|
|
45
47
|
refusalError;
|
|
48
|
+
/** When this connection last received a frame or a pong. */
|
|
49
|
+
heardAt = 0;
|
|
50
|
+
probing;
|
|
46
51
|
get url() {
|
|
47
52
|
return relayUrl(this.target, this.nodeId, this.wakeParked);
|
|
48
53
|
}
|
|
@@ -58,6 +63,7 @@ export class RelayTransport extends EventEmitter {
|
|
|
58
63
|
});
|
|
59
64
|
ws.once('upgrade', () => mark('relay.upgrade_response', { node: this.nodeId, target: kind, since_dial_ms: since() }));
|
|
60
65
|
ws.once('open', () => mark('relay.ws_open', { node: this.nodeId, target: kind, since_dial_ms: since() }));
|
|
66
|
+
ws.on('pong', () => { this.heardAt = Date.now(); });
|
|
61
67
|
// A refusal's JSON body carries the reason (`broker_not_ready`, `attach_revive_failed`); ws would drop it as a bare status.
|
|
62
68
|
ws.on('unexpected-response', (_req, res) => {
|
|
63
69
|
let text = '';
|
|
@@ -129,6 +135,44 @@ export class RelayTransport extends EventEmitter {
|
|
|
129
135
|
/* dead socket — 'close' will fire and drive teardown */
|
|
130
136
|
}
|
|
131
137
|
}
|
|
138
|
+
/** A WebSocket whose network path went away (the computer slept, the wifi changed) stays OPEN and reports no close for minutes, and a
|
|
139
|
+
* frame sent on it is lost. Ping it; with no pong inside `timeoutMs`, terminate it so 'close' fires and the caller redials. */
|
|
140
|
+
probe(timeoutMs) {
|
|
141
|
+
const ws = this.ws;
|
|
142
|
+
if (ws === undefined || ws.readyState !== WebSocket.OPEN)
|
|
143
|
+
return Promise.resolve(true);
|
|
144
|
+
if (Date.now() - this.heardAt < PROBE_FRESH_MS)
|
|
145
|
+
return Promise.resolve(true);
|
|
146
|
+
if (this.probing !== undefined)
|
|
147
|
+
return this.probing;
|
|
148
|
+
const probing = new Promise((resolve) => {
|
|
149
|
+
const settle = (answered) => {
|
|
150
|
+
clearTimeout(timer);
|
|
151
|
+
ws.off('pong', onPong);
|
|
152
|
+
ws.off('close', onClose);
|
|
153
|
+
this.probing = undefined;
|
|
154
|
+
resolve(answered);
|
|
155
|
+
};
|
|
156
|
+
const onPong = () => settle(true);
|
|
157
|
+
// The connection closed by itself: the ordinary close path is already running.
|
|
158
|
+
const onClose = () => settle(false);
|
|
159
|
+
const drop = () => {
|
|
160
|
+
settle(false);
|
|
161
|
+
ws.terminate();
|
|
162
|
+
};
|
|
163
|
+
const timer = setTimeout(drop, timeoutMs);
|
|
164
|
+
ws.on('pong', onPong);
|
|
165
|
+
ws.on('close', onClose);
|
|
166
|
+
try {
|
|
167
|
+
ws.ping();
|
|
168
|
+
}
|
|
169
|
+
catch {
|
|
170
|
+
drop();
|
|
171
|
+
}
|
|
172
|
+
});
|
|
173
|
+
this.probing = probing;
|
|
174
|
+
return probing;
|
|
175
|
+
}
|
|
132
176
|
destroy() {
|
|
133
177
|
const ws = this.ws;
|
|
134
178
|
if (ws !== undefined && ws.readyState <= WebSocket.OPEN) {
|
|
@@ -152,6 +196,7 @@ export class RelayTransport extends EventEmitter {
|
|
|
152
196
|
// the local FrameDecoder's own bad-JSON handling).
|
|
153
197
|
return;
|
|
154
198
|
}
|
|
199
|
+
this.heardAt = Date.now();
|
|
155
200
|
this.emit('frame', frame);
|
|
156
201
|
}
|
|
157
202
|
onError(err) {
|
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
// same state/attempt/owner fence `settleDelivery` applies to deliveries.
|
|
7
7
|
import { randomBytes } from 'node:crypto';
|
|
8
8
|
import { withCanvasWrite, openDb } from './db.js';
|
|
9
|
+
import { CLAIM_OWNER_EXPIRED_SQL } from './reconciler-leases.js';
|
|
9
10
|
import { normalizedSettlement } from './deliveries.js';
|
|
10
11
|
import { withRetryBudget } from './delivery-contract.js';
|
|
11
12
|
import { emitEvent } from '../events/emit.js';
|
|
@@ -92,7 +93,7 @@ export async function retryFailedDaemonAction(actionId, now = Date.now()) {
|
|
|
92
93
|
WHERE action_id = ? AND state = 'permanent_failed' AND canceled_at IS NULL AND last_failure_json IS NOT NULL`).run(now, now, actionId)).changes) === 1;
|
|
93
94
|
}
|
|
94
95
|
/** Daemon startup: an action a previous daemon handed off is due again now. */
|
|
95
|
-
export async function resetHandedOffDaemonActions(now) {
|
|
96
|
+
export async function resetHandedOffDaemonActions(now, onlyExpired = false) {
|
|
96
97
|
return Number((await (await openDb()).prepare(`UPDATE daemon_actions SET state = 'pending', next_attempt_at = ?, claimed_at = NULL, claim_owner = NULL, updated_at = ?
|
|
97
|
-
WHERE state = 'handed_off'`).run(now, now)).changes);
|
|
98
|
+
WHERE state = 'handed_off'${onlyExpired ? ` AND ${CLAIM_OWNER_EXPIRED_SQL}` : ''}`).run(now, now, ...(onlyExpired ? [new Date(now).toISOString()] : []))).changes);
|
|
98
99
|
}
|
|
@@ -2,6 +2,7 @@ import { prepared as cachedStatement } from '../sqlite-statements.js';
|
|
|
2
2
|
import { existsSync, readFileSync } from 'node:fs';
|
|
3
3
|
import { randomBytes } from 'node:crypto';
|
|
4
4
|
import { withCanvasWrite, openDb } from './db.js';
|
|
5
|
+
import { CLAIM_OWNER_EXPIRED_SQL } from './reconciler-leases.js';
|
|
5
6
|
import { inboxPath, passivePath } from './paths.js';
|
|
6
7
|
import { withRetryBudget } from './delivery-contract.js';
|
|
7
8
|
import { emitEvent } from '../events/emit.js';
|
|
@@ -201,16 +202,19 @@ export async function claimPushDelivery(deliveryId, now, claimOwner) {
|
|
|
201
202
|
return deliveryFrom(await db.prepare('SELECT * FROM deliveries WHERE delivery_id = ?').get(deliveryId));
|
|
202
203
|
});
|
|
203
204
|
}
|
|
204
|
-
export async function resetHandedOffDeliveries(now) {
|
|
205
|
+
export async function resetHandedOffDeliveries(now, onlyExpired = false) {
|
|
205
206
|
return await withCanvasWrite(async (db) => {
|
|
206
207
|
// Boot has reaped the previous daemon's detached work. Canceled attempts
|
|
207
208
|
// must retire, not return to pending and block their replacement forever.
|
|
209
|
+
// A cloud role releases only claims whose owner's heartbeat lapsed: a live peer pod keeps its own.
|
|
210
|
+
const expired = onlyExpired ? ` AND ${CLAIM_OWNER_EXPIRED_SQL}` : '';
|
|
211
|
+
const lease = onlyExpired ? [new Date(now).toISOString()] : [];
|
|
208
212
|
const retired = await db.prepare(`UPDATE deliveries SET state = 'permanent_failed', next_attempt_at = NULL,
|
|
209
213
|
claimed_at = NULL, claim_owner = NULL, failed_at = ?, updated_at = ?
|
|
210
|
-
WHERE state = 'handed_off' AND canceled_at IS NOT NULL AND next_attempt_at IS NOT NULL`).run(now, now);
|
|
214
|
+
WHERE state = 'handed_off' AND canceled_at IS NOT NULL AND next_attempt_at IS NOT NULL${expired}`).run(now, now, ...lease);
|
|
211
215
|
const released = await db.prepare(`UPDATE deliveries SET state = 'pending', next_attempt_at = CASE WHEN next_attempt_at IS NOT NULL THEN ?::bigint ELSE NULL END,
|
|
212
216
|
claimed_at = NULL, claim_owner = NULL, updated_at = ?
|
|
213
|
-
WHERE state = 'handed_off' AND (canceled_at IS NULL OR next_attempt_at IS NULL)`).run(now, now);
|
|
217
|
+
WHERE state = 'handed_off' AND (canceled_at IS NULL OR next_attempt_at IS NULL)${expired}`).run(now, now, ...lease);
|
|
214
218
|
return Number(retired.changes) + Number(released.changes);
|
|
215
219
|
});
|
|
216
220
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
2
|
import { openDb, withCanvasWrite } from './db.js';
|
|
3
|
-
import { capturePidIdentities, captureLivenessSnapshot, identitiesMatch, isBootScopedIdentity, isLegacyTicksIdentity } from './pid.js';
|
|
3
|
+
import { capturePidIdentities, captureLivenessSnapshot, identitiesMatch, recordedPidLiveness, isBootScopedIdentity, isLegacyTicksIdentity } from './pid.js';
|
|
4
4
|
import { existsSync, readFileSync } from 'node:fs';
|
|
5
5
|
import { LAUNCHER_SOCKET } from '../../launcher/spec.js';
|
|
6
6
|
import { revokeNodeTokens } from './node-tokens.js';
|
|
@@ -50,7 +50,7 @@ export class ExecutionCapReached extends Error {
|
|
|
50
50
|
}
|
|
51
51
|
}
|
|
52
52
|
/** Thrown by `beginExecution` when the node already holds a live execution another caller owns: a remote one, or a process
|
|
53
|
-
* one this daemon epoch began. The holder keeps its row and token; the caller adopts it or backs off, never replaces it. */
|
|
53
|
+
* one this daemon epoch began (launching or running). The holder keeps its row and token; the caller adopts it or backs off, never replaces it. */
|
|
54
54
|
export class ExecutionAlreadyLive extends Error {
|
|
55
55
|
nodeId;
|
|
56
56
|
executionId;
|
|
@@ -77,11 +77,12 @@ export async function beginExecution(nodeId, input) {
|
|
|
77
77
|
if (live >= input.cap)
|
|
78
78
|
throw new ExecutionCapReached(input.cap, live);
|
|
79
79
|
}
|
|
80
|
-
// Under the node lock, a live row
|
|
81
|
-
//
|
|
82
|
-
// and
|
|
83
|
-
const live = await db.prepare("SELECT execution_id, runner, daemon_epoch, state FROM executions WHERE node_id = ? AND state != 'exited'").all(nodeId);
|
|
84
|
-
const owned = live.find((row) => row.
|
|
80
|
+
// Under the node lock, a live row a remote broker owns or this daemon epoch began is refused, not replaced: replacing it
|
|
81
|
+
// would revoke the token its owner handed to a broker. A running process row of this epoch whose process is provably dead,
|
|
82
|
+
// and any process row an earlier daemon epoch left behind, is superseded.
|
|
83
|
+
const live = await db.prepare("SELECT execution_id, runner, daemon_epoch, state, pid, process_identity FROM executions WHERE node_id = ? AND state != 'exited'").all(nodeId);
|
|
84
|
+
const owned = live.find((row) => row.runner !== 'process' || (input.daemonEpoch !== null && row.daemon_epoch === input.daemonEpoch
|
|
85
|
+
&& (row.state === 'launching' || recordedPidLiveness(row.pid, row.process_identity, captureLivenessSnapshot()) !== 'dead')));
|
|
85
86
|
if (owned !== undefined)
|
|
86
87
|
throw new ExecutionAlreadyLive(nodeId, owned.execution_id);
|
|
87
88
|
const superseded = await db.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = 'superseded' WHERE node_id = ? AND state != 'exited'").run(at, at, nodeId);
|
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
import { openDb } from './db.js';
|
|
2
|
+
/** The lane whose rows are live daemon instances: a delivery or daemon-action claim is held by an instance id with an unexpired row here. */
|
|
3
|
+
export const DAEMON_OWNER_LANE = 'cron-owner';
|
|
4
|
+
/** SQL (parameter: now ISO) true for a claim whose owner has no live heartbeat. */
|
|
5
|
+
export const CLAIM_OWNER_EXPIRED_SQL = `NOT EXISTS (SELECT 1 FROM reconciler_leases WHERE lane = '${DAEMON_OWNER_LANE}' AND key = claim_owner AND expires_at > ?)`;
|
|
2
6
|
function expiry(ttlMs) {
|
|
3
7
|
if (!Number.isFinite(ttlMs) || ttlMs <= 0)
|
|
4
8
|
throw new Error('reconciler lease duration must be positive');
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
/** The canvas schema version this build supports: the number of the highest delta in `schema-pg/` (the baseline
|
|
7
7
|
* `schema-pg.sql` is version 1). `scripts/install-runtime.mjs` reads this module from a candidate generation to refuse
|
|
8
8
|
* one below the live database's `schema_min_reader`. */
|
|
9
|
-
export const CANVAS_SCHEMA_VERSION =
|
|
9
|
+
export const CANVAS_SCHEMA_VERSION = 28;
|
|
10
10
|
/** The Postgres schema holding the canvas tables: `CRTR_DATABASE_SCHEMA` (`crtr` in the cloud deploy). Unset or empty
|
|
11
11
|
* means the role's own search_path (`public` on a Mac and on a VM). A name that is not a plain identifier is an error:
|
|
12
12
|
* it is put in a `search_path` connection option. */
|
|
@@ -98,7 +98,7 @@ export function createStoreClient(address, token) {
|
|
|
98
98
|
return { header: header, entries, path: reply.path ?? '' };
|
|
99
99
|
return { header: header, entries: entries.slice(0, reply.tail - 1), tail: entries.slice(reply.tail - 1), path: reply.path ?? '' };
|
|
100
100
|
};
|
|
101
|
-
const readPath = (id, window) => window === 'cycle' ? `${url(id)}?from=cycle` : window ? `${url(id)}?head=${window.head}&tail=${window.tail}` : url(id);
|
|
101
|
+
const readPath = (id, window) => window === 'cycle' ? `${url(id)}?from=cycle` : window && 'beforeCycle' in window ? `${url(id)}?before=cycle&bytes=${window.beforeCycle}` : window ? `${url(id)}?head=${window.head}&tail=${window.tail}` : url(id);
|
|
102
102
|
return {
|
|
103
103
|
create(nodeId, header, entries, path) {
|
|
104
104
|
return JSON.parse(call('POST', '/conversations', { node_id: nodeId, header, entries, path }).body);
|
|
@@ -233,7 +233,7 @@ export function createRowStore() {
|
|
|
233
233
|
const snap = await snapshot(db, id);
|
|
234
234
|
const size = snap.parts.reduce((n, p) => n + p.bytes, 0) + snap.tail.reduce((n, p) => n + p.bytes, 0);
|
|
235
235
|
const entriesOf = (text) => decode(text).filter((entry) => entry.type !== 'session');
|
|
236
|
-
|
|
236
|
+
const cycleOffset = async () => {
|
|
237
237
|
const stored = await db.prepare('SELECT cycle_offset FROM conversation_parts WHERE conversation_id = ? AND seq = 0').get(id);
|
|
238
238
|
let offset = stored?.cycle_offset == null ? null : Number(stored.cycle_offset);
|
|
239
239
|
if (offset === null) {
|
|
@@ -250,8 +250,21 @@ export function createRowStore() {
|
|
|
250
250
|
}
|
|
251
251
|
await withCanvasWrite(async (tx) => { await tx.prepare('UPDATE conversation_parts SET cycle_offset = ? WHERE conversation_id = ? AND seq = 0 AND cycle_offset IS NULL').run(offset, id); });
|
|
252
252
|
}
|
|
253
|
+
return offset;
|
|
254
|
+
};
|
|
255
|
+
if (window === 'cycle') {
|
|
256
|
+
const offset = await cycleOffset();
|
|
253
257
|
return { header, entries: entriesOf((await bytesOf(snap, offset, size)).toString('utf8')), path };
|
|
254
258
|
}
|
|
259
|
+
if (window && 'beforeCycle' in window) {
|
|
260
|
+
const end = await cycleOffset();
|
|
261
|
+
const from = Math.max(0, end - window.beforeCycle);
|
|
262
|
+
// One byte before the window says whether it begins on a line boundary.
|
|
263
|
+
const lines = (await bytesOf(snap, from > 0 ? from - 1 : 0, end)).toString('utf8').split('\n');
|
|
264
|
+
if (from > 0)
|
|
265
|
+
lines.shift();
|
|
266
|
+
return { header, entries: entriesOf(lines.join('\n')), path };
|
|
267
|
+
}
|
|
255
268
|
if (!window || size <= window.head + window.tail)
|
|
256
269
|
return { header, entries: entriesOf((await bytesOf(snap, 0, size)).toString('utf8')), path };
|
|
257
270
|
const front = (await bytesOf(snap, 0, Math.max(0, window.head))).toString('utf8').split('\n');
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
* the one `ownerForGrantee` gives), and a document with a `source_path` is shipped. */
|
|
7
7
|
import { randomUUID } from 'node:crypto';
|
|
8
8
|
import { documentFields } from '../../migrations/004-canvas-documents/fields.js';
|
|
9
|
-
import {
|
|
9
|
+
import { findMany as findBodies, put as putBody } from './bodies.js';
|
|
10
10
|
import { applyDocumentFields, deleteDocument, documentRecord, heads, importDocument, linksIn, moveDocument } from './documents.js';
|
|
11
11
|
import { deleteShippedReader, writeShippedReader } from '../permissions/facts.js';
|
|
12
12
|
import { setLinks } from './edges.js';
|
|
@@ -59,8 +59,13 @@ export async function relinkAllShipped(db) {
|
|
|
59
59
|
for (const { id, owner } of docs) {
|
|
60
60
|
const doc = (await getById(db, id));
|
|
61
61
|
const [head] = await heads(db, doc);
|
|
62
|
-
if (head
|
|
63
|
-
|
|
62
|
+
if (head === undefined)
|
|
63
|
+
continue;
|
|
64
|
+
// A head with no `bodies` row belongs to a package not yet converged in this pass (an upgrade from before text moved into the table);
|
|
65
|
+
// its own publish heals the row, so it is skipped here rather than failing every other package.
|
|
66
|
+
const body = (await findBodies(db, [head.body_hash])).get(head.body_hash);
|
|
67
|
+
if (body !== undefined)
|
|
68
|
+
await deriveLinks(db, (await getById(db, owner)), doc, body);
|
|
64
69
|
}
|
|
65
70
|
}
|
|
66
71
|
export async function convergeFile(db, owner, file, report, reposFn) {
|