@agntn/tools 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"h3.mjs","names":[],"sources":["../src/h3.ts"],"sourcesContent":["/**\n * h3-mcp adapter: hands {@link ToolDefinition}s to `defineMcpHandler` from h3-mcp.\n */\n\nimport type { JsonSchema, ToolDefinition as H3ToolDefinition } from \"h3-mcp\";\n\nimport { type ToolCallContext, type ToolDefinition } from \"./index.ts\";\nimport { callTool, listTools, progressSteps } from \"./mcp-answers.ts\";\n\n/** An h3-mcp tool whose `inputSchema` is the plain JSON Schema `tools/list` sends. */\nexport type H3Tool = H3ToolDefinition<JsonSchema>;\n\n/**\n * Turns tools into h3-mcp tool definitions for `defineMcpHandler({ tools })`.\n *\n * Each entry carries what `listTools` lists, and its handler answers through\n * `callTool`, so the text, the validation lines and the sanitized errors are the\n * ones every other MCP transport gives. The schema goes out as plain JSON\n * Schema, which h3-mcp passes through without validating; the core validates\n * instead. An unknown name never reaches a handler: h3-mcp answers it itself\n * with a JSON-RPC error.\n *\n * Imports only types from h3-mcp, so the adapter loads neither h3-mcp nor the MCP SDK.\n *\n * @param info - Server info; `name` is the word in the message for an unknown tool.\n * @param tools - Tools to serve.\n * @returns {H3Tool[]} Tool definitions in the order given.\n * @throws {ToolDefinitionError} When two tools share a name.\n */\nexport function toH3Tools(\n info: { readonly name: string },\n tools: readonly ToolDefinition[],\n): H3Tool[] {\n return listTools(tools).map((entry) => ({\n name: entry.name,\n title: entry.title,\n description: entry.description,\n inputSchema: entry.inputSchema as JsonSchema,\n annotations: entry.annotations,\n handler: (args, event) => {\n // Read now: a legacy batch shares one context between its calls.\n const mcp = event.context.mcp;\n const context: ToolCallContext = {\n signal: mcp?.signal,\n ...(mcp?.progressToken === undefined || mcp.progress === undefined\n ? {}\n : {\n progress: progressSteps(({ progress, total, message }) =>\n mcp.progress?.(progress, total, message),\n ),\n }),\n };\n return callTool(info, tools, entry.name, args, context);\n },\n }));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA6BA;AAKI,SAAM"}
package/dist/index.d.mts CHANGED
@@ -38,9 +38,18 @@ export interface ToolCliHints {
38
38
  /** String properties that read stdin when given as `-`. */
39
39
  readonly stdin?: readonly string[];
40
40
  }
41
+ /** How far a long call has come, for hosts that draw it. */
42
+ export interface ToolProgress {
43
+ /** Work done so far. MCP skips an update where it doesn't grow. */
44
+ readonly progress: number;
45
+ /** All the work there is, when the tool knows it. */
46
+ readonly total?: number;
47
+ }
41
48
  /** Per-call context the adapters hand to `execute`. */
42
49
  export interface ToolCallContext {
43
50
  signal?: AbortSignal;
51
+ /** Says the call is still at it. Absent where the host can't show it, so call `progress?.()`. */
52
+ progress?: (message: string, amount?: ToolProgress) => void;
44
53
  }
45
54
  export interface ToolDefinition<Input extends TObject = TObject, Details = unknown> {
46
55
  /** Wire name, `<package>_<operation>`. */
@@ -135,6 +144,9 @@ export declare function validateInput<Input extends TObject>(tool: ToolDefinitio
135
144
  /**
136
145
  * Validates and runs a tool. Every adapter calls through here.
137
146
  *
147
+ * Progress is best effort: a line after the call settles goes nowhere, and a host that throws on
148
+ * one doesn't fail the call.
149
+ *
138
150
  * @param tool - Tool to run.
139
151
  * @param args - Arguments as received from the host.
140
152
  * @param context - Per-call context.
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/index.ts"],"mappings":";;YAgCY;EACN;EAAc;;EACd;EAAe;EAAc;;;iBAGlB,WAAW;EAC1B,SAAS;EACT,SAAS;;EAET;;;;;;;;;YAUU;;;;;iBAMK;;WAEN;WACA;;WAEA;;WAEA;;WAEA;;;iBAIM;EACf,SAAS;;iBAGM,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;;;;;;;;;;wBAyJQ,WACpB,MAAM,gBACN,eACA,UAAS,kBACR,QAAQ;;;;;;;;;;;;wBAmBK,aAAa;;;;;;;wBAab,WAAW,QAAQ"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/index.ts"],"mappings":";;YAgCY;EACN;EAAc;;EACd;EAAe;EAAc;;;iBAGlB,WAAW;EAC1B,SAAS;EACT,SAAS;;EAET;;;;;;;;;YAUU;;;;;iBAMK;;WAEN;WACA;;WAEA;;WAEA;;WAEA;;;iBAIM;;WAEN;;WAEA;;;iBAIM;EACf,SAAS;;EAET,YAAY,iBAAiB,SAAS;;iBAGvB,eAAe,cAAc,UAAU,SAAS;;WAEtD;;WAEA;;WAEA;;WAEA;;WAEA;WACA,QAAQ;;WAER;;WAEA;WACA,OAAO;;WAEP,MAAM;;;;;;;EAOf,QACE,OAAO,OAAO,QACd,SAAS,kBACR,WAAW,WAAW,QAAQ,WAAW;;;qBAIjC,4BAA4B;EAC9B;;;qBAIE,uBAAuB;EACzB;;WAEA;;;;EAKT,YAAY;;;;;;;;wBAcE,iBAAiB,cAAc,SAAS,SACtD,MAAM,eAAe,OAAO,WAC3B,eAAe,OAAO;;;;;;;;;;wBA+GT,WAAW,MAAM,iBAAiB;;;;;;;;;;wBAalC,WAAW,gBAAgB,mBAAmB,oBAAoB;YAStE,WAAW,cAAc;EAC/B;EAAU,OAAO,OAAO;;EACxB;EAAW;;;;;;;;;;;;;;;;wBAgBD,cAAc,cAAc,SAC1C,MAAM,eAAe,iBACrB,gBACC,WAAW;;;;;;;;;;;;;wBA4JQ,WACpB,MAAM,gBACN,eACA,UAAS,kBACR,QAAQ;;;;;;;;;;;;wBAmCK,aAAa;;;;;;;wBAab,WAAW,QAAQ"}
package/dist/mcp.d.mts CHANGED
@@ -1,9 +1,13 @@
1
- import { ToolDefinition } from "./index.mjs";
2
- import { CallToolResult, Server, ToolAnnotations } from "@modelcontextprotocol/server";
3
- export interface McpServerInfo {
1
+ import { ToolCallContext, ToolDefinition } from "./index.mjs";
2
+ import { CallToolResult, Server, Tool, ToolAnnotations } from "@modelcontextprotocol/server";
3
+ interface McpServerInfo {
4
4
  /** Server name, also used in the unknown-tool message. */
5
5
  readonly name: string;
6
6
  readonly version: string;
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;
7
11
  }
8
12
  /**
9
13
  * Maps a tool's title and declared effect to MCP annotations. Claude Code reads its label here.
@@ -24,6 +28,25 @@ export declare function toolAnnotations(tool: ToolDefinition): ToolAnnotations;
24
28
  * @returns {CallToolResult} MCP error result.
25
29
  */
26
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>;
27
50
  /**
28
51
  * Creates an unconnected MCP server exposing the tools.
29
52
  *
@@ -38,9 +61,13 @@ export declare function errorResult(...lines: readonly string[]): CallToolResult
38
61
  * clients that see structured output prefer it over `content` and would hide
39
62
  * the readable answer. Every fact a follow-up call needs belongs in the text.
40
63
  *
41
- * @param info - Server name and version.
64
+ * A progress notification that fails to send goes to `onerror`, never to the tool.
65
+ *
66
+ * @param info - Server name, version and optional title and website, sent to the client as given.
42
67
  * @param tools - Tools to serve.
43
68
  * @returns {Server} Unconnected MCP server.
69
+ * @throws {ToolDefinitionError} When two tools share a name.
44
70
  */
45
71
  export declare function createMcpServer(info: McpServerInfo, tools: readonly ToolDefinition[]): Server;
72
+ export type { McpServerInfo };
46
73
  //# sourceMappingURL=mcp.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"mcp.d.mts","names":[],"sources":["../src/mcp.ts"],"mappings":";;iBAoBiB;;WAEN;WACA;;;;;;;;wBASK,gBAAgB,MAAM,iBAAiB;;;;;;;;;;;;wBAqBvC,eAAe,2BAA2B;;;;;;;;;;;;;;;;;;;wBAsB1C,gBAAgB,MAAM,eAAe,gBAAgB,mBAAmB"}
1
+ {"version":3,"file":"mcp.d.mts","names":[],"sources":["../src/mcp-answers.ts","../src/mcp.ts"],"mappings":";;UAmBiB;;WAEN;WACA;;WAEA;;WAEA;;;;;;;;wBASK,gBAAgB,MAAM,iBAAiB;;;;;;;;;;;;wBAqBvC,eAAe,2BAA2B;;;;;;;;wBAW1C,UAAU,gBAAgB,mBAAmB;;;;;;;;;;;wBAqBvC,SACpB,MAAM,KAAK,wBACX,gBAAgB,kBAChB,cACA,gBACA,UAAS,kBACR,QAAQ;;;;;;;;;;;;;;;;;;;;;;wBClDK,gBAAgB,MAAM,eAAe,gBAAgB,mBAAmB"}
package/dist/mcp.mjs CHANGED
@@ -1,52 +1,36 @@
1
- import { ToolInputError, indexTools, invokeTool, sanitizeLine, wireSchema } from "./_chunks/src.mjs";
1
+ import { indexTools } from "./_chunks/src.mjs";
2
+ import { callTool, errorResult, listTools, progressSteps, toolAnnotations } from "./_chunks/mcp-answers.mjs";
2
3
  import { Server } from "@modelcontextprotocol/server";
3
- function toolAnnotations(tool) {
4
- return {
5
- title: tool.title,
6
- readOnlyHint: tool.effect === "read",
7
- destructiveHint: tool.effect === "destructive",
8
- idempotentHint: tool.idempotent ?? tool.effect === "read",
9
- openWorldHint: tool.openWorld ?? false
10
- };
11
- }
12
- function errorResult(...lines) {
13
- return {
14
- content: [{
15
- type: "text",
16
- text: lines.map(sanitizeLine).join("\n")
17
- }],
18
- isError: true
19
- };
20
- }
21
4
  function createMcpServer(info, tools) {
22
- const byName = indexTools(tools);
5
+ indexTools(tools);
6
+ const { name, version, title, websiteUrl } = info;
23
7
  const server = new Server({
24
- name: info.name,
25
- version: info.version
8
+ name,
9
+ version,
10
+ title,
11
+ websiteUrl
26
12
  }, { capabilities: { tools: {} } });
27
- server.setRequestHandler("tools/list", () => ({ tools: tools.map((tool) => ({
28
- name: tool.name,
29
- title: tool.title,
30
- description: tool.description,
31
- inputSchema: wireSchema(tool),
32
- annotations: toolAnnotations(tool)
33
- })) }));
34
- server.setRequestHandler("tools/call", async (request, ctx) => {
35
- const tool = byName.get(request.params.name);
36
- if (!tool) return errorResult(`Unknown ${info.name} tool: ${JSON.stringify(request.params.name)}`);
37
- try {
38
- const result = await invokeTool(tool, request.params.arguments ?? {}, { signal: ctx.mcpReq.signal });
39
- return {
40
- content: result.content,
41
- ...result.isError === void 0 ? {} : { isError: result.isError }
42
- };
43
- } catch (error) {
44
- if (error instanceof ToolInputError) return errorResult(...error.lines);
45
- return errorResult(`${tool.name} failed: ${error instanceof Error ? error.message : String(error)}`);
46
- }
13
+ server.setRequestHandler("tools/list", () => ({ tools: listTools(tools) }));
14
+ server.setRequestHandler("tools/call", (request, ctx) => {
15
+ const progressToken = ctx.mcpReq._meta?.progressToken;
16
+ const notify = (params) => {
17
+ ctx.mcpReq.notify({
18
+ method: "notifications/progress",
19
+ params: {
20
+ progressToken,
21
+ ...params
22
+ }
23
+ }).catch((error) => {
24
+ server.onerror?.(error instanceof Error ? error : new Error(String(error)));
25
+ });
26
+ };
27
+ return callTool(info, tools, request.params.name, request.params.arguments, {
28
+ signal: ctx.mcpReq.signal,
29
+ ...progressToken === void 0 ? {} : { progress: progressSteps(notify) }
30
+ });
47
31
  });
48
32
  return server;
49
33
  }
50
- export { createMcpServer, errorResult, toolAnnotations };
34
+ export { callTool, createMcpServer, errorResult, listTools, toolAnnotations };
51
35
 
52
36
  //# sourceMappingURL=mcp.mjs.map
package/dist/mcp.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"mcp.mjs","names":[],"sources":["../src/mcp.ts"],"sourcesContent":["/**\n * MCP adapter: serves {@link ToolDefinition}s from an unconnected MCP server.\n */\n\nimport {\n Server,\n type CallToolResult,\n type Tool,\n type ToolAnnotations,\n} from \"@modelcontextprotocol/server\";\n\nimport {\n indexTools,\n invokeTool,\n sanitizeLine,\n ToolInputError,\n wireSchema,\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}\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 * 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 * @param info - Server name and version.\n * @param tools - Tools to serve.\n * @returns {Server} Unconnected MCP server.\n */\nexport function createMcpServer(info: McpServerInfo, tools: readonly ToolDefinition[]): Server {\n const byName = indexTools(tools);\n const server = new Server(\n { name: info.name, version: info.version },\n { capabilities: { tools: {} } },\n );\n\n server.setRequestHandler(\"tools/list\", () => ({\n tools: tools.map((tool): 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 server.setRequestHandler(\"tools/call\", async (request, ctx) => {\n const tool = byName.get(request.params.name);\n if (!tool) {\n return errorResult(`Unknown ${info.name} tool: ${JSON.stringify(request.params.name)}`);\n }\n\n try {\n const result = await invokeTool(tool, request.params.arguments ?? {}, {\n signal: ctx.mcpReq.signal,\n });\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 return server;\n}\n"],"mappings":";;;;;;;;;CAgCA;AACE;AAEE,SAAA,YAAmB,GAAA,OAAA;CACnB,OAAA;EACA,SAAA,CAAA;GACA,MAAA;GACF,MAAA,MAAA,IAAA,YAAA,CAAA,CAAA,KAAA,IAAA;EACF,CAAA;;;;;;;;;;;EAaA,MAAA,KAAgB;EACd,OAAO,KAAA;EAAE,aAAU,KAAA;EAAE,aAAM,WAAA,IAAA;EAAQ,aAAY,gBAAgB,IAAE;CAAW,EAAC,EAAA,EAAA;CAAG,OAAA,kBAAS,cAAA,OAAA,SAAA,QAAA;EAAK,MAAA,OAAA,OAAA,IAAA,QAAA,OAAA,IAAA;EAChG,IAAA,CAAA,MAAA,OAAA,YAAA,WAAA,KAAA,KAAA,SAAA,KAAA,UAAA,QAAA,OAAA,IAAA,GAAA"}
1
+ {"version":3,"file":"mcp.mjs","names":[],"sources":["../src/mcp.ts"],"sourcesContent":["/**\n * MCP adapter: serves {@link ToolDefinition}s from an unconnected MCP server.\n */\n\nimport { Server } from \"@modelcontextprotocol/server\";\n\nimport { indexTools, type ToolDefinition } from \"./index.ts\";\nimport {\n callTool,\n listTools,\n progressSteps,\n type McpServerInfo,\n type ProgressParams,\n} from \"./mcp-answers.ts\";\n\nexport {\n callTool,\n errorResult,\n listTools,\n toolAnnotations,\n type McpServerInfo,\n} from \"./mcp-answers.ts\";\n\n/**\n * Creates an unconnected MCP server exposing the tools.\n *\n * Built on the low-level `Server` of MCP SDK v2, which the SDK marks\n * `@deprecated`, not on `McpServer`. `McpServer.registerTool` in 2.2.0 would\n * take the schema, but it answers `toString`, `constructor` and `__proto__` as\n * \"Tool toString disabled\" (a lookup that reaches `Object.prototype`), echoes a\n * raw tool name with newlines and escapes into its error, joins validation\n * failures into one line and passes a thrown message through unsanitized.\n *\n * `details` never reaches the client and `structuredContent` is never set:\n * clients that see structured output prefer it over `content` and would hide\n * the readable answer. Every fact a follow-up call needs belongs in the text.\n *\n * A progress notification that fails to send goes to `onerror`, never to the tool.\n *\n * @param info - Server name, version and optional title and website, sent to the client as given.\n * @param tools - Tools to serve.\n * @returns {Server} Unconnected MCP server.\n * @throws {ToolDefinitionError} When two tools share a name.\n */\nexport function createMcpServer(info: McpServerInfo, tools: readonly ToolDefinition[]): Server {\n indexTools(tools);\n const { name, version, title, websiteUrl } = info;\n const server = new Server({ name, version, title, websiteUrl }, { capabilities: { tools: {} } });\n\n server.setRequestHandler(\"tools/list\", () => ({ tools: listTools(tools) }));\n server.setRequestHandler(\"tools/call\", (request, ctx) => {\n const progressToken = ctx.mcpReq._meta?.progressToken;\n const notify = (params: ProgressParams): void => {\n ctx.mcpReq\n .notify({ method: \"notifications/progress\", params: { progressToken, ...params } })\n .catch((error: unknown) => {\n server.onerror?.(error instanceof Error ? error : new Error(String(error)));\n });\n };\n return callTool(info, tools, request.params.name, request.params.arguments, {\n signal: ctx.mcpReq.signal,\n ...(progressToken === undefined ? {} : { progress: progressSteps(notify) }),\n });\n });\n\n return server;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;EA4CA;EACE,OAAA,SAAgB,MAAA,OAAA,QAAA,OAAA,MAAA,QAAA,OAAA,WAAA;GAChB,QAAQ,IAAM,OAAA;GACd,GAAA,kBAAmB,KAAO,IAAA,CAAA,IAAA,EAAA,UAAA,cAAA,MAAA,EAAA;EAAE,CAAA;CAAM,CAAA;CAAS,OAAA;AAAO;AAElD,SAAO,UAAA,iBAAkB,aAAuB,WAAO"}
package/dist/omp.d.mts CHANGED
@@ -21,6 +21,8 @@ export interface OmpRenderers {
21
21
  export interface OmpToolOptions {
22
22
  /** The host `Text` component, imported by the extension from the package root. */
23
23
  readonly Text: TextComponent;
24
+ /** `"essential"` keeps every tool in OMP's top-level list. Left out, OMP hides them behind discovery. */
25
+ readonly loadMode?: ToolDefinition["loadMode"];
24
26
  /** Status-line renderers by tool name. */
25
27
  readonly renderers?: Readonly<Record<string, OmpRenderers>>;
26
28
  }
@@ -34,7 +36,8 @@ export interface OmpToolOptions {
34
36
  *
35
37
  * @param pi - OMP extension API.
36
38
  * @param tools - Tools to register.
37
- * @param options - Host `Text` and optional renderers.
39
+ * @param options - Host `Text`, optional load mode and renderers.
40
+ * @throws {ToolDefinitionError} When two tools share a name.
38
41
  */
39
42
  export declare function registerOmpTools(pi: ExtensionAPI, tools: readonly ToolDefinition$1[], options: OmpToolOptions): void;
40
43
  //# sourceMappingURL=omp.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"omp.d.mts","names":["HostText","OmpToolDefinition","ToolDefinition"],"sources":["../src/omp.ts"],"mappings":";;KAyBK,uBAAuBA;;iBAIX;WACN;WACA;;;iBAIM;;EAEf,cAAc,MAAM,SAAS;;EAE7B,gBAAgB,QAAQ;;;;;EAKxB,eAAeC;;iBAGA;;WAEN,MAAM;;WAEN,YAAY,SAAS,eAAe;;;;;;;;;;;;;;wBAsB/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,gBAAgB,QAAQ;;;;;EAKxB,eAAeC;;iBAGA;;WAEN,MAAM;;WAEN,WAAWA;;WAEX,YAAY,SAAS,eAAe;;;;;;;;;;;;;;;wBAuB/B,iBACd,IAAI,cACJ,gBAAgBC,oBAChB,SAAS"}
package/dist/omp.mjs CHANGED
@@ -1,10 +1,12 @@
1
- import { invokeTool, sanitizeLine, wireSchema } from "./_chunks/src.mjs";
1
+ import { indexTools, invokeTool, sanitizeLine, wireSchema } from "./_chunks/src.mjs";
2
+ import { hostContext } from "./_chunks/updates.mjs";
2
3
  const APPROVAL = {
3
4
  read: "read",
4
5
  write: "write",
5
6
  destructive: "write"
6
7
  };
7
8
  function registerOmpTools(pi, tools, options) {
9
+ indexTools(tools);
8
10
  const { Type } = pi.typebox;
9
11
  const { Text } = options;
10
12
  for (const tool of tools) {
@@ -15,8 +17,9 @@ function registerOmpTools(pi, tools, options) {
15
17
  description: tool.description,
16
18
  parameters: Type.Unsafe(wireSchema(tool)),
17
19
  approval: APPROVAL[tool.effect],
18
- async execute(_toolCallId, params, signal) {
19
- return await invokeTool(tool, params, signal ? { signal } : {});
20
+ loadMode: options.loadMode,
21
+ async execute(_toolCallId, params, signal, onUpdate) {
22
+ return await invokeTool(tool, params, hostContext(signal, onUpdate));
20
23
  },
21
24
  renderCall(args, renderOptions, theme) {
22
25
  const summary = renderers?.describeCall ? sanitizeLine(renderers.describeCall(args)) : "";
@@ -25,16 +28,25 @@ function registerOmpTools(pi, tools, options) {
25
28
  },
26
29
  renderResult(result, renderOptions, theme, args) {
27
30
  if (renderers?.renderResult) return renderers.renderResult(result, renderOptions, theme, args);
31
+ if (renderOptions.isPartial) return new Text(progressLine(tool, result, renderOptions, theme), 0, 0);
28
32
  const icon = result.isError ? theme.styledSymbol("status.error", "error") : theme.styledSymbol("status.done", "success");
29
33
  const { bracketLeft, bracketRight } = theme.format;
30
34
  const badge = theme.fg("accent", `${bracketLeft}${APPROVAL[tool.effect]}${bracketRight}`);
31
- const facts = result.isError ? [] : renderers?.describeResult?.(result).map(sanitizeLine).filter(Boolean) ?? [];
32
- const meta = facts.length > 0 ? ` ${theme.fg("dim", facts.join(theme.sep.dot))}` : "";
33
- return new Text(`${icon} ${theme.fg("accent", sanitizeLine(tool.title))} ${badge}${meta}`, 0, 0);
35
+ const facts = result.isError ? [] : renderers?.describeResult?.(result) ?? [];
36
+ return new Text(`${icon} ${theme.fg("accent", sanitizeLine(tool.title))} ${badge}${dimFacts(facts, theme)}`, 0, 0);
34
37
  }
35
38
  });
36
39
  }
37
40
  }
41
+ function progressLine(tool, result, options, theme) {
42
+ const message = sanitizeLine(result.content.findLast((block) => block.type === "text")?.text ?? "");
43
+ const title = theme.fg("accent", sanitizeLine(tool.title));
44
+ return `${callIcon(options, theme)} ${title}${message ? ` ${theme.fg("dim", message)}` : ""}`;
45
+ }
46
+ function dimFacts(facts, theme) {
47
+ const shown = facts.map(sanitizeLine).filter(Boolean);
48
+ return shown.length > 0 ? ` ${theme.fg("dim", shown.join(theme.sep.dot))}` : "";
49
+ }
38
50
  function callIcon(options, theme) {
39
51
  if (!options.isPartial) return theme.styledSymbol("status.done", "success");
40
52
  if (options.spinnerFrame === void 0) return theme.styledSymbol("status.pending", "muted");
package/dist/omp.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"omp.mjs","names":[],"sources":["../src/omp.ts"],"sourcesContent":["/**\n * OMP adapter: registers {@link ToolDefinition}s on an OMP `ExtensionAPI`.\n *\n * Only types come from `@oh-my-pi/pi-coding-agent`. Compiled OMP injects the\n * package root into the extension file itself, not into its dependencies, so\n * the extension passes the host `Text` component in.\n */\n\nimport type {\n AgentToolResult,\n ExtensionAPI,\n Text as HostText,\n Theme,\n ToolDefinition as OmpToolDefinition,\n ToolRenderResultOptions,\n} from \"@oh-my-pi/pi-coding-agent\";\n\nimport {\n invokeTool,\n sanitizeLine,\n wireSchema,\n type ToolDefinition,\n type ToolEffect,\n} from \"./index.ts\";\n\ntype TextComponent = typeof HostText;\ntype Component = ReturnType<NonNullable<OmpToolDefinition[\"renderCall\"]>>;\n\n/** The part of a host result a renderer reads. */\nexport interface OmpResultView {\n readonly details?: unknown;\n readonly isError?: boolean;\n}\n\n/** Per-tool renderer overrides, drawn with the host theme. */\nexport interface OmpRenderers {\n /** One-line summary of the arguments after the title. Sanitized by the adapter. */\n describeCall?(args: Readonly<Record<string, unknown>>): unknown;\n /** Short metadata after the badge, one entry per fact. Each entry is sanitized. */\n describeResult?(result: OmpResultView): readonly unknown[];\n /**\n * Replaces the result status line with the package's own component, such as\n * a bounded preview of long output. It owns sanitizing what it draws.\n */\n renderResult?: OmpToolDefinition[\"renderResult\"];\n}\n\nexport interface OmpToolOptions {\n /** The host `Text` component, imported by the extension from the package root. */\n readonly Text: TextComponent;\n /** Status-line renderers by tool name. */\n readonly renderers?: Readonly<Record<string, OmpRenderers>>;\n}\n\nconst APPROVAL: Record<ToolEffect, \"read\" | \"write\"> = {\n read: \"read\",\n write: \"write\",\n // OMP has no destructive tier; `exec` means running commands.\n destructive: \"write\",\n};\n\n/**\n * Registers every tool on the OMP extension API.\n *\n * The schema reaches OMP through `pi.typebox.Type.Unsafe`: the host-injected\n * build validates the raw JSON Schema with its full validator and emits the\n * document verbatim, so `pattern` and `maxProperties` survive. A standalone\n * omptype schema would drop both.\n *\n * @param pi - OMP extension API.\n * @param tools - Tools to register.\n * @param options - Host `Text` and optional renderers.\n */\nexport function registerOmpTools(\n pi: ExtensionAPI,\n tools: readonly ToolDefinition[],\n options: OmpToolOptions,\n): void {\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 async execute(_toolCallId, params, signal): Promise<AgentToolResult<unknown>> {\n // Returned as is: OMP reads `isError` from the object (`explicitError`).\n return await invokeTool(tool, params, signal ? { signal } : {});\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 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\n ? []\n : (renderers?.describeResult?.(result).map(sanitizeLine).filter(Boolean) ?? []);\n const meta = facts.length > 0 ? ` ${theme.fg(\"dim\", facts.join(theme.sep.dot))}` : \"\";\n return new Text(\n `${icon} ${theme.fg(\"accent\", sanitizeLine(tool.title))} ${badge}${meta}`,\n 0,\n 0,\n );\n },\n });\n }\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":";AAsDA,MAAM,WAAiD;CACrD,MAAM;CACN,OAAO;CAEP,aAAa;AACf;;;;;;;;;;;;GAcA,MAAgB,QAAA,aAEd,QACA,QACM;IACN,OAAQ,MAAA,WAAY,MAAA,QAAA,SAAA,EAAA,OAAA,IAAA,CAAA,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,MAAA,OAAU,OAAS,UAAK,MAAA,aAAA,gBAAA,OAAA,IAAA,MAAA,aAAA,eAAA,SAAA;IACxB,MAAM,EAAA,aAAQ,iBAAqB,MAA2C;IAE5E,MAAA,QAAa,MAAA,GAAA,UAAiB,GAAA,cAAmB,SAAO,KAAM,UAAA,cAAA;IAChE,MAAA,QAAA,OAAA,UAAA,CAAA,IAAA,WAAA,iBAAA,MAAA,CAAA,CAAA,IAAA,YAAA,CAAA,CAAA,OAAA,OAAA,KAAA,CAAA;IACA,MAAA,OAAW,MAAM,SAAA,IAAe,IAAA,MAAkB,GAAA,OAAA,MAAA,KAAA,MAAA,IAAA,GAAA,CAAA,MAAA;IAChD,OAAM,IAAA,KAAU,GAAA,KAAA,GAAW,MAAA,GAAA,UAAe,aAAa,KAAA,KAAU,CAAA,EAAA,GAAA,QAAkB,QAAI,GAAA,CAAA;GACvF;EACA,CAAA;CAKF;AACA;AAGE,SAAA,SAAa,SAAO,OAChB;CAEJ,IAAA,CAAA,QAAQ,WAAa,OAAA,MAAA,aAAuB,eAAA,SAAA;CAC5C,IAAA,QAAM,iBAAiB,KAAA,GAAU,OAAG,MAAA,aAAuB,kBAAe,OAAA;CAC1E,OAAA,MAAM,cAAe,QAChB,eACW,MAAA,cAAiB,WAAY,MAAA,aAAqB,kBAAa,QAAA;AAC/E;AAMF,SAAA"}
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"}
package/dist/pi.d.mts CHANGED
@@ -1,5 +1,8 @@
1
1
  import { ToolDefinition as ToolDefinition$1 } from "./index.mjs";
2
2
  import { ExtensionAPI, ToolDefinition } from "@earendil-works/pi-coding-agent";
3
+ type Component = ReturnType<NonNullable<ToolDefinition["renderCall"]>>;
4
+ /** The `Text` component of `@earendil-works/pi-tui`, which Pi resolves for every extension. */
5
+ export type PiTextComponent = new (text: string, paddingX: number, paddingY: number) => Component;
3
6
  export interface PiToolOptions {
4
7
  /**
5
8
  * How a returned `isError` result reaches Pi.
@@ -10,17 +13,33 @@ export interface PiToolOptions {
10
13
  * only with a peer range of `>=0.99.0`, since Pi does not check peer ranges.
11
14
  */
12
15
  readonly failures?: "throw" | "return";
13
- /** Host renderers by tool name, passed to Pi unchanged. */
16
+ /** Host `Text` from `@earendil-works/pi-tui`, which `describeCall` draws with. */
17
+ readonly Text?: PiTextComponent;
18
+ /** Renderers by tool name. */
14
19
  readonly renderers?: Readonly<Record<string, PiRenderers>>;
20
+ /** Questions to ask before a call runs, by tool name. A name off the tool list throws. */
21
+ readonly confirm?: Readonly<Record<string, PiConfirm>>;
22
+ }
23
+ /** Builds the question for one call from its validated input; `undefined` skips it. */
24
+ export type PiConfirm = (input: Readonly<Record<string, unknown>>) => PiQuestion | undefined | Promise<PiQuestion | undefined>;
25
+ /** What `ctx.ui.confirm` shows. The adapter sanitizes both and keeps the message's lines. */
26
+ export interface PiQuestion {
27
+ readonly title: string;
28
+ readonly message: string;
29
+ }
30
+ /** Renderers for one tool: Pi's own, passed unchanged, or a one-line call summary. */
31
+ export interface PiRenderers extends Readonly<Pick<ToolDefinition, "renderCall" | "renderResult">> {
32
+ /** One-line summary of the arguments after the title, sanitized here. A `renderCall` wins. */
33
+ readonly describeCall?: (args: Readonly<Record<string, unknown>>) => unknown;
15
34
  }
16
- /** The host's own call and result renderers for one tool. */
17
- export type PiRenderers = Pick<ToolDefinition, "renderCall" | "renderResult">;
18
35
  /**
19
36
  * Registers every tool on the Pi extension API.
20
37
  *
21
38
  * @param pi - Pi extension API.
22
39
  * @param tools - Tools to register.
23
- * @param options - Failure policy and renderers.
40
+ * @param options - Failure policy, host `Text`, renderers and questions.
41
+ * @throws {ToolDefinitionError} When two tools share a name, a tool has `describeCall` but no
42
+ * `Text` came with it, or `confirm` names a tool that isn't in the list.
24
43
  */
25
44
  export declare function registerPiTools(pi: ExtensionAPI, tools: readonly ToolDefinition$1[], options?: PiToolOptions): void;
26
45
  //# sourceMappingURL=pi.d.mts.map
package/dist/pi.d.mts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"pi.d.mts","names":["PiToolDefinition","ToolDefinition"],"sources":["../src/pi.ts"],"mappings":";;iBAeiB;;;;;;;;;WASN;;WAEA,YAAY,SAAS,eAAe;;;YAInC,cAAc,KAAKA;;;;;;;;wBASf,gBACd,IAAI,cACJ,gBAAgBC,oBAChB,UAAS"}
1
+ {"version":3,"file":"pi.d.mts","names":["PiToolDefinition","ToolDefinition"],"sources":["../src/pi.ts"],"mappings":";;KA4BK,YAAY,WAAW,YAAYA;;YAG5B,uBAAuB,cAAc,kBAAkB,qBAAqB;iBAEvE;;;;;;;;;WASN;;WAEA,OAAO;;WAEP,YAAY,SAAS,eAAe;;WAEpC,UAAU,SAAS,eAAe;;;YAIjC,aACV,OAAO,SAAS,6BACb,yBAAyB,QAAQ;;iBAGrB;WACN;WACA;;;iBAIM,oBAAoB,SACnC,KAAKA;;WAGI,gBAAgB,MAAM,SAAS;;;;;;;;;;;wBAY1B,gBACd,IAAI,cACJ,gBAAgBC,oBAChB,UAAS"}
package/dist/pi.mjs CHANGED
@@ -1,24 +1,58 @@
1
- import { invokeTool, resultText } from "./_chunks/src.mjs";
1
+ import { ToolDefinitionError, ToolInputError, indexTools, invokeTool, resultText, sanitizeLine, sanitizeText, validateInput } from "./_chunks/src.mjs";
2
+ import { hostContext } from "./_chunks/updates.mjs";
2
3
  function registerPiTools(pi, tools, options = {}) {
4
+ const listed = indexTools(tools);
3
5
  const failures = options.failures ?? "throw";
6
+ const stray = Object.keys(options.confirm ?? {}).find((name) => !listed.has(name));
7
+ if (stray !== void 0) throw new ToolDefinitionError(`confirm names ${JSON.stringify(stray)}, which isn't in the tool list`);
4
8
  for (const tool of tools) {
5
- const renderers = Object.hasOwn(options.renderers ?? {}, tool.name) ? options.renderers?.[tool.name] : void 0;
9
+ const renderers = byName(options.renderers, tool.name);
10
+ const ask = byName(options.confirm, tool.name);
6
11
  pi.registerTool({
7
- ...renderers,
12
+ ...hostRenderers(tool, renderers, options.Text),
8
13
  name: tool.name,
9
14
  label: tool.title,
10
15
  description: tool.description,
11
16
  ...tool.snippet === void 0 ? {} : { promptSnippet: tool.snippet },
12
17
  ...tool.guidelines === void 0 ? {} : { promptGuidelines: [...tool.guidelines] },
13
18
  parameters: tool.input,
14
- async execute(_toolCallId, params, signal) {
15
- const result = await invokeTool(tool, params, signal ? { signal } : {});
19
+ async execute(_toolCallId, params, signal, onUpdate, ctx) {
20
+ if (ask) await approve(tool, ask, params, signal, ctx);
21
+ const result = await invokeTool(tool, params, hostContext(signal, onUpdate));
16
22
  if (result.isError && failures === "throw") throw new Error(resultText(result));
17
23
  return result;
18
24
  }
19
25
  });
20
26
  }
21
27
  }
28
+ function byName(entries, name) {
29
+ return entries && Object.hasOwn(entries, name) ? entries[name] : void 0;
30
+ }
31
+ async function approve(tool, ask, params, signal, ctx) {
32
+ const checked = validateInput(tool, params);
33
+ if (!checked.ok) throw new ToolInputError(checked.lines);
34
+ const question = await ask(checked.value);
35
+ if (question === void 0) return;
36
+ if (!ctx.hasUI) throw new Error(`${tool.name} needs interactive approval in Pi TUI or RPC mode`);
37
+ const approved = await ctx.ui.confirm(sanitizeLine(question.title), sanitizeText(question.message), signal ? { signal } : {});
38
+ signal?.throwIfAborted();
39
+ if (!approved) throw new Error(`${tool.name} was cancelled by the user. Do not retry unless the user asks again.`);
40
+ }
41
+ function hostRenderers(tool, renderers, Text) {
42
+ if (!renderers) return {};
43
+ const { describeCall, ...own } = renderers;
44
+ if (own.renderCall || !describeCall) return own;
45
+ if (!Text) throw new ToolDefinitionError(`${tool.name}: describeCall needs the host Text option`);
46
+ const title = sanitizeLine(tool.title);
47
+ return {
48
+ ...own,
49
+ renderCall(args, theme) {
50
+ const summary = sanitizeLine(describeCall(args));
51
+ const header = theme.fg("toolTitle", theme.bold(title));
52
+ return new Text(summary ? `${header} ${theme.fg("muted", summary)}` : header, 0, 0);
53
+ }
54
+ };
55
+ }
22
56
  export { registerPiTools };
23
57
 
24
58
  //# sourceMappingURL=pi.mjs.map
package/dist/pi.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"pi.mjs","names":[],"sources":["../src/pi.ts"],"sourcesContent":["/**\n * Pi adapter: registers {@link ToolDefinition}s on a Pi `ExtensionAPI`.\n *\n * Only types come from `@earendil-works/pi-coding-agent`; nothing is imported\n * from the host at runtime.\n */\n\nimport type {\n AgentToolResult,\n ExtensionAPI,\n ToolDefinition as PiToolDefinition,\n} from \"@earendil-works/pi-coding-agent\";\n\nimport { invokeTool, resultText, type ToolDefinition } from \"./index.ts\";\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 renderers by tool name, passed to Pi unchanged. */\n readonly renderers?: Readonly<Record<string, PiRenderers>>;\n}\n\n/** The host's own call and result renderers for one tool. */\nexport type PiRenderers = Pick<PiToolDefinition, \"renderCall\" | \"renderResult\">;\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 and renderers.\n */\nexport function registerPiTools(\n pi: ExtensionAPI,\n tools: readonly ToolDefinition[],\n options: PiToolOptions = {},\n): void {\n const failures = options.failures ?? \"throw\";\n\n for (const tool of tools) {\n const renderers = Object.hasOwn(options.renderers ?? {}, tool.name)\n ? options.renderers?.[tool.name]\n : undefined;\n pi.registerTool({\n ...renderers,\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): Promise<AgentToolResult<unknown>> {\n const result = await invokeTool(tool, params, signal ? { signal } : {});\n if (result.isError && failures === \"throw\") throw new Error(resultText(result));\n return result;\n },\n });\n }\n}\n"],"mappings":";;;;;;;GAuCA,MAAgB,KAAA;GAKd,OAAM,KAAA;GAEN,aAAW,KAAQ;GACjB,GAAA,KAAM,YAAY,KAAO,IAAA,CAAA,IAAO,EAAA,eAAQ,KAAiB,QAAK;GAG9D,GAAG,KAAA,eAAa,KAAA,IAAA,CAAA,IAAA,EAAA,kBAAA,CAAA,GAAA,KAAA,UAAA,EAAA;GACd,YAAG,KAAA;GACH,MAAM,QAAK,aAAA,QAAA,QAAA;IACX,MAAO,SAAK,MAAA,WAAA,MAAA,QAAA,SAAA,EAAA,OAAA,IAAA,CAAA,CAAA;IACZ,IAAA,OAAA,WAAkB,aAAA,SAAA,MAAA,IAAA,MAAA,WAAA,MAAA,CAAA;IAClB,OAAS;GACT;EACA,CAAA;CACA;AACE;AAEA,SAAA"}
1
+ {"version":3,"file":"pi.mjs","names":[],"sources":["../src/pi.ts"],"sourcesContent":["/**\n * Pi adapter: registers {@link ToolDefinition}s on a Pi `ExtensionAPI`.\n *\n * Only types come from `@earendil-works/pi-coding-agent`; nothing is imported\n * from the host at runtime. A call line from `describeCall` needs the host\n * `Text`, which the extension passes in.\n */\n\nimport type {\n AgentToolResult,\n ExtensionAPI,\n ExtensionContext,\n ToolDefinition as PiToolDefinition,\n} from \"@earendil-works/pi-coding-agent\";\n\nimport { sanitizeText } from \"./escapes.ts\";\nimport {\n indexTools,\n invokeTool,\n resultText,\n sanitizeLine,\n ToolDefinitionError,\n ToolInputError,\n validateInput,\n type ToolDefinition,\n} from \"./index.ts\";\nimport { hostContext } from \"./updates.ts\";\n\ntype Component = ReturnType<NonNullable<PiToolDefinition[\"renderCall\"]>>;\n\n/** The `Text` component of `@earendil-works/pi-tui`, which Pi resolves for every extension. */\nexport type PiTextComponent = new (text: string, paddingX: number, paddingY: number) => Component;\n\nexport interface PiToolOptions {\n /**\n * How a returned `isError` result reaches Pi.\n *\n * `throw` (default) raises the result text: `pi-agent-core` up to 0.98 marks\n * every returned object as a success and records an error only after a throw.\n * `return` hands the result over unchanged and keeps its `details`; use it\n * only with a peer range of `>=0.99.0`, since Pi does not check peer ranges.\n */\n readonly failures?: \"throw\" | \"return\";\n /** Host `Text` from `@earendil-works/pi-tui`, which `describeCall` draws with. */\n readonly Text?: PiTextComponent;\n /** Renderers by tool name. */\n readonly renderers?: Readonly<Record<string, PiRenderers>>;\n /** Questions to ask before a call runs, by tool name. A name off the tool list throws. */\n readonly confirm?: Readonly<Record<string, PiConfirm>>;\n}\n\n/** Builds the question for one call from its validated input; `undefined` skips it. */\nexport type PiConfirm = (\n input: Readonly<Record<string, unknown>>,\n) => PiQuestion | undefined | Promise<PiQuestion | undefined>;\n\n/** What `ctx.ui.confirm` shows. The adapter sanitizes both and keeps the message's lines. */\nexport interface PiQuestion {\n readonly title: string;\n readonly message: string;\n}\n\n/** Renderers for one tool: Pi's own, passed unchanged, or a one-line call summary. */\nexport interface PiRenderers extends Readonly<\n Pick<PiToolDefinition, \"renderCall\" | \"renderResult\">\n> {\n /** One-line summary of the arguments after the title, sanitized here. A `renderCall` wins. */\n readonly describeCall?: (args: Readonly<Record<string, unknown>>) => unknown;\n}\n\n/**\n * Registers every tool on the Pi extension API.\n *\n * @param pi - Pi extension API.\n * @param tools - Tools to register.\n * @param options - Failure policy, host `Text`, renderers and questions.\n * @throws {ToolDefinitionError} When two tools share a name, a tool has `describeCall` but no\n * `Text` came with it, or `confirm` names a tool that isn't in the list.\n */\nexport function registerPiTools(\n pi: ExtensionAPI,\n tools: readonly ToolDefinition[],\n options: PiToolOptions = {},\n): void {\n const listed = indexTools(tools);\n const failures = options.failures ?? \"throw\";\n const stray = Object.keys(options.confirm ?? {}).find((name) => !listed.has(name));\n if (stray !== undefined) {\n throw new ToolDefinitionError(\n `confirm names ${JSON.stringify(stray)}, which isn't in the tool list`,\n );\n }\n\n for (const tool of tools) {\n const renderers = byName(options.renderers, tool.name);\n const ask = byName(options.confirm, tool.name);\n pi.registerTool({\n ...hostRenderers(tool, renderers, options.Text),\n name: tool.name,\n label: tool.title,\n description: tool.description,\n ...(tool.snippet === undefined ? {} : { promptSnippet: tool.snippet }),\n ...(tool.guidelines === undefined ? {} : { promptGuidelines: [...tool.guidelines] }),\n parameters: tool.input,\n async execute(_toolCallId, params, signal, onUpdate, ctx): Promise<AgentToolResult<unknown>> {\n if (ask) await approve(tool, ask, params, signal, ctx);\n const result = await invokeTool(tool, params, hostContext(signal, onUpdate));\n if (result.isError && failures === \"throw\") throw new Error(resultText(result));\n return result;\n },\n });\n }\n}\n\n/**\n * Own entry of a by-name option, so a tool named `constructor` doesn't reach the prototype.\n *\n * @param entries - Option keyed by tool name.\n * @param name - Tool name.\n * @returns {T | undefined} The entry, if the option has one for this tool.\n */\nfunction byName<T>(entries: Readonly<Record<string, T>> | undefined, name: string): T | undefined {\n return entries && Object.hasOwn(entries, name) ? entries[name] : undefined;\n}\n\n/**\n * Asks the user about one call and throws unless they say yes.\n *\n * @param tool - Tool being called.\n * @param ask - Its question builder.\n * @param params - Arguments as Pi passes them.\n * @param signal - The call's abort signal, which also dismisses the dialog.\n * @param ctx - Pi context of the call.\n * @returns {Promise<void>} Once the call may run.\n * @throws {ToolInputError} When the arguments fail the schema, before anyone is asked.\n * @throws {Error} Without a UI, on a \"no\", or with the reason of an abort.\n */\nasync function approve(\n tool: ToolDefinition,\n ask: PiConfirm,\n params: unknown,\n signal: AbortSignal | undefined,\n ctx: ExtensionContext,\n): Promise<void> {\n const checked = validateInput(tool, params);\n if (!checked.ok) throw new ToolInputError(checked.lines);\n const question = await ask(checked.value);\n if (question === undefined) return;\n if (!ctx.hasUI) throw new Error(`${tool.name} needs interactive approval in Pi TUI or RPC mode`);\n const approved = await ctx.ui.confirm(\n sanitizeLine(question.title),\n sanitizeText(question.message),\n signal ? { signal } : {},\n );\n signal?.throwIfAborted();\n if (!approved) {\n throw new Error(\n `${tool.name} was cancelled by the user. Do not retry unless the user asks again.`,\n );\n }\n}\n\n/**\n * The renderers Pi gets for one tool, with `describeCall` turned into a `renderCall`.\n *\n * @param tool - Tool being registered.\n * @param renderers - Its renderers, if any.\n * @param Text - Host `Text` component.\n * @returns {Pick<PiToolDefinition, \"renderCall\" | \"renderResult\">} What goes to `pi.registerTool`.\n * @throws {ToolDefinitionError} When `describeCall` would draw but `Text` is missing.\n */\nfunction hostRenderers(\n tool: ToolDefinition,\n renderers: PiRenderers | undefined,\n Text: PiTextComponent | undefined,\n): Pick<PiToolDefinition, \"renderCall\" | \"renderResult\"> {\n if (!renderers) return {};\n const { describeCall, ...own } = renderers;\n if (own.renderCall || !describeCall) return own;\n if (!Text) throw new ToolDefinitionError(`${tool.name}: describeCall needs the host Text option`);\n const title = sanitizeLine(tool.title);\n return {\n ...own,\n renderCall(args, theme): Component {\n const summary = sanitizeLine(describeCall(args as Readonly<Record<string, unknown>>));\n const header = theme.fg(\"toolTitle\", theme.bold(title));\n return new Text(summary ? `${header} ${theme.fg(\"muted\", summary)}` : header, 0, 0);\n },\n };\n}\n"],"mappings":";;;;;;;;;;EA+EA,GAAA,aAAgB;GAKd,GAAA,cAAe,MAAA,WAAgB,QAAA,IAAA;GAC/B,MAAM,KAAA;GACN,OAAM,KAAQ;GACd,aAAc,KAAA;GAMd,GAAK,KAAA,YAAc,KAAO,IAAA,CAAA,IAAA,EAAA,eAAA,KAAA,QAAA;GACxB,GAAA,KAAM,eAAY,KAAO,IAAQ,CAAA,IAAA,EAAA,kBAAoB,CAAA,GAAA,KAAA,UAAA,EAAA;GACrD,YAAY,KAAA;GACZ,MAAG,QAAA,aAAa,QAAA,QAAA,UAAA,KAAA;IACd,IAAG,KAAA,MAAA,QAAoB,MAAA,KAAW,QAAQ,QAAI,GAAA;IAC9C,MAAM,SAAK,MAAA,WAAA,MAAA,QAAA,YAAA,QAAA,QAAA,CAAA;IACX,IAAA,OAAY,WAAA,aAAA,SAAA,MAAA,IAAA,MAAA,WAAA,MAAA,CAAA;IACZ,OAAA;GACA;EACA,CAAA;CACA;AACA;AAEE,SAAA,OAAM,SAAe,MAAA;CACrB,OAAI,WAAO,OAAW,OAAA,SAAa,IAAA,IAAS,QAAU,QAAM,KAAA;AAC5D;AAEJ,eAAC,QAAA,MAAA,KAAA,QAAA,QAAA,KAAA;CACH,MAAA,UAAA,cAAA,MAAA,MAAA;CACF,IAAA,CAAA,QAAA,IAAA,MAAA,IAAA,eAAA,QAAA,KAAA;;;;;;;;AAUE,SAAO,cAAW,MAAO,WAAO,MAAa;CAC/C,IAAA,CAAA,WAAA,OAAA,CAAA;;;;;;;;;;;;;AAcA;AAQE,SAAK"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agntn/tools",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "One tool definition for MCP, Pi, OMP and the AI SDK",
5
5
  "homepage": "https://github.com/agntn/tools#readme",
6
6
  "bugs": "https://github.com/agntn/tools/issues",
@@ -24,6 +24,10 @@
24
24
  "types": "./dist/mcp.d.mts",
25
25
  "import": "./dist/mcp.mjs"
26
26
  },
27
+ "./h3": {
28
+ "types": "./dist/h3.d.mts",
29
+ "import": "./dist/h3.mjs"
30
+ },
27
31
  "./pi": {
28
32
  "types": "./dist/pi.d.mts",
29
33
  "import": "./dist/pi.mjs"
@@ -46,13 +50,15 @@
46
50
  },
47
51
  "devDependencies": {
48
52
  "@agntn/ox": "0.1.0",
49
- "@earendil-works/pi-coding-agent": "0.84.2",
53
+ "@earendil-works/pi-coding-agent": "1.0.1",
50
54
  "@modelcontextprotocol/client": "2.2.0",
51
55
  "@modelcontextprotocol/server": "2.2.0",
52
56
  "@oh-my-pi/pi-coding-agent": "18.0.0",
53
57
  "@types/node": "26.2.0",
54
- "ai": "7.0.126",
58
+ "ai": "7.0.127",
55
59
  "changelogen": "0.6.2",
60
+ "h3": "2.0.1",
61
+ "h3-mcp": "0.2.0",
56
62
  "obuild": "0.4.43",
57
63
  "typebox": "1.3.34",
58
64
  "typescript": "7.0.2",
@@ -60,10 +66,11 @@
60
66
  "vite-plus": "1.0.0"
61
67
  },
62
68
  "peerDependencies": {
63
- "@earendil-works/pi-coding-agent": ">=0.84.2 <1",
69
+ "@earendil-works/pi-coding-agent": ">=0.84.2 <2",
64
70
  "@modelcontextprotocol/server": ">=2.2.0 <3",
65
71
  "@oh-my-pi/pi-coding-agent": ">=18.0.0 <19",
66
- "ai": ">=7.0.0 <8"
72
+ "ai": ">=7.0.0 <8",
73
+ "h3-mcp": ">=0.2.0 <0.3"
67
74
  },
68
75
  "peerDependenciesMeta": {
69
76
  "@earendil-works/pi-coding-agent": {
@@ -77,18 +84,22 @@
77
84
  },
78
85
  "ai": {
79
86
  "optional": true
87
+ },
88
+ "h3-mcp": {
89
+ "optional": true
80
90
  }
81
91
  },
82
92
  "engines": {
83
- "node": ">=24"
93
+ "node": ">=26"
84
94
  },
85
95
  "scripts": {
86
96
  "build": "obuild",
87
97
  "lint": "vp lint && vp fmt --check",
88
98
  "lint:fix": "vp lint --fix && vp fmt",
89
99
  "typecheck": "tsc --noEmit --skipLibCheck",
100
+ "typecheck:dist": "tsc -p tsconfig.dist.json",
90
101
  "test": "vp test run",
91
102
  "test:watch": "vp test watch",
92
- "release": "pnpm test && pnpm build && changelogen --release --push"
103
+ "release": "pnpm test && pnpm build && pnpm typecheck:dist && changelogen --release --push"
93
104
  }
94
105
  }