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 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 };
113}
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>;
121}
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;
131}
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;
310}
311
312interface EnsureActiveAssistantSegmentResult {
313 readonly itemId: string;
314 readonly startedEvent?: Extract<AcpParsedSessionEvent, { readonly _tag: "AssistantItemStarted" }>;
315}
316
317interface AcpActivePrompt {
318 readonly fiber: Fiber.Fiber<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpError>;
319 readonly completed: Deferred.Deferred<void>;
320}
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 sessionLoadGateRef = yield* Ref.make<Option.Option<SessionLoadGate>>(Option.none());
362
363 const ensureConnected = Effect.gen(function* () {
364 const error = yield* Ref.get(terminationErrorRef);
365 if (Option.isSome(error)) {
366 return yield* error.value;
367 }
368 if (yield* Ref.get(stoppingRef)) {
369 return yield* new EffectAcpErrors.AcpTransportError({
370 detail: "The ACP session runtime is closed.",
371 cause: undefined,
372 });
373 }
374 });
375
376 const recordTermination = Effect.fn("AcpSessionRuntime.recordTermination")(function* (
377 error: EffectAcpErrors.AcpError,
378 ) {
379 if (yield* Ref.get(stoppingRef)) {
380 return;
381 }
382 const firstTermination = yield* Ref.modify(terminationErrorRef, (current) =>
383 Option.isSome(current)
384 ? ([false, current] as const)
385 : ([true, Option.some(error)] as const),
386 );
387 if (!firstTermination) {
388 return;
389 }
390 yield* closeActiveAssistantSegment({ queue: eventQueue, assistantSegmentRef });
391 yield* Queue.offer(eventQueue, { _tag: "ConnectionTerminated", error });
392 });
393
394 const logRequest = (event: AcpSessionRequestLogEvent) =>
395 options.requestLogger ? options.requestLogger(event) : Effect.void;
396
397 const runLoggedRequest = <A>(
398 method: string,
399 payload: unknown,
400 effect: Effect.Effect<A, EffectAcpErrors.AcpError>,
401 ): Effect.Effect<A, EffectAcpErrors.AcpError> =>
402 logRequest({ method, payload, status: "started" }).pipe(
403 Effect.flatMap(() =>
404 (options.onStderr
405 ? Effect.raceFirst(effect, Deferred.await(stderrFailure))
406 : effect
407 ).pipe(
408 Effect.tap((result) =>
409 logRequest({
410 method,
411 payload,
412 status: "succeeded",
413 result,
414 }),
415 ),
416 Effect.onError((cause) =>
417 logRequest({
418 method,
419 payload,
420 status: "failed",
421 cause,
422 }),
423 ),
424 ),
425 ),
426 );
427
428 const spawnCommand = yield* resolveSpawnCommand(options.spawn.command, options.spawn.args, {
429 ...(options.spawn.env ? { env: options.spawn.env } : {}),
430 extendEnv: options.spawn.extendEnv ?? true,
431 });
432 const child = yield* spawner
433 .spawn(
434 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
435 ...(options.spawn.cwd ? { cwd: options.spawn.cwd } : {}),
436 ...(options.spawn.env ? { env: options.spawn.env } : {}),
437 extendEnv: options.spawn.extendEnv ?? true,
438 shell: spawnCommand.shell,
439 }),
440 )
441 .pipe(
442 Effect.provideService(Scope.Scope, runtimeScope),
443 Effect.mapError(
444 (cause) =>
445 new EffectAcpErrors.AcpSpawnError({
446 command: options.spawn.command,
447 cause,
448 }),
449 ),
450 );
451
452 yield* child.stderr.pipe(
453 Stream.decodeText(),
454 Stream.runForEach((chunk) =>
455 (options.onStderr
456 ? options.onStderr(chunk.slice(-maxStderrChunkLength))
457 : Effect.void
458 ).pipe(
459 Effect.catch((error) =>
460 Effect.gen(function* () {
461 yield* Deferred.fail(stderrFailure, error);
462 yield* recordTermination(error);
463 yield* child.kill({ forceKillAfter: "1 second" }).pipe(Effect.ignore);
464 }),
465 ),
466 ),
467 ),
468 Effect.ignore,
469 Effect.forkIn(runtimeScope),
470 );
471
472 const acpContext = yield* Layer.build(
473 EffectAcpClient.layerChildProcess(child, {
474 ...(options.transformStdout ? { transformStdout: options.transformStdout } : {}),
475 ...(options.transformSessionUpdate
476 ? { transformSessionUpdate: options.transformSessionUpdate }
477 : {}),
478 onTermination: recordTermination,
479 ...(options.protocolLogging?.logIncoming !== undefined
480 ? { logIncoming: options.protocolLogging.logIncoming }
481 : {}),
482 ...(options.protocolLogging?.logOutgoing !== undefined
483 ? { logOutgoing: options.protocolLogging.logOutgoing }
484 : {}),
485 ...(options.protocolLogging?.logger ? { logger: options.protocolLogging.logger } : {}),
486 }),
487 ).pipe(Effect.provideService(Scope.Scope, runtimeScope));
488
489 const acp = yield* Effect.service(EffectAcpClient.AcpClient).pipe(Effect.provide(acpContext));
490
491 const processSessionUpdate = (notification: EffectAcpSchema.SessionNotification) =>
492 handleSessionUpdate({
493 queue: eventQueue,
494 modeStateRef,
495 configOptionsRef,
496 toolCallsRef,
497 assistantSegmentRef,
498 assistantItemRuntimeId,
499 params: notification,
500 });
501
502 yield* acp.handleSessionUpdate((notification) =>
503 notificationSemaphore.withPermit(
504 Effect.gen(function* () {
505 if (Option.isSome(yield* Ref.get(terminationErrorRef))) {
506 return;
507 }
508 const gate = yield* Ref.get(sessionLoadGateRef);
509 if (
510 Option.isSome(gate) &&
511 gate.value.active &&
512 notification.sessionId === options.resumeSessionId
513 ) {
514 const lastActivityAtMillis = yield* Clock.currentTimeMillis;
515 yield* Ref.set(
516 sessionLoadGateRef,
517 Option.some({
518 ...gate.value,
519 lastActivityAtMillis,
520 }),
521 );
522 }
523 if (sessionUpdateIsReplay(notification)) {
524 return;
525 }
526 const startState = yield* Ref.get(startStateRef);
527 if (startState._tag === "Starting") {
528 if (isStartupMetadataUpdate(notification)) {
529 yield* Ref.update(startupMetadataRef, (current) =>
530 [
531 ...current.filter(
532 (previous) =>
533 previous.sessionId !== notification.sessionId ||
534 previous.update.sessionUpdate !== notification.update.sessionUpdate,
535 ),
536 notification,
537 ].slice(-maxStartupMetadataUpdates),
538 );
539 }
540 return;
541 }
542 // One runtime projects one root ACP session. Child-session updates need
543 // explicit lineage routing and must never be flattened into this stream.
544 if (
545 startState._tag !== "Started" ||
546 notification.sessionId !== startState.result.sessionId
547 ) {
548 return;
549 }
550 yield* processSessionUpdate(notification);
551 }),
552 ),
553 );
554 yield* Scope.addFinalizer(
555 runtimeScope,
556 Ref.set(stoppingRef, true).pipe(Effect.andThen(Deferred.succeed(runtimeClosed, undefined))),
557 );
558 const initializeClientCapabilities = {
559 fs: {
560 readTextFile: false,
561 writeTextFile: false,
562 ...options.clientCapabilities?.fs,
563 },
564 terminal: options.clientCapabilities?.terminal ?? false,
565 ...(options.clientCapabilities?.auth ? { auth: options.clientCapabilities.auth } : {}),
566 ...(options.clientCapabilities?.elicitation
567 ? { elicitation: options.clientCapabilities.elicitation }
568 : {}),
569 ...(options.clientCapabilities?._meta ? { _meta: options.clientCapabilities._meta } : {}),
570 } satisfies NonNullable<EffectAcpSchema.InitializeRequest["clientCapabilities"]>;
571
572 const getStartedState = Effect.gen(function* () {
573 yield* ensureConnected;
574 const state = yield* Ref.get(startStateRef);
575 if (state._tag === "Started") {
576 return state.result;
577 }
578 return yield* new EffectAcpErrors.AcpTransportError({
579 detail: "ACP session runtime has not been started",
580 cause: "ACP session runtime has not been started",
581 });
582 });
583
584 const validateConfigOptionValue = (
585 configId: string,
586 value: string | boolean,
587 ): Effect.Effect<void, EffectAcpErrors.AcpError> =>
588 Effect.gen(function* () {
589 const configOption = findSessionConfigOption(yield* Ref.get(configOptionsRef), configId);
590 if (!configOption) {
591 return;
592 }
593 if (configOption.type === "boolean") {
594 if (typeof value === "boolean") {
595 return;
596 }
597 return yield* new EffectAcpErrors.AcpRequestError({
598 code: -32602,
599 errorMessage: `Invalid value ${formatConfigOptionValue(value)} for session config option "${configOption.id}": expected boolean`,
600 data: {
601 configId: configOption.id,
602 expectedType: "boolean",
603 receivedValue: value,
604 },
605 });
606 }
607 if (typeof value !== "string") {
608 return yield* new EffectAcpErrors.AcpRequestError({
609 code: -32602,
610 errorMessage: `Invalid value ${formatConfigOptionValue(value)} for session config option "${configOption.id}": expected string`,
611 data: {
612 configId: configOption.id,
613 expectedType: "string",
614 receivedValue: value,
615 },
616 });
617 }
618 const allowedValues = collectSessionConfigOptionValues(configOption);
619 if (allowedValues.includes(value)) {
620 return;
621 }
622 return yield* new EffectAcpErrors.AcpRequestError({
623 code: -32602,
624 errorMessage: `Invalid value ${formatConfigOptionValue(value)} for session config option "${configOption.id}": expected one of ${allowedValues.join(", ")}`,
625 data: {
626 configId: configOption.id,
627 allowedValues,
628 receivedValue: value,
629 },
630 });
631 });
632
633 const updateConfigOptions = Effect.fn("AcpSessionRuntime.updateConfigOptions")(function* (
634 response: EffectAcpSchema.SetSessionConfigOptionResponse,
635 ) {
636 const configOptions = sessionConfigOptionsFromSetup(response);
637 yield* Ref.set(configOptionsRef, configOptions);
638 yield* Queue.offer(eventQueue, {
639 _tag: "ConfigOptionsUpdated",
640 configOptions,
641 rawPayload: response,
642 });
643 });
644
645 const updateCurrentModeId = (modeId: string): Effect.Effect<void> =>
646 Ref.update(modeStateRef, (current) =>
647 current ? { ...current, currentModeId: modeId } : current,
648 );
649
650 const setConfigOption = (
651 configId: string,
652 value: string | boolean,
653 ): Effect.Effect<EffectAcpSchema.SetSessionConfigOptionResponse, EffectAcpErrors.AcpError> =>
654 validateConfigOptionValue(configId, value).pipe(
655 Effect.flatMap(() => getStartedState),
656 Effect.flatMap((started) =>
657 Ref.get(configOptionsRef).pipe(
658 Effect.flatMap((configOptions) => {
659 const existing = findSessionConfigOption(configOptions, configId);
660 if (existing && configOptionCurrentValueMatches(existing, value)) {
661 return Effect.succeed({
662 configOptions,
663 } satisfies EffectAcpSchema.SetSessionConfigOptionResponse);
664 }
665 const requestPayload =
666 typeof value === "boolean"
667 ? ({
668 sessionId: started.sessionId,
669 configId,
670 type: "boolean",
671 value,
672 } satisfies EffectAcpSchema.SetSessionConfigOptionRequest)
673 : ({
674 sessionId: started.sessionId,
675 configId,
676 value: String(value),
677 } satisfies EffectAcpSchema.SetSessionConfigOptionRequest);
678 return runLoggedRequest(
679 "session/set_config_option",
680 requestPayload,
681 acp.agent.setSessionConfigOption(requestPayload),
682 ).pipe(Effect.tap((response) => updateConfigOptions(response)));
683 }),
684 ),
685 ),
686 );
687
688 const initializePayload = {
689 protocolVersion: 1,
690 clientCapabilities: initializeClientCapabilities,
691 clientInfo: options.clientInfo,
692 } satisfies EffectAcpSchema.InitializeRequest;
693 const sendInitialize = runLoggedRequest(
694 "initialize",
695 initializePayload,
696 acp.agent.initialize(initializePayload),
697 );
698
699 const startOnce = Effect.gen(function* () {
700 const initializeResult = yield* sendInitialize;
701
702 const authenticatePayload = {
703 methodId: options.authMethodId,
704 } satisfies EffectAcpSchema.AuthenticateRequest;
705
706 yield* runLoggedRequest(
707 "authenticate",
708 authenticatePayload,
709 acp.agent.authenticate(authenticatePayload),
710 );
711
712 let sessionId: string;
713 let sessionSetupResult:
714 | EffectAcpSchema.LoadSessionResponse
715 | EffectAcpSchema.NewSessionResponse
716 | EffectAcpSchema.ResumeSessionResponse;
717 if (options.resumeSessionId && options.resumeMethod === "resume") {
718 if (!initializeResult.agentCapabilities?.sessionCapabilities?.resume) {
719 return yield* new EffectAcpErrors.AcpTransportError({
720 method: "session/resume",
721 detail: "The ACP agent does not support session/resume.",
722 cause: undefined,
723 });
724 }
725 const resumePayload = {
726 sessionId: options.resumeSessionId,
727 cwd: options.cwd,
728 mcpServers: options.mcpServers ?? [],
729 ...(options.additionalDirectories && options.additionalDirectories.length > 0
730 ? { additionalDirectories: options.additionalDirectories }
731 : {}),
732 } satisfies EffectAcpSchema.ResumeSessionRequest;
733 sessionId = options.resumeSessionId;
734 sessionSetupResult = yield* runLoggedRequest(
735 "session/resume",
736 resumePayload,
737 acp.agent.resumeSession(resumePayload).pipe(
738 Effect.timeoutOption(options.sessionLoadTimeout ?? defaultSessionLoadTimeout),
739 Effect.flatMap((result) =>
740 Option.isSome(result)
741 ? Effect.succeed(result.value)
742 : Effect.fail(
743 new EffectAcpErrors.AcpTransportError({
744 operation: "call-rpc",
745 method: "session/resume",
746 detail: "session/resume timed out waiting for the agent response.",
747 cause: undefined,
748 }),
749 ),
750 ),
751 ),
752 );
753 } else if (options.resumeSessionId) {
754 const loadPayload = {
755 sessionId: options.resumeSessionId,
756 cwd: options.cwd,
757 mcpServers: options.mcpServers ?? [],
758 } satisfies EffectAcpSchema.LoadSessionRequest;
759 const sessionLoadTimeout = Duration.fromInputUnsafe(
760 options.sessionLoadTimeout ?? defaultSessionLoadTimeout,
761 );
762 const sessionLoadReplayIdleGap = Duration.fromInputUnsafe(
763 options.sessionLoadReplayIdleGap ?? defaultSessionLoadReplayIdleGap,
764 );
765
766 yield* Ref.set(
767 sessionLoadGateRef,
768 Option.some({
769 active: true,
770 lastActivityAtMillis: undefined,
771 idleGap: sessionLoadReplayIdleGap,
772 initializeResult,
773 }),
774 );
775
776 sessionId = options.resumeSessionId;
777 sessionSetupResult = yield* Effect.gen(function* () {
778 yield* logRequest({
779 method: "session/load",
780 payload: loadPayload,
781 status: "started",
782 });
783
784 const idleFiber = yield* waitForSessionLoadReplayIdle({
785 gateRef: sessionLoadGateRef,
786 }).pipe(Effect.forkIn(runtimeScope));
787 const loaded = yield* Effect.raceFirst(
788 acp.agent.loadSession(loadPayload),
789 Fiber.join(idleFiber),
790 ).pipe(
791 Effect.ensuring(Fiber.interrupt(idleFiber).pipe(Effect.ignore)),
792 Effect.timeoutOption(sessionLoadTimeout),
793 Effect.flatMap((result) =>
794 Option.match(result, {
795 onNone: () =>
796 Effect.fail(
797 new EffectAcpErrors.AcpTransportError({
798 operation: "call-rpc",
799 method: "session/load",
800 detail: "session/load timed out waiting for RPC response or replay idle gap",
801 cause: undefined,
802 }),
803 ),
804 onSome: Effect.succeed,
805 }),
806 ),
807 Effect.tap((result) =>
808 logRequest({
809 method: "session/load",
810 payload: loadPayload,
811 status: "succeeded",
812 result,
813 }),
814 ),
815 Effect.onError((cause) =>
816 logRequest({
817 method: "session/load",
818 payload: loadPayload,
819 status: "failed",
820 cause,
821 }),
822 ),
823 );
824
825 return loaded;
826 }).pipe(Effect.ensuring(Ref.set(sessionLoadGateRef, Option.none())));
827 } else {
828 const createPayload = {
829 cwd: options.cwd,
830 mcpServers: options.mcpServers ?? [],
831 ...(options.additionalDirectories && options.additionalDirectories.length > 0
832 ? { additionalDirectories: options.additionalDirectories }
833 : {}),
834 } satisfies EffectAcpSchema.NewSessionRequest;
835 const created = yield* runLoggedRequest(
836 "session/new",
837 createPayload,
838 acp.agent.createSession(createPayload),
839 );
840 sessionId = created.sessionId;
841 sessionSetupResult = created;
842 }
843
844 yield* Ref.set(modeStateRef, parseSessionModeState(sessionSetupResult));
845 yield* Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(sessionSetupResult));
846
847 const nextState = {
848 sessionId,
849 initializeResult,
850 sessionSetupResult,
851 modelConfigId: extractModelConfigId(sessionSetupResult),
852 } satisfies AcpStartedState;
853 return nextState;
854 });
855
856 const start = Effect.gen(function* () {
857 yield* ensureConnected;
858 const deferred = yield* Deferred.make<
859 AcpSessionRuntimeStartResult,
860 EffectAcpErrors.AcpError
861 >();
862 const effect = yield* Ref.modify(startStateRef, (state) => {
863 switch (state._tag) {
864 case "Started":
865 return [Effect.succeed(state.result), state] as const;
866 case "Starting":
867 return [Deferred.await(state.deferred), state] as const;
868 case "NotStarted":
869 return [
870 startOnce.pipe(
871 Effect.tap((result) =>
872 notificationSemaphore.withPermit(
873 Effect.gen(function* () {
874 const error = yield* Ref.get(terminationErrorRef);
875 if (Option.isSome(error)) {
876 return yield* error.value;
877 }
878 yield* Ref.set(startStateRef, { _tag: "Started", result });
879 const metadata = yield* Ref.getAndSet(startupMetadataRef, []);
880 for (const notification of metadata) {
881 if (notification.sessionId === result.sessionId) {
882 yield* processSessionUpdate(notification);
883 }
884 }
885 yield* Deferred.succeed(deferred, result);
886 }),
887 ),
888 ),
889 Effect.onError((cause) =>
890 Deferred.failCause(deferred, cause).pipe(
891 Effect.andThen(Ref.set(startStateRef, { _tag: "NotStarted" })),
892 Effect.andThen(Ref.set(startupMetadataRef, [])),
893 ),
894 ),
895 ),
896 { _tag: "Starting", deferred } satisfies AcpStartState,
897 ] as const;
898 }
899 });
900 return yield* effect;
901 });
902
903 const drainEvents = Effect.gen(function* () {
904 if (yield* Ref.get(stoppingRef)) {
905 return;
906 }
907 const acknowledge = yield* Deferred.make<void>();
908 yield* Queue.offer(eventQueue, { _tag: "EventStreamBarrier", acknowledge });
909 yield* Effect.raceFirst(Deferred.await(acknowledge), Deferred.await(runtimeClosed));
910 });
911
912 const retireRuntime = Effect.fn("AcpSessionRuntime.retireRuntime")(function* (
913 error: EffectAcpErrors.AcpError,
914 ) {
915 yield* recordTermination(error);
916 yield* child.kill({ forceKillAfter: "1 second" }).pipe(Effect.ignore);
917 });
918
919 const cancel = Effect.gen(function* () {
920 const started = yield* getStartedState;
921 const activePrompt = yield* Ref.get(activePromptRef);
922 if (options.cancelBehavior !== "wait-for-prompt") {
923 if (Option.isSome(activePrompt)) {
924 yield* Fiber.interrupt(activePrompt.value.fiber).pipe(Effect.ignore);
925 }
926 // Write cancel before a replacement prompt can reach the agent.
927 yield* acp.agent.cancel({ sessionId: started.sessionId }).pipe(Effect.ignore);
928 return;
929 }
930
931 yield* acp.agent.cancel({ sessionId: started.sessionId });
932 if (Option.isNone(activePrompt)) {
933 return;
934 }
935 const completed = yield* Effect.gen(function* () {
936 const result = yield* Fiber.await(activePrompt.value.fiber);
937 yield* Deferred.await(activePrompt.value.completed);
938 if (Option.isNone(yield* Ref.get(terminationErrorRef))) {
939 yield* drainEvents;
940 }
941 return result;
942 }).pipe(Effect.timeoutOption(options.cancelTimeout ?? defaultCancelTimeout));
943 if (Option.isNone(completed)) {
944 const error = new EffectAcpErrors.AcpTransportError({
945 operation: "call-rpc",
946 method: "session/cancel",
947 detail: "The ACP agent did not finish cancellation. Its process was stopped.",
948 cause: undefined,
949 });
950 yield* retireRuntime(error);
951 return yield* error;
952 }
953 if (Exit.isFailure(completed.value)) {
954 return yield* Effect.failCause(completed.value.cause);
955 }
956 });
957
958 return {
959 handleRequestPermission: acp.handleRequestPermission,
960 handleElicitation: acp.handleElicitation,
961 handleReadTextFile: acp.handleReadTextFile,
962 handleWriteTextFile: acp.handleWriteTextFile,
963 handleCreateTerminal: acp.handleCreateTerminal,
964 handleTerminalOutput: acp.handleTerminalOutput,
965 handleTerminalWaitForExit: acp.handleTerminalWaitForExit,
966 handleTerminalKill: acp.handleTerminalKill,
967 handleTerminalRelease: acp.handleTerminalRelease,
968 handleSessionUpdate: acp.handleSessionUpdate,
969 handleElicitationComplete: acp.handleElicitationComplete,
970 handleUnknownExtRequest: acp.handleUnknownExtRequest,
971 handleUnknownExtNotification: acp.handleUnknownExtNotification,
972 handleExtRequest: acp.handleExtRequest,
973 handleExtNotification: acp.handleExtNotification,
974 initialize: () => ensureConnected.pipe(Effect.andThen(sendInitialize)),
975 start: () => start,
976 getEvents: () => Stream.fromQueue(eventQueue),
977 drainEvents,
978 getModeState: Ref.get(modeStateRef),
979 getConfigOptions: Ref.get(configOptionsRef),
980 prompt: (payload, promptOptions?) =>
981 promptSerializationSemaphore.withPermit(
982 Effect.acquireUseRelease(
983 promptDispatchSemaphore.withPermit(
984 Effect.gen(function* () {
985 const started = yield* getStartedState;
986 yield* closeActiveAssistantSegment({ queue: eventQueue, assistantSegmentRef });
987 const requestPayload = {
988 sessionId: started.sessionId,
989 ...payload,
990 } satisfies EffectAcpSchema.PromptRequest;
991 const completed = yield* Deferred.make<void>();
992 const fiber = yield* runLoggedRequest(
993 "session/prompt",
994 requestPayload,
995 acp.agent.prompt(requestPayload),
996 ).pipe(Effect.forkIn(runtimeScope));
997 const active = { fiber, completed } satisfies AcpActivePrompt;
998 yield* Ref.set(activePromptRef, Option.some(active));
999 if (promptOptions?.dispatched) {
1000 yield* Deferred.succeed(promptOptions.dispatched, undefined);
1001 }
1002 return active;
1003 }),
1004 ),
1005 (activePrompt) =>
1006 Fiber.join(activePrompt.fiber).pipe(
1007 Effect.catchCause((cause) =>
1008 options.cancelBehavior !== "wait-for-prompt" && Cause.hasInterruptsOnly(cause)
1009 ? Effect.succeed({
1010 stopReason: "cancelled",
1011 } satisfies EffectAcpSchema.PromptResponse)
1012 : Effect.failCause(cause),
1013 ),
1014 Effect.tap(() =>
1015 closeActiveAssistantSegment({ queue: eventQueue, assistantSegmentRef }),
1016 ),
1017 ),
1018 (activePrompt, result) =>
1019 Effect.gen(function* () {
1020 if (
1021 options.cancelBehavior === "wait-for-prompt" &&
1022 Exit.isFailure(result) &&
1023 Cause.hasInterrupts(result.cause)
1024 ) {
1025 yield* retireRuntime(
1026 new EffectAcpErrors.AcpTransportError({
1027 method: "session/prompt",
1028 detail: "The ACP prompt stopped before the agent confirmed completion.",
1029 cause: undefined,
1030 }),
1031 );
1032 }
1033 yield* Fiber.interrupt(activePrompt.fiber).pipe(Effect.ignore);
1034 yield* Ref.set(activePromptRef, Option.none());
1035 yield* Deferred.succeed(activePrompt.completed, undefined);
1036 }),
1037 ),
1038 ),
1039 cancel:
1040 options.cancelBehavior === "wait-for-prompt"
1041 ? promptDispatchSemaphore.withPermit(cancel)
1042 : cancel,
1043 setMode: (modeId) =>
1044 Ref.get(modeStateRef).pipe(
1045 Effect.flatMap((modeState) => {
1046 if (modeState?.currentModeId === modeId) {
1047 return Effect.succeed({} satisfies EffectAcpSchema.SetSessionModeResponse);
1048 }
1049 return setConfigOption("mode", modeId).pipe(
1050 Effect.tap(() => updateCurrentModeId(modeId)),
1051 Effect.as({} satisfies EffectAcpSchema.SetSessionModeResponse),
1052 );
1053 }),
1054 ),
1055 setConfigOption,
1056 setModel: (model) =>
1057 getStartedState.pipe(
1058 Effect.flatMap((started) => setConfigOption(started.modelConfigId ?? "model", model)),
1059 Effect.asVoid,
1060 ),
1061 setSessionModel: (modelId, meta) =>
1062 getStartedState.pipe(
1063 Effect.flatMap((started) => {
1064 const requestPayload = {
1065 sessionId: started.sessionId,
1066 modelId,
1067 ...(meta !== undefined ? { _meta: meta } : {}),
1068 } satisfies EffectAcpSchema.SetSessionModelRequest;
1069 return runLoggedRequest(
1070 "session/set_model",
1071 requestPayload,
1072 acp.agent.setSessionModel(requestPayload),
1073 );
1074 }),
1075 ),
1076 request: (method, payload) =>
1077 ensureConnected.pipe(
1078 Effect.andThen(runLoggedRequest(method, payload, acp.raw.request(method, payload))),
1079 ),
1080 notify: (method, payload) =>
1081 ensureConnected.pipe(Effect.andThen(acp.raw.notify(method, payload))),
1082 } satisfies AcpSessionRuntime["Service"];
1083 });
1084
1085export const layer = (
1086 options: AcpSessionRuntimeOptions,
1087): Layer.Layer<
1088 AcpSessionRuntime,
1089 EffectAcpErrors.AcpError,
1090 ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto
1091> => Layer.effect(AcpSessionRuntime, make(options));
1092
1093function sessionConfigOptionsFromSetup(
1094 response:
1095 | {
1096 readonly configOptions?: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null;
1097 }
1098 | undefined,
1099): ReadonlyArray<EffectAcpSchema.SessionConfigOption> {
1100 return response?.configOptions ?? [];
1101}
1102
1103function configOptionCurrentValueMatches(
1104 configOption: EffectAcpSchema.SessionConfigOption,
1105 value: string | boolean,
1106): boolean {
1107 const currentValue = configOption.currentValue;
1108 if (configOption.type === "boolean") {
1109 return currentValue === value;
1110 }
1111 if (typeof currentValue !== "string") {
1112 return false;
1113 }
1114 return currentValue.trim() === String(value).trim();
1115}
1116
1117function isStartupMetadataUpdate(notification: EffectAcpSchema.SessionNotification): boolean {
1118 switch (notification.update.sessionUpdate) {
1119 case "current_mode_update":
1120 case "config_option_update":
1121 case "available_commands_update":
1122 return true;
1123 default:
1124 return false;
1125 }
1126}
1127
1128const handleSessionUpdate = ({
1129 queue,
1130 modeStateRef,
1131 configOptionsRef,
1132 toolCallsRef,
1133 assistantSegmentRef,
1134 assistantItemRuntimeId,
1135 params,
1136}: {
1137 readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;
1138 readonly modeStateRef: Ref.Ref<AcpSessionModeState | undefined>;
1139 readonly configOptionsRef: Ref.Ref<ReadonlyArray<EffectAcpSchema.SessionConfigOption>>;
1140 readonly toolCallsRef: Ref.Ref<Map<string, AcpToolCallTrackedState>>;
1141 readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
1142 readonly assistantItemRuntimeId: string;
1143 readonly params: EffectAcpSchema.SessionNotification;
1144}): Effect.Effect<void> =>
1145 Effect.gen(function* () {
1146 if (params.update.sessionUpdate === "config_option_update") {
1147 yield* Ref.set(configOptionsRef, params.update.configOptions);
1148 }
1149 const parsed = parseSessionUpdateEvent(params);
1150 if (parsed.modeId) {
1151 yield* Ref.update(modeStateRef, (current) =>
1152 current === undefined ? current : updateModeState(current, parsed.modeId!),
1153 );
1154 }
1155 for (const event of parsed.events) {
1156 if (event._tag === "ToolCallUpdated") {
1157 yield* closeActiveAssistantSegment({
1158 queue,
1159 assistantSegmentRef,
1160 });
1161 const { merged, decision } = yield* Ref.modify(toolCallsRef, (current) => {
1162 const tracked = current.get(event.toolCall.toolCallId);
1163 const previous = tracked?.state;
1164 const nextToolCall = mergeToolCallState(previous, event.toolCall);
1165 const decision = decideToolCallUpdateEmission({
1166 previous,
1167 next: nextToolCall,
1168 lastEmittedDetailLength: tracked?.lastEmittedDetailLength,
1169 skippedSinceEmit: tracked?.skippedSinceEmit ?? 0,
1170 });
1171 const next = new Map(current);
1172 if (nextToolCall.status === "completed" || nextToolCall.status === "failed") {
1173 next.delete(nextToolCall.toolCallId);
1174 } else {
1175 next.set(nextToolCall.toolCallId, {
1176 state: nextToolCall,
1177 lastEmittedDetailLength: decision.emit
1178 ? toolCallProgressLength(nextToolCall)
1179 : tracked?.lastEmittedDetailLength,
1180 skippedSinceEmit: decision.skippedSinceEmit,
1181 });
1182 }
1183 return [{ merged: nextToolCall, decision }, next] as const;
1184 });
1185 if (!decision.emit) {
1186 continue;
1187 }
1188 yield* Queue.offer(queue, {
1189 _tag: "ToolCallUpdated",
1190 toolCall: merged,
1191 rawPayload: event.rawPayload,
1192 });
1193 continue;
1194 }
1195 if (event._tag === "ContentDelta") {
1196 if (event.text.trim().length === 0) {
1197 const assistantSegmentState = yield* Ref.get(assistantSegmentRef);
1198 if (!assistantSegmentState.activeItemId) {
1199 continue;
1200 }
1201 }
1202 const itemId = yield* ensureActiveAssistantSegment({
1203 queue,
1204 assistantSegmentRef,
1205 sessionId: params.sessionId,
1206 assistantItemRuntimeId,
1207 });
1208 yield* Queue.offer(queue, {
1209 ...event,
1210 itemId,
1211 });
1212 continue;
1213 }
1214 yield* Queue.offer(queue, event);
1215 }
1216 });
1217
1218function updateModeState(modeState: AcpSessionModeState, nextModeId: string): AcpSessionModeState {
1219 const normalized = nextModeId.trim();
1220 if (!normalized) {
1221 return modeState;
1222 }
1223 return modeState.availableModes.some((mode) => mode.id === normalized)
1224 ? {
1225 ...modeState,
1226 currentModeId: normalized,
1227 }
1228 : modeState;
1229}
1230
1231const assistantItemId = (sessionId: string, runtimeId: string, segmentIndex: number) =>
1232 `assistant:${sessionId}:runtime:${runtimeId}:segment:${segmentIndex}`;
1233
1234const ensureActiveAssistantSegment = ({
1235 queue,
1236 assistantSegmentRef,
1237 sessionId,
1238 assistantItemRuntimeId,
1239}: {
1240 readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;
1241 readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
1242 readonly sessionId: string;
1243 readonly assistantItemRuntimeId: string;
1244}) =>
1245 Ref.modify<AcpAssistantSegmentState, EnsureActiveAssistantSegmentResult>(
1246 assistantSegmentRef,
1247 (current) => {
1248 if (current.activeItemId) {
1249 return [{ itemId: current.activeItemId }, current] as const;
1250 }
1251 const itemId = assistantItemId(sessionId, assistantItemRuntimeId, current.nextSegmentIndex);
1252 return [
1253 {
1254 itemId,
1255 startedEvent: {
1256 _tag: "AssistantItemStarted",
1257 itemId,
1258 } satisfies Extract<AcpParsedSessionEvent, { readonly _tag: "AssistantItemStarted" }>,
1259 },
1260 {
1261 nextSegmentIndex: current.nextSegmentIndex + 1,
1262 activeItemId: itemId,
1263 } satisfies AcpAssistantSegmentState,
1264 ] as const;
1265 },
1266 ).pipe(
1267 Effect.flatMap((result) =>
1268 result.startedEvent
1269 ? Queue.offer(queue, result.startedEvent).pipe(Effect.as(result.itemId))
1270 : Effect.succeed(result.itemId),
1271 ),
1272 );
1273
1274const closeActiveAssistantSegment = ({
1275 queue,
1276 assistantSegmentRef,
1277}: {
1278 readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;
1279 readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
1280}) =>
1281 Ref.modify(assistantSegmentRef, (current) => {
1282 if (!current.activeItemId) {
1283 return [undefined, current] as const;
1284 }
1285 return [
1286 {
1287 _tag: "AssistantItemCompleted",
1288 itemId: current.activeItemId,
1289 } satisfies AcpParsedSessionEvent,
1290 {
1291 nextSegmentIndex: current.nextSegmentIndex,
1292 } satisfies AcpAssistantSegmentState,
1293 ] as const;
1294 }).pipe(Effect.flatMap((event) => (event ? Queue.offer(queue, event) : Effect.void)));