@agntn/tools 0.3.2 โ†’ 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -5,18 +5,18 @@
5
5
  [![license](https://npmx.dev/api/registry/badge/license/@agntn/tools)](https://npmx.dev/package/@agntn/tools)
6
6
  [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/agntn/tools)
7
7
 
8
- ๐Ÿงฐ Four hosts, one definition. You write the tool once. MCP, Pi, OMP and the AI SDK each get it the way they like it.
8
+ ๐Ÿงฐ Five hosts, one definition. You write the tool once. MCP, Pi, OMP, OpenCode and the AI SDK each get it the way they like it.
9
9
 
10
- Want to watch it happen? [tools.agntn.dev](https://tools.agntn.dev) has the docs and a playground. One call, four hosts, all live in your tab.
10
+ Want to watch it happen? [tools.agntn.dev](https://tools.agntn.dev) has the docs and a playground. One call, MCP, Pi, OMP, OpenCode and the AI SDK, all live in your tab.
11
11
 
12
12
  ## Why?
13
13
 
14
- MCP wants an `inputSchema`. Pi wants `parameters` and a prompt snippet. OMP swaps your TypeBox for its own. The AI SDK wants yet another schema. So every tool lived in four files, and four files drift. Now it lives in one.
14
+ MCP wants an `inputSchema`. Pi wants `parameters` and a prompt snippet. OMP swaps your TypeBox for its own. The AI SDK wants yet another schema. So every tool lived in a file per host, and those files drift. Now it lives in one.
15
15
 
16
16
  ## โœจ Features
17
17
 
18
18
  - ๐Ÿ“ **One definition.** Name, schema, effect and `execute`. That's the whole tool.
19
- - ๐Ÿ”Œ **Four host adapters.** `createMcpServer`, `registerPiTools`, `registerOmpTools` and `toAiTool`. One call each.
19
+ - ๐Ÿ”Œ **Five host adapters.** `createMcpServer`, `registerPiTools`, `registerOmpTools`, `registerOpencodeTools` and `toAiTool`. One call each.
20
20
  - ๐Ÿ›ก๏ธ **Validation on every host.** The core checks each call before your code runs. Even when the host skips its own check.
21
21
  - ๐Ÿ—ฃ๏ธ **Errors a model can use.** A misspelled key names itself and the keys you do take. An enum lists its values.
22
22
  - ๐Ÿงต **One line per error.** Newlines, escape codes and bidi tricks in echoed text get flattened. No forged lines.
@@ -86,15 +86,17 @@ The typo never reached `execute`. The model gets told what it did wrong and what
86
86
 
87
87
  ## ๐Ÿค– Hosts
88
88
 
89
- | Host | Adapter | Peer |
90
- | ------ | -------------------------------------------- | ----------------------------------- |
91
- | MCP | `createMcpServer` from `@agntn/tools/mcp` | `@modelcontextprotocol/server` |
92
- | H3 | `toH3Tools` from `@agntn/tools/h3` | `h3-mcp` |
93
- | Docus | `toToolkitTools` from `@agntn/tools/toolkit` | `zod`, beside `@nuxtjs/mcp-toolkit` |
94
- | Pi | `registerPiTools` from `@agntn/tools/pi` | `@earendil-works/pi-coding-agent` |
95
- | OMP | `registerOmpTools` from `@agntn/tools/omp` | `@oh-my-pi/pi-coding-agent` |
96
- | AI SDK | `toAiTool` from `@agntn/tools/ai` | `ai` |
97
- | CLI | `runCli` from `@agntn/tools/cli` | none |
89
+ | Host | Adapter | Peer |
90
+ | -------- | ---------------------------------------------------- | ----------------------------------- |
91
+ | MCP | `createMcpServer` from `@agntn/tools/mcp` | `@modelcontextprotocol/server` |
92
+ | H3 | `toH3Tools` from `@agntn/tools/h3` | `h3-mcp` |
93
+ | Docus | `toToolkitTools` from `@agntn/tools/toolkit` | `zod`, beside `@nuxtjs/mcp-toolkit` |
94
+ | Pi | `registerPiTools` from `@agntn/tools/pi` | `@earendil-works/pi-coding-agent` |
95
+ | OMP | `registerOmpTools` from `@agntn/tools/omp` | `@oh-my-pi/pi-coding-agent` |
96
+ | OpenCode | `registerOpencodeTools` from `@agntn/tools/opencode` | `@opencode/plugin`, types only |
97
+ | AI SDK | `toAiTool` from `@agntn/tools/ai` | `ai` |
98
+ | CLI | `runCli` from `@agntn/tools/cli` | none |
99
+ | HTTP | `createHttpHandler` from `@agntn/tools/http` | none |
98
100
 
99
101
  Install only what you ship. An MCP server doesn't need the AI SDK, and nobody makes it pretend. Every host has its own page with the gotchas: [tools.agntn.dev/hosts](https://tools.agntn.dev/hosts).
100
102
 
@@ -14,12 +14,15 @@ function causeLines(error) {
14
14
  for (let depth = 0; depth < CAUSE_DEPTH && level !== void 0 && !seen.has(level); depth += 1) {
15
15
  seen.add(level);
16
16
  const text = causeText(level);
17
- if (text !== "" && !above.includes(text)) lines.push(`caused by: ${text}`);
18
- if (text !== "") above = text;
17
+ if (text !== "" && !alreadySaid(above, text)) lines.push(`caused by: ${text}`);
18
+ if (text !== "") above += `\n${text}`;
19
19
  level = nextCause(level);
20
20
  }
21
21
  return lines;
22
22
  }
23
+ function alreadySaid(above, text) {
24
+ return above.includes(text.length > CAUSE_LENGTH ? text.slice(0, CAUSE_LENGTH) : text);
25
+ }
23
26
  function nextCause(error) {
24
27
  if (!(error instanceof Error)) return void 0;
25
28
  if (error.cause !== void 0) return error.cause;
@@ -9,6 +9,13 @@ import { Static, TObject } from "./libs/typebox.mjs";
9
9
  * @returns {string} The text without escape sequences or other control characters.
10
10
  */
11
11
  export declare function sanitizeText(text: string): string;
12
+ /**
13
+ * Loads a module once and hands it out, but never to a call cancelled while it loaded.
14
+ *
15
+ * @param load - The `import()`, run again after a failure.
16
+ * @returns {(signal?: AbortSignal) => Promise<T>} The loader `execute` awaits.
17
+ */
18
+ export declare function lazy<T>(load: () => Promise<T>): (signal?: AbortSignal) => Promise<T>;
12
19
  /** Content block understood by MCP, Pi and OMP alike. */
13
20
  export type ToolContent = {
14
21
  type: "text";
@@ -26,7 +33,7 @@ export interface ToolResult<Details = unknown> {
26
33
  isError?: boolean;
27
34
  }
28
35
  /**
29
- * What a call does to the world, mapped to MCP annotations and OMP approval.
36
+ * What a call does to the world: MCP annotations, and approval on OMP, OpenCode and the AI SDK.
30
37
  *
31
38
  * - `read` changes nothing.
32
39
  * - `write` changes state that the next call can undo or overwrite.
@@ -53,10 +60,14 @@ export interface ToolCliHints {
53
60
  readonly plain?: readonly string[];
54
61
  /** Short flags by property, `{ limit: "n" }` for `-n 5`. Only a whole word counts. */
55
62
  readonly short?: Readonly<Record<string, string>>;
63
+ /** Old long flags by property, `{ family: ["type"] }` for `--type`. Positionals too. */
64
+ readonly flags?: Readonly<Record<string, readonly string[]>>;
56
65
  /** String properties that read stdin when given as `-`. */
57
66
  readonly stdin?: readonly string[];
58
67
  /** `false` takes `--json` away, for a command that writes its own bytes to stdout. */
59
68
  readonly json?: boolean;
69
+ /** `true` prints the text unsanitized, for a command whose product is invisible characters. */
70
+ readonly verbatim?: boolean;
60
71
  }
61
72
  /** How far a long call has come, for hosts that draw it. */
62
73
  export interface ToolProgress {
@@ -95,7 +106,7 @@ export interface Icon {
95
106
  }
96
107
  /** Per-call context the adapters hand to `execute`. */
97
108
  export interface ToolCallContext {
98
- /** On cancel a read answers at once and a write still waits. Pass it on so the work stops too. */
109
+ /** On cancel a read answers at once and a write still waits. Pass it on, `lazy` loaders too. */
99
110
  signal?: AbortSignal;
100
111
  /** Says the call is still at it. Absent where the host can't show it, so call `progress?.()`. */
101
112
  progress?: (message: string, amount?: ToolProgress) => void;
@@ -106,7 +117,10 @@ export interface ToolCallContext {
106
117
  * replayed, so ask before the first effect and in the same order every time.
107
118
  */
108
119
  ask?: ToolAsk;
109
- /** Pi's or OMP's `ctx`, the CLI's `CliHost`, MCP's `McpHost` or nothing. Narrow it yourself. */
120
+ /**
121
+ * Pi's or OMP's `ctx`, OpenCode's `ToolContext`, `CliHost`, `McpHost`, `HttpHost` or nothing.
122
+ * Narrow it yourself.
123
+ */
110
124
  host?: unknown;
111
125
  }
112
126
  export interface ToolDefinition<Input extends TObject = TObject, Details = unknown, Name extends string = string> {
@@ -116,7 +130,7 @@ export interface ToolDefinition<Input extends TObject = TObject, Details = unkno
116
130
  readonly title: string;
117
131
  /** Complete instruction for the model. MCP clients see nothing else. */
118
132
  readonly description: string;
119
- /** MCP `icons` in `tools/list`. Pi, OMP, the AI SDK and the CLI don't draw them. */
133
+ /** MCP `icons` in `tools/list`. Pi, OMP, OpenCode, the AI SDK and the CLI don't draw them. */
120
134
  readonly icons?: readonly Icon[];
121
135
  /** MCP `_meta` in `tools/list`, such as `ui` or `openai/extensions`. No other surface reads it. */
122
136
  readonly meta?: Readonly<Record<string, unknown>>;
@@ -156,6 +170,8 @@ export interface InputIssue {
156
170
  readonly problem: string;
157
171
  /** Required properties the value at `at` lacks, when that is the failure. */
158
172
  readonly missing?: readonly string[];
173
+ /** The way out of the whole failure, not of one key. Say it in `line` too. */
174
+ readonly hint?: string;
159
175
  }
160
176
  /** Thrown by {@link invokeTool} when the arguments fail the tool schema. */
161
177
  export declare class ToolInputError extends Error {
@@ -228,8 +244,9 @@ export declare function validateInput<Input extends TObject>(tool: ToolDefinitio
228
244
  *
229
245
  * Progress is best effort: a line after the call settles goes nowhere, and a host that throws on
230
246
  * one doesn't fail the call. The call answers once every question it started has settled, and a
231
- * question after that point rejects: nobody waits for the answer. A cancelled read doesn't wait
232
- * for anything and rejects with the abort reason. A write waits, since the host may have it.
247
+ * question after that point rejects: nobody waits for the answer. A call cancelled before it
248
+ * starts never runs. A cancelled read doesn't wait and rejects with the abort reason. A write
249
+ * waits, since the host may have it.
233
250
  *
234
251
  * @param tool - Tool to run.
235
252
  * @param args - Arguments as received from the host.
@@ -1,3 +1,4 @@
1
+ import "./libs/typebox.mjs";
1
2
  import { Icon, ToolCallContext, ToolDefinition } from "./index.mjs";
2
3
  import { CallToolResult, Tool, ToolAnnotations } from "@modelcontextprotocol/server";
3
4
  export interface McpServerInfo {
@@ -11,6 +12,8 @@ export interface McpServerInfo {
11
12
  readonly icons?: readonly Icon[];
12
13
  /** Project home a client can link to. */
13
14
  readonly websiteUrl?: string;
15
+ /** When to reach for these tools. Claude Code's tool search reads it before any tool. */
16
+ readonly instructions?: string;
14
17
  }
15
18
  /** What a tool finds in `host` over MCP. The client wrote all of it, so none of it is proof. */
16
19
  export interface McpHost {
@@ -70,8 +70,9 @@ function answer(tool, result) {
70
70
  };
71
71
  return errorResult(`${tool.name} returned details that don't match its output schema`, ...[...Errors(tool.output, result.details)].map((failure) => `at ${failure.instancePath || "/"}: ${failure.message}`));
72
72
  }
73
- function questionRound(responses, state) {
74
- const read = readState(state);
73
+ function questionRound(retry, form) {
74
+ const { responses } = retry;
75
+ const read = readState(retry.state);
75
76
  const answers = [...read.answers];
76
77
  const { asking } = read;
77
78
  const { promise: stopped, resolve: stop } = Promise.withResolvers();
@@ -93,7 +94,11 @@ function questionRound(responses, state) {
93
94
  };
94
95
  return answer;
95
96
  }
96
- pending = inputRequired(index, question, {
97
+ pending = inputRequired({
98
+ index,
99
+ question,
100
+ form
101
+ }, {
97
102
  answers: answers.slice(0, index),
98
103
  asking: print
99
104
  });
@@ -115,7 +120,7 @@ async function hold() {
115
120
  return await new Promise(() => {});
116
121
  }
117
122
  async function fingerprint(question) {
118
- const text = JSON.stringify([question.message, question.requested]);
123
+ const text = JSON.stringify([question.message, question.openai]);
119
124
  const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
120
125
  return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
121
126
  }
@@ -140,21 +145,37 @@ function quietOnQuestion(progress, round) {
140
145
  if (round.pending() === void 0) progress(message, amount);
141
146
  };
142
147
  }
143
- function inputRequired(index, question, state) {
144
- const { message, requested } = question;
148
+ function inputRequired(asking, state) {
149
+ const { index, question, form } = asking;
145
150
  return {
146
151
  resultType: "input_required",
147
- inputRequests: { [`ask-${index}`]: {
148
- method: "elicitation/create",
149
- params: {
150
- mode: "form",
151
- message,
152
- requestedSchema: requested
153
- }
154
- } },
152
+ inputRequests: { [`ask-${index}`]: elicitRequest(question, form) },
155
153
  requestState: JSON.stringify(state)
156
154
  };
157
155
  }
156
+ function elicitRequest(question, form) {
157
+ const { message } = question;
158
+ if (form === "mcp") return {
159
+ method: "elicitation/create",
160
+ params: {
161
+ mode: "form",
162
+ message,
163
+ requestedSchema: question.requested()
164
+ }
165
+ };
166
+ return {
167
+ method: "elicitation/create",
168
+ params: {
169
+ mode: "form",
170
+ message,
171
+ requestedSchema: {
172
+ type: "object",
173
+ properties: {}
174
+ },
175
+ _meta: { "openai/elicitation": { requestedSchema: question.openai } }
176
+ }
177
+ };
178
+ }
158
179
  function readState(state) {
159
180
  try {
160
181
  const { answers, asking } = JSON.parse(state ?? "{}") ?? {};
@@ -176,6 +197,31 @@ function canAsk(capabilities) {
176
197
  const modes = elicitation;
177
198
  return modes.form !== void 0 || modes.url === void 0;
178
199
  }
200
+ function askForm(capabilities) {
201
+ const { elicitation } = capabilities ?? {};
202
+ return fieldOf(elicitation, "form") !== void 0 && fillsOpenaiForms(capabilities) ? "openai" : "mcp";
203
+ }
204
+ const OPENAI_ELICIT = "openai/elicitation/create";
205
+ const ANSWER_TIMEOUT = 6e5;
206
+ function fillsOpenaiForms(capabilities) {
207
+ const { extensions } = capabilities ?? {};
208
+ return fieldOf(fieldOf(extensions, "openai/elicitation"), "form") !== void 0;
209
+ }
210
+ function openaiElicitRequest(question) {
211
+ const { message } = question;
212
+ const requestedSchema = question.openai;
213
+ return {
214
+ method: OPENAI_ELICIT,
215
+ params: {
216
+ mode: "form",
217
+ message,
218
+ requestedSchema
219
+ }
220
+ };
221
+ }
222
+ function fieldOf(value, key) {
223
+ return typeof value === "object" && value !== null ? value[key] : void 0;
224
+ }
179
225
  function progressSteps(notify) {
180
226
  let last;
181
227
  return (message, amount) => {
@@ -190,4 +236,4 @@ function progressSteps(notify) {
190
236
  });
191
237
  };
192
238
  }
193
- export { callAsking, callTool, canAsk, copyIcons, errorResult, listTools, mcpHost, progressSteps, questionRound, toolAnnotations };
239
+ export { ANSWER_TIMEOUT, OPENAI_ELICIT, askForm, callAsking, callTool, canAsk, copyIcons, errorResult, fillsOpenaiForms, listTools, mcpHost, openaiElicitRequest, progressSteps, questionRound, toolAnnotations };
@@ -15,11 +15,17 @@ const ROOT_KEYS = /* @__PURE__ */ new Set([
15
15
  "description"
16
16
  ]);
17
17
  function requestedSchema(question) {
18
+ return formOf(question, false);
19
+ }
20
+ function openaiSchema(question) {
21
+ return formOf(question, true);
22
+ }
23
+ function formOf(question, openai) {
18
24
  const root = JSON.parse(JSON.stringify(question.schema));
19
25
  if (!isRecord(root) || root.type !== "object" || !isRecord(root.properties)) throw new ToolDefinitionError("A question needs a Type.Object of fields");
20
26
  const extra = Object.keys(root).find((key) => !ROOT_KEYS.has(key));
21
27
  if (extra !== void 0) throw new ToolDefinitionError(`A question can't carry ${JSON.stringify(extra)} on its Type.Object: an MCP form has no place for it`);
22
- const properties = Object.fromEntries(Object.entries(root.properties).map(([key, field]) => [key, flatField(key, field)]));
28
+ const properties = Object.fromEntries(Object.entries(root.properties).map(([key, field]) => [key, flatField(key, field, openai)]));
23
29
  const required = Array.isArray(root.required) ? root.required.map(String) : [];
24
30
  return {
25
31
  type: "object",
@@ -27,22 +33,65 @@ function requestedSchema(question) {
27
33
  ...required.length > 0 ? { required } : {}
28
34
  };
29
35
  }
30
- function flatField(key, field) {
36
+ function flatField(key, field, openai) {
31
37
  if (isRecord(field)) {
32
38
  if (isStringEnum(field)) return cleanLabels({
33
39
  type: "string",
34
40
  ...field
35
41
  });
36
42
  if (typeof field.type === "string" && PRIMITIVES.has(field.type)) return cleanLabels(field);
37
- if (field.type === "array" && isRecord(field.items) && isStringEnum(field.items)) return cleanLabels({
38
- ...field,
39
- items: {
40
- type: "string",
41
- ...field.items
42
- }
43
- });
43
+ const several = field.type === "array" ? severalField(key, field, openai) : void 0;
44
+ if (several) return several;
44
45
  }
45
- throw new ToolDefinitionError(`Question field ${JSON.stringify(key)} must be a string, number, integer, boolean, Type.Enum of strings or an array of one`);
46
+ throw new ToolDefinitionError(`Question field ${JSON.stringify(key)} must be a string, number, integer, boolean, Type.Enum of strings, an array of one or a resource pick`);
47
+ }
48
+ function severalField(key, field, openai) {
49
+ const { items, "x-openai-input": input } = field;
50
+ if (!isRecord(items)) return void 0;
51
+ if (isStringEnum(items)) return cleanLabels({
52
+ ...field,
53
+ items: {
54
+ type: "string",
55
+ ...items
56
+ }
57
+ });
58
+ const options = items.type === "string" ? resourceOptions(input) : void 0;
59
+ if (!options) return void 0;
60
+ if (openai) return cleanLabels({
61
+ ...field,
62
+ "x-openai-input": {
63
+ ...input,
64
+ options
65
+ }
66
+ });
67
+ if (options.length === 0) throw new ToolDefinitionError(`Question field ${JSON.stringify(key)} needs options: only ChatGPT can pick a resource without one`);
68
+ const anyOf = options.map((option) => ({
69
+ const: option.uri,
70
+ title: resourceTitle(option)
71
+ }));
72
+ return cleanLabels({
73
+ ...withoutPicker(field),
74
+ ...implicitDefault(input, options),
75
+ items: { anyOf }
76
+ });
77
+ }
78
+ function implicitDefault(input, options) {
79
+ return isRecord(input) && input.selection === "implicit" ? { default: options.map((option) => option.uri) } : {};
80
+ }
81
+ function resourceOptions(input) {
82
+ if (!isRecord(input) || input.type !== "resource" || !Array.isArray(input.options)) return;
83
+ const options = input.options.map(cleanBranch);
84
+ return options.every(isResource) ? options : void 0;
85
+ }
86
+ function isResource(option) {
87
+ return isRecord(option) && typeof option.uri === "string";
88
+ }
89
+ function resourceTitle(option) {
90
+ const label = [option.title, option.name].find((value) => typeof value === "string");
91
+ return typeof label === "string" ? label : option.uri;
92
+ }
93
+ function withoutPicker(field) {
94
+ return Object.fromEntries(Object.entries(field).filter(([key]) => key !== "x-openai-input"));
46
95
  }
47
96
  function cleanLabels(field) {
48
97
  const labels = Object.fromEntries(["title", "description"].filter((key) => typeof field[key] === "string").map((key) => [key, sanitizeLine(field[key])]));
@@ -79,9 +128,11 @@ function hostAsk(ask) {
79
128
  message: sanitizeText(message),
80
129
  schema
81
130
  };
131
+ const openai = openaiSchema(question);
82
132
  const answer = readAnswer(question, await ask({
83
133
  ...question,
84
- requested: requestedSchema(question)
134
+ openai,
135
+ requested: () => requestedSchema(question)
85
136
  }));
86
137
  if (!answer) throw new Error("The answer doesn't fit the question");
87
138
  return answer;
@@ -17,6 +17,18 @@ function problemText(message, params) {
17
17
  const allowed = typeof params === "object" && params !== null ? params.allowedValues : void 0;
18
18
  return Array.isArray(allowed) ? `must be one of ${allowed.join(", ")}` : message;
19
19
  }
20
+ function lazy(load) {
21
+ let pending;
22
+ return async (signal) => {
23
+ pending ??= load().catch((error) => {
24
+ pending = void 0;
25
+ throw error;
26
+ });
27
+ const value = await pending;
28
+ signal?.throwIfAborted();
29
+ return value;
30
+ };
31
+ }
20
32
  var ToolDefinitionError = class extends Error {
21
33
  name = "ToolDefinitionError";
22
34
  };
@@ -178,8 +190,8 @@ function schemaAt(root, pointer) {
178
190
  async function invokeTool(tool, args, context = {}) {
179
191
  const checked = validateInput(tool, args);
180
192
  if (!checked.ok) throw new ToolInputError(checked.lines, checked.issues, tool.name);
193
+ context.signal?.throwIfAborted();
181
194
  const signal = tool.effect === "read" ? context.signal : void 0;
182
- signal?.throwIfAborted();
183
195
  const { progress, ask } = context;
184
196
  if (!progress && !ask) return await untilAborted(() => tool.execute(checked.value, context), signal);
185
197
  let settled = false;
@@ -243,4 +255,4 @@ function sanitizeLine(value) {
243
255
  function resultText(result) {
244
256
  return result.content.flatMap((block) => block.type === "text" ? [block.text] : []).join("\n");
245
257
  }
246
- export { ToolDefinitionError, ToolInputError, defineTool, indexTools, invokeTool, problemText, resultText, sanitizeLine, sanitizeText, validateInput, wireSchema };
258
+ export { ToolDefinitionError, ToolInputError, defineTool, indexTools, invokeTool, lazy, problemText, resultText, sanitizeLine, sanitizeText, validateInput, wireSchema };
@@ -21,11 +21,12 @@ function dialogsOf(host) {
21
21
  ].every((dialog) => typeof dialog === "function") ? ui : void 0;
22
22
  }
23
23
  async function fillForm(ui, question, signal) {
24
- const keys = Object.keys(question.requested.properties);
25
- const required = new Set(question.requested.required);
24
+ const requested = question.requested();
25
+ const keys = Object.keys(requested.properties);
26
+ const required = new Set(requested.required);
26
27
  const content = Object.create(null);
27
28
  for (const key of keys) {
28
- const field = question.requested.properties[key] ?? {};
29
+ const field = requested.properties[key] ?? {};
29
30
  const value = await askField({
30
31
  ui,
31
32
  title: sanitizeLine(keys.length === 1 ? question.message : `${question.message}: ${labelOf(key, field)}`),
@@ -60,8 +61,11 @@ async function promptOnce(prompt) {
60
61
  }
61
62
  function choicesOf(field) {
62
63
  if (Array.isArray(field.enum)) return [field.enum, field.enum.map(String)];
63
- if (!Array.isArray(field.oneOf)) return [[], []];
64
- const branches = field.oneOf.filter((branch) => typeof branch === "object" && branch !== null && "const" in branch);
64
+ return titledChoices(field.oneOf);
65
+ }
66
+ function titledChoices(titled) {
67
+ if (!Array.isArray(titled)) return [[], []];
68
+ const branches = titled.filter((branch) => typeof branch === "object" && branch !== null && "const" in branch);
65
69
  return [branches.map((branch) => branch.const), branches.map((branch) => String(typeof branch.title === "string" ? branch.title : branch.const))];
66
70
  }
67
71
  async function pick(prompt, values, labels) {
@@ -74,12 +78,13 @@ async function pick(prompt, values, labels) {
74
78
  return prompt.optional && index === values.length ? SKIP : chosen;
75
79
  }
76
80
  async function toggle(prompt) {
77
- const values = prompt.field.items.enum.map(String);
81
+ const items = prompt.field.items;
82
+ const [values, labels] = Array.isArray(items.enum) ? [items.enum.map(String), items.enum.map(String)] : titledChoices(items.anyOf);
78
83
  const picked = new Set(Array.isArray(prompt.field.default) ? prompt.field.default : []);
79
84
  const ends = prompt.optional ? [DONE_LABEL, SKIP_LABEL] : [DONE_LABEL];
80
85
  const ticked = () => values.filter((value) => picked.has(value));
81
86
  for (;;) {
82
- const lines = toggleLines(values, (value) => picked.has(value));
87
+ const lines = toggleLines(labels, (index) => picked.has(values[index]));
83
88
  const chosen = await prompt.ui.select(prompt.title, [...lines, ...ends], signalOption(prompt));
84
89
  const ending = endOfToggle(chosen, prompt.optional, ticked);
85
90
  if (ending !== void 0) return ending;
@@ -92,8 +97,8 @@ function endOfToggle(chosen, optional, ticked) {
92
97
  if (chosen === DONE_LABEL) return ticked();
93
98
  return optional && chosen === SKIP_LABEL ? SKIP : void 0;
94
99
  }
95
- function toggleLines(values, isPicked) {
96
- return distinct(values.map((value) => `${isPicked(value) ? "[x]" : "[ ]"} ${sanitizeLine(value)}`));
100
+ function toggleLines(labels, isPicked) {
101
+ return distinct(labels.map((label, index) => `${isPicked(index) ? "[x]" : "[ ]"} ${sanitizeLine(label)}`));
97
102
  }
98
103
  async function typeIn(prompt) {
99
104
  const { field } = prompt;
package/dist/ai.d.mts CHANGED
@@ -20,7 +20,8 @@ export type AiToolOutput<Details> = (Details extends object ? Details : {
20
20
  /**
21
21
  * Converts one tool, keeping its input and details types.
22
22
  *
23
- * A result with `isError` throws its text, which the AI SDK reports to the
23
+ * A tool whose `effect` isn't `read` waits for approval, unless the caller's `toolApproval`
24
+ * says otherwise. A result with `isError` throws its text, which the AI SDK reports to the
24
25
  * model as a tool error, the same as an executor that throws. The model reads
25
26
  * `text` and the images, as on every other host, not the details spelled out a second time.
26
27
  *
package/dist/ai.mjs CHANGED
@@ -5,6 +5,7 @@ function toAiTool(definition) {
5
5
  return tool({
6
6
  title: definition.title,
7
7
  description: definition.description,
8
+ needsApproval: definition.effect !== "read",
8
9
  inputSchema: jsonSchema(wireSchema(definition), { validate(value) {
9
10
  const checked = validateInput(definition, value);
10
11
  return checked.ok ? {