opencode-ahp 0.1.5 → 0.1.6

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.
@@ -0,0 +1,654 @@
1
+ /**
2
+ * Terminal section (design §12). Two kinds of terminal channels:
3
+ *
4
+ * - SYNTHETIC (`ahp-terminal:` prefix): read-only renderings of
5
+ * foreground `shell`-tool executions, host-managed, turn-scoped
6
+ * catalog retention.
7
+ * - PTY (client-chosen channel URI): interactive shells spawned via
8
+ * `createTerminal` (the `spawnPty` seam — Bun in production, a fake
9
+ * in tests), with real input/resize, claim/title/clear through the
10
+ * official reducer, and a rolling content-buffer trim the official
11
+ * append-only reducer never performs.
12
+ */
13
+
14
+ import { fileURLToPath } from "node:url";
15
+ import { HostChangesets } from "./host-changesets.js";
16
+ import {
17
+ ActionOrigin,
18
+ ActionType,
19
+ StateAction,
20
+ TerminalClaim,
21
+ TerminalClaimedAction,
22
+ TerminalClaimKind,
23
+ TerminalContentPart,
24
+ TerminalInfo,
25
+ TerminalInputAction,
26
+ TerminalLifecycleStatus,
27
+ TerminalResizedAction,
28
+ TerminalState,
29
+ TerminalTitleChangedAction,
30
+ } from "@microsoft/agent-host-protocol";
31
+ import { directoryUri, FacadeToolContent } from "./bridge.js";
32
+ import { ROOT_CHANNEL, channelKind, terminalChannelURI } from "./channels.js";
33
+ import {
34
+ ERROR_ALREADY_EXISTS,
35
+ ERROR_INTERNAL,
36
+ ERROR_INVALID_REQUEST,
37
+ ERROR_METHOD_NOT_FOUND,
38
+ ERROR_PERMISSION_DENIED,
39
+ } from "./host-errors.js";
40
+ import { ERROR_INVALID_PARAMS } from "./handshake.js";
41
+ import { isRecord } from "./options.js";
42
+ import { createTerminalStateStore } from "./state.js";
43
+ import { ChatRuntime, PtyTerminalRecord, RpcMessage, SessionRecord } from "./host-types.js";
44
+ import { errorMessage, isPathInside, shellExitCodeOf } from "./host-util.js";
45
+
46
+ /**
47
+ * The opencode tool names whose executions render as synthetic
48
+ * `ahp-terminal:` channels. `shell`
49
+ * is the v2 core tool name; `bash` is its pre-rename alias (kept so an
50
+ * older provider-side tool name still maps).
51
+ */
52
+ const SHELL_TOOL_NAMES = new Set(["shell", "bash"]);
53
+
54
+ /**
55
+ * Max characters of the command line kept in the terminal title (the
56
+ * catalog row and the state title share it — long pipelines stay
57
+ * one-line in the Agents-window list).
58
+ */
59
+ const TERMINAL_TITLE_MAX = 64;
60
+
61
+ /**
62
+ * Rolling buffer budget for pty terminal content — the VS Code reference
63
+ * client's terminalConstants: once the stored content exceeds the max,
64
+ * trim back to the target (drop whole parts from the front, then slice
65
+ * the head part). The official terminal reducer is append-only and never
66
+ * trims, so the host does it after each `terminal/data` apply.
67
+ */
68
+ const TERMINAL_MAX_CONTENT_LENGTH = 100_000;
69
+ const TERMINAL_TRIMMED_CONTENT_LENGTH = 80_000;
70
+
71
+ /** A positive integer, or null. */
72
+ function positiveInt(value: unknown): number | null {
73
+ return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : null;
74
+ }
75
+
76
+ /** The character size of a content part (command parts count their output). */
77
+ function partSize(part: TerminalContentPart): number {
78
+ return part.type === "command" ? part.output.length : part.value.length;
79
+ }
80
+
81
+ /**
82
+ * Validate a wire `TerminalClaim` (createTerminal params, the
83
+ * terminal/claimed action payload): a client claim naming the dispatching
84
+ * client (a claim is not a credential — naming someone else is
85
+ * rejected), or a session claim with its session/chat URIs (optional
86
+ * turnId/toolCallId scope passed through). Null when the shape is wrong.
87
+ */
88
+ function normalizeTerminalClaim(claim: unknown, clientId: string | null): TerminalClaim | null {
89
+ if (!isRecord(claim)) return null;
90
+ if (claim["kind"] === TerminalClaimKind.Client) {
91
+ const id = claim["clientId"];
92
+ if (typeof id !== "string" || id.length === 0) return null;
93
+ if (clientId !== null && id !== clientId) return null;
94
+ return { kind: TerminalClaimKind.Client, clientId: id };
95
+ }
96
+ if (claim["kind"] === TerminalClaimKind.Session) {
97
+ if (typeof claim["session"] !== "string" || claim["session"].length === 0) return null;
98
+ if (typeof claim["chat"] !== "string" || claim["chat"].length === 0) return null;
99
+ return {
100
+ kind: TerminalClaimKind.Session,
101
+ session: claim["session"],
102
+ chat: claim["chat"],
103
+ ...(typeof claim["turnId"] === "string" ? { turnId: claim["turnId"] } : {}),
104
+ ...(typeof claim["toolCallId"] === "string" ? { toolCallId: claim["toolCallId"] } : {}),
105
+ };
106
+ }
107
+ return null;
108
+ }
109
+
110
+ /**
111
+ * Unwrap the client's agent-host URI wrapper to the original file path.
112
+ * The VS Code 1.145.2 scheme
113
+ * (`vscode-agent-host://<authority>/<path>?_ah=<urlsafe-base64 JSON>`)
114
+ * keeps the original path verbatim in the URI path and carries the
115
+ * original scheme/authority/path in the `_ah` query parameter — the `_ah`
116
+ * meta path wins when present (the content path); otherwise the URI path
117
+ * is used. Null when the URI does not parse to a path.
118
+ */
119
+ function unwrapAgentHostCwd(raw: string): string | null {
120
+ let url: URL;
121
+ try {
122
+ url = new URL(raw);
123
+ } catch {
124
+ return null;
125
+ }
126
+ const meta = url.searchParams.get("_ah");
127
+ if (meta !== null) {
128
+ try {
129
+ const decoded: unknown = JSON.parse(Buffer.from(meta, "base64url").toString("utf8"));
130
+ if (isRecord(decoded) && typeof decoded["path"] === "string" && decoded["path"].length > 0) {
131
+ return decoded["path"];
132
+ }
133
+ } catch {
134
+ // Malformed `_ah` meta — fall through to the URI path.
135
+ }
136
+ }
137
+ return url.pathname.length > 0 ? url.pathname : null;
138
+ }
139
+
140
+ export class HostTerminals extends HostChangesets {
141
+ // ── pty terminals (createTerminal / disposeTerminal) ─────────────────
142
+
143
+ /**
144
+ * `createTerminal` (AHP 1.0.0): spawn an interactive pty shell in the
145
+ * resolved working directory and register the client-chosen channel.
146
+ * The result is `null` per the AHP message contract — the client then
147
+ * subscribes to the channel for the state snapshot. Errors: -32601 when
148
+ * the terminal capability is off or the runtime cannot spawn ptys;
149
+ * -32600 for a channel URI inside the host namespace (including the
150
+ * reserved `ahp-terminal:` synthetic prefix); -32010 (AHP
151
+ * AlreadyExists) for a duplicate channel; -32602 for malformed params;
152
+ * -32603 when the spawn itself throws (R2 — logged, the host survives,
153
+ * and the command answers the error).
154
+ */
155
+ async handleCreateTerminal(socketId: number, msg: RpcMessage): Promise<void> {
156
+ if (!this.opts.terminals) {
157
+ this.sendError(socketId, msg.id, ERROR_METHOD_NOT_FOUND, "createTerminal is not enabled on this host");
158
+ return;
159
+ }
160
+ const params = isRecord(msg.params) ? msg.params : {};
161
+ const channel = params["channel"];
162
+ if (typeof channel !== "string" || channel.length === 0) {
163
+ this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "createTerminal requires a channel URI");
164
+ return;
165
+ }
166
+ // The channel must be client-chosen: anything that classifies as a
167
+ // host channel (ahp-root/session/chat/changeset/terminal) is refused —
168
+ // including the reserved `ahp-terminal:` synthetic prefix.
169
+ if (channelKind(channel) !== "unknown") {
170
+ this.sendError(
171
+ socketId,
172
+ msg.id,
173
+ ERROR_INVALID_REQUEST,
174
+ `createTerminal channel ${channel} must not use the host channel namespace`,
175
+ );
176
+ return;
177
+ }
178
+ const socket = this.sockets.get(socketId);
179
+ const claim = normalizeTerminalClaim(params["claim"], socket?.clientId ?? null);
180
+ if (claim === null) {
181
+ this.sendError(
182
+ socketId,
183
+ msg.id,
184
+ ERROR_INVALID_PARAMS,
185
+ "createTerminal requires a valid claim (a client claim for the dispatching client, or a session claim)",
186
+ );
187
+ return;
188
+ }
189
+ if (this.terminals.has(channel)) {
190
+ this.sendError(socketId, msg.id, ERROR_ALREADY_EXISTS, `terminal ${channel} already exists`);
191
+ return;
192
+ }
193
+ const spawn = this.opts.spawnPty;
194
+ if (spawn === undefined) {
195
+ this.sendError(socketId, msg.id, ERROR_METHOD_NOT_FOUND, "interactive terminal spawning is unavailable in this runtime");
196
+ return;
197
+ }
198
+ const cwd = this.resolveTerminalCwd(typeof params["cwd"] === "string" ? params["cwd"] : undefined);
199
+ const cols = positiveInt(params["cols"]) ?? 80;
200
+ const rows = positiveInt(params["rows"]) ?? 24;
201
+ const name = typeof params["name"] === "string" && params["name"].length > 0 ? params["name"] : undefined;
202
+ // The output/exit callbacks re-look-up the record so a dispose that
203
+ // races the pty callbacks no-ops cleanly (post-dispose race).
204
+ const onOutput = (data: string): void => {
205
+ const rec = this.terminals.get(channel);
206
+ if (rec === undefined || rec.kind !== "pty") return;
207
+ this.appendPtyOutput(rec, data);
208
+ };
209
+ const onExit = (code: number | undefined): void => {
210
+ const rec = this.terminals.get(channel);
211
+ if (rec === undefined || rec.kind !== "pty") return;
212
+ this.ptyExited(rec, code);
213
+ };
214
+ let pty: PtyTerminalRecord["process"];
215
+ try {
216
+ pty = spawn({ cwd, cols, rows, onOutput, onExit });
217
+ } catch (err) {
218
+ this.log(`terminal ${channel}: spawn failed: ${errorMessage(err)}`);
219
+ this.sendError(socketId, msg.id, ERROR_INTERNAL, `failed to spawn the terminal process: ${errorMessage(err)}`);
220
+ return;
221
+ }
222
+ this.terminals.set(channel, {
223
+ uri: channel,
224
+ kind: "pty",
225
+ process: pty,
226
+ cwd,
227
+ startedAt: Date.now(),
228
+ store: createTerminalStateStore({
229
+ title: name ?? "Shell",
230
+ content: [],
231
+ lifecycle: { status: TerminalLifecycleStatus.Running },
232
+ claim,
233
+ isPty: true,
234
+ // A directory URI (trailing slash — RFC 8089).
235
+ cwd: directoryUri(cwd),
236
+ cols,
237
+ rows,
238
+ } satisfies TerminalState),
239
+ });
240
+ this.channels.addTerminal(channel);
241
+ // No terminal-channel action announces the creation (AHP has none) —
242
+ // the client subscribes for the snapshot; the root catalog gets the
243
+ // row via root/terminalsChanged.
244
+ this.refreshTerminals();
245
+ this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: null });
246
+ }
247
+
248
+ /**
249
+ * `disposeTerminal` (AHP 1.0.0): kill the pty and drop its record.
250
+ * Idempotent success (`null`) for unknown channels — the VS Code
251
+ * client's shutdown path disposes terminals that may already be gone
252
+ * (its reference manager no-ops unknown URIs). Synthetic
253
+ * (session-owned) terminals are host-managed: -32009 (AHP
254
+ * PermissionDenied — the client is not permitted to dispose them).
255
+ */
256
+ async handleDisposeTerminal(socketId: number, msg: RpcMessage): Promise<void> {
257
+ if (!this.opts.terminals) {
258
+ this.sendError(socketId, msg.id, ERROR_METHOD_NOT_FOUND, "disposeTerminal is not enabled on this host");
259
+ return;
260
+ }
261
+ const params = isRecord(msg.params) ? msg.params : {};
262
+ const channel = params["channel"];
263
+ if (typeof channel !== "string" || channel.length === 0) {
264
+ this.sendError(socketId, msg.id, ERROR_INVALID_PARAMS, "disposeTerminal requires a channel URI");
265
+ return;
266
+ }
267
+ const t = this.terminals.get(channel);
268
+ if (t === undefined) {
269
+ this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: null });
270
+ return;
271
+ }
272
+ if (t.kind === "synthetic") {
273
+ this.sendError(
274
+ socketId,
275
+ msg.id,
276
+ ERROR_PERMISSION_DENIED,
277
+ `shell-tool terminals are host-managed and cannot be disposed by a client`,
278
+ );
279
+ return;
280
+ }
281
+ this.disposePtyTerminal(t);
282
+ this.sendFrame(socketId, { jsonrpc: "2.0", id: msg.id ?? null, result: null });
283
+ }
284
+
285
+ /**
286
+ * Resolve a `createTerminal` cwd to an absolute path inside the
287
+ * location directory. Accepted: a plain `file://` URI (what the VS
288
+ * Code client sends — it unwraps its own wrapper before the wire), the
289
+ * client's `vscode-agent-host:`/`agent-host:` wrapper (supported for
290
+ * robustness), and a bare absolute path. Anything malformed — and
291
+ * anything outside the location directory — falls back to the location
292
+ * directory: the shell is a tool of the session's agent and must not
293
+ * be spawned outside its working root.
294
+ */
295
+ protected resolveTerminalCwd(raw: string | undefined): string {
296
+ const fallback = this.opts.defaultDirectory ?? process.cwd();
297
+ if (raw === undefined || raw.length === 0) return fallback;
298
+ let path: string | null = null;
299
+ if (raw.startsWith("file://")) {
300
+ try {
301
+ path = fileURLToPath(raw);
302
+ } catch {
303
+ path = null;
304
+ }
305
+ } else if (raw.startsWith("vscode-agent-host:") || raw.startsWith("agent-host:")) {
306
+ path = unwrapAgentHostCwd(raw);
307
+ } else if (raw.startsWith("/")) {
308
+ path = raw;
309
+ }
310
+ if (path === null || !path.startsWith("/")) {
311
+ this.log(`terminal cwd ${raw} is not a usable path; falling back to ${fallback}`);
312
+ return fallback;
313
+ }
314
+ if (this.opts.defaultDirectory !== undefined && !isPathInside(path, this.opts.defaultDirectory)) {
315
+ this.log(`terminal cwd ${path} is outside the location directory; clamping to ${fallback}`);
316
+ return fallback;
317
+ }
318
+ return path;
319
+ }
320
+
321
+ /**
322
+ * Dispatch a client-dispatchable action on a live pty terminal:
323
+ * `terminal/input` and `terminal/resized` drive the process (rejected
324
+ * once it has exited — a dead pty has no stdin to write to);
325
+ * `terminal/claimed` applies only when the dispatching client
326
+ * currently holds the client claim (the AHP spec's SHOULD; session
327
+ * claims are host-mediated here and never client-dispatchable);
328
+ * `terminal/titleChanged` (non-empty) and `terminal/cleared` apply
329
+ * through the official reducer (the cleared action resets the content
330
+ * parts) and are allowed even after exit — the state still exists.
331
+ * Accepted title/claim changes refresh the root catalog (the row's
332
+ * title/claim fields are denormalized from the state — VS Code
333
+ * reference parity: _setTitle/_setClaim → _broadcastTerminalList).
334
+ */
335
+ protected dispatchPtyTerminal(t: PtyTerminalRecord, action: StateAction, origin: ActionOrigin | undefined): void {
336
+ const channel = t.uri;
337
+ const exited = t.store.state.lifecycle.status === TerminalLifecycleStatus.Exited;
338
+ switch (action.type) {
339
+ case ActionType.TerminalInput: {
340
+ const a = action as TerminalInputAction;
341
+ if (typeof a.data !== "string") {
342
+ this.echo(channel, action, origin, "invalid terminal/input params (data must be a string)");
343
+ return;
344
+ }
345
+ if (exited) {
346
+ this.echo(channel, action, origin, "terminal process has exited; input is no longer accepted");
347
+ return;
348
+ }
349
+ t.process.write(a.data);
350
+ this.echo(channel, action, origin);
351
+ return;
352
+ }
353
+ case ActionType.TerminalResized: {
354
+ const a = action as TerminalResizedAction;
355
+ const cols = positiveInt(a.cols);
356
+ const rows = positiveInt(a.rows);
357
+ if (cols === null || rows === null) {
358
+ this.echo(channel, action, origin, "invalid terminal/resized params (cols/rows must be positive integers)");
359
+ return;
360
+ }
361
+ if (exited) {
362
+ this.echo(channel, action, origin, "terminal process has exited; it cannot be resized");
363
+ return;
364
+ }
365
+ t.process.resize(cols, rows);
366
+ this.echo(channel, action, origin);
367
+ return;
368
+ }
369
+ case ActionType.TerminalClaimed: {
370
+ const a = action as TerminalClaimedAction;
371
+ const current = t.store.state.claim;
372
+ if (current.kind !== TerminalClaimKind.Client || current.clientId !== (origin?.clientId ?? null)) {
373
+ this.echo(channel, action, origin, "only the client currently holding this terminal may re-claim it");
374
+ return;
375
+ }
376
+ const next = normalizeTerminalClaim(a.claim, origin?.clientId ?? null);
377
+ if (next === null) {
378
+ this.echo(channel, action, origin, "invalid terminal/claimed params (claim must be a client or session claim)");
379
+ return;
380
+ }
381
+ this.echo(channel, action, origin);
382
+ this.refreshTerminals();
383
+ return;
384
+ }
385
+ case ActionType.TerminalTitleChanged: {
386
+ const a = action as TerminalTitleChangedAction;
387
+ if (typeof a.title !== "string" || a.title.length === 0) {
388
+ this.echo(channel, action, origin, "invalid terminal/titleChanged params (title must be a non-empty string)");
389
+ return;
390
+ }
391
+ this.echo(channel, action, origin);
392
+ this.refreshTerminals();
393
+ return;
394
+ }
395
+ case ActionType.TerminalCleared:
396
+ // The official reducer resets the content parts.
397
+ this.echo(channel, action, origin);
398
+ return;
399
+ default:
400
+ this.echo(channel, action, origin, `unsupported action on terminal channel: ${String(action.type)}`);
401
+ }
402
+ }
403
+
404
+ /**
405
+ * Append pty output: publish `terminal/data` (the official reducer
406
+ * appends to the content tail — one growing unclassified part while no
407
+ * command is executing), then trim the stored content back to the
408
+ * rolling-buffer budget (the host-side transition — see
409
+ * `trimPtyContent`).
410
+ */
411
+ protected appendPtyOutput(t: PtyTerminalRecord, data: string): void {
412
+ if (data.length === 0) return;
413
+ this.publish({ channel: t.uri, action: { type: ActionType.TerminalData, data } });
414
+ this.trimPtyContent(t);
415
+ }
416
+
417
+ /**
418
+ * Host-side trim of the pty content parts (the official terminal
419
+ * reducer never trims — append-only). Mirrors the VS Code reference
420
+ * client's `_trimContent`: drop whole parts from the front while the
421
+ * size exceeds the trimmed target and more than one part remains, then
422
+ * slice the head part by the excess. The replay window still carries
423
+ * the raw `terminal/data` actions (inherent — the window is shared).
424
+ */
425
+ protected trimPtyContent(t: PtyTerminalRecord): void {
426
+ const s = t.store.state;
427
+ let size = 0;
428
+ for (const part of s.content) size += partSize(part);
429
+ if (size <= TERMINAL_MAX_CONTENT_LENGTH) return;
430
+ const content = [...s.content];
431
+ while (size > TERMINAL_TRIMMED_CONTENT_LENGTH && content.length > 1) {
432
+ const removed = content.shift()!;
433
+ size -= partSize(removed);
434
+ }
435
+ if (size > TERMINAL_TRIMMED_CONTENT_LENGTH && content.length > 0) {
436
+ const head = content[0]!;
437
+ const excess = size - TERMINAL_TRIMMED_CONTENT_LENGTH;
438
+ content[0] =
439
+ head.type === "command"
440
+ ? { ...head, output: head.output.slice(excess) }
441
+ : { ...head, value: head.value.slice(excess) };
442
+ }
443
+ t.store.replace({ ...s, content });
444
+ }
445
+
446
+ /**
447
+ * A pty process exited on its own: publish `terminal/exited` (the
448
+ * exit code when the runtime reported one) and refresh the catalog —
449
+ * the row stays listed with its (final) exited lifecycle until the
450
+ * client disposes it or the location tears down. Idempotent: a
451
+ * record that already exited (or was disposed) is left alone.
452
+ */
453
+ protected ptyExited(t: PtyTerminalRecord, code: number | undefined): void {
454
+ if (t.store.state.lifecycle.status === TerminalLifecycleStatus.Exited) return;
455
+ this.publish({
456
+ channel: t.uri,
457
+ action: { type: ActionType.TerminalExited, ...(code !== undefined ? { exitCode: code } : {}) },
458
+ });
459
+ this.refreshTerminals();
460
+ }
461
+
462
+ /**
463
+ * Kill a pty terminal and drop its record (shared by the client's
464
+ * `disposeTerminal` and location teardown): a still-running process
465
+ * gets a final `terminal/exited` (no exit code — a host-initiated
466
+ * kill), the process is killed, the record and the registry entry go,
467
+ * and the root catalog refreshes (the row drops). The pty's own
468
+ * `onExit` callback finds no record and no-ops (post-dispose race).
469
+ */
470
+ protected disposePtyTerminal(t: PtyTerminalRecord): void {
471
+ if (t.store.state.lifecycle.status === TerminalLifecycleStatus.Running) {
472
+ this.publish({ channel: t.uri, action: { type: ActionType.TerminalExited } });
473
+ }
474
+ try {
475
+ t.process.kill();
476
+ } catch (err) {
477
+ this.log(`terminal ${t.uri}: kill failed: ${errorMessage(err)}`);
478
+ }
479
+ this.terminals.delete(t.uri);
480
+ this.channels.removeTerminal(t.uri);
481
+ this.refreshTerminals();
482
+ }
483
+
484
+ /**
485
+ * Kill every live pty terminal (location teardown — called before the
486
+ * listener stops so the final `terminal/exited` actions still reach
487
+ * subscribers). Synthetic terminals are chat/record-scoped — their
488
+ * teardown rides the session-removal path and there is nothing to
489
+ * kill.
490
+ */
491
+ stopTerminals(): void {
492
+ for (const t of [...this.terminals.values()]) {
493
+ if (t.kind !== "pty") continue;
494
+ this.disposePtyTerminal(t);
495
+ }
496
+ }
497
+
498
+ // ── synthetic shell-command terminals ───────────────────────────────────
499
+
500
+ /**
501
+ * Open the synthetic `ahp-terminal:` channel for a foreground
502
+ * `shell`-tool call (read-only rendering of the command execution):
503
+ * seed the state (`isPty: false`, session claim scoped to
504
+ * chat/turn/toolCall, `supportsCommandDetection: true`), publish
505
+ * `terminal/commandExecuted` (commandId = toolCallId), register the
506
+ * channel, and refresh the root catalog. No-op for the excluded shapes
507
+ * (capability off, no active turn, non-shell tool, malformed input,
508
+ * background calls — the background result carries no turn-scoped
509
+ * completion).
510
+ */
511
+ protected openTerminalForToolCall(rec: SessionRecord, chat: ChatRuntime, toolCallId: string, inputJson: string): void {
512
+ if (!this.opts.terminals) return;
513
+ const turnId = chat.currentTurnId;
514
+ if (turnId === null) return;
515
+ const name = chat.toolName.get(toolCallId);
516
+ if (name === undefined || !SHELL_TOOL_NAMES.has(name)) return;
517
+ let input: unknown;
518
+ try {
519
+ input = JSON.parse(inputJson);
520
+ } catch {
521
+ return; // malformed input text — nothing to render
522
+ }
523
+ if (!isRecord(input)) return;
524
+ const command = input["command"];
525
+ if (typeof command !== "string" || command.length === 0) return;
526
+ if (input["background"] === true) return; // excluded: no synchronous completion
527
+ const uri = terminalChannelURI(toolCallId);
528
+ if (this.terminals.has(uri)) {
529
+ this.log(`terminal ${uri} already exists (duplicate toolCallId ${toolCallId}); not reopening`);
530
+ return;
531
+ }
532
+ const now = Date.now();
533
+ const initial: TerminalState = {
534
+ title:
535
+ command.length > TERMINAL_TITLE_MAX ? `${command.slice(0, TERMINAL_TITLE_MAX - 1)}…` : command,
536
+ content: [],
537
+ lifecycle: { status: TerminalLifecycleStatus.Running },
538
+ claim: { kind: TerminalClaimKind.Session, session: rec.channel, chat: chat.uri, turnId, toolCallId },
539
+ supportsCommandDetection: true,
540
+ isPty: false,
541
+ // A directory URI (trailing slash — RFC 8089).
542
+ ...(this.opts.defaultDirectory !== undefined ? { cwd: directoryUri(this.opts.defaultDirectory) } : {}),
543
+ };
544
+ this.terminals.set(uri, {
545
+ uri,
546
+ kind: "synthetic",
547
+ rec,
548
+ chat,
549
+ toolCallId,
550
+ turnId,
551
+ store: createTerminalStateStore(initial),
552
+ commandLine: command,
553
+ startedAt: now,
554
+ });
555
+ this.channels.addTerminal(uri);
556
+ this.publish({
557
+ channel: uri,
558
+ action: { type: ActionType.TerminalCommandExecuted, commandId: toolCallId, commandLine: command, timestamp: now },
559
+ });
560
+ this.refreshTerminals();
561
+ }
562
+
563
+ /**
564
+ * Complete the synthetic terminal of a `shell`-tool call: publish
565
+ * `terminal/data` (the output — the tool's text content on success,
566
+ * the error message on failure), `terminal/commandFinished` (exitCode
567
+ * + duration), and `terminal/exited`, then refresh the root catalog
568
+ * (the listed lifecycle flips to exited while the turn still runs).
569
+ * Idempotent — a terminal that already exited is left alone. The
570
+ * record itself is retained (retention); only the state moves on.
571
+ */
572
+ protected finishTerminal(
573
+ chat: ChatRuntime,
574
+ toolCallId: string,
575
+ result: { ok: true; content: FacadeToolContent[] } | { ok: false; message: string },
576
+ ): void {
577
+ if (!this.opts.terminals) return;
578
+ const uri = terminalChannelURI(toolCallId);
579
+ const t = this.terminals.get(uri);
580
+ // Synthetic URIs can never hold pty records (createTerminal refuses
581
+ // the reserved prefix) — the guard is the union's narrowing.
582
+ if (t === undefined || t.kind !== "synthetic") return;
583
+ if (t.store.state.lifecycle.status === TerminalLifecycleStatus.Exited) return;
584
+ const output = result.ok
585
+ ? result.content
586
+ .filter((c) => c.type === "text" && typeof c.text === "string")
587
+ .map((c) => c.text as string)
588
+ .join("\n")
589
+ : result.message;
590
+ if (output.length > 0) {
591
+ this.publish({ channel: uri, action: { type: ActionType.TerminalData, data: output } });
592
+ }
593
+ const exitCode = result.ok ? (shellExitCodeOf(result.content) ?? undefined) : undefined;
594
+ const durationMs = Math.max(0, Date.now() - t.startedAt);
595
+ this.publish({
596
+ channel: uri,
597
+ action: {
598
+ type: ActionType.TerminalCommandFinished,
599
+ commandId: toolCallId,
600
+ ...(exitCode !== undefined ? { exitCode } : {}),
601
+ ...(durationMs > 0 ? { durationMs } : {}),
602
+ },
603
+ });
604
+ this.publish({
605
+ channel: uri,
606
+ action: { type: ActionType.TerminalExited, ...(exitCode !== undefined ? { exitCode } : {}) },
607
+ });
608
+ this.refreshTerminals();
609
+ }
610
+
611
+ /**
612
+ * Republish the root terminal catalog (`root/terminalsChanged`, full
613
+ * replacement). Synthetic terminals are turn-scoped: listed while
614
+ * their turn is still the owning chat's active turn (finished commands
615
+ * keep their (final) lifecycle row until the turn ends, then the row
616
+ * drops — host-controlled retention). Pty terminals are listed while
617
+ * their record is alive (running or exited) until disposed. No-op when
618
+ * the serialized list is unchanged.
619
+ */
620
+ protected refreshTerminals(): void {
621
+ if (!this.opts.terminals) return;
622
+ const terminals: TerminalInfo[] = [];
623
+ for (const t of this.terminals.values()) {
624
+ if (t.kind === "synthetic" && t.chat.currentTurnId !== t.turnId) continue;
625
+ const s = t.store.state;
626
+ terminals.push({ resource: t.uri, title: s.title, claim: s.claim, lifecycle: s.lifecycle });
627
+ }
628
+ if (JSON.stringify(this.state.state.terminals) === JSON.stringify(terminals)) return;
629
+ this.publish({ channel: ROOT_CHANNEL, action: { type: ActionType.RootTerminalsChanged, terminals } });
630
+ }
631
+
632
+ /**
633
+ * Drop a chat's SYNTHETIC terminal channels (removeChat — covers both
634
+ * chat disposal and record removal): a still-running command gets a
635
+ * final `terminal/exited` (it dies with the chat), then the records and
636
+ * registry entries go and the root catalog refreshes. Existing socket
637
+ * subscriptions linger (the session-removal precedent) — no further
638
+ * actions will reach them. Pty terminals are not chat-owned — they are
639
+ * never touched here.
640
+ */
641
+ protected teardownTerminalsForChat(chat: ChatRuntime): void {
642
+ let changed = false;
643
+ for (const t of [...this.terminals.values()]) {
644
+ if (t.kind !== "synthetic" || t.chat !== chat) continue;
645
+ if (t.store.state.lifecycle.status === TerminalLifecycleStatus.Running) {
646
+ this.publish({ channel: t.uri, action: { type: ActionType.TerminalExited } });
647
+ }
648
+ this.terminals.delete(t.uri);
649
+ this.channels.removeTerminal(t.uri);
650
+ changed = true;
651
+ }
652
+ if (changed) this.refreshTerminals();
653
+ }
654
+ }