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

client.ts

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