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.error === undefined ? {} : { error: idle.error }),
801 ...(idle._meta === undefined ? {} : { _meta: idle._meta }),
802 }).pipe(Effect.asVoid);
803 })
804 : Effect.void;
805 if (notificationHandlers.sessionUpdate.handlers.length === 0) {
806 notificationHandlers.sessionUpdate.pending.push(normalized);
807 return completePrompt;
808 }
809 return Effect.all(
810 [completePrompt, runNotificationHandlers(notificationHandlers.sessionUpdate, normalized)],
811 { discard: true },
812 );
813 }
814 case "ElicitationComplete": {
815 if (notificationHandlers.elicitationComplete.handlers.length === 0) {
816 notificationHandlers.elicitationComplete.pending.push(notification.params);
817 return Effect.void;
818 }
819 return runNotificationHandlers(
820 notificationHandlers.elicitationComplete,
821 notification.params,
822 );
823 }
824 case "ExtNotification": {
825 const handler = extNotificationHandlers.get(notification.method);
826 if (handler) {
827 return handler(notification.params);
828 }
829 return unknownExtNotificationHandler
830 ? unknownExtNotificationHandler(notification.method, notification.params)
831 : Effect.void;
832 }
833 }
834 };
835
836 const dispatchExtRequest = (
837 method: string,
838 params: unknown,
839 context: AcpProtocol.AcpRequestContext,
840 ) => {
841 const handler = extRequestHandlers.get(method);
842 if (handler) {
843 return handler(params, context);
844 }
845 return unknownExtRequestHandler
846 ? unknownExtRequestHandler(method, params, context)
847 : Effect.fail(AcpError.AcpRequestError.methodNotFound(method));
848 };
849
850 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
851 stdio: stdio,
852 ...(terminationError ? { terminationError } : {}),
853 serverRequestMethods: new Set(AcpRpcs.CompatClientRpcs.requests.keys()),
854 ...(options.logIncoming !== undefined ? { logIncoming: options.logIncoming } : {}),
855 ...(options.logOutgoing !== undefined ? { logOutgoing: options.logOutgoing } : {}),
856 ...(options.logger ? { logger: options.logger } : {}),
857 ...(options.onIncomingRequest ? { onIncomingRequest: options.onIncomingRequest } : {}),
858 onTermination: (error) =>
859 Effect.all(
860 [
861 ...Array.from(promptCompletions.values(), (completion) =>
862 Deferred.fail(completion, error).pipe(Effect.asVoid),
863 ),
864 options.onTermination?.(error) ?? Effect.void,
865 ],
866 { discard: true },
867 ).pipe(
868 Effect.tap(() =>
869 Effect.sync(() => {
870 promptCompletions.clear();
871 }),
872 ),
873 ),
874 ...(options.onOutgoingResponseFailure
875 ? { onOutgoingResponseFailure: options.onOutgoingResponseFailure }
876 : {}),
877 ...(options.onOutgoingResponse ? { onOutgoingResponse: options.onOutgoingResponse } : {}),
878 transformSessionUpdate: (notification) => {
879 const normalized =
880 negotiatedProtocolGeneration === 1
881 ? normalizeV1SessionUpdate(notification as AcpSchemaV1.SessionNotification)
882 : normalizeSessionUpdate(notification as AcpSchemaV2.UpdateSessionNotification);
883 return options.transformSessionUpdate?.(normalized) ?? normalized;
884 },
885 onNotification: dispatchNotification,
886 onExtRequest: dispatchExtRequest,
887 });
888
889 const requestContext = (
890 requestId: RpcMessage.RequestId,
891 method: string,
892 ): AcpProtocol.AcpRequestContext => ({
893 requestId: AcpProtocol.acpRequestIdentity(requestId),
894 method,
895 });
896
897 const layerClientHandler = AcpRpcs.CompatClientRpcs.toLayer(
898 AcpRpcs.CompatClientRpcs.of({
899 [CLIENT_METHODS.session_request_permission]: (payload, { requestId }) =>
900 runHandler(
901 coreHandlers.requestPermission,
902 "toolCall" in payload
903 ? (payload as AcpSchema.RequestPermissionRequest)
904 : normalizePermissionRequest(
905 payload,
906 requestContext(requestId, CLIENT_METHODS.session_request_permission),
907 ),
908 CLIENT_METHODS.session_request_permission,
909 requestContext(requestId, CLIENT_METHODS.session_request_permission),
910 ),
911 [AcpRpcs.V1_CLIENT_METHODS.session_elicitation]: (payload, { requestId }) =>
912 runHandler(
913 coreHandlers.elicitation,
914 payload,
915 AcpRpcs.V1_CLIENT_METHODS.session_elicitation,
916 requestContext(requestId, AcpRpcs.V1_CLIENT_METHODS.session_elicitation),
917 ).pipe(
918 Effect.map(({ _meta, ...action }) => ({
919 action,
920 ...(_meta === undefined ? {} : { _meta }),
921 })),
922 ),
923 [AcpRpcs.V1_CLIENT_METHODS.unstable_session_elicitation]: (payload, { requestId }) =>
924 runHandler(
925 coreHandlers.elicitation,
926 payload,
927 AcpRpcs.V1_CLIENT_METHODS.unstable_session_elicitation,
928 requestContext(requestId, AcpRpcs.V1_CLIENT_METHODS.unstable_session_elicitation),
929 ).pipe(
930 Effect.map(({ _meta, ...action }) => ({
931 action,
932 ...(_meta === undefined ? {} : { _meta }),
933 })),
934 ),
935 [CLIENT_METHODS.elicitation_create]: (payload, { requestId }) =>
936 decodeElicitationRequest(payload).pipe(
937 Effect.mapError((cause) =>
938 AcpError.AcpRequestError.invalidExtensionPayload(
939 CLIENT_METHODS.elicitation_create,
940 cause,
941 ).toProtocolError(),
942 ),
943 Effect.flatMap((request) =>
944 runHandler(
945 coreHandlers.elicitation,
946 request,
947 CLIENT_METHODS.elicitation_create,
948 requestContext(requestId, CLIENT_METHODS.elicitation_create),
949 ),
950 ),
951 ),
952 [CLIENT_METHODS.mcp_connect]: (payload, { requestId }) =>
953 runHandler(
954 coreHandlers.mcpConnect,
955 payload,
956 CLIENT_METHODS.mcp_connect,
957 requestContext(requestId, CLIENT_METHODS.mcp_connect),
958 ),
959 [CLIENT_METHODS.mcp_message]: (payload, { requestId }) =>
960 runHandler(
961 coreHandlers.mcpMessage,
962 payload,
963 CLIENT_METHODS.mcp_message,
964 requestContext(requestId, CLIENT_METHODS.mcp_message),
965 ),
966 [CLIENT_METHODS.mcp_disconnect]: (payload, { requestId }) =>
967 runHandler(
968 coreHandlers.mcpDisconnect,
969 payload,
970 CLIENT_METHODS.mcp_disconnect,
971 requestContext(requestId, CLIENT_METHODS.mcp_disconnect),
972 ),
973 [AcpRpcs.V1_CLIENT_METHODS.fs_read_text_file]: (payload, { requestId }) =>
974 runHandler(
975 coreHandlers.readTextFile,
976 payload,
977 AcpRpcs.V1_CLIENT_METHODS.fs_read_text_file,
978 requestContext(requestId, AcpRpcs.V1_CLIENT_METHODS.fs_read_text_file),
979 ),
980 [AcpRpcs.V1_CLIENT_METHODS.fs_write_text_file]: (payload, { requestId }) =>
981 runHandler(
982 coreHandlers.writeTextFile,
983 payload,
984 AcpRpcs.V1_CLIENT_METHODS.fs_write_text_file,
985 requestContext(requestId, AcpRpcs.V1_CLIENT_METHODS.fs_write_text_file),
986 ).pipe(Effect.map((result) => result ?? {})),
987 [AcpRpcs.V1_CLIENT_METHODS.terminal_create]: (payload, { requestId }) =>
988 runHandler(
989 coreHandlers.createTerminal,
990 payload,
991 AcpRpcs.V1_CLIENT_METHODS.terminal_create,
992 requestContext(requestId, AcpRpcs.V1_CLIENT_METHODS.terminal_create),
993 ),
994 [AcpRpcs.V1_CLIENT_METHODS.terminal_output]: (payload, { requestId }) =>
995 runHandler(
996 coreHandlers.terminalOutput,
997 payload,
998 AcpRpcs.V1_CLIENT_METHODS.terminal_output,
999 requestContext(requestId, AcpRpcs.V1_CLIENT_METHODS.terminal_output),
1000 ),
1001 [AcpRpcs.V1_CLIENT_METHODS.terminal_wait_for_exit]: (payload, { requestId }) =>
1002 runHandler(
1003 coreHandlers.terminalWaitForExit,
1004 payload,
1005 AcpRpcs.V1_CLIENT_METHODS.terminal_wait_for_exit,
1006 requestContext(requestId, AcpRpcs.V1_CLIENT_METHODS.terminal_wait_for_exit),
1007 ),
1008 [AcpRpcs.V1_CLIENT_METHODS.terminal_kill]: (payload, { requestId }) =>
1009 runHandler(
1010 coreHandlers.terminalKill,
1011 payload,
1012 AcpRpcs.V1_CLIENT_METHODS.terminal_kill,
1013 requestContext(requestId, AcpRpcs.V1_CLIENT_METHODS.terminal_kill),
1014 ).pipe(Effect.map((result) => result ?? {})),
1015 [AcpRpcs.V1_CLIENT_METHODS.terminal_release]: (payload, { requestId }) =>
1016 runHandler(
1017 coreHandlers.terminalRelease,
1018 payload,
1019 AcpRpcs.V1_CLIENT_METHODS.terminal_release,
1020 requestContext(requestId, AcpRpcs.V1_CLIENT_METHODS.terminal_release),
1021 ).pipe(Effect.map((result) => result ?? {})),
1022 }),
1023 );
1024
1025 yield* RpcServer.make(AcpRpcs.CompatClientRpcs, { disableFatalDefects: true }).pipe(
1026 // runHandler logs handler defects with their method. A reporter inherited
1027 // from the caller (a WebSocket request, say) would log them again.
1028 Effect.provideService(ErrorReporter.CurrentErrorReporters, new Set()),
1029 Effect.provideService(RpcServer.Protocol, transport.serverProtocol),
1030 Effect.provide(layerClientHandler),
1031 Effect.forkScoped,
1032 );
1033
1034 let nextRpcRequestId = AcpProtocol.RPC_REQUEST_ID_START;
1035 const rpc = yield* RpcClient.make(AcpRpcs.CompatAgentRpcs, {
1036 generateRequestId: () => RpcMessage.RequestId(nextRpcRequestId++),
1037 }).pipe(Effect.provideService(RpcClient.Protocol, transport.clientProtocol));
1038
1039 return AcpClient.of({
1040 raw: {
1041 notifications: transport.incoming,
1042 request: transport.request,
1043 notify: transport.notify,
1044 },
1045 agent: {
1046 initialize: (payload) =>
1047 callRpc(
1048 AGENT_METHODS.initialize,
1049 rpc[AGENT_METHODS.initialize](toNegotiatingInitializeRequest(payload)),
1050 ).pipe(
1051 Effect.map((response) => {
1052 // ACP v1 protocolVersion values were not generation identifiers in
1053 // every shipped agent. Antigravity, for example, reports version 2
1054 // with the v1 agentInfo/agentCapabilities response shape.
1055 if (isV2InitializeResponse(response)) {
1056 negotiatedProtocolGeneration = 2;
1057 return normalizeInitializeResponse(response);
1058 }
1059 negotiatedProtocolGeneration = 1;
1060 return response as AcpSchema.InitializeResponse;
1061 }),
1062 ),
1063 authenticate: (payload) =>
1064 negotiatedProtocolGeneration === 1
1065 ? callRpc(
1066 AcpRpcs.V1_AGENT_METHODS.authenticate,
1067 rpc[AcpRpcs.V1_AGENT_METHODS.authenticate](payload),
1068 )
1069 : callRpc(AGENT_METHODS.auth_login, rpc[AGENT_METHODS.auth_login](payload)),
1070 logout: (payload) =>
1071 negotiatedProtocolGeneration === 1
1072 ? callRpc(AcpRpcs.V1_AGENT_METHODS.logout, rpc[AcpRpcs.V1_AGENT_METHODS.logout](payload))
1073 : callRpc(AGENT_METHODS.auth_logout, rpc[AGENT_METHODS.auth_logout](payload)),
1074 createSession: (payload) =>
1075 negotiatedProtocolGeneration === 1
1076 ? callRpc(
1077 AGENT_METHODS.session_new,
1078 rpc[AGENT_METHODS.session_new](payload as AcpSchemaV1.NewSessionRequest),
1079 ).pipe(Effect.map((response) => response as AcpSchema.NewSessionResponse))
1080 : callRpc(
1081 AGENT_METHODS.session_new,
1082 rpc[AGENT_METHODS.session_new]({
1083 ...payload,
1084 mcpServers: payload.mcpServers.map(toV2McpServer),
1085 }),
1086 ).pipe(
1087 Effect.map(
1088 (response) =>
1089 normalizeV2SessionSetupResponse(
1090 response as AcpSchemaV2.NewSessionResponse,
1091 ) as AcpSchema.NewSessionResponse,
1092 ),
1093 ),
1094 loadSession: (payload) =>
1095 negotiatedProtocolGeneration === 1
1096 ? callRpc(
1097 AcpRpcs.V1_AGENT_METHODS.session_load,
1098 rpc[AcpRpcs.V1_AGENT_METHODS.session_load](payload as AcpSchemaV1.LoadSessionRequest),
1099 ).pipe(Effect.map((response) => response as AcpSchema.LoadSessionResponse))
1100 : callRpc(
1101 AGENT_METHODS.session_resume,
1102 rpc[AGENT_METHODS.session_resume](toV2ResumeRequest(payload, { type: "start" })),
1103 ).pipe(
1104 Effect.map(
1105 (response) =>
1106 normalizeV2SessionSetupResponse(
1107 response as AcpSchemaV2.ResumeSessionResponse,
1108 ) as AcpSchema.LoadSessionResponse,
1109 ),
1110 ),
1111 listSessions: (payload) =>
1112 callRpc(AGENT_METHODS.session_list, rpc[AGENT_METHODS.session_list](payload)).pipe(
1113 Effect.map((response) => response as AcpSchema.ListSessionsResponse),
1114 ),
1115 forkSession: (payload) =>
1116 negotiatedProtocolGeneration === 1
1117 ? callRpc(
1118 AGENT_METHODS.session_fork,
1119 rpc[AGENT_METHODS.session_fork](payload as AcpSchemaV1.ForkSessionRequest),
1120 ).pipe(Effect.map((response) => response as AcpSchema.ForkSessionResponse))
1121 : callRpc(
1122 AGENT_METHODS.session_fork,
1123 rpc[AGENT_METHODS.session_fork](toV2ForkRequest(payload)),
1124 ).pipe(
1125 Effect.map(
1126 (response) =>
1127 normalizeV2SessionSetupResponse(
1128 response as AcpSchemaV2.ForkSessionResponse,
1129 ) as AcpSchema.ForkSessionResponse,
1130 ),
1131 ),
1132 resumeSession: (payload) =>
1133 negotiatedProtocolGeneration === 1
1134 ? callRpc(
1135 AGENT_METHODS.session_resume,
1136 rpc[AGENT_METHODS.session_resume](payload as AcpSchemaV1.ResumeSessionRequest),
1137 ).pipe(Effect.map((response) => response as AcpSchema.ResumeSessionResponse))
1138 : callRpc(
1139 AGENT_METHODS.session_resume,
1140 rpc[AGENT_METHODS.session_resume](
1141 toV2ResumeRequest(payload, payload.replayFrom ?? undefined),
1142 ),
1143 ).pipe(
1144 Effect.map(
1145 (response) =>
1146 normalizeV2SessionSetupResponse(
1147 response as AcpSchemaV2.ResumeSessionResponse,
1148 ) as AcpSchema.ResumeSessionResponse,
1149 ),
1150 ),
1151 closeSession: (payload) =>
1152 callRpc(AGENT_METHODS.session_close, rpc[AGENT_METHODS.session_close](payload)).pipe(
1153 Effect.map((response) => response as AcpSchema.CloseSessionResponse),
1154 ),
1155 deleteSession: (payload) =>
1156 negotiatedProtocolGeneration === 1
1157 ? Effect.fail(AcpError.AcpRequestError.methodNotFound(AGENT_METHODS.session_delete))
1158 : callRpc(AGENT_METHODS.session_delete, rpc[AGENT_METHODS.session_delete](payload)),
1159 listProviders: (payload) =>
1160 negotiatedProtocolGeneration === 1
1161 ? Effect.fail(AcpError.AcpRequestError.methodNotFound(AGENT_METHODS.providers_list))
1162 : callRpc(AGENT_METHODS.providers_list, rpc[AGENT_METHODS.providers_list](payload)),
1163 setProvider: (payload) =>
1164 negotiatedProtocolGeneration === 1
1165 ? Effect.fail(AcpError.AcpRequestError.methodNotFound(AGENT_METHODS.providers_set))
1166 : callRpc(AGENT_METHODS.providers_set, rpc[AGENT_METHODS.providers_set](payload)),
1167 disableProvider: (payload) =>
1168 negotiatedProtocolGeneration === 1
1169 ? Effect.fail(AcpError.AcpRequestError.methodNotFound(AGENT_METHODS.providers_disable))
1170 : callRpc(AGENT_METHODS.providers_disable, rpc[AGENT_METHODS.providers_disable](payload)),
1171 setSessionModel: (payload) =>
1172 negotiatedProtocolGeneration === 1
1173 ? callRpc(
1174 AcpRpcs.V1_AGENT_METHODS.session_set_model,
1175 rpc[AcpRpcs.V1_AGENT_METHODS.session_set_model](payload),
1176 )
1177 : Effect.fail(
1178 AcpError.AcpRequestError.methodNotFound(AcpRpcs.V1_AGENT_METHODS.session_set_model),
1179 ),
1180 setSessionMode: (payload) =>
1181 negotiatedProtocolGeneration === 1
1182 ? callRpc(
1183 AcpRpcs.V1_AGENT_METHODS.session_set_mode,
1184 rpc[AcpRpcs.V1_AGENT_METHODS.session_set_mode](payload),
1185 )
1186 : Effect.fail(
1187 AcpError.AcpRequestError.methodNotFound(AcpRpcs.V1_AGENT_METHODS.session_set_mode),
1188 ),
1189 setSessionConfigOption: (payload) =>
1190 negotiatedProtocolGeneration === 1
1191 ? callRpc(
1192 AGENT_METHODS.session_set_config_option,
1193 rpc[AGENT_METHODS.session_set_config_option](
1194 payload as AcpSchemaV1.SetSessionConfigOptionRequest,
1195 ),
1196 ).pipe(Effect.map((response) => response as AcpSchema.SetSessionConfigOptionResponse))
1197 : callRpc(
1198 AGENT_METHODS.session_set_config_option,
1199 rpc[AGENT_METHODS.session_set_config_option]({
1200 ...payload,
1201 type: "type" in payload && payload.type === "boolean" ? "boolean" : "id",
1202 }),
1203 ).pipe(
1204 Effect.map((response) => ({
1205 configOptions:
1206 normalizeConfigOptions(
1207 (response as AcpSchemaV2.SetSessionConfigOptionResponse).configOptions,
1208 ) ?? [],
1209 })),
1210 ),
1211 prompt: (payload) =>
1212 negotiatedProtocolGeneration === 1
1213 ? callRpc(
1214 AGENT_METHODS.session_prompt,
1215 rpc[AGENT_METHODS.session_prompt](payload as AcpSchemaV1.PromptRequest),
1216 ).pipe(Effect.map((response) => response as AcpSchema.PromptResponse))
1217 : Effect.gen(function* () {
1218 const existing = promptCompletions.get(payload.sessionId);
1219 if (existing !== undefined) {
1220 return yield* AcpError.AcpRequestError.internalError(
1221 `ACP session '${payload.sessionId}' already has an active prompt.`,
1222 );
1223 }
1224 const completion = yield* Deferred.make<
1225 AcpSchema.PromptResponse,
1226 AcpError.AcpError
1227 >();
1228 promptCompletions.set(payload.sessionId, completion);
1229 return yield* callRpc(
1230 AGENT_METHODS.session_prompt,
1231 rpc[AGENT_METHODS.session_prompt](payload as AcpSchemaV2.PromptRequest),
1232 ).pipe(
1233 Effect.andThen(Deferred.await(completion)),
1234 Effect.ensuring(
1235 Effect.sync(() => {
1236 if (promptCompletions.get(payload.sessionId) === completion) {
1237 promptCompletions.delete(payload.sessionId);
1238 }
1239 }),
1240 ),
1241 );
1242 }),
1243 cancel: (payload) => transport.notify(AGENT_METHODS.session_cancel, payload),
1244 },
1245 handleRequestPermission: (handler) =>
1246 Effect.suspend(() => {
1247 coreHandlers.requestPermission = handler;
1248 return Effect.void;
1249 }),
1250 handleElicitation: (handler) =>
1251 Effect.suspend(() => {
1252 coreHandlers.elicitation = handler;
1253 return Effect.void;
1254 }),
1255 handleMcpConnect: (handler) =>
1256 Effect.sync(() => {
1257 coreHandlers.mcpConnect = handler;
1258 }),
1259 handleMcpMessage: (handler) =>
1260 Effect.sync(() => {
1261 coreHandlers.mcpMessage = handler;
1262 }),
1263 handleMcpDisconnect: (handler) =>
1264 Effect.sync(() => {
1265 coreHandlers.mcpDisconnect = handler;
1266 }),
1267 handleMcpNotification: (handler) =>
1268 Effect.sync(() => {
1269 extNotificationHandlers.set(CLIENT_METHODS.mcp_message, (params) =>
1270 Schema.decodeUnknownEffect(AcpSchemaV2.MessageMcpNotification)(params).pipe(
1271 Effect.mapError(() => AcpError.AcpRequestError.invalidParams()),
1272 Effect.flatMap(handler),
1273 ),
1274 );
1275 }),
1276 handleReadTextFile: (handler) =>
1277 Effect.sync(() => {
1278 coreHandlers.readTextFile = handler;
1279 }),
1280 handleWriteTextFile: (handler) =>
1281 Effect.sync(() => {
1282 coreHandlers.writeTextFile = handler;
1283 }),
1284 handleCreateTerminal: (handler) =>
1285 Effect.sync(() => {
1286 coreHandlers.createTerminal = handler;
1287 }),
1288 handleTerminalOutput: (handler) =>
1289 Effect.sync(() => {
1290 coreHandlers.terminalOutput = handler;
1291 }),
1292 handleTerminalWaitForExit: (handler) =>
1293 Effect.sync(() => {
1294 coreHandlers.terminalWaitForExit = handler;
1295 }),
1296 handleTerminalKill: (handler) =>
1297 Effect.sync(() => {
1298 coreHandlers.terminalKill = handler;
1299 }),
1300 handleTerminalRelease: (handler) =>
1301 Effect.sync(() => {
1302 coreHandlers.terminalRelease = handler;
1303 }),
1304 handleSessionUpdate: (handler) =>
1305 Effect.suspend(() => {
1306 notificationHandlers.sessionUpdate.handlers.push(handler);
1307 return flushBufferedNotifications(notificationHandlers.sessionUpdate);
1308 }),
1309 handleElicitationComplete: (handler) =>
1310 Effect.suspend(() => {
1311 notificationHandlers.elicitationComplete.handlers.push(handler);
1312 return flushBufferedNotifications(notificationHandlers.elicitationComplete);
1313 }),
1314 handleUnknownExtRequest: (handler) =>
1315 Effect.suspend(() => {
1316 unknownExtRequestHandler = handler;
1317 return Effect.void;
1318 }),
1319 handleUnknownExtNotification: (handler) =>
1320 Effect.suspend(() => {
1321 unknownExtNotificationHandler = handler;
1322 return Effect.void;
1323 }),
1324 handleExtRequest: (method, payload, handler) =>
1325 Effect.suspend(() => {
1326 extRequestHandlers.set(method, decodeExtRequestRegistration(method, payload, handler));
1327 return Effect.void;
1328 }),
1329 handleExtNotification: (method, payload, handler) =>
1330 Effect.suspend(() => {
1331 extNotificationHandlers.set(
1332 method,
1333 decodeExtNotificationRegistration(method, payload, handler),
1334 );
1335 return Effect.void;
1336 }),
1337 });
1338});
1339
1340export const layerChildProcess = (
1341 handle: ChildProcessSpawner.ChildProcessHandle,
1342 options: AcpClientOptions = {},
1343): Layer.Layer<AcpClient> => {
1344 const stdio = {
1345 ...makeChildStdio(handle),
1346 stdin: options.transformStdout?.(handle.stdout) ?? handle.stdout,
1347 };
1348 const terminationError = makeTerminationError(handle);
1349 return Layer.effect(AcpClient, make(stdio, options, terminationError));
1350};