@copilotkit/runtime 1.67.0 → 1.68.0
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/agent/index.cjs +5 -0
- package/dist/agent/index.cjs.map +1 -1
- package/dist/agent/index.d.cts +2 -1
- package/dist/agent/index.d.cts.map +1 -1
- package/dist/agent/index.d.mts +2 -1
- package/dist/agent/index.d.mts.map +1 -1
- package/dist/agent/index.mjs +5 -0
- package/dist/agent/index.mjs.map +1 -1
- package/dist/lib/integrations/node-http/request-handler.cjs +1 -2
- package/dist/lib/integrations/node-http/request-handler.cjs.map +1 -1
- package/dist/lib/integrations/node-http/request-handler.mjs +1 -2
- package/dist/lib/integrations/node-http/request-handler.mjs.map +1 -1
- package/dist/lib/runtime/copilot-runtime.cjs +25 -4
- package/dist/lib/runtime/copilot-runtime.cjs.map +1 -1
- package/dist/lib/runtime/copilot-runtime.d.cts +14 -3
- package/dist/lib/runtime/copilot-runtime.d.cts.map +1 -1
- package/dist/lib/runtime/copilot-runtime.d.mts +14 -3
- package/dist/lib/runtime/copilot-runtime.d.mts.map +1 -1
- package/dist/lib/runtime/copilot-runtime.mjs +25 -4
- package/dist/lib/runtime/copilot-runtime.mjs.map +1 -1
- package/dist/package.cjs +2 -2
- package/dist/runtime/package.mjs +2 -2
- package/dist/v2/index.d.cts +2 -1
- package/dist/v2/index.d.mts +2 -1
- package/dist/v2/runtime/core/channel-manager.cjs +14 -2
- package/dist/v2/runtime/core/channel-manager.cjs.map +1 -1
- package/dist/v2/runtime/core/channel-manager.d.cts.map +1 -1
- package/dist/v2/runtime/core/channel-manager.d.mts +1 -0
- package/dist/v2/runtime/core/channel-manager.d.mts.map +1 -1
- package/dist/v2/runtime/core/channel-manager.mjs +14 -2
- 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/core/learning.cjs +21 -0
- package/dist/v2/runtime/core/learning.cjs.map +1 -0
- package/dist/v2/runtime/core/learning.d.cts +27 -0
- package/dist/v2/runtime/core/learning.d.cts.map +1 -0
- package/dist/v2/runtime/core/learning.d.mts +27 -0
- package/dist/v2/runtime/core/learning.d.mts.map +1 -0
- package/dist/v2/runtime/core/learning.mjs +19 -0
- package/dist/v2/runtime/core/learning.mjs.map +1 -0
- package/dist/v2/runtime/core/runtime-error-reporter.cjs +72 -0
- package/dist/v2/runtime/core/runtime-error-reporter.cjs.map +1 -0
- package/dist/v2/runtime/core/runtime-error-reporter.mjs +67 -0
- package/dist/v2/runtime/core/runtime-error-reporter.mjs.map +1 -0
- package/dist/v2/runtime/core/runtime.cjs +11 -0
- package/dist/v2/runtime/core/runtime.cjs.map +1 -1
- package/dist/v2/runtime/core/runtime.d.cts +8 -0
- package/dist/v2/runtime/core/runtime.d.cts.map +1 -1
- package/dist/v2/runtime/core/runtime.d.mts +8 -0
- package/dist/v2/runtime/core/runtime.d.mts.map +1 -1
- package/dist/v2/runtime/core/runtime.mjs +11 -0
- package/dist/v2/runtime/core/runtime.mjs.map +1 -1
- package/dist/v2/runtime/handlers/handle-run.cjs +14 -2
- package/dist/v2/runtime/handlers/handle-run.cjs.map +1 -1
- package/dist/v2/runtime/handlers/handle-run.mjs +14 -2
- package/dist/v2/runtime/handlers/handle-run.mjs.map +1 -1
- package/dist/v2/runtime/handlers/intelligence/annotate.cjs +1 -1
- package/dist/v2/runtime/handlers/intelligence/annotate.cjs.map +1 -1
- package/dist/v2/runtime/handlers/intelligence/annotate.mjs +1 -1
- package/dist/v2/runtime/handlers/intelligence/annotate.mjs.map +1 -1
- package/dist/v2/runtime/handlers/intelligence/run.cjs +51 -8
- package/dist/v2/runtime/handlers/intelligence/run.cjs.map +1 -1
- package/dist/v2/runtime/handlers/intelligence/run.mjs +51 -8
- package/dist/v2/runtime/handlers/intelligence/run.mjs.map +1 -1
- package/dist/v2/runtime/handlers/shared/sse-response.cjs +24 -1
- package/dist/v2/runtime/handlers/shared/sse-response.cjs.map +1 -1
- package/dist/v2/runtime/handlers/shared/sse-response.mjs +24 -1
- package/dist/v2/runtime/handlers/shared/sse-response.mjs.map +1 -1
- package/dist/v2/runtime/handlers/sse/connect.cjs +1 -0
- package/dist/v2/runtime/handlers/sse/connect.cjs.map +1 -1
- package/dist/v2/runtime/handlers/sse/connect.mjs +1 -0
- package/dist/v2/runtime/handlers/sse/connect.mjs.map +1 -1
- package/dist/v2/runtime/handlers/sse/run.cjs +4 -1
- package/dist/v2/runtime/handlers/sse/run.cjs.map +1 -1
- package/dist/v2/runtime/handlers/sse/run.mjs +4 -1
- package/dist/v2/runtime/handlers/sse/run.mjs.map +1 -1
- package/dist/v2/runtime/index.d.cts +1 -0
- package/dist/v2/runtime/index.d.cts.map +1 -1
- package/dist/v2/runtime/index.d.mts +1 -0
- package/dist/v2/runtime/index.d.mts.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.cjs +6 -4
- package/dist/v2/runtime/intelligence-platform/client.cjs.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.d.cts +10 -7
- package/dist/v2/runtime/intelligence-platform/client.d.cts.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.d.mts +10 -7
- package/dist/v2/runtime/intelligence-platform/client.d.mts.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.mjs +6 -4
- package/dist/v2/runtime/intelligence-platform/client.mjs.map +1 -1
- package/dist/v2/runtime/runner/agent-runner.cjs.map +1 -1
- package/dist/v2/runtime/runner/agent-runner.d.cts +1 -0
- package/dist/v2/runtime/runner/agent-runner.d.cts.map +1 -1
- package/dist/v2/runtime/runner/agent-runner.d.mts +1 -0
- package/dist/v2/runtime/runner/agent-runner.d.mts.map +1 -1
- package/dist/v2/runtime/runner/agent-runner.mjs.map +1 -1
- package/package.json +6 -6
- package/skills/runtime/SKILL.md +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.mjs","names":["pkg"],"sources":["../../../../src/v2/runtime/core/runtime.ts"],"sourcesContent":["import type {\n MaybePromise,\n NonEmptyRecord,\n RuntimeMode,\n} from \"@copilotkit/shared\";\nimport {\n RUNTIME_MODE_SSE,\n RUNTIME_MODE_INTELLIGENCE,\n} from \"@copilotkit/shared\";\nimport { createLicenseChecker } from \"@copilotkit/license-verifier\";\nimport type { LicenseChecker } from \"@copilotkit/license-verifier\";\nimport { resolveDebugConfig } from \"@copilotkit/shared\";\nimport type { ResolvedDebugConfig, DebugConfig } from \"@copilotkit/shared\";\nimport { resolveForwardHeadersPolicy } from \"../handlers/header-utils\";\nimport type {\n ForwardHeadersConfig,\n ResolvedForwardHeadersPolicy,\n} from \"../handlers/header-utils\";\nimport type { AbstractAgent } from \"@ag-ui/client\";\nimport type { MCPClientConfig } from \"@ag-ui/mcp-apps-middleware\";\nimport type { A2UIMiddlewareConfig } from \"@ag-ui/a2ui-middleware\";\nimport pkg from \"../../../../package.json\";\nimport type {\n BeforeRequestMiddleware,\n AfterRequestMiddleware,\n} from \"./middleware\";\nimport { createLogger } from \"../../../lib/logger\";\nimport type { CopilotRuntimeLogger } from \"../../../lib/logger\";\nimport { logRuntimeTelemetryDisclosure } from \"../../../lib/telemetry-disclosure\";\nimport type { TranscriptionService } from \"../transcription-service/transcription-service\";\nimport { DebugEventBus } from \"./debug-event-bus\";\nimport type { AgentRunner } from \"../runner/agent-runner\";\nimport { InMemoryAgentRunner } from \"../runner/in-memory\";\nimport { IntelligenceAgentRunner } from \"../runner/intelligence\";\nimport type { CopilotKitIntelligence } from \"../intelligence-platform\";\n// Type-only: @copilotkit/channels-core is the pure-ESM type source, so a value import would break this\n// package's CJS output. The channels are validated + activated (wired to delivery\n// transports) by `startChannels` from @copilotkit/channels-intelligence, called\n// by the Channel-listener bootstrap — not here.\nimport type { Channel } from \"@copilotkit/channels-core\";\nimport telemetry from \"../telemetry/telemetry-client\";\n\nexport const VERSION = pkg.version;\n\ninterface BaseCopilotRuntimeMiddlewareOptions {\n /** If set, middleware only applies to these named agents. Applies to all agents if omitted. */\n agents?: string[];\n}\n\n/** Per-server tool policy belongs to the external middleware and is unsupported at its pinned 0.0.3 release. */\nexport type McpAppsServerConfig = MCPClientConfig & {\n /** Agent to bind this server to. If omitted, the server is available to all agents. */\n agentId?: string;\n};\n\nexport interface McpAppsConfig {\n /** List of MCP server configurations. */\n servers: McpAppsServerConfig[];\n}\n\nexport interface OpenGenerativeUIOptions extends BaseCopilotRuntimeMiddlewareOptions {}\n\nexport type OpenGenerativeUIConfig = boolean | OpenGenerativeUIOptions;\n\ninterface CopilotRuntimeMiddlewares {\n /**\n * Auto-apply A2UIMiddleware to agents at run time.\n * Pass an object to enable and customise behaviour, or omit to disable.\n */\n a2ui?: BaseCopilotRuntimeMiddlewareOptions &\n A2UIMiddlewareConfig & {\n /**\n * Explicit on/off switch. Omit (or set `true`) to enable; set `false`\n * to disable A2UI for this runtime while keeping the rest of the config\n * (e.g. a `schema`/`catalog`) in place. A bare `a2ui: {}` stays enabled\n * for backwards compatibility.\n */\n enabled?: boolean;\n };\n /** Auto-apply MCPAppsMiddleware to agents at run time. */\n mcpApps?: McpAppsConfig;\n /** Auto-apply OpenGenerativeUIMiddleware to agents at run time. */\n openGenerativeUI?: OpenGenerativeUIConfig;\n}\n\n/**\n * Context passed to agent factory functions for per-request agent resolution.\n */\nexport interface AgentFactoryContext {\n /** The incoming HTTP request. */\n request: Request;\n}\n\n/**\n * A function that dynamically creates agents on a per-request basis.\n * Useful for multi-tenant scenarios or request-scoped agent configuration.\n */\nexport type AgentsFactory = (\n ctx: AgentFactoryContext,\n) => MaybePromise<NonEmptyRecord<Record<string, AbstractAgent>>>;\n\n/**\n * Agents can be provided as:\n * - A static record of agents\n * - A Promise that resolves to a record of agents\n * - A factory function that receives request context and returns agents (or a Promise of agents)\n */\nexport type AgentsConfig =\n | MaybePromise<NonEmptyRecord<Record<string, AbstractAgent>>>\n | AgentsFactory;\n\n/**\n * Resolve an AgentsConfig value to a concrete record of agents.\n * If the config is a factory function, it is called with the given request context.\n * Otherwise it is awaited directly (static record or Promise).\n */\nexport async function resolveAgents(\n agents: AgentsConfig,\n request?: Request,\n): Promise<Record<string, AbstractAgent>> {\n if (typeof agents === \"function\") {\n if (!request) {\n throw new Error(\n \"Agent factory function requires a request context, but none was provided.\",\n );\n }\n return agents({ request });\n }\n return agents;\n}\n\ninterface BaseCopilotRuntimeOptions extends CopilotRuntimeMiddlewares {\n /**\n * Map of available agents, or a factory function for per-request agent resolution.\n *\n * Static record:\n * ```ts\n * agents: { support: new SupportAgent(), technical: new TechnicalAgent() }\n * ```\n *\n * Factory function (called per-request):\n * ```ts\n * agents: ({ request }) => {\n * const tenantId = request.headers.get(\"x-tenant-id\");\n * return { default: createAgentForTenant(tenantId) };\n * }\n * ```\n */\n agents: AgentsConfig;\n /** Optional transcription service for audio processing. */\n transcriptionService?: TranscriptionService;\n /** Optional *before* middleware – callback function or webhook URL. */\n beforeRequestMiddleware?: BeforeRequestMiddleware;\n /** Optional *after* middleware – callback function or webhook URL. */\n afterRequestMiddleware?: AfterRequestMiddleware;\n /** Signed license token for server-side feature verification. Falls back to COPILOTKIT_LICENSE_TOKEN env var. */\n licenseToken?: string;\n /** Enable debug logging for the event pipeline. */\n debug?: DebugConfig;\n /**\n * Policy controlling which inbound HTTP headers are forwarded onto the\n * outgoing agent call. By default a built-in denylist strips known\n * infrastructure/proxy/platform headers (`x-forwarded-*`, `x-real-ip`,\n * `x-vercel-*`, `x-copilotcloud-*`, etc.) while `authorization` and custom\n * `x-*` application headers continue to forward (#5712). Set\n * `{ useDefaultDenylist: false }` to restore the previous wide-open behavior.\n */\n forwardHeaders?: ForwardHeadersConfig;\n /**\n * Opt-in flag exposing the client-facing memory proxy routes\n * (`/memories`, `/memories/recall`, `/memories/subscribe`, `/memories/:id`).\n *\n * Defaults to `false` — a **secure default**. When off, every `/memories/*`\n * request 404s as if the route did not exist, so an un-opted-in deployment\n * reveals nothing about memory even when Intelligence is configured. This does\n * NOT affect the agent's own server-side memory tooling (`recall_memory` runs\n * via the Intelligence MCP path, separate from this client REST proxy).\n *\n * Flip to `true` to power a client memory inspector (e.g. the dev console's\n * Memory tab). Existing Intelligence deployments relying on the previously\n * always-on Learning tab must set this to restore it.\n *\n * @deprecated Configure `memory.access` on an Intelligence Runtime. That one\n * policy enables and limits both agent and browser Memory.\n */\n exposeMemoryRoutes?: boolean;\n}\n\nexport interface CopilotRuntimeUser {\n id: string;\n name: string;\n}\n\nexport type IdentifyUserCallback = (\n request: Request,\n) => MaybePromise<CopilotRuntimeUser>;\n\nexport type MemoryAccess = \"none\" | \"read\" | \"read-write\";\n\nexport interface MemoryGrant {\n readonly user: MemoryAccess;\n readonly project: MemoryAccess;\n}\n\nexport type MemoryConsumer = \"agent\" | \"client\";\n\nexport interface CopilotRuntimeMemoryConfig {\n /** Resolves immutable Memory access for one authenticated web request. */\n access(input: {\n readonly request: Request;\n readonly user: CopilotRuntimeUser;\n readonly consumer: MemoryConsumer;\n }): MaybePromise<MemoryGrant | null>;\n}\n\nexport interface CopilotSseRuntimeOptions extends BaseCopilotRuntimeOptions {\n /** The runner to use for running agents in SSE mode. */\n runner?: AgentRunner;\n intelligence?: undefined;\n generateThreadNames?: undefined;\n /** Intelligence Channels require the Intelligence runtime; not available in SSE mode. */\n channels?: undefined;\n}\n\ninterface CopilotIntelligenceRuntimeBaseOptions extends BaseCopilotRuntimeOptions {\n /** Configures Intelligence mode for durable threads and realtime events. */\n intelligence: CopilotKitIntelligence;\n /** Auto-generate short names for newly created threads. */\n generateThreadNames?: boolean;\n /** Max delay (ms) for WebSocket reconnect backoff. @default 10_000 */\n maxReconnectMs?: number;\n /** Max delay (ms) for channel rejoin backoff. @default 30_000 */\n maxRejoinMs?: number;\n /** Lock TTL in seconds. Clamped to a maximum of 3600 (1 hour). @default 20 */\n lockTtlSeconds?: number;\n /** Custom Redis key prefix for the thread lock. */\n lockKeyPrefix?: string;\n /** Interval in seconds at which the runtime renews the thread lock. Clamped to a maximum of 3000 (50 minutes). @default 15 */\n lockHeartbeatIntervalSeconds?: number;\n /**\n * Intelligence Channels declared by this runtime. Each is a\n * `createChannel({ name })` instance. Only available on the Intelligence runtime\n * path. Names are validated (required, lowercase kebab-case, unique) and wired\n * to delivery/egress transports when activated via `startChannels` from\n * `@copilotkit/channels-intelligence` — not at construction.\n */\n}\n\ntype NonEmptyChannels = readonly [Channel, ...Channel[]];\n\n/** Intelligence runtime options with web identity, Channels, or both. */\nexport type CopilotIntelligenceRuntimeOptions =\n CopilotIntelligenceRuntimeBaseOptions &\n (\n | {\n /** Resolves the authenticated user for web requests. */\n identifyUser: IdentifyUserCallback;\n /** Enables agent and browser Memory under one request policy. */\n memory?: CopilotRuntimeMemoryConfig;\n channels?: readonly Channel[];\n }\n | {\n /** Channels-only runtimes expose no functional web surface. */\n identifyUser?: undefined;\n memory?: undefined;\n channels: NonEmptyChannels;\n }\n );\n\nexport type CopilotRuntimeOptions =\n | CopilotSseRuntimeOptions\n | CopilotIntelligenceRuntimeOptions;\n\nexport interface CopilotRuntimeLike {\n agents: CopilotRuntimeOptions[\"agents\"];\n transcriptionService: CopilotRuntimeOptions[\"transcriptionService\"];\n beforeRequestMiddleware: CopilotRuntimeOptions[\"beforeRequestMiddleware\"];\n afterRequestMiddleware: CopilotRuntimeOptions[\"afterRequestMiddleware\"];\n runner: AgentRunner;\n a2ui: CopilotRuntimeOptions[\"a2ui\"];\n mcpApps: CopilotRuntimeOptions[\"mcpApps\"];\n openGenerativeUI: CopilotRuntimeOptions[\"openGenerativeUI\"];\n intelligence?: CopilotKitIntelligence;\n identifyUser?: IdentifyUserCallback;\n mode: RuntimeMode;\n licenseChecker?: LicenseChecker;\n debugEventBus?: DebugEventBus;\n debug: ResolvedDebugConfig;\n debugLogger?: CopilotRuntimeLogger;\n /**\n * Resolved inbound-header forwarding policy read by the /run and /connect call\n * sites. Optional on the published interface so an external `CopilotRuntimeLike`\n * implementor predating this field stays source-compatible (non-breaking minor\n * release). Concrete runtimes (`BaseCopilotRuntime`) always resolve and set it;\n * the call sites coalesce a missing value to the default resolved policy\n * (`resolveForwardHeadersPolicy(undefined)` — default-on denylist).\n */\n forwardHeadersPolicy?: ResolvedForwardHeadersPolicy;\n /**\n * Resolved opt-in flag for the client-facing memory proxy routes. Optional on\n * the published interface so an external `CopilotRuntimeLike` implementor\n * predating this field stays source-compatible; the dispatcher coalesces a\n * missing value to `false` (secure default — routes hidden). Concrete runtimes\n * (`BaseCopilotRuntime`) always resolve and set it.\n */\n exposeMemoryRoutes?: boolean;\n memory?: CopilotRuntimeMemoryConfig;\n}\n\nexport interface CopilotSseRuntimeLike extends CopilotRuntimeLike {\n intelligence?: undefined;\n mode: typeof RUNTIME_MODE_SSE;\n}\n\nexport interface CopilotIntelligenceRuntimeLike extends CopilotRuntimeLike {\n intelligence: CopilotKitIntelligence;\n identifyUser?: IdentifyUserCallback;\n generateThreadNames: boolean;\n lockTtlSeconds: number;\n lockKeyPrefix?: string;\n lockHeartbeatIntervalSeconds: number;\n channels: Channel[];\n mode: typeof RUNTIME_MODE_INTELLIGENCE;\n}\n\nabstract class BaseCopilotRuntime implements CopilotRuntimeLike {\n public agents: CopilotRuntimeOptions[\"agents\"];\n public transcriptionService: CopilotRuntimeOptions[\"transcriptionService\"];\n public beforeRequestMiddleware: CopilotRuntimeOptions[\"beforeRequestMiddleware\"];\n public afterRequestMiddleware: CopilotRuntimeOptions[\"afterRequestMiddleware\"];\n public runner: AgentRunner;\n public a2ui: CopilotRuntimeOptions[\"a2ui\"];\n public mcpApps: CopilotRuntimeOptions[\"mcpApps\"];\n public openGenerativeUI: CopilotRuntimeOptions[\"openGenerativeUI\"];\n public licenseChecker?: LicenseChecker;\n public readonly debugEventBus?: DebugEventBus;\n public debug: ResolvedDebugConfig;\n public debugLogger?: CopilotRuntimeLogger;\n public readonly forwardHeadersPolicy: ResolvedForwardHeadersPolicy;\n public readonly exposeMemoryRoutes: boolean;\n public readonly memory?: CopilotRuntimeMemoryConfig;\n\n /**\n * License token resolved once with the env fallback, so telemetry\n * attribution (below) and subclass feature gating\n * (CopilotIntelligenceRuntime's licenseChecker) read the exact same value\n * instead of each re-applying `?? COPILOTKIT_LICENSE_TOKEN`.\n */\n protected readonly resolvedLicenseToken?: string;\n\n abstract readonly intelligence?: CopilotKitIntelligence;\n abstract readonly mode: RuntimeMode;\n\n constructor(options: BaseCopilotRuntimeOptions, runner: AgentRunner) {\n logRuntimeTelemetryDisclosure();\n\n const {\n agents,\n transcriptionService,\n beforeRequestMiddleware,\n afterRequestMiddleware,\n a2ui,\n mcpApps,\n openGenerativeUI,\n } = options;\n\n this.agents = agents;\n this.transcriptionService = transcriptionService;\n this.beforeRequestMiddleware = beforeRequestMiddleware;\n this.afterRequestMiddleware = afterRequestMiddleware;\n this.a2ui = a2ui || undefined;\n this.mcpApps = mcpApps;\n this.openGenerativeUI = openGenerativeUI;\n this.runner = runner;\n\n // Resolve the license token once (matching the license-verifier's env\n // fallback) so telemetry attribution and subclass feature gating share\n // one value.\n this.resolvedLicenseToken =\n options.licenseToken ?? process.env.COPILOTKIT_LICENSE_TOKEN;\n\n // Attribute telemetry to the licensed customer for *every* runtime mode.\n // Done in the shared base (not the subclasses) so SSE and Intelligence\n // runtimes behave identically — previously only CopilotIntelligenceRuntime\n // set this, so self-hosted SSE users never got a telemetry_id on their\n // runtime events even with a license token configured.\n if (this.resolvedLicenseToken) {\n telemetry.setLicenseToken(this.resolvedLicenseToken);\n }\n\n if (process.env.NODE_ENV !== \"production\") {\n this.debugEventBus = new DebugEventBus();\n }\n // Resolve the inbound-header forwarding policy once (mirroring the\n // `debug` → `ResolvedDebugConfig` resolve-once above) so both the /run and\n // /connect call sites read the exact same resolved policy off the runtime\n // and can never diverge.\n this.forwardHeadersPolicy = resolveForwardHeadersPolicy(\n options.forwardHeaders,\n );\n // Secure default: the client-facing memory proxy routes stay hidden (404)\n // unless a deployment explicitly opts in.\n this.memory = (options as { memory?: CopilotRuntimeMemoryConfig }).memory;\n this.exposeMemoryRoutes =\n this.memory !== undefined || (options.exposeMemoryRoutes ?? false);\n this.debug = resolveDebugConfig(options.debug);\n if (this.debug.enabled) {\n this.debugLogger = createLogger({\n level: \"debug\",\n component: \"copilotkit-debug\",\n });\n }\n }\n}\n\nexport class CopilotSseRuntime\n extends BaseCopilotRuntime\n implements CopilotSseRuntimeLike\n{\n readonly intelligence = undefined;\n readonly mode = RUNTIME_MODE_SSE;\n\n constructor(options: CopilotSseRuntimeOptions) {\n // Runtime guard mirroring the discriminated-union type: the SSE runtime has\n // no Intelligence delivery path, so `channels` cannot be honored here. The\n // type forbids it, but a JS / `as any` caller passing `{ agents, channels }`\n // would otherwise land here and have `channels` silently dropped — fail\n // loud instead.\n const channels = (options as { channels?: unknown[] }).channels;\n if (Array.isArray(channels) && channels.length > 0) {\n throw new Error(\n \"`channels` requires the Intelligence runtime (pass `intelligence`); \" +\n \"Intelligence Channels are not available in SSE mode.\",\n );\n }\n super(options, options.runner ?? new InMemoryAgentRunner());\n }\n}\n\nexport class CopilotIntelligenceRuntime\n extends BaseCopilotRuntime\n implements CopilotIntelligenceRuntimeLike\n{\n readonly intelligence: CopilotKitIntelligence;\n readonly identifyUser?: IdentifyUserCallback;\n readonly generateThreadNames: boolean;\n readonly lockTtlSeconds: number;\n readonly lockKeyPrefix?: string;\n readonly lockHeartbeatIntervalSeconds: number;\n readonly channels: Channel[];\n readonly mode = RUNTIME_MODE_INTELLIGENCE;\n\n /** Maximum allowed lock TTL in seconds (1 hour). */\n static readonly MAX_LOCK_TTL_SECONDS = 3_600;\n /** Maximum allowed heartbeat interval in seconds (50 minutes). */\n static readonly MAX_HEARTBEAT_INTERVAL_SECONDS = 3_000;\n\n constructor(options: CopilotIntelligenceRuntimeOptions) {\n const rawOptions = options as CopilotIntelligenceRuntimeBaseOptions & {\n identifyUser?: unknown;\n channels?: unknown;\n memory?: unknown;\n };\n if (\n rawOptions.identifyUser !== undefined &&\n typeof rawOptions.identifyUser !== \"function\"\n ) {\n throw new Error(\"Intelligence Runtime `identifyUser` must be a callback\");\n }\n if (\n rawOptions.channels !== undefined &&\n !Array.isArray(rawOptions.channels)\n ) {\n throw new Error(\"Intelligence Runtime `channels` must be an array\");\n }\n const hasWebIdentity = typeof rawOptions.identifyUser === \"function\";\n const hasChannels =\n Array.isArray(rawOptions.channels) && rawOptions.channels.length > 0;\n if (!hasWebIdentity && !hasChannels) {\n throw new Error(\n \"Intelligence Runtime requires web `identifyUser`, at least one Channel, or both surfaces\",\n );\n }\n if (\n rawOptions.memory !== undefined &&\n (typeof rawOptions.memory !== \"object\" ||\n rawOptions.memory === null ||\n typeof (rawOptions.memory as { access?: unknown }).access !==\n \"function\")\n ) {\n throw new Error(\n \"Intelligence Runtime `memory.access` must be a callback\",\n );\n }\n if (rawOptions.memory !== undefined && !hasWebIdentity) {\n throw new Error(\n \"Intelligence Runtime web `memory` requires `identifyUser`\",\n );\n }\n super(\n options,\n new IntelligenceAgentRunner({\n url: options.intelligence.ɵgetRunnerWsUrl(),\n authToken: options.intelligence.ɵgetRunnerAuthToken(),\n maxReconnectMs: options.maxReconnectMs,\n maxRejoinMs: options.maxRejoinMs,\n }),\n );\n this.intelligence = options.intelligence;\n this.identifyUser = hasWebIdentity\n ? (rawOptions.identifyUser as IdentifyUserCallback)\n : undefined;\n this.generateThreadNames = options.generateThreadNames ?? true;\n // Telemetry attribution is handled by the base constructor for all modes;\n // here we only need the token for feature gating. Reuse the base-resolved\n // value so gating and attribution can never disagree.\n this.licenseChecker = createLicenseChecker(this.resolvedLicenseToken);\n this.lockTtlSeconds = Math.min(\n options.lockTtlSeconds ?? 20,\n CopilotIntelligenceRuntime.MAX_LOCK_TTL_SECONDS,\n );\n this.lockKeyPrefix = options.lockKeyPrefix;\n this.lockHeartbeatIntervalSeconds = Math.min(\n options.lockHeartbeatIntervalSeconds ?? 15,\n CopilotIntelligenceRuntime.MAX_HEARTBEAT_INTERVAL_SECONDS,\n );\n // Declared Intelligence Channels. Lowercase kebab-case name-shape validation\n // (`assertValidChannelNames`) lives in the channels-intelligence launcher —\n // it can't run here because it's a value import from the pure-ESM\n // `@copilotkit/channels-intelligence`, which this CJS package must not pull in.\n // Name UNIQUENESS across declared Channels is enforced by\n // `ChannelManager.activate()`, not the launcher: the managed path activates\n // one Channel per launcher call, so the launcher never sees the full set.\n // Fail fast on the most common misconfiguration (a missing name) right here\n // at construction, though, rather than only at activation.\n this.channels = [\n ...((rawOptions.channels as readonly Channel[] | undefined) ?? []),\n ];\n for (const c of this.channels) {\n if (!c || typeof c !== \"object\" || !c.name) {\n throw new Error(\n \"Intelligence Channel is missing a `name` — pass createChannel({ name }) for each Channel in `channels`\",\n );\n }\n }\n }\n}\n\nfunction hasIntelligenceOptions(\n options: CopilotRuntimeOptions,\n): options is CopilotIntelligenceRuntimeOptions {\n return \"intelligence\" in options && !!options.intelligence;\n}\n\nexport function isIntelligenceRuntime(\n runtime: CopilotRuntimeLike,\n): runtime is CopilotIntelligenceRuntimeLike {\n return runtime.mode === RUNTIME_MODE_INTELLIGENCE && !!runtime.intelligence;\n}\n\n/**\n * Single source of truth for \"is A2UI on for this runtime?\". Both the run path\n * (which applies `A2UIMiddleware`) and the `/info` response (which tells the\n * client whether to mount the A2UI renderer + catalog context) MUST go through\n * this, so they can never disagree — the divergence between them was the root\n * of CopilotKit/CopilotKit#5369.\n *\n * Backwards compatible: any config object is enabled (matching the historical\n * `!!runtime.a2ui`); only an explicit `enabled: false` turns it off.\n */\nexport function isA2UIEnabled(\n a2ui: CopilotRuntimeOptions[\"a2ui\"],\n): a2ui is NonNullable<CopilotRuntimeOptions[\"a2ui\"]> {\n return !!a2ui && a2ui.enabled !== false;\n}\n\n/**\n * Compile-time phantom brand marking a {@link CopilotRuntime} that was\n * constructed with at least one declared Intelligence Channel. It has no runtime\n * representation — the shim never sets this property; it exists purely so\n * `createCopilotRuntimeHandler` can tell, at the type level, that the resulting\n * handler will carry a non-optional `.channels` control surface.\n */\nexport interface RuntimeWithDeclaredChannels {\n /**\n * @internal Phantom brand key. Never present at runtime; do not read or set.\n */\n readonly __copilotkitChannelsDeclared: true;\n}\n\n/**\n * Instance shape of the {@link CopilotRuntime} compatibility shim. Extends\n * {@link CopilotRuntimeLike} with the Intelligence-only accessors the shim\n * surfaces (all `undefined` in SSE mode). Declared explicitly so the exported\n * `CopilotRuntime` name resolves as a type as well as a value.\n */\nexport interface CopilotRuntime extends CopilotRuntimeLike {\n /** Auto-generate short thread names; `undefined` in SSE mode. */\n generateThreadNames?: boolean;\n /** Thread lock TTL in seconds; `undefined` in SSE mode. */\n lockTtlSeconds?: number;\n /** Custom Redis key prefix for the thread lock; `undefined` in SSE mode. */\n lockKeyPrefix?: string;\n /** Thread lock heartbeat interval in seconds; `undefined` in SSE mode. */\n lockHeartbeatIntervalSeconds?: number;\n /** Declared Intelligence Channels; `undefined` in SSE mode. */\n channels?: Channel[];\n}\n\n/**\n * Constructor type for the {@link CopilotRuntime} compatibility shim.\n *\n * The first overload fires when the caller passes `intelligence` together with a\n * non-empty `channels` tuple: it returns a {@link RuntimeWithDeclaredChannels}-\n * branded runtime, which `createCopilotRuntimeHandler` maps to a handler whose\n * `.channels` is non-optional. Every other configuration (SSE, or Intelligence\n * without channels, or an empty `channels: []`) falls through to the second\n * overload and stays unbranded, so its handler keeps `.channels` optional.\n *\n * A class constructor cannot vary its return type across overloads (it is pinned\n * to the instance type), so the branding lives on this construct-signature\n * interface instead of on the class itself.\n */\nexport interface CopilotRuntimeConstructor {\n new (\n options: CopilotIntelligenceRuntimeBaseOptions &\n (\n | {\n identifyUser: IdentifyUserCallback;\n memory?: CopilotRuntimeMemoryConfig;\n channels: NonEmptyChannels;\n }\n | {\n identifyUser?: undefined;\n memory?: undefined;\n channels: NonEmptyChannels;\n }\n ),\n ): CopilotRuntime & RuntimeWithDeclaredChannels;\n new (options: CopilotRuntimeOptions): CopilotRuntime;\n}\n\n/**\n * Compatibility shim that preserves the legacy `CopilotRuntime` entrypoint.\n * New code should prefer `CopilotSseRuntime` or `CopilotIntelligenceRuntime`.\n *\n * Exported to consumers as the {@link CopilotRuntime} value (typed as\n * {@link CopilotRuntimeConstructor}) rather than as a class, so that the\n * channel-presence brand can flow from construction into the handler type.\n */\nclass CopilotRuntimeShim implements CopilotRuntime {\n private delegate: CopilotRuntimeLike;\n\n constructor(options: CopilotRuntimeOptions) {\n this.delegate = hasIntelligenceOptions(options)\n ? new CopilotIntelligenceRuntime(options)\n : new CopilotSseRuntime(options);\n }\n\n get agents(): CopilotRuntimeOptions[\"agents\"] {\n return this.delegate.agents;\n }\n\n get transcriptionService(): CopilotRuntimeOptions[\"transcriptionService\"] {\n return this.delegate.transcriptionService;\n }\n\n get beforeRequestMiddleware(): CopilotRuntimeOptions[\"beforeRequestMiddleware\"] {\n return this.delegate.beforeRequestMiddleware;\n }\n\n get afterRequestMiddleware(): CopilotRuntimeOptions[\"afterRequestMiddleware\"] {\n return this.delegate.afterRequestMiddleware;\n }\n\n get runner(): AgentRunner {\n return this.delegate.runner;\n }\n\n get a2ui(): CopilotRuntimeOptions[\"a2ui\"] {\n return this.delegate.a2ui;\n }\n\n get mcpApps(): CopilotRuntimeOptions[\"mcpApps\"] {\n return this.delegate.mcpApps;\n }\n\n get openGenerativeUI(): CopilotRuntimeOptions[\"openGenerativeUI\"] {\n return this.delegate.openGenerativeUI;\n }\n\n get intelligence(): CopilotKitIntelligence | undefined {\n return this.delegate.intelligence;\n }\n\n get generateThreadNames(): boolean | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.generateThreadNames\n : undefined;\n }\n\n get identifyUser(): IdentifyUserCallback | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.identifyUser\n : undefined;\n }\n\n get lockTtlSeconds(): number | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.lockTtlSeconds\n : undefined;\n }\n\n get lockKeyPrefix(): string | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.lockKeyPrefix\n : undefined;\n }\n\n get lockHeartbeatIntervalSeconds(): number | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.lockHeartbeatIntervalSeconds\n : undefined;\n }\n\n get channels(): Channel[] | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.channels\n : undefined;\n }\n\n get mode(): RuntimeMode {\n return this.delegate.mode;\n }\n\n get licenseChecker() {\n return this.delegate.licenseChecker;\n }\n\n get debugEventBus() {\n return this.delegate.debugEventBus;\n }\n\n get debug(): ResolvedDebugConfig {\n return this.delegate.debug;\n }\n\n get debugLogger(): CopilotRuntimeLogger | undefined {\n return this.delegate.debugLogger;\n }\n\n get forwardHeadersPolicy(): ResolvedForwardHeadersPolicy {\n return this.delegate.forwardHeadersPolicy;\n }\n\n get exposeMemoryRoutes(): boolean | undefined {\n return this.delegate.exposeMemoryRoutes;\n }\n\n get memory(): CopilotRuntimeMemoryConfig | undefined {\n return this.delegate.memory;\n }\n}\n\n/**\n * The public `CopilotRuntime` constructor. Backed by {@link CopilotRuntimeShim}\n * but typed as {@link CopilotRuntimeConstructor} so that constructing with a\n * non-empty `channels` array yields a {@link RuntimeWithDeclaredChannels}-branded\n * runtime type.\n *\n * The `as unknown as` cast is required (not dishonest widening): the brand is a\n * phantom, compile-time-only marker with no runtime representation, so the shim\n * instances legitimately do not carry the brand property. Behavior is identical\n * to the former `class CopilotRuntime` — this only refines the static type.\n */\nexport const CopilotRuntime: CopilotRuntimeConstructor =\n CopilotRuntimeShim as unknown as CopilotRuntimeConstructor;\n"],"mappings":";;;;;;;;;;;;;;;AA0CA,MAAa,UAAUA,uBAAI;;;;;;AA0E3B,eAAsB,cACpB,QACA,SACwC;AACxC,KAAI,OAAO,WAAW,YAAY;AAChC,MAAI,CAAC,QACH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AClB,SAAO,KAAK,SAAS;;CAGvB,IAAI,QAA6B;AAC/B,SAAO,KAAK,SAAS;;CAGvB,IAAI,cAAgD;AAClD,SAAO,KAAK,SAAS;;CAGvB,IAAI,uBAAqD;AACvD,SAAO,KAAK,SAAS;;CAGvB,IAAI,qBAA0C;AAC5C,SAAO,KAAK,SAAS;;CAGvB,IAAI,SAAiD;AACnD,SAAO,KAAK,SAAS;;;;;;;;;;;;;;AAezB,MAAa,iBACX"}
|
|
1
|
+
{"version":3,"file":"runtime.mjs","names":["pkg"],"sources":["../../../../src/v2/runtime/core/runtime.ts"],"sourcesContent":["import type {\n MaybePromise,\n NonEmptyRecord,\n RuntimeMode,\n} from \"@copilotkit/shared\";\nimport {\n RUNTIME_MODE_SSE,\n RUNTIME_MODE_INTELLIGENCE,\n} from \"@copilotkit/shared\";\nimport { createLicenseChecker } from \"@copilotkit/license-verifier\";\nimport type { LicenseChecker } from \"@copilotkit/license-verifier\";\nimport { resolveDebugConfig } from \"@copilotkit/shared\";\nimport type { ResolvedDebugConfig, DebugConfig } from \"@copilotkit/shared\";\nimport { resolveForwardHeadersPolicy } from \"../handlers/header-utils\";\nimport type {\n ForwardHeadersConfig,\n ResolvedForwardHeadersPolicy,\n} from \"../handlers/header-utils\";\nimport type { AbstractAgent } from \"@ag-ui/client\";\nimport type { MCPClientConfig } from \"@ag-ui/mcp-apps-middleware\";\nimport type { A2UIMiddlewareConfig } from \"@ag-ui/a2ui-middleware\";\nimport pkg from \"../../../../package.json\";\nimport type {\n BeforeRequestMiddleware,\n AfterRequestMiddleware,\n} from \"./middleware\";\nimport { createLogger } from \"../../../lib/logger\";\nimport type { CopilotRuntimeLogger } from \"../../../lib/logger\";\nimport { logRuntimeTelemetryDisclosure } from \"../../../lib/telemetry-disclosure\";\nimport type { TranscriptionService } from \"../transcription-service/transcription-service\";\nimport { DebugEventBus } from \"./debug-event-bus\";\nimport type { AgentRunner } from \"../runner/agent-runner\";\nimport { InMemoryAgentRunner } from \"../runner/in-memory\";\nimport { IntelligenceAgentRunner } from \"../runner/intelligence\";\nimport type { CopilotKitIntelligence } from \"../intelligence-platform\";\n// Type-only: @copilotkit/channels-core is the pure-ESM type source, so a value import would break this\n// package's CJS output. The channels are validated + activated (wired to delivery\n// transports) by `startChannels` from @copilotkit/channels-intelligence, called\n// by the Channel-listener bootstrap — not here.\nimport type { Channel } from \"@copilotkit/channels-core\";\nimport telemetry from \"../telemetry/telemetry-client\";\nimport {\n attachRuntimeErrorReporter,\n getRuntimeErrorReporterFromOptions,\n} from \"./runtime-error-reporter\";\nimport type { CopilotRuntimeLearningConfig } from \"./learning\";\nimport { assertStableLearningContainerId } from \"./learning\";\n\nexport type {\n CopilotRuntimeLearningConfig,\n CopilotRuntimeLearningContext,\n} from \"./learning\";\n\nexport const VERSION = pkg.version;\n\ninterface BaseCopilotRuntimeMiddlewareOptions {\n /** If set, middleware only applies to these named agents. Applies to all agents if omitted. */\n agents?: string[];\n}\n\n/** Per-server tool policy belongs to the external middleware and is unsupported at its pinned 0.0.3 release. */\nexport type McpAppsServerConfig = MCPClientConfig & {\n /** Agent to bind this server to. If omitted, the server is available to all agents. */\n agentId?: string;\n};\n\nexport interface McpAppsConfig {\n /** List of MCP server configurations. */\n servers: McpAppsServerConfig[];\n}\n\nexport interface OpenGenerativeUIOptions extends BaseCopilotRuntimeMiddlewareOptions {}\n\nexport type OpenGenerativeUIConfig = boolean | OpenGenerativeUIOptions;\n\ninterface CopilotRuntimeMiddlewares {\n /**\n * Auto-apply A2UIMiddleware to agents at run time.\n * Pass an object to enable and customise behaviour, or omit to disable.\n */\n a2ui?: BaseCopilotRuntimeMiddlewareOptions &\n A2UIMiddlewareConfig & {\n /**\n * Explicit on/off switch. Omit (or set `true`) to enable; set `false`\n * to disable A2UI for this runtime while keeping the rest of the config\n * (e.g. a `schema`/`catalog`) in place. A bare `a2ui: {}` stays enabled\n * for backwards compatibility.\n */\n enabled?: boolean;\n };\n /** Auto-apply MCPAppsMiddleware to agents at run time. */\n mcpApps?: McpAppsConfig;\n /** Auto-apply OpenGenerativeUIMiddleware to agents at run time. */\n openGenerativeUI?: OpenGenerativeUIConfig;\n}\n\n/**\n * Context passed to agent factory functions for per-request agent resolution.\n */\nexport interface AgentFactoryContext {\n /** The incoming HTTP request. */\n request: Request;\n}\n\n/**\n * A function that dynamically creates agents on a per-request basis.\n * Useful for multi-tenant scenarios or request-scoped agent configuration.\n */\nexport type AgentsFactory = (\n ctx: AgentFactoryContext,\n) => MaybePromise<NonEmptyRecord<Record<string, AbstractAgent>>>;\n\n/**\n * Agents can be provided as:\n * - A static record of agents\n * - A Promise that resolves to a record of agents\n * - A factory function that receives request context and returns agents (or a Promise of agents)\n */\nexport type AgentsConfig =\n | MaybePromise<NonEmptyRecord<Record<string, AbstractAgent>>>\n | AgentsFactory;\n\n/**\n * Resolve an AgentsConfig value to a concrete record of agents.\n * If the config is a factory function, it is called with the given request context.\n * Otherwise it is awaited directly (static record or Promise).\n */\nexport async function resolveAgents(\n agents: AgentsConfig,\n request?: Request,\n): Promise<Record<string, AbstractAgent>> {\n if (typeof agents === \"function\") {\n if (!request) {\n throw new Error(\n \"Agent factory function requires a request context, but none was provided.\",\n );\n }\n return agents({ request });\n }\n return agents;\n}\n\ninterface BaseCopilotRuntimeOptions extends CopilotRuntimeMiddlewares {\n /**\n * Map of available agents, or a factory function for per-request agent resolution.\n *\n * Static record:\n * ```ts\n * agents: { support: new SupportAgent(), technical: new TechnicalAgent() }\n * ```\n *\n * Factory function (called per-request):\n * ```ts\n * agents: ({ request }) => {\n * const tenantId = request.headers.get(\"x-tenant-id\");\n * return { default: createAgentForTenant(tenantId) };\n * }\n * ```\n */\n agents: AgentsConfig;\n /** Optional transcription service for audio processing. */\n transcriptionService?: TranscriptionService;\n /** Optional *before* middleware – callback function or webhook URL. */\n beforeRequestMiddleware?: BeforeRequestMiddleware;\n /** Optional *after* middleware – callback function or webhook URL. */\n afterRequestMiddleware?: AfterRequestMiddleware;\n /** Signed license token for server-side feature verification. Falls back to COPILOTKIT_LICENSE_TOKEN env var. */\n licenseToken?: string;\n /** Enable debug logging for the event pipeline. */\n debug?: DebugConfig;\n /**\n * Policy controlling which inbound HTTP headers are forwarded onto the\n * outgoing agent call. By default a built-in denylist strips known\n * infrastructure/proxy/platform headers (`x-forwarded-*`, `x-real-ip`,\n * `x-vercel-*`, `x-copilotcloud-*`, etc.) while `authorization` and custom\n * `x-*` application headers continue to forward (#5712). Set\n * `{ useDefaultDenylist: false }` to restore the previous wide-open behavior.\n */\n forwardHeaders?: ForwardHeadersConfig;\n /**\n * Opt-in flag exposing the client-facing memory proxy routes\n * (`/memories`, `/memories/recall`, `/memories/subscribe`, `/memories/:id`).\n *\n * Defaults to `false` — a **secure default**. When off, every `/memories/*`\n * request 404s as if the route did not exist, so an un-opted-in deployment\n * reveals nothing about memory even when Intelligence is configured. This does\n * NOT affect the agent's own server-side memory tooling (`recall_memory` runs\n * via the Intelligence MCP path, separate from this client REST proxy).\n *\n * Flip to `true` to power a client memory inspector (e.g. the dev console's\n * Memory tab). Existing Intelligence deployments relying on the previously\n * always-on Learning tab must set this to restore it.\n *\n * @deprecated Configure `memory.access` on an Intelligence Runtime. That one\n * policy enables and limits both agent and browser Memory.\n */\n exposeMemoryRoutes?: boolean;\n}\n\nexport interface CopilotRuntimeUser {\n id: string;\n name: string;\n}\n\nexport type IdentifyUserCallback = (\n request: Request,\n) => MaybePromise<CopilotRuntimeUser>;\n\nexport type MemoryAccess = \"none\" | \"read\" | \"read-write\";\n\nexport interface MemoryGrant {\n readonly user: MemoryAccess;\n readonly project: MemoryAccess;\n}\n\nexport type MemoryConsumer = \"agent\" | \"client\";\n\nexport interface CopilotRuntimeMemoryConfig {\n /** Resolves immutable Memory access for one authenticated web request. */\n access(input: {\n readonly request: Request;\n readonly user: CopilotRuntimeUser;\n readonly consumer: MemoryConsumer;\n }): MaybePromise<MemoryGrant | null>;\n}\n\nexport interface CopilotSseRuntimeOptions extends BaseCopilotRuntimeOptions {\n /** The runner to use for running agents in SSE mode. */\n runner?: AgentRunner;\n intelligence?: undefined;\n generateThreadNames?: undefined;\n /** Intelligence Channels require the Intelligence runtime; not available in SSE mode. */\n channels?: undefined;\n}\n\ninterface CopilotIntelligenceRuntimeBaseOptions extends BaseCopilotRuntimeOptions {\n /** Configures Intelligence mode for durable threads and realtime events. */\n intelligence: CopilotKitIntelligence;\n /** Chooses one stable Learning Container ID for each web or Channel run. */\n ɵlearning?: CopilotRuntimeLearningConfig;\n /** Auto-generate short names for newly created threads. */\n generateThreadNames?: boolean;\n /** Max delay (ms) for WebSocket reconnect backoff. @default 10_000 */\n maxReconnectMs?: number;\n /** Max delay (ms) for channel rejoin backoff. @default 30_000 */\n maxRejoinMs?: number;\n /** Lock TTL in seconds. Clamped to a maximum of 3600 (1 hour). @default 20 */\n lockTtlSeconds?: number;\n /** Custom Redis key prefix for the thread lock. */\n lockKeyPrefix?: string;\n /** Interval in seconds at which the runtime renews the thread lock. Clamped to a maximum of 3000 (50 minutes). @default 15 */\n lockHeartbeatIntervalSeconds?: number;\n /**\n * Intelligence Channels declared by this runtime. Each is a\n * `createChannel({ name })` instance. Only available on the Intelligence runtime\n * path. Names are validated (required, lowercase kebab-case, unique) and wired\n * to delivery/egress transports when activated via `startChannels` from\n * `@copilotkit/channels-intelligence` — not at construction.\n */\n}\n\ntype NonEmptyChannels = readonly [Channel, ...Channel[]];\n\n/** Intelligence runtime options with web identity, Channels, or both. */\nexport type CopilotIntelligenceRuntimeOptions =\n CopilotIntelligenceRuntimeBaseOptions &\n (\n | {\n /** Resolves the authenticated user for web requests. */\n identifyUser: IdentifyUserCallback;\n /** Enables agent and browser Memory under one request policy. */\n memory?: CopilotRuntimeMemoryConfig;\n channels?: readonly Channel[];\n }\n | {\n /** Channels-only runtimes expose no functional web surface. */\n identifyUser?: undefined;\n memory?: undefined;\n channels: NonEmptyChannels;\n }\n );\n\nexport type CopilotRuntimeOptions =\n | CopilotSseRuntimeOptions\n | CopilotIntelligenceRuntimeOptions;\n\nexport interface CopilotRuntimeLike {\n agents: CopilotRuntimeOptions[\"agents\"];\n transcriptionService: CopilotRuntimeOptions[\"transcriptionService\"];\n beforeRequestMiddleware: CopilotRuntimeOptions[\"beforeRequestMiddleware\"];\n afterRequestMiddleware: CopilotRuntimeOptions[\"afterRequestMiddleware\"];\n runner: AgentRunner;\n a2ui: CopilotRuntimeOptions[\"a2ui\"];\n mcpApps: CopilotRuntimeOptions[\"mcpApps\"];\n openGenerativeUI: CopilotRuntimeOptions[\"openGenerativeUI\"];\n intelligence?: CopilotKitIntelligence;\n identifyUser?: IdentifyUserCallback;\n mode: RuntimeMode;\n licenseChecker?: LicenseChecker;\n debugEventBus?: DebugEventBus;\n debug: ResolvedDebugConfig;\n debugLogger?: CopilotRuntimeLogger;\n /**\n * Resolved inbound-header forwarding policy read by the /run and /connect call\n * sites. Optional on the published interface so an external `CopilotRuntimeLike`\n * implementor predating this field stays source-compatible (non-breaking minor\n * release). Concrete runtimes (`BaseCopilotRuntime`) always resolve and set it;\n * the call sites coalesce a missing value to the default resolved policy\n * (`resolveForwardHeadersPolicy(undefined)` — default-on denylist).\n */\n forwardHeadersPolicy?: ResolvedForwardHeadersPolicy;\n /**\n * Resolved opt-in flag for the client-facing memory proxy routes. Optional on\n * the published interface so an external `CopilotRuntimeLike` implementor\n * predating this field stays source-compatible; the dispatcher coalesces a\n * missing value to `false` (secure default — routes hidden). Concrete runtimes\n * (`BaseCopilotRuntime`) always resolve and set it.\n */\n exposeMemoryRoutes?: boolean;\n memory?: CopilotRuntimeMemoryConfig;\n learning?: CopilotRuntimeLearningConfig;\n}\n\nexport interface CopilotSseRuntimeLike extends CopilotRuntimeLike {\n intelligence?: undefined;\n mode: typeof RUNTIME_MODE_SSE;\n}\n\nexport interface CopilotIntelligenceRuntimeLike extends CopilotRuntimeLike {\n intelligence: CopilotKitIntelligence;\n identifyUser?: IdentifyUserCallback;\n generateThreadNames: boolean;\n lockTtlSeconds: number;\n lockKeyPrefix?: string;\n lockHeartbeatIntervalSeconds: number;\n channels: Channel[];\n learning?: CopilotRuntimeLearningConfig;\n mode: typeof RUNTIME_MODE_INTELLIGENCE;\n}\n\nabstract class BaseCopilotRuntime implements CopilotRuntimeLike {\n public agents: CopilotRuntimeOptions[\"agents\"];\n public transcriptionService: CopilotRuntimeOptions[\"transcriptionService\"];\n public beforeRequestMiddleware: CopilotRuntimeOptions[\"beforeRequestMiddleware\"];\n public afterRequestMiddleware: CopilotRuntimeOptions[\"afterRequestMiddleware\"];\n public runner: AgentRunner;\n public a2ui: CopilotRuntimeOptions[\"a2ui\"];\n public mcpApps: CopilotRuntimeOptions[\"mcpApps\"];\n public openGenerativeUI: CopilotRuntimeOptions[\"openGenerativeUI\"];\n public licenseChecker?: LicenseChecker;\n public readonly debugEventBus?: DebugEventBus;\n public debug: ResolvedDebugConfig;\n public debugLogger?: CopilotRuntimeLogger;\n public readonly forwardHeadersPolicy: ResolvedForwardHeadersPolicy;\n public readonly exposeMemoryRoutes: boolean;\n public readonly memory?: CopilotRuntimeMemoryConfig;\n\n /**\n * License token resolved once with the env fallback, so telemetry\n * attribution (below) and subclass feature gating\n * (CopilotIntelligenceRuntime's licenseChecker) read the exact same value\n * instead of each re-applying `?? COPILOTKIT_LICENSE_TOKEN`.\n */\n protected readonly resolvedLicenseToken?: string;\n\n abstract readonly intelligence?: CopilotKitIntelligence;\n abstract readonly mode: RuntimeMode;\n\n constructor(options: BaseCopilotRuntimeOptions, runner: AgentRunner) {\n logRuntimeTelemetryDisclosure();\n\n const {\n agents,\n transcriptionService,\n beforeRequestMiddleware,\n afterRequestMiddleware,\n a2ui,\n mcpApps,\n openGenerativeUI,\n } = options;\n\n this.agents = agents;\n this.transcriptionService = transcriptionService;\n this.beforeRequestMiddleware = beforeRequestMiddleware;\n this.afterRequestMiddleware = afterRequestMiddleware;\n this.a2ui = a2ui || undefined;\n this.mcpApps = mcpApps;\n this.openGenerativeUI = openGenerativeUI;\n this.runner = runner;\n\n // Resolve the license token once (matching the license-verifier's env\n // fallback) so telemetry attribution and subclass feature gating share\n // one value.\n this.resolvedLicenseToken =\n options.licenseToken ?? process.env.COPILOTKIT_LICENSE_TOKEN;\n\n // Attribute telemetry to the licensed customer for *every* runtime mode.\n // Done in the shared base (not the subclasses) so SSE and Intelligence\n // runtimes behave identically — previously only CopilotIntelligenceRuntime\n // set this, so self-hosted SSE users never got a telemetry_id on their\n // runtime events even with a license token configured.\n if (this.resolvedLicenseToken) {\n telemetry.setLicenseToken(this.resolvedLicenseToken);\n }\n\n if (process.env.NODE_ENV !== \"production\") {\n this.debugEventBus = new DebugEventBus();\n }\n // Resolve the inbound-header forwarding policy once (mirroring the\n // `debug` → `ResolvedDebugConfig` resolve-once above) so both the /run and\n // /connect call sites read the exact same resolved policy off the runtime\n // and can never diverge.\n this.forwardHeadersPolicy = resolveForwardHeadersPolicy(\n options.forwardHeaders,\n );\n // Secure default: the client-facing memory proxy routes stay hidden (404)\n // unless a deployment explicitly opts in.\n this.memory = (options as { memory?: CopilotRuntimeMemoryConfig }).memory;\n this.exposeMemoryRoutes =\n this.memory !== undefined || (options.exposeMemoryRoutes ?? false);\n this.debug = resolveDebugConfig(options.debug);\n if (this.debug.enabled) {\n this.debugLogger = createLogger({\n level: \"debug\",\n component: \"copilotkit-debug\",\n });\n }\n }\n}\n\nexport class CopilotSseRuntime\n extends BaseCopilotRuntime\n implements CopilotSseRuntimeLike\n{\n readonly intelligence = undefined;\n readonly mode = RUNTIME_MODE_SSE;\n\n constructor(options: CopilotSseRuntimeOptions) {\n // Runtime guard mirroring the discriminated-union type: the SSE runtime has\n // no Intelligence delivery path, so `channels` cannot be honored here. The\n // type forbids it, but a JS / `as any` caller passing `{ agents, channels }`\n // would otherwise land here and have `channels` silently dropped — fail\n // loud instead.\n const channels = (options as { channels?: unknown[] }).channels;\n if (Array.isArray(channels) && channels.length > 0) {\n throw new Error(\n \"`channels` requires the Intelligence runtime (pass `intelligence`); \" +\n \"Intelligence Channels are not available in SSE mode.\",\n );\n }\n if ((options as { ɵlearning?: unknown }).ɵlearning !== undefined) {\n throw new Error(\n \"`ɵlearning` requires the Intelligence runtime (pass `intelligence`); \" +\n \"Learning Containers are not available in SSE mode.\",\n );\n }\n super(options, options.runner ?? new InMemoryAgentRunner());\n }\n}\n\nexport class CopilotIntelligenceRuntime\n extends BaseCopilotRuntime\n implements CopilotIntelligenceRuntimeLike\n{\n readonly intelligence: CopilotKitIntelligence;\n readonly identifyUser?: IdentifyUserCallback;\n readonly generateThreadNames: boolean;\n readonly lockTtlSeconds: number;\n readonly lockKeyPrefix?: string;\n readonly lockHeartbeatIntervalSeconds: number;\n readonly channels: Channel[];\n readonly learning?: CopilotRuntimeLearningConfig;\n readonly mode = RUNTIME_MODE_INTELLIGENCE;\n\n /** Maximum allowed lock TTL in seconds (1 hour). */\n static readonly MAX_LOCK_TTL_SECONDS = 3_600;\n /** Maximum allowed heartbeat interval in seconds (50 minutes). */\n static readonly MAX_HEARTBEAT_INTERVAL_SECONDS = 3_000;\n\n constructor(options: CopilotIntelligenceRuntimeOptions) {\n const rawOptions = options as CopilotIntelligenceRuntimeBaseOptions & {\n identifyUser?: unknown;\n channels?: unknown;\n memory?: unknown;\n ɵlearning?: unknown;\n };\n if (\n rawOptions.identifyUser !== undefined &&\n typeof rawOptions.identifyUser !== \"function\"\n ) {\n throw new Error(\"Intelligence Runtime `identifyUser` must be a callback\");\n }\n if (\n rawOptions.channels !== undefined &&\n !Array.isArray(rawOptions.channels)\n ) {\n throw new Error(\"Intelligence Runtime `channels` must be an array\");\n }\n const hasWebIdentity = typeof rawOptions.identifyUser === \"function\";\n const hasChannels =\n Array.isArray(rawOptions.channels) && rawOptions.channels.length > 0;\n if (!hasWebIdentity && !hasChannels) {\n throw new Error(\n \"Intelligence Runtime requires web `identifyUser`, at least one Channel, or both surfaces\",\n );\n }\n if (\n rawOptions.memory !== undefined &&\n (typeof rawOptions.memory !== \"object\" ||\n rawOptions.memory === null ||\n typeof (rawOptions.memory as { access?: unknown }).access !==\n \"function\")\n ) {\n throw new Error(\n \"Intelligence Runtime `memory.access` must be a callback\",\n );\n }\n if (rawOptions.memory !== undefined && !hasWebIdentity) {\n throw new Error(\n \"Intelligence Runtime web `memory` requires `identifyUser`\",\n );\n }\n if (\n rawOptions.ɵlearning !== undefined &&\n (typeof rawOptions.ɵlearning !== \"object\" ||\n rawOptions.ɵlearning === null ||\n !(\n typeof (rawOptions.ɵlearning as { containerId?: unknown })\n .containerId === \"string\" ||\n typeof (rawOptions.ɵlearning as { containerId?: unknown })\n .containerId === \"function\"\n ))\n ) {\n throw new Error(\n \"Intelligence Runtime `ɵlearning.containerId` must be a stable ID or callback\",\n );\n }\n if (\n typeof (rawOptions.ɵlearning as { containerId?: unknown } | undefined)\n ?.containerId === \"string\"\n ) {\n assertStableLearningContainerId(\n (rawOptions.ɵlearning as { containerId: string }).containerId,\n );\n }\n super(\n options,\n new IntelligenceAgentRunner({\n url: options.intelligence.ɵgetRunnerWsUrl(),\n authToken: options.intelligence.ɵgetRunnerAuthToken(),\n maxReconnectMs: options.maxReconnectMs,\n maxRejoinMs: options.maxRejoinMs,\n }),\n );\n this.intelligence = options.intelligence;\n this.learning = options.ɵlearning;\n this.identifyUser = hasWebIdentity\n ? (rawOptions.identifyUser as IdentifyUserCallback)\n : undefined;\n this.generateThreadNames = options.generateThreadNames ?? true;\n // Telemetry attribution is handled by the base constructor for all modes;\n // here we only need the token for feature gating. Reuse the base-resolved\n // value so gating and attribution can never disagree.\n this.licenseChecker = createLicenseChecker(this.resolvedLicenseToken);\n this.lockTtlSeconds = Math.min(\n options.lockTtlSeconds ?? 20,\n CopilotIntelligenceRuntime.MAX_LOCK_TTL_SECONDS,\n );\n this.lockKeyPrefix = options.lockKeyPrefix;\n this.lockHeartbeatIntervalSeconds = Math.min(\n options.lockHeartbeatIntervalSeconds ?? 15,\n CopilotIntelligenceRuntime.MAX_HEARTBEAT_INTERVAL_SECONDS,\n );\n // Declared Intelligence Channels. Lowercase kebab-case name-shape validation\n // (`assertValidChannelNames`) lives in the channels-intelligence launcher —\n // it can't run here because it's a value import from the pure-ESM\n // `@copilotkit/channels-intelligence`, which this CJS package must not pull in.\n // Name UNIQUENESS across declared Channels is enforced by\n // `ChannelManager.activate()`, not the launcher: the managed path activates\n // one Channel per launcher call, so the launcher never sees the full set.\n // Fail fast on the most common misconfiguration (a missing name) right here\n // at construction, though, rather than only at activation.\n this.channels = [\n ...((rawOptions.channels as readonly Channel[] | undefined) ?? []),\n ];\n for (const c of this.channels) {\n if (!c || typeof c !== \"object\" || !c.name) {\n throw new Error(\n \"Intelligence Channel is missing a `name` — pass createChannel({ name }) for each Channel in `channels`\",\n );\n }\n }\n }\n}\n\nfunction hasIntelligenceOptions(\n options: CopilotRuntimeOptions,\n): options is CopilotIntelligenceRuntimeOptions {\n return \"intelligence\" in options && !!options.intelligence;\n}\n\nexport function isIntelligenceRuntime(\n runtime: CopilotRuntimeLike,\n): runtime is CopilotIntelligenceRuntimeLike {\n return runtime.mode === RUNTIME_MODE_INTELLIGENCE && !!runtime.intelligence;\n}\n\n/**\n * Single source of truth for \"is A2UI on for this runtime?\". Both the run path\n * (which applies `A2UIMiddleware`) and the `/info` response (which tells the\n * client whether to mount the A2UI renderer + catalog context) MUST go through\n * this, so they can never disagree — the divergence between them was the root\n * of CopilotKit/CopilotKit#5369.\n *\n * Backwards compatible: any config object is enabled (matching the historical\n * `!!runtime.a2ui`); only an explicit `enabled: false` turns it off.\n */\nexport function isA2UIEnabled(\n a2ui: CopilotRuntimeOptions[\"a2ui\"],\n): a2ui is NonNullable<CopilotRuntimeOptions[\"a2ui\"]> {\n return !!a2ui && a2ui.enabled !== false;\n}\n\n/**\n * Compile-time phantom brand marking a {@link CopilotRuntime} that was\n * constructed with at least one declared Intelligence Channel. It has no runtime\n * representation — the shim never sets this property; it exists purely so\n * `createCopilotRuntimeHandler` can tell, at the type level, that the resulting\n * handler will carry a non-optional `.channels` control surface.\n */\nexport interface RuntimeWithDeclaredChannels {\n /**\n * @internal Phantom brand key. Never present at runtime; do not read or set.\n */\n readonly __copilotkitChannelsDeclared: true;\n}\n\n/**\n * Instance shape of the {@link CopilotRuntime} compatibility shim. Extends\n * {@link CopilotRuntimeLike} with the Intelligence-only accessors the shim\n * surfaces (all `undefined` in SSE mode). Declared explicitly so the exported\n * `CopilotRuntime` name resolves as a type as well as a value.\n */\nexport interface CopilotRuntime extends CopilotRuntimeLike {\n /** Auto-generate short thread names; `undefined` in SSE mode. */\n generateThreadNames?: boolean;\n /** Thread lock TTL in seconds; `undefined` in SSE mode. */\n lockTtlSeconds?: number;\n /** Custom Redis key prefix for the thread lock; `undefined` in SSE mode. */\n lockKeyPrefix?: string;\n /** Thread lock heartbeat interval in seconds; `undefined` in SSE mode. */\n lockHeartbeatIntervalSeconds?: number;\n /** Declared Intelligence Channels; `undefined` in SSE mode. */\n channels?: Channel[];\n /** Learning Container selector; `undefined` in SSE mode. */\n learning?: CopilotRuntimeLearningConfig;\n}\n\n/**\n * Constructor type for the {@link CopilotRuntime} compatibility shim.\n *\n * The first overload fires when the caller passes `intelligence` together with a\n * non-empty `channels` tuple: it returns a {@link RuntimeWithDeclaredChannels}-\n * branded runtime, which `createCopilotRuntimeHandler` maps to a handler whose\n * `.channels` is non-optional. Every other configuration (SSE, or Intelligence\n * without channels, or an empty `channels: []`) falls through to the second\n * overload and stays unbranded, so its handler keeps `.channels` optional.\n *\n * A class constructor cannot vary its return type across overloads (it is pinned\n * to the instance type), so the branding lives on this construct-signature\n * interface instead of on the class itself.\n */\nexport interface CopilotRuntimeConstructor {\n new (\n options: CopilotIntelligenceRuntimeBaseOptions &\n (\n | {\n identifyUser: IdentifyUserCallback;\n memory?: CopilotRuntimeMemoryConfig;\n channels: NonEmptyChannels;\n }\n | {\n identifyUser?: undefined;\n memory?: undefined;\n channels: NonEmptyChannels;\n }\n ),\n ): CopilotRuntime & RuntimeWithDeclaredChannels;\n new (options: CopilotRuntimeOptions): CopilotRuntime;\n}\n\n/**\n * Compatibility shim that preserves the legacy `CopilotRuntime` entrypoint.\n * New code should prefer `CopilotSseRuntime` or `CopilotIntelligenceRuntime`.\n *\n * Exported to consumers as the {@link CopilotRuntime} value (typed as\n * {@link CopilotRuntimeConstructor}) rather than as a class, so that the\n * channel-presence brand can flow from construction into the handler type.\n */\nclass CopilotRuntimeShim implements CopilotRuntime {\n private delegate: CopilotRuntimeLike;\n\n constructor(options: CopilotRuntimeOptions) {\n this.delegate = hasIntelligenceOptions(options)\n ? new CopilotIntelligenceRuntime(options)\n : new CopilotSseRuntime(options);\n\n const reporter = getRuntimeErrorReporterFromOptions(options);\n if (reporter) {\n attachRuntimeErrorReporter(this, reporter);\n }\n }\n\n get agents(): CopilotRuntimeOptions[\"agents\"] {\n return this.delegate.agents;\n }\n\n get transcriptionService(): CopilotRuntimeOptions[\"transcriptionService\"] {\n return this.delegate.transcriptionService;\n }\n\n get beforeRequestMiddleware(): CopilotRuntimeOptions[\"beforeRequestMiddleware\"] {\n return this.delegate.beforeRequestMiddleware;\n }\n\n get afterRequestMiddleware(): CopilotRuntimeOptions[\"afterRequestMiddleware\"] {\n return this.delegate.afterRequestMiddleware;\n }\n\n get runner(): AgentRunner {\n return this.delegate.runner;\n }\n\n get a2ui(): CopilotRuntimeOptions[\"a2ui\"] {\n return this.delegate.a2ui;\n }\n\n get mcpApps(): CopilotRuntimeOptions[\"mcpApps\"] {\n return this.delegate.mcpApps;\n }\n\n get openGenerativeUI(): CopilotRuntimeOptions[\"openGenerativeUI\"] {\n return this.delegate.openGenerativeUI;\n }\n\n get intelligence(): CopilotKitIntelligence | undefined {\n return this.delegate.intelligence;\n }\n\n get generateThreadNames(): boolean | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.generateThreadNames\n : undefined;\n }\n\n get identifyUser(): IdentifyUserCallback | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.identifyUser\n : undefined;\n }\n\n get lockTtlSeconds(): number | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.lockTtlSeconds\n : undefined;\n }\n\n get lockKeyPrefix(): string | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.lockKeyPrefix\n : undefined;\n }\n\n get lockHeartbeatIntervalSeconds(): number | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.lockHeartbeatIntervalSeconds\n : undefined;\n }\n\n get channels(): Channel[] | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.channels\n : undefined;\n }\n\n get learning(): CopilotRuntimeLearningConfig | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.learning\n : undefined;\n }\n\n get mode(): RuntimeMode {\n return this.delegate.mode;\n }\n\n get licenseChecker() {\n return this.delegate.licenseChecker;\n }\n\n get debugEventBus() {\n return this.delegate.debugEventBus;\n }\n\n get debug(): ResolvedDebugConfig {\n return this.delegate.debug;\n }\n\n get debugLogger(): CopilotRuntimeLogger | undefined {\n return this.delegate.debugLogger;\n }\n\n get forwardHeadersPolicy(): ResolvedForwardHeadersPolicy {\n return this.delegate.forwardHeadersPolicy;\n }\n\n get exposeMemoryRoutes(): boolean | undefined {\n return this.delegate.exposeMemoryRoutes;\n }\n\n get memory(): CopilotRuntimeMemoryConfig | undefined {\n return this.delegate.memory;\n }\n}\n\n/**\n * The public `CopilotRuntime` constructor. Backed by {@link CopilotRuntimeShim}\n * but typed as {@link CopilotRuntimeConstructor} so that constructing with a\n * non-empty `channels` array yields a {@link RuntimeWithDeclaredChannels}-branded\n * runtime type.\n *\n * The `as unknown as` cast is required (not dishonest widening): the brand is a\n * phantom, compile-time-only marker with no runtime representation, so the shim\n * instances legitimately do not carry the brand property. Behavior is identical\n * to the former `class CopilotRuntime` — this only refines the static type.\n */\nexport const CopilotRuntime: CopilotRuntimeConstructor =\n CopilotRuntimeShim as unknown as CopilotRuntimeConstructor;\n"],"mappings":";;;;;;;;;;;;;;;;;AAqDA,MAAa,UAAUA,uBAAI;;;;;;AA0E3B,eAAsB,cACpB,QAC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GACvC,KAAK,SAAS,eACd;;CAGN,IAAI,iBAAqC;AACvC,SAAO,sBAAsB,KAAK,SAAS,GACvC,KAAK,SAAS,iBACd;;CAGN,IAAI,gBAAoC;AACtC,SAAO,sBAAsB,KAAK,SAAS,GACvC,KAAK,SAAS,gBACd;;CAGN,IAAI,+BAAmD;AACrD,SAAO,sBAAsB,KAAK,SAAS,GACvC,KAAK,SAAS,+BACd;;CAGN,IAAI,WAAkC;AACpC,SAAO,sBAAsB,KAAK,SAAS,GACvC,KAAK,SAAS,WACd;;CAGN,IAAI,WAAqD;AACvD,SAAO,sBAAsB,KAAK,SAAS,GACvC,KAAK,SAAS,WACd;;CAGN,IAAI,OAAoB;AACtB,SAAO,KAAK,SAAS;;CAGvB,IAAI,iBAAiB;AACnB,SAAO,KAAK,SAAS;;CAGvB,IAAI,gBAAgB;AAClB,SAAO,KAAK,SAAS;;CAGvB,IAAI,QAA6B;AAC/B,SAAO,KAAK,SAAS;;CAGvB,IAAI,cAAgD;AAClD,SAAO,KAAK,SAAS;;CAGvB,IAAI,uBAAqD;AACvD,SAAO,KAAK,SAAS;;CAGvB,IAAI,qBAA0C;AAC5C,SAAO,KAAK,SAAS;;CAGvB,IAAI,SAAiD;AACnD,SAAO,KAAK,SAAS;;;;;;;;;;;;;;AAezB,MAAa,iBACX"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
require("reflect-metadata");
|
|
2
2
|
const require_telemetry_client = require('../telemetry/telemetry-client.cjs');
|
|
3
|
+
const require_runtime_error_reporter = require('../core/runtime-error-reporter.cjs');
|
|
3
4
|
const require_runtime = require('../core/runtime.cjs');
|
|
4
5
|
const require_agent_utils = require('./shared/agent-utils.cjs');
|
|
5
6
|
const require_run = require('./intelligence/run.cjs');
|
|
@@ -7,6 +8,7 @@ const require_run$1 = require('./sse/run.cjs');
|
|
|
7
8
|
|
|
8
9
|
//#region src/v2/runtime/handlers/handle-run.ts
|
|
9
10
|
async function handleRunAgent({ runtime, request, agentId }) {
|
|
11
|
+
const startTime = Date.now();
|
|
10
12
|
require_telemetry_client.default.capture("oss.runtime.copilot_request_created", {
|
|
11
13
|
"cloud.guardrails.enabled": false,
|
|
12
14
|
requestType: "run",
|
|
@@ -44,7 +46,8 @@ async function handleRunAgent({ runtime, request, agentId }) {
|
|
|
44
46
|
request,
|
|
45
47
|
agentId,
|
|
46
48
|
agent,
|
|
47
|
-
input
|
|
49
|
+
input,
|
|
50
|
+
startTime
|
|
48
51
|
});
|
|
49
52
|
return require_run$1.handleSseRun({
|
|
50
53
|
runtime,
|
|
@@ -53,9 +56,18 @@ async function handleRunAgent({ runtime, request, agentId }) {
|
|
|
53
56
|
input,
|
|
54
57
|
agentId,
|
|
55
58
|
debug: runtime.debug,
|
|
56
|
-
logger: runtime.debugLogger
|
|
59
|
+
logger: runtime.debugLogger,
|
|
60
|
+
startTime
|
|
57
61
|
});
|
|
58
62
|
} catch (error) {
|
|
63
|
+
require_runtime_error_reporter.getRuntimeErrorReporter(runtime)?.report({
|
|
64
|
+
request,
|
|
65
|
+
error,
|
|
66
|
+
operation: "agent.run",
|
|
67
|
+
agentId,
|
|
68
|
+
phase: "common",
|
|
69
|
+
startTime
|
|
70
|
+
});
|
|
59
71
|
console.error("Error running agent:", error);
|
|
60
72
|
console.error("Error stack:", error instanceof Error ? error.stack : "No stack trace");
|
|
61
73
|
console.error("Error details:", {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handle-run.cjs","names":["cloneAgentForRequest","parseRunRequest","attachIntelligenceEnterpriseLearning","isIntelligenceRuntime","handleIntelligenceRun","handleSseRun"],"sources":["../../../../src/v2/runtime/handlers/handle-run.ts"],"sourcesContent":["import { isIntelligenceRuntime } from \"../core/runtime\";\nimport { telemetry } from \"../telemetry\";\nimport type { RunAgentParameters } from \"./shared/agent-utils\";\nimport {\n attachIntelligenceEnterpriseLearning,\n cloneAgentForRequest,\n configureAgentForRequest,\n parseRunRequest,\n} from \"./shared/agent-utils\";\nimport { handleIntelligenceRun } from \"./intelligence/run\";\nimport { handleSseRun } from \"./sse/run\";\n\nexport async function handleRunAgent({\n runtime,\n request,\n agentId,\n}: RunAgentParameters) {\n telemetry.capture(\"oss.runtime.copilot_request_created\", {\n \"cloud.guardrails.enabled\": false,\n requestType: \"run\",\n \"cloud.api_key_provided\": !!request.headers.get(\n \"x-copilotcloud-public-api-key\",\n ),\n ...(request.headers.get(\"x-copilotcloud-public-api-key\")\n ? {\n \"cloud.public_api_key\": request.headers.get(\n \"x-copilotcloud-public-api-key\",\n )!,\n }\n : {}),\n });\n\n try {\n const agent = await cloneAgentForRequest(runtime, agentId, request);\n if (agent instanceof Response) {\n return agent;\n }\n\n // Ensure the clone carries the registry key so InMemoryAgentRunner can\n // tag historic runs with the correct agentId for filtering.\n agent.agentId = agentId;\n\n // Parse the body before configuring middleware: the request is single-read,\n // and middleware configuration needs the A2UI catalog signal the React\n // provider forwards (see `a2uiCatalogAvailable` below). Middleware is applied\n // to the agent here; the run itself is kicked off later, so this is safe.\n const input = await parseRunRequest(request);\n if (input instanceof Response) {\n return input;\n }\n\n // `<CopilotKit a2ui={{ catalog }}>` forwards this flag on every run. Its\n // presence alone is enough to turn A2UI on end-to-end — no runtime-side\n // `a2ui` config required.\n const providerA2UIHasCatalog =\n (input.forwardedProps as Record<string, unknown> | undefined)\n ?.a2uiCatalogAvailable === true;\n\n configureAgentForRequest({\n runtime,\n request,\n agentId,\n agent,\n providerA2UIHasCatalog,\n });\n const memoryResponse = await attachIntelligenceEnterpriseLearning({\n runtime,\n request,\n agent,\n });\n if (memoryResponse instanceof Response) return memoryResponse;\n\n agent.setMessages(input.messages);\n agent.setState(input.state);\n agent.threadId = input.threadId;\n\n if (runtime.debug?.lifecycle && runtime.debugLogger) {\n runtime.debugLogger.debug(\n { agentName: agentId, threadId: input.threadId },\n \"Agent run started\",\n );\n }\n\n if (isIntelligenceRuntime(runtime)) {\n return handleIntelligenceRun({\n runtime,\n request,\n agentId,\n agent,\n input,\n });\n }\n\n return handleSseRun({\n runtime,\n request,\n agent,\n input,\n agentId,\n debug: runtime.debug,\n logger: runtime.debugLogger,\n });\n } catch (error) {\n console.error(\"Error running agent:\", error);\n console.error(\n \"Error stack:\",\n error instanceof Error ? error.stack : \"No stack trace\",\n );\n console.error(\"Error details:\", {\n name: error instanceof Error ? error.name : \"Unknown\",\n message: error instanceof Error ? error.message : String(error),\n cause: error instanceof Error ? error.cause : undefined,\n });\n\n return new Response(\n JSON.stringify({\n error: \"Failed to run agent\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"handle-run.cjs","names":["cloneAgentForRequest","parseRunRequest","attachIntelligenceEnterpriseLearning","isIntelligenceRuntime","handleIntelligenceRun","handleSseRun"],"sources":["../../../../src/v2/runtime/handlers/handle-run.ts"],"sourcesContent":["import { isIntelligenceRuntime } from \"../core/runtime\";\nimport { telemetry } from \"../telemetry\";\nimport type { RunAgentParameters } from \"./shared/agent-utils\";\nimport {\n attachIntelligenceEnterpriseLearning,\n cloneAgentForRequest,\n configureAgentForRequest,\n parseRunRequest,\n} from \"./shared/agent-utils\";\nimport { handleIntelligenceRun } from \"./intelligence/run\";\nimport { handleSseRun } from \"./sse/run\";\nimport { getRuntimeErrorReporter } from \"../core/runtime-error-reporter\";\n\nexport async function handleRunAgent({\n runtime,\n request,\n agentId,\n}: RunAgentParameters) {\n const startTime = Date.now();\n telemetry.capture(\"oss.runtime.copilot_request_created\", {\n \"cloud.guardrails.enabled\": false,\n requestType: \"run\",\n \"cloud.api_key_provided\": !!request.headers.get(\n \"x-copilotcloud-public-api-key\",\n ),\n ...(request.headers.get(\"x-copilotcloud-public-api-key\")\n ? {\n \"cloud.public_api_key\": request.headers.get(\n \"x-copilotcloud-public-api-key\",\n )!,\n }\n : {}),\n });\n\n try {\n const agent = await cloneAgentForRequest(runtime, agentId, request);\n if (agent instanceof Response) {\n return agent;\n }\n\n // Ensure the clone carries the registry key so InMemoryAgentRunner can\n // tag historic runs with the correct agentId for filtering.\n agent.agentId = agentId;\n\n // Parse the body before configuring middleware: the request is single-read,\n // and middleware configuration needs the A2UI catalog signal the React\n // provider forwards (see `a2uiCatalogAvailable` below). Middleware is applied\n // to the agent here; the run itself is kicked off later, so this is safe.\n const input = await parseRunRequest(request);\n if (input instanceof Response) {\n return input;\n }\n\n // `<CopilotKit a2ui={{ catalog }}>` forwards this flag on every run. Its\n // presence alone is enough to turn A2UI on end-to-end — no runtime-side\n // `a2ui` config required.\n const providerA2UIHasCatalog =\n (input.forwardedProps as Record<string, unknown> | undefined)\n ?.a2uiCatalogAvailable === true;\n\n configureAgentForRequest({\n runtime,\n request,\n agentId,\n agent,\n providerA2UIHasCatalog,\n });\n const memoryResponse = await attachIntelligenceEnterpriseLearning({\n runtime,\n request,\n agent,\n });\n if (memoryResponse instanceof Response) return memoryResponse;\n\n agent.setMessages(input.messages);\n agent.setState(input.state);\n agent.threadId = input.threadId;\n\n if (runtime.debug?.lifecycle && runtime.debugLogger) {\n runtime.debugLogger.debug(\n { agentName: agentId, threadId: input.threadId },\n \"Agent run started\",\n );\n }\n\n if (isIntelligenceRuntime(runtime)) {\n return handleIntelligenceRun({\n runtime,\n request,\n agentId,\n agent,\n input,\n startTime,\n });\n }\n\n return handleSseRun({\n runtime,\n request,\n agent,\n input,\n agentId,\n debug: runtime.debug,\n logger: runtime.debugLogger,\n startTime,\n });\n } catch (error) {\n getRuntimeErrorReporter(runtime)?.report({\n request,\n error,\n operation: \"agent.run\",\n agentId,\n phase: \"common\",\n startTime,\n });\n console.error(\"Error running agent:\", error);\n console.error(\n \"Error stack:\",\n error instanceof Error ? error.stack : \"No stack trace\",\n );\n console.error(\"Error details:\", {\n name: error instanceof Error ? error.name : \"Unknown\",\n message: error instanceof Error ? error.message : String(error),\n cause: error instanceof Error ? error.cause : undefined,\n });\n\n return new Response(\n JSON.stringify({\n error: \"Failed to run agent\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;;;;;AAaA,eAAsB,eAAe,EACnC,SACA,SACA,WACqB;CACrB,MAAM,YAAY,KAAK,KAAK;AAC5B,kCAAU,QAAQ,uCAAuC;EACvD,4BAA4B;EAC5B,aAAa;EACb,0BAA0B,CAAC,CAAC,QAAQ,QAAQ,IAC1C,gCACD;EACD,GAAI,QAAQ,QAAQ,IAAI,gCAAgC,GACpD,EACE,wBAAwB,QAAQ,QAAQ,IACtC,gCACD,EACF,GACD,EAAE;EACP,CAAC;AAEF,KAAI;EACF,MAAM,QAAQ,MAAMA,yCAAqB,SAAS,SAAS,QAAQ;AACnE,MAAI,iBAAiB,SACnB,QAAO;AAKT,QAAM,UAAU;EAMhB,MAAM,QAAQ,MAAMC,oCAAgB,QAAQ;AAC5C,MAAI,iBAAiB,SACnB,QAAO;AAUT,+CAAyB;GACvB;GACA;GACA;GACA;GACA,wBARC,MAAM,gBACH,yBAAyB;GAQ9B,CAAC;EACF,MAAM,iBAAiB,MAAMC,yDAAqC;GAChE;GACA;GACA;GACD,CAAC;AACF,MAAI,0BAA0B,SAAU,QAAO;AAE/C,QAAM,YAAY,MAAM,SAAS;AACjC,QAAM,SAAS,MAAM,MAAM;AAC3B,QAAM,WAAW,MAAM;AAEvB,MAAI,QAAQ,OAAO,aAAa,QAAQ,YACtC,SAAQ,YAAY,MAClB;GAAE,WAAW;GAAS,UAAU,MAAM;GAAU,EAChD,oBACD;AAGH,MAAIC,sCAAsB,QAAQ,CAChC,QAAOC,kCAAsB;GAC3B;GACA;GACA;GACA;GACA;GACA;GACD,CAAC;AAGJ,SAAOC,2BAAa;GAClB;GACA;GACA;GACA;GACA;GACA,OAAO,QAAQ;GACf,QAAQ,QAAQ;GAChB;GACD,CAAC;UACK,OAAO;AACd,yDAAwB,QAAQ,EAAE,OAAO;GACvC;GACA;GACA,WAAW;GACX;GACA,OAAO;GACP;GACD,CAAC;AACF,UAAQ,MAAM,wBAAwB,MAAM;AAC5C,UAAQ,MACN,gBACA,iBAAiB,QAAQ,MAAM,QAAQ,iBACxC;AACD,UAAQ,MAAM,kBAAkB;GAC9B,MAAM,iBAAiB,QAAQ,MAAM,OAAO;GAC5C,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAC/D,OAAO,iBAAiB,QAAQ,MAAM,QAAQ;GAC/C,CAAC;AAEF,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU;GACnD,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import "reflect-metadata";
|
|
2
2
|
import telemetry from "../telemetry/telemetry-client.mjs";
|
|
3
|
+
import { getRuntimeErrorReporter } from "../core/runtime-error-reporter.mjs";
|
|
3
4
|
import { isIntelligenceRuntime } from "../core/runtime.mjs";
|
|
4
5
|
import { attachIntelligenceEnterpriseLearning, cloneAgentForRequest, configureAgentForRequest, parseRunRequest } from "./shared/agent-utils.mjs";
|
|
5
6
|
import { handleIntelligenceRun } from "./intelligence/run.mjs";
|
|
@@ -7,6 +8,7 @@ import { handleSseRun } from "./sse/run.mjs";
|
|
|
7
8
|
|
|
8
9
|
//#region src/v2/runtime/handlers/handle-run.ts
|
|
9
10
|
async function handleRunAgent({ runtime, request, agentId }) {
|
|
11
|
+
const startTime = Date.now();
|
|
10
12
|
telemetry.capture("oss.runtime.copilot_request_created", {
|
|
11
13
|
"cloud.guardrails.enabled": false,
|
|
12
14
|
requestType: "run",
|
|
@@ -44,7 +46,8 @@ async function handleRunAgent({ runtime, request, agentId }) {
|
|
|
44
46
|
request,
|
|
45
47
|
agentId,
|
|
46
48
|
agent,
|
|
47
|
-
input
|
|
49
|
+
input,
|
|
50
|
+
startTime
|
|
48
51
|
});
|
|
49
52
|
return handleSseRun({
|
|
50
53
|
runtime,
|
|
@@ -53,9 +56,18 @@ async function handleRunAgent({ runtime, request, agentId }) {
|
|
|
53
56
|
input,
|
|
54
57
|
agentId,
|
|
55
58
|
debug: runtime.debug,
|
|
56
|
-
logger: runtime.debugLogger
|
|
59
|
+
logger: runtime.debugLogger,
|
|
60
|
+
startTime
|
|
57
61
|
});
|
|
58
62
|
} catch (error) {
|
|
63
|
+
getRuntimeErrorReporter(runtime)?.report({
|
|
64
|
+
request,
|
|
65
|
+
error,
|
|
66
|
+
operation: "agent.run",
|
|
67
|
+
agentId,
|
|
68
|
+
phase: "common",
|
|
69
|
+
startTime
|
|
70
|
+
});
|
|
59
71
|
console.error("Error running agent:", error);
|
|
60
72
|
console.error("Error stack:", error instanceof Error ? error.stack : "No stack trace");
|
|
61
73
|
console.error("Error details:", {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handle-run.mjs","names":[],"sources":["../../../../src/v2/runtime/handlers/handle-run.ts"],"sourcesContent":["import { isIntelligenceRuntime } from \"../core/runtime\";\nimport { telemetry } from \"../telemetry\";\nimport type { RunAgentParameters } from \"./shared/agent-utils\";\nimport {\n attachIntelligenceEnterpriseLearning,\n cloneAgentForRequest,\n configureAgentForRequest,\n parseRunRequest,\n} from \"./shared/agent-utils\";\nimport { handleIntelligenceRun } from \"./intelligence/run\";\nimport { handleSseRun } from \"./sse/run\";\n\nexport async function handleRunAgent({\n runtime,\n request,\n agentId,\n}: RunAgentParameters) {\n telemetry.capture(\"oss.runtime.copilot_request_created\", {\n \"cloud.guardrails.enabled\": false,\n requestType: \"run\",\n \"cloud.api_key_provided\": !!request.headers.get(\n \"x-copilotcloud-public-api-key\",\n ),\n ...(request.headers.get(\"x-copilotcloud-public-api-key\")\n ? {\n \"cloud.public_api_key\": request.headers.get(\n \"x-copilotcloud-public-api-key\",\n )!,\n }\n : {}),\n });\n\n try {\n const agent = await cloneAgentForRequest(runtime, agentId, request);\n if (agent instanceof Response) {\n return agent;\n }\n\n // Ensure the clone carries the registry key so InMemoryAgentRunner can\n // tag historic runs with the correct agentId for filtering.\n agent.agentId = agentId;\n\n // Parse the body before configuring middleware: the request is single-read,\n // and middleware configuration needs the A2UI catalog signal the React\n // provider forwards (see `a2uiCatalogAvailable` below). Middleware is applied\n // to the agent here; the run itself is kicked off later, so this is safe.\n const input = await parseRunRequest(request);\n if (input instanceof Response) {\n return input;\n }\n\n // `<CopilotKit a2ui={{ catalog }}>` forwards this flag on every run. Its\n // presence alone is enough to turn A2UI on end-to-end — no runtime-side\n // `a2ui` config required.\n const providerA2UIHasCatalog =\n (input.forwardedProps as Record<string, unknown> | undefined)\n ?.a2uiCatalogAvailable === true;\n\n configureAgentForRequest({\n runtime,\n request,\n agentId,\n agent,\n providerA2UIHasCatalog,\n });\n const memoryResponse = await attachIntelligenceEnterpriseLearning({\n runtime,\n request,\n agent,\n });\n if (memoryResponse instanceof Response) return memoryResponse;\n\n agent.setMessages(input.messages);\n agent.setState(input.state);\n agent.threadId = input.threadId;\n\n if (runtime.debug?.lifecycle && runtime.debugLogger) {\n runtime.debugLogger.debug(\n { agentName: agentId, threadId: input.threadId },\n \"Agent run started\",\n );\n }\n\n if (isIntelligenceRuntime(runtime)) {\n return handleIntelligenceRun({\n runtime,\n request,\n agentId,\n agent,\n input,\n });\n }\n\n return handleSseRun({\n runtime,\n request,\n agent,\n input,\n agentId,\n debug: runtime.debug,\n logger: runtime.debugLogger,\n });\n } catch (error) {\n console.error(\"Error running agent:\", error);\n console.error(\n \"Error stack:\",\n error instanceof Error ? error.stack : \"No stack trace\",\n );\n console.error(\"Error details:\", {\n name: error instanceof Error ? error.name : \"Unknown\",\n message: error instanceof Error ? error.message : String(error),\n cause: error instanceof Error ? error.cause : undefined,\n });\n\n return new Response(\n JSON.stringify({\n error: \"Failed to run agent\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"handle-run.mjs","names":[],"sources":["../../../../src/v2/runtime/handlers/handle-run.ts"],"sourcesContent":["import { isIntelligenceRuntime } from \"../core/runtime\";\nimport { telemetry } from \"../telemetry\";\nimport type { RunAgentParameters } from \"./shared/agent-utils\";\nimport {\n attachIntelligenceEnterpriseLearning,\n cloneAgentForRequest,\n configureAgentForRequest,\n parseRunRequest,\n} from \"./shared/agent-utils\";\nimport { handleIntelligenceRun } from \"./intelligence/run\";\nimport { handleSseRun } from \"./sse/run\";\nimport { getRuntimeErrorReporter } from \"../core/runtime-error-reporter\";\n\nexport async function handleRunAgent({\n runtime,\n request,\n agentId,\n}: RunAgentParameters) {\n const startTime = Date.now();\n telemetry.capture(\"oss.runtime.copilot_request_created\", {\n \"cloud.guardrails.enabled\": false,\n requestType: \"run\",\n \"cloud.api_key_provided\": !!request.headers.get(\n \"x-copilotcloud-public-api-key\",\n ),\n ...(request.headers.get(\"x-copilotcloud-public-api-key\")\n ? {\n \"cloud.public_api_key\": request.headers.get(\n \"x-copilotcloud-public-api-key\",\n )!,\n }\n : {}),\n });\n\n try {\n const agent = await cloneAgentForRequest(runtime, agentId, request);\n if (agent instanceof Response) {\n return agent;\n }\n\n // Ensure the clone carries the registry key so InMemoryAgentRunner can\n // tag historic runs with the correct agentId for filtering.\n agent.agentId = agentId;\n\n // Parse the body before configuring middleware: the request is single-read,\n // and middleware configuration needs the A2UI catalog signal the React\n // provider forwards (see `a2uiCatalogAvailable` below). Middleware is applied\n // to the agent here; the run itself is kicked off later, so this is safe.\n const input = await parseRunRequest(request);\n if (input instanceof Response) {\n return input;\n }\n\n // `<CopilotKit a2ui={{ catalog }}>` forwards this flag on every run. Its\n // presence alone is enough to turn A2UI on end-to-end — no runtime-side\n // `a2ui` config required.\n const providerA2UIHasCatalog =\n (input.forwardedProps as Record<string, unknown> | undefined)\n ?.a2uiCatalogAvailable === true;\n\n configureAgentForRequest({\n runtime,\n request,\n agentId,\n agent,\n providerA2UIHasCatalog,\n });\n const memoryResponse = await attachIntelligenceEnterpriseLearning({\n runtime,\n request,\n agent,\n });\n if (memoryResponse instanceof Response) return memoryResponse;\n\n agent.setMessages(input.messages);\n agent.setState(input.state);\n agent.threadId = input.threadId;\n\n if (runtime.debug?.lifecycle && runtime.debugLogger) {\n runtime.debugLogger.debug(\n { agentName: agentId, threadId: input.threadId },\n \"Agent run started\",\n );\n }\n\n if (isIntelligenceRuntime(runtime)) {\n return handleIntelligenceRun({\n runtime,\n request,\n agentId,\n agent,\n input,\n startTime,\n });\n }\n\n return handleSseRun({\n runtime,\n request,\n agent,\n input,\n agentId,\n debug: runtime.debug,\n logger: runtime.debugLogger,\n startTime,\n });\n } catch (error) {\n getRuntimeErrorReporter(runtime)?.report({\n request,\n error,\n operation: \"agent.run\",\n agentId,\n phase: \"common\",\n startTime,\n });\n console.error(\"Error running agent:\", error);\n console.error(\n \"Error stack:\",\n error instanceof Error ? error.stack : \"No stack trace\",\n );\n console.error(\"Error details:\", {\n name: error instanceof Error ? error.name : \"Unknown\",\n message: error instanceof Error ? error.message : String(error),\n cause: error instanceof Error ? error.cause : undefined,\n });\n\n return new Response(\n JSON.stringify({\n error: \"Failed to run agent\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;;;;;AAaA,eAAsB,eAAe,EACnC,SACA,SACA,WACqB;CACrB,MAAM,YAAY,KAAK,KAAK;AAC5B,WAAU,QAAQ,uCAAuC;EACvD,4BAA4B;EAC5B,aAAa;EACb,0BAA0B,CAAC,CAAC,QAAQ,QAAQ,IAC1C,gCACD;EACD,GAAI,QAAQ,QAAQ,IAAI,gCAAgC,GACpD,EACE,wBAAwB,QAAQ,QAAQ,IACtC,gCACD,EACF,GACD,EAAE;EACP,CAAC;AAEF,KAAI;EACF,MAAM,QAAQ,MAAM,qBAAqB,SAAS,SAAS,QAAQ;AAC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@ function isNonEmptyString(value) {
|
|
|
26
26
|
* `POST /annotate` handler.
|
|
27
27
|
*
|
|
28
28
|
* Three-tier flow:
|
|
29
|
-
* recordAnnotation() (frontend lib; called by useLearnFromUserAction
|
|
29
|
+
* recordAnnotation() (frontend lib; called by useLearnFromUserAction)
|
|
30
30
|
* → POST ${runtimeUrl}/annotate
|
|
31
31
|
* → this handler resolves the Intel user from BFF auth
|
|
32
32
|
* → intelligence.annotate(...)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"annotate.cjs","names":["errorResponse","isIntelligenceRuntime","isHandlerResponse","resolveIntelligenceUser","PlatformRequestError"],"sources":["../../../../../src/v2/runtime/handlers/intelligence/annotate.ts"],"sourcesContent":["import { logger } from \"@copilotkit/shared\";\nimport type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { PlatformRequestError } from \"../../intelligence-platform/client\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\n\ninterface AnnotateHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface AnnotateBody {\n /** Discriminator identifying the annotation type (e.g. `\"user_action\"`). */\n type: string;\n /** Type-specific payload. Shape varies by `type`. */\n payload?: unknown;\n /** The thread the annotation is associated with. */\n threadId: string;\n /** Caller-supplied idempotency key. Optional — platform auto-generates one when absent. */\n clientEventId?: string;\n /** ISO-8601 client-asserted timestamp. Defaults to server NOW() when absent. */\n occurredAt?: string;\n}\n\nasync function parseJsonBody(\n request: Request,\n): Promise<Record<string, unknown> | Response> {\n try {\n return (await request.json()) as Record<string, unknown>;\n } catch (error) {\n logger.error({ err: error }, \"Malformed JSON in annotate body\");\n return errorResponse(\"Invalid request body\", 400);\n }\n}\n\nfunction requireIntelligenceRuntime(\n runtime: CopilotRuntimeLike,\n): CopilotIntelligenceRuntimeLike | Response {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. annotate requires a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n }\n return runtime;\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0;\n}\n\n/**\n * `POST /annotate` handler.\n *\n * Three-tier flow:\n * recordAnnotation() (frontend lib; called by useLearnFromUserAction
|
|
1
|
+
{"version":3,"file":"annotate.cjs","names":["errorResponse","isIntelligenceRuntime","isHandlerResponse","resolveIntelligenceUser","PlatformRequestError"],"sources":["../../../../../src/v2/runtime/handlers/intelligence/annotate.ts"],"sourcesContent":["import { logger } from \"@copilotkit/shared\";\nimport type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { PlatformRequestError } from \"../../intelligence-platform/client\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\n\ninterface AnnotateHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface AnnotateBody {\n /** Discriminator identifying the annotation type (e.g. `\"user_action\"`). */\n type: string;\n /** Type-specific payload. Shape varies by `type`. */\n payload?: unknown;\n /** The thread the annotation is associated with. */\n threadId: string;\n /** Caller-supplied idempotency key. Optional — platform auto-generates one when absent. */\n clientEventId?: string;\n /** ISO-8601 client-asserted timestamp. Defaults to server NOW() when absent. */\n occurredAt?: string;\n}\n\nasync function parseJsonBody(\n request: Request,\n): Promise<Record<string, unknown> | Response> {\n try {\n return (await request.json()) as Record<string, unknown>;\n } catch (error) {\n logger.error({ err: error }, \"Malformed JSON in annotate body\");\n return errorResponse(\"Invalid request body\", 400);\n }\n}\n\nfunction requireIntelligenceRuntime(\n runtime: CopilotRuntimeLike,\n): CopilotIntelligenceRuntimeLike | Response {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. annotate requires a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n }\n return runtime;\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0;\n}\n\n/**\n * `POST /annotate` handler.\n *\n * Three-tier flow:\n * recordAnnotation() (frontend lib; called by useLearnFromUserAction)\n * → POST ${runtimeUrl}/annotate\n * → this handler resolves the Intel user from BFF auth\n * → intelligence.annotate(...)\n * → PUT ${apiUrl}/connector/annotate/:clientEventId\n *\n * The frontend hook may auto-generate a UUID `clientEventId` per call\n * so retries are idempotent end-to-end (the platform collapses to the\n * original row).\n */\nexport async function handleAnnotate({\n runtime,\n request,\n}: AnnotateHandlerParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) return intelligenceRuntime;\n\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n const parsed = parseAnnotateBody(body);\n if (isHandlerResponse(parsed)) return parsed;\n\n try {\n const result = await intelligenceRuntime.intelligence.annotate({\n userId: user.id,\n threadId: parsed.threadId,\n type: parsed.type,\n payload: parsed.payload,\n clientEventId: parsed.clientEventId,\n occurredAt: parsed.occurredAt,\n });\n return new Response(JSON.stringify(result), {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n });\n } catch (err) {\n logger.error({ err }, \"annotate: platform call failed\");\n // Forward the platform's HTTP status when it's a client error\n // (4xx) so the SDK author sees an actionable response instead of\n // a generic 502. 5xx and non-platform errors collapse to 502\n // (\"Bad Gateway\") because the upstream is genuinely at fault.\n if (\n err instanceof PlatformRequestError &&\n err.status >= 400 &&\n err.status < 500\n ) {\n return errorResponse(err.message, err.status);\n }\n return errorResponse(\"Failed to annotate\", 502);\n }\n}\n\nfunction parseAnnotateBody(\n body: Record<string, unknown>,\n): AnnotateBody | Response {\n if (!isNonEmptyString(body.threadId)) {\n return errorResponse(\"Valid threadId is required\", 400);\n }\n if (!isNonEmptyString(body.type)) {\n return errorResponse(\"Valid type is required\", 400);\n }\n return {\n type: body.type,\n payload: body.payload,\n threadId: body.threadId,\n clientEventId: isNonEmptyString(body.clientEventId)\n ? body.clientEventId\n : undefined,\n occurredAt: isNonEmptyString(body.occurredAt) ? body.occurredAt : undefined,\n };\n}\n"],"mappings":";;;;;;;;;AA4BA,eAAe,cACb,SAC6C;AAC7C,KAAI;AACF,SAAQ,MAAM,QAAQ,MAAM;UACrB,OAAO;AACd,4BAAO,MAAM,EAAE,KAAK,OAAO,EAAE,kCAAkC;AAC/D,SAAOA,oCAAc,wBAAwB,IAAI;;;AAIrD,SAAS,2BACP,SAC2C;AAC3C,KAAI,CAACC,wCAAsB,QAAQ,CACjC,QAAOD,oCACL,+IACA,IACD;AAEH,QAAO;;AAGT,SAAS,iBAAiB,OAAiC;AACzD,QAAO,OAAO,UAAU,YAAY,MAAM,SAAS;;;;;;;;;;;;;;;;AAiBrD,eAAsB,eAAe,EACnC,SACA,WAC2C;CAC3C,MAAM,sBAAsB,2BAA2B,QAAQ;AAC/D,KAAIE,wCAAkB,oBAAoB,CAAE,QAAO;CAEnD,MAAM,OAAO,MAAM,cAAc,QAAQ;AACzC,KAAIA,wCAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,OAAO,MAAMC,0DAAwB;EACzC,SAAS;EACT;EACD,CAAC;AACF,KAAID,wCAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,SAAS,kBAAkB,KAAK;AACtC,KAAIA,wCAAkB,OAAO,CAAE,QAAO;AAEtC,KAAI;EACF,MAAM,SAAS,MAAM,oBAAoB,aAAa,SAAS;GAC7D,QAAQ,KAAK;GACb,UAAU,OAAO;GACjB,MAAM,OAAO;GACb,SAAS,OAAO;GAChB,eAAe,OAAO;GACtB,YAAY,OAAO;GACpB,CAAC;AACF,SAAO,IAAI,SAAS,KAAK,UAAU,OAAO,EAAE;GAC1C,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CAAC;UACK,KAAK;AACZ,4BAAO,MAAM,EAAE,KAAK,EAAE,iCAAiC;AAKvD,MACE,eAAeE,uCACf,IAAI,UAAU,OACd,IAAI,SAAS,IAEb,QAAOJ,oCAAc,IAAI,SAAS,IAAI,OAAO;AAE/C,SAAOA,oCAAc,sBAAsB,IAAI;;;AAInD,SAAS,kBACP,MACyB;AACzB,KAAI,CAAC,iBAAiB,KAAK,SAAS,CAClC,QAAOA,oCAAc,8BAA8B,IAAI;AAEzD,KAAI,CAAC,iBAAiB,KAAK,KAAK,CAC9B,QAAOA,oCAAc,0BAA0B,IAAI;AAErD,QAAO;EACL,MAAM,KAAK;EACX,SAAS,KAAK;EACd,UAAU,KAAK;EACf,eAAe,iBAAiB,KAAK,cAAc,GAC/C,KAAK,gBACL;EACJ,YAAY,iBAAiB,KAAK,WAAW,GAAG,KAAK,aAAa;EACnE"}
|
|
@@ -25,7 +25,7 @@ function isNonEmptyString(value) {
|
|
|
25
25
|
* `POST /annotate` handler.
|
|
26
26
|
*
|
|
27
27
|
* Three-tier flow:
|
|
28
|
-
* recordAnnotation() (frontend lib; called by useLearnFromUserAction
|
|
28
|
+
* recordAnnotation() (frontend lib; called by useLearnFromUserAction)
|
|
29
29
|
* → POST ${runtimeUrl}/annotate
|
|
30
30
|
* → this handler resolves the Intel user from BFF auth
|
|
31
31
|
* → intelligence.annotate(...)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"annotate.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/intelligence/annotate.ts"],"sourcesContent":["import { logger } from \"@copilotkit/shared\";\nimport type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { PlatformRequestError } from \"../../intelligence-platform/client\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\n\ninterface AnnotateHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface AnnotateBody {\n /** Discriminator identifying the annotation type (e.g. `\"user_action\"`). */\n type: string;\n /** Type-specific payload. Shape varies by `type`. */\n payload?: unknown;\n /** The thread the annotation is associated with. */\n threadId: string;\n /** Caller-supplied idempotency key. Optional — platform auto-generates one when absent. */\n clientEventId?: string;\n /** ISO-8601 client-asserted timestamp. Defaults to server NOW() when absent. */\n occurredAt?: string;\n}\n\nasync function parseJsonBody(\n request: Request,\n): Promise<Record<string, unknown> | Response> {\n try {\n return (await request.json()) as Record<string, unknown>;\n } catch (error) {\n logger.error({ err: error }, \"Malformed JSON in annotate body\");\n return errorResponse(\"Invalid request body\", 400);\n }\n}\n\nfunction requireIntelligenceRuntime(\n runtime: CopilotRuntimeLike,\n): CopilotIntelligenceRuntimeLike | Response {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. annotate requires a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n }\n return runtime;\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0;\n}\n\n/**\n * `POST /annotate` handler.\n *\n * Three-tier flow:\n * recordAnnotation() (frontend lib; called by useLearnFromUserAction
|
|
1
|
+
{"version":3,"file":"annotate.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/intelligence/annotate.ts"],"sourcesContent":["import { logger } from \"@copilotkit/shared\";\nimport type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { PlatformRequestError } from \"../../intelligence-platform/client\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\n\ninterface AnnotateHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface AnnotateBody {\n /** Discriminator identifying the annotation type (e.g. `\"user_action\"`). */\n type: string;\n /** Type-specific payload. Shape varies by `type`. */\n payload?: unknown;\n /** The thread the annotation is associated with. */\n threadId: string;\n /** Caller-supplied idempotency key. Optional — platform auto-generates one when absent. */\n clientEventId?: string;\n /** ISO-8601 client-asserted timestamp. Defaults to server NOW() when absent. */\n occurredAt?: string;\n}\n\nasync function parseJsonBody(\n request: Request,\n): Promise<Record<string, unknown> | Response> {\n try {\n return (await request.json()) as Record<string, unknown>;\n } catch (error) {\n logger.error({ err: error }, \"Malformed JSON in annotate body\");\n return errorResponse(\"Invalid request body\", 400);\n }\n}\n\nfunction requireIntelligenceRuntime(\n runtime: CopilotRuntimeLike,\n): CopilotIntelligenceRuntimeLike | Response {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. annotate requires a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n }\n return runtime;\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0;\n}\n\n/**\n * `POST /annotate` handler.\n *\n * Three-tier flow:\n * recordAnnotation() (frontend lib; called by useLearnFromUserAction)\n * → POST ${runtimeUrl}/annotate\n * → this handler resolves the Intel user from BFF auth\n * → intelligence.annotate(...)\n * → PUT ${apiUrl}/connector/annotate/:clientEventId\n *\n * The frontend hook may auto-generate a UUID `clientEventId` per call\n * so retries are idempotent end-to-end (the platform collapses to the\n * original row).\n */\nexport async function handleAnnotate({\n runtime,\n request,\n}: AnnotateHandlerParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) return intelligenceRuntime;\n\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n const parsed = parseAnnotateBody(body);\n if (isHandlerResponse(parsed)) return parsed;\n\n try {\n const result = await intelligenceRuntime.intelligence.annotate({\n userId: user.id,\n threadId: parsed.threadId,\n type: parsed.type,\n payload: parsed.payload,\n clientEventId: parsed.clientEventId,\n occurredAt: parsed.occurredAt,\n });\n return new Response(JSON.stringify(result), {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n });\n } catch (err) {\n logger.error({ err }, \"annotate: platform call failed\");\n // Forward the platform's HTTP status when it's a client error\n // (4xx) so the SDK author sees an actionable response instead of\n // a generic 502. 5xx and non-platform errors collapse to 502\n // (\"Bad Gateway\") because the upstream is genuinely at fault.\n if (\n err instanceof PlatformRequestError &&\n err.status >= 400 &&\n err.status < 500\n ) {\n return errorResponse(err.message, err.status);\n }\n return errorResponse(\"Failed to annotate\", 502);\n }\n}\n\nfunction parseAnnotateBody(\n body: Record<string, unknown>,\n): AnnotateBody | Response {\n if (!isNonEmptyString(body.threadId)) {\n return errorResponse(\"Valid threadId is required\", 400);\n }\n if (!isNonEmptyString(body.type)) {\n return errorResponse(\"Valid type is required\", 400);\n }\n return {\n type: body.type,\n payload: body.payload,\n threadId: body.threadId,\n clientEventId: isNonEmptyString(body.clientEventId)\n ? body.clientEventId\n : undefined,\n occurredAt: isNonEmptyString(body.occurredAt) ? body.occurredAt : undefined,\n };\n}\n"],"mappings":";;;;;;;;AA4BA,eAAe,cACb,SAC6C;AAC7C,KAAI;AACF,SAAQ,MAAM,QAAQ,MAAM;UACrB,OAAO;AACd,SAAO,MAAM,EAAE,KAAK,OAAO,EAAE,kCAAkC;AAC/D,SAAO,cAAc,wBAAwB,IAAI;;;AAIrD,SAAS,2BACP,SAC2C;AAC3C,KAAI,CAAC,sBAAsB,QAAQ,CACjC,QAAO,cACL,+IACA,IACD;AAEH,QAAO;;AAGT,SAAS,iBAAiB,OAAiC;AACzD,QAAO,OAAO,UAAU,YAAY,MAAM,SAAS;;;;;;;;;;;;;;;;AAiBrD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|
const require_runtime = require('../../../../_virtual/_rolldown/runtime.cjs');
|
|
3
3
|
const require_telemetry_client = require('../../telemetry/telemetry-client.cjs');
|
|
4
|
+
const require_runtime_error_reporter = require('../../core/runtime-error-reporter.cjs');
|
|
5
|
+
const require_learning = require('../../core/learning.cjs');
|
|
4
6
|
const require_json_response = require('../shared/json-response.cjs');
|
|
7
|
+
const require_intelligence_utils = require('../shared/intelligence-utils.cjs');
|
|
5
8
|
const require_resolve_intelligence_user = require('../shared/resolve-intelligence-user.cjs');
|
|
6
9
|
const require_thread_names = require('./thread-names.cjs');
|
|
7
10
|
let _copilotkit_shared = require("@copilotkit/shared");
|
|
@@ -20,7 +23,7 @@ function buildRealtimeConnectionInfo(params) {
|
|
|
20
23
|
function hasRunnerStartupBoundary(runner) {
|
|
21
24
|
return typeof runner.runWithStartupBoundary === "function" && (Object.prototype.hasOwnProperty.call(runner, "runWithStartupBoundary") || Object.prototype.hasOwnProperty.call(runner, "threads"));
|
|
22
25
|
}
|
|
23
|
-
async function handleIntelligenceRun({ runtime, request, agentId, agent, input }) {
|
|
26
|
+
async function handleIntelligenceRun({ runtime, request, agentId, agent, input, startTime }) {
|
|
24
27
|
if (!runtime.intelligence) return Response.json({
|
|
25
28
|
error: "Intelligence not configured",
|
|
26
29
|
message: "Intelligence mode requires a CopilotKitIntelligence"
|
|
@@ -31,11 +34,26 @@ async function handleIntelligenceRun({ runtime, request, agentId, agent, input }
|
|
|
31
34
|
});
|
|
32
35
|
if (require_json_response.isHandlerResponse(user)) return user;
|
|
33
36
|
const userId = user.id;
|
|
37
|
+
let learningContainerId;
|
|
38
|
+
try {
|
|
39
|
+
learningContainerId = await require_learning.resolveLearningContainerId(runtime.learning, {
|
|
40
|
+
surface: "web",
|
|
41
|
+
request,
|
|
42
|
+
threadId: input.threadId,
|
|
43
|
+
runId: input.runId,
|
|
44
|
+
agentId,
|
|
45
|
+
userId
|
|
46
|
+
});
|
|
47
|
+
} catch (error) {
|
|
48
|
+
_copilotkit_shared.logger.error("Failed to resolve Learning Container:", error);
|
|
49
|
+
return Response.json({ error: "Failed to resolve Learning Container" }, { status: 500 });
|
|
50
|
+
}
|
|
34
51
|
try {
|
|
35
52
|
const { thread, created } = await runtime.intelligence.getOrCreateThread({
|
|
36
53
|
threadId: input.threadId,
|
|
37
54
|
userId,
|
|
38
|
-
agentId
|
|
55
|
+
agentId,
|
|
56
|
+
...learningContainerId !== void 0 ? { learningContainerId } : {}
|
|
39
57
|
});
|
|
40
58
|
if (created && runtime.generateThreadNames && !thread.name?.trim()) require_thread_names.generateThreadNameForNewThread({
|
|
41
59
|
runtime,
|
|
@@ -49,7 +67,8 @@ async function handleIntelligenceRun({ runtime, request, agentId, agent, input }
|
|
|
49
67
|
});
|
|
50
68
|
} catch (error) {
|
|
51
69
|
_copilotkit_shared.logger.error("Failed to get or create thread:", error);
|
|
52
|
-
|
|
70
|
+
const platformStatus = require_intelligence_utils.getPlatformErrorStatus(error);
|
|
71
|
+
return Response.json({ error: "Failed to initialize thread" }, { status: platformStatus !== void 0 && platformStatus >= 400 && platformStatus < 500 ? platformStatus : 502 });
|
|
53
72
|
}
|
|
54
73
|
let canonicalThreadId = input.threadId;
|
|
55
74
|
let canonicalRunId = input.runId;
|
|
@@ -60,6 +79,7 @@ async function handleIntelligenceRun({ runtime, request, agentId, agent, input }
|
|
|
60
79
|
runId: input.runId,
|
|
61
80
|
userId,
|
|
62
81
|
agentId,
|
|
82
|
+
...learningContainerId !== void 0 ? { learningContainerId } : {},
|
|
63
83
|
...runtime.lockKeyPrefix !== void 0 ? { lockKeyPrefix: runtime.lockKeyPrefix } : {},
|
|
64
84
|
ttlSeconds: runtime.lockTtlSeconds
|
|
65
85
|
});
|
|
@@ -68,7 +88,8 @@ async function handleIntelligenceRun({ runtime, request, agentId, agent, input }
|
|
|
68
88
|
joinToken = lockResult.joinToken;
|
|
69
89
|
} catch (error) {
|
|
70
90
|
_copilotkit_shared.logger.error("Thread lock denied:", error);
|
|
71
|
-
|
|
91
|
+
const platformStatus = require_intelligence_utils.getPlatformErrorStatus(error);
|
|
92
|
+
return Response.json({ error: "Thread lock denied" }, { status: platformStatus === 409 ? 409 : 502 });
|
|
72
93
|
}
|
|
73
94
|
const cleanupLock = (reason) => runtime.intelligence.ɵcleanupThreadLock({
|
|
74
95
|
threadId: canonicalThreadId || input.threadId,
|
|
@@ -140,6 +161,22 @@ async function handleIntelligenceRun({ runtime, request, agentId, agent, input }
|
|
|
140
161
|
input: canonicalInput,
|
|
141
162
|
...persistedInputMessages !== void 0 ? { persistedInputMessages } : {}
|
|
142
163
|
};
|
|
164
|
+
const runtimeErrorReporter = require_runtime_error_reporter.getRuntimeErrorReporter(runtime);
|
|
165
|
+
let agentErrorReported = false;
|
|
166
|
+
const reportAgentError = (error, phase) => {
|
|
167
|
+
if (agentErrorReported) return;
|
|
168
|
+
agentErrorReported = true;
|
|
169
|
+
runtimeErrorReporter?.report({
|
|
170
|
+
request,
|
|
171
|
+
error,
|
|
172
|
+
operation: "agent.run",
|
|
173
|
+
agentId,
|
|
174
|
+
threadId: canonicalThreadId,
|
|
175
|
+
runId: canonicalRunId,
|
|
176
|
+
phase,
|
|
177
|
+
startTime
|
|
178
|
+
});
|
|
179
|
+
};
|
|
143
180
|
try {
|
|
144
181
|
const runStart = hasRunnerStartupBoundary(runtime.runner) ? runtime.runner.runWithStartupBoundary(runRequest) : {
|
|
145
182
|
events: runtime.runner.run(runRequest),
|
|
@@ -148,13 +185,18 @@ async function handleIntelligenceRun({ runtime, request, agentId, agent, input }
|
|
|
148
185
|
runStart.events.subscribe({
|
|
149
186
|
next: (event) => {
|
|
150
187
|
if (event.type === _ag_ui_client.EventType.RUN_STARTED) runStarted.current = true;
|
|
151
|
-
if (event.type === _ag_ui_client.EventType.RUN_ERROR
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
188
|
+
if (event.type === _ag_ui_client.EventType.RUN_ERROR) {
|
|
189
|
+
const message = "message" in event && typeof event.message === "string" ? event.message : "Runner failed before the run started";
|
|
190
|
+
reportAgentError(new Error(message), runStarted.current ? "intelligence.subscription" : "intelligence.startup");
|
|
191
|
+
if (!runStarted.current) {
|
|
192
|
+
clearHeartbeat();
|
|
193
|
+
immediateStartupErrorMessage = message;
|
|
194
|
+
immediateStartupCleanup = cleanupLock("runner-start-failed");
|
|
195
|
+
}
|
|
155
196
|
}
|
|
156
197
|
},
|
|
157
198
|
error: (error) => {
|
|
199
|
+
reportAgentError(error, runStarted.current ? "intelligence.subscription" : "intelligence.startup");
|
|
158
200
|
clearHeartbeat();
|
|
159
201
|
if (!runStarted.current) {
|
|
160
202
|
immediateStartupErrorMessage = error instanceof Error ? error.message : String(error);
|
|
@@ -170,6 +212,7 @@ async function handleIntelligenceRun({ runtime, request, agentId, agent, input }
|
|
|
170
212
|
});
|
|
171
213
|
await runStart.startup;
|
|
172
214
|
} catch (error) {
|
|
215
|
+
reportAgentError(error, "intelligence.startup");
|
|
173
216
|
clearHeartbeat();
|
|
174
217
|
await (immediateStartupCleanup ?? cleanupLock("runner-start-threw"));
|
|
175
218
|
_copilotkit_shared.logger.error("Error starting agent runner:", error);
|