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

agent.test.ts

417 lines14.1 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(Effect.isSuccess);
260​
261 const permissionRequest = firstIsPermission
262 ? yield* decodedPermission(firstOutbound)
263 : yield* decodedPermission(secondOutbound);
264 const extRequest = firstIsPermission
265 ? yield* decodedExt(secondOutbound)
266 : yield* decodedExt(firstOutbound);
267​
268 assert.notEqual(permissionRequest.id, extRequest.id);
269 // Keep locally generated ids compatible with SDKs that decode signed int32.
270 assert.typeOf(permissionRequest.id, "number");
271 assert.equal(permissionRequest.id, 2 ** 30);
272 assert.isAtMost(Number(permissionRequest.id), 2 ** 31 - 1);
273 assert.equal(extRequest.id, 1);
274​
275 yield* Queue.offer(
276 input,
277 yield* encodeJsonl(RequestPermissionResponse, {
278 jsonrpc: "2.0",
279 id: permissionRequest.id,
280 result: {
281 outcome: {
282 outcome: "selected",
283 optionId: "allow",
284 },
285 },
286 }),
287 );
288 yield* Queue.offer(
289 input,
290 yield* encodeJsonl(ExtResponse, {
291 jsonrpc: "2.0",
292 id: extRequest.id,
293 result: { ok: true },
294 }),
295 );
296​
297 const permission = yield* Fiber.join(permissionFiber);
298 assert.equal(permission.outcome.outcome, "selected");
299 assert.deepEqual(yield* Fiber.join(extFiber), { ok: true });
300​
301 const nextPermissionFiber = yield* agent.client
302 .requestPermission(permissionRequest.params)
303 .pipe(Effect.forkScoped);
304 const nextPermissionRequest = yield* decodedPermission(yield* Queue.take(output));
305 assert.equal(nextPermissionRequest.id, 2 ** 30 + 1);
306 yield* Queue.offer(
307 input,
308 yield* encodeJsonl(RequestPermissionResponse, {
309 jsonrpc: "2.0",
310 id: nextPermissionRequest.id,
311 result: { outcome: { outcome: "cancelled" } },
312 }),
313 );
314 assert.equal((yield* Fiber.join(nextPermissionFiber)).outcome.outcome, "cancelled");
315 }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
316 }),
317);
318​
319it.effect.each([0, 2 ** 30, 2 ** 32])(
320 "effect-acp agent answers incoming id %s independently of outbound ids",
321 (requestId) =>
322 Effect.gen(function* () {
323 const { stdio, input, output } = yield* makeInMemoryStdio();
324 const agent = yield* AcpAgent.make(stdio);
325 const contexts = yield* Ref.make<Array<AcpProtocol.AcpRequestContext>>([]);
326 yield* agent.handleInitialize((_request, context) =>
327 Ref.update(contexts, (current) => [...current, context]).pipe(
328 Effect.as({
329 protocolVersion: 2,
330 capabilities: {},
331 info: { name: "mock-agent", version: "0.0.0" },
332 }),
333 ),
334 );
335​
336 // Opposite directions may reuse an id even while a request is pending.
337 const outboundFiber = yield* agent.client
338 .requestPermission({
339 sessionId: "session-1",
340 title: "Allow mock action",
341 subject: {
342 type: "tool_call",
343 toolCall: { toolCallId: "tool-1", title: "Allow mock action" },
344 },
345 options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
346 })
347 .pipe(Effect.forkScoped);
348 const outbound = yield* decodeRequestPermissionRequest(yield* Queue.take(output));
349​
350 yield* Queue.offer(
351 input,
352 yield* encodeJsonl(InitializeRequest, {
353 jsonrpc: "2.0",
354 id: requestId,
355 method: "initialize",
356 params: {
357 protocolVersion: 2,
358 capabilities: {},
359 info: { name: "test-client", version: "0.0.0" },
360 },
361 headers: [],
362 }),
363 );
364 assert.deepEqual(yield* decodeInitializeResponse(yield* Queue.take(output)), {
365 jsonrpc: "2.0",
366 id: requestId,
367 result: {
368 protocolVersion: 2,
369 capabilities: {},
370 info: { name: "mock-agent", version: "0.0.0" },
371 },
372 });
373 assert.deepEqual(yield* Ref.get(contexts), [
374 { requestId: `$t3:jsonrpc:number:${requestId}`, method: "initialize" },
375 ]);
376​
377 yield* Queue.offer(
378 input,
379 yield* encodeJsonl(RequestPermissionResponse, {
380 jsonrpc: "2.0",
381 id: outbound.id,
382 result: { outcome: { outcome: "cancelled" } },
383 }),
384 );
385 assert.equal((yield* Fiber.join(outboundFiber)).outcome.outcome, "cancelled");
386 }),
387);
388​
389it.effect("effect-acp agent answers a request whose handler dies with an error for it", () =>
390 Effect.gen(function* () {
391 const { stdio, input, output } = yield* makeInMemoryStdio();
392 const scope = yield* Scope.make();
393 const context = yield* Layer.buildWithScope(AcpAgent.layer(stdio), scope);
394 const agent = yield* Effect.service(AcpAgent.AcpAgent).pipe(Effect.provide(context));
395 yield* agent.handleInitialize(() => Effect.die(new Error("handler bug")));
396​
397 yield* Queue.offer(
398 input,
399 yield* encodeJsonl(InitializeRequest, {
400 jsonrpc: "2.0",
401 id: 7,
402 method: "initialize",
403 params: {
404 protocolVersion: 2,
405 capabilities: {},
406 info: { name: "effect-acp-test", version: "0.0.0" },
407 },
408 headers: [],
409 }),
410 );
411 const response = yield* Queue.take(output).pipe(
412 Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(DieResponse))),
413 );
414 assert.equal(response.id, 7);
415 yield* Scope.close(scope, Exit.void);
416 }),
417);