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

client.ts

1,425 lines54.3 KB

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