@ulm0/gonogo 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/README.md +30 -2
- package/bin/gonogo.js +18 -0
- package/dist/client/THIRD-PARTY-NOTICES.md +409 -0
- package/dist/client/apple-touch-icon.png +0 -0
- package/dist/client/assets/doto-latin-900-normal-D1bF_x6I.woff +0 -0
- package/dist/client/assets/geist-latin-400-normal-B40WzpMT.woff2 +0 -0
- package/dist/client/assets/geist-latin-400-normal-akEymXtG.woff +0 -0
- package/dist/client/assets/geist-latin-500-normal-BDXIbFrL.woff +0 -0
- package/dist/client/assets/geist-latin-500-normal-CTWBw9NS.woff2 +0 -0
- package/dist/client/assets/geist-latin-600-normal-CSETrqM2.woff2 +0 -0
- package/dist/client/assets/geist-latin-600-normal-DsPlZH-9.woff +0 -0
- package/dist/client/assets/geist-mono-latin-400-normal-B2yvC1Cq.woff +0 -0
- package/dist/client/assets/geist-mono-latin-400-normal-DTRLJnHl.woff2 +0 -0
- package/dist/client/assets/geist-mono-latin-500-normal-D-GG86Jb.woff +0 -0
- package/dist/client/assets/geist-mono-latin-500-normal-YINYabwD.woff2 +0 -0
- package/dist/client/assets/geist-mono-latin-600-normal-V-KvD_pi.woff2 +0 -0
- package/dist/client/assets/geist-mono-latin-600-normal-bZn07FKM.woff +0 -0
- package/dist/client/assets/index-B6MsSoeo.css +1 -0
- package/dist/client/assets/index-DRtiRh1Y.js +31 -0
- package/dist/client/favicon.ico +0 -0
- package/dist/client/favicon.svg +1 -0
- package/dist/client/index.html +19 -0
- package/dist/server/cleanroom.js +214 -0
- package/dist/server/cli.js +630 -0
- package/dist/server/command.js +44 -0
- package/dist/server/constants.js +427 -0
- package/dist/server/docking.js +541 -0
- package/dist/server/downlink.js +191 -0
- package/dist/server/home.js +497 -0
- package/dist/server/hooks.js +166 -0
- package/dist/server/hub.js +2484 -0
- package/dist/server/launcher.js +542 -0
- package/dist/server/livery.js +210 -0
- package/dist/server/logsearch.js +112 -0
- package/dist/server/mcp.js +196 -0
- package/dist/server/migrate.js +119 -0
- package/dist/server/missionlog.js +209 -0
- package/dist/server/payload.js +168 -0
- package/dist/server/propellant.js +314 -0
- package/dist/server/providers.js +137 -0
- package/dist/server/relay.js +300 -0
- package/dist/server/relaykinds.js +182 -0
- package/dist/server/schedules.js +277 -0
- package/dist/server/tasks.js +272 -0
- package/dist/server/terminal.js +635 -0
- package/dist/server/uplinks.js +356 -0
- package/dist/server/web.js +1466 -0
- package/dist/shared/cron.js +149 -0
- package/dist/shared/fuel.js +18 -0
- package/dist/shared/livery.js +348 -0
- package/dist/shared/positions.js +132 -0
- package/dist/shared/protocol.js +212 -0
- package/package.json +84 -3
|
@@ -0,0 +1,635 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Terminal host (contract section 6): one pty and one headless mirror per agent name. The mirror is what the hub reads
|
|
3
|
+
* (prompt box, dialogs, title) and what a joining browser is served; everything that depends on how claude draws its
|
|
4
|
+
* screen lives here. No method of the host throws after spawn(): a pty call that fails returns false.
|
|
5
|
+
*/
|
|
6
|
+
import { accessSync, chmodSync, constants as fsConstants, existsSync, readdirSync, statSync } from 'node:fs';
|
|
7
|
+
import { createRequire } from 'node:module';
|
|
8
|
+
import { dirname, join, resolve } from 'node:path';
|
|
9
|
+
import { spawn as ptySpawn } from '@lydell/node-pty';
|
|
10
|
+
import { SerializeAddon } from '@xterm/addon-serialize';
|
|
11
|
+
import xtermHeadless from '@xterm/headless';
|
|
12
|
+
import { BOX_MAX_ROWS, DEFAULT_COLS, DEFAULT_ROWS, DIALOG_PATTERNS, ENTER, EXIT_TAIL_CHARS, EXIT_TAIL_LINES, MAX_COLS, MAX_ROWS, MIN_COLS, MIN_ROWS, MIRROR_SCROLLBACK_LINES, NBSP, PASTE_END, PASTE_START, POINTER_PREFIX, PROMPT_GLYPH, RULE_CHAR, RULE_MIN_RUN, SNAPSHOT_SCROLLBACK_LINES, STOP_GIVEUP_AFTER_KILL_MS, STOP_KILL_AFTER_MS, TERM_VALUE, TITLE_IDLE_GLYPH, TITLE_WORKING_GLYPHS, nullLogger, } from './constants.js';
|
|
13
|
+
// The package is CommonJS: the named import is undefined in plain Node ESM (vitest and tsc accept it, which hides that).
|
|
14
|
+
const { Terminal } = xtermHeadless;
|
|
15
|
+
/** A pointer is one short line; anything longer is not one (contract 6.7). */
|
|
16
|
+
const SUBMIT_MAX_CHARS = 500;
|
|
17
|
+
/** What execvp falls back to when the child environment has no PATH. */
|
|
18
|
+
const FALLBACK_PATH = '/usr/bin:/bin:/usr/sbin:/sbin';
|
|
19
|
+
/* ---- screen analysis (6.4) ---- */
|
|
20
|
+
const RULE_RUN = new RegExp(`${RULE_CHAR}{${RULE_MIN_RUN},}`);
|
|
21
|
+
const BOX_PREFIX = PROMPT_GLYPH + NBSP;
|
|
22
|
+
const DIALOGS = DIALOG_PATTERNS.map(({ kind, source }) => ({ kind, regex: new RegExp(source) }));
|
|
23
|
+
/** The lowest row that is a prompt row between two rules, or -1. The lowest is the live box, not an echo in the transcript. */
|
|
24
|
+
function findPromptBox(rows) {
|
|
25
|
+
for (let y = rows.length - 1; y >= 1; y--) {
|
|
26
|
+
if (!rows[y].startsWith(BOX_PREFIX) || !RULE_RUN.test(rows[y - 1]))
|
|
27
|
+
continue;
|
|
28
|
+
for (let k = 1; k <= BOX_MAX_ROWS && y + k < rows.length; k++) {
|
|
29
|
+
if (RULE_RUN.test(rows[y + k]))
|
|
30
|
+
return y;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return -1;
|
|
34
|
+
}
|
|
35
|
+
function findDialog(lines) {
|
|
36
|
+
const hasMenu = () => DIALOGS.some((d) => d.kind === 'menu' && lines.some((line) => d.regex.test(line)));
|
|
37
|
+
for (const { kind, regex } of DIALOGS) {
|
|
38
|
+
if (!lines.some((line) => regex.test(line)))
|
|
39
|
+
continue;
|
|
40
|
+
// "Do you want to ..." without a numbered menu is assistant prose, not a permission dialog.
|
|
41
|
+
if (kind === 'permission' && !hasMenu())
|
|
42
|
+
continue;
|
|
43
|
+
return kind;
|
|
44
|
+
}
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
/** `rows` are the visible rows of the active buffer as xterm returns them (the NBSP of an empty box row must survive). */
|
|
48
|
+
export function analyzeScreen(rows, cols) {
|
|
49
|
+
const boxRow = findPromptBox(rows);
|
|
50
|
+
// The box row is left out of the dialog search: a draft or placeholder in the box must never look like a dialog.
|
|
51
|
+
const lines = rows.map((row, y) => (y === boxRow ? '' : row.trimEnd()));
|
|
52
|
+
return {
|
|
53
|
+
cols,
|
|
54
|
+
rows: rows.length,
|
|
55
|
+
promptBox: boxRow >= 0,
|
|
56
|
+
dialog: findDialog(lines),
|
|
57
|
+
promptText: boxRow >= 0 ? rows[boxRow].slice(BOX_PREFIX.length).trim() : null,
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
/* ---- window title (6.5) ---- */
|
|
61
|
+
export function classifyTitle(title) {
|
|
62
|
+
const first = title.trimStart().charAt(0);
|
|
63
|
+
if (first === TITLE_IDLE_GLYPH)
|
|
64
|
+
return 'idle';
|
|
65
|
+
return TITLE_WORKING_GLYPHS.includes(first) ? 'working' : 'unknown';
|
|
66
|
+
}
|
|
67
|
+
/* ---- typing (6.7) ---- */
|
|
68
|
+
// C0 controls except tab and line feed (carriage returns are turned into line feeds first), DEL, C1, then the characters
|
|
69
|
+
// Claude Code strips itself: zero-width, bidi and tag characters.
|
|
70
|
+
const UNSAFE_IN_PASTE = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u{200b}-\u{200f}\u{202a}-\u{202e}\u{2060}-\u{2064}\u{2066}-\u{2069}\u{feff}\u{e0000}-\u{e007f}]/gu;
|
|
71
|
+
/** Removing ESC is what stops a message from ending the paste with ESC[201~ and typing keys. */
|
|
72
|
+
export function sanitizeForPaste(text) {
|
|
73
|
+
return text.replace(/\r\n?/g, '\n').replace(UNSAFE_IN_PASTE, '').trim();
|
|
74
|
+
}
|
|
75
|
+
export function buildSubmit(text) {
|
|
76
|
+
return PASTE_START + sanitizeForPaste(text) + PASTE_END + ENTER;
|
|
77
|
+
}
|
|
78
|
+
/* ---- terminal modes that serialize() does not carry (6.6) ---- */
|
|
79
|
+
const MODE_SEQUENCE = /\x1b\[\?([0-9;]*)([hl])/g;
|
|
80
|
+
const UNFINISHED_MODE_SEQUENCE = /^\x1b(?:\[(?:\?[0-9;]*)?)?$/;
|
|
81
|
+
const MAX_UNFINISHED_BYTES = 32;
|
|
82
|
+
/** Order of fixup(): SGR mouse encoding, colour-scheme reports, cursor visibility. */
|
|
83
|
+
const TRACKED_MODES = [1006, 2031, 25];
|
|
84
|
+
const asLatin1 = (chunk) => typeof chunk === 'string' ? chunk : Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength).toString('latin1');
|
|
85
|
+
/**
|
|
86
|
+
* Remembers the last `ESC [ ? n h|l` of three modes in the raw output. xterm's serialize() restores bracketed paste,
|
|
87
|
+
* mouse tracking and the alternate screen but not these three, and a joining browser would get the wrong mouse encoding.
|
|
88
|
+
* Arrow fields, not methods: no `this`, so a method may be passed on detached.
|
|
89
|
+
*/
|
|
90
|
+
export class ModeTracker {
|
|
91
|
+
last = new Map();
|
|
92
|
+
tail = '';
|
|
93
|
+
feed = (chunk) => {
|
|
94
|
+
const text = this.tail + asLatin1(chunk);
|
|
95
|
+
for (const match of text.matchAll(MODE_SEQUENCE)) {
|
|
96
|
+
for (const param of match[1].split(';')) {
|
|
97
|
+
const mode = Number(param);
|
|
98
|
+
if (param !== '' && TRACKED_MODES.includes(mode))
|
|
99
|
+
this.last.set(mode, match[2] === 'h');
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
// A sequence may be cut by the chunk boundary: keep what could still become one.
|
|
103
|
+
const esc = text.lastIndexOf('\x1b');
|
|
104
|
+
const rest = esc < 0 ? '' : text.slice(esc);
|
|
105
|
+
this.tail = rest.length <= MAX_UNFINISHED_BYTES && UNFINISHED_MODE_SEQUENCE.test(rest) ? rest : '';
|
|
106
|
+
};
|
|
107
|
+
fixup = () => TRACKED_MODES.filter((mode) => this.last.has(mode))
|
|
108
|
+
.map((mode) => `\x1b[?${mode}${this.last.get(mode) ? 'h' : 'l'}`)
|
|
109
|
+
.join('');
|
|
110
|
+
}
|
|
111
|
+
/* ---- spawn-helper guard (6.10) ---- */
|
|
112
|
+
const require = createRequire(import.meta.url);
|
|
113
|
+
const errorMessage = (error) => (error instanceof Error ? error.message : String(error));
|
|
114
|
+
const errorCode = (error) => typeof error === 'object' && error !== null && 'code' in error ? String(error.code) : undefined;
|
|
115
|
+
function resolveQuietly(specifier, log) {
|
|
116
|
+
try {
|
|
117
|
+
return require.resolve(specifier);
|
|
118
|
+
}
|
|
119
|
+
catch (error) {
|
|
120
|
+
log.debug(`${specifier} is not installed: ${errorMessage(error)}`);
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
/** Package directories of the pty libraries that may be installed. `<package>/package.json` is not exported by the @lydell packages. */
|
|
125
|
+
function ptyPackageDirs(log) {
|
|
126
|
+
const dirs = [];
|
|
127
|
+
const platformEntry = resolveQuietly(`@lydell/node-pty-${process.platform}-${process.arch}`, log);
|
|
128
|
+
if (platformEntry !== null)
|
|
129
|
+
dirs.push(dirname(dirname(platformEntry))); // <pkg>/lib/index.js
|
|
130
|
+
const official = resolveQuietly('node-pty/package.json', log);
|
|
131
|
+
if (official !== null)
|
|
132
|
+
dirs.push(dirname(official));
|
|
133
|
+
return dirs;
|
|
134
|
+
}
|
|
135
|
+
function helperPaths(packageDir) {
|
|
136
|
+
const candidates = [join(packageDir, 'build', 'Release', 'spawn-helper')];
|
|
137
|
+
const prebuilds = join(packageDir, 'prebuilds');
|
|
138
|
+
if (existsSync(prebuilds)) {
|
|
139
|
+
for (const entry of readdirSync(prebuilds, { withFileTypes: true })) {
|
|
140
|
+
if (entry.isDirectory())
|
|
141
|
+
candidates.push(join(prebuilds, entry.name, 'spawn-helper'));
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return candidates.filter((path) => existsSync(path));
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* node-pty 1.1.0 ships its macOS spawn-helper without the executable bit, and then every spawn fails with
|
|
148
|
+
* "posix_spawnp failed". Returns the paths it fixed; a file it cannot change is logged and left alone.
|
|
149
|
+
*/
|
|
150
|
+
export function ensureSpawnHelperExecutable(log = nullLogger, roots) {
|
|
151
|
+
const fixed = [];
|
|
152
|
+
for (const packageDir of roots ?? ptyPackageDirs(log)) {
|
|
153
|
+
let helpers = [];
|
|
154
|
+
try {
|
|
155
|
+
helpers = helperPaths(packageDir);
|
|
156
|
+
}
|
|
157
|
+
catch (error) {
|
|
158
|
+
log.warn(`cannot look for spawn-helper in ${packageDir}: ${errorMessage(error)}`);
|
|
159
|
+
}
|
|
160
|
+
for (const helper of helpers) {
|
|
161
|
+
try {
|
|
162
|
+
const mode = statSync(helper).mode;
|
|
163
|
+
if ((mode & 0o111) !== 0) {
|
|
164
|
+
log.debug(`spawn-helper is executable: ${helper}`);
|
|
165
|
+
continue;
|
|
166
|
+
}
|
|
167
|
+
chmodSync(helper, (mode & 0o7777) | 0o755);
|
|
168
|
+
fixed.push(helper);
|
|
169
|
+
log.info(`made spawn-helper executable: ${helper}`);
|
|
170
|
+
}
|
|
171
|
+
catch (error) {
|
|
172
|
+
log.warn(`cannot make spawn-helper executable: ${helper}: ${errorMessage(error)}`);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
return fixed;
|
|
177
|
+
}
|
|
178
|
+
let helperChecked = false;
|
|
179
|
+
const isLive = (rec) => rec.running && !rec.exited;
|
|
180
|
+
const clampDim = (value, min, max, fallback) => {
|
|
181
|
+
const n = value !== undefined && Number.isFinite(value) ? Math.trunc(value) : fallback;
|
|
182
|
+
return Math.min(max, Math.max(min, n));
|
|
183
|
+
};
|
|
184
|
+
function viewportRows(mirror) {
|
|
185
|
+
const buffer = mirror.buffer.active;
|
|
186
|
+
const rows = [];
|
|
187
|
+
for (let y = 0; y < mirror.rows; y++)
|
|
188
|
+
rows.push(buffer.getLine(buffer.viewportY + y)?.translateToString(true) ?? '');
|
|
189
|
+
return rows;
|
|
190
|
+
}
|
|
191
|
+
function exitTail(mirror) {
|
|
192
|
+
const lines = viewportRows(mirror)
|
|
193
|
+
.map((row) => row.trimEnd())
|
|
194
|
+
.filter((row) => row.length > 0);
|
|
195
|
+
return lines.slice(-EXIT_TAIL_LINES).join('\n').slice(-EXIT_TAIL_CHARS);
|
|
196
|
+
}
|
|
197
|
+
/** node-pty does not throw for a missing command on macOS: the child just exits with code 1 and no output. */
|
|
198
|
+
function commandExists(spec) {
|
|
199
|
+
const direct = spec.file.includes('/');
|
|
200
|
+
const candidates = direct
|
|
201
|
+
? [resolve(spec.cwd || '.', spec.file)]
|
|
202
|
+
: (spec.env.PATH ?? FALLBACK_PATH).split(':').map((dir) => join(dir || '.', spec.file));
|
|
203
|
+
return candidates.some((candidate) => {
|
|
204
|
+
try {
|
|
205
|
+
accessSync(candidate, fsConstants.X_OK);
|
|
206
|
+
return statSync(candidate).isFile();
|
|
207
|
+
}
|
|
208
|
+
catch {
|
|
209
|
+
return false; // not there or not executable: try the next directory
|
|
210
|
+
}
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
export function createTerminalHost(options = {}) {
|
|
214
|
+
const log = options.log ?? nullLogger;
|
|
215
|
+
const now = options.now ?? Date.now;
|
|
216
|
+
const killAfterMs = options.killAfterMs ?? STOP_KILL_AFTER_MS;
|
|
217
|
+
const giveUpAfterKillMs = options.giveUpAfterKillMs ?? STOP_GIVEUP_AFTER_KILL_MS;
|
|
218
|
+
const records = new Map();
|
|
219
|
+
const handlers = [];
|
|
220
|
+
/** Callbacks of node-pty and xterm run inside their emitters: an exception there would end the process. */
|
|
221
|
+
const guarded = (what, fn) => {
|
|
222
|
+
try {
|
|
223
|
+
fn();
|
|
224
|
+
}
|
|
225
|
+
catch (error) {
|
|
226
|
+
log.error(`terminal ${what} failed`, error);
|
|
227
|
+
}
|
|
228
|
+
};
|
|
229
|
+
const emit = (event) => {
|
|
230
|
+
for (const handler of [...handlers])
|
|
231
|
+
guarded('event handler', () => handler(event));
|
|
232
|
+
};
|
|
233
|
+
const probeOf = (rec) => {
|
|
234
|
+
let probe = rec.probe;
|
|
235
|
+
if (probe === null || probe.version !== rec.version) {
|
|
236
|
+
probe = { version: rec.version, value: analyzeScreen(viewportRows(rec.mirror), rec.mirror.cols) };
|
|
237
|
+
rec.probe = probe;
|
|
238
|
+
}
|
|
239
|
+
return { ...probe.value };
|
|
240
|
+
};
|
|
241
|
+
/**
|
|
242
|
+
* Ready = claude wrote ESC[?2004h (raw mode is on, so an Enter is not lost) and the boxed prompt row is drawn with no
|
|
243
|
+
* dialog on screen. Not "output went quiet" (the status line and the spinner never let it), not SessionStart.
|
|
244
|
+
*/
|
|
245
|
+
const checkReady = (rec) => {
|
|
246
|
+
if (rec.ready || !rec.mirror.modes.bracketedPasteMode)
|
|
247
|
+
return;
|
|
248
|
+
const probe = probeOf(rec);
|
|
249
|
+
if (!probe.promptBox || probe.dialog !== null)
|
|
250
|
+
return;
|
|
251
|
+
rec.ready = true;
|
|
252
|
+
emit({ kind: 'ready', name: rec.name, generation: rec.generation, at: now() });
|
|
253
|
+
};
|
|
254
|
+
const afterParse = (rec) => {
|
|
255
|
+
rec.pending -= 1;
|
|
256
|
+
rec.version += 1;
|
|
257
|
+
guarded('ready check', () => checkReady(rec));
|
|
258
|
+
};
|
|
259
|
+
const onTitle = (rec, title) => {
|
|
260
|
+
const glyph = classifyTitle(title);
|
|
261
|
+
const at = now();
|
|
262
|
+
const previous = rec.title;
|
|
263
|
+
if (previous !== null && previous.glyph === glyph) {
|
|
264
|
+
rec.title = { glyph, title, since: previous.since };
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
rec.title = { glyph, title, since: at };
|
|
268
|
+
emit({ kind: 'title', name: rec.name, generation: rec.generation, glyph, title, at });
|
|
269
|
+
};
|
|
270
|
+
const deliver = (sink, chunk) => {
|
|
271
|
+
if (sink.detached)
|
|
272
|
+
return;
|
|
273
|
+
if (!sink.started) {
|
|
274
|
+
sink.buffer.push(chunk);
|
|
275
|
+
return;
|
|
276
|
+
}
|
|
277
|
+
guarded('output listener', () => sink.listener(chunk));
|
|
278
|
+
};
|
|
279
|
+
const onChunk = (rec, data) => {
|
|
280
|
+
if (!rec.running)
|
|
281
|
+
return;
|
|
282
|
+
const chunk = typeof data === 'string' ? Buffer.from(data) : data;
|
|
283
|
+
rec.bytes += chunk.length;
|
|
284
|
+
rec.tracker.feed(chunk);
|
|
285
|
+
rec.pending += 1;
|
|
286
|
+
try {
|
|
287
|
+
rec.mirror.write(chunk, () => afterParse(rec));
|
|
288
|
+
}
|
|
289
|
+
catch (error) {
|
|
290
|
+
// xterm refuses writes beyond 50 MB of unparsed data; logging every chunk of a flood would be worse than the flood.
|
|
291
|
+
rec.pending -= 1;
|
|
292
|
+
if (!rec.mirrorFailed) {
|
|
293
|
+
rec.mirrorFailed = true;
|
|
294
|
+
log.error(`the mirror of ${rec.name} rejected output`, error);
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
for (const sink of rec.sinks)
|
|
298
|
+
deliver(sink, chunk);
|
|
299
|
+
};
|
|
300
|
+
const clearStopTimers = (rec) => {
|
|
301
|
+
if (rec.killTimer !== null)
|
|
302
|
+
clearTimeout(rec.killTimer);
|
|
303
|
+
if (rec.giveUpTimer !== null)
|
|
304
|
+
clearTimeout(rec.giveUpTimer);
|
|
305
|
+
rec.killTimer = null;
|
|
306
|
+
rec.giveUpTimer = null;
|
|
307
|
+
};
|
|
308
|
+
const finishExit = (rec, exitCode, signal) => {
|
|
309
|
+
if (rec.exited)
|
|
310
|
+
return;
|
|
311
|
+
rec.exited = true;
|
|
312
|
+
clearStopTimers(rec);
|
|
313
|
+
// node-pty reports exit code 0 together with the signal for a process that was killed.
|
|
314
|
+
const killedBy = signal > 0 ? signal : null;
|
|
315
|
+
const code = killedBy === null ? exitCode : null;
|
|
316
|
+
const durationMs = now() - rec.spawnedAt;
|
|
317
|
+
const complete = () => {
|
|
318
|
+
let tail = '';
|
|
319
|
+
try {
|
|
320
|
+
tail = exitTail(rec.mirror);
|
|
321
|
+
}
|
|
322
|
+
catch (error) {
|
|
323
|
+
log.warn(`cannot read the last screen of ${rec.name}`, error);
|
|
324
|
+
}
|
|
325
|
+
rec.running = false;
|
|
326
|
+
rec.pty = null;
|
|
327
|
+
emit({
|
|
328
|
+
kind: 'exit',
|
|
329
|
+
name: rec.name,
|
|
330
|
+
generation: rec.generation,
|
|
331
|
+
info: { code, signal: killedBy, durationMs, requested: rec.stopRequested, tail },
|
|
332
|
+
at: now(),
|
|
333
|
+
});
|
|
334
|
+
rec.markDone();
|
|
335
|
+
};
|
|
336
|
+
try {
|
|
337
|
+
// The marker is parsed after every chunk written so far, so the tail holds the whole last screen.
|
|
338
|
+
rec.mirror.write('', complete);
|
|
339
|
+
}
|
|
340
|
+
catch (error) {
|
|
341
|
+
log.warn(`the mirror of ${rec.name} could not flush before the exit event`, error);
|
|
342
|
+
complete();
|
|
343
|
+
}
|
|
344
|
+
};
|
|
345
|
+
/** To the process group (the pty child leads its own session), so its children end with it. */
|
|
346
|
+
const sendSignal = (rec, signal) => {
|
|
347
|
+
if (!(rec.pid > 1))
|
|
348
|
+
return; // kill(0) and kill(-1) would reach far more than this agent
|
|
349
|
+
for (const target of [-rec.pid, rec.pid]) {
|
|
350
|
+
try {
|
|
351
|
+
process.kill(target, signal);
|
|
352
|
+
return;
|
|
353
|
+
}
|
|
354
|
+
catch (error) {
|
|
355
|
+
if (errorCode(error) !== 'ESRCH') {
|
|
356
|
+
log.warn(`${signal} to ${rec.name} (${target}) failed`, error);
|
|
357
|
+
return;
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
};
|
|
362
|
+
const spawn = (name, generation, spec) => {
|
|
363
|
+
if (!helperChecked) {
|
|
364
|
+
helperChecked = true;
|
|
365
|
+
ensureSpawnHelperExecutable(log);
|
|
366
|
+
}
|
|
367
|
+
const previous = records.get(name);
|
|
368
|
+
if (previous?.running)
|
|
369
|
+
throw new Error(`agent ${name} is already running`);
|
|
370
|
+
if (!commandExists(spec))
|
|
371
|
+
throw new Error(`could not start ${spec.file}: command not found or not executable`);
|
|
372
|
+
const cols = clampDim(spec.cols ?? previous?.mirror.cols, MIN_COLS, MAX_COLS, DEFAULT_COLS);
|
|
373
|
+
const rows = clampDim(spec.rows ?? previous?.mirror.rows, MIN_ROWS, MAX_ROWS, DEFAULT_ROWS);
|
|
374
|
+
// Built before the pty so that nothing that can still fail is left to run after the process started.
|
|
375
|
+
// logLevel off: xterm prints every parser error it recovers from to the console, and what the agent writes is not ours to fix.
|
|
376
|
+
const mirror = new Terminal({ cols, rows, scrollback: MIRROR_SCROLLBACK_LINES, allowProposedApi: true, logLevel: 'off' });
|
|
377
|
+
const serializer = new SerializeAddon();
|
|
378
|
+
mirror.loadAddon(serializer);
|
|
379
|
+
let pty;
|
|
380
|
+
try {
|
|
381
|
+
pty = ptySpawn(spec.file, spec.args, { name: TERM_VALUE, cols, rows, cwd: spec.cwd, env: spec.env, encoding: null });
|
|
382
|
+
}
|
|
383
|
+
catch (error) {
|
|
384
|
+
const message = errorMessage(error);
|
|
385
|
+
const hint = message.includes('posix_spawnp failed') ? ' (command not found, or the pty helper is not executable)' : '';
|
|
386
|
+
throw new Error(`could not start ${spec.file}: ${message}${hint}`);
|
|
387
|
+
}
|
|
388
|
+
let markDone = () => { };
|
|
389
|
+
const done = new Promise((resolveDone) => {
|
|
390
|
+
markDone = resolveDone;
|
|
391
|
+
});
|
|
392
|
+
const rec = {
|
|
393
|
+
name,
|
|
394
|
+
generation,
|
|
395
|
+
pid: pty.pid,
|
|
396
|
+
pty,
|
|
397
|
+
mirror,
|
|
398
|
+
serializer,
|
|
399
|
+
tracker: new ModeTracker(),
|
|
400
|
+
sinks: new Set(),
|
|
401
|
+
spawnedAt: now(),
|
|
402
|
+
bytes: 0,
|
|
403
|
+
pending: 0,
|
|
404
|
+
version: 0,
|
|
405
|
+
probe: null,
|
|
406
|
+
title: null,
|
|
407
|
+
ready: false,
|
|
408
|
+
exited: false,
|
|
409
|
+
running: true,
|
|
410
|
+
stopRequested: false,
|
|
411
|
+
killTimer: null,
|
|
412
|
+
giveUpTimer: null,
|
|
413
|
+
mirrorFailed: false,
|
|
414
|
+
done,
|
|
415
|
+
markDone,
|
|
416
|
+
};
|
|
417
|
+
records.set(name, rec);
|
|
418
|
+
mirror.onTitleChange((title) => guarded('title handler', () => onTitle(rec, title)));
|
|
419
|
+
pty.onData((data) => guarded('data handler', () => onChunk(rec, data)));
|
|
420
|
+
pty.onExit(({ exitCode, signal }) => guarded('exit handler', () => finishExit(rec, exitCode, signal ?? 0)));
|
|
421
|
+
log.debug(`spawned ${name} generation ${generation} pid ${rec.pid} at ${cols}x${rows}`);
|
|
422
|
+
return { pid: rec.pid };
|
|
423
|
+
};
|
|
424
|
+
const stop = (name, generation) => {
|
|
425
|
+
const rec = records.get(name);
|
|
426
|
+
if (!rec || !rec.running || (generation !== undefined && generation !== rec.generation))
|
|
427
|
+
return Promise.resolve();
|
|
428
|
+
// A process that is already gone (exit handling still flushing the mirror) is never signalled: its pid may be reused.
|
|
429
|
+
if (!rec.stopRequested && !rec.exited) {
|
|
430
|
+
rec.stopRequested = true;
|
|
431
|
+
// SIGTERM first: claude runs its SessionEnd hooks and ends its own children; SIGKILL would orphan them.
|
|
432
|
+
sendSignal(rec, 'SIGTERM');
|
|
433
|
+
const killTimer = setTimeout(() => {
|
|
434
|
+
rec.killTimer = null;
|
|
435
|
+
if (rec.exited)
|
|
436
|
+
return;
|
|
437
|
+
guarded('SIGKILL timer', () => {
|
|
438
|
+
log.warn(`${rec.name} did not exit after SIGTERM; sending SIGKILL`);
|
|
439
|
+
sendSignal(rec, 'SIGKILL');
|
|
440
|
+
});
|
|
441
|
+
const giveUpTimer = setTimeout(() => {
|
|
442
|
+
rec.giveUpTimer = null;
|
|
443
|
+
if (rec.exited)
|
|
444
|
+
return;
|
|
445
|
+
guarded('give-up timer', () => {
|
|
446
|
+
log.warn(`${rec.name} did not exit after SIGKILL; treating it as gone`);
|
|
447
|
+
const pty = rec.pty;
|
|
448
|
+
finishExit(rec, 0, 9);
|
|
449
|
+
pty?.destroy?.();
|
|
450
|
+
});
|
|
451
|
+
}, giveUpAfterKillMs);
|
|
452
|
+
giveUpTimer.unref();
|
|
453
|
+
rec.giveUpTimer = giveUpTimer;
|
|
454
|
+
}, killAfterMs);
|
|
455
|
+
killTimer.unref();
|
|
456
|
+
rec.killTimer = killTimer;
|
|
457
|
+
}
|
|
458
|
+
return rec.done;
|
|
459
|
+
};
|
|
460
|
+
const stopAll = async () => {
|
|
461
|
+
await Promise.all([...records.values()].filter((rec) => rec.running).map((rec) => stop(rec.name)));
|
|
462
|
+
};
|
|
463
|
+
const write = (name, data) => {
|
|
464
|
+
const rec = records.get(name);
|
|
465
|
+
if (!rec?.pty || !isLive(rec))
|
|
466
|
+
return false;
|
|
467
|
+
try {
|
|
468
|
+
rec.pty.write(typeof data === 'string' ? data : Buffer.from(data));
|
|
469
|
+
return true;
|
|
470
|
+
}
|
|
471
|
+
catch (error) {
|
|
472
|
+
log.debug(`write to ${name} failed: ${errorMessage(error)}`);
|
|
473
|
+
return false;
|
|
474
|
+
}
|
|
475
|
+
};
|
|
476
|
+
const submit = (name, generation, text) => {
|
|
477
|
+
const rec = records.get(name);
|
|
478
|
+
if (!rec?.pty || !isLive(rec) || rec.generation !== generation)
|
|
479
|
+
return false;
|
|
480
|
+
if (!rec.mirror.modes.bracketedPasteMode)
|
|
481
|
+
return false;
|
|
482
|
+
const clean = sanitizeForPaste(text);
|
|
483
|
+
// The prefix is what makes it impossible for the server to type anything but a pointer.
|
|
484
|
+
if (clean === '' || clean.length > SUBMIT_MAX_CHARS || !clean.startsWith(POINTER_PREFIX))
|
|
485
|
+
return false;
|
|
486
|
+
try {
|
|
487
|
+
rec.pty.write(PASTE_START + clean + PASTE_END + ENTER);
|
|
488
|
+
return true;
|
|
489
|
+
}
|
|
490
|
+
catch (error) {
|
|
491
|
+
log.debug(`submit to ${name} failed: ${errorMessage(error)}`);
|
|
492
|
+
return false;
|
|
493
|
+
}
|
|
494
|
+
};
|
|
495
|
+
const resize = (name, cols, rows) => {
|
|
496
|
+
const rec = records.get(name);
|
|
497
|
+
if (!rec?.pty || !isLive(rec) || !Number.isFinite(cols) || !Number.isFinite(rows))
|
|
498
|
+
return false;
|
|
499
|
+
const c = clampDim(cols, MIN_COLS, MAX_COLS, DEFAULT_COLS);
|
|
500
|
+
const r = clampDim(rows, MIN_ROWS, MAX_ROWS, DEFAULT_ROWS);
|
|
501
|
+
// Every resize makes claude repaint everything, so an unchanged size must not reach the pty.
|
|
502
|
+
if (c === rec.mirror.cols && r === rec.mirror.rows)
|
|
503
|
+
return true;
|
|
504
|
+
try {
|
|
505
|
+
rec.pty.resize(c, r); // throws EBADF once the child is gone; then the mirror keeps the size the pty still has
|
|
506
|
+
}
|
|
507
|
+
catch (error) {
|
|
508
|
+
log.debug(`resize of ${name} failed: ${errorMessage(error)}`);
|
|
509
|
+
return false;
|
|
510
|
+
}
|
|
511
|
+
rec.mirror.resize(c, r);
|
|
512
|
+
rec.version += 1;
|
|
513
|
+
return true;
|
|
514
|
+
};
|
|
515
|
+
const rename = (oldName, newName) => {
|
|
516
|
+
const rec = records.get(oldName);
|
|
517
|
+
if (!rec || rec.running || records.get(newName)?.running)
|
|
518
|
+
return false;
|
|
519
|
+
records.delete(oldName);
|
|
520
|
+
rec.name = newName;
|
|
521
|
+
records.set(newName, rec);
|
|
522
|
+
return true;
|
|
523
|
+
};
|
|
524
|
+
/** A removed agent's record would otherwise keep its mirror, with up to MIRROR_SCROLLBACK_LINES rows, for the life of the server. */
|
|
525
|
+
const forget = (name) => {
|
|
526
|
+
const rec = records.get(name);
|
|
527
|
+
if (!rec || rec.running)
|
|
528
|
+
return;
|
|
529
|
+
records.delete(name);
|
|
530
|
+
for (const sink of rec.sinks) {
|
|
531
|
+
sink.detached = true;
|
|
532
|
+
sink.buffer = [];
|
|
533
|
+
}
|
|
534
|
+
rec.sinks.clear();
|
|
535
|
+
try {
|
|
536
|
+
rec.mirror.dispose();
|
|
537
|
+
}
|
|
538
|
+
catch (error) {
|
|
539
|
+
log.warn(`could not dispose the mirror of ${name}`, error);
|
|
540
|
+
}
|
|
541
|
+
};
|
|
542
|
+
const startSink = (sink) => {
|
|
543
|
+
if (sink.started || sink.detached)
|
|
544
|
+
return;
|
|
545
|
+
sink.started = true;
|
|
546
|
+
const queued = sink.buffer;
|
|
547
|
+
sink.buffer = [];
|
|
548
|
+
for (const chunk of queued) {
|
|
549
|
+
if (sink.detached)
|
|
550
|
+
return;
|
|
551
|
+
guarded('output listener', () => sink.listener(chunk));
|
|
552
|
+
}
|
|
553
|
+
};
|
|
554
|
+
const attach = (name, listener) => {
|
|
555
|
+
const rec = records.get(name);
|
|
556
|
+
if (!rec) {
|
|
557
|
+
const empty = {
|
|
558
|
+
snapshot: { cols: DEFAULT_COLS, rows: DEFAULT_ROWS, data: '', generation: 0, running: false },
|
|
559
|
+
start() { },
|
|
560
|
+
detach() { },
|
|
561
|
+
};
|
|
562
|
+
return Promise.resolve(empty);
|
|
563
|
+
}
|
|
564
|
+
// Steps 1 and 2 are one synchronous block: every chunk after this point is buffered for the sink, and the marker sits
|
|
565
|
+
// in the mirror's queue right behind everything that is not, so the snapshot and the buffer meet with no gap or overlap.
|
|
566
|
+
const sink = { listener, started: false, detached: false, buffer: [] };
|
|
567
|
+
rec.sinks.add(sink);
|
|
568
|
+
const modes = rec.tracker.fixup();
|
|
569
|
+
return new Promise((resolveAttachment) => {
|
|
570
|
+
const atMark = () => {
|
|
571
|
+
let data = modes;
|
|
572
|
+
try {
|
|
573
|
+
data = rec.serializer.serialize({ scrollback: SNAPSHOT_SCROLLBACK_LINES }) + modes;
|
|
574
|
+
}
|
|
575
|
+
catch (error) {
|
|
576
|
+
log.warn(`snapshot of ${name} failed`, error);
|
|
577
|
+
}
|
|
578
|
+
resolveAttachment({
|
|
579
|
+
snapshot: { cols: rec.mirror.cols, rows: rec.mirror.rows, data, generation: rec.generation, running: rec.running },
|
|
580
|
+
start: () => startSink(sink),
|
|
581
|
+
detach: () => {
|
|
582
|
+
sink.detached = true;
|
|
583
|
+
sink.buffer = [];
|
|
584
|
+
rec.sinks.delete(sink);
|
|
585
|
+
},
|
|
586
|
+
});
|
|
587
|
+
};
|
|
588
|
+
try {
|
|
589
|
+
rec.mirror.write('', atMark);
|
|
590
|
+
}
|
|
591
|
+
catch (error) {
|
|
592
|
+
log.warn(`the mirror of ${name} could not take a marker`, error);
|
|
593
|
+
atMark();
|
|
594
|
+
}
|
|
595
|
+
});
|
|
596
|
+
};
|
|
597
|
+
const screen = (name) => {
|
|
598
|
+
const rec = records.get(name);
|
|
599
|
+
return rec && rec.pending === 0 ? probeOf(rec) : null;
|
|
600
|
+
};
|
|
601
|
+
const titleOf = (name) => {
|
|
602
|
+
const current = records.get(name)?.title;
|
|
603
|
+
return current ? { ...current } : null;
|
|
604
|
+
};
|
|
605
|
+
const info = (name) => {
|
|
606
|
+
const rec = records.get(name);
|
|
607
|
+
if (!rec)
|
|
608
|
+
return null;
|
|
609
|
+
// Running until the exit event went out (contract 6.9), the same moment spawn() and rename() start to accept the name again.
|
|
610
|
+
return { running: rec.running, generation: rec.generation, pid: rec.running ? rec.pid : null, cols: rec.mirror.cols, rows: rec.mirror.rows };
|
|
611
|
+
};
|
|
612
|
+
return {
|
|
613
|
+
spawn,
|
|
614
|
+
stop,
|
|
615
|
+
stopAll,
|
|
616
|
+
write,
|
|
617
|
+
submit,
|
|
618
|
+
resize,
|
|
619
|
+
rename,
|
|
620
|
+
forget,
|
|
621
|
+
attach,
|
|
622
|
+
screen,
|
|
623
|
+
title: titleOf,
|
|
624
|
+
outputBytes: (name) => records.get(name)?.bytes ?? 0,
|
|
625
|
+
info,
|
|
626
|
+
onEvent: (handler) => {
|
|
627
|
+
handlers.push(handler);
|
|
628
|
+
return () => {
|
|
629
|
+
const index = handlers.indexOf(handler);
|
|
630
|
+
if (index >= 0)
|
|
631
|
+
handlers.splice(index, 1);
|
|
632
|
+
};
|
|
633
|
+
},
|
|
634
|
+
};
|
|
635
|
+
}
|