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