@agntn/tools 0.1.1 โ 0.2.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 +3 -1
- package/dist/_chunks/mcp-answers.mjs +60 -0
- package/dist/_chunks/mcp-answers.mjs.map +1 -0
- package/dist/_chunks/src.mjs +21 -2
- package/dist/_chunks/src.mjs.map +1 -1
- package/dist/_chunks/updates.mjs +15 -0
- package/dist/_chunks/updates.mjs.map +1 -0
- package/dist/ai.d.mts +1 -0
- package/dist/ai.d.mts.map +1 -1
- package/dist/ai.mjs +2 -1
- package/dist/ai.mjs.map +1 -1
- package/dist/cli.d.mts.map +1 -1
- package/dist/cli.mjs +1 -5
- package/dist/cli.mjs.map +1 -1
- package/dist/h3.d.mts +25 -0
- package/dist/h3.d.mts.map +1 -0
- package/dist/h3.mjs +22 -0
- package/dist/h3.mjs.map +1 -0
- package/dist/index.d.mts +12 -0
- package/dist/index.d.mts.map +1 -1
- package/dist/mcp.d.mts +26 -3
- package/dist/mcp.d.mts.map +1 -1
- package/dist/mcp.mjs +22 -41
- package/dist/mcp.mjs.map +1 -1
- package/dist/omp.d.mts +4 -1
- package/dist/omp.d.mts.map +1 -1
- package/dist/omp.mjs +18 -6
- package/dist/omp.mjs.map +1 -1
- package/dist/pi.d.mts +23 -4
- package/dist/pi.d.mts.map +1 -1
- package/dist/pi.mjs +39 -5
- package/dist/pi.mjs.map +1 -1
- package/package.json +13 -3
package/README.md
CHANGED
|
@@ -22,6 +22,7 @@ MCP wants an `inputSchema`. Pi wants `parameters` and a prompt snippet. OMP swap
|
|
|
22
22
|
- ๐งต **One line per error.** Newlines, escape codes and bidi tricks in echoed text get flattened. No forged lines.
|
|
23
23
|
- ๐ชค **The OMP TypeBox trap, defused.** TypeBox is bundled, so OMP has nothing left to rewrite behind your back.
|
|
24
24
|
- ๐งช **Schema rules at definition time.** An open object or a union of literals fails in `defineTool`. Not three weeks later in a model's hands.
|
|
25
|
+
- โณ **Progress that gets somewhere.** `progress?.("still at it")` turns into `onUpdate` in Pi and OMP and `notifications/progress` in MCP. A slow call stops looking like a dead one.
|
|
25
26
|
- โจ๏ธ **A CLI on the side.** `runCli` turns the same tools into commands, no CLI library needed. Flags come from the schema. A hint adds positionals and stdin.
|
|
26
27
|
- ๐ **Runs anywhere.** No `node:*` import in the core or the host adapters. The docs site runs them in a browser tab. The CLI is the one Node part, as a CLI should be.
|
|
27
28
|
|
|
@@ -31,7 +32,7 @@ MCP wants an `inputSchema`. Pi wants `parameters` and a prompt snippet. OMP swap
|
|
|
31
32
|
pnpm add @agntn/tools
|
|
32
33
|
```
|
|
33
34
|
|
|
34
|
-
Node.js
|
|
35
|
+
Node.js 26 or newer. Then add the hosts you serve. Each one is an optional peer.
|
|
35
36
|
|
|
36
37
|
## ๐ First call
|
|
37
38
|
|
|
@@ -86,6 +87,7 @@ The typo never reached `execute`. The model gets told what it did wrong and what
|
|
|
86
87
|
| Host | Adapter | Peer |
|
|
87
88
|
| ------ | ------------------------------------------ | --------------------------------- |
|
|
88
89
|
| MCP | `createMcpServer` from `@agntn/tools/mcp` | `@modelcontextprotocol/server` |
|
|
90
|
+
| H3 | `toH3Tools` from `@agntn/tools/h3` | `h3-mcp` |
|
|
89
91
|
| Pi | `registerPiTools` from `@agntn/tools/pi` | `@earendil-works/pi-coding-agent` |
|
|
90
92
|
| OMP | `registerOmpTools` from `@agntn/tools/omp` | `@oh-my-pi/pi-coding-agent` |
|
|
91
93
|
| AI SDK | `toAiTool` from `@agntn/tools/ai` | `ai` |
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { ToolInputError, indexTools, invokeTool, sanitizeLine, wireSchema } from "./src.mjs";
|
|
2
|
+
function toolAnnotations(tool) {
|
|
3
|
+
return {
|
|
4
|
+
title: tool.title,
|
|
5
|
+
readOnlyHint: tool.effect === "read",
|
|
6
|
+
destructiveHint: tool.effect === "destructive",
|
|
7
|
+
idempotentHint: tool.idempotent ?? tool.effect === "read",
|
|
8
|
+
openWorldHint: tool.openWorld ?? false
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
function errorResult(...lines) {
|
|
12
|
+
return {
|
|
13
|
+
content: [{
|
|
14
|
+
type: "text",
|
|
15
|
+
text: lines.map(sanitizeLine).join("\n")
|
|
16
|
+
}],
|
|
17
|
+
isError: true
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
function listTools(tools) {
|
|
21
|
+
indexTools(tools);
|
|
22
|
+
return tools.map((tool) => ({
|
|
23
|
+
name: tool.name,
|
|
24
|
+
title: tool.title,
|
|
25
|
+
description: tool.description,
|
|
26
|
+
inputSchema: wireSchema(tool),
|
|
27
|
+
annotations: toolAnnotations(tool)
|
|
28
|
+
}));
|
|
29
|
+
}
|
|
30
|
+
async function callTool(info, tools, name, args = {}, context = {}) {
|
|
31
|
+
const tool = tools.find((candidate) => candidate.name === name);
|
|
32
|
+
if (!tool) return errorResult(`Unknown ${info.name} tool: ${JSON.stringify(name)}`);
|
|
33
|
+
try {
|
|
34
|
+
const result = await invokeTool(tool, args, context);
|
|
35
|
+
return {
|
|
36
|
+
content: result.content,
|
|
37
|
+
...result.isError === void 0 ? {} : { isError: result.isError }
|
|
38
|
+
};
|
|
39
|
+
} catch (error) {
|
|
40
|
+
if (error instanceof ToolInputError) return errorResult(...error.lines);
|
|
41
|
+
return errorResult(`${tool.name} failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
function progressSteps(notify) {
|
|
45
|
+
let last;
|
|
46
|
+
return (message, amount) => {
|
|
47
|
+
const progress = amount?.progress ?? (last ?? 0) + 1;
|
|
48
|
+
if (!Number.isFinite(progress) || last !== void 0 && progress <= last) return;
|
|
49
|
+
last = progress;
|
|
50
|
+
const total = amount?.total;
|
|
51
|
+
notify({
|
|
52
|
+
progress,
|
|
53
|
+
...Number.isFinite(total) ? { total } : {},
|
|
54
|
+
message
|
|
55
|
+
});
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
export { callTool, errorResult, listTools, progressSteps, toolAnnotations };
|
|
59
|
+
|
|
60
|
+
//# sourceMappingURL=mcp-answers.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mcp-answers.mjs","names":[],"sources":["../../src/mcp-answers.ts"],"sourcesContent":["/**\n * What `tools/list` and `tools/call` answer, without the MCP SDK at runtime.\n *\n * Shared by the `Server` in `mcp.ts` and the h3-mcp adapter in `h3.ts`, so a\n * transport that brings its own JSON-RPC layer never loads the SDK.\n */\n\nimport type { CallToolResult, Tool, ToolAnnotations } from \"@modelcontextprotocol/server\";\n\nimport {\n indexTools,\n invokeTool,\n sanitizeLine,\n ToolInputError,\n wireSchema,\n type ToolCallContext,\n type ToolDefinition,\n} from \"./index.ts\";\n\nexport interface McpServerInfo {\n /** Server name, also used in the unknown-tool message. */\n readonly name: string;\n readonly version: string;\n /** Display name for clients that show one, such as `Forges`. */\n readonly title?: string;\n /** Project home a client can link to. */\n readonly websiteUrl?: string;\n}\n\n/**\n * Maps a tool's title and declared effect to MCP annotations. Claude Code reads its label here.\n *\n * @param tool - Tool to describe.\n * @returns {ToolAnnotations} Title and hints for the MCP client.\n */\nexport function toolAnnotations(tool: ToolDefinition): ToolAnnotations {\n return {\n title: tool.title,\n readOnlyHint: tool.effect === \"read\",\n destructiveHint: tool.effect === \"destructive\",\n idempotentHint: tool.idempotent ?? tool.effect === \"read\",\n openWorldHint: tool.openWorld ?? false,\n };\n}\n\n/**\n * Error result with every line-forging character replaced.\n *\n * The messages echo client-controlled values (a tool name, an argument) and\n * downstream error text, so they pass through here on every branch. Each line\n * is cleaned on its own, so only the breaks between the lines passed in\n * survive; a newline inside one line becomes a space.\n *\n * @param lines - Error lines.\n * @returns {CallToolResult} MCP error result.\n */\nexport function errorResult(...lines: readonly string[]): CallToolResult {\n return { content: [{ type: \"text\", text: lines.map(sanitizeLine).join(\"\\n\") }], isError: true };\n}\n\n/**\n * The entries `tools/list` answers with, in the order given.\n *\n * @param tools - Tools to list.\n * @returns {Tool[]} Name, title, description, schema and annotations of each tool.\n * @throws {ToolDefinitionError} When two tools share a name.\n */\nexport function listTools(tools: readonly ToolDefinition[]): Tool[] {\n indexTools(tools);\n return tools.map((tool) => ({\n name: tool.name,\n title: tool.title,\n description: tool.description,\n inputSchema: wireSchema(tool) as Tool[\"inputSchema\"],\n annotations: toolAnnotations(tool),\n }));\n}\n\n/**\n * Answers one call as `tools/call` does and never throws, so every transport gives the same text.\n *\n * @param info - Server info; `name` is the word in the message for an unknown tool.\n * @param tools - Tools to look the name up in.\n * @param name - Tool name as the client sent it.\n * @param args - Arguments as the client sent them; missing ones count as `{}`.\n * @param context - Context for this call, such as the request's abort signal.\n * @returns {Promise<CallToolResult>} The tool's text, or the sanitized error.\n */\nexport async function callTool(\n info: Pick<McpServerInfo, \"name\">,\n tools: readonly ToolDefinition[],\n name: string,\n args: unknown = {},\n context: ToolCallContext = {},\n): Promise<CallToolResult> {\n const tool = tools.find((candidate) => candidate.name === name);\n if (!tool) return errorResult(`Unknown ${info.name} tool: ${JSON.stringify(name)}`);\n\n try {\n const result = await invokeTool(tool, args, context);\n return {\n content: result.content,\n ...(result.isError === undefined ? {} : { isError: result.isError }),\n };\n } catch (error) {\n if (error instanceof ToolInputError) return errorResult(...error.lines);\n return errorResult(\n `${tool.name} failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n\n/** One `notifications/progress` without its token. */\nexport interface ProgressParams {\n readonly progress: number;\n readonly total?: number;\n readonly message: string;\n}\n\n/**\n * Numbers progress lines for MCP: a bare line counts one up, an amount that doesn't grow drops.\n *\n * @param notify - Sends one notification for the request.\n * @returns {NonNullable<ToolCallContext[\"progress\"]>} The callback for `execute`.\n */\nexport function progressSteps(\n notify: (params: ProgressParams) => void,\n): NonNullable<ToolCallContext[\"progress\"]> {\n let last: number | undefined;\n return (message, amount) => {\n const progress = amount?.progress ?? (last ?? 0) + 1;\n if (!Number.isFinite(progress) || (last !== undefined && progress <= last)) return;\n last = progress;\n const total = amount?.total;\n notify({ progress, ...(Number.isFinite(total) ? { total } : {}), message });\n };\n}\n"],"mappings":";;;;;;EAmCA,gBAAgB,KAAA,cAAuD,KAAA,WAAA;EACrE,eAAO,KAAA,aAAA;CACL;AACA;AAEA,SAAA,YAAgB,GAAK,OAAA;CACrB,OAAA;EACF,SAAA,CAAA;GACF,MAAA;;;;;;;;;;;EAaA,aAAgB,KAAA;EACd,aAAO,WAAA,IAAA;EAAE,aAAU,gBAAA,IAAA;CAAE,EAAA;AAAc;AAA6C,eAAS,SAAA,MAAA,OAAA,MAAA,OAAA,CAAA,GAAA,UAAA,CAAA,GAAA;CAAK,MAAA,OAAA,MAAA,MAAA,cAAA,UAAA,SAAA,IAAA;CAChG,IAAA,CAAA,MAAA,OAAA,YAAA,WAAA,KAAA,KAAA,SAAA,KAAA,UAAA,IAAA,GAAA;;;;;;;;EASA,IAAA,iBAA0B,gBAA0C,OAAA,YAAA,GAAA,MAAA,KAAA;EAClE,OAAA,YAAgB,GAAA,KAAA,KAAA,WAAA,iBAAA,QAAA,MAAA,UAAA,OAAA,KAAA,GAAA;CAChB;AACE;AAEA,SAAA,cAAkB,QAAA;CAClB,IAAA;CACA,QAAA,SAAa,WAAA;EACf,MAAE,WAAA,QAAA,aAAA,QAAA,KAAA;EACJ,IAAA,CAAA,OAAA,SAAA,QAAA,KAAA,SAAA,KAAA,KAAA,YAAA,MAAA;;;;;;;;;;AAYA,SAAA,UAAsB,aAEpB,WAEA,eACA"}
|
package/dist/_chunks/src.mjs
CHANGED
|
@@ -9,6 +9,10 @@ function stripEscapes(text) {
|
|
|
9
9
|
const end = Math.max(afterLast(text, "\x07"), afterLast(text, "\x1B\\"), afterLast(text, "ย"));
|
|
10
10
|
return text.slice(0, end).replaceAll(ESCAPE_SEQUENCE, "") + text.slice(end).replaceAll(CONTROL_SEQUENCE, "");
|
|
11
11
|
}
|
|
12
|
+
const FORGING = /[\u0000-\u0008\u000B-\u001F\u007F-\u009F\u061C\u200E\u200F\u202A-\u202E\u2066-\u206F]/g;
|
|
13
|
+
function sanitizeText(text) {
|
|
14
|
+
return stripEscapes(text.replaceAll(/\r\n?/g, "\n")).replaceAll(FORGING, "").replaceAll(/[\u2028\u2029]/g, " ");
|
|
15
|
+
}
|
|
12
16
|
var ToolDefinitionError = class extends Error {
|
|
13
17
|
name = "ToolDefinitionError";
|
|
14
18
|
};
|
|
@@ -144,7 +148,22 @@ function schemaAt(root, pointer) {
|
|
|
144
148
|
async function invokeTool(tool, args, context = {}) {
|
|
145
149
|
const checked = validateInput(tool, args);
|
|
146
150
|
if (!checked.ok) throw new ToolInputError(checked.lines);
|
|
147
|
-
|
|
151
|
+
const { progress } = context;
|
|
152
|
+
if (!progress) return await tool.execute(checked.value, context);
|
|
153
|
+
let settled = false;
|
|
154
|
+
try {
|
|
155
|
+
return await tool.execute(checked.value, {
|
|
156
|
+
...context,
|
|
157
|
+
progress(message, amount) {
|
|
158
|
+
if (settled) return;
|
|
159
|
+
try {
|
|
160
|
+
progress(sanitizeLine(message), amount);
|
|
161
|
+
} catch {}
|
|
162
|
+
}
|
|
163
|
+
});
|
|
164
|
+
} finally {
|
|
165
|
+
settled = true;
|
|
166
|
+
}
|
|
148
167
|
}
|
|
149
168
|
const LINE_BREAKING = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu;
|
|
150
169
|
function sanitizeLine(value) {
|
|
@@ -153,6 +172,6 @@ function sanitizeLine(value) {
|
|
|
153
172
|
function resultText(result) {
|
|
154
173
|
return result.content.flatMap((block) => block.type === "text" ? [block.text] : []).join("\n");
|
|
155
174
|
}
|
|
156
|
-
export { ToolDefinitionError, ToolInputError, defineTool, indexTools, invokeTool, resultText, sanitizeLine,
|
|
175
|
+
export { ToolDefinitionError, ToolInputError, defineTool, indexTools, invokeTool, resultText, sanitizeLine, sanitizeText, validateInput, wireSchema };
|
|
157
176
|
|
|
158
177
|
//# sourceMappingURL=src.mjs.map
|
package/dist/_chunks/src.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"src.mjs","names":["Value.Check","Value.Errors"],"sources":["../../src/escapes.ts","../../src/index.ts"],"sourcesContent":["/**\n * Terminal escape sequences, the pattern Node 26 uses in `stripVTControlCharacters`.\n * Kept here rather than imported from `node:util` so the core runs in a browser or a worker.\n */\nexport const ESCAPE_SEQUENCE =\n /* oxlint-disable-next-line no-control-regex */\n /(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]/g;\n\n/** The same pattern without its OSC branch, for text no string terminator follows. */\nconst CONTROL_SEQUENCE =\n /* oxlint-disable-next-line no-control-regex */\n /[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]/g;\n\n/**\n * @param text - Text to search.\n * @param token - Terminator to find.\n * @returns {number} Index just past the last `token`, or 0 without one.\n */\nfunction afterLast(text: string, token: string): number {\n const index = text.lastIndexOf(token);\n return index === -1 ? 0 : index + token.length;\n}\n\n/**\n * Node 26's `stripVTControlCharacters` to the letter, minus the quadratic walk: no OSC closes past\n * the last terminator, so that tail skips the branch that rescanned it from every `ESC ]`.\n *\n * @param text - Text to clean.\n * @returns {string} The text without escape sequences.\n */\nexport function stripEscapes(text: string): string {\n const end = Math.max(\n afterLast(text, \"\\u0007\"),\n afterLast(text, \"\\u001B\\\\\"),\n afterLast(text, \"\\u009C\"),\n );\n return (\n text.slice(0, end).replaceAll(ESCAPE_SEQUENCE, \"\") +\n text.slice(end).replaceAll(CONTROL_SEQUENCE, \"\")\n );\n}\n","/**\n * One tool definition shared by every agent surface.\n *\n * A package declares each tool once with {@link defineTool}; the adapters in\n * `@agntn/tools/mcp`, `/pi`, `/omp` and `/ai` translate it into each host's\n * registration shape. The schema is plain TypeBox 1.x, which is plain JSON\n * Schema at runtime, so every host receives the same document.\n */\n\nimport type { Static, TObject } from \"typebox\";\n\n/**\n * TypeBox builders for tool schemas. Author schemas with this, not with a\n * bare `import { Type } from \"typebox\"`: OMP's extension loader rewrites the\n * bare `typebox` specifier, in the extension and every module it imports, to\n * its omptype facade, whose schemas are functions instead of JSON Schema.\n * Subpaths such as `typebox/type` are left alone.\n */\nexport * as Type from \"typebox/type\";\n\n/**\n * Every schema type of the same bundled TypeBox build. Import them from here, not from `typebox`.\n * All of them, not a few: a package that exports a tool definition needs each type its schema\n * uses to be nameable in its declarations.\n */\nexport type * from \"typebox\";\n\nimport { Value } from \"typebox/value\";\n\nimport { stripEscapes } from \"./escapes.ts\";\n\n/** Content block understood by MCP, Pi and OMP alike. */\nexport type ToolContent =\n | { type: \"text\"; text: string }\n | { type: \"image\"; data: string; mimeType: string };\n\n/** Text for the model plus details for the harness. */\nexport interface ToolResult<Details = unknown> {\n content: ToolContent[];\n details: Details;\n /** Set when the tool could not answer. Each adapter carries it to its host. */\n isError?: boolean;\n}\n\n/**\n * What a call does to the world, mapped to MCP annotations and OMP approval.\n *\n * - `read` changes nothing.\n * - `write` changes state that the next call can undo or overwrite.\n * - `destructive` deletes or overwrites what cannot be recovered.\n */\nexport type ToolEffect = \"read\" | \"write\" | \"destructive\";\n\n/**\n * How a tool reads on the command line. Without hints the command is the tool\n * name without its package prefix, in kebab case, and every property is a flag.\n */\nexport interface ToolCliHints {\n /** Command name instead of the derived one. */\n readonly command?: string;\n readonly aliases?: readonly string[];\n /** Line in the command list. Defaults to the first sentence of `description`. */\n readonly description?: string;\n /** Properties taken in this order as positional arguments instead of flags. */\n readonly positional?: readonly string[];\n /** String properties that read stdin when given as `-`. */\n readonly stdin?: readonly string[];\n}\n\n/** Per-call context the adapters hand to `execute`. */\nexport interface ToolCallContext {\n signal?: AbortSignal;\n}\n\nexport interface ToolDefinition<Input extends TObject = TObject, Details = unknown> {\n /** Wire name, `<package>_<operation>`. */\n readonly name: string;\n /** Human label: MCP `title` and `annotations.title`, Pi and OMP `label`. */\n readonly title: string;\n /** Complete instruction for the model. MCP clients see nothing else. */\n readonly description: string;\n /** Pi `promptSnippet`. */\n readonly snippet?: string;\n /** Pi `promptGuidelines`. Must not promise anything `description` lacks. */\n readonly guidelines?: readonly string[];\n readonly effect: ToolEffect;\n /** Repeating the call with the same input has no further effect. Defaults to `effect === \"read\"`. */\n readonly idempotent?: boolean;\n /** The call reaches outside the local machine. */\n readonly openWorld?: boolean;\n readonly input: Input;\n /** Command line shape for `@agntn/tools/cli`. No other surface reads it. */\n readonly cli?: ToolCliHints;\n /**\n * Runs the tool on input that already passed {@link validateInput}.\n *\n * Method syntax on purpose: it keeps the parameter bivariant, so a list of\n * tools with different inputs is still a `readonly ToolDefinition[]`.\n */\n execute(\n input: Static<Input>,\n context: ToolCallContext,\n ): ToolResult<Details> | Promise<ToolResult<Details>>;\n}\n\n/** Thrown when a tool definition breaks a contract every surface relies on. */\nexport class ToolDefinitionError extends Error {\n override name = \"ToolDefinitionError\";\n}\n\n/** Thrown by {@link invokeTool} when the arguments fail the tool schema. */\nexport class ToolInputError extends Error {\n override name = \"ToolInputError\";\n /** One validation failure per line. Only these line breaks are the core's own. */\n readonly lines: readonly string[];\n\n /**\n * @param lines - One validation failure per line.\n */\n constructor(lines: readonly string[]) {\n super(lines.join(\"\\n\"));\n this.lines = lines;\n }\n}\n\nconst TOOL_NAME = /^[a-z][a-z0-9_]{0,63}$/;\n\n/**\n * Declares a tool and checks the schema rules every surface depends on.\n *\n * @param tool - Tool definition.\n * @returns {ToolDefinition<Input, Details>} The same definition, typed.\n */\nexport function defineTool<const Input extends TObject, Details>(\n tool: ToolDefinition<Input, Details>,\n): ToolDefinition<Input, Details> {\n if (!TOOL_NAME.test(tool.name)) {\n throw new ToolDefinitionError(`Tool name ${JSON.stringify(tool.name)} must match ${TOOL_NAME}`);\n }\n if (typeof tool.input !== \"object\" || tool.input === null) {\n // A function here is an omptype schema: `Type` came from a bare `typebox`\n // import that OMP remapped. `Value.Check` accepts any value against it.\n throw new ToolDefinitionError(\n `${tool.name}: input must be a JSON Schema object; build it with Type from @agntn/tools, not from \"typebox\"`,\n );\n }\n assertSchema(tool.name, wireSchema(tool));\n return tool;\n}\n\ntype SchemaNode = Readonly<Record<string, unknown>>;\n\n/**\n * Enforces two rules on the input schema, at every depth.\n *\n * A non-empty object must be closed (`additionalProperties: false`), because a\n * misspelled key would otherwise be dropped without a signal: `read_only`\n * instead of `readOnly` ran `harnesses_run` with full tool access. An empty\n * object stays open, since models send placeholders like `{_: \"\"}` to it.\n *\n * A union of literals must be `Type.Enum`: TypeBox serializes the union as\n * `anyOf` const objects, which triples the wire size, and `Value.Errors`\n * reports it as `must be equal to constant` against the first literal only.\n *\n * @param toolName - Tool the schema belongs to, for the error.\n * @param node - Schema node to check.\n * @param path - JSON pointer of the node, empty at the root.\n */\nfunction assertSchema(toolName: string, node: SchemaNode, path = \"\"): void {\n const at = path || \"/\";\n if (isOpenObject(node)) {\n throw new ToolDefinitionError(\n `${toolName}: object at ${at} must be closed with additionalProperties: false`,\n );\n }\n if (isLiteralUnion(node)) {\n throw new ToolDefinitionError(`${toolName}: union of literals at ${at} must use Type.Enum`);\n }\n for (const [child, childPath] of schemaChildren(node, path)) {\n assertSchema(toolName, child, childPath);\n }\n}\n\n/**\n * @param node - Schema node.\n * @returns {boolean} Whether the node is an object with properties that accepts other keys.\n */\nfunction isOpenObject(node: SchemaNode): boolean {\n const properties = node.properties as SchemaNode | undefined;\n return (\n node.type === \"object\" &&\n properties !== undefined &&\n Object.keys(properties).length > 0 &&\n node.additionalProperties !== false\n );\n}\n\n/**\n * @param node - Schema node.\n * @returns {boolean} Whether the node is an `anyOf` of two or more constants.\n */\nfunction isLiteralUnion(node: SchemaNode): boolean {\n const anyOf = node.anyOf as readonly SchemaNode[] | undefined;\n return anyOf !== undefined && anyOf.length > 1 && anyOf.every((branch) => \"const\" in branch);\n}\n\n/**\n * @param value - Any schema keyword value.\n * @returns {boolean} Whether it is a nested schema.\n */\nfunction isNode(value: unknown): value is SchemaNode {\n return typeof value === \"object\" && value !== null;\n}\n\n/**\n * The subschemas a value of this node can reach: properties, record values,\n * array items and union branches.\n *\n * @param node - Schema node.\n * @param path - JSON pointer of the node.\n * @returns {Array<[SchemaNode, string]>} Each subschema with its path.\n */\nfunction schemaChildren(node: SchemaNode, path: string): Array<[SchemaNode, string]> {\n const keyed = (keyword: string, childPath: (key: string) => string) =>\n Object.entries(isNode(node[keyword]) ? node[keyword] : {}).flatMap(\n ([key, child]): Array<[SchemaNode, string]> =>\n isNode(child) ? [[child, childPath(key)]] : [],\n );\n const branches = Array.isArray(node.anyOf) ? (node.anyOf as readonly unknown[]) : [];\n return [\n ...keyed(\"properties\", (key) => `${path}/${key}`),\n ...keyed(\"patternProperties\", () => `${path}/*`),\n ...(isNode(node.items) ? [[node.items, `${path}/items`] as [SchemaNode, string]] : []),\n ...branches.filter(isNode).map((branch): [SchemaNode, string] => [branch, path]),\n ];\n}\n\n/**\n * The input schema as the plain JSON Schema object every host receives.\n *\n * TypeBox 1.x schemas are plain objects already; this only drops the static\n * type, which lacks the index signature host APIs declare.\n *\n * @param tool - Tool whose schema to emit.\n * @returns {Record<string, unknown>} JSON Schema document.\n */\nexport function wireSchema(tool: ToolDefinition): Record<string, unknown> {\n return Object.fromEntries(Object.entries(tool.input));\n}\n\n/**\n * Indexes tools by name.\n *\n * A `Map`, not a plain object: a lookup of `toString` in a `Record` finds\n * `Object.prototype.toString` and skips the unknown-tool branch.\n *\n * @param tools - Tools to index.\n * @returns {ReadonlyMap<string, ToolDefinition>} Tools by wire name.\n */\nexport function indexTools(tools: readonly ToolDefinition[]): ReadonlyMap<string, ToolDefinition> {\n const byName = new Map<string, ToolDefinition>();\n for (const tool of tools) {\n if (byName.has(tool.name)) throw new ToolDefinitionError(`Duplicate tool name ${tool.name}`);\n byName.set(tool.name, tool);\n }\n return byName;\n}\n\nexport type InputCheck<Input extends TObject> =\n | { ok: true; value: Static<Input> }\n | { ok: false; lines: readonly string[] };\n\n/**\n * Validates arguments against the tool schema, reporting every failure.\n *\n * Runs on every surface, not only MCP: a host may skip its own validation, and\n * OMP's omptype drops `pattern` from the schema it emits. The message has one\n * line per failure: an undeclared key names itself with the keys its object\n * takes, at any depth, and an enum failure names the allowed values, so the\n * caller does not go back to the tool list and guess. Format from agntn/hashes\n * (#58). TypeBox stops at eight errors, so root keys are read off the arguments.\n *\n * @param tool - Tool whose schema applies.\n * @param args - Arguments as received from the host.\n * @returns {InputCheck<Input>} The typed value, or the failures, one per line.\n */\nexport function validateInput<Input extends TObject>(\n tool: ToolDefinition<Input, unknown>,\n args: unknown,\n): InputCheck<Input> {\n if (Value.Check(tool.input, args)) return { ok: true, value: args };\n\n const schema = wireSchema(tool);\n const rootKeys =\n args !== null && typeof args === \"object\" && !Array.isArray(args)\n ? Object.keys(args).filter((key) => !Object.hasOwn(tool.input.properties, key))\n : [];\n const unknown = rootKeys.map((key) => unknownKeyLine(\"\", key, [schema]));\n const other: string[] = [];\n for (const error of Value.Errors(tool.input, args)) {\n if (error.keyword === \"additionalProperties\") continue;\n const refused = refusedKeyLines(schema, error.instancePath, error.schemaPath);\n if (refused === undefined)\n other.push(errorLine(error.instancePath, error.message, error.params));\n else unknown.push(...refused);\n }\n const lines = [...unknown, ...other];\n return { ok: false, lines: lines.length > 0 ? [...new Set(lines)] : [\"Invalid arguments\"] };\n}\n\n/**\n * @param at - JSON pointer of the failing value.\n * @param message - TypeBox's message.\n * @param params - TypeBox's parameters of the failure.\n * @returns {string} The line, with the allowed values when an enum failed.\n */\nfunction errorLine(at: string, message: string, params: unknown): string {\n const allowed = isNode(params) ? params.allowedValues : undefined;\n const text = Array.isArray(allowed) ? `must be one of ${allowed.join(\", \")}` : message;\n return `Invalid arguments at ${at || \"/\"}: ${text}`;\n}\n\n/**\n * A closed object refuses each extra key as `schema is false`, which names nothing on its own.\n *\n * @param root - Tool input schema.\n * @param at - JSON pointer of the failing value.\n * @param schemaPath - Schema path of the failure.\n * @returns {string[] | undefined} The line, none when another union branch takes the key, or\n * `undefined` for any other failure.\n */\nfunction refusedKeyLines(root: SchemaNode, at: string, schemaPath: string): string[] | undefined {\n const suffix = \"/additionalProperties\";\n if (!schemaPath.endsWith(suffix)) return undefined;\n const objectPath = schemaPath.slice(0, -suffix.length);\n const node = schemaAt(root, objectPath);\n if (node?.additionalProperties !== false) return undefined;\n const cut = at.lastIndexOf(\"/\");\n const key = unescapeToken(at.slice(cut + 1));\n const alternatives = alternativesAt(root, objectPath);\n if (alternatives.some((alternative) => takesKey(alternative, key))) return [];\n return [unknownKeyLine(at.slice(0, cut), key, alternatives)];\n}\n\n/**\n * Each union branch fails on its own, so the same object in another branch may take the key.\n *\n * @param root - Tool input schema.\n * @param pointer - Schema path of a closed object.\n * @returns {SchemaNode[]} That object as every branch of every enclosing union has it.\n */\nfunction alternativesAt(root: SchemaNode, pointer: string): SchemaNode[] {\n let nodes: unknown[] = [root];\n let previous = \"\";\n for (const token of pointer.split(\"/\").slice(1)) {\n const key = unescapeToken(token);\n const everyBranch = previous === \"anyOf\" && /^\\d+$/.test(key);\n nodes = nodes.flatMap((node): unknown[] => {\n if (everyBranch && Array.isArray(node)) return node;\n return isNode(node) && Object.hasOwn(node, key) ? [node[key]] : [];\n });\n previous = key;\n }\n return nodes.filter(isNode);\n}\n\n/**\n * @param token - One JSON pointer segment.\n * @returns {string} The property name it encodes.\n */\nfunction unescapeToken(token: string): string {\n return token.replaceAll(\"~1\", \"/\").replaceAll(\"~0\", \"~\");\n}\n\n/**\n * @param node - Schema node.\n * @param key - Property name.\n * @returns {boolean} Whether an object of this schema accepts the key.\n */\nfunction takesKey(node: SchemaNode, key: string): boolean {\n if (node.type !== \"object\") return false;\n if (node.additionalProperties !== false) return true;\n if (isNode(node.properties) && Object.hasOwn(node.properties, key)) return true;\n return patternsOf(node).some((pattern) => new RegExp(pattern, \"u\").test(key));\n}\n\n/**\n * @param node - Schema node.\n * @returns {string[]} Its `patternProperties` patterns.\n */\nfunction patternsOf(node: SchemaNode): string[] {\n return Object.keys(isNode(node.patternProperties) ? node.patternProperties : {});\n}\n\n/**\n * @param at - JSON pointer of the object, empty at the root.\n * @param key - The undeclared key.\n * @param objects - Schema of that object, once per union branch it sits in.\n * @returns {string} The key with what the object takes, and the object's path when it is nested.\n */\nfunction unknownKeyLine(at: string, key: string, objects: readonly SchemaNode[]): string {\n const lists = [\n ...new Set(\n objects\n .filter((object) => object.type === \"object\")\n .map((object) =>\n [\n ...Object.keys(isNode(object.properties) ? object.properties : {}),\n ...patternsOf(object).map((pattern) => `keys matching ${JSON.stringify(pattern)}`),\n ].join(\", \"),\n ),\n ),\n ];\n const takes = lists.length > 1 ? lists.map((list) => `{${list}}`).join(\" or \") : lists[0];\n const where = at === \"\" ? \"\" : ` at ${at}`;\n const what = takes || \"no properties\";\n return `Invalid arguments${where}: unknown property ${JSON.stringify(key)}; takes ${what}`;\n}\n\n/**\n * @param root - Tool input schema.\n * @param pointer - Schema path from a validation error, such as `#/properties/point`.\n * @returns {SchemaNode | undefined} The subschema it points at.\n */\nfunction schemaAt(root: SchemaNode, pointer: string): SchemaNode | undefined {\n let node: unknown = root;\n for (const token of pointer.split(\"/\").slice(1)) {\n const key = unescapeToken(token);\n node = isNode(node) && Object.hasOwn(node, key) ? node[key] : undefined;\n }\n return isNode(node) ? node : undefined;\n}\n\n/**\n * Validates and runs a tool. Every adapter calls through here.\n *\n * @param tool - Tool to run.\n * @param args - Arguments as received from the host.\n * @param context - Per-call context.\n * @returns {Promise<ToolResult>} The executor's result, unchanged.\n * @throws {ToolInputError} When the arguments fail the schema.\n */\nexport async function invokeTool(\n tool: ToolDefinition,\n args: unknown,\n context: ToolCallContext = {},\n): Promise<ToolResult> {\n const checked = validateInput(tool, args);\n if (!checked.ok) throw new ToolInputError(checked.lines);\n return await tool.execute(checked.value, context);\n}\n\nconst LINE_BREAKING = /[\\p{Cc}\\p{Cf}\\p{Zl}\\p{Zp}]/gu;\n\n/**\n * Makes a value safe for one line of terminal or protocol text.\n *\n * Removes escape sequences, then replaces every control, format, line and\n * paragraph separator character with a space: a raw newline, U+2028 or a bidi\n * override (U+202E, a `Cf`) in an echoed value forges a line that reads as the\n * tool's own output. `String()` first, since hostile JSON ignores declared types.\n *\n * @param value - Value to render.\n * @returns {string} Single-line text.\n */\nexport function sanitizeLine(value: unknown): string {\n return stripEscapes(String(value))\n .replaceAll(LINE_BREAKING, \" \")\n .replaceAll(/ {2,}/g, \" \")\n .trim();\n}\n\n/**\n * Text of a result, for hosts that carry failures as thrown errors.\n *\n * @param result - Tool result.\n * @returns {string} Text blocks joined by newlines.\n */\nexport function resultText(result: ToolResult): string {\n return result.content.flatMap((block) => (block.type === \"text\" ? [block.text] : [])).join(\"\\n\");\n}\n"],"mappings":";;;;CASA,MAAM,QAAA,KAAA,YAEJ,KAAA;;;;;CAOF,OAAA,KAAS,MAAU,GAAA,GAAc,CAAA,CAAA,WAAuB,iBAAA,EAAA,IAAA,KAAA,MAAA,GAAA,CAAA,CAAA,WAAA,kBAAA,EAAA;AACtD;;;;;;CAWF;CAME,YACO,OAAM;EAGf,MAAA,MAAA,KAAA,IAAA,CAAA;;;ACkEA;AACE,MAAS,YAAO;;CAIlB,IAAa,CAAA,UAAA,KAAb,KAAA,IAAA,GAAA,MAAoC,IAAM,oBAAA,aAAA,KAAA,UAAA,KAAA,IAAA,EAAA,cAAA,WAAA;CACxC,IAAS,OAAO,KAAA,UAAA,YAAA,KAAA,UAAA,MAAA,MAAA,IAAA,oBAAA,GAAA,KAAA,KAAA,+FAAA;;CAEhB,OAAS;;;CAKT,MAAA,KAAA,QAAsC;CACpC,IAAA,aAAY,IAAK,GAAK,MAAA,IAAA,oBAAA,GAAA,SAAA,cAAA,GAAA,iDAAA;CACtB,IAAA,eAAa,IAAA,GAAA,MAAA,IAAA,oBAAA,GAAA,SAAA,yBAAA,GAAA,oBAAA;CACf,KAAA,MAAA,CAA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AAa,QAAA,SAAiB,UAAQ,MAAM,SAAK,SAAA,CAAA,MAAmB,IAAA,IAAA,CAAA,CAAA,CAAA,CAAA,KAAA,IAAA;AAAE"}
|
|
1
|
+
{"version":3,"file":"src.mjs","names":["Value.Check","Value.Errors"],"sources":["../../src/escapes.ts","../../src/index.ts"],"sourcesContent":["/**\n * Terminal escape sequences, the pattern Node 26 uses in `stripVTControlCharacters`.\n * Kept here rather than imported from `node:util` so the core runs in a browser or a worker.\n */\nexport const ESCAPE_SEQUENCE =\n /* oxlint-disable-next-line no-control-regex */\n /(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]/g;\n\n/** The same pattern without its OSC branch, for text no string terminator follows. */\nconst CONTROL_SEQUENCE =\n /* oxlint-disable-next-line no-control-regex */\n /[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]/g;\n\n/**\n * @param text - Text to search.\n * @param token - Terminator to find.\n * @returns {number} Index just past the last `token`, or 0 without one.\n */\nfunction afterLast(text: string, token: string): number {\n const index = text.lastIndexOf(token);\n return index === -1 ? 0 : index + token.length;\n}\n\n/**\n * Node 26's `stripVTControlCharacters` to the letter, minus the quadratic walk: no OSC closes past\n * the last terminator, so that tail skips the branch that rescanned it from every `ESC ]`.\n *\n * @param text - Text to clean.\n * @returns {string} The text without escape sequences.\n */\nexport function stripEscapes(text: string): string {\n const end = Math.max(\n afterLast(text, \"\\u0007\"),\n afterLast(text, \"\\u001B\\\\\"),\n afterLast(text, \"\\u009C\"),\n );\n return (\n text.slice(0, end).replaceAll(ESCAPE_SEQUENCE, \"\") +\n text.slice(end).replaceAll(CONTROL_SEQUENCE, \"\")\n );\n}\n\n/** C0 and C1 controls but tab and line feed, and the bidi marks, embeddings, overrides and isolates. */\nconst FORGING =\n /* oxlint-disable-next-line no-control-regex */\n /[\\u0000-\\u0008\\u000B-\\u001F\\u007F-\\u009F\\u061C\\u200E\\u200F\\u202A-\\u202E\\u2066-\\u206F]/g;\n\n/**\n * Makes multi-line tool text safe for a terminal. Unlike {@link sanitizeLine}\n * it keeps the layout: line feeds, tabs and the joiners of emoji and scripts\n * (ZWJ, ZWNJ) stay, CR and CRLF become a line feed, and the Unicode line and\n * paragraph separators become a space so words do not run together.\n *\n * @param text - Tool text.\n * @returns {string} The text without escape sequences or other control characters.\n */\nexport function sanitizeText(text: string): string {\n return stripEscapes(text.replaceAll(/\\r\\n?/g, \"\\n\"))\n .replaceAll(FORGING, \"\")\n .replaceAll(/[\\u2028\\u2029]/g, \" \");\n}\n","/**\n * One tool definition shared by every agent surface.\n *\n * A package declares each tool once with {@link defineTool}; the adapters in\n * `@agntn/tools/mcp`, `/pi`, `/omp` and `/ai` translate it into each host's\n * registration shape. The schema is plain TypeBox 1.x, which is plain JSON\n * Schema at runtime, so every host receives the same document.\n */\n\nimport type { Static, TObject } from \"typebox\";\n\n/**\n * TypeBox builders for tool schemas. Author schemas with this, not with a\n * bare `import { Type } from \"typebox\"`: OMP's extension loader rewrites the\n * bare `typebox` specifier, in the extension and every module it imports, to\n * its omptype facade, whose schemas are functions instead of JSON Schema.\n * Subpaths such as `typebox/type` are left alone.\n */\nexport * as Type from \"typebox/type\";\n\n/**\n * Every schema type of the same bundled TypeBox build. Import them from here, not from `typebox`.\n * All of them, not a few: a package that exports a tool definition needs each type its schema\n * uses to be nameable in its declarations.\n */\nexport type * from \"typebox\";\n\nimport { Value } from \"typebox/value\";\n\nimport { stripEscapes } from \"./escapes.ts\";\n\n/** Content block understood by MCP, Pi and OMP alike. */\nexport type ToolContent =\n | { type: \"text\"; text: string }\n | { type: \"image\"; data: string; mimeType: string };\n\n/** Text for the model plus details for the harness. */\nexport interface ToolResult<Details = unknown> {\n content: ToolContent[];\n details: Details;\n /** Set when the tool could not answer. Each adapter carries it to its host. */\n isError?: boolean;\n}\n\n/**\n * What a call does to the world, mapped to MCP annotations and OMP approval.\n *\n * - `read` changes nothing.\n * - `write` changes state that the next call can undo or overwrite.\n * - `destructive` deletes or overwrites what cannot be recovered.\n */\nexport type ToolEffect = \"read\" | \"write\" | \"destructive\";\n\n/**\n * How a tool reads on the command line. Without hints the command is the tool\n * name without its package prefix, in kebab case, and every property is a flag.\n */\nexport interface ToolCliHints {\n /** Command name instead of the derived one. */\n readonly command?: string;\n readonly aliases?: readonly string[];\n /** Line in the command list. Defaults to the first sentence of `description`. */\n readonly description?: string;\n /** Properties taken in this order as positional arguments instead of flags. */\n readonly positional?: readonly string[];\n /** String properties that read stdin when given as `-`. */\n readonly stdin?: readonly string[];\n}\n\n/** How far a long call has come, for hosts that draw it. */\nexport interface ToolProgress {\n /** Work done so far. MCP skips an update where it doesn't grow. */\n readonly progress: number;\n /** All the work there is, when the tool knows it. */\n readonly total?: number;\n}\n\n/** Per-call context the adapters hand to `execute`. */\nexport interface ToolCallContext {\n signal?: AbortSignal;\n /** Says the call is still at it. Absent where the host can't show it, so call `progress?.()`. */\n progress?: (message: string, amount?: ToolProgress) => void;\n}\n\nexport interface ToolDefinition<Input extends TObject = TObject, Details = unknown> {\n /** Wire name, `<package>_<operation>`. */\n readonly name: string;\n /** Human label: MCP `title` and `annotations.title`, Pi and OMP `label`. */\n readonly title: string;\n /** Complete instruction for the model. MCP clients see nothing else. */\n readonly description: string;\n /** Pi `promptSnippet`. */\n readonly snippet?: string;\n /** Pi `promptGuidelines`. Must not promise anything `description` lacks. */\n readonly guidelines?: readonly string[];\n readonly effect: ToolEffect;\n /** Repeating the call with the same input has no further effect. Defaults to `effect === \"read\"`. */\n readonly idempotent?: boolean;\n /** The call reaches outside the local machine. */\n readonly openWorld?: boolean;\n readonly input: Input;\n /** Command line shape for `@agntn/tools/cli`. No other surface reads it. */\n readonly cli?: ToolCliHints;\n /**\n * Runs the tool on input that already passed {@link validateInput}.\n *\n * Method syntax on purpose: it keeps the parameter bivariant, so a list of\n * tools with different inputs is still a `readonly ToolDefinition[]`.\n */\n execute(\n input: Static<Input>,\n context: ToolCallContext,\n ): ToolResult<Details> | Promise<ToolResult<Details>>;\n}\n\n/** Thrown when a tool definition breaks a contract every surface relies on. */\nexport class ToolDefinitionError extends Error {\n override name = \"ToolDefinitionError\";\n}\n\n/** Thrown by {@link invokeTool} when the arguments fail the tool schema. */\nexport class ToolInputError extends Error {\n override name = \"ToolInputError\";\n /** One validation failure per line. Only these line breaks are the core's own. */\n readonly lines: readonly string[];\n\n /**\n * @param lines - One validation failure per line.\n */\n constructor(lines: readonly string[]) {\n super(lines.join(\"\\n\"));\n this.lines = lines;\n }\n}\n\nconst TOOL_NAME = /^[a-z][a-z0-9_]{0,63}$/;\n\n/**\n * Declares a tool and checks the schema rules every surface depends on.\n *\n * @param tool - Tool definition.\n * @returns {ToolDefinition<Input, Details>} The same definition, typed.\n */\nexport function defineTool<const Input extends TObject, Details>(\n tool: ToolDefinition<Input, Details>,\n): ToolDefinition<Input, Details> {\n if (!TOOL_NAME.test(tool.name)) {\n throw new ToolDefinitionError(`Tool name ${JSON.stringify(tool.name)} must match ${TOOL_NAME}`);\n }\n if (typeof tool.input !== \"object\" || tool.input === null) {\n // A function here is an omptype schema: `Type` came from a bare `typebox`\n // import that OMP remapped. `Value.Check` accepts any value against it.\n throw new ToolDefinitionError(\n `${tool.name}: input must be a JSON Schema object; build it with Type from @agntn/tools, not from \"typebox\"`,\n );\n }\n assertSchema(tool.name, wireSchema(tool));\n return tool;\n}\n\ntype SchemaNode = Readonly<Record<string, unknown>>;\n\n/**\n * Enforces two rules on the input schema, at every depth.\n *\n * A non-empty object must be closed (`additionalProperties: false`), because a\n * misspelled key would otherwise be dropped without a signal: `read_only`\n * instead of `readOnly` ran `harnesses_run` with full tool access. An empty\n * object stays open, since models send placeholders like `{_: \"\"}` to it.\n *\n * A union of literals must be `Type.Enum`: TypeBox serializes the union as\n * `anyOf` const objects, which triples the wire size, and `Value.Errors`\n * reports it as `must be equal to constant` against the first literal only.\n *\n * @param toolName - Tool the schema belongs to, for the error.\n * @param node - Schema node to check.\n * @param path - JSON pointer of the node, empty at the root.\n */\nfunction assertSchema(toolName: string, node: SchemaNode, path = \"\"): void {\n const at = path || \"/\";\n if (isOpenObject(node)) {\n throw new ToolDefinitionError(\n `${toolName}: object at ${at} must be closed with additionalProperties: false`,\n );\n }\n if (isLiteralUnion(node)) {\n throw new ToolDefinitionError(`${toolName}: union of literals at ${at} must use Type.Enum`);\n }\n for (const [child, childPath] of schemaChildren(node, path)) {\n assertSchema(toolName, child, childPath);\n }\n}\n\n/**\n * @param node - Schema node.\n * @returns {boolean} Whether the node is an object with properties that accepts other keys.\n */\nfunction isOpenObject(node: SchemaNode): boolean {\n const properties = node.properties as SchemaNode | undefined;\n return (\n node.type === \"object\" &&\n properties !== undefined &&\n Object.keys(properties).length > 0 &&\n node.additionalProperties !== false\n );\n}\n\n/**\n * @param node - Schema node.\n * @returns {boolean} Whether the node is an `anyOf` of two or more constants.\n */\nfunction isLiteralUnion(node: SchemaNode): boolean {\n const anyOf = node.anyOf as readonly SchemaNode[] | undefined;\n return anyOf !== undefined && anyOf.length > 1 && anyOf.every((branch) => \"const\" in branch);\n}\n\n/**\n * @param value - Any schema keyword value.\n * @returns {boolean} Whether it is a nested schema.\n */\nfunction isNode(value: unknown): value is SchemaNode {\n return typeof value === \"object\" && value !== null;\n}\n\n/**\n * The subschemas a value of this node can reach: properties, record values,\n * array items and union branches.\n *\n * @param node - Schema node.\n * @param path - JSON pointer of the node.\n * @returns {Array<[SchemaNode, string]>} Each subschema with its path.\n */\nfunction schemaChildren(node: SchemaNode, path: string): Array<[SchemaNode, string]> {\n const keyed = (keyword: string, childPath: (key: string) => string) =>\n Object.entries(isNode(node[keyword]) ? node[keyword] : {}).flatMap(\n ([key, child]): Array<[SchemaNode, string]> =>\n isNode(child) ? [[child, childPath(key)]] : [],\n );\n const branches = Array.isArray(node.anyOf) ? (node.anyOf as readonly unknown[]) : [];\n return [\n ...keyed(\"properties\", (key) => `${path}/${key}`),\n ...keyed(\"patternProperties\", () => `${path}/*`),\n ...(isNode(node.items) ? [[node.items, `${path}/items`] as [SchemaNode, string]] : []),\n ...branches.filter(isNode).map((branch): [SchemaNode, string] => [branch, path]),\n ];\n}\n\n/**\n * The input schema as the plain JSON Schema object every host receives.\n *\n * TypeBox 1.x schemas are plain objects already; this only drops the static\n * type, which lacks the index signature host APIs declare.\n *\n * @param tool - Tool whose schema to emit.\n * @returns {Record<string, unknown>} JSON Schema document.\n */\nexport function wireSchema(tool: ToolDefinition): Record<string, unknown> {\n return Object.fromEntries(Object.entries(tool.input));\n}\n\n/**\n * Indexes tools by name.\n *\n * A `Map`, not a plain object: a lookup of `toString` in a `Record` finds\n * `Object.prototype.toString` and skips the unknown-tool branch.\n *\n * @param tools - Tools to index.\n * @returns {ReadonlyMap<string, ToolDefinition>} Tools by wire name.\n */\nexport function indexTools(tools: readonly ToolDefinition[]): ReadonlyMap<string, ToolDefinition> {\n const byName = new Map<string, ToolDefinition>();\n for (const tool of tools) {\n if (byName.has(tool.name)) throw new ToolDefinitionError(`Duplicate tool name ${tool.name}`);\n byName.set(tool.name, tool);\n }\n return byName;\n}\n\nexport type InputCheck<Input extends TObject> =\n | { ok: true; value: Static<Input> }\n | { ok: false; lines: readonly string[] };\n\n/**\n * Validates arguments against the tool schema, reporting every failure.\n *\n * Runs on every surface, not only MCP: a host may skip its own validation, and\n * OMP's omptype drops `pattern` from the schema it emits. The message has one\n * line per failure: an undeclared key names itself with the keys its object\n * takes, at any depth, and an enum failure names the allowed values, so the\n * caller does not go back to the tool list and guess. Format from agntn/hashes\n * (#58). TypeBox stops at eight errors, so root keys are read off the arguments.\n *\n * @param tool - Tool whose schema applies.\n * @param args - Arguments as received from the host.\n * @returns {InputCheck<Input>} The typed value, or the failures, one per line.\n */\nexport function validateInput<Input extends TObject>(\n tool: ToolDefinition<Input, unknown>,\n args: unknown,\n): InputCheck<Input> {\n if (Value.Check(tool.input, args)) return { ok: true, value: args };\n\n const schema = wireSchema(tool);\n const rootKeys =\n args !== null && typeof args === \"object\" && !Array.isArray(args)\n ? Object.keys(args).filter((key) => !Object.hasOwn(tool.input.properties, key))\n : [];\n const unknown = rootKeys.map((key) => unknownKeyLine(\"\", key, [schema]));\n const other: string[] = [];\n for (const error of Value.Errors(tool.input, args)) {\n if (error.keyword === \"additionalProperties\") continue;\n const refused = refusedKeyLines(schema, error.instancePath, error.schemaPath);\n if (refused === undefined)\n other.push(errorLine(error.instancePath, error.message, error.params));\n else unknown.push(...refused);\n }\n const lines = [...unknown, ...other];\n return { ok: false, lines: lines.length > 0 ? [...new Set(lines)] : [\"Invalid arguments\"] };\n}\n\n/**\n * @param at - JSON pointer of the failing value.\n * @param message - TypeBox's message.\n * @param params - TypeBox's parameters of the failure.\n * @returns {string} The line, with the allowed values when an enum failed.\n */\nfunction errorLine(at: string, message: string, params: unknown): string {\n const allowed = isNode(params) ? params.allowedValues : undefined;\n const text = Array.isArray(allowed) ? `must be one of ${allowed.join(\", \")}` : message;\n return `Invalid arguments at ${at || \"/\"}: ${text}`;\n}\n\n/**\n * A closed object refuses each extra key as `schema is false`, which names nothing on its own.\n *\n * @param root - Tool input schema.\n * @param at - JSON pointer of the failing value.\n * @param schemaPath - Schema path of the failure.\n * @returns {string[] | undefined} The line, none when another union branch takes the key, or\n * `undefined` for any other failure.\n */\nfunction refusedKeyLines(root: SchemaNode, at: string, schemaPath: string): string[] | undefined {\n const suffix = \"/additionalProperties\";\n if (!schemaPath.endsWith(suffix)) return undefined;\n const objectPath = schemaPath.slice(0, -suffix.length);\n const node = schemaAt(root, objectPath);\n if (node?.additionalProperties !== false) return undefined;\n const cut = at.lastIndexOf(\"/\");\n const key = unescapeToken(at.slice(cut + 1));\n const alternatives = alternativesAt(root, objectPath);\n if (alternatives.some((alternative) => takesKey(alternative, key))) return [];\n return [unknownKeyLine(at.slice(0, cut), key, alternatives)];\n}\n\n/**\n * Each union branch fails on its own, so the same object in another branch may take the key.\n *\n * @param root - Tool input schema.\n * @param pointer - Schema path of a closed object.\n * @returns {SchemaNode[]} That object as every branch of every enclosing union has it.\n */\nfunction alternativesAt(root: SchemaNode, pointer: string): SchemaNode[] {\n let nodes: unknown[] = [root];\n let previous = \"\";\n for (const token of pointer.split(\"/\").slice(1)) {\n const key = unescapeToken(token);\n const everyBranch = previous === \"anyOf\" && /^\\d+$/.test(key);\n nodes = nodes.flatMap((node): unknown[] => {\n if (everyBranch && Array.isArray(node)) return node;\n return isNode(node) && Object.hasOwn(node, key) ? [node[key]] : [];\n });\n previous = key;\n }\n return nodes.filter(isNode);\n}\n\n/**\n * @param token - One JSON pointer segment.\n * @returns {string} The property name it encodes.\n */\nfunction unescapeToken(token: string): string {\n return token.replaceAll(\"~1\", \"/\").replaceAll(\"~0\", \"~\");\n}\n\n/**\n * @param node - Schema node.\n * @param key - Property name.\n * @returns {boolean} Whether an object of this schema accepts the key.\n */\nfunction takesKey(node: SchemaNode, key: string): boolean {\n if (node.type !== \"object\") return false;\n if (node.additionalProperties !== false) return true;\n if (isNode(node.properties) && Object.hasOwn(node.properties, key)) return true;\n return patternsOf(node).some((pattern) => new RegExp(pattern, \"u\").test(key));\n}\n\n/**\n * @param node - Schema node.\n * @returns {string[]} Its `patternProperties` patterns.\n */\nfunction patternsOf(node: SchemaNode): string[] {\n return Object.keys(isNode(node.patternProperties) ? node.patternProperties : {});\n}\n\n/**\n * @param at - JSON pointer of the object, empty at the root.\n * @param key - The undeclared key.\n * @param objects - Schema of that object, once per union branch it sits in.\n * @returns {string} The key with what the object takes, and the object's path when it is nested.\n */\nfunction unknownKeyLine(at: string, key: string, objects: readonly SchemaNode[]): string {\n const lists = [\n ...new Set(\n objects\n .filter((object) => object.type === \"object\")\n .map((object) =>\n [\n ...Object.keys(isNode(object.properties) ? object.properties : {}),\n ...patternsOf(object).map((pattern) => `keys matching ${JSON.stringify(pattern)}`),\n ].join(\", \"),\n ),\n ),\n ];\n const takes = lists.length > 1 ? lists.map((list) => `{${list}}`).join(\" or \") : lists[0];\n const where = at === \"\" ? \"\" : ` at ${at}`;\n const what = takes || \"no properties\";\n return `Invalid arguments${where}: unknown property ${JSON.stringify(key)}; takes ${what}`;\n}\n\n/**\n * @param root - Tool input schema.\n * @param pointer - Schema path from a validation error, such as `#/properties/point`.\n * @returns {SchemaNode | undefined} The subschema it points at.\n */\nfunction schemaAt(root: SchemaNode, pointer: string): SchemaNode | undefined {\n let node: unknown = root;\n for (const token of pointer.split(\"/\").slice(1)) {\n const key = unescapeToken(token);\n node = isNode(node) && Object.hasOwn(node, key) ? node[key] : undefined;\n }\n return isNode(node) ? node : undefined;\n}\n\n/**\n * Validates and runs a tool. Every adapter calls through here.\n *\n * Progress is best effort: a line after the call settles goes nowhere, and a host that throws on\n * one doesn't fail the call.\n *\n * @param tool - Tool to run.\n * @param args - Arguments as received from the host.\n * @param context - Per-call context.\n * @returns {Promise<ToolResult>} The executor's result, unchanged.\n * @throws {ToolInputError} When the arguments fail the schema.\n */\nexport async function invokeTool(\n tool: ToolDefinition,\n args: unknown,\n context: ToolCallContext = {},\n): Promise<ToolResult> {\n const checked = validateInput(tool, args);\n if (!checked.ok) throw new ToolInputError(checked.lines);\n const { progress } = context;\n if (!progress) return await tool.execute(checked.value, context);\n\n let settled = false;\n try {\n return await tool.execute(checked.value, {\n ...context,\n progress(message, amount) {\n if (settled) return;\n try {\n progress(sanitizeLine(message), amount);\n } catch {}\n },\n });\n } finally {\n settled = true;\n }\n}\n\nconst LINE_BREAKING = /[\\p{Cc}\\p{Cf}\\p{Zl}\\p{Zp}]/gu;\n\n/**\n * Makes a value safe for one line of terminal or protocol text.\n *\n * Removes escape sequences, then replaces every control, format, line and\n * paragraph separator character with a space: a raw newline, U+2028 or a bidi\n * override (U+202E, a `Cf`) in an echoed value forges a line that reads as the\n * tool's own output. `String()` first, since hostile JSON ignores declared types.\n *\n * @param value - Value to render.\n * @returns {string} Single-line text.\n */\nexport function sanitizeLine(value: unknown): string {\n return stripEscapes(String(value))\n .replaceAll(LINE_BREAKING, \" \")\n .replaceAll(/ {2,}/g, \" \")\n .trim();\n}\n\n/**\n * Text of a result, for hosts that carry failures as thrown errors.\n *\n * @param result - Tool result.\n * @returns {string} Text blocks joined by newlines.\n */\nexport function resultText(result: ToolResult): string {\n return result.content.flatMap((block) => (block.type === \"text\" ? [block.text] : [])).join(\"\\n\");\n}\n"],"mappings":";;;;CASA,MAAM,QAAA,KAAA,YAEJ,KAAA;;;;;CAOF,OAAA,KAAS,MAAU,GAAA,GAAc,CAAA,CAAA,WAAuB,iBAAA,EAAA,IAAA,KAAA,MAAA,GAAA,CAAA,CAAA,WAAA,kBAAA,EAAA;AACtD;AAEF,MAAA,UAAA;;;;;CASA,OAAA;AACE;AASF,IAAA,iBAAA,cAAA,MAAA;;;;;;;;;AAgBA,SAAgB,WAAA,MAAa;CAC3B,IAAA,CAAA,UAAO,KAAa,KAAK,IAAA,GAAA,MAAW,IAAA,oBACjC,aAAsB,KACtB,UAAW,KAAA,IAAA,EAAA,cAAsB,WAAA;CACtC,IAAA,OAAA,KAAA,UAAA,YAAA,KAAA,UAAA,MAAA,MAAA,IAAA,oBAAA,GAAA,KAAA,KAAA,+FAAA;;;ACwDA;AAEA,SAAA,aAAA,UAAA,MAAA,OAAA,IAAA;;CAGA,IAAa,aAAA,IAAb,GAAA,MAAA,IAAoC,oBAAM,GAAA,SAAA,cAAA,GAAA,iDAAA;CACxC,IAAS,eAAO,IAAA,GAAA,MAAA,IAAA,oBAAA,GAAA,SAAA,yBAAA,GAAA,oBAAA;;AAEhB;;;CAKA,OAAA,KAAY,SAA0B,YAAA,eAAA,KAAA,KAAA,OAAA,KAAA,UAAA,CAAA,CAAA,SAAA,KAAA,KAAA,yBAAA;AACpC;AAEF,SAAA,eAAA,MAAA;CACF,MAAA,QAAA,KAAA;CAEA,OAAM,UAAY,KAAA,KAAA,MAAA,SAAA,KAAA,MAAA,OAAA,WAAA,WA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0 +1,15 @@
|
|
|
1
|
+
function hostContext(signal, onUpdate) {
|
|
2
|
+
return {
|
|
3
|
+
...signal ? { signal } : {},
|
|
4
|
+
...onUpdate ? { progress: (text) => onUpdate({
|
|
5
|
+
content: [{
|
|
6
|
+
type: "text",
|
|
7
|
+
text
|
|
8
|
+
}],
|
|
9
|
+
details: {}
|
|
10
|
+
}) } : {}
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
export { hostContext };
|
|
14
|
+
|
|
15
|
+
//# sourceMappingURL=updates.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"updates.mjs","names":[],"sources":["../../src/updates.ts"],"sourcesContent":["/** The call context Pi and OMP share: a signal and an `onUpdate` for partial results. */\n\nimport type { ToolCallContext, ToolContent } from \"./index.ts\";\n\n/** A partial result as `onUpdate` takes it in Pi and OMP. */\nexport interface PartialResult {\n readonly content: ToolContent[];\n readonly details: Readonly<Record<string, never>>;\n}\n\n/**\n * Turns the host's signal and `onUpdate` into a context, one text block per progress line.\n *\n * @param signal - The call's abort signal, if the host passed one.\n * @param onUpdate - The host's partial result callback, if it passed one.\n * @returns {ToolCallContext} Context for `invokeTool`.\n */\nexport function hostContext(\n signal: AbortSignal | undefined,\n onUpdate: ((partial: PartialResult) => void) | undefined,\n): ToolCallContext {\n return {\n ...(signal ? { signal } : {}),\n ...(onUpdate\n ? { progress: (text: string) => onUpdate({ content: [{ type: \"text\", text }], details: {} }) }\n : {}),\n };\n}\n"],"mappings":";;;;;;IAiBA;GAIE,CAAA;GACE,SAAI,CAAA;EACJ,CAAA,EAAI,IAAA,CAAA;CACyC;AAAY;AAAmB,SAAC"}
|
package/dist/ai.d.mts
CHANGED
|
@@ -25,6 +25,7 @@ export declare function toAiTool<Input extends TObject, Details>(definition: Too
|
|
|
25
25
|
*
|
|
26
26
|
* @param tools - Tools to convert.
|
|
27
27
|
* @returns {Record<string, Tool>} AI SDK tools.
|
|
28
|
+
* @throws {ToolDefinitionError} When two tools share a name.
|
|
28
29
|
*/
|
|
29
30
|
export declare function toAiTools(tools: readonly ToolDefinition[]): Record<string, Tool>;
|
|
30
31
|
//# sourceMappingURL=ai.d.mts.map
|
package/dist/ai.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ai.d.mts","names":[],"sources":["../src/ai.ts"],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"ai.d.mts","names":[],"sources":["../src/ai.ts"],"mappings":";;;;;;;YAwBY,aAAa,YAAY,yBAAyB;EAAY,SAAS;;EACjF;;;;;;;;;;;wBAYc,SAAS,cAAc,SAAS,SAC9C,YAAY,eAAe,OAAO,WACjC,KAAK,OAAO,QAAQ,aAAa;;;;;;;;wBA2CpB,UAAU,gBAAgB,mBAAmB,eAAe"}
|
package/dist/ai.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ToolDefinitionError, invokeTool, resultText, validateInput, wireSchema } from "./_chunks/src.mjs";
|
|
1
|
+
import { ToolDefinitionError, indexTools, invokeTool, resultText, validateInput, wireSchema } from "./_chunks/src.mjs";
|
|
2
2
|
import { jsonSchema, tool } from "ai";
|
|
3
3
|
function toAiTool(definition) {
|
|
4
4
|
return tool({
|
|
@@ -32,6 +32,7 @@ function toAiTool(definition) {
|
|
|
32
32
|
});
|
|
33
33
|
}
|
|
34
34
|
function toAiTools(tools) {
|
|
35
|
+
indexTools(tools);
|
|
35
36
|
return Object.fromEntries(tools.map((definition) => [definition.name, toAiTool(definition)]));
|
|
36
37
|
}
|
|
37
38
|
export { toAiTool, toAiTools };
|
package/dist/ai.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ai.mjs","names":[],"sources":["../src/ai.ts"],"sourcesContent":["/**\n * AI SDK adapter: turns {@link ToolDefinition}s into AI SDK tools.\n *\n * The TypeBox schema goes through `jsonSchema()` with the shared validator, so\n * a package needs no second schema in Zod.\n */\n\nimport { jsonSchema, tool, type Tool } from \"ai\";\nimport type { Static, TObject } from \"typebox\";\n\nimport {\n invokeTool,\n resultText,\n ToolDefinitionError,\n validateInput,\n wireSchema,\n type ToolDefinition,\n} from \"./index.ts\";\n\n/**\n * What an AI SDK tool returns: the executor's details with the text MCP\n * clients read. The AI SDK hands this object to the model as JSON.\n */\nexport type AiToolOutput<Details> = (Details extends object ? Details : { details: Details }) & {\n text: string;\n};\n\n/**\n * Converts one tool, keeping its input and details types.\n *\n * A result with `isError` throws its text, which the AI SDK reports to the\n * model as a tool error, the same as an executor that throws.\n *\n * @param definition - Tool to convert.\n * @returns {Tool} AI SDK tool.\n */\nexport function toAiTool<Input extends TObject, Details>(\n definition: ToolDefinition<Input, Details>,\n): Tool<Static<Input>, AiToolOutput<Details>> {\n // Built on concrete types and narrowed once on return: the AI SDK's\n // `NeverOptional` does not resolve for a generic output type.\n const built = tool({\n title: definition.title,\n description: definition.description,\n inputSchema: jsonSchema<unknown>(wireSchema(definition), {\n validate(value) {\n const checked = validateInput(definition, value);\n return checked.ok\n ? { success: true, value: checked.value }\n : { success: false, error: new Error(checked.lines.join(\"\\n\")) };\n },\n }),\n async execute(input, { abortSignal }): Promise<object> {\n const result = await invokeTool(\n definition,\n input,\n abortSignal ? { signal: abortSignal } : {},\n );\n const text = resultText(result);\n if (result.isError) throw new Error(text);\n const { details } = result;\n if (typeof details !== \"object\" || details === null) return { details, text };\n if (Object.hasOwn(details, \"text\")) {\n // The spread would overwrite one of the two without a sign.\n throw new ToolDefinitionError(\n `${definition.name}: details must not have a text field, the AI SDK output adds one`,\n );\n }\n return { ...details, text };\n },\n });\n return built as unknown as Tool<Static<Input>, AiToolOutput<Details>>;\n}\n\n/**\n * Builds an AI SDK tool set keyed by tool name.\n *\n * @param tools - Tools to convert.\n * @returns {Record<string, Tool>} AI SDK tools.\n */\nexport function toAiTools(tools: readonly ToolDefinition[]): Record<string, Tool> {\n return Object.fromEntries(tools.map((definition) => [definition.name, toAiTool(definition)]));\n}\n"],"mappings":";;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"ai.mjs","names":[],"sources":["../src/ai.ts"],"sourcesContent":["/**\n * AI SDK adapter: turns {@link ToolDefinition}s into AI SDK tools.\n *\n * The TypeBox schema goes through `jsonSchema()` with the shared validator, so\n * a package needs no second schema in Zod.\n */\n\nimport { jsonSchema, tool, type Tool } from \"ai\";\nimport type { Static, TObject } from \"typebox\";\n\nimport {\n indexTools,\n invokeTool,\n resultText,\n ToolDefinitionError,\n validateInput,\n wireSchema,\n type ToolDefinition,\n} from \"./index.ts\";\n\n/**\n * What an AI SDK tool returns: the executor's details with the text MCP\n * clients read. The AI SDK hands this object to the model as JSON.\n */\nexport type AiToolOutput<Details> = (Details extends object ? Details : { details: Details }) & {\n text: string;\n};\n\n/**\n * Converts one tool, keeping its input and details types.\n *\n * A result with `isError` throws its text, which the AI SDK reports to the\n * model as a tool error, the same as an executor that throws.\n *\n * @param definition - Tool to convert.\n * @returns {Tool} AI SDK tool.\n */\nexport function toAiTool<Input extends TObject, Details>(\n definition: ToolDefinition<Input, Details>,\n): Tool<Static<Input>, AiToolOutput<Details>> {\n // Built on concrete types and narrowed once on return: the AI SDK's\n // `NeverOptional` does not resolve for a generic output type.\n const built = tool({\n title: definition.title,\n description: definition.description,\n inputSchema: jsonSchema<unknown>(wireSchema(definition), {\n validate(value) {\n const checked = validateInput(definition, value);\n return checked.ok\n ? { success: true, value: checked.value }\n : { success: false, error: new Error(checked.lines.join(\"\\n\")) };\n },\n }),\n async execute(input, { abortSignal }): Promise<object> {\n const result = await invokeTool(\n definition,\n input,\n abortSignal ? { signal: abortSignal } : {},\n );\n const text = resultText(result);\n if (result.isError) throw new Error(text);\n const { details } = result;\n if (typeof details !== \"object\" || details === null) return { details, text };\n if (Object.hasOwn(details, \"text\")) {\n // The spread would overwrite one of the two without a sign.\n throw new ToolDefinitionError(\n `${definition.name}: details must not have a text field, the AI SDK output adds one`,\n );\n }\n return { ...details, text };\n },\n });\n return built as unknown as Tool<Static<Input>, AiToolOutput<Details>>;\n}\n\n/**\n * Builds an AI SDK tool set keyed by tool name.\n *\n * @param tools - Tools to convert.\n * @returns {Record<string, Tool>} AI SDK tools.\n * @throws {ToolDefinitionError} When two tools share a name.\n */\nexport function toAiTools(tools: readonly ToolDefinition[]): Record<string, Tool> {\n indexTools(tools);\n return Object.fromEntries(tools.map((definition) => [definition.name, toAiTool(definition)]));\n}\n"],"mappings":";;;;;;;;;;;;;;;EAqCA,EAAA,CAAA;EAmCE,MA9Bc,QAAK,OAAA,EAAA,eAAA;GACjB,MAAO,SAAA,MAAW,WAAA,YAAA,OAAA,cAAA,EAAA,QAAA,YAAA,IAAA,CAAA,CAAA;GAClB,MAAA,OAAa,WAAW,MAAA;GACxB,IAAA,OAAA,SAAa,MAAoB,IAAA,MAAW,IAAA;GAExC,MAAM,EAAA,YAAU;GAChB,IAAA,OAAO,YACH,YAAA,YAAA,MAAA,OAAA;IAAE;IAAe;GAAqB;GACpC,IAAA,OAAS,OAAA,SAAA,MAAA,GAAA,MAAA,IAAA,oBAAA,GAAA,WAAA,KAAA,iEAAA;GAAO,OAAA;IAA2C,GAAA;IAErE;GACA;EACE;CAKA,CAAA;AACA;AAEA,SAAI,UAAO,OAAY;CAAuC,WAAA,KAAA;CAAS,OAAA,OAAA,YAAA,MAAA,KAAA,eAAA,CAAA,WAAA,MAAA,SAAA,UAAA,CAAA,CAAA,CAAA;AAAK;AAO5E,SAAA,UAAO"}
|
package/dist/cli.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.d.mts","names":[],"sources":["../src/cli.ts"],"mappings":";iBA0BiB;;WAEN;WACA;WACA;WACA,gBAAgB;;;;;;;WAOhB,oBAAoB;;WAEpB;;WAEA;;WAEA;;;;;WAKA,YAAY;;;;;;wBA8CP,YAAY,MAAM;;
|
|
1
|
+
{"version":3,"file":"cli.d.mts","names":[],"sources":["../src/cli.ts"],"mappings":";iBA0BiB;;WAEN;WACA;WACA;WACA,gBAAgB;;;;;;;WAOhB,oBAAoB;;WAEpB;;WAEA;;WAEA;;;;;WAKA,YAAY;;;;;;wBA8CP,YAAY,MAAM;;iBA8mBjB;;EAEf,IAAI,0BAA0B;;;;;;;;;;wBAWhB,UAAU,SAAS,aAAa;;;;;;;;;;;wBA6BhC,cAAc,SAAS,YAAY;;;;;;;;wBAgK7B,OACpB,SAAS,YACT,2BACC"}
|
package/dist/cli.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Convert } from "./_chunks/libs/typebox.mjs";
|
|
2
|
-
import { ToolDefinitionError, ToolInputError, indexTools, invokeTool, resultText, sanitizeLine,
|
|
2
|
+
import { ToolDefinitionError, ToolInputError, indexTools, invokeTool, resultText, sanitizeLine, sanitizeText } 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.-]*$/;
|
|
@@ -216,10 +216,6 @@ function toolInput(tool, fields, values) {
|
|
|
216
216
|
if (errors.length > 0) throw new ToolInputError(errors);
|
|
217
217
|
return Convert(tool.input, input);
|
|
218
218
|
}
|
|
219
|
-
const FORGING = /[\u0000-\u0008\u000B-\u001F\u007F-\u009F\u061C\u200E\u200F\u202A-\u202E\u2066-\u206F]/g;
|
|
220
|
-
function sanitizeText(text) {
|
|
221
|
-
return stripEscapes(text.replaceAll(/\r\n?/g, "\n")).replaceAll(FORGING, "").replaceAll(/[\u2028\u2029]/g, " ");
|
|
222
|
-
}
|
|
223
219
|
function writeLine(stream, text) {
|
|
224
220
|
process[stream].write(text.endsWith("\n") ? text : `${text}\n`);
|
|
225
221
|
}
|
package/dist/cli.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.mjs","names":["Value.Convert"],"sources":["../src/cli.ts"],"sourcesContent":["/**\n * CLI adapter: one command per {@link ToolDefinition}, plus the package's own\n * commands and an optional stdio MCP server, with no CLI library underneath.\n *\n * A tool's properties become flags, its {@link ToolCliHints} pick positional\n * arguments and stdin, and every call goes through {@link invokeTool}, so the\n * command line validates and fails like every other surface. A package\n * command is a tool definition too, one that only the CLI gets.\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { parseArgs } from \"node:util\";\n\nimport { Value } from \"typebox/value\";\n\nimport { stripEscapes } from \"./escapes.ts\";\nimport {\n indexTools,\n invokeTool,\n resultText,\n sanitizeLine,\n ToolDefinitionError,\n ToolInputError,\n type ToolDefinition,\n} from \"./index.ts\";\n\nexport interface CliOptions {\n /** Executable name, also the MCP server name. */\n readonly name: string;\n readonly version: string;\n readonly description: string;\n readonly tools: readonly ToolDefinition[];\n /**\n * The package's own commands, as tool definitions that only the CLI gets:\n * no MCP, Pi, OMP or AI SDK host sees them. One whose command name matches\n * a generated command, `mcp` included, takes its place. A command that\n * needs bytes, not text, reads `-` from stdin itself in `execute`.\n */\n readonly commands?: readonly ToolDefinition[];\n /** Command for an empty command line. */\n readonly default?: string;\n /** Command for a first word that names no command: `hashes sha256 x` runs `hashes hash sha256 x`. */\n readonly fallback?: string;\n /** Adds `mcp`, the tools as an MCP server over stdio. */\n readonly mcp?: boolean;\n /**\n * Errors the package throws on purpose. They print as one line with exit\n * code 1; any other error keeps its stack trace.\n */\n readonly expected?: (error: unknown) => boolean;\n}\n\n/** A flag `--<flag>` can spell: not empty, no `=`, no space or control, not starting with `-`. */\nconst FLAG_WORD = /^[a-z0-9][a-z0-9.-]*$/;\n\n/** Flags every tool command answers itself. */\nconst RESERVED_FLAGS = new Set([\"help\", \"version\", \"json\"]);\n\ntype FieldKind = \"string\" | \"number\" | \"boolean\" | \"enum\" | \"json\";\n\ninterface Field {\n readonly key: string;\n readonly schema: SchemaNode;\n readonly required: boolean;\n readonly flag: string;\n readonly kind: FieldKind;\n readonly positional: boolean;\n readonly stdin: boolean;\n}\n\ntype SchemaNode = Readonly<Record<string, unknown>>;\n\nconst TYPE_KINDS = new Map<unknown, FieldKind>([\n [\"boolean\", \"boolean\"],\n [\"integer\", \"number\"],\n [\"number\", \"number\"],\n [\"object\", \"json\"],\n [\"array\", \"json\"],\n]);\n\n/**\n * @param key - Property name, `camelCase` or `snake_case`.\n * @returns {string} The flag, in kebab case.\n */\nfunction flagName(key: string): string {\n return key\n .replaceAll(/([a-z0-9])([A-Z])/g, \"$1-$2\")\n .replaceAll(\"_\", \"-\")\n .toLowerCase();\n}\n\n/**\n * @param tool - Tool to name.\n * @returns {string} The hinted command, or the tool name without its package prefix, in kebab case.\n */\nexport function commandName(tool: ToolDefinition): string {\n if (tool.cli?.command !== undefined) return commandWord(tool.name, tool.cli.command);\n const separator = tool.name.indexOf(\"_\");\n const derived = separator === -1 ? tool.name : tool.name.slice(separator + 1);\n // `pkg__h` would derive `-h` and `pkg_` nothing; neither can be dispatched.\n return commandWord(tool.name, derived.replaceAll(\"_\", \"-\"));\n}\n\n/** A command word the CLI can dispatch to: not empty, not an option, nothing that forges a line. */\nconst COMMAND_WORD = /^[a-z0-9_][a-z0-9_.:-]*$/i;\n\n/**\n * @param owner - Tool or CLI the name belongs to, for the error.\n * @param word - Command name or alias.\n * @returns {string} The word, checked.\n * @throws {ToolDefinitionError} When no command line could reach it.\n */\nfunction commandWord(owner: string, word: string): string {\n if (!COMMAND_WORD.test(word)) {\n throw new ToolDefinitionError(\n `${owner}: command ${JSON.stringify(word)} must match ${COMMAND_WORD}`,\n );\n }\n return word;\n}\n\n/**\n * How a value for this property is read from one command line word.\n *\n * @param schema - Property schema.\n * @returns {FieldKind} The reading.\n */\nfunction fieldKind(schema: SchemaNode): FieldKind {\n if (Array.isArray(schema.enum) && schema.enum.every((value) => typeof value === \"string\")) {\n return \"enum\";\n }\n const branches = Array.isArray(schema.anyOf) ? (schema.anyOf as readonly SchemaNode[]) : [];\n if (branches.some((branch) => fieldKind(branch) === \"json\")) return \"json\";\n return TYPE_KINDS.get(schema.type) ?? \"string\";\n}\n\n/**\n * Reads a tool's schema and hints into command line fields.\n *\n * @param tool - Tool to read.\n * @returns {Field[]} One field per property, positional ones in hint order first.\n * @throws {ToolDefinitionError} When a hint names a property the tool lacks, or two properties share a flag.\n */\nfunction toolFields(tool: ToolDefinition): Field[] {\n const properties = tool.input.properties as Readonly<Record<string, SchemaNode>>;\n const positional = tool.cli?.positional ?? [];\n const stdin = tool.cli?.stdin ?? [];\n for (const key of [...positional, ...stdin]) {\n if (!Object.hasOwn(properties, key)) {\n throw new ToolDefinitionError(`${tool.name}: cli hint names unknown property ${key}`);\n }\n }\n const repeated = positional.find((key, index) => positional.indexOf(key) !== index);\n if (repeated !== undefined) {\n throw new ToolDefinitionError(`${tool.name}: cli hint lists positional ${repeated} twice`);\n }\n\n const keys = [\n ...positional,\n ...Object.keys(properties).filter((key) => !positional.includes(key)),\n ];\n const required = (tool.input.required as readonly string[] | undefined) ?? [];\n const flags = new Set<string>();\n const fields = keys.map((key): Field => {\n const field: Field = {\n key,\n schema: properties[key] ?? {},\n required: required.includes(key),\n flag: flagName(key),\n kind: fieldKind(properties[key] ?? {}),\n positional: positional.includes(key),\n stdin: stdin.includes(key),\n };\n assertField(tool, field, !field.positional && flags.has(field.flag));\n if (!field.positional) flags.add(field.flag);\n return field;\n });\n assertOneOptionPerSpelling(tool, fields);\n assertRequiredPositionalsFirst(tool, fields);\n return fields;\n}\n\n/**\n * @param tool - Tool the field belongs to.\n * @param field - Field to check.\n * @throws {ToolDefinitionError} When no word can spell the flag, or it is reserved or reads as a negation.\n */\nfunction assertFlag(tool: ToolDefinition, field: Field): void {\n if (!FLAG_WORD.test(field.flag)) {\n throw new ToolDefinitionError(\n `${tool.name}: property ${JSON.stringify(field.key)} gives the flag ${JSON.stringify(field.flag)}, which must match ${FLAG_WORD}`,\n );\n }\n if (field.kind === \"boolean\" && field.flag.startsWith(\"no-\")) {\n // `util.parseArgs` reads `--no-cache` as `cache` negated, never as a flag `no-cache`.\n throw new ToolDefinitionError(\n `${tool.name}: boolean property ${field.key} cannot take a flag starting with no-; name the positive and --no-${field.flag.slice(3)} negates it`,\n );\n }\n if (RESERVED_FLAGS.has(field.flag)) {\n throw new ToolDefinitionError(\n `${tool.name}: property ${field.key} takes the reserved flag --${field.flag}`,\n );\n }\n}\n\n/**\n * @param tool - Tool the field belongs to.\n * @param field - Field to check.\n * @param taken - Whether an option before it has the same flag.\n * @throws {ToolDefinitionError} When no word can spell the flag, it is reserved or taken, or a hint does not fit the field.\n */\nfunction assertField(tool: ToolDefinition, field: Field, taken: boolean): void {\n // A positional is never an option: its key needs no flag spelling.\n if (!field.positional) assertFlag(tool, field);\n if (taken) {\n throw new ToolDefinitionError(`${tool.name}: two properties take the flag --${field.flag}`);\n }\n if (field.positional && field.kind === \"boolean\") {\n throw new ToolDefinitionError(\n `${tool.name}: boolean property ${field.key} cannot be positional`,\n );\n }\n if (field.stdin && field.kind !== \"string\") {\n throw new ToolDefinitionError(`${tool.name}: stdin property ${field.key} must be a string`);\n }\n}\n\n/**\n * Words fill the positionals in order, so an optional one before a required\n * one would take the only word given and leave the required one empty.\n *\n * @param tool - Tool the fields belong to.\n * @param fields - The tool's fields.\n * @throws {ToolDefinitionError} When an optional positional comes before a required one.\n */\nfunction assertRequiredPositionalsFirst(tool: ToolDefinition, fields: readonly Field[]): void {\n const positional = fields.filter((field) => field.positional);\n const optional = positional.findIndex((field) => !field.required);\n const late = positional\n .slice(optional === -1 ? positional.length : optional)\n .find((field) => field.required);\n if (late !== undefined) {\n throw new ToolDefinitionError(\n `${tool.name}: required positional ${late.key} comes after an optional one`,\n );\n }\n}\n\n/**\n * Every spelling the CLI reads for an option names one property: a boolean also\n * answers to `--no-<flag>`, so a boolean `cache` and a property `noCache`\n * would both claim `--no-cache`.\n *\n * @param tool - Tool the fields belong to.\n * @param fields - The tool's fields.\n * @throws {ToolDefinitionError} When two options share a spelling.\n */\nfunction assertOneOptionPerSpelling(tool: ToolDefinition, fields: readonly Field[]): void {\n const owners = new Map<string, string>();\n for (const field of fields.filter((each) => !each.positional)) {\n const negation = field.kind === \"boolean\" ? [`no-${field.flag}`] : [];\n for (const spelling of [field.flag, ...negation]) {\n const owner = owners.get(spelling);\n if (owner !== undefined) {\n throw new ToolDefinitionError(\n `${tool.name}: properties ${owner} and ${field.key} both answer to --${spelling}`,\n );\n }\n owners.set(spelling, field.key);\n }\n }\n}\n\n/**\n * @param field - Field to describe.\n * @returns {string} Its line in the usage text, after the flag.\n */\nfunction fieldDescription(field: Field): string {\n const { schema } = field;\n return [\n typeof schema.description === \"string\" ? schema.description : \"\",\n field.stdin ? \"(- reads stdin)\" : \"\",\n field.required ? \"(required)\" : \"\",\n ]\n .filter((part) => part !== \"\")\n .join(\" \");\n}\n\n/**\n * @param field - Option field.\n * @returns {string} What the value looks like in the usage text.\n */\nfunction valueHint(field: Field): string {\n if (field.kind === \"enum\") return (field.schema.enum as string[]).join(\"|\");\n return field.kind === \"string\" ? field.flag : field.kind;\n}\n\n/**\n * A record without a prototype: a property named `toString` reads as unset\n * instead of `Object.prototype.toString`, and `__proto__` is a plain key.\n *\n * @returns {Record<string, T>} An empty record.\n */\nfunction emptyRecord<T>(): Record<string, T> {\n return Object.create(null) as Record<string, T>;\n}\n\ninterface ParsedWords {\n /** Raw values by property: a string, or `true`/`false` for a boolean. */\n readonly values: Readonly<Record<string, string | boolean>>;\n readonly json: boolean;\n /** `--help` or `-h` before any `--`; a value or a word after `--` is not one. */\n readonly help: boolean;\n readonly errors: readonly string[];\n}\n\n/**\n * Reads the words after the command name, on `util.parseArgs` tokens. Only\n * `--flag`, `--flag=value` and, for a boolean, `--no-flag` are options;\n * an unknown option, a single dash before a name, a missing value, a value\n * given twice or a positional too many is a failure, never a skipped word.\n *\n * @param rawArgs - Words after the command name.\n * @param fields - The command's fields.\n * @param takesJson - Whether the command takes `--json`.\n * @returns {ParsedWords} Values by property and the failures, one per line.\n */\nfunction parseWords(\n rawArgs: readonly string[],\n fields: readonly Field[],\n takesJson: boolean,\n): ParsedWords {\n const entries: Array<[string, Field | \"json\"]> = [\n ...fields\n .filter((field) => !field.positional)\n .map((field): [string, Field] => [field.flag, field]),\n ...(takesJson ? [[\"json\", \"json\"] as [string, \"json\"]] : []),\n ];\n const options: Readonly<Record<string, Field | \"json\">> = Object.fromEntries(entries);\n const { tokens } = parseArgs({\n args: [...rawArgs],\n options: Object.fromEntries(\n Object.entries(options).map(([flag, field]) => [\n flag,\n { type: field === \"json\" || field.kind === \"boolean\" ? \"boolean\" : \"string\" },\n ]),\n ) as Record<string, { type: \"boolean\" | \"string\" }>,\n strict: false,\n allowPositionals: true,\n allowNegative: true,\n tokens: true,\n });\n\n const values = emptyRecord<string | boolean>();\n const errors: string[] = [];\n const positionals: string[] = [];\n const flags = new Set<string>();\n for (const token of tokens) {\n if (token.kind === \"positional\") positionals.push(token.value);\n if (token.kind !== \"option\") continue;\n const read = readOption(options, token, rawArgs[token.index] ?? \"\", Object.keys(values));\n if (\"error\" in read) errors.push(read.error);\n else if (\"flag\" in read) flags.add(read.flag);\n else values[read.key] = read.value;\n }\n return {\n values: Object.assign(values, positionalValues(fields, positionals)),\n json: flags.has(\"json\"),\n help: flags.has(\"help\"),\n errors: [...new Set(errors.length > 0 ? errors : extraPositionals(fields, positionals))],\n };\n}\n\n/**\n * @param fields - The command's fields.\n * @param positionals - Positional words in order.\n * @returns {Record<string, string>} Each positional property with its word.\n */\nfunction positionalValues(\n fields: readonly Field[],\n positionals: readonly string[],\n): Record<string, string> {\n const takes = fields.filter((field) => field.positional);\n return Object.assign(\n emptyRecord<string>(),\n Object.fromEntries(\n takes.flatMap((field, index) => {\n const value = positionals[index];\n return value === undefined ? [] : [[field.key, value]];\n }),\n ),\n );\n}\n\n/**\n * @param fields - The command's fields.\n * @param positionals - Positional words in order.\n * @returns {string[]} The failure when there are more words than positional properties.\n */\nfunction extraPositionals(fields: readonly Field[], positionals: readonly string[]): string[] {\n const extra = positionals.length - fields.filter((field) => field.positional).length;\n if (extra <= 0) return [];\n return [`Invalid arguments: ${extra} unexpected positional argument${extra === 1 ? \"\" : \"s\"}`];\n}\n\ninterface OptionToken {\n readonly name: string;\n readonly rawName: string;\n readonly value?: string | undefined;\n readonly inlineValue?: boolean | undefined;\n}\n\ntype OptionRead =\n | { readonly error: string }\n | { readonly flag: \"json\" | \"help\" }\n | { readonly key: string; readonly value: string | boolean };\n\n/**\n * `-xh` expands to `-x` and `-h`; only the whole word `-h` asks for help.\n *\n * @param token - The token `util.parseArgs` made.\n * @param word - The command line word it came from.\n * @returns {boolean} Whether the token is `--help` or the word `-h`.\n */\nfunction asksHelp(token: OptionToken, word: string): boolean {\n return token.rawName === \"--help\" || word === \"-h\";\n}\n\n/**\n * @param options - Option fields by flag, and `--json` when the command takes it.\n * @param token - The token `util.parseArgs` made.\n * @param word - The command line word it came from.\n * @returns {Field | \"json\" | \"help\" | undefined} What the token names under a spelling it takes.\n */\nfunction optionField(\n options: Readonly<Record<string, Field | \"json\">>,\n token: OptionToken,\n word: string,\n): Field | \"json\" | \"help\" | undefined {\n if (asksHelp(token, word)) return \"help\";\n const field = Object.hasOwn(options, token.name) ? options[token.name] : undefined;\n if (field === \"json\") return token.rawName === \"--json\" ? field : undefined;\n if (field === undefined || token.rawName === `--${token.name}`) return field;\n return token.rawName === `--no-${token.name}` && field.kind === \"boolean\" ? field : undefined;\n}\n\n/**\n * @param options - Option fields by flag, and `--json` when the command takes it.\n * @param token - The token `util.parseArgs` made.\n * @param word - The command line word it came from.\n * @param seen - Properties set by earlier words.\n * @returns {OptionRead} The value it sets, `--json`, or the failure.\n */\nfunction readOption(\n options: Readonly<Record<string, Field | \"json\">>,\n token: OptionToken,\n word: string,\n seen: readonly string[],\n): OptionRead {\n const field = optionField(options, token, word);\n if (field === undefined) {\n const flags = Object.keys(options).map((flag) => `--${flag}`);\n const takes = flags.length > 0 ? flags.join(\", \") : \"no options\";\n return { error: `Invalid arguments: unknown option ${JSON.stringify(word)}; takes ${takes}` };\n }\n if (field === \"json\" || field === \"help\") {\n return token.inlineValue === true\n ? { error: `Invalid arguments: ${token.rawName} takes no value` }\n : { flag: field };\n }\n const problem = optionProblem(field, token, seen.includes(field.key));\n if (problem !== undefined) return { error: `Invalid arguments: --${field.flag} ${problem}` };\n const value = field.kind === \"boolean\" ? token.rawName === `--${field.flag}` : token.value;\n return { key: field.key, value: value ?? \"\" };\n}\n\n/**\n * @param field - The option's field.\n * @param token - Its token.\n * @param seen - Whether an earlier word set the property already.\n * @returns {string | undefined} What is wrong with the option, if anything.\n */\nfunction optionProblem(field: Field, token: OptionToken, seen: boolean): string | undefined {\n if (seen) return \"given more than once\";\n if (field.kind === \"boolean\") return token.inlineValue === true ? \"takes no value\" : undefined;\n return token.value === undefined ? \"needs a value\" : undefined;\n}\n\n/**\n * Reads stdin as strict UTF-8. A lenient decode would turn each invalid byte\n * into U+FFFD, and a tool hashing or encoding the text would answer for other\n * input without a word; binary data needs a command of the package's own.\n *\n * @returns {string | undefined} The text, or nothing when stdin is not UTF-8.\n */\nfunction readStdin(): string | undefined {\n try {\n return new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true }).decode(readFileSync(0));\n } catch (error) {\n if (error instanceof TypeError) return undefined;\n throw error;\n }\n}\n\n/**\n * @param field - Field the word belongs to.\n * @param raw - What {@link parseWords} read for it.\n * @returns {{ value: unknown } | { error: string }} The value before TypeBox conversion, or why there is none.\n */\nfunction fieldValue(field: Field, raw: unknown): { value: unknown } | { error: string } {\n if (field.stdin && raw === \"-\") {\n const text = readStdin();\n return text === undefined ? { error: \"stdin is not UTF-8 text\" } : { value: text };\n }\n if (field.kind !== \"json\" || typeof raw !== \"string\") return { value: raw };\n try {\n return { value: JSON.parse(raw) as unknown };\n } catch {\n return { error: \"must be JSON\" };\n }\n}\n\n/**\n * Builds the tool input from parsed arguments. Numbers and booleans in the\n * schema are converted from their text by TypeBox; objects and arrays are\n * JSON. The result still goes through {@link invokeTool} validation.\n *\n * @param tool - Tool to call.\n * @param fields - The command's fields.\n * @param values - Raw values by property, from {@link parseWords}.\n * @returns {unknown} The input object.\n * @throws {ToolInputError} When a JSON value does not parse.\n */\nfunction toolInput(\n tool: ToolDefinition,\n fields: readonly Field[],\n values: Readonly<Record<string, string | boolean>>,\n): unknown {\n const input = emptyRecord<unknown>();\n const fromStdin = fields.filter((field) => field.stdin && values[field.key] === \"-\");\n if (fromStdin.length > 1) {\n throw new ToolInputError([\n `Invalid arguments: stdin can feed one argument, not ${fromStdin.map((field) => field.key).join(\" and \")}`,\n ]);\n }\n const errors: string[] = [];\n for (const field of fields) {\n const raw = values[field.key];\n if (raw === undefined) continue;\n const read = fieldValue(field, raw);\n if (\"error\" in read) errors.push(`Invalid arguments at /${field.key}: ${read.error}`);\n else input[field.key] = read.value;\n }\n if (errors.length > 0) throw new ToolInputError(errors);\n return Value.Convert(tool.input, input);\n}\n\n/** C0 and C1 controls but tab and line feed, and the bidi marks, embeddings, overrides and isolates. */\nconst FORGING =\n /* oxlint-disable-next-line no-control-regex */\n /[\\u0000-\\u0008\\u000B-\\u001F\\u007F-\\u009F\\u061C\\u200E\\u200F\\u202A-\\u202E\\u2066-\\u206F]/g;\n\n/**\n * Makes multi-line tool text safe for a terminal. Unlike {@link sanitizeLine}\n * it keeps the layout: line feeds, tabs and the joiners of emoji and scripts\n * (ZWJ, ZWNJ) stay, CR and CRLF become a line feed, and the Unicode line and\n * paragraph separators become a space so words do not run together.\n *\n * @param text - Tool text.\n * @returns {string} The text without escape sequences or other control characters.\n */\nfunction sanitizeText(text: string): string {\n return stripEscapes(text.replaceAll(/\\r\\n?/g, \"\\n\"))\n .replaceAll(FORGING, \"\")\n .replaceAll(/[\\u2028\\u2029]/g, \" \");\n}\n\n/**\n * @param stream - Where to write.\n * @param text - Text, given a trailing newline when it lacks one.\n */\nfunction writeLine(stream: \"stdout\" | \"stderr\", text: string): void {\n process[stream].write(text.endsWith(\"\\n\") ? text : `${text}\\n`);\n}\n\n/**\n * Prints an error the CLI expects and sets exit code 1.\n *\n * @param lines - Failure lines.\n */\nfunction fail(lines: readonly string[]): void {\n writeLine(\"stderr\", lines.map(sanitizeLine).join(\"\\n\"));\n process.exitCode = 1;\n}\n\n/**\n * Turns expected errors into {@link fail}; any other error goes on with its stack.\n *\n * @param options - CLI options.\n * @param error - What the command threw.\n */\nfunction handleError(options: CliOptions, error: unknown): void {\n if (error instanceof ToolInputError) fail(error.lines);\n else if (options.expected?.(error) === true) {\n fail([error instanceof Error ? error.message : String(error)]);\n } else throw error;\n}\n\n/**\n * @param details - Tool details.\n * @returns {string} Pretty JSON; a bigint becomes its decimal string, no details `null`.\n */\nfunction detailsJson(details: unknown): string {\n // `JSON.stringify` answers `undefined`, not a string, for undefined details.\n const json =\n (JSON.stringify(\n details,\n (_key, value: unknown) => (typeof value === \"bigint\" ? value.toString() : value),\n 2,\n ) as string | undefined) ?? \"null\";\n return json.replaceAll(\n JSON_FORGING,\n (character) => `\\\\u${(character.codePointAt(0) ?? 0).toString(16).padStart(4, \"0\")}`,\n );\n}\n\n/**\n * What `JSON.stringify` leaves literal although a terminal acts on it: DEL and\n * C1, the bidi marks, overrides and isolates, and the Unicode line and\n * paragraph separators. They only occur inside strings, so a `\\u` escape\n * keeps the parsed details the same.\n */\nconst JSON_FORGING =\n /* oxlint-disable-next-line no-control-regex */\n /[\\u007F-\\u009F\\u061C\\u200E\\u200F\\u2028\\u2029\\u202A-\\u202E\\u2066-\\u206F]/g;\n\n/** One command the CLI dispatches to: a tool, a package command or `mcp`. */\ninterface Command {\n readonly name: string;\n readonly aliases: readonly string[];\n /** Line in the command list. */\n readonly summary: string;\n readonly fields: readonly Field[];\n /** Takes `--json`: a tool command prints its details; `mcp` has none. */\n readonly json: boolean;\n run(words: ParsedWords): Promise<void>;\n}\n\n/**\n * @param tool - Tool or package command to run.\n * @returns {Command} The command calling it.\n */\nfunction toolCommand(tool: ToolDefinition): Command {\n const fields = toolFields(tool);\n const [summary = tool.title] = tool.description.split(/(?<=[.!?])\\s/, 1);\n return {\n name: commandName(tool),\n aliases: (tool.cli?.aliases ?? []).map((alias) => commandWord(tool.name, alias)),\n summary: tool.cli?.description ?? summary,\n fields,\n json: true,\n async run(words) {\n const result = await invokeTool(tool, toolInput(tool, fields, words.values));\n if (result.isError === true) {\n writeLine(\"stderr\", sanitizeText(resultText(result)));\n process.exitCode = 1;\n } else if (words.json) {\n writeLine(\"stdout\", detailsJson(result.details));\n } else {\n writeLine(\"stdout\", sanitizeText(resultText(result)));\n const images = result.content.filter((block) => block.type === \"image\").length;\n if (images > 0) writeLine(\"stderr\", `(${images} image block(s) not printed)`);\n }\n },\n };\n}\n\n/**\n * @param options - CLI options.\n * @returns {Command} The stdio MCP server command.\n */\nfunction mcpCommand(options: CliOptions): Command {\n return {\n name: \"mcp\",\n aliases: [],\n summary: `Run the ${options.name} MCP server over stdio`,\n fields: [],\n json: false,\n async run() {\n const [{ createMcpServer }, { StdioServerTransport }] = await Promise.all([\n import(\"./mcp.ts\"),\n import(\"@modelcontextprotocol/server/stdio\"),\n ]);\n await createMcpServer(options, options.tools).connect(new StdioServerTransport());\n },\n };\n}\n\n/**\n * The definitions behind the commands, in listing order: the tools, each\n * replaced in place by a package command of its command name, then the rest\n * of the package commands.\n *\n * @param options - CLI options.\n * @returns {ToolDefinition[]} One definition per command but `mcp`.\n */\nfunction commandTools(options: CliOptions): ToolDefinition[] {\n const own = options.commands ?? [];\n const byName = new Map(own.map((command) => [commandName(command), command]));\n const listed = options.tools.map((tool) => byName.get(commandName(tool)) ?? tool);\n return [...listed, ...own.filter((command) => !listed.includes(command))];\n}\n\n/**\n * @param options - CLI options.\n * @returns {boolean} Whether the built-in `mcp` command is on and no package command replaces it.\n */\nfunction builtInMcp(options: CliOptions): boolean {\n return (\n options.mcp === true &&\n !(options.commands ?? []).some((command) => commandName(command) === \"mcp\")\n );\n}\n\n/**\n * @param options - CLI options.\n * @returns {string[]} Every command name and alias, `mcp` included when built in.\n */\nfunction commandWords(options: CliOptions): string[] {\n return [\n ...commandTools(options).flatMap((tool) => [commandName(tool), ...(tool.cli?.aliases ?? [])]),\n ...(builtInMcp(options) ? [\"mcp\"] : []),\n ];\n}\n\n/** A built command line interface. */\nexport interface Cli {\n /** Runs one command line: the words after the executable and script. */\n run(argv: readonly string[]): Promise<void>;\n}\n\n/**\n * Builds the commands and checks every definition, so a broken hint fails at\n * startup and not on the first call that reaches it.\n *\n * @param options - CLI options.\n * @returns {Cli} The CLI.\n * @throws {ToolDefinitionError} When two commands share a name or alias, a hint does not fit its schema, or `default` or `fallback` names no command.\n */\nexport function createCli(options: CliOptions): Cli {\n indexTools(options.tools);\n indexTools(options.commands ?? []);\n const commands = [\n ...commandTools(options).map((tool) => toolCommand(tool)),\n ...(builtInMcp(options) ? [mcpCommand(options)] : []),\n ];\n const words = commandWords(options);\n const repeated = words.find((word, index) => words.indexOf(word) !== index);\n if (repeated !== undefined) throw new ToolDefinitionError(`Two commands are named ${repeated}`);\n const missing = [options.default, options.fallback].find(\n (name) => name !== undefined && !words.includes(name),\n );\n if (missing !== undefined)\n throw new ToolDefinitionError(`${options.name}: no command ${missing}`);\n\n return { run: (argv) => dispatch(options, commands, normalizeArgv(options, argv)) };\n}\n\n/**\n * Applies `default` and `fallback`: an empty command line runs `default`, and\n * a first word that names no command goes to `fallback` as its first\n * argument. A leading option such as `--help` stays at the root; a lone `-`\n * is the stdin word of the fallback's positional, not an option.\n *\n * @param options - CLI options.\n * @param argv - Words after the executable and script.\n * @returns {string[]} The words to dispatch.\n */\nexport function normalizeArgv(options: CliOptions, argv: readonly string[]): string[] {\n const [first] = argv;\n if (first === undefined) return options.default === undefined ? [] : [options.default];\n const option = first.startsWith(\"-\") && first !== \"-\";\n if (options.fallback === undefined || option || commandWords(options).includes(first)) {\n return [...argv];\n }\n return [options.fallback, ...argv];\n}\n\n/**\n * Picks the command by its first word and runs it. `--help` and `-h` count\n * only where the parse finds an option: after `--` or as an option's value\n * they are the tool's words. Every error line goes through\n * {@link sanitizeLine}, an unknown word inside `JSON.stringify`.\n *\n * @param options - CLI options.\n * @param commands - The commands.\n * @param argv - Words after {@link normalizeArgv}.\n */\nasync function dispatch(\n options: CliOptions,\n commands: readonly Command[],\n argv: readonly string[],\n): Promise<void> {\n const [first, ...rest] = argv;\n if (argv.length === 1 && (first === \"--version\" || first === \"-v\")) {\n writeLine(\"stdout\", sanitizeLine(options.version));\n } else if (first === \"--help\" || first === \"-h\") {\n writeLine(\"stdout\", sanitizeText(mainUsage(options, commands)));\n } else if (first === undefined) {\n writeLine(\"stderr\", sanitizeText(mainUsage(options, commands)));\n fail([\"No command specified\"]);\n } else {\n const command = commands.find((each) => each.name === first || each.aliases.includes(first));\n if (command === undefined) {\n fail([\n `Unknown command ${JSON.stringify(first)}`,\n `Run ${options.name} --help for the commands`,\n ]);\n } else {\n await runCommand(options, command, rest);\n }\n }\n}\n\n/**\n * @param options - CLI options.\n * @param command - The chosen command.\n * @param rawArgs - Words after the command name.\n */\nasync function runCommand(\n options: CliOptions,\n command: Command,\n rawArgs: readonly string[],\n): Promise<void> {\n const words = parseWords(rawArgs, command.fields, command.json);\n if (words.help) {\n writeLine(\"stdout\", sanitizeText(commandUsage(options, command)));\n return;\n }\n try {\n if (words.errors.length > 0) throw new ToolInputError(words.errors);\n await command.run(words);\n } catch (error) {\n handleError(options, error);\n }\n}\n\n/**\n * @param rows - Left and right column of each row.\n * @returns {string[]} The rows, indented, with the right column aligned.\n */\nfunction table(rows: readonly (readonly [string, string])[]): string[] {\n const width = Math.max(0, ...rows.map(([left]) => left.length));\n return rows.map(([left, right]) => ` ${left.padEnd(width)} ${right}`.trimEnd());\n}\n\n/**\n * @param options - CLI options.\n * @param commands - The commands.\n * @returns {string} The usage text of the CLI.\n */\nfunction mainUsage(options: CliOptions, commands: readonly Command[]): string {\n return [\n `${options.description} (${options.name} v${options.version})`,\n \"\",\n `USAGE ${options.name} <command> [OPTIONS]`,\n \"\",\n \"COMMANDS\",\n \"\",\n ...table(\n commands.map((command) => [[command.name, ...command.aliases].join(\", \"), command.summary]),\n ),\n \"\",\n `Use ${options.name} <command> --help for more information about a command.`,\n ].join(\"\\n\");\n}\n\n/**\n * @param options - CLI options.\n * @param command - The command.\n * @returns {string} Its usage text.\n */\nfunction commandUsage(options: CliOptions, command: Command): string {\n const positional = command.fields.filter((field) => field.positional);\n const flags = command.fields.filter((field) => !field.positional);\n const takesOptions = flags.length > 0 || command.json;\n const words = positional.map((field) => {\n const name = field.flag.toUpperCase();\n return field.required ? `<${name}>` : `[${name}]`;\n });\n const rows = [\n ...flags.map((field): [string, string] => [\n field.kind === \"boolean\" ? `--[no-]${field.flag}` : `--${field.flag}=<${valueHint(field)}>`,\n fieldDescription(field),\n ]),\n ...(command.json\n ? [[\"--json\", \"Print the details as JSON instead of the text\"] as [string, string]]\n : []),\n [\"-h, --help\", \"Show this help\"] as [string, string],\n ];\n return [\n `${command.summary} (${options.name} ${command.name} v${options.version})`,\n \"\",\n `USAGE ${[options.name, command.name, ...(takesOptions ? [\"[OPTIONS]\"] : []), ...words].join(\" \")}`,\n ...(positional.length > 0\n ? [\n \"\",\n \"ARGUMENTS\",\n \"\",\n ...table(positional.map((field) => [field.flag.toUpperCase(), fieldDescription(field)])),\n ]\n : []),\n \"\",\n \"OPTIONS\",\n \"\",\n ...table(rows),\n ].join(\"\\n\");\n}\n\n/**\n * Ends the process once the reader of stdout or stderr is gone, as after\n * `| head -1`. Node ignores SIGPIPE, so without a listener the next write\n * throws `EPIPE` with a stack trace. The exit code stays what the command set.\n *\n * @param error - The error the stream emitted.\n */\nfunction exitOnClosedPipe(error: Readonly<NodeJS.ErrnoException>): void {\n if (error.code !== \"EPIPE\") throw error;\n process.exit();\n}\n\n/**\n * Runs the CLI on `process.argv`. The CLI writes no colors, so nothing\n * depends on the terminal it writes to.\n *\n * @param options - CLI options.\n * @param argv - Words after the executable and script.\n */\nexport async function runCli(\n options: CliOptions,\n argv: readonly string[] = process.argv.slice(2),\n): Promise<void> {\n process.stdout.on(\"error\", exitOnClosedPipe);\n process.stderr.on(\"error\", exitOnClosedPipe);\n await createCli(options).run(argv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M,KAAA;AACN;AAEE,eAAM,OAAY,SAAI,OAAA,QAAA,KAAA,MAAA,CAAA,GAAA;CACtB,QAAA,OAAU,GAAK,SAAK,gBAAoB;CACxC,QAAA,OAAc,GAAA,SAAK,gBAAe;CAClC,MAAA,UAAA,OAAA,CAAA,CAAA,IAAA,IAAA;AACA;AAEE,SAAM,aAAS,WAAM,eAAiB"}
|
|
1
|
+
{"version":3,"file":"cli.mjs","names":["Value.Convert"],"sources":["../src/cli.ts"],"sourcesContent":["/**\n * CLI adapter: one command per {@link ToolDefinition}, plus the package's own\n * commands and an optional stdio MCP server, with no CLI library underneath.\n *\n * A tool's properties become flags, its {@link ToolCliHints} pick positional\n * arguments and stdin, and every call goes through {@link invokeTool}, so the\n * command line validates and fails like every other surface. A package\n * command is a tool definition too, one that only the CLI gets.\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { parseArgs } from \"node:util\";\n\nimport { Value } from \"typebox/value\";\n\nimport { sanitizeText } from \"./escapes.ts\";\nimport {\n indexTools,\n invokeTool,\n resultText,\n sanitizeLine,\n ToolDefinitionError,\n ToolInputError,\n type ToolDefinition,\n} from \"./index.ts\";\n\nexport interface CliOptions {\n /** Executable name, also the MCP server name. */\n readonly name: string;\n readonly version: string;\n readonly description: string;\n readonly tools: readonly ToolDefinition[];\n /**\n * The package's own commands, as tool definitions that only the CLI gets:\n * no MCP, Pi, OMP or AI SDK host sees them. One whose command name matches\n * a generated command, `mcp` included, takes its place. A command that\n * needs bytes, not text, reads `-` from stdin itself in `execute`.\n */\n readonly commands?: readonly ToolDefinition[];\n /** Command for an empty command line. */\n readonly default?: string;\n /** Command for a first word that names no command: `hashes sha256 x` runs `hashes hash sha256 x`. */\n readonly fallback?: string;\n /** Adds `mcp`, the tools as an MCP server over stdio. */\n readonly mcp?: boolean;\n /**\n * Errors the package throws on purpose. They print as one line with exit\n * code 1; any other error keeps its stack trace.\n */\n readonly expected?: (error: unknown) => boolean;\n}\n\n/** A flag `--<flag>` can spell: not empty, no `=`, no space or control, not starting with `-`. */\nconst FLAG_WORD = /^[a-z0-9][a-z0-9.-]*$/;\n\n/** Flags every tool command answers itself. */\nconst RESERVED_FLAGS = new Set([\"help\", \"version\", \"json\"]);\n\ntype FieldKind = \"string\" | \"number\" | \"boolean\" | \"enum\" | \"json\";\n\ninterface Field {\n readonly key: string;\n readonly schema: SchemaNode;\n readonly required: boolean;\n readonly flag: string;\n readonly kind: FieldKind;\n readonly positional: boolean;\n readonly stdin: boolean;\n}\n\ntype SchemaNode = Readonly<Record<string, unknown>>;\n\nconst TYPE_KINDS = new Map<unknown, FieldKind>([\n [\"boolean\", \"boolean\"],\n [\"integer\", \"number\"],\n [\"number\", \"number\"],\n [\"object\", \"json\"],\n [\"array\", \"json\"],\n]);\n\n/**\n * @param key - Property name, `camelCase` or `snake_case`.\n * @returns {string} The flag, in kebab case.\n */\nfunction flagName(key: string): string {\n return key\n .replaceAll(/([a-z0-9])([A-Z])/g, \"$1-$2\")\n .replaceAll(\"_\", \"-\")\n .toLowerCase();\n}\n\n/**\n * @param tool - Tool to name.\n * @returns {string} The hinted command, or the tool name without its package prefix, in kebab case.\n */\nexport function commandName(tool: ToolDefinition): string {\n if (tool.cli?.command !== undefined) return commandWord(tool.name, tool.cli.command);\n const separator = tool.name.indexOf(\"_\");\n const derived = separator === -1 ? tool.name : tool.name.slice(separator + 1);\n // `pkg__h` would derive `-h` and `pkg_` nothing; neither can be dispatched.\n return commandWord(tool.name, derived.replaceAll(\"_\", \"-\"));\n}\n\n/** A command word the CLI can dispatch to: not empty, not an option, nothing that forges a line. */\nconst COMMAND_WORD = /^[a-z0-9_][a-z0-9_.:-]*$/i;\n\n/**\n * @param owner - Tool or CLI the name belongs to, for the error.\n * @param word - Command name or alias.\n * @returns {string} The word, checked.\n * @throws {ToolDefinitionError} When no command line could reach it.\n */\nfunction commandWord(owner: string, word: string): string {\n if (!COMMAND_WORD.test(word)) {\n throw new ToolDefinitionError(\n `${owner}: command ${JSON.stringify(word)} must match ${COMMAND_WORD}`,\n );\n }\n return word;\n}\n\n/**\n * How a value for this property is read from one command line word.\n *\n * @param schema - Property schema.\n * @returns {FieldKind} The reading.\n */\nfunction fieldKind(schema: SchemaNode): FieldKind {\n if (Array.isArray(schema.enum) && schema.enum.every((value) => typeof value === \"string\")) {\n return \"enum\";\n }\n const branches = Array.isArray(schema.anyOf) ? (schema.anyOf as readonly SchemaNode[]) : [];\n if (branches.some((branch) => fieldKind(branch) === \"json\")) return \"json\";\n return TYPE_KINDS.get(schema.type) ?? \"string\";\n}\n\n/**\n * Reads a tool's schema and hints into command line fields.\n *\n * @param tool - Tool to read.\n * @returns {Field[]} One field per property, positional ones in hint order first.\n * @throws {ToolDefinitionError} When a hint names a property the tool lacks, or two properties share a flag.\n */\nfunction toolFields(tool: ToolDefinition): Field[] {\n const properties = tool.input.properties as Readonly<Record<string, SchemaNode>>;\n const positional = tool.cli?.positional ?? [];\n const stdin = tool.cli?.stdin ?? [];\n for (const key of [...positional, ...stdin]) {\n if (!Object.hasOwn(properties, key)) {\n throw new ToolDefinitionError(`${tool.name}: cli hint names unknown property ${key}`);\n }\n }\n const repeated = positional.find((key, index) => positional.indexOf(key) !== index);\n if (repeated !== undefined) {\n throw new ToolDefinitionError(`${tool.name}: cli hint lists positional ${repeated} twice`);\n }\n\n const keys = [\n ...positional,\n ...Object.keys(properties).filter((key) => !positional.includes(key)),\n ];\n const required = (tool.input.required as readonly string[] | undefined) ?? [];\n const flags = new Set<string>();\n const fields = keys.map((key): Field => {\n const field: Field = {\n key,\n schema: properties[key] ?? {},\n required: required.includes(key),\n flag: flagName(key),\n kind: fieldKind(properties[key] ?? {}),\n positional: positional.includes(key),\n stdin: stdin.includes(key),\n };\n assertField(tool, field, !field.positional && flags.has(field.flag));\n if (!field.positional) flags.add(field.flag);\n return field;\n });\n assertOneOptionPerSpelling(tool, fields);\n assertRequiredPositionalsFirst(tool, fields);\n return fields;\n}\n\n/**\n * @param tool - Tool the field belongs to.\n * @param field - Field to check.\n * @throws {ToolDefinitionError} When no word can spell the flag, or it is reserved or reads as a negation.\n */\nfunction assertFlag(tool: ToolDefinition, field: Field): void {\n if (!FLAG_WORD.test(field.flag)) {\n throw new ToolDefinitionError(\n `${tool.name}: property ${JSON.stringify(field.key)} gives the flag ${JSON.stringify(field.flag)}, which must match ${FLAG_WORD}`,\n );\n }\n if (field.kind === \"boolean\" && field.flag.startsWith(\"no-\")) {\n // `util.parseArgs` reads `--no-cache` as `cache` negated, never as a flag `no-cache`.\n throw new ToolDefinitionError(\n `${tool.name}: boolean property ${field.key} cannot take a flag starting with no-; name the positive and --no-${field.flag.slice(3)} negates it`,\n );\n }\n if (RESERVED_FLAGS.has(field.flag)) {\n throw new ToolDefinitionError(\n `${tool.name}: property ${field.key} takes the reserved flag --${field.flag}`,\n );\n }\n}\n\n/**\n * @param tool - Tool the field belongs to.\n * @param field - Field to check.\n * @param taken - Whether an option before it has the same flag.\n * @throws {ToolDefinitionError} When no word can spell the flag, it is reserved or taken, or a hint does not fit the field.\n */\nfunction assertField(tool: ToolDefinition, field: Field, taken: boolean): void {\n // A positional is never an option: its key needs no flag spelling.\n if (!field.positional) assertFlag(tool, field);\n if (taken) {\n throw new ToolDefinitionError(`${tool.name}: two properties take the flag --${field.flag}`);\n }\n if (field.positional && field.kind === \"boolean\") {\n throw new ToolDefinitionError(\n `${tool.name}: boolean property ${field.key} cannot be positional`,\n );\n }\n if (field.stdin && field.kind !== \"string\") {\n throw new ToolDefinitionError(`${tool.name}: stdin property ${field.key} must be a string`);\n }\n}\n\n/**\n * Words fill the positionals in order, so an optional one before a required\n * one would take the only word given and leave the required one empty.\n *\n * @param tool - Tool the fields belong to.\n * @param fields - The tool's fields.\n * @throws {ToolDefinitionError} When an optional positional comes before a required one.\n */\nfunction assertRequiredPositionalsFirst(tool: ToolDefinition, fields: readonly Field[]): void {\n const positional = fields.filter((field) => field.positional);\n const optional = positional.findIndex((field) => !field.required);\n const late = positional\n .slice(optional === -1 ? positional.length : optional)\n .find((field) => field.required);\n if (late !== undefined) {\n throw new ToolDefinitionError(\n `${tool.name}: required positional ${late.key} comes after an optional one`,\n );\n }\n}\n\n/**\n * Every spelling the CLI reads for an option names one property: a boolean also\n * answers to `--no-<flag>`, so a boolean `cache` and a property `noCache`\n * would both claim `--no-cache`.\n *\n * @param tool - Tool the fields belong to.\n * @param fields - The tool's fields.\n * @throws {ToolDefinitionError} When two options share a spelling.\n */\nfunction assertOneOptionPerSpelling(tool: ToolDefinition, fields: readonly Field[]): void {\n const owners = new Map<string, string>();\n for (const field of fields.filter((each) => !each.positional)) {\n const negation = field.kind === \"boolean\" ? [`no-${field.flag}`] : [];\n for (const spelling of [field.flag, ...negation]) {\n const owner = owners.get(spelling);\n if (owner !== undefined) {\n throw new ToolDefinitionError(\n `${tool.name}: properties ${owner} and ${field.key} both answer to --${spelling}`,\n );\n }\n owners.set(spelling, field.key);\n }\n }\n}\n\n/**\n * @param field - Field to describe.\n * @returns {string} Its line in the usage text, after the flag.\n */\nfunction fieldDescription(field: Field): string {\n const { schema } = field;\n return [\n typeof schema.description === \"string\" ? schema.description : \"\",\n field.stdin ? \"(- reads stdin)\" : \"\",\n field.required ? \"(required)\" : \"\",\n ]\n .filter((part) => part !== \"\")\n .join(\" \");\n}\n\n/**\n * @param field - Option field.\n * @returns {string} What the value looks like in the usage text.\n */\nfunction valueHint(field: Field): string {\n if (field.kind === \"enum\") return (field.schema.enum as string[]).join(\"|\");\n return field.kind === \"string\" ? field.flag : field.kind;\n}\n\n/**\n * A record without a prototype: a property named `toString` reads as unset\n * instead of `Object.prototype.toString`, and `__proto__` is a plain key.\n *\n * @returns {Record<string, T>} An empty record.\n */\nfunction emptyRecord<T>(): Record<string, T> {\n return Object.create(null) as Record<string, T>;\n}\n\ninterface ParsedWords {\n /** Raw values by property: a string, or `true`/`false` for a boolean. */\n readonly values: Readonly<Record<string, string | boolean>>;\n readonly json: boolean;\n /** `--help` or `-h` before any `--`; a value or a word after `--` is not one. */\n readonly help: boolean;\n readonly errors: readonly string[];\n}\n\n/**\n * Reads the words after the command name, on `util.parseArgs` tokens. Only\n * `--flag`, `--flag=value` and, for a boolean, `--no-flag` are options;\n * an unknown option, a single dash before a name, a missing value, a value\n * given twice or a positional too many is a failure, never a skipped word.\n *\n * @param rawArgs - Words after the command name.\n * @param fields - The command's fields.\n * @param takesJson - Whether the command takes `--json`.\n * @returns {ParsedWords} Values by property and the failures, one per line.\n */\nfunction parseWords(\n rawArgs: readonly string[],\n fields: readonly Field[],\n takesJson: boolean,\n): ParsedWords {\n const entries: Array<[string, Field | \"json\"]> = [\n ...fields\n .filter((field) => !field.positional)\n .map((field): [string, Field] => [field.flag, field]),\n ...(takesJson ? [[\"json\", \"json\"] as [string, \"json\"]] : []),\n ];\n const options: Readonly<Record<string, Field | \"json\">> = Object.fromEntries(entries);\n const { tokens } = parseArgs({\n args: [...rawArgs],\n options: Object.fromEntries(\n Object.entries(options).map(([flag, field]) => [\n flag,\n { type: field === \"json\" || field.kind === \"boolean\" ? \"boolean\" : \"string\" },\n ]),\n ) as Record<string, { type: \"boolean\" | \"string\" }>,\n strict: false,\n allowPositionals: true,\n allowNegative: true,\n tokens: true,\n });\n\n const values = emptyRecord<string | boolean>();\n const errors: string[] = [];\n const positionals: string[] = [];\n const flags = new Set<string>();\n for (const token of tokens) {\n if (token.kind === \"positional\") positionals.push(token.value);\n if (token.kind !== \"option\") continue;\n const read = readOption(options, token, rawArgs[token.index] ?? \"\", Object.keys(values));\n if (\"error\" in read) errors.push(read.error);\n else if (\"flag\" in read) flags.add(read.flag);\n else values[read.key] = read.value;\n }\n return {\n values: Object.assign(values, positionalValues(fields, positionals)),\n json: flags.has(\"json\"),\n help: flags.has(\"help\"),\n errors: [...new Set(errors.length > 0 ? errors : extraPositionals(fields, positionals))],\n };\n}\n\n/**\n * @param fields - The command's fields.\n * @param positionals - Positional words in order.\n * @returns {Record<string, string>} Each positional property with its word.\n */\nfunction positionalValues(\n fields: readonly Field[],\n positionals: readonly string[],\n): Record<string, string> {\n const takes = fields.filter((field) => field.positional);\n return Object.assign(\n emptyRecord<string>(),\n Object.fromEntries(\n takes.flatMap((field, index) => {\n const value = positionals[index];\n return value === undefined ? [] : [[field.key, value]];\n }),\n ),\n );\n}\n\n/**\n * @param fields - The command's fields.\n * @param positionals - Positional words in order.\n * @returns {string[]} The failure when there are more words than positional properties.\n */\nfunction extraPositionals(fields: readonly Field[], positionals: readonly string[]): string[] {\n const extra = positionals.length - fields.filter((field) => field.positional).length;\n if (extra <= 0) return [];\n return [`Invalid arguments: ${extra} unexpected positional argument${extra === 1 ? \"\" : \"s\"}`];\n}\n\ninterface OptionToken {\n readonly name: string;\n readonly rawName: string;\n readonly value?: string | undefined;\n readonly inlineValue?: boolean | undefined;\n}\n\ntype OptionRead =\n | { readonly error: string }\n | { readonly flag: \"json\" | \"help\" }\n | { readonly key: string; readonly value: string | boolean };\n\n/**\n * `-xh` expands to `-x` and `-h`; only the whole word `-h` asks for help.\n *\n * @param token - The token `util.parseArgs` made.\n * @param word - The command line word it came from.\n * @returns {boolean} Whether the token is `--help` or the word `-h`.\n */\nfunction asksHelp(token: OptionToken, word: string): boolean {\n return token.rawName === \"--help\" || word === \"-h\";\n}\n\n/**\n * @param options - Option fields by flag, and `--json` when the command takes it.\n * @param token - The token `util.parseArgs` made.\n * @param word - The command line word it came from.\n * @returns {Field | \"json\" | \"help\" | undefined} What the token names under a spelling it takes.\n */\nfunction optionField(\n options: Readonly<Record<string, Field | \"json\">>,\n token: OptionToken,\n word: string,\n): Field | \"json\" | \"help\" | undefined {\n if (asksHelp(token, word)) return \"help\";\n const field = Object.hasOwn(options, token.name) ? options[token.name] : undefined;\n if (field === \"json\") return token.rawName === \"--json\" ? field : undefined;\n if (field === undefined || token.rawName === `--${token.name}`) return field;\n return token.rawName === `--no-${token.name}` && field.kind === \"boolean\" ? field : undefined;\n}\n\n/**\n * @param options - Option fields by flag, and `--json` when the command takes it.\n * @param token - The token `util.parseArgs` made.\n * @param word - The command line word it came from.\n * @param seen - Properties set by earlier words.\n * @returns {OptionRead} The value it sets, `--json`, or the failure.\n */\nfunction readOption(\n options: Readonly<Record<string, Field | \"json\">>,\n token: OptionToken,\n word: string,\n seen: readonly string[],\n): OptionRead {\n const field = optionField(options, token, word);\n if (field === undefined) {\n const flags = Object.keys(options).map((flag) => `--${flag}`);\n const takes = flags.length > 0 ? flags.join(\", \") : \"no options\";\n return { error: `Invalid arguments: unknown option ${JSON.stringify(word)}; takes ${takes}` };\n }\n if (field === \"json\" || field === \"help\") {\n return token.inlineValue === true\n ? { error: `Invalid arguments: ${token.rawName} takes no value` }\n : { flag: field };\n }\n const problem = optionProblem(field, token, seen.includes(field.key));\n if (problem !== undefined) return { error: `Invalid arguments: --${field.flag} ${problem}` };\n const value = field.kind === \"boolean\" ? token.rawName === `--${field.flag}` : token.value;\n return { key: field.key, value: value ?? \"\" };\n}\n\n/**\n * @param field - The option's field.\n * @param token - Its token.\n * @param seen - Whether an earlier word set the property already.\n * @returns {string | undefined} What is wrong with the option, if anything.\n */\nfunction optionProblem(field: Field, token: OptionToken, seen: boolean): string | undefined {\n if (seen) return \"given more than once\";\n if (field.kind === \"boolean\") return token.inlineValue === true ? \"takes no value\" : undefined;\n return token.value === undefined ? \"needs a value\" : undefined;\n}\n\n/**\n * Reads stdin as strict UTF-8. A lenient decode would turn each invalid byte\n * into U+FFFD, and a tool hashing or encoding the text would answer for other\n * input without a word; binary data needs a command of the package's own.\n *\n * @returns {string | undefined} The text, or nothing when stdin is not UTF-8.\n */\nfunction readStdin(): string | undefined {\n try {\n return new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true }).decode(readFileSync(0));\n } catch (error) {\n if (error instanceof TypeError) return undefined;\n throw error;\n }\n}\n\n/**\n * @param field - Field the word belongs to.\n * @param raw - What {@link parseWords} read for it.\n * @returns {{ value: unknown } | { error: string }} The value before TypeBox conversion, or why there is none.\n */\nfunction fieldValue(field: Field, raw: unknown): { value: unknown } | { error: string } {\n if (field.stdin && raw === \"-\") {\n const text = readStdin();\n return text === undefined ? { error: \"stdin is not UTF-8 text\" } : { value: text };\n }\n if (field.kind !== \"json\" || typeof raw !== \"string\") return { value: raw };\n try {\n return { value: JSON.parse(raw) as unknown };\n } catch {\n return { error: \"must be JSON\" };\n }\n}\n\n/**\n * Builds the tool input from parsed arguments. Numbers and booleans in the\n * schema are converted from their text by TypeBox; objects and arrays are\n * JSON. The result still goes through {@link invokeTool} validation.\n *\n * @param tool - Tool to call.\n * @param fields - The command's fields.\n * @param values - Raw values by property, from {@link parseWords}.\n * @returns {unknown} The input object.\n * @throws {ToolInputError} When a JSON value does not parse.\n */\nfunction toolInput(\n tool: ToolDefinition,\n fields: readonly Field[],\n values: Readonly<Record<string, string | boolean>>,\n): unknown {\n const input = emptyRecord<unknown>();\n const fromStdin = fields.filter((field) => field.stdin && values[field.key] === \"-\");\n if (fromStdin.length > 1) {\n throw new ToolInputError([\n `Invalid arguments: stdin can feed one argument, not ${fromStdin.map((field) => field.key).join(\" and \")}`,\n ]);\n }\n const errors: string[] = [];\n for (const field of fields) {\n const raw = values[field.key];\n if (raw === undefined) continue;\n const read = fieldValue(field, raw);\n if (\"error\" in read) errors.push(`Invalid arguments at /${field.key}: ${read.error}`);\n else input[field.key] = read.value;\n }\n if (errors.length > 0) throw new ToolInputError(errors);\n return Value.Convert(tool.input, input);\n}\n\n/**\n * @param stream - Where to write.\n * @param text - Text, given a trailing newline when it lacks one.\n */\nfunction writeLine(stream: \"stdout\" | \"stderr\", text: string): void {\n process[stream].write(text.endsWith(\"\\n\") ? text : `${text}\\n`);\n}\n\n/**\n * Prints an error the CLI expects and sets exit code 1.\n *\n * @param lines - Failure lines.\n */\nfunction fail(lines: readonly string[]): void {\n writeLine(\"stderr\", lines.map(sanitizeLine).join(\"\\n\"));\n process.exitCode = 1;\n}\n\n/**\n * Turns expected errors into {@link fail}; any other error goes on with its stack.\n *\n * @param options - CLI options.\n * @param error - What the command threw.\n */\nfunction handleError(options: CliOptions, error: unknown): void {\n if (error instanceof ToolInputError) fail(error.lines);\n else if (options.expected?.(error) === true) {\n fail([error instanceof Error ? error.message : String(error)]);\n } else throw error;\n}\n\n/**\n * @param details - Tool details.\n * @returns {string} Pretty JSON; a bigint becomes its decimal string, no details `null`.\n */\nfunction detailsJson(details: unknown): string {\n // `JSON.stringify` answers `undefined`, not a string, for undefined details.\n const json =\n (JSON.stringify(\n details,\n (_key, value: unknown) => (typeof value === \"bigint\" ? value.toString() : value),\n 2,\n ) as string | undefined) ?? \"null\";\n return json.replaceAll(\n JSON_FORGING,\n (character) => `\\\\u${(character.codePointAt(0) ?? 0).toString(16).padStart(4, \"0\")}`,\n );\n}\n\n/**\n * What `JSON.stringify` leaves literal although a terminal acts on it: DEL and\n * C1, the bidi marks, overrides and isolates, and the Unicode line and\n * paragraph separators. They only occur inside strings, so a `\\u` escape\n * keeps the parsed details the same.\n */\nconst JSON_FORGING =\n /* oxlint-disable-next-line no-control-regex */\n /[\\u007F-\\u009F\\u061C\\u200E\\u200F\\u2028\\u2029\\u202A-\\u202E\\u2066-\\u206F]/g;\n\n/** One command the CLI dispatches to: a tool, a package command or `mcp`. */\ninterface Command {\n readonly name: string;\n readonly aliases: readonly string[];\n /** Line in the command list. */\n readonly summary: string;\n readonly fields: readonly Field[];\n /** Takes `--json`: a tool command prints its details; `mcp` has none. */\n readonly json: boolean;\n run(words: ParsedWords): Promise<void>;\n}\n\n/**\n * @param tool - Tool or package command to run.\n * @returns {Command} The command calling it.\n */\nfunction toolCommand(tool: ToolDefinition): Command {\n const fields = toolFields(tool);\n const [summary = tool.title] = tool.description.split(/(?<=[.!?])\\s/, 1);\n return {\n name: commandName(tool),\n aliases: (tool.cli?.aliases ?? []).map((alias) => commandWord(tool.name, alias)),\n summary: tool.cli?.description ?? summary,\n fields,\n json: true,\n async run(words) {\n const result = await invokeTool(tool, toolInput(tool, fields, words.values));\n if (result.isError === true) {\n writeLine(\"stderr\", sanitizeText(resultText(result)));\n process.exitCode = 1;\n } else if (words.json) {\n writeLine(\"stdout\", detailsJson(result.details));\n } else {\n writeLine(\"stdout\", sanitizeText(resultText(result)));\n const images = result.content.filter((block) => block.type === \"image\").length;\n if (images > 0) writeLine(\"stderr\", `(${images} image block(s) not printed)`);\n }\n },\n };\n}\n\n/**\n * @param options - CLI options.\n * @returns {Command} The stdio MCP server command.\n */\nfunction mcpCommand(options: CliOptions): Command {\n return {\n name: \"mcp\",\n aliases: [],\n summary: `Run the ${options.name} MCP server over stdio`,\n fields: [],\n json: false,\n async run() {\n const [{ createMcpServer }, { StdioServerTransport }] = await Promise.all([\n import(\"./mcp.ts\"),\n import(\"@modelcontextprotocol/server/stdio\"),\n ]);\n await createMcpServer(options, options.tools).connect(new StdioServerTransport());\n },\n };\n}\n\n/**\n * The definitions behind the commands, in listing order: the tools, each\n * replaced in place by a package command of its command name, then the rest\n * of the package commands.\n *\n * @param options - CLI options.\n * @returns {ToolDefinition[]} One definition per command but `mcp`.\n */\nfunction commandTools(options: CliOptions): ToolDefinition[] {\n const own = options.commands ?? [];\n const byName = new Map(own.map((command) => [commandName(command), command]));\n const listed = options.tools.map((tool) => byName.get(commandName(tool)) ?? tool);\n return [...listed, ...own.filter((command) => !listed.includes(command))];\n}\n\n/**\n * @param options - CLI options.\n * @returns {boolean} Whether the built-in `mcp` command is on and no package command replaces it.\n */\nfunction builtInMcp(options: CliOptions): boolean {\n return (\n options.mcp === true &&\n !(options.commands ?? []).some((command) => commandName(command) === \"mcp\")\n );\n}\n\n/**\n * @param options - CLI options.\n * @returns {string[]} Every command name and alias, `mcp` included when built in.\n */\nfunction commandWords(options: CliOptions): string[] {\n return [\n ...commandTools(options).flatMap((tool) => [commandName(tool), ...(tool.cli?.aliases ?? [])]),\n ...(builtInMcp(options) ? [\"mcp\"] : []),\n ];\n}\n\n/** A built command line interface. */\nexport interface Cli {\n /** Runs one command line: the words after the executable and script. */\n run(argv: readonly string[]): Promise<void>;\n}\n\n/**\n * Builds the commands and checks every definition, so a broken hint fails at\n * startup and not on the first call that reaches it.\n *\n * @param options - CLI options.\n * @returns {Cli} The CLI.\n * @throws {ToolDefinitionError} When two commands share a name or alias, a hint does not fit its schema, or `default` or `fallback` names no command.\n */\nexport function createCli(options: CliOptions): Cli {\n indexTools(options.tools);\n indexTools(options.commands ?? []);\n const commands = [\n ...commandTools(options).map((tool) => toolCommand(tool)),\n ...(builtInMcp(options) ? [mcpCommand(options)] : []),\n ];\n const words = commandWords(options);\n const repeated = words.find((word, index) => words.indexOf(word) !== index);\n if (repeated !== undefined) throw new ToolDefinitionError(`Two commands are named ${repeated}`);\n const missing = [options.default, options.fallback].find(\n (name) => name !== undefined && !words.includes(name),\n );\n if (missing !== undefined)\n throw new ToolDefinitionError(`${options.name}: no command ${missing}`);\n\n return { run: (argv) => dispatch(options, commands, normalizeArgv(options, argv)) };\n}\n\n/**\n * Applies `default` and `fallback`: an empty command line runs `default`, and\n * a first word that names no command goes to `fallback` as its first\n * argument. A leading option such as `--help` stays at the root; a lone `-`\n * is the stdin word of the fallback's positional, not an option.\n *\n * @param options - CLI options.\n * @param argv - Words after the executable and script.\n * @returns {string[]} The words to dispatch.\n */\nexport function normalizeArgv(options: CliOptions, argv: readonly string[]): string[] {\n const [first] = argv;\n if (first === undefined) return options.default === undefined ? [] : [options.default];\n const option = first.startsWith(\"-\") && first !== \"-\";\n if (options.fallback === undefined || option || commandWords(options).includes(first)) {\n return [...argv];\n }\n return [options.fallback, ...argv];\n}\n\n/**\n * Picks the command by its first word and runs it. `--help` and `-h` count\n * only where the parse finds an option: after `--` or as an option's value\n * they are the tool's words. Every error line goes through\n * {@link sanitizeLine}, an unknown word inside `JSON.stringify`.\n *\n * @param options - CLI options.\n * @param commands - The commands.\n * @param argv - Words after {@link normalizeArgv}.\n */\nasync function dispatch(\n options: CliOptions,\n commands: readonly Command[],\n argv: readonly string[],\n): Promise<void> {\n const [first, ...rest] = argv;\n if (argv.length === 1 && (first === \"--version\" || first === \"-v\")) {\n writeLine(\"stdout\", sanitizeLine(options.version));\n } else if (first === \"--help\" || first === \"-h\") {\n writeLine(\"stdout\", sanitizeText(mainUsage(options, commands)));\n } else if (first === undefined) {\n writeLine(\"stderr\", sanitizeText(mainUsage(options, commands)));\n fail([\"No command specified\"]);\n } else {\n const command = commands.find((each) => each.name === first || each.aliases.includes(first));\n if (command === undefined) {\n fail([\n `Unknown command ${JSON.stringify(first)}`,\n `Run ${options.name} --help for the commands`,\n ]);\n } else {\n await runCommand(options, command, rest);\n }\n }\n}\n\n/**\n * @param options - CLI options.\n * @param command - The chosen command.\n * @param rawArgs - Words after the command name.\n */\nasync function runCommand(\n options: CliOptions,\n command: Command,\n rawArgs: readonly string[],\n): Promise<void> {\n const words = parseWords(rawArgs, command.fields, command.json);\n if (words.help) {\n writeLine(\"stdout\", sanitizeText(commandUsage(options, command)));\n return;\n }\n try {\n if (words.errors.length > 0) throw new ToolInputError(words.errors);\n await command.run(words);\n } catch (error) {\n handleError(options, error);\n }\n}\n\n/**\n * @param rows - Left and right column of each row.\n * @returns {string[]} The rows, indented, with the right column aligned.\n */\nfunction table(rows: readonly (readonly [string, string])[]): string[] {\n const width = Math.max(0, ...rows.map(([left]) => left.length));\n return rows.map(([left, right]) => ` ${left.padEnd(width)} ${right}`.trimEnd());\n}\n\n/**\n * @param options - CLI options.\n * @param commands - The commands.\n * @returns {string} The usage text of the CLI.\n */\nfunction mainUsage(options: CliOptions, commands: readonly Command[]): string {\n return [\n `${options.description} (${options.name} v${options.version})`,\n \"\",\n `USAGE ${options.name} <command> [OPTIONS]`,\n \"\",\n \"COMMANDS\",\n \"\",\n ...table(\n commands.map((command) => [[command.name, ...command.aliases].join(\", \"), command.summary]),\n ),\n \"\",\n `Use ${options.name} <command> --help for more information about a command.`,\n ].join(\"\\n\");\n}\n\n/**\n * @param options - CLI options.\n * @param command - The command.\n * @returns {string} Its usage text.\n */\nfunction commandUsage(options: CliOptions, command: Command): string {\n const positional = command.fields.filter((field) => field.positional);\n const flags = command.fields.filter((field) => !field.positional);\n const takesOptions = flags.length > 0 || command.json;\n const words = positional.map((field) => {\n const name = field.flag.toUpperCase();\n return field.required ? `<${name}>` : `[${name}]`;\n });\n const rows = [\n ...flags.map((field): [string, string] => [\n field.kind === \"boolean\" ? `--[no-]${field.flag}` : `--${field.flag}=<${valueHint(field)}>`,\n fieldDescription(field),\n ]),\n ...(command.json\n ? [[\"--json\", \"Print the details as JSON instead of the text\"] as [string, string]]\n : []),\n [\"-h, --help\", \"Show this help\"] as [string, string],\n ];\n return [\n `${command.summary} (${options.name} ${command.name} v${options.version})`,\n \"\",\n `USAGE ${[options.name, command.name, ...(takesOptions ? [\"[OPTIONS]\"] : []), ...words].join(\" \")}`,\n ...(positional.length > 0\n ? [\n \"\",\n \"ARGUMENTS\",\n \"\",\n ...table(positional.map((field) => [field.flag.toUpperCase(), fieldDescription(field)])),\n ]\n : []),\n \"\",\n \"OPTIONS\",\n \"\",\n ...table(rows),\n ].join(\"\\n\");\n}\n\n/**\n * Ends the process once the reader of stdout or stderr is gone, as after\n * `| head -1`. Node ignores SIGPIPE, so without a listener the next write\n * throws `EPIPE` with a stack trace. The exit code stays what the command set.\n *\n * @param error - The error the stream emitted.\n */\nfunction exitOnClosedPipe(error: Readonly<NodeJS.ErrnoException>): void {\n if (error.code !== \"EPIPE\") throw error;\n process.exit();\n}\n\n/**\n * Runs the CLI on `process.argv`. The CLI writes no colors, so nothing\n * depends on the terminal it writes to.\n *\n * @param options - CLI options.\n * @param argv - Words after the executable and script.\n */\nexport async function runCli(\n options: CliOptions,\n argv: readonly string[] = process.argv.slice(2),\n): Promise<void> {\n process.stdout.on(\"error\", exitOnClosedPipe);\n process.stderr.on(\"error\", exitOnClosedPipe);\n await createCli(options).run(argv);\n}\n"],"mappings":";;;;;;;;;;;CAqDA,CAAA,WAAM,SAAY;;CAGlB,CAAA,UAAM,QAAA;CAA0B,CAAA,UAAA,MAAA;CAAQ,CAAA,SAAA,MAAA;AAAW,CAAA;AAgBnD,SAAM,SAAA,KAAA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QAAA,OAAW,GAAA,SACT,gBAAU;CACL,MAAA,UAAA,OAAA,CAAA,CAAA,IAAA,IAAA;AACL;AAEA,SAAI,aAAY,WAAU,eAAc"}
|
package/dist/h3.d.mts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { ToolDefinition as ToolDefinition$1 } from "./index.mjs";
|
|
2
|
+
import { JsonSchema, ToolDefinition } from "h3-mcp";
|
|
3
|
+
/** An h3-mcp tool whose `inputSchema` is the plain JSON Schema `tools/list` sends. */
|
|
4
|
+
export type H3Tool = ToolDefinition<JsonSchema>;
|
|
5
|
+
/**
|
|
6
|
+
* Turns tools into h3-mcp tool definitions for `defineMcpHandler({ tools })`.
|
|
7
|
+
*
|
|
8
|
+
* Each entry carries what `listTools` lists, and its handler answers through
|
|
9
|
+
* `callTool`, so the text, the validation lines and the sanitized errors are the
|
|
10
|
+
* ones every other MCP transport gives. The schema goes out as plain JSON
|
|
11
|
+
* Schema, which h3-mcp passes through without validating; the core validates
|
|
12
|
+
* instead. An unknown name never reaches a handler: h3-mcp answers it itself
|
|
13
|
+
* with a JSON-RPC error.
|
|
14
|
+
*
|
|
15
|
+
* Imports only types from h3-mcp, so the adapter loads neither h3-mcp nor the MCP SDK.
|
|
16
|
+
*
|
|
17
|
+
* @param info - Server info; `name` is the word in the message for an unknown tool.
|
|
18
|
+
* @param tools - Tools to serve.
|
|
19
|
+
* @returns {H3Tool[]} Tool definitions in the order given.
|
|
20
|
+
* @throws {ToolDefinitionError} When two tools share a name.
|
|
21
|
+
*/
|
|
22
|
+
export declare function toH3Tools(info: {
|
|
23
|
+
readonly name: string;
|
|
24
|
+
}, tools: readonly ToolDefinition$1[]): H3Tool[];
|
|
25
|
+
//# sourceMappingURL=h3.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"h3.d.mts","names":["H3ToolDefinition","ToolDefinition"],"sources":["../src/h3.ts"],"mappings":";;;YAUY,SAASA,eAAiB;;;;;;;;;;;;;;;;;;wBAmBtB,UACd;WAAiB;GACjB,gBAAgBC,qBACf"}
|
package/dist/h3.mjs
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import "./_chunks/src.mjs";
|
|
2
|
+
import { callTool, listTools, progressSteps } from "./_chunks/mcp-answers.mjs";
|
|
3
|
+
function toH3Tools(info, tools) {
|
|
4
|
+
return listTools(tools).map((entry) => ({
|
|
5
|
+
name: entry.name,
|
|
6
|
+
title: entry.title,
|
|
7
|
+
description: entry.description,
|
|
8
|
+
inputSchema: entry.inputSchema,
|
|
9
|
+
annotations: entry.annotations,
|
|
10
|
+
handler: (args, event) => {
|
|
11
|
+
const mcp = event.context.mcp;
|
|
12
|
+
const context = {
|
|
13
|
+
signal: mcp?.signal,
|
|
14
|
+
...mcp?.progressToken === void 0 || mcp.progress === void 0 ? {} : { progress: progressSteps(({ progress, total, message }) => mcp.progress?.(progress, total, message)) }
|
|
15
|
+
};
|
|
16
|
+
return callTool(info, tools, entry.name, args, context);
|
|
17
|
+
}
|
|
18
|
+
}));
|
|
19
|
+
}
|
|
20
|
+
export { toH3Tools };
|
|
21
|
+
|
|
22
|
+
//# sourceMappingURL=h3.mjs.map
|
package/dist/h3.mjs.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"h3.mjs","names":[],"sources":["../src/h3.ts"],"sourcesContent":["/**\n * h3-mcp adapter: hands {@link ToolDefinition}s to `defineMcpHandler` from h3-mcp.\n */\n\nimport type { JsonSchema, ToolDefinition as H3ToolDefinition } from \"h3-mcp\";\n\nimport { type ToolCallContext, type ToolDefinition } from \"./index.ts\";\nimport { callTool, listTools, progressSteps } from \"./mcp-answers.ts\";\n\n/** An h3-mcp tool whose `inputSchema` is the plain JSON Schema `tools/list` sends. */\nexport type H3Tool = H3ToolDefinition<JsonSchema>;\n\n/**\n * Turns tools into h3-mcp tool definitions for `defineMcpHandler({ tools })`.\n *\n * Each entry carries what `listTools` lists, and its handler answers through\n * `callTool`, so the text, the validation lines and the sanitized errors are the\n * ones every other MCP transport gives. The schema goes out as plain JSON\n * Schema, which h3-mcp passes through without validating; the core validates\n * instead. An unknown name never reaches a handler: h3-mcp answers it itself\n * with a JSON-RPC error.\n *\n * Imports only types from h3-mcp, so the adapter loads neither h3-mcp nor the MCP SDK.\n *\n * @param info - Server info; `name` is the word in the message for an unknown tool.\n * @param tools - Tools to serve.\n * @returns {H3Tool[]} Tool definitions in the order given.\n * @throws {ToolDefinitionError} When two tools share a name.\n */\nexport function toH3Tools(\n info: { readonly name: string },\n tools: readonly ToolDefinition[],\n): H3Tool[] {\n return listTools(tools).map((entry) => ({\n name: entry.name,\n title: entry.title,\n description: entry.description,\n inputSchema: entry.inputSchema as JsonSchema,\n annotations: entry.annotations,\n handler: (args, event) => {\n // Read now: a legacy batch shares one context between its calls.\n const mcp = event.context.mcp;\n const context: ToolCallContext = {\n signal: mcp?.signal,\n ...(mcp?.progressToken === undefined || mcp.progress === undefined\n ? {}\n : {\n progress: progressSteps(({ progress, total, message }) =>\n mcp.progress?.(progress, total, message),\n ),\n }),\n };\n return callTool(info, tools, entry.name, args, context);\n },\n }));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA6BA;AAKI,SAAM"}
|
package/dist/index.d.mts
CHANGED
|
@@ -38,9 +38,18 @@ export interface ToolCliHints {
|
|
|
38
38
|
/** String properties that read stdin when given as `-`. */
|
|
39
39
|
readonly stdin?: readonly string[];
|
|
40
40
|
}
|
|
41
|
+
/** How far a long call has come, for hosts that draw it. */
|
|
42
|
+
export interface ToolProgress {
|
|
43
|
+
/** Work done so far. MCP skips an update where it doesn't grow. */
|
|
44
|
+
readonly progress: number;
|
|
45
|
+
/** All the work there is, when the tool knows it. */
|
|
46
|
+
readonly total?: number;
|
|
47
|
+
}
|
|
41
48
|
/** Per-call context the adapters hand to `execute`. */
|
|
42
49
|
export interface ToolCallContext {
|
|
43
50
|
signal?: AbortSignal;
|
|
51
|
+
/** Says the call is still at it. Absent where the host can't show it, so call `progress?.()`. */
|
|
52
|
+
progress?: (message: string, amount?: ToolProgress) => void;
|
|
44
53
|
}
|
|
45
54
|
export interface ToolDefinition<Input extends TObject = TObject, Details = unknown> {
|
|
46
55
|
/** Wire name, `<package>_<operation>`. */
|
|
@@ -135,6 +144,9 @@ export declare function validateInput<Input extends TObject>(tool: ToolDefinitio
|
|
|
135
144
|
/**
|
|
136
145
|
* Validates and runs a tool. Every adapter calls through here.
|
|
137
146
|
*
|
|
147
|
+
* Progress is best effort: a line after the call settles goes nowhere, and a host that throws on
|
|
148
|
+
* one doesn't fail the call.
|
|
149
|
+
*
|
|
138
150
|
* @param tool - Tool to run.
|
|
139
151
|
* @param args - Arguments as received from the host.
|
|
140
152
|
* @param context - Per-call context.
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/index.ts"],"mappings":";;YAgCY;EACN;EAAc;;EACd;EAAe;EAAc;;;iBAGlB,WAAW;EAC1B,SAAS;EACT,SAAS;;EAET;;;;;;;;;YAUU;;;;;iBAMK;;WAEN;WACA;;WAEA;;WAEA;;WAEA;;;iBAIM;EACf,SAAS;;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/index.ts"],"mappings":";;YAgCY;EACN;EAAc;;EACd;EAAe;EAAc;;;iBAGlB,WAAW;EAC1B,SAAS;EACT,SAAS;;EAET;;;;;;;;;YAUU;;;;;iBAMK;;WAEN;WACA;;WAEA;;WAEA;;WAEA;;;iBAIM;;WAEN;;WAEA;;;iBAIM;EACf,SAAS;;EAET,YAAY,iBAAiB,SAAS;;iBAGvB,eAAe,cAAc,UAAU,SAAS;;WAEtD;;WAEA;;WAEA;;WAEA;;WAEA;WACA,QAAQ;;WAER;;WAEA;WACA,OAAO;;WAEP,MAAM;;;;;;;EAOf,QACE,OAAO,OAAO,QACd,SAAS,kBACR,WAAW,WAAW,QAAQ,WAAW;;;qBAIjC,4BAA4B;EAC9B;;;qBAIE,uBAAuB;EACzB;;WAEA;;;;EAKT,YAAY;;;;;;;;wBAcE,iBAAiB,cAAc,SAAS,SACtD,MAAM,eAAe,OAAO,WAC3B,eAAe,OAAO;;;;;;;;;;wBA+GT,WAAW,MAAM,iBAAiB;;;;;;;;;;wBAalC,WAAW,gBAAgB,mBAAmB,oBAAoB;YAStE,WAAW,cAAc;EAC/B;EAAU,OAAO,OAAO;;EACxB;EAAW;;;;;;;;;;;;;;;;wBAgBD,cAAc,cAAc,SAC1C,MAAM,eAAe,iBACrB,gBACC,WAAW;;;;;;;;;;;;;wBA4JQ,WACpB,MAAM,gBACN,eACA,UAAS,kBACR,QAAQ;;;;;;;;;;;;wBAmCK,aAAa;;;;;;;wBAab,WAAW,QAAQ"}
|
package/dist/mcp.d.mts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { ToolDefinition } from "./index.mjs";
|
|
2
|
-
import { CallToolResult, Server, ToolAnnotations } from "@modelcontextprotocol/server";
|
|
3
|
-
|
|
1
|
+
import { ToolCallContext, ToolDefinition } from "./index.mjs";
|
|
2
|
+
import { CallToolResult, Server, Tool, ToolAnnotations } from "@modelcontextprotocol/server";
|
|
3
|
+
interface McpServerInfo {
|
|
4
4
|
/** Server name, also used in the unknown-tool message. */
|
|
5
5
|
readonly name: string;
|
|
6
6
|
readonly version: string;
|
|
@@ -28,6 +28,25 @@ export declare function toolAnnotations(tool: ToolDefinition): ToolAnnotations;
|
|
|
28
28
|
* @returns {CallToolResult} MCP error result.
|
|
29
29
|
*/
|
|
30
30
|
export declare function errorResult(...lines: readonly string[]): CallToolResult;
|
|
31
|
+
/**
|
|
32
|
+
* The entries `tools/list` answers with, in the order given.
|
|
33
|
+
*
|
|
34
|
+
* @param tools - Tools to list.
|
|
35
|
+
* @returns {Tool[]} Name, title, description, schema and annotations of each tool.
|
|
36
|
+
* @throws {ToolDefinitionError} When two tools share a name.
|
|
37
|
+
*/
|
|
38
|
+
export declare function listTools(tools: readonly ToolDefinition[]): Tool[];
|
|
39
|
+
/**
|
|
40
|
+
* Answers one call as `tools/call` does and never throws, so every transport gives the same text.
|
|
41
|
+
*
|
|
42
|
+
* @param info - Server info; `name` is the word in the message for an unknown tool.
|
|
43
|
+
* @param tools - Tools to look the name up in.
|
|
44
|
+
* @param name - Tool name as the client sent it.
|
|
45
|
+
* @param args - Arguments as the client sent them; missing ones count as `{}`.
|
|
46
|
+
* @param context - Context for this call, such as the request's abort signal.
|
|
47
|
+
* @returns {Promise<CallToolResult>} The tool's text, or the sanitized error.
|
|
48
|
+
*/
|
|
49
|
+
export declare function callTool(info: Pick<McpServerInfo, "name">, tools: readonly ToolDefinition[], name: string, args?: unknown, context?: ToolCallContext): Promise<CallToolResult>;
|
|
31
50
|
/**
|
|
32
51
|
* Creates an unconnected MCP server exposing the tools.
|
|
33
52
|
*
|
|
@@ -42,9 +61,13 @@ export declare function errorResult(...lines: readonly string[]): CallToolResult
|
|
|
42
61
|
* clients that see structured output prefer it over `content` and would hide
|
|
43
62
|
* the readable answer. Every fact a follow-up call needs belongs in the text.
|
|
44
63
|
*
|
|
64
|
+
* A progress notification that fails to send goes to `onerror`, never to the tool.
|
|
65
|
+
*
|
|
45
66
|
* @param info - Server name, version and optional title and website, sent to the client as given.
|
|
46
67
|
* @param tools - Tools to serve.
|
|
47
68
|
* @returns {Server} Unconnected MCP server.
|
|
69
|
+
* @throws {ToolDefinitionError} When two tools share a name.
|
|
48
70
|
*/
|
|
49
71
|
export declare function createMcpServer(info: McpServerInfo, tools: readonly ToolDefinition[]): Server;
|
|
72
|
+
export type { McpServerInfo };
|
|
50
73
|
//# sourceMappingURL=mcp.d.mts.map
|
package/dist/mcp.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mcp.d.mts","names":[],"sources":["../src/mcp.ts"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"mcp.d.mts","names":[],"sources":["../src/mcp-answers.ts","../src/mcp.ts"],"mappings":";;UAmBiB;;WAEN;WACA;;WAEA;;WAEA;;;;;;;;wBASK,gBAAgB,MAAM,iBAAiB;;;;;;;;;;;;wBAqBvC,eAAe,2BAA2B;;;;;;;;wBAW1C,UAAU,gBAAgB,mBAAmB;;;;;;;;;;;wBAqBvC,SACpB,MAAM,KAAK,wBACX,gBAAgB,kBAChB,cACA,gBACA,UAAS,kBACR,QAAQ;;;;;;;;;;;;;;;;;;;;;;wBClDK,gBAAgB,MAAM,eAAe,gBAAgB,mBAAmB"}
|
package/dist/mcp.mjs
CHANGED
|
@@ -1,25 +1,8 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { indexTools } from "./_chunks/src.mjs";
|
|
2
|
+
import { callTool, errorResult, listTools, progressSteps, toolAnnotations } from "./_chunks/mcp-answers.mjs";
|
|
2
3
|
import { Server } from "@modelcontextprotocol/server";
|
|
3
|
-
function toolAnnotations(tool) {
|
|
4
|
-
return {
|
|
5
|
-
title: tool.title,
|
|
6
|
-
readOnlyHint: tool.effect === "read",
|
|
7
|
-
destructiveHint: tool.effect === "destructive",
|
|
8
|
-
idempotentHint: tool.idempotent ?? tool.effect === "read",
|
|
9
|
-
openWorldHint: tool.openWorld ?? false
|
|
10
|
-
};
|
|
11
|
-
}
|
|
12
|
-
function errorResult(...lines) {
|
|
13
|
-
return {
|
|
14
|
-
content: [{
|
|
15
|
-
type: "text",
|
|
16
|
-
text: lines.map(sanitizeLine).join("\n")
|
|
17
|
-
}],
|
|
18
|
-
isError: true
|
|
19
|
-
};
|
|
20
|
-
}
|
|
21
4
|
function createMcpServer(info, tools) {
|
|
22
|
-
|
|
5
|
+
indexTools(tools);
|
|
23
6
|
const { name, version, title, websiteUrl } = info;
|
|
24
7
|
const server = new Server({
|
|
25
8
|
name,
|
|
@@ -27,29 +10,27 @@ function createMcpServer(info, tools) {
|
|
|
27
10
|
title,
|
|
28
11
|
websiteUrl
|
|
29
12
|
}, { capabilities: { tools: {} } });
|
|
30
|
-
server.setRequestHandler("tools/list", () => ({ tools: tools
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
return errorResult(`${tool.name} failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
49
|
-
}
|
|
13
|
+
server.setRequestHandler("tools/list", () => ({ tools: listTools(tools) }));
|
|
14
|
+
server.setRequestHandler("tools/call", (request, ctx) => {
|
|
15
|
+
const progressToken = ctx.mcpReq._meta?.progressToken;
|
|
16
|
+
const notify = (params) => {
|
|
17
|
+
ctx.mcpReq.notify({
|
|
18
|
+
method: "notifications/progress",
|
|
19
|
+
params: {
|
|
20
|
+
progressToken,
|
|
21
|
+
...params
|
|
22
|
+
}
|
|
23
|
+
}).catch((error) => {
|
|
24
|
+
server.onerror?.(error instanceof Error ? error : new Error(String(error)));
|
|
25
|
+
});
|
|
26
|
+
};
|
|
27
|
+
return callTool(info, tools, request.params.name, request.params.arguments, {
|
|
28
|
+
signal: ctx.mcpReq.signal,
|
|
29
|
+
...progressToken === void 0 ? {} : { progress: progressSteps(notify) }
|
|
30
|
+
});
|
|
50
31
|
});
|
|
51
32
|
return server;
|
|
52
33
|
}
|
|
53
|
-
export { createMcpServer, errorResult, toolAnnotations };
|
|
34
|
+
export { callTool, createMcpServer, errorResult, listTools, toolAnnotations };
|
|
54
35
|
|
|
55
36
|
//# sourceMappingURL=mcp.mjs.map
|
package/dist/mcp.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mcp.mjs","names":[],"sources":["../src/mcp.ts"],"sourcesContent":["/**\n * MCP adapter: serves {@link ToolDefinition}s from an unconnected MCP server.\n */\n\nimport {
|
|
1
|
+
{"version":3,"file":"mcp.mjs","names":[],"sources":["../src/mcp.ts"],"sourcesContent":["/**\n * MCP adapter: serves {@link ToolDefinition}s from an unconnected MCP server.\n */\n\nimport { Server } from \"@modelcontextprotocol/server\";\n\nimport { indexTools, type ToolDefinition } from \"./index.ts\";\nimport {\n callTool,\n listTools,\n progressSteps,\n type McpServerInfo,\n type ProgressParams,\n} from \"./mcp-answers.ts\";\n\nexport {\n callTool,\n errorResult,\n listTools,\n toolAnnotations,\n type McpServerInfo,\n} from \"./mcp-answers.ts\";\n\n/**\n * Creates an unconnected MCP server exposing the tools.\n *\n * Built on the low-level `Server` of MCP SDK v2, which the SDK marks\n * `@deprecated`, not on `McpServer`. `McpServer.registerTool` in 2.2.0 would\n * take the schema, but it answers `toString`, `constructor` and `__proto__` as\n * \"Tool toString disabled\" (a lookup that reaches `Object.prototype`), echoes a\n * raw tool name with newlines and escapes into its error, joins validation\n * failures into one line and passes a thrown message through unsanitized.\n *\n * `details` never reaches the client and `structuredContent` is never set:\n * clients that see structured output prefer it over `content` and would hide\n * the readable answer. Every fact a follow-up call needs belongs in the text.\n *\n * A progress notification that fails to send goes to `onerror`, never to the tool.\n *\n * @param info - Server name, version and optional title and website, sent to the client as given.\n * @param tools - Tools to serve.\n * @returns {Server} Unconnected MCP server.\n * @throws {ToolDefinitionError} When two tools share a name.\n */\nexport function createMcpServer(info: McpServerInfo, tools: readonly ToolDefinition[]): Server {\n indexTools(tools);\n const { name, version, title, websiteUrl } = info;\n const server = new Server({ name, version, title, websiteUrl }, { capabilities: { tools: {} } });\n\n server.setRequestHandler(\"tools/list\", () => ({ tools: listTools(tools) }));\n server.setRequestHandler(\"tools/call\", (request, ctx) => {\n const progressToken = ctx.mcpReq._meta?.progressToken;\n const notify = (params: ProgressParams): void => {\n ctx.mcpReq\n .notify({ method: \"notifications/progress\", params: { progressToken, ...params } })\n .catch((error: unknown) => {\n server.onerror?.(error instanceof Error ? error : new Error(String(error)));\n });\n };\n return callTool(info, tools, request.params.name, request.params.arguments, {\n signal: ctx.mcpReq.signal,\n ...(progressToken === undefined ? {} : { progress: progressSteps(notify) }),\n });\n });\n\n return server;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;EA4CA;EACE,OAAA,SAAgB,MAAA,OAAA,QAAA,OAAA,MAAA,QAAA,OAAA,WAAA;GAChB,QAAQ,IAAM,OAAA;GACd,GAAA,kBAAmB,KAAO,IAAA,CAAA,IAAA,EAAA,UAAA,cAAA,MAAA,EAAA;EAAE,CAAA;CAAM,CAAA;CAAS,OAAA;AAAO;AAElD,SAAO,UAAA,iBAAkB,aAAuB,WAAO"}
|
package/dist/omp.d.mts
CHANGED
|
@@ -21,6 +21,8 @@ export interface OmpRenderers {
|
|
|
21
21
|
export interface OmpToolOptions {
|
|
22
22
|
/** The host `Text` component, imported by the extension from the package root. */
|
|
23
23
|
readonly Text: TextComponent;
|
|
24
|
+
/** `"essential"` keeps every tool in OMP's top-level list. Left out, OMP hides them behind discovery. */
|
|
25
|
+
readonly loadMode?: ToolDefinition["loadMode"];
|
|
24
26
|
/** Status-line renderers by tool name. */
|
|
25
27
|
readonly renderers?: Readonly<Record<string, OmpRenderers>>;
|
|
26
28
|
}
|
|
@@ -34,7 +36,8 @@ export interface OmpToolOptions {
|
|
|
34
36
|
*
|
|
35
37
|
* @param pi - OMP extension API.
|
|
36
38
|
* @param tools - Tools to register.
|
|
37
|
-
* @param options - Host `Text
|
|
39
|
+
* @param options - Host `Text`, optional load mode and renderers.
|
|
40
|
+
* @throws {ToolDefinitionError} When two tools share a name.
|
|
38
41
|
*/
|
|
39
42
|
export declare function registerOmpTools(pi: ExtensionAPI, tools: readonly ToolDefinition$1[], options: OmpToolOptions): void;
|
|
40
43
|
//# sourceMappingURL=omp.d.mts.map
|
package/dist/omp.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"omp.d.mts","names":["HostText","OmpToolDefinition","ToolDefinition"],"sources":["../src/omp.ts"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"omp.d.mts","names":["HostText","OmpToolDefinition","ToolDefinition"],"sources":["../src/omp.ts"],"mappings":";;KA2BK,uBAAuBA;;iBAIX;WACN;WACA;;;iBAIM;;EAEf,cAAc,MAAM,SAAS;;EAE7B,gBAAgB,QAAQ;;;;;EAKxB,eAAeC;;iBAGA;;WAEN,MAAM;;WAEN,WAAWA;;WAEX,YAAY,SAAS,eAAe;;;;;;;;;;;;;;;wBAuB/B,iBACd,IAAI,cACJ,gBAAgBC,oBAChB,SAAS"}
|
package/dist/omp.mjs
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
|
-
import { invokeTool, sanitizeLine, wireSchema } from "./_chunks/src.mjs";
|
|
1
|
+
import { indexTools, invokeTool, sanitizeLine, wireSchema } from "./_chunks/src.mjs";
|
|
2
|
+
import { hostContext } from "./_chunks/updates.mjs";
|
|
2
3
|
const APPROVAL = {
|
|
3
4
|
read: "read",
|
|
4
5
|
write: "write",
|
|
5
6
|
destructive: "write"
|
|
6
7
|
};
|
|
7
8
|
function registerOmpTools(pi, tools, options) {
|
|
9
|
+
indexTools(tools);
|
|
8
10
|
const { Type } = pi.typebox;
|
|
9
11
|
const { Text } = options;
|
|
10
12
|
for (const tool of tools) {
|
|
@@ -15,8 +17,9 @@ function registerOmpTools(pi, tools, options) {
|
|
|
15
17
|
description: tool.description,
|
|
16
18
|
parameters: Type.Unsafe(wireSchema(tool)),
|
|
17
19
|
approval: APPROVAL[tool.effect],
|
|
18
|
-
|
|
19
|
-
|
|
20
|
+
loadMode: options.loadMode,
|
|
21
|
+
async execute(_toolCallId, params, signal, onUpdate) {
|
|
22
|
+
return await invokeTool(tool, params, hostContext(signal, onUpdate));
|
|
20
23
|
},
|
|
21
24
|
renderCall(args, renderOptions, theme) {
|
|
22
25
|
const summary = renderers?.describeCall ? sanitizeLine(renderers.describeCall(args)) : "";
|
|
@@ -25,16 +28,25 @@ function registerOmpTools(pi, tools, options) {
|
|
|
25
28
|
},
|
|
26
29
|
renderResult(result, renderOptions, theme, args) {
|
|
27
30
|
if (renderers?.renderResult) return renderers.renderResult(result, renderOptions, theme, args);
|
|
31
|
+
if (renderOptions.isPartial) return new Text(progressLine(tool, result, renderOptions, theme), 0, 0);
|
|
28
32
|
const icon = result.isError ? theme.styledSymbol("status.error", "error") : theme.styledSymbol("status.done", "success");
|
|
29
33
|
const { bracketLeft, bracketRight } = theme.format;
|
|
30
34
|
const badge = theme.fg("accent", `${bracketLeft}${APPROVAL[tool.effect]}${bracketRight}`);
|
|
31
|
-
const facts = result.isError ? [] : renderers?.describeResult?.(result)
|
|
32
|
-
|
|
33
|
-
return new Text(`${icon} ${theme.fg("accent", sanitizeLine(tool.title))} ${badge}${meta}`, 0, 0);
|
|
35
|
+
const facts = result.isError ? [] : renderers?.describeResult?.(result) ?? [];
|
|
36
|
+
return new Text(`${icon} ${theme.fg("accent", sanitizeLine(tool.title))} ${badge}${dimFacts(facts, theme)}`, 0, 0);
|
|
34
37
|
}
|
|
35
38
|
});
|
|
36
39
|
}
|
|
37
40
|
}
|
|
41
|
+
function progressLine(tool, result, options, theme) {
|
|
42
|
+
const message = sanitizeLine(result.content.findLast((block) => block.type === "text")?.text ?? "");
|
|
43
|
+
const title = theme.fg("accent", sanitizeLine(tool.title));
|
|
44
|
+
return `${callIcon(options, theme)} ${title}${message ? ` ${theme.fg("dim", message)}` : ""}`;
|
|
45
|
+
}
|
|
46
|
+
function dimFacts(facts, theme) {
|
|
47
|
+
const shown = facts.map(sanitizeLine).filter(Boolean);
|
|
48
|
+
return shown.length > 0 ? ` ${theme.fg("dim", shown.join(theme.sep.dot))}` : "";
|
|
49
|
+
}
|
|
38
50
|
function callIcon(options, theme) {
|
|
39
51
|
if (!options.isPartial) return theme.styledSymbol("status.done", "success");
|
|
40
52
|
if (options.spinnerFrame === void 0) return theme.styledSymbol("status.pending", "muted");
|
package/dist/omp.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"omp.mjs","names":[],"sources":["../src/omp.ts"],"sourcesContent":["/**\n * OMP adapter: registers {@link ToolDefinition}s on an OMP `ExtensionAPI`.\n *\n * Only types come from `@oh-my-pi/pi-coding-agent`. Compiled OMP injects the\n * package root into the extension file itself, not into its dependencies, so\n * the extension passes the host `Text` component in.\n */\n\nimport type {\n AgentToolResult,\n ExtensionAPI,\n Text as HostText,\n Theme,\n ToolDefinition as OmpToolDefinition,\n ToolRenderResultOptions,\n} from \"@oh-my-pi/pi-coding-agent\";\n\nimport {\n invokeTool,\n sanitizeLine,\n wireSchema,\n type ToolDefinition,\n type ToolEffect,\n} from \"./index.ts\";\n\ntype TextComponent = typeof HostText;\ntype Component = ReturnType<NonNullable<OmpToolDefinition[\"renderCall\"]>>;\n\n/** The part of a host result a renderer reads. */\nexport interface OmpResultView {\n readonly details?: unknown;\n readonly isError?: boolean;\n}\n\n/** Per-tool renderer overrides, drawn with the host theme. */\nexport interface OmpRenderers {\n /** One-line summary of the arguments after the title. Sanitized by the adapter. */\n describeCall?(args: Readonly<Record<string, unknown>>): unknown;\n /** Short metadata after the badge, one entry per fact. Each entry is sanitized. */\n describeResult?(result: OmpResultView): readonly unknown[];\n /**\n * Replaces the result status line with the package's own component, such as\n * a bounded preview of long output. It owns sanitizing what it draws.\n */\n renderResult?: OmpToolDefinition[\"renderResult\"];\n}\n\nexport interface OmpToolOptions {\n /** The host `Text` component, imported by the extension from the package root. */\n readonly Text: TextComponent;\n /** Status-line renderers by tool name. */\n readonly renderers?: Readonly<Record<string, OmpRenderers>>;\n}\n\nconst APPROVAL: Record<ToolEffect, \"read\" | \"write\"> = {\n read: \"read\",\n write: \"write\",\n // OMP has no destructive tier; `exec` means running commands.\n destructive: \"write\",\n};\n\n/**\n * Registers every tool on the OMP extension API.\n *\n * The schema reaches OMP through `pi.typebox.Type.Unsafe`: the host-injected\n * build validates the raw JSON Schema with its full validator and emits the\n * document verbatim, so `pattern` and `maxProperties` survive. A standalone\n * omptype schema would drop both.\n *\n * @param pi - OMP extension API.\n * @param tools - Tools to register.\n * @param options - Host `Text
|
|
1
|
+
{"version":3,"file":"omp.mjs","names":[],"sources":["../src/omp.ts"],"sourcesContent":["/**\n * OMP adapter: registers {@link ToolDefinition}s on an OMP `ExtensionAPI`.\n *\n * Only types come from `@oh-my-pi/pi-coding-agent`. Compiled OMP injects the\n * package root into the extension file itself, not into its dependencies, so\n * the extension passes the host `Text` component in.\n */\n\nimport type {\n AgentToolResult,\n ExtensionAPI,\n Text as HostText,\n Theme,\n ToolDefinition as OmpToolDefinition,\n ToolRenderResultOptions,\n} from \"@oh-my-pi/pi-coding-agent\";\n\nimport {\n indexTools,\n invokeTool,\n sanitizeLine,\n wireSchema,\n type ToolDefinition,\n type ToolEffect,\n} from \"./index.ts\";\nimport { hostContext } from \"./updates.ts\";\n\ntype TextComponent = typeof HostText;\ntype Component = ReturnType<NonNullable<OmpToolDefinition[\"renderCall\"]>>;\n\n/** The part of a host result a renderer reads. */\nexport interface OmpResultView {\n readonly details?: unknown;\n readonly isError?: boolean;\n}\n\n/** Per-tool renderer overrides, drawn with the host theme. */\nexport interface OmpRenderers {\n /** One-line summary of the arguments after the title. Sanitized by the adapter. */\n describeCall?(args: Readonly<Record<string, unknown>>): unknown;\n /** Short metadata after the badge, one entry per fact. Each entry is sanitized. */\n describeResult?(result: OmpResultView): readonly unknown[];\n /**\n * Replaces the result status line with the package's own component, such as\n * a bounded preview of long output. It owns sanitizing what it draws.\n */\n renderResult?: OmpToolDefinition[\"renderResult\"];\n}\n\nexport interface OmpToolOptions {\n /** The host `Text` component, imported by the extension from the package root. */\n readonly Text: TextComponent;\n /** `\"essential\"` keeps every tool in OMP's top-level list. Left out, OMP hides them behind discovery. */\n readonly loadMode?: OmpToolDefinition[\"loadMode\"];\n /** Status-line renderers by tool name. */\n readonly renderers?: Readonly<Record<string, OmpRenderers>>;\n}\n\nconst APPROVAL: Record<ToolEffect, \"read\" | \"write\"> = {\n read: \"read\",\n write: \"write\",\n // OMP has no destructive tier; `exec` means running commands.\n destructive: \"write\",\n};\n\n/**\n * Registers every tool on the OMP extension API.\n *\n * The schema reaches OMP through `pi.typebox.Type.Unsafe`: the host-injected\n * build validates the raw JSON Schema with its full validator and emits the\n * document verbatim, so `pattern` and `maxProperties` survive. A standalone\n * omptype schema would drop both.\n *\n * @param pi - OMP extension API.\n * @param tools - Tools to register.\n * @param options - Host `Text`, optional load mode and renderers.\n * @throws {ToolDefinitionError} When two tools share a name.\n */\nexport function registerOmpTools(\n pi: ExtensionAPI,\n tools: readonly ToolDefinition[],\n options: OmpToolOptions,\n): void {\n indexTools(tools);\n const { Type } = pi.typebox;\n const { Text } = options;\n\n for (const tool of tools) {\n const renderers = Object.hasOwn(options.renderers ?? {}, tool.name)\n ? options.renderers?.[tool.name]\n : undefined;\n\n pi.registerTool({\n name: tool.name,\n label: tool.title,\n description: tool.description,\n parameters: Type.Unsafe<Record<string, unknown>>(wireSchema(tool)),\n approval: APPROVAL[tool.effect],\n loadMode: options.loadMode,\n async execute(_toolCallId, params, signal, onUpdate): Promise<AgentToolResult<unknown>> {\n // Returned as is: OMP reads `isError` from the object (`explicitError`).\n return await invokeTool(tool, params, hostContext(signal, onUpdate));\n },\n renderCall(args, renderOptions, theme): Component {\n const summary = renderers?.describeCall ? sanitizeLine(renderers.describeCall(args)) : \"\";\n const title = theme.fg(\"accent\", sanitizeLine(tool.title));\n return new Text(\n `${callIcon(renderOptions, theme)} ${title}${summary ? `: ${theme.fg(\"muted\", summary)}` : \"\"}`,\n 0,\n 0,\n );\n },\n renderResult(result, renderOptions, theme, args): Component {\n if (renderers?.renderResult)\n return renderers.renderResult(result, renderOptions, theme, args);\n if (renderOptions.isPartial)\n return new Text(progressLine(tool, result, renderOptions, theme), 0, 0);\n const icon = result.isError\n ? theme.styledSymbol(\"status.error\", \"error\")\n : theme.styledSymbol(\"status.done\", \"success\");\n const { bracketLeft, bracketRight } = theme.format;\n const badge = theme.fg(\"accent\", `${bracketLeft}${APPROVAL[tool.effect]}${bracketRight}`);\n const facts = result.isError ? [] : (renderers?.describeResult?.(result) ?? []);\n return new Text(\n `${icon} ${theme.fg(\"accent\", sanitizeLine(tool.title))} ${badge}${dimFacts(facts, theme)}`,\n 0,\n 0,\n );\n },\n });\n }\n}\n\n/**\n * Status line while the call runs: the spinner, the title and its last progress line.\n *\n * @param tool - Tool being called.\n * @param result - Partial result from `onUpdate`.\n * @param options - Render options from the host.\n * @param theme - Host theme.\n * @returns {string} The styled line.\n */\nfunction progressLine(\n tool: ToolDefinition,\n result: Readonly<{ content: readonly Readonly<{ type: string; text?: string }>[] }>,\n options: ToolRenderResultOptions,\n theme: Theme,\n): string {\n const message = sanitizeLine(\n result.content.findLast((block) => block.type === \"text\")?.text ?? \"\",\n );\n const title = theme.fg(\"accent\", sanitizeLine(tool.title));\n return `${callIcon(options, theme)} ${title}${message ? ` ${theme.fg(\"dim\", message)}` : \"\"}`;\n}\n\n/**\n * The `describeResult` facts after the badge, sanitized and dimmed; empty ones drop out.\n *\n * @param facts - Facts as the renderer gave them.\n * @param theme - Host theme.\n * @returns {string} The facts with a leading space, or nothing.\n */\nfunction dimFacts(facts: readonly unknown[], theme: Theme): string {\n const shown = facts.map(sanitizeLine).filter(Boolean);\n return shown.length > 0 ? ` ${theme.fg(\"dim\", shown.join(theme.sep.dot))}` : \"\";\n}\n\n/**\n * Status icon for a call: pending, spinning or done.\n *\n * Drawn with the host theme on purpose: compiled OMP injects only the package\n * root, so importing `@oh-my-pi/pi-coding-agent/tui` would stop the extension.\n *\n * @param options - Render options from the host.\n * @param theme - Host theme.\n * @returns {string} The styled icon.\n */\nfunction callIcon(options: ToolRenderResultOptions, theme: Theme): string {\n if (!options.isPartial) return theme.styledSymbol(\"status.done\", \"success\");\n if (options.spinnerFrame === undefined) return theme.styledSymbol(\"status.pending\", \"muted\");\n return (\n theme.spinnerFrames[options.spinnerFrame % theme.spinnerFrames.length] ??\n theme.styledSymbol(\"status.running\", \"accent\")\n );\n}\n"],"mappings":";;AA0DA,MAAM,WAAiD;CACrD,MAAM;CACN,OAAO;CAEP,aAAa;A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,GAAO,UAChB,aAAM,KAAA,KAAa,CAAA;CAEvB,OAAA,GAAM,SAAE,SAAa,KAAA,EAAA,GAAA,QAAiB,UAAM,IAAA,MAAA,GAAA,OAAA,OAAA,MAAA;AAC5C;AAEA,SAAA,SAAW,OACN,OAAQ;CAIf,MAAA,QAAA,MAAA,IAAA,YAAA,CAAA,CAAA,OAAA,OAAA;CACF,OAAC,MAAA,SAAA,IAAA,IAAA,MAAA,GAAA,OAAA,MAAA,KAAA,MAAA,IAAA,GAAA,CAAA,MAAA;AACH"}
|
package/dist/pi.d.mts
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import { ToolDefinition as ToolDefinition$1 } from "./index.mjs";
|
|
2
2
|
import { ExtensionAPI, ToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
type Component = ReturnType<NonNullable<ToolDefinition["renderCall"]>>;
|
|
4
|
+
/** The `Text` component of `@earendil-works/pi-tui`, which Pi resolves for every extension. */
|
|
5
|
+
export type PiTextComponent = new (text: string, paddingX: number, paddingY: number) => Component;
|
|
3
6
|
export interface PiToolOptions {
|
|
4
7
|
/**
|
|
5
8
|
* How a returned `isError` result reaches Pi.
|
|
@@ -10,17 +13,33 @@ export interface PiToolOptions {
|
|
|
10
13
|
* only with a peer range of `>=0.99.0`, since Pi does not check peer ranges.
|
|
11
14
|
*/
|
|
12
15
|
readonly failures?: "throw" | "return";
|
|
13
|
-
/** Host
|
|
16
|
+
/** Host `Text` from `@earendil-works/pi-tui`, which `describeCall` draws with. */
|
|
17
|
+
readonly Text?: PiTextComponent;
|
|
18
|
+
/** Renderers by tool name. */
|
|
14
19
|
readonly renderers?: Readonly<Record<string, PiRenderers>>;
|
|
20
|
+
/** Questions to ask before a call runs, by tool name. A name off the tool list throws. */
|
|
21
|
+
readonly confirm?: Readonly<Record<string, PiConfirm>>;
|
|
22
|
+
}
|
|
23
|
+
/** Builds the question for one call from its validated input; `undefined` skips it. */
|
|
24
|
+
export type PiConfirm = (input: Readonly<Record<string, unknown>>) => PiQuestion | undefined | Promise<PiQuestion | undefined>;
|
|
25
|
+
/** What `ctx.ui.confirm` shows. The adapter sanitizes both and keeps the message's lines. */
|
|
26
|
+
export interface PiQuestion {
|
|
27
|
+
readonly title: string;
|
|
28
|
+
readonly message: string;
|
|
29
|
+
}
|
|
30
|
+
/** Renderers for one tool: Pi's own, passed unchanged, or a one-line call summary. */
|
|
31
|
+
export interface PiRenderers extends Readonly<Pick<ToolDefinition, "renderCall" | "renderResult">> {
|
|
32
|
+
/** One-line summary of the arguments after the title, sanitized here. A `renderCall` wins. */
|
|
33
|
+
readonly describeCall?: (args: Readonly<Record<string, unknown>>) => unknown;
|
|
15
34
|
}
|
|
16
|
-
/** The host's own call and result renderers for one tool. */
|
|
17
|
-
export type PiRenderers = Pick<ToolDefinition, "renderCall" | "renderResult">;
|
|
18
35
|
/**
|
|
19
36
|
* Registers every tool on the Pi extension API.
|
|
20
37
|
*
|
|
21
38
|
* @param pi - Pi extension API.
|
|
22
39
|
* @param tools - Tools to register.
|
|
23
|
-
* @param options - Failure policy and
|
|
40
|
+
* @param options - Failure policy, host `Text`, renderers and questions.
|
|
41
|
+
* @throws {ToolDefinitionError} When two tools share a name, a tool has `describeCall` but no
|
|
42
|
+
* `Text` came with it, or `confirm` names a tool that isn't in the list.
|
|
24
43
|
*/
|
|
25
44
|
export declare function registerPiTools(pi: ExtensionAPI, tools: readonly ToolDefinition$1[], options?: PiToolOptions): void;
|
|
26
45
|
//# sourceMappingURL=pi.d.mts.map
|
package/dist/pi.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pi.d.mts","names":["PiToolDefinition","ToolDefinition"],"sources":["../src/pi.ts"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"pi.d.mts","names":["PiToolDefinition","ToolDefinition"],"sources":["../src/pi.ts"],"mappings":";;KA4BK,YAAY,WAAW,YAAYA;;YAG5B,uBAAuB,cAAc,kBAAkB,qBAAqB;iBAEvE;;;;;;;;;WASN;;WAEA,OAAO;;WAEP,YAAY,SAAS,eAAe;;WAEpC,UAAU,SAAS,eAAe;;;YAIjC,aACV,OAAO,SAAS,6BACb,yBAAyB,QAAQ;;iBAGrB;WACN;WACA;;;iBAIM,oBAAoB,SACnC,KAAKA;;WAGI,gBAAgB,MAAM,SAAS;;;;;;;;;;;wBAY1B,gBACd,IAAI,cACJ,gBAAgBC,oBAChB,UAAS"}
|
package/dist/pi.mjs
CHANGED
|
@@ -1,24 +1,58 @@
|
|
|
1
|
-
import { invokeTool, resultText } from "./_chunks/src.mjs";
|
|
1
|
+
import { ToolDefinitionError, ToolInputError, indexTools, invokeTool, resultText, sanitizeLine, sanitizeText, validateInput } from "./_chunks/src.mjs";
|
|
2
|
+
import { hostContext } from "./_chunks/updates.mjs";
|
|
2
3
|
function registerPiTools(pi, tools, options = {}) {
|
|
4
|
+
const listed = indexTools(tools);
|
|
3
5
|
const failures = options.failures ?? "throw";
|
|
6
|
+
const stray = Object.keys(options.confirm ?? {}).find((name) => !listed.has(name));
|
|
7
|
+
if (stray !== void 0) throw new ToolDefinitionError(`confirm names ${JSON.stringify(stray)}, which isn't in the tool list`);
|
|
4
8
|
for (const tool of tools) {
|
|
5
|
-
const renderers =
|
|
9
|
+
const renderers = byName(options.renderers, tool.name);
|
|
10
|
+
const ask = byName(options.confirm, tool.name);
|
|
6
11
|
pi.registerTool({
|
|
7
|
-
...renderers,
|
|
12
|
+
...hostRenderers(tool, renderers, options.Text),
|
|
8
13
|
name: tool.name,
|
|
9
14
|
label: tool.title,
|
|
10
15
|
description: tool.description,
|
|
11
16
|
...tool.snippet === void 0 ? {} : { promptSnippet: tool.snippet },
|
|
12
17
|
...tool.guidelines === void 0 ? {} : { promptGuidelines: [...tool.guidelines] },
|
|
13
18
|
parameters: tool.input,
|
|
14
|
-
async execute(_toolCallId, params, signal) {
|
|
15
|
-
|
|
19
|
+
async execute(_toolCallId, params, signal, onUpdate, ctx) {
|
|
20
|
+
if (ask) await approve(tool, ask, params, signal, ctx);
|
|
21
|
+
const result = await invokeTool(tool, params, hostContext(signal, onUpdate));
|
|
16
22
|
if (result.isError && failures === "throw") throw new Error(resultText(result));
|
|
17
23
|
return result;
|
|
18
24
|
}
|
|
19
25
|
});
|
|
20
26
|
}
|
|
21
27
|
}
|
|
28
|
+
function byName(entries, name) {
|
|
29
|
+
return entries && Object.hasOwn(entries, name) ? entries[name] : void 0;
|
|
30
|
+
}
|
|
31
|
+
async function approve(tool, ask, params, signal, ctx) {
|
|
32
|
+
const checked = validateInput(tool, params);
|
|
33
|
+
if (!checked.ok) throw new ToolInputError(checked.lines);
|
|
34
|
+
const question = await ask(checked.value);
|
|
35
|
+
if (question === void 0) return;
|
|
36
|
+
if (!ctx.hasUI) throw new Error(`${tool.name} needs interactive approval in Pi TUI or RPC mode`);
|
|
37
|
+
const approved = await ctx.ui.confirm(sanitizeLine(question.title), sanitizeText(question.message), signal ? { signal } : {});
|
|
38
|
+
signal?.throwIfAborted();
|
|
39
|
+
if (!approved) throw new Error(`${tool.name} was cancelled by the user. Do not retry unless the user asks again.`);
|
|
40
|
+
}
|
|
41
|
+
function hostRenderers(tool, renderers, Text) {
|
|
42
|
+
if (!renderers) return {};
|
|
43
|
+
const { describeCall, ...own } = renderers;
|
|
44
|
+
if (own.renderCall || !describeCall) return own;
|
|
45
|
+
if (!Text) throw new ToolDefinitionError(`${tool.name}: describeCall needs the host Text option`);
|
|
46
|
+
const title = sanitizeLine(tool.title);
|
|
47
|
+
return {
|
|
48
|
+
...own,
|
|
49
|
+
renderCall(args, theme) {
|
|
50
|
+
const summary = sanitizeLine(describeCall(args));
|
|
51
|
+
const header = theme.fg("toolTitle", theme.bold(title));
|
|
52
|
+
return new Text(summary ? `${header} ${theme.fg("muted", summary)}` : header, 0, 0);
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
}
|
|
22
56
|
export { registerPiTools };
|
|
23
57
|
|
|
24
58
|
//# sourceMappingURL=pi.mjs.map
|
package/dist/pi.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pi.mjs","names":[],"sources":["../src/pi.ts"],"sourcesContent":["/**\n * Pi adapter: registers {@link ToolDefinition}s on a Pi `ExtensionAPI`.\n *\n * Only types come from `@earendil-works/pi-coding-agent`; nothing is imported\n * from the host at runtime.\n */\n\nimport type {\n AgentToolResult,\n ExtensionAPI,\n ToolDefinition as PiToolDefinition,\n} from \"@earendil-works/pi-coding-agent\";\n\nimport { invokeTool
|
|
1
|
+
{"version":3,"file":"pi.mjs","names":[],"sources":["../src/pi.ts"],"sourcesContent":["/**\n * Pi adapter: registers {@link ToolDefinition}s on a Pi `ExtensionAPI`.\n *\n * Only types come from `@earendil-works/pi-coding-agent`; nothing is imported\n * from the host at runtime. A call line from `describeCall` needs the host\n * `Text`, which the extension passes in.\n */\n\nimport type {\n AgentToolResult,\n ExtensionAPI,\n ExtensionContext,\n ToolDefinition as PiToolDefinition,\n} from \"@earendil-works/pi-coding-agent\";\n\nimport { sanitizeText } from \"./escapes.ts\";\nimport {\n indexTools,\n invokeTool,\n resultText,\n sanitizeLine,\n ToolDefinitionError,\n ToolInputError,\n validateInput,\n type ToolDefinition,\n} from \"./index.ts\";\nimport { hostContext } from \"./updates.ts\";\n\ntype Component = ReturnType<NonNullable<PiToolDefinition[\"renderCall\"]>>;\n\n/** The `Text` component of `@earendil-works/pi-tui`, which Pi resolves for every extension. */\nexport type PiTextComponent = new (text: string, paddingX: number, paddingY: number) => Component;\n\nexport interface PiToolOptions {\n /**\n * How a returned `isError` result reaches Pi.\n *\n * `throw` (default) raises the result text: `pi-agent-core` up to 0.98 marks\n * every returned object as a success and records an error only after a throw.\n * `return` hands the result over unchanged and keeps its `details`; use it\n * only with a peer range of `>=0.99.0`, since Pi does not check peer ranges.\n */\n readonly failures?: \"throw\" | \"return\";\n /** Host `Text` from `@earendil-works/pi-tui`, which `describeCall` draws with. */\n readonly Text?: PiTextComponent;\n /** Renderers by tool name. */\n readonly renderers?: Readonly<Record<string, PiRenderers>>;\n /** Questions to ask before a call runs, by tool name. A name off the tool list throws. */\n readonly confirm?: Readonly<Record<string, PiConfirm>>;\n}\n\n/** Builds the question for one call from its validated input; `undefined` skips it. */\nexport type PiConfirm = (\n input: Readonly<Record<string, unknown>>,\n) => PiQuestion | undefined | Promise<PiQuestion | undefined>;\n\n/** What `ctx.ui.confirm` shows. The adapter sanitizes both and keeps the message's lines. */\nexport interface PiQuestion {\n readonly title: string;\n readonly message: string;\n}\n\n/** Renderers for one tool: Pi's own, passed unchanged, or a one-line call summary. */\nexport interface PiRenderers extends Readonly<\n Pick<PiToolDefinition, \"renderCall\" | \"renderResult\">\n> {\n /** One-line summary of the arguments after the title, sanitized here. A `renderCall` wins. */\n readonly describeCall?: (args: Readonly<Record<string, unknown>>) => unknown;\n}\n\n/**\n * Registers every tool on the Pi extension API.\n *\n * @param pi - Pi extension API.\n * @param tools - Tools to register.\n * @param options - Failure policy, host `Text`, renderers and questions.\n * @throws {ToolDefinitionError} When two tools share a name, a tool has `describeCall` but no\n * `Text` came with it, or `confirm` names a tool that isn't in the list.\n */\nexport function registerPiTools(\n pi: ExtensionAPI,\n tools: readonly ToolDefinition[],\n options: PiToolOptions = {},\n): void {\n const listed = indexTools(tools);\n const failures = options.failures ?? \"throw\";\n const stray = Object.keys(options.confirm ?? {}).find((name) => !listed.has(name));\n if (stray !== undefined) {\n throw new ToolDefinitionError(\n `confirm names ${JSON.stringify(stray)}, which isn't in the tool list`,\n );\n }\n\n for (const tool of tools) {\n const renderers = byName(options.renderers, tool.name);\n const ask = byName(options.confirm, tool.name);\n pi.registerTool({\n ...hostRenderers(tool, renderers, options.Text),\n name: tool.name,\n label: tool.title,\n description: tool.description,\n ...(tool.snippet === undefined ? {} : { promptSnippet: tool.snippet }),\n ...(tool.guidelines === undefined ? {} : { promptGuidelines: [...tool.guidelines] }),\n parameters: tool.input,\n async execute(_toolCallId, params, signal, onUpdate, ctx): Promise<AgentToolResult<unknown>> {\n if (ask) await approve(tool, ask, params, signal, ctx);\n const result = await invokeTool(tool, params, hostContext(signal, onUpdate));\n if (result.isError && failures === \"throw\") throw new Error(resultText(result));\n return result;\n },\n });\n }\n}\n\n/**\n * Own entry of a by-name option, so a tool named `constructor` doesn't reach the prototype.\n *\n * @param entries - Option keyed by tool name.\n * @param name - Tool name.\n * @returns {T | undefined} The entry, if the option has one for this tool.\n */\nfunction byName<T>(entries: Readonly<Record<string, T>> | undefined, name: string): T | undefined {\n return entries && Object.hasOwn(entries, name) ? entries[name] : undefined;\n}\n\n/**\n * Asks the user about one call and throws unless they say yes.\n *\n * @param tool - Tool being called.\n * @param ask - Its question builder.\n * @param params - Arguments as Pi passes them.\n * @param signal - The call's abort signal, which also dismisses the dialog.\n * @param ctx - Pi context of the call.\n * @returns {Promise<void>} Once the call may run.\n * @throws {ToolInputError} When the arguments fail the schema, before anyone is asked.\n * @throws {Error} Without a UI, on a \"no\", or with the reason of an abort.\n */\nasync function approve(\n tool: ToolDefinition,\n ask: PiConfirm,\n params: unknown,\n signal: AbortSignal | undefined,\n ctx: ExtensionContext,\n): Promise<void> {\n const checked = validateInput(tool, params);\n if (!checked.ok) throw new ToolInputError(checked.lines);\n const question = await ask(checked.value);\n if (question === undefined) return;\n if (!ctx.hasUI) throw new Error(`${tool.name} needs interactive approval in Pi TUI or RPC mode`);\n const approved = await ctx.ui.confirm(\n sanitizeLine(question.title),\n sanitizeText(question.message),\n signal ? { signal } : {},\n );\n signal?.throwIfAborted();\n if (!approved) {\n throw new Error(\n `${tool.name} was cancelled by the user. Do not retry unless the user asks again.`,\n );\n }\n}\n\n/**\n * The renderers Pi gets for one tool, with `describeCall` turned into a `renderCall`.\n *\n * @param tool - Tool being registered.\n * @param renderers - Its renderers, if any.\n * @param Text - Host `Text` component.\n * @returns {Pick<PiToolDefinition, \"renderCall\" | \"renderResult\">} What goes to `pi.registerTool`.\n * @throws {ToolDefinitionError} When `describeCall` would draw but `Text` is missing.\n */\nfunction hostRenderers(\n tool: ToolDefinition,\n renderers: PiRenderers | undefined,\n Text: PiTextComponent | undefined,\n): Pick<PiToolDefinition, \"renderCall\" | \"renderResult\"> {\n if (!renderers) return {};\n const { describeCall, ...own } = renderers;\n if (own.renderCall || !describeCall) return own;\n if (!Text) throw new ToolDefinitionError(`${tool.name}: describeCall needs the host Text option`);\n const title = sanitizeLine(tool.title);\n return {\n ...own,\n renderCall(args, theme): Component {\n const summary = sanitizeLine(describeCall(args as Readonly<Record<string, unknown>>));\n const header = theme.fg(\"toolTitle\", theme.bold(title));\n return new Text(summary ? `${header} ${theme.fg(\"muted\", summary)}` : header, 0, 0);\n },\n };\n}\n"],"mappings":";;;;;;;;;;EA+EA,GAAA,aAAgB;GAKd,GAAA,cAAe,MAAA,WAAgB,QAAA,IAAA;GAC/B,MAAM,KAAA;GACN,OAAM,KAAQ;GACd,aAAc,KAAA;GAMd,GAAK,KAAA,YAAc,KAAO,IAAA,CAAA,IAAA,EAAA,eAAA,KAAA,QAAA;GACxB,GAAA,KAAM,eAAY,KAAO,IAAQ,CAAA,IAAA,EAAA,kBAAoB,CAAA,GAAA,KAAA,UAAA,EAAA;GACrD,YAAY,KAAA;GACZ,MAAG,QAAA,aAAa,QAAA,QAAA,UAAA,KAAA;IACd,IAAG,KAAA,MAAA,QAAoB,MAAA,KAAW,QAAQ,QAAI,GAAA;IAC9C,MAAM,SAAK,MAAA,WAAA,MAAA,QAAA,YAAA,QAAA,QAAA,CAAA;IACX,IAAA,OAAY,WAAA,aAAA,SAAA,MAAA,IAAA,MAAA,WAAA,MAAA,CAAA;IACZ,OAAA;GACA;EACA,CAAA;CACA;AACA;AAEE,SAAA,OAAM,SAAe,MAAA;CACrB,OAAI,WAAO,OAAW,OAAA,SAAa,IAAA,IAAS,QAAU,QAAM,KAAA;AAC5D;AAEJ,eAAC,QAAA,MAAA,KAAA,QAAA,QAAA,KAAA;CACH,MAAA,UAAA,cAAA,MAAA,MAAA;CACF,IAAA,CAAA,QAAA,IAAA,MAAA,IAAA,eAAA,QAAA,KAAA;;;;;;;;AAUE,SAAO,cAAW,MAAO,WAAO,MAAa;CAC/C,IAAA,CAAA,WAAA,OAAA,CAAA;;;;;;;;;;;;;AAcA;AAQE,SAAK"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agntn/tools",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "One tool definition for MCP, Pi, OMP and the AI SDK",
|
|
5
5
|
"homepage": "https://github.com/agntn/tools#readme",
|
|
6
6
|
"bugs": "https://github.com/agntn/tools/issues",
|
|
@@ -24,6 +24,10 @@
|
|
|
24
24
|
"types": "./dist/mcp.d.mts",
|
|
25
25
|
"import": "./dist/mcp.mjs"
|
|
26
26
|
},
|
|
27
|
+
"./h3": {
|
|
28
|
+
"types": "./dist/h3.d.mts",
|
|
29
|
+
"import": "./dist/h3.mjs"
|
|
30
|
+
},
|
|
27
31
|
"./pi": {
|
|
28
32
|
"types": "./dist/pi.d.mts",
|
|
29
33
|
"import": "./dist/pi.mjs"
|
|
@@ -53,6 +57,8 @@
|
|
|
53
57
|
"@types/node": "26.2.0",
|
|
54
58
|
"ai": "7.0.127",
|
|
55
59
|
"changelogen": "0.6.2",
|
|
60
|
+
"h3": "2.0.1",
|
|
61
|
+
"h3-mcp": "0.2.0",
|
|
56
62
|
"obuild": "0.4.43",
|
|
57
63
|
"typebox": "1.3.34",
|
|
58
64
|
"typescript": "7.0.2",
|
|
@@ -63,7 +69,8 @@
|
|
|
63
69
|
"@earendil-works/pi-coding-agent": ">=0.84.2 <2",
|
|
64
70
|
"@modelcontextprotocol/server": ">=2.2.0 <3",
|
|
65
71
|
"@oh-my-pi/pi-coding-agent": ">=18.0.0 <19",
|
|
66
|
-
"ai": ">=7.0.0 <8"
|
|
72
|
+
"ai": ">=7.0.0 <8",
|
|
73
|
+
"h3-mcp": ">=0.2.0 <0.3"
|
|
67
74
|
},
|
|
68
75
|
"peerDependenciesMeta": {
|
|
69
76
|
"@earendil-works/pi-coding-agent": {
|
|
@@ -77,10 +84,13 @@
|
|
|
77
84
|
},
|
|
78
85
|
"ai": {
|
|
79
86
|
"optional": true
|
|
87
|
+
},
|
|
88
|
+
"h3-mcp": {
|
|
89
|
+
"optional": true
|
|
80
90
|
}
|
|
81
91
|
},
|
|
82
92
|
"engines": {
|
|
83
|
-
"node": ">=
|
|
93
|
+
"node": ">=26"
|
|
84
94
|
},
|
|
85
95
|
"scripts": {
|
|
86
96
|
"build": "obuild",
|