The best way to control Claude Code, Codex and more from any computer or phone

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