Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

client.ts

1,374 lines52.9 KB

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