Open History to see the last commit
1import * as Context from "effect/Context";
2import * as Deferred from "effect/Deferred";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Schema from "effect/Schema";
6import * as Scope from "effect/Scope";
7import * as Stream from "effect/Stream";
8import * as RpcClient from "effect/unstable/rpc/RpcClient";
9import * as RpcMessage from "effect/unstable/rpc/RpcMessage";
10import * as RpcServer from "effect/unstable/rpc/RpcServer";
11import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
12
13import * as AcpError from "./errors.ts";
14import * as AcpProtocol from "./protocol.ts";
15import * as AcpRpcs from "./rpc.ts";
16import * as AcpSchema from "./compat.ts";
17import type * as AcpSchemaV1 from "./_generated/schema-v1.gen.ts";
18import * as AcpSchemaV2 from "./_generated/schema.gen.ts";
19import { AGENT_METHODS, CLIENT_METHODS } from "./_generated/meta.gen.ts";
20import {
21 callRpc,
22 decodeExtNotificationRegistration,
23 decodeExtRequestRegistration,
24 runHandler,
25} from "./_internal/shared.ts";
26import { makeChildStdio, makeTerminationError } from "./_internal/stdio.ts";
27
28export interface AcpClientOptions {
29 readonly logIncoming?: boolean;
30 readonly logOutgoing?: boolean;
31 readonly logger?: (event: AcpProtocol.AcpProtocolLogEvent) => Effect.Effect<void, never>;
32 readonly onIncomingRequest?: AcpProtocol.AcpPatchedProtocolOptions["onIncomingRequest"];
33 readonly onTermination?: AcpProtocol.AcpPatchedProtocolOptions["onTermination"];
34 readonly onOutgoingResponseFailure?: AcpProtocol.AcpPatchedProtocolOptions["onOutgoingResponseFailure"];
35 readonly onOutgoingResponse?: AcpProtocol.AcpPatchedProtocolOptions["onOutgoingResponse"];
36 /** Transforms child output before protocol logging and parsing. */
37 readonly transformStdout?: (
38 stdout: ChildProcessSpawner.ChildProcessHandle["stdout"],
39 ) => AcpProtocol.AcpStdio["stdin"];
40 /** Transforms decoded session updates before buffering or delivery. */
41 readonly transformSessionUpdate?: (
42 notification: AcpSchema.SessionNotification,
43 ) => AcpSchema.SessionNotification;
44}
45
46type AcpClientRaw = {
47 readonly notifications: Stream.Stream<AcpProtocol.AcpIncomingNotification>;
48 readonly request: (method: string, payload: unknown) => Effect.Effect<unknown, AcpError.AcpError>;
49 readonly notify: (method: string, payload: unknown) => Effect.Effect<void, AcpError.AcpError>;
50};
51
52export type AcpRequestHandler<Request, Response> = AcpProtocol.AcpRequestHandler<Request, Response>;
53
54export class AcpClient extends Context.Service<
55 AcpClient,
56 {
57 readonly raw: AcpClientRaw;
58 readonly agent: {
59 /**
60 * Initializes the ACP session and negotiates capabilities.
61 * @see https://agentclientprotocol.com/protocol/schema#initialize
62 */
63 readonly initialize: (
64 payload: AcpSchema.InitializeRequest,
65 ) => Effect.Effect<AcpSchema.InitializeResponse, AcpError.AcpError>;
66 /**
67 * Performs authentication with the method negotiated for ACP v1 or v2.
68 * @see https://agentclientprotocol.com/protocol/v2/draft/authentication
69 */
70 readonly authenticate: (
71 payload: AcpSchema.AuthenticateRequest,
72 ) => Effect.Effect<AcpSchema.AuthenticateResponse, AcpError.AcpError>;
73 /**
74 * Logs out the current ACP identity using the negotiated generation.
75 * @see https://agentclientprotocol.com/protocol/v2/draft/authentication
76 */
77 readonly logout: (
78 payload: AcpSchema.LogoutRequest,
79 ) => Effect.Effect<AcpSchema.LogoutResponse, AcpError.AcpError>;
80 /**
81 * Starts a new ACP session.
82 * @see https://agentclientprotocol.com/protocol/schema#session/new
83 */
84 readonly createSession: (
85 payload: AcpSchema.NewSessionRequest,
86 ) => Effect.Effect<AcpSchema.NewSessionResponse, AcpError.AcpError>;
87 /**
88 * Resumes a saved ACP session with replay from the beginning.
89 *
90 * This compatibility name maps to ACP v2's `session/resume`; v2 removed
91 * `session/load` and expresses replay with `replayFrom`.
92 */
93 readonly loadSession: (
94 payload: AcpSchema.LoadSessionRequest,
95 ) => Effect.Effect<AcpSchema.LoadSessionResponse, AcpError.AcpError>;
96 /**
97 * Lists available ACP sessions.
98 * @see https://agentclientprotocol.com/protocol/schema#session/list
99 */
100 readonly listSessions: (
101 payload: AcpSchema.ListSessionsRequest,
102 ) => Effect.Effect<AcpSchema.ListSessionsResponse, AcpError.AcpError>;
103 /**
104 * Forks an ACP session.
105 * @see https://agentclientprotocol.com/protocol/schema#session/fork
106 */
107 readonly forkSession: (
108 payload: AcpSchema.ForkSessionRequest,
109 ) => Effect.Effect<AcpSchema.ForkSessionResponse, AcpError.AcpError>;
110 /**
111 * Resumes an ACP session.
112 * @see https://agentclientprotocol.com/protocol/schema#session/resume
113 */
114 readonly resumeSession: (
115 payload: AcpSchema.ResumeSessionRequest,
116 ) => Effect.Effect<AcpSchema.ResumeSessionResponse, AcpError.AcpError>;
117 /**
118 * Closes an ACP session.
119 * @see https://agentclientprotocol.com/protocol/schema#session/close
120 */
121 readonly closeSession: (
122 payload: AcpSchema.CloseSessionRequest,
123 ) => Effect.Effect<AcpSchema.CloseSessionResponse, AcpError.AcpError>;
124 readonly deleteSession: (
125 payload: AcpSchema.DeleteSessionRequest,
126 ) => Effect.Effect<AcpSchema.DeleteSessionResponse, AcpError.AcpError>;
127 readonly listProviders: (
128 payload: AcpSchema.ListProvidersRequest,
129 ) => Effect.Effect<AcpSchema.ListProvidersResponse, AcpError.AcpError>;
130 readonly setProvider: (
131 payload: AcpSchema.SetProviderRequest,
132 ) => Effect.Effect<AcpSchema.SetProviderResponse, AcpError.AcpError>;
133 readonly disableProvider: (
134 payload: AcpSchema.DisableProviderRequest,
135 ) => Effect.Effect<AcpSchema.DisableProviderResponse, AcpError.AcpError>;
136 /**
137 * Updates a session configuration option.
138 * @see https://agentclientprotocol.com/protocol/schema#session/set_config_option
139 */
140 readonly setSessionModel: (
141 payload: AcpSchema.SetSessionModelRequest,
142 ) => Effect.Effect<AcpSchema.SetSessionModelResponse, AcpError.AcpError>;
143 readonly setSessionConfigOption: (
144 payload: AcpSchema.SetSessionConfigOptionRequest,
145 ) => Effect.Effect<AcpSchema.SetSessionConfigOptionResponse, AcpError.AcpError>;
146 /**
147 * Sends a prompt turn to the agent.
148 * @see https://agentclientprotocol.com/protocol/schema#session/prompt
149 */
150 readonly prompt: (
151 payload: AcpSchema.PromptRequest,
152 ) => Effect.Effect<AcpSchema.PromptResponse, AcpError.AcpError>;
153 /**
154 * Sends a real ACP `session/cancel` notification.
155 * @see https://agentclientprotocol.com/protocol/schema#session/cancel
156 */
157 readonly cancel: (
158 payload: AcpSchema.CancelNotification,
159 ) => Effect.Effect<void, AcpError.AcpError>;
160 };
161 /**
162 * Registers a handler for `session/request_permission`.
163 * @see https://agentclientprotocol.com/protocol/schema#session/request_permission
164 */
165 readonly handleRequestPermission: (
166 handler: AcpRequestHandler<
167 AcpSchema.RequestPermissionRequest,
168 AcpSchema.RequestPermissionResponse
169 >,
170 ) => Effect.Effect<void>;
171 /**
172 * Registers a handler for `elicitation/create` requests.
173 * @see https://agentclientprotocol.com/protocol/schema#elicitation/create
174 */
175 readonly handleElicitation: (
176 handler: AcpRequestHandler<
177 AcpSchema.CreateElicitationRequest,
178 AcpSchema.CreateElicitationResponse
179 >,
180 ) => Effect.Effect<void>;
181 readonly handleMcpConnect: (
182 handler: AcpRequestHandler<AcpSchema.ConnectMcpRequest, AcpSchema.ConnectMcpResponse>,
183 ) => Effect.Effect<void>;
184 readonly handleMcpMessage: (
185 handler: AcpRequestHandler<AcpSchema.MessageMcpRequest, AcpSchema.MessageMcpResponse>,
186 ) => Effect.Effect<void>;
187 readonly handleMcpDisconnect: (
188 handler: AcpRequestHandler<AcpSchema.DisconnectMcpRequest, AcpSchema.DisconnectMcpResponse>,
189 ) => Effect.Effect<void>;
190 readonly handleMcpNotification: (
191 handler: (
192 notification: AcpSchema.MessageMcpNotification,
193 ) => Effect.Effect<void, AcpError.AcpError>,
194 ) => Effect.Effect<void>;
195 /** Legacy ACP v1 hooks retained for policy compatibility; ACP v2 never advertises them. */
196 readonly handleReadTextFile: (
197 handler: AcpRequestHandler<AcpSchema.ReadTextFileRequest, AcpSchema.ReadTextFileResponse>,
198 ) => Effect.Effect<void>;
199 readonly handleWriteTextFile: (
200 handler: AcpRequestHandler<
201 AcpSchema.WriteTextFileRequest,
202 AcpSchema.WriteTextFileResponse | void
203 >,
204 ) => Effect.Effect<void>;
205 readonly handleCreateTerminal: (
206 handler: AcpRequestHandler<AcpSchema.CreateTerminalRequest, AcpSchema.CreateTerminalResponse>,
207 ) => Effect.Effect<void>;
208 readonly handleTerminalOutput: (
209 handler: AcpRequestHandler<AcpSchema.TerminalOutputRequest, AcpSchema.TerminalOutputResponse>,
210 ) => Effect.Effect<void>;
211 readonly handleTerminalWaitForExit: (
212 handler: AcpRequestHandler<
213 AcpSchema.WaitForTerminalExitRequest,
214 AcpSchema.WaitForTerminalExitResponse
215 >,
216 ) => Effect.Effect<void>;
217 readonly handleTerminalKill: (
218 handler: AcpRequestHandler<
219 AcpSchema.KillTerminalRequest,
220 AcpSchema.KillTerminalResponse | void
221 >,
222 ) => Effect.Effect<void>;
223 readonly handleTerminalRelease: (
224 handler: AcpRequestHandler<
225 AcpSchema.ReleaseTerminalRequest,
226 AcpSchema.ReleaseTerminalResponse | void
227 >,
228 ) => Effect.Effect<void>;
229 /**
230 * Registers a handler for `session/update`.
231 * @see https://agentclientprotocol.com/protocol/schema#session/update
232 */
233 readonly handleSessionUpdate: (
234 handler: (
235 notification: AcpSchema.SessionNotification,
236 ) => Effect.Effect<void, AcpError.AcpError>,
237 ) => Effect.Effect<void>;
238 /**
239 * Registers a handler for `elicitation/complete`.
240 * @see https://agentclientprotocol.com/protocol/schema#elicitation/complete
241 */
242 readonly handleElicitationComplete: (
243 handler: (
244 notification: AcpSchema.CompleteElicitationNotification,
245 ) => Effect.Effect<void, AcpError.AcpError>,
246 ) => Effect.Effect<void>;
247 /**
248 * Registers a fallback extension request handler.
249 * @see https://agentclientprotocol.com/protocol/extensibility
250 */
251 readonly handleUnknownExtRequest: (
252 handler: (
253 method: string,
254 params: unknown,
255 context: AcpProtocol.AcpRequestContext,
256 ) => Effect.Effect<unknown, AcpError.AcpError>,
257 ) => Effect.Effect<void>;
258 /**
259 * Registers a fallback extension notification handler.
260 * @see https://agentclientprotocol.com/protocol/extensibility
261 */
262 readonly handleUnknownExtNotification: (
263 handler: (method: string, params: unknown) => Effect.Effect<void, AcpError.AcpError>,
264 ) => Effect.Effect<void>;
265 /**
266 * Registers a typed extension request handler.
267 * @see https://agentclientprotocol.com/protocol/extensibility
268 */
269 readonly handleExtRequest: <A, I>(
270 method: string,
271 payload: Schema.Codec<A, I>,
272 handler: AcpRequestHandler<A, unknown>,
273 ) => Effect.Effect<void>;
274 /**
275 * Registers a typed extension notification handler.
276 * @see https://agentclientprotocol.com/protocol/extensibility
277 */
278 readonly handleExtNotification: <A, I>(
279 method: string,
280 payload: Schema.Codec<A, I>,
281 handler: (payload: A) => Effect.Effect<void, AcpError.AcpError>,
282 ) => Effect.Effect<void>;
283 }
284>()("effect-acp/client/AcpClient") {}
285
286interface AcpCoreRequestHandlers {
287 requestPermission?: AcpRequestHandler<
288 AcpSchema.RequestPermissionRequest,
289 AcpSchema.RequestPermissionResponse
290 >;
291 elicitation?: AcpRequestHandler<
292 AcpSchema.CreateElicitationRequest,
293 AcpSchema.CreateElicitationResponse
294 >;
295 mcpConnect?: AcpRequestHandler<AcpSchema.ConnectMcpRequest, AcpSchema.ConnectMcpResponse>;
296 mcpMessage?: AcpRequestHandler<AcpSchema.MessageMcpRequest, AcpSchema.MessageMcpResponse>;
297 mcpDisconnect?: AcpRequestHandler<
298 AcpSchema.DisconnectMcpRequest,
299 AcpSchema.DisconnectMcpResponse
300 >;
301 readTextFile?: AcpRequestHandler<AcpSchema.ReadTextFileRequest, AcpSchema.ReadTextFileResponse>;
302 writeTextFile?: AcpRequestHandler<
303 AcpSchema.WriteTextFileRequest,
304 AcpSchema.WriteTextFileResponse | void
305 >;
306 createTerminal?: AcpRequestHandler<
307 AcpSchema.CreateTerminalRequest,
308 AcpSchema.CreateTerminalResponse
309 >;
310 terminalOutput?: AcpRequestHandler<
311 AcpSchema.TerminalOutputRequest,
312 AcpSchema.TerminalOutputResponse
313 >;
314 terminalWaitForExit?: AcpRequestHandler<
315 AcpSchema.WaitForTerminalExitRequest,
316 AcpSchema.WaitForTerminalExitResponse
317 >;
318 terminalKill?: AcpRequestHandler<
319 AcpSchema.KillTerminalRequest,
320 AcpSchema.KillTerminalResponse | void
321 >;
322 terminalRelease?: AcpRequestHandler<
323 AcpSchema.ReleaseTerminalRequest,
324 AcpSchema.ReleaseTerminalResponse | void
325 >;
326}
327
328interface AcpNotificationHandlers {
329 readonly sessionUpdate: BufferedNotificationHandler<AcpSchema.SessionNotification>;
330 readonly elicitationComplete: BufferedNotificationHandler<AcpSchema.CompleteElicitationNotification>;
331}
332
333interface BufferedNotificationHandler<A> {
334 readonly handlers: Array<(notification: A) => Effect.Effect<void, AcpError.AcpError>>;
335 readonly pending: Array<A>;
336}
337
338function normalizeContentBlock(content: AcpSchemaV2.ContentBlock): AcpSchema.ContentBlock {
339 switch (content.type) {
340 case "text":
341 case "image":
342 case "audio":
343 case "resource_link":
344 case "resource":
345 return content as AcpSchema.ContentBlock;
346 default:
347 return { type: "_t3_unknown", originalType: content.type, raw: content };
348 }
349}
350
351function normalizeToolCallContent(content: AcpSchemaV2.ToolCallContent): AcpSchema.ToolCallContent {
352 if (content.type === "content") {
353 const known = content as Extract<AcpSchemaV2.ToolCallContent, { readonly type: "content" }>;
354 return { ...known, content: normalizeContentBlock(known.content) };
355 }
356 if (content.type === "terminal") {
357 return content as Extract<AcpSchemaV2.ToolCallContent, { readonly type: "terminal" }>;
358 }
359 if (content.type !== "diff") {
360 return { type: "_t3_unknown", originalType: content.type, raw: content };
361 }
362
363 return content as Extract<AcpSchemaV2.ToolCallContent, { readonly type: "diff" }>;
364}
365
366function normalizeToolCallUpdate(update: AcpSchemaV2.ToolCallUpdate): AcpSchema.ToolCallUpdate {
367 return {
368 toolCallId: update.toolCallId,
369 ...(update.name === undefined ? {} : { name: update.name }),
370 ...(update.title === undefined ? {} : { title: update.title }),
371 ...(update.kind === undefined ? {} : { kind: update.kind }),
372 ...(update.status === undefined ? {} : { status: update.status }),
373 ...(update.content === undefined
374 ? {}
375 : {
376 content: update.content === null ? null : update.content.map(normalizeToolCallContent),
377 }),
378 ...(update.locations === undefined ? {} : { locations: update.locations }),
379 ...(update.rawInput === undefined ? {} : { rawInput: update.rawInput }),
380 ...(update.rawOutput === undefined ? {} : { rawOutput: update.rawOutput }),
381 ...(update._meta === undefined ? {} : { _meta: update._meta }),
382 };
383}
384
385function normalizeConfigOption(
386 option: AcpSchemaV2.SessionConfigOption,
387): AcpSchema.SessionConfigOption | undefined {
388 if (option.type === "boolean") {
389 const known = option as Extract<AcpSchemaV2.SessionConfigOption, { readonly type: "boolean" }>;
390 return {
391 type: "boolean",
392 id: known.configId,
393 name: known.name,
394 currentValue: known.currentValue,
395 ...(known.description === undefined ? {} : { description: known.description }),
396 ...(known.category === undefined ? {} : { category: known.category }),
397 ...(known._meta === undefined ? {} : { _meta: known._meta }),
398 };
399 }
400 if (option.type === "select") {
401 const known = option as Extract<AcpSchemaV2.SessionConfigOption, { readonly type: "select" }>;
402 return {
403 type: "select",
404 id: known.configId,
405 name: known.name,
406 currentValue: known.currentValue,
407 options: known.options,
408 ...(known.description === undefined ? {} : { description: known.description }),
409 ...(known.category === undefined ? {} : { category: known.category }),
410 ...(known._meta === undefined ? {} : { _meta: known._meta }),
411 };
412 }
413 return undefined;
414}
415
416function normalizeConfigOptions(
417 options: ReadonlyArray<AcpSchemaV2.SessionConfigOption> | undefined,
418): ReadonlyArray<AcpSchema.SessionConfigOption> | undefined {
419 return options?.flatMap((option) => {
420 const normalized = normalizeConfigOption(option);
421 return normalized === undefined ? [] : [normalized];
422 });
423}
424
425function normalizeSessionUpdate(
426 notification: AcpSchemaV2.UpdateSessionNotification,
427): AcpSchema.SessionNotification {
428 const update = notification.update;
429 const base = {
430 sessionId: notification.sessionId,
431 ...(notification._meta === undefined ? {} : { _meta: notification._meta }),
432 };
433
434 switch (update.sessionUpdate) {
435 case "user_message_chunk":
436 case "agent_message_chunk":
437 case "agent_thought_chunk": {
438 const known = update as Extract<
439 AcpSchemaV2.SessionUpdate,
440 {
441 readonly sessionUpdate:
442 | "user_message_chunk"
443 | "agent_message_chunk"
444 | "agent_thought_chunk";
445 }
446 >;
447 const content = normalizeContentBlock(known.content);
448 return { ...base, update: { ...known, content } };
449 }
450 case "user_message":
451 case "agent_message":
452 case "agent_thought": {
453 const known = update as Extract<
454 AcpSchemaV2.SessionUpdate,
455 { readonly sessionUpdate: "user_message" | "agent_message" | "agent_thought" }
456 >;
457 const content = known.content;
458 return {
459 ...base,
460 update: {
461 ...known,
462 ...(content === undefined
463 ? {}
464 : {
465 content:
466 content === null
467 ? null
468 : (content as ReadonlyArray<AcpSchemaV2.ContentBlock>).map(
469 normalizeContentBlock,
470 ),
471 }),
472 },
473 } as AcpSchema.SessionNotification;
474 }
475 case "tool_call_update": {
476 const known = update as Extract<
477 AcpSchemaV2.SessionUpdate,
478 { readonly sessionUpdate: "tool_call_update" }
479 >;
480 return {
481 ...base,
482 update: { sessionUpdate: "tool_call_update", ...normalizeToolCallUpdate(known) },
483 };
484 }
485 case "tool_call_content_chunk": {
486 const known = update as Extract<
487 AcpSchemaV2.SessionUpdate,
488 { readonly sessionUpdate: "tool_call_content_chunk" }
489 >;
490 return {
491 ...base,
492 update: {
493 sessionUpdate: "tool_call_content_chunk",
494 toolCallId: known.toolCallId,
495 content: normalizeToolCallContent(known.content),
496 ...(known._meta === undefined ? {} : { _meta: known._meta }),
497 },
498 };
499 }
500 case "config_option_update": {
501 const known = update as Extract<
502 AcpSchemaV2.SessionUpdate,
503 { readonly sessionUpdate: "config_option_update" }
504 >;
505 return {
506 ...base,
507 update: {
508 sessionUpdate: "config_option_update",
509 configOptions: known.configOptions.flatMap((option) => {
510 const normalized = normalizeConfigOption(option);
511 return normalized === undefined ? [] : [normalized];
512 }),
513 ...(known._meta === undefined ? {} : { _meta: known._meta }),
514 },
515 };
516 }
517 case "state_update":
518 case "terminal_update":
519 case "terminal_output_chunk":
520 case "plan_update":
521 case "plan_removed":
522 case "session_info_update":
523 case "usage_update":
524 case "compaction_update":
525 case "compaction_summary_chunk":
526 return { ...base, update } as AcpSchema.SessionNotification;
527 case "available_commands_update": {
528 const known = update as Extract<
529 AcpSchemaV2.SessionUpdate,
530 { readonly sessionUpdate: "available_commands_update" }
531 >;
532 return {
533 ...base,
534 update: {
535 ...known,
536 availableCommands: known.availableCommands.map((command) => ({
537 ...command,
538 ...(command.input?.type === "text"
539 ? {
540 input: command.input as Extract<
541 AcpSchemaV2.AvailableCommandInput,
542 { readonly type: "text" }
543 >,
544 }
545 : { input: null }),
546 })),
547 },
548 };
549 }
550 default:
551 return {
552 ...base,
553 update: {
554 sessionUpdate: "_t3_unknown",
555 originalSessionUpdate: update.sessionUpdate,
556 raw: update,
557 },
558 };
559 }
560}
561
562function normalizeV1SessionUpdate(
563 notification: AcpSchemaV1.SessionNotification,
564): AcpSchema.SessionNotification {
565 if (notification.update.sessionUpdate !== "available_commands_update") {
566 return notification as unknown as AcpSchema.SessionNotification;
567 }
568 return {
569 ...notification,
570 update: {
571 ...notification.update,
572 availableCommands: notification.update.availableCommands.map((command) => {
573 const { input, ...rest } = command;
574 return {
575 ...rest,
576 ...(input == null ? {} : { input: { type: "text" as const, hint: input.hint } }),
577 };
578 }),
579 },
580 };
581}
582
583function toV2McpServer(server: AcpSchema.McpServer): AcpSchemaV2.McpServer {
584 if ("type" in server) return server;
585 return {
586 type: "stdio",
587 name: server.name,
588 command: server.command,
589 ...(server.args === undefined ? {} : { args: server.args }),
590 ...(server.env === undefined ? {} : { env: server.env }),
591 ...(server._meta === undefined ? {} : { _meta: server._meta }),
592 };
593}
594
595function toV2ResumeRequest(
596 request: AcpSchema.ResumeSessionRequest,
597 replayFrom?: AcpSchemaV2.ReplayFrom,
598): AcpSchemaV2.ResumeSessionRequest {
599 const { mcpServers, ...rest } = request;
600 return {
601 ...rest,
602 ...(mcpServers === undefined ? {} : { mcpServers: mcpServers.map(toV2McpServer) }),
603 ...(replayFrom === undefined ? {} : { replayFrom }),
604 };
605}
606
607function toV2ForkRequest(request: AcpSchema.ForkSessionRequest): AcpSchemaV2.ForkSessionRequest {
608 const { mcpServers, ...rest } = request;
609 return {
610 ...rest,
611 ...(mcpServers === undefined ? {} : { mcpServers: mcpServers.map(toV2McpServer) }),
612 };
613}
614
615function normalizeInitializeResponse(
616 response: AcpSchemaV2.InitializeResponse,
617): AcpSchema.InitializeResponse {
618 const session = response.capabilities?.session;
619 const prompt = session?.prompt;
620 const mcp = session?.mcp;
621 return {
622 protocolVersion: response.protocolVersion,
623 agentInfo: response.info,
624 agentCapabilities: {
625 loadSession: session !== undefined && session !== null,
626 promptCapabilities: {
627 image: prompt?.image != null,
628 audio: prompt?.audio != null,
629 embeddedContext: prompt?.embeddedContext != null,
630 },
631 mcpCapabilities: {
632 stdio: mcp?.stdio != null,
633 http: mcp?.http != null,
634 acp: mcp?.acp != null,
635 },
636 ...(session == null
637 ? {}
638 : {
639 sessionCapabilities: {
640 list: {},
641 resume: {},
642 close: {},
643 ...(session.delete == null ? {} : { delete: {} }),
644 ...(session.fork == null ? {} : { fork: {} }),
645 ...(session.additionalDirectories == null ? {} : { additionalDirectories: {} }),
646 },
647 }),
648 ...(response.capabilities?.providers == null ? {} : { providers: {} }),
649 ...(response.authMethods === undefined || response.authMethods.length === 0
650 ? {}
651 : { auth: { logout: {} } }),
652 },
653 ...(response.authMethods === undefined
654 ? {}
655 : {
656 authMethods: response.authMethods.map((method) => {
657 const record = method as AcpSchemaV2.AuthMethod;
658 const base = {
659 id: record.methodId,
660 name: record.name,
661 ...(record.description === undefined ? {} : { description: record.description }),
662 ...(record._meta === undefined ? {} : { _meta: record._meta }),
663 };
664 if (
665 record.type === "env_var" &&
666 Array.isArray(record.vars) &&
667 record.vars.every(
668 (variable) =>
669 typeof variable === "object" &&
670 variable !== null &&
671 typeof (variable as { readonly name?: unknown }).name === "string",
672 )
673 ) {
674 return {
675 ...base,
676 type: "env_var" as const,
677 vars: record.vars.map((variable) => {
678 const value = variable as { readonly name: string; readonly label?: unknown };
679 return {
680 name: value.name,
681 ...(typeof value.label === "string" ? { label: value.label } : {}),
682 };
683 }),
684 ...(typeof record.link === "string" ? { link: record.link } : {}),
685 };
686 }
687 if (record.type !== "terminal") return { ...base, type: "agent" as const };
688 return {
689 ...base,
690 type: "terminal" as const,
691 ...(Array.isArray(record.args)
692 ? {
693 args: record.args.filter(
694 (argument): argument is string => typeof argument === "string",
695 ),
696 }
697 : {}),
698 ...(Array.isArray(record.env)
699 ? {
700 env: Object.fromEntries(
701 (record.env as ReadonlyArray<AcpSchemaV2.EnvVariable>).map((variable) => [
702 variable.name,
703 variable.value,
704 ]),
705 ),
706 }
707 : {}),
708 };
709 }),
710 }),
711 ...(response._meta === undefined ? {} : { _meta: response._meta }),
712 };
713}
714
715function toV2InitializeRequest(
716 request: AcpSchema.InitializeRequest,
717): AcpSchemaV2.InitializeRequest {
718 const capabilities = request.clientCapabilities;
719 return {
720 protocolVersion: 2,
721 info: request.clientInfo ?? { name: "t3-code", version: "unknown" },
722 capabilities: {
723 ...(capabilities?.auth?.terminal === true ? { auth: { terminal: {} } } : {}),
724 ...(capabilities?.elicitation == null ? {} : { elicitation: capabilities.elicitation }),
725 ...(capabilities?._meta === undefined ? {} : { _meta: capabilities._meta }),
726 },
727 ...(request._meta === undefined ? {} : { _meta: request._meta }),
728 };
729}
730
731function toNegotiatingInitializeRequest(
732 request: AcpSchema.InitializeRequest,
733): AcpSchemaV1.InitializeRequest | AcpSchemaV2.InitializeRequest {
734 return {
735 ...toV2InitializeRequest(request),
736 clientCapabilities: request.clientCapabilities ?? {},
737 ...(request.clientInfo === undefined ? {} : { clientInfo: request.clientInfo }),
738 } as unknown as AcpSchemaV1.InitializeRequest | AcpSchemaV2.InitializeRequest;
739}
740
741function isV2InitializeResponse(
742 response: AcpSchemaV1.InitializeResponse | AcpSchemaV2.InitializeResponse,
743): response is AcpSchemaV2.InitializeResponse {
744 return "info" in response;
745}
746
747function normalizeV2SessionSetupResponse(
748 response:
749 | AcpSchemaV2.NewSessionResponse
750 | AcpSchemaV2.ResumeSessionResponse
751 | AcpSchemaV2.ForkSessionResponse,
752) {
753 const configOptions = normalizeConfigOptions(response.configOptions);
754 return {
755 ...("sessionId" in response ? { sessionId: response.sessionId } : {}),
756 ...(configOptions === undefined ? {} : { configOptions }),
757 ...(response._meta === undefined ? {} : { _meta: response._meta }),
758 };
759}
760
761function normalizePermissionRequest(
762 request: AcpSchemaV2.RequestPermissionRequest,
763 context: AcpProtocol.AcpRequestContext,
764): AcpSchema.RequestPermissionRequest {
765 const subject = request.subject;
766 const toolCall =
767 subject?.type === "tool_call" && "toolCall" in subject
768 ? normalizeToolCallUpdate(subject.toolCall as AcpSchemaV2.ToolCallUpdate)
769 : {
770 toolCallId:
771 subject?.type === "command" &&
772 "toolCallId" in subject &&
773 typeof subject.toolCallId === "string"
774 ? subject.toolCallId
775 : context.requestId,
776 title: request.title,
777 kind: subject?.type === "command" ? ("execute" as const) : ("other" as const),
778 };
779 return {
780 sessionId: request.sessionId,
781 title: request.title,
782 ...(request.description === undefined ? {} : { description: request.description }),
783 ...(subject === undefined ? {} : { subject }),
784 toolCall,
785 options: request.options,
786 ...(request._meta === undefined ? {} : { _meta: request._meta }),
787 };
788}
789
790export const make = Effect.fn("effect-acp/AcpClient.make")(function* (
791 stdio: AcpProtocol.AcpStdio,
792 options: AcpClientOptions = {},
793 terminationError?: Effect.Effect<AcpError.AcpError>,
794): Effect.fn.Return<AcpClient["Service"], never, Scope.Scope> {
795 const coreHandlers: AcpCoreRequestHandlers = {};
796 const notificationHandlers: AcpNotificationHandlers = {
797 sessionUpdate: { handlers: [], pending: [] },
798 elicitationComplete: { handlers: [], pending: [] },
799 };
800 const promptCompletions = new Map<
801 string,
802 Deferred.Deferred<AcpSchema.PromptResponse, AcpError.AcpError>
803 >();
804 const extRequestHandlers = new Map<string, AcpRequestHandler<unknown, unknown>>();
805 const extNotificationHandlers = new Map<
806 string,
807 (params: unknown) => Effect.Effect<void, AcpError.AcpError>
808 >();
809 let unknownExtRequestHandler:
810 | ((
811 method: string,
812 params: unknown,
813 context: AcpProtocol.AcpRequestContext,
814 ) => Effect.Effect<unknown, AcpError.AcpError>)
815 | undefined;
816 let unknownExtNotificationHandler:
817 | ((method: string, params: unknown) => Effect.Effect<void, AcpError.AcpError>)
818 | undefined;
819 let negotiatedProtocolGeneration: 1 | 2 | undefined;
820
821 const runNotificationHandlers = <A>(
822 registration: BufferedNotificationHandler<A>,
823 notification: A,
824 ) =>
825 Effect.forEach(
826 registration.handlers,
827 (handler) => handler(notification).pipe(Effect.catch(() => Effect.void)),
828 { discard: true },
829 );
830
831 const flushBufferedNotifications = <A>(registration: BufferedNotificationHandler<A>) =>
832 Effect.suspend(() => {
833 if (registration.handlers.length === 0 || registration.pending.length === 0) {
834 return Effect.void;
835 }
836 const pending = registration.pending.splice(0, registration.pending.length);
837 return Effect.forEach(
838 pending,
839 (notification) => runNotificationHandlers(registration, notification),
840 {
841 discard: true,
842 },
843 );
844 });
845
846 const dispatchNotification = (notification: AcpProtocol.AcpIncomingNotification) => {
847 switch (notification._tag) {
848 case "SessionUpdate": {
849 const normalized = notification.params as AcpSchema.SessionNotification;
850 const state = normalized.update;
851 const completePrompt =
852 state.sessionUpdate === "state_update" && state.state === "idle"
853 ? Effect.suspend(() => {
854 const idle = state as Extract<
855 AcpSchema.SessionUpdate,
856 { readonly sessionUpdate: "state_update"; readonly state: "idle" }
857 >;
858 const completion = promptCompletions.get(normalized.sessionId);
859 if (completion === undefined) return Effect.void;
860 promptCompletions.delete(normalized.sessionId);
861 return Deferred.succeed(completion, {
862 stopReason: idle.stopReason ?? "end_turn",
863 ...(idle.usage === undefined ? {} : { usage: idle.usage }),
864 ...(idle._meta === undefined ? {} : { _meta: idle._meta }),
865 }).pipe(Effect.asVoid);
866 })
867 : Effect.void;
868 if (notificationHandlers.sessionUpdate.handlers.length === 0) {
869 notificationHandlers.sessionUpdate.pending.push(normalized);
870 return completePrompt;
871 }
872 return Effect.all(
873 [completePrompt, runNotificationHandlers(notificationHandlers.sessionUpdate, normalized)],
874 { discard: true },
875 );
876 }
877 case "ElicitationComplete": {
878 if (notificationHandlers.elicitationComplete.handlers.length === 0) {
879 notificationHandlers.elicitationComplete.pending.push(notification.params);
880 return Effect.void;
881 }
882 return runNotificationHandlers(
883 notificationHandlers.elicitationComplete,
884 notification.params,
885 );
886 }
887 case "ExtNotification": {
888 const handler = extNotificationHandlers.get(notification.method);
889 if (handler) {
890 return handler(notification.params);
891 }
892 return unknownExtNotificationHandler
893 ? unknownExtNotificationHandler(notification.method, notification.params)
894 : Effect.void;
895 }
896 }
897 };
898
899 const dispatchExtRequest = (
900 method: string,
901 params: unknown,
902 context: AcpProtocol.AcpRequestContext,
903 ) => {
904 const handler = extRequestHandlers.get(method);
905 if (handler) {
906 return handler(params, context);
907 }
908 return unknownExtRequestHandler
909 ? unknownExtRequestHandler(method, params, context)
910 : Effect.fail(AcpError.AcpRequestError.methodNotFound(method));
911 };
912
913 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
914 stdio: stdio,
915 ...(terminationError ? { terminationError } : {}),
916 serverRequestMethods: new Set(AcpRpcs.CompatClientRpcs.requests.keys()),
917 ...(options.logIncoming !== undefined ? { logIncoming: options.logIncoming } : {}),
918 ...(options.logOutgoing !== undefined ? { logOutgoing: options.logOutgoing } : {}),
919 ...(options.logger ? { logger: options.logger } : {}),
920 ...(options.onIncomingRequest ? { onIncomingRequest: options.onIncomingRequest } : {}),
921 onTermination: (error) =>
922 Effect.all(
923 [
924 ...Array.from(promptCompletions.values(), (completion) =>
925 Deferred.fail(completion, error).pipe(Effect.asVoid),
926 ),
927 options.onTermination?.(error) ?? Effect.void,
928 ],
929 { discard: true },
930 ).pipe(
931 Effect.tap(() =>
932 Effect.sync(() => {
933 promptCompletions.clear();
934 }),
935 ),
936 ),
937 ...(options.onOutgoingResponseFailure
938 ? { onOutgoingResponseFailure: options.onOutgoingResponseFailure }
939 : {}),
940 ...(options.onOutgoingResponse ? { onOutgoingResponse: options.onOutgoingResponse } : {}),
941 transformSessionUpdate: (notification) => {
942 const normalized =
943 negotiatedProtocolGeneration === 1
944 ? normalizeV1SessionUpdate(notification as AcpSchemaV1.SessionNotification)
945 : normalizeSessionUpdate(notification as AcpSchemaV2.UpdateSessionNotification);
946 return options.transformSessionUpdate?.(normalized) ?? normalized;
947 },
948 onNotification: dispatchNotification,
949 onExtRequest: dispatchExtRequest,
950 });
951
952 const requestContext = (
953 requestId: RpcMessage.RequestId,
954 method: string,
955 ): AcpProtocol.AcpRequestContext => ({
956 requestId: AcpProtocol.acpRequestIdentity(requestId),
957 method,
958 });
959
960 const clientHandlerLayer = AcpRpcs.CompatClientRpcs.toLayer(
961 AcpRpcs.CompatClientRpcs.of({
962 [CLIENT_METHODS.session_request_permission]: (payload, { requestId }) =>
963 runHandler(
964 coreHandlers.requestPermission,
965 "toolCall" in payload
966 ? (payload as AcpSchema.RequestPermissionRequest)
967 : normalizePermissionRequest(
968 payload,
969 requestContext(requestId, CLIENT_METHODS.session_request_permission),
970 ),
971 CLIENT_METHODS.session_request_permission,
972 requestContext(requestId, CLIENT_METHODS.session_request_permission),
973 ),
974 [AcpRpcs.V1_CLIENT_METHODS.session_elicitation]: (payload, { requestId }) =>
975 runHandler(
976 coreHandlers.elicitation,
977 payload,
978 AcpRpcs.V1_CLIENT_METHODS.session_elicitation,
979 requestContext(requestId, AcpRpcs.V1_CLIENT_METHODS.session_elicitation),
980 ).pipe(
981 Effect.map(({ _meta, ...action }) => ({
982 action,
983 ...(_meta === undefined ? {} : { _meta }),
984 })),
985 ),
986 [CLIENT_METHODS.elicitation_create]: (payload, { requestId }) =>
987 runHandler(
988 coreHandlers.elicitation,
989 payload,
990 CLIENT_METHODS.elicitation_create,
991 requestContext(requestId, CLIENT_METHODS.elicitation_create),
992 ),
993 [CLIENT_METHODS.mcp_connect]: (payload, { requestId }) =>
994 runHandler(
995 coreHandlers.mcpConnect,
996 payload,
997 CLIENT_METHODS.mcp_connect,
998 requestContext(requestId, CLIENT_METHODS.mcp_connect),
999 ),
1000 [CLIENT_METHODS.mcp_message]: (payload, { requestId }) =>
1001 runHandler(
1002 coreHandlers.mcpMessage,
1003 payload,
1004 CLIENT_METHODS.mcp_message,
1005 requestContext(requestId, CLIENT_METHODS.mcp_message),
1006 ),
1007 [CLIENT_METHODS.mcp_disconnect]: (payload, { requestId }) =>
1008 runHandler(
1009 coreHandlers.mcpDisconnect,
1010 payload,
1011 CLIENT_METHODS.mcp_disconnect,
1012 requestContext(requestId, CLIENT_METHODS.mcp_disconnect),
1013 ),
1014 [AcpRpcs.V1_CLIENT_METHODS.fs_read_text_file]: (payload, { requestId }) =>
1015 runHandler(
1016 coreHandlers.readTextFile,
1017 payload,
1018 AcpRpcs.V1_CLIENT_METHODS.fs_read_text_file,
1019 requestContext(requestId, AcpRpcs.V1_CLIENT_METHODS.fs_read_text_file),
1020 ),
1021 [AcpRpcs.V1_CLIENT_METHODS.fs_write_text_file]: (payload, { requestId }) =>
1022 runHandler(
1023 coreHandlers.writeTextFile,
1024 payload,
1025 AcpRpcs.V1_CLIENT_METHODS.fs_write_text_file,
1026 requestContext(requestId, AcpRpcs.V1_CLIENT_METHODS.fs_write_text_file),
1027 ).pipe(Effect.map((result) => result ?? {})),
1028 [AcpRpcs.V1_CLIENT_METHODS.terminal_create]: (payload, { requestId }) =>
1029 runHandler(
1030 coreHandlers.createTerminal,
1031 payload,
1032 AcpRpcs.V1_CLIENT_METHODS.terminal_create,
1033 requestContext(requestId, AcpRpcs.V1_CLIENT_METHODS.terminal_create),
1034 ),
1035 [AcpRpcs.V1_CLIENT_METHODS.terminal_output]: (payload, { requestId }) =>
1036 runHandler(
1037 coreHandlers.terminalOutput,
1038 payload,
1039 AcpRpcs.V1_CLIENT_METHODS.terminal_output,
1040 requestContext(requestId, AcpRpcs.V1_CLIENT_METHODS.terminal_output),
1041 ),
1042 [AcpRpcs.V1_CLIENT_METHODS.terminal_wait_for_exit]: (payload, { requestId }) =>
1043 runHandler(
1044 coreHandlers.terminalWaitForExit,
1045 payload,
1046 AcpRpcs.V1_CLIENT_METHODS.terminal_wait_for_exit,
1047 requestContext(requestId, AcpRpcs.V1_CLIENT_METHODS.terminal_wait_for_exit),
1048 ),
1049 [AcpRpcs.V1_CLIENT_METHODS.terminal_kill]: (payload, { requestId }) =>
1050 runHandler(
1051 coreHandlers.terminalKill,
1052 payload,
1053 AcpRpcs.V1_CLIENT_METHODS.terminal_kill,
1054 requestContext(requestId, AcpRpcs.V1_CLIENT_METHODS.terminal_kill),
1055 ).pipe(Effect.map((result) => result ?? {})),
1056 [AcpRpcs.V1_CLIENT_METHODS.terminal_release]: (payload, { requestId }) =>
1057 runHandler(
1058 coreHandlers.terminalRelease,
1059 payload,
1060 AcpRpcs.V1_CLIENT_METHODS.terminal_release,
1061 requestContext(requestId, AcpRpcs.V1_CLIENT_METHODS.terminal_release),
1062 ).pipe(Effect.map((result) => result ?? {})),
1063 }),
1064 );
1065
1066 yield* RpcServer.make(AcpRpcs.CompatClientRpcs).pipe(
1067 Effect.provideService(RpcServer.Protocol, transport.serverProtocol),
1068 Effect.provide(clientHandlerLayer),
1069 Effect.forkScoped,
1070 );
1071
1072 let nextRpcRequestId = 2 ** 32;
1073 const rpc = yield* RpcClient.make(AcpRpcs.CompatAgentRpcs, {
1074 generateRequestId: () => RpcMessage.RequestId(nextRpcRequestId++),
1075 }).pipe(Effect.provideService(RpcClient.Protocol, transport.clientProtocol));
1076
1077 return AcpClient.of({
1078 raw: {
1079 notifications: transport.incoming,
1080 request: transport.request,
1081 notify: transport.notify,
1082 },
1083 agent: {
1084 initialize: (payload) =>
1085 callRpc(
1086 AGENT_METHODS.initialize,
1087 rpc[AGENT_METHODS.initialize](toNegotiatingInitializeRequest(payload)),
1088 ).pipe(
1089 Effect.map((response) => {
1090 // ACP v1 protocolVersion values were not generation identifiers in
1091 // every shipped agent. Antigravity, for example, reports version 2
1092 // with the v1 agentInfo/agentCapabilities response shape. The
1093 // response discriminator determines the wire generation reliably.
1094 if (isV2InitializeResponse(response)) {
1095 negotiatedProtocolGeneration = 2;
1096 return normalizeInitializeResponse(response);
1097 }
1098 negotiatedProtocolGeneration = 1;
1099 return response as AcpSchema.InitializeResponse;
1100 }),
1101 ),
1102 authenticate: (payload) =>
1103 negotiatedProtocolGeneration === 1
1104 ? callRpc(
1105 AcpRpcs.V1_AGENT_METHODS.authenticate,
1106 rpc[AcpRpcs.V1_AGENT_METHODS.authenticate](payload),
1107 )
1108 : callRpc(AGENT_METHODS.auth_login, rpc[AGENT_METHODS.auth_login](payload)),
1109 logout: (payload) =>
1110 negotiatedProtocolGeneration === 1
1111 ? callRpc(AcpRpcs.V1_AGENT_METHODS.logout, rpc[AcpRpcs.V1_AGENT_METHODS.logout](payload))
1112 : callRpc(AGENT_METHODS.auth_logout, rpc[AGENT_METHODS.auth_logout](payload)),
1113 createSession: (payload) =>
1114 negotiatedProtocolGeneration === 1
1115 ? callRpc(
1116 AGENT_METHODS.session_new,
1117 rpc[AGENT_METHODS.session_new](payload as AcpSchemaV1.NewSessionRequest),
1118 ).pipe(Effect.map((response) => response as AcpSchema.NewSessionResponse))
1119 : callRpc(
1120 AGENT_METHODS.session_new,
1121 rpc[AGENT_METHODS.session_new]({
1122 ...payload,
1123 mcpServers: payload.mcpServers.map(toV2McpServer),
1124 }),
1125 ).pipe(
1126 Effect.map(
1127 (response) =>
1128 normalizeV2SessionSetupResponse(
1129 response as AcpSchemaV2.NewSessionResponse,
1130 ) as AcpSchema.NewSessionResponse,
1131 ),
1132 ),
1133 loadSession: (payload) =>
1134 negotiatedProtocolGeneration === 1
1135 ? callRpc(
1136 AcpRpcs.V1_AGENT_METHODS.session_load,
1137 rpc[AcpRpcs.V1_AGENT_METHODS.session_load](payload as AcpSchemaV1.LoadSessionRequest),
1138 ).pipe(Effect.map((response) => response as AcpSchema.LoadSessionResponse))
1139 : callRpc(
1140 AGENT_METHODS.session_resume,
1141 rpc[AGENT_METHODS.session_resume](toV2ResumeRequest(payload, { type: "start" })),
1142 ).pipe(
1143 Effect.map(
1144 (response) =>
1145 normalizeV2SessionSetupResponse(
1146 response as AcpSchemaV2.ResumeSessionResponse,
1147 ) as AcpSchema.LoadSessionResponse,
1148 ),
1149 ),
1150 listSessions: (payload) =>
1151 callRpc(AGENT_METHODS.session_list, rpc[AGENT_METHODS.session_list](payload)).pipe(
1152 Effect.map((response) => response as AcpSchema.ListSessionsResponse),
1153 ),
1154 forkSession: (payload) =>
1155 negotiatedProtocolGeneration === 1
1156 ? callRpc(
1157 AGENT_METHODS.session_fork,
1158 rpc[AGENT_METHODS.session_fork](payload as AcpSchemaV1.ForkSessionRequest),
1159 ).pipe(Effect.map((response) => response as AcpSchema.ForkSessionResponse))
1160 : callRpc(
1161 AGENT_METHODS.session_fork,
1162 rpc[AGENT_METHODS.session_fork](toV2ForkRequest(payload)),
1163 ).pipe(
1164 Effect.map(
1165 (response) =>
1166 normalizeV2SessionSetupResponse(
1167 response as AcpSchemaV2.ForkSessionResponse,
1168 ) as AcpSchema.ForkSessionResponse,
1169 ),
1170 ),
1171 resumeSession: (payload) =>
1172 negotiatedProtocolGeneration === 1
1173 ? callRpc(
1174 AGENT_METHODS.session_resume,
1175 rpc[AGENT_METHODS.session_resume](payload as AcpSchemaV1.ResumeSessionRequest),
1176 ).pipe(Effect.map((response) => response as AcpSchema.ResumeSessionResponse))
1177 : callRpc(
1178 AGENT_METHODS.session_resume,
1179 rpc[AGENT_METHODS.session_resume](
1180 toV2ResumeRequest(payload, payload.replayFrom ?? undefined),
1181 ),
1182 ).pipe(
1183 Effect.map(
1184 (response) =>
1185 normalizeV2SessionSetupResponse(
1186 response as AcpSchemaV2.ResumeSessionResponse,
1187 ) as AcpSchema.ResumeSessionResponse,
1188 ),
1189 ),
1190 closeSession: (payload) =>
1191 callRpc(AGENT_METHODS.session_close, rpc[AGENT_METHODS.session_close](payload)).pipe(
1192 Effect.map((response) => response as AcpSchema.CloseSessionResponse),
1193 ),
1194 deleteSession: (payload) =>
1195 negotiatedProtocolGeneration === 1
1196 ? Effect.fail(AcpError.AcpRequestError.methodNotFound(AGENT_METHODS.session_delete))
1197 : callRpc(AGENT_METHODS.session_delete, rpc[AGENT_METHODS.session_delete](payload)),
1198 listProviders: (payload) =>
1199 negotiatedProtocolGeneration === 1
1200 ? Effect.fail(AcpError.AcpRequestError.methodNotFound(AGENT_METHODS.providers_list))
1201 : callRpc(AGENT_METHODS.providers_list, rpc[AGENT_METHODS.providers_list](payload)),
1202 setProvider: (payload) =>
1203 negotiatedProtocolGeneration === 1
1204 ? Effect.fail(AcpError.AcpRequestError.methodNotFound(AGENT_METHODS.providers_set))
1205 : callRpc(AGENT_METHODS.providers_set, rpc[AGENT_METHODS.providers_set](payload)),
1206 disableProvider: (payload) =>
1207 negotiatedProtocolGeneration === 1
1208 ? Effect.fail(AcpError.AcpRequestError.methodNotFound(AGENT_METHODS.providers_disable))
1209 : callRpc(AGENT_METHODS.providers_disable, rpc[AGENT_METHODS.providers_disable](payload)),
1210 setSessionModel: (payload) =>
1211 negotiatedProtocolGeneration === 1
1212 ? callRpc(
1213 AcpRpcs.V1_AGENT_METHODS.session_set_model,
1214 rpc[AcpRpcs.V1_AGENT_METHODS.session_set_model](payload),
1215 )
1216 : Effect.fail(
1217 AcpError.AcpRequestError.methodNotFound(AcpRpcs.V1_AGENT_METHODS.session_set_model),
1218 ),
1219 setSessionConfigOption: (payload) =>
1220 negotiatedProtocolGeneration === 1
1221 ? callRpc(
1222 AGENT_METHODS.session_set_config_option,
1223 rpc[AGENT_METHODS.session_set_config_option](
1224 payload as AcpSchemaV1.SetSessionConfigOptionRequest,
1225 ),
1226 ).pipe(Effect.map((response) => response as AcpSchema.SetSessionConfigOptionResponse))
1227 : callRpc(
1228 AGENT_METHODS.session_set_config_option,
1229 rpc[AGENT_METHODS.session_set_config_option]({
1230 ...payload,
1231 type: "type" in payload && payload.type === "boolean" ? "boolean" : "id",
1232 }),
1233 ).pipe(
1234 Effect.map((response) => ({
1235 configOptions:
1236 normalizeConfigOptions(
1237 (response as AcpSchemaV2.SetSessionConfigOptionResponse).configOptions,
1238 ) ?? [],
1239 })),
1240 ),
1241 prompt: (payload) =>
1242 negotiatedProtocolGeneration === 1
1243 ? callRpc(
1244 AGENT_METHODS.session_prompt,
1245 rpc[AGENT_METHODS.session_prompt](payload as AcpSchemaV1.PromptRequest),
1246 ).pipe(Effect.map((response) => response as AcpSchema.PromptResponse))
1247 : Effect.gen(function* () {
1248 const existing = promptCompletions.get(payload.sessionId);
1249 if (existing !== undefined) {
1250 return yield* AcpError.AcpRequestError.internalError(
1251 `ACP session '${payload.sessionId}' already has an active prompt.`,
1252 );
1253 }
1254 const completion = yield* Deferred.make<
1255 AcpSchema.PromptResponse,
1256 AcpError.AcpError
1257 >();
1258 promptCompletions.set(payload.sessionId, completion);
1259 return yield* callRpc(
1260 AGENT_METHODS.session_prompt,
1261 rpc[AGENT_METHODS.session_prompt](payload as AcpSchemaV2.PromptRequest),
1262 ).pipe(
1263 Effect.andThen(Deferred.await(completion)),
1264 Effect.ensuring(
1265 Effect.sync(() => {
1266 if (promptCompletions.get(payload.sessionId) === completion) {
1267 promptCompletions.delete(payload.sessionId);
1268 }
1269 }),
1270 ),
1271 );
1272 }),
1273 cancel: (payload) => transport.notify(AGENT_METHODS.session_cancel, payload),
1274 },
1275 handleRequestPermission: (handler) =>
1276 Effect.suspend(() => {
1277 coreHandlers.requestPermission = handler;
1278 return Effect.void;
1279 }),
1280 handleElicitation: (handler) =>
1281 Effect.suspend(() => {
1282 coreHandlers.elicitation = handler;
1283 return Effect.void;
1284 }),
1285 handleMcpConnect: (handler) =>
1286 Effect.sync(() => {
1287 coreHandlers.mcpConnect = handler;
1288 }),
1289 handleMcpMessage: (handler) =>
1290 Effect.sync(() => {
1291 coreHandlers.mcpMessage = handler;
1292 }),
1293 handleMcpDisconnect: (handler) =>
1294 Effect.sync(() => {
1295 coreHandlers.mcpDisconnect = handler;
1296 }),
1297 handleMcpNotification: (handler) =>
1298 Effect.sync(() => {
1299 extNotificationHandlers.set(CLIENT_METHODS.mcp_message, (params) =>
1300 Schema.decodeUnknownEffect(AcpSchemaV2.MessageMcpNotification)(params).pipe(
1301 Effect.mapError(() => AcpError.AcpRequestError.invalidParams()),
1302 Effect.flatMap(handler),
1303 ),
1304 );
1305 }),
1306 handleReadTextFile: (handler) =>
1307 Effect.sync(() => {
1308 coreHandlers.readTextFile = handler;
1309 }),
1310 handleWriteTextFile: (handler) =>
1311 Effect.sync(() => {
1312 coreHandlers.writeTextFile = handler;
1313 }),
1314 handleCreateTerminal: (handler) =>
1315 Effect.sync(() => {
1316 coreHandlers.createTerminal = handler;
1317 }),
1318 handleTerminalOutput: (handler) =>
1319 Effect.sync(() => {
1320 coreHandlers.terminalOutput = handler;
1321 }),
1322 handleTerminalWaitForExit: (handler) =>
1323 Effect.sync(() => {
1324 coreHandlers.terminalWaitForExit = handler;
1325 }),
1326 handleTerminalKill: (handler) =>
1327 Effect.sync(() => {
1328 coreHandlers.terminalKill = handler;
1329 }),
1330 handleTerminalRelease: (handler) =>
1331 Effect.sync(() => {
1332 coreHandlers.terminalRelease = handler;
1333 }),
1334 handleSessionUpdate: (handler) =>
1335 Effect.suspend(() => {
1336 notificationHandlers.sessionUpdate.handlers.push(handler);
1337 return flushBufferedNotifications(notificationHandlers.sessionUpdate);
1338 }),
1339 handleElicitationComplete: (handler) =>
1340 Effect.suspend(() => {
1341 notificationHandlers.elicitationComplete.handlers.push(handler);
1342 return flushBufferedNotifications(notificationHandlers.elicitationComplete);
1343 }),
1344 handleUnknownExtRequest: (handler) =>
1345 Effect.suspend(() => {
1346 unknownExtRequestHandler = handler;
1347 return Effect.void;
1348 }),
1349 handleUnknownExtNotification: (handler) =>
1350 Effect.suspend(() => {
1351 unknownExtNotificationHandler = handler;
1352 return Effect.void;
1353 }),
1354 handleExtRequest: (method, payload, handler) =>
1355 Effect.suspend(() => {
1356 extRequestHandlers.set(method, decodeExtRequestRegistration(method, payload, handler));
1357 return Effect.void;
1358 }),
1359 handleExtNotification: (method, payload, handler) =>
1360 Effect.suspend(() => {
1361 extNotificationHandlers.set(
1362 method,
1363 decodeExtNotificationRegistration(method, payload, handler),
1364 );
1365 return Effect.void;
1366 }),
1367 });
1368});
1369
1370export const layerChildProcess = (
1371 handle: ChildProcessSpawner.ChildProcessHandle,
1372 options: AcpClientOptions = {},
1373): Layer.Layer<AcpClient> => {
1374 const stdio = {
1375 ...makeChildStdio(handle),
1376 stdin: options.transformStdout?.(handle.stdout) ?? handle.stdout,
1377 };
1378 const terminationError = makeTerminationError(handle);
1379 return Layer.effect(AcpClient, make(stdio, options, terminationError));
1380};