Open History to see the last commit
1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as Schema from "effect/Schema";
5import * as Scope from "effect/Scope";
6import * as Stream from "effect/Stream";
7import * as Stdio from "effect/Stdio";
8import * as RpcClient from "effect/unstable/rpc/RpcClient";
9import * as RpcServer from "effect/unstable/rpc/RpcServer";
10
11import * as AcpSchema from "./_generated/schema.gen.ts";
12import { AGENT_METHODS, CLIENT_METHODS } from "./_generated/meta.gen.ts";
13import * as AcpError from "./errors.ts";
14import * as AcpProtocol from "./protocol.ts";
15import * as AcpRpcs from "./rpc.ts";
16import {
17 callRpc,
18 decodeExtNotificationRegistration,
19 decodeExtRequestRegistration,
20 runHandler,
21} from "./_internal/shared.ts";
22import * as AcpTerminal from "./terminal.ts";
23
24export interface AcpAgentOptions {
25 readonly logIncoming?: boolean;
26 readonly logOutgoing?: boolean;
27 readonly logger?: (event: AcpProtocol.AcpProtocolLogEvent) => Effect.Effect<void, never>;
28}
29
30export interface AcpAgentShape {
31 readonly raw: {
32 /**
33 * Stream of inbound ACP notifications observed on the connection.
34 */
35 readonly notifications: Stream.Stream<AcpProtocol.AcpIncomingNotification>;
36 /**
37 * Sends a generic ACP extension request.
38 * @see https://agentclientprotocol.com/protocol/extensibility
39 */
40 readonly request: (
41 method: string,
42 payload: unknown,
43 ) => Effect.Effect<unknown, AcpError.AcpError>;
44 /**
45 * Sends a generic ACP extension notification.
46 * @see https://agentclientprotocol.com/protocol/extensibility
47 */
48 readonly notify: (method: string, payload: unknown) => Effect.Effect<void, AcpError.AcpError>;
49 };
50 readonly client: {
51 /**
52 * Requests client permission for an operation.
53 * @see https://agentclientprotocol.com/protocol/schema#session/request_permission
54 */
55 readonly requestPermission: (
56 payload: AcpSchema.RequestPermissionRequest,
57 ) => Effect.Effect<AcpSchema.RequestPermissionResponse, AcpError.AcpError>;
58 /**
59 * Requests structured user input from the client.
60 * @see https://agentclientprotocol.com/protocol/schema#session/elicitation
61 */
62 readonly elicit: (
63 payload: AcpSchema.ElicitationRequest,
64 ) => Effect.Effect<AcpSchema.ElicitationResponse, AcpError.AcpError>;
65 /**
66 * Requests file contents from the client.
67 * @see https://agentclientprotocol.com/protocol/schema#fs/read_text_file
68 */
69 readonly readTextFile: (
70 payload: AcpSchema.ReadTextFileRequest,
71 ) => Effect.Effect<AcpSchema.ReadTextFileResponse, AcpError.AcpError>;
72 /**
73 * Writes a text file through the client.
74 * @see https://agentclientprotocol.com/protocol/schema#fs/write_text_file
75 */
76 readonly writeTextFile: (
77 payload: AcpSchema.WriteTextFileRequest,
78 ) => Effect.Effect<AcpSchema.WriteTextFileResponse, AcpError.AcpError>;
79 /**
80 * Creates a terminal on the client side.
81 * @see https://agentclientprotocol.com/protocol/schema#terminal/create
82 */
83 readonly createTerminal: (
84 payload: AcpSchema.CreateTerminalRequest,
85 ) => Effect.Effect<AcpTerminal.AcpTerminal, AcpError.AcpError>;
86 /**
87 * Sends a `session/update` notification to the client.
88 * @see https://agentclientprotocol.com/protocol/schema#session/update
89 */
90 readonly sessionUpdate: (
91 payload: AcpSchema.SessionNotification,
92 ) => Effect.Effect<void, AcpError.AcpError>;
93 /**
94 * Sends a `session/elicitation/complete` notification to the client.
95 * @see https://agentclientprotocol.com/protocol/schema#session/elicitation/complete
96 */
97 readonly elicitationComplete: (
98 payload: AcpSchema.ElicitationCompleteNotification,
99 ) => Effect.Effect<void, AcpError.AcpError>;
100 /**
101 * Sends an ACP extension request to the client.
102 * @see https://agentclientprotocol.com/protocol/extensibility
103 */
104 readonly extRequest: (
105 method: string,
106 payload: unknown,
107 ) => Effect.Effect<unknown, AcpError.AcpError>;
108 /**
109 * Sends an ACP extension notification to the client.
110 * @see https://agentclientprotocol.com/protocol/extensibility
111 */
112 readonly extNotification: (
113 method: string,
114 payload: unknown,
115 ) => Effect.Effect<void, AcpError.AcpError>;
116 };
117 /**
118 * Registers a handler for `initialize`.
119 * @see https://agentclientprotocol.com/protocol/schema#initialize
120 */
121 readonly handleInitialize: (
122 handler: (
123 request: AcpSchema.InitializeRequest,
124 ) => Effect.Effect<AcpSchema.InitializeResponse, AcpError.AcpError>,
125 ) => Effect.Effect<void>;
126 /**
127 * Registers a handler for `authenticate`.
128 * @see https://agentclientprotocol.com/protocol/schema#authenticate
129 */
130 readonly handleAuthenticate: (
131 handler: (
132 request: AcpSchema.AuthenticateRequest,
133 ) => Effect.Effect<AcpSchema.AuthenticateResponse, AcpError.AcpError>,
134 ) => Effect.Effect<void>;
135 readonly handleLogout: (
136 handler: (
137 request: AcpSchema.LogoutRequest,
138 ) => Effect.Effect<AcpSchema.LogoutResponse, AcpError.AcpError>,
139 ) => Effect.Effect<void>;
140 readonly handleCreateSession: (
141 handler: (
142 request: AcpSchema.NewSessionRequest,
143 ) => Effect.Effect<AcpSchema.NewSessionResponse, AcpError.AcpError>,
144 ) => Effect.Effect<void>;
145 readonly handleLoadSession: (
146 handler: (
147 request: AcpSchema.LoadSessionRequest,
148 ) => Effect.Effect<AcpSchema.LoadSessionResponse, AcpError.AcpError>,
149 ) => Effect.Effect<void>;
150 readonly handleListSessions: (
151 handler: (
152 request: AcpSchema.ListSessionsRequest,
153 ) => Effect.Effect<AcpSchema.ListSessionsResponse, AcpError.AcpError>,
154 ) => Effect.Effect<void>;
155 readonly handleForkSession: (
156 handler: (
157 request: AcpSchema.ForkSessionRequest,
158 ) => Effect.Effect<AcpSchema.ForkSessionResponse, AcpError.AcpError>,
159 ) => Effect.Effect<void>;
160 readonly handleResumeSession: (
161 handler: (
162 request: AcpSchema.ResumeSessionRequest,
163 ) => Effect.Effect<AcpSchema.ResumeSessionResponse, AcpError.AcpError>,
164 ) => Effect.Effect<void>;
165 readonly handleCloseSession: (
166 handler: (
167 request: AcpSchema.CloseSessionRequest,
168 ) => Effect.Effect<AcpSchema.CloseSessionResponse, AcpError.AcpError>,
169 ) => Effect.Effect<void>;
170 readonly handleSetSessionModel: (
171 handler: (
172 request: AcpSchema.SetSessionModelRequest,
173 ) => Effect.Effect<AcpSchema.SetSessionModelResponse, AcpError.AcpError>,
174 ) => Effect.Effect<void>;
175 readonly handleSetSessionConfigOption: (
176 handler: (
177 request: AcpSchema.SetSessionConfigOptionRequest,
178 ) => Effect.Effect<AcpSchema.SetSessionConfigOptionResponse, AcpError.AcpError>,
179 ) => Effect.Effect<void>;
180 readonly handlePrompt: (
181 handler: (
182 request: AcpSchema.PromptRequest,
183 ) => Effect.Effect<AcpSchema.PromptResponse, AcpError.AcpError>,
184 ) => Effect.Effect<void>;
185 /**
186 * Registers a handler for `session/cancel`.
187 * @see https://agentclientprotocol.com/protocol/schema#session/cancel
188 */
189 readonly handleCancel: (
190 handler: (notification: AcpSchema.CancelNotification) => Effect.Effect<void, AcpError.AcpError>,
191 ) => Effect.Effect<void>;
192 readonly handleUnknownExtRequest: (
193 handler: (method: string, params: unknown) => Effect.Effect<unknown, AcpError.AcpError>,
194 ) => Effect.Effect<void>;
195 readonly handleUnknownExtNotification: (
196 handler: (method: string, params: unknown) => Effect.Effect<void, AcpError.AcpError>,
197 ) => Effect.Effect<void>;
198 readonly handleExtRequest: <A, I>(
199 method: string,
200 payload: Schema.Codec<A, I>,
201 handler: (payload: A) => Effect.Effect<unknown, AcpError.AcpError>,
202 ) => Effect.Effect<void>;
203 readonly handleExtNotification: <A, I>(
204 method: string,
205 payload: Schema.Codec<A, I>,
206 handler: (payload: A) => Effect.Effect<void, AcpError.AcpError>,
207 ) => Effect.Effect<void>;
208}
209
210export class AcpAgent extends Context.Service<AcpAgent, AcpAgentShape>()(
211 "effect-acp/agent/AcpAgent",
212) {}
213
214interface AcpCoreAgentRequestHandlers {
215 initialize?: (
216 request: AcpSchema.InitializeRequest,
217 ) => Effect.Effect<AcpSchema.InitializeResponse, AcpError.AcpError>;
218 authenticate?: (
219 request: AcpSchema.AuthenticateRequest,
220 ) => Effect.Effect<AcpSchema.AuthenticateResponse, AcpError.AcpError>;
221 logout?: (
222 request: AcpSchema.LogoutRequest,
223 ) => Effect.Effect<AcpSchema.LogoutResponse, AcpError.AcpError>;
224 createSession?: (
225 request: AcpSchema.NewSessionRequest,
226 ) => Effect.Effect<AcpSchema.NewSessionResponse, AcpError.AcpError>;
227 loadSession?: (
228 request: AcpSchema.LoadSessionRequest,
229 ) => Effect.Effect<AcpSchema.LoadSessionResponse, AcpError.AcpError>;
230 listSessions?: (
231 request: AcpSchema.ListSessionsRequest,
232 ) => Effect.Effect<AcpSchema.ListSessionsResponse, AcpError.AcpError>;
233 forkSession?: (
234 request: AcpSchema.ForkSessionRequest,
235 ) => Effect.Effect<AcpSchema.ForkSessionResponse, AcpError.AcpError>;
236 resumeSession?: (
237 request: AcpSchema.ResumeSessionRequest,
238 ) => Effect.Effect<AcpSchema.ResumeSessionResponse, AcpError.AcpError>;
239 closeSession?: (
240 request: AcpSchema.CloseSessionRequest,
241 ) => Effect.Effect<AcpSchema.CloseSessionResponse, AcpError.AcpError>;
242 setSessionModel?: (
243 request: AcpSchema.SetSessionModelRequest,
244 ) => Effect.Effect<AcpSchema.SetSessionModelResponse, AcpError.AcpError>;
245 setSessionConfigOption?: (
246 request: AcpSchema.SetSessionConfigOptionRequest,
247 ) => Effect.Effect<AcpSchema.SetSessionConfigOptionResponse, AcpError.AcpError>;
248 prompt?: (
249 request: AcpSchema.PromptRequest,
250 ) => Effect.Effect<AcpSchema.PromptResponse, AcpError.AcpError>;
251}
252
253const decodeCancelNotification = Schema.decodeUnknownEffect(AcpSchema.CancelNotification);
254
255export const make = Effect.fn("effect-acp/AcpAgent.make")(function* (
256 stdio: Stdio.Stdio,
257 options: AcpAgentOptions = {},
258): Effect.fn.Return<AcpAgentShape, never, Scope.Scope> {
259 const coreHandlers: AcpCoreAgentRequestHandlers = {};
260 const cancelHandlers: Array<
261 (notification: AcpSchema.CancelNotification) => Effect.Effect<void, AcpError.AcpError>
262 > = [];
263 const extRequestHandlers = new Map<
264 string,
265 (params: unknown) => Effect.Effect<unknown, AcpError.AcpError>
266 >();
267 const extNotificationHandlers = new Map<
268 string,
269 (params: unknown) => Effect.Effect<void, AcpError.AcpError>
270 >();
271 let unknownExtRequestHandler:
272 | ((method: string, params: unknown) => Effect.Effect<unknown, AcpError.AcpError>)
273 | undefined;
274 let unknownExtNotificationHandler:
275 | ((method: string, params: unknown) => Effect.Effect<void, AcpError.AcpError>)
276 | undefined;
277
278 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
279 stdio,
280 serverRequestMethods: new Set(AcpRpcs.AgentRpcs.requests.keys()),
281 ...(options.logIncoming !== undefined ? { logIncoming: options.logIncoming } : {}),
282 ...(options.logOutgoing !== undefined ? { logOutgoing: options.logOutgoing } : {}),
283 ...(options.logger ? { logger: options.logger } : {}),
284 onNotification: (notification) => {
285 if (
286 notification._tag === "ExtNotification" &&
287 notification.method === AGENT_METHODS.session_cancel
288 ) {
289 return decodeCancelNotification(notification.params).pipe(
290 Effect.mapError(
291 (error) =>
292 new AcpError.AcpProtocolParseError({
293 detail: `Invalid ${AGENT_METHODS.session_cancel} notification payload`,
294 cause: error,
295 }),
296 ),
297 Effect.flatMap((decoded) =>
298 Effect.forEach(cancelHandlers, (handler) => handler(decoded), { discard: true }),
299 ),
300 );
301 }
302
303 if (notification._tag !== "ExtNotification") {
304 return Effect.void;
305 }
306
307 const handler = extNotificationHandlers.get(notification.method);
308 if (handler) {
309 return handler(notification.params);
310 }
311 return unknownExtNotificationHandler
312 ? unknownExtNotificationHandler(notification.method, notification.params)
313 : Effect.void;
314 },
315 onExtRequest: (method, params) => {
316 const handler = extRequestHandlers.get(method);
317 if (handler) {
318 return handler(params);
319 }
320 return unknownExtRequestHandler
321 ? unknownExtRequestHandler(method, params)
322 : Effect.fail(AcpError.AcpRequestError.methodNotFound(method));
323 },
324 });
325
326 const agentHandlerLayer = AcpRpcs.AgentRpcs.toLayer(
327 AcpRpcs.AgentRpcs.of({
328 [AGENT_METHODS.initialize]: (payload) =>
329 runHandler(coreHandlers.initialize, payload, AGENT_METHODS.initialize),
330 [AGENT_METHODS.authenticate]: (payload) =>
331 runHandler(coreHandlers.authenticate, payload, AGENT_METHODS.authenticate),
332 [AGENT_METHODS.logout]: (payload) =>
333 runHandler(coreHandlers.logout, payload, AGENT_METHODS.logout),
334 [AGENT_METHODS.session_new]: (payload) =>
335 runHandler(coreHandlers.createSession, payload, AGENT_METHODS.session_new),
336 [AGENT_METHODS.session_load]: (payload) =>
337 runHandler(coreHandlers.loadSession, payload, AGENT_METHODS.session_load),
338 [AGENT_METHODS.session_list]: (payload) =>
339 runHandler(coreHandlers.listSessions, payload, AGENT_METHODS.session_list),
340 [AGENT_METHODS.session_fork]: (payload) =>
341 runHandler(coreHandlers.forkSession, payload, AGENT_METHODS.session_fork),
342 [AGENT_METHODS.session_resume]: (payload) =>
343 runHandler(coreHandlers.resumeSession, payload, AGENT_METHODS.session_resume),
344 [AGENT_METHODS.session_close]: (payload) =>
345 runHandler(coreHandlers.closeSession, payload, AGENT_METHODS.session_close),
346 [AGENT_METHODS.session_set_model]: (payload) =>
347 runHandler(coreHandlers.setSessionModel, payload, AGENT_METHODS.session_set_model),
348 [AGENT_METHODS.session_set_config_option]: (payload) =>
349 runHandler(
350 coreHandlers.setSessionConfigOption,
351 payload,
352 AGENT_METHODS.session_set_config_option,
353 ),
354 [AGENT_METHODS.session_prompt]: (payload) =>
355 runHandler(coreHandlers.prompt, payload, AGENT_METHODS.session_prompt),
356 }),
357 );
358
359 yield* RpcServer.make(AcpRpcs.AgentRpcs).pipe(
360 Effect.provideService(RpcServer.Protocol, transport.serverProtocol),
361 Effect.provide(agentHandlerLayer),
362 Effect.forkScoped,
363 );
364
365 let nextRpcRequestId = 1n << 32n;
366 const rpc = yield* RpcClient.make(AcpRpcs.ClientRpcs, {
367 generateRequestId: () => nextRpcRequestId++ as never,
368 }).pipe(Effect.provideService(RpcClient.Protocol, transport.clientProtocol));
369
370 return AcpAgent.of({
371 raw: {
372 notifications: transport.incoming,
373 request: transport.request,
374 notify: transport.notify,
375 },
376 client: {
377 requestPermission: (payload) =>
378 callRpc(rpc[CLIENT_METHODS.session_request_permission](payload)),
379 elicit: (payload) => callRpc(rpc[CLIENT_METHODS.session_elicitation](payload)),
380 readTextFile: (payload) => callRpc(rpc[CLIENT_METHODS.fs_read_text_file](payload)),
381 writeTextFile: (payload) => callRpc(rpc[CLIENT_METHODS.fs_write_text_file](payload)),
382 createTerminal: (payload) =>
383 callRpc(rpc[CLIENT_METHODS.terminal_create](payload)).pipe(
384 Effect.map((response) =>
385 AcpTerminal.makeTerminal({
386 sessionId: payload.sessionId,
387 terminalId: response.terminalId,
388 output: callRpc(
389 rpc[CLIENT_METHODS.terminal_output]({
390 sessionId: payload.sessionId,
391 terminalId: response.terminalId,
392 }),
393 ),
394 waitForExit: callRpc(
395 rpc[CLIENT_METHODS.terminal_wait_for_exit]({
396 sessionId: payload.sessionId,
397 terminalId: response.terminalId,
398 }),
399 ),
400 kill: callRpc(
401 rpc[CLIENT_METHODS.terminal_kill]({
402 sessionId: payload.sessionId,
403 terminalId: response.terminalId,
404 }),
405 ),
406 release: callRpc(
407 rpc[CLIENT_METHODS.terminal_release]({
408 sessionId: payload.sessionId,
409 terminalId: response.terminalId,
410 }),
411 ),
412 }),
413 ),
414 ),
415 sessionUpdate: (payload) => transport.notify(CLIENT_METHODS.session_update, payload),
416 elicitationComplete: (payload) =>
417 transport.notify(CLIENT_METHODS.session_elicitation_complete, payload),
418 extRequest: transport.request,
419 extNotification: transport.notify,
420 },
421 handleInitialize: (handler) =>
422 Effect.suspend(() => {
423 coreHandlers.initialize = handler;
424 return Effect.void;
425 }),
426 handleAuthenticate: (handler) =>
427 Effect.suspend(() => {
428 coreHandlers.authenticate = handler;
429 return Effect.void;
430 }),
431 handleLogout: (handler) =>
432 Effect.suspend(() => {
433 coreHandlers.logout = handler;
434 return Effect.void;
435 }),
436 handleCreateSession: (handler) =>
437 Effect.suspend(() => {
438 coreHandlers.createSession = handler;
439 return Effect.void;
440 }),
441 handleLoadSession: (handler) =>
442 Effect.suspend(() => {
443 coreHandlers.loadSession = handler;
444 return Effect.void;
445 }),
446 handleListSessions: (handler) =>
447 Effect.suspend(() => {
448 coreHandlers.listSessions = handler;
449 return Effect.void;
450 }),
451 handleForkSession: (handler) =>
452 Effect.suspend(() => {
453 coreHandlers.forkSession = handler;
454 return Effect.void;
455 }),
456 handleResumeSession: (handler) =>
457 Effect.suspend(() => {
458 coreHandlers.resumeSession = handler;
459 return Effect.void;
460 }),
461 handleCloseSession: (handler) =>
462 Effect.suspend(() => {
463 coreHandlers.closeSession = handler;
464 return Effect.void;
465 }),
466 handleSetSessionModel: (handler) =>
467 Effect.suspend(() => {
468 coreHandlers.setSessionModel = handler;
469 return Effect.void;
470 }),
471 handleSetSessionConfigOption: (handler) =>
472 Effect.suspend(() => {
473 coreHandlers.setSessionConfigOption = handler;
474 return Effect.void;
475 }),
476 handlePrompt: (handler) =>
477 Effect.suspend(() => {
478 coreHandlers.prompt = handler;
479 return Effect.void;
480 }),
481 handleCancel: (handler) =>
482 Effect.suspend(() => {
483 cancelHandlers.push(handler);
484 return Effect.void;
485 }),
486 handleUnknownExtRequest: (handler) =>
487 Effect.suspend(() => {
488 unknownExtRequestHandler = handler;
489 return Effect.void;
490 }),
491 handleUnknownExtNotification: (handler) =>
492 Effect.suspend(() => {
493 unknownExtNotificationHandler = handler;
494 return Effect.void;
495 }),
496 handleExtRequest: (method, payload, handler) =>
497 Effect.suspend(() => {
498 extRequestHandlers.set(method, decodeExtRequestRegistration(method, payload, handler));
499 return Effect.void;
500 }),
501 handleExtNotification: (method, payload, handler) =>
502 Effect.suspend(() => {
503 extNotificationHandlers.set(
504 method,
505 decodeExtNotificationRegistration(method, payload, handler),
506 );
507 return Effect.void;
508 }),
509 });
510});
511
512export const layer = (stdio: Stdio.Stdio, options: AcpAgentOptions = {}): Layer.Layer<AcpAgent> =>
513 Layer.effect(AcpAgent, make(stdio, options));
514
515export const layerStdio = (
516 options: AcpAgentOptions = {},
517): Layer.Layer<AcpAgent, never, Stdio.Stdio> =>
518 Layer.effect(
519 AcpAgent,
520 Effect.flatMap(Effect.service(Stdio.Stdio), (stdio) => make(stdio, options)),
521 );