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

agent.test.ts

422 lines14.2 KB

1import * as Deferred from "effect/Deferred";
2import * as Effect from "effect/Effect";
3import * as Exit from "effect/Exit";
4import * as Fiber from "effect/Fiber";
5import * as Layer from "effect/Layer";
6import * as Queue from "effect/Queue";
7import * as Ref from "effect/Ref";
8import * as Schema from "effect/Schema";
9import * as Scope from "effect/Scope";
10​
11import { assert, it } from "@effect/vitest";
12​
13import * as AcpAgent from "./agent.ts";
14import * as AcpSchema from "./_generated/schema.gen.ts";
15import type * as AcpProtocol from "./protocol.ts";
16import {
17 encodeJsonl,
18 jsonRpcNotification,
19 jsonRpcRequest,
20 jsonRpcResponse,
21} from "./_internal/shared.ts";
22import { makeInMemoryStdio } from "./_internal/stdio.ts";
23​
24const RequestPermissionRequest = jsonRpcRequest(
25 "session/request_permission",
26 AcpSchema.RequestPermissionRequest,
27);
28const InitializeRequest = jsonRpcRequest("initialize", AcpSchema.InitializeRequest);
29const InitializeResponse = jsonRpcResponse(AcpSchema.InitializeResponse);
30const RequestPermissionResponse = jsonRpcResponse(AcpSchema.RequestPermissionResponse);
31const SessionCancelNotification = jsonRpcNotification(
32 "session/cancel",
33 AcpSchema.CancelSessionNotification,
34);
35const ExtPingNotification = jsonRpcNotification("x/ping", Schema.Struct({ count: Schema.Number }));
36const ExtRequest = jsonRpcRequest("x/test", Schema.Struct({ hello: Schema.String }));
37const ExtResponse = jsonRpcResponse(Schema.Struct({ ok: Schema.Boolean }));
38const DieResponse = Schema.Struct({
39 id: Schema.Number,
40 error: Schema.TaggedStruct("Cause", { data: Schema.Tuple([Schema.TaggedStruct("Die", {})]) }),
41});
42const decodeRequestPermissionRequest = Schema.decodeEffect(
43 Schema.fromJsonString(RequestPermissionRequest),
44);
45const decodeInitializeResponse = Schema.decodeEffect(Schema.fromJsonString(InitializeResponse));
46const decodeExtResponse = Schema.decodeEffect(Schema.fromJsonString(ExtResponse));
47​
48it.effect("effect-acp agent handles core agent requests and outbound client requests", () =>
49 Effect.gen(function* () {
50 const { stdio, input, output } = yield* makeInMemoryStdio();
51 const cancelNotifications = yield* Ref.make<Array<string>>([]);
52 const extNotifications = yield* Ref.make<Array<number>>([]);
53 const requestContexts = yield* Ref.make<Array<AcpProtocol.AcpRequestContext>>([]);
54 const cancelReceived = yield* Deferred.make<void>();
55 const extReceived = yield* Deferred.make<void>();
56 const scope = yield* Scope.make();
57 const context = yield* Layer.buildWithScope(AcpAgent.layer(stdio), scope);
58​
59 yield* Effect.gen(function* () {
60 const agent = yield* AcpAgent.AcpAgent;
61​
62 yield* agent.handleInitialize((_request, requestContext) =>
63 Ref.update(requestContexts, (current) => [...current, requestContext]).pipe(
64 Effect.as({
65 protocolVersion: 2,
66 capabilities: {},
67 info: {
68 name: "mock-agent",
69 version: "0.0.0",
70 },
71 }),
72 ),
73 );
74 yield* agent.handleExtRequest(
75 "x/test",
76 Schema.Struct({ hello: Schema.String }),
77 (_payload, requestContext) =>
78 Ref.update(requestContexts, (current) => [...current, requestContext]).pipe(
79 Effect.as({ ok: true }),
80 ),
81 );
82 yield* agent.handleCancel((notification) =>
83 Ref.update(cancelNotifications, (current) => [...current, notification.sessionId]).pipe(
84 Effect.andThen(Deferred.succeed(cancelReceived, undefined)),
85 ),
86 );
87 yield* agent.handleExtNotification(
88 "x/ping",
89 Schema.Struct({ count: Schema.Number }),
90 (payload) =>
91 Ref.update(extNotifications, (current) => [...current, payload.count]).pipe(
92 Effect.andThen(Deferred.succeed(extReceived, undefined)),
93 ),
94 );
95​
96 const permissionFiber = yield* agent.client
97 .requestPermission({
98 sessionId: "session-1",
99 title: "Allow mock action",
100 subject: {
101 type: "tool_call",
102 toolCall: {
103 toolCallId: "tool-1",
104 title: "Allow mock action",
105 },
106 },
107 options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
108 })
109 .pipe(Effect.forkScoped);
110​
111 const permissionRequest = yield* decodeRequestPermissionRequest(yield* Queue.take(output));
112 assert.equal(permissionRequest.jsonrpc, "2.0");
113 assert.equal(permissionRequest.method, "session/request_permission");
114 assert.deepEqual(permissionRequest.params, {
115 sessionId: "session-1",
116 title: "Allow mock action",
117 subject: {
118 type: "tool_call",
119 toolCall: {
120 toolCallId: "tool-1",
121 title: "Allow mock action",
122 },
123 },
124 options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
125 });
126 assert.deepEqual(permissionRequest.headers, []);
127​
128 yield* Queue.offer(
129 input,
130 yield* encodeJsonl(RequestPermissionResponse, {
131 jsonrpc: "2.0",
132 id: permissionRequest.id,
133 result: {
134 outcome: {
135 outcome: "selected",
136 optionId: "allow",
137 },
138 },
139 }),
140 );
141​
142 const permission = yield* Fiber.join(permissionFiber);
143 assert.equal(permission.outcome.outcome, "selected");
144​
145 yield* Queue.offer(
146 input,
147 yield* encodeJsonl(InitializeRequest, {
148 jsonrpc: "2.0",
149 id: 2,
150 method: "initialize",
151 params: {
152 protocolVersion: 2,
153 capabilities: {},
154 info: {
155 name: "effect-acp-test",
156 version: "0.0.0",
157 },
158 },
159 headers: [],
160 }),
161 );
162​
163 const initResponse = yield* decodeInitializeResponse(yield* Queue.take(output));
164 assert.deepEqual(initResponse, {
165 jsonrpc: "2.0",
166 id: 2,
167 result: {
168 protocolVersion: 2,
169 capabilities: {},
170 info: {
171 name: "mock-agent",
172 version: "0.0.0",
173 },
174 },
175 });
176​
177 yield* Queue.offer(
178 input,
179 yield* encodeJsonl(ExtRequest, {
180 jsonrpc: "2.0",
181 id: "extension-3",
182 method: "x/test",
183 params: { hello: "world" },
184 headers: [],
185 }),
186 );
187 const extResponse = yield* decodeExtResponse(yield* Queue.take(output));
188 assert.deepEqual(extResponse, {
189 jsonrpc: "2.0",
190 id: "extension-3",
191 result: { ok: true },
192 });
193 assert.deepEqual(yield* Ref.get(requestContexts), [
194 { requestId: "$t3:jsonrpc:number:2", method: "initialize" },
195 { requestId: "extension-3", method: "x/test" },
196 ]);
197​
198 yield* Queue.offer(
199 input,
200 yield* encodeJsonl(SessionCancelNotification, {
201 jsonrpc: "2.0",
202 method: "session/cancel",
203 params: {
204 sessionId: "session-1",
205 },
206 }),
207 );
208 yield* Queue.offer(
209 input,
210 yield* encodeJsonl(ExtPingNotification, {
211 jsonrpc: "2.0",
212 method: "x/ping",
213 params: { count: 2 },
214 }),
215 );
216​
217 yield* Deferred.await(cancelReceived);
218 yield* Deferred.await(extReceived);
219 assert.deepEqual(yield* Ref.get(cancelNotifications), ["session-1"]);
220 assert.deepEqual(yield* Ref.get(extNotifications), [2]);
221 }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
222 }),
223);
224​
225it.effect("effect-acp agent keeps RPC ids within int32 and apart from extension ids", () =>
226 Effect.gen(function* () {
227 const { stdio, input, output } = yield* makeInMemoryStdio();
228 const scope = yield* Scope.make();
229 const context = yield* Layer.buildWithScope(AcpAgent.layer(stdio), scope);
230​
231 yield* Effect.gen(function* () {
232 const agent = yield* AcpAgent.AcpAgent;
233​
234 const permissionFiber = yield* agent.client
235 .requestPermission({
236 sessionId: "session-1",
237 title: "Allow mock action",
238 subject: {
239 type: "tool_call",
240 toolCall: {
241 toolCallId: "tool-1",
242 title: "Allow mock action",
243 },
244 },
245 options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
246 })
247 .pipe(Effect.forkScoped);
248 const extFiber = yield* agent.client
249 .extRequest("x/test", { hello: "world" })
250 .pipe(Effect.forkScoped);
251​
252 const firstOutbound = yield* Queue.take(output);
253 const secondOutbound = yield* Queue.take(output);
254​
255 const decodedPermission = Schema.decodeEffect(
256 Schema.fromJsonString(RequestPermissionRequest),
257 );
258 const decodedExt = Schema.decodeEffect(Schema.fromJsonString(ExtRequest));
259 const firstIsPermission = yield* decodedPermission(firstOutbound).pipe(
260 Effect.match({
261 onFailure: () => false,
262 onSuccess: () => true,
263 }),
264 );
265​
266 const permissionRequest = firstIsPermission
267 ? yield* decodedPermission(firstOutbound)
268 : yield* decodedPermission(secondOutbound);
269 const extRequest = firstIsPermission
270 ? yield* decodedExt(secondOutbound)
271 : yield* decodedExt(firstOutbound);
272​
273 assert.notEqual(permissionRequest.id, extRequest.id);
274 // Keep locally generated ids compatible with SDKs that decode signed int32.
275 assert.typeOf(permissionRequest.id, "number");
276 assert.equal(permissionRequest.id, 2 ** 30);
277 assert.isAtMost(Number(permissionRequest.id), 2 ** 31 - 1);
278 assert.equal(extRequest.id, 1);
279​
280 yield* Queue.offer(
281 input,
282 yield* encodeJsonl(RequestPermissionResponse, {
283 jsonrpc: "2.0",
284 id: permissionRequest.id,
285 result: {
286 outcome: {
287 outcome: "selected",
288 optionId: "allow",
289 },
290 },
291 }),
292 );
293 yield* Queue.offer(
294 input,
295 yield* encodeJsonl(ExtResponse, {
296 jsonrpc: "2.0",
297 id: extRequest.id,
298 result: { ok: true },
299 }),
300 );
301​
302 const permission = yield* Fiber.join(permissionFiber);
303 assert.equal(permission.outcome.outcome, "selected");
304 assert.deepEqual(yield* Fiber.join(extFiber), { ok: true });
305​
306 const nextPermissionFiber = yield* agent.client
307 .requestPermission(permissionRequest.params)
308 .pipe(Effect.forkScoped);
309 const nextPermissionRequest = yield* decodedPermission(yield* Queue.take(output));
310 assert.equal(nextPermissionRequest.id, 2 ** 30 + 1);
311 yield* Queue.offer(
312 input,
313 yield* encodeJsonl(RequestPermissionResponse, {
314 jsonrpc: "2.0",
315 id: nextPermissionRequest.id,
316 result: { outcome: { outcome: "cancelled" } },
317 }),
318 );
319 assert.equal((yield* Fiber.join(nextPermissionFiber)).outcome.outcome, "cancelled");
320 }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
321 }),
322);
323​
324it.effect.each([0, 2 ** 30, 2 ** 32])(
325 "effect-acp agent answers incoming id %s independently of outbound ids",
326 (requestId) =>
327 Effect.gen(function* () {
328 const { stdio, input, output } = yield* makeInMemoryStdio();
329 const agent = yield* AcpAgent.make(stdio);
330 const contexts = yield* Ref.make<Array<AcpProtocol.AcpRequestContext>>([]);
331 yield* agent.handleInitialize((_request, context) =>
332 Ref.update(contexts, (current) => [...current, context]).pipe(
333 Effect.as({
334 protocolVersion: 2,
335 capabilities: {},
336 info: { name: "mock-agent", version: "0.0.0" },
337 }),
338 ),
339 );
340​
341 // Opposite directions may reuse an id even while a request is pending.
342 const outboundFiber = yield* agent.client
343 .requestPermission({
344 sessionId: "session-1",
345 title: "Allow mock action",
346 subject: {
347 type: "tool_call",
348 toolCall: { toolCallId: "tool-1", title: "Allow mock action" },
349 },
350 options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
351 })
352 .pipe(Effect.forkScoped);
353 const outbound = yield* decodeRequestPermissionRequest(yield* Queue.take(output));
354​
355 yield* Queue.offer(
356 input,
357 yield* encodeJsonl(InitializeRequest, {
358 jsonrpc: "2.0",
359 id: requestId,
360 method: "initialize",
361 params: {
362 protocolVersion: 2,
363 capabilities: {},
364 info: { name: "test-client", version: "0.0.0" },
365 },
366 headers: [],
367 }),
368 );
369 assert.deepEqual(yield* decodeInitializeResponse(yield* Queue.take(output)), {
370 jsonrpc: "2.0",
371 id: requestId,
372 result: {
373 protocolVersion: 2,
374 capabilities: {},
375 info: { name: "mock-agent", version: "0.0.0" },
376 },
377 });
378 assert.deepEqual(yield* Ref.get(contexts), [
379 { requestId: `$t3:jsonrpc:number:${requestId}`, method: "initialize" },
380 ]);
381​
382 yield* Queue.offer(
383 input,
384 yield* encodeJsonl(RequestPermissionResponse, {
385 jsonrpc: "2.0",
386 id: outbound.id,
387 result: { outcome: { outcome: "cancelled" } },
388 }),
389 );
390 assert.equal((yield* Fiber.join(outboundFiber)).outcome.outcome, "cancelled");
391 }),
392);
393​
394it.effect("effect-acp agent answers a request whose handler dies with an error for it", () =>
395 Effect.gen(function* () {
396 const { stdio, input, output } = yield* makeInMemoryStdio();
397 const scope = yield* Scope.make();
398 const context = yield* Layer.buildWithScope(AcpAgent.layer(stdio), scope);
399 const agent = yield* Effect.service(AcpAgent.AcpAgent).pipe(Effect.provide(context));
400 yield* agent.handleInitialize(() => Effect.die(new Error("handler bug")));
401​
402 yield* Queue.offer(
403 input,
404 yield* encodeJsonl(InitializeRequest, {
405 jsonrpc: "2.0",
406 id: 7,
407 method: "initialize",
408 params: {
409 protocolVersion: 2,
410 capabilities: {},
411 info: { name: "effect-acp-test", version: "0.0.0" },
412 },
413 headers: [],
414 }),
415 );
416 const response = yield* Queue.take(output).pipe(
417 Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(DieResponse))),
418 );
419 assert.equal(response.id, 7);
420 yield* Scope.close(scope, Exit.void);
421 }),
422);