@copilotkit/runtime 1.57.3 → 1.58.0-canary.thread-id-propagation

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 (346) hide show
  1. package/dist/lib/observability.d.cts +1 -1
  2. package/dist/lib/observability.d.cts.map +1 -1
  3. package/dist/lib/observability.d.mts +1 -1
  4. package/dist/lib/observability.d.mts.map +1 -1
  5. package/dist/lib/runtime/copilot-runtime.cjs +2 -0
  6. package/dist/lib/runtime/copilot-runtime.cjs.map +1 -1
  7. package/dist/lib/runtime/copilot-runtime.d.cts.map +1 -1
  8. package/dist/lib/runtime/copilot-runtime.d.mts.map +1 -1
  9. package/dist/lib/runtime/copilot-runtime.mjs +2 -0
  10. package/dist/lib/runtime/copilot-runtime.mjs.map +1 -1
  11. package/dist/package.cjs +5 -8
  12. package/dist/package.mjs +5 -8
  13. package/dist/v2/runtime/core/runtime.cjs +4 -1
  14. package/dist/v2/runtime/core/runtime.cjs.map +1 -1
  15. package/dist/v2/runtime/core/runtime.d.cts.map +1 -1
  16. package/dist/v2/runtime/core/runtime.d.mts.map +1 -1
  17. package/dist/v2/runtime/core/runtime.mjs +4 -1
  18. package/dist/v2/runtime/core/runtime.mjs.map +1 -1
  19. package/dist/v2/runtime/handlers/get-runtime-info.cjs +1 -1
  20. package/dist/v2/runtime/handlers/get-runtime-info.mjs +1 -1
  21. package/dist/v2/runtime/handlers/handle-connect.cjs +1 -1
  22. package/dist/v2/runtime/handlers/handle-connect.mjs +1 -1
  23. package/dist/v2/runtime/handlers/handle-run.cjs +1 -1
  24. package/dist/v2/runtime/handlers/handle-run.mjs +1 -1
  25. package/dist/v2/runtime/handlers/shared/agent-utils.cjs +1 -1
  26. package/dist/v2/runtime/handlers/shared/agent-utils.cjs.map +1 -1
  27. package/dist/v2/runtime/handlers/shared/agent-utils.mjs +1 -1
  28. package/dist/v2/runtime/handlers/shared/agent-utils.mjs.map +1 -1
  29. package/dist/v2/runtime/telemetry/telemetry-client.cjs +22 -6
  30. package/dist/v2/runtime/telemetry/telemetry-client.cjs.map +1 -1
  31. package/dist/v2/runtime/telemetry/telemetry-client.mjs +27 -11
  32. package/dist/v2/runtime/telemetry/telemetry-client.mjs.map +1 -1
  33. package/package.json +9 -19
  34. package/skills/runtime/SKILL.md +98 -0
  35. package/skills/runtime/references/agent-runners-custom.md +161 -0
  36. package/skills/runtime/references/agent-runners-in-memory.md +64 -0
  37. package/skills/runtime/references/agent-runners-sqlite.md +90 -0
  38. package/skills/runtime/references/agent-runners.md +304 -0
  39. package/skills/runtime/references/built-in-agent-factory-modes.md +232 -0
  40. package/skills/runtime/references/built-in-agent-helper-utilities.md +123 -0
  41. package/skills/runtime/references/built-in-agent-model-identifiers.md +59 -0
  42. package/skills/runtime/references/built-in-agent.md +523 -0
  43. package/skills/runtime/references/intelligence-mode.md +336 -0
  44. package/skills/runtime/references/middleware.md +376 -0
  45. package/skills/runtime/references/server-side-tools.md +414 -0
  46. package/skills/runtime/references/setup-endpoint.md +503 -0
  47. package/skills/runtime/references/transcription.md +287 -0
  48. package/skills/runtime/references/wiring-a2a.md +40 -0
  49. package/skills/runtime/references/wiring-adk.md +45 -0
  50. package/skills/runtime/references/wiring-ag2.md +41 -0
  51. package/skills/runtime/references/wiring-agno.md +39 -0
  52. package/skills/runtime/references/wiring-aws-strands.md +59 -0
  53. package/skills/runtime/references/wiring-crewai-crews.md +51 -0
  54. package/skills/runtime/references/wiring-crewai-flows.md +45 -0
  55. package/skills/runtime/references/wiring-external-agents.md +348 -0
  56. package/skills/runtime/references/wiring-langgraph.md +50 -0
  57. package/skills/runtime/references/wiring-llamaindex.md +39 -0
  58. package/skills/runtime/references/wiring-mastra.md +70 -0
  59. package/skills/runtime/references/wiring-mcp-apps-middleware.md +68 -0
  60. package/skills/runtime/references/wiring-ms-agent-framework.md +41 -0
  61. package/skills/runtime/references/wiring-pydantic-ai.md +45 -0
  62. package/CHANGELOG.md +0 -3624
  63. package/__snapshots__/schema/schema.graphql +0 -371
  64. package/dist/v2/runtime/telemetry/scarf-client.cjs +0 -32
  65. package/dist/v2/runtime/telemetry/scarf-client.cjs.map +0 -1
  66. package/dist/v2/runtime/telemetry/scarf-client.mjs +0 -32
  67. package/dist/v2/runtime/telemetry/scarf-client.mjs.map +0 -1
  68. package/scripts/generate-gql-schema.ts +0 -16
  69. package/src/agent/__tests__/agent-test-helpers.ts +0 -476
  70. package/src/agent/__tests__/agent.test.ts +0 -593
  71. package/src/agent/__tests__/ai-sdk-v6-compat.test.ts +0 -116
  72. package/src/agent/__tests__/basic-agent.test.ts +0 -1698
  73. package/src/agent/__tests__/capabilities.test.ts +0 -81
  74. package/src/agent/__tests__/config-tools-execution.test.ts +0 -516
  75. package/src/agent/__tests__/converter-aisdk.test.ts +0 -692
  76. package/src/agent/__tests__/converter-custom.test.ts +0 -319
  77. package/src/agent/__tests__/converter-tanstack-input.test.ts +0 -211
  78. package/src/agent/__tests__/converter-tanstack.test.ts +0 -594
  79. package/src/agent/__tests__/mcp-clients.test.ts +0 -246
  80. package/src/agent/__tests__/mcp-servers-integration.test.ts +0 -373
  81. package/src/agent/__tests__/multimodal-tanstack.test.ts +0 -284
  82. package/src/agent/__tests__/multimodal.test.ts +0 -176
  83. package/src/agent/__tests__/property-overrides.test.ts +0 -598
  84. package/src/agent/__tests__/provider-id-collision.test.ts +0 -195
  85. package/src/agent/__tests__/standard-schema-tools.test.ts +0 -313
  86. package/src/agent/__tests__/standard-schema-types.test.ts +0 -158
  87. package/src/agent/__tests__/state-tools.test.ts +0 -436
  88. package/src/agent/__tests__/test-helpers.ts +0 -197
  89. package/src/agent/__tests__/utils.test.ts +0 -536
  90. package/src/agent/__tests__/zod-regression.test.ts +0 -350
  91. package/src/agent/converters/aisdk.ts +0 -326
  92. package/src/agent/converters/index.ts +0 -7
  93. package/src/agent/converters/tanstack.ts +0 -451
  94. package/src/agent/index.ts +0 -1743
  95. package/src/agents/langgraph/__tests__/event-source.test.ts +0 -256
  96. package/src/agents/langgraph/event-source.ts +0 -365
  97. package/src/agents/langgraph/events.ts +0 -394
  98. package/src/graphql/inputs/action.input.ts +0 -16
  99. package/src/graphql/inputs/agent-session.input.ts +0 -13
  100. package/src/graphql/inputs/agent-state.input.ts +0 -13
  101. package/src/graphql/inputs/cloud-guardrails.input.ts +0 -16
  102. package/src/graphql/inputs/cloud.input.ts +0 -8
  103. package/src/graphql/inputs/context-property.input.ts +0 -10
  104. package/src/graphql/inputs/copilot-context.input.ts +0 -10
  105. package/src/graphql/inputs/custom-property.input.ts +0 -15
  106. package/src/graphql/inputs/extensions.input.ts +0 -21
  107. package/src/graphql/inputs/forwarded-parameters.input.ts +0 -22
  108. package/src/graphql/inputs/frontend.input.ts +0 -14
  109. package/src/graphql/inputs/generate-copilot-response.input.ts +0 -59
  110. package/src/graphql/inputs/load-agent-state.input.ts +0 -10
  111. package/src/graphql/inputs/message.input.ts +0 -110
  112. package/src/graphql/inputs/meta-event.input.ts +0 -18
  113. package/src/graphql/message-conversion/agui-to-gql.test.ts +0 -1384
  114. package/src/graphql/message-conversion/agui-to-gql.ts +0 -384
  115. package/src/graphql/message-conversion/gql-to-agui.test.ts +0 -1653
  116. package/src/graphql/message-conversion/gql-to-agui.ts +0 -297
  117. package/src/graphql/message-conversion/index.ts +0 -2
  118. package/src/graphql/message-conversion/roundtrip-conversion.test.ts +0 -561
  119. package/src/graphql/resolvers/__tests__/resolve-message-id.test.ts +0 -25
  120. package/src/graphql/resolvers/copilot.resolver.ts +0 -785
  121. package/src/graphql/resolvers/resolve-message-id.ts +0 -14
  122. package/src/graphql/resolvers/state.resolver.ts +0 -30
  123. package/src/graphql/types/agents-response.type.ts +0 -19
  124. package/src/graphql/types/base/index.ts +0 -10
  125. package/src/graphql/types/converted/index.ts +0 -183
  126. package/src/graphql/types/copilot-response.type.ts +0 -141
  127. package/src/graphql/types/enums.ts +0 -38
  128. package/src/graphql/types/extensions-response.type.ts +0 -23
  129. package/src/graphql/types/guardrails-result.type.ts +0 -20
  130. package/src/graphql/types/load-agent-state-response.type.ts +0 -17
  131. package/src/graphql/types/message-status.type.ts +0 -48
  132. package/src/graphql/types/meta-events.type.ts +0 -78
  133. package/src/graphql/types/response-status.type.ts +0 -77
  134. package/src/index.ts +0 -3
  135. package/src/langgraph.ts +0 -1
  136. package/src/lib/__tests__/telemetry-disclosure.test.ts +0 -55
  137. package/src/lib/cloud/index.ts +0 -4
  138. package/src/lib/error-messages.ts +0 -211
  139. package/src/lib/index.ts +0 -52
  140. package/src/lib/integrations/index.ts +0 -6
  141. package/src/lib/integrations/nest/index.ts +0 -21
  142. package/src/lib/integrations/nextjs/app-router.ts +0 -47
  143. package/src/lib/integrations/nextjs/pages-router.ts +0 -45
  144. package/src/lib/integrations/node-express/index.ts +0 -21
  145. package/src/lib/integrations/node-http/__tests__/request-duck-type.test.ts +0 -66
  146. package/src/lib/integrations/node-http/index.ts +0 -187
  147. package/src/lib/integrations/node-http/request-handler.ts +0 -128
  148. package/src/lib/integrations/shared.ts +0 -112
  149. package/src/lib/logger.ts +0 -31
  150. package/src/lib/observability.ts +0 -167
  151. package/src/lib/runtime/__tests__/copilot-runtime-error.test.ts +0 -183
  152. package/src/lib/runtime/__tests__/handle-service-adapter.test.ts +0 -108
  153. package/src/lib/runtime/__tests__/mcp-tools-utils.test.ts +0 -499
  154. package/src/lib/runtime/__tests__/on-after-request.test.ts +0 -122
  155. package/src/lib/runtime/__tests__/retry-utils.test.ts +0 -137
  156. package/src/lib/runtime/__tests__/v1-agent-factory.test.ts +0 -109
  157. package/src/lib/runtime/agent-integrations/langgraph/__tests__/dispatch-event-filtering.test.ts +0 -345
  158. package/src/lib/runtime/agent-integrations/langgraph/__tests__/run-message-filtering.test.ts +0 -156
  159. package/src/lib/runtime/agent-integrations/langgraph/agent.ts +0 -263
  160. package/src/lib/runtime/agent-integrations/langgraph/consts.ts +0 -37
  161. package/src/lib/runtime/agent-integrations/langgraph/index.ts +0 -2
  162. package/src/lib/runtime/copilot-runtime.ts +0 -863
  163. package/src/lib/runtime/mcp-tools-utils.ts +0 -313
  164. package/src/lib/runtime/retry-utils.ts +0 -141
  165. package/src/lib/runtime/telemetry-agent-runner.ts +0 -151
  166. package/src/lib/runtime/types.ts +0 -48
  167. package/src/lib/runtime/utils.ts +0 -93
  168. package/src/lib/streaming.ts +0 -220
  169. package/src/lib/telemetry-client.ts +0 -66
  170. package/src/lib/telemetry-disclosure.ts +0 -53
  171. package/src/service-adapters/anthropic/anthropic-adapter.ts +0 -532
  172. package/src/service-adapters/anthropic/utils.ts +0 -219
  173. package/src/service-adapters/bedrock/bedrock-adapter.ts +0 -73
  174. package/src/service-adapters/conversion.test.ts +0 -56
  175. package/src/service-adapters/conversion.ts +0 -69
  176. package/src/service-adapters/empty/empty-adapter.ts +0 -38
  177. package/src/service-adapters/events.ts +0 -337
  178. package/src/service-adapters/experimental/ollama/ollama-adapter.ts +0 -84
  179. package/src/service-adapters/google/google-genai-adapter.test.ts +0 -151
  180. package/src/service-adapters/google/google-genai-adapter.ts +0 -95
  181. package/src/service-adapters/groq/groq-adapter.ts +0 -229
  182. package/src/service-adapters/index.ts +0 -18
  183. package/src/service-adapters/langchain/langchain-adapter.ts +0 -113
  184. package/src/service-adapters/langchain/langserve.ts +0 -88
  185. package/src/service-adapters/langchain/types.ts +0 -20
  186. package/src/service-adapters/langchain/utils.ts +0 -330
  187. package/src/service-adapters/openai/__tests__/openai-v5-compat.test.ts +0 -177
  188. package/src/service-adapters/openai/openai-adapter.ts +0 -324
  189. package/src/service-adapters/openai/openai-assistant-adapter.ts +0 -385
  190. package/src/service-adapters/openai/utils.ts +0 -305
  191. package/src/service-adapters/service-adapter.ts +0 -50
  192. package/src/service-adapters/shared/error-utils.ts +0 -64
  193. package/src/service-adapters/shared/index.ts +0 -2
  194. package/src/service-adapters/shared/sdk-client-utils.ts +0 -19
  195. package/src/service-adapters/unify/unify-adapter.ts +0 -165
  196. package/src/utils/failed-response-status-reasons.ts +0 -70
  197. package/src/utils/index.ts +0 -1
  198. package/src/v2/express.ts +0 -1
  199. package/src/v2/hono.ts +0 -1
  200. package/src/v2/index.ts +0 -5
  201. package/src/v2/node.ts +0 -1
  202. package/src/v2/runtime/__tests__/agents-factory.test.ts +0 -136
  203. package/src/v2/runtime/__tests__/backward-compat.test.ts +0 -261
  204. package/src/v2/runtime/__tests__/code-review-fixes.test.ts +0 -500
  205. package/src/v2/runtime/__tests__/cors-credentials.test.ts +0 -320
  206. package/src/v2/runtime/__tests__/debug-sse-response.test.ts +0 -302
  207. package/src/v2/runtime/__tests__/express-adapter.test.ts +0 -188
  208. package/src/v2/runtime/__tests__/express-body-order.test.ts +0 -76
  209. package/src/v2/runtime/__tests__/express-fetch-bridge.test.ts +0 -344
  210. package/src/v2/runtime/__tests__/express-single-sse.test.ts +0 -122
  211. package/src/v2/runtime/__tests__/express-single-telemetry.integration.test.ts +0 -65
  212. package/src/v2/runtime/__tests__/express-telemetry.integration.test.ts +0 -101
  213. package/src/v2/runtime/__tests__/fetch-cors.test.ts +0 -205
  214. package/src/v2/runtime/__tests__/fetch-handler-validation.test.ts +0 -440
  215. package/src/v2/runtime/__tests__/fetch-handler.test.ts +0 -456
  216. package/src/v2/runtime/__tests__/fetch-router.test.ts +0 -276
  217. package/src/v2/runtime/__tests__/get-runtime-info.test.ts +0 -335
  218. package/src/v2/runtime/__tests__/handle-connect.test.ts +0 -585
  219. package/src/v2/runtime/__tests__/handle-run.test.ts +0 -1388
  220. package/src/v2/runtime/__tests__/handle-threads.test.ts +0 -930
  221. package/src/v2/runtime/__tests__/handle-transcribe.test.ts +0 -301
  222. package/src/v2/runtime/__tests__/header-utils.test.ts +0 -88
  223. package/src/v2/runtime/__tests__/hono-adapter.test.ts +0 -150
  224. package/src/v2/runtime/__tests__/hono-single-telemetry.integration.test.ts +0 -46
  225. package/src/v2/runtime/__tests__/hono-telemetry.integration.test.ts +0 -99
  226. package/src/v2/runtime/__tests__/hooks-edge-cases.test.ts +0 -457
  227. package/src/v2/runtime/__tests__/hooks.test.ts +0 -557
  228. package/src/v2/runtime/__tests__/in-process-agent-runner-messages.test.ts +0 -230
  229. package/src/v2/runtime/__tests__/in-process-agent-runner.test.ts +0 -1030
  230. package/src/v2/runtime/__tests__/integration/bun/bun-servers.integration.test.ts +0 -27
  231. package/src/v2/runtime/__tests__/integration/bun/elysia-multi.ts +0 -32
  232. package/src/v2/runtime/__tests__/integration/bun/elysia-single.ts +0 -33
  233. package/src/v2/runtime/__tests__/integration/bun/hono-bun-multi.ts +0 -25
  234. package/src/v2/runtime/__tests__/integration/bun/hono-bun-single.ts +0 -32
  235. package/src/v2/runtime/__tests__/integration/helpers/create-test-runtime.ts +0 -15
  236. package/src/v2/runtime/__tests__/integration/helpers/sse-reader.ts +0 -45
  237. package/src/v2/runtime/__tests__/integration/helpers/test-agent.ts +0 -58
  238. package/src/v2/runtime/__tests__/integration/node-servers.integration.test.ts +0 -58
  239. package/src/v2/runtime/__tests__/integration/servers/express-multi.ts +0 -35
  240. package/src/v2/runtime/__tests__/integration/servers/express-single.ts +0 -36
  241. package/src/v2/runtime/__tests__/integration/servers/fetch-direct.ts +0 -39
  242. package/src/v2/runtime/__tests__/integration/servers/hono-multi.ts +0 -30
  243. package/src/v2/runtime/__tests__/integration/servers/hono-single.ts +0 -37
  244. package/src/v2/runtime/__tests__/integration/servers/node-multi.ts +0 -45
  245. package/src/v2/runtime/__tests__/integration/servers/node-single.ts +0 -46
  246. package/src/v2/runtime/__tests__/integration/servers/types.ts +0 -18
  247. package/src/v2/runtime/__tests__/integration/suites/debug-events.suite.ts +0 -253
  248. package/src/v2/runtime/__tests__/integration/suites/multi-endpoint.suite.ts +0 -358
  249. package/src/v2/runtime/__tests__/integration/suites/single-endpoint.suite.ts +0 -363
  250. package/src/v2/runtime/__tests__/intelligence-run-telemetry.test.ts +0 -194
  251. package/src/v2/runtime/__tests__/mcp-apps-middleware-integration.test.ts +0 -275
  252. package/src/v2/runtime/__tests__/middleware-express.test.ts +0 -208
  253. package/src/v2/runtime/__tests__/middleware-single-express.test.ts +0 -213
  254. package/src/v2/runtime/__tests__/middleware-single.test.ts +0 -225
  255. package/src/v2/runtime/__tests__/middleware-sse-parser.test.ts +0 -237
  256. package/src/v2/runtime/__tests__/middleware.test.ts +0 -250
  257. package/src/v2/runtime/__tests__/node-fetch-handler.test.ts +0 -157
  258. package/src/v2/runtime/__tests__/open-generative-ui-middleware.e2e.test.ts +0 -728
  259. package/src/v2/runtime/__tests__/router-edge-cases.test.ts +0 -217
  260. package/src/v2/runtime/__tests__/routing-express.test.ts +0 -174
  261. package/src/v2/runtime/__tests__/routing-single-express.test.ts +0 -168
  262. package/src/v2/runtime/__tests__/routing-single.test.ts +0 -193
  263. package/src/v2/runtime/__tests__/routing.test.ts +0 -257
  264. package/src/v2/runtime/__tests__/runtime.test.ts +0 -234
  265. package/src/v2/runtime/__tests__/sse-response-telemetry.test.ts +0 -108
  266. package/src/v2/runtime/__tests__/telemetry.test.ts +0 -167
  267. package/src/v2/runtime/__tests__/thread-names.test.ts +0 -188
  268. package/src/v2/runtime/core/__tests__/debug-event-bus.test.ts +0 -156
  269. package/src/v2/runtime/core/debug-event-bus.ts +0 -45
  270. package/src/v2/runtime/core/fetch-cors.ts +0 -136
  271. package/src/v2/runtime/core/fetch-handler.ts +0 -492
  272. package/src/v2/runtime/core/fetch-router.ts +0 -203
  273. package/src/v2/runtime/core/hooks.ts +0 -160
  274. package/src/v2/runtime/core/middleware-sse-parser.ts +0 -210
  275. package/src/v2/runtime/core/middleware.ts +0 -115
  276. package/src/v2/runtime/core/runtime.ts +0 -432
  277. package/src/v2/runtime/endpoints/express-fetch-bridge.ts +0 -137
  278. package/src/v2/runtime/endpoints/express-single.ts +0 -54
  279. package/src/v2/runtime/endpoints/express.ts +0 -179
  280. package/src/v2/runtime/endpoints/hono-single.ts +0 -60
  281. package/src/v2/runtime/endpoints/hono.ts +0 -89
  282. package/src/v2/runtime/endpoints/index.ts +0 -4
  283. package/src/v2/runtime/endpoints/node-fetch-handler.ts +0 -48
  284. package/src/v2/runtime/endpoints/node.ts +0 -28
  285. package/src/v2/runtime/endpoints/single-route-helpers.ts +0 -125
  286. package/src/v2/runtime/express.ts +0 -2
  287. package/src/v2/runtime/handlers/__tests__/handle-debug-events.test.ts +0 -176
  288. package/src/v2/runtime/handlers/get-runtime-info.ts +0 -101
  289. package/src/v2/runtime/handlers/handle-connect.ts +0 -80
  290. package/src/v2/runtime/handlers/handle-debug-events.ts +0 -52
  291. package/src/v2/runtime/handlers/handle-run.ts +0 -111
  292. package/src/v2/runtime/handlers/handle-stop.ts +0 -77
  293. package/src/v2/runtime/handlers/handle-threads.ts +0 -11
  294. package/src/v2/runtime/handlers/handle-transcribe.ts +0 -269
  295. package/src/v2/runtime/handlers/header-utils.ts +0 -24
  296. package/src/v2/runtime/handlers/intelligence/connect.ts +0 -102
  297. package/src/v2/runtime/handlers/intelligence/run.ts +0 -351
  298. package/src/v2/runtime/handlers/intelligence/thread-names.ts +0 -246
  299. package/src/v2/runtime/handlers/intelligence/threads.ts +0 -420
  300. package/src/v2/runtime/handlers/shared/agent-utils.ts +0 -154
  301. package/src/v2/runtime/handlers/shared/intelligence-utils.ts +0 -41
  302. package/src/v2/runtime/handlers/shared/json-response.ts +0 -9
  303. package/src/v2/runtime/handlers/shared/resolve-intelligence-user.ts +0 -28
  304. package/src/v2/runtime/handlers/shared/sse-response.ts +0 -215
  305. package/src/v2/runtime/handlers/sse/__tests__/sse-connect-agent-id.test.ts +0 -71
  306. package/src/v2/runtime/handlers/sse/connect.ts +0 -30
  307. package/src/v2/runtime/handlers/sse/run.ts +0 -40
  308. package/src/v2/runtime/hono.ts +0 -2
  309. package/src/v2/runtime/index.ts +0 -51
  310. package/src/v2/runtime/intelligence-platform/__tests__/client.test.ts +0 -601
  311. package/src/v2/runtime/intelligence-platform/__tests__/intelligence-mcp-helper.test.ts +0 -246
  312. package/src/v2/runtime/intelligence-platform/client.ts +0 -818
  313. package/src/v2/runtime/intelligence-platform/index.ts +0 -10
  314. package/src/v2/runtime/node.ts +0 -6
  315. package/src/v2/runtime/open-generative-ui-middleware.ts +0 -373
  316. package/src/v2/runtime/runner/__tests__/finalize-events.test.ts +0 -109
  317. package/src/v2/runtime/runner/__tests__/in-memory-runner.e2e.test.ts +0 -775
  318. package/src/v2/runtime/runner/__tests__/in-memory-runner.test.ts +0 -777
  319. package/src/v2/runtime/runner/__tests__/intelligence-runner.test.ts +0 -1039
  320. package/src/v2/runtime/runner/agent-runner.ts +0 -35
  321. package/src/v2/runtime/runner/in-memory.ts +0 -467
  322. package/src/v2/runtime/runner/index.ts +0 -4
  323. package/src/v2/runtime/runner/intelligence.ts +0 -498
  324. package/src/v2/runtime/telemetry/__tests__/instance-created.test.ts +0 -96
  325. package/src/v2/runtime/telemetry/events.ts +0 -35
  326. package/src/v2/runtime/telemetry/index.ts +0 -7
  327. package/src/v2/runtime/telemetry/instance-created.ts +0 -44
  328. package/src/v2/runtime/telemetry/scarf-client.ts +0 -39
  329. package/src/v2/runtime/telemetry/telemetry-client.ts +0 -70
  330. package/src/v2/runtime/transcription-service/transcription-service.ts +0 -11
  331. package/tests/global.d.ts +0 -1
  332. package/tests/service-adapters/anthropic/allowlist-approach.test.ts +0 -259
  333. package/tests/service-adapters/anthropic/anthropic-adapter-language-model.test.ts +0 -101
  334. package/tests/service-adapters/anthropic/anthropic-adapter.test.ts +0 -645
  335. package/tests/service-adapters/anthropic/utils-token-trimming.test.ts +0 -301
  336. package/tests/service-adapters/groq/groq-adapter-language-model.test.ts +0 -102
  337. package/tests/service-adapters/openai/allowlist-approach.test.ts +0 -294
  338. package/tests/service-adapters/openai/openai-adapter-language-model.test.ts +0 -122
  339. package/tests/service-adapters/openai/openai-adapter.test.ts +0 -291
  340. package/tests/service-adapters/shared/sdk-client-utils.test.ts +0 -36
  341. package/tests/setup.vitest.ts +0 -8
  342. package/tests/tsconfig.json +0 -10
  343. package/tsconfig.json +0 -20
  344. package/tsdown.config.ts +0 -45
  345. package/typedoc.json +0 -4
  346. package/vitest.config.mjs +0 -13
@@ -0,0 +1,336 @@
1
+ # CopilotKit Intelligence Mode
2
+
3
+ Intelligence currently ships as a managed cloud service. The only supported `apiUrl` /
4
+ `wsUrl` today is the CopilotKit-managed cloud Intelligence instance — the `ɵ`-prefixed
5
+ runtime internals and REST/WebSocket contract that back Intelligence are still
6
+ stabilizing and `organizationId` is reserved for future self-hosted deployments. If you
7
+ need on-prem durable threads today, use SSE mode with a persistent runner
8
+ (`SqliteAgentRunner` or a custom one) instead.
9
+
10
+ Obtain `apiKey` and `organizationId` from the CopilotKit Cloud dashboard.
11
+
12
+ ### URL format
13
+
14
+ The client prepends `/api/...` and the Intelligence websocket layer derives `/runner`
15
+ or `/client` suffixes internally. Pass the bare base URLs — do NOT append `/api`,
16
+ `/socket`, `/runner`, or `/client` yourself:
17
+
18
+ ```typescript
19
+ // Correct — bare base URLs
20
+ apiUrl: "https://api.copilotkit.ai",
21
+ wsUrl: "wss://api.copilotkit.ai",
22
+
23
+ // Wrong — adding /api produces /api/api/... on every REST call; /socket/runner is not a real path
24
+ apiUrl: "https://api.copilotkit.ai/api",
25
+ wsUrl: "wss://api.copilotkit.ai/socket",
26
+ ```
27
+
28
+ Source: `packages/runtime/src/v2/runtime/intelligence-platform/client.ts:41-46, 259,
29
+ 356-357, 437, 468, 682-708`.
30
+
31
+ ## Setup
32
+
33
+ ```typescript
34
+ import {
35
+ CopilotRuntime,
36
+ CopilotKitIntelligence,
37
+ createCopilotRuntimeHandler,
38
+ } from "@copilotkit/runtime/v2";
39
+
40
+ const intelligence = new CopilotKitIntelligence({
41
+ apiUrl: "https://api.copilotkit.ai",
42
+ wsUrl: "wss://api.copilotkit.ai",
43
+ apiKey: process.env.COPILOTKIT_CLOUD_API_KEY!,
44
+ organizationId: process.env.COPILOTKIT_CLOUD_ORG_ID!,
45
+ });
46
+
47
+ const runtime = new CopilotRuntime({
48
+ agents: {
49
+ /* ... */
50
+ } as any,
51
+ intelligence,
52
+ identifyUser: (request) => ({
53
+ id: request.headers.get("x-user-id") ?? "anonymous",
54
+ }),
55
+ // Optional tuning:
56
+ generateThreadNames: true, // default true — 1 LLM call per new thread
57
+ lockTtlSeconds: 20, // clamped to ≤ 3600
58
+ lockHeartbeatIntervalSeconds: 15, // clamped to ≤ 3000
59
+ });
60
+
61
+ const handler = createCopilotRuntimeHandler({
62
+ runtime,
63
+ basePath: "/api/copilotkit",
64
+ });
65
+
66
+ export default { fetch: handler };
67
+ ```
68
+
69
+ When `intelligence` is set, the runtime auto-wires `IntelligenceAgentRunner` internally.
70
+ Do NOT pass `runner` — see the failure-modes section.
71
+
72
+ ## Core Patterns
73
+
74
+ ### Identify the user from an auth cookie
75
+
76
+ `identifyUser` is for user identification only — it does NOT forward thrown `Response`s.
77
+ `resolveIntelligenceUser` (`handlers/shared/resolve-intelligence-user.ts:14-24`) wraps the
78
+ call in try/catch and converts any thrown value (including `Response`) into a generic
79
+ `errorResponse("Failed to identify user", 500)`. Gate auth in `hooks.onRequest`
80
+ (see the `middleware` skill) and keep `identifyUser` focused on returning an id:
81
+
82
+ ```typescript
83
+ import {
84
+ CopilotRuntime,
85
+ createCopilotRuntimeHandler,
86
+ } from "@copilotkit/runtime/v2";
87
+ import { parse } from "cookie";
88
+
89
+ const runtime = new CopilotRuntime({
90
+ agents,
91
+ intelligence,
92
+ // identifyUser returns the id; auth rejection is hooked elsewhere.
93
+ identifyUser: async (request) => {
94
+ const cookies = parse(request.headers.get("cookie") ?? "");
95
+ const user = await resolveSession(cookies["session"]); // your auth lib
96
+ return { id: user?.id ?? "anonymous" };
97
+ },
98
+ });
99
+
100
+ const handler = createCopilotRuntimeHandler({
101
+ runtime,
102
+ basePath: "/api/copilotkit",
103
+ hooks: {
104
+ onRequest: async ({ request }) => {
105
+ const cookies = parse(request.headers.get("cookie") ?? "");
106
+ const user = await resolveSession(cookies["session"]);
107
+ // onRequest DOES forward thrown Responses — use it for auth rejection.
108
+ if (!user) throw new Response("Unauthorized", { status: 401 });
109
+ },
110
+ },
111
+ });
112
+
113
+ async function resolveSession(token: string | undefined) {
114
+ if (!token) return null;
115
+ return { id: "user-123" };
116
+ }
117
+ ```
118
+
119
+ ### Disable thread-name generation to avoid a per-thread LLM call
120
+
121
+ ```typescript
122
+ new CopilotRuntime({
123
+ agents,
124
+ intelligence,
125
+ identifyUser: (req) => ({ id: req.headers.get("x-user-id")! }),
126
+ generateThreadNames: false,
127
+ });
128
+ ```
129
+
130
+ ### Frontend — no config change
131
+
132
+ The frontend reads `GET /info` on mount. When the runtime reports `mode: "intelligence"`
133
+ and an `intelligence.wsUrl`, `CopilotKitCore` auto-switches from SSE to the websocket
134
+ transport. The React integration just points at the runtime URL:
135
+
136
+ ```tsx
137
+ import { CopilotKitProvider } from "@copilotkit/react-core/v2";
138
+
139
+ export function App({ children }: { children: React.ReactNode }) {
140
+ return (
141
+ <CopilotKitProvider runtimeUrl="/api/copilotkit">
142
+ {children}
143
+ </CopilotKitProvider>
144
+ );
145
+ }
146
+ ```
147
+
148
+ ## Common Mistakes
149
+
150
+ ### CRITICAL Missing identifyUser
151
+
152
+ Wrong:
153
+
154
+ ```typescript
155
+ new CopilotRuntime({ agents, intelligence });
156
+ ```
157
+
158
+ Correct:
159
+
160
+ ```typescript
161
+ new CopilotRuntime({
162
+ agents,
163
+ intelligence,
164
+ identifyUser: (req) => ({ id: req.headers.get("x-user-id")! }),
165
+ });
166
+ ```
167
+
168
+ `identifyUser` is required on `CopilotIntelligenceRuntimeOptions` — omitting it is a
169
+ TypeScript error and (if suppressed) crashes handlers at request time. Every thread is
170
+ scoped to a user ID.
171
+
172
+ Source: `packages/runtime/src/v2/runtime/core/runtime.ts:156-160`.
173
+
174
+ ### CRITICAL Adding /api or /socket suffixes, or pointing at an unsupported self-hosted server
175
+
176
+ Wrong:
177
+
178
+ ```typescript
179
+ new CopilotKitIntelligence({
180
+ apiUrl: "https://api.copilotkit.ai/api", // double /api prefix
181
+ wsUrl: "wss://api.copilotkit.ai/socket", // /socket is not a real path
182
+ apiKey,
183
+ organizationId,
184
+ });
185
+
186
+ new CopilotKitIntelligence({
187
+ apiUrl: "https://internal.myco.com/intelligence", // self-hosting is not yet supported
188
+ wsUrl: "wss://internal.myco.com/intelligence",
189
+ apiKey,
190
+ organizationId,
191
+ });
192
+ ```
193
+
194
+ Correct:
195
+
196
+ ```typescript
197
+ new CopilotKitIntelligence({
198
+ apiUrl: "https://api.copilotkit.ai",
199
+ wsUrl: "wss://api.copilotkit.ai",
200
+ apiKey: process.env.COPILOTKIT_CLOUD_API_KEY!,
201
+ organizationId: process.env.COPILOTKIT_CLOUD_ORG_ID!,
202
+ });
203
+ // For on-prem durability without Intelligence: SSE mode + SqliteAgentRunner.
204
+ ```
205
+
206
+ Two failure modes to avoid:
207
+
208
+ 1. The client prepends `/api/...` to every REST call (`#request` at line 356-357) and
209
+ the websocket layer derives `/runner` / `/client` suffixes from `wsUrl` internally.
210
+ Passing `apiUrl: ".../api"` produces double-prefixed `/api/api/threads`; passing
211
+ `wsUrl: ".../socket"` produces a broken `.../socket/runner` upgrade path.
212
+ 2. Self-hosting Intelligence is not yet supported. The `ɵ`-prefixed runtime internals
213
+ and REST/WebSocket contract are still stabilizing. `organizationId` is reserved for
214
+ future self-hosted instances. For on-prem durable threads today, use SSE mode +
215
+ `SqliteAgentRunner` (see `copilotkit/agent-runners`).
216
+
217
+ Source: `packages/runtime/src/v2/runtime/intelligence-platform/client.ts:41-46, 68-69,
218
+ 259, 356-357, 437, 682-708`.
219
+
220
+ ### HIGH Setting runner alongside intelligence
221
+
222
+ Wrong:
223
+
224
+ ```typescript
225
+ import { SqliteAgentRunner } from "@copilotkit/sqlite-runner";
226
+
227
+ new CopilotRuntime({
228
+ agents,
229
+ intelligence,
230
+ runner: new SqliteAgentRunner({ dbPath: "./threads.db" }),
231
+ });
232
+ ```
233
+
234
+ Correct:
235
+
236
+ ```typescript
237
+ new CopilotRuntime({
238
+ agents,
239
+ intelligence,
240
+ identifyUser,
241
+ });
242
+ ```
243
+
244
+ `CopilotIntelligenceRuntimeOptions` excludes `runner` at the type level. Intelligence
245
+ forces its own `IntelligenceAgentRunner` tied to the Cloud WebSocket; a user-supplied
246
+ runner is rejected.
247
+
248
+ Source: `packages/runtime/src/v2/runtime/core/runtime.ts:149-173,285-294`.
249
+
250
+ ### HIGH Calling /threads against an SSE-mode runtime
251
+
252
+ Wrong:
253
+
254
+ ```typescript
255
+ // SSE-only runtime (no `intelligence` configured)
256
+ await fetch("/api/copilotkit/threads");
257
+ ```
258
+
259
+ Correct:
260
+
261
+ ```typescript
262
+ // Enable Intelligence mode first, OR don't call thread routes.
263
+ // Client-side, the useThreads hook errors with "Runtime URL is not configured" when
264
+ // the runtime isn't in Intelligence mode.
265
+ ```
266
+
267
+ The `/threads`, `/threads/subscribe`, `PATCH /threads/:id`, `POST /threads/:id/archive`,
268
+ `DELETE /threads/:id`, and `/threads/:id/messages` routes always resolve in the router,
269
+ but the handlers call `requireIntelligenceRuntime(runtime)` first and return HTTP 422
270
+ ("Missing CopilotKitIntelligence configuration. Thread operations require a
271
+ CopilotKitIntelligence instance to be provided in CopilotRuntime options.") when the
272
+ runtime isn't an `IntelligenceRuntime`.
273
+
274
+ Source: `packages/runtime/src/v2/runtime/handlers/intelligence/threads.ts:37-48`;
275
+ route table in `dev-docs/architecture/setup-intelligence.md:179-183`.
276
+
277
+ ### LOW Over-clamping lockTtlSeconds
278
+
279
+ Wrong:
280
+
281
+ ```typescript
282
+ new CopilotRuntime({
283
+ agents,
284
+ intelligence,
285
+ identifyUser,
286
+ lockTtlSeconds: 86400, // "I want 1-day lock"
287
+ });
288
+ ```
289
+
290
+ Correct:
291
+
292
+ ```typescript
293
+ new CopilotRuntime({
294
+ agents,
295
+ intelligence,
296
+ identifyUser,
297
+ lockTtlSeconds: 3600, // max is 1 hour
298
+ });
299
+ // Rethink long-running workflows if 1 hour is insufficient.
300
+ ```
301
+
302
+ `lockTtlSeconds` is silently `Math.min(value, 3600)`; `lockHeartbeatIntervalSeconds` is
303
+ `Math.min(value, 3000)`. Requests over the cap are clamped without warning.
304
+
305
+ Source: `packages/runtime/src/v2/runtime/core/runtime.ts:281-307`.
306
+
307
+ ### MEDIUM generateThreadNames unset expecting no LLM cost
308
+
309
+ Wrong:
310
+
311
+ ```typescript
312
+ new CopilotRuntime({ agents, intelligence, identifyUser });
313
+ // assumes no extra LLM spend
314
+ ```
315
+
316
+ Correct:
317
+
318
+ ```typescript
319
+ new CopilotRuntime({
320
+ agents,
321
+ intelligence,
322
+ identifyUser,
323
+ generateThreadNames: false,
324
+ });
325
+ ```
326
+
327
+ `generateThreadNames` defaults to `true`. Every newly created thread triggers an extra
328
+ LLM call on the Cloud side to generate a short name, billed against your Cloud quota.
329
+
330
+ Source: `packages/runtime/src/v2/runtime/core/runtime.ts` (generateThreadNames default).
331
+
332
+ ## See also
333
+
334
+ - `copilotkit/agent-runners` — Intelligence forces `IntelligenceAgentRunner`
335
+ - `copilotkit/setup-endpoint` — `/threads/*` routes flip on with Intelligence
336
+ - `copilotkit/threads` (react-core) — `useThreads` depends on Intelligence routes
@@ -0,0 +1,376 @@
1
+ # CopilotKit Runtime Middleware
2
+
3
+ Two coexisting middleware surfaces:
4
+
5
+ - **`hooks`** (preferred, newer) — pass to `createCopilotRuntimeHandler({ hooks })`.
6
+ Route-aware via `onBeforeHandler({ route })`. Throw a `Response` to short-circuit.
7
+ - **`beforeRequestMiddleware` / `afterRequestMiddleware`** (legacy) — pass to
8
+ `new CopilotRuntime({ ... })`. Runs **after `hooks.onRequest` but before routing** (see
9
+ `fetch-handler.ts:136-147` for exact order). Pre-routing only.
10
+
11
+ Use **hooks** for new code.
12
+
13
+ ## Setup
14
+
15
+ ```typescript
16
+ import {
17
+ CopilotRuntime,
18
+ createCopilotRuntimeHandler,
19
+ } from "@copilotkit/runtime/v2";
20
+
21
+ const runtime = new CopilotRuntime({
22
+ agents: {
23
+ /* ... */
24
+ } as any,
25
+ });
26
+
27
+ const handler = createCopilotRuntimeHandler({
28
+ runtime,
29
+ basePath: "/api/copilotkit",
30
+ hooks: {
31
+ onRequest: async ({ request }) => {
32
+ const token = request.headers.get("authorization");
33
+ if (!token) throw new Response("Unauthorized", { status: 401 });
34
+ },
35
+ onBeforeHandler: async ({ route, request }) => {
36
+ if (route.method === "agent/run" && route.agentId === "admin") {
37
+ const user = await verifyAdminToken(
38
+ request.headers.get("authorization"),
39
+ );
40
+ if (!user) throw new Response("Forbidden", { status: 403 });
41
+ }
42
+ },
43
+ onResponse: async ({ response }) => {
44
+ const headers = new Headers(response.headers);
45
+ headers.set("x-copilot-version", "2.0");
46
+ return new Response(response.body, {
47
+ status: response.status,
48
+ statusText: response.statusText,
49
+ headers,
50
+ });
51
+ },
52
+ onError: async ({ error, route }) => {
53
+ console.error("[copilotkit]", route?.method, error);
54
+ },
55
+ },
56
+ });
57
+
58
+ async function verifyAdminToken(
59
+ header: string | null,
60
+ ): Promise<{ id: string } | null> {
61
+ if (!header) return null;
62
+ // delegate to your auth lib
63
+ return { id: "admin" };
64
+ }
65
+
66
+ export default { fetch: handler };
67
+ ```
68
+
69
+ ## Core Patterns
70
+
71
+ ### Reject unauthenticated requests at the runtime boundary
72
+
73
+ ```typescript
74
+ createCopilotRuntimeHandler({
75
+ runtime,
76
+ basePath: "/api/copilotkit",
77
+ hooks: {
78
+ onRequest: ({ request }) => {
79
+ const token = request.headers.get("authorization");
80
+ if (!token?.startsWith("Bearer ")) {
81
+ throw new Response(JSON.stringify({ error: "unauthorized" }), {
82
+ status: 401,
83
+ headers: { "content-type": "application/json" },
84
+ });
85
+ }
86
+ },
87
+ },
88
+ });
89
+ ```
90
+
91
+ ### Route-aware authorization
92
+
93
+ Use `onBeforeHandler` — the `route` object carries `method`, `agentId`, and (for thread/stop
94
+ methods) `threadId`.
95
+
96
+ ```typescript
97
+ createCopilotRuntimeHandler({
98
+ runtime,
99
+ basePath: "/api/copilotkit",
100
+ hooks: {
101
+ onBeforeHandler: async ({ route, request }) => {
102
+ if (route.method === "agent/run" && route.agentId === "billing") {
103
+ const ok = await canAccessBilling(request);
104
+ if (!ok) throw new Response("Forbidden", { status: 403 });
105
+ }
106
+ },
107
+ },
108
+ });
109
+
110
+ async function canAccessBilling(request: Request): Promise<boolean> {
111
+ // delegate to your policy engine
112
+ return true;
113
+ }
114
+ ```
115
+
116
+ ### Rate-limit by calling an external limiter from the hook
117
+
118
+ Delegate to a dedicated lib — do not implement a rate limiter inline.
119
+
120
+ ```typescript
121
+ import { Ratelimit } from "@upstash/ratelimit";
122
+ import { Redis } from "@upstash/redis";
123
+
124
+ const ratelimit = new Ratelimit({
125
+ redis: Redis.fromEnv(),
126
+ limiter: Ratelimit.slidingWindow(60, "1 m"),
127
+ });
128
+
129
+ createCopilotRuntimeHandler({
130
+ runtime,
131
+ basePath: "/api/copilotkit",
132
+ hooks: {
133
+ onRequest: async ({ request }) => {
134
+ const userId = request.headers.get("x-user-id") ?? "anon";
135
+ const { success } = await ratelimit.limit(userId);
136
+ if (!success) throw new Response("Too Many Requests", { status: 429 });
137
+ },
138
+ },
139
+ });
140
+ ```
141
+
142
+ ### Non-blocking telemetry on response
143
+
144
+ `afterRequestMiddleware` runs non-blocking (errors inside only log). Do not await heavy
145
+ work that the user's response waits on.
146
+
147
+ ```typescript
148
+ import { CopilotRuntime } from "@copilotkit/runtime/v2";
149
+
150
+ const runtime = new CopilotRuntime({
151
+ agents: {
152
+ /* ... */
153
+ } as any,
154
+ afterRequestMiddleware: async ({ threadId, messages }) => {
155
+ // fire-and-forget; do not await heavy work that blocks response
156
+ void queue.enqueue({ type: "chat", threadId, messages });
157
+ },
158
+ });
159
+ ```
160
+
161
+ ## Common Mistakes
162
+
163
+ ### HIGH Returning a Response instead of throwing
164
+
165
+ Wrong:
166
+
167
+ ```typescript
168
+ new CopilotRuntime({
169
+ agents,
170
+ beforeRequestMiddleware: async () =>
171
+ new Response("Unauthorized", { status: 401 }),
172
+ });
173
+ ```
174
+
175
+ Correct:
176
+
177
+ ```typescript
178
+ new CopilotRuntime({
179
+ agents,
180
+ beforeRequestMiddleware: async ({ request }) => {
181
+ if (!request.headers.get("authorization")) {
182
+ throw new Response("Unauthorized", { status: 401 });
183
+ }
184
+ },
185
+ });
186
+ ```
187
+
188
+ The middleware contract returns `Request | void`. Returning a Response corrupts the
189
+ request object — `fetch-handler.ts:140-147` assigns any truthy return value back to
190
+ `request`, so the router then tries to read `request.method` / `request.headers.get(...)`
191
+ from the Response and downstream handling blows up. Always `throw` a Response to
192
+ short-circuit; never return one.
193
+
194
+ Source: `packages/runtime/src/v2/runtime/core/fetch-handler.ts:140-156`.
195
+
196
+ ### MEDIUM Defaulting to beforeRequestMiddleware when hooks are preferred
197
+
198
+ Wrong:
199
+
200
+ ```typescript
201
+ new CopilotRuntime({
202
+ agents,
203
+ beforeRequestMiddleware: async ({ request, path }) => {
204
+ if (path.includes("/agent/admin/")) {
205
+ /* check admin auth */
206
+ }
207
+ },
208
+ });
209
+ ```
210
+
211
+ Correct:
212
+
213
+ ```typescript
214
+ const runtime = new CopilotRuntime({ agents });
215
+ const handler = createCopilotRuntimeHandler({
216
+ runtime,
217
+ basePath: "/api/copilotkit",
218
+ hooks: {
219
+ onBeforeHandler: ({ route, request }) => {
220
+ if (route.method === "agent/run" && route.agentId === "admin") {
221
+ /* ... */
222
+ }
223
+ },
224
+ },
225
+ });
226
+ ```
227
+
228
+ Both surfaces coexist. For new code the hook API on `createCopilotRuntimeHandler` is
229
+ preferred — `onBeforeHandler` receives typed `route` info, so you don't string-match paths.
230
+
231
+ Source: `packages/runtime/src/v2/runtime/core/hooks.ts:84-117`; maintainer Phase 4c.
232
+
233
+ ### MEDIUM Route-specific auth in global beforeRequestMiddleware
234
+
235
+ Wrong:
236
+
237
+ ```typescript
238
+ new CopilotRuntime({
239
+ agents,
240
+ beforeRequestMiddleware: async ({ path, request }) => {
241
+ if (path.includes("/agent/admin/")) {
242
+ /* ... */
243
+ }
244
+ },
245
+ });
246
+ ```
247
+
248
+ Correct:
249
+
250
+ ```typescript
251
+ createCopilotRuntimeHandler({
252
+ runtime,
253
+ basePath: "/api/copilotkit",
254
+ hooks: {
255
+ onBeforeHandler: ({ route, request }) => {
256
+ if (route.method === "agent/run" && route.agentId === "admin") {
257
+ /* ... */
258
+ }
259
+ },
260
+ },
261
+ });
262
+ ```
263
+
264
+ `beforeRequestMiddleware` fires before routing, so no route info exists yet — string-matching
265
+ paths is fragile. `onBeforeHandler` fires after routing with typed `route.method`, `route.agentId`.
266
+
267
+ Source: `packages/runtime/src/v2/runtime/core/hooks.ts:94-103`.
268
+
269
+ ### MEDIUM Blocking on afterRequestMiddleware
270
+
271
+ Wrong:
272
+
273
+ ```typescript
274
+ new CopilotRuntime({
275
+ agents,
276
+ afterRequestMiddleware: async ({ response, threadId, messages }) => {
277
+ await heavyAnalytics(response, threadId, messages);
278
+ },
279
+ });
280
+ ```
281
+
282
+ Correct:
283
+
284
+ ```typescript
285
+ new CopilotRuntime({
286
+ agents,
287
+ afterRequestMiddleware: async ({ response, threadId, messages }) => {
288
+ void queue.enqueue({ type: "chat", threadId, messages, response });
289
+ },
290
+ });
291
+ ```
292
+
293
+ The `afterRequestMiddleware` callback receives
294
+ `{ runtime, response, path, messages?, threadId?, runId? }` — all these fields are always
295
+ available (`messages`/`threadId`/`runId` are populated from the SSE stream when present,
296
+ undefined otherwise). The hook runs non-blocking via `.catch()` so errors only log and any
297
+ heavy awaited work can be lost on process exit — fire-and-forget is the intended shape.
298
+
299
+ Source: `packages/runtime/src/v2/runtime/core/fetch-handler.ts:225-234`.
300
+
301
+ ### MEDIUM Passing a webhook URL string as middleware
302
+
303
+ Wrong:
304
+
305
+ ```typescript
306
+ new CopilotRuntime({
307
+ agents,
308
+ beforeRequestMiddleware: "https://hooks.example/auth" as any,
309
+ });
310
+ ```
311
+
312
+ Correct:
313
+
314
+ ```typescript
315
+ new CopilotRuntime({
316
+ agents,
317
+ beforeRequestMiddleware: async ({ request }) => {
318
+ await fetch("https://hooks.example/auth", {
319
+ method: "POST",
320
+ body: request.headers.get("authorization") ?? "",
321
+ });
322
+ },
323
+ });
324
+ ```
325
+
326
+ Webhook-URL middleware is dead code in v2 — the runtime logs
327
+ `"Unsupported beforeRequestMiddleware value – skipped"` and does nothing. Only function
328
+ middleware is wired.
329
+
330
+ Source: `packages/runtime/src/v2/runtime/core/middleware.ts:72-87`.
331
+
332
+ ### HIGH Implementing auth / rate-limit inside CopilotKit middleware
333
+
334
+ Wrong:
335
+
336
+ ```typescript
337
+ new CopilotRuntime({
338
+ agents,
339
+ beforeRequestMiddleware: async ({ request }) => {
340
+ // hand-rolling a token-bucket rate limiter inline with Redis calls...
341
+ },
342
+ });
343
+ ```
344
+
345
+ Correct:
346
+
347
+ ```typescript
348
+ import { Ratelimit } from "@upstash/ratelimit";
349
+ import { Redis } from "@upstash/redis";
350
+
351
+ const ratelimit = new Ratelimit({
352
+ redis: Redis.fromEnv(),
353
+ limiter: Ratelimit.slidingWindow(60, "1 m"),
354
+ });
355
+
356
+ new CopilotRuntime({
357
+ agents,
358
+ beforeRequestMiddleware: async ({ request }) => {
359
+ const { success } = await ratelimit.limit(
360
+ request.headers.get("x-user-id") ?? "anon",
361
+ );
362
+ if (!success) throw new Response("Too Many Requests", { status: 429 });
363
+ },
364
+ });
365
+ ```
366
+
367
+ Auth, rate-limiting, and observability are server-framework concerns. CopilotKit middleware
368
+ is the hook to invoke them, not a replacement.
369
+
370
+ Source: maintainer interview (Phase 2c).
371
+
372
+ ## See also
373
+
374
+ - `copilotkit/setup-endpoint` — `hooks` are passed to `createCopilotRuntimeHandler`
375
+ - `copilotkit/go-to-production` — production checklist lists auth/rate-limit wiring
376
+ - `copilotkit/debug-and-troubleshoot` — `onError` telemetry pattern