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

AcpSessionRuntime.ts

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