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