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

agent.ts

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