@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
package/CHANGELOG.md ADDED
@@ -0,0 +1,17 @@
1
+ # @johnhenry/aimatey-tool-protocols
2
+
3
+ ## 0.1.0
4
+
5
+ ### Minor Changes
6
+
7
+ - b10e69e: `code` protocol prompt v2: a worked two-step example (fetch and log, then answer in a later reply), a rule never to call `final()` in the same snippet as a tool call whose result has not been seen, and a rule to read result types from the interface instead of guessing. New `codeProtocol({ systemPrompt })` option to supply your own prompt builder; the old prompt is available as the internal `buildLegacyCodePrompt` for ablations.
8
+ - 671abac: Add the `code` tool protocol: the model writes JavaScript against a generated `tools.*` API and a `CodeExecutor` runs it. Includes `codeProtocol()`, `registerCodeProtocol()`, `generateToolsInterface()` and `andboxExecutor()` (sandboxed via the optional peer `@johnhenry/andbox` in wasm mode). Every tool call from a snippet goes through the same validation, gate and execute path as native calls.
9
+ - 2c0700d: `ToolDefinition.outputSchema` (optional). `aimatey-mcp` carries an MCP tool's `outputSchema` onto its definition and, for such tools, returns `structuredContent` as the result value instead of flattened text. The `code` protocol types tool results from `outputSchema` (`Promise<unknown>` when absent).
10
+ - 1b89457: Add the `text` tool protocol (tool calling through a fenced JSON block, for models with no native tool support), `autoProtocol()` (native when the backend supports tools, else text) and `registerTextProtocols()`.
11
+
12
+ ### Patch Changes
13
+
14
+ - Updated dependencies [2c0700d]
15
+ - Updated dependencies [211dc02]
16
+ - @johnhenry/aimatey-types@0.10.0
17
+ - @johnhenry/aimatey-utils@0.6.4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 AI Matey Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,171 @@
1
+ "use strict";
2
+ /**
3
+ * {@link CodeExecutor} backed by `@johnhenry/andbox` in `mode: 'wasm'`
4
+ * (QuickJS-ng compiled to WebAssembly). andbox is an OPTIONAL peer
5
+ * dependency, loaded lazily.
6
+ *
7
+ * @module
8
+ */
9
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ var desc = Object.getOwnPropertyDescriptor(m, k);
12
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
13
+ desc = { enumerable: true, get: function() { return m[k]; } };
14
+ }
15
+ Object.defineProperty(o, k2, desc);
16
+ }) : (function(o, m, k, k2) {
17
+ if (k2 === undefined) k2 = k;
18
+ o[k2] = m[k];
19
+ }));
20
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
21
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
22
+ }) : function(o, v) {
23
+ o["default"] = v;
24
+ });
25
+ var __importStar = (this && this.__importStar) || (function () {
26
+ var ownKeys = function(o) {
27
+ ownKeys = Object.getOwnPropertyNames || function (o) {
28
+ var ar = [];
29
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
30
+ return ar;
31
+ };
32
+ return ownKeys(o);
33
+ };
34
+ return function (mod) {
35
+ if (mod && mod.__esModule) return mod;
36
+ var result = {};
37
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
38
+ __setModuleDefault(result, mod);
39
+ return result;
40
+ };
41
+ })();
42
+ Object.defineProperty(exports, "__esModule", { value: true });
43
+ exports.DEFAULT_CODE_LIMITS = void 0;
44
+ exports.toJsonSafe = toJsonSafe;
45
+ exports.andboxExecutor = andboxExecutor;
46
+ exports.DEFAULT_CODE_LIMITS = {
47
+ fuel: 20_000,
48
+ memoryBytes: 32 * 1024 * 1024,
49
+ deadlineMs: 10_000,
50
+ maxToolCalls: 50,
51
+ };
52
+ async function loadAndbox() {
53
+ try {
54
+ return (await Promise.resolve().then(() => __importStar(require('@johnhenry/andbox'))));
55
+ }
56
+ catch (error) {
57
+ throw new Error('andboxExecutor needs the optional peer @johnhenry/andbox (>=0.0.8) and its wasm engine: ' +
58
+ 'npm install @johnhenry/andbox && npm install --save-exact quickjs-emscripten-core@0.32.0 ' +
59
+ `@jitl/quickjs-ng-wasmfile-release-sync@0.32.0 (${error instanceof Error ? error.message : String(error)})`, { cause: error });
60
+ }
61
+ }
62
+ /** JSON-safe copy of any tool result: bigint, Date, Map/Set, cycles and functions never throw. */
63
+ function toJsonSafe(value) {
64
+ if (value === undefined) {
65
+ return null;
66
+ }
67
+ const seen = new WeakSet();
68
+ try {
69
+ const text = JSON.stringify(value, (_key, v) => {
70
+ if (typeof v === 'bigint') {
71
+ return v.toString();
72
+ }
73
+ if (typeof v === 'function') {
74
+ return '[Function]';
75
+ }
76
+ if (typeof v === 'symbol') {
77
+ return v.toString();
78
+ }
79
+ if (v instanceof Map) {
80
+ return Object.fromEntries(v);
81
+ }
82
+ if (v instanceof Set) {
83
+ return [...v];
84
+ }
85
+ if (v instanceof Error) {
86
+ return { name: v.name, message: v.message };
87
+ }
88
+ if (typeof v === 'object' && v !== null) {
89
+ if (seen.has(v)) {
90
+ return '[Circular]';
91
+ }
92
+ seen.add(v);
93
+ }
94
+ return v;
95
+ });
96
+ return text === undefined ? null : JSON.parse(text);
97
+ }
98
+ catch {
99
+ return Object.prototype.toString.call(value);
100
+ }
101
+ }
102
+ // Written as one line so the user's code keeps its own line numbers.
103
+ function prelude(toolNames) {
104
+ return (`const tools = Object.fromEntries(${JSON.stringify(toolNames)}.map((n) => [n, (input) => host.call('tool', n, input === undefined ? {} : input)]));` +
105
+ `const final = (answer) => host.call('final', answer);`);
106
+ }
107
+ /**
108
+ * Executor using andbox wasm mode. A fresh sandbox (and so a fresh QuickJS
109
+ * runtime) is created per snippet and disposed afterwards.
110
+ */
111
+ function andboxExecutor(options = {}) {
112
+ return {
113
+ async run(code, run) {
114
+ const andbox = options.andbox ?? (await loadAndbox());
115
+ const limits = { ...exports.DEFAULT_CODE_LIMITS, ...options.limits, ...run.limits };
116
+ const logs = [];
117
+ let final;
118
+ const toolNames = new Set(run.toolNames);
119
+ const sandbox = await andbox.createSandbox({
120
+ mode: 'wasm',
121
+ ...options.sandboxOptions,
122
+ capabilities: {
123
+ tool: async (name, input) => {
124
+ if (typeof name !== 'string' || !toolNames.has(name)) {
125
+ throw new Error(`Unknown tool: ${String(name)}`);
126
+ }
127
+ return toJsonSafe(await run.callTool(name, input));
128
+ },
129
+ final: (answer) => {
130
+ final = { answer };
131
+ return null;
132
+ },
133
+ },
134
+ policy: { capabilities: { tool: { maxCalls: limits.maxToolCalls } } },
135
+ fuel: limits.fuel,
136
+ memoryBytes: limits.memoryBytes,
137
+ deadlineMs: limits.deadlineMs,
138
+ ...(limits.stackBytes !== undefined && { stackBytes: limits.stackBytes }),
139
+ onConsole: (level, ...args) => {
140
+ const line = args
141
+ .map((a) => (typeof a === 'string' ? a : JSON.stringify(toJsonSafe(a))))
142
+ .join(' ');
143
+ logs.push(level === 'log' || level === 'info' ? line : `[${level}] ${line}`);
144
+ },
145
+ });
146
+ try {
147
+ const result = await sandbox.evaluate(`${prelude(run.toolNames)}\n${code}`, {
148
+ ...(run.signal && { signal: run.signal }),
149
+ timeoutMs: limits.deadlineMs + 1000,
150
+ });
151
+ return { logs, ...(result !== undefined && { result }), ...(final && { final }) };
152
+ }
153
+ catch (error) {
154
+ const e = error;
155
+ return {
156
+ logs,
157
+ ...(final && { final }),
158
+ error: {
159
+ name: e?.name ?? 'Error',
160
+ message: e?.message ?? String(error),
161
+ ...(e?.code && { code: e.code }),
162
+ },
163
+ };
164
+ }
165
+ finally {
166
+ await sandbox.dispose();
167
+ }
168
+ },
169
+ };
170
+ }
171
+ //# 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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CH,gCAqCC;AAcD,wCA2DC;AAnIY,QAAA,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,wDAAa,mBAAmB,GAAC,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,MAAM,CAAC,KAAK,CAAC,GAAG,EAC7G,EAAE,KAAK,EAAE,KAAK,EAAE,CACjB,CAAC;IACJ,CAAC;AACH,CAAC;AAED,kGAAkG;AAClG,SAAgB,UAAU,CAAC,KAAc;IACvC,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;QACxB,OAAO,IAAI,CAAC;IACd,CAAC;IACD,MAA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AO,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,34 @@
1
+ "use strict";
2
+ /**
3
+ * The `auto` tool protocol and registration of the text-based protocols.
4
+ *
5
+ * @module
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.autoProtocol = autoProtocol;
9
+ exports.registerTextProtocols = registerTextProtocols;
10
+ const aimatey_core_1 = require("@johnhenry/aimatey-core");
11
+ const text_js_1 = require("./text.js");
12
+ /**
13
+ * Pick native tool calling when the backend supports it, else `text`.
14
+ * An unknown capability counts as native, so hosted models are unaffected.
15
+ * Stateless: the choice is made from the context on every call.
16
+ */
17
+ function autoProtocol() {
18
+ const text = (0, text_js_1.textProtocol)();
19
+ const pick = (context) => context.supportsNativeTools === false ? text : aimatey_core_1.nativeToolProtocol;
20
+ return {
21
+ name: 'auto',
22
+ prepare: (request, context) => pick(context).prepare(request, context),
23
+ interpret: (response, context) => pick(context).interpret(response, context),
24
+ };
25
+ }
26
+ /**
27
+ * Register `text` and `auto` so `runTools({ protocol: 'text' | 'auto' })`
28
+ * resolves by name. (`code` is registered by its own module.)
29
+ */
30
+ function registerTextProtocols() {
31
+ (0, aimatey_core_1.registerToolProtocol)((0, text_js_1.textProtocol)());
32
+ (0, aimatey_core_1.registerToolProtocol)(autoProtocol());
33
+ }
34
+ //# sourceMappingURL=auto.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auto.js","sourceRoot":"","sources":["../../src/auto.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AAiBH,oCAcC;AAMD,sDAGC;AAtCD,0DAAmF;AAQnF,uCAAyC;AAEzC;;;;GAIG;AACH,SAAgB,YAAY;IAC1B,MAAM,IAAI,GAAG,IAAA,sBAAY,GAAE,CAAC;IAC5B,MAAM,IAAI,GAAG,CAAC,OAA4B,EAAgB,EAAE,CAC1D,OAAO,CAAC,mBAAmB,KAAK,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,iCAAkB,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,SAAgB,qBAAqB;IACnC,IAAA,mCAAoB,EAAC,IAAA,sBAAY,GAAE,CAAC,CAAC;IACrC,IAAA,mCAAoB,EAAC,YAAY,EAAE,CAAC,CAAC;AACvC,CAAC"}
@@ -0,0 +1,166 @@
1
+ "use strict";
2
+ /**
3
+ * Prompt-side helpers for the `code` protocol: turn tool JSON schemas into a
4
+ * TypeScript-style `declare const tools` block.
5
+ *
6
+ * @module
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.schemaToTs = schemaToTs;
10
+ exports.generateToolsInterface = generateToolsInterface;
11
+ exports.buildCodePrompt = buildCodePrompt;
12
+ exports.buildLegacyCodePrompt = buildLegacyCodePrompt;
13
+ const isObject = (v) => typeof v === 'object' && v !== null;
14
+ function literal(value) {
15
+ return typeof value === 'string'
16
+ ? `'${value.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`
17
+ : (JSON.stringify(value) ?? 'unknown');
18
+ }
19
+ function comment(text, indent) {
20
+ const clean = text
21
+ .replace(/\*\//g, '* /')
22
+ .replace(/\s*\n\s*/g, ' ')
23
+ .trim();
24
+ return `${indent}/** ${clean} */\n`;
25
+ }
26
+ /** Render one JSON-schema node as a TypeScript type expression. */
27
+ function schemaToTs(schema, indent = '', depth = 0) {
28
+ if (!isObject(schema) || depth > 8) {
29
+ return 'unknown';
30
+ }
31
+ if (Array.isArray(schema.enum)) {
32
+ return schema.enum.map(literal).join(' | ') || 'never';
33
+ }
34
+ if ('const' in schema) {
35
+ return literal(schema.const);
36
+ }
37
+ for (const key of ['anyOf', 'oneOf']) {
38
+ const branches = schema[key];
39
+ if (Array.isArray(branches) && branches.length > 0) {
40
+ return branches.map((b) => schemaToTs(b, indent, depth + 1)).join(' | ');
41
+ }
42
+ }
43
+ const type = schema.type;
44
+ if (Array.isArray(type)) {
45
+ return type.map((t) => schemaToTs({ ...schema, type: t }, indent, depth + 1)).join(' | ');
46
+ }
47
+ switch (type) {
48
+ case 'string':
49
+ return 'string';
50
+ case 'number':
51
+ case 'integer':
52
+ return 'number';
53
+ case 'boolean':
54
+ return 'boolean';
55
+ case 'null':
56
+ return 'null';
57
+ case 'array': {
58
+ const item = schemaToTs(schema.items, indent, depth + 1);
59
+ return /[|&]/.test(item) ? `(${item})[]` : `${item}[]`;
60
+ }
61
+ case 'object':
62
+ case undefined: {
63
+ const props = schema.properties;
64
+ if (!isObject(props)) {
65
+ return type === 'object' ? 'Record<string, unknown>' : 'unknown';
66
+ }
67
+ const required = new Set(Array.isArray(schema.required) ? schema.required : []);
68
+ const names = Object.keys(props);
69
+ if (names.length === 0) {
70
+ return '{}';
71
+ }
72
+ const inner = `${indent} `;
73
+ const lines = names.map((name) => {
74
+ const prop = props[name];
75
+ const doc = isObject(prop) && typeof prop.description === 'string'
76
+ ? comment(prop.description, inner)
77
+ : '';
78
+ const key = /^[A-Za-z_$][\w$]*$/.test(name) ? name : JSON.stringify(name);
79
+ return `${doc}${inner}${key}${required.has(name) ? '' : '?'}: ${schemaToTs(prop, inner, depth + 1)};`;
80
+ });
81
+ return `{\n${lines.join('\n')}\n${indent}}`;
82
+ }
83
+ default:
84
+ return 'unknown';
85
+ }
86
+ }
87
+ /**
88
+ * Generate the `declare const tools: { ... }` block shown to the model.
89
+ * Results are typed from a tool's `outputSchema` when it has one, else `unknown`.
90
+ */
91
+ function generateToolsInterface(tools) {
92
+ const entries = Object.entries(tools).map(([name, def]) => {
93
+ const doc = def.description ? comment(def.description, ' ') : '';
94
+ const params = schemaToTs(def.parameters, ' ');
95
+ const optional = params === '{}' || !def.parameters?.required;
96
+ const key = /^[A-Za-z_$][\w$]*$/.test(name) ? name : JSON.stringify(name);
97
+ const output = def.outputSchema ? schemaToTs(def.outputSchema, ' ') : 'unknown';
98
+ return `${doc} ${key}(input${optional ? '?' : ''}: ${params}): Promise<${output}>;`;
99
+ });
100
+ return `declare const tools: {\n${entries.join('\n')}\n};\ndeclare function final(answer: unknown): void;`;
101
+ }
102
+ /**
103
+ * The system prompt that teaches a model the `code` protocol (v2): a worked
104
+ * two-step example, "log first, finish next turn", and read result types from
105
+ * the interface. Kept short for small models.
106
+ */
107
+ function buildCodePrompt(tools) {
108
+ return [
109
+ '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.',
110
+ '',
111
+ 'Example. The user asks: "How warm is it in Paris?"',
112
+ 'Your first reply is only this:',
113
+ '```js',
114
+ "const r = await tools.get_weather({ city: 'Paris' });",
115
+ 'console.log(r);',
116
+ '```',
117
+ 'You then receive: Output: {"city":"Paris","celsius":18}',
118
+ 'Your NEXT reply, now that you have seen the result, is plain text with no code block:',
119
+ 'It is 18 degrees Celsius in Paris.',
120
+ '',
121
+ 'Rules:',
122
+ '- Plain JavaScript only: no imports, no require, and no fetch, timers (setTimeout) or process in the sandbox.',
123
+ '- Call tools as `await tools.name({...})`. Arguments and results are JSON. Use Promise.all for independent calls.',
124
+ '- Read each result type in the interface below. Do not guess the shape of a result.',
125
+ '- 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.',
126
+ '- 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.',
127
+ '- A tool call can throw (denied, invalid arguments, tool failure); the error comes back to you, so read it and retry if you can.',
128
+ '- You get the printed output and the value you `return` in the next message. Nothing persists between snippets.',
129
+ '',
130
+ 'Available tools:',
131
+ '',
132
+ '```ts',
133
+ generateToolsInterface(tools),
134
+ '```',
135
+ ].join('\n');
136
+ }
137
+ /**
138
+ * The first (v1) system prompt, kept only so the benchmark ablation can
139
+ * reproduce it. Not part of the supported API.
140
+ *
141
+ * @internal
142
+ */
143
+ function buildLegacyCodePrompt(tools) {
144
+ return [
145
+ 'You act by writing JavaScript. To use tools, reply with exactly ONE fenced code block:',
146
+ '',
147
+ '```js',
148
+ 'const r = await tools.name({ arg: 1 });',
149
+ 'console.log(r);',
150
+ '```',
151
+ '',
152
+ 'Rules:',
153
+ '- Plain JavaScript only: no imports, no require, and no fetch, timers (setTimeout) or process in the sandbox.',
154
+ '- Call tools as `await tools.name({...})`. Arguments and results are JSON. Use Promise.all for independent calls.',
155
+ '- A tool call can throw (denied, invalid arguments, tool failure); use try/catch if you can recover.',
156
+ '- 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.',
157
+ '- To finish, call `final(answer)` inside the code, or reply with NO code block: that text is your final answer.',
158
+ '',
159
+ 'Available tools:',
160
+ '',
161
+ '```ts',
162
+ generateToolsInterface(tools),
163
+ '```',
164
+ ].join('\n');
165
+ }
166
+ //# sourceMappingURL=code-api.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"code-api.js","sourceRoot":"","sources":["../../src/code-api.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;AAuBH,gCA4DC;AAMD,wDAUC;AAOD,0CA6BC;AAQD,sDAsBC;AA/JD,MAAM,QAAQ,GAAG,CAAC,CAAU,EAAe,EAAE,CAAC,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,IAAI,CAAC;AAElF,SAAS,OAAO,CAAC,KAAc;IAC7B,OAAO,OAAO,KAAK,KAAK,QAAQ;QAC9B,CAAC,CAAC,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC,GAAG;QAC1D,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,SAAS,CAAC,CAAC;AAC3C,CAAC;AAED,SAAS,OAAO,CAAC,IAAY,EAAE,MAAc;IAC3C,MAAM,KAAK,GAAG,IAAI;SACf,OAAO,CAAC,OAAO,EAAE,KAAK,CAAC;SACvB,OAAO,CAAC,WAAW,EAAE,GAAG,CAAC;SACzB,IAAI,EAAE,CAAC;IACV,OAAO,GAAG,MAAM,OAAO,KAAK,OAAO,CAAC;AACtC,CAAC;AAED,mEAAmE;AACnE,SAAgB,UAAU,CAAC,MAAe,EAAE,MAAM,GAAG,EAAE,EAAE,KAAK,GAAG,CAAC;IAChE,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,KAAK,GAAG,CAAC,EAAE,CAAC;QACnC,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC;QAC/B,OAAO,MAAM,CAAC,IAAI,CAAC,GAAG,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OAAO,GAAG,GAAG,KAAK,GAAG,SAAS,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,KAAK,MAAM,cAAc,MAAM,IAAI,CAAC;IACvF,CAAC,CAAC,CAAC;IACH,OAAO,2BAA2B,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,sDAAsD,CAAC;AAC7G,CAAC;AAED;;;;GAIG;AACH,SAAgB,eAAe,CAAC,KAA+C;IAC7E,OAAO;QACL,4IAA4I;QAC5I,EAAE;QACF,oDAAoD;QACpD,gCAAgC;QAChC,OAAO;QACP,uDAAuD;QACvD,iBAAiB;QACjB,KAAK;QACL,yDAAyD;QACzD,uFAAuF;QACvF,oCAAoC;QACpC,EAAE;QACF,QAAQ;QACR,+GAA+G;QAC/G,mHAAmH;QACnH,qFAAqF;QACrF,wJAAwJ;QACxJ,uJAAuJ;QACvJ,kIAAkI;QAClI,iHAAiH;QACjH,EAAE;QACF,kBAAkB;QAClB,EAAE;QACF,OAAO;QACP,sBAAsB,CAAC,KAAK,CAAC;QAC7B,KAAK;KACN,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACf,CAAC;AAED;;;;;GAKG;AACH,SAAgB,qBAAqB,CAAC,KAA+C;IACnF,OAAO;QACL,wFAAwF;QACxF,EAAE;QACF,OAAO;QACP,yCAAyC;QACzC,iBAAiB;QACjB,KAAK;QACL,EAAE;QACF,QAAQ;QACR,+GAA+G;QAC/G,mHAAmH;QACnH,sGAAsG;QACtG,oKAAoK;QACpK,iHAAiH;QACjH,EAAE;QACF,kBAAkB;QAClB,EAAE;QACF,OAAO;QACP,sBAAsB,CAAC,KAAK,CAAC;QAC7B,KAAK;KACN,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACf,CAAC"}
@@ -0,0 +1,162 @@
1
+ "use strict";
2
+ /**
3
+ * The `code` tool protocol: the model writes JavaScript against a generated
4
+ * `tools.*` API; a {@link CodeExecutor} runs it and every tool call inside
5
+ * goes back through the loop's `invoke` (validation, gate, execute).
6
+ *
7
+ * @module
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.andboxExecutor = exports.buildLegacyCodePrompt = exports.buildCodePrompt = exports.schemaToTs = exports.generateToolsInterface = void 0;
11
+ exports.extractCodeBlock = extractCodeBlock;
12
+ exports.codeProtocol = codeProtocol;
13
+ exports.registerCodeProtocol = registerCodeProtocol;
14
+ const aimatey_core_1 = require("@johnhenry/aimatey-core");
15
+ const code_api_js_1 = require("./code-api.js");
16
+ var code_api_js_2 = require("./code-api.js");
17
+ Object.defineProperty(exports, "generateToolsInterface", { enumerable: true, get: function () { return code_api_js_2.generateToolsInterface; } });
18
+ Object.defineProperty(exports, "schemaToTs", { enumerable: true, get: function () { return code_api_js_2.schemaToTs; } });
19
+ Object.defineProperty(exports, "buildCodePrompt", { enumerable: true, get: function () { return code_api_js_2.buildCodePrompt; } });
20
+ Object.defineProperty(exports, "buildLegacyCodePrompt", { enumerable: true, get: function () { return code_api_js_2.buildLegacyCodePrompt; } });
21
+ var andbox_executor_js_1 = require("./andbox-executor.js");
22
+ Object.defineProperty(exports, "andboxExecutor", { enumerable: true, get: function () { return andbox_executor_js_1.andboxExecutor; } });
23
+ const DEFAULT_MAX_LOG_CHARS = 4000;
24
+ /** First js/javascript/ts fenced block (or an untagged one); tolerates a missing closing fence. */
25
+ function extractCodeBlock(text) {
26
+ const re = /```[ \t]*([A-Za-z]*)[^\n]*\n([\s\S]*?)(?:```|$)/g;
27
+ for (const m of text.matchAll(re)) {
28
+ const lang = (m[1] ?? '').toLowerCase();
29
+ if (['', 'js', 'javascript', 'ts', 'typescript', 'mjs'].includes(lang)) {
30
+ return m[2];
31
+ }
32
+ }
33
+ return undefined;
34
+ }
35
+ function messageText(response) {
36
+ const content = response.message.content;
37
+ if (typeof content === 'string') {
38
+ return content;
39
+ }
40
+ return content
41
+ .filter((b) => b.type === 'text')
42
+ .map((b) => b.text)
43
+ .join('');
44
+ }
45
+ function show(value) {
46
+ if (typeof value === 'string') {
47
+ return value;
48
+ }
49
+ try {
50
+ return JSON.stringify(value) ?? String(value);
51
+ }
52
+ catch {
53
+ return String(value);
54
+ }
55
+ }
56
+ function truncate(text, max) {
57
+ if (text.length <= max) {
58
+ return text;
59
+ }
60
+ return `${text.slice(0, max)}\n[truncated ${text.length - max} chars]`;
61
+ }
62
+ /**
63
+ * Create the `code` protocol. The model writes JavaScript instead of
64
+ * emitting tool calls; tools are not sent in `request.tools`.
65
+ */
66
+ function codeProtocol(options) {
67
+ const { executor, limits } = options;
68
+ const systemPrompt = options.systemPrompt ?? code_api_js_1.buildCodePrompt;
69
+ const maxLogChars = options.maxLogChars ?? DEFAULT_MAX_LOG_CHARS;
70
+ return {
71
+ name: 'code',
72
+ prepare(request, context) {
73
+ const prompt = systemPrompt(context.tools);
74
+ const messages = [...request.messages];
75
+ const first = messages[0];
76
+ if (first?.role === 'system' && typeof first.content === 'string') {
77
+ messages[0] = { ...first, content: `${first.content}\n\n${prompt}` };
78
+ }
79
+ else {
80
+ messages.unshift({ role: 'system', content: prompt });
81
+ }
82
+ return { ...request, messages, tools: undefined };
83
+ },
84
+ async interpret(response, context) {
85
+ const code = extractCodeBlock(messageText(response));
86
+ if (code === undefined) {
87
+ return { kind: 'final' };
88
+ }
89
+ const calls = [];
90
+ const results = [];
91
+ const callTool = async (name, input) => {
92
+ const call = {
93
+ id: `code-${context.iteration}-${calls.length + 1}`,
94
+ name,
95
+ input: typeof input === 'object' && input !== null && !Array.isArray(input)
96
+ ? input
97
+ : input === undefined || input === null
98
+ ? {}
99
+ : { value: input },
100
+ };
101
+ calls.push(call);
102
+ const result = await context.invoke(call);
103
+ results.push(result);
104
+ if (result.isError) {
105
+ throw new Error(show(result.result));
106
+ }
107
+ return result.result;
108
+ };
109
+ let run;
110
+ try {
111
+ run = await executor.run(code, {
112
+ callTool,
113
+ toolNames: Object.keys(context.tools),
114
+ ...(limits && { limits }),
115
+ ...(context.signal && { signal: context.signal }),
116
+ });
117
+ }
118
+ catch (error) {
119
+ context.signal?.throwIfAborted();
120
+ run = {
121
+ logs: [],
122
+ error: {
123
+ name: error instanceof Error ? error.name : 'Error',
124
+ message: error instanceof Error ? error.message : String(error),
125
+ },
126
+ };
127
+ }
128
+ if (run.final) {
129
+ return { kind: 'final', text: show(run.final.answer) };
130
+ }
131
+ const parts = [];
132
+ if (run.logs.length > 0) {
133
+ parts.push(`Output:\n${run.logs.join('\n')}`);
134
+ }
135
+ if (run.error) {
136
+ parts.push(`Error (${run.error.name}${run.error.code ? `, ${run.error.code}` : ''}): ${run.error.message}`);
137
+ }
138
+ else if (run.result !== undefined) {
139
+ parts.push(`Returned: ${show(run.result)}`);
140
+ }
141
+ if (parts.length === 0) {
142
+ parts.push('The code ran and produced no output and no return value.');
143
+ }
144
+ return {
145
+ kind: 'continue',
146
+ calls,
147
+ results,
148
+ messages: [
149
+ response.message,
150
+ { role: 'user', content: truncate(parts.join('\n\n'), maxLogChars) },
151
+ ],
152
+ };
153
+ },
154
+ };
155
+ }
156
+ /** Register the `code` protocol so `runTools({ protocol: 'code' })` resolves it. */
157
+ function registerCodeProtocol(executor, options = {}) {
158
+ const protocol = codeProtocol({ ...options, executor });
159
+ (0, aimatey_core_1.registerToolProtocol)(protocol);
160
+ return protocol;
161
+ }
162
+ //# sourceMappingURL=code.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"code.js","sourceRoot":"","sources":["../../src/code.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;AAmFH,4CASC;AAmCD,oCAoGC;AAGD,oDAOC;AA3OD,0DAA+D;AAY/D,+CAAgD;AAEhD,6CAKuB;AAJrB,qHAAA,sBAAsB,OAAA;AACtB,yGAAA,UAAU,OAAA;AACV,8GAAA,eAAe,OAAA;AACf,oHAAA,qBAAqB,OAAA;AAEvB,2DAAkF;AAAzE,oHAAA,cAAc,OAAA;AA0DvB,MAAM,qBAAqB,GAAG,IAAI,CAAC;AAEnC,mGAAmG;AACnG,SAAgB,gBAAg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AO,EAAE,CAChG,CAAC;YACJ,CAAC;iBAAM,IAAI,GAAG,CAAC,MAAM,KAAK,SAAS,EAAE,CAAC;gBACpC,KAAK,CAAC,IAAI,CAAC,aAAa,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;YAC9C,CAAC;YACD,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;gBACvB,KAAK,CAAC,IAAI,CAAC,0DAA0D,CAAC,CAAC;YACzE,CAAC;YAED,OAAO;gBACL,IAAI,EAAE,UAAU;gBAChB,KAAK;gBACL,OAAO;gBACP,QAAQ,EAAE;oBACR,QAAQ,CAAC,OAAO;oBAChB,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,CAAC,EAAE;iBACrE;aACF,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC;AAED,oFAAoF;AACpF,SAAgB,oBAAoB,CAClC,QAAsB,EACtB,UAAiD,EAAE;IAEnD,MAAM,QAAQ,GAAG,YAAY,CAAC,EAAE,GAAG,OAAO,EAAE,QAAQ,EAAE,CAAC,CAAC;IACxD,IAAA,mCAAoB,EAAC,QAAQ,CAAC,CAAC;IAC/B,OAAO,QAAQ,CAAC;AAClB,CAAC"}
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./text.js"), exports);
18
+ __exportStar(require("./auto.js"), exports);
19
+ __exportStar(require("./code.js"), exports);
20
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,4CAA0B;AAC1B,4CAA0B;AAC1B,4CAA0B"}