veryfront 0.0.70 → 0.0.71
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/components.js +109 -23
- package/dist/ai/components.js.map +2 -2
- package/dist/ai/dev.js.map +2 -2
- package/dist/ai/index.js +102 -21
- package/dist/ai/index.js.map +2 -2
- package/dist/ai/primitives.js +21 -16
- package/dist/ai/primitives.js.map +2 -2
- package/dist/ai/react.js +68 -13
- package/dist/ai/react.js.map +2 -2
- package/dist/ai/workflow.js +2 -1
- package/dist/ai/workflow.js.map +2 -2
- package/dist/cli.js +3 -3
- package/dist/components.js +1 -1
- package/dist/components.js.map +1 -1
- package/dist/config.js +1 -1
- package/dist/config.js.map +1 -1
- package/dist/data.js +1 -1
- package/dist/data.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/ai/dev.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/_shims/deno-env.ts", "../../../src/ai/dev/testing/agent-tester.ts", "../../../src/ai/dev/testing/tool-tester.ts", "../../../src/ai/utils/zod-json-schema.ts", "../../../src/core/utils/runtime-guards.ts", "../../../src/core/utils/logger/env.ts", "../../../src/core/utils/logger/logger.ts", "../../../src/core/errors/veryfront-error.ts", "../../../src/ai/utils/tool.ts", "../../../src/ai/mcp/resource.ts", "../../../src/ai/mcp/prompt.ts", "../../../src/ai/mcp/registry.ts", "../../../src/ai/dev/debug/inspector.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Shim for Deno.env in Node.js environment\n * This file is injected by esbuild to provide Deno.env compatibility\n */\n\n// @ts-ignore - Global Deno shim for Node.js\nglobalThis.Deno = globalThis.Deno || {\n env: {\n get(key: string): string | undefined {\n return process.env[key];\n },\n set(key: string, value: string): void {\n process.env[key] = value;\n },\n delete(key: string): void {\n delete process.env[key];\n },\n has(key: string): boolean {\n return key in process.env;\n },\n toObject(): Record<string, string> {\n return { ...process.env } as Record<string, string>;\n },\n },\n};\n", "/**\n * Agent Testing Utilities\n *\n * Utilities for testing agents in development and CI/CD.\n */\n\nimport type { Agent, AgentResponse, Message } from \"../../types/agent.ts\";\n\nexport interface TestCase {\n /** Test name */\n name: string;\n\n /** Input to agent */\n input: string | Message[];\n\n /** Expected output pattern (regex or string) */\n expected?: RegExp | string;\n\n /** Expected tool calls */\n expectToolCalls?: string[];\n\n /** Maximum execution time (ms) */\n timeout?: number;\n\n /** Custom validator */\n validate?: (response: AgentResponse) => boolean | Promise<boolean>;\n}\n\nexport interface TestResult {\n /** Test case name */\n name: string;\n\n /** Pass/fail */\n passed: boolean;\n\n /** Response from agent */\n response?: AgentResponse;\n\n /** Error if test failed */\n error?: string;\n\n /** Execution time */\n executionTime: number;\n\n /** Tool calls made */\n toolCalls: string[];\n}\n\nexport interface TestSuite {\n /** Suite name */\n name: string;\n\n /** Test results */\n results: TestResult[];\n\n /** Overall pass/fail */\n passed: boolean;\n\n /** Total execution time */\n totalTime: number;\n}\n\n/**\n * Test an agent with multiple test cases\n *\n * @example\n * ```typescript\n * import { testAgent } from 'veryfront/ai/dev';\n *\n * const results = await testAgent(myAgent, [\n * {\n * name: 'Simple greeting',\n * input: 'Hello',\n * expected: /hello|hi|hey/i,\n * },\n * {\n * name: 'Tool usage',\n * input: 'Search for AI frameworks',\n * expectToolCalls: ['searchWeb'],\n * },\n * ]);\n *\n * console.log(`Passed: ${results.results.filter(r => r.passed).length}/${results.results.length}`);\n * ```\n */\nexport async function testAgent(\n agent: Agent,\n testCases: TestCase[],\n): Promise<TestSuite> {\n const suite: TestSuite = {\n name: agent.id,\n results: [],\n passed: true,\n totalTime: 0,\n };\n\n const suiteStartTime = Date.now();\n\n for (const testCase of testCases) {\n const result = await runTestCase(agent, testCase);\n suite.results.push(result);\n\n if (!result.passed) {\n suite.passed = false;\n }\n }\n\n suite.totalTime = Date.now() - suiteStartTime;\n\n return suite;\n}\n\n/**\n * Run a single test case\n */\nasync function runTestCase(agent: Agent, testCase: TestCase): Promise<TestResult> {\n const startTime = Date.now();\n\n try {\n // Set timeout\n const timeout = testCase.timeout || 30000;\n const timeoutPromise = new Promise<never>((_, reject) => {\n setTimeout(() => reject(new Error(\"Test timeout\")), timeout);\n });\n\n // Execute agent\n const responsePromise = agent.generate({\n input: testCase.input,\n });\n\n const response = await Promise.race([responsePromise, timeoutPromise]);\n\n const executionTime = Date.now() - startTime;\n const toolCalls = response.toolCalls.map((tc) => tc.name);\n\n // Validate response\n let passed = true;\n let error: string | undefined;\n\n // Check expected output\n if (testCase.expected) {\n if (testCase.expected instanceof RegExp) {\n passed = testCase.expected.test(response.text);\n if (!passed) {\n error = `Output \"${response.text}\" does not match pattern ${testCase.expected}`;\n }\n } else {\n passed = response.text.includes(testCase.expected);\n if (!passed) {\n error = `Output does not contain expected text: \"${testCase.expected}\"`;\n }\n }\n }\n\n // Check expected tool calls\n if (passed && testCase.expectToolCalls) {\n const expectedTools = testCase.expectToolCalls;\n const missingTools = expectedTools.filter((t) => !toolCalls.includes(t));\n\n if (missingTools.length > 0) {\n passed = false;\n error = `Expected tool calls not found: ${missingTools.join(\", \")}`;\n }\n }\n\n // Custom validation\n if (passed && testCase.validate) {\n try {\n passed = await testCase.validate(response);\n if (!passed) {\n error = \"Custom validation failed\";\n }\n } catch (err) {\n passed = false;\n error = `Custom validation error: ${err instanceof Error ? err.message : String(err)}`;\n }\n }\n\n return {\n name: testCase.name,\n passed,\n response,\n error,\n executionTime,\n toolCalls,\n };\n } catch (err) {\n return {\n name: testCase.name,\n passed: false,\n error: err instanceof Error ? err.message : String(err),\n executionTime: Date.now() - startTime,\n toolCalls: [],\n };\n }\n}\n\n/**\n * Print test results in a readable format\n */\nexport function printTestResults(suite: TestSuite): void {\n console.log(`\\n=== Test Suite: ${suite.name} ===\\n`);\n\n const passed = suite.results.filter((r) => r.passed).length;\n const total = suite.results.length;\n\n suite.results.forEach((result, index) => {\n const icon = result.passed ? \"\u2705\" : \"\u274C\";\n console.log(`${icon} ${index + 1}. ${result.name}`);\n\n if (!result.passed && result.error) {\n console.log(` Error: ${result.error}`);\n }\n\n if (result.toolCalls.length > 0) {\n console.log(` Tools used: ${result.toolCalls.join(\", \")}`);\n }\n\n console.log(` Time: ${result.executionTime}ms\\n`);\n });\n\n console.log(`Results: ${passed}/${total} passed`);\n console.log(`Total time: ${suite.totalTime}ms`);\n console.log(`Status: ${suite.passed ? \"\u2705 PASSED\" : \"\u274C FAILED\"}\\n`);\n}\n\n/**\n * Assert that an agent response contains text\n */\nexport function assertContains(response: AgentResponse, text: string): boolean {\n return response.text.toLowerCase().includes(text.toLowerCase());\n}\n\n/**\n * Assert that an agent called a specific tool\n */\nexport function assertToolCalled(response: AgentResponse, toolName: string): boolean {\n return response.toolCalls.some((tc) => tc.name === toolName);\n}\n\n/**\n * Assert that an agent completed successfully\n */\nexport function assertCompleted(response: AgentResponse): boolean {\n return response.status === \"completed\";\n}\n", "/**\n * Tool Testing Utilities\n *\n * Utilities for testing individual tools.\n */\n\nimport type { Tool } from \"../../types/tool.ts\";\n\nexport interface ToolTestCase {\n /** Test name */\n name: string;\n\n /** Tool input */\n input: any;\n\n /** Expected output (partial match) */\n expectedOutput?: any;\n\n /** Custom validator */\n validate?: (result: any) => boolean | Promise<boolean>;\n\n /** Should throw error */\n shouldThrow?: boolean;\n\n /** Expected error message pattern */\n expectedError?: RegExp | string;\n}\n\nexport interface ToolTestResult {\n /** Test case name */\n name: string;\n\n /** Pass/fail */\n passed: boolean;\n\n /** Tool result */\n result?: any;\n\n /** Error if test failed */\n error?: string;\n\n /** Execution time */\n executionTime: number;\n}\n\n/**\n * Test a tool with multiple test cases\n *\n * @example\n * ```typescript\n * import { testTool } from 'veryfront/ai/dev';\n *\n * const results = await testTool(calculatorTool, [\n * {\n * name: 'Addition',\n * input: { operation: 'add', a: 2, b: 3 },\n * expectedOutput: { result: 5 },\n * },\n * {\n * name: 'Division by zero',\n * input: { operation: 'divide', a: 5, b: 0 },\n * shouldThrow: true,\n * expectedError: /cannot divide by zero/i,\n * },\n * ]);\n * ```\n */\nexport async function testTool(\n tool: Tool,\n testCases: ToolTestCase[],\n): Promise<ToolTestResult[]> {\n const results: ToolTestResult[] = [];\n\n for (const testCase of testCases) {\n const result = await runToolTest(tool, testCase);\n results.push(result);\n }\n\n return results;\n}\n\n/**\n * Run a single tool test\n */\nasync function runToolTest(\n tool: Tool,\n testCase: ToolTestCase,\n): Promise<ToolTestResult> {\n const startTime = Date.now();\n\n try {\n // Execute tool\n const result = await tool.execute(testCase.input);\n const executionTime = Date.now() - startTime;\n\n // If we expected an error but didn't get one\n if (testCase.shouldThrow) {\n return {\n name: testCase.name,\n passed: false,\n error: \"Expected tool to throw error but it succeeded\",\n executionTime,\n };\n }\n\n // Validate output\n let passed = true;\n let error: string | undefined;\n\n if (testCase.expectedOutput !== undefined) {\n passed = deepMatch(result, testCase.expectedOutput);\n if (!passed) {\n error = `Output mismatch. Expected: ${JSON.stringify(testCase.expectedOutput)}, Got: ${\n JSON.stringify(result)\n }`;\n }\n }\n\n if (passed && testCase.validate) {\n try {\n passed = await testCase.validate(result);\n if (!passed) {\n error = \"Custom validation failed\";\n }\n } catch (err) {\n passed = false;\n error = `Validation error: ${err instanceof Error ? err.message : String(err)}`;\n }\n }\n\n return {\n name: testCase.name,\n passed,\n result,\n error,\n executionTime,\n };\n } catch (err) {\n const executionTime = Date.now() - startTime;\n const errorMessage = err instanceof Error ? err.message : String(err);\n\n // If we expected an error\n if (testCase.shouldThrow) {\n let passed = true;\n let error: string | undefined;\n\n if (testCase.expectedError) {\n if (testCase.expectedError instanceof RegExp) {\n passed = testCase.expectedError.test(errorMessage);\n } else {\n passed = errorMessage.includes(testCase.expectedError);\n }\n\n if (!passed) {\n error =\n `Error message mismatch. Expected pattern: ${testCase.expectedError}, Got: ${errorMessage}`;\n }\n }\n\n return {\n name: testCase.name,\n passed,\n error,\n executionTime,\n };\n }\n\n // Unexpected error\n return {\n name: testCase.name,\n passed: false,\n error: `Unexpected error: ${errorMessage}`,\n executionTime,\n };\n }\n}\n\n/**\n * Deep match for partial object comparison\n */\nfunction deepMatch(actual: any, expected: any): boolean {\n if (expected === actual) return true;\n if (typeof expected !== \"object\" || expected === null) return false;\n if (typeof actual !== \"object\" || actual === null) return false;\n\n for (const key in expected) {\n if (!(key in actual)) return false;\n\n const expectedValue = expected[key];\n const actualValue = actual[key];\n\n if (typeof expectedValue === \"object\" && expectedValue !== null) {\n if (!deepMatch(actualValue, expectedValue)) return false;\n } else {\n if (actualValue !== expectedValue) return false;\n }\n }\n\n return true;\n}\n\n/**\n * Print tool test results\n */\nexport function printToolTestResults(\n toolId: string,\n results: ToolTestResult[],\n): void {\n console.log(`\\n=== Tool Tests: ${toolId} ===\\n`);\n\n const passed = results.filter((r) => r.passed).length;\n const total = results.length;\n\n results.forEach((result, index) => {\n const icon = result.passed ? \"\u2705\" : \"\u274C\";\n console.log(`${icon} ${index + 1}. ${result.name}`);\n\n if (!result.passed && result.error) {\n console.log(` Error: ${result.error}`);\n }\n\n if (result.result !== undefined) {\n console.log(` Result: ${JSON.stringify(result.result)}`);\n }\n\n console.log(` Time: ${result.executionTime}ms\\n`);\n });\n\n console.log(`Results: ${passed}/${total} passed`);\n console.log(`Status: ${passed === total ? \"\u2705 ALL PASSED\" : \"\u274C SOME FAILED\"}\\n`);\n}\n", "import type { z } from \"zod\";\nimport { ZodFirstPartyTypeKind } from \"zod\";\nimport type { JsonSchema } from \"../types/json-schema.ts\";\n\nexport function zodToJsonSchema(schema: z.ZodTypeAny): JsonSchema {\n // Guard against invalid schemas (can happen with different zod instances in npm bundle)\n if (!schema || typeof schema !== \"object\" || !(\"_def\" in schema)) {\n throw new Error(\"Invalid Zod schema: missing _def property\");\n }\n\n const details = unwrapSchema(schema);\n const json = convert(details.schema);\n if (details.nullable) {\n return { anyOf: [json, { type: \"null\" }] };\n }\n return json;\n}\n\nexport function isOptionalSchema(schema: z.ZodTypeAny): boolean {\n const { optional } = unwrapSchema(schema);\n return optional;\n}\n\nfunction convert(schema: z.ZodTypeAny): JsonSchema {\n switch (schema._def.typeName) {\n case ZodFirstPartyTypeKind.ZodString:\n return { type: \"string\" };\n case ZodFirstPartyTypeKind.ZodNumber:\n return { type: \"number\" };\n case ZodFirstPartyTypeKind.ZodBoolean:\n return { type: \"boolean\" };\n case ZodFirstPartyTypeKind.ZodBigInt:\n return { type: \"integer\" };\n case ZodFirstPartyTypeKind.ZodLiteral: {\n const literal = (schema as z.ZodLiteral<unknown>)._def.value;\n return {\n const: literal,\n type: typeof literal === \"string\"\n ? \"string\"\n : typeof literal === \"number\"\n ? \"number\"\n : typeof literal === \"boolean\"\n ? \"boolean\"\n : undefined,\n };\n }\n case ZodFirstPartyTypeKind.ZodEnum:\n return {\n type: \"string\",\n enum: (schema as z.ZodEnum<[string, ...string[]]>)._def.values,\n };\n case ZodFirstPartyTypeKind.ZodNativeEnum:\n return {\n enum: Object.values((schema as z.ZodNativeEnum<any>)._def.values).filter(\n (value) => typeof value !== \"number\",\n ),\n };\n case ZodFirstPartyTypeKind.ZodObject: {\n const obj = schema as z.ZodObject<any>;\n const properties: Record<string, JsonSchema> = {};\n const required: string[] = [];\n\n // Access shape - it might be a function (lazy getter) or an object\n const shape = typeof obj._def.shape === \"function\" ? obj._def.shape() : obj._def.shape;\n\n for (const [key, value] of Object.entries(shape || {})) {\n const zodSchema = value as z.ZodTypeAny;\n properties[key] = zodToJsonSchema(zodSchema);\n if (!isOptionalSchema(zodSchema)) {\n required.push(key);\n }\n }\n\n const json: JsonSchema = { type: \"object\", properties };\n if (required.length > 0) {\n json.required = required;\n }\n return json;\n }\n case ZodFirstPartyTypeKind.ZodArray: {\n const array = schema as z.ZodArray<z.ZodTypeAny>;\n return {\n type: \"array\",\n items: zodToJsonSchema(array._def.type),\n };\n }\n case ZodFirstPartyTypeKind.ZodTuple: {\n const tuple = schema as z.ZodTuple;\n return {\n type: \"array\",\n prefixItems: tuple._def.items.map((item) => zodToJsonSchema(item)),\n minItems: tuple._def.items.length,\n maxItems: tuple._def.items.length,\n };\n }\n case ZodFirstPartyTypeKind.ZodUnion: {\n const union = schema as z.ZodUnion<[z.ZodTypeAny, z.ZodTypeAny, ...z.ZodTypeAny[]]>;\n return {\n anyOf: union._def.options.map((option) => zodToJsonSchema(option)),\n };\n }\n case ZodFirstPartyTypeKind.ZodDiscriminatedUnion: {\n const union = schema as z.ZodDiscriminatedUnion<string, z.ZodObject<any>[]>;\n return {\n anyOf: Array.from(union._def.options.values()).map((option) => zodToJsonSchema(option)),\n };\n }\n case ZodFirstPartyTypeKind.ZodRecord:\n return {\n type: \"object\",\n additionalProperties: zodToJsonSchema((schema as z.ZodRecord<any>)._def.valueType),\n };\n case ZodFirstPartyTypeKind.ZodDefault: {\n const def = schema as z.ZodDefault<z.ZodTypeAny>;\n const inner = zodToJsonSchema(def._def.innerType);\n const defaultValue = def._def.defaultValue();\n if (typeof inner === \"object\" && !(\"anyOf\" in inner)) {\n inner.default = defaultValue;\n }\n return inner;\n }\n case ZodFirstPartyTypeKind.ZodLazy:\n return convert((schema as z.ZodLazy<any>)._def.getter());\n case ZodFirstPartyTypeKind.ZodEffects:\n return convert((schema as z.ZodEffects<any>)._def.schema);\n default:\n return { type: \"object\" };\n }\n}\n\nfunction unwrapSchema(schema: z.ZodTypeAny) {\n let current: z.ZodTypeAny = schema;\n let nullable = false;\n let optional = false;\n\n while (true) {\n switch (current._def.typeName) {\n case ZodFirstPartyTypeKind.ZodNullable:\n nullable = true;\n current = (current as z.ZodNullable<z.ZodTypeAny>)._def.innerType;\n continue;\n case ZodFirstPartyTypeKind.ZodOptional:\n optional = true;\n current = (current as z.ZodOptional<z.ZodTypeAny>)._def.innerType;\n continue;\n case ZodFirstPartyTypeKind.ZodEffects:\n current = (current as z.ZodEffects<any>)._def.schema;\n continue;\n default:\n return { schema: current, nullable, optional };\n }\n }\n}\n", "export interface GlobalWithDeno {\n Deno?: {\n env: {\n get(key: string): string | undefined;\n };\n };\n}\n\nexport interface GlobalWithProcess {\n process?: {\n env: Record<string, string | undefined>;\n version?: string;\n versions?: Record<string, string>;\n };\n}\n\nexport interface GlobalWithBun {\n Bun?: {\n version: string;\n };\n}\n\nexport function hasDenoRuntime(global: unknown): global is GlobalWithDeno {\n return (\n typeof global === \"object\" &&\n global !== null &&\n \"Deno\" in global &&\n typeof (global as GlobalWithDeno).Deno?.env?.get === \"function\"\n );\n}\n\nexport function hasNodeProcess(global: unknown): global is GlobalWithProcess {\n return (\n typeof global === \"object\" &&\n global !== null &&\n \"process\" in global &&\n typeof (global as GlobalWithProcess).process?.env === \"object\"\n );\n}\n\nexport function hasBunRuntime(global: unknown): global is GlobalWithBun {\n return (\n typeof global === \"object\" &&\n global !== null &&\n \"Bun\" in global &&\n typeof (global as GlobalWithBun).Bun !== \"undefined\"\n );\n}\n", "import type { GlobalWithDeno, GlobalWithProcess } from \"../runtime-guards.ts\";\nimport { hasDenoRuntime, hasNodeProcess } from \"../runtime-guards.ts\";\n\nexport function getEnvironmentVariable(name: string): string | undefined {\n try {\n if (typeof Deno !== \"undefined\" && hasDenoRuntime(globalThis)) {\n const value = (globalThis as GlobalWithDeno).Deno?.env.get(name);\n return value === \"\" ? undefined : value;\n }\n if (hasNodeProcess(globalThis)) {\n const value = (globalThis as GlobalWithProcess).process?.env[name];\n return value === \"\" ? undefined : value;\n }\n } catch {\n return undefined;\n }\n return undefined;\n}\n\nexport function isTestEnvironment(): boolean {\n return getEnvironmentVariable(\"NODE_ENV\") === \"test\";\n}\n\nexport function isProductionEnvironment(): boolean {\n return getEnvironmentVariable(\"NODE_ENV\") === \"production\";\n}\n\nexport function isDevelopmentEnvironment(): boolean {\n const env = getEnvironmentVariable(\"NODE_ENV\");\n return env === \"development\" || env === undefined;\n}\n", "import { getEnvironmentVariable } from \"./env.ts\";\n\nexport enum LogLevel {\n DEBUG = 0,\n INFO = 1,\n WARN = 2,\n ERROR = 3,\n}\n\nexport interface Logger {\n debug(message: string, ...args: unknown[]): void;\n info(message: string, ...args: unknown[]): void;\n warn(message: string, ...args: unknown[]): void;\n error(message: string, ...args: unknown[]): void;\n time<T>(label: string, fn: () => Promise<T>): Promise<T>;\n}\n\nconst originalConsole = {\n debug: console.debug,\n log: console.log,\n warn: console.warn,\n error: console.error,\n};\n\nlet cachedLogLevel: LogLevel | undefined;\n\nfunction resolveLogLevel(force = false): LogLevel {\n if (force || cachedLogLevel === undefined) {\n cachedLogLevel = getDefaultLevel();\n }\n return cachedLogLevel;\n}\n\nclass ConsoleLogger implements Logger {\n constructor(\n private prefix: string,\n private level: LogLevel = resolveLogLevel(),\n ) {}\n\n setLevel(level: LogLevel): void {\n this.level = level;\n }\n\n getLevel(): LogLevel {\n return this.level;\n }\n\n debug(message: string, ...args: unknown[]): void {\n if (this.level <= LogLevel.DEBUG) {\n console.debug(`[${this.prefix}] DEBUG: ${message}`, ...args);\n }\n }\n\n info(message: string, ...args: unknown[]): void {\n if (this.level <= LogLevel.INFO) {\n console.log(`[${this.prefix}] ${message}`, ...args);\n }\n }\n\n warn(message: string, ...args: unknown[]): void {\n if (this.level <= LogLevel.WARN) {\n console.warn(`[${this.prefix}] WARN: ${message}`, ...args);\n }\n }\n\n error(message: string, ...args: unknown[]): void {\n if (this.level <= LogLevel.ERROR) {\n console.error(`[${this.prefix}] ERROR: ${message}`, ...args);\n }\n }\n\n async time<T>(label: string, fn: () => Promise<T>): Promise<T> {\n const start = performance.now();\n try {\n const result = await fn();\n const end = performance.now();\n this.debug(`${label} completed in ${(end - start).toFixed(2)}ms`);\n return result;\n } catch (error) {\n const end = performance.now();\n this.error(`${label} failed after ${(end - start).toFixed(2)}ms`, error);\n throw error;\n }\n }\n}\n\nfunction parseLogLevel(levelString: string | undefined): LogLevel | undefined {\n if (!levelString) return undefined;\n const upper = levelString.toUpperCase();\n switch (upper) {\n case \"DEBUG\":\n return LogLevel.DEBUG;\n case \"WARN\":\n return LogLevel.WARN;\n case \"ERROR\":\n return LogLevel.ERROR;\n case \"INFO\":\n return LogLevel.INFO;\n default:\n return undefined;\n }\n}\n\nconst getDefaultLevel = (): LogLevel => {\n const envLevel = getEnvironmentVariable(\"LOG_LEVEL\");\n const parsedLevel = parseLogLevel(envLevel);\n if (parsedLevel !== undefined) return parsedLevel;\n\n const debugFlag = getEnvironmentVariable(\"VERYFRONT_DEBUG\");\n if (debugFlag === \"1\" || debugFlag === \"true\") return LogLevel.DEBUG;\n\n return LogLevel.INFO;\n};\n\nconst trackedLoggers = new Set<ConsoleLogger>();\n\nfunction createLogger(prefix: string): ConsoleLogger {\n const logger = new ConsoleLogger(prefix);\n trackedLoggers.add(logger);\n return logger;\n}\n\nexport const cliLogger = createLogger(\"CLI\");\nexport const serverLogger = createLogger(\"SERVER\");\nexport const rendererLogger = createLogger(\"RENDERER\");\nexport const bundlerLogger = createLogger(\"BUNDLER\");\nexport const agentLogger = createLogger(\"AGENT\");\n\nexport const logger = createLogger(\"VERYFRONT\");\n\ntype LoggerResetOptions = {\n restoreConsole?: boolean;\n};\n\nexport function __loggerResetForTests(options: LoggerResetOptions = {}): void {\n const updatedLevel = resolveLogLevel(true);\n for (const instance of trackedLoggers) {\n instance.setLevel(updatedLevel);\n }\n\n if (options.restoreConsole) {\n console.debug = originalConsole.debug;\n console.log = originalConsole.log;\n console.warn = originalConsole.warn;\n console.error = originalConsole.error;\n }\n}\n", "export interface BuildContext {\n file?: string;\n line?: number;\n column?: number;\n moduleId?: string;\n phase?: \"parse\" | \"transform\" | \"bundle\" | \"optimize\";\n}\n\nexport interface APIContext {\n endpoint?: string;\n method?: string;\n statusCode?: number;\n headers?: Record<string, string>;\n}\n\nexport interface RenderContext {\n component?: string;\n route?: string;\n phase?: \"server\" | \"client\" | \"hydration\";\n props?: unknown;\n}\n\nexport interface ConfigContext {\n configFile?: string;\n field?: string;\n value?: unknown;\n expected?: string;\n}\n\nexport interface AgentContext {\n agentId?: string;\n intent?: string;\n timeout?: number;\n}\n\nexport interface FileContext {\n path?: string;\n operation?: \"read\" | \"write\" | \"delete\" | \"mkdir\";\n permissions?: string;\n}\n\nexport interface NetworkContext {\n url?: string;\n timeout?: number;\n retryCount?: number;\n}\n\nexport type VeryfrontError =\n | { type: \"build\"; message: string; context?: BuildContext }\n | { type: \"api\"; message: string; context?: APIContext }\n | { type: \"render\"; message: string; context?: RenderContext }\n | { type: \"config\"; message: string; context?: ConfigContext }\n | { type: \"agent\"; message: string; context?: AgentContext }\n | { type: \"file\"; message: string; context?: FileContext }\n | { type: \"network\"; message: string; context?: NetworkContext }\n | { type: \"permission\"; message: string; context?: FileContext }\n | { type: \"not_supported\"; message: string; feature?: string };\n\nexport function createError(error: VeryfrontError): VeryfrontError {\n return error;\n}\n\nexport function isBuildError(\n error: VeryfrontError,\n): error is Extract<VeryfrontError, { type: \"build\" }> {\n return error.type === \"build\";\n}\n\nexport function isAPIError(\n error: VeryfrontError,\n): error is Extract<VeryfrontError, { type: \"api\" }> {\n return error.type === \"api\";\n}\n\nexport function isRenderError(\n error: VeryfrontError,\n): error is Extract<VeryfrontError, { type: \"render\" }> {\n return error.type === \"render\";\n}\n\nexport function isConfigError(\n error: VeryfrontError,\n): error is Extract<VeryfrontError, { type: \"config\" }> {\n return error.type === \"config\";\n}\n\nexport function isAgentError(\n error: VeryfrontError,\n): error is Extract<VeryfrontError, { type: \"agent\" }> {\n return error.type === \"agent\";\n}\n\nexport function isFileError(\n error: VeryfrontError,\n): error is Extract<VeryfrontError, { type: \"file\" }> {\n return error.type === \"file\";\n}\n\nexport function isNetworkError(\n error: VeryfrontError,\n): error is Extract<VeryfrontError, { type: \"network\" }> {\n return error.type === \"network\";\n}\n\nexport function toError(veryfrontError: VeryfrontError): Error {\n const error = new Error(veryfrontError.message);\n error.name = `VeryfrontError[${veryfrontError.type}]`;\n Object.defineProperty(error, \"context\", {\n value: veryfrontError,\n enumerable: false,\n configurable: true,\n });\n return error;\n}\n\nexport function fromError(error: unknown): VeryfrontError | null {\n if (error && typeof error === \"object\" && \"context\" in error) {\n // Safe access after 'in' check\n const context = (error as Record<string, unknown>).context;\n if (\n context &&\n typeof context === \"object\" &&\n \"type\" in context &&\n \"message\" in context\n ) {\n return context as VeryfrontError;\n }\n }\n return null;\n}\n\nexport function logError(\n error: VeryfrontError,\n logger?: { error: (msg: string, ...args: unknown[]) => void },\n): void {\n const log = logger || console;\n const context = \"context\" in error ? error.context || {} : {};\n log.error(`[${error.type}] ${error.message}`, context);\n}\n", "import type { Tool, ToolConfig, ToolDefinition, ToolExecutionContext } from \"../types/tool.ts\";\nimport type { JsonSchema } from \"../types/json-schema.ts\";\nimport { zodToJsonSchema } from \"./zod-json-schema.ts\";\nimport { agentLogger } from \"../../core/utils/logger/logger.ts\";\nimport { createError, toError } from \"../../core/errors/veryfront-error.ts\";\n\n/**\n * Create a tool\n *\n * @example\n * ```typescript\n * import { tool } from 'veryfront/ai';\n * import { z } from 'zod';\n\n *\n * export default tool({\n * description: 'Search the web',\n * inputSchema: z.object({\n * query: z.string(),\n * }),\n * execute: async ({ query }) => {\n * const results = await searchWeb(query);\n * return results;\n * },\n * });\n * ```\n */\nexport function tool<TInput = any, TOutput = any>(\n config: ToolConfig<TInput, TOutput>,\n): Tool<TInput, TOutput> {\n const id = config.id || generateToolId();\n\n // Check if we have a valid zod schema (has _def property)\n const hasValidZodSchema = config.inputSchema &&\n typeof config.inputSchema === \"object\" &&\n \"_def\" in config.inputSchema &&\n (config.inputSchema as { _def?: { typeName?: string } })._def?.typeName;\n\n // Pre-convert Zod schema to JSON Schema immediately\n // This happens BEFORE any bundling, in a clean environment\n let inputSchemaJson: JsonSchema | undefined;\n if (hasValidZodSchema) {\n try {\n inputSchemaJson = zodToJsonSchema(config.inputSchema);\n agentLogger.info(\n `[TOOL] Pre-converted schema for \"${id}\": ${\n Object.keys(inputSchemaJson.properties || {}).length\n } properties`,\n );\n } catch (error) {\n agentLogger.warn(`[TOOL] Failed to pre-convert schema for \"${id}\":`, error);\n // Continue without pre-converted schema - will fall back to runtime conversion\n }\n } else {\n // Try to introspect the schema from external zod instance\n const externalSchema = config.inputSchema as {\n _def?: {\n typeName?: string;\n shape?: (() => Record<string, unknown>) | Record<string, unknown>;\n };\n };\n\n if (externalSchema?._def?.shape) {\n try {\n const shape = typeof externalSchema._def.shape === \"function\"\n ? externalSchema._def.shape()\n : externalSchema._def.shape;\n\n // Build JSON Schema from shape inspection\n const properties: Record<string, JsonSchema> = {};\n for (const key of Object.keys(shape || {})) {\n // Default to string type for unknown schemas\n properties[key] = { type: \"string\" as const };\n }\n inputSchemaJson = {\n type: \"object\" as const,\n properties,\n required: Object.keys(properties),\n };\n agentLogger.info(\n `[TOOL] Introspected schema for \"${id}\" from external zod: ${\n Object.keys(properties).length\n } properties`,\n );\n } catch {\n inputSchemaJson = { type: \"object\", properties: {} };\n agentLogger.warn(\n `[TOOL] Schema for \"${id}\" could not be introspected. Using empty schema.`,\n );\n }\n } else {\n agentLogger.warn(\n `[TOOL] Schema for \"${id}\" is not a valid Zod schema (different zod instance?). ` +\n `Skipping pre-conversion. Input validation may be limited.`,\n );\n // Create a basic schema from inspection if possible\n inputSchemaJson = { type: \"object\", properties: {} };\n }\n }\n\n return {\n id,\n description: config.description,\n inputSchema: config.inputSchema,\n inputSchemaJson, // Store pre-converted schema\n execute: async (input: TInput, context?: ToolExecutionContext) => {\n // Validate input if zod schema is available\n if (hasValidZodSchema) {\n try {\n config.inputSchema.parse(input);\n } catch (error) {\n throw toError(createError({\n type: \"agent\",\n message: `Tool \"${id}\" input validation failed: ${\n error instanceof Error ? error.message : String(error)\n }`,\n }));\n }\n } else if (\n config.inputSchema &&\n typeof config.inputSchema === \"object\" &&\n \"parse\" in config.inputSchema &&\n typeof (config.inputSchema as { parse?: unknown }).parse === \"function\"\n ) {\n // Try to use parse method if available (external zod instance)\n try {\n (config.inputSchema as { parse: (input: unknown) => void }).parse(input);\n } catch (error) {\n throw toError(createError({\n type: \"agent\",\n message: `Tool \"${id}\" input validation failed: ${\n error instanceof Error ? error.message : String(error)\n }`,\n }));\n }\n }\n\n // Execute tool\n return await config.execute(input, context);\n },\n mcp: config.mcp,\n };\n}\n\n/**\n * Generate a unique tool ID\n */\nlet toolIdCounter = 0;\nfunction generateToolId(): string {\n return `tool_${Date.now()}_${toolIdCounter++}`;\n}\n\n/**\n * Tool registry for managing tools\n */\nclass ToolRegistryClass {\n private tools = new Map<string, Tool>();\n\n register(id: string, toolInstance: Tool): void {\n if (this.tools.has(id)) {\n // Debug level - overwriting is expected during hot reload and re-discovery\n agentLogger.debug(`Tool \"${id}\" is already registered. Overwriting.`);\n }\n\n this.tools.set(id, toolInstance);\n }\n\n /**\n * Get a tool by ID\n */\n get(id: string): Tool | undefined {\n return this.tools.get(id);\n }\n\n /**\n * Check if a tool exists\n */\n has(id: string): boolean {\n return this.tools.has(id);\n }\n\n /**\n * Get all tool IDs\n */\n getAllIds(): string[] {\n return Array.from(this.tools.keys());\n }\n\n /**\n * Get all tools\n */\n getAll(): Map<string, Tool> {\n return new Map(this.tools);\n }\n\n /**\n * Clear all tools (for testing)\n */\n clear(): void {\n this.tools.clear();\n }\n\n getToolsForProvider(): ToolDefinition[] {\n return Array.from(this.tools.values()).map(toolToProviderDefinition);\n }\n}\n\n// Singleton instance using globalThis to share across module contexts\n// This is necessary for esbuild-bundled API routes to access the same registry\nconst TOOL_REGISTRY_KEY = \"__veryfront_tool_registry__\";\n// deno-lint-ignore no-explicit-any\nconst _globalTool = globalThis as any;\nexport const toolRegistry: ToolRegistryClass = _globalTool[TOOL_REGISTRY_KEY] ||=\n new ToolRegistryClass();\n\nexport function toolToProviderDefinition(tool: Tool): ToolDefinition {\n // Use pre-converted JSON Schema if available (preferred)\n // Fall back to runtime conversion if needed\n const jsonSchema = tool.inputSchemaJson || zodToJsonSchema(tool.inputSchema);\n\n agentLogger.info(\n `[TOOL] Using ${\n tool.inputSchemaJson ? \"pre-converted\" : \"runtime-converted\"\n } schema for \"${tool.id}\"`,\n );\n\n return {\n name: tool.id,\n description: tool.description,\n parameters: jsonSchema,\n };\n}\n\n/**\n * Execute a tool by ID\n */\nexport async function executeTool(\n toolId: string,\n input: unknown,\n context?: ToolExecutionContext,\n): Promise<unknown> {\n const tool = toolRegistry.get(toolId);\n\n if (!tool) {\n throw toError(createError({\n type: \"agent\",\n message: `Tool \"${toolId}\" not found`,\n }));\n }\n\n try {\n const result = await tool.execute(input, context);\n return result;\n } catch (error) {\n throw toError(createError({\n type: \"agent\",\n message: `Tool \"${toolId}\" execution failed: ${\n error instanceof Error ? error.message : String(error)\n }`,\n }));\n }\n}\n\nexport { zodToJsonSchema } from \"./zod-json-schema.ts\";\n", "/**\n * MCP Resource factory and utilities\n */\n\nimport type { Resource, ResourceConfig } from \"../types/mcp.ts\";\nimport { agentLogger } from \"../../core/utils/logger/logger.ts\";\nimport { createError, toError } from \"../../core/errors/veryfront-error.ts\";\n\n/**\n * Create an MCP resource\n *\n * @example\n * ```typescript\n * import { resource } from 'veryfront/ai';\n * import { z } from 'zod';\n\n *\n * export default resource({\n * description: 'Get user profile',\n * paramsSchema: z.object({\n * userId: z.string(),\n * }),\n * load: async ({ userId }) => {\n * return await db.users.findUnique({ where: { id: userId } });\n * },\n * });\n * ```\n */\nexport function resource<TParams = any, TData = any>(\n config: ResourceConfig<TParams, TData>,\n): Resource<TParams, TData> {\n // Generate pattern if not provided\n const pattern = config.pattern || generateResourcePattern();\n\n // Generate ID from pattern\n const id = patternToId(pattern);\n\n return {\n id,\n pattern,\n description: config.description,\n paramsSchema: config.paramsSchema,\n load: async (params: TParams) => {\n // Validate params\n try {\n config.paramsSchema.parse(params);\n } catch (error) {\n throw toError(createError({\n type: \"agent\",\n message: `Resource \"${id}\" params validation failed: ${\n error instanceof Error ? error.message : String(error)\n }`,\n }));\n }\n\n return await config.load(params);\n },\n subscribe: config.subscribe,\n mcp: config.mcp,\n };\n}\n\n/**\n * Generate resource pattern fallback\n * Note: In practice, resources should explicitly define their pattern.\n * Auto-discovery is handled by the discovery.ts module which scans\n * the filesystem and extracts patterns from resource definitions.\n */\nfunction generateResourcePattern(): string {\n return `/resource_${Date.now()}`;\n}\n\n/**\n * Convert path pattern to ID\n * Example: \"/users/:userId/profile\" -> \"users_userId_profile\"\n */\nfunction patternToId(pattern: string): string {\n return pattern\n .replace(/^\\//, \"\")\n .replace(/\\//g, \"_\")\n .replace(/:/g, \"\");\n}\n\n/**\n * Resource registry\n */\nclass ResourceRegistryClass {\n private resources = new Map<string, Resource>();\n\n /**\n * Register a resource\n */\n register(id: string, resourceInstance: Resource): void {\n if (this.resources.has(id)) {\n // Debug level - overwriting is expected during hot reload and re-discovery\n agentLogger.debug(`Resource \"${id}\" is already registered. Overwriting.`);\n }\n\n this.resources.set(id, resourceInstance);\n }\n\n /**\n * Get a resource by ID\n */\n get(id: string): Resource | undefined {\n return this.resources.get(id);\n }\n\n /**\n * Get resource by pattern matching\n */\n findByPattern(uri: string): Resource | undefined {\n for (const resource of this.resources.values()) {\n if (this.matchesPattern(uri, resource.pattern)) {\n return resource;\n }\n }\n return undefined;\n }\n\n /**\n * Check if URI matches pattern\n * Uses regex-based pattern matching with named capture groups.\n * Supports Express-style patterns like \"/users/:userId/profile\"\n */\n private matchesPattern(uri: string, pattern: string): boolean {\n const patternRegex = new RegExp(\n \"^\" + pattern.replace(/:(\\w+)/g, \"(?<$1>[^/]+)\") + \"$\",\n );\n return patternRegex.test(uri);\n }\n\n /**\n * Extract params from URI using pattern\n */\n extractParams(uri: string, pattern: string): Record<string, string> {\n const patternRegex = new RegExp(\n \"^\" + pattern.replace(/:(\\w+)/g, \"(?<$1>[^/]+)\") + \"$\",\n );\n const match = uri.match(patternRegex);\n\n return match?.groups || {};\n }\n\n /**\n * Get all resources\n */\n getAll(): Map<string, Resource> {\n return new Map(this.resources);\n }\n\n /**\n * Clear all resources\n */\n clear(): void {\n this.resources.clear();\n }\n}\n\n// Singleton instance using globalThis to share across module contexts\n// This is necessary for esbuild-bundled API routes to access the same registry\nconst RESOURCE_REGISTRY_KEY = \"__veryfront_resource_registry__\";\n// deno-lint-ignore no-explicit-any\nconst _globalResource = globalThis as any;\nexport const resourceRegistry: ResourceRegistryClass = _globalResource[RESOURCE_REGISTRY_KEY] ||=\n new ResourceRegistryClass();\n", "/**\n * MCP Prompt factory and utilities\n */\n\nimport type { Prompt, PromptConfig } from \"../types/mcp.ts\";\nimport { agentLogger } from \"../../core/utils/logger/logger.ts\";\nimport { createError, toError } from \"../../core/errors/veryfront-error.ts\";\n\n/**\n * Create an MCP prompt template\n *\n * @example\n * ```typescript\n * import { prompt } from 'veryfront/ai';\n\n *\n * export default prompt({\n * description: 'Customer support prompt',\n * content: 'You are a helpful customer support agent...',\n * });\n * ```\n */\nexport function prompt(config: PromptConfig): Prompt {\n const id = config.id || generatePromptId();\n\n return {\n id,\n description: config.description,\n\n async getContent(\n variables?: Record<string, unknown>,\n ): Promise<string> {\n // If static content\n if (config.content) {\n return interpolateVariables(config.content, variables || {});\n }\n\n // If dynamic generator\n if (config.generate) {\n return await config.generate(variables || {});\n }\n\n throw toError(createError({\n type: \"agent\",\n message: `Prompt \"${id}\" has no content or generator`,\n }));\n },\n };\n}\n\n/**\n * Generate a unique prompt ID\n */\nlet promptIdCounter = 0;\nfunction generatePromptId(): string {\n return `prompt_${Date.now()}_${promptIdCounter++}`;\n}\n\n/**\n * Interpolate variables in prompt template\n * Replaces {variableName} with actual values\n */\nfunction interpolateVariables(\n template: string,\n variables: Record<string, unknown>,\n): string {\n return template.replace(/\\{(\\w+)\\}/g, (match, key) => {\n const value = variables[key];\n return value !== undefined ? String(value) : match;\n });\n}\n\n/**\n * Prompt registry\n */\nclass PromptRegistryClass {\n private prompts = new Map<string, Prompt>();\n\n /**\n * Register a prompt\n */\n register(id: string, promptInstance: Prompt): void {\n if (this.prompts.has(id)) {\n // Debug level - overwriting is expected during hot reload and re-discovery\n agentLogger.debug(`Prompt \"${id}\" is already registered. Overwriting.`);\n }\n\n this.prompts.set(id, promptInstance);\n }\n\n /**\n * Get a prompt by ID\n */\n get(id: string): Prompt | undefined {\n return this.prompts.get(id);\n }\n\n /**\n * Get prompt content by ID\n */\n async getContent(\n id: string,\n variables?: Record<string, unknown>,\n ): Promise<string> {\n const promptInstance = this.get(id);\n\n if (!promptInstance) {\n throw toError(createError({\n type: \"agent\",\n message: `Prompt \"${id}\" not found`,\n }));\n }\n\n return await promptInstance.getContent(variables);\n }\n\n /**\n * Get all prompts\n */\n getAll(): Map<string, Prompt> {\n return new Map(this.prompts);\n }\n\n /**\n * Clear all prompts\n */\n clear(): void {\n this.prompts.clear();\n }\n}\n\n// Singleton instance using globalThis to share across module contexts\n// This is necessary for esbuild-bundled API routes to access the same registry\nconst PROMPT_REGISTRY_KEY = \"__veryfront_prompt_registry__\";\n// deno-lint-ignore no-explicit-any\nconst _globalPrompt = globalThis as any;\nexport const promptRegistry: PromptRegistryClass = _globalPrompt[PROMPT_REGISTRY_KEY] ||=\n new PromptRegistryClass();\n", "/**\n * MCP Registry - Central registry for all MCP resources\n */\n\nimport type { MCPRegistry } from \"../types/mcp.ts\";\nimport type { Tool } from \"../types/tool.ts\";\nimport type { Prompt, Resource } from \"../types/mcp.ts\";\nimport { toolRegistry } from \"../utils/tool.ts\";\nimport { resourceRegistry } from \"./resource.ts\";\nimport { promptRegistry } from \"./prompt.ts\";\n\n/**\n * Get the global MCP registry\n */\nexport function getMCPRegistry(): MCPRegistry {\n return {\n tools: toolRegistry.getAll(),\n resources: resourceRegistry.getAll(),\n prompts: promptRegistry.getAll(),\n };\n}\n\n/**\n * Register a tool in the MCP registry\n */\nexport function registerTool(id: string, tool: Tool): void {\n toolRegistry.register(id, tool);\n}\n\n/**\n * Register a resource in the MCP registry\n */\nexport function registerResource(id: string, resource: Resource): void {\n resourceRegistry.register(id, resource);\n}\n\n/**\n * Register a prompt in the MCP registry\n */\nexport function registerPrompt(id: string, promptInstance: Prompt): void {\n promptRegistry.register(id, promptInstance);\n}\n\n/**\n * Get MCP registry stats\n */\nexport function getMCPStats(): {\n tools: number;\n resources: number;\n prompts: number;\n total: number;\n} {\n const registry = getMCPRegistry();\n\n return {\n tools: registry.tools.size,\n resources: registry.resources.size,\n prompts: registry.prompts.size,\n total: registry.tools.size + registry.resources.size + registry.prompts.size,\n };\n}\n\n/**\n * Clear all MCP registries (for testing)\n */\nexport function clearMCPRegistry(): void {\n toolRegistry.clear();\n resourceRegistry.clear();\n promptRegistry.clear();\n}\n", "/**\n * Agent & Tool Inspector\n *\n * Debugging utilities for inspecting agent execution and tool calls.\n */\n\nimport type { Agent, Message } from \"../../types/agent.ts\";\nimport { getMCPRegistry, getMCPStats } from \"../../mcp/registry.ts\";\nimport { agentLogger } from \"@veryfront/utils/logger/logger.ts\";\n\nexport interface InspectionReport {\n /** Agent information */\n agent: {\n id: string;\n model: string;\n maxSteps: number;\n memoryType: string;\n };\n\n /** Execution details */\n execution: {\n input: string | Message[];\n output: string;\n status: string;\n steps: number;\n executionTime: number;\n };\n\n /** Tool usage */\n tools: {\n called: Array<{\n name: string;\n args: Record<string, unknown>;\n result: unknown;\n executionTime?: number;\n status: string;\n }>;\n available: string[];\n };\n\n /** Memory usage */\n memory: {\n messagesCount: number;\n estimatedTokens: number;\n };\n\n /** Token usage */\n usage?: {\n promptTokens: number;\n completionTokens: number;\n totalTokens: number;\n };\n}\n\n/**\n * Inspect an agent execution\n *\n * @example\n * ```typescript\n * import { inspectAgent } from 'veryfront/ai/dev';\n *\n * const report = await inspectAgent(myAgent, 'Test input');\n * console.log(report);\n * ```\n */\nexport async function inspectAgent(\n agent: Agent,\n input: string | Message[],\n): Promise<InspectionReport> {\n const startTime = Date.now();\n\n // Get memory stats before execution\n const _memoryStatsBefore = await agent.getMemoryStats();\n\n // Execute agent\n const response = await agent.generate({ input });\n\n const executionTime = Date.now() - startTime;\n\n // Get memory stats after execution\n const memoryStatsAfter = await agent.getMemoryStats();\n\n // Get available tools\n const availableTools = agent.config.tools ? Object.keys(agent.config.tools) : [];\n\n return {\n agent: {\n id: agent.id,\n model: agent.config.model,\n maxSteps: agent.config.maxSteps || 20,\n memoryType: agent.config.memory?.type || \"conversation\",\n },\n execution: {\n input,\n output: response.text,\n status: response.status,\n steps: response.toolCalls.length + 1, // Tool calls + final response\n executionTime,\n },\n tools: {\n called: response.toolCalls.map((tc) => ({\n name: tc.name,\n args: tc.args,\n result: tc.result,\n executionTime: tc.executionTime,\n status: tc.status,\n })),\n available: availableTools,\n },\n memory: {\n messagesCount: memoryStatsAfter.totalMessages,\n estimatedTokens: memoryStatsAfter.estimatedTokens,\n },\n usage: response.usage,\n };\n}\n\n/**\n * Print inspection report\n */\nexport function printInspectionReport(report: InspectionReport): void {\n agentLogger.info(\"\\n=== Agent Inspection Report ===\\n\");\n\n agentLogger.info(\"Agent:\");\n agentLogger.info(` ID: ${report.agent.id}`);\n agentLogger.info(` Model: ${report.agent.model}`);\n agentLogger.info(` Max Steps: ${report.agent.maxSteps}`);\n agentLogger.info(` Memory: ${report.agent.memoryType}\\n`);\n\n agentLogger.info(\"Execution:\");\n agentLogger.info(\n ` Input: ${\n typeof report.execution.input === \"string\"\n ? report.execution.input\n : `${(report.execution.input as Message[]).length} messages`\n }`,\n );\n agentLogger.info(` Output: ${report.execution.output.substring(0, 100)}...`);\n agentLogger.info(` Status: ${report.execution.status}`);\n agentLogger.info(` Steps: ${report.execution.steps}`);\n agentLogger.info(` Time: ${report.execution.executionTime}ms\\n`);\n\n agentLogger.info(\"Tools:\");\n agentLogger.info(\n ` Available: ${report.tools.available.length} (${report.tools.available.join(\", \")})`,\n );\n agentLogger.info(` Called: ${report.tools.called.length}`);\n\n if (report.tools.called.length > 0) {\n report.tools.called.forEach((tool, i) => {\n agentLogger.info(` ${i + 1}. ${tool.name}(${JSON.stringify(tool.args)})`);\n agentLogger.info(` Status: ${tool.status}`);\n agentLogger.info(` Time: ${tool.executionTime}ms`);\n agentLogger.info(` Result: ${JSON.stringify(tool.result).substring(0, 100)}...`);\n });\n }\n agentLogger.info(\"\");\n\n agentLogger.info(\"Memory:\");\n agentLogger.info(` Messages: ${report.memory.messagesCount}`);\n agentLogger.info(` Estimated Tokens: ${report.memory.estimatedTokens}\\n`);\n\n if (report.usage) {\n agentLogger.info(\"Token Usage:\");\n agentLogger.info(` Prompt: ${report.usage.promptTokens}`);\n agentLogger.info(` Completion: ${report.usage.completionTokens}`);\n agentLogger.info(` Total: ${report.usage.totalTokens}\\n`);\n }\n}\n\n/**\n * Get MCP registry overview\n */\nexport function getRegistryOverview(): {\n tools: Array<{ id: string; description: string }>;\n resources: Array<{ id: string; pattern: string; description: string }>;\n prompts: Array<{ id: string; description: string }>;\n stats: ReturnType<typeof getMCPStats>;\n} {\n const registry = getMCPRegistry();\n const stats = getMCPStats();\n\n return {\n tools: Array.from(registry.tools.values()).map((t) => ({\n id: t.id,\n description: t.description,\n })),\n resources: Array.from(registry.resources.values()).map((r) => ({\n id: r.id,\n pattern: r.pattern,\n description: r.description,\n })),\n prompts: Array.from(registry.prompts.values()).map((p) => ({\n id: p.id,\n description: p.description,\n })),\n stats,\n };\n}\n\n/**\n * Print registry overview\n */\nexport function printRegistryOverview(): void {\n const overview = getRegistryOverview();\n\n agentLogger.info(\"\\n=== MCP Registry Overview ===\\n\");\n agentLogger.info(`Total: ${overview.stats.total} items\\n`);\n\n agentLogger.info(`Tools (${overview.stats.tools}):`);\n overview.tools.forEach((t) => {\n agentLogger.info(` \u2022 ${t.id}: ${t.description}`);\n });\n agentLogger.info(\"\");\n\n agentLogger.info(`Resources (${overview.stats.resources}):`);\n overview.resources.forEach((r) => {\n agentLogger.info(` \u2022 ${r.id} (${r.pattern}): ${r.description}`);\n });\n agentLogger.info(\"\");\n\n agentLogger.info(`Prompts (${overview.stats.prompts}):`);\n overview.prompts.forEach((p) => {\n agentLogger.info(` \u2022 ${p.id}: ${p.description}`);\n });\n agentLogger.info(\"\");\n}\n"],
|
|
5
|
-
"mappings": ";AAMA,WAAW,OAAO,WAAW,QAAQ;AAAA,EACnC,KAAK;AAAA,IACH,IAAI,KAAiC;AACnC,aAAO,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,cAAY,KAAK,UAAU,SAAS,MAAM,KAAK,IAAI;AACnD,WAAS,MAAM,QAAQ,CAAC,MAAM;AAC5B,gBAAY,KAAK,YAAO,EAAE,EAAE,KAAK,EAAE,WAAW,EAAE;AAAA,EAClD,CAAC;AACD,cAAY,KAAK,EAAE;AAEnB,cAAY,KAAK,cAAc,SAAS,MAAM,SAAS,IAAI;AAC3D,WAAS,UAAU,QAAQ,CAAC,MAAM;AAChC,gBAAY,KAAK,YAAO,EAAE,EAAE,KAAK,EAAE,OAAO,MAAM,EAAE,WAAW,EAAE;AAAA,EACjE,CAAC;AACD,cAAY,KAAK,EAAE;AAEnB,cAAY,KAAK,YAAY,SAAS,MAAM,OAAO,IAAI;AACvD,WAAS,QAAQ,QAAQ,CAAC,MAAM;AAC9B,gBAAY,KAAK,YAAO,EAAE,EAAE,KAAK,EAAE,WAAW,EAAE;AAAA,EAClD,CAAC;AACD,cAAY,KAAK,EAAE;AACrB;",
|
|
4
|
+
"sourcesContent": ["/**\n * Shim for Deno.env in Node.js environment\n * This file is injected by esbuild to provide Deno.env compatibility\n */\n\n// @ts-ignore - Global Deno shim for Node.js\nglobalThis.Deno = globalThis.Deno || {\n env: {\n get(key: string): string | undefined {\n return process.env[key];\n },\n set(key: string, value: string): void {\n process.env[key] = value;\n },\n delete(key: string): void {\n delete process.env[key];\n },\n has(key: string): boolean {\n return key in process.env;\n },\n toObject(): Record<string, string> {\n return { ...process.env } as Record<string, string>;\n },\n },\n};\n", "/**\n * Agent Testing Utilities\n *\n * Utilities for testing agents in development and CI/CD.\n */\n\nimport type { Agent, AgentResponse, Message } from \"../../types/agent.ts\";\n\nexport interface TestCase {\n /** Test name */\n name: string;\n\n /** Input to agent */\n input: string | Message[];\n\n /** Expected output pattern (regex or string) */\n expected?: RegExp | string;\n\n /** Expected tool calls */\n expectToolCalls?: string[];\n\n /** Maximum execution time (ms) */\n timeout?: number;\n\n /** Custom validator */\n validate?: (response: AgentResponse) => boolean | Promise<boolean>;\n}\n\nexport interface TestResult {\n /** Test case name */\n name: string;\n\n /** Pass/fail */\n passed: boolean;\n\n /** Response from agent */\n response?: AgentResponse;\n\n /** Error if test failed */\n error?: string;\n\n /** Execution time */\n executionTime: number;\n\n /** Tool calls made */\n toolCalls: string[];\n}\n\nexport interface TestSuite {\n /** Suite name */\n name: string;\n\n /** Test results */\n results: TestResult[];\n\n /** Overall pass/fail */\n passed: boolean;\n\n /** Total execution time */\n totalTime: number;\n}\n\n/**\n * Test an agent with multiple test cases\n *\n * @example\n * ```typescript\n * import { testAgent } from 'veryfront/ai/dev';\n *\n * const results = await testAgent(myAgent, [\n * {\n * name: 'Simple greeting',\n * input: 'Hello',\n * expected: /hello|hi|hey/i,\n * },\n * {\n * name: 'Tool usage',\n * input: 'Search for AI frameworks',\n * expectToolCalls: ['searchWeb'],\n * },\n * ]);\n *\n * console.log(`Passed: ${results.results.filter(r => r.passed).length}/${results.results.length}`);\n * ```\n */\nexport async function testAgent(\n agent: Agent,\n testCases: TestCase[],\n): Promise<TestSuite> {\n const suite: TestSuite = {\n name: agent.id,\n results: [],\n passed: true,\n totalTime: 0,\n };\n\n const suiteStartTime = Date.now();\n\n for (const testCase of testCases) {\n const result = await runTestCase(agent, testCase);\n suite.results.push(result);\n\n if (!result.passed) {\n suite.passed = false;\n }\n }\n\n suite.totalTime = Date.now() - suiteStartTime;\n\n return suite;\n}\n\n/**\n * Run a single test case\n */\nasync function runTestCase(agent: Agent, testCase: TestCase): Promise<TestResult> {\n const startTime = Date.now();\n\n try {\n // Set timeout\n const timeout = testCase.timeout || 30000;\n const timeoutPromise = new Promise<never>((_, reject) => {\n setTimeout(() => reject(new Error(\"Test timeout\")), timeout);\n });\n\n // Execute agent\n const responsePromise = agent.generate({\n input: testCase.input,\n });\n\n const response = await Promise.race([responsePromise, timeoutPromise]);\n\n const executionTime = Date.now() - startTime;\n const toolCalls = response.toolCalls.map((tc) => tc.name);\n\n // Validate response\n let passed = true;\n let error: string | undefined;\n\n // Check expected output\n if (testCase.expected) {\n if (testCase.expected instanceof RegExp) {\n passed = testCase.expected.test(response.text);\n if (!passed) {\n error = `Output \"${response.text}\" does not match pattern ${testCase.expected}`;\n }\n } else {\n passed = response.text.includes(testCase.expected);\n if (!passed) {\n error = `Output does not contain expected text: \"${testCase.expected}\"`;\n }\n }\n }\n\n // Check expected tool calls\n if (passed && testCase.expectToolCalls) {\n const expectedTools = testCase.expectToolCalls;\n const missingTools = expectedTools.filter((t) => !toolCalls.includes(t));\n\n if (missingTools.length > 0) {\n passed = false;\n error = `Expected tool calls not found: ${missingTools.join(\", \")}`;\n }\n }\n\n // Custom validation\n if (passed && testCase.validate) {\n try {\n passed = await testCase.validate(response);\n if (!passed) {\n error = \"Custom validation failed\";\n }\n } catch (err) {\n passed = false;\n error = `Custom validation error: ${err instanceof Error ? err.message : String(err)}`;\n }\n }\n\n return {\n name: testCase.name,\n passed,\n response,\n error,\n executionTime,\n toolCalls,\n };\n } catch (err) {\n return {\n name: testCase.name,\n passed: false,\n error: err instanceof Error ? err.message : String(err),\n executionTime: Date.now() - startTime,\n toolCalls: [],\n };\n }\n}\n\n/**\n * Print test results in a readable format\n */\nexport function printTestResults(suite: TestSuite): void {\n console.log(`\\n=== Test Suite: ${suite.name} ===\\n`);\n\n const passed = suite.results.filter((r) => r.passed).length;\n const total = suite.results.length;\n\n suite.results.forEach((result, index) => {\n const icon = result.passed ? \"\u2705\" : \"\u274C\";\n console.log(`${icon} ${index + 1}. ${result.name}`);\n\n if (!result.passed && result.error) {\n console.log(` Error: ${result.error}`);\n }\n\n if (result.toolCalls.length > 0) {\n console.log(` Tools used: ${result.toolCalls.join(\", \")}`);\n }\n\n console.log(` Time: ${result.executionTime}ms\\n`);\n });\n\n console.log(`Results: ${passed}/${total} passed`);\n console.log(`Total time: ${suite.totalTime}ms`);\n console.log(`Status: ${suite.passed ? \"\u2705 PASSED\" : \"\u274C FAILED\"}\\n`);\n}\n\n/**\n * Assert that an agent response contains text\n */\nexport function assertContains(response: AgentResponse, text: string): boolean {\n return response.text.toLowerCase().includes(text.toLowerCase());\n}\n\n/**\n * Assert that an agent called a specific tool\n */\nexport function assertToolCalled(response: AgentResponse, toolName: string): boolean {\n return response.toolCalls.some((tc) => tc.name === toolName);\n}\n\n/**\n * Assert that an agent completed successfully\n */\nexport function assertCompleted(response: AgentResponse): boolean {\n return response.status === \"completed\";\n}\n", "/**\n * Tool Testing Utilities\n *\n * Utilities for testing individual tools.\n */\n\nimport type { Tool } from \"../../types/tool.ts\";\n\nexport interface ToolTestCase {\n /** Test name */\n name: string;\n\n /** Tool input */\n input: any;\n\n /** Expected output (partial match) */\n expectedOutput?: any;\n\n /** Custom validator */\n validate?: (result: any) => boolean | Promise<boolean>;\n\n /** Should throw error */\n shouldThrow?: boolean;\n\n /** Expected error message pattern */\n expectedError?: RegExp | string;\n}\n\nexport interface ToolTestResult {\n /** Test case name */\n name: string;\n\n /** Pass/fail */\n passed: boolean;\n\n /** Tool result */\n result?: any;\n\n /** Error if test failed */\n error?: string;\n\n /** Execution time */\n executionTime: number;\n}\n\n/**\n * Test a tool with multiple test cases\n *\n * @example\n * ```typescript\n * import { testTool } from 'veryfront/ai/dev';\n *\n * const results = await testTool(calculatorTool, [\n * {\n * name: 'Addition',\n * input: { operation: 'add', a: 2, b: 3 },\n * expectedOutput: { result: 5 },\n * },\n * {\n * name: 'Division by zero',\n * input: { operation: 'divide', a: 5, b: 0 },\n * shouldThrow: true,\n * expectedError: /cannot divide by zero/i,\n * },\n * ]);\n * ```\n */\nexport async function testTool(\n tool: Tool,\n testCases: ToolTestCase[],\n): Promise<ToolTestResult[]> {\n const results: ToolTestResult[] = [];\n\n for (const testCase of testCases) {\n const result = await runToolTest(tool, testCase);\n results.push(result);\n }\n\n return results;\n}\n\n/**\n * Run a single tool test\n */\nasync function runToolTest(\n tool: Tool,\n testCase: ToolTestCase,\n): Promise<ToolTestResult> {\n const startTime = Date.now();\n\n try {\n // Execute tool\n const result = await tool.execute(testCase.input);\n const executionTime = Date.now() - startTime;\n\n // If we expected an error but didn't get one\n if (testCase.shouldThrow) {\n return {\n name: testCase.name,\n passed: false,\n error: \"Expected tool to throw error but it succeeded\",\n executionTime,\n };\n }\n\n // Validate output\n let passed = true;\n let error: string | undefined;\n\n if (testCase.expectedOutput !== undefined) {\n passed = deepMatch(result, testCase.expectedOutput);\n if (!passed) {\n error = `Output mismatch. Expected: ${JSON.stringify(testCase.expectedOutput)}, Got: ${\n JSON.stringify(result)\n }`;\n }\n }\n\n if (passed && testCase.validate) {\n try {\n passed = await testCase.validate(result);\n if (!passed) {\n error = \"Custom validation failed\";\n }\n } catch (err) {\n passed = false;\n error = `Validation error: ${err instanceof Error ? err.message : String(err)}`;\n }\n }\n\n return {\n name: testCase.name,\n passed,\n result,\n error,\n executionTime,\n };\n } catch (err) {\n const executionTime = Date.now() - startTime;\n const errorMessage = err instanceof Error ? err.message : String(err);\n\n // If we expected an error\n if (testCase.shouldThrow) {\n let passed = true;\n let error: string | undefined;\n\n if (testCase.expectedError) {\n if (testCase.expectedError instanceof RegExp) {\n passed = testCase.expectedError.test(errorMessage);\n } else {\n passed = errorMessage.includes(testCase.expectedError);\n }\n\n if (!passed) {\n error =\n `Error message mismatch. Expected pattern: ${testCase.expectedError}, Got: ${errorMessage}`;\n }\n }\n\n return {\n name: testCase.name,\n passed,\n error,\n executionTime,\n };\n }\n\n // Unexpected error\n return {\n name: testCase.name,\n passed: false,\n error: `Unexpected error: ${errorMessage}`,\n executionTime,\n };\n }\n}\n\n/**\n * Deep match for partial object comparison\n */\nfunction deepMatch(actual: any, expected: any): boolean {\n if (expected === actual) return true;\n if (typeof expected !== \"object\" || expected === null) return false;\n if (typeof actual !== \"object\" || actual === null) return false;\n\n for (const key in expected) {\n if (!(key in actual)) return false;\n\n const expectedValue = expected[key];\n const actualValue = actual[key];\n\n if (typeof expectedValue === \"object\" && expectedValue !== null) {\n if (!deepMatch(actualValue, expectedValue)) return false;\n } else {\n if (actualValue !== expectedValue) return false;\n }\n }\n\n return true;\n}\n\n/**\n * Print tool test results\n */\nexport function printToolTestResults(\n toolId: string,\n results: ToolTestResult[],\n): void {\n console.log(`\\n=== Tool Tests: ${toolId} ===\\n`);\n\n const passed = results.filter((r) => r.passed).length;\n const total = results.length;\n\n results.forEach((result, index) => {\n const icon = result.passed ? \"\u2705\" : \"\u274C\";\n console.log(`${icon} ${index + 1}. ${result.name}`);\n\n if (!result.passed && result.error) {\n console.log(` Error: ${result.error}`);\n }\n\n if (result.result !== undefined) {\n console.log(` Result: ${JSON.stringify(result.result)}`);\n }\n\n console.log(` Time: ${result.executionTime}ms\\n`);\n });\n\n console.log(`Results: ${passed}/${total} passed`);\n console.log(`Status: ${passed === total ? \"\u2705 ALL PASSED\" : \"\u274C SOME FAILED\"}\\n`);\n}\n", "import type { z } from \"zod\";\nimport { ZodFirstPartyTypeKind } from \"zod\";\nimport type { JsonSchema } from \"../types/json-schema.ts\";\n\nexport function zodToJsonSchema(schema: z.ZodTypeAny): JsonSchema {\n // Guard against invalid schemas (can happen with different zod instances in npm bundle)\n if (!schema || typeof schema !== \"object\" || !(\"_def\" in schema)) {\n throw new Error(\"Invalid Zod schema: missing _def property\");\n }\n\n const details = unwrapSchema(schema);\n const json = convert(details.schema);\n if (details.nullable) {\n return { anyOf: [json, { type: \"null\" }] };\n }\n return json;\n}\n\nexport function isOptionalSchema(schema: z.ZodTypeAny): boolean {\n const { optional } = unwrapSchema(schema);\n return optional;\n}\n\nfunction convert(schema: z.ZodTypeAny): JsonSchema {\n switch (schema._def.typeName) {\n case ZodFirstPartyTypeKind.ZodString:\n return { type: \"string\" };\n case ZodFirstPartyTypeKind.ZodNumber:\n return { type: \"number\" };\n case ZodFirstPartyTypeKind.ZodBoolean:\n return { type: \"boolean\" };\n case ZodFirstPartyTypeKind.ZodBigInt:\n return { type: \"integer\" };\n case ZodFirstPartyTypeKind.ZodLiteral: {\n const literal = (schema as z.ZodLiteral<unknown>)._def.value;\n return {\n const: literal,\n type: typeof literal === \"string\"\n ? \"string\"\n : typeof literal === \"number\"\n ? \"number\"\n : typeof literal === \"boolean\"\n ? \"boolean\"\n : undefined,\n };\n }\n case ZodFirstPartyTypeKind.ZodEnum:\n return {\n type: \"string\",\n enum: (schema as z.ZodEnum<[string, ...string[]]>)._def.values,\n };\n case ZodFirstPartyTypeKind.ZodNativeEnum:\n return {\n enum: Object.values((schema as z.ZodNativeEnum<any>)._def.values).filter(\n (value) => typeof value !== \"number\",\n ),\n };\n case ZodFirstPartyTypeKind.ZodObject: {\n const obj = schema as z.ZodObject<any>;\n const properties: Record<string, JsonSchema> = {};\n const required: string[] = [];\n\n // Access shape - it might be a function (lazy getter) or an object\n const shape = typeof obj._def.shape === \"function\" ? obj._def.shape() : obj._def.shape;\n\n for (const [key, value] of Object.entries(shape || {})) {\n const zodSchema = value as z.ZodTypeAny;\n properties[key] = zodToJsonSchema(zodSchema);\n if (!isOptionalSchema(zodSchema)) {\n required.push(key);\n }\n }\n\n const json: JsonSchema = { type: \"object\", properties };\n if (required.length > 0) {\n json.required = required;\n }\n return json;\n }\n case ZodFirstPartyTypeKind.ZodArray: {\n const array = schema as z.ZodArray<z.ZodTypeAny>;\n return {\n type: \"array\",\n items: zodToJsonSchema(array._def.type),\n };\n }\n case ZodFirstPartyTypeKind.ZodTuple: {\n const tuple = schema as z.ZodTuple;\n return {\n type: \"array\",\n prefixItems: tuple._def.items.map((item) => zodToJsonSchema(item)),\n minItems: tuple._def.items.length,\n maxItems: tuple._def.items.length,\n };\n }\n case ZodFirstPartyTypeKind.ZodUnion: {\n const union = schema as z.ZodUnion<[z.ZodTypeAny, z.ZodTypeAny, ...z.ZodTypeAny[]]>;\n return {\n anyOf: union._def.options.map((option) => zodToJsonSchema(option)),\n };\n }\n case ZodFirstPartyTypeKind.ZodDiscriminatedUnion: {\n const union = schema as z.ZodDiscriminatedUnion<string, z.ZodObject<any>[]>;\n return {\n anyOf: Array.from(union._def.options.values()).map((option) => zodToJsonSchema(option)),\n };\n }\n case ZodFirstPartyTypeKind.ZodRecord:\n return {\n type: \"object\",\n additionalProperties: zodToJsonSchema((schema as z.ZodRecord<any>)._def.valueType),\n };\n case ZodFirstPartyTypeKind.ZodDefault: {\n const def = schema as z.ZodDefault<z.ZodTypeAny>;\n const inner = zodToJsonSchema(def._def.innerType);\n const defaultValue = def._def.defaultValue();\n if (typeof inner === \"object\" && !(\"anyOf\" in inner)) {\n inner.default = defaultValue;\n }\n return inner;\n }\n case ZodFirstPartyTypeKind.ZodLazy:\n return convert((schema as z.ZodLazy<any>)._def.getter());\n case ZodFirstPartyTypeKind.ZodEffects:\n return convert((schema as z.ZodEffects<any>)._def.schema);\n default:\n return { type: \"object\" };\n }\n}\n\nfunction unwrapSchema(schema: z.ZodTypeAny) {\n let current: z.ZodTypeAny = schema;\n let nullable = false;\n let optional = false;\n\n while (true) {\n switch (current._def.typeName) {\n case ZodFirstPartyTypeKind.ZodNullable:\n nullable = true;\n current = (current as z.ZodNullable<z.ZodTypeAny>)._def.innerType;\n continue;\n case ZodFirstPartyTypeKind.ZodOptional:\n optional = true;\n current = (current as z.ZodOptional<z.ZodTypeAny>)._def.innerType;\n continue;\n case ZodFirstPartyTypeKind.ZodEffects:\n current = (current as z.ZodEffects<any>)._def.schema;\n continue;\n default:\n return { schema: current, nullable, optional };\n }\n }\n}\n", "export interface GlobalWithDeno {\n Deno?: {\n env: {\n get(key: string): string | undefined;\n };\n };\n}\n\nexport interface GlobalWithProcess {\n process?: {\n env: Record<string, string | undefined>;\n version?: string;\n versions?: Record<string, string>;\n };\n}\n\nexport interface GlobalWithBun {\n Bun?: {\n version: string;\n };\n}\n\nexport function hasDenoRuntime(global: unknown): global is GlobalWithDeno {\n return (\n typeof global === \"object\" &&\n global !== null &&\n \"Deno\" in global &&\n typeof (global as GlobalWithDeno).Deno?.env?.get === \"function\"\n );\n}\n\nexport function hasNodeProcess(global: unknown): global is GlobalWithProcess {\n return (\n typeof global === \"object\" &&\n global !== null &&\n \"process\" in global &&\n typeof (global as GlobalWithProcess).process?.env === \"object\"\n );\n}\n\nexport function hasBunRuntime(global: unknown): global is GlobalWithBun {\n return (\n typeof global === \"object\" &&\n global !== null &&\n \"Bun\" in global &&\n typeof (global as GlobalWithBun).Bun !== \"undefined\"\n );\n}\n", "import type { GlobalWithDeno, GlobalWithProcess } from \"../runtime-guards.ts\";\nimport { hasDenoRuntime, hasNodeProcess } from \"../runtime-guards.ts\";\n\nexport function getEnvironmentVariable(name: string): string | undefined {\n try {\n if (typeof Deno !== \"undefined\" && hasDenoRuntime(globalThis)) {\n const value = (globalThis as GlobalWithDeno).Deno?.env.get(name);\n return value === \"\" ? undefined : value;\n }\n if (hasNodeProcess(globalThis)) {\n const value = (globalThis as GlobalWithProcess).process?.env[name];\n return value === \"\" ? undefined : value;\n }\n } catch {\n return undefined;\n }\n return undefined;\n}\n\nexport function isTestEnvironment(): boolean {\n return getEnvironmentVariable(\"NODE_ENV\") === \"test\";\n}\n\nexport function isProductionEnvironment(): boolean {\n return getEnvironmentVariable(\"NODE_ENV\") === \"production\";\n}\n\nexport function isDevelopmentEnvironment(): boolean {\n const env = getEnvironmentVariable(\"NODE_ENV\");\n return env === \"development\" || env === undefined;\n}\n", "import { getEnvironmentVariable } from \"./env.ts\";\n\nexport enum LogLevel {\n DEBUG = 0,\n INFO = 1,\n WARN = 2,\n ERROR = 3,\n}\n\nexport interface Logger {\n debug(message: string, ...args: unknown[]): void;\n info(message: string, ...args: unknown[]): void;\n warn(message: string, ...args: unknown[]): void;\n error(message: string, ...args: unknown[]): void;\n time<T>(label: string, fn: () => Promise<T>): Promise<T>;\n}\n\nconst originalConsole = {\n debug: console.debug,\n log: console.log,\n warn: console.warn,\n error: console.error,\n};\n\nlet cachedLogLevel: LogLevel | undefined;\n\nfunction resolveLogLevel(force = false): LogLevel {\n if (force || cachedLogLevel === undefined) {\n cachedLogLevel = getDefaultLevel();\n }\n return cachedLogLevel;\n}\n\nclass ConsoleLogger implements Logger {\n constructor(\n private prefix: string,\n private level: LogLevel = resolveLogLevel(),\n ) {}\n\n setLevel(level: LogLevel): void {\n this.level = level;\n }\n\n getLevel(): LogLevel {\n return this.level;\n }\n\n debug(message: string, ...args: unknown[]): void {\n if (this.level <= LogLevel.DEBUG) {\n console.debug(`[${this.prefix}] DEBUG: ${message}`, ...args);\n }\n }\n\n info(message: string, ...args: unknown[]): void {\n if (this.level <= LogLevel.INFO) {\n console.log(`[${this.prefix}] ${message}`, ...args);\n }\n }\n\n warn(message: string, ...args: unknown[]): void {\n if (this.level <= LogLevel.WARN) {\n console.warn(`[${this.prefix}] WARN: ${message}`, ...args);\n }\n }\n\n error(message: string, ...args: unknown[]): void {\n if (this.level <= LogLevel.ERROR) {\n console.error(`[${this.prefix}] ERROR: ${message}`, ...args);\n }\n }\n\n async time<T>(label: string, fn: () => Promise<T>): Promise<T> {\n const start = performance.now();\n try {\n const result = await fn();\n const end = performance.now();\n this.debug(`${label} completed in ${(end - start).toFixed(2)}ms`);\n return result;\n } catch (error) {\n const end = performance.now();\n this.error(`${label} failed after ${(end - start).toFixed(2)}ms`, error);\n throw error;\n }\n }\n}\n\nfunction parseLogLevel(levelString: string | undefined): LogLevel | undefined {\n if (!levelString) return undefined;\n const upper = levelString.toUpperCase();\n switch (upper) {\n case \"DEBUG\":\n return LogLevel.DEBUG;\n case \"WARN\":\n return LogLevel.WARN;\n case \"ERROR\":\n return LogLevel.ERROR;\n case \"INFO\":\n return LogLevel.INFO;\n default:\n return undefined;\n }\n}\n\nconst getDefaultLevel = (): LogLevel => {\n const envLevel = getEnvironmentVariable(\"LOG_LEVEL\");\n const parsedLevel = parseLogLevel(envLevel);\n if (parsedLevel !== undefined) return parsedLevel;\n\n const debugFlag = getEnvironmentVariable(\"VERYFRONT_DEBUG\");\n if (debugFlag === \"1\" || debugFlag === \"true\") return LogLevel.DEBUG;\n\n return LogLevel.INFO;\n};\n\nconst trackedLoggers = new Set<ConsoleLogger>();\n\nfunction createLogger(prefix: string): ConsoleLogger {\n const logger = new ConsoleLogger(prefix);\n trackedLoggers.add(logger);\n return logger;\n}\n\nexport const cliLogger = createLogger(\"CLI\");\nexport const serverLogger = createLogger(\"SERVER\");\nexport const rendererLogger = createLogger(\"RENDERER\");\nexport const bundlerLogger = createLogger(\"BUNDLER\");\nexport const agentLogger = createLogger(\"AGENT\");\n\nexport const logger = createLogger(\"VERYFRONT\");\n\ntype LoggerResetOptions = {\n restoreConsole?: boolean;\n};\n\nexport function __loggerResetForTests(options: LoggerResetOptions = {}): void {\n const updatedLevel = resolveLogLevel(true);\n for (const instance of trackedLoggers) {\n instance.setLevel(updatedLevel);\n }\n\n if (options.restoreConsole) {\n console.debug = originalConsole.debug;\n console.log = originalConsole.log;\n console.warn = originalConsole.warn;\n console.error = originalConsole.error;\n }\n}\n", "export interface BuildContext {\n file?: string;\n line?: number;\n column?: number;\n moduleId?: string;\n phase?: \"parse\" | \"transform\" | \"bundle\" | \"optimize\";\n}\n\nexport interface APIContext {\n endpoint?: string;\n method?: string;\n statusCode?: number;\n headers?: Record<string, string>;\n}\n\nexport interface RenderContext {\n component?: string;\n route?: string;\n phase?: \"server\" | \"client\" | \"hydration\";\n props?: unknown;\n}\n\nexport interface ConfigContext {\n configFile?: string;\n field?: string;\n value?: unknown;\n expected?: string;\n}\n\nexport interface AgentContext {\n agentId?: string;\n intent?: string;\n timeout?: number;\n}\n\nexport interface FileContext {\n path?: string;\n operation?: \"read\" | \"write\" | \"delete\" | \"mkdir\";\n permissions?: string;\n}\n\nexport interface NetworkContext {\n url?: string;\n timeout?: number;\n retryCount?: number;\n}\n\nexport type VeryfrontError =\n | { type: \"build\"; message: string; context?: BuildContext }\n | { type: \"api\"; message: string; context?: APIContext }\n | { type: \"render\"; message: string; context?: RenderContext }\n | { type: \"config\"; message: string; context?: ConfigContext }\n | { type: \"agent\"; message: string; context?: AgentContext }\n | { type: \"file\"; message: string; context?: FileContext }\n | { type: \"network\"; message: string; context?: NetworkContext }\n | { type: \"permission\"; message: string; context?: FileContext }\n | { type: \"not_supported\"; message: string; feature?: string };\n\nexport function createError(error: VeryfrontError): VeryfrontError {\n return error;\n}\n\nexport function isBuildError(\n error: VeryfrontError,\n): error is Extract<VeryfrontError, { type: \"build\" }> {\n return error.type === \"build\";\n}\n\nexport function isAPIError(\n error: VeryfrontError,\n): error is Extract<VeryfrontError, { type: \"api\" }> {\n return error.type === \"api\";\n}\n\nexport function isRenderError(\n error: VeryfrontError,\n): error is Extract<VeryfrontError, { type: \"render\" }> {\n return error.type === \"render\";\n}\n\nexport function isConfigError(\n error: VeryfrontError,\n): error is Extract<VeryfrontError, { type: \"config\" }> {\n return error.type === \"config\";\n}\n\nexport function isAgentError(\n error: VeryfrontError,\n): error is Extract<VeryfrontError, { type: \"agent\" }> {\n return error.type === \"agent\";\n}\n\nexport function isFileError(\n error: VeryfrontError,\n): error is Extract<VeryfrontError, { type: \"file\" }> {\n return error.type === \"file\";\n}\n\nexport function isNetworkError(\n error: VeryfrontError,\n): error is Extract<VeryfrontError, { type: \"network\" }> {\n return error.type === \"network\";\n}\n\nexport function toError(veryfrontError: VeryfrontError): Error {\n const error = new Error(veryfrontError.message);\n error.name = `VeryfrontError[${veryfrontError.type}]`;\n Object.defineProperty(error, \"context\", {\n value: veryfrontError,\n enumerable: false,\n configurable: true,\n });\n return error;\n}\n\nexport function fromError(error: unknown): VeryfrontError | null {\n if (error && typeof error === \"object\" && \"context\" in error) {\n // Safe access after 'in' check\n const context = (error as Record<string, unknown>).context;\n if (\n context &&\n typeof context === \"object\" &&\n \"type\" in context &&\n \"message\" in context\n ) {\n return context as VeryfrontError;\n }\n }\n return null;\n}\n\nexport function logError(\n error: VeryfrontError,\n logger?: { error: (msg: string, ...args: unknown[]) => void },\n): void {\n const log = logger || console;\n const context = \"context\" in error ? error.context || {} : {};\n log.error(`[${error.type}] ${error.message}`, context);\n}\n", "import type { Tool, ToolConfig, ToolDefinition, ToolExecutionContext } from \"../types/tool.ts\";\nimport type { JsonSchema } from \"../types/json-schema.ts\";\nimport { zodToJsonSchema } from \"./zod-json-schema.ts\";\nimport { agentLogger } from \"../../core/utils/logger/logger.ts\";\nimport { createError, toError } from \"../../core/errors/veryfront-error.ts\";\n\n/**\n * Create a tool\n *\n * @example\n * ```typescript\n * import { tool } from 'veryfront/ai';\n * import { z } from 'zod';\n\n *\n * export default tool({\n * description: 'Search the web',\n * inputSchema: z.object({\n * query: z.string(),\n * }),\n * execute: async ({ query }) => {\n * const results = await searchWeb(query);\n * return results;\n * },\n * });\n * ```\n */\nexport function tool<TInput = any, TOutput = any>(\n config: ToolConfig<TInput, TOutput>,\n): Tool<TInput, TOutput> {\n const id = config.id || generateToolId();\n\n // Check if we have a valid zod schema (has _def property)\n const hasValidZodSchema = config.inputSchema &&\n typeof config.inputSchema === \"object\" &&\n \"_def\" in config.inputSchema &&\n (config.inputSchema as { _def?: { typeName?: string } })._def?.typeName;\n\n // Pre-convert Zod schema to JSON Schema immediately\n // This happens BEFORE any bundling, in a clean environment\n let inputSchemaJson: JsonSchema | undefined;\n if (hasValidZodSchema) {\n try {\n inputSchemaJson = zodToJsonSchema(config.inputSchema);\n agentLogger.info(\n `[TOOL] Pre-converted schema for \"${id}\": ${\n Object.keys(inputSchemaJson.properties || {}).length\n } properties`,\n );\n } catch (error) {\n agentLogger.warn(`[TOOL] Failed to pre-convert schema for \"${id}\":`, error);\n // Continue without pre-converted schema - will fall back to runtime conversion\n }\n } else {\n // Try to introspect the schema from external zod instance\n const externalSchema = config.inputSchema as {\n _def?: {\n typeName?: string;\n shape?: (() => Record<string, unknown>) | Record<string, unknown>;\n };\n };\n\n if (externalSchema?._def?.shape) {\n try {\n const shape = typeof externalSchema._def.shape === \"function\"\n ? externalSchema._def.shape()\n : externalSchema._def.shape;\n\n // Build JSON Schema from shape inspection\n const properties: Record<string, JsonSchema> = {};\n for (const key of Object.keys(shape || {})) {\n // Default to string type for unknown schemas\n properties[key] = { type: \"string\" as const };\n }\n inputSchemaJson = {\n type: \"object\" as const,\n properties,\n required: Object.keys(properties),\n };\n agentLogger.info(\n `[TOOL] Introspected schema for \"${id}\" from external zod: ${\n Object.keys(properties).length\n } properties`,\n );\n } catch {\n inputSchemaJson = { type: \"object\", properties: {} };\n agentLogger.warn(\n `[TOOL] Schema for \"${id}\" could not be introspected. Using empty schema.`,\n );\n }\n } else {\n agentLogger.warn(\n `[TOOL] Schema for \"${id}\" is not a valid Zod schema (different zod instance?). ` +\n `Skipping pre-conversion. Input validation may be limited.`,\n );\n // Create a basic schema from inspection if possible\n inputSchemaJson = { type: \"object\", properties: {} };\n }\n }\n\n return {\n id,\n type: \"function\" as const,\n description: config.description,\n inputSchema: config.inputSchema,\n inputSchemaJson, // Store pre-converted schema\n execute: async (input: TInput, context?: ToolExecutionContext) => {\n // Validate input if zod schema is available\n if (hasValidZodSchema) {\n try {\n config.inputSchema.parse(input);\n } catch (error) {\n throw toError(createError({\n type: \"agent\",\n message: `Tool \"${id}\" input validation failed: ${\n error instanceof Error ? error.message : String(error)\n }`,\n }));\n }\n } else if (\n config.inputSchema &&\n typeof config.inputSchema === \"object\" &&\n \"parse\" in config.inputSchema &&\n typeof (config.inputSchema as { parse?: unknown }).parse === \"function\"\n ) {\n // Try to use parse method if available (external zod instance)\n try {\n (config.inputSchema as { parse: (input: unknown) => void }).parse(input);\n } catch (error) {\n throw toError(createError({\n type: \"agent\",\n message: `Tool \"${id}\" input validation failed: ${\n error instanceof Error ? error.message : String(error)\n }`,\n }));\n }\n }\n\n // Execute tool\n return await config.execute(input, context);\n },\n mcp: config.mcp,\n };\n}\n\n/**\n * Configuration for dynamic tools where input/output types are unknown at compile time\n */\nexport interface DynamicToolConfig {\n /** Tool identifier (optional, auto-generated if not provided) */\n id?: string;\n\n /** Tool description for the AI model */\n description: string;\n\n /**\n * Input schema - any Zod schema is accepted. For dynamic tools where the input shape\n * is truly unknown at compile time, it is recommended to use z.unknown(), z.any(),\n * or z.object({}). A schema is still required for validation even though types are unknown.\n */\n inputSchema: unknown;\n\n /**\n * Tool execution function - input is typed as unknown and must be validated/cast at runtime\n */\n execute: (\n input: unknown,\n context?: ToolExecutionContext,\n ) => Promise<unknown> | unknown;\n\n /**\n * Optional conversion function that maps the tool result to an output\n * that can be used by the language model\n */\n toModelOutput?: (output: unknown) => unknown;\n\n /** MCP configuration */\n mcp?: {\n /** Expose via MCP */\n enabled?: boolean;\n /** Require authentication */\n requiresAuth?: boolean;\n /** Cache policy */\n cachePolicy?: \"no-cache\" | \"cache\" | \"cache-first\";\n };\n}\n\n/**\n * Create a dynamic tool where input/output types are not known at compile time.\n *\n * Use this for:\n * - MCP (Model Context Protocol) tools without schemas\n * - User-defined functions loaded at runtime\n * - Tools loaded from external sources or databases\n * - Dynamic tool generation based on user input\n *\n * @example\n * ```typescript\n * import { dynamicTool } from 'veryfront/ai';\n * import { z } from 'zod';\n *\n * export const customTool = dynamicTool({\n * description: 'Execute a custom user-defined function',\n * inputSchema: z.object({}),\n * execute: async (input) => {\n * // input is typed as 'unknown' - validate/cast at runtime\n * const { action, parameters } = input as any;\n * return { result: `Executed ${action}` };\n * },\n * });\n * ```\n */\nexport function dynamicTool(config: DynamicToolConfig): Tool<unknown, unknown> {\n const id = config.id || generateToolId();\n\n // Try to convert schema to JSON Schema if possible\n let inputSchemaJson: JsonSchema | undefined;\n\n // Check if it's a zod-like schema with _def\n const zodLikeSchema = config.inputSchema as {\n _def?: { typeName?: string; shape?: (() => Record<string, unknown>) | Record<string, unknown> };\n };\n\n if (zodLikeSchema?._def?.typeName) {\n try {\n // deno-lint-ignore no-explicit-any\n inputSchemaJson = zodToJsonSchema(config.inputSchema as any);\n agentLogger.info(\n `[DYNAMIC_TOOL] Converted schema for \"${id}\": ${\n Object.keys(inputSchemaJson.properties || {}).length\n } properties`,\n );\n } catch {\n // For z.unknown() or z.any(), create a permissive schema\n inputSchemaJson = { type: \"object\", properties: {}, additionalProperties: true };\n agentLogger.info(`[DYNAMIC_TOOL] Using permissive schema for \"${id}\"`);\n }\n } else if (zodLikeSchema?._def?.shape) {\n // Try to introspect shape\n try {\n const shape = typeof zodLikeSchema._def.shape === \"function\"\n ? zodLikeSchema._def.shape()\n : zodLikeSchema._def.shape;\n\n const properties: Record<string, JsonSchema> = {};\n for (const key of Object.keys(shape || {})) {\n properties[key] = { type: \"string\" as const };\n }\n inputSchemaJson = {\n type: \"object\" as const,\n properties,\n additionalProperties: true,\n };\n agentLogger.info(`[DYNAMIC_TOOL] Introspected schema for \"${id}\"`);\n } catch {\n inputSchemaJson = { type: \"object\", properties: {}, additionalProperties: true };\n }\n } else {\n // Fully dynamic - accept anything\n inputSchemaJson = { type: \"object\", properties: {}, additionalProperties: true };\n agentLogger.info(`[DYNAMIC_TOOL] Using fully dynamic schema for \"${id}\"`);\n }\n\n return {\n id,\n type: \"dynamic\" as const,\n description: config.description,\n inputSchema: config.inputSchema as any,\n inputSchemaJson,\n execute: async (input: unknown, context?: ToolExecutionContext) => {\n // For dynamic tools, we skip input validation entirely.\n // The tool implementation is responsible for runtime validation.\n const result = await config.execute(input, context);\n\n // Apply output transformation if provided\n if (config.toModelOutput) {\n return config.toModelOutput(result);\n }\n\n return result;\n },\n mcp: config.mcp,\n };\n}\n\n/**\n * Generate a unique tool ID\n */\nlet toolIdCounter = 0;\nfunction generateToolId(): string {\n return `tool_${Date.now()}_${toolIdCounter++}`;\n}\n\n/**\n * Tool registry for managing tools\n */\nclass ToolRegistryClass {\n private tools = new Map<string, Tool>();\n\n register(id: string, toolInstance: Tool): void {\n if (this.tools.has(id)) {\n // Debug level - overwriting is expected during hot reload and re-discovery\n agentLogger.debug(`Tool \"${id}\" is already registered. Overwriting.`);\n }\n\n this.tools.set(id, toolInstance);\n }\n\n /**\n * Get a tool by ID\n */\n get(id: string): Tool | undefined {\n return this.tools.get(id);\n }\n\n /**\n * Check if a tool exists\n */\n has(id: string): boolean {\n return this.tools.has(id);\n }\n\n /**\n * Get all tool IDs\n */\n getAllIds(): string[] {\n return Array.from(this.tools.keys());\n }\n\n /**\n * Get all tools\n */\n getAll(): Map<string, Tool> {\n return new Map(this.tools);\n }\n\n /**\n * Clear all tools (for testing)\n */\n clear(): void {\n this.tools.clear();\n }\n\n getToolsForProvider(): ToolDefinition[] {\n return Array.from(this.tools.values()).map(toolToProviderDefinition);\n }\n}\n\n// Singleton instance using globalThis to share across module contexts\n// This is necessary for esbuild-bundled API routes to access the same registry\nconst TOOL_REGISTRY_KEY = \"__veryfront_tool_registry__\";\n// deno-lint-ignore no-explicit-any\nconst _globalTool = globalThis as any;\nexport const toolRegistry: ToolRegistryClass = _globalTool[TOOL_REGISTRY_KEY] ||=\n new ToolRegistryClass();\n\nexport function toolToProviderDefinition(tool: Tool): ToolDefinition {\n // Use pre-converted JSON Schema if available (preferred)\n // Fall back to runtime conversion if needed\n const jsonSchema = tool.inputSchemaJson || zodToJsonSchema(tool.inputSchema);\n\n agentLogger.info(\n `[TOOL] Using ${\n tool.inputSchemaJson ? \"pre-converted\" : \"runtime-converted\"\n } schema for \"${tool.id}\"`,\n );\n\n return {\n name: tool.id,\n description: tool.description,\n parameters: jsonSchema,\n };\n}\n\n/**\n * Execute a tool by ID\n */\nexport async function executeTool(\n toolId: string,\n input: unknown,\n context?: ToolExecutionContext,\n): Promise<unknown> {\n const tool = toolRegistry.get(toolId);\n\n if (!tool) {\n throw toError(createError({\n type: \"agent\",\n message: `Tool \"${toolId}\" not found`,\n }));\n }\n\n try {\n const result = await tool.execute(input, context);\n return result;\n } catch (error) {\n throw toError(createError({\n type: \"agent\",\n message: `Tool \"${toolId}\" execution failed: ${\n error instanceof Error ? error.message : String(error)\n }`,\n }));\n }\n}\n\nexport { zodToJsonSchema } from \"./zod-json-schema.ts\";\n", "/**\n * MCP Resource factory and utilities\n */\n\nimport type { Resource, ResourceConfig } from \"../types/mcp.ts\";\nimport { agentLogger } from \"../../core/utils/logger/logger.ts\";\nimport { createError, toError } from \"../../core/errors/veryfront-error.ts\";\n\n/**\n * Create an MCP resource\n *\n * @example\n * ```typescript\n * import { resource } from 'veryfront/ai';\n * import { z } from 'zod';\n\n *\n * export default resource({\n * description: 'Get user profile',\n * paramsSchema: z.object({\n * userId: z.string(),\n * }),\n * load: async ({ userId }) => {\n * return await db.users.findUnique({ where: { id: userId } });\n * },\n * });\n * ```\n */\nexport function resource<TParams = any, TData = any>(\n config: ResourceConfig<TParams, TData>,\n): Resource<TParams, TData> {\n // Generate pattern if not provided\n const pattern = config.pattern || generateResourcePattern();\n\n // Generate ID from pattern\n const id = patternToId(pattern);\n\n return {\n id,\n pattern,\n description: config.description,\n paramsSchema: config.paramsSchema,\n load: async (params: TParams) => {\n // Validate params\n try {\n config.paramsSchema.parse(params);\n } catch (error) {\n throw toError(createError({\n type: \"agent\",\n message: `Resource \"${id}\" params validation failed: ${\n error instanceof Error ? error.message : String(error)\n }`,\n }));\n }\n\n return await config.load(params);\n },\n subscribe: config.subscribe,\n mcp: config.mcp,\n };\n}\n\n/**\n * Generate resource pattern fallback\n * Note: In practice, resources should explicitly define their pattern.\n * Auto-discovery is handled by the discovery.ts module which scans\n * the filesystem and extracts patterns from resource definitions.\n */\nfunction generateResourcePattern(): string {\n return `/resource_${Date.now()}`;\n}\n\n/**\n * Convert path pattern to ID\n * Example: \"/users/:userId/profile\" -> \"users_userId_profile\"\n */\nfunction patternToId(pattern: string): string {\n return pattern\n .replace(/^\\//, \"\")\n .replace(/\\//g, \"_\")\n .replace(/:/g, \"\");\n}\n\n/**\n * Resource registry\n */\nclass ResourceRegistryClass {\n private resources = new Map<string, Resource>();\n\n /**\n * Register a resource\n */\n register(id: string, resourceInstance: Resource): void {\n if (this.resources.has(id)) {\n // Debug level - overwriting is expected during hot reload and re-discovery\n agentLogger.debug(`Resource \"${id}\" is already registered. Overwriting.`);\n }\n\n this.resources.set(id, resourceInstance);\n }\n\n /**\n * Get a resource by ID\n */\n get(id: string): Resource | undefined {\n return this.resources.get(id);\n }\n\n /**\n * Get resource by pattern matching\n */\n findByPattern(uri: string): Resource | undefined {\n for (const resource of this.resources.values()) {\n if (this.matchesPattern(uri, resource.pattern)) {\n return resource;\n }\n }\n return undefined;\n }\n\n /**\n * Check if URI matches pattern\n * Uses regex-based pattern matching with named capture groups.\n * Supports Express-style patterns like \"/users/:userId/profile\"\n */\n private matchesPattern(uri: string, pattern: string): boolean {\n const patternRegex = new RegExp(\n \"^\" + pattern.replace(/:(\\w+)/g, \"(?<$1>[^/]+)\") + \"$\",\n );\n return patternRegex.test(uri);\n }\n\n /**\n * Extract params from URI using pattern\n */\n extractParams(uri: string, pattern: string): Record<string, string> {\n const patternRegex = new RegExp(\n \"^\" + pattern.replace(/:(\\w+)/g, \"(?<$1>[^/]+)\") + \"$\",\n );\n const match = uri.match(patternRegex);\n\n return match?.groups || {};\n }\n\n /**\n * Get all resources\n */\n getAll(): Map<string, Resource> {\n return new Map(this.resources);\n }\n\n /**\n * Clear all resources\n */\n clear(): void {\n this.resources.clear();\n }\n}\n\n// Singleton instance using globalThis to share across module contexts\n// This is necessary for esbuild-bundled API routes to access the same registry\nconst RESOURCE_REGISTRY_KEY = \"__veryfront_resource_registry__\";\n// deno-lint-ignore no-explicit-any\nconst _globalResource = globalThis as any;\nexport const resourceRegistry: ResourceRegistryClass = _globalResource[RESOURCE_REGISTRY_KEY] ||=\n new ResourceRegistryClass();\n", "/**\n * MCP Prompt factory and utilities\n */\n\nimport type { Prompt, PromptConfig } from \"../types/mcp.ts\";\nimport { agentLogger } from \"../../core/utils/logger/logger.ts\";\nimport { createError, toError } from \"../../core/errors/veryfront-error.ts\";\n\n/**\n * Create an MCP prompt template\n *\n * @example\n * ```typescript\n * import { prompt } from 'veryfront/ai';\n\n *\n * export default prompt({\n * description: 'Customer support prompt',\n * content: 'You are a helpful customer support agent...',\n * });\n * ```\n */\nexport function prompt(config: PromptConfig): Prompt {\n const id = config.id || generatePromptId();\n\n return {\n id,\n description: config.description,\n\n async getContent(\n variables?: Record<string, unknown>,\n ): Promise<string> {\n // If static content\n if (config.content) {\n return interpolateVariables(config.content, variables || {});\n }\n\n // If dynamic generator\n if (config.generate) {\n return await config.generate(variables || {});\n }\n\n throw toError(createError({\n type: \"agent\",\n message: `Prompt \"${id}\" has no content or generator`,\n }));\n },\n };\n}\n\n/**\n * Generate a unique prompt ID\n */\nlet promptIdCounter = 0;\nfunction generatePromptId(): string {\n return `prompt_${Date.now()}_${promptIdCounter++}`;\n}\n\n/**\n * Interpolate variables in prompt template\n * Replaces {variableName} with actual values\n */\nfunction interpolateVariables(\n template: string,\n variables: Record<string, unknown>,\n): string {\n return template.replace(/\\{(\\w+)\\}/g, (match, key) => {\n const value = variables[key];\n return value !== undefined ? String(value) : match;\n });\n}\n\n/**\n * Prompt registry\n */\nclass PromptRegistryClass {\n private prompts = new Map<string, Prompt>();\n\n /**\n * Register a prompt\n */\n register(id: string, promptInstance: Prompt): void {\n if (this.prompts.has(id)) {\n // Debug level - overwriting is expected during hot reload and re-discovery\n agentLogger.debug(`Prompt \"${id}\" is already registered. Overwriting.`);\n }\n\n this.prompts.set(id, promptInstance);\n }\n\n /**\n * Get a prompt by ID\n */\n get(id: string): Prompt | undefined {\n return this.prompts.get(id);\n }\n\n /**\n * Get prompt content by ID\n */\n async getContent(\n id: string,\n variables?: Record<string, unknown>,\n ): Promise<string> {\n const promptInstance = this.get(id);\n\n if (!promptInstance) {\n throw toError(createError({\n type: \"agent\",\n message: `Prompt \"${id}\" not found`,\n }));\n }\n\n return await promptInstance.getContent(variables);\n }\n\n /**\n * Get all prompts\n */\n getAll(): Map<string, Prompt> {\n return new Map(this.prompts);\n }\n\n /**\n * Clear all prompts\n */\n clear(): void {\n this.prompts.clear();\n }\n}\n\n// Singleton instance using globalThis to share across module contexts\n// This is necessary for esbuild-bundled API routes to access the same registry\nconst PROMPT_REGISTRY_KEY = \"__veryfront_prompt_registry__\";\n// deno-lint-ignore no-explicit-any\nconst _globalPrompt = globalThis as any;\nexport const promptRegistry: PromptRegistryClass = _globalPrompt[PROMPT_REGISTRY_KEY] ||=\n new PromptRegistryClass();\n", "/**\n * MCP Registry - Central registry for all MCP resources\n */\n\nimport type { MCPRegistry } from \"../types/mcp.ts\";\nimport type { Tool } from \"../types/tool.ts\";\nimport type { Prompt, Resource } from \"../types/mcp.ts\";\nimport { toolRegistry } from \"../utils/tool.ts\";\nimport { resourceRegistry } from \"./resource.ts\";\nimport { promptRegistry } from \"./prompt.ts\";\n\n/**\n * Get the global MCP registry\n */\nexport function getMCPRegistry(): MCPRegistry {\n return {\n tools: toolRegistry.getAll(),\n resources: resourceRegistry.getAll(),\n prompts: promptRegistry.getAll(),\n };\n}\n\n/**\n * Register a tool in the MCP registry\n */\nexport function registerTool(id: string, tool: Tool): void {\n toolRegistry.register(id, tool);\n}\n\n/**\n * Register a resource in the MCP registry\n */\nexport function registerResource(id: string, resource: Resource): void {\n resourceRegistry.register(id, resource);\n}\n\n/**\n * Register a prompt in the MCP registry\n */\nexport function registerPrompt(id: string, promptInstance: Prompt): void {\n promptRegistry.register(id, promptInstance);\n}\n\n/**\n * Get MCP registry stats\n */\nexport function getMCPStats(): {\n tools: number;\n resources: number;\n prompts: number;\n total: number;\n} {\n const registry = getMCPRegistry();\n\n return {\n tools: registry.tools.size,\n resources: registry.resources.size,\n prompts: registry.prompts.size,\n total: registry.tools.size + registry.resources.size + registry.prompts.size,\n };\n}\n\n/**\n * Clear all MCP registries (for testing)\n */\nexport function clearMCPRegistry(): void {\n toolRegistry.clear();\n resourceRegistry.clear();\n promptRegistry.clear();\n}\n", "/**\n * Agent & Tool Inspector\n *\n * Debugging utilities for inspecting agent execution and tool calls.\n */\n\nimport type { Agent, Message } from \"../../types/agent.ts\";\nimport { getMCPRegistry, getMCPStats } from \"../../mcp/registry.ts\";\nimport { agentLogger } from \"@veryfront/utils/logger/logger.ts\";\n\nexport interface InspectionReport {\n /** Agent information */\n agent: {\n id: string;\n model: string;\n maxSteps: number;\n memoryType: string;\n };\n\n /** Execution details */\n execution: {\n input: string | Message[];\n output: string;\n status: string;\n steps: number;\n executionTime: number;\n };\n\n /** Tool usage */\n tools: {\n called: Array<{\n name: string;\n args: Record<string, unknown>;\n result: unknown;\n executionTime?: number;\n status: string;\n }>;\n available: string[];\n };\n\n /** Memory usage */\n memory: {\n messagesCount: number;\n estimatedTokens: number;\n };\n\n /** Token usage */\n usage?: {\n promptTokens: number;\n completionTokens: number;\n totalTokens: number;\n };\n}\n\n/**\n * Inspect an agent execution\n *\n * @example\n * ```typescript\n * import { inspectAgent } from 'veryfront/ai/dev';\n *\n * const report = await inspectAgent(myAgent, 'Test input');\n * console.log(report);\n * ```\n */\nexport async function inspectAgent(\n agent: Agent,\n input: string | Message[],\n): Promise<InspectionReport> {\n const startTime = Date.now();\n\n // Get memory stats before execution\n const _memoryStatsBefore = await agent.getMemoryStats();\n\n // Execute agent\n const response = await agent.generate({ input });\n\n const executionTime = Date.now() - startTime;\n\n // Get memory stats after execution\n const memoryStatsAfter = await agent.getMemoryStats();\n\n // Get available tools\n const availableTools = agent.config.tools ? Object.keys(agent.config.tools) : [];\n\n return {\n agent: {\n id: agent.id,\n model: agent.config.model,\n maxSteps: agent.config.maxSteps || 20,\n memoryType: agent.config.memory?.type || \"conversation\",\n },\n execution: {\n input,\n output: response.text,\n status: response.status,\n steps: response.toolCalls.length + 1, // Tool calls + final response\n executionTime,\n },\n tools: {\n called: response.toolCalls.map((tc) => ({\n name: tc.name,\n args: tc.args,\n result: tc.result,\n executionTime: tc.executionTime,\n status: tc.status,\n })),\n available: availableTools,\n },\n memory: {\n messagesCount: memoryStatsAfter.totalMessages,\n estimatedTokens: memoryStatsAfter.estimatedTokens,\n },\n usage: response.usage,\n };\n}\n\n/**\n * Print inspection report\n */\nexport function printInspectionReport(report: InspectionReport): void {\n agentLogger.info(\"\\n=== Agent Inspection Report ===\\n\");\n\n agentLogger.info(\"Agent:\");\n agentLogger.info(` ID: ${report.agent.id}`);\n agentLogger.info(` Model: ${report.agent.model}`);\n agentLogger.info(` Max Steps: ${report.agent.maxSteps}`);\n agentLogger.info(` Memory: ${report.agent.memoryType}\\n`);\n\n agentLogger.info(\"Execution:\");\n agentLogger.info(\n ` Input: ${\n typeof report.execution.input === \"string\"\n ? report.execution.input\n : `${(report.execution.input as Message[]).length} messages`\n }`,\n );\n agentLogger.info(` Output: ${report.execution.output.substring(0, 100)}...`);\n agentLogger.info(` Status: ${report.execution.status}`);\n agentLogger.info(` Steps: ${report.execution.steps}`);\n agentLogger.info(` Time: ${report.execution.executionTime}ms\\n`);\n\n agentLogger.info(\"Tools:\");\n agentLogger.info(\n ` Available: ${report.tools.available.length} (${report.tools.available.join(\", \")})`,\n );\n agentLogger.info(` Called: ${report.tools.called.length}`);\n\n if (report.tools.called.length > 0) {\n report.tools.called.forEach((tool, i) => {\n agentLogger.info(` ${i + 1}. ${tool.name}(${JSON.stringify(tool.args)})`);\n agentLogger.info(` Status: ${tool.status}`);\n agentLogger.info(` Time: ${tool.executionTime}ms`);\n agentLogger.info(` Result: ${JSON.stringify(tool.result).substring(0, 100)}...`);\n });\n }\n agentLogger.info(\"\");\n\n agentLogger.info(\"Memory:\");\n agentLogger.info(` Messages: ${report.memory.messagesCount}`);\n agentLogger.info(` Estimated Tokens: ${report.memory.estimatedTokens}\\n`);\n\n if (report.usage) {\n agentLogger.info(\"Token Usage:\");\n agentLogger.info(` Prompt: ${report.usage.promptTokens}`);\n agentLogger.info(` Completion: ${report.usage.completionTokens}`);\n agentLogger.info(` Total: ${report.usage.totalTokens}\\n`);\n }\n}\n\n/**\n * Get MCP registry overview\n */\nexport function getRegistryOverview(): {\n tools: Array<{ id: string; description: string }>;\n resources: Array<{ id: string; pattern: string; description: string }>;\n prompts: Array<{ id: string; description: string }>;\n stats: ReturnType<typeof getMCPStats>;\n} {\n const registry = getMCPRegistry();\n const stats = getMCPStats();\n\n return {\n tools: Array.from(registry.tools.values()).map((t) => ({\n id: t.id,\n description: t.description,\n })),\n resources: Array.from(registry.resources.values()).map((r) => ({\n id: r.id,\n pattern: r.pattern,\n description: r.description,\n })),\n prompts: Array.from(registry.prompts.values()).map((p) => ({\n id: p.id,\n description: p.description,\n })),\n stats,\n };\n}\n\n/**\n * Print registry overview\n */\nexport function printRegistryOverview(): void {\n const overview = getRegistryOverview();\n\n agentLogger.info(\"\\n=== MCP Registry Overview ===\\n\");\n agentLogger.info(`Total: ${overview.stats.total} items\\n`);\n\n agentLogger.info(`Tools (${overview.stats.tools}):`);\n overview.tools.forEach((t) => {\n agentLogger.info(` \u2022 ${t.id}: ${t.description}`);\n });\n agentLogger.info(\"\");\n\n agentLogger.info(`Resources (${overview.stats.resources}):`);\n overview.resources.forEach((r) => {\n agentLogger.info(` \u2022 ${r.id} (${r.pattern}): ${r.description}`);\n });\n agentLogger.info(\"\");\n\n agentLogger.info(`Prompts (${overview.stats.prompts}):`);\n overview.prompts.forEach((p) => {\n agentLogger.info(` \u2022 ${p.id}: ${p.description}`);\n });\n agentLogger.info(\"\");\n}\n"],
|
|
5
|
+
"mappings": ";AAMA,WAAW,OAAO,WAAW,QAAQ;AAAA,EACnC,KAAK;AAAA,IACH,IAAI,KAAiC;AACnC,aAAO,QAAQ,IAAI,GAAG;AAAA,IACxB;AAAA,IACA,IAAI,KAAa,OAAqB;AACpC,cAAQ,IAAI,GAAG,IAAI;AAAA,IACrB;AAAA,IACA,OAAO,KAAmB;AACxB,aAAO,QAAQ,IAAI,GAAG;AAAA,IACxB;AAAA,IACA,IAAI,KAAsB;AACxB,aAAO,OAAO,QAAQ;AAAA,IACxB;AAAA,IACA,WAAmC;AACjC,aAAO,EAAE,GAAG,QAAQ,IAAI;AAAA,IAC1B;AAAA,EACF;AACF;;;AC6DA,eAAsB,UACpB,OACA,WACoB;AACpB,QAAM,QAAmB;AAAA,IACvB,MAAM,MAAM;AAAA,IACZ,SAAS,CAAC;AAAA,IACV,QAAQ;AAAA,IACR,WAAW;AAAA,EACb;AAEA,QAAM,iBAAiB,KAAK,IAAI;AAEhC,aAAW,YAAY,WAAW;AAChC,UAAM,SAAS,MAAM,YAAY,OAAO,QAAQ;AAChD,UAAM,QAAQ,KAAK,MAAM;AAEzB,QAAI,CAAC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
|
|
7
7
|
}
|
package/dist/ai/index.js
CHANGED
|
@@ -1270,6 +1270,7 @@ function tool(config) {
|
|
|
1270
1270
|
}
|
|
1271
1271
|
return {
|
|
1272
1272
|
id,
|
|
1273
|
+
type: "function",
|
|
1273
1274
|
description: config.description,
|
|
1274
1275
|
inputSchema: config.inputSchema,
|
|
1275
1276
|
inputSchemaJson,
|
|
@@ -1299,6 +1300,56 @@ function tool(config) {
|
|
|
1299
1300
|
mcp: config.mcp
|
|
1300
1301
|
};
|
|
1301
1302
|
}
|
|
1303
|
+
function dynamicTool(config) {
|
|
1304
|
+
const id = config.id || generateToolId();
|
|
1305
|
+
let inputSchemaJson;
|
|
1306
|
+
const zodLikeSchema = config.inputSchema;
|
|
1307
|
+
if (zodLikeSchema?._def?.typeName) {
|
|
1308
|
+
try {
|
|
1309
|
+
inputSchemaJson = zodToJsonSchema(config.inputSchema);
|
|
1310
|
+
agentLogger.info(
|
|
1311
|
+
`[DYNAMIC_TOOL] Converted schema for "${id}": ${Object.keys(inputSchemaJson.properties || {}).length} properties`
|
|
1312
|
+
);
|
|
1313
|
+
} catch {
|
|
1314
|
+
inputSchemaJson = { type: "object", properties: {}, additionalProperties: true };
|
|
1315
|
+
agentLogger.info(`[DYNAMIC_TOOL] Using permissive schema for "${id}"`);
|
|
1316
|
+
}
|
|
1317
|
+
} else if (zodLikeSchema?._def?.shape) {
|
|
1318
|
+
try {
|
|
1319
|
+
const shape = typeof zodLikeSchema._def.shape === "function" ? zodLikeSchema._def.shape() : zodLikeSchema._def.shape;
|
|
1320
|
+
const properties = {};
|
|
1321
|
+
for (const key of Object.keys(shape || {})) {
|
|
1322
|
+
properties[key] = { type: "string" };
|
|
1323
|
+
}
|
|
1324
|
+
inputSchemaJson = {
|
|
1325
|
+
type: "object",
|
|
1326
|
+
properties,
|
|
1327
|
+
additionalProperties: true
|
|
1328
|
+
};
|
|
1329
|
+
agentLogger.info(`[DYNAMIC_TOOL] Introspected schema for "${id}"`);
|
|
1330
|
+
} catch {
|
|
1331
|
+
inputSchemaJson = { type: "object", properties: {}, additionalProperties: true };
|
|
1332
|
+
}
|
|
1333
|
+
} else {
|
|
1334
|
+
inputSchemaJson = { type: "object", properties: {}, additionalProperties: true };
|
|
1335
|
+
agentLogger.info(`[DYNAMIC_TOOL] Using fully dynamic schema for "${id}"`);
|
|
1336
|
+
}
|
|
1337
|
+
return {
|
|
1338
|
+
id,
|
|
1339
|
+
type: "dynamic",
|
|
1340
|
+
description: config.description,
|
|
1341
|
+
inputSchema: config.inputSchema,
|
|
1342
|
+
inputSchemaJson,
|
|
1343
|
+
execute: async (input, context) => {
|
|
1344
|
+
const result = await config.execute(input, context);
|
|
1345
|
+
if (config.toModelOutput) {
|
|
1346
|
+
return config.toModelOutput(result);
|
|
1347
|
+
}
|
|
1348
|
+
return result;
|
|
1349
|
+
},
|
|
1350
|
+
mcp: config.mcp
|
|
1351
|
+
};
|
|
1352
|
+
}
|
|
1302
1353
|
var toolIdCounter = 0;
|
|
1303
1354
|
function generateToolId() {
|
|
1304
1355
|
return `tool_${Date.now()}_${toolIdCounter++}`;
|
|
@@ -1738,6 +1789,7 @@ import { z as z4 } from "zod";
|
|
|
1738
1789
|
function agentAsTool(agent2, description) {
|
|
1739
1790
|
return {
|
|
1740
1791
|
id: `agent_${agent2.id}`,
|
|
1792
|
+
type: "function",
|
|
1741
1793
|
description,
|
|
1742
1794
|
inputSchema: z4.object({
|
|
1743
1795
|
input: z4.string().describe("Input for the agent")
|
|
@@ -2043,7 +2095,7 @@ import { join } from "node:path";
|
|
|
2043
2095
|
// deno.json
|
|
2044
2096
|
var deno_default = {
|
|
2045
2097
|
name: "veryfront",
|
|
2046
|
-
version: "0.0.
|
|
2098
|
+
version: "0.0.71",
|
|
2047
2099
|
nodeModulesDir: "auto",
|
|
2048
2100
|
exclude: [
|
|
2049
2101
|
"npm/",
|
|
@@ -4183,7 +4235,8 @@ var AgentRuntime = class {
|
|
|
4183
4235
|
start: async (controller) => {
|
|
4184
4236
|
try {
|
|
4185
4237
|
this.status = "streaming";
|
|
4186
|
-
const
|
|
4238
|
+
const messageId = `msg-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
|
|
4239
|
+
const startEvent = JSON.stringify({ type: "start", messageId });
|
|
4187
4240
|
controller.enqueue(encoder.encode(`data: ${startEvent}
|
|
4188
4241
|
|
|
4189
4242
|
`));
|
|
@@ -4390,6 +4443,10 @@ var AgentRuntime = class {
|
|
|
4390
4443
|
totalTokens: 0
|
|
4391
4444
|
};
|
|
4392
4445
|
for (let step2 = 0; step2 < maxSteps; step2++) {
|
|
4446
|
+
const startStepEvent = JSON.stringify({ type: "start-step" });
|
|
4447
|
+
controller.enqueue(encoder.encode(`data: ${startStepEvent}
|
|
4448
|
+
|
|
4449
|
+
`));
|
|
4393
4450
|
const tools = this.getAvailableTools();
|
|
4394
4451
|
const stream = await provider.stream({
|
|
4395
4452
|
model,
|
|
@@ -4422,9 +4479,13 @@ var AgentRuntime = class {
|
|
|
4422
4479
|
toolCall.status = "error";
|
|
4423
4480
|
toolCall.error = errorStr;
|
|
4424
4481
|
toolCalls.push(toolCall);
|
|
4482
|
+
const errorTool = toolRegistry.get(toolCall.name);
|
|
4483
|
+
const errorIsDynamic = errorTool?.type === "dynamic";
|
|
4425
4484
|
const errorData = JSON.stringify({
|
|
4426
|
-
type: "error",
|
|
4427
|
-
|
|
4485
|
+
type: "tool-output-error",
|
|
4486
|
+
toolCallId: toolCall.id,
|
|
4487
|
+
errorText: errorStr,
|
|
4488
|
+
...errorIsDynamic && { dynamic: true }
|
|
4428
4489
|
});
|
|
4429
4490
|
controller.enqueue(encoder.encode(`data: ${errorData}
|
|
4430
4491
|
|
|
@@ -4467,10 +4528,13 @@ var AgentRuntime = class {
|
|
|
4467
4528
|
name: event.toolCall.name,
|
|
4468
4529
|
arguments: ""
|
|
4469
4530
|
});
|
|
4531
|
+
const startTool = toolRegistry.get(event.toolCall.name);
|
|
4532
|
+
const startIsDynamic = startTool?.type === "dynamic";
|
|
4470
4533
|
const toolStartEvent = JSON.stringify({
|
|
4471
|
-
type: "tool-
|
|
4534
|
+
type: "tool-input-start",
|
|
4472
4535
|
toolCallId: event.toolCall.id,
|
|
4473
|
-
toolName: event.toolCall.name
|
|
4536
|
+
toolName: event.toolCall.name,
|
|
4537
|
+
...startIsDynamic && { dynamic: true }
|
|
4474
4538
|
});
|
|
4475
4539
|
controller.enqueue(encoder.encode(`data: ${toolStartEvent}
|
|
4476
4540
|
|
|
@@ -4482,9 +4546,9 @@ var AgentRuntime = class {
|
|
|
4482
4546
|
const tc = streamToolCalls.get(event.id);
|
|
4483
4547
|
tc.arguments += event.arguments;
|
|
4484
4548
|
const toolDeltaEvent = JSON.stringify({
|
|
4485
|
-
type: "tool-
|
|
4549
|
+
type: "tool-input-delta",
|
|
4486
4550
|
toolCallId: event.id,
|
|
4487
|
-
|
|
4551
|
+
inputTextDelta: event.arguments
|
|
4488
4552
|
});
|
|
4489
4553
|
controller.enqueue(encoder.encode(`data: ${toolDeltaEvent}
|
|
4490
4554
|
|
|
@@ -4498,12 +4562,15 @@ var AgentRuntime = class {
|
|
|
4498
4562
|
name: event.toolCall.name,
|
|
4499
4563
|
arguments: event.toolCall.arguments
|
|
4500
4564
|
});
|
|
4565
|
+
const completeTool = toolRegistry.get(event.toolCall.name);
|
|
4566
|
+
const completeIsDynamic = completeTool?.type === "dynamic";
|
|
4501
4567
|
const { args } = parseStreamToolArgs(event.toolCall.arguments);
|
|
4502
4568
|
const toolCallEvent = JSON.stringify({
|
|
4503
|
-
type: "tool-
|
|
4569
|
+
type: "tool-input-available",
|
|
4504
4570
|
toolCallId: event.toolCall.id,
|
|
4505
4571
|
toolName: event.toolCall.name,
|
|
4506
|
-
args
|
|
4572
|
+
input: args,
|
|
4573
|
+
...completeIsDynamic && { dynamic: true }
|
|
4507
4574
|
});
|
|
4508
4575
|
controller.enqueue(encoder.encode(`data: ${toolCallEvent}
|
|
4509
4576
|
|
|
@@ -4600,6 +4667,17 @@ var AgentRuntime = class {
|
|
|
4600
4667
|
toolCallId: tc.id,
|
|
4601
4668
|
error: argError
|
|
4602
4669
|
});
|
|
4670
|
+
const inputErrorTool = toolRegistry.get(tc.name);
|
|
4671
|
+
const inputErrorIsDynamic = inputErrorTool?.type === "dynamic";
|
|
4672
|
+
const inputErrorEvent = JSON.stringify({
|
|
4673
|
+
type: "tool-input-error",
|
|
4674
|
+
toolCallId: tc.id,
|
|
4675
|
+
errorText: `Invalid tool arguments: ${argError}`,
|
|
4676
|
+
...inputErrorIsDynamic && { dynamic: true }
|
|
4677
|
+
});
|
|
4678
|
+
controller.enqueue(encoder.encode(`data: ${inputErrorEvent}
|
|
4679
|
+
|
|
4680
|
+
`));
|
|
4603
4681
|
await recordToolError(toolCall, `Invalid tool arguments: ${argError}`);
|
|
4604
4682
|
continue;
|
|
4605
4683
|
}
|
|
@@ -4609,15 +4687,6 @@ var AgentRuntime = class {
|
|
|
4609
4687
|
if (callbacks?.onToolCall) {
|
|
4610
4688
|
callbacks.onToolCall(toolCall);
|
|
4611
4689
|
}
|
|
4612
|
-
const toolCallEvent = JSON.stringify({
|
|
4613
|
-
type: "tool-call",
|
|
4614
|
-
toolCallId: toolCall.id,
|
|
4615
|
-
toolName: toolCall.name,
|
|
4616
|
-
args: toolCall.args
|
|
4617
|
-
});
|
|
4618
|
-
controller.enqueue(encoder.encode(`data: ${toolCallEvent}
|
|
4619
|
-
|
|
4620
|
-
`));
|
|
4621
4690
|
const result = await executeTool(tc.name, toolCall.args, {
|
|
4622
4691
|
agentId: this.id,
|
|
4623
4692
|
...toolContext
|
|
@@ -4626,10 +4695,13 @@ var AgentRuntime = class {
|
|
|
4626
4695
|
toolCall.result = result;
|
|
4627
4696
|
toolCall.executionTime = Date.now() - startTime;
|
|
4628
4697
|
toolCalls.push(toolCall);
|
|
4698
|
+
const outputTool = toolRegistry.get(tc.name);
|
|
4699
|
+
const outputIsDynamic = outputTool?.type === "dynamic";
|
|
4629
4700
|
const toolResultEvent = JSON.stringify({
|
|
4630
|
-
type: "tool-
|
|
4701
|
+
type: "tool-output-available",
|
|
4631
4702
|
toolCallId: toolCall.id,
|
|
4632
|
-
result
|
|
4703
|
+
output: result,
|
|
4704
|
+
...outputIsDynamic && { dynamic: true }
|
|
4633
4705
|
});
|
|
4634
4706
|
controller.enqueue(encoder.encode(`data: ${toolResultEvent}
|
|
4635
4707
|
|
|
@@ -4652,9 +4724,17 @@ var AgentRuntime = class {
|
|
|
4652
4724
|
await recordToolError(toolCall, errorStr);
|
|
4653
4725
|
}
|
|
4654
4726
|
}
|
|
4727
|
+
const finishStepToolsEvent = JSON.stringify({ type: "finish-step" });
|
|
4728
|
+
controller.enqueue(encoder.encode(`data: ${finishStepToolsEvent}
|
|
4729
|
+
|
|
4730
|
+
`));
|
|
4655
4731
|
this.status = "thinking";
|
|
4656
4732
|
continue;
|
|
4657
4733
|
}
|
|
4734
|
+
const finishStepEvent = JSON.stringify({ type: "finish-step" });
|
|
4735
|
+
controller.enqueue(encoder.encode(`data: ${finishStepEvent}
|
|
4736
|
+
|
|
4737
|
+
`));
|
|
4658
4738
|
break;
|
|
4659
4739
|
}
|
|
4660
4740
|
const lastMessage = currentMessages[currentMessages.length - 1];
|
|
@@ -8469,6 +8549,7 @@ export {
|
|
|
8469
8549
|
createWorkflowClient,
|
|
8470
8550
|
detectPlatform,
|
|
8471
8551
|
discoverAll,
|
|
8552
|
+
dynamicTool,
|
|
8472
8553
|
embed,
|
|
8473
8554
|
embedMany,
|
|
8474
8555
|
experimental_createMCPClient,
|