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