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