@utcp/code-mode
Advanced tools
+511
| "use strict"; | ||
| var __create = Object.create; | ||
| var __defProp = Object.defineProperty; | ||
| var __getOwnPropDesc = Object.getOwnPropertyDescriptor; | ||
| var __getOwnPropNames = Object.getOwnPropertyNames; | ||
| var __getProtoOf = Object.getPrototypeOf; | ||
| var __hasOwnProp = Object.prototype.hasOwnProperty; | ||
| var __export = (target, all) => { | ||
| for (var name in all) | ||
| __defProp(target, name, { get: all[name], enumerable: true }); | ||
| }; | ||
| var __copyProps = (to, from, except, desc) => { | ||
| if (from && typeof from === "object" || typeof from === "function") { | ||
| for (let key of __getOwnPropNames(from)) | ||
| if (!__hasOwnProp.call(to, key) && key !== except) | ||
| __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); | ||
| } | ||
| return to; | ||
| }; | ||
| var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( | ||
| // If the importer is in node compatibility mode or this is not an ESM | ||
| // file that has been converted to a CommonJS file using a Babel- | ||
| // compatible transform (i.e. "__esModule" has not been set), then set | ||
| // "default" to the CommonJS "module.exports" for node compatibility. | ||
| isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, | ||
| mod | ||
| )); | ||
| var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); | ||
| // src/index.ts | ||
| var index_exports = {}; | ||
| __export(index_exports, { | ||
| CodeModeUtcpClient: () => CodeModeUtcpClient | ||
| }); | ||
| module.exports = __toCommonJS(index_exports); | ||
| // src/code_mode_utcp_client.ts | ||
| var import_sdk = require("@utcp/sdk"); | ||
| var import_isolated_vm = __toESM(require("isolated-vm"), 1); | ||
| var CodeModeUtcpClient = class _CodeModeUtcpClient extends import_sdk.UtcpClient { | ||
| toolFunctionCache = /* @__PURE__ */ new Map(); | ||
| /** | ||
| * Standard prompt template for AI agents using CodeModeUtcpClient. | ||
| * This provides guidance on how to properly discover and use tools within code execution. | ||
| */ | ||
| static AGENT_PROMPT_TEMPLATE = ` | ||
| ## UTCP CodeMode Tool Usage Guide | ||
| You have access to a CodeModeUtcpClient that allows you to execute TypeScript code with access to registered tools. Follow this workflow: | ||
| ### 1. Tool Discovery Phase | ||
| **Always start by discovering available tools:** | ||
| - Tools are organized by manual namespace (e.g., \`manual_name.tool_name\`) | ||
| - Use hierarchical access patterns: \`manual.tool({ param: value })\` (synchronous, no await) | ||
| - Multiple manuals can contain tools with the same name - namespaces prevent conflicts | ||
| ### 2. Interface Introspection | ||
| **Understand tool contracts before using them:** | ||
| - Access \`__interfaces\` to see all available TypeScript interface definitions | ||
| - Use \`__getToolInterface('manual.tool')\` to get specific tool interfaces | ||
| - Interfaces show required inputs, expected outputs, and descriptions | ||
| - Look for "Access as: manual.tool(args)" comments for usage patterns | ||
| ### 3. Code Execution Guidelines | ||
| **When writing code for \`callToolChain\`:** | ||
| - Use \`manual.tool({ param: value })\` syntax for all tool calls (synchronous, no await needed) | ||
| - Tools are synchronous functions - the main process handles async operations internally | ||
| - You have access to standard JavaScript globals: \`console\`, \`JSON\`, \`Math\`, \`Date\`, etc. | ||
| - All console output (\`console.log\`, \`console.error\`, etc.) is automatically captured and returned | ||
| - Build properly structured input objects based on interface definitions | ||
| - Handle errors appropriately with try/catch blocks | ||
| - Chain tool calls by using results from previous calls | ||
| - Use \`return\` to return the final result from your code | ||
| ### 4. Best Practices | ||
| - **Discover first, code second**: Always explore available tools before writing execution code | ||
| - **Respect namespaces**: Use full \`manual.tool\` names to avoid conflicts | ||
| - **Parse interfaces**: Use interface information to construct proper input objects | ||
| - **Error handling**: Wrap tool calls in try/catch for robustness | ||
| - **Data flow**: Chain tools by passing outputs as inputs to subsequent tools | ||
| ### 5. Available Runtime Context | ||
| - \`__interfaces\`: String containing all TypeScript interface definitions | ||
| - \`__getToolInterface(toolName)\`: Function to get specific tool interface | ||
| - All registered tools as \`manual.tool\` functions | ||
| - Standard JavaScript built-ins for data processing | ||
| Remember: Always discover and understand available tools before attempting to use them in code execution. | ||
| `.trim(); | ||
| /** | ||
| * Creates a new CodeModeUtcpClient instance. | ||
| * This creates a regular UtcpClient and then upgrades it to a CodeModeUtcpClient | ||
| * with all the same configuration and additional code execution capabilities. | ||
| * | ||
| * @param root_dir The root directory for the client to resolve relative paths from | ||
| * @param config The configuration for the client | ||
| * @returns A new CodeModeUtcpClient instance | ||
| */ | ||
| /** | ||
| * Debug method to expose registered call template serializers from the SDK instance used by code-mode. | ||
| * Use this to verify if the SDK is shared with other plugins like @utcp/direct-call. | ||
| */ | ||
| static getRegisteredSerializers() { | ||
| const serializerClass = import_sdk.CallTemplateSerializer; | ||
| return Object.keys(serializerClass.serializers || {}); | ||
| } | ||
| static async create(root_dir = process.cwd(), config = null) { | ||
| console.log( | ||
| "[CodeModeUtcpClient] Registered serializers at create():", | ||
| _CodeModeUtcpClient.getRegisteredSerializers() | ||
| ); | ||
| const baseClient = await import_sdk.UtcpClient.create(root_dir, config); | ||
| const codeModeClient = Object.setPrototypeOf(baseClient, _CodeModeUtcpClient.prototype); | ||
| codeModeClient.toolFunctionCache = /* @__PURE__ */ new Map(); | ||
| return codeModeClient; | ||
| } | ||
| /** | ||
| * Sanitizes an identifier to be a valid TypeScript identifier. | ||
| * Replaces any non-alphanumeric character (except underscore) with underscore | ||
| * and ensures the first character is not a number. | ||
| * | ||
| * @param name The name to sanitize | ||
| * @returns Sanitized identifier | ||
| */ | ||
| sanitizeIdentifier(name) { | ||
| return name.replace(/[^a-zA-Z0-9_]/g, "_").replace(/^[0-9]/, "_$&"); | ||
| } | ||
| /** | ||
| * Converts a Tool object into a TypeScript function interface string. | ||
| * This generates the function signature that can be used in TypeScript code. | ||
| * | ||
| * @param tool The Tool object to convert | ||
| * @returns TypeScript function interface as a string | ||
| */ | ||
| toolToTypeScriptInterface(tool) { | ||
| if (this.toolFunctionCache.has(tool.name)) { | ||
| return this.toolFunctionCache.get(tool.name); | ||
| } | ||
| let interfaceContent; | ||
| let accessPattern; | ||
| if (tool.name.includes(".")) { | ||
| const [manualName, ...toolParts] = tool.name.split("."); | ||
| const sanitizedManualName = this.sanitizeIdentifier(manualName); | ||
| const toolName = toolParts.map((part) => this.sanitizeIdentifier(part)).join("_"); | ||
| accessPattern = `${sanitizedManualName}.${toolName}`; | ||
| const inputInterfaceContent = this.jsonSchemaToObjectContent(tool.inputs); | ||
| const outputInterfaceContent = this.jsonSchemaToObjectContent(tool.outputs); | ||
| interfaceContent = ` | ||
| namespace ${sanitizedManualName} { | ||
| interface ${toolName}Input { | ||
| ${inputInterfaceContent} | ||
| } | ||
| interface ${toolName}Output { | ||
| ${outputInterfaceContent} | ||
| } | ||
| }`; | ||
| } else { | ||
| const sanitizedToolName = this.sanitizeIdentifier(tool.name); | ||
| accessPattern = sanitizedToolName; | ||
| const inputType = this.jsonSchemaToTypeScript(tool.inputs, `${sanitizedToolName}Input`); | ||
| const outputType = this.jsonSchemaToTypeScript(tool.outputs, `${sanitizedToolName}Output`); | ||
| interfaceContent = `${inputType} | ||
| ${outputType}`; | ||
| } | ||
| const interfaceString = ` | ||
| ${interfaceContent} | ||
| /** | ||
| * ${this.escapeComment(tool.description)} | ||
| * Tags: ${this.escapeComment(tool.tags.join(", "))} | ||
| * Access as: ${accessPattern}(args) | ||
| */`; | ||
| this.toolFunctionCache.set(tool.name, interfaceString); | ||
| return interfaceString; | ||
| } | ||
| /** | ||
| * Converts all registered tools to TypeScript interface definitions. | ||
| * This provides the complete type definitions for all available tools. | ||
| * | ||
| * @returns A complete TypeScript interface definition string | ||
| */ | ||
| async getAllToolsTypeScriptInterfaces() { | ||
| const tools = await this.getTools(); | ||
| const interfaces = tools.map((tool) => this.toolToTypeScriptInterface(tool)); | ||
| return `// Auto-generated TypeScript interfaces for UTCP tools | ||
| ${interfaces.join("\n\n")}`; | ||
| } | ||
| /** | ||
| * Executes TypeScript code with access to registered tools and captures console output. | ||
| * The code can call tools directly as functions and has access to standard JavaScript globals. | ||
| * Uses isolated-vm for secure sandboxed execution. | ||
| * | ||
| * @param code TypeScript code to execute | ||
| * @param timeout Optional timeout in milliseconds (default: 30000) | ||
| * @param memoryLimit Optional memory limit in MB (default: 128) | ||
| * @returns Object containing both the execution result and captured console logs | ||
| */ | ||
| async callToolChain(code, timeout = 3e4, memoryLimit = 128) { | ||
| const tools = await this.getTools(); | ||
| const logs = []; | ||
| const isolate = new import_isolated_vm.default.Isolate({ memoryLimit }); | ||
| try { | ||
| const context = await isolate.createContext(); | ||
| const jail = context.global; | ||
| await jail.set("global", jail.derefInto()); | ||
| await this.setupConsoleBridge(isolate, context, jail, logs); | ||
| await this.setupToolBridges(isolate, context, jail, tools); | ||
| await this.setupUtilities(isolate, context, jail, tools); | ||
| const wrappedCode = ` | ||
| (function() { | ||
| var __result = (function() { | ||
| ${code} | ||
| })(); | ||
| return JSON.stringify({ __result: __result }); | ||
| })() | ||
| `; | ||
| const script = await isolate.compileScript(wrappedCode); | ||
| const resultJson = await script.run(context, { timeout }); | ||
| const result = typeof resultJson === "string" ? JSON.parse(resultJson).__result : resultJson; | ||
| return { result, logs }; | ||
| } catch (error) { | ||
| const errorMessage = error instanceof Error ? error.message : String(error); | ||
| return { | ||
| result: null, | ||
| logs: [...logs, `[ERROR] Code execution failed: ${errorMessage}`] | ||
| }; | ||
| } finally { | ||
| isolate.dispose(); | ||
| } | ||
| } | ||
| /** | ||
| * Sets up console bridge functions in the isolated context. | ||
| * Console calls in the isolate are forwarded to the main process for logging. | ||
| */ | ||
| async setupConsoleBridge(isolate, context, jail, logs) { | ||
| const createLogHandler = (prefix) => { | ||
| return new import_isolated_vm.default.Reference((...args) => { | ||
| const message = args.join(" "); | ||
| logs.push(prefix ? `${prefix} ${message}` : message); | ||
| }); | ||
| }; | ||
| await jail.set("__logRef", createLogHandler("")); | ||
| await jail.set("__errorRef", createLogHandler("[ERROR]")); | ||
| await jail.set("__warnRef", createLogHandler("[WARN]")); | ||
| await jail.set("__infoRef", createLogHandler("[INFO]")); | ||
| const consoleSetupScript = await isolate.compileScript(` | ||
| const __stringify = (a) => typeof a === 'object' && a !== null ? JSON.stringify(a, null, 2) : String(a); | ||
| global.console = { | ||
| log: (...args) => __logRef.applySync(undefined, args.map(__stringify)), | ||
| error: (...args) => __errorRef.applySync(undefined, args.map(__stringify)), | ||
| warn: (...args) => __warnRef.applySync(undefined, args.map(__stringify)), | ||
| info: (...args) => __infoRef.applySync(undefined, args.map(__stringify)) | ||
| }; | ||
| `); | ||
| await consoleSetupScript.run(context); | ||
| } | ||
| /** | ||
| * Sets up tool bridge functions in the isolated context. | ||
| * Tool calls in the isolate are forwarded to the main process for execution. | ||
| */ | ||
| async setupToolBridges(isolate, context, jail, tools) { | ||
| const toolCallerRef = new import_isolated_vm.default.Reference(async (toolName, argsJson) => { | ||
| try { | ||
| const args = JSON.parse(argsJson); | ||
| const result = await this.callTool(toolName, args); | ||
| return JSON.stringify({ success: true, result }); | ||
| } catch (error) { | ||
| return JSON.stringify({ | ||
| success: false, | ||
| error: error instanceof Error ? error.message : String(error) | ||
| }); | ||
| } | ||
| }); | ||
| await jail.set("__callToolRef", toolCallerRef); | ||
| const toolSetupParts = []; | ||
| const namespaces = /* @__PURE__ */ new Set(); | ||
| for (const tool of tools) { | ||
| if (tool.name.includes(".")) { | ||
| const [manualName, ...toolParts] = tool.name.split("."); | ||
| const sanitizedManualName = this.sanitizeIdentifier(manualName); | ||
| const toolFnName = toolParts.map((part) => this.sanitizeIdentifier(part)).join("_"); | ||
| if (!namespaces.has(sanitizedManualName)) { | ||
| namespaces.add(sanitizedManualName); | ||
| toolSetupParts.push(`global.${sanitizedManualName} = global.${sanitizedManualName} || {};`); | ||
| } | ||
| toolSetupParts.push(` | ||
| global.${sanitizedManualName}.${toolFnName} = function(args) { | ||
| // applySyncPromise blocks until async tool call completes in main process | ||
| var resultJson = __callToolRef.applySyncPromise(undefined, [${JSON.stringify(tool.name)}, JSON.stringify(args || {})]); | ||
| var parsed = JSON.parse(resultJson); | ||
| if (!parsed.success) throw new Error(parsed.error); | ||
| return parsed.result; | ||
| }; | ||
| `); | ||
| } else { | ||
| const sanitizedToolName = this.sanitizeIdentifier(tool.name); | ||
| toolSetupParts.push(` | ||
| global.${sanitizedToolName} = function(args) { | ||
| // applySyncPromise blocks until async tool call completes in main process | ||
| var resultJson = __callToolRef.applySyncPromise(undefined, [${JSON.stringify(tool.name)}, JSON.stringify(args || {})]); | ||
| var parsed = JSON.parse(resultJson); | ||
| if (!parsed.success) throw new Error(parsed.error); | ||
| return parsed.result; | ||
| }; | ||
| `); | ||
| } | ||
| } | ||
| const toolSetupScript = await isolate.compileScript(toolSetupParts.join("\n")); | ||
| await toolSetupScript.run(context); | ||
| } | ||
| /** | ||
| * Sets up utility functions and interfaces in the isolated context. | ||
| */ | ||
| async setupUtilities(isolate, context, jail, tools) { | ||
| const interfaces = await this.getAllToolsTypeScriptInterfaces(); | ||
| await jail.set("__interfaces", interfaces); | ||
| const interfaceMap = {}; | ||
| for (const tool of tools) { | ||
| interfaceMap[tool.name] = this.toolToTypeScriptInterface(tool); | ||
| } | ||
| await jail.set("__interfaceMapJson", JSON.stringify(interfaceMap)); | ||
| const utilSetupScript = await isolate.compileScript(` | ||
| global.__getToolInterface = (toolName) => { | ||
| const map = JSON.parse(__interfaceMapJson); | ||
| return map[toolName] || null; | ||
| }; | ||
| `); | ||
| await utilSetupScript.run(context); | ||
| } | ||
| /** | ||
| * Converts a JSON Schema to TypeScript object content (properties only, no interface wrapper). | ||
| * This generates the content inside an interface definition. | ||
| * | ||
| * @param schema JSON Schema to convert | ||
| * @returns TypeScript interface properties as string | ||
| */ | ||
| jsonSchemaToObjectContent(schema) { | ||
| if (!schema || typeof schema !== "object" || schema.type !== "object") { | ||
| return " [key: string]: any;"; | ||
| } | ||
| const properties = schema.properties || {}; | ||
| const required = schema.required || []; | ||
| const lines = []; | ||
| for (const [propName, propSchema] of Object.entries(properties)) { | ||
| const isRequired = required.includes(propName); | ||
| const optionalMarker = isRequired ? "" : "?"; | ||
| const description = propSchema.description || ""; | ||
| const tsType = this.jsonSchemaToTypeScriptType(propSchema); | ||
| if (description) { | ||
| lines.push(` /** ${this.escapeComment(description)} */`); | ||
| } | ||
| lines.push(` ${propName}${optionalMarker}: ${tsType};`); | ||
| } | ||
| return lines.length > 0 ? lines.join("\n") : " [key: string]: any;"; | ||
| } | ||
| /** | ||
| * Converts a JSON Schema to TypeScript interface definition. | ||
| * This handles the most common JSON Schema patterns used in UTCP tools. | ||
| * | ||
| * @param schema JSON Schema to convert | ||
| * @param typeName Name for the generated TypeScript type | ||
| * @returns TypeScript type definition as string | ||
| */ | ||
| jsonSchemaToTypeScript(schema, typeName) { | ||
| if (!schema || typeof schema !== "object") { | ||
| return `type ${typeName} = any;`; | ||
| } | ||
| switch (schema.type) { | ||
| case "object": | ||
| return this.objectSchemaToTypeScript(schema, typeName); | ||
| case "array": | ||
| return this.arraySchemaToTypeScript(schema, typeName); | ||
| case "string": | ||
| return this.primitiveSchemaToTypeScript(schema, typeName, "string"); | ||
| case "number": | ||
| case "integer": | ||
| return this.primitiveSchemaToTypeScript(schema, typeName, "number"); | ||
| case "boolean": | ||
| return this.primitiveSchemaToTypeScript(schema, typeName, "boolean"); | ||
| case "null": | ||
| return `type ${typeName} = null;`; | ||
| default: | ||
| if (Array.isArray(schema.type)) { | ||
| const types = schema.type.map((t) => this.mapJsonTypeToTS(t)).join(" | "); | ||
| return `type ${typeName} = ${types};`; | ||
| } | ||
| return `type ${typeName} = any;`; | ||
| } | ||
| } | ||
| /** | ||
| * Converts an object JSON Schema to TypeScript interface. | ||
| */ | ||
| objectSchemaToTypeScript(schema, typeName) { | ||
| if (!schema.properties) { | ||
| return `interface ${typeName} { | ||
| [key: string]: any; | ||
| }`; | ||
| } | ||
| const properties = Object.entries(schema.properties).map(([key, propSchema]) => { | ||
| const isRequired = schema.required?.includes(key) ?? false; | ||
| const optional = isRequired ? "" : "?"; | ||
| const propType = this.jsonSchemaToTypeScriptType(propSchema); | ||
| const description = propSchema.description ? ` /** ${this.escapeComment(propSchema.description)} */ | ||
| ` : ""; | ||
| return `${description} ${key}${optional}: ${propType};`; | ||
| }).join("\n"); | ||
| return `interface ${typeName} { | ||
| ${properties} | ||
| }`; | ||
| } | ||
| /** | ||
| * Converts an array JSON Schema to TypeScript type. | ||
| */ | ||
| arraySchemaToTypeScript(schema, typeName) { | ||
| if (!schema.items) { | ||
| return `type ${typeName} = any[];`; | ||
| } | ||
| const itemType = Array.isArray(schema.items) ? schema.items.map((item) => this.jsonSchemaToTypeScriptType(item)).join(" | ") : this.jsonSchemaToTypeScriptType(schema.items); | ||
| return `type ${typeName} = (${itemType})[];`; | ||
| } | ||
| /** | ||
| * Converts a primitive JSON Schema to TypeScript type with enum support. | ||
| */ | ||
| primitiveSchemaToTypeScript(schema, typeName, baseType) { | ||
| if (schema.enum) { | ||
| const enumValues = schema.enum.map( | ||
| (val) => typeof val === "string" ? JSON.stringify(val) : String(val) | ||
| ).join(" | "); | ||
| return `type ${typeName} = ${enumValues};`; | ||
| } | ||
| return `type ${typeName} = ${baseType};`; | ||
| } | ||
| /** | ||
| * Converts a JSON Schema to a TypeScript type (not a full type definition). | ||
| */ | ||
| jsonSchemaToTypeScriptType(schema) { | ||
| if (!schema || typeof schema !== "object") { | ||
| return "any"; | ||
| } | ||
| if (schema.enum) { | ||
| return schema.enum.map( | ||
| (val) => typeof val === "string" ? JSON.stringify(val) : String(val) | ||
| ).join(" | "); | ||
| } | ||
| switch (schema.type) { | ||
| case "object": | ||
| if (!schema.properties) return "{ [key: string]: any }"; | ||
| const props = Object.entries(schema.properties).map(([key, propSchema]) => { | ||
| const isRequired = schema.required?.includes(key) ?? false; | ||
| const optional = isRequired ? "" : "?"; | ||
| const propType = this.jsonSchemaToTypeScriptType(propSchema); | ||
| return `${key}${optional}: ${propType}`; | ||
| }).join("; "); | ||
| return `{ ${props} }`; | ||
| case "array": | ||
| if (!schema.items) return "any[]"; | ||
| const itemType = Array.isArray(schema.items) ? schema.items.map((item) => this.jsonSchemaToTypeScriptType(item)).join(" | ") : this.jsonSchemaToTypeScriptType(schema.items); | ||
| return `(${itemType})[]`; | ||
| case "string": | ||
| return "string"; | ||
| case "number": | ||
| case "integer": | ||
| return "number"; | ||
| case "boolean": | ||
| return "boolean"; | ||
| case "null": | ||
| return "null"; | ||
| default: | ||
| if (Array.isArray(schema.type)) { | ||
| return schema.type.map((t) => this.mapJsonTypeToTS(t)).join(" | "); | ||
| } | ||
| return "any"; | ||
| } | ||
| } | ||
| /** | ||
| * Escapes a string for safe use in JSDoc comments. | ||
| * Prevents comment injection via star-slash sequences. | ||
| */ | ||
| escapeComment(text) { | ||
| return text.replace(/\*\//g, "*\\/").replace(/\n/g, " "); | ||
| } | ||
| /** | ||
| * Maps basic JSON Schema types to TypeScript types. | ||
| */ | ||
| mapJsonTypeToTS(type) { | ||
| switch (type) { | ||
| case "string": | ||
| return "string"; | ||
| case "number": | ||
| case "integer": | ||
| return "number"; | ||
| case "boolean": | ||
| return "boolean"; | ||
| case "null": | ||
| return "null"; | ||
| case "object": | ||
| return "object"; | ||
| case "array": | ||
| return "any[]"; | ||
| default: | ||
| return "any"; | ||
| } | ||
| } | ||
| }; | ||
| // Annotate the CommonJS export names for ESM import in node: | ||
| 0 && (module.exports = { | ||
| CodeModeUtcpClient | ||
| }); | ||
| //# sourceMappingURL=index.cjs.map |
| {"version":3,"sources":["../src/index.ts","../src/code_mode_utcp_client.ts"],"sourcesContent":["export { CodeModeUtcpClient } from './code_mode_utcp_client';\r\n","import { UtcpClient, Tool, JsonSchema, UtcpClientConfig, CallTemplateSerializer } from '@utcp/sdk';\r\nimport ivm from 'isolated-vm';\r\n\r\n/**\r\n * CodeModeUtcpClient extends UtcpClient to provide TypeScript code execution capabilities.\r\n * This allows executing TypeScript code that can directly call registered tools as functions.\r\n */\r\nexport class CodeModeUtcpClient extends UtcpClient {\r\n private toolFunctionCache: Map<string, string> = new Map();\r\n\r\n /**\r\n * Standard prompt template for AI agents using CodeModeUtcpClient.\r\n * This provides guidance on how to properly discover and use tools within code execution.\r\n */\r\n public static readonly AGENT_PROMPT_TEMPLATE = `\r\n## UTCP CodeMode Tool Usage Guide\r\n\r\nYou have access to a CodeModeUtcpClient that allows you to execute TypeScript code with access to registered tools. Follow this workflow:\r\n\r\n### 1. Tool Discovery Phase\r\n**Always start by discovering available tools:**\r\n- Tools are organized by manual namespace (e.g., \\`manual_name.tool_name\\`)\r\n- Use hierarchical access patterns: \\`manual.tool({ param: value })\\` (synchronous, no await)\r\n- Multiple manuals can contain tools with the same name - namespaces prevent conflicts\r\n\r\n### 2. Interface Introspection\r\n**Understand tool contracts before using them:**\r\n- Access \\`__interfaces\\` to see all available TypeScript interface definitions\r\n- Use \\`__getToolInterface('manual.tool')\\` to get specific tool interfaces\r\n- Interfaces show required inputs, expected outputs, and descriptions\r\n- Look for \"Access as: manual.tool(args)\" comments for usage patterns\r\n\r\n### 3. Code Execution Guidelines\r\n**When writing code for \\`callToolChain\\`:**\r\n- Use \\`manual.tool({ param: value })\\` syntax for all tool calls (synchronous, no await needed)\r\n- Tools are synchronous functions - the main process handles async operations internally\r\n- You have access to standard JavaScript globals: \\`console\\`, \\`JSON\\`, \\`Math\\`, \\`Date\\`, etc.\r\n- All console output (\\`console.log\\`, \\`console.error\\`, etc.) is automatically captured and returned\r\n- Build properly structured input objects based on interface definitions\r\n- Handle errors appropriately with try/catch blocks\r\n- Chain tool calls by using results from previous calls\r\n- Use \\`return\\` to return the final result from your code\r\n\r\n### 4. Best Practices\r\n- **Discover first, code second**: Always explore available tools before writing execution code\r\n- **Respect namespaces**: Use full \\`manual.tool\\` names to avoid conflicts\r\n- **Parse interfaces**: Use interface information to construct proper input objects\r\n- **Error handling**: Wrap tool calls in try/catch for robustness\r\n- **Data flow**: Chain tools by passing outputs as inputs to subsequent tools\r\n\r\n### 5. Available Runtime Context\r\n- \\`__interfaces\\`: String containing all TypeScript interface definitions\r\n- \\`__getToolInterface(toolName)\\`: Function to get specific tool interface\r\n- All registered tools as \\`manual.tool\\` functions\r\n- Standard JavaScript built-ins for data processing\r\n\r\nRemember: Always discover and understand available tools before attempting to use them in code execution.\r\n`.trim();\r\n\r\n /**\r\n * Creates a new CodeModeUtcpClient instance.\r\n * This creates a regular UtcpClient and then upgrades it to a CodeModeUtcpClient\r\n * with all the same configuration and additional code execution capabilities.\r\n * \r\n * @param root_dir The root directory for the client to resolve relative paths from\r\n * @param config The configuration for the client\r\n * @returns A new CodeModeUtcpClient instance\r\n */\r\n /**\r\n * Debug method to expose registered call template serializers from the SDK instance used by code-mode.\r\n * Use this to verify if the SDK is shared with other plugins like @utcp/direct-call.\r\n */\r\n public static getRegisteredSerializers(): string[] {\r\n // Access the static serializers map\r\n const serializerClass = CallTemplateSerializer as any;\r\n return Object.keys(serializerClass.serializers || {});\r\n }\r\n\r\n public static async create(\r\n root_dir: string = process.cwd(),\r\n config: UtcpClientConfig | null = null\r\n ): Promise<CodeModeUtcpClient> {\r\n // Debug: log registered serializers at creation time\r\n console.log('[CodeModeUtcpClient] Registered serializers at create():', \r\n CodeModeUtcpClient.getRegisteredSerializers());\r\n \r\n // Create a regular UtcpClient first\r\n const baseClient = await UtcpClient.create(root_dir, config);\r\n \r\n // Create a CodeModeUtcpClient using the same configuration\r\n const codeModeClient = Object.setPrototypeOf(baseClient, CodeModeUtcpClient.prototype) as CodeModeUtcpClient;\r\n \r\n // Initialize the cache\r\n (codeModeClient as any).toolFunctionCache = new Map();\r\n \r\n return codeModeClient;\r\n }\r\n\r\n /**\r\n * Sanitizes an identifier to be a valid TypeScript identifier.\r\n * Replaces any non-alphanumeric character (except underscore) with underscore\r\n * and ensures the first character is not a number.\r\n * \r\n * @param name The name to sanitize\r\n * @returns Sanitized identifier\r\n */\r\n private sanitizeIdentifier(name: string): string {\r\n return name\r\n .replace(/[^a-zA-Z0-9_]/g, '_')\r\n .replace(/^[0-9]/, '_$&');\r\n }\r\n\r\n /**\r\n * Converts a Tool object into a TypeScript function interface string.\r\n * This generates the function signature that can be used in TypeScript code.\r\n * \r\n * @param tool The Tool object to convert\r\n * @returns TypeScript function interface as a string\r\n */\r\n public toolToTypeScriptInterface(tool: Tool): string {\r\n if (this.toolFunctionCache.has(tool.name)) {\r\n return this.toolFunctionCache.get(tool.name)!;\r\n }\r\n\r\n // Generate hierarchical interface structure\r\n let interfaceContent: string;\r\n let accessPattern: string;\r\n \r\n if (tool.name.includes('.')) {\r\n const [manualName, ...toolParts] = tool.name.split('.');\r\n const sanitizedManualName = this.sanitizeIdentifier(manualName);\r\n const toolName = toolParts.map(part => this.sanitizeIdentifier(part)).join('_');\r\n accessPattern = `${sanitizedManualName}.${toolName}`;\r\n \r\n // Generate interfaces within namespace\r\n const inputInterfaceContent = this.jsonSchemaToObjectContent(tool.inputs);\r\n const outputInterfaceContent = this.jsonSchemaToObjectContent(tool.outputs);\r\n \r\n interfaceContent = `\r\nnamespace ${sanitizedManualName} {\r\n interface ${toolName}Input {\r\n${inputInterfaceContent}\r\n }\r\n\r\n interface ${toolName}Output {\r\n${outputInterfaceContent}\r\n }\r\n}`;\r\n } else {\r\n // No manual namespace, generate flat interfaces\r\n const sanitizedToolName = this.sanitizeIdentifier(tool.name);\r\n accessPattern = sanitizedToolName;\r\n const inputType = this.jsonSchemaToTypeScript(tool.inputs, `${sanitizedToolName}Input`);\r\n const outputType = this.jsonSchemaToTypeScript(tool.outputs, `${sanitizedToolName}Output`);\r\n interfaceContent = `${inputType}\\n\\n${outputType}`;\r\n }\r\n const interfaceString = `\r\n${interfaceContent}\r\n\r\n/**\r\n * ${this.escapeComment(tool.description)}\r\n * Tags: ${this.escapeComment(tool.tags.join(', '))}\r\n * Access as: ${accessPattern}(args)\r\n */`;\r\n\r\n this.toolFunctionCache.set(tool.name, interfaceString);\r\n return interfaceString;\r\n }\r\n\r\n /**\r\n * Converts all registered tools to TypeScript interface definitions.\r\n * This provides the complete type definitions for all available tools.\r\n * \r\n * @returns A complete TypeScript interface definition string\r\n */\r\n public async getAllToolsTypeScriptInterfaces(): Promise<string> {\r\n const tools = await this.getTools();\r\n const interfaces = tools.map(tool => this.toolToTypeScriptInterface(tool));\r\n \r\n return `// Auto-generated TypeScript interfaces for UTCP tools\r\n${interfaces.join('\\n\\n')}`;\r\n }\r\n\r\n /**\r\n * Executes TypeScript code with access to registered tools and captures console output.\r\n * The code can call tools directly as functions and has access to standard JavaScript globals.\r\n * Uses isolated-vm for secure sandboxed execution.\r\n * \r\n * @param code TypeScript code to execute \r\n * @param timeout Optional timeout in milliseconds (default: 30000)\r\n * @param memoryLimit Optional memory limit in MB (default: 128)\r\n * @returns Object containing both the execution result and captured console logs\r\n */\r\n public async callToolChain(\r\n code: string, \r\n timeout: number = 30000,\r\n memoryLimit: number = 128\r\n ): Promise<{result: any, logs: string[]}> {\r\n const tools = await this.getTools();\r\n const logs: string[] = [];\r\n \r\n // Create isolated VM\r\n const isolate = new ivm.Isolate({ memoryLimit });\r\n \r\n try {\r\n const context = await isolate.createContext();\r\n const jail = context.global;\r\n \r\n // Set up the jail with a reference to itself\r\n await jail.set('global', jail.derefInto());\r\n \r\n // Set up console logging bridges\r\n await this.setupConsoleBridge(isolate, context, jail, logs);\r\n \r\n // Set up tool bridges\r\n await this.setupToolBridges(isolate, context, jail, tools);\r\n \r\n // Set up utility functions and interfaces\r\n await this.setupUtilities(isolate, context, jail, tools);\r\n \r\n // Compile and run the user code - code is SYNC since tools use applySyncPromise\r\n // Wrap result in JSON.stringify to transfer objects out of isolate\r\n const wrappedCode = `\r\n (function() {\r\n var __result = (function() {\r\n ${code}\r\n })();\r\n return JSON.stringify({ __result: __result });\r\n })()\r\n `;\r\n \r\n const script = await isolate.compileScript(wrappedCode);\r\n const resultJson = await script.run(context, { timeout });\r\n \r\n // Parse the result from JSON\r\n const result = typeof resultJson === 'string' \r\n ? JSON.parse(resultJson).__result\r\n : resultJson;\r\n \r\n return { result, logs };\r\n } catch (error) {\r\n const errorMessage = error instanceof Error ? error.message : String(error);\r\n return { \r\n result: null, \r\n logs: [...logs, `[ERROR] Code execution failed: ${errorMessage}`] \r\n };\r\n } finally {\r\n isolate.dispose();\r\n }\r\n }\r\n\r\n /**\r\n * Sets up console bridge functions in the isolated context.\r\n * Console calls in the isolate are forwarded to the main process for logging.\r\n */\r\n private async setupConsoleBridge(\r\n isolate: ivm.Isolate,\r\n context: ivm.Context,\r\n jail: ivm.Reference<Record<string | number | symbol, unknown>>,\r\n logs: string[]\r\n ): Promise<void> {\r\n // Create log capture functions in main process\r\n const createLogHandler = (prefix: string) => {\r\n return new ivm.Reference((...args: any[]) => {\r\n const message = args.join(' ');\r\n logs.push(prefix ? `${prefix} ${message}` : message);\r\n });\r\n };\r\n\r\n // Set up console references in isolate\r\n await jail.set('__logRef', createLogHandler(''));\r\n await jail.set('__errorRef', createLogHandler('[ERROR]'));\r\n await jail.set('__warnRef', createLogHandler('[WARN]'));\r\n await jail.set('__infoRef', createLogHandler('[INFO]'));\r\n \r\n // Create console object in isolate that calls the references\r\n const consoleSetupScript = await isolate.compileScript(`\r\n const __stringify = (a) => typeof a === 'object' && a !== null ? JSON.stringify(a, null, 2) : String(a);\r\n global.console = {\r\n log: (...args) => __logRef.applySync(undefined, args.map(__stringify)),\r\n error: (...args) => __errorRef.applySync(undefined, args.map(__stringify)),\r\n warn: (...args) => __warnRef.applySync(undefined, args.map(__stringify)),\r\n info: (...args) => __infoRef.applySync(undefined, args.map(__stringify))\r\n };\r\n `);\r\n await consoleSetupScript.run(context);\r\n }\r\n\r\n /**\r\n * Sets up tool bridge functions in the isolated context.\r\n * Tool calls in the isolate are forwarded to the main process for execution.\r\n */\r\n private async setupToolBridges(\r\n isolate: ivm.Isolate,\r\n context: ivm.Context,\r\n jail: ivm.Reference<Record<string | number | symbol, unknown>>,\r\n tools: Tool[]\r\n ): Promise<void> {\r\n // Create a reference for the tool caller in main process\r\n const toolCallerRef = new ivm.Reference(async (toolName: string, argsJson: string) => {\r\n try {\r\n const args = JSON.parse(argsJson);\r\n const result = await this.callTool(toolName, args);\r\n return JSON.stringify({ success: true, result });\r\n } catch (error) {\r\n return JSON.stringify({ \r\n success: false, \r\n error: error instanceof Error ? error.message : String(error) \r\n });\r\n }\r\n });\r\n \r\n await jail.set('__callToolRef', toolCallerRef);\r\n \r\n // Build tool namespace setup code\r\n const toolSetupParts: string[] = [];\r\n const namespaces = new Set<string>();\r\n \r\n for (const tool of tools) {\r\n if (tool.name.includes('.')) {\r\n const [manualName, ...toolParts] = tool.name.split('.');\r\n const sanitizedManualName = this.sanitizeIdentifier(manualName);\r\n const toolFnName = toolParts.map(part => this.sanitizeIdentifier(part)).join('_');\r\n \r\n if (!namespaces.has(sanitizedManualName)) {\r\n namespaces.add(sanitizedManualName);\r\n toolSetupParts.push(`global.${sanitizedManualName} = global.${sanitizedManualName} || {};`);\r\n }\r\n \r\n toolSetupParts.push(`\r\n global.${sanitizedManualName}.${toolFnName} = function(args) {\r\n // applySyncPromise blocks until async tool call completes in main process\r\n var resultJson = __callToolRef.applySyncPromise(undefined, [${JSON.stringify(tool.name)}, JSON.stringify(args || {})]);\r\n var parsed = JSON.parse(resultJson);\r\n if (!parsed.success) throw new Error(parsed.error);\r\n return parsed.result;\r\n };\r\n `);\r\n } else {\r\n const sanitizedToolName = this.sanitizeIdentifier(tool.name);\r\n toolSetupParts.push(`\r\n global.${sanitizedToolName} = function(args) {\r\n // applySyncPromise blocks until async tool call completes in main process\r\n var resultJson = __callToolRef.applySyncPromise(undefined, [${JSON.stringify(tool.name)}, JSON.stringify(args || {})]);\r\n var parsed = JSON.parse(resultJson);\r\n if (!parsed.success) throw new Error(parsed.error);\r\n return parsed.result;\r\n };\r\n `);\r\n }\r\n }\r\n \r\n // Execute tool setup in isolate\r\n const toolSetupScript = await isolate.compileScript(toolSetupParts.join('\\n'));\r\n await toolSetupScript.run(context);\r\n }\r\n\r\n /**\r\n * Sets up utility functions and interfaces in the isolated context.\r\n */\r\n private async setupUtilities(\r\n isolate: ivm.Isolate,\r\n context: ivm.Context,\r\n jail: ivm.Reference<Record<string | number | symbol, unknown>>,\r\n tools: Tool[]\r\n ): Promise<void> {\r\n // Add TypeScript interface definitions\r\n const interfaces = await this.getAllToolsTypeScriptInterfaces();\r\n await jail.set('__interfaces', interfaces);\r\n \r\n // Create interface lookup map\r\n const interfaceMap: Record<string, string> = {};\r\n for (const tool of tools) {\r\n interfaceMap[tool.name] = this.toolToTypeScriptInterface(tool);\r\n }\r\n await jail.set('__interfaceMapJson', JSON.stringify(interfaceMap));\r\n \r\n // Execute utility setup in isolate\r\n const utilSetupScript = await isolate.compileScript(`\r\n global.__getToolInterface = (toolName) => {\r\n const map = JSON.parse(__interfaceMapJson);\r\n return map[toolName] || null;\r\n };\r\n `);\r\n await utilSetupScript.run(context);\r\n }\r\n\r\n /**\r\n * Converts a JSON Schema to TypeScript object content (properties only, no interface wrapper).\r\n * This generates the content inside an interface definition.\r\n * \r\n * @param schema JSON Schema to convert\r\n * @returns TypeScript interface properties as string\r\n */\r\n private jsonSchemaToObjectContent(schema: JsonSchema): string {\r\n if (!schema || typeof schema !== 'object' || schema.type !== 'object') {\r\n return ' [key: string]: any;';\r\n }\r\n\r\n const properties = schema.properties || {};\r\n const required = schema.required || [];\r\n const lines: string[] = [];\r\n\r\n for (const [propName, propSchema] of Object.entries(properties)) {\r\n const isRequired = required.includes(propName);\r\n const optionalMarker = isRequired ? '' : '?';\r\n const description = (propSchema as any).description || '';\r\n const tsType = this.jsonSchemaToTypeScriptType(propSchema as JsonSchema);\r\n\r\n if (description) {\r\n lines.push(` /** ${this.escapeComment(description)} */`);\r\n }\r\n lines.push(` ${propName}${optionalMarker}: ${tsType};`);\r\n }\r\n\r\n return lines.length > 0 ? lines.join('\\n') : ' [key: string]: any;';\r\n }\r\n\r\n /**\r\n * Converts a JSON Schema to TypeScript interface definition.\r\n * This handles the most common JSON Schema patterns used in UTCP tools.\r\n * \r\n * @param schema JSON Schema to convert\r\n * @param typeName Name for the generated TypeScript type\r\n * @returns TypeScript type definition as string\r\n */\r\n private jsonSchemaToTypeScript(schema: JsonSchema, typeName: string): string {\r\n if (!schema || typeof schema !== 'object') {\r\n return `type ${typeName} = any;`;\r\n }\r\n\r\n // Handle different schema types\r\n switch (schema.type) {\r\n case 'object':\r\n return this.objectSchemaToTypeScript(schema, typeName);\r\n case 'array':\r\n return this.arraySchemaToTypeScript(schema, typeName);\r\n case 'string':\r\n return this.primitiveSchemaToTypeScript(schema, typeName, 'string');\r\n case 'number':\r\n case 'integer':\r\n return this.primitiveSchemaToTypeScript(schema, typeName, 'number');\r\n case 'boolean':\r\n return this.primitiveSchemaToTypeScript(schema, typeName, 'boolean');\r\n case 'null':\r\n return `type ${typeName} = null;`;\r\n default:\r\n // Handle union types or fallback to any\r\n if (Array.isArray(schema.type)) {\r\n const types = schema.type.map(t => this.mapJsonTypeToTS(t)).join(' | ');\r\n return `type ${typeName} = ${types};`;\r\n }\r\n return `type ${typeName} = any;`;\r\n }\r\n }\r\n\r\n /**\r\n * Converts an object JSON Schema to TypeScript interface.\r\n */\r\n private objectSchemaToTypeScript(schema: JsonSchema, typeName: string): string {\r\n if (!schema.properties) {\r\n return `interface ${typeName} {\r\n [key: string]: any;\r\n}`;\r\n }\r\n\r\n const properties = Object.entries(schema.properties).map(([key, propSchema]) => {\r\n const isRequired = schema.required?.includes(key) ?? false;\r\n const optional = isRequired ? '' : '?';\r\n const propType = this.jsonSchemaToTypeScriptType(propSchema);\r\n const description = propSchema.description ? ` /** ${this.escapeComment(propSchema.description)} */\\n` : '';\r\n \r\n return `${description} ${key}${optional}: ${propType};`;\r\n }).join('\\n');\r\n\r\n return `interface ${typeName} {\r\n${properties}\r\n}`;\r\n }\r\n\r\n /**\r\n * Converts an array JSON Schema to TypeScript type.\r\n */\r\n private arraySchemaToTypeScript(schema: JsonSchema, typeName: string): string {\r\n if (!schema.items) {\r\n return `type ${typeName} = any[];`;\r\n }\r\n\r\n const itemType = Array.isArray(schema.items) \r\n ? schema.items.map(item => this.jsonSchemaToTypeScriptType(item)).join(' | ')\r\n : this.jsonSchemaToTypeScriptType(schema.items);\r\n\r\n return `type ${typeName} = (${itemType})[];`;\r\n }\r\n\r\n /**\r\n * Converts a primitive JSON Schema to TypeScript type with enum support.\r\n */\r\n private primitiveSchemaToTypeScript(schema: JsonSchema, typeName: string, baseType: string): string {\r\n if (schema.enum) {\r\n const enumValues = schema.enum.map(val => \r\n typeof val === 'string' ? JSON.stringify(val) : String(val)\r\n ).join(' | ');\r\n return `type ${typeName} = ${enumValues};`;\r\n }\r\n\r\n return `type ${typeName} = ${baseType};`;\r\n }\r\n\r\n /**\r\n * Converts a JSON Schema to a TypeScript type (not a full type definition).\r\n */\r\n private jsonSchemaToTypeScriptType(schema: JsonSchema): string {\r\n if (!schema || typeof schema !== 'object') {\r\n return 'any';\r\n }\r\n\r\n if (schema.enum) {\r\n return schema.enum.map(val => \r\n typeof val === 'string' ? JSON.stringify(val) : String(val)\r\n ).join(' | ');\r\n }\r\n\r\n switch (schema.type) {\r\n case 'object':\r\n if (!schema.properties) return '{ [key: string]: any }';\r\n const props = Object.entries(schema.properties).map(([key, propSchema]) => {\r\n const isRequired = schema.required?.includes(key) ?? false;\r\n const optional = isRequired ? '' : '?';\r\n const propType = this.jsonSchemaToTypeScriptType(propSchema);\r\n return `${key}${optional}: ${propType}`;\r\n }).join('; ');\r\n return `{ ${props} }`;\r\n \r\n case 'array':\r\n if (!schema.items) return 'any[]';\r\n const itemType = Array.isArray(schema.items)\r\n ? schema.items.map(item => this.jsonSchemaToTypeScriptType(item)).join(' | ')\r\n : this.jsonSchemaToTypeScriptType(schema.items);\r\n return `(${itemType})[]`;\r\n \r\n case 'string':\r\n return 'string';\r\n case 'number':\r\n case 'integer':\r\n return 'number';\r\n case 'boolean':\r\n return 'boolean';\r\n case 'null':\r\n return 'null';\r\n \r\n default:\r\n if (Array.isArray(schema.type)) {\r\n return schema.type.map(t => this.mapJsonTypeToTS(t)).join(' | ');\r\n }\r\n return 'any';\r\n }\r\n }\r\n\r\n /**\r\n * Escapes a string for safe use in JSDoc comments.\r\n * Prevents comment injection via star-slash sequences.\r\n */\r\n private escapeComment(text: string): string {\r\n return text.replace(/\\*\\//g, '*\\\\/').replace(/\\n/g, ' ');\r\n }\r\n\r\n /**\r\n * Maps basic JSON Schema types to TypeScript types.\r\n */\r\n private mapJsonTypeToTS(type: string): string {\r\n switch (type) {\r\n case 'string': return 'string';\r\n case 'number':\r\n case 'integer': return 'number';\r\n case 'boolean': return 'boolean';\r\n case 'null': return 'null';\r\n case 'object': return 'object';\r\n case 'array': return 'any[]';\r\n default: return 'any';\r\n }\r\n }\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,iBAAuF;AACvF,yBAAgB;AAMT,IAAM,qBAAN,MAAM,4BAA2B,sBAAW;AAAA,EACzC,oBAAyC,oBAAI,IAAI;AAAA;AAAA;AAAA;AAAA;AAAA,EAMzD,OAAuB,wBAAwB;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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA2C/C,KAAK;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAeL,OAAc,2BAAqC;AAEjD,UAAM,kBAAkB;AACxB,WAAO,OAAO,KAAK,gBAAgB,eAAe,CAAC,CAAC;AAAA,EACtD;AAAA,EAEA,aAAoB,OAClB,WAAmB,QAAQ,IAAI,GAC/B,SAAkC,MACL;AAE7B,YAAQ;AAAA,MAAI;AAAA,MACV,oBAAmB,yBAAyB;AAAA,IAAC;AAG/C,UAAM,aAAa,MAAM,sBAAW,OAAO,UAAU,MAA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IAAI;AACZ,eAAO,KAAK,KAAK;AAAA,MAEnB,KAAK;AACH,YAAI,CAAC,OAAO,MAAO,QAAO;AAC1B,cAAM,WAAW,MAAM,QAAQ,OAAO,KAAK,IACvC,OAAO,MAAM,IAAI,UAAQ,KAAK,2BAA2B,IAAI,CAAC,EAAE,KAAK,KAAK,IAC1E,KAAK,2BAA2B,OAAO,KAAK;AAChD,eAAO,IAAI,QAAQ;AAAA,MAErB,KAAK;AACH,eAAO;AAAA,MACT,KAAK;AAAA,MACL,KAAK;AACH,eAAO;AAAA,MACT,KAAK;AACH,eAAO;AAAA,MACT,KAAK;AACH,eAAO;AAAA,MAET;AACE,YAAI,MAAM,QAAQ,OAAO,IAAI,GAAG;AAC9B,iBAAO,OAAO,KAAK,IAAI,OAAK,KAAK,gBAAgB,CAAC,CAAC,EAAE,KAAK,KAAK;AAAA,QACjE;AACA,eAAO;AAAA,IACX;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMQ,cAAc,MAAsB;AAC1C,WAAO,KAAK,QAAQ,SAAS,MAAM,EAAE,QAAQ,OAAO,GAAG;AAAA,EACzD;AAAA;AAAA;AAAA;AAAA,EAKQ,gBAAgB,MAAsB;AAC5C,YAAQ,MAAM;AAAA,MACZ,KAAK;AAAU,eAAO;AAAA,MACtB,KAAK;AAAA,MACL,KAAK;AAAW,eAAO;AAAA,MACvB,KAAK;AAAW,eAAO;AAAA,MACvB,KAAK;AAAQ,eAAO;AAAA,MACpB,KAAK;AAAU,eAAO;AAAA,MACtB,KAAK;AAAS,eAAO;AAAA,MACrB;AAAS,eAAO;AAAA,IAClB;AAAA,EACF;AACF;","names":["ivm"]} |
+125
| import { UtcpClient, UtcpClientConfig, Tool } from '@utcp/sdk'; | ||
| /** | ||
| * CodeModeUtcpClient extends UtcpClient to provide TypeScript code execution capabilities. | ||
| * This allows executing TypeScript code that can directly call registered tools as functions. | ||
| */ | ||
| declare class CodeModeUtcpClient extends UtcpClient { | ||
| private toolFunctionCache; | ||
| /** | ||
| * Standard prompt template for AI agents using CodeModeUtcpClient. | ||
| * This provides guidance on how to properly discover and use tools within code execution. | ||
| */ | ||
| static readonly AGENT_PROMPT_TEMPLATE: string; | ||
| /** | ||
| * Creates a new CodeModeUtcpClient instance. | ||
| * This creates a regular UtcpClient and then upgrades it to a CodeModeUtcpClient | ||
| * with all the same configuration and additional code execution capabilities. | ||
| * | ||
| * @param root_dir The root directory for the client to resolve relative paths from | ||
| * @param config The configuration for the client | ||
| * @returns A new CodeModeUtcpClient instance | ||
| */ | ||
| /** | ||
| * Debug method to expose registered call template serializers from the SDK instance used by code-mode. | ||
| * Use this to verify if the SDK is shared with other plugins like @utcp/direct-call. | ||
| */ | ||
| static getRegisteredSerializers(): string[]; | ||
| static create(root_dir?: string, config?: UtcpClientConfig | null): Promise<CodeModeUtcpClient>; | ||
| /** | ||
| * Sanitizes an identifier to be a valid TypeScript identifier. | ||
| * Replaces any non-alphanumeric character (except underscore) with underscore | ||
| * and ensures the first character is not a number. | ||
| * | ||
| * @param name The name to sanitize | ||
| * @returns Sanitized identifier | ||
| */ | ||
| private sanitizeIdentifier; | ||
| /** | ||
| * Converts a Tool object into a TypeScript function interface string. | ||
| * This generates the function signature that can be used in TypeScript code. | ||
| * | ||
| * @param tool The Tool object to convert | ||
| * @returns TypeScript function interface as a string | ||
| */ | ||
| toolToTypeScriptInterface(tool: Tool): string; | ||
| /** | ||
| * Converts all registered tools to TypeScript interface definitions. | ||
| * This provides the complete type definitions for all available tools. | ||
| * | ||
| * @returns A complete TypeScript interface definition string | ||
| */ | ||
| getAllToolsTypeScriptInterfaces(): Promise<string>; | ||
| /** | ||
| * Executes TypeScript code with access to registered tools and captures console output. | ||
| * The code can call tools directly as functions and has access to standard JavaScript globals. | ||
| * Uses isolated-vm for secure sandboxed execution. | ||
| * | ||
| * @param code TypeScript code to execute | ||
| * @param timeout Optional timeout in milliseconds (default: 30000) | ||
| * @param memoryLimit Optional memory limit in MB (default: 128) | ||
| * @returns Object containing both the execution result and captured console logs | ||
| */ | ||
| callToolChain(code: string, timeout?: number, memoryLimit?: number): Promise<{ | ||
| result: any; | ||
| logs: string[]; | ||
| }>; | ||
| /** | ||
| * Sets up console bridge functions in the isolated context. | ||
| * Console calls in the isolate are forwarded to the main process for logging. | ||
| */ | ||
| private setupConsoleBridge; | ||
| /** | ||
| * Sets up tool bridge functions in the isolated context. | ||
| * Tool calls in the isolate are forwarded to the main process for execution. | ||
| */ | ||
| private setupToolBridges; | ||
| /** | ||
| * Sets up utility functions and interfaces in the isolated context. | ||
| */ | ||
| private setupUtilities; | ||
| /** | ||
| * Converts a JSON Schema to TypeScript object content (properties only, no interface wrapper). | ||
| * This generates the content inside an interface definition. | ||
| * | ||
| * @param schema JSON Schema to convert | ||
| * @returns TypeScript interface properties as string | ||
| */ | ||
| private jsonSchemaToObjectContent; | ||
| /** | ||
| * Converts a JSON Schema to TypeScript interface definition. | ||
| * This handles the most common JSON Schema patterns used in UTCP tools. | ||
| * | ||
| * @param schema JSON Schema to convert | ||
| * @param typeName Name for the generated TypeScript type | ||
| * @returns TypeScript type definition as string | ||
| */ | ||
| private jsonSchemaToTypeScript; | ||
| /** | ||
| * Converts an object JSON Schema to TypeScript interface. | ||
| */ | ||
| private objectSchemaToTypeScript; | ||
| /** | ||
| * Converts an array JSON Schema to TypeScript type. | ||
| */ | ||
| private arraySchemaToTypeScript; | ||
| /** | ||
| * Converts a primitive JSON Schema to TypeScript type with enum support. | ||
| */ | ||
| private primitiveSchemaToTypeScript; | ||
| /** | ||
| * Converts a JSON Schema to a TypeScript type (not a full type definition). | ||
| */ | ||
| private jsonSchemaToTypeScriptType; | ||
| /** | ||
| * Escapes a string for safe use in JSDoc comments. | ||
| * Prevents comment injection via star-slash sequences. | ||
| */ | ||
| private escapeComment; | ||
| /** | ||
| * Maps basic JSON Schema types to TypeScript types. | ||
| */ | ||
| private mapJsonTypeToTS; | ||
| } | ||
| export { CodeModeUtcpClient }; |
+125
-2
@@ -1,2 +0,125 @@ | ||
| export { CodeModeUtcpClient } from './code_mode_utcp_client'; | ||
| //# sourceMappingURL=index.d.ts.map | ||
| import { UtcpClient, UtcpClientConfig, Tool } from '@utcp/sdk'; | ||
| /** | ||
| * CodeModeUtcpClient extends UtcpClient to provide TypeScript code execution capabilities. | ||
| * This allows executing TypeScript code that can directly call registered tools as functions. | ||
| */ | ||
| declare class CodeModeUtcpClient extends UtcpClient { | ||
| private toolFunctionCache; | ||
| /** | ||
| * Standard prompt template for AI agents using CodeModeUtcpClient. | ||
| * This provides guidance on how to properly discover and use tools within code execution. | ||
| */ | ||
| static readonly AGENT_PROMPT_TEMPLATE: string; | ||
| /** | ||
| * Creates a new CodeModeUtcpClient instance. | ||
| * This creates a regular UtcpClient and then upgrades it to a CodeModeUtcpClient | ||
| * with all the same configuration and additional code execution capabilities. | ||
| * | ||
| * @param root_dir The root directory for the client to resolve relative paths from | ||
| * @param config The configuration for the client | ||
| * @returns A new CodeModeUtcpClient instance | ||
| */ | ||
| /** | ||
| * Debug method to expose registered call template serializers from the SDK instance used by code-mode. | ||
| * Use this to verify if the SDK is shared with other plugins like @utcp/direct-call. | ||
| */ | ||
| static getRegisteredSerializers(): string[]; | ||
| static create(root_dir?: string, config?: UtcpClientConfig | null): Promise<CodeModeUtcpClient>; | ||
| /** | ||
| * Sanitizes an identifier to be a valid TypeScript identifier. | ||
| * Replaces any non-alphanumeric character (except underscore) with underscore | ||
| * and ensures the first character is not a number. | ||
| * | ||
| * @param name The name to sanitize | ||
| * @returns Sanitized identifier | ||
| */ | ||
| private sanitizeIdentifier; | ||
| /** | ||
| * Converts a Tool object into a TypeScript function interface string. | ||
| * This generates the function signature that can be used in TypeScript code. | ||
| * | ||
| * @param tool The Tool object to convert | ||
| * @returns TypeScript function interface as a string | ||
| */ | ||
| toolToTypeScriptInterface(tool: Tool): string; | ||
| /** | ||
| * Converts all registered tools to TypeScript interface definitions. | ||
| * This provides the complete type definitions for all available tools. | ||
| * | ||
| * @returns A complete TypeScript interface definition string | ||
| */ | ||
| getAllToolsTypeScriptInterfaces(): Promise<string>; | ||
| /** | ||
| * Executes TypeScript code with access to registered tools and captures console output. | ||
| * The code can call tools directly as functions and has access to standard JavaScript globals. | ||
| * Uses isolated-vm for secure sandboxed execution. | ||
| * | ||
| * @param code TypeScript code to execute | ||
| * @param timeout Optional timeout in milliseconds (default: 30000) | ||
| * @param memoryLimit Optional memory limit in MB (default: 128) | ||
| * @returns Object containing both the execution result and captured console logs | ||
| */ | ||
| callToolChain(code: string, timeout?: number, memoryLimit?: number): Promise<{ | ||
| result: any; | ||
| logs: string[]; | ||
| }>; | ||
| /** | ||
| * Sets up console bridge functions in the isolated context. | ||
| * Console calls in the isolate are forwarded to the main process for logging. | ||
| */ | ||
| private setupConsoleBridge; | ||
| /** | ||
| * Sets up tool bridge functions in the isolated context. | ||
| * Tool calls in the isolate are forwarded to the main process for execution. | ||
| */ | ||
| private setupToolBridges; | ||
| /** | ||
| * Sets up utility functions and interfaces in the isolated context. | ||
| */ | ||
| private setupUtilities; | ||
| /** | ||
| * Converts a JSON Schema to TypeScript object content (properties only, no interface wrapper). | ||
| * This generates the content inside an interface definition. | ||
| * | ||
| * @param schema JSON Schema to convert | ||
| * @returns TypeScript interface properties as string | ||
| */ | ||
| private jsonSchemaToObjectContent; | ||
| /** | ||
| * Converts a JSON Schema to TypeScript interface definition. | ||
| * This handles the most common JSON Schema patterns used in UTCP tools. | ||
| * | ||
| * @param schema JSON Schema to convert | ||
| * @param typeName Name for the generated TypeScript type | ||
| * @returns TypeScript type definition as string | ||
| */ | ||
| private jsonSchemaToTypeScript; | ||
| /** | ||
| * Converts an object JSON Schema to TypeScript interface. | ||
| */ | ||
| private objectSchemaToTypeScript; | ||
| /** | ||
| * Converts an array JSON Schema to TypeScript type. | ||
| */ | ||
| private arraySchemaToTypeScript; | ||
| /** | ||
| * Converts a primitive JSON Schema to TypeScript type with enum support. | ||
| */ | ||
| private primitiveSchemaToTypeScript; | ||
| /** | ||
| * Converts a JSON Schema to a TypeScript type (not a full type definition). | ||
| */ | ||
| private jsonSchemaToTypeScriptType; | ||
| /** | ||
| * Escapes a string for safe use in JSDoc comments. | ||
| * Prevents comment injection via star-slash sequences. | ||
| */ | ||
| private escapeComment; | ||
| /** | ||
| * Maps basic JSON Schema types to TypeScript types. | ||
| */ | ||
| private mapJsonTypeToTS; | ||
| } | ||
| export { CodeModeUtcpClient }; |
+473
-5
@@ -1,6 +0,474 @@ | ||
| "use strict"; | ||
| Object.defineProperty(exports, "__esModule", { value: true }); | ||
| exports.CodeModeUtcpClient = void 0; | ||
| var code_mode_utcp_client_1 = require("./code_mode_utcp_client"); | ||
| Object.defineProperty(exports, "CodeModeUtcpClient", { enumerable: true, get: function () { return code_mode_utcp_client_1.CodeModeUtcpClient; } }); | ||
| // src/code_mode_utcp_client.ts | ||
| import { UtcpClient, CallTemplateSerializer } from "@utcp/sdk"; | ||
| import ivm from "isolated-vm"; | ||
| var CodeModeUtcpClient = class _CodeModeUtcpClient extends UtcpClient { | ||
| toolFunctionCache = /* @__PURE__ */ new Map(); | ||
| /** | ||
| * Standard prompt template for AI agents using CodeModeUtcpClient. | ||
| * This provides guidance on how to properly discover and use tools within code execution. | ||
| */ | ||
| static AGENT_PROMPT_TEMPLATE = ` | ||
| ## UTCP CodeMode Tool Usage Guide | ||
| You have access to a CodeModeUtcpClient that allows you to execute TypeScript code with access to registered tools. Follow this workflow: | ||
| ### 1. Tool Discovery Phase | ||
| **Always start by discovering available tools:** | ||
| - Tools are organized by manual namespace (e.g., \`manual_name.tool_name\`) | ||
| - Use hierarchical access patterns: \`manual.tool({ param: value })\` (synchronous, no await) | ||
| - Multiple manuals can contain tools with the same name - namespaces prevent conflicts | ||
| ### 2. Interface Introspection | ||
| **Understand tool contracts before using them:** | ||
| - Access \`__interfaces\` to see all available TypeScript interface definitions | ||
| - Use \`__getToolInterface('manual.tool')\` to get specific tool interfaces | ||
| - Interfaces show required inputs, expected outputs, and descriptions | ||
| - Look for "Access as: manual.tool(args)" comments for usage patterns | ||
| ### 3. Code Execution Guidelines | ||
| **When writing code for \`callToolChain\`:** | ||
| - Use \`manual.tool({ param: value })\` syntax for all tool calls (synchronous, no await needed) | ||
| - Tools are synchronous functions - the main process handles async operations internally | ||
| - You have access to standard JavaScript globals: \`console\`, \`JSON\`, \`Math\`, \`Date\`, etc. | ||
| - All console output (\`console.log\`, \`console.error\`, etc.) is automatically captured and returned | ||
| - Build properly structured input objects based on interface definitions | ||
| - Handle errors appropriately with try/catch blocks | ||
| - Chain tool calls by using results from previous calls | ||
| - Use \`return\` to return the final result from your code | ||
| ### 4. Best Practices | ||
| - **Discover first, code second**: Always explore available tools before writing execution code | ||
| - **Respect namespaces**: Use full \`manual.tool\` names to avoid conflicts | ||
| - **Parse interfaces**: Use interface information to construct proper input objects | ||
| - **Error handling**: Wrap tool calls in try/catch for robustness | ||
| - **Data flow**: Chain tools by passing outputs as inputs to subsequent tools | ||
| ### 5. Available Runtime Context | ||
| - \`__interfaces\`: String containing all TypeScript interface definitions | ||
| - \`__getToolInterface(toolName)\`: Function to get specific tool interface | ||
| - All registered tools as \`manual.tool\` functions | ||
| - Standard JavaScript built-ins for data processing | ||
| Remember: Always discover and understand available tools before attempting to use them in code execution. | ||
| `.trim(); | ||
| /** | ||
| * Creates a new CodeModeUtcpClient instance. | ||
| * This creates a regular UtcpClient and then upgrades it to a CodeModeUtcpClient | ||
| * with all the same configuration and additional code execution capabilities. | ||
| * | ||
| * @param root_dir The root directory for the client to resolve relative paths from | ||
| * @param config The configuration for the client | ||
| * @returns A new CodeModeUtcpClient instance | ||
| */ | ||
| /** | ||
| * Debug method to expose registered call template serializers from the SDK instance used by code-mode. | ||
| * Use this to verify if the SDK is shared with other plugins like @utcp/direct-call. | ||
| */ | ||
| static getRegisteredSerializers() { | ||
| const serializerClass = CallTemplateSerializer; | ||
| return Object.keys(serializerClass.serializers || {}); | ||
| } | ||
| static async create(root_dir = process.cwd(), config = null) { | ||
| console.log( | ||
| "[CodeModeUtcpClient] Registered serializers at create():", | ||
| _CodeModeUtcpClient.getRegisteredSerializers() | ||
| ); | ||
| const baseClient = await UtcpClient.create(root_dir, config); | ||
| const codeModeClient = Object.setPrototypeOf(baseClient, _CodeModeUtcpClient.prototype); | ||
| codeModeClient.toolFunctionCache = /* @__PURE__ */ new Map(); | ||
| return codeModeClient; | ||
| } | ||
| /** | ||
| * Sanitizes an identifier to be a valid TypeScript identifier. | ||
| * Replaces any non-alphanumeric character (except underscore) with underscore | ||
| * and ensures the first character is not a number. | ||
| * | ||
| * @param name The name to sanitize | ||
| * @returns Sanitized identifier | ||
| */ | ||
| sanitizeIdentifier(name) { | ||
| return name.replace(/[^a-zA-Z0-9_]/g, "_").replace(/^[0-9]/, "_$&"); | ||
| } | ||
| /** | ||
| * Converts a Tool object into a TypeScript function interface string. | ||
| * This generates the function signature that can be used in TypeScript code. | ||
| * | ||
| * @param tool The Tool object to convert | ||
| * @returns TypeScript function interface as a string | ||
| */ | ||
| toolToTypeScriptInterface(tool) { | ||
| if (this.toolFunctionCache.has(tool.name)) { | ||
| return this.toolFunctionCache.get(tool.name); | ||
| } | ||
| let interfaceContent; | ||
| let accessPattern; | ||
| if (tool.name.includes(".")) { | ||
| const [manualName, ...toolParts] = tool.name.split("."); | ||
| const sanitizedManualName = this.sanitizeIdentifier(manualName); | ||
| const toolName = toolParts.map((part) => this.sanitizeIdentifier(part)).join("_"); | ||
| accessPattern = `${sanitizedManualName}.${toolName}`; | ||
| const inputInterfaceContent = this.jsonSchemaToObjectContent(tool.inputs); | ||
| const outputInterfaceContent = this.jsonSchemaToObjectContent(tool.outputs); | ||
| interfaceContent = ` | ||
| namespace ${sanitizedManualName} { | ||
| interface ${toolName}Input { | ||
| ${inputInterfaceContent} | ||
| } | ||
| interface ${toolName}Output { | ||
| ${outputInterfaceContent} | ||
| } | ||
| }`; | ||
| } else { | ||
| const sanitizedToolName = this.sanitizeIdentifier(tool.name); | ||
| accessPattern = sanitizedToolName; | ||
| const inputType = this.jsonSchemaToTypeScript(tool.inputs, `${sanitizedToolName}Input`); | ||
| const outputType = this.jsonSchemaToTypeScript(tool.outputs, `${sanitizedToolName}Output`); | ||
| interfaceContent = `${inputType} | ||
| ${outputType}`; | ||
| } | ||
| const interfaceString = ` | ||
| ${interfaceContent} | ||
| /** | ||
| * ${this.escapeComment(tool.description)} | ||
| * Tags: ${this.escapeComment(tool.tags.join(", "))} | ||
| * Access as: ${accessPattern}(args) | ||
| */`; | ||
| this.toolFunctionCache.set(tool.name, interfaceString); | ||
| return interfaceString; | ||
| } | ||
| /** | ||
| * Converts all registered tools to TypeScript interface definitions. | ||
| * This provides the complete type definitions for all available tools. | ||
| * | ||
| * @returns A complete TypeScript interface definition string | ||
| */ | ||
| async getAllToolsTypeScriptInterfaces() { | ||
| const tools = await this.getTools(); | ||
| const interfaces = tools.map((tool) => this.toolToTypeScriptInterface(tool)); | ||
| return `// Auto-generated TypeScript interfaces for UTCP tools | ||
| ${interfaces.join("\n\n")}`; | ||
| } | ||
| /** | ||
| * Executes TypeScript code with access to registered tools and captures console output. | ||
| * The code can call tools directly as functions and has access to standard JavaScript globals. | ||
| * Uses isolated-vm for secure sandboxed execution. | ||
| * | ||
| * @param code TypeScript code to execute | ||
| * @param timeout Optional timeout in milliseconds (default: 30000) | ||
| * @param memoryLimit Optional memory limit in MB (default: 128) | ||
| * @returns Object containing both the execution result and captured console logs | ||
| */ | ||
| async callToolChain(code, timeout = 3e4, memoryLimit = 128) { | ||
| const tools = await this.getTools(); | ||
| const logs = []; | ||
| const isolate = new ivm.Isolate({ memoryLimit }); | ||
| try { | ||
| const context = await isolate.createContext(); | ||
| const jail = context.global; | ||
| await jail.set("global", jail.derefInto()); | ||
| await this.setupConsoleBridge(isolate, context, jail, logs); | ||
| await this.setupToolBridges(isolate, context, jail, tools); | ||
| await this.setupUtilities(isolate, context, jail, tools); | ||
| const wrappedCode = ` | ||
| (function() { | ||
| var __result = (function() { | ||
| ${code} | ||
| })(); | ||
| return JSON.stringify({ __result: __result }); | ||
| })() | ||
| `; | ||
| const script = await isolate.compileScript(wrappedCode); | ||
| const resultJson = await script.run(context, { timeout }); | ||
| const result = typeof resultJson === "string" ? JSON.parse(resultJson).__result : resultJson; | ||
| return { result, logs }; | ||
| } catch (error) { | ||
| const errorMessage = error instanceof Error ? error.message : String(error); | ||
| return { | ||
| result: null, | ||
| logs: [...logs, `[ERROR] Code execution failed: ${errorMessage}`] | ||
| }; | ||
| } finally { | ||
| isolate.dispose(); | ||
| } | ||
| } | ||
| /** | ||
| * Sets up console bridge functions in the isolated context. | ||
| * Console calls in the isolate are forwarded to the main process for logging. | ||
| */ | ||
| async setupConsoleBridge(isolate, context, jail, logs) { | ||
| const createLogHandler = (prefix) => { | ||
| return new ivm.Reference((...args) => { | ||
| const message = args.join(" "); | ||
| logs.push(prefix ? `${prefix} ${message}` : message); | ||
| }); | ||
| }; | ||
| await jail.set("__logRef", createLogHandler("")); | ||
| await jail.set("__errorRef", createLogHandler("[ERROR]")); | ||
| await jail.set("__warnRef", createLogHandler("[WARN]")); | ||
| await jail.set("__infoRef", createLogHandler("[INFO]")); | ||
| const consoleSetupScript = await isolate.compileScript(` | ||
| const __stringify = (a) => typeof a === 'object' && a !== null ? JSON.stringify(a, null, 2) : String(a); | ||
| global.console = { | ||
| log: (...args) => __logRef.applySync(undefined, args.map(__stringify)), | ||
| error: (...args) => __errorRef.applySync(undefined, args.map(__stringify)), | ||
| warn: (...args) => __warnRef.applySync(undefined, args.map(__stringify)), | ||
| info: (...args) => __infoRef.applySync(undefined, args.map(__stringify)) | ||
| }; | ||
| `); | ||
| await consoleSetupScript.run(context); | ||
| } | ||
| /** | ||
| * Sets up tool bridge functions in the isolated context. | ||
| * Tool calls in the isolate are forwarded to the main process for execution. | ||
| */ | ||
| async setupToolBridges(isolate, context, jail, tools) { | ||
| const toolCallerRef = new ivm.Reference(async (toolName, argsJson) => { | ||
| try { | ||
| const args = JSON.parse(argsJson); | ||
| const result = await this.callTool(toolName, args); | ||
| return JSON.stringify({ success: true, result }); | ||
| } catch (error) { | ||
| return JSON.stringify({ | ||
| success: false, | ||
| error: error instanceof Error ? error.message : String(error) | ||
| }); | ||
| } | ||
| }); | ||
| await jail.set("__callToolRef", toolCallerRef); | ||
| const toolSetupParts = []; | ||
| const namespaces = /* @__PURE__ */ new Set(); | ||
| for (const tool of tools) { | ||
| if (tool.name.includes(".")) { | ||
| const [manualName, ...toolParts] = tool.name.split("."); | ||
| const sanitizedManualName = this.sanitizeIdentifier(manualName); | ||
| const toolFnName = toolParts.map((part) => this.sanitizeIdentifier(part)).join("_"); | ||
| if (!namespaces.has(sanitizedManualName)) { | ||
| namespaces.add(sanitizedManualName); | ||
| toolSetupParts.push(`global.${sanitizedManualName} = global.${sanitizedManualName} || {};`); | ||
| } | ||
| toolSetupParts.push(` | ||
| global.${sanitizedManualName}.${toolFnName} = function(args) { | ||
| // applySyncPromise blocks until async tool call completes in main process | ||
| var resultJson = __callToolRef.applySyncPromise(undefined, [${JSON.stringify(tool.name)}, JSON.stringify(args || {})]); | ||
| var parsed = JSON.parse(resultJson); | ||
| if (!parsed.success) throw new Error(parsed.error); | ||
| return parsed.result; | ||
| }; | ||
| `); | ||
| } else { | ||
| const sanitizedToolName = this.sanitizeIdentifier(tool.name); | ||
| toolSetupParts.push(` | ||
| global.${sanitizedToolName} = function(args) { | ||
| // applySyncPromise blocks until async tool call completes in main process | ||
| var resultJson = __callToolRef.applySyncPromise(undefined, [${JSON.stringify(tool.name)}, JSON.stringify(args || {})]); | ||
| var parsed = JSON.parse(resultJson); | ||
| if (!parsed.success) throw new Error(parsed.error); | ||
| return parsed.result; | ||
| }; | ||
| `); | ||
| } | ||
| } | ||
| const toolSetupScript = await isolate.compileScript(toolSetupParts.join("\n")); | ||
| await toolSetupScript.run(context); | ||
| } | ||
| /** | ||
| * Sets up utility functions and interfaces in the isolated context. | ||
| */ | ||
| async setupUtilities(isolate, context, jail, tools) { | ||
| const interfaces = await this.getAllToolsTypeScriptInterfaces(); | ||
| await jail.set("__interfaces", interfaces); | ||
| const interfaceMap = {}; | ||
| for (const tool of tools) { | ||
| interfaceMap[tool.name] = this.toolToTypeScriptInterface(tool); | ||
| } | ||
| await jail.set("__interfaceMapJson", JSON.stringify(interfaceMap)); | ||
| const utilSetupScript = await isolate.compileScript(` | ||
| global.__getToolInterface = (toolName) => { | ||
| const map = JSON.parse(__interfaceMapJson); | ||
| return map[toolName] || null; | ||
| }; | ||
| `); | ||
| await utilSetupScript.run(context); | ||
| } | ||
| /** | ||
| * Converts a JSON Schema to TypeScript object content (properties only, no interface wrapper). | ||
| * This generates the content inside an interface definition. | ||
| * | ||
| * @param schema JSON Schema to convert | ||
| * @returns TypeScript interface properties as string | ||
| */ | ||
| jsonSchemaToObjectContent(schema) { | ||
| if (!schema || typeof schema !== "object" || schema.type !== "object") { | ||
| return " [key: string]: any;"; | ||
| } | ||
| const properties = schema.properties || {}; | ||
| const required = schema.required || []; | ||
| const lines = []; | ||
| for (const [propName, propSchema] of Object.entries(properties)) { | ||
| const isRequired = required.includes(propName); | ||
| const optionalMarker = isRequired ? "" : "?"; | ||
| const description = propSchema.description || ""; | ||
| const tsType = this.jsonSchemaToTypeScriptType(propSchema); | ||
| if (description) { | ||
| lines.push(` /** ${this.escapeComment(description)} */`); | ||
| } | ||
| lines.push(` ${propName}${optionalMarker}: ${tsType};`); | ||
| } | ||
| return lines.length > 0 ? lines.join("\n") : " [key: string]: any;"; | ||
| } | ||
| /** | ||
| * Converts a JSON Schema to TypeScript interface definition. | ||
| * This handles the most common JSON Schema patterns used in UTCP tools. | ||
| * | ||
| * @param schema JSON Schema to convert | ||
| * @param typeName Name for the generated TypeScript type | ||
| * @returns TypeScript type definition as string | ||
| */ | ||
| jsonSchemaToTypeScript(schema, typeName) { | ||
| if (!schema || typeof schema !== "object") { | ||
| return `type ${typeName} = any;`; | ||
| } | ||
| switch (schema.type) { | ||
| case "object": | ||
| return this.objectSchemaToTypeScript(schema, typeName); | ||
| case "array": | ||
| return this.arraySchemaToTypeScript(schema, typeName); | ||
| case "string": | ||
| return this.primitiveSchemaToTypeScript(schema, typeName, "string"); | ||
| case "number": | ||
| case "integer": | ||
| return this.primitiveSchemaToTypeScript(schema, typeName, "number"); | ||
| case "boolean": | ||
| return this.primitiveSchemaToTypeScript(schema, typeName, "boolean"); | ||
| case "null": | ||
| return `type ${typeName} = null;`; | ||
| default: | ||
| if (Array.isArray(schema.type)) { | ||
| const types = schema.type.map((t) => this.mapJsonTypeToTS(t)).join(" | "); | ||
| return `type ${typeName} = ${types};`; | ||
| } | ||
| return `type ${typeName} = any;`; | ||
| } | ||
| } | ||
| /** | ||
| * Converts an object JSON Schema to TypeScript interface. | ||
| */ | ||
| objectSchemaToTypeScript(schema, typeName) { | ||
| if (!schema.properties) { | ||
| return `interface ${typeName} { | ||
| [key: string]: any; | ||
| }`; | ||
| } | ||
| const properties = Object.entries(schema.properties).map(([key, propSchema]) => { | ||
| const isRequired = schema.required?.includes(key) ?? false; | ||
| const optional = isRequired ? "" : "?"; | ||
| const propType = this.jsonSchemaToTypeScriptType(propSchema); | ||
| const description = propSchema.description ? ` /** ${this.escapeComment(propSchema.description)} */ | ||
| ` : ""; | ||
| return `${description} ${key}${optional}: ${propType};`; | ||
| }).join("\n"); | ||
| return `interface ${typeName} { | ||
| ${properties} | ||
| }`; | ||
| } | ||
| /** | ||
| * Converts an array JSON Schema to TypeScript type. | ||
| */ | ||
| arraySchemaToTypeScript(schema, typeName) { | ||
| if (!schema.items) { | ||
| return `type ${typeName} = any[];`; | ||
| } | ||
| const itemType = Array.isArray(schema.items) ? schema.items.map((item) => this.jsonSchemaToTypeScriptType(item)).join(" | ") : this.jsonSchemaToTypeScriptType(schema.items); | ||
| return `type ${typeName} = (${itemType})[];`; | ||
| } | ||
| /** | ||
| * Converts a primitive JSON Schema to TypeScript type with enum support. | ||
| */ | ||
| primitiveSchemaToTypeScript(schema, typeName, baseType) { | ||
| if (schema.enum) { | ||
| const enumValues = schema.enum.map( | ||
| (val) => typeof val === "string" ? JSON.stringify(val) : String(val) | ||
| ).join(" | "); | ||
| return `type ${typeName} = ${enumValues};`; | ||
| } | ||
| return `type ${typeName} = ${baseType};`; | ||
| } | ||
| /** | ||
| * Converts a JSON Schema to a TypeScript type (not a full type definition). | ||
| */ | ||
| jsonSchemaToTypeScriptType(schema) { | ||
| if (!schema || typeof schema !== "object") { | ||
| return "any"; | ||
| } | ||
| if (schema.enum) { | ||
| return schema.enum.map( | ||
| (val) => typeof val === "string" ? JSON.stringify(val) : String(val) | ||
| ).join(" | "); | ||
| } | ||
| switch (schema.type) { | ||
| case "object": | ||
| if (!schema.properties) return "{ [key: string]: any }"; | ||
| const props = Object.entries(schema.properties).map(([key, propSchema]) => { | ||
| const isRequired = schema.required?.includes(key) ?? false; | ||
| const optional = isRequired ? "" : "?"; | ||
| const propType = this.jsonSchemaToTypeScriptType(propSchema); | ||
| return `${key}${optional}: ${propType}`; | ||
| }).join("; "); | ||
| return `{ ${props} }`; | ||
| case "array": | ||
| if (!schema.items) return "any[]"; | ||
| const itemType = Array.isArray(schema.items) ? schema.items.map((item) => this.jsonSchemaToTypeScriptType(item)).join(" | ") : this.jsonSchemaToTypeScriptType(schema.items); | ||
| return `(${itemType})[]`; | ||
| case "string": | ||
| return "string"; | ||
| case "number": | ||
| case "integer": | ||
| return "number"; | ||
| case "boolean": | ||
| return "boolean"; | ||
| case "null": | ||
| return "null"; | ||
| default: | ||
| if (Array.isArray(schema.type)) { | ||
| return schema.type.map((t) => this.mapJsonTypeToTS(t)).join(" | "); | ||
| } | ||
| return "any"; | ||
| } | ||
| } | ||
| /** | ||
| * Escapes a string for safe use in JSDoc comments. | ||
| * Prevents comment injection via star-slash sequences. | ||
| */ | ||
| escapeComment(text) { | ||
| return text.replace(/\*\//g, "*\\/").replace(/\n/g, " "); | ||
| } | ||
| /** | ||
| * Maps basic JSON Schema types to TypeScript types. | ||
| */ | ||
| mapJsonTypeToTS(type) { | ||
| switch (type) { | ||
| case "string": | ||
| return "string"; | ||
| case "number": | ||
| case "integer": | ||
| return "number"; | ||
| case "boolean": | ||
| return "boolean"; | ||
| case "null": | ||
| return "null"; | ||
| case "object": | ||
| return "object"; | ||
| case "array": | ||
| return "any[]"; | ||
| default: | ||
| return "any"; | ||
| } | ||
| } | ||
| }; | ||
| export { | ||
| CodeModeUtcpClient | ||
| }; | ||
| //# sourceMappingURL=index.js.map |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,iEAA6D;AAApD,2HAAA,kBAAkB,OAAA"} | ||
| {"version":3,"sources":["../src/code_mode_utcp_client.ts"],"sourcesContent":["import { UtcpClient, Tool, JsonSchema, UtcpClientConfig, CallTemplateSerializer } from '@utcp/sdk';\r\nimport ivm from 'isolated-vm';\r\n\r\n/**\r\n * CodeModeUtcpClient extends UtcpClient to provide TypeScript code execution capabilities.\r\n * This allows executing TypeScript code that can directly call registered tools as functions.\r\n */\r\nexport class CodeModeUtcpClient extends UtcpClient {\r\n private toolFunctionCache: Map<string, string> = new Map();\r\n\r\n /**\r\n * Standard prompt template for AI agents using CodeModeUtcpClient.\r\n * This provides guidance on how to properly discover and use tools within code execution.\r\n */\r\n public static readonly AGENT_PROMPT_TEMPLATE = `\r\n## UTCP CodeMode Tool Usage Guide\r\n\r\nYou have access to a CodeModeUtcpClient that allows you to execute TypeScript code with access to registered tools. Follow this workflow:\r\n\r\n### 1. Tool Discovery Phase\r\n**Always start by discovering available tools:**\r\n- Tools are organized by manual namespace (e.g., \\`manual_name.tool_name\\`)\r\n- Use hierarchical access patterns: \\`manual.tool({ param: value })\\` (synchronous, no await)\r\n- Multiple manuals can contain tools with the same name - namespaces prevent conflicts\r\n\r\n### 2. Interface Introspection\r\n**Understand tool contracts before using them:**\r\n- Access \\`__interfaces\\` to see all available TypeScript interface definitions\r\n- Use \\`__getToolInterface('manual.tool')\\` to get specific tool interfaces\r\n- Interfaces show required inputs, expected outputs, and descriptions\r\n- Look for \"Access as: manual.tool(args)\" comments for usage patterns\r\n\r\n### 3. Code Execution Guidelines\r\n**When writing code for \\`callToolChain\\`:**\r\n- Use \\`manual.tool({ param: value })\\` syntax for all tool calls (synchronous, no await needed)\r\n- Tools are synchronous functions - the main process handles async operations internally\r\n- You have access to standard JavaScript globals: \\`console\\`, \\`JSON\\`, \\`Math\\`, \\`Date\\`, etc.\r\n- All console output (\\`console.log\\`, \\`console.error\\`, etc.) is automatically captured and returned\r\n- Build properly structured input objects based on interface definitions\r\n- Handle errors appropriately with try/catch blocks\r\n- Chain tool calls by using results from previous calls\r\n- Use \\`return\\` to return the final result from your code\r\n\r\n### 4. Best Practices\r\n- **Discover first, code second**: Always explore available tools before writing execution code\r\n- **Respect namespaces**: Use full \\`manual.tool\\` names to avoid conflicts\r\n- **Parse interfaces**: Use interface information to construct proper input objects\r\n- **Error handling**: Wrap tool calls in try/catch for robustness\r\n- **Data flow**: Chain tools by passing outputs as inputs to subsequent tools\r\n\r\n### 5. Available Runtime Context\r\n- \\`__interfaces\\`: String containing all TypeScript interface definitions\r\n- \\`__getToolInterface(toolName)\\`: Function to get specific tool interface\r\n- All registered tools as \\`manual.tool\\` functions\r\n- Standard JavaScript built-ins for data processing\r\n\r\nRemember: Always discover and understand available tools before attempting to use them in code execution.\r\n`.trim();\r\n\r\n /**\r\n * Creates a new CodeModeUtcpClient instance.\r\n * This creates a regular UtcpClient and then upgrades it to a CodeModeUtcpClient\r\n * with all the same configuration and additional code execution capabilities.\r\n * \r\n * @param root_dir The root directory for the client to resolve relative paths from\r\n * @param config The configuration for the client\r\n * @returns A new CodeModeUtcpClient instance\r\n */\r\n /**\r\n * Debug method to expose registered call template serializers from the SDK instance used by code-mode.\r\n * Use this to verify if the SDK is shared with other plugins like @utcp/direct-call.\r\n */\r\n public static getRegisteredSerializers(): string[] {\r\n // Access the static serializers map\r\n const serializerClass = CallTemplateSerializer as any;\r\n return Object.keys(serializerClass.serializers || {});\r\n }\r\n\r\n public static async create(\r\n root_dir: string = process.cwd(),\r\n config: UtcpClientConfig | null = null\r\n ): Promise<CodeModeUtcpClient> {\r\n // Debug: log registered serializers at creation time\r\n console.log('[CodeModeUtcpClient] Registered serializers at create():', \r\n CodeModeUtcpClient.getRegisteredSerializers());\r\n \r\n // Create a regular UtcpClient first\r\n const baseClient = await UtcpClient.create(root_dir, config);\r\n \r\n // Create a CodeModeUtcpClient using the same configuration\r\n const codeModeClient = Object.setPrototypeOf(baseClient, CodeModeUtcpClient.prototype) as CodeModeUtcpClient;\r\n \r\n // Initialize the cache\r\n (codeModeClient as any).toolFunctionCache = new Map();\r\n \r\n return codeModeClient;\r\n }\r\n\r\n /**\r\n * Sanitizes an identifier to be a valid TypeScript identifier.\r\n * Replaces any non-alphanumeric character (except underscore) with underscore\r\n * and ensures the first character is not a number.\r\n * \r\n * @param name The name to sanitize\r\n * @returns Sanitized identifier\r\n */\r\n private sanitizeIdentifier(name: string): string {\r\n return name\r\n .replace(/[^a-zA-Z0-9_]/g, '_')\r\n .replace(/^[0-9]/, '_$&');\r\n }\r\n\r\n /**\r\n * Converts a Tool object into a TypeScript function interface string.\r\n * This generates the function signature that can be used in TypeScript code.\r\n * \r\n * @param tool The Tool object to convert\r\n * @returns TypeScript function interface as a string\r\n */\r\n public toolToTypeScriptInterface(tool: Tool): string {\r\n if (this.toolFunctionCache.has(tool.name)) {\r\n return this.toolFunctionCache.get(tool.name)!;\r\n }\r\n\r\n // Generate hierarchical interface structure\r\n let interfaceContent: string;\r\n let accessPattern: string;\r\n \r\n if (tool.name.includes('.')) {\r\n const [manualName, ...toolParts] = tool.name.split('.');\r\n const sanitizedManualName = this.sanitizeIdentifier(manualName);\r\n const toolName = toolParts.map(part => this.sanitizeIdentifier(part)).join('_');\r\n accessPattern = `${sanitizedManualName}.${toolName}`;\r\n \r\n // Generate interfaces within namespace\r\n const inputInterfaceContent = this.jsonSchemaToObjectContent(tool.inputs);\r\n const outputInterfaceContent = this.jsonSchemaToObjectContent(tool.outputs);\r\n \r\n interfaceContent = `\r\nnamespace ${sanitizedManualName} {\r\n interface ${toolName}Input {\r\n${inputInterfaceContent}\r\n }\r\n\r\n interface ${toolName}Output {\r\n${outputInterfaceContent}\r\n }\r\n}`;\r\n } else {\r\n // No manual namespace, generate flat interfaces\r\n const sanitizedToolName = this.sanitizeIdentifier(tool.name);\r\n accessPattern = sanitizedToolName;\r\n const inputType = this.jsonSchemaToTypeScript(tool.inputs, `${sanitizedToolName}Input`);\r\n const outputType = this.jsonSchemaToTypeScript(tool.outputs, `${sanitizedToolName}Output`);\r\n interfaceContent = `${inputType}\\n\\n${outputType}`;\r\n }\r\n const interfaceString = `\r\n${interfaceContent}\r\n\r\n/**\r\n * ${this.escapeComment(tool.description)}\r\n * Tags: ${this.escapeComment(tool.tags.join(', '))}\r\n * Access as: ${accessPattern}(args)\r\n */`;\r\n\r\n this.toolFunctionCache.set(tool.name, interfaceString);\r\n return interfaceString;\r\n }\r\n\r\n /**\r\n * Converts all registered tools to TypeScript interface definitions.\r\n * This provides the complete type definitions for all available tools.\r\n * \r\n * @returns A complete TypeScript interface definition string\r\n */\r\n public async getAllToolsTypeScriptInterfaces(): Promise<string> {\r\n const tools = await this.getTools();\r\n const interfaces = tools.map(tool => this.toolToTypeScriptInterface(tool));\r\n \r\n return `// Auto-generated TypeScript interfaces for UTCP tools\r\n${interfaces.join('\\n\\n')}`;\r\n }\r\n\r\n /**\r\n * Executes TypeScript code with access to registered tools and captures console output.\r\n * The code can call tools directly as functions and has access to standard JavaScript globals.\r\n * Uses isolated-vm for secure sandboxed execution.\r\n * \r\n * @param code TypeScript code to execute \r\n * @param timeout Optional timeout in milliseconds (default: 30000)\r\n * @param memoryLimit Optional memory limit in MB (default: 128)\r\n * @returns Object containing both the execution result and captured console logs\r\n */\r\n public async callToolChain(\r\n code: string, \r\n timeout: number = 30000,\r\n memoryLimit: number = 128\r\n ): Promise<{result: any, logs: string[]}> {\r\n const tools = await this.getTools();\r\n const logs: string[] = [];\r\n \r\n // Create isolated VM\r\n const isolate = new ivm.Isolate({ memoryLimit });\r\n \r\n try {\r\n const context = await isolate.createContext();\r\n const jail = context.global;\r\n \r\n // Set up the jail with a reference to itself\r\n await jail.set('global', jail.derefInto());\r\n \r\n // Set up console logging bridges\r\n await this.setupConsoleBridge(isolate, context, jail, logs);\r\n \r\n // Set up tool bridges\r\n await this.setupToolBridges(isolate, context, jail, tools);\r\n \r\n // Set up utility functions and interfaces\r\n await this.setupUtilities(isolate, context, jail, tools);\r\n \r\n // Compile and run the user code - code is SYNC since tools use applySyncPromise\r\n // Wrap result in JSON.stringify to transfer objects out of isolate\r\n const wrappedCode = `\r\n (function() {\r\n var __result = (function() {\r\n ${code}\r\n })();\r\n return JSON.stringify({ __result: __result });\r\n })()\r\n `;\r\n \r\n const script = await isolate.compileScript(wrappedCode);\r\n const resultJson = await script.run(context, { timeout });\r\n \r\n // Parse the result from JSON\r\n const result = typeof resultJson === 'string' \r\n ? JSON.parse(resultJson).__result\r\n : resultJson;\r\n \r\n return { result, logs };\r\n } catch (error) {\r\n const errorMessage = error instanceof Error ? error.message : String(error);\r\n return { \r\n result: null, \r\n logs: [...logs, `[ERROR] Code execution failed: ${errorMessage}`] \r\n };\r\n } finally {\r\n isolate.dispose();\r\n }\r\n }\r\n\r\n /**\r\n * Sets up console bridge functions in the isolated context.\r\n * Console calls in the isolate are forwarded to the main process for logging.\r\n */\r\n private async setupConsoleBridge(\r\n isolate: ivm.Isolate,\r\n context: ivm.Context,\r\n jail: ivm.Reference<Record<string | number | symbol, unknown>>,\r\n logs: string[]\r\n ): Promise<void> {\r\n // Create log capture functions in main process\r\n const createLogHandler = (prefix: string) => {\r\n return new ivm.Reference((...args: any[]) => {\r\n const message = args.join(' ');\r\n logs.push(prefix ? `${prefix} ${message}` : message);\r\n });\r\n };\r\n\r\n // Set up console references in isolate\r\n await jail.set('__logRef', createLogHandler(''));\r\n await jail.set('__errorRef', createLogHandler('[ERROR]'));\r\n await jail.set('__warnRef', createLogHandler('[WARN]'));\r\n await jail.set('__infoRef', createLogHandler('[INFO]'));\r\n \r\n // Create console object in isolate that calls the references\r\n const consoleSetupScript = await isolate.compileScript(`\r\n const __stringify = (a) => typeof a === 'object' && a !== null ? JSON.stringify(a, null, 2) : String(a);\r\n global.console = {\r\n log: (...args) => __logRef.applySync(undefined, args.map(__stringify)),\r\n error: (...args) => __errorRef.applySync(undefined, args.map(__stringify)),\r\n warn: (...args) => __warnRef.applySync(undefined, args.map(__stringify)),\r\n info: (...args) => __infoRef.applySync(undefined, args.map(__stringify))\r\n };\r\n `);\r\n await consoleSetupScript.run(context);\r\n }\r\n\r\n /**\r\n * Sets up tool bridge functions in the isolated context.\r\n * Tool calls in the isolate are forwarded to the main process for execution.\r\n */\r\n private async setupToolBridges(\r\n isolate: ivm.Isolate,\r\n context: ivm.Context,\r\n jail: ivm.Reference<Record<string | number | symbol, unknown>>,\r\n tools: Tool[]\r\n ): Promise<void> {\r\n // Create a reference for the tool caller in main process\r\n const toolCallerRef = new ivm.Reference(async (toolName: string, argsJson: string) => {\r\n try {\r\n const args = JSON.parse(argsJson);\r\n const result = await this.callTool(toolName, args);\r\n return JSON.stringify({ success: true, result });\r\n } catch (error) {\r\n return JSON.stringify({ \r\n success: false, \r\n error: error instanceof Error ? error.message : String(error) \r\n });\r\n }\r\n });\r\n \r\n await jail.set('__callToolRef', toolCallerRef);\r\n \r\n // Build tool namespace setup code\r\n const toolSetupParts: string[] = [];\r\n const namespaces = new Set<string>();\r\n \r\n for (const tool of tools) {\r\n if (tool.name.includes('.')) {\r\n const [manualName, ...toolParts] = tool.name.split('.');\r\n const sanitizedManualName = this.sanitizeIdentifier(manualName);\r\n const toolFnName = toolParts.map(part => this.sanitizeIdentifier(part)).join('_');\r\n \r\n if (!namespaces.has(sanitizedManualName)) {\r\n namespaces.add(sanitizedManualName);\r\n toolSetupParts.push(`global.${sanitizedManualName} = global.${sanitizedManualName} || {};`);\r\n }\r\n \r\n toolSetupParts.push(`\r\n global.${sanitizedManualName}.${toolFnName} = function(args) {\r\n // applySyncPromise blocks until async tool call completes in main process\r\n var resultJson = __callToolRef.applySyncPromise(undefined, [${JSON.stringify(tool.name)}, JSON.stringify(args || {})]);\r\n var parsed = JSON.parse(resultJson);\r\n if (!parsed.success) throw new Error(parsed.error);\r\n return parsed.result;\r\n };\r\n `);\r\n } else {\r\n const sanitizedToolName = this.sanitizeIdentifier(tool.name);\r\n toolSetupParts.push(`\r\n global.${sanitizedToolName} = function(args) {\r\n // applySyncPromise blocks until async tool call completes in main process\r\n var resultJson = __callToolRef.applySyncPromise(undefined, [${JSON.stringify(tool.name)}, JSON.stringify(args || {})]);\r\n var parsed = JSON.parse(resultJson);\r\n if (!parsed.success) throw new Error(parsed.error);\r\n return parsed.result;\r\n };\r\n `);\r\n }\r\n }\r\n \r\n // Execute tool setup in isolate\r\n const toolSetupScript = await isolate.compileScript(toolSetupParts.join('\\n'));\r\n await toolSetupScript.run(context);\r\n }\r\n\r\n /**\r\n * Sets up utility functions and interfaces in the isolated context.\r\n */\r\n private async setupUtilities(\r\n isolate: ivm.Isolate,\r\n context: ivm.Context,\r\n jail: ivm.Reference<Record<string | number | symbol, unknown>>,\r\n tools: Tool[]\r\n ): Promise<void> {\r\n // Add TypeScript interface definitions\r\n const interfaces = await this.getAllToolsTypeScriptInterfaces();\r\n await jail.set('__interfaces', interfaces);\r\n \r\n // Create interface lookup map\r\n const interfaceMap: Record<string, string> = {};\r\n for (const tool of tools) {\r\n interfaceMap[tool.name] = this.toolToTypeScriptInterface(tool);\r\n }\r\n await jail.set('__interfaceMapJson', JSON.stringify(interfaceMap));\r\n \r\n // Execute utility setup in isolate\r\n const utilSetupScript = await isolate.compileScript(`\r\n global.__getToolInterface = (toolName) => {\r\n const map = JSON.parse(__interfaceMapJson);\r\n return map[toolName] || null;\r\n };\r\n `);\r\n await utilSetupScript.run(context);\r\n }\r\n\r\n /**\r\n * Converts a JSON Schema to TypeScript object content (properties only, no interface wrapper).\r\n * This generates the content inside an interface definition.\r\n * \r\n * @param schema JSON Schema to convert\r\n * @returns TypeScript interface properties as string\r\n */\r\n private jsonSchemaToObjectContent(schema: JsonSchema): string {\r\n if (!schema || typeof schema !== 'object' || schema.type !== 'object') {\r\n return ' [key: string]: any;';\r\n }\r\n\r\n const properties = schema.properties || {};\r\n const required = schema.required || [];\r\n const lines: string[] = [];\r\n\r\n for (const [propName, propSchema] of Object.entries(properties)) {\r\n const isRequired = required.includes(propName);\r\n const optionalMarker = isRequired ? '' : '?';\r\n const description = (propSchema as any).description || '';\r\n const tsType = this.jsonSchemaToTypeScriptType(propSchema as JsonSchema);\r\n\r\n if (description) {\r\n lines.push(` /** ${this.escapeComment(description)} */`);\r\n }\r\n lines.push(` ${propName}${optionalMarker}: ${tsType};`);\r\n }\r\n\r\n return lines.length > 0 ? lines.join('\\n') : ' [key: string]: any;';\r\n }\r\n\r\n /**\r\n * Converts a JSON Schema to TypeScript interface definition.\r\n * This handles the most common JSON Schema patterns used in UTCP tools.\r\n * \r\n * @param schema JSON Schema to convert\r\n * @param typeName Name for the generated TypeScript type\r\n * @returns TypeScript type definition as string\r\n */\r\n private jsonSchemaToTypeScript(schema: JsonSchema, typeName: string): string {\r\n if (!schema || typeof schema !== 'object') {\r\n return `type ${typeName} = any;`;\r\n }\r\n\r\n // Handle different schema types\r\n switch (schema.type) {\r\n case 'object':\r\n return this.objectSchemaToTypeScript(schema, typeName);\r\n case 'array':\r\n return this.arraySchemaToTypeScript(schema, typeName);\r\n case 'string':\r\n return this.primitiveSchemaToTypeScript(schema, typeName, 'string');\r\n case 'number':\r\n case 'integer':\r\n return this.primitiveSchemaToTypeScript(schema, typeName, 'number');\r\n case 'boolean':\r\n return this.primitiveSchemaToTypeScript(schema, typeName, 'boolean');\r\n case 'null':\r\n return `type ${typeName} = null;`;\r\n default:\r\n // Handle union types or fallback to any\r\n if (Array.isArray(schema.type)) {\r\n const types = schema.type.map(t => this.mapJsonTypeToTS(t)).join(' | ');\r\n return `type ${typeName} = ${types};`;\r\n }\r\n return `type ${typeName} = any;`;\r\n }\r\n }\r\n\r\n /**\r\n * Converts an object JSON Schema to TypeScript interface.\r\n */\r\n private objectSchemaToTypeScript(schema: JsonSchema, typeName: string): string {\r\n if (!schema.properties) {\r\n return `interface ${typeName} {\r\n [key: string]: any;\r\n}`;\r\n }\r\n\r\n const properties = Object.entries(schema.properties).map(([key, propSchema]) => {\r\n const isRequired = schema.required?.includes(key) ?? false;\r\n const optional = isRequired ? '' : '?';\r\n const propType = this.jsonSchemaToTypeScriptType(propSchema);\r\n const description = propSchema.description ? ` /** ${this.escapeComment(propSchema.description)} */\\n` : '';\r\n \r\n return `${description} ${key}${optional}: ${propType};`;\r\n }).join('\\n');\r\n\r\n return `interface ${typeName} {\r\n${properties}\r\n}`;\r\n }\r\n\r\n /**\r\n * Converts an array JSON Schema to TypeScript type.\r\n */\r\n private arraySchemaToTypeScript(schema: JsonSchema, typeName: string): string {\r\n if (!schema.items) {\r\n return `type ${typeName} = any[];`;\r\n }\r\n\r\n const itemType = Array.isArray(schema.items) \r\n ? schema.items.map(item => this.jsonSchemaToTypeScriptType(item)).join(' | ')\r\n : this.jsonSchemaToTypeScriptType(schema.items);\r\n\r\n return `type ${typeName} = (${itemType})[];`;\r\n }\r\n\r\n /**\r\n * Converts a primitive JSON Schema to TypeScript type with enum support.\r\n */\r\n private primitiveSchemaToTypeScript(schema: JsonSchema, typeName: string, baseType: string): string {\r\n if (schema.enum) {\r\n const enumValues = schema.enum.map(val => \r\n typeof val === 'string' ? JSON.stringify(val) : String(val)\r\n ).join(' | ');\r\n return `type ${typeName} = ${enumValues};`;\r\n }\r\n\r\n return `type ${typeName} = ${baseType};`;\r\n }\r\n\r\n /**\r\n * Converts a JSON Schema to a TypeScript type (not a full type definition).\r\n */\r\n private jsonSchemaToTypeScriptType(schema: JsonSchema): string {\r\n if (!schema || typeof schema !== 'object') {\r\n return 'any';\r\n }\r\n\r\n if (schema.enum) {\r\n return schema.enum.map(val => \r\n typeof val === 'string' ? JSON.stringify(val) : String(val)\r\n ).join(' | ');\r\n }\r\n\r\n switch (schema.type) {\r\n case 'object':\r\n if (!schema.properties) return '{ [key: string]: any }';\r\n const props = Object.entries(schema.properties).map(([key, propSchema]) => {\r\n const isRequired = schema.required?.includes(key) ?? false;\r\n const optional = isRequired ? '' : '?';\r\n const propType = this.jsonSchemaToTypeScriptType(propSchema);\r\n return `${key}${optional}: ${propType}`;\r\n }).join('; ');\r\n return `{ ${props} }`;\r\n \r\n case 'array':\r\n if (!schema.items) return 'any[]';\r\n const itemType = Array.isArray(schema.items)\r\n ? schema.items.map(item => this.jsonSchemaToTypeScriptType(item)).join(' | ')\r\n : this.jsonSchemaToTypeScriptType(schema.items);\r\n return `(${itemType})[]`;\r\n \r\n case 'string':\r\n return 'string';\r\n case 'number':\r\n case 'integer':\r\n return 'number';\r\n case 'boolean':\r\n return 'boolean';\r\n case 'null':\r\n return 'null';\r\n \r\n default:\r\n if (Array.isArray(schema.type)) {\r\n return schema.type.map(t => this.mapJsonTypeToTS(t)).join(' | ');\r\n }\r\n return 'any';\r\n }\r\n }\r\n\r\n /**\r\n * Escapes a string for safe use in JSDoc comments.\r\n * Prevents comment injection via star-slash sequences.\r\n */\r\n private escapeComment(text: string): string {\r\n return text.replace(/\\*\\//g, '*\\\\/').replace(/\\n/g, ' ');\r\n }\r\n\r\n /**\r\n * Maps basic JSON Schema types to TypeScript types.\r\n */\r\n private mapJsonTypeToTS(type: string): string {\r\n switch (type) {\r\n case 'string': return 'string';\r\n case 'number':\r\n case 'integer': return 'number';\r\n case 'boolean': return 'boolean';\r\n case 'null': return 'null';\r\n case 'object': return 'object';\r\n case 'array': return 'any[]';\r\n default: return 'any';\r\n }\r\n }\r\n}\r\n"],"mappings":";AAAA,SAAS,YAAgD,8BAA8B;AACvF,OAAO,SAAS;AAMT,IAAM,qBAAN,MAAM,4BAA2B,WAAW;AAAA,EACzC,oBAAyC,oBAAI,IAAI;AAAA;AAAA;AA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AAAA;AAAA;AAAA;AAAA,EAMQ,cAAc,MAAsB;AAC1C,WAAO,KAAK,QAAQ,SAAS,MAAM,EAAE,QAAQ,OAAO,GAAG;AAAA,EACzD;AAAA;AAAA;AAAA;AAAA,EAKQ,gBAAgB,MAAsB;AAC5C,YAAQ,MAAM;AAAA,MACZ,KAAK;AAAU,eAAO;AAAA,MACtB,KAAK;AAAA,MACL,KAAK;AAAW,eAAO;AAAA,MACvB,KAAK;AAAW,eAAO;AAAA,MACvB,KAAK;AAAQ,eAAO;AAAA,MACpB,KAAK;AAAU,eAAO;AAAA,MACtB,KAAK;AAAS,eAAO;AAAA,MACrB;AAAS,eAAO;AAAA,IAClB;AAAA,EACF;AACF;","names":[]} |
+8
-3
| { | ||
| "name": "@utcp/code-mode", | ||
| "version": "1.2.6", | ||
| "version": "1.2.7", | ||
| "description": "Code execution mode for UTCP - enables executing TypeScript code chains with tool access using isolated-vm for security", | ||
| "main": "dist/index.js", | ||
| "type": "module", | ||
| "main": "dist/index.cjs", | ||
| "module": "dist/index.js", | ||
| "types": "dist/index.d.ts", | ||
@@ -28,3 +30,3 @@ "license": "MPL-2.0", | ||
| "scripts": { | ||
| "build": "tsc", | ||
| "build": "tsup", | ||
| "test": "jest", | ||
@@ -40,2 +42,3 @@ "prepublishOnly": "npm run build" | ||
| "import": "./dist/index.js", | ||
| "require": "./dist/index.cjs", | ||
| "default": "./dist/index.js" | ||
@@ -59,4 +62,6 @@ } | ||
| "@utcp/direct-call": "^1.1.0", | ||
| "isolated-vm": "^5.0.1", | ||
| "jest": "^29.7.0", | ||
| "ts-jest": "^29.1.2", | ||
| "tsup": "^8.5.0", | ||
| "typescript": "^5.0.0" | ||
@@ -63,0 +68,0 @@ }, |
| import { UtcpClient, Tool, UtcpClientConfig } from '@utcp/sdk'; | ||
| /** | ||
| * CodeModeUtcpClient extends UtcpClient to provide TypeScript code execution capabilities. | ||
| * This allows executing TypeScript code that can directly call registered tools as functions. | ||
| */ | ||
| export declare class CodeModeUtcpClient extends UtcpClient { | ||
| private toolFunctionCache; | ||
| /** | ||
| * Standard prompt template for AI agents using CodeModeUtcpClient. | ||
| * This provides guidance on how to properly discover and use tools within code execution. | ||
| */ | ||
| static readonly AGENT_PROMPT_TEMPLATE: string; | ||
| /** | ||
| * Creates a new CodeModeUtcpClient instance. | ||
| * This creates a regular UtcpClient and then upgrades it to a CodeModeUtcpClient | ||
| * with all the same configuration and additional code execution capabilities. | ||
| * | ||
| * @param root_dir The root directory for the client to resolve relative paths from | ||
| * @param config The configuration for the client | ||
| * @returns A new CodeModeUtcpClient instance | ||
| */ | ||
| /** | ||
| * Debug method to expose registered call template serializers from the SDK instance used by code-mode. | ||
| * Use this to verify if the SDK is shared with other plugins like @utcp/direct-call. | ||
| */ | ||
| static getRegisteredSerializers(): string[]; | ||
| static create(root_dir?: string, config?: UtcpClientConfig | null): Promise<CodeModeUtcpClient>; | ||
| /** | ||
| * Sanitizes an identifier to be a valid TypeScript identifier. | ||
| * Replaces any non-alphanumeric character (except underscore) with underscore | ||
| * and ensures the first character is not a number. | ||
| * | ||
| * @param name The name to sanitize | ||
| * @returns Sanitized identifier | ||
| */ | ||
| private sanitizeIdentifier; | ||
| /** | ||
| * Converts a Tool object into a TypeScript function interface string. | ||
| * This generates the function signature that can be used in TypeScript code. | ||
| * | ||
| * @param tool The Tool object to convert | ||
| * @returns TypeScript function interface as a string | ||
| */ | ||
| toolToTypeScriptInterface(tool: Tool): string; | ||
| /** | ||
| * Converts all registered tools to TypeScript interface definitions. | ||
| * This provides the complete type definitions for all available tools. | ||
| * | ||
| * @returns A complete TypeScript interface definition string | ||
| */ | ||
| getAllToolsTypeScriptInterfaces(): Promise<string>; | ||
| /** | ||
| * Executes TypeScript code with access to registered tools and captures console output. | ||
| * The code can call tools directly as functions and has access to standard JavaScript globals. | ||
| * Uses isolated-vm for secure sandboxed execution. | ||
| * | ||
| * @param code TypeScript code to execute | ||
| * @param timeout Optional timeout in milliseconds (default: 30000) | ||
| * @param memoryLimit Optional memory limit in MB (default: 128) | ||
| * @returns Object containing both the execution result and captured console logs | ||
| */ | ||
| callToolChain(code: string, timeout?: number, memoryLimit?: number): Promise<{ | ||
| result: any; | ||
| logs: string[]; | ||
| }>; | ||
| /** | ||
| * Sets up console bridge functions in the isolated context. | ||
| * Console calls in the isolate are forwarded to the main process for logging. | ||
| */ | ||
| private setupConsoleBridge; | ||
| /** | ||
| * Sets up tool bridge functions in the isolated context. | ||
| * Tool calls in the isolate are forwarded to the main process for execution. | ||
| */ | ||
| private setupToolBridges; | ||
| /** | ||
| * Sets up utility functions and interfaces in the isolated context. | ||
| */ | ||
| private setupUtilities; | ||
| /** | ||
| * Converts a JSON Schema to TypeScript object content (properties only, no interface wrapper). | ||
| * This generates the content inside an interface definition. | ||
| * | ||
| * @param schema JSON Schema to convert | ||
| * @returns TypeScript interface properties as string | ||
| */ | ||
| private jsonSchemaToObjectContent; | ||
| /** | ||
| * Converts a JSON Schema to TypeScript interface definition. | ||
| * This handles the most common JSON Schema patterns used in UTCP tools. | ||
| * | ||
| * @param schema JSON Schema to convert | ||
| * @param typeName Name for the generated TypeScript type | ||
| * @returns TypeScript type definition as string | ||
| */ | ||
| private jsonSchemaToTypeScript; | ||
| /** | ||
| * Converts an object JSON Schema to TypeScript interface. | ||
| */ | ||
| private objectSchemaToTypeScript; | ||
| /** | ||
| * Converts an array JSON Schema to TypeScript type. | ||
| */ | ||
| private arraySchemaToTypeScript; | ||
| /** | ||
| * Converts a primitive JSON Schema to TypeScript type with enum support. | ||
| */ | ||
| private primitiveSchemaToTypeScript; | ||
| /** | ||
| * Converts a JSON Schema to a TypeScript type (not a full type definition). | ||
| */ | ||
| private jsonSchemaToTypeScriptType; | ||
| /** | ||
| * Escapes a string for safe use in JSDoc comments. | ||
| * Prevents comment injection via star-slash sequences. | ||
| */ | ||
| private escapeComment; | ||
| /** | ||
| * Maps basic JSON Schema types to TypeScript types. | ||
| */ | ||
| private mapJsonTypeToTS; | ||
| } | ||
| //# sourceMappingURL=code_mode_utcp_client.d.ts.map |
| {"version":3,"file":"code_mode_utcp_client.d.ts","sourceRoot":"","sources":["../src/code_mode_utcp_client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,IAAI,EAAc,gBAAgB,EAA0B,MAAM,WAAW,CAAC;AAGnG;;;GAGG;AACH,qBAAa,kBAAmB,SAAQ,UAAU;IAChD,OAAO,CAAC,iBAAiB,CAAkC;IAE3D;;;OAGG;IACH,gBAAuB,qBAAqB,SA2CrC;IAEP;;;;;;;;OAQG;IACH;;;OAGG;WACW,wBAAwB,IAAI,MAAM,EAAE;WAM9B,MAAM,CACxB,QAAQ,GAAE,MAAsB,EAChC,MAAM,GAAE,gBAAgB,GAAG,IAAW,GACrC,OAAO,CAAC,kBAAkB,CAAC;IAiB9B;;;;;;;OAOG;IACH,OAAO,CAAC,kBAAkB;IAM1B;;;;;;OAMG;IACI,yBAAyB,CAAC,IAAI,EAAE,IAAI,GAAG,MAAM;IAkDpD;;;;;OAKG;IACU,+BAA+B,IAAI,OAAO,CAAC,MAAM,CAAC;IAQ/D;;;;;;;;;OASG;IACU,aAAa,CACxB,IAAI,EAAE,MAAM,EACZ,OAAO,GAAE,MAAc,EACvB,WAAW,GAAE,MAAY,GACxB,OAAO,CAAC;QAAC,MAAM,EAAE,GAAG,CAAC;QAAC,IAAI,EAAE,MAAM,EAAE,CAAA;KAAC,CAAC;IAsDzC;;;OAGG;YACW,kBAAkB;IAiChC;;;OAGG;YACW,gBAAgB;IAiE9B;;OAEG;YACW,cAAc;IA2B5B;;;;;;OAMG;IACH,OAAO,CAAC,yBAAyB;IAwBjC;;;;;;;OAOG;IACH,OAAO,CAAC,sBAAsB;IA8B9B;;OAEG;IACH,OAAO,CAAC,wBAAwB;IAqBhC;;OAEG;IACH,OAAO,CAAC,uBAAuB;IAY/B;;OAEG;IACH,OAAO,CAAC,2BAA2B;IAWnC;;OAEG;IACH,OAAO,CAAC,0BAA0B;IA+ClC;;;OAGG;IACH,OAAO,CAAC,aAAa;IAIrB;;OAEG;IACH,OAAO,CAAC,eAAe;CAYxB"} |
| "use strict"; | ||
| var __importDefault = (this && this.__importDefault) || function (mod) { | ||
| return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
| }; | ||
| Object.defineProperty(exports, "__esModule", { value: true }); | ||
| exports.CodeModeUtcpClient = void 0; | ||
| const sdk_1 = require("@utcp/sdk"); | ||
| const isolated_vm_1 = __importDefault(require("isolated-vm")); | ||
| /** | ||
| * CodeModeUtcpClient extends UtcpClient to provide TypeScript code execution capabilities. | ||
| * This allows executing TypeScript code that can directly call registered tools as functions. | ||
| */ | ||
| class CodeModeUtcpClient extends sdk_1.UtcpClient { | ||
| toolFunctionCache = new Map(); | ||
| /** | ||
| * Standard prompt template for AI agents using CodeModeUtcpClient. | ||
| * This provides guidance on how to properly discover and use tools within code execution. | ||
| */ | ||
| static AGENT_PROMPT_TEMPLATE = ` | ||
| ## UTCP CodeMode Tool Usage Guide | ||
| You have access to a CodeModeUtcpClient that allows you to execute TypeScript code with access to registered tools. Follow this workflow: | ||
| ### 1. Tool Discovery Phase | ||
| **Always start by discovering available tools:** | ||
| - Tools are organized by manual namespace (e.g., \`manual_name.tool_name\`) | ||
| - Use hierarchical access patterns: \`manual.tool({ param: value })\` (synchronous, no await) | ||
| - Multiple manuals can contain tools with the same name - namespaces prevent conflicts | ||
| ### 2. Interface Introspection | ||
| **Understand tool contracts before using them:** | ||
| - Access \`__interfaces\` to see all available TypeScript interface definitions | ||
| - Use \`__getToolInterface('manual.tool')\` to get specific tool interfaces | ||
| - Interfaces show required inputs, expected outputs, and descriptions | ||
| - Look for "Access as: manual.tool(args)" comments for usage patterns | ||
| ### 3. Code Execution Guidelines | ||
| **When writing code for \`callToolChain\`:** | ||
| - Use \`manual.tool({ param: value })\` syntax for all tool calls (synchronous, no await needed) | ||
| - Tools are synchronous functions - the main process handles async operations internally | ||
| - You have access to standard JavaScript globals: \`console\`, \`JSON\`, \`Math\`, \`Date\`, etc. | ||
| - All console output (\`console.log\`, \`console.error\`, etc.) is automatically captured and returned | ||
| - Build properly structured input objects based on interface definitions | ||
| - Handle errors appropriately with try/catch blocks | ||
| - Chain tool calls by using results from previous calls | ||
| - Use \`return\` to return the final result from your code | ||
| ### 4. Best Practices | ||
| - **Discover first, code second**: Always explore available tools before writing execution code | ||
| - **Respect namespaces**: Use full \`manual.tool\` names to avoid conflicts | ||
| - **Parse interfaces**: Use interface information to construct proper input objects | ||
| - **Error handling**: Wrap tool calls in try/catch for robustness | ||
| - **Data flow**: Chain tools by passing outputs as inputs to subsequent tools | ||
| ### 5. Available Runtime Context | ||
| - \`__interfaces\`: String containing all TypeScript interface definitions | ||
| - \`__getToolInterface(toolName)\`: Function to get specific tool interface | ||
| - All registered tools as \`manual.tool\` functions | ||
| - Standard JavaScript built-ins for data processing | ||
| Remember: Always discover and understand available tools before attempting to use them in code execution. | ||
| `.trim(); | ||
| /** | ||
| * Creates a new CodeModeUtcpClient instance. | ||
| * This creates a regular UtcpClient and then upgrades it to a CodeModeUtcpClient | ||
| * with all the same configuration and additional code execution capabilities. | ||
| * | ||
| * @param root_dir The root directory for the client to resolve relative paths from | ||
| * @param config The configuration for the client | ||
| * @returns A new CodeModeUtcpClient instance | ||
| */ | ||
| /** | ||
| * Debug method to expose registered call template serializers from the SDK instance used by code-mode. | ||
| * Use this to verify if the SDK is shared with other plugins like @utcp/direct-call. | ||
| */ | ||
| static getRegisteredSerializers() { | ||
| // Access the static serializers map | ||
| const serializerClass = sdk_1.CallTemplateSerializer; | ||
| return Object.keys(serializerClass.serializers || {}); | ||
| } | ||
| static async create(root_dir = process.cwd(), config = null) { | ||
| // Debug: log registered serializers at creation time | ||
| console.log('[CodeModeUtcpClient] Registered serializers at create():', CodeModeUtcpClient.getRegisteredSerializers()); | ||
| // Create a regular UtcpClient first | ||
| const baseClient = await sdk_1.UtcpClient.create(root_dir, config); | ||
| // Create a CodeModeUtcpClient using the same configuration | ||
| const codeModeClient = Object.setPrototypeOf(baseClient, CodeModeUtcpClient.prototype); | ||
| // Initialize the cache | ||
| codeModeClient.toolFunctionCache = new Map(); | ||
| return codeModeClient; | ||
| } | ||
| /** | ||
| * Sanitizes an identifier to be a valid TypeScript identifier. | ||
| * Replaces any non-alphanumeric character (except underscore) with underscore | ||
| * and ensures the first character is not a number. | ||
| * | ||
| * @param name The name to sanitize | ||
| * @returns Sanitized identifier | ||
| */ | ||
| sanitizeIdentifier(name) { | ||
| return name | ||
| .replace(/[^a-zA-Z0-9_]/g, '_') | ||
| .replace(/^[0-9]/, '_$&'); | ||
| } | ||
| /** | ||
| * Converts a Tool object into a TypeScript function interface string. | ||
| * This generates the function signature that can be used in TypeScript code. | ||
| * | ||
| * @param tool The Tool object to convert | ||
| * @returns TypeScript function interface as a string | ||
| */ | ||
| toolToTypeScriptInterface(tool) { | ||
| if (this.toolFunctionCache.has(tool.name)) { | ||
| return this.toolFunctionCache.get(tool.name); | ||
| } | ||
| // Generate hierarchical interface structure | ||
| let interfaceContent; | ||
| let accessPattern; | ||
| if (tool.name.includes('.')) { | ||
| const [manualName, ...toolParts] = tool.name.split('.'); | ||
| const sanitizedManualName = this.sanitizeIdentifier(manualName); | ||
| const toolName = toolParts.map(part => this.sanitizeIdentifier(part)).join('_'); | ||
| accessPattern = `${sanitizedManualName}.${toolName}`; | ||
| // Generate interfaces within namespace | ||
| const inputInterfaceContent = this.jsonSchemaToObjectContent(tool.inputs); | ||
| const outputInterfaceContent = this.jsonSchemaToObjectContent(tool.outputs); | ||
| interfaceContent = ` | ||
| namespace ${sanitizedManualName} { | ||
| interface ${toolName}Input { | ||
| ${inputInterfaceContent} | ||
| } | ||
| interface ${toolName}Output { | ||
| ${outputInterfaceContent} | ||
| } | ||
| }`; | ||
| } | ||
| else { | ||
| // No manual namespace, generate flat interfaces | ||
| const sanitizedToolName = this.sanitizeIdentifier(tool.name); | ||
| accessPattern = sanitizedToolName; | ||
| const inputType = this.jsonSchemaToTypeScript(tool.inputs, `${sanitizedToolName}Input`); | ||
| const outputType = this.jsonSchemaToTypeScript(tool.outputs, `${sanitizedToolName}Output`); | ||
| interfaceContent = `${inputType}\n\n${outputType}`; | ||
| } | ||
| const interfaceString = ` | ||
| ${interfaceContent} | ||
| /** | ||
| * ${this.escapeComment(tool.description)} | ||
| * Tags: ${this.escapeComment(tool.tags.join(', '))} | ||
| * Access as: ${accessPattern}(args) | ||
| */`; | ||
| this.toolFunctionCache.set(tool.name, interfaceString); | ||
| return interfaceString; | ||
| } | ||
| /** | ||
| * Converts all registered tools to TypeScript interface definitions. | ||
| * This provides the complete type definitions for all available tools. | ||
| * | ||
| * @returns A complete TypeScript interface definition string | ||
| */ | ||
| async getAllToolsTypeScriptInterfaces() { | ||
| const tools = await this.getTools(); | ||
| const interfaces = tools.map(tool => this.toolToTypeScriptInterface(tool)); | ||
| return `// Auto-generated TypeScript interfaces for UTCP tools | ||
| ${interfaces.join('\n\n')}`; | ||
| } | ||
| /** | ||
| * Executes TypeScript code with access to registered tools and captures console output. | ||
| * The code can call tools directly as functions and has access to standard JavaScript globals. | ||
| * Uses isolated-vm for secure sandboxed execution. | ||
| * | ||
| * @param code TypeScript code to execute | ||
| * @param timeout Optional timeout in milliseconds (default: 30000) | ||
| * @param memoryLimit Optional memory limit in MB (default: 128) | ||
| * @returns Object containing both the execution result and captured console logs | ||
| */ | ||
| async callToolChain(code, timeout = 30000, memoryLimit = 128) { | ||
| const tools = await this.getTools(); | ||
| const logs = []; | ||
| // Create isolated VM | ||
| const isolate = new isolated_vm_1.default.Isolate({ memoryLimit }); | ||
| try { | ||
| const context = await isolate.createContext(); | ||
| const jail = context.global; | ||
| // Set up the jail with a reference to itself | ||
| await jail.set('global', jail.derefInto()); | ||
| // Set up console logging bridges | ||
| await this.setupConsoleBridge(isolate, context, jail, logs); | ||
| // Set up tool bridges | ||
| await this.setupToolBridges(isolate, context, jail, tools); | ||
| // Set up utility functions and interfaces | ||
| await this.setupUtilities(isolate, context, jail, tools); | ||
| // Compile and run the user code - code is SYNC since tools use applySyncPromise | ||
| // Wrap result in JSON.stringify to transfer objects out of isolate | ||
| const wrappedCode = ` | ||
| (function() { | ||
| var __result = (function() { | ||
| ${code} | ||
| })(); | ||
| return JSON.stringify({ __result: __result }); | ||
| })() | ||
| `; | ||
| const script = await isolate.compileScript(wrappedCode); | ||
| const resultJson = await script.run(context, { timeout }); | ||
| // Parse the result from JSON | ||
| const result = typeof resultJson === 'string' | ||
| ? JSON.parse(resultJson).__result | ||
| : resultJson; | ||
| return { result, logs }; | ||
| } | ||
| catch (error) { | ||
| const errorMessage = error instanceof Error ? error.message : String(error); | ||
| return { | ||
| result: null, | ||
| logs: [...logs, `[ERROR] Code execution failed: ${errorMessage}`] | ||
| }; | ||
| } | ||
| finally { | ||
| isolate.dispose(); | ||
| } | ||
| } | ||
| /** | ||
| * Sets up console bridge functions in the isolated context. | ||
| * Console calls in the isolate are forwarded to the main process for logging. | ||
| */ | ||
| async setupConsoleBridge(isolate, context, jail, logs) { | ||
| // Create log capture functions in main process | ||
| const createLogHandler = (prefix) => { | ||
| return new isolated_vm_1.default.Reference((...args) => { | ||
| const message = args.join(' '); | ||
| logs.push(prefix ? `${prefix} ${message}` : message); | ||
| }); | ||
| }; | ||
| // Set up console references in isolate | ||
| await jail.set('__logRef', createLogHandler('')); | ||
| await jail.set('__errorRef', createLogHandler('[ERROR]')); | ||
| await jail.set('__warnRef', createLogHandler('[WARN]')); | ||
| await jail.set('__infoRef', createLogHandler('[INFO]')); | ||
| // Create console object in isolate that calls the references | ||
| const consoleSetupScript = await isolate.compileScript(` | ||
| const __stringify = (a) => typeof a === 'object' && a !== null ? JSON.stringify(a, null, 2) : String(a); | ||
| global.console = { | ||
| log: (...args) => __logRef.applySync(undefined, args.map(__stringify)), | ||
| error: (...args) => __errorRef.applySync(undefined, args.map(__stringify)), | ||
| warn: (...args) => __warnRef.applySync(undefined, args.map(__stringify)), | ||
| info: (...args) => __infoRef.applySync(undefined, args.map(__stringify)) | ||
| }; | ||
| `); | ||
| await consoleSetupScript.run(context); | ||
| } | ||
| /** | ||
| * Sets up tool bridge functions in the isolated context. | ||
| * Tool calls in the isolate are forwarded to the main process for execution. | ||
| */ | ||
| async setupToolBridges(isolate, context, jail, tools) { | ||
| // Create a reference for the tool caller in main process | ||
| const toolCallerRef = new isolated_vm_1.default.Reference(async (toolName, argsJson) => { | ||
| try { | ||
| const args = JSON.parse(argsJson); | ||
| const result = await this.callTool(toolName, args); | ||
| return JSON.stringify({ success: true, result }); | ||
| } | ||
| catch (error) { | ||
| return JSON.stringify({ | ||
| success: false, | ||
| error: error instanceof Error ? error.message : String(error) | ||
| }); | ||
| } | ||
| }); | ||
| await jail.set('__callToolRef', toolCallerRef); | ||
| // Build tool namespace setup code | ||
| const toolSetupParts = []; | ||
| const namespaces = new Set(); | ||
| for (const tool of tools) { | ||
| if (tool.name.includes('.')) { | ||
| const [manualName, ...toolParts] = tool.name.split('.'); | ||
| const sanitizedManualName = this.sanitizeIdentifier(manualName); | ||
| const toolFnName = toolParts.map(part => this.sanitizeIdentifier(part)).join('_'); | ||
| if (!namespaces.has(sanitizedManualName)) { | ||
| namespaces.add(sanitizedManualName); | ||
| toolSetupParts.push(`global.${sanitizedManualName} = global.${sanitizedManualName} || {};`); | ||
| } | ||
| toolSetupParts.push(` | ||
| global.${sanitizedManualName}.${toolFnName} = function(args) { | ||
| // applySyncPromise blocks until async tool call completes in main process | ||
| var resultJson = __callToolRef.applySyncPromise(undefined, [${JSON.stringify(tool.name)}, JSON.stringify(args || {})]); | ||
| var parsed = JSON.parse(resultJson); | ||
| if (!parsed.success) throw new Error(parsed.error); | ||
| return parsed.result; | ||
| }; | ||
| `); | ||
| } | ||
| else { | ||
| const sanitizedToolName = this.sanitizeIdentifier(tool.name); | ||
| toolSetupParts.push(` | ||
| global.${sanitizedToolName} = function(args) { | ||
| // applySyncPromise blocks until async tool call completes in main process | ||
| var resultJson = __callToolRef.applySyncPromise(undefined, [${JSON.stringify(tool.name)}, JSON.stringify(args || {})]); | ||
| var parsed = JSON.parse(resultJson); | ||
| if (!parsed.success) throw new Error(parsed.error); | ||
| return parsed.result; | ||
| }; | ||
| `); | ||
| } | ||
| } | ||
| // Execute tool setup in isolate | ||
| const toolSetupScript = await isolate.compileScript(toolSetupParts.join('\n')); | ||
| await toolSetupScript.run(context); | ||
| } | ||
| /** | ||
| * Sets up utility functions and interfaces in the isolated context. | ||
| */ | ||
| async setupUtilities(isolate, context, jail, tools) { | ||
| // Add TypeScript interface definitions | ||
| const interfaces = await this.getAllToolsTypeScriptInterfaces(); | ||
| await jail.set('__interfaces', interfaces); | ||
| // Create interface lookup map | ||
| const interfaceMap = {}; | ||
| for (const tool of tools) { | ||
| interfaceMap[tool.name] = this.toolToTypeScriptInterface(tool); | ||
| } | ||
| await jail.set('__interfaceMapJson', JSON.stringify(interfaceMap)); | ||
| // Execute utility setup in isolate | ||
| const utilSetupScript = await isolate.compileScript(` | ||
| global.__getToolInterface = (toolName) => { | ||
| const map = JSON.parse(__interfaceMapJson); | ||
| return map[toolName] || null; | ||
| }; | ||
| `); | ||
| await utilSetupScript.run(context); | ||
| } | ||
| /** | ||
| * Converts a JSON Schema to TypeScript object content (properties only, no interface wrapper). | ||
| * This generates the content inside an interface definition. | ||
| * | ||
| * @param schema JSON Schema to convert | ||
| * @returns TypeScript interface properties as string | ||
| */ | ||
| jsonSchemaToObjectContent(schema) { | ||
| if (!schema || typeof schema !== 'object' || schema.type !== 'object') { | ||
| return ' [key: string]: any;'; | ||
| } | ||
| const properties = schema.properties || {}; | ||
| const required = schema.required || []; | ||
| const lines = []; | ||
| for (const [propName, propSchema] of Object.entries(properties)) { | ||
| const isRequired = required.includes(propName); | ||
| const optionalMarker = isRequired ? '' : '?'; | ||
| const description = propSchema.description || ''; | ||
| const tsType = this.jsonSchemaToTypeScriptType(propSchema); | ||
| if (description) { | ||
| lines.push(` /** ${this.escapeComment(description)} */`); | ||
| } | ||
| lines.push(` ${propName}${optionalMarker}: ${tsType};`); | ||
| } | ||
| return lines.length > 0 ? lines.join('\n') : ' [key: string]: any;'; | ||
| } | ||
| /** | ||
| * Converts a JSON Schema to TypeScript interface definition. | ||
| * This handles the most common JSON Schema patterns used in UTCP tools. | ||
| * | ||
| * @param schema JSON Schema to convert | ||
| * @param typeName Name for the generated TypeScript type | ||
| * @returns TypeScript type definition as string | ||
| */ | ||
| jsonSchemaToTypeScript(schema, typeName) { | ||
| if (!schema || typeof schema !== 'object') { | ||
| return `type ${typeName} = any;`; | ||
| } | ||
| // Handle different schema types | ||
| switch (schema.type) { | ||
| case 'object': | ||
| return this.objectSchemaToTypeScript(schema, typeName); | ||
| case 'array': | ||
| return this.arraySchemaToTypeScript(schema, typeName); | ||
| case 'string': | ||
| return this.primitiveSchemaToTypeScript(schema, typeName, 'string'); | ||
| case 'number': | ||
| case 'integer': | ||
| return this.primitiveSchemaToTypeScript(schema, typeName, 'number'); | ||
| case 'boolean': | ||
| return this.primitiveSchemaToTypeScript(schema, typeName, 'boolean'); | ||
| case 'null': | ||
| return `type ${typeName} = null;`; | ||
| default: | ||
| // Handle union types or fallback to any | ||
| if (Array.isArray(schema.type)) { | ||
| const types = schema.type.map(t => this.mapJsonTypeToTS(t)).join(' | '); | ||
| return `type ${typeName} = ${types};`; | ||
| } | ||
| return `type ${typeName} = any;`; | ||
| } | ||
| } | ||
| /** | ||
| * Converts an object JSON Schema to TypeScript interface. | ||
| */ | ||
| objectSchemaToTypeScript(schema, typeName) { | ||
| if (!schema.properties) { | ||
| return `interface ${typeName} { | ||
| [key: string]: any; | ||
| }`; | ||
| } | ||
| const properties = Object.entries(schema.properties).map(([key, propSchema]) => { | ||
| const isRequired = schema.required?.includes(key) ?? false; | ||
| const optional = isRequired ? '' : '?'; | ||
| const propType = this.jsonSchemaToTypeScriptType(propSchema); | ||
| const description = propSchema.description ? ` /** ${this.escapeComment(propSchema.description)} */\n` : ''; | ||
| return `${description} ${key}${optional}: ${propType};`; | ||
| }).join('\n'); | ||
| return `interface ${typeName} { | ||
| ${properties} | ||
| }`; | ||
| } | ||
| /** | ||
| * Converts an array JSON Schema to TypeScript type. | ||
| */ | ||
| arraySchemaToTypeScript(schema, typeName) { | ||
| if (!schema.items) { | ||
| return `type ${typeName} = any[];`; | ||
| } | ||
| const itemType = Array.isArray(schema.items) | ||
| ? schema.items.map(item => this.jsonSchemaToTypeScriptType(item)).join(' | ') | ||
| : this.jsonSchemaToTypeScriptType(schema.items); | ||
| return `type ${typeName} = (${itemType})[];`; | ||
| } | ||
| /** | ||
| * Converts a primitive JSON Schema to TypeScript type with enum support. | ||
| */ | ||
| primitiveSchemaToTypeScript(schema, typeName, baseType) { | ||
| if (schema.enum) { | ||
| const enumValues = schema.enum.map(val => typeof val === 'string' ? JSON.stringify(val) : String(val)).join(' | '); | ||
| return `type ${typeName} = ${enumValues};`; | ||
| } | ||
| return `type ${typeName} = ${baseType};`; | ||
| } | ||
| /** | ||
| * Converts a JSON Schema to a TypeScript type (not a full type definition). | ||
| */ | ||
| jsonSchemaToTypeScriptType(schema) { | ||
| if (!schema || typeof schema !== 'object') { | ||
| return 'any'; | ||
| } | ||
| if (schema.enum) { | ||
| return schema.enum.map(val => typeof val === 'string' ? JSON.stringify(val) : String(val)).join(' | '); | ||
| } | ||
| switch (schema.type) { | ||
| case 'object': | ||
| if (!schema.properties) | ||
| return '{ [key: string]: any }'; | ||
| const props = Object.entries(schema.properties).map(([key, propSchema]) => { | ||
| const isRequired = schema.required?.includes(key) ?? false; | ||
| const optional = isRequired ? '' : '?'; | ||
| const propType = this.jsonSchemaToTypeScriptType(propSchema); | ||
| return `${key}${optional}: ${propType}`; | ||
| }).join('; '); | ||
| return `{ ${props} }`; | ||
| case 'array': | ||
| if (!schema.items) | ||
| return 'any[]'; | ||
| const itemType = Array.isArray(schema.items) | ||
| ? schema.items.map(item => this.jsonSchemaToTypeScriptType(item)).join(' | ') | ||
| : this.jsonSchemaToTypeScriptType(schema.items); | ||
| return `(${itemType})[]`; | ||
| case 'string': | ||
| return 'string'; | ||
| case 'number': | ||
| case 'integer': | ||
| return 'number'; | ||
| case 'boolean': | ||
| return 'boolean'; | ||
| case 'null': | ||
| return 'null'; | ||
| default: | ||
| if (Array.isArray(schema.type)) { | ||
| return schema.type.map(t => this.mapJsonTypeToTS(t)).join(' | '); | ||
| } | ||
| return 'any'; | ||
| } | ||
| } | ||
| /** | ||
| * Escapes a string for safe use in JSDoc comments. | ||
| * Prevents comment injection via star-slash sequences. | ||
| */ | ||
| escapeComment(text) { | ||
| return text.replace(/\*\//g, '*\\/').replace(/\n/g, ' '); | ||
| } | ||
| /** | ||
| * Maps basic JSON Schema types to TypeScript types. | ||
| */ | ||
| mapJsonTypeToTS(type) { | ||
| switch (type) { | ||
| case 'string': return 'string'; | ||
| case 'number': | ||
| case 'integer': return 'number'; | ||
| case 'boolean': return 'boolean'; | ||
| case 'null': return 'null'; | ||
| case 'object': return 'object'; | ||
| case 'array': return 'any[]'; | ||
| default: return 'any'; | ||
| } | ||
| } | ||
| } | ||
| exports.CodeModeUtcpClient = CodeModeUtcpClient; | ||
| //# sourceMappingURL=code_mode_utcp_client.js.map |
| {"version":3,"file":"code_mode_utcp_client.js","sourceRoot":"","sources":["../src/code_mode_utcp_client.ts"],"names":[],"mappings":";;;;;;AAAA,mCAAmG;AACnG,8DAA8B;AAE9B;;;GAGG;AACH,MAAa,kBAAmB,SAAQ,gBAAU;IACxC,iBAAiB,GAAwB,IAAI,GAAG,EAAE,CAAC;IAE3D;;;OAGG;IACI,MAAM,CAAU,qBAAqB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2ChD,CAAC,IAAI,EAAE,CAAC;IAEP;;;;;;;;OAQG;IACH;;;OAGG;IACI,MAAM,CAAC,wBAAwB;QACpC,oCAAoC;QACpC,MAAM,eAAe,GAAG,4BAA6B,CAAC;QACtD,OAAO,MAAM,CAAC,IAAI,CAAC,eAAe,CAAC,WAAW,IAAI,EAAE,CAAC,CAAC;IACxD,CAAC;I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C,CAAC,OAAO,QAAQ,CAAC;YAC/B,KAAK,QAAQ,CAAC;YACd,KAAK,SAAS,CAAC,CAAC,OAAO,QAAQ,CAAC;YAChC,KAAK,SAAS,CAAC,CAAC,OAAO,SAAS,CAAC;YACjC,KAAK,MAAM,CAAC,CAAC,OAAO,MAAM,CAAC;YAC3B,KAAK,QAAQ,CAAC,CAAC,OAAO,QAAQ,CAAC;YAC/B,KAAK,OAAO,CAAC,CAAC,OAAO,OAAO,CAAC;YAC7B,OAAO,CAAC,CAAC,OAAO,KAAK,CAAC;QACxB,CAAC;IACH,CAAC;;AA9jBH,gDA+jBC"} |
| {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC"} |
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
Long strings
Supply chain riskContains long string literals, which may be a sign of obfuscated or packed code.
Found 1 instance in 1 package
Long strings
Supply chain riskContains long string literals, which may be a sign of obfuscated or packed code.
Found 1 instance in 1 package
117302
163.66%1084
73.72%Yes
NaN9
28.57%7
-22.22%2
100%1
Infinity%