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