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