@north-light/cli 0.3.698 → 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.
Files changed (93) hide show
  1. package/dist/api/client.d.ts +4 -0
  2. package/dist/api/client.js +1 -1
  3. package/dist/api/contract.d.ts +1 -1
  4. package/dist/api/contract.js +1 -1
  5. package/dist/api/dto/nodes.d.ts +2 -0
  6. package/dist/api/routes.d.ts +1 -0
  7. package/dist/api/routes.js +1 -1
  8. package/dist/clients/attach/input/controller.d.ts +3 -0
  9. package/dist/clients/attach/input/controller.js +3 -3
  10. package/dist/clients/attach/render/chat-view.d.ts +12 -0
  11. package/dist/clients/attach/render/chat-view.js +2 -2
  12. package/dist/clients/attach/session/input-wiring.d.ts +2 -0
  13. package/dist/clients/attach/session/input-wiring.js +1 -1
  14. package/dist/clients/attach/viewer.js +289 -289
  15. package/dist/commands/node/inspect.js +6 -6
  16. package/dist/commands/node-lifecycle-revive.d.ts +2 -10
  17. package/dist/commands/node-lifecycle-revive.js +1 -1
  18. package/dist/core/canvas/status-glyph.d.ts +9 -0
  19. package/dist/core/canvas/status-glyph.js +1 -1
  20. package/dist/core/command-plugins/compose.js +1 -1
  21. package/dist/core/command.js +8 -8
  22. package/dist/core/feed/messages.js +4 -4
  23. package/dist/core/graph/names.d.ts +1 -1
  24. package/dist/core/graph/names.js +10 -10
  25. package/dist/core/help.js +2 -2
  26. package/dist/core/permissions/ceiling.d.ts +1 -1
  27. package/dist/core/permissions/evaluator.d.ts +4 -6
  28. package/dist/core/permissions/evaluator.js +2 -2
  29. package/dist/core/runtime/broker/client-registry.d.ts +2 -2
  30. package/dist/core/runtime/broker/client-registry.js +1 -1
  31. package/dist/core/runtime/broker-protocol.d.ts +8 -10
  32. package/dist/core/runtime/broker-protocol.js +3 -3
  33. package/dist/core/runtime/broker-wedge.d.ts +20 -0
  34. package/dist/core/runtime/broker-wedge.js +2 -0
  35. package/dist/core/runtime/broker.js +1 -1
  36. package/dist/core/runtime/host.js +3 -3
  37. package/dist/core/runtime/runner/machine/call.js +1 -1
  38. package/dist/core/runtime/runner/machine/executor.js +1 -1
  39. package/dist/core/runtime/runner/machine/machine-executor.test.js +2 -2
  40. package/dist/core/runtime/runner/machine/ops.d.ts +1 -14
  41. package/dist/core/runtime/runner/machine/ops.js +1 -1
  42. package/dist/core/substrate/delivery/corpus.js +2 -2
  43. package/dist/daemon/api/handlers/nodes.js +1 -1
  44. package/dist/daemon/api/handlers/objects.js +3 -3
  45. package/dist/daemon/api/map.js +2 -2
  46. package/dist/daemon/api/operations.js +1 -1
  47. package/dist/daemon/machine-daemon.js +1 -1
  48. package/dist/daemon/machine-link/client.d.ts +14 -2
  49. package/dist/daemon/machine-link/client.js +1 -1
  50. package/dist/daemon/machine-link/frames.d.ts +38 -0
  51. package/dist/daemon/machine-link/frames.js +1 -1
  52. package/dist/daemon/machine-link/holder.d.ts +8 -0
  53. package/dist/daemon/machine-link/holder.js +5 -4
  54. package/dist/daemon/machine-supervision.d.ts +17 -0
  55. package/dist/daemon/machine-supervision.js +1 -0
  56. package/dist/daemon/reconcilers/broker-supervision.d.ts +11 -14
  57. package/dist/daemon/reconcilers/broker-supervision.js +3 -4
  58. package/dist/daemon/reconcilers/node-lifecycle/tick.js +1 -1
  59. package/package.json +3 -3
  60. package/packages/crouter-api/dist/api/client.js +4 -0
  61. package/packages/crouter-api/dist/api/contract.js +1 -1
  62. package/packages/crouter-api/dist/api/routes.js +1 -0
  63. package/packages/crouter-api/dist/clients/attach/input/controller.js +5 -1
  64. package/packages/crouter-api/dist/clients/attach/render/chat-view.js +55 -1
  65. package/packages/crouter-api/dist/clients/attach/session/input-wiring.js +1 -0
  66. package/packages/crouter-api/dist/clients/attach/viewer.js +2 -1
  67. package/packages/crouter-api/dist/commands/node/inspect.js +2 -1
  68. package/packages/crouter-api/dist/commands/node-lifecycle-revive.js +14 -16
  69. package/packages/crouter-api/dist/core/canvas/status-glyph.js +15 -0
  70. package/packages/crouter-api/dist/core/command-plugins/compose.js +5 -0
  71. package/packages/crouter-api/dist/core/command.js +13 -1
  72. package/packages/crouter-api/dist/core/feed/messages.js +1 -1
  73. package/packages/crouter-api/dist/core/graph/names.js +7 -8
  74. package/packages/crouter-api/dist/core/help.js +1 -1
  75. package/packages/crouter-api/dist/core/permissions/ceiling.js +1 -1
  76. package/packages/crouter-api/dist/core/permissions/evaluator.js +20 -12
  77. package/packages/crouter-api/dist/core/runtime/broker-protocol.js +26 -12
  78. package/packages/crouter-api/dist/core/runtime/broker-wedge.js +99 -0
  79. package/packages/crouter-api/dist/core/runtime/host.js +10 -3
  80. package/packages/crouter-api/dist/core/runtime/runner/machine/call.js +1 -1
  81. package/packages/crouter-api/dist/core/runtime/runner/machine/ops.js +1 -1
  82. package/packages/crouter-api/dist/core/substrate/delivery/corpus.js +3 -3
  83. package/packages/crouter-api/dist/daemon/api/map.js +2 -0
  84. package/packages/crouter-api/dist/daemon/api/operations.js +1 -0
  85. package/packages/crouter-api/dist/daemon/machine-link/frames.js +4 -0
  86. package/packages/crouter-api/dist/daemon/machine-link/holder.js +63 -1
  87. package/packages/crouter-api/dist/daemon/reconcilers/broker-supervision.js +61 -163
  88. package/packages/crouter-api/package.json +1 -1
  89. package/packages/crouter-identity/package.json +1 -1
  90. package/packages/crouter-plugin/package.json +3 -3
  91. package/runtime.lock.json +14 -14
  92. package/dist/daemon/reconcilers/node-lifecycle/machine-sweep.d.ts +0 -5
  93. package/dist/daemon/reconcilers/node-lifecycle/machine-sweep.js +0 -4
@@ -2,15 +2,14 @@ import { isSafeNodeId } from '../canvas/paths.js';
2
2
  import { OBJECT_TYPE } from '../permissions/builtin.js';
3
3
  import { ceilingFrag, readablePackageApps } from '../permissions/ceiling.js';
4
4
  import { compilePermission } from '../permissions/compile.js';
5
- import { ceilingOf, permits, readerUser, resolveReader, subjectSet } from '../permissions/evaluator.js';
6
- import { loadDefinitions } from '../permissions/schemas.js';
5
+ import { ceilingOf, permits, resolveReader } from '../permissions/evaluator.js';
7
6
  import { and, or, raw } from '../permissions/sql.js';
8
7
  import { flatMapAsync } from '../async-array.js';
9
8
  /** The owners a bare name is looked up under, in order: own node, repos nearest
10
9
  * first (each checkout's own repo object first, then others oldest first), the profile's project repos, profile, app, you, your groups, then the apps whose tools the run may use (installed
11
10
  * plugins) with `crtr` last. */
12
- export async function viewOf(db, reader) {
13
- const user = await readerUser(db, reader);
11
+ export async function viewOf(db, reader, ev) {
12
+ const { userId: user, subjects } = ev ?? await resolveReader(db, reader);
14
13
  const person = user === null ? undefined : await db.prepare(`SELECT o.* FROM objects o JOIN identities i ON i.object = o.id AND i.scheme = 'user'
15
14
  WHERE o.type = 'person' AND o.home_machine IS NULL AND regexp_replace(i.external_id, '^user:', '') = ?`).get(user);
16
15
  // The apps whose shipped documents the reader may read (the read rule), `crtr` last. A person reads every published package.
@@ -24,7 +23,7 @@ export async function viewOf(db, reader) {
24
23
  : reader.class === 'object' ? [reader.owner, ...reader.repos, reader.app]
25
24
  : [];
26
25
  // The groups the reader's person belongs to: their own documents load for members, after the person's.
27
- const groupIds = user === null ? [] : (await subjectSet(db, user)).groupIds.filter((id) => id.startsWith('group:')).map((id) => id.slice('group:'.length));
26
+ const groupIds = subjects.groupIds.filter((id) => id.startsWith('group:')).map((id) => id.slice('group:'.length));
28
27
  const groups = groupIds.length === 0 ? [] : await db.prepare(`SELECT * FROM objects WHERE type = 'group' AND deleted_at IS NULL AND id = ANY(?::text[]) ORDER BY created_at, seq`).all(groupIds);
29
28
  const seen = new Set();
30
29
  return [...head, person, ...groups, ...tools].filter((o) => !!o && !seen.has(o.id) && !!seen.add(o.id));
@@ -36,7 +35,7 @@ export async function viewOf(db, reader) {
36
35
  export async function readableOrDeleted(db, ev, alias) {
37
36
  const live = await permits(db, ev, 'read', alias);
38
37
  const ceiling = await ceilingOf(db, ev, 'read');
39
- const grants = compilePermission(await loadDefinitions(db), ev.subjects, OBJECT_TYPE, 'read', raw('gr.id'));
38
+ const grants = compilePermission(ev.defs, ev.subjects, OBJECT_TYPE, 'read', raw('gr.id'));
40
39
  const chain = { sql: `EXISTS (WITH RECURSIVE up(id, depth) AS (
41
40
  SELECT ${alias}.id, 0
42
41
  UNION ALL SELECT p.owner, up.depth + 1 FROM up JOIN objects p ON p.id = up.id WHERE p.owner IS NOT NULL AND up.depth < 12)
@@ -123,7 +122,7 @@ export async function resolveNames(db, reader, raws, context) {
123
122
  if (all.length === 0)
124
123
  return new Map();
125
124
  const ev = context?.ev ?? await resolveReader(db, reader);
126
- const view = context?.view ?? await viewOf(db, reader);
125
+ const view = context?.view ?? await viewOf(db, reader, ev);
127
126
  const normal = new Map();
128
127
  for (const raw of all) {
129
128
  let name = unwrapRef(raw);
@@ -218,7 +217,7 @@ export async function stubsNamed(db, reader, raw) {
218
217
  const name = unwrapRef(raw);
219
218
  const ev = await resolveReader(db, reader);
220
219
  const found = async (owners, rest) => await flatMapAsync(owners, async (owner) => await namedObjects(db, ev, owner, rest, false, true));
221
- const inView = await found(await viewOf(db, reader), name);
220
+ const inView = await found(await viewOf(db, reader, ev), name);
222
221
  if (inView.length)
223
222
  return inView;
224
223
  const split = splitOwnerRef(name);
@@ -285,7 +285,7 @@ function paramDesc(p, leafName) {
285
285
  const f = p;
286
286
  const focusedNote = focusedFlagHelpNote(f, leafName);
287
287
  if (f.type === 'bool')
288
- return `${req} boolean. Presence means true. ${f.constraint}${focusedNote}`.trim();
288
+ return `${req} boolean. Presence means true; \`--no-${f.name}\` means false. ${f.constraint}${focusedNote}`.trim();
289
289
  const dflt = f.default !== undefined ? ` Default: ${String(f.default)}.` : '';
290
290
  const choices = f.type === 'enum' && f.choices !== undefined
291
291
  ? ` One of: ${f.choices.join(', ')}.`
@@ -69,7 +69,7 @@ export async function readablePackageApps(db, reader, user) {
69
69
  const held = reader.scopes;
70
70
  return await eligiblePackageApps(db, { holdsProvider: (ext) => held !== null && holdsProviderGroup(held, ext), cloud: isCloudRole(), ownExt: await externalId(db, reader.app.id), user });
71
71
  }
72
- /** The ceiling of `reader` for `access`; null for a person reader (no ceiling). `user` is the bare user id the reader acts for (`readerUser`), null for a
72
+ /** The ceiling of `reader` for `access`; null for a person reader (no ceiling). `user` is the bare user id the reader acts for (`resolveReader`), null for a
73
73
  * reader that acts for no person: it reads the package apps every reader reads and the providers its scopes hold, never a plugin. */
74
74
  export async function resolveCeiling(db, reader, user, access, options = {}) {
75
75
  if (reader.class === 'person')
@@ -23,14 +23,6 @@ export async function userOf(db, reader) {
23
23
  const row = await db.prepare('SELECT sub FROM nodes WHERE node_id = ?').get(nodeId);
24
24
  return bareUser(row?.sub ?? await personIdAsync());
25
25
  }
26
- /** The user a reader reads as: `userOf`, except that on a cloud role an app reader with no `sub` (a runtime-owned call, such as
27
- * package link derivation at boot) acts for no person and answers null. `userOf` itself keeps throwing there, so no write path
28
- * records an object as kept for a person that is not there. */
29
- export async function readerUser(db, reader) {
30
- if (reader.class === 'app' && reader.sub === undefined && isCloudRole())
31
- return null;
32
- return await userOf(db, reader);
33
- }
34
26
  /** The user ids a subject stands for (the user and `*`) and every group it reaches, directly or through nested groups. */
35
27
  export async function subjectSet(db, userId) {
36
28
  const userIds = [userId, '*'];
@@ -42,9 +34,25 @@ export async function subjectSet(db, userId) {
42
34
  SELECT id FROM g`).all(GROUP_TYPE, userIds, GROUP_TYPE, GROUP_TYPE);
43
35
  return { userIds, groupIds: rows.map((r) => r.id) };
44
36
  }
45
- export async function resolveReader(db, reader) {
46
- const userId = await readerUser(db, reader);
47
- return { reader, userId, subjects: userId === null ? { userIds: ['*'], groupIds: [] } : await subjectSet(db, userId) };
37
+ /** A reader `shareReads` marked is built for one request: its user, subjects and definitions are resolved once; any other reader may outlive a
38
+ * membership change and resolves them per call. The user a reader reads as is `userOf`, except that on a cloud role an app reader with no `sub` (a
39
+ * runtime-owned call, such as package link derivation at boot) acts for no person: null. `userOf` itself keeps throwing there. */
40
+ const oneRequest = new WeakMap();
41
+ export const shareReads = (reader) => { if (!oneRequest.has(reader))
42
+ oneRequest.set(reader, null); return reader; };
43
+ export function resolveReader(db, reader) {
44
+ const shared = oneRequest.get(reader);
45
+ if (shared)
46
+ return shared;
47
+ const ev = (async () => {
48
+ const userId = reader.class === 'app' && reader.sub === undefined && isCloudRole() ? null : await userOf(db, reader);
49
+ return { reader, userId, subjects: userId === null ? { userIds: ['*'], groupIds: [] } : await subjectSet(db, userId), defs: await loadDefinitions(db) };
50
+ })();
51
+ if (shared === null) {
52
+ oneRequest.set(reader, ev);
53
+ ev.catch(() => oneRequest.set(reader, null));
54
+ }
55
+ return ev;
48
56
  }
49
57
  const isEval = (r) => 'subjects' in r;
50
58
  /** SQL true when `reader` holds `permission` on the object `alias` (a row of `objects` in the caller's SELECT): schema within the ceiling.
@@ -53,7 +61,7 @@ export async function permits(db, reader, permission, alias = 'o', options = {})
53
61
  if (!PERMISSIONS.includes(permission))
54
62
  throw new PermissionError(400, 'unknown_permission', `unknown permission ${permission}`);
55
63
  const ev = isEval(reader) ? reader : await resolveReader(db, reader);
56
- const defs = await loadDefinitions(db);
64
+ const { defs } = ev;
57
65
  const id = raw(`${alias}.id`);
58
66
  // Apps are the roots of every tree and are shared by every account: any reader sees that an app exists. Nothing below an app inherits this
59
67
  // (a fact `reader @ user:*` on the app would), so it is the one type-level rule in the evaluator.
@@ -17,13 +17,31 @@
17
17
  // follow pi.
18
18
  import { StringDecoder } from 'node:string_decoder';
19
19
  // Client → broker frames
20
- /** Largest transcript window a client may request in its welcome snapshot. */
21
- export const SNAPSHOT_TAIL_MAX = 500;
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 undefined;
26
- return Math.min(value, SNAPSHOT_TAIL_MAX);
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. The `welcome.snapshot` carries the
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: 256 * 1024 * 1024,
58
- maxTotalBytes: 256 * 1024 * 1024,
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
- prepared = await prepareBrokerTeardown(nodeId, opts);
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, 'status.all': 15, delete: 15, viewer: 15, 'cron.run': 15, 'cron.cancel': 15, 'job.stop': 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', 'status.all', 'delete', 'viewer', 'cron.run', 'cron.cancel', 'job.stop',
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;