Open History to see the last commit
1import * as Channel from "effect/Channel";
2import * as Deferred from "effect/Deferred";
3import * as Duration from "effect/Duration";
4import * as Effect from "effect/Effect";
5import * as Exit from "effect/Exit";
6import * as Fiber from "effect/Fiber";
7import * as Scope from "effect/Scope";
8import * as Semaphore from "effect/Semaphore";
9import * as Stream from "effect/Stream";
10import * as ChildProcess from "effect/process/ChildProcess";
11import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
12import * as EffectAcpErrors from "effect-acp/errors";
13import type * as EffectAcpSchema from "effect-acp/compat";
14import * as NodeBuffer from "node:buffer";
15
16const MAX_LIVE_TERMINALS = 16;
17const MAX_UNRELEASED_TERMINALS = 64;
18const MAX_RETAINED_TERMINALS = 32;
19const MAX_RETAINED_OUTPUT_BYTES = 16 * 1024 * 1024;
20const DEFAULT_OUTPUT_BYTE_LIMIT = 4 * 1024 * 1024;
21const MAX_OUTPUT_BYTE_LIMIT = 8 * 1024 * 1024;
22
23const terminalRequestError = (message: string, cause?: unknown) =>
24 EffectAcpErrors.AcpRequestError.internalError(
25 message,
26 undefined,
27 cause === undefined ? {} : { cause },
28 );
29
30interface OutputBufferState {
31 chunks: Array<Uint8Array>;
32 bytes: number;
33 truncated: boolean;
34 readonly limit: number;
35}
36
37function trimOutputStart(state: OutputBufferState, bytes: number): void {
38 let remaining = Math.min(bytes, state.bytes);
39 while (remaining > 0) {
40 const head = state.chunks[0]!;
41 if (head.byteLength <= remaining) {
42 state.chunks.shift();
43 state.bytes -= head.byteLength;
44 remaining -= head.byteLength;
45 } else {
46 state.chunks[0] = head.subarray(remaining);
47 state.bytes -= remaining;
48 remaining = 0;
49 }
50 state.truncated = true;
51 }
52}
53
54function appendOutput(state: OutputBufferState, chunk: Uint8Array): void {
55 state.chunks.push(chunk);
56 state.bytes += chunk.byteLength;
57 // The spec requires truncation from the beginning of the output.
58 if (state.bytes > state.limit) trimOutputStart(state, state.bytes - state.limit);
59}
60
61function readOutput(state: OutputBufferState): string {
62 let combined: Uint8Array = NodeBuffer.Buffer.concat(state.chunks, state.bytes);
63 if (state.truncated) {
64 // The spec requires truncation at a UTF-8 character boundary.
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;
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,
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 forceKillAfter = options.forceKillAfter ?? "5 seconds";
155 const creationPermit = yield* Semaphore.make(1);
156 const terminals = new Map<string, ManagedAcpTerminal>();
157 let nextTerminalNumber = 1;
158
159 const enforceTotalOutputLimit = (): void => {
160 let excess =
161 Array.from(terminals.values()).reduce((total, terminal) => total + terminal.buffer.bytes, 0) -
162 MAX_RETAINED_OUTPUT_BYTES;
163 if (excess <= 0) return;
164 for (const terminal of terminals.values()) {
165 const before = terminal.buffer.bytes;
166 trimOutputStart(terminal.buffer, excess);
167 excess -= before - terminal.buffer.bytes;
168 if (excess <= 0) return;
169 }
170 };
171
172 const pruneReleasedSnapshots = (): void => {
173 const released = Array.from(terminals.values()).filter((terminal) => terminal.released);
174 let retainedBytes = released.reduce((total, terminal) => total + terminal.buffer.bytes, 0);
175 while (released.length > MAX_RETAINED_TERMINALS || retainedBytes > MAX_RETAINED_OUTPUT_BYTES) {
176 const terminal = released.shift();
177 if (terminal === undefined) break;
178 retainedBytes -= terminal.buffer.bytes;
179 terminals.delete(terminal.terminalId);
180 }
181 };
182
183 const requireTerminal = (
184 sessionId: string,
185 terminalId: string,
186 operation: string,
187 ): Effect.Effect<ManagedAcpTerminal, EffectAcpErrors.AcpRequestError> => {
188 const terminal = terminals.get(terminalId);
189 if (terminal === undefined || terminal.sessionId !== sessionId || terminal.released) {
190 return Effect.fail(
191 terminalRequestError(`ACP ${operation} received an unknown terminal ID '${terminalId}'.`),
192 );
193 }
194 return Effect.succeed(terminal);
195 };
196
197 const create: AcpClientTerminals["create"] = (request) =>
198 creationPermit.withPermit(
199 Effect.uninterruptibleMask((restore) =>
200 Effect.gen(function* () {
201 const liveCount = Array.from(terminals.values()).filter(
202 (terminal) => !terminal.released && terminal.exitStatus === undefined,
203 ).length;
204 const unreleasedCount = Array.from(terminals.values()).filter(
205 (terminal) => !terminal.released,
206 ).length;
207 if (unreleasedCount >= MAX_UNRELEASED_TERMINALS) {
208 return yield* terminalRequestError(
209 `ACP terminal/create exceeded the limit of ${MAX_UNRELEASED_TERMINALS} unreleased terminals.`,
210 );
211 }
212 if (liveCount >= MAX_LIVE_TERMINALS) {
213 return yield* terminalRequestError(
214 `ACP terminal/create exceeded the limit of ${MAX_LIVE_TERMINALS} concurrent terminals.`,
215 );
216 }
217 const requestEnvironment = Object.fromEntries(
218 (request.env ?? []).map((variable) => [variable.name, variable.value] as const),
219 );
220 const sessionEnvironment = options.environmentForSession?.(request.sessionId);
221 const environment =
222 options.environment === undefined &&
223 sessionEnvironment === undefined &&
224 (request.env?.length ?? 0) === 0
225 ? undefined
226 : { ...options.environment, ...sessionEnvironment, ...requestEnvironment };
227 const terminalScope = yield* Scope.make();
228 const child = yield* restore(
229 spawner
230 .spawn(
231 acpTerminalCommand({
232 request,
233 shellCommands: options.shellCommands,
234 defaultCwd: options.defaultCwd,
235 environment,
236 forceKillAfter,
237 }),
238 )
239 .pipe(
240 Effect.provideService(Scope.Scope, terminalScope),
241 Effect.mapError((cause) =>
242 terminalRequestError(
243 `Could not start terminal command '${request.command}'.`,
244 cause,
245 ),
246 ),
247 ),
248 ).pipe(
249 Effect.onExit((exit) =>
250 Exit.isFailure(exit) ? Scope.close(terminalScope, Exit.void) : Effect.void,
251 ),
252 );
253
254 const terminalId = `t3-term-${nextTerminalNumber}`;
255 nextTerminalNumber += 1;
256 const record: ManagedAcpTerminal = {
257 terminalId,
258 sessionId: request.sessionId,
259 commandLine: [request.command, ...(request.args ?? [])].join(" "),
260 buffer: {
261 chunks: [],
262 bytes: 0,
263 truncated: false,
264 limit: Math.min(
265 request.outputByteLimit ?? DEFAULT_OUTPUT_BYTE_LIMIT,
266 MAX_OUTPUT_BYTE_LIMIT,
267 ),
268 },
269 exit: yield* Deferred.make<EffectAcpSchema.WaitForTerminalExitResponse>(),
270 // The spawner only applies the command's forceKillAfter on scope close;
271 // an explicit kill must pass it or a SIGTERM-ignoring command never exits.
272 kill: child.kill({ forceKillAfter }).pipe(Effect.ignore),
273 dispose: Scope.close(terminalScope, Exit.void).pipe(Effect.ignore),
274 exitStatus: undefined,
275 released: false,
276 };
277 terminals.set(terminalId, record);
278
279 const pump = (stream: typeof child.stdout) =>
280 stream.pipe(
281 // Keep each pipe's UTF-8 decoder independent and preserve literal BOMs.
282 Stream.pipeThroughChannel(Channel.decodeText("utf-8", { ignoreBOM: true })),
283 Stream.encodeText,
284 Stream.runForEach((chunk) =>
285 Effect.sync(() => {
286 appendOutput(record.buffer, chunk);
287 enforceTotalOutputLimit();
288 }),
289 ),
290 Effect.ignore,
291 );
292 const stdoutPump = yield* Effect.forkDetach(pump(child.stdout));
293 const stderrPump = yield* Effect.forkDetach(pump(child.stderr));
294 yield* Effect.forkDetach(
295 child.exitCode.pipe(
296 Effect.match({
297 onFailure: (error) => ({ exitCode: null, signal: terminalExitSignal(error) }),
298 onSuccess: (code) => ({ exitCode: Number(code), signal: null }),
299 }),
300 Effect.flatMap((status) =>
301 Effect.all([Fiber.join(stdoutPump), Fiber.join(stderrPump)], {
302 discard: true,
303 }).pipe(
304 Effect.andThen(
305 Effect.sync(() => {
306 record.exitStatus = status;
307 }),
308 ),
309 Effect.andThen(Deferred.succeed(record.exit, status)),
310 ),
311 ),
312 ),
313 );
314 return { terminalId };
315 }),
316 ),
317 );
318
319 const output: AcpClientTerminals["output"] = (request) =>
320 requireTerminal(request.sessionId, request.terminalId, "terminal/output").pipe(
321 Effect.map((terminal) => ({
322 output: readOutput(terminal.buffer),
323 truncated: terminal.buffer.truncated,
324 ...(terminal.exitStatus === undefined ? {} : { exitStatus: terminal.exitStatus }),
325 })),
326 );
327
328 const waitForExit: AcpClientTerminals["waitForExit"] = (request) =>
329 requireTerminal(request.sessionId, request.terminalId, "terminal/wait_for_exit").pipe(
330 Effect.flatMap((terminal) => Deferred.await(terminal.exit)),
331 );
332
333 const kill: AcpClientTerminals["kill"] = (request) =>
334 requireTerminal(request.sessionId, request.terminalId, "terminal/kill").pipe(
335 Effect.flatMap((terminal) => terminal.kill),
336 Effect.as({}),
337 );
338
339 const release: AcpClientTerminals["release"] = (request) =>
340 Effect.uninterruptible(
341 requireTerminal(request.sessionId, request.terminalId, "terminal/release").pipe(
342 Effect.flatMap((terminal) =>
343 Effect.sync(() => {
344 terminal.released = true;
345 }).pipe(
346 Effect.andThen(terminal.dispose),
347 Effect.andThen(Deferred.await(terminal.exit)),
348 Effect.andThen(Effect.sync(pruneReleasedSnapshots)),
349 ),
350 ),
351 Effect.as({}),
352 ),
353 );
354
355 const readOutputSnapshot: AcpClientTerminals["readOutputSnapshot"] = (sessionId, terminalId) => {
356 const terminal = terminals.get(terminalId);
357 if (terminal === undefined || terminal.sessionId !== sessionId) return undefined;
358 return {
359 output: readOutput(terminal.buffer),
360 truncated: terminal.buffer.truncated,
361 exitStatus: terminal.exitStatus,
362 };
363 };
364
365 const readCommandLine: AcpClientTerminals["readCommandLine"] = (terminalId) =>
366 terminals.get(terminalId)?.commandLine;
367
368 const disposeAll: AcpClientTerminals["disposeAll"] = Effect.uninterruptible(
369 Effect.suspend(() =>
370 Effect.forEach(
371 Array.from(terminals.values()),
372 (terminal) =>
373 Effect.sync(() => {
374 terminal.released = true;
375 }).pipe(Effect.andThen(terminal.dispose), Effect.andThen(Deferred.await(terminal.exit))),
376 { concurrency: "unbounded", discard: true },
377 ).pipe(Effect.andThen(Effect.sync(pruneReleasedSnapshots))),
378 ),
379 );
380
381 const logged =
382 <Request, Response>(
383 operation: string,
384 handler: (request: Request) => Effect.Effect<Response, EffectAcpErrors.AcpRequestError>,
385 ) =>
386 (request: Request) =>
387 handler(request).pipe(
388 Effect.tapError((error) =>
389 Effect.logWarning("ACP client terminal operation failed", {
390 operation,
391 detail: error.message,
392 }),
393 ),
394 );
395
396 return {
397 create: logged("terminal/create", create),
398 output: logged("terminal/output", output),
399 waitForExit: logged("terminal/wait_for_exit", waitForExit),
400 kill: logged("terminal/kill", kill),
401 release: logged("terminal/release", release),
402 readOutputSnapshot,
403 readCommandLine,
404 disposeAll,
405 };
406});
407
408export function resolveEmbeddedTerminalContent(
409 notification: EffectAcpSchema.SessionNotification,
410 readOutputSnapshot: AcpClientTerminals["readOutputSnapshot"],
411): EffectAcpSchema.SessionNotification {
412 const update = notification.update;
413 if (update.sessionUpdate !== "tool_call" && update.sessionUpdate !== "tool_call_update") {
414 return notification;
415 }
416 const content = update.content;
417 if (!content || !content.some((entry) => entry.type === "terminal")) {
418 return notification;
419 }
420 const mapped = content.map((entry): EffectAcpSchema.ToolCallContent => {
421 if (entry.type !== "terminal") return entry;
422 const snapshot = readOutputSnapshot(notification.sessionId, entry.terminalId);
423 return {
424 type: "content",
425 content: {
426 type: "text",
427 text: snapshot === undefined ? `[terminal ${entry.terminalId}]` : snapshot.output,
428 },
429 };
430 });
431 return { ...notification, update: { ...update, content: mapped } };
432}