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