pi-agent-ide 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +1 -0
  3. package/dist/{chunk-RHV5STR3.js → chunk-3SE372WC.js} +3 -3
  4. package/dist/{chunk-EWNWKDMP.js → chunk-6DZA4CLO.js} +1 -1
  5. package/dist/{chunk-VZJIZXSH.js → chunk-7JYQMAEL.js} +1 -1
  6. package/dist/{chunk-SSHZEWWV.js → chunk-DQF5QMJ2.js} +1 -1
  7. package/dist/chunk-EJ5OACQM.js +1 -0
  8. package/dist/{chunk-CW53ZTU3.js → chunk-GFW5QPQV.js} +1 -1
  9. package/dist/chunk-J34VKQGJ.js +1 -0
  10. package/dist/{chunk-CEKXBS55.js → chunk-TI5GMJ7Q.js} +1 -1
  11. package/dist/chunk-XSTHESNR.js +25 -0
  12. package/dist/{chunk-LRYE2WCN.js → chunk-Y7ZMR4LT.js} +1 -1
  13. package/dist/entry-10.js +1 -1
  14. package/dist/entry-14.js +1 -1
  15. package/dist/entry-21.js +1 -1
  16. package/dist/entry-26.js +1 -1
  17. package/dist/entry-28.js +1 -1
  18. package/dist/entry-32.js +1 -1
  19. package/dist/entry-37.js +1 -1
  20. package/dist/entry-40.js +1 -1
  21. package/dist/entry-46.js +1 -1
  22. package/dist/entry-49.js +1 -1
  23. package/dist/entry-51.js +1 -1
  24. package/dist/entry-53.js +1 -1
  25. package/dist/entry-54.js +1 -1
  26. package/dist/entry-56.js +1 -1
  27. package/dist/entry-59.js +1 -1
  28. package/dist/entry-62.js +1 -1
  29. package/dist/entry-69.js +1 -1
  30. package/dist/entry-70.js +18 -18
  31. package/dist/entry-71.js +2 -2
  32. package/dist/entry-72.js +1 -1
  33. package/dist/entry-75.js +1 -1
  34. package/dist/pi-agent-ide.js +3 -3
  35. package/docs/tools.md +11 -0
  36. package/node_modules/pi-agent-doctor/package.json +1 -1
  37. package/node_modules/pi-agent-filesystem/package.json +6 -6
  38. package/node_modules/pi-agent-filesystem-image/package.json +3 -3
  39. package/node_modules/pi-agent-filesystem-pdf/package.json +3 -3
  40. package/node_modules/pi-agent-filesystem-text/package.json +3 -3
  41. package/node_modules/pi-agent-ide-ast/package.json +9 -9
  42. package/node_modules/pi-agent-ide-changes/package.json +6 -6
  43. package/node_modules/pi-agent-ide-formatter/package.json +3 -3
  44. package/node_modules/pi-agent-ide-languages/package.json +2 -2
  45. package/node_modules/pi-agent-ide-lint/package.json +7 -7
  46. package/node_modules/pi-agent-ide-lsp/package.json +9 -9
  47. package/node_modules/pi-agent-image/package.json +2 -2
  48. package/node_modules/pi-agent-invariant/package.json +1 -1
  49. package/node_modules/pi-agent-pdf/package.json +2 -2
  50. package/node_modules/pi-agent-read/package.json +6 -6
  51. package/node_modules/pi-agent-read/src/core/tools/read/read-renderer.ts +3 -0
  52. package/node_modules/pi-agent-resource/package.json +1 -1
  53. package/node_modules/pi-agent-resource/src/resource.ts +2 -0
  54. package/node_modules/pi-agent-search/package.json +3 -3
  55. package/node_modules/pi-agent-search-text/package.json +6 -6
  56. package/node_modules/pi-agent-text/package.json +2 -2
  57. package/node_modules/pi-agent-text-anchor-constant/package.json +3 -3
  58. package/node_modules/pi-agent-text-anchor-exact/package.json +3 -3
  59. package/node_modules/pi-agent-text-anchor-line-hash/package.json +5 -5
  60. package/node_modules/pi-agent-text-editor/package.json +8 -8
  61. package/node_modules/pi-agent-text-editor/src/api/plugin-protocol.ts +1 -1
  62. package/node_modules/pi-agent-text-editor/src/api/tool-renderer.ts +3 -0
  63. package/node_modules/pi-agent-text-editor/src/core/text-editor-core.ts +41 -4
  64. package/node_modules/pi-agent-text-editor/src/core/text-mutation.ts +12 -2
  65. package/node_modules/pi-agent-text-editor-renderer/package.json +5 -5
  66. package/node_modules/pi-agent-text-editor-renderer/src/renderer.ts +1 -2
  67. package/node_modules/pi-agent-text-editor-stale-anchor/package.json +4 -4
  68. package/node_modules/pi-agent-tool-call-interception/package.json +2 -2
  69. package/node_modules/pi-agent-tool-ui/package.json +1 -1
  70. package/node_modules/pi-agent-web/package.json +6 -6
  71. package/node_modules/pi-agent-web-html/package.json +2 -2
  72. package/node_modules/pi-agent-web-image/package.json +3 -3
  73. package/node_modules/pi-agent-web-pdf/package.json +3 -3
  74. package/node_modules/pi-agent-web-text/package.json +3 -3
  75. package/package.json +36 -33
  76. package/src/composite/builtin-extensions.ts +6 -0
  77. package/src/composite/extensions-config.ts +18 -0
  78. package/src/composite/module-labels.ts +4 -0
  79. package/src/composite/module-settings-store.ts +17 -1
  80. package/src/composite/module-settings.ts +34 -4
  81. package/src/composite/preferences.ts +26 -0
  82. package/src/composite/settings-panel.ts +62 -30
  83. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/package.json +6 -6
  84. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/package.json +3 -3
  85. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/package.json +3 -3
  86. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/package.json +3 -3
  87. package/src/extensions/pi-agent-read/extensions/pi-agent-web/package.json +6 -6
  88. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/package.json +2 -2
  89. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/package.json +3 -3
  90. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/package.json +3 -3
  91. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/package.json +3 -3
  92. package/src/extensions/pi-agent-read/package.json +6 -6
  93. package/src/extensions/pi-agent-read/src/core/tools/read/read-renderer.ts +3 -0
  94. package/src/extensions/pi-agent-search/package.json +3 -3
  95. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/package.json +6 -6
  96. package/src/extensions/pi-agent-text-editor/package.json +8 -8
  97. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/package.json +3 -3
  98. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/package.json +3 -3
  99. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/package.json +5 -5
  100. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/package.json +5 -5
  101. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/renderer.ts +1 -2
  102. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/package.json +4 -4
  103. package/src/extensions/pi-agent-text-editor/src/api/plugin-protocol.ts +1 -1
  104. package/src/extensions/pi-agent-text-editor/src/api/tool-renderer.ts +3 -0
  105. package/src/extensions/pi-agent-text-editor/src/core/text-editor-core.ts +41 -4
  106. package/src/extensions/pi-agent-text-editor/src/core/text-mutation.ts +12 -2
  107. package/src/pi-agent-ide.ts +2 -1
  108. package/src/plugins/pi-agent-ide-ast/package.json +9 -9
  109. package/src/plugins/pi-agent-ide-changes/package.json +6 -6
  110. package/src/plugins/pi-agent-ide-formatter/package.json +3 -3
  111. package/src/plugins/pi-agent-ide-languages/package.json +2 -2
  112. package/src/plugins/pi-agent-ide-lint/package.json +7 -7
  113. package/src/plugins/pi-agent-ide-lsp/package.json +9 -9
  114. package/src/plugins/pi-agent-ide-terminal/index.ts +34 -0
  115. package/src/plugins/pi-agent-ide-terminal/src/renderer.ts +238 -0
  116. package/src/plugins/pi-agent-ide-terminal/src/resources.ts +461 -0
  117. package/src/plugins/pi-agent-ide-terminal/src/screen-image.ts +127 -0
  118. package/src/plugins/pi-agent-ide-terminal/src/search.ts +159 -0
  119. package/src/plugins/pi-agent-ide-terminal/src/session-manager.ts +529 -0
  120. package/src/plugins/pi-agent-ide-terminal/src/shell-profile.ts +56 -0
  121. package/src/plugins/pi-agent-ide-terminal/src/tools.ts +157 -0
  122. package/src/plugins/pi-agent-ide-terminal/src/types.ts +66 -0
  123. package/src/plugins/pi-agent-ide-terminal/src/ui.ts +336 -0
  124. package/dist/chunk-VCCMVQXU.js +0 -1
@@ -0,0 +1,159 @@
1
+ import { connectSearchPlugin } from "pi-agent-search/api/connect-plugin";
2
+ import {
3
+ SEARCH_API_VERSION,
4
+ SEARCH_PROTOCOL,
5
+ type SearchPlugin,
6
+ } from "pi-agent-search/api/plugin-protocol";
7
+ import type { SearchRequest, SearchSelectionMatch } from "pi-agent-search/api/search";
8
+
9
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
10
+
11
+ import { renderTerminalAction } from "#src/plugins/pi-agent-ide-terminal/src/renderer.js";
12
+ import type { TerminalSessionManager } from "#src/plugins/pi-agent-ide-terminal/src/session-manager.js";
13
+ import type { TerminalSessionSnapshot } from "#src/plugins/pi-agent-ide-terminal/src/types.js";
14
+
15
+ interface TerminalSearchPayload {
16
+ readonly snapshot: TerminalSessionSnapshot;
17
+ readonly query: string;
18
+ readonly matches: readonly SearchSelectionMatch[];
19
+ }
20
+
21
+ /** Register retained terminal output as a searchable resource. */
22
+ export async function registerTerminalSearch(
23
+ pi: ExtensionAPI,
24
+ manager: TerminalSessionManager,
25
+ ): Promise<void> {
26
+ const plugin = {
27
+ protocol: SEARCH_PROTOCOL,
28
+ apiVersion: SEARCH_API_VERSION,
29
+ id: "terminal",
30
+ setup(api) {
31
+ api.addResolver({ resolver: terminalSearchResolver(manager), priority: 100 });
32
+ api.describe(
33
+ "path shell:<session> searches the retained text output of that terminal, including rows outside its current screen.",
34
+ );
35
+ api.addPromptGuideline(
36
+ "Use search with path shell:<session> to find text in retained terminal output. Read the same shell source with the returned line number when more context is needed.",
37
+ );
38
+ },
39
+ } satisfies SearchPlugin;
40
+ await connectSearchPlugin(pi, plugin);
41
+ }
42
+
43
+ function terminalSearchResolver(manager: TerminalSessionManager) {
44
+ return {
45
+ id: "terminal",
46
+ async tryResolve(request: SearchRequest) {
47
+ if (request.path === undefined || !request.path.startsWith("shell:")) {
48
+ return { kind: "not-handled" as const };
49
+ }
50
+ const session = manager.get(request.path);
51
+ if (session === undefined) {
52
+ return {
53
+ kind: "failed" as const,
54
+ error: new Error(`Unknown terminal session ${request.path}`),
55
+ };
56
+ }
57
+ const snapshot = manager.snapshot(session);
58
+ const matches = findTerminalMatches(snapshot, request);
59
+ return {
60
+ kind: "resolved" as const,
61
+ payload: {
62
+ snapshot,
63
+ query: request.query,
64
+ matches,
65
+ },
66
+ };
67
+ },
68
+ format(payload: unknown) {
69
+ const result = parsePayload(payload);
70
+ const lines = result.matches.map(
71
+ (match) => `${result.snapshot.source}:${match.lineNumber}: ${match.lineText}`,
72
+ );
73
+ return {
74
+ content: [
75
+ {
76
+ type: "text" as const,
77
+ text:
78
+ lines.length === 0
79
+ ? `No matches in ${result.snapshot.source}`
80
+ : `${lines.join("\n")}\n\n${lines.length} match${lines.length === 1 ? "" : "es"} in ${result.snapshot.source}`,
81
+ },
82
+ ],
83
+ details: { source: result.snapshot.source, payload: result },
84
+ };
85
+ },
86
+ renderResult(
87
+ result: { details: unknown },
88
+ _options: unknown,
89
+ theme: Parameters<typeof renderTerminalAction>[4],
90
+ ) {
91
+ const details = result.details;
92
+ const payload = isRecord(details) ? parsePayload(details.payload) : parsePayload(undefined);
93
+ return renderTerminalAction(
94
+ payload.snapshot,
95
+ "search",
96
+ JSON.stringify(payload.query),
97
+ payload.matches.slice(-6).map((match) => `${match.lineNumber}: ${match.lineText}`),
98
+ theme,
99
+ );
100
+ },
101
+ };
102
+ }
103
+
104
+ export function findTerminalMatches(
105
+ snapshot: TerminalSessionSnapshot,
106
+ request: SearchRequest,
107
+ ): SearchSelectionMatch[] {
108
+ const query = request.caseSensitive === true ? request.query : request.query.toLocaleLowerCase();
109
+ if (query.length === 0) return [];
110
+ const matches: SearchSelectionMatch[] = [];
111
+ const maximum = request.limit ?? 100;
112
+ for (const [index, lineText] of snapshot.output.replaceAll("\r", "").split("\n").entries()) {
113
+ const haystack = request.caseSensitive === true ? lineText : lineText.toLocaleLowerCase();
114
+ let column = 0;
115
+ while (matches.length < maximum) {
116
+ const startColumn = haystack.indexOf(query, column);
117
+ if (startColumn < 0) break;
118
+ const endColumn = startColumn + query.length;
119
+ const wholeWord =
120
+ request.wholeWord !== true || isWordBoundary(haystack, startColumn, endColumn);
121
+ if (wholeWord) {
122
+ matches.push({
123
+ source: snapshot.source,
124
+ lineNumber: index + 1,
125
+ startColumn,
126
+ endColumn,
127
+ matchedText: lineText.slice(startColumn, endColumn),
128
+ lineText,
129
+ });
130
+ }
131
+ column = Math.max(endColumn, startColumn + 1);
132
+ }
133
+ if (matches.length >= maximum) break;
134
+ }
135
+ return matches;
136
+ }
137
+
138
+ function isWordBoundary(text: string, start: number, end: number): boolean {
139
+ return !/[\p{L}\p{N}_]/u.test(text[start - 1] ?? "") && !/[\p{L}\p{N}_]/u.test(text[end] ?? "");
140
+ }
141
+
142
+ function parsePayload(value: unknown): TerminalSearchPayload {
143
+ if (!isTerminalSearchPayload(value)) throw new TypeError("Invalid terminal search result");
144
+ return value;
145
+ }
146
+
147
+ function isTerminalSearchPayload(value: unknown): value is TerminalSearchPayload {
148
+ return (
149
+ isRecord(value) &&
150
+ typeof value.query === "string" &&
151
+ Array.isArray(value.matches) &&
152
+ isRecord(value.snapshot) &&
153
+ typeof value.snapshot.source === "string"
154
+ );
155
+ }
156
+
157
+ function isRecord(value: unknown): value is Record<string, unknown> {
158
+ return typeof value === "object" && value !== null;
159
+ }
@@ -0,0 +1,529 @@
1
+ import { spawn as spawnProcess } from "node:child_process";
2
+ import { createRequire } from "node:module";
3
+ import { randomUUID } from "node:crypto";
4
+ import { stripVTControlCharacters } from "node:util";
5
+
6
+ import type { Terminal as XtermTerminal } from "@xterm/headless";
7
+ import type { IPty, IPtyForkOptions, IWindowsPtyForkOptions } from "node-pty";
8
+
9
+ import type {
10
+ ShellProfile,
11
+ TerminalSession,
12
+ TerminalSessionSnapshot,
13
+ } from "#src/plugins/pi-agent-ide-terminal/src/types.js";
14
+
15
+ const require = createRequire(import.meta.url);
16
+ const MAX_OUTPUT_CHARS = 1_000_000;
17
+ const DEFAULT_COLS = 100;
18
+ const DEFAULT_ROWS = 30;
19
+ const STOP_GRACE_MS = 2_000;
20
+
21
+ type SessionListener = (session: TerminalSession) => void;
22
+
23
+ /** Owns live PTYs, bounded output, virtual screens, and process-tree termination. */
24
+ export class TerminalSessionManager {
25
+ readonly #createId: () => string;
26
+ readonly #sessions = new Map<string, TerminalSession>();
27
+ readonly #changeListeners = new Set<SessionListener>();
28
+ readonly #completionListeners = new Set<SessionListener>();
29
+ #disposed = false;
30
+
31
+ public constructor(createId: () => string = defaultSessionId) {
32
+ this.#createId = createId;
33
+ }
34
+
35
+ public onDidChange(listener: SessionListener): () => void {
36
+ this.#changeListeners.add(listener);
37
+ return () => this.#changeListeners.delete(listener);
38
+ }
39
+
40
+ public onDidComplete(listener: SessionListener): () => void {
41
+ this.#completionListeners.add(listener);
42
+ return () => this.#completionListeners.delete(listener);
43
+ }
44
+
45
+ public list(): readonly TerminalSessionSnapshot[] {
46
+ return [...this.#sessions.values()]
47
+ .sort((left, right) => right.startedAt - left.startedAt)
48
+ .map((session) => this.snapshot(session));
49
+ }
50
+
51
+ public get(sourceOrId: string): TerminalSession | undefined {
52
+ return this.#sessions.get(normalizeSessionId(sourceOrId));
53
+ }
54
+
55
+ public snapshot(session: TerminalSession, now = Date.now()): TerminalSessionSnapshot {
56
+ return {
57
+ id: session.id,
58
+ source: session.source,
59
+ command: session.command,
60
+ cwd: session.cwd,
61
+ shell: session.shell.displayName,
62
+ shellFamily: session.shell.family,
63
+ background: session.background,
64
+ status: session.status,
65
+ startedAt: session.startedAt,
66
+ ...(session.endedAt === undefined ? {} : { endedAt: session.endedAt }),
67
+ elapsedMs: (session.endedAt ?? now) - session.startedAt,
68
+ ...(session.exitCode === undefined ? {} : { exitCode: session.exitCode }),
69
+ ...(session.signal === undefined ? {} : { signal: session.signal }),
70
+ ...(session.error === undefined ? {} : { error: session.error }),
71
+ output: session.output,
72
+ outputStart: session.outputStart,
73
+ outputEnd: session.outputStart + session.output.length,
74
+ truncated: session.outputStart > 0,
75
+ cols: session.cols,
76
+ rows: session.rows,
77
+ };
78
+ }
79
+
80
+ public start(options: {
81
+ readonly command: string;
82
+ readonly background: boolean;
83
+ readonly cwd: string;
84
+ readonly shell: ShellProfile;
85
+ readonly cols?: number;
86
+ readonly rows?: number;
87
+ }): TerminalSession {
88
+ if (this.#disposed) throw new Error("Terminal session manager is closed");
89
+ const id = this.#createId();
90
+ if (!/^[a-f\d]{12}$/u.test(id) || this.#sessions.has(id)) {
91
+ throw new Error("Terminal session IDs must be unique 12-character hexadecimal values");
92
+ }
93
+ const cols = options.cols ?? DEFAULT_COLS;
94
+ const rows = options.rows ?? DEFAULT_ROWS;
95
+ const screen = createScreen(cols, rows);
96
+ let resolveCompletion = (_session: TerminalSession): void => {};
97
+ const completion = new Promise<TerminalSession>((resolve) => {
98
+ resolveCompletion = resolve;
99
+ });
100
+ const base = {
101
+ id,
102
+ source: `shell:${id}`,
103
+ command: options.command,
104
+ background: options.background,
105
+ cwd: options.cwd,
106
+ shell: options.shell,
107
+ startedAt: Date.now(),
108
+ cols,
109
+ rows,
110
+ screen,
111
+ status: "running" as const,
112
+ output: "",
113
+ outputStart: 0,
114
+ screenReady: Promise.resolve(),
115
+ completion,
116
+ resolveCompletion,
117
+ completionDelivered: false,
118
+ };
119
+
120
+ let process: IPty;
121
+ try {
122
+ const pty = require("node-pty") as {
123
+ spawn(
124
+ executable: string,
125
+ args: string[],
126
+ options: IPtyForkOptions | IWindowsPtyForkOptions,
127
+ ): IPty;
128
+ };
129
+ const ptyOptions: IPtyForkOptions | IWindowsPtyForkOptions = {
130
+ name: "xterm-256color",
131
+ cols,
132
+ rows,
133
+ cwd: options.cwd,
134
+ env: cleanEnvironment(processEnvironment()),
135
+ };
136
+ process = pty.spawn(
137
+ options.shell.executable,
138
+ [...options.shell.commandArgs(options.command)],
139
+ ptyOptions,
140
+ );
141
+ } catch (error) {
142
+ const session: TerminalSession = {
143
+ ...base,
144
+ status: "failed",
145
+ endedAt: Date.now(),
146
+ error: errorMessage(error),
147
+ };
148
+ this.#sessions.set(id, session);
149
+ resolveCompletion(session);
150
+ queueMicrotask(() => this.#emitCompleted(session));
151
+ return session;
152
+ }
153
+
154
+ const session: TerminalSession = { ...base, process };
155
+ this.#sessions.set(id, session);
156
+ process.onData((data) => this.#appendOutput(session, data));
157
+ process.onExit(({ exitCode, signal }) => {
158
+ if (isTerminalStatus(session.status)) return;
159
+ session.endedAt = Date.now();
160
+ session.exitCode = exitCode;
161
+ if (signal !== 0) session.signal = signal;
162
+ session.status =
163
+ session.status === "stopping" ? "stopped" : exitCode === 0 ? "completed" : "failed";
164
+ session.resolveCompletion(session);
165
+ this.#emitChanged(session);
166
+ this.#emitCompleted(session);
167
+ });
168
+ this.#emitChanged(session);
169
+ return session;
170
+ }
171
+
172
+ public async wait(sourceOrId: string, signal?: AbortSignal): Promise<TerminalSession> {
173
+ const session = this.required(sourceOrId);
174
+ if (isTerminalStatus(session.status)) return session;
175
+ if (signal?.aborted === true) {
176
+ await this.stop(session.source, "cancelled");
177
+ return session;
178
+ }
179
+ return await new Promise<TerminalSession>((resolve, reject) => {
180
+ const onAbort = (): void => {
181
+ void this.stop(session.source, "cancelled").then(resolve, reject);
182
+ };
183
+ signal?.addEventListener("abort", onAbort, { once: true });
184
+ session.completion.then((completed) => {
185
+ signal?.removeEventListener("abort", onAbort);
186
+ resolve(completed);
187
+ }, reject);
188
+ });
189
+ }
190
+
191
+ /** Wait for PTY output triggered by input to settle before capturing the screen. */
192
+ public async waitForOutputAfter(session: TerminalSession, previousEnd: number): Promise<void> {
193
+ const deadline = Date.now() + 300;
194
+ let lastEnd = previousEnd;
195
+ let changedAt: number | undefined;
196
+ while (Date.now() < deadline) {
197
+ const currentEnd = session.outputStart + session.output.length;
198
+ if (currentEnd !== lastEnd) {
199
+ lastEnd = currentEnd;
200
+ changedAt = Date.now();
201
+ await session.screenReady;
202
+ } else if (changedAt !== undefined && Date.now() - changedAt >= 40) {
203
+ return;
204
+ }
205
+ await delay(10);
206
+ }
207
+ await session.screenReady;
208
+ }
209
+ /** Capture the current virtual terminal viewport as plain text rows. */
210
+ public screenRows(session: TerminalSession): readonly string[] {
211
+ const buffer = session.screen.buffer.active;
212
+ return Array.from({ length: session.rows }, (_, row) =>
213
+ (buffer.getLine(buffer.baseY + row)?.translateToString(true) ?? "").trimEnd(),
214
+ );
215
+ }
216
+
217
+ /** Return the densest changed screen region, marking the cursor when it is inside. */
218
+ public screenChangeRegion(
219
+ session: TerminalSession,
220
+ before: readonly string[],
221
+ count = 6,
222
+ ): { readonly lines: readonly string[]; readonly startRow: number } {
223
+ const after = this.screenRows(session);
224
+ const size = Math.max(1, Math.min(session.rows, count));
225
+ let bestStart = Math.max(0, session.screen.buffer.active.cursorY - Math.floor(size / 2));
226
+ let bestScore = -1;
227
+ for (let start = 0; start <= session.rows - size; start += 1) {
228
+ let score = 0;
229
+ for (let row = start; row < start + size; row += 1) {
230
+ const previous = before[row] ?? "";
231
+ const current = after[row] ?? "";
232
+ const introduced = current.length > 0 && !before.includes(current);
233
+ const removed = previous.length > 0 && current.length === 0;
234
+ if (previous !== current && (introduced || removed)) score += 1;
235
+ }
236
+ if (score > bestScore) {
237
+ bestScore = score;
238
+ bestStart = start;
239
+ }
240
+ }
241
+ const cursor = session.screen.buffer.active;
242
+ const lines = after.slice(bestStart, bestStart + size).map((text, index) => {
243
+ const row = bestStart + index;
244
+ if (row !== cursor.cursorY) return text;
245
+ const padded = text.padEnd(cursor.cursorX, " ");
246
+ return `${padded.slice(0, cursor.cursorX)}▌${padded.slice(cursor.cursorX)}`;
247
+ });
248
+ return { lines, startRow: bestStart };
249
+ }
250
+
251
+ public screenChangeWindow(
252
+ session: TerminalSession,
253
+ before: readonly string[],
254
+ count = 6,
255
+ ): readonly string[] {
256
+ return this.screenChangeRegion(session, before, count).lines;
257
+ }
258
+ /** Return the latest meaningful rows from the current virtual terminal screen. */
259
+ public screenTail(session: TerminalSession, count = session.rows): readonly string[] {
260
+ const buffer = session.screen.buffer.active;
261
+ const firstRow = Math.max(0, buffer.baseY);
262
+ const lines: string[] = [];
263
+ for (let row = 0; row < session.rows; row += 1) {
264
+ const line = buffer
265
+ .getLine(firstRow + row)
266
+ ?.translateToString(true)
267
+ .trimEnd();
268
+ if (line !== undefined && line.length > 0) lines.push(line);
269
+ }
270
+ return lines.slice(-Math.max(0, count));
271
+ }
272
+ public write(sourceOrId: string, data: string): void {
273
+ const session = this.requiredRunning(sourceOrId);
274
+ session.process?.write(data);
275
+ }
276
+
277
+ public sendKeys(sourceOrId: string, keys: string): void {
278
+ const session = this.requiredRunning(sourceOrId);
279
+ session.process?.write(encodeTerminalKeys(keys));
280
+ }
281
+
282
+ public async stop(
283
+ sourceOrId: string,
284
+ finalStatus: "stopped" | "cancelled" = "stopped",
285
+ ): Promise<TerminalSession> {
286
+ const session = this.required(sourceOrId);
287
+ if (isTerminalStatus(session.status)) return session;
288
+ session.status = "stopping";
289
+ this.#emitChanged(session);
290
+ await terminateProcessTree(session, false);
291
+ const graceful = await Promise.race([
292
+ session.completion.then(() => true),
293
+ delay(STOP_GRACE_MS).then(() => false),
294
+ ]);
295
+ if (!graceful) {
296
+ await terminateProcessTree(session, true);
297
+ await Promise.race([session.completion, delay(1_000)]);
298
+ }
299
+ if (!isTerminalStatus(session.status)) {
300
+ session.status = finalStatus;
301
+ session.endedAt = Date.now();
302
+ session.resolveCompletion(session);
303
+ this.#emitCompleted(session);
304
+ }
305
+ if (finalStatus === "cancelled") session.status = "cancelled";
306
+ this.#emitChanged(session);
307
+ return session;
308
+ }
309
+
310
+ /** Terminate a live process if needed, dispose its screen, and forget the session. */
311
+ public async delete(sourceOrId: string): Promise<void> {
312
+ const session = this.required(sourceOrId);
313
+ session.completionDelivered = true;
314
+ await this.stop(session.source);
315
+ session.screen.dispose();
316
+ this.#sessions.delete(session.id);
317
+ this.#emitChanged(session);
318
+ }
319
+ public async screenLines(sourceOrId: string): Promise<readonly string[]> {
320
+ const session = this.required(sourceOrId);
321
+ await session.screenReady;
322
+ const buffer = session.screen.buffer.active;
323
+ const lines: string[] = [];
324
+ const start = Math.max(0, buffer.baseY);
325
+ for (let row = start; row < start + session.rows; row += 1) {
326
+ lines.push(buffer.getLine(row)?.translateToString(true) ?? "");
327
+ }
328
+ return lines;
329
+ }
330
+
331
+ public cursor(sourceOrId: string): { readonly x: number; readonly y: number } {
332
+ const session = this.required(sourceOrId);
333
+ return { x: session.screen.buffer.active.cursorX, y: session.screen.buffer.active.cursorY };
334
+ }
335
+
336
+ public async dispose(): Promise<void> {
337
+ if (this.#disposed) return;
338
+ this.#disposed = true;
339
+ await Promise.all(
340
+ [...this.#sessions.values()]
341
+ .filter((session) => !isTerminalStatus(session.status))
342
+ .map((session) => this.stop(session.source)),
343
+ );
344
+ for (const session of this.#sessions.values()) session.screen.dispose();
345
+ this.#changeListeners.clear();
346
+ this.#completionListeners.clear();
347
+ }
348
+
349
+ private required(sourceOrId: string): TerminalSession {
350
+ const session = this.get(sourceOrId);
351
+ if (session === undefined) throw new Error(`Unknown terminal session ${sourceOrId}`);
352
+ return session;
353
+ }
354
+
355
+ private requiredRunning(sourceOrId: string): TerminalSession {
356
+ const session = this.required(sourceOrId);
357
+ if (session.status !== "running") {
358
+ throw new Error(
359
+ `Terminal session ${session.source} is ${session.status}; input is unavailable`,
360
+ );
361
+ }
362
+ return session;
363
+ }
364
+
365
+ #appendOutput(session: TerminalSession, data: string): void {
366
+ const plain = stripVTControlCharacters(data);
367
+ session.output += plain;
368
+ if (session.output.length > MAX_OUTPUT_CHARS) {
369
+ const removed = session.output.length - MAX_OUTPUT_CHARS;
370
+ session.output = session.output.slice(removed);
371
+ session.outputStart += removed;
372
+ }
373
+ session.screenReady = session.screenReady.then(
374
+ () =>
375
+ new Promise<void>((resolve) => {
376
+ session.screen.write(data, resolve);
377
+ }),
378
+ );
379
+ this.#emitChanged(session);
380
+ }
381
+
382
+ #emitChanged(session: TerminalSession): void {
383
+ for (const listener of this.#changeListeners) listener(session);
384
+ }
385
+
386
+ #emitCompleted(session: TerminalSession): void {
387
+ for (const listener of this.#completionListeners) listener(session);
388
+ }
389
+ }
390
+
391
+ function createScreen(cols: number, rows: number): XtermTerminal {
392
+ const { Terminal } = require("@xterm/headless") as {
393
+ Terminal: new (options: {
394
+ cols: number;
395
+ rows: number;
396
+ scrollback: number;
397
+ allowProposedApi: boolean;
398
+ }) => XtermTerminal;
399
+ };
400
+ return new Terminal({ cols, rows, scrollback: 2_000, allowProposedApi: true });
401
+ }
402
+
403
+ function defaultSessionId(): string {
404
+ return randomUUID().replaceAll("-", "").slice(0, 12);
405
+ }
406
+ function normalizeSessionId(sourceOrId: string): string {
407
+ return sourceOrId.startsWith("shell:") ? sourceOrId.slice("shell:".length) : sourceOrId;
408
+ }
409
+
410
+ function isTerminalStatus(status: TerminalSession["status"]): boolean {
411
+ return status !== "running" && status !== "stopping";
412
+ }
413
+
414
+ function processEnvironment(): Record<string, string | undefined> {
415
+ return process.env;
416
+ }
417
+
418
+ function cleanEnvironment(environment: Record<string, string | undefined>): Record<string, string> {
419
+ return {
420
+ ...Object.fromEntries(
421
+ Object.entries(environment).filter(
422
+ (entry): entry is [string, string] => entry[1] !== undefined,
423
+ ),
424
+ ),
425
+ PAGER: "cat",
426
+ GIT_PAGER: "cat",
427
+ SYSTEMD_PAGER: "cat",
428
+ GH_PAGER: "cat",
429
+ };
430
+ }
431
+
432
+ /** Encode named terminal keys and Unix caret control notation as PTY input. */
433
+ export function encodeTerminalKeys(value: string): string {
434
+ return value
435
+ .split(/[\s,]+/u)
436
+ .filter(Boolean)
437
+ .map(encodeTerminalKey)
438
+ .join("");
439
+ }
440
+
441
+ function encodeTerminalKey(value: string): string {
442
+ if (/^\^[?@A-Z[\\\]^_]$/iu.test(value)) {
443
+ const character = value.slice(1).toUpperCase();
444
+ return character === "?" ? "\u007f" : String.fromCharCode(character.charCodeAt(0) & 31);
445
+ }
446
+
447
+ const parts = value.toLowerCase().split("+");
448
+ const key = parts.pop() ?? "";
449
+ const modifiers = new Set(parts);
450
+ if (
451
+ [...modifiers].some(
452
+ (modifier) => !["ctrl", "control", "alt", "meta", "shift"].includes(modifier),
453
+ )
454
+ ) {
455
+ throw new Error(`Unsupported terminal key ${value}`);
456
+ }
457
+ const ctrl = modifiers.has("ctrl") || modifiers.has("control");
458
+ const alt = modifiers.has("alt") || modifiers.has("meta");
459
+ const shift = modifiers.has("shift");
460
+ if (ctrl && key.length === 1 && /[a-z@[\\\]^_?]/u.test(key)) {
461
+ const character = key.toUpperCase();
462
+ const control =
463
+ character === "?" ? "\u007f" : String.fromCharCode(character.charCodeAt(0) & 31);
464
+ return alt ? `\u001b${control}` : control;
465
+ }
466
+
467
+ const simple: Readonly<Record<string, string>> = {
468
+ enter: "\r",
469
+ tab: "\t",
470
+ escape: "\u001b",
471
+ esc: "\u001b",
472
+ backspace: "\u007f",
473
+ home: "\u001b[H",
474
+ end: "\u001b[F",
475
+ delete: "\u001b[3~",
476
+ };
477
+ if (!ctrl && !alt && !shift && simple[key] !== undefined) return simple[key];
478
+ if (alt && !ctrl && !shift && simple[key] !== undefined) return `\u001b${simple[key]}`;
479
+
480
+ const finals: Readonly<Record<string, string>> = {
481
+ up: "A",
482
+ down: "B",
483
+ right: "C",
484
+ left: "D",
485
+ home: "H",
486
+ end: "F",
487
+ };
488
+ const final = finals[key];
489
+ if (final !== undefined) {
490
+ if (!ctrl && !alt && !shift) return `\u001b[${final}`;
491
+ const modifier = 1 + (shift ? 1 : 0) + (alt ? 2 : 0) + (ctrl ? 4 : 0);
492
+ return `\u001b[1;${modifier}${final}`;
493
+ }
494
+ if (alt && !ctrl && key.length === 1) return `\u001b${shift ? key.toUpperCase() : key}`;
495
+ throw new Error(`Unsupported terminal key ${value}`);
496
+ }
497
+
498
+ async function terminateProcessTree(session: TerminalSession, force: boolean): Promise<void> {
499
+ const process = session.process;
500
+ if (process === undefined) return;
501
+ if (globalThis.process.platform !== "win32") {
502
+ try {
503
+ globalThis.process.kill(-process.pid, force ? "SIGKILL" : "SIGTERM");
504
+ return;
505
+ } catch {
506
+ try {
507
+ process.kill(force ? "SIGKILL" : "SIGTERM");
508
+ } catch {}
509
+ return;
510
+ }
511
+ }
512
+ await new Promise<void>((resolve) => {
513
+ const child = spawnProcess(
514
+ "taskkill.exe",
515
+ ["/PID", String(process.pid), "/T", ...(force ? ["/F"] : [])],
516
+ { windowsHide: true, stdio: "ignore" },
517
+ );
518
+ child.once("error", () => resolve());
519
+ child.once("exit", () => resolve());
520
+ });
521
+ }
522
+
523
+ function delay(milliseconds: number): Promise<void> {
524
+ return new Promise((resolve) => setTimeout(resolve, milliseconds));
525
+ }
526
+
527
+ function errorMessage(error: unknown): string {
528
+ return error instanceof Error ? error.message : String(error);
529
+ }