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