@copilotkit/runtime 1.72.0 → 1.73.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (195) hide show
  1. package/dist/agent/index.cjs +82 -8
  2. package/dist/agent/index.cjs.map +1 -1
  3. package/dist/agent/index.d.cts +55 -8
  4. package/dist/agent/index.d.cts.map +1 -1
  5. package/dist/agent/index.d.mts +53 -6
  6. package/dist/agent/index.d.mts.map +1 -1
  7. package/dist/agent/index.mjs +83 -10
  8. package/dist/agent/index.mjs.map +1 -1
  9. package/dist/agent/learned-skills.cjs +77 -0
  10. package/dist/agent/learned-skills.cjs.map +1 -0
  11. package/dist/agent/learned-skills.d.cts +16 -0
  12. package/dist/agent/learned-skills.d.cts.map +1 -0
  13. package/dist/agent/learned-skills.d.mts +16 -0
  14. package/dist/agent/learned-skills.d.mts.map +1 -0
  15. package/dist/agent/learned-skills.mjs +75 -0
  16. package/dist/agent/learned-skills.mjs.map +1 -0
  17. package/dist/index.cjs +1 -1
  18. package/dist/index.d.cts +27 -20
  19. package/dist/index.d.mts +27 -20
  20. package/dist/index.mjs +1 -1
  21. package/dist/internal/learned-skills.cjs +22 -0
  22. package/dist/internal/learned-skills.d.cts +10 -0
  23. package/dist/internal/learned-skills.d.mts +10 -0
  24. package/dist/internal/learned-skills.mjs +10 -0
  25. package/dist/langgraph.d.cts +3 -1
  26. package/dist/langgraph.d.mts +3 -1
  27. package/dist/lib/index.cjs +1 -1
  28. package/dist/lib/index.cjs.map +1 -1
  29. package/dist/lib/index.d.cts +2 -2
  30. package/dist/lib/index.d.cts.map +1 -1
  31. package/dist/lib/index.d.mts +2 -2
  32. package/dist/lib/index.d.mts.map +1 -1
  33. package/dist/lib/index.mjs +1 -1
  34. package/dist/lib/index.mjs.map +1 -1
  35. package/dist/lib/integrations/nextjs/app-router.cjs.map +1 -1
  36. package/dist/lib/integrations/nextjs/app-router.mjs.map +1 -1
  37. package/dist/lib/integrations/node-express/index.cjs.map +1 -1
  38. package/dist/lib/integrations/node-express/index.mjs.map +1 -1
  39. package/dist/lib/integrations/node-http/index.cjs.map +1 -1
  40. package/dist/lib/integrations/node-http/index.d.cts.map +1 -1
  41. package/dist/lib/integrations/node-http/index.d.mts.map +1 -1
  42. package/dist/lib/integrations/node-http/index.mjs.map +1 -1
  43. package/dist/lib/integrations/shared.cjs.map +1 -1
  44. package/dist/lib/integrations/shared.d.cts +1 -1
  45. package/dist/lib/integrations/shared.d.cts.map +1 -1
  46. package/dist/lib/integrations/shared.d.mts +1 -1
  47. package/dist/lib/integrations/shared.d.mts.map +1 -1
  48. package/dist/lib/integrations/shared.mjs.map +1 -1
  49. package/dist/lib/runtime/agent-integrations/langgraph/agent.d.cts +1 -1
  50. package/dist/lib/runtime/copilot-runtime.cjs +2 -16
  51. package/dist/lib/runtime/copilot-runtime.cjs.map +1 -1
  52. package/dist/lib/runtime/copilot-runtime.d.cts +2 -2
  53. package/dist/lib/runtime/copilot-runtime.d.cts.map +1 -1
  54. package/dist/lib/runtime/copilot-runtime.d.mts +2 -2
  55. package/dist/lib/runtime/copilot-runtime.d.mts.map +1 -1
  56. package/dist/lib/runtime/copilot-runtime.mjs +3 -17
  57. package/dist/lib/runtime/copilot-runtime.mjs.map +1 -1
  58. package/dist/package.cjs +9 -3
  59. package/dist/package.mjs +9 -3
  60. package/dist/service-adapters/anthropic/anthropic-adapter.cjs.map +1 -1
  61. package/dist/service-adapters/anthropic/anthropic-adapter.d.cts.map +1 -1
  62. package/dist/service-adapters/anthropic/anthropic-adapter.d.mts.map +1 -1
  63. package/dist/service-adapters/anthropic/anthropic-adapter.mjs.map +1 -1
  64. package/dist/service-adapters/shared/sdk-client-utils.cjs.map +1 -1
  65. package/dist/service-adapters/shared/sdk-client-utils.d.cts.map +1 -1
  66. package/dist/service-adapters/shared/sdk-client-utils.d.mts.map +1 -1
  67. package/dist/service-adapters/shared/sdk-client-utils.mjs.map +1 -1
  68. package/dist/v2/index.cjs +7 -0
  69. package/dist/v2/index.d.cts +6 -5
  70. package/dist/v2/index.d.mts +6 -5
  71. package/dist/v2/index.mjs +3 -3
  72. package/dist/v2/runtime/core/channel-manager.d.cts +1 -1
  73. package/dist/v2/runtime/core/channel-manager.d.mts +2 -1
  74. package/dist/v2/runtime/core/channel-manager.d.mts.map +1 -1
  75. package/dist/v2/runtime/core/debug-event-bus.cjs +22 -0
  76. package/dist/v2/runtime/core/debug-event-bus.cjs.map +1 -1
  77. package/dist/v2/runtime/core/debug-event-bus.d.cts +1 -1
  78. package/dist/v2/runtime/core/debug-event-bus.d.mts +1 -1
  79. package/dist/v2/runtime/core/debug-event-bus.mjs +22 -1
  80. package/dist/v2/runtime/core/debug-event-bus.mjs.map +1 -1
  81. package/dist/v2/runtime/core/runtime.cjs +10 -5
  82. package/dist/v2/runtime/core/runtime.cjs.map +1 -1
  83. package/dist/v2/runtime/core/runtime.d.cts +29 -3
  84. package/dist/v2/runtime/core/runtime.d.cts.map +1 -1
  85. package/dist/v2/runtime/core/runtime.d.mts +28 -2
  86. package/dist/v2/runtime/core/runtime.d.mts.map +1 -1
  87. package/dist/v2/runtime/core/runtime.mjs +11 -6
  88. package/dist/v2/runtime/core/runtime.mjs.map +1 -1
  89. package/dist/v2/runtime/handlers/handle-connect.cjs +3 -2
  90. package/dist/v2/runtime/handlers/handle-connect.cjs.map +1 -1
  91. package/dist/v2/runtime/handlers/handle-connect.mjs +3 -2
  92. package/dist/v2/runtime/handlers/handle-connect.mjs.map +1 -1
  93. package/dist/v2/runtime/handlers/handle-debug-events.cjs +2 -1
  94. package/dist/v2/runtime/handlers/handle-debug-events.cjs.map +1 -1
  95. package/dist/v2/runtime/handlers/handle-debug-events.mjs +3 -1
  96. package/dist/v2/runtime/handlers/handle-debug-events.mjs.map +1 -1
  97. package/dist/v2/runtime/handlers/handle-run.cjs +5 -3
  98. package/dist/v2/runtime/handlers/handle-run.cjs.map +1 -1
  99. package/dist/v2/runtime/handlers/handle-run.mjs +5 -3
  100. package/dist/v2/runtime/handlers/handle-run.mjs.map +1 -1
  101. package/dist/v2/runtime/handlers/handle-suggest.cjs +4 -3
  102. package/dist/v2/runtime/handlers/handle-suggest.cjs.map +1 -1
  103. package/dist/v2/runtime/handlers/handle-suggest.mjs +5 -4
  104. package/dist/v2/runtime/handlers/handle-suggest.mjs.map +1 -1
  105. package/dist/v2/runtime/handlers/shared/cloud-telemetry.cjs +31 -0
  106. package/dist/v2/runtime/handlers/shared/cloud-telemetry.cjs.map +1 -0
  107. package/dist/v2/runtime/handlers/shared/cloud-telemetry.mjs +30 -0
  108. package/dist/v2/runtime/handlers/shared/cloud-telemetry.mjs.map +1 -0
  109. package/dist/v2/runtime/handlers/shared/sse-keep-alive.cjs +69 -0
  110. package/dist/v2/runtime/handlers/shared/sse-keep-alive.cjs.map +1 -0
  111. package/dist/v2/runtime/handlers/shared/sse-keep-alive.mjs +67 -0
  112. package/dist/v2/runtime/handlers/shared/sse-keep-alive.mjs.map +1 -0
  113. package/dist/v2/runtime/handlers/shared/sse-response.cjs +35 -4
  114. package/dist/v2/runtime/handlers/shared/sse-response.cjs.map +1 -1
  115. package/dist/v2/runtime/handlers/shared/sse-response.mjs +35 -4
  116. package/dist/v2/runtime/handlers/shared/sse-response.mjs.map +1 -1
  117. package/dist/v2/runtime/handlers/sse/connect.cjs +1 -0
  118. package/dist/v2/runtime/handlers/sse/connect.cjs.map +1 -1
  119. package/dist/v2/runtime/handlers/sse/connect.mjs +1 -0
  120. package/dist/v2/runtime/handlers/sse/connect.mjs.map +1 -1
  121. package/dist/v2/runtime/handlers/sse/run.cjs +2 -0
  122. package/dist/v2/runtime/handlers/sse/run.cjs.map +1 -1
  123. package/dist/v2/runtime/handlers/sse/run.mjs +2 -0
  124. package/dist/v2/runtime/handlers/sse/run.mjs.map +1 -1
  125. package/dist/v2/runtime/index.d.cts +3 -3
  126. package/dist/v2/runtime/index.d.mts +3 -3
  127. package/dist/v2/runtime/intelligence-platform/client.d.cts +1 -1
  128. package/dist/v2/runtime/intelligence-platform/client.d.mts +1 -1
  129. package/dist/v2/runtime/intelligence-platform/skill-registry/archive.cjs +132 -0
  130. package/dist/v2/runtime/intelligence-platform/skill-registry/archive.cjs.map +1 -0
  131. package/dist/v2/runtime/intelligence-platform/skill-registry/archive.d.cts +11 -0
  132. package/dist/v2/runtime/intelligence-platform/skill-registry/archive.d.cts.map +1 -0
  133. package/dist/v2/runtime/intelligence-platform/skill-registry/archive.d.mts +11 -0
  134. package/dist/v2/runtime/intelligence-platform/skill-registry/archive.d.mts.map +1 -0
  135. package/dist/v2/runtime/intelligence-platform/skill-registry/archive.mjs +128 -0
  136. package/dist/v2/runtime/intelligence-platform/skill-registry/archive.mjs.map +1 -0
  137. package/dist/v2/runtime/intelligence-platform/skill-registry/config.cjs +48 -0
  138. package/dist/v2/runtime/intelligence-platform/skill-registry/config.cjs.map +1 -0
  139. package/dist/v2/runtime/intelligence-platform/skill-registry/config.d.cts +27 -0
  140. package/dist/v2/runtime/intelligence-platform/skill-registry/config.d.cts.map +1 -0
  141. package/dist/v2/runtime/intelligence-platform/skill-registry/config.d.mts +27 -0
  142. package/dist/v2/runtime/intelligence-platform/skill-registry/config.d.mts.map +1 -0
  143. package/dist/v2/runtime/intelligence-platform/skill-registry/config.mjs +48 -0
  144. package/dist/v2/runtime/intelligence-platform/skill-registry/config.mjs.map +1 -0
  145. package/dist/v2/runtime/intelligence-platform/skill-registry/errors.cjs +11 -0
  146. package/dist/v2/runtime/intelligence-platform/skill-registry/errors.cjs.map +1 -0
  147. package/dist/v2/runtime/intelligence-platform/skill-registry/errors.d.cts +8 -0
  148. package/dist/v2/runtime/intelligence-platform/skill-registry/errors.d.cts.map +1 -0
  149. package/dist/v2/runtime/intelligence-platform/skill-registry/errors.d.mts +8 -0
  150. package/dist/v2/runtime/intelligence-platform/skill-registry/errors.d.mts.map +1 -0
  151. package/dist/v2/runtime/intelligence-platform/skill-registry/errors.mjs +11 -0
  152. package/dist/v2/runtime/intelligence-platform/skill-registry/errors.mjs.map +1 -0
  153. package/dist/v2/runtime/intelligence-platform/skill-registry/index.d.cts +8 -0
  154. package/dist/v2/runtime/intelligence-platform/skill-registry/index.d.mts +8 -0
  155. package/dist/v2/runtime/intelligence-platform/skill-registry/registry.cjs +132 -0
  156. package/dist/v2/runtime/intelligence-platform/skill-registry/registry.cjs.map +1 -0
  157. package/dist/v2/runtime/intelligence-platform/skill-registry/registry.d.cts +31 -0
  158. package/dist/v2/runtime/intelligence-platform/skill-registry/registry.d.cts.map +1 -0
  159. package/dist/v2/runtime/intelligence-platform/skill-registry/registry.d.mts +31 -0
  160. package/dist/v2/runtime/intelligence-platform/skill-registry/registry.d.mts.map +1 -0
  161. package/dist/v2/runtime/intelligence-platform/skill-registry/registry.mjs +132 -0
  162. package/dist/v2/runtime/intelligence-platform/skill-registry/registry.mjs.map +1 -0
  163. package/dist/v2/runtime/intelligence-platform/skill-registry/skill-content.cjs +42 -0
  164. package/dist/v2/runtime/intelligence-platform/skill-registry/skill-content.cjs.map +1 -0
  165. package/dist/v2/runtime/intelligence-platform/skill-registry/skill-content.d.cts +13 -0
  166. package/dist/v2/runtime/intelligence-platform/skill-registry/skill-content.d.cts.map +1 -0
  167. package/dist/v2/runtime/intelligence-platform/skill-registry/skill-content.d.mts +13 -0
  168. package/dist/v2/runtime/intelligence-platform/skill-registry/skill-content.d.mts.map +1 -0
  169. package/dist/v2/runtime/intelligence-platform/skill-registry/skill-content.mjs +39 -0
  170. package/dist/v2/runtime/intelligence-platform/skill-registry/skill-content.mjs.map +1 -0
  171. package/dist/v2/runtime/intelligence-platform/skill-registry/snapshot.cjs +93 -0
  172. package/dist/v2/runtime/intelligence-platform/skill-registry/snapshot.cjs.map +1 -0
  173. package/dist/v2/runtime/intelligence-platform/skill-registry/snapshot.d.cts +28 -0
  174. package/dist/v2/runtime/intelligence-platform/skill-registry/snapshot.d.cts.map +1 -0
  175. package/dist/v2/runtime/intelligence-platform/skill-registry/snapshot.d.mts +28 -0
  176. package/dist/v2/runtime/intelligence-platform/skill-registry/snapshot.d.mts.map +1 -0
  177. package/dist/v2/runtime/intelligence-platform/skill-registry/snapshot.mjs +92 -0
  178. package/dist/v2/runtime/intelligence-platform/skill-registry/snapshot.mjs.map +1 -0
  179. package/dist/v2/runtime/runner/agent-runner.d.cts +1 -1
  180. package/dist/v2/runtime/runner/in-memory.d.cts +1 -1
  181. package/dist/v2/runtime/runner/index.d.cts +2 -2
  182. package/dist/v2/runtime/runner/index.d.mts +2 -2
  183. package/dist/v2/runtime/runner/index.mjs +2 -2
  184. package/dist/v2/runtime/runner/intelligence.d.cts +1 -1
  185. package/dist/v2/runtime/telemetry/events.d.cts +12 -0
  186. package/dist/v2/runtime/telemetry/events.d.cts.map +1 -1
  187. package/dist/v2/runtime/telemetry/events.d.mts +12 -0
  188. package/dist/v2/runtime/telemetry/events.d.mts.map +1 -1
  189. package/dist/v2/runtime/telemetry/telemetry-client.cjs +3 -2
  190. package/dist/v2/runtime/telemetry/telemetry-client.cjs.map +1 -1
  191. package/dist/v2/runtime/telemetry/telemetry-client.d.cts.map +1 -1
  192. package/dist/v2/runtime/telemetry/telemetry-client.d.mts.map +1 -1
  193. package/dist/v2/runtime/telemetry/telemetry-client.mjs +7 -6
  194. package/dist/v2/runtime/telemetry/telemetry-client.mjs.map +1 -1
  195. package/package.json +9 -3
@@ -1 +1 @@
1
- {"version":3,"file":"app-router.cjs","names":["getCommonConfig","getRuntimeInstanceTelemetryInfo","createCopilotEndpointSingleRoute"],"sources":["../../../../../src/v1-deprecated/lib/integrations/nextjs/app-router.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 — copilotRuntimeNextJSAppRouterEndpoint:\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\nimport { createCopilotEndpointSingleRoute } from \"../../../../v2/runtime\";\nimport type { CreateCopilotRuntimeServerOptions } from \"../shared\";\nimport { getCommonConfig } from \"../shared\";\nimport telemetry, {\n getRuntimeInstanceTelemetryInfo,\n} from \"../../telemetry-client\";\nimport { handle } from \"hono/vercel\";\n\nexport function copilotRuntimeNextJSAppRouterEndpoint(\n options: CreateCopilotRuntimeServerOptions,\n) {\n const commonConfig = getCommonConfig(options);\n\n telemetry.setGlobalProperties({\n runtime: {\n framework: \"nextjs-app-router\",\n },\n });\n\n if (options.properties?._copilotkit) {\n telemetry.setGlobalProperties({\n _copilotkit: options.properties._copilotkit,\n });\n }\n\n options.runtime.telemetry.capture(\n \"oss.runtime.instance_created\",\n getRuntimeInstanceTelemetryInfo(options),\n );\n\n const logger = commonConfig.logging;\n logger.debug(\"Creating NextJS App Router endpoint\");\n\n const serviceAdapter = options.serviceAdapter;\n if (serviceAdapter) {\n options.runtime.handleServiceAdapter(serviceAdapter);\n }\n\n // Note: cors option requires @copilotkit/runtime with credentials support\n const copilotRoute = createCopilotEndpointSingleRoute({\n runtime: options.runtime.instance,\n basePath: options.baseUrl ?? options.endpoint,\n ...(options.cors && { cors: options.cors }),\n } as any);\n\n const handleRequest = handle(copilotRoute as any);\n return { handleRequest };\n}\n"],"mappings":";;;;;;;;AA2BA,SAAgB,sCACd,SACA;CACA,MAAM,eAAeA,+BAAgB,QAAQ;AAE7C,kCAAU,oBAAoB,EAC5B,SAAS,EACP,WAAW,qBACZ,EACF,CAAC;AAEF,KAAI,QAAQ,YAAY,YACtB,kCAAU,oBAAoB,EAC5B,aAAa,QAAQ,WAAW,aACjC,CAAC;AAGJ,SAAQ,QAAQ,UAAU,QACxB,gCACAC,yDAAgC,QAAQ,CACzC;AAGD,CADe,aAAa,QACrB,MAAM,sCAAsC;CAEnD,MAAM,iBAAiB,QAAQ;AAC/B,KAAI,eACF,SAAQ,QAAQ,qBAAqB,eAAe;AAWtD,QAAO,EAAE,uCAPYC,qDAAiC;EACpD,SAAS,QAAQ,QAAQ;EACzB,UAAU,QAAQ,WAAW,QAAQ;EACrC,GAAI,QAAQ,QAAQ,EAAE,MAAM,QAAQ,MAAM;EAC3C,CAAQ,CAEwC,EACzB"}
1
+ {"version":3,"file":"app-router.cjs","names":["getCommonConfig","getRuntimeInstanceTelemetryInfo","createCopilotEndpointSingleRoute"],"sources":["../../../../../src/v1-deprecated/lib/integrations/nextjs/app-router.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 — copilotRuntimeNextJSAppRouterEndpoint:\n * V2 import and usage:\n * import { createCopilotRuntimeHandler } from \"@copilotkit/runtime/v2\";\n * const v2CreateCopilotRuntimeHandler = createCopilotRuntimeHandler;\n * V2 replacement source: packages/runtime/src/v2/runtime/core/fetch-handler.ts\n * V2 docs: https://docs.copilotkit.ai/runtime-server-adapter\n *\n * Migration guide: https://docs.copilotkit.ai/migrate/v2\n *\n * END V1 SDK DEPRECATED. USE V2 INSTEAD NOTICE\n */\n\nimport { createCopilotEndpointSingleRoute } from \"../../../../v2/runtime\";\nimport type { CreateCopilotRuntimeServerOptions } from \"../shared\";\nimport { getCommonConfig } from \"../shared\";\nimport telemetry, {\n getRuntimeInstanceTelemetryInfo,\n} from \"../../telemetry-client\";\nimport { handle } from \"hono/vercel\";\n\nexport function copilotRuntimeNextJSAppRouterEndpoint(\n options: CreateCopilotRuntimeServerOptions,\n) {\n const commonConfig = getCommonConfig(options);\n\n telemetry.setGlobalProperties({\n runtime: {\n framework: \"nextjs-app-router\",\n },\n });\n\n if (options.properties?._copilotkit) {\n telemetry.setGlobalProperties({\n _copilotkit: options.properties._copilotkit,\n });\n }\n\n options.runtime.telemetry.capture(\n \"oss.runtime.instance_created\",\n getRuntimeInstanceTelemetryInfo(options),\n );\n\n const logger = commonConfig.logging;\n logger.debug(\"Creating NextJS App Router endpoint\");\n\n const serviceAdapter = options.serviceAdapter;\n if (serviceAdapter) {\n options.runtime.handleServiceAdapter(serviceAdapter);\n }\n\n // Note: cors option requires @copilotkit/runtime with credentials support\n const copilotRoute = createCopilotEndpointSingleRoute({\n runtime: options.runtime.instance,\n basePath: options.baseUrl ?? options.endpoint,\n ...(options.cors && { cors: options.cors }),\n } as any);\n\n const handleRequest = handle(copilotRoute as any);\n return { handleRequest };\n}\n"],"mappings":";;;;;;;;AA2BA,SAAgB,sCACd,SACA;CACA,MAAM,eAAeA,+BAAgB,QAAQ;AAE7C,kCAAU,oBAAoB,EAC5B,SAAS,EACP,WAAW,qBACZ,EACF,CAAC;AAEF,KAAI,QAAQ,YAAY,YACtB,kCAAU,oBAAoB,EAC5B,aAAa,QAAQ,WAAW,aACjC,CAAC;AAGJ,SAAQ,QAAQ,UAAU,QACxB,gCACAC,yDAAgC,QAAQ,CACzC;AAGD,CADe,aAAa,QACrB,MAAM,sCAAsC;CAEnD,MAAM,iBAAiB,QAAQ;AAC/B,KAAI,eACF,SAAQ,QAAQ,qBAAqB,eAAe;AAWtD,QAAO,EAAE,uCAPYC,qDAAiC;EACpD,SAAS,QAAQ,QAAQ;EACzB,UAAU,QAAQ,WAAW,QAAQ;EACrC,GAAI,QAAQ,QAAQ,EAAE,MAAM,QAAQ,MAAM;EAC3C,CAAQ,CAEwC,EACzB"}
@@ -1 +1 @@
1
- {"version":3,"file":"app-router.mjs","names":[],"sources":["../../../../../src/v1-deprecated/lib/integrations/nextjs/app-router.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 — copilotRuntimeNextJSAppRouterEndpoint:\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\nimport { createCopilotEndpointSingleRoute } from \"../../../../v2/runtime\";\nimport type { CreateCopilotRuntimeServerOptions } from \"../shared\";\nimport { getCommonConfig } from \"../shared\";\nimport telemetry, {\n getRuntimeInstanceTelemetryInfo,\n} from \"../../telemetry-client\";\nimport { handle } from \"hono/vercel\";\n\nexport function copilotRuntimeNextJSAppRouterEndpoint(\n options: CreateCopilotRuntimeServerOptions,\n) {\n const commonConfig = getCommonConfig(options);\n\n telemetry.setGlobalProperties({\n runtime: {\n framework: \"nextjs-app-router\",\n },\n });\n\n if (options.properties?._copilotkit) {\n telemetry.setGlobalProperties({\n _copilotkit: options.properties._copilotkit,\n });\n }\n\n options.runtime.telemetry.capture(\n \"oss.runtime.instance_created\",\n getRuntimeInstanceTelemetryInfo(options),\n );\n\n const logger = commonConfig.logging;\n logger.debug(\"Creating NextJS App Router endpoint\");\n\n const serviceAdapter = options.serviceAdapter;\n if (serviceAdapter) {\n options.runtime.handleServiceAdapter(serviceAdapter);\n }\n\n // Note: cors option requires @copilotkit/runtime with credentials support\n const copilotRoute = createCopilotEndpointSingleRoute({\n runtime: options.runtime.instance,\n basePath: options.baseUrl ?? options.endpoint,\n ...(options.cors && { cors: options.cors }),\n } as any);\n\n const handleRequest = handle(copilotRoute as any);\n return { handleRequest };\n}\n"],"mappings":";;;;;;;AA2BA,SAAgB,sCACd,SACA;CACA,MAAM,eAAe,gBAAgB,QAAQ;AAE7C,iBAAU,oBAAoB,EAC5B,SAAS,EACP,WAAW,qBACZ,EACF,CAAC;AAEF,KAAI,QAAQ,YAAY,YACtB,iBAAU,oBAAoB,EAC5B,aAAa,QAAQ,WAAW,aACjC,CAAC;AAGJ,SAAQ,QAAQ,UAAU,QACxB,gCACA,gCAAgC,QAAQ,CACzC;AAGD,CADe,aAAa,QACrB,MAAM,sCAAsC;CAEnD,MAAM,iBAAiB,QAAQ;AAC/B,KAAI,eACF,SAAQ,QAAQ,qBAAqB,eAAe;AAWtD,QAAO,EAAE,eADa,OAND,iCAAiC;EACpD,SAAS,QAAQ,QAAQ;EACzB,UAAU,QAAQ,WAAW,QAAQ;EACrC,GAAI,QAAQ,QAAQ,EAAE,MAAM,QAAQ,MAAM;EAC3C,CAAQ,CAEwC,EACzB"}
1
+ {"version":3,"file":"app-router.mjs","names":[],"sources":["../../../../../src/v1-deprecated/lib/integrations/nextjs/app-router.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 — copilotRuntimeNextJSAppRouterEndpoint:\n * V2 import and usage:\n * import { createCopilotRuntimeHandler } from \"@copilotkit/runtime/v2\";\n * const v2CreateCopilotRuntimeHandler = createCopilotRuntimeHandler;\n * V2 replacement source: packages/runtime/src/v2/runtime/core/fetch-handler.ts\n * V2 docs: https://docs.copilotkit.ai/runtime-server-adapter\n *\n * Migration guide: https://docs.copilotkit.ai/migrate/v2\n *\n * END V1 SDK DEPRECATED. USE V2 INSTEAD NOTICE\n */\n\nimport { createCopilotEndpointSingleRoute } from \"../../../../v2/runtime\";\nimport type { CreateCopilotRuntimeServerOptions } from \"../shared\";\nimport { getCommonConfig } from \"../shared\";\nimport telemetry, {\n getRuntimeInstanceTelemetryInfo,\n} from \"../../telemetry-client\";\nimport { handle } from \"hono/vercel\";\n\nexport function copilotRuntimeNextJSAppRouterEndpoint(\n options: CreateCopilotRuntimeServerOptions,\n) {\n const commonConfig = getCommonConfig(options);\n\n telemetry.setGlobalProperties({\n runtime: {\n framework: \"nextjs-app-router\",\n },\n });\n\n if (options.properties?._copilotkit) {\n telemetry.setGlobalProperties({\n _copilotkit: options.properties._copilotkit,\n });\n }\n\n options.runtime.telemetry.capture(\n \"oss.runtime.instance_created\",\n getRuntimeInstanceTelemetryInfo(options),\n );\n\n const logger = commonConfig.logging;\n logger.debug(\"Creating NextJS App Router endpoint\");\n\n const serviceAdapter = options.serviceAdapter;\n if (serviceAdapter) {\n options.runtime.handleServiceAdapter(serviceAdapter);\n }\n\n // Note: cors option requires @copilotkit/runtime with credentials support\n const copilotRoute = createCopilotEndpointSingleRoute({\n runtime: options.runtime.instance,\n basePath: options.baseUrl ?? options.endpoint,\n ...(options.cors && { cors: options.cors }),\n } as any);\n\n const handleRequest = handle(copilotRoute as any);\n return { handleRequest };\n}\n"],"mappings":";;;;;;;AA2BA,SAAgB,sCACd,SACA;CACA,MAAM,eAAe,gBAAgB,QAAQ;AAE7C,iBAAU,oBAAoB,EAC5B,SAAS,EACP,WAAW,qBACZ,EACF,CAAC;AAEF,KAAI,QAAQ,YAAY,YACtB,iBAAU,oBAAoB,EAC5B,aAAa,QAAQ,WAAW,aACjC,CAAC;AAGJ,SAAQ,QAAQ,UAAU,QACxB,gCACA,gCAAgC,QAAQ,CACzC;AAGD,CADe,aAAa,QACrB,MAAM,sCAAsC;CAEnD,MAAM,iBAAiB,QAAQ;AAC/B,KAAI,eACF,SAAQ,QAAQ,qBAAqB,eAAe;AAWtD,QAAO,EAAE,eADa,OAND,iCAAiC;EACpD,SAAS,QAAQ,QAAQ;EACzB,UAAU,QAAQ,WAAW,QAAQ;EACrC,GAAI,QAAQ,QAAQ,EAAE,MAAM,QAAQ,MAAM;EAC3C,CAAQ,CAEwC,EACzB"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["getRuntimeInstanceTelemetryInfo","copilotRuntimeNodeHttpEndpoint"],"sources":["../../../../../src/v1-deprecated/lib/integrations/node-express/index.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 — copilotRuntimeNodeExpressEndpoint:\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\nimport type { CreateCopilotRuntimeServerOptions } from \"../shared\";\nimport { copilotRuntimeNodeHttpEndpoint } from \"../node-http\";\nimport telemetry, {\n getRuntimeInstanceTelemetryInfo,\n} from \"../../telemetry-client\";\n\nexport function copilotRuntimeNodeExpressEndpoint(\n options: CreateCopilotRuntimeServerOptions,\n) {\n telemetry.setGlobalProperties({\n runtime: {\n framework: \"node-express\",\n },\n });\n\n options.runtime.telemetry.capture(\n \"oss.runtime.instance_created\",\n getRuntimeInstanceTelemetryInfo(options),\n );\n return copilotRuntimeNodeHttpEndpoint(options);\n}\n"],"mappings":";;;;;AAyBA,SAAgB,kCACd,SACA;AACA,kCAAU,oBAAoB,EAC5B,SAAS,EACP,WAAW,gBACZ,EACF,CAAC;AAEF,SAAQ,QAAQ,UAAU,QACxB,gCACAA,yDAAgC,QAAQ,CACzC;AACD,QAAOC,6CAA+B,QAAQ"}
1
+ {"version":3,"file":"index.cjs","names":["getRuntimeInstanceTelemetryInfo","copilotRuntimeNodeHttpEndpoint"],"sources":["../../../../../src/v1-deprecated/lib/integrations/node-express/index.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 — copilotRuntimeNodeExpressEndpoint:\n * V2 import and usage:\n * import { createCopilotExpressHandler } from \"@copilotkit/runtime/v2/express\";\n * const v2CreateCopilotExpressHandler = createCopilotExpressHandler;\n * V2 replacement source: packages/runtime/src/v2/runtime/endpoints/express.ts\n * V2 docs: https://docs.copilotkit.ai/runtime-server-adapter\n *\n * Migration guide: https://docs.copilotkit.ai/migrate/v2\n *\n * END V1 SDK DEPRECATED. USE V2 INSTEAD NOTICE\n */\n\nimport type { CreateCopilotRuntimeServerOptions } from \"../shared\";\nimport { copilotRuntimeNodeHttpEndpoint } from \"../node-http\";\nimport telemetry, {\n getRuntimeInstanceTelemetryInfo,\n} from \"../../telemetry-client\";\n\nexport function copilotRuntimeNodeExpressEndpoint(\n options: CreateCopilotRuntimeServerOptions,\n) {\n telemetry.setGlobalProperties({\n runtime: {\n framework: \"node-express\",\n },\n });\n\n options.runtime.telemetry.capture(\n \"oss.runtime.instance_created\",\n getRuntimeInstanceTelemetryInfo(options),\n );\n return copilotRuntimeNodeHttpEndpoint(options);\n}\n"],"mappings":";;;;;AAyBA,SAAgB,kCACd,SACA;AACA,kCAAU,oBAAoB,EAC5B,SAAS,EACP,WAAW,gBACZ,EACF,CAAC;AAEF,SAAQ,QAAQ,UAAU,QACxB,gCACAA,yDAAgC,QAAQ,CACzC;AACD,QAAOC,6CAA+B,QAAQ"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../../../../src/v1-deprecated/lib/integrations/node-express/index.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 — copilotRuntimeNodeExpressEndpoint:\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\nimport type { CreateCopilotRuntimeServerOptions } from \"../shared\";\nimport { copilotRuntimeNodeHttpEndpoint } from \"../node-http\";\nimport telemetry, {\n getRuntimeInstanceTelemetryInfo,\n} from \"../../telemetry-client\";\n\nexport function copilotRuntimeNodeExpressEndpoint(\n options: CreateCopilotRuntimeServerOptions,\n) {\n telemetry.setGlobalProperties({\n runtime: {\n framework: \"node-express\",\n },\n });\n\n options.runtime.telemetry.capture(\n \"oss.runtime.instance_created\",\n getRuntimeInstanceTelemetryInfo(options),\n );\n return copilotRuntimeNodeHttpEndpoint(options);\n}\n"],"mappings":";;;;;AAyBA,SAAgB,kCACd,SACA;AACA,iBAAU,oBAAoB,EAC5B,SAAS,EACP,WAAW,gBACZ,EACF,CAAC;AAEF,SAAQ,QAAQ,UAAU,QACxB,gCACA,gCAAgC,QAAQ,CACzC;AACD,QAAO,+BAA+B,QAAQ"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../../../../src/v1-deprecated/lib/integrations/node-express/index.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 — copilotRuntimeNodeExpressEndpoint:\n * V2 import and usage:\n * import { createCopilotExpressHandler } from \"@copilotkit/runtime/v2/express\";\n * const v2CreateCopilotExpressHandler = createCopilotExpressHandler;\n * V2 replacement source: packages/runtime/src/v2/runtime/endpoints/express.ts\n * V2 docs: https://docs.copilotkit.ai/runtime-server-adapter\n *\n * Migration guide: https://docs.copilotkit.ai/migrate/v2\n *\n * END V1 SDK DEPRECATED. USE V2 INSTEAD NOTICE\n */\n\nimport type { CreateCopilotRuntimeServerOptions } from \"../shared\";\nimport { copilotRuntimeNodeHttpEndpoint } from \"../node-http\";\nimport telemetry, {\n getRuntimeInstanceTelemetryInfo,\n} from \"../../telemetry-client\";\n\nexport function copilotRuntimeNodeExpressEndpoint(\n options: CreateCopilotRuntimeServerOptions,\n) {\n telemetry.setGlobalProperties({\n runtime: {\n framework: \"node-express\",\n },\n });\n\n options.runtime.telemetry.capture(\n \"oss.runtime.instance_created\",\n getRuntimeInstanceTelemetryInfo(options),\n );\n return copilotRuntimeNodeHttpEndpoint(options);\n}\n"],"mappings":";;;;;AAyBA,SAAgB,kCACd,SACA;AACA,iBAAU,oBAAoB,EAC5B,SAAS,EACP,WAAW,gBACZ,EACF,CAAC;AAEF,SAAQ,QAAQ,UAAU,QACxB,gCACA,gCAAgC,QAAQ,CACzC;AACD,QAAO,+BAA+B,QAAQ"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["getCommonConfig","getRuntimeInstanceTelemetryInfo","createCopilotEndpointSingleRoute","getFullUrl","toHeaders","isStreamConsumed","nodeStreamToReadableStream","synthesizeBodyFromParsedBody","isDisturbedOrLockedError"],"sources":["../../../../../src/v1-deprecated/lib/integrations/node-http/index.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 — copilotRuntimeNodeHttpEndpoint:\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 */\nimport type { CreateCopilotRuntimeServerOptions } from \"../shared\";\nimport { getCommonConfig } from \"../shared\";\nimport telemetry, {\n getRuntimeInstanceTelemetryInfo,\n} from \"../../telemetry-client\";\nimport { createCopilotEndpointSingleRoute } from \"../../../../v2/runtime\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport type { IncomingWithBody } from \"./request-handler\";\nimport {\n getFullUrl,\n isDisturbedOrLockedError,\n isStreamConsumed,\n nodeStreamToReadableStream,\n readableStreamToNodeStream,\n synthesizeBodyFromParsedBody,\n toHeaders,\n} from \"./request-handler\";\n\nexport function copilotRuntimeNodeHttpEndpoint(\n options: CreateCopilotRuntimeServerOptions,\n) {\n const commonConfig = getCommonConfig(options);\n\n telemetry.setGlobalProperties({\n runtime: {\n framework: \"node-http\",\n },\n });\n\n if (options.properties?._copilotkit) {\n telemetry.setGlobalProperties({\n _copilotkit: options.properties._copilotkit,\n });\n }\n\n options.runtime.telemetry.capture(\n \"oss.runtime.instance_created\",\n getRuntimeInstanceTelemetryInfo(options),\n );\n\n const logger = commonConfig.logging;\n logger.debug(\"Creating Node HTTP endpoint\");\n\n const serviceAdapter = options.serviceAdapter;\n if (serviceAdapter) {\n options.runtime.handleServiceAdapter(serviceAdapter);\n }\n\n // Note: cors option requires @copilotkit/runtime with credentials support\n const honoApp = createCopilotEndpointSingleRoute({\n runtime: options.runtime.instance,\n basePath: options.baseUrl ?? options.endpoint,\n ...(options.cors && { cors: options.cors }),\n } as any);\n\n const handle = async function handler(\n req: IncomingWithBody,\n res: ServerResponse,\n ) {\n const url = getFullUrl(req);\n const hasBody = req.method !== \"GET\" && req.method !== \"HEAD\";\n\n const baseHeaders = toHeaders(req.headers);\n const parsedBody = req.body;\n\n const streamConsumed = isStreamConsumed(req) || parsedBody !== undefined;\n const canStream = hasBody && !streamConsumed;\n\n let requestBody: BodyInit | null | undefined = undefined;\n let useDuplex = false;\n\n if (hasBody && canStream) {\n requestBody = nodeStreamToReadableStream(req);\n useDuplex = true;\n }\n\n if (hasBody && streamConsumed) {\n if (parsedBody !== undefined) {\n const synthesized = synthesizeBodyFromParsedBody(\n parsedBody,\n baseHeaders,\n );\n requestBody = synthesized.body ?? undefined;\n baseHeaders.delete(\"content-length\");\n\n if (synthesized.contentType) {\n baseHeaders.set(\"content-type\", synthesized.contentType);\n }\n\n logger.debug(\n \"Request stream already consumed; using parsed req.body to rebuild request.\",\n );\n } else {\n logger.warn(\n \"Request stream consumed with no available body; sending empty payload.\",\n );\n requestBody = undefined;\n }\n }\n\n const buildRequest = (\n body: BodyInit | null | undefined,\n headers: Headers,\n duplex: boolean,\n ) =>\n new Request(url, {\n method: req.method,\n headers,\n body,\n duplex: duplex ? \"half\" : undefined,\n } as RequestInit);\n\n let response: Response;\n try {\n response = await honoApp.fetch(\n buildRequest(requestBody, baseHeaders, useDuplex),\n );\n } catch (error) {\n if (isDisturbedOrLockedError(error) && hasBody) {\n logger.warn(\n \"Encountered disturbed/locked request body; rebuilding request using parsed body or empty payload.\",\n );\n\n const fallbackHeaders = new Headers(baseHeaders);\n let fallbackBody: BodyInit | null | undefined;\n\n if (parsedBody !== undefined) {\n const synthesized = synthesizeBodyFromParsedBody(\n parsedBody,\n fallbackHeaders,\n );\n fallbackBody = synthesized.body ?? undefined;\n fallbackHeaders.delete(\"content-length\");\n\n if (synthesized.contentType) {\n fallbackHeaders.set(\"content-type\", synthesized.contentType);\n }\n } else {\n fallbackBody = undefined;\n }\n\n response = await honoApp.fetch(\n buildRequest(fallbackBody, fallbackHeaders, false),\n );\n } else {\n throw error;\n }\n }\n\n res.statusCode = response.status;\n response.headers.forEach((value, key) => {\n res.setHeader(key, value);\n });\n\n if (response.body) {\n readableStreamToNodeStream(response.body).pipe(res);\n } else {\n res.end();\n }\n };\n\n // Duck-type check for Request-like objects (handles polyfilled Request from @hono/node-server)\n function isRequestLike(obj: unknown): obj is Request {\n return (\n obj instanceof Request ||\n (typeof obj === \"object\" &&\n obj !== null &&\n \"url\" in obj &&\n \"method\" in obj &&\n \"headers\" in obj &&\n typeof (obj as any).url === \"string\" &&\n typeof (obj as any).method === \"string\")\n );\n }\n\n return function (\n reqOrRequest: IncomingMessage | Request,\n res?: ServerResponse,\n ): Promise<void> | Promise<Response> | Response {\n if (isRequestLike(reqOrRequest) && !res) {\n return honoApp.fetch(reqOrRequest as Request);\n }\n if (!res) {\n throw new TypeError(\"ServerResponse is required for Node HTTP requests\");\n }\n return handle(reqOrRequest as IncomingMessage, res);\n };\n}\n"],"mappings":";;;;;;;AAoCA,SAAgB,+BACd,SACA;CACA,MAAM,eAAeA,+BAAgB,QAAQ;AAE7C,kCAAU,oBAAoB,EAC5B,SAAS,EACP,WAAW,aACZ,EACF,CAAC;AAEF,KAAI,QAAQ,YAAY,YACtB,kCAAU,oBAAoB,EAC5B,aAAa,QAAQ,WAAW,aACjC,CAAC;AAGJ,SAAQ,QAAQ,UAAU,QACxB,gCACAC,yDAAgC,QAAQ,CACzC;CAED,MAAM,SAAS,aAAa;AAC5B,QAAO,MAAM,8BAA8B;CAE3C,MAAM,iBAAiB,QAAQ;AAC/B,KAAI,eACF,SAAQ,QAAQ,qBAAqB,eAAe;CAItD,MAAM,UAAUC,qDAAiC;EAC/C,SAAS,QAAQ,QAAQ;EACzB,UAAU,QAAQ,WAAW,QAAQ;EACrC,GAAI,QAAQ,QAAQ,EAAE,MAAM,QAAQ,MAAM;EAC3C,CAAQ;CAET,MAAM,SAAS,eAAe,QAC5B,KACA,KACA;EACA,MAAM,MAAMC,mCAAW,IAAI;EAC3B,MAAM,UAAU,IAAI,WAAW,SAAS,IAAI,WAAW;EAEvD,MAAM,cAAcC,kCAAU,IAAI,QAAQ;EAC1C,MAAM,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CAKb,SAAS,cAAc,KAA8B;AACnD,SACE,eAAe,WACd,OAAO,QAAQ,YACd,QAAQ,QACR,SAAS,OACT,YAAY,OACZ,aAAa,OACb,OAAQ,IAAY,QAAQ,YAC5B,OAAQ,IAAY,WAAW;;AAIrC,QAAO,SACL,cACA,KAC8C;AAC9C,MAAI,cAAc,aAAa,IAAI,CAAC,IAClC,QAAO,QAAQ,MAAM,aAAwB;AAE/C,MAAI,CAAC,IACH,OAAM,IAAI,UAAU,oDAAoD;AAE1E,SAAO,OAAO,cAAiC,IAAI"}
1
+ {"version":3,"file":"index.cjs","names":["getCommonConfig","getRuntimeInstanceTelemetryInfo","createCopilotEndpointSingleRoute","getFullUrl","toHeaders","isStreamConsumed","nodeStreamToReadableStream","synthesizeBodyFromParsedBody","isDisturbedOrLockedError"],"sources":["../../../../../src/v1-deprecated/lib/integrations/node-http/index.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 — copilotRuntimeNodeHttpEndpoint:\n * V2 import and usage:\n * import { createCopilotRuntimeHandler } from \"@copilotkit/runtime/v2\";\n * const v2CreateCopilotRuntimeHandler = createCopilotRuntimeHandler;\n * V2 replacement source: packages/runtime/src/v2/runtime/core/fetch-handler.ts\n * V2 docs: https://docs.copilotkit.ai/runtime-server-adapter\n *\n * Migration guide: https://docs.copilotkit.ai/migrate/v2\n *\n * END V1 SDK DEPRECATED. USE V2 INSTEAD NOTICE\n */\n\nimport type { CreateCopilotRuntimeServerOptions } from \"../shared\";\nimport { getCommonConfig } from \"../shared\";\nimport telemetry, {\n getRuntimeInstanceTelemetryInfo,\n} from \"../../telemetry-client\";\nimport { createCopilotEndpointSingleRoute } from \"../../../../v2/runtime\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport type { IncomingWithBody } from \"./request-handler\";\nimport {\n getFullUrl,\n isDisturbedOrLockedError,\n isStreamConsumed,\n nodeStreamToReadableStream,\n readableStreamToNodeStream,\n synthesizeBodyFromParsedBody,\n toHeaders,\n} from \"./request-handler\";\n\nexport function copilotRuntimeNodeHttpEndpoint(\n options: CreateCopilotRuntimeServerOptions,\n) {\n const commonConfig = getCommonConfig(options);\n\n telemetry.setGlobalProperties({\n runtime: {\n framework: \"node-http\",\n },\n });\n\n if (options.properties?._copilotkit) {\n telemetry.setGlobalProperties({\n _copilotkit: options.properties._copilotkit,\n });\n }\n\n options.runtime.telemetry.capture(\n \"oss.runtime.instance_created\",\n getRuntimeInstanceTelemetryInfo(options),\n );\n\n const logger = commonConfig.logging;\n logger.debug(\"Creating Node HTTP endpoint\");\n\n const serviceAdapter = options.serviceAdapter;\n if (serviceAdapter) {\n options.runtime.handleServiceAdapter(serviceAdapter);\n }\n\n // Note: cors option requires @copilotkit/runtime with credentials support\n const honoApp = createCopilotEndpointSingleRoute({\n runtime: options.runtime.instance,\n basePath: options.baseUrl ?? options.endpoint,\n ...(options.cors && { cors: options.cors }),\n } as any);\n\n const handle = async function handler(\n req: IncomingWithBody,\n res: ServerResponse,\n ) {\n const url = getFullUrl(req);\n const hasBody = req.method !== \"GET\" && req.method !== \"HEAD\";\n\n const baseHeaders = toHeaders(req.headers);\n const parsedBody = req.body;\n\n const streamConsumed = isStreamConsumed(req) || parsedBody !== undefined;\n const canStream = hasBody && !streamConsumed;\n\n let requestBody: BodyInit | null | undefined = undefined;\n let useDuplex = false;\n\n if (hasBody && canStream) {\n requestBody = nodeStreamToReadableStream(req);\n useDuplex = true;\n }\n\n if (hasBody && streamConsumed) {\n if (parsedBody !== undefined) {\n const synthesized = synthesizeBodyFromParsedBody(\n parsedBody,\n baseHeaders,\n );\n requestBody = synthesized.body ?? undefined;\n baseHeaders.delete(\"content-length\");\n\n if (synthesized.contentType) {\n baseHeaders.set(\"content-type\", synthesized.contentType);\n }\n\n logger.debug(\n \"Request stream already consumed; using parsed req.body to rebuild request.\",\n );\n } else {\n logger.warn(\n \"Request stream consumed with no available body; sending empty payload.\",\n );\n requestBody = undefined;\n }\n }\n\n const buildRequest = (\n body: BodyInit | null | undefined,\n headers: Headers,\n duplex: boolean,\n ) =>\n new Request(url, {\n method: req.method,\n headers,\n body,\n duplex: duplex ? \"half\" : undefined,\n } as RequestInit);\n\n let response: Response;\n try {\n response = await honoApp.fetch(\n buildRequest(requestBody, baseHeaders, useDuplex),\n );\n } catch (error) {\n if (isDisturbedOrLockedError(error) && hasBody) {\n logger.warn(\n \"Encountered disturbed/locked request body; rebuilding request using parsed body or empty payload.\",\n );\n\n const fallbackHeaders = new Headers(baseHeaders);\n let fallbackBody: BodyInit | null | undefined;\n\n if (parsedBody !== undefined) {\n const synthesized = synthesizeBodyFromParsedBody(\n parsedBody,\n fallbackHeaders,\n );\n fallbackBody = synthesized.body ?? undefined;\n fallbackHeaders.delete(\"content-length\");\n\n if (synthesized.contentType) {\n fallbackHeaders.set(\"content-type\", synthesized.contentType);\n }\n } else {\n fallbackBody = undefined;\n }\n\n response = await honoApp.fetch(\n buildRequest(fallbackBody, fallbackHeaders, false),\n );\n } else {\n throw error;\n }\n }\n\n res.statusCode = response.status;\n response.headers.forEach((value, key) => {\n res.setHeader(key, value);\n });\n\n if (response.body) {\n readableStreamToNodeStream(response.body).pipe(res);\n } else {\n res.end();\n }\n };\n\n // Duck-type check for Request-like objects (handles polyfilled Request from @hono/node-server)\n function isRequestLike(obj: unknown): obj is Request {\n return (\n obj instanceof Request ||\n (typeof obj === \"object\" &&\n obj !== null &&\n \"url\" in obj &&\n \"method\" in obj &&\n \"headers\" in obj &&\n typeof (obj as any).url === \"string\" &&\n typeof (obj as any).method === \"string\")\n );\n }\n\n return function (\n reqOrRequest: IncomingMessage | Request,\n res?: ServerResponse,\n ): Promise<void> | Promise<Response> | Response {\n if (isRequestLike(reqOrRequest) && !res) {\n return honoApp.fetch(reqOrRequest as Request);\n }\n if (!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precated/lib/integrations/node-http/index.ts"],"mappings":";;;;;iBAoCgB,8BAAA,CACd,OAAA,EAAS,iCAAA,IA6JP,YAAA,EAAc,eAAA,GAAkB,OAAA,EAChC,GAAA,GAAM,cAAA,KACL,OAAA,SAAgB,OAAA,CAAQ,QAAA,IAAY,QAAA"}
1
+ {"version":3,"file":"index.d.cts","names":[],"sources":["../../../../../src/v1-deprecated/lib/integrations/node-http/index.ts"],"mappings":";;;;;iBAqCgB,8BAAA,CACd,OAAA,EAAS,iCAAA,IA6JP,YAAA,EAAc,eAAA,GAAkB,OAAA,EAChC,GAAA,GAAM,cAAA,KACL,OAAA,SAAgB,OAAA,CAAQ,QAAA,IAAY,QAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../../../../src/v1-deprecated/lib/integrations/node-http/index.ts"],"mappings":";;;;;iBAoCgB,8BAAA,CACd,OAAA,EAAS,iCAAA,IA6JP,YAAA,EAAc,eAAA,GAAkB,OAAA,EAChC,GAAA,GAAM,cAAA,KACL,OAAA,SAAgB,OAAA,CAAQ,QAAA,IAAY,QAAA"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../../../../src/v1-deprecated/lib/integrations/node-http/index.ts"],"mappings":";;;;;iBAqCgB,8BAAA,CACd,OAAA,EAAS,iCAAA,IA6JP,YAAA,EAAc,eAAA,GAAkB,OAAA,EAChC,GAAA,GAAM,cAAA,KACL,OAAA,SAAgB,OAAA,CAAQ,QAAA,IAAY,QAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../../../../src/v1-deprecated/lib/integrations/node-http/index.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 — copilotRuntimeNodeHttpEndpoint:\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 */\nimport type { CreateCopilotRuntimeServerOptions } from \"../shared\";\nimport { getCommonConfig } from \"../shared\";\nimport telemetry, {\n getRuntimeInstanceTelemetryInfo,\n} from \"../../telemetry-client\";\nimport { createCopilotEndpointSingleRoute } from \"../../../../v2/runtime\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport type { IncomingWithBody } from \"./request-handler\";\nimport {\n getFullUrl,\n isDisturbedOrLockedError,\n isStreamConsumed,\n nodeStreamToReadableStream,\n readableStreamToNodeStream,\n synthesizeBodyFromParsedBody,\n toHeaders,\n} from \"./request-handler\";\n\nexport function copilotRuntimeNodeHttpEndpoint(\n options: CreateCopilotRuntimeServerOptions,\n) {\n const commonConfig = getCommonConfig(options);\n\n telemetry.setGlobalProperties({\n runtime: {\n framework: \"node-http\",\n },\n });\n\n if (options.properties?._copilotkit) {\n telemetry.setGlobalProperties({\n _copilotkit: options.properties._copilotkit,\n });\n }\n\n options.runtime.telemetry.capture(\n \"oss.runtime.instance_created\",\n getRuntimeInstanceTelemetryInfo(options),\n );\n\n const logger = commonConfig.logging;\n logger.debug(\"Creating Node HTTP endpoint\");\n\n const serviceAdapter = options.serviceAdapter;\n if (serviceAdapter) {\n options.runtime.handleServiceAdapter(serviceAdapter);\n }\n\n // Note: cors option requires @copilotkit/runtime with credentials support\n const honoApp = createCopilotEndpointSingleRoute({\n runtime: options.runtime.instance,\n basePath: options.baseUrl ?? options.endpoint,\n ...(options.cors && { cors: options.cors }),\n } as any);\n\n const handle = async function handler(\n req: IncomingWithBody,\n res: ServerResponse,\n ) {\n const url = getFullUrl(req);\n const hasBody = req.method !== \"GET\" && req.method !== \"HEAD\";\n\n const baseHeaders = toHeaders(req.headers);\n const parsedBody = req.body;\n\n const streamConsumed = isStreamConsumed(req) || parsedBody !== undefined;\n const canStream = hasBody && !streamConsumed;\n\n let requestBody: BodyInit | null | undefined = undefined;\n let useDuplex = false;\n\n if (hasBody && canStream) {\n requestBody = nodeStreamToReadableStream(req);\n useDuplex = true;\n }\n\n if (hasBody && streamConsumed) {\n if (parsedBody !== undefined) {\n const synthesized = synthesizeBodyFromParsedBody(\n parsedBody,\n baseHeaders,\n );\n requestBody = synthesized.body ?? undefined;\n baseHeaders.delete(\"content-length\");\n\n if (synthesized.contentType) {\n baseHeaders.set(\"content-type\", synthesized.contentType);\n }\n\n logger.debug(\n \"Request stream already consumed; using parsed req.body to rebuild request.\",\n );\n } else {\n logger.warn(\n \"Request stream consumed with no available body; sending empty payload.\",\n );\n requestBody = undefined;\n }\n }\n\n const buildRequest = (\n body: BodyInit | null | undefined,\n headers: Headers,\n duplex: boolean,\n ) =>\n new Request(url, {\n method: req.method,\n headers,\n body,\n duplex: duplex ? \"half\" : undefined,\n } as RequestInit);\n\n let response: Response;\n try {\n response = await honoApp.fetch(\n buildRequest(requestBody, baseHeaders, useDuplex),\n );\n } catch (error) {\n if (isDisturbedOrLockedError(error) && hasBody) {\n logger.warn(\n \"Encountered disturbed/locked request body; rebuilding request using parsed body or empty payload.\",\n );\n\n const fallbackHeaders = new Headers(baseHeaders);\n let fallbackBody: BodyInit | null | undefined;\n\n if (parsedBody !== undefined) {\n const synthesized = synthesizeBodyFromParsedBody(\n parsedBody,\n fallbackHeaders,\n );\n fallbackBody = synthesized.body ?? undefined;\n fallbackHeaders.delete(\"content-length\");\n\n if (synthesized.contentType) {\n fallbackHeaders.set(\"content-type\", synthesized.contentType);\n }\n } else {\n fallbackBody = undefined;\n }\n\n response = await honoApp.fetch(\n buildRequest(fallbackBody, fallbackHeaders, false),\n );\n } else {\n throw error;\n }\n }\n\n res.statusCode = response.status;\n response.headers.forEach((value, key) => {\n res.setHeader(key, value);\n });\n\n if (response.body) {\n readableStreamToNodeStream(response.body).pipe(res);\n } else {\n res.end();\n }\n };\n\n // Duck-type check for Request-like objects (handles polyfilled Request from @hono/node-server)\n function isRequestLike(obj: unknown): obj is Request {\n return (\n obj instanceof Request ||\n (typeof obj === \"object\" &&\n obj !== null &&\n \"url\" in obj &&\n \"method\" in obj &&\n \"headers\" in obj &&\n typeof (obj as any).url === \"string\" &&\n typeof (obj as any).method === \"string\")\n );\n }\n\n return function (\n reqOrRequest: IncomingMessage | Request,\n res?: ServerResponse,\n ): Promise<void> | Promise<Response> | Response {\n if (isRequestLike(reqOrRequest) && !res) {\n return honoApp.fetch(reqOrRequest as Request);\n }\n if (!res) {\n throw new TypeError(\"ServerResponse is required for Node HTTP requests\");\n }\n return handle(reqOrRequest as IncomingMessage, res);\n };\n}\n"],"mappings":";;;;;;;AAoCA,SAAgB,+BACd,SACA;CACA,MAAM,eAAe,gBAAgB,QAAQ;AAE7C,iBAAU,oBAAoB,EAC5B,SAAS,EACP,WAAW,aACZ,EACF,CAAC;AAEF,KAAI,QAAQ,YAAY,YACtB,iBAAU,oBAAoB,EAC5B,aAAa,QAAQ,WAAW,aACjC,CAAC;AAGJ,SAAQ,QAAQ,UAAU,QACxB,gCACA,gCAAgC,QAAQ,CACzC;CAED,MAAM,SAAS,aAAa;AAC5B,QAAO,MAAM,8BAA8B;CAE3C,MAAM,iBAAiB,QAAQ;AAC/B,KAAI,eACF,SAAQ,QAAQ,qBAAqB,eAAe;CAItD,MAAM,UAAU,iCAAiC;EAC/C,SAAS,QAAQ,QAAQ;EACzB,UAAU,QAAQ,WAAW,QAAQ;EACrC,GAAI,QAAQ,QAAQ,EAAE,MAAM,QAAQ,MAAM;EAC3C,CAAQ;CAET,MAAM,SAAS,eAAe,QAC5B,KACA,KACA;EACA,MAAM,MAAM,WAAW,IAAI;EAC3B,MAAM,UAAU,IAAI,WAAW,SAAS,IAAI,WAAW;EAEvD,MAAM,cAAc,UA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AI;MAEnD,KAAI,KAAK;;CAKb,SAAS,cAAc,KAA8B;AACnD,SACE,eAAe,WACd,OAAO,QAAQ,YACd,QAAQ,QACR,SAAS,OACT,YAAY,OACZ,aAAa,OACb,OAAQ,IAAY,QAAQ,YAC5B,OAAQ,IAAY,WAAW;;AAIrC,QAAO,SACL,cACA,KAC8C;AAC9C,MAAI,cAAc,aAAa,IAAI,CAAC,IAClC,QAAO,QAAQ,MAAM,aAAwB;AAE/C,MAAI,CAAC,IACH,OAAM,IAAI,UAAU,oDAAoD;AAE1E,SAAO,OAAO,cAAiC,IAAI"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../../../../src/v1-deprecated/lib/integrations/node-http/index.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 — copilotRuntimeNodeHttpEndpoint:\n * V2 import and usage:\n * import { createCopilotRuntimeHandler } from \"@copilotkit/runtime/v2\";\n * const v2CreateCopilotRuntimeHandler = createCopilotRuntimeHandler;\n * V2 replacement source: packages/runtime/src/v2/runtime/core/fetch-handler.ts\n * V2 docs: https://docs.copilotkit.ai/runtime-server-adapter\n *\n * Migration guide: https://docs.copilotkit.ai/migrate/v2\n *\n * END V1 SDK DEPRECATED. USE V2 INSTEAD NOTICE\n */\n\nimport type { CreateCopilotRuntimeServerOptions } from \"../shared\";\nimport { getCommonConfig } from \"../shared\";\nimport telemetry, {\n getRuntimeInstanceTelemetryInfo,\n} from \"../../telemetry-client\";\nimport { createCopilotEndpointSingleRoute } from \"../../../../v2/runtime\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport type { IncomingWithBody } from \"./request-handler\";\nimport {\n getFullUrl,\n isDisturbedOrLockedError,\n isStreamConsumed,\n nodeStreamToReadableStream,\n readableStreamToNodeStream,\n synthesizeBodyFromParsedBody,\n toHeaders,\n} from \"./request-handler\";\n\nexport function copilotRuntimeNodeHttpEndpoint(\n options: CreateCopilotRuntimeServerOptions,\n) {\n const commonConfig = getCommonConfig(options);\n\n telemetry.setGlobalProperties({\n runtime: {\n framework: \"node-http\",\n },\n });\n\n if (options.properties?._copilotkit) {\n telemetry.setGlobalProperties({\n _copilotkit: options.properties._copilotkit,\n });\n }\n\n options.runtime.telemetry.capture(\n \"oss.runtime.instance_created\",\n getRuntimeInstanceTelemetryInfo(options),\n );\n\n const logger = commonConfig.logging;\n logger.debug(\"Creating Node HTTP endpoint\");\n\n const serviceAdapter = options.serviceAdapter;\n if (serviceAdapter) {\n options.runtime.handleServiceAdapter(serviceAdapter);\n }\n\n // Note: cors option requires @copilotkit/runtime with credentials support\n const honoApp = createCopilotEndpointSingleRoute({\n runtime: options.runtime.instance,\n basePath: options.baseUrl ?? options.endpoint,\n ...(options.cors && { cors: options.cors }),\n } as any);\n\n const handle = async function handler(\n req: IncomingWithBody,\n res: ServerResponse,\n ) {\n const url = getFullUrl(req);\n const hasBody = req.method !== \"GET\" && req.method !== \"HEAD\";\n\n const baseHeaders = toHeaders(req.headers);\n const parsedBody = req.body;\n\n const streamConsumed = isStreamConsumed(req) || parsedBody !== undefined;\n const canStream = hasBody && !streamConsumed;\n\n let requestBody: BodyInit | null | undefined = undefined;\n let useDuplex = false;\n\n if (hasBody && canStream) {\n requestBody = nodeStreamToReadableStream(req);\n useDuplex = true;\n }\n\n if (hasBody && streamConsumed) {\n if (parsedBody !== undefined) {\n const synthesized = synthesizeBodyFromParsedBody(\n parsedBody,\n baseHeaders,\n );\n requestBody = synthesized.body ?? undefined;\n baseHeaders.delete(\"content-length\");\n\n if (synthesized.contentType) {\n baseHeaders.set(\"content-type\", synthesized.contentType);\n }\n\n logger.debug(\n \"Request stream already consumed; using parsed req.body to rebuild request.\",\n );\n } else {\n logger.warn(\n \"Request stream consumed with no available body; sending empty payload.\",\n );\n requestBody = undefined;\n }\n }\n\n const buildRequest = (\n body: BodyInit | null | undefined,\n headers: Headers,\n duplex: boolean,\n ) =>\n new Request(url, {\n method: req.method,\n headers,\n body,\n duplex: duplex ? \"half\" : undefined,\n } as RequestInit);\n\n let response: Response;\n try {\n response = await honoApp.fetch(\n buildRequest(requestBody, baseHeaders, useDuplex),\n );\n } catch (error) {\n if (isDisturbedOrLockedError(error) && hasBody) {\n logger.warn(\n \"Encountered disturbed/locked request body; rebuilding request using parsed body or empty payload.\",\n );\n\n const fallbackHeaders = new Headers(baseHeaders);\n let fallbackBody: BodyInit | null | undefined;\n\n if (parsedBody !== undefined) {\n const synthesized = synthesizeBodyFromParsedBody(\n parsedBody,\n fallbackHeaders,\n );\n fallbackBody = synthesized.body ?? undefined;\n fallbackHeaders.delete(\"content-length\");\n\n if (synthesized.contentType) {\n fallbackHeaders.set(\"content-type\", synthesized.contentType);\n }\n } else {\n fallbackBody = undefined;\n }\n\n response = await honoApp.fetch(\n buildRequest(fallbackBody, fallbackHeaders, false),\n );\n } else {\n throw error;\n }\n }\n\n res.statusCode = response.status;\n response.headers.forEach((value, key) => {\n res.setHeader(key, value);\n });\n\n if (response.body) {\n readableStreamToNodeStream(response.body).pipe(res);\n } else {\n res.end();\n }\n };\n\n // Duck-type check for Request-like objects (handles polyfilled Request from @hono/node-server)\n function isRequestLike(obj: unknown): obj is Request {\n return (\n obj instanceof Request ||\n (typeof obj === \"object\" &&\n obj !== null &&\n \"url\" in obj &&\n \"method\" in obj &&\n \"headers\" in obj &&\n typeof (obj as any).url === \"string\" &&\n typeof (obj as any).method === \"string\")\n );\n }\n\n return function (\n reqOrRequest: IncomingMessage | Request,\n res?: ServerResponse,\n ): Promise<void> | Promise<Response> | Response {\n if (isRequestLike(reqOrRequest) && !res) {\n return honoApp.fetch(reqOrRequest as Request);\n }\n if (!res) {\n throw new TypeError(\"ServerResponse is required for Node HTTP requests\");\n }\n return handle(reqOrRequest as IncomingMessage, res);\n };\n}\n"],"mappings":";;;;;;;AAqC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;GACZ;GACA;GACA,QAAQ,SAAS,SAAS;GAC3B,CAAgB;EAEnB,IAAI;AACJ,MAAI;AACF,cAAW,MAAM,QAAQ,MACvB,aAAa,aAAa,aAAa,UAAU,CAClD;WACM,OAAO;AACd,OAAI,yBAAyB,MAAM,IAAI,SAAS;AAC9C,WAAO,KACL,oGACD;IAED,MAAM,kBAAkB,IAAI,QAAQ,YAAY;IAChD,IAAI;AAEJ,QAAI,eAAe,QAAW;KAC5B,MAAM,cAAc,6BAClB,YACA,gBACD;AACD,oBAAe,YAAY,QAAQ;AACnC,qBAAgB,OAAO,iBAAiB;AAExC,SAAI,YAAY,YACd,iBAAgB,IAAI,gBAAgB,YAAY,YAAY;UAG9D,gBAAe;AAGjB,eAAW,MAAM,QAAQ,MACvB,aAAa,cAAc,iBAAiB,MAAM,CACnD;SAED,OAAM;;AAIV,MAAI,aAAa,SAAS;AAC1B,WAAS,QAAQ,SAAS,OAAO,QAAQ;AACvC,OAAI,UAAU,KAAK,MAAM;IACzB;AAEF,MAAI,SAAS,KACX,4BAA2B,SAAS,KAAK,CAAC,KAAK,IAAI;MAEnD,KAAI,KAAK;;CAKb,SAAS,cAAc,KAA8B;AACnD,SACE,eAAe,WACd,OAAO,QAAQ,YACd,QAAQ,QACR,SAAS,OACT,YAAY,OACZ,aAAa,OACb,OAAQ,IAAY,QAAQ,YAC5B,OAAQ,IAAY,WAAW;;AAIrC,QAAO,SACL,cACA,KAC8C;AAC9C,MAAI,cAAc,aAAa,IAAI,CAAC,IAClC,QAAO,QAAQ,MAAM,aAAwB;AAE/C,MAAI,CAAC,IACH,OAAM,IAAI,UAAU,oDAAoD;AAE1E,SAAO,OAAO,cAAiC,IAAI"}
@@ -1 +1 @@
1
- {"version":3,"file":"shared.cjs","names":["createLogger","CopilotResolver","StateResolver"],"sources":["../../../../src/v1-deprecated/lib/integrations/shared.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 — buildSchema:\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 — CommonConfig:\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 — CopilotEndpointCorsConfig:\n * V2 import and usage:\n * import type { CopilotEndpointCorsConfig } from \"@copilotkit/runtime/v2\";\n * type V2CopilotEndpointCorsConfig = CopilotEndpointCorsConfig;\n * V2 replacement source: packages/runtime/src/v2/runtime/endpoints/hono.ts\n * V2 docs: https://docs.copilotkit.ai/runtime-server-adapter\n *\n * @copilotkit/runtime — CopilotRequestContextProperties:\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 — CreateCopilotRuntimeServerOptions:\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 — getCommonConfig:\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 — GraphQLContext:\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\nimport { buildSchemaSync } from \"type-graphql\";\nimport { CopilotResolver } from \"../../graphql/resolvers/copilot.resolver\";\nimport type { CopilotRuntime } from \"../runtime/copilot-runtime\";\nimport type { CopilotServiceAdapter } from \"../../service-adapters\";\nimport type { CopilotCloudOptions } from \"../cloud\";\nimport type { LogLevel } from \"../../lib/logger\";\nimport { createLogger } from \"../../lib/logger\";\nimport telemetry from \"../telemetry-client\";\nimport { StateResolver } from \"../../graphql/resolvers/state.resolver\";\n\n/**\n * CORS configuration for CopilotKit endpoints.\n */\nexport interface CopilotEndpointCorsConfig {\n /**\n * Allowed origin(s). Can be a string, array of strings, or a function that returns the origin.\n */\n origin:\n | string\n | string[]\n | ((origin: string, c: any) => string | undefined | null);\n /**\n * Whether to include credentials (cookies, authorization headers) in CORS requests.\n * When true, origin cannot be \"*\" - must be an explicit origin.\n */\n credentials?: boolean;\n}\n\nconst logger = createLogger();\n\ntype AnyPrimitive = string | boolean | number | null;\nexport type CopilotRequestContextProperties = Record<\n string,\n AnyPrimitive | Record<string, AnyPrimitive>\n>;\n\n/**\n * The request-scoped fields the v1 middleware hooks read off the GraphQL\n * context.\n *\n * Declared here rather than imported as Yoga's `YogaInitialContext`. Nothing in\n * this package serves GraphQL any more -- every v1 integration entry point\n * delegates to the v2 Hono endpoint -- but that one type reference was enough to\n * pull the whole `graphql-yoga` barrel, and with it `lru-cache@10`, into every\n * consumer's program. `lru-cache@10` declares `implements Map`, which costs five\n * TS2416 errors under `strict` with `skipLibCheck: false` (OSS-899).\n *\n * Structurally identical to `YogaInitialContext`, so a real Yoga context still\n * satisfies it.\n */\nexport interface GraphQLRequestContext {\n /** GraphQL parameters parsed from the request. */\n params: {\n operationName?: string;\n query?: string;\n variables?: Record<string, any>;\n extensions?: Record<string, any>;\n };\n /** The incoming HTTP request. */\n request: Request;\n /** Defers work past the response, where the host runtime supports it. */\n waitUntil(promise: Promise<unknown> | void): void;\n}\n\nexport type GraphQLContext = GraphQLRequestContext & {\n _copilotkit: CreateCopilotRuntimeServerOptions;\n properties: CopilotRequestContextProperties;\n logger: typeof logger;\n};\n\nexport interface CreateCopilotRuntimeServerOptions {\n runtime: CopilotRuntime<any>;\n serviceAdapter?: CopilotServiceAdapter;\n endpoint: string;\n baseUrl?: string;\n cloud?: CopilotCloudOptions;\n properties?: CopilotRequestContextProperties;\n logLevel?: LogLevel;\n /**\n * Optional CORS configuration. When not provided, defaults to allowing all origins without credentials.\n * To support HTTP-only cookies, provide cors config with credentials: true and explicit origin.\n */\n cors?: CopilotEndpointCorsConfig;\n}\n\nexport function buildSchema(\n options: {\n emitSchemaFile?: string;\n } = {},\n) {\n logger.debug(\"Building GraphQL schema...\");\n const schema = buildSchemaSync({\n resolvers: [CopilotResolver, StateResolver],\n emitSchemaFile: options.emitSchemaFile,\n });\n logger.debug(\"GraphQL schema built successfully\");\n return schema;\n}\n\nexport type CommonConfig = {\n logging: typeof logger;\n};\n\nexport function getCommonConfig(\n options: CreateCopilotRuntimeServerOptions,\n): CommonConfig {\n const logLevel =\n (process.env.LOG_LEVEL as LogLevel) ||\n (options.logLevel as LogLevel) ||\n \"error\";\n const logger = createLogger({\n level: logLevel,\n component: \"getCommonConfig\",\n });\n\n if (options.cloud) {\n telemetry.setCloudConfiguration({\n publicApiKey: options.cloud.publicApiKey,\n baseUrl: options.cloud.baseUrl,\n });\n }\n\n if (options.properties?._copilotkit) {\n telemetry.setGlobalProperties({\n _copilotkit: {\n ...(options.properties._copilotkit as Record<string, any>),\n },\n });\n }\n\n telemetry.setGlobalProperties({\n runtime: {\n serviceAdapter: options.serviceAdapter?.constructor?.name ?? \"none\",\n },\n });\n\n return {\n logging: createLogger({ component: \"CopilotKit Runtime\", level: logLevel }),\n };\n}\n"],"mappings":";;;;;;;;;AAyFA,MAAM,SAASA,6BAAc;AAyD7B,SAAgB,YACd,UAEI,EAAE,EACN;AACA,QAAO,MAAM,6BAA6B;CAC1C,MAAM,2CAAyB;EAC7B,WAAW,CAACC,0CAAiBC,qCAAc;EAC3C,gBAAgB,QAAQ;EACzB,CAAC;AACF,QAAO,MAAM,oCAAoC;AACjD,QAAO;;AAOT,SAAgB,gBACd,SACc;CACd,MAAM,WACH,QAAQ,IAAI,aACZ,QAAQ,YACT;AACa,6BAAa;EAC1B,OAAO;EACP,WAAW;EACZ,CAAC;AAEF,KAAI,QAAQ,MACV,kCAAU,sBAAsB;EAC9B,cAAc,QAAQ,MAAM;EAC5B,SAAS,QAAQ,MAAM;EACxB,CAAC;AAGJ,KAAI,QAAQ,YAAY,YACtB,kCAAU,oBAAoB,EAC5B,aAAa,EACX,GAAI,QAAQ,WAAW,aACxB,EACF,CAAC;AAGJ,kCAAU,oBAAoB,EAC5B,SAAS,EACP,gBAAgB,QAAQ,gBAAgB,aAAa,QAAQ,QAC9D,EACF,CAAC;AAEF,QAAO,EACL,SAASF,4BAAa;EAAE,WAAW;EAAsB,OAAO;EAAU,CAAC,EAC5E"}
1
+ {"version":3,"file":"shared.cjs","names":["createLogger","CopilotResolver","StateResolver"],"sources":["../../../../src/v1-deprecated/lib/integrations/shared.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 — buildSchema:\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 — CommonConfig:\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 — CopilotEndpointCorsConfig:\n * V2 import and usage:\n * import type { CopilotEndpointCorsConfig } from \"@copilotkit/runtime/v2\";\n * type V2CopilotEndpointCorsConfig = CopilotEndpointCorsConfig;\n * V2 replacement source: packages/runtime/src/v2/runtime/endpoints/hono.ts\n * V2 docs: https://docs.copilotkit.ai/runtime-server-adapter\n *\n * @copilotkit/runtime — CopilotRequestContextProperties:\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 — CreateCopilotRuntimeServerOptions:\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 — getCommonConfig:\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 — GraphQLContext:\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 — GraphQLRequestContext:\n * No 1:1 v2 replacement is available.\n * Start at: @copilotkit/runtime/v2\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * Migration guide: https://docs.copilotkit.ai/migrate/v2\n *\n * END V1 SDK DEPRECATED. USE V2 INSTEAD NOTICE\n */\n\nimport { buildSchemaSync } from \"type-graphql\";\nimport { CopilotResolver } from \"../../graphql/resolvers/copilot.resolver\";\nimport type { CopilotRuntime } from \"../runtime/copilot-runtime\";\nimport type { CopilotServiceAdapter } from \"../../service-adapters\";\nimport type { CopilotCloudOptions } from \"../cloud\";\nimport type { LogLevel } from \"../../lib/logger\";\nimport { createLogger } from \"../../lib/logger\";\nimport telemetry from \"../telemetry-client\";\nimport { StateResolver } from \"../../graphql/resolvers/state.resolver\";\n\n/**\n * CORS configuration for CopilotKit endpoints.\n */\nexport interface CopilotEndpointCorsConfig {\n /**\n * Allowed origin(s). Can be a string, array of strings, or a function that returns the origin.\n */\n origin:\n | string\n | string[]\n | ((origin: string, c: any) => string | undefined | null);\n /**\n * Whether to include credentials (cookies, authorization headers) in CORS requests.\n * When true, origin cannot be \"*\" - must be an explicit origin.\n */\n credentials?: boolean;\n}\n\nconst logger = createLogger();\n\ntype AnyPrimitive = string | boolean | number | null;\nexport type CopilotRequestContextProperties = Record<\n string,\n AnyPrimitive | Record<string, AnyPrimitive>\n>;\n\n/**\n * The request-scoped fields the v1 middleware hooks read off the GraphQL\n * context.\n *\n * Declared here rather than imported as Yoga's `YogaInitialContext`. Nothing in\n * this package serves GraphQL any more -- every v1 integration entry point\n * delegates to the v2 Hono endpoint -- but that one type reference was enough to\n * pull the whole `graphql-yoga` barrel, and with it `lru-cache@10`, into every\n * consumer's program. `lru-cache@10` declares `implements Map`, which costs five\n * TS2416 errors under `strict` with `skipLibCheck: false` (OSS-899).\n *\n * Structurally identical to `YogaInitialContext`, so a real Yoga context still\n * satisfies it.\n */\nexport interface GraphQLRequestContext {\n /** GraphQL parameters parsed from the request. */\n params: {\n operationName?: string;\n query?: string;\n variables?: Record<string, any>;\n extensions?: Record<string, any>;\n };\n /** The incoming HTTP request. */\n request: Request;\n /** Defers work past the response, where the host runtime supports it. */\n waitUntil(promise: Promise<unknown> | void): void;\n}\n\nexport type GraphQLContext = GraphQLRequestContext & {\n _copilotkit: CreateCopilotRuntimeServerOptions;\n properties: CopilotRequestContextProperties;\n logger: typeof logger;\n};\n\nexport interface CreateCopilotRuntimeServerOptions {\n runtime: CopilotRuntime<any>;\n serviceAdapter?: CopilotServiceAdapter;\n endpoint: string;\n baseUrl?: string;\n cloud?: CopilotCloudOptions;\n properties?: CopilotRequestContextProperties;\n logLevel?: LogLevel;\n /**\n * Optional CORS configuration. When not provided, defaults to allowing all origins without credentials.\n * To support HTTP-only cookies, provide cors config with credentials: true and explicit origin.\n */\n cors?: CopilotEndpointCorsConfig;\n}\n\nexport function buildSchema(\n options: {\n emitSchemaFile?: string;\n } = {},\n) {\n logger.debug(\"Building GraphQL schema...\");\n const schema = buildSchemaSync({\n resolvers: [CopilotResolver, StateResolver],\n emitSchemaFile: options.emitSchemaFile,\n });\n logger.debug(\"GraphQL schema built successfully\");\n return schema;\n}\n\nexport type CommonConfig = {\n logging: typeof logger;\n};\n\nexport function getCommonConfig(\n options: CreateCopilotRuntimeServerOptions,\n): CommonConfig {\n const logLevel =\n (process.env.LOG_LEVEL as LogLevel) ||\n (options.logLevel as LogLevel) ||\n \"error\";\n const logger = createLogger({\n level: logLevel,\n component: \"getCommonConfig\",\n });\n\n if (options.cloud) {\n telemetry.setCloudConfiguration({\n publicApiKey: options.cloud.publicApiKey,\n baseUrl: options.cloud.baseUrl,\n });\n }\n\n if (options.properties?._copilotkit) {\n telemetry.setGlobalProperties({\n _copilotkit: {\n ...(options.properties._copilotkit as Record<string, any>),\n },\n });\n }\n\n telemetry.setGlobalProperties({\n runtime: {\n serviceAdapter: options.serviceAdapter?.constructor?.name ?? \"none\",\n },\n });\n\n return {\n logging: createLogger({ component: \"CopilotKit Runtime\", level: logLevel }),\n };\n}\n"],"mappings":";;;;;;;;;AA+FA,MAAM,SAASA,6BAAc;AAyD7B,SAAgB,YACd,UAEI,EAAE,EACN;AACA,QAAO,MAAM,6BAA6B;CAC1C,MAAM,2CAAyB;EAC7B,WAAW,CAACC,0CAAiBC,qCAAc;EAC3C,gBAAgB,QAAQ;EACzB,CAAC;AACF,QAAO,MAAM,oCAAoC;AACjD,QAAO;;AAOT,SAAgB,gBACd,SACc;CACd,MAAM,WACH,QAAQ,IAAI,aACZ,QAAQ,YACT;AACa,6BAAa;EAC1B,OAAO;EACP,WAAW;EACZ,CAAC;AAEF,KAAI,QAAQ,MACV,kCAAU,sBAAsB;EAC9B,cAAc,QAAQ,MAAM;EAC5B,SAAS,QAAQ,MAAM;EACxB,CAAC;AAGJ,KAAI,QAAQ,YAAY,YACtB,kCAAU,oBAAoB,EAC5B,aAAa,EACX,GAAI,QAAQ,WAAW,aACxB,EACF,CAAC;AAGJ,kCAAU,oBAAoB,EAC5B,SAAS,EACP,gBAAgB,QAAQ,gBAAgB,aAAa,QAAQ,QAC9D,EACF,CAAC;AAEF,QAAO,EACL,SAASF,4BAAa;EAAE,WAAW;EAAsB,OAAO;EAAU,CAAC,EAC5E"}
@@ -1,7 +1,7 @@
1
1
 
2
+ import { LogLevel } from "../logger.cjs";
2
3
  import { CopilotServiceAdapter } from "../../service-adapters/service-adapter.cjs";
3
4
  import "../../service-adapters/index.cjs";
4
- import { LogLevel } from "../logger.cjs";
5
5
  import { CopilotRuntime } from "../runtime/copilot-runtime.cjs";
6
6
  import { CopilotCloudOptions } from "../cloud/index.cjs";
7
7
  import * as pino from "pino";
@@ -1 +1 @@
1
- {"version":3,"file":"shared.d.cts","names":[],"sources":["../../../../src/v1-deprecated/lib/integrations/shared.ts"],"mappings":";;;;;;;;;;;;;UA0EiB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A,GAAe,MAAA,SAAe,YAAA;;;;AALpB;;;;;AAGZ;;;;;;UAmBiB,qBAAA;EAnBmC;EAqBlD,MAAA;IACE,aAAA;IACA,KAAA;IACA,SAAA,GAAY,MAAA;IACZ,UAAA,GAAa,MAAA;EAAA;EAvB2B;EA0B1C,OAAA,EAAS,OAAA;EAT2B;EAWpC,SAAA,CAAU,OAAA,EAAS,OAAA;AAAA;AAAA,KAGT,cAAA,GAAiB,qBAAA;EAC3B,WAAA,EAAa,iCAAA;EACb,UAAA,EAAY,+BAAA;EACZ,MAAA,SAAe,MAAA;AAAA;AAAA,UAGA,iCAAA;EACf,OAAA,EAAS,cAAA;EACT,cAAA,GAAiB,qBAAA;EACjB,QAAA;EACA,OAAA;EACA,KAAA,GAAQ,mBAAA;EACR,UAAA,GAAa,+BAAA;EACb,QAAA,GAAW,QAAA;EAlBF;;;;EAuBT,IAAA,GAAO,yBAAA;AAAA;AAAA,iBAGO,WAAA,CACd,OAAA;EACE,cAAA;AAAA,IAFuB,OAAA,CAGnB,aAAA;AAAA,KAWI,YAAA;EACV,OAAA,SAAgB,MAAA;AAAA;AAAA,iBAGF,eAAA,CACd,OAAA,EAAS,iCAAA,GACR,YAAA"}
@@ -1,7 +1,7 @@
1
1
 
2
+ import { LogLevel } from "../logger.mjs";
2
3
  import { CopilotServiceAdapter } from "../../service-adapters/service-adapter.mjs";
3
4
  import "../../service-adapters/index.mjs";
4
- import { LogLevel } from "../logger.mjs";
5
5
  import { CopilotRuntime } from "../runtime/copilot-runtime.mjs";
6
6
  import { CopilotCloudOptions } from "../cloud/index.mjs";
7
7
  import * as graphql from "graphql";
@@ -1 +1 @@
1
- {"version":3,"file":"shared.d.mts","names":[],"sources":["../../../../src/v1-deprecated/lib/integrations/shared.ts"],"mappings":";;;;;;;;;;;;;UA0EiB,yBAAA;;AAAjB;;EAIE,MAAA,wBAGM,MAAA,UAAgB,CAAA;EAPkB;;;;EAYxC,WAAA;AAAA;AAAA,cAGI,MAAA,EAAuB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AA;IACA,SAAA,GAAY,MAAA;IACZ,UAAA,GAAa,MAAA;EAAA;EAvB2B;EA0B1C,OAAA,EAAS,OAAA;EAT2B;EAWpC,SAAA,CAAU,OAAA,EAAS,OAAA;AAAA;AAAA,KAGT,cAAA,GAAiB,qBAAA;EAC3B,WAAA,EAAa,iCAAA;EACb,UAAA,EAAY,+BAAA;EACZ,MAAA,SAAe,MAAA;AAAA;AAAA,UAGA,iCAAA;EACf,OAAA,EAAS,cAAA;EACT,cAAA,GAAiB,qBAAA;EACjB,QAAA;EACA,OAAA;EACA,KAAA,GAAQ,mBAAA;EACR,UAAA,GAAa,+BAAA;EACb,QAAA,GAAW,QAAA;EAlBF;;;;EAuBT,IAAA,GAAO,yBAAA;AAAA;AAAA,iBAGO,WAAA,CACd,OAAA;EACE,cAAA;AAAA,IAFuB,OAAA,CAGnB,aAAA;AAAA,KAWI,YAAA;EACV,OAAA,SAAgB,MAAA;AAAA;AAAA,iBAGF,eAAA,CACd,OAAA,EAAS,iCAAA,GACR,YAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"shared.mjs","names":[],"sources":["../../../../src/v1-deprecated/lib/integrations/shared.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 — buildSchema:\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 — CommonConfig:\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 — CopilotEndpointCorsConfig:\n * V2 import and usage:\n * import type { CopilotEndpointCorsConfig } from \"@copilotkit/runtime/v2\";\n * type V2CopilotEndpointCorsConfig = CopilotEndpointCorsConfig;\n * V2 replacement source: packages/runtime/src/v2/runtime/endpoints/hono.ts\n * V2 docs: https://docs.copilotkit.ai/runtime-server-adapter\n *\n * @copilotkit/runtime — CopilotRequestContextProperties:\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 — CreateCopilotRuntimeServerOptions:\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 — getCommonConfig:\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 — GraphQLContext:\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\nimport { buildSchemaSync } from \"type-graphql\";\nimport { CopilotResolver } from \"../../graphql/resolvers/copilot.resolver\";\nimport type { CopilotRuntime } from \"../runtime/copilot-runtime\";\nimport type { CopilotServiceAdapter } from \"../../service-adapters\";\nimport type { CopilotCloudOptions } from \"../cloud\";\nimport type { LogLevel } from \"../../lib/logger\";\nimport { createLogger } from \"../../lib/logger\";\nimport telemetry from \"../telemetry-client\";\nimport { StateResolver } from \"../../graphql/resolvers/state.resolver\";\n\n/**\n * CORS configuration for CopilotKit endpoints.\n */\nexport interface CopilotEndpointCorsConfig {\n /**\n * Allowed origin(s). Can be a string, array of strings, or a function that returns the origin.\n */\n origin:\n | string\n | string[]\n | ((origin: string, c: any) => string | undefined | null);\n /**\n * Whether to include credentials (cookies, authorization headers) in CORS requests.\n * When true, origin cannot be \"*\" - must be an explicit origin.\n */\n credentials?: boolean;\n}\n\nconst logger = createLogger();\n\ntype AnyPrimitive = string | boolean | number | null;\nexport type CopilotRequestContextProperties = Record<\n string,\n AnyPrimitive | Record<string, AnyPrimitive>\n>;\n\n/**\n * The request-scoped fields the v1 middleware hooks read off the GraphQL\n * context.\n *\n * Declared here rather than imported as Yoga's `YogaInitialContext`. Nothing in\n * this package serves GraphQL any more -- every v1 integration entry point\n * delegates to the v2 Hono endpoint -- but that one type reference was enough to\n * pull the whole `graphql-yoga` barrel, and with it `lru-cache@10`, into every\n * consumer's program. `lru-cache@10` declares `implements Map`, which costs five\n * TS2416 errors under `strict` with `skipLibCheck: false` (OSS-899).\n *\n * Structurally identical to `YogaInitialContext`, so a real Yoga context still\n * satisfies it.\n */\nexport interface GraphQLRequestContext {\n /** GraphQL parameters parsed from the request. */\n params: {\n operationName?: string;\n query?: string;\n variables?: Record<string, any>;\n extensions?: Record<string, any>;\n };\n /** The incoming HTTP request. */\n request: Request;\n /** Defers work past the response, where the host runtime supports it. */\n waitUntil(promise: Promise<unknown> | void): void;\n}\n\nexport type GraphQLContext = GraphQLRequestContext & {\n _copilotkit: CreateCopilotRuntimeServerOptions;\n properties: CopilotRequestContextProperties;\n logger: typeof logger;\n};\n\nexport interface CreateCopilotRuntimeServerOptions {\n runtime: CopilotRuntime<any>;\n serviceAdapter?: CopilotServiceAdapter;\n endpoint: string;\n baseUrl?: string;\n cloud?: CopilotCloudOptions;\n properties?: CopilotRequestContextProperties;\n logLevel?: LogLevel;\n /**\n * Optional CORS configuration. When not provided, defaults to allowing all origins without credentials.\n * To support HTTP-only cookies, provide cors config with credentials: true and explicit origin.\n */\n cors?: CopilotEndpointCorsConfig;\n}\n\nexport function buildSchema(\n options: {\n emitSchemaFile?: string;\n } = {},\n) {\n logger.debug(\"Building GraphQL schema...\");\n const schema = buildSchemaSync({\n resolvers: [CopilotResolver, StateResolver],\n emitSchemaFile: options.emitSchemaFile,\n });\n logger.debug(\"GraphQL schema built successfully\");\n return schema;\n}\n\nexport type CommonConfig = {\n logging: typeof logger;\n};\n\nexport function getCommonConfig(\n options: CreateCopilotRuntimeServerOptions,\n): CommonConfig {\n const logLevel =\n (process.env.LOG_LEVEL as LogLevel) ||\n (options.logLevel as LogLevel) ||\n \"error\";\n const logger = createLogger({\n level: logLevel,\n component: \"getCommonConfig\",\n });\n\n if (options.cloud) {\n telemetry.setCloudConfiguration({\n publicApiKey: options.cloud.publicApiKey,\n baseUrl: options.cloud.baseUrl,\n });\n }\n\n if (options.properties?._copilotkit) {\n telemetry.setGlobalProperties({\n _copilotkit: {\n ...(options.properties._copilotkit as Record<string, any>),\n },\n });\n }\n\n telemetry.setGlobalProperties({\n runtime: {\n serviceAdapter: options.serviceAdapter?.constructor?.name ?? \"none\",\n },\n });\n\n return {\n logging: createLogger({ component: \"CopilotKit Runtime\", level: logLevel }),\n };\n}\n"],"mappings":";;;;;;;;AAyFA,MAAM,SAAS,cAAc;AAyD7B,SAAgB,YACd,UAEI,EAAE,EACN;AACA,QAAO,MAAM,6BAA6B;CAC1C,MAAM,SAAS,gBAAgB;EAC7B,WAAW,CAAC,iBAAiB,cAAc;EAC3C,gBAAgB,QAAQ;EACzB,CAAC;AACF,QAAO,MAAM,oCAAoC;AACjD,QAAO;;AAOT,SAAgB,gBACd,SACc;CACd,MAAM,WACH,QAAQ,IAAI,aACZ,QAAQ,YACT;AACa,cAAa;EAC1B,OAAO;EACP,WAAW;EACZ,CAAC;AAEF,KAAI,QAAQ,MACV,iBAAU,sBAAsB;EAC9B,cAAc,QAAQ,MAAM;EAC5B,SAAS,QAAQ,MAAM;EACxB,CAAC;AAGJ,KAAI,QAAQ,YAAY,YACtB,iBAAU,oBAAoB,EAC5B,aAAa,EACX,GAAI,QAAQ,WAAW,aACxB,EACF,CAAC;AAGJ,iBAAU,oBAAoB,EAC5B,SAAS,EACP,gBAAgB,QAAQ,gBAAgB,aAAa,QAAQ,QAC9D,EACF,CAAC;AAEF,QAAO,EACL,SAAS,aAAa;EAAE,WAAW;EAAsB,OAAO;EAAU,CAAC,EAC5E"}
1
+ {"version":3,"file":"shared.mjs","names":[],"sources":["../../../../src/v1-deprecated/lib/integrations/shared.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 — buildSchema:\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 — CommonConfig:\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 — CopilotEndpointCorsConfig:\n * V2 import and usage:\n * import type { CopilotEndpointCorsConfig } from \"@copilotkit/runtime/v2\";\n * type V2CopilotEndpointCorsConfig = CopilotEndpointCorsConfig;\n * V2 replacement source: packages/runtime/src/v2/runtime/endpoints/hono.ts\n * V2 docs: https://docs.copilotkit.ai/runtime-server-adapter\n *\n * @copilotkit/runtime — CopilotRequestContextProperties:\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 — CreateCopilotRuntimeServerOptions:\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 — getCommonConfig:\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 — GraphQLContext:\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 — GraphQLRequestContext:\n * No 1:1 v2 replacement is available.\n * Start at: @copilotkit/runtime/v2\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * Migration guide: https://docs.copilotkit.ai/migrate/v2\n *\n * END V1 SDK DEPRECATED. USE V2 INSTEAD NOTICE\n */\n\nimport { buildSchemaSync } from \"type-graphql\";\nimport { CopilotResolver } from \"../../graphql/resolvers/copilot.resolver\";\nimport type { CopilotRuntime } from \"../runtime/copilot-runtime\";\nimport type { CopilotServiceAdapter } from \"../../service-adapters\";\nimport type { CopilotCloudOptions } from \"../cloud\";\nimport type { LogLevel } from \"../../lib/logger\";\nimport { createLogger } from \"../../lib/logger\";\nimport telemetry from \"../telemetry-client\";\nimport { StateResolver } from \"../../graphql/resolvers/state.resolver\";\n\n/**\n * CORS configuration for CopilotKit endpoints.\n */\nexport interface CopilotEndpointCorsConfig {\n /**\n * Allowed origin(s). Can be a string, array of strings, or a function that returns the origin.\n */\n origin:\n | string\n | string[]\n | ((origin: string, c: any) => string | undefined | null);\n /**\n * Whether to include credentials (cookies, authorization headers) in CORS requests.\n * When true, origin cannot be \"*\" - must be an explicit origin.\n */\n credentials?: boolean;\n}\n\nconst logger = createLogger();\n\ntype AnyPrimitive = string | boolean | number | null;\nexport type CopilotRequestContextProperties = Record<\n string,\n AnyPrimitive | Record<string, AnyPrimitive>\n>;\n\n/**\n * The request-scoped fields the v1 middleware hooks read off the GraphQL\n * context.\n *\n * Declared here rather than imported as Yoga's `YogaInitialContext`. Nothing in\n * this package serves GraphQL any more -- every v1 integration entry point\n * delegates to the v2 Hono endpoint -- but that one type reference was enough to\n * pull the whole `graphql-yoga` barrel, and with it `lru-cache@10`, into every\n * consumer's program. `lru-cache@10` declares `implements Map`, which costs five\n * TS2416 errors under `strict` with `skipLibCheck: false` (OSS-899).\n *\n * Structurally identical to `YogaInitialContext`, so a real Yoga context still\n * satisfies it.\n */\nexport interface GraphQLRequestContext {\n /** GraphQL parameters parsed from the request. */\n params: {\n operationName?: string;\n query?: string;\n variables?: Record<string, any>;\n extensions?: Record<string, any>;\n };\n /** The incoming HTTP request. */\n request: Request;\n /** Defers work past the response, where the host runtime supports it. */\n waitUntil(promise: Promise<unknown> | void): void;\n}\n\nexport type GraphQLContext = GraphQLRequestContext & {\n _copilotkit: CreateCopilotRuntimeServerOptions;\n properties: CopilotRequestContextProperties;\n logger: typeof logger;\n};\n\nexport interface CreateCopilotRuntimeServerOptions {\n runtime: CopilotRuntime<any>;\n serviceAdapter?: CopilotServiceAdapter;\n endpoint: string;\n baseUrl?: string;\n cloud?: CopilotCloudOptions;\n properties?: CopilotRequestContextProperties;\n logLevel?: LogLevel;\n /**\n * Optional CORS configuration. When not provided, defaults to allowing all origins without credentials.\n * To support HTTP-only cookies, provide cors config with credentials: true and explicit origin.\n */\n cors?: CopilotEndpointCorsConfig;\n}\n\nexport function buildSchema(\n options: {\n emitSchemaFile?: string;\n } = {},\n) {\n logger.debug(\"Building GraphQL schema...\");\n const schema = buildSchemaSync({\n resolvers: [CopilotResolver, StateResolver],\n emitSchemaFile: options.emitSchemaFile,\n });\n logger.debug(\"GraphQL schema built successfully\");\n return schema;\n}\n\nexport type CommonConfig = {\n logging: typeof logger;\n};\n\nexport function getCommonConfig(\n options: CreateCopilotRuntimeServerOptions,\n): CommonConfig {\n const logLevel =\n (process.env.LOG_LEVEL as LogLevel) ||\n (options.logLevel as LogLevel) ||\n \"error\";\n const logger = createLogger({\n level: logLevel,\n component: \"getCommonConfig\",\n });\n\n if (options.cloud) {\n telemetry.setCloudConfiguration({\n publicApiKey: options.cloud.publicApiKey,\n baseUrl: options.cloud.baseUrl,\n });\n }\n\n if (options.properties?._copilotkit) {\n telemetry.setGlobalProperties({\n _copilotkit: {\n ...(options.properties._copilotkit as Record<string, any>),\n },\n });\n }\n\n telemetry.setGlobalProperties({\n runtime: {\n serviceAdapter: options.serviceAdapter?.constructor?.name ?? \"none\",\n },\n });\n\n return {\n logging: createLogger({ component: \"CopilotKit Runtime\", level: logLevel }),\n };\n}\n"],"mappings":";;;;;;;;AA+FA,MAAM,SAAS,cAAc;AAyD7B,SAAgB,YACd,UAEI,EAAE,EACN;AACA,QAAO,MAAM,6BAA6B;CAC1C,MAAM,SAAS,gBAAgB;EAC7B,WAAW,CAAC,iBAAiB,cAAc;EAC3C,gBAAgB,QAAQ;EACzB,CAAC;AACF,QAAO,MAAM,oCAAoC;AACjD,QAAO;;AAOT,SAAgB,gBACd,SACc;CACd,MAAM,WACH,QAAQ,IAAI,aACZ,QAAQ,YACT;AACa,cAAa;EAC1B,OAAO;EACP,WAAW;EACZ,CAAC;AAEF,KAAI,QAAQ,MACV,iBAAU,sBAAsB;EAC9B,cAAc,QAAQ,MAAM;EAC5B,SAAS,QAAQ,MAAM;EACxB,CAAC;AAGJ,KAAI,QAAQ,YAAY,YACtB,iBAAU,oBAAoB,EAC5B,aAAa,EACX,GAAI,QAAQ,WAAW,aACxB,EACF,CAAC;AAGJ,iBAAU,oBAAoB,EAC5B,SAAS,EACP,gBAAgB,QAAQ,gBAAgB,aAAa,QAAQ,QAC9D,EACF,CAAC;AAEF,QAAO,EACL,SAAS,aAAa;EAAE,WAAW;EAAsB,OAAO;EAAU,CAAC,EAC5E"}
@@ -1,7 +1,7 @@
1
1
 
2
2
  import { CustomEventNames } from "./consts.cjs";
3
- import { Observable } from "rxjs";
4
3
  import { RunAgentInput } from "@ag-ui/client";
4
+ import { Observable } from "rxjs";
5
5
  import { BaseEvent as BaseEvent$1 } from "@ag-ui/core";
6
6
  import { LangGraphAgent, LangGraphAgentConfig, LangGraphHttpAgent, ProcessedEvents, SchemaKeys, State, StateEnrichment } from "@ag-ui/langgraph";
7
7
 
@@ -6,7 +6,6 @@ const require_in_memory = require('../../v2/runtime/runner/in-memory.cjs');
6
6
  const require_telemetry_identity = require('../../v2/runtime/telemetry/telemetry-identity.cjs');
7
7
  const require_runtime_error_reporter = require('../../v2/runtime/core/runtime-error-reporter.cjs');
8
8
  const require_runtime$1 = require('../../v2/runtime/core/runtime.cjs');
9
- const require_telemetry_agent_runner = require('./telemetry-agent-runner.cjs');
10
9
  const require_types = require('./types.cjs');
11
10
  const require_mcp_tools_utils = require('./mcp-tools-utils.cjs');
12
11
  const require_index = require('../../agent/index.cjs');
@@ -60,15 +59,12 @@ var CopilotRuntime = class {
60
59
  const resolvedTelemetryId = (0, _copilotkit_shared.firstNonBlankTelemetryId)(params?.telemetryId, process.env.CPK_TELEMETRY_ID);
61
60
  const resolvedTelemetryIdentity = resolvedTelemetryId !== void 0 ? { telemetryId: resolvedTelemetryId } : resolvedLicenseToken !== void 0 ? { licenseToken: resolvedLicenseToken } : {};
62
61
  this.telemetry = require_telemetry_client.default.createScope(resolvedTelemetryIdentity);
63
- const baseRunner = params?.runner ?? new require_in_memory.InMemoryAgentRunner();
64
- const runner = (0, _copilotkit_shared.isTelemetryDisabled)() ? baseRunner : new require_telemetry_agent_runner.TelemetryAgentRunner({
65
- runner: baseRunner,
66
- telemetry: this.telemetry
67
- });
62
+ const runner = params?.runner ?? new require_in_memory.InMemoryAgentRunner();
68
63
  const sharedRuntimeArgs = {
69
64
  agents: mergedAgents,
70
65
  telemetryId: resolvedTelemetryId,
71
66
  licenseToken: resolvedLicenseToken,
67
+ ɵtelemetry: this.telemetry,
72
68
  telemetryProperties: params?.telemetryProperties,
73
69
  debug: params?.debug,
74
70
  beforeRequestMiddleware: this.createOnBeforeRequestHandler(params).bind(this),
@@ -171,17 +167,7 @@ var CopilotRuntime = class {
171
167
  createOnBeforeRequestHandler(params) {
172
168
  return async (hookParams) => {
173
169
  const { request } = hookParams;
174
- const publicApiKey = request.headers.get("x-copilotcloud-public-api-key");
175
170
  const body = await (0, _copilotkit_shared.readBody)(request);
176
- const forwardedProps = body?.forwardedProps;
177
- const cloudBaseUrl = process.env.COPILOT_CLOUD_BASE_URL || "https://api.cloud.copilotkit.ai";
178
- this.telemetry.capture("oss.runtime.copilot_request_created", {
179
- "cloud.guardrails.enabled": forwardedProps?.cloud?.guardrails !== void 0,
180
- requestType: forwardedProps?.metadata?.requestType ?? "unknown",
181
- "cloud.api_key_provided": !!publicApiKey,
182
- ...publicApiKey ? { "cloud.public_api_key": publicApiKey } : {},
183
- "cloud.base_url": cloudBaseUrl
184
- });
185
171
  if (request.method === "GET" || !body) return;
186
172
  const middlewareResult = await params?.beforeRequestMiddleware?.(hookParams);
187
173
  if (params?.middleware?.onBeforeRequest) {
@@ -1 +1 @@
1
- {"version":3,"file":"copilot-runtime.cjs","names":["firstNonBlankLicenseToken","telemetry","InMemoryAgentRunner","TelemetryAgentRunner","runtimeErrorReporterOption","createRuntimeErrorReporter","CopilotRuntimeVNext","EndpointType","CopilotKitMisuseError","BuiltInAgent","aguiToGQL","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 isTelemetryDisabled,\n} from \"@copilotkit/shared\";\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 {\n CopilotRuntime as CopilotRuntimeVNext,\n InMemoryAgentRunner,\n} from \"../../../v2/runtime\";\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 AgentRunner,\n AgentsConfig,\n AgentsFactory,\n AgentFactoryContext,\n} from \"../../../v2/runtime\";\n\nexport type { AgentsConfig, AgentsFactory, AgentFactoryContext };\nimport { TelemetryAgentRunner } from \"./telemetry-agent-runner\";\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\";\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 * @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 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 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 // Cache MCP tools per endpoint to avoid re-fetching repeatedly\n private mcpToolsCache: Map<string, BuiltInAgentClassicConfig[\"tools\"]> =\n new Map();\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 // Determine the base runner (user-provided or default)\n const baseRunner = params?.runner ?? new InMemoryAgentRunner();\n\n // Wrap with TelemetryAgentRunner unless telemetry is disabled\n // This ensures we always capture agent execution telemetry when enabled,\n // even if the user provides their own custom runner.\n const runner = isTelemetryDisabled()\n ? baseRunner\n : new TelemetryAgentRunner({\n runner: baseRunner,\n telemetry: this.telemetry,\n });\n\n const sharedRuntimeArgs = {\n agents: mergedAgents,\n telemetryId: resolvedTelemetryId,\n licenseToken: resolvedLicenseToken,\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 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 this.runtimeArgs.agents = Promise.resolve(\n this.runtimeArgs.agents ?? {},\n ).then(async (agents) => {\n // An AgentsFactory function has no enumerable keys, so it flows through\n // this path the same way an empty record does.\n let agentsList = agents as Record<string, AbstractAgent>;\n const isAgentsListEmpty = !Object.keys(agents).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 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 mcpTools = await this.getToolsFromMCP();\n const actionTools = actions ? this.getToolsFromActions(actions) : [];\n agentsList = this.assignToolsToAgents(agentsList, [\n ...actionTools,\n ...mcpTools,\n ]);\n\n return agentsList;\n });\n }\n\n // Receive this.params.action and turn it into the AbstractAgent tools\n private getToolsFromActions(\n actions: ActionsConfiguration<any>,\n ): BuiltInAgentClassicConfig[\"tools\"] {\n // Resolve actions to an array (handle function case)\n const actionsArray =\n typeof actions === \"function\"\n ? actions({ properties: {}, url: undefined })\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 // Capture telemetry for copilot request creation\n const publicApiKey = request.headers.get(\"x-copilotcloud-public-api-key\");\n const body = (await readBody(request)) as RunAgentInput;\n\n const forwardedProps = body?.forwardedProps as\n | {\n cloud?: { guardrails?: unknown };\n metadata?: { requestType?: string };\n }\n | undefined;\n\n // Get cloud base URL from environment or default\n const cloudBaseUrl =\n process.env.COPILOT_CLOUD_BASE_URL || \"https://api.cloud.copilotkit.ai\";\n\n this.telemetry.capture(\"oss.runtime.copilot_request_created\", {\n \"cloud.guardrails.enabled\":\n forwardedProps?.cloud?.guardrails !== undefined,\n requestType: forwardedProps?.metadata?.requestType ?? \"unknown\",\n \"cloud.api_key_provided\": !!publicApiKey,\n ...(publicApiKey ? { \"cloud.public_api_key\": publicApiKey } : {}),\n \"cloud.base_url\": cloudBaseUrl,\n });\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<BuiltInAgentClassicConfig[\"tools\"]> {\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 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 allTools: BuiltInAgentClassicConfig[\"tools\"] = [];\n\n for (const config of effectiveEndpoints) {\n const endpointUrl = config.endpoint;\n // Return cached tool definitions when available\n const cached = this.mcpToolsCache.get(endpointUrl);\n if (cached) {\n allTools.push(...cached);\n continue;\n }\n\n try {\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 || `MCP tool: ${toolName} (from ${endpointUrl})`,\n parameters: zodSchema,\n // The MCP client stays live for the lifetime of the cached tool\n // definitions; `tool.execute` calls the server.\n execute: async (args: unknown) => tool.execute(args),\n };\n });\n\n // Cache per endpoint and add to aggregate\n this.mcpToolsCache.set(endpointUrl, toolDefs);\n allTools.push(...toolDefs);\n } catch (error) {\n console.error(\n `MCP: Failed to fetch tools from endpoint ${endpointUrl}. 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 // Leaving the entry absent lets a later resolution try again.\n }\n }\n\n // Dedupe tools by name while preserving last-in wins (request overrides)\n const dedupedByName = new Map<string, (typeof allTools)[number]>();\n for (const tool of allTools) {\n dedupedByName.set(tool.name, tool);\n }\n\n return Array.from(dedupedByName.values());\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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;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","BuiltInAgent","aguiToGQL","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 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 {\n CopilotRuntime as CopilotRuntimeVNext,\n InMemoryAgentRunner,\n} from \"../../../v2/runtime\";\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 AgentRunner,\n AgentsConfig,\n AgentsFactory,\n AgentFactoryContext,\n} from \"../../../v2/runtime\";\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\";\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 * @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 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 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 // Cache MCP tools per endpoint to avoid re-fetching repeatedly\n private mcpToolsCache: Map<string, BuiltInAgentClassicConfig[\"tools\"]> =\n new Map();\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 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 this.runtimeArgs.agents = Promise.resolve(\n this.runtimeArgs.agents ?? {},\n ).then(async (agents) => {\n // An AgentsFactory function has no enumerable keys, so it flows through\n // this path the same way an empty record does.\n let agentsList = agents as Record<string, AbstractAgent>;\n const isAgentsListEmpty = !Object.keys(agents).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 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 mcpTools = await this.getToolsFromMCP();\n const actionTools = actions ? this.getToolsFromActions(actions) : [];\n agentsList = this.assignToolsToAgents(agentsList, [\n ...actionTools,\n ...mcpTools,\n ]);\n\n return agentsList;\n });\n }\n\n // Receive this.params.action and turn it into the AbstractAgent tools\n private getToolsFromActions(\n actions: ActionsConfiguration<any>,\n ): BuiltInAgentClassicConfig[\"tools\"] {\n // Resolve actions to an array (handle function case)\n const actionsArray =\n typeof actions === \"function\"\n ? actions({ properties: {}, url: undefined })\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<BuiltInAgentClassicConfig[\"tools\"]> {\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 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 allTools: BuiltInAgentClassicConfig[\"tools\"] = [];\n\n for (const config of effectiveEndpoints) {\n const endpointUrl = config.endpoint;\n // Return cached tool definitions when available\n const cached = this.mcpToolsCache.get(endpointUrl);\n if (cached) {\n allTools.push(...cached);\n continue;\n }\n\n try {\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 || `MCP tool: ${toolName} (from ${endpointUrl})`,\n parameters: zodSchema,\n // The MCP client stays live for the lifetime of the cached tool\n // definitions; `tool.execute` calls the server.\n execute: async (args: unknown) => tool.execute(args),\n };\n });\n\n // Cache per endpoint and add to aggregate\n this.mcpToolsCache.set(endpointUrl, toolDefs);\n allTools.push(...toolDefs);\n } catch (error) {\n console.error(\n `MCP: Failed to fetch tools from endpoint ${endpointUrl}. 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 // Leaving the entry absent lets a later resolution try again.\n }\n }\n\n // Dedupe tools by name while preserving last-in wins (request overrides)\n const dedupedByName = new Map<string, (typeof allTools)[number]>();\n for (const tool of allTools) {\n dedupedByName.set(tool.name, tool);\n }\n\n return Array.from(dedupedByName.values());\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmaA,IAAa,iBAAb,MAAmE;CAWjE,YAAY,QAA6C;uCANvD,IAAI,KAAK;AAOT,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;GAC7B,OAAO,QAAQ;GAIf,yBACE,KAAK,6BAA6B,OAAO,CAAC,KAAK,KAAK;GACtD,GAAI,QAAQ,0BAA0B,QAAQ,YAAY,iBACtD,EACE,wBACE,KAAK,4BAA4B,OAAO,CAAC,KAAK,KAAK,EACtD,GACD,EAAE;GACN,MAAM,QAAQ;GACd,SAAS,QAAQ;GACjB,kBAA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