veryfront 0.0.38 → 0.0.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/ai/components.js +48 -47
  2. package/dist/ai/components.js.map +2 -2
  3. package/dist/ai/dev.js +3 -3
  4. package/dist/ai/dev.js.map +2 -2
  5. package/dist/ai/index.js +39 -13
  6. package/dist/ai/index.js.map +3 -3
  7. package/dist/cli.js +3775 -2924
  8. package/dist/components.js +1 -1
  9. package/dist/components.js.map +1 -1
  10. package/dist/config.js +2 -2
  11. package/dist/config.js.map +2 -2
  12. package/dist/data.js +1 -1
  13. package/dist/data.js.map +1 -1
  14. package/dist/index.js +3 -2
  15. package/dist/index.js.map +2 -2
  16. package/dist/templates/ai/ai/agents/assistant.ts +5 -3
  17. package/dist/templates/ai/ai/prompts/assistant.ts +7 -6
  18. package/dist/templates/ai/ai/tools/.gitkeep +0 -0
  19. package/dist/templates/ai/app/layout.tsx +3 -10
  20. package/dist/templates/ai/app/page.tsx +7 -13
  21. package/dist/templates/app/app/dashboard/page.tsx +5 -5
  22. package/dist/templates/app/app/layout.tsx +7 -29
  23. package/dist/templates/app/app/login/page.tsx +53 -125
  24. package/dist/templates/app/components/DashboardLayout.tsx +29 -95
  25. package/dist/templates/app/components/FeatureGrid.tsx +24 -30
  26. package/dist/templates/app/components/Header.tsx +13 -16
  27. package/dist/templates/app/components/HeroSection.tsx +19 -29
  28. package/dist/templates/blog/app/layout.tsx +28 -37
  29. package/dist/templates/blog/app/page.tsx +2 -2
  30. package/dist/templates/blog/components/BlogPostList.tsx +15 -24
  31. package/dist/templates/docs/app/layout.tsx +12 -25
  32. package/dist/templates/docs/components/Header.tsx +25 -22
  33. package/dist/templates/docs/components/Sidebar.tsx +8 -8
  34. package/dist/templates/minimal/app/layout.tsx +4 -11
  35. package/dist/templates/minimal/app/page.tsx +8 -8
  36. package/package.json +1 -1
  37. package/dist/templates/ai/ai/tools/get-weather.ts +0 -29
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../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 * 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 agentLogger.warn(`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 agentLogger.warn(`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 agentLogger.warn(`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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ClD,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 * 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": ";AAqFA,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,OAAO,QAAQ;AAClB,YAAM,SAAS;AAAA,IACjB;AAAA,EACF;AAEA,QAAM,YAAY,KAAK,IAAI,IAAI;AAE/B,SAAO;AACT;AAKA,eAAe,YAAY,OAAc,UAAyC;AAChF,QAAM,YAAY,KAAK,IAAI;AAE3B,MAAI;AAEF,UAAM,UAAU,SAAS,WAAW;AACpC,UAAM,iBAAiB,IAAI,QAAe,CAAC,GAAG,WAAW;AACvD,iBAAW,MAAM,OAAO,IAAI,MAAM,cAAc,CAAC,GAAG,OAAO;AAAA,IAC7D,CAAC;AAGD,UAAM,kBAAkB,MAAM,SAAS;AAAA,MACrC,OAAO,SAAS;AAAA,IAClB,CAAC;AAED,UAAM,WAAW,MAAM,QAAQ,KAAK,CAAC,iBAAiB,cAAc,CAAC;AAErE,UAAM,gBAAgB,KAAK,IAAI,IAAI;AACnC,UAAM,YAAY,SAAS,UAAU,IAAI,CAAC,OAAO,GAAG,IAAI;AAGxD,QAAI,SAAS;AACb,QAAI;AAGJ,QAAI,SAAS,UAAU;AACrB,UAAI,S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M,KAAK;AAAA,CAAU;AAEzD,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;",
6
6
  "names": ["logger"]
7
7
  }
package/dist/ai/index.js CHANGED
@@ -1277,7 +1277,7 @@ var ToolRegistryClass = class {
1277
1277
  }
1278
1278
  register(id, toolInstance) {
1279
1279
  if (this.tools.has(id)) {
1280
- agentLogger.warn(`Tool "${id}" is already registered. Overwriting.`);
1280
+ agentLogger.debug(`Tool "${id}" is already registered. Overwriting.`);
1281
1281
  }
1282
1282
  this.tools.set(id, toolInstance);
1283
1283
  }
@@ -1675,7 +1675,7 @@ var LRU_DEFAULT_MAX_SIZE_BYTES = 50 * 1024 * 1024;
1675
1675
  // deno.json
1676
1676
  var deno_default = {
1677
1677
  name: "veryfront",
1678
- version: "0.0.38",
1678
+ version: "0.0.40",
1679
1679
  exclude: [
1680
1680
  "npm/",
1681
1681
  "dist/",
@@ -3133,7 +3133,7 @@ var ResourceRegistryClass = class {
3133
3133
  */
3134
3134
  register(id, resourceInstance) {
3135
3135
  if (this.resources.has(id)) {
3136
- agentLogger.warn(`Resource "${id}" is already registered. Overwriting.`);
3136
+ agentLogger.debug(`Resource "${id}" is already registered. Overwriting.`);
3137
3137
  }
3138
3138
  this.resources.set(id, resourceInstance);
3139
3139
  }
@@ -3231,7 +3231,7 @@ var PromptRegistryClass = class {
3231
3231
  */
3232
3232
  register(id, promptInstance) {
3233
3233
  if (this.prompts.has(id)) {
3234
- agentLogger.warn(`Prompt "${id}" is already registered. Overwriting.`);
3234
+ agentLogger.debug(`Prompt "${id}" is already registered. Overwriting.`);
3235
3235
  }
3236
3236
  this.prompts.set(id, promptInstance);
3237
3237
  }
@@ -3363,7 +3363,7 @@ var AgentRegistryClass = class {
3363
3363
  */
3364
3364
  register(id, agent2) {
3365
3365
  if (this.agents.has(id)) {
3366
- agentLogger.warn(`Agent "${id}" is already registered. Overwriting.`);
3366
+ agentLogger.debug(`Agent "${id}" is already registered. Overwriting.`);
3367
3367
  }
3368
3368
  this.agents.set(id, agent2);
3369
3369
  agentLogger.debug(`Registered agent: ${id}`);
@@ -3888,7 +3888,7 @@ async function getConfig(projectDir, adapter) {
3888
3888
  throw error;
3889
3889
  }
3890
3890
  const errorMessage = error instanceof Error ? error.message : String(error);
3891
- serverLogger.warn(`[CONFIG] Failed to load ${configFile}, trying next config file:`, {
3891
+ serverLogger.debug(`[CONFIG] Failed to load ${configFile}, trying next config file:`, {
3892
3892
  error: errorMessage
3893
3893
  });
3894
3894
  continue;
@@ -4227,6 +4227,7 @@ function getPathMod() {
4227
4227
  }
4228
4228
  var dirname = (path) => getPathMod().dirname(path);
4229
4229
  var join2 = (...paths) => getPathMod().join(...paths);
4230
+ var resolve = (...paths) => getPathMod().resolve(...paths);
4230
4231
  var sep = nodePath.sep;
4231
4232
 
4232
4233
  // src/ai/utils/discovery.ts
@@ -4248,6 +4249,15 @@ async function importModule(file, context) {
4248
4249
  const isJsx = filePath.endsWith(".jsx");
4249
4250
  const loader = isTsx ? "tsx" : isJsx ? "jsx" : filePath.endsWith(".ts") ? "ts" : "js";
4250
4251
  const { build } = await import("esbuild");
4252
+ const fileDir = dirname(filePath);
4253
+ const relativeImportPattern = /from\s+["'](\.\.[^"']+)["']/g;
4254
+ const relativeImports = [];
4255
+ let match;
4256
+ while ((match = relativeImportPattern.exec(source)) !== null) {
4257
+ if (match[1]) {
4258
+ relativeImports.push(match[1]);
4259
+ }
4260
+ }
4251
4261
  const result = await build({
4252
4262
  bundle: true,
4253
4263
  write: false,
@@ -4266,12 +4276,14 @@ async function importModule(file, context) {
4266
4276
  "veryfront",
4267
4277
  "veryfront/*",
4268
4278
  "@opentelemetry/*",
4269
- "path"
4279
+ "path",
4280
+ // Mark relative imports as external to avoid filesystem access issues
4281
+ ...relativeImports
4270
4282
  ],
4271
4283
  stdin: {
4272
4284
  contents: source,
4273
4285
  loader,
4274
- resolveDir: dirname(filePath),
4286
+ resolveDir: fileDir,
4275
4287
  sourcefile: filePath
4276
4288
  }
4277
4289
  });
@@ -4284,9 +4296,9 @@ async function importModule(file, context) {
4284
4296
  const tempFile = join2(tempDir, "module.mjs");
4285
4297
  let transformedCode;
4286
4298
  if (isDeno) {
4287
- transformedCode = rewriteForDeno(js);
4299
+ transformedCode = rewriteForDeno(js, fileDir);
4288
4300
  } else {
4289
- transformedCode = await rewriteDiscoveryImports(js, context.baseDir || ".", fs2);
4301
+ transformedCode = await rewriteDiscoveryImports(js, context.baseDir || ".", fs2, fileDir);
4290
4302
  }
4291
4303
  await fs2.writeTextFile(tempFile, transformedCode);
4292
4304
  try {
@@ -4297,7 +4309,7 @@ async function importModule(file, context) {
4297
4309
  await fs2.remove(tempDir, { recursive: true });
4298
4310
  }
4299
4311
  }
4300
- function rewriteForDeno(code) {
4312
+ function rewriteForDeno(code, fileDir) {
4301
4313
  let transformed = code;
4302
4314
  const npmPackages = [
4303
4315
  { pattern: /from\s+["']ai["']/g, replacement: 'from "npm:ai"' },
@@ -4310,12 +4322,26 @@ function rewriteForDeno(code) {
4310
4322
  for (const { pattern, replacement } of npmPackages) {
4311
4323
  transformed = transformed.replace(pattern, replacement);
4312
4324
  }
4325
+ transformed = transformed.replace(
4326
+ /from\s+["'](\.\.\/[^"']+)["']/g,
4327
+ (_match, relativePath) => {
4328
+ const absolutePath = resolve(fileDir, relativePath);
4329
+ return `from "file://${absolutePath}"`;
4330
+ }
4331
+ );
4313
4332
  return transformed;
4314
4333
  }
4315
- async function rewriteDiscoveryImports(code, projectDir, fs2) {
4334
+ async function rewriteDiscoveryImports(code, projectDir, fs2, fileDir) {
4316
4335
  let transformed = code;
4317
4336
  try {
4318
4337
  const { pathToFileURL } = await import("node:url");
4338
+ transformed = transformed.replace(
4339
+ /from\s+["'](\.\.\/[^"']+)["']/g,
4340
+ (_match, relativePath) => {
4341
+ const absolutePath = resolve(fileDir, relativePath);
4342
+ return `from "${pathToFileURL(absolutePath).href}"`;
4343
+ }
4344
+ );
4319
4345
  const resolvePackageToFileUrl = async (packageName) => {
4320
4346
  const packagePath = join2(projectDir, "node_modules", packageName);
4321
4347
  const packageJsonPath = join2(packagePath, "package.json");
@@ -7726,7 +7752,7 @@ var WorkflowExecutor = class _WorkflowExecutor {
7726
7752
  if (run.status === "cancelled") {
7727
7753
  throw new Error("Workflow was cancelled");
7728
7754
  }
7729
- await new Promise((resolve) => setTimeout(resolve, pollInterval));
7755
+ await new Promise((resolve2) => setTimeout(resolve2, pollInterval));
7730
7756
  }
7731
7757
  }
7732
7758
  /**