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

agent.ts

536 lines20.2 KB

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