@agntn/tools 0.2.2 โ†’ 0.2.3

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.
Files changed (44) hide show
  1. package/README.md +10 -8
  2. package/dist/_chunks/index.d.mts +48 -4
  3. package/dist/_chunks/libs/typebox.d.mts +1 -2
  4. package/dist/_chunks/libs/typebox.mjs +0 -2
  5. package/dist/_chunks/mcp-answers.d.mts +2 -3
  6. package/dist/_chunks/mcp-answers.mjs +125 -9
  7. package/dist/_chunks/questions.mjs +93 -0
  8. package/dist/_chunks/src.mjs +78 -27
  9. package/dist/_chunks/updates.mjs +131 -2
  10. package/dist/ai.d.mts +4 -4
  11. package/dist/ai.mjs +12 -3
  12. package/dist/cli.d.mts +1 -2
  13. package/dist/cli.mjs +60 -17
  14. package/dist/h3.d.mts +3 -2
  15. package/dist/h3.mjs +15 -6
  16. package/dist/index.d.mts +2 -2
  17. package/dist/mcp.d.mts +5 -3
  18. package/dist/mcp.mjs +11 -6
  19. package/dist/omp.d.mts +1 -2
  20. package/dist/omp.mjs +0 -2
  21. package/dist/pi.d.mts +1 -2
  22. package/dist/pi.mjs +1 -3
  23. package/dist/toolkit.d.mts +78 -0
  24. package/dist/toolkit.mjs +62 -0
  25. package/package.json +13 -3
  26. package/dist/_chunks/index.d.mts.map +0 -1
  27. package/dist/_chunks/libs/typebox.d.mts.map +0 -1
  28. package/dist/_chunks/libs/typebox.mjs.map +0 -1
  29. package/dist/_chunks/mcp-answers.d.mts.map +0 -1
  30. package/dist/_chunks/mcp-answers.mjs.map +0 -1
  31. package/dist/_chunks/src.mjs.map +0 -1
  32. package/dist/_chunks/updates.mjs.map +0 -1
  33. package/dist/ai.d.mts.map +0 -1
  34. package/dist/ai.mjs.map +0 -1
  35. package/dist/cli.d.mts.map +0 -1
  36. package/dist/cli.mjs.map +0 -1
  37. package/dist/h3.d.mts.map +0 -1
  38. package/dist/h3.mjs.map +0 -1
  39. package/dist/mcp.d.mts.map +0 -1
  40. package/dist/mcp.mjs.map +0 -1
  41. package/dist/omp.d.mts.map +0 -1
  42. package/dist/omp.mjs.map +0 -1
  43. package/dist/pi.d.mts.map +0 -1
  44. package/dist/pi.mjs.map +0 -1
package/README.md CHANGED
@@ -23,6 +23,7 @@ MCP wants an `inputSchema`. Pi wants `parameters` and a prompt snippet. OMP swap
23
23
  - ๐Ÿชค **The OMP TypeBox trap, defused.** TypeBox is bundled, so OMP has nothing left to rewrite behind your back.
24
24
  - ๐Ÿงช **Schema rules at definition time.** An open object or a union of literals fails in `defineTool`. Not three weeks later in a model's hands.
25
25
  - โณ **Progress that gets somewhere.** `progress?.("still at it")` turns into `onUpdate` in Pi and OMP, `notifications/progress` in MCP and one live line in your terminal. A slow call stops looking like a dead one.
26
+ - ๐Ÿ™‹ **Ask the person, not the model.** `ask?.({ message, schema })` becomes MCP elicitation, or one dialog per field in Pi and OMP. Three puzzles match? Let them pick instead of letting the model guess.
26
27
  - โŒจ๏ธ **A CLI on the side.** `runCli` turns the same tools into commands, no CLI library needed. Flags come from the schema. Hints add positionals, short flags and stdin.
27
28
  - ๐ŸŒ **Runs anywhere.** No `node:*` import in the core or the host adapters. The docs site runs them in a browser tab. The CLI is the one Node part, as a CLI should be.
28
29
 
@@ -84,14 +85,15 @@ The typo never reached `execute`. The model gets told what it did wrong and what
84
85
 
85
86
  ## ๐Ÿค– Hosts
86
87
 
87
- | Host | Adapter | Peer |
88
- | ------ | ------------------------------------------ | --------------------------------- |
89
- | MCP | `createMcpServer` from `@agntn/tools/mcp` | `@modelcontextprotocol/server` |
90
- | H3 | `toH3Tools` from `@agntn/tools/h3` | `h3-mcp` |
91
- | Pi | `registerPiTools` from `@agntn/tools/pi` | `@earendil-works/pi-coding-agent` |
92
- | OMP | `registerOmpTools` from `@agntn/tools/omp` | `@oh-my-pi/pi-coding-agent` |
93
- | AI SDK | `toAiTool` from `@agntn/tools/ai` | `ai` |
94
- | CLI | `runCli` from `@agntn/tools/cli` | none |
88
+ | Host | Adapter | Peer |
89
+ | ------ | -------------------------------------------- | ----------------------------------- |
90
+ | MCP | `createMcpServer` from `@agntn/tools/mcp` | `@modelcontextprotocol/server` |
91
+ | H3 | `toH3Tools` from `@agntn/tools/h3` | `h3-mcp` |
92
+ | Docus | `toToolkitTools` from `@agntn/tools/toolkit` | `zod`, beside `@nuxtjs/mcp-toolkit` |
93
+ | Pi | `registerPiTools` from `@agntn/tools/pi` | `@earendil-works/pi-coding-agent` |
94
+ | OMP | `registerOmpTools` from `@agntn/tools/omp` | `@oh-my-pi/pi-coding-agent` |
95
+ | AI SDK | `toAiTool` from `@agntn/tools/ai` | `ai` |
96
+ | CLI | `runCli` from `@agntn/tools/cli` | none |
95
97
 
96
98
  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).
97
99
 
@@ -47,6 +47,8 @@ export interface ToolCliHints {
47
47
  readonly positional?: readonly string[];
48
48
  /** Words left after `positional`: joined by spaces into a string, one per item into an array. */
49
49
  readonly rest?: string;
50
+ /** Positionals no dashed word may fill, such as ids. One there fails as an unknown option. */
51
+ readonly plain?: readonly string[];
50
52
  /** Short flags by property, `{ limit: "n" }` for `-n 5`. Only a whole word counts. */
51
53
  readonly short?: Readonly<Record<string, string>>;
52
54
  /** String properties that read stdin when given as `-`. */
@@ -61,6 +63,22 @@ export interface ToolProgress {
61
63
  /** All the work there is, when the tool knows it. */
62
64
  readonly total?: number;
63
65
  }
66
+ /** A small form for the user: one message over flat fields, the shape MCP elicitation takes. */
67
+ export interface ToolQuestion<Schema extends TObject = TObject> {
68
+ /** What the user reads above the fields. Lines and tabs survive, escapes don't. */
69
+ readonly message: string;
70
+ /** Strings, numbers, booleans, `Type.Enum` picks and arrays of such an enum. Nothing nested. */
71
+ readonly schema: Schema;
72
+ }
73
+ /** What came back: the checked fields on `accept`, nothing on a "no" or a closed form. */
74
+ export type ToolAnswer<Content> = {
75
+ readonly action: "accept";
76
+ readonly content: Content;
77
+ } | {
78
+ readonly action: "decline" | "cancel";
79
+ };
80
+ /** Puts a {@link ToolQuestion} in front of the user and waits for the {@link ToolAnswer}. */
81
+ export type ToolAsk = <Schema extends TObject>(question: ToolQuestion<Schema>) => Promise<ToolAnswer<Static<Schema>>>;
64
82
  /** An MCP icon, the SDK's own shape: a URL or `data:` URI a client can draw on its card. */
65
83
  export interface Icon {
66
84
  readonly src: string;
@@ -75,6 +93,13 @@ export interface ToolCallContext {
75
93
  signal?: AbortSignal;
76
94
  /** Says the call is still at it. Absent where the host can't show it, so call `progress?.()`. */
77
95
  progress?: (message: string, amount?: ToolProgress) => void;
96
+ /**
97
+ * Asks the user and waits. Absent where nobody can answer, so check before calling.
98
+ *
99
+ * Over MCP the call starts over from the top for each answer, the earlier ones
100
+ * replayed, so ask before the first effect and in the same order every time.
101
+ */
102
+ ask?: ToolAsk;
78
103
  /** Pi's or OMP's own `ctx`, the CLI's `CliHost`, nothing elsewhere. Narrow it yourself. */
79
104
  host?: unknown;
80
105
  }
@@ -87,6 +112,10 @@ export interface ToolDefinition<Input extends TObject = TObject, Details = unkno
87
112
  readonly description: string;
88
113
  /** MCP `icons` in `tools/list`. Pi, OMP, the AI SDK and the CLI don't draw them. */
89
114
  readonly icons?: readonly Icon[];
115
+ /** MCP `_meta` in `tools/list`, such as `ui` or `openai/extensions`. No other surface reads it. */
116
+ readonly meta?: Readonly<Record<string, unknown>>;
117
+ /** Schema of `details`. MCP lists it as `outputSchema` and sends them as `structuredContent`. */
118
+ readonly output?: TObject;
90
119
  /** Pi `promptSnippet`. */
91
120
  readonly snippet?: string;
92
121
  /** Pi `promptGuidelines`. Must not promise anything `description` lacks. */
@@ -111,15 +140,29 @@ export interface ToolDefinition<Input extends TObject = TObject, Details = unkno
111
140
  export declare class ToolDefinitionError extends Error {
112
141
  name: string;
113
142
  }
143
+ /** One schema failure, with its place kept apart so a surface can name it in its own words. */
144
+ export interface InputIssue {
145
+ /** The line as {@link ToolInputError.lines} has it. */
146
+ readonly line: string;
147
+ /** JSON pointer of the failing value, empty for the arguments as a whole. */
148
+ readonly at: string;
149
+ /** What is wrong there, without the place. */
150
+ readonly problem: string;
151
+ /** Required properties the value at `at` lacks, when that is the failure. */
152
+ readonly missing?: readonly string[];
153
+ }
114
154
  /** Thrown by {@link invokeTool} when the arguments fail the tool schema. */
115
155
  export declare class ToolInputError extends Error {
116
156
  name: string;
117
157
  /** One validation failure per line. Only these line breaks are the core's own. */
118
158
  readonly lines: readonly string[];
159
+ /** The schema failures behind the lines, empty when the lines come from elsewhere. */
160
+ readonly issues: readonly InputIssue[];
119
161
  /**
120
162
  * @param lines - One validation failure per line.
163
+ * @param issues - The schema failures behind them, if any.
121
164
  */
122
- constructor(lines: readonly string[]);
165
+ constructor(lines: readonly string[], issues?: readonly InputIssue[]);
123
166
  }
124
167
  /**
125
168
  * Declares a tool and checks the schema rules every surface depends on.
@@ -154,6 +197,7 @@ export type InputCheck<Input extends TObject> = {
154
197
  } | {
155
198
  ok: false;
156
199
  lines: readonly string[];
200
+ issues: readonly InputIssue[];
157
201
  };
158
202
  /**
159
203
  * Validates arguments against the tool schema, reporting every failure.
@@ -174,7 +218,8 @@ export declare function validateInput<Input extends TObject>(tool: ToolDefinitio
174
218
  * Validates and runs a tool. Every adapter calls through here.
175
219
  *
176
220
  * Progress is best effort: a line after the call settles goes nowhere, and a host that throws on
177
- * one doesn't fail the call.
221
+ * one doesn't fail the call. The call answers once every question it started has settled, and a
222
+ * question after that point rejects: nobody waits for the answer.
178
223
  *
179
224
  * @param tool - Tool to run.
180
225
  * @param args - Arguments as received from the host.
@@ -201,5 +246,4 @@ export declare function sanitizeLine(value: unknown): string;
201
246
  * @param result - Tool result.
202
247
  * @returns {string} Text blocks joined by newlines.
203
248
  */
204
- export declare function resultText(result: ToolResult): string;
205
- //# sourceMappingURL=index.d.mts.map
249
+ export declare function resultText(result: ToolResult): string;
@@ -2478,5 +2478,4 @@ export declare function Script<Context extends TProperties, Script extends strin
2478
2478
  export declare function Script<Script extends string>(input: Script, options: TScriptOptions): TScript<{}, Script>;
2479
2479
  /** Parses a type from a TypeScript type expression */
2480
2480
  export declare function Script<Context extends TProperties, Script extends string>(context: Context, input: Script, options: TScriptOptions): TScript<Context, Script>;
2481
- export { BigInt$1 as BigInt, Capitalize$1 as Capitalize, Dependent$1 as Dependent, Exclude$1 as Exclude, Extract$1 as Extract, Integer$1 as Integer, Lowercase$1 as Lowercase, Number$1 as Number, Omit$1 as Omit, Parameter$1 as Parameter, Partial$1 as Partial, Pick$1 as Pick, Readonly$2 as Readonly, Record$1 as Record, Required$1 as Required, ReturnType$1 as ReturnType, String$1 as String, TBigInt$1 as TBigInt, TDependent$1 as TDependent, TDistribute$1 as TDistribute, TInteger$1 as TInteger, TNumber$1 as TNumber, TParameter$1 as TParameter, TReadonly$1 as TReadonly, TString$1 as TString, Uncapitalize$1 as Uncapitalize, Uppercase$1 as Uppercase, _Object_$1 as _Object_, index_d_exports, result_d_exports };
2482
- //# sourceMappingURL=typebox.d.mts.map
2481
+ export { BigInt$1 as BigInt, Capitalize$1 as Capitalize, Dependent$1 as Dependent, Exclude$1 as Exclude, Extract$1 as Extract, Integer$1 as Integer, Lowercase$1 as Lowercase, Number$1 as Number, Omit$1 as Omit, Parameter$1 as Parameter, Partial$1 as Partial, Pick$1 as Pick, Readonly$2 as Readonly, Record$1 as Record, Required$1 as Required, ReturnType$1 as ReturnType, String$1 as String, TBigInt$1 as TBigInt, TDependent$1 as TDependent, TDistribute$1 as TDistribute, TInteger$1 as TInteger, TNumber$1 as TNumber, TParameter$1 as TParameter, TReadonly$1 as TReadonly, TString$1 as TString, Uncapitalize$1 as Uncapitalize, Uppercase$1 as Uppercase, _Object_$1 as _Object_, index_d_exports, result_d_exports };
@@ -5639,5 +5639,3 @@ Union([
5639
5639
  })
5640
5640
  ]);
5641
5641
  export { Check, Errors, type_exports };
5642
-
5643
- //# sourceMappingURL=typebox.mjs.map
@@ -35,7 +35,7 @@ export declare function errorResult(...lines: readonly string[]): CallToolResult
35
35
  * The entries `tools/list` answers with, in the order given.
36
36
  *
37
37
  * @param tools - Tools to list.
38
- * @returns {Tool[]} Name, title, description, icons, schema and annotations of each tool.
38
+ * @returns {Tool[]} Name, title, description, icons, schemas, annotations and `_meta` of each tool.
39
39
  * @throws {ToolDefinitionError} When two tools share a name.
40
40
  */
41
41
  export declare function listTools(tools: readonly ToolDefinition[]): Tool[];
@@ -49,5 +49,4 @@ export declare function listTools(tools: readonly ToolDefinition[]): Tool[];
49
49
  * @param context - Context for this call, such as the request's abort signal.
50
50
  * @returns {Promise<CallToolResult>} The tool's text, or the sanitized error.
51
51
  */
52
- export declare function callTool(info: Pick<McpServerInfo, "name">, tools: readonly ToolDefinition[], name: string, args?: unknown, context?: ToolCallContext): Promise<CallToolResult>;
53
- //# sourceMappingURL=mcp-answers.d.mts.map
52
+ export declare function callTool(info: Pick<McpServerInfo, "name">, tools: readonly ToolDefinition[], name: string, args?: unknown, context?: ToolCallContext): Promise<CallToolResult>;
@@ -1,4 +1,6 @@
1
+ import { Check, Errors } from "./libs/typebox.mjs";
1
2
  import { ToolInputError, indexTools, invokeTool, sanitizeLine, wireSchema } from "./src.mjs";
3
+ import { hostAsk, readAnswer } from "./questions.mjs";
2
4
  function toolAnnotations(tool) {
3
5
  return {
4
6
  title: tool.title,
@@ -25,7 +27,9 @@ function listTools(tools) {
25
27
  description: tool.description,
26
28
  ...tool.icons === void 0 ? {} : { icons: copyIcons(tool.icons) },
27
29
  inputSchema: wireSchema(tool),
28
- annotations: toolAnnotations(tool)
30
+ ...tool.output === void 0 ? {} : { outputSchema: { ...tool.output } },
31
+ annotations: toolAnnotations(tool),
32
+ ...tool.meta === void 0 ? {} : { _meta: { ...tool.meta } }
29
33
  }));
30
34
  }
31
35
  function copyIcons(icons) {
@@ -38,16 +42,130 @@ async function callTool(info, tools, name, args = {}, context = {}) {
38
42
  const tool = tools.find((candidate) => candidate.name === name);
39
43
  if (!tool) return errorResult(`Unknown ${info.name} tool: ${JSON.stringify(name)}`);
40
44
  try {
41
- const result = await invokeTool(tool, args, context);
42
- return {
43
- content: result.content,
44
- ...result.isError === void 0 ? {} : { isError: result.isError }
45
- };
45
+ return answer(tool, await invokeTool(tool, args, context));
46
46
  } catch (error) {
47
47
  if (error instanceof ToolInputError) return errorResult(...error.lines);
48
48
  return errorResult(`${tool.name} failed: ${error instanceof Error ? error.message : String(error)}`);
49
49
  }
50
50
  }
51
+ function answer(tool, result) {
52
+ const content = {
53
+ content: result.content,
54
+ ...result.isError === void 0 ? {} : { isError: result.isError }
55
+ };
56
+ if (tool.output === void 0 || result.isError === true) return content;
57
+ if (Check(tool.output, result.details)) return {
58
+ ...content,
59
+ structuredContent: result.details
60
+ };
61
+ 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}`));
62
+ }
63
+ function questionRound(responses, state) {
64
+ const read = readState(state);
65
+ const answers = [...read.answers];
66
+ const { asking } = read;
67
+ const { promise: stopped, resolve: stop } = Promise.withResolvers();
68
+ let asked = 0;
69
+ let turn = Promise.resolve();
70
+ let pending;
71
+ const settle = async (index, question) => {
72
+ const print = await fingerprint(question);
73
+ if (pending !== void 0 || index > answers.length) return await hold();
74
+ const known = index < answers.length ? answers[index] : {
75
+ q: asking,
76
+ a: responses?.[`ask-${index}`]
77
+ };
78
+ const answer = known?.q === print ? readAnswer(question, known.a) : void 0;
79
+ if (answer) {
80
+ answers[index] = {
81
+ q: print,
82
+ a: answer
83
+ };
84
+ return answer;
85
+ }
86
+ pending = inputRequired(index, question, {
87
+ answers: answers.slice(0, index),
88
+ asking: print
89
+ });
90
+ stop();
91
+ return await hold();
92
+ };
93
+ return {
94
+ ask: hostAsk(async (question) => {
95
+ const index = asked++;
96
+ const reply = turn.then(async () => await settle(index, question));
97
+ turn = reply.catch(() => void 0);
98
+ return await reply;
99
+ }),
100
+ pending: () => pending,
101
+ stopped: async () => await stopped
102
+ };
103
+ }
104
+ async function hold() {
105
+ return await new Promise(() => {});
106
+ }
107
+ async function fingerprint(question) {
108
+ const text = JSON.stringify([question.message, question.requested]);
109
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
110
+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
111
+ }
112
+ async function callAsking(info, tools, name, args, context, round) {
113
+ if (!round) return await callTool(info, tools, name, args, context);
114
+ const halt = new AbortController();
115
+ const { progress, signal } = context;
116
+ const call = callTool(info, tools, name, args, {
117
+ ...context,
118
+ signal: signal ? AbortSignal.any([signal, halt.signal]) : halt.signal,
119
+ ...progress ? { progress: quietOnQuestion(progress, round) } : {},
120
+ ask: round.ask
121
+ });
122
+ const result = await Promise.race([call, round.stopped()]);
123
+ const pending = round.pending();
124
+ if (pending === void 0 && result !== void 0) return result;
125
+ halt.abort(/* @__PURE__ */ new Error("The call stopped to wait for the user"));
126
+ return pending ?? await call;
127
+ }
128
+ function quietOnQuestion(progress, round) {
129
+ return (message, amount) => {
130
+ if (round.pending() === void 0) progress(message, amount);
131
+ };
132
+ }
133
+ function inputRequired(index, question, state) {
134
+ const { message, requested } = question;
135
+ return {
136
+ resultType: "input_required",
137
+ inputRequests: { [`ask-${index}`]: {
138
+ method: "elicitation/create",
139
+ params: {
140
+ mode: "form",
141
+ message,
142
+ requestedSchema: requested
143
+ }
144
+ } },
145
+ requestState: JSON.stringify(state)
146
+ };
147
+ }
148
+ function readState(state) {
149
+ try {
150
+ const { answers, asking } = JSON.parse(state ?? "{}") ?? {};
151
+ return {
152
+ answers: Array.isArray(answers) ? answers.filter(isAnswered) : [],
153
+ ...typeof asking === "string" ? { asking } : {}
154
+ };
155
+ } catch {
156
+ return { answers: [] };
157
+ }
158
+ }
159
+ function isAnswered(entry) {
160
+ return typeof entry === "object" && entry !== null && typeof entry.q === "string";
161
+ }
162
+ function canAsk(capabilities) {
163
+ if (typeof capabilities !== "object" || capabilities === null) return false;
164
+ const { elicitation } = capabilities;
165
+ if (typeof elicitation !== "object" || elicitation === null) return false;
166
+ const modes = elicitation;
167
+ return modes.form !== void 0 || modes.url === void 0;
168
+ }
51
169
  function progressSteps(notify) {
52
170
  let last;
53
171
  return (message, amount) => {
@@ -62,6 +180,4 @@ function progressSteps(notify) {
62
180
  });
63
181
  };
64
182
  }
65
- export { callTool, copyIcons, errorResult, listTools, progressSteps, toolAnnotations };
66
-
67
- //# sourceMappingURL=mcp-answers.mjs.map
183
+ export { callAsking, callTool, canAsk, copyIcons, errorResult, listTools, progressSteps, questionRound, toolAnnotations };
@@ -0,0 +1,93 @@
1
+ import { Check } from "./libs/typebox.mjs";
2
+ import { ToolDefinitionError, sanitizeLine, sanitizeText } from "./src.mjs";
3
+ const PRIMITIVES = /* @__PURE__ */ new Set([
4
+ "string",
5
+ "number",
6
+ "integer",
7
+ "boolean"
8
+ ]);
9
+ const ROOT_KEYS = /* @__PURE__ */ new Set([
10
+ "type",
11
+ "properties",
12
+ "required",
13
+ "additionalProperties",
14
+ "title",
15
+ "description"
16
+ ]);
17
+ function requestedSchema(question) {
18
+ const root = JSON.parse(JSON.stringify(question.schema));
19
+ if (!isRecord(root) || root.type !== "object" || !isRecord(root.properties)) throw new ToolDefinitionError("A question needs a Type.Object of fields");
20
+ const extra = Object.keys(root).find((key) => !ROOT_KEYS.has(key));
21
+ 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)]));
23
+ const required = Array.isArray(root.required) ? root.required.map(String) : [];
24
+ return {
25
+ type: "object",
26
+ properties,
27
+ ...required.length > 0 ? { required } : {}
28
+ };
29
+ }
30
+ function flatField(key, field) {
31
+ if (isRecord(field)) {
32
+ if (isStringEnum(field)) return cleanLabels({
33
+ type: "string",
34
+ ...field
35
+ });
36
+ 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
+ });
44
+ }
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
+ }
47
+ function cleanLabels(field) {
48
+ const labels = Object.fromEntries(["title", "description"].filter((key) => typeof field[key] === "string").map((key) => [key, sanitizeLine(field[key])]));
49
+ const branches = Object.fromEntries(["oneOf", "anyOf"].filter((key) => Array.isArray(field[key])).map((key) => [key, field[key].map(cleanBranch)]));
50
+ const items = isRecord(field.items) ? { items: cleanLabels(field.items) } : {};
51
+ return {
52
+ ...field,
53
+ ...labels,
54
+ ...branches,
55
+ ...items
56
+ };
57
+ }
58
+ function cleanBranch(branch) {
59
+ return isRecord(branch) ? cleanLabels(branch) : branch;
60
+ }
61
+ function isStringEnum(node) {
62
+ return Array.isArray(node.enum) && node.enum.length > 0 && node.enum.every((value) => typeof value === "string") && (node.type === void 0 || node.type === "string");
63
+ }
64
+ function readAnswer(question, reply) {
65
+ const { schema } = question;
66
+ if (!isRecord(reply)) return void 0;
67
+ if (reply.action === "decline" || reply.action === "cancel") return { action: reply.action };
68
+ if (reply.action !== "accept") return void 0;
69
+ const given = isRecord(reply.content) ? reply.content : {};
70
+ const content = Object.fromEntries(Object.keys(schema.properties).filter((key) => Object.hasOwn(given, key)).map((key) => [key, given[key]]));
71
+ return Check(schema, content) ? {
72
+ action: "accept",
73
+ content
74
+ } : void 0;
75
+ }
76
+ function hostAsk(ask) {
77
+ return async ({ message, schema }) => {
78
+ const question = {
79
+ message: sanitizeText(message),
80
+ schema
81
+ };
82
+ const answer = readAnswer(question, await ask({
83
+ ...question,
84
+ requested: requestedSchema(question)
85
+ }));
86
+ if (!answer) throw new Error("The answer doesn't fit the question");
87
+ return answer;
88
+ };
89
+ }
90
+ function isRecord(value) {
91
+ return typeof value === "object" && value !== null && !Array.isArray(value);
92
+ }
93
+ export { hostAsk, readAnswer };
@@ -13,15 +13,21 @@ const FORGING = /[\u0000-\u0008\u000B-\u001F\u007F-\u009F\u061C\u200E\u200F\u202
13
13
  function sanitizeText(text) {
14
14
  return stripEscapes(text.replaceAll(/\r\n?/g, "\n")).replaceAll(FORGING, "").replaceAll(/[\u2028\u2029]/g, " ");
15
15
  }
16
+ function problemText(message, params) {
17
+ const allowed = typeof params === "object" && params !== null ? params.allowedValues : void 0;
18
+ return Array.isArray(allowed) ? `must be one of ${allowed.join(", ")}` : message;
19
+ }
16
20
  var ToolDefinitionError = class extends Error {
17
21
  name = "ToolDefinitionError";
18
22
  };
19
23
  var ToolInputError = class extends Error {
20
24
  name = "ToolInputError";
21
25
  lines;
22
- constructor(lines) {
26
+ issues;
27
+ constructor(lines, issues = []) {
23
28
  super(lines.join("\n"));
24
29
  this.lines = lines;
30
+ this.issues = issues;
25
31
  }
26
32
  };
27
33
  const TOOL_NAME = /^[a-z][a-z0-9_]{0,63}$/;
@@ -29,8 +35,12 @@ function defineTool(tool) {
29
35
  if (!TOOL_NAME.test(tool.name)) throw new ToolDefinitionError(`Tool name ${JSON.stringify(tool.name)} must match ${TOOL_NAME}`);
30
36
  if (typeof tool.input !== "object" || tool.input === null) throw new ToolDefinitionError(`${tool.name}: input must be a JSON Schema object; build it with Type from @agntn/tools, not from "typebox"`);
31
37
  assertSchema(tool.name, wireSchema(tool));
38
+ if (tool.output !== void 0 && !isObjectSchema(tool.output)) throw new ToolDefinitionError(`${tool.name}: output must be a JSON Schema object of type "object"; build it with Type.Object from @agntn/tools`);
32
39
  return tool;
33
40
  }
41
+ function isObjectSchema(schema) {
42
+ return isNode(schema) && schema.type === "object";
43
+ }
34
44
  function assertSchema(toolName, node, path = "") {
35
45
  const at = path || "/";
36
46
  if (isOpenObject(node)) throw new ToolDefinitionError(`${toolName}: object at ${at} must be closed with additionalProperties: false`);
@@ -75,26 +85,40 @@ function validateInput(tool, args) {
75
85
  value: args
76
86
  };
77
87
  const schema = wireSchema(tool);
78
- const unknown = (args !== null && typeof args === "object" && !Array.isArray(args) ? Object.keys(args).filter((key) => !Object.hasOwn(tool.input.properties, key)) : []).map((key) => unknownKeyLine("", key, [schema]));
88
+ const unknown = (args !== null && typeof args === "object" && !Array.isArray(args) ? Object.keys(args).filter((key) => !Object.hasOwn(tool.input.properties, key)) : []).map((key) => unknownKeyIssue("", key, [schema]));
79
89
  const other = [];
80
90
  for (const error of Errors(tool.input, args)) {
81
91
  if (error.keyword === "additionalProperties") continue;
82
- const refused = refusedKeyLines(schema, error.instancePath, error.schemaPath);
83
- if (refused === void 0) other.push(errorLine(error.instancePath, error.message, error.params));
92
+ const refused = refusedKeyIssues(schema, error.instancePath, error.schemaPath);
93
+ if (refused === void 0) other.push(errorIssue(error.instancePath, error.message, error.params));
84
94
  else unknown.push(...refused);
85
95
  }
86
- const lines = [...unknown, ...other];
96
+ const issues = [...new Map([...unknown, ...other].map((issue) => [issue.line, issue])).values()];
97
+ if (issues.length === 0) return {
98
+ ok: false,
99
+ lines: ["Invalid arguments"],
100
+ issues
101
+ };
87
102
  return {
88
103
  ok: false,
89
- lines: lines.length > 0 ? [...new Set(lines)] : ["Invalid arguments"]
104
+ lines: issues.map((issue) => issue.line),
105
+ issues
90
106
  };
91
107
  }
92
- function errorLine(at, message, params) {
93
- const allowed = isNode(params) ? params.allowedValues : void 0;
94
- const text = Array.isArray(allowed) ? `must be one of ${allowed.join(", ")}` : message;
95
- return `Invalid arguments at ${at || "/"}: ${text}`;
108
+ function errorIssue(at, message, params) {
109
+ const problem = problemText(message, params);
110
+ const issue = {
111
+ line: `Invalid arguments at ${at || "/"}: ${problem}`,
112
+ at,
113
+ problem
114
+ };
115
+ const missing = isNode(params) ? params.requiredProperties : void 0;
116
+ return Array.isArray(missing) ? {
117
+ ...issue,
118
+ missing: missing.map(String)
119
+ } : issue;
96
120
  }
97
- function refusedKeyLines(root, at, schemaPath) {
121
+ function refusedKeyIssues(root, at, schemaPath) {
98
122
  if (!schemaPath.endsWith("/additionalProperties")) return void 0;
99
123
  const objectPath = schemaPath.slice(0, -21);
100
124
  if (schemaAt(root, objectPath)?.additionalProperties !== false) return void 0;
@@ -102,7 +126,7 @@ function refusedKeyLines(root, at, schemaPath) {
102
126
  const key = unescapeToken(at.slice(cut + 1));
103
127
  const alternatives = alternativesAt(root, objectPath);
104
128
  if (alternatives.some((alternative) => takesKey(alternative, key))) return [];
105
- return [unknownKeyLine(at.slice(0, cut), key, alternatives)];
129
+ return [unknownKeyIssue(at.slice(0, cut), key, alternatives)];
106
130
  }
107
131
  function alternativesAt(root, pointer) {
108
132
  let nodes = [root];
@@ -130,12 +154,16 @@ function takesKey(node, key) {
130
154
  function patternsOf(node) {
131
155
  return Object.keys(isNode(node.patternProperties) ? node.patternProperties : {});
132
156
  }
133
- function unknownKeyLine(at, key, objects) {
157
+ function unknownKeyIssue(at, key, objects) {
134
158
  const lists = [...new Set(objects.filter((object) => object.type === "object").map((object) => [...Object.keys(isNode(object.properties) ? object.properties : {}), ...patternsOf(object).map((pattern) => `keys matching ${JSON.stringify(pattern)}`)].join(", ")))];
135
159
  const takes = lists.length > 1 ? lists.map((list) => `{${list}}`).join(" or ") : lists[0];
136
160
  const where = at === "" ? "" : ` at ${at}`;
137
- const what = takes || "no properties";
138
- return `Invalid arguments${where}: unknown property ${JSON.stringify(key)}; takes ${what}`;
161
+ const problem = `unknown property ${JSON.stringify(key)}; takes ${takes || "no properties"}`;
162
+ return {
163
+ line: `Invalid arguments${where}: ${problem}`,
164
+ at,
165
+ problem
166
+ };
139
167
  }
140
168
  function schemaAt(root, pointer) {
141
169
  let node = root;
@@ -147,24 +175,49 @@ function schemaAt(root, pointer) {
147
175
  }
148
176
  async function invokeTool(tool, args, context = {}) {
149
177
  const checked = validateInput(tool, args);
150
- if (!checked.ok) throw new ToolInputError(checked.lines);
151
- const { progress } = context;
152
- if (!progress) return await tool.execute(checked.value, context);
178
+ if (!checked.ok) throw new ToolInputError(checked.lines, checked.issues);
179
+ const { progress, ask } = context;
180
+ if (!progress && !ask) return await tool.execute(checked.value, context);
153
181
  let settled = false;
182
+ const questions = ask ? closedAfter(tool, ask, () => settled) : void 0;
154
183
  try {
155
184
  return await tool.execute(checked.value, {
156
185
  ...context,
157
- progress(message, amount) {
158
- if (settled) return;
159
- try {
160
- progress(sanitizeLine(message), amount);
161
- } catch {}
162
- }
186
+ ...progress ? { progress: quietAfter(progress, () => settled) } : {},
187
+ ...questions ? { ask: questions.ask } : {}
163
188
  });
164
189
  } finally {
190
+ await questions?.drained();
165
191
  settled = true;
166
192
  }
167
193
  }
194
+ function quietAfter(progress, settled) {
195
+ return (message, amount) => {
196
+ if (settled()) return;
197
+ try {
198
+ progress(sanitizeLine(message), amount);
199
+ } catch {}
200
+ };
201
+ }
202
+ function closedAfter(tool, ask, settled) {
203
+ const open = /* @__PURE__ */ new Set();
204
+ const asked = async (question) => {
205
+ if (settled()) throw new Error(`${tool.name} asked a question after its call had answered`);
206
+ return await ask(question);
207
+ };
208
+ return {
209
+ ask: (question) => {
210
+ const answer = asked(question);
211
+ const release = () => void open.delete(answer);
212
+ open.add(answer);
213
+ answer.then(release, release);
214
+ return answer;
215
+ },
216
+ drained: async () => {
217
+ while (open.size > 0) await Promise.allSettled(open);
218
+ }
219
+ };
220
+ }
168
221
  const LINE_BREAKING = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu;
169
222
  function sanitizeLine(value) {
170
223
  return stripEscapes(String(value)).replaceAll(LINE_BREAKING, " ").replaceAll(/ {2,}/g, " ").trim();
@@ -172,6 +225,4 @@ function sanitizeLine(value) {
172
225
  function resultText(result) {
173
226
  return result.content.flatMap((block) => block.type === "text" ? [block.text] : []).join("\n");
174
227
  }
175
- export { ToolDefinitionError, ToolInputError, defineTool, indexTools, invokeTool, resultText, sanitizeLine, sanitizeText, validateInput, wireSchema };
176
-
177
- //# sourceMappingURL=src.mjs.map
228
+ export { ToolDefinitionError, ToolInputError, defineTool, indexTools, invokeTool, problemText, resultText, sanitizeLine, sanitizeText, validateInput, wireSchema };