@copilotkit/runtime 1.64.2 → 1.64.3-canary.1785623356
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +35 -0
- package/dist/package.cjs +1 -1
- package/dist/runtime/package.mjs +1 -1
- package/dist/v2/index.d.cts +2 -2
- package/dist/v2/index.d.mts +2 -2
- package/dist/v2/runtime/core/channel-activation-config.cjs +6 -14
- package/dist/v2/runtime/core/channel-activation-config.cjs.map +1 -1
- package/dist/v2/runtime/core/channel-activation-config.d.cts +0 -8
- package/dist/v2/runtime/core/channel-activation-config.d.cts.map +1 -1
- package/dist/v2/runtime/core/channel-activation-config.d.mts +0 -8
- package/dist/v2/runtime/core/channel-activation-config.d.mts.map +1 -1
- package/dist/v2/runtime/core/channel-activation-config.mjs +6 -14
- package/dist/v2/runtime/core/channel-activation-config.mjs.map +1 -1
- package/dist/v2/runtime/core/channel-manager.cjs +62 -107
- package/dist/v2/runtime/core/channel-manager.cjs.map +1 -1
- package/dist/v2/runtime/core/channel-manager.d.cts +4 -15
- package/dist/v2/runtime/core/channel-manager.d.cts.map +1 -1
- package/dist/v2/runtime/core/channel-manager.d.mts +4 -15
- package/dist/v2/runtime/core/channel-manager.d.mts.map +1 -1
- package/dist/v2/runtime/core/channel-manager.mjs +62 -107
- package/dist/v2/runtime/core/channel-manager.mjs.map +1 -1
- package/dist/v2/runtime/core/fetch-handler.cjs +1 -0
- package/dist/v2/runtime/core/fetch-handler.cjs.map +1 -1
- package/dist/v2/runtime/core/fetch-handler.mjs +1 -0
- package/dist/v2/runtime/core/fetch-handler.mjs.map +1 -1
- package/dist/v2/runtime/core/runtime.cjs +16 -4
- package/dist/v2/runtime/core/runtime.cjs.map +1 -1
- package/dist/v2/runtime/core/runtime.d.cts +43 -17
- package/dist/v2/runtime/core/runtime.d.cts.map +1 -1
- package/dist/v2/runtime/core/runtime.d.mts +43 -17
- package/dist/v2/runtime/core/runtime.d.mts.map +1 -1
- package/dist/v2/runtime/core/runtime.mjs +16 -4
- package/dist/v2/runtime/core/runtime.mjs.map +1 -1
- package/dist/v2/runtime/handlers/get-runtime-info.cjs +9 -8
- package/dist/v2/runtime/handlers/get-runtime-info.cjs.map +1 -1
- package/dist/v2/runtime/handlers/get-runtime-info.mjs +9 -8
- package/dist/v2/runtime/handlers/get-runtime-info.mjs.map +1 -1
- package/dist/v2/runtime/handlers/handle-run.cjs +2 -1
- package/dist/v2/runtime/handlers/handle-run.cjs.map +1 -1
- package/dist/v2/runtime/handlers/handle-run.mjs +2 -1
- package/dist/v2/runtime/handlers/handle-run.mjs.map +1 -1
- package/dist/v2/runtime/handlers/intelligence/memories.cjs +37 -38
- package/dist/v2/runtime/handlers/intelligence/memories.cjs.map +1 -1
- package/dist/v2/runtime/handlers/intelligence/memories.mjs +37 -38
- package/dist/v2/runtime/handlers/intelligence/memories.mjs.map +1 -1
- package/dist/v2/runtime/handlers/shared/agent-utils.cjs +11 -5
- package/dist/v2/runtime/handlers/shared/agent-utils.cjs.map +1 -1
- package/dist/v2/runtime/handlers/shared/agent-utils.mjs +11 -5
- package/dist/v2/runtime/handlers/shared/agent-utils.mjs.map +1 -1
- package/dist/v2/runtime/handlers/shared/memory-policy.cjs +41 -0
- package/dist/v2/runtime/handlers/shared/memory-policy.cjs.map +1 -0
- package/dist/v2/runtime/handlers/shared/memory-policy.mjs +41 -0
- package/dist/v2/runtime/handlers/shared/memory-policy.mjs.map +1 -0
- package/dist/v2/runtime/handlers/shared/resolve-intelligence-user.cjs +8 -0
- package/dist/v2/runtime/handlers/shared/resolve-intelligence-user.cjs.map +1 -1
- package/dist/v2/runtime/handlers/shared/resolve-intelligence-user.mjs +8 -0
- package/dist/v2/runtime/handlers/shared/resolve-intelligence-user.mjs.map +1 -1
- package/dist/v2/runtime/index.d.cts +1 -1
- package/dist/v2/runtime/index.d.mts +1 -1
- package/dist/v2/runtime/intelligence-platform/client.cjs +13 -6
- package/dist/v2/runtime/intelligence-platform/client.cjs.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.d.cts +32 -2
- package/dist/v2/runtime/intelligence-platform/client.d.cts.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.d.mts +32 -2
- package/dist/v2/runtime/intelligence-platform/client.d.mts.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.mjs +13 -7
- package/dist/v2/runtime/intelligence-platform/client.mjs.map +1 -1
- package/package.json +6 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"memories.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/intelligence/memories.ts"],"sourcesContent":["import type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { logger } from \"@copilotkit/shared\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { PlatformRequestError } from \"../../intelligence-platform/client\";\n\ninterface MemoriesHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface MemoryMutationParams extends MemoriesHandlerParams {\n memoryId: string;\n}\n\nconst MISSING_INTELLIGENCE_MESSAGE =\n \"Missing CopilotKitIntelligence configuration. Memory operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\";\n\n/** Allowed `kind` vocabulary the platform's memory endpoints accept. */\nconst MEMORY_KINDS: ReadonlySet<string> = new Set([\n \"topical\",\n \"episodic\",\n \"operational\",\n]);\n/** Allowed `scope` vocabulary the platform's memory endpoints accept. */\nconst MEMORY_SCOPES: ReadonlySet<string> = new Set([\"user\", \"project\"]);\n\n/**\n * Maps a thrown error to a `Response`.\n *\n * For a {@link PlatformRequestError}, forward only client-actionable **4xx**\n * statuses verbatim (e.g. 404 missing/wrong-scope memory, 409 conflict, 422\n * unprocessable) so a `useMemories` consumer can branch on them — a flat 500\n * would erase that distinction. A platform **5xx** (or any non-4xx / malformed\n * status) means the runtime is healthy but its dependency failed, so it surfaces\n * as `502 Bad Gateway` rather than echoing the upstream status as if the runtime\n * itself broke — and this also avoids a `new Response(..., { status })`\n * `RangeError` on an out-of-range status. Non-platform throws stay 500.\n */\nfunction memoryErrorResponse(error: unknown, message: string): Response {\n if (error instanceof PlatformRequestError) {\n const { status } = error;\n if (Number.isInteger(status) && status >= 400 && status <= 499) {\n return errorResponse(message, status);\n }\n return errorResponse(message, 502);\n }\n return errorResponse(message, 500);\n}\n\nasync function parseJsonBody(\n request: Request,\n): Promise<Record<string, unknown> | Response> {\n try {\n return (await request.json()) as Record<string, unknown>;\n } catch (error) {\n logger.error({ err: error }, \"Malformed JSON in memory request body\");\n return errorResponse(\"Invalid request body\", 400);\n }\n}\n\n/**\n * Extracts and validates the create/supersede body fields the platform's\n * memory endpoints require. Returns a `Response` (400) on invalid input.\n */\nfunction parseMemoryBody(body: Record<string, unknown>):\n | {\n content: string;\n kind: string;\n scope?: string;\n sourceThreadIds?: string[];\n }\n | Response {\n const { content, kind, scope, sourceThreadIds } = body;\n if (typeof content !== \"string\" || typeof kind !== \"string\") {\n return errorResponse(\"Memory requires string `content` and `kind`\", 400);\n }\n // `kind` must be one of the platform's known kinds. Reject an out-of-vocabulary\n // value here rather than forwarding it for the platform to reject.\n if (!MEMORY_KINDS.has(kind)) {\n return errorResponse(\n \"Memory `kind` must be one of: topical, episodic, operational\",\n 400,\n );\n }\n // `scope` is optional: when omitted the platform applies its default\n // (`\"user\"`). Only reject a present-but-wrong-typed scope.\n if (scope !== undefined && typeof scope !== \"string\") {\n return errorResponse(\"Memory `scope` must be a string when provided\", 400);\n }\n // When `scope` is present, it must be one of the known scopes.\n if (typeof scope === \"string\" && !MEMORY_SCOPES.has(scope)) {\n return errorResponse(\"Memory `scope` must be one of: user, project\", 400);\n }\n // `sourceThreadIds` is optional, but when present it must be a string array.\n // Validate every element so non-string ids are not forwarded to the platform.\n if (\n sourceThreadIds !== undefined &&\n (!Array.isArray(sourceThreadIds) ||\n !sourceThreadIds.every((id) => typeof id === \"string\"))\n ) {\n return errorResponse(\n \"Memory `sourceThreadIds` must be an array of strings when provided\",\n 400,\n );\n }\n return {\n content,\n kind,\n ...(typeof scope === \"string\" ? { scope } : {}),\n ...(Array.isArray(sourceThreadIds)\n ? { sourceThreadIds: sourceThreadIds as string[] }\n : {}),\n // `sourceThreadIds` elements are validated as strings above; the cast is safe.\n };\n}\n\n/**\n * Validates the recall body: `query` required non-empty string (trimmed);\n * `limit` optional finite positive integer; `scope` optional and in the known\n * scopes. Returns a 400 Response on invalid input. The returned `query` is the\n * trimmed value so a whitespace-padded query is never forwarded to the platform.\n */\nfunction parseRecallBody(\n body: Record<string, unknown>,\n): { query: string; limit?: number; scope?: string } | Response {\n const { query, limit, scope } = body;\n // Trim before the emptiness check so whitespace-only queries (e.g. \" \")\n // are rejected rather than forwarded as a useless query to the platform.\n const trimmedQuery = typeof query === \"string\" ? query.trim() : query;\n if (typeof trimmedQuery !== \"string\" || trimmedQuery.length === 0) {\n return errorResponse(\"Recall requires a non-empty string `query`\", 400);\n }\n // When provided, `limit` must be a finite positive integer. `Number.isInteger`\n // already rejects NaN, Infinity, and fractions (NaN/Infinity would otherwise\n // JSON-serialize to `null` and silently corrupt the forwarded request);\n // the `> 0` guard rejects zero and negatives.\n if (\n limit !== undefined &&\n !(typeof limit === \"number\" && Number.isInteger(limit) && limit > 0)\n ) {\n return errorResponse(\"Recall `limit` must be a positive integer\", 400);\n }\n if (scope !== undefined && typeof scope !== \"string\") {\n return errorResponse(\"Recall `scope` must be a string when provided\", 400);\n }\n if (typeof scope === \"string\" && !MEMORY_SCOPES.has(scope)) {\n return errorResponse(\"Recall `scope` must be one of: user, project\", 400);\n }\n return {\n query: trimmedQuery,\n ...(typeof limit === \"number\" ? { limit } : {}),\n ...(typeof scope === \"string\" ? { scope } : {}),\n };\n}\n\n/**\n * Lists the resolved user's long-term memories via the Intelligence platform.\n *\n * Mirrors {@link handleListThreads}: requires a `CopilotKitIntelligence`\n * runtime, resolves the user with `identifyUser` (never trusting a\n * client-supplied id), and proxies to the platform's `GET /api/memories`\n * with the project API key + resolved user. The `?includeInvalidated=true`\n * query is forwarded so callers can opt into retired rows. The response is\n * the platform's `{ memories }` envelope, which the client memory store\n * consumes directly.\n */\nexport async function handleListMemories({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (isIntelligenceRuntime(runtime)) {\n try {\n const url = new URL(request.url);\n const includeInvalidated =\n url.searchParams.get(\"includeInvalidated\") === \"true\";\n\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.listMemories({\n userId: user.id,\n ...(includeInvalidated ? { includeInvalidated: true } : {}),\n });\n\n // The client memory store consumes the `{ memories: [...] }` envelope\n // directly. Assert the shape before forwarding so a platform contract\n // violation surfaces as a clear 502 (the runtime is healthy but its\n // dependency returned the wrong shape) instead of a 200 the client will\n // choke on.\n if (\n data == null ||\n typeof data !== \"object\" ||\n !Array.isArray((data as { memories?: unknown }).memories)\n ) {\n logger.error(\n { data },\n \"listMemories: platform returned a response without a `memories` array\",\n );\n return errorResponse(\n \"Memory platform returned an invalid list response\",\n 502,\n );\n }\n\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error listing memories\");\n return memoryErrorResponse(error, \"Failed to list memories\");\n }\n }\n\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n}\n\n/**\n * Semantically recalls the resolved user's memories via the platform (`POST\n * /api/memories/recall`, hybrid RAG). Mirrors {@link handleListMemories}:\n * requires a `CopilotKitIntelligence` runtime, resolves the user with\n * `identifyUser` (never a client-supplied id), proxies with the project API\n * key + resolved user. Body `{ query, limit?, scope? }`; response `{ memories }`,\n * each optionally carrying `score`.\n */\nexport async function handleRecallMemories({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n const fields = parseRecallBody(body);\n if (isHandlerResponse(fields)) return fields;\n\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.recallMemories({\n userId: user.id,\n ...fields,\n });\n\n if (\n data == null ||\n typeof data !== \"object\" ||\n !Array.isArray((data as { memories?: unknown }).memories)\n ) {\n logger.error(\n { data },\n \"recallMemories: platform returned a response without a `memories` array\",\n );\n return errorResponse(\n \"Memory platform returned an invalid recall response\",\n 502,\n );\n }\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error recalling memories\");\n return memoryErrorResponse(error, \"Failed to recall memories\");\n }\n}\n\n/**\n * Mints memory-realtime join credentials (platform `POST\n * /api/memories/subscribe`). Mirrors {@link handleSubscribeToThreads}: requires\n * a `CopilotKitIntelligence` runtime and resolves the user with `identifyUser`\n * (never a client-supplied id). Returns `{ joinToken, joinCode }` — memory needs\n * the `joinCode` here (unlike threads, where it rides the thread-list response)\n * because the client builds the `user_meta:memories:<joinCode>` channel topic\n * from it.\n *\n * When the platform also resolves a project scope, the response additionally\n * carries `projectJoinToken` / `projectJoinCode`, which the client uses to open\n * a second `project_meta:memories:<projectJoinCode>` channel. These are\n * optional: absent project scope → both fields are omitted (silent-degrade\n * contract; the client opens only the user channel).\n */\nexport async function handleSubscribeToMemories({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const credentials = await runtime.intelligence.ɵsubscribeToMemories({\n userId: user.id,\n });\n\n return Response.json({\n joinToken: credentials.joinToken,\n joinCode: credentials.joinCode,\n // Project-scoped credentials ride along only when the platform minted\n // them; omit both when absent (silent-degrade contract).\n ...(credentials.projectJoinToken !== undefined\n ? { projectJoinToken: credentials.projectJoinToken }\n : {}),\n ...(credentials.projectJoinCode !== undefined\n ? { projectJoinCode: credentials.projectJoinCode }\n : {}),\n });\n } catch (error) {\n logger.error({ err: error }, \"Error subscribing to memories\");\n return memoryErrorResponse(error, \"Failed to subscribe to memories\");\n }\n }\n\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n}\n\n/**\n * Creates a memory for the resolved user (platform `POST /api/memories`).\n * Identity comes from `identifyUser`, never the request body. Returns 201\n * with the stored memory (the client store applies it server-authoritatively).\n */\nexport async function handleCreateMemory({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n const fields = parseMemoryBody(body);\n if (isHandlerResponse(fields)) return fields;\n\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.createMemory({\n userId: user.id,\n ...fields,\n });\n return Response.json(data, { status: 201 });\n } catch (error) {\n logger.error({ err: error }, \"Error creating memory\");\n return memoryErrorResponse(error, \"Failed to create memory\");\n }\n}\n\n/**\n * Supersedes a memory (platform `PATCH /api/memories/:id`): retires `:id` and\n * inserts the new content atomically; the response carries `retiredId`.\n */\nexport async function handleUpdateMemory({\n runtime,\n request,\n memoryId,\n}: MemoryMutationParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n const fields = parseMemoryBody(body);\n if (isHandlerResponse(fields)) return fields;\n\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.updateMemory({\n userId: user.id,\n id: memoryId,\n ...fields,\n });\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error updating memory\");\n return memoryErrorResponse(error, \"Failed to update memory\");\n }\n}\n\n/**\n * Retires (forgets) a memory (platform `DELETE /api/memories/:id`). Non-lossy\n * on the platform side; returns 204.\n */\nexport async function handleRemoveMemory({\n runtime,\n request,\n memoryId,\n}: MemoryMutationParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n await runtime.intelligence.removeMemory({ userId: user.id, id: memoryId });\n return new Response(null, { status: 204 });\n } catch (error) {\n logger.error({ err: error }, \"Error removing memory\");\n return memoryErrorResponse(error, \"Failed to remove memory\");\n }\n}\n"],"mappings":";;;;;;;;AAgBA,MAAM,+BACJ;;AAGF,MAAM,eAAoC,IAAI,IAAI;CAChD;CACA;CACA;CACD,CAAC;;AAEF,MAAM,gBAAqC,IAAI,IAAI,CAAC,QAAQ,UAAU,CAAC;;;;;;;;;;;;;AAcvE,SAAS,oBAAoB,OAAgB,SAA2B;AACtE,KAAI,iBAAiB,sBAAsB;EACzC,MAAM,EAAE,WAAW;AACnB,MAAI,OAAO,UAAU,OAAO,IAAI,UAAU,OAAO,UAAU,IACzD,QAAO,cAAc,SAAS,OAAO;AAEvC,SAAO,cAAc,SAAS,IAAI;;AAEpC,QAAO,cAAc,SAAS,IAAI;;AAGpC,eAAe,cACb,SAC6C;AAC7C,KAAI;AACF,SAAQ,MAAM,QAAQ,MAAM;UACrB,OAAO;AACd,SAAO,MAAM,EAAE,KAAK,OAAO,EAAE,wCAAwC;AACrE,SAAO,cAAc,wBAAwB,IAAI;;;;;;;AAQrD,SAAS,gBAAgB,MAOZ;CACX,MAAM,EAAE,SAAS,MAAM,OAAO,oBAAoB;AAClD,KAAI,OAAO,YAAY,YAAY,OAAO,SAAS,SACjD,QAAO,cAAc,+CAA+C,IAAI;AAI1E,KAAI,CAAC,aAAa,IAAI,KAAK,CACzB,QAAO,cACL,gEACA,IACD;AAIH,KAAI,UAAU,UAAa,OAAO,UAAU,SAC1C,QAAO,cAAc,iDAAiD,IA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A,YAC0C;AAC1C,KAAI,CAAC,sBAAsB,QAAQ,CACjC,QAAO,cAAc,8BAA8B,IAAI;AAEzD,KAAI;EACF,MAAM,OAAO,MAAM,cAAc,QAAQ;AACzC,MAAI,kBAAkB,KAAK,CAAE,QAAO;EACpC,MAAM,SAAS,gBAAgB,KAAK;AACpC,MAAI,kBAAkB,OAAO,CAAE,QAAO;EAEtC,MAAM,OAAO,MAAM,wBAAwB;GAAE;GAAS;GAAS,CAAC;AAChE,MAAI,kBAAkB,KAAK,CAAE,QAAO;EAEpC,MAAM,OAAO,MAAM,QAAQ,aAAa,aAAa;GACnD,QAAQ,KAAK;GACb,IAAI;GACJ,GAAG;GACJ,CAAC;AACF,SAAO,SAAS,KAAK,KAAK;UACnB,OAAO;AACd,SAAO,MAAM,EAAE,KAAK,OAAO,EAAE,wBAAwB;AACrD,SAAO,oBAAoB,OAAO,0BAA0B;;;;;;;AAQhE,eAAsB,mBAAmB,EACvC,SACA,SACA,YAC0C;AAC1C,KAAI,CAAC,sBAAsB,QAAQ,CACjC,QAAO,cAAc,8BAA8B,IAAI;AAEzD,KAAI;EACF,MAAM,OAAO,MAAM,wBAAwB;GAAE;GAAS;GAAS,CAAC;AAChE,MAAI,kBAAkB,KAAK,CAAE,QAAO;AAEpC,QAAM,QAAQ,aAAa,aAAa;GAAE,QAAQ,KAAK;GAAI,IAAI;GAAU,CAAC;AAC1E,SAAO,IAAI,SAAS,MAAM,EAAE,QAAQ,KAAK,CAAC;UACnC,OAAO;AACd,SAAO,MAAM,EAAE,KAAK,OAAO,EAAE,wBAAwB;AACrD,SAAO,oBAAoB,OAAO,0BAA0B"}
|
|
1
|
+
{"version":3,"file":"memories.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/intelligence/memories.ts"],"sourcesContent":["import type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { logger } from \"@copilotkit/shared\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { resolveWebMemory } from \"../shared/memory-policy\";\nimport { PlatformRequestError } from \"../../intelligence-platform/client\";\n\ninterface MemoriesHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface MemoryMutationParams extends MemoriesHandlerParams {\n memoryId: string;\n}\n\nasync function resolveClientMemory(\n runtime: CopilotIntelligenceRuntimeLike,\n request: Request,\n) {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n return resolveWebMemory(runtime, request, user, \"client\");\n}\n\nconst MISSING_INTELLIGENCE_MESSAGE =\n \"Missing CopilotKitIntelligence configuration. Memory operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\";\n\n/** Allowed `kind` vocabulary the platform's memory endpoints accept. */\nconst MEMORY_KINDS: ReadonlySet<string> = new Set([\n \"topical\",\n \"episodic\",\n \"operational\",\n]);\n/** Allowed `scope` vocabulary the platform's memory endpoints accept. */\nconst MEMORY_SCOPES: ReadonlySet<string> = new Set([\"user\", \"project\"]);\n\n/**\n * Maps a thrown error to a `Response`.\n *\n * For a {@link PlatformRequestError}, forward only client-actionable **4xx**\n * statuses verbatim (e.g. 404 missing/wrong-scope memory, 409 conflict, 422\n * unprocessable) so a `useMemories` consumer can branch on them — a flat 500\n * would erase that distinction. A platform **5xx** (or any non-4xx / malformed\n * status) means the runtime is healthy but its dependency failed, so it surfaces\n * as `502 Bad Gateway` rather than echoing the upstream status as if the runtime\n * itself broke — and this also avoids a `new Response(..., { status })`\n * `RangeError` on an out-of-range status. Non-platform throws stay 500.\n */\nfunction memoryErrorResponse(error: unknown, message: string): Response {\n if (error instanceof PlatformRequestError) {\n const { status } = error;\n if (Number.isInteger(status) && status >= 400 && status <= 499) {\n return errorResponse(message, status);\n }\n return errorResponse(message, 502);\n }\n return errorResponse(message, 500);\n}\n\nasync function parseJsonBody(\n request: Request,\n): Promise<Record<string, unknown> | Response> {\n try {\n return (await request.json()) as Record<string, unknown>;\n } catch (error) {\n logger.error({ err: error }, \"Malformed JSON in memory request body\");\n return errorResponse(\"Invalid request body\", 400);\n }\n}\n\n/**\n * Extracts and validates the create/supersede body fields the platform's\n * memory endpoints require. Returns a `Response` (400) on invalid input.\n */\nfunction parseMemoryBody(body: Record<string, unknown>):\n | {\n content: string;\n kind: string;\n scope?: string;\n sourceThreadIds?: string[];\n }\n | Response {\n const { content, kind, scope, sourceThreadIds } = body;\n if (typeof content !== \"string\" || typeof kind !== \"string\") {\n return errorResponse(\"Memory requires string `content` and `kind`\", 400);\n }\n // `kind` must be one of the platform's known kinds. Reject an out-of-vocabulary\n // value here rather than forwarding it for the platform to reject.\n if (!MEMORY_KINDS.has(kind)) {\n return errorResponse(\n \"Memory `kind` must be one of: topical, episodic, operational\",\n 400,\n );\n }\n // `scope` is optional: when omitted the platform applies its default\n // (`\"user\"`). Only reject a present-but-wrong-typed scope.\n if (scope !== undefined && typeof scope !== \"string\") {\n return errorResponse(\"Memory `scope` must be a string when provided\", 400);\n }\n // When `scope` is present, it must be one of the known scopes.\n if (typeof scope === \"string\" && !MEMORY_SCOPES.has(scope)) {\n return errorResponse(\"Memory `scope` must be one of: user, project\", 400);\n }\n // `sourceThreadIds` is optional, but when present it must be a string array.\n // Validate every element so non-string ids are not forwarded to the platform.\n if (\n sourceThreadIds !== undefined &&\n (!Array.isArray(sourceThreadIds) ||\n !sourceThreadIds.every((id) => typeof id === \"string\"))\n ) {\n return errorResponse(\n \"Memory `sourceThreadIds` must be an array of strings when provided\",\n 400,\n );\n }\n return {\n content,\n kind,\n ...(typeof scope === \"string\" ? { scope } : {}),\n ...(Array.isArray(sourceThreadIds)\n ? { sourceThreadIds: sourceThreadIds as string[] }\n : {}),\n // `sourceThreadIds` elements are validated as strings above; the cast is safe.\n };\n}\n\n/**\n * Validates the recall body: `query` required non-empty string (trimmed);\n * `limit` optional finite positive integer; `scope` optional and in the known\n * scopes. Returns a 400 Response on invalid input. The returned `query` is the\n * trimmed value so a whitespace-padded query is never forwarded to the platform.\n */\nfunction parseRecallBody(\n body: Record<string, unknown>,\n): { query: string; limit?: number; scope?: string } | Response {\n const { query, limit, scope } = body;\n // Trim before the emptiness check so whitespace-only queries (e.g. \" \")\n // are rejected rather than forwarded as a useless query to the platform.\n const trimmedQuery = typeof query === \"string\" ? query.trim() : query;\n if (typeof trimmedQuery !== \"string\" || trimmedQuery.length === 0) {\n return errorResponse(\"Recall requires a non-empty string `query`\", 400);\n }\n // When provided, `limit` must be a finite positive integer. `Number.isInteger`\n // already rejects NaN, Infinity, and fractions (NaN/Infinity would otherwise\n // JSON-serialize to `null` and silently corrupt the forwarded request);\n // the `> 0` guard rejects zero and negatives.\n if (\n limit !== undefined &&\n !(typeof limit === \"number\" && Number.isInteger(limit) && limit > 0)\n ) {\n return errorResponse(\"Recall `limit` must be a positive integer\", 400);\n }\n if (scope !== undefined && typeof scope !== \"string\") {\n return errorResponse(\"Recall `scope` must be a string when provided\", 400);\n }\n if (typeof scope === \"string\" && !MEMORY_SCOPES.has(scope)) {\n return errorResponse(\"Recall `scope` must be one of: user, project\", 400);\n }\n return {\n query: trimmedQuery,\n ...(typeof limit === \"number\" ? { limit } : {}),\n ...(typeof scope === \"string\" ? { scope } : {}),\n };\n}\n\n/**\n * Lists the resolved user's long-term memories via the Intelligence platform.\n *\n * Mirrors {@link handleListThreads}: requires a `CopilotKitIntelligence`\n * runtime, resolves the user with `identifyUser` (never trusting a\n * client-supplied id), and proxies to the platform's `GET /api/memories`\n * with the project API key + resolved user. The `?includeInvalidated=true`\n * query is forwarded so callers can opt into retired rows. The response is\n * the platform's `{ memories }` envelope, which the client memory store\n * consumes directly.\n */\nexport async function handleListMemories({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (isIntelligenceRuntime(runtime)) {\n try {\n const url = new URL(request.url);\n const includeInvalidated =\n url.searchParams.get(\"includeInvalidated\") === \"true\";\n\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const data = await runtime.intelligence.listMemories({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n ...(includeInvalidated ? { includeInvalidated: true } : {}),\n });\n\n // The client memory store consumes the `{ memories: [...] }` envelope\n // directly. Assert the shape before forwarding so a platform contract\n // violation surfaces as a clear 502 (the runtime is healthy but its\n // dependency returned the wrong shape) instead of a 200 the client will\n // choke on.\n if (\n data == null ||\n typeof data !== \"object\" ||\n !Array.isArray((data as { memories?: unknown }).memories)\n ) {\n logger.error(\n { data },\n \"listMemories: platform returned a response without a `memories` array\",\n );\n return errorResponse(\n \"Memory platform returned an invalid list response\",\n 502,\n );\n }\n\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error listing memories\");\n return memoryErrorResponse(error, \"Failed to list memories\");\n }\n }\n\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n}\n\n/**\n * Semantically recalls the resolved user's memories via the platform (`POST\n * /api/memories/recall`, hybrid RAG). Mirrors {@link handleListMemories}:\n * requires a `CopilotKitIntelligence` runtime, resolves the user with\n * `identifyUser` (never a client-supplied id), proxies with the project API\n * key + resolved user. Body `{ query, limit?, scope? }`; response `{ memories }`,\n * each optionally carrying `score`.\n */\nexport async function handleRecallMemories({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n const fields = parseRecallBody(body);\n if (isHandlerResponse(fields)) return fields;\n\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const data = await runtime.intelligence.recallMemories({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n ...fields,\n });\n\n if (\n data == null ||\n typeof data !== \"object\" ||\n !Array.isArray((data as { memories?: unknown }).memories)\n ) {\n logger.error(\n { data },\n \"recallMemories: platform returned a response without a `memories` array\",\n );\n return errorResponse(\n \"Memory platform returned an invalid recall response\",\n 502,\n );\n }\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error recalling memories\");\n return memoryErrorResponse(error, \"Failed to recall memories\");\n }\n}\n\n/**\n * Mints memory-realtime join credentials (platform `POST\n * /api/memories/subscribe`). Mirrors {@link handleSubscribeToThreads}: requires\n * a `CopilotKitIntelligence` runtime and resolves the user with `identifyUser`\n * (never a client-supplied id). Returns `{ joinToken, joinCode }` — memory needs\n * the `joinCode` here (unlike threads, where it rides the thread-list response)\n * because the client builds the `user_meta:memories:<joinCode>` channel topic\n * from it.\n *\n * When the platform also resolves a project scope, the response additionally\n * carries `projectJoinToken` / `projectJoinCode`, which the client uses to open\n * a second `project_meta:memories:<projectJoinCode>` channel. These are\n * optional: absent project scope → both fields are omitted (silent-degrade\n * contract; the client opens only the user channel).\n */\nexport async function handleSubscribeToMemories({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (isIntelligenceRuntime(runtime)) {\n try {\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const credentials = await runtime.intelligence.ɵsubscribeToMemories({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n });\n\n return Response.json({\n ...(credentials.joinToken !== undefined\n ? { joinToken: credentials.joinToken }\n : {}),\n ...(credentials.joinCode !== undefined\n ? { joinCode: credentials.joinCode }\n : {}),\n // Project-scoped credentials ride along only when the platform minted\n // them; omit both when absent (silent-degrade contract).\n ...(credentials.projectJoinToken !== undefined\n ? { projectJoinToken: credentials.projectJoinToken }\n : {}),\n ...(credentials.projectJoinCode !== undefined\n ? { projectJoinCode: credentials.projectJoinCode }\n : {}),\n });\n } catch (error) {\n logger.error({ err: error }, \"Error subscribing to memories\");\n return memoryErrorResponse(error, \"Failed to subscribe to memories\");\n }\n }\n\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n}\n\n/**\n * Creates a memory for the resolved user (platform `POST /api/memories`).\n * Identity comes from `identifyUser`, never the request body. Returns 201\n * with the stored memory (the client store applies it server-authoritatively).\n */\nexport async function handleCreateMemory({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n const fields = parseMemoryBody(body);\n if (isHandlerResponse(fields)) return fields;\n\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const data = await runtime.intelligence.createMemory({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n ...fields,\n });\n return Response.json(data, { status: 201 });\n } catch (error) {\n logger.error({ err: error }, \"Error creating memory\");\n return memoryErrorResponse(error, \"Failed to create memory\");\n }\n}\n\n/**\n * Supersedes a memory (platform `PATCH /api/memories/:id`): retires `:id` and\n * inserts the new content atomically; the response carries `retiredId`.\n */\nexport async function handleUpdateMemory({\n runtime,\n request,\n memoryId,\n}: MemoryMutationParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n const fields = parseMemoryBody(body);\n if (isHandlerResponse(fields)) return fields;\n\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const data = await runtime.intelligence.updateMemory({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n id: memoryId,\n ...fields,\n });\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error updating memory\");\n return memoryErrorResponse(error, \"Failed to update memory\");\n }\n}\n\n/**\n * Retires (forgets) a memory (platform `DELETE /api/memories/:id`). Non-lossy\n * on the platform side; returns 204.\n */\nexport async function handleRemoveMemory({\n runtime,\n request,\n memoryId,\n}: MemoryMutationParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n await runtime.intelligence.removeMemory({\n userId: access.user.id,\n id: memoryId,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n });\n return new Response(null, { status: 204 });\n } catch (error) {\n logger.error({ err: error }, \"Error removing memory\");\n return memoryErrorResponse(error, \"Failed to remove memory\");\n }\n}\n"],"mappings":";;;;;;;;;AAoBA,eAAe,oBACb,SACA,SACA;CACA,MAAM,OAAO,MAAM,wBAAwB;EAAE;EAAS;EAAS,CAAC;AAChE,KAAI,kBAAkB,KAAK,CAAE,QAAO;AACpC,QAAO,iBAAiB,SAAS,SAAS,MAAM,SAAS;;AAG3D,MAAM,+BACJ;;AAGF,MAAM,eAAoC,IAAI,IAAI;CAChD;CACA;CACA;CACD,CAAC;;AAEF,MAAM,gBAAqC,IAAI,IAAI,CAAC,QAAQ,UAAU,CAAC;;;;;;;;;;;;;AAcvE,SAAS,oBAAoB,OAAgB,SAA2B;AACtE,KAAI,iBAAiB,sBAAsB;EACzC,MAAM,EAAE,WAAW;AACnB,MAAI,OAAO,UAAU,OAAO,IAAI,UAAU,OAAO,UAAU,IACzD,QAAO,cAAc,SAAS,OAAO;AAEvC,SAAO,cAAc,SAAS,IAAI;;AAEpC,QAAO,cAAc,SAAS,IAAI;;AAGpC,eAAe,cACb,SAC6C;AAC7C,KAAI;AACF,SAAQ,MAAM,QAAQ,MAAM;UACrB,OAAO;AACd,SAAO,MAAM,EAAE,KAAK,OAAO,EAAE,wCAAwC;AACrE,SAAO,cAAc,wBAAwB,IAAI;;;;;;;AAQrD,SAAS,gBAAgB,MAOZ;CACX,MAAM,EAAE,SAAS,MAAM,OAAO,oBAAoB;AAClD,KAAI,OAAO,YAAY,YAAY,OAAO,SAAS,SACjD,QAA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;EACF,MAAM,SAAS,MAAM,oBAAoB,SAAS,QAAQ;AAC1D,MAAI,kBAAkB,OAAO,CAAE,QAAO;AAEtC,QAAM,QAAQ,aAAa,aAAa;GACtC,QAAQ,OAAO,KAAK;GACpB,IAAI;GACJ,GAAI,QAAQ,SAAS,EAAE,aAAa,OAAO,OAAO,GAAG,EAAE;GACxD,CAAC;AACF,SAAO,IAAI,SAAS,MAAM,EAAE,QAAQ,KAAK,CAAC;UACnC,OAAO;AACd,SAAO,MAAM,EAAE,KAAK,OAAO,EAAE,wBAAwB;AACrD,SAAO,oBAAoB,OAAO,0BAA0B"}
|
|
@@ -2,14 +2,16 @@ require("reflect-metadata");
|
|
|
2
2
|
const require_runtime = require('../../../../_virtual/_rolldown/runtime.cjs');
|
|
3
3
|
const require_header_utils = require('../header-utils.cjs');
|
|
4
4
|
const require_runtime$1 = require('../../core/runtime.cjs');
|
|
5
|
-
const require_open_generative_ui_middleware = require('../../open-generative-ui-middleware.cjs');
|
|
6
5
|
const require_client = require('../../intelligence-platform/client.cjs');
|
|
6
|
+
const require_open_generative_ui_middleware = require('../../open-generative-ui-middleware.cjs');
|
|
7
|
+
const require_json_response = require('./json-response.cjs');
|
|
7
8
|
const require_resolve_intelligence_user = require('./resolve-intelligence-user.cjs');
|
|
9
|
+
const require_memory_policy = require('./memory-policy.cjs');
|
|
8
10
|
let _copilotkit_shared = require("@copilotkit/shared");
|
|
9
11
|
let _ag_ui_client = require("@ag-ui/client");
|
|
12
|
+
let _ag_ui_mcp_middleware = require("@ag-ui/mcp-middleware");
|
|
10
13
|
let _ag_ui_a2ui_middleware = require("@ag-ui/a2ui-middleware");
|
|
11
14
|
let _ag_ui_mcp_apps_middleware = require("@ag-ui/mcp-apps-middleware");
|
|
12
|
-
let _ag_ui_mcp_middleware = require("@ag-ui/mcp-middleware");
|
|
13
15
|
|
|
14
16
|
//#region src/v2/runtime/handlers/shared/agent-utils.ts
|
|
15
17
|
/**
|
|
@@ -88,8 +90,9 @@ function configureAgentForRequest(params) {
|
|
|
88
90
|
async function attachIntelligenceEnterpriseLearning(params) {
|
|
89
91
|
const { runtime, request } = params;
|
|
90
92
|
const agent = params.agent;
|
|
91
|
-
if (!require_runtime$1.isIntelligenceRuntime(runtime) || !runtime.intelligence?.ɵisEnterpriseLearningEnabled?.()) return;
|
|
93
|
+
if (!require_runtime$1.isIntelligenceRuntime(runtime) || runtime.memory === void 0 && !runtime.intelligence?.ɵisEnterpriseLearningEnabled?.()) return;
|
|
92
94
|
if (typeof agent.use !== "function") {
|
|
95
|
+
if (runtime.memory) return require_json_response.errorResponse("Memory is configured, but this agent does not support middleware", 500);
|
|
93
96
|
_copilotkit_shared.logger.warn("CopilotKitIntelligence.enableEnterpriseLearning is enabled, but the agent does not support middleware (no `.use()` method); Intelligence tools were not attached for this run.");
|
|
94
97
|
return;
|
|
95
98
|
}
|
|
@@ -97,14 +100,17 @@ async function attachIntelligenceEnterpriseLearning(params) {
|
|
|
97
100
|
runtime,
|
|
98
101
|
request
|
|
99
102
|
});
|
|
100
|
-
if (userResult instanceof Response) return;
|
|
103
|
+
if (userResult instanceof Response) return userResult;
|
|
104
|
+
const access = await require_memory_policy.resolveWebMemory(runtime, request, userResult, "agent");
|
|
105
|
+
if (access instanceof Response) return access;
|
|
101
106
|
agent.use(new _ag_ui_mcp_middleware.MCPMiddleware([{
|
|
102
107
|
type: "http",
|
|
103
108
|
url: `${runtime.intelligence.ɵgetApiUrl()}/mcp`,
|
|
104
109
|
serverId: "intelligence",
|
|
105
110
|
headers: {
|
|
106
111
|
Authorization: `Bearer ${runtime.intelligence.ɵgetApiKey()}`,
|
|
107
|
-
[require_client.INTELLIGENCE_USER_ID_HEADER]: userResult.id
|
|
112
|
+
[require_client.INTELLIGENCE_USER_ID_HEADER]: userResult.id,
|
|
113
|
+
...runtime.memory ? { [require_client.INTELLIGENCE_MEMORY_GRANT_HEADER]: JSON.stringify(access.grant) } : {}
|
|
108
114
|
}
|
|
109
115
|
}]));
|
|
110
116
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-utils.cjs","names":["resolveAgents","isA2UIEnabled","A2UIMiddleware","MCPAppsMiddleware","OpenGenerativeUIMiddleware","mergeForwardableHeaders","resolveForwardHeadersPolicy","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 {\n isA2UIEnabled,\n isIntelligenceRuntime,\n resolveAgents,\n} from \"../../core/runtime\";\nimport { OpenGenerativeUIMiddleware } from \"../../open-generative-ui-middleware\";\nimport { INTELLIGENCE_USER_ID_HEADER } from \"../../intelligence-platform/client\";\nimport {\n mergeForwardableHeaders,\n resolveForwardHeadersPolicy,\n} 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\n/**\n * Resolve `agentId` against the runtime's agents and return a per-request\n * clone of the matching agent.\n *\n * Dual return contract — both callers (`handle-run.ts`, `handle-connect.ts`)\n * depend on it:\n * - Returns a cloned `AbstractAgent` when the agent exists.\n * - Returns a 404 `Response` (`{ error: \"Agent not found\", ... }`) when the\n * agent is unknown. Callers MUST `instanceof Response`-check the result and\n * return it directly; this doubles as the connect/run path's agent-existence\n * guard, so skipping the check would let unknown agent ids slip through.\n *\n * The clone is what subsequent per-request mutation (middleware attach,\n * `agent.headers` merge) operates on, leaving the shared agent registration\n * untouched.\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 /**\n * True when the React provider was given an A2UI catalog\n * (`<CopilotKit a2ui={{ catalog }}>`), forwarded per-run. A catalog alone is\n * enough to enable A2UI and inject the render tool — the developer no longer\n * has to also set `a2ui.injectA2UITool` on the runtime.\n */\n providerA2UIHasCatalog?: boolean;\n}): void {\n const { runtime, request, agentId, providerA2UIHasCatalog } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n // A2UI is on when the runtime explicitly enables it, OR when the provider\n // forwarded a catalog — but an explicit `enabled: false` always wins (we\n // provide a quick default, never override a deeper opt-out).\n const a2uiEnabledByCatalog =\n !!providerA2UIHasCatalog && runtime.a2ui?.enabled !== false;\n\n if (isA2UIEnabled(runtime.a2ui) || a2uiEnabledByCatalog) {\n // `enabled` is a CopilotKit-level switch, not an A2UIMiddleware option —\n // drop it (alongside the agent filter) before forwarding to the middleware.\n const {\n agents: targetAgents,\n enabled: _enabled,\n injectA2UITool,\n ...a2uiOptions\n } = runtime.a2ui ?? {};\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(\n new A2UIMiddleware({\n ...a2uiOptions,\n // Default render-tool injection on when a catalog is present and the\n // developer hasn't set it explicitly. `??` means an explicit value\n // (including `false`) is always respected.\n injectA2UITool:\n injectA2UITool ?? (providerA2UIHasCatalog ? true : undefined),\n }),\n );\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 // Forward eligible inbound headers onto the outgoing agent call under the\n // runtime's resolved forwarding policy (`authorization` / custom `x-*`, with\n // known infra/proxy/platform headers stripped by the default denylist —\n // #5712), but let headers the server explicitly configured on the agent WIN\n // on collision (case-insensitively): a server-set service-to-service token\n // (e.g. an IAM bearer) must never be silently overridden by a\n // browser/edge/platform-injected inbound header. See `mergeForwardableHeaders`\n // for the casing/duplicate-key rationale and `shouldForwardHeader` for breadth.\n agent.headers = mergeForwardableHeaders(\n agent.headers,\n request,\n // `forwardHeadersPolicy` is optional on the published `CopilotRuntimeLike`\n // interface (non-breaking minor release). Concrete runtimes always set it;\n // a policy-less external implementor falls back to the default resolved\n // policy (default-on denylist) so behavior stays identical and never derefs\n // undefined.\n runtime.forwardHeadersPolicy ?? resolveForwardHeadersPolicy(undefined),\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDA,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,QAYhC;CACP,MAAM,EAAE,SAAS,SAAS,SAAS,2BAA2B;CAC9D,MAAM,QAAQ,OAAO;CAKrB,MAAM,uBACJ,CAAC,CAAC,0BAA0B,QAAQ,MAAM,YAAY;AAExD,KAAIC,gCAAc,QAAQ,KAAK,IAAI,sBAAsB;EAGvD,MAAM,EACJ,QAAQ,cACR,SAAS,UACT,gBACA,GAAG,gBACD,QAAQ,QAAQ,EAAE;AAEtB,OADoB,CAAC,gBAAgB,aAAa,SAAS,QAAQ,KAChD,OAAO,MAAM,QAAQ,WACt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AC3C;EACF,CACF,CAAC,CACH;;AAGH,eAAsB,gBACpB,SACmC;AACnC,KAAI;EACF,MAAM,cAAc,MAAM,QAAQ,MAAM;AACxC,SAAOC,kCAAoB,MAAM,YAAY;UACtC,OAAO;AACd,4BAAO,MAAM,6BAA6B,MAAM;AAChD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAChE,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;;;AAIL,eAAsB,oBAAoB,SAMxC;AACA,KAAI;EACF,MAAM,cAAc,MAAM,QAAQ,MAAM;EACxC,MAAM,QAAQA,kCAAoB,MAAM,YAAY;EACpD,IAAI,kBAAiC;AAErC,MACE,qBAAsB,gBACrB,OAAQ,YAAwC,oBAC/C,YACC,YAAwC,oBAAoB,MAE/D,mBACG,YAAmC,mBAAmB;AAG3D,SAAO;GAAE;GAAO;GAAiB;UAC1B,OAAO;AACd,4BAAO,MAAM,iCAAiC,MAAM;AACpD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAChE,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
|
|
1
|
+
{"version":3,"file":"agent-utils.cjs","names":["resolveAgents","isA2UIEnabled","A2UIMiddleware","MCPAppsMiddleware","OpenGenerativeUIMiddleware","mergeForwardableHeaders","resolveForwardHeadersPolicy","isIntelligenceRuntime","errorResponse","resolveIntelligenceUser","resolveWebMemory","MCPMiddleware","INTELLIGENCE_USER_ID_HEADER","INTELLIGENCE_MEMORY_GRANT_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 {\n isA2UIEnabled,\n isIntelligenceRuntime,\n resolveAgents,\n} from \"../../core/runtime\";\nimport { OpenGenerativeUIMiddleware } from \"../../open-generative-ui-middleware\";\nimport {\n INTELLIGENCE_MEMORY_GRANT_HEADER,\n INTELLIGENCE_USER_ID_HEADER,\n} from \"../../intelligence-platform/client\";\nimport {\n mergeForwardableHeaders,\n resolveForwardHeadersPolicy,\n} from \"../header-utils\";\nimport { resolveIntelligenceUser } from \"./resolve-intelligence-user\";\nimport { resolveWebMemory } from \"./memory-policy\";\nimport { errorResponse } from \"./json-response\";\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\n/**\n * Resolve `agentId` against the runtime's agents and return a per-request\n * clone of the matching agent.\n *\n * Dual return contract — both callers (`handle-run.ts`, `handle-connect.ts`)\n * depend on it:\n * - Returns a cloned `AbstractAgent` when the agent exists.\n * - Returns a 404 `Response` (`{ error: \"Agent not found\", ... }`) when the\n * agent is unknown. Callers MUST `instanceof Response`-check the result and\n * return it directly; this doubles as the connect/run path's agent-existence\n * guard, so skipping the check would let unknown agent ids slip through.\n *\n * The clone is what subsequent per-request mutation (middleware attach,\n * `agent.headers` merge) operates on, leaving the shared agent registration\n * untouched.\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 /**\n * True when the React provider was given an A2UI catalog\n * (`<CopilotKit a2ui={{ catalog }}>`), forwarded per-run. A catalog alone is\n * enough to enable A2UI and inject the render tool — the developer no longer\n * has to also set `a2ui.injectA2UITool` on the runtime.\n */\n providerA2UIHasCatalog?: boolean;\n}): void {\n const { runtime, request, agentId, providerA2UIHasCatalog } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n // A2UI is on when the runtime explicitly enables it, OR when the provider\n // forwarded a catalog — but an explicit `enabled: false` always wins (we\n // provide a quick default, never override a deeper opt-out).\n const a2uiEnabledByCatalog =\n !!providerA2UIHasCatalog && runtime.a2ui?.enabled !== false;\n\n if (isA2UIEnabled(runtime.a2ui) || a2uiEnabledByCatalog) {\n // `enabled` is a CopilotKit-level switch, not an A2UIMiddleware option —\n // drop it (alongside the agent filter) before forwarding to the middleware.\n const {\n agents: targetAgents,\n enabled: _enabled,\n injectA2UITool,\n ...a2uiOptions\n } = runtime.a2ui ?? {};\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(\n new A2UIMiddleware({\n ...a2uiOptions,\n // Default render-tool injection on when a catalog is present and the\n // developer hasn't set it explicitly. `??` means an explicit value\n // (including `false`) is always respected.\n injectA2UITool:\n injectA2UITool ?? (providerA2UIHasCatalog ? true : undefined),\n }),\n );\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 // Forward eligible inbound headers onto the outgoing agent call under the\n // runtime's resolved forwarding policy (`authorization` / custom `x-*`, with\n // known infra/proxy/platform headers stripped by the default denylist —\n // #5712), but let headers the server explicitly configured on the agent WIN\n // on collision (case-insensitively): a server-set service-to-service token\n // (e.g. an IAM bearer) must never be silently overridden by a\n // browser/edge/platform-injected inbound header. See `mergeForwardableHeaders`\n // for the casing/duplicate-key rationale and `shouldForwardHeader` for breadth.\n agent.headers = mergeForwardableHeaders(\n agent.headers,\n request,\n // `forwardHeadersPolicy` is optional on the published `CopilotRuntimeLike`\n // interface (non-breaking minor release). Concrete runtimes always set it;\n // a policy-less external implementor falls back to the default resolved\n // policy (default-on denylist) so behavior stays identical and never derefs\n // undefined.\n runtime.forwardHeadersPolicy ?? resolveForwardHeadersPolicy(undefined),\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 | Response> {\n const { runtime, request } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n if (\n !isIntelligenceRuntime(runtime) ||\n (runtime.memory === undefined &&\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 if (runtime.memory) {\n return errorResponse(\n \"Memory is configured, but this agent does not support middleware\",\n 500,\n );\n }\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 userResult;\n const access = await resolveWebMemory(runtime, request, userResult, \"agent\");\n if (access instanceof Response) return access;\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 ...(runtime.memory\n ? {\n [INTELLIGENCE_MEMORY_GRANT_HEADER]: JSON.stringify(\n access.grant,\n ),\n }\n : {}),\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,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,QAYhC;CACP,MAAM,EAAE,SAAS,SAAS,SAAS,2BAA2B;CAC9D,MAAM,QAAQ,OAAO;CAKrB,MAAM,uBACJ,CAAC,CAAC,0BAA0B,QAAQ,MAAM,YAAY;AAExD,KAAIC,gCAAc,QAAQ,KAAK,IAAI,sBAAsB;EAGvD,MAAM,EACJ,QAAQ,cACR,SAAS,UACT,gBACA,GAAG,gBACD,QAAQ,QAAQ,EAAE;AAEtB,OADoB,CAAC,gBAAgB,aAAa,SAAS,QAAQ,KAChD,OAAO,MAAM,QAAQ,WACtC,OAAM,IACJ,IAAIC,sCAAe;GACjB,GAA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AAM;EACN,KAAK,GAAG,QAAQ,aAAa,YAAY,CAAC;EAC1C,UAAU;EACV,SAAS;GACP,eAAe,UAAU,QAAQ,aAAa,YAAY;IACzDC,6CAA8B,WAAW;GAC1C,GAAI,QAAQ,SACR,GACGC,kDAAmC,KAAK,UACvC,OAAO,MACR,EACF,GACD,EAAE;GACP;EACF,CACF,CAAC,CACH;;AAGH,eAAsB,gBACpB,SACmC;AACnC,KAAI;EACF,MAAM,cAAc,MAAM,QAAQ,MAAM;AACxC,SAAOC,kCAAoB,MAAM,YAAY;UACtC,OAAO;AACd,4BAAO,MAAM,6BAA6B,MAAM;AAChD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAChE,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;;;AAIL,eAAsB,oBAAoB,SAMxC;AACA,KAAI;EACF,MAAM,cAAc,MAAM,QAAQ,MAAM;EACxC,MAAM,QAAQA,kCAAoB,MAAM,YAAY;EACpD,IAAI,kBAAiC;AAErC,MACE,qBAAsB,gBACrB,OAAQ,YAAwC,oBAC/C,YACC,YAAwC,oBAAoB,MAE/D,mBACG,YAAmC,mBAAmB;AAG3D,SAAO;GAAE;GAAO;GAAiB;UAC1B,OAAO;AACd,4BAAO,MAAM,iCAAiC,MAAM;AACpD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAChE,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
|
|
@@ -1,14 +1,16 @@
|
|
|
1
1
|
import "reflect-metadata";
|
|
2
2
|
import { mergeForwardableHeaders, resolveForwardHeadersPolicy } from "../header-utils.mjs";
|
|
3
3
|
import { isA2UIEnabled, isIntelligenceRuntime, resolveAgents } from "../../core/runtime.mjs";
|
|
4
|
+
import { INTELLIGENCE_MEMORY_GRANT_HEADER, INTELLIGENCE_USER_ID_HEADER } from "../../intelligence-platform/client.mjs";
|
|
4
5
|
import { OpenGenerativeUIMiddleware } from "../../open-generative-ui-middleware.mjs";
|
|
5
|
-
import {
|
|
6
|
+
import { errorResponse } from "./json-response.mjs";
|
|
6
7
|
import { resolveIntelligenceUser } from "./resolve-intelligence-user.mjs";
|
|
8
|
+
import { resolveWebMemory } from "./memory-policy.mjs";
|
|
7
9
|
import { logger } from "@copilotkit/shared";
|
|
8
10
|
import { RunAgentInputSchema } from "@ag-ui/client";
|
|
11
|
+
import { MCPMiddleware } from "@ag-ui/mcp-middleware";
|
|
9
12
|
import { A2UIMiddleware } from "@ag-ui/a2ui-middleware";
|
|
10
13
|
import { MCPAppsMiddleware } from "@ag-ui/mcp-apps-middleware";
|
|
11
|
-
import { MCPMiddleware } from "@ag-ui/mcp-middleware";
|
|
12
14
|
|
|
13
15
|
//#region src/v2/runtime/handlers/shared/agent-utils.ts
|
|
14
16
|
/**
|
|
@@ -87,8 +89,9 @@ function configureAgentForRequest(params) {
|
|
|
87
89
|
async function attachIntelligenceEnterpriseLearning(params) {
|
|
88
90
|
const { runtime, request } = params;
|
|
89
91
|
const agent = params.agent;
|
|
90
|
-
if (!isIntelligenceRuntime(runtime) || !runtime.intelligence?.ɵisEnterpriseLearningEnabled?.()) return;
|
|
92
|
+
if (!isIntelligenceRuntime(runtime) || runtime.memory === void 0 && !runtime.intelligence?.ɵisEnterpriseLearningEnabled?.()) return;
|
|
91
93
|
if (typeof agent.use !== "function") {
|
|
94
|
+
if (runtime.memory) return errorResponse("Memory is configured, but this agent does not support middleware", 500);
|
|
92
95
|
logger.warn("CopilotKitIntelligence.enableEnterpriseLearning is enabled, but the agent does not support middleware (no `.use()` method); Intelligence tools were not attached for this run.");
|
|
93
96
|
return;
|
|
94
97
|
}
|
|
@@ -96,14 +99,17 @@ async function attachIntelligenceEnterpriseLearning(params) {
|
|
|
96
99
|
runtime,
|
|
97
100
|
request
|
|
98
101
|
});
|
|
99
|
-
if (userResult instanceof Response) return;
|
|
102
|
+
if (userResult instanceof Response) return userResult;
|
|
103
|
+
const access = await resolveWebMemory(runtime, request, userResult, "agent");
|
|
104
|
+
if (access instanceof Response) return access;
|
|
100
105
|
agent.use(new MCPMiddleware([{
|
|
101
106
|
type: "http",
|
|
102
107
|
url: `${runtime.intelligence.ɵgetApiUrl()}/mcp`,
|
|
103
108
|
serverId: "intelligence",
|
|
104
109
|
headers: {
|
|
105
110
|
Authorization: `Bearer ${runtime.intelligence.ɵgetApiKey()}`,
|
|
106
|
-
[INTELLIGENCE_USER_ID_HEADER]: userResult.id
|
|
111
|
+
[INTELLIGENCE_USER_ID_HEADER]: userResult.id,
|
|
112
|
+
...runtime.memory ? { [INTELLIGENCE_MEMORY_GRANT_HEADER]: JSON.stringify(access.grant) } : {}
|
|
107
113
|
}
|
|
108
114
|
}]));
|
|
109
115
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-utils.mjs","names":[],"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 {\n isA2UIEnabled,\n isIntelligenceRuntime,\n resolveAgents,\n} from \"../../core/runtime\";\nimport { OpenGenerativeUIMiddleware } from \"../../open-generative-ui-middleware\";\nimport { INTELLIGENCE_USER_ID_HEADER } from \"../../intelligence-platform/client\";\nimport {\n mergeForwardableHeaders,\n resolveForwardHeadersPolicy,\n} 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\n/**\n * Resolve `agentId` against the runtime's agents and return a per-request\n * clone of the matching agent.\n *\n * Dual return contract — both callers (`handle-run.ts`, `handle-connect.ts`)\n * depend on it:\n * - Returns a cloned `AbstractAgent` when the agent exists.\n * - Returns a 404 `Response` (`{ error: \"Agent not found\", ... }`) when the\n * agent is unknown. Callers MUST `instanceof Response`-check the result and\n * return it directly; this doubles as the connect/run path's agent-existence\n * guard, so skipping the check would let unknown agent ids slip through.\n *\n * The clone is what subsequent per-request mutation (middleware attach,\n * `agent.headers` merge) operates on, leaving the shared agent registration\n * untouched.\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 /**\n * True when the React provider was given an A2UI catalog\n * (`<CopilotKit a2ui={{ catalog }}>`), forwarded per-run. A catalog alone is\n * enough to enable A2UI and inject the render tool — the developer no longer\n * has to also set `a2ui.injectA2UITool` on the runtime.\n */\n providerA2UIHasCatalog?: boolean;\n}): void {\n const { runtime, request, agentId, providerA2UIHasCatalog } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n // A2UI is on when the runtime explicitly enables it, OR when the provider\n // forwarded a catalog — but an explicit `enabled: false` always wins (we\n // provide a quick default, never override a deeper opt-out).\n const a2uiEnabledByCatalog =\n !!providerA2UIHasCatalog && runtime.a2ui?.enabled !== false;\n\n if (isA2UIEnabled(runtime.a2ui) || a2uiEnabledByCatalog) {\n // `enabled` is a CopilotKit-level switch, not an A2UIMiddleware option —\n // drop it (alongside the agent filter) before forwarding to the middleware.\n const {\n agents: targetAgents,\n enabled: _enabled,\n injectA2UITool,\n ...a2uiOptions\n } = runtime.a2ui ?? {};\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(\n new A2UIMiddleware({\n ...a2uiOptions,\n // Default render-tool injection on when a catalog is present and the\n // developer hasn't set it explicitly. `??` means an explicit value\n // (including `false`) is always respected.\n injectA2UITool:\n injectA2UITool ?? (providerA2UIHasCatalog ? true : undefined),\n }),\n );\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 // Forward eligible inbound headers onto the outgoing agent call under the\n // runtime's resolved forwarding policy (`authorization` / custom `x-*`, with\n // known infra/proxy/platform headers stripped by the default denylist —\n // #5712), but let headers the server explicitly configured on the agent WIN\n // on collision (case-insensitively): a server-set service-to-service token\n // (e.g. an IAM bearer) must never be silently overridden by a\n // browser/edge/platform-injected inbound header. See `mergeForwardableHeaders`\n // for the casing/duplicate-key rationale and `shouldForwardHeader` for breadth.\n agent.headers = mergeForwardableHeaders(\n agent.headers,\n request,\n // `forwardHeadersPolicy` is optional on the published `CopilotRuntimeLike`\n // interface (non-breaking minor release). Concrete runtimes always set it;\n // a policy-less external implementor falls back to the default resolved\n // policy (default-on denylist) so behavior stays identical and never derefs\n // undefined.\n runtime.forwardHeadersPolicy ?? resolveForwardHeadersPolicy(undefined),\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDA,eAAsB,qBACpB,SACA,SACA,SACmC;CACnC,MAAM,SAAS,MAAM,cAAc,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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+
{"version":3,"file":"agent-utils.mjs","names":[],"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 {\n isA2UIEnabled,\n isIntelligenceRuntime,\n resolveAgents,\n} from \"../../core/runtime\";\nimport { OpenGenerativeUIMiddleware } from \"../../open-generative-ui-middleware\";\nimport {\n INTELLIGENCE_MEMORY_GRANT_HEADER,\n INTELLIGENCE_USER_ID_HEADER,\n} from \"../../intelligence-platform/client\";\nimport {\n mergeForwardableHeaders,\n resolveForwardHeadersPolicy,\n} from \"../header-utils\";\nimport { resolveIntelligenceUser } from \"./resolve-intelligence-user\";\nimport { resolveWebMemory } from \"./memory-policy\";\nimport { errorResponse } from \"./json-response\";\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\n/**\n * Resolve `agentId` against the runtime's agents and return a per-request\n * clone of the matching agent.\n *\n * Dual return contract — both callers (`handle-run.ts`, `handle-connect.ts`)\n * depend on it:\n * - Returns a cloned `AbstractAgent` when the agent exists.\n * - Returns a 404 `Response` (`{ error: \"Agent not found\", ... }`) when the\n * agent is unknown. Callers MUST `instanceof Response`-check the result and\n * return it directly; this doubles as the connect/run path's agent-existence\n * guard, so skipping the check would let unknown agent ids slip through.\n *\n * The clone is what subsequent per-request mutation (middleware attach,\n * `agent.headers` merge) operates on, leaving the shared agent registration\n * untouched.\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 /**\n * True when the React provider was given an A2UI catalog\n * (`<CopilotKit a2ui={{ catalog }}>`), forwarded per-run. A catalog alone is\n * enough to enable A2UI and inject the render tool — the developer no longer\n * has to also set `a2ui.injectA2UITool` on the runtime.\n */\n providerA2UIHasCatalog?: boolean;\n}): void {\n const { runtime, request, agentId, providerA2UIHasCatalog } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n // A2UI is on when the runtime explicitly enables it, OR when the provider\n // forwarded a catalog — but an explicit `enabled: false` always wins (we\n // provide a quick default, never override a deeper opt-out).\n const a2uiEnabledByCatalog =\n !!providerA2UIHasCatalog && runtime.a2ui?.enabled !== false;\n\n if (isA2UIEnabled(runtime.a2ui) || a2uiEnabledByCatalog) {\n // `enabled` is a CopilotKit-level switch, not an A2UIMiddleware option —\n // drop it (alongside the agent filter) before forwarding to the middleware.\n const {\n agents: targetAgents,\n enabled: _enabled,\n injectA2UITool,\n ...a2uiOptions\n } = runtime.a2ui ?? {};\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(\n new A2UIMiddleware({\n ...a2uiOptions,\n // Default render-tool injection on when a catalog is present and the\n // developer hasn't set it explicitly. `??` means an explicit value\n // (including `false`) is always respected.\n injectA2UITool:\n injectA2UITool ?? (providerA2UIHasCatalog ? true : undefined),\n }),\n );\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 // Forward eligible inbound headers onto the outgoing agent call under the\n // runtime's resolved forwarding policy (`authorization` / custom `x-*`, with\n // known infra/proxy/platform headers stripped by the default denylist —\n // #5712), but let headers the server explicitly configured on the agent WIN\n // on collision (case-insensitively): a server-set service-to-service token\n // (e.g. an IAM bearer) must never be silently overridden by a\n // browser/edge/platform-injected inbound header. See `mergeForwardableHeaders`\n // for the casing/duplicate-key rationale and `shouldForwardHeader` for breadth.\n agent.headers = mergeForwardableHeaders(\n agent.headers,\n request,\n // `forwardHeadersPolicy` is optional on the published `CopilotRuntimeLike`\n // interface (non-breaking minor release). Concrete runtimes always set it;\n // a policy-less external implementor falls back to the default resolved\n // policy (default-on denylist) so behavior stays identical and never derefs\n // undefined.\n runtime.forwardHeadersPolicy ?? resolveForwardHeadersPolicy(undefined),\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 | Response> {\n const { runtime, request } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n if (\n !isIntelligenceRuntime(runtime) ||\n (runtime.memory === undefined &&\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 if (runtime.memory) {\n return errorResponse(\n \"Memory is configured, but this agent does not support middleware\",\n 500,\n );\n }\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 userResult;\n const access = await resolveWebMemory(runtime, request, userResult, \"agent\");\n if (access instanceof Response) return access;\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 ...(runtime.memory\n ? {\n [INTELLIGENCE_MEMORY_GRANT_HEADER]: JSON.stringify(\n access.grant,\n ),\n }\n : {}),\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,eAAsB,qBACpB,SACA,SACA,SACmC;CACnC,MAAM,SAAS,MAAM,cAAc,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,QAYhC;CACP,MAAM,EAAE,SAAS,SAAS,SAAS,2BAA2B;CAC9D,MAAM,QAAQ,OAAO;CAKrB,MAAM,uBACJ,CAAC,CAAC,0BAA0B,QAAQ,MAAM,YAAY;AAExD,KAAI,cAAc,QAAQ,KAAK,IAAI,sBAAsB;EAGvD,MAAM,EACJ,QAAQ,cACR,SAAS,UACT,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
|
+
const require_json_response = require('./json-response.cjs');
|
|
3
|
+
|
|
4
|
+
//#region src/v2/runtime/handlers/shared/memory-policy.ts
|
|
5
|
+
const ACCESS = new Set([
|
|
6
|
+
"none",
|
|
7
|
+
"read",
|
|
8
|
+
"read-write"
|
|
9
|
+
]);
|
|
10
|
+
/** Evaluates and validates one configured web Memory policy. */
|
|
11
|
+
async function resolveWebMemory(runtime, request, user, consumer) {
|
|
12
|
+
if (!runtime.memory) return {
|
|
13
|
+
user,
|
|
14
|
+
grant: {
|
|
15
|
+
user: "read-write",
|
|
16
|
+
project: "read-write"
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
try {
|
|
20
|
+
const grant = await runtime.memory.access({
|
|
21
|
+
request,
|
|
22
|
+
user,
|
|
23
|
+
consumer
|
|
24
|
+
});
|
|
25
|
+
if (grant === null || grant.user === "none" && grant.project === "none") return require_json_response.errorResponse("Memory access denied", 403);
|
|
26
|
+
if (!ACCESS.has(grant.user) || !ACCESS.has(grant.project)) return require_json_response.errorResponse("Memory policy returned an invalid grant", 500);
|
|
27
|
+
return {
|
|
28
|
+
user,
|
|
29
|
+
grant: {
|
|
30
|
+
user: grant.user,
|
|
31
|
+
project: grant.project
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
} catch {
|
|
35
|
+
return require_json_response.errorResponse("Memory policy failed", 500);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
//#endregion
|
|
40
|
+
exports.resolveWebMemory = resolveWebMemory;
|
|
41
|
+
//# sourceMappingURL=memory-policy.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"memory-policy.cjs","names":["errorResponse"],"sources":["../../../../../src/v2/runtime/handlers/shared/memory-policy.ts"],"sourcesContent":["import type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeUser,\n MemoryConsumer,\n MemoryGrant,\n} from \"../../core/runtime\";\nimport { errorResponse } from \"./json-response\";\n\nconst ACCESS = new Set([\"none\", \"read\", \"read-write\"]);\n\nexport interface ResolvedWebMemory {\n readonly user: CopilotRuntimeUser;\n readonly grant: MemoryGrant;\n}\n\n/** Evaluates and validates one configured web Memory policy. */\nexport async function resolveWebMemory(\n runtime: CopilotIntelligenceRuntimeLike,\n request: Request,\n user: CopilotRuntimeUser,\n consumer: MemoryConsumer,\n): Promise<ResolvedWebMemory | Response> {\n if (!runtime.memory) {\n return {\n user,\n grant: { user: \"read-write\", project: \"read-write\" },\n };\n }\n\n try {\n const grant = await runtime.memory.access({ request, user, consumer });\n if (grant === null || (grant.user === \"none\" && grant.project === \"none\")) {\n return errorResponse(\"Memory access denied\", 403);\n }\n if (!ACCESS.has(grant.user) || !ACCESS.has(grant.project)) {\n return errorResponse(\"Memory policy returned an invalid grant\", 500);\n }\n return { user, grant: { user: grant.user, project: grant.project } };\n } catch {\n return errorResponse(\"Memory policy failed\", 500);\n }\n}\n"],"mappings":";;;;AAQA,MAAM,SAAS,IAAI,IAAI;CAAC;CAAQ;CAAQ;CAAa,CAAC;;AAQtD,eAAsB,iBACpB,SACA,SACA,MACA,UACuC;AACvC,KAAI,CAAC,QAAQ,OACX,QAAO;EACL;EACA,OAAO;GAAE,MAAM;GAAc,SAAS;GAAc;EACrD;AAGH,KAAI;EACF,MAAM,QAAQ,MAAM,QAAQ,OAAO,OAAO;GAAE;GAAS;GAAM;GAAU,CAAC;AACtE,MAAI,UAAU,QAAS,MAAM,SAAS,UAAU,MAAM,YAAY,OAChE,QAAOA,oCAAc,wBAAwB,IAAI;AAEnD,MAAI,CAAC,OAAO,IAAI,MAAM,KAAK,IAAI,CAAC,OAAO,IAAI,MAAM,QAAQ,CACvD,QAAOA,oCAAc,2CAA2C,IAAI;AAEtE,SAAO;GAAE;GAAM,OAAO;IAAE,MAAM,MAAM;IAAM,SAAS,MAAM;IAAS;GAAE;SAC9D;AACN,SAAOA,oCAAc,wBAAwB,IAAI"}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import "reflect-metadata";
|
|
2
|
+
import { errorResponse } from "./json-response.mjs";
|
|
3
|
+
|
|
4
|
+
//#region src/v2/runtime/handlers/shared/memory-policy.ts
|
|
5
|
+
const ACCESS = new Set([
|
|
6
|
+
"none",
|
|
7
|
+
"read",
|
|
8
|
+
"read-write"
|
|
9
|
+
]);
|
|
10
|
+
/** Evaluates and validates one configured web Memory policy. */
|
|
11
|
+
async function resolveWebMemory(runtime, request, user, consumer) {
|
|
12
|
+
if (!runtime.memory) return {
|
|
13
|
+
user,
|
|
14
|
+
grant: {
|
|
15
|
+
user: "read-write",
|
|
16
|
+
project: "read-write"
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
try {
|
|
20
|
+
const grant = await runtime.memory.access({
|
|
21
|
+
request,
|
|
22
|
+
user,
|
|
23
|
+
consumer
|
|
24
|
+
});
|
|
25
|
+
if (grant === null || grant.user === "none" && grant.project === "none") return errorResponse("Memory access denied", 403);
|
|
26
|
+
if (!ACCESS.has(grant.user) || !ACCESS.has(grant.project)) return errorResponse("Memory policy returned an invalid grant", 500);
|
|
27
|
+
return {
|
|
28
|
+
user,
|
|
29
|
+
grant: {
|
|
30
|
+
user: grant.user,
|
|
31
|
+
project: grant.project
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
} catch {
|
|
35
|
+
return errorResponse("Memory policy failed", 500);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
//#endregion
|
|
40
|
+
export { resolveWebMemory };
|
|
41
|
+
//# sourceMappingURL=memory-policy.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"memory-policy.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/shared/memory-policy.ts"],"sourcesContent":["import type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeUser,\n MemoryConsumer,\n MemoryGrant,\n} from \"../../core/runtime\";\nimport { errorResponse } from \"./json-response\";\n\nconst ACCESS = new Set([\"none\", \"read\", \"read-write\"]);\n\nexport interface ResolvedWebMemory {\n readonly user: CopilotRuntimeUser;\n readonly grant: MemoryGrant;\n}\n\n/** Evaluates and validates one configured web Memory policy. */\nexport async function resolveWebMemory(\n runtime: CopilotIntelligenceRuntimeLike,\n request: Request,\n user: CopilotRuntimeUser,\n consumer: MemoryConsumer,\n): Promise<ResolvedWebMemory | Response> {\n if (!runtime.memory) {\n return {\n user,\n grant: { user: \"read-write\", project: \"read-write\" },\n };\n }\n\n try {\n const grant = await runtime.memory.access({ request, user, consumer });\n if (grant === null || (grant.user === \"none\" && grant.project === \"none\")) {\n return errorResponse(\"Memory access denied\", 403);\n }\n if (!ACCESS.has(grant.user) || !ACCESS.has(grant.project)) {\n return errorResponse(\"Memory policy returned an invalid grant\", 500);\n }\n return { user, grant: { user: grant.user, project: grant.project } };\n } catch {\n return errorResponse(\"Memory policy failed\", 500);\n }\n}\n"],"mappings":";;;;AAQA,MAAM,SAAS,IAAI,IAAI;CAAC;CAAQ;CAAQ;CAAa,CAAC;;AAQtD,eAAsB,iBACpB,SACA,SACA,MACA,UACuC;AACvC,KAAI,CAAC,QAAQ,OACX,QAAO;EACL;EACA,OAAO;GAAE,MAAM;GAAc,SAAS;GAAc;EACrD;AAGH,KAAI;EACF,MAAM,QAAQ,MAAM,QAAQ,OAAO,OAAO;GAAE;GAAS;GAAM;GAAU,CAAC;AACtE,MAAI,UAAU,QAAS,MAAM,SAAS,UAAU,MAAM,YAAY,OAChE,QAAO,cAAc,wBAAwB,IAAI;AAEnD,MAAI,CAAC,OAAO,IAAI,MAAM,KAAK,IAAI,CAAC,OAAO,IAAI,MAAM,QAAQ,CACvD,QAAO,cAAc,2CAA2C,IAAI;AAEtE,SAAO;GAAE;GAAM,OAAO;IAAE,MAAM,MAAM;IAAM,SAAS,MAAM;IAAS;GAAE;SAC9D;AACN,SAAO,cAAc,wBAAwB,IAAI"}
|
|
@@ -3,8 +3,16 @@ const require_json_response = require('./json-response.cjs');
|
|
|
3
3
|
const require_intelligence_utils = require('./intelligence-utils.cjs');
|
|
4
4
|
|
|
5
5
|
//#region src/v2/runtime/handlers/shared/resolve-intelligence-user.ts
|
|
6
|
+
const resolvedUsers = /* @__PURE__ */ new WeakMap();
|
|
6
7
|
async function resolveIntelligenceUser(params) {
|
|
7
8
|
const { runtime, request } = params;
|
|
9
|
+
const existing = resolvedUsers.get(request);
|
|
10
|
+
if (existing) return existing;
|
|
11
|
+
const resolution = resolveUser(runtime, request);
|
|
12
|
+
resolvedUsers.set(request, resolution);
|
|
13
|
+
return resolution;
|
|
14
|
+
}
|
|
15
|
+
async function resolveUser(runtime, request) {
|
|
8
16
|
try {
|
|
9
17
|
const user = await runtime.identifyUser(request);
|
|
10
18
|
if (!require_intelligence_utils.isValidIdentifier(user?.id)) return require_json_response.errorResponse("identifyUser must return a valid user id", 400);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolve-intelligence-user.cjs","names":["isValidIdentifier","errorResponse"],"sources":["../../../../../src/v2/runtime/handlers/shared/resolve-intelligence-user.ts"],"sourcesContent":["import {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeUser,\n} from \"../../core/runtime\";\nimport { errorResponse } from \"./json-response\";\nimport { isValidIdentifier } from \"./intelligence-utils\";\n\nexport async function resolveIntelligenceUser(params: {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n}): Promise<CopilotRuntimeUser | Response> {\n const { runtime, request } = params;\n\n try {\n const user = await runtime.identifyUser(request);\n if (!isValidIdentifier(user?.id)) {\n return errorResponse(\"identifyUser must return a valid user id\", 400);\n }\n if (typeof user?.name !== \"string\" || user.name.trim().length === 0) {\n return errorResponse(\"identifyUser must return a valid user name\", 400);\n }\n\n return { id: user.id, name: user.name };\n } catch (error) {\n console.error(\"Error identifying intelligence user:\", error);\n return errorResponse(\"Failed to identify user\", 500);\n }\n}\n"],"mappings":";;;;;AAOA,eAAsB,wBAAwB,QAGH;CACzC,MAAM,EAAE,SAAS,YAAY;
|
|
1
|
+
{"version":3,"file":"resolve-intelligence-user.cjs","names":["isValidIdentifier","errorResponse"],"sources":["../../../../../src/v2/runtime/handlers/shared/resolve-intelligence-user.ts"],"sourcesContent":["import type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeUser,\n} from \"../../core/runtime\";\nimport { errorResponse } from \"./json-response\";\nimport { isValidIdentifier } from \"./intelligence-utils\";\n\nconst resolvedUsers = new WeakMap<\n Request,\n Promise<CopilotRuntimeUser | Response>\n>();\n\nexport async function resolveIntelligenceUser(params: {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n}): Promise<CopilotRuntimeUser | Response> {\n const { runtime, request } = params;\n\n const existing = resolvedUsers.get(request);\n if (existing) return existing;\n\n const resolution = resolveUser(runtime, request);\n resolvedUsers.set(request, resolution);\n return resolution;\n}\n\nasync function resolveUser(\n runtime: CopilotIntelligenceRuntimeLike,\n request: Request,\n): Promise<CopilotRuntimeUser | Response> {\n try {\n const user = await runtime.identifyUser(request);\n if (!isValidIdentifier(user?.id)) {\n return errorResponse(\"identifyUser must return a valid user id\", 400);\n }\n if (typeof user?.name !== \"string\" || user.name.trim().length === 0) {\n return errorResponse(\"identifyUser must return a valid user name\", 400);\n }\n\n return { id: user.id, name: user.name };\n } catch (error) {\n console.error(\"Error identifying intelligence user:\", error);\n return errorResponse(\"Failed to identify user\", 500);\n }\n}\n"],"mappings":";;;;;AAOA,MAAM,gCAAgB,IAAI,SAGvB;AAEH,eAAsB,wBAAwB,QAGH;CACzC,MAAM,EAAE,SAAS,YAAY;CAE7B,MAAM,WAAW,cAAc,IAAI,QAAQ;AAC3C,KAAI,SAAU,QAAO;CAErB,MAAM,aAAa,YAAY,SAAS,QAAQ;AAChD,eAAc,IAAI,SAAS,WAAW;AACtC,QAAO;;AAGT,eAAe,YACb,SACA,SACwC;AACxC,KAAI;EACF,MAAM,OAAO,MAAM,QAAQ,aAAa,QAAQ;AAChD,MAAI,CAACA,6CAAkB,MAAM,GAAG,CAC9B,QAAOC,oCAAc,4CAA4C,IAAI;AAEvE,MAAI,OAAO,MAAM,SAAS,YAAY,KAAK,KAAK,MAAM,CAAC,WAAW,EAChE,QAAOA,oCAAc,8CAA8C,IAAI;AAGzE,SAAO;GAAE,IAAI,KAAK;GAAI,MAAM,KAAK;GAAM;UAChC,OAAO;AACd,UAAQ,MAAM,wCAAwC,MAAM;AAC5D,SAAOA,oCAAc,2BAA2B,IAAI"}
|
|
@@ -3,8 +3,16 @@ import { errorResponse } from "./json-response.mjs";
|
|
|
3
3
|
import { isValidIdentifier } from "./intelligence-utils.mjs";
|
|
4
4
|
|
|
5
5
|
//#region src/v2/runtime/handlers/shared/resolve-intelligence-user.ts
|
|
6
|
+
const resolvedUsers = /* @__PURE__ */ new WeakMap();
|
|
6
7
|
async function resolveIntelligenceUser(params) {
|
|
7
8
|
const { runtime, request } = params;
|
|
9
|
+
const existing = resolvedUsers.get(request);
|
|
10
|
+
if (existing) return existing;
|
|
11
|
+
const resolution = resolveUser(runtime, request);
|
|
12
|
+
resolvedUsers.set(request, resolution);
|
|
13
|
+
return resolution;
|
|
14
|
+
}
|
|
15
|
+
async function resolveUser(runtime, request) {
|
|
8
16
|
try {
|
|
9
17
|
const user = await runtime.identifyUser(request);
|
|
10
18
|
if (!isValidIdentifier(user?.id)) return errorResponse("identifyUser must return a valid user id", 400);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolve-intelligence-user.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/shared/resolve-intelligence-user.ts"],"sourcesContent":["import {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeUser,\n} from \"../../core/runtime\";\nimport { errorResponse } from \"./json-response\";\nimport { isValidIdentifier } from \"./intelligence-utils\";\n\nexport async function resolveIntelligenceUser(params: {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n}): Promise<CopilotRuntimeUser | Response> {\n const { runtime, request } = params;\n\n try {\n const user = await runtime.identifyUser(request);\n if (!isValidIdentifier(user?.id)) {\n return errorResponse(\"identifyUser must return a valid user id\", 400);\n }\n if (typeof user?.name !== \"string\" || user.name.trim().length === 0) {\n return errorResponse(\"identifyUser must return a valid user name\", 400);\n }\n\n return { id: user.id, name: user.name };\n } catch (error) {\n console.error(\"Error identifying intelligence user:\", error);\n return errorResponse(\"Failed to identify user\", 500);\n }\n}\n"],"mappings":";;;;;AAOA,eAAsB,wBAAwB,QAGH;CACzC,MAAM,EAAE,SAAS,YAAY;
|
|
1
|
+
{"version":3,"file":"resolve-intelligence-user.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/shared/resolve-intelligence-user.ts"],"sourcesContent":["import type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeUser,\n} from \"../../core/runtime\";\nimport { errorResponse } from \"./json-response\";\nimport { isValidIdentifier } from \"./intelligence-utils\";\n\nconst resolvedUsers = new WeakMap<\n Request,\n Promise<CopilotRuntimeUser | Response>\n>();\n\nexport async function resolveIntelligenceUser(params: {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n}): Promise<CopilotRuntimeUser | Response> {\n const { runtime, request } = params;\n\n const existing = resolvedUsers.get(request);\n if (existing) return existing;\n\n const resolution = resolveUser(runtime, request);\n resolvedUsers.set(request, resolution);\n return resolution;\n}\n\nasync function resolveUser(\n runtime: CopilotIntelligenceRuntimeLike,\n request: Request,\n): Promise<CopilotRuntimeUser | Response> {\n try {\n const user = await runtime.identifyUser(request);\n if (!isValidIdentifier(user?.id)) {\n return errorResponse(\"identifyUser must return a valid user id\", 400);\n }\n if (typeof user?.name !== \"string\" || user.name.trim().length === 0) {\n return errorResponse(\"identifyUser must return a valid user name\", 400);\n }\n\n return { id: user.id, name: user.name };\n } catch (error) {\n console.error(\"Error identifying intelligence user:\", error);\n return errorResponse(\"Failed to identify user\", 500);\n }\n}\n"],"mappings":";;;;;AAOA,MAAM,gCAAgB,IAAI,SAGvB;AAEH,eAAsB,wBAAwB,QAGH;CACzC,MAAM,EAAE,SAAS,YAAY;CAE7B,MAAM,WAAW,cAAc,IAAI,QAAQ;AAC3C,KAAI,SAAU,QAAO;CAErB,MAAM,aAAa,YAAY,SAAS,QAAQ;AAChD,eAAc,IAAI,SAAS,WAAW;AACtC,QAAO;;AAGT,eAAe,YACb,SACA,SACwC;AACxC,KAAI;EACF,MAAM,OAAO,MAAM,QAAQ,aAAa,QAAQ;AAChD,MAAI,CAAC,kBAAkB,MAAM,GAAG,CAC9B,QAAO,cAAc,4CAA4C,IAAI;AAEvE,MAAI,OAAO,MAAM,SAAS,YAAY,KAAK,KAAK,MAAM,CAAC,WAAW,EAChE,QAAO,cAAc,8CAA8C,IAAI;AAGzE,SAAO;GAAE,IAAI,KAAK;GAAI,MAAM,KAAK;GAAM;UAChC,OAAO;AACd,UAAQ,MAAM,wCAAwC,MAAM;AAC5D,SAAO,cAAc,2BAA2B,IAAI"}
|
|
@@ -2,7 +2,7 @@ require("reflect-metadata");
|
|
|
2
2
|
import { TranscribeFileOptions, TranscriptionService } from "./transcription-service/transcription-service.cjs";
|
|
3
3
|
import { AgentRunner, AgentRunnerConnectRequest, AgentRunnerIsRunningRequest, AgentRunnerRunRequest, AgentRunnerStopRequest, LocalThreadEndpointRecord, LocalThreadEndpointRunner, supportsLocalThreadEndpoints } from "./runner/agent-runner.cjs";
|
|
4
4
|
import { CopilotKitIntelligence, CopilotKitIntelligenceConfig, CreateThreadRequest, ListThreadsResponse, SubscribeToThreadsRequest, SubscribeToThreadsResponse, ThreadSummary, UpdateThreadRequest } from "./intelligence-platform/client.cjs";
|
|
5
|
-
import { AgentFactoryContext, AgentsConfig, AgentsFactory, CopilotIntelligenceRuntime, CopilotIntelligenceRuntimeLike, CopilotIntelligenceRuntimeOptions, CopilotRuntime, CopilotRuntimeConstructor, CopilotRuntimeLike, CopilotRuntimeOptions, CopilotRuntimeUser, CopilotSseRuntime, CopilotSseRuntimeLike, CopilotSseRuntimeOptions, IdentifyUserCallback, McpAppsConfig, McpAppsServerConfig, OpenGenerativeUIConfig, OpenGenerativeUIOptions, RuntimeWithDeclaredChannels, VERSION, isA2UIEnabled, isIntelligenceRuntime, resolveAgents } from "./core/runtime.cjs";
|
|
5
|
+
import { AgentFactoryContext, AgentsConfig, AgentsFactory, CopilotIntelligenceRuntime, CopilotIntelligenceRuntimeLike, CopilotIntelligenceRuntimeOptions, CopilotRuntime, CopilotRuntimeConstructor, CopilotRuntimeLike, CopilotRuntimeMemoryConfig, CopilotRuntimeOptions, CopilotRuntimeUser, CopilotSseRuntime, CopilotSseRuntimeLike, CopilotSseRuntimeOptions, IdentifyUserCallback, McpAppsConfig, McpAppsServerConfig, MemoryAccess, MemoryConsumer, MemoryGrant, OpenGenerativeUIConfig, OpenGenerativeUIOptions, RuntimeWithDeclaredChannels, VERSION, isA2UIEnabled, isIntelligenceRuntime, resolveAgents } from "./core/runtime.cjs";
|
|
6
6
|
import { CopilotCorsConfig } from "./core/fetch-cors.cjs";
|
|
7
7
|
import { CopilotRuntimeHooks, ErrorHookContext, HandlerHookContext, HookContext, ResponseHookContext, RouteInfo } from "./core/hooks.cjs";
|
|
8
8
|
import { ChannelStatus, ChannelsControl } from "./core/channel-manager.cjs";
|
|
@@ -2,7 +2,7 @@ import "reflect-metadata";
|
|
|
2
2
|
import { TranscribeFileOptions, TranscriptionService } from "./transcription-service/transcription-service.mjs";
|
|
3
3
|
import { AgentRunner, AgentRunnerConnectRequest, AgentRunnerIsRunningRequest, AgentRunnerRunRequest, AgentRunnerStopRequest, LocalThreadEndpointRecord, LocalThreadEndpointRunner, supportsLocalThreadEndpoints } from "./runner/agent-runner.mjs";
|
|
4
4
|
import { CopilotKitIntelligence, CopilotKitIntelligenceConfig, CreateThreadRequest, ListThreadsResponse, SubscribeToThreadsRequest, SubscribeToThreadsResponse, ThreadSummary, UpdateThreadRequest } from "./intelligence-platform/client.mjs";
|
|
5
|
-
import { AgentFactoryContext, AgentsConfig, AgentsFactory, CopilotIntelligenceRuntime, CopilotIntelligenceRuntimeLike, CopilotIntelligenceRuntimeOptions, CopilotRuntime, CopilotRuntimeConstructor, CopilotRuntimeLike, CopilotRuntimeOptions, CopilotRuntimeUser, CopilotSseRuntime, CopilotSseRuntimeLike, CopilotSseRuntimeOptions, IdentifyUserCallback, McpAppsConfig, McpAppsServerConfig, OpenGenerativeUIConfig, OpenGenerativeUIOptions, RuntimeWithDeclaredChannels, VERSION, isA2UIEnabled, isIntelligenceRuntime, resolveAgents } from "./core/runtime.mjs";
|
|
5
|
+
import { AgentFactoryContext, AgentsConfig, AgentsFactory, CopilotIntelligenceRuntime, CopilotIntelligenceRuntimeLike, CopilotIntelligenceRuntimeOptions, CopilotRuntime, CopilotRuntimeConstructor, CopilotRuntimeLike, CopilotRuntimeMemoryConfig, CopilotRuntimeOptions, CopilotRuntimeUser, CopilotSseRuntime, CopilotSseRuntimeLike, CopilotSseRuntimeOptions, IdentifyUserCallback, McpAppsConfig, McpAppsServerConfig, MemoryAccess, MemoryConsumer, MemoryGrant, OpenGenerativeUIConfig, OpenGenerativeUIOptions, RuntimeWithDeclaredChannels, VERSION, isA2UIEnabled, isIntelligenceRuntime, resolveAgents } from "./core/runtime.mjs";
|
|
6
6
|
import { CopilotCorsConfig } from "./core/fetch-cors.mjs";
|
|
7
7
|
import { CopilotRuntimeHooks, ErrorHookContext, HandlerHookContext, HookContext, ResponseHookContext, RouteInfo } from "./core/hooks.mjs";
|
|
8
8
|
import { ChannelStatus, ChannelsControl } from "./core/channel-manager.mjs";
|
|
@@ -15,6 +15,12 @@ let crypto = require("crypto");
|
|
|
15
15
|
* @internal
|
|
16
16
|
*/
|
|
17
17
|
const INTELLIGENCE_USER_ID_HEADER = "x-cpki-user-id";
|
|
18
|
+
/** Immutable user/project Memory grant forwarded to Intelligence. */
|
|
19
|
+
const INTELLIGENCE_MEMORY_GRANT_HEADER = "x-cpki-memory-grant";
|
|
20
|
+
const memoryRequestHeaders = (userId, grant) => ({
|
|
21
|
+
[INTELLIGENCE_USER_ID_HEADER]: userId,
|
|
22
|
+
...grant ? { [INTELLIGENCE_MEMORY_GRANT_HEADER]: JSON.stringify(grant) } : {}
|
|
23
|
+
});
|
|
18
24
|
/**
|
|
19
25
|
* REST base URL of CopilotKit's managed Intelligence platform — the default
|
|
20
26
|
* when {@link CopilotKitIntelligenceConfig.apiUrl} is omitted.
|
|
@@ -253,7 +259,7 @@ var CopilotKitIntelligence = class {
|
|
|
253
259
|
*/
|
|
254
260
|
async listMemories(params) {
|
|
255
261
|
const qs = params.includeInvalidated ? "?includeInvalidated=true" : "";
|
|
256
|
-
return this.#request("GET", `/api/memories${qs}`, void 0,
|
|
262
|
+
return this.#request("GET", `/api/memories${qs}`, void 0, memoryRequestHeaders(params.userId, params.memoryGrant));
|
|
257
263
|
}
|
|
258
264
|
/**
|
|
259
265
|
* Create a memory for the given user (platform `POST /api/memories`).
|
|
@@ -267,7 +273,7 @@ var CopilotKitIntelligence = class {
|
|
|
267
273
|
kind: params.kind,
|
|
268
274
|
...params.scope !== void 0 ? { scope: params.scope } : {},
|
|
269
275
|
sourceThreadIds: params.sourceThreadIds ?? []
|
|
270
|
-
},
|
|
276
|
+
}, memoryRequestHeaders(params.userId, params.memoryGrant));
|
|
271
277
|
}
|
|
272
278
|
/**
|
|
273
279
|
* Supersede an existing memory (platform `PATCH /api/memories/:id`). The
|
|
@@ -283,14 +289,14 @@ var CopilotKitIntelligence = class {
|
|
|
283
289
|
kind: params.kind,
|
|
284
290
|
...params.scope !== void 0 ? { scope: params.scope } : {},
|
|
285
291
|
sourceThreadIds: params.sourceThreadIds ?? []
|
|
286
|
-
},
|
|
292
|
+
}, memoryRequestHeaders(params.userId, params.memoryGrant));
|
|
287
293
|
}
|
|
288
294
|
/**
|
|
289
295
|
* Non-lossily retire (forget) a memory (platform `DELETE /api/memories/:id`).
|
|
290
296
|
* @throws {@link PlatformRequestError} on non-2xx responses.
|
|
291
297
|
*/
|
|
292
298
|
async removeMemory(params) {
|
|
293
|
-
await this.#request("DELETE", `/api/memories/${encodeURIComponent(params.id)}`, void 0,
|
|
299
|
+
await this.#request("DELETE", `/api/memories/${encodeURIComponent(params.id)}`, void 0, memoryRequestHeaders(params.userId, params.memoryGrant));
|
|
294
300
|
}
|
|
295
301
|
/**
|
|
296
302
|
* Semantically recall the given user's memories (platform `POST
|
|
@@ -303,7 +309,7 @@ var CopilotKitIntelligence = class {
|
|
|
303
309
|
query: params.query,
|
|
304
310
|
...params.limit !== void 0 ? { limit: params.limit } : {},
|
|
305
311
|
...params.scope !== void 0 ? { scope: params.scope } : {}
|
|
306
|
-
},
|
|
312
|
+
}, memoryRequestHeaders(params.userId, params.memoryGrant));
|
|
307
313
|
}
|
|
308
314
|
async ɵsubscribeToThreads(params) {
|
|
309
315
|
return this.#request("POST", "/api/threads/subscribe", { userId: params.userId });
|
|
@@ -326,7 +332,7 @@ var CopilotKitIntelligence = class {
|
|
|
326
332
|
* @throws {@link PlatformRequestError} on non-2xx responses.
|
|
327
333
|
*/
|
|
328
334
|
async ɵsubscribeToMemories(params) {
|
|
329
|
-
return this.#request("POST", "/api/memories/subscribe", void 0,
|
|
335
|
+
return this.#request("POST", "/api/memories/subscribe", void 0, memoryRequestHeaders(params.userId, params.memoryGrant));
|
|
330
336
|
}
|
|
331
337
|
/**
|
|
332
338
|
* Update thread metadata (e.g. name).
|
|
@@ -626,6 +632,7 @@ function deriveChannelsWsUrl(wsUrl) {
|
|
|
626
632
|
|
|
627
633
|
//#endregion
|
|
628
634
|
exports.CopilotKitIntelligence = CopilotKitIntelligence;
|
|
635
|
+
exports.INTELLIGENCE_MEMORY_GRANT_HEADER = INTELLIGENCE_MEMORY_GRANT_HEADER;
|
|
629
636
|
exports.INTELLIGENCE_USER_ID_HEADER = INTELLIGENCE_USER_ID_HEADER;
|
|
630
637
|
exports.PlatformRequestError = PlatformRequestError;
|
|
631
638
|
//# sourceMappingURL=client.cjs.map
|