UNPKG

@copilotkit/runtime

Version:

<img src="https://github.com/user-attachments/assets/0a6b64d9-e193-4940-a3f6-60334ac34084" alt="banner" style="border-radius: 12px; border: 2px solid #d6d4fa;" />

132 lines (130 loc) 5.44 kB
import "reflect-metadata"; import { isIntelligenceRuntime, resolveAgents } from "../../core/runtime.mjs"; import { OpenGenerativeUIMiddleware } from "../../open-generative-ui-middleware.mjs"; import { INTELLIGENCE_USER_ID_HEADER } from "../../intelligence-platform/client.mjs"; import { extractForwardableHeaders } from "../header-utils.mjs"; import { resolveIntelligenceUser } from "./resolve-intelligence-user.mjs"; import { logger } from "@copilotkit/shared"; import { RunAgentInputSchema } from "@ag-ui/client"; import { A2UIMiddleware } from "@ag-ui/a2ui-middleware"; import { MCPAppsMiddleware } from "@ag-ui/mcp-apps-middleware"; import { MCPMiddleware } from "@ag-ui/mcp-middleware"; //#region src/v2/runtime/handlers/shared/agent-utils.ts async function cloneAgentForRequest(runtime, agentId, request) { const agents = await resolveAgents(runtime.agents, request); if (!agents[agentId]) return new Response(JSON.stringify({ error: "Agent not found", message: `Agent '${agentId}' does not exist` }), { status: 404, headers: { "Content-Type": "application/json" } }); return agents[agentId].clone(); } function configureAgentForRequest(params) { const { runtime, request, agentId } = params; const agent = params.agent; if (runtime.a2ui) { const { agents: targetAgents, ...a2uiOptions } = runtime.a2ui; if ((!targetAgents || targetAgents.includes(agentId)) && typeof agent.use === "function") agent.use(new A2UIMiddleware(a2uiOptions)); } if (runtime.mcpApps?.servers?.length) { const mcpServers = runtime.mcpApps.servers.filter((server) => !server.agentId || server.agentId === agentId).map((server) => { const mcpServer = { ...server }; delete mcpServer.agentId; return mcpServer; }); if (mcpServers.length > 0 && typeof agent.use === "function") agent.use(new MCPAppsMiddleware({ mcpServers })); } if (runtime.openGenerativeUI) { const config = runtime.openGenerativeUI; const targetAgents = typeof config === "object" ? config.agents : void 0; if ((!targetAgents || targetAgents.includes(agentId)) && typeof agent.use === "function") agent.use(new OpenGenerativeUIMiddleware()); } agent.headers = { ...agent.headers, ...extractForwardableHeaders(request) }; } /** * Attach the Intelligence platform's MCP tools to the agent run when * `CopilotKitIntelligence` was constructed with * `enableEnterpriseLearning: true`. Uses `@ag-ui/mcp-middleware`, so the * tools are available uniformly across agent frameworks (not just * `BuiltInAgent`). * * The middleware sits on a per-request agent clone, so the per-request * auth (Bearer apiKey + resolved user-id) is baked into the transport * headers at attach time. If user resolution fails, attachment is * skipped silently — the intelligence run handler will reject the * request with the same error. Note this means `identifyUser` is * resolved twice per learning-enabled run (here and in the run handler); * the callback is expected to be idempotent and side-effect-free. * * Intentionally split out from `configureAgentForRequest`: this is only * relevant to actual agent runs, not auxiliary flows like thread-name * generation (which has no need for MCP tools and shouldn't pay the * `listTools` round-trip). */ async function attachIntelligenceEnterpriseLearning(params) { const { runtime, request } = params; const agent = params.agent; if (!isIntelligenceRuntime(runtime) || !runtime.intelligence?.ɵisEnterpriseLearningEnabled?.()) return; if (typeof agent.use !== "function") { logger.warn("CopilotKitIntelligence.enableEnterpriseLearning is enabled, but the agent does not support middleware (no `.use()` method); Intelligence tools were not attached for this run."); return; } const userResult = await resolveIntelligenceUser({ runtime, request }); if (userResult instanceof Response) return; agent.use(new MCPMiddleware([{ type: "http", url: `${runtime.intelligence.ɵgetApiUrl()}/mcp`, serverId: "intelligence", headers: { Authorization: `Bearer ${runtime.intelligence.ɵgetApiKey()}`, [INTELLIGENCE_USER_ID_HEADER]: userResult.id } }])); } async function parseRunRequest(request) { try { const requestBody = await request.json(); return RunAgentInputSchema.parse(requestBody); } catch (error) { logger.error("Invalid run request body:", error); return new Response(JSON.stringify({ error: "Invalid request body", details: error instanceof Error ? error.message : String(error) }), { status: 400, headers: { "Content-Type": "application/json" } }); } } async function parseConnectRequest(request) { try { const requestBody = await request.json(); const input = RunAgentInputSchema.parse(requestBody); let lastSeenEventId = null; if ("lastSeenEventId" in requestBody && (typeof requestBody.lastSeenEventId === "string" || requestBody.lastSeenEventId === null)) lastSeenEventId = requestBody.lastSeenEventId ?? null; return { input, lastSeenEventId }; } catch (error) { logger.error("Invalid connect request body:", error); return new Response(JSON.stringify({ error: "Invalid request body", details: error instanceof Error ? error.message : String(error) }), { status: 400, headers: { "Content-Type": "application/json" } }); } } //#endregion export { attachIntelligenceEnterpriseLearning, cloneAgentForRequest, configureAgentForRequest, parseConnectRequest, parseRunRequest }; //# sourceMappingURL=agent-utils.mjs.map