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

agent.ts

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