@copilotkit/runtime 1.72.1-canary.sp-longthread-perf → 1.73.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent/index.cjs +48 -8
- package/dist/agent/index.cjs.map +1 -1
- package/dist/agent/index.d.cts +20 -7
- package/dist/agent/index.d.cts.map +1 -1
- package/dist/agent/index.d.mts +18 -5
- package/dist/agent/index.d.mts.map +1 -1
- package/dist/agent/index.mjs +48 -8
- package/dist/agent/index.mjs.map +1 -1
- package/dist/agent/learned-skills.cjs +77 -0
- package/dist/agent/learned-skills.cjs.map +1 -0
- package/dist/agent/learned-skills.d.cts +16 -0
- package/dist/agent/learned-skills.d.cts.map +1 -0
- package/dist/agent/learned-skills.d.mts +16 -0
- package/dist/agent/learned-skills.d.mts.map +1 -0
- package/dist/agent/learned-skills.mjs +75 -0
- package/dist/agent/learned-skills.mjs.map +1 -0
- package/dist/index.d.cts +4 -4
- package/dist/index.d.mts +4 -4
- package/dist/internal/learned-skills.cjs +22 -0
- package/dist/internal/learned-skills.d.cts +10 -0
- package/dist/internal/learned-skills.d.mts +10 -0
- package/dist/internal/learned-skills.mjs +10 -0
- package/dist/lib/index.d.cts +2 -2
- package/dist/lib/index.d.mts +2 -2
- package/dist/lib/integrations/node-http/index.cjs.map +1 -1
- package/dist/lib/integrations/node-http/index.d.cts.map +1 -1
- package/dist/lib/integrations/node-http/index.d.mts.map +1 -1
- package/dist/lib/integrations/node-http/index.mjs.map +1 -1
- package/dist/lib/integrations/shared.cjs.map +1 -1
- package/dist/lib/integrations/shared.d.cts +1 -1
- package/dist/lib/integrations/shared.d.cts.map +1 -1
- package/dist/lib/integrations/shared.d.mts +1 -1
- package/dist/lib/integrations/shared.d.mts.map +1 -1
- package/dist/lib/integrations/shared.mjs.map +1 -1
- package/dist/lib/runtime/agent-integrations/langgraph/agent.d.cts +1 -1
- package/dist/lib/runtime/copilot-runtime.d.cts +2 -2
- package/dist/lib/runtime/copilot-runtime.d.mts +2 -2
- package/dist/package.cjs +9 -3
- package/dist/package.mjs +9 -3
- package/dist/service-adapters/anthropic/anthropic-adapter.cjs.map +1 -1
- package/dist/service-adapters/anthropic/anthropic-adapter.d.cts.map +1 -1
- package/dist/service-adapters/anthropic/anthropic-adapter.d.mts.map +1 -1
- package/dist/service-adapters/anthropic/anthropic-adapter.mjs.map +1 -1
- package/dist/service-adapters/shared/sdk-client-utils.cjs.map +1 -1
- package/dist/service-adapters/shared/sdk-client-utils.d.cts.map +1 -1
- package/dist/service-adapters/shared/sdk-client-utils.d.mts.map +1 -1
- package/dist/service-adapters/shared/sdk-client-utils.mjs.map +1 -1
- package/dist/v2/index.cjs +6 -0
- package/dist/v2/index.d.cts +6 -5
- package/dist/v2/index.d.mts +6 -5
- package/dist/v2/index.mjs +2 -2
- package/dist/v2/runtime/core/channel-manager.d.cts +1 -1
- package/dist/v2/runtime/core/channel-manager.d.mts +1 -1
- package/dist/v2/runtime/core/runtime.cjs +5 -0
- package/dist/v2/runtime/core/runtime.cjs.map +1 -1
- package/dist/v2/runtime/core/runtime.d.cts +18 -3
- package/dist/v2/runtime/core/runtime.d.cts.map +1 -1
- package/dist/v2/runtime/core/runtime.d.mts +17 -2
- package/dist/v2/runtime/core/runtime.d.mts.map +1 -1
- package/dist/v2/runtime/core/runtime.mjs +5 -0
- package/dist/v2/runtime/core/runtime.mjs.map +1 -1
- package/dist/v2/runtime/handlers/handle-suggest.cjs +4 -3
- package/dist/v2/runtime/handlers/handle-suggest.cjs.map +1 -1
- package/dist/v2/runtime/handlers/handle-suggest.mjs +5 -4
- package/dist/v2/runtime/handlers/handle-suggest.mjs.map +1 -1
- package/dist/v2/runtime/handlers/shared/sse-keep-alive.cjs +69 -0
- package/dist/v2/runtime/handlers/shared/sse-keep-alive.cjs.map +1 -0
- package/dist/v2/runtime/handlers/shared/sse-keep-alive.mjs +67 -0
- package/dist/v2/runtime/handlers/shared/sse-keep-alive.mjs.map +1 -0
- package/dist/v2/runtime/handlers/shared/sse-response.cjs +5 -2
- package/dist/v2/runtime/handlers/shared/sse-response.cjs.map +1 -1
- package/dist/v2/runtime/handlers/shared/sse-response.mjs +5 -2
- package/dist/v2/runtime/handlers/shared/sse-response.mjs.map +1 -1
- package/dist/v2/runtime/handlers/sse/connect.cjs +1 -0
- package/dist/v2/runtime/handlers/sse/connect.cjs.map +1 -1
- package/dist/v2/runtime/handlers/sse/connect.mjs +1 -0
- package/dist/v2/runtime/handlers/sse/connect.mjs.map +1 -1
- package/dist/v2/runtime/handlers/sse/run.cjs +1 -0
- package/dist/v2/runtime/handlers/sse/run.cjs.map +1 -1
- package/dist/v2/runtime/handlers/sse/run.mjs +1 -0
- package/dist/v2/runtime/handlers/sse/run.mjs.map +1 -1
- package/dist/v2/runtime/index.d.cts +3 -3
- package/dist/v2/runtime/index.d.mts +3 -3
- package/dist/v2/runtime/intelligence-platform/client.d.cts +1 -1
- package/dist/v2/runtime/intelligence-platform/client.d.mts +1 -1
- package/dist/v2/runtime/intelligence-platform/skill-registry/archive.cjs +132 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/archive.cjs.map +1 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/archive.d.cts +11 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/archive.d.cts.map +1 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/archive.d.mts +11 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/archive.d.mts.map +1 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/archive.mjs +128 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/archive.mjs.map +1 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/config.cjs +48 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/config.cjs.map +1 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/config.d.cts +27 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/config.d.cts.map +1 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/config.d.mts +27 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/config.d.mts.map +1 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/config.mjs +48 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/config.mjs.map +1 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/errors.cjs +11 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/errors.cjs.map +1 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/errors.d.cts +8 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/errors.d.cts.map +1 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/errors.d.mts +8 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/errors.d.mts.map +1 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/errors.mjs +11 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/errors.mjs.map +1 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/index.d.cts +8 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/index.d.mts +8 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/registry.cjs +132 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/registry.cjs.map +1 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/registry.d.cts +31 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/registry.d.cts.map +1 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/registry.d.mts +31 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/registry.d.mts.map +1 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/registry.mjs +132 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/registry.mjs.map +1 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/skill-content.cjs +42 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/skill-content.cjs.map +1 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/skill-content.d.cts +13 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/skill-content.d.cts.map +1 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/skill-content.d.mts +13 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/skill-content.d.mts.map +1 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/skill-content.mjs +39 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/skill-content.mjs.map +1 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/snapshot.cjs +93 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/snapshot.cjs.map +1 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/snapshot.d.cts +28 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/snapshot.d.cts.map +1 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/snapshot.d.mts +28 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/snapshot.d.mts.map +1 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/snapshot.mjs +92 -0
- package/dist/v2/runtime/intelligence-platform/skill-registry/snapshot.mjs.map +1 -0
- package/dist/v2/runtime/runner/agent-runner.d.cts +1 -1
- package/dist/v2/runtime/runner/in-memory.d.cts +1 -1
- package/dist/v2/runtime/runner/index.d.cts +2 -2
- package/dist/v2/runtime/runner/index.d.mts +2 -2
- package/dist/v2/runtime/runner/index.mjs +2 -2
- package/dist/v2/runtime/runner/intelligence.d.cts +1 -1
- package/package.json +9 -3
package/dist/package.cjs
CHANGED
|
@@ -5,7 +5,7 @@ const require_runtime = require('./_virtual/_rolldown/runtime.cjs');
|
|
|
5
5
|
var require_package = /* @__PURE__ */ require_runtime.__commonJSMin(((exports, module) => {
|
|
6
6
|
module.exports = {
|
|
7
7
|
"name": "@copilotkit/runtime",
|
|
8
|
-
"version": "1.
|
|
8
|
+
"version": "1.73.0",
|
|
9
9
|
"private": false,
|
|
10
10
|
"keywords": [
|
|
11
11
|
"ai",
|
|
@@ -41,6 +41,10 @@ var require_package = /* @__PURE__ */ require_runtime.__commonJSMin(((exports, m
|
|
|
41
41
|
"import": "./dist/index.mjs",
|
|
42
42
|
"require": "./dist/index.cjs"
|
|
43
43
|
},
|
|
44
|
+
"./internal/learned-skills": {
|
|
45
|
+
"import": "./dist/internal/learned-skills.mjs",
|
|
46
|
+
"require": "./dist/internal/learned-skills.cjs"
|
|
47
|
+
},
|
|
44
48
|
"./langgraph": {
|
|
45
49
|
"import": "./dist/langgraph.mjs",
|
|
46
50
|
"require": "./dist/langgraph.cjs"
|
|
@@ -123,7 +127,8 @@ var require_package = /* @__PURE__ */ require_runtime.__commonJSMin(((exports, m
|
|
|
123
127
|
"type-graphql": "2.0.0-rc.1",
|
|
124
128
|
"uuid": "^11.1.0",
|
|
125
129
|
"ws": "^8.18.0",
|
|
126
|
-
"zod": "^3.23.3"
|
|
130
|
+
"zod": "^3.23.3",
|
|
131
|
+
"yauzl": "2.10.0"
|
|
127
132
|
},
|
|
128
133
|
"devDependencies": {
|
|
129
134
|
"@copilotkit/aimock": "latest",
|
|
@@ -145,7 +150,8 @@ var require_package = /* @__PURE__ */ require_runtime.__commonJSMin(((exports, m
|
|
|
145
150
|
"tsdown": "^0.20.3",
|
|
146
151
|
"typescript": "^5.2.3",
|
|
147
152
|
"valibot": "^1.2.0",
|
|
148
|
-
"vitest": "^3.2.4"
|
|
153
|
+
"vitest": "^3.2.4",
|
|
154
|
+
"@types/yauzl": "2.10.3"
|
|
149
155
|
},
|
|
150
156
|
"peerDependencies": {
|
|
151
157
|
"@anthropic-ai/sdk": ">=0.57.0",
|
package/dist/package.mjs
CHANGED
|
@@ -5,7 +5,7 @@ import { __commonJSMin } from "./_virtual/_rolldown/runtime.mjs";
|
|
|
5
5
|
var require_package = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
6
6
|
module.exports = {
|
|
7
7
|
"name": "@copilotkit/runtime",
|
|
8
|
-
"version": "1.
|
|
8
|
+
"version": "1.73.0",
|
|
9
9
|
"private": false,
|
|
10
10
|
"keywords": [
|
|
11
11
|
"ai",
|
|
@@ -41,6 +41,10 @@ var require_package = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
41
41
|
"import": "./dist/index.mjs",
|
|
42
42
|
"require": "./dist/index.cjs"
|
|
43
43
|
},
|
|
44
|
+
"./internal/learned-skills": {
|
|
45
|
+
"import": "./dist/internal/learned-skills.mjs",
|
|
46
|
+
"require": "./dist/internal/learned-skills.cjs"
|
|
47
|
+
},
|
|
44
48
|
"./langgraph": {
|
|
45
49
|
"import": "./dist/langgraph.mjs",
|
|
46
50
|
"require": "./dist/langgraph.cjs"
|
|
@@ -123,7 +127,8 @@ var require_package = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
123
127
|
"type-graphql": "2.0.0-rc.1",
|
|
124
128
|
"uuid": "^11.1.0",
|
|
125
129
|
"ws": "^8.18.0",
|
|
126
|
-
"zod": "^3.23.3"
|
|
130
|
+
"zod": "^3.23.3",
|
|
131
|
+
"yauzl": "2.10.0"
|
|
127
132
|
},
|
|
128
133
|
"devDependencies": {
|
|
129
134
|
"@copilotkit/aimock": "latest",
|
|
@@ -145,7 +150,8 @@ var require_package = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
145
150
|
"tsdown": "^0.20.3",
|
|
146
151
|
"typescript": "^5.2.3",
|
|
147
152
|
"valibot": "^1.2.0",
|
|
148
|
-
"vitest": "^3.2.4"
|
|
153
|
+
"vitest": "^3.2.4",
|
|
154
|
+
"@types/yauzl": "2.10.3"
|
|
149
155
|
},
|
|
150
156
|
"peerDependencies": {
|
|
151
157
|
"@anthropic-ai/sdk": ">=0.57.0",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"anthropic-adapter.cjs","names":["getSdkClientOptions","convertActionInputToAnthropicTool","limitMessagesToTokenCount","coalesceConsecutiveSameRoleMessages","convertMessageToAnthropicMessage","convertServiceAdapterError"],"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,QAAQ,iBAAiB,EAAE,SAAS,OAAO;AAChE,OAAK,iBAAiB,QAAQ;;CAGhC,mBAAkC;EAChC,MAAM,YAAY,KAAK,iBAAiB;EACxC,MAAM,UA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AAY,gCAEvB,mBAAkB,WAAW;;AAIjC,0DAA6B;AAC7B,kBAAa,qBAAqB,EAAE,WAAW,kBAAkB,CAAC;AAClE,kBAAa,uBAAuB;MAClC,WAAW;MACX,SAAS;MACV,CAAC;AACF,kBAAa,mBAAmB,EAAE,WAAW,kBAAkB,CAAC;;AAGlE,iBAAa,UAAU;KACvB;WACK,OAAO;AACd,SAAMA,+CAA2B,OAAO,YAAY;;AAGtD,SAAO,EACL,UAAU,gDAAwB,EACnC;;;AAIL,MAAM,eAAe;AACrB,MAAM,mBAAmB;;;;;;;;;;;;;AAczB,IAAa,2BAAb,MAAsC;;gBACX;kBAKG;;CAE5B,YAAY,MAAsB;AAChC,MAAI,KAAK,SACP,QAAO;AAET,OAAK,UAAU;AAEf,MAAI,KAAK,OAAO,SAAS,IAAqB;AAC5C,OAAI,aAAa,WAAW,KAAK,OAAO,CAEtC,QAAO;AAET,UAAO,KAAK,SAAS;;AAGvB,MAAI,CAAC,KAAK,OAAO,WAAW,aAAa,CAGvC,QAAO,KAAK,SAAS;EAGvB,MAAM,MAAM,KAAK,OAAO,QAAQ,iBAAiB;AACjD,MAAI,QAAQ,GAEV,QAAO;EAET,MAAM,OAAO,KAAK,OAAO,MAAM,MAAM,GAAwB;AAC7D,OAAK,SAAS;AACd,OAAK,WAAW;AAChB,SAAO;;;;;;;CAQT,QAAgB;AACd,MAAI,KAAK,SACP,QAAO;EAET,MAAM,UACJ,KAAK,OAAO,SAAS,MACrB,aAAa,WAAW,KAAK,OAAO,GAChC,KAAK,SACL;AACN,OAAK,SAAS;AACd,OAAK,WAAW;AAChB,SAAO;;CAGT,QAAQ;AACN,OAAK,SAAS;AACd,OAAK,WAAW;;CAGlB,AAAQ,UAAkB;EACxB,MAAM,UAAU,KAAK;AACrB,OAAK,SAAS;AACd,OAAK,WAAW;AAChB,SAAO"}
|
|
1
|
+
{"version":3,"file":"anthropic-adapter.cjs","names":["getSdkClientOptions","convertActionInputToAnthropicTool","limitMessagesToTokenCount","coalesceConsecutiveSameRoleMessages","convertMessageToAnthropicMessage","convertServiceAdapterError"],"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 * @copilotkit/runtime — FilterThinkingTextBuffer:\n * No 1:1 v2 replacement is available.\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":";;;;;;;;;AAkFA,MAAM,gBAAgB;AAuCtB,IAAa,mBAAb,MAA+D;CAO7D,IAA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S,MACrB,aAAa,WAAW,KAAK,OAAO,GAChC,KAAK,SACL;AACN,OAAK,SAAS;AACd,OAAK,WAAW;AAChB,SAAO;;CAGT,QAAQ;AACN,OAAK,SAAS;AACd,OAAK,WAAW;;CAGlB,AAAQ,UAAkB;EACxB,MAAM,UAAU,KAAK;AACrB,OAAK,SAAS;AACd,OAAK,WAAW;AAChB,SAAO"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"anthropic-adapter.d.cts","names":[],"sources":["../../../../src/v1-deprecated/service-adapters/anthropic/anthropic-adapter.ts"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"anthropic-adapter.d.cts","names":[],"sources":["../../../../src/v1-deprecated/service-adapters/anthropic/anthropic-adapter.ts"],"mappings":";;;;;;UAoFiB,4BAAA;EAwMJ;;;EApMX,OAAA;EAiC4D;;;EA5B5D,KAAA;AAAA;AAAA,UAGe,sBAAA;EA6BP;;;;EAxBR,SAAA,GAAY,aAAA;;;;EAKZ,KAAA;EAyCoB;;;;EAnCpB,aAAA,GAAgB,4BAAA;EA2KV;;;;EArKN,cAAA;AAAA;AAAA,cAGW,gBAAA,YAA4B,qBAAA;EAChC,KAAA;EACA,QAAA;EAAA,QACC,aAAA;EAAA,QACA,cAAA;EAAA,QAEA,UAAA;EAAA,IACG,SAAA,CAAA,GAAa,aAAA;EAAA,IAGb,IAAA,CAAA;cAIC,MAAA,GAAS,sBAAA;EAYrB,gBAAA,CAAA,GAAoB,aAAA;EAAA,QAYZ,eAAA;EAwdA;;;EAAA,QA5cA,sBAAA;;;;UAkCA,4BAAA;EAAA,QAwCA,8BAAA;EAsCF,OAAA,CACJ,OAAA,EAAS,mCAAA,GACR,OAAA,CAAQ,oCAAA;AAAA;;;;;;;;;;;;;cA2RA,wBAAA;EAAA,QACH,MAAA;;;;;UAKA,QAAA;EAER,WAAA,CAAY,IAAA;;;;;;EAoCZ,KAAA,CAAA;EAcA,KAAA,CAAA;EAAA,QAKQ,OAAA;AAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"anthropic-adapter.d.mts","names":[],"sources":["../../../../src/v1-deprecated/service-adapters/anthropic/anthropic-adapter.ts"],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"anthropic-adapter.d.mts","names":[],"sources":["../../../../src/v1-deprecated/service-adapters/anthropic/anthropic-adapter.ts"],"mappings":";;;;;;;UAoFiB,4BAAA;EA+DK;;;EA3DpB,OAAA;EAiCuC;;;EA5BvC,KAAA;AAAA;AAAA,UAGe,sBAAA;EA4BP;;;;EAvBR,SAAA,GAAY,aAAA;EA8BD;;;EAzBX,KAAA;EAyCA;;;;EAnCA,aAAA,GAAgB,4BAAA;EAqIR;;;;EA/HR,cAAA;AAAA;AAAA,cAGW,gBAAA,YAA4B,qBAAA;EAChC,KAAA;EACA,QAAA;EAAA,QACC,aAAA;EAAA,QACA,cAAA;EAAA,QAEA,UAAA;EAAA,IACG,SAAA,CAAA,GAAa,aAAA;EAAA,IAGb,IAAA,CAAA;cAIC,MAAA,GAAS,sBAAA;EAYrB,gBAAA,CAAA,GAAoB,aAAA;EAAA,QAYZ,eAAA;EAmdR;;;EAAA,QAvcQ,sBAAA;;;;UAkCA,4BAAA;EAAA,QAwCA,8BAAA;EAsCF,OAAA,CACJ,OAAA,EAAS,mCAAA,GACR,OAAA,CAAQ,oCAAA;AAAA;;;;;;;;;;;;;cA2RA,wBAAA;EAAA,QACH,MAAA;;;;;UAKA,QAAA;EAER,WAAA,CAAY,IAAA;;;;;;EAoCZ,KAAA,CAAA;EAcA,KAAA,CAAA;EAAA,QAKQ,OAAA;AAAA"}
|
|
@@ -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 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,QAAQ,iBAAiB,EAAE,SAAS,OAAO;AAChE,OAAK,iBAAiB,QAAQ;;CAGhC,mBAAkC;EAChC,MAAM,YAAY,KAAK,iBAAiB;EACxC,MAAM,UAAU,oBAAoB,UAAU;AAO9C,SANiB,g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W;;AAIjC,wBAAmB,UAAU;AAC7B,kBAAa,qBAAqB,EAAE,WAAW,kBAAkB,CAAC;AAClE,kBAAa,uBAAuB;MAClC,WAAW;MACX,SAAS;MACV,CAAC;AACF,kBAAa,mBAAmB,EAAE,WAAW,kBAAkB,CAAC;;AAGlE,iBAAa,UAAU;KACvB;WACK,OAAO;AACd,SAAM,2BAA2B,OAAO,YAAY;;AAGtD,SAAO,EACL,UAAU,YAAY,YAAY,EACnC;;;AAIL,MAAM,eAAe;AACrB,MAAM,mBAAmB;;;;;;;;;;;;;AAczB,IAAa,2BAAb,MAAsC;;gBACX;kBAKG;;CAE5B,YAAY,MAAsB;AAChC,MAAI,KAAK,SACP,QAAO;AAET,OAAK,UAAU;AAEf,MAAI,KAAK,OAAO,SAAS,IAAqB;AAC5C,OAAI,aAAa,WAAW,KAAK,OAAO,CAEtC,QAAO;AAET,UAAO,KAAK,SAAS;;AAGvB,MAAI,CAAC,KAAK,OAAO,WAAW,aAAa,CAGvC,QAAO,KAAK,SAAS;EAGvB,MAAM,MAAM,KAAK,OAAO,QAAQ,iBAAiB;AACjD,MAAI,QAAQ,GAEV,QAAO;EAET,MAAM,OAAO,KAAK,OAAO,MAAM,MAAM,GAAwB;AAC7D,OAAK,SAAS;AACd,OAAK,WAAW;AAChB,SAAO;;;;;;;CAQT,QAAgB;AACd,MAAI,KAAK,SACP,QAAO;EAET,MAAM,UACJ,KAAK,OAAO,SAAS,MACrB,aAAa,WAAW,KAAK,OAAO,GAChC,KAAK,SACL;AACN,OAAK,SAAS;AACd,OAAK,WAAW;AAChB,SAAO;;CAGT,QAAQ;AACN,OAAK,SAAS;AACd,OAAK,WAAW;;CAGlB,AAAQ,UAAkB;EACxB,MAAM,UAAU,KAAK;AACrB,OAAK,SAAS;AACd,OAAK,WAAW;AAChB,SAAO"}
|
|
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 * @copilotkit/runtime — FilterThinkingTextBuffer:\n * No 1:1 v2 replacement is available.\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":";;;;;;;;;AAkFA,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,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,QAAQ;AACN,OAAK,SAAS;AACd,OAAK,WAAW;;CAGlB,AAAQ,UAAkB;EACxB,MAAM,UAAU,KAAK;AACrB,OAAK,SAAS;AACd,OAAK,WAAW;AAChB,SAAO"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sdk-client-utils.cjs","names":[],"sources":["../../../../src/v1-deprecated/service-adapters/shared/sdk-client-utils.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 — getSdkClientOptions:\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 * The part of a vendor SDK client these adapters actually use.\n *\n * `@anthropic-ai/sdk` and `groq-sdk` are *optional* peer dependencies, so a\n * consumer who never touches those adapters does not install them. Naming their\n * types in a published signature makes the declaration unresolvable for everyone\n * else -- a TS2307 on a bare `import { CopilotRuntime }` under\n * `skipLibCheck: false` (OSS-899).\n *\n * A real `Anthropic` or `Groq` instance satisfies this, so passing one still\n * type-checks. The adapters read nothing beyond these two fields; everything\n * else goes through `getSdkClientOptions`, which takes an `object`.\n */\nexport interface SdkClientLike {\n /** Base URL the client was configured with. */\n baseURL: string;\n /** API key the client was configured with. */\n apiKey: string | null;\n}\n\n/**\n * SDK clients (OpenAI, Anthropic, Groq) store constructor options like\n * `defaultHeaders` and `fetch` in a private/protected `_options` field\n * with no public accessor. This extracts them with a narrow type assertion.\n */\nexport function getSdkClientOptions(client: object): {\n defaultHeaders?: Record<string, string>;\n fetch?: typeof globalThis.fetch;\n} {\n const rec = client as Record<string, unknown>;\n const options = rec._options;\n if (options != null && typeof options === \"object\") {\n return options as {\n defaultHeaders?: Record<string, string>;\n fetch?: typeof globalThis.fetch;\n };\n }\n return {};\n}\n"],"mappings":";;;;;;;;
|
|
1
|
+
{"version":3,"file":"sdk-client-utils.cjs","names":[],"sources":["../../../../src/v1-deprecated/service-adapters/shared/sdk-client-utils.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 — getSdkClientOptions:\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 — SdkClientLike:\n * No 1:1 v2 replacement is available.\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 * The part of a vendor SDK client these adapters actually use.\n *\n * `@anthropic-ai/sdk` and `groq-sdk` are *optional* peer dependencies, so a\n * consumer who never touches those adapters does not install them. Naming their\n * types in a published signature makes the declaration unresolvable for everyone\n * else -- a TS2307 on a bare `import { CopilotRuntime }` under\n * `skipLibCheck: false` (OSS-899).\n *\n * A real `Anthropic` or `Groq` instance satisfies this, so passing one still\n * type-checks. The adapters read nothing beyond these two fields; everything\n * else goes through `getSdkClientOptions`, which takes an `object`.\n */\nexport interface SdkClientLike {\n /** Base URL the client was configured with. */\n baseURL: string;\n /** API key the client was configured with. */\n apiKey: string | null;\n}\n\n/**\n * SDK clients (OpenAI, Anthropic, Groq) store constructor options like\n * `defaultHeaders` and `fetch` in a private/protected `_options` field\n * with no public accessor. This extracts them with a narrow type assertion.\n */\nexport function getSdkClientOptions(client: object): {\n defaultHeaders?: Record<string, string>;\n fetch?: typeof globalThis.fetch;\n} {\n const rec = client as Record<string, unknown>;\n const options = rec._options;\n if (options != null && typeof options === \"object\") {\n return options as {\n defaultHeaders?: Record<string, string>;\n fetch?: typeof globalThis.fetch;\n };\n }\n return {};\n}\n"],"mappings":";;;;;;;;AAkDA,SAAgB,oBAAoB,QAGlC;CAEA,MAAM,UADM,OACQ;AACpB,KAAI,WAAW,QAAQ,OAAO,YAAY,SACxC,QAAO;AAKT,QAAO,EAAE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sdk-client-utils.d.cts","names":[],"sources":["../../../../src/v1-deprecated/service-adapters/shared/sdk-client-utils.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"sdk-client-utils.d.cts","names":[],"sources":["../../../../src/v1-deprecated/service-adapters/shared/sdk-client-utils.ts"],"mappings":";;;AAsCA;;;;;AAYA;;;;;;;UAZiB,aAAA;EAcA;EAZf,OAAA;EAY+B;EAV/B,MAAA;AAAA;;;;;;iBAQc,mBAAA,CAAoB,MAAA;EAClC,cAAA,GAAiB,MAAA;EACjB,KAAA,UAAe,UAAA,CAAW,KAAA;AAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sdk-client-utils.d.mts","names":[],"sources":["../../../../src/v1-deprecated/service-adapters/shared/sdk-client-utils.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"sdk-client-utils.d.mts","names":[],"sources":["../../../../src/v1-deprecated/service-adapters/shared/sdk-client-utils.ts"],"mappings":";;;AAsCA;;;;;AAYA;;;;;;;UAZiB,aAAA;EAcA;EAZf,OAAA;EAY+B;EAV/B,MAAA;AAAA;;;;;;iBAQc,mBAAA,CAAoB,MAAA;EAClC,cAAA,GAAiB,MAAA;EACjB,KAAA,UAAe,UAAA,CAAW,KAAA;AAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sdk-client-utils.mjs","names":[],"sources":["../../../../src/v1-deprecated/service-adapters/shared/sdk-client-utils.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 — getSdkClientOptions:\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 * The part of a vendor SDK client these adapters actually use.\n *\n * `@anthropic-ai/sdk` and `groq-sdk` are *optional* peer dependencies, so a\n * consumer who never touches those adapters does not install them. Naming their\n * types in a published signature makes the declaration unresolvable for everyone\n * else -- a TS2307 on a bare `import { CopilotRuntime }` under\n * `skipLibCheck: false` (OSS-899).\n *\n * A real `Anthropic` or `Groq` instance satisfies this, so passing one still\n * type-checks. The adapters read nothing beyond these two fields; everything\n * else goes through `getSdkClientOptions`, which takes an `object`.\n */\nexport interface SdkClientLike {\n /** Base URL the client was configured with. */\n baseURL: string;\n /** API key the client was configured with. */\n apiKey: string | null;\n}\n\n/**\n * SDK clients (OpenAI, Anthropic, Groq) store constructor options like\n * `defaultHeaders` and `fetch` in a private/protected `_options` field\n * with no public accessor. This extracts them with a narrow type assertion.\n */\nexport function getSdkClientOptions(client: object): {\n defaultHeaders?: Record<string, string>;\n fetch?: typeof globalThis.fetch;\n} {\n const rec = client as Record<string, unknown>;\n const options = rec._options;\n if (options != null && typeof options === \"object\") {\n return options as {\n defaultHeaders?: Record<string, string>;\n fetch?: typeof globalThis.fetch;\n };\n }\n return {};\n}\n"],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"sdk-client-utils.mjs","names":[],"sources":["../../../../src/v1-deprecated/service-adapters/shared/sdk-client-utils.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 — getSdkClientOptions:\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 — SdkClientLike:\n * No 1:1 v2 replacement is available.\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 * The part of a vendor SDK client these adapters actually use.\n *\n * `@anthropic-ai/sdk` and `groq-sdk` are *optional* peer dependencies, so a\n * consumer who never touches those adapters does not install them. Naming their\n * types in a published signature makes the declaration unresolvable for everyone\n * else -- a TS2307 on a bare `import { CopilotRuntime }` under\n * `skipLibCheck: false` (OSS-899).\n *\n * A real `Anthropic` or `Groq` instance satisfies this, so passing one still\n * type-checks. The adapters read nothing beyond these two fields; everything\n * else goes through `getSdkClientOptions`, which takes an `object`.\n */\nexport interface SdkClientLike {\n /** Base URL the client was configured with. */\n baseURL: string;\n /** API key the client was configured with. */\n apiKey: string | null;\n}\n\n/**\n * SDK clients (OpenAI, Anthropic, Groq) store constructor options like\n * `defaultHeaders` and `fetch` in a private/protected `_options` field\n * with no public accessor. This extracts them with a narrow type assertion.\n */\nexport function getSdkClientOptions(client: object): {\n defaultHeaders?: Record<string, string>;\n fetch?: typeof globalThis.fetch;\n} {\n const rec = client as Record<string, unknown>;\n const options = rec._options;\n if (options != null && typeof options === \"object\") {\n return options as {\n defaultHeaders?: Record<string, string>;\n fetch?: typeof globalThis.fetch;\n };\n }\n return {};\n}\n"],"mappings":";;;;;;;AAkDA,SAAgB,oBAAoB,QAGlC;CAEA,MAAM,UADM,OACQ;AACpB,KAAI,WAAW,QAAQ,OAAO,YAAY,SACxC,QAAO;AAKT,QAAO,EAAE"}
|
package/dist/v2/index.cjs
CHANGED
|
@@ -46,6 +46,12 @@ exports.createCopilotEndpointSingleRoute = require_hono_single.createCopilotEndp
|
|
|
46
46
|
exports.createCopilotEndpointSingleRouteExpress = require_express_single.createCopilotEndpointSingleRouteExpress;
|
|
47
47
|
exports.createCopilotHonoHandler = require_hono.createCopilotHonoHandler;
|
|
48
48
|
exports.createCopilotRuntimeHandler = require_fetch_handler.createCopilotRuntimeHandler;
|
|
49
|
+
Object.defineProperty(exports, 'createRunEventFinalizer', {
|
|
50
|
+
enumerable: true,
|
|
51
|
+
get: function () {
|
|
52
|
+
return _copilotkit_shared.createRunEventFinalizer;
|
|
53
|
+
}
|
|
54
|
+
});
|
|
49
55
|
exports.defineTool = require_index.defineTool;
|
|
50
56
|
Object.defineProperty(exports, 'finalizeRunEvents', {
|
|
51
57
|
enumerable: true,
|
package/dist/v2/index.d.cts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
|
|
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
|
-
import { CopilotRuntimeLearningConfig, CopilotRuntimeLearningContext, CopilotRuntimeUser, GetLearningContainerId, LearningContainerSelectorInput } from "./runtime/core/learning.cjs";
|
|
5
4
|
import { GetLearnedSkillsSnapshotRequest, LearnedSkillsError, LearnedSkillsErrorCode, LearnedSkillsSnapshotResult } from "./runtime/intelligence-platform/learned-skills.cjs";
|
|
6
|
-
import { CopilotKitIntelligence, CopilotKitIntelligenceConfig, CreateThreadRequest, ListThreadsResponse, SubscribeToThreadsRequest, SubscribeToThreadsResponse, ThreadSummary, UpdateThreadRequest } from "./runtime/intelligence-platform/client.cjs";
|
|
7
5
|
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";
|
|
6
|
+
import { CopilotRuntimeLearningConfig, CopilotRuntimeLearningContext, CopilotRuntimeUser, GetLearningContainerId, LearningContainerSelectorInput } from "./runtime/core/learning.cjs";
|
|
7
|
+
import { CopilotKitIntelligence, CopilotKitIntelligenceConfig, CreateThreadRequest, ListThreadsResponse, SubscribeToThreadsRequest, SubscribeToThreadsResponse, ThreadSummary, UpdateThreadRequest } from "./runtime/intelligence-platform/client.cjs";
|
|
8
8
|
import { CopilotCorsConfig } from "./runtime/core/fetch-cors.cjs";
|
|
9
9
|
import { CopilotRuntimeHooks, ErrorHookContext, HandlerHookContext, HookContext, ResponseHookContext, RouteInfo } from "./runtime/core/hooks.cjs";
|
|
10
10
|
import { ChannelStatus, ChannelsControl } from "./runtime/core/channel-manager.cjs";
|
|
@@ -14,10 +14,11 @@ import { CopilotExpressEndpointParams, CopilotExpressRouter, createCopilotExpres
|
|
|
14
14
|
import { createCopilotEndpointSingleRouteExpress } from "./runtime/endpoints/express-single.cjs";
|
|
15
15
|
import { InMemoryAgentRunner, InMemoryAgentRunnerOptions, InMemoryLimits, InMemoryThread, ɵBoundedThreadStore, ɵGLOBAL_STORE, ɵINMEMORY_DEFAULTS, ɵestimateBytes, ɵnormalizeLimits } from "./runtime/runner/in-memory.cjs";
|
|
16
16
|
import { IntelligenceAgentRunner, IntelligenceAgentRunnerOptions, RunnerStartupBoundary } from "./runtime/runner/intelligence.cjs";
|
|
17
|
-
import { finalizeRunEvents } from "./runtime/runner/index.cjs";
|
|
17
|
+
import { FinalizeRunOptions, RunEventFinalizer, createRunEventFinalizer, finalizeRunEvents } from "./runtime/runner/index.cjs";
|
|
18
18
|
import { CopilotRuntimeFetchHandler, CopilotRuntimeFetchHandlerWithChannels, CopilotRuntimeHandlerOptions, createCopilotRuntimeHandler } from "./runtime/core/fetch-handler.cjs";
|
|
19
19
|
import { CopilotKitRequestHandler, MCPClient, MCPTransport } from "./runtime/index.cjs";
|
|
20
|
+
import { BuiltInAgentLearnedSkills, BuiltInAgentLearnedSkillsOptions } from "../agent/learned-skills.cjs";
|
|
20
21
|
import { convertAISDKStream } from "../agent/converters/aisdk.cjs";
|
|
21
22
|
import { TanStackChatMessage, TanStackInputResult, convertInputToTanStackAI, convertTanStackStream } from "../agent/converters/tanstack.cjs";
|
|
22
|
-
import { BasicAgent, BasicAgentConfiguration, BuiltInAgent, BuiltInAgentAISDKFactoryConfig, BuiltInAgentClassicConfig, BuiltInAgentConfiguration, BuiltInAgentCustomFactoryConfig, BuiltInAgentFactoryConfig, BuiltInAgentModel, BuiltInAgentTanStackFactoryConfig, InterruptSignal, MCPClientConfig, MCPClientConfigHTTP, MCPClientConfigSSE, MCPClientProvider, MessageConversionOptions, ModelSpecifier, OverridableProperty, ToolDefinition, classifyModelSpec, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, defineTool, resolveModel } from "../agent/index.cjs";
|
|
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, classifyModelSpec, 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
|
+
import { BasicAgent, BasicAgentConfiguration, BuiltInAgent, BuiltInAgentAISDKFactoryConfig, BuiltInAgentClassicConfig, BuiltInAgentConfiguration, BuiltInAgentCustomFactoryConfig, BuiltInAgentFactoryConfig, BuiltInAgentFactoryContext, BuiltInAgentModel, BuiltInAgentTanStackFactoryConfig, InterruptSignal, MCPClientConfig, MCPClientConfigHTTP, MCPClientConfigSSE, MCPClientProvider, MessageConversionOptions, ModelSpecifier, OverridableProperty, ToolDefinition, classifyModelSpec, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, defineTool, resolveModel } from "../agent/index.cjs";
|
|
24
|
+
export { type AgentFactoryContext, AgentRunner, AgentRunnerConnectRequest, AgentRunnerIsRunningRequest, AgentRunnerRunRequest, AgentRunnerStopRequest, AgentsConfig, AgentsFactory, BasicAgent, BasicAgentConfiguration, BuiltInAgent, BuiltInAgentAISDKFactoryConfig, BuiltInAgentClassicConfig, BuiltInAgentConfiguration, BuiltInAgentCustomFactoryConfig, BuiltInAgentFactoryConfig, BuiltInAgentFactoryContext, BuiltInAgentLearnedSkills, BuiltInAgentLearnedSkillsOptions, 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, FinalizeRunOptions, 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, RunEventFinalizer, RunnerStartupBoundary, RuntimeWithDeclaredChannels, SubscribeToThreadsRequest, SubscribeToThreadsResponse, TanStackChatMessage, TanStackInputResult, ThreadSummary, ToolDefinition, TranscribeFileOptions, TranscriptionService, UpdateThreadRequest, VERSION, classifyModelSpec, convertAISDKStream, convertInputToTanStackAI, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertTanStackStream, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, createCopilotEndpoint, createCopilotExpressHandler as createCopilotEndpointExpress, createCopilotExpressHandler, createCopilotEndpointSingleRoute, createCopilotEndpointSingleRouteExpress, createCopilotHonoHandler, createCopilotRuntimeHandler, createRunEventFinalizer, defineTool, finalizeRunEvents, isA2UIEnabled, isIntelligenceRuntime, resolveAgents, resolveModel, supportsLocalThreadEndpoints, toFetchCorsConfig, ɵBoundedThreadStore, ɵGLOBAL_STORE, ɵINMEMORY_DEFAULTS, ɵestimateBytes, ɵnormalizeLimits };
|
package/dist/v2/index.d.mts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
|
|
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
|
-
import { CopilotRuntimeLearningConfig, CopilotRuntimeLearningContext, CopilotRuntimeUser, GetLearningContainerId, LearningContainerSelectorInput } from "./runtime/core/learning.mjs";
|
|
5
4
|
import { GetLearnedSkillsSnapshotRequest, LearnedSkillsError, LearnedSkillsErrorCode, LearnedSkillsSnapshotResult } from "./runtime/intelligence-platform/learned-skills.mjs";
|
|
6
|
-
import { CopilotKitIntelligence, CopilotKitIntelligenceConfig, CreateThreadRequest, ListThreadsResponse, SubscribeToThreadsRequest, SubscribeToThreadsResponse, ThreadSummary, UpdateThreadRequest } from "./runtime/intelligence-platform/client.mjs";
|
|
7
5
|
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";
|
|
6
|
+
import { CopilotRuntimeLearningConfig, CopilotRuntimeLearningContext, CopilotRuntimeUser, GetLearningContainerId, LearningContainerSelectorInput } from "./runtime/core/learning.mjs";
|
|
7
|
+
import { CopilotKitIntelligence, CopilotKitIntelligenceConfig, CreateThreadRequest, ListThreadsResponse, SubscribeToThreadsRequest, SubscribeToThreadsResponse, ThreadSummary, UpdateThreadRequest } from "./runtime/intelligence-platform/client.mjs";
|
|
8
8
|
import { CopilotCorsConfig } from "./runtime/core/fetch-cors.mjs";
|
|
9
9
|
import { CopilotRuntimeHooks, ErrorHookContext, HandlerHookContext, HookContext, ResponseHookContext, RouteInfo } from "./runtime/core/hooks.mjs";
|
|
10
10
|
import { ChannelStatus, ChannelsControl } from "./runtime/core/channel-manager.mjs";
|
|
@@ -14,10 +14,11 @@ import { CopilotExpressEndpointParams, CopilotExpressRouter, createCopilotExpres
|
|
|
14
14
|
import { createCopilotEndpointSingleRouteExpress } from "./runtime/endpoints/express-single.mjs";
|
|
15
15
|
import { InMemoryAgentRunner, InMemoryAgentRunnerOptions, InMemoryLimits, InMemoryThread, ɵBoundedThreadStore, ɵGLOBAL_STORE, ɵINMEMORY_DEFAULTS, ɵestimateBytes, ɵnormalizeLimits } from "./runtime/runner/in-memory.mjs";
|
|
16
16
|
import { IntelligenceAgentRunner, IntelligenceAgentRunnerOptions, RunnerStartupBoundary } from "./runtime/runner/intelligence.mjs";
|
|
17
|
-
import { finalizeRunEvents } from "./runtime/runner/index.mjs";
|
|
17
|
+
import { FinalizeRunOptions, RunEventFinalizer, createRunEventFinalizer, finalizeRunEvents } from "./runtime/runner/index.mjs";
|
|
18
18
|
import { CopilotRuntimeFetchHandler, CopilotRuntimeFetchHandlerWithChannels, CopilotRuntimeHandlerOptions, createCopilotRuntimeHandler } from "./runtime/core/fetch-handler.mjs";
|
|
19
19
|
import { CopilotKitRequestHandler, MCPClient, MCPTransport } from "./runtime/index.mjs";
|
|
20
|
+
import { BuiltInAgentLearnedSkills, BuiltInAgentLearnedSkillsOptions } from "../agent/learned-skills.mjs";
|
|
20
21
|
import { convertAISDKStream } from "../agent/converters/aisdk.mjs";
|
|
21
22
|
import { TanStackChatMessage, TanStackInputResult, convertInputToTanStackAI, convertTanStackStream } from "../agent/converters/tanstack.mjs";
|
|
22
|
-
import { BasicAgent, BasicAgentConfiguration, BuiltInAgent, BuiltInAgentAISDKFactoryConfig, BuiltInAgentClassicConfig, BuiltInAgentConfiguration, BuiltInAgentCustomFactoryConfig, BuiltInAgentFactoryConfig, BuiltInAgentModel, BuiltInAgentTanStackFactoryConfig, InterruptSignal, MCPClientConfig, MCPClientConfigHTTP, MCPClientConfigSSE, MCPClientProvider, MessageConversionOptions, ModelSpecifier, OverridableProperty, ToolDefinition, classifyModelSpec, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, defineTool, resolveModel } from "../agent/index.mjs";
|
|
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, classifyModelSpec, 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
|
+
import { BasicAgent, BasicAgentConfiguration, BuiltInAgent, BuiltInAgentAISDKFactoryConfig, BuiltInAgentClassicConfig, BuiltInAgentConfiguration, BuiltInAgentCustomFactoryConfig, BuiltInAgentFactoryConfig, BuiltInAgentFactoryContext, BuiltInAgentModel, BuiltInAgentTanStackFactoryConfig, InterruptSignal, MCPClientConfig, MCPClientConfigHTTP, MCPClientConfigSSE, MCPClientProvider, MessageConversionOptions, ModelSpecifier, OverridableProperty, ToolDefinition, classifyModelSpec, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, defineTool, resolveModel } from "../agent/index.mjs";
|
|
24
|
+
export { type AgentFactoryContext, AgentRunner, AgentRunnerConnectRequest, AgentRunnerIsRunningRequest, AgentRunnerRunRequest, AgentRunnerStopRequest, AgentsConfig, AgentsFactory, BasicAgent, BasicAgentConfiguration, BuiltInAgent, BuiltInAgentAISDKFactoryConfig, BuiltInAgentClassicConfig, BuiltInAgentConfiguration, BuiltInAgentCustomFactoryConfig, BuiltInAgentFactoryConfig, BuiltInAgentFactoryContext, BuiltInAgentLearnedSkills, BuiltInAgentLearnedSkillsOptions, 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, FinalizeRunOptions, 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, RunEventFinalizer, RunnerStartupBoundary, RuntimeWithDeclaredChannels, SubscribeToThreadsRequest, SubscribeToThreadsResponse, TanStackChatMessage, TanStackInputResult, ThreadSummary, ToolDefinition, TranscribeFileOptions, TranscriptionService, UpdateThreadRequest, VERSION, classifyModelSpec, convertAISDKStream, convertInputToTanStackAI, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertTanStackStream, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, createCopilotEndpoint, createCopilotExpressHandler as createCopilotEndpointExpress, createCopilotExpressHandler, createCopilotEndpointSingleRoute, createCopilotEndpointSingleRouteExpress, createCopilotHonoHandler, createCopilotRuntimeHandler, createRunEventFinalizer, defineTool, finalizeRunEvents, isA2UIEnabled, isIntelligenceRuntime, resolveAgents, resolveModel, supportsLocalThreadEndpoints, toFetchCorsConfig, ɵBoundedThreadStore, ɵGLOBAL_STORE, ɵINMEMORY_DEFAULTS, ɵestimateBytes, ɵnormalizeLimits };
|
package/dist/v2/index.mjs
CHANGED
|
@@ -10,10 +10,10 @@ import { createCopilotEndpoint, createCopilotHonoHandler, toFetchCorsConfig } fr
|
|
|
10
10
|
import { createCopilotEndpointSingleRoute } from "./runtime/endpoints/hono-single.mjs";
|
|
11
11
|
import { createCopilotExpressHandler } from "./runtime/endpoints/express.mjs";
|
|
12
12
|
import { createCopilotEndpointSingleRouteExpress } from "./runtime/endpoints/express-single.mjs";
|
|
13
|
-
import { finalizeRunEvents } from "./runtime/runner/index.mjs";
|
|
13
|
+
import { createRunEventFinalizer, finalizeRunEvents } from "./runtime/runner/index.mjs";
|
|
14
14
|
import { TranscriptionService } from "./runtime/transcription-service/transcription-service.mjs";
|
|
15
15
|
import { convertAISDKStream } from "../agent/converters/aisdk.mjs";
|
|
16
16
|
import { convertInputToTanStackAI, convertTanStackStream } from "../agent/converters/tanstack.mjs";
|
|
17
17
|
import { BasicAgent, BuiltInAgent, InterruptSignal, classifyModelSpec, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, defineTool, resolveModel } from "../agent/index.mjs";
|
|
18
18
|
|
|
19
|
-
export { AgentRunner, BasicAgent, BuiltInAgent, CopilotIntelligenceRuntime, CopilotKitIntelligence, CopilotRuntime, CopilotSseRuntime, InMemoryAgentRunner, IntelligenceAgentRunner, InterruptSignal, LearnedSkillsError, TranscriptionService, VERSION, classifyModelSpec, 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, classifyModelSpec, convertAISDKStream, convertInputToTanStackAI, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertTanStackStream, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, createCopilotEndpoint, createCopilotExpressHandler as createCopilotEndpointExpress, createCopilotExpressHandler, createCopilotEndpointSingleRoute, createCopilotEndpointSingleRouteExpress, createCopilotHonoHandler, createCopilotRuntimeHandler, createRunEventFinalizer, defineTool, finalizeRunEvents, isA2UIEnabled, isIntelligenceRuntime, resolveAgents, resolveModel, supportsLocalThreadEndpoints, toFetchCorsConfig, ɵBoundedThreadStore, ɵGLOBAL_STORE, ɵINMEMORY_DEFAULTS, ɵestimateBytes, ɵnormalizeLimits };
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
|
|
2
2
|
import "../runner/agent-runner.cjs";
|
|
3
|
-
import "./learning.cjs";
|
|
4
3
|
import "../intelligence-platform/index.cjs";
|
|
4
|
+
import "./learning.cjs";
|
|
5
5
|
import { ChannelActivationConfig } from "./channel-activation-config.cjs";
|
|
6
6
|
import { AbstractAgent, Message } from "@ag-ui/client";
|
|
7
7
|
import { Channel, ReplyContinuationOptions } from "@copilotkit/channels-core";
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
|
|
2
2
|
import "../runner/agent-runner.mjs";
|
|
3
|
-
import "./learning.mjs";
|
|
4
3
|
import "../intelligence-platform/index.mjs";
|
|
5
4
|
import "../telemetry/telemetry-client.mjs";
|
|
5
|
+
import "./learning.mjs";
|
|
6
6
|
import { ChannelActivationConfig } from "./channel-activation-config.mjs";
|
|
7
7
|
import { AbstractAgent, Message } from "@ag-ui/client";
|
|
8
8
|
import { Channel, ReplyContinuationOptions } from "@copilotkit/channels-core";
|
|
@@ -2,6 +2,7 @@ require("reflect-metadata");
|
|
|
2
2
|
const require_runtime = require('../../../_virtual/_rolldown/runtime.cjs');
|
|
3
3
|
const require_logger = require('../../../lib/logger.cjs');
|
|
4
4
|
const require_header_utils = require('../handlers/header-utils.cjs');
|
|
5
|
+
const require_sse_keep_alive = require('../handlers/shared/sse-keep-alive.cjs');
|
|
5
6
|
const require_package$1 = require('../../../package.cjs');
|
|
6
7
|
const require_telemetry_disclosure = require('../../../lib/telemetry-disclosure.cjs');
|
|
7
8
|
const require_debug_event_bus = require('./debug-event-bus.cjs');
|
|
@@ -52,6 +53,7 @@ var BaseCopilotRuntime = class {
|
|
|
52
53
|
});
|
|
53
54
|
if (require_debug_event_bus.isDebugEventFeedEnabled(this.debug)) this.debugEventBus = new require_debug_event_bus.DebugEventBus();
|
|
54
55
|
this.forwardHeadersPolicy = require_header_utils.resolveForwardHeadersPolicy(options.forwardHeaders);
|
|
56
|
+
this.sseKeepAliveIntervalSeconds = require_sse_keep_alive.resolveSseKeepAliveIntervalSeconds(options.sseKeepAliveIntervalSeconds);
|
|
55
57
|
this.memory = options.memory;
|
|
56
58
|
this.exposeMemoryRoutes = this.memory !== void 0 || (options.exposeMemoryRoutes ?? false);
|
|
57
59
|
}
|
|
@@ -207,6 +209,9 @@ var CopilotRuntimeShim = class {
|
|
|
207
209
|
get forwardHeadersPolicy() {
|
|
208
210
|
return this.delegate.forwardHeadersPolicy;
|
|
209
211
|
}
|
|
212
|
+
get sseKeepAliveIntervalSeconds() {
|
|
213
|
+
return this.delegate.sseKeepAliveIntervalSeconds;
|
|
214
|
+
}
|
|
210
215
|
get exposeMemoryRoutes() {
|
|
211
216
|
return this.delegate.exposeMemoryRoutes;
|
|
212
217
|
}
|