@johnhenry/aimatey-tool-protocols 0.0.0-stage → 0.1.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.
Files changed (41) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/LICENSE +21 -0
  3. package/dist/cjs/andbox-executor.js +171 -0
  4. package/dist/cjs/andbox-executor.js.map +1 -0
  5. package/dist/cjs/auto.js +34 -0
  6. package/dist/cjs/auto.js.map +1 -0
  7. package/dist/cjs/code-api.js +166 -0
  8. package/dist/cjs/code-api.js.map +1 -0
  9. package/dist/cjs/code.js +162 -0
  10. package/dist/cjs/code.js.map +1 -0
  11. package/dist/cjs/index.js +20 -0
  12. package/dist/cjs/index.js.map +1 -0
  13. package/dist/cjs/text.js +310 -0
  14. package/dist/cjs/text.js.map +1 -0
  15. package/dist/esm/andbox-executor.js +133 -0
  16. package/dist/esm/andbox-executor.js.map +1 -0
  17. package/dist/esm/auto.js +30 -0
  18. package/dist/esm/auto.js.map +1 -0
  19. package/dist/esm/code-api.js +160 -0
  20. package/dist/esm/code-api.js.map +1 -0
  21. package/dist/esm/code.js +151 -0
  22. package/dist/esm/code.js.map +1 -0
  23. package/dist/esm/index.js +4 -0
  24. package/dist/esm/index.js.map +1 -0
  25. package/dist/esm/text.js +307 -0
  26. package/dist/esm/text.js.map +1 -0
  27. package/dist/types/andbox-executor.d.ts +33 -0
  28. package/dist/types/andbox-executor.d.ts.map +1 -0
  29. package/dist/types/auto.d.ts +18 -0
  30. package/dist/types/auto.d.ts.map +1 -0
  31. package/dist/types/code-api.d.ts +28 -0
  32. package/dist/types/code-api.d.ts.map +1 -0
  33. package/dist/types/code.d.ts +77 -0
  34. package/dist/types/code.d.ts.map +1 -0
  35. package/dist/types/index.d.ts +4 -0
  36. package/dist/types/index.d.ts.map +1 -0
  37. package/dist/types/text.d.ts +25 -0
  38. package/dist/types/text.d.ts.map +1 -0
  39. package/package.json +77 -4
  40. package/readme.md +83 -0
  41. package/README.md +0 -3
@@ -0,0 +1,310 @@
1
+ "use strict";
2
+ /**
3
+ * The `text` tool protocol: tool calling for models with no native tool
4
+ * support. Tools are described in a system message; the model replies with a
5
+ * fenced JSON action block, or a plain-text final answer.
6
+ *
7
+ * @module
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.textProtocol = textProtocol;
11
+ const FENCE = '```';
12
+ function isRecord(value) {
13
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
14
+ }
15
+ /** Remove trailing commas before `}` or `]`, leaving string contents alone. */
16
+ function stripTrailingCommas(text) {
17
+ let out = '';
18
+ let inString = false;
19
+ for (let i = 0; i < text.length; i++) {
20
+ const ch = text[i];
21
+ if (inString) {
22
+ out += ch;
23
+ if (ch === '\\') {
24
+ out += text[++i] ?? '';
25
+ }
26
+ else if (ch === '"') {
27
+ inString = false;
28
+ }
29
+ }
30
+ else if (ch === '"') {
31
+ inString = true;
32
+ out += ch;
33
+ }
34
+ else if (ch === ',') {
35
+ let j = i + 1;
36
+ while (j < text.length && /\s/.test(text[j] ?? '')) {
37
+ j++;
38
+ }
39
+ if (text[j] !== '}' && text[j] !== ']') {
40
+ out += ch;
41
+ }
42
+ }
43
+ else {
44
+ out += ch;
45
+ }
46
+ }
47
+ return out;
48
+ }
49
+ /** JSON.parse that also accepts trailing commas. Returns `undefined` on failure. */
50
+ function lenientParse(text) {
51
+ for (const candidate of [text, stripTrailingCommas(text)]) {
52
+ try {
53
+ return { value: JSON.parse(candidate) };
54
+ }
55
+ catch {
56
+ // try the next form
57
+ }
58
+ }
59
+ return undefined;
60
+ }
61
+ /** The balanced `{...}` or `[...]` span starting at `start`, string-aware. */
62
+ function balancedSpan(text, start) {
63
+ let depth = 0;
64
+ let inString = false;
65
+ for (let i = start; i < text.length; i++) {
66
+ const ch = text[i];
67
+ if (inString) {
68
+ if (ch === '\\') {
69
+ i++;
70
+ }
71
+ else if (ch === '"') {
72
+ inString = false;
73
+ }
74
+ }
75
+ else if (ch === '"') {
76
+ inString = true;
77
+ }
78
+ else if (ch === '{' || ch === '[') {
79
+ depth++;
80
+ }
81
+ else if ((ch === '}' || ch === ']') && --depth === 0) {
82
+ return text.slice(start, i + 1);
83
+ }
84
+ }
85
+ return undefined;
86
+ }
87
+ function toAction(value) {
88
+ if (!isRecord(value)) {
89
+ return 'an action must be a JSON object like {"tool": "name", "args": {...}}';
90
+ }
91
+ const tool = value.tool;
92
+ if (typeof tool !== 'string' || tool.length === 0) {
93
+ return 'the action is missing the "tool" key (a string naming the tool to call)';
94
+ }
95
+ const args = value.args ?? value.arguments ?? value.input ?? {};
96
+ if (!isRecord(args)) {
97
+ return `"args" for tool "${tool}" must be a JSON object`;
98
+ }
99
+ return { tool, args };
100
+ }
101
+ function toActions(value) {
102
+ const items = Array.isArray(value) ? value : [value];
103
+ if (items.length === 0) {
104
+ return 'the action array is empty';
105
+ }
106
+ const actions = [];
107
+ for (const item of items) {
108
+ const action = toAction(item);
109
+ if (typeof action === 'string') {
110
+ return action;
111
+ }
112
+ actions.push(action);
113
+ }
114
+ return actions;
115
+ }
116
+ /** Does a parsed value look like an attempted action (as opposed to a JSON answer)? */
117
+ function looksLikeAction(value) {
118
+ const items = Array.isArray(value) ? value : [value];
119
+ return items.length > 0 && items.every((v) => isRecord(v) && ('tool' in v || 'args' in v));
120
+ }
121
+ const ACTION_START = /[{[]\s*(?:\{\s*)?["']?tool["']?\s*:/g;
122
+ /** Read the model's reply: fenced JSON blocks first, then a bare action object. */
123
+ function parseReply(text) {
124
+ const actions = [];
125
+ const fenceRe = /```([\w-]*)[ \t]*\r?\n?([\s\S]*?)```/g;
126
+ for (const match of text.matchAll(fenceRe)) {
127
+ const lang = (match[1] ?? '').toLowerCase();
128
+ const body = (match[2] ?? '').trim();
129
+ const jsonish = lang === 'json' || lang === 'json5' || body.startsWith('{') || body.startsWith('[');
130
+ if (!jsonish) {
131
+ continue;
132
+ }
133
+ const parsed = lenientParse(body);
134
+ if (!parsed) {
135
+ if (lang === 'json' || /["']?tool["']?\s*:/.test(body)) {
136
+ return {
137
+ kind: 'error',
138
+ message: 'your JSON block is not valid JSON and could not be parsed',
139
+ };
140
+ }
141
+ continue;
142
+ }
143
+ if (!looksLikeAction(parsed.value)) {
144
+ continue;
145
+ }
146
+ const found = toActions(parsed.value);
147
+ if (typeof found === 'string') {
148
+ return { kind: 'error', message: found };
149
+ }
150
+ actions.push(...found);
151
+ }
152
+ if (actions.length > 0) {
153
+ return { kind: 'actions', actions };
154
+ }
155
+ if (!text.includes(FENCE)) {
156
+ // No fence: look for a bare {"tool": ...} object (or array of them).
157
+ for (const match of text.matchAll(ACTION_START)) {
158
+ const span = balancedSpan(text, match.index);
159
+ const parsed = span === undefined ? undefined : lenientParse(span);
160
+ if (!parsed) {
161
+ return {
162
+ kind: 'error',
163
+ message: 'your JSON action is not valid JSON and could not be parsed',
164
+ };
165
+ }
166
+ const found = toActions(parsed.value);
167
+ if (typeof found === 'string') {
168
+ return { kind: 'error', message: found };
169
+ }
170
+ return { kind: 'actions', actions: found };
171
+ }
172
+ }
173
+ return { kind: 'none' };
174
+ }
175
+ function replyText(response) {
176
+ const content = response.message.content;
177
+ if (typeof content === 'string') {
178
+ return content;
179
+ }
180
+ return content.map((block) => (block.type === 'text' ? block.text : '')).join('');
181
+ }
182
+ function describeTools(tools) {
183
+ return Object.entries(tools)
184
+ .map(([name, tool]) => {
185
+ const lines = [`- ${name}${tool.description ? `: ${tool.description}` : ''}`];
186
+ if (tool.parameters) {
187
+ lines.push(` parameters (JSON schema): ${JSON.stringify(tool.parameters)}`);
188
+ }
189
+ return lines.join('\n');
190
+ })
191
+ .join('\n');
192
+ }
193
+ function buildSystemPrompt(context, options) {
194
+ const parallel = context.parallelToolCalls;
195
+ const shape = parallel
196
+ ? `an array of such objects, one per call:\n${FENCE}json\n[{"tool": "tool_name", "args": {"param": "value"}}]\n${FENCE}`
197
+ : `${FENCE}json\n{"tool": "tool_name", "args": {"param": "value"}}\n${FENCE}`;
198
+ const lines = [
199
+ 'You can use the following tools:',
200
+ describeTools(context.tools),
201
+ '',
202
+ 'To call a tool, reply with exactly one fenced JSON block' +
203
+ (parallel ? ' containing ' : ' like this:\n') +
204
+ shape,
205
+ parallel
206
+ ? 'Use one array entry for each tool you want to call now.'
207
+ : 'Call one tool at a time and put nothing else you need in that block.',
208
+ 'You will receive the result in the next message, then you can call another tool or answer.',
209
+ 'When you have the final answer, reply in plain text with no JSON action block.',
210
+ ];
211
+ if (options.instructions) {
212
+ lines.push('', options.instructions);
213
+ }
214
+ return lines.join('\n');
215
+ }
216
+ function mergeSystem(messages, prompt) {
217
+ const first = messages[0];
218
+ if (first?.role !== 'system') {
219
+ return [{ role: 'system', content: prompt }, ...messages];
220
+ }
221
+ const merged = typeof first.content === 'string'
222
+ ? { ...first, content: `${first.content}\n\n${prompt}` }
223
+ : { ...first, content: [...first.content, { type: 'text', text: prompt }] };
224
+ return [merged, ...messages.slice(1)];
225
+ }
226
+ function stringify(value) {
227
+ if (typeof value === 'string') {
228
+ return JSON.stringify(value);
229
+ }
230
+ return JSON.stringify(value) ?? 'null';
231
+ }
232
+ function resultMessage(calls, results) {
233
+ const names = new Map(calls.map((c) => [c.id, c.name]));
234
+ const text = results
235
+ .map((r) => {
236
+ const name = names.get(r.toolCallId) ?? 'unknown';
237
+ const label = r.isError ? 'Tool error for' : 'Tool result for';
238
+ return `${label} ${name} (${r.toolCallId}): ${stringify(r.result)}`;
239
+ })
240
+ .join('\n');
241
+ return { role: 'user', content: text };
242
+ }
243
+ /**
244
+ * Tool calling through plain text. Works with any model, including ones with
245
+ * no native tool support.
246
+ *
247
+ * The model is told to reply with one fenced JSON block
248
+ * (`{"tool": "name", "args": {...}}`, or an array when parallel calls are
249
+ * allowed) to call a tool, or with plain text to answer. A reply that tries
250
+ * to call a tool but cannot be read is fed back as an error and uses up an
251
+ * iteration.
252
+ */
253
+ function textProtocol(options = {}) {
254
+ return {
255
+ name: 'text',
256
+ prepare(request, context) {
257
+ const { tools: _tools, toolChoice: _toolChoice, ...rest } = request;
258
+ void _tools;
259
+ void _toolChoice;
260
+ return {
261
+ ...rest,
262
+ messages: mergeSystem(request.messages, buildSystemPrompt(context, options)),
263
+ };
264
+ },
265
+ async interpret(response, context) {
266
+ const parsed = parseReply(replyText(response));
267
+ if (parsed.kind === 'none') {
268
+ return { kind: 'final' };
269
+ }
270
+ if (parsed.kind === 'error') {
271
+ return {
272
+ kind: 'continue',
273
+ calls: [],
274
+ results: [],
275
+ messages: [
276
+ response.message,
277
+ {
278
+ role: 'user',
279
+ content: `Error: ${parsed.message}. Reply with exactly one fenced json block like ` +
280
+ `{"tool": "name", "args": {...}} to call a tool, or plain text to answer.`,
281
+ },
282
+ ],
283
+ };
284
+ }
285
+ const actions = context.parallelToolCalls ? parsed.actions : parsed.actions.slice(0, 1);
286
+ const calls = actions.map((a, index) => ({
287
+ id: `text-${context.iteration}-${index}`,
288
+ name: a.tool,
289
+ input: a.args,
290
+ }));
291
+ let results;
292
+ if (context.parallelToolCalls) {
293
+ results = await Promise.all(calls.map(context.invoke));
294
+ }
295
+ else {
296
+ results = [];
297
+ for (const call of calls) {
298
+ results.push(await context.invoke(call));
299
+ }
300
+ }
301
+ return {
302
+ kind: 'continue',
303
+ calls,
304
+ results,
305
+ messages: [response.message, resultMessage(calls, results)],
306
+ };
307
+ },
308
+ };
309
+ }
310
+ //# sourceMappingURL=text.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"text.js","sourceRoot":"","sources":["../../src/text.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;AA2RH,oCAiEC;AAjUD,MAAM,KAAK,GAAG,KAAK,CAAC;AAEpB,SAAS,QAAQ,CAAC,KAAc;IAC9B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC;AAED,+EAA+E;AAC/E,SAAS,mBAAmB,CAAC,IAAY;IACvC,I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,CAAC,MAAM,CAAC,CAAC,CAAC;YACzD,CAAC;iBAAM,CAAC;gBACN,OAAO,GAAG,EAAE,CAAC;gBACb,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;oBACzB,OAAO,CAAC,IAAI,CAAC,MAAM,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;gBAC3C,CAAC;YACH,CAAC;YAED,OAAO;gBACL,IAAI,EAAE,UAAU;gBAChB,KAAK;gBACL,OAAO;gBACP,QAAQ,EAAE,CAAC,QAAQ,CAAC,OAAO,EAAE,aAAa,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;aAC5D,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,133 @@
1
+ /**
2
+ * {@link CodeExecutor} backed by `@johnhenry/andbox` in `mode: 'wasm'`
3
+ * (QuickJS-ng compiled to WebAssembly). andbox is an OPTIONAL peer
4
+ * dependency, loaded lazily.
5
+ *
6
+ * @module
7
+ */
8
+ export const DEFAULT_CODE_LIMITS = {
9
+ fuel: 20_000,
10
+ memoryBytes: 32 * 1024 * 1024,
11
+ deadlineMs: 10_000,
12
+ maxToolCalls: 50,
13
+ };
14
+ async function loadAndbox() {
15
+ try {
16
+ return (await import('@johnhenry/andbox'));
17
+ }
18
+ catch (error) {
19
+ throw new Error('andboxExecutor needs the optional peer @johnhenry/andbox (>=0.0.8) and its wasm engine: ' +
20
+ 'npm install @johnhenry/andbox && npm install --save-exact quickjs-emscripten-core@0.32.0 ' +
21
+ `@jitl/quickjs-ng-wasmfile-release-sync@0.32.0 (${error instanceof Error ? error.message : String(error)})`, { cause: error });
22
+ }
23
+ }
24
+ /** JSON-safe copy of any tool result: bigint, Date, Map/Set, cycles and functions never throw. */
25
+ export function toJsonSafe(value) {
26
+ if (value === undefined) {
27
+ return null;
28
+ }
29
+ const seen = new WeakSet();
30
+ try {
31
+ const text = JSON.stringify(value, (_key, v) => {
32
+ if (typeof v === 'bigint') {
33
+ return v.toString();
34
+ }
35
+ if (typeof v === 'function') {
36
+ return '[Function]';
37
+ }
38
+ if (typeof v === 'symbol') {
39
+ return v.toString();
40
+ }
41
+ if (v instanceof Map) {
42
+ return Object.fromEntries(v);
43
+ }
44
+ if (v instanceof Set) {
45
+ return [...v];
46
+ }
47
+ if (v instanceof Error) {
48
+ return { name: v.name, message: v.message };
49
+ }
50
+ if (typeof v === 'object' && v !== null) {
51
+ if (seen.has(v)) {
52
+ return '[Circular]';
53
+ }
54
+ seen.add(v);
55
+ }
56
+ return v;
57
+ });
58
+ return text === undefined ? null : JSON.parse(text);
59
+ }
60
+ catch {
61
+ return Object.prototype.toString.call(value);
62
+ }
63
+ }
64
+ // Written as one line so the user's code keeps its own line numbers.
65
+ function prelude(toolNames) {
66
+ return (`const tools = Object.fromEntries(${JSON.stringify(toolNames)}.map((n) => [n, (input) => host.call('tool', n, input === undefined ? {} : input)]));` +
67
+ `const final = (answer) => host.call('final', answer);`);
68
+ }
69
+ /**
70
+ * Executor using andbox wasm mode. A fresh sandbox (and so a fresh QuickJS
71
+ * runtime) is created per snippet and disposed afterwards.
72
+ */
73
+ export function andboxExecutor(options = {}) {
74
+ return {
75
+ async run(code, run) {
76
+ const andbox = options.andbox ?? (await loadAndbox());
77
+ const limits = { ...DEFAULT_CODE_LIMITS, ...options.limits, ...run.limits };
78
+ const logs = [];
79
+ let final;
80
+ const toolNames = new Set(run.toolNames);
81
+ const sandbox = await andbox.createSandbox({
82
+ mode: 'wasm',
83
+ ...options.sandboxOptions,
84
+ capabilities: {
85
+ tool: async (name, input) => {
86
+ if (typeof name !== 'string' || !toolNames.has(name)) {
87
+ throw new Error(`Unknown tool: ${String(name)}`);
88
+ }
89
+ return toJsonSafe(await run.callTool(name, input));
90
+ },
91
+ final: (answer) => {
92
+ final = { answer };
93
+ return null;
94
+ },
95
+ },
96
+ policy: { capabilities: { tool: { maxCalls: limits.maxToolCalls } } },
97
+ fuel: limits.fuel,
98
+ memoryBytes: limits.memoryBytes,
99
+ deadlineMs: limits.deadlineMs,
100
+ ...(limits.stackBytes !== undefined && { stackBytes: limits.stackBytes }),
101
+ onConsole: (level, ...args) => {
102
+ const line = args
103
+ .map((a) => (typeof a === 'string' ? a : JSON.stringify(toJsonSafe(a))))
104
+ .join(' ');
105
+ logs.push(level === 'log' || level === 'info' ? line : `[${level}] ${line}`);
106
+ },
107
+ });
108
+ try {
109
+ const result = await sandbox.evaluate(`${prelude(run.toolNames)}\n${code}`, {
110
+ ...(run.signal && { signal: run.signal }),
111
+ timeoutMs: limits.deadlineMs + 1000,
112
+ });
113
+ return { logs, ...(result !== undefined && { result }), ...(final && { final }) };
114
+ }
115
+ catch (error) {
116
+ const e = error;
117
+ return {
118
+ logs,
119
+ ...(final && { final }),
120
+ error: {
121
+ name: e?.name ?? 'Error',
122
+ message: e?.message ?? String(error),
123
+ ...(e?.code && { code: e.code }),
124
+ },
125
+ };
126
+ }
127
+ finally {
128
+ await sandbox.dispose();
129
+ }
130
+ },
131
+ };
132
+ }
133
+ //# sourceMappingURL=andbox-executor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"andbox-executor.js","sourceRoot":"","sources":["../../src/andbox-executor.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAqBH,MAAM,CAAC,MAAM,mBAAmB,GAA0D;IACxF,IAAI,EAAE,MAAM;IACZ,WAAW,EAAE,EAAE,GAAG,IAAI,GAAG,IAAI;IAC7B,UAAU,EAAE,MAAM;IAClB,YAAY,EAAE,EAAE;CACjB,CAAC;AAEF,KAAK,UAAU,UAAU;IACvB,IAAI,CAAC;QACH,OAAO,CAAC,MAAM,MAAM,CAAC,mBAAmB,CAAC,CAA0B,CAAC;IACtE,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,IAAI,KAAK,CACb,0FAA0F;YACxF,2FAA2F;YAC3F,kDAAkD,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MA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AC,GAAG,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,KAAK,IAAI,EAAE,EAAE;oBAC1E,GAAG,CAAC,GAAG,CAAC,MAAM,IAAI,EAAE,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,CAAC;oBACzC,SAAS,EAAE,MAAM,CAAC,UAAU,GAAG,IAAI;iBACpC,CAAC,CAAC;gBACH,OAAO,EAAE,IAAI,EAAE,GAAG,CAAC,MAAM,KAAK,SAAS,IAAI,EAAE,MAAM,EAAE,CAAC,EAAE,GAAG,CAAC,KAAK,IAAI,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC;YACpF,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,MAAM,CAAC,GAAG,KAA2D,CAAC;gBACtE,OAAO;oBACL,IAAI;oBACJ,GAAG,CAAC,KAAK,IAAI,EAAE,KAAK,EAAE,CAAC;oBACvB,KAAK,EAAE;wBACL,IAAI,EAAE,CAAC,EAAE,IAAI,IAAI,OAAO;wBACxB,OAAO,EAAE,CAAC,EAAE,OAAO,IAAI,MAAM,CAAC,KAAK,CAAC;wBACpC,GAAG,CAAC,CAAC,EAAE,IAAI,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;qBACjC;iBACF,CAAC;YACJ,CAAC;oBAAS,CAAC;gBACT,MAAM,OAAO,CAAC,OAAO,EAAE,CAAC;YAC1B,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,30 @@
1
+ /**
2
+ * The `auto` tool protocol and registration of the text-based protocols.
3
+ *
4
+ * @module
5
+ */
6
+ import { nativeToolProtocol, registerToolProtocol } from '@johnhenry/aimatey-core';
7
+ import { textProtocol } from './text.js';
8
+ /**
9
+ * Pick native tool calling when the backend supports it, else `text`.
10
+ * An unknown capability counts as native, so hosted models are unaffected.
11
+ * Stateless: the choice is made from the context on every call.
12
+ */
13
+ export function autoProtocol() {
14
+ const text = textProtocol();
15
+ const pick = (context) => context.supportsNativeTools === false ? text : nativeToolProtocol;
16
+ return {
17
+ name: 'auto',
18
+ prepare: (request, context) => pick(context).prepare(request, context),
19
+ interpret: (response, context) => pick(context).interpret(response, context),
20
+ };
21
+ }
22
+ /**
23
+ * Register `text` and `auto` so `runTools({ protocol: 'text' | 'auto' })`
24
+ * resolves by name. (`code` is registered by its own module.)
25
+ */
26
+ export function registerTextProtocols() {
27
+ registerToolProtocol(textProtocol());
28
+ registerToolProtocol(autoProtocol());
29
+ }
30
+ //# sourceMappingURL=auto.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auto.js","sourceRoot":"","sources":["../../src/auto.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AAQnF,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAEzC;;;;GAIG;AACH,MAAM,UAAU,YAAY;IAC1B,MAAM,IAAI,GAAG,YAAY,EAAE,CAAC;IAC5B,MAAM,IAAI,GAAG,CAAC,OAA4B,EAAgB,EAAE,CAC1D,OAAO,CAAC,mBAAmB,KAAK,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,kBAAkB,CAAC;IAEpE,OAAO;QACL,IAAI,EAAE,MAAM;QACZ,OAAO,EAAE,CAAC,OAAsB,EAAE,OAA4B,EAAE,EAAE,CAChE,IAAI,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,OAAO,EAAE,OAAO,CAAC;QACzC,SAAS,EAAE,CACT,QAAwB,EACxB,OAA4B,EACE,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,SAAS,CAAC,QAAQ,EAAE,OAAO,CAAC;KAC9E,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,qBAAqB;IACnC,oBAAoB,CAAC,YAAY,EAAE,CAAC,CAAC;IACrC,oBAAoB,CAAC,YAAY,EAAE,CAAC,CAAC;AACvC,CAAC"}
@@ -0,0 +1,160 @@
1
+ /**
2
+ * Prompt-side helpers for the `code` protocol: turn tool JSON schemas into a
3
+ * TypeScript-style `declare const tools` block.
4
+ *
5
+ * @module
6
+ */
7
+ const isObject = (v) => typeof v === 'object' && v !== null;
8
+ function literal(value) {
9
+ return typeof value === 'string'
10
+ ? `'${value.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`
11
+ : (JSON.stringify(value) ?? 'unknown');
12
+ }
13
+ function comment(text, indent) {
14
+ const clean = text
15
+ .replace(/\*\//g, '* /')
16
+ .replace(/\s*\n\s*/g, ' ')
17
+ .trim();
18
+ return `${indent}/** ${clean} */\n`;
19
+ }
20
+ /** Render one JSON-schema node as a TypeScript type expression. */
21
+ export function schemaToTs(schema, indent = '', depth = 0) {
22
+ if (!isObject(schema) || depth > 8) {
23
+ return 'unknown';
24
+ }
25
+ if (Array.isArray(schema.enum)) {
26
+ return schema.enum.map(literal).join(' | ') || 'never';
27
+ }
28
+ if ('const' in schema) {
29
+ return literal(schema.const);
30
+ }
31
+ for (const key of ['anyOf', 'oneOf']) {
32
+ const branches = schema[key];
33
+ if (Array.isArray(branches) && branches.length > 0) {
34
+ return branches.map((b) => schemaToTs(b, indent, depth + 1)).join(' | ');
35
+ }
36
+ }
37
+ const type = schema.type;
38
+ if (Array.isArray(type)) {
39
+ return type.map((t) => schemaToTs({ ...schema, type: t }, indent, depth + 1)).join(' | ');
40
+ }
41
+ switch (type) {
42
+ case 'string':
43
+ return 'string';
44
+ case 'number':
45
+ case 'integer':
46
+ return 'number';
47
+ case 'boolean':
48
+ return 'boolean';
49
+ case 'null':
50
+ return 'null';
51
+ case 'array': {
52
+ const item = schemaToTs(schema.items, indent, depth + 1);
53
+ return /[|&]/.test(item) ? `(${item})[]` : `${item}[]`;
54
+ }
55
+ case 'object':
56
+ case undefined: {
57
+ const props = schema.properties;
58
+ if (!isObject(props)) {
59
+ return type === 'object' ? 'Record<string, unknown>' : 'unknown';
60
+ }
61
+ const required = new Set(Array.isArray(schema.required) ? schema.required : []);
62
+ const names = Object.keys(props);
63
+ if (names.length === 0) {
64
+ return '{}';
65
+ }
66
+ const inner = `${indent} `;
67
+ const lines = names.map((name) => {
68
+ const prop = props[name];
69
+ const doc = isObject(prop) && typeof prop.description === 'string'
70
+ ? comment(prop.description, inner)
71
+ : '';
72
+ const key = /^[A-Za-z_$][\w$]*$/.test(name) ? name : JSON.stringify(name);
73
+ return `${doc}${inner}${key}${required.has(name) ? '' : '?'}: ${schemaToTs(prop, inner, depth + 1)};`;
74
+ });
75
+ return `{\n${lines.join('\n')}\n${indent}}`;
76
+ }
77
+ default:
78
+ return 'unknown';
79
+ }
80
+ }
81
+ /**
82
+ * Generate the `declare const tools: { ... }` block shown to the model.
83
+ * Results are typed from a tool's `outputSchema` when it has one, else `unknown`.
84
+ */
85
+ export function generateToolsInterface(tools) {
86
+ const entries = Object.entries(tools).map(([name, def]) => {
87
+ const doc = def.description ? comment(def.description, ' ') : '';
88
+ const params = schemaToTs(def.parameters, ' ');
89
+ const optional = params === '{}' || !def.parameters?.required;
90
+ const key = /^[A-Za-z_$][\w$]*$/.test(name) ? name : JSON.stringify(name);
91
+ const output = def.outputSchema ? schemaToTs(def.outputSchema, ' ') : 'unknown';
92
+ return `${doc} ${key}(input${optional ? '?' : ''}: ${params}): Promise<${output}>;`;
93
+ });
94
+ return `declare const tools: {\n${entries.join('\n')}\n};\ndeclare function final(answer: unknown): void;`;
95
+ }
96
+ /**
97
+ * The system prompt that teaches a model the `code` protocol (v2): a worked
98
+ * two-step example, "log first, finish next turn", and read result types from
99
+ * the interface. Kept short for small models.
100
+ */
101
+ export function buildCodePrompt(tools) {
102
+ return [
103
+ 'You act by writing JavaScript. To use tools, reply with exactly ONE fenced code block. To answer, reply with plain text and no code block.',
104
+ '',
105
+ 'Example. The user asks: "How warm is it in Paris?"',
106
+ 'Your first reply is only this:',
107
+ '```js',
108
+ "const r = await tools.get_weather({ city: 'Paris' });",
109
+ 'console.log(r);',
110
+ '```',
111
+ 'You then receive: Output: {"city":"Paris","celsius":18}',
112
+ 'Your NEXT reply, now that you have seen the result, is plain text with no code block:',
113
+ 'It is 18 degrees Celsius in Paris.',
114
+ '',
115
+ 'Rules:',
116
+ '- Plain JavaScript only: no imports, no require, and no fetch, timers (setTimeout) or process in the sandbox.',
117
+ '- Call tools as `await tools.name({...})`. Arguments and results are JSON. Use Promise.all for independent calls.',
118
+ '- Read each result type in the interface below. Do not guess the shape of a result.',
119
+ '- Never call final() in the same snippet as a tool call whose result you have not seen. console.log the results first, then finish in your NEXT reply.',
120
+ '- final(answer) is optional sugar: its argument is the answer text itself, never a call written inside prose. Plain text is the normal way to answer.',
121
+ '- A tool call can throw (denied, invalid arguments, tool failure); the error comes back to you, so read it and retry if you can.',
122
+ '- You get the printed output and the value you `return` in the next message. Nothing persists between snippets.',
123
+ '',
124
+ 'Available tools:',
125
+ '',
126
+ '```ts',
127
+ generateToolsInterface(tools),
128
+ '```',
129
+ ].join('\n');
130
+ }
131
+ /**
132
+ * The first (v1) system prompt, kept only so the benchmark ablation can
133
+ * reproduce it. Not part of the supported API.
134
+ *
135
+ * @internal
136
+ */
137
+ export function buildLegacyCodePrompt(tools) {
138
+ return [
139
+ 'You act by writing JavaScript. To use tools, reply with exactly ONE fenced code block:',
140
+ '',
141
+ '```js',
142
+ 'const r = await tools.name({ arg: 1 });',
143
+ 'console.log(r);',
144
+ '```',
145
+ '',
146
+ 'Rules:',
147
+ '- Plain JavaScript only: no imports, no require, and no fetch, timers (setTimeout) or process in the sandbox.',
148
+ '- Call tools as `await tools.name({...})`. Arguments and results are JSON. Use Promise.all for independent calls.',
149
+ '- A tool call can throw (denied, invalid arguments, tool failure); use try/catch if you can recover.',
150
+ '- Use console.log to show what you need to see; you will get the printed output and the value you `return` in the next message. Nothing persists between snippets.',
151
+ '- To finish, call `final(answer)` inside the code, or reply with NO code block: that text is your final answer.',
152
+ '',
153
+ 'Available tools:',
154
+ '',
155
+ '```ts',
156
+ generateToolsInterface(tools),
157
+ '```',
158
+ ].join('\n');
159
+ }
160
+ //# sourceMappingURL=code-api.js.map