Open History to see the last commit
1import * as Path from "effect/Path";
2import * as Cause from "effect/Cause";
3import * as Effect from "effect/Effect";
4import * as Exit from "effect/Exit";
5import * as Fiber from "effect/Fiber";
6import * as Layer from "effect/Layer";
7import * as Queue from "effect/Queue";
8import * as Ref from "effect/Ref";
9import * as Schema from "effect/Schema";
10import * as Scope from "effect/Scope";
11import * as Stream from "effect/Stream";
12import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
13
14import * as NodeServices from "@effect/platform-node/NodeServices";
15import { it, assert } from "@effect/vitest";
16
17import * as AcpClient from "./client.ts";
18import * as AcpSchema from "./_generated/schema.gen.ts";
19import * as AcpError from "./errors.ts";
20import { encodeJsonl, jsonRpcRequest, jsonRpcResponse } from "./_internal/shared.ts";
21import { makeInMemoryStdio } from "./_internal/stdio.ts";
22
23const InitializeRequest = jsonRpcRequest("initialize", AcpSchema.InitializeRequest);
24const InitializeResponse = jsonRpcResponse(AcpSchema.InitializeResponse);
25const ExtRequest = jsonRpcRequest("x/test", Schema.Struct({ hello: Schema.String }));
26const ExtResponse = jsonRpcResponse(Schema.Struct({ ok: Schema.Boolean }));
27const mockPeerPath = Effect.map(Effect.service(Path.Path), (path) =>
28 path.join(import.meta.dirname, "../test/fixtures/acp-mock-peer.ts"),
29);
30
31it.layer(NodeServices.layer)("effect-acp client", (it) => {
32 const makeHandle = (env?: Record<string, string>) =>
33 Effect.gen(function* () {
34 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
35 const path = yield* Path.Path;
36 const command = ChildProcess.make("bun", ["run", yield* mockPeerPath], {
37 cwd: path.join(import.meta.dirname, ".."),
38 shell: process.platform === "win32",
39 ...(env ? { env: { ...process.env, ...env } } : {}),
40 });
41 return yield* spawner.spawn(command);
42 });
43
44 it.effect("initializes, prompts, receives updates, and handles permission requests", () =>
45 Effect.gen(function* () {
46 const updates = yield* Ref.make<Array<unknown>>([]);
47 const elicitationCompletions = yield* Ref.make<Array<unknown>>([]);
48 const typedRequests = yield* Ref.make<Array<unknown>>([]);
49 const typedNotifications = yield* Ref.make<Array<unknown>>([]);
50 const handle = yield* makeHandle();
51 const scope = yield* Scope.make();
52 const acpLayer = AcpClient.layerChildProcess(handle);
53 const context = yield* Layer.buildWithScope(acpLayer, scope);
54
55 const ext = yield* Effect.gen(function* () {
56 const acp = yield* AcpClient.AcpClient;
57
58 yield* acp.handleRequestPermission(() =>
59 Effect.succeed({
60 outcome: {
61 outcome: "selected",
62 optionId: "allow",
63 },
64 }),
65 );
66 yield* acp.handleElicitation(() =>
67 Effect.succeed({
68 action: {
69 action: "accept",
70 content: {
71 approved: true,
72 },
73 },
74 }),
75 );
76 yield* acp.handleSessionUpdate((notification) =>
77 Ref.update(updates, (current) => [...current, notification]),
78 );
79 yield* acp.handleElicitationComplete((notification) =>
80 Ref.update(elicitationCompletions, (current) => [...current, notification]),
81 );
82 yield* acp.handleExtRequest(
83 "x/typed_request",
84 Schema.Struct({ message: Schema.String }),
85 (payload) =>
86 Ref.update(typedRequests, (current) => [...current, payload]).pipe(
87 Effect.as({
88 ok: true,
89 echoedMessage: payload.message,
90 }),
91 ),
92 );
93 yield* acp.handleExtNotification(
94 "x/typed_notification",
95 Schema.Struct({ count: Schema.Number }),
96 (payload) => Ref.update(typedNotifications, (current) => [...current, payload]),
97 );
98
99 const init = yield* acp.agent.initialize({
100 protocolVersion: 1,
101 clientCapabilities: {
102 fs: { readTextFile: false, writeTextFile: false },
103 terminal: false,
104 },
105 clientInfo: {
106 name: "effect-acp-test",
107 version: "0.0.0",
108 },
109 });
110 assert.equal(init.protocolVersion, 1);
111
112 yield* acp.agent.authenticate({ methodId: "cursor_login" });
113
114 const session = yield* acp.agent.createSession({
115 cwd: process.cwd(),
116 mcpServers: [],
117 });
118 assert.equal(session.sessionId, "mock-session-1");
119
120 const prompt = yield* acp.agent.prompt({
121 sessionId: session.sessionId,
122 prompt: [{ type: "text", text: "hello" }],
123 });
124 assert.equal(prompt.stopReason, "end_turn");
125
126 const streamed = yield* Stream.runCollect(Stream.take(acp.raw.notifications, 2));
127 assert.equal(streamed.length, 2);
128 assert.equal(streamed[0]?._tag, "SessionUpdate");
129 assert.equal(streamed[1]?._tag, "ElicitationComplete");
130 assert.equal((yield* Ref.get(updates)).length, 1);
131 assert.equal((yield* Ref.get(elicitationCompletions)).length, 1);
132 assert.deepEqual(yield* Ref.get(typedRequests), [{ message: "hello from typed request" }]);
133 assert.deepEqual(yield* Ref.get(typedNotifications), [{ count: 2 }]);
134
135 return yield* acp.raw.request("x/echo", {
136 hello: "world",
137 });
138 }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
139
140 assert.deepEqual(ext, {
141 echoedMethod: "x/echo",
142 echoedParams: {
143 hello: "world",
144 },
145 });
146 }),
147 );
148
149 it.effect(
150 "returns formatted invalid params when a typed extension request payload is wrong",
151 () =>
152 Effect.gen(function* () {
153 const handle = yield* makeHandle({ ACP_MOCK_BAD_TYPED_REQUEST: "1" });
154 const scope = yield* Scope.make();
155 const acpLayer = AcpClient.layerChildProcess(handle);
156 const context = yield* Layer.buildWithScope(acpLayer, scope);
157
158 const result = yield* Effect.gen(function* () {
159 const acp = yield* AcpClient.AcpClient;
160
161 yield* acp.handleRequestPermission(() =>
162 Effect.succeed({
163 outcome: {
164 outcome: "selected",
165 optionId: "allow",
166 },
167 }),
168 );
169 yield* acp.handleElicitation(() =>
170 Effect.succeed({
171 action: {
172 action: "accept",
173 content: {
174 approved: true,
175 },
176 },
177 }),
178 );
179 yield* acp.handleExtRequest(
180 "x/typed_request",
181 Schema.Struct({ message: Schema.String }),
182 () => Effect.succeed({ ok: true }),
183 );
184
185 yield* acp.agent.initialize({
186 protocolVersion: 1,
187 clientCapabilities: {
188 fs: { readTextFile: false, writeTextFile: false },
189 terminal: false,
190 },
191 clientInfo: {
192 name: "effect-acp-test",
193 version: "0.0.0",
194 },
195 });
196
197 yield* acp.agent.authenticate({ methodId: "cursor_login" });
198
199 const session = yield* acp.agent.createSession({
200 cwd: process.cwd(),
201 mcpServers: [],
202 });
203
204 return yield* Effect.exit(
205 acp.agent.prompt({
206 sessionId: session.sessionId,
207 prompt: [{ type: "text", text: "hello" }],
208 }),
209 );
210 }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
211
212 if (result._tag !== "Failure") {
213 assert.fail("Expected prompt to fail for invalid typed extension payload");
214 }
215 const rendered = Cause.pretty(result.cause);
216 assert.include(rendered, "Invalid x/typed_request payload:");
217 assert.include(rendered, "Expected string, got 123");
218 }),
219 );
220
221 it.effect("replays buffered notifications to handlers registered after they arrive", () =>
222 Effect.gen(function* () {
223 const updates = yield* Ref.make<Array<unknown>>([]);
224 const elicitationCompletions = yield* Ref.make<Array<unknown>>([]);
225 const typedRequests = yield* Ref.make<Array<unknown>>([]);
226 const typedNotifications = yield* Ref.make<Array<unknown>>([]);
227 const handle = yield* makeHandle();
228 const scope = yield* Scope.make();
229 const acpLayer = AcpClient.layerChildProcess(handle);
230 const context = yield* Layer.buildWithScope(acpLayer, scope);
231
232 yield* Effect.gen(function* () {
233 const acp = yield* AcpClient.AcpClient;
234
235 yield* acp.handleRequestPermission(() =>
236 Effect.succeed({
237 outcome: {
238 outcome: "selected",
239 optionId: "allow",
240 },
241 }),
242 );
243 yield* acp.handleElicitation(() =>
244 Effect.succeed({
245 action: {
246 action: "accept",
247 content: {
248 approved: true,
249 },
250 },
251 }),
252 );
253 yield* acp.handleExtRequest(
254 "x/typed_request",
255 Schema.Struct({ message: Schema.String }),
256 (payload) =>
257 Ref.update(typedRequests, (current) => [...current, payload]).pipe(
258 Effect.as({
259 ok: true,
260 echoedMessage: payload.message,
261 }),
262 ),
263 );
264 yield* acp.handleExtNotification(
265 "x/typed_notification",
266 Schema.Struct({ count: Schema.Number }),
267 (payload) => Ref.update(typedNotifications, (current) => [...current, payload]),
268 );
269
270 yield* acp.agent.initialize({
271 protocolVersion: 1,
272 clientCapabilities: {
273 fs: { readTextFile: false, writeTextFile: false },
274 terminal: false,
275 },
276 clientInfo: {
277 name: "effect-acp-test",
278 version: "0.0.0",
279 },
280 });
281 yield* acp.agent.authenticate({ methodId: "cursor_login" });
282
283 const session = yield* acp.agent.createSession({
284 cwd: process.cwd(),
285 mcpServers: [],
286 });
287 yield* acp.agent.prompt({
288 sessionId: session.sessionId,
289 prompt: [{ type: "text", text: "hello" }],
290 });
291
292 yield* acp.handleSessionUpdate((notification) =>
293 Ref.update(updates, (current) => [...current, notification]),
294 );
295 yield* acp.handleElicitationComplete((notification) =>
296 Ref.update(elicitationCompletions, (current) => [...current, notification]),
297 );
298
299 assert.equal((yield* Ref.get(updates)).length, 1);
300 assert.equal((yield* Ref.get(elicitationCompletions)).length, 1);
301 assert.deepEqual(yield* Ref.get(typedRequests), [{ message: "hello from typed request" }]);
302 assert.deepEqual(yield* Ref.get(typedNotifications), [{ count: 2 }]);
303 }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
304 }),
305 );
306
307 it.effect("continues dispatching session updates after one handler fails", () =>
308 Effect.gen(function* () {
309 const successfulHandlers = yield* Ref.make(0);
310 const handle = yield* makeHandle();
311 const scope = yield* Scope.make();
312 const acpLayer = AcpClient.layerChildProcess(handle);
313 const context = yield* Layer.buildWithScope(acpLayer, scope);
314
315 yield* Effect.gen(function* () {
316 const acp = yield* AcpClient.AcpClient;
317
318 yield* acp.handleRequestPermission(() =>
319 Effect.succeed({
320 outcome: {
321 outcome: "selected",
322 optionId: "allow",
323 },
324 }),
325 );
326 yield* acp.handleElicitation(() =>
327 Effect.succeed({
328 action: {
329 action: "accept",
330 content: {
331 approved: true,
332 },
333 },
334 }),
335 );
336 yield* acp.handleExtRequest(
337 "x/typed_request",
338 Schema.Struct({ message: Schema.String }),
339 () => Effect.succeed({ ok: true }),
340 );
341 yield* acp.handleExtNotification(
342 "x/typed_notification",
343 Schema.Struct({ count: Schema.Number }),
344 () => Effect.void,
345 );
346 yield* acp.handleSessionUpdate(() =>
347 Effect.fail(AcpError.AcpRequestError.internalError("session update handler failed")),
348 );
349 yield* acp.handleSessionUpdate(() => Ref.update(successfulHandlers, (count) => count + 1));
350
351 yield* acp.agent.initialize({
352 protocolVersion: 1,
353 clientCapabilities: {
354 fs: { readTextFile: false, writeTextFile: false },
355 terminal: false,
356 },
357 clientInfo: {
358 name: "effect-acp-test",
359 version: "0.0.0",
360 },
361 });
362 yield* acp.agent.authenticate({ methodId: "cursor_login" });
363
364 const session = yield* acp.agent.createSession({
365 cwd: process.cwd(),
366 mcpServers: [],
367 });
368 yield* acp.agent.prompt({
369 sessionId: session.sessionId,
370 prompt: [{ type: "text", text: "hello" }],
371 });
372
373 assert.equal(yield* Ref.get(successfulHandlers), 1);
374 }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
375 }),
376 );
377
378 it.effect("uses distinct ids for RPC calls and extension requests", () =>
379 Effect.gen(function* () {
380 const { stdio, input, output } = yield* makeInMemoryStdio();
381 const scope = yield* Scope.make();
382 const acp = yield* AcpClient.make(stdio).pipe(Effect.provideService(Scope.Scope, scope));
383
384 const initializeFiber = yield* acp.agent
385 .initialize({
386 protocolVersion: 1,
387 clientCapabilities: {
388 fs: { readTextFile: false, writeTextFile: false },
389 terminal: false,
390 },
391 clientInfo: {
392 name: "effect-acp-test",
393 version: "0.0.0",
394 },
395 })
396 .pipe(Effect.forkScoped);
397 const extFiber = yield* acp.raw.request("x/test", { hello: "world" }).pipe(Effect.forkScoped);
398
399 const firstOutbound = yield* Queue.take(output);
400 const secondOutbound = yield* Queue.take(output);
401
402 const decodedInitialize = Schema.decodeEffect(Schema.fromJsonString(InitializeRequest));
403 const decodedExt = Schema.decodeEffect(Schema.fromJsonString(ExtRequest));
404 const firstIsInitialize = yield* decodedInitialize(firstOutbound).pipe(
405 Effect.match({
406 onFailure: () => false,
407 onSuccess: () => true,
408 }),
409 );
410
411 const initializeRequest = firstIsInitialize
412 ? yield* decodedInitialize(firstOutbound)
413 : yield* decodedInitialize(secondOutbound);
414 const extRequest = firstIsInitialize
415 ? yield* decodedExt(secondOutbound)
416 : yield* decodedExt(firstOutbound);
417
418 assert.notEqual(initializeRequest.id, extRequest.id);
419
420 yield* Queue.offer(
421 input,
422 yield* encodeJsonl(InitializeResponse, {
423 jsonrpc: "2.0",
424 id: initializeRequest.id,
425 result: {
426 protocolVersion: 1,
427 agentCapabilities: {},
428 agentInfo: {
429 name: "mock-agent",
430 version: "0.0.0",
431 },
432 },
433 }),
434 );
435 yield* Queue.offer(
436 input,
437 yield* encodeJsonl(ExtResponse, {
438 jsonrpc: "2.0",
439 id: extRequest.id,
440 result: { ok: true },
441 }),
442 );
443
444 yield* Fiber.join(initializeFiber);
445 assert.deepEqual(yield* Fiber.join(extFiber), { ok: true });
446 yield* Scope.close(scope, Exit.void);
447 }),
448 );
449});