@copilotkit/runtime 1.71.1 → 1.71.2

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.
Files changed (88) hide show
  1. package/README.md +22 -0
  2. package/dist/agent/index.cjs +14 -2
  3. package/dist/agent/index.cjs.map +1 -1
  4. package/dist/agent/index.d.cts +1 -0
  5. package/dist/agent/index.d.cts.map +1 -1
  6. package/dist/agent/index.d.mts +1 -0
  7. package/dist/agent/index.d.mts.map +1 -1
  8. package/dist/agent/index.mjs +14 -2
  9. package/dist/agent/index.mjs.map +1 -1
  10. package/dist/index.cjs +1 -0
  11. package/dist/index.d.cts +9 -1
  12. package/dist/index.d.mts +9 -1
  13. package/dist/index.mjs +2 -2
  14. package/dist/lib/telemetry-client.cjs.map +1 -1
  15. package/dist/lib/telemetry-client.mjs.map +1 -1
  16. package/dist/package.cjs +6 -4
  17. package/dist/package.mjs +6 -4
  18. package/dist/service-adapters/anthropic/anthropic-adapter.cjs +59 -25
  19. package/dist/service-adapters/anthropic/anthropic-adapter.cjs.map +1 -1
  20. package/dist/service-adapters/anthropic/anthropic-adapter.d.cts +30 -1
  21. package/dist/service-adapters/anthropic/anthropic-adapter.d.cts.map +1 -1
  22. package/dist/service-adapters/anthropic/anthropic-adapter.d.mts +30 -1
  23. package/dist/service-adapters/anthropic/anthropic-adapter.d.mts.map +1 -1
  24. package/dist/service-adapters/anthropic/anthropic-adapter.mjs +59 -26
  25. package/dist/service-adapters/anthropic/anthropic-adapter.mjs.map +1 -1
  26. package/dist/service-adapters/index.d.cts +1 -1
  27. package/dist/service-adapters/index.d.mts +1 -1
  28. package/dist/v2/index.cjs +2 -0
  29. package/dist/v2/index.d.cts +2 -1
  30. package/dist/v2/index.d.mts +2 -1
  31. package/dist/v2/index.mjs +2 -1
  32. package/dist/v2/runtime/core/runtime.cjs.map +1 -1
  33. package/dist/v2/runtime/core/runtime.d.cts +2 -1
  34. package/dist/v2/runtime/core/runtime.d.cts.map +1 -1
  35. package/dist/v2/runtime/core/runtime.d.mts +2 -1
  36. package/dist/v2/runtime/core/runtime.d.mts.map +1 -1
  37. package/dist/v2/runtime/core/runtime.mjs.map +1 -1
  38. package/dist/v2/runtime/handlers/handle-run.cjs +2 -1
  39. package/dist/v2/runtime/handlers/handle-run.cjs.map +1 -1
  40. package/dist/v2/runtime/handlers/handle-run.mjs +2 -1
  41. package/dist/v2/runtime/handlers/handle-run.mjs.map +1 -1
  42. package/dist/v2/runtime/handlers/handle-stop.cjs +41 -1
  43. package/dist/v2/runtime/handlers/handle-stop.cjs.map +1 -1
  44. package/dist/v2/runtime/handlers/handle-stop.mjs +42 -2
  45. package/dist/v2/runtime/handlers/handle-stop.mjs.map +1 -1
  46. package/dist/v2/runtime/handlers/intelligence/run.cjs +1 -1
  47. package/dist/v2/runtime/handlers/intelligence/run.cjs.map +1 -1
  48. package/dist/v2/runtime/handlers/intelligence/run.mjs +1 -1
  49. package/dist/v2/runtime/handlers/intelligence/run.mjs.map +1 -1
  50. package/dist/v2/runtime/handlers/intelligence/threads.cjs +2 -3
  51. package/dist/v2/runtime/handlers/intelligence/threads.cjs.map +1 -1
  52. package/dist/v2/runtime/handlers/intelligence/threads.mjs +2 -3
  53. package/dist/v2/runtime/handlers/intelligence/threads.mjs.map +1 -1
  54. package/dist/v2/runtime/handlers/shared/agent-utils.cjs +8 -2
  55. package/dist/v2/runtime/handlers/shared/agent-utils.cjs.map +1 -1
  56. package/dist/v2/runtime/handlers/shared/agent-utils.mjs +8 -2
  57. package/dist/v2/runtime/handlers/shared/agent-utils.mjs.map +1 -1
  58. package/dist/v2/runtime/index.d.cts +1 -0
  59. package/dist/v2/runtime/index.d.cts.map +1 -1
  60. package/dist/v2/runtime/index.d.mts +1 -0
  61. package/dist/v2/runtime/index.d.mts.map +1 -1
  62. package/dist/v2/runtime/intelligence-platform/client.cjs +106 -1
  63. package/dist/v2/runtime/intelligence-platform/client.cjs.map +1 -1
  64. package/dist/v2/runtime/intelligence-platform/client.d.cts +11 -0
  65. package/dist/v2/runtime/intelligence-platform/client.d.cts.map +1 -1
  66. package/dist/v2/runtime/intelligence-platform/client.d.mts +11 -0
  67. package/dist/v2/runtime/intelligence-platform/client.d.mts.map +1 -1
  68. package/dist/v2/runtime/intelligence-platform/client.mjs +106 -1
  69. package/dist/v2/runtime/intelligence-platform/client.mjs.map +1 -1
  70. package/dist/v2/runtime/intelligence-platform/index.d.cts +1 -0
  71. package/dist/v2/runtime/intelligence-platform/index.d.mts +1 -0
  72. package/dist/v2/runtime/intelligence-platform/learned-skills.cjs +43 -0
  73. package/dist/v2/runtime/intelligence-platform/learned-skills.cjs.map +1 -0
  74. package/dist/v2/runtime/intelligence-platform/learned-skills.d.cts +34 -0
  75. package/dist/v2/runtime/intelligence-platform/learned-skills.d.cts.map +1 -0
  76. package/dist/v2/runtime/intelligence-platform/learned-skills.d.mts +34 -0
  77. package/dist/v2/runtime/intelligence-platform/learned-skills.d.mts.map +1 -0
  78. package/dist/v2/runtime/intelligence-platform/learned-skills.mjs +41 -0
  79. package/dist/v2/runtime/intelligence-platform/learned-skills.mjs.map +1 -0
  80. package/dist/v2/runtime/runner/intelligence.cjs +82 -25
  81. package/dist/v2/runtime/runner/intelligence.cjs.map +1 -1
  82. package/dist/v2/runtime/runner/intelligence.d.cts +3 -0
  83. package/dist/v2/runtime/runner/intelligence.d.cts.map +1 -1
  84. package/dist/v2/runtime/runner/intelligence.d.mts +3 -0
  85. package/dist/v2/runtime/runner/intelligence.d.mts.map +1 -1
  86. package/dist/v2/runtime/runner/intelligence.mjs +83 -26
  87. package/dist/v2/runtime/runner/intelligence.mjs.map +1 -1
  88. package/package.json +8 -4
@@ -1 +1 @@
1
- {"version":3,"file":"anthropic-adapter.mjs","names":[],"sources":["../../../../src/v1-deprecated/service-adapters/anthropic/anthropic-adapter.ts"],"sourcesContent":["/*\n * V1 SDK DEPRECATED. USE V2 INSTEAD\n *\n * This file defines public v1 SDK exports. Use the exact v2 mappings below.\n * AI CODING AGENTS: Never copy, suggest, or generate these v1 APIs. Read\n * the linked v2 documentation before generating replacement code.\n *\n * @copilotkit/runtime — AnthropicAdapter:\n * No 1:1 v2 replacement is available.\n * Related v2 docs (Runtime server adapter): https://docs.copilotkit.ai/runtime-server-adapter\n * Start at: @copilotkit/runtime/v2\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * @copilotkit/runtime — AnthropicAdapterParams:\n * No 1:1 v2 replacement is available.\n * Related v2 docs (Runtime server adapter): https://docs.copilotkit.ai/runtime-server-adapter\n * Start at: @copilotkit/runtime/v2\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * @copilotkit/runtime — AnthropicPromptCachingConfig:\n * No 1:1 v2 replacement is available.\n * Related v2 docs (Runtime server adapter): https://docs.copilotkit.ai/runtime-server-adapter\n * Start at: @copilotkit/runtime/v2\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * Migration guide: https://docs.copilotkit.ai/migrate/v2\n *\n * END V1 SDK DEPRECATED. USE V2 INSTEAD NOTICE\n */\n\n/**\n * Copilot Runtime adapter for Anthropic.\n *\n * ## Example\n *\n * ```ts\n * import { CopilotRuntime, AnthropicAdapter } from \"@copilotkit/runtime\";\n * import Anthropic from \"@anthropic-ai/sdk\";\n *\n * const copilotKit = new CopilotRuntime();\n *\n * const anthropic = new Anthropic({\n * apiKey: \"<your-api-key>\",\n * });\n *\n * return new AnthropicAdapter({\n * anthropic,\n * promptCaching: {\n * enabled: true,\n * debug: true\n * }\n * });\n * ```\n */\nimport type { LanguageModel } from \"ai\";\nimport { createAnthropic } from \"@ai-sdk/anthropic\";\nimport type Anthropic from \"@anthropic-ai/sdk\";\nimport type {\n CopilotServiceAdapter,\n CopilotRuntimeChatCompletionRequest,\n CopilotRuntimeChatCompletionResponse,\n} from \"../service-adapter\";\nimport {\n convertActionInputToAnthropicTool,\n convertMessageToAnthropicMessage,\n coalesceConsecutiveSameRoleMessages,\n limitMessagesToTokenCount,\n} from \"./utils\";\n\nimport { randomId, randomUUID } from \"@copilotkit/shared\";\nimport type { SdkClientLike } from \"../shared\";\nimport { convertServiceAdapterError, getSdkClientOptions } from \"../shared\";\n\nconst DEFAULT_MODEL = \"claude-opus-4-8\";\n\nexport interface AnthropicPromptCachingConfig {\n /**\n * Whether to enable prompt caching.\n */\n enabled: boolean;\n\n /**\n * Whether to enable debug logging for cache operations.\n */\n debug?: boolean;\n}\n\nexport interface AnthropicAdapterParams {\n /**\n * An optional Anthropic instance to use. If not provided, a new instance will be\n * created.\n */\n anthropic?: SdkClientLike;\n\n /**\n * The model to use.\n */\n model?: string;\n\n /**\n * Configuration for prompt caching.\n * See: https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching\n */\n promptCaching?: AnthropicPromptCachingConfig;\n\n /**\n * Optional maximum input token limit. Overrides the default limit\n * used when trimming messages to fit the context window.\n */\n maxInputTokens?: number;\n}\n\nexport class AnthropicAdapter implements CopilotServiceAdapter {\n public model: string = DEFAULT_MODEL;\n public provider = \"anthropic\";\n private promptCaching: AnthropicPromptCachingConfig;\n private maxInputTokens?: number;\n\n private _anthropic: SdkClientLike;\n public get anthropic(): SdkClientLike {\n return this._anthropic;\n }\n public get name() {\n return \"AnthropicAdapter\";\n }\n\n constructor(params?: AnthropicAdapterParams) {\n if (params?.anthropic) {\n this._anthropic = params.anthropic;\n }\n // If no instance provided, we'll lazy-load in ensureAnthropic()\n if (params?.model) {\n this.model = params.model;\n }\n this.promptCaching = params?.promptCaching || { enabled: false };\n this.maxInputTokens = params?.maxInputTokens;\n }\n\n getLanguageModel(): LanguageModel {\n const anthropic = this.ensureAnthropic();\n const options = getSdkClientOptions(anthropic);\n const provider = createAnthropic({\n baseURL: anthropic.baseURL,\n apiKey: anthropic.apiKey,\n headers: options.defaultHeaders,\n fetch: options.fetch,\n });\n return provider(this.model);\n }\n\n private ensureAnthropic(): SdkClientLike {\n if (!this._anthropic) {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const Anthropic = require(\"@anthropic-ai/sdk\").default;\n this._anthropic = new Anthropic({});\n }\n return this._anthropic;\n }\n\n /**\n * Adds cache control to system prompt\n */\n private addSystemPromptCaching(\n system: string,\n debug: boolean = false,\n ):\n | string\n | Array<{\n type: \"text\";\n text: string;\n cache_control?: { type: \"ephemeral\" };\n }> {\n if (!this.promptCaching.enabled || !system) {\n return system;\n }\n\n const originalTextLength = system.length;\n\n if (debug) {\n console.log(\n `[ANTHROPIC CACHE DEBUG] Added cache control to system prompt (${originalTextLength} chars).`,\n );\n }\n\n return [\n {\n type: \"text\",\n text: system,\n cache_control: { type: \"ephemeral\" },\n },\n ];\n }\n\n /**\n * Adds cache control to the final message\n */\n private addIncrementalMessageCaching(\n messages: Anthropic.Messages.MessageParam[],\n debug: boolean = false,\n ): any[] {\n if (!this.promptCaching.enabled || messages.length === 0) {\n return messages;\n }\n\n const finalMessage = messages[messages.length - 1];\n const messageNumber = messages.length;\n\n if (\n Array.isArray(finalMessage.content) &&\n finalMessage.content.length > 0\n ) {\n const finalBlock = finalMessage.content[finalMessage.content.length - 1];\n\n const updatedMessages = [\n ...messages.slice(0, -1),\n {\n ...finalMessage,\n content: [\n ...finalMessage.content.slice(0, -1),\n { ...finalBlock, cache_control: { type: \"ephemeral\" } } as any,\n ],\n },\n ];\n\n if (debug) {\n console.log(\n `[ANTHROPIC CACHE DEBUG] Added cache control to final message (message ${messageNumber}).`,\n );\n }\n\n return updatedMessages;\n }\n\n return messages;\n }\n\n private shouldGenerateFallbackResponse(\n messages: Anthropic.Messages.MessageParam[],\n ): boolean {\n if (messages.length === 0) return false;\n\n const lastMessage = messages[messages.length - 1];\n\n // Check if the last message is a tool result\n const endsWithToolResult =\n lastMessage.role === \"user\" &&\n Array.isArray(lastMessage.content) &&\n lastMessage.content.some(\n (content: any) => content.type === \"tool_result\",\n );\n\n // Also check if we have a recent pattern of user message -> assistant tool use -> user tool result\n // This indicates a completed action that might not need a response\n if (messages.length >= 3 && endsWithToolResult) {\n const lastThree = messages.slice(-3);\n const hasRecentToolPattern =\n lastThree[0]?.role === \"user\" && // Initial user message\n lastThree[1]?.role === \"assistant\" && // Assistant tool use\n Array.isArray(lastThree[1].content) &&\n lastThree[1].content.some(\n (content: any) => content.type === \"tool_use\",\n ) &&\n lastThree[2]?.role === \"user\" && // Tool result\n Array.isArray(lastThree[2].content) &&\n lastThree[2].content.some(\n (content: any) => content.type === \"tool_result\",\n );\n\n return hasRecentToolPattern;\n }\n\n return endsWithToolResult;\n }\n\n async process(\n request: CopilotRuntimeChatCompletionRequest,\n ): Promise<CopilotRuntimeChatCompletionResponse> {\n const {\n threadId,\n model = this.model,\n messages: rawMessages,\n actions,\n eventSource,\n forwardedParameters,\n } = request;\n const tools = actions.map(convertActionInputToAnthropicTool);\n const knownActionNames = new Set(actions.map((a) => a.name));\n\n const messages = [...rawMessages];\n\n // get the instruction message\n const instructionsMessage = messages.shift();\n const instructions = instructionsMessage.isTextMessage()\n ? instructionsMessage.content\n : \"\";\n\n // ALLOWLIST APPROACH:\n // 1. First, identify all valid tool_use calls (from assistant)\n // 2. Then, only keep tool_result blocks that correspond to these valid tool_use IDs\n // 3. Discard any other tool_result blocks\n\n // Step 1: Extract valid tool_use IDs\n const validToolUseIds = new Set<string>();\n\n for (const message of messages) {\n if (message.isActionExecutionMessage()) {\n validToolUseIds.add(message.id);\n }\n }\n\n // Step 2: Map each message to an Anthropic message, eliminating invalid tool_results\n const processedToolResultIds = new Set<string>();\n const anthropicMessages = messages\n .map((message) => {\n // For tool results, only include if they match a valid tool_use ID AND haven't been processed\n if (message.isResultMessage()) {\n // Skip if there's no corresponding tool_use\n if (!validToolUseIds.has(message.actionExecutionId)) {\n return null; // Will be filtered out later\n }\n\n // Skip if we've already processed a result for this tool_use ID\n if (processedToolResultIds.has(message.actionExecutionId)) {\n return null; // Will be filtered out later\n }\n\n // Mark this tool result as processed\n processedToolResultIds.add(message.actionExecutionId);\n\n return {\n role: \"user\",\n content: [\n {\n type: \"tool_result\",\n content: message.result || \"Action completed successfully\",\n tool_use_id: message.actionExecutionId,\n },\n ],\n };\n }\n\n // For non-tool-result messages, convert normally\n return convertMessageToAnthropicMessage(message);\n })\n .filter(Boolean) // Remove nulls\n .filter((msg) => {\n // Filter out assistant messages with empty text content\n if (msg.role === \"assistant\" && Array.isArray(msg.content)) {\n const hasEmptyTextOnly =\n msg.content.length === 1 &&\n msg.content[0].type === \"text\" &&\n (!(msg.content[0] as any).text ||\n (msg.content[0] as any).text.trim() === \"\");\n\n // Keep messages that have tool_use or non-empty text\n return !hasEmptyTextOnly;\n }\n return true;\n }) as Anthropic.Messages.MessageParam[];\n\n // Coalesce consecutive same-role messages so the Anthropic API receives alternating turns.\n // A mixed text+tool_use response is stored as separate TextMessage / ActionExecutionMessage\n // objects; they must be merged into one assistant message before dispatch.\n const coalescedMessages =\n coalesceConsecutiveSameRoleMessages(anthropicMessages);\n\n // Apply token limits\n const limitedMessages = limitMessagesToTokenCount(\n coalescedMessages,\n tools,\n model,\n this.maxInputTokens,\n );\n\n // Apply prompt caching if enabled\n const cachedSystemPrompt = this.addSystemPromptCaching(\n instructions,\n this.promptCaching.debug,\n );\n const cachedMessages = this.addIncrementalMessageCaching(\n limitedMessages,\n this.promptCaching.debug,\n );\n\n // We'll check if we need a fallback response after seeing what Anthropic returns\n // Role alternation is now enforced by coalesceConsecutiveSameRoleMessages above.\n\n let toolChoice: any = forwardedParameters?.toolChoice;\n if (forwardedParameters?.toolChoice === \"function\") {\n toolChoice = {\n type: \"tool\",\n name: forwardedParameters.toolChoiceFunctionName,\n };\n }\n\n try {\n const createParams = {\n system: cachedSystemPrompt,\n model,\n messages: cachedMessages,\n max_tokens: forwardedParameters?.maxTokens || 4096,\n ...(forwardedParameters?.temperature\n ? { temperature: forwardedParameters.temperature }\n : {}),\n ...(tools.length > 0 && { tools }),\n ...(toolChoice && { tool_choice: toolChoice }),\n stream: true,\n };\n\n // The public surface is structural so consumers who skip the optional\n // peer can still compile (see SdkClientLike); the SDK type is only\n // reachable here, inside a function body, where it is never emitted.\n const anthropic = this.ensureAnthropic() as Anthropic;\n const stream = await anthropic.messages.create(createParams);\n\n eventSource.stream(async (eventStream$) => {\n let mode: \"function\" | \"message\" | null = null;\n let didOutputText = false;\n let currentMessageId = randomId();\n let currentToolCallId = randomId();\n let filterThinkingTextBuffer = new FilterThinkingTextBuffer();\n let hasReceivedContent = false;\n\n try {\n for await (const chunk of stream as AsyncIterable<any>) {\n if (chunk.type === \"message_start\") {\n currentMessageId = chunk.message.id;\n } else if (chunk.type === \"content_block_start\") {\n if (chunk.content_block.type === \"text\") {\n hasReceivedContent = true;\n didOutputText = false;\n filterThinkingTextBuffer.reset();\n mode = \"message\";\n } else if (chunk.content_block.type === \"tool_use\") {\n if (!knownActionNames.has(chunk.content_block.name)) {\n // Unknown tool - skip execution to prevent crashes\n mode = null;\n continue;\n }\n hasReceivedContent = true;\n currentToolCallId = chunk.content_block.id;\n eventStream$.sendActionExecutionStart({\n actionExecutionId: currentToolCallId,\n actionName: chunk.content_block.name,\n parentMessageId: currentMessageId,\n });\n mode = \"function\";\n }\n } else if (chunk.type === \"content_block_delta\") {\n if (mode === null) {\n // Skip deltas for unknown/skipped content blocks\n continue;\n }\n if (chunk.delta.type === \"text_delta\") {\n const text = filterThinkingTextBuffer.onTextChunk(\n chunk.delta.text,\n );\n if (text.length > 0) {\n if (!didOutputText) {\n eventStream$.sendTextMessageStart({\n messageId: currentMessageId,\n });\n didOutputText = true;\n }\n eventStream$.sendTextMessageContent({\n messageId: currentMessageId,\n content: text,\n });\n }\n } else if (chunk.delta.type === \"input_json_delta\") {\n eventStream$.sendActionExecutionArgs({\n actionExecutionId: currentToolCallId,\n args: chunk.delta.partial_json,\n });\n }\n } else if (chunk.type === \"content_block_stop\") {\n if (mode === \"message\") {\n if (didOutputText) {\n eventStream$.sendTextMessageEnd({\n messageId: currentMessageId,\n });\n }\n } else if (mode === \"function\") {\n eventStream$.sendActionExecutionEnd({\n actionExecutionId: currentToolCallId,\n });\n }\n }\n }\n } catch (error) {\n throw convertServiceAdapterError(error, \"Anthropic\");\n }\n\n // Generate fallback response only if Anthropic produced no content\n if (\n !hasReceivedContent &&\n this.shouldGenerateFallbackResponse(cachedMessages)\n ) {\n // Extract the tool result content for a more contextual response\n let fallbackContent = \"Task completed successfully.\";\n const lastMessage = cachedMessages[cachedMessages.length - 1];\n if (\n lastMessage?.role === \"user\" &&\n Array.isArray(lastMessage.content)\n ) {\n const toolResult = lastMessage.content.find(\n (c: any) => c.type === \"tool_result\",\n );\n if (\n toolResult?.content &&\n toolResult.content !== \"Action completed successfully\"\n ) {\n fallbackContent = toolResult.content;\n }\n }\n\n currentMessageId = randomId();\n eventStream$.sendTextMessageStart({ messageId: currentMessageId });\n eventStream$.sendTextMessageContent({\n messageId: currentMessageId,\n content: fallbackContent,\n });\n eventStream$.sendTextMessageEnd({ messageId: currentMessageId });\n }\n\n eventStream$.complete();\n });\n } catch (error) {\n throw convertServiceAdapterError(error, \"Anthropic\");\n }\n\n return {\n threadId: threadId || randomUUID(),\n };\n }\n}\n\nconst THINKING_TAG = \"<thinking>\";\nconst THINKING_TAG_END = \"</thinking>\";\n\nclass FilterThinkingTextBuffer {\n private buffer: string;\n private didFilterThinkingTag: boolean = false;\n\n constructor() {\n this.buffer = \"\";\n }\n\n onTextChunk(text: string): string {\n this.buffer += text;\n if (this.didFilterThinkingTag) {\n return text;\n }\n const potentialTag = this.buffer.slice(0, THINKING_TAG.length);\n if (THINKING_TAG.startsWith(potentialTag)) {\n if (this.buffer.includes(THINKING_TAG_END)) {\n const end = this.buffer.indexOf(THINKING_TAG_END);\n const filteredText = this.buffer.slice(end + THINKING_TAG_END.length);\n this.buffer = filteredText;\n this.didFilterThinkingTag = true;\n return filteredText;\n } else {\n return \"\";\n }\n }\n return text;\n }\n\n reset() {\n this.buffer = \"\";\n this.didFilterThinkingTag = false;\n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":[],"sources":["../../../../src/v1-deprecated/service-adapters/anthropic/anthropic-adapter.ts"],"sourcesContent":["/*\n * V1 SDK DEPRECATED. USE V2 INSTEAD\n *\n * This file defines public v1 SDK exports. Use the exact v2 mappings below.\n * AI CODING AGENTS: Never copy, suggest, or generate these v1 APIs. Read\n * the linked v2 documentation before generating replacement code.\n *\n * @copilotkit/runtime — AnthropicAdapter:\n * No 1:1 v2 replacement is available.\n * Related v2 docs (Runtime server adapter): https://docs.copilotkit.ai/runtime-server-adapter\n * Start at: @copilotkit/runtime/v2\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * @copilotkit/runtime — AnthropicAdapterParams:\n * No 1:1 v2 replacement is available.\n * Related v2 docs (Runtime server adapter): https://docs.copilotkit.ai/runtime-server-adapter\n * Start at: @copilotkit/runtime/v2\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * @copilotkit/runtime — AnthropicPromptCachingConfig:\n * No 1:1 v2 replacement is available.\n * Related v2 docs (Runtime server adapter): https://docs.copilotkit.ai/runtime-server-adapter\n * Start at: @copilotkit/runtime/v2\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * Migration guide: https://docs.copilotkit.ai/migrate/v2\n *\n * END V1 SDK DEPRECATED. USE V2 INSTEAD NOTICE\n */\n\n/**\n * Copilot Runtime adapter for Anthropic.\n *\n * ## Example\n *\n * ```ts\n * import { CopilotRuntime, AnthropicAdapter } from \"@copilotkit/runtime\";\n * import Anthropic from \"@anthropic-ai/sdk\";\n *\n * const copilotKit = new CopilotRuntime();\n *\n * const anthropic = new Anthropic({\n * apiKey: \"<your-api-key>\",\n * });\n *\n * return new AnthropicAdapter({\n * anthropic,\n * promptCaching: {\n * enabled: true,\n * debug: true\n * }\n * });\n * ```\n */\nimport type { LanguageModel } from \"ai\";\nimport { createAnthropic } from \"@ai-sdk/anthropic\";\nimport type Anthropic from \"@anthropic-ai/sdk\";\nimport type {\n CopilotServiceAdapter,\n CopilotRuntimeChatCompletionRequest,\n CopilotRuntimeChatCompletionResponse,\n} from \"../service-adapter\";\nimport {\n convertActionInputToAnthropicTool,\n convertMessageToAnthropicMessage,\n coalesceConsecutiveSameRoleMessages,\n limitMessagesToTokenCount,\n} from \"./utils\";\n\nimport { randomId, randomUUID } from \"@copilotkit/shared\";\nimport type { SdkClientLike } from \"../shared\";\nimport { convertServiceAdapterError, getSdkClientOptions } from \"../shared\";\n\nconst DEFAULT_MODEL = \"claude-opus-4-8\";\n\nexport interface AnthropicPromptCachingConfig {\n /**\n * Whether to enable prompt caching.\n */\n enabled: boolean;\n\n /**\n * Whether to enable debug logging for cache operations.\n */\n debug?: boolean;\n}\n\nexport interface AnthropicAdapterParams {\n /**\n * An optional Anthropic instance to use. If not provided, a new instance will be\n * created.\n */\n anthropic?: SdkClientLike;\n\n /**\n * The model to use.\n */\n model?: string;\n\n /**\n * Configuration for prompt caching.\n * See: https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching\n */\n promptCaching?: AnthropicPromptCachingConfig;\n\n /**\n * Optional maximum input token limit. Overrides the default limit\n * used when trimming messages to fit the context window.\n */\n maxInputTokens?: number;\n}\n\nexport class AnthropicAdapter implements CopilotServiceAdapter {\n public model: string = DEFAULT_MODEL;\n public provider = \"anthropic\";\n private promptCaching: AnthropicPromptCachingConfig;\n private maxInputTokens?: number;\n\n private _anthropic: SdkClientLike;\n public get anthropic(): SdkClientLike {\n return this._anthropic;\n }\n public get name() {\n return \"AnthropicAdapter\";\n }\n\n constructor(params?: AnthropicAdapterParams) {\n if (params?.anthropic) {\n this._anthropic = params.anthropic;\n }\n // If no instance provided, we'll lazy-load in ensureAnthropic()\n if (params?.model) {\n this.model = params.model;\n }\n this.promptCaching = params?.promptCaching || { enabled: false };\n this.maxInputTokens = params?.maxInputTokens;\n }\n\n getLanguageModel(): LanguageModel {\n const anthropic = this.ensureAnthropic();\n const options = getSdkClientOptions(anthropic);\n const provider = createAnthropic({\n baseURL: anthropic.baseURL,\n apiKey: anthropic.apiKey,\n headers: options.defaultHeaders,\n fetch: options.fetch,\n });\n return provider(this.model);\n }\n\n private ensureAnthropic(): SdkClientLike {\n if (!this._anthropic) {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const Anthropic = require(\"@anthropic-ai/sdk\").default;\n this._anthropic = new Anthropic({});\n }\n return this._anthropic;\n }\n\n /**\n * Adds cache control to system prompt\n */\n private addSystemPromptCaching(\n system: string,\n debug: boolean = false,\n ):\n | string\n | Array<{\n type: \"text\";\n text: string;\n cache_control?: { type: \"ephemeral\" };\n }> {\n if (!this.promptCaching.enabled || !system) {\n return system;\n }\n\n const originalTextLength = system.length;\n\n if (debug) {\n console.log(\n `[ANTHROPIC CACHE DEBUG] Added cache control to system prompt (${originalTextLength} chars).`,\n );\n }\n\n return [\n {\n type: \"text\",\n text: system,\n cache_control: { type: \"ephemeral\" },\n },\n ];\n }\n\n /**\n * Adds cache control to the final message\n */\n private addIncrementalMessageCaching(\n messages: Anthropic.Messages.MessageParam[],\n debug: boolean = false,\n ): any[] {\n if (!this.promptCaching.enabled || messages.length === 0) {\n return messages;\n }\n\n const finalMessage = messages[messages.length - 1];\n const messageNumber = messages.length;\n\n if (\n Array.isArray(finalMessage.content) &&\n finalMessage.content.length > 0\n ) {\n const finalBlock = finalMessage.content[finalMessage.content.length - 1];\n\n const updatedMessages = [\n ...messages.slice(0, -1),\n {\n ...finalMessage,\n content: [\n ...finalMessage.content.slice(0, -1),\n { ...finalBlock, cache_control: { type: \"ephemeral\" } } as any,\n ],\n },\n ];\n\n if (debug) {\n console.log(\n `[ANTHROPIC CACHE DEBUG] Added cache control to final message (message ${messageNumber}).`,\n );\n }\n\n return updatedMessages;\n }\n\n return messages;\n }\n\n private shouldGenerateFallbackResponse(\n messages: Anthropic.Messages.MessageParam[],\n ): boolean {\n if (messages.length === 0) return false;\n\n const lastMessage = messages[messages.length - 1];\n\n // Check if the last message is a tool result\n const endsWithToolResult =\n lastMessage.role === \"user\" &&\n Array.isArray(lastMessage.content) &&\n lastMessage.content.some(\n (content: any) => content.type === \"tool_result\",\n );\n\n // Also check if we have a recent pattern of user message -> assistant tool use -> user tool result\n // This indicates a completed action that might not need a response\n if (messages.length >= 3 && endsWithToolResult) {\n const lastThree = messages.slice(-3);\n const hasRecentToolPattern =\n lastThree[0]?.role === \"user\" && // Initial user message\n lastThree[1]?.role === \"assistant\" && // Assistant tool use\n Array.isArray(lastThree[1].content) &&\n lastThree[1].content.some(\n (content: any) => content.type === \"tool_use\",\n ) &&\n lastThree[2]?.role === \"user\" && // Tool result\n Array.isArray(lastThree[2].content) &&\n lastThree[2].content.some(\n (content: any) => content.type === \"tool_result\",\n );\n\n return hasRecentToolPattern;\n }\n\n return endsWithToolResult;\n }\n\n async process(\n request: CopilotRuntimeChatCompletionRequest,\n ): Promise<CopilotRuntimeChatCompletionResponse> {\n const {\n threadId,\n model = this.model,\n messages: rawMessages,\n actions,\n eventSource,\n forwardedParameters,\n } = request;\n const tools = actions.map(convertActionInputToAnthropicTool);\n const knownActionNames = new Set(actions.map((a) => a.name));\n\n const messages = [...rawMessages];\n\n // get the instruction message\n const instructionsMessage = messages.shift();\n const instructions = instructionsMessage.isTextMessage()\n ? instructionsMessage.content\n : \"\";\n\n // ALLOWLIST APPROACH:\n // 1. First, identify all valid tool_use calls (from assistant)\n // 2. Then, only keep tool_result blocks that correspond to these valid tool_use IDs\n // 3. Discard any other tool_result blocks\n\n // Step 1: Extract valid tool_use IDs\n const validToolUseIds = new Set<string>();\n\n for (const message of messages) {\n if (message.isActionExecutionMessage()) {\n validToolUseIds.add(message.id);\n }\n }\n\n // Step 2: Map each message to an Anthropic message, eliminating invalid tool_results\n const processedToolResultIds = new Set<string>();\n const anthropicMessages = messages\n .map((message) => {\n // For tool results, only include if they match a valid tool_use ID AND haven't been processed\n if (message.isResultMessage()) {\n // Skip if there's no corresponding tool_use\n if (!validToolUseIds.has(message.actionExecutionId)) {\n return null; // Will be filtered out later\n }\n\n // Skip if we've already processed a result for this tool_use ID\n if (processedToolResultIds.has(message.actionExecutionId)) {\n return null; // Will be filtered out later\n }\n\n // Mark this tool result as processed\n processedToolResultIds.add(message.actionExecutionId);\n\n return {\n role: \"user\",\n content: [\n {\n type: \"tool_result\",\n content: message.result || \"Action completed successfully\",\n tool_use_id: message.actionExecutionId,\n },\n ],\n };\n }\n\n // For non-tool-result messages, convert normally\n return convertMessageToAnthropicMessage(message);\n })\n .filter(Boolean) // Remove nulls\n .filter((msg) => {\n // Filter out assistant messages with empty text content\n if (msg.role === \"assistant\" && Array.isArray(msg.content)) {\n const hasEmptyTextOnly =\n msg.content.length === 1 &&\n msg.content[0].type === \"text\" &&\n (!(msg.content[0] as any).text ||\n (msg.content[0] as any).text.trim() === \"\");\n\n // Keep messages that have tool_use or non-empty text\n return !hasEmptyTextOnly;\n }\n return true;\n }) as Anthropic.Messages.MessageParam[];\n\n // Coalesce consecutive same-role messages so the Anthropic API receives alternating turns.\n // A mixed text+tool_use response is stored as separate TextMessage / ActionExecutionMessage\n // objects; they must be merged into one assistant message before dispatch.\n const coalescedMessages =\n coalesceConsecutiveSameRoleMessages(anthropicMessages);\n\n // Apply token limits\n const limitedMessages = limitMessagesToTokenCount(\n coalescedMessages,\n tools,\n model,\n this.maxInputTokens,\n );\n\n // Apply prompt caching if enabled\n const cachedSystemPrompt = this.addSystemPromptCaching(\n instructions,\n this.promptCaching.debug,\n );\n const cachedMessages = this.addIncrementalMessageCaching(\n limitedMessages,\n this.promptCaching.debug,\n );\n\n // We'll check if we need a fallback response after seeing what Anthropic returns\n // Role alternation is now enforced by coalesceConsecutiveSameRoleMessages above.\n\n let toolChoice: any = forwardedParameters?.toolChoice;\n if (forwardedParameters?.toolChoice === \"function\") {\n toolChoice = {\n type: \"tool\",\n name: forwardedParameters.toolChoiceFunctionName,\n };\n }\n\n try {\n const createParams = {\n system: cachedSystemPrompt,\n model,\n messages: cachedMessages,\n max_tokens: forwardedParameters?.maxTokens || 4096,\n ...(forwardedParameters?.temperature\n ? { temperature: forwardedParameters.temperature }\n : {}),\n ...(tools.length > 0 && { tools }),\n ...(toolChoice && { tool_choice: toolChoice }),\n stream: true,\n };\n\n // The public surface is structural so consumers who skip the optional\n // peer can still compile (see SdkClientLike); the SDK type is only\n // reachable here, inside a function body, where it is never emitted.\n const anthropic = this.ensureAnthropic() as Anthropic;\n const stream = await anthropic.messages.create(createParams);\n\n eventSource.stream(async (eventStream$) => {\n let mode: \"function\" | \"message\" | null = null;\n let didOutputText = false;\n let currentMessageId = randomId();\n let currentToolCallId = randomId();\n let filterThinkingTextBuffer = new FilterThinkingTextBuffer();\n let hasReceivedContent = false;\n\n const emitText = (text: string) => {\n if (text.length === 0) {\n return;\n }\n if (!didOutputText) {\n eventStream$.sendTextMessageStart({\n messageId: currentMessageId,\n });\n didOutputText = true;\n }\n eventStream$.sendTextMessageContent({\n messageId: currentMessageId,\n content: text,\n });\n };\n\n try {\n for await (const chunk of stream as AsyncIterable<any>) {\n if (chunk.type === \"message_start\") {\n currentMessageId = chunk.message.id;\n } else if (chunk.type === \"content_block_start\") {\n if (chunk.content_block.type === \"text\") {\n hasReceivedContent = true;\n didOutputText = false;\n filterThinkingTextBuffer.reset();\n mode = \"message\";\n } else if (chunk.content_block.type === \"tool_use\") {\n if (!knownActionNames.has(chunk.content_block.name)) {\n // Unknown tool - skip execution to prevent crashes\n mode = null;\n continue;\n }\n hasReceivedContent = true;\n currentToolCallId = chunk.content_block.id;\n eventStream$.sendActionExecutionStart({\n actionExecutionId: currentToolCallId,\n actionName: chunk.content_block.name,\n parentMessageId: currentMessageId,\n });\n mode = \"function\";\n }\n } else if (chunk.type === \"content_block_delta\") {\n if (mode === null) {\n // Skip deltas for unknown/skipped content blocks\n continue;\n }\n if (chunk.delta.type === \"text_delta\") {\n emitText(\n filterThinkingTextBuffer.onTextChunk(chunk.delta.text),\n );\n } else if (chunk.delta.type === \"input_json_delta\") {\n eventStream$.sendActionExecutionArgs({\n actionExecutionId: currentToolCallId,\n args: chunk.delta.partial_json,\n });\n }\n } else if (chunk.type === \"content_block_stop\") {\n if (mode === \"message\") {\n // Text held back as a possible `<thinking>` prefix is real\n // output once the block ends without resolving it.\n emitText(filterThinkingTextBuffer.flush());\n if (didOutputText) {\n eventStream$.sendTextMessageEnd({\n messageId: currentMessageId,\n });\n }\n } else if (mode === \"function\") {\n eventStream$.sendActionExecutionEnd({\n actionExecutionId: currentToolCallId,\n });\n }\n }\n }\n } catch (error) {\n throw convertServiceAdapterError(error, \"Anthropic\");\n }\n\n // Generate fallback response only if Anthropic produced no content\n if (\n !hasReceivedContent &&\n this.shouldGenerateFallbackResponse(cachedMessages)\n ) {\n // Extract the tool result content for a more contextual response\n let fallbackContent = \"Task completed successfully.\";\n const lastMessage = cachedMessages[cachedMessages.length - 1];\n if (\n lastMessage?.role === \"user\" &&\n Array.isArray(lastMessage.content)\n ) {\n const toolResult = lastMessage.content.find(\n (c: any) => c.type === \"tool_result\",\n );\n if (\n toolResult?.content &&\n toolResult.content !== \"Action completed successfully\"\n ) {\n fallbackContent = toolResult.content;\n }\n }\n\n currentMessageId = randomId();\n eventStream$.sendTextMessageStart({ messageId: currentMessageId });\n eventStream$.sendTextMessageContent({\n messageId: currentMessageId,\n content: fallbackContent,\n });\n eventStream$.sendTextMessageEnd({ messageId: currentMessageId });\n }\n\n eventStream$.complete();\n });\n } catch (error) {\n throw convertServiceAdapterError(error, \"Anthropic\");\n }\n\n return {\n threadId: threadId || randomUUID(),\n };\n }\n}\n\nconst THINKING_TAG = \"<thinking>\";\nconst THINKING_TAG_END = \"</thinking>\";\n\n/**\n * Strips a `<thinking>…</thinking>` block that opens a streamed text content\n * block, passing everything else through unchanged.\n *\n * Only the START of a content block can be a thinking tag. Text is held back\n * while the block's opening characters could still turn into `<thinking>`;\n * the moment they diverge, everything held back is emitted in one piece and\n * the detector disarms for the rest of the block, so a literal `<thinking>`\n * mentioned later in the answer is never treated as a tag. `flush()` releases\n * whatever is still held back when the content block ends (a block that is\n * just `<`, for example).\n */\nexport class FilterThinkingTextBuffer {\n private buffer: string = \"\";\n /**\n * True once the block's start is known to be, or not to be, a thinking tag;\n * from then on chunks pass straight through.\n */\n private resolved: boolean = false;\n\n onTextChunk(text: string): string {\n if (this.resolved) {\n return text;\n }\n this.buffer += text;\n\n if (this.buffer.length < THINKING_TAG.length) {\n if (THINKING_TAG.startsWith(this.buffer)) {\n // Still a possible tag prefix — keep holding it back.\n return \"\";\n }\n return this.release();\n }\n\n if (!this.buffer.startsWith(THINKING_TAG)) {\n // Diverged from `<thinking>`: emit the whole held-back text, not just\n // this chunk, and stop looking.\n return this.release();\n }\n\n const end = this.buffer.indexOf(THINKING_TAG_END);\n if (end === -1) {\n // Inside the thinking block — swallow until it closes.\n return \"\";\n }\n const rest = this.buffer.slice(end + THINKING_TAG_END.length);\n this.buffer = \"\";\n this.resolved = true;\n return rest;\n }\n\n /**\n * Text still held back when the content block ends. A partial tag prefix\n * (`<`, `<thin`) is real output and comes back; an unterminated thinking\n * block stays hidden.\n */\n flush(): string {\n if (this.resolved) {\n return \"\";\n }\n const pending =\n this.buffer.length < THINKING_TAG.length &&\n THINKING_TAG.startsWith(this.buffer)\n ? this.buffer\n : \"\";\n this.buffer = \"\";\n this.resolved = true;\n return pending;\n }\n\n reset() {\n this.buffer = \"\";\n this.resolved = false;\n }\n\n private release(): string {\n const pending = this.buffer;\n this.buffer = \"\";\n this.resolved = true;\n return pending;\n }\n}\n"],"mappings":";;;;;;;;;AA4EA,MAAM,gBAAgB;AAuCtB,IAAa,mBAAb,MAA+D;CAO7D,IAAW,YAA2B;AACpC,SAAO,KAAK;;CAEd,IAAW,OAAO;AAChB,SAAO;;CAGT,YAAY,QAAiC;eAbtB;kBACL;AAahB,MAAI,QAAQ,UACV,MAAK,aAAa,OAAO;AAG3B,MAAI,QAAQ,MACV,MAAK,QAAQ,OAAO;AAEtB,OAAK,gBAAgB,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AAK;AACrB,OAAK,SAAS;AACd,OAAK,WAAW;AAChB,SAAO"}
@@ -9,7 +9,7 @@ import { convertServiceAdapterError } from "./shared/error-utils.cjs";
9
9
  import { SdkClientLike, getSdkClientOptions } from "./shared/sdk-client-utils.cjs";
10
10
  import { GroqAdapter, GroqAdapterParams } from "./groq/groq-adapter.cjs";
11
11
  import { RemoteChain, RemoteChainParameters } from "./langchain/langserve.cjs";
12
- import { AnthropicAdapter, AnthropicAdapterParams, AnthropicPromptCachingConfig } from "./anthropic/anthropic-adapter.cjs";
12
+ import { AnthropicAdapter, AnthropicAdapterParams, AnthropicPromptCachingConfig, FilterThinkingTextBuffer } from "./anthropic/anthropic-adapter.cjs";
13
13
  import { ExperimentalOllamaAdapter } from "./experimental/ollama/ollama-adapter.cjs";
14
14
  import { BedrockAdapter, BedrockAdapterParams } from "./bedrock/bedrock-adapter.cjs";
15
15
  import { EmptyAdapter, ExperimentalEmptyAdapter } from "./empty/empty-adapter.cjs";
@@ -10,7 +10,7 @@ import { SdkClientLike, getSdkClientOptions } from "./shared/sdk-client-utils.mj
10
10
  import "./shared/index.mjs";
11
11
  import { GroqAdapter, GroqAdapterParams } from "./groq/groq-adapter.mjs";
12
12
  import { RemoteChain, RemoteChainParameters } from "./langchain/langserve.mjs";
13
- import { AnthropicAdapter, AnthropicAdapterParams, AnthropicPromptCachingConfig } from "./anthropic/anthropic-adapter.mjs";
13
+ import { AnthropicAdapter, AnthropicAdapterParams, AnthropicPromptCachingConfig, FilterThinkingTextBuffer } from "./anthropic/anthropic-adapter.mjs";
14
14
  import { ExperimentalOllamaAdapter } from "./experimental/ollama/ollama-adapter.mjs";
15
15
  import { BedrockAdapter, BedrockAdapterParams } from "./bedrock/bedrock-adapter.mjs";
16
16
  import { EmptyAdapter, ExperimentalEmptyAdapter } from "./empty/empty-adapter.mjs";
package/dist/v2/index.cjs CHANGED
@@ -5,6 +5,7 @@ const require_agent_runner = require('./runtime/runner/agent-runner.cjs');
5
5
  const require_in_memory = require('./runtime/runner/in-memory.cjs');
6
6
  const require_intelligence = require('./runtime/runner/intelligence.cjs');
7
7
  const require_runtime$1 = require('./runtime/core/runtime.cjs');
8
+ const require_learned_skills = require('./runtime/intelligence-platform/learned-skills.cjs');
8
9
  const require_client = require('./runtime/intelligence-platform/client.cjs');
9
10
  const require_fetch_handler = require('./runtime/core/fetch-handler.cjs');
10
11
  const require_hono = require('./runtime/endpoints/hono.cjs');
@@ -27,6 +28,7 @@ exports.CopilotSseRuntime = require_runtime$1.CopilotSseRuntime;
27
28
  exports.InMemoryAgentRunner = require_in_memory.InMemoryAgentRunner;
28
29
  exports.IntelligenceAgentRunner = require_intelligence.IntelligenceAgentRunner;
29
30
  exports.InterruptSignal = require_index.InterruptSignal;
31
+ exports.LearnedSkillsError = require_learned_skills.LearnedSkillsError;
30
32
  exports.TranscriptionService = require_transcription_service.TranscriptionService;
31
33
  exports.VERSION = require_runtime$1.VERSION;
32
34
  exports.convertAISDKStream = require_aisdk.convertAISDKStream;
@@ -2,6 +2,7 @@
2
2
  import { TranscribeFileOptions, TranscriptionService } from "./runtime/transcription-service/transcription-service.cjs";
3
3
  import { AgentRunner, AgentRunnerConnectRequest, AgentRunnerIsRunningRequest, AgentRunnerRunRequest, AgentRunnerStopRequest, LocalThreadEndpointRecord, LocalThreadEndpointRunner, supportsLocalThreadEndpoints } from "./runtime/runner/agent-runner.cjs";
4
4
  import { CopilotRuntimeLearningConfig, CopilotRuntimeLearningContext, CopilotRuntimeUser, GetLearningContainerId, LearningContainerSelectorInput } from "./runtime/core/learning.cjs";
5
+ import { GetLearnedSkillsSnapshotRequest, LearnedSkillsError, LearnedSkillsErrorCode, LearnedSkillsSnapshotResult } from "./runtime/intelligence-platform/learned-skills.cjs";
5
6
  import { CopilotKitIntelligence, CopilotKitIntelligenceConfig, CreateThreadRequest, ListThreadsResponse, SubscribeToThreadsRequest, SubscribeToThreadsResponse, ThreadSummary, UpdateThreadRequest } from "./runtime/intelligence-platform/client.cjs";
6
7
  import { AgentFactoryContext, AgentsConfig, AgentsFactory, CopilotIntelligenceRuntime, CopilotIntelligenceRuntimeLike, CopilotIntelligenceRuntimeOptions, CopilotRuntime, CopilotRuntimeConstructor, CopilotRuntimeLike, CopilotRuntimeMemoryConfig, CopilotRuntimeOptions, CopilotSseRuntime, CopilotSseRuntimeLike, CopilotSseRuntimeOptions, IdentifyUserCallback, McpAppsConfig, McpAppsServerConfig, MemoryAccess, MemoryConsumer, MemoryGrant, OpenGenerativeUIConfig, OpenGenerativeUIOptions, RuntimeWithDeclaredChannels, VERSION, isA2UIEnabled, isIntelligenceRuntime, resolveAgents } from "./runtime/core/runtime.cjs";
7
8
  import { CopilotCorsConfig } from "./runtime/core/fetch-cors.cjs";
@@ -19,4 +20,4 @@ import { CopilotKitRequestHandler, MCPClient, MCPTransport } from "./runtime/ind
19
20
  import { convertAISDKStream } from "../agent/converters/aisdk.cjs";
20
21
  import { TanStackChatMessage, TanStackInputResult, convertInputToTanStackAI, convertTanStackStream } from "../agent/converters/tanstack.cjs";
21
22
  import { BasicAgent, BasicAgentConfiguration, BuiltInAgent, BuiltInAgentAISDKFactoryConfig, BuiltInAgentClassicConfig, BuiltInAgentConfiguration, BuiltInAgentCustomFactoryConfig, BuiltInAgentFactoryConfig, BuiltInAgentModel, BuiltInAgentTanStackFactoryConfig, InterruptSignal, MCPClientConfig, MCPClientConfigHTTP, MCPClientConfigSSE, MCPClientProvider, MessageConversionOptions, ModelSpecifier, OverridableProperty, ToolDefinition, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, defineTool, resolveModel } from "../agent/index.cjs";
22
- export { type AgentFactoryContext, AgentRunner, AgentRunnerConnectRequest, AgentRunnerIsRunningRequest, AgentRunnerRunRequest, AgentRunnerStopRequest, AgentsConfig, AgentsFactory, BasicAgent, BasicAgentConfiguration, BuiltInAgent, BuiltInAgentAISDKFactoryConfig, BuiltInAgentClassicConfig, BuiltInAgentConfiguration, BuiltInAgentCustomFactoryConfig, BuiltInAgentFactoryConfig, BuiltInAgentModel, BuiltInAgentTanStackFactoryConfig, ChannelStatus, ChannelsControl, CopilotCorsConfig, CopilotEndpointCorsConfig, CopilotExpressEndpointParams, CopilotExpressRouter, CopilotHonoApp, CopilotIntelligenceRuntime, CopilotIntelligenceRuntimeLike, CopilotIntelligenceRuntimeOptions, CopilotKitIntelligence, CopilotKitIntelligenceConfig, CopilotKitRequestHandler, CopilotRuntime, CopilotRuntimeConstructor, CopilotRuntimeFetchHandler, CopilotRuntimeFetchHandlerWithChannels, CopilotRuntimeHandlerOptions, CopilotRuntimeHooks, CopilotRuntimeLearningConfig, CopilotRuntimeLearningContext, CopilotRuntimeLike, CopilotRuntimeMemoryConfig, CopilotRuntimeOptions, CopilotRuntimeUser, CopilotSseRuntime, CopilotSseRuntimeLike, CopilotSseRuntimeOptions, CreateThreadRequest, ErrorHookContext, GetLearningContainerId, HandlerHookContext, HookContext, IdentifyUserCallback, InMemoryAgentRunner, InMemoryAgentRunnerOptions, InMemoryLimits, InMemoryThread, IntelligenceAgentRunner, IntelligenceAgentRunnerOptions, InterruptSignal, LearningContainerSelectorInput, ListThreadsResponse, LocalThreadEndpointRecord, LocalThreadEndpointRunner, MCPClient, MCPClientConfig, MCPClientConfigHTTP, MCPClientConfigSSE, MCPClientProvider, MCPTransport, McpAppsConfig, McpAppsServerConfig, MemoryAccess, MemoryConsumer, MemoryGrant, MessageConversionOptions, ModelSpecifier, OpenGenerativeUIConfig, OpenGenerativeUIOptions, OverridableProperty, ResponseHookContext, RouteInfo, RunnerStartupBoundary, RuntimeWithDeclaredChannels, SubscribeToThreadsRequest, SubscribeToThreadsResponse, TanStackChatMessage, TanStackInputResult, ThreadSummary, ToolDefinition, TranscribeFileOptions, TranscriptionService, UpdateThreadRequest, VERSION, convertAISDKStream, convertInputToTanStackAI, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertTanStackStream, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, createCopilotEndpoint, createCopilotExpressHandler as createCopilotEndpointExpress, createCopilotExpressHandler, createCopilotEndpointSingleRoute, createCopilotEndpointSingleRouteExpress, createCopilotHonoHandler, createCopilotRuntimeHandler, defineTool, finalizeRunEvents, isA2UIEnabled, isIntelligenceRuntime, resolveAgents, resolveModel, supportsLocalThreadEndpoints, toFetchCorsConfig, ɵBoundedThreadStore, ɵGLOBAL_STORE, ɵINMEMORY_DEFAULTS, ɵestimateBytes, ɵnormalizeLimits };
23
+ export { type AgentFactoryContext, AgentRunner, AgentRunnerConnectRequest, AgentRunnerIsRunningRequest, AgentRunnerRunRequest, AgentRunnerStopRequest, AgentsConfig, AgentsFactory, BasicAgent, BasicAgentConfiguration, BuiltInAgent, BuiltInAgentAISDKFactoryConfig, BuiltInAgentClassicConfig, BuiltInAgentConfiguration, BuiltInAgentCustomFactoryConfig, BuiltInAgentFactoryConfig, BuiltInAgentModel, BuiltInAgentTanStackFactoryConfig, ChannelStatus, ChannelsControl, CopilotCorsConfig, CopilotEndpointCorsConfig, CopilotExpressEndpointParams, CopilotExpressRouter, CopilotHonoApp, CopilotIntelligenceRuntime, CopilotIntelligenceRuntimeLike, CopilotIntelligenceRuntimeOptions, CopilotKitIntelligence, CopilotKitIntelligenceConfig, CopilotKitRequestHandler, CopilotRuntime, CopilotRuntimeConstructor, CopilotRuntimeFetchHandler, CopilotRuntimeFetchHandlerWithChannels, CopilotRuntimeHandlerOptions, CopilotRuntimeHooks, CopilotRuntimeLearningConfig, CopilotRuntimeLearningContext, CopilotRuntimeLike, CopilotRuntimeMemoryConfig, CopilotRuntimeOptions, CopilotRuntimeUser, CopilotSseRuntime, CopilotSseRuntimeLike, CopilotSseRuntimeOptions, CreateThreadRequest, ErrorHookContext, GetLearnedSkillsSnapshotRequest, GetLearningContainerId, HandlerHookContext, HookContext, IdentifyUserCallback, InMemoryAgentRunner, InMemoryAgentRunnerOptions, InMemoryLimits, InMemoryThread, IntelligenceAgentRunner, IntelligenceAgentRunnerOptions, InterruptSignal, LearnedSkillsError, LearnedSkillsErrorCode, LearnedSkillsSnapshotResult, LearningContainerSelectorInput, ListThreadsResponse, LocalThreadEndpointRecord, LocalThreadEndpointRunner, MCPClient, MCPClientConfig, MCPClientConfigHTTP, MCPClientConfigSSE, MCPClientProvider, MCPTransport, McpAppsConfig, McpAppsServerConfig, MemoryAccess, MemoryConsumer, MemoryGrant, MessageConversionOptions, ModelSpecifier, OpenGenerativeUIConfig, OpenGenerativeUIOptions, OverridableProperty, ResponseHookContext, RouteInfo, RunnerStartupBoundary, RuntimeWithDeclaredChannels, SubscribeToThreadsRequest, SubscribeToThreadsResponse, TanStackChatMessage, TanStackInputResult, ThreadSummary, ToolDefinition, TranscribeFileOptions, TranscriptionService, UpdateThreadRequest, VERSION, convertAISDKStream, convertInputToTanStackAI, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertTanStackStream, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, createCopilotEndpoint, createCopilotExpressHandler as createCopilotEndpointExpress, createCopilotExpressHandler, createCopilotEndpointSingleRoute, createCopilotEndpointSingleRouteExpress, createCopilotHonoHandler, createCopilotRuntimeHandler, defineTool, finalizeRunEvents, isA2UIEnabled, isIntelligenceRuntime, resolveAgents, resolveModel, supportsLocalThreadEndpoints, toFetchCorsConfig, ɵBoundedThreadStore, ɵGLOBAL_STORE, ɵINMEMORY_DEFAULTS, ɵestimateBytes, ɵnormalizeLimits };
@@ -2,6 +2,7 @@
2
2
  import { TranscribeFileOptions, TranscriptionService } from "./runtime/transcription-service/transcription-service.mjs";
3
3
  import { AgentRunner, AgentRunnerConnectRequest, AgentRunnerIsRunningRequest, AgentRunnerRunRequest, AgentRunnerStopRequest, LocalThreadEndpointRecord, LocalThreadEndpointRunner, supportsLocalThreadEndpoints } from "./runtime/runner/agent-runner.mjs";
4
4
  import { CopilotRuntimeLearningConfig, CopilotRuntimeLearningContext, CopilotRuntimeUser, GetLearningContainerId, LearningContainerSelectorInput } from "./runtime/core/learning.mjs";
5
+ import { GetLearnedSkillsSnapshotRequest, LearnedSkillsError, LearnedSkillsErrorCode, LearnedSkillsSnapshotResult } from "./runtime/intelligence-platform/learned-skills.mjs";
5
6
  import { CopilotKitIntelligence, CopilotKitIntelligenceConfig, CreateThreadRequest, ListThreadsResponse, SubscribeToThreadsRequest, SubscribeToThreadsResponse, ThreadSummary, UpdateThreadRequest } from "./runtime/intelligence-platform/client.mjs";
6
7
  import { AgentFactoryContext, AgentsConfig, AgentsFactory, CopilotIntelligenceRuntime, CopilotIntelligenceRuntimeLike, CopilotIntelligenceRuntimeOptions, CopilotRuntime, CopilotRuntimeConstructor, CopilotRuntimeLike, CopilotRuntimeMemoryConfig, CopilotRuntimeOptions, CopilotSseRuntime, CopilotSseRuntimeLike, CopilotSseRuntimeOptions, IdentifyUserCallback, McpAppsConfig, McpAppsServerConfig, MemoryAccess, MemoryConsumer, MemoryGrant, OpenGenerativeUIConfig, OpenGenerativeUIOptions, RuntimeWithDeclaredChannels, VERSION, isA2UIEnabled, isIntelligenceRuntime, resolveAgents } from "./runtime/core/runtime.mjs";
7
8
  import { CopilotCorsConfig } from "./runtime/core/fetch-cors.mjs";
@@ -19,4 +20,4 @@ import { CopilotKitRequestHandler, MCPClient, MCPTransport } from "./runtime/ind
19
20
  import { convertAISDKStream } from "../agent/converters/aisdk.mjs";
20
21
  import { TanStackChatMessage, TanStackInputResult, convertInputToTanStackAI, convertTanStackStream } from "../agent/converters/tanstack.mjs";
21
22
  import { BasicAgent, BasicAgentConfiguration, BuiltInAgent, BuiltInAgentAISDKFactoryConfig, BuiltInAgentClassicConfig, BuiltInAgentConfiguration, BuiltInAgentCustomFactoryConfig, BuiltInAgentFactoryConfig, BuiltInAgentModel, BuiltInAgentTanStackFactoryConfig, InterruptSignal, MCPClientConfig, MCPClientConfigHTTP, MCPClientConfigSSE, MCPClientProvider, MessageConversionOptions, ModelSpecifier, OverridableProperty, ToolDefinition, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, defineTool, resolveModel } from "../agent/index.mjs";
22
- export { type AgentFactoryContext, AgentRunner, AgentRunnerConnectRequest, AgentRunnerIsRunningRequest, AgentRunnerRunRequest, AgentRunnerStopRequest, AgentsConfig, AgentsFactory, BasicAgent, BasicAgentConfiguration, BuiltInAgent, BuiltInAgentAISDKFactoryConfig, BuiltInAgentClassicConfig, BuiltInAgentConfiguration, BuiltInAgentCustomFactoryConfig, BuiltInAgentFactoryConfig, BuiltInAgentModel, BuiltInAgentTanStackFactoryConfig, ChannelStatus, ChannelsControl, CopilotCorsConfig, CopilotEndpointCorsConfig, CopilotExpressEndpointParams, CopilotExpressRouter, CopilotHonoApp, CopilotIntelligenceRuntime, CopilotIntelligenceRuntimeLike, CopilotIntelligenceRuntimeOptions, CopilotKitIntelligence, CopilotKitIntelligenceConfig, CopilotKitRequestHandler, CopilotRuntime, CopilotRuntimeConstructor, CopilotRuntimeFetchHandler, CopilotRuntimeFetchHandlerWithChannels, CopilotRuntimeHandlerOptions, CopilotRuntimeHooks, CopilotRuntimeLearningConfig, CopilotRuntimeLearningContext, CopilotRuntimeLike, CopilotRuntimeMemoryConfig, CopilotRuntimeOptions, CopilotRuntimeUser, CopilotSseRuntime, CopilotSseRuntimeLike, CopilotSseRuntimeOptions, CreateThreadRequest, ErrorHookContext, GetLearningContainerId, HandlerHookContext, HookContext, IdentifyUserCallback, InMemoryAgentRunner, InMemoryAgentRunnerOptions, InMemoryLimits, InMemoryThread, IntelligenceAgentRunner, IntelligenceAgentRunnerOptions, InterruptSignal, LearningContainerSelectorInput, ListThreadsResponse, LocalThreadEndpointRecord, LocalThreadEndpointRunner, MCPClient, MCPClientConfig, MCPClientConfigHTTP, MCPClientConfigSSE, MCPClientProvider, MCPTransport, McpAppsConfig, McpAppsServerConfig, MemoryAccess, MemoryConsumer, MemoryGrant, MessageConversionOptions, ModelSpecifier, OpenGenerativeUIConfig, OpenGenerativeUIOptions, OverridableProperty, ResponseHookContext, RouteInfo, RunnerStartupBoundary, RuntimeWithDeclaredChannels, SubscribeToThreadsRequest, SubscribeToThreadsResponse, TanStackChatMessage, TanStackInputResult, ThreadSummary, ToolDefinition, TranscribeFileOptions, TranscriptionService, UpdateThreadRequest, VERSION, convertAISDKStream, convertInputToTanStackAI, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertTanStackStream, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, createCopilotEndpoint, createCopilotExpressHandler as createCopilotEndpointExpress, createCopilotExpressHandler, createCopilotEndpointSingleRoute, createCopilotEndpointSingleRouteExpress, createCopilotHonoHandler, createCopilotRuntimeHandler, defineTool, finalizeRunEvents, isA2UIEnabled, isIntelligenceRuntime, resolveAgents, resolveModel, supportsLocalThreadEndpoints, toFetchCorsConfig, ɵBoundedThreadStore, ɵGLOBAL_STORE, ɵINMEMORY_DEFAULTS, ɵestimateBytes, ɵnormalizeLimits };
23
+ export { type AgentFactoryContext, AgentRunner, AgentRunnerConnectRequest, AgentRunnerIsRunningRequest, AgentRunnerRunRequest, AgentRunnerStopRequest, AgentsConfig, AgentsFactory, BasicAgent, BasicAgentConfiguration, BuiltInAgent, BuiltInAgentAISDKFactoryConfig, BuiltInAgentClassicConfig, BuiltInAgentConfiguration, BuiltInAgentCustomFactoryConfig, BuiltInAgentFactoryConfig, BuiltInAgentModel, BuiltInAgentTanStackFactoryConfig, ChannelStatus, ChannelsControl, CopilotCorsConfig, CopilotEndpointCorsConfig, CopilotExpressEndpointParams, CopilotExpressRouter, CopilotHonoApp, CopilotIntelligenceRuntime, CopilotIntelligenceRuntimeLike, CopilotIntelligenceRuntimeOptions, CopilotKitIntelligence, CopilotKitIntelligenceConfig, CopilotKitRequestHandler, CopilotRuntime, CopilotRuntimeConstructor, CopilotRuntimeFetchHandler, CopilotRuntimeFetchHandlerWithChannels, CopilotRuntimeHandlerOptions, CopilotRuntimeHooks, CopilotRuntimeLearningConfig, CopilotRuntimeLearningContext, CopilotRuntimeLike, CopilotRuntimeMemoryConfig, CopilotRuntimeOptions, CopilotRuntimeUser, CopilotSseRuntime, CopilotSseRuntimeLike, CopilotSseRuntimeOptions, CreateThreadRequest, ErrorHookContext, GetLearnedSkillsSnapshotRequest, GetLearningContainerId, HandlerHookContext, HookContext, IdentifyUserCallback, InMemoryAgentRunner, InMemoryAgentRunnerOptions, InMemoryLimits, InMemoryThread, IntelligenceAgentRunner, IntelligenceAgentRunnerOptions, InterruptSignal, LearnedSkillsError, LearnedSkillsErrorCode, LearnedSkillsSnapshotResult, LearningContainerSelectorInput, ListThreadsResponse, LocalThreadEndpointRecord, LocalThreadEndpointRunner, MCPClient, MCPClientConfig, MCPClientConfigHTTP, MCPClientConfigSSE, MCPClientProvider, MCPTransport, McpAppsConfig, McpAppsServerConfig, MemoryAccess, MemoryConsumer, MemoryGrant, MessageConversionOptions, ModelSpecifier, OpenGenerativeUIConfig, OpenGenerativeUIOptions, OverridableProperty, ResponseHookContext, RouteInfo, RunnerStartupBoundary, RuntimeWithDeclaredChannels, SubscribeToThreadsRequest, SubscribeToThreadsResponse, TanStackChatMessage, TanStackInputResult, ThreadSummary, ToolDefinition, TranscribeFileOptions, TranscriptionService, UpdateThreadRequest, VERSION, convertAISDKStream, convertInputToTanStackAI, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertTanStackStream, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, createCopilotEndpoint, createCopilotExpressHandler as createCopilotEndpointExpress, createCopilotExpressHandler, createCopilotEndpointSingleRoute, createCopilotEndpointSingleRouteExpress, createCopilotHonoHandler, createCopilotRuntimeHandler, defineTool, finalizeRunEvents, isA2UIEnabled, isIntelligenceRuntime, resolveAgents, resolveModel, supportsLocalThreadEndpoints, toFetchCorsConfig, ɵBoundedThreadStore, ɵGLOBAL_STORE, ɵINMEMORY_DEFAULTS, ɵestimateBytes, ɵnormalizeLimits };
package/dist/v2/index.mjs CHANGED
@@ -3,6 +3,7 @@ import { AgentRunner, supportsLocalThreadEndpoints } from "./runtime/runner/agen
3
3
  import { InMemoryAgentRunner, ɵBoundedThreadStore, ɵGLOBAL_STORE, ɵINMEMORY_DEFAULTS, ɵestimateBytes, ɵnormalizeLimits } from "./runtime/runner/in-memory.mjs";
4
4
  import { IntelligenceAgentRunner } from "./runtime/runner/intelligence.mjs";
5
5
  import { CopilotIntelligenceRuntime, CopilotRuntime, CopilotSseRuntime, VERSION, isA2UIEnabled, isIntelligenceRuntime, resolveAgents } from "./runtime/core/runtime.mjs";
6
+ import { LearnedSkillsError } from "./runtime/intelligence-platform/learned-skills.mjs";
6
7
  import { CopilotKitIntelligence } from "./runtime/intelligence-platform/client.mjs";
7
8
  import { createCopilotRuntimeHandler } from "./runtime/core/fetch-handler.mjs";
8
9
  import { createCopilotEndpoint, createCopilotHonoHandler, toFetchCorsConfig } from "./runtime/endpoints/hono.mjs";
@@ -15,4 +16,4 @@ import { convertAISDKStream } from "../agent/converters/aisdk.mjs";
15
16
  import { convertInputToTanStackAI, convertTanStackStream } from "../agent/converters/tanstack.mjs";
16
17
  import { BasicAgent, BuiltInAgent, InterruptSignal, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, defineTool, resolveModel } from "../agent/index.mjs";
17
18
 
18
- export { AgentRunner, BasicAgent, BuiltInAgent, CopilotIntelligenceRuntime, CopilotKitIntelligence, CopilotRuntime, CopilotSseRuntime, InMemoryAgentRunner, IntelligenceAgentRunner, InterruptSignal, TranscriptionService, VERSION, convertAISDKStream, convertInputToTanStackAI, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertTanStackStream, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, createCopilotEndpoint, createCopilotExpressHandler as createCopilotEndpointExpress, createCopilotExpressHandler, createCopilotEndpointSingleRoute, createCopilotEndpointSingleRouteExpress, createCopilotHonoHandler, createCopilotRuntimeHandler, defineTool, finalizeRunEvents, isA2UIEnabled, isIntelligenceRuntime, resolveAgents, resolveModel, supportsLocalThreadEndpoints, toFetchCorsConfig, ɵBoundedThreadStore, ɵGLOBAL_STORE, ɵINMEMORY_DEFAULTS, ɵestimateBytes, ɵnormalizeLimits };
19
+ export { AgentRunner, BasicAgent, BuiltInAgent, CopilotIntelligenceRuntime, CopilotKitIntelligence, CopilotRuntime, CopilotSseRuntime, InMemoryAgentRunner, IntelligenceAgentRunner, InterruptSignal, LearnedSkillsError, TranscriptionService, VERSION, convertAISDKStream, convertInputToTanStackAI, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertTanStackStream, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, createCopilotEndpoint, createCopilotExpressHandler as createCopilotEndpointExpress, createCopilotExpressHandler, createCopilotEndpointSingleRoute, createCopilotEndpointSingleRouteExpress, createCopilotHonoHandler, createCopilotRuntimeHandler, defineTool, finalizeRunEvents, isA2UIEnabled, isIntelligenceRuntime, resolveAgents, resolveModel, supportsLocalThreadEndpoints, toFetchCorsConfig, ɵBoundedThreadStore, ɵGLOBAL_STORE, ɵINMEMORY_DEFAULTS, ɵestimateBytes, ɵnormalizeLimits };
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.cjs","names":["pkg","firstNonBlankLicenseToken","telemetry","DebugEventBus","resolveForwardHeadersPolicy","createLogger","InMemoryAgentRunner","RUNTIME_MODE_SSE","IntelligenceAgentRunner","RUNTIME_MODE_INTELLIGENCE","getRuntimeErrorReporterFromOptions"],"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 \"../../../v1-deprecated/lib/logger\";\nimport type { CopilotRuntimeLogger } from \"../../../v1-deprecated/lib/logger\";\nimport { logRuntimeTelemetryDisclosure } from \"../../../v1-deprecated/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 type { TelemetryCapture } from \"../telemetry/telemetry-client\";\nimport {\n firstNonBlankLicenseToken,\n firstNonBlankTelemetryId,\n} from \"../telemetry/telemetry-identity\";\nimport {\n attachRuntimeErrorReporter,\n getRuntimeErrorReporterFromOptions,\n} from \"./runtime-error-reporter\";\nimport type {\n CopilotRuntimeLearningConfig,\n CopilotRuntimeUser,\n} from \"./learning\";\nimport { assertStableLearningContainerId } from \"./learning\";\n\nexport type {\n CopilotRuntimeUser,\n CopilotRuntimeLearningConfig,\n CopilotRuntimeLearningContext,\n GetLearningContainerId,\n LearningContainerSelectorInput,\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 /** Standalone telemetry identity. Falls back to CPK_TELEMETRY_ID before legacy license identity. */\n telemetryId?: string;\n /**\n * Properties added to every telemetry event this runtime sends.\n *\n * For what is true of the whole process rather than of one event. A product\n * built on this runtime can name itself here and then be told apart in the\n * events that already go, rather than sending events of its own.\n *\n * No effect when telemetry is off: nothing is sent, so nothing carries this.\n */\n telemetryProperties?: Record<string, unknown>;\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 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 /**\n * Chooses one stable Learning Container ID for each web or Channel run.\n * @deprecated Configure `getLearningContainerId` on `CopilotKitIntelligence`.\n */\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 * Runtime-bound telemetry capture. Optional so external implementations of\n * this published interface remain source-compatible.\n */\n telemetry?: TelemetryCapture;\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 telemetry: TelemetryCapture;\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 = firstNonBlankLicenseToken(\n options.licenseToken,\n process.env.COPILOTKIT_LICENSE_TOKEN,\n );\n\n // Snapshot identity and sampling authority for this runtime. Capture\n // scopes share process-level telemetry settings but cannot be rewritten by\n // another runtime's construction.\n const resolvedTelemetryId = firstNonBlankTelemetryId(\n options.telemetryId,\n process.env.CPK_TELEMETRY_ID,\n );\n this.telemetry = telemetry.createScope(\n resolvedTelemetryId !== undefined\n ? { telemetryId: resolvedTelemetryId }\n : this.resolvedLicenseToken !== undefined\n ? { licenseToken: this.resolvedLicenseToken }\n : {},\n );\n\n // Set here rather than per event, beside the license token and for the same\n // reason: it describes the caller, not the call, and every event should\n // carry it whichever handler fired.\n if (options.telemetryProperties) {\n telemetry.setGlobalProperties(options.telemetryProperties);\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 runner?: unknown;\n ɵlearning?: unknown;\n };\n // Runtime guard mirroring the `channels` guard in `CopilotSseRuntime`: this\n // constructor hardcodes `IntelligenceAgentRunner` into its `super()` call,\n // so a caller-supplied `runner` can never be honored. The type forbids it\n // (`runner` is declared only on `CopilotSseRuntimeOptions`), but that is an\n // excess-property check — a JS / `as any` / non-literal caller passing\n // `{ intelligence, runner }` would otherwise land here and have `runner`\n // silently dropped in favor of the auto-wired one. Fail loud instead.\n if (rawOptions.runner !== undefined) {\n throw new Error(\n \"Intelligence Runtime auto-wires its own `runner`; passing `runner` \" +\n \"alongside `intelligence` is not supported. Durability is managed by \" +\n \"the Intelligence service, so `InMemoryAgentRunner` / a SQLite runner \" +\n \"is unnecessary here — drop `runner`, or drop `intelligence` to run \" +\n \"in SSE mode with a runner you control.\",\n );\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 rawOptions.ɵlearning !== undefined &&\n options.intelligence.ɵgetLearningContainerId?.() !== undefined\n ) {\n throw new Error(\n \"Configure Learning Containers with `getLearningContainerId` on `CopilotKitIntelligence`; do not also pass deprecated `ɵlearning` to `CopilotRuntime`\",\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 /** Telemetry capture bound to this runtime's construction-time identity. */\n telemetry: TelemetryCapture;\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: CopilotSseRuntime | CopilotIntelligenceRuntime;\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 telemetry(): TelemetryCapture {\n return this.delegate.telemetry;\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":";;;;;;;;;;;;;;;;;;AAgEA,MAAa,UAAUA,uBAAI;;;;;;AA0E3B,eAAsB,cACpB,QACA,SACwC;AACxC,KAAI,OAAO,WAAW,YAAY;AAChC,MAAI,CAAC,QACH,OAAM,IAAI,MACR,4EACD;AAEH,SAAO,OAAO,EAAE,SAAS,CAAC;;AAE5B,QAAO;;AAwNT,IAAe,qBAAf,MAAgE;CA6B9D,YAAY,SAAoC,QAAqB;AACnE,8DAA+B;EAE/B,MAAM,EACJ,QACA,sBACA,yBACA,wBACA,MACA,SACA,qBACE;AAEJ,OAAK,SAAS;AACd,OAAK,u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;;CAGN,IAAI,eAAiD;AACnD,SAAO,sBAAsB,KAAK,SAAS,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,YAA8B;AAChC,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.cjs","names":["pkg","firstNonBlankLicenseToken","telemetry","DebugEventBus","resolveForwardHeadersPolicy","createLogger","InMemoryAgentRunner","RUNTIME_MODE_SSE","IntelligenceAgentRunner","RUNTIME_MODE_INTELLIGENCE","getRuntimeErrorReporterFromOptions"],"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 \"../../../v1-deprecated/lib/logger\";\nimport type { CopilotRuntimeLogger } from \"../../../v1-deprecated/lib/logger\";\nimport { logRuntimeTelemetryDisclosure } from \"../../../v1-deprecated/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 type { TelemetryCapture } from \"../telemetry/telemetry-client\";\nimport {\n firstNonBlankLicenseToken,\n firstNonBlankTelemetryId,\n} from \"../telemetry/telemetry-identity\";\nimport {\n attachRuntimeErrorReporter,\n getRuntimeErrorReporterFromOptions,\n} from \"./runtime-error-reporter\";\nimport type {\n CopilotRuntimeLearningConfig,\n CopilotRuntimeUser,\n} from \"./learning\";\nimport { assertStableLearningContainerId } from \"./learning\";\n\nexport type {\n CopilotRuntimeUser,\n CopilotRuntimeLearningConfig,\n CopilotRuntimeLearningContext,\n GetLearningContainerId,\n LearningContainerSelectorInput,\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 /** Intelligence-only HTTP/SSE credentials from trusted server config, never iframe input. */\n headers?: Record<string, string>;\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 /** Standalone telemetry identity. Falls back to CPK_TELEMETRY_ID before legacy license identity. */\n telemetryId?: string;\n /**\n * Properties added to every telemetry event this runtime sends.\n *\n * For what is true of the whole process rather than of one event. A product\n * built on this runtime can name itself here and then be told apart in the\n * events that already go, rather than sending events of its own.\n *\n * No effect when telemetry is off: nothing is sent, so nothing carries this.\n */\n telemetryProperties?: Record<string, unknown>;\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 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 /**\n * Chooses one stable Learning Container ID for each web or Channel run.\n * @deprecated Configure `getLearningContainerId` on `CopilotKitIntelligence`.\n */\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 * Runtime-bound telemetry capture. Optional so external implementations of\n * this published interface remain source-compatible.\n */\n telemetry?: TelemetryCapture;\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 telemetry: TelemetryCapture;\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 = firstNonBlankLicenseToken(\n options.licenseToken,\n process.env.COPILOTKIT_LICENSE_TOKEN,\n );\n\n // Snapshot identity and sampling authority for this runtime. Capture\n // scopes share process-level telemetry settings but cannot be rewritten by\n // another runtime's construction.\n const resolvedTelemetryId = firstNonBlankTelemetryId(\n options.telemetryId,\n process.env.CPK_TELEMETRY_ID,\n );\n this.telemetry = telemetry.createScope(\n resolvedTelemetryId !== undefined\n ? { telemetryId: resolvedTelemetryId }\n : this.resolvedLicenseToken !== undefined\n ? { licenseToken: this.resolvedLicenseToken }\n : {},\n );\n\n // Set here rather than per event, beside the license token and for the same\n // reason: it describes the caller, not the call, and every event should\n // carry it whichever handler fired.\n if (options.telemetryProperties) {\n telemetry.setGlobalProperties(options.telemetryProperties);\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 runner?: unknown;\n ɵlearning?: unknown;\n };\n // Runtime guard mirroring the `channels` guard in `CopilotSseRuntime`: this\n // constructor hardcodes `IntelligenceAgentRunner` into its `super()` call,\n // so a caller-supplied `runner` can never be honored. The type forbids it\n // (`runner` is declared only on `CopilotSseRuntimeOptions`), but that is an\n // excess-property check — a JS / `as any` / non-literal caller passing\n // `{ intelligence, runner }` would otherwise land here and have `runner`\n // silently dropped in favor of the auto-wired one. Fail loud instead.\n if (rawOptions.runner !== undefined) {\n throw new Error(\n \"Intelligence Runtime auto-wires its own `runner`; passing `runner` \" +\n \"alongside `intelligence` is not supported. Durability is managed by \" +\n \"the Intelligence service, so `InMemoryAgentRunner` / a SQLite runner \" +\n \"is unnecessary here — drop `runner`, or drop `intelligence` to run \" +\n \"in SSE mode with a runner you control.\",\n );\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 rawOptions.ɵlearning !== undefined &&\n options.intelligence.ɵgetLearningContainerId?.() !== undefined\n ) {\n throw new Error(\n \"Configure Learning Containers with `getLearningContainerId` on `CopilotKitIntelligence`; do not also pass deprecated `ɵlearning` to `CopilotRuntime`\",\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 /** Telemetry capture bound to this runtime's construction-time identity. */\n telemetry: TelemetryCapture;\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: CopilotSseRuntime | CopilotIntelligenceRuntime;\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 telemetry(): TelemetryCapture {\n return this.delegate.telemetry;\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":";;;;;;;;;;;;;;;;;;AAgEA,MAAa,UAAUA,uBAAI;;;;;;AA4E3B,eAAsB,cACpB,QACA,SACwC;AACxC,KAAI,OAAO,WAAW,YAAY;AAChC,MAAI,CAAC,QACH,OAAM,IAAI,MACR,4EACD;A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IAAI,UAA4C;AAC9C,SAAO,KAAK,SAAS;;CAGvB,IAAI,mBAA8D;AAChE,SAAO,KAAK,SAAS;;CAGvB,IAAI,eAAmD;AACrD,SAAO,KAAK,SAAS;;CAGvB,IAAI,sBAA2C;AAC7C,SAAO,sBAAsB,KAAK,SAAS,GACvC,KAAK,SAAS,sBACd;;CAGN,IAAI,eAAiD;AACnD,SAAO,sBAAsB,KAAK,SAAS,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,YAA8B;AAChC,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"}
@@ -24,7 +24,8 @@ interface BaseCopilotRuntimeMiddlewareOptions {
24
24
  }
25
25
  /** Per-server tool policy belongs to the external middleware and is unsupported at its pinned 0.0.3 release. */
26
26
  type McpAppsServerConfig = MCPClientConfig & {
27
- /** Agent to bind this server to. If omitted, the server is available to all agents. */agentId?: string;
27
+ /** Intelligence-only HTTP/SSE credentials from trusted server config, never iframe input. */headers?: Record<string, string>; /** Agent to bind this server to. If omitted, the server is available to all agents. */
28
+ agentId?: string;
28
29
  };
29
30
  interface McpAppsConfig {
30
31
  /** List of MCP server configurations. */
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.d.cts","names":[],"sources":["../../../../src/v2/runtime/core/runtime.ts"],"mappings":";;;;;;;;;;;;;;;;;;;cAgEa,OAAA;AAAA,UAEH,mCAAA;;EAER,MAAA;AAAA;AAJiC;AAAA,KAQvB,mBAAA,GAAsB,eAAA;yFAEhC,OAAA;AAAA;AAAA,UAGe,aAAA;EALc;EAO7B,OAAA,EAAS,mBAAA;AAAA;AAAA,UAGM,uBAAA,SAAgC,mCAAA;AAAA,KAErC,sBAAA,aAAmC,uBAAA;AAAA,UAErC,yBAAA;EAPR;;AAGF;;EASE,IAAA,GAAO,mCAAA,GACL,oBAAA;IAVgF;;AAEpF;;;;IAeM,OAAA;EAAA;EAb6B;EAgBjC,OAAA,GAAU,aAAA;EAXH;EAaP,gBAAA,GAAmB,sBAAA;AAAA;;;;UAMJ,mBAAA;EAnBR;EAqBP,OAAA,EAAS,OAAA;AAAA;;;;;KAOC,aAAA,IACV,GAAA,EAAK,mBAAA,KACF,YAAA,CAAa,cAAA,CAAe,MAAA,SAAe,aAAA;;AAXhD;;;;;KAmBY,YAAA,GACR,YAAA,CAAa,cAAA,CAAe,MAAA,SAAe,aAAA,MAC3C,aAAA;;;;;;iBAOkB,aAAA,CACpB,MAAA,EAAQ,YAAA,EACR,OAAA,GAAU,OAAA,GACT,OAAA,CAAQ,MAAA,SAAe,aAAA;AAAA,UAYhB,yBAAA,SAAkC,yBAAA;EAhC3B;;;;;;;;;;AAQjB;;;;;;EAyCE,MAAA,EAAQ,YAAA;EAvCN;EAyCF,oBAAA,GAAuB,oB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OAAA;EAnXX;EAqXA,QAAA,GAAW,4BAAA;AAAA;;AAlXb;;;;;;;;;;;;;UAmYiB,yBAAA;EAAA,KAEb,OAAA,EAAS,qCAAA;IAGD,YAAA,EAAc,oBAAA;IACd,MAAA,GAAS,0BAAA;IACT,QAAA,EAAU,gBAAA;EAAA;IAGV,YAAA;IACA,MAAA;IACA,QAAA,EAAU,gBAAA;EAAA,KAGjB,cAAA,GAAiB,2BAAA;EAAA,KACf,OAAA,EAAS,qBAAA,GAAwB,cAAA;AAAA;;;;AAzYvC;;;;;;;;cAgiBY,cAAA,EAAgB,yBAAA"}
@@ -24,7 +24,8 @@ interface BaseCopilotRuntimeMiddlewareOptions {
24
24
  }
25
25
  /** Per-server tool policy belongs to the external middleware and is unsupported at its pinned 0.0.3 release. */
26
26
  type McpAppsServerConfig = MCPClientConfig & {
27
- /** Agent to bind this server to. If omitted, the server is available to all agents. */agentId?: string;
27
+ /** Intelligence-only HTTP/SSE credentials from trusted server config, never iframe input. */headers?: Record<string, string>; /** Agent to bind this server to. If omitted, the server is available to all agents. */
28
+ agentId?: string;
28
29
  };
29
30
  interface McpAppsConfig {
30
31
  /** List of MCP server configurations. */
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.d.mts","names":[],"sources":["../../../../src/v2/runtime/core/runtime.ts"],"mappings":";;;;;;;;;;;;;;;;;;;cAgEa,OAAA;AAAA,UAEH,mCAAA;;EAER,MAAA;AAAA;AAJiC;AAAA,KAQvB,mBAAA,GAAsB,eAAA;yFAEhC,OAAA;AAAA;AAAA,UAGe,aAAA;EALc;EAO7B,OAAA,EAAS,mBAAA;AAAA;AAAA,UAGM,uBAAA,SAAgC,mCAAA;AAAA,KAErC,sBAAA,aAAmC,uBAAA;AAAA,UAErC,yBAAA;EAPR;;AAGF;;EASE,IAAA,GAAO,mCAAA,GACL,oBAAA;IAVgF;;AAEpF;;;;IAeM,OAAA;EAAA;EAb6B;EAgBjC,OAAA,GAAU,aAAA;EAXH;EAaP,gBAAA,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