@niwa-labs/acp 0.0.0-stage → 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +2 -2
- package/package.json +18 -4
- package/scripts/gen-acp.ts +284 -0
- package/src/client.ts +362 -0
- package/src/content.ts +24 -0
- package/src/generated/acp-0.14.ts +484 -0
- package/src/generated/acp-1.3.ts +906 -0
- package/src/index.ts +8 -0
- package/src/variant.ts +85 -0
- package/test/client.test.ts +347 -0
- package/test/generated.test.ts +31 -0
- package/test/variant.test.ts +39 -0
- package/tsconfig.json +7 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { AcpClient } from "./client.ts";
|
|
2
|
+
export type { AcpClientOptions, AgentNotification, AgentRequest, CallOptions, RequestId, RpcFrame, RpcOutcome, Written } from "./client.ts";
|
|
3
|
+
export { answerText } from "./content.ts";
|
|
4
|
+
export type { AcpContent } from "./content.ts";
|
|
5
|
+
export { acpVariant, readVariant } from "./variant.ts";
|
|
6
|
+
export type { Read, UnknownVariant } from "./variant.ts";
|
|
7
|
+
export * as Acp014 from "./generated/acp-0.14.ts";
|
|
8
|
+
export * as Acp13 from "./generated/acp-1.3.ts";
|
package/src/variant.ts
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reading a message of an ACP dialect against niwa's snapshot of it.
|
|
3
|
+
*
|
|
4
|
+
* A message whose variant the snapshot does not know means the harness got newer than niwa: it
|
|
5
|
+
* must never crash a session, so it reads as a typed unknown carrying the protocol, the value of
|
|
6
|
+
* its discriminator and the message as it came. A message of a variant the snapshot does know,
|
|
7
|
+
* whose fields do not fit it, is not the same: it is a malformed message, and the fields it is
|
|
8
|
+
* wrong in are kept to be told to the agent.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type { z } from "zod";
|
|
12
|
+
|
|
13
|
+
import type { JsonValue } from "@niwa-labs/core";
|
|
14
|
+
import { VariantNameSchema, rawJson } from "@niwa-labs/harness";
|
|
15
|
+
import type { ProtocolName, VariantName } from "@niwa-labs/harness";
|
|
16
|
+
|
|
17
|
+
/** A message the snapshot of a protocol does not know. */
|
|
18
|
+
export interface UnknownVariant {
|
|
19
|
+
/** The protocol, as niwa names its snapshot (`acp-0.14/claude-code`, ...). */
|
|
20
|
+
readonly protocol: ProtocolName;
|
|
21
|
+
/** The value of the discriminator, as far as it could be read. */
|
|
22
|
+
readonly variant: VariantName;
|
|
23
|
+
readonly raw: JsonValue;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* What reading a message gave: the typed message, or the unknown it is. `invalid` is set when the
|
|
28
|
+
* variant is known and the message does not fit it, and says where, as `path: reason` for each field.
|
|
29
|
+
*/
|
|
30
|
+
export type Read<T> =
|
|
31
|
+
| { readonly ok: true; readonly value: T }
|
|
32
|
+
| { readonly ok: false; readonly unknown: UnknownVariant; readonly invalid?: string };
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Where a message holds its discriminator: the `method`, and for a `session/update` the
|
|
36
|
+
* `sessionUpdate` of the update (as `acpVariant` reads them).
|
|
37
|
+
*/
|
|
38
|
+
const DISCRIMINATOR_PATHS: readonly (readonly string[])[] = [["method"], ["params", "update", "sessionUpdate"]];
|
|
39
|
+
|
|
40
|
+
/** Whether an issue says that no variant of the snapshot has the value the message's discriminator holds. */
|
|
41
|
+
function missesDiscriminator(issue: z.core.$ZodIssue): boolean {
|
|
42
|
+
if (issue.code !== "invalid_union" || !("discriminator" in issue)) return false;
|
|
43
|
+
return DISCRIMINATOR_PATHS.some((path) => path.length === issue.path.length && path.every((key, at) => key === issue.path[at]));
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Read `value` with `schema`; on failure, the unknown it is, with where the message is wrong when its
|
|
48
|
+
* variant is known. `variant` names the discriminator of the message (`method`, or `method` and
|
|
49
|
+
* `sessionUpdate` for a session update).
|
|
50
|
+
*/
|
|
51
|
+
export function readVariant<S extends z.ZodType>(
|
|
52
|
+
schema: S,
|
|
53
|
+
value: unknown,
|
|
54
|
+
protocol: ProtocolName,
|
|
55
|
+
variant: (value: unknown) => string,
|
|
56
|
+
): Read<z.output<S>> {
|
|
57
|
+
const parsed = schema.safeParse(value);
|
|
58
|
+
if (parsed.success) return { ok: true, value: parsed.data };
|
|
59
|
+
const unknown: UnknownVariant = { protocol, variant: VariantNameSchema.parse(variant(value)), raw: rawJson(value) };
|
|
60
|
+
if (parsed.error.issues.some(missesDiscriminator)) return { ok: false, unknown };
|
|
61
|
+
const invalid = parsed.error.issues.map((issue) => `${issue.path.join(".") || "(message)"}: ${issue.message}`).join("; ");
|
|
62
|
+
return { ok: false, unknown, invalid };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The string at `key` of an object, or `""`. */
|
|
66
|
+
function field(value: unknown, key: string): string {
|
|
67
|
+
const found = member(value, key);
|
|
68
|
+
return typeof found === "string" ? found : "";
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** The member `key` of an object, when it is one. */
|
|
72
|
+
function member(value: unknown, key: string): unknown {
|
|
73
|
+
if (typeof value !== "object" || value === null) return undefined;
|
|
74
|
+
return key in value ? Object.getOwnPropertyDescriptor(value, key)?.value : undefined;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* The discriminator of a JSON-RPC message: its `method`, and for a `session/update` the
|
|
79
|
+
* `sessionUpdate` of the update too (`session/update tool_call`).
|
|
80
|
+
*/
|
|
81
|
+
export function acpVariant(message: unknown): string {
|
|
82
|
+
const method = field(message, "method");
|
|
83
|
+
if (method !== "session/update") return method;
|
|
84
|
+
return `${method} ${field(member(member(message, "params"), "update"), "sessionUpdate")}`;
|
|
85
|
+
}
|
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
import { expect, test } from "bun:test";
|
|
2
|
+
|
|
3
|
+
import { AcpClient } from "../src/index.ts";
|
|
4
|
+
import type { AcpClientOptions, AgentNotification, AgentRequest, RpcOutcome } from "../src/index.ts";
|
|
5
|
+
|
|
6
|
+
function client(overrides: Partial<AcpClientOptions> = {}) {
|
|
7
|
+
const written: Array<Record<string, unknown>> = [];
|
|
8
|
+
const requests: AgentRequest[] = [];
|
|
9
|
+
const notifications: AgentNotification[] = [];
|
|
10
|
+
const unreadable: string[] = [];
|
|
11
|
+
let overflowed = 0;
|
|
12
|
+
const acp = new AcpClient({
|
|
13
|
+
write: (line) => {
|
|
14
|
+
written.push(JSON.parse(line) as Record<string, unknown>);
|
|
15
|
+
return "accepted";
|
|
16
|
+
},
|
|
17
|
+
onRequest: (request) => requests.push(request),
|
|
18
|
+
onNotification: (notification) => notifications.push(notification),
|
|
19
|
+
onUnreadable: (line) => unreadable.push(line),
|
|
20
|
+
onOverflow: () => {
|
|
21
|
+
overflowed += 1;
|
|
22
|
+
},
|
|
23
|
+
callTimeoutMs: 1_000,
|
|
24
|
+
...overrides,
|
|
25
|
+
});
|
|
26
|
+
return { acp, written, requests, notifications, unreadable, overflowed: () => overflowed };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
test("an answer settles the call of its id, even when it comes in pieces and out of order", async () => {
|
|
30
|
+
const { acp, written } = client();
|
|
31
|
+
const first = acp.request("a", {});
|
|
32
|
+
const second = acp.request("b", {});
|
|
33
|
+
expect(written.map((frame) => [frame["id"], frame["method"]])).toEqual([
|
|
34
|
+
[1, "a"],
|
|
35
|
+
[2, "b"],
|
|
36
|
+
]);
|
|
37
|
+
acp.feed('{"jsonrpc":"2.0","id":2,"res');
|
|
38
|
+
acp.feed('ult":{"x":2}}\n{"jsonrpc":"2.0","id":1,"result":{"x":1}}\n');
|
|
39
|
+
expect(await first).toEqual({ ok: true, result: { x: 1 } });
|
|
40
|
+
expect(await second).toEqual({ ok: true, result: { x: 2 } });
|
|
41
|
+
expect(acp.waiting).toBe(0);
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
test("a call fails by how far it got: refused, never written, unanswered in time, or cut off by the close", async () => {
|
|
45
|
+
const { acp } = client();
|
|
46
|
+
const refused = acp.request("a", {});
|
|
47
|
+
acp.receive('{"jsonrpc":"2.0","id":1,"error":{"code":-32602,"message":"busy"}}');
|
|
48
|
+
expect(await refused).toEqual({ ok: false, error: "busy", code: -32602, dispatch: "refused" });
|
|
49
|
+
|
|
50
|
+
const unwritable = client({ write: () => "unsent" }).acp;
|
|
51
|
+
expect(await unwritable.request("a", {})).toEqual({ ok: false, error: "the request was not written", dispatch: "unsent" });
|
|
52
|
+
|
|
53
|
+
const slow = client({ callTimeoutMs: 10 });
|
|
54
|
+
expect(await slow.acp.request("a", {})).toEqual({ ok: false, error: "the call a timed out", dispatch: "uncertain", timedOut: true });
|
|
55
|
+
|
|
56
|
+
const cut = acp.request("b", {});
|
|
57
|
+
acp.close("the agent exited");
|
|
58
|
+
expect(await cut).toEqual({ ok: false, error: "the agent exited", dispatch: "uncertain" });
|
|
59
|
+
// After the close nothing more is written.
|
|
60
|
+
expect(await acp.request("c", {})).toEqual({ ok: false, error: "the agent exited", dispatch: "unsent" });
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
test("an overdue call is cancelled, given one more timeout, and fails with the timeout even when it is answered", async () => {
|
|
64
|
+
const { acp } = client({ callTimeoutMs: 10 });
|
|
65
|
+
let cancelled = 0;
|
|
66
|
+
const call = acp.request("prompt", {}, { overdue: () => (cancelled += 1) });
|
|
67
|
+
await Bun.sleep(15);
|
|
68
|
+
expect(cancelled).toBe(1);
|
|
69
|
+
acp.receive('{"jsonrpc":"2.0","id":1,"result":{"stopReason":"cancelled"}}');
|
|
70
|
+
expect(await call).toMatchObject({ ok: false, timedOut: true });
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
test("a cancelled call waits its own grace for the agent's answer, and fails unconfirmed when none comes", async () => {
|
|
74
|
+
// The call has a long time of its own (a turn); the grace after the cancel is short.
|
|
75
|
+
const { acp } = client({ callTimeoutMs: 1_000 });
|
|
76
|
+
const started = Date.now();
|
|
77
|
+
const call = acp.request("prompt", {}, { timeoutMs: 10, graceMs: 20, overdue: () => {} });
|
|
78
|
+
const outcome = await call;
|
|
79
|
+
expect(outcome).toMatchObject({ ok: false, timedOut: true, unconfirmed: true });
|
|
80
|
+
expect(Date.now() - started).toBeLessThan(500);
|
|
81
|
+
expect(acp.waiting).toBe(0);
|
|
82
|
+
|
|
83
|
+
// An answer inside the grace is a cancelled call that was confirmed: it is not unconfirmed.
|
|
84
|
+
const answered = acp.request("prompt", {}, { timeoutMs: 10, graceMs: 200, overdue: () => {} });
|
|
85
|
+
await Bun.sleep(30);
|
|
86
|
+
acp.receive('{"jsonrpc":"2.0","id":2,"result":{"stopReason":"cancelled"}}');
|
|
87
|
+
const confirmed = await answered;
|
|
88
|
+
expect(confirmed).toMatchObject({ ok: false, timedOut: true });
|
|
89
|
+
expect(confirmed).not.toHaveProperty("unconfirmed");
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
test("a request of the agent, a notification, a line that is not JSON and one too long each go to their handler", () => {
|
|
93
|
+
const { acp, requests, notifications, unreadable, overflowed } = client({ maxLineBytes: 128 });
|
|
94
|
+
acp.feed('{"jsonrpc":"2.0","id":"r1","method":"session/request_permission","params":{}}\n');
|
|
95
|
+
acp.feed('{"jsonrpc":"2.0","method":"session/update","params":{}}\nnot json\n');
|
|
96
|
+
acp.feed('{"jsonrpc":"1.0","method":"other"}\n');
|
|
97
|
+
expect(requests.map((request) => request.id)).toEqual(["r1"]);
|
|
98
|
+
expect(notifications.map((notification) => notification.method)).toEqual(["session/update"]);
|
|
99
|
+
expect(unreadable).toEqual(["not json"]);
|
|
100
|
+
acp.feed("x".repeat(200));
|
|
101
|
+
expect(overflowed()).toBe(1);
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
test("a reply and a refusal answer the agent's request by its id", () => {
|
|
105
|
+
const { acp, written } = client();
|
|
106
|
+
acp.reply("r1", { outcome: "allowed" });
|
|
107
|
+
acp.refuse(7, -32601, "not served");
|
|
108
|
+
acp.notify("session/cancel", { sessionId: "s" });
|
|
109
|
+
expect(written).toEqual([
|
|
110
|
+
{ jsonrpc: "2.0", id: "r1", result: { outcome: "allowed" } },
|
|
111
|
+
{ jsonrpc: "2.0", id: 7, error: { code: -32601, message: "not served" } },
|
|
112
|
+
{ jsonrpc: "2.0", method: "session/cancel", params: { sessionId: "s" } },
|
|
113
|
+
]);
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
test("an answer settles the call of its own id only: a string that reads as the number is another id", async () => {
|
|
117
|
+
const { acp, unreadable } = client({ callTimeoutMs: 50 });
|
|
118
|
+
const call = acp.request("a", {});
|
|
119
|
+
acp.receive('{"jsonrpc":"2.0","id":"1","result":{"x":1}}');
|
|
120
|
+
expect(acp.waiting).toBe(1);
|
|
121
|
+
expect(unreadable).toEqual([]);
|
|
122
|
+
expect(await call).toMatchObject({ ok: false, timedOut: true });
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
test("a frame with a method and an id is a request even when the id is null, and without an id it is a notification", () => {
|
|
126
|
+
const { acp, requests, notifications, written } = client();
|
|
127
|
+
acp.receive('{"jsonrpc":"2.0","id":null,"method":"session/request_permission","params":{}}');
|
|
128
|
+
acp.receive('{"jsonrpc":"2.0","method":"session/update","params":{}}');
|
|
129
|
+
expect(requests.map((request) => request.id)).toEqual([null]);
|
|
130
|
+
expect(notifications.map((notification) => notification.method)).toEqual(["session/update"]);
|
|
131
|
+
acp.refuse(null, -32601, "not served");
|
|
132
|
+
acp.reply(null, {});
|
|
133
|
+
expect(written).toEqual([
|
|
134
|
+
{ jsonrpc: "2.0", id: null, error: { code: -32601, message: "not served" } },
|
|
135
|
+
{ jsonrpc: "2.0", id: null, result: {} },
|
|
136
|
+
]);
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
test("a request whose id is neither a string, a number nor null is unreadable", () => {
|
|
140
|
+
const { acp, requests, unreadable } = client();
|
|
141
|
+
acp.receive('{"jsonrpc":"2.0","id":{"a":1},"method":"m","params":{}}');
|
|
142
|
+
acp.receive('{"jsonrpc":"2.0","id":true,"method":"m","params":{}}');
|
|
143
|
+
expect(requests).toEqual([]);
|
|
144
|
+
expect(unreadable).toHaveLength(2);
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
test("a malformed answer is unreadable and leaves its call waiting for a valid one", async () => {
|
|
148
|
+
const { acp, unreadable } = client();
|
|
149
|
+
const call = acp.request("a", {});
|
|
150
|
+
for (const frame of [
|
|
151
|
+
'{"jsonrpc":"2.0","id":1,"error":null}',
|
|
152
|
+
'{"jsonrpc":"2.0","id":1}',
|
|
153
|
+
'{"jsonrpc":"2.0","id":1,"result":{},"error":{"code":-1,"message":"both"}}',
|
|
154
|
+
'{"jsonrpc":"2.0","id":1,"error":{"message":"no code"}}',
|
|
155
|
+
'{"jsonrpc":"2.0","id":1,"error":{"code":"-1","message":"string code"}}',
|
|
156
|
+
'{"jsonrpc":"2.0","id":1,"error":{"code":-1}}',
|
|
157
|
+
'{"jsonrpc":"2.0","id":1,"error":"busy"}',
|
|
158
|
+
]) {
|
|
159
|
+
acp.receive(frame);
|
|
160
|
+
}
|
|
161
|
+
expect(unreadable).toHaveLength(7);
|
|
162
|
+
expect(acp.waiting).toBe(1);
|
|
163
|
+
acp.receive('{"jsonrpc":"2.0","id":1,"result":null}');
|
|
164
|
+
expect(await call).toEqual({ ok: true, result: null });
|
|
165
|
+
expect(acp.waiting).toBe(0);
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
test("a malformed answer does not stop the close from settling the call", async () => {
|
|
169
|
+
const { acp } = client();
|
|
170
|
+
const call = acp.request("a", {});
|
|
171
|
+
acp.receive('{"jsonrpc":"2.0","id":1,"error":null}');
|
|
172
|
+
acp.close("the agent exited");
|
|
173
|
+
expect(await call).toEqual({ ok: false, error: "the agent exited", dispatch: "uncertain" });
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
/** A notification frame padded to exactly `bytes` bytes (without its newline). */
|
|
177
|
+
function frameOf(bytes: number): string {
|
|
178
|
+
const bare = JSON.stringify({ jsonrpc: "2.0", method: "m", params: { pad: "" } });
|
|
179
|
+
return JSON.stringify({ jsonrpc: "2.0", method: "m", params: { pad: "x".repeat(bytes - Buffer.byteLength(bare)) } });
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** Every way to cut `text` into two chunks, and the whole of it as one. */
|
|
183
|
+
function splits(text: string): string[][] {
|
|
184
|
+
return [[text], ...Array.from({ length: text.length - 1 }, (_, at) => [text.slice(0, at + 1), text.slice(at + 1)])];
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
test("a line over the limit overflows however its chunks are cut, and never reaches the handler", () => {
|
|
188
|
+
const line = frameOf(100);
|
|
189
|
+
expect(Buffer.byteLength(line)).toBe(100);
|
|
190
|
+
for (const chunks of splits(`${line}\n`)) {
|
|
191
|
+
const { acp, notifications, overflowed } = client({ maxLineBytes: 64 });
|
|
192
|
+
for (const chunk of chunks) acp.feed(chunk);
|
|
193
|
+
expect(notifications).toEqual([]);
|
|
194
|
+
expect(overflowed()).toBe(1);
|
|
195
|
+
}
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
test("a line of exactly the limit is read however its chunks are cut", () => {
|
|
199
|
+
const line = frameOf(64);
|
|
200
|
+
for (const chunks of splits(`${line}\n`)) {
|
|
201
|
+
const { acp, notifications, overflowed } = client({ maxLineBytes: 64 });
|
|
202
|
+
for (const chunk of chunks) acp.feed(chunk);
|
|
203
|
+
expect(notifications).toHaveLength(1);
|
|
204
|
+
expect(overflowed()).toBe(0);
|
|
205
|
+
}
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
test("the limit counts bytes, and the lines of a chunk after an overflowing one are not read", () => {
|
|
209
|
+
const { acp, notifications, overflowed } = client({ maxLineBytes: 100 });
|
|
210
|
+
const wide = JSON.stringify({ jsonrpc: "2.0", method: "m", params: { pad: "é".repeat(30) } });
|
|
211
|
+
expect(wide.length).toBeLessThan(100);
|
|
212
|
+
expect(Buffer.byteLength(wide)).toBeGreaterThan(100);
|
|
213
|
+
acp.feed(`${frameOf(100)}\n${wide}\n${frameOf(100)}\n`);
|
|
214
|
+
expect(notifications).toHaveLength(1);
|
|
215
|
+
expect(overflowed()).toBe(1);
|
|
216
|
+
acp.feed(`${frameOf(100)}\n`);
|
|
217
|
+
expect(notifications).toHaveLength(1);
|
|
218
|
+
expect(overflowed()).toBe(1);
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
test("a request the transport did not take fails as unsent at once, and leaves nothing waiting", async () => {
|
|
222
|
+
const { acp } = client({ write: () => "unsent" });
|
|
223
|
+
const calls: unknown[] = [];
|
|
224
|
+
acp.send("session/prompt", {}, (outcome) => calls.push(outcome), { timeoutMs: null });
|
|
225
|
+
expect(calls).toEqual([{ ok: false, error: "the request was not written", dispatch: "unsent" }]);
|
|
226
|
+
expect(acp.waiting).toBe(0);
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
test("a request the transport took, or may have taken, waits for its answer; the close fails it as uncertain", async () => {
|
|
230
|
+
for (const outcome of ["accepted", "unknown"] as const) {
|
|
231
|
+
const { acp } = client({ write: () => outcome });
|
|
232
|
+
const call = acp.request("a", {}, { timeoutMs: null });
|
|
233
|
+
expect(acp.waiting).toBe(1);
|
|
234
|
+
acp.close("the agent exited");
|
|
235
|
+
expect(await call).toEqual({ ok: false, error: "the agent exited", dispatch: "uncertain" });
|
|
236
|
+
}
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
test("a write that throws leaves it unknown whether the request left: the call fails as uncertain", async () => {
|
|
240
|
+
const { acp } = client({
|
|
241
|
+
write: () => {
|
|
242
|
+
throw new Error("closed pipe");
|
|
243
|
+
},
|
|
244
|
+
});
|
|
245
|
+
expect(await acp.request("a", {}, { timeoutMs: null })).toEqual({ ok: false, error: "closed pipe", dispatch: "uncertain" });
|
|
246
|
+
expect(acp.waiting).toBe(0);
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
test("a request that cannot be serialized never reaches the transport and fails as unsent", async () => {
|
|
250
|
+
const { acp, written } = client();
|
|
251
|
+
expect(await acp.request("a", { big: 1n }, { timeoutMs: null })).toMatchObject({ ok: false, dispatch: "unsent" });
|
|
252
|
+
expect(written).toEqual([]);
|
|
253
|
+
expect(acp.waiting).toBe(0);
|
|
254
|
+
});
|
|
255
|
+
|
|
256
|
+
test("a notification, a reply and a refusal say what became of the line", () => {
|
|
257
|
+
for (const outcome of ["accepted", "unsent", "unknown"] as const) {
|
|
258
|
+
const { acp } = client({ write: () => outcome });
|
|
259
|
+
expect(acp.notify("session/cancel", {})).toBe(outcome);
|
|
260
|
+
expect(acp.reply(1, {})).toBe(outcome);
|
|
261
|
+
expect(acp.refuse(1, -32601, "no")).toBe(outcome);
|
|
262
|
+
}
|
|
263
|
+
const throwing = client({
|
|
264
|
+
write: () => {
|
|
265
|
+
throw new Error("closed pipe");
|
|
266
|
+
},
|
|
267
|
+
}).acp;
|
|
268
|
+
expect(throwing.notify("session/cancel", {})).toBe("unknown");
|
|
269
|
+
});
|
|
270
|
+
|
|
271
|
+
test("a closed client reads nothing more: not a late line, not the rest of the chunk that closed it, not a half line", () => {
|
|
272
|
+
const closing: { acp?: AcpClient } = {};
|
|
273
|
+
const seen: string[] = [];
|
|
274
|
+
const first = client({
|
|
275
|
+
onNotification: (notification) => {
|
|
276
|
+
seen.push(notification.method);
|
|
277
|
+
closing.acp?.close("the agent exited");
|
|
278
|
+
},
|
|
279
|
+
onRequest: (request) => seen.push(`request ${String(request.id)}`),
|
|
280
|
+
});
|
|
281
|
+
closing.acp = first.acp;
|
|
282
|
+
first.acp.feed(`${frameOf(60)}\n{"jsonrpc":"2.0","id":9,"method":"session/request_permission","params":{}}\n`);
|
|
283
|
+
expect(seen).toEqual(["m"]);
|
|
284
|
+
first.acp.feed('{"jsonrpc":"2.0","id":9,"method":"session/request_permission","params":{}}\n');
|
|
285
|
+
first.acp.receive('{"jsonrpc":"2.0","id":9,"method":"session/request_permission","params":{}}');
|
|
286
|
+
expect(seen).toEqual(["m"]);
|
|
287
|
+
|
|
288
|
+
const half = client();
|
|
289
|
+
half.acp.feed('{"jsonrpc":"2.0","method":"m",');
|
|
290
|
+
half.acp.close("the agent exited");
|
|
291
|
+
half.acp.feed('"params":{}}\n');
|
|
292
|
+
expect(half.notifications).toEqual([]);
|
|
293
|
+
});
|
|
294
|
+
|
|
295
|
+
test("a closed client writes nothing more: not a notification, not a reply, not a refusal", () => {
|
|
296
|
+
const { acp, written } = client();
|
|
297
|
+
acp.close("the agent exited");
|
|
298
|
+
expect(acp.notify("session/cancel", {})).toBe("unsent");
|
|
299
|
+
expect(acp.reply(1, {})).toBe("unsent");
|
|
300
|
+
expect(acp.refuse(1, -32601, "no")).toBe("unsent");
|
|
301
|
+
expect(written).toEqual([]);
|
|
302
|
+
});
|
|
303
|
+
|
|
304
|
+
test("an error answer keeps its code, message and data, and is a refusal only where the code says nothing ran", async () => {
|
|
305
|
+
const { acp } = client();
|
|
306
|
+
const answered = async (code: number, data?: unknown) => {
|
|
307
|
+
const outcomes: RpcOutcome[] = [];
|
|
308
|
+
const id = acp.send("a", {}, (outcome) => outcomes.push(outcome));
|
|
309
|
+
const error = { code, message: "no", ...(data === undefined ? {} : { data }) };
|
|
310
|
+
acp.receive(JSON.stringify({ jsonrpc: "2.0", id, error }));
|
|
311
|
+
return outcomes[0];
|
|
312
|
+
};
|
|
313
|
+
// The codes JSON-RPC reserves for a request that was not understood: nothing was run.
|
|
314
|
+
for (const code of [-32700, -32600, -32601, -32602]) {
|
|
315
|
+
expect(await answered(code)).toEqual({ ok: false, error: "no", code, dispatch: "refused" });
|
|
316
|
+
}
|
|
317
|
+
// Any other error may come from work that was begun: internal, cancelled, authentication, the agent's own.
|
|
318
|
+
for (const code of [-32603, -32800, -32000, -32002, 1]) {
|
|
319
|
+
expect(await answered(code, { why: "late" })).toEqual({ ok: false, error: "no", code, data: { why: "late" }, dispatch: "uncertain" });
|
|
320
|
+
}
|
|
321
|
+
});
|
|
322
|
+
|
|
323
|
+
test("a call whose settle throws does not keep the others from being settled by the close", () => {
|
|
324
|
+
const { acp } = client();
|
|
325
|
+
const seen: RpcOutcome[] = [];
|
|
326
|
+
acp.send("a", {}, () => {
|
|
327
|
+
throw new Error("boom");
|
|
328
|
+
});
|
|
329
|
+
acp.send("b", {}, (outcome) => seen.push(outcome));
|
|
330
|
+
acp.send("c", {}, () => {
|
|
331
|
+
throw new Error("bang");
|
|
332
|
+
});
|
|
333
|
+
acp.send("d", {}, (outcome) => seen.push(outcome));
|
|
334
|
+
// The handlers' errors are reported once every call has its outcome.
|
|
335
|
+
expect(() => acp.close("the agent exited")).toThrow(AggregateError);
|
|
336
|
+
expect(seen).toEqual([
|
|
337
|
+
{ ok: false, error: "the agent exited", dispatch: "uncertain" },
|
|
338
|
+
{ ok: false, error: "the agent exited", dispatch: "uncertain" },
|
|
339
|
+
]);
|
|
340
|
+
expect(acp.waiting).toBe(0);
|
|
341
|
+
|
|
342
|
+
const single = client().acp;
|
|
343
|
+
single.send("a", {}, () => {
|
|
344
|
+
throw new Error("boom");
|
|
345
|
+
});
|
|
346
|
+
expect(() => single.close("the agent exited")).toThrow("boom");
|
|
347
|
+
});
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { expect, test } from "bun:test";
|
|
2
|
+
|
|
3
|
+
import { Acp014, Acp13 } from "../src/index.ts";
|
|
4
|
+
|
|
5
|
+
const snapshots = [
|
|
6
|
+
["0.14", Acp014],
|
|
7
|
+
["1.3", Acp13],
|
|
8
|
+
] as const;
|
|
9
|
+
|
|
10
|
+
test("a response keeps its result whatever method it answers", () => {
|
|
11
|
+
for (const [, acp] of snapshots) {
|
|
12
|
+
const prompted = { id: 1, result: { stopReason: "end_turn" } };
|
|
13
|
+
expect(acp.AgentResponse.parse(prompted)).toEqual(prompted);
|
|
14
|
+
const asked = { id: 2, result: { outcome: { outcome: "selected", optionId: "allow" } } };
|
|
15
|
+
expect(acp.ClientResponse.parse(asked)).toEqual(asked);
|
|
16
|
+
const failed = { id: 3, error: { code: -32602, message: "no" } };
|
|
17
|
+
expect(acp.AgentResponse.parse(failed)).toEqual(failed);
|
|
18
|
+
expect(acp.ClientResponse.parse(failed)).toEqual(failed);
|
|
19
|
+
}
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
test("the result of a request is read by the schema of its method", () => {
|
|
23
|
+
for (const [, acp] of snapshots) {
|
|
24
|
+
expect(acp.ClientToAgentResults["session/prompt"].parse({ stopReason: "end_turn" })).toEqual({ stopReason: "end_turn" });
|
|
25
|
+
expect(acp.ClientToAgentResults["session/prompt"].safeParse({}).success).toBe(false);
|
|
26
|
+
const selected = { outcome: { outcome: "selected", optionId: "allow" } };
|
|
27
|
+
expect(acp.AgentToClientResults["session/request_permission"].parse(selected)).toEqual(selected);
|
|
28
|
+
expect(Object.keys(acp.ClientToAgentResults)).toContain("initialize");
|
|
29
|
+
expect(Object.keys(acp.AgentToClientResults)).toContain("session/request_permission");
|
|
30
|
+
}
|
|
31
|
+
});
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { expect, test } from "bun:test";
|
|
2
|
+
|
|
3
|
+
import { ProtocolNameSchema } from "@niwa-labs/harness";
|
|
4
|
+
|
|
5
|
+
import { Acp014, acpVariant, readVariant } from "../src/index.ts";
|
|
6
|
+
|
|
7
|
+
const protocol = ProtocolNameSchema.parse("acp-0.14.1/claude-code");
|
|
8
|
+
|
|
9
|
+
test("a message that fits its variant reads as the typed value", () => {
|
|
10
|
+
const frame = { id: 1, method: "session/request_permission", params: { sessionId: "s", toolCall: { toolCallId: "c" }, options: [] } };
|
|
11
|
+
expect(readVariant(Acp014.AgentToClientRequest, frame, protocol, acpVariant)).toMatchObject({ ok: true });
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
test("a method the snapshot does not know is an unknown variant, and so is an update it does not know", () => {
|
|
15
|
+
const request = { id: 1, method: "_zed/unknown", params: {} };
|
|
16
|
+
const read = readVariant(Acp014.AgentToClientRequest, request, protocol, acpVariant);
|
|
17
|
+
expect(read).toEqual({ ok: false, unknown: { protocol, variant: "_zed/unknown", raw: request } });
|
|
18
|
+
|
|
19
|
+
const update = { method: "session/update", params: { sessionId: "s", update: { sessionUpdate: "compaction_update" } } };
|
|
20
|
+
expect(readVariant(Acp014.AgentToClientNotification, update, protocol, acpVariant)).toEqual({
|
|
21
|
+
ok: false,
|
|
22
|
+
unknown: { protocol, variant: "session/update compaction_update", raw: update },
|
|
23
|
+
});
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
test("a known method whose params do not fit is invalid, with the field it is wrong in, and keeps the raw frame", () => {
|
|
27
|
+
const request = { id: 1, method: "session/request_permission", params: { sessionId: "s", options: "none" } };
|
|
28
|
+
const read = readVariant(Acp014.AgentToClientRequest, request, protocol, acpVariant);
|
|
29
|
+
expect(read.ok).toBe(false);
|
|
30
|
+
if (read.ok) return;
|
|
31
|
+
expect(read.unknown).toEqual({ protocol, variant: "session/request_permission", raw: request });
|
|
32
|
+
expect(read.invalid).toContain("params.options");
|
|
33
|
+
expect(read.invalid).toContain("params.toolCall");
|
|
34
|
+
|
|
35
|
+
const update = { method: "session/update", params: { sessionId: "s", update: { sessionUpdate: "tool_call" } } };
|
|
36
|
+
const badUpdate = readVariant(Acp014.AgentToClientNotification, update, protocol, acpVariant);
|
|
37
|
+
expect(badUpdate).toMatchObject({ ok: false, unknown: { variant: "session/update tool_call" } });
|
|
38
|
+
expect(badUpdate.ok ? "" : badUpdate.invalid).toContain("params.update.toolCallId");
|
|
39
|
+
});
|