Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

clientTerminals.ts

448 lines17.1 KB

1import * as Deferred from "effect/Deferred";
2import * as Duration from "effect/Duration";
3import * as Effect from "effect/Effect";
4import * as Exit from "effect/Exit";
5import * as Fiber from "effect/Fiber";
6import * as Scope from "effect/Scope";
7import * as Semaphore from "effect/Semaphore";
8import * as Stream from "effect/Stream";
9import * as ChildProcess from "effect/process/ChildProcess";
10import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
11import * as EffectAcpErrors from "effect-acp/errors";
12import type * as EffectAcpSchema from "effect-acp/compat";
13import * as NodeBuffer from "node:buffer";
14​
15/**
16 * Client-side implementation of the ACP `terminal` capability.
17 *
18 * Agents create terminals to run commands through the client
19 * (`terminal/create`), poll buffered output, await exit, kill, and release
20 * them. Terminals also appear as embedded tool-call content, which
21 * {@link resolveEmbeddedTerminalContent} rewrites into plain text so the
22 * existing tool-call projection renders live command output.
23 */
24​
25const MAX_LIVE_TERMINALS = 16;
26const MAX_UNRELEASED_TERMINALS = 64;
27const MAX_RETAINED_TERMINALS = 32;
28const MAX_RETAINED_OUTPUT_BYTES = 16 * 1024 * 1024;
29const DEFAULT_OUTPUT_BYTE_LIMIT = 4 * 1024 * 1024;
30const MAX_OUTPUT_BYTE_LIMIT = 8 * 1024 * 1024;
31​
32const terminalRequestError = (message: string, cause?: unknown) =>
33 EffectAcpErrors.AcpRequestError.internalError(
34 message,
35 undefined,
36 cause === undefined ? {} : { cause },
37 );
38​
39interface OutputBufferState {
40 chunks: Array<Uint8Array>;
41 bytes: number;
42 truncated: boolean;
43 readonly limit: number;
45​
46function trimOutputStart(state: OutputBufferState, bytes: number): void {
47 let remaining = Math.min(bytes, state.bytes);
48 while (remaining > 0) {
49 const head = state.chunks[0]!;
50 if (head.byteLength <= remaining) {
51 state.chunks.shift();
52 state.bytes -= head.byteLength;
53 remaining -= head.byteLength;
54 } else {
55 state.chunks[0] = head.subarray(remaining);
56 state.bytes -= remaining;
57 remaining = 0;
58 }
59 state.truncated = true;
60 }
62​
63function appendOutput(state: OutputBufferState, chunk: Uint8Array): void {
64 state.chunks.push(chunk);
65 state.bytes += chunk.byteLength;
66 // The spec requires truncation from the beginning of the output.
67 if (state.bytes > state.limit) trimOutputStart(state, state.bytes - state.limit);
69​
70function readOutput(state: OutputBufferState): string {
71 let combined: Uint8Array = NodeBuffer.Buffer.concat(state.chunks, state.bytes);
72 if (state.truncated) {
73 // Drop leading UTF-8 continuation bytes so truncation lands on a
74 // character boundary, as the spec requires.
75 let start = 0;
76 while (start < combined.byteLength && (combined[start]! & 0b1100_0000) === 0b1000_0000) {
77 start += 1;
78 }
79 combined = combined.subarray(start);
80 }
81 return NodeBuffer.Buffer.from(combined).toString("utf8");
83​
84function terminalExitSignal(error: unknown): string | null {
85 const cause = error instanceof Error ? error.cause : undefined;
86 const message =
87 cause instanceof Error ? cause.message : error instanceof Error ? error.message : "";
88 return message.match(/signal: '([^']+)'/u)?.[1] ?? null;
90​
91export interface AcpTerminalOutputSnapshot {
92 readonly output: string;
93 readonly truncated: boolean;
94 readonly exitStatus: EffectAcpSchema.TerminalExitStatus | undefined;
96​
97interface ManagedAcpTerminal {
98 readonly terminalId: string;
99 readonly sessionId: string;
100 /** The spawned command with args, kept for MCP-fallback identification. */
101 readonly commandLine: string;
102 readonly buffer: OutputBufferState;
103 readonly exit: Deferred.Deferred<EffectAcpSchema.WaitForTerminalExitResponse>;
104 readonly kill: Effect.Effect<void>;
105 /** Closes the terminal's scope, killing the process if still running. */
106 readonly dispose: Effect.Effect<void>;
107 exitStatus: EffectAcpSchema.TerminalExitStatus | undefined;
108 released: boolean;
110​
111export interface AcpClientTerminals {
112 readonly create: (
113 request: EffectAcpSchema.CreateTerminalRequest,
114 ) => Effect.Effect<EffectAcpSchema.CreateTerminalResponse, EffectAcpErrors.AcpRequestError>;
115 readonly output: (
116 request: EffectAcpSchema.TerminalOutputRequest,
117 ) => Effect.Effect<EffectAcpSchema.TerminalOutputResponse, EffectAcpErrors.AcpRequestError>;
118 readonly waitForExit: (
119 request: EffectAcpSchema.WaitForTerminalExitRequest,
120 ) => Effect.Effect<EffectAcpSchema.WaitForTerminalExitResponse, EffectAcpErrors.AcpRequestError>;
121 readonly kill: (
122 request: EffectAcpSchema.KillTerminalRequest,
123 ) => Effect.Effect<EffectAcpSchema.KillTerminalResponse, EffectAcpErrors.AcpRequestError>;
124 readonly release: (
125 request: EffectAcpSchema.ReleaseTerminalRequest,
126 ) => Effect.Effect<EffectAcpSchema.ReleaseTerminalResponse, EffectAcpErrors.AcpRequestError>;
127 /** Buffered output for embedded tool-call content; survives release. */
128 readonly readOutputSnapshot: (
129 sessionId: string,
130 terminalId: string,
131 ) => AcpTerminalOutputSnapshot | undefined;
132 /** Command line a terminal was created with; presentation-only lookup. */
133 readonly readCommandLine: (terminalId: string) => string | undefined;
134 /** Kills every terminal that is still running. Safe to call repeatedly. */
135 readonly disposeAll: Effect.Effect<void>;
137​
138export interface AcpClientTerminalsOptions {
139 /** Devin sends shell source in command, rather than an executable plus args. */
140 readonly shellCommands?: boolean | undefined;
141 readonly defaultCwd: string;
142 readonly environment?: NodeJS.ProcessEnv | undefined;
143 readonly environmentForSession?:
144 | ((sessionId: string) => NodeJS.ProcessEnv | undefined)
145 | undefined;
146 readonly forceKillAfter?: Duration.Input | undefined;
148​
149function acpTerminalCommand(input: {
150 readonly request: EffectAcpSchema.CreateTerminalRequest;
151 readonly shellCommands?: boolean | undefined;
152 readonly defaultCwd: string;
153 readonly environment?: NodeJS.ProcessEnv | undefined;
154 readonly forceKillAfter?: Duration.Input | undefined;
155}) {
156 return ChildProcess.make(input.request.command, input.request.args ?? [], {
157 cwd: input.request.cwd ?? input.defaultCwd,
158 ...(input.environment === undefined ? {} : { env: input.environment }),
159 shell: input.shellCommands === true && (input.request.args?.length ?? 0) === 0,
160 forceKillAfter: input.forceKillAfter ?? "5 seconds",
161 });
163​
164export const makeAcpClientTerminals = Effect.fn("makeAcpClientTerminals")(function* (
165 options: AcpClientTerminalsOptions,
166): Effect.fn.Return<AcpClientTerminals, never, ChildProcessSpawner.ChildProcessSpawner> {
167 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
168 const creationPermit = yield* Semaphore.make(1);
169 const terminals = new Map<string, ManagedAcpTerminal>();
170 let nextTerminalNumber = 1;
171​
172 const enforceTotalOutputLimit = (): void => {
173 let excess =
174 Array.from(terminals.values()).reduce((total, terminal) => total + terminal.buffer.bytes, 0) -
175 MAX_RETAINED_OUTPUT_BYTES;
176 if (excess <= 0) return;
177 for (const terminal of terminals.values()) {
178 const before = terminal.buffer.bytes;
179 trimOutputStart(terminal.buffer, excess);
180 excess -= before - terminal.buffer.bytes;
181 if (excess <= 0) return;
182 }
183 };
184​
185 const pruneReleasedSnapshots = (): void => {
186 const released = Array.from(terminals.values()).filter((terminal) => terminal.released);
187 let retainedBytes = released.reduce((total, terminal) => total + terminal.buffer.bytes, 0);
188 while (released.length > MAX_RETAINED_TERMINALS || retainedBytes > MAX_RETAINED_OUTPUT_BYTES) {
189 const terminal = released.shift();
190 if (terminal === undefined) break;
191 retainedBytes -= terminal.buffer.bytes;
192 terminals.delete(terminal.terminalId);
193 }
194 };
195​
196 const requireTerminal = (
197 sessionId: string,
198 terminalId: string,
199 operation: string,
200 ): Effect.Effect<ManagedAcpTerminal, EffectAcpErrors.AcpRequestError> => {
201 const terminal = terminals.get(terminalId);
202 if (terminal === undefined || terminal.sessionId !== sessionId || terminal.released) {
203 return Effect.fail(
204 terminalRequestError(`ACP ${operation} received an unknown terminal ID '${terminalId}'.`),
205 );
206 }
207 return Effect.succeed(terminal);
208 };
209​
210 const create: AcpClientTerminals["create"] = (request) =>
211 creationPermit.withPermit(
212 Effect.uninterruptibleMask((restore) =>
213 Effect.gen(function* () {
214 const liveCount = Array.from(terminals.values()).filter(
215 (terminal) => !terminal.released && terminal.exitStatus === undefined,
216 ).length;
217 const unreleasedCount = Array.from(terminals.values()).filter(
218 (terminal) => !terminal.released,
219 ).length;
220 if (unreleasedCount >= MAX_UNRELEASED_TERMINALS) {
221 return yield* terminalRequestError(
222 `ACP terminal/create exceeded the limit of ${MAX_UNRELEASED_TERMINALS} unreleased terminals.`,
223 );
224 }
225 if (liveCount >= MAX_LIVE_TERMINALS) {
226 return yield* terminalRequestError(
227 `ACP terminal/create exceeded the limit of ${MAX_LIVE_TERMINALS} concurrent terminals.`,
228 );
229 }
230 const requestEnvironment = Object.fromEntries(
231 (request.env ?? []).map((variable) => [variable.name, variable.value] as const),
232 );
233 const sessionEnvironment = options.environmentForSession?.(request.sessionId);
234 const environment =
235 options.environment === undefined &&
236 sessionEnvironment === undefined &&
237 (request.env?.length ?? 0) === 0
238 ? undefined
239 : { ...options.environment, ...sessionEnvironment, ...requestEnvironment };
240 // Each terminal owns a scope so the spawned process is reliably reaped:
241 // closing the scope kills a still-running command and frees the handle.
242 const terminalScope = yield* Scope.make();
243 const child = yield* restore(
244 spawner
245 .spawn(
246 acpTerminalCommand({
247 request,
248 shellCommands: options.shellCommands,
249 defaultCwd: options.defaultCwd,
250 environment,
251 forceKillAfter: options.forceKillAfter,
252 }),
253 )
254 .pipe(
255 Effect.provideService(Scope.Scope, terminalScope),
256 Effect.mapError((cause) =>
257 terminalRequestError(
258 `Could not start terminal command '${request.command}'.`,
259 cause,
260 ),
261 ),
262 ),
263 ).pipe(
264 Effect.onExit((exit) =>
265 Exit.isFailure(exit) ? Scope.close(terminalScope, Exit.void) : Effect.void,
266 ),
267 );
268​
269 const terminalId = `t3-term-${nextTerminalNumber}`;
270 nextTerminalNumber += 1;
271 const record: ManagedAcpTerminal = {
272 terminalId,
273 sessionId: request.sessionId,
274 commandLine: [request.command, ...(request.args ?? [])].join(" "),
275 buffer: {
276 chunks: [],
277 bytes: 0,
278 truncated: false,
279 limit: Math.min(
280 request.outputByteLimit ?? DEFAULT_OUTPUT_BYTE_LIMIT,
281 MAX_OUTPUT_BYTE_LIMIT,
282 ),
283 },
284 exit: yield* Deferred.make<EffectAcpSchema.WaitForTerminalExitResponse>(),
285 kill: child.kill().pipe(Effect.ignore),
286 dispose: Scope.close(terminalScope, Exit.void).pipe(Effect.ignore),
287 exitStatus: undefined,
288 released: false,
289 };
290 terminals.set(terminalId, record);
291​
292 const pump = (stream: typeof child.stdout) =>
293 stream.pipe(
294 Stream.runForEach((chunk) =>
295 Effect.sync(() => {
296 appendOutput(record.buffer, chunk);
297 enforceTotalOutputLimit();
298 }),
299 ),
300 Effect.ignore,
301 );
302 const stdoutPump = yield* Effect.forkDetach(pump(child.stdout));
303 const stderrPump = yield* Effect.forkDetach(pump(child.stderr));
304 yield* Effect.forkDetach(
305 child.exitCode.pipe(
306 Effect.match({
307 onFailure: (error) => ({ exitCode: null, signal: terminalExitSignal(error) }),
308 onSuccess: (code) => ({ exitCode: Number(code), signal: null }),
309 }),
310 Effect.flatMap((status) =>
311 Effect.all([Fiber.join(stdoutPump), Fiber.join(stderrPump)], {
312 discard: true,
313 }).pipe(
314 Effect.andThen(
315 Effect.sync(() => {
316 record.exitStatus = status;
317 }),
318 ),
319 Effect.andThen(Deferred.succeed(record.exit, status)),
320 ),
321 ),
322 ),
323 );
324 return { terminalId };
325 }),
326 ),
327 );
328​
329 const output: AcpClientTerminals["output"] = (request) =>
330 requireTerminal(request.sessionId, request.terminalId, "terminal/output").pipe(
331 Effect.map((terminal) => ({
332 output: readOutput(terminal.buffer),
333 truncated: terminal.buffer.truncated,
334 ...(terminal.exitStatus === undefined ? {} : { exitStatus: terminal.exitStatus }),
335 })),
336 );
337​
338 const waitForExit: AcpClientTerminals["waitForExit"] = (request) =>
339 requireTerminal(request.sessionId, request.terminalId, "terminal/wait_for_exit").pipe(
340 Effect.flatMap((terminal) => Deferred.await(terminal.exit)),
341 );
342​
343 const kill: AcpClientTerminals["kill"] = (request) =>
344 requireTerminal(request.sessionId, request.terminalId, "terminal/kill").pipe(
345 Effect.flatMap((terminal) => terminal.kill),
346 Effect.as({}),
347 );
348​
349 const release: AcpClientTerminals["release"] = (request) =>
350 Effect.uninterruptible(
351 requireTerminal(request.sessionId, request.terminalId, "terminal/release").pipe(
352 Effect.flatMap((terminal) =>
353 Effect.sync(() => {
354 terminal.released = true;
355 }).pipe(
356 Effect.andThen(terminal.dispose),
357 Effect.andThen(Deferred.await(terminal.exit)),
358 Effect.andThen(Effect.sync(pruneReleasedSnapshots)),
359 ),
360 ),
361 Effect.as({}),
362 ),
363 );
364​
365 const readOutputSnapshot: AcpClientTerminals["readOutputSnapshot"] = (sessionId, terminalId) => {
366 const terminal = terminals.get(terminalId);
367 if (terminal === undefined || terminal.sessionId !== sessionId) return undefined;
368 return {
369 output: readOutput(terminal.buffer),
370 truncated: terminal.buffer.truncated,
371 exitStatus: terminal.exitStatus,
372 };
373 };
374​
375 const readCommandLine: AcpClientTerminals["readCommandLine"] = (terminalId) =>
376 terminals.get(terminalId)?.commandLine;
377​
378 const disposeAll: AcpClientTerminals["disposeAll"] = Effect.uninterruptible(
379 Effect.suspend(() =>
380 Effect.forEach(
381 Array.from(terminals.values()),
382 (terminal) =>
383 Effect.sync(() => {
384 terminal.released = true;
385 }).pipe(Effect.andThen(terminal.dispose), Effect.andThen(Deferred.await(terminal.exit))),
386 { concurrency: "unbounded", discard: true },
387 ).pipe(Effect.andThen(Effect.sync(pruneReleasedSnapshots))),
388 ),
389 );
390​
391 // Terminal failures surface to the agent as JSON-RPC errors and to the
392 // user only as a failed tool item, so log them for server-side diagnosis.
393 const logged =
394 <Request, Response>(
395 operation: string,
396 handler: (request: Request) => Effect.Effect<Response, EffectAcpErrors.AcpRequestError>,
397 ) =>
398 (request: Request) =>
399 handler(request).pipe(
400 Effect.tapError((error) =>
401 Effect.logWarning("ACP client terminal operation failed", {
402 operation,
403 detail: error.message,
404 }),
405 ),
406 );
407​
408 return {
409 create: logged("terminal/create", create),
410 output: logged("terminal/output", output),
411 waitForExit: logged("terminal/wait_for_exit", waitForExit),
412 kill: logged("terminal/kill", kill),
413 release: logged("terminal/release", release),
414 readOutputSnapshot,
415 readCommandLine,
416 disposeAll,
417 };
418});
419​
420/**
421 * Rewrites embedded `terminal` tool-call content into plain text content so
422 * the provider-neutral tool-call projection can display live command output.
423 */
424export function resolveEmbeddedTerminalContent(
425 notification: EffectAcpSchema.SessionNotification,
426 readOutputSnapshot: AcpClientTerminals["readOutputSnapshot"],
427): EffectAcpSchema.SessionNotification {
428 const update = notification.update;
429 if (update.sessionUpdate !== "tool_call" && update.sessionUpdate !== "tool_call_update") {
430 return notification;
431 }
432 const content = update.content;
433 if (!content || !content.some((entry) => entry.type === "terminal")) {
434 return notification;
435 }
436 const mapped = content.map((entry): EffectAcpSchema.ToolCallContent => {
437 if (entry.type !== "terminal") return entry;
438 const snapshot = readOutputSnapshot(notification.sessionId, entry.terminalId);
439 return {
440 type: "content",
441 content: {
442 type: "text",
443 text: snapshot === undefined ? `[terminal ${entry.terminalId}]` : snapshot.output,
444 },
445 };
446 });
447 return { ...notification, update: { ...update, content: mapped } };