@north-light/cli 0.3.709 → 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/clients/attach/input/capabilities.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/teardown.d.ts +2 -0
- package/dist/clients/attach/session/teardown.js +3 -3
- package/dist/clients/attach/slash/dispatch.js +2 -2
- package/dist/clients/attach/slash/recover.d.ts +10 -0
- package/dist/clients/attach/slash/recover.js +2 -0
- package/dist/clients/attach/viewer.js +504 -501
- 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/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/runtime/broker-request.d.ts +2 -0
- package/dist/core/runtime/broker-request.js +1 -1
- package/dist/core/runtime/broker.js +1 -1
- package/dist/core/runtime/model-swap.d.ts +2 -1
- package/dist/core/runtime/model-swap.js +1 -1
- package/dist/core/runtime/placement-tmux.d.ts +1 -1
- package/dist/core/runtime/placement-tmux.js +1 -1
- package/dist/core/runtime/runner/machine/call.js +2 -2
- package/dist/core/runtime/runner/machine/ops.d.ts +11 -1
- package/dist/core/runtime/runner/machine/ops.js +1 -1
- package/dist/core/runtime/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/handlers/nodes.js +1 -1
- package/dist/daemon/fleet.d.ts +1 -1
- package/dist/daemon/fleet.js +4 -4
- package/dist/daemon/reconcilers/managed-worktree-sweep.js +1 -1
- 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/clients/attach/input/capabilities.js +1 -0
- package/packages/crouter-api/dist/clients/attach/session/layout-record.js +52 -0
- package/packages/crouter-api/dist/clients/attach/session/teardown.js +2 -0
- package/packages/crouter-api/dist/clients/attach/slash/dispatch.js +12 -0
- package/packages/crouter-api/dist/clients/attach/slash/recover.js +111 -0
- package/packages/crouter-api/dist/clients/attach/viewer.js +9 -1
- package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
- 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/model-swap.js +2 -1
- package/packages/crouter-api/dist/core/runtime/placement-tmux.js +1 -1
- 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/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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.710",
|
|
4
4
|
"description": "crtr — agent runtime with memory, plugins, and marketplaces",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -157,8 +157,8 @@
|
|
|
157
157
|
},
|
|
158
158
|
"license": "UNLICENSED",
|
|
159
159
|
"dependencies": {
|
|
160
|
-
"@north-light/identity": "0.3.
|
|
161
|
-
"@north-light/plugin": "0.3.
|
|
160
|
+
"@north-light/identity": "0.3.710",
|
|
161
|
+
"@north-light/plugin": "0.3.710",
|
|
162
162
|
"@earendil-works/chord": "1.5.2",
|
|
163
163
|
"@earendil-works/pi-agent-core": "1.5.2",
|
|
164
164
|
"@earendil-works/pi-ai": "1.5.2",
|
|
@@ -92,6 +92,7 @@ export function viewerOperationForSlash(name, builtin, canvas) {
|
|
|
92
92
|
case 'tutorial': return 'engine-drive';
|
|
93
93
|
// These run local `crtr node …`, rewrite this machine's tmux titles, or read this machine's MCP config:
|
|
94
94
|
// with --canvas they would act on a same-id local node or local state, not the remote node.
|
|
95
|
+
case 'recover':
|
|
95
96
|
case 'promote':
|
|
96
97
|
case 'rename':
|
|
97
98
|
case 'mcp': return 'local-host';
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// session/layout-record.ts — one small file per viewed node recording where its viewer pane sits in tmux
|
|
2
|
+
// (session, window, pane position, cwd), so `/recover` can rebuild the viewer layout after a crash or
|
|
3
|
+
// reboot has taken the tmux server with it. This is machine-local tmux state, not canvas state: the
|
|
4
|
+
// daemon never reads it. A viewer rewrites its file whenever it starts or gains focus and deletes it only
|
|
5
|
+
// when the person detaches or the node finishes — a SIGHUP from a dying tmux server leaves it in place.
|
|
6
|
+
import { mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
7
|
+
import { join } from 'node:path';
|
|
8
|
+
import { runtimeRoot } from '../../../core/layout.js';
|
|
9
|
+
import { paneCoordinates } from '../../../core/runtime/placement-tmux.js';
|
|
10
|
+
function recordsDir() { return join(runtimeRoot(), 'viewer-panes'); }
|
|
11
|
+
function recordPath(nodeId) { return join(recordsDir(), `${nodeId}.json`); }
|
|
12
|
+
export function writeLayoutRecord(nodeId, pane, cwd) {
|
|
13
|
+
if (pane === undefined || pane === '')
|
|
14
|
+
return;
|
|
15
|
+
const where = paneCoordinates(pane);
|
|
16
|
+
if (where === null)
|
|
17
|
+
return;
|
|
18
|
+
const record = { nodeId, session: where.session, windowIndex: where.windowIndex, windowName: where.windowName, paneIndex: where.paneIndex, cwd, pane };
|
|
19
|
+
try {
|
|
20
|
+
mkdirSync(recordsDir(), { recursive: true });
|
|
21
|
+
writeFileSync(recordPath(nodeId), JSON.stringify(record));
|
|
22
|
+
}
|
|
23
|
+
catch { /* best-effort: a missing record only costs the recovery one pane */ }
|
|
24
|
+
}
|
|
25
|
+
/** Delete this node's record unless another viewer pane has since claimed it. */
|
|
26
|
+
export function removeLayoutRecord(nodeId, pane) {
|
|
27
|
+
try {
|
|
28
|
+
const current = JSON.parse(readFileSync(recordPath(nodeId), 'utf8'));
|
|
29
|
+
if (pane === undefined || current.pane === pane)
|
|
30
|
+
rmSync(recordPath(nodeId), { force: true });
|
|
31
|
+
}
|
|
32
|
+
catch { /* no record */ }
|
|
33
|
+
}
|
|
34
|
+
export function readLayoutRecords() {
|
|
35
|
+
let names;
|
|
36
|
+
try {
|
|
37
|
+
names = readdirSync(recordsDir());
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
return [];
|
|
41
|
+
}
|
|
42
|
+
const records = [];
|
|
43
|
+
for (const name of names) {
|
|
44
|
+
if (!name.endsWith('.json'))
|
|
45
|
+
continue;
|
|
46
|
+
try {
|
|
47
|
+
records.push(JSON.parse(readFileSync(join(recordsDir(), name), 'utf8')));
|
|
48
|
+
}
|
|
49
|
+
catch { /* skip a torn file */ }
|
|
50
|
+
}
|
|
51
|
+
return records;
|
|
52
|
+
}
|
|
@@ -55,6 +55,8 @@ export function createTeardown(s, hooks) {
|
|
|
55
55
|
if (reason === 'detach')
|
|
56
56
|
socket.send({ type: 'bye' });
|
|
57
57
|
socket.close();
|
|
58
|
+
if (reason === 'detach' || reason === 'node-done')
|
|
59
|
+
hooks.forgetLayout();
|
|
58
60
|
restore();
|
|
59
61
|
// A clean detach leaves the broker running (the engine runs on) — the
|
|
60
62
|
// documented "detach leaves the broker running" contract. Teardown reaps
|
|
@@ -26,6 +26,7 @@ import { BUILTIN_SLASH_COMMANDS } from '../../../core/runtime/pi-vendored.js';
|
|
|
26
26
|
import { surfaceTmuxStyleArgs } from '../../../core/runtime/surface-bg.js';
|
|
27
27
|
import { crouterMenuTmuxArgs } from '../../../core/runtime/tmux-bindings.js';
|
|
28
28
|
import { viewerOperationForSlash } from '../input/capabilities.js';
|
|
29
|
+
import { formatReport, recover } from './recover.js';
|
|
29
30
|
import { shellQuote } from '../../../shared/shell-quote.js';
|
|
30
31
|
/** Canvas slash-commands — implemented NATIVE in the viewer, the ONLY live host:
|
|
31
32
|
* the broker binds mode:'rpc', so broker pi-extensions never run their
|
|
@@ -49,6 +50,7 @@ export const CANVAS_SLASH_COMMANDS = [
|
|
|
49
50
|
{ name: 'mcp', description: 'MCP servers — status from the adapter’s config/cache; Enter (or /mcp <server>) connects, reconnects, or re-auths' },
|
|
50
51
|
{ name: 'rename', description: 'Rename this node everywhere — node row, viewer window, session chip, tmux pane: /rename <name>' },
|
|
51
52
|
{ name: 'color', description: 'Color this node — tmux pane outline + name chip: /color <color> (red, blue, #rrggbb, …) or /color none' },
|
|
53
|
+
{ name: 'recover', description: 'After a crash or reboot: revive every disconnected node and rebuild the tmux viewer panes that were open' },
|
|
52
54
|
{ name: 'mouse', description: 'Toggle mouse wheel scrolling and drag-select — off restores tmux drag-select and copy-mode mouse' },
|
|
53
55
|
{ name: 'copy-message', description: 'Copy the newest message visible in the transcript viewport' },
|
|
54
56
|
{ name: 'copy-tool', description: 'Copy the newest tool call output' },
|
|
@@ -407,6 +409,16 @@ function dispatchCanvasCommand(name, arg, ctx) {
|
|
|
407
409
|
else
|
|
408
410
|
ctx.notify('Verbosity is not wired into this viewer');
|
|
409
411
|
return true;
|
|
412
|
+
case 'recover':
|
|
413
|
+
if (arg)
|
|
414
|
+
return usage(ctx, '/recover — no argument');
|
|
415
|
+
if (process.env['TMUX'] === undefined) {
|
|
416
|
+
ctx.notify('/recover needs tmux');
|
|
417
|
+
return true;
|
|
418
|
+
}
|
|
419
|
+
ctx.notify('Recovering — reviving nodes and rebuilding panes…');
|
|
420
|
+
recover().then((report) => ctx.notify(formatReport(report)), (err) => ctx.notify(`recover failed: ${err instanceof Error ? err.message : String(err)}`));
|
|
421
|
+
return true;
|
|
410
422
|
case 'mouse':
|
|
411
423
|
// Viewer-local render state only — no frame, no CLI, no node mutation.
|
|
412
424
|
if (ctx.onToggleMouse)
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// slash/recover.ts — `/recover`: after a crash or reboot, revive every disconnected node and rebuild the
|
|
2
|
+
// tmux viewer layout. The layout comes from the per-viewer records in session/layout-record.ts; when none
|
|
3
|
+
// exist it falls back to the nodes whose viewers the daemon logged opening in the last hour.
|
|
4
|
+
import { existsSync, statSync, openSync, readSync, closeSync } from 'node:fs';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
import { routes } from '../../../api/index.js';
|
|
7
|
+
import { cliClient } from '../../../commands/api-client.js';
|
|
8
|
+
import { runtimeRoot } from '../../../core/layout.js';
|
|
9
|
+
import { liveViewerPanes } from '../../../core/runtime/tmux-driver.js';
|
|
10
|
+
import { openViewerPane, selectLayout } from '../../../core/runtime/placement-tmux.js';
|
|
11
|
+
import { readLayoutRecords } from '../session/layout-record.js';
|
|
12
|
+
const LOG_TAIL_BYTES = 8 * 1024 * 1024;
|
|
13
|
+
const FALLBACK_WINDOW_MS = 60 * 60_000;
|
|
14
|
+
/** Node ids of viewers the daemon logged opening within the last hour, oldest first. */
|
|
15
|
+
function recentViewOpens(now) {
|
|
16
|
+
const path = join(runtimeRoot(), 'crtrd.log');
|
|
17
|
+
if (!existsSync(path))
|
|
18
|
+
return [];
|
|
19
|
+
const size = statSync(path).size;
|
|
20
|
+
const start = Math.max(0, size - LOG_TAIL_BYTES);
|
|
21
|
+
const buf = Buffer.alloc(size - start);
|
|
22
|
+
const fd = openSync(path, 'r');
|
|
23
|
+
try {
|
|
24
|
+
readSync(fd, buf, 0, buf.length, start);
|
|
25
|
+
}
|
|
26
|
+
finally {
|
|
27
|
+
closeSync(fd);
|
|
28
|
+
}
|
|
29
|
+
const ids = [];
|
|
30
|
+
for (const line of buf.toString('utf8').split('\n')) {
|
|
31
|
+
if (!line.includes('daemon.timing.view_open_received'))
|
|
32
|
+
continue;
|
|
33
|
+
try {
|
|
34
|
+
const e = JSON.parse(line);
|
|
35
|
+
if (e.event === 'daemon.timing.view_open_received' && e.node_id !== undefined && now - Date.parse(e.ts) <= FALLBACK_WINDOW_MS && !ids.includes(e.node_id))
|
|
36
|
+
ids.push(e.node_id);
|
|
37
|
+
}
|
|
38
|
+
catch { /* partial first line of the tail */ }
|
|
39
|
+
}
|
|
40
|
+
return ids;
|
|
41
|
+
}
|
|
42
|
+
export async function recover(now = Date.now()) {
|
|
43
|
+
const client = cliClient();
|
|
44
|
+
const result = await client.request('POST', routes.reviveAll());
|
|
45
|
+
const failedIds = new Set(result.failed.map((f) => f.node_id));
|
|
46
|
+
const report = {
|
|
47
|
+
revived: result.revived.length,
|
|
48
|
+
failed: result.failed.map((f) => `${f.node_id}: ${f.error}`),
|
|
49
|
+
frozen: result.frozen.length, panes: 0, skipped: 0, source: 'none',
|
|
50
|
+
};
|
|
51
|
+
let records = readLayoutRecords();
|
|
52
|
+
if (records.length > 0)
|
|
53
|
+
report.source = 'snapshot';
|
|
54
|
+
else {
|
|
55
|
+
const nodes = recentViewOpens(now);
|
|
56
|
+
if (nodes.length > 0)
|
|
57
|
+
report.source = 'recent views';
|
|
58
|
+
// One session per project directory, one window per node.
|
|
59
|
+
records = [];
|
|
60
|
+
for (const nodeId of nodes)
|
|
61
|
+
records.push({ nodeId, session: '', windowIndex: records.length, windowName: '', paneIndex: 0, cwd: '', pane: '' });
|
|
62
|
+
}
|
|
63
|
+
const viewed = new Set(liveViewerPanes().map((p) => p.nodeId));
|
|
64
|
+
const targets = [];
|
|
65
|
+
for (const rec of records) {
|
|
66
|
+
if (viewed.has(rec.nodeId) || failedIds.has(rec.nodeId)) {
|
|
67
|
+
report.skipped++;
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
try {
|
|
71
|
+
const node = await client.getNode(rec.nodeId);
|
|
72
|
+
if (node.status === 'done' || node.status === 'canceled' || node.final_report != null) {
|
|
73
|
+
report.skipped++;
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
const cwd = rec.cwd === '' ? node.cwd : rec.cwd;
|
|
77
|
+
const session = rec.session === '' ? (cwd.split('/').filter(Boolean).pop() ?? 'crtr') : rec.session;
|
|
78
|
+
targets.push({ ...rec, cwd, session, windowName: rec.windowName === '' ? node.name : rec.windowName });
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
report.skipped++;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
targets.sort((a, b) => a.session.localeCompare(b.session) || a.windowIndex - b.windowIndex || a.paneIndex - b.paneIndex);
|
|
85
|
+
const firstPane = new Map();
|
|
86
|
+
for (const t of targets) {
|
|
87
|
+
const key = `${t.session}\t${t.windowIndex}`;
|
|
88
|
+
const beside = firstPane.get(key);
|
|
89
|
+
const opened = openViewerPane(t.nodeId, t.session, { name: t.windowName, cwd: t.cwd, waitForBroker: true, ...(beside === undefined ? {} : { besidePane: beside }) });
|
|
90
|
+
if (opened === null) {
|
|
91
|
+
report.failed.push(`${t.nodeId}: tmux refused to open a pane`);
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
if (beside === undefined)
|
|
95
|
+
firstPane.set(key, opened.pane);
|
|
96
|
+
else if (opened.window !== null)
|
|
97
|
+
selectLayout(opened.window, 'even-horizontal');
|
|
98
|
+
report.panes++;
|
|
99
|
+
}
|
|
100
|
+
return report;
|
|
101
|
+
}
|
|
102
|
+
export function formatReport(r) {
|
|
103
|
+
const parts = [`revived ${r.revived}`, `${r.panes} pane${r.panes === 1 ? '' : 's'} recreated (${r.source})`];
|
|
104
|
+
if (r.frozen > 0)
|
|
105
|
+
parts.push(`${r.frozen} waiting for broker slots`);
|
|
106
|
+
if (r.skipped > 0)
|
|
107
|
+
parts.push(`${r.skipped} skipped (already viewed, finished, or not revivable)`);
|
|
108
|
+
if (r.failed.length > 0)
|
|
109
|
+
parts.push(`${r.failed.length} failed: ${r.failed.join('; ')}`);
|
|
110
|
+
return `Recovered — ${parts.join(', ')}`;
|
|
111
|
+
}
|
|
@@ -63,6 +63,7 @@ import { createLayout } from './session/layout.js';
|
|
|
63
63
|
import { createEditorInventory } from './session/editor-inventory.js';
|
|
64
64
|
import { createFrecencyStore } from './input/completion-frecency.js';
|
|
65
65
|
import { createNodeIdentity } from './session/identity.js';
|
|
66
|
+
import { removeLayoutRecord, writeLayoutRecord } from './session/layout-record.js';
|
|
66
67
|
import { createPaneTag } from './session/pane-tag.js';
|
|
67
68
|
import { launchProfileFileSearch, relatedNodes } from './session/profile-files.js';
|
|
68
69
|
import { createSessionStateSync } from './session/state-sync.js';
|
|
@@ -671,6 +672,8 @@ onConnected) {
|
|
|
671
672
|
(observer ? ' --observer' : '') +
|
|
672
673
|
(canvasName !== undefined ? ` --canvas ${quoteIfNeeded(canvasName)}` : ''),
|
|
673
674
|
tagPane: paneTag.pane,
|
|
675
|
+
forgetLayout: () => { if (!remote && ctx.nodeId !== '')
|
|
676
|
+
removeLayoutRecord(ctx.nodeId, paneTag.pane()); },
|
|
674
677
|
});
|
|
675
678
|
const teardown = lifecycle.teardown;
|
|
676
679
|
let startupFailure;
|
|
@@ -700,6 +703,8 @@ onConnected) {
|
|
|
700
703
|
},
|
|
701
704
|
});
|
|
702
705
|
paneTag.set();
|
|
706
|
+
if (!remote && ctx.nodeId !== '')
|
|
707
|
+
writeLayoutRecord(ctx.nodeId, paneTag.pane(), meta.cwd);
|
|
703
708
|
// 5. Lay out and paint; the broker connection follows (`dialBroker`).
|
|
704
709
|
layout.mount();
|
|
705
710
|
// Synchronous with tui.start(): the caller's screen gives the terminal back and the viewer takes it in the same tick, with no cooked-mode gap.
|
|
@@ -804,8 +809,11 @@ onConnected) {
|
|
|
804
809
|
detachHint: () => detachHint(crouterBindings),
|
|
805
810
|
hasExclusiveSurface: () => surfaceHost.hasFullPaneSurface(),
|
|
806
811
|
setPaneFocused: (focused) => {
|
|
807
|
-
if (focused)
|
|
812
|
+
if (focused) {
|
|
808
813
|
paneTag.stamp();
|
|
814
|
+
if (!remote && ctx.nodeId !== '')
|
|
815
|
+
writeLayoutRecord(ctx.nodeId, paneTag.pane(), meta.cwd);
|
|
816
|
+
}
|
|
809
817
|
paneFocus.setPaneFocused(focused);
|
|
810
818
|
tui.requestRender();
|
|
811
819
|
},
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
/** The canvas schema version this build supports: the number of the highest delta in `schema-pg/` (the baseline
|
|
7
7
|
* `schema-pg.sql` is version 1). `scripts/install-runtime.mjs` reads this module from a candidate generation to refuse
|
|
8
8
|
* one below the live database's `schema_min_reader`. */
|
|
9
|
-
export const CANVAS_SCHEMA_VERSION =
|
|
9
|
+
export const CANVAS_SCHEMA_VERSION = 28;
|
|
10
10
|
/** The Postgres schema holding the canvas tables: `CRTR_DATABASE_SCHEMA` (`crtr` in the cloud deploy). Unset or empty
|
|
11
11
|
* means the role's own search_path (`public` on a Mac and on a VM). A name that is not a plain identifier is an error:
|
|
12
12
|
* it is put in a `search_path` connection option. */
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// A broker declares its owning canvas in argv at spawn:
|
|
2
|
+
// `broker-cli.js --canvas-home <home> --epoch <id> <nodeId>`.
|
|
3
|
+
// Untagged brokers and brokers of another home are not ours to count or kill.
|
|
4
|
+
export function brokerCommandDeclaresCanvasHome(command, home) {
|
|
5
|
+
return command.includes(` --canvas-home ${home} `);
|
|
6
|
+
}
|
|
@@ -35,7 +35,7 @@ export class BrokerUnreachableError extends Error {
|
|
|
35
35
|
export function oneShotControllerRequest(opts) {
|
|
36
36
|
return new Promise(async (resolve, reject) => {
|
|
37
37
|
// A daemon-internal controller: its connect outcome says nothing about any person's viewer, so it records no viewer fault.
|
|
38
|
-
const client = new BrokerClient(opts.nodeId, { transport: new SocketTransport(opts.nodeId, { recordsViewerFaults: false }) });
|
|
38
|
+
const client = new BrokerClient(opts.nodeId, { transport: opts.transport ?? new SocketTransport(opts.nodeId, { recordsViewerFaults: false }) });
|
|
39
39
|
const clientId = randomUUID();
|
|
40
40
|
const frameId = randomUUID();
|
|
41
41
|
let settled = false;
|
|
@@ -29,11 +29,12 @@ export function isBrokerLive(node) {
|
|
|
29
29
|
* `intent` is the routing contract the CALLER derived from the RAW token
|
|
30
30
|
* (`explicitModelIntent`); `spec` is already normalized, so its shape no longer
|
|
31
31
|
* says whether the pick was portable. Undefined means an exact model. */
|
|
32
|
-
export function setModelLive(nodeId, spec, intent) {
|
|
32
|
+
export function setModelLive(nodeId, spec, intent, transport) {
|
|
33
33
|
// `set_model` carries no frame id, so the ack is matched on `for` alone.
|
|
34
34
|
let resolvedSpec;
|
|
35
35
|
return oneShotControllerRequest({
|
|
36
36
|
nodeId,
|
|
37
|
+
transport,
|
|
37
38
|
what: 'the model switch',
|
|
38
39
|
ackFor: 'set_model',
|
|
39
40
|
frame: () => ({ type: 'set_model', model: spec, ...(intent !== undefined ? { intent } : {}) }),
|
|
@@ -20,7 +20,7 @@ import { paneLocation, ensureSession, openNodeWindow, splitWindow, selectLayout,
|
|
|
20
20
|
import { BROKER_VIEW_SOCKET_WAIT_MS } from './view-socket.js';
|
|
21
21
|
// Re-export the pure tmux driver verbs the CLI/viewer consumers need without
|
|
22
22
|
// exposing the canvas focuses table or sending command modules to the raw driver.
|
|
23
|
-
export { paneExists, paneLocation, paneOfNode, paneCurrentPath, paneSize, paneRunning, ensureSession, openNodeWindow, splitWindow, closePane, currentTmux, switchClient, selectWindow, selectLayout, selectPane, getPaneOption, setPaneOption, breakPane, inTmux, piCommand, shellQuote, renameWindow, displayPopup, displayPopupAsync, windowOfPane, respawnPaneSync, respawnPaneInBackground, runShellInBackground, paneStartCommand, swapPanes, paneCurrentCommand, closeWindow, windowAlive, listLivePanes, VIEWER_STAMP_OPTION, stampViewerPaneAsync, liveViewerPanes, sendAttachControl, displayClientMessage, displayMessage, windowIndex, sessionExists, tmuxAvailable, tmuxInteractive, } from './tmux-driver.js';
|
|
23
|
+
export { paneExists, paneLocation, paneCoordinates, paneOfNode, paneCurrentPath, paneSize, paneRunning, ensureSession, openNodeWindow, splitWindow, closePane, currentTmux, switchClient, selectWindow, selectLayout, selectPane, getPaneOption, setPaneOption, breakPane, inTmux, piCommand, shellQuote, renameWindow, displayPopup, displayPopupAsync, windowOfPane, respawnPaneSync, respawnPaneInBackground, runShellInBackground, paneStartCommand, swapPanes, paneCurrentCommand, closeWindow, windowAlive, listLivePanes, VIEWER_STAMP_OPTION, stampViewerPaneAsync, liveViewerPanes, sendAttachControl, displayClientMessage, displayMessage, windowIndex, sessionExists, tmuxAvailable, tmuxInteractive, } from './tmux-driver.js';
|
|
24
24
|
export { installTmuxBindings } from './tmux-bindings.js';
|
|
25
25
|
// view.sock readiness — the one shared broker-cold-start primitive
|
|
26
26
|
export { BROKER_VIEW_SOCKET_WAIT_MS, waitForBrokerViewSocket } from './view-socket.js';
|
|
@@ -12,7 +12,7 @@ import { MachineCallFailedError, MachineLostError, MachineOfflineError } from '.
|
|
|
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
14
|
start: 60, wake: 15, stop: 15, status: 15, delete: 15, viewer: 15, 'cron.run': 15, 'cron.cancel': 15, 'job.stop': 15,
|
|
15
|
-
'worktree.create': 60, 'worktree.rollback': 60, 'worktree.close': 60, 'worktree.abandon': 60, 'worktree.finalize': 60,
|
|
15
|
+
'worktree.create': 60, 'worktree.rollback': 60, 'worktree.close': 60, 'worktree.abandon': 60, 'worktree.finalize': 60, 'worktree.sweep': 60,
|
|
16
16
|
'repo.identify': 15,
|
|
17
17
|
};
|
|
18
18
|
const REREAD_MS = 1000;
|
|
@@ -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. */
|