@copilotkit/runtime 1.79.2-canary.1792172552 → 1.81.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.
Files changed (165) hide show
  1. package/dist/_virtual/_rolldown/runtime.mjs +15 -1
  2. package/dist/agent/index.cjs.map +1 -1
  3. package/dist/agent/index.d.cts +5 -3
  4. package/dist/agent/index.d.cts.map +1 -1
  5. package/dist/agent/index.d.mts +4 -2
  6. package/dist/agent/index.d.mts.map +1 -1
  7. package/dist/agent/index.mjs.map +1 -1
  8. package/dist/lib/runtime/agent-integrations/langgraph/agent.cjs +25 -1
  9. package/dist/lib/runtime/agent-integrations/langgraph/agent.cjs.map +1 -1
  10. package/dist/lib/runtime/agent-integrations/langgraph/agent.d.cts.map +1 -1
  11. package/dist/lib/runtime/agent-integrations/langgraph/agent.d.mts.map +1 -1
  12. package/dist/lib/runtime/agent-integrations/langgraph/agent.mjs +25 -1
  13. package/dist/lib/runtime/agent-integrations/langgraph/agent.mjs.map +1 -1
  14. package/dist/lib/runtime/copilot-runtime.cjs +17 -3
  15. package/dist/lib/runtime/copilot-runtime.cjs.map +1 -1
  16. package/dist/lib/runtime/copilot-runtime.d.cts +2 -3
  17. package/dist/lib/runtime/copilot-runtime.d.cts.map +1 -1
  18. package/dist/lib/runtime/copilot-runtime.d.mts +2 -3
  19. package/dist/lib/runtime/copilot-runtime.d.mts.map +1 -1
  20. package/dist/lib/runtime/copilot-runtime.mjs +18 -4
  21. package/dist/lib/runtime/copilot-runtime.mjs.map +1 -1
  22. package/dist/lib/runtime/legacy-service-adapter-agent.cjs +360 -0
  23. package/dist/lib/runtime/legacy-service-adapter-agent.cjs.map +1 -0
  24. package/dist/lib/runtime/legacy-service-adapter-agent.mjs +359 -0
  25. package/dist/lib/runtime/legacy-service-adapter-agent.mjs.map +1 -0
  26. package/dist/lib/telemetry-client.cjs +12 -1
  27. package/dist/lib/telemetry-client.cjs.map +1 -1
  28. package/dist/lib/telemetry-client.mjs +12 -1
  29. package/dist/lib/telemetry-client.mjs.map +1 -1
  30. package/dist/package.cjs +6 -6
  31. package/dist/package.mjs +6 -6
  32. package/dist/service-adapters/events.cjs +91 -0
  33. package/dist/service-adapters/events.cjs.map +1 -1
  34. package/dist/service-adapters/events.d.cts +6 -1
  35. package/dist/service-adapters/events.d.cts.map +1 -1
  36. package/dist/service-adapters/events.d.mts +6 -1
  37. package/dist/service-adapters/events.d.mts.map +1 -1
  38. package/dist/service-adapters/events.mjs +90 -1
  39. package/dist/service-adapters/events.mjs.map +1 -1
  40. package/dist/service-adapters/langchain/langchain-adapter.cjs +1 -1
  41. package/dist/service-adapters/langchain/langchain-adapter.cjs.map +1 -1
  42. package/dist/service-adapters/langchain/langchain-adapter.d.cts.map +1 -1
  43. package/dist/service-adapters/langchain/langchain-adapter.d.mts.map +1 -1
  44. package/dist/service-adapters/langchain/langchain-adapter.mjs +2 -2
  45. package/dist/service-adapters/langchain/langchain-adapter.mjs.map +1 -1
  46. package/dist/service-adapters/langchain/utils.cjs +53 -15
  47. package/dist/service-adapters/langchain/utils.cjs.map +1 -1
  48. package/dist/service-adapters/langchain/utils.mjs +53 -16
  49. package/dist/service-adapters/langchain/utils.mjs.map +1 -1
  50. package/dist/v2/index.cjs +6 -0
  51. package/dist/v2/index.d.cts +7 -4
  52. package/dist/v2/index.d.mts +7 -4
  53. package/dist/v2/index.mjs +5 -3
  54. package/dist/v2/runtime/core/middleware-sse-parser.cjs +11 -2
  55. package/dist/v2/runtime/core/middleware-sse-parser.cjs.map +1 -1
  56. package/dist/v2/runtime/core/middleware-sse-parser.mjs +11 -2
  57. package/dist/v2/runtime/core/middleware-sse-parser.mjs.map +1 -1
  58. package/dist/v2/runtime/core/package-info.cjs +1 -1
  59. package/dist/v2/runtime/core/package-info.mjs +1 -1
  60. package/dist/v2/runtime/core/runtime.cjs +6 -3
  61. package/dist/v2/runtime/core/runtime.cjs.map +1 -1
  62. package/dist/v2/runtime/core/runtime.d.cts +15 -3
  63. package/dist/v2/runtime/core/runtime.d.cts.map +1 -1
  64. package/dist/v2/runtime/core/runtime.d.mts +15 -3
  65. package/dist/v2/runtime/core/runtime.d.mts.map +1 -1
  66. package/dist/v2/runtime/core/runtime.mjs +6 -3
  67. package/dist/v2/runtime/core/runtime.mjs.map +1 -1
  68. package/dist/v2/runtime/endpoints/express.cjs +2 -2
  69. package/dist/v2/runtime/endpoints/express.cjs.map +1 -1
  70. package/dist/v2/runtime/endpoints/express.mjs +2 -2
  71. package/dist/v2/runtime/endpoints/express.mjs.map +1 -1
  72. package/dist/v2/runtime/endpoints/node-fetch-handler.cjs +51 -1
  73. package/dist/v2/runtime/endpoints/node-fetch-handler.cjs.map +1 -1
  74. package/dist/v2/runtime/endpoints/node-fetch-handler.d.cts.map +1 -1
  75. package/dist/v2/runtime/endpoints/node-fetch-handler.d.mts.map +1 -1
  76. package/dist/v2/runtime/endpoints/node-fetch-handler.mjs +52 -2
  77. package/dist/v2/runtime/endpoints/node-fetch-handler.mjs.map +1 -1
  78. package/dist/v2/runtime/generative-ui/generative-ui-middleware.cjs +394 -0
  79. package/dist/v2/runtime/generative-ui/generative-ui-middleware.cjs.map +1 -0
  80. package/dist/v2/runtime/generative-ui/generative-ui-middleware.d.cts +21 -0
  81. package/dist/v2/runtime/generative-ui/generative-ui-middleware.d.cts.map +1 -0
  82. package/dist/v2/runtime/generative-ui/generative-ui-middleware.d.mts +21 -0
  83. package/dist/v2/runtime/generative-ui/generative-ui-middleware.d.mts.map +1 -0
  84. package/dist/v2/runtime/generative-ui/generative-ui-middleware.mjs +393 -0
  85. package/dist/v2/runtime/generative-ui/generative-ui-middleware.mjs.map +1 -0
  86. package/dist/v2/runtime/generative-ui/index.d.cts +3 -0
  87. package/dist/v2/runtime/generative-ui/index.d.mts +3 -0
  88. package/dist/v2/runtime/generative-ui/surface-writer.cjs +86 -0
  89. package/dist/v2/runtime/generative-ui/surface-writer.cjs.map +1 -0
  90. package/dist/v2/runtime/generative-ui/surface-writer.d.cts +33 -0
  91. package/dist/v2/runtime/generative-ui/surface-writer.d.cts.map +1 -0
  92. package/dist/v2/runtime/generative-ui/surface-writer.d.mts +33 -0
  93. package/dist/v2/runtime/generative-ui/surface-writer.d.mts.map +1 -0
  94. package/dist/v2/runtime/generative-ui/surface-writer.mjs +85 -0
  95. package/dist/v2/runtime/generative-ui/surface-writer.mjs.map +1 -0
  96. package/dist/v2/runtime/handlers/handle-run.cjs +8 -3
  97. package/dist/v2/runtime/handlers/handle-run.cjs.map +1 -1
  98. package/dist/v2/runtime/handlers/handle-run.mjs +5 -1
  99. package/dist/v2/runtime/handlers/handle-run.mjs.map +1 -1
  100. package/dist/v2/runtime/handlers/intelligence/run.cjs +2 -3
  101. package/dist/v2/runtime/handlers/intelligence/run.cjs.map +1 -1
  102. package/dist/v2/runtime/handlers/intelligence/run.mjs +2 -3
  103. package/dist/v2/runtime/handlers/intelligence/run.mjs.map +1 -1
  104. package/dist/v2/runtime/handlers/shared/agent-utils.cjs +7 -0
  105. package/dist/v2/runtime/handlers/shared/agent-utils.cjs.map +1 -1
  106. package/dist/v2/runtime/handlers/shared/agent-utils.mjs +7 -0
  107. package/dist/v2/runtime/handlers/shared/agent-utils.mjs.map +1 -1
  108. package/dist/v2/runtime/handlers/shared/sse-response.cjs +39 -0
  109. package/dist/v2/runtime/handlers/shared/sse-response.cjs.map +1 -1
  110. package/dist/v2/runtime/handlers/shared/sse-response.mjs +39 -0
  111. package/dist/v2/runtime/handlers/shared/sse-response.mjs.map +1 -1
  112. package/dist/v2/runtime/index.d.cts +7 -3
  113. package/dist/v2/runtime/index.d.cts.map +1 -1
  114. package/dist/v2/runtime/index.d.mts +7 -3
  115. package/dist/v2/runtime/index.d.mts.map +1 -1
  116. package/dist/v2/runtime/intelligence-platform/client.cjs +100 -1
  117. package/dist/v2/runtime/intelligence-platform/client.cjs.map +1 -1
  118. package/dist/v2/runtime/intelligence-platform/client.d.cts +33 -1
  119. package/dist/v2/runtime/intelligence-platform/client.d.cts.map +1 -1
  120. package/dist/v2/runtime/intelligence-platform/client.d.mts +33 -1
  121. package/dist/v2/runtime/intelligence-platform/client.d.mts.map +1 -1
  122. package/dist/v2/runtime/intelligence-platform/client.mjs +100 -1
  123. package/dist/v2/runtime/intelligence-platform/client.mjs.map +1 -1
  124. package/dist/v2/runtime/intelligence-platform/experimental.d.cts +27 -0
  125. package/dist/v2/runtime/intelligence-platform/experimental.d.cts.map +1 -0
  126. package/dist/v2/runtime/intelligence-platform/experimental.d.mts +27 -0
  127. package/dist/v2/runtime/intelligence-platform/experimental.d.mts.map +1 -0
  128. package/dist/v2/runtime/intelligence-platform/index.d.cts +2 -1
  129. package/dist/v2/runtime/intelligence-platform/index.d.mts +2 -1
  130. package/dist/v2/runtime/intelligence-platform/learning-management.cjs +204 -0
  131. package/dist/v2/runtime/intelligence-platform/learning-management.cjs.map +1 -0
  132. package/dist/v2/runtime/intelligence-platform/learning-management.d.cts +112 -0
  133. package/dist/v2/runtime/intelligence-platform/learning-management.d.cts.map +1 -0
  134. package/dist/v2/runtime/intelligence-platform/learning-management.d.mts +112 -0
  135. package/dist/v2/runtime/intelligence-platform/learning-management.d.mts.map +1 -0
  136. package/dist/v2/runtime/intelligence-platform/learning-management.mjs +194 -0
  137. package/dist/v2/runtime/intelligence-platform/learning-management.mjs.map +1 -0
  138. package/dist/v2/runtime/runner/agent-runner.cjs +16 -0
  139. package/dist/v2/runtime/runner/agent-runner.cjs.map +1 -1
  140. package/dist/v2/runtime/runner/agent-runner.d.cts +11 -1
  141. package/dist/v2/runtime/runner/agent-runner.d.cts.map +1 -1
  142. package/dist/v2/runtime/runner/agent-runner.d.mts +11 -1
  143. package/dist/v2/runtime/runner/agent-runner.d.mts.map +1 -1
  144. package/dist/v2/runtime/runner/agent-runner.mjs +16 -1
  145. package/dist/v2/runtime/runner/agent-runner.mjs.map +1 -1
  146. package/dist/v2/runtime/runner/in-memory.cjs +1 -1
  147. package/dist/v2/runtime/runner/in-memory.cjs.map +1 -1
  148. package/dist/v2/runtime/runner/in-memory.mjs +2 -2
  149. package/dist/v2/runtime/runner/in-memory.mjs.map +1 -1
  150. package/dist/v2/runtime/runner/index.d.cts +2 -2
  151. package/dist/v2/runtime/runner/index.d.mts +2 -2
  152. package/dist/v2/runtime/runner/index.mjs +1 -1
  153. package/dist/v2/runtime/runner/intelligence.cjs +25 -85
  154. package/dist/v2/runtime/runner/intelligence.cjs.map +1 -1
  155. package/dist/v2/runtime/runner/intelligence.d.cts +2 -31
  156. package/dist/v2/runtime/runner/intelligence.d.cts.map +1 -1
  157. package/dist/v2/runtime/runner/intelligence.d.mts +2 -31
  158. package/dist/v2/runtime/runner/intelligence.d.mts.map +1 -1
  159. package/dist/v2/runtime/runner/intelligence.mjs +27 -87
  160. package/dist/v2/runtime/runner/intelligence.mjs.map +1 -1
  161. package/package.json +8 -8
  162. package/dist/v2/runtime/endpoints/express-fetch-bridge.cjs +0 -82
  163. package/dist/v2/runtime/endpoints/express-fetch-bridge.cjs.map +0 -1
  164. package/dist/v2/runtime/endpoints/express-fetch-bridge.mjs +0 -81
  165. package/dist/v2/runtime/endpoints/express-fetch-bridge.mjs.map +0 -1
@@ -7,6 +7,30 @@ let _ag_ui_client = require("@ag-ui/client");
7
7
  let _ag_ui_langgraph = require("@ag-ui/langgraph");
8
8
 
9
9
  //#region src/v1-deprecated/lib/runtime/agent-integrations/langgraph/agent.ts
10
+ /**
11
+ * Copy `name`, `description` and `parameters` from an OpenAI-style
12
+ * `{ function: { ... } }` descriptor to the top level, so Python agents that
13
+ * read `tool["parameters"]` get the real schema instead of `None` (#6570).
14
+ * Non-null fields already at the top level win, and `function` is kept intact.
15
+ * A top-level `null` is backfilled too: Python `None` comes back as `null`
16
+ * when state is restored from a checkpoint.
17
+ *
18
+ * Scope: this only normalizes `copilotkit.actions` for the v1 `LangGraphAgent`.
19
+ * `state["tools"]` and `ag-ui.tools` stay nested, and v2 users of
20
+ * `@ag-ui/langgraph` see no change. The full fix belongs upstream in
21
+ * `langGraphDefaultMergeState` in ag-ui-protocol/ag-ui.
22
+ */
23
+ function normalizeLangGraphTool(tool) {
24
+ const functionSpec = tool?.function;
25
+ if (!functionSpec || typeof functionSpec !== "object") return tool;
26
+ const normalized = { ...tool };
27
+ for (const key of [
28
+ "name",
29
+ "description",
30
+ "parameters"
31
+ ]) if (normalized[key] == null && functionSpec[key] != null) normalized[key] = functionSpec[key];
32
+ return normalized;
33
+ }
10
34
  var LangGraphAgent = class extends _ag_ui_langgraph.LangGraphAgent {
11
35
  constructor(config) {
12
36
  super(config);
@@ -120,7 +144,7 @@ var LangGraphAgent = class extends _ag_ui_langgraph.LangGraphAgent {
120
144
  langGraphDefaultMergeState(state, messages, input) {
121
145
  const aguiMergedState = super.langGraphDefaultMergeState(state, messages, input);
122
146
  const { tools: returnedTools, "ag-ui": agui } = aguiMergedState;
123
- const rawCombinedTools = [...returnedTools ?? [], ...agui?.tools ?? []];
147
+ const rawCombinedTools = [...returnedTools ?? [], ...agui?.tools ?? []].map(normalizeLangGraphTool);
124
148
  const combinedTools = Array.from(new Map(rawCombinedTools.map((t) => [t?.id ?? t?.name ?? t?.key ?? JSON.stringify(t), t])).values());
125
149
  return {
126
150
  ...aguiMergedState,
@@ -1 +1 @@
1
- {"version":3,"file":"agent.cjs","names":["AGUILangGraphAgent","EventType","CustomEventNames","LangGraphEventTypes"],"sources":["../../../../../../src/v1-deprecated/lib/runtime/agent-integrations/langgraph/agent.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/langgraph — LangGraphAgent:\n * No 1:1 v2 replacement is available.\n * Related v2 docs (LangGraph agents): https://docs.copilotkit.ai/agent-spec/langgraph\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\nimport type { Observable } from \"rxjs\";\nimport { map } from \"rxjs\";\nimport { LangGraphEventTypes } from \"../../../../agents/langgraph/events\";\nimport type { BaseEvent, RawEvent } from \"@ag-ui/core\";\nimport type {\n ProcessedEvents,\n SchemaKeys,\n StateEnrichment,\n} from \"@ag-ui/langgraph\";\nimport {\n LangGraphAgent as AGUILangGraphAgent,\n LangGraphHttpAgent,\n} from \"@ag-ui/langgraph\";\nimport type { LangGraphAgentConfig, State } from \"@ag-ui/langgraph\";\nimport type { ThreadState } from \"@langchain/langgraph-sdk\";\n\ninterface CopilotKitStateEnrichment {\n copilotkit: {\n actions: StateEnrichment[\"ag-ui\"][\"tools\"];\n context: StateEnrichment[\"ag-ui\"][\"context\"];\n };\n}\n\nimport type { RunAgentInput, CustomEvent } from \"@ag-ui/client\";\nimport { EventType } from \"@ag-ui/client\";\n\n// Import and re-export from separate file to maintain API compatibility\nimport type {\n TextMessageEvents,\n ToolCallEvents,\n PredictStateTool,\n} from \"./consts\";\nimport { CustomEventNames } from \"./consts\";\nexport { CustomEventNames };\n\n/**\n * The message type the base class's `langGraphDefaultMergeState` accepts.\n *\n * Derived from the base signature rather than deep-imported from\n * `@langchain/langgraph-sdk/dist/types.messages`. That path is an internal file\n * of an optional peer dependency: it is not part of the SDK's public entry\n * points, and consumers who skip the optional peer cannot resolve it at all,\n * which costs them a TS2307 on `skipLibCheck: false` (OSS-899). `@ag-ui/langgraph`\n * is a real dependency, so this stays resolvable for everyone.\n */\ntype LangGraphMessage = Parameters<\n AGUILangGraphAgent[\"langGraphDefaultMergeState\"]\n>[1][number];\n\nexport class LangGraphAgent extends AGUILangGraphAgent {\n constructor(config: LangGraphAgentConfig) {\n super(config);\n }\n\n dispatchEvent(event: ProcessedEvents) {\n if (event.type === EventType.CUSTOM) {\n // const event = processedEvent as unknown as CustomEvent;\n const customEvent = event as unknown as CustomEvent;\n\n if (customEvent.name === CustomEventNames.CopilotKitManuallyEmitMessage) {\n this.subscriber.next({\n type: EventType.TEXT_MESSAGE_START,\n role: \"assistant\",\n messageId: customEvent.value.message_id,\n rawEvent: event,\n });\n this.subscriber.next({\n type: EventType.TEXT_MESSAGE_CONTENT,\n messageId: customEvent.value.message_id,\n delta: customEvent.value.message,\n rawEvent: event,\n });\n this.subscriber.next({\n type: EventType.TEXT_MESSAGE_END,\n messageId: customEvent.value.message_id,\n rawEvent: event,\n });\n return true;\n }\n\n if (\n customEvent.name === CustomEventNames.CopilotKitManuallyEmitToolCall\n ) {\n this.subscriber.next({\n type: EventType.TOOL_CALL_START,\n toolCallId: customEvent.value.id,\n toolCallName: customEvent.value.name,\n parentMessageId: customEvent.value.id,\n rawEvent: event,\n });\n this.subscriber.next({\n type: EventType.TOOL_CALL_ARGS,\n toolCallId: customEvent.value.id,\n delta: customEvent.value.args,\n rawEvent: event,\n });\n this.subscriber.next({\n type: EventType.TOOL_CALL_END,\n toolCallId: customEvent.value.id,\n rawEvent: event,\n });\n return true;\n }\n\n if (\n customEvent.name ===\n CustomEventNames.CopilotKitManuallyEmitIntermediateState\n ) {\n this.activeRun.manuallyEmittedState = customEvent.value;\n this.dispatchEvent({\n type: EventType.STATE_SNAPSHOT,\n snapshot: this.getStateSnapshot({\n values: this.activeRun.manuallyEmittedState,\n } as ThreadState<State>),\n rawEvent: event,\n });\n return true;\n }\n\n if (customEvent.name === CustomEventNames.CopilotKitExit) {\n this.subscriber.next({\n type: EventType.CUSTOM,\n name: \"Exit\",\n value: true,\n });\n return true;\n }\n }\n\n // Intercept all text message and tool call events and check if should disable\n const rawEvent = (event as ToolCallEvents | TextMessageEvents).rawEvent;\n if (!rawEvent) {\n this.subscriber.next(event);\n return true;\n }\n\n const isMessageEvent =\n event.type === EventType.TEXT_MESSAGE_START ||\n event.type === EventType.TEXT_MESSAGE_CONTENT ||\n event.type === EventType.TEXT_MESSAGE_END;\n const isToolEvent =\n event.type === EventType.TOOL_CALL_START ||\n event.type === EventType.TOOL_CALL_ARGS ||\n event.type === EventType.TOOL_CALL_END;\n if (\"copilotkit:emit-tool-calls\" in (rawEvent.metadata || {})) {\n if (\n rawEvent.metadata[\"copilotkit:emit-tool-calls\"] === false &&\n isToolEvent\n ) {\n return false;\n }\n }\n if (\"copilotkit:emit-messages\" in (rawEvent.metadata || {})) {\n if (\n rawEvent.metadata[\"copilotkit:emit-messages\"] === false &&\n isMessageEvent\n ) {\n // Clean up tracked message state to prevent stale records from\n // leaking into subsequent nodes that have emit-messages enabled.\n if (this.activeRun?.id) {\n this.messagesInProcess[this.activeRun.id] = null;\n }\n return false;\n }\n }\n\n this.subscriber.next(event);\n return true;\n }\n\n // @ts-ignore\n run(input: RunAgentInput): Observable<BaseEvent> {\n // @ag-ui/langgraph's message converter throws \"message role is not\n // supported.\" on any role it doesn't enumerate (user|assistant|system|tool).\n // Reasoning-stream agents (e.g. OpenAI Responses API with reasoning summaries)\n // emit AG-UI messages with role:\"reasoning\" that the client then replays on\n // subsequent turns; without this filter the second turn crashes before the\n // model is ever called.\n const messages = (input.messages ?? []).filter(\n (m: { role?: string }) => m?.role !== \"reasoning\",\n );\n const enrichedInput = {\n ...input,\n messages,\n forwardedProps: {\n ...input.forwardedProps,\n streamSubgraphs: input.forwardedProps?.streamSubgraphs ?? true,\n },\n };\n return super.run(enrichedInput).pipe(\n map((processedEvent) => {\n // Turn raw event into emit state snapshot from tool call event\n if (processedEvent.type === EventType.RAW) {\n // Get the LangGraph event from the AGUI event.\n const event =\n (processedEvent as RawEvent).event ??\n (processedEvent as RawEvent).rawEvent;\n\n const eventType = event.event;\n const toolCallData = event.data?.chunk?.tool_call_chunks?.[0];\n const toolCallUsedToPredictState = event.metadata?.[\n \"copilotkit:emit-intermediate-state\"\n ]?.some(\n (predictStateTool: PredictStateTool) =>\n predictStateTool.tool === toolCallData?.name,\n );\n\n if (\n eventType === LangGraphEventTypes.OnChatModelStream &&\n toolCallUsedToPredictState\n ) {\n return {\n type: EventType.CUSTOM,\n name: \"PredictState\",\n value: event.metadata[\"copilotkit:emit-intermediate-state\"],\n };\n }\n }\n\n return processedEvent;\n }),\n );\n }\n\n langGraphDefaultMergeState(\n state: State,\n messages: LangGraphMessage[],\n input: RunAgentInput,\n ): State<StateEnrichment & CopilotKitStateEnrichment> {\n const aguiMergedState = super.langGraphDefaultMergeState(\n state,\n messages,\n input,\n );\n const { tools: returnedTools, \"ag-ui\": agui } = aguiMergedState;\n // tolerate undefined and de-duplicate by stable key (id | name | key)\n const rawCombinedTools = [\n ...((returnedTools as any[]) ?? []),\n ...((agui?.tools as any[]) ?? []),\n ];\n const combinedTools = Array.from(\n new Map(\n rawCombinedTools.map((t: any) => [\n t?.id ?? t?.name ?? t?.key ?? JSON.stringify(t),\n t,\n ]),\n ).values(),\n );\n\n return {\n ...aguiMergedState,\n copilotkit: {\n actions: combinedTools,\n context: agui?.context ?? [],\n },\n };\n }\n\n async getSchemaKeys(): Promise<SchemaKeys> {\n const CONSTANT_KEYS = [\"copilotkit\"];\n const schemaKeys = await super.getSchemaKeys();\n return {\n config: schemaKeys.config,\n input: schemaKeys.input ? [...schemaKeys.input, ...CONSTANT_KEYS] : null,\n output: schemaKeys.output\n ? [...schemaKeys.output, ...CONSTANT_KEYS]\n : null,\n context: schemaKeys.context\n ? [...schemaKeys.context, ...CONSTANT_KEYS]\n : null,\n };\n }\n}\n\nexport { LangGraphHttpAgent };\n"],"mappings":";;;;;;;;;AAoEA,IAAa,iBAAb,cAAoCA,gCAAmB;CACrD,YAAY,QAA8B;AACxC,QAAM,OAAO;;CAGf,cAAc,OAAwB;AACpC,MAAI,MAAM,SAASC,wBAAU,QAAQ;GAEnC,MAAM,cAAc;AAEpB,OAAI,YAAY,SAASC,gCAAiB,+BAA+B;AACvE,SAAK,WAAW,KAAK;KACnB,MAAMD,wBAAU;KAChB,MAAM;KACN,WAAW,YAAY,MAAM;KAC7B,UAAU;KACX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AO,KAAK,UAAU,EAAE,EAC/C,EACD,CAAC,CACH,CAAC,QAAQ,CACX;AAED,SAAO;GACL,GAAG;GACH,YAAY;IACV,SAAS;IACT,SAAS,MAAM,WAAW,EAAE;IAC7B;GACF;;CAGH,MAAM,gBAAqC;EACzC,MAAM,gBAAgB,CAAC,aAAa;EACpC,MAAM,aAAa,MAAM,MAAM,eAAe;AAC9C,SAAO;GACL,QAAQ,WAAW;GACnB,OAAO,WAAW,QAAQ,CAAC,GAAG,WAAW,OAAO,GAAG,cAAc,GAAG;GACpE,QAAQ,WAAW,SACf,CAAC,GAAG,WAAW,QAAQ,GAAG,cAAc,GACxC;GACJ,SAAS,WAAW,UAChB,CAAC,GAAG,WAAW,SAAS,GAAG,cAAc,GACzC;GACL"}
1
+ {"version":3,"file":"agent.cjs","names":["AGUILangGraphAgent","EventType","CustomEventNames","LangGraphEventTypes"],"sources":["../../../../../../src/v1-deprecated/lib/runtime/agent-integrations/langgraph/agent.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/langgraph — LangGraphAgent:\n * No 1:1 v2 replacement is available.\n * Related v2 docs (LangGraph agents): https://docs.copilotkit.ai/agent-spec/langgraph\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\nimport type { Observable } from \"rxjs\";\nimport { map } from \"rxjs\";\nimport { LangGraphEventTypes } from \"../../../../agents/langgraph/events\";\nimport type { BaseEvent, RawEvent } from \"@ag-ui/core\";\nimport type {\n ProcessedEvents,\n SchemaKeys,\n StateEnrichment,\n} from \"@ag-ui/langgraph\";\nimport {\n LangGraphAgent as AGUILangGraphAgent,\n LangGraphHttpAgent,\n} from \"@ag-ui/langgraph\";\nimport type { LangGraphAgentConfig, State } from \"@ag-ui/langgraph\";\nimport type { ThreadState } from \"@langchain/langgraph-sdk\";\n\ninterface CopilotKitStateEnrichment {\n copilotkit: {\n actions: StateEnrichment[\"ag-ui\"][\"tools\"];\n context: StateEnrichment[\"ag-ui\"][\"context\"];\n };\n}\n\nimport type { RunAgentInput, CustomEvent } from \"@ag-ui/client\";\nimport { EventType } from \"@ag-ui/client\";\n\n// Import and re-export from separate file to maintain API compatibility\nimport type {\n TextMessageEvents,\n ToolCallEvents,\n PredictStateTool,\n} from \"./consts\";\nimport { CustomEventNames } from \"./consts\";\nexport { CustomEventNames };\n\n/**\n * The message type the base class's `langGraphDefaultMergeState` accepts.\n *\n * Derived from the base signature rather than deep-imported from\n * `@langchain/langgraph-sdk/dist/types.messages`. That path is an internal file\n * of an optional peer dependency: it is not part of the SDK's public entry\n * points, and consumers who skip the optional peer cannot resolve it at all,\n * which costs them a TS2307 on `skipLibCheck: false` (OSS-899). `@ag-ui/langgraph`\n * is a real dependency, so this stays resolvable for everyone.\n */\ntype LangGraphMessage = Parameters<\n AGUILangGraphAgent[\"langGraphDefaultMergeState\"]\n>[1][number];\n\n/**\n * Copy `name`, `description` and `parameters` from an OpenAI-style\n * `{ function: { ... } }` descriptor to the top level, so Python agents that\n * read `tool[\"parameters\"]` get the real schema instead of `None` (#6570).\n * Non-null fields already at the top level win, and `function` is kept intact.\n * A top-level `null` is backfilled too: Python `None` comes back as `null`\n * when state is restored from a checkpoint.\n *\n * Scope: this only normalizes `copilotkit.actions` for the v1 `LangGraphAgent`.\n * `state[\"tools\"]` and `ag-ui.tools` stay nested, and v2 users of\n * `@ag-ui/langgraph` see no change. The full fix belongs upstream in\n * `langGraphDefaultMergeState` in ag-ui-protocol/ag-ui.\n */\nfunction normalizeLangGraphTool(tool: any): any {\n const functionSpec = tool?.function;\n if (!functionSpec || typeof functionSpec !== \"object\") return tool;\n\n const normalized = { ...tool };\n for (const key of [\"name\", \"description\", \"parameters\"] as const) {\n if (normalized[key] == null && functionSpec[key] != null) {\n normalized[key] = functionSpec[key];\n }\n }\n return normalized;\n}\n\nexport class LangGraphAgent extends AGUILangGraphAgent {\n constructor(config: LangGraphAgentConfig) {\n super(config);\n }\n\n dispatchEvent(event: ProcessedEvents) {\n if (event.type === EventType.CUSTOM) {\n // const event = processedEvent as unknown as CustomEvent;\n const customEvent = event as unknown as CustomEvent;\n\n if (customEvent.name === CustomEventNames.CopilotKitManuallyEmitMessage) {\n this.subscriber.next({\n type: EventType.TEXT_MESSAGE_START,\n role: \"assistant\",\n messageId: customEvent.value.message_id,\n rawEvent: event,\n });\n this.subscriber.next({\n type: EventType.TEXT_MESSAGE_CONTENT,\n messageId: customEvent.value.message_id,\n delta: customEvent.value.message,\n rawEvent: event,\n });\n this.subscriber.next({\n type: EventType.TEXT_MESSAGE_END,\n messageId: customEvent.value.message_id,\n rawEvent: event,\n });\n return true;\n }\n\n if (\n customEvent.name === CustomEventNames.CopilotKitManuallyEmitToolCall\n ) {\n this.subscriber.next({\n type: EventType.TOOL_CALL_START,\n toolCallId: customEvent.value.id,\n toolCallName: customEvent.value.name,\n parentMessageId: customEvent.value.id,\n rawEvent: event,\n });\n this.subscriber.next({\n type: EventType.TOOL_CALL_ARGS,\n toolCallId: customEvent.value.id,\n delta: customEvent.value.args,\n rawEvent: event,\n });\n this.subscriber.next({\n type: EventType.TOOL_CALL_END,\n toolCallId: customEvent.value.id,\n rawEvent: event,\n });\n return true;\n }\n\n if (\n customEvent.name ===\n CustomEventNames.CopilotKitManuallyEmitIntermediateState\n ) {\n this.activeRun.manuallyEmittedState = customEvent.value;\n this.dispatchEvent({\n type: EventType.STATE_SNAPSHOT,\n snapshot: this.getStateSnapshot({\n values: this.activeRun.manuallyEmittedState,\n } as ThreadState<State>),\n rawEvent: event,\n });\n return true;\n }\n\n if (customEvent.name === CustomEventNames.CopilotKitExit) {\n this.subscriber.next({\n type: EventType.CUSTOM,\n name: \"Exit\",\n value: true,\n });\n return true;\n }\n }\n\n // Intercept all text message and tool call events and check if should disable\n const rawEvent = (event as ToolCallEvents | TextMessageEvents).rawEvent;\n if (!rawEvent) {\n this.subscriber.next(event);\n return true;\n }\n\n const isMessageEvent =\n event.type === EventType.TEXT_MESSAGE_START ||\n event.type === EventType.TEXT_MESSAGE_CONTENT ||\n event.type === EventType.TEXT_MESSAGE_END;\n const isToolEvent =\n event.type === EventType.TOOL_CALL_START ||\n event.type === EventType.TOOL_CALL_ARGS ||\n event.type === EventType.TOOL_CALL_END;\n if (\"copilotkit:emit-tool-calls\" in (rawEvent.metadata || {})) {\n if (\n rawEvent.metadata[\"copilotkit:emit-tool-calls\"] === false &&\n isToolEvent\n ) {\n return false;\n }\n }\n if (\"copilotkit:emit-messages\" in (rawEvent.metadata || {})) {\n if (\n rawEvent.metadata[\"copilotkit:emit-messages\"] === false &&\n isMessageEvent\n ) {\n // Clean up tracked message state to prevent stale records from\n // leaking into subsequent nodes that have emit-messages enabled.\n if (this.activeRun?.id) {\n this.messagesInProcess[this.activeRun.id] = null;\n }\n return false;\n }\n }\n\n this.subscriber.next(event);\n return true;\n }\n\n // @ts-ignore\n run(input: RunAgentInput): Observable<BaseEvent> {\n // @ag-ui/langgraph's message converter throws \"message role is not\n // supported.\" on any role it doesn't enumerate (user|assistant|system|tool).\n // Reasoning-stream agents (e.g. OpenAI Responses API with reasoning summaries)\n // emit AG-UI messages with role:\"reasoning\" that the client then replays on\n // subsequent turns; without this filter the second turn crashes before the\n // model is ever called.\n const messages = (input.messages ?? []).filter(\n (m: { role?: string }) => m?.role !== \"reasoning\",\n );\n const enrichedInput = {\n ...input,\n messages,\n forwardedProps: {\n ...input.forwardedProps,\n streamSubgraphs: input.forwardedProps?.streamSubgraphs ?? true,\n },\n };\n return super.run(enrichedInput).pipe(\n map((processedEvent) => {\n // Turn raw event into emit state snapshot from tool call event\n if (processedEvent.type === EventType.RAW) {\n // Get the LangGraph event from the AGUI event.\n const event =\n (processedEvent as RawEvent).event ??\n (processedEvent as RawEvent).rawEvent;\n\n const eventType = event.event;\n const toolCallData = event.data?.chunk?.tool_call_chunks?.[0];\n const toolCallUsedToPredictState = event.metadata?.[\n \"copilotkit:emit-intermediate-state\"\n ]?.some(\n (predictStateTool: PredictStateTool) =>\n predictStateTool.tool === toolCallData?.name,\n );\n\n if (\n eventType === LangGraphEventTypes.OnChatModelStream &&\n toolCallUsedToPredictState\n ) {\n return {\n type: EventType.CUSTOM,\n name: \"PredictState\",\n value: event.metadata[\"copilotkit:emit-intermediate-state\"],\n };\n }\n }\n\n return processedEvent;\n }),\n );\n }\n\n langGraphDefaultMergeState(\n state: State,\n messages: LangGraphMessage[],\n input: RunAgentInput,\n ): State<StateEnrichment & CopilotKitStateEnrichment> {\n const aguiMergedState = super.langGraphDefaultMergeState(\n state,\n messages,\n input,\n );\n const { tools: returnedTools, \"ag-ui\": agui } = aguiMergedState;\n // tolerate undefined, normalize nested descriptors, and de-duplicate by\n // stable key (id | name | key). Normalizing first means a nested tool\n // collapses with a flat tool of the same name; the later entry wins.\n const rawCombinedTools = [\n ...((returnedTools as any[]) ?? []),\n ...((agui?.tools as any[]) ?? []),\n ].map(normalizeLangGraphTool);\n const combinedTools = Array.from(\n new Map(\n rawCombinedTools.map((t: any) => [\n t?.id ?? t?.name ?? t?.key ?? JSON.stringify(t),\n t,\n ]),\n ).values(),\n );\n\n return {\n ...aguiMergedState,\n copilotkit: {\n actions: combinedTools,\n context: agui?.context ?? [],\n },\n };\n }\n\n async getSchemaKeys(): Promise<SchemaKeys> {\n const CONSTANT_KEYS = [\"copilotkit\"];\n const schemaKeys = await super.getSchemaKeys();\n return {\n config: schemaKeys.config,\n input: schemaKeys.input ? [...schemaKeys.input, ...CONSTANT_KEYS] : null,\n output: schemaKeys.output\n ? [...schemaKeys.output, ...CONSTANT_KEYS]\n : null,\n context: schemaKeys.context\n ? [...schemaKeys.context,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/lib/runtime/agent-integrations/langgraph/agent.ts"],"mappings":";;;;;;;;UAmCU,yBAAA;EACR,UAAA;IACE,OAAA,EAAS,eAAA;IACT,OAAA,EAAS,eAAA;EAAA;AAAA;;;;;AAce;;;;;AAgB5B;KAJK,gBAAA,GAAmB,UAAA,CACtB,cAAA;AAAA,cAGW,gBAAA,SAAuB,cAAA;cACtB,MAAA,EAAQ,oBAAA;EAIpB,aAAA,CAAc,KAAA,EAAO,eAAA;EAqHrB,GAAA,CAAI,KAAA,EAAO,aAAA,GAAgB,UAAA,CAAW,WAAA;EAqDtC,0BAAA,CACE,KAAA,EAAO,KAAA,EACP,QAAA,EAAU,gBAAA,IACV,KAAA,EAAO,aAAA,GACN,KAAA,CAAM,eAAA,GAAkB,yBAAA;EA8BrB,aAAA,CAAA,GAAiB,OAAA,CAAQ,UAAA;AAAA"}
1
+ {"version":3,"file":"agent.d.cts","names":[],"sources":["../../../../../../src/v1-deprecated/lib/runtime/agent-integrations/langgraph/agent.ts"],"mappings":";;;;;;;;UAmCU,yBAAA;EACR,UAAA;IACE,OAAA,EAAS,eAAA;IACT,OAAA,EAAS,eAAA;EAAA;AAAA;;;;;AAce;;;;;AA0C5B;KA9BK,gBAAA,GAAmB,UAAA,CACtB,cAAA;AAAA,cA6BW,gBAAA,SAAuB,cAAA;cACtB,MAAA,EAAQ,oBAAA;EAIpB,aAAA,CAAc,KAAA,EAAO,eAAA;EAqHrB,GAAA,CAAI,KAAA,EAAO,aAAA,GAAgB,UAAA,CAAW,WAAA;EAqDtC,0BAAA,CACE,KAAA,EAAO,KAAA,EACP,QAAA,EAAU,gBAAA,IACV,KAAA,EAAO,aAAA,GACN,KAAA,CAAM,eAAA,GAAkB,yBAAA;EAgCrB,aAAA,CAAA,GAAiB,OAAA,CAAQ,UAAA;AAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"agent.d.mts","names":[],"sources":["../../../../../../src/v1-deprecated/lib/runtime/agent-integrations/langgraph/agent.ts"],"mappings":";;;;;;;;UAmCU,yBAAA;EACR,UAAA;IACE,OAAA,EAAS,eAAA;IACT,OAAA,EAAS,eAAA;EAAA;AAAA;;;;;AAce;;;;;AAgB5B;KAJK,gBAAA,GAAmB,UAAA,CACtB,cAAA;AAAA,cAGW,gBAAA,SAAuB,cAAA;cACtB,MAAA,EAAQ,oBAAA;EAIpB,aAAA,CAAc,KAAA,EAAO,eAAA;EAqHrB,GAAA,CAAI,KAAA,EAAO,aAAA,GAAgB,UAAA,CAAW,WAAA;EAqDtC,0BAAA,CACE,KAAA,EAAO,KAAA,EACP,QAAA,EAAU,gBAAA,IACV,KAAA,EAAO,aAAA,GACN,KAAA,CAAM,eAAA,GAAkB,yBAAA;EA8BrB,aAAA,CAAA,GAAiB,OAAA,CAAQ,UAAA;AAAA"}
1
+ {"version":3,"file":"agent.d.mts","names":[],"sources":["../../../../../../src/v1-deprecated/lib/runtime/agent-integrations/langgraph/agent.ts"],"mappings":";;;;;;;;UAmCU,yBAAA;EACR,UAAA;IACE,OAAA,EAAS,eAAA;IACT,OAAA,EAAS,eAAA;EAAA;AAAA;;;;;AAce;;;;;AA0C5B;KA9BK,gBAAA,GAAmB,UAAA,CACtB,cAAA;AAAA,cA6BW,gBAAA,SAAuB,cAAA;cACtB,MAAA,EAAQ,oBAAA;EAIpB,aAAA,CAAc,KAAA,EAAO,eAAA;EAqHrB,GAAA,CAAI,KAAA,EAAO,aAAA,GAAgB,UAAA,CAAW,WAAA;EAqDtC,0BAAA,CACE,KAAA,EAAO,KAAA,EACP,QAAA,EAAU,gBAAA,IACV,KAAA,EAAO,aAAA,GACN,KAAA,CAAM,eAAA,GAAkB,yBAAA;EAgCrB,aAAA,CAAA,GAAiB,OAAA,CAAQ,UAAA;AAAA"}
@@ -6,6 +6,30 @@ import { EventType } from "@ag-ui/client";
6
6
  import { LangGraphAgent, LangGraphHttpAgent } from "@ag-ui/langgraph";
7
7
 
8
8
  //#region src/v1-deprecated/lib/runtime/agent-integrations/langgraph/agent.ts
9
+ /**
10
+ * Copy `name`, `description` and `parameters` from an OpenAI-style
11
+ * `{ function: { ... } }` descriptor to the top level, so Python agents that
12
+ * read `tool["parameters"]` get the real schema instead of `None` (#6570).
13
+ * Non-null fields already at the top level win, and `function` is kept intact.
14
+ * A top-level `null` is backfilled too: Python `None` comes back as `null`
15
+ * when state is restored from a checkpoint.
16
+ *
17
+ * Scope: this only normalizes `copilotkit.actions` for the v1 `LangGraphAgent`.
18
+ * `state["tools"]` and `ag-ui.tools` stay nested, and v2 users of
19
+ * `@ag-ui/langgraph` see no change. The full fix belongs upstream in
20
+ * `langGraphDefaultMergeState` in ag-ui-protocol/ag-ui.
21
+ */
22
+ function normalizeLangGraphTool(tool) {
23
+ const functionSpec = tool?.function;
24
+ if (!functionSpec || typeof functionSpec !== "object") return tool;
25
+ const normalized = { ...tool };
26
+ for (const key of [
27
+ "name",
28
+ "description",
29
+ "parameters"
30
+ ]) if (normalized[key] == null && functionSpec[key] != null) normalized[key] = functionSpec[key];
31
+ return normalized;
32
+ }
9
33
  var LangGraphAgent$1 = class extends LangGraphAgent {
10
34
  constructor(config) {
11
35
  super(config);
@@ -119,7 +143,7 @@ var LangGraphAgent$1 = class extends LangGraphAgent {
119
143
  langGraphDefaultMergeState(state, messages, input) {
120
144
  const aguiMergedState = super.langGraphDefaultMergeState(state, messages, input);
121
145
  const { tools: returnedTools, "ag-ui": agui } = aguiMergedState;
122
- const rawCombinedTools = [...returnedTools ?? [], ...agui?.tools ?? []];
146
+ const rawCombinedTools = [...returnedTools ?? [], ...agui?.tools ?? []].map(normalizeLangGraphTool);
123
147
  const combinedTools = Array.from(new Map(rawCombinedTools.map((t) => [t?.id ?? t?.name ?? t?.key ?? JSON.stringify(t), t])).values());
124
148
  return {
125
149
  ...aguiMergedState,
@@ -1 +1 @@
1
- {"version":3,"file":"agent.mjs","names":["LangGraphAgent","AGUILangGraphAgent"],"sources":["../../../../../../src/v1-deprecated/lib/runtime/agent-integrations/langgraph/agent.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/langgraph — LangGraphAgent:\n * No 1:1 v2 replacement is available.\n * Related v2 docs (LangGraph agents): https://docs.copilotkit.ai/agent-spec/langgraph\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\nimport type { Observable } from \"rxjs\";\nimport { map } from \"rxjs\";\nimport { LangGraphEventTypes } from \"../../../../agents/langgraph/events\";\nimport type { BaseEvent, RawEvent } from \"@ag-ui/core\";\nimport type {\n ProcessedEvents,\n SchemaKeys,\n StateEnrichment,\n} from \"@ag-ui/langgraph\";\nimport {\n LangGraphAgent as AGUILangGraphAgent,\n LangGraphHttpAgent,\n} from \"@ag-ui/langgraph\";\nimport type { LangGraphAgentConfig, State } from \"@ag-ui/langgraph\";\nimport type { ThreadState } from \"@langchain/langgraph-sdk\";\n\ninterface CopilotKitStateEnrichment {\n copilotkit: {\n actions: StateEnrichment[\"ag-ui\"][\"tools\"];\n context: StateEnrichment[\"ag-ui\"][\"context\"];\n };\n}\n\nimport type { RunAgentInput, CustomEvent } from \"@ag-ui/client\";\nimport { EventType } from \"@ag-ui/client\";\n\n// Import and re-export from separate file to maintain API compatibility\nimport type {\n TextMessageEvents,\n ToolCallEvents,\n PredictStateTool,\n} from \"./consts\";\nimport { CustomEventNames } from \"./consts\";\nexport { CustomEventNames };\n\n/**\n * The message type the base class's `langGraphDefaultMergeState` accepts.\n *\n * Derived from the base signature rather than deep-imported from\n * `@langchain/langgraph-sdk/dist/types.messages`. That path is an internal file\n * of an optional peer dependency: it is not part of the SDK's public entry\n * points, and consumers who skip the optional peer cannot resolve it at all,\n * which costs them a TS2307 on `skipLibCheck: false` (OSS-899). `@ag-ui/langgraph`\n * is a real dependency, so this stays resolvable for everyone.\n */\ntype LangGraphMessage = Parameters<\n AGUILangGraphAgent[\"langGraphDefaultMergeState\"]\n>[1][number];\n\nexport class LangGraphAgent extends AGUILangGraphAgent {\n constructor(config: LangGraphAgentConfig) {\n super(config);\n }\n\n dispatchEvent(event: ProcessedEvents) {\n if (event.type === EventType.CUSTOM) {\n // const event = processedEvent as unknown as CustomEvent;\n const customEvent = event as unknown as CustomEvent;\n\n if (customEvent.name === CustomEventNames.CopilotKitManuallyEmitMessage) {\n this.subscriber.next({\n type: EventType.TEXT_MESSAGE_START,\n role: \"assistant\",\n messageId: customEvent.value.message_id,\n rawEvent: event,\n });\n this.subscriber.next({\n type: EventType.TEXT_MESSAGE_CONTENT,\n messageId: customEvent.value.message_id,\n delta: customEvent.value.message,\n rawEvent: event,\n });\n this.subscriber.next({\n type: EventType.TEXT_MESSAGE_END,\n messageId: customEvent.value.message_id,\n rawEvent: event,\n });\n return true;\n }\n\n if (\n customEvent.name === CustomEventNames.CopilotKitManuallyEmitToolCall\n ) {\n this.subscriber.next({\n type: EventType.TOOL_CALL_START,\n toolCallId: customEvent.value.id,\n toolCallName: customEvent.value.name,\n parentMessageId: customEvent.value.id,\n rawEvent: event,\n });\n this.subscriber.next({\n type: EventType.TOOL_CALL_ARGS,\n toolCallId: customEvent.value.id,\n delta: customEvent.value.args,\n rawEvent: event,\n });\n this.subscriber.next({\n type: EventType.TOOL_CALL_END,\n toolCallId: customEvent.value.id,\n rawEvent: event,\n });\n return true;\n }\n\n if (\n customEvent.name ===\n CustomEventNames.CopilotKitManuallyEmitIntermediateState\n ) {\n this.activeRun.manuallyEmittedState = customEvent.value;\n this.dispatchEvent({\n type: EventType.STATE_SNAPSHOT,\n snapshot: this.getStateSnapshot({\n values: this.activeRun.manuallyEmittedState,\n } as ThreadState<State>),\n rawEvent: event,\n });\n return true;\n }\n\n if (customEvent.name === CustomEventNames.CopilotKitExit) {\n this.subscriber.next({\n type: EventType.CUSTOM,\n name: \"Exit\",\n value: true,\n });\n return true;\n }\n }\n\n // Intercept all text message and tool call events and check if should disable\n const rawEvent = (event as ToolCallEvents | TextMessageEvents).rawEvent;\n if (!rawEvent) {\n this.subscriber.next(event);\n return true;\n }\n\n const isMessageEvent =\n event.type === EventType.TEXT_MESSAGE_START ||\n event.type === EventType.TEXT_MESSAGE_CONTENT ||\n event.type === EventType.TEXT_MESSAGE_END;\n const isToolEvent =\n event.type === EventType.TOOL_CALL_START ||\n event.type === EventType.TOOL_CALL_ARGS ||\n event.type === EventType.TOOL_CALL_END;\n if (\"copilotkit:emit-tool-calls\" in (rawEvent.metadata || {})) {\n if (\n rawEvent.metadata[\"copilotkit:emit-tool-calls\"] === false &&\n isToolEvent\n ) {\n return false;\n }\n }\n if (\"copilotkit:emit-messages\" in (rawEvent.metadata || {})) {\n if (\n rawEvent.metadata[\"copilotkit:emit-messages\"] === false &&\n isMessageEvent\n ) {\n // Clean up tracked message state to prevent stale records from\n // leaking into subsequent nodes that have emit-messages enabled.\n if (this.activeRun?.id) {\n this.messagesInProcess[this.activeRun.id] = null;\n }\n return false;\n }\n }\n\n this.subscriber.next(event);\n return true;\n }\n\n // @ts-ignore\n run(input: RunAgentInput): Observable<BaseEvent> {\n // @ag-ui/langgraph's message converter throws \"message role is not\n // supported.\" on any role it doesn't enumerate (user|assistant|system|tool).\n // Reasoning-stream agents (e.g. OpenAI Responses API with reasoning summaries)\n // emit AG-UI messages with role:\"reasoning\" that the client then replays on\n // subsequent turns; without this filter the second turn crashes before the\n // model is ever called.\n const messages = (input.messages ?? []).filter(\n (m: { role?: string }) => m?.role !== \"reasoning\",\n );\n const enrichedInput = {\n ...input,\n messages,\n forwardedProps: {\n ...input.forwardedProps,\n streamSubgraphs: input.forwardedProps?.streamSubgraphs ?? true,\n },\n };\n return super.run(enrichedInput).pipe(\n map((processedEvent) => {\n // Turn raw event into emit state snapshot from tool call event\n if (processedEvent.type === EventType.RAW) {\n // Get the LangGraph event from the AGUI event.\n const event =\n (processedEvent as RawEvent).event ??\n (processedEvent as RawEvent).rawEvent;\n\n const eventType = event.event;\n const toolCallData = event.data?.chunk?.tool_call_chunks?.[0];\n const toolCallUsedToPredictState = event.metadata?.[\n \"copilotkit:emit-intermediate-state\"\n ]?.some(\n (predictStateTool: PredictStateTool) =>\n predictStateTool.tool === toolCallData?.name,\n );\n\n if (\n eventType === LangGraphEventTypes.OnChatModelStream &&\n toolCallUsedToPredictState\n ) {\n return {\n type: EventType.CUSTOM,\n name: \"PredictState\",\n value: event.metadata[\"copilotkit:emit-intermediate-state\"],\n };\n }\n }\n\n return processedEvent;\n }),\n );\n }\n\n langGraphDefaultMergeState(\n state: State,\n messages: LangGraphMessage[],\n input: RunAgentInput,\n ): State<StateEnrichment & CopilotKitStateEnrichment> {\n const aguiMergedState = super.langGraphDefaultMergeState(\n state,\n messages,\n input,\n );\n const { tools: returnedTools, \"ag-ui\": agui } = aguiMergedState;\n // tolerate undefined and de-duplicate by stable key (id | name | key)\n const rawCombinedTools = [\n ...((returnedTools as any[]) ?? []),\n ...((agui?.tools as any[]) ?? []),\n ];\n const combinedTools = Array.from(\n new Map(\n rawCombinedTools.map((t: any) => [\n t?.id ?? t?.name ?? t?.key ?? JSON.stringify(t),\n t,\n ]),\n ).values(),\n );\n\n return {\n ...aguiMergedState,\n copilotkit: {\n actions: combinedTools,\n context: agui?.context ?? [],\n },\n };\n }\n\n async getSchemaKeys(): Promise<SchemaKeys> {\n const CONSTANT_KEYS = [\"copilotkit\"];\n const schemaKeys = await super.getSchemaKeys();\n return {\n config: schemaKeys.config,\n input: schemaKeys.input ? [...schemaKeys.input, ...CONSTANT_KEYS] : null,\n output: schemaKeys.output\n ? [...schemaKeys.output, ...CONSTANT_KEYS]\n : null,\n context: schemaKeys.context\n ? [...schemaKeys.context, ...CONSTANT_KEYS]\n : null,\n };\n }\n}\n\nexport { LangG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OACA,UACA,OACoD;EACpD,MAAM,kBAAkB,MAAM,2BAC5B,OACA,UACA,MACD;EACD,MAAM,EAAE,OAAO,eAAe,SAAS,SAAS;EAEhD,MAAM,mBAAmB,CACvB,GAAK,iBAA2B,EAAE,EAClC,GAAK,MAAM,SAAmB,EAAE,CACjC;EACD,MAAM,gBAAgB,MAAM,KAC1B,IAAI,IACF,iBAAiB,KAAK,MAAW,CAC/B,GAAG,MAAM,GAAG,QAAQ,GAAG,OAAO,KAAK,UAAU,EAAE,EAC/C,EACD,CAAC,CACH,CAAC,QAAQ,CACX;AAED,SAAO;GACL,GAAG;GACH,YAAY;IACV,SAAS;IACT,SAAS,MAAM,WAAW,EAAE;IAC7B;GACF;;CAGH,MAAM,gBAAqC;EACzC,MAAM,gBAAgB,CAAC,aAAa;EACpC,MAAM,aAAa,MAAM,MAAM,eAAe;AAC9C,SAAO;GACL,QAAQ,WAAW;GACnB,OAAO,WAAW,QAAQ,CAAC,GAAG,WAAW,OAAO,GAAG,cAAc,GAAG;GACpE,QAAQ,WAAW,SACf,CAAC,GAAG,WAAW,QAAQ,GAAG,cAAc,GACxC;GACJ,SAAS,WAAW,UAChB,CAAC,GAAG,WAAW,SAAS,GAAG,cAAc,GACzC;GACL"}
1
+ {"version":3,"file":"agent.mjs","names":["LangGraphAgent","AGUILangGraphAgent"],"sources":["../../../../../../src/v1-deprecated/lib/runtime/agent-integrations/langgraph/agent.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/langgraph — LangGraphAgent:\n * No 1:1 v2 replacement is available.\n * Related v2 docs (LangGraph agents): https://docs.copilotkit.ai/agent-spec/langgraph\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\nimport type { Observable } from \"rxjs\";\nimport { map } from \"rxjs\";\nimport { LangGraphEventTypes } from \"../../../../agents/langgraph/events\";\nimport type { BaseEvent, RawEvent } from \"@ag-ui/core\";\nimport type {\n ProcessedEvents,\n SchemaKeys,\n StateEnrichment,\n} from \"@ag-ui/langgraph\";\nimport {\n LangGraphAgent as AGUILangGraphAgent,\n LangGraphHttpAgent,\n} from \"@ag-ui/langgraph\";\nimport type { LangGraphAgentConfig, State } from \"@ag-ui/langgraph\";\nimport type { ThreadState } from \"@langchain/langgraph-sdk\";\n\ninterface CopilotKitStateEnrichment {\n copilotkit: {\n actions: StateEnrichment[\"ag-ui\"][\"tools\"];\n context: StateEnrichment[\"ag-ui\"][\"context\"];\n };\n}\n\nimport type { RunAgentInput, CustomEvent } from \"@ag-ui/client\";\nimport { EventType } from \"@ag-ui/client\";\n\n// Import and re-export from separate file to maintain API compatibility\nimport type {\n TextMessageEvents,\n ToolCallEvents,\n PredictStateTool,\n} from \"./consts\";\nimport { CustomEventNames } from \"./consts\";\nexport { CustomEventNames };\n\n/**\n * The message type the base class's `langGraphDefaultMergeState` accepts.\n *\n * Derived from the base signature rather than deep-imported from\n * `@langchain/langgraph-sdk/dist/types.messages`. That path is an internal file\n * of an optional peer dependency: it is not part of the SDK's public entry\n * points, and consumers who skip the optional peer cannot resolve it at all,\n * which costs them a TS2307 on `skipLibCheck: false` (OSS-899). `@ag-ui/langgraph`\n * is a real dependency, so this stays resolvable for everyone.\n */\ntype LangGraphMessage = Parameters<\n AGUILangGraphAgent[\"langGraphDefaultMergeState\"]\n>[1][number];\n\n/**\n * Copy `name`, `description` and `parameters` from an OpenAI-style\n * `{ function: { ... } }` descriptor to the top level, so Python agents that\n * read `tool[\"parameters\"]` get the real schema instead of `None` (#6570).\n * Non-null fields already at the top level win, and `function` is kept intact.\n * A top-level `null` is backfilled too: Python `None` comes back as `null`\n * when state is restored from a checkpoint.\n *\n * Scope: this only normalizes `copilotkit.actions` for the v1 `LangGraphAgent`.\n * `state[\"tools\"]` and `ag-ui.tools` stay nested, and v2 users of\n * `@ag-ui/langgraph` see no change. The full fix belongs upstream in\n * `langGraphDefaultMergeState` in ag-ui-protocol/ag-ui.\n */\nfunction normalizeLangGraphTool(tool: any): any {\n const functionSpec = tool?.function;\n if (!functionSpec || typeof functionSpec !== \"object\") return tool;\n\n const normalized = { ...tool };\n for (const key of [\"name\", \"description\", \"parameters\"] as const) {\n if (normalized[key] == null && functionSpec[key] != null) {\n normalized[key] = functionSpec[key];\n }\n }\n return normalized;\n}\n\nexport class LangGraphAgent extends AGUILangGraphAgent {\n constructor(config: LangGraphAgentConfig) {\n super(config);\n }\n\n dispatchEvent(event: ProcessedEvents) {\n if (event.type === EventType.CUSTOM) {\n // const event = processedEvent as unknown as CustomEvent;\n const customEvent = event as unknown as CustomEvent;\n\n if (customEvent.name === CustomEventNames.CopilotKitManuallyEmitMessage) {\n this.subscriber.next({\n type: EventType.TEXT_MESSAGE_START,\n role: \"assistant\",\n messageId: customEvent.value.message_id,\n rawEvent: event,\n });\n this.subscriber.next({\n type: EventType.TEXT_MESSAGE_CONTENT,\n messageId: customEvent.value.message_id,\n delta: customEvent.value.message,\n rawEvent: event,\n });\n this.subscriber.next({\n type: EventType.TEXT_MESSAGE_END,\n messageId: customEvent.value.message_id,\n rawEvent: event,\n });\n return true;\n }\n\n if (\n customEvent.name === CustomEventNames.CopilotKitManuallyEmitToolCall\n ) {\n this.subscriber.next({\n type: EventType.TOOL_CALL_START,\n toolCallId: customEvent.value.id,\n toolCallName: customEvent.value.name,\n parentMessageId: customEvent.value.id,\n rawEvent: event,\n });\n this.subscriber.next({\n type: EventType.TOOL_CALL_ARGS,\n toolCallId: customEvent.value.id,\n delta: customEvent.value.args,\n rawEvent: event,\n });\n this.subscriber.next({\n type: EventType.TOOL_CALL_END,\n toolCallId: customEvent.value.id,\n rawEvent: event,\n });\n return true;\n }\n\n if (\n customEvent.name ===\n CustomEventNames.CopilotKitManuallyEmitIntermediateState\n ) {\n this.activeRun.manuallyEmittedState = customEvent.value;\n this.dispatchEvent({\n type: EventType.STATE_SNAPSHOT,\n snapshot: this.getStateSnapshot({\n values: this.activeRun.manuallyEmittedState,\n } as ThreadState<State>),\n rawEvent: event,\n });\n return true;\n }\n\n if (customEvent.name === CustomEventNames.CopilotKitExit) {\n this.subscriber.next({\n type: EventType.CUSTOM,\n name: \"Exit\",\n value: true,\n });\n return true;\n }\n }\n\n // Intercept all text message and tool call events and check if should disable\n const rawEvent = (event as ToolCallEvents | TextMessageEvents).rawEvent;\n if (!rawEvent) {\n this.subscriber.next(event);\n return true;\n }\n\n const isMessageEvent =\n event.type === EventType.TEXT_MESSAGE_START ||\n event.type === EventType.TEXT_MESSAGE_CONTENT ||\n event.type === EventType.TEXT_MESSAGE_END;\n const isToolEvent =\n event.type === EventType.TOOL_CALL_START ||\n event.type === EventType.TOOL_CALL_ARGS ||\n event.type === EventType.TOOL_CALL_END;\n if (\"copilotkit:emit-tool-calls\" in (rawEvent.metadata || {})) {\n if (\n rawEvent.metadata[\"copilotkit:emit-tool-calls\"] === false &&\n isToolEvent\n ) {\n return false;\n }\n }\n if (\"copilotkit:emit-messages\" in (rawEvent.metadata || {})) {\n if (\n rawEvent.metadata[\"copilotkit:emit-messages\"] === false &&\n isMessageEvent\n ) {\n // Clean up tracked message state to prevent stale records from\n // leaking into subsequent nodes that have emit-messages enabled.\n if (this.activeRun?.id) {\n this.messagesInProcess[this.activeRun.id] = null;\n }\n return false;\n }\n }\n\n this.subscriber.next(event);\n return true;\n }\n\n // @ts-ignore\n run(input: RunAgentInput): Observable<BaseEvent> {\n // @ag-ui/langgraph's message converter throws \"message role is not\n // supported.\" on any role it doesn't enumerate (user|assistant|system|tool).\n // Reasoning-stream agents (e.g. OpenAI Responses API with reasoning summaries)\n // emit AG-UI messages with role:\"reasoning\" that the client then replays on\n // subsequent turns; without this filter the second turn crashes before the\n // model is ever called.\n const messages = (input.messages ?? []).filter(\n (m: { role?: string }) => m?.role !== \"reasoning\",\n );\n const enrichedInput = {\n ...input,\n messages,\n forwardedProps: {\n ...input.forwardedProps,\n streamSubgraphs: input.forwardedProps?.streamSubgraphs ?? true,\n },\n };\n return super.run(enrichedInput).pipe(\n map((processedEvent) => {\n // Turn raw event into emit state snapshot from tool call event\n if (processedEvent.type === EventType.RAW) {\n // Get the LangGraph event from the AGUI event.\n const event =\n (processedEvent as RawEvent).event ??\n (processedEvent as RawEvent).rawEvent;\n\n const eventType = event.event;\n const toolCallData = event.data?.chunk?.tool_call_chunks?.[0];\n const toolCallUsedToPredictState = event.metadata?.[\n \"copilotkit:emit-intermediate-state\"\n ]?.some(\n (predictStateTool: PredictStateTool) =>\n predictStateTool.tool === toolCallData?.name,\n );\n\n if (\n eventType === LangGraphEventTypes.OnChatModelStream &&\n toolCallUsedToPredictState\n ) {\n return {\n type: EventType.CUSTOM,\n name: \"PredictState\",\n value: event.metadata[\"copilotkit:emit-intermediate-state\"],\n };\n }\n }\n\n return processedEvent;\n }),\n );\n }\n\n langGraphDefaultMergeState(\n state: State,\n messages: LangGraphMessage[],\n input: RunAgentInput,\n ): State<StateEnrichment & CopilotKitStateEnrichment> {\n const aguiMergedState = super.langGraphDefaultMergeState(\n state,\n messages,\n input,\n );\n const { tools: returnedTools, \"ag-ui\": agui } = aguiMergedState;\n // tolerate undefined, normalize nested descriptors, and de-duplicate by\n // stable key (id | name | key). Normalizing first means a nested tool\n // collapses with a flat tool of the same name; the later entry wins.\n const rawCombinedTools = [\n ...((returnedTools as any[]) ?? []),\n ...((agui?.tools as any[]) ?? []),\n ].map(normalizeLangGraphTool);\n const combinedTools = Array.from(\n new Map(\n rawCombinedTools.map((t: any) => [\n t?.id ?? t?.name ?? t?.key ?? JSON.stringify(t),\n t,\n ]),\n ).values(),\n );\n\n return {\n ...aguiMergedState,\n copilotkit: {\n actions: combinedTools,\n context: agui?.context ?? [],\n },\n };\n }\n\n async getSchemaKeys(): Promise<SchemaKeys> {\n const CONSTANT_KEYS = [\"copilotkit\"];\n const schemaKeys = await super.getSchemaKeys();\n return {\n config: schemaKeys.config,\n input: schemaKeys.input ? [...schemaKeys.input, ...CONSTANT_KEYS] : null,\n output: schemaKeys.output\n ? [...schemaKeys.output, ...CONSTANT_KEYS]\n : null,\n context: schemaKeys.context\n ? [...schemaKeys.context, ...CONSTANT_KEYS]\n : null,\n };\n }\n}\n\nexport { LangGraphHttpAgent };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAiFA,SAAS,uBAAuB,MAAgB;CAC9C,MAAM,eAAe,MAAM;AAC3B,KAAI,CAAC,gBAAgB,OAAO,iBAAiB,SAAU,QAAO;CAE9D,MAAM,aAAa,EAAE,GAAG,MAAM;AAC9B,MAAK,MAAM,OAAO;EAAC;EAAQ;EAAe;EAAa,CACrD,KAAI,WAAW,QAAQ,QAAQ,aAAa,QAAQ,KAClD,YAAW,OAAO,aAAa;AAGnC,QAAO;;AAGT,IAAaA,mBAAb,cAAoCC,eAAmB;CACrD,YAAY,QAA8B;AACxC,QAAM,OAAO;;CAGf,cAAc,OAAwB;AACpC,MAAI,MAAM,SAAS,UAAU,QAAQ;GAEnC,MAAM,cAAc;AAEpB,OAAI,YAAY,SAAS,iBAAiB,+BAA+B;AACvE,SAAK,WAAW,KAAK;KACnB,MAAM,UAAU;KAChB,MAAM;KACN,WAAW,YAAY,MAAM;KAC7B,UAAU;KACX,CAAC;AACF,SAAK,WAAW,KAAK;KACnB,MAAM,UAAU;KAChB,WAAW,YAAY,MAAM;KAC7B,OAAO,YAAY,MAAM;KACzB,UAAU;KACX,CAAC;AACF,SAAK,WAAW,KAAK;KACnB,MAAM,UAAU;KAChB,WAAW,YAAY,MAAM;KAC7B,UAAU;KACX,CAAC;AACF,WAAO;;AAGT,OACE,YAAY,SAAS,iBAAiB,gCACtC;AACA,SAAK,WAAW,KAAK;KACnB,MAAM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CAAC,GAAG,WAAW,OAAO,GAAG,cAAc,GAAG;GACpE,QAAQ,WAAW,SACf,CAAC,GAAG,WAAW,QAAQ,GAAG,cAAc,GACxC;GACJ,SAAS,WAAW,UAChB,CAAC,GAAG,WAAW,SAAS,GAAG,cAAc,GACzC;GACL"}
@@ -11,6 +11,7 @@ const require_types = require('./types.cjs');
11
11
  const require_mcp_tools_utils = require('./mcp-tools-utils.cjs');
12
12
  const require_mcp_tool_names = require('../../agent/mcp-tool-names.cjs');
13
13
  const require_index = require('../../agent/index.cjs');
14
+ const require_legacy_service_adapter_agent = require('./legacy-service-adapter-agent.cjs');
14
15
  const require_telemetry_client = require('../telemetry-client.cjs');
15
16
  let _copilotkit_shared = require("@copilotkit/shared");
16
17
 
@@ -29,6 +30,19 @@ let _copilotkit_shared = require("@copilotkit/shared");
29
30
  * ```
30
31
  */
31
32
  /**
33
+ * Whether the adapter's `provider/model` strings name a model BuiltInAgent can
34
+ * build. `BedrockAdapter` sets `provider = "bedrock"`, which it cannot.
35
+ */
36
+ function canResolveModel(serviceAdapter) {
37
+ if (!serviceAdapter.provider || !serviceAdapter.model) return false;
38
+ try {
39
+ require_index.resolveModel(`${serviceAdapter.provider}/${serviceAdapter.model}`);
40
+ return true;
41
+ } catch {
42
+ return false;
43
+ }
44
+ }
45
+ /**
32
46
  * Central runtime object passed to all request handlers.
33
47
  * @deprecated The v1 SDK is deprecated. Use v2 instead. Use `CopilotRuntime` from `@copilotkit/runtime/v2` instead.
34
48
  *
@@ -88,7 +102,6 @@ var CopilotRuntime = class {
88
102
  maxReconnectMs: params.maxReconnectMs,
89
103
  maxRejoinMs: params.maxRejoinMs,
90
104
  heartbeatIntervalMs: params.heartbeatIntervalMs,
91
- onEventDeliveryStats: params.onEventDeliveryStats,
92
105
  lockTtlSeconds: params.lockTtlSeconds,
93
106
  lockKeyPrefix: params.lockKeyPrefix,
94
107
  lockHeartbeatIntervalSeconds: params.lockHeartbeatIntervalSeconds
@@ -157,8 +170,9 @@ var CopilotRuntime = class {
157
170
  if (isAgentsListEmpty) {
158
171
  const languageModel = serviceAdapter.getLanguageModel?.();
159
172
  if (languageModel) agentsList.default = new require_index.BuiltInAgent({ model: languageModel });
160
- else if (serviceAdapter.provider && serviceAdapter.model) agentsList.default = new require_index.BuiltInAgent({ model: `${serviceAdapter.provider}/${serviceAdapter.model}` });
161
- else throw new _copilotkit_shared.CopilotKitMisuseError({ message: `Service adapter "${serviceAdapter.name ?? "unknown"}" does not provide model information. When using adapters like LangChainAdapter without an explicit agents list, please provide a default agent in the runtime config. Example:\n new CopilotRuntime({\n agents: { default: new BuiltInAgent({ model: "openai/gpt-4o" }) }\n })` });
173
+ else if (canResolveModel(serviceAdapter)) agentsList.default = new require_index.BuiltInAgent({ model: `${serviceAdapter.provider}/${serviceAdapter.model}` });
174
+ else if (serviceAdapter.name === "OpenAIAssistantAdapter") throw new _copilotkit_shared.CopilotKitMisuseError({ message: "OpenAIAssistantAdapter is not supported: OpenAI shut down the Assistants API on 2026-08-26. Use OpenAIAdapter, or a BuiltInAgent in the runtime's agents." });
175
+ else agentsList.default = new require_legacy_service_adapter_agent.LegacyServiceAdapterAgent(serviceAdapter);
162
176
  }
163
177
  return agentsList;
164
178
  }
@@ -1 +1 @@
1
- {"version":3,"file":"copilot-runtime.cjs","names":["firstNonBlankLicenseToken","telemetry","InMemoryAgentRunner","runtimeErrorReporterOption","createRuntimeErrorReporter","CopilotRuntimeVNext","EndpointType","CopilotKitMisuseError","resolveMCPToolNames","BuiltInAgent","aguiToGQL","describeEndpoint","resolveMCPEntry","extractParametersFromSchema"],"sources":["../../../../src/v1-deprecated/lib/runtime/copilot-runtime.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 — copilotKitEndpoint:\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 — CopilotRuntime:\n * V2 import and usage:\n * import { CopilotRuntime } from \"@copilotkit/runtime/v2\";\n *\n * const runtime = new CopilotRuntime({ agents: {} });\n * V2 replacement source: packages/runtime/src/v2/runtime/core/runtime.ts\n * V2 docs: https://docs.copilotkit.ai/runtime-server-adapter\n * Migration note: V2 uses AG-UI runtime handlers instead of the v1 GraphQL adapter setup.\n *\n * @copilotkit/runtime — CopilotRuntimeConstructorParams_BASE:\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 — langGraphPlatformEndpoint:\n * No 1:1 v2 replacement is available.\n * Related v2 docs (LangGraph agents): https://docs.copilotkit.ai/agent-spec/langgraph\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 — resolveEndpointType:\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 * <Callout type=\"info\">\n * This is the reference for the `CopilotRuntime` class. For more information and example code snippets, please see [Concept: Copilot Runtime](/backend/copilot-runtime).\n * </Callout>\n *\n * ## Usage\n *\n * ```tsx\n * import { CopilotRuntime } from \"@copilotkit/runtime\";\n *\n * const copilotKit = new CopilotRuntime();\n * ```\n */\n\nimport {\n CopilotKitMisuseError,\n readBody,\n getZodParameters,\n} from \"@copilotkit/shared\";\nimport {\n resolveMCPEntry,\n touchMCPEntry,\n describeEndpoint,\n} from \"./mcp-client-cache\";\nimport type {\n Action,\n CopilotErrorHandler,\n MaybePromise,\n NonEmptyRecord,\n Parameter,\n PartialBy,\n DebugConfig,\n TelemetryCapture,\n} from \"@copilotkit/shared\";\nimport type { RunAgentInput } from \"@ag-ui/core\";\nimport { aguiToGQL } from \"../../graphql/message-conversion/agui-to-gql\";\nimport type {\n CopilotServiceAdapter,\n RemoteChainParameters,\n} from \"../../service-adapters\";\nimport { CopilotRuntime as CopilotRuntimeVNext } from \"../../../v2/runtime/core/runtime\";\nimport { InMemoryAgentRunner } from \"../../../v2/runtime/runner\";\nimport {\n createRuntimeErrorReporter,\n runtimeErrorReporterOption,\n} from \"../../../v2/runtime/core/runtime-error-reporter\";\nimport type { RuntimeErrorReporterOptions } from \"../../../v2/runtime/core/runtime-error-reporter\";\nimport type {\n CopilotIntelligenceRuntimeOptions,\n CopilotRuntimeOptions,\n CopilotRuntimeOptions as CopilotRuntimeOptionsVNext,\n AgentsConfig,\n AgentsFactory,\n AgentFactoryContext,\n} from \"../../../v2/runtime/core/runtime\";\nimport type { AgentRunner } from \"../../../v2/runtime/runner\";\n\nexport type { AgentsConfig, AgentsFactory, AgentFactoryContext };\nimport telemetry from \"../telemetry-client\";\nimport { logRuntimeTelemetryDisclosure } from \"../telemetry-disclosure\";\n\nimport type { MessageInput } from \"../../graphql/inputs/message.input\";\nimport type { Message } from \"../../graphql/types/converted\";\n\nimport { EndpointType } from \"./types\";\nimport type {\n EndpointDefinition,\n CopilotKitEndpoint,\n LangGraphPlatformEndpoint,\n} from \"./types\";\n\nimport type {\n CopilotObservabilityConfig,\n LLMRequestData,\n LLMResponseData,\n} from \"../observability\";\nimport type { AbstractAgent } from \"@ag-ui/client\";\nimport {\n firstNonBlankLicenseToken,\n firstNonBlankTelemetryId,\n} from \"../../../v2/runtime/telemetry/telemetry-identity\";\n\n// +++ MCP Imports +++\nimport { extractParametersFromSchema } from \"./mcp-tools-utils\";\nimport type { MCPClient, MCPEndpointConfig, MCPTool } from \"./mcp-tools-utils\";\nimport { BuiltInAgent } from \"../../../agent\";\nimport type { BuiltInAgentClassicConfig } from \"../../../agent\";\nimport { resolveMCPToolNames } from \"../../../agent/mcp-tool-names\";\n// Define the function type alias here or import if defined elsewhere\ntype CreateMCPClientFunction = (\n config: MCPEndpointConfig,\n) => Promise<MCPClient>;\n\ntype ActionsConfiguration<T extends Parameter[] | [] = []> =\n | Action<T>[]\n | ((ctx: { properties: any; url?: string }) => Action<T>[]);\n\ninterface OnBeforeRequestOptions {\n threadId?: string;\n runId?: string;\n inputMessages: Message[];\n properties: any;\n url?: string;\n}\n\ntype OnBeforeRequestHandler = (\n options: OnBeforeRequestOptions,\n) => void | Promise<void>;\n\ninterface OnAfterRequestOptions {\n threadId: string;\n runId?: string;\n inputMessages: Message[];\n outputMessages: Message[];\n properties: any;\n url?: string;\n}\n\ntype OnAfterRequestHandler = (\n options: OnAfterRequestOptions,\n) => void | Promise<void>;\n\ninterface OnStopGenerationOptions {\n threadId: string;\n runId?: string;\n url?: string;\n agentName?: string;\n lastMessage: MessageInput;\n}\ntype OnStopGenerationHandler = (\n options: OnStopGenerationOptions,\n) => void | Promise<void>;\n\ninterface Middleware {\n /**\n * A function that is called before the request is processed.\n */\n /**\n * @deprecated This middleware hook is deprecated and will be removed in a future version.\n * Use updated middleware integration methods in CopilotRuntimeVNext instead.\n */\n onBeforeRequest?: OnBeforeRequestHandler;\n\n /**\n * A function that is called after the request is processed.\n */\n /**\n * @deprecated This middleware hook is deprecated and will be removed in a future version.\n * Use updated middleware integration methods in CopilotRuntimeVNext instead.\n */\n onAfterRequest?: OnAfterRequestHandler;\n}\n\nexport interface CopilotRuntimeConstructorParams_BASE<\n T extends Parameter[] | [] = [],\n> {\n /** Standalone telemetry identity. Falls back to CPK_TELEMETRY_ID before legacy license identity. */\n telemetryId?: string;\n /**\n * Middleware to be used by the runtime.\n *\n * ```ts\n * onBeforeRequest: (options: {\n * threadId?: string;\n * runId?: string;\n * inputMessages: Message[];\n * properties: any;\n * }) => void | Promise<void>;\n * ```\n *\n * ```ts\n * onAfterRequest: (options: {\n * threadId?: string;\n * runId?: string;\n * inputMessages: Message[];\n * outputMessages: Message[];\n * properties: any;\n * }) => void | Promise<void>;\n * ```\n */\n /**\n * @deprecated This middleware hook is deprecated and will be removed in a future version.\n * Use updated middleware integration methods in CopilotRuntimeVNext instead.\n */\n middleware?: Middleware;\n\n /*\n * A list of server side actions that can be executed. Will be ignored when remoteActions are set\n */\n actions?: ActionsConfiguration<T>;\n\n /*\n * Deprecated: Use `remoteEndpoints`.\n */\n remoteActions?: CopilotKitEndpoint[];\n\n /*\n * A list of remote actions that can be executed.\n */\n remoteEndpoints?: EndpointDefinition[];\n\n /*\n * An array of LangServer URLs.\n */\n langserve?: RemoteChainParameters[];\n\n /**\n * Optional agent runner to use for SSE runtime.\n */\n runner?: AgentRunner;\n\n /*\n * A map of agent names to AGUI agents.\n * Example agent config:\n * ```ts\n * import { AbstractAgent } from \"@ag-ui/client\";\n * // ...\n * agents: {\n * \"support\": new CustomerSupportAgent(),\n * \"technical\": new TechnicalAgent()\n * }\n * ```\n */\n agents?: Record<string, AbstractAgent>;\n\n /*\n * Delegates agent state processing to the service adapter.\n *\n * When enabled, individual agent state requests will not be processed by the agent itself.\n * Instead, all processing will be handled by the service adapter.\n */\n delegateAgentProcessingToServiceAdapter?: boolean;\n\n /**\n * Configuration for LLM request/response logging.\n *\n * Example logging config:\n * ```ts\n * logging: {\n * enabled: true, // Enable or disable logging\n * progressive: true, // Set to false for buffered logging\n * logger: {\n * logRequest: (data) => langfuse.trace({ name: \"LLM Request\", input: data }),\n * logResponse: (data) => langfuse.trace({ name: \"LLM Response\", output: data }),\n * logError: (errorData) => langfuse.trace({ name: \"LLM Error\", metadata: errorData }),\n * },\n * }\n * ```\n */\n observability_c?: CopilotObservabilityConfig;\n\n /**\n * Configuration for connecting to Model Context Protocol (MCP) servers.\n * Allows fetching and using tools defined on external MCP-compliant servers.\n * Requires providing the `createMCPClient` function during instantiation.\n *\n * A request can also name its own servers, as `mcpServers` (or the older\n * `mcpEndpoints`) inside `forwardedProps` — that is what the frontend's\n * `setMcpServers` sends. Those are merged with this list and connected from\n * the server.\n *\n * That merge previously never ran: whatever the browser sent was accepted\n * and discarded. It now takes effect, so a deployment that has been sending\n * `setMcpServers` will start connecting to those endpoints without changing\n * anything on its side.\n *\n * The destination is therefore caller-controlled, not only config-controlled.\n * If your deployment does not mean to let the browser choose an MCP server,\n * check `config.endpoint` inside `createMCPClient` and reject anything\n * outside your allowlist. Without that check a request can aim the server at\n * a loopback, link-local, or otherwise internal address (SSRF).\n * @experimental\n */\n mcpServers?: MCPEndpointConfig[];\n\n /**\n * A function that creates an MCP client instance for a given endpoint configuration.\n * This function is responsible for using the appropriate MCP client library\n * (e.g., `@copilotkit/runtime`, `ai`) to establish a connection.\n * Required if `mcpServers` is provided.\n *\n * ```typescript\n * import { experimental_createMCPClient } from \"ai\"; // Import from vercel ai library\n * // ...\n * const runtime = new CopilotRuntime({\n * mcpServers: [{ endpoint: \"...\" }],\n * async createMCPClient(config) {\n * return await experimental_createMCPClient({\n * transport: {\n * type: \"sse\",\n * url: config.endpoint,\n * headers: config.apiKey\n * ? { Authorization: `Bearer ${config.apiKey}` }\n * : undefined,\n * },\n * });\n * }\n * });\n * ```\n *\n * Define this once, at module scope, if you build a new `CopilotRuntime`\n * per request. Connections are cached against the identity of this function\n * plus the endpoint config, and an inline function is a new object on every\n * request — so a per-request runtime with an inline factory opens a new\n * connection each time and never reuses one. A module-scope factory, which\n * is what the documented setup uses, shares connections across requests and\n * keeps the cache bounded by how many distinct credentials are in play\n * rather than by traffic.\n */\n createMCPClient?: CreateMCPClientFunction;\n\n /**\n * Optional error handler for comprehensive debugging and observability.\n *\n * @param errorEvent - Structured error event with rich debugging context\n *\n * @example\n * ```typescript\n * const runtime = new CopilotRuntime({\n * onError: (errorEvent) => {\n * debugDashboard.capture(errorEvent);\n * }\n * });\n * ```\n */\n onError?: CopilotErrorHandler;\n\n onStopGeneration?: OnStopGenerationHandler;\n\n /**\n * Enable debug logging for the runtime event pipeline.\n * Pass `true` for full output, or an object for granular control:\n *\n * ```ts\n * const runtime = new CopilotRuntime({\n * debug: true,\n * // or: debug: { events: true, lifecycle: true, verbose: false }\n * });\n * ```\n */\n debug?: DebugConfig;\n\n // /** Optional transcription service for audio processing. */\n // transcriptionService?: CopilotRuntimeOptionsVNext[\"transcriptionService\"];\n // /** Optional *before* middleware – callback function or webhook URL. */\n // beforeRequestMiddleware?: CopilotRuntimeOptionsVNext[\"beforeRequestMiddleware\"];\n // /** Optional *after* middleware – callback function or webhook URL. */\n // afterRequestMiddleware?: CopilotRuntimeOptionsVNext[\"afterRequestMiddleware\"];\n}\n\ntype BeforeRequestMiddleware =\n CopilotRuntimeOptionsVNext[\"beforeRequestMiddleware\"];\ntype AfterRequestMiddleware =\n CopilotRuntimeOptionsVNext[\"afterRequestMiddleware\"];\ntype BeforeRequestMiddlewareFn = Exclude<BeforeRequestMiddleware, string>;\ntype BeforeRequestMiddlewareFnParameters =\n Parameters<BeforeRequestMiddlewareFn>;\ntype BeforeRequestMiddlewareFnResult = ReturnType<BeforeRequestMiddlewareFn>;\ntype AfterRequestMiddlewareFn = Exclude<AfterRequestMiddleware, string>;\ntype AfterRequestMiddlewareFnParameters = Parameters<AfterRequestMiddlewareFn>;\n\ninterface CopilotRuntimeConstructorParams<T extends Parameter[] | [] = []>\n extends\n Omit<CopilotRuntimeConstructorParams_BASE<T>, \"agents\">,\n Omit<CopilotRuntimeOptionsVNext, \"agents\" | \"transcriptionService\"> {\n /**\n * TODO: un-omit `transcriptionService` above once it's supported\n *\n * This satisfies...\n * – the optional constraint in `CopilotRuntimeConstructorParams_BASE`\n * – the `MaybePromise<NonEmptyRecord<T>>` constraint in `CopilotRuntimeOptionsVNext`\n * – the `Record<string, AbstractAgent>` constraint in `both\n */\n agents?: AgentsConfig;\n\n intelligence?: CopilotIntelligenceRuntimeOptions[\"intelligence\"];\n identifyUser?: CopilotIntelligenceRuntimeOptions[\"identifyUser\"];\n memory?: CopilotIntelligenceRuntimeOptions[\"memory\"];\n channels?: CopilotIntelligenceRuntimeOptions[\"channels\"];\n ɵlearning?: CopilotIntelligenceRuntimeOptions[\"ɵlearning\"];\n generateThreadNames?: CopilotIntelligenceRuntimeOptions[\"generateThreadNames\"];\n maxReconnectMs?: CopilotIntelligenceRuntimeOptions[\"maxReconnectMs\"];\n maxRejoinMs?: CopilotIntelligenceRuntimeOptions[\"maxRejoinMs\"];\n heartbeatIntervalMs?: CopilotIntelligenceRuntimeOptions[\"heartbeatIntervalMs\"];\n onEventDeliveryStats?: CopilotIntelligenceRuntimeOptions[\"onEventDeliveryStats\"];\n lockTtlSeconds?: CopilotIntelligenceRuntimeOptions[\"lockTtlSeconds\"];\n lockKeyPrefix?: CopilotIntelligenceRuntimeOptions[\"lockKeyPrefix\"];\n lockHeartbeatIntervalSeconds?: CopilotIntelligenceRuntimeOptions[\"lockHeartbeatIntervalSeconds\"];\n}\n\n/**\n * Central runtime object passed to all request handlers.\n * @deprecated The v1 SDK is deprecated. Use v2 instead. Use `CopilotRuntime` from `@copilotkit/runtime/v2` instead.\n *\n * ```tsx\n * import { CopilotRuntime } from \"@copilotkit/runtime/v2\";\n *\n * const runtime = new CopilotRuntime({ agents: {} });\n * ```\n * See https://docs.copilotkit.ai/runtime-server-adapter\n */\nexport class CopilotRuntime<const T extends Parameter[] | [] = []> {\n params?: CopilotRuntimeConstructorParams<T>;\n private observability?: CopilotObservabilityConfig;\n /**\n * The request-independent half of agent resolution: validation, and the\n * default agent built from the service adapter. Resolved once, because\n * re-running the misuse checks on every request would turn a configuration\n * error into a per-request throw.\n */\n private baseAgents?: Promise<Record<string, AbstractAgent>>;\n /**\n * The `agents` value as configured, captured before the per-request factory\n * replaces it, so that repeated `handleServiceAdapter` calls do not wrap the\n * factory in itself.\n */\n private configuredAgents?: CopilotRuntimeOptions[\"agents\"];\n private runtimeArgs: CopilotRuntimeOptions & RuntimeErrorReporterOptions;\n private _instance: CopilotRuntimeVNext;\n /** Runtime-bound telemetry identity and sampling authority. */\n public readonly telemetry: TelemetryCapture;\n\n constructor(params?: CopilotRuntimeConstructorParams<T>) {\n logRuntimeTelemetryDisclosure();\n\n const agents = params?.agents ?? {};\n const endpointAgents = this.assignEndpointsToAgents(\n params?.remoteEndpoints ?? [],\n );\n\n // Merge endpoint agents with user-provided agents.\n // When agents is a factory function, wrap it so endpoint agents are merged\n // at resolution time (spreading a function produces {} — silent data loss).\n let mergedAgents: AgentsConfig;\n if (typeof agents === \"function\") {\n mergedAgents = async (ctx) => {\n const resolved = await agents(ctx);\n return { ...endpointAgents, ...resolved };\n };\n } else {\n mergedAgents = Promise.resolve(agents).then((resolved) => ({\n ...endpointAgents,\n ...resolved,\n }));\n }\n\n // Resolve identity once and bind it to this compatibility Runtime. The\n // capture scope shares process-level sinks and settings without exposing\n // mutable identity to other live runtimes.\n const resolvedLicenseToken = firstNonBlankLicenseToken(\n params?.licenseToken,\n process.env.COPILOTKIT_LICENSE_TOKEN,\n );\n const resolvedTelemetryId = firstNonBlankTelemetryId(\n params?.telemetryId,\n process.env.CPK_TELEMETRY_ID,\n );\n const resolvedTelemetryIdentity =\n resolvedTelemetryId !== undefined\n ? { telemetryId: resolvedTelemetryId }\n : resolvedLicenseToken !== undefined\n ? { licenseToken: resolvedLicenseToken }\n : {};\n this.telemetry = telemetry.createScope(resolvedTelemetryIdentity);\n\n // No TelemetryAgentRunner wrap. The V2 SSE path already emits\n // `agent_execution_stream_*` for this runtime, and since it now emits\n // through this entrypoint's scope, wrapping would put two copies of\n // every stream event on the wire. The class stays exported for callers\n // who construct it themselves. The rawEvent enrichment it used to add\n // moved to `v2/runtime/handlers/shared/sse-response.ts`, so nothing is\n // lost and v2 callers gain it too.\n const runner = params?.runner ?? new InMemoryAgentRunner();\n\n const sharedRuntimeArgs = {\n agents: mergedAgents,\n telemetryId: resolvedTelemetryId,\n licenseToken: resolvedLicenseToken,\n // Emit through this entrypoint's own scope rather than letting the\n // delegated V2 runtime build its own. That scope writes to Segment\n // and stamps the v1 surface, so handing it down is what lets the v1\n // middleware below stop emitting the same events a second time.\n ɵtelemetry: this.telemetry,\n telemetryProperties: params?.telemetryProperties,\n debug: params?.debug,\n // TODO: add support for transcriptionService from CopilotRuntimeOptionsVNext once it is ready\n // transcriptionService: params?.transcriptionService,\n\n beforeRequestMiddleware:\n this.createOnBeforeRequestHandler(params).bind(this),\n ...(params?.afterRequestMiddleware || params?.middleware?.onAfterRequest\n ? {\n afterRequestMiddleware:\n this.createOnAfterRequestHandler(params).bind(this),\n }\n : {}),\n a2ui: params?.a2ui,\n mcpApps: params?.mcpApps,\n openGenerativeUI: params?.openGenerativeUI,\n [runtimeErrorReporterOption]: createRuntimeErrorReporter(params?.onError),\n forwardHeaders: params?.forwardHeaders,\n exposeMemoryRoutes: params?.exposeMemoryRoutes,\n };\n if (params?.intelligence !== undefined) {\n // The compatibility constructor keeps Intelligence identity optional at\n // compile time, while the v2 runtime checks that callers supply web\n // identity, Channels, or both. Preserve that runtime validation here.\n this.runtimeArgs = {\n ...sharedRuntimeArgs,\n intelligence: params.intelligence,\n identifyUser: params.identifyUser,\n memory: params.memory,\n channels: params.channels,\n ɵlearning: params.ɵlearning,\n generateThreadNames: params.generateThreadNames,\n maxReconnectMs: params.maxReconnectMs,\n maxRejoinMs: params.maxRejoinMs,\n heartbeatIntervalMs: params.heartbeatIntervalMs,\n onEventDeliveryStats: params.onEventDeliveryStats,\n lockTtlSeconds: params.lockTtlSeconds,\n lockKeyPrefix: params.lockKeyPrefix,\n lockHeartbeatIntervalSeconds: params.lockHeartbeatIntervalSeconds,\n } as CopilotRuntimeOptions;\n } else {\n this.runtimeArgs = {\n ...sharedRuntimeArgs,\n runner,\n };\n }\n this.params = params;\n this.observability = params?.observability_c;\n }\n\n get instance() {\n if (!this._instance) {\n this._instance = new CopilotRuntimeVNext(this.runtimeArgs);\n }\n\n return this._instance;\n }\n\n private assignEndpointsToAgents(\n endpoints: CopilotRuntimeConstructorParams<T>[\"remoteEndpoints\"],\n ): Record<string, AbstractAgent> {\n let result: Record<string, AbstractAgent> = {};\n\n if (\n endpoints.some(\n (endpoint) =>\n resolveEndpointType(endpoint) == EndpointType.LangGraphPlatform,\n )\n ) {\n throw new CopilotKitMisuseError({\n message:\n \"LangGraphPlatformEndpoint in remoteEndpoints is deprecated. \" +\n 'Please use the \"agents\" option instead with LangGraphAgent from \"@copilotkit/runtime/langgraph\". ' +\n 'Example: agents: { myAgent: new LangGraphAgent({ deploymentUrl: \"...\", graphId: \"...\" }) }',\n });\n }\n\n return result;\n }\n\n handleServiceAdapter(serviceAdapter: CopilotServiceAdapter) {\n // Capture the configured value before the factory below replaces it, so a\n // second call does not wrap the factory in itself.\n this.configuredAgents ??= this.runtimeArgs.agents ?? {};\n const configuredAgents = this.configuredAgents;\n\n // Resolve the request-independent half once. Calling this twice (the\n // endpoint factory runs on every request under the documented v1 route)\n // must not re-validate or rebuild the default agent.\n //\n // A caller who supplied their own agents factory has no request-independent\n // half: their record is whatever they return for this request, so the same\n // checks run per request further down.\n if (typeof configuredAgents !== \"function\") {\n this.baseAgents ??= Promise.resolve(configuredAgents).then((agents) =>\n this.ensureDefaultAgent(\n agents as Record<string, AbstractAgent>,\n serviceAdapter,\n ),\n );\n // A misconfigured adapter rejects that promise, and nothing awaits it\n // until the first request arrives. Attach an inert handler so a runtime\n // that is never called does not surface an unhandled rejection; the\n // factory below still sees the rejection when it awaits.\n this.baseAgents.catch(() => {});\n }\n\n // Install the per-request factory the v2 runtime has supported since\n // #2941. Resolving once was what kept a dynamic `actions` function from\n // ever seeing request properties, and kept every request sharing one MCP\n // client regardless of whose credentials built it (#7116, #2407).\n const resolvePerRequest = async ({ request }: { request: Request }) => {\n // A caller-supplied agents factory is called here, with this request.\n // Treating it as a record instead (a function has no enumerable keys)\n // meant the service adapter's default replaced it and the caller's\n // function was never invoked at all.\n const baseAgents =\n typeof configuredAgents === \"function\"\n ? this.ensureDefaultAgent(\n { ...(await configuredAgents({ request })) },\n serviceAdapter,\n )\n : await this.baseAgents!;\n const properties = await this.readRequestProperties(request);\n const actions = this.params?.actions;\n\n // `actions` and `mcpServers` are attached independently: a runtime may\n // configure MCP servers without any local actions.\n const mcpSources = await this.getToolsFromMCP({ properties });\n const actionTools = actions\n ? this.getToolsFromActions(actions, { properties, url: request.url })\n : [];\n // An MCP tool that shares a name with an action, or with another\n // server's tool, is prefixed rather than dropped or duplicated.\n const mcpNames = resolveMCPToolNames(\n new Set(actionTools.map((tool) => tool.name)),\n mcpSources.map(({ label, tools }) => ({\n label,\n names: tools.map((tool) => tool.name),\n })),\n \"\",\n );\n const mcpTools = mcpSources.flatMap(({ tools }, i) =>\n tools.map((tool, j) => ({ ...tool, name: mcpNames[i]![j]! })),\n );\n const tools = [...actionTools, ...mcpTools];\n\n // Nothing to attach means nothing to isolate: hand the record back\n // untouched, exactly as a runtime with no actions and no MCP behaved\n // before this became a factory.\n if (!tools.length) {\n return baseAgents;\n }\n\n // Clone before attaching. `assignToolsToAgents` writes `config` onto the\n // agent, so mutating the shared instances would let one request's tools\n // reach another request that is already in flight.\n const perRequestAgents: Record<string, AbstractAgent> = {};\n for (const [agentId, agent] of Object.entries(baseAgents)) {\n const clone = agent.clone() as AbstractAgent;\n // `BuiltInAgent.clone()` rebuilds from `this.config`, so its own tools\n // survive. An agent whose `clone()` does not know about `config` --\n // `HttpAgent`, and anything else a v1 user registered -- would arrive\n // here empty, and the tools it declares itself would be shadowed by a\n // v1 action of the same name. Carry the config across when the clone\n // did not.\n if (\n Reflect.get(clone, \"config\") === undefined &&\n Reflect.get(agent, \"config\") !== undefined\n ) {\n Reflect.set(clone, \"config\", Reflect.get(agent, \"config\"));\n }\n perRequestAgents[agentId] = clone;\n }\n\n return this.assignToolsToAgents(perRequestAgents, tools);\n };\n\n this.runtimeArgs.agents =\n resolvePerRequest as unknown as CopilotRuntimeOptions[\"agents\"];\n }\n\n /**\n * Fill in the default agent the service adapter implies, and reject a\n * configuration that names no model at all.\n */\n private ensureDefaultAgent(\n agentsList: Record<string, AbstractAgent>,\n serviceAdapter: CopilotServiceAdapter,\n ): Record<string, AbstractAgent> {\n const isAgentsListEmpty = !Object.keys(agentsList).length;\n const hasServiceAdapter = Boolean(serviceAdapter);\n const illegalServiceAdapterNames = [\"EmptyAdapter\"];\n const serviceAdapterCanBeUsedForAgent =\n !illegalServiceAdapterNames.includes(serviceAdapter.name);\n\n if (\n isAgentsListEmpty &&\n (!hasServiceAdapter || !serviceAdapterCanBeUsedForAgent)\n ) {\n throw new CopilotKitMisuseError({\n message:\n \"No default agent provided. Please provide a default agent in the runtime config.\",\n });\n }\n\n if (isAgentsListEmpty) {\n const languageModel = serviceAdapter.getLanguageModel?.();\n if (languageModel) {\n // Adapter exposes a pre-configured LanguageModel (e.g. OpenAI/Anthropic adapters)\n agentsList.default = new BuiltInAgent({ model: languageModel });\n } else if (serviceAdapter.provider && serviceAdapter.model) {\n // Adapter exposes provider/model strings\n agentsList.default = new BuiltInAgent({\n model: `${serviceAdapter.provider}/${serviceAdapter.model}`,\n });\n } else {\n throw new CopilotKitMisuseError({\n message:\n `Service adapter \"${serviceAdapter.name ?? \"unknown\"}\" does not provide model information. ` +\n `When using adapters like LangChainAdapter without an explicit agents list, ` +\n `please provide a default agent in the runtime config. Example:\\n` +\n ` new CopilotRuntime({\\n` +\n ` agents: { default: new BuiltInAgent({ model: \"openai/gpt-4o\" }) }\\n` +\n ` })`,\n });\n }\n }\n\n return agentsList;\n }\n\n /**\n * The `forwardedProps` the browser sent with this request, which is what a\n * v1 `actions` function and `mcpServers` overrides are documented to read.\n *\n * `readBody` clones, so the handler still gets an unconsumed body, and it\n * returns `undefined` for GET, which is how the `/info` route reaches here.\n */\n private async readRequestProperties(\n request: Request,\n ): Promise<Record<string, unknown>> {\n try {\n const body = (await readBody(request)) as RunAgentInput | undefined;\n const properties = body?.forwardedProps;\n return properties && typeof properties === \"object\"\n ? (properties as Record<string, unknown>)\n : {};\n } catch {\n // A malformed body is the request handler's problem to report, not a\n // reason to fail agent resolution.\n return {};\n }\n }\n\n // Receive this.params.action and turn it into the AbstractAgent tools\n private getToolsFromActions(\n actions: ActionsConfiguration<any>,\n ctx: { properties: Record<string, unknown>; url?: string },\n ): BuiltInAgentClassicConfig[\"tools\"] {\n // Resolve actions to an array (handle function case).\n //\n // The function form is documented to receive the request's properties and\n // url. It was called once at resolution time with `{ properties: {}, url:\n // undefined }`, so a runtime that keyed its action list on the tenant, the\n // user, or anything else request-shaped got the same empty context every\n // time (#7116).\n const actionsArray =\n typeof actions === \"function\"\n ? actions({ properties: ctx.properties, url: ctx.url })\n : actions;\n\n // Convert each Action to a ToolDefinition\n return actionsArray.map((action) => {\n // Convert JSON schema to Zod schema\n const zodSchema = getZodParameters(action.parameters || []);\n\n return {\n name: action.name,\n description: action.description || \"\",\n parameters: zodSchema,\n // `handler` is an in-process function and was never part of the remote\n // executor deleted in v1.50.0 — only the wiring to it was lost. Call it.\n //\n // The result must never be `undefined`: `JSON.stringify(undefined)` is\n // not a string, which strips the required `content` off\n // TOOL_CALL_RESULT and surfaces as a Zod error in the browser\n // (#2915, #3198). Both branches below return a string instead.\n execute: async (args: unknown) => {\n if (typeof action.handler !== \"function\") {\n return (\n `The tool \"${action.name}\" was advertised without a handler, so it ` +\n `has no implementation to run. Tell the user this tool is unavailable.`\n );\n }\n const result = await action.handler(args as any);\n return result === undefined\n ? `The tool \"${action.name}\" ran and returned no value.`\n : result;\n },\n };\n });\n }\n\n private assignToolsToAgents(\n agents: Record<string, AbstractAgent>,\n tools: BuiltInAgentClassicConfig[\"tools\"],\n ): Record<string, AbstractAgent> {\n if (!tools?.length) {\n return agents;\n }\n\n const enrichedAgents: Record<string, AbstractAgent> = { ...agents };\n\n for (const [agentId, agent] of Object.entries(enrichedAgents)) {\n const existingConfig = (Reflect.get(agent, \"config\") ?? {}) as Record<\n string,\n unknown\n >;\n\n // Skip factory-mode agents — they don't have a tools property\n if (\"factory\" in existingConfig) {\n continue;\n }\n\n const classicConfig =\n existingConfig as unknown as BuiltInAgentClassicConfig;\n const existingTools = classicConfig.tools ?? [];\n\n // The endpoint factory runs `handleServiceAdapter` every time it is\n // called, and the documented v1 route builds the endpoint inside the\n // request handler — so a module-scope runtime lands here once per\n // request. Appending unconditionally advertised N copies of every tool\n // to the model. Skip names the agent already carries, which also leaves\n // a tool the agent defines itself in place.\n const existingNames = new Set(existingTools.map((tool) => tool.name));\n const newTools = tools.filter((tool) => !existingNames.has(tool.name));\n if (newTools.length === 0) {\n continue;\n }\n\n const updatedConfig: BuiltInAgentClassicConfig = {\n ...classicConfig,\n tools: [...existingTools, ...newTools],\n };\n\n Reflect.set(agent, \"config\", updatedConfig);\n enrichedAgents[agentId] = agent;\n }\n\n return enrichedAgents;\n }\n\n private createOnBeforeRequestHandler(\n params?: CopilotRuntimeConstructorParams<T> &\n PartialBy<CopilotRuntimeOptions, \"agents\">,\n ) {\n return async (hookParams: BeforeRequestMiddlewareFnParameters[0]) => {\n const { request } = hookParams;\n\n // No `copilot_request_created` capture here. The V2 handlers this\n // runtime delegates to already emit it, through this runtime's own\n // scope, and they know the route — so `requestType` is \"run\" or\n // \"connect\" rather than the \"unknown\" this site reported for every\n // request that did not set `forwardedProps.metadata.requestType`.\n const body = (await readBody(request)) as RunAgentInput;\n\n // We do not process middleware for the internal GET requests\n if (request.method === \"GET\" || !body) return;\n\n // TODO: get public api key and run with expected data\n // if (this.observability?.enabled && this.params.publicApiKey) {\n // this.logObservabilityBeforeRequest()\n // }\n\n // TODO: replace hooksParams top argument type with BeforeRequestMiddlewareParameters when exported\n const middlewareResult =\n await params?.beforeRequestMiddleware?.(hookParams);\n\n if (params?.middleware?.onBeforeRequest) {\n const { request, runtime, path } = hookParams;\n const gqlMessages = (aguiToGQL(body.messages) as Message[]).reduce(\n (acc, msg) => {\n if (\"role\" in msg && msg.role === \"user\") {\n acc.inputMessages.push(msg);\n } else {\n acc.outputMessages.push(msg);\n }\n return acc;\n },\n { inputMessages: [] as Message[], outputMessages: [] as Message[] },\n );\n const { inputMessages, outputMessages } = gqlMessages;\n params.middleware.onBeforeRequest({\n threadId: body.threadId,\n runId: body.runId,\n inputMessages,\n properties: body.forwardedProps,\n url: request.url,\n } satisfies OnBeforeRequestOptions);\n }\n\n return middlewareResult;\n };\n }\n\n private createOnAfterRequestHandler(\n params?: CopilotRuntimeConstructorParams<T> &\n PartialBy<CopilotRuntimeOptions, \"agents\">,\n ) {\n return async (hookParams: AfterRequestMiddlewareFnParameters[0]) => {\n // TODO: get public api key and run with expected data\n // if (this.observability?.enabled && publicApiKey) {\n // this.logObservabilityAfterRequest()\n // }\n\n // TODO: replace hooksParams top argument type with AfterRequestMiddlewareParameters when exported\n params?.afterRequestMiddleware?.(hookParams);\n\n if (params?.middleware?.onAfterRequest) {\n const messages = hookParams.messages ?? [];\n params.middleware.onAfterRequest({\n threadId: hookParams.threadId ?? \"\",\n runId: hookParams.runId,\n inputMessages: messages.filter(\n (m): m is typeof m & { role: string } =>\n \"role\" in m && m.role === \"user\",\n ) as unknown as Message[],\n outputMessages: messages.filter(\n (m): m is typeof m & { role: string } =>\n \"role\" in m && m.role !== \"user\",\n ) as unknown as Message[],\n // TODO: forward actual properties once the after-request hook has access to the request body\n properties: {},\n url: hookParams.path,\n } satisfies OnAfterRequestOptions);\n }\n };\n }\n\n // Observability Methods\n\n /**\n * Log LLM request if observability is enabled\n */\n private async logObservabilityBeforeRequest(\n requestData: LLMRequestData,\n ): Promise<void> {\n try {\n await this.observability.hooks.handleRequest(requestData);\n } catch (error) {\n console.error(\"Error logging LLM request:\", error);\n }\n }\n\n /**\n * Log final LLM response after request completes\n */\n private logObservabilityAfterRequest(\n outputMessagesPromise: Promise<Message[]>,\n baseData: {\n threadId: string;\n runId?: string;\n model?: string;\n provider?: string;\n agentName?: string;\n nodeName?: string;\n },\n streamedChunks: any[],\n requestStartTime: number,\n publicApiKey?: string,\n ): void {\n try {\n outputMessagesPromise\n .then((outputMessages) => {\n const responseData: LLMResponseData = {\n threadId: baseData.threadId,\n runId: baseData.runId,\n model: baseData.model,\n // Use collected chunks for progressive mode or outputMessages for regular mode\n output: this.observability.progressive\n ? streamedChunks\n : outputMessages,\n latency: Date.now() - requestStartTime,\n timestamp: Date.now(),\n provider: baseData.provider,\n isFinalResponse: true,\n agentName: baseData.agentName,\n nodeName: baseData.nodeName,\n };\n\n try {\n this.observability.hooks.handleResponse(responseData);\n } catch (logError) {\n console.error(\"Error logging LLM response:\", logError);\n }\n })\n .catch((error) => {\n console.error(\"Failed to get output messages for logging:\", error);\n });\n } catch (error) {\n console.error(\"Error setting up logging for LLM response:\", error);\n }\n }\n\n // Resolve MCP tools to BuiltInAgent tool definitions\n // Optionally accepts request-scoped properties to merge request-provided mcpServers\n private async getToolsFromMCP(options?: {\n properties?: Record<string, unknown>;\n }): Promise<\n { label: string; tools: NonNullable<BuiltInAgentClassicConfig[\"tools\"]> }[]\n > {\n const runtimeMcpServers = (this.params?.mcpServers ??\n []) as MCPEndpointConfig[];\n const createMCPClient = this.params?.createMCPClient as\n | CreateMCPClientFunction\n | undefined;\n\n // If no runtime config and no request overrides, nothing to do\n const requestMcpServers = ((\n options?.properties as { mcpServers?: MCPEndpointConfig[] } | undefined\n )?.mcpServers ??\n (\n options?.properties as\n | { mcpEndpoints?: MCPEndpointConfig[] }\n | undefined\n )?.mcpEndpoints ??\n []) as MCPEndpointConfig[];\n\n const hasAnyServers =\n (runtimeMcpServers?.length ?? 0) > 0 ||\n (requestMcpServers?.length ?? 0) > 0;\n if (!hasAnyServers) {\n return [];\n }\n\n if (!createMCPClient) {\n // Mirror legacy behavior: when servers are provided without a factory, treat as misconfiguration\n throw new CopilotKitMisuseError({\n message:\n \"MCP Integration Error: `mcpServers` were provided, but the `createMCPClient` function was not passed to the CopilotRuntime constructor. Please provide an implementation for `createMCPClient`.\",\n });\n }\n\n // Merge and dedupe endpoints by URL; request-level overrides take precedence.\n //\n // `requestMcpServers` is caller-supplied: it arrives in `forwardedProps`\n // from the browser. Validating it here is not this shim's call — the\n // endpoint shape, the transport, and the auth all belong to the\n // application's `createMCPClient`, and a hardcoded allowlist would break\n // the multi-tenant case this per-request path exists to serve. The\n // constraint is documented on `mcpServers` instead: a deployment that does\n // not intend browser-chosen servers has to reject them in its factory.\n const effectiveEndpoints = (() => {\n const byUrl = new Map<string, MCPEndpointConfig>();\n for (const ep of runtimeMcpServers) {\n if (ep?.endpoint) byUrl.set(ep.endpoint, ep);\n }\n for (const ep of requestMcpServers) {\n if (ep?.endpoint) byUrl.set(ep.endpoint, ep);\n }\n return Array.from(byUrl.values());\n })();\n\n const sources: {\n label: string;\n tools: NonNullable<BuiltInAgentClassicConfig[\"tools\"]>;\n }[] = [];\n\n for (const [index, config] of effectiveEndpoints.entries()) {\n // Everything that leaves this process with the endpoint in it uses the\n // redacted form: the raw URL's query can carry the credential, which is\n // exactly what the #2407 workaround puts there.\n const endpointLabel = describeEndpoint(config.endpoint);\n\n try {\n // Keyed by the client factory plus the whole config, so two callers\n // with different credentials for one endpoint get one client each.\n // Keying on the URL alone is #2407: the first caller's client served\n // everyone, and the reporter's `?uid=<hash>` workaround existed only\n // to force distinct keys.\n const entry = await resolveMCPEntry<BuiltInAgentClassicConfig[\"tools\"]>(\n createMCPClient,\n config,\n async () => {\n const client = await createMCPClient(config);\n const toolsMap = await client.tools();\n\n const toolDefs: BuiltInAgentClassicConfig[\"tools\"] = Object.entries(\n toolsMap,\n ).map(([toolName, tool]: [string, MCPTool]) => {\n const params: Parameter[] = extractParametersFromSchema(tool);\n const zodSchema = getZodParameters(params);\n return {\n name: toolName,\n description:\n tool.description ||\n `MCP tool: ${toolName} (from ${endpointLabel})`,\n parameters: zodSchema,\n // `tool.execute` calls the server over the cached client. That\n // client outlives this request but not necessarily this tool\n // definition: eviction can close it while these defs are still\n // held by an already-resolved agent.\n execute: async (args: unknown) => {\n // Executing is the only evidence this runtime gets that a\n // connection is still in use. Without it the entry ages from\n // the moment the agent resolved, and a busy process evicts\n // and closes a client that a live run is still calling.\n touchMCPEntry(createMCPClient, config);\n return tool.execute(args);\n },\n };\n });\n\n return { client, tools: toolDefs };\n },\n );\n\n sources.push({ label: `mcp${index + 1}`, tools: entry.tools ?? [] });\n } catch (error) {\n console.error(\n `MCP: Failed to fetch tools from endpoint ${endpointLabel}. Skipping. Error:`,\n error,\n );\n // Deliberately not cached. Caching the empty result meant a server\n // that was briefly unreachable when the runtime first resolved stayed\n // toolless for the life of that runtime, even after it recovered.\n // `resolveMCPEntry` drops a rejected entry so a later request retries.\n }\n }\n\n return sources;\n }\n}\n\n// The two functions below are \"factory functions\", meant to create the action objects that adhere to the expected interfaces\nexport function copilotKitEndpoint(\n config: Omit<CopilotKitEndpoint, \"type\">,\n): CopilotKitEndpoint {\n return {\n ...config,\n type: EndpointType.CopilotKit,\n };\n}\n\nexport function langGraphPlatformEndpoint(\n config: Omit<LangGraphPlatformEndpoint, \"type\">,\n): LangGraphPlatformEndpoint {\n return {\n ...config,\n type: EndpointType.LangGraphPlatform,\n };\n}\n\nexport function resolveEndpointType(endpoint: EndpointDefinition) {\n if (!endpoint.type) {\n if (\"deploymentUrl\" in endpoint && \"agents\" in endpoint) {\n return EndpointType.LangGraphPlatform;\n } else {\n return EndpointType.CopilotKit;\n }\n }\n\n return endpoint.type;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkcA,IAAa,iBAAb,MAAmE;CAqBjE,YAAY,QAA6C;AACvD,8DAA+B;EAE/B,MAAM,SAAS,QAAQ,UAAU,EAAE;EACnC,MAAM,iBAAiB,KAAK,wBAC1B,QAAQ,mBAAmB,EAAE,CAC9B;EAKD,IAAI;AACJ,MAAI,OAAO,WAAW,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AM,OAAO,OAAO;AA4BrC,YAAO;MAAE;MAAQ,OA1BoC,OAAO,QAC1D,SACD,CAAC,KAAK,CAAC,UAAU,UAA6B;OAE7C,MAAM,qDADsBC,oDAA4B,KAAK,CACnB;AAC1C,cAAO;QACL,MAAM;QACN,aACE,KAAK,eACL,aAAa,SAAS,SAAS,cAAc;QAC/C,YAAY;QAKZ,SAAS,OAAO,SAAkB;AAKhC,gDAAc,iBAAiB,OAAO;AACtC,gBAAO,KAAK,QAAQ,KAAK;;QAE5B;QACD;MAEgC;MAErC;AAED,YAAQ,KAAK;KAAE,OAAO,MAAM,QAAQ;KAAK,OAAO,MAAM,SAAS,EAAE;KAAE,CAAC;YAC7D,OAAO;AACd,YAAQ,MACN,4CAA4C,cAAc,qBAC1D,MACD;;;AAQL,SAAO;;;AAKX,SAAgB,mBACd,QACoB;AACpB,QAAO;EACL,GAAG;EACH,MAAMP,2BAAa;EACpB;;AAGH,SAAgB,0BACd,QAC2B;AAC3B,QAAO;EACL,GAAG;EACH,MAAMA,2BAAa;EACpB;;AAGH,SAAgB,oBAAoB,UAA8B;AAChE,KAAI,CAAC,SAAS,KACZ,KAAI,mBAAmB,YAAY,YAAY,SAC7C,QAAOA,2BAAa;KAEpB,QAAOA,2BAAa;AAIxB,QAAO,SAAS"}
1
+ {"version":3,"file":"copilot-runtime.cjs","names":["firstNonBlankLicenseToken","telemetry","InMemoryAgentRunner","runtimeErrorReporterOption","createRuntimeErrorReporter","CopilotRuntimeVNext","EndpointType","CopilotKitMisuseError","resolveMCPToolNames","BuiltInAgent","LegacyServiceAdapterAgent","aguiToGQL","describeEndpoint","resolveMCPEntry","extractParametersFromSchema"],"sources":["../../../../src/v1-deprecated/lib/runtime/copilot-runtime.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 — copilotKitEndpoint:\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 — CopilotRuntime:\n * V2 import and usage:\n * import { CopilotRuntime } from \"@copilotkit/runtime/v2\";\n *\n * const runtime = new CopilotRuntime({ agents: {} });\n * V2 replacement source: packages/runtime/src/v2/runtime/core/runtime.ts\n * V2 docs: https://docs.copilotkit.ai/runtime-server-adapter\n * Migration note: V2 uses AG-UI runtime handlers instead of the v1 GraphQL adapter setup.\n *\n * @copilotkit/runtime — CopilotRuntimeConstructorParams_BASE:\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 — langGraphPlatformEndpoint:\n * No 1:1 v2 replacement is available.\n * Related v2 docs (LangGraph agents): https://docs.copilotkit.ai/agent-spec/langgraph\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 — resolveEndpointType:\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 * <Callout type=\"info\">\n * This is the reference for the `CopilotRuntime` class. For more information and example code snippets, please see [Concept: Copilot Runtime](/backend/copilot-runtime).\n * </Callout>\n *\n * ## Usage\n *\n * ```tsx\n * import { CopilotRuntime } from \"@copilotkit/runtime\";\n *\n * const copilotKit = new CopilotRuntime();\n * ```\n */\n\nimport {\n CopilotKitMisuseError,\n readBody,\n getZodParameters,\n} from \"@copilotkit/shared\";\nimport {\n resolveMCPEntry,\n touchMCPEntry,\n describeEndpoint,\n} from \"./mcp-client-cache\";\nimport type {\n Action,\n CopilotErrorHandler,\n MaybePromise,\n NonEmptyRecord,\n Parameter,\n PartialBy,\n DebugConfig,\n TelemetryCapture,\n} from \"@copilotkit/shared\";\nimport type { RunAgentInput } from \"@ag-ui/core\";\nimport { aguiToGQL } from \"../../graphql/message-conversion/agui-to-gql\";\nimport type {\n CopilotServiceAdapter,\n RemoteChainParameters,\n} from \"../../service-adapters\";\nimport { CopilotRuntime as CopilotRuntimeVNext } from \"../../../v2/runtime/core/runtime\";\nimport { InMemoryAgentRunner } from \"../../../v2/runtime/runner\";\nimport {\n createRuntimeErrorReporter,\n runtimeErrorReporterOption,\n} from \"../../../v2/runtime/core/runtime-error-reporter\";\nimport type { RuntimeErrorReporterOptions } from \"../../../v2/runtime/core/runtime-error-reporter\";\nimport type {\n CopilotIntelligenceRuntimeOptions,\n CopilotRuntimeOptions,\n CopilotRuntimeOptions as CopilotRuntimeOptionsVNext,\n AgentsConfig,\n AgentsFactory,\n AgentFactoryContext,\n} from \"../../../v2/runtime/core/runtime\";\nimport type { AgentRunner } from \"../../../v2/runtime/runner\";\n\nexport type { AgentsConfig, AgentsFactory, AgentFactoryContext };\nimport telemetry from \"../telemetry-client\";\nimport { logRuntimeTelemetryDisclosure } from \"../telemetry-disclosure\";\n\nimport type { MessageInput } from \"../../graphql/inputs/message.input\";\nimport type { Message } from \"../../graphql/types/converted\";\n\nimport { EndpointType } from \"./types\";\nimport type {\n EndpointDefinition,\n CopilotKitEndpoint,\n LangGraphPlatformEndpoint,\n} from \"./types\";\n\nimport type {\n CopilotObservabilityConfig,\n LLMRequestData,\n LLMResponseData,\n} from \"../observability\";\nimport type { AbstractAgent } from \"@ag-ui/client\";\nimport {\n firstNonBlankLicenseToken,\n firstNonBlankTelemetryId,\n} from \"../../../v2/runtime/telemetry/telemetry-identity\";\n\n// +++ MCP Imports +++\nimport { extractParametersFromSchema } from \"./mcp-tools-utils\";\nimport type { MCPClient, MCPEndpointConfig, MCPTool } from \"./mcp-tools-utils\";\nimport { BuiltInAgent, resolveModel } from \"../../../agent\";\nimport type { BuiltInAgentClassicConfig } from \"../../../agent\";\nimport { LegacyServiceAdapterAgent } from \"./legacy-service-adapter-agent\";\nimport { resolveMCPToolNames } from \"../../../agent/mcp-tool-names\";\n// Define the function type alias here or import if defined elsewhere\ntype CreateMCPClientFunction = (\n config: MCPEndpointConfig,\n) => Promise<MCPClient>;\n\ntype ActionsConfiguration<T extends Parameter[] | [] = []> =\n | Action<T>[]\n | ((ctx: { properties: any; url?: string }) => Action<T>[]);\n\ninterface OnBeforeRequestOptions {\n threadId?: string;\n runId?: string;\n inputMessages: Message[];\n properties: any;\n url?: string;\n}\n\ntype OnBeforeRequestHandler = (\n options: OnBeforeRequestOptions,\n) => void | Promise<void>;\n\ninterface OnAfterRequestOptions {\n threadId: string;\n runId?: string;\n inputMessages: Message[];\n outputMessages: Message[];\n properties: any;\n url?: string;\n}\n\ntype OnAfterRequestHandler = (\n options: OnAfterRequestOptions,\n) => void | Promise<void>;\n\ninterface OnStopGenerationOptions {\n threadId: string;\n runId?: string;\n url?: string;\n agentName?: string;\n lastMessage: MessageInput;\n}\ntype OnStopGenerationHandler = (\n options: OnStopGenerationOptions,\n) => void | Promise<void>;\n\ninterface Middleware {\n /**\n * A function that is called before the request is processed.\n */\n /**\n * @deprecated This middleware hook is deprecated and will be removed in a future version.\n * Use updated middleware integration methods in CopilotRuntimeVNext instead.\n */\n onBeforeRequest?: OnBeforeRequestHandler;\n\n /**\n * A function that is called after the request is processed.\n */\n /**\n * @deprecated This middleware hook is deprecated and will be removed in a future version.\n * Use updated middleware integration methods in CopilotRuntimeVNext instead.\n */\n onAfterRequest?: OnAfterRequestHandler;\n}\n\nexport interface CopilotRuntimeConstructorParams_BASE<\n T extends Parameter[] | [] = [],\n> {\n /** Standalone telemetry identity. Falls back to CPK_TELEMETRY_ID before legacy license identity. */\n telemetryId?: string;\n /**\n * Middleware to be used by the runtime.\n *\n * ```ts\n * onBeforeRequest: (options: {\n * threadId?: string;\n * runId?: string;\n * inputMessages: Message[];\n * properties: any;\n * }) => void | Promise<void>;\n * ```\n *\n * ```ts\n * onAfterRequest: (options: {\n * threadId?: string;\n * runId?: string;\n * inputMessages: Message[];\n * outputMessages: Message[];\n * properties: any;\n * }) => void | Promise<void>;\n * ```\n */\n /**\n * @deprecated This middleware hook is deprecated and will be removed in a future version.\n * Use updated middleware integration methods in CopilotRuntimeVNext instead.\n */\n middleware?: Middleware;\n\n /*\n * A list of server side actions that can be executed. Will be ignored when remoteActions are set\n */\n actions?: ActionsConfiguration<T>;\n\n /*\n * Deprecated: Use `remoteEndpoints`.\n */\n remoteActions?: CopilotKitEndpoint[];\n\n /*\n * A list of remote actions that can be executed.\n */\n remoteEndpoints?: EndpointDefinition[];\n\n /*\n * An array of LangServer URLs.\n */\n langserve?: RemoteChainParameters[];\n\n /**\n * Optional agent runner to use for SSE runtime.\n */\n runner?: AgentRunner;\n\n /*\n * A map of agent names to AGUI agents.\n * Example agent config:\n * ```ts\n * import { AbstractAgent } from \"@ag-ui/client\";\n * // ...\n * agents: {\n * \"support\": new CustomerSupportAgent(),\n * \"technical\": new TechnicalAgent()\n * }\n * ```\n */\n agents?: Record<string, AbstractAgent>;\n\n /*\n * Delegates agent state processing to the service adapter.\n *\n * When enabled, individual agent state requests will not be processed by the agent itself.\n * Instead, all processing will be handled by the service adapter.\n */\n delegateAgentProcessingToServiceAdapter?: boolean;\n\n /**\n * Configuration for LLM request/response logging.\n *\n * Example logging config:\n * ```ts\n * logging: {\n * enabled: true, // Enable or disable logging\n * progressive: true, // Set to false for buffered logging\n * logger: {\n * logRequest: (data) => langfuse.trace({ name: \"LLM Request\", input: data }),\n * logResponse: (data) => langfuse.trace({ name: \"LLM Response\", output: data }),\n * logError: (errorData) => langfuse.trace({ name: \"LLM Error\", metadata: errorData }),\n * },\n * }\n * ```\n */\n observability_c?: CopilotObservabilityConfig;\n\n /**\n * Configuration for connecting to Model Context Protocol (MCP) servers.\n * Allows fetching and using tools defined on external MCP-compliant servers.\n * Requires providing the `createMCPClient` function during instantiation.\n *\n * A request can also name its own servers, as `mcpServers` (or the older\n * `mcpEndpoints`) inside `forwardedProps` — that is what the frontend's\n * `setMcpServers` sends. Those are merged with this list and connected from\n * the server.\n *\n * That merge previously never ran: whatever the browser sent was accepted\n * and discarded. It now takes effect, so a deployment that has been sending\n * `setMcpServers` will start connecting to those endpoints without changing\n * anything on its side.\n *\n * The destination is therefore caller-controlled, not only config-controlled.\n * If your deployment does not mean to let the browser choose an MCP server,\n * check `config.endpoint` inside `createMCPClient` and reject anything\n * outside your allowlist. Without that check a request can aim the server at\n * a loopback, link-local, or otherwise internal address (SSRF).\n * @experimental\n */\n mcpServers?: MCPEndpointConfig[];\n\n /**\n * A function that creates an MCP client instance for a given endpoint configuration.\n * This function is responsible for using the appropriate MCP client library\n * (e.g., `@copilotkit/runtime`, `ai`) to establish a connection.\n * Required if `mcpServers` is provided.\n *\n * ```typescript\n * import { experimental_createMCPClient } from \"ai\"; // Import from vercel ai library\n * // ...\n * const runtime = new CopilotRuntime({\n * mcpServers: [{ endpoint: \"...\" }],\n * async createMCPClient(config) {\n * return await experimental_createMCPClient({\n * transport: {\n * type: \"sse\",\n * url: config.endpoint,\n * headers: config.apiKey\n * ? { Authorization: `Bearer ${config.apiKey}` }\n * : undefined,\n * },\n * });\n * }\n * });\n * ```\n *\n * Define this once, at module scope, if you build a new `CopilotRuntime`\n * per request. Connections are cached against the identity of this function\n * plus the endpoint config, and an inline function is a new object on every\n * request — so a per-request runtime with an inline factory opens a new\n * connection each time and never reuses one. A module-scope factory, which\n * is what the documented setup uses, shares connections across requests and\n * keeps the cache bounded by how many distinct credentials are in play\n * rather than by traffic.\n */\n createMCPClient?: CreateMCPClientFunction;\n\n /**\n * Optional error handler for comprehensive debugging and observability.\n *\n * @param errorEvent - Structured error event with rich debugging context\n *\n * @example\n * ```typescript\n * const runtime = new CopilotRuntime({\n * onError: (errorEvent) => {\n * debugDashboard.capture(errorEvent);\n * }\n * });\n * ```\n */\n onError?: CopilotErrorHandler;\n\n onStopGeneration?: OnStopGenerationHandler;\n\n /**\n * Enable debug logging for the runtime event pipeline.\n * Pass `true` for full output, or an object for granular control:\n *\n * ```ts\n * const runtime = new CopilotRuntime({\n * debug: true,\n * // or: debug: { events: true, lifecycle: true, verbose: false }\n * });\n * ```\n */\n debug?: DebugConfig;\n\n // /** Optional transcription service for audio processing. */\n // transcriptionService?: CopilotRuntimeOptionsVNext[\"transcriptionService\"];\n // /** Optional *before* middleware – callback function or webhook URL. */\n // beforeRequestMiddleware?: CopilotRuntimeOptionsVNext[\"beforeRequestMiddleware\"];\n // /** Optional *after* middleware – callback function or webhook URL. */\n // afterRequestMiddleware?: CopilotRuntimeOptionsVNext[\"afterRequestMiddleware\"];\n}\n\ntype BeforeRequestMiddleware =\n CopilotRuntimeOptionsVNext[\"beforeRequestMiddleware\"];\ntype AfterRequestMiddleware =\n CopilotRuntimeOptionsVNext[\"afterRequestMiddleware\"];\ntype BeforeRequestMiddlewareFn = Exclude<BeforeRequestMiddleware, string>;\ntype BeforeRequestMiddlewareFnParameters =\n Parameters<BeforeRequestMiddlewareFn>;\ntype BeforeRequestMiddlewareFnResult = ReturnType<BeforeRequestMiddlewareFn>;\ntype AfterRequestMiddlewareFn = Exclude<AfterRequestMiddleware, string>;\ntype AfterRequestMiddlewareFnParameters = Parameters<AfterRequestMiddlewareFn>;\n\ninterface CopilotRuntimeConstructorParams<T extends Parameter[] | [] = []>\n extends\n Omit<CopilotRuntimeConstructorParams_BASE<T>, \"agents\">,\n Omit<CopilotRuntimeOptionsVNext, \"agents\" | \"transcriptionService\"> {\n /**\n * TODO: un-omit `transcriptionService` above once it's supported\n *\n * This satisfies...\n * – the optional constraint in `CopilotRuntimeConstructorParams_BASE`\n * – the `MaybePromise<NonEmptyRecord<T>>` constraint in `CopilotRuntimeOptionsVNext`\n * – the `Record<string, AbstractAgent>` constraint in `both\n */\n agents?: AgentsConfig;\n\n intelligence?: CopilotIntelligenceRuntimeOptions[\"intelligence\"];\n identifyUser?: CopilotIntelligenceRuntimeOptions[\"identifyUser\"];\n memory?: CopilotIntelligenceRuntimeOptions[\"memory\"];\n channels?: CopilotIntelligenceRuntimeOptions[\"channels\"];\n ɵlearning?: CopilotIntelligenceRuntimeOptions[\"ɵlearning\"];\n generateThreadNames?: CopilotIntelligenceRuntimeOptions[\"generateThreadNames\"];\n maxReconnectMs?: CopilotIntelligenceRuntimeOptions[\"maxReconnectMs\"];\n maxRejoinMs?: CopilotIntelligenceRuntimeOptions[\"maxRejoinMs\"];\n heartbeatIntervalMs?: CopilotIntelligenceRuntimeOptions[\"heartbeatIntervalMs\"];\n lockTtlSeconds?: CopilotIntelligenceRuntimeOptions[\"lockTtlSeconds\"];\n lockKeyPrefix?: CopilotIntelligenceRuntimeOptions[\"lockKeyPrefix\"];\n lockHeartbeatIntervalSeconds?: CopilotIntelligenceRuntimeOptions[\"lockHeartbeatIntervalSeconds\"];\n}\n\n/**\n * Whether the adapter's `provider/model` strings name a model BuiltInAgent can\n * build. `BedrockAdapter` sets `provider = \"bedrock\"`, which it cannot.\n */\nfunction canResolveModel(serviceAdapter: CopilotServiceAdapter): boolean {\n if (!serviceAdapter.provider || !serviceAdapter.model) {\n return false;\n }\n try {\n resolveModel(`${serviceAdapter.provider}/${serviceAdapter.model}`);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Central runtime object passed to all request handlers.\n * @deprecated The v1 SDK is deprecated. Use v2 instead. Use `CopilotRuntime` from `@copilotkit/runtime/v2` instead.\n *\n * ```tsx\n * import { CopilotRuntime } from \"@copilotkit/runtime/v2\";\n *\n * const runtime = new CopilotRuntime({ agents: {} });\n * ```\n * See https://docs.copilotkit.ai/runtime-server-adapter\n */\nexport class CopilotRuntime<const T extends Parameter[] | [] = []> {\n params?: CopilotRuntimeConstructorParams<T>;\n private observability?: CopilotObservabilityConfig;\n /**\n * The request-independent half of agent resolution: validation, and the\n * default agent built from the service adapter. Resolved once, because\n * re-running the misuse checks on every request would turn a configuration\n * error into a per-request throw.\n */\n private baseAgents?: Promise<Record<string, AbstractAgent>>;\n /**\n * The `agents` value as configured, captured before the per-request factory\n * replaces it, so that repeated `handleServiceAdapter` calls do not wrap the\n * factory in itself.\n */\n private configuredAgents?: CopilotRuntimeOptions[\"agents\"];\n private runtimeArgs: CopilotRuntimeOptions & RuntimeErrorReporterOptions;\n private _instance: CopilotRuntimeVNext;\n /** Runtime-bound telemetry identity and sampling authority. */\n public readonly telemetry: TelemetryCapture;\n\n constructor(params?: CopilotRuntimeConstructorParams<T>) {\n logRuntimeTelemetryDisclosure();\n\n const agents = params?.agents ?? {};\n const endpointAgents = this.assignEndpointsToAgents(\n params?.remoteEndpoints ?? [],\n );\n\n // Merge endpoint agents with user-provided agents.\n // When agents is a factory function, wrap it so endpoint agents are merged\n // at resolution time (spreading a function produces {} — silent data loss).\n let mergedAgents: AgentsConfig;\n if (typeof agents === \"function\") {\n mergedAgents = async (ctx) => {\n const resolved = await agents(ctx);\n return { ...endpointAgents, ...resolved };\n };\n } else {\n mergedAgents = Promise.resolve(agents).then((resolved) => ({\n ...endpointAgents,\n ...resolved,\n }));\n }\n\n // Resolve identity once and bind it to this compatibility Runtime. The\n // capture scope shares process-level sinks and settings without exposing\n // mutable identity to other live runtimes.\n const resolvedLicenseToken = firstNonBlankLicenseToken(\n params?.licenseToken,\n process.env.COPILOTKIT_LICENSE_TOKEN,\n );\n const resolvedTelemetryId = firstNonBlankTelemetryId(\n params?.telemetryId,\n process.env.CPK_TELEMETRY_ID,\n );\n const resolvedTelemetryIdentity =\n resolvedTelemetryId !== undefined\n ? { telemetryId: resolvedTelemetryId }\n : resolvedLicenseToken !== undefined\n ? { licenseToken: resolvedLicenseToken }\n : {};\n this.telemetry = telemetry.createScope(resolvedTelemetryIdentity);\n\n // No TelemetryAgentRunner wrap. The V2 SSE path already emits\n // `agent_execution_stream_*` for this runtime, and since it now emits\n // through this entrypoint's scope, wrapping would put two copies of\n // every stream event on the wire. The class stays exported for callers\n // who construct it themselves. The rawEvent enrichment it used to add\n // moved to `v2/runtime/handlers/shared/sse-response.ts`, so nothing is\n // lost and v2 callers gain it too.\n const runner = params?.runner ?? new InMemoryAgentRunner();\n\n const sharedRuntimeArgs = {\n agents: mergedAgents,\n telemetryId: resolvedTelemetryId,\n licenseToken: resolvedLicenseToken,\n // Emit through this entrypoint's own scope rather than letting the\n // delegated V2 runtime build its own. That scope writes to Segment\n // and stamps the v1 surface, so handing it down is what lets the v1\n // middleware below stop emitting the same events a second time.\n ɵtelemetry: this.telemetry,\n telemetryProperties: params?.telemetryProperties,\n debug: params?.debug,\n // TODO: add support for transcriptionService from CopilotRuntimeOptionsVNext once it is ready\n // transcriptionService: params?.transcriptionService,\n\n beforeRequestMiddleware:\n this.createOnBeforeRequestHandler(params).bind(this),\n ...(params?.afterRequestMiddleware || params?.middleware?.onAfterRequest\n ? {\n afterRequestMiddleware:\n this.createOnAfterRequestHandler(params).bind(this),\n }\n : {}),\n a2ui: params?.a2ui,\n mcpApps: params?.mcpApps,\n openGenerativeUI: params?.openGenerativeUI,\n [runtimeErrorReporterOption]: createRuntimeErrorReporter(params?.onError),\n forwardHeaders: params?.forwardHeaders,\n exposeMemoryRoutes: params?.exposeMemoryRoutes,\n };\n if (params?.intelligence !== undefined) {\n // The compatibility constructor keeps Intelligence identity optional at\n // compile time, while the v2 runtime checks that callers supply web\n // identity, Channels, or both. Preserve that runtime validation here.\n this.runtimeArgs = {\n ...sharedRuntimeArgs,\n intelligence: params.intelligence,\n identifyUser: params.identifyUser,\n memory: params.memory,\n channels: params.channels,\n ɵlearning: params.ɵlearning,\n generateThreadNames: params.generateThreadNames,\n maxReconnectMs: params.maxReconnectMs,\n maxRejoinMs: params.maxRejoinMs,\n heartbeatIntervalMs: params.heartbeatIntervalMs,\n lockTtlSeconds: params.lockTtlSeconds,\n lockKeyPrefix: params.lockKeyPrefix,\n lockHeartbeatIntervalSeconds: params.lockHeartbeatIntervalSeconds,\n } as CopilotRuntimeOptions;\n } else {\n this.runtimeArgs = {\n ...sharedRuntimeArgs,\n runner,\n };\n }\n this.params = params;\n this.observability = params?.observability_c;\n }\n\n get instance() {\n if (!this._instance) {\n this._instance = new CopilotRuntimeVNext(this.runtimeArgs);\n }\n\n return this._instance;\n }\n\n private assignEndpointsToAgents(\n endpoints: CopilotRuntimeConstructorParams<T>[\"remoteEndpoints\"],\n ): Record<string, AbstractAgent> {\n let result: Record<string, AbstractAgent> = {};\n\n if (\n endpoints.some(\n (endpoint) =>\n resolveEndpointType(endpoint) == EndpointType.LangGraphPlatform,\n )\n ) {\n throw new CopilotKitMisuseError({\n message:\n \"LangGraphPlatformEndpoint in remoteEndpoints is deprecated. \" +\n 'Please use the \"agents\" option instead with LangGraphAgent from \"@copilotkit/runtime/langgraph\". ' +\n 'Example: agents: { myAgent: new LangGraphAgent({ deploymentUrl: \"...\", graphId: \"...\" }) }',\n });\n }\n\n return result;\n }\n\n handleServiceAdapter(serviceAdapter: CopilotServiceAdapter) {\n // Capture the configured value before the factory below replaces it, so a\n // second call does not wrap the factory in itself.\n this.configuredAgents ??= this.runtimeArgs.agents ?? {};\n const configuredAgents = this.configuredAgents;\n\n // Resolve the request-independent half once. Calling this twice (the\n // endpoint factory runs on every request under the documented v1 route)\n // must not re-validate or rebuild the default agent.\n //\n // A caller who supplied their own agents factory has no request-independent\n // half: their record is whatever they return for this request, so the same\n // checks run per request further down.\n if (typeof configuredAgents !== \"function\") {\n this.baseAgents ??= Promise.resolve(configuredAgents).then((agents) =>\n this.ensureDefaultAgent(\n agents as Record<string, AbstractAgent>,\n serviceAdapter,\n ),\n );\n // A misconfigured adapter rejects that promise, and nothing awaits it\n // until the first request arrives. Attach an inert handler so a runtime\n // that is never called does not surface an unhandled rejection; the\n // factory below still sees the rejection when it awaits.\n this.baseAgents.catch(() => {});\n }\n\n // Install the per-request factory the v2 runtime has supported since\n // #2941. Resolving once was what kept a dynamic `actions` function from\n // ever seeing request properties, and kept every request sharing one MCP\n // client regardless of whose credentials built it (#7116, #2407).\n const resolvePerRequest = async ({ request }: { request: Request }) => {\n // A caller-supplied agents factory is called here, with this request.\n // Treating it as a record instead (a function has no enumerable keys)\n // meant the service adapter's default replaced it and the caller's\n // function was never invoked at all.\n const baseAgents =\n typeof configuredAgents === \"function\"\n ? this.ensureDefaultAgent(\n { ...(await configuredAgents({ request })) },\n serviceAdapter,\n )\n : await this.baseAgents!;\n const properties = await this.readRequestProperties(request);\n const actions = this.params?.actions;\n\n // `actions` and `mcpServers` are attached independently: a runtime may\n // configure MCP servers without any local actions.\n const mcpSources = await this.getToolsFromMCP({ properties });\n const actionTools = actions\n ? this.getToolsFromActions(actions, { properties, url: request.url })\n : [];\n // An MCP tool that shares a name with an action, or with another\n // server's tool, is prefixed rather than dropped or duplicated.\n const mcpNames = resolveMCPToolNames(\n new Set(actionTools.map((tool) => tool.name)),\n mcpSources.map(({ label, tools }) => ({\n label,\n names: tools.map((tool) => tool.name),\n })),\n \"\",\n );\n const mcpTools = mcpSources.flatMap(({ tools }, i) =>\n tools.map((tool, j) => ({ ...tool, name: mcpNames[i]![j]! })),\n );\n const tools = [...actionTools, ...mcpTools];\n\n // Nothing to attach means nothing to isolate: hand the record back\n // untouched, exactly as a runtime with no actions and no MCP behaved\n // before this became a factory.\n if (!tools.length) {\n return baseAgents;\n }\n\n // Clone before attaching. `assignToolsToAgents` writes `config` onto the\n // agent, so mutating the shared instances would let one request's tools\n // reach another request that is already in flight.\n const perRequestAgents: Record<string, AbstractAgent> = {};\n for (const [agentId, agent] of Object.entries(baseAgents)) {\n const clone = agent.clone() as AbstractAgent;\n // `BuiltInAgent.clone()` rebuilds from `this.config`, so its own tools\n // survive. An agent whose `clone()` does not know about `config` --\n // `HttpAgent`, and anything else a v1 user registered -- would arrive\n // here empty, and the tools it declares itself would be shadowed by a\n // v1 action of the same name. Carry the config across when the clone\n // did not.\n if (\n Reflect.get(clone, \"config\") === undefined &&\n Reflect.get(agent, \"config\") !== undefined\n ) {\n Reflect.set(clone, \"config\", Reflect.get(agent, \"config\"));\n }\n perRequestAgents[agentId] = clone;\n }\n\n return this.assignToolsToAgents(perRequestAgents, tools);\n };\n\n this.runtimeArgs.agents =\n resolvePerRequest as unknown as CopilotRuntimeOptions[\"agents\"];\n }\n\n /**\n * Fill in the default agent the service adapter implies, and reject a\n * configuration that names no model at all.\n */\n private ensureDefaultAgent(\n agentsList: Record<string, AbstractAgent>,\n serviceAdapter: CopilotServiceAdapter,\n ): Record<string, AbstractAgent> {\n const isAgentsListEmpty = !Object.keys(agentsList).length;\n const hasServiceAdapter = Boolean(serviceAdapter);\n const illegalServiceAdapterNames = [\"EmptyAdapter\"];\n const serviceAdapterCanBeUsedForAgent =\n !illegalServiceAdapterNames.includes(serviceAdapter.name);\n\n if (\n isAgentsListEmpty &&\n (!hasServiceAdapter || !serviceAdapterCanBeUsedForAgent)\n ) {\n throw new CopilotKitMisuseError({\n message:\n \"No default agent provided. Please provide a default agent in the runtime config.\",\n });\n }\n\n if (isAgentsListEmpty) {\n const languageModel = serviceAdapter.getLanguageModel?.();\n if (languageModel) {\n // Adapter exposes a pre-configured LanguageModel (e.g. OpenAI/Anthropic adapters)\n agentsList.default = new BuiltInAgent({ model: languageModel });\n } else if (canResolveModel(serviceAdapter)) {\n // Adapter exposes provider/model strings BuiltInAgent understands\n agentsList.default = new BuiltInAgent({\n model: `${serviceAdapter.provider}/${serviceAdapter.model}`,\n });\n } else if (serviceAdapter.name === \"OpenAIAssistantAdapter\") {\n // Its `process()` needs the OpenAI thread and run ids carried between\n // requests, and the Assistants API it calls was shut down by OpenAI on\n // 2026-08-26. Fail clearly rather than run it and fail on the network.\n throw new CopilotKitMisuseError({\n message:\n `OpenAIAssistantAdapter is not supported: OpenAI shut down the Assistants API ` +\n `on 2026-08-26. Use OpenAIAdapter, or a BuiltInAgent in the runtime's agents.`,\n });\n } else {\n // Everything else -- LangChainAdapter's `chainFn`, BedrockAdapter\n // (\"bedrock\" is not a BuiltInAgent provider), custom adapters -- runs\n // through its own `process()`, as in v1 (#3217).\n agentsList.default = new LegacyServiceAdapterAgent(serviceAdapter);\n }\n }\n\n return agentsList;\n }\n\n /**\n * The `forwardedProps` the browser sent with this request, which is what a\n * v1 `actions` function and `mcpServers` overrides are documented to read.\n *\n * `readBody` clones, so the handler still gets an unconsumed body, and it\n * returns `undefined` for GET, which is how the `/info` route reaches here.\n */\n private async readRequestProperties(\n request: Request,\n ): Promise<Record<string, unknown>> {\n try {\n const body = (await readBody(request)) as RunAgentInput | undefined;\n const properties = body?.forwardedProps;\n return properties && typeof properties === \"object\"\n ? (properties as Record<string, unknown>)\n : {};\n } catch {\n // A malformed body is the request handler's problem to report, not a\n // reason to fail agent resolution.\n return {};\n }\n }\n\n // Receive this.params.action and turn it into the AbstractAgent tools\n private getToolsFromActions(\n actions: ActionsConfiguration<any>,\n ctx: { properties: Record<string, unknown>; url?: string },\n ): BuiltInAgentClassicConfig[\"tools\"] {\n // Resolve actions to an array (handle function case).\n //\n // The function form is documented to receive the request's properties and\n // url. It was called once at resolution time with `{ properties: {}, url:\n // undefined }`, so a runtime that keyed its action list on the tenant, the\n // user, or anything else request-shaped got the same empty context every\n // time (#7116).\n const actionsArray =\n typeof actions === \"function\"\n ? actions({ properties: ctx.properties, url: ctx.url })\n : actions;\n\n // Convert each Action to a ToolDefinition\n return actionsArray.map((action) => {\n // Convert JSON schema to Zod schema\n const zodSchema = getZodParameters(action.parameters || []);\n\n return {\n name: action.name,\n description: action.description || \"\",\n parameters: zodSchema,\n // `handler` is an in-process function and was never part of the remote\n // executor deleted in v1.50.0 — only the wiring to it was lost. Call it.\n //\n // The result must never be `undefined`: `JSON.stringify(undefined)` is\n // not a string, which strips the required `content` off\n // TOOL_CALL_RESULT and surfaces as a Zod error in the browser\n // (#2915, #3198). Both branches below return a string instead.\n execute: async (args: unknown) => {\n if (typeof action.handler !== \"function\") {\n return (\n `The tool \"${action.name}\" was advertised without a handler, so it ` +\n `has no implementation to run. Tell the user this tool is unavailable.`\n );\n }\n const result = await action.handler(args as any);\n return result === undefined\n ? `The tool \"${action.name}\" ran and returned no value.`\n : result;\n },\n };\n });\n }\n\n private assignToolsToAgents(\n agents: Record<string, AbstractAgent>,\n tools: BuiltInAgentClassicConfig[\"tools\"],\n ): Record<string, AbstractAgent> {\n if (!tools?.length) {\n return agents;\n }\n\n const enrichedAgents: Record<string, AbstractAgent> = { ...agents };\n\n for (const [agentId, agent] of Object.entries(enrichedAgents)) {\n const existingConfig = (Reflect.get(agent, \"config\") ?? {}) as Record<\n string,\n unknown\n >;\n\n // Skip factory-mode agents — they don't have a tools property\n if (\"factory\" in existingConfig) {\n continue;\n }\n\n const classicConfig =\n existingConfig as unknown as BuiltInAgentClassicConfig;\n const existingTools = classicConfig.tools ?? [];\n\n // The endpoint factory runs `handleServiceAdapter` every time it is\n // called, and the documented v1 route builds the endpoint inside the\n // request handler — so a module-scope runtime lands here once per\n // request. Appending unconditionally advertised N copies of every tool\n // to the model. Skip names the agent already carries, which also leaves\n // a tool the agent defines itself in place.\n const existingNames = new Set(existingTools.map((tool) => tool.name));\n const newTools = tools.filter((tool) => !existingNames.has(tool.name));\n if (newTools.length === 0) {\n continue;\n }\n\n const updatedConfig: BuiltInAgentClassicConfig = {\n ...classicConfig,\n tools: [...existingTools, ...newTools],\n };\n\n Reflect.set(agent, \"config\", updatedConfig);\n enrichedAgents[agentId] = agent;\n }\n\n return enrichedAgents;\n }\n\n private createOnBeforeRequestHandler(\n params?: CopilotRuntimeConstructorParams<T> &\n PartialBy<CopilotRuntimeOptions, \"agents\">,\n ) {\n return async (hookParams: BeforeRequestMiddlewareFnParameters[0]) => {\n const { request } = hookParams;\n\n // No `copilot_request_created` capture here. The V2 handlers this\n // runtime delegates to already emit it, through this runtime's own\n // scope, and they know the route — so `requestType` is \"run\" or\n // \"connect\" rather than the \"unknown\" this site reported for every\n // request that did not set `forwardedProps.metadata.requestType`.\n const body = (await readBody(request)) as RunAgentInput;\n\n // We do not process middleware for the internal GET requests\n if (request.method === \"GET\" || !body) return;\n\n // TODO: get public api key and run with expected data\n // if (this.observability?.enabled && this.params.publicApiKey) {\n // this.logObservabilityBeforeRequest()\n // }\n\n // TODO: replace hooksParams top argument type with BeforeRequestMiddlewareParameters when exported\n const middlewareResult =\n await params?.beforeRequestMiddleware?.(hookParams);\n\n if (params?.middleware?.onBeforeRequest) {\n const { request, runtime, path } = hookParams;\n const gqlMessages = (aguiToGQL(body.messages) as Message[]).reduce(\n (acc, msg) => {\n if (\"role\" in msg && msg.role === \"user\") {\n acc.inputMessages.push(msg);\n } else {\n acc.outputMessages.push(msg);\n }\n return acc;\n },\n { inputMessages: [] as Message[], outputMessages: [] as Message[] },\n );\n const { inputMessages, outputMessages } = gqlMessages;\n params.middleware.onBeforeRequest({\n threadId: body.threadId,\n runId: body.runId,\n inputMessages,\n properties: body.forwardedProps,\n url: request.url,\n } satisfies OnBeforeRequestOptions);\n }\n\n return middlewareResult;\n };\n }\n\n private createOnAfterRequestHandler(\n params?: CopilotRuntimeConstructorParams<T> &\n PartialBy<CopilotRuntimeOptions, \"agents\">,\n ) {\n return async (hookParams: AfterRequestMiddlewareFnParameters[0]) => {\n // TODO: get public api key and run with expected data\n // if (this.observability?.enabled && publicApiKey) {\n // this.logObservabilityAfterRequest()\n // }\n\n // TODO: replace hooksParams top argument type with AfterRequestMiddlewareParameters when exported\n params?.afterRequestMiddleware?.(hookParams);\n\n if (params?.middleware?.onAfterRequest) {\n const messages = hookParams.messages ?? [];\n params.middleware.onAfterRequest({\n threadId: hookParams.threadId ?? \"\",\n runId: hookParams.runId,\n inputMessages: messages.filter(\n (m): m is typeof m & { role: string } =>\n \"role\" in m && m.role === \"user\",\n ) as unknown as Message[],\n outputMessages: messages.filter(\n (m): m is typeof m & { role: string } =>\n \"role\" in m && m.role !== \"user\",\n ) as unknown as Message[],\n // TODO: forward actual properties once the after-request hook has access to the request body\n properties: {},\n url: hookParams.path,\n } satisfies OnAfterRequestOptions);\n }\n };\n }\n\n // Observability Methods\n\n /**\n * Log LLM request if observability is enabled\n */\n private async logObservabilityBeforeRequest(\n requestData: LLMRequestData,\n ): Promise<void> {\n try {\n await this.observability.hooks.handleRequest(requestData);\n } catch (error) {\n console.error(\"Error logging LLM request:\", error);\n }\n }\n\n /**\n * Log final LLM response after request completes\n */\n private logObservabilityAfterRequest(\n outputMessagesPromise: Promise<Message[]>,\n baseData: {\n threadId: string;\n runId?: string;\n model?: string;\n provider?: string;\n agentName?: string;\n nodeName?: string;\n },\n streamedChunks: any[],\n requestStartTime: number,\n publicApiKey?: string,\n ): void {\n try {\n outputMessagesPromise\n .then((outputMessages) => {\n const responseData: LLMResponseData = {\n threadId: baseData.threadId,\n runId: baseData.runId,\n model: baseData.model,\n // Use collected chunks for progressive mode or outputMessages for regular mode\n output: this.observability.progressive\n ? streamedChunks\n : outputMessages,\n latency: Date.now() - requestStartTime,\n timestamp: Date.now(),\n provider: baseData.provider,\n isFinalResponse: true,\n agentName: baseData.agentName,\n nodeName: baseData.nodeName,\n };\n\n try {\n this.observability.hooks.handleResponse(responseData);\n } catch (logError) {\n console.error(\"Error logging LLM response:\", logError);\n }\n })\n .catch((error) => {\n console.error(\"Failed to get output messages for logging:\", error);\n });\n } catch (error) {\n console.error(\"Error setting up logging for LLM response:\", error);\n }\n }\n\n // Resolve MCP tools to BuiltInAgent tool definitions\n // Optionally accepts request-scoped properties to merge request-provided mcpServers\n private async getToolsFromMCP(options?: {\n properties?: Record<string, unknown>;\n }): Promise<\n { label: string; tools: NonNullable<BuiltInAgentClassicConfig[\"tools\"]> }[]\n > {\n const runtimeMcpServers = (this.params?.mcpServers ??\n []) as MCPEndpointConfig[];\n const createMCPClient = this.params?.createMCPClient as\n | CreateMCPClientFunction\n | undefined;\n\n // If no runtime config and no request overrides, nothing to do\n const requestMcpServers = ((\n options?.properties as { mcpServers?: MCPEndpointConfig[] } | undefined\n )?.mcpServers ??\n (\n options?.properties as\n | { mcpEndpoints?: MCPEndpointConfig[] }\n | undefined\n )?.mcpEndpoints ??\n []) as MCPEndpointConfig[];\n\n const hasAnyServers =\n (runtimeMcpServers?.length ?? 0) > 0 ||\n (requestMcpServers?.length ?? 0) > 0;\n if (!hasAnyServers) {\n return [];\n }\n\n if (!createMCPClient) {\n // Mirror legacy behavior: when servers are provided without a factory, treat as misconfiguration\n throw new CopilotKitMisuseError({\n message:\n \"MCP Integration Error: `mcpServers` were provided, but the `createMCPClient` function was not passed to the CopilotRuntime constructor. Please provide an implementation for `createMCPClient`.\",\n });\n }\n\n // Merge and dedupe endpoints by URL; request-level overrides take precedence.\n //\n // `requestMcpServers` is caller-supplied: it arrives in `forwardedProps`\n // from the browser. Validating it here is not this shim's call — the\n // endpoint shape, the transport, and the auth all belong to the\n // application's `createMCPClient`, and a hardcoded allowlist would break\n // the multi-tenant case this per-request path exists to serve. The\n // constraint is documented on `mcpServers` instead: a deployment that does\n // not intend browser-chosen servers has to reject them in its factory.\n const effectiveEndpoints = (() => {\n const byUrl = new Map<string, MCPEndpointConfig>();\n for (const ep of runtimeMcpServers) {\n if (ep?.endpoint) byUrl.set(ep.endpoint, ep);\n }\n for (const ep of requestMcpServers) {\n if (ep?.endpoint) byUrl.set(ep.endpoint, ep);\n }\n return Array.from(byUrl.values());\n })();\n\n const sources: {\n label: string;\n tools: NonNullable<BuiltInAgentClassicConfig[\"tools\"]>;\n }[] = [];\n\n for (const [index, config] of effectiveEndpoints.entries()) {\n // Everything that leaves this process with the endpoint in it uses the\n // redacted form: the raw URL's query can carry the credential, which is\n // exactly what the #2407 workaround puts there.\n const endpointLabel = describeEndpoint(config.endpoint);\n\n try {\n // Keyed by the client factory plus the whole config, so two callers\n // with different credentials for one endpoint get one client each.\n // Keying on the URL alone is #2407: the first caller's client served\n // everyone, and the reporter's `?uid=<hash>` workaround existed only\n // to force distinct keys.\n const entry = await resolveMCPEntry<BuiltInAgentClassicConfig[\"tools\"]>(\n createMCPClient,\n config,\n async () => {\n const client = await createMCPClient(config);\n const toolsMap = await client.tools();\n\n const toolDefs: BuiltInAgentClassicConfig[\"tools\"] = Object.entries(\n toolsMap,\n ).map(([toolName, tool]: [string, MCPTool]) => {\n const params: Parameter[] = extractParametersFromSchema(tool);\n const zodSchema = getZodParameters(params);\n return {\n name: toolName,\n description:\n tool.description ||\n `MCP tool: ${toolName} (from ${endpointLabel})`,\n parameters: zodSchema,\n // `tool.execute` calls the server over the cached client. That\n // client outlives this request but not necessarily this tool\n // definition: eviction can close it while these defs are still\n // held by an already-resolved agent.\n execute: async (args: unknown) => {\n // Executing is the only evidence this runtime gets that a\n // connection is still in use. Without it the entry ages from\n // the moment the agent resolved, and a busy process evicts\n // and closes a client that a live run is still calling.\n touchMCPEntry(createMCPClient, config);\n return tool.execute(args);\n },\n };\n });\n\n return { client, tools: toolDefs };\n },\n );\n\n sources.push({ label: `mcp${index + 1}`, tools: entry.tools ?? [] });\n } catch (error) {\n console.error(\n `MCP: Failed to fetch tools from endpoint ${endpointLabel}. Skipping. Error:`,\n error,\n );\n // Deliberately not cached. Caching the empty result meant a server\n // that was briefly unreachable when the runtime first resolved stayed\n // toolless for the life of that runtime, even after it recovered.\n // `resolveMCPEntry` drops a rejected entry so a later request retries.\n }\n }\n\n return sources;\n }\n}\n\n// The two functions below are \"factory functions\", meant to create the action objects that adhere to the expected interfaces\nexport function copilotKitEndpoint(\n config: Omit<CopilotKitEndpoint, \"type\">,\n): CopilotKitEndpoint {\n return {\n ...config,\n type: EndpointType.CopilotKit,\n };\n}\n\nexport function langGraphPlatformEndpoint(\n config: Omit<LangGraphPlatformEndpoint, \"type\">,\n): LangGraphPlatformEndpoint {\n return {\n ...config,\n type: EndpointType.LangGraphPlatform,\n };\n}\n\nexport function resolveEndpointType(endpoint: EndpointDefinition) {\n if (!endpoint.type) {\n if (\"deploymentUrl\" in endpoint && \"agents\" in endpoint) {\n return EndpointType.LangGraphPlatform;\n } else {\n return EndpointType.CopilotKit;\n }\n }\n\n return endpoint.type;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2bA,SAAS,gBAAgB,gBAAgD;AACvE,KAAI,CAAC,eAAe,YAAY,CAAC,eAAe,MAC9C,QAAO;AAET,KAAI;AACF,6BAAa,GAAG,eAAe,SAAS,GAAG,eAAe,QAAQ;AAClE,SAAO;SACD;AACN,SAAO;;;;;;;;;;;;;;AAeX,IAAa,iBAAb,MAAmE;CAqBjE,YAAY,QAA6C;AACvD,8DAA+B;EAE/B,MAAM,SAAS,QAAQ,UAAU,EAAE;EACnC,MAAM,iBAAiB,KAAK,wBAC1B,QAAQ,mBAAmB,EAAE,CAC9B;EAKD,IAAI;AACJ,MAAI,OAAO,WAAW,WACpB,gBAAe,OAAO,QAAQ;GAC5B,MAAM,WAAW,MAAM,OAAO,IAAI;AAClC,UAAO;IAAE,GAAG;IAAgB,GAAG;IAAU;;MAG3C,gBAAe,QAAQ,QAAQ,OAAO,CAAC,MAAM,cAAc;GACzD,GAAG;GACH,GAAG;GACJ,EAAE;EAML,MAAM,uBAAuBA,qDAC3B,QAAQ,cACR,QAAQ,IAAI,yBACb;EACD,MAAM,uEACJ,QAAQ,aACR,QAAQ,IAAI,iBACb;EACD,MAAM,4BACJ,wBAAwB,SACpB,EAAE,aAAa,qBAAqB,GACpC,yBAAyB,SACvB,EAAE,cAAc,sBAAsB,GACtC,EAAE;AACV,OAAK,YAAYC,iCAAU,YAAY,0BAA0B;EASjE,MAAM,SAAS,QAAQ,UAAU,IAAIC,uCAAqB;EAE1D,MAAM,oBAAoB;GACxB,QAAQ;GACR,aAAa;GACb,cAAc;GAKd,YAAY,KAAK;GACjB,qBAAqB,QAAQ;GA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,QAC2B;AAC3B,QAAO;EACL,GAAG;EACH,MAAMA,2BAAa;EACpB;;AAGH,SAAgB,oBAAoB,UAA8B;AAChE,KAAI,CAAC,SAAS,KACZ,KAAI,mBAAmB,YAAY,YAAY,SAC7C,QAAOA,2BAAa;KAEpB,QAAOA,2BAAa;AAIxB,QAAO,SAAS"}
@@ -44,7 +44,7 @@ interface OnStopGenerationOptions {
44
44
  lastMessage: MessageInput;
45
45
  }
46
46
  type OnStopGenerationHandler = (options: OnStopGenerationOptions) => void | Promise<void>;
47
- interface Middleware {
47
+ interface Middleware$1 {
48
48
  /**
49
49
  * A function that is called before the request is processed.
50
50
  */
@@ -91,7 +91,7 @@ interface CopilotRuntimeConstructorParams_BASE<T extends Parameter[] | [] = []>
91
91
  * @deprecated This middleware hook is deprecated and will be removed in a future version.
92
92
  * Use updated middleware integration methods in CopilotRuntimeVNext instead.
93
93
  */
94
- middleware?: Middleware;
94
+ middleware?: Middleware$1;
95
95
  actions?: ActionsConfiguration<T>;
96
96
  remoteActions?: CopilotKitEndpoint[];
97
97
  remoteEndpoints?: EndpointDefinition[];
@@ -225,7 +225,6 @@ interface CopilotRuntimeConstructorParams<T extends Parameter[] | [] = []> exten
225
225
  maxReconnectMs?: CopilotIntelligenceRuntimeOptions["maxReconnectMs"];
226
226
  maxRejoinMs?: CopilotIntelligenceRuntimeOptions["maxRejoinMs"];
227
227
  heartbeatIntervalMs?: CopilotIntelligenceRuntimeOptions["heartbeatIntervalMs"];
228
- onEventDeliveryStats?: CopilotIntelligenceRuntimeOptions["onEventDeliveryStats"];
229
228
  lockTtlSeconds?: CopilotIntelligenceRuntimeOptions["lockTtlSeconds"];
230
229
  lockKeyPrefix?: CopilotIntelligenceRuntimeOptions["lockKeyPrefix"];
231
230
  lockHeartbeatIntervalSeconds?: CopilotIntelligenceRuntimeOptions["lockHeartbeatIntervalSeconds"];
@@ -1 +1 @@
1
- {"version":3,"file":"copilot-runtime.d.cts","names":[],"sources":["../../../../src/v1-deprecated/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