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