@north-light/cli 0.3.708 → 0.3.710
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/api/dto/crons.d.ts +3 -0
- package/dist/clients/attach/chrome/inbox-strip.js +1 -1
- package/dist/clients/attach/chrome/roster.js +6 -6
- package/dist/clients/attach/chrome/status-line.d.ts +1 -1
- package/dist/clients/attach/chrome/status-line.js +1 -1
- package/dist/clients/attach/input/capabilities.js +1 -1
- package/dist/clients/attach/input/controller.d.ts +4 -0
- package/dist/clients/attach/input/controller.js +3 -3
- package/dist/clients/attach/overlays/graph.d.ts +3 -2
- package/dist/clients/attach/overlays/graph.js +1 -1
- package/dist/clients/attach/render/chat-view.d.ts +2 -0
- package/dist/clients/attach/render/chat-view.js +1 -1
- package/dist/clients/attach/render/doc-links.d.ts +1 -1
- package/dist/clients/attach/session/chrome-refresh.js +1 -1
- package/dist/clients/attach/session/connection.d.ts +10 -9
- package/dist/clients/attach/session/connection.js +1 -1
- package/dist/clients/attach/session/context.d.ts +1 -1
- package/dist/clients/attach/session/document-links.d.ts +1 -1
- package/dist/clients/attach/session/document-links.js +1 -1
- package/dist/clients/attach/session/identity.d.ts +2 -0
- package/dist/clients/attach/session/identity.js +1 -1
- package/dist/clients/attach/session/input-wiring.d.ts +2 -0
- package/dist/clients/attach/session/input-wiring.js +1 -1
- package/dist/clients/attach/session/keys.d.ts +2 -0
- package/dist/clients/attach/session/keys.js +1 -1
- package/dist/clients/attach/session/layout-record.d.ts +13 -0
- package/dist/clients/attach/session/layout-record.js +1 -0
- package/dist/clients/attach/session/pane-tag.d.ts +3 -1
- package/dist/clients/attach/session/pane-tag.js +1 -1
- package/dist/clients/attach/session/reconnect.js +1 -1
- package/dist/clients/attach/session/teardown.d.ts +4 -2
- package/dist/clients/attach/session/teardown.js +9 -7
- package/dist/clients/attach/slash/dispatch.js +2 -2
- package/dist/clients/attach/slash/recover.d.ts +10 -0
- package/dist/clients/attach/slash/recover.js +2 -0
- package/dist/clients/attach/viewer.d.ts +7 -5
- package/dist/clients/attach/viewer.js +563 -558
- package/dist/commands/node/wait.js +2 -6
- package/dist/core/broker-client/client.d.ts +6 -3
- package/dist/core/broker-client/client.js +1 -1
- package/dist/core/canvas/crons.d.ts +11 -1
- package/dist/core/canvas/crons.js +14 -14
- package/dist/core/canvas/executions.js +1 -1
- package/dist/core/canvas/managed-worktree-sweep-candidates.d.ts +2 -2
- package/dist/core/canvas/managed-worktree-sweep-candidates.js +5 -3
- package/dist/core/canvas/schema-pg/026-cron-deadline-body.sql +9 -0
- package/dist/core/canvas/schema-pg/027-cron-fires.sql +4 -0
- package/dist/core/canvas/schema-pg/028-machine-calls-worktree-sweep.sql +6 -0
- package/dist/core/canvas/schema-version.d.ts +1 -1
- package/dist/core/canvas/schema-version.js +1 -1
- package/dist/core/command.js +5 -5
- package/dist/core/feed/messages.d.ts +5 -0
- package/dist/core/feed/messages.js +5 -5
- package/dist/core/runtime/bearings.js +4 -4
- package/dist/core/runtime/boot-root.js +4 -4
- package/dist/core/runtime/broker-request.d.ts +2 -0
- package/dist/core/runtime/broker-request.js +1 -1
- package/dist/core/runtime/broker.js +1 -1
- package/dist/core/runtime/lifecycle.js +2 -2
- package/dist/core/runtime/model-swap.d.ts +2 -1
- package/dist/core/runtime/model-swap.js +1 -1
- package/dist/core/runtime/placement-tmux.d.ts +1 -1
- package/dist/core/runtime/placement-tmux.js +1 -1
- package/dist/core/runtime/revive.js +2 -2
- package/dist/core/runtime/runner/blaxel/client.d.ts +4 -0
- package/dist/core/runtime/runner/blaxel/client.js +1 -1
- package/dist/core/runtime/runner/blaxel/runner.d.ts +2 -3
- package/dist/core/runtime/runner/blaxel/runner.js +3 -3
- package/dist/core/runtime/runner/delete-sandboxes.d.ts +5 -0
- package/dist/core/runtime/runner/delete-sandboxes.js +6 -1
- package/dist/core/runtime/runner/machine/call.js +2 -2
- package/dist/core/runtime/runner/machine/ops.d.ts +11 -1
- package/dist/core/runtime/runner/machine/ops.js +1 -1
- package/dist/core/runtime/runner/types.d.ts +19 -3
- package/dist/core/runtime/tmux-driver.d.ts +7 -0
- package/dist/core/runtime/tmux-driver.js +6 -6
- package/dist/core/worktree-machine.d.ts +4 -1
- package/dist/core/worktree-machine.js +1 -1
- package/dist/core/worktree-sweep.d.ts +14 -3
- package/dist/core/worktree-sweep.js +4 -4
- package/dist/daemon/api/bridge.d.ts +5 -0
- package/dist/daemon/api/bridge.js +3 -3
- package/dist/daemon/api/handlers/crons.d.ts +2 -0
- package/dist/daemon/api/handlers/crons.js +1 -1
- package/dist/daemon/api/handlers/nodes.js +1 -1
- package/dist/daemon/api/operations.js +1 -1
- package/dist/daemon/cron/ended.d.ts +3 -0
- package/dist/daemon/cron/ended.js +2 -2
- package/dist/daemon/cron/lease-recovery.js +1 -1
- package/dist/daemon/cron/machine-fire.d.ts +9 -2
- package/dist/daemon/cron/machine-fire.js +1 -1
- package/dist/daemon/cron/passes.js +1 -1
- package/dist/daemon/cron-run.js +2 -2
- package/dist/daemon/fleet.d.ts +1 -1
- package/dist/daemon/fleet.js +4 -4
- package/dist/daemon/machine-link/client.js +1 -1
- package/dist/daemon/reconcilers/fault-retry-backstop.js +1 -1
- package/dist/daemon/reconcilers/idle-sandbox.d.ts +1 -1
- package/dist/daemon/reconcilers/idle-sandbox.js +2 -2
- package/dist/daemon/reconcilers/managed-worktree-sweep.js +1 -1
- package/dist/daemon/reconcilers/node-lifecycle/remote-wake.js +2 -2
- package/dist/daemon/runs/observer.d.ts +4 -0
- package/dist/daemon/runs/observer.js +1 -1
- package/dist/pi-extensions/canvas-inbox-watcher.js +1 -1
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/clients/attach/chrome/inbox-strip.js +5 -5
- package/packages/crouter-api/dist/clients/attach/chrome/roster.js +8 -8
- package/packages/crouter-api/dist/clients/attach/chrome/status-line.js +1 -1
- package/packages/crouter-api/dist/clients/attach/input/capabilities.js +3 -1
- package/packages/crouter-api/dist/clients/attach/input/controller.js +17 -0
- package/packages/crouter-api/dist/clients/attach/overlays/graph.js +4 -3
- package/packages/crouter-api/dist/clients/attach/render/chat-view.js +9 -0
- package/packages/crouter-api/dist/clients/attach/session/chrome-refresh.js +6 -3
- package/packages/crouter-api/dist/clients/attach/session/connection.js +53 -53
- package/packages/crouter-api/dist/clients/attach/session/document-links.js +1 -1
- package/packages/crouter-api/dist/clients/attach/session/identity.js +1 -0
- package/packages/crouter-api/dist/clients/attach/session/input-wiring.js +4 -3
- package/packages/crouter-api/dist/clients/attach/session/keys.js +11 -4
- package/packages/crouter-api/dist/clients/attach/session/layout-record.js +52 -0
- package/packages/crouter-api/dist/clients/attach/session/pane-tag.js +7 -1
- package/packages/crouter-api/dist/clients/attach/session/reconnect.js +3 -3
- package/packages/crouter-api/dist/clients/attach/session/teardown.js +9 -4
- package/packages/crouter-api/dist/clients/attach/slash/dispatch.js +12 -0
- package/packages/crouter-api/dist/clients/attach/slash/recover.js +111 -0
- package/packages/crouter-api/dist/clients/attach/viewer.js +86 -31
- package/packages/crouter-api/dist/commands/node/wait.js +2 -10
- package/packages/crouter-api/dist/core/broker-client/client.js +20 -10
- package/packages/crouter-api/dist/core/canvas/crons.js +26 -10
- package/packages/crouter-api/dist/core/canvas/executions.js +7 -2
- package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
- package/packages/crouter-api/dist/core/command.js +3 -0
- package/packages/crouter-api/dist/core/feed/messages.js +15 -0
- package/packages/crouter-api/dist/core/runtime/bearings.js +2 -2
- package/packages/crouter-api/dist/core/runtime/broker-ownership.js +6 -0
- package/packages/crouter-api/dist/core/runtime/broker-request.js +1 -1
- package/packages/crouter-api/dist/core/runtime/lifecycle.js +3 -0
- package/packages/crouter-api/dist/core/runtime/model-swap.js +2 -1
- package/packages/crouter-api/dist/core/runtime/placement-tmux.js +1 -1
- package/packages/crouter-api/dist/core/runtime/revive.js +5 -25
- package/packages/crouter-api/dist/core/runtime/runner/blaxel/client.js +15 -8
- package/packages/crouter-api/dist/core/runtime/runner/blaxel/runner.js +60 -19
- package/packages/crouter-api/dist/core/runtime/runner/delete-sandboxes.js +18 -2
- package/packages/crouter-api/dist/core/runtime/runner/machine/call.js +1 -1
- package/packages/crouter-api/dist/core/runtime/runner/machine/executor.js +235 -0
- package/packages/crouter-api/dist/core/runtime/runner/machine/ops.js +1 -1
- package/packages/crouter-api/dist/core/runtime/tmux-driver.js +11 -0
- package/packages/crouter-api/dist/core/worktree-machine.js +20 -0
- package/packages/crouter-api/dist/core/worktree-sweep.js +439 -0
- package/packages/crouter-api/dist/daemon/api/operations.js +2 -2
- package/packages/crouter-api/dist/daemon/cron/ended.js +22 -11
- package/packages/crouter-api/dist/daemon/cron/machine-fire.js +69 -6
- package/packages/crouter-api/dist/daemon/reconcilers/node-lifecycle/remote-wake.js +2 -2
- package/packages/crouter-api/dist/daemon/runs/observer.js +1 -1
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
- package/dist/core/runtime/starting-screen.d.ts +0 -12
- package/dist/core/runtime/starting-screen.js +0 -9
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
// src/core/runtime/runner/machine/executor.ts — what the Mac does for each call the control plane sends over the machine link (design-import I13).
|
|
2
|
+
//
|
|
3
|
+
// DB-free: a machine-role crtrd has no local Postgres. `start` uses the start bundle the call carries, writes the run dir's `broker-launch.json`, and
|
|
4
|
+
// spawns `broker-cli` with the token on fd 3.
|
|
5
|
+
// The broker finds itself by the `--epoch <execution id>` in its argv: `wake`, `stop` and `status` scan the process table for it.
|
|
6
|
+
import { spawn } from 'node:child_process';
|
|
7
|
+
import { closeSync, existsSync, mkdirSync, openSync, statSync } from 'node:fs';
|
|
8
|
+
import { rm } from 'node:fs/promises';
|
|
9
|
+
import { basename, dirname, join } from 'node:path';
|
|
10
|
+
import { fileURLToPath } from 'node:url';
|
|
11
|
+
import { emitEvent } from '../../../events/emit.js';
|
|
12
|
+
import { contextDir, jobDir, nodeRunDir, crtrHome, viewSocketPath } from '../../../canvas/paths.js';
|
|
13
|
+
import { captureTeardownSnapshot, isAnyPidAlive, killProcessTreePids, listProcessTableAsync } from '../../../canvas/pid.js';
|
|
14
|
+
import { scopesFilePath } from '../../../canvas/paths.js';
|
|
15
|
+
import { writeFileBeneath } from '../../../spaces/open-beneath.js';
|
|
16
|
+
import { FRONT_DOOR_ENV } from '../../front-door-env.js';
|
|
17
|
+
import { brokerCommandDeclaresCanvasHome } from '../../broker-ownership.js';
|
|
18
|
+
import { isShippedCanvasExtension } from '../../../canvas/extensions.js';
|
|
19
|
+
import { CANVAS_EXTENSIONS, mergeCanvasExtensions } from '../../canvas-extensions.js';
|
|
20
|
+
import { layoutRoot, runtimeRoot } from '../../../layout.js';
|
|
21
|
+
import { composeAppProcessEnv, overlayBrokerEnv } from '../../spawn-env.js';
|
|
22
|
+
const brokerEntry = () => join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'broker-cli.js');
|
|
23
|
+
const killGroup = (pid) => { if (pid !== undefined)
|
|
24
|
+
try {
|
|
25
|
+
process.kill(-pid, 'SIGKILL');
|
|
26
|
+
}
|
|
27
|
+
catch { /* gone */ } };
|
|
28
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
29
|
+
/** Broker processes: `{pid, execution, node}` for each `broker-cli.js ... --epoch <execution> <node>` command line. Throws when the process table cannot
|
|
30
|
+
* be read: an unreadable table is not an empty one, and a caller that read it as "no brokers" would start a second broker or report a stop that did not happen. */
|
|
31
|
+
export async function findBrokers() {
|
|
32
|
+
const out = [];
|
|
33
|
+
const table = await listProcessTableAsync();
|
|
34
|
+
if (table === null)
|
|
35
|
+
throw new Error('the process table could not be read, so which brokers are running is unknown');
|
|
36
|
+
for (const { pid, command } of table) {
|
|
37
|
+
const m = /broker-cli\.js .*--epoch (\S+) (\S+)\s*$/.exec(command);
|
|
38
|
+
if (m !== null)
|
|
39
|
+
out.push({ pid, execution: m[1], node: m[2], command });
|
|
40
|
+
}
|
|
41
|
+
return out;
|
|
42
|
+
}
|
|
43
|
+
/** The launch recipe's env keys that name a path in the control plane's filesystem. The control plane builds the recipe on its own layout (a Linux pod:
|
|
44
|
+
* `/work/crtr`, `/opt/crouter/runtime`), so none of them is a path on this machine: the home and runtime home are dropped (this machine's own are
|
|
45
|
+
* pinned by `machineBrokerEnv`), and the context dir and scopes file are derived from this machine's layout. */
|
|
46
|
+
const CONTROL_PLANE_HOME_KEYS = ['CRTR_HOME', 'CRTR_RUNTIME_HOME'];
|
|
47
|
+
/** `launch.env` with every machine-local path key replaced by this machine's own; everything else (identity, kind, profile, settings) is the bundle's. */
|
|
48
|
+
function localLaunchEnv(env, node) {
|
|
49
|
+
const out = { ...env };
|
|
50
|
+
for (const key of CONTROL_PLANE_HOME_KEYS)
|
|
51
|
+
delete out[key];
|
|
52
|
+
if (out['CRTR_CONTEXT_DIR'] !== undefined)
|
|
53
|
+
out['CRTR_CONTEXT_DIR'] = contextDir(node.id, out['CRTR_GRANTEE'] ?? node.app);
|
|
54
|
+
if (out['CRTR_SCOPES_FILE'] !== undefined)
|
|
55
|
+
out['CRTR_SCOPES_FILE'] = scopesFilePath(node.id);
|
|
56
|
+
return out;
|
|
57
|
+
}
|
|
58
|
+
/** The recipe's `-e` extension paths name files of the control plane's install (`/opt/crouter/runtime/generations/...`), and its release may ship a different
|
|
59
|
+
* set of canvas extensions than this install. So the mandatory canvas extensions are this install's complete list (`mergeCanvasExtensions`), whatever the recipe
|
|
60
|
+
* carried of them; the recipe's own extensions are kept and must exist on this machine, or the launch is refused. Every other argument is the recipe's. */
|
|
61
|
+
export function localExtensionArgv(argv) {
|
|
62
|
+
// A canvas hook of the control plane's release is dropped whether or not this install still ships it: this install's own list replaces them.
|
|
63
|
+
// `isShippedCanvasExtension` knows the hooks by name; `system-prompt-entry` is mandatory but not one of them, and a hook this install retired has no local file.
|
|
64
|
+
const stem = (path) => basename(path).replace(/\.[jt]s$/, '');
|
|
65
|
+
const mandatoryStems = new Set(CANVAS_EXTENSIONS.map(stem));
|
|
66
|
+
const shipped = (path) => isShippedCanvasExtension(path) || (basename(dirname(path)) === 'pi-extensions' && (mandatoryStems.has(stem(path)) || (stem(path).startsWith('canvas-') && !existsSync(path))));
|
|
67
|
+
const rest = [];
|
|
68
|
+
const custom = [];
|
|
69
|
+
for (let i = 0; i < argv.length; i++) {
|
|
70
|
+
if (argv[i] === '-e' && argv[i + 1] !== undefined) {
|
|
71
|
+
const path = argv[++i];
|
|
72
|
+
if (shipped(path))
|
|
73
|
+
continue;
|
|
74
|
+
if (!existsSync(path))
|
|
75
|
+
throw new Error(`extension ${path} does not exist on this machine`);
|
|
76
|
+
custom.push(path);
|
|
77
|
+
}
|
|
78
|
+
else
|
|
79
|
+
rest.push(argv[i]);
|
|
80
|
+
}
|
|
81
|
+
return [...mergeCanvasExtensions(custom).flatMap((path) => ['-e', path]), ...rest];
|
|
82
|
+
}
|
|
83
|
+
/** The recipe this machine's broker reads from `broker-launch.json` (the broker merges its `env` into `process.env` and loads its `argv` extensions):
|
|
84
|
+
* the control plane's recipe with the machine-local paths above. */
|
|
85
|
+
export function machineLaunchRecipe(launchJson, node, start) {
|
|
86
|
+
const recipe = JSON.parse(launchJson);
|
|
87
|
+
return JSON.stringify({ ...recipe, argv: localExtensionArgv(recipe.argv), env: localLaunchEnv(recipe.env ?? {}, node), ...(start === undefined ? {} : { start }) });
|
|
88
|
+
}
|
|
89
|
+
/** The env a machine's broker starts with: what the process runner's `buildBrokerEnv` builds for the same node. The environment's secret rows come from the
|
|
90
|
+
* control plane in the start bundle with the profile's metadata (this role has no database and no profiles, so the profile is never looked up here); the operational base, the profile's metadata, the app's pi dir and the launch recipe's env
|
|
91
|
+
* go over them in `buildBrokerEnv`'s order, and the link's own settings are pinned last. The recipe's path-shaped keys are this machine's (`localLaunchEnv`). */
|
|
92
|
+
export function machineBrokerEnv(bundle, deps, executionId) {
|
|
93
|
+
const launch = bundle.launch;
|
|
94
|
+
const env = overlayBrokerEnv({ argv: [], env: localLaunchEnv(launch.env ?? {}, bundle.node) }, composeAppProcessEnv(bundle.node.cwd, null, bundle.node.app, bundle.machine_env ?? {}, {}));
|
|
95
|
+
return Object.assign(env, { CRTR_HOME: layoutRoot(), CRTR_RUNTIME_HOME: process.env['CRTR_RUNTIME_HOME'] ?? runtimeRoot(), CRTR_API_URL: deps.apiUrl, CRTR_EXECUTION_ID: executionId, CRTR_ENVIRONMENT_ID: deps.environmentId, CRTR_VIEW_WSS: '0', [FRONT_DOOR_ENV]: '1' });
|
|
96
|
+
}
|
|
97
|
+
/** Stop one broker and its whole process tree: SIGTERM, `graceMs` for it to exit, then SIGTERM and SIGKILL to what remains of the tree. */
|
|
98
|
+
async function stopBroker(pid, graceMs, excludePid) {
|
|
99
|
+
// The tree is captured before any signal: once the broker dies, its detached children are reparented away from it and a later walk cannot find them.
|
|
100
|
+
const { tree, identities } = captureTeardownSnapshot(pid, null, excludePid);
|
|
101
|
+
if (identities === null)
|
|
102
|
+
return { confirmed: false, error: `the process tree of broker ${pid} could not be read, so shutdown cannot be confirmed` };
|
|
103
|
+
const waitUntilDead = async (pids, ms) => {
|
|
104
|
+
for (let waited = 0; isAnyPidAlive(pids); waited += 100) {
|
|
105
|
+
if (waited >= ms)
|
|
106
|
+
return false;
|
|
107
|
+
await sleep(100);
|
|
108
|
+
}
|
|
109
|
+
return true;
|
|
110
|
+
};
|
|
111
|
+
try {
|
|
112
|
+
process.kill(pid, 'SIGTERM');
|
|
113
|
+
}
|
|
114
|
+
catch { /* gone */ }
|
|
115
|
+
await waitUntilDead([pid], graceMs);
|
|
116
|
+
// The broker is down or ignored SIGTERM; whatever of its tree remains (detached bash work included) is ended.
|
|
117
|
+
killProcessTreePids(tree, 'SIGTERM', identities);
|
|
118
|
+
if (await waitUntilDead(tree, 2_000))
|
|
119
|
+
return { confirmed: true };
|
|
120
|
+
killProcessTreePids(tree, 'SIGKILL', identities);
|
|
121
|
+
return await waitUntilDead(tree, 5_000) ? { confirmed: true } : { confirmed: false, error: `broker process tree of ${pid} survived SIGKILL` };
|
|
122
|
+
}
|
|
123
|
+
/** Stop every broker of this crtr home (a machine daemon starting with no sign-in, design-crtr-northlight-signin component 5). A broker of another
|
|
124
|
+
* home on the same computer (its `--canvas-home` differs) is not touched. Rejects when the process table cannot be read or a broker's tree survives
|
|
125
|
+
* SIGKILL, so the caller never reports stopped while something of this home may still run. */
|
|
126
|
+
export async function stopAllBrokers(graceMs = 10_000) {
|
|
127
|
+
const outcomes = await Promise.all((await findBrokers()).filter((broker) => brokerCommandDeclaresCanvasHome(broker.command, crtrHome())).map((broker) => stopBroker(broker.pid, graceMs)));
|
|
128
|
+
const survivors = outcomes.filter((outcome) => !outcome.confirmed);
|
|
129
|
+
if (survivors.length > 0)
|
|
130
|
+
throw new Error(survivors.map((outcome) => outcome.error ?? 'a broker did not stop').join('; '));
|
|
131
|
+
}
|
|
132
|
+
export function createMachineExecutor(deps) {
|
|
133
|
+
const stopGraceMs = (deps.stopGraceS ?? 10) * 1000;
|
|
134
|
+
const brokerOf = async (executionId) => (await findBrokers()).find((b) => b.execution === executionId);
|
|
135
|
+
return {
|
|
136
|
+
async start(args, signal) {
|
|
137
|
+
const timings = {};
|
|
138
|
+
let stepStart = performance.now();
|
|
139
|
+
const stepDone = (name) => { const now = performance.now(); timings[name] = Math.round((now - stepStart) * 10) / 10; stepStart = now; };
|
|
140
|
+
const existing = await brokerOf(args.executionId);
|
|
141
|
+
stepDone('process_lookup');
|
|
142
|
+
if (existing !== undefined)
|
|
143
|
+
return { pid: existing.pid, timings };
|
|
144
|
+
signal?.throwIfAborted();
|
|
145
|
+
// Known launch errors are refused now, so the control plane reads a launch failure, not a silent start.
|
|
146
|
+
if (!existsSync(args.cwd) || !statSync(args.cwd).isDirectory())
|
|
147
|
+
throw new Error(`the node's cwd ${args.cwd} is not a directory on this machine`);
|
|
148
|
+
if (!existsSync(brokerEntry()))
|
|
149
|
+
throw new Error(`the broker entry ${brokerEntry()} does not exist`);
|
|
150
|
+
// A control plane older than this Mac (a rollback, or a pod still rolling) may send a start from its runner without one.
|
|
151
|
+
if (args.bundle === undefined)
|
|
152
|
+
throw new Error('the control plane carried no start bundle: it runs an older release than this Mac');
|
|
153
|
+
const { bundle } = args;
|
|
154
|
+
const launch = bundle.launch;
|
|
155
|
+
const runDir = nodeRunDir(args.nodeId);
|
|
156
|
+
mkdirSync(runDir, { recursive: true });
|
|
157
|
+
writeFileBeneath(runDir, join(runDir, 'broker-launch.json'), machineLaunchRecipe(args.launchJson, bundle.node, args.start), { atomic: true, mode: 0o600 });
|
|
158
|
+
if (launch.env?.['CRTR_SCOPES_FILE'] !== undefined)
|
|
159
|
+
writeFileBeneath(runDir, scopesFilePath(args.nodeId), JSON.stringify(launch.scopes ?? []), { atomic: true });
|
|
160
|
+
const logDir = jobDir(args.nodeId);
|
|
161
|
+
mkdirSync(logDir, { recursive: true });
|
|
162
|
+
const logFd = openSync(join(logDir, 'broker.log'), 'a');
|
|
163
|
+
const env = machineBrokerEnv(bundle, deps, args.executionId);
|
|
164
|
+
delete env['CRTR_NODE_TOKEN'];
|
|
165
|
+
stepDone('file_writes');
|
|
166
|
+
try {
|
|
167
|
+
// The link may have dropped meanwhile: the control plane already read this call as unanswered, so nothing is spawned for it.
|
|
168
|
+
signal?.throwIfAborted();
|
|
169
|
+
const child = spawn(process.execPath, [brokerEntry(), '--canvas-home', crtrHome(), '--epoch', args.executionId, args.nodeId], { cwd: args.cwd, detached: true, stdio: ['ignore', logFd, logFd, 'pipe'], env });
|
|
170
|
+
// Listening from the spawn on, so a broker that dies before the launch finishes is still reported once it has.
|
|
171
|
+
let exited;
|
|
172
|
+
let launched = false;
|
|
173
|
+
const report = () => { if (exited !== undefined)
|
|
174
|
+
deps.onExit?.({ execution: args.executionId, node: args.nodeId, ...exited }); };
|
|
175
|
+
child.once('exit', (code, signal) => { exited = { code, signal }; if (launched)
|
|
176
|
+
report(); });
|
|
177
|
+
const pipe = child.stdio[3];
|
|
178
|
+
if (pipe === null || pipe === undefined || !('end' in pipe)) {
|
|
179
|
+
killGroup(child.pid);
|
|
180
|
+
throw new Error('broker token pipe did not open');
|
|
181
|
+
}
|
|
182
|
+
const pid = await new Promise((resolve, reject) => {
|
|
183
|
+
child.once('error', reject);
|
|
184
|
+
child.once('spawn', () => {
|
|
185
|
+
child.off('error', reject);
|
|
186
|
+
// After spawn, a pipe failure is a launch failure; a later child exit is ordinary status recovery.
|
|
187
|
+
pipe.once('error', (error) => { killGroup(child.pid); reject(error); });
|
|
188
|
+
pipe.end(args.nodeToken, (error) => { if (error)
|
|
189
|
+
reject(error);
|
|
190
|
+
else
|
|
191
|
+
resolve(child.pid); });
|
|
192
|
+
});
|
|
193
|
+
});
|
|
194
|
+
launched = true;
|
|
195
|
+
report();
|
|
196
|
+
child.unref();
|
|
197
|
+
stepDone('spawn_and_token_pipe');
|
|
198
|
+
emitEvent({ level: 'info', event: 'machine.start.timing', node_id: args.nodeId, fields: { execution: args.executionId, ...timings } });
|
|
199
|
+
return { pid, timings };
|
|
200
|
+
}
|
|
201
|
+
finally {
|
|
202
|
+
closeSync(logFd);
|
|
203
|
+
}
|
|
204
|
+
},
|
|
205
|
+
async wake({ execution }) {
|
|
206
|
+
const broker = await brokerOf(execution.executionId);
|
|
207
|
+
if (broker === undefined)
|
|
208
|
+
return 'no_broker';
|
|
209
|
+
try {
|
|
210
|
+
process.kill(broker.pid, 'SIGUSR1');
|
|
211
|
+
return 'signalled';
|
|
212
|
+
}
|
|
213
|
+
catch (error) {
|
|
214
|
+
if (error.code === 'ESRCH')
|
|
215
|
+
return 'no_broker';
|
|
216
|
+
throw error;
|
|
217
|
+
}
|
|
218
|
+
},
|
|
219
|
+
async stop({ execution, options }) {
|
|
220
|
+
const broker = await brokerOf(execution.executionId);
|
|
221
|
+
return broker === undefined ? { confirmed: true } : await stopBroker(broker.pid, stopGraceMs, options.excludePid);
|
|
222
|
+
},
|
|
223
|
+
async status({ execution }) {
|
|
224
|
+
const broker = await brokerOf(execution.executionId);
|
|
225
|
+
return broker === undefined ? { state: 'gone' } : { state: 'running', pid: broker.pid };
|
|
226
|
+
},
|
|
227
|
+
async delete({ nodeId }) {
|
|
228
|
+
await rm(nodeRunDir(nodeId), { recursive: true, force: true });
|
|
229
|
+
return null;
|
|
230
|
+
},
|
|
231
|
+
async viewer({ execution }) {
|
|
232
|
+
return { kind: 'unix', path: viewSocketPath(execution.nodeId) };
|
|
233
|
+
},
|
|
234
|
+
};
|
|
235
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export const MACHINE_OPS = ['start', 'wake', 'stop', 'status', 'delete', 'viewer', 'cron.run', 'cron.cancel', 'job.stop',
|
|
2
|
-
'worktree.create', 'worktree.rollback', 'worktree.close', 'worktree.abandon', 'worktree.finalize', 'repo.identify'];
|
|
2
|
+
'worktree.create', 'worktree.rollback', 'worktree.close', 'worktree.abandon', 'worktree.finalize', 'worktree.sweep', '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 {
|
|
5
5
|
environmentId;
|
|
@@ -314,6 +314,17 @@ export function paneLocation(pane) {
|
|
|
314
314
|
return null;
|
|
315
315
|
return { session: match[1], window: match[2] };
|
|
316
316
|
}
|
|
317
|
+
/** A pane's session and window and pane position, as a person counts them (`#{window_index}`, `#{pane_index}`). Null if the pane is gone or tmux fails. */
|
|
318
|
+
export function paneCoordinates(pane) {
|
|
319
|
+
// Space-separated like paneLocation: tmux -p escapes tabs and control characters. The window name is last, so it may hold spaces.
|
|
320
|
+
const r = tmux(['display-message', '-p', '-t', pane, '#{window_index} #{pane_index} #{session_name}@@@#{window_name}']);
|
|
321
|
+
if (!r.ok)
|
|
322
|
+
return null;
|
|
323
|
+
const match = /^(\d+) (\d+) (.+?)@@@(.*)$/s.exec(r.stdout);
|
|
324
|
+
if (match === null)
|
|
325
|
+
return null;
|
|
326
|
+
return { session: match[3], windowIndex: Number(match[1]), paneIndex: Number(match[2]), windowName: match[4] };
|
|
327
|
+
}
|
|
317
328
|
/** The index tmux shows for a window target (`#{window_index}`) — the number a
|
|
318
329
|
* person sees in the status line and presses after the prefix. Null if the
|
|
319
330
|
* target is gone or tmux fails. */
|
|
@@ -8,6 +8,10 @@ import { abandonWorktreeAndRepoint, getNode } from './canvas/index.js';
|
|
|
8
8
|
import { isCloudRole } from './canvas/person-state.js';
|
|
9
9
|
import { callMachine } from './runtime/runner/machine/call.js';
|
|
10
10
|
import { machineEnvironmentOfProfile } from './runtime/runner/machine/environment.js';
|
|
11
|
+
import { MachineOfflineError } from './runtime/runner/machine/ops.js';
|
|
12
|
+
import { findBrokers } from './runtime/runner/machine/executor.js';
|
|
13
|
+
import { deleteTrashAsync } from './worktree-remove.js';
|
|
14
|
+
import { sweepManagedWorktreeOnHost } from './worktree-sweep.js';
|
|
11
15
|
import { closeManagedWorktreeOnHost, concludedCloseResult, persistCloseOutcome } from './worktree-close.js';
|
|
12
16
|
import { abandonManagedWorktreeOnHost, createManagedWorktreeAsync, finalizeManagedWorktreeOnHost, rollbackManagedWorktreeAsync } from './worktree-mutation-async.js';
|
|
13
17
|
import { persistClosedWorktreeState, WorktreeError } from './worktree.js';
|
|
@@ -29,6 +33,13 @@ export const machineWorktreeHandlers = {
|
|
|
29
33
|
'worktree.close': (args) => answer(() => closeManagedWorktreeOnHost(args.nodeId, args.worktree)),
|
|
30
34
|
'worktree.abandon': (args) => answer(() => abandonManagedWorktreeOnHost(args.nodeId, args.worktree, args.by)),
|
|
31
35
|
'worktree.finalize': (args) => answer(() => finalizeManagedWorktreeOnHost(args.nodeId, args.worktree)),
|
|
36
|
+
// The node is still gone while no broker of it runs on this Mac, which owns its brokers.
|
|
37
|
+
// An unreadable process table counts as a running broker. The trash is deleted after the answer, so a large checkout cannot outlast the call.
|
|
38
|
+
'worktree.sweep': (args) => answer(async () => {
|
|
39
|
+
const swept = await sweepManagedWorktreeOnHost(args.worktree, { stillEligible: () => findBrokers().then((brokers) => !brokers.some((b) => b.node === args.nodeId), () => false) }, async () => args.dependentCwds);
|
|
40
|
+
void deleteTrashAsync(args.worktree.path, swept.trash);
|
|
41
|
+
return swept;
|
|
42
|
+
}),
|
|
32
43
|
};
|
|
33
44
|
// ---------------------------------------------------------------------------------------------------------------- the control plane's side
|
|
34
45
|
/** The machine environment that holds a node's checkouts: on a cloud role, the one its profile points at; else null (Git runs here). */
|
|
@@ -90,3 +101,12 @@ export async function finalizeManagedWorktreeOnMachine(environmentId, nodeId) {
|
|
|
90
101
|
}
|
|
91
102
|
return outcome.kind === 'open' ? { ...outcome, worktree: wt } : outcome;
|
|
92
103
|
}
|
|
104
|
+
/** The sweep's Git work on the Mac that holds the node's checkout; the lane writes the rows from the answer. */
|
|
105
|
+
export function sweepOnMachine(environmentId, nodeId) {
|
|
106
|
+
const none = { base: null, upstream: null, branch: null, checkout: null };
|
|
107
|
+
return (worktree, dependentCwds) => callWorktree(environmentId, 'worktree.sweep', { nodeId, worktree, dependentCwds }).catch((error) => ({
|
|
108
|
+
// Offline says nothing about the checkout: no refusal, no backoff. A lost or timed-out call is a failure, retried with backoff.
|
|
109
|
+
outcome: error instanceof MachineOfflineError ? { status: 'skipped', reason: 'machine_offline' } : { status: 'failed', reason: 'machine_call_failed', detail: error instanceof Error ? error.message : String(error) },
|
|
110
|
+
observed: none,
|
|
111
|
+
}));
|
|
112
|
+
}
|