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>()("effect-acp/AcpAgent") {}
211
212interface AcpCoreAgentRequestHandlers {
213 initialize?: (
214 request: AcpSchema.InitializeRequest,
215 ) => Effect.Effect<AcpSchema.InitializeResponse, AcpError.AcpError>;
216 authenticate?: (
217 request: AcpSchema.AuthenticateRequest,
218 ) => Effect.Effect<AcpSchema.AuthenticateResponse, AcpError.AcpError>;
219 logout?: (
220 request: AcpSchema.LogoutRequest,
221 ) => Effect.Effect<AcpSchema.LogoutResponse, AcpError.AcpError>;
222 createSession?: (
223 request: AcpSchema.NewSessionRequest,
224 ) => Effect.Effect<AcpSchema.NewSessionResponse, AcpError.AcpError>;
225 loadSession?: (
226 request: AcpSchema.LoadSessionRequest,
227 ) => Effect.Effect<AcpSchema.LoadSessionResponse, AcpError.AcpError>;
228 listSessions?: (
229 request: AcpSchema.ListSessionsRequest,
230 ) => Effect.Effect<AcpSchema.ListSessionsResponse, AcpError.AcpError>;
231 forkSession?: (
232 request: AcpSchema.ForkSessionRequest,
233 ) => Effect.Effect<AcpSchema.ForkSessionResponse, AcpError.AcpError>;
234 resumeSession?: (
235 request: AcpSchema.ResumeSessionRequest,
236 ) => Effect.Effect<AcpSchema.ResumeSessionResponse, AcpError.AcpError>;
237 closeSession?: (
238 request: AcpSchema.CloseSessionRequest,
239 ) => Effect.Effect<AcpSchema.CloseSessionResponse, AcpError.AcpError>;
240 setSessionModel?: (
241 request: AcpSchema.SetSessionModelRequest,
242 ) => Effect.Effect<AcpSchema.SetSessionModelResponse, AcpError.AcpError>;
243 setSessionConfigOption?: (
244 request: AcpSchema.SetSessionConfigOptionRequest,
245 ) => Effect.Effect<AcpSchema.SetSessionConfigOptionResponse, AcpError.AcpError>;
246 prompt?: (
247 request: AcpSchema.PromptRequest,
248 ) => Effect.Effect<AcpSchema.PromptResponse, AcpError.AcpError>;
249}
250
251const decodeCancelNotification = Schema.decodeUnknownEffect(AcpSchema.CancelNotification);
252
253export const make = Effect.fn("effect-acp/AcpAgent.make")(function* (
254 stdio: Stdio.Stdio,
255 options: AcpAgentOptions = {},
256): Effect.fn.Return<AcpAgentShape, never, Scope.Scope> {
257 const coreHandlers: AcpCoreAgentRequestHandlers = {};
258 const cancelHandlers: Array<
259 (notification: AcpSchema.CancelNotification) => Effect.Effect<void, AcpError.AcpError>
260 > = [];
261 const extRequestHandlers = new Map<
262 string,
263 (params: unknown) => Effect.Effect<unknown, AcpError.AcpError>
264 >();
265 const extNotificationHandlers = new Map<
266 string,
267 (params: unknown) => Effect.Effect<void, AcpError.AcpError>
268 >();
269 let unknownExtRequestHandler:
270 | ((method: string, params: unknown) => Effect.Effect<unknown, AcpError.AcpError>)
271 | undefined;
272 let unknownExtNotificationHandler:
273 | ((method: string, params: unknown) => Effect.Effect<void, AcpError.AcpError>)
274 | undefined;
275
276 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
277 stdio,
278 serverRequestMethods: new Set(AcpRpcs.AgentRpcs.requests.keys()),
279 ...(options.logIncoming !== undefined ? { logIncoming: options.logIncoming } : {}),
280 ...(options.logOutgoing !== undefined ? { logOutgoing: options.logOutgoing } : {}),
281 ...(options.logger ? { logger: options.logger } : {}),
282 onNotification: (notification) => {
283 if (
284 notification._tag === "ExtNotification" &&
285 notification.method === AGENT_METHODS.session_cancel
286 ) {
287 return decodeCancelNotification(notification.params).pipe(
288 Effect.mapError(
289 (error) =>
290 new AcpError.AcpProtocolParseError({
291 detail: `Invalid ${AGENT_METHODS.session_cancel} notification payload`,
292 cause: error,
293 }),
294 ),
295 Effect.flatMap((decoded) =>
296 Effect.forEach(cancelHandlers, (handler) => handler(decoded), { discard: true }),
297 ),
298 );
299 }
300
301 if (notification._tag !== "ExtNotification") {
302 return Effect.void;
303 }
304
305 const handler = extNotificationHandlers.get(notification.method);
306 if (handler) {
307 return handler(notification.params);
308 }
309 return unknownExtNotificationHandler
310 ? unknownExtNotificationHandler(notification.method, notification.params)
311 : Effect.void;
312 },
313 onExtRequest: (method, params) => {
314 const handler = extRequestHandlers.get(method);
315 if (handler) {
316 return handler(params);
317 }
318 return unknownExtRequestHandler
319 ? unknownExtRequestHandler(method, params)
320 : Effect.fail(AcpError.AcpRequestError.methodNotFound(method));
321 },
322 });
323
324 const agentHandlerLayer = AcpRpcs.AgentRpcs.toLayer(
325 AcpRpcs.AgentRpcs.of({
326 [AGENT_METHODS.initialize]: (payload) =>
327 runHandler(coreHandlers.initialize, payload, AGENT_METHODS.initialize),
328 [AGENT_METHODS.authenticate]: (payload) =>
329 runHandler(coreHandlers.authenticate, payload, AGENT_METHODS.authenticate),
330 [AGENT_METHODS.logout]: (payload) =>
331 runHandler(coreHandlers.logout, payload, AGENT_METHODS.logout),
332 [AGENT_METHODS.session_new]: (payload) =>
333 runHandler(coreHandlers.createSession, payload, AGENT_METHODS.session_new),
334 [AGENT_METHODS.session_load]: (payload) =>
335 runHandler(coreHandlers.loadSession, payload, AGENT_METHODS.session_load),
336 [AGENT_METHODS.session_list]: (payload) =>
337 runHandler(coreHandlers.listSessions, payload, AGENT_METHODS.session_list),
338 [AGENT_METHODS.session_fork]: (payload) =>
339 runHandler(coreHandlers.forkSession, payload, AGENT_METHODS.session_fork),
340 [AGENT_METHODS.session_resume]: (payload) =>
341 runHandler(coreHandlers.resumeSession, payload, AGENT_METHODS.session_resume),
342 [AGENT_METHODS.session_close]: (payload) =>
343 runHandler(coreHandlers.closeSession, payload, AGENT_METHODS.session_close),
344 [AGENT_METHODS.session_set_model]: (payload) =>
345 runHandler(coreHandlers.setSessionModel, payload, AGENT_METHODS.session_set_model),
346 [AGENT_METHODS.session_set_config_option]: (payload) =>
347 runHandler(
348 coreHandlers.setSessionConfigOption,
349 payload,
350 AGENT_METHODS.session_set_config_option,
351 ),
352 [AGENT_METHODS.session_prompt]: (payload) =>
353 runHandler(coreHandlers.prompt, payload, AGENT_METHODS.session_prompt),
354 }),
355 );
356
357 yield* RpcServer.make(AcpRpcs.AgentRpcs).pipe(
358 Effect.provideService(RpcServer.Protocol, transport.serverProtocol),
359 Effect.provide(agentHandlerLayer),
360 Effect.forkScoped,
361 );
362
363 let nextRpcRequestId = 1n << 32n;
364 const rpc = yield* RpcClient.make(AcpRpcs.ClientRpcs, {
365 generateRequestId: () => nextRpcRequestId++ as never,
366 }).pipe(Effect.provideService(RpcClient.Protocol, transport.clientProtocol));
367
368 return AcpAgent.of({
369 raw: {
370 notifications: transport.incoming,
371 request: transport.request,
372 notify: transport.notify,
373 },
374 client: {
375 requestPermission: (payload) =>
376 callRpc(rpc[CLIENT_METHODS.session_request_permission](payload)),
377 elicit: (payload) => callRpc(rpc[CLIENT_METHODS.session_elicitation](payload)),
378 readTextFile: (payload) => callRpc(rpc[CLIENT_METHODS.fs_read_text_file](payload)),
379 writeTextFile: (payload) => callRpc(rpc[CLIENT_METHODS.fs_write_text_file](payload)),
380 createTerminal: (payload) =>
381 callRpc(rpc[CLIENT_METHODS.terminal_create](payload)).pipe(
382 Effect.map((response) =>
383 AcpTerminal.makeTerminal({
384 sessionId: payload.sessionId,
385 terminalId: response.terminalId,
386 output: callRpc(
387 rpc[CLIENT_METHODS.terminal_output]({
388 sessionId: payload.sessionId,
389 terminalId: response.terminalId,
390 }),
391 ),
392 waitForExit: callRpc(
393 rpc[CLIENT_METHODS.terminal_wait_for_exit]({
394 sessionId: payload.sessionId,
395 terminalId: response.terminalId,
396 }),
397 ),
398 kill: callRpc(
399 rpc[CLIENT_METHODS.terminal_kill]({
400 sessionId: payload.sessionId,
401 terminalId: response.terminalId,
402 }),
403 ),
404 release: callRpc(
405 rpc[CLIENT_METHODS.terminal_release]({
406 sessionId: payload.sessionId,
407 terminalId: response.terminalId,
408 }),
409 ),
410 }),
411 ),
412 ),
413 sessionUpdate: (payload) => transport.notify(CLIENT_METHODS.session_update, payload),
414 elicitationComplete: (payload) =>
415 transport.notify(CLIENT_METHODS.session_elicitation_complete, payload),
416 extRequest: transport.request,
417 extNotification: transport.notify,
418 },
419 handleInitialize: (handler) =>
420 Effect.suspend(() => {
421 coreHandlers.initialize = handler;
422 return Effect.void;
423 }),
424 handleAuthenticate: (handler) =>
425 Effect.suspend(() => {
426 coreHandlers.authenticate = handler;
427 return Effect.void;
428 }),
429 handleLogout: (handler) =>
430 Effect.suspend(() => {
431 coreHandlers.logout = handler;
432 return Effect.void;
433 }),
434 handleCreateSession: (handler) =>
435 Effect.suspend(() => {
436 coreHandlers.createSession = handler;
437 return Effect.void;
438 }),
439 handleLoadSession: (handler) =>
440 Effect.suspend(() => {
441 coreHandlers.loadSession = handler;
442 return Effect.void;
443 }),
444 handleListSessions: (handler) =>
445 Effect.suspend(() => {
446 coreHandlers.listSessions = handler;
447 return Effect.void;
448 }),
449 handleForkSession: (handler) =>
450 Effect.suspend(() => {
451 coreHandlers.forkSession = handler;
452 return Effect.void;
453 }),
454 handleResumeSession: (handler) =>
455 Effect.suspend(() => {
456 coreHandlers.resumeSession = handler;
457 return Effect.void;
458 }),
459 handleCloseSession: (handler) =>
460 Effect.suspend(() => {
461 coreHandlers.closeSession = handler;
462 return Effect.void;
463 }),
464 handleSetSessionModel: (handler) =>
465 Effect.suspend(() => {
466 coreHandlers.setSessionModel = handler;
467 return Effect.void;
468 }),
469 handleSetSessionConfigOption: (handler) =>
470 Effect.suspend(() => {
471 coreHandlers.setSessionConfigOption = handler;
472 return Effect.void;
473 }),
474 handlePrompt: (handler) =>
475 Effect.suspend(() => {
476 coreHandlers.prompt = handler;
477 return Effect.void;
478 }),
479 handleCancel: (handler) =>
480 Effect.suspend(() => {
481 cancelHandlers.push(handler);
482 return Effect.void;
483 }),
484 handleUnknownExtRequest: (handler) =>
485 Effect.suspend(() => {
486 unknownExtRequestHandler = handler;
487 return Effect.void;
488 }),
489 handleUnknownExtNotification: (handler) =>
490 Effect.suspend(() => {
491 unknownExtNotificationHandler = handler;
492 return Effect.void;
493 }),
494 handleExtRequest: (method, payload, handler) =>
495 Effect.suspend(() => {
496 extRequestHandlers.set(method, decodeExtRequestRegistration(method, payload, handler));
497 return Effect.void;
498 }),
499 handleExtNotification: (method, payload, handler) =>
500 Effect.suspend(() => {
501 extNotificationHandlers.set(
502 method,
503 decodeExtNotificationRegistration(method, payload, handler),
504 );
505 return Effect.void;
506 }),
507 });
508});
509
510export const layer = (stdio: Stdio.Stdio, options: AcpAgentOptions = {}): Layer.Layer<AcpAgent> =>
511 Layer.effect(AcpAgent, make(stdio, options));
512
513export const layerStdio = (
514 options: AcpAgentOptions = {},
515): Layer.Layer<AcpAgent, never, Stdio.Stdio> =>
516 Layer.effect(
517 AcpAgent,
518 Effect.flatMap(Effect.service(Stdio.Stdio), (stdio) => make(stdio, options)),
519 );