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

AcpSessionRuntime.ts

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