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

AcpSessionRuntime.ts

1,033 lines38.5 KB

1import * as Cause from "effect/Cause";
2import * as Clock from "effect/Clock";
3import * as Context from "effect/Context";
4import * as Crypto from "effect/Crypto";
5import * as Deferred from "effect/Deferred";
6import * as Duration from "effect/Duration";
7import * as Effect from "effect/Effect";
8import * as Fiber from "effect/Fiber";
9import * as Layer from "effect/Layer";
10import * as Option from "effect/Option";
11import * as Queue from "effect/Queue";
12import * as Ref from "effect/Ref";
13import * as Scope from "effect/Scope";
14import * as Semaphore from "effect/Semaphore";
15import * as Stream from "effect/Stream";
16import * as ChildProcess from "effect/unstable/process/ChildProcess";
17import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
18import * as EffectAcpClient from "effect-acp/client";
19import * as EffectAcpErrors from "effect-acp/errors";
20import type * as EffectAcpSchema from "effect-acp/schema";
21import type * as EffectAcpProtocol from "effect-acp/protocol";
22import { resolveSpawnCommand } from "@t3tools/shared/shell";
23​
24import {
25 collectSessionConfigOptionValues,
26 decideToolCallUpdateEmission,
27 extractModelConfigId,
28 findSessionConfigOption,
29 mergeToolCallState,
30 toolCallProgressLength,
31 parseSessionModeState,
32 parseSessionUpdateEvent,
33 sessionUpdateIsReplay,
34 waitForSessionLoadReplayIdle,
35 type SessionLoadGate,
36 type AcpParsedSessionEvent,
37 type AcpSessionModeState,
38 type AcpToolCallState,
39} from "./AcpRuntimeModel.ts";
40​
41interface AcpToolCallTrackedState {
42 readonly state: AcpToolCallState;
43 readonly lastEmittedDetailLength: number | undefined;
44 readonly skippedSinceEmit: number;
46​
47function formatConfigOptionValue(value: string | boolean): string {
48 return JSON.stringify(value);
50​
51export interface AcpSessionEventStreamBarrier {
52 readonly _tag: "EventStreamBarrier";
53 readonly acknowledge: Deferred.Deferred<void>;
55​
56export type AcpSessionRuntimeEvent = AcpParsedSessionEvent | AcpSessionEventStreamBarrier;
57​
58const defaultSessionLoadTimeout = Duration.seconds(90);
59const defaultSessionLoadReplayIdleGap = Duration.seconds(2);
60​
61export interface AcpSpawnInput {
62 readonly command: string;
63 readonly args: ReadonlyArray<string>;
64 readonly cwd?: string;
65 readonly env?: NodeJS.ProcessEnv;
67​
68export interface AcpSessionRuntimeOptions {
69 readonly spawn: AcpSpawnInput;
70 readonly cwd: string;
71 readonly resumeSessionId?: string;
72 readonly sessionLoadTimeout?: Duration.Input;
73 readonly sessionLoadReplayIdleGap?: Duration.Input;
74 readonly clientCapabilities?: EffectAcpSchema.InitializeRequest["clientCapabilities"];
75 readonly clientInfo: {
76 readonly name: string;
77 readonly version: string;
78 };
79 readonly authMethodId: string;
80 readonly mcpServers?: ReadonlyArray<EffectAcpSchema.McpServer>;
81 readonly requestLogger?: (event: AcpSessionRequestLogEvent) => Effect.Effect<void, never>;
82 readonly protocolLogging?: {
83 readonly logIncoming?: boolean;
84 readonly logOutgoing?: boolean;
85 readonly logger?: (event: EffectAcpProtocol.AcpProtocolLogEvent) => Effect.Effect<void, never>;
86 };
88​
89export interface AcpSessionRequestLogEvent {
90 readonly method: string;
91 readonly payload: unknown;
92 readonly status: "started" | "succeeded" | "failed";
93 readonly result?: unknown;
94 readonly cause?: Cause.Cause<EffectAcpErrors.AcpError>;
96​
97export interface AcpSessionRuntimeStartResult {
98 readonly sessionId: string;
99 readonly initializeResult: EffectAcpSchema.InitializeResponse;
100 readonly sessionSetupResult:
101 | EffectAcpSchema.LoadSessionResponse
102 | EffectAcpSchema.NewSessionResponse
103 | EffectAcpSchema.ResumeSessionResponse;
104 readonly modelConfigId: string | undefined;
106​
107export class AcpSessionRuntime extends Context.Service<
108 AcpSessionRuntime,
109 {
110 /**
111 * Registers a handler for `session/request_permission`.
112 * @see https://agentclientprotocol.com/protocol/schema#session/request_permission
113 */
114 readonly handleRequestPermission: EffectAcpClient.AcpClient["Service"]["handleRequestPermission"];
115 /**
116 * Registers a handler for `session/elicitation`.
117 * @see https://agentclientprotocol.com/protocol/schema#session/elicitation
118 */
119 readonly handleElicitation: EffectAcpClient.AcpClient["Service"]["handleElicitation"];
120 /**
121 * Registers a handler for `fs/read_text_file`.
122 * @see https://agentclientprotocol.com/protocol/schema#fs/read_text_file
123 */
124 readonly handleReadTextFile: EffectAcpClient.AcpClient["Service"]["handleReadTextFile"];
125 /**
126 * Registers a handler for `fs/write_text_file`.
127 * @see https://agentclientprotocol.com/protocol/schema#fs/write_text_file
128 */
129 readonly handleWriteTextFile: EffectAcpClient.AcpClient["Service"]["handleWriteTextFile"];
130 /**
131 * Registers a handler for `terminal/create`.
132 * @see https://agentclientprotocol.com/protocol/schema#terminal/create
133 */
134 readonly handleCreateTerminal: EffectAcpClient.AcpClient["Service"]["handleCreateTerminal"];
135 /**
136 * Registers a handler for `terminal/output`.
137 * @see https://agentclientprotocol.com/protocol/schema#terminal/output
138 */
139 readonly handleTerminalOutput: EffectAcpClient.AcpClient["Service"]["handleTerminalOutput"];
140 /**
141 * Registers a handler for `terminal/wait_for_exit`.
142 * @see https://agentclientprotocol.com/protocol/schema#terminal/wait_for_exit
143 */
144 readonly handleTerminalWaitForExit: EffectAcpClient.AcpClient["Service"]["handleTerminalWaitForExit"];
145 /**
146 * Registers a handler for `terminal/kill`.
147 * @see https://agentclientprotocol.com/protocol/schema#terminal/kill
148 */
149 readonly handleTerminalKill: EffectAcpClient.AcpClient["Service"]["handleTerminalKill"];
150 /**
151 * Registers a handler for `terminal/release`.
152 * @see https://agentclientprotocol.com/protocol/schema#terminal/release
153 */
154 readonly handleTerminalRelease: EffectAcpClient.AcpClient["Service"]["handleTerminalRelease"];
155 /**
156 * Registers a handler for `session/update`.
157 * @see https://agentclientprotocol.com/protocol/schema#session/update
158 */
159 readonly handleSessionUpdate: EffectAcpClient.AcpClient["Service"]["handleSessionUpdate"];
160 /**
161 * Registers a handler for `session/elicitation/complete`.
162 * @see https://agentclientprotocol.com/protocol/schema#session/elicitation/complete
163 */
164 readonly handleElicitationComplete: EffectAcpClient.AcpClient["Service"]["handleElicitationComplete"];
165 /**
166 * Registers a fallback extension request handler.
167 * @see https://agentclientprotocol.com/protocol/extensibility
168 */
169 readonly handleUnknownExtRequest: EffectAcpClient.AcpClient["Service"]["handleUnknownExtRequest"];
170 /**
171 * Registers a fallback extension notification handler.
172 * @see https://agentclientprotocol.com/protocol/extensibility
173 */
174 readonly handleUnknownExtNotification: EffectAcpClient.AcpClient["Service"]["handleUnknownExtNotification"];
175 /**
176 * Registers a typed extension request handler.
177 * @see https://agentclientprotocol.com/protocol/extensibility
178 */
179 readonly handleExtRequest: EffectAcpClient.AcpClient["Service"]["handleExtRequest"];
180 /**
181 * Registers a typed extension notification handler.
182 * @see https://agentclientprotocol.com/protocol/extensibility
183 */
184 readonly handleExtNotification: EffectAcpClient.AcpClient["Service"]["handleExtNotification"];
185 /**
186 * Sends only `initialize` and returns the agent's response. Health probes use this to read
187 * advertised capabilities without authenticating or opening a session, so a probe can never
188 * start an interactive login or boot MCP servers.
189 * @see https://agentclientprotocol.com/protocol/schema#initialize
190 */
191 readonly initialize: () => Effect.Effect<
192 EffectAcpSchema.InitializeResponse,
193 EffectAcpErrors.AcpError
194 >;
195 /**
196 * Initializes the ACP connection, authenticates, and loads, resumes, or creates the session.
197 * Concurrent calls share the same in-flight startup and a failed startup may be retried.
198 */
199 readonly start: () => Effect.Effect<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;
200 /** Stream of parsed ACP session events emitted after startup. */
201 readonly getEvents: () => Stream.Stream<AcpSessionRuntimeEvent, never>;
202 /** Waits until the current event consumer has processed every queued event. */
203 readonly drainEvents: Effect.Effect<void>;
204 /** Latest mode state observed from session setup and `session/update` notifications. */
205 readonly getModeState: Effect.Effect<AcpSessionModeState | undefined>;
206 /** Latest configuration options observed from session setup and configuration writes. */
207 readonly getConfigOptions: Effect.Effect<ReadonlyArray<EffectAcpSchema.SessionConfigOption>>;
208 /**
209 * Sends a prompt turn to the active session. `options.dispatched` settles once the
210 * `session/prompt` RPC is registered as the active prompt, so a caller that forks this
211 * effect knows when a later `cancel` will target this prompt.
212 * @see https://agentclientprotocol.com/protocol/schema#session/prompt
213 */
214 readonly prompt: (
215 payload: Omit<EffectAcpSchema.PromptRequest, "sessionId">,
216 options?: { readonly dispatched?: Deferred.Deferred<void> },
217 ) => Effect.Effect<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpError>;
218 /**
219 * Sends a real ACP `session/cancel` notification for the active session.
220 * @see https://agentclientprotocol.com/protocol/schema#session/cancel
221 */
222 readonly cancel: Effect.Effect<void, EffectAcpErrors.AcpError>;
223 /**
224 * Selects the active mode through the negotiated `mode` configuration option.
225 * This is a no-op when the requested mode is already active.
226 * @see https://agentclientprotocol.com/protocol/schema#session/set_config_option
227 */
228 readonly setMode: (
229 modeId: string,
230 ) => Effect.Effect<EffectAcpSchema.SetSessionModeResponse, EffectAcpErrors.AcpError>;
231 /**
232 * Updates a session configuration option and the runtime configuration snapshot.
233 * @see https://agentclientprotocol.com/protocol/schema#session/set_config_option
234 */
235 readonly setConfigOption: (
236 configId: string,
237 value: string | boolean,
238 ) => Effect.Effect<EffectAcpSchema.SetSessionConfigOptionResponse, EffectAcpErrors.AcpError>;
239 /**
240 * Selects the base model through the negotiated model configuration option.
241 * @see https://agentclientprotocol.com/protocol/schema#session/set_config_option
242 */
243 readonly setModel: (model: string) => Effect.Effect<void, EffectAcpErrors.AcpError>;
244 /**
245 * Selects the active model through the unstable ACP `session/set_model` capability.
246 * @see https://agentclientprotocol.com/protocol/schema#session/set_model
247 */
248 readonly setSessionModel: (
249 modelId: string,
250 meta?: EffectAcpSchema.SetSessionModelRequest["_meta"],
251 ) => Effect.Effect<EffectAcpSchema.SetSessionModelResponse, EffectAcpErrors.AcpError>;
252 /**
253 * Sends a generic ACP extension request and records it through the request logger.
254 * @see https://agentclientprotocol.com/protocol/extensibility
255 */
256 readonly request: (
257 method: string,
258 payload: unknown,
259 ) => Effect.Effect<unknown, EffectAcpErrors.AcpError>;
260 /**
261 * Sends a generic ACP extension notification.
262 * @see https://agentclientprotocol.com/protocol/extensibility
263 */
264 readonly notify: (
265 method: string,
266 payload: unknown,
267 ) => Effect.Effect<void, EffectAcpErrors.AcpError>;
268 }
269>()("t3/provider/acp/AcpSessionRuntime") {}
270​
271interface AcpStartedState extends AcpSessionRuntimeStartResult {}
272​
273type AcpStartState =
274 | { readonly _tag: "NotStarted" }
275 | {
276 readonly _tag: "Starting";
277 readonly deferred: Deferred.Deferred<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;
278 }
279 | { readonly _tag: "Started"; readonly result: AcpStartedState };
280​
281interface AcpAssistantSegmentState {
282 readonly nextSegmentIndex: number;
283 readonly activeItemId?: string;
285​
286interface EnsureActiveAssistantSegmentResult {
287 readonly itemId: string;
288 readonly startedEvent?: Extract<AcpParsedSessionEvent, { readonly _tag: "AssistantItemStarted" }>;
290​
291export const make = (
292 options: AcpSessionRuntimeOptions,
293): Effect.Effect<
294 AcpSessionRuntime["Service"],
295 EffectAcpErrors.AcpError,
296 ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | Scope.Scope
297> =>
298 Effect.gen(function* () {
299 const crypto = yield* Crypto.Crypto;
300 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
301 const runtimeScope = yield* Scope.Scope;
302 const eventQueue = yield* Queue.unbounded<AcpSessionRuntimeEvent>();
303 const modeStateRef = yield* Ref.make<AcpSessionModeState | undefined>(undefined);
304 const toolCallsRef = yield* Ref.make(new Map<string, AcpToolCallTrackedState>());
305 const assistantItemRuntimeId = yield* crypto.randomUUIDv4.pipe(
306 Effect.mapError(
307 (cause) =>
308 new EffectAcpErrors.AcpTransportError({
309 detail: "Failed to generate an ACP assistant item runtime identifier.",
310 cause,
311 }),
312 ),
313 );
314 const assistantSegmentRef = yield* Ref.make<AcpAssistantSegmentState>({ nextSegmentIndex: 0 });
315 const configOptionsRef = yield* Ref.make(sessionConfigOptionsFromSetup(undefined));
316 const startStateRef = yield* Ref.make<AcpStartState>({ _tag: "NotStarted" });
317 const promptSerializationSemaphore = yield* Semaphore.make(1);
318 const activePromptFiberRef = yield* Ref.make<
319 Option.Option<Fiber.Fiber<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpError>>
320 >(Option.none());
321 const sessionLoadGateRef = yield* Ref.make<Option.Option<SessionLoadGate>>(Option.none());
322​
323 const logRequest = (event: AcpSessionRequestLogEvent) =>
324 options.requestLogger ? options.requestLogger(event) : Effect.void;
325​
326 const runLoggedRequest = <A>(
327 method: string,
328 payload: unknown,
329 effect: Effect.Effect<A, EffectAcpErrors.AcpError>,
330 ): Effect.Effect<A, EffectAcpErrors.AcpError> =>
331 logRequest({ method, payload, status: "started" }).pipe(
332 Effect.flatMap(() =>
333 effect.pipe(
334 Effect.tap((result) =>
335 logRequest({
336 method,
337 payload,
338 status: "succeeded",
339 result,
340 }),
341 ),
342 Effect.onError((cause) =>
343 logRequest({
344 method,
345 payload,
346 status: "failed",
347 cause,
348 }),
349 ),
350 ),
351 ),
352 );
353​
354 const spawnCommand = yield* resolveSpawnCommand(
355 options.spawn.command,
356 options.spawn.args,
357 options.spawn.env ? { env: options.spawn.env, extendEnv: true } : {},
358 );
359 const child = yield* spawner
360 .spawn(
361 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
362 ...(options.spawn.cwd ? { cwd: options.spawn.cwd } : {}),
363 ...(options.spawn.env ? { env: options.spawn.env, extendEnv: true } : {}),
364 shell: spawnCommand.shell,
365 }),
366 )
367 .pipe(
368 Effect.provideService(Scope.Scope, runtimeScope),
369 Effect.mapError(
370 (cause) =>
371 new EffectAcpErrors.AcpSpawnError({
372 command: options.spawn.command,
373 cause,
374 }),
375 ),
376 );
377​
378 const acpContext = yield* Layer.build(
379 EffectAcpClient.layerChildProcess(child, {
380 ...(options.protocolLogging?.logIncoming !== undefined
381 ? { logIncoming: options.protocolLogging.logIncoming }
382 : {}),
383 ...(options.protocolLogging?.logOutgoing !== undefined
384 ? { logOutgoing: options.protocolLogging.logOutgoing }
385 : {}),
386 ...(options.protocolLogging?.logger ? { logger: options.protocolLogging.logger } : {}),
387 }),
388 ).pipe(Effect.provideService(Scope.Scope, runtimeScope));
389​
390 const acp = yield* Effect.service(EffectAcpClient.AcpClient).pipe(Effect.provide(acpContext));
391​
392 yield* acp.handleSessionUpdate((notification) =>
393 Effect.gen(function* () {
394 const gate = yield* Ref.get(sessionLoadGateRef);
395 if (Option.isSome(gate) && gate.value.active) {
396 const lastActivityAtMillis = yield* Clock.currentTimeMillis;
397 yield* Ref.set(
398 sessionLoadGateRef,
399 Option.some({
400 ...gate.value,
401 lastActivityAtMillis,
402 }),
403 );
404 return;
405 }
406 if (sessionUpdateIsReplay(notification)) {
407 return;
408 }
409 const startState = yield* Ref.get(startStateRef);
410 // One runtime projects one root ACP session. Child-session updates need
411 // explicit lineage routing and must never be flattened into this stream.
412 if (
413 startState._tag !== "Started" ||
414 notification.sessionId !== startState.result.sessionId
415 ) {
416 return;
417 }
418 yield* handleSessionUpdate({
419 queue: eventQueue,
420 modeStateRef,
421 toolCallsRef,
422 assistantSegmentRef,
423 assistantItemRuntimeId,
424 params: notification,
425 });
426 }),
427 );
428 const initializeClientCapabilities = {
429 fs: {
430 readTextFile: false,
431 writeTextFile: false,
432 ...options.clientCapabilities?.fs,
433 },
434 terminal: options.clientCapabilities?.terminal ?? false,
435 ...(options.clientCapabilities?.auth ? { auth: options.clientCapabilities.auth } : {}),
436 ...(options.clientCapabilities?.elicitation
437 ? { elicitation: options.clientCapabilities.elicitation }
438 : {}),
439 ...(options.clientCapabilities?._meta ? { _meta: options.clientCapabilities._meta } : {}),
440 } satisfies NonNullable<EffectAcpSchema.InitializeRequest["clientCapabilities"]>;
441​
442 const getStartedState = Effect.gen(function* () {
443 const state = yield* Ref.get(startStateRef);
444 if (state._tag === "Started") {
445 return state.result;
446 }
447 return yield* new EffectAcpErrors.AcpTransportError({
448 detail: "ACP session runtime has not been started",
449 cause: "ACP session runtime has not been started",
450 });
451 });
452​
453 const validateConfigOptionValue = (
454 configId: string,
455 value: string | boolean,
456 ): Effect.Effect<void, EffectAcpErrors.AcpError> =>
457 Effect.gen(function* () {
458 const configOption = findSessionConfigOption(yield* Ref.get(configOptionsRef), configId);
459 if (!configOption) {
460 return;
461 }
462 if (configOption.type === "boolean") {
463 if (typeof value === "boolean") {
464 return;
465 }
466 return yield* new EffectAcpErrors.AcpRequestError({
467 code: -32602,
468 errorMessage: `Invalid value ${formatConfigOptionValue(value)} for session config option "${configOption.id}": expected boolean`,
469 data: {
470 configId: configOption.id,
471 expectedType: "boolean",
472 receivedValue: value,
473 },
474 });
475 }
476 if (typeof value !== "string") {
477 return yield* new EffectAcpErrors.AcpRequestError({
478 code: -32602,
479 errorMessage: `Invalid value ${formatConfigOptionValue(value)} for session config option "${configOption.id}": expected string`,
480 data: {
481 configId: configOption.id,
482 expectedType: "string",
483 receivedValue: value,
484 },
485 });
486 }
487 const allowedValues = collectSessionConfigOptionValues(configOption);
488 if (allowedValues.includes(value)) {
489 return;
490 }
491 return yield* new EffectAcpErrors.AcpRequestError({
492 code: -32602,
493 errorMessage: `Invalid value ${formatConfigOptionValue(value)} for session config option "${configOption.id}": expected one of ${allowedValues.join(", ")}`,
494 data: {
495 configId: configOption.id,
496 allowedValues,
497 receivedValue: value,
498 },
499 });
500 });
501​
502 const updateConfigOptions = (
503 response:
504 | EffectAcpSchema.SetSessionConfigOptionResponse
505 | EffectAcpSchema.LoadSessionResponse
506 | EffectAcpSchema.NewSessionResponse
507 | EffectAcpSchema.ResumeSessionResponse,
508 ): Effect.Effect<void> => Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(response));
509​
510 const updateCurrentModeId = (modeId: string): Effect.Effect<void> =>
511 Ref.update(modeStateRef, (current) =>
512 current ? { ...current, currentModeId: modeId } : current,
513 );
514​
515 const setConfigOption = (
516 configId: string,
517 value: string | boolean,
518 ): Effect.Effect<EffectAcpSchema.SetSessionConfigOptionResponse, EffectAcpErrors.AcpError> =>
519 validateConfigOptionValue(configId, value).pipe(
520 Effect.flatMap(() => getStartedState),
521 Effect.flatMap((started) =>
522 Ref.get(configOptionsRef).pipe(
523 Effect.flatMap((configOptions) => {
524 const existing = findSessionConfigOption(configOptions, configId);
525 if (existing && configOptionCurrentValueMatches(existing, value)) {
526 return Effect.succeed({
527 configOptions,
528 } satisfies EffectAcpSchema.SetSessionConfigOptionResponse);
529 }
530 const requestPayload =
531 typeof value === "boolean"
532 ? ({
533 sessionId: started.sessionId,
534 configId,
535 type: "boolean",
536 value,
537 } satisfies EffectAcpSchema.SetSessionConfigOptionRequest)
538 : ({
539 sessionId: started.sessionId,
540 configId,
541 value: String(value),
542 } satisfies EffectAcpSchema.SetSessionConfigOptionRequest);
543 return runLoggedRequest(
544 "session/set_config_option",
545 requestPayload,
546 acp.agent.setSessionConfigOption(requestPayload),
547 ).pipe(Effect.tap((response) => updateConfigOptions(response)));
548 }),
549 ),
550 ),
551 );
552​
553 const initializePayload = {
554 protocolVersion: 1,
555 clientCapabilities: initializeClientCapabilities,
556 clientInfo: options.clientInfo,
557 } satisfies EffectAcpSchema.InitializeRequest;
558 const sendInitialize = runLoggedRequest(
559 "initialize",
560 initializePayload,
561 acp.agent.initialize(initializePayload),
562 );
563​
564 const startOnce = Effect.gen(function* () {
565 const initializeResult = yield* sendInitialize;
566​
567 const authenticatePayload = {
568 methodId: options.authMethodId,
569 } satisfies EffectAcpSchema.AuthenticateRequest;
570​
571 yield* runLoggedRequest(
572 "authenticate",
573 authenticatePayload,
574 acp.agent.authenticate(authenticatePayload),
575 );
576​
577 let sessionId: string;
578 let sessionSetupResult:
579 | EffectAcpSchema.LoadSessionResponse
580 | EffectAcpSchema.NewSessionResponse
581 | EffectAcpSchema.ResumeSessionResponse;
582 if (options.resumeSessionId) {
583 const loadPayload = {
584 sessionId: options.resumeSessionId,
585 cwd: options.cwd,
586 mcpServers: options.mcpServers ?? [],
587 } satisfies EffectAcpSchema.LoadSessionRequest;
588 const sessionLoadTimeout = Duration.fromInputUnsafe(
589 options.sessionLoadTimeout ?? defaultSessionLoadTimeout,
590 );
591 const sessionLoadReplayIdleGap = Duration.fromInputUnsafe(
592 options.sessionLoadReplayIdleGap ?? defaultSessionLoadReplayIdleGap,
593 );
594​
595 yield* Ref.set(
596 sessionLoadGateRef,
597 Option.some({
598 active: true,
599 lastActivityAtMillis: undefined,
600 idleGap: sessionLoadReplayIdleGap,
601 initializeResult,
602 }),
603 );
604​
605 sessionId = options.resumeSessionId;
606 sessionSetupResult = yield* Effect.gen(function* () {
607 yield* logRequest({
608 method: "session/load",
609 payload: loadPayload,
610 status: "started",
611 });
612​
613 const idleFiber = yield* waitForSessionLoadReplayIdle({
614 gateRef: sessionLoadGateRef,
615 }).pipe(Effect.forkIn(runtimeScope));
616 const loaded = yield* Effect.raceFirst(
617 acp.agent.loadSession(loadPayload),
618 Fiber.join(idleFiber),
619 ).pipe(
620 Effect.ensuring(Fiber.interrupt(idleFiber).pipe(Effect.ignore)),
621 Effect.timeoutOption(sessionLoadTimeout),
622 Effect.flatMap((result) =>
623 Option.match(result, {
624 onNone: () =>
625 Effect.fail(
626 new EffectAcpErrors.AcpTransportError({
627 operation: "call-rpc",
628 method: "session/load",
629 detail: "session/load timed out waiting for RPC response or replay idle gap",
630 cause: undefined,
631 }),
632 ),
633 onSome: Effect.succeed,
634 }),
635 ),
636 Effect.tap((result) =>
637 logRequest({
638 method: "session/load",
639 payload: loadPayload,
640 status: "succeeded",
641 result,
642 }),
643 ),
644 Effect.onError((cause) =>
645 logRequest({
646 method: "session/load",
647 payload: loadPayload,
648 status: "failed",
649 cause,
650 }),
651 ),
652 );
653​
654 return loaded;
655 }).pipe(Effect.ensuring(Ref.set(sessionLoadGateRef, Option.none())));
656 } else {
657 const createPayload = {
658 cwd: options.cwd,
659 mcpServers: options.mcpServers ?? [],
660 } satisfies EffectAcpSchema.NewSessionRequest;
661 const created = yield* runLoggedRequest(
662 "session/new",
663 createPayload,
664 acp.agent.createSession(createPayload),
665 );
666 sessionId = created.sessionId;
667 sessionSetupResult = created;
668 }
669​
670 yield* Ref.set(modeStateRef, parseSessionModeState(sessionSetupResult));
671 yield* Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(sessionSetupResult));
672​
673 const nextState = {
674 sessionId,
675 initializeResult,
676 sessionSetupResult,
677 modelConfigId: extractModelConfigId(sessionSetupResult),
678 } satisfies AcpStartedState;
679 return nextState;
680 });
681​
682 const start = Effect.gen(function* () {
683 const deferred = yield* Deferred.make<
684 AcpSessionRuntimeStartResult,
685 EffectAcpErrors.AcpError
686 >();
687 const effect = yield* Ref.modify(startStateRef, (state) => {
688 switch (state._tag) {
689 case "Started":
690 return [Effect.succeed(state.result), state] as const;
691 case "Starting":
692 return [Deferred.await(state.deferred), state] as const;
693 case "NotStarted":
694 return [
695 startOnce.pipe(
696 Effect.tap((result) =>
697 Ref.set(startStateRef, { _tag: "Started", result }).pipe(
698 Effect.andThen(Deferred.succeed(deferred, result)),
699 ),
700 ),
701 Effect.onError((cause) =>
702 Deferred.failCause(deferred, cause).pipe(
703 Effect.andThen(Ref.set(startStateRef, { _tag: "NotStarted" })),
704 ),
705 ),
706 ),
707 { _tag: "Starting", deferred } satisfies AcpStartState,
708 ] as const;
709 }
710 });
711 return yield* effect;
712 });
713​
714 return {
715 handleRequestPermission: acp.handleRequestPermission,
716 handleElicitation: acp.handleElicitation,
717 handleReadTextFile: acp.handleReadTextFile,
718 handleWriteTextFile: acp.handleWriteTextFile,
719 handleCreateTerminal: acp.handleCreateTerminal,
720 handleTerminalOutput: acp.handleTerminalOutput,
721 handleTerminalWaitForExit: acp.handleTerminalWaitForExit,
722 handleTerminalKill: acp.handleTerminalKill,
723 handleTerminalRelease: acp.handleTerminalRelease,
724 handleSessionUpdate: acp.handleSessionUpdate,
725 handleElicitationComplete: acp.handleElicitationComplete,
726 handleUnknownExtRequest: acp.handleUnknownExtRequest,
727 handleUnknownExtNotification: acp.handleUnknownExtNotification,
728 handleExtRequest: acp.handleExtRequest,
729 handleExtNotification: acp.handleExtNotification,
730 initialize: () => sendInitialize,
731 start: () => start,
732 getEvents: () => Stream.fromQueue(eventQueue),
733 drainEvents: Effect.gen(function* () {
734 const acknowledge = yield* Deferred.make<void>();
735 yield* Queue.offer(eventQueue, {
736 _tag: "EventStreamBarrier",
737 acknowledge,
738 });
739 yield* Deferred.await(acknowledge);
740 }),
741 getModeState: Ref.get(modeStateRef),
742 getConfigOptions: Ref.get(configOptionsRef),
743 prompt: (payload, promptOptions?) =>
744 promptSerializationSemaphore.withPermit(
745 Effect.gen(function* () {
746 const started = yield* getStartedState;
747 yield* closeActiveAssistantSegment({
748 queue: eventQueue,
749 assistantSegmentRef,
750 });
751 const requestPayload = {
752 sessionId: started.sessionId,
753 ...payload,
754 } satisfies EffectAcpSchema.PromptRequest;
755 const cancelledResponse = {
756 stopReason: "cancelled",
757 } satisfies EffectAcpSchema.PromptResponse;
758 const promptRpcFiber = yield* runLoggedRequest(
759 "session/prompt",
760 requestPayload,
761 acp.agent.prompt(requestPayload),
762 ).pipe(Effect.forkIn(runtimeScope));
763 yield* Ref.set(activePromptFiberRef, Option.some(promptRpcFiber));
764 if (promptOptions?.dispatched) {
765 yield* Deferred.succeed(promptOptions.dispatched, undefined);
766 }
767 return yield* Fiber.join(promptRpcFiber).pipe(
768 Effect.catchCause((cause) =>
769 Cause.hasInterruptsOnly(cause)
770 ? Effect.succeed(cancelledResponse)
771 : Effect.failCause(cause),
772 ),
773 Effect.ensuring(
774 Effect.gen(function* () {
775 yield* Fiber.interrupt(promptRpcFiber).pipe(Effect.ignore);
776 yield* Ref.set(activePromptFiberRef, Option.none());
777 }),
778 ),
779 Effect.tap(() =>
780 closeActiveAssistantSegment({
781 queue: eventQueue,
782 assistantSegmentRef,
783 }),
784 ),
785 );
786 }),
787 ),
788 cancel: getStartedState.pipe(
789 Effect.flatMap((started) =>
790 Effect.gen(function* () {
791 const activePromptFiber = yield* Ref.get(activePromptFiberRef);
792 if (Option.isSome(activePromptFiber)) {
793 yield* Fiber.interrupt(activePromptFiber.value).pipe(Effect.ignore);
794 }
795 // Await the notification write so a replacement session/prompt
796 // cannot race ahead of session/cancel on the wire.
797 yield* acp.agent.cancel({ sessionId: started.sessionId }).pipe(Effect.ignore);
798 }),
799 ),
800 ),
801 setMode: (modeId) =>
802 Ref.get(modeStateRef).pipe(
803 Effect.flatMap((modeState) => {
804 if (modeState?.currentModeId === modeId) {
805 return Effect.succeed({} satisfies EffectAcpSchema.SetSessionModeResponse);
806 }
807 return setConfigOption("mode", modeId).pipe(
808 Effect.tap(() => updateCurrentModeId(modeId)),
809 Effect.as({} satisfies EffectAcpSchema.SetSessionModeResponse),
810 );
811 }),
812 ),
813 setConfigOption,
814 setModel: (model) =>
815 getStartedState.pipe(
816 Effect.flatMap((started) => setConfigOption(started.modelConfigId ?? "model", model)),
817 Effect.asVoid,
818 ),
819 setSessionModel: (modelId, meta) =>
820 getStartedState.pipe(
821 Effect.flatMap((started) => {
822 const requestPayload = {
823 sessionId: started.sessionId,
824 modelId,
825 ...(meta !== undefined ? { _meta: meta } : {}),
826 } satisfies EffectAcpSchema.SetSessionModelRequest;
827 return runLoggedRequest(
828 "session/set_model",
829 requestPayload,
830 acp.agent.setSessionModel(requestPayload),
831 );
832 }),
833 ),
834 request: (method, payload) =>
835 runLoggedRequest(method, payload, acp.raw.request(method, payload)),
836 notify: acp.raw.notify,
837 } satisfies AcpSessionRuntime["Service"];
838 });
839​
840export const layer = (
841 options: AcpSessionRuntimeOptions,
842): Layer.Layer<
843 AcpSessionRuntime,
844 EffectAcpErrors.AcpError,
845 ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto
846> => Layer.effect(AcpSessionRuntime, make(options));
847​
848function sessionConfigOptionsFromSetup(
849 response:
850 | {
851 readonly configOptions?: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null;
852 }
853 | undefined,
854): ReadonlyArray<EffectAcpSchema.SessionConfigOption> {
855 return response?.configOptions ?? [];
857​
858function configOptionCurrentValueMatches(
859 configOption: EffectAcpSchema.SessionConfigOption,
860 value: string | boolean,
861): boolean {
862 const currentValue = configOption.currentValue;
863 if (configOption.type === "boolean") {
864 return currentValue === value;
865 }
866 if (typeof currentValue !== "string") {
867 return false;
868 }
869 return currentValue.trim() === String(value).trim();
871​
872const handleSessionUpdate = ({
873 queue,
874 modeStateRef,
875 toolCallsRef,
876 assistantSegmentRef,
877 assistantItemRuntimeId,
878 params,
879}: {
880 readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;
881 readonly modeStateRef: Ref.Ref<AcpSessionModeState | undefined>;
882 readonly toolCallsRef: Ref.Ref<Map<string, AcpToolCallTrackedState>>;
883 readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
884 readonly assistantItemRuntimeId: string;
885 readonly params: EffectAcpSchema.SessionNotification;
886}): Effect.Effect<void> =>
887 Effect.gen(function* () {
888 const parsed = parseSessionUpdateEvent(params);
889 if (parsed.modeId) {
890 yield* Ref.update(modeStateRef, (current) =>
891 current === undefined ? current : updateModeState(current, parsed.modeId!),
892 );
893 }
894 for (const event of parsed.events) {
895 if (event._tag === "ToolCallUpdated") {
896 yield* closeActiveAssistantSegment({
897 queue,
898 assistantSegmentRef,
899 });
900 const { merged, decision } = yield* Ref.modify(toolCallsRef, (current) => {
901 const tracked = current.get(event.toolCall.toolCallId);
902 const previous = tracked?.state;
903 const nextToolCall = mergeToolCallState(previous, event.toolCall);
904 const decision = decideToolCallUpdateEmission({
905 previous,
906 next: nextToolCall,
907 lastEmittedDetailLength: tracked?.lastEmittedDetailLength,
908 skippedSinceEmit: tracked?.skippedSinceEmit ?? 0,
909 });
910 const next = new Map(current);
911 if (nextToolCall.status === "completed" || nextToolCall.status === "failed") {
912 next.delete(nextToolCall.toolCallId);
913 } else {
914 next.set(nextToolCall.toolCallId, {
915 state: nextToolCall,
916 lastEmittedDetailLength: decision.emit
917 ? toolCallProgressLength(nextToolCall)
918 : tracked?.lastEmittedDetailLength,
919 skippedSinceEmit: decision.skippedSinceEmit,
920 });
921 }
922 return [{ merged: nextToolCall, decision }, next] as const;
923 });
924 if (!decision.emit) {
925 continue;
926 }
927 yield* Queue.offer(queue, {
928 _tag: "ToolCallUpdated",
929 toolCall: merged,
930 rawPayload: event.rawPayload,
931 });
932 continue;
933 }
934 if (event._tag === "ContentDelta") {
935 if (event.text.trim().length === 0) {
936 const assistantSegmentState = yield* Ref.get(assistantSegmentRef);
937 if (!assistantSegmentState.activeItemId) {
938 continue;
939 }
940 }
941 const itemId = yield* ensureActiveAssistantSegment({
942 queue,
943 assistantSegmentRef,
944 sessionId: params.sessionId,
945 assistantItemRuntimeId,
946 });
947 yield* Queue.offer(queue, {
948 ...event,
949 itemId,
950 });
951 continue;
952 }
953 yield* Queue.offer(queue, event);
954 }
955 });
956​
957function updateModeState(modeState: AcpSessionModeState, nextModeId: string): AcpSessionModeState {
958 const normalized = nextModeId.trim();
959 if (!normalized) {
960 return modeState;
961 }
962 return modeState.availableModes.some((mode) => mode.id === normalized)
963 ? {
964 ...modeState,
965 currentModeId: normalized,
966 }
967 : modeState;
969​
970const assistantItemId = (sessionId: string, runtimeId: string, segmentIndex: number) =>
971 `assistant:${sessionId}:runtime:${runtimeId}:segment:${segmentIndex}`;
972​
973const ensureActiveAssistantSegment = ({
974 queue,
975 assistantSegmentRef,
976 sessionId,
977 assistantItemRuntimeId,
978}: {
979 readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;
980 readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
981 readonly sessionId: string;
982 readonly assistantItemRuntimeId: string;
983}) =>
984 Ref.modify<AcpAssistantSegmentState, EnsureActiveAssistantSegmentResult>(
985 assistantSegmentRef,
986 (current) => {
987 if (current.activeItemId) {
988 return [{ itemId: current.activeItemId }, current] as const;
989 }
990 const itemId = assistantItemId(sessionId, assistantItemRuntimeId, current.nextSegmentIndex);
991 return [
992 {
993 itemId,
994 startedEvent: {
995 _tag: "AssistantItemStarted",
996 itemId,
997 } satisfies Extract<AcpParsedSessionEvent, { readonly _tag: "AssistantItemStarted" }>,
998 },
999 {
1000 nextSegmentIndex: current.nextSegmentIndex + 1,
1001 activeItemId: itemId,
1002 } satisfies AcpAssistantSegmentState,
1003 ] as const;
1004 },
1005 ).pipe(
1006 Effect.flatMap((result) =>
1007 result.startedEvent
1008 ? Queue.offer(queue, result.startedEvent).pipe(Effect.as(result.itemId))
1009 : Effect.succeed(result.itemId),
1010 ),
1011 );
1012​
1013const closeActiveAssistantSegment = ({
1014 queue,
1015 assistantSegmentRef,
1016}: {
1017 readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;
1018 readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
1019}) =>
1020 Ref.modify(assistantSegmentRef, (current) => {
1021 if (!current.activeItemId) {
1022 return [undefined, current] as const;
1024 return [
1026 _tag: "AssistantItemCompleted",
1027 itemId: current.activeItemId,
1028 } satisfies AcpParsedSessionEvent,
1030 nextSegmentIndex: current.nextSegmentIndex,
1031 } satisfies AcpAssistantSegmentState,
1032 ] as const;
1033 }).pipe(Effect.flatMap((event) => (event ? Queue.offer(queue, event) : Effect.void)));