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/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 /** Devin sends shell source in command, rather than an executable plus args. */
139 readonly shellCommands?: boolean | undefined;
140 readonly spawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
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;
147}
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 });
162}
163
164export const makeAcpClientTerminals = (
165 options: AcpClientTerminalsOptions,
166): Effect.Effect<AcpClientTerminals> =>
167 Effect.gen(function* () {
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(
175 (total, terminal) => total + terminal.buffer.bytes,
176 0,
177 ) - MAX_RETAINED_OUTPUT_BYTES;
178 if (excess <= 0) return;
179 for (const terminal of terminals.values()) {
180 const before = terminal.buffer.bytes;
181 trimOutputStart(terminal.buffer, excess);
182 excess -= before - terminal.buffer.bytes;
183 if (excess <= 0) return;
184 }
185 };
186
187 const pruneReleasedSnapshots = (): void => {
188 const released = Array.from(terminals.values()).filter((terminal) => terminal.released);
189 let retainedBytes = released.reduce((total, terminal) => total + terminal.buffer.bytes, 0);
190 while (
191 released.length > MAX_RETAINED_TERMINALS ||
192 retainedBytes > MAX_RETAINED_OUTPUT_BYTES
193 ) {
194 const terminal = released.shift();
195 if (terminal === undefined) break;
196 retainedBytes -= terminal.buffer.bytes;
197 terminals.delete(terminal.terminalId);
198 }
199 };
200
201 const requireTerminal = (
202 sessionId: string,
203 terminalId: string,
204 operation: string,
205 ): Effect.Effect<ManagedAcpTerminal, EffectAcpErrors.AcpRequestError> => {
206 const terminal = terminals.get(terminalId);
207 if (terminal === undefined || terminal.sessionId !== sessionId || terminal.released) {
208 return Effect.fail(
209 terminalRequestError(`ACP ${operation} received an unknown terminal ID '${terminalId}'.`),
210 );
211 }
212 return Effect.succeed(terminal);
213 };
214
215 const create: AcpClientTerminals["create"] = (request) =>
216 creationPermit.withPermit(
217 Effect.uninterruptibleMask((restore) =>
218 Effect.gen(function* () {
219 const liveCount = Array.from(terminals.values()).filter(
220 (terminal) => !terminal.released && terminal.exitStatus === undefined,
221 ).length;
222 const unreleasedCount = Array.from(terminals.values()).filter(
223 (terminal) => !terminal.released,
224 ).length;
225 if (unreleasedCount >= MAX_UNRELEASED_TERMINALS) {
226 return yield* terminalRequestError(
227 `ACP terminal/create exceeded the limit of ${MAX_UNRELEASED_TERMINALS} unreleased terminals.`,
228 );
229 }
230 if (liveCount >= MAX_LIVE_TERMINALS) {
231 return yield* terminalRequestError(
232 `ACP terminal/create exceeded the limit of ${MAX_LIVE_TERMINALS} concurrent terminals.`,
233 );
234 }
235 const requestEnvironment = Object.fromEntries(
236 (request.env ?? []).map((variable) => [variable.name, variable.value] as const),
237 );
238 const sessionEnvironment = options.environmentForSession?.(request.sessionId);
239 const environment =
240 options.environment === undefined &&
241 sessionEnvironment === undefined &&
242 (request.env?.length ?? 0) === 0
243 ? undefined
244 : { ...options.environment, ...sessionEnvironment, ...requestEnvironment };
245 // Each terminal owns a scope so the spawned process is reliably reaped:
246 // closing the scope kills a still-running command and frees the handle.
247 const terminalScope = yield* Scope.make();
248 const child = yield* restore(
249 options.spawner
250 .spawn(
251 acpTerminalCommand({
252 request,
253 shellCommands: options.shellCommands,
254 defaultCwd: options.defaultCwd,
255 environment,
256 forceKillAfter: options.forceKillAfter,
257 }),
258 )
259 .pipe(
260 Effect.provideService(Scope.Scope, terminalScope),
261 Effect.mapError((cause) =>
262 terminalRequestError(
263 `Could not start terminal command '${request.command}'.`,
264 cause,
265 ),
266 ),
267 ),
268 ).pipe(
269 Effect.onExit((exit) =>
270 Exit.isFailure(exit) ? Scope.close(terminalScope, Exit.void) : Effect.void,
271 ),
272 );
273
274 const terminalId = `t3-term-${nextTerminalNumber}`;
275 nextTerminalNumber += 1;
276 const record: ManagedAcpTerminal = {
277 terminalId,
278 sessionId: request.sessionId,
279 commandLine: [request.command, ...(request.args ?? [])].join(" "),
280 buffer: {
281 chunks: [],
282 bytes: 0,
283 truncated: false,
284 limit: Math.min(
285 request.outputByteLimit ?? DEFAULT_OUTPUT_BYTE_LIMIT,
286 MAX_OUTPUT_BYTE_LIMIT,
287 ),
288 },
289 exit: yield* Deferred.make<EffectAcpSchema.WaitForTerminalExitResponse>(),
290 kill: child.kill().pipe(Effect.ignore),
291 dispose: Scope.close(terminalScope, Exit.void).pipe(Effect.ignore),
292 exitStatus: undefined,
293 released: false,
294 };
295 terminals.set(terminalId, record);
296
297 const pump = (stream: typeof child.stdout) =>
298 stream.pipe(
299 Stream.runForEach((chunk) =>
300 Effect.sync(() => {
301 appendOutput(record.buffer, chunk);
302 enforceTotalOutputLimit();
303 }),
304 ),
305 Effect.ignore,
306 );
307 const stdoutPump = yield* Effect.forkDetach(pump(child.stdout));
308 const stderrPump = yield* Effect.forkDetach(pump(child.stderr));
309 yield* Effect.forkDetach(
310 child.exitCode.pipe(
311 Effect.match({
312 onFailure: (error) => ({ exitCode: null, signal: terminalExitSignal(error) }),
313 onSuccess: (code) => ({ exitCode: Number(code), signal: null }),
314 }),
315 Effect.flatMap((status) =>
316 Effect.all([Fiber.join(stdoutPump), Fiber.join(stderrPump)], {
317 discard: true,
318 }).pipe(
319 Effect.andThen(
320 Effect.sync(() => {
321 record.exitStatus = status;
322 }),
323 ),
324 Effect.andThen(Deferred.succeed(record.exit, status)),
325 ),
326 ),
327 ),
328 );
329 return { terminalId };
330 }),
331 ),
332 );
333
334 const output: AcpClientTerminals["output"] = (request) =>
335 requireTerminal(request.sessionId, request.terminalId, "terminal/output").pipe(
336 Effect.map((terminal) => ({
337 output: readOutput(terminal.buffer),
338 truncated: terminal.buffer.truncated,
339 ...(terminal.exitStatus === undefined ? {} : { exitStatus: terminal.exitStatus }),
340 })),
341 );
342
343 const waitForExit: AcpClientTerminals["waitForExit"] = (request) =>
344 requireTerminal(request.sessionId, request.terminalId, "terminal/wait_for_exit").pipe(
345 Effect.flatMap((terminal) => Deferred.await(terminal.exit)),
346 );
347
348 const kill: AcpClientTerminals["kill"] = (request) =>
349 requireTerminal(request.sessionId, request.terminalId, "terminal/kill").pipe(
350 Effect.flatMap((terminal) => terminal.kill),
351 Effect.as({}),
352 );
353
354 const release: AcpClientTerminals["release"] = (request) =>
355 Effect.uninterruptible(
356 requireTerminal(request.sessionId, request.terminalId, "terminal/release").pipe(
357 Effect.flatMap((terminal) =>
358 Effect.sync(() => {
359 terminal.released = true;
360 }).pipe(
361 Effect.andThen(terminal.dispose),
362 Effect.andThen(Deferred.await(terminal.exit)),
363 Effect.andThen(Effect.sync(pruneReleasedSnapshots)),
364 ),
365 ),
366 Effect.as({}),
367 ),
368 );
369
370 const readOutputSnapshot: AcpClientTerminals["readOutputSnapshot"] = (
371 sessionId,
372 terminalId,
373 ) => {
374 const terminal = terminals.get(terminalId);
375 if (terminal === undefined || terminal.sessionId !== sessionId) return undefined;
376 return {
377 output: readOutput(terminal.buffer),
378 truncated: terminal.buffer.truncated,
379 exitStatus: terminal.exitStatus,
380 };
381 };
382
383 const readCommandLine: AcpClientTerminals["readCommandLine"] = (terminalId) =>
384 terminals.get(terminalId)?.commandLine;
385
386 const disposeAll: AcpClientTerminals["disposeAll"] = Effect.uninterruptible(
387 Effect.suspend(() =>
388 Effect.forEach(
389 Array.from(terminals.values()),
390 (terminal) =>
391 Effect.sync(() => {
392 terminal.released = true;
393 }).pipe(
394 Effect.andThen(terminal.dispose),
395 Effect.andThen(Deferred.await(terminal.exit)),
396 ),
397 { concurrency: "unbounded", discard: true },
398 ).pipe(Effect.andThen(Effect.sync(pruneReleasedSnapshots))),
399 ),
400 );
401
402 // Terminal failures surface to the agent as JSON-RPC errors and to the
403 // user only as a failed tool item, so log them for server-side diagnosis.
404 const logged =
405 <Request, Response>(
406 operation: string,
407 handler: (request: Request) => Effect.Effect<Response, EffectAcpErrors.AcpRequestError>,
408 ) =>
409 (request: Request) =>
410 handler(request).pipe(
411 Effect.tapError((error) =>
412 Effect.logWarning("ACP client terminal operation failed", {
413 operation,
414 detail: error.message,
415 }),
416 ),
417 );
418
419 return {
420 create: logged("terminal/create", create),
421 output: logged("terminal/output", output),
422 waitForExit: logged("terminal/wait_for_exit", waitForExit),
423 kill: logged("terminal/kill", kill),
424 release: logged("terminal/release", release),
425 readOutputSnapshot,
426 readCommandLine,
427 disposeAll,
428 };
429 });
430
431/**
432 * Rewrites embedded `terminal` tool-call content into plain text content so
433 * the provider-neutral tool-call projection can display live command output.
434 */
435export function resolveEmbeddedTerminalContent(
436 notification: EffectAcpSchema.SessionNotification,
437 readOutputSnapshot: AcpClientTerminals["readOutputSnapshot"],
438): EffectAcpSchema.SessionNotification {
439 const update = notification.update;
440 if (update.sessionUpdate !== "tool_call" && update.sessionUpdate !== "tool_call_update") {
441 return notification;
442 }
443 const content = update.content;
444 if (!content || !content.some((entry) => entry.type === "terminal")) {
445 return notification;
446 }
447 const mapped = content.map((entry): EffectAcpSchema.ToolCallContent => {
448 if (entry.type !== "terminal") return entry;
449 const snapshot = readOutputSnapshot(notification.sessionId, entry.terminalId);
450 return {
451 type: "content",
452 content: {
453 type: "text",
454 text: snapshot === undefined ? `[terminal ${entry.terminalId}]` : snapshot.output,
455 },
456 };
457 });
458 return { ...notification, update: { ...update, content: mapped } };
459}