@agntn/tools 0.2.1 → 0.2.2

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 CHANGED
@@ -22,7 +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
+ - ⏳ **Progress that gets somewhere.** `progress?.("still at it")` turns into `onUpdate` in Pi and OMP, `notifications/progress` in MCP and one live line in your terminal. A slow call stops looking like a dead one.
26
26
  - ⌨️ **A CLI on the side.** `runCli` turns the same tools into commands, no CLI library needed. Flags come from the schema. Hints add positionals, short flags and stdin.
27
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.
28
28
 
@@ -45,7 +45,7 @@ export interface ToolCliHints {
45
45
  readonly description?: string;
46
46
  /** Properties taken in this order as positional arguments instead of flags. */
47
47
  readonly positional?: readonly string[];
48
- /** A string property that takes every word left after `positional`, joined by single spaces. */
48
+ /** Words left after `positional`: joined by spaces into a string, one per item into an array. */
49
49
  readonly rest?: string;
50
50
  /** Short flags by property, `{ limit: "n" }` for `-n 5`. Only a whole word counts. */
51
51
  readonly short?: Readonly<Record<string, string>>;
@@ -75,7 +75,7 @@ export interface ToolCallContext {
75
75
  signal?: AbortSignal;
76
76
  /** Says the call is still at it. Absent where the host can't show it, so call `progress?.()`. */
77
77
  progress?: (message: string, amount?: ToolProgress) => void;
78
- /** The host's own `ctx`: Pi and OMP pass it, other surfaces don't. Narrow it yourself. */
78
+ /** Pi's or OMP's own `ctx`, the CLI's `CliHost`, nothing elsewhere. Narrow it yourself. */
79
79
  host?: unknown;
80
80
  }
81
81
  export interface ToolDefinition<Input extends TObject = TObject, Details = unknown> {
@@ -0,0 +1,53 @@
1
+ import { Icon, ToolCallContext, ToolDefinition } from "./index.mjs";
2
+ import { CallToolResult, Tool, ToolAnnotations } from "@modelcontextprotocol/server";
3
+ export interface McpServerInfo {
4
+ /** Server name, also used in the unknown-tool message. */
5
+ readonly name: string;
6
+ readonly version: string;
7
+ /** Display name for clients that show one, such as `Forges`. */
8
+ readonly title?: string;
9
+ /** One line under the name on a connector card or in a registry. */
10
+ readonly description?: string;
11
+ readonly icons?: readonly Icon[];
12
+ /** Project home a client can link to. */
13
+ readonly websiteUrl?: string;
14
+ }
15
+ /**
16
+ * Maps a tool's title and declared effect to MCP annotations. Claude Code reads its label here.
17
+ *
18
+ * @param tool - Tool to describe.
19
+ * @returns {ToolAnnotations} Title and hints for the MCP client.
20
+ */
21
+ export declare function toolAnnotations(tool: ToolDefinition): ToolAnnotations;
22
+ /**
23
+ * Error result with every line-forging character replaced.
24
+ *
25
+ * The messages echo client-controlled values (a tool name, an argument) and
26
+ * downstream error text, so they pass through here on every branch. Each line
27
+ * is cleaned on its own, so only the breaks between the lines passed in
28
+ * survive; a newline inside one line becomes a space.
29
+ *
30
+ * @param lines - Error lines.
31
+ * @returns {CallToolResult} MCP error result.
32
+ */
33
+ export declare function errorResult(...lines: readonly string[]): CallToolResult;
34
+ /**
35
+ * The entries `tools/list` answers with, in the order given.
36
+ *
37
+ * @param tools - Tools to list.
38
+ * @returns {Tool[]} Name, title, description, icons, schema and annotations of each tool.
39
+ * @throws {ToolDefinitionError} When two tools share a name.
40
+ */
41
+ export declare function listTools(tools: readonly ToolDefinition[]): Tool[];
42
+ /**
43
+ * Answers one call as `tools/call` does and never throws, so every transport gives the same text.
44
+ *
45
+ * @param info - Server info; `name` is the word in the message for an unknown tool.
46
+ * @param tools - Tools to look the name up in.
47
+ * @param name - Tool name as the client sent it.
48
+ * @param args - Arguments as the client sent them; missing ones count as `{}`.
49
+ * @param context - Context for this call, such as the request's abort signal.
50
+ * @returns {Promise<CallToolResult>} The tool's text, or the sanitized error.
51
+ */
52
+ export declare function callTool(info: Pick<McpServerInfo, "name">, tools: readonly ToolDefinition[], name: string, args?: unknown, context?: ToolCallContext): Promise<CallToolResult>;
53
+ //# sourceMappingURL=mcp-answers.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mcp-answers.d.mts","names":[],"sources":["../../src/mcp-answers.ts"],"mappings":";;iBAoBiB;;WAEN;WACA;;WAEA;;WAEA;WACA,iBAAiB;;WAEjB;;;;;;;;wBASK,gBAAgB,MAAM,iBAAiB;;;;;;;;;;;;wBAqBvC,eAAe,2BAA2B;;;;;;;;wBAW1C,UAAU,gBAAgB,mBAAmB;;;;;;;;;;;wBAkCvC,SACpB,MAAM,KAAK,wBACX,gBAAgB,kBAChB,cACA,gBACA,UAAS,kBACR,QAAQ"}
@@ -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/** 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\nexport { sanitizeText } 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 /** A string property that takes every word left after `positional`, joined by single spaces. */\n readonly rest?: string;\n /** Short flags by property, `{ limit: \"n\" }` for `-n 5`. Only a whole word counts. */\n readonly short?: Readonly<Record<string, string>>;\n /** String properties that read stdin when given as `-`. */\n readonly stdin?: readonly string[];\n /** `false` takes `--json` away, for a command that writes its own bytes to stdout. */\n readonly json?: boolean;\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/** An MCP icon, the SDK's own shape: a URL or `data:` URI a client can draw on its card. */\nexport interface Icon {\n readonly src: string;\n readonly mimeType?: string;\n /** `WxH` sizes such as `48x48`, or `any` for an SVG. */\n readonly sizes?: readonly string[];\n /** Background the icon is drawn for. */\n readonly theme?: \"light\" | \"dark\";\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 /** The host's own `ctx`: Pi and OMP pass it, other surfaces don't. Narrow it yourself. */\n host?: unknown;\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 /** MCP `icons` in `tools/list`. Pi, OMP, the AI SDK and the CLI don't draw them. */\n readonly icons?: readonly Icon[];\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;;;AC8EA;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,WAAA,MAAA;;;;;AAQlB,SAAgB,eACd,MACgC,MAAA;CAChC,MAAK,SAAU,SAAK,cACZ,OAAI,QAAA,OAAA,KAAoB,QAAA,IAAa,KAAK,WAAU,CAAA,CAAK,CAAA,CAAA,S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E;;;;;;;;;AAYF;AAEE,SAAK,eAAc,IAAO,KAAA,SAAA;CACxB,MAAI,QAAO,CAAA,GAAI,IAAK,IAAI,QAAS,QAAI,WAAA,OAAoB,SAAA,QAAA,CAAA,CAAA,KAAuB,WAAW,CAAA,GAAA,OAAA,KAAA,OAAA,OAAA,UAAA,IAAA,OAAA,aAAA,CAAA,CAAA,GAAA,GAAA,WAAA,MAAA,CAAA,CAAA,KAAA,YAAA,iBAAA,KAAA,UAAA,OAAA,GAAA,CAAA,CAAA,CAAA,KAAA,IAAA,CAAA,CAAA,CAAA;CAC3F,MAAA,QAAW,MAAK,SAAU,IAAA,MAAA,KAAA,SAAA,IAAA,KAAA,EAAA,CAAA,CAAA,KAAA,MAAA,IAAA,MAAA;CAC5B,MAAA,QAAA,OAAA,KAAA,KAAA,OAAA;CACA,MAAA,OAAO,SAAA;CACT,OAAA,oBAAA,MAAA,qBAAA,KAAA,UAAA,GAAA,EAAA,UAAA;;;;;;;;;;;;;CAoBA,MAAA,EAAgB,aAAA;CAId,IAAIA,CAAAA,UAAiB,OAAO,MAAI,KAAG,QAAO,QAAA,OAAA,OAAA;CAAE,IAAA,UAAI;CAAM,IAAA;EAAY,OAAA,MAAA,KAAA,QAAA,QAAA,OAAA;GAElE,GAAA;GAKA,SAAM,SAHJ,QAAS;IAIX,IAAM,SAAmB;IACzB,IAAK;KACH,SAAU,aAAY,OAAA,GAAA,MAAA;IACtB,QAAM,CAAA;GACN;EAEK,CAAA;CACP,UAAA;EACA,UAAM;CACN;AAAS;AAAW,MAAA,gBAAa;AACnC,SAAA,aAAA,OAAA;;;;;;AASE,SAAM,qBAAuB,gBAAW,YAAgB,YAAA,YAAA,YAAA,cAAA,cAAA,eAAA"}
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\nexport { sanitizeText } 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 /** Words left after `positional`: joined by spaces into a string, one per item into an array. */\n readonly rest?: string;\n /** Short flags by property, `{ limit: \"n\" }` for `-n 5`. Only a whole word counts. */\n readonly short?: Readonly<Record<string, string>>;\n /** String properties that read stdin when given as `-`. */\n readonly stdin?: readonly string[];\n /** `false` takes `--json` away, for a command that writes its own bytes to stdout. */\n readonly json?: boolean;\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/** An MCP icon, the SDK's own shape: a URL or `data:` URI a client can draw on its card. */\nexport interface Icon {\n readonly src: string;\n readonly mimeType?: string;\n /** `WxH` sizes such as `48x48`, or `any` for an SVG. */\n readonly sizes?: readonly string[];\n /** Background the icon is drawn for. */\n readonly theme?: \"light\" | \"dark\";\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 /** Pi's or OMP's own `ctx`, the CLI's `CliHost`, nothing elsewhere. Narrow it yourself. */\n host?: unknown;\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 /** MCP `icons` in `tools/list`. Pi, OMP, the AI SDK and the CLI don't draw them. */\n readonly icons?: readonly Icon[];\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;;;AC8EA;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,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S;IAIX,IAAM,SAAmB;IACzB,IAAK;KACH,SAAU,aAAY,OAAA,GAAA,MAAA;IACtB,QAAM,CAAA;GACN;EAEK,CAAA;CACP,UAAA;EACA,UAAM;CACN;AAAS;AAAW,MAAA,gBAAa;AACnC,SAAA,aAAA,OAAA;;;;;;AASE,SAAM,qBAAuB,gBAAW,YAAgB,YAAA,YAAA,YAAA,cAAA,cAAA,eAAA"}
package/dist/cli.d.mts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { ToolDefinition } from "./_chunks/index.mjs";
2
+ import { McpServerInfo } from "./_chunks/mcp-answers.mjs";
2
3
  export interface CliOptions {
3
4
  /** Executable name, also the MCP server name. */
4
5
  readonly name: string;
@@ -11,20 +12,28 @@ export interface CliOptions {
11
12
  * a generated command, `mcp` included, takes its place. Bytes are the
12
13
  * command's own business: it reads `-` from stdin itself in `execute`, and
13
14
  * writes to stdout itself, answering with no content and `cli.json: false`.
15
+ * A command that prints rows as they land reads `--json` off its {@link CliHost},
16
+ * and leaves `progress` alone: on a terminal its line would sit in front of the rows.
14
17
  */
15
18
  readonly commands?: readonly ToolDefinition[];
16
19
  /** Command for an empty command line. */
17
20
  readonly default?: string;
18
21
  /** Command for a first word that names no command: `hashes sha256 x` runs `hashes hash sha256 x`. */
19
22
  readonly fallback?: string;
20
- /** Adds `mcp`, the tools as an MCP server over stdio. */
21
- readonly mcp?: boolean;
23
+ /** Adds `mcp` over stdio, named by the CLI on `true` or by the server info it's handed. */
24
+ readonly mcp?: boolean | McpServerInfo;
22
25
  /**
23
26
  * Errors the package throws on purpose. They print as one line with exit
24
27
  * code 1; any other error keeps its stack trace.
25
28
  */
26
29
  readonly expected?: (error: unknown) => boolean;
27
30
  }
31
+ /** What a CLI command finds in `host`: narrow to it and look at `json` before writing a byte. */
32
+ export interface CliHost {
33
+ readonly cli: true;
34
+ /** `--json` was given, so the details are the answer and stdout stays theirs. */
35
+ readonly json: boolean;
36
+ }
28
37
  /**
29
38
  * @param tool - Tool to name.
30
39
  * @returns {string} The hinted command, or the tool name without its package prefix, in kebab case.
@@ -56,8 +65,8 @@ export declare function createCli(options: CliOptions): Cli;
56
65
  */
57
66
  export declare function normalizeArgv(options: CliOptions, argv: readonly string[]): string[];
58
67
  /**
59
- * Runs the CLI on `process.argv`. The CLI writes no colors, so nothing
60
- * depends on the terminal it writes to.
68
+ * Runs the CLI on `process.argv`. The CLI writes no colors; a terminal on
69
+ * stderr only gets the progress line, which never reaches a pipe.
61
70
  *
62
71
  * @param options - CLI options.
63
72
  * @param argv - Words after the executable and script.
@@ -1 +1 @@
1
- {"version":3,"file":"cli.d.mts","names":[],"sources":["../src/cli.ts"],"mappings":";iBA0BiB;;WAEN;WACA;WACA;WACA,gBAAgB;;;;;;;;WAQhB,oBAAoB;;WAEpB;;WAEA;;WAEA;;;;;WAKA,YAAY;;;;;;wBAuDP,YAAY,MAAM;;iBAo7BjB;;EAEf,IAAI,0BAA0B;;;;;;;;;;wBAWhB,UAAU,SAAS,aAAa;;;;;;;;;;;wBA6BhC,cAAc,SAAS,YAAY;;;;;;;;wBAgK7B,OACpB,SAAS,YACT,2BACC"}
1
+ {"version":3,"file":"cli.d.mts","names":[],"sources":["../src/cli.ts"],"mappings":";;iBA6BiB;;WAEN;WACA;WACA;WACA,gBAAgB;;;;;;;;;;WAUhB,oBAAoB;;WAEpB;;WAEA;;WAEA,gBAAgB;;;;;WAKhB,YAAY;;;iBAIN;WACN;;WAEA;;;;;;wBAyDK,YAAY,MAAM;;iBAukCjB;;EAEf,IAAI,0BAA0B;;;;;;;;;;wBAWhB,UAAU,SAAS,aAAa;;;;;;;;;;;wBA6BhC,cAAc,SAAS,YAAY;;;;;;;;wBAgK7B,OACpB,SAAS,YACT,2BACC"}
package/dist/cli.mjs CHANGED
@@ -36,6 +36,16 @@ function fieldKind(schema) {
36
36
  if ((Array.isArray(schema.anyOf) ? schema.anyOf : []).some((branch) => fieldKind(branch) === "json")) return "json";
37
37
  return TYPE_KINDS.get(schema.type) ?? "string";
38
38
  }
39
+ function textItems(schema) {
40
+ const { items } = schema;
41
+ if (schema.type !== "array" || typeof items !== "object" || items === null) return void 0;
42
+ if (Array.isArray(items)) return void 0;
43
+ return unionBranches(items).every(takesText) ? items : void 0;
44
+ }
45
+ function takesText(branch) {
46
+ if (branch.type === "string" || typeof branch.const === "string") return true;
47
+ return Array.isArray(branch.enum) && branch.enum.every((value) => typeof value === "string");
48
+ }
39
49
  function cliHints(tool) {
40
50
  const cli = tool.cli ?? {};
41
51
  const rest = cli.rest === void 0 ? [] : [cli.rest];
@@ -71,6 +81,7 @@ function toolFields(tool) {
71
81
  kind: fieldKind(properties[key] ?? {}),
72
82
  positional: positional.includes(key),
73
83
  rest: rest.includes(key),
84
+ restItems: rest.includes(key) ? textItems(properties[key] ?? {}) : void 0,
74
85
  short: Object.hasOwn(short, key) ? short[key] : void 0,
75
86
  stdin: stdin.includes(key)
76
87
  };
@@ -92,8 +103,11 @@ function assertField(tool, field, taken) {
92
103
  if (!field.positional) assertFlag(tool, field);
93
104
  if (taken) throw new ToolDefinitionError(`${tool.name}: two properties take the flag --${field.flag}`);
94
105
  if (field.positional && field.kind === "boolean") throw new ToolDefinitionError(`${tool.name}: boolean property ${field.key} cannot be positional`);
106
+ assertTextHints(tool, field);
107
+ }
108
+ function assertTextHints(tool, field) {
95
109
  if (field.stdin && field.kind !== "string") throw new ToolDefinitionError(`${tool.name}: stdin property ${field.key} must be a string`);
96
- if (field.rest && !TEXT_KINDS.has(field.kind)) throw new ToolDefinitionError(`${tool.name}: rest property ${field.key} must be a string`);
110
+ if (field.rest && field.restItems === void 0 && !TEXT_KINDS.has(field.kind)) throw new ToolDefinitionError(`${tool.name}: rest property ${field.key} must be a string or an array of strings`);
97
111
  }
98
112
  function assertShort(tool, field) {
99
113
  if (field.short === void 0) return;
@@ -238,6 +252,7 @@ function positionalValues(fields, positionals) {
238
252
  const takes = fields.filter((field) => field.positional);
239
253
  return Object.assign(emptyRecord(), Object.fromEntries(takes.flatMap((field, index) => {
240
254
  const words = field.rest ? positionals.slice(index) : positionals.slice(index, index + 1);
255
+ if (field.restItems !== void 0) return words.length > 0 || field.required ? [[field.key, words]] : [];
241
256
  return words.length === 0 ? [] : [[field.key, words.join(" ")]];
242
257
  })));
243
258
  }
@@ -360,7 +375,7 @@ function toolInput(fields, values) {
360
375
  for (const field of fields) {
361
376
  const raw = values[field.key];
362
377
  if (raw === void 0) continue;
363
- const read = fieldValue(field, raw);
378
+ const read = typeof raw === "object" ? { value: raw.map((word) => wordValue(field.restItems ?? {}, word)) } : fieldValue(field, raw);
364
379
  if ("error" in read) errors.push(`Invalid arguments at /${field.key}: ${read.error}`);
365
380
  else input[field.key] = read.value;
366
381
  }
@@ -383,6 +398,59 @@ function detailsJson(details) {
383
398
  return (JSON.stringify(details, (_key, value) => typeof value === "bigint" ? value.toString() : value, 2) ?? "null").replaceAll(JSON_FORGING, (character) => `\\u${(character.codePointAt(0) ?? 0).toString(16).padStart(4, "0")}`);
384
399
  }
385
400
  const JSON_FORGING = /[\u007F-\u009F\u061C\u200E\u200F\u2028\u2029\u202A-\u202E\u2066-\u206F]/g;
401
+ const GRAPHEMES = new Intl.Segmenter();
402
+ const WIDE = /^(?:\p{Extended_Pictographic}|[\u1100-\u115F\u231A\u231B\u2329\u232A\u2630-\u2637\u268A-\u268F\u2E80-\u303E\u3041-\u33FF\u3400-\u4DFF\u4E00-\u9FFF\uA000-\uA4CF\uA960-\uA97F\uAC00-\uD7A3\uF900-\uFAFF\uFE10-\uFE19\uFE30-\uFE6F\uFF00-\uFF60\uFFE0-\uFFE6\u{16FE0}-\u{18DFF}\u{1AFF0}-\u{1B2FF}\u{1D15E}-\u{1D164}\u{1D1BB}-\u{1D1C0}\u{1D300}-\u{1D376}\u{1F000}-\u{1FAFF}\u{20000}-\u{3FFFD}])$/u;
403
+ const EMOJI = /^\p{RGI_Emoji}$/v;
404
+ const ZERO_WIDTH = /^[\p{Mn}\p{Me}]$/u;
405
+ function pointCells(point) {
406
+ if (WIDE.test(point)) return 2;
407
+ return ZERO_WIDTH.test(point) ? 0 : 1;
408
+ }
409
+ function graphemeCells(grapheme) {
410
+ let size = 0;
411
+ for (const point of grapheme.normalize("NFC")) size += pointCells(point);
412
+ return Math.max(EMOJI.test(grapheme) ? 2 : 1, size);
413
+ }
414
+ function fitLine(text, room) {
415
+ let fitted = "";
416
+ let used = 0;
417
+ for (const { segment } of GRAPHEMES.segment(text)) {
418
+ const size = graphemeCells(segment);
419
+ if (used + size > room) break;
420
+ fitted += segment;
421
+ used += size;
422
+ }
423
+ return {
424
+ text: fitted,
425
+ cells: used
426
+ };
427
+ }
428
+ function progressText(message, amount) {
429
+ const { progress, total } = amount ?? { progress: NaN };
430
+ if (!Number.isFinite(progress) || !Number.isFinite(total)) return message;
431
+ return `${message} (${progress}/${total})`.trim();
432
+ }
433
+ function progressLine() {
434
+ const stream = process.stderr;
435
+ if (stream.isTTY !== true) return {
436
+ context: {},
437
+ wipe() {}
438
+ };
439
+ let width = 0;
440
+ const wipe = () => {
441
+ if (width > 0) stream.write(`\r${" ".repeat(width)}\r`);
442
+ width = 0;
443
+ };
444
+ return {
445
+ context: { progress(message, amount) {
446
+ const line = fitLine(progressText(message, amount), Math.max(1, (stream.columns || 80) - 1));
447
+ wipe();
448
+ stream.write(line.text);
449
+ width = line.cells;
450
+ } },
451
+ wipe
452
+ };
453
+ }
386
454
  function toolCommand(tool) {
387
455
  const fields = toolFields(tool);
388
456
  const [summary = tool.title] = tool.description.split(/(?<=[.!?])\s/, 1);
@@ -393,7 +461,20 @@ function toolCommand(tool) {
393
461
  fields,
394
462
  json: tool.cli?.json !== false,
395
463
  async run(words) {
396
- const result = await invokeTool(tool, toolInput(fields, words.values));
464
+ const host = {
465
+ cli: true,
466
+ json: words.json
467
+ };
468
+ const line = progressLine();
469
+ let result;
470
+ try {
471
+ result = await invokeTool(tool, toolInput(fields, words.values), {
472
+ ...line.context,
473
+ host
474
+ });
475
+ } finally {
476
+ line.wipe();
477
+ }
397
478
  if (result.isError === true) {
398
479
  writeLine("stderr", sanitizeText(resultText(result)));
399
480
  process.exitCode = 1;
@@ -415,7 +496,7 @@ function mcpCommand(options) {
415
496
  json: false,
416
497
  async run() {
417
498
  const [{ createMcpServer }, { StdioServerTransport }] = await Promise.all([import("./mcp.mjs"), import("@modelcontextprotocol/server/stdio")]);
418
- await createMcpServer(options, options.tools).connect(new StdioServerTransport());
499
+ await createMcpServer(typeof options.mcp === "object" ? options.mcp : options, options.tools).connect(new StdioServerTransport());
419
500
  }
420
501
  };
421
502
  }
@@ -426,7 +507,7 @@ function commandTools(options) {
426
507
  return [...listed, ...own.filter((command) => !listed.includes(command))];
427
508
  }
428
509
  function builtInMcp(options) {
429
- return options.mcp === true && !(options.commands ?? []).some((command) => commandName(command) === "mcp");
510
+ return options.mcp !== void 0 && options.mcp !== false && !(options.commands ?? []).some((command) => commandName(command) === "mcp");
430
511
  }
431
512
  function commandWords(options) {
432
513
  return [...commandTools(options).flatMap((tool) => [commandName(tool), ...tool.cli?.aliases ?? []]), ...builtInMcp(options) ? ["mcp"] : []];
package/dist/cli.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.mjs","names":["Value.Check"],"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 positionals,\n * short flags 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. Bytes are the\n * command's own business: it reads `-` from stdin itself in `execute`, and\n * writes to stdout itself, answering with no content and `cli.json: false`.\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\n/** Kinds whose value is the text itself: `enum` is string values only. */\nconst TEXT_KINDS = new Set<FieldKind>([\"string\", \"enum\"]);\n\n/** A short flag: one letter, so a negative number never reads as one. */\nconst SHORT_FLAG = /^[a-z]$/i;\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 /** Takes the words the other positionals leave, so it's always the last one. */\n readonly rest: boolean;\n readonly short: string | undefined;\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\ninterface CliHints {\n /** The `positional` hint with `rest` at the end. */\n readonly positional: readonly string[];\n readonly rest: readonly string[];\n readonly short: Readonly<Record<string, string>>;\n readonly stdin: readonly string[];\n}\n\n/**\n * @param tool - Tool to read.\n * @returns {CliHints} Its hints, every key a property of the tool.\n * @throws {ToolDefinitionError} When a hint names a property the tool lacks, or a positional twice.\n */\nfunction cliHints(tool: ToolDefinition): CliHints {\n const cli = tool.cli ?? {};\n const rest = cli.rest === undefined ? [] : [cli.rest];\n const hints = {\n positional: [...(cli.positional ?? []), ...rest],\n rest,\n short: cli.short ?? {},\n stdin: cli.stdin ?? [],\n };\n const properties = tool.input.properties as Readonly<Record<string, unknown>>;\n for (const key of [...hints.positional, ...Object.keys(hints.short), ...hints.stdin]) {\n if (!Object.hasOwn(properties, key)) {\n throw new ToolDefinitionError(`${tool.name}: cli hint names unknown property ${key}`);\n }\n }\n const { positional } = hints;\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 return hints;\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, rest, short, stdin } = cliHints(tool);\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 rest: rest.includes(key),\n short: Object.hasOwn(short, key) ? short[key] : undefined,\n stdin: stdin.includes(key),\n };\n assertField(tool, field, !field.positional && flags.has(field.flag));\n assertShort(tool, field);\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 if (field.rest && !TEXT_KINDS.has(field.kind)) {\n throw new ToolDefinitionError(`${tool.name}: rest property ${field.key} must be a string`);\n }\n}\n\n/**\n * @param tool - Tool the field belongs to.\n * @param field - Field to check.\n * @throws {ToolDefinitionError} When the short flag is no letter, is `h` or sits on a positional.\n */\nfunction assertShort(tool: ToolDefinition, field: Field): void {\n if (field.short === undefined) return;\n if (field.positional) {\n throw new ToolDefinitionError(\n `${tool.name}: positional property ${field.key} takes no short flag`,\n );\n }\n if (!SHORT_FLAG.test(field.short)) {\n throw new ToolDefinitionError(\n `${tool.name}: short flag ${JSON.stringify(field.short)} of ${field.key} must match ${SHORT_FLAG}`,\n );\n }\n if (field.short === \"h\") {\n throw new ToolDefinitionError(\n `${tool.name}: property ${field.key} takes -h, which asks for help`,\n );\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`, and two short flags can land on one letter.\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 const short = field.short === undefined ? [] : [`-${field.short}`];\n for (const spelling of [`--${field.flag}`, ...negation, ...short]) {\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 * @param field - Option field.\n * @returns {string} Its long spelling in the usage text.\n */\nfunction optionSpelling(field: Field): string {\n return field.kind === \"boolean\"\n ? `--[no-]${field.flag}`\n : `--${field.flag}=<${valueHint(field)}>`;\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`, for a boolean `--no-flag`, and a short flag as\n * a whole word are options. A dashed word that spells none fills a free\n * positional ({@link takeDashedText}); past that, an unknown option, a missing\n * value, a value given twice or a positional too many is a failure, never a\n * 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 { args, origins, texts, refused } = takeDashedText(rawArgs, fields, options);\n const { tokens } = parseArgs({\n args,\n options: Object.fromEntries(\n Object.entries(options).map(([flag, field]) => [\n flag,\n field === \"json\"\n ? { type: \"boolean\" }\n : {\n type: field.kind === \"boolean\" ? \"boolean\" : \"string\",\n ...(field.short === undefined ? {} : { short: field.short }),\n },\n ]),\n ) as Record<string, { type: \"boolean\" | \"string\"; short?: string }>,\n strict: false,\n allowPositionals: true,\n allowNegative: true,\n tokens: true,\n });\n\n const values = emptyRecord<string | boolean>();\n const errors = refused.map((word) => unknownOption(options, word));\n const flags = new Set<string>();\n for (const token of tokens) {\n if (token.kind !== \"option\") continue;\n const read = readOption(options, token, args[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 const positionals = inLineOrder(tokens, origins, texts);\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/** The line for `util.parseArgs` without the dashed text, and where each word stood. */\ninterface DashedText {\n readonly args: string[];\n /** Index on the original line of each word in `args`. */\n readonly origins: readonly number[];\n /** Dashed words read as positionals, with their index on the original line. */\n readonly texts: ReadonlyArray<readonly [number, string]>;\n /** Dashed words no positional is left for, which fail as unknown options. */\n readonly refused: readonly string[];\n}\n\n/**\n * Morse, PGP armor and `-5` take a positional the plain words leave free, or fail as unknown\n * options. Neither reaches `util.parseArgs`, which reads the inner `-` of `-.-.` as `--`.\n *\n * @param rawArgs - Words after the command name.\n * @param fields - The command's fields.\n * @param options - Option fields by flag, and `--json` when the command takes it.\n * @returns {DashedText} The words left for `util.parseArgs` and the dashed text.\n */\nfunction takeDashedText(\n rawArgs: readonly string[],\n fields: readonly Field[],\n options: Readonly<Record<string, Field | \"json\">>,\n): DashedText {\n const { dashed, plain } = scanWords(rawArgs, options);\n const free = fields.filter((field) => field.positional).length - plain;\n const taken = dashed.slice(0, Math.max(free, 0));\n const skipped = new Set(dashed);\n const origins = rawArgs.flatMap((_, index) => (skipped.has(index) ? [] : [index]));\n const word = (index: number): string => rawArgs[index] ?? \"\";\n return {\n args: origins.map(word),\n origins,\n texts: taken.map((index) => [index, word(index)] as const),\n refused: dashed.slice(taken.length).map(word),\n };\n}\n\n/**\n * @param rawArgs - Words after the command name.\n * @param options - Option fields by flag, and `--json` when the command takes it.\n * @returns {{ dashed: number[]; plain: number }} Dashed words that spell no option, plain words.\n */\nfunction scanWords(\n rawArgs: readonly string[],\n options: Readonly<Record<string, Field | \"json\">>,\n): { dashed: number[]; plain: number } {\n const dashed: number[] = [];\n let plain = 0;\n for (let index = 0; index < rawArgs.length; index++) {\n const word = rawArgs[index] ?? \"\";\n if (word === \"--\") return { dashed, plain: plain + rawArgs.length - index - 1 };\n const kind = wordKind(word, options);\n if (kind === \"plain\") plain++;\n else if (kind === \"text\") dashed.push(index);\n else if (kind === \"valued\") index++;\n }\n return { dashed, plain };\n}\n\n/**\n * Reads a whole word the way {@link optionField} takes its tokens.\n *\n * @param word - One word before `--`.\n * @param options - Option fields by flag, and `--json` when the command takes it.\n * @returns {\"plain\" | \"option\" | \"valued\" | \"text\"} `valued` takes the next word as its value.\n */\nfunction wordKind(\n word: string,\n options: Readonly<Record<string, Field | \"json\">>,\n): \"plain\" | \"option\" | \"valued\" | \"text\" {\n if (!word.startsWith(\"-\") || word === \"-\") return \"plain\";\n if (word === \"-h\") return \"option\";\n const field = word.startsWith(\"--\")\n ? longField(word.slice(2), options)\n : shortField(word, options);\n if (field === undefined) return \"text\";\n if (field === \"option\" || field.kind === \"boolean\" || word.includes(\"=\")) return \"option\";\n return \"valued\";\n}\n\n/**\n * @param tokens - Tokens of the line without the dashed text.\n * @param origins - Index on the original line of each word `util.parseArgs` read.\n * @param texts - The dashed text with its index on the original line.\n * @returns {string[]} Every positional word, in the order the line gave them.\n */\nfunction inLineOrder(\n tokens: ReadonlyArray<Readonly<{ kind: string; index: number; value?: string | undefined }>>,\n origins: readonly number[],\n texts: ReadonlyArray<readonly [number, string]>,\n): string[] {\n const read = tokens.flatMap((token) =>\n token.kind === \"positional\" ? [[origins[token.index] ?? 0, token.value ?? \"\"] as const] : [],\n );\n return [...texts, ...read].toSorted(([a], [b]) => a - b).map(([, word]) => word);\n}\n\n/**\n * @param spelled - A long option without its `--`, maybe with `=value`.\n * @param options - Option fields by flag, and `--json` when the command takes it.\n * @returns {Field | \"option\" | undefined} The field, or `option` for help, json, `--no-`.\n */\nfunction longField(\n spelled: string,\n options: Readonly<Record<string, Field | \"json\">>,\n): Field | \"option\" | undefined {\n const [name = \"\"] = spelled.split(\"=\", 1);\n if (name === \"help\") return \"option\";\n const field = Object.hasOwn(options, name) ? options[name] : undefined;\n if (field !== undefined) return field === \"json\" ? \"option\" : field;\n return negatesBoolean(name, options) ? \"option\" : undefined;\n}\n\n/**\n * @param name - A long option name without its `--`.\n * @param options - Option fields by flag.\n * @returns {boolean} Whether the name is the `no-` form of a boolean flag.\n */\nfunction negatesBoolean(name: string, options: Readonly<Record<string, Field | \"json\">>): boolean {\n const flag = name.slice(3);\n const field = name.startsWith(\"no-\") && Object.hasOwn(options, flag) ? options[flag] : undefined;\n return field !== undefined && field !== \"json\" && field.kind === \"boolean\";\n}\n\n/**\n * @param word - A word with one leading dash.\n * @param options - Option fields by flag.\n * @returns {Field | undefined} The field whose short flag the whole word is.\n */\nfunction shortField(\n word: string,\n options: Readonly<Record<string, Field | \"json\">>,\n): Field | undefined {\n return Object.values(options).find(\n (field): field is Field =>\n field !== \"json\" && field.short !== undefined && `-${field.short}` === word,\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, `rest` with the others.\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 words = field.rest ? positionals.slice(index) : positionals.slice(index, index + 1);\n return words.length === 0 ? [] : [[field.key, words.join(\" \")]];\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 for words no positional takes.\n */\nfunction extraPositionals(fields: readonly Field[], positionals: readonly string[]): string[] {\n if (fields.some((field) => field.rest)) return [];\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 return field !== undefined && spells(field, token, word) ? field : undefined;\n}\n\n/**\n * `--flag`, `--no-flag` for a boolean, or the short flag as a whole word only,\n * since `util.parseArgs` would read a mistyped `-provider` as `-p rovider`.\n *\n * @param field - Field the token's name points to.\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 a spelling the field takes.\n */\nfunction spells(field: Field, token: OptionToken, word: string): boolean {\n if (token.rawName === `--${field.flag}`) return true;\n if (field.short !== undefined && token.rawName === `-${field.short}`)\n return word === token.rawName;\n return field.kind === \"boolean\" && token.rawName === `--no-${field.flag}`;\n}\n\n/**\n * @param options - Option fields by flag, and `--json` when the command takes it.\n * @param word - The command line word that names no option.\n * @returns {string} The failure, with every flag the command takes.\n */\nfunction unknownOption(options: Readonly<Record<string, Field | \"json\">>, word: string): string {\n const flags = Object.entries(options).map(([flag, each]) =>\n each === \"json\" || each.short === undefined ? `--${flag}` : `--${flag} (-${each.short})`,\n );\n const takes = flags.length > 0 ? flags.join(\", \") : \"no options\";\n return `Invalid arguments: unknown option ${JSON.stringify(word)}; takes ${takes}`;\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) return { error: unknownOption(options, word) };\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 !== `--no-${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/** An `integer` word: decimal digits, maybe signed. */\nconst DECIMAL_INTEGER = /^[+-]?\\d+$/;\n\n/** A `number` word: decimal, with an optional fraction and exponent. */\nconst DECIMAL_NUMBER = /^[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?$/i;\n\n/**\n * Reads a number word as written: `Number` alone takes `0x10`, and an empty word as zero.\n *\n * @param integer - Whether the schema wants an `integer` rather than any `number`.\n * @param word - The word.\n * @returns {{ value: number } | { error: string }} The number, or the core's type error.\n */\nfunction numberValue(integer: boolean, word: string): { value: number } | { error: string } {\n const value = Number(word);\n const written = (integer ? DECIMAL_INTEGER : DECIMAL_NUMBER).test(word);\n if (written && Number.isFinite(value)) return { value };\n return { error: integer ? \"must be integer\" : \"must be number\" };\n}\n\n/** Literal values a word can spell; an object or array never comes from one word. */\nconst LITERAL_TYPES = new Set([\"string\", \"number\", \"boolean\"]);\n\n/** Types whose every value is a literal a word spells. */\nconst TYPE_LITERALS = new Map<unknown, readonly unknown[]>([\n [\"null\", [null]],\n [\"boolean\", [true, false]],\n]);\n\n/**\n * @param values - Every value the branch allows, from `const`, `enum` or its type.\n * @param word - The word.\n * @returns {{ value: unknown } | undefined} The literal the word spells exactly, if any.\n */\nfunction literalValue(values: readonly unknown[], word: string): { value: unknown } | undefined {\n const spelled = (item: unknown) =>\n (item === null || LITERAL_TYPES.has(typeof item)) && String(item) === word;\n return values.some(spelled) ? { value: values.find(spelled) } : undefined;\n}\n\n/**\n * @param branch - One branch of a union.\n * @param word - The word.\n * @returns {{ value: unknown } | undefined} What the branch reads the word as, if it takes it at all.\n */\nfunction branchValue(branch: SchemaNode, word: string): { value: unknown } | undefined {\n if (Object.hasOwn(branch, \"const\")) return literalValue([branch.const], word);\n if (Array.isArray(branch.enum)) return literalValue(branch.enum, word);\n const literals = TYPE_LITERALS.get(branch.type);\n if (literals !== undefined) return literalValue(literals, word);\n if (TYPE_KINDS.get(branch.type) !== \"number\") return undefined;\n const read = numberValue(branch.type === \"integer\", word);\n return \"value\" in read ? read : undefined;\n}\n\n/**\n * @param schema - Property schema.\n * @returns {readonly SchemaNode[]} Its branches, with nested combinators and type lists opened.\n */\nfunction unionBranches(schema: SchemaNode): readonly SchemaNode[] {\n const union = schema.anyOf ?? schema.oneOf ?? schema.allOf;\n if (Array.isArray(union)) return (union as readonly SchemaNode[]).flatMap(unionBranches);\n if (!Array.isArray(schema.type)) return [schema];\n return (schema.type as readonly unknown[]).map((type) => ({ ...schema, type }));\n}\n\n/**\n * The first reading of the word the schema accepts: the text itself, then what each branch spells.\n *\n * @param schema - Property schema, a union or not.\n * @param word - The word.\n * @returns {unknown} The value, or the word for validation to judge.\n */\nfunction wordValue(schema: SchemaNode, word: string): unknown {\n const readings = [\n word,\n ...unionBranches(schema).flatMap((branch) => {\n const read = branchValue(branch, word);\n return read === undefined ? [] : [read.value];\n }),\n ];\n const index = readings.findIndex((value) => Value.Check(schema, value));\n return index === -1 ? word : readings[index];\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, 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 (typeof raw !== \"string\") return { value: raw };\n if (field.kind === \"number\") return numberValue(field.schema.type === \"integer\", raw);\n if (field.kind === \"string\") return { value: wordValue(field.schema, raw) };\n if (field.kind !== \"json\") 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 are read as decimals,\n * booleans come from the flag, objects and arrays are JSON, any other word is\n * its first reading the schema accepts, and nothing is bent to fit it:\n * {@link invokeTool} validates as on every surface.\n *\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 number or a JSON value does not read.\n */\nfunction toolInput(\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 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: tool.cli?.json !== false,\n async run(words) {\n const result = await invokeTool(tool, toolInput(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 if (result.content.length > 0) {\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()}${field.rest ? \"...\" : \"\"}`;\n return field.required ? `<${name}>` : `[${name}]`;\n });\n const rows = [\n ...flags.map((field): [string, string] => [\n `${field.short === undefined ? \"\" : `-${field.short}, `}${optionSpelling(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":";;;;;;;;;;AAsDA,MAAM,6BAAY,IAAA,IAAA,CAAA,UAAA,MAAA,CAAA;AAGlB,MAAM,aAAA;AAA0B,MAAA,6BAAA,IAAA,IAAA;CAAQ,CAAA,WAAA,SAAA;CAAW,CAAA,WAAA,Q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AAA,MAAA,MAAA;EAC9F,MAAM,QAAA,IAAW,KAAA;CAEjB,SAAO,OAAO;EAChB,YAAA,SAAA,KAAA;;;;;CAOA,OAAA,KAAS,KAAA,CAAA,MAAY,WAAkE,KAAA,KAAA,OAAA,KAAA,EAAA,IAAA,QAAA,QAAA,CAAA;AACrF;AAEA,SAAM,UAAW,SAAA,UAAkB;CACnC,OAAI;EACJ,GAAI,QAAA,YAAe,IAAO,QAAU,KAAA,IAAA,QAAiB,QAAA;EACrD;EACA,SAAO,QAAW,KAAA;EACpB;;;;;EAMA,OAAS,QAAA,KAAA;CACP,CAAA,CAAA,KAAM,IAAA;AACN;AAEA,SAAQ,aAAmC,SAAK,SAAU;CAAE,MAAG,aAAA,QAAA,OAAA,QAAA,UAAA,MAAA,UAAA;CAAQ,MAAA,QAAA,QAAA,OAAA,QAAA,UAAA,CAAA,MAAA,UAAA;CAAK,MAAE,eAAA,MAAA,SAAA,KAAA,QAAA;CAChF,MAAA,QAAA,WAAA,KAAA,UAAA;;;;;;;;CASA;CACE,OAAM;EAGF,GAAA,QAAM,QAAO,IAAA,QAAY,KAAQ,GAAI,QAAA,KAAA,IAAA,QAAA,QAAA;EACrC;EACD,SACH;GACA,QAAM;GACN,QAAO;GACT,GAAA,eAAA,CAAA,WAAA,IAAA,CAAA;;;;;;GAOA;GACE,GAAI,MAAM,WAAS,KAAQ,UAAK,CAAA,MAAA,KAAA,YAAA,GAAA,iBAAA,KAAA,CAAA,CAAA,CAAA;EAC9B,IAAA,CAAA;EACA;EACF;EACA;EACA,GAAI,MAAM,IAAA;CACV,CAAA,CAAA,KAAI,IAAM;AACV;AAEE,SAAO,iBAAc,OAAS;CAChC,IAAA,MAAQ,SAAA,SAAA,MAAA;CACN,QAAO,KAAE;AACX"}
1
+ {"version":3,"file":"cli.mjs","names":["Value.Check"],"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 positionals,\n * short flags 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 ToolCallContext,\n type ToolDefinition,\n type ToolProgress,\n} from \"./index.ts\";\nimport type { McpServerInfo } from \"./mcp-answers.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. Bytes are the\n * command's own business: it reads `-` from stdin itself in `execute`, and\n * writes to stdout itself, answering with no content and `cli.json: false`.\n * A command that prints rows as they land reads `--json` off its {@link CliHost},\n * and leaves `progress` alone: on a terminal its line would sit in front of the rows.\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` over stdio, named by the CLI on `true` or by the server info it's handed. */\n readonly mcp?: boolean | McpServerInfo;\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/** What a CLI command finds in `host`: narrow to it and look at `json` before writing a byte. */\nexport interface CliHost {\n readonly cli: true;\n /** `--json` was given, so the details are the answer and stdout stays theirs. */\n readonly json: 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\n/** Kinds whose value is the text itself: `enum` is string values only. */\nconst TEXT_KINDS = new Set<FieldKind>([\"string\", \"enum\"]);\n\n/** A short flag: one letter, so a negative number never reads as one. */\nconst SHORT_FLAG = /^[a-z]$/i;\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 /** Takes the words the other positionals leave, so it's always the last one. */\n readonly rest: boolean;\n /** Items of a `rest` array, where each word stays one item instead of joining the others. */\n readonly restItems: SchemaNode | undefined;\n readonly short: string | undefined;\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 * @param schema - Property schema.\n * @returns {SchemaNode | undefined} The items of an array of text, if the schema is one.\n */\nfunction textItems(schema: SchemaNode): SchemaNode | undefined {\n const { items } = schema;\n if (schema.type !== \"array\" || typeof items !== \"object\" || items === null) return undefined;\n if (Array.isArray(items)) return undefined;\n return unionBranches(items as SchemaNode).every(takesText) ? (items as SchemaNode) : undefined;\n}\n\n/**\n * @param branch - One branch of an item schema, unions opened.\n * @returns {boolean} Whether it takes text only, so no word turns into a number or `null`.\n */\nfunction takesText(branch: SchemaNode): boolean {\n if (branch.type === \"string\" || typeof branch.const === \"string\") return true;\n return Array.isArray(branch.enum) && branch.enum.every((value) => typeof value === \"string\");\n}\n\ninterface CliHints {\n /** The `positional` hint with `rest` at the end. */\n readonly positional: readonly string[];\n readonly rest: readonly string[];\n readonly short: Readonly<Record<string, string>>;\n readonly stdin: readonly string[];\n}\n\n/**\n * @param tool - Tool to read.\n * @returns {CliHints} Its hints, every key a property of the tool.\n * @throws {ToolDefinitionError} When a hint names a property the tool lacks, or a positional twice.\n */\nfunction cliHints(tool: ToolDefinition): CliHints {\n const cli = tool.cli ?? {};\n const rest = cli.rest === undefined ? [] : [cli.rest];\n const hints = {\n positional: [...(cli.positional ?? []), ...rest],\n rest,\n short: cli.short ?? {},\n stdin: cli.stdin ?? [],\n };\n const properties = tool.input.properties as Readonly<Record<string, unknown>>;\n for (const key of [...hints.positional, ...Object.keys(hints.short), ...hints.stdin]) {\n if (!Object.hasOwn(properties, key)) {\n throw new ToolDefinitionError(`${tool.name}: cli hint names unknown property ${key}`);\n }\n }\n const { positional } = hints;\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 return hints;\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, rest, short, stdin } = cliHints(tool);\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 rest: rest.includes(key),\n restItems: rest.includes(key) ? textItems(properties[key] ?? {}) : undefined,\n short: Object.hasOwn(short, key) ? short[key] : undefined,\n stdin: stdin.includes(key),\n };\n assertField(tool, field, !field.positional && flags.has(field.flag));\n assertShort(tool, field);\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 assertTextHints(tool, field);\n}\n\n/**\n * @param tool - Tool the field belongs to.\n * @param field - Field to check.\n * @throws {ToolDefinitionError} When `stdin` or `rest` sits on a property that takes no text.\n */\nfunction assertTextHints(tool: ToolDefinition, field: Field): void {\n if (field.stdin && field.kind !== \"string\") {\n throw new ToolDefinitionError(`${tool.name}: stdin property ${field.key} must be a string`);\n }\n if (field.rest && field.restItems === undefined && !TEXT_KINDS.has(field.kind)) {\n throw new ToolDefinitionError(\n `${tool.name}: rest property ${field.key} must be a string or an array of strings`,\n );\n }\n}\n\n/**\n * @param tool - Tool the field belongs to.\n * @param field - Field to check.\n * @throws {ToolDefinitionError} When the short flag is no letter, is `h` or sits on a positional.\n */\nfunction assertShort(tool: ToolDefinition, field: Field): void {\n if (field.short === undefined) return;\n if (field.positional) {\n throw new ToolDefinitionError(\n `${tool.name}: positional property ${field.key} takes no short flag`,\n );\n }\n if (!SHORT_FLAG.test(field.short)) {\n throw new ToolDefinitionError(\n `${tool.name}: short flag ${JSON.stringify(field.short)} of ${field.key} must match ${SHORT_FLAG}`,\n );\n }\n if (field.short === \"h\") {\n throw new ToolDefinitionError(\n `${tool.name}: property ${field.key} takes -h, which asks for help`,\n );\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`, and two short flags can land on one letter.\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 const short = field.short === undefined ? [] : [`-${field.short}`];\n for (const spelling of [`--${field.flag}`, ...negation, ...short]) {\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 * @param field - Option field.\n * @returns {string} Its long spelling in the usage text.\n */\nfunction optionSpelling(field: Field): string {\n return field.kind === \"boolean\"\n ? `--[no-]${field.flag}`\n : `--${field.flag}=<${valueHint(field)}>`;\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\n/** A raw value: a word, `true`/`false` for a boolean, the words of a `rest` array. */\ntype RawValue = string | boolean | readonly string[];\n\ninterface ParsedWords {\n /** Raw values by property, before {@link toolInput} reads them. */\n readonly values: Readonly<Record<string, RawValue>>;\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`, for a boolean `--no-flag`, and a short flag as\n * a whole word are options. A dashed word that spells none fills a free\n * positional ({@link takeDashedText}); past that, an unknown option, a missing\n * value, a value given twice or a positional too many is a failure, never a\n * 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 { args, origins, texts, refused } = takeDashedText(rawArgs, fields, options);\n const { tokens } = parseArgs({\n args,\n options: Object.fromEntries(\n Object.entries(options).map(([flag, field]) => [\n flag,\n field === \"json\"\n ? { type: \"boolean\" }\n : {\n type: field.kind === \"boolean\" ? \"boolean\" : \"string\",\n ...(field.short === undefined ? {} : { short: field.short }),\n },\n ]),\n ) as Record<string, { type: \"boolean\" | \"string\"; short?: string }>,\n strict: false,\n allowPositionals: true,\n allowNegative: true,\n tokens: true,\n });\n\n const values = emptyRecord<RawValue>();\n const errors = refused.map((word) => unknownOption(options, word));\n const flags = new Set<string>();\n for (const token of tokens) {\n if (token.kind !== \"option\") continue;\n const read = readOption(options, token, args[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 const positionals = inLineOrder(tokens, origins, texts);\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/** The line for `util.parseArgs` without the dashed text, and where each word stood. */\ninterface DashedText {\n readonly args: string[];\n /** Index on the original line of each word in `args`. */\n readonly origins: readonly number[];\n /** Dashed words read as positionals, with their index on the original line. */\n readonly texts: ReadonlyArray<readonly [number, string]>;\n /** Dashed words no positional is left for, which fail as unknown options. */\n readonly refused: readonly string[];\n}\n\n/**\n * Morse, PGP armor and `-5` take a positional the plain words leave free, or fail as unknown\n * options. Neither reaches `util.parseArgs`, which reads the inner `-` of `-.-.` as `--`.\n *\n * @param rawArgs - Words after the command name.\n * @param fields - The command's fields.\n * @param options - Option fields by flag, and `--json` when the command takes it.\n * @returns {DashedText} The words left for `util.parseArgs` and the dashed text.\n */\nfunction takeDashedText(\n rawArgs: readonly string[],\n fields: readonly Field[],\n options: Readonly<Record<string, Field | \"json\">>,\n): DashedText {\n const { dashed, plain } = scanWords(rawArgs, options);\n const free = fields.filter((field) => field.positional).length - plain;\n const taken = dashed.slice(0, Math.max(free, 0));\n const skipped = new Set(dashed);\n const origins = rawArgs.flatMap((_, index) => (skipped.has(index) ? [] : [index]));\n const word = (index: number): string => rawArgs[index] ?? \"\";\n return {\n args: origins.map(word),\n origins,\n texts: taken.map((index) => [index, word(index)] as const),\n refused: dashed.slice(taken.length).map(word),\n };\n}\n\n/**\n * @param rawArgs - Words after the command name.\n * @param options - Option fields by flag, and `--json` when the command takes it.\n * @returns {{ dashed: number[]; plain: number }} Dashed words that spell no option, plain words.\n */\nfunction scanWords(\n rawArgs: readonly string[],\n options: Readonly<Record<string, Field | \"json\">>,\n): { dashed: number[]; plain: number } {\n const dashed: number[] = [];\n let plain = 0;\n for (let index = 0; index < rawArgs.length; index++) {\n const word = rawArgs[index] ?? \"\";\n if (word === \"--\") return { dashed, plain: plain + rawArgs.length - index - 1 };\n const kind = wordKind(word, options);\n if (kind === \"plain\") plain++;\n else if (kind === \"text\") dashed.push(index);\n else if (kind === \"valued\") index++;\n }\n return { dashed, plain };\n}\n\n/**\n * Reads a whole word the way {@link optionField} takes its tokens.\n *\n * @param word - One word before `--`.\n * @param options - Option fields by flag, and `--json` when the command takes it.\n * @returns {\"plain\" | \"option\" | \"valued\" | \"text\"} `valued` takes the next word as its value.\n */\nfunction wordKind(\n word: string,\n options: Readonly<Record<string, Field | \"json\">>,\n): \"plain\" | \"option\" | \"valued\" | \"text\" {\n if (!word.startsWith(\"-\") || word === \"-\") return \"plain\";\n if (word === \"-h\") return \"option\";\n const field = word.startsWith(\"--\")\n ? longField(word.slice(2), options)\n : shortField(word, options);\n if (field === undefined) return \"text\";\n if (field === \"option\" || field.kind === \"boolean\" || word.includes(\"=\")) return \"option\";\n return \"valued\";\n}\n\n/**\n * @param tokens - Tokens of the line without the dashed text.\n * @param origins - Index on the original line of each word `util.parseArgs` read.\n * @param texts - The dashed text with its index on the original line.\n * @returns {string[]} Every positional word, in the order the line gave them.\n */\nfunction inLineOrder(\n tokens: ReadonlyArray<Readonly<{ kind: string; index: number; value?: string | undefined }>>,\n origins: readonly number[],\n texts: ReadonlyArray<readonly [number, string]>,\n): string[] {\n const read = tokens.flatMap((token) =>\n token.kind === \"positional\" ? [[origins[token.index] ?? 0, token.value ?? \"\"] as const] : [],\n );\n return [...texts, ...read].toSorted(([a], [b]) => a - b).map(([, word]) => word);\n}\n\n/**\n * @param spelled - A long option without its `--`, maybe with `=value`.\n * @param options - Option fields by flag, and `--json` when the command takes it.\n * @returns {Field | \"option\" | undefined} The field, or `option` for help, json, `--no-`.\n */\nfunction longField(\n spelled: string,\n options: Readonly<Record<string, Field | \"json\">>,\n): Field | \"option\" | undefined {\n const [name = \"\"] = spelled.split(\"=\", 1);\n if (name === \"help\") return \"option\";\n const field = Object.hasOwn(options, name) ? options[name] : undefined;\n if (field !== undefined) return field === \"json\" ? \"option\" : field;\n return negatesBoolean(name, options) ? \"option\" : undefined;\n}\n\n/**\n * @param name - A long option name without its `--`.\n * @param options - Option fields by flag.\n * @returns {boolean} Whether the name is the `no-` form of a boolean flag.\n */\nfunction negatesBoolean(name: string, options: Readonly<Record<string, Field | \"json\">>): boolean {\n const flag = name.slice(3);\n const field = name.startsWith(\"no-\") && Object.hasOwn(options, flag) ? options[flag] : undefined;\n return field !== undefined && field !== \"json\" && field.kind === \"boolean\";\n}\n\n/**\n * @param word - A word with one leading dash.\n * @param options - Option fields by flag.\n * @returns {Field | undefined} The field whose short flag the whole word is.\n */\nfunction shortField(\n word: string,\n options: Readonly<Record<string, Field | \"json\">>,\n): Field | undefined {\n return Object.values(options).find(\n (field): field is Field =>\n field !== \"json\" && field.short !== undefined && `-${field.short}` === word,\n );\n}\n\n/**\n * @param fields - The command's fields.\n * @param positionals - Positional words in order.\n * @returns {Record<string, RawValue>} Each positional property with its word, `rest` with the\n * others: joined by spaces for a string, one item per word for an array, empty when required.\n */\nfunction positionalValues(\n fields: readonly Field[],\n positionals: readonly string[],\n): Record<string, RawValue> {\n const takes = fields.filter((field) => field.positional);\n return Object.assign(\n emptyRecord<RawValue>(),\n Object.fromEntries(\n takes.flatMap((field, index): Array<[string, RawValue]> => {\n const words = field.rest ? positionals.slice(index) : positionals.slice(index, index + 1);\n if (field.restItems !== undefined)\n return words.length > 0 || field.required ? [[field.key, words]] : [];\n return words.length === 0 ? [] : [[field.key, words.join(\" \")]];\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 for words no positional takes.\n */\nfunction extraPositionals(fields: readonly Field[], positionals: readonly string[]): string[] {\n if (fields.some((field) => field.rest)) return [];\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 return field !== undefined && spells(field, token, word) ? field : undefined;\n}\n\n/**\n * `--flag`, `--no-flag` for a boolean, or the short flag as a whole word only,\n * since `util.parseArgs` would read a mistyped `-provider` as `-p rovider`.\n *\n * @param field - Field the token's name points to.\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 a spelling the field takes.\n */\nfunction spells(field: Field, token: OptionToken, word: string): boolean {\n if (token.rawName === `--${field.flag}`) return true;\n if (field.short !== undefined && token.rawName === `-${field.short}`)\n return word === token.rawName;\n return field.kind === \"boolean\" && token.rawName === `--no-${field.flag}`;\n}\n\n/**\n * @param options - Option fields by flag, and `--json` when the command takes it.\n * @param word - The command line word that names no option.\n * @returns {string} The failure, with every flag the command takes.\n */\nfunction unknownOption(options: Readonly<Record<string, Field | \"json\">>, word: string): string {\n const flags = Object.entries(options).map(([flag, each]) =>\n each === \"json\" || each.short === undefined ? `--${flag}` : `--${flag} (-${each.short})`,\n );\n const takes = flags.length > 0 ? flags.join(\", \") : \"no options\";\n return `Invalid arguments: unknown option ${JSON.stringify(word)}; takes ${takes}`;\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) return { error: unknownOption(options, word) };\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 !== `--no-${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/** An `integer` word: decimal digits, maybe signed. */\nconst DECIMAL_INTEGER = /^[+-]?\\d+$/;\n\n/** A `number` word: decimal, with an optional fraction and exponent. */\nconst DECIMAL_NUMBER = /^[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?$/i;\n\n/**\n * Reads a number word as written: `Number` alone takes `0x10`, and an empty word as zero.\n *\n * @param integer - Whether the schema wants an `integer` rather than any `number`.\n * @param word - The word.\n * @returns {{ value: number } | { error: string }} The number, or the core's type error.\n */\nfunction numberValue(integer: boolean, word: string): { value: number } | { error: string } {\n const value = Number(word);\n const written = (integer ? DECIMAL_INTEGER : DECIMAL_NUMBER).test(word);\n if (written && Number.isFinite(value)) return { value };\n return { error: integer ? \"must be integer\" : \"must be number\" };\n}\n\n/** Literal values a word can spell; an object or array never comes from one word. */\nconst LITERAL_TYPES = new Set([\"string\", \"number\", \"boolean\"]);\n\n/** Types whose every value is a literal a word spells. */\nconst TYPE_LITERALS = new Map<unknown, readonly unknown[]>([\n [\"null\", [null]],\n [\"boolean\", [true, false]],\n]);\n\n/**\n * @param values - Every value the branch allows, from `const`, `enum` or its type.\n * @param word - The word.\n * @returns {{ value: unknown } | undefined} The literal the word spells exactly, if any.\n */\nfunction literalValue(values: readonly unknown[], word: string): { value: unknown } | undefined {\n const spelled = (item: unknown) =>\n (item === null || LITERAL_TYPES.has(typeof item)) && String(item) === word;\n return values.some(spelled) ? { value: values.find(spelled) } : undefined;\n}\n\n/**\n * @param branch - One branch of a union.\n * @param word - The word.\n * @returns {{ value: unknown } | undefined} What the branch reads the word as, if it takes it at all.\n */\nfunction branchValue(branch: SchemaNode, word: string): { value: unknown } | undefined {\n if (Object.hasOwn(branch, \"const\")) return literalValue([branch.const], word);\n if (Array.isArray(branch.enum)) return literalValue(branch.enum, word);\n const literals = TYPE_LITERALS.get(branch.type);\n if (literals !== undefined) return literalValue(literals, word);\n if (TYPE_KINDS.get(branch.type) !== \"number\") return undefined;\n const read = numberValue(branch.type === \"integer\", word);\n return \"value\" in read ? read : undefined;\n}\n\n/**\n * @param schema - Property schema.\n * @returns {readonly SchemaNode[]} Its branches, with nested combinators and type lists opened.\n */\nfunction unionBranches(schema: SchemaNode): readonly SchemaNode[] {\n const union = schema.anyOf ?? schema.oneOf ?? schema.allOf;\n if (Array.isArray(union)) return (union as readonly SchemaNode[]).flatMap(unionBranches);\n if (!Array.isArray(schema.type)) return [schema];\n return (schema.type as readonly unknown[]).map((type) => ({ ...schema, type }));\n}\n\n/**\n * The first reading of the word the schema accepts: the text itself, then what each branch spells.\n *\n * @param schema - Property schema, a union or not.\n * @param word - The word.\n * @returns {unknown} The value, or the word for validation to judge.\n */\nfunction wordValue(schema: SchemaNode, word: string): unknown {\n const readings = [\n word,\n ...unionBranches(schema).flatMap((branch) => {\n const read = branchValue(branch, word);\n return read === undefined ? [] : [read.value];\n }),\n ];\n const index = readings.findIndex((value) => Value.Check(schema, value));\n return index === -1 ? word : readings[index];\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, or why there is none.\n */\nfunction fieldValue(field: Field, raw: string | boolean): { 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 (typeof raw !== \"string\") return { value: raw };\n if (field.kind === \"number\") return numberValue(field.schema.type === \"integer\", raw);\n if (field.kind === \"string\") return { value: wordValue(field.schema, raw) };\n if (field.kind !== \"json\") 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 are read as decimals,\n * booleans come from the flag, objects and arrays are JSON (a `rest` array\n * takes its words instead), any other word is its first reading the schema\n * accepts, and nothing is bent to fit it: {@link invokeTool} validates as on\n * every surface.\n *\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 number or a JSON value does not read.\n */\nfunction toolInput(fields: readonly Field[], values: Readonly<Record<string, RawValue>>): 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 =\n typeof raw === \"object\"\n ? { value: raw.map((word) => wordValue(field.restItems ?? {}, word)) }\n : 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 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/** Cuts the progress line between characters a terminal draws, so an emoji stays whole. */\nconst GRAPHEMES = new Intl.Segmenter();\n\n/** Code points a terminal draws two cells wide: emoji and the East Asian wide blocks. */\nconst WIDE =\n /^(?:\\p{Extended_Pictographic}|[\\u1100-\\u115F\\u231A\\u231B\\u2329\\u232A\\u2630-\\u2637\\u268A-\\u268F\\u2E80-\\u303E\\u3041-\\u33FF\\u3400-\\u4DFF\\u4E00-\\u9FFF\\uA000-\\uA4CF\\uA960-\\uA97F\\uAC00-\\uD7A3\\uF900-\\uFAFF\\uFE10-\\uFE19\\uFE30-\\uFE6F\\uFF00-\\uFF60\\uFFE0-\\uFFE6\\u{16FE0}-\\u{18DFF}\\u{1AFF0}-\\u{1B2FF}\\u{1D15E}-\\u{1D164}\\u{1D1BB}-\\u{1D1C0}\\u{1D300}-\\u{1D376}\\u{1F000}-\\u{1FAFF}\\u{20000}-\\u{3FFFD}])$/u;\n\n/** Emoji a terminal draws two cells wide whatever their code points add up to, as `1️⃣`. */\nconst EMOJI = /^\\p{RGI_Emoji}$/v;\n\n/** Marks that sit on the character before them and take no cell of their own. */\nconst ZERO_WIDTH = /^[\\p{Mn}\\p{Me}]$/u;\n\n/**\n * @param point - One code point.\n * @returns {number} Cells it takes on a terminal.\n */\nfunction pointCells(point: string): number {\n if (WIDE.test(point)) return 2;\n return ZERO_WIDTH.test(point) ? 0 : 1;\n}\n\n/**\n * @param grapheme - One grapheme.\n * @returns {number} Cells it takes on a terminal.\n */\nfunction graphemeCells(grapheme: string): number {\n let size = 0;\n for (const point of grapheme.normalize(\"NFC\")) size += pointCells(point);\n return Math.max(EMOJI.test(grapheme) ? 2 : 1, size);\n}\n\n/**\n * Counts no fewer cells than Node's ICU, since a short count wraps the line past the wipe.\n *\n * @param text - Line to fit.\n * @param room - Cells there are.\n * @returns {{ text: string; cells: number }} The graphemes that fit and the cells they take.\n */\nfunction fitLine(text: string, room: number): { text: string; cells: number } {\n let fitted = \"\";\n let used = 0;\n for (const { segment } of GRAPHEMES.segment(text)) {\n const size = graphemeCells(segment);\n if (used + size > room) break;\n fitted += segment;\n used += size;\n }\n return { text: fitted, cells: used };\n}\n\n/** Where a call's progress goes on the command line, and how to take it back. */\ninterface ProgressLine {\n readonly context: Pick<ToolCallContext, \"progress\">;\n readonly wipe: () => void;\n}\n\n/**\n * @param message - Line from the tool, already through `sanitizeLine`.\n * @param amount - How far it has come.\n * @returns {string} The line, with `(3/10)` when the tool knows the total.\n */\nfunction progressText(message: string, amount?: ToolProgress): string {\n const { progress, total } = amount ?? { progress: Number.NaN };\n if (!Number.isFinite(progress) || !Number.isFinite(total)) return message;\n return `${message} (${progress}/${total})`.trim();\n}\n\n/**\n * One stderr line that each progress update rewrites in place, wiped before the answer.\n * Off a terminal there's no line at all, so a pipe or a log gets the answer and nothing else.\n *\n * @returns {ProgressLine} The context to hand `invokeTool` and the wipe for after it.\n */\nfunction progressLine(): ProgressLine {\n const stream = process.stderr;\n if (stream.isTTY !== true) return { context: {}, wipe() {} };\n let width = 0;\n /** Blanks the line and puts the cursor back at its start, where every update leaves it. */\n const wipe = (): void => {\n if (width > 0) stream.write(`\\r${\" \".repeat(width)}\\r`);\n width = 0;\n };\n return {\n context: {\n progress(message, amount) {\n const line = fitLine(\n progressText(message, amount),\n Math.max(1, (stream.columns || 80) - 1),\n );\n wipe();\n stream.write(line.text);\n width = line.cells;\n },\n },\n wipe,\n };\n}\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: tool.cli?.json !== false,\n async run(words) {\n const host: CliHost = { cli: true, json: words.json };\n const line = progressLine();\n let result;\n try {\n result = await invokeTool(tool, toolInput(fields, words.values), { ...line.context, host });\n } finally {\n line.wipe();\n }\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 if (result.content.length > 0) {\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 const info = typeof options.mcp === \"object\" ? options.mcp : options;\n await createMcpServer(info, 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 !== undefined &&\n options.mcp !== false &&\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()}${field.rest ? \"...\" : \"\"}`;\n return field.required ? `<${name}>` : `[${name}]`;\n });\n const rows = [\n ...flags.map((field): [string, string] => [\n `${field.short === undefined ? \"\" : `-${field.short}, `}${optionSpelling(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; a terminal on\n * stderr only gets the progress line, which never reaches a pipe.\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"],"m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ACA;EACE;EACA,GAAA,MAAI,SAAQ,KAAW,YAAA,CAAA,CAAA,QAAA,MAAA,GAAA,QAAA,OAAA,CAAA,CAAA,KAAA,IAAA,GAAA,QAAA,OAAA,CAAA,CAAA;EACvB;EAIA,OAAI,QAAW,KAAA;CACV,CAAA,CAAA,KAAA,IAAA;AACP;AAEA,SAAO,aAAA,SAAA,SAAA;CACT,MAAA,aAAA,QAAA,OAAA,QAAA,UAAA,MAAA,UAAA;;;;;EAMA,OAAS,MAAA,WAAU,IAA6B,KAAoB,KAAA,IAAA,KAAA;CAClE,CAAA;CACF,MAAA,OAAA;;;;;;EAOA,GAAA,QAAS,QAAqC,IAAA,QAAA,KAAA,GAAA,QAAA,KAAA,IAAA,QAAA,QAAA;EAC5C;EACA,SAAQ;GACV,QAAA;;;;;;;GAQA;GACE;GACK,GAAA,MAAI,WAAQ,KAAA,UAAgB,CAAA,MAAM,KACrC,YAAM,GAAA,iBAAyB,KAAM,CAAA,CAAA,CAAA;EAChC,IAAA,CAAA;EACT;;;;;AAMA;AAYA,SAAA,iBAAA,OAAA;;;;;;CAQA,QAAM,OAAA,GAAA,SAEJ,gBAAA;;AAGF;AAGA,SAAM,aACJ,WAAA,eAAA"}
package/dist/mcp.d.mts CHANGED
@@ -1,55 +1,6 @@
1
- import { Icon, ToolCallContext, ToolDefinition } from "./_chunks/index.mjs";
2
- import { CallToolResult, Server, Tool, ToolAnnotations } from "@modelcontextprotocol/server";
3
- interface McpServerInfo {
4
- /** Server name, also used in the unknown-tool message. */
5
- readonly name: string;
6
- readonly version: string;
7
- /** Display name for clients that show one, such as `Forges`. */
8
- readonly title?: string;
9
- /** One line under the name on a connector card or in a registry. */
10
- readonly description?: string;
11
- readonly icons?: readonly Icon[];
12
- /** Project home a client can link to. */
13
- readonly websiteUrl?: string;
14
- }
15
- /**
16
- * Maps a tool's title and declared effect to MCP annotations. Claude Code reads its label here.
17
- *
18
- * @param tool - Tool to describe.
19
- * @returns {ToolAnnotations} Title and hints for the MCP client.
20
- */
21
- export declare function toolAnnotations(tool: ToolDefinition): ToolAnnotations;
22
- /**
23
- * Error result with every line-forging character replaced.
24
- *
25
- * The messages echo client-controlled values (a tool name, an argument) and
26
- * downstream error text, so they pass through here on every branch. Each line
27
- * is cleaned on its own, so only the breaks between the lines passed in
28
- * survive; a newline inside one line becomes a space.
29
- *
30
- * @param lines - Error lines.
31
- * @returns {CallToolResult} MCP error result.
32
- */
33
- export declare function errorResult(...lines: readonly string[]): CallToolResult;
34
- /**
35
- * The entries `tools/list` answers with, in the order given.
36
- *
37
- * @param tools - Tools to list.
38
- * @returns {Tool[]} Name, title, description, icons, schema and annotations of each tool.
39
- * @throws {ToolDefinitionError} When two tools share a name.
40
- */
41
- export declare function listTools(tools: readonly ToolDefinition[]): Tool[];
42
- /**
43
- * Answers one call as `tools/call` does and never throws, so every transport gives the same text.
44
- *
45
- * @param info - Server info; `name` is the word in the message for an unknown tool.
46
- * @param tools - Tools to look the name up in.
47
- * @param name - Tool name as the client sent it.
48
- * @param args - Arguments as the client sent them; missing ones count as `{}`.
49
- * @param context - Context for this call, such as the request's abort signal.
50
- * @returns {Promise<CallToolResult>} The tool's text, or the sanitized error.
51
- */
52
- export declare function callTool(info: Pick<McpServerInfo, "name">, tools: readonly ToolDefinition[], name: string, args?: unknown, context?: ToolCallContext): Promise<CallToolResult>;
1
+ import { ToolDefinition } from "./_chunks/index.mjs";
2
+ import { McpServerInfo, callTool, errorResult, listTools, toolAnnotations } from "./_chunks/mcp-answers.mjs";
3
+ import { Server } from "@modelcontextprotocol/server";
53
4
  /**
54
5
  * Creates an unconnected MCP server exposing the tools.
55
6
  *
@@ -72,5 +23,5 @@ export declare function callTool(info: Pick<McpServerInfo, "name">, tools: reado
72
23
  * @throws {ToolDefinitionError} When two tools share a name.
73
24
  */
74
25
  export declare function createMcpServer(info: McpServerInfo, tools: readonly ToolDefinition[]): Server;
75
- export type { McpServerInfo };
26
+ export { type McpServerInfo, callTool, errorResult, listTools, toolAnnotations };
76
27
  //# sourceMappingURL=mcp.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"mcp.d.mts","names":[],"sources":["../src/mcp-answers.ts","../src/mcp.ts"],"mappings":";;UAoBiB;;WAEN;WACA;;WAEA;;WAEA;WACA,iBAAiB;;WAEjB;;;;;;;;wBASK,gBAAgB,MAAM,iBAAiB;;;;;;;;;;;;wBAqBvC,eAAe,2BAA2B;;;;;;;;wBAW1C,UAAU,gBAAgB,mBAAmB;;;;;;;;;;;wBAkCvC,SACpB,MAAM,KAAK,wBACX,gBAAgB,kBAChB,cACA,gBACA,UAAS,kBACR,QAAQ;;;;;;;;;;;;;;;;;;;;;;wBClEK,gBAAgB,MAAM,eAAe,gBAAgB,mBAAmB"}
1
+ {"version":3,"file":"mcp.d.mts","names":[],"sources":["../src/mcp.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;wBA6CgB,gBAAgB,MAAM,eAAe,gBAAgB,mBAAmB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agntn/tools",
3
- "version": "0.2.1",
3
+ "version": "0.2.2",
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",