@north-light/cli 0.3.710 → 0.3.712
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/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 +4 -2
- package/dist/clients/attach/session/layout-record.js +1 -1
- package/dist/clients/attach/session/reconnect.d.ts +8 -1
- package/dist/clients/attach/session/reconnect.js +1 -1
- package/dist/clients/attach/slash/recover.js +3 -2
- package/dist/clients/attach/viewer.js +405 -404
- 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/reconciler-leases.d.ts +4 -0
- package/dist/core/canvas/reconciler-leases.js +5 -5
- 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/graph/reader.js +3 -3
- package/dist/core/human/requests.js +19 -19
- package/dist/core/import/load/run.js +2 -2
- package/dist/core/permissions/evaluator.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.js +1 -1
- package/dist/core/runtime/placement-tmux.d.ts +1 -0
- package/dist/core/runtime/placement-tmux.js +1 -1
- package/dist/core/runtime/session-cycles.d.ts +21 -0
- package/dist/core/runtime/session-cycles.js +1 -1
- 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/human/finish.js +3 -3
- package/dist/daemon/human/settle.js +1 -1
- package/dist/daemon/machine-daemon.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/node-lifecycle/requested-stops.js +2 -2
- package/package.json +4 -3
- package/packages/crouter-api/dist/api/contract.js +1 -1
- 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 +7 -7
- package/packages/crouter-api/dist/clients/attach/session/reconnect.js +41 -2
- package/packages/crouter-api/dist/clients/attach/slash/recover.js +23 -1
- package/packages/crouter-api/dist/clients/attach/viewer.js +21 -10
- 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/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/graph/reader.js +7 -1
- package/packages/crouter-api/dist/core/human/requests.js +2 -2
- package/packages/crouter-api/dist/core/permissions/evaluator.js +12 -6
- package/packages/crouter-api/dist/core/runtime/broker-protocol.js +4 -4
- package/packages/crouter-api/dist/core/runtime/placement-tmux.js +2 -2
- package/packages/crouter-api/dist/core/runtime/session-cycles.js +90 -8
- 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/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
|
@@ -253,6 +253,9 @@ export class ChatView {
|
|
|
253
253
|
* welcome snapshot rebuild never drops them. */
|
|
254
254
|
pendingContainer = new MeasuredContainer();
|
|
255
255
|
pendingSends = [];
|
|
256
|
+
/** True while the viewer is redialing a closed connection. */
|
|
257
|
+
pendingUndelivered = false;
|
|
258
|
+
undeliveredNote;
|
|
256
259
|
/** Optional banner, above history and status in the viewport's flat source. */
|
|
257
260
|
bannerContainer;
|
|
258
261
|
/** Add one line to the banner after construction: a new root learns its id only when its create returns. */
|
|
@@ -1675,8 +1678,9 @@ export class ChatView {
|
|
|
1675
1678
|
this.bashComponent = undefined;
|
|
1676
1679
|
}
|
|
1677
1680
|
/** Show a message the person just sent as pending: gray text, no background,
|
|
1678
|
-
* until the engine echoes it as a user message.
|
|
1679
|
-
|
|
1681
|
+
* until the engine echoes it as a user message. `resend`: it went to the broker
|
|
1682
|
+
* socket, so a reconnect sends it again when the fresh snapshot does not hold it. */
|
|
1683
|
+
addPendingSend(text, resend = false) {
|
|
1680
1684
|
const trimmed = text.trim();
|
|
1681
1685
|
if (!trimmed)
|
|
1682
1686
|
return;
|
|
@@ -1686,9 +1690,40 @@ export class ChatView {
|
|
|
1686
1690
|
];
|
|
1687
1691
|
for (const part of parts)
|
|
1688
1692
|
this.pendingContainer.addChild(part);
|
|
1689
|
-
this.pendingSends.push({ text: trimmed, parts });
|
|
1693
|
+
this.pendingSends.push({ text: trimmed, parts, resend });
|
|
1694
|
+
this.refreshUndeliveredNote();
|
|
1690
1695
|
this.tui.requestRender();
|
|
1691
1696
|
}
|
|
1697
|
+
/** While the viewer redials, say under the pending messages that they were not delivered. */
|
|
1698
|
+
setPendingUndelivered(on) {
|
|
1699
|
+
this.pendingUndelivered = on;
|
|
1700
|
+
this.refreshUndeliveredNote();
|
|
1701
|
+
this.tui.requestRender();
|
|
1702
|
+
}
|
|
1703
|
+
refreshUndeliveredNote() {
|
|
1704
|
+
if (this.undeliveredNote !== undefined)
|
|
1705
|
+
this.pendingContainer.removeChild(this.undeliveredNote);
|
|
1706
|
+
this.undeliveredNote = undefined;
|
|
1707
|
+
if (!this.pendingUndelivered || !this.pendingSends.some((sent) => sent.resend))
|
|
1708
|
+
return;
|
|
1709
|
+
this.undeliveredNote = new Text(this.dimStyle('✗ not delivered — reconnecting; it is sent again when the connection is back'), 1, 0);
|
|
1710
|
+
this.pendingContainer.addChild(this.undeliveredNote);
|
|
1711
|
+
}
|
|
1712
|
+
/** After a reconnect: the pending messages sent to the broker socket that the fresh snapshot holds neither as a user message nor in its queue, oldest first. */
|
|
1713
|
+
unconfirmedSends(snapshot) {
|
|
1714
|
+
const seen = new Set([...(snapshot.queued?.steering ?? []), ...(snapshot.queued?.followUp ?? [])].map((text) => text.trim()));
|
|
1715
|
+
for (const message of snapshot.messages.slice(-50)) {
|
|
1716
|
+
if (message.role === 'user')
|
|
1717
|
+
seen.add(this.userMessageText(message).trim());
|
|
1718
|
+
}
|
|
1719
|
+
return this.pendingSends.filter((sent) => sent.resend && !seen.has(sent.text)).map((sent) => sent.text);
|
|
1720
|
+
}
|
|
1721
|
+
/** The pending messages were handed to a parked node's wake message, so a reconnect must not send them again. */
|
|
1722
|
+
stopResendingPendingSends() {
|
|
1723
|
+
for (const sent of this.pendingSends)
|
|
1724
|
+
sent.resend = false;
|
|
1725
|
+
this.refreshUndeliveredNote();
|
|
1726
|
+
}
|
|
1692
1727
|
/** The engine echoed a user message: the matching pending send landed. */
|
|
1693
1728
|
confirmPendingSend(text) {
|
|
1694
1729
|
// The engine may reshape the text (image blocks, wrapping); with no exact
|
|
@@ -1700,6 +1735,7 @@ export class ChatView {
|
|
|
1700
1735
|
const [sent] = this.pendingSends.splice(index, 1);
|
|
1701
1736
|
for (const part of sent.parts)
|
|
1702
1737
|
this.pendingContainer.removeChild(part);
|
|
1738
|
+
this.refreshUndeliveredNote();
|
|
1703
1739
|
}
|
|
1704
1740
|
/** A snapshot rebuild: drop pending sends whose text the history now holds. */
|
|
1705
1741
|
confirmPendingSendsIn(messages) {
|
|
@@ -1717,6 +1753,7 @@ export class ChatView {
|
|
|
1717
1753
|
for (const part of sent.parts)
|
|
1718
1754
|
this.pendingContainer.removeChild(part);
|
|
1719
1755
|
}
|
|
1756
|
+
this.refreshUndeliveredNote();
|
|
1720
1757
|
}
|
|
1721
1758
|
/** Swap the single active activity indicator (working/compaction/retry). */
|
|
1722
1759
|
setActivity(loader) {
|
|
@@ -8,26 +8,26 @@ import { join } from 'node:path';
|
|
|
8
8
|
import { runtimeRoot } from '../../../core/layout.js';
|
|
9
9
|
import { paneCoordinates } from '../../../core/runtime/placement-tmux.js';
|
|
10
10
|
function recordsDir() { return join(runtimeRoot(), 'viewer-panes'); }
|
|
11
|
-
function recordPath(nodeId) { return join(recordsDir(), `${nodeId}.json`); }
|
|
12
|
-
export function writeLayoutRecord(nodeId, pane, cwd) {
|
|
11
|
+
function recordPath(nodeId, canvas) { return join(recordsDir(), canvas === undefined ? `${nodeId}.json` : `${canvas.replace(/[^A-Za-z0-9._-]/g, '_')}--${nodeId}.json`); }
|
|
12
|
+
export function writeLayoutRecord(nodeId, pane, cwd, canvas) {
|
|
13
13
|
if (pane === undefined || pane === '')
|
|
14
14
|
return;
|
|
15
15
|
const where = paneCoordinates(pane);
|
|
16
16
|
if (where === null)
|
|
17
17
|
return;
|
|
18
|
-
const record = { nodeId, session: where.session, windowIndex: where.windowIndex, windowName: where.windowName, paneIndex: where.paneIndex, cwd, pane };
|
|
18
|
+
const record = { nodeId, session: where.session, windowIndex: where.windowIndex, windowName: where.windowName, paneIndex: where.paneIndex, cwd, pane, ...(canvas === undefined ? {} : { canvas }) };
|
|
19
19
|
try {
|
|
20
20
|
mkdirSync(recordsDir(), { recursive: true });
|
|
21
|
-
writeFileSync(recordPath(nodeId), JSON.stringify(record));
|
|
21
|
+
writeFileSync(recordPath(nodeId, canvas), JSON.stringify(record));
|
|
22
22
|
}
|
|
23
23
|
catch { /* best-effort: a missing record only costs the recovery one pane */ }
|
|
24
24
|
}
|
|
25
25
|
/** Delete this node's record unless another viewer pane has since claimed it. */
|
|
26
|
-
export function removeLayoutRecord(nodeId, pane) {
|
|
26
|
+
export function removeLayoutRecord(nodeId, pane, canvas) {
|
|
27
27
|
try {
|
|
28
|
-
const current = JSON.parse(readFileSync(recordPath(nodeId), 'utf8'));
|
|
28
|
+
const current = JSON.parse(readFileSync(recordPath(nodeId, canvas), 'utf8'));
|
|
29
29
|
if (pane === undefined || current.pane === pane)
|
|
30
|
-
rmSync(recordPath(nodeId), { force: true });
|
|
30
|
+
rmSync(recordPath(nodeId, canvas), { force: true });
|
|
31
31
|
}
|
|
32
32
|
catch { /* no record */ }
|
|
33
33
|
}
|
|
@@ -12,6 +12,11 @@ import { AttachRefusedError, reconnectShouldGiveUp } from '../../../core/broker-
|
|
|
12
12
|
const RECONNECT_ACTIVE_DELAY_CAP_MS = 1_000;
|
|
13
13
|
/** Dormant by choice — low-rate patience. */
|
|
14
14
|
const RECONNECT_DORMANT_DELAY_MS = 3_000;
|
|
15
|
+
/** How long a probed connection has to answer before it is dropped and redialed. */
|
|
16
|
+
const PROBE_TIMEOUT_MS = 5_000;
|
|
17
|
+
/** The sleep check runs this often and sends nothing; a run that comes this much later than scheduled means the computer slept. */
|
|
18
|
+
const SLEEP_CHECK_MS = 5_000;
|
|
19
|
+
const SLEEP_GAP_MS = 15_000;
|
|
15
20
|
export function createReconnect(ctx, hooks) {
|
|
16
21
|
const { socket, canvasSource } = ctx;
|
|
17
22
|
let lastSocketError;
|
|
@@ -53,6 +58,18 @@ export function createReconnect(ctx, hooks) {
|
|
|
53
58
|
// `welcomed`: this session has been welcomed at least once. `refusedByRelay`: the relay closed the current connection as unavailable.
|
|
54
59
|
let welcomed = false;
|
|
55
60
|
let refusedByRelay = false;
|
|
61
|
+
// A probe went unanswered, so the close that follows is a lost connection, not a broker being replaced.
|
|
62
|
+
let connectionLost = false;
|
|
63
|
+
// A redial succeeded and its welcome has not arrived yet.
|
|
64
|
+
let awaitingRedialWelcome = false;
|
|
65
|
+
const probe = () => {
|
|
66
|
+
if (stopped || reconnecting || viewerDormant || !welcomed || hooks.isTornDown())
|
|
67
|
+
return;
|
|
68
|
+
void socket.probe(PROBE_TIMEOUT_MS).then((answered) => {
|
|
69
|
+
if (!answered)
|
|
70
|
+
connectionLost = true;
|
|
71
|
+
});
|
|
72
|
+
};
|
|
56
73
|
const sendHello = () => {
|
|
57
74
|
refusedByRelay = false;
|
|
58
75
|
socket.send({
|
|
@@ -75,8 +92,11 @@ export function createReconnect(ctx, hooks) {
|
|
|
75
92
|
const attemptReconnect = async (quiet = false) => {
|
|
76
93
|
reconnecting = true;
|
|
77
94
|
let noticed = !quiet;
|
|
95
|
+
const reconnectingNotice = connectionLost ? '↻ connection lost — reconnecting…' : '↻ node refreshing — reconnecting…';
|
|
78
96
|
if (noticed)
|
|
79
|
-
hooks.setNotice(
|
|
97
|
+
hooks.setNotice(reconnectingNotice, { sticky: true });
|
|
98
|
+
if (!quiet)
|
|
99
|
+
hooks.onReconnecting?.();
|
|
80
100
|
let delay = 200;
|
|
81
101
|
try {
|
|
82
102
|
while (!stopped && !hooks.isTornDown()) {
|
|
@@ -111,7 +131,7 @@ export function createReconnect(ctx, hooks) {
|
|
|
111
131
|
if (enteredDormancy)
|
|
112
132
|
hooks.onEnterDormancy();
|
|
113
133
|
if (noticed || !dormant) {
|
|
114
|
-
hooks.setNotice(deadOrCanceled ? `node is ${row?.status} — waiting for a revive` : dormant ? '' :
|
|
134
|
+
hooks.setNotice(deadOrCanceled ? `node is ${row?.status} — waiting for a revive` : dormant ? '' : reconnectingNotice, { sticky: !dormant });
|
|
115
135
|
noticed = !dormant;
|
|
116
136
|
}
|
|
117
137
|
try {
|
|
@@ -121,6 +141,8 @@ export function createReconnect(ctx, hooks) {
|
|
|
121
141
|
]);
|
|
122
142
|
if (!redialed || stopped || hooks.isTornDown())
|
|
123
143
|
return;
|
|
144
|
+
awaitingRedialWelcome = true;
|
|
145
|
+
connectionLost = false;
|
|
124
146
|
sendHello();
|
|
125
147
|
viewerDormant = false;
|
|
126
148
|
hooks.setNotice('');
|
|
@@ -146,10 +168,26 @@ export function createReconnect(ctx, hooks) {
|
|
|
146
168
|
};
|
|
147
169
|
const install = async () => {
|
|
148
170
|
socket.on('frame', (frame) => {
|
|
171
|
+
// The session's first welcome delivers the frames the viewer held for it, so only a later one is a reconnect.
|
|
172
|
+
const firstWelcome = !welcomed;
|
|
149
173
|
if (frame.type === 'welcome')
|
|
150
174
|
welcomed = true;
|
|
151
175
|
hooks.onFrame(frame);
|
|
176
|
+
if (frame.type === 'welcome' && awaitingRedialWelcome) {
|
|
177
|
+
awaitingRedialWelcome = false;
|
|
178
|
+
if (!firstWelcome)
|
|
179
|
+
hooks.onReconnected?.(frame.snapshot);
|
|
180
|
+
}
|
|
152
181
|
});
|
|
182
|
+
let checkedAt = Date.now();
|
|
183
|
+
const sleepCheck = setInterval(() => {
|
|
184
|
+
const now = Date.now();
|
|
185
|
+
if (now - checkedAt > SLEEP_CHECK_MS + SLEEP_GAP_MS)
|
|
186
|
+
probe();
|
|
187
|
+
checkedAt = now;
|
|
188
|
+
}, SLEEP_CHECK_MS);
|
|
189
|
+
sleepCheck.unref();
|
|
190
|
+
void stoppedSignal.then(() => clearInterval(sleepCheck));
|
|
153
191
|
socket.on('error', (err) => {
|
|
154
192
|
// Stash the reason; a 'close' follows and teardown converges there, where
|
|
155
193
|
// a broker-gone message prefers this over the generic text.
|
|
@@ -185,6 +223,7 @@ export function createReconnect(ctx, hooks) {
|
|
|
185
223
|
void attemptReconnect(true);
|
|
186
224
|
},
|
|
187
225
|
isDormant: () => viewerDormant,
|
|
226
|
+
probe,
|
|
188
227
|
lastSocketError: () => lastSocketError,
|
|
189
228
|
install,
|
|
190
229
|
stop: () => {
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// tmux viewer layout. The layout comes from the per-viewer records in session/layout-record.ts; when none
|
|
3
3
|
// exist it falls back to the nodes whose viewers the daemon logged opening in the last hour.
|
|
4
4
|
import { existsSync, statSync, openSync, readSync, closeSync } from 'node:fs';
|
|
5
|
+
import { spawnSync } from 'node:child_process';
|
|
5
6
|
import { join } from 'node:path';
|
|
6
7
|
import { routes } from '../../../api/index.js';
|
|
7
8
|
import { cliClient } from '../../../commands/api-client.js';
|
|
@@ -39,6 +40,17 @@ function recentViewOpens(now) {
|
|
|
39
40
|
}
|
|
40
41
|
return ids;
|
|
41
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
|
+
}
|
|
42
54
|
export async function recover(now = Date.now()) {
|
|
43
55
|
const client = cliClient();
|
|
44
56
|
const result = await client.request('POST', routes.reviveAll());
|
|
@@ -61,8 +73,18 @@ export async function recover(now = Date.now()) {
|
|
|
61
73
|
records.push({ nodeId, session: '', windowIndex: records.length, windowName: '', paneIndex: 0, cwd: '', pane: '' });
|
|
62
74
|
}
|
|
63
75
|
const viewed = new Set(liveViewerPanes().map((p) => p.nodeId));
|
|
76
|
+
const cloudViewed = runningCloudViewers();
|
|
64
77
|
const targets = [];
|
|
65
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
|
+
}
|
|
66
88
|
if (viewed.has(rec.nodeId) || failedIds.has(rec.nodeId)) {
|
|
67
89
|
report.skipped++;
|
|
68
90
|
continue;
|
|
@@ -86,7 +108,7 @@ export async function recover(now = Date.now()) {
|
|
|
86
108
|
for (const t of targets) {
|
|
87
109
|
const key = `${t.session}\t${t.windowIndex}`;
|
|
88
110
|
const beside = firstPane.get(key);
|
|
89
|
-
const opened = openViewerPane(t.nodeId, t.session, { name: t.windowName, cwd: t.cwd, waitForBroker:
|
|
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 }) });
|
|
90
112
|
if (opened === null) {
|
|
91
113
|
report.failed.push(`${t.nodeId}: tmux refused to open a pane`);
|
|
92
114
|
continue;
|
|
@@ -455,10 +455,12 @@ onConnected) {
|
|
|
455
455
|
// True once nothing is held any more: delivered at the first welcome, or handed to a parked node's wake path.
|
|
456
456
|
let settled = false;
|
|
457
457
|
const sendToBroker = (frame) => {
|
|
458
|
-
if (welcomed)
|
|
459
|
-
socket.send(frame);
|
|
460
|
-
else
|
|
458
|
+
if (!welcomed) {
|
|
461
459
|
heldFrames.push(frame);
|
|
460
|
+
return;
|
|
461
|
+
}
|
|
462
|
+
socket.send(frame);
|
|
463
|
+
reconnect.probe();
|
|
462
464
|
};
|
|
463
465
|
const onFirstWelcome = () => {
|
|
464
466
|
welcomed = true;
|
|
@@ -488,7 +490,7 @@ onConnected) {
|
|
|
488
490
|
if (userConfig.whip_mode)
|
|
489
491
|
whipAnimation.play();
|
|
490
492
|
},
|
|
491
|
-
onMessageSent: (text) => chatView.addPendingSend(text),
|
|
493
|
+
onMessageSent: (text, viaSocket) => chatView.addPendingSend(text, viaSocket),
|
|
492
494
|
send: sendToBroker,
|
|
493
495
|
frecency,
|
|
494
496
|
});
|
|
@@ -672,8 +674,8 @@ onConnected) {
|
|
|
672
674
|
(observer ? ' --observer' : '') +
|
|
673
675
|
(canvasName !== undefined ? ` --canvas ${quoteIfNeeded(canvasName)}` : ''),
|
|
674
676
|
tagPane: paneTag.pane,
|
|
675
|
-
forgetLayout: () => { if (
|
|
676
|
-
removeLayoutRecord(ctx.nodeId, paneTag.pane()); },
|
|
677
|
+
forgetLayout: () => { if (ctx.nodeId !== '')
|
|
678
|
+
removeLayoutRecord(ctx.nodeId, paneTag.pane(), canvasName); },
|
|
677
679
|
});
|
|
678
680
|
const teardown = lifecycle.teardown;
|
|
679
681
|
let startupFailure;
|
|
@@ -701,10 +703,17 @@ onConnected) {
|
|
|
701
703
|
chatView.settleRun();
|
|
702
704
|
sync.patchLocal({ isStreaming: false });
|
|
703
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
|
+
},
|
|
704
713
|
});
|
|
705
714
|
paneTag.set();
|
|
706
|
-
if (
|
|
707
|
-
writeLayoutRecord(ctx.nodeId, paneTag.pane(), meta.cwd);
|
|
715
|
+
if (ctx.nodeId !== '')
|
|
716
|
+
writeLayoutRecord(ctx.nodeId, paneTag.pane(), meta.cwd, canvasName);
|
|
708
717
|
// 5. Lay out and paint; the broker connection follows (`dialBroker`).
|
|
709
718
|
layout.mount();
|
|
710
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.
|
|
@@ -811,8 +820,9 @@ onConnected) {
|
|
|
811
820
|
setPaneFocused: (focused) => {
|
|
812
821
|
if (focused) {
|
|
813
822
|
paneTag.stamp();
|
|
814
|
-
if (
|
|
815
|
-
writeLayoutRecord(ctx.nodeId, paneTag.pane(), meta.cwd);
|
|
823
|
+
if (ctx.nodeId !== '')
|
|
824
|
+
writeLayoutRecord(ctx.nodeId, paneTag.pane(), meta.cwd, canvasName);
|
|
825
|
+
reconnect.probe();
|
|
816
826
|
}
|
|
817
827
|
paneFocus.setPaneFocused(focused);
|
|
818
828
|
tui.requestRender();
|
|
@@ -902,6 +912,7 @@ onConnected) {
|
|
|
902
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.
|
|
903
913
|
// An engine command (`/x`, `!x`) is refused as a later parked submission is, and returned to the editor.
|
|
904
914
|
settled = true;
|
|
915
|
+
chatView.stopResendingPendingSends();
|
|
905
916
|
const refused = [];
|
|
906
917
|
for (const frame of heldFrames.splice(0)) {
|
|
907
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');
|
|
@@ -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);
|