@agntn/tools 0.3.3 โ 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -13
- package/dist/_chunks/index.d.mts +24 -7
- package/dist/_chunks/mcp-answers.d.mts +3 -1
- package/dist/_chunks/mcp-answers.mjs +68 -25
- package/dist/_chunks/outputs.mjs +22 -0
- package/dist/_chunks/questions.mjs +62 -11
- package/dist/_chunks/src.mjs +14 -2
- package/dist/_chunks/updates.mjs +14 -9
- package/dist/ai.d.mts +2 -1
- package/dist/ai.mjs +1 -0
- package/dist/cli.mjs +78 -39
- package/dist/h3.mjs +6 -2
- package/dist/http.d.mts +79 -0
- package/dist/http.mjs +247 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +2 -2
- package/dist/mcp.d.mts +11 -2
- package/dist/mcp.mjs +56 -11
- package/dist/opencode.d.mts +14 -0
- package/dist/opencode.mjs +73 -0
- package/dist/pi.mjs +20 -1
- package/dist/stdio.d.mts +11 -0
- package/dist/stdio.mjs +64 -0
- package/dist/toolkit.d.mts +33 -10
- package/dist/toolkit.mjs +41 -9
- package/package.json +21 -4
package/README.md
CHANGED
|
@@ -5,18 +5,18 @@
|
|
|
5
5
|
[](https://npmx.dev/package/@agntn/tools)
|
|
6
6
|
[](https://deepwiki.com/agntn/tools)
|
|
7
7
|
|
|
8
|
-
๐งฐ
|
|
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,
|
|
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
|
|
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
|
-
- ๐ **
|
|
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
|
|
90
|
-
|
|
|
91
|
-
| MCP
|
|
92
|
-
| H3
|
|
93
|
-
| Docus
|
|
94
|
-
| Pi
|
|
95
|
-
| OMP
|
|
96
|
-
|
|
|
97
|
-
|
|
|
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
|
|
package/dist/_chunks/index.d.mts
CHANGED
|
@@ -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
|
|
36
|
+
* What a call does to the world: MCP and Pi annotations, 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
|
|
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
|
-
/**
|
|
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,11 +130,11 @@ 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>>;
|
|
123
|
-
/** Schema of `details
|
|
137
|
+
/** Schema of `details`, which MCP and Pi send as `structuredContent` under its `outputSchema`. */
|
|
124
138
|
readonly output?: TObject;
|
|
125
139
|
/** Pi `promptSnippet`. */
|
|
126
140
|
readonly snippet?: string;
|
|
@@ -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
|
|
232
|
-
*
|
|
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 {
|
|
@@ -22,7 +25,6 @@ export interface McpHost {
|
|
|
22
25
|
}
|
|
23
26
|
/**
|
|
24
27
|
* Maps a tool's title and declared effect to MCP annotations. Claude Code reads its label here.
|
|
25
|
-
* A process the tool starts can delete anything, so `exec` counts as destructive.
|
|
26
28
|
*
|
|
27
29
|
* @param tool - Tool to describe.
|
|
28
30
|
* @returns {ToolAnnotations} Title and hints for the MCP client.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { Check, Errors } from "./libs/typebox.mjs";
|
|
2
1
|
import { ToolInputError, indexTools, invokeTool, sanitizeLine, wireSchema } from "./src.mjs";
|
|
3
2
|
import { causeLines } from "./causes.mjs";
|
|
3
|
+
import { checkDetails, toolHints } from "./outputs.mjs";
|
|
4
4
|
import { hostAsk, readAnswer } from "./questions.mjs";
|
|
5
5
|
function mcpHost(from) {
|
|
6
6
|
const { request, meta } = from;
|
|
@@ -14,10 +14,7 @@ function mcpHost(from) {
|
|
|
14
14
|
function toolAnnotations(tool) {
|
|
15
15
|
return {
|
|
16
16
|
title: tool.title,
|
|
17
|
-
|
|
18
|
-
destructiveHint: tool.effect === "destructive" || tool.effect === "exec",
|
|
19
|
-
idempotentHint: tool.idempotent ?? tool.effect === "read",
|
|
20
|
-
openWorldHint: tool.openWorld ?? false
|
|
17
|
+
...toolHints(tool)
|
|
21
18
|
};
|
|
22
19
|
}
|
|
23
20
|
function errorResult(...lines) {
|
|
@@ -63,15 +60,16 @@ function answer(tool, result) {
|
|
|
63
60
|
content: result.content,
|
|
64
61
|
...result.isError === void 0 ? {} : { isError: result.isError }
|
|
65
62
|
};
|
|
66
|
-
|
|
67
|
-
if (
|
|
63
|
+
const checked = result.isError === true ? void 0 : checkDetails(tool, result.details);
|
|
64
|
+
if (checked === void 0) return content;
|
|
65
|
+
return checked.ok ? {
|
|
68
66
|
...content,
|
|
69
|
-
structuredContent:
|
|
70
|
-
};
|
|
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}`));
|
|
67
|
+
structuredContent: checked.value
|
|
68
|
+
} : errorResult(...checked.lines);
|
|
72
69
|
}
|
|
73
|
-
function questionRound(
|
|
74
|
-
const
|
|
70
|
+
function questionRound(retry, form) {
|
|
71
|
+
const { responses } = retry;
|
|
72
|
+
const read = readState(retry.state);
|
|
75
73
|
const answers = [...read.answers];
|
|
76
74
|
const { asking } = read;
|
|
77
75
|
const { promise: stopped, resolve: stop } = Promise.withResolvers();
|
|
@@ -93,7 +91,11 @@ function questionRound(responses, state) {
|
|
|
93
91
|
};
|
|
94
92
|
return answer;
|
|
95
93
|
}
|
|
96
|
-
pending = inputRequired(
|
|
94
|
+
pending = inputRequired({
|
|
95
|
+
index,
|
|
96
|
+
question,
|
|
97
|
+
form
|
|
98
|
+
}, {
|
|
97
99
|
answers: answers.slice(0, index),
|
|
98
100
|
asking: print
|
|
99
101
|
});
|
|
@@ -115,7 +117,7 @@ async function hold() {
|
|
|
115
117
|
return await new Promise(() => {});
|
|
116
118
|
}
|
|
117
119
|
async function fingerprint(question) {
|
|
118
|
-
const text = JSON.stringify([question.message, question.
|
|
120
|
+
const text = JSON.stringify([question.message, question.openai]);
|
|
119
121
|
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
|
|
120
122
|
return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
121
123
|
}
|
|
@@ -140,21 +142,37 @@ function quietOnQuestion(progress, round) {
|
|
|
140
142
|
if (round.pending() === void 0) progress(message, amount);
|
|
141
143
|
};
|
|
142
144
|
}
|
|
143
|
-
function inputRequired(
|
|
144
|
-
const {
|
|
145
|
+
function inputRequired(asking, state) {
|
|
146
|
+
const { index, question, form } = asking;
|
|
145
147
|
return {
|
|
146
148
|
resultType: "input_required",
|
|
147
|
-
inputRequests: { [`ask-${index}`]:
|
|
148
|
-
method: "elicitation/create",
|
|
149
|
-
params: {
|
|
150
|
-
mode: "form",
|
|
151
|
-
message,
|
|
152
|
-
requestedSchema: requested
|
|
153
|
-
}
|
|
154
|
-
} },
|
|
149
|
+
inputRequests: { [`ask-${index}`]: elicitRequest(question, form) },
|
|
155
150
|
requestState: JSON.stringify(state)
|
|
156
151
|
};
|
|
157
152
|
}
|
|
153
|
+
function elicitRequest(question, form) {
|
|
154
|
+
const { message } = question;
|
|
155
|
+
if (form === "mcp") return {
|
|
156
|
+
method: "elicitation/create",
|
|
157
|
+
params: {
|
|
158
|
+
mode: "form",
|
|
159
|
+
message,
|
|
160
|
+
requestedSchema: question.requested()
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
return {
|
|
164
|
+
method: "elicitation/create",
|
|
165
|
+
params: {
|
|
166
|
+
mode: "form",
|
|
167
|
+
message,
|
|
168
|
+
requestedSchema: {
|
|
169
|
+
type: "object",
|
|
170
|
+
properties: {}
|
|
171
|
+
},
|
|
172
|
+
_meta: { "openai/elicitation": { requestedSchema: question.openai } }
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
}
|
|
158
176
|
function readState(state) {
|
|
159
177
|
try {
|
|
160
178
|
const { answers, asking } = JSON.parse(state ?? "{}") ?? {};
|
|
@@ -176,6 +194,31 @@ function canAsk(capabilities) {
|
|
|
176
194
|
const modes = elicitation;
|
|
177
195
|
return modes.form !== void 0 || modes.url === void 0;
|
|
178
196
|
}
|
|
197
|
+
function askForm(capabilities) {
|
|
198
|
+
const { elicitation } = capabilities ?? {};
|
|
199
|
+
return fieldOf(elicitation, "form") !== void 0 && fillsOpenaiForms(capabilities) ? "openai" : "mcp";
|
|
200
|
+
}
|
|
201
|
+
const OPENAI_ELICIT = "openai/elicitation/create";
|
|
202
|
+
const ANSWER_TIMEOUT = 6e5;
|
|
203
|
+
function fillsOpenaiForms(capabilities) {
|
|
204
|
+
const { extensions } = capabilities ?? {};
|
|
205
|
+
return fieldOf(fieldOf(extensions, "openai/elicitation"), "form") !== void 0;
|
|
206
|
+
}
|
|
207
|
+
function openaiElicitRequest(question) {
|
|
208
|
+
const { message } = question;
|
|
209
|
+
const requestedSchema = question.openai;
|
|
210
|
+
return {
|
|
211
|
+
method: OPENAI_ELICIT,
|
|
212
|
+
params: {
|
|
213
|
+
mode: "form",
|
|
214
|
+
message,
|
|
215
|
+
requestedSchema
|
|
216
|
+
}
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
function fieldOf(value, key) {
|
|
220
|
+
return typeof value === "object" && value !== null ? value[key] : void 0;
|
|
221
|
+
}
|
|
179
222
|
function progressSteps(notify) {
|
|
180
223
|
let last;
|
|
181
224
|
return (message, amount) => {
|
|
@@ -190,4 +233,4 @@ function progressSteps(notify) {
|
|
|
190
233
|
});
|
|
191
234
|
};
|
|
192
235
|
}
|
|
193
|
-
export { callAsking, callTool, canAsk, copyIcons, errorResult, listTools, mcpHost, progressSteps, questionRound, toolAnnotations };
|
|
236
|
+
export { ANSWER_TIMEOUT, OPENAI_ELICIT, askForm, callAsking, callTool, canAsk, copyIcons, errorResult, fillsOpenaiForms, listTools, mcpHost, openaiElicitRequest, progressSteps, questionRound, toolAnnotations };
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { Check, Errors } from "./libs/typebox.mjs";
|
|
2
|
+
function toolHints(tool) {
|
|
3
|
+
return {
|
|
4
|
+
readOnlyHint: tool.effect === "read",
|
|
5
|
+
destructiveHint: tool.effect === "destructive" || tool.effect === "exec",
|
|
6
|
+
idempotentHint: tool.idempotent ?? tool.effect === "read",
|
|
7
|
+
openWorldHint: tool.openWorld ?? false
|
|
8
|
+
};
|
|
9
|
+
}
|
|
10
|
+
function checkDetails(tool, details) {
|
|
11
|
+
const { output } = tool;
|
|
12
|
+
if (output === void 0) return void 0;
|
|
13
|
+
if (Check(output, details)) return {
|
|
14
|
+
ok: true,
|
|
15
|
+
value: details
|
|
16
|
+
};
|
|
17
|
+
return {
|
|
18
|
+
ok: false,
|
|
19
|
+
lines: [`${tool.name} returned details that don't match its output schema`, ...[...Errors(output, details)].map((failure) => `at ${failure.instancePath || "/"}: ${failure.message}`)]
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
export { checkDetails, toolHints };
|
|
@@ -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
|
-
|
|
38
|
-
|
|
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
|
|
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
|
-
|
|
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;
|
package/dist/_chunks/src.mjs
CHANGED
|
@@ -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 };
|
package/dist/_chunks/updates.mjs
CHANGED
|
@@ -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
|
|
25
|
-
const
|
|
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 =
|
|
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
|
-
|
|
64
|
-
|
|
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
|
|
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(
|
|
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(
|
|
96
|
-
return distinct(
|
|
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
|
|
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 ? {
|