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

AcpSessionRuntime.ts

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