@agntn/tools 0.3.3 → 0.4.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/README.md +15 -13
- package/dist/_chunks/index.d.mts +23 -6
- package/dist/_chunks/mcp-answers.d.mts +3 -0
- package/dist/_chunks/mcp-answers.mjs +61 -15
- package/dist/_chunks/questions.mjs +62 -11
- package/dist/_chunks/src.mjs +14 -2
- package/dist/_chunks/updates.mjs +14 -9
- package/dist/ai.d.mts +2 -1
- package/dist/ai.mjs +1 -0
- package/dist/cli.mjs +78 -39
- package/dist/h3.mjs +6 -2
- package/dist/http.d.mts +79 -0
- package/dist/http.mjs +247 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +2 -2
- package/dist/mcp.d.mts +11 -2
- package/dist/mcp.mjs +56 -11
- package/dist/opencode.d.mts +14 -0
- package/dist/opencode.mjs +73 -0
- package/dist/stdio.d.mts +11 -0
- package/dist/stdio.mjs +64 -0
- package/dist/toolkit.d.mts +33 -10
- package/dist/toolkit.mjs +41 -9
- package/package.json +21 -4
package/dist/cli.mjs
CHANGED
|
@@ -53,21 +53,25 @@ function takesText(branch) {
|
|
|
53
53
|
if (branch.type === "string" || typeof branch.const === "string") return true;
|
|
54
54
|
return Array.isArray(branch.enum) && branch.enum.every((value) => typeof value === "string");
|
|
55
55
|
}
|
|
56
|
-
function
|
|
57
|
-
const cli = tool.cli ?? {};
|
|
56
|
+
function hintDefaults(cli) {
|
|
58
57
|
const rest = cli.rest === void 0 ? [] : [cli.rest];
|
|
59
|
-
|
|
58
|
+
return {
|
|
60
59
|
positional: [...cli.positional ?? [], ...rest],
|
|
61
60
|
plain: cli.plain ?? [],
|
|
62
61
|
rest,
|
|
63
62
|
short: cli.short ?? {},
|
|
63
|
+
flags: cli.flags ?? {},
|
|
64
64
|
stdin: cli.stdin ?? []
|
|
65
65
|
};
|
|
66
|
+
}
|
|
67
|
+
function cliHints(tool) {
|
|
68
|
+
const hints = hintDefaults(tool.cli ?? {});
|
|
66
69
|
const properties = tool.input.properties;
|
|
67
70
|
const named = [
|
|
68
71
|
...hints.positional,
|
|
69
72
|
...hints.plain,
|
|
70
73
|
...Object.keys(hints.short),
|
|
74
|
+
...Object.keys(hints.flags),
|
|
71
75
|
...hints.stdin
|
|
72
76
|
];
|
|
73
77
|
for (const key of named) if (!Object.hasOwn(properties, key)) throw new ToolDefinitionError(`${tool.name}: cli hint names unknown property ${key}`);
|
|
@@ -81,9 +85,12 @@ function assertPositionals(tool, hints) {
|
|
|
81
85
|
const flag = hints.plain.find((key) => !positional.includes(key));
|
|
82
86
|
if (flag !== void 0) throw new ToolDefinitionError(`${tool.name}: plain property ${flag} must be positional`);
|
|
83
87
|
}
|
|
88
|
+
function ownEntry(record, key) {
|
|
89
|
+
return Object.hasOwn(record, key) ? record[key] : void 0;
|
|
90
|
+
}
|
|
84
91
|
function toolFields(tool) {
|
|
85
92
|
const properties = tool.input.properties;
|
|
86
|
-
const { positional, plain, rest, short, stdin } = cliHints(tool);
|
|
93
|
+
const { positional, plain, rest, short, flags: aliases, stdin } = cliHints(tool);
|
|
87
94
|
const keys = [...positional, ...Object.keys(properties).filter((key) => !positional.includes(key))];
|
|
88
95
|
const required = tool.input.required ?? [];
|
|
89
96
|
const flags = /* @__PURE__ */ new Set();
|
|
@@ -98,7 +105,8 @@ function toolFields(tool) {
|
|
|
98
105
|
plain: plain.includes(key),
|
|
99
106
|
rest: rest.includes(key),
|
|
100
107
|
restItems: rest.includes(key) ? textItems(properties[key] ?? {}) : void 0,
|
|
101
|
-
short:
|
|
108
|
+
short: ownEntry(short, key),
|
|
109
|
+
aliases: ownEntry(aliases, key) ?? [],
|
|
102
110
|
stdin: stdin.includes(key)
|
|
103
111
|
};
|
|
104
112
|
assertField(tool, field, !field.positional && flags.has(field.flag));
|
|
@@ -110,17 +118,22 @@ function toolFields(tool) {
|
|
|
110
118
|
assertRequiredPositionalsFirst(tool, fields);
|
|
111
119
|
return fields;
|
|
112
120
|
}
|
|
113
|
-
function assertFlag(tool, field) {
|
|
114
|
-
if (!FLAG_WORD.test(
|
|
115
|
-
if (field.kind === "boolean" &&
|
|
116
|
-
if (RESERVED_FLAGS.has(
|
|
121
|
+
function assertFlag(tool, field, flag) {
|
|
122
|
+
if (!FLAG_WORD.test(flag)) throw new ToolDefinitionError(`${tool.name}: property ${JSON.stringify(field.key)} gives the flag ${JSON.stringify(flag)}, which must match ${FLAG_WORD}`);
|
|
123
|
+
if (field.kind === "boolean" && flag.startsWith("no-")) throw new ToolDefinitionError(`${tool.name}: boolean property ${field.key} cannot take a flag starting with no-; name the positive and --no-${flag.slice(3)} negates it`);
|
|
124
|
+
if (RESERVED_FLAGS.has(flag)) throw new ToolDefinitionError(`${tool.name}: property ${field.key} takes the reserved flag --${flag}`);
|
|
117
125
|
}
|
|
118
126
|
function assertField(tool, field, taken) {
|
|
119
|
-
if (!field.positional) assertFlag(tool, field);
|
|
127
|
+
if (!field.positional) assertFlag(tool, field, field.flag);
|
|
128
|
+
assertAliases(tool, field);
|
|
120
129
|
if (taken) throw new ToolDefinitionError(`${tool.name}: two properties take the flag --${field.flag}`);
|
|
121
130
|
if (field.positional && field.kind === "boolean") throw new ToolDefinitionError(`${tool.name}: boolean property ${field.key} cannot be positional`);
|
|
122
131
|
assertTextHints(tool, field);
|
|
123
132
|
}
|
|
133
|
+
function assertAliases(tool, field) {
|
|
134
|
+
if (!Array.isArray(field.aliases)) throw new ToolDefinitionError(`${tool.name}: flags of ${field.key} must be a list of names`);
|
|
135
|
+
for (const alias of field.aliases) assertFlag(tool, field, alias);
|
|
136
|
+
}
|
|
124
137
|
function assertTextHints(tool, field) {
|
|
125
138
|
if (field.stdin && field.kind !== "string") throw new ToolDefinitionError(`${tool.name}: stdin property ${field.key} must be a string`);
|
|
126
139
|
if (field.rest && field.restItems === void 0 && !TEXT_KINDS.has(field.kind)) throw new ToolDefinitionError(`${tool.name}: rest property ${field.key} must be a string or an array of strings`);
|
|
@@ -139,20 +152,26 @@ function assertRequiredPositionalsFirst(tool, fields) {
|
|
|
139
152
|
}
|
|
140
153
|
function assertOneOptionPerSpelling(tool, fields) {
|
|
141
154
|
const owners = /* @__PURE__ */ new Map();
|
|
142
|
-
for (const field of fields
|
|
143
|
-
const
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
...negation,
|
|
148
|
-
...short
|
|
149
|
-
]) {
|
|
150
|
-
const owner = owners.get(spelling);
|
|
151
|
-
if (owner !== void 0) throw new ToolDefinitionError(`${tool.name}: properties ${owner} and ${field.key} both answer to ${spelling}`);
|
|
152
|
-
owners.set(spelling, field.key);
|
|
153
|
-
}
|
|
155
|
+
for (const field of fields) for (const spelling of spellings(field)) {
|
|
156
|
+
const owner = owners.get(spelling);
|
|
157
|
+
if (owner === field.key) throw new ToolDefinitionError(`${tool.name}: property ${owner} answers to ${spelling} twice`);
|
|
158
|
+
if (owner !== void 0) throw new ToolDefinitionError(`${tool.name}: properties ${owner} and ${field.key} both answer to ${spelling}`);
|
|
159
|
+
owners.set(spelling, field.key);
|
|
154
160
|
}
|
|
155
161
|
}
|
|
162
|
+
function longFlags(field) {
|
|
163
|
+
return [...field.positional ? [] : [field.flag], ...field.aliases];
|
|
164
|
+
}
|
|
165
|
+
function spellings(field) {
|
|
166
|
+
const long = longFlags(field);
|
|
167
|
+
const negation = field.kind === "boolean" ? long.map((flag) => `--no-${flag}`) : [];
|
|
168
|
+
const short = field.short === void 0 ? [] : [`-${field.short}`];
|
|
169
|
+
return [
|
|
170
|
+
...long.map((flag) => `--${flag}`),
|
|
171
|
+
...negation,
|
|
172
|
+
...short
|
|
173
|
+
];
|
|
174
|
+
}
|
|
156
175
|
function fieldDescription(field, values = "") {
|
|
157
176
|
const { schema } = field;
|
|
158
177
|
return [
|
|
@@ -187,7 +206,7 @@ function emptyRecord() {
|
|
|
187
206
|
return Object.create(null);
|
|
188
207
|
}
|
|
189
208
|
function parseWords(rawArgs, fields, takesJson) {
|
|
190
|
-
const entries = [...fields.
|
|
209
|
+
const entries = [...fields.flatMap((field) => longFlags(field).map((flag) => [flag, field])), ...takesJson ? [["json", "json"]] : []];
|
|
191
210
|
const options = Object.fromEntries(entries);
|
|
192
211
|
const { args, origins, texts, refused } = takeDashedText(rawArgs, fields, options);
|
|
193
212
|
const { tokens } = parseArgs({
|
|
@@ -204,20 +223,22 @@ function parseWords(rawArgs, fields, takesJson) {
|
|
|
204
223
|
const ordered = inLineOrder(tokens, origins, texts);
|
|
205
224
|
const positionals = ordered.map(([, word]) => word);
|
|
206
225
|
const values = emptyRecord();
|
|
207
|
-
const
|
|
226
|
+
const misread = [];
|
|
208
227
|
const flags = /* @__PURE__ */ new Set();
|
|
209
228
|
for (const token of tokens) {
|
|
210
229
|
if (token.kind !== "option") continue;
|
|
211
230
|
const read = readOption(options, token, args[token.index] ?? "", Object.keys(values));
|
|
212
|
-
if ("error" in read)
|
|
231
|
+
if ("error" in read) misread.push(read.error);
|
|
213
232
|
else if ("flag" in read) flags.add(read.flag);
|
|
214
233
|
else values[read.key] = read.value;
|
|
215
234
|
}
|
|
235
|
+
const open = fields.filter((field) => !Object.hasOwn(values, field.key));
|
|
236
|
+
const errors = [...[...landedInPlain(open, ordered, texts), ...refused].map((word) => unknownOption(options, word)), ...misread];
|
|
216
237
|
return {
|
|
217
|
-
values: Object.assign(values, positionalValues(
|
|
238
|
+
values: Object.assign(values, positionalValues(open, positionals)),
|
|
218
239
|
json: flags.has("json"),
|
|
219
240
|
help: flags.has("help"),
|
|
220
|
-
errors: [...new Set(errors.length > 0 ? errors : extraPositionals(
|
|
241
|
+
errors: [...new Set(errors.length > 0 ? errors : extraPositionals(open, positionals))]
|
|
221
242
|
};
|
|
222
243
|
}
|
|
223
244
|
function takeDashedText(rawArgs, fields, options) {
|
|
@@ -244,15 +265,19 @@ function scanWords(rawArgs, options) {
|
|
|
244
265
|
plain: plain + rawArgs.length - index - 1
|
|
245
266
|
};
|
|
246
267
|
const kind = wordKind(word, options);
|
|
247
|
-
if (kind === "
|
|
248
|
-
else if (kind === "
|
|
249
|
-
|
|
268
|
+
if (kind === "text") dashed.push(index);
|
|
269
|
+
else if (kind === "plain" || fillsPositional(word, options)) plain++;
|
|
270
|
+
if (kind === "valued") index++;
|
|
250
271
|
}
|
|
251
272
|
return {
|
|
252
273
|
dashed,
|
|
253
274
|
plain
|
|
254
275
|
};
|
|
255
276
|
}
|
|
277
|
+
function fillsPositional(word, options) {
|
|
278
|
+
const field = word.startsWith("--") ? longField(word.slice(2), options) : void 0;
|
|
279
|
+
return typeof field === "object" && field.positional;
|
|
280
|
+
}
|
|
256
281
|
function wordKind(word, options) {
|
|
257
282
|
if (!word.startsWith("-") || word === "-") return "plain";
|
|
258
283
|
if (word === "-h") return "option";
|
|
@@ -312,12 +337,11 @@ function optionField(options, token, word) {
|
|
|
312
337
|
return field !== void 0 && spells(field, token, word) ? field : void 0;
|
|
313
338
|
}
|
|
314
339
|
function spells(field, token, word) {
|
|
315
|
-
if (token.rawName === `--${field.flag}`) return true;
|
|
316
340
|
if (field.short !== void 0 && token.rawName === `-${field.short}`) return word === token.rawName;
|
|
317
|
-
return field.
|
|
341
|
+
return spellings(field).includes(token.rawName);
|
|
318
342
|
}
|
|
319
343
|
function unknownOption(options, word) {
|
|
320
|
-
const flags = Object.entries(options).map(([flag, each]) => each === "json" || each.short === void 0 ? `--${flag}` : `--${flag} (-${each.short})`);
|
|
344
|
+
const flags = Object.entries(options).filter(([flag, each]) => each === "json" || !each.positional && flag === each.flag).map(([flag, each]) => each === "json" || each.short === void 0 ? `--${flag}` : `--${flag} (-${each.short})`);
|
|
321
345
|
const takes = flags.length > 0 ? flags.join(", ") : "no options";
|
|
322
346
|
return `Invalid arguments: unknown option ${JSON.stringify(word)}; takes ${takes}`;
|
|
323
347
|
}
|
|
@@ -325,17 +349,25 @@ function readOption(options, token, word, seen) {
|
|
|
325
349
|
const field = optionField(options, token, word);
|
|
326
350
|
if (field === void 0) return { error: unknownOption(options, word) };
|
|
327
351
|
if (field === "json" || field === "help") return token.inlineValue === true ? { error: `Invalid arguments: ${token.rawName} takes no value` } : { flag: field };
|
|
352
|
+
const flag = typedFlag(field, token);
|
|
328
353
|
const problem = optionProblem(field, token, seen.includes(field.key));
|
|
329
|
-
if (problem !== void 0) return { error: `Invalid arguments: --${
|
|
330
|
-
const value = field.kind === "boolean" ? token.rawName !== `--no-${
|
|
354
|
+
if (problem !== void 0) return { error: `Invalid arguments: --${flag} ${problem}` };
|
|
355
|
+
const value = field.kind === "boolean" ? token.rawName !== `--no-${flag}` : token.value;
|
|
331
356
|
return {
|
|
332
357
|
key: field.key,
|
|
333
358
|
value: value ?? ""
|
|
334
359
|
};
|
|
335
360
|
}
|
|
361
|
+
function typedFlag(field, token) {
|
|
362
|
+
const typed = (flag) => token.rawName === `--${flag}` || token.rawName === `--no-${flag}`;
|
|
363
|
+
return field.aliases.find(typed) ?? field.flag;
|
|
364
|
+
}
|
|
336
365
|
function optionProblem(field, token, seen) {
|
|
337
366
|
if (seen) return "given more than once";
|
|
338
|
-
if (field.kind === "boolean")
|
|
367
|
+
if (field.kind === "boolean") {
|
|
368
|
+
const flag = typedFlag(field, token);
|
|
369
|
+
return token.inlineValue === true ? `takes no value; use --${flag} or --no-${flag}` : void 0;
|
|
370
|
+
}
|
|
339
371
|
return token.value === void 0 ? "needs a value" : void 0;
|
|
340
372
|
}
|
|
341
373
|
function readStdin() {
|
|
@@ -449,6 +481,12 @@ function placeIn(field, inner) {
|
|
|
449
481
|
return `/${inner.join("/")} of ${fieldWord(field)}`;
|
|
450
482
|
}
|
|
451
483
|
function cliIssueLines(fields, issue) {
|
|
484
|
+
const lines = rebuiltLines(fields, issue);
|
|
485
|
+
if (lines === void 0) return [issue.line];
|
|
486
|
+
if (issue.hint === void 0 || lines.length === 0) return lines;
|
|
487
|
+
return [...lines.slice(0, -1), `${lines.at(-1)}. ${issue.hint}`];
|
|
488
|
+
}
|
|
489
|
+
function rebuiltLines(fields, issue) {
|
|
452
490
|
const byKey = (key) => fields.find((field) => field.key === key);
|
|
453
491
|
if (issue.at === "" && issue.missing !== void 0) return issue.missing.map((key) => {
|
|
454
492
|
const field = byKey(key);
|
|
@@ -456,7 +494,7 @@ function cliIssueLines(fields, issue) {
|
|
|
456
494
|
});
|
|
457
495
|
const [, first, ...inner] = issue.at.split("/");
|
|
458
496
|
const field = first === void 0 ? void 0 : byKey(first.replaceAll("~1", "/").replaceAll("~0", "~"));
|
|
459
|
-
if (field === void 0) return
|
|
497
|
+
if (field === void 0) return void 0;
|
|
460
498
|
return [`Invalid arguments at ${placeIn(field, inner)}: ${issue.problem}`];
|
|
461
499
|
}
|
|
462
500
|
function cliLines(fields, refusal) {
|
|
@@ -552,6 +590,7 @@ function toolCommand(tool) {
|
|
|
552
590
|
const fields = toolFields(tool);
|
|
553
591
|
const [summary = tool.title] = tool.description.split(/(?<=[.!?])\s/, 1);
|
|
554
592
|
const name = commandName(tool);
|
|
593
|
+
const print = tool.cli?.verbatim === true ? String : sanitizeText;
|
|
555
594
|
return {
|
|
556
595
|
name,
|
|
557
596
|
word: name.slice(name.indexOf(" ") + 1),
|
|
@@ -581,7 +620,7 @@ function toolCommand(tool) {
|
|
|
581
620
|
process.exitCode = 1;
|
|
582
621
|
} else if (words.json) writeLine("stdout", detailsJson(result.details));
|
|
583
622
|
else if (result.content.length > 0) {
|
|
584
|
-
writeLine("stdout",
|
|
623
|
+
writeLine("stdout", print(resultText(result)));
|
|
585
624
|
const images = result.content.filter((block) => block.type === "image").length;
|
|
586
625
|
if (images > 0) writeLine("stderr", `(${images} image block(s) not printed)`);
|
|
587
626
|
}
|
|
@@ -597,7 +636,7 @@ function mcpCommand(options) {
|
|
|
597
636
|
fields: [],
|
|
598
637
|
json: false,
|
|
599
638
|
async run() {
|
|
600
|
-
const [{ createMcpServer }, { serveStdio }] = await Promise.all([import("./mcp.mjs"), import("
|
|
639
|
+
const [{ createMcpServer }, { serveStdio }] = await Promise.all([import("./mcp.mjs"), import("./stdio.mjs")]);
|
|
601
640
|
const info = typeof options.mcp === "object" ? options.mcp : options;
|
|
602
641
|
serveStdio(() => createMcpServer(info, options.tools));
|
|
603
642
|
}
|
package/dist/h3.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import "./_chunks/src.mjs";
|
|
2
|
-
import { callAsking, canAsk, listTools, mcpHost, progressSteps, questionRound } from "./_chunks/mcp-answers.mjs";
|
|
2
|
+
import { askForm, callAsking, canAsk, listTools, mcpHost, progressSteps, questionRound } from "./_chunks/mcp-answers.mjs";
|
|
3
3
|
function toH3Tools(info, tools) {
|
|
4
4
|
return listTools(tools).map((entry) => ({
|
|
5
5
|
name: entry.name,
|
|
@@ -28,7 +28,11 @@ function toH3Tools(info, tools) {
|
|
|
28
28
|
}
|
|
29
29
|
function roundOf(mcp) {
|
|
30
30
|
if (mcp?.era !== "modern" || !canAsk(mcp.clientCapabilities)) return void 0;
|
|
31
|
-
|
|
31
|
+
const { inputResponses: responses, requestState: state, clientCapabilities } = mcp;
|
|
32
|
+
return questionRound({
|
|
33
|
+
responses,
|
|
34
|
+
state
|
|
35
|
+
}, askForm(clientCapabilities));
|
|
32
36
|
}
|
|
33
37
|
function numbered(send) {
|
|
34
38
|
return progressSteps(({ progress, total, message }) => send(progress, total, message));
|
package/dist/http.d.mts
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { ToolDefinition, ToolEffect } from "./_chunks/index.mjs";
|
|
2
|
+
/** What `GET /` names the server by. */
|
|
3
|
+
export interface HttpServerInfo {
|
|
4
|
+
/** Server name, also the word in the message for an unknown tool. */
|
|
5
|
+
readonly name: string;
|
|
6
|
+
readonly version: string;
|
|
7
|
+
}
|
|
8
|
+
/** Options for {@link createHttpHandler}. */
|
|
9
|
+
export interface HttpHandlerOptions {
|
|
10
|
+
/** Effects served, `["read"]` by default. */
|
|
11
|
+
readonly effects?: readonly ToolEffect[];
|
|
12
|
+
/** Mount path, such as `/http/memory`. The root by default. */
|
|
13
|
+
readonly base?: string;
|
|
14
|
+
/** Largest body in bytes, 4 MiB by default. A bigger one gets 413. */
|
|
15
|
+
readonly maxRequestBodySize?: number;
|
|
16
|
+
}
|
|
17
|
+
/** What a tool finds in `host` over HTTP. The client wrote it, so it proves nothing. */
|
|
18
|
+
export interface HttpHost {
|
|
19
|
+
readonly http: true;
|
|
20
|
+
/** The request behind the call, headers included. */
|
|
21
|
+
readonly request: Request;
|
|
22
|
+
}
|
|
23
|
+
/** One tool as `GET /` lists it. */
|
|
24
|
+
export interface HttpToolEntry {
|
|
25
|
+
readonly name: string;
|
|
26
|
+
readonly title: string;
|
|
27
|
+
readonly description: string;
|
|
28
|
+
readonly effect: ToolEffect;
|
|
29
|
+
readonly inputSchema: Readonly<Record<string, unknown>>;
|
|
30
|
+
}
|
|
31
|
+
/** What `GET /` answers. */
|
|
32
|
+
export interface HttpListing {
|
|
33
|
+
readonly name: string;
|
|
34
|
+
readonly version: string;
|
|
35
|
+
readonly tools: readonly HttpToolEntry[];
|
|
36
|
+
}
|
|
37
|
+
/** What a tool answered: status 200, or 422 when it set `isError`. */
|
|
38
|
+
export interface HttpAnswer {
|
|
39
|
+
/** The text blocks joined by newlines. */
|
|
40
|
+
readonly text: string;
|
|
41
|
+
readonly details: unknown;
|
|
42
|
+
/** The result's image blocks, present only when it has some. */
|
|
43
|
+
readonly images?: readonly {
|
|
44
|
+
readonly data: string;
|
|
45
|
+
readonly mimeType: string;
|
|
46
|
+
}[];
|
|
47
|
+
}
|
|
48
|
+
/** Why the call never got an answer: bad input, an unknown tool, a throw. */
|
|
49
|
+
export interface HttpRefusal {
|
|
50
|
+
/** One line each, cleaned of anything that forges a line. */
|
|
51
|
+
readonly lines: readonly string[];
|
|
52
|
+
}
|
|
53
|
+
/** One `progress` event of a streamed call. Numbers only when the tool gave them. */
|
|
54
|
+
export interface HttpProgress {
|
|
55
|
+
readonly message: string;
|
|
56
|
+
readonly progress?: number;
|
|
57
|
+
readonly total?: number;
|
|
58
|
+
}
|
|
59
|
+
/** The `result` event ending a stream: the plain body plus its status. */
|
|
60
|
+
export type HttpResult = (HttpAnswer | HttpRefusal) & {
|
|
61
|
+
readonly status: number;
|
|
62
|
+
};
|
|
63
|
+
/** A Fetch handler: `Request` in, `Response` out. */
|
|
64
|
+
export interface HttpHandler {
|
|
65
|
+
readonly fetch: (request: Request) => Promise<Response>;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Serves tools as JSON: `GET /` lists them, `POST /<tool name>` calls one.
|
|
69
|
+
* A call with `Accept: text/event-stream` streams its progress before the answer.
|
|
70
|
+
*
|
|
71
|
+
* @param info - Name and version for the listing.
|
|
72
|
+
* @param tools - Tools to serve.
|
|
73
|
+
* @param options - The served effects and the mount path.
|
|
74
|
+
* @returns {HttpHandler} The handler, with `fetch` bound to it.
|
|
75
|
+
* @throws {ToolDefinitionError} When two tools share a name.
|
|
76
|
+
* @throws {TypeError} When `base` or `effects` is malformed.
|
|
77
|
+
* @throws {RangeError} When `maxRequestBodySize` isn't a positive number.
|
|
78
|
+
*/
|
|
79
|
+
export declare function createHttpHandler(info: HttpServerInfo, tools: readonly ToolDefinition[], options?: HttpHandlerOptions): HttpHandler;
|
package/dist/http.mjs
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
import { ToolInputError, indexTools, invokeTool, resultText, sanitizeLine, wireSchema } from "./_chunks/src.mjs";
|
|
2
|
+
import { causeLines } from "./_chunks/causes.mjs";
|
|
3
|
+
const MAX_BODY = 4194304;
|
|
4
|
+
const EFFECTS = [
|
|
5
|
+
"read",
|
|
6
|
+
"write",
|
|
7
|
+
"destructive",
|
|
8
|
+
"exec"
|
|
9
|
+
];
|
|
10
|
+
function createHttpHandler(info, tools, options = {}) {
|
|
11
|
+
indexTools(tools);
|
|
12
|
+
const effects = servedEffects(options.effects);
|
|
13
|
+
const listed = tools.filter((tool) => effects.includes(tool.effect)).map(entryOf);
|
|
14
|
+
const served = {
|
|
15
|
+
info,
|
|
16
|
+
base: basePath(options.base),
|
|
17
|
+
maxBody: bodyLimit(options.maxRequestBodySize),
|
|
18
|
+
effects,
|
|
19
|
+
tools: [...tools],
|
|
20
|
+
listing: {
|
|
21
|
+
name: info.name,
|
|
22
|
+
version: info.version,
|
|
23
|
+
tools: listed
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
return { fetch: async (request) => await route(served, request) };
|
|
27
|
+
}
|
|
28
|
+
function servedEffects(effects) {
|
|
29
|
+
if (effects === void 0) return ["read"];
|
|
30
|
+
if (!Array.isArray(effects)) throw new TypeError(`effects must be a list, got ${JSON.stringify(effects)}`);
|
|
31
|
+
const stray = effects.find((effect) => !EFFECTS.includes(effect));
|
|
32
|
+
if (stray !== void 0) throw new TypeError(`effects takes ${EFFECTS.join(", ")}, got ${JSON.stringify(stray)}`);
|
|
33
|
+
return [...effects];
|
|
34
|
+
}
|
|
35
|
+
function basePath(base) {
|
|
36
|
+
if (base === void 0) return "";
|
|
37
|
+
if (!base.startsWith("/")) throw new TypeError(`base must start with "/", got ${JSON.stringify(base)}`);
|
|
38
|
+
return new URL(base, "http://localhost").pathname.replace(/\/+$/, "");
|
|
39
|
+
}
|
|
40
|
+
function bodyLimit(size) {
|
|
41
|
+
if (size === void 0) return MAX_BODY;
|
|
42
|
+
if (typeof size !== "number" || !Number.isFinite(size) || size <= 0) throw new RangeError(`maxRequestBodySize must be a positive number of bytes, got ${String(size)}`);
|
|
43
|
+
return size;
|
|
44
|
+
}
|
|
45
|
+
function entryOf(tool) {
|
|
46
|
+
const { name, title, description, effect } = tool;
|
|
47
|
+
return {
|
|
48
|
+
name,
|
|
49
|
+
title,
|
|
50
|
+
description,
|
|
51
|
+
effect,
|
|
52
|
+
inputSchema: wireSchema(tool)
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
async function route(served, request) {
|
|
56
|
+
const { pathname } = new URL(request.url);
|
|
57
|
+
const name = toolPath(served.base, pathname);
|
|
58
|
+
if (name === "") return request.method === "GET" ? Response.json(served.listing) : wrongMethod("GET");
|
|
59
|
+
if (name === void 0) return refusal(404, `Nothing at ${pathname}`);
|
|
60
|
+
if (request.method !== "POST") return wrongMethod("POST");
|
|
61
|
+
return await call(served, name, request);
|
|
62
|
+
}
|
|
63
|
+
function toolPath(base, pathname) {
|
|
64
|
+
if (!pathname.startsWith(base)) return void 0;
|
|
65
|
+
const rest = pathname.slice(base.length);
|
|
66
|
+
if (rest === "" || rest === "/") return "";
|
|
67
|
+
const name = rest.slice(1);
|
|
68
|
+
return rest.startsWith("/") && name !== "" && !name.includes("/") ? name : void 0;
|
|
69
|
+
}
|
|
70
|
+
async function call(served, name, request) {
|
|
71
|
+
const tool = served.tools.find((candidate) => candidate.name === name);
|
|
72
|
+
if (tool === void 0) return refusal(404, `Unknown ${served.info.name} tool: ${JSON.stringify(name)}`);
|
|
73
|
+
if (!served.effects.includes(tool.effect)) {
|
|
74
|
+
const allowed = served.effects.join(", ") || "nothing";
|
|
75
|
+
return refusal(403, `${tool.name} is a ${tool.effect} tool, and this handler serves ${allowed}`);
|
|
76
|
+
}
|
|
77
|
+
if (!isJson(request.headers.get("content-type"))) return refusal(415, "Send the input as Content-Type: application/json");
|
|
78
|
+
const input = await readInput(request, served.maxBody);
|
|
79
|
+
if (!input.ok) return refusal(input.status, input.line);
|
|
80
|
+
if (wantsStream(request.headers.get("accept"))) return streamed(tool, input.value, request);
|
|
81
|
+
const host = {
|
|
82
|
+
http: true,
|
|
83
|
+
request
|
|
84
|
+
};
|
|
85
|
+
const { status, body } = encoded(tool, await settle(tool, input.value, {
|
|
86
|
+
signal: request.signal,
|
|
87
|
+
host
|
|
88
|
+
}), false);
|
|
89
|
+
return new Response(body, {
|
|
90
|
+
status,
|
|
91
|
+
headers: { "content-type": "application/json" }
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
function wantsStream(accept) {
|
|
95
|
+
return (accept ?? "").split(",").some((range) => {
|
|
96
|
+
const [type, ...params] = range.split(";").map((part) => part.trim().toLowerCase());
|
|
97
|
+
return type === "text/event-stream" && !params.some((param) => /^q=0(?:\.0*)?$/u.test(param));
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
async function settle(tool, input, context) {
|
|
101
|
+
try {
|
|
102
|
+
const result = await invokeTool(tool, input, context);
|
|
103
|
+
return {
|
|
104
|
+
status: result.isError === true ? 422 : 200,
|
|
105
|
+
body: answerOf(result)
|
|
106
|
+
};
|
|
107
|
+
} catch (error) {
|
|
108
|
+
return failure(tool, error);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
function failure(tool, error) {
|
|
112
|
+
if (error instanceof ToolInputError) return refused(400, ...error.lines);
|
|
113
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
114
|
+
return refused(500, `${tool.name} failed: ${message}`, ...causeLines(error));
|
|
115
|
+
}
|
|
116
|
+
function encoded(tool, settled, withStatus) {
|
|
117
|
+
const text = (ending) => JSON.stringify(withStatus ? {
|
|
118
|
+
status: ending.status,
|
|
119
|
+
...ending.body
|
|
120
|
+
} : ending.body);
|
|
121
|
+
try {
|
|
122
|
+
return {
|
|
123
|
+
status: settled.status,
|
|
124
|
+
body: text(settled)
|
|
125
|
+
};
|
|
126
|
+
} catch (error) {
|
|
127
|
+
const fallback = failure(tool, error);
|
|
128
|
+
return {
|
|
129
|
+
status: fallback.status,
|
|
130
|
+
body: text(fallback)
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
function streamed(tool, input, request) {
|
|
135
|
+
const left = new AbortController();
|
|
136
|
+
const signal = AbortSignal.any([request.signal, left.signal]);
|
|
137
|
+
const host = {
|
|
138
|
+
http: true,
|
|
139
|
+
request
|
|
140
|
+
};
|
|
141
|
+
const encoder = new TextEncoder();
|
|
142
|
+
const body = new ReadableStream({
|
|
143
|
+
start(controller) {
|
|
144
|
+
const send = (event, data) => {
|
|
145
|
+
controller.enqueue(encoder.encode(`event: ${event}\ndata: ${data}\n\n`));
|
|
146
|
+
};
|
|
147
|
+
const progress = (message, amount) => {
|
|
148
|
+
send("progress", JSON.stringify(progressOf(message, amount)));
|
|
149
|
+
};
|
|
150
|
+
settle(tool, input, {
|
|
151
|
+
signal,
|
|
152
|
+
host,
|
|
153
|
+
progress
|
|
154
|
+
}).then((settled) => {
|
|
155
|
+
try {
|
|
156
|
+
send("result", encoded(tool, settled, true).body);
|
|
157
|
+
controller.close();
|
|
158
|
+
} catch {}
|
|
159
|
+
});
|
|
160
|
+
},
|
|
161
|
+
cancel(reason) {
|
|
162
|
+
left.abort(reason);
|
|
163
|
+
}
|
|
164
|
+
});
|
|
165
|
+
return new Response(body, { headers: {
|
|
166
|
+
"content-type": "text/event-stream",
|
|
167
|
+
"cache-control": "no-cache"
|
|
168
|
+
} });
|
|
169
|
+
}
|
|
170
|
+
function progressOf(message, amount) {
|
|
171
|
+
const progress = amount?.progress;
|
|
172
|
+
const total = amount?.total;
|
|
173
|
+
return {
|
|
174
|
+
message,
|
|
175
|
+
...Number.isFinite(progress) ? { progress } : {},
|
|
176
|
+
...Number.isFinite(total) ? { total } : {}
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
function isJson(type) {
|
|
180
|
+
return type?.split(";", 1)[0]?.trim().toLowerCase() === "application/json";
|
|
181
|
+
}
|
|
182
|
+
async function readInput(request, limit) {
|
|
183
|
+
try {
|
|
184
|
+
const body = await readBody(request, limit);
|
|
185
|
+
if (body === void 0) return {
|
|
186
|
+
ok: false,
|
|
187
|
+
status: 413,
|
|
188
|
+
line: `Body is over ${limit} bytes`
|
|
189
|
+
};
|
|
190
|
+
return {
|
|
191
|
+
ok: true,
|
|
192
|
+
value: body.trim() === "" ? {} : JSON.parse(body)
|
|
193
|
+
};
|
|
194
|
+
} catch (error) {
|
|
195
|
+
return {
|
|
196
|
+
ok: false,
|
|
197
|
+
status: 400,
|
|
198
|
+
line: `Body is not JSON: ${error instanceof Error ? error.message : String(error)}`
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
async function readBody(request, limit) {
|
|
203
|
+
if (Number(request.headers.get("content-length")) > limit) return void 0;
|
|
204
|
+
const reader = request.body?.getReader();
|
|
205
|
+
if (reader === void 0) return "";
|
|
206
|
+
const decoder = new TextDecoder();
|
|
207
|
+
let text = "";
|
|
208
|
+
let size = 0;
|
|
209
|
+
for (let read = await reader.read(); !read.done; read = await reader.read()) {
|
|
210
|
+
size += read.value.byteLength;
|
|
211
|
+
if (size > limit) {
|
|
212
|
+
reader.cancel().catch(() => void 0);
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
text += decoder.decode(read.value, { stream: true });
|
|
216
|
+
}
|
|
217
|
+
return text + decoder.decode();
|
|
218
|
+
}
|
|
219
|
+
function answerOf(result) {
|
|
220
|
+
const images = result.content.flatMap((block) => block.type === "image" ? [{
|
|
221
|
+
data: block.data,
|
|
222
|
+
mimeType: block.mimeType
|
|
223
|
+
}] : []);
|
|
224
|
+
return {
|
|
225
|
+
text: resultText(result),
|
|
226
|
+
details: result.details ?? null,
|
|
227
|
+
...images.length > 0 ? { images } : {}
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
function refused(status, ...lines) {
|
|
231
|
+
return {
|
|
232
|
+
status,
|
|
233
|
+
body: { lines: lines.map(sanitizeLine) }
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
function refusal(status, ...lines) {
|
|
237
|
+
const { body } = refused(status, ...lines);
|
|
238
|
+
return Response.json(body, { status });
|
|
239
|
+
}
|
|
240
|
+
function wrongMethod(allow) {
|
|
241
|
+
const body = { lines: [`Use ${allow} here`] };
|
|
242
|
+
return Response.json(body, {
|
|
243
|
+
status: 405,
|
|
244
|
+
headers: { allow }
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
export { createHttpHandler };
|