@agntn/tools 0.2.1 → 0.2.3
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 +11 -9
- package/dist/_chunks/index.d.mts +50 -6
- package/dist/_chunks/libs/typebox.d.mts +1 -2
- package/dist/_chunks/libs/typebox.mjs +0 -2
- package/dist/_chunks/mcp-answers.d.mts +52 -0
- package/dist/_chunks/mcp-answers.mjs +125 -9
- package/dist/_chunks/questions.mjs +93 -0
- package/dist/_chunks/src.mjs +78 -27
- package/dist/_chunks/updates.mjs +131 -2
- package/dist/ai.d.mts +4 -4
- package/dist/ai.mjs +12 -3
- package/dist/cli.d.mts +14 -6
- package/dist/cli.mjs +145 -21
- package/dist/h3.d.mts +3 -2
- package/dist/h3.mjs +15 -6
- package/dist/index.d.mts +2 -2
- package/dist/mcp.d.mts +8 -55
- package/dist/mcp.mjs +11 -6
- package/dist/omp.d.mts +1 -2
- package/dist/omp.mjs +0 -2
- package/dist/pi.d.mts +1 -2
- package/dist/pi.mjs +1 -3
- package/dist/toolkit.d.mts +78 -0
- package/dist/toolkit.mjs +62 -0
- package/package.json +13 -3
- package/dist/_chunks/index.d.mts.map +0 -1
- package/dist/_chunks/libs/typebox.d.mts.map +0 -1
- package/dist/_chunks/libs/typebox.mjs.map +0 -1
- package/dist/_chunks/mcp-answers.mjs.map +0 -1
- package/dist/_chunks/src.mjs.map +0 -1
- package/dist/_chunks/updates.mjs.map +0 -1
- package/dist/ai.d.mts.map +0 -1
- package/dist/ai.mjs.map +0 -1
- package/dist/cli.d.mts.map +0 -1
- package/dist/cli.mjs.map +0 -1
- package/dist/h3.d.mts.map +0 -1
- package/dist/h3.mjs.map +0 -1
- package/dist/mcp.d.mts.map +0 -1
- package/dist/mcp.mjs.map +0 -1
- package/dist/omp.d.mts.map +0 -1
- package/dist/omp.mjs.map +0 -1
- package/dist/pi.d.mts.map +0 -1
- package/dist/pi.mjs.map +0 -1
package/dist/_chunks/updates.mjs
CHANGED
|
@@ -1,5 +1,136 @@
|
|
|
1
|
+
import { Check, Errors } from "./libs/typebox.mjs";
|
|
2
|
+
import { problemText, sanitizeLine } from "./src.mjs";
|
|
3
|
+
import { hostAsk } from "./questions.mjs";
|
|
4
|
+
const SKIP = Symbol("skip");
|
|
5
|
+
const CLOSED = Symbol("closed");
|
|
6
|
+
const SKIP_LABEL = "(skip)";
|
|
7
|
+
const DONE_LABEL = "Done";
|
|
8
|
+
function dialogAsk(host, signal) {
|
|
9
|
+
const ui = dialogsOf(host);
|
|
10
|
+
return ui ? hostAsk(async (question) => await fillForm(ui, question, signal)) : void 0;
|
|
11
|
+
}
|
|
12
|
+
function dialogsOf(host) {
|
|
13
|
+
if (typeof host !== "object" || host === null) return void 0;
|
|
14
|
+
const { hasUI, ui } = host;
|
|
15
|
+
if (hasUI !== true || typeof ui !== "object" || ui === null) return void 0;
|
|
16
|
+
const { select, input, notify } = ui;
|
|
17
|
+
return [
|
|
18
|
+
select,
|
|
19
|
+
input,
|
|
20
|
+
notify
|
|
21
|
+
].every((dialog) => typeof dialog === "function") ? ui : void 0;
|
|
22
|
+
}
|
|
23
|
+
async function fillForm(ui, question, signal) {
|
|
24
|
+
const keys = Object.keys(question.requested.properties);
|
|
25
|
+
const required = new Set(question.requested.required);
|
|
26
|
+
const content = Object.create(null);
|
|
27
|
+
for (const key of keys) {
|
|
28
|
+
const field = question.requested.properties[key] ?? {};
|
|
29
|
+
const value = await askField({
|
|
30
|
+
ui,
|
|
31
|
+
title: sanitizeLine(keys.length === 1 ? question.message : `${question.message}: ${labelOf(key, field)}`),
|
|
32
|
+
field,
|
|
33
|
+
optional: !required.has(key),
|
|
34
|
+
signal
|
|
35
|
+
}, question.schema.properties[key], labelOf(key, field));
|
|
36
|
+
if (value === CLOSED) return { action: "cancel" };
|
|
37
|
+
if (value !== SKIP) content[key] = value;
|
|
38
|
+
}
|
|
39
|
+
return {
|
|
40
|
+
action: "accept",
|
|
41
|
+
content
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
async function askField(prompt, schema, label) {
|
|
45
|
+
for (;;) {
|
|
46
|
+
const value = await promptOnce(prompt);
|
|
47
|
+
prompt.signal?.throwIfAborted();
|
|
48
|
+
if (value === CLOSED || value === SKIP || !schema || Check(schema, value)) return value;
|
|
49
|
+
const [failure] = Errors(schema, value);
|
|
50
|
+
const problem = failure ? problemText(failure.message, failure.params) : "not a value this field takes";
|
|
51
|
+
prompt.ui.notify(sanitizeLine(`${label}: ${problem}`), "warning");
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
async function promptOnce(prompt) {
|
|
55
|
+
const { field } = prompt;
|
|
56
|
+
if (field.type === "boolean") return await pick(prompt, [true, false], ["Yes", "No"]);
|
|
57
|
+
if (field.type === "array") return await toggle(prompt);
|
|
58
|
+
const [values, labels] = choicesOf(field);
|
|
59
|
+
return values.length > 0 ? await pick(prompt, values, labels) : await typeIn(prompt);
|
|
60
|
+
}
|
|
61
|
+
function choicesOf(field) {
|
|
62
|
+
if (Array.isArray(field.enum)) return [field.enum, field.enum.map(String)];
|
|
63
|
+
if (!Array.isArray(field.oneOf)) return [[], []];
|
|
64
|
+
const branches = field.oneOf.filter((branch) => typeof branch === "object" && branch !== null && "const" in branch);
|
|
65
|
+
return [branches.map((branch) => branch.const), branches.map((branch) => String(typeof branch.title === "string" ? branch.title : branch.const))];
|
|
66
|
+
}
|
|
67
|
+
async function pick(prompt, values, labels) {
|
|
68
|
+
const lines = labels.map(sanitizeLine);
|
|
69
|
+
const options = distinct(prompt.optional ? [...lines, SKIP_LABEL] : lines);
|
|
70
|
+
const chosen = await prompt.ui.select(prompt.title, options, signalOption(prompt));
|
|
71
|
+
if (chosen === void 0) return CLOSED;
|
|
72
|
+
const index = options.indexOf(chosen);
|
|
73
|
+
if (index >= 0 && index < values.length) return values[index];
|
|
74
|
+
return prompt.optional && index === values.length ? SKIP : chosen;
|
|
75
|
+
}
|
|
76
|
+
async function toggle(prompt) {
|
|
77
|
+
const values = prompt.field.items.enum.map(String);
|
|
78
|
+
const picked = new Set(Array.isArray(prompt.field.default) ? prompt.field.default : []);
|
|
79
|
+
const ends = prompt.optional ? [DONE_LABEL, SKIP_LABEL] : [DONE_LABEL];
|
|
80
|
+
const ticked = () => values.filter((value) => picked.has(value));
|
|
81
|
+
for (;;) {
|
|
82
|
+
const lines = toggleLines(values, (value) => picked.has(value));
|
|
83
|
+
const chosen = await prompt.ui.select(prompt.title, [...lines, ...ends], signalOption(prompt));
|
|
84
|
+
const ending = endOfToggle(chosen, prompt.optional, ticked);
|
|
85
|
+
if (ending !== void 0) return ending;
|
|
86
|
+
const value = values[lines.indexOf(chosen ?? "")];
|
|
87
|
+
if (value !== void 0 && !picked.delete(value)) picked.add(value);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
function endOfToggle(chosen, optional, ticked) {
|
|
91
|
+
if (chosen === void 0) return CLOSED;
|
|
92
|
+
if (chosen === DONE_LABEL) return ticked();
|
|
93
|
+
return optional && chosen === SKIP_LABEL ? SKIP : void 0;
|
|
94
|
+
}
|
|
95
|
+
function toggleLines(values, isPicked) {
|
|
96
|
+
return distinct(values.map((value) => `${isPicked(value) ? "[x]" : "[ ]"} ${sanitizeLine(value)}`));
|
|
97
|
+
}
|
|
98
|
+
async function typeIn(prompt) {
|
|
99
|
+
const { field } = prompt;
|
|
100
|
+
const text = await prompt.ui.input(prompt.title, hintOf(field), signalOption(prompt));
|
|
101
|
+
if (text === void 0) return CLOSED;
|
|
102
|
+
if (text === "" && field.default !== void 0) return field.default;
|
|
103
|
+
if (text === "" && prompt.optional) return SKIP;
|
|
104
|
+
return field.type === "number" || field.type === "integer" ? decimal(text) : text;
|
|
105
|
+
}
|
|
106
|
+
function hintOf(field) {
|
|
107
|
+
const hint = typeof field.description === "string" ? field.description : field.default;
|
|
108
|
+
return hint === void 0 ? void 0 : sanitizeLine(hint);
|
|
109
|
+
}
|
|
110
|
+
function distinct(lines) {
|
|
111
|
+
const seen = /* @__PURE__ */ new Set();
|
|
112
|
+
return lines.map((line) => {
|
|
113
|
+
let label = line;
|
|
114
|
+
for (let count = 2; seen.has(label); count++) label = `${line} (${count})`;
|
|
115
|
+
seen.add(label);
|
|
116
|
+
return label;
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
const DECIMAL = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i;
|
|
120
|
+
function decimal(text) {
|
|
121
|
+
const trimmed = text.trim();
|
|
122
|
+
return DECIMAL.test(trimmed) ? Number(trimmed) : text;
|
|
123
|
+
}
|
|
124
|
+
function labelOf(key, field) {
|
|
125
|
+
return typeof field.title === "string" ? field.title : key;
|
|
126
|
+
}
|
|
127
|
+
function signalOption(prompt) {
|
|
128
|
+
return prompt.signal ? { signal: prompt.signal } : {};
|
|
129
|
+
}
|
|
1
130
|
function hostContext(signal, onUpdate, host) {
|
|
131
|
+
const ask = dialogAsk(host, signal);
|
|
2
132
|
return {
|
|
133
|
+
...ask ? { ask } : {},
|
|
3
134
|
...signal ? { signal } : {},
|
|
4
135
|
...host === void 0 ? {} : { host },
|
|
5
136
|
...onUpdate ? { progress: (text) => onUpdate({
|
|
@@ -12,5 +143,3 @@ function hostContext(signal, onUpdate, host) {
|
|
|
12
143
|
};
|
|
13
144
|
}
|
|
14
145
|
export { hostContext };
|
|
15
|
-
|
|
16
|
-
//# sourceMappingURL=updates.mjs.map
|
package/dist/ai.d.mts
CHANGED
|
@@ -3,7 +3,7 @@ import { ToolDefinition } from "./_chunks/index.mjs";
|
|
|
3
3
|
import { Tool } from "ai";
|
|
4
4
|
/**
|
|
5
5
|
* What an AI SDK tool returns: the executor's details with the text MCP
|
|
6
|
-
* clients read.
|
|
6
|
+
* clients read. Your code gets the whole object, the model reads only `text`.
|
|
7
7
|
*/
|
|
8
8
|
export type AiToolOutput<Details> = (Details extends object ? Details : {
|
|
9
9
|
details: Details;
|
|
@@ -14,7 +14,8 @@ export type AiToolOutput<Details> = (Details extends object ? Details : {
|
|
|
14
14
|
* Converts one tool, keeping its input and details types.
|
|
15
15
|
*
|
|
16
16
|
* A result with `isError` throws its text, which the AI SDK reports to the
|
|
17
|
-
* model as a tool error, the same as an executor that throws.
|
|
17
|
+
* model as a tool error, the same as an executor that throws. The model reads
|
|
18
|
+
* `text` alone, as on every other host, not the details spelled out a second time.
|
|
18
19
|
*
|
|
19
20
|
* @param definition - Tool to convert.
|
|
20
21
|
* @returns {Tool} AI SDK tool.
|
|
@@ -27,5 +28,4 @@ export declare function toAiTool<Input extends TObject, Details>(definition: Too
|
|
|
27
28
|
* @returns {Record<string, Tool>} AI SDK tools.
|
|
28
29
|
* @throws {ToolDefinitionError} When two tools share a name.
|
|
29
30
|
*/
|
|
30
|
-
export declare function toAiTools(tools: readonly ToolDefinition[]): Record<string, Tool>;
|
|
31
|
-
//# sourceMappingURL=ai.d.mts.map
|
|
31
|
+
export declare function toAiTools(tools: readonly ToolDefinition[]): Record<string, Tool>;
|
package/dist/ai.mjs
CHANGED
|
@@ -28,13 +28,22 @@ function toAiTool(definition) {
|
|
|
28
28
|
...details,
|
|
29
29
|
text
|
|
30
30
|
};
|
|
31
|
-
}
|
|
31
|
+
},
|
|
32
|
+
toModelOutput: ({ output }) => modelOutput(output)
|
|
32
33
|
});
|
|
33
34
|
}
|
|
35
|
+
function modelOutput(output) {
|
|
36
|
+
const text = typeof output === "object" && output !== null ? output.text : void 0;
|
|
37
|
+
return typeof text === "string" && text !== "" ? {
|
|
38
|
+
type: "text",
|
|
39
|
+
value: text
|
|
40
|
+
} : {
|
|
41
|
+
type: "json",
|
|
42
|
+
value: output
|
|
43
|
+
};
|
|
44
|
+
}
|
|
34
45
|
function toAiTools(tools) {
|
|
35
46
|
indexTools(tools);
|
|
36
47
|
return Object.fromEntries(tools.map((definition) => [definition.name, toAiTool(definition)]));
|
|
37
48
|
}
|
|
38
49
|
export { toAiTool, toAiTools };
|
|
39
|
-
|
|
40
|
-
//# sourceMappingURL=ai.mjs.map
|
package/dist/cli.d.mts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { ToolDefinition } from "./_chunks/index.mjs";
|
|
2
|
+
import { McpServerInfo } from "./_chunks/mcp-answers.mjs";
|
|
2
3
|
export interface CliOptions {
|
|
3
4
|
/** Executable name, also the MCP server name. */
|
|
4
5
|
readonly name: string;
|
|
@@ -11,20 +12,28 @@ export interface CliOptions {
|
|
|
11
12
|
* a generated command, `mcp` included, takes its place. Bytes are the
|
|
12
13
|
* command's own business: it reads `-` from stdin itself in `execute`, and
|
|
13
14
|
* writes to stdout itself, answering with no content and `cli.json: false`.
|
|
15
|
+
* A command that prints rows as they land reads `--json` off its {@link CliHost},
|
|
16
|
+
* and leaves `progress` alone: on a terminal its line would sit in front of the rows.
|
|
14
17
|
*/
|
|
15
18
|
readonly commands?: readonly ToolDefinition[];
|
|
16
19
|
/** Command for an empty command line. */
|
|
17
20
|
readonly default?: string;
|
|
18
21
|
/** Command for a first word that names no command: `hashes sha256 x` runs `hashes hash sha256 x`. */
|
|
19
22
|
readonly fallback?: string;
|
|
20
|
-
/** Adds `mcp
|
|
21
|
-
readonly mcp?: boolean;
|
|
23
|
+
/** Adds `mcp` over stdio, named by the CLI on `true` or by the server info it's handed. */
|
|
24
|
+
readonly mcp?: boolean | McpServerInfo;
|
|
22
25
|
/**
|
|
23
26
|
* Errors the package throws on purpose. They print as one line with exit
|
|
24
27
|
* code 1; any other error keeps its stack trace.
|
|
25
28
|
*/
|
|
26
29
|
readonly expected?: (error: unknown) => boolean;
|
|
27
30
|
}
|
|
31
|
+
/** What a CLI command finds in `host`: narrow to it and look at `json` before writing a byte. */
|
|
32
|
+
export interface CliHost {
|
|
33
|
+
readonly cli: true;
|
|
34
|
+
/** `--json` was given, so the details are the answer and stdout stays theirs. */
|
|
35
|
+
readonly json: boolean;
|
|
36
|
+
}
|
|
28
37
|
/**
|
|
29
38
|
* @param tool - Tool to name.
|
|
30
39
|
* @returns {string} The hinted command, or the tool name without its package prefix, in kebab case.
|
|
@@ -56,11 +65,10 @@ export declare function createCli(options: CliOptions): Cli;
|
|
|
56
65
|
*/
|
|
57
66
|
export declare function normalizeArgv(options: CliOptions, argv: readonly string[]): string[];
|
|
58
67
|
/**
|
|
59
|
-
* Runs the CLI on `process.argv`. The CLI writes no colors
|
|
60
|
-
*
|
|
68
|
+
* Runs the CLI on `process.argv`. The CLI writes no colors; a terminal on
|
|
69
|
+
* stderr only gets the progress line, which never reaches a pipe.
|
|
61
70
|
*
|
|
62
71
|
* @param options - CLI options.
|
|
63
72
|
* @param argv - Words after the executable and script.
|
|
64
73
|
*/
|
|
65
|
-
export declare function runCli(options: CliOptions, argv?: readonly string[]): Promise<void>;
|
|
66
|
-
//# sourceMappingURL=cli.d.mts.map
|
|
74
|
+
export declare function runCli(options: CliOptions, argv?: readonly string[]): Promise<void>;
|
package/dist/cli.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Check } from "./_chunks/libs/typebox.mjs";
|
|
2
|
-
import { ToolDefinitionError, ToolInputError, indexTools, invokeTool, resultText, sanitizeLine, sanitizeText } from "./_chunks/src.mjs";
|
|
2
|
+
import { ToolDefinitionError, ToolInputError, indexTools, invokeTool, resultText, sanitizeLine, sanitizeText, validateInput } from "./_chunks/src.mjs";
|
|
3
3
|
import { readFileSync } from "node:fs";
|
|
4
4
|
import { parseArgs } from "node:util";
|
|
5
5
|
const FLAG_WORD = /^[a-z0-9][a-z0-9.-]*$/;
|
|
@@ -36,29 +36,47 @@ function fieldKind(schema) {
|
|
|
36
36
|
if ((Array.isArray(schema.anyOf) ? schema.anyOf : []).some((branch) => fieldKind(branch) === "json")) return "json";
|
|
37
37
|
return TYPE_KINDS.get(schema.type) ?? "string";
|
|
38
38
|
}
|
|
39
|
+
function textItems(schema) {
|
|
40
|
+
const { items } = schema;
|
|
41
|
+
if (schema.type !== "array" || typeof items !== "object" || items === null) return void 0;
|
|
42
|
+
if (Array.isArray(items)) return void 0;
|
|
43
|
+
return unionBranches(items).every(takesText) ? items : void 0;
|
|
44
|
+
}
|
|
45
|
+
function takesText(branch) {
|
|
46
|
+
if (branch.type === "string" || typeof branch.const === "string") return true;
|
|
47
|
+
return Array.isArray(branch.enum) && branch.enum.every((value) => typeof value === "string");
|
|
48
|
+
}
|
|
39
49
|
function cliHints(tool) {
|
|
40
50
|
const cli = tool.cli ?? {};
|
|
41
51
|
const rest = cli.rest === void 0 ? [] : [cli.rest];
|
|
42
52
|
const hints = {
|
|
43
53
|
positional: [...cli.positional ?? [], ...rest],
|
|
54
|
+
plain: cli.plain ?? [],
|
|
44
55
|
rest,
|
|
45
56
|
short: cli.short ?? {},
|
|
46
57
|
stdin: cli.stdin ?? []
|
|
47
58
|
};
|
|
48
59
|
const properties = tool.input.properties;
|
|
49
|
-
|
|
60
|
+
const named = [
|
|
50
61
|
...hints.positional,
|
|
62
|
+
...hints.plain,
|
|
51
63
|
...Object.keys(hints.short),
|
|
52
64
|
...hints.stdin
|
|
53
|
-
]
|
|
65
|
+
];
|
|
66
|
+
for (const key of named) if (!Object.hasOwn(properties, key)) throw new ToolDefinitionError(`${tool.name}: cli hint names unknown property ${key}`);
|
|
67
|
+
assertPositionals(tool, hints);
|
|
68
|
+
return hints;
|
|
69
|
+
}
|
|
70
|
+
function assertPositionals(tool, hints) {
|
|
54
71
|
const { positional } = hints;
|
|
55
72
|
const repeated = positional.find((key, index) => positional.indexOf(key) !== index);
|
|
56
73
|
if (repeated !== void 0) throw new ToolDefinitionError(`${tool.name}: cli hint lists positional ${repeated} twice`);
|
|
57
|
-
|
|
74
|
+
const flag = hints.plain.find((key) => !positional.includes(key));
|
|
75
|
+
if (flag !== void 0) throw new ToolDefinitionError(`${tool.name}: plain property ${flag} must be positional`);
|
|
58
76
|
}
|
|
59
77
|
function toolFields(tool) {
|
|
60
78
|
const properties = tool.input.properties;
|
|
61
|
-
const { positional, rest, short, stdin } = cliHints(tool);
|
|
79
|
+
const { positional, plain, rest, short, stdin } = cliHints(tool);
|
|
62
80
|
const keys = [...positional, ...Object.keys(properties).filter((key) => !positional.includes(key))];
|
|
63
81
|
const required = tool.input.required ?? [];
|
|
64
82
|
const flags = /* @__PURE__ */ new Set();
|
|
@@ -70,7 +88,9 @@ function toolFields(tool) {
|
|
|
70
88
|
flag: flagName(key),
|
|
71
89
|
kind: fieldKind(properties[key] ?? {}),
|
|
72
90
|
positional: positional.includes(key),
|
|
91
|
+
plain: plain.includes(key),
|
|
73
92
|
rest: rest.includes(key),
|
|
93
|
+
restItems: rest.includes(key) ? textItems(properties[key] ?? {}) : void 0,
|
|
74
94
|
short: Object.hasOwn(short, key) ? short[key] : void 0,
|
|
75
95
|
stdin: stdin.includes(key)
|
|
76
96
|
};
|
|
@@ -92,8 +112,11 @@ function assertField(tool, field, taken) {
|
|
|
92
112
|
if (!field.positional) assertFlag(tool, field);
|
|
93
113
|
if (taken) throw new ToolDefinitionError(`${tool.name}: two properties take the flag --${field.flag}`);
|
|
94
114
|
if (field.positional && field.kind === "boolean") throw new ToolDefinitionError(`${tool.name}: boolean property ${field.key} cannot be positional`);
|
|
115
|
+
assertTextHints(tool, field);
|
|
116
|
+
}
|
|
117
|
+
function assertTextHints(tool, field) {
|
|
95
118
|
if (field.stdin && field.kind !== "string") throw new ToolDefinitionError(`${tool.name}: stdin property ${field.key} must be a string`);
|
|
96
|
-
if (field.rest && !TEXT_KINDS.has(field.kind)) throw new ToolDefinitionError(`${tool.name}: rest property ${field.key} must be a string`);
|
|
119
|
+
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`);
|
|
97
120
|
}
|
|
98
121
|
function assertShort(tool, field) {
|
|
99
122
|
if (field.short === void 0) return;
|
|
@@ -156,8 +179,10 @@ function parseWords(rawArgs, fields, takesJson) {
|
|
|
156
179
|
allowNegative: true,
|
|
157
180
|
tokens: true
|
|
158
181
|
});
|
|
182
|
+
const ordered = inLineOrder(tokens, origins, texts);
|
|
183
|
+
const positionals = ordered.map(([, word]) => word);
|
|
159
184
|
const values = emptyRecord();
|
|
160
|
-
const errors = refused.map((word) => unknownOption(options, word));
|
|
185
|
+
const errors = [...landedInPlain(fields, ordered, texts), ...refused].map((word) => unknownOption(options, word));
|
|
161
186
|
const flags = /* @__PURE__ */ new Set();
|
|
162
187
|
for (const token of tokens) {
|
|
163
188
|
if (token.kind !== "option") continue;
|
|
@@ -166,7 +191,6 @@ function parseWords(rawArgs, fields, takesJson) {
|
|
|
166
191
|
else if ("flag" in read) flags.add(read.flag);
|
|
167
192
|
else values[read.key] = read.value;
|
|
168
193
|
}
|
|
169
|
-
const positionals = inLineOrder(tokens, origins, texts);
|
|
170
194
|
return {
|
|
171
195
|
values: Object.assign(values, positionalValues(fields, positionals)),
|
|
172
196
|
json: flags.has("json"),
|
|
@@ -217,7 +241,15 @@ function wordKind(word, options) {
|
|
|
217
241
|
}
|
|
218
242
|
function inLineOrder(tokens, origins, texts) {
|
|
219
243
|
const read = tokens.flatMap((token) => token.kind === "positional" ? [[origins[token.index] ?? 0, token.value ?? ""]] : []);
|
|
220
|
-
return [...texts, ...read].toSorted(([a], [b]) => a - b)
|
|
244
|
+
return [...texts, ...read].toSorted(([a], [b]) => a - b);
|
|
245
|
+
}
|
|
246
|
+
function landedInPlain(fields, ordered, texts) {
|
|
247
|
+
const takes = fields.filter((field) => field.positional);
|
|
248
|
+
const dashed = new Set(texts.map(([index]) => index));
|
|
249
|
+
return ordered.flatMap(([index, word], slot) => {
|
|
250
|
+
const field = takes[Math.min(slot, takes.length - 1)];
|
|
251
|
+
return dashed.has(index) && field?.plain === true ? [word] : [];
|
|
252
|
+
});
|
|
221
253
|
}
|
|
222
254
|
function longField(spelled, options) {
|
|
223
255
|
const [name = ""] = spelled.split("=", 1);
|
|
@@ -238,6 +270,7 @@ function positionalValues(fields, positionals) {
|
|
|
238
270
|
const takes = fields.filter((field) => field.positional);
|
|
239
271
|
return Object.assign(emptyRecord(), Object.fromEntries(takes.flatMap((field, index) => {
|
|
240
272
|
const words = field.rest ? positionals.slice(index) : positionals.slice(index, index + 1);
|
|
273
|
+
if (field.restItems !== void 0) return words.length > 0 || field.required ? [[field.key, words]] : [];
|
|
241
274
|
return words.length === 0 ? [] : [[field.key, words.join(" ")]];
|
|
242
275
|
})));
|
|
243
276
|
}
|
|
@@ -355,18 +388,46 @@ function fieldValue(field, raw) {
|
|
|
355
388
|
function toolInput(fields, values) {
|
|
356
389
|
const input = emptyRecord();
|
|
357
390
|
const fromStdin = fields.filter((field) => field.stdin && values[field.key] === "-");
|
|
358
|
-
if (fromStdin.length > 1) throw new ToolInputError([`Invalid arguments: stdin can feed one argument, not ${fromStdin.map(
|
|
391
|
+
if (fromStdin.length > 1) throw new ToolInputError([`Invalid arguments: stdin can feed one argument, not ${fromStdin.map(fieldWord).join(" and ")}`]);
|
|
359
392
|
const errors = [];
|
|
360
393
|
for (const field of fields) {
|
|
361
394
|
const raw = values[field.key];
|
|
362
395
|
if (raw === void 0) continue;
|
|
363
|
-
const read = fieldValue(field, raw);
|
|
364
|
-
if ("error" in read) errors.push(`Invalid arguments at
|
|
396
|
+
const read = typeof raw === "object" ? { value: raw.map((word) => wordValue(field.restItems ?? {}, word)) } : fieldValue(field, raw);
|
|
397
|
+
if ("error" in read) errors.push(`Invalid arguments at ${fieldWord(field)}: ${read.error}`);
|
|
365
398
|
else input[field.key] = read.value;
|
|
366
399
|
}
|
|
367
400
|
if (errors.length > 0) throw new ToolInputError(errors);
|
|
368
401
|
return input;
|
|
369
402
|
}
|
|
403
|
+
function fieldWord(field) {
|
|
404
|
+
if (!field.positional) return `--${field.flag}`;
|
|
405
|
+
const name = `${field.flag.toUpperCase()}${field.rest ? "..." : ""}`;
|
|
406
|
+
return field.required ? `<${name}>` : `[${name}]`;
|
|
407
|
+
}
|
|
408
|
+
function placeIn(field, inner) {
|
|
409
|
+
if (inner.length === 0) return fieldWord(field);
|
|
410
|
+
const [index = ""] = inner;
|
|
411
|
+
if (field.restItems !== void 0 && inner.length === 1 && /^\d+$/.test(index)) return `word ${Number(index) + 1} of ${fieldWord(field)}`;
|
|
412
|
+
return `/${inner.join("/")} of ${fieldWord(field)}`;
|
|
413
|
+
}
|
|
414
|
+
function cliIssueLines(fields, issue) {
|
|
415
|
+
const byKey = (key) => fields.find((field) => field.key === key);
|
|
416
|
+
if (issue.at === "" && issue.missing !== void 0) return issue.missing.map((key) => {
|
|
417
|
+
const field = byKey(key);
|
|
418
|
+
return `Invalid arguments: missing ${field ? fieldWord(field) : JSON.stringify(key)}`;
|
|
419
|
+
});
|
|
420
|
+
const [, first, ...inner] = issue.at.split("/");
|
|
421
|
+
const field = first === void 0 ? void 0 : byKey(first.replaceAll("~1", "/").replaceAll("~0", "~"));
|
|
422
|
+
if (field === void 0) return [issue.line];
|
|
423
|
+
return [`Invalid arguments at ${placeIn(field, inner)}: ${issue.problem}`];
|
|
424
|
+
}
|
|
425
|
+
function checkInput(tool, fields, input) {
|
|
426
|
+
const checked = validateInput(tool, input);
|
|
427
|
+
if (checked.ok) return;
|
|
428
|
+
const lines = checked.issues.flatMap((issue) => cliIssueLines(fields, issue));
|
|
429
|
+
throw new ToolInputError(lines.length > 0 ? [...new Set(lines)] : checked.lines, checked.issues);
|
|
430
|
+
}
|
|
370
431
|
function writeLine(stream, text) {
|
|
371
432
|
process[stream].write(text.endsWith("\n") ? text : `${text}\n`);
|
|
372
433
|
}
|
|
@@ -383,6 +444,59 @@ function detailsJson(details) {
|
|
|
383
444
|
return (JSON.stringify(details, (_key, value) => typeof value === "bigint" ? value.toString() : value, 2) ?? "null").replaceAll(JSON_FORGING, (character) => `\\u${(character.codePointAt(0) ?? 0).toString(16).padStart(4, "0")}`);
|
|
384
445
|
}
|
|
385
446
|
const JSON_FORGING = /[\u007F-\u009F\u061C\u200E\u200F\u2028\u2029\u202A-\u202E\u2066-\u206F]/g;
|
|
447
|
+
const GRAPHEMES = new Intl.Segmenter();
|
|
448
|
+
const WIDE = /^(?:\p{Extended_Pictographic}|[\u1100-\u115F\u231A\u231B\u2329\u232A\u2630-\u2637\u268A-\u268F\u2E80-\u303E\u3041-\u33FF\u3400-\u4DFF\u4E00-\u9FFF\uA000-\uA4CF\uA960-\uA97F\uAC00-\uD7A3\uF900-\uFAFF\uFE10-\uFE19\uFE30-\uFE6F\uFF00-\uFF60\uFFE0-\uFFE6\u{16FE0}-\u{18DFF}\u{1AFF0}-\u{1B2FF}\u{1D15E}-\u{1D164}\u{1D1BB}-\u{1D1C0}\u{1D300}-\u{1D376}\u{1F000}-\u{1FAFF}\u{20000}-\u{3FFFD}])$/u;
|
|
449
|
+
const EMOJI = /^\p{RGI_Emoji}$/v;
|
|
450
|
+
const ZERO_WIDTH = /^[\p{Mn}\p{Me}]$/u;
|
|
451
|
+
function pointCells(point) {
|
|
452
|
+
if (WIDE.test(point)) return 2;
|
|
453
|
+
return ZERO_WIDTH.test(point) ? 0 : 1;
|
|
454
|
+
}
|
|
455
|
+
function graphemeCells(grapheme) {
|
|
456
|
+
let size = 0;
|
|
457
|
+
for (const point of grapheme.normalize("NFC")) size += pointCells(point);
|
|
458
|
+
return Math.max(EMOJI.test(grapheme) ? 2 : 1, size);
|
|
459
|
+
}
|
|
460
|
+
function fitLine(text, room) {
|
|
461
|
+
let fitted = "";
|
|
462
|
+
let used = 0;
|
|
463
|
+
for (const { segment } of GRAPHEMES.segment(text)) {
|
|
464
|
+
const size = graphemeCells(segment);
|
|
465
|
+
if (used + size > room) break;
|
|
466
|
+
fitted += segment;
|
|
467
|
+
used += size;
|
|
468
|
+
}
|
|
469
|
+
return {
|
|
470
|
+
text: fitted,
|
|
471
|
+
cells: used
|
|
472
|
+
};
|
|
473
|
+
}
|
|
474
|
+
function progressText(message, amount) {
|
|
475
|
+
const { progress, total } = amount ?? { progress: NaN };
|
|
476
|
+
if (!Number.isFinite(progress) || !Number.isFinite(total)) return message;
|
|
477
|
+
return `${message} (${progress}/${total})`.trim();
|
|
478
|
+
}
|
|
479
|
+
function progressLine() {
|
|
480
|
+
const stream = process.stderr;
|
|
481
|
+
if (stream.isTTY !== true) return {
|
|
482
|
+
context: {},
|
|
483
|
+
wipe() {}
|
|
484
|
+
};
|
|
485
|
+
let width = 0;
|
|
486
|
+
const wipe = () => {
|
|
487
|
+
if (width > 0) stream.write(`\r${" ".repeat(width)}\r`);
|
|
488
|
+
width = 0;
|
|
489
|
+
};
|
|
490
|
+
return {
|
|
491
|
+
context: { progress(message, amount) {
|
|
492
|
+
const line = fitLine(progressText(message, amount), Math.max(1, (stream.columns || 80) - 1));
|
|
493
|
+
wipe();
|
|
494
|
+
stream.write(line.text);
|
|
495
|
+
width = line.cells;
|
|
496
|
+
} },
|
|
497
|
+
wipe
|
|
498
|
+
};
|
|
499
|
+
}
|
|
386
500
|
function toolCommand(tool) {
|
|
387
501
|
const fields = toolFields(tool);
|
|
388
502
|
const [summary = tool.title] = tool.description.split(/(?<=[.!?])\s/, 1);
|
|
@@ -393,7 +507,22 @@ function toolCommand(tool) {
|
|
|
393
507
|
fields,
|
|
394
508
|
json: tool.cli?.json !== false,
|
|
395
509
|
async run(words) {
|
|
396
|
-
const
|
|
510
|
+
const host = {
|
|
511
|
+
cli: true,
|
|
512
|
+
json: words.json
|
|
513
|
+
};
|
|
514
|
+
const line = progressLine();
|
|
515
|
+
let result;
|
|
516
|
+
try {
|
|
517
|
+
const input = toolInput(fields, words.values);
|
|
518
|
+
checkInput(tool, fields, input);
|
|
519
|
+
result = await invokeTool(tool, input, {
|
|
520
|
+
...line.context,
|
|
521
|
+
host
|
|
522
|
+
});
|
|
523
|
+
} finally {
|
|
524
|
+
line.wipe();
|
|
525
|
+
}
|
|
397
526
|
if (result.isError === true) {
|
|
398
527
|
writeLine("stderr", sanitizeText(resultText(result)));
|
|
399
528
|
process.exitCode = 1;
|
|
@@ -415,7 +544,7 @@ function mcpCommand(options) {
|
|
|
415
544
|
json: false,
|
|
416
545
|
async run() {
|
|
417
546
|
const [{ createMcpServer }, { StdioServerTransport }] = await Promise.all([import("./mcp.mjs"), import("@modelcontextprotocol/server/stdio")]);
|
|
418
|
-
await createMcpServer(options, options.tools).connect(new StdioServerTransport());
|
|
547
|
+
await createMcpServer(typeof options.mcp === "object" ? options.mcp : options, options.tools).connect(new StdioServerTransport());
|
|
419
548
|
}
|
|
420
549
|
};
|
|
421
550
|
}
|
|
@@ -426,7 +555,7 @@ function commandTools(options) {
|
|
|
426
555
|
return [...listed, ...own.filter((command) => !listed.includes(command))];
|
|
427
556
|
}
|
|
428
557
|
function builtInMcp(options) {
|
|
429
|
-
return options.mcp
|
|
558
|
+
return options.mcp !== void 0 && options.mcp !== false && !(options.commands ?? []).some((command) => commandName(command) === "mcp");
|
|
430
559
|
}
|
|
431
560
|
function commandWords(options) {
|
|
432
561
|
return [...commandTools(options).flatMap((tool) => [commandName(tool), ...tool.cli?.aliases ?? []]), ...builtInMcp(options) ? ["mcp"] : []];
|
|
@@ -496,10 +625,7 @@ function commandUsage(options, command) {
|
|
|
496
625
|
const positional = command.fields.filter((field) => field.positional);
|
|
497
626
|
const flags = command.fields.filter((field) => !field.positional);
|
|
498
627
|
const takesOptions = flags.length > 0 || command.json;
|
|
499
|
-
const words = positional.map(
|
|
500
|
-
const name = `${field.flag.toUpperCase()}${field.rest ? "..." : ""}`;
|
|
501
|
-
return field.required ? `<${name}>` : `[${name}]`;
|
|
502
|
-
});
|
|
628
|
+
const words = positional.map(fieldWord);
|
|
503
629
|
const rows = [
|
|
504
630
|
...flags.map((field) => [`${field.short === void 0 ? "" : `-${field.short}, `}${optionSpelling(field)}`, fieldDescription(field)]),
|
|
505
631
|
...command.json ? [["--json", "Print the details as JSON instead of the text"]] : [],
|
|
@@ -536,5 +662,3 @@ async function runCli(options, argv = process.argv.slice(2)) {
|
|
|
536
662
|
await createCli(options).run(argv);
|
|
537
663
|
}
|
|
538
664
|
export { commandName, createCli, normalizeArgv, runCli };
|
|
539
|
-
|
|
540
|
-
//# sourceMappingURL=cli.mjs.map
|
package/dist/h3.d.mts
CHANGED
|
@@ -12,6 +12,8 @@ export type H3Tool = ToolDefinition<JsonSchema>;
|
|
|
12
12
|
* instead. An unknown name never reaches a handler: h3-mcp answers it itself
|
|
13
13
|
* with a JSON-RPC error.
|
|
14
14
|
*
|
|
15
|
+
* `ask` reaches a client with `elicitation` on the 2026 revision only: h3-mcp has no 2025 shim.
|
|
16
|
+
*
|
|
15
17
|
* Imports only types from h3-mcp, so the adapter loads neither h3-mcp nor the MCP SDK.
|
|
16
18
|
*
|
|
17
19
|
* @param info - Server info; `name` is the word in the message for an unknown tool.
|
|
@@ -21,5 +23,4 @@ export type H3Tool = ToolDefinition<JsonSchema>;
|
|
|
21
23
|
*/
|
|
22
24
|
export declare function toH3Tools(info: {
|
|
23
25
|
readonly name: string;
|
|
24
|
-
}, tools: readonly ToolDefinition$1[]): H3Tool[];
|
|
25
|
-
//# sourceMappingURL=h3.d.mts.map
|
|
26
|
+
}, tools: readonly ToolDefinition$1[]): H3Tool[];
|
package/dist/h3.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import "./_chunks/src.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { callAsking, canAsk, listTools, 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,
|
|
@@ -7,17 +7,26 @@ function toH3Tools(info, tools) {
|
|
|
7
7
|
description: entry.description,
|
|
8
8
|
...entry.icons === void 0 ? {} : { icons: entry.icons },
|
|
9
9
|
inputSchema: entry.inputSchema,
|
|
10
|
+
...entry.outputSchema === void 0 ? {} : { outputSchema: entry.outputSchema },
|
|
10
11
|
annotations: entry.annotations,
|
|
11
|
-
|
|
12
|
+
...entry._meta === void 0 ? {} : { _meta: entry._meta },
|
|
13
|
+
handler: async (args, event) => {
|
|
12
14
|
const mcp = event.context.mcp;
|
|
15
|
+
const round = roundOf(mcp);
|
|
16
|
+
const progress = mcp?.progressToken === void 0 ? void 0 : mcp.progress;
|
|
13
17
|
const context = {
|
|
14
18
|
signal: mcp?.signal,
|
|
15
|
-
...
|
|
19
|
+
...progress === void 0 ? {} : { progress: numbered(progress) }
|
|
16
20
|
};
|
|
17
|
-
return
|
|
21
|
+
return await callAsking(info, tools, entry.name, args, context, round);
|
|
18
22
|
}
|
|
19
23
|
}));
|
|
20
24
|
}
|
|
25
|
+
function roundOf(mcp) {
|
|
26
|
+
if (mcp?.era !== "modern" || !canAsk(mcp.clientCapabilities)) return void 0;
|
|
27
|
+
return questionRound(mcp.inputResponses, mcp.requestState);
|
|
28
|
+
}
|
|
29
|
+
function numbered(send) {
|
|
30
|
+
return progressSteps(({ progress, total, message }) => send(progress, total, message));
|
|
31
|
+
}
|
|
21
32
|
export { toH3Tools };
|
|
22
|
-
|
|
23
|
-
//# sourceMappingURL=h3.mjs.map
|