{"version":3,"file":"agent-utils.cjs","names":["resolveAgents","A2UIMiddleware","MCPAppsMiddleware","OpenGenerativeUIMiddleware","extractForwardableHeaders","isIntelligenceRuntime","resolveIntelligenceUser","MCPMiddleware","INTELLIGENCE_USER_ID_HEADER","RunAgentInputSchema"],"sources":["../../../../../src/v2/runtime/handlers/shared/agent-utils.ts"],"sourcesContent":["import type { AbstractAgent, RunAgentInput } from \"@ag-ui/client\";\nimport { RunAgentInputSchema } from \"@ag-ui/client\";\nimport { A2UIMiddleware } from \"@ag-ui/a2ui-middleware\";\nimport { MCPAppsMiddleware } from \"@ag-ui/mcp-apps-middleware\";\nimport { MCPMiddleware } from \"@ag-ui/mcp-middleware\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { isIntelligenceRuntime, resolveAgents } from \"../../core/runtime\";\nimport { OpenGenerativeUIMiddleware } from \"../../open-generative-ui-middleware\";\nimport { INTELLIGENCE_USER_ID_HEADER } from \"../../intelligence-platform/client\";\nimport { extractForwardableHeaders } from \"../header-utils\";\nimport { resolveIntelligenceUser } from \"./resolve-intelligence-user\";\nimport { logger } from \"@copilotkit/shared\";\n\ntype MiddlewareCapableAgent = AbstractAgent & {\n  use?: (middleware: unknown) => void;\n  headers?: Record<string, string>;\n};\n\nexport interface RunAgentParameters {\n  request: Request;\n  runtime: CopilotRuntimeLike;\n  agentId: string;\n}\n\nexport interface ConnectRequestBody extends RunAgentInput {\n  lastSeenEventId?: string | null;\n}\n\nexport async function cloneAgentForRequest(\n  runtime: CopilotRuntimeLike,\n  agentId: string,\n  request?: Request,\n): Promise<AbstractAgent | Response> {\n  const agents = await resolveAgents(runtime.agents, request);\n\n  if (!agents[agentId]) {\n    return new Response(\n      JSON.stringify({\n        error: \"Agent not found\",\n        message: `Agent '${agentId}' does not exist`,\n      }),\n      {\n        status: 404,\n        headers: { \"Content-Type\": \"application/json\" },\n      },\n    );\n  }\n\n  return (agents[agentId] as AbstractAgent).clone() as AbstractAgent;\n}\n\nexport function configureAgentForRequest(params: {\n  runtime: CopilotRuntimeLike;\n  request: Request;\n  agentId: string;\n  agent: AbstractAgent;\n}): void {\n  const { runtime, request, agentId } = params;\n  const agent = params.agent as MiddlewareCapableAgent;\n\n  if (runtime.a2ui) {\n    const { agents: targetAgents, ...a2uiOptions } = runtime.a2ui;\n    const shouldApply = !targetAgents || targetAgents.includes(agentId);\n    if (shouldApply && typeof agent.use === \"function\") {\n      agent.use(new A2UIMiddleware(a2uiOptions));\n    }\n  }\n\n  if (runtime.mcpApps?.servers?.length) {\n    const mcpServers = runtime.mcpApps.servers\n      .filter((server) => !server.agentId || server.agentId === agentId)\n      .map((server) => {\n        const mcpServer = { ...server };\n        delete mcpServer.agentId;\n        return mcpServer;\n      });\n\n    if (mcpServers.length > 0 && typeof agent.use === \"function\") {\n      agent.use(new MCPAppsMiddleware({ mcpServers }));\n    }\n  }\n\n  if (runtime.openGenerativeUI) {\n    const config = runtime.openGenerativeUI;\n    const targetAgents = typeof config === \"object\" ? config.agents : undefined;\n    const shouldApply = !targetAgents || targetAgents.includes(agentId);\n    if (shouldApply && typeof agent.use === \"function\") {\n      agent.use(new OpenGenerativeUIMiddleware());\n    }\n  }\n\n  agent.headers = {\n    ...agent.headers,\n    ...extractForwardableHeaders(request),\n  };\n}\n\n/**\n * Attach the Intelligence platform's MCP tools to the agent run when\n * `CopilotKitIntelligence` was constructed with\n * `enableEnterpriseLearning: true`. Uses `@ag-ui/mcp-middleware`, so the\n * tools are available uniformly across agent frameworks (not just\n * `BuiltInAgent`).\n *\n * The middleware sits on a per-request agent clone, so the per-request\n * auth (Bearer apiKey + resolved user-id) is baked into the transport\n * headers at attach time. If user resolution fails, attachment is\n * skipped silently — the intelligence run handler will reject the\n * request with the same error. Note this means `identifyUser` is\n * resolved twice per learning-enabled run (here and in the run handler);\n * the callback is expected to be idempotent and side-effect-free.\n *\n * Intentionally split out from `configureAgentForRequest`: this is only\n * relevant to actual agent runs, not auxiliary flows like thread-name\n * generation (which has no need for MCP tools and shouldn't pay the\n * `listTools` round-trip).\n */\nexport async function attachIntelligenceEnterpriseLearning(params: {\n  runtime: CopilotRuntimeLike;\n  request: Request;\n  agent: AbstractAgent;\n}): Promise<void> {\n  const { runtime, request } = params;\n  const agent = params.agent as MiddlewareCapableAgent;\n\n  if (\n    !isIntelligenceRuntime(runtime) ||\n    !runtime.intelligence?.ɵisEnterpriseLearningEnabled?.()\n  ) {\n    return;\n  }\n\n  // Enterprise learning is enabled, but this agent's framework can't take\n  // middleware — surface it rather than silently shipping a run with none\n  // of the tools the operator opted into.\n  if (typeof agent.use !== \"function\") {\n    logger.warn(\n      \"CopilotKitIntelligence.enableEnterpriseLearning is enabled, but the agent \" +\n        \"does not support middleware (no `.use()` method); Intelligence tools were \" +\n        \"not attached for this run.\",\n    );\n    return;\n  }\n\n  const userResult = await resolveIntelligenceUser({ runtime, request });\n  if (userResult instanceof Response) return;\n\n  agent.use(\n    new MCPMiddleware([\n      {\n        type: \"http\",\n        url: `${runtime.intelligence.ɵgetApiUrl()}/mcp`,\n        serverId: \"intelligence\",\n        headers: {\n          Authorization: `Bearer ${runtime.intelligence.ɵgetApiKey()}`,\n          [INTELLIGENCE_USER_ID_HEADER]: userResult.id,\n        },\n      },\n    ]),\n  );\n}\n\nexport async function parseRunRequest(\n  request: Request,\n): Promise<RunAgentInput | Response> {\n  try {\n    const requestBody = await request.json();\n    return RunAgentInputSchema.parse(requestBody);\n  } catch (error) {\n    logger.error(\"Invalid run request body:\", error);\n    return new Response(\n      JSON.stringify({\n        error: \"Invalid request body\",\n        details: error instanceof Error ? error.message : String(error),\n      }),\n      {\n        status: 400,\n        headers: { \"Content-Type\": \"application/json\" },\n      },\n    );\n  }\n}\n\nexport async function parseConnectRequest(request: Request): Promise<\n  | Response\n  | {\n      input: RunAgentInput;\n      lastSeenEventId: string | null;\n    }\n> {\n  try {\n    const requestBody = await request.json();\n    const input = RunAgentInputSchema.parse(requestBody);\n    let lastSeenEventId: string | null = null;\n\n    if (\n      \"lastSeenEventId\" in (requestBody as Record<string, unknown>) &&\n      (typeof (requestBody as Record<string, unknown>).lastSeenEventId ===\n        \"string\" ||\n        (requestBody as Record<string, unknown>).lastSeenEventId === null)\n    ) {\n      lastSeenEventId =\n        (requestBody as ConnectRequestBody).lastSeenEventId ?? null;\n    }\n\n    return { input, lastSeenEventId };\n  } catch (error) {\n    logger.error(\"Invalid connect request body:\", error);\n    return new Response(\n      JSON.stringify({\n        error: \"Invalid request body\",\n        details: error instanceof Error ? error.message : String(error),\n      }),\n      {\n        status: 400,\n        headers: { \"Content-Type\": \"application/json\" },\n      },\n    );\n  }\n}\n"],"mappings":";;;;;;;;;;;;;;AA4BA,eAAsB,qBACpB,SACA,SACA,SACmC;CACnC,MAAM,SAAS,MAAMA,gCAAc,QAAQ,QAAQ,QAAQ;AAE3D,KAAI,CAAC,OAAO,SACV,QAAO,IAAI,SACT,KAAK,UAAU;EACb,OAAO;EACP,SAAS,UAAU,QAAQ;EAC5B,CAAC,EACF;EACE,QAAQ;EACR,SAAS,EAAE,gBAAgB,oBAAoB;EAChD,CACF;AAGH,QAAQ,OAAO,SAA2B,OAAO;;AAGnD,SAAgB,yBAAyB,QAKhC;CACP,MAAM,EAAE,SAAS,SAAS,YAAY;CACtC,MAAM,QAAQ,OAAO;AAErB,KAAI,QAAQ,MAAM;EAChB,MAAM,EAAE,QAAQ,cAAc,GAAG,gBAAgB,QAAQ;AAEzD,OADoB,CAAC,gBAAgB,aAAa,SAAS,QAAQ,KAChD,OAAO,MAAM,QAAQ,WACtC,OAAM,IAAI,IAAIC,sCAAe,YAAY,CAAC;;AAI9C,KAAI,QAAQ,SAAS,SAAS,QAAQ;EACpC,MAAM,aAAa,QAAQ,QAAQ,QAChC,QAAQ,WAAW,CAAC,OAAO,WAAW,OAAO,YAAY,QAAQ,CACjE,KAAK,WAAW;GACf,MAAM,YAAY,EAAE,GAAG,QAAQ;AAC/B,UAAO,UAAU;AACjB,UAAO;IACP;AAEJ,MAAI,WAAW,SAA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