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

AcpSessionRuntime.ts

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