@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/client.ts
ADDED
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The client side of an ACP connection: JSON-RPC 2.0 over the lines of a child's stdio.
|
|
3
|
+
*
|
|
4
|
+
* One demux over the lines the agent writes, a monotonic request id, the calls in flight by that
|
|
5
|
+
* id with a timeout each, and every call settled when the connection closes. A request the agent
|
|
6
|
+
* makes of the client and a notification are handed to the dialect that owns the connection; the
|
|
7
|
+
* client only frames, matches and settles.
|
|
8
|
+
*
|
|
9
|
+
* A call that fails says how far it got (`Dispatch`): never written, refused by the agent, or
|
|
10
|
+
* written and not known to have been done. Only the last may have done what it asked; an error
|
|
11
|
+
* answer is a refusal only when its code says the request was not taken in. The transport says what
|
|
12
|
+
* became of each line it was given (`Written`), and the client believes it.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import type { Dispatch } from "@niwa-labs/harness";
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* The id of a request: a number or a string, and `null` where a snapshot of the protocol allows
|
|
19
|
+
* it. A request has an id when the member is present, whatever its value.
|
|
20
|
+
*/
|
|
21
|
+
export type RequestId = number | string | null;
|
|
22
|
+
|
|
23
|
+
/** One JSON-RPC message, either way: what is present says which it is. */
|
|
24
|
+
export interface RpcFrame {
|
|
25
|
+
readonly jsonrpc?: string;
|
|
26
|
+
readonly id?: RequestId;
|
|
27
|
+
readonly method?: string;
|
|
28
|
+
readonly params?: unknown;
|
|
29
|
+
readonly result?: unknown;
|
|
30
|
+
readonly error?: { readonly code?: number; readonly message?: string; readonly data?: unknown };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** A request the agent makes of the client: it must be answered, or the agent waits forever. */
|
|
34
|
+
export type AgentRequest = RpcFrame & { readonly id: RequestId; readonly method: string };
|
|
35
|
+
|
|
36
|
+
/** A notification of the agent. */
|
|
37
|
+
export type AgentNotification = RpcFrame & { readonly method: string };
|
|
38
|
+
|
|
39
|
+
/** What became of a call. */
|
|
40
|
+
export type RpcOutcome =
|
|
41
|
+
| { readonly ok: true; readonly result: unknown }
|
|
42
|
+
| {
|
|
43
|
+
readonly ok: false;
|
|
44
|
+
readonly error: string;
|
|
45
|
+
/** The code of the agent's error answer, when it answered with one. */
|
|
46
|
+
readonly code?: number;
|
|
47
|
+
/** The `data` of the agent's error answer, when it came with any. */
|
|
48
|
+
readonly data?: unknown;
|
|
49
|
+
readonly dispatch: Dispatch;
|
|
50
|
+
/** The answer did not come in time. */
|
|
51
|
+
readonly timedOut?: true;
|
|
52
|
+
/** The call was over its time, the work was cancelled (`overdue`), and the agent did not answer even that in the grace: nobody knows what became of the work. */
|
|
53
|
+
readonly unconfirmed?: true;
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
/** How a call waits for its answer. */
|
|
57
|
+
export interface CallOptions {
|
|
58
|
+
/** How long the answer may take; `null` waits until the connection closes. The client's own when absent. */
|
|
59
|
+
readonly timeoutMs?: number | null;
|
|
60
|
+
/**
|
|
61
|
+
* Run when the call is over its time, instead of giving it up at once (a cancel of the work):
|
|
62
|
+
* the call then waits one more timeout (`graceMs`) for the agent to answer, and fails with the
|
|
63
|
+
* timeout either way, so a cancelled answer is never taken for a success. A call whose grace ran
|
|
64
|
+
* out without an answer fails `unconfirmed`.
|
|
65
|
+
*/
|
|
66
|
+
readonly overdue?: () => void;
|
|
67
|
+
/** How long a call that was cancelled waits for the agent to answer the cancel. The call's own timeout when absent. */
|
|
68
|
+
readonly graceMs?: number;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* What became of a line given to the transport: taken (`accepted`), certainly not written
|
|
73
|
+
* (`unsent`: the process is gone, its stdin closed), or not known (`unknown`: the write may have
|
|
74
|
+
* partly happened). A write that throws is `unknown`.
|
|
75
|
+
*/
|
|
76
|
+
export type Written = "accepted" | "unsent" | "unknown";
|
|
77
|
+
|
|
78
|
+
export interface AcpClientOptions {
|
|
79
|
+
/** Write one line to the agent, and say what became of it. */
|
|
80
|
+
readonly write: (line: string) => Written;
|
|
81
|
+
readonly onRequest: (request: AgentRequest) => void;
|
|
82
|
+
readonly onNotification: (notification: AgentNotification) => void;
|
|
83
|
+
/** A line that is not JSON: never a crash. */
|
|
84
|
+
readonly onUnreadable: (line: string, error: unknown) => void;
|
|
85
|
+
/** A line longer than the frame budget: the transport has failed. */
|
|
86
|
+
readonly onOverflow: () => void;
|
|
87
|
+
/** How long a call waits for its answer by default. */
|
|
88
|
+
readonly callTimeoutMs: number;
|
|
89
|
+
/** The most bytes one line may hold. */
|
|
90
|
+
readonly maxLineBytes?: number;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const DEFAULT_MAX_LINE_BYTES = 16 * 1024 * 1024;
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* The error codes JSON-RPC reserves for a request the agent did not take in: it could not be
|
|
97
|
+
* parsed, is not a request, names no method, or has parameters the method does not accept. Nothing
|
|
98
|
+
* ran, so a call that fails with one is a refusal. Any other error (an internal one, a cancelled
|
|
99
|
+
* request, the agent's own) can come from work that was begun, and the call is then uncertain.
|
|
100
|
+
*/
|
|
101
|
+
const NOT_RUN_CODES = new Set([-32700, -32600, -32601, -32602]);
|
|
102
|
+
|
|
103
|
+
/** What an answer says: its result, or the error it carries; why it is neither, when it is not well formed. */
|
|
104
|
+
function answerOf(frame: RpcFrame): RpcOutcome | string {
|
|
105
|
+
const hasResult = Object.hasOwn(frame, "result");
|
|
106
|
+
const hasError = Object.hasOwn(frame, "error");
|
|
107
|
+
if (hasResult === hasError) return "an answer holds exactly one of a result and an error";
|
|
108
|
+
if (hasResult) return { ok: true, result: frame.result };
|
|
109
|
+
const error: unknown = frame.error;
|
|
110
|
+
if (typeof error !== "object" || error === null) return "the error of an answer is not an object";
|
|
111
|
+
const { code, message } = error as { readonly code?: unknown; readonly message?: unknown };
|
|
112
|
+
if (typeof code !== "number" || typeof message !== "string") {
|
|
113
|
+
return "the error of an answer has no numeric code and string message";
|
|
114
|
+
}
|
|
115
|
+
const data: unknown = (error as { readonly data?: unknown }).data;
|
|
116
|
+
return {
|
|
117
|
+
ok: false,
|
|
118
|
+
error: message,
|
|
119
|
+
code,
|
|
120
|
+
...(data === undefined ? {} : { data }),
|
|
121
|
+
dispatch: NOT_RUN_CODES.has(code) ? "refused" : "uncertain",
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function isRequestId(id: unknown): id is RequestId {
|
|
126
|
+
return id === null || typeof id === "number" || typeof id === "string";
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** A failure to write, as its reason. */
|
|
130
|
+
function reasonOf(error: unknown): string {
|
|
131
|
+
return error instanceof Error ? error.message : String(error);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export class AcpClient {
|
|
135
|
+
readonly #options: AcpClientOptions;
|
|
136
|
+
readonly #pending = new Map<number, (outcome: RpcOutcome) => void>();
|
|
137
|
+
#nextId = 1;
|
|
138
|
+
/** The start of a line whose end has not come yet, and its length in bytes. */
|
|
139
|
+
#fragment = "";
|
|
140
|
+
#fragmentBytes = 0;
|
|
141
|
+
#overflowed = false;
|
|
142
|
+
#closed: string | undefined;
|
|
143
|
+
|
|
144
|
+
constructor(options: AcpClientOptions) {
|
|
145
|
+
this.#options = options;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** How many calls wait for their answer. */
|
|
149
|
+
get waiting(): number {
|
|
150
|
+
return this.#pending.size;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* A chunk of the agent's stdout: each whole line is read as it completes.
|
|
155
|
+
*
|
|
156
|
+
* A line longer than the budget is the transport failing, and it is so however its chunks were
|
|
157
|
+
* cut: the length of a line is measured in bytes before the line is read, whether it ends in this
|
|
158
|
+
* chunk or is still growing. After an overflow nothing more is read.
|
|
159
|
+
*/
|
|
160
|
+
feed(chunk: string): void {
|
|
161
|
+
const limit = this.#options.maxLineBytes ?? DEFAULT_MAX_LINE_BYTES;
|
|
162
|
+
let start = 0;
|
|
163
|
+
while (!this.#overflowed && this.#closed === undefined) {
|
|
164
|
+
const newline = chunk.indexOf("\n", start);
|
|
165
|
+
const piece = newline === -1 ? chunk.slice(start) : chunk.slice(start, newline);
|
|
166
|
+
const bytes = this.#fragmentBytes + Buffer.byteLength(piece, "utf8");
|
|
167
|
+
if (bytes > limit) {
|
|
168
|
+
this.#overflowed = true;
|
|
169
|
+
this.#fragment = "";
|
|
170
|
+
this.#fragmentBytes = 0;
|
|
171
|
+
this.#options.onOverflow();
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
if (newline === -1) {
|
|
175
|
+
this.#fragment += piece;
|
|
176
|
+
this.#fragmentBytes = bytes;
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
const line = this.#fragment + piece;
|
|
180
|
+
this.#fragment = "";
|
|
181
|
+
this.#fragmentBytes = 0;
|
|
182
|
+
this.receive(line.trim());
|
|
183
|
+
start = newline + 1;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* One line of the agent: a response settles exactly one call, a request and a notification go to
|
|
189
|
+
* the dialect. A frame that is not JSON-RPC 2.0 is not one of ours.
|
|
190
|
+
*/
|
|
191
|
+
receive(line: string): void {
|
|
192
|
+
if (line.length === 0 || this.#closed !== undefined) return;
|
|
193
|
+
let frame: RpcFrame;
|
|
194
|
+
try {
|
|
195
|
+
frame = JSON.parse(line) as RpcFrame;
|
|
196
|
+
} catch (error) {
|
|
197
|
+
this.#options.onUnreadable(line, error);
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
if (typeof frame !== "object" || frame === null) {
|
|
201
|
+
this.#options.onUnreadable(line, new Error("the line is not a JSON-RPC frame"));
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
if (frame.jsonrpc !== undefined && frame.jsonrpc !== "2.0") return;
|
|
205
|
+
if (frame.method !== undefined && typeof frame.method !== "string") {
|
|
206
|
+
this.#options.onUnreadable(line, new Error("the method of the frame is not a string"));
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
// What is present says what a frame is, not what its values are: an id of `null` is still an id.
|
|
210
|
+
const hasId = Object.hasOwn(frame, "id");
|
|
211
|
+
if (frame.method !== undefined && hasId) {
|
|
212
|
+
if (!isRequestId(frame.id)) {
|
|
213
|
+
this.#options.onUnreadable(line, new Error("the id of the request is neither a number, a string nor null"));
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
this.#options.onRequest(frame as AgentRequest);
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
if (frame.method === undefined && hasId) {
|
|
220
|
+
// Our ids are numbers: an answer is of the call whose id it repeats, and no other.
|
|
221
|
+
if (typeof frame.id !== "number") return;
|
|
222
|
+
const settle = this.#pending.get(frame.id);
|
|
223
|
+
if (settle === undefined) return;
|
|
224
|
+
// The answer is checked before the call is given up: a malformed one settles nothing.
|
|
225
|
+
const answer = answerOf(frame);
|
|
226
|
+
if (typeof answer === "string") {
|
|
227
|
+
this.#options.onUnreadable(line, new Error(answer));
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
this.#pending.delete(frame.id);
|
|
231
|
+
settle(answer);
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
if (frame.method !== undefined) this.#options.onNotification(frame as AgentNotification);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* Send a request; `settle` is told what became of it, in the same turn of the event loop as the
|
|
239
|
+
* line that answered it. The wait is registered before the request is written, so an answer read
|
|
240
|
+
* in the same chunk as the write is never missed.
|
|
241
|
+
*/
|
|
242
|
+
send(method: string, params: unknown, settle: (outcome: RpcOutcome) => void, options: CallOptions = {}): number {
|
|
243
|
+
const id = this.#nextId;
|
|
244
|
+
this.#nextId += 1;
|
|
245
|
+
if (this.#closed !== undefined) {
|
|
246
|
+
settle({ ok: false, error: this.#closed, dispatch: "unsent" });
|
|
247
|
+
return id;
|
|
248
|
+
}
|
|
249
|
+
// The line is made before the call is registered: a request that cannot be serialized never
|
|
250
|
+
// reached the transport.
|
|
251
|
+
let line: string;
|
|
252
|
+
try {
|
|
253
|
+
line = JSON.stringify({ jsonrpc: "2.0", id, method, params });
|
|
254
|
+
} catch (error) {
|
|
255
|
+
settle({ ok: false, error: reasonOf(error), dispatch: "unsent" });
|
|
256
|
+
return id;
|
|
257
|
+
}
|
|
258
|
+
const timeoutMs = options.timeoutMs === undefined ? this.#options.callTimeoutMs : options.timeoutMs;
|
|
259
|
+
const timedOut: RpcOutcome = { ok: false, error: `the call ${method} timed out`, dispatch: "uncertain", timedOut: true };
|
|
260
|
+
let late = false;
|
|
261
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
262
|
+
let grace: ReturnType<typeof setTimeout> | undefined;
|
|
263
|
+
if (timeoutMs !== null) {
|
|
264
|
+
timer = setTimeout(() => {
|
|
265
|
+
if (!this.#pending.has(id)) return;
|
|
266
|
+
if (options.overdue === undefined) {
|
|
267
|
+
this.#pending.delete(id);
|
|
268
|
+
settle(timedOut);
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
late = true;
|
|
272
|
+
try {
|
|
273
|
+
options.overdue();
|
|
274
|
+
} catch {
|
|
275
|
+
// The agent is gone: there is nothing to cancel.
|
|
276
|
+
}
|
|
277
|
+
grace = setTimeout(() => {
|
|
278
|
+
if (this.#pending.delete(id)) settle({ ...timedOut, unconfirmed: true });
|
|
279
|
+
}, options.graceMs ?? timeoutMs);
|
|
280
|
+
grace.unref?.();
|
|
281
|
+
}, timeoutMs);
|
|
282
|
+
timer.unref?.();
|
|
283
|
+
}
|
|
284
|
+
const finish = (outcome: RpcOutcome): void => {
|
|
285
|
+
clearTimeout(timer);
|
|
286
|
+
clearTimeout(grace);
|
|
287
|
+
settle(late ? timedOut : outcome);
|
|
288
|
+
};
|
|
289
|
+
this.#pending.set(id, finish);
|
|
290
|
+
let written: Written | Error;
|
|
291
|
+
try {
|
|
292
|
+
written = this.#options.write(line);
|
|
293
|
+
} catch (error) {
|
|
294
|
+
written = error instanceof Error ? error : new Error(String(error));
|
|
295
|
+
}
|
|
296
|
+
if (written === "unsent") {
|
|
297
|
+
this.#pending.delete(id);
|
|
298
|
+
finish({ ok: false, error: "the request was not written", dispatch: "unsent" });
|
|
299
|
+
} else if (written instanceof Error) {
|
|
300
|
+
// It is not known whether the request left, and nothing says an answer will come.
|
|
301
|
+
this.#pending.delete(id);
|
|
302
|
+
finish({ ok: false, error: written.message, dispatch: "uncertain" });
|
|
303
|
+
}
|
|
304
|
+
return id;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/** `send`, as a promise of the outcome. */
|
|
308
|
+
request(method: string, params: unknown, options: CallOptions = {}): Promise<RpcOutcome> {
|
|
309
|
+
return new Promise<RpcOutcome>((resolve) => {
|
|
310
|
+
this.send(method, params, resolve, options);
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** A notification: no id, no answer. It says what became of the line. */
|
|
315
|
+
notify(method: string, params: unknown = {}): Written {
|
|
316
|
+
return this.#write(JSON.stringify({ jsonrpc: "2.0", method, params }));
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/** The answer to a request of the agent. */
|
|
320
|
+
reply(id: RequestId, result: unknown): Written {
|
|
321
|
+
return this.#write(JSON.stringify({ jsonrpc: "2.0", id, result }));
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/** The refusal of a request of the agent, so it never waits on the client. */
|
|
325
|
+
refuse(id: RequestId, code: number, message: string): Written {
|
|
326
|
+
return this.#write(JSON.stringify({ jsonrpc: "2.0", id, error: { code, message } }));
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/** A line to the transport: one that throws left it unknown what became of the line. */
|
|
330
|
+
#write(line: string): Written {
|
|
331
|
+
if (this.#closed !== undefined) return "unsent";
|
|
332
|
+
try {
|
|
333
|
+
return this.#options.write(line);
|
|
334
|
+
} catch {
|
|
335
|
+
return "unknown";
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/**
|
|
340
|
+
* The connection is gone, in both directions: every call in flight fails with `reason`, and
|
|
341
|
+
* nothing is written or read any more, the half line and the rest of the current chunk included.
|
|
342
|
+
*/
|
|
343
|
+
close(reason: string): void {
|
|
344
|
+
if (this.#closed === undefined) this.#closed = reason;
|
|
345
|
+
this.#fragment = "";
|
|
346
|
+
this.#fragmentBytes = 0;
|
|
347
|
+
const pending = [...this.#pending.values()];
|
|
348
|
+
this.#pending.clear();
|
|
349
|
+
// Every call gets its outcome before a handler's failure is reported: one that throws must not
|
|
350
|
+
// leave the calls after it unsettled, for nothing would settle them any more.
|
|
351
|
+
const failures: unknown[] = [];
|
|
352
|
+
for (const settle of pending) {
|
|
353
|
+
try {
|
|
354
|
+
settle({ ok: false, error: reason, dispatch: "uncertain" });
|
|
355
|
+
} catch (error) {
|
|
356
|
+
failures.push(error);
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
if (failures.length === 1) throw failures[0];
|
|
360
|
+
if (failures.length > 1) throw new AggregateError(failures, "calls that were settled by the close failed");
|
|
361
|
+
}
|
|
362
|
+
}
|
package/src/content.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/** The content blocks of an ACP message, as every snapshot niwa has (0.14.1, 1.3.0) names them. */
|
|
2
|
+
|
|
3
|
+
import { assertNever } from "@niwa-labs/core";
|
|
4
|
+
|
|
5
|
+
/** A content block, by the fields the answer needs. */
|
|
6
|
+
export type AcpContent =
|
|
7
|
+
| { readonly type: "text"; readonly text: string }
|
|
8
|
+
| { readonly type: "image" | "audio" | "resource_link" | "resource" };
|
|
9
|
+
|
|
10
|
+
/** The text a content block adds to the answer: only a text block adds any. */
|
|
11
|
+
export function answerText(content: AcpContent): string {
|
|
12
|
+
switch (content.type) {
|
|
13
|
+
case "text":
|
|
14
|
+
return content.text;
|
|
15
|
+
// An image, a sound or a resource is not text of the answer.
|
|
16
|
+
case "image":
|
|
17
|
+
case "audio":
|
|
18
|
+
case "resource_link":
|
|
19
|
+
case "resource":
|
|
20
|
+
return "";
|
|
21
|
+
default:
|
|
22
|
+
return assertNever(content, "ACP content block");
|
|
23
|
+
}
|
|
24
|
+
}
|