mirror of
https://github.com/hanzoai/dev-desktop.git
synced 2026-11-23 05:52:02 +00:00
1450 lines
51 KiB
TypeScript
1450 lines
51 KiB
TypeScript
import * as Path from "effect/Path";
|
|
import * as AcpError from "./errors.ts";
|
|
import * as Effect from "effect/Effect";
|
|
import * as Deferred from "effect/Deferred";
|
|
import * as Fiber from "effect/Fiber";
|
|
import * as Exit from "effect/Exit";
|
|
import * as Logger from "effect/Logger";
|
|
import * as Queue from "effect/Queue";
|
|
import * as References from "effect/References";
|
|
import * as Schema from "effect/Schema";
|
|
import * as Scope from "effect/Scope";
|
|
import * as Sink from "effect/Sink";
|
|
import * as Stdio from "effect/Stdio";
|
|
import * as Stream from "effect/Stream";
|
|
import * as Ref from "effect/Ref";
|
|
import * as TestClock from "effect/testing/TestClock";
|
|
import { ChildProcess, ChildProcessSpawner } from "effect/process";
|
|
|
|
import { it, assert, expect } from "@effect/vitest";
|
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
|
|
|
import * as AcpSchema from "./schema.ts";
|
|
import * as AcpProtocol from "./protocol.ts";
|
|
import {
|
|
encodeJsonl,
|
|
jsonRpcNotification,
|
|
jsonRpcRequest,
|
|
jsonRpcResponse,
|
|
} from "./_internal/shared.ts";
|
|
import { makeInMemoryStdio, makeTerminationError, makeChildStdio } from "./_internal/stdio.ts";
|
|
|
|
const SessionCancelNotification = jsonRpcNotification(
|
|
"session/cancel",
|
|
AcpSchema.CancelNotification,
|
|
);
|
|
const SessionUpdateNotification = jsonRpcNotification(
|
|
"session/update",
|
|
AcpSchema.SessionNotification,
|
|
);
|
|
const ElicitationCompleteNotification = jsonRpcNotification(
|
|
"elicitation/complete",
|
|
AcpSchema.CompleteElicitationNotification,
|
|
);
|
|
const RequestPermissionRequest = jsonRpcRequest(
|
|
"session/request_permission",
|
|
AcpSchema.RequestPermissionRequest,
|
|
);
|
|
const RequestPermissionResponse = jsonRpcResponse(AcpSchema.RequestPermissionResponse);
|
|
const ExtRequest = jsonRpcRequest("x/test", Schema.Struct({ hello: Schema.String }));
|
|
const ExtResponse = jsonRpcResponse(Schema.Struct({ ok: Schema.Boolean }));
|
|
const decodeSessionCancelNotification = Schema.decodeEffect(
|
|
Schema.fromJsonString(SessionCancelNotification),
|
|
);
|
|
const decodeExtRequest = Schema.decodeEffect(Schema.fromJsonString(ExtRequest));
|
|
const decodeRequestPermissionResponse = Schema.decodeEffect(
|
|
Schema.fromJsonString(RequestPermissionResponse),
|
|
);
|
|
const JsonRpcErrorResponse = Schema.Struct({
|
|
jsonrpc: Schema.Literal("2.0"),
|
|
id: Schema.Number,
|
|
error: Schema.Struct({ code: Schema.Number, message: Schema.String }),
|
|
});
|
|
const encodeUnknownJsonString = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
|
|
const encoder = new TextEncoder();
|
|
const MIB = 1024 * 1024;
|
|
const decodeIndex = Schema.decodeUnknownSync(Schema.Struct({ index: Schema.Number }));
|
|
const largeNotification = (index: number, textLength: number) =>
|
|
encoder.encode(
|
|
`${encodeUnknownJsonString({
|
|
jsonrpc: "2.0",
|
|
method: "x/large",
|
|
params: { index, text: "x".repeat(textLength) },
|
|
})}\n`,
|
|
);
|
|
const mockPeerPath = Effect.map(Effect.service(Path.Path), (path) =>
|
|
path.join(import.meta.dirname, "../test/fixtures/acp-mock-peer.ts"),
|
|
);
|
|
const mockPeerArgs = (path: string) => [path];
|
|
|
|
const makeHandle = (env?: Record<string, string>) =>
|
|
Effect.gen(function* () {
|
|
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
|
const path = yield* Path.Path;
|
|
const command = ChildProcess.make(process.execPath, mockPeerArgs(yield* mockPeerPath), {
|
|
cwd: path.join(import.meta.dirname, ".."),
|
|
...(env ? { env: { ...process.env, ...env } } : {}),
|
|
});
|
|
return yield* spawner.spawn(command);
|
|
});
|
|
|
|
it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
|
|
it.effect(
|
|
"emits exact JSON-RPC notifications and decodes inbound session/update and elicitation completion",
|
|
() =>
|
|
Effect.gen(function* () {
|
|
const { stdio, input, output } = yield* makeInMemoryStdio();
|
|
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
|
stdio,
|
|
serverRequestMethods: new Set(),
|
|
});
|
|
|
|
const notifications =
|
|
yield* Deferred.make<ReadonlyArray<AcpProtocol.AcpIncomingNotification>>();
|
|
yield* transport.incoming.pipe(
|
|
Stream.take(3),
|
|
Stream.runCollect,
|
|
Effect.flatMap((notificationChunk) => Deferred.succeed(notifications, notificationChunk)),
|
|
Effect.forkScoped,
|
|
);
|
|
|
|
yield* transport.notify("session/cancel", { sessionId: "session-1" });
|
|
const outbound = yield* Queue.take(output);
|
|
assert.deepEqual(yield* decodeSessionCancelNotification(outbound), {
|
|
jsonrpc: "2.0",
|
|
method: "session/cancel",
|
|
params: {
|
|
sessionId: "session-1",
|
|
},
|
|
});
|
|
|
|
const updateFrame = yield* encodeJsonl(SessionUpdateNotification, {
|
|
jsonrpc: "2.0",
|
|
method: "session/update",
|
|
params: {
|
|
sessionId: "session-1",
|
|
update: {
|
|
sessionUpdate: "plan",
|
|
entries: [
|
|
{
|
|
content: "Inspect repository",
|
|
priority: "high",
|
|
status: "in_progress",
|
|
},
|
|
],
|
|
},
|
|
},
|
|
});
|
|
const completionFrame = yield* encodeJsonl(ElicitationCompleteNotification, {
|
|
jsonrpc: "2.0",
|
|
method: "elicitation/complete",
|
|
params: {
|
|
elicitationId: "elicitation-1",
|
|
},
|
|
});
|
|
|
|
const commandResult = {
|
|
exit_code: null,
|
|
signal: null,
|
|
timed_out: false,
|
|
termination_indeterminate: true,
|
|
};
|
|
const cancelledToolFrame = encoder.encode(
|
|
`${encodeUnknownJsonString({
|
|
jsonrpc: "2.0",
|
|
method: "session/update",
|
|
params: {
|
|
sessionId: "session-1",
|
|
update: {
|
|
sessionUpdate: "tool_call_update",
|
|
toolCallId: "cancelled-tool",
|
|
status: "failed",
|
|
command_result: commandResult,
|
|
},
|
|
},
|
|
})}\n`,
|
|
);
|
|
// Frames split across reads, with one read ending one frame and starting the next.
|
|
const wire = new Uint8Array([...updateFrame, ...completionFrame, ...cancelledToolFrame]);
|
|
const splits = [10, updateFrame.length + 10, wire.length];
|
|
let start = 0;
|
|
for (const end of splits) {
|
|
yield* Queue.offer(input, wire.subarray(start, end));
|
|
start = end;
|
|
}
|
|
|
|
const [update, completion, cancelledTool] = yield* Deferred.await(notifications);
|
|
assert.equal(update?._tag, "SessionUpdate");
|
|
assert.equal(completion?._tag, "ElicitationComplete");
|
|
assert.deepEqual(cancelledTool?.params, {
|
|
sessionId: "session-1",
|
|
update: {
|
|
sessionUpdate: "tool_call_update",
|
|
toolCallId: "cancelled-tool",
|
|
status: "failed",
|
|
command_result: commandResult,
|
|
},
|
|
});
|
|
}),
|
|
);
|
|
|
|
it.effect("keeps only recent raw notifications after their callbacks run", () =>
|
|
Effect.gen(function* () {
|
|
const { stdio, input } = yield* makeInMemoryStdio();
|
|
const handled = yield* Deferred.make<void>();
|
|
let handledCount = 0;
|
|
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
|
stdio,
|
|
serverRequestMethods: new Set(),
|
|
onNotification: () =>
|
|
Effect.sync(() => ++handledCount).pipe(
|
|
Effect.flatMap((count) =>
|
|
count === 64 ? Deferred.succeed(handled, undefined).pipe(Effect.asVoid) : Effect.void,
|
|
),
|
|
),
|
|
});
|
|
|
|
const messages = Array.from({ length: 64 }, (_, index) =>
|
|
encodeUnknownJsonString({
|
|
jsonrpc: "2.0",
|
|
method: "x/performance",
|
|
params: { index },
|
|
}),
|
|
);
|
|
yield* Queue.offer(input, encoder.encode(`${messages.join("\n")}\n`));
|
|
yield* Deferred.await(handled);
|
|
|
|
const retained = yield* transport.incoming.pipe(Stream.take(32), Stream.runCollect);
|
|
|
|
assert.equal(handledCount, 64);
|
|
assert.equal(retained.length, 32);
|
|
assert.deepEqual(retained[0]?.params, { index: 32 });
|
|
assert.deepEqual(retained[31]?.params, { index: 63 });
|
|
}),
|
|
);
|
|
|
|
it.effect("keeps the newest unread raw notifications whose JSON fits in 16Mi characters", () =>
|
|
Effect.gen(function* () {
|
|
const { stdio, input } = yield* makeInMemoryStdio();
|
|
const handled = yield* Queue.unbounded<number>();
|
|
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
|
stdio,
|
|
serverRequestMethods: new Set(),
|
|
onNotification: (notification) =>
|
|
Queue.offer(handled, decodeIndex(notification.params).index).pipe(Effect.asVoid),
|
|
});
|
|
|
|
// Ten 3 MiB notifications: only the newest five fit in the budget.
|
|
for (let index = 0; index < 10; index++) {
|
|
yield* Queue.offer(input, largeNotification(index, 3 * MIB));
|
|
assert.equal(yield* Queue.take(handled), index);
|
|
}
|
|
|
|
const retained = yield* transport.incoming.pipe(Stream.take(5), Stream.runCollect);
|
|
assert.deepEqual(
|
|
retained.map((notification) => decodeIndex(notification.params).index),
|
|
[5, 6, 7, 8, 9],
|
|
);
|
|
}),
|
|
);
|
|
|
|
it.effect("keeps a single unread raw notification that alone exceeds the budget", () =>
|
|
Effect.gen(function* () {
|
|
const { stdio, input } = yield* makeInMemoryStdio();
|
|
const handled = yield* Queue.unbounded<number>();
|
|
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
|
stdio,
|
|
serverRequestMethods: new Set(),
|
|
onNotification: (notification) =>
|
|
Queue.offer(handled, decodeIndex(notification.params).index).pipe(Effect.asVoid),
|
|
});
|
|
|
|
yield* Queue.offer(input, largeNotification(0, 1));
|
|
yield* Queue.take(handled);
|
|
yield* Queue.offer(input, largeNotification(1, 17 * MIB));
|
|
yield* Queue.take(handled);
|
|
|
|
const [retained] = yield* transport.incoming.pipe(Stream.take(1), Stream.runCollect);
|
|
assert.equal(decodeIndex(retained?.params).index, 1);
|
|
}),
|
|
);
|
|
|
|
it.effect("evicts unread raw notifications while a slow reader handles an earlier one", () =>
|
|
Effect.gen(function* () {
|
|
const { stdio, input } = yield* makeInMemoryStdio();
|
|
const handled = yield* Queue.unbounded<number>();
|
|
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
|
stdio,
|
|
serverRequestMethods: new Set(),
|
|
onNotification: (notification) =>
|
|
Queue.offer(handled, decodeIndex(notification.params).index).pipe(Effect.asVoid),
|
|
});
|
|
const send = (index: number, textLength: number) =>
|
|
Queue.offer(input, largeNotification(index, textLength)).pipe(
|
|
Effect.andThen(Queue.take(handled)),
|
|
);
|
|
|
|
yield* send(1, 6 * MIB);
|
|
yield* send(2, 6 * MIB);
|
|
const entered = yield* Deferred.make<void>();
|
|
const release = yield* Deferred.make<void>();
|
|
const reader = yield* transport.incoming.pipe(
|
|
Stream.map((notification) => decodeIndex(notification.params).index),
|
|
Stream.tap((index) =>
|
|
index === 1
|
|
? Deferred.succeed(entered, undefined).pipe(Effect.andThen(Deferred.await(release)))
|
|
: Effect.void,
|
|
),
|
|
Stream.take(4),
|
|
Stream.runCollect,
|
|
Effect.forkScoped,
|
|
);
|
|
yield* Deferred.await(entered);
|
|
|
|
// Notification 2 is still unread, so 3 and 4 push it past the budget.
|
|
yield* send(3, 6 * MIB);
|
|
yield* send(4, 6 * MIB);
|
|
yield* send(5, 1);
|
|
yield* Deferred.succeed(release, undefined);
|
|
|
|
assert.deepEqual(yield* Fiber.join(reader), [1, 3, 4, 5]);
|
|
}),
|
|
);
|
|
|
|
it.effect("delivers every raw notification to a reader that keeps up, then ends", () =>
|
|
Effect.gen(function* () {
|
|
const { stdio, input } = yield* makeInMemoryStdio();
|
|
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
|
stdio,
|
|
serverRequestMethods: new Set(),
|
|
});
|
|
const received = yield* Queue.unbounded<number>();
|
|
const reader = yield* transport.incoming.pipe(
|
|
Stream.map((notification) => decodeIndex(notification.params).index),
|
|
Stream.tap((index) => Queue.offer(received, index)),
|
|
Stream.runCollect,
|
|
Effect.forkScoped,
|
|
);
|
|
|
|
// 30 MiB in total, well past the unread budget.
|
|
for (let index = 0; index < 10; index++) {
|
|
yield* Queue.offer(input, largeNotification(index, 3 * MIB));
|
|
assert.equal(yield* Queue.take(received), index);
|
|
}
|
|
yield* Queue.end(input);
|
|
|
|
assert.deepEqual(yield* Fiber.join(reader), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
|
|
}),
|
|
);
|
|
|
|
it.effect("ends the raw notification stream when the connection scope closes", () =>
|
|
Effect.gen(function* () {
|
|
const { stdio } = yield* makeInMemoryStdio();
|
|
const connection = yield* Scope.make();
|
|
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
|
stdio,
|
|
serverRequestMethods: new Set(),
|
|
}).pipe(Scope.provide(connection));
|
|
const reader = yield* transport.incoming.pipe(Stream.runCollect, Effect.forkScoped);
|
|
|
|
yield* Scope.close(connection, Exit.void);
|
|
|
|
assert.deepEqual(yield* Fiber.join(reader), []);
|
|
}),
|
|
);
|
|
|
|
it.effect("keeps the ended raw backlog intact when notifications arrive after termination", () =>
|
|
Effect.gen(function* () {
|
|
const { stdio, input } = yield* makeInMemoryStdio();
|
|
const handled = yield* Queue.unbounded<number>();
|
|
const terminated = yield* Deferred.make<void>();
|
|
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
|
stdio: Stdio.make({
|
|
args: stdio.args,
|
|
stdin: stdio.stdin,
|
|
stdout: () => Sink.forEach(() => Effect.die("stdout failed")),
|
|
stderr: () => Sink.drain,
|
|
}),
|
|
serverRequestMethods: new Set(),
|
|
onNotification: (notification) =>
|
|
Queue.offer(handled, decodeIndex(notification.params).index).pipe(Effect.asVoid),
|
|
onTermination: () => Deferred.succeed(terminated, undefined).pipe(Effect.asVoid),
|
|
});
|
|
const deliver = (index: number) =>
|
|
Queue.offer(
|
|
input,
|
|
encoder.encode(
|
|
`${encodeUnknownJsonString({ jsonrpc: "2.0", method: "x/late", params: { index } })}\n`,
|
|
),
|
|
).pipe(Effect.andThen(Queue.take(handled)));
|
|
|
|
for (let index = 0; index < 32; index++) {
|
|
assert.equal(yield* deliver(index), index);
|
|
}
|
|
// A failed write terminates the connection while the reader keeps running.
|
|
yield* transport.notify("x/fail", {}).pipe(Effect.exit);
|
|
yield* Deferred.await(terminated);
|
|
assert.equal(yield* deliver(32), 32);
|
|
|
|
const retained = yield* transport.incoming.pipe(
|
|
Stream.map((notification) => decodeIndex(notification.params).index),
|
|
Stream.runCollect,
|
|
);
|
|
assert.deepEqual(
|
|
retained,
|
|
Array.from({ length: 32 }, (_, index) => index),
|
|
);
|
|
}),
|
|
);
|
|
|
|
// clanka once sent a usage_update without `used` and `size`. One bad update
|
|
// must not end a session whose later updates are fine.
|
|
it.effect("drops a session/update that fails to decode and keeps reading", () =>
|
|
Effect.gen(function* () {
|
|
const secret = "acp-core-notification-secret-sentinel";
|
|
const { stdio, input } = yield* makeInMemoryStdio();
|
|
const events: Array<AcpProtocol.AcpProtocolLogEvent> = [];
|
|
const warnings: Array<unknown> = [];
|
|
let terminated = false;
|
|
let transformCalls = 0;
|
|
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
|
stdio,
|
|
serverRequestMethods: new Set(),
|
|
logIncoming: true,
|
|
logger: (event) =>
|
|
Effect.sync(() => {
|
|
events.push(event);
|
|
}),
|
|
transformSessionUpdate: (notification) => {
|
|
transformCalls += 1;
|
|
return notification;
|
|
},
|
|
onTermination: () =>
|
|
Effect.sync(() => {
|
|
terminated = true;
|
|
}),
|
|
}).pipe(
|
|
Effect.provide(
|
|
Logger.layer([
|
|
Logger.make(({ logLevel, fiber }) => {
|
|
if (logLevel === "Warn")
|
|
warnings.push(fiber.getRef(References.CurrentLogAnnotations));
|
|
}),
|
|
]),
|
|
),
|
|
);
|
|
const received = yield* Deferred.make<AcpProtocol.AcpIncomingNotification>();
|
|
yield* transport.incoming.pipe(
|
|
Stream.runForEach((notification) => Deferred.succeed(received, notification)),
|
|
Effect.forkScoped,
|
|
);
|
|
|
|
const send = (params: unknown) =>
|
|
Queue.offer(
|
|
input,
|
|
encoder.encode(
|
|
`${encodeUnknownJsonString({ jsonrpc: "2.0", method: "session/update", params })}\n`,
|
|
),
|
|
);
|
|
const malformed = {
|
|
sessionId: "session-1",
|
|
update: { sessionUpdate: "usage_update", cost: { amount: 1, currency: secret } },
|
|
};
|
|
yield* send(malformed);
|
|
yield* send(malformed);
|
|
yield* send({
|
|
sessionId: "session-1",
|
|
update: { sessionUpdate: "usage_update", used: 10, size: 100 },
|
|
});
|
|
|
|
const notification = yield* TestClock.withLive(
|
|
Deferred.await(received).pipe(Effect.timeout("2 seconds")),
|
|
);
|
|
assert.equal(notification._tag, "SessionUpdate");
|
|
assert.deepEqual(notification.params, {
|
|
sessionId: "session-1",
|
|
update: { sessionUpdate: "usage_update", used: 10, size: 100 },
|
|
});
|
|
assert.isFalse(terminated);
|
|
assert.equal(transformCalls, 1);
|
|
|
|
const decodeFailed = events.find(({ stage }) => stage === "decode_failed");
|
|
expect(decodeFailed?.payload).toMatchObject({
|
|
operation: "decode-notification-payload",
|
|
method: "session/update",
|
|
issueSummary: expect.stringContaining("update.used missing"),
|
|
});
|
|
assert.lengthOf(
|
|
events.filter(({ stage }) => stage === "decode_failed"),
|
|
2,
|
|
);
|
|
assert.lengthOf(warnings, 1);
|
|
expect(warnings[0]).toMatchObject({
|
|
issueSummary: expect.stringContaining("update.used missing"),
|
|
});
|
|
assert.notInclude(encodeUnknownJsonString({ decodeFailed, warnings }), secret);
|
|
}),
|
|
);
|
|
|
|
it.effect("terminates when a callback on the reader dies", () =>
|
|
Effect.gen(function* () {
|
|
const { stdio, input } = yield* makeInMemoryStdio();
|
|
const termination = yield* Deferred.make<AcpError.AcpError>();
|
|
yield* AcpProtocol.makeAcpPatchedProtocol({
|
|
stdio,
|
|
serverRequestMethods: new Set(),
|
|
transformSessionUpdate: () => {
|
|
throw new Error("normalizer bug");
|
|
},
|
|
onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
|
|
});
|
|
|
|
yield* Queue.offer(
|
|
input,
|
|
encoder.encode(
|
|
`${encodeUnknownJsonString({
|
|
jsonrpc: "2.0",
|
|
method: "session/update",
|
|
params: {
|
|
sessionId: "session-1",
|
|
update: { sessionUpdate: "plan", entries: [] },
|
|
},
|
|
})}\n`,
|
|
),
|
|
);
|
|
|
|
const error = yield* TestClock.withLive(
|
|
Deferred.await(termination).pipe(Effect.timeout("2 seconds")),
|
|
);
|
|
assert.instanceOf(error, AcpError.AcpTransportError);
|
|
assert.equal((error as AcpError.AcpTransportError).operation, "read-input-stream");
|
|
}),
|
|
);
|
|
|
|
// regression: #9154 notifications went out with `id` and `headers`, which Grok CLI drops
|
|
it.effect("logs outgoing notifications when logOutgoing is enabled", () =>
|
|
Effect.gen(function* () {
|
|
const { stdio } = yield* makeInMemoryStdio();
|
|
const events: Array<AcpProtocol.AcpProtocolLogEvent> = [];
|
|
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
|
stdio,
|
|
serverRequestMethods: new Set(),
|
|
logOutgoing: true,
|
|
logger: (event) =>
|
|
Effect.sync(() => {
|
|
events.push(event);
|
|
}),
|
|
});
|
|
|
|
yield* transport.notify("session/cancel", { sessionId: "session-1" });
|
|
|
|
// A notification must not carry `id` or `headers`. Grok CLI drops frames that do.
|
|
assert.deepEqual(events, [
|
|
{
|
|
direction: "outgoing",
|
|
stage: "decoded",
|
|
payload: {
|
|
_tag: "Notification",
|
|
tag: "session/cancel",
|
|
payload: {
|
|
sessionId: "session-1",
|
|
},
|
|
},
|
|
},
|
|
{
|
|
direction: "outgoing",
|
|
stage: "raw",
|
|
payload:
|
|
'{"jsonrpc":"2.0","method":"session/cancel","params":{"sessionId":"session-1"}}\n',
|
|
},
|
|
]);
|
|
}),
|
|
);
|
|
|
|
it.effect("skips blank lines between agent messages", () =>
|
|
Effect.gen(function* () {
|
|
const { stdio, input } = yield* makeInMemoryStdio();
|
|
const outcome = yield* Deferred.make<string>();
|
|
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
|
stdio,
|
|
serverRequestMethods: new Set(),
|
|
onTermination: (error) => Deferred.succeed(outcome, error._tag).pipe(Effect.asVoid),
|
|
});
|
|
yield* transport.incoming.pipe(
|
|
Stream.runForEach((notification) => Deferred.succeed(outcome, notification._tag)),
|
|
Effect.forkScoped,
|
|
);
|
|
|
|
const update = encodeUnknownJsonString({
|
|
jsonrpc: "2.0",
|
|
method: "session/update",
|
|
params: { sessionId: "session-1", update: { sessionUpdate: "plan", entries: [] } },
|
|
});
|
|
yield* Queue.offer(input, encoder.encode(`\n\r\n \t\n${update}\n\n`));
|
|
|
|
assert.equal(yield* Deferred.await(outcome), "SessionUpdate");
|
|
}),
|
|
);
|
|
|
|
it.effect("logs decode failures without copying the cause or wire payload", () =>
|
|
Effect.gen(function* () {
|
|
const secret = "acp-wire-secret-sentinel";
|
|
const { stdio, input } = yield* makeInMemoryStdio();
|
|
const events: Array<AcpProtocol.AcpProtocolLogEvent> = [];
|
|
const termination = yield* Deferred.make<AcpError.AcpError>();
|
|
yield* AcpProtocol.makeAcpPatchedProtocol({
|
|
stdio,
|
|
serverRequestMethods: new Set(),
|
|
logIncoming: true,
|
|
logger: (event) =>
|
|
Effect.sync(() => {
|
|
events.push(event);
|
|
}),
|
|
onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
|
|
});
|
|
|
|
yield* Queue.offer(input, encoder.encode(`{"secret":"${secret}"\n`));
|
|
yield* Deferred.await(termination);
|
|
|
|
const event = events.find(({ stage }) => stage === "decode_failed");
|
|
assert.deepEqual(event, {
|
|
direction: "incoming",
|
|
stage: "decode_failed",
|
|
payload: {
|
|
operation: "decode-wire-message",
|
|
},
|
|
});
|
|
assert.notInclude(encodeUnknownJsonString(event), secret);
|
|
}),
|
|
);
|
|
|
|
it.effect("fails notification encoding through the declared ACP error channel", () =>
|
|
Effect.gen(function* () {
|
|
const { stdio } = yield* makeInMemoryStdio();
|
|
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
|
stdio,
|
|
serverRequestMethods: new Set(),
|
|
});
|
|
|
|
const bigintError = yield* transport.notify("x/test", 1n).pipe(Effect.flip);
|
|
assert.instanceOf(bigintError, AcpError.AcpProtocolParseError);
|
|
assert.equal(bigintError.operation, "encode-message");
|
|
assert.equal(bigintError.method, "x/test");
|
|
assert.isDefined(bigintError.cause);
|
|
assert.equal(
|
|
bigintError.message,
|
|
"ACP protocol operation 'encode-message' failed for method 'x/test'.",
|
|
);
|
|
|
|
const circular: Record<string, unknown> = {};
|
|
circular.self = circular;
|
|
const circularError = yield* transport.notify("x/test", circular).pipe(Effect.flip);
|
|
assert.instanceOf(circularError, AcpError.AcpProtocolParseError);
|
|
assert.equal(circularError.operation, "encode-message");
|
|
assert.equal(circularError.method, "x/test");
|
|
assert.isDefined(circularError.cause);
|
|
|
|
const requestError = yield* transport.request("x/request", 1n).pipe(
|
|
Effect.match({
|
|
onFailure: (error) => error,
|
|
onSuccess: () => assert.fail("Expected request encoding to fail"),
|
|
}),
|
|
);
|
|
assert.instanceOf(requestError, AcpError.AcpProtocolParseError);
|
|
assert.deepInclude(requestError, {
|
|
operation: "encode-message",
|
|
method: "x/request",
|
|
requestId: 1,
|
|
});
|
|
}),
|
|
);
|
|
|
|
it.effect("does not correlate a string response id with a numeric extension request id", () =>
|
|
Effect.gen(function* () {
|
|
const { stdio, input, output } = yield* makeInMemoryStdio();
|
|
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
|
stdio,
|
|
serverRequestMethods: new Set(),
|
|
});
|
|
|
|
const response = yield* transport
|
|
.request("x/test", { hello: "world" })
|
|
.pipe(Effect.forkScoped);
|
|
yield* Queue.take(output);
|
|
yield* Queue.offer(
|
|
input,
|
|
encoder.encode(
|
|
`${encodeUnknownJsonString({
|
|
jsonrpc: "2.0",
|
|
id: "1",
|
|
result: { ok: false },
|
|
})}\n`,
|
|
),
|
|
);
|
|
yield* Effect.yieldNow;
|
|
assert.isUndefined(response.pollUnsafe());
|
|
|
|
yield* Queue.offer(
|
|
input,
|
|
yield* encodeJsonl(ExtResponse, {
|
|
jsonrpc: "2.0",
|
|
id: 1,
|
|
result: { ok: true },
|
|
}),
|
|
);
|
|
assert.deepEqual(yield* Fiber.join(response), { ok: true });
|
|
}),
|
|
);
|
|
|
|
it.effect("correlates extension response errors with the originating request", () =>
|
|
Effect.gen(function* () {
|
|
const { stdio, input, output } = yield* makeInMemoryStdio();
|
|
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
|
stdio,
|
|
serverRequestMethods: new Set(),
|
|
});
|
|
|
|
const response = yield* transport
|
|
.request("x/private", { hello: "world" })
|
|
.pipe(Effect.forkScoped);
|
|
yield* Queue.take(output);
|
|
yield* Queue.offer(
|
|
input,
|
|
encoder.encode(
|
|
`${encodeUnknownJsonString({
|
|
jsonrpc: "2.0",
|
|
id: 1,
|
|
error: {
|
|
_tag: "Cause",
|
|
code: -32602,
|
|
message: "Invalid params",
|
|
data: [
|
|
{
|
|
_tag: "Fail",
|
|
error: {
|
|
code: -32602,
|
|
message: "Invalid params",
|
|
data: { field: "hello" },
|
|
},
|
|
},
|
|
],
|
|
},
|
|
})}\n`,
|
|
),
|
|
);
|
|
|
|
const error = yield* Fiber.join(response).pipe(
|
|
Effect.match({
|
|
onFailure: (error) => error,
|
|
onSuccess: () => assert.fail("Expected extension request to fail"),
|
|
}),
|
|
);
|
|
assert.instanceOf(error, AcpError.AcpRequestError);
|
|
assert.deepInclude(error, {
|
|
code: -32602,
|
|
errorMessage: "Invalid params",
|
|
method: "x/private",
|
|
requestId: 1,
|
|
operation: "receive-response",
|
|
});
|
|
}),
|
|
);
|
|
|
|
it.effect("preserves application error data in outgoing extension responses", () =>
|
|
Effect.gen(function* () {
|
|
const { stdio, input, output } = yield* makeInMemoryStdio();
|
|
const acknowledged = yield* Deferred.make<string>();
|
|
yield* AcpProtocol.makeAcpPatchedProtocol({
|
|
stdio,
|
|
serverRequestMethods: new Set(),
|
|
onExtRequest: () =>
|
|
Effect.fail(AcpError.AcpRequestError.invalidParams("bad input", { field: "name" })),
|
|
onOutgoingResponse: (requestId) =>
|
|
Deferred.succeed(acknowledged, requestId).pipe(Effect.asVoid),
|
|
});
|
|
|
|
yield* Queue.offer(
|
|
input,
|
|
encoder.encode(
|
|
encodeUnknownJsonString({
|
|
jsonrpc: "2.0",
|
|
id: "peer-1",
|
|
method: "x/test",
|
|
params: {},
|
|
}) + "\n",
|
|
),
|
|
);
|
|
|
|
assert.deepEqual(JSON.parse(yield* Queue.take(output)), {
|
|
jsonrpc: "2.0",
|
|
id: "peer-1",
|
|
error: { code: -32602, message: "bad input", data: { field: "name" } },
|
|
});
|
|
assert.equal(yield* Deferred.await(acknowledged), "peer-1");
|
|
}),
|
|
);
|
|
|
|
it.effect("completes a batch with successful and failed extension responses", () =>
|
|
Effect.gen(function* () {
|
|
const { stdio, input, output } = yield* makeInMemoryStdio();
|
|
const acknowledgements = yield* Queue.unbounded<string>();
|
|
yield* AcpProtocol.makeAcpPatchedProtocol({
|
|
stdio,
|
|
serverRequestMethods: new Set(),
|
|
onExtRequest: (method) =>
|
|
method === "x/success"
|
|
? Effect.succeed({ ok: true })
|
|
: Effect.fail(AcpError.AcpRequestError.invalidParams("bad input", { field: "name" })),
|
|
onOutgoingResponse: (requestId) => Queue.offer(acknowledgements, requestId),
|
|
});
|
|
|
|
yield* Queue.offer(
|
|
input,
|
|
encoder.encode(
|
|
encodeUnknownJsonString([
|
|
{ jsonrpc: "2.0", id: 0, method: "x/success", params: {} },
|
|
{ jsonrpc: "2.0", id: "peer-1", method: "x/failure", params: {} },
|
|
]) + "\n",
|
|
),
|
|
);
|
|
|
|
assert.deepEqual(JSON.parse(yield* Queue.take(output)), [
|
|
{ jsonrpc: "2.0", id: 0, result: { ok: true } },
|
|
{
|
|
jsonrpc: "2.0",
|
|
id: "peer-1",
|
|
error: { code: -32602, message: "bad input", data: { field: "name" } },
|
|
},
|
|
]);
|
|
assert.equal(yield* Queue.take(acknowledgements), "peer-1");
|
|
}),
|
|
);
|
|
|
|
it.effect.each([
|
|
{
|
|
name: "typed failure",
|
|
cause: [{ _tag: "Fail", error: { code: -32602, message: "bad input", data: null } }],
|
|
error: { code: -32602, message: "bad input", data: null },
|
|
},
|
|
{
|
|
name: "typed failure with interruption",
|
|
cause: [
|
|
{ _tag: "Fail", error: { code: -32602, message: "bad input", data: { field: "name" } } },
|
|
{ _tag: "Interrupt", fiberId: null },
|
|
],
|
|
error: { code: -32602, message: "bad input", data: { field: "name" } },
|
|
},
|
|
{
|
|
name: "defect",
|
|
cause: [{ _tag: "Die", defect: "private defect" }],
|
|
error: { code: -32603, message: "Internal error" },
|
|
},
|
|
{
|
|
name: "failure with a defect",
|
|
cause: [
|
|
{ _tag: "Fail", error: { code: -32602, message: "bad input" } },
|
|
{ _tag: "Die", defect: "private defect" },
|
|
],
|
|
error: { code: -32603, message: "Internal error" },
|
|
},
|
|
] as const)("emits a standard ACP error for a core $name", ({ cause, error }) =>
|
|
Effect.gen(function* () {
|
|
const { stdio, output } = yield* makeInMemoryStdio();
|
|
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
|
stdio,
|
|
serverRequestMethods: new Set(),
|
|
});
|
|
|
|
yield* transport.serverProtocol.send(0, {
|
|
_tag: "Exit",
|
|
requestId: 0,
|
|
exit: { _tag: "Failure", cause },
|
|
});
|
|
|
|
assert.deepEqual(JSON.parse(yield* Queue.take(output)), {
|
|
jsonrpc: "2.0",
|
|
id: 0,
|
|
error,
|
|
});
|
|
}),
|
|
);
|
|
|
|
it.effect("answers an extension request whose handler also dies as an internal error", () =>
|
|
Effect.gen(function* () {
|
|
const { stdio, input, output } = yield* makeInMemoryStdio();
|
|
yield* AcpProtocol.makeAcpPatchedProtocol({
|
|
stdio,
|
|
serverRequestMethods: new Set(),
|
|
onExtRequest: () =>
|
|
Effect.fail(AcpError.AcpRequestError.invalidParams("bad params")).pipe(
|
|
Effect.ensuring(Effect.die(new Error("cleanup bug"))),
|
|
),
|
|
});
|
|
|
|
yield* Queue.offer(
|
|
input,
|
|
yield* encodeJsonl(ExtRequest, {
|
|
jsonrpc: "2.0",
|
|
id: 9,
|
|
method: "x/test",
|
|
params: { hello: "world" },
|
|
headers: [],
|
|
}),
|
|
);
|
|
const decodeJsonRpcErrorResponse = Schema.decodeEffect(
|
|
Schema.fromJsonString(JsonRpcErrorResponse),
|
|
);
|
|
|
|
const response = yield* decodeJsonRpcErrorResponse(yield* Queue.take(output));
|
|
assert.equal(response.id, 9);
|
|
assert.equal(response.error.code, -32603);
|
|
}),
|
|
);
|
|
|
|
it.effect("preserves zero-valued ids for inbound core client requests", () =>
|
|
Effect.gen(function* () {
|
|
const { stdio, input, output } = yield* makeInMemoryStdio();
|
|
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
|
stdio,
|
|
serverRequestMethods: new Set(["session/request_permission"]),
|
|
});
|
|
const inboundRequest = yield* Deferred.make<unknown>();
|
|
|
|
yield* transport.serverProtocol
|
|
.run((_clientId, message) => Deferred.succeed(inboundRequest, message).pipe(Effect.asVoid))
|
|
.pipe(Effect.forkScoped);
|
|
|
|
yield* Queue.offer(
|
|
input,
|
|
yield* encodeJsonl(RequestPermissionRequest, {
|
|
jsonrpc: "2.0",
|
|
id: 0,
|
|
method: "session/request_permission",
|
|
params: {
|
|
sessionId: "session-1",
|
|
title: "Allow mock action",
|
|
subject: {
|
|
type: "tool_call",
|
|
toolCall: {
|
|
toolCallId: "tool-1",
|
|
title: "Allow mock action",
|
|
},
|
|
},
|
|
options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
|
|
},
|
|
headers: [],
|
|
}),
|
|
);
|
|
|
|
const message = yield* Deferred.await(inboundRequest);
|
|
assert.deepEqual(message, {
|
|
_tag: "Request",
|
|
id: 0,
|
|
tag: "session/request_permission",
|
|
payload: {
|
|
sessionId: "session-1",
|
|
title: "Allow mock action",
|
|
subject: {
|
|
type: "tool_call",
|
|
toolCall: {
|
|
toolCallId: "tool-1",
|
|
title: "Allow mock action",
|
|
},
|
|
},
|
|
options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
|
|
},
|
|
headers: [],
|
|
});
|
|
|
|
yield* transport.serverProtocol.send(0, {
|
|
_tag: "Exit",
|
|
requestId: 0,
|
|
exit: {
|
|
_tag: "Success",
|
|
value: {
|
|
outcome: {
|
|
outcome: "selected",
|
|
optionId: "allow",
|
|
},
|
|
},
|
|
},
|
|
});
|
|
|
|
const outbound = yield* Queue.take(output);
|
|
assert.deepEqual(yield* decodeRequestPermissionResponse(outbound), {
|
|
jsonrpc: "2.0",
|
|
id: 0,
|
|
result: {
|
|
outcome: {
|
|
outcome: "selected",
|
|
optionId: "allow",
|
|
},
|
|
},
|
|
});
|
|
}),
|
|
);
|
|
|
|
it.effect("acknowledges outgoing responses and reports encoding failures by request id", () =>
|
|
Effect.gen(function* () {
|
|
const { stdio } = yield* makeInMemoryStdio();
|
|
const acknowledged = yield* Deferred.make<string>();
|
|
const failed = yield* Deferred.make<readonly [string, AcpError.AcpError]>();
|
|
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
|
stdio,
|
|
serverRequestMethods: new Set(),
|
|
onOutgoingResponse: (requestId) =>
|
|
Deferred.succeed(acknowledged, requestId).pipe(Effect.asVoid),
|
|
onOutgoingResponseFailure: (requestId, error) =>
|
|
Deferred.succeed(failed, [requestId, error]).pipe(Effect.asVoid),
|
|
});
|
|
|
|
yield* transport.serverProtocol.send(0, {
|
|
_tag: "Exit",
|
|
requestId: "success-1",
|
|
exit: { _tag: "Success", value: { ok: true } },
|
|
});
|
|
assert.equal(yield* Deferred.await(acknowledged), "success-1");
|
|
|
|
const circular: { self?: unknown } = {};
|
|
circular.self = circular;
|
|
yield* transport.serverProtocol
|
|
.send(0, {
|
|
_tag: "Exit",
|
|
requestId: "failure-1",
|
|
exit: { _tag: "Success", value: circular },
|
|
})
|
|
.pipe(Effect.exit);
|
|
const [requestId, error] = yield* Deferred.await(failed);
|
|
assert.equal(requestId, "failure-1");
|
|
assert.instanceOf(error, AcpError.AcpProtocolParseError);
|
|
}),
|
|
);
|
|
|
|
it.effect("acknowledges a response only after the stdout write completes", () =>
|
|
Effect.gen(function* () {
|
|
const writeStarted = yield* Deferred.make<void>();
|
|
const releaseWrite = yield* Deferred.make<void>();
|
|
const acknowledged = yield* Deferred.make<string>();
|
|
const stdio = Stdio.make({
|
|
args: Effect.succeed([]),
|
|
stdin: Stream.never,
|
|
stdout: () =>
|
|
Sink.forEach(() =>
|
|
Deferred.succeed(writeStarted, undefined).pipe(
|
|
Effect.andThen(Deferred.await(releaseWrite)),
|
|
),
|
|
),
|
|
stderr: () => Sink.drain,
|
|
});
|
|
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
|
stdio,
|
|
serverRequestMethods: new Set(),
|
|
onOutgoingResponse: (requestId) =>
|
|
Deferred.succeed(acknowledged, requestId).pipe(Effect.asVoid),
|
|
});
|
|
const sendFiber = yield* transport.serverProtocol
|
|
.send(0, {
|
|
_tag: "Exit",
|
|
requestId: "held-write",
|
|
exit: { _tag: "Success", value: { ok: true } },
|
|
})
|
|
.pipe(Effect.forkScoped);
|
|
|
|
yield* Deferred.await(writeStarted);
|
|
assert.isUndefined(sendFiber.pollUnsafe());
|
|
assert.isFalse(yield* Deferred.isDone(acknowledged));
|
|
yield* Deferred.succeed(releaseWrite, undefined);
|
|
yield* Fiber.join(sendFiber);
|
|
assert.equal(yield* Deferred.await(acknowledged), "held-write");
|
|
}),
|
|
);
|
|
|
|
it.effect("fails current, queued, and future responses when the stdout writer fails", () =>
|
|
Effect.gen(function* () {
|
|
const writeStarted = yield* Deferred.make<void>();
|
|
const releaseFailure = yield* Deferred.make<void>();
|
|
const failures = yield* Queue.unbounded<string>();
|
|
const terminated = yield* Deferred.make<AcpError.AcpError>();
|
|
const stdio = Stdio.make({
|
|
args: Effect.succeed([]),
|
|
stdin: Stream.never,
|
|
stdout: () =>
|
|
Sink.forEach(() =>
|
|
Deferred.succeed(writeStarted, undefined).pipe(
|
|
Effect.andThen(Deferred.await(releaseFailure)),
|
|
Effect.andThen(Effect.die("stdout failed")),
|
|
),
|
|
),
|
|
stderr: () => Sink.drain,
|
|
});
|
|
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
|
stdio,
|
|
serverRequestMethods: new Set(),
|
|
onOutgoingResponseFailure: (requestId) => Queue.offer(failures, requestId),
|
|
onTermination: (error) => Deferred.succeed(terminated, error).pipe(Effect.asVoid),
|
|
});
|
|
const send = (requestId: string) =>
|
|
transport.serverProtocol
|
|
.send(0, {
|
|
_tag: "Exit",
|
|
requestId,
|
|
exit: { _tag: "Success", value: { ok: true } },
|
|
})
|
|
.pipe(Effect.exit);
|
|
const current = yield* send("current").pipe(Effect.forkScoped);
|
|
yield* Deferred.await(writeStarted);
|
|
const queued = yield* send("queued").pipe(Effect.forkScoped);
|
|
yield* Effect.yieldNow;
|
|
assert.isUndefined(current.pollUnsafe());
|
|
assert.isUndefined(queued.pollUnsafe());
|
|
yield* Deferred.succeed(releaseFailure, undefined);
|
|
assert.instanceOf(yield* Deferred.await(terminated), AcpError.AcpTransportError);
|
|
yield* Fiber.join(current);
|
|
yield* Fiber.join(queued);
|
|
yield* send("future");
|
|
|
|
assert.deepEqual(
|
|
new Set(yield* Queue.takeN(failures, 3)),
|
|
new Set(["current", "queued", "future"]),
|
|
);
|
|
}),
|
|
);
|
|
|
|
it.effect(
|
|
"atomically rejects an admitted response when the writer closes before queue offer",
|
|
() =>
|
|
Effect.gen(function* () {
|
|
const admitted = yield* Deferred.make<void>();
|
|
const releaseAdmission = yield* Deferred.make<void>();
|
|
const failures = yield* Queue.unbounded<string>();
|
|
const protocolScope = yield* Scope.make();
|
|
const stdio = Stdio.make({
|
|
args: Effect.succeed([]),
|
|
stdin: Stream.never,
|
|
stdout: () => Sink.drain,
|
|
stderr: () => Sink.drain,
|
|
});
|
|
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
|
stdio,
|
|
serverRequestMethods: new Set(),
|
|
onOutgoingResponseFailure: (requestId) => Queue.offer(failures, requestId),
|
|
testHooks: {
|
|
onOutgoingWriteAdmitted: () =>
|
|
Deferred.succeed(admitted, undefined).pipe(
|
|
Effect.andThen(Deferred.await(releaseAdmission)),
|
|
),
|
|
},
|
|
}).pipe(Effect.provideService(Scope.Scope, protocolScope));
|
|
const send = (requestId: string) =>
|
|
transport.serverProtocol
|
|
.send(0, {
|
|
_tag: "Exit",
|
|
requestId,
|
|
exit: { _tag: "Success", value: { ok: true } },
|
|
})
|
|
.pipe(Effect.exit);
|
|
const admittedSend = yield* send("admitted").pipe(Effect.forkScoped);
|
|
|
|
yield* Deferred.await(admitted);
|
|
yield* Scope.close(protocolScope, Exit.void);
|
|
yield* Deferred.succeed(releaseAdmission, undefined);
|
|
yield* Fiber.join(admittedSend);
|
|
yield* send("future");
|
|
|
|
assert.deepEqual(yield* Queue.takeN(failures, 2), ["admitted", "future"]);
|
|
}),
|
|
);
|
|
|
|
it.effect("drops agent-internal JSON-RPC responses with non-numeric request ids", () =>
|
|
Effect.gen(function* () {
|
|
const { stdio, input } = yield* makeInMemoryStdio();
|
|
const notifications =
|
|
yield* Deferred.make<ReadonlyArray<AcpProtocol.AcpIncomingNotification>>();
|
|
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
|
stdio,
|
|
serverRequestMethods: new Set(),
|
|
});
|
|
|
|
yield* transport.incoming.pipe(
|
|
Stream.take(1),
|
|
Stream.runCollect,
|
|
Effect.flatMap((notificationChunk) => Deferred.succeed(notifications, notificationChunk)),
|
|
Effect.forkScoped,
|
|
);
|
|
|
|
yield* Queue.offer(
|
|
input,
|
|
encoder.encode(
|
|
`${encodeUnknownJsonString({
|
|
jsonrpc: "2.0",
|
|
id: "skills-reload",
|
|
result: {
|
|
reloaded: true,
|
|
},
|
|
})}\n`,
|
|
),
|
|
);
|
|
yield* Queue.offer(
|
|
input,
|
|
yield* encodeJsonl(SessionUpdateNotification, {
|
|
jsonrpc: "2.0",
|
|
method: "session/update",
|
|
params: {
|
|
sessionId: "session-1",
|
|
update: {
|
|
sessionUpdate: "plan",
|
|
entries: [
|
|
{
|
|
content: "Reload skills",
|
|
priority: "high",
|
|
status: "in_progress",
|
|
},
|
|
],
|
|
},
|
|
},
|
|
}),
|
|
);
|
|
|
|
const [update] = yield* Deferred.await(notifications);
|
|
assert.equal(update?._tag, "SessionUpdate");
|
|
}),
|
|
);
|
|
|
|
it.effect("cleans up interrupted extension requests before a late response arrives", () =>
|
|
Effect.gen(function* () {
|
|
const { stdio, input, output } = yield* makeInMemoryStdio();
|
|
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
|
stdio,
|
|
serverRequestMethods: new Set(),
|
|
});
|
|
const lateResponse = yield* Deferred.make<unknown>();
|
|
|
|
yield* transport.clientProtocol
|
|
.run(0, (message) => Deferred.succeed(lateResponse, message).pipe(Effect.asVoid))
|
|
.pipe(Effect.forkScoped);
|
|
|
|
const response = yield* transport
|
|
.request("x/test", { hello: "world" })
|
|
.pipe(Effect.forkScoped);
|
|
const outbound = yield* Queue.take(output);
|
|
assert.deepEqual(yield* decodeExtRequest(outbound), {
|
|
jsonrpc: "2.0",
|
|
id: 1,
|
|
method: "x/test",
|
|
params: {
|
|
hello: "world",
|
|
},
|
|
headers: [],
|
|
});
|
|
|
|
yield* Fiber.interrupt(response);
|
|
yield* Queue.offer(
|
|
input,
|
|
yield* encodeJsonl(ExtResponse, {
|
|
jsonrpc: "2.0",
|
|
id: 1,
|
|
result: {
|
|
ok: true,
|
|
},
|
|
}),
|
|
);
|
|
|
|
const message = yield* Deferred.await(lateResponse);
|
|
assert.deepEqual(message, {
|
|
_tag: "Exit",
|
|
requestId: 1,
|
|
exit: {
|
|
_tag: "Success",
|
|
value: {
|
|
ok: true,
|
|
},
|
|
},
|
|
});
|
|
}),
|
|
);
|
|
|
|
it.effect("fails pending and later requests when input ends before the process exits", () =>
|
|
Effect.gen(function* () {
|
|
const { stdio, input, output } = yield* makeInMemoryStdio();
|
|
const termination = yield* Deferred.make<AcpError.AcpError>();
|
|
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
|
stdio,
|
|
terminationError: Effect.never,
|
|
serverRequestMethods: new Set(),
|
|
onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
|
|
});
|
|
const pending = yield* transport
|
|
.request("x/test", { hello: "world" })
|
|
.pipe(Effect.flip, Effect.orDie, Effect.forkScoped);
|
|
yield* Queue.take(output);
|
|
yield* Queue.offer(input, encoder.encode('{"jsonrpc":"2.0","id":1,"result":'));
|
|
yield* Queue.end(input);
|
|
|
|
const error = yield* Deferred.await(termination);
|
|
assert.instanceOf(error, AcpError.AcpInputStreamEndedError);
|
|
assert.strictEqual(yield* Fiber.join(pending), error);
|
|
assert.strictEqual(
|
|
yield* transport.request("x/test", { hello: "later" }).pipe(Effect.flip, Effect.orDie),
|
|
error,
|
|
);
|
|
assert.strictEqual(
|
|
yield* transport.notify("session/cancel", { sessionId: "session-1" }).pipe(Effect.flip),
|
|
error,
|
|
);
|
|
}),
|
|
);
|
|
|
|
it.effect("answers a pending request from a final response without a trailing newline", () =>
|
|
Effect.gen(function* () {
|
|
const { stdio, input, output } = yield* makeInMemoryStdio();
|
|
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
|
stdio,
|
|
serverRequestMethods: new Set(),
|
|
});
|
|
const pending = yield* transport
|
|
.request("x/test", { hello: "world" })
|
|
.pipe(Effect.forkScoped);
|
|
yield* Queue.take(output);
|
|
yield* Queue.offer(
|
|
input,
|
|
encoder.encode(encodeUnknownJsonString({ jsonrpc: "2.0", id: 1, result: { ok: true } })),
|
|
);
|
|
yield* Queue.end(input);
|
|
|
|
assert.deepEqual(yield* Fiber.join(pending), { ok: true });
|
|
}),
|
|
);
|
|
|
|
it.effect("propagates the real child exit code when the input stream ends", () =>
|
|
Effect.gen(function* () {
|
|
const handle = yield* makeHandle({ ACP_MOCK_EXIT_IMMEDIATELY_CODE: "7" });
|
|
const firstMessage = yield* Deferred.make<unknown>();
|
|
const termination = yield* Deferred.make<AcpError.AcpError>();
|
|
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
|
stdio: makeChildStdio(handle),
|
|
terminationError: makeTerminationError(handle),
|
|
serverRequestMethods: new Set(),
|
|
onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
|
|
});
|
|
|
|
yield* transport.clientProtocol
|
|
.run(0, (message) => Deferred.succeed(firstMessage, message).pipe(Effect.asVoid))
|
|
.pipe(Effect.forkScoped);
|
|
|
|
const message = yield* Deferred.await(firstMessage);
|
|
const exitError = yield* Deferred.await(termination);
|
|
assert.instanceOf(exitError, AcpError.AcpProcessExitedError);
|
|
assert.equal((exitError as AcpError.AcpProcessExitedError).code, 7);
|
|
assert.equal((message as { readonly _tag?: string })._tag, "ClientProtocolError");
|
|
const defect = (message as { readonly error: { readonly reason: unknown } }).error.reason as {
|
|
readonly _tag: string;
|
|
readonly message: string;
|
|
readonly cause: unknown;
|
|
};
|
|
assert.equal(defect._tag, "RpcClientDefect");
|
|
assert.equal(defect.message, "ACP protocol terminated.");
|
|
assert.instanceOf(defect.cause, AcpError.AcpProcessExitedError);
|
|
assert.equal((defect.cause as AcpError.AcpProcessExitedError).code, 7);
|
|
}),
|
|
);
|
|
|
|
it.effect("does not treat intentional serverProtocol.end as a transport failure", () =>
|
|
Effect.gen(function* () {
|
|
const { stdio, input } = yield* makeInMemoryStdio();
|
|
const terminations = yield* Ref.make(0);
|
|
const writerExit = yield* Deferred.make<{ readonly intentionalEnd: boolean }>();
|
|
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
|
stdio,
|
|
serverRequestMethods: new Set(),
|
|
onTermination: () => Ref.update(terminations, (count) => count + 1),
|
|
testHooks: {
|
|
onOutgoingWriterExit: (detail) =>
|
|
Deferred.succeed(writerExit, detail).pipe(Effect.asVoid),
|
|
},
|
|
});
|
|
|
|
yield* transport.serverProtocol.end(0);
|
|
const exitDetail = yield* Deferred.await(writerExit);
|
|
assert.isTrue(exitDetail.intentionalEnd);
|
|
assert.equal(yield* Ref.get(terminations), 0);
|
|
|
|
yield* Queue.end(input);
|
|
}),
|
|
);
|
|
|
|
it.effect("does not emit a second process-exit error after a decode failure", () =>
|
|
Effect.gen(function* () {
|
|
const handle = yield* makeHandle({
|
|
ACP_MOCK_MALFORMED_OUTPUT: "1",
|
|
ACP_MOCK_MALFORMED_OUTPUT_EXIT_CODE: "23",
|
|
});
|
|
const terminationCalls = yield* Ref.make(0);
|
|
const firstMessage = yield* Deferred.make<unknown>();
|
|
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
|
stdio: makeChildStdio(handle),
|
|
terminationError: makeTerminationError(handle),
|
|
serverRequestMethods: new Set(),
|
|
onTermination: () => Ref.update(terminationCalls, (count) => count + 1),
|
|
});
|
|
|
|
yield* transport.clientProtocol
|
|
.run(0, (message) => Deferred.succeed(firstMessage, message).pipe(Effect.asVoid))
|
|
.pipe(Effect.forkScoped);
|
|
|
|
const message = yield* Deferred.await(firstMessage);
|
|
assert.equal(yield* Ref.get(terminationCalls), 1);
|
|
assert.equal((message as { readonly _tag?: string })._tag, "ClientProtocolError");
|
|
const defect = (message as { readonly error: { readonly reason: unknown } }).error.reason as {
|
|
readonly _tag: string;
|
|
readonly message: string;
|
|
readonly cause: unknown;
|
|
};
|
|
assert.equal(defect._tag, "RpcClientDefect");
|
|
assert.equal(defect.message, "ACP protocol terminated.");
|
|
assert.instanceOf(defect.cause, AcpError.AcpProtocolParseError);
|
|
}),
|
|
);
|
|
|
|
it.effect.each(["request", "notification"] as const)(
|
|
"rejects a %s if the connection ends while its logger is running",
|
|
(operation) =>
|
|
Effect.gen(function* () {
|
|
const { stdio, input, output } = yield* makeInMemoryStdio();
|
|
const writeStarted = yield* Deferred.make<void>();
|
|
const releaseWrite = yield* Deferred.make<void>();
|
|
const terminated = yield* Deferred.make<AcpError.AcpError>();
|
|
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
|
|
stdio,
|
|
serverRequestMethods: new Set(),
|
|
logOutgoing: true,
|
|
logger: (event) =>
|
|
event.stage === "raw"
|
|
? Deferred.succeed(writeStarted, undefined).pipe(
|
|
Effect.andThen(Deferred.await(releaseWrite)),
|
|
)
|
|
: Effect.void,
|
|
onTermination: (error) => Deferred.succeed(terminated, error).pipe(Effect.asVoid),
|
|
});
|
|
const send = yield* (
|
|
operation === "request"
|
|
? transport.request("x/test", { hello: "world" })
|
|
: transport.notify("session/cancel", { sessionId: "session-1" })
|
|
).pipe(Effect.forkScoped);
|
|
|
|
yield* Deferred.await(writeStarted);
|
|
yield* Queue.end(input);
|
|
const error = yield* Deferred.await(terminated);
|
|
yield* Deferred.succeed(releaseWrite, undefined);
|
|
|
|
const failure = yield* Fiber.join(send).pipe(
|
|
Effect.match({
|
|
onFailure: (failure) => failure,
|
|
onSuccess: () => assert.fail("Expected the send to fail after termination"),
|
|
}),
|
|
);
|
|
assert.strictEqual(failure, error);
|
|
assert.equal(yield* Queue.size(output), 0);
|
|
}),
|
|
);
|
|
});
|