@north-light/cli 0.3.699 → 0.3.700
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/client.d.ts +4 -0
- package/dist/api/client.js +1 -1
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/nodes.d.ts +2 -0
- package/dist/api/routes.d.ts +1 -0
- package/dist/api/routes.js +1 -1
- package/dist/clients/attach/viewer.js +4 -4
- package/dist/commands/node/inspect.js +6 -6
- package/dist/commands/node-lifecycle-revive.d.ts +2 -10
- package/dist/commands/node-lifecycle-revive.js +1 -1
- package/dist/core/canvas/status-glyph.d.ts +9 -0
- package/dist/core/canvas/status-glyph.js +1 -1
- package/dist/core/command-plugins/compose.js +1 -1
- package/dist/core/command.js +8 -8
- package/dist/core/graph/names.d.ts +1 -1
- package/dist/core/graph/names.js +10 -10
- package/dist/core/help.js +2 -2
- package/dist/core/permissions/ceiling.d.ts +1 -1
- package/dist/core/permissions/evaluator.d.ts +4 -6
- package/dist/core/permissions/evaluator.js +2 -2
- package/dist/core/runtime/broker/client-registry.d.ts +2 -2
- package/dist/core/runtime/broker/client-registry.js +1 -1
- package/dist/core/runtime/broker-protocol.d.ts +8 -10
- package/dist/core/runtime/broker-protocol.js +3 -3
- package/dist/core/runtime/broker-wedge.d.ts +20 -0
- package/dist/core/runtime/broker-wedge.js +2 -0
- package/dist/core/runtime/broker.js +1 -1
- package/dist/core/runtime/host.js +3 -3
- package/dist/core/runtime/runner/machine/call.js +1 -1
- package/dist/core/runtime/runner/machine/executor.js +1 -1
- package/dist/core/runtime/runner/machine/machine-executor.test.js +2 -2
- package/dist/core/runtime/runner/machine/ops.d.ts +1 -14
- package/dist/core/runtime/runner/machine/ops.js +1 -1
- package/dist/core/substrate/delivery/corpus.js +2 -2
- package/dist/daemon/api/handlers/nodes.js +1 -1
- package/dist/daemon/api/handlers/objects.js +3 -3
- package/dist/daemon/api/map.js +2 -2
- package/dist/daemon/api/operations.js +1 -1
- package/dist/daemon/machine-daemon.js +1 -1
- package/dist/daemon/machine-link/client.d.ts +14 -2
- package/dist/daemon/machine-link/client.js +1 -1
- package/dist/daemon/machine-link/frames.d.ts +38 -0
- package/dist/daemon/machine-link/frames.js +1 -1
- package/dist/daemon/machine-link/holder.d.ts +8 -0
- package/dist/daemon/machine-link/holder.js +5 -4
- package/dist/daemon/machine-supervision.d.ts +17 -0
- package/dist/daemon/machine-supervision.js +1 -0
- package/dist/daemon/reconcilers/broker-supervision.d.ts +11 -14
- package/dist/daemon/reconcilers/broker-supervision.js +3 -4
- package/dist/daemon/reconcilers/node-lifecycle/tick.js +1 -1
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/client.js +4 -0
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/api/routes.js +1 -0
- package/packages/crouter-api/dist/clients/attach/viewer.js +1 -1
- package/packages/crouter-api/dist/commands/node/inspect.js +2 -1
- package/packages/crouter-api/dist/commands/node-lifecycle-revive.js +14 -16
- package/packages/crouter-api/dist/core/canvas/status-glyph.js +15 -0
- package/packages/crouter-api/dist/core/command-plugins/compose.js +5 -0
- package/packages/crouter-api/dist/core/command.js +13 -1
- package/packages/crouter-api/dist/core/graph/names.js +7 -8
- package/packages/crouter-api/dist/core/help.js +1 -1
- package/packages/crouter-api/dist/core/permissions/ceiling.js +1 -1
- package/packages/crouter-api/dist/core/permissions/evaluator.js +20 -12
- package/packages/crouter-api/dist/core/runtime/broker-protocol.js +26 -12
- package/packages/crouter-api/dist/core/runtime/broker-wedge.js +99 -0
- package/packages/crouter-api/dist/core/runtime/host.js +10 -3
- package/packages/crouter-api/dist/core/runtime/runner/machine/call.js +1 -1
- package/packages/crouter-api/dist/core/runtime/runner/machine/ops.js +1 -1
- package/packages/crouter-api/dist/core/substrate/delivery/corpus.js +3 -3
- package/packages/crouter-api/dist/daemon/api/map.js +2 -0
- package/packages/crouter-api/dist/daemon/api/operations.js +1 -0
- package/packages/crouter-api/dist/daemon/machine-link/frames.js +4 -0
- package/packages/crouter-api/dist/daemon/machine-link/holder.js +63 -1
- package/packages/crouter-api/dist/daemon/reconcilers/broker-supervision.js +61 -163
- 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/dist/daemon/reconcilers/node-lifecycle/machine-sweep.d.ts +0 -5
- package/dist/daemon/reconcilers/node-lifecycle/machine-sweep.js +0 -4
|
@@ -17,13 +17,31 @@
|
|
|
17
17
|
// follow pi.
|
|
18
18
|
import { StringDecoder } from 'node:string_decoder';
|
|
19
19
|
// Client → broker frames
|
|
20
|
-
/**
|
|
21
|
-
export const
|
|
22
|
-
/** Invalid requests preserve the complete welcome; valid requests are capped. */
|
|
20
|
+
/** The welcome holds at most the last SNAPSHOT_TAIL messages; older ones are read with `crtr canvas read`. */
|
|
21
|
+
export const SNAPSHOT_TAIL = 100;
|
|
23
22
|
export function normalizeSnapshotTail(value) {
|
|
24
23
|
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1)
|
|
25
|
-
return
|
|
26
|
-
return Math.min(value,
|
|
24
|
+
return SNAPSHOT_TAIL;
|
|
25
|
+
return Math.min(value, SNAPSHOT_TAIL);
|
|
26
|
+
}
|
|
27
|
+
export function toolCallIds(messages) {
|
|
28
|
+
const ids = new Set();
|
|
29
|
+
for (const message of messages) {
|
|
30
|
+
if (message.role !== 'assistant' || !Array.isArray(message.content))
|
|
31
|
+
continue;
|
|
32
|
+
for (const part of message.content) {
|
|
33
|
+
if (part?.type === 'toolCall' && typeof part.id === 'string')
|
|
34
|
+
ids.add(part.id);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return ids;
|
|
38
|
+
}
|
|
39
|
+
/** A welcome carries no image bytes: each image part becomes one line of text. */
|
|
40
|
+
export function withoutImages(message, nodeId) {
|
|
41
|
+
const content = message.content;
|
|
42
|
+
if (!Array.isArray(content) || !content.some((part) => part?.type === 'image'))
|
|
43
|
+
return message;
|
|
44
|
+
return { ...message, content: content.map((part) => part?.type === 'image' ? { type: 'text', text: `[image omitted; crtr canvas read ${nodeId}]` } : part) };
|
|
27
45
|
}
|
|
28
46
|
// Newline-delimited JSON codec (the framing pi solves with `jsonl`, reproduced
|
|
29
47
|
// locally so the protocol module owns no transport dependency)
|
|
@@ -48,14 +66,10 @@ export class FrameOverflowError extends Error {
|
|
|
48
66
|
this.name = 'FrameOverflowError';
|
|
49
67
|
}
|
|
50
68
|
}
|
|
51
|
-
/** Caps the CLIENT uses reading BROKER frames
|
|
52
|
-
* full message history and can be many MiB, so these are generous. Covers
|
|
53
|
-
* realistic long sessions; snapshot CHUNKING is deferred — the long-lived
|
|
54
|
-
* broker makes a big welcome a realistic, not pathological, trigger, but the
|
|
55
|
-
* fixed cap is accepted. */
|
|
69
|
+
/** Caps the CLIENT uses reading BROKER frames: the broker drops a viewer past 32 MiB pending. */
|
|
56
70
|
export const CLIENT_READ_CAPS = {
|
|
57
|
-
maxLineBytes:
|
|
58
|
-
maxTotalBytes:
|
|
71
|
+
maxLineBytes: 32 * 1024 * 1024,
|
|
72
|
+
maxTotalBytes: 32 * 1024 * 1024,
|
|
59
73
|
};
|
|
60
74
|
/** Caps the BROKER uses reading CLIENT frames. Sized so an image-paste frame
|
|
61
75
|
* fits: a resizeImage-bounded PNG's base64 is a few MiB and would clip a
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
// src/core/runtime/broker-wedge.ts — the stuck-turn and stalled-refresh rules for a broker, shared by the daemon that holds the process:
|
|
2
|
+
// the control plane's supervision for its own brokers and a Mac's machine daemon for the brokers it runs.
|
|
3
|
+
import { execFile } from 'node:child_process';
|
|
4
|
+
import { promisify } from 'node:util';
|
|
5
|
+
const execFileAsync = promisify(execFile);
|
|
6
|
+
export const YIELD_STALL_GRACE_MS = 3 * 60_000;
|
|
7
|
+
export const KILL_ESCALATE_MS = 20_000;
|
|
8
|
+
export const WEDGE_QUIET_MS = 20 * 60_000;
|
|
9
|
+
export const WEDGE_CPU_MAX_PERCENT = 2;
|
|
10
|
+
export function yieldStallVerdict(piPidAlive, intent, busy, stalledFor) {
|
|
11
|
+
if (piPidAlive !== true)
|
|
12
|
+
return 'leave';
|
|
13
|
+
if (intent !== 'refresh')
|
|
14
|
+
return 'leave';
|
|
15
|
+
if (busy)
|
|
16
|
+
return 'leave';
|
|
17
|
+
if (stalledFor === null || stalledFor < YIELD_STALL_GRACE_MS)
|
|
18
|
+
return 'pending';
|
|
19
|
+
return 'kill';
|
|
20
|
+
}
|
|
21
|
+
export function wedgeVerdict(input) {
|
|
22
|
+
if (!input.busy)
|
|
23
|
+
return 'leave';
|
|
24
|
+
if (input.quietForMs === null || input.quietForMs < WEDGE_QUIET_MS)
|
|
25
|
+
return 'leave';
|
|
26
|
+
if (input.cpuPercent === null)
|
|
27
|
+
return 'pending';
|
|
28
|
+
if (input.hasDescendants !== false && input.cpuPercent > WEDGE_CPU_MAX_PERCENT)
|
|
29
|
+
return 'pending';
|
|
30
|
+
return 'wedged';
|
|
31
|
+
}
|
|
32
|
+
function parsePsTree(psOutput) {
|
|
33
|
+
const byPid = new Map();
|
|
34
|
+
const childrenOf = new Map();
|
|
35
|
+
for (const line of psOutput.split('\n')) {
|
|
36
|
+
const trimmed = line.trim();
|
|
37
|
+
if (trimmed === '')
|
|
38
|
+
continue;
|
|
39
|
+
const parts = trimmed.split(/\s+/);
|
|
40
|
+
if (parts.length < 3)
|
|
41
|
+
continue;
|
|
42
|
+
const pid = Number(parts[0]);
|
|
43
|
+
const ppid = Number(parts[1]);
|
|
44
|
+
const pcpu = Number(parts[2]);
|
|
45
|
+
if (!Number.isFinite(pid) || !Number.isFinite(ppid) || !Number.isFinite(pcpu))
|
|
46
|
+
continue;
|
|
47
|
+
byPid.set(pid, pcpu);
|
|
48
|
+
const siblings = childrenOf.get(ppid);
|
|
49
|
+
if (siblings === undefined)
|
|
50
|
+
childrenOf.set(ppid, [pid]);
|
|
51
|
+
else
|
|
52
|
+
siblings.push(pid);
|
|
53
|
+
}
|
|
54
|
+
return { byPid, childrenOf };
|
|
55
|
+
}
|
|
56
|
+
export function sumTreeCpu(psOutput, rootPid) {
|
|
57
|
+
const { byPid, childrenOf } = parsePsTree(psOutput);
|
|
58
|
+
if (!byPid.has(rootPid))
|
|
59
|
+
return null;
|
|
60
|
+
let total = 0;
|
|
61
|
+
const stack = [rootPid];
|
|
62
|
+
const seen = new Set();
|
|
63
|
+
while (stack.length > 0) {
|
|
64
|
+
const pid = stack.pop();
|
|
65
|
+
if (seen.has(pid))
|
|
66
|
+
continue;
|
|
67
|
+
seen.add(pid);
|
|
68
|
+
total += byPid.get(pid) ?? 0;
|
|
69
|
+
const kids = childrenOf.get(pid);
|
|
70
|
+
if (kids !== undefined)
|
|
71
|
+
stack.push(...kids);
|
|
72
|
+
}
|
|
73
|
+
return total;
|
|
74
|
+
}
|
|
75
|
+
export function treeHasDescendants(psOutput, rootPid) {
|
|
76
|
+
const { byPid, childrenOf } = parsePsTree(psOutput);
|
|
77
|
+
if (!byPid.has(rootPid))
|
|
78
|
+
return null;
|
|
79
|
+
return (childrenOf.get(rootPid) ?? []).length > 0;
|
|
80
|
+
}
|
|
81
|
+
/** One `ps` sample of a broker's process tree: its summed CPU and whether it has any subprocess; null when it cannot be read. */
|
|
82
|
+
export async function sampleBrokerTree(pid) {
|
|
83
|
+
try {
|
|
84
|
+
const { stdout } = await execFileAsync('ps', ['-ax', '-o', 'pid=,ppid=,pcpu='], {
|
|
85
|
+
encoding: 'utf8',
|
|
86
|
+
timeout: 2000,
|
|
87
|
+
});
|
|
88
|
+
if (typeof stdout !== 'string')
|
|
89
|
+
return null;
|
|
90
|
+
const cpuPercent = sumTreeCpu(stdout, pid);
|
|
91
|
+
const hasDescendants = treeHasDescendants(stdout, pid);
|
|
92
|
+
if (cpuPercent === null || hasDescendants === null)
|
|
93
|
+
return null;
|
|
94
|
+
return { cpuPercent, hasDescendants };
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
@@ -29,7 +29,7 @@ import { readConfig, readMergedLaunchConfig } from '../config.js';
|
|
|
29
29
|
import { loadRotationConfig } from '../subscription-state.js';
|
|
30
30
|
import { getNode } from '../canvas/index.js';
|
|
31
31
|
import { withCanvasWrite } from '../canvas/db.js';
|
|
32
|
-
import { requestExecutionStop, setExecutionLaunchJson } from '../canvas/executions.js';
|
|
32
|
+
import { liveExecutionForNode, requestExecutionStop, setExecutionLaunchJson } from '../canvas/executions.js';
|
|
33
33
|
import { scopesFilePath, crtrHome, nodeRunDir, nodeRunJobDir, jobDir, viewSocketPath, nodeAgentDir, contextDir, nodeHome } from '../canvas/paths.js';
|
|
34
34
|
import { encodeFrame } from './broker-protocol.js';
|
|
35
35
|
import { buildBrokerEnv } from './spawn-env-rows.js';
|
|
@@ -328,7 +328,14 @@ export async function requestBrokerTeardown(nodeId, opts = {}, after) {
|
|
|
328
328
|
let prepared;
|
|
329
329
|
try {
|
|
330
330
|
await requestExecutionStop(nodeId, { afterTurn: opts.startAfter !== undefined, reason: opts.reason ?? 'teardown' });
|
|
331
|
-
|
|
331
|
+
// A Mac broker is not in this host's process table: its machine stops it, by the execution the row names.
|
|
332
|
+
const execution = await liveExecutionForNode(nodeId);
|
|
333
|
+
if (execution?.runner === 'machine') {
|
|
334
|
+
const { runnerForExecution } = await import('./runner/index.js');
|
|
335
|
+
prepared = { machine: () => runnerForExecution('machine').stop(execution, { reason: opts.reason ?? 'teardown' }) };
|
|
336
|
+
}
|
|
337
|
+
else
|
|
338
|
+
prepared = await prepareBrokerTeardown(nodeId, opts);
|
|
332
339
|
}
|
|
333
340
|
catch (error) {
|
|
334
341
|
const failure = { confirmed: false, error: error instanceof Error ? error : new Error(String(error)) };
|
|
@@ -337,7 +344,7 @@ export async function requestBrokerTeardown(nodeId, opts = {}, after) {
|
|
|
337
344
|
}
|
|
338
345
|
return await new Promise((resolve) => {
|
|
339
346
|
const run = () => {
|
|
340
|
-
void runPreparedBrokerTeardown(prepared).then(async (result) => {
|
|
347
|
+
void ('machine' in prepared ? prepared.machine() : runPreparedBrokerTeardown(prepared)).then(async (result) => {
|
|
341
348
|
if (result.confirmed) {
|
|
342
349
|
if (after !== undefined) {
|
|
343
350
|
try {
|
|
@@ -11,7 +11,7 @@ import { MachineCallFailedError, MachineLostError, MachineOfflineError } from '.
|
|
|
11
11
|
/** Seconds a caller waits: `start` 60, every other op 15 (design). The `worktree.*` ops run Git under a repository lock that waits up to
|
|
12
12
|
* 25 s, so they get 60 too (`worktree.finalize` also asks origin, bounded at 10 s). */
|
|
13
13
|
export const MACHINE_CALL_TIMEOUT_S = {
|
|
14
|
-
start: 60, wake: 15, stop: 15, status: 15,
|
|
14
|
+
start: 60, wake: 15, stop: 15, status: 15, delete: 15, viewer: 15, 'cron.run': 15, 'cron.cancel': 15, 'job.stop': 15,
|
|
15
15
|
'worktree.create': 60, 'worktree.rollback': 60, 'worktree.close': 60, 'worktree.abandon': 60, 'worktree.finalize': 60,
|
|
16
16
|
'repo.identify': 15,
|
|
17
17
|
};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export const MACHINE_OPS = ['start', 'wake', 'stop', 'status', '
|
|
1
|
+
export const MACHINE_OPS = ['start', 'wake', 'stop', 'status', 'delete', 'viewer', 'cron.run', 'cron.cancel', 'job.stop',
|
|
2
2
|
'worktree.create', 'worktree.rollback', 'worktree.close', 'worktree.abandon', 'worktree.finalize', 'repo.identify'];
|
|
3
3
|
/** No live link row for the environment: the caller leaves its work pending and retries on its own backoff. */
|
|
4
4
|
export class MachineOfflineError extends Error {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/** The documents delivery may consider for one reader: every document carrying a rule for the activity (or, at boot, owned by the node)
|
|
2
2
|
* whose owner is in the reader's view and that the reader's `permits(read)` admits inside the query. The view also ranks names and caps
|
|
3
3
|
* owners. */
|
|
4
|
-
import { permits, resolveReader } from '../../permissions/evaluator.js';
|
|
4
|
+
import { permits, resolveReader, shareReads } from '../../permissions/evaluator.js';
|
|
5
5
|
import { get as getBody, getMany as getBodies } from '../../graph/bodies.js';
|
|
6
6
|
import { resolveName, viewOf, viewResolutions } from '../../graph/names.js';
|
|
7
7
|
import { rulesOn, rulesOfMany } from '../../graph/rules.js';
|
|
@@ -46,7 +46,7 @@ const sharing = new WeakSet();
|
|
|
46
46
|
const shared = new WeakMap();
|
|
47
47
|
/** Make every document, head, rule, name and body read this reader's deliveries make run once per distinct input. Only for a reader built for one
|
|
48
48
|
* render that writes no documents while it lives: the answers are those of the first read, whatever changes after. */
|
|
49
|
-
export function shareCorpusReads(reader) { sharing.add(reader); }
|
|
49
|
+
export function shareCorpusReads(reader) { sharing.add(shareReads(reader)); }
|
|
50
50
|
function once(reader, key, load) {
|
|
51
51
|
if (!sharing.has(reader))
|
|
52
52
|
return load();
|
|
@@ -70,8 +70,8 @@ function corpusScope(db, reader) {
|
|
|
70
70
|
let scope = scopes.get(reader);
|
|
71
71
|
if (scope === undefined) {
|
|
72
72
|
scope = (async () => {
|
|
73
|
-
const view = await viewOf(db, reader);
|
|
74
73
|
const ev = await resolveReader(db, reader);
|
|
74
|
+
const view = await viewOf(db, reader, ev);
|
|
75
75
|
return { reader, context: { view, ev }, read: await permits(db, ev, 'read', 'o'), manifest: await readerManifest(db, reader) };
|
|
76
76
|
})();
|
|
77
77
|
scopes.set(reader, scope);
|
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
// reasonable projections; this module is what makes them concrete, so any DTO
|
|
11
11
|
// field that projection proves wrong is corrected here at the source.
|
|
12
12
|
import { join } from 'node:path';
|
|
13
|
+
import { liveExecutionForNode } from '../../core/canvas/executions.js';
|
|
13
14
|
import { readOutputResult } from '../../core/runtime/output-result.js';
|
|
14
15
|
import { ReviewOperationError as ReviewOperationErrorClass } from '../../core/review/types.js';
|
|
15
16
|
import { cronSinkDisplay } from '../../core/canvas/crons.js';
|
|
@@ -260,6 +261,7 @@ export async function toNodeDetailDTO(meta, edges) {
|
|
|
260
261
|
terminal_reason: meta.terminal_reason ?? null,
|
|
261
262
|
pi_pid: meta.pi_pid ?? null,
|
|
262
263
|
pi_pid_identity: meta.pi_pid_identity ?? null,
|
|
264
|
+
runner: (await liveExecutionForNode(meta.node_id))?.runner ?? null,
|
|
263
265
|
window: meta.window ?? null,
|
|
264
266
|
tmux_session: meta.tmux_session ?? null,
|
|
265
267
|
pane: meta.pane ?? null,
|
|
@@ -165,6 +165,7 @@ export const OPERATIONS = [
|
|
|
165
165
|
{ name: 'nodes.get.94', method: 'GET', path: '/v1/nodes/:id/context', classes: ['person', 'broker', 'cron'], resource: 'node-read' },
|
|
166
166
|
{ name: 'nodes.post.96', method: 'POST', path: '/v1/nodes/:id/fork', classes: ['person', 'broker'], resource: 'node-write', scope: 'crtr:act' },
|
|
167
167
|
{ name: 'nodes.post.97', method: 'POST', path: '/v1/nodes/:id/revive', classes: ['person', 'broker'], resource: 'node-write', scope: 'crtr:act' },
|
|
168
|
+
{ name: 'nodes.post.kick', method: 'POST', path: '/v1/nodes/:id/kick', classes: ['person', 'broker'], resource: 'node-write', scope: 'crtr:act' },
|
|
168
169
|
{ name: 'nodes.post.98', method: 'POST', path: '/v1/nodes/:id/relaunch-root', classes: ['person', 'broker'], resource: 'node-write', scope: 'crtr:act' },
|
|
169
170
|
{ name: 'nodes.post.99', method: 'POST', path: '/v1/nodes/:id/close', classes: ['person', 'broker'], resource: 'node-write', scope: 'crtr:act' },
|
|
170
171
|
{ name: 'nodes.post.read', method: 'POST', path: '/v1/nodes/:id/read', classes: ['person'], resource: 'node-write', scope: 'crtr:act' },
|
|
@@ -15,6 +15,10 @@ export function parseFrame(data) {
|
|
|
15
15
|
case 'result': return strings('call_id') && (frame['ok'] === true || (frame['ok'] === false && strings('error'))) ? frame : null;
|
|
16
16
|
case 'exit': return strings('execution', 'node') && nullableNumber(frame['code']) && (frame['signal'] === null || typeof frame['signal'] === 'string') ? frame : null;
|
|
17
17
|
case 'job.report': return strings('id', 'node', 'job') && typeof frame['request'] === 'object' && frame['request'] !== null ? frame : null;
|
|
18
|
+
case 'running': return Array.isArray(frame['executions']) && frame['executions'].every((e) => typeof e === 'string') ? frame : null;
|
|
19
|
+
case 'turns': return strings('id') && Array.isArray(frame['brokers']) && frame['brokers'].every((b) => typeof b === 'object' && b !== null && typeof b.execution === 'string' && typeof b.node === 'string') ? frame : null;
|
|
20
|
+
case 'turns.answer': return strings('id') && typeof frame['turns'] === 'object' && frame['turns'] !== null ? frame : null;
|
|
21
|
+
case 'wedge': return strings('execution', 'node') && typeof frame['since'] === 'number' && typeof frame['quiet_ms'] === 'number' ? frame : null;
|
|
18
22
|
case 'job.reported': return strings('id') ? frame : null;
|
|
19
23
|
case 'view.open': return strings('channel', 'node') ? frame : null;
|
|
20
24
|
case 'view.ready':
|
|
@@ -12,7 +12,13 @@ import { randomUUID } from 'node:crypto';
|
|
|
12
12
|
import { WebSocket, WebSocketServer } from 'ws';
|
|
13
13
|
import { openDb } from '../../core/canvas/db.js';
|
|
14
14
|
import { emitEvent } from '../../core/events/emit.js';
|
|
15
|
-
import { endExecution, recordExecutionExit } from '../../core/canvas/executions.js';
|
|
15
|
+
import { endExecution, liveExecutionForNode, recordExecutionExit } from '../../core/canvas/executions.js';
|
|
16
|
+
import { getNode } from '../../core/canvas/index.js';
|
|
17
|
+
import { fullName } from '../../core/canvas/labels.js';
|
|
18
|
+
import { readLiveTurn } from '../../core/canvas/recovery.js';
|
|
19
|
+
import { runningJobs } from '../../core/graph/jobs.js';
|
|
20
|
+
import { readSupervisionMark, writeSupervisionMark } from '../park-pending.js';
|
|
21
|
+
import { reportWedge, wedgeLabel } from '../reconcilers/broker-supervision.js';
|
|
16
22
|
import { machineEnvironmentOfNode } from '../../core/runtime/runner/machine/runner.js';
|
|
17
23
|
import { storeJobReport } from '../api/handlers/bash-jobs.js';
|
|
18
24
|
import { APIError } from '../../api/errors.js';
|
|
@@ -46,6 +52,7 @@ export class HeldLink extends EventEmitter {
|
|
|
46
52
|
claiming = false;
|
|
47
53
|
closed = false;
|
|
48
54
|
alive = true;
|
|
55
|
+
openedAt = new Date().toISOString();
|
|
49
56
|
channels = new Map();
|
|
50
57
|
constructor(environmentId, generation, ws, token) {
|
|
51
58
|
super();
|
|
@@ -167,9 +174,20 @@ export class HeldLink extends EventEmitter {
|
|
|
167
174
|
case 'exit':
|
|
168
175
|
await recordMachineBrokerExit(this.environmentId, frame);
|
|
169
176
|
return;
|
|
177
|
+
case 'running':
|
|
178
|
+
if (!await this.isCurrentGeneration())
|
|
179
|
+
return;
|
|
180
|
+
await endUnlistedMachineExecutions(this.environmentId, new Set(frame.executions), this.openedAt);
|
|
181
|
+
return;
|
|
170
182
|
case 'job.report':
|
|
171
183
|
await this.storeJobReport(frame);
|
|
172
184
|
return;
|
|
185
|
+
case 'turns':
|
|
186
|
+
this.send({ type: 'turns.answer', id: frame.id, turns: await this.turns(frame.brokers) });
|
|
187
|
+
return;
|
|
188
|
+
case 'wedge':
|
|
189
|
+
await this.recordWedge(frame);
|
|
190
|
+
return;
|
|
173
191
|
case 'view.ready':
|
|
174
192
|
this.channels.get(frame.channel)?.emit('connect');
|
|
175
193
|
return;
|
|
@@ -197,6 +215,40 @@ export class HeldLink extends EventEmitter {
|
|
|
197
215
|
this.send({ type: 'job.reported', id: frame.id, error: { status: known ? error.status : 500, code: known ? error.code : 'internal_error', message: error.message } });
|
|
198
216
|
}
|
|
199
217
|
}
|
|
218
|
+
/** The node row of a broker this machine runs, when that broker is the node's live execution and the node runs in this link's environment. */
|
|
219
|
+
async ownNode(execution, node) {
|
|
220
|
+
if (typeof node !== 'string' || await machineEnvironmentOfNode(node) !== this.environmentId || (await liveExecutionForNode(node))?.executionId !== execution)
|
|
221
|
+
return null;
|
|
222
|
+
return await getNode(node);
|
|
223
|
+
}
|
|
224
|
+
/** The turn state the Mac's stuck-turn check needs, for each of its brokers that is its node's live execution. A turn's progress from before the node's
|
|
225
|
+
* latest launch is not this broker's, so it reads as no open turn. */
|
|
226
|
+
async turns(brokers) {
|
|
227
|
+
const turns = {};
|
|
228
|
+
for (const { execution, node } of brokers) {
|
|
229
|
+
const row = await this.ownNode(execution, node);
|
|
230
|
+
if (row === null)
|
|
231
|
+
continue;
|
|
232
|
+
const turn = await readLiveTurn(node);
|
|
233
|
+
const since = turn?.busy === true && turn.progressAt !== null ? Date.parse(turn.progressAt) : Number.NaN;
|
|
234
|
+
const launched = Date.parse(row.launched_at ?? '');
|
|
235
|
+
turns[execution] = { since: Number.isFinite(since) && Number.isFinite(launched) && since >= launched ? since : null, refresh: row.intent === 'refresh', jobs: (await runningJobs(await openDb(), node)).length > 0 };
|
|
236
|
+
}
|
|
237
|
+
return turns;
|
|
238
|
+
}
|
|
239
|
+
/** A stuck turn the Mac found: recorded and announced once per turn, as for a broker this control plane runs. */
|
|
240
|
+
async recordWedge(frame) {
|
|
241
|
+
const row = await this.ownNode(frame.execution, frame.node);
|
|
242
|
+
if (row === null || await readSupervisionMark(frame.node, 'wedge_noticed_at') === frame.since)
|
|
243
|
+
return;
|
|
244
|
+
await writeSupervisionMark(frame.node, 'wedge_noticed_at', frame.since);
|
|
245
|
+
const hasDescendants = frame.has_descendants ?? true;
|
|
246
|
+
await reportWedge(frame.node, {
|
|
247
|
+
quietForMs: frame.quiet_ms, cpuPercent: frame.cpu_percent, hasDescendants: frame.has_descendants, kickAttempted: frame.kick_attempted, kicked: frame.kicked,
|
|
248
|
+
kickSuppressionReason: null, pid: null,
|
|
249
|
+
label: wedgeLabel(`${fullName(row)} (${frame.node})`, Math.round(frame.quiet_ms / 60_000), hasDescendants, false, frame.kicked),
|
|
250
|
+
});
|
|
251
|
+
}
|
|
200
252
|
async teardown() {
|
|
201
253
|
if (this.closed)
|
|
202
254
|
return;
|
|
@@ -244,6 +296,16 @@ export async function recordMachineBrokerExit(environmentId, exit) {
|
|
|
244
296
|
emitEvent({ level: 'info', event: 'broker.exit.reported', node_id: exit.node, fields: { environment: environmentId, code: exit.code, signal: exit.signal } });
|
|
245
297
|
return true;
|
|
246
298
|
}
|
|
299
|
+
/** The Mac's list of its running brokers, sent at each link open: every `running` execution of this environment it does not list exited
|
|
300
|
+
* while no link carried its `exit` frame, and is ended as one. Only an execution started before this link opened is judged: a call sent on
|
|
301
|
+
* this link may have started one after the Mac's scan. A node held by an import is left to the import. */
|
|
302
|
+
async function endUnlistedMachineExecutions(environmentId, listed, openedAt) {
|
|
303
|
+
const rows = await (await openDb()).prepare(`SELECT x.execution_id, x.node_id FROM executions x JOIN nodes n ON n.node_id = x.node_id JOIN profiles p ON p.id = n.profile_id
|
|
304
|
+
WHERE x.state = 'running' AND x.runner = 'machine' AND p.environment_id = ? AND x.started_at < ?`).all(environmentId, openedAt);
|
|
305
|
+
for (const row of rows)
|
|
306
|
+
if (!listed.has(row.execution_id))
|
|
307
|
+
await recordMachineBrokerExit(environmentId, { execution: row.execution_id, node: row.node_id, code: null, signal: null });
|
|
308
|
+
}
|
|
247
309
|
/** A viewer channel to one node's view.sock on the Mac, as the relay's broker-side link. */
|
|
248
310
|
export class MachineViewLink extends EventEmitter {
|
|
249
311
|
link;
|