Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

clientTerminals.ts

428 lines16.1 KB

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;
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 }
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);
59​
60function readOutput(state: OutputBufferState): string {
61 let combined: Uint8Array = NodeBuffer.Buffer.concat(state.chunks, state.bytes);
62 if (state.truncated) {
63 // The spec requires truncation at a UTF-8 character boundary.
64 let start = 0;
65 while (start < combined.byteLength && (combined[start]! & 0b1100_0000) === 0b1000_0000) {
66 start += 1;
67 }
68 combined = combined.subarray(start);
69 }
70 return NodeBuffer.Buffer.from(combined).toString("utf8");
72​
73function terminalExitSignal(error: unknown): string | null {
74 const cause = error instanceof Error ? error.cause : undefined;
75 const message =
76 cause instanceof Error ? cause.message : error instanceof Error ? error.message : "";
77 return message.match(/signal: '([^']+)'/u)?.[1] ?? null;
79​
80export interface AcpTerminalOutputSnapshot {
81 readonly output: string;
82 readonly truncated: boolean;
83 readonly exitStatus: EffectAcpSchema.TerminalExitStatus | undefined;
85​
86interface ManagedAcpTerminal {
87 readonly terminalId: string;
88 readonly sessionId: string;
89 readonly commandLine: string;
90 readonly buffer: OutputBufferState;
91 readonly exit: Deferred.Deferred<EffectAcpSchema.WaitForTerminalExitResponse>;
92 readonly kill: Effect.Effect<void>;
93 readonly dispose: Effect.Effect<void>;
94 exitStatus: EffectAcpSchema.TerminalExitStatus | undefined;
95 released: boolean;
97​
98export interface AcpClientTerminals {
99 readonly create: (
100 request: EffectAcpSchema.CreateTerminalRequest,
101 ) => Effect.Effect<EffectAcpSchema.CreateTerminalResponse, EffectAcpErrors.AcpRequestError>;
102 readonly output: (
103 request: EffectAcpSchema.TerminalOutputRequest,
104 ) => Effect.Effect<EffectAcpSchema.TerminalOutputResponse, EffectAcpErrors.AcpRequestError>;
105 readonly waitForExit: (
106 request: EffectAcpSchema.WaitForTerminalExitRequest,
107 ) => Effect.Effect<EffectAcpSchema.WaitForTerminalExitResponse, EffectAcpErrors.AcpRequestError>;
108 readonly kill: (
109 request: EffectAcpSchema.KillTerminalRequest,
110 ) => Effect.Effect<EffectAcpSchema.KillTerminalResponse, EffectAcpErrors.AcpRequestError>;
111 readonly release: (
112 request: EffectAcpSchema.ReleaseTerminalRequest,
113 ) => Effect.Effect<EffectAcpSchema.ReleaseTerminalResponse, EffectAcpErrors.AcpRequestError>;
114 /** Buffered output for embedded tool-call content; survives release. */
115 readonly readOutputSnapshot: (
116 sessionId: string,
117 terminalId: string,
118 ) => AcpTerminalOutputSnapshot | undefined;
119 readonly readCommandLine: (terminalId: string) => string | undefined;
120 readonly disposeAll: Effect.Effect<void>;
122​
123export interface AcpClientTerminalsOptions {
124 /** Devin sends shell source in command, rather than an executable plus args. */
125 readonly shellCommands?: boolean | undefined;
126 readonly defaultCwd: string;
127 readonly environment?: NodeJS.ProcessEnv | undefined;
128 readonly environmentForSession?:
129 | ((sessionId: string) => NodeJS.ProcessEnv | undefined)
130 | undefined;
131 readonly forceKillAfter?: Duration.Input | undefined;
133​
134function acpTerminalCommand(input: {
135 readonly request: EffectAcpSchema.CreateTerminalRequest;
136 readonly shellCommands?: boolean | undefined;
137 readonly defaultCwd: string;
138 readonly environment?: NodeJS.ProcessEnv | undefined;
139 readonly forceKillAfter: Duration.Input;
140}) {
141 return ChildProcess.make(input.request.command, input.request.args ?? [], {
142 cwd: input.request.cwd ?? input.defaultCwd,
143 ...(input.environment === undefined ? {} : { env: input.environment }),
144 shell: input.shellCommands === true && (input.request.args?.length ?? 0) === 0,
145 forceKillAfter: input.forceKillAfter,
146 });
148​
149export const makeAcpClientTerminals = Effect.fn("makeAcpClientTerminals")(function* (
150 options: AcpClientTerminalsOptions,
151): Effect.fn.Return<AcpClientTerminals, never, ChildProcessSpawner.ChildProcessSpawner> {
152 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
153 const forceKillAfter = options.forceKillAfter ?? "5 seconds";
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,
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 // The spawner only applies the command's forceKillAfter on scope close;
270 // an explicit kill must pass it or a SIGTERM-ignoring command never exits.
271 kill: child.kill({ forceKillAfter }).pipe(Effect.ignore),
272 dispose: Scope.close(terminalScope, Exit.void).pipe(Effect.ignore),
273 exitStatus: undefined,
274 released: false,
275 };
276 terminals.set(terminalId, record);
277​
278 const pump = (stream: typeof child.stdout) =>
279 stream.pipe(
280 Stream.runForEach((chunk) =>
281 Effect.sync(() => {
282 appendOutput(record.buffer, chunk);
283 enforceTotalOutputLimit();
284 }),
285 ),
286 Effect.ignore,
287 );
288 const stdoutPump = yield* Effect.forkDetach(pump(child.stdout));
289 const stderrPump = yield* Effect.forkDetach(pump(child.stderr));
290 yield* Effect.forkDetach(
291 child.exitCode.pipe(
292 Effect.match({
293 onFailure: (error) => ({ exitCode: null, signal: terminalExitSignal(error) }),
294 onSuccess: (code) => ({ exitCode: Number(code), signal: null }),
295 }),
296 Effect.flatMap((status) =>
297 Effect.all([Fiber.join(stdoutPump), Fiber.join(stderrPump)], {
298 discard: true,
299 }).pipe(
300 Effect.andThen(
301 Effect.sync(() => {
302 record.exitStatus = status;
303 }),
304 ),
305 Effect.andThen(Deferred.succeed(record.exit, status)),
306 ),
307 ),
308 ),
309 );
310 return { terminalId };
311 }),
312 ),
313 );
314​
315 const output: AcpClientTerminals["output"] = (request) =>
316 requireTerminal(request.sessionId, request.terminalId, "terminal/output").pipe(
317 Effect.map((terminal) => ({
318 output: readOutput(terminal.buffer),
319 truncated: terminal.buffer.truncated,
320 ...(terminal.exitStatus === undefined ? {} : { exitStatus: terminal.exitStatus }),
321 })),
322 );
323​
324 const waitForExit: AcpClientTerminals["waitForExit"] = (request) =>
325 requireTerminal(request.sessionId, request.terminalId, "terminal/wait_for_exit").pipe(
326 Effect.flatMap((terminal) => Deferred.await(terminal.exit)),
327 );
328​
329 const kill: AcpClientTerminals["kill"] = (request) =>
330 requireTerminal(request.sessionId, request.terminalId, "terminal/kill").pipe(
331 Effect.flatMap((terminal) => terminal.kill),
332 Effect.as({}),
333 );
334​
335 const release: AcpClientTerminals["release"] = (request) =>
336 Effect.uninterruptible(
337 requireTerminal(request.sessionId, request.terminalId, "terminal/release").pipe(
338 Effect.flatMap((terminal) =>
339 Effect.sync(() => {
340 terminal.released = true;
341 }).pipe(
342 Effect.andThen(terminal.dispose),
343 Effect.andThen(Deferred.await(terminal.exit)),
344 Effect.andThen(Effect.sync(pruneReleasedSnapshots)),
345 ),
346 ),
347 Effect.as({}),
348 ),
349 );
350​
351 const readOutputSnapshot: AcpClientTerminals["readOutputSnapshot"] = (sessionId, terminalId) => {
352 const terminal = terminals.get(terminalId);
353 if (terminal === undefined || terminal.sessionId !== sessionId) return undefined;
354 return {
355 output: readOutput(terminal.buffer),
356 truncated: terminal.buffer.truncated,
357 exitStatus: terminal.exitStatus,
358 };
359 };
360​
361 const readCommandLine: AcpClientTerminals["readCommandLine"] = (terminalId) =>
362 terminals.get(terminalId)?.commandLine;
363​
364 const disposeAll: AcpClientTerminals["disposeAll"] = Effect.uninterruptible(
365 Effect.suspend(() =>
366 Effect.forEach(
367 Array.from(terminals.values()),
368 (terminal) =>
369 Effect.sync(() => {
370 terminal.released = true;
371 }).pipe(Effect.andThen(terminal.dispose), Effect.andThen(Deferred.await(terminal.exit))),
372 { concurrency: "unbounded", discard: true },
373 ).pipe(Effect.andThen(Effect.sync(pruneReleasedSnapshots))),
374 ),
375 );
376​
377 const logged =
378 <Request, Response>(
379 operation: string,
380 handler: (request: Request) => Effect.Effect<Response, EffectAcpErrors.AcpRequestError>,
381 ) =>
382 (request: Request) =>
383 handler(request).pipe(
384 Effect.tapError((error) =>
385 Effect.logWarning("ACP client terminal operation failed", {
386 operation,
387 detail: error.message,
388 }),
389 ),
390 );
391​
392 return {
393 create: logged("terminal/create", create),
394 output: logged("terminal/output", output),
395 waitForExit: logged("terminal/wait_for_exit", waitForExit),
396 kill: logged("terminal/kill", kill),
397 release: logged("terminal/release", release),
398 readOutputSnapshot,
399 readCommandLine,
400 disposeAll,
401 };
402});
403​
404export function resolveEmbeddedTerminalContent(
405 notification: EffectAcpSchema.SessionNotification,
406 readOutputSnapshot: AcpClientTerminals["readOutputSnapshot"],
407): EffectAcpSchema.SessionNotification {
408 const update = notification.update;
409 if (update.sessionUpdate !== "tool_call" && update.sessionUpdate !== "tool_call_update") {
410 return notification;
411 }
412 const content = update.content;
413 if (!content || !content.some((entry) => entry.type === "terminal")) {
414 return notification;
415 }
416 const mapped = content.map((entry): EffectAcpSchema.ToolCallContent => {
417 if (entry.type !== "terminal") return entry;
418 const snapshot = readOutputSnapshot(notification.sessionId, entry.terminalId);
419 return {
420 type: "content",
421 content: {
422 type: "text",
423 text: snapshot === undefined ? `[terminal ${entry.terminalId}]` : snapshot.output,
424 },
425 };
426 });
427 return { ...notification, update: { ...update, content: mapped } };