{"version":3,"sources":["../src/server/app-setup.ts","../src/routes/definitions.ts","../src/handlers/agent.handlers.ts","../src/utils/options.ts","../src/handlers/agent-additional.handlers.ts","../src/handlers/log.handlers.ts","../src/handlers/workflow.handlers.ts","../src/utils/sse.ts","../src/handlers/memory-observability.handlers.ts","../src/handlers/memory.handlers.ts","../src/a2a/registry.ts","../src/a2a/types.ts","../src/a2a/handlers.ts","../src/types/responses.ts","../src/utils/response-mappers.ts"],"sourcesContent":["/**\n * Common app setup utilities\n * Framework-agnostic application configuration helpers\n */\n\nimport type { ServerProviderDeps } from \"@voltagent/core\";\nimport { getGlobalLogger } from \"@voltagent/core\";\nimport type { Logger } from \"@voltagent/internal\";\n\n/**\n * OpenAPI documentation info\n */\nexport interface OpenApiInfo {\n  version?: string;\n  title?: string;\n  description?: string;\n}\n\n/**\n * Common app setup configuration\n */\nexport interface AppSetupConfig {\n  /**\n   * Enable Swagger UI\n   */\n  enableSwaggerUI?: boolean;\n\n  /**\n   * CORS options\n   */\n  corsOptions?: any;\n\n  /**\n   * OpenAPI documentation info\n   */\n  openApiInfo?: OpenApiInfo;\n\n  /**\n   * Server port for documentation\n   */\n  port?: number;\n}\n\n/**\n * Get or create a logger instance\n * @param deps Server provider dependencies\n * @param component Component name for logger\n * @returns Logger instance\n */\nexport function getOrCreateLogger(deps: ServerProviderDeps, component = \"api-server\"): Logger {\n  return deps.logger?.child({ component }) ?? getGlobalLogger().child({ component });\n}\n\n/**\n * Check if Swagger UI should be enabled\n * @param config App configuration\n * @returns Whether Swagger UI should be enabled\n */\nexport function shouldEnableSwaggerUI(config: { enableSwaggerUI?: boolean }): boolean {\n  const isProduction = process.env.NODE_ENV === \"production\";\n  return config.enableSwaggerUI ?? !isProduction;\n}\n\n/**\n * Get default OpenAPI documentation info\n * @param port Server port\n * @returns OpenAPI documentation object\n */\nexport function getOpenApiDoc(port: number, info?: OpenApiInfo) {\n  return {\n    openapi: \"3.1.0\" as const,\n    info: {\n      version: info?.version || \"1.0.0\",\n      title: info?.title || \"VoltAgent Core API\",\n      description: info?.description || \"API for managing and interacting with VoltAgents\",\n    },\n    servers: [\n      {\n        url: `http://localhost:${port}`,\n        description: \"Local development server\",\n      },\n    ],\n  };\n}\n\n/**\n * Default CORS configuration\n */\nexport const DEFAULT_CORS_OPTIONS = {\n  origin: \"*\",\n  methods: [\"GET\", \"POST\", \"PUT\", \"DELETE\", \"OPTIONS\"],\n  allowedHeaders: [\"Content-Type\", \"Authorization\"],\n  credentials: true,\n};\n","/**\n * Framework-agnostic route definitions\n * These can be used by any server implementation (Hono, Fastify, Express, etc.)\n */\n\n/**\n * HTTP methods\n */\nexport type HttpMethod = \"get\" | \"post\" | \"put\" | \"patch\" | \"delete\" | \"options\" | \"head\";\n\n/**\n * Response definition for a specific status code\n */\nexport interface ResponseDefinition {\n  description: string;\n  contentType?: string;\n}\n\n/**\n * Base route definition that can be used by any framework\n */\nexport interface RouteDefinition {\n  method: HttpMethod;\n  path: string;\n  summary: string;\n  description: string;\n  tags: string[];\n  operationId?: string;\n  responses?: Record<number, ResponseDefinition>;\n}\n\n/**\n * Agent route definitions\n */\nexport const AGENT_ROUTES = {\n  listAgents: {\n    method: \"get\" as const,\n    path: \"/agents\",\n    summary: \"List all registered agents\",\n    description:\n      \"Retrieve a comprehensive list of all agents registered in the system. Each agent includes its configuration, status, model information, tools, sub-agents, and memory settings. Use this endpoint to discover available agents and their capabilities.\",\n    tags: [\"Agent Management\"],\n    operationId: \"listAgents\",\n    responses: {\n      200: {\n        description: \"Successfully retrieved list of all registered agents\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to retrieve agents due to server error\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  getAgent: {\n    method: \"get\" as const,\n    path: \"/agents/:id\",\n    summary: \"Get agent by ID\",\n    description: \"Retrieve detailed information about a specific agent by its ID.\",\n    tags: [\"Agent Management\"],\n    operationId: \"getAgent\",\n    responses: {\n      200: {\n        description: \"Successfully retrieved agent details\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Agent not found\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to retrieve agent due to server error\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  generateText: {\n    method: \"post\" as const,\n    path: \"/agents/:id/text\",\n    summary: \"Generate text response\",\n    description:\n      \"Generate a text response from an agent using the provided conversation history. This endpoint processes messages synchronously and returns the complete response once generation is finished. Use this for traditional request-response interactions where you need the full response before proceeding.\",\n    tags: [\"Agent Generation\"],\n    operationId: \"generateText\",\n    responses: {\n      200: {\n        description: \"Successfully generated text response from the agent\",\n        contentType: \"application/json\",\n      },\n      400: {\n        description: \"Invalid request parameters or message format\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Agent not found\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to generate text due to server error\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  streamText: {\n    method: \"post\" as const,\n    path: \"/agents/:id/stream\",\n    summary: \"Stream raw text response\",\n    description:\n      \"Generate a text response from an agent and stream the raw fullStream data via Server-Sent Events (SSE). This endpoint provides direct access to all stream events including text deltas, tool calls, and tool results. Use this for advanced applications that need full control over stream processing.\",\n    tags: [\"Agent Generation\"],\n    operationId: \"streamText\",\n    responses: {\n      200: {\n        description: \"Successfully established SSE stream for raw text generation\",\n        contentType: \"text/event-stream\",\n      },\n      400: {\n        description: \"Invalid request parameters or message format\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Agent not found\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to stream text due to server error\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  chatStream: {\n    method: \"post\" as const,\n    path: \"/agents/:id/chat\",\n    summary: \"Stream chat messages\",\n    description:\n      \"Generate a text response from an agent and stream it as UI messages via Server-Sent Events (SSE). This endpoint is optimized for chat interfaces and works seamlessly with the AI SDK's useChat hook. It provides a high-level stream format with automatic handling of messages, tool calls, and metadata.\",\n    tags: [\"Agent Generation\"],\n    operationId: \"chatStream\",\n    responses: {\n      200: {\n        description: \"Successfully established SSE stream for chat generation\",\n        contentType: \"text/event-stream\",\n      },\n      400: {\n        description: \"Invalid request parameters or message format\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Agent not found\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to stream chat due to server error\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  resumeChatStream: {\n    method: \"get\" as const,\n    path: \"/agents/:id/chat/:conversationId/stream\",\n    summary: \"Resume chat stream\",\n    description:\n      \"Resume an in-progress UI message stream for a chat conversation. Requires userId query parameter. Returns 204 if no active stream is found.\",\n    tags: [\"Agent Generation\"],\n    operationId: \"resumeChatStream\",\n    responses: {\n      200: {\n        description: \"Successfully resumed SSE stream for chat generation\",\n        contentType: \"text/event-stream\",\n      },\n      400: {\n        description: \"Missing or invalid userId\",\n        contentType: \"application/json\",\n      },\n      204: {\n        description: \"No active stream found for the conversation\",\n        contentType: \"text/plain\",\n      },\n      404: {\n        description: \"Resumable streams not configured\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to resume chat stream due to server error\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  generateObject: {\n    method: \"post\" as const,\n    path: \"/agents/:id/object\",\n    summary: \"Generate structured object\",\n    description:\n      \"Generate a structured object that conforms to a specified JSON schema. This endpoint is perfect for extracting structured data from unstructured input, generating form data, or creating API responses with guaranteed structure. The agent will ensure the output matches the provided schema exactly.\",\n    tags: [\"Agent Generation\"],\n    operationId: \"generateObject\",\n    responses: {\n      200: {\n        description: \"Successfully generated structured object matching the provided schema\",\n        contentType: \"application/json\",\n      },\n      400: {\n        description: \"Invalid request parameters, message format, or schema\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Agent not found\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to generate object due to server error\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  streamObject: {\n    method: \"post\" as const,\n    path: \"/agents/:id/stream-object\",\n    summary: \"Stream structured object generation\",\n    description:\n      \"Generate a structured object and stream partial updates via Server-Sent Events (SSE). This allows you to display incremental object construction in real-time, useful for complex object generation where you want to show progress. Events may contain partial object updates or the complete final object, depending on the agent's implementation.\",\n    tags: [\"Agent Generation\"],\n    operationId: \"streamObject\",\n    responses: {\n      200: {\n        description: \"Successfully established SSE stream for object generation\",\n        contentType: \"text/event-stream\",\n      },\n      400: {\n        description: \"Invalid request parameters, message format, or schema\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Agent not found\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to stream object due to server error\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  getAgentHistory: {\n    method: \"get\" as const,\n    path: \"/agents/:id/history\",\n    summary: \"Get agent history\",\n    description: \"Retrieve the execution history for a specific agent with pagination support.\",\n    tags: [\"Agent Management\"],\n    operationId: \"getAgentHistory\",\n    responses: {\n      200: {\n        description: \"Successfully retrieved agent execution history\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Agent not found\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to retrieve agent history due to server error\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  getWorkspace: {\n    method: \"get\" as const,\n    path: \"/agents/:id/workspace\",\n    summary: \"Get agent workspace info\",\n    description:\n      \"Retrieve workspace configuration metadata for an agent, including capabilities (filesystem, sandbox, search, skills).\",\n    tags: [\"Agent Workspace\"],\n    operationId: \"getAgentWorkspace\",\n    responses: {\n      200: {\n        description: \"Successfully retrieved workspace info\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Agent or workspace not found\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to retrieve workspace info due to server error\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  listWorkspaceFiles: {\n    method: \"get\" as const,\n    path: \"/agents/:id/workspace/ls\",\n    summary: \"List workspace files\",\n    description: \"List files and directories under a workspace path.\",\n    tags: [\"Agent Workspace\"],\n    operationId: \"listWorkspaceFiles\",\n    responses: {\n      200: {\n        description: \"Successfully listed workspace files\",\n        contentType: \"application/json\",\n      },\n      400: {\n        description: \"Invalid request parameters\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Agent or workspace not found\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to list workspace files due to server error\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  readWorkspaceFile: {\n    method: \"get\" as const,\n    path: \"/agents/:id/workspace/read\",\n    summary: \"Read workspace file\",\n    description: \"Read a file from the workspace filesystem.\",\n    tags: [\"Agent Workspace\"],\n    operationId: \"readWorkspaceFile\",\n    responses: {\n      200: {\n        description: \"Successfully read workspace file\",\n        contentType: \"application/json\",\n      },\n      400: {\n        description: \"Invalid request parameters\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Agent or workspace not found\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to read workspace file due to server error\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  listWorkspaceSkills: {\n    method: \"get\" as const,\n    path: \"/agents/:id/workspace/skills\",\n    summary: \"List workspace skills\",\n    description: \"List available workspace skills for an agent.\",\n    tags: [\"Agent Workspace\"],\n    operationId: \"listWorkspaceSkills\",\n    responses: {\n      200: {\n        description: \"Successfully listed workspace skills\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Agent, workspace, or skills not found\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to list workspace skills due to server error\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  getWorkspaceSkill: {\n    method: \"get\" as const,\n    path: \"/agents/:id/workspace/skills/:skillId\",\n    summary: \"Get workspace skill\",\n    description: \"Retrieve a specific workspace skill including its instructions.\",\n    tags: [\"Agent Workspace\"],\n    operationId: \"getWorkspaceSkill\",\n    responses: {\n      200: {\n        description: \"Successfully retrieved workspace skill\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Agent, workspace, or skill not found\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to retrieve workspace skill due to server error\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n} as const;\n\n/**\n * Workflow route definitions\n */\nexport const WORKFLOW_ROUTES = {\n  listWorkflows: {\n    method: \"get\" as const,\n    path: \"/workflows\",\n    summary: \"List all registered workflows\",\n    description:\n      \"Retrieve a list of all workflows registered in the system. Each workflow includes its ID, name, purpose, step count, and current status. Use this endpoint to discover available workflows and understand their capabilities before execution.\",\n    tags: [\"Workflow Management\"],\n    operationId: \"listWorkflows\",\n    responses: {\n      200: {\n        description: \"Successfully retrieved list of all registered workflows\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to retrieve workflows due to server error\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  getWorkflow: {\n    method: \"get\" as const,\n    path: \"/workflows/:id\",\n    summary: \"Get workflow by ID\",\n    description: \"Retrieve detailed information about a specific workflow by its ID.\",\n    tags: [\"Workflow Management\"],\n    operationId: \"getWorkflow\",\n    responses: {\n      200: {\n        description: \"Successfully retrieved workflow details\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Workflow not found\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to retrieve workflow due to server error\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  listWorkflowRuns: {\n    method: \"get\" as const,\n    path: \"/workflows/executions\",\n    summary: \"List workflow executions (query-driven)\",\n    description:\n      \"Retrieve workflow executions using query params (workflowId, status, from, to, limit, offset, userId) without path parameters. You can also filter metadata with `metadata` (JSON object) or key-based params such as `metadata.tenantId=acme`.\",\n    tags: [\"Workflow Management\"],\n    operationId: \"listWorkflowRuns\",\n    responses: {\n      200: {\n        description: \"Successfully retrieved workflow executions\",\n        contentType: \"application/json\",\n      },\n      400: {\n        description: \"Invalid query parameters\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Workflow not found\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to retrieve workflow executions due to server error\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  executeWorkflow: {\n    method: \"post\" as const,\n    path: \"/workflows/:id/execute\",\n    summary: \"Execute workflow synchronously\",\n    description:\n      \"Execute a workflow and wait for it to complete. This endpoint runs the workflow to completion and returns the final result. Use this for workflows that complete quickly or when you need the complete result before proceeding. For long-running workflows, consider using the streaming endpoint instead.\",\n    tags: [\"Workflow Management\"],\n    operationId: \"executeWorkflow\",\n    responses: {\n      200: {\n        description: \"Successfully executed workflow and returned final result\",\n        contentType: \"application/json\",\n      },\n      400: {\n        description: \"Invalid workflow input or parameters\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Workflow not found\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to execute workflow due to server error\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  streamWorkflow: {\n    method: \"post\" as const,\n    path: \"/workflows/:id/stream\",\n    summary: \"Stream workflow execution events\",\n    description:\n      \"Execute a workflow and stream real-time events via Server-Sent Events (SSE). The stream remains open during suspension and continues after resume.\",\n    tags: [\"Workflow Management\"],\n    operationId: \"streamWorkflow\",\n    responses: {\n      200: {\n        description: \"Successfully established SSE stream for workflow execution\",\n        contentType: \"text/event-stream\",\n      },\n      400: {\n        description: \"Invalid workflow input or parameters\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Workflow not found\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to stream workflow due to server error\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  attachWorkflowStream: {\n    method: \"get\" as const,\n    path: \"/workflows/:id/executions/:executionId/stream\",\n    summary: \"Attach to workflow execution stream\",\n    description:\n      \"Attach to an in-progress workflow execution stream and receive real-time events via Server-Sent Events (SSE). Use Last-Event-ID header or `fromSequence` query parameter to replay missed events on reconnect.\",\n    tags: [\"Workflow Management\"],\n    operationId: \"attachWorkflowStream\",\n    responses: {\n      200: {\n        description: \"Successfully attached to workflow SSE stream\",\n        contentType: \"text/event-stream\",\n      },\n      404: {\n        description: \"Workflow or execution not found\",\n        contentType: \"application/json\",\n      },\n      409: {\n        description: \"Workflow execution is not streamable in current state\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to attach workflow stream due to server error\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  suspendWorkflow: {\n    method: \"post\" as const,\n    path: \"/workflows/:id/executions/:executionId/suspend\",\n    summary: \"Suspend workflow execution\",\n    description:\n      \"Suspend a running workflow execution at its current step. This allows you to pause long-running workflows, perform external validations, wait for human approval, or handle rate limits. The workflow state is preserved and can be resumed later with the resume endpoint. Only workflows in 'running' state can be suspended.\",\n    tags: [\"Workflow Management\"],\n    operationId: \"suspendWorkflow\",\n    responses: {\n      200: {\n        description: \"Successfully suspended workflow execution\",\n        contentType: \"application/json\",\n      },\n      400: {\n        description: \"Workflow is not in a suspendable state\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Workflow or execution not found\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to suspend workflow due to server error\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  cancelWorkflow: {\n    method: \"post\" as const,\n    path: \"/workflows/:id/executions/:executionId/cancel\",\n    summary: \"Cancel workflow execution\",\n    description:\n      \"Cancel a running workflow execution immediately. The workflow stops execution and the state is marked as cancelled. Cancelled workflows cannot be resumed.\",\n    tags: [\"Workflow Management\"],\n    operationId: \"cancelWorkflow\",\n    responses: {\n      200: {\n        description: \"Successfully cancelled workflow execution\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Workflow or execution not found\",\n        contentType: \"application/json\",\n      },\n      409: {\n        description: \"Workflow execution already completed or not cancellable\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to cancel workflow due to server error\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  resumeWorkflow: {\n    method: \"post\" as const,\n    path: \"/workflows/:id/executions/:executionId/resume\",\n    summary: \"Resume suspended workflow\",\n    description:\n      \"Resume a previously suspended workflow execution from where it left off. You can optionally provide resume data that will be passed to the suspended step for processing. This is commonly used after human approval, external system responses, or scheduled resumptions. The workflow continues execution and returns the final result.\",\n    tags: [\"Workflow Management\"],\n    operationId: \"resumeWorkflow\",\n    responses: {\n      200: {\n        description: \"Successfully resumed workflow execution and returned final result\",\n        contentType: \"application/json\",\n      },\n      400: {\n        description: \"Workflow is not in a suspended state\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Workflow or execution not found\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to resume workflow due to server error\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  replayWorkflow: {\n    method: \"post\" as const,\n    path: \"/workflows/:id/executions/:executionId/replay\",\n    summary: \"Replay workflow execution from a step\",\n    description:\n      \"Create a deterministic replay execution from a historical workflow run and selected step. Replay creates a new execution ID and preserves the original run history.\",\n    tags: [\"Workflow Management\"],\n    operationId: \"replayWorkflow\",\n    responses: {\n      200: {\n        description: \"Successfully replayed workflow execution\",\n        contentType: \"application/json\",\n      },\n      400: {\n        description: \"Invalid replay parameters\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Workflow or source execution not found\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to replay workflow due to server error\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  getWorkflowState: {\n    method: \"get\" as const,\n    path: \"/workflows/:id/executions/:executionId/state\",\n    summary: \"Get workflow execution state\",\n    description:\n      \"Retrieve the workflow execution state including input data, suspension information, context, and current status. This is essential for understanding the current state of a workflow execution, especially for suspended workflows that need to be resumed with the correct context.\",\n    tags: [\"Workflow Management\"],\n    operationId: \"getWorkflowState\",\n    responses: {\n      200: {\n        description: \"Successfully retrieved workflow execution state\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Workflow or execution not found\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to retrieve workflow state due to server error\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n} as const;\n\n/**\n * Log route definitions\n */\nexport const LOG_ROUTES = {\n  getLogs: {\n    method: \"get\" as const,\n    path: \"/api/logs\",\n    summary: \"Get logs with filters\",\n    description:\n      \"Retrieve system logs with optional filtering by level, agent ID, workflow ID, conversation ID, execution ID, and time range.\",\n    tags: [\"Logging\"],\n    operationId: \"getLogs\",\n    responses: {\n      200: {\n        description: \"Successfully retrieved filtered log entries\",\n        contentType: \"application/json\",\n      },\n      400: {\n        description: \"Invalid filter parameters\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to retrieve logs due to server error\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n} as const;\n\n/**\n * Update route definitions\n */\nexport const UPDATE_ROUTES = {\n  checkUpdates: {\n    method: \"get\" as const,\n    path: \"/updates\",\n    summary: \"Check for updates\",\n    description: \"Check for available package updates in the VoltAgent ecosystem.\",\n    tags: [\"System\"],\n    operationId: \"checkUpdates\",\n    responses: {\n      200: {\n        description: \"Successfully checked for available updates\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to check updates due to server error\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  installUpdates: {\n    method: \"post\" as const,\n    path: \"/updates\",\n    summary: \"Install updates\",\n    description:\n      \"Install available updates for VoltAgent packages. Can install a single package or all packages.\",\n    tags: [\"System\"],\n    operationId: \"installUpdates\",\n    responses: {\n      200: {\n        description: \"Successfully installed requested updates\",\n        contentType: \"application/json\",\n      },\n      400: {\n        description: \"Invalid update request or package not found\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to install updates due to server error\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  installSingleUpdate: {\n    method: \"post\" as const,\n    path: \"/updates/:packageName\",\n    summary: \"Install single package update\",\n    description:\n      \"Install update for a specific VoltAgent package. The package manager is automatically detected based on lock files (pnpm-lock.yaml, yarn.lock, package-lock.json, or bun.lockb).\",\n    tags: [\"System\"],\n    operationId: \"installSingleUpdate\",\n    responses: {\n      200: {\n        description: \"Successfully installed package update\",\n        contentType: \"application/json\",\n      },\n      400: {\n        description: \"Invalid package name or package not found\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to install update due to server error\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n} as const;\n\n/**\n * Observability route definitions\n */\nexport const OBSERVABILITY_ROUTES = {\n  setupObservability: {\n    method: \"post\" as const,\n    path: \"/setup-observability\",\n    summary: \"Configure observability settings\",\n    description:\n      \"Updates the .env file with VoltAgent public and secret keys to enable observability features. This allows automatic tracing and monitoring of agent operations.\",\n    tags: [\"Observability\"],\n    operationId: \"setupObservability\",\n    responses: {\n      200: {\n        description: \"Successfully configured observability settings\",\n        contentType: \"application/json\",\n      },\n      400: {\n        description: \"Invalid request - missing publicKey or secretKey\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to update .env file\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  getTraces: {\n    method: \"get\" as const,\n    path: \"/observability/traces\",\n    summary: \"List all traces\",\n    description:\n      \"Retrieve all OpenTelemetry traces from the observability store. Each trace represents a complete operation with its spans showing the execution flow.\",\n    tags: [\"Observability\"],\n    operationId: \"getTraces\",\n    responses: {\n      200: {\n        description: \"Successfully retrieved traces\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to retrieve traces due to server error\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  getTraceById: {\n    method: \"get\" as const,\n    path: \"/observability/traces/:traceId\",\n    summary: \"Get trace by ID\",\n    description: \"Retrieve a specific trace and all its spans by trace ID.\",\n    tags: [\"Observability\"],\n    operationId: \"getTraceById\",\n    responses: {\n      200: {\n        description: \"Successfully retrieved trace\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Trace not found\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to retrieve trace due to server error\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  getSpanById: {\n    method: \"get\" as const,\n    path: \"/observability/spans/:spanId\",\n    summary: \"Get span by ID\",\n    description: \"Retrieve a specific span by its ID.\",\n    tags: [\"Observability\"],\n    operationId: \"getSpanById\",\n    responses: {\n      200: {\n        description: \"Successfully retrieved span\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Span not found\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to retrieve span due to server error\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  getObservabilityStatus: {\n    method: \"get\" as const,\n    path: \"/observability/status\",\n    summary: \"Get observability status\",\n    description: \"Check the status and configuration of the observability system.\",\n    tags: [\"Observability\"],\n    operationId: \"getObservabilityStatus\",\n    responses: {\n      200: {\n        description: \"Successfully retrieved observability status\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to retrieve status due to server error\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  getLogsByTraceId: {\n    method: \"get\" as const,\n    path: \"/observability/traces/:traceId/logs\",\n    summary: \"Get logs by trace ID\",\n    description: \"Retrieve all logs associated with a specific trace ID.\",\n    tags: [\"Observability\"],\n    operationId: \"getLogsByTraceId\",\n    responses: {\n      200: {\n        description: \"Successfully retrieved logs\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"No logs found for the trace\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to retrieve logs due to server error\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  getLogsBySpanId: {\n    method: \"get\" as const,\n    path: \"/observability/spans/:spanId/logs\",\n    summary: \"Get logs by span ID\",\n    description: \"Retrieve all logs associated with a specific span ID.\",\n    tags: [\"Observability\"],\n    operationId: \"getLogsBySpanId\",\n    responses: {\n      200: {\n        description: \"Successfully retrieved logs\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"No logs found for the span\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to retrieve logs due to server error\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  queryLogs: {\n    method: \"get\" as const,\n    path: \"/observability/logs\",\n    summary: \"Query logs\",\n    description: \"Query logs with filters such as severity, time range, trace ID, etc.\",\n    tags: [\"Observability\"],\n    operationId: \"queryLogs\",\n    responses: {\n      200: {\n        description: \"Successfully retrieved logs\",\n        contentType: \"application/json\",\n      },\n      400: {\n        description: \"Invalid query parameters\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to query logs due to server error\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n} as const;\n\nexport const OBSERVABILITY_MEMORY_ROUTES = {\n  listMemoryUsers: {\n    method: \"get\" as const,\n    path: \"/observability/memory/users\",\n    summary: \"List memory users\",\n    description:\n      \"Retrieve all users who have associated memory records. Supports optional filtering by agent and pagination controls.\",\n    tags: [\"Observability\", \"Memory\"],\n    operationId: \"listMemoryUsers\",\n    responses: {\n      200: {\n        description: \"Successfully retrieved users\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to retrieve memory users due to server error\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  listMemoryConversations: {\n    method: \"get\" as const,\n    path: \"/observability/memory/conversations\",\n    summary: \"List memory conversations\",\n    description:\n      \"Retrieve conversations stored in memory with optional filtering by agent or user. Results are paginated and sorted by last update by default.\",\n    tags: [\"Observability\", \"Memory\"],\n    operationId: \"listObservabilityMemoryConversations\",\n    responses: {\n      200: {\n        description: \"Successfully retrieved conversations\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to retrieve conversations due to server error\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  getMemoryConversationMessages: {\n    method: \"get\" as const,\n    path: \"/observability/memory/conversations/:conversationId/messages\",\n    summary: \"Get conversation messages\",\n    description:\n      \"Fetch the messages for a specific conversation stored in memory. Supports optional role filtering and windowing via before/after parameters.\",\n    tags: [\"Observability\", \"Memory\"],\n    operationId: \"getMemoryConversationMessages\",\n    responses: {\n      200: {\n        description: \"Successfully retrieved messages\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Conversation not found\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to retrieve messages due to server error\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  getConversationSteps: {\n    method: \"get\" as const,\n    path: \"/observability/memory/conversations/:conversationId/steps\",\n    summary: \"Get conversation steps\",\n    description: \"Fetch the recorded agent steps for a specific conversation stored in memory.\",\n    tags: [\"Observability\", \"Memory\"],\n    operationId: \"getConversationSteps\",\n    responses: {\n      200: {\n        description: \"Successfully retrieved conversation steps\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Conversation not found\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to retrieve conversation steps due to server error\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  getWorkingMemory: {\n    method: \"get\" as const,\n    path: \"/observability/memory/working-memory\",\n    summary: \"Get working memory\",\n    description:\n      \"Retrieve working memory content for a conversation or user. Specify the scope and relevant identifiers in query parameters.\",\n    tags: [\"Observability\", \"Memory\"],\n    operationId: \"getWorkingMemory\",\n    responses: {\n      200: {\n        description: \"Successfully retrieved working memory\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Working memory not found\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to retrieve working memory due to server error\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n} as const;\n\n/**\n * Tool route definitions\n */\nexport const TOOL_ROUTES = {\n  listTools: {\n    method: \"get\" as const,\n    path: \"/tools\",\n    summary: \"List all tools\",\n    description:\n      \"Retrieve a list of all tools registered across agents. Includes name, description, parameters, and owning agent metadata.\",\n    tags: [\"Tools\"],\n    operationId: \"listTools\",\n    responses: {\n      200: {\n        description: \"Successfully retrieved list of tools\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to retrieve tools due to server error\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  executeTool: {\n    method: \"post\" as const,\n    path: \"/tools/:name/execute\",\n    summary: \"Execute a tool directly\",\n    description:\n      \"Execute a registered tool directly via HTTP without going through the agent chat flow. Accepts tool input and optional context metadata.\",\n    tags: [\"Tools\"],\n    operationId: \"executeTool\",\n    responses: {\n      200: {\n        description: \"Successfully executed tool\",\n        contentType: \"application/json\",\n      },\n      400: {\n        description: \"Invalid request or tool input\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Tool not found\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to execute tool due to server error\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n} as const;\n\n/**\n * Memory route definitions\n */\nexport const MEMORY_ROUTES = {\n  listConversations: {\n    method: \"get\" as const,\n    path: \"/api/memory/conversations\",\n    summary: \"List memory conversations\",\n    description:\n      \"Retrieve conversations stored in memory with optional filtering by resource or user.\",\n    tags: [\"Memory\"],\n    operationId: \"listMemoryConversations\",\n    responses: {\n      200: {\n        description: \"Successfully retrieved memory conversations\",\n        contentType: \"application/json\",\n      },\n      400: {\n        description: \"Invalid query parameters\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to list memory conversations\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  getConversation: {\n    method: \"get\" as const,\n    path: \"/api/memory/conversations/:conversationId\",\n    summary: \"Get conversation by ID\",\n    description: \"Retrieve a single conversation by ID from memory storage.\",\n    tags: [\"Memory\"],\n    operationId: \"getMemoryConversation\",\n    responses: {\n      200: {\n        description: \"Successfully retrieved conversation\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Conversation not found\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to retrieve conversation\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  listMessages: {\n    method: \"get\" as const,\n    path: \"/api/memory/conversations/:conversationId/messages\",\n    summary: \"List conversation messages\",\n    description: \"Retrieve messages for a conversation with optional filtering.\",\n    tags: [\"Memory\"],\n    operationId: \"listMemoryConversationMessages\",\n    responses: {\n      200: {\n        description: \"Successfully retrieved conversation messages\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Conversation not found\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to retrieve conversation messages\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  getMemoryWorkingMemory: {\n    method: \"get\" as const,\n    path: \"/api/memory/conversations/:conversationId/working-memory\",\n    summary: \"Get working memory\",\n    description: \"Retrieve working memory content for a conversation.\",\n    tags: [\"Memory\"],\n    operationId: \"getMemoryWorkingMemory\",\n    responses: {\n      200: {\n        description: \"Successfully retrieved working memory\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Working memory not found\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to retrieve working memory\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  saveMessages: {\n    method: \"post\" as const,\n    path: \"/api/memory/save-messages\",\n    summary: \"Save messages\",\n    description: \"Persist new messages into memory storage.\",\n    tags: [\"Memory\"],\n    operationId: \"saveMemoryMessages\",\n    responses: {\n      200: {\n        description: \"Successfully saved messages\",\n        contentType: \"application/json\",\n      },\n      400: {\n        description: \"Invalid request body\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to save messages\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  createConversation: {\n    method: \"post\" as const,\n    path: \"/api/memory/conversations\",\n    summary: \"Create conversation\",\n    description: \"Create a new conversation in memory storage.\",\n    tags: [\"Memory\"],\n    operationId: \"createMemoryConversation\",\n    responses: {\n      200: {\n        description: \"Successfully created conversation\",\n        contentType: \"application/json\",\n      },\n      400: {\n        description: \"Invalid request body\",\n        contentType: \"application/json\",\n      },\n      409: {\n        description: \"Conversation already exists\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to create conversation\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  updateConversation: {\n    method: \"patch\" as const,\n    path: \"/api/memory/conversations/:conversationId\",\n    summary: \"Update conversation\",\n    description: \"Update an existing conversation in memory storage.\",\n    tags: [\"Memory\"],\n    operationId: \"updateMemoryConversation\",\n    responses: {\n      200: {\n        description: \"Successfully updated conversation\",\n        contentType: \"application/json\",\n      },\n      400: {\n        description: \"Invalid request body\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Conversation not found\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to update conversation\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  deleteConversation: {\n    method: \"delete\" as const,\n    path: \"/api/memory/conversations/:conversationId\",\n    summary: \"Delete conversation\",\n    description: \"Delete a conversation and its messages from memory storage.\",\n    tags: [\"Memory\"],\n    operationId: \"deleteMemoryConversation\",\n    responses: {\n      200: {\n        description: \"Successfully deleted conversation\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Conversation not found\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to delete conversation\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  cloneConversation: {\n    method: \"post\" as const,\n    path: \"/api/memory/conversations/:conversationId/clone\",\n    summary: \"Clone conversation\",\n    description: \"Create a copy of a conversation, optionally including messages.\",\n    tags: [\"Memory\"],\n    operationId: \"cloneMemoryConversation\",\n    responses: {\n      200: {\n        description: \"Successfully cloned conversation\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Conversation not found\",\n        contentType: \"application/json\",\n      },\n      409: {\n        description: \"Conversation already exists\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to clone conversation\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  updateWorkingMemory: {\n    method: \"post\" as const,\n    path: \"/api/memory/conversations/:conversationId/working-memory\",\n    summary: \"Update working memory\",\n    description: \"Update working memory content for a conversation.\",\n    tags: [\"Memory\"],\n    operationId: \"updateMemoryWorkingMemory\",\n    responses: {\n      200: {\n        description: \"Successfully updated working memory\",\n        contentType: \"application/json\",\n      },\n      400: {\n        description: \"Invalid request body\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Conversation not found\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to update working memory\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  deleteMessages: {\n    method: \"post\" as const,\n    path: \"/api/memory/messages/delete\",\n    summary: \"Delete messages\",\n    description: \"Delete specific messages from memory storage.\",\n    tags: [\"Memory\"],\n    operationId: \"deleteMemoryMessages\",\n    responses: {\n      200: {\n        description: \"Successfully deleted messages\",\n        contentType: \"application/json\",\n      },\n      400: {\n        description: \"Invalid request body\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to delete messages\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  searchMemory: {\n    method: \"get\" as const,\n    path: \"/api/memory/search\",\n    summary: \"Search memory\",\n    description: \"Search memory using semantic search when available.\",\n    tags: [\"Memory\"],\n    operationId: \"searchMemory\",\n    responses: {\n      200: {\n        description: \"Successfully searched memory\",\n        contentType: \"application/json\",\n      },\n      400: {\n        description: \"Invalid query parameters\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to search memory\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n} as const;\n\n/**\n * All route definitions combined\n */\nexport const ALL_ROUTES = {\n  ...AGENT_ROUTES,\n  ...WORKFLOW_ROUTES,\n  ...TOOL_ROUTES,\n  ...LOG_ROUTES,\n  ...UPDATE_ROUTES,\n  ...MEMORY_ROUTES,\n  ...OBSERVABILITY_ROUTES,\n  ...OBSERVABILITY_MEMORY_ROUTES,\n} as const;\n\n/**\n * Helper to get all routes as an array\n */\nexport function getAllRoutesArray(): RouteDefinition[] {\n  return Object.values(ALL_ROUTES).map((route) => ({\n    ...route,\n    tags: [...route.tags], // Convert readonly array to mutable array\n    responses: route.responses ? { ...route.responses } : undefined,\n  }));\n}\n\n/**\n * MCP route definitions\n */\nexport const MCP_ROUTES = {\n  listServers: {\n    method: \"get\" as const,\n    path: \"/mcp/servers\",\n    summary: \"List MCP servers\",\n    description:\n      \"Return metadata for all MCP servers currently registered with the running VoltAgent instance.\",\n    tags: [\"MCP\"],\n    operationId: \"listMcpServers\",\n    responses: {\n      200: {\n        description: \"Successfully retrieved the list of MCP servers\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to retrieve MCP servers\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  getServer: {\n    method: \"get\" as const,\n    path: \"/mcp/servers/:serverId\",\n    summary: \"Get MCP server metadata\",\n    description: \"Return metadata for a specific MCP server by ID.\",\n    tags: [\"MCP\"],\n    operationId: \"getMcpServer\",\n    responses: {\n      200: {\n        description: \"Successfully retrieved MCP server metadata\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Requested MCP server does not exist\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  listTools: {\n    method: \"get\" as const,\n    path: \"/mcp/servers/:serverId/tools\",\n    summary: \"List MCP server tools\",\n    description:\n      \"Return the tools exposed by a specific MCP server, including metadata for UI rendering.\",\n    tags: [\"MCP\"],\n    operationId: \"listMcpServerTools\",\n    responses: {\n      200: {\n        description: \"Successfully retrieved tool metadata\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Requested MCP server does not exist or has no tools\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to retrieve MCP tools\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  invokeTool: {\n    method: \"post\" as const,\n    path: \"/mcp/servers/:serverId/tools/:toolName\",\n    summary: \"Invoke MCP tool\",\n    description: \"Execute a single MCP tool exposed by the given server with provided arguments.\",\n    tags: [\"MCP\"],\n    operationId: \"invokeMcpTool\",\n    responses: {\n      200: {\n        description: \"Tool executed successfully\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Requested MCP server or tool does not exist\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Tool execution failed\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  setLogLevel: {\n    method: \"post\" as const,\n    path: \"/mcp/servers/:serverId/logging/level\",\n    summary: \"Update MCP logging level\",\n    description:\n      \"Update the logging level of an MCP server when the logging capability is enabled.\",\n    tags: [\"MCP\"],\n    operationId: \"setMcpLogLevel\",\n    responses: {\n      200: {\n        description: \"Logging level updated\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Requested MCP server does not support logging capability\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to update logging level\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  listPrompts: {\n    method: \"get\" as const,\n    path: \"/mcp/servers/:serverId/prompts\",\n    summary: \"List MCP prompts\",\n    description:\n      \"Return all prompts exposed by an MCP server when the prompts capability is enabled.\",\n    tags: [\"MCP\"],\n    operationId: \"listMcpPrompts\",\n    responses: {\n      200: {\n        description: \"Successfully retrieved MCP prompts\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Requested MCP server does not expose prompts\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to retrieve MCP prompts\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  getPrompt: {\n    method: \"get\" as const,\n    path: \"/mcp/servers/:serverId/prompts/:promptName\",\n    summary: \"Get MCP prompt\",\n    description:\n      \"Retrieve a fully resolved prompt by name from an MCP server, optionally templated with arguments.\",\n    tags: [\"MCP\"],\n    operationId: \"getMcpPrompt\",\n    responses: {\n      200: {\n        description: \"Successfully retrieved MCP prompt\",\n        contentType: \"application/json\",\n      },\n      400: {\n        description: \"Invalid prompt arguments\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Requested MCP server does not expose prompts\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to retrieve MCP prompt\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  listResources: {\n    method: \"get\" as const,\n    path: \"/mcp/servers/:serverId/resources\",\n    summary: \"List MCP resources\",\n    description:\n      \"Return all static or dynamic resources available from an MCP server when the resources capability is enabled.\",\n    tags: [\"MCP\"],\n    operationId: \"listMcpResources\",\n    responses: {\n      200: {\n        description: \"Successfully retrieved MCP resources\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Requested MCP server does not expose resources\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to retrieve MCP resources\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  readResource: {\n    method: \"get\" as const,\n    path: \"/mcp/servers/:serverId/resources/contents\",\n    summary: \"Read MCP resource\",\n    description: \"Fetch the contents of a resource by URI from an MCP server.\",\n    tags: [\"MCP\"],\n    operationId: \"readMcpResource\",\n    responses: {\n      200: {\n        description: \"Successfully retrieved MCP resource contents\",\n        contentType: \"application/json\",\n      },\n      400: {\n        description: \"Missing or invalid resource URI\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Requested MCP server does not expose resources\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to retrieve MCP resource contents\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  listResourceTemplates: {\n    method: \"get\" as const,\n    path: \"/mcp/servers/:serverId/resource-templates\",\n    summary: \"List MCP resource templates\",\n    description: \"Return resource templates exposed by an MCP server when supported.\",\n    tags: [\"MCP\"],\n    operationId: \"listMcpResourceTemplates\",\n    responses: {\n      200: {\n        description: \"Successfully retrieved MCP resource templates\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Requested MCP server does not expose resource templates\",\n        contentType: \"application/json\",\n      },\n      500: {\n        description: \"Failed to retrieve MCP resource templates\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n} satisfies Record<string, RouteDefinition>;\n\nexport const A2A_ROUTES = {\n  agentCard: {\n    method: \"get\" as const,\n    path: \"/.well-known/:serverId/agent-card.json\",\n    summary: \"Get A2A agent card\",\n    description: \"Return the agent card JSON document for the specified A2A server.\",\n    tags: [\"A2A\"],\n    operationId: \"getA2AAgentCard\",\n    responses: {\n      200: {\n        description: \"Agent card retrieved successfully\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Requested A2A server not found\",\n        contentType: \"application/json\",\n      },\n      400: {\n        description: \"Invalid request parameters\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n  jsonRpc: {\n    method: \"post\" as const,\n    path: \"/a2a/:serverId\",\n    summary: \"Dispatch A2A JSON-RPC request\",\n    description:\n      \"Forward a JSON-RPC message (message/send, message/stream, tasks/get, tasks/cancel) to the specified A2A server.\",\n    tags: [\"A2A\"],\n    operationId: \"executeA2ARequest\",\n    responses: {\n      200: {\n        description: \"Request accepted or completed\",\n        contentType: \"application/json\",\n      },\n      400: {\n        description: \"Invalid JSON-RPC payload\",\n        contentType: \"application/json\",\n      },\n      404: {\n        description: \"Requested A2A server not found\",\n        contentType: \"application/json\",\n      },\n    },\n  },\n} satisfies Record<string, RouteDefinition>;\n\n/**\n * Helper to get routes by tag\n */\nexport function getRoutesByTag(tag: string): RouteDefinition[] {\n  return getAllRoutesArray().filter((route) => route.tags.includes(tag));\n}\n","import { ClientHTTPError, type ServerProviderDeps } from \"@voltagent/core\";\nimport { convertUsage } from \"@voltagent/core\";\nimport { type Logger, safeStringify } from \"@voltagent/internal\";\nimport { type UIMessage, UI_MESSAGE_STREAM_HEADERS, generateId } from \"ai\";\nimport { z } from \"zod\";\nimport { convertJsonSchemaToZod } from \"zod-from-json-schema\";\nimport { convertJsonSchemaToZod as convertJsonSchemaToZodV3 } from \"zod-from-json-schema-v3\";\nimport type { ApiResponse } from \"../types\";\nimport { processAgentOptions } from \"../utils/options\";\n\n/**\n * Handler for listing all agents\n * Returns agent data array\n */\nexport async function handleGetAgents(\n  deps: ServerProviderDeps,\n  logger: Logger,\n): Promise<ApiResponse> {\n  try {\n    const agents = deps.agentRegistry.getAllAgents();\n\n    const agentDataArray = agents.map((agent) => {\n      const fullState = agent.getFullState();\n      const isTelemetryEnabled = agent.isTelemetryConfigured();\n      return {\n        id: fullState.id,\n        name: fullState.name,\n        description: fullState.instructions,\n        status: fullState.status,\n        model: fullState.model,\n        tools: fullState.tools,\n        subAgents: fullState.subAgents?.map((subAgent) => ({\n          id: subAgent.id,\n          name: subAgent.name,\n          description: subAgent.instructions,\n          status: subAgent.status,\n          model: subAgent.model,\n          tools: subAgent.tools,\n          memory: subAgent.memory,\n        })),\n        memory: fullState.memory,\n        isTelemetryEnabled,\n      };\n    });\n\n    return {\n      success: true,\n      data: agentDataArray,\n    };\n  } catch (error) {\n    logger.error(\"Failed to get agents\", { error });\n    return {\n      success: false,\n      error: error instanceof Error ? error.message : \"Unknown error\",\n    };\n  }\n}\n\n/**\n * Handler for generating text\n * Returns generated text data\n */\nexport async function handleGenerateText(\n  agentId: string,\n  body: any,\n  deps: ServerProviderDeps,\n  logger: Logger,\n  signal?: AbortSignal,\n  requestHeaders?: Headers | Record<string, string | string[] | undefined>,\n): Promise<ApiResponse> {\n  try {\n    const agent = deps.agentRegistry.getAgent(agentId);\n    if (!agent) {\n      return {\n        success: false,\n        error: `Agent ${agentId} not found`,\n      };\n    }\n\n    const { input } = body;\n    const options = processAgentOptions(body, signal, requestHeaders);\n\n    const result = await agent.generateText(input, options);\n\n    // Convert usage format if present\n    const usage = result.usage ? convertUsage(result.usage) : undefined;\n\n    return {\n      success: true,\n      data: {\n        text: result.text,\n        usage,\n        finishReason: result.finishReason,\n        toolCalls: result.toolCalls,\n        toolResults: result.toolResults,\n        feedback: result.feedback ?? null,\n        // Try to access output safely - getter throws if not defined\n        ...(() => {\n          try {\n            return result.output ? { output: result.output } : {};\n          } catch {\n            return {};\n          }\n        })(),\n      },\n    };\n  } catch (error) {\n    logger.error(\"Failed to generate text\", { error });\n    if (error instanceof ClientHTTPError) {\n      return {\n        success: false,\n        error: error.message,\n        code: error.code,\n        name: error.name,\n        httpStatus: error.httpStatus,\n      };\n    }\n    return {\n      success: false,\n      error: error instanceof Error ? error.message : \"Unknown error\",\n    };\n  }\n}\n\n/**\n * Handler for streaming text generation with raw fullStream\n * Returns raw stream data via SSE\n */\nexport async function handleStreamText(\n  agentId: string,\n  body: any,\n  deps: ServerProviderDeps,\n  logger: Logger,\n  signal?: AbortSignal,\n  requestHeaders?: Headers | Record<string, string | string[] | undefined>,\n): Promise<Response> {\n  try {\n    const agent = deps.agentRegistry.getAgent(agentId);\n    if (!agent) {\n      return new Response(\n        safeStringify({\n          error: `Agent ${agentId} not found`,\n          message: `Agent ${agentId} not found`,\n        }),\n        {\n          status: 404,\n          headers: {\n            \"Content-Type\": \"application/json\",\n          },\n        },\n      );\n    }\n\n    const { input } = body;\n    const options = processAgentOptions(body, signal, requestHeaders);\n\n    const result = await agent.streamText(input, options);\n\n    // Access the fullStream property\n    const { fullStream } = result;\n\n    // Convert fullStream to SSE format\n    const encoder = new TextEncoder();\n    const stream = new ReadableStream({\n      async start(controller) {\n        try {\n          for await (const part of fullStream) {\n            // Send each part as a JSON-encoded SSE event\n            const data = `data: ${safeStringify(part)}\\n\\n`;\n            controller.enqueue(encoder.encode(data));\n          }\n        } catch (error) {\n          logger.error(\"Error in fullStream iteration\", { error });\n          // Send error event\n          const errorData = `data: ${safeStringify({ type: \"error\", error: error instanceof Error ? error.message : \"Unknown error\" })}\\n\\n`;\n          controller.enqueue(encoder.encode(errorData));\n        } finally {\n          controller.close();\n        }\n      },\n    });\n\n    return new Response(stream, {\n      status: 200,\n      headers: {\n        \"Content-Type\": \"text/event-stream\",\n        \"Cache-Control\": \"no-cache\",\n        Connection: \"keep-alive\",\n      },\n    });\n  } catch (error) {\n    logger.error(\"Failed to handle stream text request\", { error });\n\n    const errorMessage = error instanceof Error ? error.message : \"Unknown error\";\n\n    return new Response(\n      safeStringify({\n        error: errorMessage,\n        message: errorMessage,\n      }),\n      {\n        status: 500,\n        headers: {\n          \"Content-Type\": \"application/json\",\n        },\n      },\n    );\n  }\n}\n\n/**\n * Handler for streaming chat messages\n * Returns AI SDK UI Message Stream Response\n */\nexport async function handleChatStream(\n  agentId: string,\n  body: any,\n  deps: ServerProviderDeps,\n  logger: Logger,\n  signal?: AbortSignal,\n  requestHeaders?: Headers | Record<string, string | string[] | undefined>,\n): Promise<Response> {\n  try {\n    const agent = deps.agentRegistry.getAgent(agentId);\n    if (!agent) {\n      return new Response(\n        safeStringify({\n          error: `Agent ${agentId} not found`,\n          message: `Agent ${agentId} not found`,\n        }),\n        {\n          status: 404,\n          headers: {\n            \"Content-Type\": \"application/json\",\n          },\n        },\n      );\n    }\n\n    const { input } = body;\n    const originalMessages =\n      Array.isArray(input) &&\n      input.length > 0 &&\n      input.every((message) => Array.isArray((message as { parts?: unknown }).parts))\n        ? (input as UIMessage[])\n        : undefined;\n    let resumableStreamRequested =\n      typeof body?.options?.resumableStream === \"boolean\"\n        ? body.options.resumableStream\n        : (deps.resumableStreamDefault ?? false);\n    const options = processAgentOptions(body, signal, requestHeaders);\n    const memory =\n      options.memory && typeof options.memory === \"object\" ? options.memory : undefined;\n    const memoryConversationId =\n      memory && typeof memory.conversationId === \"string\" && memory.conversationId.trim().length > 0\n        ? memory.conversationId\n        : undefined;\n    const memoryUserId =\n      memory && typeof memory.userId === \"string\" && memory.userId.trim().length > 0\n        ? memory.userId\n        : undefined;\n    const conversationId =\n      memoryConversationId ??\n      (typeof options.conversationId === \"string\" ? options.conversationId : undefined);\n    const userId =\n      memoryUserId ??\n      (typeof options.userId === \"string\" && options.userId.trim().length > 0\n        ? options.userId\n        : undefined);\n    const resumableEnabled = Boolean(deps.resumableStream);\n    const resumableStreamEnabled =\n      resumableEnabled &&\n      resumableStreamRequested === true &&\n      Boolean(conversationId) &&\n      Boolean(userId);\n\n    if (resumableStreamRequested === true && !resumableEnabled) {\n      logger.warn(\n        \"Resumable streams requested but not configured. Falling back to non-resumable streams.\",\n        {\n          docsUrl: \"https://voltagent.dev/docs/agents/resumable-streaming/\",\n        },\n      );\n      resumableStreamRequested = false;\n    }\n\n    if (resumableStreamRequested === true && !conversationId) {\n      return new Response(\n        safeStringify({\n          error: \"conversationId is required for resumable streams\",\n          message: \"conversationId is required for resumable streams\",\n        }),\n        {\n          status: 400,\n          headers: {\n            \"Content-Type\": \"application/json\",\n          },\n        },\n      );\n    }\n\n    if (resumableStreamRequested === true && !userId) {\n      return new Response(\n        safeStringify({\n          error: \"userId is required for resumable streams\",\n          message: \"userId is required for resumable streams\",\n        }),\n        {\n          status: 400,\n          headers: {\n            \"Content-Type\": \"application/json\",\n          },\n        },\n      );\n    }\n\n    if (resumableStreamEnabled) {\n      options.abortSignal = undefined;\n    }\n\n    options.resumableStream = resumableStreamEnabled;\n\n    const resumableStreamAdapter = deps.resumableStream;\n    if (resumableStreamEnabled && resumableStreamAdapter && conversationId && userId) {\n      try {\n        await resumableStreamAdapter.clearActiveStream({ conversationId, agentId, userId });\n      } catch (error) {\n        logger.warn(\"Failed to clear active resumable stream\", { error });\n      }\n    }\n\n    const result = await agent.streamText(input, options);\n    let activeStreamId: string | null = null;\n\n    // Use the built-in toUIMessageStreamResponse - it handles errors properly\n    return result.toUIMessageStreamResponse({\n      originalMessages,\n      generateMessageId: generateId,\n      sendReasoning: true,\n      sendSources: true,\n      consumeSseStream: async ({ stream }) => {\n        if (!resumableStreamEnabled || !resumableStreamAdapter || !conversationId || !userId) {\n          return;\n        }\n\n        try {\n          activeStreamId = await resumableStreamAdapter.createStream({\n            conversationId,\n            agentId,\n            userId,\n            stream,\n          });\n        } catch (error) {\n          logger.error(\"Failed to persist resumable chat stream\", { error });\n        }\n      },\n      onFinish: async () => {\n        if (!resumableStreamEnabled || !resumableStreamAdapter || !conversationId || !userId) {\n          return;\n        }\n\n        try {\n          await resumableStreamAdapter.clearActiveStream({\n            conversationId,\n            agentId,\n            userId,\n            streamId: activeStreamId ?? undefined,\n          });\n        } catch (error) {\n          logger.error(\"Failed to clear resumable chat stream\", { error });\n        }\n      },\n    });\n  } catch (error) {\n    logger.error(\"Failed to handle chat stream request\", { error });\n\n    const errorMessage = error instanceof Error ? error.message : \"Unknown error\";\n\n    return new Response(\n      safeStringify({\n        error: errorMessage,\n        message: errorMessage,\n      }),\n      {\n        status: 500,\n        headers: {\n          \"Content-Type\": \"application/json\",\n        },\n      },\n    );\n  }\n}\n\n/**\n * Handler for resuming chat streams\n * Returns SSE stream if active, or 204 if no stream is active\n */\nexport async function handleResumeChatStream(\n  agentId: string,\n  conversationId: string,\n  deps: ServerProviderDeps,\n  logger: Logger,\n  userId?: string,\n): Promise<Response> {\n  try {\n    if (!deps.resumableStream) {\n      return new Response(null, { status: 204 });\n    }\n\n    if (!userId) {\n      return new Response(\n        safeStringify({\n          error: \"userId is required for resumable streams\",\n          message: \"userId is required for resumable streams\",\n        }),\n        {\n          status: 400,\n          headers: {\n            \"Content-Type\": \"application/json\",\n          },\n        },\n      );\n    }\n\n    const streamId = await deps.resumableStream.getActiveStreamId({\n      conversationId,\n      agentId,\n      userId,\n    });\n\n    if (!streamId) {\n      return new Response(null, { status: 204 });\n    }\n\n    const stream = await deps.resumableStream.resumeStream(streamId);\n    if (!stream) {\n      try {\n        await deps.resumableStream.clearActiveStream({\n          conversationId,\n          agentId,\n          userId,\n          streamId,\n        });\n      } catch (error) {\n        logger.warn(\"Failed to clear inactive resumable stream\", { error });\n      }\n      return new Response(null, { status: 204 });\n    }\n\n    const encodedStream = stream.pipeThrough(new TextEncoderStream());\n\n    return new Response(encodedStream, {\n      status: 200,\n      headers: UI_MESSAGE_STREAM_HEADERS,\n    });\n  } catch (error) {\n    logger.error(\"Failed to resume chat stream\", { error });\n    const errorMessage = error instanceof Error ? error.message : \"Unknown error\";\n    return new Response(\n      safeStringify({\n        error: errorMessage,\n        message: errorMessage,\n      }),\n      {\n        status: 500,\n        headers: {\n          \"Content-Type\": \"application/json\",\n        },\n      },\n    );\n  }\n}\n\n/**\n * Handler for generating objects\n * Returns generated object data\n */\nexport async function handleGenerateObject(\n  agentId: string,\n  body: any,\n  deps: ServerProviderDeps,\n  logger: Logger,\n  signal?: AbortSignal,\n  requestHeaders?: Headers | Record<string, string | string[] | undefined>,\n): Promise<ApiResponse> {\n  try {\n    const agent = deps.agentRegistry.getAgent(agentId);\n    if (!agent) {\n      return {\n        success: false,\n        error: `Agent ${agentId} not found`,\n      };\n    }\n\n    const { input, schema: jsonSchema } = body;\n    const options = processAgentOptions(body, signal, requestHeaders);\n\n    // Convert JSON schema to Zod schema (supports zod v3 and v4)\n    const zodSchema = (\"toJSONSchema\" in z ? convertJsonSchemaToZod : convertJsonSchemaToZodV3)(\n      jsonSchema,\n    ) as any;\n\n    const result = await agent.generateObject(input, zodSchema, options);\n\n    return {\n      success: true,\n      data: result.object,\n    };\n  } catch (error) {\n    logger.error(\"Failed to generate object\", { error });\n    return {\n      success: false,\n      error: error instanceof Error ? error.message : \"Unknown error\",\n    };\n  }\n}\n\n/**\n * Handler for streaming object generation\n * Returns AI SDK Response or error\n */\nexport async function handleStreamObject(\n  agentId: string,\n  body: any,\n  deps: ServerProviderDeps,\n  logger: Logger,\n  signal?: AbortSignal,\n  requestHeaders?: Headers | Record<string, string | string[] | undefined>,\n): Promise<Response> {\n  try {\n    const agent = deps.agentRegistry.getAgent(agentId);\n    if (!agent) {\n      return new Response(\n        safeStringify({\n          error: `Agent ${agentId} not found`,\n          message: `Agent ${agentId} not found`,\n        }),\n        {\n          status: 404,\n          headers: {\n            \"Content-Type\": \"application/json\",\n          },\n        },\n      );\n    }\n\n    const { input, schema: jsonSchema } = body;\n    const options = processAgentOptions(body, signal, requestHeaders);\n\n    // Convert JSON schema to Zod schema (supports zod v3 and v4)\n    const zodSchema = (\"toJSONSchema\" in z ? convertJsonSchemaToZod : convertJsonSchemaToZodV3)(\n      jsonSchema,\n    ) as any;\n\n    const result = await agent.streamObject(input, zodSchema, options);\n\n    // Use the built-in toTextStreamResponse - it handles errors properly\n    return result.toTextStreamResponse();\n  } catch (error) {\n    logger.error(\"Failed to handle stream object request\", { error });\n\n    const errorMessage = error instanceof Error ? error.message : \"Unknown error\";\n\n    return new Response(\n      safeStringify({\n        error: errorMessage,\n        message: errorMessage,\n      }),\n      {\n        status: 500,\n        headers: {\n          \"Content-Type\": \"application/json\",\n        },\n      },\n    );\n  }\n}\n","import { Output } from \"ai\";\nimport { z } from \"zod\";\nimport { convertJsonSchemaToZod } from \"zod-from-json-schema\";\nimport { convertJsonSchemaToZod as convertJsonSchemaToZodV3 } from \"zod-from-json-schema-v3\";\n\ntype RequestHeadersInput = Headers | Record<string, string | string[] | undefined>;\n\nfunction normalizeRequestHeaders(\n  headers?: RequestHeadersInput,\n): Record<string, string> | undefined {\n  if (!headers) {\n    return undefined;\n  }\n\n  if (typeof Headers !== \"undefined\" && headers instanceof Headers) {\n    const entries = Array.from(headers.entries()).map(\n      ([key, value]) => [key.toLowerCase(), value] as const,\n    );\n    return entries.length > 0 ? Object.fromEntries(entries) : undefined;\n  }\n\n  const normalized: Record<string, string> = {};\n  for (const [key, value] of Object.entries(headers)) {\n    if (typeof value === \"string\") {\n      normalized[key.toLowerCase()] = value;\n    } else if (Array.isArray(value)) {\n      normalized[key.toLowerCase()] = value.join(\", \");\n    }\n  }\n\n  return Object.keys(normalized).length > 0 ? normalized : undefined;\n}\n\n/**\n * Process agent options from request body\n */\nexport interface ProcessedAgentOptions {\n  memory?: {\n    conversationId?: string;\n    userId?: string;\n    options?: {\n      contextLimit?: number;\n      readOnly?: boolean;\n      semanticMemory?: {\n        enabled?: boolean;\n        semanticLimit?: number;\n        semanticThreshold?: number;\n        mergeStrategy?: \"prepend\" | \"append\" | \"interleave\";\n      };\n      conversationPersistence?: {\n        mode?: \"step\" | \"finish\";\n        debounceMs?: number;\n        flushOnToolResult?: boolean;\n      };\n    };\n  };\n  conversationId?: string;\n  userId?: string;\n  context?: Map<string, any>;\n  temperature?: number;\n  maxOutputTokens?: number;\n  maxSteps?: number;\n  contextLimit?: number;\n  semanticMemory?: {\n    enabled?: boolean;\n    semanticLimit?: number;\n    semanticThreshold?: number;\n    mergeStrategy?: \"prepend\" | \"append\" | \"interleave\";\n  };\n  conversationPersistence?: {\n    mode?: \"step\" | \"finish\";\n    debounceMs?: number;\n    flushOnToolResult?: boolean;\n  };\n  topP?: number;\n  topK?: number;\n  frequencyPenalty?: number;\n  presencePenalty?: number;\n  seed?: number;\n  stopSequences?: string[];\n  maxRetries?: number;\n  abortSignal?: AbortSignal;\n  requestHeaders?: Record<string, string>;\n  onFinish?: (result: unknown) => Promise<void>;\n  output?: any;\n  resumableStream?: boolean;\n  [key: string]: any;\n}\n\n/**\n * Process and normalize agent options from request body\n */\nexport function processAgentOptions(\n  body: any,\n  signal?: AbortSignal,\n  requestHeaders?: RequestHeadersInput,\n): ProcessedAgentOptions {\n  // Now all options should be in body.options, no need to merge from root\n  const options = body.options || {};\n  const normalizedRequestHeaders = normalizeRequestHeaders(requestHeaders);\n\n  const processedOptions: ProcessedAgentOptions = {\n    ...options,\n    ...(signal && { abortSignal: signal }),\n    ...(normalizedRequestHeaders && { requestHeaders: normalizedRequestHeaders }),\n  };\n\n  // Convert context to Map for internal use\n  if (options.context && typeof options.context === \"object\" && !(options.context instanceof Map)) {\n    processedOptions.context = new Map(Object.entries(options.context));\n  }\n\n  // Process output if provided\n  // The client sends: { type: \"object\"|\"text\", schema?: {...}, maxLength?: number, description?: string }\n  // We need to convert it to AI SDK's Output.object() or Output.text() format\n  if (options.output) {\n    const { type, schema: jsonSchema } = options.output;\n\n    if (type === \"object\" && jsonSchema) {\n      // Convert JSON schema to Zod schema (supports zod v3 and v4)\n      const zodSchema = (\"toJSONSchema\" in z ? convertJsonSchemaToZod : convertJsonSchemaToZodV3)(\n        jsonSchema,\n      ) as any;\n\n      processedOptions.output = Output.object({ schema: zodSchema });\n    } else if (type === \"text\") {\n      // Output.text() takes no parameters - it's for constrained text generation\n      processedOptions.output = Output.text();\n    }\n  }\n\n  return processedOptions;\n}\n\n/**\n * Process workflow options from request body\n */\nexport function processWorkflowOptions(options?: any, suspendController?: any): any {\n  if (!options) {\n    return suspendController ? { suspendController } : {};\n  }\n\n  const processedOptions = {\n    ...options,\n    ...(options.context &&\n      typeof options.context === \"object\" &&\n      !(options.context instanceof Map) && {\n        context: new Map(Object.entries(options.context)),\n      }),\n    ...(suspendController && { suspendController }),\n  };\n\n  // Context is already handled above, no need to delete\n\n  return processedOptions;\n}\n","import type { ServerProviderDeps, Workspace, WorkspaceSkillMetadata } from \"@voltagent/core\";\nimport type { Logger } from \"@voltagent/internal\";\nimport type { ApiResponse } from \"../types\";\n\n/**\n * Handler for getting a single agent by ID\n * Returns agent data\n */\nexport async function handleGetAgent(\n  agentId: string,\n  deps: ServerProviderDeps,\n  logger: Logger,\n): Promise<ApiResponse> {\n  try {\n    const agent = deps.agentRegistry.getAgent(agentId);\n\n    if (!agent) {\n      return {\n        success: false,\n        error: `Agent ${agentId} not found`,\n      };\n    }\n\n    const agentState = agent.getFullState();\n    const isTelemetryEnabled = agent.isTelemetryConfigured();\n\n    return {\n      success: true,\n      data: {\n        ...agentState,\n        status: agentState.status,\n        tools: agent.getToolsForApi ? agent.getToolsForApi() : agentState.tools,\n        subAgents: agentState.subAgents,\n        isTelemetryEnabled,\n      },\n    };\n  } catch (error) {\n    logger.error(\"Failed to get agent\", { error });\n    return {\n      success: false,\n      error: error instanceof Error ? error.message : \"Unknown error\",\n    };\n  }\n}\n\n/**\n * Handler for getting agent history\n * Returns agent history data\n */\nexport async function handleGetAgentHistory(\n  agentId: string,\n  page: number,\n  limit: number,\n  deps: ServerProviderDeps,\n  logger: Logger,\n): Promise<ApiResponse> {\n  try {\n    const agent = deps.agentRegistry.getAgent(agentId);\n\n    if (!agent) {\n      return {\n        success: false,\n        error: `Agent ${agentId} not found`,\n      };\n    }\n\n    // Check if agent supports history\n    if (!(\"getHistory\" in agent) || typeof agent.getHistory !== \"function\") {\n      return {\n        success: false,\n        error: \"Agent does not support history\",\n      };\n    }\n\n    // Validate pagination parameters\n    if (page < 0 || limit < 1 || limit > 100) {\n      return {\n        success: false,\n        error: \"Invalid pagination parameters. Page must be >= 0, limit must be between 1 and 100\",\n      };\n    }\n\n    // Get history from agent\n    const historyResult = await agent.getHistory({ page, limit });\n\n    return {\n      success: true,\n      data: historyResult,\n    };\n  } catch (error) {\n    logger.error(\"Failed to get history for agent\", { error });\n    return {\n      success: false,\n      error: error instanceof Error ? error.message : \"Failed to get agent history\",\n    };\n  }\n}\n\nconst parseOptionalInteger = (value: unknown): number | null | undefined => {\n  if (value === undefined || value === null || value === \"\") {\n    return undefined;\n  }\n  if (typeof value === \"number\" && Number.isFinite(value)) {\n    return value;\n  }\n  const parsed = Number.parseInt(String(value), 10);\n  return Number.isNaN(parsed) ? null : parsed;\n};\n\nconst parseOptionalBoolean = (value: unknown): boolean | null | undefined => {\n  if (value === undefined || value === null || value === \"\") {\n    return undefined;\n  }\n  if (typeof value === \"boolean\") {\n    return value;\n  }\n  const normalized = String(value).toLowerCase();\n  if (normalized === \"true\") return true;\n  if (normalized === \"false\") return false;\n  return null;\n};\n\nconst resolveAgentWorkspace = (\n  agentId: string,\n  deps: ServerProviderDeps,\n): {\n  agent: ReturnType<ServerProviderDeps[\"agentRegistry\"][\"getAgent\"]>;\n  workspace: Workspace | null;\n} | null => {\n  const agent = deps.agentRegistry.getAgent(agentId);\n  if (!agent) {\n    return null;\n  }\n  const workspace = agent.getWorkspace?.();\n  if (!workspace) {\n    return { agent, workspace: null };\n  }\n  return { agent, workspace };\n};\n\n/**\n * Handler for getting agent workspace info\n */\nexport async function handleGetAgentWorkspaceInfo(\n  agentId: string,\n  deps: ServerProviderDeps,\n  logger: Logger,\n): Promise<ApiResponse> {\n  try {\n    const resolved = resolveAgentWorkspace(agentId, deps);\n    if (!resolved) {\n      return {\n        success: false,\n        error: `Agent ${agentId} not found`,\n        httpStatus: 404,\n      };\n    }\n\n    if (!resolved.workspace) {\n      return {\n        success: false,\n        error: \"Workspace not configured for this agent\",\n        httpStatus: 404,\n      };\n    }\n\n    const workspace = resolved.workspace;\n\n    return {\n      success: true,\n      data: {\n        id: workspace.id,\n        name: workspace.name,\n        scope: workspace.scope,\n        capabilities: {\n          filesystem: true,\n          sandbox: Boolean(workspace.sandbox),\n          search: Boolean(workspace.getInfo().search),\n          skills: Boolean(workspace.skills),\n        },\n      },\n    };\n  } catch (error) {\n    logger.error(\"Failed to get workspace info\", { error });\n    return {\n      success: false,\n      error: error instanceof Error ? error.message : \"Failed to get workspace info\",\n      httpStatus: 500,\n    };\n  }\n}\n\n/**\n * Handler for listing workspace files\n */\nexport async function handleListAgentWorkspaceFiles(\n  agentId: string,\n  options: { path?: string },\n  deps: ServerProviderDeps,\n  logger: Logger,\n): Promise<ApiResponse> {\n  try {\n    const resolved = resolveAgentWorkspace(agentId, deps);\n    if (!resolved) {\n      return {\n        success: false,\n        error: `Agent ${agentId} not found`,\n        httpStatus: 404,\n      };\n    }\n    if (!resolved.workspace) {\n      return {\n        success: false,\n        error: \"Workspace not configured for this agent\",\n        httpStatus: 404,\n      };\n    }\n\n    const path = options.path && options.path.trim().length > 0 ? options.path : \"/\";\n    const entries = await resolved.workspace.filesystem.lsInfo(path);\n\n    return {\n      success: true,\n      data: {\n        path,\n        entries,\n      },\n    };\n  } catch (error) {\n    logger.error(\"Failed to list workspace files\", { error });\n    return {\n      success: false,\n      error: error instanceof Error ? error.message : \"Failed to list workspace files\",\n      httpStatus: 500,\n    };\n  }\n}\n\n/**\n * Handler for reading a workspace file\n */\nexport async function handleReadAgentWorkspaceFile(\n  agentId: string,\n  options: { path?: string; offset?: unknown; limit?: unknown },\n  deps: ServerProviderDeps,\n  logger: Logger,\n): Promise<ApiResponse> {\n  try {\n    const resolved = resolveAgentWorkspace(agentId, deps);\n    if (!resolved) {\n      return {\n        success: false,\n        error: `Agent ${agentId} not found`,\n        httpStatus: 404,\n      };\n    }\n    if (!resolved.workspace) {\n      return {\n        success: false,\n        error: \"Workspace not configured for this agent\",\n        httpStatus: 404,\n      };\n    }\n\n    const path = options.path?.trim();\n    if (!path) {\n      return {\n        success: false,\n        error: \"Missing required path parameter\",\n        httpStatus: 400,\n      };\n    }\n\n    const offset = parseOptionalInteger(options.offset);\n    if (offset === null) {\n      return {\n        success: false,\n        error: \"Invalid offset parameter\",\n        httpStatus: 400,\n      };\n    }\n    const limit = parseOptionalInteger(options.limit);\n    if (limit === null) {\n      return {\n        success: false,\n        error: \"Invalid limit parameter\",\n        httpStatus: 400,\n      };\n    }\n    if (offset !== undefined && offset < 0) {\n      return {\n        success: false,\n        error: \"Offset must be >= 0\",\n        httpStatus: 400,\n      };\n    }\n    if (limit !== undefined && limit < 1) {\n      return {\n        success: false,\n        error: \"Limit must be >= 1\",\n        httpStatus: 400,\n      };\n    }\n\n    const content = await resolved.workspace.filesystem.read(path, {\n      offset: offset ?? 0,\n      limit: limit ?? 2000,\n    });\n\n    return {\n      success: true,\n      data: {\n        path,\n        content,\n      },\n    };\n  } catch (error) {\n    logger.error(\"Failed to read workspace file\", { error });\n    return {\n      success: false,\n      error: error instanceof Error ? error.message : \"Failed to read workspace file\",\n      httpStatus: 500,\n    };\n  }\n}\n\n/**\n * Handler for listing workspace skills\n */\nexport async function handleListAgentWorkspaceSkills(\n  agentId: string,\n  options: { refresh?: unknown },\n  deps: ServerProviderDeps,\n  logger: Logger,\n): Promise<ApiResponse> {\n  try {\n    const resolved = resolveAgentWorkspace(agentId, deps);\n    if (!resolved) {\n      return {\n        success: false,\n        error: `Agent ${agentId} not found`,\n        httpStatus: 404,\n      };\n    }\n    if (!resolved.workspace) {\n      return {\n        success: false,\n        error: \"Workspace not configured for this agent\",\n        httpStatus: 404,\n      };\n    }\n    if (!resolved.workspace.skills) {\n      return {\n        success: false,\n        error: \"Workspace skills are not configured for this agent\",\n        httpStatus: 404,\n      };\n    }\n\n    const refresh = parseOptionalBoolean(options.refresh);\n    if (refresh === null) {\n      return {\n        success: false,\n        error: \"Invalid refresh parameter\",\n        httpStatus: 400,\n      };\n    }\n\n    const skills: WorkspaceSkillMetadata[] = await resolved.workspace.skills.discoverSkills({\n      refresh: Boolean(refresh),\n    });\n    const activeIds = new Set(\n      resolved.workspace.skills.getActiveSkills().map((skill: WorkspaceSkillMetadata) => skill.id),\n    );\n    const list = skills.map((skill) => ({\n      ...skill,\n      active: activeIds.has(skill.id),\n    }));\n\n    return {\n      success: true,\n      data: {\n        skills: list,\n      },\n    };\n  } catch (error) {\n    logger.error(\"Failed to list workspace skills\", { error });\n    return {\n      success: false,\n      error: error instanceof Error ? error.message : \"Failed to list workspace skills\",\n      httpStatus: 500,\n    };\n  }\n}\n\n/**\n * Handler for reading a workspace skill\n */\nexport async function handleGetAgentWorkspaceSkill(\n  agentId: string,\n  skillId: string,\n  deps: ServerProviderDeps,\n  logger: Logger,\n): Promise<ApiResponse> {\n  try {\n    const resolved = resolveAgentWorkspace(agentId, deps);\n    if (!resolved) {\n      return {\n        success: false,\n        error: `Agent ${agentId} not found`,\n        httpStatus: 404,\n      };\n    }\n    if (!resolved.workspace) {\n      return {\n        success: false,\n        error: \"Workspace not configured for this agent\",\n        httpStatus: 404,\n      };\n    }\n    if (!resolved.workspace.skills) {\n      return {\n        success: false,\n        error: \"Workspace skills are not configured for this agent\",\n        httpStatus: 404,\n      };\n    }\n    if (!skillId || skillId.trim().length === 0) {\n      return {\n        success: false,\n        error: \"Missing skillId parameter\",\n        httpStatus: 400,\n      };\n    }\n\n    const skill = await resolved.workspace.skills.loadSkill(skillId);\n    if (!skill) {\n      return {\n        success: false,\n        error: `Skill ${skillId} not found`,\n        httpStatus: 404,\n      };\n    }\n\n    return {\n      success: true,\n      data: skill,\n    };\n  } catch (error) {\n    logger.error(\"Failed to get workspace skill\", { error });\n    return {\n      success: false,\n      error: error instanceof Error ? error.message : \"Failed to get workspace skill\",\n      httpStatus: 500,\n    };\n  }\n}\n","import type { ServerProviderDeps } from \"@voltagent/core\";\nimport { getGlobalLogBuffer } from \"@voltagent/core\";\nimport type { LogEntry, LogFilter, LogLevel, Logger } from \"@voltagent/internal\";\nimport type { ApiResponse } from \"../types\";\n\n/**\n * Log filter options for querying logs\n */\nexport interface LogFilterOptions {\n  limit?: number;\n  level?: LogLevel;\n  agentId?: string;\n  conversationId?: string;\n  workflowId?: string;\n  executionId?: string;\n  since?: string | Date;\n  until?: string | Date;\n}\n\nexport interface LogHandlerResponse {\n  logs: LogEntry[];\n  total: number;\n  query: LogFilter;\n}\n\n/**\n * Handler for getting logs with filters\n * Returns filtered log entries\n */\nexport async function handleGetLogs(\n  options: LogFilterOptions,\n  _deps: ServerProviderDeps,\n  logger: Logger,\n): Promise<ApiResponse<LogHandlerResponse>> {\n  try {\n    const logBuffer = getGlobalLogBuffer();\n    const limit = options.limit || 100;\n\n    const filter = {\n      level: options.level,\n      agentId: options.agentId,\n      workflowId: options.workflowId,\n      conversationId: options.conversationId,\n      executionId: options.executionId,\n      since: options.since ? new Date(options.since) : undefined,\n      until: options.until ? new Date(options.until) : undefined,\n      limit,\n    };\n\n    const logs = logBuffer.query(filter);\n\n    return {\n      success: true,\n      data: {\n        logs,\n        total: logs.length,\n        query: filter,\n      },\n    };\n  } catch (error) {\n    logger.error(\"Failed to get logs\", { error });\n    return {\n      success: false,\n      error: error instanceof Error ? error.message : \"Unknown error\",\n    };\n  }\n}\n","import type {\n  ServerProviderDeps,\n  Workflow,\n  WorkflowRunQuery,\n  WorkflowStateEntry,\n} from \"@voltagent/core\";\nimport { zodSchemaToJsonUI } from \"@voltagent/core\";\nimport type { Logger } from \"@voltagent/internal\";\nimport type { z } from \"zod\";\nimport type { WorkflowReplayRequestSchema } from \"../schemas/agent.schemas\";\nimport type { ApiResponse, ErrorResponse } from \"../types\";\nimport { processWorkflowOptions } from \"../utils/options\";\nimport { formatSSE } from \"../utils/sse\";\n\nconst MAX_STREAM_REPLAY_HISTORY = 500;\n\ntype StreamQueryValue = string | number | null | undefined;\n\ntype SSEEncoder = {\n  encode: (input?: string) => Uint8Array;\n};\n\ntype WorkflowStreamSubscriber = {\n  controller: ReadableStreamDefaultController<Uint8Array>;\n  encoder: SSEEncoder;\n};\n\ntype WorkflowStreamReplayEntry = {\n  sequence: number;\n  payload: unknown;\n};\n\ntype WorkflowStreamSession = {\n  workflowId: string;\n  executionId: string;\n  subscribers: Set<WorkflowStreamSubscriber>;\n  replayBuffer: WorkflowStreamReplayEntry[];\n  nextSequence: number;\n  isClosed: boolean;\n  streamExecution: ResumableStreamingWorkflowExecution;\n};\n\nconst activeWorkflowStreamSessions = new Map<string, WorkflowStreamSession>();\n\ntype StreamingWorkflowExecution = AsyncIterable<unknown> & {\n  executionId: string;\n  workflowId?: string;\n  startAt?: Date;\n  result: Promise<unknown>;\n  status: Promise<string>;\n  endAt: Promise<Date | string>;\n};\n\ntype ResumableStreamingWorkflowExecution = StreamingWorkflowExecution & {\n  resume?: (\n    input: unknown,\n    options?: {\n      stepId?: string;\n    },\n  ) => Promise<ResumableStreamingWorkflowExecution>;\n};\n\ntype WorkflowReplayRequestBody = z.infer<typeof WorkflowReplayRequestSchema>;\ntype WorkflowTimeTravelRequest = Parameters<\n  NonNullable<Workflow<any, any, any, any>[\"timeTravel\"]>\n>[0];\n\nfunction parseReplaySequence(value: StreamQueryValue): number | undefined {\n  if (value === undefined || value === null || value === \"\") {\n    return undefined;\n  }\n\n  const parsed = typeof value === \"number\" ? value : Number(value);\n  if (!Number.isFinite(parsed) || parsed < 0) {\n    return undefined;\n  }\n\n  return Math.floor(parsed);\n}\n\nfunction createWorkflowStreamSession(\n  workflowId: string,\n  executionId: string,\n  streamExecution: ResumableStreamingWorkflowExecution,\n): WorkflowStreamSession {\n  return {\n    workflowId,\n    executionId,\n    subscribers: new Set(),\n    replayBuffer: [],\n    nextSequence: 1,\n    isClosed: false,\n    streamExecution,\n  };\n}\n\nfunction unregisterWorkflowStreamSession(session: WorkflowStreamSession): void {\n  activeWorkflowStreamSessions.delete(session.executionId);\n}\n\nfunction closeWorkflowStreamSession(session: WorkflowStreamSession): void {\n  if (session.isClosed) {\n    return;\n  }\n\n  session.isClosed = true;\n\n  for (const subscriber of session.subscribers) {\n    try {\n      subscriber.controller.close();\n    } catch {\n      // no-op: stream may already be closed\n    }\n  }\n\n  session.subscribers.clear();\n  unregisterWorkflowStreamSession(session);\n}\n\nfunction enqueueSSEMessage(\n  subscriber: WorkflowStreamSubscriber,\n  payload: unknown,\n  sequence: number,\n): void {\n  const ssePayload = formatSSE(payload, undefined, String(sequence));\n  subscriber.controller.enqueue(subscriber.encoder.encode(ssePayload));\n}\n\nfunction appendReplayEvent(\n  session: WorkflowStreamSession,\n  payload: unknown,\n  sequence: number,\n): void {\n  session.replayBuffer.push({ sequence, payload });\n\n  if (session.replayBuffer.length > MAX_STREAM_REPLAY_HISTORY) {\n    session.replayBuffer.splice(0, session.replayBuffer.length - MAX_STREAM_REPLAY_HISTORY);\n  }\n}\n\nfunction broadcastWorkflowStreamEvent(session: WorkflowStreamSession, payload: unknown): void {\n  if (session.isClosed) {\n    return;\n  }\n\n  const sequence = session.nextSequence;\n  session.nextSequence += 1;\n  appendReplayEvent(session, payload, sequence);\n\n  for (const subscriber of session.subscribers) {\n    try {\n      enqueueSSEMessage(subscriber, payload, sequence);\n    } catch {\n      session.subscribers.delete(subscriber);\n    }\n  }\n}\n\nfunction createWorkflowSessionStream(\n  session: WorkflowStreamSession,\n  options?: {\n    fromSequence?: number;\n  },\n): ReadableStream {\n  let subscriber: WorkflowStreamSubscriber | undefined;\n  const replayFrom = options?.fromSequence;\n\n  return new ReadableStream({\n    start(controller) {\n      subscriber = {\n        controller,\n        encoder: new TextEncoder(),\n      };\n\n      if (replayFrom !== undefined) {\n        for (const replayEntry of session.replayBuffer) {\n          if (replayEntry.sequence > replayFrom) {\n            enqueueSSEMessage(subscriber, replayEntry.payload, replayEntry.sequence);\n          }\n        }\n      }\n\n      if (session.isClosed) {\n        controller.close();\n        return;\n      }\n\n      session.subscribers.add(subscriber);\n    },\n    cancel() {\n      if (!subscriber) {\n        return;\n      }\n\n      session.subscribers.delete(subscriber);\n    },\n  });\n}\n\nasync function consumeWorkflowStream(\n  session: WorkflowStreamSession,\n  deps: ServerProviderDeps,\n  logger: Logger,\n): Promise<void> {\n  try {\n    // Iterate over the original stream source. Resume operations continue on the same underlying\n    // stream controller, while `session.streamExecution` is updated to reflect latest promises.\n    for await (const event of session.streamExecution) {\n      broadcastWorkflowStreamEvent(session, event);\n    }\n\n    const terminalExecution = session.streamExecution;\n    const result = await terminalExecution.result;\n    const status = await terminalExecution.status;\n    const endAt = await terminalExecution.endAt;\n\n    const finalEvent = {\n      type: \"workflow-result\",\n      executionId: terminalExecution.executionId,\n      status,\n      result,\n      endAt: endAt instanceof Date ? endAt.toISOString() : endAt,\n    };\n\n    broadcastWorkflowStreamEvent(session, finalEvent);\n\n    if (deps.workflowRegistry.activeExecutions) {\n      deps.workflowRegistry.activeExecutions.delete(terminalExecution.executionId);\n    }\n\n    closeWorkflowStreamSession(session);\n  } catch (error) {\n    logger.error(\"Failed during workflow stream:\", { error });\n\n    if (deps.workflowRegistry.activeExecutions) {\n      deps.workflowRegistry.activeExecutions.delete(session.executionId);\n    }\n\n    broadcastWorkflowStreamEvent(session, {\n      type: \"error\",\n      error: error instanceof Error ? error.message : \"Stream failed\",\n    });\n\n    closeWorkflowStreamSession(session);\n  }\n}\n\n/**\n * Handler for listing all workflows\n * Returns workflow list data\n */\nexport async function handleGetWorkflows(\n  deps: ServerProviderDeps,\n  logger: Logger,\n): Promise<ApiResponse> {\n  try {\n    const workflows = deps.workflowRegistry.getWorkflowsForApi();\n    return {\n      success: true,\n      data: workflows,\n    };\n  } catch (error) {\n    logger.error(\"Failed to get workflows\", { error });\n    return {\n      success: false,\n      error: error instanceof Error ? error.message : \"Unknown error\",\n    };\n  }\n}\n\n/**\n * Handler for getting a single workflow\n * Returns workflow detail data with inferred schemas\n */\nexport async function handleGetWorkflow(\n  workflowId: string,\n  deps: ServerProviderDeps,\n  logger: Logger,\n): Promise<ApiResponse> {\n  try {\n    const workflowData = deps.workflowRegistry.getWorkflowDetailForApi(workflowId);\n\n    if (!workflowData) {\n      return {\n        success: false,\n        error: `Workflow with id ${workflowId} not found`,\n      };\n    }\n\n    // Get the registered workflow to access schemas\n    const registeredWorkflow = deps.workflowRegistry.getWorkflow(workflowId);\n    let inputSchema: unknown = null;\n    let resultSchema: unknown = null;\n    let suspendSchema: unknown = null;\n    let resumeSchema: unknown = null;\n\n    if (registeredWorkflow?.inputSchema) {\n      try {\n        // Convert Zod schema to JSON schema using zodSchemaToJsonUI\n        inputSchema = zodSchemaToJsonUI(registeredWorkflow.inputSchema);\n      } catch (error) {\n        logger.warn(\"Failed to convert input schema to JSON schema:\", { error });\n      }\n    }\n\n    if (registeredWorkflow?.resultSchema) {\n      try {\n        resultSchema = zodSchemaToJsonUI(registeredWorkflow.resultSchema);\n      } catch (error) {\n        logger.warn(\"Failed to convert result schema to JSON schema:\", { error });\n      }\n    }\n\n    if (registeredWorkflow?.suspendSchema) {\n      try {\n        suspendSchema = zodSchemaToJsonUI(registeredWorkflow.suspendSchema);\n      } catch (error) {\n        logger.warn(\"Failed to convert suspend schema to JSON schema:\", { error });\n      }\n    }\n\n    if (registeredWorkflow?.resumeSchema) {\n      try {\n        resumeSchema = zodSchemaToJsonUI(registeredWorkflow.resumeSchema);\n      } catch (error) {\n        logger.warn(\"Failed to convert resume schema to JSON schema:\", { error });\n      }\n    }\n\n    // Type guard to check if workflowData has steps array\n    const hasSteps = (data: unknown): data is { steps: unknown[] } => {\n      return (\n        typeof data === \"object\" &&\n        data !== null &&\n        \"steps\" in data &&\n        Array.isArray((data as Record<string, unknown>).steps)\n      );\n    };\n\n    // Convert step-level schemas to JSON format\n    if (hasSteps(workflowData)) {\n      workflowData.steps = workflowData.steps.map((step) => {\n        // Type guard for step with schemas\n        const isStepWithSchemas = (s: unknown): s is Record<string, unknown> => {\n          return typeof s === \"object\" && s !== null;\n        };\n\n        if (!isStepWithSchemas(step)) {\n          return step;\n        }\n\n        const convertedStep = { ...step };\n\n        // Convert step schemas if they exist\n        if (\"inputSchema\" in step && step.inputSchema) {\n          try {\n            convertedStep.inputSchema = zodSchemaToJsonUI(step.inputSchema);\n          } catch (error) {\n            logger.warn(\"Failed to convert input schema for step:\", { error });\n          }\n        }\n\n        if (\"outputSchema\" in step && step.outputSchema) {\n          try {\n            convertedStep.outputSchema = zodSchemaToJsonUI(step.outputSchema);\n          } catch (error) {\n            logger.warn(\"Failed to convert output schema for step:\", { error });\n          }\n        }\n\n        if (\"suspendSchema\" in step && step.suspendSchema) {\n          try {\n            convertedStep.suspendSchema = zodSchemaToJsonUI(step.suspendSchema);\n          } catch (error) {\n            logger.warn(\"Failed to convert suspend schema for step:\", { error });\n          }\n        }\n\n        if (\"resumeSchema\" in step && step.resumeSchema) {\n          try {\n            convertedStep.resumeSchema = zodSchemaToJsonUI(step.resumeSchema);\n          } catch (error) {\n            logger.warn(\"Failed to convert resume schema for step:\", { error });\n          }\n        }\n\n        return convertedStep;\n      });\n    }\n\n    return {\n      success: true,\n      data: {\n        ...workflowData,\n        inputSchema,\n        resultSchema,\n        suspendSchema,\n        resumeSchema,\n      },\n    };\n  } catch (error) {\n    logger.error(\"Failed to get workflow\", { error });\n    return {\n      success: false,\n      error: error instanceof Error ? error.message : \"Unknown error\",\n    };\n  }\n}\n\n/**\n * Handler for executing a workflow\n * Returns workflow execution result\n */\nexport async function handleExecuteWorkflow(\n  workflowId: string,\n  body: any,\n  deps: ServerProviderDeps,\n  logger: Logger,\n): Promise<ApiResponse> {\n  try {\n    const { input, options } = body;\n\n    const registeredWorkflow = deps.workflowRegistry.getWorkflow(workflowId);\n\n    if (!registeredWorkflow) {\n      return {\n        success: false,\n        error: \"Workflow not found\",\n      };\n    }\n\n    // Create suspension controller\n    const suspendController = registeredWorkflow.workflow.createSuspendController?.();\n    if (!suspendController) {\n      throw new Error(\"Workflow does not support suspension\");\n    }\n\n    const processedOptions = processWorkflowOptions(options, suspendController);\n    processedOptions.signal = suspendController.signal;\n\n    // Track execution for suspension\n    let capturedExecutionId: string | null = null;\n    const historyCreatedHandler = (historyEntry: any) => {\n      if (historyEntry.workflowId === workflowId && !capturedExecutionId) {\n        capturedExecutionId = historyEntry.id;\n        if (deps.workflowRegistry.activeExecutions) {\n          deps.workflowRegistry.activeExecutions.set(historyEntry.id, suspendController);\n        }\n        logger.trace(`Captured execution ${historyEntry.id} for suspension tracking`);\n      }\n    };\n\n    deps.workflowRegistry.on(\"historyCreated\", historyCreatedHandler);\n\n    try {\n      const result = await registeredWorkflow.workflow.run(input, processedOptions);\n\n      deps.workflowRegistry.off(\"historyCreated\", historyCreatedHandler);\n\n      // Clean up active execution\n      if (deps.workflowRegistry.activeExecutions) {\n        deps.workflowRegistry.activeExecutions.delete(result.executionId);\n      }\n\n      return {\n        success: true,\n        data: {\n          executionId: result.executionId,\n          startAt: result.startAt instanceof Date ? result.startAt.toISOString() : result.startAt,\n          endAt: result.endAt instanceof Date ? result.endAt.toISOString() : result.endAt,\n          status: result.status,\n          result: result.result,\n        },\n      };\n    } catch (error) {\n      deps.workflowRegistry.off(\"historyCreated\", historyCreatedHandler);\n\n      if (capturedExecutionId && deps.workflowRegistry.activeExecutions) {\n        deps.workflowRegistry.activeExecutions.delete(capturedExecutionId);\n      }\n\n      throw error;\n    }\n  } catch (error) {\n    logger.error(\"Failed to execute workflow\", { error });\n    return {\n      success: false,\n      error: error instanceof Error ? error.message : \"Failed to execute workflow\",\n    };\n  }\n}\n\n/**\n * Handler for streaming workflow execution\n * Returns a ReadableStream for SSE\n */\nexport async function handleStreamWorkflow(\n  workflowId: string,\n  body: any,\n  deps: ServerProviderDeps,\n  logger: Logger,\n): Promise<ReadableStream | ErrorResponse> {\n  try {\n    const { input, options } = body;\n\n    const registeredWorkflow = deps.workflowRegistry.getWorkflow(workflowId);\n\n    if (!registeredWorkflow) {\n      return {\n        success: false,\n        error: \"Workflow not found\",\n      };\n    }\n\n    // Create suspension controller\n    const suspendController = registeredWorkflow.workflow.createSuspendController?.();\n    if (!suspendController) {\n      throw new Error(\"Workflow does not support suspension\");\n    }\n\n    const processedOptions = processWorkflowOptions(options, suspendController);\n    const workflowStream = registeredWorkflow.workflow.stream(\n      input,\n      processedOptions,\n    ) as ResumableStreamingWorkflowExecution;\n    const executionId = workflowStream.executionId;\n\n    if (!executionId) {\n      throw new Error(\"Workflow stream executionId is required\");\n    }\n\n    // Track as active execution for suspend/cancel operations.\n    if (deps.workflowRegistry.activeExecutions) {\n      deps.workflowRegistry.activeExecutions.set(executionId, suspendController);\n    }\n\n    const existingSession = activeWorkflowStreamSessions.get(executionId);\n    if (existingSession) {\n      closeWorkflowStreamSession(existingSession);\n    }\n\n    const session = createWorkflowStreamSession(workflowId, executionId, workflowStream);\n    activeWorkflowStreamSessions.set(executionId, session);\n\n    consumeWorkflowStream(session, deps, logger).catch((error) => {\n      logger.error(\"Unhandled workflow stream consumer error\", { error });\n    });\n\n    return createWorkflowSessionStream(session);\n  } catch (error) {\n    logger.error(\"Failed to initiate workflow stream\", { error });\n    return {\n      success: false,\n      error: error instanceof Error ? error.message : \"Failed to initiate workflow stream\",\n    };\n  }\n}\n\n/**\n * Handler for attaching to an existing workflow execution stream\n * Returns a ReadableStream for SSE\n */\nexport async function handleAttachWorkflowStream(\n  workflowId: string,\n  executionId: string,\n  query: {\n    fromSequence?: string | number;\n    lastEventId?: string | null;\n  },\n  deps: ServerProviderDeps,\n  logger: Logger,\n): Promise<ReadableStream | ErrorResponse> {\n  try {\n    const registeredWorkflow = deps.workflowRegistry.getWorkflow(workflowId);\n\n    if (!registeredWorkflow) {\n      return {\n        success: false,\n        error: \"Workflow not found\",\n        httpStatus: 404,\n      };\n    }\n\n    const activeSession = activeWorkflowStreamSessions.get(executionId);\n    if (activeSession && activeSession.workflowId === workflowId) {\n      const replayFromSequence =\n        parseReplaySequence(query.fromSequence) ?? parseReplaySequence(query.lastEventId);\n\n      return createWorkflowSessionStream(activeSession, {\n        fromSequence: replayFromSequence,\n      });\n    }\n\n    const workflowState = await registeredWorkflow.workflow.memory.getWorkflowState(executionId);\n    if (!workflowState || workflowState.workflowId !== workflowId) {\n      return {\n        success: false,\n        error: \"Workflow execution not found\",\n        httpStatus: 404,\n      };\n    }\n\n    if (workflowState.status === \"completed\" || workflowState.status === \"cancelled\") {\n      return {\n        success: false,\n        error: `Workflow execution is not streamable in '${workflowState.status}' status`,\n        httpStatus: 409,\n      };\n    }\n\n    if (workflowState.status === \"error\") {\n      return {\n        success: false,\n        error: \"Workflow execution is not streamable in 'error' status\",\n        httpStatus: 409,\n      };\n    }\n\n    return {\n      success: false,\n      error: \"Workflow execution has no active stream context to attach\",\n      httpStatus: 409,\n    };\n  } catch (error) {\n    logger.error(\"Failed to attach to workflow stream\", { error });\n    return {\n      success: false,\n      error: error instanceof Error ? error.message : \"Failed to attach to workflow stream\",\n    };\n  }\n}\n\nasync function isWorkflowExecutionOwnedByRoute(\n  body: WorkflowControlRequestBody | undefined,\n  executionId: string,\n  deps: ServerProviderDeps,\n) {\n  const workflowId = body?.__workflowId;\n  if (typeof workflowId !== \"string\" || workflowId.trim().length === 0) {\n    return false;\n  }\n\n  return (\n    (\n      await deps.workflowRegistry\n        .getWorkflow(workflowId)\n        ?.workflow.memory.getWorkflowState(executionId)\n    )?.workflowId === workflowId\n  );\n}\n\nexport type WorkflowControlRequestBody = Record<string, unknown> & {\n  __workflowId: string;\n  reason?: string;\n};\n\nexport function createWorkflowControlRequestBody(\n  body: unknown,\n  workflowId: string,\n): WorkflowControlRequestBody | undefined {\n  if (!body || typeof body !== \"object\" || Array.isArray(body)) {\n    return undefined;\n  }\n\n  return {\n    ...(body as Record<string, unknown>),\n    __workflowId: workflowId,\n  };\n}\n\n/**\n * Handler for suspending a workflow\n * Returns suspension result\n */\nexport async function handleSuspendWorkflow(\n  executionId: string,\n  body: WorkflowControlRequestBody | undefined,\n  deps: ServerProviderDeps,\n  logger: Logger,\n): Promise<ApiResponse> {\n  try {\n    const { reason } = body || {};\n\n    if (!deps.workflowRegistry.activeExecutions) {\n      return {\n        success: false,\n        error: \"Workflow suspension not supported\",\n      };\n    }\n\n    if (!(await isWorkflowExecutionOwnedByRoute(body, executionId, deps))) {\n      return {\n        success: false,\n        error: \"Workflow execution not found or already completed\",\n      };\n    }\n\n    const suspendController = deps.workflowRegistry.activeExecutions.get(executionId);\n\n    if (!suspendController) {\n      return {\n        success: false,\n        error: \"Workflow execution not found or already completed\",\n      };\n    }\n\n    // Trigger suspension\n    suspendController.suspend(reason || \"API request\");\n\n    // Remove from active executions\n    deps.workflowRegistry.activeExecutions.delete(executionId);\n\n    // Wait for suspension to propagate\n    await new Promise((resolve) => setTimeout(resolve, 100));\n\n    return {\n      success: true,\n      data: {\n        executionId,\n        status: \"suspended\",\n        suspension: {\n          suspendedAt: new Date().toISOString(),\n          reason: reason || \"API request\",\n        },\n      },\n    };\n  } catch (error) {\n    logger.error(\"Failed to suspend workflow\", { error });\n    return {\n      success: false,\n      error: error instanceof Error ? error.message : \"Failed to suspend workflow\",\n    };\n  }\n}\n\n/**\n * Handler for cancelling a workflow\n * Returns cancellation result\n */\nexport async function handleCancelWorkflow(\n  executionId: string,\n  body: WorkflowControlRequestBody | undefined,\n  deps: ServerProviderDeps,\n  logger: Logger,\n): Promise<ApiResponse> {\n  try {\n    const { reason } = body || {};\n\n    if (!deps.workflowRegistry.activeExecutions) {\n      return {\n        success: false,\n        error: \"Workflow cancellation not supported\",\n      };\n    }\n\n    if (!(await isWorkflowExecutionOwnedByRoute(body, executionId, deps))) {\n      return {\n        success: false,\n        error: \"No active execution found or workflow already completed\",\n      };\n    }\n\n    const suspendController = deps.workflowRegistry.activeExecutions.get(executionId);\n\n    if (!suspendController) {\n      return {\n        success: false,\n        error: \"No active execution found or workflow already completed\",\n      };\n    }\n\n    if (suspendController.isCancelled?.()) {\n      return {\n        success: true,\n        data: {\n          executionId,\n          status: \"cancelled\" as const,\n          cancelledAt: new Date().toISOString(),\n          reason: suspendController.getCancelReason?.(),\n        },\n      };\n    }\n\n    const cancellationReason = reason || \"API request\";\n\n    suspendController.cancel(cancellationReason);\n\n    // Remove from active executions immediately to prevent duplicate cancellations\n    deps.workflowRegistry.activeExecutions.delete(executionId);\n\n    // Wait a moment to allow cancellation to propagate\n    await new Promise((resolve) => setTimeout(resolve, 50));\n\n    return {\n      success: true,\n      data: {\n        executionId,\n        status: \"cancelled\" as const,\n        cancelledAt: new Date().toISOString(),\n        reason: cancellationReason,\n      },\n    };\n  } catch (error) {\n    logger.error(\"Failed to cancel workflow\", { error });\n    return {\n      success: false,\n      error: error instanceof Error ? error.message : \"Failed to cancel workflow\",\n    };\n  }\n}\n\n/**\n * Handler for resuming a workflow\n * Returns resume result\n */\nexport async function handleResumeWorkflow(\n  workflowId: string,\n  executionId: string,\n  body: any,\n  deps: ServerProviderDeps,\n  logger: Logger,\n): Promise<ApiResponse> {\n  try {\n    const { resumeData, options } = body || {};\n\n    const activeSession = activeWorkflowStreamSessions.get(executionId);\n    if (\n      activeSession &&\n      activeSession.workflowId === workflowId &&\n      typeof activeSession.streamExecution.resume === \"function\"\n    ) {\n      const resumedStreamExecution = await activeSession.streamExecution.resume(\n        resumeData,\n        options?.stepId ? { stepId: options.stepId } : undefined,\n      );\n      activeSession.streamExecution = resumedStreamExecution;\n\n      const status = await resumedStreamExecution.status;\n      const result = await resumedStreamExecution.result;\n      const endAt = await resumedStreamExecution.endAt;\n\n      return {\n        success: true,\n        data: {\n          executionId: resumedStreamExecution.executionId,\n          startAt:\n            resumedStreamExecution.startAt instanceof Date\n              ? resumedStreamExecution.startAt.toISOString()\n              : resumedStreamExecution.startAt,\n          endAt: endAt instanceof Date ? endAt.toISOString() : endAt,\n          status,\n          result,\n        },\n      };\n    }\n\n    // Use the registry to resume the workflow\n    const result = await deps.workflowRegistry.resumeSuspendedWorkflow(\n      workflowId,\n      executionId,\n      resumeData,\n      options?.stepId,\n    );\n\n    if (!result) {\n      return {\n        success: false,\n        error: \"Failed to resume workflow - execution not found or not suspended\",\n      };\n    }\n\n    return {\n      success: true,\n      data: {\n        executionId: result.executionId,\n        startAt: result.startAt instanceof Date ? result.startAt.toISOString() : result.startAt,\n        endAt: result.endAt instanceof Date ? result.endAt.toISOString() : result.endAt,\n        status: result.status,\n        result: result.result,\n      },\n    };\n  } catch (error) {\n    logger.error(\"Failed to resume workflow\", { error });\n    return {\n      success: false,\n      error: error instanceof Error ? error.message : \"Failed to resume workflow\",\n    };\n  }\n}\n\n/**\n * Handler for replaying a workflow execution from a historical step\n * Returns replay result\n */\nexport async function handleReplayWorkflow(\n  workflowId: string,\n  executionId: string,\n  body: WorkflowReplayRequestBody | undefined,\n  deps: ServerProviderDeps,\n  logger: Logger,\n): Promise<ApiResponse> {\n  try {\n    const { stepId, inputData, resumeData, workflowStateOverride } = body || {};\n\n    if (typeof stepId !== \"string\" || stepId.trim().length === 0) {\n      return {\n        success: false,\n        error: \"stepId is required\",\n        httpStatus: 400,\n      };\n    }\n\n    const registeredWorkflow = deps.workflowRegistry.getWorkflow(workflowId);\n    if (!registeredWorkflow) {\n      return {\n        success: false,\n        error: \"Workflow not found\",\n        httpStatus: 404,\n      };\n    }\n\n    const workflowWithReplay = registeredWorkflow.workflow as Partial<\n      Pick<Workflow<any, any, any, any>, \"timeTravel\">\n    >;\n\n    if (typeof workflowWithReplay.timeTravel !== \"function\") {\n      return {\n        success: false,\n        error: \"Workflow does not support replay\",\n        httpStatus: 400,\n      };\n    }\n\n    const replayOptions: WorkflowTimeTravelRequest = {\n      executionId,\n      stepId: stepId.trim(),\n      inputData,\n      resumeData,\n      workflowStateOverride,\n    };\n    const result = await workflowWithReplay.timeTravel(replayOptions);\n\n    return {\n      success: true,\n      data: {\n        executionId: result.executionId,\n        startAt: result.startAt instanceof Date ? result.startAt.toISOString() : result.startAt,\n        endAt: result.endAt instanceof Date ? result.endAt.toISOString() : result.endAt,\n        status: result.status,\n        result: result.result,\n      },\n    };\n  } catch (error) {\n    logger.error(\"Failed to replay workflow\", { error, workflowId, executionId });\n\n    const message = error instanceof Error ? error.message : \"Failed to replay workflow\";\n    const normalizedMessage = message.toLowerCase();\n    const isReplayPreparationError =\n      normalizedMessage.includes(\"missing historical snapshots\") ||\n      normalizedMessage.includes(\"missing snapshot\") ||\n      normalizedMessage.includes(\"missing input\") ||\n      normalizedMessage.includes(\"no historical\") ||\n      normalizedMessage.includes(\"missing history\");\n    const httpStatus = normalizedMessage.includes(\"not found\")\n      ? 404\n      : normalizedMessage.includes(\"cannot time travel\") ||\n          normalizedMessage.includes(\"still running\") ||\n          normalizedMessage.includes(\"belongs to workflow\") ||\n          isReplayPreparationError\n        ? 400\n        : 500;\n\n    return {\n      success: false,\n      error: message,\n      httpStatus,\n    };\n  }\n}\n\nfunction formatWorkflowState(workflowState: WorkflowStateEntry) {\n  return {\n    ...workflowState,\n    createdAt:\n      workflowState.createdAt instanceof Date\n        ? workflowState.createdAt.toISOString()\n        : workflowState.createdAt,\n    updatedAt:\n      workflowState.updatedAt instanceof Date\n        ? workflowState.updatedAt.toISOString()\n        : workflowState.updatedAt,\n    suspension: workflowState.suspension\n      ? {\n          ...workflowState.suspension,\n          suspendedAt:\n            workflowState.suspension.suspendedAt instanceof Date\n              ? workflowState.suspension.suspendedAt.toISOString()\n              : workflowState.suspension.suspendedAt,\n        }\n      : undefined,\n  };\n}\n\ntype WorkflowRunsQuery = {\n  status?: string | number;\n  from?: string | number;\n  to?: string | number;\n  limit?: string | number;\n  offset?: string | number;\n  workflowId?: string | number;\n  userId?: string | number;\n  metadata?: string;\n} & Record<string, string | number | undefined>;\n\nconst WORKFLOW_RUN_STATUSES = new Set<WorkflowStateEntry[\"status\"]>([\n  \"running\",\n  \"suspended\",\n  \"completed\",\n  \"cancelled\",\n  \"error\",\n]);\n\nconst WORKFLOW_RUN_STATUS_ALIASES: Partial<Record<string, WorkflowStateEntry[\"status\"]>> = {\n  success: \"completed\",\n  pending: \"running\",\n};\n\nfunction normalizeWorkflowRunStatus(value: string | number | undefined) {\n  if (value === undefined) {\n    return undefined;\n  }\n\n  const normalized = String(value).trim().toLowerCase();\n  const resolved = WORKFLOW_RUN_STATUS_ALIASES[normalized] ?? normalized;\n\n  if (WORKFLOW_RUN_STATUSES.has(resolved as WorkflowStateEntry[\"status\"])) {\n    return resolved as WorkflowStateEntry[\"status\"];\n  }\n\n  return undefined;\n}\n\nfunction parseQueryNumber(value: string | number | undefined, options?: { min?: number }) {\n  if (value === undefined) {\n    return undefined;\n  }\n\n  const parsed = typeof value === \"number\" ? value : Number(value);\n  if (!Number.isFinite(parsed)) {\n    return undefined;\n  }\n\n  if (options?.min !== undefined && parsed < options.min) {\n    return undefined;\n  }\n\n  return parsed;\n}\n\nfunction parseQueryDate(value: string | number | undefined) {\n  if (value === undefined) {\n    return undefined;\n  }\n\n  const parsed = new Date(String(value));\n  if (Number.isNaN(parsed.getTime())) {\n    return undefined;\n  }\n\n  return parsed;\n}\n\nfunction parseMetadataFilterValue(value: string | number) {\n  if (typeof value === \"number\") {\n    return value;\n  }\n\n  try {\n    return JSON.parse(value);\n  } catch {\n    return value;\n  }\n}\n\nfunction parseMetadataFilters(query: WorkflowRunsQuery | undefined, logger: Logger) {\n  const metadataFilters: Record<string, unknown> = {};\n\n  const rawMetadata = query?.metadata;\n  if (typeof rawMetadata === \"string\") {\n    try {\n      const parsed = JSON.parse(rawMetadata);\n      if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n        Object.assign(metadataFilters, parsed as Record<string, unknown>);\n      }\n    } catch (error) {\n      logger.warn(\"Ignoring invalid workflow metadata filter payload\", {\n        metadata: rawMetadata,\n        error,\n      });\n    }\n  }\n\n  for (const [key, value] of Object.entries(query ?? {})) {\n    if (!key.startsWith(\"metadata.\") || value === undefined) {\n      continue;\n    }\n\n    const metadataKey = key.slice(\"metadata.\".length).trim();\n    if (!metadataKey) {\n      continue;\n    }\n\n    metadataFilters[metadataKey] = parseMetadataFilterValue(value);\n  }\n\n  return Object.keys(metadataFilters).length > 0 ? metadataFilters : undefined;\n}\n\n/**\n * Handler for listing workflow execution runs\n */\nexport async function handleListWorkflowRuns(\n  workflowId: string | undefined,\n  query: WorkflowRunsQuery | undefined,\n  deps: ServerProviderDeps,\n  logger: Logger,\n): Promise<ApiResponse> {\n  try {\n    const effectiveWorkflowId =\n      query?.workflowId !== undefined ? String(query.workflowId) : workflowId;\n    const metadataFilters = parseMetadataFilters(query, logger);\n\n    const filters: WorkflowRunQuery = {\n      workflowId: effectiveWorkflowId,\n      status: normalizeWorkflowRunStatus(query?.status),\n      limit: parseQueryNumber(query?.limit, { min: 1 }),\n      offset: parseQueryNumber(query?.offset, { min: 0 }),\n      userId: query?.userId !== undefined ? String(query.userId) : undefined,\n      metadata: metadataFilters,\n    };\n\n    filters.from = parseQueryDate(query?.from);\n    filters.to = parseQueryDate(query?.to);\n\n    if (effectiveWorkflowId) {\n      const registeredWorkflow = deps.workflowRegistry.getWorkflow(effectiveWorkflowId);\n\n      if (!registeredWorkflow) {\n        return {\n          success: false,\n          error: `Workflow with id ${effectiveWorkflowId} not found`,\n        };\n      }\n\n      const workflowStates = await registeredWorkflow.workflow.memory.queryWorkflowRuns(filters);\n      const formattedStates = workflowStates.map((state) => formatWorkflowState(state));\n\n      return {\n        success: true,\n        data: formattedStates,\n      };\n    }\n\n    // No workflowId provided: aggregate across all registered workflows\n    const allWorkflowIds = deps.workflowRegistry.getAllWorkflowIds?.() ?? [];\n    const results: WorkflowStateEntry[] = [];\n\n    for (const id of allWorkflowIds) {\n      const registeredWorkflow = deps.workflowRegistry.getWorkflow(id);\n      if (!registeredWorkflow) continue;\n      const states = await registeredWorkflow.workflow.memory.queryWorkflowRuns({\n        ...filters,\n        workflowId: id,\n      });\n      results.push(...states);\n    }\n\n    const formattedStates = results\n      .sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime())\n      .map((state) => formatWorkflowState(state));\n\n    return {\n      success: true,\n      data: formattedStates,\n    };\n  } catch (error) {\n    logger.error(\"Failed to get workflow states\", { error });\n    return {\n      success: false,\n      error: error instanceof Error ? error.message : \"Failed to get workflow states\",\n    };\n  }\n}\n\n/**\n * Handler for getting workflow execution state\n * Returns workflow state from Memory V2\n */\nexport async function handleGetWorkflowState(\n  workflowId: string,\n  executionId: string,\n  deps: ServerProviderDeps,\n  logger: Logger,\n): Promise<ApiResponse> {\n  try {\n    // Get the registered workflow\n    const registeredWorkflow = deps.workflowRegistry.getWorkflow(workflowId);\n\n    if (!registeredWorkflow) {\n      return {\n        success: false,\n        error: `Workflow with id ${workflowId} not found`,\n      };\n    }\n\n    // Get the workflow state from Memory\n    const workflowState = await registeredWorkflow.workflow.memory.getWorkflowState(executionId);\n\n    if (!workflowState) {\n      return {\n        success: false,\n        error: `Workflow execution state for ${executionId} not found`,\n      };\n    }\n\n    // Format dates for JSON response\n    const formattedState = formatWorkflowState(workflowState);\n\n    return {\n      success: true,\n      data: formattedState,\n    };\n  } catch (error) {\n    logger.error(\"Failed to get workflow state\", { error });\n    return {\n      success: false,\n      error: error instanceof Error ? error.message : \"Failed to get workflow state\",\n    };\n  }\n}\n","/**\n * Server-Sent Events (SSE) utilities\n * Framework-agnostic SSE helpers for streaming responses\n */\n\nimport { safeStringify } from \"@voltagent/internal\";\n\n/**\n * Format data for SSE transmission\n * @param data The data to send\n * @param event Optional event type\n * @param id Optional event ID\n * @returns Formatted SSE string\n */\nexport function formatSSE(data: any, event?: string, id?: string): string {\n  let message = \"\";\n\n  if (id) {\n    message += `id: ${id}\\n`;\n  }\n\n  if (event) {\n    message += `event: ${event}\\n`;\n  }\n\n  // Handle multiline data\n  const dataStr = typeof data === \"string\" ? data : safeStringify(data);\n  const lines = dataStr.split(\"\\n\");\n\n  for (const line of lines) {\n    message += `data: ${line}\\n`;\n  }\n\n  message += \"\\n\";\n  return message;\n}\n\n/**\n * Create an SSE-compatible ReadableStream from an async generator\n * @param generator Async generator that yields SSE events\n * @returns ReadableStream that outputs SSE-formatted data\n */\nexport function createSSEStream(\n  generator: AsyncGenerator<any, void, unknown>,\n): ReadableStream<Uint8Array> {\n  const encoder = new TextEncoder();\n\n  return new ReadableStream({\n    async start(controller) {\n      try {\n        for await (const data of generator) {\n          const formatted = formatSSE(data);\n          controller.enqueue(encoder.encode(formatted));\n        }\n      } catch (error) {\n        // Send error as SSE event\n        const errorData = {\n          error: error instanceof Error ? error.message : \"Unknown error\",\n          type: \"error\",\n        };\n        controller.enqueue(encoder.encode(formatSSE(errorData, \"error\")));\n      } finally {\n        controller.close();\n      }\n    },\n  });\n}\n\n/**\n * Transform a ReadableStream to SSE format\n * @param stream Input stream\n * @param options Transformation options\n * @returns SSE-formatted ReadableStream\n */\nexport function transformToSSE(\n  stream: ReadableStream,\n  options?: {\n    eventType?: string;\n    formatter?: (chunk: any) => any;\n  },\n): ReadableStream<Uint8Array> {\n  const encoder = new TextEncoder();\n  const decoder = new TextDecoder();\n\n  return stream.pipeThrough(\n    new TransformStream({\n      transform(chunk, controller) {\n        try {\n          // Decode if it's a Uint8Array\n          const data = chunk instanceof Uint8Array ? decoder.decode(chunk) : chunk;\n\n          // Apply custom formatter if provided\n          const formatted = options?.formatter ? options.formatter(data) : data;\n\n          // Format as SSE\n          const sse = formatSSE(formatted, options?.eventType);\n          controller.enqueue(encoder.encode(sse));\n        } catch (error) {\n          const errorSSE = formatSSE(\n            { error: error instanceof Error ? error.message : \"Transform error\" },\n            \"error\",\n          );\n          controller.enqueue(encoder.encode(errorSSE));\n        }\n      },\n    }),\n  );\n}\n\n/**\n * Create SSE headers for response\n * @returns Headers object with SSE content type\n */\nexport function createSSEHeaders(): Record<string, string> {\n  return {\n    \"Content-Type\": \"text/event-stream\",\n    \"Cache-Control\": \"no-cache\",\n    Connection: \"keep-alive\",\n    \"X-Accel-Buffering\": \"no\", // Disable Nginx buffering\n  };\n}\n\n/**\n * Create an SSE response from a stream\n * Framework-agnostic SSE response creation\n * @param stream The stream to send as SSE\n * @param status HTTP status code\n * @returns Response object\n */\nexport function createSSEResponse(stream: ReadableStream<Uint8Array>, status = 200): Response {\n  return new Response(stream, {\n    status,\n    headers: createSSEHeaders(),\n  });\n}\n","import type { ServerProviderDeps } from \"@voltagent/core\";\nimport type { Agent, Memory } from \"@voltagent/core\";\nimport { safeStringify } from \"@voltagent/internal\";\nimport type {\n  MemoryConversationMessagesResult,\n  MemoryConversationStepsResult,\n  MemoryConversationSummary,\n  MemoryGetMessagesQuery,\n  MemoryGetStepsQuery,\n  MemoryListConversationsQuery,\n  MemoryListUsersQuery,\n  MemoryUserSummary,\n  MemoryWorkingMemoryResult,\n} from \"../types/observability-memory\";\nimport type { ApiResponse } from \"../types/responses\";\n\ninterface AgentMemoryContext {\n  agentId: string;\n  agentName?: string;\n  agent: Agent;\n  memory: Memory;\n}\n\nconst DEFAULT_LIMIT = 50;\nconst MAX_LIMIT = 200;\n\nfunction clampLimit(value?: number): number {\n  if (!value || Number.isNaN(value)) {\n    return DEFAULT_LIMIT;\n  }\n  return Math.min(Math.max(1, value), MAX_LIMIT);\n}\n\nfunction normalizeOffset(value?: number): number {\n  if (!value || Number.isNaN(value) || value < 0) {\n    return 0;\n  }\n  return value;\n}\n\nfunction getAgentsWithMemory(\n  deps: ServerProviderDeps,\n  targetAgentId?: string,\n): AgentMemoryContext[] {\n  const agents = deps.agentRegistry.getAllAgents();\n\n  return agents\n    .filter((agent) => {\n      if (targetAgentId && agent.getFullState().id !== targetAgentId) {\n        return false;\n      }\n      const memory = agent.getMemory();\n      return (\n        typeof memory === \"object\" &&\n        memory !== null &&\n        typeof (memory as Memory).queryConversations === \"function\"\n      );\n    })\n    .map((agent) => {\n      const state = agent.getFullState();\n      return {\n        agent,\n        agentId: state.id,\n        agentName: state.name,\n        memory: agent.getMemory() as Memory,\n      };\n    });\n}\n\nfunction sortConversations(\n  conversations: MemoryConversationSummary[],\n  orderBy: string,\n  direction: \"ASC\" | \"DESC\",\n) {\n  const multiplier = direction === \"ASC\" ? 1 : -1;\n\n  conversations.sort((a, b) => {\n    if (orderBy === \"title\") {\n      return a.title.localeCompare(b.title) * multiplier;\n    }\n    if (orderBy === \"created_at\") {\n      return (new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()) * multiplier;\n    }\n    return (new Date(a.updatedAt).getTime() - new Date(b.updatedAt).getTime()) * multiplier;\n  });\n}\n\nexport async function listMemoryUsersHandler(\n  deps: ServerProviderDeps,\n  query: MemoryListUsersQuery,\n): Promise<\n  ApiResponse<{ users: MemoryUserSummary[]; total: number; limit: number; offset: number }>\n> {\n  try {\n    const limit = clampLimit(query.limit);\n    const offset = normalizeOffset(query.offset);\n    const agents = getAgentsWithMemory(deps, query.agentId);\n\n    if (agents.length === 0) {\n      return {\n        success: true,\n        data: { users: [], total: 0, limit, offset },\n      };\n    }\n\n    const userMap = new Map<string, MemoryUserSummary>();\n\n    for (const { agentId, agentName, memory } of agents) {\n      // Fetch all conversations for this agent; currently no native distinct-user query\n      // TODO: optimize via storage-level user listing\n      const conversations: any[] = await memory.queryConversations({ resourceId: agentId });\n\n      for (const conversation of conversations) {\n        if (!conversation?.userId) {\n          continue;\n        }\n\n        const userId = conversation.userId as string;\n        const lastInteractionAt = conversation.updatedAt as string;\n        let summary = userMap.get(userId);\n\n        if (!summary) {\n          summary = {\n            userId,\n            conversationCount: 0,\n            agents: [],\n            lastInteractionAt,\n          };\n          userMap.set(userId, summary);\n        }\n\n        summary.conversationCount += 1;\n        if (\n          !summary.lastInteractionAt ||\n          new Date(lastInteractionAt).getTime() > new Date(summary.lastInteractionAt).getTime()\n        ) {\n          summary.lastInteractionAt = lastInteractionAt;\n        }\n\n        let agentSummary = summary.agents.find((item) => item.agentId === agentId);\n        if (!agentSummary) {\n          agentSummary = {\n            agentId,\n            agentName,\n            conversationCount: 0,\n            lastInteractionAt,\n          };\n          summary.agents.push(agentSummary);\n        }\n\n        agentSummary.conversationCount += 1;\n        if (\n          !agentSummary.lastInteractionAt ||\n          new Date(lastInteractionAt).getTime() > new Date(agentSummary.lastInteractionAt).getTime()\n        ) {\n          agentSummary.lastInteractionAt = lastInteractionAt;\n        }\n      }\n    }\n\n    let users = Array.from(userMap.values());\n\n    if (query.search) {\n      const term = query.search.toLowerCase();\n      users = users.filter((item) => item.userId.toLowerCase().includes(term));\n    }\n\n    users.sort((a, b) => {\n      const aTime = a.lastInteractionAt ? new Date(a.lastInteractionAt).getTime() : 0;\n      const bTime = b.lastInteractionAt ? new Date(b.lastInteractionAt).getTime() : 0;\n      return bTime - aTime;\n    });\n\n    const total = users.length;\n    const paginated = users.slice(offset, offset + limit);\n\n    return {\n      success: true,\n      data: {\n        users: paginated,\n        total,\n        limit,\n        offset,\n      },\n    };\n  } catch (error) {\n    return {\n      success: false,\n      error: error instanceof Error ? error.message : safeStringify(error),\n    };\n  }\n}\n\nexport async function listMemoryConversationsHandler(\n  deps: ServerProviderDeps,\n  query: MemoryListConversationsQuery,\n): Promise<\n  ApiResponse<{\n    conversations: MemoryConversationSummary[];\n    total: number;\n    limit: number;\n    offset: number;\n  }>\n> {\n  try {\n    const limit = clampLimit(query.limit);\n    const offset = normalizeOffset(query.offset);\n    const orderBy = query.orderBy || \"updated_at\";\n    const orderDirection = query.orderDirection || \"DESC\";\n\n    const agents = getAgentsWithMemory(deps, query.agentId);\n\n    if (agents.length === 0) {\n      return {\n        success: true,\n        data: { conversations: [], total: 0, limit, offset },\n      };\n    }\n\n    const conversations: MemoryConversationSummary[] = [];\n\n    for (const { agentId, agentName, memory } of agents) {\n      const convList: any[] = await memory.queryConversations({\n        resourceId: agentId,\n        userId: query.userId,\n        orderBy,\n        orderDirection,\n      });\n\n      for (const conv of convList) {\n        const summary: MemoryConversationSummary = {\n          id: conv.id,\n          userId: conv.userId,\n          agentId,\n          agentName,\n          title: conv.title,\n          createdAt: conv.createdAt,\n          updatedAt: conv.updatedAt,\n          metadata: conv.metadata,\n        };\n\n        conversations.push(summary);\n      }\n    }\n\n    sortConversations(conversations, orderBy, orderDirection);\n\n    const total = conversations.length;\n    const paginated = conversations.slice(offset, offset + limit);\n\n    return {\n      success: true,\n      data: {\n        conversations: paginated,\n        total,\n        limit,\n        offset,\n      },\n    };\n  } catch (error) {\n    return {\n      success: false,\n      error: error instanceof Error ? error.message : safeStringify(error),\n    };\n  }\n}\n\nexport async function getConversationMessagesHandler(\n  deps: ServerProviderDeps,\n  conversationId: string,\n  query: MemoryGetMessagesQuery,\n): Promise<ApiResponse<MemoryConversationMessagesResult>> {\n  try {\n    const agents = getAgentsWithMemory(deps, query.agentId);\n\n    if (agents.length === 0) {\n      return {\n        success: false,\n        error: \"Conversation not found\",\n      };\n    }\n\n    for (const { agentId, agentName, memory } of agents) {\n      const conversation = await memory.getConversation(conversationId);\n      if (!conversation) {\n        continue;\n      }\n\n      const messages = await memory.getMessages(conversation.userId, conversationId, {\n        limit: query.limit ? clampLimit(query.limit) : undefined,\n        before: query.before,\n        after: query.after,\n        roles: query.roles,\n      });\n\n      const result: MemoryConversationMessagesResult = {\n        conversation: {\n          id: conversation.id,\n          userId: conversation.userId,\n          agentId,\n          agentName,\n          title: conversation.title,\n          createdAt: conversation.createdAt,\n          updatedAt: conversation.updatedAt,\n          metadata: conversation.metadata,\n        },\n        messages,\n      };\n\n      return {\n        success: true,\n        data: result,\n      };\n    }\n\n    return {\n      success: false,\n      error: \"Conversation not found\",\n    };\n  } catch (error) {\n    return {\n      success: false,\n      error: error instanceof Error ? error.message : safeStringify(error),\n    };\n  }\n}\n\nexport async function getConversationStepsHandler(\n  deps: ServerProviderDeps,\n  conversationId: string,\n  query: MemoryGetStepsQuery,\n): Promise<ApiResponse<MemoryConversationStepsResult>> {\n  try {\n    const agents = getAgentsWithMemory(deps, query.agentId);\n\n    if (agents.length === 0) {\n      return {\n        success: false,\n        error: \"Conversation not found\",\n      };\n    }\n\n    for (const { agentId, agentName, memory } of agents) {\n      const conversation = await memory.getConversation(conversationId);\n      if (!conversation) {\n        continue;\n      }\n\n      const memoryWithSteps = memory as Memory & {\n        getConversationSteps?: (\n          userId: string,\n          conversationId: string,\n          options?: MemoryGetStepsQuery,\n        ) => Promise<any>;\n      };\n\n      if (typeof memoryWithSteps.getConversationSteps !== \"function\") {\n        return {\n          success: false,\n          error: \"Conversation steps are not supported by this memory adapter.\",\n        };\n      }\n\n      const steps = await memoryWithSteps.getConversationSteps(\n        conversation.userId,\n        conversationId,\n        {\n          limit: query.limit ? clampLimit(query.limit) : undefined,\n          operationId: query.operationId,\n        },\n      );\n\n      return {\n        success: true,\n        data: {\n          conversation: {\n            id: conversation.id,\n            userId: conversation.userId,\n            agentId,\n            agentName,\n            title: conversation.title,\n            createdAt: conversation.createdAt,\n            updatedAt: conversation.updatedAt,\n            metadata: conversation.metadata,\n          },\n          steps,\n        },\n      };\n    }\n\n    return {\n      success: false,\n      error: \"Conversation not found\",\n    };\n  } catch (error) {\n    return {\n      success: false,\n      error: error instanceof Error ? error.message : safeStringify(error),\n    };\n  }\n}\n\nexport async function getWorkingMemoryHandler(\n  deps: ServerProviderDeps,\n  params: {\n    agentId?: string;\n    conversationId?: string;\n    userId?: string;\n    scope: \"conversation\" | \"user\";\n  },\n): Promise<ApiResponse<MemoryWorkingMemoryResult>> {\n  try {\n    const agents = getAgentsWithMemory(deps, params.agentId);\n\n    if (agents.length === 0) {\n      if (params.scope === \"user\" && params.userId) {\n        return {\n          success: true,\n          data: {\n            agentId: null,\n            agentName: null,\n            scope: \"user\",\n            content: null,\n            format: null,\n            template: null,\n          },\n        };\n      }\n\n      return {\n        success: false,\n        error: \"Working memory not found\",\n      };\n    }\n\n    for (const { agentId, agentName, memory } of agents) {\n      if (params.scope === \"conversation\" && params.conversationId) {\n        const conversation = await memory.getConversation(params.conversationId);\n        if (!conversation) {\n          continue;\n        }\n\n        const content = await memory.getWorkingMemory({\n          conversationId: params.conversationId,\n          userId: conversation.userId,\n        });\n\n        return {\n          success: true,\n          data: {\n            agentId,\n            agentName,\n            scope: \"conversation\",\n            content,\n            format: memory.getWorkingMemoryFormat?.() ?? null,\n            template: memory.getWorkingMemoryTemplate?.() ?? null,\n          },\n        };\n      }\n\n      if (params.scope === \"user\" && params.userId) {\n        const content = await memory.getWorkingMemory({\n          userId: params.userId,\n        });\n\n        if (content !== null) {\n          return {\n            success: true,\n            data: {\n              agentId,\n              agentName,\n              scope: \"user\",\n              content,\n              format: memory.getWorkingMemoryFormat?.() ?? null,\n              template: memory.getWorkingMemoryTemplate?.() ?? null,\n            },\n          };\n        }\n      }\n    }\n\n    if (params.scope === \"user\" && params.userId) {\n      const fallbackAgent = agents[0];\n      return {\n        success: true,\n        data: {\n          agentId: fallbackAgent ? fallbackAgent.agentId : null,\n          agentName: fallbackAgent ? fallbackAgent.agentName : null,\n          scope: \"user\",\n          content: null,\n          format: null,\n          template: null,\n        },\n      };\n    }\n\n    return {\n      success: false,\n      error: \"Working memory not found\",\n    };\n  } catch (error) {\n    return {\n      success: false,\n      error: error instanceof Error ? error.message : safeStringify(error),\n    };\n  }\n}\n","import {\n  AgentRegistry,\n  type Conversation,\n  ConversationAlreadyExistsError,\n  ConversationNotFoundError,\n  EmbeddingAdapterNotConfiguredError,\n  type Memory,\n  type ServerProviderDeps,\n  VectorAdapterNotConfiguredError,\n} from \"@voltagent/core\";\nimport { safeStringify } from \"@voltagent/internal\";\nimport { type UIMessage, generateId } from \"ai\";\nimport type { ApiResponse } from \"../types\";\n\ntype MemoryResolution =\n  | {\n      ok: true;\n      memory: Memory;\n      agentId?: string;\n      agentName?: string;\n      resourceId?: string;\n    }\n  | {\n      ok: false;\n      error: string;\n      httpStatus?: number;\n    };\n\nfunction resolveMemory(\n  deps: { agentRegistry: ServerProviderDeps[\"agentRegistry\"] },\n  agentId?: string,\n): MemoryResolution {\n  if (agentId) {\n    const agent = deps.agentRegistry.getAgent(agentId);\n    if (!agent) {\n      return {\n        ok: false,\n        error: `Agent ${agentId} not found`,\n        httpStatus: 404,\n      };\n    }\n\n    const memory = agent.getMemory();\n    if (!memory) {\n      return {\n        ok: false,\n        error: `Memory not configured for agent ${agentId}`,\n        httpStatus: 400,\n      };\n    }\n\n    const state = agent.getFullState();\n    return {\n      ok: true,\n      memory,\n      agentId: state.id,\n      agentName: state.name,\n      resourceId: state.id,\n    };\n  }\n\n  const registry = AgentRegistry.getInstance();\n  const globalMemory = registry.getGlobalMemory();\n  if (globalMemory) {\n    return { ok: true, memory: globalMemory };\n  }\n\n  const agents = deps.agentRegistry.getAllAgents();\n  const agentsWithMemory = agents.filter((agent) => {\n    const memory = agent.getMemory();\n    return typeof memory === \"object\" && memory !== null;\n  });\n\n  if (agentsWithMemory.length === 1) {\n    const agent = agentsWithMemory[0];\n    const memory = agent.getMemory() as Memory;\n    const state = agent.getFullState();\n    return {\n      ok: true,\n      memory,\n      agentId: state.id,\n      agentName: state.name,\n      resourceId: state.id,\n    };\n  }\n\n  if (agentsWithMemory.length > 1) {\n    return {\n      ok: false,\n      error: \"agentId is required when multiple agents are configured\",\n      httpStatus: 400,\n    };\n  }\n\n  return {\n    ok: false,\n    error: \"Memory not configured\",\n    httpStatus: 400,\n  };\n}\n\nfunction buildErrorResponse(error: unknown): ApiResponse {\n  return {\n    success: false,\n    error: error instanceof Error ? error.message : safeStringify(error),\n  };\n}\n\nexport async function handleListMemoryConversations(\n  deps: ServerProviderDeps,\n  query: {\n    agentId?: string;\n    resourceId?: string;\n    userId?: string;\n    limit?: number;\n    offset?: number;\n    orderBy?: \"created_at\" | \"updated_at\" | \"title\";\n    orderDirection?: \"ASC\" | \"DESC\";\n  },\n): Promise<\n  ApiResponse<{ conversations: Conversation[]; total: number; limit: number; offset: number }>\n> {\n  try {\n    const resolved = resolveMemory(deps, query.agentId);\n    if (!resolved.ok) {\n      return {\n        success: false,\n        error: resolved.error,\n        httpStatus: resolved.httpStatus,\n      };\n    }\n\n    const resourceId = query.resourceId ?? resolved.resourceId;\n    const [conversations, total] = await Promise.all([\n      resolved.memory.queryConversations({\n        userId: query.userId,\n        resourceId,\n        limit: query.limit,\n        offset: query.offset,\n        orderBy: query.orderBy,\n        orderDirection: query.orderDirection,\n      }),\n      resolved.memory.countConversations({\n        userId: query.userId,\n        resourceId,\n      }),\n    ]);\n\n    return {\n      success: true,\n      data: {\n        conversations,\n        total,\n        limit: query.limit ?? conversations.length,\n        offset: query.offset ?? 0,\n      },\n    };\n  } catch (error) {\n    return buildErrorResponse(error);\n  }\n}\n\nexport async function handleGetMemoryConversation(\n  deps: ServerProviderDeps,\n  conversationId: string,\n  query: { agentId?: string },\n): Promise<ApiResponse<{ conversation: Conversation }>> {\n  try {\n    const resolved = resolveMemory(deps, query.agentId);\n    if (!resolved.ok) {\n      return {\n        success: false,\n        error: resolved.error,\n        httpStatus: resolved.httpStatus,\n      };\n    }\n\n    const conversation = await resolved.memory.getConversation(conversationId);\n    if (!conversation) {\n      return {\n        success: false,\n        error: \"Conversation not found\",\n        httpStatus: 404,\n      };\n    }\n\n    return {\n      success: true,\n      data: { conversation },\n    };\n  } catch (error) {\n    return buildErrorResponse(error);\n  }\n}\n\nexport async function handleListMemoryConversationMessages(\n  deps: ServerProviderDeps,\n  conversationId: string,\n  query: {\n    agentId?: string;\n    limit?: number;\n    before?: Date;\n    after?: Date;\n    roles?: string[];\n    userId?: string;\n  },\n): Promise<ApiResponse<{ conversation: Conversation; messages: UIMessage[] }>> {\n  try {\n    const resolved = resolveMemory(deps, query.agentId);\n    if (!resolved.ok) {\n      return {\n        success: false,\n        error: resolved.error,\n        httpStatus: resolved.httpStatus,\n      };\n    }\n\n    const conversation = await resolved.memory.getConversation(conversationId);\n    if (!conversation) {\n      return {\n        success: false,\n        error: \"Conversation not found\",\n        httpStatus: 404,\n      };\n    }\n\n    const userId = query.userId ?? conversation.userId;\n    const messages = await resolved.memory.getMessages(userId, conversationId, {\n      limit: query.limit,\n      before: query.before,\n      after: query.after,\n      roles: query.roles,\n    });\n\n    return {\n      success: true,\n      data: { conversation, messages },\n    };\n  } catch (error) {\n    return buildErrorResponse(error);\n  }\n}\n\nexport async function handleGetMemoryWorkingMemory(\n  deps: ServerProviderDeps,\n  conversationId: string,\n  query: { agentId?: string; scope?: \"conversation\" | \"user\"; userId?: string },\n): Promise<\n  ApiResponse<{\n    content: string | null;\n    format: \"markdown\" | \"json\" | null;\n    template: string | null;\n    scope: \"conversation\" | \"user\";\n  }>\n> {\n  try {\n    const resolved = resolveMemory(deps, query.agentId);\n    if (!resolved.ok) {\n      return {\n        success: false,\n        error: resolved.error,\n        httpStatus: resolved.httpStatus,\n      };\n    }\n\n    const scope = query.scope === \"user\" ? \"user\" : \"conversation\";\n    let content: string | null = null;\n    let userId = query.userId;\n\n    if (scope === \"conversation\") {\n      const conversation = await resolved.memory.getConversation(conversationId);\n      if (!conversation) {\n        return {\n          success: false,\n          error: \"Conversation not found\",\n          httpStatus: 404,\n        };\n      }\n\n      userId = userId ?? conversation.userId;\n      content = await resolved.memory.getWorkingMemory({\n        conversationId,\n        userId,\n      });\n    } else {\n      if (!userId) {\n        return {\n          success: false,\n          error: \"userId is required for user-scoped working memory\",\n          httpStatus: 400,\n        };\n      }\n\n      content = await resolved.memory.getWorkingMemory({\n        userId,\n      });\n    }\n\n    if (content === null) {\n      return {\n        success: false,\n        error: \"Working memory not found\",\n        httpStatus: 404,\n      };\n    }\n\n    return {\n      success: true,\n      data: {\n        content,\n        scope,\n        format: resolved.memory.getWorkingMemoryFormat?.() ?? null,\n        template: resolved.memory.getWorkingMemoryTemplate?.() ?? null,\n      },\n    };\n  } catch (error) {\n    return buildErrorResponse(error);\n  }\n}\n\ntype SaveMessageEntry =\n  | (UIMessage & { userId?: string; conversationId?: string })\n  | { message: UIMessage; userId?: string; conversationId?: string };\n\nexport async function handleSaveMemoryMessages(\n  deps: ServerProviderDeps,\n  body: {\n    agentId?: string;\n    userId?: string;\n    conversationId?: string;\n    messages?: SaveMessageEntry[];\n  },\n): Promise<ApiResponse<{ saved: number }>> {\n  try {\n    const resolved = resolveMemory(deps, body.agentId);\n    if (!resolved.ok) {\n      return {\n        success: false,\n        error: resolved.error,\n        httpStatus: resolved.httpStatus,\n      };\n    }\n\n    if (!Array.isArray(body.messages) || body.messages.length === 0) {\n      return {\n        success: false,\n        error: \"messages array is required\",\n        httpStatus: 400,\n      };\n    }\n\n    const normalized = body.messages.map((entry) => {\n      const isWrapped = typeof entry === \"object\" && entry !== null && \"message\" in entry;\n      const message = isWrapped ? entry.message : (entry as UIMessage);\n      const conversationId =\n        (isWrapped ? entry.conversationId : entry.conversationId) ?? body.conversationId;\n      const userId = (isWrapped ? entry.userId : entry.userId) ?? body.userId;\n\n      return {\n        message: {\n          ...message,\n          id: message.id || generateId(),\n        },\n        conversationId,\n        userId,\n      };\n    });\n\n    const missing = normalized.filter((item) => !item.conversationId || !item.userId);\n    if (missing.length > 0) {\n      return {\n        success: false,\n        error: \"Each message must include conversationId and userId\",\n        httpStatus: 400,\n      };\n    }\n\n    const conversationCache = new Map<string, Conversation>();\n    for (const item of normalized) {\n      const conversationId = item.conversationId as string;\n      if (!conversationCache.has(conversationId)) {\n        const conversation = await resolved.memory.getConversation(conversationId);\n        if (!conversation) {\n          return {\n            success: false,\n            error: `Conversation not found: ${conversationId}`,\n            httpStatus: 404,\n          };\n        }\n        conversationCache.set(conversationId, conversation);\n      }\n    }\n\n    for (const item of normalized) {\n      const conversation = conversationCache.get(item.conversationId as string);\n      if (conversation && conversation.userId !== item.userId) {\n        return {\n          success: false,\n          error: `userId does not match conversation ${conversation.id}`,\n          httpStatus: 400,\n        };\n      }\n    }\n\n    const grouped = new Map<\n      string,\n      { userId: string; conversationId: string; messages: UIMessage[] }\n    >();\n    for (const item of normalized) {\n      const conversationId = item.conversationId as string;\n      const userId = item.userId as string;\n      const key = `${userId}:${conversationId}`;\n      const entry = grouped.get(key) || { userId, conversationId, messages: [] };\n      entry.messages.push(item.message);\n      grouped.set(key, entry);\n    }\n\n    for (const entry of grouped.values()) {\n      await resolved.memory.addMessages(entry.messages, entry.userId, entry.conversationId);\n    }\n\n    return {\n      success: true,\n      data: { saved: normalized.length },\n    };\n  } catch (error) {\n    return buildErrorResponse(error);\n  }\n}\n\nexport async function handleCreateMemoryConversation(\n  deps: ServerProviderDeps,\n  body: {\n    agentId?: string;\n    conversationId?: string;\n    resourceId?: string;\n    userId?: string;\n    title?: string;\n    metadata?: Record<string, unknown>;\n  },\n): Promise<ApiResponse<{ conversation: Conversation }>> {\n  try {\n    const resolved = resolveMemory(deps, body.agentId);\n    if (!resolved.ok) {\n      return {\n        success: false,\n        error: resolved.error,\n        httpStatus: resolved.httpStatus,\n      };\n    }\n\n    if (!body.userId) {\n      return {\n        success: false,\n        error: \"userId is required\",\n        httpStatus: 400,\n      };\n    }\n\n    const resourceId = body.resourceId ?? resolved.resourceId;\n    if (!resourceId) {\n      return {\n        success: false,\n        error: \"resourceId is required\",\n        httpStatus: 400,\n      };\n    }\n\n    const conversationId = body.conversationId ?? generateId();\n    const conversation = await resolved.memory.createConversation({\n      id: conversationId,\n      resourceId,\n      userId: body.userId,\n      title: body.title ?? \"\",\n      metadata: body.metadata ?? {},\n    });\n\n    return {\n      success: true,\n      data: { conversation },\n    };\n  } catch (error) {\n    if (error instanceof ConversationAlreadyExistsError) {\n      return {\n        success: false,\n        error: error.message,\n        httpStatus: 409,\n      };\n    }\n    return buildErrorResponse(error);\n  }\n}\n\nexport async function handleUpdateMemoryConversation(\n  deps: ServerProviderDeps,\n  conversationId: string,\n  body: {\n    agentId?: string;\n    resourceId?: string;\n    userId?: string;\n    title?: string;\n    metadata?: Record<string, unknown>;\n  },\n): Promise<ApiResponse<{ conversation: Conversation }>> {\n  try {\n    const resolved = resolveMemory(deps, body.agentId);\n    if (!resolved.ok) {\n      return {\n        success: false,\n        error: resolved.error,\n        httpStatus: resolved.httpStatus,\n      };\n    }\n\n    const updates: Partial<Omit<Conversation, \"id\" | \"createdAt\" | \"updatedAt\">> = {};\n    if (body.resourceId !== undefined) {\n      updates.resourceId = body.resourceId;\n    }\n    if (body.userId !== undefined) {\n      updates.userId = body.userId;\n    }\n    if (body.title !== undefined) {\n      updates.title = body.title;\n    }\n    if (body.metadata !== undefined) {\n      updates.metadata = body.metadata;\n    }\n\n    if (Object.keys(updates).length === 0) {\n      return {\n        success: false,\n        error: \"No updates provided\",\n        httpStatus: 400,\n      };\n    }\n\n    const conversation = await resolved.memory.updateConversation(conversationId, updates);\n    return {\n      success: true,\n      data: { conversation },\n    };\n  } catch (error) {\n    if (error instanceof ConversationNotFoundError) {\n      return {\n        success: false,\n        error: error.message,\n        httpStatus: 404,\n      };\n    }\n    return buildErrorResponse(error);\n  }\n}\n\nexport async function handleDeleteMemoryConversation(\n  deps: ServerProviderDeps,\n  conversationId: string,\n  query: { agentId?: string },\n): Promise<ApiResponse<{ deleted: boolean }>> {\n  try {\n    const resolved = resolveMemory(deps, query.agentId);\n    if (!resolved.ok) {\n      return {\n        success: false,\n        error: resolved.error,\n        httpStatus: resolved.httpStatus,\n      };\n    }\n\n    await resolved.memory.deleteConversation(conversationId);\n    return {\n      success: true,\n      data: { deleted: true },\n    };\n  } catch (error) {\n    if (error instanceof ConversationNotFoundError) {\n      return {\n        success: false,\n        error: error.message,\n        httpStatus: 404,\n      };\n    }\n    return buildErrorResponse(error);\n  }\n}\n\nexport async function handleCloneMemoryConversation(\n  deps: ServerProviderDeps,\n  conversationId: string,\n  body: {\n    agentId?: string;\n    newConversationId?: string;\n    resourceId?: string;\n    userId?: string;\n    title?: string;\n    metadata?: Record<string, unknown>;\n    includeMessages?: boolean;\n  },\n): Promise<ApiResponse<{ conversation: Conversation; messageCount: number }>> {\n  try {\n    const resolved = resolveMemory(deps, body.agentId);\n    if (!resolved.ok) {\n      return {\n        success: false,\n        error: resolved.error,\n        httpStatus: resolved.httpStatus,\n      };\n    }\n\n    const source = await resolved.memory.getConversation(conversationId);\n    if (!source) {\n      return {\n        success: false,\n        error: \"Conversation not found\",\n        httpStatus: 404,\n      };\n    }\n\n    const clonedId = body.newConversationId ?? generateId();\n    const conversation = await resolved.memory.createConversation({\n      id: clonedId,\n      resourceId: body.resourceId ?? source.resourceId,\n      userId: body.userId ?? source.userId,\n      title: body.title ?? source.title,\n      metadata: body.metadata ?? source.metadata,\n    });\n\n    let messageCount = 0;\n    const includeMessages = body.includeMessages !== false;\n    if (includeMessages) {\n      const messages = await resolved.memory.getMessages(source.userId, conversationId);\n      if (messages.length > 0) {\n        await resolved.memory.addMessages(messages, conversation.userId, conversation.id);\n        messageCount = messages.length;\n      }\n    }\n\n    return {\n      success: true,\n      data: { conversation, messageCount },\n    };\n  } catch (error) {\n    if (error instanceof ConversationAlreadyExistsError) {\n      return {\n        success: false,\n        error: error.message,\n        httpStatus: 409,\n      };\n    }\n    return buildErrorResponse(error);\n  }\n}\n\nexport async function handleUpdateMemoryWorkingMemory(\n  deps: ServerProviderDeps,\n  conversationId: string,\n  body: {\n    agentId?: string;\n    userId?: string;\n    content?: string | Record<string, unknown>;\n    mode?: \"replace\" | \"append\";\n  },\n): Promise<ApiResponse<{ updated: boolean }>> {\n  try {\n    const resolved = resolveMemory(deps, body.agentId);\n    if (!resolved.ok) {\n      return {\n        success: false,\n        error: resolved.error,\n        httpStatus: resolved.httpStatus,\n      };\n    }\n\n    if (body.content === undefined) {\n      return {\n        success: false,\n        error: \"content is required\",\n        httpStatus: 400,\n      };\n    }\n\n    const conversation = await resolved.memory.getConversation(conversationId);\n    if (!conversation) {\n      return {\n        success: false,\n        error: \"Conversation not found\",\n        httpStatus: 404,\n      };\n    }\n\n    const userId = body.userId ?? conversation.userId;\n    if (body.userId && body.userId !== conversation.userId) {\n      return {\n        success: false,\n        error: `userId does not match conversation ${conversation.id}`,\n        httpStatus: 400,\n      };\n    }\n    await resolved.memory.updateWorkingMemory({\n      conversationId,\n      userId,\n      content: body.content,\n      options: body.mode ? { mode: body.mode } : undefined,\n    });\n\n    return {\n      success: true,\n      data: { updated: true },\n    };\n  } catch (error) {\n    return buildErrorResponse(error);\n  }\n}\n\nexport async function handleDeleteMemoryMessages(\n  deps: ServerProviderDeps,\n  body: {\n    agentId?: string;\n    conversationId?: string;\n    userId?: string;\n    messageIds?: string[];\n  },\n): Promise<ApiResponse<{ deleted: number }>> {\n  try {\n    const resolved = resolveMemory(deps, body.agentId);\n    if (!resolved.ok) {\n      return {\n        success: false,\n        error: resolved.error,\n        httpStatus: resolved.httpStatus,\n      };\n    }\n\n    if (!Array.isArray(body.messageIds) || body.messageIds.length === 0) {\n      return {\n        success: false,\n        error: \"messageIds array is required\",\n        httpStatus: 400,\n      };\n    }\n\n    if (!body.conversationId || !body.userId) {\n      return {\n        success: false,\n        error: \"conversationId and userId are required\",\n        httpStatus: 400,\n      };\n    }\n\n    const conversation = await resolved.memory.getConversation(body.conversationId);\n    if (!conversation) {\n      return {\n        success: false,\n        error: \"Conversation not found\",\n        httpStatus: 404,\n      };\n    }\n    if (conversation.userId !== body.userId) {\n      return {\n        success: false,\n        error: `userId does not match conversation ${conversation.id}`,\n        httpStatus: 400,\n      };\n    }\n\n    const messages = await resolved.memory.getMessages(body.userId, body.conversationId);\n    const idsToDelete = new Set(body.messageIds);\n    const deleted = messages.filter((message) => idsToDelete.has(message.id)).length;\n    await resolved.memory.deleteMessages(body.messageIds, body.userId, body.conversationId);\n    return {\n      success: true,\n      data: { deleted },\n    };\n  } catch (error) {\n    return buildErrorResponse(error);\n  }\n}\n\nexport async function handleSearchMemory(\n  deps: ServerProviderDeps,\n  query: {\n    agentId?: string;\n    searchQuery?: string;\n    limit?: number;\n    threshold?: number;\n    conversationId?: string;\n    userId?: string;\n  },\n): Promise<ApiResponse<{ results: unknown[]; count: number; query: string }>> {\n  try {\n    if (!query.searchQuery) {\n      return {\n        success: false,\n        error: \"searchQuery is required\",\n        httpStatus: 400,\n      };\n    }\n\n    const resolved = resolveMemory(deps, query.agentId);\n    if (!resolved.ok) {\n      return {\n        success: false,\n        error: resolved.error,\n        httpStatus: resolved.httpStatus,\n      };\n    }\n\n    const filter: Record<string, unknown> = {};\n    if (query.conversationId) {\n      filter.conversationId = query.conversationId;\n    }\n    if (query.userId) {\n      filter.userId = query.userId;\n    }\n\n    const results = await resolved.memory.searchSimilar(query.searchQuery, {\n      limit: query.limit,\n      threshold: query.threshold,\n      filter: Object.keys(filter).length > 0 ? filter : undefined,\n    });\n\n    return {\n      success: true,\n      data: {\n        results,\n        count: results.length,\n        query: query.searchQuery,\n      },\n    };\n  } catch (error) {\n    if (\n      error instanceof EmbeddingAdapterNotConfiguredError ||\n      error instanceof VectorAdapterNotConfiguredError\n    ) {\n      return {\n        success: false,\n        error: error.message,\n        httpStatus: 400,\n      };\n    }\n    return buildErrorResponse(error);\n  }\n}\n","import type { A2AServerRegistry } from \"@voltagent/core\";\nimport type { A2AServerMetadata } from \"@voltagent/internal/a2a\";\n\nimport type { A2AServerLikeWithHandlers } from \"./types\";\n\nexport interface A2AServerLookupResult {\n  server?: A2AServerLikeWithHandlers;\n  metadata?: A2AServerMetadata;\n}\n\nexport function listA2AServers(\n  registry: A2AServerRegistry<A2AServerLikeWithHandlers>,\n): A2AServerMetadata[] {\n  return registry.listMetadata();\n}\n\nexport function lookupA2AServer(\n  registry: A2AServerRegistry<A2AServerLikeWithHandlers>,\n  serverId: string,\n): A2AServerLookupResult {\n  const server = registry.getServer(serverId);\n  const metadata = registry.getMetadata(serverId);\n  return { server, metadata };\n}\n","import type { A2AServerLike } from \"@voltagent/internal/a2a\";\n\nexport type A2AJsonRpcId = string | number | null;\n\nexport interface JsonRpcError<Data = unknown> {\n  code: number;\n  message: string;\n  data?: Data;\n}\n\nexport interface JsonRpcResponse<Result = unknown, ErrorData = unknown> {\n  jsonrpc: \"2.0\";\n  id: A2AJsonRpcId;\n  result?: Result;\n  error?: JsonRpcError<ErrorData> | null;\n}\n\nexport interface JsonRpcStream<Result = unknown, ErrorData = unknown> {\n  kind: \"stream\";\n  id: A2AJsonRpcId;\n  stream: AsyncGenerator<JsonRpcResponse<Result, ErrorData>>;\n}\n\nexport type JsonRpcHandlerResult<Result = unknown, ErrorData = unknown> =\n  | JsonRpcResponse<Result, ErrorData>\n  | JsonRpcStream<Result, ErrorData>;\n\nexport interface JsonRpcRequest<Params = unknown> {\n  jsonrpc: \"2.0\";\n  id: A2AJsonRpcId;\n  method: string;\n  params?: Params;\n}\n\nexport interface A2ARequestContext {\n  userId?: string;\n  sessionId?: string;\n  metadata?: Record<string, unknown>;\n  requestUrl?: string;\n}\n\nexport interface AgentCardSkill {\n  id: string;\n  name: string;\n  description?: string;\n  tags?: string[];\n}\n\nexport interface AgentCardProviderInfo {\n  organization?: string;\n  url?: string;\n}\n\nexport interface AgentCardCapabilities {\n  streaming: boolean;\n  pushNotifications: boolean;\n  stateTransitionHistory: boolean;\n}\n\nexport interface AgentCard {\n  name: string;\n  description?: string;\n  url: string;\n  provider?: AgentCardProviderInfo;\n  version: string;\n  capabilities: AgentCardCapabilities;\n  defaultInputModes: string[];\n  defaultOutputModes: string[];\n  skills: AgentCardSkill[];\n}\n\nexport interface A2AServerLikeWithHandlers extends A2AServerLike {\n  getAgentCard?(agentId: string, context?: A2ARequestContext): AgentCard;\n  handleRequest?(\n    agentId: string,\n    request: JsonRpcRequest,\n    context?: A2ARequestContext,\n  ): Promise<JsonRpcHandlerResult>;\n}\n\nexport const A2AErrorCode = {\n  PARSE_ERROR: -32700,\n  INVALID_REQUEST: -32600,\n  METHOD_NOT_FOUND: -32601,\n  INVALID_PARAMS: -32602,\n  INTERNAL_ERROR: -32603,\n  TASK_NOT_FOUND: -32001,\n  TASK_NOT_CANCELABLE: -32002,\n  PUSH_NOTIFICATION_UNSUPPORTED: -32003,\n  UNSUPPORTED_OPERATION: -32004,\n} as const;\n\nexport type A2AErrorCode = (typeof A2AErrorCode)[keyof typeof A2AErrorCode];\n\nexport class VoltA2AError extends Error {\n  constructor(\n    public code: A2AErrorCode,\n    message: string,\n    public data?: unknown,\n    public taskId?: string,\n  ) {\n    super(message);\n    this.name = \"VoltA2AError\";\n  }\n\n  toJsonRpcError(): JsonRpcError {\n    return {\n      code: this.code,\n      message: this.message,\n      data: {\n        taskId: this.taskId,\n        ...(this.data ? { details: this.data } : {}),\n      },\n    };\n  }\n\n  static parseError(details?: unknown) {\n    return new VoltA2AError(A2AErrorCode.PARSE_ERROR, \"Invalid JSON payload\", details);\n  }\n\n  static invalidRequest(message = \"Invalid request\", details?: unknown) {\n    return new VoltA2AError(A2AErrorCode.INVALID_REQUEST, message, details);\n  }\n\n  static methodNotFound(method: string) {\n    return new VoltA2AError(A2AErrorCode.METHOD_NOT_FOUND, `Unknown method '${method}'`);\n  }\n\n  static invalidParams(message = \"Invalid parameters\", details?: unknown) {\n    return new VoltA2AError(A2AErrorCode.INVALID_PARAMS, message, details);\n  }\n\n  static taskNotFound(taskId: string) {\n    return new VoltA2AError(\n      A2AErrorCode.TASK_NOT_FOUND,\n      `Task '${taskId}' not found`,\n      undefined,\n      taskId,\n    );\n  }\n\n  static taskNotCancelable(taskId: string) {\n    return new VoltA2AError(\n      A2AErrorCode.TASK_NOT_CANCELABLE,\n      `Task '${taskId}' can no longer be canceled`,\n      undefined,\n      taskId,\n    );\n  }\n\n  static unsupportedOperation(message = \"Unsupported operation\") {\n    return new VoltA2AError(A2AErrorCode.UNSUPPORTED_OPERATION, message);\n  }\n\n  static internal(message = \"Internal error\", details?: unknown) {\n    return new VoltA2AError(A2AErrorCode.INTERNAL_ERROR, message, details);\n  }\n}\n\nexport function normalizeError(id: A2AJsonRpcId, cause: unknown): JsonRpcResponse<never> {\n  if (cause instanceof VoltA2AError) {\n    return {\n      jsonrpc: \"2.0\",\n      id,\n      error: cause.toJsonRpcError(),\n    };\n  }\n  if (cause instanceof SyntaxError) {\n    return {\n      jsonrpc: \"2.0\",\n      id,\n      error: VoltA2AError.parseError(cause.message).toJsonRpcError(),\n    };\n  }\n  if (cause instanceof Error) {\n    return {\n      jsonrpc: \"2.0\",\n      id,\n      error: VoltA2AError.internal(cause.message).toJsonRpcError(),\n    };\n  }\n  return {\n    jsonrpc: \"2.0\",\n    id,\n    error: VoltA2AError.internal(\"Unknown error\", cause).toJsonRpcError(),\n  };\n}\n\nexport function isJsonRpcRequest(value: unknown): value is JsonRpcRequest {\n  if (!value || typeof value !== \"object\") {\n    return false;\n  }\n  const candidate = value as Partial<JsonRpcRequest>;\n  return candidate.jsonrpc === \"2.0\" && typeof candidate.method === \"string\";\n}\n","import type { A2AServerRegistry } from \"@voltagent/core\";\nimport type { Logger } from \"@voltagent/internal\";\n\nimport { lookupA2AServer } from \"./registry\";\nimport {\n  type A2ARequestContext,\n  type A2AServerLikeWithHandlers,\n  type AgentCard,\n  type JsonRpcHandlerResult,\n  type JsonRpcRequest,\n  VoltA2AError,\n  isJsonRpcRequest,\n  normalizeError,\n} from \"./types\";\n\nexport function parseJsonRpcRequest(payload: unknown): JsonRpcRequest {\n  if (!isJsonRpcRequest(payload)) {\n    throw VoltA2AError.invalidRequest(\"Body is not a valid JSON-RPC request\");\n  }\n\n  if (typeof payload.id === \"undefined\") {\n    throw VoltA2AError.invalidRequest(\"JSON-RPC request 'id' must be provided\");\n  }\n\n  return payload;\n}\n\nexport function resolveAgentCard(\n  registry: A2AServerRegistry<A2AServerLikeWithHandlers>,\n  serverId: string,\n  agentId: string,\n  context: A2ARequestContext = {},\n): AgentCard {\n  const { server } = lookupA2AServer(registry, serverId);\n  if (!server || typeof server.getAgentCard !== \"function\") {\n    throw VoltA2AError.invalidRequest(`A2A server '${serverId}' not available`);\n  }\n\n  return server.getAgentCard(agentId, context);\n}\n\nexport async function executeA2ARequest(params: {\n  registry: A2AServerRegistry<A2AServerLikeWithHandlers>;\n  serverId: string;\n  request: JsonRpcRequest;\n  context?: A2ARequestContext;\n  logger?: Logger;\n}): Promise<JsonRpcHandlerResult> {\n  const { registry, serverId, request, context = {}, logger } = params;\n  const { server } = lookupA2AServer(registry, serverId);\n\n  if (!server || typeof server.handleRequest !== \"function\") {\n    return normalizeError(\n      request.id ?? null,\n      VoltA2AError.invalidRequest(`A2A server '${serverId}' not available`),\n    );\n  }\n\n  try {\n    return await server.handleRequest(serverId, request, context);\n  } catch (error) {\n    logger?.error(\"A2A request failed\", {\n      error: error instanceof Error ? error.message : error,\n      serverId,\n    });\n    return normalizeError(request.id ?? null, error);\n  }\n}\n","/**\n * Framework-agnostic response types for server handlers\n */\n\nexport interface SuccessResponse<T = any> {\n  success: true;\n  data: T;\n}\n\nexport interface ErrorResponse {\n  success: false;\n  error: string;\n  httpStatus?: number;\n  code?: string;\n  name?: string;\n}\n\nexport type ApiResponse<T = any> = SuccessResponse<T> | ErrorResponse;\n\n// Stream handlers can return either a Response (AI SDK) or ReadableStream or ErrorResponse\nexport type StreamResponse = Response | ReadableStream | ErrorResponse;\n\n// Type guard to check if response is an error\nexport function isErrorResponse(response: any): response is ErrorResponse {\n  return (\n    response && typeof response === \"object\" && \"success\" in response && response.success === false\n  );\n}\n\n// Type guard to check if response is a success response\nexport function isSuccessResponse<T>(response: any): response is SuccessResponse<T> {\n  return (\n    response && typeof response === \"object\" && \"success\" in response && response.success === true\n  );\n}\n","import type { LogEntry, LogFilter } from \"@voltagent/internal\";\nimport type { LogHandlerResponse } from \"../handlers/log.handlers\";\nimport type { ApiResponse, ErrorResponse } from \"../types\";\n\ninterface LogResponseData {\n  success: true;\n  data: LogEntry[];\n  total: number;\n  query: LogFilter;\n}\n\n/**\n * Maps a log handler response to match OpenAPI schema expectations\n * Extracts nested data properties to root level\n */\nexport function mapLogResponse(\n  response: ApiResponse<LogHandlerResponse>,\n): LogResponseData | ErrorResponse {\n  if (!response.success) {\n    return response;\n  }\n\n  return {\n    success: true,\n    data: response.data.logs,\n    total: response.data.total,\n    query: response.data.query,\n  };\n}\n\n/**\n * Maps a generic handler response to framework-specific format\n * Can be extended for other response types as needed\n */\nexport function mapHandlerResponse(response: ApiResponse, type?: string) {\n  switch (type) {\n    case \"logs\":\n      return mapLogResponse(response);\n    default:\n      return response;\n  }\n}\n\n/**\n * Extracts HTTP status code from response\n */\nexport function getResponseStatus(response: ApiResponse): number {\n  return response.success ? 200 : 500;\n}\n"],"mappings":";;;;AAMA,SAAS,uBAAuB;AA2CzB,SAAS,kBAAkB,MAA0B,YAAY,cAAsB;AAC5F,SAAO,KAAK,QAAQ,MAAM,EAAE,UAAU,CAAC,KAAK,gBAAgB,EAAE,MAAM,EAAE,UAAU,CAAC;AACnF;AAFgB;;;ACfT,IAAM,eAAe;AAAA,EAC1B,YAAY;AAAA,IACV,QAAQ;AAAA,IACR,MAAM;AAAA,IACN,SAAS;AAAA,IACT,aACE;AAAA,IACF,MAAM,CAAC,kBAAkB;AAAA,IACzB,aAAa;AAAA,IACb,WAAW;AAAA,MACT,KAAK;AAAA,QACH,aAAa;AAAA,QACb,aAAa;AAAA,MACf;AAAA,MACA,KAAK;AAAA,QACH,aAAa;AAAA,QACb,aAAa;AAAA,MACf;AAAA,IACF;AAAA,EACF;AAAA,EACA,UAAU;AAAA,IACR,QAAQ;AAAA,IACR,MAAM;AAAA,IACN,SAAS;AAAA,IACT,aAAa;A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AClBf,SAAS,gBAAgB,UAA0C;AACxE,SACE,YAAY,OAAO,aAAa,YAAY,aAAa,YAAY,SAAS,YAAY;AAE9F;AAJgB;;;ACRT,SAAS,eACd,UACiC;AACjC,MAAI,CAAC,SAAS,SAAS;AACrB,WAAO;AAAA,EACT;AAEA,SAAO;AAAA,IACL,SAAS;AAAA,IACT,MAAM,SAAS,KAAK;AAAA,IACpB,OAAO,SAAS,KAAK;AAAA,IACrB,OAAO,SAAS,KAAK;AAAA,EACvB;AACF;AAbgB;","names":["z","convertJsonSchemaToZod","convertJsonSchemaToZodV3","z","convertJsonSchemaToZod","convertJsonSchemaToZodV3","safeStringify","safeStringify","result","formattedStates","safeStringify","safeStringify","safeStringify","generateId","safeStringify","generateId"]}