@tanstack/ai-code-mode 0.3.0 → 0.3.2
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/dist/esm/agent-store.d.ts +21 -0
- package/dist/esm/agent-store.js +29 -0
- package/dist/esm/agent-store.js.map +1 -0
- package/dist/esm/bindings/tool-to-binding.d.ts +25 -0
- package/dist/esm/bindings/tool-to-binding.js +94 -0
- package/dist/esm/bindings/tool-to-binding.js.map +1 -0
- package/dist/esm/code-wrapper.d.ts +9 -0
- package/dist/esm/code-wrapper.js +18 -0
- package/dist/esm/code-wrapper.js.map +1 -0
- package/dist/esm/create-code-mode-tool.d.ts +50 -0
- package/dist/esm/create-code-mode-tool.js +146 -0
- package/dist/esm/create-code-mode-tool.js.map +1 -0
- package/dist/esm/create-code-mode.d.ts +23 -0
- package/dist/esm/create-code-mode.js +19 -0
- package/dist/esm/create-code-mode.js.map +1 -0
- package/dist/esm/create-discovery-tool.d.ts +28 -0
- package/dist/esm/create-discovery-tool.js +62 -0
- package/dist/esm/create-discovery-tool.js.map +1 -0
- package/dist/esm/create-system-prompt.d.ts +24 -0
- package/dist/esm/create-system-prompt.js +76 -0
- package/dist/esm/create-system-prompt.js.map +1 -0
- package/dist/esm/index.d.ts +11 -0
- package/dist/esm/index.js +25 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/strip-typescript.d.ts +44 -0
- package/dist/esm/strip-typescript.js +49 -0
- package/dist/esm/strip-typescript.js.map +1 -0
- package/dist/esm/type-generator/json-schema-to-ts.d.ts +31 -0
- package/dist/esm/type-generator/json-schema-to-ts.js +100 -0
- package/dist/esm/type-generator/json-schema-to-ts.js.map +1 -0
- package/dist/esm/types.d.ts +238 -0
- package/package.json +3 -3
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { renderLazyCatalogEntry } from "@tanstack/ai";
|
|
2
|
+
import { toolsToBindings } from "./bindings/tool-to-binding.js";
|
|
3
|
+
import { generateTypeStubs } from "./type-generator/json-schema-to-ts.js";
|
|
4
|
+
function createCodeModeSystemPrompt(config) {
|
|
5
|
+
const { tools } = config;
|
|
6
|
+
const include = config.lazyToolsConfig?.includeDescription ?? "none";
|
|
7
|
+
const eagerTools = tools.filter((t) => !t.lazy);
|
|
8
|
+
const lazyTools = tools.filter((t) => t.lazy);
|
|
9
|
+
const bindings = toolsToBindings(eagerTools, "external_");
|
|
10
|
+
const typeStubs = generateTypeStubs(bindings);
|
|
11
|
+
const functionDocs = Object.entries(bindings).map(([name, binding]) => `- \`${name}(input)\`: ${binding.description}`).join("\n");
|
|
12
|
+
const discoverableSection = lazyTools.length > 0 ? `
|
|
13
|
+
|
|
14
|
+
### Discoverable APIs
|
|
15
|
+
|
|
16
|
+
These additional functions are available but not yet documented. Before calling \`external_<name>\` for any of them inside \`execute_typescript\`, call the \`discover_tools\` tool with their names to get full TypeScript signatures:
|
|
17
|
+
|
|
18
|
+
${lazyTools.map(
|
|
19
|
+
(t) => `- ${renderLazyCatalogEntry(`external_${t.name}`, t.description, include)}`
|
|
20
|
+
).join("\n")}` : "";
|
|
21
|
+
return `## Code Execution Tool
|
|
22
|
+
|
|
23
|
+
You have access to \`execute_typescript\` which runs TypeScript code in a sandboxed environment.
|
|
24
|
+
|
|
25
|
+
### When to Use
|
|
26
|
+
|
|
27
|
+
Use \`execute_typescript\` when you need to:
|
|
28
|
+
- Process data with loops, conditionals, or complex logic
|
|
29
|
+
- Make multiple API calls in parallel (Promise.all)
|
|
30
|
+
- Transform, filter, or aggregate data
|
|
31
|
+
- Perform calculations or data analysis
|
|
32
|
+
|
|
33
|
+
For simple operations, prefer calling tools directly.
|
|
34
|
+
|
|
35
|
+
### Available External APIs
|
|
36
|
+
|
|
37
|
+
Inside your TypeScript code, you can call these async functions:
|
|
38
|
+
|
|
39
|
+
${functionDocs}
|
|
40
|
+
|
|
41
|
+
### Type Definitions
|
|
42
|
+
|
|
43
|
+
\`\`\`typescript
|
|
44
|
+
${typeStubs}
|
|
45
|
+
\`\`\`${discoverableSection}
|
|
46
|
+
|
|
47
|
+
### Example
|
|
48
|
+
|
|
49
|
+
\`\`\`typescript
|
|
50
|
+
// Fetch weather for multiple cities in parallel
|
|
51
|
+
const cities = ["Tokyo", "Paris", "NYC"];
|
|
52
|
+
const results = await Promise.all(
|
|
53
|
+
cities.map(city => external_fetchWeather({ location: city }))
|
|
54
|
+
);
|
|
55
|
+
|
|
56
|
+
// Find the warmest city
|
|
57
|
+
const warmest = results.reduce((prev, curr) =>
|
|
58
|
+
curr.temperature > prev.temperature ? curr : prev
|
|
59
|
+
);
|
|
60
|
+
|
|
61
|
+
return { warmestCity: warmest.location, temperature: warmest.temperature };
|
|
62
|
+
\`\`\`
|
|
63
|
+
|
|
64
|
+
### Important Notes
|
|
65
|
+
|
|
66
|
+
- All \`external_*\` calls are async - always use \`await\`
|
|
67
|
+
- Return a value to pass results back to you
|
|
68
|
+
- Use \`console.log()\` for debugging (logs are captured)
|
|
69
|
+
- The sandbox is isolated - no network access or file system
|
|
70
|
+
- Each execution is independent (no shared state between calls)
|
|
71
|
+
`;
|
|
72
|
+
}
|
|
73
|
+
export {
|
|
74
|
+
createCodeModeSystemPrompt
|
|
75
|
+
};
|
|
76
|
+
//# sourceMappingURL=create-system-prompt.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"create-system-prompt.js","sources":["../../src/create-system-prompt.ts"],"sourcesContent":["import { renderLazyCatalogEntry } from '@tanstack/ai'\nimport { toolsToBindings } from './bindings/tool-to-binding'\nimport { generateTypeStubs } from './type-generator/json-schema-to-ts'\nimport type { CodeModeToolConfig } from './types'\n\n/**\n * Create a system prompt snippet that documents the execute_typescript tool\n * and all available external_* functions.\n *\n * Add this to your system prompts array when using createCodeModeTool.\n *\n * @example\n * ```typescript\n * import { createCodeMode } from '@tanstack/ai-code-mode'\n * import { createNodeIsolateDriver } from '@tanstack/ai-isolate-node'\n *\n * const { tool, systemPrompt } = createCodeMode({\n * driver: createNodeIsolateDriver(),\n * tools: [weatherTool, dbTool],\n * })\n *\n * chat({\n * systemPrompts: ['You are a helpful assistant.', systemPrompt],\n * tools: [tool, ...otherTools],\n * })\n * ```\n */\nexport function createCodeModeSystemPrompt(config: CodeModeToolConfig): string {\n const { tools } = config\n const include = config.lazyToolsConfig?.includeDescription ?? 'none'\n\n const eagerTools = tools.filter((t) => !t.lazy)\n const lazyTools = tools.filter((t) => t.lazy)\n\n // Only eager tools get full type stubs + doc lines.\n const bindings = toolsToBindings(eagerTools, 'external_')\n const typeStubs = generateTypeStubs(bindings)\n\n const functionDocs = Object.entries(bindings)\n .map(([name, binding]) => `- \\`${name}(input)\\`: ${binding.description}`)\n .join('\\n')\n\n const discoverableSection =\n lazyTools.length > 0\n ? `\n\n### Discoverable APIs\n\nThese additional functions are available but not yet documented. Before calling \\`external_<name>\\` for any of them inside \\`execute_typescript\\`, call the \\`discover_tools\\` tool with their names to get full TypeScript signatures:\n\n${lazyTools\n .map(\n (t) =>\n `- ${renderLazyCatalogEntry(`external_${t.name}`, t.description, include)}`,\n )\n .join('\\n')}`\n : ''\n\n return `## Code Execution Tool\n\nYou have access to \\`execute_typescript\\` which runs TypeScript code in a sandboxed environment.\n\n### When to Use\n\nUse \\`execute_typescript\\` when you need to:\n- Process data with loops, conditionals, or complex logic\n- Make multiple API calls in parallel (Promise.all)\n- Transform, filter, or aggregate data\n- Perform calculations or data analysis\n\nFor simple operations, prefer calling tools directly.\n\n### Available External APIs\n\nInside your TypeScript code, you can call these async functions:\n\n${functionDocs}\n\n### Type Definitions\n\n\\`\\`\\`typescript\n${typeStubs}\n\\`\\`\\`${discoverableSection}\n\n### Example\n\n\\`\\`\\`typescript\n// Fetch weather for multiple cities in parallel\nconst cities = [\"Tokyo\", \"Paris\", \"NYC\"];\nconst results = await Promise.all(\n cities.map(city => external_fetchWeather({ location: city }))\n);\n\n// Find the warmest city\nconst warmest = results.reduce((prev, curr) =>\n curr.temperature > prev.temperature ? curr : prev\n);\n\nreturn { warmestCity: warmest.location, temperature: warmest.temperature };\n\\`\\`\\`\n\n### Important Notes\n\n- All \\`external_*\\` calls are async - always use \\`await\\`\n- Return a value to pass results back to you\n- Use \\`console.log()\\` for debugging (logs are captured)\n- The sandbox is isolated - no network access or file system\n- Each execution is independent (no shared state between calls)\n`\n}\n"],"names":[],"mappings":";;;AA2BO,SAAS,2BAA2B,QAAoC;AAC7E,QAAM,EAAE,UAAU;AAClB,QAAM,UAAU,OAAO,iBAAiB,sBAAsB;AAE9D,QAAM,aAAa,MAAM,OAAO,CAAC,MAAM,CAAC,EAAE,IAAI;AAC9C,QAAM,YAAY,MAAM,OAAO,CAAC,MAAM,EAAE,IAAI;AAG5C,QAAM,WAAW,gBAAgB,YAAY,WAAW;AACxD,QAAM,YAAY,kBAAkB,QAAQ;AAE5C,QAAM,eAAe,OAAO,QAAQ,QAAQ,EACzC,IAAI,CAAC,CAAC,MAAM,OAAO,MAAM,OAAO,IAAI,cAAc,QAAQ,WAAW,EAAE,EACvE,KAAK,IAAI;AAEZ,QAAM,sBACJ,UAAU,SAAS,IACf;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMN,UACC;AAAA,IACC,CAAC,MACC,KAAK,uBAAuB,YAAY,EAAE,IAAI,IAAI,EAAE,aAAa,OAAO,CAAC;AAAA,EAAA,EAE5E,KAAK,IAAI,CAAC,KACL;AAEN,SAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAkBP,YAAY;AAAA;AAAA;AAAA;AAAA;AAAA,EAKZ,SAAS;AAAA,QACH,mBAAmB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA2B3B;"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export { createCodeModeTool } from './create-code-mode-tool.js';
|
|
2
|
+
export type { ExecuteTypescriptInput, ExecuteTypescriptOutput, } from './create-code-mode-tool.js';
|
|
3
|
+
export { createCodeModeSystemPrompt } from './create-system-prompt.js';
|
|
4
|
+
export { createCodeMode } from './create-code-mode.js';
|
|
5
|
+
export { createDiscoveryTool } from './create-discovery-tool.js';
|
|
6
|
+
export { InMemoryAgentStore, generateAgentName, type AgentSession, type AgentStore, } from './agent-store.js';
|
|
7
|
+
export { toolToBinding, toolsToBindings, createEventAwareBindings, } from './bindings/tool-to-binding.js';
|
|
8
|
+
export { generateTypeStubs, jsonSchemaToTypeScript, type TypeGeneratorOptions, } from './type-generator/json-schema-to-ts.js';
|
|
9
|
+
export { stripTypeScript } from './strip-typescript.js';
|
|
10
|
+
export { wrapCode } from './code-wrapper.js';
|
|
11
|
+
export type { CodeModeToolConfig, CreateCodeModeResult, CodeModeToolResult, IsolateDriver, IsolateConfig, IsolateContext, ExecutionResult, NormalizedError, ToolBinding, CodeModeTool, ToolExecutionContext, } from './types.js';
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { createCodeModeTool } from "./create-code-mode-tool.js";
|
|
2
|
+
import { createCodeModeSystemPrompt } from "./create-system-prompt.js";
|
|
3
|
+
import { createCodeMode } from "./create-code-mode.js";
|
|
4
|
+
import { createDiscoveryTool } from "./create-discovery-tool.js";
|
|
5
|
+
import { InMemoryAgentStore, generateAgentName } from "./agent-store.js";
|
|
6
|
+
import { createEventAwareBindings, toolToBinding, toolsToBindings } from "./bindings/tool-to-binding.js";
|
|
7
|
+
import { generateTypeStubs, jsonSchemaToTypeScript } from "./type-generator/json-schema-to-ts.js";
|
|
8
|
+
import { stripTypeScript } from "./strip-typescript.js";
|
|
9
|
+
import { wrapCode } from "./code-wrapper.js";
|
|
10
|
+
export {
|
|
11
|
+
InMemoryAgentStore,
|
|
12
|
+
createCodeMode,
|
|
13
|
+
createCodeModeSystemPrompt,
|
|
14
|
+
createCodeModeTool,
|
|
15
|
+
createDiscoveryTool,
|
|
16
|
+
createEventAwareBindings,
|
|
17
|
+
generateAgentName,
|
|
18
|
+
generateTypeStubs,
|
|
19
|
+
jsonSchemaToTypeScript,
|
|
20
|
+
stripTypeScript,
|
|
21
|
+
toolToBinding,
|
|
22
|
+
toolsToBindings,
|
|
23
|
+
wrapCode
|
|
24
|
+
};
|
|
25
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;"}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Strip TypeScript syntax from code, converting it to plain JavaScript.
|
|
3
|
+
*
|
|
4
|
+
* This is a safety net to ensure that even if an LLM generates TypeScript
|
|
5
|
+
* code with type annotations, it will be converted to valid JavaScript
|
|
6
|
+
* before being sent to the sandbox for execution.
|
|
7
|
+
*
|
|
8
|
+
* Uses sucrase's pure-JavaScript `transform`, which strips the TypeScript
|
|
9
|
+
* syntax that LLM-generated snippets use in practice:
|
|
10
|
+
* - Type annotations (: string, : number, etc.)
|
|
11
|
+
* - Generic types (Array<T>, Record<K, V>, etc.)
|
|
12
|
+
* - Interface and type declarations
|
|
13
|
+
* - Type assertions
|
|
14
|
+
* - Enums (converted to JavaScript objects)
|
|
15
|
+
*
|
|
16
|
+
* Unlike esbuild, sucrase has no native binary and pulls in no Node-only
|
|
17
|
+
* built-ins on its `transform` path, so this module is safe to bundle for
|
|
18
|
+
* browsers and edge runtimes (Cloudflare Workers/Pages etc.).
|
|
19
|
+
*
|
|
20
|
+
* Limitations vs esbuild: sucrase is a type-stripper, not a down-leveler.
|
|
21
|
+
* `disableESTransforms` leaves modern ECMAScript syntax untouched (the sandbox
|
|
22
|
+
* engines are modern), and sucrase does NOT compile a few exotic constructs:
|
|
23
|
+
* - TypeScript value `namespace`/`module` blocks are DROPPED (not emitted as an
|
|
24
|
+
* IIFE), so referencing the namespace at runtime throws `ReferenceError`.
|
|
25
|
+
* - Decorators and the `accessor` keyword pass through un-lowered, so the
|
|
26
|
+
* sandbox sees invalid syntax.
|
|
27
|
+
* - Post-ES2022 syntax (`using` declarations, RegExp `/v`·`/d` flags) is passed
|
|
28
|
+
* through; it runs on modern V8/Node sandboxes but may fail on older engines
|
|
29
|
+
* (e.g. QuickJS).
|
|
30
|
+
* If you need any of these, supply a heavier (Node-only) transpiler via the
|
|
31
|
+
* `transpile` option on `createCodeModeTool`.
|
|
32
|
+
*
|
|
33
|
+
* The code is wrapped in an async function before transformation to allow
|
|
34
|
+
* top-level `return` and `await` statements, then unwrapped after.
|
|
35
|
+
*
|
|
36
|
+
* Note on errors: sucrase reports syntax errors with a position relative to the
|
|
37
|
+
* *wrapped* code (offset by the one-line wrapper prefix), so any line numbers
|
|
38
|
+
* surfaced downstream (e.g. `CodeModeToolResult.error.line`) are approximate.
|
|
39
|
+
*
|
|
40
|
+
* @param code - TypeScript or JavaScript code
|
|
41
|
+
* @returns Plain JavaScript code with all type syntax removed
|
|
42
|
+
* @throws Error if sucrase fails (e.g., syntax error) or wrapper extraction fails
|
|
43
|
+
*/
|
|
44
|
+
export declare function stripTypeScript(code: string): Promise<string>;
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { transform } from "sucrase";
|
|
2
|
+
const WRAPPER_START = "___TANSTACK_WRAPPER_START___";
|
|
3
|
+
const WRAPPER_END = "___TANSTACK_WRAPPER_END___";
|
|
4
|
+
async function stripTypeScript(code) {
|
|
5
|
+
const wrappedCode = `async function ${WRAPPER_START}() {
|
|
6
|
+
${code}
|
|
7
|
+
}; ${WRAPPER_END}`;
|
|
8
|
+
const result = transform(wrappedCode, {
|
|
9
|
+
// Only strip/lower TypeScript-specific syntax...
|
|
10
|
+
transforms: ["typescript"],
|
|
11
|
+
// ...and leave modern ECMAScript syntax untouched for the sandbox engines.
|
|
12
|
+
disableESTransforms: true
|
|
13
|
+
});
|
|
14
|
+
const transformed = result.code;
|
|
15
|
+
const functionStart = transformed.indexOf(`async function ${WRAPPER_START}()`);
|
|
16
|
+
if (functionStart === -1) {
|
|
17
|
+
throw new Error(
|
|
18
|
+
"[stripTypeScript] Could not find wrapper function start in transformed output"
|
|
19
|
+
);
|
|
20
|
+
}
|
|
21
|
+
const openBrace = transformed.indexOf("{", functionStart);
|
|
22
|
+
if (openBrace === -1) {
|
|
23
|
+
throw new Error(
|
|
24
|
+
"[stripTypeScript] Could not find opening brace in transformed output"
|
|
25
|
+
);
|
|
26
|
+
}
|
|
27
|
+
const endMarkerIndex = transformed.indexOf(WRAPPER_END);
|
|
28
|
+
if (endMarkerIndex === -1) {
|
|
29
|
+
throw new Error(
|
|
30
|
+
"[stripTypeScript] Could not find end marker in transformed output"
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
const codeBeforeEndMarker = transformed.substring(
|
|
34
|
+
openBrace + 1,
|
|
35
|
+
endMarkerIndex
|
|
36
|
+
);
|
|
37
|
+
const closingBraceIndex = codeBeforeEndMarker.lastIndexOf("}");
|
|
38
|
+
if (closingBraceIndex === -1) {
|
|
39
|
+
throw new Error(
|
|
40
|
+
"[stripTypeScript] Could not find closing brace in transformed output"
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
const functionBody = codeBeforeEndMarker.substring(0, closingBraceIndex).trim();
|
|
44
|
+
return functionBody;
|
|
45
|
+
}
|
|
46
|
+
export {
|
|
47
|
+
stripTypeScript
|
|
48
|
+
};
|
|
49
|
+
//# sourceMappingURL=strip-typescript.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"strip-typescript.js","sources":["../../src/strip-typescript.ts"],"sourcesContent":["import { transform } from 'sucrase'\n\n// Unique markers for wrapping/unwrapping code\nconst WRAPPER_START = '___TANSTACK_WRAPPER_START___'\nconst WRAPPER_END = '___TANSTACK_WRAPPER_END___'\n\n/**\n * Strip TypeScript syntax from code, converting it to plain JavaScript.\n *\n * This is a safety net to ensure that even if an LLM generates TypeScript\n * code with type annotations, it will be converted to valid JavaScript\n * before being sent to the sandbox for execution.\n *\n * Uses sucrase's pure-JavaScript `transform`, which strips the TypeScript\n * syntax that LLM-generated snippets use in practice:\n * - Type annotations (: string, : number, etc.)\n * - Generic types (Array<T>, Record<K, V>, etc.)\n * - Interface and type declarations\n * - Type assertions\n * - Enums (converted to JavaScript objects)\n *\n * Unlike esbuild, sucrase has no native binary and pulls in no Node-only\n * built-ins on its `transform` path, so this module is safe to bundle for\n * browsers and edge runtimes (Cloudflare Workers/Pages etc.).\n *\n * Limitations vs esbuild: sucrase is a type-stripper, not a down-leveler.\n * `disableESTransforms` leaves modern ECMAScript syntax untouched (the sandbox\n * engines are modern), and sucrase does NOT compile a few exotic constructs:\n * - TypeScript value `namespace`/`module` blocks are DROPPED (not emitted as an\n * IIFE), so referencing the namespace at runtime throws `ReferenceError`.\n * - Decorators and the `accessor` keyword pass through un-lowered, so the\n * sandbox sees invalid syntax.\n * - Post-ES2022 syntax (`using` declarations, RegExp `/v`·`/d` flags) is passed\n * through; it runs on modern V8/Node sandboxes but may fail on older engines\n * (e.g. QuickJS).\n * If you need any of these, supply a heavier (Node-only) transpiler via the\n * `transpile` option on `createCodeModeTool`.\n *\n * The code is wrapped in an async function before transformation to allow\n * top-level `return` and `await` statements, then unwrapped after.\n *\n * Note on errors: sucrase reports syntax errors with a position relative to the\n * *wrapped* code (offset by the one-line wrapper prefix), so any line numbers\n * surfaced downstream (e.g. `CodeModeToolResult.error.line`) are approximate.\n *\n * @param code - TypeScript or JavaScript code\n * @returns Plain JavaScript code with all type syntax removed\n * @throws Error if sucrase fails (e.g., syntax error) or wrapper extraction fails\n */\n// sucrase's transform is synchronous, but we keep the published Promise-returning\n// signature so existing `await stripTypeScript(...)` callers (and a custom async\n// `transpile` hook) stay source-compatible across this swap.\n// eslint-disable-next-line @typescript-eslint/require-await\nexport async function stripTypeScript(code: string): Promise<string> {\n // Wrap the code in an async function to allow top-level return/await.\n // This is necessary because top-level `return` is invalid outside a function.\n const wrappedCode = `async function ${WRAPPER_START}() {\\n${code}\\n}; ${WRAPPER_END}`\n\n const result = transform(wrappedCode, {\n // Only strip/lower TypeScript-specific syntax...\n transforms: ['typescript'],\n // ...and leave modern ECMAScript syntax untouched for the sandbox engines.\n disableESTransforms: true,\n })\n\n // Extract the code from inside the wrapper function\n const transformed = result.code\n\n // Find the function declaration start\n const functionStart = transformed.indexOf(`async function ${WRAPPER_START}()`)\n if (functionStart === -1) {\n throw new Error(\n '[stripTypeScript] Could not find wrapper function start in transformed output',\n )\n }\n\n // Find the opening brace of the function\n const openBrace = transformed.indexOf('{', functionStart)\n if (openBrace === -1) {\n throw new Error(\n '[stripTypeScript] Could not find opening brace in transformed output',\n )\n }\n\n // Find the end marker (regardless of formatting)\n const endMarkerIndex = transformed.indexOf(WRAPPER_END)\n if (endMarkerIndex === -1) {\n throw new Error(\n '[stripTypeScript] Could not find end marker in transformed output',\n )\n }\n\n // Find the closing brace of the function (last } before the end marker)\n // We need to find the } that matches the function opening\n const codeBeforeEndMarker = transformed.substring(\n openBrace + 1,\n endMarkerIndex,\n )\n\n // Find the last } before the end marker, accounting for the semicolon\n // The code will be: ...function body...}; WRAPPER_END or ...};\\nWRAPPER_END\n const closingBraceIndex = codeBeforeEndMarker.lastIndexOf('}')\n\n if (closingBraceIndex === -1) {\n throw new Error(\n '[stripTypeScript] Could not find closing brace in transformed output',\n )\n }\n\n // Extract the function body (between { and })\n const functionBody = codeBeforeEndMarker\n .substring(0, closingBraceIndex)\n .trim()\n\n return functionBody\n}\n"],"names":[],"mappings":";AAGA,MAAM,gBAAgB;AACtB,MAAM,cAAc;AAiDpB,eAAsB,gBAAgB,MAA+B;AAGnE,QAAM,cAAc,kBAAkB,aAAa;AAAA,EAAS,IAAI;AAAA,KAAQ,WAAW;AAEnF,QAAM,SAAS,UAAU,aAAa;AAAA;AAAA,IAEpC,YAAY,CAAC,YAAY;AAAA;AAAA,IAEzB,qBAAqB;AAAA,EAAA,CACtB;AAGD,QAAM,cAAc,OAAO;AAG3B,QAAM,gBAAgB,YAAY,QAAQ,kBAAkB,aAAa,IAAI;AAC7E,MAAI,kBAAkB,IAAI;AACxB,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAAA,EAEJ;AAGA,QAAM,YAAY,YAAY,QAAQ,KAAK,aAAa;AACxD,MAAI,cAAc,IAAI;AACpB,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAAA,EAEJ;AAGA,QAAM,iBAAiB,YAAY,QAAQ,WAAW;AACtD,MAAI,mBAAmB,IAAI;AACzB,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAAA,EAEJ;AAIA,QAAM,sBAAsB,YAAY;AAAA,IACtC,YAAY;AAAA,IACZ;AAAA,EAAA;AAKF,QAAM,oBAAoB,oBAAoB,YAAY,GAAG;AAE7D,MAAI,sBAAsB,IAAI;AAC5B,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAAA,EAEJ;AAGA,QAAM,eAAe,oBAClB,UAAU,GAAG,iBAAiB,EAC9B,KAAA;AAEH,SAAO;AACT;"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { ToolBinding } from '../types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Options for type stub generation
|
|
4
|
+
*/
|
|
5
|
+
export interface TypeGeneratorOptions {
|
|
6
|
+
/**
|
|
7
|
+
* Include JSDoc comments with descriptions
|
|
8
|
+
* @default true
|
|
9
|
+
*/
|
|
10
|
+
includeDescriptions?: boolean;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Generate TypeScript type stubs for all tool bindings
|
|
14
|
+
*
|
|
15
|
+
* These stubs are included in the LLM system prompt so it knows
|
|
16
|
+
* the exact type signatures of available tools.
|
|
17
|
+
*
|
|
18
|
+
* Tool names match the actual function names injected into the sandbox.
|
|
19
|
+
*/
|
|
20
|
+
export declare function generateTypeStubs(bindings: Record<string, ToolBinding>, options?: TypeGeneratorOptions): string;
|
|
21
|
+
interface TypeResult {
|
|
22
|
+
name: string;
|
|
23
|
+
declaration: string;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Convert a JSON Schema to a TypeScript type
|
|
27
|
+
*
|
|
28
|
+
* Supports basic types: string, number, boolean, object, array
|
|
29
|
+
*/
|
|
30
|
+
export declare function jsonSchemaToTypeScript(schema: Record<string, unknown>, typeName: string): TypeResult;
|
|
31
|
+
export {};
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
function generateTypeStubs(bindings, options = {}) {
|
|
2
|
+
const { includeDescriptions = true } = options;
|
|
3
|
+
const declarations = [];
|
|
4
|
+
for (const [name, binding] of Object.entries(bindings)) {
|
|
5
|
+
const inputTypeName = `${capitalize(name)}Input`;
|
|
6
|
+
const outputTypeName = `${capitalize(name)}Output`;
|
|
7
|
+
const inputType = jsonSchemaToTypeScript(binding.inputSchema, inputTypeName);
|
|
8
|
+
if (inputType.declaration) {
|
|
9
|
+
declarations.push(inputType.declaration);
|
|
10
|
+
}
|
|
11
|
+
let outputTypeRef = "unknown";
|
|
12
|
+
if (binding.outputSchema) {
|
|
13
|
+
const outputType = jsonSchemaToTypeScript(
|
|
14
|
+
binding.outputSchema,
|
|
15
|
+
outputTypeName
|
|
16
|
+
);
|
|
17
|
+
if (outputType.declaration) {
|
|
18
|
+
declarations.push(outputType.declaration);
|
|
19
|
+
}
|
|
20
|
+
outputTypeRef = outputType.name;
|
|
21
|
+
}
|
|
22
|
+
const description = includeDescriptions && binding.description ? `/** ${binding.description} */
|
|
23
|
+
` : "";
|
|
24
|
+
declarations.push(
|
|
25
|
+
`${description}declare function ${name}(input: ${inputType.name}): Promise<${outputTypeRef}>;`
|
|
26
|
+
);
|
|
27
|
+
}
|
|
28
|
+
return declarations.join("\n\n");
|
|
29
|
+
}
|
|
30
|
+
function jsonSchemaToTypeScript(schema, typeName) {
|
|
31
|
+
const type = schemaToType(schema);
|
|
32
|
+
if (schema.type === "object" && schema.properties && Object.keys(schema.properties).length > 0) {
|
|
33
|
+
return {
|
|
34
|
+
name: typeName,
|
|
35
|
+
declaration: `interface ${typeName} ${type}`
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
return {
|
|
39
|
+
name: type,
|
|
40
|
+
declaration: ""
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
function schemaToType(schema) {
|
|
44
|
+
if (typeof schema !== "object") {
|
|
45
|
+
return "unknown";
|
|
46
|
+
}
|
|
47
|
+
const schemaType = schema.type;
|
|
48
|
+
if (schemaType === "string") return "string";
|
|
49
|
+
if (schemaType === "number" || schemaType === "integer") return "number";
|
|
50
|
+
if (schemaType === "boolean") return "boolean";
|
|
51
|
+
if (schemaType === "null") return "null";
|
|
52
|
+
if (schemaType === "array") {
|
|
53
|
+
const items = schema.items;
|
|
54
|
+
const itemType = items ? schemaToType(items) : "unknown";
|
|
55
|
+
return `Array<${itemType}>`;
|
|
56
|
+
}
|
|
57
|
+
if (schemaType === "object" && schema.properties) {
|
|
58
|
+
const properties = schema.properties;
|
|
59
|
+
const required = new Set(
|
|
60
|
+
schema.required ?? []
|
|
61
|
+
);
|
|
62
|
+
const props = Object.entries(properties).map(([key, propSchema]) => {
|
|
63
|
+
const optional = required.has(key) ? "" : "?";
|
|
64
|
+
const propType = schemaToType(propSchema);
|
|
65
|
+
const safeName = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(key) ? key : `"${key}"`;
|
|
66
|
+
return ` ${safeName}${optional}: ${propType};`;
|
|
67
|
+
}).join("\n");
|
|
68
|
+
return `{
|
|
69
|
+
${props}
|
|
70
|
+
}`;
|
|
71
|
+
}
|
|
72
|
+
if (schema.enum) {
|
|
73
|
+
const enumValues = schema.enum;
|
|
74
|
+
return enumValues.map((v) => JSON.stringify(v)).join(" | ");
|
|
75
|
+
}
|
|
76
|
+
if (schema.anyOf || schema.oneOf) {
|
|
77
|
+
const variants = schema.anyOf || schema.oneOf;
|
|
78
|
+
return variants.map((v) => schemaToType(v)).join(" | ");
|
|
79
|
+
}
|
|
80
|
+
if (Array.isArray(schemaType)) {
|
|
81
|
+
return schemaType.map((t) => {
|
|
82
|
+
if (t === "string") return "string";
|
|
83
|
+
if (t === "number" || t === "integer") return "number";
|
|
84
|
+
if (t === "boolean") return "boolean";
|
|
85
|
+
if (t === "null") return "null";
|
|
86
|
+
if (t === "array") return "Array<unknown>";
|
|
87
|
+
if (t === "object") return "object";
|
|
88
|
+
return "unknown";
|
|
89
|
+
}).join(" | ");
|
|
90
|
+
}
|
|
91
|
+
return "unknown";
|
|
92
|
+
}
|
|
93
|
+
function capitalize(str) {
|
|
94
|
+
return str.charAt(0).toUpperCase() + str.slice(1);
|
|
95
|
+
}
|
|
96
|
+
export {
|
|
97
|
+
generateTypeStubs,
|
|
98
|
+
jsonSchemaToTypeScript
|
|
99
|
+
};
|
|
100
|
+
//# sourceMappingURL=json-schema-to-ts.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"json-schema-to-ts.js","sources":["../../../src/type-generator/json-schema-to-ts.ts"],"sourcesContent":["import type { ToolBinding } from '../types'\n\n/**\n * Options for type stub generation\n */\nexport interface TypeGeneratorOptions {\n /**\n * Include JSDoc comments with descriptions\n * @default true\n */\n includeDescriptions?: boolean\n}\n\n/**\n * Generate TypeScript type stubs for all tool bindings\n *\n * These stubs are included in the LLM system prompt so it knows\n * the exact type signatures of available tools.\n *\n * Tool names match the actual function names injected into the sandbox.\n */\nexport function generateTypeStubs(\n bindings: Record<string, ToolBinding>,\n options: TypeGeneratorOptions = {},\n): string {\n const { includeDescriptions = true } = options\n\n const declarations: Array<string> = []\n\n for (const [name, binding] of Object.entries(bindings)) {\n const inputTypeName = `${capitalize(name)}Input`\n const outputTypeName = `${capitalize(name)}Output`\n\n // Generate input type\n const inputType = jsonSchemaToTypeScript(binding.inputSchema, inputTypeName)\n if (inputType.declaration) {\n declarations.push(inputType.declaration)\n }\n\n // Generate output type if present\n let outputTypeRef = 'unknown'\n if (binding.outputSchema) {\n const outputType = jsonSchemaToTypeScript(\n binding.outputSchema,\n outputTypeName,\n )\n if (outputType.declaration) {\n declarations.push(outputType.declaration)\n }\n outputTypeRef = outputType.name\n }\n\n // Generate function declaration matching the actual sandbox function name\n const description =\n includeDescriptions && binding.description\n ? `/** ${binding.description} */\\n`\n : ''\n\n declarations.push(\n `${description}declare function ${name}(input: ${inputType.name}): Promise<${outputTypeRef}>;`,\n )\n }\n\n return declarations.join('\\n\\n')\n}\n\ninterface TypeResult {\n name: string\n declaration: string\n}\n\n/**\n * Convert a JSON Schema to a TypeScript type\n *\n * Supports basic types: string, number, boolean, object, array\n */\nexport function jsonSchemaToTypeScript(\n schema: Record<string, unknown>,\n typeName: string,\n): TypeResult {\n const type = schemaToType(schema)\n\n // For object schemas with properties, create a named interface\n if (\n schema.type === 'object' &&\n schema.properties &&\n Object.keys(schema.properties).length > 0\n ) {\n return {\n name: typeName,\n declaration: `interface ${typeName} ${type}`,\n }\n }\n\n // For simple types or empty objects, create a type alias\n return {\n name: type,\n declaration: '',\n }\n}\n\n/**\n * Convert a JSON Schema to a TypeScript type string\n */\nfunction schemaToType(schema: Record<string, unknown>): string {\n if (typeof schema !== 'object') {\n return 'unknown'\n }\n\n const schemaType = schema.type\n\n // Handle basic types\n if (schemaType === 'string') return 'string'\n if (schemaType === 'number' || schemaType === 'integer') return 'number'\n if (schemaType === 'boolean') return 'boolean'\n if (schemaType === 'null') return 'null'\n\n // Handle arrays\n if (schemaType === 'array') {\n const items = schema.items as Record<string, unknown> | undefined\n const itemType = items ? schemaToType(items) : 'unknown'\n return `Array<${itemType}>`\n }\n\n // Handle objects with properties\n if (schemaType === 'object' && schema.properties) {\n const properties = schema.properties as Record<\n string,\n Record<string, unknown>\n >\n const required = new Set(\n (schema.required as Array<string> | undefined) ?? [],\n )\n\n const props = Object.entries(properties)\n .map(([key, propSchema]) => {\n const optional = required.has(key) ? '' : '?'\n const propType = schemaToType(propSchema)\n // Handle property names that need quoting\n const safeName = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(key)\n ? key\n : `\"${key}\"`\n return ` ${safeName}${optional}: ${propType};`\n })\n .join('\\n')\n\n return `{\\n${props}\\n}`\n }\n\n // Handle enums\n if (schema.enum) {\n const enumValues = schema.enum as Array<unknown>\n return enumValues.map((v) => JSON.stringify(v)).join(' | ')\n }\n\n // Handle union types (anyOf, oneOf)\n if (schema.anyOf || schema.oneOf) {\n const variants = (schema.anyOf || schema.oneOf) as Array<\n Record<string, unknown>\n >\n return variants.map((v) => schemaToType(v)).join(' | ')\n }\n\n // Handle type arrays (e.g., [\"string\", \"null\"])\n if (Array.isArray(schemaType)) {\n return schemaType\n .map((t) => {\n if (t === 'string') return 'string'\n if (t === 'number' || t === 'integer') return 'number'\n if (t === 'boolean') return 'boolean'\n if (t === 'null') return 'null'\n if (t === 'array') return 'Array<unknown>'\n if (t === 'object') return 'object'\n return 'unknown'\n })\n .join(' | ')\n }\n\n // Fallback for unknown schemas\n return 'unknown'\n}\n\n/**\n * Capitalize the first letter of a string\n */\nfunction capitalize(str: string): string {\n return str.charAt(0).toUpperCase() + str.slice(1)\n}\n"],"names":[],"mappings":"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"}
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
import { LazyToolsConfig, SchemaInput, ServerTool, ToolExecutionContext } from '@tanstack/ai';
|
|
2
|
+
/**
|
|
3
|
+
* Interface for isolate/sandbox drivers
|
|
4
|
+
* Each runtime environment implements this to provide sandboxed code execution
|
|
5
|
+
*/
|
|
6
|
+
export interface IsolateDriver {
|
|
7
|
+
/**
|
|
8
|
+
* Create a new isolated execution context with tool bindings
|
|
9
|
+
*/
|
|
10
|
+
createContext: (config: IsolateConfig) => Promise<IsolateContext>;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Configuration for creating an isolate context
|
|
14
|
+
*/
|
|
15
|
+
export interface IsolateConfig {
|
|
16
|
+
/**
|
|
17
|
+
* Tools transformed into callable bindings for the sandbox
|
|
18
|
+
*/
|
|
19
|
+
bindings: Record<string, ToolBinding>;
|
|
20
|
+
/**
|
|
21
|
+
* Execution timeout in milliseconds (default: 30000)
|
|
22
|
+
*/
|
|
23
|
+
timeout?: number;
|
|
24
|
+
/**
|
|
25
|
+
* Memory limit in MB (default: 128)
|
|
26
|
+
*/
|
|
27
|
+
memoryLimit?: number;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Isolated execution context with tool bindings injected
|
|
31
|
+
*/
|
|
32
|
+
export interface IsolateContext {
|
|
33
|
+
/**
|
|
34
|
+
* Execute generated code and return results
|
|
35
|
+
*/
|
|
36
|
+
execute: <T = unknown>(code: string) => Promise<ExecutionResult<T>>;
|
|
37
|
+
/**
|
|
38
|
+
* Clean up sandbox resources
|
|
39
|
+
*/
|
|
40
|
+
dispose: () => Promise<void>;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Result of code execution in the sandbox
|
|
44
|
+
*/
|
|
45
|
+
export interface ExecutionResult<T = unknown> {
|
|
46
|
+
/**
|
|
47
|
+
* Whether execution completed without errors
|
|
48
|
+
*/
|
|
49
|
+
success: boolean;
|
|
50
|
+
/**
|
|
51
|
+
* Return value from the executed code (if successful)
|
|
52
|
+
*/
|
|
53
|
+
value?: T;
|
|
54
|
+
/**
|
|
55
|
+
* Normalized error information (if failed)
|
|
56
|
+
*/
|
|
57
|
+
error?: NormalizedError;
|
|
58
|
+
/**
|
|
59
|
+
* Console output captured during execution
|
|
60
|
+
*/
|
|
61
|
+
logs?: Array<string>;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Normalized error format for cross-runtime compatibility
|
|
65
|
+
*/
|
|
66
|
+
export interface NormalizedError {
|
|
67
|
+
/**
|
|
68
|
+
* Error name/type
|
|
69
|
+
*/
|
|
70
|
+
name: string;
|
|
71
|
+
/**
|
|
72
|
+
* Error message
|
|
73
|
+
*/
|
|
74
|
+
message: string;
|
|
75
|
+
/**
|
|
76
|
+
* Stack trace (if available)
|
|
77
|
+
*/
|
|
78
|
+
stack?: string;
|
|
79
|
+
/**
|
|
80
|
+
* Error code (if available)
|
|
81
|
+
*/
|
|
82
|
+
code?: string;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* A tool transformed into a format suitable for sandbox injection
|
|
86
|
+
*/
|
|
87
|
+
export interface ToolBinding {
|
|
88
|
+
/**
|
|
89
|
+
* Unique tool identifier
|
|
90
|
+
*/
|
|
91
|
+
name: string;
|
|
92
|
+
/**
|
|
93
|
+
* Human-readable description for the LLM
|
|
94
|
+
*/
|
|
95
|
+
description: string;
|
|
96
|
+
/**
|
|
97
|
+
* JSON Schema for tool input parameters
|
|
98
|
+
*/
|
|
99
|
+
inputSchema: Record<string, unknown>;
|
|
100
|
+
/**
|
|
101
|
+
* JSON Schema for tool output (optional)
|
|
102
|
+
*/
|
|
103
|
+
outputSchema?: Record<string, unknown> | undefined;
|
|
104
|
+
/**
|
|
105
|
+
* The execute function that will be injected into the sandbox.
|
|
106
|
+
* Accepts optional context for emitting custom events.
|
|
107
|
+
*/
|
|
108
|
+
execute: (args: unknown, context?: ToolExecutionContext) => Promise<unknown>;
|
|
109
|
+
}
|
|
110
|
+
export type { ToolExecutionContext };
|
|
111
|
+
/**
|
|
112
|
+
* Server-side tool types that can be passed to Code Mode.
|
|
113
|
+
*
|
|
114
|
+
* Code Mode executes tools inside a server-managed sandbox. Client tools and
|
|
115
|
+
* bare tool definitions are intentionally excluded because they do not provide
|
|
116
|
+
* a server execution implementation for the sandbox binding.
|
|
117
|
+
*/
|
|
118
|
+
export type CodeModeTool = ServerTool<SchemaInput, SchemaInput, string, unknown>;
|
|
119
|
+
/**
|
|
120
|
+
* Configuration for createCodeModeTool
|
|
121
|
+
*/
|
|
122
|
+
export interface CodeModeToolConfig {
|
|
123
|
+
/**
|
|
124
|
+
* Isolate driver for sandboxed code execution
|
|
125
|
+
*/
|
|
126
|
+
driver: IsolateDriver;
|
|
127
|
+
/**
|
|
128
|
+
* Tools to expose as external_* functions in the sandbox
|
|
129
|
+
*/
|
|
130
|
+
tools: Array<CodeModeTool>;
|
|
131
|
+
/**
|
|
132
|
+
* Execution timeout in milliseconds (default: 30000)
|
|
133
|
+
*/
|
|
134
|
+
timeout?: number;
|
|
135
|
+
/**
|
|
136
|
+
* Memory limit for isolate in MB (default: 128)
|
|
137
|
+
*/
|
|
138
|
+
memoryLimit?: number;
|
|
139
|
+
/**
|
|
140
|
+
* Optional function to get additional bindings dynamically.
|
|
141
|
+
* Called at execution time (each execute_typescript call) to get current skill bindings.
|
|
142
|
+
* These are merged with the static external_* bindings.
|
|
143
|
+
*
|
|
144
|
+
* @returns Record of skill bindings with skill_ prefix
|
|
145
|
+
*
|
|
146
|
+
* @example
|
|
147
|
+
* ```typescript
|
|
148
|
+
* getSkillBindings: async () => {
|
|
149
|
+
* const skills = await storage.loadAll()
|
|
150
|
+
* return skillsToBindings(skills, 'skill_')
|
|
151
|
+
* }
|
|
152
|
+
* ```
|
|
153
|
+
*/
|
|
154
|
+
getSkillBindings?: () => Promise<Record<string, ToolBinding>>;
|
|
155
|
+
/**
|
|
156
|
+
* Optional lazy-tool discovery config. Tools marked `lazy: true` are kept out
|
|
157
|
+
* of the system prompt's full documentation and listed in a Discoverable APIs
|
|
158
|
+
* catalog instead; this tunes how much of each lazy tool's description that
|
|
159
|
+
* catalog shows. Optional — defaults to `{ includeDescription: 'none' }`.
|
|
160
|
+
*/
|
|
161
|
+
lazyToolsConfig?: LazyToolsConfig;
|
|
162
|
+
/**
|
|
163
|
+
* Optional escape hatch to swap out the TypeScript-stripping step.
|
|
164
|
+
*
|
|
165
|
+
* Receives the raw model-generated code and must return runnable JavaScript
|
|
166
|
+
* with all TypeScript syntax removed. Defaults to the built-in
|
|
167
|
+
* {@link stripTypeScript}, which uses sucrase and is safe to bundle for
|
|
168
|
+
* browsers and edge runtimes (Cloudflare Workers/Pages etc.).
|
|
169
|
+
*
|
|
170
|
+
* Provide your own only to trade the edge-safe default for a faster
|
|
171
|
+
* Node-only transpiler. A custom transpiler MUST tolerate top-level `return`
|
|
172
|
+
* and `await` in its input (the default wraps the code in an async function
|
|
173
|
+
* internally to allow this).
|
|
174
|
+
*
|
|
175
|
+
* NOTE: This only affects `createCodeModeTool`. The skills helpers
|
|
176
|
+
* (`skillsToTools`, `codeModeWithSkills` in `@tanstack/ai-code-mode-skills`)
|
|
177
|
+
* call the exported `stripTypeScript` directly, so they ignore this hook — but
|
|
178
|
+
* they still get the edge-safe sucrase default, so #487 is fixed for them too;
|
|
179
|
+
* they just can't be pointed at a different transpiler.
|
|
180
|
+
*
|
|
181
|
+
* @example
|
|
182
|
+
* ```typescript
|
|
183
|
+
* // Node-only fast path using esbuild (NOT edge-safe — Node only). esbuild
|
|
184
|
+
* // rejects top-level `return`, so reuse the same async-function wrapper the
|
|
185
|
+
* // default uses, then slice the body back out. `keepNames: false` stops
|
|
186
|
+
* // esbuild injecting `__name()` helpers the sandbox can't resolve.
|
|
187
|
+
* import { transformSync } from 'esbuild'
|
|
188
|
+
* transpile: (code) => {
|
|
189
|
+
* const out = transformSync(`async function _w(){\n${code}\n}`, {
|
|
190
|
+
* loader: 'ts',
|
|
191
|
+
* keepNames: false,
|
|
192
|
+
* }).code
|
|
193
|
+
* return out.slice(out.indexOf('{') + 1, out.lastIndexOf('}'))
|
|
194
|
+
* }
|
|
195
|
+
* ```
|
|
196
|
+
*/
|
|
197
|
+
transpile?: (code: string) => string | Promise<string>;
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* Result returned by the execute_typescript tool
|
|
201
|
+
*/
|
|
202
|
+
export interface CodeModeToolResult {
|
|
203
|
+
/**
|
|
204
|
+
* Whether execution completed without errors
|
|
205
|
+
*/
|
|
206
|
+
success: boolean;
|
|
207
|
+
/**
|
|
208
|
+
* Return value from the executed code (if successful)
|
|
209
|
+
*/
|
|
210
|
+
result?: unknown;
|
|
211
|
+
/**
|
|
212
|
+
* Console output captured during execution
|
|
213
|
+
*/
|
|
214
|
+
logs?: Array<string>;
|
|
215
|
+
/**
|
|
216
|
+
* Error details if execution failed
|
|
217
|
+
*/
|
|
218
|
+
error?: {
|
|
219
|
+
message: string;
|
|
220
|
+
name?: string | undefined;
|
|
221
|
+
line?: number | undefined;
|
|
222
|
+
} | undefined;
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* Return shape of `createCodeMode`. `tool` (execute_typescript) and
|
|
226
|
+
* `systemPrompt` are preserved for backward compatibility; `discoveryTool` and
|
|
227
|
+
* `tools` are additive. Spread `tools` into `chat({ tools })`.
|
|
228
|
+
*/
|
|
229
|
+
export interface CreateCodeModeResult {
|
|
230
|
+
/** The execute_typescript tool. */
|
|
231
|
+
tool: ServerTool<SchemaInput, SchemaInput, 'execute_typescript'>;
|
|
232
|
+
/** The discover_tools tool, or null when there are no lazy tools. */
|
|
233
|
+
discoveryTool: ServerTool<SchemaInput, SchemaInput, 'discover_tools'> | null;
|
|
234
|
+
/** [tool] or [tool, discoveryTool] — the array to spread into chat({ tools }). */
|
|
235
|
+
tools: Array<ServerTool<SchemaInput, SchemaInput, string>>;
|
|
236
|
+
/** The matching system prompt. */
|
|
237
|
+
systemPrompt: string;
|
|
238
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tanstack/ai-code-mode",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.2",
|
|
4
4
|
"description": "Secure TypeScript Code Mode for TanStack AI agents to execute sandboxed tool orchestration programs.",
|
|
5
5
|
"author": "Tanner Linsley",
|
|
6
6
|
"license": "MIT",
|
|
@@ -54,12 +54,12 @@
|
|
|
54
54
|
},
|
|
55
55
|
"peerDependencies": {
|
|
56
56
|
"zod": "^3.0.0 || ^4.0.0",
|
|
57
|
-
"@tanstack/ai": "0.
|
|
57
|
+
"@tanstack/ai": "0.38.0"
|
|
58
58
|
},
|
|
59
59
|
"devDependencies": {
|
|
60
60
|
"@vitest/coverage-v8": "4.0.14",
|
|
61
61
|
"zod": "^4.2.0",
|
|
62
|
-
"@tanstack/ai": "0.
|
|
62
|
+
"@tanstack/ai": "0.38.0"
|
|
63
63
|
},
|
|
64
64
|
"scripts": {
|
|
65
65
|
"build": "vite build",
|