New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

@utcp/code-mode

Package Overview
Dependencies
Maintainers
1
Versions
18
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@utcp/code-mode - npm Package Compare versions

Comparing version
1.2.10
to
1.2.11
+5
-1
dist/index.cjs

@@ -258,5 +258,9 @@ "use strict";

} catch (error) {
let errorMsg = error instanceof Error ? error.message : String(error);
if (error.response?.data) {
errorMsg += ` Error data: ${JSON.stringify(error.response.data)}`;
}
return JSON.stringify({
success: false,
error: error instanceof Error ? error.message : String(error)
error: errorMsg
});

@@ -263,0 +267,0 @@ }

+1
-1

@@ -1,1 +0,1 @@

{"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 } 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 public static async create(\r\n root_dir: string = process.cwd(),\r\n config: UtcpClientConfig | null = null\r\n ): Promise<CodeModeUtcpClient> {\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,iBAA+D;AAC/D,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;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AQ,eAAO;AAAA,MACpB,KAAK;AAAU,eAAO;AAAA,MACtB,KAAK;AAAS,eAAO;AAAA,MACrB;AAAS,eAAO;AAAA,IAClB;AAAA,EACF;AACF;","names":["ivm"]}
{"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 } 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 public static async create(\r\n root_dir: string = process.cwd(),\r\n config: UtcpClientConfig | null = null\r\n ): Promise<CodeModeUtcpClient> {\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: any) {\r\n let errorMsg: string = error instanceof Error ? error.message : String(error);\r\n // HTTP response error handling\r\n if (error.response?.data) {\r\n errorMsg += ` Error data: ${JSON.stringify(error.response.data)}`;\r\n }\r\n return JSON.stringify({ \r\n success: false, \r\n error: errorMsg\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,iBAA+D;AAC/D,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;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IAClB;AAAA,EACF;AACF;","names":["ivm"]}

@@ -222,5 +222,9 @@ // src/code_mode_utcp_client.ts

} catch (error) {
let errorMsg = error instanceof Error ? error.message : String(error);
if (error.response?.data) {
errorMsg += ` Error data: ${JSON.stringify(error.response.data)}`;
}
return JSON.stringify({
success: false,
error: error instanceof Error ? error.message : String(error)
error: errorMsg
});

@@ -227,0 +231,0 @@ }

@@ -1,1 +0,1 @@

{"version":3,"sources":["../src/code_mode_utcp_client.ts"],"sourcesContent":["import { UtcpClient, Tool, JsonSchema, UtcpClientConfig } 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 public static async create(\r\n root_dir: string = process.cwd(),\r\n config: UtcpClientConfig | null = null\r\n ): Promise<CodeModeUtcpClient> {\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,kBAAsD;AAC/D,OAAO,SAAS;AAMT,IAAM,qBAAN,MAAM,4BAA2B,WAAW;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,EAWL,aAAoB,OAClB,WAAmB,QAAQ,IAAI,GAC/B,SAAkC,MACL;AAE7B,UAAM,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E,KAAK,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":[]}
{"version":3,"sources":["../src/code_mode_utcp_client.ts"],"sourcesContent":["import { UtcpClient, Tool, JsonSchema, UtcpClientConfig } 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 public static async create(\r\n root_dir: string = process.cwd(),\r\n config: UtcpClientConfig | null = null\r\n ): Promise<CodeModeUtcpClient> {\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: any) {\r\n let errorMsg: string = error instanceof Error ? error.message : String(error);\r\n // HTTP response error handling\r\n if (error.response?.data) {\r\n errorMsg += ` Error data: ${JSON.stringify(error.response.data)}`;\r\n }\r\n return JSON.stringify({ \r\n success: false, \r\n error: errorMsg\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,kBAAsD;AAC/D,OAAO,SAAS;AAMT,IAAM,qBAAN,MAAM,4BAA2B,WAAW;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,EAWL,aAAoB,OAClB,WAAmB,QAAQ,IAAI,GAC/B,SAAkC,MACL;AAE7B,UAAM,aAAa,MAAM,WAAW,OAAO,UAAU,MAAM;AAG3D,UAAM,iBAAiB,OAAO,eAAe,YAAY,oBAAmB,SAAS;AAGrF,IAAC,eAAuB,oBAAoB,oBAAI,IAAI;AAEpD,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUQ,mBAAmB,MAAsB;AAC/C,WAAO,KACJ,QAAQ,kBAAkB,GAAG,EAC7B,QAAQ,UAAU,KAAK;AAAA,EAC5B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;A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,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":[]}
{
"name": "@utcp/code-mode",
"version": "1.2.10",
"version": "1.2.11",
"description": "Code execution mode for UTCP - enables executing TypeScript code chains with tool access using isolated-vm for security",

@@ -5,0 +5,0 @@ "type": "module",