megacode-agent-sdk 0.0.0-stage → 0.32.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-APACHE +176 -0
- package/LICENSE-MIT +23 -0
- package/README.md +38 -2
- package/dist/binary/archive.d.ts +7 -0
- package/dist/binary/archive.js +215 -0
- package/dist/binary/cache.d.ts +21 -0
- package/dist/binary/cache.js +256 -0
- package/dist/binary/download.d.ts +16 -0
- package/dist/binary/download.js +174 -0
- package/dist/binary/index.d.ts +49 -0
- package/dist/binary/index.js +160 -0
- package/dist/client.d.ts +94 -0
- package/dist/client.js +868 -0
- package/dist/errors.d.ts +58 -0
- package/dist/errors.js +97 -0
- package/dist/index.d.ts +52 -0
- package/dist/index.js +42 -0
- package/dist/options.d.ts +48 -0
- package/dist/options.js +49 -0
- package/dist/pins.d.ts +5 -0
- package/dist/pins.js +22 -0
- package/dist/process.d.ts +72 -0
- package/dist/process.js +255 -0
- package/dist/tools.d.ts +74 -0
- package/dist/tools.js +256 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +3 -0
- package/dist/wire.d.ts +241 -0
- package/dist/wire.js +620 -0
- package/package.json +33 -4
package/dist/process.js
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
// The session's process (spec slice-ar R1, R2.1, R8.6): the options file,
|
|
2
|
+
// the start, the stdout line splitter, the stderr tail, and the stop.
|
|
3
|
+
import { spawn as spawnChild } from "node:child_process";
|
|
4
|
+
import * as fs from "node:fs";
|
|
5
|
+
import * as os from "node:os";
|
|
6
|
+
import * as path from "node:path";
|
|
7
|
+
import { BinaryUnavailable } from "./errors.js";
|
|
8
|
+
/** The lines of stderr kept for diagnostics (R1.4). */
|
|
9
|
+
export const STDERR_TAIL = 200;
|
|
10
|
+
/** How long the stop waits after SIGTERM before SIGKILL (R8.6.2). */
|
|
11
|
+
const TERM_WAIT_MS = 5000;
|
|
12
|
+
/** How long the stop waits for the reaping after SIGKILL. */
|
|
13
|
+
const KILL_WAIT_MS = 4000;
|
|
14
|
+
/** The options file in its own private folder (R2.1): removed, file then
|
|
15
|
+
* folder, at `init` or at the process's exit, whichever is first. */
|
|
16
|
+
export class OptionsFile {
|
|
17
|
+
dir;
|
|
18
|
+
file;
|
|
19
|
+
removed = false;
|
|
20
|
+
constructor(dir, file) {
|
|
21
|
+
this.dir = dir;
|
|
22
|
+
this.file = file;
|
|
23
|
+
}
|
|
24
|
+
/** Writes `body` to `options.json` in a new folder (mode 0700, from
|
|
25
|
+
* `mkdtemp`) under the temporary folder; the file is created exclusively,
|
|
26
|
+
* mode 0600. */
|
|
27
|
+
static write(body) {
|
|
28
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), `megacode-agent-sdk-${process.pid}-`));
|
|
29
|
+
const made = new OptionsFile(dir, path.join(dir, "options.json"));
|
|
30
|
+
try {
|
|
31
|
+
fs.writeFileSync(made.file, body, { mode: 0o600, flag: "wx" });
|
|
32
|
+
}
|
|
33
|
+
catch (e) {
|
|
34
|
+
made.remove();
|
|
35
|
+
throw e;
|
|
36
|
+
}
|
|
37
|
+
return made;
|
|
38
|
+
}
|
|
39
|
+
/** Removes the file and its folder; later calls do nothing. */
|
|
40
|
+
remove() {
|
|
41
|
+
if (this.removed)
|
|
42
|
+
return;
|
|
43
|
+
this.removed = true;
|
|
44
|
+
try {
|
|
45
|
+
fs.unlinkSync(this.file);
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
// Already gone, or never written.
|
|
49
|
+
}
|
|
50
|
+
try {
|
|
51
|
+
fs.rmdirSync(this.dir);
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
// Already gone.
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
/** Children not yet reaped, SIGKILLed at this process's exit (R8.6.3): a
|
|
59
|
+
* program that never awaited `close()` leaves no session behind. */
|
|
60
|
+
const live = new Set();
|
|
61
|
+
let hooked = false;
|
|
62
|
+
function killLive() {
|
|
63
|
+
for (const child of live) {
|
|
64
|
+
try {
|
|
65
|
+
child.kill("SIGKILL");
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
// Gone meanwhile.
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/** Splits a byte stream at `\n` only (never U+2028, U+2029 or a lone `\r`),
|
|
73
|
+
* handing each whole line on as bytes, so a character split across chunks is
|
|
74
|
+
* decoded whole (Review Focus 1). A `\r` before the `\n` is dropped. */
|
|
75
|
+
export class LineSplitter {
|
|
76
|
+
parts = [];
|
|
77
|
+
push(chunk, onLine) {
|
|
78
|
+
let start = 0;
|
|
79
|
+
for (;;) {
|
|
80
|
+
const at = chunk.indexOf(0x0a, start);
|
|
81
|
+
if (at < 0)
|
|
82
|
+
break;
|
|
83
|
+
const piece = chunk.subarray(start, at);
|
|
84
|
+
let whole = this.parts.length === 0 ? piece : Buffer.concat([...this.parts, piece]);
|
|
85
|
+
this.parts = [];
|
|
86
|
+
if (whole.length > 0 && whole[whole.length - 1] === 0x0d)
|
|
87
|
+
whole = whole.subarray(0, whole.length - 1);
|
|
88
|
+
start = at + 1;
|
|
89
|
+
onLine(whole);
|
|
90
|
+
}
|
|
91
|
+
if (start < chunk.length)
|
|
92
|
+
this.parts.push(chunk.subarray(start));
|
|
93
|
+
}
|
|
94
|
+
/** At the stream's end: an unterminated last line is a line too. */
|
|
95
|
+
end(onLine) {
|
|
96
|
+
if (this.parts.length === 0)
|
|
97
|
+
return;
|
|
98
|
+
const whole = Buffer.concat(this.parts);
|
|
99
|
+
this.parts = [];
|
|
100
|
+
onLine(whole);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
/** A started process: its pipes, its exit, its stderr tail. */
|
|
104
|
+
export class Proc {
|
|
105
|
+
child;
|
|
106
|
+
exit = null;
|
|
107
|
+
stderrTail = [];
|
|
108
|
+
stderrDone = false;
|
|
109
|
+
exitWaiters = [];
|
|
110
|
+
stderrWaiters = [];
|
|
111
|
+
constructor(child) {
|
|
112
|
+
this.child = child;
|
|
113
|
+
live.add(child);
|
|
114
|
+
// A pipe's error (EPIPE on stdin, a reset) is the session's to handle
|
|
115
|
+
// through its writer and reader; an unheard `error` event would throw.
|
|
116
|
+
child.on("error", () => { });
|
|
117
|
+
child.stdin.on("error", () => { });
|
|
118
|
+
child.stdout.on("error", () => { });
|
|
119
|
+
child.stderr.on("error", () => { });
|
|
120
|
+
child.on("exit", (code, signal) => {
|
|
121
|
+
live.delete(child);
|
|
122
|
+
this.exit = { code, signal };
|
|
123
|
+
for (const wake of this.exitWaiters.splice(0))
|
|
124
|
+
wake();
|
|
125
|
+
});
|
|
126
|
+
const tail = new LineSplitter();
|
|
127
|
+
const keep = (line) => {
|
|
128
|
+
if (this.stderrTail.length === STDERR_TAIL)
|
|
129
|
+
this.stderrTail.shift();
|
|
130
|
+
this.stderrTail.push(line.toString("utf8").trimEnd());
|
|
131
|
+
};
|
|
132
|
+
child.stderr.on("data", (chunk) => tail.push(chunk, keep));
|
|
133
|
+
const done = () => {
|
|
134
|
+
if (this.stderrDone)
|
|
135
|
+
return;
|
|
136
|
+
tail.end(keep);
|
|
137
|
+
this.stderrDone = true;
|
|
138
|
+
for (const wake of this.stderrWaiters.splice(0))
|
|
139
|
+
wake();
|
|
140
|
+
};
|
|
141
|
+
child.stderr.on("end", done);
|
|
142
|
+
child.stderr.on("close", done);
|
|
143
|
+
}
|
|
144
|
+
get pid() {
|
|
145
|
+
return this.child.pid;
|
|
146
|
+
}
|
|
147
|
+
/** Calls `wake` once the process was reaped (at once if it was). */
|
|
148
|
+
onExit(wake) {
|
|
149
|
+
if (this.exit !== null)
|
|
150
|
+
wake();
|
|
151
|
+
else
|
|
152
|
+
this.exitWaiters.push(wake);
|
|
153
|
+
}
|
|
154
|
+
/** Waits until the process was reaped, at most `ms`; `true` if it was. */
|
|
155
|
+
waitExit(ms) {
|
|
156
|
+
return waitFor(() => this.exit !== null, (w) => this.exitWaiters.push(w), ms);
|
|
157
|
+
}
|
|
158
|
+
waitStderr(ms) {
|
|
159
|
+
return waitFor(() => this.stderrDone, (w) => this.stderrWaiters.push(w), ms);
|
|
160
|
+
}
|
|
161
|
+
/** Signals a child not yet reaped. */
|
|
162
|
+
signal(sig) {
|
|
163
|
+
if (this.exit !== null)
|
|
164
|
+
return;
|
|
165
|
+
try {
|
|
166
|
+
this.child.kill(sig);
|
|
167
|
+
}
|
|
168
|
+
catch {
|
|
169
|
+
// Gone meanwhile.
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
/** The stop (R8.6.2), after the caller sent `quit` or closed stdin: up to
|
|
173
|
+
* `firstWaitMs` for the exit, then SIGTERM and up to 5 s, then SIGKILL;
|
|
174
|
+
* reaped. */
|
|
175
|
+
async stop(firstWaitMs) {
|
|
176
|
+
if (await this.waitExit(firstWaitMs))
|
|
177
|
+
return;
|
|
178
|
+
this.signal("SIGTERM");
|
|
179
|
+
if (await this.waitExit(TERM_WAIT_MS))
|
|
180
|
+
return;
|
|
181
|
+
this.signal("SIGKILL");
|
|
182
|
+
await this.waitExit(KILL_WAIT_MS);
|
|
183
|
+
}
|
|
184
|
+
/** The diagnostics of an ended process: its exit and stderr tail, each
|
|
185
|
+
* waited for briefly. Once the process was reaped and its stderr waited
|
|
186
|
+
* for, stdin and stderr are destroyed: a descendant holding them open
|
|
187
|
+
* never keeps Node alive. */
|
|
188
|
+
async diagnostics() {
|
|
189
|
+
await this.waitExit(2000);
|
|
190
|
+
await this.waitStderr(1000);
|
|
191
|
+
const release = () => {
|
|
192
|
+
this.child.stdin.destroy();
|
|
193
|
+
this.child.stderr.destroy();
|
|
194
|
+
};
|
|
195
|
+
if (this.exit !== null)
|
|
196
|
+
release();
|
|
197
|
+
else
|
|
198
|
+
this.onExit(() => void this.waitStderr(1000).then(release));
|
|
199
|
+
return {
|
|
200
|
+
exitStatus: this.exit?.code ?? null,
|
|
201
|
+
signal: this.exit?.signal ?? null,
|
|
202
|
+
stderrTail: [...this.stderrTail],
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
function waitFor(done, enlist, ms) {
|
|
207
|
+
if (done())
|
|
208
|
+
return Promise.resolve(true);
|
|
209
|
+
return new Promise((resolve) => {
|
|
210
|
+
const timer = setTimeout(() => resolve(done()), ms);
|
|
211
|
+
enlist(() => {
|
|
212
|
+
clearTimeout(timer);
|
|
213
|
+
resolve(true);
|
|
214
|
+
});
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
function sleep(ms) {
|
|
218
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
219
|
+
}
|
|
220
|
+
/** Starts `harness run|resume <id> [--mock <file>] --input-format
|
|
221
|
+
* stream-json --options <file>` (R1.1), with `env` added to this process's
|
|
222
|
+
* environment. */
|
|
223
|
+
export async function spawn(launch) {
|
|
224
|
+
if (!hooked) {
|
|
225
|
+
hooked = true;
|
|
226
|
+
process.on("exit", killLive);
|
|
227
|
+
}
|
|
228
|
+
const args = launch.resume === null ? ["run"] : ["resume", launch.resume];
|
|
229
|
+
if (launch.mock !== undefined)
|
|
230
|
+
args.push("--mock", launch.mock);
|
|
231
|
+
args.push("--input-format", "stream-json", "--options", launch.options.file);
|
|
232
|
+
// A binary written moments ago can still be open for writing in a child
|
|
233
|
+
// forked meanwhile (`ETXTBSY`); that passes.
|
|
234
|
+
for (let tries = 0;; tries++) {
|
|
235
|
+
const child = spawnChild(launch.binary, args, {
|
|
236
|
+
cwd: launch.cwd,
|
|
237
|
+
env: { ...process.env, ...launch.env },
|
|
238
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
239
|
+
});
|
|
240
|
+
const failed = await new Promise((resolve) => {
|
|
241
|
+
child.once("spawn", () => resolve(null));
|
|
242
|
+
child.once("error", (e) => resolve(e));
|
|
243
|
+
});
|
|
244
|
+
if (failed === null) {
|
|
245
|
+
const proc = new Proc(child);
|
|
246
|
+
proc.onExit(() => launch.options.remove());
|
|
247
|
+
return proc;
|
|
248
|
+
}
|
|
249
|
+
if (failed.code === "ETXTBSY" && tries < 50) {
|
|
250
|
+
await sleep(20);
|
|
251
|
+
continue;
|
|
252
|
+
}
|
|
253
|
+
throw new BinaryUnavailable(`cannot run ${launch.binary}: ${failed.message}`);
|
|
254
|
+
}
|
|
255
|
+
}
|
package/dist/tools.d.ts
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { debugQuoted } from "./wire.js";
|
|
2
|
+
export { debugQuoted };
|
|
3
|
+
/** A call's handler may take this long by default (R8.4.1). */
|
|
4
|
+
export declare const DEFAULT_TOOL_TIMEOUT_MS: number;
|
|
5
|
+
/** The most bytes a result line may hold: harness's line limit less room
|
|
6
|
+
* for the envelope (R8.4.6). */
|
|
7
|
+
export declare const RESULT_LIMIT: number;
|
|
8
|
+
/** What a handler returns: text, or text plus one image (R8.4.2). */
|
|
9
|
+
export interface ToolOutput {
|
|
10
|
+
readonly text: string;
|
|
11
|
+
readonly image?: {
|
|
12
|
+
readonly mediaType: string;
|
|
13
|
+
readonly data: Uint8Array;
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
/** What a call runs with: its id, and a signal that fires on
|
|
17
|
+
* `client_tool_cancel`, the session's end and `close()` (R8.4.4). */
|
|
18
|
+
export interface ToolContext {
|
|
19
|
+
readonly callId: string;
|
|
20
|
+
readonly signal: AbortSignal;
|
|
21
|
+
}
|
|
22
|
+
/** A tool the program runs when the model calls it (R8.4.1). Before the
|
|
23
|
+
* handler runs, the arguments are checked against the schema's top-level
|
|
24
|
+
* `required`, each property's `type` and `additionalProperties: false`; a
|
|
25
|
+
* call that fails it, a handler that throws or rejects, returns no promise,
|
|
26
|
+
* or resolves to neither a string nor a `ToolOutput`, answers `is_error`
|
|
27
|
+
* with the reason. */
|
|
28
|
+
export interface Tool {
|
|
29
|
+
readonly name: string;
|
|
30
|
+
readonly description: string;
|
|
31
|
+
readonly inputSchema: Record<string, unknown>;
|
|
32
|
+
readonly ask?: boolean;
|
|
33
|
+
readonly timeoutMs?: number;
|
|
34
|
+
readonly handler: (args: unknown, ctx: ToolContext) => Promise<ToolOutput | string>;
|
|
35
|
+
}
|
|
36
|
+
/** `ms` in whole seconds, rounded up, at least one. */
|
|
37
|
+
export declare function wholeSeconds(ms: number): number;
|
|
38
|
+
/** The tool's `client_tools` entry (R3.1). */
|
|
39
|
+
export declare function definition(tool: Tool): Record<string, unknown>;
|
|
40
|
+
/** An `is_error` result whose text is `message` cut to 64 KiB. */
|
|
41
|
+
export declare function errorLine(id: string, message: string): Buffer;
|
|
42
|
+
/** The result line for a call's outcome; one over `RESULT_LIMIT` becomes
|
|
43
|
+
* R8.4.6's error. An image's encoded size is counted before its base64 is
|
|
44
|
+
* made, so an image too large for any string is refused by its size. */
|
|
45
|
+
export declare function resultLine(id: string, outcome: {
|
|
46
|
+
ok: ToolOutput;
|
|
47
|
+
} | {
|
|
48
|
+
error: string;
|
|
49
|
+
}): Buffer;
|
|
50
|
+
/** A handler's output read once into a plain `ToolOutput`, or `null` when it
|
|
51
|
+
* is not one: an object with string `text` and, if any, an `image` of string
|
|
52
|
+
* `mediaType` and `Uint8Array` `data`. Each property is read once, so a
|
|
53
|
+
* getter cannot answer one thing to the check and another to the line. */
|
|
54
|
+
export declare function toToolOutput(out: unknown): ToolOutput | null;
|
|
55
|
+
/** A value as a message shows it: its JSON, else its `String()`, else its
|
|
56
|
+
* type's name. Never throws. */
|
|
57
|
+
export declare function shown(v: unknown): string;
|
|
58
|
+
/** A value's type, as a message names it: `null`, `undefined`, `Array`, a
|
|
59
|
+
* class's name (`Object` for a plain object), or the primitive's `typeof`. */
|
|
60
|
+
export declare function typeName(value: unknown): string;
|
|
61
|
+
/** Whether a rejection is an abort: an `AbortError` (an `AbortSignal`'s
|
|
62
|
+
* default reason, `fetch`'s on abort). */
|
|
63
|
+
export declare function isAbort(e: unknown): boolean;
|
|
64
|
+
/** A thrown value as the call's error: an `Error`'s message (its name when
|
|
65
|
+
* the message is empty), a string itself, any other value as `shown` shows
|
|
66
|
+
* it. Never throws. */
|
|
67
|
+
export declare function failureText(e: unknown): string;
|
|
68
|
+
/** The schema subset R8.4.3 checks, as the Rust SDK's `check_arguments`:
|
|
69
|
+
* the arguments an object, the schema's top-level `required` present, each
|
|
70
|
+
* present property of the `type` it names, and no property beyond
|
|
71
|
+
* `properties` when `additionalProperties` is `false`. Fields are checked
|
|
72
|
+
* in code-point order of their names (Rust's ordered map); nested values are
|
|
73
|
+
* the handler's, never recursed into. `null` when they fit, else why not. */
|
|
74
|
+
export declare function checkArguments(schema: unknown, args: unknown): string | null;
|
package/dist/tools.js
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
// Client tools (spec slice-ar R8.4): a definition with its handler, the
|
|
2
|
+
// context a call runs with, its output, and the `client_tool_result` line the
|
|
3
|
+
// SDK sends for it.
|
|
4
|
+
import { cut, debugQuoted, jsonLine, LINE_LIMIT, REASON_LIMIT, wellFormed } from "./wire.js";
|
|
5
|
+
export { debugQuoted };
|
|
6
|
+
/** A call's handler may take this long by default (R8.4.1). */
|
|
7
|
+
export const DEFAULT_TOOL_TIMEOUT_MS = 5 * 60 * 1000;
|
|
8
|
+
/** The most bytes a result line may hold: harness's line limit less room
|
|
9
|
+
* for the envelope (R8.4.6). */
|
|
10
|
+
export const RESULT_LIMIT = LINE_LIMIT - 64 * 1024;
|
|
11
|
+
/** `ms` in whole seconds, rounded up, at least one. */
|
|
12
|
+
export function wholeSeconds(ms) {
|
|
13
|
+
return Math.max(1, Math.ceil(ms / 1000));
|
|
14
|
+
}
|
|
15
|
+
/** The tool's `client_tools` entry (R3.1). */
|
|
16
|
+
export function definition(tool) {
|
|
17
|
+
return {
|
|
18
|
+
name: tool.name,
|
|
19
|
+
description: tool.description,
|
|
20
|
+
input_schema: tool.inputSchema,
|
|
21
|
+
ask: tool.ask ?? false,
|
|
22
|
+
timeout: `${wholeSeconds(tool.timeoutMs ?? DEFAULT_TOOL_TIMEOUT_MS)}s`,
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
function encoded(id, content, isError) {
|
|
26
|
+
return jsonLine({ type: "client_tool_result", id, content, is_error: isError });
|
|
27
|
+
}
|
|
28
|
+
/** An `is_error` result whose text is `message` cut to 64 KiB. */
|
|
29
|
+
export function errorLine(id, message) {
|
|
30
|
+
return encoded(id, [{ type: "text", text: cut(message, REASON_LIMIT) }], true);
|
|
31
|
+
}
|
|
32
|
+
/** The result line for a call's outcome; one over `RESULT_LIMIT` becomes
|
|
33
|
+
* R8.4.6's error. An image's encoded size is counted before its base64 is
|
|
34
|
+
* made, so an image too large for any string is refused by its size. */
|
|
35
|
+
export function resultLine(id, outcome) {
|
|
36
|
+
if ("error" in outcome)
|
|
37
|
+
return limited(id, errorLine(id, outcome.error));
|
|
38
|
+
const content = [{ type: "text", text: outcome.ok.text }];
|
|
39
|
+
const image = outcome.ok.image;
|
|
40
|
+
if (image === undefined)
|
|
41
|
+
return limited(id, encoded(id, content, false));
|
|
42
|
+
const part = { type: "image", media_type: image.mediaType, data: "" };
|
|
43
|
+
content.push(part);
|
|
44
|
+
const size = encoded(id, content, false).length + 4 * Math.ceil(image.data.length / 3);
|
|
45
|
+
if (size > RESULT_LIMIT)
|
|
46
|
+
return tooLarge(id, size);
|
|
47
|
+
part["data"] = Buffer.from(image.data.buffer, image.data.byteOffset, image.data.byteLength).toString("base64");
|
|
48
|
+
return limited(id, encoded(id, content, false));
|
|
49
|
+
}
|
|
50
|
+
function limited(id, line) {
|
|
51
|
+
return line.length > RESULT_LIMIT ? tooLarge(id, line.length) : line;
|
|
52
|
+
}
|
|
53
|
+
function tooLarge(id, size) {
|
|
54
|
+
return errorLine(id, `the tool's result was too large (${size} bytes; the limit is 8 MiB)`);
|
|
55
|
+
}
|
|
56
|
+
/** A handler's output read once into a plain `ToolOutput`, or `null` when it
|
|
57
|
+
* is not one: an object with string `text` and, if any, an `image` of string
|
|
58
|
+
* `mediaType` and `Uint8Array` `data`. Each property is read once, so a
|
|
59
|
+
* getter cannot answer one thing to the check and another to the line. */
|
|
60
|
+
export function toToolOutput(out) {
|
|
61
|
+
if (typeof out !== "object" || out === null)
|
|
62
|
+
return null;
|
|
63
|
+
const { text, image } = out;
|
|
64
|
+
if (typeof text !== "string")
|
|
65
|
+
return null;
|
|
66
|
+
if (image === undefined)
|
|
67
|
+
return { text };
|
|
68
|
+
if (typeof image !== "object" || image === null)
|
|
69
|
+
return null;
|
|
70
|
+
const { mediaType, data } = image;
|
|
71
|
+
if (typeof mediaType !== "string" || !(data instanceof Uint8Array))
|
|
72
|
+
return null;
|
|
73
|
+
return { text, image: { mediaType, data } };
|
|
74
|
+
}
|
|
75
|
+
/** A value as a message shows it: its JSON, else its `String()`, else its
|
|
76
|
+
* type's name. Never throws. */
|
|
77
|
+
export function shown(v) {
|
|
78
|
+
try {
|
|
79
|
+
const json = JSON.stringify(v);
|
|
80
|
+
if (json !== undefined)
|
|
81
|
+
return json;
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
// A cycle, a BigInt or a nesting too deep: the next form.
|
|
85
|
+
}
|
|
86
|
+
try {
|
|
87
|
+
return String(v);
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
return typeName(v);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
// ------------------------------------------------------- the call's checks
|
|
94
|
+
/** A value's type, as a message names it: `null`, `undefined`, `Array`, a
|
|
95
|
+
* class's name (`Object` for a plain object), or the primitive's `typeof`. */
|
|
96
|
+
export function typeName(value) {
|
|
97
|
+
if (value === null)
|
|
98
|
+
return "null";
|
|
99
|
+
if (Array.isArray(value))
|
|
100
|
+
return "Array";
|
|
101
|
+
if (typeof value === "object") {
|
|
102
|
+
try {
|
|
103
|
+
const name = Object.getPrototypeOf(value)?.constructor?.name;
|
|
104
|
+
return typeof name === "string" && name !== "" ? name : "Object";
|
|
105
|
+
}
|
|
106
|
+
catch {
|
|
107
|
+
return "Object";
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return typeof value;
|
|
111
|
+
}
|
|
112
|
+
/** Whether a rejection is an abort: an `AbortError` (an `AbortSignal`'s
|
|
113
|
+
* default reason, `fetch`'s on abort). */
|
|
114
|
+
export function isAbort(e) {
|
|
115
|
+
try {
|
|
116
|
+
return typeof e === "object" && e !== null && e.name === "AbortError";
|
|
117
|
+
}
|
|
118
|
+
catch {
|
|
119
|
+
return false;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
/** A thrown value as the call's error: an `Error`'s message (its name when
|
|
123
|
+
* the message is empty), a string itself, any other value as `shown` shows
|
|
124
|
+
* it. Never throws. */
|
|
125
|
+
export function failureText(e) {
|
|
126
|
+
try {
|
|
127
|
+
if (e instanceof Error)
|
|
128
|
+
return e.message !== "" ? e.message : e.name;
|
|
129
|
+
if (typeof e === "string")
|
|
130
|
+
return e;
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
// A getter that throws: the value's own form.
|
|
134
|
+
}
|
|
135
|
+
return shown(e);
|
|
136
|
+
}
|
|
137
|
+
/** The schema subset R8.4.3 checks, as the Rust SDK's `check_arguments`:
|
|
138
|
+
* the arguments an object, the schema's top-level `required` present, each
|
|
139
|
+
* present property of the `type` it names, and no property beyond
|
|
140
|
+
* `properties` when `additionalProperties` is `false`. Fields are checked
|
|
141
|
+
* in code-point order of their names (Rust's ordered map); nested values are
|
|
142
|
+
* the handler's, never recursed into. `null` when they fit, else why not. */
|
|
143
|
+
export function checkArguments(schema, args) {
|
|
144
|
+
if (!isPlainObject(args))
|
|
145
|
+
return `the arguments must be an object, not ${kind(args)}`;
|
|
146
|
+
if (!isPlainObject(schema))
|
|
147
|
+
return null;
|
|
148
|
+
// Names as the options file gives them to harness: well-formed, the later
|
|
149
|
+
// of two that become one winning, as a JSON object's duplicate.
|
|
150
|
+
const given = schema["properties"];
|
|
151
|
+
const properties = isPlainObject(given)
|
|
152
|
+
? Object.fromEntries(Object.entries(given).map(([k, v]) => [wellFormed(k), v]))
|
|
153
|
+
: {};
|
|
154
|
+
const required = schema["required"];
|
|
155
|
+
if (Array.isArray(required)) {
|
|
156
|
+
for (const name of required) {
|
|
157
|
+
if (typeof name !== "string")
|
|
158
|
+
continue;
|
|
159
|
+
const sent = wellFormed(name);
|
|
160
|
+
if (!Object.hasOwn(args, sent))
|
|
161
|
+
return `the required field ${debugQuoted(sent)} is missing`;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
const closed = schema["additionalProperties"] === false;
|
|
165
|
+
for (const name of Object.keys(args).sort(byCodePoint)) {
|
|
166
|
+
if (!Object.hasOwn(properties, name)) {
|
|
167
|
+
if (closed)
|
|
168
|
+
return `the field ${debugQuoted(name)} is not in the schema`;
|
|
169
|
+
continue;
|
|
170
|
+
}
|
|
171
|
+
const prop = properties[name];
|
|
172
|
+
if (isPlainObject(prop) && Object.hasOwn(prop, "type") && !fits(prop["type"], args[name])) {
|
|
173
|
+
return `the field ${debugQuoted(name)} must be ${expected(prop["type"])}, not ${kind(args[name])}`;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
return null;
|
|
177
|
+
}
|
|
178
|
+
function isPlainObject(v) {
|
|
179
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
180
|
+
}
|
|
181
|
+
/** Orders strings by code point, as Rust orders `String`s (by UTF-8 bytes). */
|
|
182
|
+
function byCodePoint(a, b) {
|
|
183
|
+
const x = a[Symbol.iterator]();
|
|
184
|
+
const y = b[Symbol.iterator]();
|
|
185
|
+
for (;;) {
|
|
186
|
+
const p = x.next();
|
|
187
|
+
const q = y.next();
|
|
188
|
+
if (p.done === true)
|
|
189
|
+
return q.done === true ? 0 : -1;
|
|
190
|
+
if (q.done === true)
|
|
191
|
+
return 1;
|
|
192
|
+
const d = p.value.codePointAt(0) - q.value.codePointAt(0);
|
|
193
|
+
if (d !== 0)
|
|
194
|
+
return d;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
/** Whether `value` is of the schema type `ty` (a word or a list of words);
|
|
198
|
+
* a word this check does not know passes. */
|
|
199
|
+
function fits(ty, value) {
|
|
200
|
+
if (typeof ty === "string")
|
|
201
|
+
return fitsWord(ty, value);
|
|
202
|
+
if (Array.isArray(ty))
|
|
203
|
+
return ty.some((w) => typeof w !== "string" || fitsWord(w, value));
|
|
204
|
+
return true;
|
|
205
|
+
}
|
|
206
|
+
function fitsWord(word, value) {
|
|
207
|
+
switch (word) {
|
|
208
|
+
case "object":
|
|
209
|
+
return isPlainObject(value);
|
|
210
|
+
case "array":
|
|
211
|
+
return Array.isArray(value);
|
|
212
|
+
case "string":
|
|
213
|
+
return typeof value === "string";
|
|
214
|
+
case "boolean":
|
|
215
|
+
return typeof value === "boolean";
|
|
216
|
+
case "null":
|
|
217
|
+
return value === null;
|
|
218
|
+
case "number":
|
|
219
|
+
return typeof value === "number";
|
|
220
|
+
case "integer":
|
|
221
|
+
return typeof value === "number" && Number.isInteger(value);
|
|
222
|
+
default:
|
|
223
|
+
return true;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
function expected(ty) {
|
|
227
|
+
const article = (w) => {
|
|
228
|
+
if (w === "object" || w === "array" || w === "integer")
|
|
229
|
+
return `an ${w}`;
|
|
230
|
+
if (w === "null")
|
|
231
|
+
return "null";
|
|
232
|
+
return `a ${w}`;
|
|
233
|
+
};
|
|
234
|
+
if (typeof ty === "string")
|
|
235
|
+
return article(ty);
|
|
236
|
+
if (Array.isArray(ty))
|
|
237
|
+
return ty.filter((w) => typeof w === "string").map(article).join(" or ");
|
|
238
|
+
return JSON.stringify(ty) ?? String(ty);
|
|
239
|
+
}
|
|
240
|
+
/** A JSON value's kind. A number with no fraction reads as an integer: the
|
|
241
|
+
* parsed value no longer tells `2.0` from `2`. */
|
|
242
|
+
function kind(value) {
|
|
243
|
+
if (value === null)
|
|
244
|
+
return "null";
|
|
245
|
+
if (typeof value === "boolean")
|
|
246
|
+
return "a boolean";
|
|
247
|
+
if (typeof value === "number")
|
|
248
|
+
return Number.isInteger(value) ? "an integer" : "a number";
|
|
249
|
+
if (typeof value === "string")
|
|
250
|
+
return "a string";
|
|
251
|
+
if (Array.isArray(value))
|
|
252
|
+
return "an array";
|
|
253
|
+
if (typeof value === "object")
|
|
254
|
+
return "an object";
|
|
255
|
+
return typeName(value);
|
|
256
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const VERSION: string;
|
package/dist/version.js
ADDED