@agntn/tools 0.2.0 → 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/dist/mcp.d.mts CHANGED
@@ -1,52 +1,6 @@
1
- import { ToolCallContext, ToolDefinition } from "./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
- /** Project home a client can link to. */
10
- readonly websiteUrl?: string;
11
- }
12
- /**
13
- * Maps a tool's title and declared effect to MCP annotations. Claude Code reads its label here.
14
- *
15
- * @param tool - Tool to describe.
16
- * @returns {ToolAnnotations} Title and hints for the MCP client.
17
- */
18
- export declare function toolAnnotations(tool: ToolDefinition): ToolAnnotations;
19
- /**
20
- * Error result with every line-forging character replaced.
21
- *
22
- * The messages echo client-controlled values (a tool name, an argument) and
23
- * downstream error text, so they pass through here on every branch. Each line
24
- * is cleaned on its own, so only the breaks between the lines passed in
25
- * survive; a newline inside one line becomes a space.
26
- *
27
- * @param lines - Error lines.
28
- * @returns {CallToolResult} MCP error result.
29
- */
30
- export declare function errorResult(...lines: readonly string[]): CallToolResult;
31
- /**
32
- * The entries `tools/list` answers with, in the order given.
33
- *
34
- * @param tools - Tools to list.
35
- * @returns {Tool[]} Name, title, description, schema and annotations of each tool.
36
- * @throws {ToolDefinitionError} When two tools share a name.
37
- */
38
- export declare function listTools(tools: readonly ToolDefinition[]): Tool[];
39
- /**
40
- * Answers one call as `tools/call` does and never throws, so every transport gives the same text.
41
- *
42
- * @param info - Server info; `name` is the word in the message for an unknown tool.
43
- * @param tools - Tools to look the name up in.
44
- * @param name - Tool name as the client sent it.
45
- * @param args - Arguments as the client sent them; missing ones count as `{}`.
46
- * @param context - Context for this call, such as the request's abort signal.
47
- * @returns {Promise<CallToolResult>} The tool's text, or the sanitized error.
48
- */
49
- export declare function callTool(info: Pick<McpServerInfo, "name">, tools: readonly ToolDefinition[], name: string, args?: unknown, context?: ToolCallContext): Promise<CallToolResult>;
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";
50
4
  /**
51
5
  * Creates an unconnected MCP server exposing the tools.
52
6
  *
@@ -63,11 +17,11 @@ export declare function callTool(info: Pick<McpServerInfo, "name">, tools: reado
63
17
  *
64
18
  * A progress notification that fails to send goes to `onerror`, never to the tool.
65
19
  *
66
- * @param info - Server name, version and optional title and website, sent to the client as given.
20
+ * @param info - Name, version and optional title, description, icons and website, sent as given.
67
21
  * @param tools - Tools to serve.
68
22
  * @returns {Server} Unconnected MCP server.
69
23
  * @throws {ToolDefinitionError} When two tools share a name.
70
24
  */
71
25
  export declare function createMcpServer(info: McpServerInfo, tools: readonly ToolDefinition[]): Server;
72
- export type { McpServerInfo };
26
+ export { type McpServerInfo, callTool, errorResult, listTools, toolAnnotations };
73
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":";;UAmBiB;;WAEN;WACA;;WAEA;;WAEA;;;;;;;;wBASK,gBAAgB,MAAM,iBAAiB;;;;;;;;;;;;wBAqBvC,eAAe,2BAA2B;;;;;;;;wBAW1C,UAAU,gBAAgB,mBAAmB;;;;;;;;;;;wBAqBvC,SACpB,MAAM,KAAK,wBACX,gBAAgB,kBAChB,cACA,gBACA,UAAS,kBACR,QAAQ;;;;;;;;;;;;;;;;;;;;;;wBClDK,gBAAgB,MAAM,eAAe,gBAAgB,mBAAmB"}
1
+ {"version":3,"file":"mcp.d.mts","names":[],"sources":["../src/mcp.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;wBA6CgB,gBAAgB,MAAM,eAAe,gBAAgB,mBAAmB"}
package/dist/mcp.mjs CHANGED
@@ -1,13 +1,15 @@
1
1
  import { indexTools } from "./_chunks/src.mjs";
2
- import { callTool, errorResult, listTools, progressSteps, toolAnnotations } from "./_chunks/mcp-answers.mjs";
2
+ import { callTool, copyIcons, errorResult, listTools, progressSteps, toolAnnotations } from "./_chunks/mcp-answers.mjs";
3
3
  import { Server } from "@modelcontextprotocol/server";
4
4
  function createMcpServer(info, tools) {
5
5
  indexTools(tools);
6
- const { name, version, title, websiteUrl } = info;
6
+ const { name, version, title, description, icons, websiteUrl } = info;
7
7
  const server = new Server({
8
8
  name,
9
9
  version,
10
10
  title,
11
+ description,
12
+ ...icons === void 0 ? {} : { icons: copyIcons(icons) },
11
13
  websiteUrl
12
14
  }, { capabilities: { tools: {} } });
13
15
  server.setRequestHandler("tools/list", () => ({ tools: listTools(tools) }));
package/dist/mcp.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"mcp.mjs","names":[],"sources":["../src/mcp.ts"],"sourcesContent":["/**\n * MCP adapter: serves {@link ToolDefinition}s from an unconnected MCP server.\n */\n\nimport { Server } from \"@modelcontextprotocol/server\";\n\nimport { indexTools, type ToolDefinition } from \"./index.ts\";\nimport {\n callTool,\n listTools,\n progressSteps,\n type McpServerInfo,\n type ProgressParams,\n} from \"./mcp-answers.ts\";\n\nexport {\n callTool,\n errorResult,\n listTools,\n toolAnnotations,\n type McpServerInfo,\n} from \"./mcp-answers.ts\";\n\n/**\n * Creates an unconnected MCP server exposing the tools.\n *\n * Built on the low-level `Server` of MCP SDK v2, which the SDK marks\n * `@deprecated`, not on `McpServer`. `McpServer.registerTool` in 2.2.0 would\n * take the schema, but it answers `toString`, `constructor` and `__proto__` as\n * \"Tool toString disabled\" (a lookup that reaches `Object.prototype`), echoes a\n * raw tool name with newlines and escapes into its error, joins validation\n * failures into one line and passes a thrown message through unsanitized.\n *\n * `details` never reaches the client and `structuredContent` is never set:\n * clients that see structured output prefer it over `content` and would hide\n * the readable answer. Every fact a follow-up call needs belongs in the text.\n *\n * A progress notification that fails to send goes to `onerror`, never to the tool.\n *\n * @param info - Server name, version and optional title and website, sent to the client as given.\n * @param tools - Tools to serve.\n * @returns {Server} Unconnected MCP server.\n * @throws {ToolDefinitionError} When two tools share a name.\n */\nexport function createMcpServer(info: McpServerInfo, tools: readonly ToolDefinition[]): Server {\n indexTools(tools);\n const { name, version, title, websiteUrl } = info;\n const server = new Server({ name, version, title, websiteUrl }, { capabilities: { tools: {} } });\n\n server.setRequestHandler(\"tools/list\", () => ({ tools: listTools(tools) }));\n server.setRequestHandler(\"tools/call\", (request, ctx) => {\n const progressToken = ctx.mcpReq._meta?.progressToken;\n const notify = (params: ProgressParams): void => {\n ctx.mcpReq\n .notify({ method: \"notifications/progress\", params: { progressToken, ...params } })\n .catch((error: unknown) => {\n server.onerror?.(error instanceof Error ? error : new Error(String(error)));\n });\n };\n return callTool(info, tools, request.params.name, request.params.arguments, {\n signal: ctx.mcpReq.signal,\n ...(progressToken === undefined ? {} : { progress: progressSteps(notify) }),\n });\n });\n\n return server;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;EA4CA;EACE,OAAA,SAAgB,MAAA,OAAA,QAAA,OAAA,MAAA,QAAA,OAAA,WAAA;GAChB,QAAQ,IAAM,OAAA;GACd,GAAA,kBAAmB,KAAO,IAAA,CAAA,IAAA,EAAA,UAAA,cAAA,MAAA,EAAA;EAAE,CAAA;CAAM,CAAA;CAAS,OAAA;AAAO;AAElD,SAAO,UAAA,iBAAkB,aAAuB,WAAO"}
1
+ {"version":3,"file":"mcp.mjs","names":[],"sources":["../src/mcp.ts"],"sourcesContent":["/**\n * MCP adapter: serves {@link ToolDefinition}s from an unconnected MCP server.\n */\n\nimport { Server } from \"@modelcontextprotocol/server\";\n\nimport { indexTools, type ToolDefinition } from \"./index.ts\";\nimport {\n callTool,\n copyIcons,\n listTools,\n progressSteps,\n type McpServerInfo,\n type ProgressParams,\n} from \"./mcp-answers.ts\";\n\nexport {\n callTool,\n errorResult,\n listTools,\n toolAnnotations,\n type McpServerInfo,\n} from \"./mcp-answers.ts\";\n\n/**\n * Creates an unconnected MCP server exposing the tools.\n *\n * Built on the low-level `Server` of MCP SDK v2, which the SDK marks\n * `@deprecated`, not on `McpServer`. `McpServer.registerTool` in 2.2.0 would\n * take the schema, but it answers `toString`, `constructor` and `__proto__` as\n * \"Tool toString disabled\" (a lookup that reaches `Object.prototype`), echoes a\n * raw tool name with newlines and escapes into its error, joins validation\n * failures into one line and passes a thrown message through unsanitized.\n *\n * `details` never reaches the client and `structuredContent` is never set:\n * clients that see structured output prefer it over `content` and would hide\n * the readable answer. Every fact a follow-up call needs belongs in the text.\n *\n * A progress notification that fails to send goes to `onerror`, never to the tool.\n *\n * @param info - Name, version and optional title, description, icons and website, sent as given.\n * @param tools - Tools to serve.\n * @returns {Server} Unconnected MCP server.\n * @throws {ToolDefinitionError} When two tools share a name.\n */\nexport function createMcpServer(info: McpServerInfo, tools: readonly ToolDefinition[]): Server {\n indexTools(tools);\n const { name, version, title, description, icons, websiteUrl } = info;\n const server = new Server(\n {\n name,\n version,\n title,\n description,\n ...(icons === undefined ? {} : { icons: copyIcons(icons) }),\n websiteUrl,\n },\n { capabilities: { tools: {} } },\n );\n\n server.setRequestHandler(\"tools/list\", () => ({ tools: listTools(tools) }));\n server.setRequestHandler(\"tools/call\", (request, ctx) => {\n const progressToken = ctx.mcpReq._meta?.progressToken;\n const notify = (params: ProgressParams): void => {\n ctx.mcpReq\n .notify({ method: \"notifications/progress\", params: { progressToken, ...params } })\n .catch((error: unknown) => {\n server.onerror?.(error instanceof Error ? error : new Error(String(error)));\n });\n };\n return callTool(info, tools, request.params.name, request.params.arguments, {\n signal: ctx.mcpReq.signal,\n ...(progressToken === undefined ? {} : { progress: progressSteps(notify) }),\n });\n });\n\n return server;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;IA6CA,OAAgB,UAAA,iBAA+E,QAAA,QAAA,IAAA,MAAA,OAAA,KAAA,CAAA,CAAA;GAC7F,CAAA;EACA;EACA,OAAM,SAAS,MAAI,OACjB,QAAA,OAAA,MAAA,QAAA,OAAA,WAAA;GACE,QAAA,IAAA,OAAA;GACA,GAAA,kBAAA,KAAA,IAAA,CAAA,IAAA,EAAA,UAAA,cAAA,MAAA,EAAA;EACA,CAAA;CACA,CAAA;CACA,OAAI;AACJ;AAKJ,SAAO,UAAA,iBAAkB,aAAuB,WAAO"}
package/dist/omp.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { ToolDefinition as ToolDefinition$1 } from "./index.mjs";
1
+ import { ToolDefinition as ToolDefinition$1 } from "./_chunks/index.mjs";
2
2
  import { ExtensionAPI, Text, ToolDefinition } from "@oh-my-pi/pi-coding-agent";
3
3
  type TextComponent = typeof Text;
4
4
  /** The part of a host result a renderer reads. */
@@ -10,6 +10,8 @@ export interface OmpResultView {
10
10
  export interface OmpRenderers {
11
11
  /** One-line summary of the arguments after the title. Sanitized by the adapter. */
12
12
  describeCall?(args: Readonly<Record<string, unknown>>): unknown;
13
+ /** Replaces the whole call line, `describeCall` included. It owns sanitizing what it draws. */
14
+ renderCall?: ToolDefinition["renderCall"];
13
15
  /** Short metadata after the badge, one entry per fact. Each entry is sanitized. */
14
16
  describeResult?(result: OmpResultView): readonly unknown[];
15
17
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"omp.d.mts","names":["HostText","OmpToolDefinition","ToolDefinition"],"sources":["../src/omp.ts"],"mappings":";;KA2BK,uBAAuBA;;iBAIX;WACN;WACA;;;iBAIM;;EAEf,cAAc,MAAM,SAAS;;EAE7B,gBAAgB,QAAQ;;;;;EAKxB,eAAeC;;iBAGA;;WAEN,MAAM;;WAEN,WAAWA;;WAEX,YAAY,SAAS,eAAe;;;;;;;;;;;;;;;wBAuB/B,iBACd,IAAI,cACJ,gBAAgBC,oBAChB,SAAS"}
1
+ {"version":3,"file":"omp.d.mts","names":["HostText","OmpToolDefinition","ToolDefinition"],"sources":["../src/omp.ts"],"mappings":";;KA2BK,uBAAuBA;;iBAIX;WACN;WACA;;;iBAIM;;EAEf,cAAc,MAAM,SAAS;;EAE7B,aAAaC;;EAEb,gBAAgB,QAAQ;;;;;EAKxB,eAAeA;;iBAGA;;WAEN,MAAM;;WAEN,WAAWA;;WAEX,YAAY,SAAS,eAAe;;;;;;;;;;;;;;;wBAuB/B,iBACd,IAAI,cACJ,gBAAgBC,oBAChB,SAAS"}
package/dist/omp.mjs CHANGED
@@ -18,10 +18,11 @@ function registerOmpTools(pi, tools, options) {
18
18
  parameters: Type.Unsafe(wireSchema(tool)),
19
19
  approval: APPROVAL[tool.effect],
20
20
  loadMode: options.loadMode,
21
- async execute(_toolCallId, params, signal, onUpdate) {
22
- return await invokeTool(tool, params, hostContext(signal, onUpdate));
21
+ async execute(_toolCallId, params, signal, onUpdate, ctx) {
22
+ return await invokeTool(tool, params, hostContext(signal, onUpdate, ctx));
23
23
  },
24
24
  renderCall(args, renderOptions, theme) {
25
+ if (renderers?.renderCall) return renderers.renderCall(args, renderOptions, theme);
25
26
  const summary = renderers?.describeCall ? sanitizeLine(renderers.describeCall(args)) : "";
26
27
  const title = theme.fg("accent", sanitizeLine(tool.title));
27
28
  return new Text(`${callIcon(renderOptions, theme)} ${title}${summary ? `: ${theme.fg("muted", summary)}` : ""}`, 0, 0);
package/dist/omp.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"omp.mjs","names":[],"sources":["../src/omp.ts"],"sourcesContent":["/**\n * OMP adapter: registers {@link ToolDefinition}s on an OMP `ExtensionAPI`.\n *\n * Only types come from `@oh-my-pi/pi-coding-agent`. Compiled OMP injects the\n * package root into the extension file itself, not into its dependencies, so\n * the extension passes the host `Text` component in.\n */\n\nimport type {\n AgentToolResult,\n ExtensionAPI,\n Text as HostText,\n Theme,\n ToolDefinition as OmpToolDefinition,\n ToolRenderResultOptions,\n} from \"@oh-my-pi/pi-coding-agent\";\n\nimport {\n indexTools,\n invokeTool,\n sanitizeLine,\n wireSchema,\n type ToolDefinition,\n type ToolEffect,\n} from \"./index.ts\";\nimport { hostContext } from \"./updates.ts\";\n\ntype TextComponent = typeof HostText;\ntype Component = ReturnType<NonNullable<OmpToolDefinition[\"renderCall\"]>>;\n\n/** The part of a host result a renderer reads. */\nexport interface OmpResultView {\n readonly details?: unknown;\n readonly isError?: boolean;\n}\n\n/** Per-tool renderer overrides, drawn with the host theme. */\nexport interface OmpRenderers {\n /** One-line summary of the arguments after the title. Sanitized by the adapter. */\n describeCall?(args: Readonly<Record<string, unknown>>): unknown;\n /** Short metadata after the badge, one entry per fact. Each entry is sanitized. */\n describeResult?(result: OmpResultView): readonly unknown[];\n /**\n * Replaces the result status line with the package's own component, such as\n * a bounded preview of long output. It owns sanitizing what it draws.\n */\n renderResult?: OmpToolDefinition[\"renderResult\"];\n}\n\nexport interface OmpToolOptions {\n /** The host `Text` component, imported by the extension from the package root. */\n readonly Text: TextComponent;\n /** `\"essential\"` keeps every tool in OMP's top-level list. Left out, OMP hides them behind discovery. */\n readonly loadMode?: OmpToolDefinition[\"loadMode\"];\n /** Status-line renderers by tool name. */\n readonly renderers?: Readonly<Record<string, OmpRenderers>>;\n}\n\nconst APPROVAL: Record<ToolEffect, \"read\" | \"write\"> = {\n read: \"read\",\n write: \"write\",\n // OMP has no destructive tier; `exec` means running commands.\n destructive: \"write\",\n};\n\n/**\n * Registers every tool on the OMP extension API.\n *\n * The schema reaches OMP through `pi.typebox.Type.Unsafe`: the host-injected\n * build validates the raw JSON Schema with its full validator and emits the\n * document verbatim, so `pattern` and `maxProperties` survive. A standalone\n * omptype schema would drop both.\n *\n * @param pi - OMP extension API.\n * @param tools - Tools to register.\n * @param options - Host `Text`, optional load mode and renderers.\n * @throws {ToolDefinitionError} When two tools share a name.\n */\nexport function registerOmpTools(\n pi: ExtensionAPI,\n tools: readonly ToolDefinition[],\n options: OmpToolOptions,\n): void {\n indexTools(tools);\n const { Type } = pi.typebox;\n const { Text } = options;\n\n for (const tool of tools) {\n const renderers = Object.hasOwn(options.renderers ?? {}, tool.name)\n ? options.renderers?.[tool.name]\n : undefined;\n\n pi.registerTool({\n name: tool.name,\n label: tool.title,\n description: tool.description,\n parameters: Type.Unsafe<Record<string, unknown>>(wireSchema(tool)),\n approval: APPROVAL[tool.effect],\n loadMode: options.loadMode,\n async execute(_toolCallId, params, signal, onUpdate): Promise<AgentToolResult<unknown>> {\n // Returned as is: OMP reads `isError` from the object (`explicitError`).\n return await invokeTool(tool, params, hostContext(signal, onUpdate));\n },\n renderCall(args, renderOptions, theme): Component {\n const summary = renderers?.describeCall ? sanitizeLine(renderers.describeCall(args)) : \"\";\n const title = theme.fg(\"accent\", sanitizeLine(tool.title));\n return new Text(\n `${callIcon(renderOptions, theme)} ${title}${summary ? `: ${theme.fg(\"muted\", summary)}` : \"\"}`,\n 0,\n 0,\n );\n },\n renderResult(result, renderOptions, theme, args): Component {\n if (renderers?.renderResult)\n return renderers.renderResult(result, renderOptions, theme, args);\n if (renderOptions.isPartial)\n return new Text(progressLine(tool, result, renderOptions, theme), 0, 0);\n const icon = result.isError\n ? theme.styledSymbol(\"status.error\", \"error\")\n : theme.styledSymbol(\"status.done\", \"success\");\n const { bracketLeft, bracketRight } = theme.format;\n const badge = theme.fg(\"accent\", `${bracketLeft}${APPROVAL[tool.effect]}${bracketRight}`);\n const facts = result.isError ? [] : (renderers?.describeResult?.(result) ?? []);\n return new Text(\n `${icon} ${theme.fg(\"accent\", sanitizeLine(tool.title))} ${badge}${dimFacts(facts, theme)}`,\n 0,\n 0,\n );\n },\n });\n }\n}\n\n/**\n * Status line while the call runs: the spinner, the title and its last progress line.\n *\n * @param tool - Tool being called.\n * @param result - Partial result from `onUpdate`.\n * @param options - Render options from the host.\n * @param theme - Host theme.\n * @returns {string} The styled line.\n */\nfunction progressLine(\n tool: ToolDefinition,\n result: Readonly<{ content: readonly Readonly<{ type: string; text?: string }>[] }>,\n options: ToolRenderResultOptions,\n theme: Theme,\n): string {\n const message = sanitizeLine(\n result.content.findLast((block) => block.type === \"text\")?.text ?? \"\",\n );\n const title = theme.fg(\"accent\", sanitizeLine(tool.title));\n return `${callIcon(options, theme)} ${title}${message ? ` ${theme.fg(\"dim\", message)}` : \"\"}`;\n}\n\n/**\n * The `describeResult` facts after the badge, sanitized and dimmed; empty ones drop out.\n *\n * @param facts - Facts as the renderer gave them.\n * @param theme - Host theme.\n * @returns {string} The facts with a leading space, or nothing.\n */\nfunction dimFacts(facts: readonly unknown[], theme: Theme): string {\n const shown = facts.map(sanitizeLine).filter(Boolean);\n return shown.length > 0 ? ` ${theme.fg(\"dim\", shown.join(theme.sep.dot))}` : \"\";\n}\n\n/**\n * Status icon for a call: pending, spinning or done.\n *\n * Drawn with the host theme on purpose: compiled OMP injects only the package\n * root, so importing `@oh-my-pi/pi-coding-agent/tui` would stop the extension.\n *\n * @param options - Render options from the host.\n * @param theme - Host theme.\n * @returns {string} The styled icon.\n */\nfunction callIcon(options: ToolRenderResultOptions, theme: Theme): string {\n if (!options.isPartial) return theme.styledSymbol(\"status.done\", \"success\");\n if (options.spinnerFrame === undefined) return theme.styledSymbol(\"status.pending\", \"muted\");\n return (\n theme.spinnerFrames[options.spinnerFrame % theme.spinnerFrames.length] ??\n theme.styledSymbol(\"status.running\", \"accent\")\n );\n}\n"],"mappings":";;AA0DA,MAAM,WAAiD;CACrD,MAAM;CACN,OAAO;CAEP,aAAa;AACf;;;;;;;;;;;;;GAeA,UAAgB,QAAA;GAKd,MAAA,QAAgB,aAAA,QAAA,QAAA,UAAA;IAChB,OAAQ,MAAA,WAAY,MAAA,QAAA,YAAA,QAAA,QAAA,CAAA;GACpB;GAEA,WAAW,MAAQ,eAAO,OAAA;IACxB,MAAM,UAAY,WAAO,eAAe,aAAiB,UAAS,aACtD,IAAA,CAAA,IAAA;IAGZ,MAAG,QAAa,MAAA,GAAA,UAAA,aAAA,KAAA,KAAA,CAAA;IACd,OAAM,IAAK,KAAA,GAAA,SAAA,eAAA,KAAA,EAAA,GAAA,QAAA,UAAA,KAAA,MAAA,GAAA,SAAA,OAAA,MAAA,MAAA,GAAA,CAAA;GACX;GACA,aAAa,QAAK,eAAA,OAAA,MAAA;IAClB,IAAA,WAAY,cAAqC,OAAW,UAAK,aAAA,QAAA,eAAA,OAAA,IAAA;IACjE,IAAA,cAAmB,WAAK,OAAA,IAAA,KAAA,aAAA,MAAA,QAAA,eAAA,KAAA,GAAA,GAAA,CAAA;IACxB,MAAA,OAAU,OAAQ,UAAA,MAAA,aAAA,gBAAA,OAAA,IAAA,MAAA,aAAA,eAAA,SAAA;IAClB,MAAM,EAAA,aAAQ,iBAAqB,MAAQ;IAEzC,MAAA,QAAa,MAAA,GAAA,UAAiB,GAAA,cAAoB,SAAQ,KAAA,UAAS,cAAA;IACrE,MAAA,QAAA,OAAA,UAAA,CAAA,IAAA,WAAA,iBAAA,MAAA,KAAA,CAAA;IACA,OAAA,IAAW,KAAM,GAAA,KAAA,GAAA,MAAe,GAAA,UAAkB,aAAA,KAAA,KAAA,CAAA,EAAA,GAAA,QAAA,SAAA,OAAA,KAAA,KAAA,GAAA,CAAA;GAChD;EACA,CAAA;CACA;AAKF;AAEE,SAAI,aAAW,MAAA,QACb,SAAO,OAAU;CACnB,MAAA,UAAI,aAAc,OAChB,QAAW,UAAK,UAAa,MAAM,SAAQ,MAAA,CAAA,EAAA,QAAoB,EAAG;CACpE,MAAA,QAAM,MAAO,GAAO,UAChB,aAAM,KAAA,KAAa,CAAA;CAEvB,OAAA,GAAM,SAAE,SAAa,KAAA,EAAA,GAAA,QAAiB,UAAM,IAAA,MAAA,GAAA,OAAA,OAAA,MAAA;AAC5C;AAEA,SAAA,SAAW,OACN,OAAQ;CAIf,MAAA,QAAA,MAAA,IAAA,YAAA,CAAA,CAAA,OAAA,OAAA;CACF,OAAC,MAAA,SAAA,IAAA,IAAA,MAAA,GAAA,OAAA,MAAA,KAAA,MAAA,IAAA,GAAA,CAAA,MAAA;AACH"}
1
+ {"version":3,"file":"omp.mjs","names":[],"sources":["../src/omp.ts"],"sourcesContent":["/**\n * OMP adapter: registers {@link ToolDefinition}s on an OMP `ExtensionAPI`.\n *\n * Only types come from `@oh-my-pi/pi-coding-agent`. Compiled OMP injects the\n * package root into the extension file itself, not into its dependencies, so\n * the extension passes the host `Text` component in.\n */\n\nimport type {\n AgentToolResult,\n ExtensionAPI,\n Text as HostText,\n Theme,\n ToolDefinition as OmpToolDefinition,\n ToolRenderResultOptions,\n} from \"@oh-my-pi/pi-coding-agent\";\n\nimport {\n indexTools,\n invokeTool,\n sanitizeLine,\n wireSchema,\n type ToolDefinition,\n type ToolEffect,\n} from \"./index.ts\";\nimport { hostContext } from \"./updates.ts\";\n\ntype TextComponent = typeof HostText;\ntype Component = ReturnType<NonNullable<OmpToolDefinition[\"renderCall\"]>>;\n\n/** The part of a host result a renderer reads. */\nexport interface OmpResultView {\n readonly details?: unknown;\n readonly isError?: boolean;\n}\n\n/** Per-tool renderer overrides, drawn with the host theme. */\nexport interface OmpRenderers {\n /** One-line summary of the arguments after the title. Sanitized by the adapter. */\n describeCall?(args: Readonly<Record<string, unknown>>): unknown;\n /** Replaces the whole call line, `describeCall` included. It owns sanitizing what it draws. */\n renderCall?: OmpToolDefinition[\"renderCall\"];\n /** Short metadata after the badge, one entry per fact. Each entry is sanitized. */\n describeResult?(result: OmpResultView): readonly unknown[];\n /**\n * Replaces the result status line with the package's own component, such as\n * a bounded preview of long output. It owns sanitizing what it draws.\n */\n renderResult?: OmpToolDefinition[\"renderResult\"];\n}\n\nexport interface OmpToolOptions {\n /** The host `Text` component, imported by the extension from the package root. */\n readonly Text: TextComponent;\n /** `\"essential\"` keeps every tool in OMP's top-level list. Left out, OMP hides them behind discovery. */\n readonly loadMode?: OmpToolDefinition[\"loadMode\"];\n /** Status-line renderers by tool name. */\n readonly renderers?: Readonly<Record<string, OmpRenderers>>;\n}\n\nconst APPROVAL: Record<ToolEffect, \"read\" | \"write\"> = {\n read: \"read\",\n write: \"write\",\n // OMP has no destructive tier; `exec` means running commands.\n destructive: \"write\",\n};\n\n/**\n * Registers every tool on the OMP extension API.\n *\n * The schema reaches OMP through `pi.typebox.Type.Unsafe`: the host-injected\n * build validates the raw JSON Schema with its full validator and emits the\n * document verbatim, so `pattern` and `maxProperties` survive. A standalone\n * omptype schema would drop both.\n *\n * @param pi - OMP extension API.\n * @param tools - Tools to register.\n * @param options - Host `Text`, optional load mode and renderers.\n * @throws {ToolDefinitionError} When two tools share a name.\n */\nexport function registerOmpTools(\n pi: ExtensionAPI,\n tools: readonly ToolDefinition[],\n options: OmpToolOptions,\n): void {\n indexTools(tools);\n const { Type } = pi.typebox;\n const { Text } = options;\n\n for (const tool of tools) {\n const renderers = Object.hasOwn(options.renderers ?? {}, tool.name)\n ? options.renderers?.[tool.name]\n : undefined;\n\n pi.registerTool({\n name: tool.name,\n label: tool.title,\n description: tool.description,\n parameters: Type.Unsafe<Record<string, unknown>>(wireSchema(tool)),\n approval: APPROVAL[tool.effect],\n loadMode: options.loadMode,\n async execute(_toolCallId, params, signal, onUpdate, ctx): Promise<AgentToolResult<unknown>> {\n // Returned as is: OMP reads `isError` from the object (`explicitError`).\n return await invokeTool(tool, params, hostContext(signal, onUpdate, ctx));\n },\n renderCall(args, renderOptions, theme): Component {\n if (renderers?.renderCall) return renderers.renderCall(args, renderOptions, theme);\n const summary = renderers?.describeCall ? sanitizeLine(renderers.describeCall(args)) : \"\";\n const title = theme.fg(\"accent\", sanitizeLine(tool.title));\n return new Text(\n `${callIcon(renderOptions, theme)} ${title}${summary ? `: ${theme.fg(\"muted\", summary)}` : \"\"}`,\n 0,\n 0,\n );\n },\n renderResult(result, renderOptions, theme, args): Component {\n if (renderers?.renderResult)\n return renderers.renderResult(result, renderOptions, theme, args);\n if (renderOptions.isPartial)\n return new Text(progressLine(tool, result, renderOptions, theme), 0, 0);\n const icon = result.isError\n ? theme.styledSymbol(\"status.error\", \"error\")\n : theme.styledSymbol(\"status.done\", \"success\");\n const { bracketLeft, bracketRight } = theme.format;\n const badge = theme.fg(\"accent\", `${bracketLeft}${APPROVAL[tool.effect]}${bracketRight}`);\n const facts = result.isError ? [] : (renderers?.describeResult?.(result) ?? []);\n return new Text(\n `${icon} ${theme.fg(\"accent\", sanitizeLine(tool.title))} ${badge}${dimFacts(facts, theme)}`,\n 0,\n 0,\n );\n },\n });\n }\n}\n\n/**\n * Status line while the call runs: the spinner, the title and its last progress line.\n *\n * @param tool - Tool being called.\n * @param result - Partial result from `onUpdate`.\n * @param options - Render options from the host.\n * @param theme - Host theme.\n * @returns {string} The styled line.\n */\nfunction progressLine(\n tool: ToolDefinition,\n result: Readonly<{ content: readonly Readonly<{ type: string; text?: string }>[] }>,\n options: ToolRenderResultOptions,\n theme: Theme,\n): string {\n const message = sanitizeLine(\n result.content.findLast((block) => block.type === \"text\")?.text ?? \"\",\n );\n const title = theme.fg(\"accent\", sanitizeLine(tool.title));\n return `${callIcon(options, theme)} ${title}${message ? ` ${theme.fg(\"dim\", message)}` : \"\"}`;\n}\n\n/**\n * The `describeResult` facts after the badge, sanitized and dimmed; empty ones drop out.\n *\n * @param facts - Facts as the renderer gave them.\n * @param theme - Host theme.\n * @returns {string} The facts with a leading space, or nothing.\n */\nfunction dimFacts(facts: readonly unknown[], theme: Theme): string {\n const shown = facts.map(sanitizeLine).filter(Boolean);\n return shown.length > 0 ? ` ${theme.fg(\"dim\", shown.join(theme.sep.dot))}` : \"\";\n}\n\n/**\n * Status icon for a call: pending, spinning or done.\n *\n * Drawn with the host theme on purpose: compiled OMP injects only the package\n * root, so importing `@oh-my-pi/pi-coding-agent/tui` would stop the extension.\n *\n * @param options - Render options from the host.\n * @param theme - Host theme.\n * @returns {string} The styled icon.\n */\nfunction callIcon(options: ToolRenderResultOptions, theme: Theme): string {\n if (!options.isPartial) return theme.styledSymbol(\"status.done\", \"success\");\n if (options.spinnerFrame === undefined) return theme.styledSymbol(\"status.pending\", \"muted\");\n return (\n theme.spinnerFrames[options.spinnerFrame % theme.spinnerFrames.length] ??\n theme.styledSymbol(\"status.running\", \"accent\")\n );\n}\n"],"mappings":";;AA4DA,MAAM,WAAiD;CACrD,MAAM;CACN,OAAO;CAEP,aAAa;AACf;;;;;;;;;;;;;GAeA,UAAgB,QAAA;GAKd,MAAA,QAAgB,aAAA,QAAA,QAAA,UAAA,KAAA;IAChB,OAAQ,MAAA,WAAY,MAAA,QAAA,YAAA,QAAA,UAAA,GAAA,CAAA;GACpB;GAEA,WAAW,MAAQ,eAAO,OAAA;IACxB,IAAM,WAAA,YAAmB,OAAO,UAAQ,WAAiB,MAAK,eAClD,KAAA;IAGZ,MAAG,UAAa,WAAA,eAAA,aAAA,UAAA,aAAA,IAAA,CAAA,IAAA;IACd,MAAM,QAAK,MAAA,GAAA,UAAA,aAAA,KAAA,KAAA,CAAA;IACX,OAAO,IAAK,KAAA,GAAA,SAAA,eAAA,KAAA,EAAA,GAAA,QAAA,UAAA,KAAA,MAAA,GAAA,SAAA,OAAA,MAAA,MAAA,GAAA,CAAA;GACZ;GACA,aAAY,QAAK,eAA2C,OAAK,MAAA;IACjE,IAAA,WAAU,cAAc,OAAA,UAAA,aAAA,QAAA,eAAA,OAAA,IAAA;IACxB,IAAA,cAAkB,WAAA,OAAA,IAAA,KAAA,aAAA,MAAA,QAAA,eAAA,KAAA,GAAA,GAAA,CAAA;IAClB,MAAM,OAAQ,OAAA,UAAa,MAAQ,aAAQ,gBAAkD,OAAA,IAAA,MAAA,aAAA,eAAA,SAAA;IAE3F,MAAA,EAAO,aAAM,iBAAyB,MAAA;IACxC,MAAA,QAAA,MAAA,GAAA,UAAA,GAAA,cAAA,SAAA,KAAA,UAAA,cAAA;IACA,MAAA,QAAW,OAAM,UAAe,CAAA,IAAA,WAAkB,iBAAA,MAAA,KAAA,CAAA;IAChD,OAAI,IAAA,KAAW,GAAA,KAAA,GAAY,MAAA,GAAO,UAAU,aAAW,KAAM,KAAA,CAAA,EAAA,GAAA,QAAoB,SAAA,OAAA,KAAA,KAAA,GAAA,CAAA;GACjF;EACA,CAAA;CACA;AAKF;AAEE,SAAI,aAAW,MAAA,QACb,SAAO,OAAU;CACnB,MAAA,UAAI,aAAc,OAChB,QAAW,UAAK,UAAa,MAAM,SAAQ,MAAA,CAAA,EAAA,QAAoB,EAAG;CACpE,MAAA,QAAM,MAAO,GAAO,UAChB,aAAM,KAAA,KAAa,CAAA;CAEvB,OAAA,GAAM,SAAE,SAAa,KAAA,EAAA,GAAA,QAAiB,UAAM,IAAA,MAAA,GAAA,OAAA,OAAA,MAAA;AAC5C;AAEA,SAAA,SAAW,OACN,OAAQ;CAIf,MAAA,QAAA,MAAA,IAAA,YAAA,CAAA,CAAA,OAAA,OAAA;CACF,OAAC,MAAA,SAAA,IAAA,IAAA,MAAA,GAAA,OAAA,MAAA,KAAA,MAAA,IAAA,GAAA,CAAA,MAAA;AACH"}
package/dist/pi.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { ToolDefinition as ToolDefinition$1 } from "./index.mjs";
1
+ import { ToolDefinition as ToolDefinition$1 } from "./_chunks/index.mjs";
2
2
  import { ExtensionAPI, ToolDefinition } from "@earendil-works/pi-coding-agent";
3
3
  type Component = ReturnType<NonNullable<ToolDefinition["renderCall"]>>;
4
4
  /** The `Text` component of `@earendil-works/pi-tui`, which Pi resolves for every extension. */
package/dist/pi.mjs CHANGED
@@ -18,7 +18,7 @@ function registerPiTools(pi, tools, options = {}) {
18
18
  parameters: tool.input,
19
19
  async execute(_toolCallId, params, signal, onUpdate, ctx) {
20
20
  if (ask) await approve(tool, ask, params, signal, ctx);
21
- const result = await invokeTool(tool, params, hostContext(signal, onUpdate));
21
+ const result = await invokeTool(tool, params, hostContext(signal, onUpdate, ctx));
22
22
  if (result.isError && failures === "throw") throw new Error(resultText(result));
23
23
  return result;
24
24
  }
package/dist/pi.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"pi.mjs","names":[],"sources":["../src/pi.ts"],"sourcesContent":["/**\n * Pi adapter: registers {@link ToolDefinition}s on a Pi `ExtensionAPI`.\n *\n * Only types come from `@earendil-works/pi-coding-agent`; nothing is imported\n * from the host at runtime. A call line from `describeCall` needs the host\n * `Text`, which the extension passes in.\n */\n\nimport type {\n AgentToolResult,\n ExtensionAPI,\n ExtensionContext,\n ToolDefinition as PiToolDefinition,\n} from \"@earendil-works/pi-coding-agent\";\n\nimport { sanitizeText } from \"./escapes.ts\";\nimport {\n indexTools,\n invokeTool,\n resultText,\n sanitizeLine,\n ToolDefinitionError,\n ToolInputError,\n validateInput,\n type ToolDefinition,\n} from \"./index.ts\";\nimport { hostContext } from \"./updates.ts\";\n\ntype Component = ReturnType<NonNullable<PiToolDefinition[\"renderCall\"]>>;\n\n/** The `Text` component of `@earendil-works/pi-tui`, which Pi resolves for every extension. */\nexport type PiTextComponent = new (text: string, paddingX: number, paddingY: number) => Component;\n\nexport interface PiToolOptions {\n /**\n * How a returned `isError` result reaches Pi.\n *\n * `throw` (default) raises the result text: `pi-agent-core` up to 0.98 marks\n * every returned object as a success and records an error only after a throw.\n * `return` hands the result over unchanged and keeps its `details`; use it\n * only with a peer range of `>=0.99.0`, since Pi does not check peer ranges.\n */\n readonly failures?: \"throw\" | \"return\";\n /** Host `Text` from `@earendil-works/pi-tui`, which `describeCall` draws with. */\n readonly Text?: PiTextComponent;\n /** Renderers by tool name. */\n readonly renderers?: Readonly<Record<string, PiRenderers>>;\n /** Questions to ask before a call runs, by tool name. A name off the tool list throws. */\n readonly confirm?: Readonly<Record<string, PiConfirm>>;\n}\n\n/** Builds the question for one call from its validated input; `undefined` skips it. */\nexport type PiConfirm = (\n input: Readonly<Record<string, unknown>>,\n) => PiQuestion | undefined | Promise<PiQuestion | undefined>;\n\n/** What `ctx.ui.confirm` shows. The adapter sanitizes both and keeps the message's lines. */\nexport interface PiQuestion {\n readonly title: string;\n readonly message: string;\n}\n\n/** Renderers for one tool: Pi's own, passed unchanged, or a one-line call summary. */\nexport interface PiRenderers extends Readonly<\n Pick<PiToolDefinition, \"renderCall\" | \"renderResult\">\n> {\n /** One-line summary of the arguments after the title, sanitized here. A `renderCall` wins. */\n readonly describeCall?: (args: Readonly<Record<string, unknown>>) => unknown;\n}\n\n/**\n * Registers every tool on the Pi extension API.\n *\n * @param pi - Pi extension API.\n * @param tools - Tools to register.\n * @param options - Failure policy, host `Text`, renderers and questions.\n * @throws {ToolDefinitionError} When two tools share a name, a tool has `describeCall` but no\n * `Text` came with it, or `confirm` names a tool that isn't in the list.\n */\nexport function registerPiTools(\n pi: ExtensionAPI,\n tools: readonly ToolDefinition[],\n options: PiToolOptions = {},\n): void {\n const listed = indexTools(tools);\n const failures = options.failures ?? \"throw\";\n const stray = Object.keys(options.confirm ?? {}).find((name) => !listed.has(name));\n if (stray !== undefined) {\n throw new ToolDefinitionError(\n `confirm names ${JSON.stringify(stray)}, which isn't in the tool list`,\n );\n }\n\n for (const tool of tools) {\n const renderers = byName(options.renderers, tool.name);\n const ask = byName(options.confirm, tool.name);\n pi.registerTool({\n ...hostRenderers(tool, renderers, options.Text),\n name: tool.name,\n label: tool.title,\n description: tool.description,\n ...(tool.snippet === undefined ? {} : { promptSnippet: tool.snippet }),\n ...(tool.guidelines === undefined ? {} : { promptGuidelines: [...tool.guidelines] }),\n parameters: tool.input,\n async execute(_toolCallId, params, signal, onUpdate, ctx): Promise<AgentToolResult<unknown>> {\n if (ask) await approve(tool, ask, params, signal, ctx);\n const result = await invokeTool(tool, params, hostContext(signal, onUpdate));\n if (result.isError && failures === \"throw\") throw new Error(resultText(result));\n return result;\n },\n });\n }\n}\n\n/**\n * Own entry of a by-name option, so a tool named `constructor` doesn't reach the prototype.\n *\n * @param entries - Option keyed by tool name.\n * @param name - Tool name.\n * @returns {T | undefined} The entry, if the option has one for this tool.\n */\nfunction byName<T>(entries: Readonly<Record<string, T>> | undefined, name: string): T | undefined {\n return entries && Object.hasOwn(entries, name) ? entries[name] : undefined;\n}\n\n/**\n * Asks the user about one call and throws unless they say yes.\n *\n * @param tool - Tool being called.\n * @param ask - Its question builder.\n * @param params - Arguments as Pi passes them.\n * @param signal - The call's abort signal, which also dismisses the dialog.\n * @param ctx - Pi context of the call.\n * @returns {Promise<void>} Once the call may run.\n * @throws {ToolInputError} When the arguments fail the schema, before anyone is asked.\n * @throws {Error} Without a UI, on a \"no\", or with the reason of an abort.\n */\nasync function approve(\n tool: ToolDefinition,\n ask: PiConfirm,\n params: unknown,\n signal: AbortSignal | undefined,\n ctx: ExtensionContext,\n): Promise<void> {\n const checked = validateInput(tool, params);\n if (!checked.ok) throw new ToolInputError(checked.lines);\n const question = await ask(checked.value);\n if (question === undefined) return;\n if (!ctx.hasUI) throw new Error(`${tool.name} needs interactive approval in Pi TUI or RPC mode`);\n const approved = await ctx.ui.confirm(\n sanitizeLine(question.title),\n sanitizeText(question.message),\n signal ? { signal } : {},\n );\n signal?.throwIfAborted();\n if (!approved) {\n throw new Error(\n `${tool.name} was cancelled by the user. Do not retry unless the user asks again.`,\n );\n }\n}\n\n/**\n * The renderers Pi gets for one tool, with `describeCall` turned into a `renderCall`.\n *\n * @param tool - Tool being registered.\n * @param renderers - Its renderers, if any.\n * @param Text - Host `Text` component.\n * @returns {Pick<PiToolDefinition, \"renderCall\" | \"renderResult\">} What goes to `pi.registerTool`.\n * @throws {ToolDefinitionError} When `describeCall` would draw but `Text` is missing.\n */\nfunction hostRenderers(\n tool: ToolDefinition,\n renderers: PiRenderers | undefined,\n Text: PiTextComponent | undefined,\n): Pick<PiToolDefinition, \"renderCall\" | \"renderResult\"> {\n if (!renderers) return {};\n const { describeCall, ...own } = renderers;\n if (own.renderCall || !describeCall) return own;\n if (!Text) throw new ToolDefinitionError(`${tool.name}: describeCall needs the host Text option`);\n const title = sanitizeLine(tool.title);\n return {\n ...own,\n renderCall(args, theme): Component {\n const summary = sanitizeLine(describeCall(args as Readonly<Record<string, unknown>>));\n const header = theme.fg(\"toolTitle\", theme.bold(title));\n return new Text(summary ? `${header} ${theme.fg(\"muted\", summary)}` : header, 0, 0);\n },\n };\n}\n"],"mappings":";;;;;;;;;;EA+EA,GAAA,aAAgB;GAKd,GAAA,cAAe,MAAA,WAAgB,QAAA,IAAA;GAC/B,MAAM,KAAA;GACN,OAAM,KAAQ;GACd,aAAc,KAAA;GAMd,GAAK,KAAA,YAAc,KAAO,IAAA,CAAA,IAAA,EAAA,eAAA,KAAA,QAAA;GACxB,GAAA,KAAM,eAAY,KAAO,IAAQ,CAAA,IAAA,EAAA,kBAAoB,CAAA,GAAA,KAAA,UAAA,EAAA;GACrD,YAAY,KAAA;GACZ,MAAG,QAAA,aAAa,QAAA,QAAA,UAAA,KAAA;IACd,IAAG,KAAA,MAAA,QAAoB,MAAA,KAAW,QAAQ,QAAI,GAAA;IAC9C,MAAM,SAAK,MAAA,WAAA,MAAA,QAAA,YAAA,QAAA,QAAA,CAAA;IACX,IAAA,OAAY,WAAA,aAAA,SAAA,MAAA,IAAA,MAAA,WAAA,MAAA,CAAA;IACZ,OAAA;GACA;EACA,CAAA;CACA;AACA;AAEE,SAAA,OAAM,SAAe,MAAA;CACrB,OAAI,WAAO,OAAW,OAAA,SAAa,IAAA,IAAS,QAAU,QAAM,KAAA;AAC5D;AAEJ,eAAC,QAAA,MAAA,KAAA,QAAA,QAAA,KAAA;CACH,MAAA,UAAA,cAAA,MAAA,MAAA;CACF,IAAA,CAAA,QAAA,IAAA,MAAA,IAAA,eAAA,QAAA,KAAA;;;;;;;;AAUE,SAAO,cAAW,MAAO,WAAO,MAAa;CAC/C,IAAA,CAAA,WAAA,OAAA,CAAA;;;;;;;;;;;;;AAcA;AAQE,SAAK"}
1
+ {"version":3,"file":"pi.mjs","names":[],"sources":["../src/pi.ts"],"sourcesContent":["/**\n * Pi adapter: registers {@link ToolDefinition}s on a Pi `ExtensionAPI`.\n *\n * Only types come from `@earendil-works/pi-coding-agent`; nothing is imported\n * from the host at runtime. A call line from `describeCall` needs the host\n * `Text`, which the extension passes in.\n */\n\nimport type {\n AgentToolResult,\n ExtensionAPI,\n ExtensionContext,\n ToolDefinition as PiToolDefinition,\n} from \"@earendil-works/pi-coding-agent\";\n\nimport { sanitizeText } from \"./escapes.ts\";\nimport {\n indexTools,\n invokeTool,\n resultText,\n sanitizeLine,\n ToolDefinitionError,\n ToolInputError,\n validateInput,\n type ToolDefinition,\n} from \"./index.ts\";\nimport { hostContext } from \"./updates.ts\";\n\ntype Component = ReturnType<NonNullable<PiToolDefinition[\"renderCall\"]>>;\n\n/** The `Text` component of `@earendil-works/pi-tui`, which Pi resolves for every extension. */\nexport type PiTextComponent = new (text: string, paddingX: number, paddingY: number) => Component;\n\nexport interface PiToolOptions {\n /**\n * How a returned `isError` result reaches Pi.\n *\n * `throw` (default) raises the result text: `pi-agent-core` up to 0.98 marks\n * every returned object as a success and records an error only after a throw.\n * `return` hands the result over unchanged and keeps its `details`; use it\n * only with a peer range of `>=0.99.0`, since Pi does not check peer ranges.\n */\n readonly failures?: \"throw\" | \"return\";\n /** Host `Text` from `@earendil-works/pi-tui`, which `describeCall` draws with. */\n readonly Text?: PiTextComponent;\n /** Renderers by tool name. */\n readonly renderers?: Readonly<Record<string, PiRenderers>>;\n /** Questions to ask before a call runs, by tool name. A name off the tool list throws. */\n readonly confirm?: Readonly<Record<string, PiConfirm>>;\n}\n\n/** Builds the question for one call from its validated input; `undefined` skips it. */\nexport type PiConfirm = (\n input: Readonly<Record<string, unknown>>,\n) => PiQuestion | undefined | Promise<PiQuestion | undefined>;\n\n/** What `ctx.ui.confirm` shows. The adapter sanitizes both and keeps the message's lines. */\nexport interface PiQuestion {\n readonly title: string;\n readonly message: string;\n}\n\n/** Renderers for one tool: Pi's own, passed unchanged, or a one-line call summary. */\nexport interface PiRenderers extends Readonly<\n Pick<PiToolDefinition, \"renderCall\" | \"renderResult\">\n> {\n /** One-line summary of the arguments after the title, sanitized here. A `renderCall` wins. */\n readonly describeCall?: (args: Readonly<Record<string, unknown>>) => unknown;\n}\n\n/**\n * Registers every tool on the Pi extension API.\n *\n * @param pi - Pi extension API.\n * @param tools - Tools to register.\n * @param options - Failure policy, host `Text`, renderers and questions.\n * @throws {ToolDefinitionError} When two tools share a name, a tool has `describeCall` but no\n * `Text` came with it, or `confirm` names a tool that isn't in the list.\n */\nexport function registerPiTools(\n pi: ExtensionAPI,\n tools: readonly ToolDefinition[],\n options: PiToolOptions = {},\n): void {\n const listed = indexTools(tools);\n const failures = options.failures ?? \"throw\";\n const stray = Object.keys(options.confirm ?? {}).find((name) => !listed.has(name));\n if (stray !== undefined) {\n throw new ToolDefinitionError(\n `confirm names ${JSON.stringify(stray)}, which isn't in the tool list`,\n );\n }\n\n for (const tool of tools) {\n const renderers = byName(options.renderers, tool.name);\n const ask = byName(options.confirm, tool.name);\n pi.registerTool({\n ...hostRenderers(tool, renderers, options.Text),\n name: tool.name,\n label: tool.title,\n description: tool.description,\n ...(tool.snippet === undefined ? {} : { promptSnippet: tool.snippet }),\n ...(tool.guidelines === undefined ? {} : { promptGuidelines: [...tool.guidelines] }),\n parameters: tool.input,\n async execute(_toolCallId, params, signal, onUpdate, ctx): Promise<AgentToolResult<unknown>> {\n if (ask) await approve(tool, ask, params, signal, ctx);\n const result = await invokeTool(tool, params, hostContext(signal, onUpdate, ctx));\n if (result.isError && failures === \"throw\") throw new Error(resultText(result));\n return result;\n },\n });\n }\n}\n\n/**\n * Own entry of a by-name option, so a tool named `constructor` doesn't reach the prototype.\n *\n * @param entries - Option keyed by tool name.\n * @param name - Tool name.\n * @returns {T | undefined} The entry, if the option has one for this tool.\n */\nfunction byName<T>(entries: Readonly<Record<string, T>> | undefined, name: string): T | undefined {\n return entries && Object.hasOwn(entries, name) ? entries[name] : undefined;\n}\n\n/**\n * Asks the user about one call and throws unless they say yes.\n *\n * @param tool - Tool being called.\n * @param ask - Its question builder.\n * @param params - Arguments as Pi passes them.\n * @param signal - The call's abort signal, which also dismisses the dialog.\n * @param ctx - Pi context of the call.\n * @returns {Promise<void>} Once the call may run.\n * @throws {ToolInputError} When the arguments fail the schema, before anyone is asked.\n * @throws {Error} Without a UI, on a \"no\", or with the reason of an abort.\n */\nasync function approve(\n tool: ToolDefinition,\n ask: PiConfirm,\n params: unknown,\n signal: AbortSignal | undefined,\n ctx: ExtensionContext,\n): Promise<void> {\n const checked = validateInput(tool, params);\n if (!checked.ok) throw new ToolInputError(checked.lines);\n const question = await ask(checked.value);\n if (question === undefined) return;\n if (!ctx.hasUI) throw new Error(`${tool.name} needs interactive approval in Pi TUI or RPC mode`);\n const approved = await ctx.ui.confirm(\n sanitizeLine(question.title),\n sanitizeText(question.message),\n signal ? { signal } : {},\n );\n signal?.throwIfAborted();\n if (!approved) {\n throw new Error(\n `${tool.name} was cancelled by the user. Do not retry unless the user asks again.`,\n );\n }\n}\n\n/**\n * The renderers Pi gets for one tool, with `describeCall` turned into a `renderCall`.\n *\n * @param tool - Tool being registered.\n * @param renderers - Its renderers, if any.\n * @param Text - Host `Text` component.\n * @returns {Pick<PiToolDefinition, \"renderCall\" | \"renderResult\">} What goes to `pi.registerTool`.\n * @throws {ToolDefinitionError} When `describeCall` would draw but `Text` is missing.\n */\nfunction hostRenderers(\n tool: ToolDefinition,\n renderers: PiRenderers | undefined,\n Text: PiTextComponent | undefined,\n): Pick<PiToolDefinition, \"renderCall\" | \"renderResult\"> {\n if (!renderers) return {};\n const { describeCall, ...own } = renderers;\n if (own.renderCall || !describeCall) return own;\n if (!Text) throw new ToolDefinitionError(`${tool.name}: describeCall needs the host Text option`);\n const title = sanitizeLine(tool.title);\n return {\n ...own,\n renderCall(args, theme): Component {\n const summary = sanitizeLine(describeCall(args as Readonly<Record<string, unknown>>));\n const header = theme.fg(\"toolTitle\", theme.bold(title));\n return new Text(summary ? `${header} ${theme.fg(\"muted\", summary)}` : header, 0, 0);\n },\n };\n}\n"],"mappings":";;;;;;;;;;EA+EA,GAAA,aAAgB;GAKd,GAAA,cAAe,MAAA,WAAgB,QAAA,IAAA;GAC/B,MAAM,KAAA;GACN,OAAM,KAAQ;GACd,aAAc,KAAA;GAMd,GAAK,KAAA,YAAc,KAAO,IAAA,CAAA,IAAA,EAAA,eAAA,KAAA,QAAA;GACxB,GAAA,KAAM,eAAY,KAAO,IAAQ,CAAA,IAAA,EAAA,kBAAoB,CAAA,GAAA,KAAA,UAAA,EAAA;GACrD,YAAY,KAAA;GACZ,MAAG,QAAA,aAAa,QAAA,QAAA,UAAA,KAAA;IACd,IAAG,KAAA,MAAA,QAAoB,MAAA,KAAW,QAAQ,QAAI,GAAA;IAC9C,MAAM,SAAK,MAAA,WAAA,MAAA,QAAA,YAAA,QAAA,UAAA,GAAA,CAAA;IACX,IAAA,OAAY,WAAA,aAAA,SAAA,MAAA,IAAA,MAAA,WAAA,MAAA,CAAA;IACZ,OAAA;GACA;EACA,CAAA;CACA;AACA;AAEE,SAAA,OAAM,SAAe,MAAA;CACrB,OAAI,WAAO,OAAW,OAAA,SAAa,IAAA,IAAS,QAAU,QAAM,KAAA;AAC5D;AAEJ,eAAC,QAAA,MAAA,KAAA,QAAA,QAAA,KAAA;CACH,MAAA,UAAA,cAAA,MAAA,MAAA;CACF,IAAA,CAAA,QAAA,IAAA,MAAA,IAAA,eAAA,QAAA,KAAA;;;;;;;;AAUE,SAAO,cAAW,MAAO,WAAO,MAAa;CAC/C,IAAA,CAAA,WAAA,OAAA,CAAA;;;;;;;;;;;;;AAcA;AAQE,SAAK"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agntn/tools",
3
- "version": "0.2.0",
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",
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/index.ts"],"mappings":";;YAgCY;EACN;EAAc;;EACd;EAAe;EAAc;;;iBAGlB,WAAW;EAC1B,SAAS;EACT,SAAS;;EAET;;;;;;;;;YAUU;;;;;iBAMK;;WAEN;WACA;;WAEA;;WAEA;;WAEA;;;iBAIM;;WAEN;;WAEA;;;iBAIM;EACf,SAAS;;EAET,YAAY,iBAAiB,SAAS;;iBAGvB,eAAe,cAAc,UAAU,SAAS;;WAEtD;;WAEA;;WAEA;;WAEA;;WAEA;WACA,QAAQ;;WAER;;WAEA;WACA,OAAO;;WAEP,MAAM;;;;;;;EAOf,QACE,OAAO,OAAO,QACd,SAAS,kBACR,WAAW,WAAW,QAAQ,WAAW;;;qBAIjC,4BAA4B;EAC9B;;;qBAIE,uBAAuB;EACzB;;WAEA;;;;EAKT,YAAY;;;;;;;;wBAcE,iBAAiB,cAAc,SAAS,SACtD,MAAM,eAAe,OAAO,WAC3B,eAAe,OAAO;;;;;;;;;;wBA+GT,WAAW,MAAM,iBAAiB;;;;;;;;;;wBAalC,WAAW,gBAAgB,mBAAmB,oBAAoB;YAStE,WAAW,cAAc;EAC/B;EAAU,OAAO,OAAO;;EACxB;EAAW;;;;;;;;;;;;;;;;wBAgBD,cAAc,cAAc,SAC1C,MAAM,eAAe,iBACrB,gBACC,WAAW;;;;;;;;;;;;;wBA4JQ,WACpB,MAAM,gBACN,eACA,UAAS,kBACR,QAAQ;;;;;;;;;;;;wBAmCK,aAAa;;;;;;;wBAab,WAAW,QAAQ"}