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

AcpSessionRuntime.ts

1,354 lines52.3 KB

1import * as Cause from "effect/Cause";
2import * as Clock from "effect/Clock";
3import * as Context from "effect/Context";
4import * as Crypto from "effect/Crypto";
5import * as Deferred from "effect/Deferred";
6import * as Duration from "effect/Duration";
7import * as Effect from "effect/Effect";
8import * as Exit from "effect/Exit";
9import * as Fiber from "effect/Fiber";
10import * as Layer from "effect/Layer";
11import * as Option from "effect/Option";
12import * as Queue from "effect/Queue";
13import * as Ref from "effect/Ref";
14import * as Scope from "effect/Scope";
15import * as Semaphore from "effect/Semaphore";
16import * as Stream from "effect/Stream";
17import * as ChildProcess from "effect/unstable/process/ChildProcess";
18import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
19import * as EffectAcpClient from "effect-acp/client";
20import * as EffectAcpErrors from "effect-acp/errors";
21import type * as EffectAcpSchema from "effect-acp/schema";
22import type * as EffectAcpProtocol from "effect-acp/protocol";
23import { resolveSpawnCommand } from "@t3tools/shared/shell";
24​
25import { appendAcpStderrTail, sanitizeAcpStderrExcerpt } from "./AcpStderr.ts";
26import {
27 collectSessionConfigOptionValues,
28 decideToolCallUpdateEmission,
29 extractModelConfigId,
30 findSessionConfigOption,
31 mergeToolCallState,
32 toolCallProgressLength,
33 parseSessionModeState,
34 parseSessionUpdateEvent,
35 sessionUpdateIsReplay,
36 waitForSessionLoadReplayIdle,
37 type SessionLoadGate,
38 type AcpParsedSessionEvent,
39 type AcpSessionModeState,
40 type AcpToolCallState,
41} from "./AcpRuntimeModel.ts";
42​
43const MAX_SHOWN_TOOL_CALL_IDS = 256;
44​
45interface AcpToolCallTrackedState {
46 readonly state: AcpToolCallState;
47 readonly lastEmittedDetailLength: number | undefined;
48 readonly skippedSinceEmit: number;
50​
51function formatConfigOptionValue(value: string | boolean): string {
52 return JSON.stringify(value);
54​
55export interface AcpSessionEventStreamBarrier {
56 readonly _tag: "EventStreamBarrier";
57 readonly acknowledge: Deferred.Deferred<void>;
59​
60export type AcpSessionRuntimeEvent =
61 | AcpParsedSessionEvent
62 | AcpSessionEventStreamBarrier
63 | {
64 readonly _tag: "ConnectionTerminated";
65 readonly error: EffectAcpErrors.AcpError;
66 };
67​
68const defaultSessionLoadTimeout = Duration.seconds(90);
69const defaultSessionLoadReplayIdleGap = Duration.seconds(2);
70const defaultCancelTimeout = Duration.seconds(15);
71const maxStartupMetadataUpdates = 32;
72// Antigravity can emit an accepted 16 KiB Google authorization URL on stderr.
73const maxStderrChunkLength = 32_768;
74​
75export interface AcpSpawnInput {
76 readonly command: string;
77 readonly args: ReadonlyArray<string>;
78 readonly cwd?: string;
79 readonly env?: NodeJS.ProcessEnv;
80 readonly extendEnv?: boolean;
82​
83export interface AcpSessionRuntimeOptions {
84 readonly spawn: AcpSpawnInput;
85 readonly cwd: string;
86 readonly resumeSessionId?: string;
87 readonly resumeMethod?: "load" | "resume";
88 readonly sessionLoadTimeout?: Duration.Input;
89 readonly sessionLoadReplayIdleGap?: Duration.Input;
90 /** Native cancellation waits for the prompt response and the getEvents consumer to drain. */
91 readonly cancelBehavior?: "interrupt" | "wait-for-prompt";
92 readonly cancelTimeout?: Duration.Input;
93 readonly clientCapabilities?: EffectAcpSchema.InitializeRequest["clientCapabilities"];
94 readonly clientInfo: {
95 readonly name: string;
96 readonly version: string;
97 };
98 readonly authMethodId: string;
99 readonly mcpServers?: ReadonlyArray<EffectAcpSchema.McpServer>;
100 /** Extra workspace roots the agent may read and write besides `cwd`. */
101 readonly additionalDirectories?: ReadonlyArray<string>;
102 /** Transforms provider stdout before protocol parsing and protocol logging. */
103 readonly transformStdout?: EffectAcpClient.AcpClientOptions["transformStdout"];
104 /** Normalizes provider-specific fields before notification queues or runtime state retain them. */
105 readonly transformSessionUpdate?: (
106 notification: EffectAcpSchema.SessionNotification,
107 ) => EffectAcpSchema.SessionNotification;
108 /** Receives bounded stderr chunks. Redact secrets before logging. A failure closes the runtime. */
109 readonly onStderr?: (text: string) => Effect.Effect<void, EffectAcpErrors.AcpError>;
110 readonly requestLogger?: (event: AcpSessionRequestLogEvent) => Effect.Effect<void, never>;
111 readonly protocolLogging?: {
112 readonly logIncoming?: boolean;
113 readonly logOutgoing?: boolean;
114 readonly logger?: (event: EffectAcpProtocol.AcpProtocolLogEvent) => Effect.Effect<void, never>;
115 };
117​
118export interface AcpSessionRequestLogEvent {
119 readonly method: string;
120 readonly payload: unknown;
121 readonly status: "started" | "succeeded" | "failed";
122 readonly result?: unknown;
123 readonly cause?: Cause.Cause<EffectAcpErrors.AcpError>;
125​
126export interface AcpSessionRuntimeStartResult {
127 readonly sessionId: string;
128 readonly initializeResult: EffectAcpSchema.InitializeResponse;
129 readonly sessionSetupResult:
130 | EffectAcpSchema.LoadSessionResponse
131 | EffectAcpSchema.NewSessionResponse
132 | EffectAcpSchema.ResumeSessionResponse;
133 readonly modelConfigId: string | undefined;
135​
136export class AcpSessionRuntime extends Context.Service<
137 AcpSessionRuntime,
138 {
139 /**
140 * Registers a handler for `session/request_permission`.
141 * @see https://agentclientprotocol.com/protocol/schema#session/request_permission
142 */
143 readonly handleRequestPermission: EffectAcpClient.AcpClient["Service"]["handleRequestPermission"];
144 /**
145 * Registers a handler for `session/elicitation`.
146 * @see https://agentclientprotocol.com/protocol/schema#session/elicitation
147 */
148 readonly handleElicitation: EffectAcpClient.AcpClient["Service"]["handleElicitation"];
149 /**
150 * Registers a handler for `fs/read_text_file`.
151 * @see https://agentclientprotocol.com/protocol/schema#fs/read_text_file
152 */
153 readonly handleReadTextFile: EffectAcpClient.AcpClient["Service"]["handleReadTextFile"];
154 /**
155 * Registers a handler for `fs/write_text_file`.
156 * @see https://agentclientprotocol.com/protocol/schema#fs/write_text_file
157 */
158 readonly handleWriteTextFile: EffectAcpClient.AcpClient["Service"]["handleWriteTextFile"];
159 /**
160 * Registers a handler for `terminal/create`.
161 * @see https://agentclientprotocol.com/protocol/schema#terminal/create
162 */
163 readonly handleCreateTerminal: EffectAcpClient.AcpClient["Service"]["handleCreateTerminal"];
164 /**
165 * Registers a handler for `terminal/output`.
166 * @see https://agentclientprotocol.com/protocol/schema#terminal/output
167 */
168 readonly handleTerminalOutput: EffectAcpClient.AcpClient["Service"]["handleTerminalOutput"];
169 /**
170 * Registers a handler for `terminal/wait_for_exit`.
171 * @see https://agentclientprotocol.com/protocol/schema#terminal/wait_for_exit
172 */
173 readonly handleTerminalWaitForExit: EffectAcpClient.AcpClient["Service"]["handleTerminalWaitForExit"];
174 /**
175 * Registers a handler for `terminal/kill`.
176 * @see https://agentclientprotocol.com/protocol/schema#terminal/kill
177 */
178 readonly handleTerminalKill: EffectAcpClient.AcpClient["Service"]["handleTerminalKill"];
179 /**
180 * Registers a handler for `terminal/release`.
181 * @see https://agentclientprotocol.com/protocol/schema#terminal/release
182 */
183 readonly handleTerminalRelease: EffectAcpClient.AcpClient["Service"]["handleTerminalRelease"];
184 /**
185 * Registers a handler for `session/update`.
186 * @see https://agentclientprotocol.com/protocol/schema#session/update
187 */
188 readonly handleSessionUpdate: EffectAcpClient.AcpClient["Service"]["handleSessionUpdate"];
189 /**
190 * Registers a handler for `session/elicitation/complete`.
191 * @see https://agentclientprotocol.com/protocol/schema#session/elicitation/complete
192 */
193 readonly handleElicitationComplete: EffectAcpClient.AcpClient["Service"]["handleElicitationComplete"];
194 /**
195 * Registers a fallback extension request handler.
196 * @see https://agentclientprotocol.com/protocol/extensibility
197 */
198 readonly handleUnknownExtRequest: EffectAcpClient.AcpClient["Service"]["handleUnknownExtRequest"];
199 /**
200 * Registers a fallback extension notification handler.
201 * @see https://agentclientprotocol.com/protocol/extensibility
202 */
203 readonly handleUnknownExtNotification: EffectAcpClient.AcpClient["Service"]["handleUnknownExtNotification"];
204 /**
205 * Registers a typed extension request handler.
206 * @see https://agentclientprotocol.com/protocol/extensibility
207 */
208 readonly handleExtRequest: EffectAcpClient.AcpClient["Service"]["handleExtRequest"];
209 /**
210 * Registers a typed extension notification handler.
211 * @see https://agentclientprotocol.com/protocol/extensibility
212 */
213 readonly handleExtNotification: EffectAcpClient.AcpClient["Service"]["handleExtNotification"];
214 /**
215 * Sends only `initialize` and returns the agent's response. Health probes use this to read
216 * advertised capabilities without authenticating or opening a session, so a probe can never
217 * start an interactive login or boot MCP servers.
218 * @see https://agentclientprotocol.com/protocol/schema#initialize
219 */
220 readonly initialize: () => Effect.Effect<
221 EffectAcpSchema.InitializeResponse,
222 EffectAcpErrors.AcpError
223 >;
224 /**
225 * Initializes the ACP connection, authenticates, and loads, resumes, or creates the session.
226 * Concurrent calls share the same in-flight startup and a failed startup may be retried.
227 */
228 readonly start: () => Effect.Effect<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;
229 /** Stream of parsed root-session events and connection failures. */
230 readonly getEvents: () => Stream.Stream<AcpSessionRuntimeEvent, never>;
231 /** Waits for queued events to be processed, or for the runtime scope to close. */
232 readonly drainEvents: Effect.Effect<void>;
233 /** Latest mode state observed from session setup and `session/update` notifications. */
234 readonly getModeState: Effect.Effect<AcpSessionModeState | undefined>;
235 /** Latest configuration options observed from session setup and configuration writes. */
236 readonly getConfigOptions: Effect.Effect<ReadonlyArray<EffectAcpSchema.SessionConfigOption>>;
237 /**
238 * Sends a prompt turn to the active session. `options.dispatched` settles once the
239 * `session/prompt` RPC is registered as the active prompt, so a caller that forks this
240 * effect knows when a later `cancel` will target this prompt.
241 * @see https://agentclientprotocol.com/protocol/schema#session/prompt
242 */
243 readonly prompt: (
244 payload: Omit<EffectAcpSchema.PromptRequest, "sessionId">,
245 options?: { readonly dispatched?: Deferred.Deferred<void> },
246 ) => Effect.Effect<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpError>;
247 /**
248 * Sends a real ACP `session/cancel` notification for the active session.
249 * @see https://agentclientprotocol.com/protocol/schema#session/cancel
250 */
251 readonly cancel: Effect.Effect<void, EffectAcpErrors.AcpError>;
252 /**
253 * Selects the active mode through the negotiated `mode` configuration option.
254 * This is a no-op when the requested mode is already active.
255 * @see https://agentclientprotocol.com/protocol/schema#session/set_config_option
256 */
257 readonly setMode: (
258 modeId: string,
259 ) => Effect.Effect<EffectAcpSchema.SetSessionModeResponse, EffectAcpErrors.AcpError>;
260 /**
261 * Updates a session configuration option and the runtime configuration snapshot.
262 * @see https://agentclientprotocol.com/protocol/schema#session/set_config_option
263 */
264 readonly setConfigOption: (
265 configId: string,
266 value: string | boolean,
267 ) => Effect.Effect<EffectAcpSchema.SetSessionConfigOptionResponse, EffectAcpErrors.AcpError>;
268 /**
269 * Selects the base model through the negotiated model configuration option.
270 * @see https://agentclientprotocol.com/protocol/schema#session/set_config_option
271 */
272 readonly setModel: (model: string) => Effect.Effect<void, EffectAcpErrors.AcpError>;
273 /**
274 * Selects the active model through the unstable ACP `session/set_model` capability.
275 * @see https://agentclientprotocol.com/protocol/schema#session/set_model
276 */
277 readonly setSessionModel: (
278 modelId: string,
279 meta?: EffectAcpSchema.SetSessionModelRequest["_meta"],
280 ) => Effect.Effect<EffectAcpSchema.SetSessionModelResponse, EffectAcpErrors.AcpError>;
281 /**
282 * Sends a generic ACP extension request and records it through the request logger.
283 * @see https://agentclientprotocol.com/protocol/extensibility
284 */
285 readonly request: (
286 method: string,
287 payload: unknown,
288 ) => Effect.Effect<unknown, EffectAcpErrors.AcpError>;
289 /**
290 * Sends a generic ACP extension notification.
291 * @see https://agentclientprotocol.com/protocol/extensibility
292 */
293 readonly notify: (
294 method: string,
295 payload: unknown,
296 ) => Effect.Effect<void, EffectAcpErrors.AcpError>;
297 }
298>()("t3/provider/acp/AcpSessionRuntime") {}
299​
300interface AcpStartedState extends AcpSessionRuntimeStartResult {}
301​
302type AcpStartState =
303 | { readonly _tag: "NotStarted" }
304 | {
305 readonly _tag: "Starting";
306 readonly deferred: Deferred.Deferred<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;
307 }
308 | { readonly _tag: "Started"; readonly result: AcpStartedState };
309​
310interface AcpAssistantSegmentState {
311 readonly nextSegmentIndex: number;
312 readonly activeItemId?: string;
314​
315interface EnsureActiveAssistantSegmentResult {
316 readonly itemId: string;
317 readonly startedEvent?: Extract<AcpParsedSessionEvent, { readonly _tag: "AssistantItemStarted" }>;
319​
320interface AcpActivePrompt {
321 readonly fiber: Fiber.Fiber<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpError>;
322 readonly completed: Deferred.Deferred<void>;
324​
325export const make = (
326 options: AcpSessionRuntimeOptions,
327): Effect.Effect<
328 AcpSessionRuntime["Service"],
329 EffectAcpErrors.AcpError,
330 ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | Scope.Scope
331> =>
332 Effect.gen(function* () {
333 const crypto = yield* Crypto.Crypto;
334 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
335 const runtimeScope = yield* Scope.Scope;
336 const eventQueue = yield* Queue.unbounded<AcpSessionRuntimeEvent>();
337 const modeStateRef = yield* Ref.make<AcpSessionModeState | undefined>(undefined);
338 const toolCallsRef = yield* Ref.make(new Map<string, AcpToolCallTrackedState>());
339 // Recently shown tool calls. A late update to a finished call is not a new
340 // boundary in the answer, although its progress state is gone.
341 const shownToolCallIds = new Set<string>();
342 const assistantItemRuntimeId = yield* crypto.randomUUIDv4.pipe(
343 Effect.mapError(
344 (cause) =>
345 new EffectAcpErrors.AcpTransportError({
346 detail: "Failed to generate an ACP assistant item runtime identifier.",
347 cause,
348 }),
349 ),
350 );
351 const assistantSegmentRef = yield* Ref.make<AcpAssistantSegmentState>({ nextSegmentIndex: 0 });
352 const configOptionsRef = yield* Ref.make(sessionConfigOptionsFromSetup(undefined));
353 const startStateRef = yield* Ref.make<AcpStartState>({ _tag: "NotStarted" });
354 const startupMetadataRef = yield* Ref.make<ReadonlyArray<EffectAcpSchema.SessionNotification>>(
355 [],
356 );
357 const notificationSemaphore = yield* Semaphore.make(1);
358 const terminationErrorRef = yield* Ref.make<Option.Option<EffectAcpErrors.AcpError>>(
359 Option.none(),
360 );
361 const stoppingRef = yield* Ref.make(false);
362 const stderrFailure = yield* Deferred.make<never, EffectAcpErrors.AcpError>();
363 const stderrTailRef = yield* Ref.make("");
364 const stderrDrained = yield* Deferred.make<void>();
365 const runtimeClosed = yield* Deferred.make<void>();
366 const promptSerializationSemaphore = yield* Semaphore.make(1);
367 const promptDispatchSemaphore = yield* Semaphore.make(1);
368 const activePromptRef = yield* Ref.make<Option.Option<AcpActivePrompt>>(Option.none());
369 const assistantUpdatesOpenRef = yield* Ref.make(true);
370 const sessionLoadGateRef = yield* Ref.make<Option.Option<SessionLoadGate>>(Option.none());
371​
372 const ensureConnected = Effect.gen(function* () {
373 const error = yield* Ref.get(terminationErrorRef);
374 if (Option.isSome(error)) {
375 return yield* error.value;
376 }
377 if (yield* Ref.get(stoppingRef)) {
378 return yield* new EffectAcpErrors.AcpTransportError({
379 detail: "The ACP session runtime is closed.",
380 cause: undefined,
381 });
382 }
383 });
384​
385 const enrichProcessExitWithStderr = (
386 error: EffectAcpErrors.AcpError,
387 ): Effect.Effect<EffectAcpErrors.AcpError> =>
388 error._tag !== "AcpProcessExitedError" || (error.stderr?.trim().length ?? 0) > 0
389 ? Effect.succeed(error)
390 : Deferred.await(stderrDrained).pipe(
391 Effect.timeout("250 millis"),
392 Effect.ignore,
393 Effect.andThen(Ref.get(stderrTailRef)),
394 Effect.map((tail) => {
395 const stderr = sanitizeAcpStderrExcerpt(tail);
396 return stderr.length === 0
397 ? error
398 : new EffectAcpErrors.AcpProcessExitedError({
399 ...(error.code !== undefined ? { code: error.code } : {}),
400 ...(error.pid !== undefined ? { pid: error.pid } : {}),
401 stderr,
402 ...(error.cause !== undefined ? { cause: error.cause } : {}),
403 });
404 }),
405 );
406​
407 const recordTermination = Effect.fn("AcpSessionRuntime.recordTermination")(function* (
408 error: EffectAcpErrors.AcpError,
409 ) {
410 if (yield* Ref.get(stoppingRef)) {
411 return;
412 }
413 const enriched = yield* enrichProcessExitWithStderr(error);
414 const firstTermination = yield* Ref.modify(terminationErrorRef, (current) =>
415 Option.isSome(current)
416 ? ([false, current] as const)
417 : ([true, Option.some(enriched)] as const),
418 );
419 if (!firstTermination) {
420 return;
421 }
422 yield* closeActiveAssistantSegment({ queue: eventQueue, assistantSegmentRef });
423 yield* Queue.offer(eventQueue, { _tag: "ConnectionTerminated", error: enriched });
424 });
425​
426 const logRequest = (event: AcpSessionRequestLogEvent) =>
427 options.requestLogger ? options.requestLogger(event) : Effect.void;
428​
429 const runLoggedRequest = <A>(
430 method: string,
431 payload: unknown,
432 effect: Effect.Effect<A, EffectAcpErrors.AcpError>,
433 ): Effect.Effect<A, EffectAcpErrors.AcpError> =>
434 logRequest({ method, payload, status: "started" }).pipe(
435 Effect.flatMap(() =>
436 (options.onStderr
437 ? Effect.raceFirst(effect, Deferred.await(stderrFailure))
438 : effect
439 ).pipe(
440 Effect.catch((error) =>
441 enrichProcessExitWithStderr(error).pipe(Effect.flatMap(Effect.fail)),
442 ),
443 Effect.tap((result) =>
444 logRequest({
445 method,
446 payload,
447 status: "succeeded",
448 result,
449 }),
450 ),
451 Effect.onError((cause) =>
452 logRequest({
453 method,
454 payload,
455 status: "failed",
456 cause,
457 }),
458 ),
459 ),
460 ),
461 );
462​
463 const spawnCommand = yield* resolveSpawnCommand(options.spawn.command, options.spawn.args, {
464 ...(options.spawn.env ? { env: options.spawn.env } : {}),
465 extendEnv: options.spawn.extendEnv ?? true,
466 });
467 const child = yield* spawner
468 .spawn(
469 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
470 ...(options.spawn.cwd ? { cwd: options.spawn.cwd } : {}),
471 ...(options.spawn.env ? { env: options.spawn.env } : {}),
472 extendEnv: options.spawn.extendEnv ?? true,
473 shell: spawnCommand.shell,
474 }),
475 )
476 .pipe(
477 Effect.provideService(Scope.Scope, runtimeScope),
478 Effect.mapError(
479 (cause) =>
480 new EffectAcpErrors.AcpSpawnError({
481 command: options.spawn.command,
482 cause,
483 }),
484 ),
485 );
486​
487 yield* child.stderr.pipe(
488 Stream.decodeText(),
489 Stream.runForEach((chunk) =>
490 Ref.update(stderrTailRef, (current) => appendAcpStderrTail(current, chunk)).pipe(
491 Effect.andThen(
492 options.onStderr ? options.onStderr(chunk.slice(-maxStderrChunkLength)) : Effect.void,
493 ),
494 Effect.catch((error) =>
495 Effect.gen(function* () {
496 yield* Deferred.fail(stderrFailure, error);
497 yield* recordTermination(error);
498 yield* child.kill({ forceKillAfter: "1 second" }).pipe(Effect.ignore);
499 }),
500 ),
501 ),
502 ),
503 Effect.ensuring(Deferred.succeed(stderrDrained, undefined)),
504 Effect.ignore,
505 Effect.forkIn(runtimeScope),
506 );
507​
508 const acpContext = yield* Layer.build(
509 EffectAcpClient.layerChildProcess(child, {
510 ...(options.transformStdout ? { transformStdout: options.transformStdout } : {}),
511 ...(options.transformSessionUpdate
512 ? { transformSessionUpdate: options.transformSessionUpdate }
513 : {}),
514 onTermination: recordTermination,
515 ...(options.protocolLogging?.logIncoming !== undefined
516 ? { logIncoming: options.protocolLogging.logIncoming }
517 : {}),
518 ...(options.protocolLogging?.logOutgoing !== undefined
519 ? { logOutgoing: options.protocolLogging.logOutgoing }
520 : {}),
521 ...(options.protocolLogging?.logger ? { logger: options.protocolLogging.logger } : {}),
522 }),
523 ).pipe(Effect.provideService(Scope.Scope, runtimeScope));
524​
525 const acp = yield* Effect.service(EffectAcpClient.AcpClient).pipe(Effect.provide(acpContext));
526​
527 const processSessionUpdate = (notification: EffectAcpSchema.SessionNotification) =>
528 handleSessionUpdate({
529 queue: eventQueue,
530 modeStateRef,
531 configOptionsRef,
532 toolCallsRef,
533 shownToolCallIds,
534 assistantSegmentRef,
535 assistantItemRuntimeId,
536 params: notification,
537 });
538​
539 yield* acp.handleSessionUpdate((notification) =>
540 notificationSemaphore.withPermit(
541 Effect.gen(function* () {
542 if (Option.isSome(yield* Ref.get(terminationErrorRef))) {
543 return;
544 }
545 const gate = yield* Ref.get(sessionLoadGateRef);
546 if (
547 Option.isSome(gate) &&
548 gate.value.active &&
549 notification.sessionId === options.resumeSessionId
550 ) {
551 const lastActivityAtMillis = yield* Clock.currentTimeMillis;
552 yield* Ref.set(
553 sessionLoadGateRef,
554 Option.some({
555 ...gate.value,
556 lastActivityAtMillis,
557 }),
558 );
559 }
560 if (sessionUpdateIsReplay(notification)) {
561 return;
562 }
563 const startState = yield* Ref.get(startStateRef);
564 if (startState._tag === "Starting") {
565 if (isStartupMetadataUpdate(notification)) {
566 yield* Ref.update(startupMetadataRef, (current) =>
567 [
568 ...current.filter(
569 (previous) =>
570 previous.sessionId !== notification.sessionId ||
571 previous.update.sessionUpdate !== notification.update.sessionUpdate,
572 ),
573 notification,
574 ].slice(-maxStartupMetadataUpdates),
575 );
576 }
577 return;
578 }
579 // One runtime projects one root ACP session. Child-session updates need
580 // explicit lineage routing and must never be flattened into this stream.
581 if (
582 startState._tag !== "Started" ||
583 notification.sessionId !== startState.result.sessionId
584 ) {
585 return;
586 }
587 if (
588 !(yield* Ref.get(assistantUpdatesOpenRef)) &&
589 (notification.update.sessionUpdate === "agent_message_chunk" ||
590 notification.update.sessionUpdate === "agent_thought_chunk")
591 ) {
592 return;
593 }
594 yield* processSessionUpdate(notification);
595 }),
596 ),
597 );
598 yield* Scope.addFinalizer(
599 runtimeScope,
600 Ref.set(stoppingRef, true).pipe(Effect.andThen(Deferred.succeed(runtimeClosed, undefined))),
601 );
602 const initializeClientCapabilities = {
603 fs: {
604 readTextFile: false,
605 writeTextFile: false,
606 ...options.clientCapabilities?.fs,
607 },
608 terminal: options.clientCapabilities?.terminal ?? false,
609 ...(options.clientCapabilities?.auth ? { auth: options.clientCapabilities.auth } : {}),
610 ...(options.clientCapabilities?.elicitation
611 ? { elicitation: options.clientCapabilities.elicitation }
612 : {}),
613 ...(options.clientCapabilities?._meta ? { _meta: options.clientCapabilities._meta } : {}),
614 } satisfies NonNullable<EffectAcpSchema.InitializeRequest["clientCapabilities"]>;
615​
616 const getStartedState = Effect.gen(function* () {
617 yield* ensureConnected;
618 const state = yield* Ref.get(startStateRef);
619 if (state._tag === "Started") {
620 return state.result;
621 }
622 return yield* new EffectAcpErrors.AcpTransportError({
623 detail: "ACP session runtime has not been started",
624 cause: "ACP session runtime has not been started",
625 });
626 });
627​
628 const validateConfigOptionValue = (
629 configId: string,
630 value: string | boolean,
631 ): Effect.Effect<void, EffectAcpErrors.AcpError> =>
632 Effect.gen(function* () {
633 const configOption = findSessionConfigOption(yield* Ref.get(configOptionsRef), configId);
634 if (!configOption) {
635 return;
636 }
637 if (configOption.type === "boolean") {
638 if (typeof value === "boolean") {
639 return;
640 }
641 return yield* new EffectAcpErrors.AcpRequestError({
642 code: -32602,
643 errorMessage: `Invalid value ${formatConfigOptionValue(value)} for session config option "${configOption.id}": expected boolean`,
644 data: {
645 configId: configOption.id,
646 expectedType: "boolean",
647 receivedValue: value,
648 },
649 });
650 }
651 if (typeof value !== "string") {
652 return yield* new EffectAcpErrors.AcpRequestError({
653 code: -32602,
654 errorMessage: `Invalid value ${formatConfigOptionValue(value)} for session config option "${configOption.id}": expected string`,
655 data: {
656 configId: configOption.id,
657 expectedType: "string",
658 receivedValue: value,
659 },
660 });
661 }
662 const allowedValues = collectSessionConfigOptionValues(configOption);
663 if (allowedValues.includes(value)) {
664 return;
665 }
666 return yield* new EffectAcpErrors.AcpRequestError({
667 code: -32602,
668 errorMessage: `Invalid value ${formatConfigOptionValue(value)} for session config option "${configOption.id}": expected one of ${allowedValues.join(", ")}`,
669 data: {
670 configId: configOption.id,
671 allowedValues,
672 receivedValue: value,
673 },
674 });
675 });
676​
677 const updateConfigOptions = Effect.fn("AcpSessionRuntime.updateConfigOptions")(function* (
678 response: EffectAcpSchema.SetSessionConfigOptionResponse,
679 ) {
680 const configOptions = sessionConfigOptionsFromSetup(response);
681 yield* Ref.set(configOptionsRef, configOptions);
682 yield* Queue.offer(eventQueue, {
683 _tag: "ConfigOptionsUpdated",
684 configOptions,
685 rawPayload: response,
686 });
687 });
688​
689 const updateCurrentModeId = (modeId: string): Effect.Effect<void> =>
690 Ref.update(modeStateRef, (current) =>
691 current ? { ...current, currentModeId: modeId } : current,
692 );
693​
694 const setConfigOption = (
695 configId: string,
696 value: string | boolean,
697 ): Effect.Effect<EffectAcpSchema.SetSessionConfigOptionResponse, EffectAcpErrors.AcpError> =>
698 validateConfigOptionValue(configId, value).pipe(
699 Effect.flatMap(() => getStartedState),
700 Effect.flatMap((started) =>
701 Ref.get(configOptionsRef).pipe(
702 Effect.flatMap((configOptions) => {
703 const existing = findSessionConfigOption(configOptions, configId);
704 if (existing && configOptionCurrentValueMatches(existing, value)) {
705 return Effect.succeed({
706 configOptions,
707 } satisfies EffectAcpSchema.SetSessionConfigOptionResponse);
708 }
709 const requestPayload =
710 typeof value === "boolean"
711 ? ({
712 sessionId: started.sessionId,
713 configId,
714 type: "boolean",
715 value,
716 } satisfies EffectAcpSchema.SetSessionConfigOptionRequest)
717 : ({
718 sessionId: started.sessionId,
719 configId,
720 value: String(value),
721 } satisfies EffectAcpSchema.SetSessionConfigOptionRequest);
722 return runLoggedRequest(
723 "session/set_config_option",
724 requestPayload,
725 acp.agent.setSessionConfigOption(requestPayload),
726 ).pipe(Effect.tap((response) => updateConfigOptions(response)));
727 }),
728 ),
729 ),
730 );
731​
732 const initializePayload = {
733 protocolVersion: 1,
734 clientCapabilities: initializeClientCapabilities,
735 clientInfo: options.clientInfo,
736 } satisfies EffectAcpSchema.InitializeRequest;
737 const sendInitialize = runLoggedRequest(
738 "initialize",
739 initializePayload,
740 acp.agent.initialize(initializePayload),
741 );
742​
743 const startOnce = Effect.gen(function* () {
744 const initializeResult = yield* sendInitialize;
745​
746 const authenticatePayload = {
747 methodId: options.authMethodId,
748 } satisfies EffectAcpSchema.AuthenticateRequest;
749​
750 yield* runLoggedRequest(
751 "authenticate",
752 authenticatePayload,
753 acp.agent.authenticate(authenticatePayload),
754 );
755​
756 let sessionId: string;
757 let sessionSetupResult:
758 | EffectAcpSchema.LoadSessionResponse
759 | EffectAcpSchema.NewSessionResponse
760 | EffectAcpSchema.ResumeSessionResponse;
761 if (options.resumeSessionId && options.resumeMethod === "resume") {
762 if (!initializeResult.agentCapabilities?.sessionCapabilities?.resume) {
763 return yield* new EffectAcpErrors.AcpTransportError({
764 method: "session/resume",
765 detail: "The ACP agent does not support session/resume.",
766 cause: undefined,
767 });
768 }
769 const resumePayload = {
770 sessionId: options.resumeSessionId,
771 cwd: options.cwd,
772 mcpServers: options.mcpServers ?? [],
773 ...(options.additionalDirectories && options.additionalDirectories.length > 0
774 ? { additionalDirectories: options.additionalDirectories }
775 : {}),
776 } satisfies EffectAcpSchema.ResumeSessionRequest;
777 sessionId = options.resumeSessionId;
778 sessionSetupResult = yield* runLoggedRequest(
779 "session/resume",
780 resumePayload,
781 acp.agent.resumeSession(resumePayload).pipe(
782 Effect.timeoutOption(options.sessionLoadTimeout ?? defaultSessionLoadTimeout),
783 Effect.flatMap(
784 Effect.fromOption(
785 () =>
786 new EffectAcpErrors.AcpTransportError({
787 operation: "call-rpc",
788 method: "session/resume",
789 detail: "session/resume timed out waiting for the agent response.",
790 cause: undefined,
791 }),
792 ),
793 ),
794 ),
795 );
796 } else if (options.resumeSessionId) {
797 const loadPayload = {
798 sessionId: options.resumeSessionId,
799 cwd: options.cwd,
800 mcpServers: options.mcpServers ?? [],
801 } satisfies EffectAcpSchema.LoadSessionRequest;
802 const sessionLoadTimeout = Duration.fromInputUnsafe(
803 options.sessionLoadTimeout ?? defaultSessionLoadTimeout,
804 );
805 const sessionLoadReplayIdleGap = Duration.fromInputUnsafe(
806 options.sessionLoadReplayIdleGap ?? defaultSessionLoadReplayIdleGap,
807 );
808​
809 yield* Ref.set(
810 sessionLoadGateRef,
811 Option.some({
812 active: true,
813 lastActivityAtMillis: undefined,
814 idleGap: sessionLoadReplayIdleGap,
815 initializeResult,
816 }),
817 );
818​
819 sessionId = options.resumeSessionId;
820 sessionSetupResult = yield* Effect.gen(function* () {
821 yield* logRequest({
822 method: "session/load",
823 payload: loadPayload,
824 status: "started",
825 });
826​
827 const idleFiber = yield* waitForSessionLoadReplayIdle({
828 gateRef: sessionLoadGateRef,
829 }).pipe(Effect.forkIn(runtimeScope));
830 const loaded = yield* Effect.raceFirst(
831 acp.agent.loadSession(loadPayload),
832 Fiber.join(idleFiber),
833 ).pipe(
834 Effect.ensuring(Fiber.interrupt(idleFiber).pipe(Effect.ignore)),
835 Effect.timeoutOption(sessionLoadTimeout),
836 Effect.flatMap(
837 Effect.fromOption(
838 () =>
839 new EffectAcpErrors.AcpTransportError({
840 operation: "call-rpc",
841 method: "session/load",
842 detail: "session/load timed out waiting for RPC response or replay idle gap",
843 cause: undefined,
844 }),
845 ),
846 ),
847 Effect.tap((result) =>
848 logRequest({
849 method: "session/load",
850 payload: loadPayload,
851 status: "succeeded",
852 result,
853 }),
854 ),
855 Effect.onError((cause) =>
856 logRequest({
857 method: "session/load",
858 payload: loadPayload,
859 status: "failed",
860 cause,
861 }),
862 ),
863 );
864​
865 return loaded;
866 }).pipe(Effect.ensuring(Ref.set(sessionLoadGateRef, Option.none())));
867 } else {
868 const createPayload = {
869 cwd: options.cwd,
870 mcpServers: options.mcpServers ?? [],
871 ...(options.additionalDirectories && options.additionalDirectories.length > 0
872 ? { additionalDirectories: options.additionalDirectories }
873 : {}),
874 } satisfies EffectAcpSchema.NewSessionRequest;
875 const created = yield* runLoggedRequest(
876 "session/new",
877 createPayload,
878 acp.agent.createSession(createPayload),
879 );
880 sessionId = created.sessionId;
881 sessionSetupResult = created;
882 }
883​
884 yield* Ref.set(modeStateRef, parseSessionModeState(sessionSetupResult));
885 yield* Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(sessionSetupResult));
886​
887 const nextState = {
888 sessionId,
889 initializeResult,
890 sessionSetupResult,
891 modelConfigId: extractModelConfigId(sessionSetupResult),
892 } satisfies AcpStartedState;
893 return nextState;
894 });
895​
896 const start = Effect.gen(function* () {
897 yield* ensureConnected;
898 const deferred = yield* Deferred.make<
899 AcpSessionRuntimeStartResult,
900 EffectAcpErrors.AcpError
901 >();
902 const effect = yield* Ref.modify(startStateRef, (state) => {
903 switch (state._tag) {
904 case "Started":
905 return [Effect.succeed(state.result), state] as const;
906 case "Starting":
907 return [Deferred.await(state.deferred), state] as const;
908 case "NotStarted":
909 return [
910 startOnce.pipe(
911 Effect.tap((result) =>
912 notificationSemaphore.withPermit(
913 Effect.gen(function* () {
914 const error = yield* Ref.get(terminationErrorRef);
915 if (Option.isSome(error)) {
916 return yield* error.value;
917 }
918 yield* Ref.set(startStateRef, { _tag: "Started", result });
919 const metadata = yield* Ref.getAndSet(startupMetadataRef, []);
920 for (const notification of metadata) {
921 if (notification.sessionId === result.sessionId) {
922 yield* processSessionUpdate(notification);
923 }
924 }
925 yield* Deferred.succeed(deferred, result);
926 }),
927 ),
928 ),
929 Effect.onError((cause) =>
930 Deferred.failCause(deferred, cause).pipe(
931 Effect.andThen(Ref.set(startStateRef, { _tag: "NotStarted" })),
932 Effect.andThen(Ref.set(startupMetadataRef, [])),
933 ),
934 ),
935 ),
936 { _tag: "Starting", deferred } satisfies AcpStartState,
937 ] as const;
938 }
939 });
940 return yield* effect;
941 });
942​
943 const drainEvents = Effect.gen(function* () {
944 if (yield* Ref.get(stoppingRef)) {
945 return;
946 }
947 const acknowledge = yield* Deferred.make<void>();
948 yield* notificationSemaphore.withPermit(
949 Effect.gen(function* () {
950 // Keep a provider's final flushed chunks together until the adapter settles the turn.
951 if (Option.isNone(yield* Ref.get(activePromptRef))) {
952 yield* Ref.set(assistantUpdatesOpenRef, false);
953 yield* closeActiveAssistantSegment({ queue: eventQueue, assistantSegmentRef });
954 }
955 yield* Queue.offer(eventQueue, { _tag: "EventStreamBarrier", acknowledge });
956 }),
957 );
958 yield* Effect.raceFirst(Deferred.await(acknowledge), Deferred.await(runtimeClosed));
959 });
960​
961 const retireRuntime = Effect.fn("AcpSessionRuntime.retireRuntime")(function* (
962 error: EffectAcpErrors.AcpError,
963 ) {
964 yield* recordTermination(error);
965 yield* child.kill({ forceKillAfter: "1 second" }).pipe(Effect.ignore);
966 });
967​
968 const cancel = Effect.gen(function* () {
969 const started = yield* getStartedState;
970 const activePrompt = yield* Ref.get(activePromptRef);
971 if (options.cancelBehavior !== "wait-for-prompt") {
972 if (Option.isSome(activePrompt)) {
973 yield* Fiber.interrupt(activePrompt.value.fiber).pipe(Effect.ignore);
974 }
975 // Write cancel before a replacement prompt can reach the agent.
976 yield* acp.agent.cancel({ sessionId: started.sessionId }).pipe(Effect.ignore);
977 return;
978 }
979​
980 yield* acp.agent.cancel({ sessionId: started.sessionId });
981 if (Option.isNone(activePrompt)) {
982 return;
983 }
984 const completed = yield* Effect.gen(function* () {
985 const result = yield* Fiber.await(activePrompt.value.fiber);
986 yield* Deferred.await(activePrompt.value.completed);
987 if (Option.isNone(yield* Ref.get(terminationErrorRef))) {
988 yield* drainEvents;
989 }
990 return result;
991 }).pipe(Effect.timeoutOption(options.cancelTimeout ?? defaultCancelTimeout));
992 if (Option.isNone(completed)) {
993 const error = new EffectAcpErrors.AcpTransportError({
994 operation: "call-rpc",
995 method: "session/cancel",
996 detail: "The ACP agent did not finish cancellation. Its process was stopped.",
997 cause: undefined,
998 });
999 yield* retireRuntime(error);
1000 return yield* error;
1002 if (Exit.isFailure(completed.value)) {
1003 return yield* Effect.failCause(completed.value.cause);
1005 });
1006​
1007 return {
1008 handleRequestPermission: acp.handleRequestPermission,
1009 handleElicitation: acp.handleElicitation,
1010 handleReadTextFile: acp.handleReadTextFile,
1011 handleWriteTextFile: acp.handleWriteTextFile,
1012 handleCreateTerminal: acp.handleCreateTerminal,
1013 handleTerminalOutput: acp.handleTerminalOutput,
1014 handleTerminalWaitForExit: acp.handleTerminalWaitForExit,
1015 handleTerminalKill: acp.handleTerminalKill,
1016 handleTerminalRelease: acp.handleTerminalRelease,
1017 handleSessionUpdate: acp.handleSessionUpdate,
1018 handleElicitationComplete: acp.handleElicitationComplete,
1019 handleUnknownExtRequest: acp.handleUnknownExtRequest,
1020 handleUnknownExtNotification: acp.handleUnknownExtNotification,
1021 handleExtRequest: acp.handleExtRequest,
1022 handleExtNotification: acp.handleExtNotification,
1023 initialize: () => ensureConnected.pipe(Effect.andThen(sendInitialize)),
1024 start: () => start,
1025 getEvents: () => Stream.fromQueue(eventQueue),
1026 drainEvents,
1027 getModeState: Ref.get(modeStateRef),
1028 getConfigOptions: Ref.get(configOptionsRef),
1029 prompt: (payload, promptOptions?) =>
1030 promptSerializationSemaphore.withPermit(
1031 Effect.acquireUseRelease(
1032 promptDispatchSemaphore.withPermit(
1033 Effect.gen(function* () {
1034 const started = yield* getStartedState;
1035 yield* closeActiveAssistantSegment({ queue: eventQueue, assistantSegmentRef });
1036 yield* Ref.set(assistantUpdatesOpenRef, true);
1037 const requestPayload = {
1038 sessionId: started.sessionId,
1039 ...payload,
1040 } satisfies EffectAcpSchema.PromptRequest;
1041 const completed = yield* Deferred.make<void>();
1042 const fiber = yield* runLoggedRequest(
1043 "session/prompt",
1044 requestPayload,
1045 acp.agent.prompt(requestPayload),
1046 ).pipe(Effect.forkIn(runtimeScope));
1047 const active = { fiber, completed } satisfies AcpActivePrompt;
1048 yield* Ref.set(activePromptRef, Option.some(active));
1049 if (promptOptions?.dispatched) {
1050 yield* Deferred.succeed(promptOptions.dispatched, undefined);
1052 return active;
1053 }).pipe(notificationSemaphore.withPermit),
1054 ),
1055 (activePrompt) =>
1056 Fiber.join(activePrompt.fiber).pipe(
1057 Effect.catchCauseIf(
1058 (cause) =>
1059 options.cancelBehavior !== "wait-for-prompt" && Cause.hasInterruptsOnly(cause),
1060 () =>
1061 Effect.succeed({
1062 stopReason: "cancelled",
1063 } satisfies EffectAcpSchema.PromptResponse),
1064 ),
1065 Effect.tap(() =>
1066 closeActiveAssistantSegment({ queue: eventQueue, assistantSegmentRef }),
1067 ),
1068 ),
1069 (activePrompt, result) =>
1070 Effect.gen(function* () {
1071 if (
1072 options.cancelBehavior === "wait-for-prompt" &&
1073 Exit.isFailure(result) &&
1074 Cause.hasInterrupts(result.cause)
1075 ) {
1076 yield* retireRuntime(
1077 new EffectAcpErrors.AcpTransportError({
1078 method: "session/prompt",
1079 detail: "The ACP prompt stopped before the agent confirmed completion.",
1080 cause: undefined,
1081 }),
1082 );
1084 yield* Fiber.interrupt(activePrompt.fiber).pipe(Effect.ignore);
1085 yield* Ref.set(activePromptRef, Option.none());
1086 yield* Deferred.succeed(activePrompt.completed, undefined);
1087 }),
1088 ),
1089 ),
1090 cancel:
1091 options.cancelBehavior === "wait-for-prompt"
1092 ? promptDispatchSemaphore.withPermit(cancel)
1093 : cancel,
1094 setMode: (modeId) =>
1095 Ref.get(modeStateRef).pipe(
1096 Effect.flatMap((modeState) => {
1097 if (modeState?.currentModeId === modeId) {
1098 return Effect.succeed({} satisfies EffectAcpSchema.SetSessionModeResponse);
1100 return setConfigOption("mode", modeId).pipe(
1101 Effect.tap(() => updateCurrentModeId(modeId)),
1102 Effect.as({} satisfies EffectAcpSchema.SetSessionModeResponse),
1103 );
1104 }),
1105 ),
1106 setConfigOption,
1107 setModel: (model) =>
1108 getStartedState.pipe(
1109 Effect.flatMap((started) => setConfigOption(started.modelConfigId ?? "model", model)),
1110 Effect.asVoid,
1111 ),
1112 setSessionModel: (modelId, meta) =>
1113 getStartedState.pipe(
1114 Effect.flatMap((started) => {
1115 const requestPayload = {
1116 sessionId: started.sessionId,
1117 modelId,
1118 ...(meta !== undefined ? { _meta: meta } : {}),
1119 } satisfies EffectAcpSchema.SetSessionModelRequest;
1120 return runLoggedRequest(
1121 "session/set_model",
1122 requestPayload,
1123 acp.agent.setSessionModel(requestPayload),
1124 );
1125 }),
1126 ),
1127 request: (method, payload) =>
1128 ensureConnected.pipe(
1129 Effect.andThen(runLoggedRequest(method, payload, acp.raw.request(method, payload))),
1130 ),
1131 notify: (method, payload) =>
1132 ensureConnected.pipe(Effect.andThen(acp.raw.notify(method, payload))),
1133 } satisfies AcpSessionRuntime["Service"];
1134 });
1135​
1136export const layer = (
1137 options: AcpSessionRuntimeOptions,
1138): Layer.Layer<
1139 AcpSessionRuntime,
1140 EffectAcpErrors.AcpError,
1141 ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto
1142> => Layer.effect(AcpSessionRuntime, make(options));
1143​
1144function sessionConfigOptionsFromSetup(
1145 response:
1146 | {
1147 readonly configOptions?: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null;
1149 | undefined,
1150): ReadonlyArray<EffectAcpSchema.SessionConfigOption> {
1151 return response?.configOptions ?? [];
1153​
1154function configOptionCurrentValueMatches(
1155 configOption: EffectAcpSchema.SessionConfigOption,
1156 value: string | boolean,
1157): boolean {
1158 const currentValue = configOption.currentValue;
1159 if (configOption.type === "boolean") {
1160 return currentValue === value;
1162 if (typeof currentValue !== "string") {
1163 return false;
1165 return currentValue.trim() === String(value).trim();
1167​
1168function isStartupMetadataUpdate(notification: EffectAcpSchema.SessionNotification): boolean {
1169 switch (notification.update.sessionUpdate) {
1170 case "current_mode_update":
1171 case "config_option_update":
1172 case "available_commands_update":
1173 return true;
1174 default:
1175 return false;
1178​
1179const handleSessionUpdate = ({
1180 queue,
1181 modeStateRef,
1182 configOptionsRef,
1183 toolCallsRef,
1184 shownToolCallIds,
1185 assistantSegmentRef,
1186 assistantItemRuntimeId,
1187 params,
1188}: {
1189 readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;
1190 readonly modeStateRef: Ref.Ref<AcpSessionModeState | undefined>;
1191 readonly configOptionsRef: Ref.Ref<ReadonlyArray<EffectAcpSchema.SessionConfigOption>>;
1192 readonly toolCallsRef: Ref.Ref<Map<string, AcpToolCallTrackedState>>;
1193 readonly shownToolCallIds: Set<string>;
1194 readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
1195 readonly assistantItemRuntimeId: string;
1196 readonly params: EffectAcpSchema.SessionNotification;
1197}): Effect.Effect<void> =>
1198 Effect.gen(function* () {
1199 if (params.update.sessionUpdate === "config_option_update") {
1200 yield* Ref.set(configOptionsRef, params.update.configOptions);
1202 const parsed = parseSessionUpdateEvent(params);
1203 if (parsed.modeId) {
1204 yield* Ref.update(modeStateRef, (current) =>
1205 current === undefined ? current : updateModeState(current, parsed.modeId!),
1206 );
1208 for (const event of parsed.events) {
1209 if (event._tag === "ToolCallUpdated") {
1210 const { merged, decision, active } = yield* Ref.modify(toolCallsRef, (current) => {
1211 const tracked = current.get(event.toolCall.toolCallId);
1212 const previous = tracked?.state;
1213 const nextToolCall = mergeToolCallState(previous, event.toolCall);
1214 const decision = decideToolCallUpdateEmission({
1215 previous,
1216 next: nextToolCall,
1217 lastEmittedDetailLength: tracked?.lastEmittedDetailLength,
1218 skippedSinceEmit: tracked?.skippedSinceEmit ?? 0,
1219 });
1220 const next = new Map(current);
1221 if (nextToolCall.status === "completed" || nextToolCall.status === "failed") {
1222 next.delete(nextToolCall.toolCallId);
1223 } else {
1224 next.set(nextToolCall.toolCallId, {
1225 state: nextToolCall,
1226 lastEmittedDetailLength: decision.emit
1227 ? toolCallProgressLength(nextToolCall)
1228 : tracked?.lastEmittedDetailLength,
1229 skippedSinceEmit: decision.skippedSinceEmit,
1230 });
1232 return [{ merged: nextToolCall, decision, active: tracked !== undefined }, next] as const;
1233 });
1234 if (!decision.emit) {
1235 continue;
1237 // A new tool call is a boundary in the prose. Progress on a call that
1238 // is already shown, such as a background command finishing, is not.
1239 if (!shownToolCallIds.has(merged.toolCallId)) {
1240 shownToolCallIds.add(merged.toolCallId);
1241 // Only recent calls get late updates; keep a long session bounded.
1242 if (shownToolCallIds.size > MAX_SHOWN_TOOL_CALL_IDS) {
1243 shownToolCallIds.delete(shownToolCallIds.values().next().value!);
1245 // A call still running is already on screen, even if it aged out.
1246 if (!active) yield* closeActiveAssistantSegment({ queue, assistantSegmentRef });
1248 yield* Queue.offer(queue, {
1249 _tag: "ToolCallUpdated",
1250 toolCall: merged,
1251 rawPayload: event.rawPayload,
1252 });
1253 continue;
1255 if (event._tag === "ContentDelta") {
1256 if (event.text.trim().length === 0) {
1257 const assistantSegmentState = yield* Ref.get(assistantSegmentRef);
1258 if (!assistantSegmentState.activeItemId) {
1259 continue;
1262 const itemId = yield* ensureActiveAssistantSegment({
1263 queue,
1264 assistantSegmentRef,
1265 sessionId: params.sessionId,
1266 assistantItemRuntimeId,
1267 });
1268 yield* Queue.offer(queue, {
1269 ...event,
1270 itemId,
1271 });
1272 continue;
1274 yield* Queue.offer(queue, event);
1276 });
1277​
1278function updateModeState(modeState: AcpSessionModeState, nextModeId: string): AcpSessionModeState {
1279 const normalized = nextModeId.trim();
1280 if (!normalized) {
1281 return modeState;
1283 return modeState.availableModes.some((mode) => mode.id === normalized)
1284 ? {
1285 ...modeState,
1286 currentModeId: normalized,
1288 : modeState;
1290​
1291const assistantItemId = (sessionId: string, runtimeId: string, segmentIndex: number) =>
1292 `assistant:${sessionId}:runtime:${runtimeId}:segment:${segmentIndex}`;
1293​
1294const ensureActiveAssistantSegment = ({
1295 queue,
1296 assistantSegmentRef,
1297 sessionId,
1298 assistantItemRuntimeId,
1299}: {
1300 readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;
1301 readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
1302 readonly sessionId: string;
1303 readonly assistantItemRuntimeId: string;
1304}) =>
1305 Ref.modify<AcpAssistantSegmentState, EnsureActiveAssistantSegmentResult>(
1306 assistantSegmentRef,
1307 (current) => {
1308 if (current.activeItemId) {
1309 return [{ itemId: current.activeItemId }, current] as const;
1311 const itemId = assistantItemId(sessionId, assistantItemRuntimeId, current.nextSegmentIndex);
1312 return [
1314 itemId,
1315 startedEvent: {
1316 _tag: "AssistantItemStarted",
1317 itemId,
1318 } satisfies Extract<AcpParsedSessionEvent, { readonly _tag: "AssistantItemStarted" }>,
1319 },
1321 nextSegmentIndex: current.nextSegmentIndex + 1,
1322 activeItemId: itemId,
1323 } satisfies AcpAssistantSegmentState,
1324 ] as const;
1325 },
1326 ).pipe(
1327 Effect.flatMap((result) =>
1328 result.startedEvent
1329 ? Queue.offer(queue, result.startedEvent).pipe(Effect.as(result.itemId))
1330 : Effect.succeed(result.itemId),
1331 ),
1332 );
1333​
1334const closeActiveAssistantSegment = ({
1335 queue,
1336 assistantSegmentRef,
1337}: {
1338 readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;
1339 readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
1340}) =>
1341 Ref.modify(assistantSegmentRef, (current) => {
1342 if (!current.activeItemId) {
1343 return [undefined, current] as const;
1345 return [
1347 _tag: "AssistantItemCompleted",
1348 itemId: current.activeItemId,
1349 } satisfies AcpParsedSessionEvent,
1351 nextSegmentIndex: current.nextSegmentIndex,
1352 } satisfies AcpAssistantSegmentState,
1353 ] as const;
1354 }).pipe(Effect.flatMap((event) => (event ? Queue.offer(queue, event) : Effect.void)));