@copilotkit/runtime 1.64.2-canary.1785380282 → 1.64.2-canary.1785417123
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/dist/package.cjs +1 -1
- package/dist/runtime/package.mjs +1 -1
- package/dist/v2/runtime/core/channel-activation-config.cjs +1 -1
- package/dist/v2/runtime/core/channel-activation-config.cjs.map +1 -1
- package/dist/v2/runtime/core/channel-activation-config.mjs +1 -1
- package/dist/v2/runtime/core/channel-activation-config.mjs.map +1 -1
- package/dist/v2/runtime/core/channel-manager.cjs +36 -48
- package/dist/v2/runtime/core/channel-manager.cjs.map +1 -1
- package/dist/v2/runtime/core/channel-manager.d.cts +4 -5
- package/dist/v2/runtime/core/channel-manager.d.cts.map +1 -1
- package/dist/v2/runtime/core/channel-manager.d.mts +4 -5
- package/dist/v2/runtime/core/channel-manager.d.mts.map +1 -1
- package/dist/v2/runtime/core/channel-manager.mjs +36 -48
- 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.d.cts.map +1 -1
- package/dist/v2/runtime/core/fetch-handler.d.mts.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/intelligence-platform/client.cjs +13 -0
- package/dist/v2/runtime/intelligence-platform/client.cjs.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.d.cts +1 -0
- package/dist/v2/runtime/intelligence-platform/client.d.cts.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.d.mts +1 -0
- package/dist/v2/runtime/intelligence-platform/client.d.mts.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.mjs +13 -0
- package/dist/v2/runtime/intelligence-platform/client.mjs.map +1 -1
- package/package.json +5 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetch-handler.mjs","names":[],"sources":["../../../../src/v2/runtime/core/fetch-handler.ts"],"sourcesContent":["/**\n * Framework-agnostic CopilotKit runtime handler.\n *\n * Returns a pure `(Request) => Promise<Response>` function that can be used\n * directly with Bun, Deno, Cloudflare Workers, Next.js App Router, or any\n * Fetch-native runtime — no framework dependency required.\n *\n * @example\n * ```typescript\n * import { CopilotRuntime, createCopilotRuntimeHandler } from \"@copilotkit/runtime/v2\";\n *\n * const handler = createCopilotRuntimeHandler({\n * runtime: new CopilotRuntime({ agents: { ... } }),\n * basePath: \"/api/copilotkit\",\n * cors: true,\n * });\n *\n * // Bun\n * Bun.serve({ fetch: handler });\n *\n * // Deno\n * Deno.serve(handler);\n *\n * // Cloudflare Workers\n * export default { fetch: handler };\n * ```\n *\n * ## Managed Channels lifecycle (serverless-safe)\n *\n * When the runtime declares managed Channels, the returned handler carries a\n * `handler.channels` control surface — but creating the handler opens NO\n * network connection. Activation (which opens a persistent gateway WebSocket)\n * is LAZY: it is triggered by the first `await handler.channels.ready()` and\n * never before — not at handler creation, not on the first HTTP request.\n *\n * - On a LONG-RUNNING host (a Node server / container / the node/express/hono\n * endpoint wrappers), call `await handler.channels.ready()` ONCE at startup to\n * open the listener; the process owns it for its lifetime.\n * - On a SERVERLESS / EDGE host (Cloudflare Workers, Next.js App Router), do NOT\n * call `ready()` — those hosts freeze/recycle per-request isolates and cannot\n * own a persistent listener, and separate cold starts would mint conflicting\n * listeners. The generic Fetch handler stays a pure request/response function\n * there, exactly as documented above.\n *\n * @example\n * ```typescript\n * // Long-running host: open the managed-Channel listener once at startup.\n * const handler = createCopilotRuntimeHandler({ runtime });\n * await handler.channels.ready();\n * ```\n */\n\nimport type {\n CopilotRuntimeLike,\n CopilotIntelligenceRuntimeLike,\n RuntimeWithDeclaredChannels,\n} from \"./runtime\";\nimport { isIntelligenceRuntime } from \"./runtime\";\nimport { ChannelManager } from \"./channel-manager\";\nimport type { ChannelsControl, ActivateChannelEngine } from \"./channel-manager\";\nimport type { CopilotRuntimeHooks, RouteInfo, HookContext } from \"./hooks\";\nimport {\n runOnRequest,\n runOnBeforeHandler,\n runOnResponse,\n runOnError,\n} from \"./hooks\";\nimport type { CopilotCorsConfig } from \"./fetch-cors\";\nimport { handleCors, addCorsHeaders } from \"./fetch-cors\";\nimport { matchRoute } from \"./fetch-router\";\nimport {\n callBeforeRequestMiddleware,\n callAfterRequestMiddleware,\n} from \"./middleware\";\nimport { handleRunAgent } from \"../handlers/handle-run\";\nimport { handleSuggestAgent } from \"../handlers/handle-suggest\";\nimport { handleConnectAgent } from \"../handlers/handle-connect\";\nimport { handleStopAgent } from \"../handlers/handle-stop\";\nimport { handleGetRuntimeInfo } from \"../handlers/get-runtime-info\";\nimport { handleTranscribe } from \"../handlers/handle-transcribe\";\nimport { handleDebugEvents } from \"../handlers/handle-debug-events\";\nimport {\n handleClearThreads,\n handleListThreads,\n handleSubscribeToThreads,\n handleUpdateThread,\n handleArchiveThread,\n handleDeleteThread,\n handleGetThreadMessages,\n handleGetThreadEvents,\n handleGetThreadState,\n} from \"../handlers/handle-threads\";\nimport {\n handleListMemories,\n handleRecallMemories,\n handleSubscribeToMemories,\n handleCreateMemory,\n handleUpdateMemory,\n handleRemoveMemory,\n} from \"../handlers/handle-memories\";\nimport { handleAnnotate } from \"../handlers/handle-user-actions\";\nimport {\n parseMethodCall,\n createJsonRequest,\n expectString,\n} from \"../endpoints/single-route-helpers\";\nimport type { MethodCall } from \"../endpoints/single-route-helpers\";\nimport { logger } from \"@copilotkit/shared\";\nimport { fireInstanceCreatedTelemetry } from \"../telemetry/instance-created\";\n\n/* ------------------------------------------------------------------------------------------------\n * Public types\n * --------------------------------------------------------------------------------------------- */\n\nexport interface CopilotRuntimeHandlerOptions {\n runtime: CopilotRuntimeLike;\n\n /**\n * Optional base path for routing.\n *\n * When provided: strict prefix stripping. The handler strips this prefix from the\n * URL pathname and matches the remainder against known routes.\n *\n * When omitted: suffix matching. The handler matches known route patterns as\n * suffixes of the URL pathname.\n */\n basePath?: string;\n\n /**\n * Endpoint mode:\n * - \"multi-route\" (default): Routes like POST /agent/:agentId/run, GET /info, etc.\n * - \"single-route\": Single POST endpoint with JSON envelope { method, params, body }\n */\n mode?: \"multi-route\" | \"single-route\";\n\n /**\n * Optional CORS configuration.\n * When not provided, no CORS headers are added (let the framework handle it).\n * Set to true for permissive defaults, or provide an object.\n */\n cors?: boolean | CopilotCorsConfig;\n\n /**\n * Lifecycle hooks for request processing.\n */\n hooks?: CopilotRuntimeHooks;\n\n /**\n * Whether the handler builds the runtime's declared managed-Channel control\n * surface. Defaults to `true`, which constructs the {@link ChannelManager} and\n * exposes `handler.channels` — but does NOT open any connection: activation is\n * lazy and triggered by the first `handler.channels.ready()` (see the factory\n * TSDoc). Set `false` to opt out entirely: no {@link ChannelManager} is\n * constructed and the returned handler has no `.channels`. Non-intelligence or\n * channel-less runtimes never build a control surface regardless of this flag.\n */\n activateChannels?: boolean;\n\n /**\n * @internal Test seam: inject a fake Channel activation engine so channel\n * activation runs without opening a real transport. Not part of the public\n * API and may change or be removed without notice.\n */\n __channelEngine?: ActivateChannelEngine;\n}\n\n/**\n * A framework-agnostic runtime handler: a `(Request) => Promise<Response>`\n * function that is also a callable object carrying an optional {@link channels}\n * control surface. A plain function is assignable to this type, so existing\n * call sites that treat it as `(Request) => Promise<Response>` keep working.\n */\nexport type CopilotRuntimeFetchHandler = ((\n request: Request,\n) => Promise<Response>) & {\n /**\n * Present only when the handler activated managed Channels for an\n * Intelligence runtime; the lifecycle control surface for those Channels.\n */\n channels?: ChannelsControl;\n};\n\n/**\n * A {@link CopilotRuntimeFetchHandler} whose {@link ChannelsControl} surface is\n * guaranteed present. Returned when the runtime was constructed with at least\n * one declared Intelligence Channel and activation was not opted out of, so the\n * documented `handler.channels.ready(...)` call type-checks without a `!` or\n * `?.` under strict TypeScript.\n */\nexport type CopilotRuntimeFetchHandlerWithChannels = ((\n request: Request,\n) => Promise<Response>) & {\n /** Lifecycle control surface for the runtime's activated managed Channels. */\n channels: ChannelsControl;\n};\n\n/**\n * Managed Channel managers keyed by runtime instance. Guarantees a single\n * manager (and thus a single activation) per runtime: creating the handler more\n * than once for the same runtime reuses the existing manager instead of\n * constructing a second one.\n */\nconst channelManagers = new WeakMap<object, ChannelManager>();\n\n/**\n * Look up (or lazily CREATE) the {@link ChannelManager} for an Intelligence\n * runtime. First creation constructs the manager and caches it; subsequent\n * lookups reuse the cached instance so there is exactly one manager per runtime.\n *\n * Activation is NOT triggered here. Constructing the manager opens no\n * transport — the persistent gateway socket is opened lazily on the first\n * {@link ChannelManager.ready} call (see the factory TSDoc). This keeps the\n * generic Fetch handler serverless/edge-safe: creating it (e.g. at\n * Cloudflare-Worker module scope or per Next.js App Router isolate) never\n * performs network I/O and never mints a listener the host cannot own.\n *\n * Caching the un-activated manager is correct: a later `ready()` activates it\n * once (idempotently), and an up-front misconfiguration (duplicate/missing\n * channel names) surfaces as a rejected `ready()` rather than a throw at\n * creation. A manager that has been {@link ChannelManager.stop}ped stays\n * stopped on reuse — its latches short-circuit any later `activate()`/`ready()`.\n *\n * @param runtime - The Intelligence runtime whose Channels the manager drives.\n * @param engine - Optional injected activation engine (test seam); when\n * omitted the manager uses its default Realtime Gateway engine.\n * @returns The runtime's (un-activated) Channel manager.\n */\nfunction getOrCreateChannelManager(\n runtime: CopilotIntelligenceRuntimeLike,\n engine: ActivateChannelEngine | undefined,\n): ChannelManager {\n const existing = channelManagers.get(runtime);\n if (existing) {\n return existing;\n }\n const manager = new ChannelManager({\n intelligence: runtime.intelligence,\n runner: runtime.runner,\n lockTtlSeconds: runtime.lockTtlSeconds,\n lockHeartbeatIntervalSeconds: runtime.lockHeartbeatIntervalSeconds,\n channels: runtime.channels,\n // Bridge the manager's diagnostic sink to the shared logger. Without this\n // every `this.log?.(...)` breadcrumb in the manager (setup_required,\n // failed-to-activate, dropped-session, teardown-stop failures) is a no-op,\n // so a channel that fails to activate is permanently dead with zero output.\n // Mirror the `logger.<level>(context, message)` call shape used elsewhere in\n // this file; a failed activation is a degraded-but-recoverable condition, so\n // `warn` is the appropriate level. The manager passes an `Error` as `meta`\n // for failure breadcrumbs, but pino only serializes an Error (its\n // non-enumerable message/stack) under the `err` key — under any other key it\n // renders as `{}` and the cause is lost. Route an Error to `err` and keep the\n // `meta` key for everything else (`meta` is typed `unknown`).\n log: (msg, meta) =>\n logger.warn(meta instanceof Error ? { err: meta } : { meta }, msg),\n ...(engine ? { activateChannel: engine } : {}),\n });\n channelManagers.set(runtime, manager);\n return manager;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Handler factory\n * --------------------------------------------------------------------------------------------- */\n\n/**\n * Overload: a runtime constructed with at least one declared Intelligence\n * Channel (a {@link RuntimeWithDeclaredChannels}-branded runtime), when\n * activation is not disabled, yields a handler with a **non-optional**\n * {@link ChannelsControl}. `activateChannels` is constrained to `true | undefined`\n * here so passing `activateChannels: false` (which skips activation and leaves no\n * `.channels`) falls through to the optional-shape overload below rather than\n * dishonestly promising a control surface that will not exist.\n */\nexport function createCopilotRuntimeHandler(\n options: CopilotRuntimeHandlerOptions & {\n runtime: RuntimeWithDeclaredChannels;\n activateChannels?: true | undefined;\n },\n): CopilotRuntimeFetchHandlerWithChannels;\n/**\n * Overload: every other runtime (SSE, Intelligence without channels, or with\n * activation disabled) yields a handler whose `.channels` is optional.\n */\nexport function createCopilotRuntimeHandler(\n options: CopilotRuntimeHandlerOptions,\n): CopilotRuntimeFetchHandler;\nexport function createCopilotRuntimeHandler(\n options: CopilotRuntimeHandlerOptions,\n): CopilotRuntimeFetchHandler {\n const { runtime, basePath, mode = \"multi-route\", cors, hooks } = options;\n\n fireInstanceCreatedTelemetry({ runtime });\n\n const corsConfig = resolveCorsConfig(cors);\n\n const handler: CopilotRuntimeFetchHandler = async (\n request: Request,\n ): Promise<Response> => {\n const url = new URL(request.url, \"http://localhost\");\n const path = url.pathname;\n const requestOrigin = request.headers.get(\"origin\");\n\n // Base hook context (route not yet known)\n const baseCtx: HookContext = { request, path, runtime };\n\n let route: RouteInfo | undefined;\n\n try {\n // 1. CORS preflight\n if (corsConfig) {\n const preflight = handleCors(request, corsConfig);\n if (preflight) return preflight;\n }\n\n // 2. onRequest hook\n request = await runOnRequest(hooks, { ...baseCtx, request });\n\n // 3. Legacy beforeRequestMiddleware\n try {\n const maybeModified = await callBeforeRequestMiddleware({\n runtime,\n request,\n path,\n });\n if (maybeModified) {\n request = maybeModified;\n }\n } catch (mwError: unknown) {\n logger.error(\n { err: mwError, url: request.url, path },\n \"Error running before request middleware\",\n );\n if (mwError instanceof Response) {\n return maybeAddCors(mwError, corsConfig, requestOrigin);\n }\n throw mwError;\n }\n\n // 4. Route matching\n let response: Response;\n\n if (mode === \"single-route\") {\n const resolved = await resolveSingleRoute(request, basePath, path);\n route = resolved.route;\n const { methodCall } = resolved;\n // 5. onBeforeHandler hook\n request = await runOnBeforeHandler(hooks, {\n request,\n path,\n runtime,\n route,\n });\n // 6. Wrap body for methods that need it, then dispatch\n if (\n route.method === \"agent/run\" ||\n route.method === \"agent/suggest\" ||\n route.method === \"agent/connect\" ||\n route.method === \"transcribe\"\n ) {\n request = createJsonRequest(request, methodCall.body);\n }\n response = await dispatchRoute(runtime, request, route, {\n threadEndpointsEnabled: false,\n });\n } else {\n // Multi-route: match URL pattern\n const matched = matchRoute(path, basePath);\n if (!matched) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n\n // Opt-in gate for the client-facing memory proxy routes (secure\n // default: off). Runs BEFORE method validation so a hidden route 404s\n // uniformly regardless of HTTP method — a 405 here would otherwise leak\n // that the route exists. `dispatchRoute` re-applies the same gate as\n // defense-in-depth (and to cover the single-route path).\n if (\n matched.method.startsWith(\"memories/\") &&\n runtime.exposeMemoryRoutes !== true\n ) {\n route = matched;\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n\n // Validate HTTP method\n const methodError = validateHttpMethod(request.method, matched);\n if (methodError) {\n route = matched;\n throw methodError;\n }\n\n route = matched;\n\n // 5. onBeforeHandler hook\n request = await runOnBeforeHandler(hooks, {\n request,\n path,\n runtime,\n route,\n });\n\n // 6. Handler dispatch\n response = await dispatchRoute(runtime, request, route, {\n threadEndpointsEnabled: true,\n });\n }\n\n // 7. onResponse hook\n response = await runOnResponse(hooks, {\n request,\n response,\n path,\n runtime,\n route,\n });\n\n // 8. CORS headers on response\n response = maybeAddCors(response, corsConfig, requestOrigin);\n\n // 9. Legacy afterRequestMiddleware (non-blocking)\n // Clone the response so middleware can read the body without consuming\n // the original stream that will be sent to the client.\n callAfterRequestMiddleware({\n runtime,\n response: response.clone(),\n path,\n }).catch((error: unknown) => {\n logger.error(\n { err: error, url: request.url, path },\n \"Error running after request middleware\",\n );\n });\n\n return response;\n } catch (error) {\n // Short-circuit with thrown Response\n if (error instanceof Response) {\n const finalResponse = await runOnResponse(hooks, {\n request,\n response: error,\n path,\n runtime,\n route: route ?? { method: \"info\" },\n });\n return maybeAddCors(finalResponse, corsConfig, requestOrigin);\n }\n\n // Run onError hook — wrapped so a throwing hook doesn't escape\n try {\n const errorResponse = await runOnError(hooks, {\n request,\n error,\n path,\n runtime,\n route,\n });\n\n if (errorResponse) {\n return maybeAddCors(errorResponse, corsConfig, requestOrigin);\n }\n } catch (hookError: unknown) {\n logger.error(\n { err: hookError, originalErr: error, url: request.url, path },\n \"onError hook threw\",\n );\n }\n\n logger.error(\n { err: error, url: request.url, path },\n \"Unhandled error in CopilotKit runtime handler\",\n );\n\n return maybeAddCors(\n jsonResponse({ error: \"internal_error\" }, 500),\n corsConfig,\n requestOrigin,\n );\n }\n };\n\n // Build (but do NOT activate) the managed-Channel control surface for an\n // Intelligence runtime that declares Channels and hasn't opted out via\n // activateChannels. `handler.channels` exists immediately, but the persistent\n // gateway socket is opened lazily on the first `handler.channels.ready()` —\n // never at handler-creation time and never inside the per-request closure\n // above. This keeps the generic Fetch handler serverless/edge-safe: no\n // module-scope network I/O, and no listener a request-driven isolate cannot\n // own. See the factory TSDoc for the full lifecycle contract.\n if (\n isIntelligenceRuntime(runtime) &&\n runtime.channels &&\n runtime.channels.length > 0 &&\n options.activateChannels !== false\n ) {\n handler.channels = getOrCreateChannelManager(\n runtime,\n options.__channelEngine,\n );\n }\n\n return handler;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Route dispatch\n * --------------------------------------------------------------------------------------------- */\n\nfunction dispatchRoute(\n runtime: CopilotRuntimeLike,\n request: Request,\n route: RouteInfo,\n options: { threadEndpointsEnabled: boolean },\n): Promise<Response> {\n // Opt-in gate for the client-facing memory proxy routes (secure default:\n // off). When not explicitly enabled, every `/memories/*` route 404s as if it\n // did not exist — this MUST run before the per-handler `isIntelligenceRuntime`\n // check so an un-opted-in deployment reveals nothing about memory (not even\n // whether Intelligence is configured). Coalesce a missing flag (external\n // `CopilotRuntimeLike` implementor) to `false`.\n if (\n route.method.startsWith(\"memories/\") &&\n runtime.exposeMemoryRoutes !== true\n ) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n\n switch (route.method) {\n case \"agent/run\":\n return handleRunAgent({\n runtime,\n request,\n agentId: route.agentId,\n });\n case \"agent/suggest\":\n return handleSuggestAgent({\n runtime,\n request,\n agentId: route.agentId,\n });\n case \"agent/connect\":\n return handleConnectAgent({\n runtime,\n request,\n agentId: route.agentId,\n });\n case \"agent/stop\":\n return handleStopAgent({\n runtime,\n request,\n agentId: route.agentId,\n threadId: route.threadId,\n });\n case \"info\":\n return handleGetRuntimeInfo({\n runtime,\n request,\n threadEndpointsEnabled: options.threadEndpointsEnabled,\n });\n case \"transcribe\":\n return handleTranscribe({ runtime, request });\n case \"threads/clear\":\n return Promise.resolve(handleClearThreads({ runtime, request }));\n case \"threads/list\":\n return handleListThreads({ runtime, request });\n case \"memories/list\":\n return request.method.toUpperCase() === \"POST\"\n ? handleCreateMemory({ runtime, request })\n : handleListMemories({ runtime, request });\n case \"memories/recall\":\n return handleRecallMemories({ runtime, request });\n case \"memories/subscribe\":\n return handleSubscribeToMemories({ runtime, request });\n case \"memories/mutate\":\n return request.method.toUpperCase() === \"DELETE\"\n ? handleRemoveMemory({ runtime, request, memoryId: route.memoryId })\n : handleUpdateMemory({ runtime, request, memoryId: route.memoryId });\n case \"threads/subscribe\":\n return handleSubscribeToThreads({ runtime, request });\n case \"threads/update\":\n if (request.method.toUpperCase() === \"DELETE\") {\n return handleDeleteThread({\n runtime,\n request,\n threadId: route.threadId,\n });\n }\n return handleUpdateThread({ runtime, request, threadId: route.threadId });\n case \"threads/archive\":\n return handleArchiveThread({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"threads/messages\":\n return handleGetThreadMessages({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"threads/events\":\n return handleGetThreadEvents({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"threads/state\":\n return handleGetThreadState({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"annotate\":\n return handleAnnotate({ runtime, request });\n case \"cpk-debug-events\":\n return Promise.resolve(handleDebugEvents({ runtime, request }));\n default: {\n // Exhaustiveness guard: a new `RouteInfo` variant added without a case\n // above becomes a compile error here instead of silently returning\n // `undefined` at runtime.\n const _exhaustive: never = route;\n throw jsonResponse(\n { error: \"Not found\", method: (_exhaustive as RouteInfo).method },\n 404,\n );\n }\n }\n}\n\ninterface SingleRouteResolution {\n route: RouteInfo;\n methodCall: MethodCall;\n}\n\nasync function resolveSingleRoute(\n request: Request,\n basePath: string | undefined,\n pathname: string,\n): Promise<SingleRouteResolution> {\n if (basePath) {\n const normalizedBase =\n basePath.length > 1 && basePath.endsWith(\"/\")\n ? basePath.slice(0, -1)\n : basePath;\n if (!pathname.startsWith(normalizedBase)) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n }\n\n if (request.method !== \"POST\") {\n throw jsonResponse({ error: \"Method not allowed\" }, 405, { Allow: \"POST\" });\n }\n\n const methodCall = await parseMethodCall(request);\n\n let route: RouteInfo;\n switch (methodCall.method) {\n case \"agent/run\":\n route = {\n method: \"agent/run\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/suggest\":\n route = {\n method: \"agent/suggest\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/connect\":\n route = {\n method: \"agent/connect\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/stop\":\n route = {\n method: \"agent/stop\",\n agentId: expectString(methodCall.params, \"agentId\"),\n threadId: expectString(methodCall.params, \"threadId\"),\n };\n break;\n case \"info\":\n route = { method: \"info\" };\n break;\n case \"transcribe\":\n route = { method: \"transcribe\" };\n break;\n default: {\n // Exhaustiveness guard: a new `METHOD_NAMES`/`EndpointMethod` variant\n // added without a case above becomes a compile error here instead of\n // leaving `route` unassigned at runtime.\n const _exhaustive: never = methodCall.method;\n throw jsonResponse({ error: \"Not found\", method: _exhaustive }, 404);\n }\n }\n\n return { route, methodCall };\n}\n\n/* ------------------------------------------------------------------------------------------------\n * HTTP method validation\n * --------------------------------------------------------------------------------------------- */\n\nfunction validateHttpMethod(\n httpMethod: string,\n route: RouteInfo,\n): Response | null {\n const method = httpMethod.toUpperCase();\n\n switch (route.method) {\n case \"info\":\n case \"threads/list\":\n case \"threads/messages\":\n case \"threads/events\":\n case \"threads/state\":\n case \"cpk-debug-events\":\n if (method === \"GET\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"GET\",\n });\n\n case \"memories/list\":\n // GET lists the user's memories; POST creates one.\n if (method === \"GET\" || method === \"POST\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"GET, POST\",\n });\n\n case \"memories/mutate\":\n // PATCH supersedes; DELETE retires.\n if (method === \"PATCH\" || method === \"DELETE\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"PATCH, DELETE\",\n });\n\n case \"memories/recall\":\n // POST-only: semantic recall carries its query in the body.\n if (method === \"POST\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"POST\",\n });\n\n case \"threads/update\":\n if (method === \"PATCH\" || method === \"DELETE\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"PATCH, DELETE\",\n });\n\n default:\n if (method === \"POST\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"POST\",\n });\n }\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Helpers\n * --------------------------------------------------------------------------------------------- */\n\nfunction resolveCorsConfig(\n cors: boolean | CopilotCorsConfig | undefined,\n): CopilotCorsConfig | null {\n if (!cors) return null;\n if (cors === true) return {};\n return cors;\n}\n\nfunction maybeAddCors(\n response: Response,\n config: CopilotCorsConfig | null,\n requestOrigin: string | null,\n): Response {\n if (!config) return response;\n return addCorsHeaders(response, config, requestOrigin);\n}\n\nfunction jsonResponse(\n body: unknown,\n status: number,\n extraHeaders?: Record<string, string>,\n): Response {\n return new Response(JSON.stringify(body), {\n status,\n headers: { \"Content-Type\": \"application/json\", ...extraHeaders },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0MA,MAAM,kCAAkB,IAAI,SAAiC;;;;;;;;;;;;;;;;;;;;;;;;AAyB7D,SAAS,0BACP,SACA,QACgB;CAChB,MAAM,WAAW,gBAAgB,IAAI,QAAQ;AAC7C,KAAI,SACF,QAAO;CAET,MAAM,UAAU,IAAI,eAAe;EACjC,cAAc,QAAQ;EACtB,QAAQ,QAAQ;EAChB,gBAAgB,QAAQ;EACxB,8BAA8B,QAAQ;EACtC,UAAU,QAAQ;EAYlB,MAAM,KAAK,SACT,OAAO,KAAK,gBAAgB,QAAQ,EAAE,KAAK,MAAM,GAAG,EAAE,MAAM,EAAE,IAAI;EACpE,GAAI,SAAS,EAAE,iBAAiB,QAAQ,GAAG,EAAE;EAC9C,CAAC;AACF,iBAAgB,IAAI,SAAS,QAAQ;AACrC,QAAO;;AA6BT,SAAgB,4BACd,SAC4B;CAC5B,MAAM,EAAE,SAAS,UAAU,OAAO,eAAe,MAAM,UAAU;A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QAAO;AAC9B,UAAO,aAAa,EAAE,OAAO,sBAAsB,EAAE,KAAK,EACxD,OAAO,QACR,CAAC;;;AAQR,SAAS,kBACP,MAC0B;AAC1B,KAAI,CAAC,KAAM,QAAO;AAClB,KAAI,SAAS,KAAM,QAAO,EAAE;AAC5B,QAAO;;AAGT,SAAS,aACP,UACA,QACA,eACU;AACV,KAAI,CAAC,OAAQ,QAAO;AACpB,QAAO,eAAe,UAAU,QAAQ,cAAc;;AAGxD,SAAS,aACP,MACA,QACA,cACU;AACV,QAAO,IAAI,SAAS,KAAK,UAAU,KAAK,EAAE;EACxC;EACA,SAAS;GAAE,gBAAgB;GAAoB,GAAG;GAAc;EACjE,CAAC"}
|
|
1
|
+
{"version":3,"file":"fetch-handler.mjs","names":[],"sources":["../../../../src/v2/runtime/core/fetch-handler.ts"],"sourcesContent":["/**\n * Framework-agnostic CopilotKit runtime handler.\n *\n * Returns a pure `(Request) => Promise<Response>` function that can be used\n * directly with Bun, Deno, Cloudflare Workers, Next.js App Router, or any\n * Fetch-native runtime — no framework dependency required.\n *\n * @example\n * ```typescript\n * import { CopilotRuntime, createCopilotRuntimeHandler } from \"@copilotkit/runtime/v2\";\n *\n * const handler = createCopilotRuntimeHandler({\n * runtime: new CopilotRuntime({ agents: { ... } }),\n * basePath: \"/api/copilotkit\",\n * cors: true,\n * });\n *\n * // Bun\n * Bun.serve({ fetch: handler });\n *\n * // Deno\n * Deno.serve(handler);\n *\n * // Cloudflare Workers\n * export default { fetch: handler };\n * ```\n *\n * ## Managed Channels lifecycle (serverless-safe)\n *\n * When the runtime declares managed Channels, the returned handler carries a\n * `handler.channels` control surface — but creating the handler opens NO\n * network connection. Activation (which opens a persistent gateway WebSocket)\n * is LAZY: it is triggered by the first `await handler.channels.ready()` and\n * never before — not at handler creation, not on the first HTTP request.\n *\n * - On a LONG-RUNNING host (a Node server / container / the node/express/hono\n * endpoint wrappers), call `await handler.channels.ready()` ONCE at startup to\n * open the listener; the process owns it for its lifetime.\n * - On a SERVERLESS / EDGE host (Cloudflare Workers, Next.js App Router), do NOT\n * call `ready()` — those hosts freeze/recycle per-request isolates and cannot\n * own a persistent listener, and separate cold starts would mint conflicting\n * listeners. The generic Fetch handler stays a pure request/response function\n * there, exactly as documented above.\n *\n * @example\n * ```typescript\n * // Long-running host: open the managed-Channel listener once at startup.\n * const handler = createCopilotRuntimeHandler({ runtime });\n * await handler.channels.ready();\n * ```\n */\n\nimport type {\n CopilotRuntimeLike,\n CopilotIntelligenceRuntimeLike,\n RuntimeWithDeclaredChannels,\n} from \"./runtime\";\nimport { isIntelligenceRuntime } from \"./runtime\";\nimport { ChannelManager } from \"./channel-manager\";\nimport type { ChannelsControl, ActivateChannelEngine } from \"./channel-manager\";\nimport type { CopilotRuntimeHooks, RouteInfo, HookContext } from \"./hooks\";\nimport {\n runOnRequest,\n runOnBeforeHandler,\n runOnResponse,\n runOnError,\n} from \"./hooks\";\nimport type { CopilotCorsConfig } from \"./fetch-cors\";\nimport { handleCors, addCorsHeaders } from \"./fetch-cors\";\nimport { matchRoute } from \"./fetch-router\";\nimport {\n callBeforeRequestMiddleware,\n callAfterRequestMiddleware,\n} from \"./middleware\";\nimport { handleRunAgent } from \"../handlers/handle-run\";\nimport { handleSuggestAgent } from \"../handlers/handle-suggest\";\nimport { handleConnectAgent } from \"../handlers/handle-connect\";\nimport { handleStopAgent } from \"../handlers/handle-stop\";\nimport { handleGetRuntimeInfo } from \"../handlers/get-runtime-info\";\nimport { handleTranscribe } from \"../handlers/handle-transcribe\";\nimport { handleDebugEvents } from \"../handlers/handle-debug-events\";\nimport {\n handleClearThreads,\n handleListThreads,\n handleSubscribeToThreads,\n handleUpdateThread,\n handleArchiveThread,\n handleDeleteThread,\n handleGetThreadMessages,\n handleGetThreadEvents,\n handleGetThreadState,\n} from \"../handlers/handle-threads\";\nimport {\n handleListMemories,\n handleRecallMemories,\n handleSubscribeToMemories,\n handleCreateMemory,\n handleUpdateMemory,\n handleRemoveMemory,\n} from \"../handlers/handle-memories\";\nimport { handleAnnotate } from \"../handlers/handle-user-actions\";\nimport {\n parseMethodCall,\n createJsonRequest,\n expectString,\n} from \"../endpoints/single-route-helpers\";\nimport type { MethodCall } from \"../endpoints/single-route-helpers\";\nimport { logger } from \"@copilotkit/shared\";\nimport { fireInstanceCreatedTelemetry } from \"../telemetry/instance-created\";\n\n/* ------------------------------------------------------------------------------------------------\n * Public types\n * --------------------------------------------------------------------------------------------- */\n\nexport interface CopilotRuntimeHandlerOptions {\n runtime: CopilotRuntimeLike;\n\n /**\n * Optional base path for routing.\n *\n * When provided: strict prefix stripping. The handler strips this prefix from the\n * URL pathname and matches the remainder against known routes.\n *\n * When omitted: suffix matching. The handler matches known route patterns as\n * suffixes of the URL pathname.\n */\n basePath?: string;\n\n /**\n * Endpoint mode:\n * - \"multi-route\" (default): Routes like POST /agent/:agentId/run, GET /info, etc.\n * - \"single-route\": Single POST endpoint with JSON envelope { method, params, body }\n */\n mode?: \"multi-route\" | \"single-route\";\n\n /**\n * Optional CORS configuration.\n * When not provided, no CORS headers are added (let the framework handle it).\n * Set to true for permissive defaults, or provide an object.\n */\n cors?: boolean | CopilotCorsConfig;\n\n /**\n * Lifecycle hooks for request processing.\n */\n hooks?: CopilotRuntimeHooks;\n\n /**\n * Whether the handler builds the runtime's declared managed-Channel control\n * surface. Defaults to `true`, which constructs the {@link ChannelManager} and\n * exposes `handler.channels` — but does NOT open any connection: activation is\n * lazy and triggered by the first `handler.channels.ready()` (see the factory\n * TSDoc). Set `false` to opt out entirely: no {@link ChannelManager} is\n * constructed and the returned handler has no `.channels`. Non-intelligence or\n * channel-less runtimes never build a control surface regardless of this flag.\n */\n activateChannels?: boolean;\n\n /**\n * @internal Test seam: inject a fake Channel activation engine so channel\n * activation runs without opening a real transport. Not part of the public\n * API and may change or be removed without notice.\n */\n __channelEngine?: ActivateChannelEngine;\n}\n\n/**\n * A framework-agnostic runtime handler: a `(Request) => Promise<Response>`\n * function that is also a callable object carrying an optional {@link channels}\n * control surface. A plain function is assignable to this type, so existing\n * call sites that treat it as `(Request) => Promise<Response>` keep working.\n */\nexport type CopilotRuntimeFetchHandler = ((\n request: Request,\n) => Promise<Response>) & {\n /**\n * Present only when the handler activated managed Channels for an\n * Intelligence runtime; the lifecycle control surface for those Channels.\n */\n channels?: ChannelsControl;\n};\n\n/**\n * A {@link CopilotRuntimeFetchHandler} whose {@link ChannelsControl} surface is\n * guaranteed present. Returned when the runtime was constructed with at least\n * one declared Intelligence Channel and activation was not opted out of, so the\n * documented `handler.channels.ready(...)` call type-checks without a `!` or\n * `?.` under strict TypeScript.\n */\nexport type CopilotRuntimeFetchHandlerWithChannels = ((\n request: Request,\n) => Promise<Response>) & {\n /** Lifecycle control surface for the runtime's activated managed Channels. */\n channels: ChannelsControl;\n};\n\n/**\n * Managed Channel managers keyed by runtime instance. Guarantees a single\n * manager (and thus a single activation) per runtime: creating the handler more\n * than once for the same runtime reuses the existing manager instead of\n * constructing a second one.\n */\nconst channelManagers = new WeakMap<object, ChannelManager>();\n\n/**\n * Look up (or lazily CREATE) the {@link ChannelManager} for an Intelligence\n * runtime. First creation constructs the manager and caches it; subsequent\n * lookups reuse the cached instance so there is exactly one manager per runtime.\n *\n * Activation is NOT triggered here. Constructing the manager opens no\n * transport — the persistent gateway socket is opened lazily on the first\n * {@link ChannelManager.ready} call (see the factory TSDoc). This keeps the\n * generic Fetch handler serverless/edge-safe: creating it (e.g. at\n * Cloudflare-Worker module scope or per Next.js App Router isolate) never\n * performs network I/O and never mints a listener the host cannot own.\n *\n * Caching the un-activated manager is correct: a later `ready()` activates it\n * once (idempotently), and an up-front misconfiguration (duplicate/missing\n * channel names) surfaces as a rejected `ready()` rather than a throw at\n * creation. A manager that has been {@link ChannelManager.stop}ped stays\n * stopped on reuse — its latches short-circuit any later `activate()`/`ready()`.\n *\n * @param runtime - The Intelligence runtime whose Channels the manager drives.\n * @param engine - Optional injected activation engine (test seam); when\n * omitted the manager uses its default Realtime Gateway engine.\n * @returns The runtime's (un-activated) Channel manager.\n */\nfunction getOrCreateChannelManager(\n runtime: CopilotIntelligenceRuntimeLike,\n engine: ActivateChannelEngine | undefined,\n): ChannelManager {\n const existing = channelManagers.get(runtime);\n if (existing) {\n return existing;\n }\n const manager = new ChannelManager({\n intelligence: runtime.intelligence,\n runner: runtime.runner,\n lockTtlSeconds: runtime.lockTtlSeconds,\n lockHeartbeatIntervalSeconds: runtime.lockHeartbeatIntervalSeconds,\n ...(runtime.lockKeyPrefix !== undefined\n ? { lockKeyPrefix: runtime.lockKeyPrefix }\n : {}),\n channels: runtime.channels,\n // Bridge the manager's diagnostic sink to the shared logger. Without this\n // every `this.log?.(...)` breadcrumb in the manager (setup_required,\n // failed-to-activate, dropped-session, teardown-stop failures) is a no-op,\n // so a channel that fails to activate is permanently dead with zero output.\n // Mirror the `logger.<level>(context, message)` call shape used elsewhere in\n // this file; a failed activation is a degraded-but-recoverable condition, so\n // `warn` is the appropriate level. The manager passes an `Error` as `meta`\n // for failure breadcrumbs, but pino only serializes an Error (its\n // non-enumerable message/stack) under the `err` key — under any other key it\n // renders as `{}` and the cause is lost. Route an Error to `err` and keep the\n // `meta` key for everything else (`meta` is typed `unknown`).\n log: (msg, meta) =>\n logger.warn(meta instanceof Error ? { err: meta } : { meta }, msg),\n ...(engine ? { activateChannel: engine } : {}),\n });\n channelManagers.set(runtime, manager);\n return manager;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Handler factory\n * --------------------------------------------------------------------------------------------- */\n\n/**\n * Overload: a runtime constructed with at least one declared Intelligence\n * Channel (a {@link RuntimeWithDeclaredChannels}-branded runtime), when\n * activation is not disabled, yields a handler with a **non-optional**\n * {@link ChannelsControl}. `activateChannels` is constrained to `true | undefined`\n * here so passing `activateChannels: false` (which skips activation and leaves no\n * `.channels`) falls through to the optional-shape overload below rather than\n * dishonestly promising a control surface that will not exist.\n */\nexport function createCopilotRuntimeHandler(\n options: CopilotRuntimeHandlerOptions & {\n runtime: RuntimeWithDeclaredChannels;\n activateChannels?: true | undefined;\n },\n): CopilotRuntimeFetchHandlerWithChannels;\n/**\n * Overload: every other runtime (SSE, Intelligence without channels, or with\n * activation disabled) yields a handler whose `.channels` is optional.\n */\nexport function createCopilotRuntimeHandler(\n options: CopilotRuntimeHandlerOptions,\n): CopilotRuntimeFetchHandler;\nexport function createCopilotRuntimeHandler(\n options: CopilotRuntimeHandlerOptions,\n): CopilotRuntimeFetchHandler {\n const { runtime, basePath, mode = \"multi-route\", cors, hooks } = options;\n\n fireInstanceCreatedTelemetry({ runtime });\n\n const corsConfig = resolveCorsConfig(cors);\n\n const handler: CopilotRuntimeFetchHandler = async (\n request: Request,\n ): Promise<Response> => {\n const url = new URL(request.url, \"http://localhost\");\n const path = url.pathname;\n const requestOrigin = request.headers.get(\"origin\");\n\n // Base hook context (route not yet known)\n const baseCtx: HookContext = { request, path, runtime };\n\n let route: RouteInfo | undefined;\n\n try {\n // 1. CORS preflight\n if (corsConfig) {\n const preflight = handleCors(request, corsConfig);\n if (preflight) return preflight;\n }\n\n // 2. onRequest hook\n request = await runOnRequest(hooks, { ...baseCtx, request });\n\n // 3. Legacy beforeRequestMiddleware\n try {\n const maybeModified = await callBeforeRequestMiddleware({\n runtime,\n request,\n path,\n });\n if (maybeModified) {\n request = maybeModified;\n }\n } catch (mwError: unknown) {\n logger.error(\n { err: mwError, url: request.url, path },\n \"Error running before request middleware\",\n );\n if (mwError instanceof Response) {\n return maybeAddCors(mwError, corsConfig, requestOrigin);\n }\n throw mwError;\n }\n\n // 4. Route matching\n let response: Response;\n\n if (mode === \"single-route\") {\n const resolved = await resolveSingleRoute(request, basePath, path);\n route = resolved.route;\n const { methodCall } = resolved;\n // 5. onBeforeHandler hook\n request = await runOnBeforeHandler(hooks, {\n request,\n path,\n runtime,\n route,\n });\n // 6. Wrap body for methods that need it, then dispatch\n if (\n route.method === \"agent/run\" ||\n route.method === \"agent/suggest\" ||\n route.method === \"agent/connect\" ||\n route.method === \"transcribe\"\n ) {\n request = createJsonRequest(request, methodCall.body);\n }\n response = await dispatchRoute(runtime, request, route, {\n threadEndpointsEnabled: false,\n });\n } else {\n // Multi-route: match URL pattern\n const matched = matchRoute(path, basePath);\n if (!matched) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n\n // Opt-in gate for the client-facing memory proxy routes (secure\n // default: off). Runs BEFORE method validation so a hidden route 404s\n // uniformly regardless of HTTP method — a 405 here would otherwise leak\n // that the route exists. `dispatchRoute` re-applies the same gate as\n // defense-in-depth (and to cover the single-route path).\n if (\n matched.method.startsWith(\"memories/\") &&\n runtime.exposeMemoryRoutes !== true\n ) {\n route = matched;\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n\n // Validate HTTP method\n const methodError = validateHttpMethod(request.method, matched);\n if (methodError) {\n route = matched;\n throw methodError;\n }\n\n route = matched;\n\n // 5. onBeforeHandler hook\n request = await runOnBeforeHandler(hooks, {\n request,\n path,\n runtime,\n route,\n });\n\n // 6. Handler dispatch\n response = await dispatchRoute(runtime, request, route, {\n threadEndpointsEnabled: true,\n });\n }\n\n // 7. onResponse hook\n response = await runOnResponse(hooks, {\n request,\n response,\n path,\n runtime,\n route,\n });\n\n // 8. CORS headers on response\n response = maybeAddCors(response, corsConfig, requestOrigin);\n\n // 9. Legacy afterRequestMiddleware (non-blocking)\n // Clone the response so middleware can read the body without consuming\n // the original stream that will be sent to the client.\n callAfterRequestMiddleware({\n runtime,\n response: response.clone(),\n path,\n }).catch((error: unknown) => {\n logger.error(\n { err: error, url: request.url, path },\n \"Error running after request middleware\",\n );\n });\n\n return response;\n } catch (error) {\n // Short-circuit with thrown Response\n if (error instanceof Response) {\n const finalResponse = await runOnResponse(hooks, {\n request,\n response: error,\n path,\n runtime,\n route: route ?? { method: \"info\" },\n });\n return maybeAddCors(finalResponse, corsConfig, requestOrigin);\n }\n\n // Run onError hook — wrapped so a throwing hook doesn't escape\n try {\n const errorResponse = await runOnError(hooks, {\n request,\n error,\n path,\n runtime,\n route,\n });\n\n if (errorResponse) {\n return maybeAddCors(errorResponse, corsConfig, requestOrigin);\n }\n } catch (hookError: unknown) {\n logger.error(\n { err: hookError, originalErr: error, url: request.url, path },\n \"onError hook threw\",\n );\n }\n\n logger.error(\n { err: error, url: request.url, path },\n \"Unhandled error in CopilotKit runtime handler\",\n );\n\n return maybeAddCors(\n jsonResponse({ error: \"internal_error\" }, 500),\n corsConfig,\n requestOrigin,\n );\n }\n };\n\n // Build (but do NOT activate) the managed-Channel control surface for an\n // Intelligence runtime that declares Channels and hasn't opted out via\n // activateChannels. `handler.channels` exists immediately, but the persistent\n // gateway socket is opened lazily on the first `handler.channels.ready()` —\n // never at handler-creation time and never inside the per-request closure\n // above. This keeps the generic Fetch handler serverless/edge-safe: no\n // module-scope network I/O, and no listener a request-driven isolate cannot\n // own. See the factory TSDoc for the full lifecycle contract.\n if (\n isIntelligenceRuntime(runtime) &&\n runtime.channels &&\n runtime.channels.length > 0 &&\n options.activateChannels !== false\n ) {\n handler.channels = getOrCreateChannelManager(\n runtime,\n options.__channelEngine,\n );\n }\n\n return handler;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Route dispatch\n * --------------------------------------------------------------------------------------------- */\n\nfunction dispatchRoute(\n runtime: CopilotRuntimeLike,\n request: Request,\n route: RouteInfo,\n options: { threadEndpointsEnabled: boolean },\n): Promise<Response> {\n // Opt-in gate for the client-facing memory proxy routes (secure default:\n // off). When not explicitly enabled, every `/memories/*` route 404s as if it\n // did not exist — this MUST run before the per-handler `isIntelligenceRuntime`\n // check so an un-opted-in deployment reveals nothing about memory (not even\n // whether Intelligence is configured). Coalesce a missing flag (external\n // `CopilotRuntimeLike` implementor) to `false`.\n if (\n route.method.startsWith(\"memories/\") &&\n runtime.exposeMemoryRoutes !== true\n ) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n\n switch (route.method) {\n case \"agent/run\":\n return handleRunAgent({\n runtime,\n request,\n agentId: route.agentId,\n });\n case \"agent/suggest\":\n return handleSuggestAgent({\n runtime,\n request,\n agentId: route.agentId,\n });\n case \"agent/connect\":\n return handleConnectAgent({\n runtime,\n request,\n agentId: route.agentId,\n });\n case \"agent/stop\":\n return handleStopAgent({\n runtime,\n request,\n agentId: route.agentId,\n threadId: route.threadId,\n });\n case \"info\":\n return handleGetRuntimeInfo({\n runtime,\n request,\n threadEndpointsEnabled: options.threadEndpointsEnabled,\n });\n case \"transcribe\":\n return handleTranscribe({ runtime, request });\n case \"threads/clear\":\n return Promise.resolve(handleClearThreads({ runtime, request }));\n case \"threads/list\":\n return handleListThreads({ runtime, request });\n case \"memories/list\":\n return request.method.toUpperCase() === \"POST\"\n ? handleCreateMemory({ runtime, request })\n : handleListMemories({ runtime, request });\n case \"memories/recall\":\n return handleRecallMemories({ runtime, request });\n case \"memories/subscribe\":\n return handleSubscribeToMemories({ runtime, request });\n case \"memories/mutate\":\n return request.method.toUpperCase() === \"DELETE\"\n ? handleRemoveMemory({ runtime, request, memoryId: route.memoryId })\n : handleUpdateMemory({ runtime, request, memoryId: route.memoryId });\n case \"threads/subscribe\":\n return handleSubscribeToThreads({ runtime, request });\n case \"threads/update\":\n if (request.method.toUpperCase() === \"DELETE\") {\n return handleDeleteThread({\n runtime,\n request,\n threadId: route.threadId,\n });\n }\n return handleUpdateThread({ runtime, request, threadId: route.threadId });\n case \"threads/archive\":\n return handleArchiveThread({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"threads/messages\":\n return handleGetThreadMessages({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"threads/events\":\n return handleGetThreadEvents({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"threads/state\":\n return handleGetThreadState({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"annotate\":\n return handleAnnotate({ runtime, request });\n case \"cpk-debug-events\":\n return Promise.resolve(handleDebugEvents({ runtime, request }));\n default: {\n // Exhaustiveness guard: a new `RouteInfo` variant added without a case\n // above becomes a compile error here instead of silently returning\n // `undefined` at runtime.\n const _exhaustive: never = route;\n throw jsonResponse(\n { error: \"Not found\", method: (_exhaustive as RouteInfo).method },\n 404,\n );\n }\n }\n}\n\ninterface SingleRouteResolution {\n route: RouteInfo;\n methodCall: MethodCall;\n}\n\nasync function resolveSingleRoute(\n request: Request,\n basePath: string | undefined,\n pathname: string,\n): Promise<SingleRouteResolution> {\n if (basePath) {\n const normalizedBase =\n basePath.length > 1 && basePath.endsWith(\"/\")\n ? basePath.slice(0, -1)\n : basePath;\n if (!pathname.startsWith(normalizedBase)) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n }\n\n if (request.method !== \"POST\") {\n throw jsonResponse({ error: \"Method not allowed\" }, 405, { Allow: \"POST\" });\n }\n\n const methodCall = await parseMethodCall(request);\n\n let route: RouteInfo;\n switch (methodCall.method) {\n case \"agent/run\":\n route = {\n method: \"agent/run\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/suggest\":\n route = {\n method: \"agent/suggest\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/connect\":\n route = {\n method: \"agent/connect\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/stop\":\n route = {\n method: \"agent/stop\",\n agentId: expectString(methodCall.params, \"agentId\"),\n threadId: expectString(methodCall.params, \"threadId\"),\n };\n break;\n case \"info\":\n route = { method: \"info\" };\n break;\n case \"transcribe\":\n route = { method: \"transcribe\" };\n break;\n default: {\n // Exhaustiveness guard: a new `METHOD_NAMES`/`EndpointMethod` variant\n // added without a case above becomes a compile error here instead of\n // leaving `route` unassigned at runtime.\n const _exhaustive: never = methodCall.method;\n throw jsonResponse({ error: \"Not found\", method: _exhaustive }, 404);\n }\n }\n\n return { route, methodCall };\n}\n\n/* ------------------------------------------------------------------------------------------------\n * HTTP method validation\n * --------------------------------------------------------------------------------------------- */\n\nfunction validateHttpMethod(\n httpMethod: string,\n route: RouteInfo,\n): Response | null {\n const method = httpMethod.toUpperCase();\n\n switch (route.method) {\n case \"info\":\n case \"threads/list\":\n case \"threads/messages\":\n case \"threads/events\":\n case \"threads/state\":\n case \"cpk-debug-events\":\n if (method === \"GET\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"GET\",\n });\n\n case \"memories/list\":\n // GET lists the user's memories; POST creates one.\n if (method === \"GET\" || method === \"POST\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"GET, POST\",\n });\n\n case \"memories/mutate\":\n // PATCH supersedes; DELETE retires.\n if (method === \"PATCH\" || method === \"DELETE\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"PATCH, DELETE\",\n });\n\n case \"memories/recall\":\n // POST-only: semantic recall carries its query in the body.\n if (method === \"POST\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"POST\",\n });\n\n case \"threads/update\":\n if (method === \"PATCH\" || method === \"DELETE\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"PATCH, DELETE\",\n });\n\n default:\n if (method === \"POST\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"POST\",\n });\n }\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Helpers\n * --------------------------------------------------------------------------------------------- */\n\nfunction resolveCorsConfig(\n cors: boolean | CopilotCorsConfig | undefined,\n): CopilotCorsConfig | null {\n if (!cors) return null;\n if (cors === true) return {};\n return cors;\n}\n\nfunction maybeAddCors(\n response: Response,\n config: CopilotCorsConfig | null,\n requestOrigin: string | null,\n): Response {\n if (!config) return response;\n return addCorsHeaders(response, config, requestOrigin);\n}\n\nfunction jsonResponse(\n body: unknown,\n status: number,\n extraHeaders?: Record<string, string>,\n): Response {\n return new Response(JSON.stringify(body), {\n status,\n headers: { \"Content-Type\": \"application/json\", ...extraHeaders },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0MA,MAAM,kCAAkB,IAAI,SAAiC;;;;;;;;;;;;;;;;;;;;;;;;AAyB7D,SAAS,0B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,EAAE,KAAK,EACxD,OAAO,OACR,CAAC;EAEJ,KAAK;AAEH,OAAI,WAAW,SAAS,WAAW,OAAQ,QAAO;AAClD,UAAO,aAAa,EAAE,OAAO,sBAAsB,EAAE,KAAK,EACxD,OAAO,aACR,CAAC;EAEJ,KAAK;AAEH,OAAI,WAAW,WAAW,WAAW,SAAU,QAAO;AACtD,UAAO,aAAa,EAAE,OAAO,sBAAsB,EAAE,KAAK,EACxD,OAAO,iBACR,CAAC;EAEJ,KAAK;AAEH,OAAI,WAAW,OAAQ,QAAO;AAC9B,UAAO,aAAa,EAAE,OAAO,sBAAsB,EAAE,KAAK,EACxD,OAAO,QACR,CAAC;EAEJ,KAAK;AACH,OAAI,WAAW,WAAW,WAAW,SAAU,QAAO;AACtD,UAAO,aAAa,EAAE,OAAO,sBAAsB,EAAE,KAAK,EACxD,OAAO,iBACR,CAAC;EAEJ;AACE,OAAI,WAAW,OAAQ,QAAO;AAC9B,UAAO,aAAa,EAAE,OAAO,sBAAsB,EAAE,KAAK,EACxD,OAAO,QACR,CAAC;;;AAQR,SAAS,kBACP,MAC0B;AAC1B,KAAI,CAAC,KAAM,QAAO;AAClB,KAAI,SAAS,KAAM,QAAO,EAAE;AAC5B,QAAO;;AAGT,SAAS,aACP,UACA,QACA,eACU;AACV,KAAI,CAAC,OAAQ,QAAO;AACpB,QAAO,eAAe,UAAU,QAAQ,cAAc;;AAGxD,SAAS,aACP,MACA,QACA,cACU;AACV,QAAO,IAAI,SAAS,KAAK,UAAU,KAAK,EAAE;EACxC;EACA,SAAS;GAAE,gBAAgB;GAAoB,GAAG;GAAc;EACjE,CAAC"}
|
|
@@ -86,6 +86,7 @@ var CopilotKitIntelligence = class {
|
|
|
86
86
|
#apiUrl;
|
|
87
87
|
#runnerWsUrl;
|
|
88
88
|
#clientWsUrl;
|
|
89
|
+
#channelsWsUrl;
|
|
89
90
|
#apiKey;
|
|
90
91
|
#enterpriseLearningEnabled;
|
|
91
92
|
#threadCreatedListeners = /* @__PURE__ */ new Set();
|
|
@@ -99,6 +100,7 @@ var CopilotKitIntelligence = class {
|
|
|
99
100
|
this.#apiUrl = (configuredApiUrl ?? MANAGED_INTELLIGENCE_API_URL).replace(/\/$/, "");
|
|
100
101
|
this.#runnerWsUrl = deriveRunnerWsUrl(intelligenceWsUrl);
|
|
101
102
|
this.#clientWsUrl = deriveClientWsUrl(intelligenceWsUrl);
|
|
103
|
+
this.#channelsWsUrl = deriveChannelsWsUrl(intelligenceWsUrl);
|
|
102
104
|
this.#apiKey = config.apiKey;
|
|
103
105
|
this.#enterpriseLearningEnabled = config.enableEnterpriseLearning ?? false;
|
|
104
106
|
if (config.onThreadCreated) this.onThreadCreated(config.onThreadCreated);
|
|
@@ -169,6 +171,9 @@ var CopilotKitIntelligence = class {
|
|
|
169
171
|
ɵgetClientWsUrl() {
|
|
170
172
|
return this.#clientWsUrl;
|
|
171
173
|
}
|
|
174
|
+
ɵgetChannelsWsUrl() {
|
|
175
|
+
return this.#channelsWsUrl;
|
|
176
|
+
}
|
|
172
177
|
ɵgetRunnerAuthToken() {
|
|
173
178
|
return this.#apiKey;
|
|
174
179
|
}
|
|
@@ -585,13 +590,21 @@ function normalizeIntelligenceWsUrl(wsUrl) {
|
|
|
585
590
|
function deriveRunnerWsUrl(wsUrl) {
|
|
586
591
|
if (wsUrl.endsWith("/runner")) return wsUrl;
|
|
587
592
|
if (wsUrl.endsWith("/client")) return `${wsUrl.slice(0, -7)}/runner`;
|
|
593
|
+
if (wsUrl.endsWith("/channels")) return `${wsUrl.slice(0, -9)}/runner`;
|
|
588
594
|
return `${wsUrl}/runner`;
|
|
589
595
|
}
|
|
590
596
|
function deriveClientWsUrl(wsUrl) {
|
|
591
597
|
if (wsUrl.endsWith("/client")) return wsUrl;
|
|
592
598
|
if (wsUrl.endsWith("/runner")) return `${wsUrl.slice(0, -7)}/client`;
|
|
599
|
+
if (wsUrl.endsWith("/channels")) return `${wsUrl.slice(0, -9)}/client`;
|
|
593
600
|
return `${wsUrl}/client`;
|
|
594
601
|
}
|
|
602
|
+
function deriveChannelsWsUrl(wsUrl) {
|
|
603
|
+
if (wsUrl.endsWith("/channels")) return wsUrl;
|
|
604
|
+
if (wsUrl.endsWith("/runner")) return `${wsUrl.slice(0, -7)}/channels`;
|
|
605
|
+
if (wsUrl.endsWith("/client")) return `${wsUrl.slice(0, -7)}/channels`;
|
|
606
|
+
return `${wsUrl}/channels`;
|
|
607
|
+
}
|
|
595
608
|
|
|
596
609
|
//#endregion
|
|
597
610
|
exports.CopilotKitIntelligence = CopilotKitIntelligence;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.cjs","names":["#apiUrl","#runnerWsUrl","#clientWsUrl","#apiKey","#enterpriseLearningEnabled","#threadCreatedListeners","#threadUpdatedListeners","#threadDeletedListeners","#request","#invokeLifecycleCallback"],"sources":["../../../../src/v2/runtime/intelligence-platform/client.ts"],"sourcesContent":["import { logger } from \"@copilotkit/shared\";\nimport { randomUUID } from \"crypto\";\n\n/**\n * Header name carrying the per-call end-user identity that the CopilotKit\n * Intelligence `/mcp` endpoint requires. Internal CopilotKit machinery —\n * `attachIntelligenceEnterpriseLearning` resolves the user via `identifyUser`\n * and bakes this header onto the `MCPMiddleware`'s transport config, so every\n * outbound MCP request stamps `X-Cpki-User-Id: <userId>`. Not part of the\n * public user API.\n *\n * @internal\n */\nexport const INTELLIGENCE_USER_ID_HEADER = \"x-cpki-user-id\";\n\n/**\n * REST base URL of CopilotKit's managed Intelligence platform — the default\n * when {@link CopilotKitIntelligenceConfig.apiUrl} is omitted.\n */\nconst MANAGED_INTELLIGENCE_API_URL = \"https://api.intelligence.copilotkit.ai\";\n\n/**\n * Websocket base URL of CopilotKit's managed Intelligence platform — the\n * default when {@link CopilotKitIntelligenceConfig.wsUrl} is omitted.\n *\n * A different host from {@link MANAGED_INTELLIGENCE_API_URL}: the API and\n * realtime planes are deployed separately.\n */\nconst MANAGED_INTELLIGENCE_WS_URL = \"wss://realtime.intelligence.copilotkit.ai\";\n\n/**\n * Error thrown when an Intelligence platform HTTP request returns a non-2xx\n * status. Carries the HTTP {@link status} code so callers can branch on\n * specific failures (e.g. 404 for \"not found\", 409 for \"conflict\") without\n * parsing the error message string.\n *\n * @example\n * ```ts\n * try {\n * await intelligence.getThread({ threadId, userId });\n * } catch (error) {\n * if (error instanceof PlatformRequestError && error.status === 404) {\n * // thread does not exist yet\n * }\n * }\n * ```\n */\nexport class PlatformRequestError extends Error {\n constructor(\n message: string,\n /** The HTTP status code returned by the platform (e.g. 404, 409, 500). */\n public readonly status: number,\n ) {\n super(message);\n this.name = \"PlatformRequestError\";\n }\n}\n\n/** Payload passed to `onThreadDeleted` listeners. */\nexport interface ThreadDeletedPayload {\n threadId: string;\n userId: string;\n agentId: string;\n}\n\nexport interface CopilotKitIntelligenceConfig {\n /**\n * Base URL of the intelligence platform API.\n *\n * Defaults to CopilotKit's managed platform,\n * `https://api.intelligence.copilotkit.ai`. Set it only when pointing at a\n * self-hosted or non-production deployment — and set {@link wsUrl} with it.\n */\n apiUrl?: string;\n /**\n * Intelligence websocket base URL. Runner and client socket URLs are derived\n * from this by appending `/runner` or `/client`, so pass the bare base.\n *\n * Defaults to CopilotKit's managed platform,\n * `wss://realtime.intelligence.copilotkit.ai`.\n *\n * This is a DIFFERENT host from {@link apiUrl} — the API and realtime planes are\n * deployed separately — so it cannot be derived by scheme-swapping `apiUrl`.\n * Overriding one without the other therefore points the two planes at\n * different deployments, which logs a warning.\n */\n wsUrl?: string;\n /** API key for authenticating with the intelligence platform */\n apiKey: string;\n /**\n * Enable Enterprise Learning — expose the Intelligence platform's\n * built-in tools (bash + thread/memory tools) to agent runs on an\n * intelligence runtime that resolve a user. Attached uniformly across\n * agent frameworks by `attachIntelligenceEnterpriseLearning` via\n * `@ag-ui/mcp-middleware`, with the resolved user-id and project apiKey\n * baked into the transport headers for that request's clone.\n *\n * Defaults to `false` — opt-in. Existing intelligence setups continue\n * to work without these tools unless they flip this flag.\n */\n enableEnterpriseLearning?: boolean;\n /**\n * Initial listener invoked after a thread is created.\n * Prefer {@link CopilotKitIntelligence.onThreadCreated} for multiple listeners.\n */\n onThreadCreated?: (thread: ThreadSummary) => void;\n /**\n * Initial listener invoked after a thread is updated.\n * Prefer {@link CopilotKitIntelligence.onThreadUpdated} for multiple listeners.\n */\n onThreadUpdated?: (thread: ThreadSummary) => void;\n /**\n * Initial listener invoked after a thread is deleted.\n * Prefer {@link CopilotKitIntelligence.onThreadDeleted} for multiple listeners.\n */\n onThreadDeleted?: (params: ThreadDeletedPayload) => void;\n}\n\n/**\n * Summary metadata for a single thread returned by the platform.\n *\n * This is the shape returned by list, get, create, and update operations.\n * It does not include the thread's message history — use\n * {@link CopilotKitIntelligence.getThreadMessages} for that.\n */\nexport interface ThreadSummary {\n /** Platform-assigned unique identifier. */\n id: string;\n /** Human-readable display name, or `null` if the thread has not been named. */\n name: string | null;\n /** ISO-8601 timestamp of the most recent agent run on this thread. */\n lastRunAt?: string;\n /** ISO-8601 timestamp of the most recent metadata update. */\n lastUpdatedAt?: string;\n /** ISO-8601 timestamp when the thread was created. */\n createdAt?: string;\n /** ISO-8601 timestamp when the thread was last updated. */\n updatedAt?: string;\n /** Whether the thread has been archived. Archived threads are excluded from default list results. */\n archived?: boolean;\n /** The agent that owns this thread. */\n agentId?: string;\n /** The user who created this thread. */\n createdById?: string;\n /** The organization this thread belongs to. */\n organizationId?: string;\n}\n\n/** Response from listing threads for a user/agent pair. */\nexport interface ListThreadsResponse {\n /** The matching threads, sorted by the platform's default ordering. */\n threads: ThreadSummary[];\n /** Join code for subscribing to realtime metadata updates for these threads. */\n joinCode: string;\n /** Short-lived token for authenticating the realtime subscription. */\n joinToken?: string;\n /** Opaque cursor for fetching the next page. `null` or absent when there are no more pages. */\n nextCursor?: string | null;\n}\n\n/**\n * A single memory as returned by the platform's list endpoint. Mirrors the\n * public projection the client memory store consumes (tenant ids stripped).\n */\nexport interface MemorySummary {\n /** Platform-assigned unique identifier. */\n id: string;\n /** Memory kind, e.g. `\"topical\"`, `\"episodic\"`, `\"operational\"`. */\n kind: string;\n /** Memory scope: `\"user\"` (private) or `\"project\"` (shared). */\n scope: string;\n /** The remembered fact, preference, or procedure. */\n content: string;\n /** Ids of the threads this memory was learned from. */\n sourceThreadIds: string[];\n /** ISO-8601 timestamp when the memory was retired, or `null` if live. */\n invalidatedAt: string | null;\n /** Relevance score from a `recall` (hybrid RAG) query. Present only on recall responses. */\n score?: number;\n}\n\n/** Response from {@link CopilotKitIntelligence.listMemories}. */\nexport interface ListMemoriesResponse {\n memories: MemorySummary[];\n}\n\n/** Response from {@link CopilotKitIntelligence.recallMemories}. */\nexport interface RecallMemoriesResponse {\n memories: MemorySummary[];\n}\n\n/**\n * Response from a create ({@link CopilotKitIntelligence.createMemory}) or\n * supersede ({@link CopilotKitIntelligence.updateMemory}) call: the stored\n * memory, plus the operation-specific marker the client store consumes.\n */\nexport interface SaveMemoryResponse extends MemorySummary {\n /** Create only: content was merged into a near-duplicate, not inserted new. */\n absorbed?: boolean;\n /** Supersede only: the id of the memory retired by this call. */\n retiredId?: string;\n}\n\n/**\n * Fields that can be updated on a thread via {@link CopilotKitIntelligence.updateThread}.\n *\n * Additional platform-specific fields can be passed as extra keys and will be\n * forwarded to the PATCH request body.\n */\nexport interface UpdateThreadRequest {\n /** New human-readable display name for the thread. */\n name?: string;\n [key: string]: unknown;\n}\n\n/** Parameters for creating a new thread via {@link CopilotKitIntelligence.createThread}. */\nexport interface CreateThreadRequest {\n /** Client-generated unique identifier for the new thread. */\n threadId: string;\n /** The user creating the thread. Used for authorization and scoping. */\n userId: string;\n /** The agent this thread belongs to. */\n agentId: string;\n /** Optional initial display name. If omitted, the thread is unnamed until explicitly renamed. */\n name?: string;\n}\n\n/** Credentials returned when locking or joining a thread's realtime channel. */\nexport interface ThreadConnectionResponse {\n /** Canonical platform thread identifier for the run or connection. */\n threadId: string;\n /** Canonical platform run identifier for an active run lock. */\n runId?: string;\n /** Short-lived token for authenticating the Phoenix channel join. */\n joinToken: string;\n /** Lock metadata echoed back by the platform. */\n lock?: ThreadLockInfo;\n}\n\nexport interface SubscribeToThreadsRequest {\n userId: string;\n}\n\nexport interface SubscribeToThreadsResponse {\n joinToken: string;\n}\n\nexport interface SubscribeToMemoriesRequest {\n userId: string;\n}\n\n/**\n * Memory subscribe returns both the token and the join code, unlike threads\n * (whose join code reaches the client via the thread-list response). Memory has\n * no list-borne code, so the code is delivered here and used to build the\n * `user_meta:memories:<joinCode>` channel topic.\n */\nexport interface SubscribeToMemoriesResponse {\n joinToken: string;\n joinCode: string;\n /**\n * Project-scoped realtime credentials, minted by the platform only when the\n * caller's API key resolves to a project scope. Absent when project scope is\n * unavailable — a silent-degrade contract: the client then opens only the\n * user channel. When present, the client builds the second\n * `project_meta:memories:<projectJoinCode>` channel topic from them.\n */\n projectJoinToken?: string;\n projectJoinCode?: string;\n}\n\nexport type ConnectThreadResponse = ThreadConnectionResponse | null;\n\nexport interface AcquireThreadLockResponse extends ThreadConnectionResponse {\n /** Canonical platform run identifier for the acquired lock. */\n runId: string;\n}\n\n/**\n * Parameters for annotating a thread event via\n * {@link CopilotKitIntelligence.annotate}. The runtime resolves `userId`\n * from the customer's BFF auth before calling this; the platform prefixes\n * it with the project id at write time.\n *\n * `payload` is the type-specific JSON blob for the annotation (e.g. a\n * `\"user_action\"` event carries the recorded fields, a\n * `\"set_learning_containers\"` event carries the container list). The exact\n * shape per type is validated by the Intelligence backend; canonical shapes\n * are documented on the Intelligence react-core side.\n */\nexport interface AnnotateParams {\n /** The user the annotation belongs to. */\n userId: string;\n /** The thread the annotation is associated with. May be unknown to the platform. */\n threadId: string;\n /**\n * Discriminator identifying the annotation type.\n * Must match a type known to the Intelligence platform\n * (e.g. `\"user_action\"`, `\"set_learning_containers\"`).\n */\n type: string;\n /** Type-specific payload. Shape varies by `type`. */\n payload?: unknown;\n /**\n * Caller-supplied idempotency key (any RFC-compliant UUID). When omitted,\n * a UUID is auto-generated. Every call hits the platform's idempotent\n * `PUT /connector/annotate/:clientEventId` endpoint; a retry with the\n * same id collapses to the original row.\n */\n clientEventId?: string;\n /** ISO-8601 client-asserted timestamp. Defaults to server NOW() when absent. */\n occurredAt?: string;\n}\n\n/** Response from {@link CopilotKitIntelligence.annotate}. */\nexport interface AnnotateResponse {\n /** Database id of the annotation row (BIGINT, returned as a string). */\n id: string;\n /**\n * True when the platform recognized the `clientEventId` as a retry of\n * a previous call and returned the original row id instead of inserting\n * a new one.\n */\n duplicate: boolean;\n}\n\n/** A single message within a thread's persisted history. */\nexport interface ThreadMessage {\n /** Unique identifier for this message. */\n id: string;\n /** Message role, e.g. `\"user\"`, `\"assistant\"`, `\"tool\"`. */\n role: string;\n /** Text content of the message. May be absent for tool-call-only messages. */\n content?: string;\n /** Tool calls initiated by this message (assistant role only). */\n toolCalls?: Array<{\n id: string;\n name: string;\n /** JSON-encoded arguments passed to the tool. */\n args: string;\n }>;\n /** For tool-result messages, the ID of the tool call this message responds to. */\n toolCallId?: string;\n}\n\n/** Response from {@link CopilotKitIntelligence.getThreadMessages}. */\nexport interface ThreadMessagesResponse {\n messages: ThreadMessage[];\n}\n\n/**\n * Persisted AG-UI event for the inspector's debugging views. The platform\n * stores raw events keyed by run; the `_inspect` route returns them in\n * replay order (oldest first) across every run that targeted the thread.\n */\nexport interface ThreadInspectEvent {\n type: string;\n [key: string]: unknown;\n}\n\n/**\n * Response from {@link CopilotKitIntelligence.getThreadEvents}. Mirrors the\n * `ThreadEventsResult` shape returned by the platform's\n * `GET /api/_inspect/threads/:id/events` endpoint.\n */\nexport interface ThreadEventsResponse {\n events: ThreadInspectEvent[];\n /** Row IDs the platform failed to decode (raw column corrupted). */\n decodeErrorRowIds: string[];\n /** True when the platform hit its per-thread event cap. */\n truncated: boolean;\n}\n\n/**\n * Response from {@link CopilotKitIntelligence.getThreadState}. Mirrors the\n * discriminated `ThreadStateResult` returned by the platform's\n * `GET /api/_inspect/threads/:id/state` endpoint, which folds RFC 6902\n * STATE_DELTA events on top of the latest STATE_SNAPSHOT.\n */\nexport type ThreadStateResponse =\n | { kind: \"no-snapshot\" }\n | { kind: \"snapshot-decode-error\" }\n | { kind: \"snapshot\"; state: unknown; skippedDeltas: number };\n\nexport interface AcquireThreadLockRequest {\n threadId: string;\n runId: string;\n userId: string;\n agentId: string;\n /** Custom Redis key prefix for the lock (default: \"thread\"). */\n lockKeyPrefix?: string;\n /** Lock TTL in seconds. When set, the lock auto-expires after this duration. */\n ttlSeconds?: number;\n}\n\nexport interface RenewThreadLockRequest {\n threadId: string;\n runId: string;\n /** New TTL to set on the lock in seconds. */\n ttlSeconds: number;\n /** Must match the prefix used when acquiring. */\n lockKeyPrefix?: string;\n}\n\nexport interface CleanupThreadLockRequest {\n threadId: string;\n runId: string;\n}\n\nexport interface RenewThreadLockResponse {\n ttlSeconds: number;\n}\n\nexport interface ThreadLockInfo {\n key: string;\n ttlSeconds: number | null;\n}\n\ninterface ThreadEnvelope {\n thread: ThreadSummary;\n}\n\n/**\n * Client for the CopilotKit Intelligence Platform REST API.\n *\n * Construct the client once and pass it to any consumers that need it\n * (e.g. `CopilotRuntime`, `IntelligenceAgentRunner`):\n *\n * ```ts\n * import { CopilotKitIntelligence, CopilotRuntime } from \"@copilotkit/runtime\";\n *\n * const intelligence = new CopilotKitIntelligence({\n * apiKey: process.env.COPILOTKIT_API_KEY!,\n * });\n *\n * const runtime = new CopilotRuntime({\n * agents,\n * intelligence,\n * });\n * ```\n *\n * `apiUrl` and `wsUrl` default to CopilotKit's managed Intelligence platform.\n * Override both together to target a self-hosted or non-production deployment:\n *\n * ```ts\n * const intelligence = new CopilotKitIntelligence({\n * apiUrl: \"https://intelligence.internal\",\n * wsUrl: \"wss://realtime.intelligence.internal\",\n * apiKey: process.env.COPILOTKIT_API_KEY!,\n * });\n * ```\n */\nexport class CopilotKitIntelligence {\n #apiUrl: string;\n #runnerWsUrl: string;\n #clientWsUrl: string;\n #apiKey: string;\n #enterpriseLearningEnabled: boolean;\n #threadCreatedListeners = new Set<(thread: ThreadSummary) => void>();\n #threadUpdatedListeners = new Set<(thread: ThreadSummary) => void>();\n #threadDeletedListeners = new Set<(params: ThreadDeletedPayload) => void>();\n\n constructor(config: CopilotKitIntelligenceConfig) {\n const configuredApiUrl = configuredUrl(config.apiUrl);\n const configuredWsUrl = configuredUrl(config.wsUrl);\n warnOnPartialHostOverride(configuredApiUrl, configuredWsUrl);\n\n const intelligenceWsUrl = normalizeIntelligenceWsUrl(\n configuredWsUrl ?? MANAGED_INTELLIGENCE_WS_URL,\n );\n\n this.#apiUrl = (configuredApiUrl ?? MANAGED_INTELLIGENCE_API_URL).replace(\n /\\/$/,\n \"\",\n );\n this.#runnerWsUrl = deriveRunnerWsUrl(intelligenceWsUrl);\n this.#clientWsUrl = deriveClientWsUrl(intelligenceWsUrl);\n this.#apiKey = config.apiKey;\n this.#enterpriseLearningEnabled = config.enableEnterpriseLearning ?? false;\n\n if (config.onThreadCreated) {\n this.onThreadCreated(config.onThreadCreated);\n }\n if (config.onThreadUpdated) {\n this.onThreadUpdated(config.onThreadUpdated);\n }\n if (config.onThreadDeleted) {\n this.onThreadDeleted(config.onThreadDeleted);\n }\n }\n\n /**\n * Register a listener invoked whenever a thread is created.\n *\n * Multiple listeners can be registered. Each call returns an unsubscribe\n * function that removes the listener when called.\n *\n * @param callback - Receives the newly created {@link ThreadSummary}.\n * @returns A function that removes this listener when called.\n *\n * @example\n * ```ts\n * const unsubscribe = intelligence.onThreadCreated((thread) => {\n * console.log(\"Thread created:\", thread.id);\n * });\n * // later…\n * unsubscribe();\n * ```\n */\n onThreadCreated(callback: (thread: ThreadSummary) => void): () => void {\n this.#threadCreatedListeners.add(callback);\n return () => {\n this.#threadCreatedListeners.delete(callback);\n };\n }\n\n /**\n * Register a listener invoked whenever a thread is updated (including archive).\n *\n * Multiple listeners can be registered. Each call returns an unsubscribe\n * function that removes the listener when called.\n *\n * @param callback - Receives the updated {@link ThreadSummary}.\n * @returns A function that removes this listener when called.\n */\n onThreadUpdated(callback: (thread: ThreadSummary) => void): () => void {\n this.#threadUpdatedListeners.add(callback);\n return () => {\n this.#threadUpdatedListeners.delete(callback);\n };\n }\n\n /**\n * Register a listener invoked whenever a thread is deleted.\n *\n * Multiple listeners can be registered. Each call returns an unsubscribe\n * function that removes the listener when called.\n *\n * @param callback - Receives the {@link ThreadDeletedPayload} identifying\n * the deleted thread.\n * @returns A function that removes this listener when called.\n */\n onThreadDeleted(\n callback: (params: ThreadDeletedPayload) => void,\n ): () => void {\n this.#threadDeletedListeners.add(callback);\n return () => {\n this.#threadDeletedListeners.delete(callback);\n };\n }\n\n ɵgetApiUrl(): string {\n return this.#apiUrl;\n }\n\n ɵgetRunnerWsUrl(): string {\n return this.#runnerWsUrl;\n }\n\n ɵgetClientWsUrl(): string {\n return this.#clientWsUrl;\n }\n\n ɵgetRunnerAuthToken(): string {\n return this.#apiKey;\n }\n\n /** @internal Used by `attachIntelligenceEnterpriseLearning` to populate `Authorization`. */\n ɵgetApiKey(): string {\n return this.#apiKey;\n }\n\n /** @internal Used by `attachIntelligenceEnterpriseLearning` to gate MCP attachment. */\n ɵisEnterpriseLearningEnabled(): boolean {\n return this.#enterpriseLearningEnabled;\n }\n\n async #request<T>(\n method: string,\n path: string,\n body?: unknown,\n extraHeaders?: Record<string, string>,\n ): Promise<T> {\n const url = `${this.#apiUrl}${path}`;\n\n const headers: Record<string, string> = {\n Authorization: `Bearer ${this.#apiKey}`,\n \"Content-Type\": \"application/json\",\n ...extraHeaders,\n };\n\n const response = await fetch(url, {\n method,\n headers,\n body: body ? JSON.stringify(body) : undefined,\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n logger.error(\n { status: response.status, body: text, path },\n \"Intelligence platform request failed\",\n );\n throw new PlatformRequestError(\n `Intelligence platform error ${response.status}: ${text || response.statusText}`,\n response.status,\n );\n }\n\n const text = await response.text();\n if (!text) {\n return undefined as T;\n }\n return JSON.parse(text) as T;\n }\n\n #invokeLifecycleCallback(\n callbackName: \"onThreadCreated\" | \"onThreadUpdated\" | \"onThreadDeleted\",\n payload: ThreadSummary | ThreadDeletedPayload,\n ): void {\n const listeners =\n callbackName === \"onThreadCreated\"\n ? this.#threadCreatedListeners\n : callbackName === \"onThreadUpdated\"\n ? this.#threadUpdatedListeners\n : this.#threadDeletedListeners;\n\n for (const callback of listeners) {\n try {\n (callback as (p: typeof payload) => void)(payload);\n } catch (error) {\n logger.error(\n { err: error, callbackName, payload },\n \"Intelligence lifecycle callback failed\",\n );\n }\n }\n }\n\n /**\n * List all non-archived threads for a given user and agent.\n *\n * @param params.userId - User whose threads to list.\n * @param params.agentId - Agent whose threads to list.\n * @returns The thread list along with realtime subscription credentials.\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async listThreads(params: {\n userId: string;\n agentId: string;\n includeArchived?: boolean;\n limit?: number;\n cursor?: string;\n }): Promise<ListThreadsResponse> {\n const query: Record<string, string> = {\n userId: params.userId,\n agentId: params.agentId,\n };\n if (params.includeArchived) query.includeArchived = \"true\";\n if (params.limit != null) query.limit = String(params.limit);\n if (params.cursor) query.cursor = params.cursor;\n\n const qs = new URLSearchParams(query).toString();\n return this.#request<ListThreadsResponse>(\"GET\", `/api/threads?${qs}`);\n }\n\n /**\n * List the given user's long-term memories, newest first.\n *\n * The platform scopes by the opaque app user supplied in the\n * `x-cpki-user-id` header (resolved by the runtime via `identifyUser`),\n * not a query param. Pass `includeInvalidated` to also return retired rows.\n *\n * @returns The `{ memories }` envelope the client memory store consumes.\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async listMemories(params: {\n userId: string;\n includeInvalidated?: boolean;\n }): Promise<ListMemoriesResponse> {\n const qs = params.includeInvalidated ? \"?includeInvalidated=true\" : \"\";\n return this.#request<ListMemoriesResponse>(\n \"GET\",\n `/api/memories${qs}`,\n undefined,\n { [INTELLIGENCE_USER_ID_HEADER]: params.userId },\n );\n }\n\n /**\n * Create a memory for the given user (platform `POST /api/memories`).\n * @returns The stored memory; `absorbed` is true if the content was merged\n * into a near-duplicate rather than inserted as a new row.\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async createMemory(params: {\n userId: string;\n content: string;\n kind: string;\n /** Optional: when omitted, the platform applies its default (`\"user\"`). */\n scope?: string;\n sourceThreadIds?: string[];\n }): Promise<SaveMemoryResponse> {\n return this.#request<SaveMemoryResponse>(\n \"POST\",\n `/api/memories`,\n {\n content: params.content,\n kind: params.kind,\n ...(params.scope !== undefined ? { scope: params.scope } : {}),\n sourceThreadIds: params.sourceThreadIds ?? [],\n },\n { [INTELLIGENCE_USER_ID_HEADER]: params.userId },\n );\n }\n\n /**\n * Supersede an existing memory (platform `PATCH /api/memories/:id`). The\n * `:id` row is retired and a new memory with the supplied content is\n * inserted atomically.\n * @returns The new memory plus `retiredId` (the id of the retired row).\n * @throws {@link PlatformRequestError} on non-2xx responses (e.g. 404 when\n * `:id` is not a live, same-scope memory for this user).\n */\n async updateMemory(params: {\n userId: string;\n id: string;\n content: string;\n kind: string;\n /** Optional: when omitted, the platform applies its default (`\"user\"`). */\n scope?: string;\n sourceThreadIds?: string[];\n }): Promise<SaveMemoryResponse> {\n return this.#request<SaveMemoryResponse>(\n \"PATCH\",\n `/api/memories/${encodeURIComponent(params.id)}`,\n {\n content: params.content,\n kind: params.kind,\n ...(params.scope !== undefined ? { scope: params.scope } : {}),\n sourceThreadIds: params.sourceThreadIds ?? [],\n },\n { [INTELLIGENCE_USER_ID_HEADER]: params.userId },\n );\n }\n\n /**\n * Non-lossily retire (forget) a memory (platform `DELETE /api/memories/:id`).\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async removeMemory(params: { userId: string; id: string }): Promise<void> {\n await this.#request<void>(\n \"DELETE\",\n `/api/memories/${encodeURIComponent(params.id)}`,\n undefined,\n { [INTELLIGENCE_USER_ID_HEADER]: params.userId },\n );\n }\n\n /**\n * Semantically recall the given user's memories (platform `POST\n * /api/memories/recall`, hybrid RAG). Each returned memory carries a\n * relevance `score`. `scope` narrows to `\"user\"`/`\"project\"`; omitted → platform default.\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async recallMemories(params: {\n userId: string;\n query: string;\n limit?: number;\n scope?: string;\n }): Promise<RecallMemoriesResponse> {\n return this.#request<RecallMemoriesResponse>(\n \"POST\",\n `/api/memories/recall`,\n {\n query: params.query,\n ...(params.limit !== undefined ? { limit: params.limit } : {}),\n ...(params.scope !== undefined ? { scope: params.scope } : {}),\n },\n { [INTELLIGENCE_USER_ID_HEADER]: params.userId },\n );\n }\n\n async ɵsubscribeToThreads(\n params: SubscribeToThreadsRequest,\n ): Promise<SubscribeToThreadsResponse> {\n return this.#request<SubscribeToThreadsResponse>(\n \"POST\",\n \"/api/threads/subscribe\",\n {\n userId: params.userId,\n },\n );\n }\n\n /**\n * Mint memory-realtime join credentials (platform `POST\n * /api/memories/subscribe`). Returns both the single-use `joinToken` and the\n * per-user `joinCode` the client needs to build the\n * `user_meta:memories:<joinCode>` channel topic. When the platform also\n * resolves a project scope it returns optional `projectJoinToken` /\n * `projectJoinCode`; both are passed through verbatim (omitted when absent,\n * the silent-degrade contract).\n *\n * The user is supplied via the `x-cpki-user-id` header — the same way every\n * other memory endpoint (`listMemories`/`createMemory`/…) identifies the app\n * user — because the platform's memory routes resolve identity from that\n * header, not the body. (This differs from `ɵsubscribeToThreads`, whose\n * platform endpoint reads `userId` from the body.)\n *\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async ɵsubscribeToMemories(\n params: SubscribeToMemoriesRequest,\n ): Promise<SubscribeToMemoriesResponse> {\n return this.#request<SubscribeToMemoriesResponse>(\n \"POST\",\n \"/api/memories/subscribe\",\n undefined,\n { [INTELLIGENCE_USER_ID_HEADER]: params.userId },\n );\n }\n\n /**\n * Update thread metadata (e.g. name).\n *\n * Triggers the `onThreadUpdated` lifecycle callback on success.\n *\n * @returns The updated thread summary.\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async updateThread(params: {\n threadId: string;\n userId: string;\n agentId: string;\n updates: UpdateThreadRequest;\n }): Promise<ThreadSummary> {\n const response = await this.#request<ThreadEnvelope>(\n \"PATCH\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n {\n userId: params.userId,\n agentId: params.agentId,\n ...params.updates,\n },\n );\n this.#invokeLifecycleCallback(\"onThreadUpdated\", response.thread);\n return response.thread;\n }\n\n /**\n * Create a new thread on the platform.\n *\n * Triggers the `onThreadCreated` lifecycle callback on success.\n *\n * @returns The newly created thread summary.\n * @throws {@link PlatformRequestError} with status 409 if a thread with the\n * same `threadId` already exists.\n */\n async createThread(params: CreateThreadRequest): Promise<ThreadSummary> {\n const response = await this.#request<ThreadEnvelope>(\n \"POST\",\n `/api/threads`,\n {\n threadId: params.threadId,\n userId: params.userId,\n agentId: params.agentId,\n ...(params.name !== undefined ? { name: params.name } : {}),\n },\n );\n this.#invokeLifecycleCallback(\"onThreadCreated\", response.thread);\n return response.thread;\n }\n\n /**\n * Fetch a single thread by ID.\n *\n * @returns The thread summary.\n * @throws {@link PlatformRequestError} with status 404 if the thread does\n * not exist.\n */\n async getThread(params: {\n threadId: string;\n userId: string;\n }): Promise<ThreadSummary> {\n const qs = new URLSearchParams({ userId: params.userId }).toString();\n const response = await this.#request<ThreadEnvelope>(\n \"GET\",\n `/api/threads/${encodeURIComponent(params.threadId)}?${qs}`,\n );\n return response.thread;\n }\n\n /**\n * Get an existing thread or create it if it does not exist.\n *\n * Handles the race where a concurrent request creates the thread between\n * the initial 404 and the subsequent `createThread` call by catching the\n * 409 Conflict and retrying the get.\n *\n * Triggers the `onThreadCreated` lifecycle callback when a new thread is\n * created.\n *\n * @returns An object containing the thread and a `created` flag indicating\n * whether the thread was newly created (`true`) or already existed (`false`).\n * @throws {@link PlatformRequestError} on non-2xx responses other than\n * 404 (get) and 409 (create race).\n */\n async getOrCreateThread(\n params: CreateThreadRequest,\n ): Promise<{ thread: ThreadSummary; created: boolean }> {\n try {\n const thread = await this.getThread({\n threadId: params.threadId,\n userId: params.userId,\n });\n return { thread, created: false };\n } catch (error) {\n if (!(error instanceof PlatformRequestError && error.status === 404)) {\n throw error;\n }\n }\n\n try {\n const thread = await this.createThread(params);\n return { thread, created: true };\n } catch (error) {\n // Another request created the thread between our get and create — retry get.\n if (error instanceof PlatformRequestError && error.status === 409) {\n const thread = await this.getThread({\n threadId: params.threadId,\n userId: params.userId,\n });\n return { thread, created: false };\n }\n throw error;\n }\n }\n\n /**\n * Fetch the full message history for a thread.\n *\n * @returns All persisted messages in chronological order.\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async getThreadMessages(params: {\n threadId: string;\n userId: string;\n }): Promise<ThreadMessagesResponse> {\n const qs = new URLSearchParams({ userId: params.userId }).toString();\n return this.#request<ThreadMessagesResponse>(\n \"GET\",\n `/api/threads/${encodeURIComponent(params.threadId)}/messages?${qs}`,\n );\n }\n\n /**\n * Fetch the persisted AG-UI event stream for a thread.\n *\n * Backed by the platform's `GET /api/_inspect/threads/:id/events`\n * introspection endpoint (see Intelligence PR #144). Events are returned\n * in replay order across every run that targeted the thread. The\n * `_inspect/` prefix flags this as debug-only — production code paths\n * must not depend on it.\n *\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async getThreadEvents(params: {\n threadId: string;\n }): Promise<ThreadEventsResponse> {\n return this.#request<ThreadEventsResponse>(\n \"GET\",\n `/api/_inspect/threads/${encodeURIComponent(params.threadId)}/events`,\n );\n }\n\n /**\n * Fetch the current agent state for a thread.\n *\n * Backed by the platform's `GET /api/_inspect/threads/:id/state`\n * introspection endpoint (see Intelligence PR #144). The platform folds\n * RFC 6902 STATE_DELTA events on top of the latest STATE_SNAPSHOT, so\n * the returned state reflects the thread's current state — not just the\n * last snapshot. The discriminated response distinguishes \"no snapshot\n * persisted yet\" from \"snapshot present\" so consumers can render the\n * correct empty state.\n *\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async getThreadState(params: {\n threadId: string;\n }): Promise<ThreadStateResponse> {\n return this.#request<ThreadStateResponse>(\n \"GET\",\n `/api/_inspect/threads/${encodeURIComponent(params.threadId)}/state`,\n );\n }\n\n /**\n * Mark a thread as archived.\n *\n * Archived threads are excluded from {@link listThreads} results.\n * Triggers the `onThreadUpdated` lifecycle callback on success.\n *\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async archiveThread(params: {\n threadId: string;\n userId: string;\n agentId: string;\n }): Promise<void> {\n const response = await this.#request<ThreadEnvelope>(\n \"PATCH\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n { userId: params.userId, agentId: params.agentId, archived: true },\n );\n this.#invokeLifecycleCallback(\"onThreadUpdated\", response.thread);\n }\n\n /**\n * Permanently delete a thread and its message history.\n *\n * This is irreversible. Triggers the `onThreadDeleted` lifecycle callback\n * on success.\n *\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async deleteThread(params: {\n threadId: string;\n userId: string;\n agentId: string;\n }): Promise<void> {\n await this.#request<void>(\n \"DELETE\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n {\n userId: params.userId,\n agentId: params.agentId,\n reason: `Deleted via CopilotKit runtime (userId=${params.userId}, agentId=${params.agentId})`,\n },\n );\n this.#invokeLifecycleCallback(\"onThreadDeleted\", params);\n }\n\n /**\n * Annotate a thread event on the Intelligence platform's general annotation\n * endpoint (`PUT /connector/annotate/:clientEventId`).\n *\n * This is the generalized replacement for the old\n * `PUT /connector/user-actions/record/:clientEventId` endpoint. It supports\n * multiple annotation types via the `type` discriminator:\n * - `\"user_action\"` — records a user UI interaction for the self-learning loop.\n * - `\"set_learning_containers\"` — sets the learning containers for a thread.\n *\n * `userId` must be resolved on the runtime side before calling this — the\n * platform prefixes it with the project id from the API key.\n *\n * Always hits the idempotent `PUT /connector/annotate/:clientEventId`\n * endpoint. A retry with the same `clientEventId` returns\n * `{ id: <original>, duplicate: true }` instead of creating a new row.\n * When `clientEventId` is omitted, a UUID is auto-generated for this call.\n *\n * @throws {@link PlatformRequestError} on non-2xx responses, OR when the\n * platform returns an empty 2xx body (which would otherwise corrupt the\n * caller's typed result).\n */\n async annotate(params: AnnotateParams): Promise<AnnotateResponse> {\n const clientEventId = params.clientEventId ?? randomUUID();\n const path = `/connector/annotate/${encodeURIComponent(clientEventId)}`;\n const body: Record<string, unknown> = {\n type: params.type,\n userId: params.userId,\n threadId: params.threadId,\n };\n if (params.payload !== undefined) {\n body.payload = params.payload;\n }\n if (params.occurredAt !== undefined) {\n body.occurredAt = params.occurredAt;\n }\n const response = await this.#request<AnnotateResponse | null | undefined>(\n \"PUT\",\n path,\n body,\n );\n // `== null` catches both `undefined` (empty body from `#request`)\n // and JSON `null` (which would otherwise corrupt the typed result\n // and surface as a `TypeError` deep in caller code).\n if (response == null) {\n logger.error(\n { path },\n \"annotate: Intelligence platform returned 200 with empty or null body\",\n );\n throw new PlatformRequestError(\n \"annotate: empty or null response body from Intelligence platform\",\n 502,\n );\n }\n return response;\n }\n\n async ɵacquireThreadLock(\n params: AcquireThreadLockRequest,\n ): Promise<AcquireThreadLockResponse> {\n return this.#request<AcquireThreadLockResponse>(\n \"POST\",\n `/api/threads/${encodeURIComponent(params.threadId)}/lock`,\n {\n runId: params.runId,\n userId: params.userId,\n agentId: params.agentId,\n ...(params.lockKeyPrefix !== undefined\n ? { lockKeyPrefix: params.lockKeyPrefix }\n : {}),\n ...(params.ttlSeconds !== undefined\n ? { ttlSeconds: params.ttlSeconds }\n : {}),\n },\n );\n }\n\n async ɵcleanupThreadLock(params: CleanupThreadLockRequest): Promise<void> {\n return this.#request<void>(\n \"DELETE\",\n `/api/threads/${encodeURIComponent(params.threadId)}/lock`,\n {\n runId: params.runId,\n },\n );\n }\n\n async ɵrenewThreadLock(\n params: RenewThreadLockRequest,\n ): Promise<RenewThreadLockResponse> {\n return this.#request<RenewThreadLockResponse>(\n \"PATCH\",\n `/api/threads/${encodeURIComponent(params.threadId)}/lock`,\n {\n runId: params.runId,\n ttlSeconds: params.ttlSeconds,\n ...(params.lockKeyPrefix !== undefined\n ? { lockKeyPrefix: params.lockKeyPrefix }\n : {}),\n },\n );\n }\n\n async ɵgetActiveJoinCode(params: {\n threadId: string;\n userId: string;\n }): Promise<ThreadConnectionResponse> {\n const qs = new URLSearchParams({ userId: params.userId }).toString();\n return this.#request<ThreadConnectionResponse>(\n \"GET\",\n `/api/threads/${encodeURIComponent(params.threadId)}/join-code?${qs}`,\n );\n }\n\n async ɵconnectThread(params: {\n threadId: string;\n userId: string;\n agentId: string;\n }): Promise<ConnectThreadResponse> {\n const result = await this.#request<ThreadConnectionResponse>(\n \"POST\",\n `/api/threads/${encodeURIComponent(params.threadId)}/connect`,\n {\n userId: params.userId,\n agentId: params.agentId,\n },\n );\n\n // request() returns undefined for empty/204 responses\n return result ?? null;\n }\n}\n\n/**\n * Normalize a configured URL to \"provided\" or \"not provided\". A blank string\n * counts as not provided: these URLs are typically wired from environment\n * variables, and a declared-but-empty variable (`COPILOTKIT_INTELLIGENCE_URL=`,\n * common in generated `.env` files and container configs) arrives as `\"\"`. Left\n * as-is it would produce host-relative requests instead of falling back to the\n * managed platform.\n */\nfunction configuredUrl(url: string | undefined): string | undefined {\n const trimmed = url?.trim();\n return trimmed ? trimmed : undefined;\n}\n\n/**\n * Warn when exactly one of `apiUrl`/`wsUrl` is configured. The API and realtime\n * planes are separate hosts, so a lone override silently leaves the other plane\n * on CopilotKit's managed platform — a self-hosted API paired with the managed\n * gateway (or vice versa), which fails as a hang rather than an error.\n */\nfunction warnOnPartialHostOverride(\n apiUrl: string | undefined,\n wsUrl: string | undefined,\n): void {\n if (apiUrl && !wsUrl) {\n logger.warn(\n `CopilotKitIntelligence: apiUrl is set to \"${apiUrl}\" but wsUrl is not, ` +\n `so wsUrl falls back to the managed default \"${MANAGED_INTELLIGENCE_WS_URL}\". ` +\n `The API and realtime planes are separate hosts — set both when pointing at a self-hosted deployment.`,\n );\n return;\n }\n\n if (wsUrl && !apiUrl) {\n logger.warn(\n `CopilotKitIntelligence: wsUrl is set to \"${wsUrl}\" but apiUrl is not, ` +\n `so apiUrl falls back to the managed default \"${MANAGED_INTELLIGENCE_API_URL}\". ` +\n `The API and realtime planes are separate hosts — set both when pointing at a self-hosted deployment.`,\n );\n }\n}\n\nfunction normalizeIntelligenceWsUrl(wsUrl: string): string {\n return wsUrl.replace(/\\/$/, \"\");\n}\n\nfunction deriveRunnerWsUrl(wsUrl: string): string {\n if (wsUrl.endsWith(\"/runner\")) {\n return wsUrl;\n }\n\n if (wsUrl.endsWith(\"/client\")) {\n return `${wsUrl.slice(0, -\"/client\".length)}/runner`;\n }\n\n return `${wsUrl}/runner`;\n}\n\nfunction deriveClientWsUrl(wsUrl: string): string {\n if (wsUrl.endsWith(\"/client\")) {\n return wsUrl;\n }\n\n if (wsUrl.endsWith(\"/runner\")) {\n return `${wsUrl.slice(0, -\"/runner\".length)}/client`;\n }\n\n return `${wsUrl}/client`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAaA,MAAa,8BAA8B;;;;;AAM3C,MAAM,+BAA+B;;;;;;;;AASrC,MAAM,8BAA8B;;;;;;;;;;;;;;;;;;AAmBpC,IAAa,uBAAb,cAA0C,MAAM;CAC9C,YACE,SAEA,AAAgB,QAChB;AACA,QAAM,QAAQ;EAFE;AAGhB,OAAK,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8YhB,IAAa,yBAAb,MAAoC;CAClC;CACA;CACA;CACA;CACA;CACA,0CAA0B,IAAI,KAAsC;CACpE,0CAA0B,IAAI,KAAsC;CACpE,0CAA0B,IAAI,KAA6C;CAE3E,YAAY,QAAsC;EAChD,MAAM,mBAAmB,cAAc,OAAO,OAAO;EACrD,MAAM,kBAAkB,cAAc,OAAO,MAAM;AACnD,4BAA0B,kBAAkB,gBAAgB;EAE5D,MAAM,oBAAoB,2BACxB,mBAAmB,4BACpB;AAED,QAAKA,UAAW,oBAAoB,8BAA8B,QAChE,OACA,GACD;AACD,QAAKC,cAAe,kBAAkB,kBAAkB;AACxD,QAAKC,cAAe,kBAAkB,kBAAkB;AACxD,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AAS,UAAU,CAC3B,QAAO,GAAG,MAAM,MAAM,GAAG,GAAkB,CAAC;AAG9C,QAAO,GAAG,MAAM"}
|
|
1
|
+
{"version":3,"file":"client.cjs","names":["#apiUrl","#runnerWsUrl","#clientWsUrl","#channelsWsUrl","#apiKey","#enterpriseLearningEnabled","#threadCreatedListeners","#threadUpdatedListeners","#threadDeletedListeners","#request","#invokeLifecycleCallback"],"sources":["../../../../src/v2/runtime/intelligence-platform/client.ts"],"sourcesContent":["import { logger } from \"@copilotkit/shared\";\nimport { randomUUID } from \"crypto\";\n\n/**\n * Header name carrying the per-call end-user identity that the CopilotKit\n * Intelligence `/mcp` endpoint requires. Internal CopilotKit machinery —\n * `attachIntelligenceEnterpriseLearning` resolves the user via `identifyUser`\n * and bakes this header onto the `MCPMiddleware`'s transport config, so every\n * outbound MCP request stamps `X-Cpki-User-Id: <userId>`. Not part of the\n * public user API.\n *\n * @internal\n */\nexport const INTELLIGENCE_USER_ID_HEADER = \"x-cpki-user-id\";\n\n/**\n * REST base URL of CopilotKit's managed Intelligence platform — the default\n * when {@link CopilotKitIntelligenceConfig.apiUrl} is omitted.\n */\nconst MANAGED_INTELLIGENCE_API_URL = \"https://api.intelligence.copilotkit.ai\";\n\n/**\n * Websocket base URL of CopilotKit's managed Intelligence platform — the\n * default when {@link CopilotKitIntelligenceConfig.wsUrl} is omitted.\n *\n * A different host from {@link MANAGED_INTELLIGENCE_API_URL}: the API and\n * realtime planes are deployed separately.\n */\nconst MANAGED_INTELLIGENCE_WS_URL = \"wss://realtime.intelligence.copilotkit.ai\";\n\n/**\n * Error thrown when an Intelligence platform HTTP request returns a non-2xx\n * status. Carries the HTTP {@link status} code so callers can branch on\n * specific failures (e.g. 404 for \"not found\", 409 for \"conflict\") without\n * parsing the error message string.\n *\n * @example\n * ```ts\n * try {\n * await intelligence.getThread({ threadId, userId });\n * } catch (error) {\n * if (error instanceof PlatformRequestError && error.status === 404) {\n * // thread does not exist yet\n * }\n * }\n * ```\n */\nexport class PlatformRequestError extends Error {\n constructor(\n message: string,\n /** The HTTP status code returned by the platform (e.g. 404, 409, 500). */\n public readonly status: number,\n ) {\n super(message);\n this.name = \"PlatformRequestError\";\n }\n}\n\n/** Payload passed to `onThreadDeleted` listeners. */\nexport interface ThreadDeletedPayload {\n threadId: string;\n userId: string;\n agentId: string;\n}\n\nexport interface CopilotKitIntelligenceConfig {\n /**\n * Base URL of the intelligence platform API.\n *\n * Defaults to CopilotKit's managed platform,\n * `https://api.intelligence.copilotkit.ai`. Set it only when pointing at a\n * self-hosted or non-production deployment — and set {@link wsUrl} with it.\n */\n apiUrl?: string;\n /**\n * Intelligence websocket base URL. Runner and client socket URLs are derived\n * from this by appending `/runner` or `/client`, so pass the bare base.\n *\n * Defaults to CopilotKit's managed platform,\n * `wss://realtime.intelligence.copilotkit.ai`.\n *\n * This is a DIFFERENT host from {@link apiUrl} — the API and realtime planes are\n * deployed separately — so it cannot be derived by scheme-swapping `apiUrl`.\n * Overriding one without the other therefore points the two planes at\n * different deployments, which logs a warning.\n */\n wsUrl?: string;\n /** API key for authenticating with the intelligence platform */\n apiKey: string;\n /**\n * Enable Enterprise Learning — expose the Intelligence platform's\n * built-in tools (bash + thread/memory tools) to agent runs on an\n * intelligence runtime that resolve a user. Attached uniformly across\n * agent frameworks by `attachIntelligenceEnterpriseLearning` via\n * `@ag-ui/mcp-middleware`, with the resolved user-id and project apiKey\n * baked into the transport headers for that request's clone.\n *\n * Defaults to `false` — opt-in. Existing intelligence setups continue\n * to work without these tools unless they flip this flag.\n */\n enableEnterpriseLearning?: boolean;\n /**\n * Initial listener invoked after a thread is created.\n * Prefer {@link CopilotKitIntelligence.onThreadCreated} for multiple listeners.\n */\n onThreadCreated?: (thread: ThreadSummary) => void;\n /**\n * Initial listener invoked after a thread is updated.\n * Prefer {@link CopilotKitIntelligence.onThreadUpdated} for multiple listeners.\n */\n onThreadUpdated?: (thread: ThreadSummary) => void;\n /**\n * Initial listener invoked after a thread is deleted.\n * Prefer {@link CopilotKitIntelligence.onThreadDeleted} for multiple listeners.\n */\n onThreadDeleted?: (params: ThreadDeletedPayload) => void;\n}\n\n/**\n * Summary metadata for a single thread returned by the platform.\n *\n * This is the shape returned by list, get, create, and update operations.\n * It does not include the thread's message history — use\n * {@link CopilotKitIntelligence.getThreadMessages} for that.\n */\nexport interface ThreadSummary {\n /** Platform-assigned unique identifier. */\n id: string;\n /** Human-readable display name, or `null` if the thread has not been named. */\n name: string | null;\n /** ISO-8601 timestamp of the most recent agent run on this thread. */\n lastRunAt?: string;\n /** ISO-8601 timestamp of the most recent metadata update. */\n lastUpdatedAt?: string;\n /** ISO-8601 timestamp when the thread was created. */\n createdAt?: string;\n /** ISO-8601 timestamp when the thread was last updated. */\n updatedAt?: string;\n /** Whether the thread has been archived. Archived threads are excluded from default list results. */\n archived?: boolean;\n /** The agent that owns this thread. */\n agentId?: string;\n /** The user who created this thread. */\n createdById?: string;\n /** The organization this thread belongs to. */\n organizationId?: string;\n}\n\n/** Response from listing threads for a user/agent pair. */\nexport interface ListThreadsResponse {\n /** The matching threads, sorted by the platform's default ordering. */\n threads: ThreadSummary[];\n /** Join code for subscribing to realtime metadata updates for these threads. */\n joinCode: string;\n /** Short-lived token for authenticating the realtime subscription. */\n joinToken?: string;\n /** Opaque cursor for fetching the next page. `null` or absent when there are no more pages. */\n nextCursor?: string | null;\n}\n\n/**\n * A single memory as returned by the platform's list endpoint. Mirrors the\n * public projection the client memory store consumes (tenant ids stripped).\n */\nexport interface MemorySummary {\n /** Platform-assigned unique identifier. */\n id: string;\n /** Memory kind, e.g. `\"topical\"`, `\"episodic\"`, `\"operational\"`. */\n kind: string;\n /** Memory scope: `\"user\"` (private) or `\"project\"` (shared). */\n scope: string;\n /** The remembered fact, preference, or procedure. */\n content: string;\n /** Ids of the threads this memory was learned from. */\n sourceThreadIds: string[];\n /** ISO-8601 timestamp when the memory was retired, or `null` if live. */\n invalidatedAt: string | null;\n /** Relevance score from a `recall` (hybrid RAG) query. Present only on recall responses. */\n score?: number;\n}\n\n/** Response from {@link CopilotKitIntelligence.listMemories}. */\nexport interface ListMemoriesResponse {\n memories: MemorySummary[];\n}\n\n/** Response from {@link CopilotKitIntelligence.recallMemories}. */\nexport interface RecallMemoriesResponse {\n memories: MemorySummary[];\n}\n\n/**\n * Response from a create ({@link CopilotKitIntelligence.createMemory}) or\n * supersede ({@link CopilotKitIntelligence.updateMemory}) call: the stored\n * memory, plus the operation-specific marker the client store consumes.\n */\nexport interface SaveMemoryResponse extends MemorySummary {\n /** Create only: content was merged into a near-duplicate, not inserted new. */\n absorbed?: boolean;\n /** Supersede only: the id of the memory retired by this call. */\n retiredId?: string;\n}\n\n/**\n * Fields that can be updated on a thread via {@link CopilotKitIntelligence.updateThread}.\n *\n * Additional platform-specific fields can be passed as extra keys and will be\n * forwarded to the PATCH request body.\n */\nexport interface UpdateThreadRequest {\n /** New human-readable display name for the thread. */\n name?: string;\n [key: string]: unknown;\n}\n\n/** Parameters for creating a new thread via {@link CopilotKitIntelligence.createThread}. */\nexport interface CreateThreadRequest {\n /** Client-generated unique identifier for the new thread. */\n threadId: string;\n /** The user creating the thread. Used for authorization and scoping. */\n userId: string;\n /** The agent this thread belongs to. */\n agentId: string;\n /** Optional initial display name. If omitted, the thread is unnamed until explicitly renamed. */\n name?: string;\n}\n\n/** Credentials returned when locking or joining a thread's realtime channel. */\nexport interface ThreadConnectionResponse {\n /** Canonical platform thread identifier for the run or connection. */\n threadId: string;\n /** Canonical platform run identifier for an active run lock. */\n runId?: string;\n /** Short-lived token for authenticating the Phoenix channel join. */\n joinToken: string;\n /** Lock metadata echoed back by the platform. */\n lock?: ThreadLockInfo;\n}\n\nexport interface SubscribeToThreadsRequest {\n userId: string;\n}\n\nexport interface SubscribeToThreadsResponse {\n joinToken: string;\n}\n\nexport interface SubscribeToMemoriesRequest {\n userId: string;\n}\n\n/**\n * Memory subscribe returns both the token and the join code, unlike threads\n * (whose join code reaches the client via the thread-list response). Memory has\n * no list-borne code, so the code is delivered here and used to build the\n * `user_meta:memories:<joinCode>` channel topic.\n */\nexport interface SubscribeToMemoriesResponse {\n joinToken: string;\n joinCode: string;\n /**\n * Project-scoped realtime credentials, minted by the platform only when the\n * caller's API key resolves to a project scope. Absent when project scope is\n * unavailable — a silent-degrade contract: the client then opens only the\n * user channel. When present, the client builds the second\n * `project_meta:memories:<projectJoinCode>` channel topic from them.\n */\n projectJoinToken?: string;\n projectJoinCode?: string;\n}\n\nexport type ConnectThreadResponse = ThreadConnectionResponse | null;\n\nexport interface AcquireThreadLockResponse extends ThreadConnectionResponse {\n /** Canonical platform run identifier for the acquired lock. */\n runId: string;\n}\n\n/**\n * Parameters for annotating a thread event via\n * {@link CopilotKitIntelligence.annotate}. The runtime resolves `userId`\n * from the customer's BFF auth before calling this; the platform prefixes\n * it with the project id at write time.\n *\n * `payload` is the type-specific JSON blob for the annotation (e.g. a\n * `\"user_action\"` event carries the recorded fields, a\n * `\"set_learning_containers\"` event carries the container list). The exact\n * shape per type is validated by the Intelligence backend; canonical shapes\n * are documented on the Intelligence react-core side.\n */\nexport interface AnnotateParams {\n /** The user the annotation belongs to. */\n userId: string;\n /** The thread the annotation is associated with. May be unknown to the platform. */\n threadId: string;\n /**\n * Discriminator identifying the annotation type.\n * Must match a type known to the Intelligence platform\n * (e.g. `\"user_action\"`, `\"set_learning_containers\"`).\n */\n type: string;\n /** Type-specific payload. Shape varies by `type`. */\n payload?: unknown;\n /**\n * Caller-supplied idempotency key (any RFC-compliant UUID). When omitted,\n * a UUID is auto-generated. Every call hits the platform's idempotent\n * `PUT /connector/annotate/:clientEventId` endpoint; a retry with the\n * same id collapses to the original row.\n */\n clientEventId?: string;\n /** ISO-8601 client-asserted timestamp. Defaults to server NOW() when absent. */\n occurredAt?: string;\n}\n\n/** Response from {@link CopilotKitIntelligence.annotate}. */\nexport interface AnnotateResponse {\n /** Database id of the annotation row (BIGINT, returned as a string). */\n id: string;\n /**\n * True when the platform recognized the `clientEventId` as a retry of\n * a previous call and returned the original row id instead of inserting\n * a new one.\n */\n duplicate: boolean;\n}\n\n/** A single message within a thread's persisted history. */\nexport interface ThreadMessage {\n /** Unique identifier for this message. */\n id: string;\n /** Message role, e.g. `\"user\"`, `\"assistant\"`, `\"tool\"`. */\n role: string;\n /** Text content of the message. May be absent for tool-call-only messages. */\n content?: string;\n /** Tool calls initiated by this message (assistant role only). */\n toolCalls?: Array<{\n id: string;\n name: string;\n /** JSON-encoded arguments passed to the tool. */\n args: string;\n }>;\n /** For tool-result messages, the ID of the tool call this message responds to. */\n toolCallId?: string;\n}\n\n/** Response from {@link CopilotKitIntelligence.getThreadMessages}. */\nexport interface ThreadMessagesResponse {\n messages: ThreadMessage[];\n}\n\n/**\n * Persisted AG-UI event for the inspector's debugging views. The platform\n * stores raw events keyed by run; the `_inspect` route returns them in\n * replay order (oldest first) across every run that targeted the thread.\n */\nexport interface ThreadInspectEvent {\n type: string;\n [key: string]: unknown;\n}\n\n/**\n * Response from {@link CopilotKitIntelligence.getThreadEvents}. Mirrors the\n * `ThreadEventsResult` shape returned by the platform's\n * `GET /api/_inspect/threads/:id/events` endpoint.\n */\nexport interface ThreadEventsResponse {\n events: ThreadInspectEvent[];\n /** Row IDs the platform failed to decode (raw column corrupted). */\n decodeErrorRowIds: string[];\n /** True when the platform hit its per-thread event cap. */\n truncated: boolean;\n}\n\n/**\n * Response from {@link CopilotKitIntelligence.getThreadState}. Mirrors the\n * discriminated `ThreadStateResult` returned by the platform's\n * `GET /api/_inspect/threads/:id/state` endpoint, which folds RFC 6902\n * STATE_DELTA events on top of the latest STATE_SNAPSHOT.\n */\nexport type ThreadStateResponse =\n | { kind: \"no-snapshot\" }\n | { kind: \"snapshot-decode-error\" }\n | { kind: \"snapshot\"; state: unknown; skippedDeltas: number };\n\nexport interface AcquireThreadLockRequest {\n threadId: string;\n runId: string;\n userId: string;\n agentId: string;\n /** Custom Redis key prefix for the lock (default: \"thread\"). */\n lockKeyPrefix?: string;\n /** Lock TTL in seconds. When set, the lock auto-expires after this duration. */\n ttlSeconds?: number;\n}\n\nexport interface RenewThreadLockRequest {\n threadId: string;\n runId: string;\n /** New TTL to set on the lock in seconds. */\n ttlSeconds: number;\n /** Must match the prefix used when acquiring. */\n lockKeyPrefix?: string;\n}\n\nexport interface CleanupThreadLockRequest {\n threadId: string;\n runId: string;\n}\n\nexport interface RenewThreadLockResponse {\n ttlSeconds: number;\n}\n\nexport interface ThreadLockInfo {\n key: string;\n ttlSeconds: number | null;\n}\n\ninterface ThreadEnvelope {\n thread: ThreadSummary;\n}\n\n/**\n * Client for the CopilotKit Intelligence Platform REST API.\n *\n * Construct the client once and pass it to any consumers that need it\n * (e.g. `CopilotRuntime`, `IntelligenceAgentRunner`):\n *\n * ```ts\n * import { CopilotKitIntelligence, CopilotRuntime } from \"@copilotkit/runtime\";\n *\n * const intelligence = new CopilotKitIntelligence({\n * apiKey: process.env.COPILOTKIT_API_KEY!,\n * });\n *\n * const runtime = new CopilotRuntime({\n * agents,\n * intelligence,\n * });\n * ```\n *\n * `apiUrl` and `wsUrl` default to CopilotKit's managed Intelligence platform.\n * Override both together to target a self-hosted or non-production deployment:\n *\n * ```ts\n * const intelligence = new CopilotKitIntelligence({\n * apiUrl: \"https://intelligence.internal\",\n * wsUrl: \"wss://realtime.intelligence.internal\",\n * apiKey: process.env.COPILOTKIT_API_KEY!,\n * });\n * ```\n */\nexport class CopilotKitIntelligence {\n #apiUrl: string;\n #runnerWsUrl: string;\n #clientWsUrl: string;\n #channelsWsUrl: string;\n #apiKey: string;\n #enterpriseLearningEnabled: boolean;\n #threadCreatedListeners = new Set<(thread: ThreadSummary) => void>();\n #threadUpdatedListeners = new Set<(thread: ThreadSummary) => void>();\n #threadDeletedListeners = new Set<(params: ThreadDeletedPayload) => void>();\n\n constructor(config: CopilotKitIntelligenceConfig) {\n const configuredApiUrl = configuredUrl(config.apiUrl);\n const configuredWsUrl = configuredUrl(config.wsUrl);\n warnOnPartialHostOverride(configuredApiUrl, configuredWsUrl);\n\n const intelligenceWsUrl = normalizeIntelligenceWsUrl(\n configuredWsUrl ?? MANAGED_INTELLIGENCE_WS_URL,\n );\n\n this.#apiUrl = (configuredApiUrl ?? MANAGED_INTELLIGENCE_API_URL).replace(\n /\\/$/,\n \"\",\n );\n this.#runnerWsUrl = deriveRunnerWsUrl(intelligenceWsUrl);\n this.#clientWsUrl = deriveClientWsUrl(intelligenceWsUrl);\n this.#channelsWsUrl = deriveChannelsWsUrl(intelligenceWsUrl);\n this.#apiKey = config.apiKey;\n this.#enterpriseLearningEnabled = config.enableEnterpriseLearning ?? false;\n\n if (config.onThreadCreated) {\n this.onThreadCreated(config.onThreadCreated);\n }\n if (config.onThreadUpdated) {\n this.onThreadUpdated(config.onThreadUpdated);\n }\n if (config.onThreadDeleted) {\n this.onThreadDeleted(config.onThreadDeleted);\n }\n }\n\n /**\n * Register a listener invoked whenever a thread is created.\n *\n * Multiple listeners can be registered. Each call returns an unsubscribe\n * function that removes the listener when called.\n *\n * @param callback - Receives the newly created {@link ThreadSummary}.\n * @returns A function that removes this listener when called.\n *\n * @example\n * ```ts\n * const unsubscribe = intelligence.onThreadCreated((thread) => {\n * console.log(\"Thread created:\", thread.id);\n * });\n * // later…\n * unsubscribe();\n * ```\n */\n onThreadCreated(callback: (thread: ThreadSummary) => void): () => void {\n this.#threadCreatedListeners.add(callback);\n return () => {\n this.#threadCreatedListeners.delete(callback);\n };\n }\n\n /**\n * Register a listener invoked whenever a thread is updated (including archive).\n *\n * Multiple listeners can be registered. Each call returns an unsubscribe\n * function that removes the listener when called.\n *\n * @param callback - Receives the updated {@link ThreadSummary}.\n * @returns A function that removes this listener when called.\n */\n onThreadUpdated(callback: (thread: ThreadSummary) => void): () => void {\n this.#threadUpdatedListeners.add(callback);\n return () => {\n this.#threadUpdatedListeners.delete(callback);\n };\n }\n\n /**\n * Register a listener invoked whenever a thread is deleted.\n *\n * Multiple listeners can be registered. Each call returns an unsubscribe\n * function that removes the listener when called.\n *\n * @param callback - Receives the {@link ThreadDeletedPayload} identifying\n * the deleted thread.\n * @returns A function that removes this listener when called.\n */\n onThreadDeleted(\n callback: (params: ThreadDeletedPayload) => void,\n ): () => void {\n this.#threadDeletedListeners.add(callback);\n return () => {\n this.#threadDeletedListeners.delete(callback);\n };\n }\n\n ɵgetApiUrl(): string {\n return this.#apiUrl;\n }\n\n ɵgetRunnerWsUrl(): string {\n return this.#runnerWsUrl;\n }\n\n ɵgetClientWsUrl(): string {\n return this.#clientWsUrl;\n }\n\n ɵgetChannelsWsUrl(): string {\n return this.#channelsWsUrl;\n }\n\n ɵgetRunnerAuthToken(): string {\n return this.#apiKey;\n }\n\n /** @internal Used by `attachIntelligenceEnterpriseLearning` to populate `Authorization`. */\n ɵgetApiKey(): string {\n return this.#apiKey;\n }\n\n /** @internal Used by `attachIntelligenceEnterpriseLearning` to gate MCP attachment. */\n ɵisEnterpriseLearningEnabled(): boolean {\n return this.#enterpriseLearningEnabled;\n }\n\n async #request<T>(\n method: string,\n path: string,\n body?: unknown,\n extraHeaders?: Record<string, string>,\n ): Promise<T> {\n const url = `${this.#apiUrl}${path}`;\n\n const headers: Record<string, string> = {\n Authorization: `Bearer ${this.#apiKey}`,\n \"Content-Type\": \"application/json\",\n ...extraHeaders,\n };\n\n const response = await fetch(url, {\n method,\n headers,\n body: body ? JSON.stringify(body) : undefined,\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n logger.error(\n { status: response.status, body: text, path },\n \"Intelligence platform request failed\",\n );\n throw new PlatformRequestError(\n `Intelligence platform error ${response.status}: ${text || response.statusText}`,\n response.status,\n );\n }\n\n const text = await response.text();\n if (!text) {\n return undefined as T;\n }\n return JSON.parse(text) as T;\n }\n\n #invokeLifecycleCallback(\n callbackName: \"onThreadCreated\" | \"onThreadUpdated\" | \"onThreadDeleted\",\n payload: ThreadSummary | ThreadDeletedPayload,\n ): void {\n const listeners =\n callbackName === \"onThreadCreated\"\n ? this.#threadCreatedListeners\n : callbackName === \"onThreadUpdated\"\n ? this.#threadUpdatedListeners\n : this.#threadDeletedListeners;\n\n for (const callback of listeners) {\n try {\n (callback as (p: typeof payload) => void)(payload);\n } catch (error) {\n logger.error(\n { err: error, callbackName, payload },\n \"Intelligence lifecycle callback failed\",\n );\n }\n }\n }\n\n /**\n * List all non-archived threads for a given user and agent.\n *\n * @param params.userId - User whose threads to list.\n * @param params.agentId - Agent whose threads to list.\n * @returns The thread list along with realtime subscription credentials.\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async listThreads(params: {\n userId: string;\n agentId: string;\n includeArchived?: boolean;\n limit?: number;\n cursor?: string;\n }): Promise<ListThreadsResponse> {\n const query: Record<string, string> = {\n userId: params.userId,\n agentId: params.agentId,\n };\n if (params.includeArchived) query.includeArchived = \"true\";\n if (params.limit != null) query.limit = String(params.limit);\n if (params.cursor) query.cursor = params.cursor;\n\n const qs = new URLSearchParams(query).toString();\n return this.#request<ListThreadsResponse>(\"GET\", `/api/threads?${qs}`);\n }\n\n /**\n * List the given user's long-term memories, newest first.\n *\n * The platform scopes by the opaque app user supplied in the\n * `x-cpki-user-id` header (resolved by the runtime via `identifyUser`),\n * not a query param. Pass `includeInvalidated` to also return retired rows.\n *\n * @returns The `{ memories }` envelope the client memory store consumes.\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async listMemories(params: {\n userId: string;\n includeInvalidated?: boolean;\n }): Promise<ListMemoriesResponse> {\n const qs = params.includeInvalidated ? \"?includeInvalidated=true\" : \"\";\n return this.#request<ListMemoriesResponse>(\n \"GET\",\n `/api/memories${qs}`,\n undefined,\n { [INTELLIGENCE_USER_ID_HEADER]: params.userId },\n );\n }\n\n /**\n * Create a memory for the given user (platform `POST /api/memories`).\n * @returns The stored memory; `absorbed` is true if the content was merged\n * into a near-duplicate rather than inserted as a new row.\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async createMemory(params: {\n userId: string;\n content: string;\n kind: string;\n /** Optional: when omitted, the platform applies its default (`\"user\"`). */\n scope?: string;\n sourceThreadIds?: string[];\n }): Promise<SaveMemoryResponse> {\n return this.#request<SaveMemoryResponse>(\n \"POST\",\n `/api/memories`,\n {\n content: params.content,\n kind: params.kind,\n ...(params.scope !== undefined ? { scope: params.scope } : {}),\n sourceThreadIds: params.sourceThreadIds ?? [],\n },\n { [INTELLIGENCE_USER_ID_HEADER]: params.userId },\n );\n }\n\n /**\n * Supersede an existing memory (platform `PATCH /api/memories/:id`). The\n * `:id` row is retired and a new memory with the supplied content is\n * inserted atomically.\n * @returns The new memory plus `retiredId` (the id of the retired row).\n * @throws {@link PlatformRequestError} on non-2xx responses (e.g. 404 when\n * `:id` is not a live, same-scope memory for this user).\n */\n async updateMemory(params: {\n userId: string;\n id: string;\n content: string;\n kind: string;\n /** Optional: when omitted, the platform applies its default (`\"user\"`). */\n scope?: string;\n sourceThreadIds?: string[];\n }): Promise<SaveMemoryResponse> {\n return this.#request<SaveMemoryResponse>(\n \"PATCH\",\n `/api/memories/${encodeURIComponent(params.id)}`,\n {\n content: params.content,\n kind: params.kind,\n ...(params.scope !== undefined ? { scope: params.scope } : {}),\n sourceThreadIds: params.sourceThreadIds ?? [],\n },\n { [INTELLIGENCE_USER_ID_HEADER]: params.userId },\n );\n }\n\n /**\n * Non-lossily retire (forget) a memory (platform `DELETE /api/memories/:id`).\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async removeMemory(params: { userId: string; id: string }): Promise<void> {\n await this.#request<void>(\n \"DELETE\",\n `/api/memories/${encodeURIComponent(params.id)}`,\n undefined,\n { [INTELLIGENCE_USER_ID_HEADER]: params.userId },\n );\n }\n\n /**\n * Semantically recall the given user's memories (platform `POST\n * /api/memories/recall`, hybrid RAG). Each returned memory carries a\n * relevance `score`. `scope` narrows to `\"user\"`/`\"project\"`; omitted → platform default.\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async recallMemories(params: {\n userId: string;\n query: string;\n limit?: number;\n scope?: string;\n }): Promise<RecallMemoriesResponse> {\n return this.#request<RecallMemoriesResponse>(\n \"POST\",\n `/api/memories/recall`,\n {\n query: params.query,\n ...(params.limit !== undefined ? { limit: params.limit } : {}),\n ...(params.scope !== undefined ? { scope: params.scope } : {}),\n },\n { [INTELLIGENCE_USER_ID_HEADER]: params.userId },\n );\n }\n\n async ɵsubscribeToThreads(\n params: SubscribeToThreadsRequest,\n ): Promise<SubscribeToThreadsResponse> {\n return this.#request<SubscribeToThreadsResponse>(\n \"POST\",\n \"/api/threads/subscribe\",\n {\n userId: params.userId,\n },\n );\n }\n\n /**\n * Mint memory-realtime join credentials (platform `POST\n * /api/memories/subscribe`). Returns both the single-use `joinToken` and the\n * per-user `joinCode` the client needs to build the\n * `user_meta:memories:<joinCode>` channel topic. When the platform also\n * resolves a project scope it returns optional `projectJoinToken` /\n * `projectJoinCode`; both are passed through verbatim (omitted when absent,\n * the silent-degrade contract).\n *\n * The user is supplied via the `x-cpki-user-id` header — the same way every\n * other memory endpoint (`listMemories`/`createMemory`/…) identifies the app\n * user — because the platform's memory routes resolve identity from that\n * header, not the body. (This differs from `ɵsubscribeToThreads`, whose\n * platform endpoint reads `userId` from the body.)\n *\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async ɵsubscribeToMemories(\n params: SubscribeToMemoriesRequest,\n ): Promise<SubscribeToMemoriesResponse> {\n return this.#request<SubscribeToMemoriesResponse>(\n \"POST\",\n \"/api/memories/subscribe\",\n undefined,\n { [INTELLIGENCE_USER_ID_HEADER]: params.userId },\n );\n }\n\n /**\n * Update thread metadata (e.g. name).\n *\n * Triggers the `onThreadUpdated` lifecycle callback on success.\n *\n * @returns The updated thread summary.\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async updateThread(params: {\n threadId: string;\n userId: string;\n agentId: string;\n updates: UpdateThreadRequest;\n }): Promise<ThreadSummary> {\n const response = await this.#request<ThreadEnvelope>(\n \"PATCH\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n {\n userId: params.userId,\n agentId: params.agentId,\n ...params.updates,\n },\n );\n this.#invokeLifecycleCallback(\"onThreadUpdated\", response.thread);\n return response.thread;\n }\n\n /**\n * Create a new thread on the platform.\n *\n * Triggers the `onThreadCreated` lifecycle callback on success.\n *\n * @returns The newly created thread summary.\n * @throws {@link PlatformRequestError} with status 409 if a thread with the\n * same `threadId` already exists.\n */\n async createThread(params: CreateThreadRequest): Promise<ThreadSummary> {\n const response = await this.#request<ThreadEnvelope>(\n \"POST\",\n `/api/threads`,\n {\n threadId: params.threadId,\n userId: params.userId,\n agentId: params.agentId,\n ...(params.name !== undefined ? { name: params.name } : {}),\n },\n );\n this.#invokeLifecycleCallback(\"onThreadCreated\", response.thread);\n return response.thread;\n }\n\n /**\n * Fetch a single thread by ID.\n *\n * @returns The thread summary.\n * @throws {@link PlatformRequestError} with status 404 if the thread does\n * not exist.\n */\n async getThread(params: {\n threadId: string;\n userId: string;\n }): Promise<ThreadSummary> {\n const qs = new URLSearchParams({ userId: params.userId }).toString();\n const response = await this.#request<ThreadEnvelope>(\n \"GET\",\n `/api/threads/${encodeURIComponent(params.threadId)}?${qs}`,\n );\n return response.thread;\n }\n\n /**\n * Get an existing thread or create it if it does not exist.\n *\n * Handles the race where a concurrent request creates the thread between\n * the initial 404 and the subsequent `createThread` call by catching the\n * 409 Conflict and retrying the get.\n *\n * Triggers the `onThreadCreated` lifecycle callback when a new thread is\n * created.\n *\n * @returns An object containing the thread and a `created` flag indicating\n * whether the thread was newly created (`true`) or already existed (`false`).\n * @throws {@link PlatformRequestError} on non-2xx responses other than\n * 404 (get) and 409 (create race).\n */\n async getOrCreateThread(\n params: CreateThreadRequest,\n ): Promise<{ thread: ThreadSummary; created: boolean }> {\n try {\n const thread = await this.getThread({\n threadId: params.threadId,\n userId: params.userId,\n });\n return { thread, created: false };\n } catch (error) {\n if (!(error instanceof PlatformRequestError && error.status === 404)) {\n throw error;\n }\n }\n\n try {\n const thread = await this.createThread(params);\n return { thread, created: true };\n } catch (error) {\n // Another request created the thread between our get and create — retry get.\n if (error instanceof PlatformRequestError && error.status === 409) {\n const thread = await this.getThread({\n threadId: params.threadId,\n userId: params.userId,\n });\n return { thread, created: false };\n }\n throw error;\n }\n }\n\n /**\n * Fetch the full message history for a thread.\n *\n * @returns All persisted messages in chronological order.\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async getThreadMessages(params: {\n threadId: string;\n userId: string;\n }): Promise<ThreadMessagesResponse> {\n const qs = new URLSearchParams({ userId: params.userId }).toString();\n return this.#request<ThreadMessagesResponse>(\n \"GET\",\n `/api/threads/${encodeURIComponent(params.threadId)}/messages?${qs}`,\n );\n }\n\n /**\n * Fetch the persisted AG-UI event stream for a thread.\n *\n * Backed by the platform's `GET /api/_inspect/threads/:id/events`\n * introspection endpoint (see Intelligence PR #144). Events are returned\n * in replay order across every run that targeted the thread. The\n * `_inspect/` prefix flags this as debug-only — production code paths\n * must not depend on it.\n *\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async getThreadEvents(params: {\n threadId: string;\n }): Promise<ThreadEventsResponse> {\n return this.#request<ThreadEventsResponse>(\n \"GET\",\n `/api/_inspect/threads/${encodeURIComponent(params.threadId)}/events`,\n );\n }\n\n /**\n * Fetch the current agent state for a thread.\n *\n * Backed by the platform's `GET /api/_inspect/threads/:id/state`\n * introspection endpoint (see Intelligence PR #144). The platform folds\n * RFC 6902 STATE_DELTA events on top of the latest STATE_SNAPSHOT, so\n * the returned state reflects the thread's current state — not just the\n * last snapshot. The discriminated response distinguishes \"no snapshot\n * persisted yet\" from \"snapshot present\" so consumers can render the\n * correct empty state.\n *\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async getThreadState(params: {\n threadId: string;\n }): Promise<ThreadStateResponse> {\n return this.#request<ThreadStateResponse>(\n \"GET\",\n `/api/_inspect/threads/${encodeURIComponent(params.threadId)}/state`,\n );\n }\n\n /**\n * Mark a thread as archived.\n *\n * Archived threads are excluded from {@link listThreads} results.\n * Triggers the `onThreadUpdated` lifecycle callback on success.\n *\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async archiveThread(params: {\n threadId: string;\n userId: string;\n agentId: string;\n }): Promise<void> {\n const response = await this.#request<ThreadEnvelope>(\n \"PATCH\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n { userId: params.userId, agentId: params.agentId, archived: true },\n );\n this.#invokeLifecycleCallback(\"onThreadUpdated\", response.thread);\n }\n\n /**\n * Permanently delete a thread and its message history.\n *\n * This is irreversible. Triggers the `onThreadDeleted` lifecycle callback\n * on success.\n *\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async deleteThread(params: {\n threadId: string;\n userId: string;\n agentId: string;\n }): Promise<void> {\n await this.#request<void>(\n \"DELETE\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n {\n userId: params.userId,\n agentId: params.agentId,\n reason: `Deleted via CopilotKit runtime (userId=${params.userId}, agentId=${params.agentId})`,\n },\n );\n this.#invokeLifecycleCallback(\"onThreadDeleted\", params);\n }\n\n /**\n * Annotate a thread event on the Intelligence platform's general annotation\n * endpoint (`PUT /connector/annotate/:clientEventId`).\n *\n * This is the generalized replacement for the old\n * `PUT /connector/user-actions/record/:clientEventId` endpoint. It supports\n * multiple annotation types via the `type` discriminator:\n * - `\"user_action\"` — records a user UI interaction for the self-learning loop.\n * - `\"set_learning_containers\"` — sets the learning containers for a thread.\n *\n * `userId` must be resolved on the runtime side before calling this — the\n * platform prefixes it with the project id from the API key.\n *\n * Always hits the idempotent `PUT /connector/annotate/:clientEventId`\n * endpoint. A retry with the same `clientEventId` returns\n * `{ id: <original>, duplicate: true }` instead of creating a new row.\n * When `clientEventId` is omitted, a UUID is auto-generated for this call.\n *\n * @throws {@link PlatformRequestError} on non-2xx responses, OR when the\n * platform returns an empty 2xx body (which would otherwise corrupt the\n * caller's typed result).\n */\n async annotate(params: AnnotateParams): Promise<AnnotateResponse> {\n const clientEventId = params.clientEventId ?? randomUUID();\n const path = `/connector/annotate/${encodeURIComponent(clientEventId)}`;\n const body: Record<string, unknown> = {\n type: params.type,\n userId: params.userId,\n threadId: params.threadId,\n };\n if (params.payload !== undefined) {\n body.payload = params.payload;\n }\n if (params.occurredAt !== undefined) {\n body.occurredAt = params.occurredAt;\n }\n const response = await this.#request<AnnotateResponse | null | undefined>(\n \"PUT\",\n path,\n body,\n );\n // `== null` catches both `undefined` (empty body from `#request`)\n // and JSON `null` (which would otherwise corrupt the typed result\n // and surface as a `TypeError` deep in caller code).\n if (response == null) {\n logger.error(\n { path },\n \"annotate: Intelligence platform returned 200 with empty or null body\",\n );\n throw new PlatformRequestError(\n \"annotate: empty or null response body from Intelligence platform\",\n 502,\n );\n }\n return response;\n }\n\n async ɵacquireThreadLock(\n params: AcquireThreadLockRequest,\n ): Promise<AcquireThreadLockResponse> {\n return this.#request<AcquireThreadLockResponse>(\n \"POST\",\n `/api/threads/${encodeURIComponent(params.threadId)}/lock`,\n {\n runId: params.runId,\n userId: params.userId,\n agentId: params.agentId,\n ...(params.lockKeyPrefix !== undefined\n ? { lockKeyPrefix: params.lockKeyPrefix }\n : {}),\n ...(params.ttlSeconds !== undefined\n ? { ttlSeconds: params.ttlSeconds }\n : {}),\n },\n );\n }\n\n async ɵcleanupThreadLock(params: CleanupThreadLockRequest): Promise<void> {\n return this.#request<void>(\n \"DELETE\",\n `/api/threads/${encodeURIComponent(params.threadId)}/lock`,\n {\n runId: params.runId,\n },\n );\n }\n\n async ɵrenewThreadLock(\n params: RenewThreadLockRequest,\n ): Promise<RenewThreadLockResponse> {\n return this.#request<RenewThreadLockResponse>(\n \"PATCH\",\n `/api/threads/${encodeURIComponent(params.threadId)}/lock`,\n {\n runId: params.runId,\n ttlSeconds: params.ttlSeconds,\n ...(params.lockKeyPrefix !== undefined\n ? { lockKeyPrefix: params.lockKeyPrefix }\n : {}),\n },\n );\n }\n\n async ɵgetActiveJoinCode(params: {\n threadId: string;\n userId: string;\n }): Promise<ThreadConnectionResponse> {\n const qs = new URLSearchParams({ userId: params.userId }).toString();\n return this.#request<ThreadConnectionResponse>(\n \"GET\",\n `/api/threads/${encodeURIComponent(params.threadId)}/join-code?${qs}`,\n );\n }\n\n async ɵconnectThread(params: {\n threadId: string;\n userId: string;\n agentId: string;\n }): Promise<ConnectThreadResponse> {\n const result = await this.#request<ThreadConnectionResponse>(\n \"POST\",\n `/api/threads/${encodeURIComponent(params.threadId)}/connect`,\n {\n userId: params.userId,\n agentId: params.agentId,\n },\n );\n\n // request() returns undefined for empty/204 responses\n return result ?? null;\n }\n}\n\n/**\n * Normalize a configured URL to \"provided\" or \"not provided\". A blank string\n * counts as not provided: these URLs are typically wired from environment\n * variables, and a declared-but-empty variable (`COPILOTKIT_INTELLIGENCE_URL=`,\n * common in generated `.env` files and container configs) arrives as `\"\"`. Left\n * as-is it would produce host-relative requests instead of falling back to the\n * managed platform.\n */\nfunction configuredUrl(url: string | undefined): string | undefined {\n const trimmed = url?.trim();\n return trimmed ? trimmed : undefined;\n}\n\n/**\n * Warn when exactly one of `apiUrl`/`wsUrl` is configured. The API and realtime\n * planes are separate hosts, so a lone override silently leaves the other plane\n * on CopilotKit's managed platform — a self-hosted API paired with the managed\n * gateway (or vice versa), which fails as a hang rather than an error.\n */\nfunction warnOnPartialHostOverride(\n apiUrl: string | undefined,\n wsUrl: string | undefined,\n): void {\n if (apiUrl && !wsUrl) {\n logger.warn(\n `CopilotKitIntelligence: apiUrl is set to \"${apiUrl}\" but wsUrl is not, ` +\n `so wsUrl falls back to the managed default \"${MANAGED_INTELLIGENCE_WS_URL}\". ` +\n `The API and realtime planes are separate hosts — set both when pointing at a self-hosted deployment.`,\n );\n return;\n }\n\n if (wsUrl && !apiUrl) {\n logger.warn(\n `CopilotKitIntelligence: wsUrl is set to \"${wsUrl}\" but apiUrl is not, ` +\n `so apiUrl falls back to the managed default \"${MANAGED_INTELLIGENCE_API_URL}\". ` +\n `The API and realtime planes are separate hosts — set both when pointing at a self-hosted deployment.`,\n );\n }\n}\n\nfunction normalizeIntelligenceWsUrl(wsUrl: string): string {\n return wsUrl.replace(/\\/$/, \"\");\n}\n\nfunction deriveRunnerWsUrl(wsUrl: string): string {\n if (wsUrl.endsWith(\"/runner\")) {\n return wsUrl;\n }\n\n if (wsUrl.endsWith(\"/client\")) {\n return `${wsUrl.slice(0, -\"/client\".length)}/runner`;\n }\n\n if (wsUrl.endsWith(\"/channels\")) {\n return `${wsUrl.slice(0, -\"/channels\".length)}/runner`;\n }\n\n return `${wsUrl}/runner`;\n}\n\nfunction deriveClientWsUrl(wsUrl: string): string {\n if (wsUrl.endsWith(\"/client\")) {\n return wsUrl;\n }\n\n if (wsUrl.endsWith(\"/runner\")) {\n return `${wsUrl.slice(0, -\"/runner\".length)}/client`;\n }\n\n if (wsUrl.endsWith(\"/channels\")) {\n return `${wsUrl.slice(0, -\"/channels\".length)}/client`;\n }\n\n return `${wsUrl}/client`;\n}\n\nfunction deriveChannelsWsUrl(wsUrl: string): string {\n if (wsUrl.endsWith(\"/channels\")) return wsUrl;\n if (wsUrl.endsWith(\"/runner\")) {\n return `${wsUrl.slice(0, -\"/runner\".length)}/channels`;\n }\n if (wsUrl.endsWith(\"/client\")) {\n return `${wsUrl.slice(0, -\"/client\".length)}/channels`;\n }\n return `${wsUrl}/channels`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAaA,MAAa,8BAA8B;;;;;AAM3C,MAAM,+BAA+B;;;;;;;;AASrC,MAAM,8BAA8B;;;;;;;;;;;;;;;;;;AAmBpC,IAAa,uBAAb,cAA0C,MAAM;CAC9C,YACE,SAEA,AAAgB,QAChB;AACA,QAAM,QAAQ;EAFE;AAGhB,OAAK,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8YhB,IAAa,yBAAb,MAAoC;CAClC;CACA;CACA;CACA;CACA;CACA;CACA,0CAA0B,IAAI,KAAsC;CACpE,0CAA0B,IAAI,KAAsC;CACpE,0CAA0B,IAAI,KAA6C;CAE3E,YAAY,QAAsC;EAChD,MAAM,mBAAmB,cAAc,OAAO,OAAO;EACrD,MAAM,kBAAk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O,MAAM,QAAQ,OAAO,GAAG;;AAGjC,SAAS,kBAAkB,OAAuB;AAChD,KAAI,MAAM,SAAS,UAAU,CAC3B,QAAO;AAGT,KAAI,MAAM,SAAS,UAAU,CAC3B,QAAO,GAAG,MAAM,MAAM,GAAG,GAAkB,CAAC;AAG9C,KAAI,MAAM,SAAS,YAAY,CAC7B,QAAO,GAAG,MAAM,MAAM,GAAG,GAAoB,CAAC;AAGhD,QAAO,GAAG,MAAM;;AAGlB,SAAS,kBAAkB,OAAuB;AAChD,KAAI,MAAM,SAAS,UAAU,CAC3B,QAAO;AAGT,KAAI,MAAM,SAAS,UAAU,CAC3B,QAAO,GAAG,MAAM,MAAM,GAAG,GAAkB,CAAC;AAG9C,KAAI,MAAM,SAAS,YAAY,CAC7B,QAAO,GAAG,MAAM,MAAM,GAAG,GAAoB,CAAC;AAGhD,QAAO,GAAG,MAAM;;AAGlB,SAAS,oBAAoB,OAAuB;AAClD,KAAI,MAAM,SAAS,YAAY,CAAE,QAAO;AACxC,KAAI,MAAM,SAAS,UAAU,CAC3B,QAAO,GAAG,MAAM,MAAM,GAAG,GAAkB,CAAC;AAE9C,KAAI,MAAM,SAAS,UAAU,CAC3B,QAAO,GAAG,MAAM,MAAM,GAAG,GAAkB,CAAC;AAE9C,QAAO,GAAG,MAAM"}
|
|
@@ -411,6 +411,7 @@ declare class CopilotKitIntelligence {
|
|
|
411
411
|
ɵgetApiUrl(): string;
|
|
412
412
|
ɵgetRunnerWsUrl(): string;
|
|
413
413
|
ɵgetClientWsUrl(): string;
|
|
414
|
+
ɵgetChannelsWsUrl(): string;
|
|
414
415
|
ɵgetRunnerAuthToken(): string;
|
|
415
416
|
/** @internal Used by `attachIntelligenceEnterpriseLearning` to populate `Authorization`. */
|
|
416
417
|
ɵgetApiKey(): string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.d.cts","names":[],"sources":["../../../../src/v2/runtime/intelligence-platform/client.ts"],"mappings":";;;UA2DiB,oBA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AQ,aAAA;;;;;;;;;;;;;;;;EAwBN,iBAAA,CACJ,MAAA,EAAQ,mBAAA,GACP,OAAA;IAAU,MAAA,EAAQ,aAAA;IAAe,OAAA;EAAA;;;;;;;EAmC9B,iBAAA,CAAkB,MAAA;IACtB,QAAA;IACA,MAAA;EAAA,IACE,OAAA,CAAQ,sBAAA;;;;;;;;;;;;EAmBN,eAAA,CAAgB,MAAA;IACpB,QAAA;EAAA,IACE,OAAA,CAAQ,oBAAA;;;;;;;;;;;;;;EAoBN,cAAA,CAAe,MAAA;IACnB,QAAA;EAAA,IACE,OAAA,CAAQ,mBAAA;;;;;;;;;EAeN,aAAA,CAAc,MAAA;IAClB,QAAA;IACA,MAAA;IACA,OAAA;EAAA,IACE,OAAA;;;;;;;;;EAiBE,YAAA,CAAa,MAAA;IACjB,QAAA;IACA,MAAA;IACA,OAAA;EAAA,IACE,OAAA;;;;;;;;;;;;;;;;;;;;;;;EAmCE,QAAA,CAAS,MAAA,EAAQ,cAAA,GAAiB,OAAA,CAAQ,gBAAA;EAmC1C,kBAAA,CACJ,MAAA,EAAQ,wBAAA,GACP,OAAA,CAAQ,yBAAA;EAkBL,kBAAA,CAAmB,MAAA,EAAQ,wBAAA,GAA2B,OAAA;EAUtD,gBAAA,CACJ,MAAA,EAAQ,sBAAA,GACP,OAAA,CAAQ,uBAAA;EAcL,kBAAA,CAAmB,MAAA;IACvB,QAAA;IACA,MAAA;EAAA,IACE,OAAA,CAAQ,wBAAA;EAQN,cAAA,CAAe,MAAA;IACnB,QAAA;IACA,MAAA;IACA,OAAA;EAAA,IACE,OAAA,CAAQ,qBAAA;AAAA"}
|
|
@@ -411,6 +411,7 @@ declare class CopilotKitIntelligence {
|
|
|
411
411
|
ɵgetApiUrl(): string;
|
|
412
412
|
ɵgetRunnerWsUrl(): string;
|
|
413
413
|
ɵgetClientWsUrl(): string;
|
|
414
|
+
ɵgetChannelsWsUrl(): string;
|
|
414
415
|
ɵgetRunnerAuthToken(): string;
|
|
415
416
|
/** @internal Used by `attachIntelligenceEnterpriseLearning` to populate `Authorization`. */
|
|
416
417
|
ɵgetApiKey(): string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.d.mts","names":[],"sources":["../../../../src/v2/runtime/intelligence-platform/client.ts"],"mappings":";;;UA2DiB,oBAAA;EACf,QAAA;EACA,MAAA;EACA,OAAA;AAAA;AAAA,UAGe,4BAAA;EAwEf;;;;;;;EAhEA,MAAA;EA4EkC;;;;;;;;;;AAepC;;EA9EE,KAAA;EA8E4B;EA5E5B,MAAA;EAgFA;;;;;;;;AAcF;;;EAlFE,wBAAA;EAmFuB;AAIzB;;;EAlFE,eAAA,IAAmB,MAAA,EAAQ,aAAA;EAmFJ;AAQzB;;;EAtFE,eAAA,IAAmB,MAAA,EAAQ,aAAA;EAsFe;;;;EAjF1C,eAAA,IAAmB,MAAA,EAAQ,oBAAA;AAAA;;;;;AAqG7B;;;UA3FiB,aAAA;EA6Ff;EA3FA,EAAA;EA+FA;EA7FA,IAAA;EA+FI;EA7FJ,SAAA;EAiGe;EA/Ff,aAAA;;EAEA,SAAA;EA+FA;EA7FA,SAAA;EAiGA;EA/FA,QAAA;EAiGO;EA/FP,OAAA;EA+FqB;EA7FrB,WAAA;EAgGwC;EA9FxC,cAAA;AAAA;;UAIe,mBAAA;EA8F0B;EA5FzC,OAAA,EAAS,aAAA;EA6FT;EA3FA,QAAA;EA8Fe;EA5Ff,SAAA;;EAEA,UAAA;AAAA;AAoGF;;;;AAAA,UA7FiB,aAAA;EA+Ff;EA7FA,EAAA;EAsGA;EApGA,IAAA;EAoGe;EAlGf,KAAA;EAqG+B;EAnG/B,OAAA;EAmGkC;EAjGlC,eAAA;EAmGe;EAjGf,aAAA;;EAEA,KAAA;AAAA;AAgHF;AAAA,UA5GiB,oBAAA;EACf,QAAA,EAAU,aAAA;AAAA;;UAIK,sBAAA;EACf,QAAA,EAAU,aAAA;AAAA;;;;;AA+HZ;UAvHiB,kBAAA,SAA2B,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 var CopilotKitIntelligence = class {
|
|
|
85
85
|
#apiUrl;
|
|
86
86
|
#runnerWsUrl;
|
|
87
87
|
#clientWsUrl;
|
|
88
|
+
#channelsWsUrl;
|
|
88
89
|
#apiKey;
|
|
89
90
|
#enterpriseLearningEnabled;
|
|
90
91
|
#threadCreatedListeners = /* @__PURE__ */ new Set();
|
|
@@ -98,6 +99,7 @@ var CopilotKitIntelligence = class {
|
|
|
98
99
|
this.#apiUrl = (configuredApiUrl ?? MANAGED_INTELLIGENCE_API_URL).replace(/\/$/, "");
|
|
99
100
|
this.#runnerWsUrl = deriveRunnerWsUrl(intelligenceWsUrl);
|
|
100
101
|
this.#clientWsUrl = deriveClientWsUrl(intelligenceWsUrl);
|
|
102
|
+
this.#channelsWsUrl = deriveChannelsWsUrl(intelligenceWsUrl);
|
|
101
103
|
this.#apiKey = config.apiKey;
|
|
102
104
|
this.#enterpriseLearningEnabled = config.enableEnterpriseLearning ?? false;
|
|
103
105
|
if (config.onThreadCreated) this.onThreadCreated(config.onThreadCreated);
|
|
@@ -168,6 +170,9 @@ var CopilotKitIntelligence = class {
|
|
|
168
170
|
ɵgetClientWsUrl() {
|
|
169
171
|
return this.#clientWsUrl;
|
|
170
172
|
}
|
|
173
|
+
ɵgetChannelsWsUrl() {
|
|
174
|
+
return this.#channelsWsUrl;
|
|
175
|
+
}
|
|
171
176
|
ɵgetRunnerAuthToken() {
|
|
172
177
|
return this.#apiKey;
|
|
173
178
|
}
|
|
@@ -584,13 +589,21 @@ function normalizeIntelligenceWsUrl(wsUrl) {
|
|
|
584
589
|
function deriveRunnerWsUrl(wsUrl) {
|
|
585
590
|
if (wsUrl.endsWith("/runner")) return wsUrl;
|
|
586
591
|
if (wsUrl.endsWith("/client")) return `${wsUrl.slice(0, -7)}/runner`;
|
|
592
|
+
if (wsUrl.endsWith("/channels")) return `${wsUrl.slice(0, -9)}/runner`;
|
|
587
593
|
return `${wsUrl}/runner`;
|
|
588
594
|
}
|
|
589
595
|
function deriveClientWsUrl(wsUrl) {
|
|
590
596
|
if (wsUrl.endsWith("/client")) return wsUrl;
|
|
591
597
|
if (wsUrl.endsWith("/runner")) return `${wsUrl.slice(0, -7)}/client`;
|
|
598
|
+
if (wsUrl.endsWith("/channels")) return `${wsUrl.slice(0, -9)}/client`;
|
|
592
599
|
return `${wsUrl}/client`;
|
|
593
600
|
}
|
|
601
|
+
function deriveChannelsWsUrl(wsUrl) {
|
|
602
|
+
if (wsUrl.endsWith("/channels")) return wsUrl;
|
|
603
|
+
if (wsUrl.endsWith("/runner")) return `${wsUrl.slice(0, -7)}/channels`;
|
|
604
|
+
if (wsUrl.endsWith("/client")) return `${wsUrl.slice(0, -7)}/channels`;
|
|
605
|
+
return `${wsUrl}/channels`;
|
|
606
|
+
}
|
|
594
607
|
|
|
595
608
|
//#endregion
|
|
596
609
|
export { CopilotKitIntelligence, INTELLIGENCE_USER_ID_HEADER, PlatformRequestError };
|