@agntn/tools 0.2.0 → 0.2.1

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.
@@ -23,10 +23,17 @@ function listTools(tools) {
23
23
  name: tool.name,
24
24
  title: tool.title,
25
25
  description: tool.description,
26
+ ...tool.icons === void 0 ? {} : { icons: copyIcons(tool.icons) },
26
27
  inputSchema: wireSchema(tool),
27
28
  annotations: toolAnnotations(tool)
28
29
  }));
29
30
  }
31
+ function copyIcons(icons) {
32
+ return icons.map(({ sizes, ...rest }) => sizes === void 0 ? rest : {
33
+ ...rest,
34
+ sizes: [...sizes]
35
+ });
36
+ }
30
37
  async function callTool(info, tools, name, args = {}, context = {}) {
31
38
  const tool = tools.find((candidate) => candidate.name === name);
32
39
  if (!tool) return errorResult(`Unknown ${info.name} tool: ${JSON.stringify(name)}`);
@@ -55,6 +62,6 @@ function progressSteps(notify) {
55
62
  });
56
63
  };
57
64
  }
58
- export { callTool, errorResult, listTools, progressSteps, toolAnnotations };
65
+ export { callTool, copyIcons, errorResult, listTools, progressSteps, toolAnnotations };
59
66
 
60
67
  //# sourceMappingURL=mcp-answers.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"mcp-answers.mjs","names":[],"sources":["../../src/mcp-answers.ts"],"sourcesContent":["/**\n * What `tools/list` and `tools/call` answer, without the MCP SDK at runtime.\n *\n * Shared by the `Server` in `mcp.ts` and the h3-mcp adapter in `h3.ts`, so a\n * transport that brings its own JSON-RPC layer never loads the SDK.\n */\n\nimport type { CallToolResult, Tool, ToolAnnotations } from \"@modelcontextprotocol/server\";\n\nimport {\n indexTools,\n invokeTool,\n sanitizeLine,\n ToolInputError,\n wireSchema,\n type ToolCallContext,\n type ToolDefinition,\n} from \"./index.ts\";\n\nexport interface McpServerInfo {\n /** Server name, also used in the unknown-tool message. */\n readonly name: string;\n readonly version: string;\n /** Display name for clients that show one, such as `Forges`. */\n readonly title?: string;\n /** Project home a client can link to. */\n readonly websiteUrl?: string;\n}\n\n/**\n * Maps a tool's title and declared effect to MCP annotations. Claude Code reads its label here.\n *\n * @param tool - Tool to describe.\n * @returns {ToolAnnotations} Title and hints for the MCP client.\n */\nexport function toolAnnotations(tool: ToolDefinition): ToolAnnotations {\n return {\n title: tool.title,\n readOnlyHint: tool.effect === \"read\",\n destructiveHint: tool.effect === \"destructive\",\n idempotentHint: tool.idempotent ?? tool.effect === \"read\",\n openWorldHint: tool.openWorld ?? false,\n };\n}\n\n/**\n * Error result with every line-forging character replaced.\n *\n * The messages echo client-controlled values (a tool name, an argument) and\n * downstream error text, so they pass through here on every branch. Each line\n * is cleaned on its own, so only the breaks between the lines passed in\n * survive; a newline inside one line becomes a space.\n *\n * @param lines - Error lines.\n * @returns {CallToolResult} MCP error result.\n */\nexport function errorResult(...lines: readonly string[]): CallToolResult {\n return { content: [{ type: \"text\", text: lines.map(sanitizeLine).join(\"\\n\") }], isError: true };\n}\n\n/**\n * The entries `tools/list` answers with, in the order given.\n *\n * @param tools - Tools to list.\n * @returns {Tool[]} Name, title, description, schema and annotations of each tool.\n * @throws {ToolDefinitionError} When two tools share a name.\n */\nexport function listTools(tools: readonly ToolDefinition[]): Tool[] {\n indexTools(tools);\n return tools.map((tool) => ({\n name: tool.name,\n title: tool.title,\n description: tool.description,\n inputSchema: wireSchema(tool) as Tool[\"inputSchema\"],\n annotations: toolAnnotations(tool),\n }));\n}\n\n/**\n * Answers one call as `tools/call` does and never throws, so every transport gives the same text.\n *\n * @param info - Server info; `name` is the word in the message for an unknown tool.\n * @param tools - Tools to look the name up in.\n * @param name - Tool name as the client sent it.\n * @param args - Arguments as the client sent them; missing ones count as `{}`.\n * @param context - Context for this call, such as the request's abort signal.\n * @returns {Promise<CallToolResult>} The tool's text, or the sanitized error.\n */\nexport async function callTool(\n info: Pick<McpServerInfo, \"name\">,\n tools: readonly ToolDefinition[],\n name: string,\n args: unknown = {},\n context: ToolCallContext = {},\n): Promise<CallToolResult> {\n const tool = tools.find((candidate) => candidate.name === name);\n if (!tool) return errorResult(`Unknown ${info.name} tool: ${JSON.stringify(name)}`);\n\n try {\n const result = await invokeTool(tool, args, context);\n return {\n content: result.content,\n ...(result.isError === undefined ? {} : { isError: result.isError }),\n };\n } catch (error) {\n if (error instanceof ToolInputError) return errorResult(...error.lines);\n return errorResult(\n `${tool.name} failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n\n/** One `notifications/progress` without its token. */\nexport interface ProgressParams {\n readonly progress: number;\n readonly total?: number;\n readonly message: string;\n}\n\n/**\n * Numbers progress lines for MCP: a bare line counts one up, an amount that doesn't grow drops.\n *\n * @param notify - Sends one notification for the request.\n * @returns {NonNullable<ToolCallContext[\"progress\"]>} The callback for `execute`.\n */\nexport function progressSteps(\n notify: (params: ProgressParams) => void,\n): NonNullable<ToolCallContext[\"progress\"]> {\n let last: number | undefined;\n return (message, amount) => {\n const progress = amount?.progress ?? (last ?? 0) + 1;\n if (!Number.isFinite(progress) || (last !== undefined && progress <= last)) return;\n last = progress;\n const total = amount?.total;\n notify({ progress, ...(Number.isFinite(total) ? { total } : {}), message });\n };\n}\n"],"mappings":";;;;;;EAmCA,gBAAgB,KAAA,cAAuD,KAAA,WAAA;EACrE,eAAO,KAAA,aAAA;CACL;AACA;AAEA,SAAA,YAAgB,GAAK,OAAA;CACrB,OAAA;EACF,SAAA,CAAA;GACF,MAAA;;;;;;;;;;;EAaA,aAAgB,KAAA;EACd,aAAO,WAAA,IAAA;EAAE,aAAU,gBAAA,IAAA;CAAE,EAAA;AAAc;AAA6C,eAAS,SAAA,MAAA,OAAA,MAAA,OAAA,CAAA,GAAA,UAAA,CAAA,GAAA;CAAK,MAAA,OAAA,MAAA,MAAA,cAAA,UAAA,SAAA,IAAA;CAChG,IAAA,CAAA,MAAA,OAAA,YAAA,WAAA,KAAA,KAAA,SAAA,KAAA,UAAA,IAAA,GAAA;;;;;;;;EASA,IAAA,iBAA0B,gBAA0C,OAAA,YAAA,GAAA,MAAA,KAAA;EAClE,OAAA,YAAgB,GAAA,KAAA,KAAA,WAAA,iBAAA,QAAA,MAAA,UAAA,OAAA,KAAA,GAAA;CAChB;AACE;AAEA,SAAA,cAAkB,QAAA;CAClB,IAAA;CACA,QAAA,SAAa,WAAA;EACf,MAAE,WAAA,QAAA,aAAA,QAAA,KAAA;EACJ,IAAA,CAAA,OAAA,SAAA,QAAA,KAAA,SAAA,KAAA,KAAA,YAAA,MAAA;;;;;;;;;;AAYA,SAAA,UAAsB,aAEpB,WAEA,eACA"}
1
+ {"version":3,"file":"mcp-answers.mjs","names":[],"sources":["../../src/mcp-answers.ts"],"sourcesContent":["/**\n * What `tools/list` and `tools/call` answer, without the MCP SDK at runtime.\n *\n * Shared by the `Server` in `mcp.ts` and the h3-mcp adapter in `h3.ts`, so a\n * transport that brings its own JSON-RPC layer never loads the SDK.\n */\n\nimport type { CallToolResult, Tool, ToolAnnotations } from \"@modelcontextprotocol/server\";\n\nimport {\n indexTools,\n invokeTool,\n sanitizeLine,\n ToolInputError,\n wireSchema,\n type Icon,\n type ToolCallContext,\n type ToolDefinition,\n} from \"./index.ts\";\n\nexport interface McpServerInfo {\n /** Server name, also used in the unknown-tool message. */\n readonly name: string;\n readonly version: string;\n /** Display name for clients that show one, such as `Forges`. */\n readonly title?: string;\n /** One line under the name on a connector card or in a registry. */\n readonly description?: string;\n readonly icons?: readonly Icon[];\n /** Project home a client can link to. */\n readonly websiteUrl?: string;\n}\n\n/**\n * Maps a tool's title and declared effect to MCP annotations. Claude Code reads its label here.\n *\n * @param tool - Tool to describe.\n * @returns {ToolAnnotations} Title and hints for the MCP client.\n */\nexport function toolAnnotations(tool: ToolDefinition): ToolAnnotations {\n return {\n title: tool.title,\n readOnlyHint: tool.effect === \"read\",\n destructiveHint: tool.effect === \"destructive\",\n idempotentHint: tool.idempotent ?? tool.effect === \"read\",\n openWorldHint: tool.openWorld ?? false,\n };\n}\n\n/**\n * Error result with every line-forging character replaced.\n *\n * The messages echo client-controlled values (a tool name, an argument) and\n * downstream error text, so they pass through here on every branch. Each line\n * is cleaned on its own, so only the breaks between the lines passed in\n * survive; a newline inside one line becomes a space.\n *\n * @param lines - Error lines.\n * @returns {CallToolResult} MCP error result.\n */\nexport function errorResult(...lines: readonly string[]): CallToolResult {\n return { content: [{ type: \"text\", text: lines.map(sanitizeLine).join(\"\\n\") }], isError: true };\n}\n\n/**\n * The entries `tools/list` answers with, in the order given.\n *\n * @param tools - Tools to list.\n * @returns {Tool[]} Name, title, description, icons, schema and annotations of each tool.\n * @throws {ToolDefinitionError} When two tools share a name.\n */\nexport function listTools(tools: readonly ToolDefinition[]): Tool[] {\n indexTools(tools);\n return tools.map((tool) => ({\n name: tool.name,\n title: tool.title,\n description: tool.description,\n ...(tool.icons === undefined ? {} : { icons: copyIcons(tool.icons) }),\n inputSchema: wireSchema(tool) as Tool[\"inputSchema\"],\n annotations: toolAnnotations(tool),\n }));\n}\n\n/**\n * Icons as the SDK types them, mutable arrays included.\n *\n * @param icons - Icons from a definition or the server info.\n * @returns {NonNullable<Tool[\"icons\"]>} The same icons, copied.\n */\nexport function copyIcons(icons: readonly Icon[]): NonNullable<Tool[\"icons\"]> {\n return icons.map(({ sizes, ...rest }) =>\n sizes === undefined ? rest : { ...rest, sizes: [...sizes] },\n );\n}\n\n/**\n * Answers one call as `tools/call` does and never throws, so every transport gives the same text.\n *\n * @param info - Server info; `name` is the word in the message for an unknown tool.\n * @param tools - Tools to look the name up in.\n * @param name - Tool name as the client sent it.\n * @param args - Arguments as the client sent them; missing ones count as `{}`.\n * @param context - Context for this call, such as the request's abort signal.\n * @returns {Promise<CallToolResult>} The tool's text, or the sanitized error.\n */\nexport async function callTool(\n info: Pick<McpServerInfo, \"name\">,\n tools: readonly ToolDefinition[],\n name: string,\n args: unknown = {},\n context: ToolCallContext = {},\n): Promise<CallToolResult> {\n const tool = tools.find((candidate) => candidate.name === name);\n if (!tool) return errorResult(`Unknown ${info.name} tool: ${JSON.stringify(name)}`);\n\n try {\n const result = await invokeTool(tool, args, context);\n return {\n content: result.content,\n ...(result.isError === undefined ? {} : { isError: result.isError }),\n };\n } catch (error) {\n if (error instanceof ToolInputError) return errorResult(...error.lines);\n return errorResult(\n `${tool.name} failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n\n/** One `notifications/progress` without its token. */\nexport interface ProgressParams {\n readonly progress: number;\n readonly total?: number;\n readonly message: string;\n}\n\n/**\n * Numbers progress lines for MCP: a bare line counts one up, an amount that doesn't grow drops.\n *\n * @param notify - Sends one notification for the request.\n * @returns {NonNullable<ToolCallContext[\"progress\"]>} The callback for `execute`.\n */\nexport function progressSteps(\n notify: (params: ProgressParams) => void,\n): NonNullable<ToolCallContext[\"progress\"]> {\n let last: number | undefined;\n return (message, amount) => {\n const progress = amount?.progress ?? (last ?? 0) + 1;\n if (!Number.isFinite(progress) || (last !== undefined && progress <= last)) return;\n last = progress;\n const total = amount?.total;\n notify({ progress, ...(Number.isFinite(total) ? { total } : {}), message });\n };\n}\n"],"mappings":";;;;;;EAuCA,gBAAgB,KAAA,cAAuD,KAAA,WAAA;EACrE,eAAO,KAAA,aAAA;CACL;AACA;AAEA,SAAA,YAAgB,GAAK,OAAA;CACrB,OAAA;EACF,SAAA,CAAA;GACF,MAAA;;;;;;;;;;;EAaA,aAAgB,KAAA;EACd,GAAA,KAAO,UAAA,KAAA,IAAA,CAAA,IAAA,EAAA,OAAA,UAAA,KAAA,KAAA,EAAA;EAAE,aAAU,WAAA,IAAA;EAAE,aAAM,gBAAA,IAAA;CAAQ,EAAA;AAAyC;AAAkB,SAAA,UAAA,OAAA;CAChG,OAAA,MAAA,KAAA,EAAA,OAAA,GAAA,WAAA,UAAA,KAAA,IAAA,OAAA;;;;;;;CASA,IAAA,CAAA,MAAgB,OAAU,YAA0C,WAAA,KAAA,KAAA,SAAA,KAAA,UAAA,IAAA,GAAA;CAClE,IAAA;EACA,MAAO,SAAM,MAAK,WAAU,MAAA,MAAA,OAAA;EAC1B,OAAM;GACN,SAAO,OAAK;GACZ,GAAA,OAAA,YAAkB,KAAA,IAAA,CAAA,IAAA,EAAA,SAAA,OAAA,QAAA;EAClB;CACA,SAAA,OAAa;EACb,IAAA,iBAAa,gBAAoB,OAAA,YAAA,GAAA,MAAA,KAAA;EACnC,OAAE,YAAA,GAAA,KAAA,KAAA,WAAA,iBAAA,QAAA,MAAA,UAAA,OAAA,KAAA,GAAA;CACJ;;;;;;EAQA,IAAA,CAAA,OAAgB,SAAU,QAAoD,KAAA,SAAA,KAAA,KAAA,YAAA,MAAA;EAC5E,OAAO;EAC0B,MAAG,QAAA,QAAA;EAAM,OAAO;GACjD;GACF,GAAA,OAAA,SAAA,KAAA,IAAA,EAAA,MAAA,IAAA,CAAA"}
@@ -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\n/** Content block understood by MCP, Pi and OMP alike. */\nexport type ToolContent =\n | { type: \"text\"; text: string }\n | { type: \"image\"; data: string; mimeType: string };\n\n/** Text for the model plus details for the harness. */\nexport interface ToolResult<Details = unknown> {\n content: ToolContent[];\n details: Details;\n /** Set when the tool could not answer. Each adapter carries it to its host. */\n isError?: boolean;\n}\n\n/**\n * What a call does to the world, mapped to MCP annotations and OMP approval.\n *\n * - `read` changes nothing.\n * - `write` changes state that the next call can undo or overwrite.\n * - `destructive` deletes or overwrites what cannot be recovered.\n */\nexport type ToolEffect = \"read\" | \"write\" | \"destructive\";\n\n/**\n * How a tool reads on the command line. Without hints the command is the tool\n * name without its package prefix, in kebab case, and every property is a flag.\n */\nexport interface ToolCliHints {\n /** Command name instead of the derived one. */\n readonly command?: string;\n readonly aliases?: readonly string[];\n /** Line in the command list. Defaults to the first sentence of `description`. */\n readonly description?: string;\n /** Properties taken in this order as positional arguments instead of flags. */\n readonly positional?: readonly string[];\n /** String properties that read stdin when given as `-`. */\n readonly stdin?: readonly string[];\n}\n\n/** How far a long call has come, for hosts that draw it. */\nexport interface ToolProgress {\n /** Work done so far. MCP skips an update where it doesn't grow. */\n readonly progress: number;\n /** All the work there is, when the tool knows it. */\n readonly total?: number;\n}\n\n/** Per-call context the adapters hand to `execute`. */\nexport interface ToolCallContext {\n signal?: AbortSignal;\n /** Says the call is still at it. Absent where the host can't show it, so call `progress?.()`. */\n progress?: (message: string, amount?: ToolProgress) => void;\n}\n\nexport interface ToolDefinition<Input extends TObject = TObject, Details = unknown> {\n /** Wire name, `<package>_<operation>`. */\n readonly name: string;\n /** Human label: MCP `title` and `annotations.title`, Pi and OMP `label`. */\n readonly title: string;\n /** Complete instruction for the model. MCP clients see nothing else. */\n readonly description: string;\n /** Pi `promptSnippet`. */\n readonly snippet?: string;\n /** Pi `promptGuidelines`. Must not promise anything `description` lacks. */\n readonly guidelines?: readonly string[];\n readonly effect: ToolEffect;\n /** Repeating the call with the same input has no further effect. Defaults to `effect === \"read\"`. */\n readonly idempotent?: boolean;\n /** The call reaches outside the local machine. */\n readonly openWorld?: boolean;\n readonly input: Input;\n /** Command line shape for `@agntn/tools/cli`. No other surface reads it. */\n readonly cli?: ToolCliHints;\n /**\n * Runs the tool on input that already passed {@link validateInput}.\n *\n * Method syntax on purpose: it keeps the parameter bivariant, so a list of\n * tools with different inputs is still a `readonly ToolDefinition[]`.\n */\n execute(\n input: Static<Input>,\n context: ToolCallContext,\n ): ToolResult<Details> | Promise<ToolResult<Details>>;\n}\n\n/** Thrown when a tool definition breaks a contract every surface relies on. */\nexport class ToolDefinitionError extends Error {\n override name = \"ToolDefinitionError\";\n}\n\n/** Thrown by {@link invokeTool} when the arguments fail the tool schema. */\nexport class ToolInputError extends Error {\n override name = \"ToolInputError\";\n /** One validation failure per line. Only these line breaks are the core's own. */\n readonly lines: readonly string[];\n\n /**\n * @param lines - One validation failure per line.\n */\n constructor(lines: readonly string[]) {\n super(lines.join(\"\\n\"));\n this.lines = lines;\n }\n}\n\nconst TOOL_NAME = /^[a-z][a-z0-9_]{0,63}$/;\n\n/**\n * Declares a tool and checks the schema rules every surface depends on.\n *\n * @param tool - Tool definition.\n * @returns {ToolDefinition<Input, Details>} The same definition, typed.\n */\nexport function defineTool<const Input extends TObject, Details>(\n tool: ToolDefinition<Input, Details>,\n): ToolDefinition<Input, Details> {\n if (!TOOL_NAME.test(tool.name)) {\n throw new ToolDefinitionError(`Tool name ${JSON.stringify(tool.name)} must match ${TOOL_NAME}`);\n }\n if (typeof tool.input !== \"object\" || tool.input === null) {\n // A function here is an omptype schema: `Type` came from a bare `typebox`\n // import that OMP remapped. `Value.Check` accepts any value against it.\n throw new ToolDefinitionError(\n `${tool.name}: input must be a JSON Schema object; build it with Type from @agntn/tools, not from \"typebox\"`,\n );\n }\n assertSchema(tool.name, wireSchema(tool));\n return tool;\n}\n\ntype SchemaNode = Readonly<Record<string, unknown>>;\n\n/**\n * Enforces two rules on the input schema, at every depth.\n *\n * A non-empty object must be closed (`additionalProperties: false`), because a\n * misspelled key would otherwise be dropped without a signal: `read_only`\n * instead of `readOnly` ran `harnesses_run` with full tool access. An empty\n * object stays open, since models send placeholders like `{_: \"\"}` to it.\n *\n * A union of literals must be `Type.Enum`: TypeBox serializes the union as\n * `anyOf` const objects, which triples the wire size, and `Value.Errors`\n * reports it as `must be equal to constant` against the first literal only.\n *\n * @param toolName - Tool the schema belongs to, for the error.\n * @param node - Schema node to check.\n * @param path - JSON pointer of the node, empty at the root.\n */\nfunction assertSchema(toolName: string, node: SchemaNode, path = \"\"): void {\n const at = path || \"/\";\n if (isOpenObject(node)) {\n throw new ToolDefinitionError(\n `${toolName}: object at ${at} must be closed with additionalProperties: false`,\n );\n }\n if (isLiteralUnion(node)) {\n throw new ToolDefinitionError(`${toolName}: union of literals at ${at} must use Type.Enum`);\n }\n for (const [child, childPath] of schemaChildren(node, path)) {\n assertSchema(toolName, child, childPath);\n }\n}\n\n/**\n * @param node - Schema node.\n * @returns {boolean} Whether the node is an object with properties that accepts other keys.\n */\nfunction isOpenObject(node: SchemaNode): boolean {\n const properties = node.properties as SchemaNode | undefined;\n return (\n node.type === \"object\" &&\n properties !== undefined &&\n Object.keys(properties).length > 0 &&\n node.additionalProperties !== false\n );\n}\n\n/**\n * @param node - Schema node.\n * @returns {boolean} Whether the node is an `anyOf` of two or more constants.\n */\nfunction isLiteralUnion(node: SchemaNode): boolean {\n const anyOf = node.anyOf as readonly SchemaNode[] | undefined;\n return anyOf !== undefined && anyOf.length > 1 && anyOf.every((branch) => \"const\" in branch);\n}\n\n/**\n * @param value - Any schema keyword value.\n * @returns {boolean} Whether it is a nested schema.\n */\nfunction isNode(value: unknown): value is SchemaNode {\n return typeof value === \"object\" && value !== null;\n}\n\n/**\n * The subschemas a value of this node can reach: properties, record values,\n * array items and union branches.\n *\n * @param node - Schema node.\n * @param path - JSON pointer of the node.\n * @returns {Array<[SchemaNode, string]>} Each subschema with its path.\n */\nfunction schemaChildren(node: SchemaNode, path: string): Array<[SchemaNode, string]> {\n const keyed = (keyword: string, childPath: (key: string) => string) =>\n Object.entries(isNode(node[keyword]) ? node[keyword] : {}).flatMap(\n ([key, child]): Array<[SchemaNode, string]> =>\n isNode(child) ? [[child, childPath(key)]] : [],\n );\n const branches = Array.isArray(node.anyOf) ? (node.anyOf as readonly unknown[]) : [];\n return [\n ...keyed(\"properties\", (key) => `${path}/${key}`),\n ...keyed(\"patternProperties\", () => `${path}/*`),\n ...(isNode(node.items) ? [[node.items, `${path}/items`] as [SchemaNode, string]] : []),\n ...branches.filter(isNode).map((branch): [SchemaNode, string] => [branch, path]),\n ];\n}\n\n/**\n * The input schema as the plain JSON Schema object every host receives.\n *\n * TypeBox 1.x schemas are plain objects already; this only drops the static\n * type, which lacks the index signature host APIs declare.\n *\n * @param tool - Tool whose schema to emit.\n * @returns {Record<string, unknown>} JSON Schema document.\n */\nexport function wireSchema(tool: ToolDefinition): Record<string, unknown> {\n return Object.fromEntries(Object.entries(tool.input));\n}\n\n/**\n * Indexes tools by name.\n *\n * A `Map`, not a plain object: a lookup of `toString` in a `Record` finds\n * `Object.prototype.toString` and skips the unknown-tool branch.\n *\n * @param tools - Tools to index.\n * @returns {ReadonlyMap<string, ToolDefinition>} Tools by wire name.\n */\nexport function indexTools(tools: readonly ToolDefinition[]): ReadonlyMap<string, ToolDefinition> {\n const byName = new Map<string, ToolDefinition>();\n for (const tool of tools) {\n if (byName.has(tool.name)) throw new ToolDefinitionError(`Duplicate tool name ${tool.name}`);\n byName.set(tool.name, tool);\n }\n return byName;\n}\n\nexport type InputCheck<Input extends TObject> =\n | { ok: true; value: Static<Input> }\n | { ok: false; lines: readonly string[] };\n\n/**\n * Validates arguments against the tool schema, reporting every failure.\n *\n * Runs on every surface, not only MCP: a host may skip its own validation, and\n * OMP's omptype drops `pattern` from the schema it emits. The message has one\n * line per failure: an undeclared key names itself with the keys its object\n * takes, at any depth, and an enum failure names the allowed values, so the\n * caller does not go back to the tool list and guess. Format from agntn/hashes\n * (#58). TypeBox stops at eight errors, so root keys are read off the arguments.\n *\n * @param tool - Tool whose schema applies.\n * @param args - Arguments as received from the host.\n * @returns {InputCheck<Input>} The typed value, or the failures, one per line.\n */\nexport function validateInput<Input extends TObject>(\n tool: ToolDefinition<Input, unknown>,\n args: unknown,\n): InputCheck<Input> {\n if (Value.Check(tool.input, args)) return { ok: true, value: args };\n\n const schema = wireSchema(tool);\n const rootKeys =\n args !== null && typeof args === \"object\" && !Array.isArray(args)\n ? Object.keys(args).filter((key) => !Object.hasOwn(tool.input.properties, key))\n : [];\n const unknown = rootKeys.map((key) => unknownKeyLine(\"\", key, [schema]));\n const other: string[] = [];\n for (const error of Value.Errors(tool.input, args)) {\n if (error.keyword === \"additionalProperties\") continue;\n const refused = refusedKeyLines(schema, error.instancePath, error.schemaPath);\n if (refused === undefined)\n other.push(errorLine(error.instancePath, error.message, error.params));\n else unknown.push(...refused);\n }\n const lines = [...unknown, ...other];\n return { ok: false, lines: lines.length > 0 ? [...new Set(lines)] : [\"Invalid arguments\"] };\n}\n\n/**\n * @param at - JSON pointer of the failing value.\n * @param message - TypeBox's message.\n * @param params - TypeBox's parameters of the failure.\n * @returns {string} The line, with the allowed values when an enum failed.\n */\nfunction errorLine(at: string, message: string, params: unknown): string {\n const allowed = isNode(params) ? params.allowedValues : undefined;\n const text = Array.isArray(allowed) ? `must be one of ${allowed.join(\", \")}` : message;\n return `Invalid arguments at ${at || \"/\"}: ${text}`;\n}\n\n/**\n * A closed object refuses each extra key as `schema is false`, which names nothing on its own.\n *\n * @param root - Tool input schema.\n * @param at - JSON pointer of the failing value.\n * @param schemaPath - Schema path of the failure.\n * @returns {string[] | undefined} The line, none when another union branch takes the key, or\n * `undefined` for any other failure.\n */\nfunction refusedKeyLines(root: SchemaNode, at: string, schemaPath: string): string[] | undefined {\n const suffix = \"/additionalProperties\";\n if (!schemaPath.endsWith(suffix)) return undefined;\n const objectPath = schemaPath.slice(0, -suffix.length);\n const node = schemaAt(root, objectPath);\n if (node?.additionalProperties !== false) return undefined;\n const cut = at.lastIndexOf(\"/\");\n const key = unescapeToken(at.slice(cut + 1));\n const alternatives = alternativesAt(root, objectPath);\n if (alternatives.some((alternative) => takesKey(alternative, key))) return [];\n return [unknownKeyLine(at.slice(0, cut), key, alternatives)];\n}\n\n/**\n * Each union branch fails on its own, so the same object in another branch may take the key.\n *\n * @param root - Tool input schema.\n * @param pointer - Schema path of a closed object.\n * @returns {SchemaNode[]} That object as every branch of every enclosing union has it.\n */\nfunction alternativesAt(root: SchemaNode, pointer: string): SchemaNode[] {\n let nodes: unknown[] = [root];\n let previous = \"\";\n for (const token of pointer.split(\"/\").slice(1)) {\n const key = unescapeToken(token);\n const everyBranch = previous === \"anyOf\" && /^\\d+$/.test(key);\n nodes = nodes.flatMap((node): unknown[] => {\n if (everyBranch && Array.isArray(node)) return node;\n return isNode(node) && Object.hasOwn(node, key) ? [node[key]] : [];\n });\n previous = key;\n }\n return nodes.filter(isNode);\n}\n\n/**\n * @param token - One JSON pointer segment.\n * @returns {string} The property name it encodes.\n */\nfunction unescapeToken(token: string): string {\n return token.replaceAll(\"~1\", \"/\").replaceAll(\"~0\", \"~\");\n}\n\n/**\n * @param node - Schema node.\n * @param key - Property name.\n * @returns {boolean} Whether an object of this schema accepts the key.\n */\nfunction takesKey(node: SchemaNode, key: string): boolean {\n if (node.type !== \"object\") return false;\n if (node.additionalProperties !== false) return true;\n if (isNode(node.properties) && Object.hasOwn(node.properties, key)) return true;\n return patternsOf(node).some((pattern) => new RegExp(pattern, \"u\").test(key));\n}\n\n/**\n * @param node - Schema node.\n * @returns {string[]} Its `patternProperties` patterns.\n */\nfunction patternsOf(node: SchemaNode): string[] {\n return Object.keys(isNode(node.patternProperties) ? node.patternProperties : {});\n}\n\n/**\n * @param at - JSON pointer of the object, empty at the root.\n * @param key - The undeclared key.\n * @param objects - Schema of that object, once per union branch it sits in.\n * @returns {string} The key with what the object takes, and the object's path when it is nested.\n */\nfunction unknownKeyLine(at: string, key: string, objects: readonly SchemaNode[]): string {\n const lists = [\n ...new Set(\n objects\n .filter((object) => object.type === \"object\")\n .map((object) =>\n [\n ...Object.keys(isNode(object.properties) ? object.properties : {}),\n ...patternsOf(object).map((pattern) => `keys matching ${JSON.stringify(pattern)}`),\n ].join(\", \"),\n ),\n ),\n ];\n const takes = lists.length > 1 ? lists.map((list) => `{${list}}`).join(\" or \") : lists[0];\n const where = at === \"\" ? \"\" : ` at ${at}`;\n const what = takes || \"no properties\";\n return `Invalid arguments${where}: unknown property ${JSON.stringify(key)}; takes ${what}`;\n}\n\n/**\n * @param root - Tool input schema.\n * @param pointer - Schema path from a validation error, such as `#/properties/point`.\n * @returns {SchemaNode | undefined} The subschema it points at.\n */\nfunction schemaAt(root: SchemaNode, pointer: string): SchemaNode | undefined {\n let node: unknown = root;\n for (const token of pointer.split(\"/\").slice(1)) {\n const key = unescapeToken(token);\n node = isNode(node) && Object.hasOwn(node, key) ? node[key] : undefined;\n }\n return isNode(node) ? node : undefined;\n}\n\n/**\n * Validates and runs a tool. Every adapter calls through here.\n *\n * Progress is best effort: a line after the call settles goes nowhere, and a host that throws on\n * one doesn't fail the call.\n *\n * @param tool - Tool to run.\n * @param args - Arguments as received from the host.\n * @param context - Per-call context.\n * @returns {Promise<ToolResult>} The executor's result, unchanged.\n * @throws {ToolInputError} When the arguments fail the schema.\n */\nexport async function invokeTool(\n tool: ToolDefinition,\n args: unknown,\n context: ToolCallContext = {},\n): Promise<ToolResult> {\n const checked = validateInput(tool, args);\n if (!checked.ok) throw new ToolInputError(checked.lines);\n const { progress } = context;\n if (!progress) return await tool.execute(checked.value, context);\n\n let settled = false;\n try {\n return await tool.execute(checked.value, {\n ...context,\n progress(message, amount) {\n if (settled) return;\n try {\n progress(sanitizeLine(message), amount);\n } catch {}\n },\n });\n } finally {\n settled = true;\n }\n}\n\nconst LINE_BREAKING = /[\\p{Cc}\\p{Cf}\\p{Zl}\\p{Zp}]/gu;\n\n/**\n * Makes a value safe for one line of terminal or protocol text.\n *\n * Removes escape sequences, then replaces every control, format, line and\n * paragraph separator character with a space: a raw newline, U+2028 or a bidi\n * override (U+202E, a `Cf`) in an echoed value forges a line that reads as the\n * tool's own output. `String()` first, since hostile JSON ignores declared types.\n *\n * @param value - Value to render.\n * @returns {string} Single-line text.\n */\nexport function sanitizeLine(value: unknown): string {\n return stripEscapes(String(value))\n .replaceAll(LINE_BREAKING, \" \")\n .replaceAll(/ {2,}/g, \" \")\n .trim();\n}\n\n/**\n * Text of a result, for hosts that carry failures as thrown errors.\n *\n * @param result - Tool result.\n * @returns {string} Text blocks joined by newlines.\n */\nexport function resultText(result: ToolResult): string {\n return result.content.flatMap((block) => (block.type === \"text\" ? [block.text] : [])).join(\"\\n\");\n}\n"],"mappings":"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"}
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":"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"}
@@ -1,6 +1,7 @@
1
- function hostContext(signal, onUpdate) {
1
+ function hostContext(signal, onUpdate, host) {
2
2
  return {
3
3
  ...signal ? { signal } : {},
4
+ ...host === void 0 ? {} : { host },
4
5
  ...onUpdate ? { progress: (text) => onUpdate({
5
6
  content: [{
6
7
  type: "text",
@@ -1 +1 @@
1
- {"version":3,"file":"updates.mjs","names":[],"sources":["../../src/updates.ts"],"sourcesContent":["/** The call context Pi and OMP share: a signal and an `onUpdate` for partial results. */\n\nimport type { ToolCallContext, ToolContent } from \"./index.ts\";\n\n/** A partial result as `onUpdate` takes it in Pi and OMP. */\nexport interface PartialResult {\n readonly content: ToolContent[];\n readonly details: Readonly<Record<string, never>>;\n}\n\n/**\n * Turns the host's signal and `onUpdate` into a context, one text block per progress line.\n *\n * @param signal - The call's abort signal, if the host passed one.\n * @param onUpdate - The host's partial result callback, if it passed one.\n * @returns {ToolCallContext} Context for `invokeTool`.\n */\nexport function hostContext(\n signal: AbortSignal | undefined,\n onUpdate: ((partial: PartialResult) => void) | undefined,\n): ToolCallContext {\n return {\n ...(signal ? { signal } : {}),\n ...(onUpdate\n ? { progress: (text: string) => onUpdate({ content: [{ type: \"text\", text }], details: {} }) }\n : {}),\n };\n}\n"],"mappings":";;;;;;IAiBA;GAIE,CAAA;GACE,SAAI,CAAA;EACJ,CAAA,EAAI,IAAA,CAAA;CACyC;AAAY;AAAmB,SAAC"}
1
+ {"version":3,"file":"updates.mjs","names":[],"sources":["../../src/updates.ts"],"sourcesContent":["/** The call context Pi and OMP share: a signal, `onUpdate` for partial results and `ctx`. */\n\nimport type { ToolCallContext, ToolContent } from \"./index.ts\";\n\n/** A partial result as `onUpdate` takes it in Pi and OMP. */\nexport interface PartialResult {\n readonly content: ToolContent[];\n readonly details: Readonly<Record<string, never>>;\n}\n\n/**\n * Turns the host's signal, `onUpdate` and `ctx` into a context, one text block per progress line.\n *\n * @param signal - The call's abort signal, if the host passed one.\n * @param onUpdate - The host's partial result callback, if it passed one.\n * @param host - The host's own context of the call, passed through as `host`.\n * @returns {ToolCallContext} Context for `invokeTool`.\n */\nexport function hostContext(\n signal: AbortSignal | undefined,\n onUpdate: ((partial: PartialResult) => void) | undefined,\n host: unknown,\n): ToolCallContext {\n return {\n ...(signal ? { signal } : {}),\n ...(host === undefined ? {} : { host }),\n ...(onUpdate\n ? { progress: (text: string) => onUpdate({ content: [{ type: \"text\", text }], details: {} }) }\n : {}),\n };\n}\n"],"mappings":";;;;;;;IAkBA;GAKE,CAAA;GACE,SAAI,CAAA;EACJ,CAAA,EAAI,IAAA,CAAA;CACJ;AAC6C;AAA0B,SAAA"}
package/dist/ai.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Static, TObject } from "./_chunks/libs/typebox.mjs";
2
- import { ToolDefinition } from "./index.mjs";
2
+ import { ToolDefinition } from "./_chunks/index.mjs";
3
3
  import { Tool } from "ai";
4
4
  /**
5
5
  * What an AI SDK tool returns: the executor's details with the text MCP
package/dist/cli.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { ToolDefinition } from "./index.mjs";
1
+ import { ToolDefinition } from "./_chunks/index.mjs";
2
2
  export interface CliOptions {
3
3
  /** Executable name, also the MCP server name. */
4
4
  readonly name: string;
@@ -8,8 +8,9 @@ export interface CliOptions {
8
8
  /**
9
9
  * The package's own commands, as tool definitions that only the CLI gets:
10
10
  * no MCP, Pi, OMP or AI SDK host sees them. One whose command name matches
11
- * a generated command, `mcp` included, takes its place. A command that
12
- * needs bytes, not text, reads `-` from stdin itself in `execute`.
11
+ * a generated command, `mcp` included, takes its place. Bytes are the
12
+ * command's own business: it reads `-` from stdin itself in `execute`, and
13
+ * writes to stdout itself, answering with no content and `cli.json: false`.
13
14
  */
14
15
  readonly commands?: readonly ToolDefinition[];
15
16
  /** Command for an empty command line. */
@@ -1 +1 @@
1
- {"version":3,"file":"cli.d.mts","names":[],"sources":["../src/cli.ts"],"mappings":";iBA0BiB;;WAEN;WACA;WACA;WACA,gBAAgB;;;;;;;WAOhB,oBAAoB;;WAEpB;;WAEA;;WAEA;;;;;WAKA,YAAY;;;;;;wBA8CP,YAAY,MAAM;;iBA8mBjB;;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":";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"}
package/dist/cli.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { Convert } from "./_chunks/libs/typebox.mjs";
1
+ import { Check } from "./_chunks/libs/typebox.mjs";
2
2
  import { ToolDefinitionError, ToolInputError, indexTools, invokeTool, resultText, sanitizeLine, sanitizeText } from "./_chunks/src.mjs";
3
3
  import { readFileSync } from "node:fs";
4
4
  import { parseArgs } from "node:util";
@@ -8,6 +8,8 @@ const RESERVED_FLAGS = /* @__PURE__ */ new Set([
8
8
  "version",
9
9
  "json"
10
10
  ]);
11
+ const TEXT_KINDS = /* @__PURE__ */ new Set(["string", "enum"]);
12
+ const SHORT_FLAG = /^[a-z]$/i;
11
13
  const TYPE_KINDS = /* @__PURE__ */ new Map([
12
14
  ["boolean", "boolean"],
13
15
  ["integer", "number"],
@@ -34,13 +36,29 @@ function fieldKind(schema) {
34
36
  if ((Array.isArray(schema.anyOf) ? schema.anyOf : []).some((branch) => fieldKind(branch) === "json")) return "json";
35
37
  return TYPE_KINDS.get(schema.type) ?? "string";
36
38
  }
37
- function toolFields(tool) {
39
+ function cliHints(tool) {
40
+ const cli = tool.cli ?? {};
41
+ const rest = cli.rest === void 0 ? [] : [cli.rest];
42
+ const hints = {
43
+ positional: [...cli.positional ?? [], ...rest],
44
+ rest,
45
+ short: cli.short ?? {},
46
+ stdin: cli.stdin ?? []
47
+ };
38
48
  const properties = tool.input.properties;
39
- const positional = tool.cli?.positional ?? [];
40
- const stdin = tool.cli?.stdin ?? [];
41
- for (const key of [...positional, ...stdin]) if (!Object.hasOwn(properties, key)) throw new ToolDefinitionError(`${tool.name}: cli hint names unknown property ${key}`);
49
+ for (const key of [
50
+ ...hints.positional,
51
+ ...Object.keys(hints.short),
52
+ ...hints.stdin
53
+ ]) if (!Object.hasOwn(properties, key)) throw new ToolDefinitionError(`${tool.name}: cli hint names unknown property ${key}`);
54
+ const { positional } = hints;
42
55
  const repeated = positional.find((key, index) => positional.indexOf(key) !== index);
43
56
  if (repeated !== void 0) throw new ToolDefinitionError(`${tool.name}: cli hint lists positional ${repeated} twice`);
57
+ return hints;
58
+ }
59
+ function toolFields(tool) {
60
+ const properties = tool.input.properties;
61
+ const { positional, rest, short, stdin } = cliHints(tool);
44
62
  const keys = [...positional, ...Object.keys(properties).filter((key) => !positional.includes(key))];
45
63
  const required = tool.input.required ?? [];
46
64
  const flags = /* @__PURE__ */ new Set();
@@ -52,9 +70,12 @@ function toolFields(tool) {
52
70
  flag: flagName(key),
53
71
  kind: fieldKind(properties[key] ?? {}),
54
72
  positional: positional.includes(key),
73
+ rest: rest.includes(key),
74
+ short: Object.hasOwn(short, key) ? short[key] : void 0,
55
75
  stdin: stdin.includes(key)
56
76
  };
57
77
  assertField(tool, field, !field.positional && flags.has(field.flag));
78
+ assertShort(tool, field);
58
79
  if (!field.positional) flags.add(field.flag);
59
80
  return field;
60
81
  });
@@ -72,6 +93,13 @@ function assertField(tool, field, taken) {
72
93
  if (taken) throw new ToolDefinitionError(`${tool.name}: two properties take the flag --${field.flag}`);
73
94
  if (field.positional && field.kind === "boolean") throw new ToolDefinitionError(`${tool.name}: boolean property ${field.key} cannot be positional`);
74
95
  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`);
97
+ }
98
+ function assertShort(tool, field) {
99
+ if (field.short === void 0) return;
100
+ if (field.positional) throw new ToolDefinitionError(`${tool.name}: positional property ${field.key} takes no short flag`);
101
+ if (!SHORT_FLAG.test(field.short)) throw new ToolDefinitionError(`${tool.name}: short flag ${JSON.stringify(field.short)} of ${field.key} must match ${SHORT_FLAG}`);
102
+ if (field.short === "h") throw new ToolDefinitionError(`${tool.name}: property ${field.key} takes -h, which asks for help`);
75
103
  }
76
104
  function assertRequiredPositionalsFirst(tool, fields) {
77
105
  const positional = fields.filter((field) => field.positional);
@@ -82,10 +110,15 @@ function assertRequiredPositionalsFirst(tool, fields) {
82
110
  function assertOneOptionPerSpelling(tool, fields) {
83
111
  const owners = /* @__PURE__ */ new Map();
84
112
  for (const field of fields.filter((each) => !each.positional)) {
85
- const negation = field.kind === "boolean" ? [`no-${field.flag}`] : [];
86
- for (const spelling of [field.flag, ...negation]) {
113
+ const negation = field.kind === "boolean" ? [`--no-${field.flag}`] : [];
114
+ const short = field.short === void 0 ? [] : [`-${field.short}`];
115
+ for (const spelling of [
116
+ `--${field.flag}`,
117
+ ...negation,
118
+ ...short
119
+ ]) {
87
120
  const owner = owners.get(spelling);
88
- if (owner !== void 0) throw new ToolDefinitionError(`${tool.name}: properties ${owner} and ${field.key} both answer to --${spelling}`);
121
+ if (owner !== void 0) throw new ToolDefinitionError(`${tool.name}: properties ${owner} and ${field.key} both answer to ${spelling}`);
89
122
  owners.set(spelling, field.key);
90
123
  }
91
124
  }
@@ -102,32 +135,38 @@ function valueHint(field) {
102
135
  if (field.kind === "enum") return field.schema.enum.join("|");
103
136
  return field.kind === "string" ? field.flag : field.kind;
104
137
  }
138
+ function optionSpelling(field) {
139
+ return field.kind === "boolean" ? `--[no-]${field.flag}` : `--${field.flag}=<${valueHint(field)}>`;
140
+ }
105
141
  function emptyRecord() {
106
142
  return Object.create(null);
107
143
  }
108
144
  function parseWords(rawArgs, fields, takesJson) {
109
145
  const entries = [...fields.filter((field) => !field.positional).map((field) => [field.flag, field]), ...takesJson ? [["json", "json"]] : []];
110
146
  const options = Object.fromEntries(entries);
147
+ const { args, origins, texts, refused } = takeDashedText(rawArgs, fields, options);
111
148
  const { tokens } = parseArgs({
112
- args: [...rawArgs],
113
- options: Object.fromEntries(Object.entries(options).map(([flag, field]) => [flag, { type: field === "json" || field.kind === "boolean" ? "boolean" : "string" }])),
149
+ args,
150
+ options: Object.fromEntries(Object.entries(options).map(([flag, field]) => [flag, field === "json" ? { type: "boolean" } : {
151
+ type: field.kind === "boolean" ? "boolean" : "string",
152
+ ...field.short === void 0 ? {} : { short: field.short }
153
+ }])),
114
154
  strict: false,
115
155
  allowPositionals: true,
116
156
  allowNegative: true,
117
157
  tokens: true
118
158
  });
119
159
  const values = emptyRecord();
120
- const errors = [];
121
- const positionals = [];
160
+ const errors = refused.map((word) => unknownOption(options, word));
122
161
  const flags = /* @__PURE__ */ new Set();
123
162
  for (const token of tokens) {
124
- if (token.kind === "positional") positionals.push(token.value);
125
163
  if (token.kind !== "option") continue;
126
- const read = readOption(options, token, rawArgs[token.index] ?? "", Object.keys(values));
164
+ const read = readOption(options, token, args[token.index] ?? "", Object.keys(values));
127
165
  if ("error" in read) errors.push(read.error);
128
166
  else if ("flag" in read) flags.add(read.flag);
129
167
  else values[read.key] = read.value;
130
168
  }
169
+ const positionals = inLineOrder(tokens, origins, texts);
131
170
  return {
132
171
  values: Object.assign(values, positionalValues(fields, positionals)),
133
172
  json: flags.has("json"),
@@ -135,14 +174,75 @@ function parseWords(rawArgs, fields, takesJson) {
135
174
  errors: [...new Set(errors.length > 0 ? errors : extraPositionals(fields, positionals))]
136
175
  };
137
176
  }
177
+ function takeDashedText(rawArgs, fields, options) {
178
+ const { dashed, plain } = scanWords(rawArgs, options);
179
+ const free = fields.filter((field) => field.positional).length - plain;
180
+ const taken = dashed.slice(0, Math.max(free, 0));
181
+ const skipped = new Set(dashed);
182
+ const origins = rawArgs.flatMap((_, index) => skipped.has(index) ? [] : [index]);
183
+ const word = (index) => rawArgs[index] ?? "";
184
+ return {
185
+ args: origins.map(word),
186
+ origins,
187
+ texts: taken.map((index) => [index, word(index)]),
188
+ refused: dashed.slice(taken.length).map(word)
189
+ };
190
+ }
191
+ function scanWords(rawArgs, options) {
192
+ const dashed = [];
193
+ let plain = 0;
194
+ for (let index = 0; index < rawArgs.length; index++) {
195
+ const word = rawArgs[index] ?? "";
196
+ if (word === "--") return {
197
+ dashed,
198
+ plain: plain + rawArgs.length - index - 1
199
+ };
200
+ const kind = wordKind(word, options);
201
+ if (kind === "plain") plain++;
202
+ else if (kind === "text") dashed.push(index);
203
+ else if (kind === "valued") index++;
204
+ }
205
+ return {
206
+ dashed,
207
+ plain
208
+ };
209
+ }
210
+ function wordKind(word, options) {
211
+ if (!word.startsWith("-") || word === "-") return "plain";
212
+ if (word === "-h") return "option";
213
+ const field = word.startsWith("--") ? longField(word.slice(2), options) : shortField(word, options);
214
+ if (field === void 0) return "text";
215
+ if (field === "option" || field.kind === "boolean" || word.includes("=")) return "option";
216
+ return "valued";
217
+ }
218
+ function inLineOrder(tokens, origins, texts) {
219
+ const read = tokens.flatMap((token) => token.kind === "positional" ? [[origins[token.index] ?? 0, token.value ?? ""]] : []);
220
+ return [...texts, ...read].toSorted(([a], [b]) => a - b).map(([, word]) => word);
221
+ }
222
+ function longField(spelled, options) {
223
+ const [name = ""] = spelled.split("=", 1);
224
+ if (name === "help") return "option";
225
+ const field = Object.hasOwn(options, name) ? options[name] : void 0;
226
+ if (field !== void 0) return field === "json" ? "option" : field;
227
+ return negatesBoolean(name, options) ? "option" : void 0;
228
+ }
229
+ function negatesBoolean(name, options) {
230
+ const flag = name.slice(3);
231
+ const field = name.startsWith("no-") && Object.hasOwn(options, flag) ? options[flag] : void 0;
232
+ return field !== void 0 && field !== "json" && field.kind === "boolean";
233
+ }
234
+ function shortField(word, options) {
235
+ return Object.values(options).find((field) => field !== "json" && field.short !== void 0 && `-${field.short}` === word);
236
+ }
138
237
  function positionalValues(fields, positionals) {
139
238
  const takes = fields.filter((field) => field.positional);
140
239
  return Object.assign(emptyRecord(), Object.fromEntries(takes.flatMap((field, index) => {
141
- const value = positionals[index];
142
- return value === void 0 ? [] : [[field.key, value]];
240
+ const words = field.rest ? positionals.slice(index) : positionals.slice(index, index + 1);
241
+ return words.length === 0 ? [] : [[field.key, words.join(" ")]];
143
242
  })));
144
243
  }
145
244
  function extraPositionals(fields, positionals) {
245
+ if (fields.some((field) => field.rest)) return [];
146
246
  const extra = positionals.length - fields.filter((field) => field.positional).length;
147
247
  if (extra <= 0) return [];
148
248
  return [`Invalid arguments: ${extra} unexpected positional argument${extra === 1 ? "" : "s"}`];
@@ -154,20 +254,25 @@ function optionField(options, token, word) {
154
254
  if (asksHelp(token, word)) return "help";
155
255
  const field = Object.hasOwn(options, token.name) ? options[token.name] : void 0;
156
256
  if (field === "json") return token.rawName === "--json" ? field : void 0;
157
- if (field === void 0 || token.rawName === `--${token.name}`) return field;
158
- return token.rawName === `--no-${token.name}` && field.kind === "boolean" ? field : void 0;
257
+ return field !== void 0 && spells(field, token, word) ? field : void 0;
258
+ }
259
+ function spells(field, token, word) {
260
+ if (token.rawName === `--${field.flag}`) return true;
261
+ if (field.short !== void 0 && token.rawName === `-${field.short}`) return word === token.rawName;
262
+ return field.kind === "boolean" && token.rawName === `--no-${field.flag}`;
263
+ }
264
+ function unknownOption(options, word) {
265
+ const flags = Object.entries(options).map(([flag, each]) => each === "json" || each.short === void 0 ? `--${flag}` : `--${flag} (-${each.short})`);
266
+ const takes = flags.length > 0 ? flags.join(", ") : "no options";
267
+ return `Invalid arguments: unknown option ${JSON.stringify(word)}; takes ${takes}`;
159
268
  }
160
269
  function readOption(options, token, word, seen) {
161
270
  const field = optionField(options, token, word);
162
- if (field === void 0) {
163
- const flags = Object.keys(options).map((flag) => `--${flag}`);
164
- const takes = flags.length > 0 ? flags.join(", ") : "no options";
165
- return { error: `Invalid arguments: unknown option ${JSON.stringify(word)}; takes ${takes}` };
166
- }
271
+ if (field === void 0) return { error: unknownOption(options, word) };
167
272
  if (field === "json" || field === "help") return token.inlineValue === true ? { error: `Invalid arguments: ${token.rawName} takes no value` } : { flag: field };
168
273
  const problem = optionProblem(field, token, seen.includes(field.key));
169
274
  if (problem !== void 0) return { error: `Invalid arguments: --${field.flag} ${problem}` };
170
- const value = field.kind === "boolean" ? token.rawName === `--${field.flag}` : token.value;
275
+ const value = field.kind === "boolean" ? token.rawName !== `--no-${field.flag}` : token.value;
171
276
  return {
172
277
  key: field.key,
173
278
  value: value ?? ""
@@ -189,19 +294,65 @@ function readStdin() {
189
294
  throw error;
190
295
  }
191
296
  }
297
+ const DECIMAL_INTEGER = /^[+-]?\d+$/;
298
+ const DECIMAL_NUMBER = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i;
299
+ function numberValue(integer, word) {
300
+ const value = Number(word);
301
+ if ((integer ? DECIMAL_INTEGER : DECIMAL_NUMBER).test(word) && Number.isFinite(value)) return { value };
302
+ return { error: integer ? "must be integer" : "must be number" };
303
+ }
304
+ const LITERAL_TYPES = /* @__PURE__ */ new Set([
305
+ "string",
306
+ "number",
307
+ "boolean"
308
+ ]);
309
+ const TYPE_LITERALS = /* @__PURE__ */ new Map([["null", [null]], ["boolean", [true, false]]]);
310
+ function literalValue(values, word) {
311
+ const spelled = (item) => (item === null || LITERAL_TYPES.has(typeof item)) && String(item) === word;
312
+ return values.some(spelled) ? { value: values.find(spelled) } : void 0;
313
+ }
314
+ function branchValue(branch, word) {
315
+ if (Object.hasOwn(branch, "const")) return literalValue([branch.const], word);
316
+ if (Array.isArray(branch.enum)) return literalValue(branch.enum, word);
317
+ const literals = TYPE_LITERALS.get(branch.type);
318
+ if (literals !== void 0) return literalValue(literals, word);
319
+ if (TYPE_KINDS.get(branch.type) !== "number") return void 0;
320
+ const read = numberValue(branch.type === "integer", word);
321
+ return "value" in read ? read : void 0;
322
+ }
323
+ function unionBranches(schema) {
324
+ const union = schema.anyOf ?? schema.oneOf ?? schema.allOf;
325
+ if (Array.isArray(union)) return union.flatMap(unionBranches);
326
+ if (!Array.isArray(schema.type)) return [schema];
327
+ return schema.type.map((type) => ({
328
+ ...schema,
329
+ type
330
+ }));
331
+ }
332
+ function wordValue(schema, word) {
333
+ const readings = [word, ...unionBranches(schema).flatMap((branch) => {
334
+ const read = branchValue(branch, word);
335
+ return read === void 0 ? [] : [read.value];
336
+ })];
337
+ const index = readings.findIndex((value) => Check(schema, value));
338
+ return index === -1 ? word : readings[index];
339
+ }
192
340
  function fieldValue(field, raw) {
193
341
  if (field.stdin && raw === "-") {
194
342
  const text = readStdin();
195
343
  return text === void 0 ? { error: "stdin is not UTF-8 text" } : { value: text };
196
344
  }
197
- if (field.kind !== "json" || typeof raw !== "string") return { value: raw };
345
+ if (typeof raw !== "string") return { value: raw };
346
+ if (field.kind === "number") return numberValue(field.schema.type === "integer", raw);
347
+ if (field.kind === "string") return { value: wordValue(field.schema, raw) };
348
+ if (field.kind !== "json") return { value: raw };
198
349
  try {
199
350
  return { value: JSON.parse(raw) };
200
351
  } catch {
201
352
  return { error: "must be JSON" };
202
353
  }
203
354
  }
204
- function toolInput(tool, fields, values) {
355
+ function toolInput(fields, values) {
205
356
  const input = emptyRecord();
206
357
  const fromStdin = fields.filter((field) => field.stdin && values[field.key] === "-");
207
358
  if (fromStdin.length > 1) throw new ToolInputError([`Invalid arguments: stdin can feed one argument, not ${fromStdin.map((field) => field.key).join(" and ")}`]);
@@ -214,7 +365,7 @@ function toolInput(tool, fields, values) {
214
365
  else input[field.key] = read.value;
215
366
  }
216
367
  if (errors.length > 0) throw new ToolInputError(errors);
217
- return Convert(tool.input, input);
368
+ return input;
218
369
  }
219
370
  function writeLine(stream, text) {
220
371
  process[stream].write(text.endsWith("\n") ? text : `${text}\n`);
@@ -240,14 +391,14 @@ function toolCommand(tool) {
240
391
  aliases: (tool.cli?.aliases ?? []).map((alias) => commandWord(tool.name, alias)),
241
392
  summary: tool.cli?.description ?? summary,
242
393
  fields,
243
- json: true,
394
+ json: tool.cli?.json !== false,
244
395
  async run(words) {
245
- const result = await invokeTool(tool, toolInput(tool, fields, words.values));
396
+ const result = await invokeTool(tool, toolInput(fields, words.values));
246
397
  if (result.isError === true) {
247
398
  writeLine("stderr", sanitizeText(resultText(result)));
248
399
  process.exitCode = 1;
249
400
  } else if (words.json) writeLine("stdout", detailsJson(result.details));
250
- else {
401
+ else if (result.content.length > 0) {
251
402
  writeLine("stdout", sanitizeText(resultText(result)));
252
403
  const images = result.content.filter((block) => block.type === "image").length;
253
404
  if (images > 0) writeLine("stderr", `(${images} image block(s) not printed)`);
@@ -346,11 +497,11 @@ function commandUsage(options, command) {
346
497
  const flags = command.fields.filter((field) => !field.positional);
347
498
  const takesOptions = flags.length > 0 || command.json;
348
499
  const words = positional.map((field) => {
349
- const name = field.flag.toUpperCase();
500
+ const name = `${field.flag.toUpperCase()}${field.rest ? "..." : ""}`;
350
501
  return field.required ? `<${name}>` : `[${name}]`;
351
502
  });
352
503
  const rows = [
353
- ...flags.map((field) => [field.kind === "boolean" ? `--[no-]${field.flag}` : `--${field.flag}=<${valueHint(field)}>`, fieldDescription(field)]),
504
+ ...flags.map((field) => [`${field.short === void 0 ? "" : `-${field.short}, `}${optionSpelling(field)}`, fieldDescription(field)]),
354
505
  ...command.json ? [["--json", "Print the details as JSON instead of the text"]] : [],
355
506
  ["-h, --help", "Show this help"]
356
507
  ];