@copilotkit/runtime 1.50.0-beta.8 → 1.50.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 (226) hide show
  1. package/CHANGELOG.md +168 -0
  2. package/dist/chunk-27JKTS6P.mjs +1704 -0
  3. package/dist/chunk-27JKTS6P.mjs.map +1 -0
  4. package/dist/chunk-2GPTVDTO.mjs +25 -0
  5. package/dist/chunk-2GPTVDTO.mjs.map +1 -0
  6. package/dist/chunk-2OZAGFV3.mjs +43 -0
  7. package/dist/chunk-2OZAGFV3.mjs.map +1 -0
  8. package/dist/chunk-3AJVKDZX.mjs +3097 -0
  9. package/dist/chunk-3AJVKDZX.mjs.map +1 -0
  10. package/dist/chunk-45RCC3ZS.mjs +25 -0
  11. package/dist/chunk-45RCC3ZS.mjs.map +1 -0
  12. package/dist/chunk-4EHJ4XFJ.mjs +25 -0
  13. package/dist/chunk-4EHJ4XFJ.mjs.map +1 -0
  14. package/dist/chunk-4IANB4TC.mjs +25 -0
  15. package/dist/chunk-4IANB4TC.mjs.map +1 -0
  16. package/dist/chunk-4KES76K3.mjs +74 -0
  17. package/dist/chunk-4KES76K3.mjs.map +1 -0
  18. package/dist/chunk-4OGE3SLW.mjs +3100 -0
  19. package/dist/chunk-4OGE3SLW.mjs.map +1 -0
  20. package/dist/chunk-54YJBMCP.mjs +3097 -0
  21. package/dist/chunk-54YJBMCP.mjs.map +1 -0
  22. package/dist/chunk-62NE5S6M.mjs +226 -0
  23. package/dist/chunk-62NE5S6M.mjs.map +1 -0
  24. package/dist/chunk-6ER4SZYH.mjs +74 -0
  25. package/dist/chunk-6ER4SZYH.mjs.map +1 -0
  26. package/dist/chunk-6TNSLHVR.mjs +74 -0
  27. package/dist/chunk-6TNSLHVR.mjs.map +1 -0
  28. package/dist/chunk-6XRUR5UK.mjs +1 -0
  29. package/dist/chunk-6XRUR5UK.mjs.map +1 -0
  30. package/dist/chunk-7V4BK7TZ.mjs +25 -0
  31. package/dist/chunk-7V4BK7TZ.mjs.map +1 -0
  32. package/dist/chunk-7YZIEXD2.mjs +74 -0
  33. package/dist/chunk-7YZIEXD2.mjs.map +1 -0
  34. package/dist/chunk-A4XHOAFU.mjs +25 -0
  35. package/dist/chunk-A4XHOAFU.mjs.map +1 -0
  36. package/dist/chunk-A555KEAD.mjs +6020 -0
  37. package/dist/chunk-A555KEAD.mjs.map +1 -0
  38. package/dist/chunk-AF73TFTX.mjs +74 -0
  39. package/dist/chunk-AF73TFTX.mjs.map +1 -0
  40. package/dist/chunk-AMUJQ6IR.mjs +50 -0
  41. package/dist/chunk-AMUJQ6IR.mjs.map +1 -0
  42. package/dist/chunk-AQG2SVCA.mjs +25 -0
  43. package/dist/chunk-AQG2SVCA.mjs.map +1 -0
  44. package/dist/chunk-BJZHMXND.mjs +74 -0
  45. package/dist/chunk-BJZHMXND.mjs.map +1 -0
  46. package/dist/chunk-CB2OJXF6.mjs +25 -0
  47. package/dist/chunk-CB2OJXF6.mjs.map +1 -0
  48. package/dist/chunk-CEOMFPJU.mjs +6020 -0
  49. package/dist/chunk-CEOMFPJU.mjs.map +1 -0
  50. package/dist/chunk-CZVLR7CC.mjs +175 -0
  51. package/dist/chunk-CZVLR7CC.mjs.map +1 -0
  52. package/dist/chunk-DCEEHMLJ.mjs +1127 -0
  53. package/dist/chunk-DCEEHMLJ.mjs.map +1 -0
  54. package/dist/chunk-DE3CLKUG.mjs +25 -0
  55. package/dist/chunk-DE3CLKUG.mjs.map +1 -0
  56. package/dist/chunk-DTPRUTNV.mjs +25 -0
  57. package/dist/chunk-DTPRUTNV.mjs.map +1 -0
  58. package/dist/chunk-ERUOA47O.mjs +626 -0
  59. package/dist/chunk-ERUOA47O.mjs.map +1 -0
  60. package/dist/chunk-ESSRC64W.mjs +74 -0
  61. package/dist/chunk-ESSRC64W.mjs.map +1 -0
  62. package/dist/chunk-FHD4JECV.mjs +33 -0
  63. package/dist/chunk-FHD4JECV.mjs.map +1 -0
  64. package/dist/chunk-GRAN6K6N.mjs +25 -0
  65. package/dist/chunk-GRAN6K6N.mjs.map +1 -0
  66. package/dist/chunk-I27F2UPA.mjs +175 -0
  67. package/dist/chunk-I27F2UPA.mjs.map +1 -0
  68. package/dist/chunk-IAZKTOQW.mjs +25 -0
  69. package/dist/chunk-IAZKTOQW.mjs.map +1 -0
  70. package/dist/chunk-J6XZ5MFB.mjs +25 -0
  71. package/dist/chunk-J6XZ5MFB.mjs.map +1 -0
  72. package/dist/chunk-JJ32MA4C.mjs +73 -0
  73. package/dist/chunk-JJ32MA4C.mjs.map +1 -0
  74. package/dist/chunk-JJY4ZTHQ.mjs +25 -0
  75. package/dist/chunk-JJY4ZTHQ.mjs.map +1 -0
  76. package/dist/chunk-KEYLBFU2.mjs +3117 -0
  77. package/dist/chunk-KEYLBFU2.mjs.map +1 -0
  78. package/dist/chunk-KQ53L4WZ.mjs +3094 -0
  79. package/dist/chunk-KQ53L4WZ.mjs.map +1 -0
  80. package/dist/chunk-KTELVQ67.mjs +3098 -0
  81. package/dist/chunk-KTELVQ67.mjs.map +1 -0
  82. package/dist/chunk-LPEPX6NH.mjs +25 -0
  83. package/dist/chunk-LPEPX6NH.mjs.map +1 -0
  84. package/dist/chunk-MDXE55DK.mjs +3117 -0
  85. package/dist/chunk-MDXE55DK.mjs.map +1 -0
  86. package/dist/chunk-MMFUVOXH.mjs +73 -0
  87. package/dist/chunk-MMFUVOXH.mjs.map +1 -0
  88. package/dist/chunk-N3Y4U66N.mjs +253 -0
  89. package/dist/chunk-N3Y4U66N.mjs.map +1 -0
  90. package/dist/chunk-O7UYB4MH.mjs +25 -0
  91. package/dist/chunk-O7UYB4MH.mjs.map +1 -0
  92. package/dist/chunk-OFNVQHNM.mjs +3089 -0
  93. package/dist/chunk-OFNVQHNM.mjs.map +1 -0
  94. package/dist/chunk-OFSV5GET.mjs +3074 -0
  95. package/dist/chunk-OFSV5GET.mjs.map +1 -0
  96. package/dist/chunk-OMRST67R.mjs +25 -0
  97. package/dist/chunk-OMRST67R.mjs.map +1 -0
  98. package/dist/chunk-OWIGJONH.mjs +275 -0
  99. package/dist/chunk-OWIGJONH.mjs.map +1 -0
  100. package/dist/chunk-PRZHE74A.mjs +25 -0
  101. package/dist/chunk-PRZHE74A.mjs.map +1 -0
  102. package/dist/chunk-PTYRVXXP.mjs +80 -0
  103. package/dist/chunk-PTYRVXXP.mjs.map +1 -0
  104. package/dist/chunk-R22B5CCO.mjs +25 -0
  105. package/dist/chunk-R22B5CCO.mjs.map +1 -0
  106. package/dist/chunk-SHBDMA63.mjs +141 -0
  107. package/dist/chunk-SHBDMA63.mjs.map +1 -0
  108. package/dist/chunk-SPVXBPRA.mjs +74 -0
  109. package/dist/chunk-SPVXBPRA.mjs.map +1 -0
  110. package/dist/chunk-T72G46ME.mjs +25 -0
  111. package/dist/chunk-T72G46ME.mjs.map +1 -0
  112. package/dist/chunk-TGELROPU.mjs +25 -0
  113. package/dist/chunk-TGELROPU.mjs.map +1 -0
  114. package/dist/chunk-UNX4IAAD.mjs +25 -0
  115. package/dist/chunk-UNX4IAAD.mjs.map +1 -0
  116. package/dist/chunk-V4DHVC7M.mjs +3085 -0
  117. package/dist/chunk-V4DHVC7M.mjs.map +1 -0
  118. package/dist/chunk-VVRFOB66.mjs +25 -0
  119. package/dist/chunk-VVRFOB66.mjs.map +1 -0
  120. package/dist/chunk-W6NVBYM6.mjs +80 -0
  121. package/dist/chunk-W6NVBYM6.mjs.map +1 -0
  122. package/dist/chunk-W7MBACGC.mjs +74 -0
  123. package/dist/chunk-W7MBACGC.mjs.map +1 -0
  124. package/dist/chunk-WMD4XZZS.mjs +25 -0
  125. package/dist/chunk-WMD4XZZS.mjs.map +1 -0
  126. package/dist/chunk-WX2ZNCRT.mjs +74 -0
  127. package/dist/chunk-WX2ZNCRT.mjs.map +1 -0
  128. package/dist/chunk-XWBDEXDA.mjs +153 -0
  129. package/dist/chunk-XWBDEXDA.mjs.map +1 -0
  130. package/dist/chunk-Y2Z62E2T.mjs +74 -0
  131. package/dist/chunk-Y2Z62E2T.mjs.map +1 -0
  132. package/dist/chunk-YO4I6RVI.mjs +25 -0
  133. package/dist/chunk-YO4I6RVI.mjs.map +1 -0
  134. package/dist/chunk-Z6Q5IW6I.mjs +3098 -0
  135. package/dist/chunk-Z6Q5IW6I.mjs.map +1 -0
  136. package/dist/chunk-Z726O3G2.mjs +25 -0
  137. package/dist/chunk-Z726O3G2.mjs.map +1 -0
  138. package/dist/chunk-ZE4SMZZR.mjs +3097 -0
  139. package/dist/chunk-ZE4SMZZR.mjs.map +1 -0
  140. package/dist/chunk-ZULZB33C.mjs +73 -0
  141. package/dist/chunk-ZULZB33C.mjs.map +1 -0
  142. package/dist/chunk-ZVRGXMY7.mjs +25 -0
  143. package/dist/chunk-ZVRGXMY7.mjs.map +1 -0
  144. package/dist/chunk-ZZ35WBYQ.mjs +25 -0
  145. package/dist/chunk-ZZ35WBYQ.mjs.map +1 -0
  146. package/dist/graphql/message-conversion/index.d.ts +18 -0
  147. package/dist/graphql/message-conversion/index.js +725 -0
  148. package/dist/graphql/message-conversion/index.js.map +1 -0
  149. package/dist/graphql/message-conversion/index.mjs +245 -0
  150. package/dist/graphql/message-conversion/index.mjs.map +1 -0
  151. package/dist/graphql/types/base/index.d.ts +6 -0
  152. package/dist/graphql/types/base/index.js +63 -0
  153. package/dist/graphql/types/base/index.js.map +1 -0
  154. package/dist/graphql/types/base/index.mjs +8 -0
  155. package/dist/graphql/types/base/index.mjs.map +1 -0
  156. package/dist/graphql/types/converted/index.d.ts +2 -0
  157. package/dist/graphql/types/converted/index.js +200 -0
  158. package/dist/graphql/types/converted/index.js.map +1 -0
  159. package/dist/graphql/types/converted/index.mjs +19 -0
  160. package/dist/graphql/types/converted/index.mjs.map +1 -0
  161. package/dist/groq-adapter-540da9c3.d.ts +331 -0
  162. package/dist/groq-adapter-a6f5e9d2.d.ts +331 -0
  163. package/dist/groq-adapter-c8aec5c5.d.ts +321 -0
  164. package/dist/index-96b330da.d.ts +119 -0
  165. package/dist/index-adbd78f1.d.ts +154 -0
  166. package/dist/index.d.ts +67 -8
  167. package/dist/index.js +118 -28
  168. package/dist/index.js.map +1 -1
  169. package/dist/index.mjs +120 -31
  170. package/dist/index.mjs.map +1 -1
  171. package/dist/langserve-0c6100e3.d.ts +257 -0
  172. package/dist/langserve-978d5790.d.ts +243 -0
  173. package/dist/langserve-9fc76ce5.d.ts +243 -0
  174. package/dist/lib/cloud/index.d.ts +6 -0
  175. package/dist/lib/cloud/index.js +18 -0
  176. package/dist/lib/cloud/index.js.map +1 -0
  177. package/dist/lib/cloud/index.mjs +1 -0
  178. package/dist/lib/cloud/index.mjs.map +1 -0
  179. package/dist/lib/index.d.ts +212 -0
  180. package/dist/lib/index.js +7843 -0
  181. package/dist/lib/index.js.map +1 -0
  182. package/dist/lib/index.mjs +76 -0
  183. package/dist/lib/index.mjs.map +1 -0
  184. package/dist/lib/integrations/index.d.ts +34 -0
  185. package/dist/lib/integrations/index.js +3052 -0
  186. package/dist/lib/integrations/index.js.map +1 -0
  187. package/dist/lib/integrations/index.mjs +37 -0
  188. package/dist/lib/integrations/index.mjs.map +1 -0
  189. package/dist/lib/integrations/nest/index.d.ts +15 -0
  190. package/dist/lib/integrations/nest/index.js +2959 -0
  191. package/dist/lib/integrations/nest/index.js.map +1 -0
  192. package/dist/lib/integrations/nest/index.mjs +14 -0
  193. package/dist/lib/integrations/nest/index.mjs.map +1 -0
  194. package/dist/lib/integrations/node-express/index.d.ts +15 -0
  195. package/dist/lib/integrations/node-express/index.js +2959 -0
  196. package/dist/lib/integrations/node-express/index.js.map +1 -0
  197. package/dist/lib/integrations/node-express/index.mjs +14 -0
  198. package/dist/lib/integrations/node-express/index.mjs.map +1 -0
  199. package/dist/lib/integrations/node-http/index.d.ts +15 -0
  200. package/dist/lib/integrations/node-http/index.js +2945 -0
  201. package/dist/lib/integrations/node-http/index.js.map +1 -0
  202. package/dist/lib/integrations/node-http/index.mjs +13 -0
  203. package/dist/lib/integrations/node-http/index.mjs.map +1 -0
  204. package/dist/service-adapters/index.d.ts +162 -0
  205. package/dist/service-adapters/index.js +1787 -0
  206. package/dist/service-adapters/index.js.map +1 -0
  207. package/dist/service-adapters/index.mjs +34 -0
  208. package/dist/service-adapters/index.mjs.map +1 -0
  209. package/dist/service-adapters/shared/index.d.ts +9 -0
  210. package/dist/service-adapters/shared/index.js +72 -0
  211. package/dist/service-adapters/shared/index.js.map +1 -0
  212. package/dist/service-adapters/shared/index.mjs +8 -0
  213. package/dist/service-adapters/shared/index.mjs.map +1 -0
  214. package/dist/shared-0a7346ce.d.ts +466 -0
  215. package/dist/shared-35c6eb04.d.ts +448 -0
  216. package/dist/shared-9ed1dc31.d.ts +414 -0
  217. package/dist/shared-da5708fe.d.ts +449 -0
  218. package/dist/utils/index.d.ts +65 -0
  219. package/dist/utils/index.js +175 -0
  220. package/dist/utils/index.js.map +1 -0
  221. package/dist/utils/index.mjs +12 -0
  222. package/dist/utils/index.mjs.map +1 -0
  223. package/package.json +14 -20
  224. package/src/lib/index.ts +7 -6
  225. package/src/lib/runtime/copilot-runtime.ts +62 -26
  226. package/src/lib/runtime/telemetry-agent-runner.ts +139 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../package.json","../../../../src/lib/integrations/nest/index.ts","../../../../src/lib/integrations/node-http/index.ts","../../../../src/lib/integrations/shared.ts","../../../../src/graphql/resolvers/copilot.resolver.ts","../../../../src/graphql/inputs/generate-copilot-response.input.ts","../../../../src/graphql/inputs/message.input.ts","../../../../src/graphql/types/enums.ts","../../../../src/graphql/types/base/index.ts","../../../../src/graphql/inputs/frontend.input.ts","../../../../src/graphql/inputs/action.input.ts","../../../../src/graphql/inputs/cloud.input.ts","../../../../src/graphql/inputs/cloud-guardrails.input.ts","../../../../src/graphql/inputs/forwarded-parameters.input.ts","../../../../src/graphql/inputs/agent-session.input.ts","../../../../src/graphql/inputs/agent-state.input.ts","../../../../src/graphql/inputs/extensions.input.ts","../../../../src/graphql/inputs/meta-event.input.ts","../../../../src/graphql/types/meta-events.type.ts","../../../../src/graphql/types/copilot-response.type.ts","../../../../src/graphql/types/message-status.type.ts","../../../../src/graphql/types/response-status.type.ts","../../../../src/graphql/types/extensions-response.type.ts","../../../../src/graphql/inputs/copilot-context.input.ts","../../../../src/service-adapters/events.ts","../../../../src/graphql/types/converted/index.ts","../../../../src/lib/runtime/remote-actions.ts","../../../../src/lib/telemetry-client.ts","../../../../src/lib/runtime/copilot-runtime.ts","../../../../src/agents/langgraph/events.ts","../../../../src/utils/failed-response-status-reasons.ts","../../../../src/graphql/types/agents-response.type.ts","../../../../src/lib/logger.ts","../../../../src/graphql/resolvers/state.resolver.ts","../../../../src/graphql/types/load-agent-state-response.type.ts","../../../../src/graphql/inputs/load-agent-state.input.ts"],"sourcesContent":["{\n \"name\": \"@copilotkit/runtime\",\n \"private\": false,\n \"homepage\": \"https://github.com/CopilotKit/CopilotKit\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/CopilotKit/CopilotKit.git\"\n },\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"version\": \"1.10.6\",\n \"sideEffects\": false,\n \"main\": \"./dist/index.js\",\n \"module\": \"./dist/index.mjs\",\n \"exports\": {\n \".\": \"./dist/index.js\"\n },\n \"types\": \"./dist/index.d.ts\",\n \"license\": \"MIT\",\n \"scripts\": {\n \"build\": \"tsup --onSuccess \\\"pnpm run generate-graphql-schema\\\"\",\n \"dev\": \"tsup --watch --onSuccess \\\"pnpm run generate-graphql-schema\\\"\",\n \"test\": \"jest --passWithNoTests\",\n \"check-types\": \"tsc --noEmit\",\n \"clean\": \"rm -rf .turbo && rm -rf node_modules && rm -rf dist && rm -rf .next && rm -rf __snapshots__\",\n \"generate-graphql-schema\": \"rm -rf __snapshots__ && ts-node ./scripts/generate-gql-schema.ts\",\n \"link:global\": \"pnpm link --global\",\n \"unlink:global\": \"pnpm unlink --global\"\n },\n \"devDependencies\": {\n \"@jest/globals\": \"^29.7.0\",\n \"@swc/core\": \"1.5.28\",\n \"@types/express\": \"^4.17.21\",\n \"@types/jest\": \"^29.5.12\",\n \"@types/node\": \"^18.11.17\",\n \"@whatwg-node/server\": \"^0.9.34\",\n \"eslint\": \"^8.56.0\",\n \"eslint-config-custom\": \"workspace:*\",\n \"jest\": \"^29.6.4\",\n \"nodemon\": \"^3.1.3\",\n \"ts-jest\": \"^29.1.1\",\n \"ts-node\": \"^10.9.2\",\n \"tsconfig\": \"workspace:*\",\n \"tsup\": \"^6.7.0\",\n \"typescript\": \"^5.2.3\",\n \"zod-to-json-schema\": \"^3.23.5\"\n },\n \"dependencies\": {\n \"@anthropic-ai/sdk\": \"^0.57.0\",\n \"@copilotkit/shared\": \"workspace:*\",\n \"@graphql-yoga/plugin-defer-stream\": \"^3.3.1\",\n \"@langchain/aws\": \"^0.1.9\",\n \"@langchain/community\": \"^0.3.29\",\n \"@langchain/core\": \"^0.3.38\",\n \"@langchain/google-gauth\": \"^0.1.0\",\n \"@langchain/langgraph-sdk\": \"^0.0.70\",\n \"@langchain/openai\": \"^0.4.2\",\n \"@scarf/scarf\": \"^1.3.0\",\n \"class-transformer\": \"^0.5.1\",\n \"class-validator\": \"^0.14.1\",\n \"express\": \"^4.19.2\",\n \"graphql\": \"^16.8.1\",\n \"graphql-scalars\": \"^1.23.0\",\n \"graphql-yoga\": \"^5.3.1\",\n \"groq-sdk\": \"^0.5.0\",\n \"langchain\": \"^0.3.3\",\n \"openai\": \"^4.85.1\",\n \"partial-json\": \"^0.1.7\",\n \"pino\": \"^9.2.0\",\n \"pino-pretty\": \"^11.2.1\",\n \"reflect-metadata\": \"^0.2.2\",\n \"rxjs\": \"7.8.1\",\n \"type-graphql\": \"2.0.0-rc.1\",\n \"zod\": \"^3.23.3\"\n },\n \"peerDependencies\": {\n \"@ag-ui/client\": \">=0.0.39\",\n \"@ag-ui/core\": \">=0.0.39\",\n \"@ag-ui/encoder\": \">=0.0.39\",\n \"@ag-ui/langgraph\": \">=0.0.18\",\n \"@ag-ui/proto\": \">=0.0.39\"\n },\n \"keywords\": [\n \"copilotkit\",\n \"copilot\",\n \"react\",\n \"nextjs\",\n \"nodejs\",\n \"ai\",\n \"assistant\",\n \"javascript\",\n \"automation\",\n \"textarea\"\n ]\n}\n","import { CreateCopilotRuntimeServerOptions } from \"../shared\";\nimport { copilotRuntimeNodeHttpEndpoint } from \"../node-http\";\nimport telemetry, { getRuntimeInstanceTelemetryInfo } from \"../../telemetry-client\";\n\nexport function copilotRuntimeNestEndpoint(options: CreateCopilotRuntimeServerOptions) {\n telemetry.setGlobalProperties({\n runtime: {\n framework: \"nest\",\n },\n });\n\n telemetry.capture(\"oss.runtime.instance_created\", getRuntimeInstanceTelemetryInfo(options));\n return copilotRuntimeNodeHttpEndpoint(options);\n}\n","import { createYoga } from \"graphql-yoga\";\nimport { CreateCopilotRuntimeServerOptions, getCommonConfig } from \"../shared\";\nimport telemetry, { getRuntimeInstanceTelemetryInfo } from \"../../telemetry-client\";\n\nexport function copilotRuntimeNodeHttpEndpoint(options: CreateCopilotRuntimeServerOptions) {\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 telemetry.capture(\"oss.runtime.instance_created\", getRuntimeInstanceTelemetryInfo(options));\n\n const logger = commonConfig.logging;\n logger.debug(\"Creating Node HTTP endpoint\");\n\n const yoga = createYoga({\n ...commonConfig,\n graphqlEndpoint: options.endpoint,\n });\n\n return yoga;\n}\n","import { YogaInitialContext } from \"graphql-yoga\";\nimport { buildSchemaSync } from \"type-graphql\";\nimport { CopilotResolver } from \"../../graphql/resolvers/copilot.resolver\";\nimport { useDeferStream } from \"@graphql-yoga/plugin-defer-stream\";\nimport { CopilotRuntime } from \"../runtime/copilot-runtime\";\nimport { CopilotServiceAdapter } from \"../../service-adapters\";\nimport { CopilotCloudOptions } from \"../cloud\";\nimport { LogLevel, createLogger } from \"../../lib/logger\";\nimport { createYoga } from \"graphql-yoga\";\nimport telemetry from \"../telemetry-client\";\nimport { StateResolver } from \"../../graphql/resolvers/state.resolver\";\nimport * as packageJson from \"../../../package.json\";\nimport { CopilotKitError, CopilotKitErrorCode } from \"@copilotkit/shared\";\n\nconst logger = createLogger();\n\nexport const addCustomHeaderPlugin = {\n onResponse({ response }) {\n // Set your custom header; adjust the header name and value as needed\n response.headers.set(\"X-CopilotKit-Runtime-Version\", packageJson.version);\n },\n};\n\ntype AnyPrimitive = string | boolean | number | null;\nexport type CopilotRequestContextProperties = Record<\n string,\n AnyPrimitive | Record<string, AnyPrimitive>\n>;\n\nexport type GraphQLContext = YogaInitialContext & {\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\nexport async function createContext(\n initialContext: YogaInitialContext,\n copilotKitContext: CreateCopilotRuntimeServerOptions,\n contextLogger: typeof logger,\n properties: CopilotRequestContextProperties = {},\n): Promise<Partial<GraphQLContext>> {\n logger.debug({ copilotKitContext }, \"Creating GraphQL context\");\n const ctx: GraphQLContext = {\n ...initialContext,\n _copilotkit: {\n ...copilotKitContext,\n },\n properties: { ...properties },\n logger: contextLogger,\n };\n return ctx;\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 schema: ReturnType<typeof buildSchema>;\n plugins: Parameters<typeof createYoga>[0][\"plugins\"];\n context: (ctx: YogaInitialContext) => Promise<Partial<GraphQLContext>>;\n maskedErrors: {\n maskError: (error: any, message: string, isDev?: boolean) => any;\n };\n};\n\nexport function getCommonConfig(options: CreateCopilotRuntimeServerOptions): CommonConfig {\n const logLevel = (process.env.LOG_LEVEL as LogLevel) || (options.logLevel as LogLevel) || \"error\";\n const logger = createLogger({ level: logLevel, component: \"getCommonConfig\" });\n\n const contextLogger = createLogger({ level: logLevel });\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,\n },\n });\n\n // User error codes that should not be logged as server errors\n const userErrorCodes = [\n CopilotKitErrorCode.AGENT_NOT_FOUND,\n CopilotKitErrorCode.API_NOT_FOUND,\n CopilotKitErrorCode.REMOTE_ENDPOINT_NOT_FOUND,\n CopilotKitErrorCode.CONFIGURATION_ERROR,\n CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR,\n ];\n\n return {\n logging: createLogger({ component: \"Yoga GraphQL\", level: logLevel }),\n schema: buildSchema(),\n plugins: [useDeferStream(), addCustomHeaderPlugin],\n context: (ctx: YogaInitialContext): Promise<Partial<GraphQLContext>> =>\n createContext(ctx, options, contextLogger, options.properties),\n // Suppress logging for user configuration errors\n maskedErrors: {\n maskError: (error: any, message: string, isDev?: boolean) => {\n // Check if this is a user configuration error (could be wrapped in GraphQLError)\n const originalError = error.originalError || error;\n const extensions = error.extensions;\n const errorCode = extensions?.code;\n\n // Suppress logging for user errors based on error code\n if (errorCode && userErrorCodes.includes(errorCode)) {\n // Log user configuration errors at debug level instead\n console.debug(\"User configuration error:\", error.message);\n return error;\n }\n\n // Check if the original error is a user error\n if (\n originalError instanceof CopilotKitError &&\n userErrorCodes.includes(originalError.code)\n ) {\n // Log user configuration errors at debug level instead\n console.debug(\"User configuration error:\", error.message);\n return error;\n }\n\n // For application errors, log normally and mask if needed\n console.error(\"Application error:\", error);\n return error;\n },\n },\n };\n}\n","import { Arg, Ctx, Mutation, Query, Resolver } from \"type-graphql\";\nimport {\n ReplaySubject,\n Subject,\n Subscription,\n filter,\n finalize,\n firstValueFrom,\n shareReplay,\n skipWhile,\n take,\n takeWhile,\n tap,\n} from \"rxjs\";\nimport { GenerateCopilotResponseInput } from \"../inputs/generate-copilot-response.input\";\nimport { CopilotResponse } from \"../types/copilot-response.type\";\nimport {\n CopilotKitLangGraphInterruptEvent,\n LangGraphInterruptEvent,\n} from \"../types/meta-events.type\";\nimport { ActionInputAvailability, MessageRole } from \"../types/enums\";\nimport { Repeater } from \"graphql-yoga\";\nimport type { CopilotRequestContextProperties, GraphQLContext } from \"../../lib/integrations\";\nimport {\n RuntimeEvent,\n RuntimeEventTypes,\n RuntimeMetaEventName,\n} from \"../../service-adapters/events\";\nimport {\n FailedMessageStatus,\n MessageStatusCode,\n MessageStatusUnion,\n SuccessMessageStatus,\n} from \"../types/message-status.type\";\nimport { ResponseStatusUnion, SuccessResponseStatus } from \"../types/response-status.type\";\nimport { GraphQLJSONObject } from \"graphql-scalars\";\nimport { plainToInstance } from \"class-transformer\";\nimport { GuardrailsResult } from \"../types/guardrails-result.type\";\nimport { GraphQLError } from \"graphql\";\nimport {\n GuardrailsValidationFailureResponse,\n MessageStreamInterruptedResponse,\n UnknownErrorResponse,\n} from \"../../utils\";\nimport {\n ActionExecutionMessage,\n AgentStateMessage,\n Message,\n MessageType,\n ResultMessage,\n TextMessage,\n} from \"../types/converted\";\nimport telemetry from \"../../lib/telemetry-client\";\nimport { randomId } from \"@copilotkit/shared\";\nimport { AgentsResponse } from \"../types/agents-response.type\";\nimport { LangGraphEventTypes } from \"../../agents/langgraph/events\";\nimport {\n CopilotKitError,\n CopilotKitLowLevelError,\n isStructuredCopilotKitError,\n} from \"@copilotkit/shared\";\n\nconst invokeGuardrails = async ({\n baseUrl,\n copilotCloudPublicApiKey,\n data,\n onResult,\n onError,\n}: {\n baseUrl: string;\n copilotCloudPublicApiKey: string;\n data: GenerateCopilotResponseInput;\n onResult: (result: GuardrailsResult) => void;\n onError: (err: Error) => void;\n}) => {\n if (\n data.messages.length &&\n data.messages[data.messages.length - 1].textMessage?.role === MessageRole.user\n ) {\n const messages = data.messages\n .filter(\n (m) =>\n m.textMessage !== undefined &&\n (m.textMessage.role === MessageRole.user || m.textMessage.role === MessageRole.assistant),\n )\n .map((m) => ({\n role: m.textMessage!.role,\n content: m.textMessage.content,\n }));\n\n const lastMessage = messages[messages.length - 1];\n const restOfMessages = messages.slice(0, -1);\n\n const body = {\n input: lastMessage.content,\n validTopics: data.cloud.guardrails.inputValidationRules.allowList,\n invalidTopics: data.cloud.guardrails.inputValidationRules.denyList,\n messages: restOfMessages,\n };\n\n const guardrailsResult = await fetch(`${baseUrl}/guardrails/validate`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-CopilotCloud-Public-API-Key\": copilotCloudPublicApiKey,\n },\n body: JSON.stringify(body),\n });\n\n if (guardrailsResult.ok) {\n const resultJson: GuardrailsResult = await guardrailsResult.json();\n onResult(resultJson);\n } else {\n onError(await guardrailsResult.json());\n }\n }\n};\n\n@Resolver(() => CopilotResponse)\nexport class CopilotResolver {\n @Query(() => String)\n async hello() {\n return \"Hello World\";\n }\n\n @Query(() => AgentsResponse)\n async availableAgents(@Ctx() ctx: GraphQLContext) {\n let logger = ctx.logger.child({ component: \"CopilotResolver.availableAgents\" });\n\n logger.debug(\"Processing\");\n const agentsWithEndpoints = await ctx._copilotkit.runtime.discoverAgentsFromEndpoints(ctx);\n\n logger.debug(\"Event source created, creating response\");\n\n return {\n agents: agentsWithEndpoints.map(\n ({ endpoint, ...agentWithoutEndpoint }) => agentWithoutEndpoint,\n ),\n };\n }\n\n @Mutation(() => CopilotResponse)\n async generateCopilotResponse(\n @Ctx() ctx: GraphQLContext,\n @Arg(\"data\") data: GenerateCopilotResponseInput,\n @Arg(\"properties\", () => GraphQLJSONObject, { nullable: true })\n properties?: CopilotRequestContextProperties,\n ) {\n telemetry.capture(\"oss.runtime.copilot_request_created\", {\n \"cloud.guardrails.enabled\": data.cloud?.guardrails !== undefined,\n requestType: data.metadata.requestType,\n \"cloud.api_key_provided\": !!ctx.request.headers.get(\"x-copilotcloud-public-api-key\"),\n ...(ctx.request.headers.get(\"x-copilotcloud-public-api-key\")\n ? {\n \"cloud.public_api_key\": ctx.request.headers.get(\"x-copilotcloud-public-api-key\"),\n }\n : {}),\n ...(ctx._copilotkit.baseUrl\n ? {\n \"cloud.base_url\": ctx._copilotkit.baseUrl,\n }\n : {\n \"cloud.base_url\": \"https://api.cloud.copilotkit.ai\",\n }),\n });\n\n let logger = ctx.logger.child({ component: \"CopilotResolver.generateCopilotResponse\" });\n logger.debug({ data }, \"Generating Copilot response\");\n\n if (properties) {\n logger.debug(\"Properties provided, merging with context properties\");\n ctx.properties = { ...ctx.properties, ...properties };\n }\n\n const copilotRuntime = ctx._copilotkit.runtime;\n const serviceAdapter = ctx._copilotkit.serviceAdapter;\n\n let copilotCloudPublicApiKey: string | null = null;\n let copilotCloudBaseUrl: string;\n\n // Extract publicApiKey from headers for both cloud and non-cloud requests\n // This enables onTrace functionality regardless of cloud configuration\n const publicApiKeyFromHeaders = ctx.request.headers.get(\"x-copilotcloud-public-api-key\");\n if (publicApiKeyFromHeaders) {\n copilotCloudPublicApiKey = publicApiKeyFromHeaders;\n }\n\n if (data.cloud) {\n logger = logger.child({ cloud: true });\n logger.debug(\"Cloud configuration provided, checking for public API key in headers\");\n\n if (!copilotCloudPublicApiKey) {\n logger.error(\"Public API key not found in headers\");\n\n await copilotRuntime.errorGraphQLError(\n {\n message: \"X-CopilotCloud-Public-API-Key header is required\",\n code: \"MISSING_PUBLIC_API_KEY\",\n type: \"GraphQLError\",\n },\n {\n operation: \"generateCopilotResponse\",\n cloudConfigPresent: Boolean(data.cloud),\n guardrailsEnabled: Boolean(data.cloud?.guardrails),\n },\n );\n\n throw new GraphQLError(\"X-CopilotCloud-Public-API-Key header is required\");\n }\n\n if (process.env.COPILOT_CLOUD_BASE_URL) {\n copilotCloudBaseUrl = process.env.COPILOT_CLOUD_BASE_URL;\n } else if (ctx._copilotkit.cloud?.baseUrl) {\n copilotCloudBaseUrl = ctx._copilotkit.cloud?.baseUrl;\n } else {\n copilotCloudBaseUrl = \"https://api.cloud.copilotkit.ai\";\n }\n\n logger = logger.child({ copilotCloudBaseUrl });\n }\n\n logger.debug(\"Setting up subjects\");\n const responseStatus$ = new ReplaySubject<typeof ResponseStatusUnion>();\n const interruptStreaming$ = new ReplaySubject<{ reason: string; messageId?: string }>();\n const guardrailsResult$ = new ReplaySubject<GuardrailsResult>();\n\n let outputMessages: Message[] = [];\n let resolveOutputMessagesPromise: (messages: Message[]) => void;\n let rejectOutputMessagesPromise: (err: Error) => void;\n\n const outputMessagesPromise = new Promise<Message[]>((resolve, reject) => {\n resolveOutputMessagesPromise = resolve;\n rejectOutputMessagesPromise = reject;\n });\n\n if (copilotCloudPublicApiKey) {\n ctx.properties[\"copilotCloudPublicApiKey\"] = copilotCloudPublicApiKey;\n }\n\n logger.debug(\"Processing\");\n let runtimeResponse;\n try {\n runtimeResponse = await copilotRuntime.processRuntimeRequest({\n serviceAdapter,\n messages: data.messages,\n actions: data.frontend.actions.filter(\n (action) => action.available !== ActionInputAvailability.disabled,\n ),\n threadId: data.threadId,\n runId: data.runId,\n publicApiKey: copilotCloudPublicApiKey,\n outputMessagesPromise,\n graphqlContext: ctx,\n forwardedParameters: data.forwardedParameters,\n agentSession: data.agentSession,\n agentStates: data.agentStates,\n url: data.frontend.url,\n extensions: data.extensions,\n metaEvents: data.metaEvents,\n context: data.context,\n });\n } catch (error) {\n // Catch structured CopilotKit errors at the main mutation level and re-throw as GraphQL errors\n if (isStructuredCopilotKitError(error) || (error as any)?.extensions?.visibility) {\n throw new GraphQLError(error.message || \"Agent error occurred\", {\n extensions: {\n ...(error as any).extensions,\n code: (error as any).code || (error as any).extensions?.code || \"AGENT_ERROR\",\n originalError: error,\n },\n });\n }\n throw error; // Re-throw non-CopilotKit errors as-is\n }\n\n const {\n eventSource,\n threadId = randomId(),\n runId,\n serverSideActions,\n actionInputsWithoutAgents,\n extensions,\n } = runtimeResponse;\n\n logger.debug(\"Event source created, creating response\");\n // run and process the event stream\n const eventStream = eventSource\n .processRuntimeEvents({\n serverSideActions,\n guardrailsResult$: data.cloud?.guardrails ? guardrailsResult$ : null,\n actionInputsWithoutAgents: actionInputsWithoutAgents.filter(\n // TODO-AGENTS: do not exclude ALL server side actions\n (action) =>\n !serverSideActions.find((serverSideAction) => serverSideAction.name == action.name),\n ),\n threadId,\n })\n .pipe(\n // shareReplay() ensures that later subscribers will see the whole stream instead of\n // just the events that were emitted after the subscriber was added.\n shareReplay(),\n finalize(() => {\n logger.debug(\"Event stream finalized\");\n }),\n );\n\n const response = {\n threadId,\n runId,\n status: firstValueFrom(responseStatus$),\n extensions,\n metaEvents: new Repeater(async (push, stop) => {\n let eventStreamSubscription: Subscription;\n\n eventStreamSubscription = eventStream.subscribe({\n next: async (event) => {\n if (event.type != RuntimeEventTypes.MetaEvent) {\n return;\n }\n switch (event.name) {\n // @ts-ignore\n case LangGraphEventTypes.OnInterrupt:\n push(\n plainToInstance(LangGraphInterruptEvent, {\n // @ts-ignore\n type: event.type,\n // @ts-ignore\n name: RuntimeMetaEventName.LangGraphInterruptEvent,\n // @ts-ignore\n value: event.value,\n }),\n );\n break;\n case RuntimeMetaEventName.LangGraphInterruptEvent:\n push(\n plainToInstance(LangGraphInterruptEvent, {\n type: event.type,\n name: event.name,\n value: event.value,\n }),\n );\n break;\n case RuntimeMetaEventName.CopilotKitLangGraphInterruptEvent:\n push(\n plainToInstance(CopilotKitLangGraphInterruptEvent, {\n type: event.type,\n name: event.name,\n data: {\n value: event.data.value,\n messages: event.data.messages.map((message) => {\n if (\n message.type === \"TextMessage\" ||\n (\"content\" in message && \"role\" in message)\n ) {\n return plainToInstance(TextMessage, {\n id: message.id,\n createdAt: new Date(),\n content: [(message as TextMessage).content],\n role: (message as TextMessage).role,\n status: new SuccessMessageStatus(),\n });\n }\n if (\"arguments\" in message) {\n return plainToInstance(ActionExecutionMessage, {\n name: message.name,\n id: message.id,\n arguments: [JSON.stringify(message.arguments)],\n createdAt: new Date(),\n status: new SuccessMessageStatus(),\n });\n }\n throw new Error(\"Unknown message in metaEvents copilot resolver\");\n }),\n },\n }),\n );\n break;\n }\n },\n error: (err) => {\n // For structured CopilotKit errors, set proper error response status\n if (err?.name?.includes(\"CopilotKit\") || err?.extensions?.visibility) {\n responseStatus$.next(\n new UnknownErrorResponse({\n description: err.message || \"Agent error occurred\",\n }),\n );\n } else {\n responseStatus$.next(\n new UnknownErrorResponse({\n description: `An unknown error has occurred in the event stream`,\n }),\n );\n }\n\n eventStreamSubscription?.unsubscribe();\n stop();\n },\n complete: async () => {\n logger.debug(\"Meta events stream completed\");\n responseStatus$.next(new SuccessResponseStatus());\n eventStreamSubscription?.unsubscribe();\n stop();\n },\n });\n }),\n messages: new Repeater(async (pushMessage, stopStreamingMessages) => {\n logger.debug(\"Messages repeater created\");\n\n if (data.cloud?.guardrails) {\n logger = logger.child({ guardrails: true });\n logger.debug(\"Guardrails is enabled, validating input\");\n\n invokeGuardrails({\n baseUrl: copilotCloudBaseUrl,\n copilotCloudPublicApiKey,\n data,\n onResult: (result) => {\n logger.debug({ status: result.status }, \"Guardrails validation done\");\n guardrailsResult$.next(result);\n\n // Guardrails validation failed\n if (result.status === \"denied\") {\n // send the reason to the client and interrupt streaming\n responseStatus$.next(\n new GuardrailsValidationFailureResponse({ guardrailsReason: result.reason }),\n );\n interruptStreaming$.next({\n reason: `Interrupted due to Guardrails validation failure. Reason: ${result.reason}`,\n });\n\n // resolve messages promise to the middleware\n outputMessages = [\n plainToInstance(TextMessage, {\n id: randomId(),\n createdAt: new Date(),\n content: result.reason,\n role: MessageRole.assistant,\n }),\n ];\n resolveOutputMessagesPromise(outputMessages);\n }\n },\n onError: (err) => {\n logger.error({ err }, \"Error in guardrails validation\");\n responseStatus$.next(\n new UnknownErrorResponse({\n description: `An unknown error has occurred in the guardrails validation`,\n }),\n );\n interruptStreaming$.next({\n reason: `Interrupted due to unknown error in guardrails validation`,\n });\n\n // reject the middleware promise\n rejectOutputMessagesPromise(err);\n },\n });\n }\n\n let eventStreamSubscription: Subscription;\n\n logger.debug(\"Event stream created, subscribing to event stream\");\n\n eventStreamSubscription = eventStream.subscribe({\n next: async (event) => {\n switch (event.type) {\n case RuntimeEventTypes.MetaEvent:\n break;\n ////////////////////////////////\n // TextMessageStart\n ////////////////////////////////\n case RuntimeEventTypes.TextMessageStart:\n // create a sub stream that contains the message content\n const textMessageContentStream = eventStream.pipe(\n // skip until this message start event\n skipWhile((e: RuntimeEvent) => e !== event),\n // take until the message end event\n takeWhile(\n (e: RuntimeEvent) =>\n !(\n e.type === RuntimeEventTypes.TextMessageEnd &&\n (e as any).messageId == event.messageId\n ),\n ),\n // filter out any other message events or message ids\n filter(\n (e: RuntimeEvent) =>\n e.type == RuntimeEventTypes.TextMessageContent &&\n (e as any).messageId == event.messageId,\n ),\n );\n\n // signal when we are done streaming\n const streamingTextStatus = new Subject<typeof MessageStatusUnion>();\n\n const messageId = event.messageId;\n // push the new message\n pushMessage({\n id: messageId,\n parentMessageId: event.parentMessageId,\n status: firstValueFrom(streamingTextStatus),\n createdAt: new Date(),\n role: MessageRole.assistant,\n content: new Repeater(async (pushTextChunk, stopStreamingText) => {\n logger.debug(\"Text message content repeater created\");\n\n const textChunks: string[] = [];\n let textSubscription: Subscription;\n\n interruptStreaming$\n .pipe(\n shareReplay(),\n take(1),\n tap(({ reason, messageId }) => {\n logger.debug({ reason, messageId }, \"Text streaming interrupted\");\n\n streamingTextStatus.next(\n plainToInstance(FailedMessageStatus, { reason }),\n );\n\n responseStatus$.next(new MessageStreamInterruptedResponse({ messageId }));\n stopStreamingText();\n textSubscription?.unsubscribe();\n }),\n )\n .subscribe();\n\n logger.debug(\"Subscribing to text message content stream\");\n\n textSubscription = textMessageContentStream.subscribe({\n next: async (e: RuntimeEvent) => {\n if (e.type == RuntimeEventTypes.TextMessageContent) {\n await pushTextChunk(e.content);\n textChunks.push(e.content);\n }\n },\n error: (err) => {\n logger.error({ err }, \"Error in text message content stream\");\n interruptStreaming$.next({\n reason: \"Error streaming message content\",\n messageId,\n });\n stopStreamingText();\n textSubscription?.unsubscribe();\n },\n complete: () => {\n logger.debug(\"Text message content stream completed\");\n streamingTextStatus.next(new SuccessMessageStatus());\n stopStreamingText();\n textSubscription?.unsubscribe();\n\n outputMessages.push(\n plainToInstance(TextMessage, {\n id: messageId,\n createdAt: new Date(),\n content: textChunks.join(\"\"),\n role: MessageRole.assistant,\n }),\n );\n },\n });\n }),\n });\n break;\n ////////////////////////////////\n // ActionExecutionStart\n ////////////////////////////////\n case RuntimeEventTypes.ActionExecutionStart:\n logger.debug(\"Action execution start event received\");\n const actionExecutionArgumentStream = eventStream.pipe(\n skipWhile((e: RuntimeEvent) => e !== event),\n // take until the action execution end event\n takeWhile(\n (e: RuntimeEvent) =>\n !(\n e.type === RuntimeEventTypes.ActionExecutionEnd &&\n (e as any).actionExecutionId == event.actionExecutionId\n ),\n ),\n // filter out any other action execution events or action execution ids\n filter(\n (e: RuntimeEvent) =>\n e.type == RuntimeEventTypes.ActionExecutionArgs &&\n (e as any).actionExecutionId == event.actionExecutionId,\n ),\n );\n const streamingArgumentsStatus = new Subject<typeof MessageStatusUnion>();\n pushMessage({\n id: event.actionExecutionId,\n parentMessageId: event.parentMessageId,\n status: firstValueFrom(streamingArgumentsStatus),\n createdAt: new Date(),\n name: event.actionName,\n arguments: new Repeater(async (pushArgumentsChunk, stopStreamingArguments) => {\n logger.debug(\"Action execution argument stream created\");\n\n const argumentChunks: string[] = [];\n let actionExecutionArgumentSubscription: Subscription;\n\n actionExecutionArgumentSubscription = actionExecutionArgumentStream.subscribe({\n next: async (e: RuntimeEvent) => {\n if (e.type == RuntimeEventTypes.ActionExecutionArgs) {\n await pushArgumentsChunk(e.args);\n argumentChunks.push(e.args);\n }\n },\n error: (err) => {\n logger.error({ err }, \"Error in action execution argument stream\");\n streamingArgumentsStatus.next(\n plainToInstance(FailedMessageStatus, {\n reason:\n \"An unknown error has occurred in the action execution argument stream\",\n }),\n );\n stopStreamingArguments();\n actionExecutionArgumentSubscription?.unsubscribe();\n },\n complete: () => {\n logger.debug(\"Action execution argument stream completed\");\n streamingArgumentsStatus.next(new SuccessMessageStatus());\n stopStreamingArguments();\n actionExecutionArgumentSubscription?.unsubscribe();\n\n outputMessages.push(\n plainToInstance(ActionExecutionMessage, {\n id: event.actionExecutionId,\n createdAt: new Date(),\n name: event.actionName,\n arguments: argumentChunks.join(\"\"),\n }),\n );\n },\n });\n }),\n });\n break;\n ////////////////////////////////\n // ActionExecutionResult\n ////////////////////////////////\n case RuntimeEventTypes.ActionExecutionResult:\n logger.debug({ result: event.result }, \"Action execution result event received\");\n pushMessage({\n id: \"result-\" + event.actionExecutionId,\n status: new SuccessMessageStatus(),\n createdAt: new Date(),\n actionExecutionId: event.actionExecutionId,\n actionName: event.actionName,\n result: event.result,\n });\n\n outputMessages.push(\n plainToInstance(ResultMessage, {\n id: \"result-\" + event.actionExecutionId,\n createdAt: new Date(),\n actionExecutionId: event.actionExecutionId,\n actionName: event.actionName,\n result: event.result,\n }),\n );\n break;\n ////////////////////////////////\n // AgentStateMessage\n ////////////////////////////////\n case RuntimeEventTypes.AgentStateMessage:\n logger.debug({ event }, \"Agent message event received\");\n pushMessage({\n id: randomId(),\n status: new SuccessMessageStatus(),\n threadId: event.threadId,\n agentName: event.agentName,\n nodeName: event.nodeName,\n runId: event.runId,\n active: event.active,\n state: event.state,\n running: event.running,\n role: MessageRole.assistant,\n createdAt: new Date(),\n });\n outputMessages.push(\n plainToInstance(AgentStateMessage, {\n id: randomId(),\n threadId: event.threadId,\n agentName: event.agentName,\n nodeName: event.nodeName,\n runId: event.runId,\n active: event.active,\n state: event.state,\n running: event.running,\n role: MessageRole.assistant,\n createdAt: new Date(),\n }),\n );\n break;\n }\n },\n error: (err) => {\n // For structured CopilotKit errors, set proper error response status\n if (\n err instanceof CopilotKitError ||\n err instanceof CopilotKitLowLevelError ||\n (err instanceof Error && err.name && err.name.includes(\"CopilotKit\")) ||\n err?.extensions?.visibility\n ) {\n responseStatus$.next(\n new UnknownErrorResponse({\n description: err.message || \"Agent error occurred\",\n // Include original error information for frontend to extract\n originalError: {\n code: err.code || err.extensions?.code,\n statusCode: err.statusCode || err.extensions?.statusCode,\n severity: err.severity || err.extensions?.severity,\n visibility: err.visibility || err.extensions?.visibility,\n originalErrorType: err.originalErrorType || err.extensions?.originalErrorType,\n extensions: err.extensions,\n },\n }),\n );\n eventStreamSubscription?.unsubscribe();\n rejectOutputMessagesPromise(err);\n stopStreamingMessages();\n return;\n }\n\n responseStatus$.next(\n new UnknownErrorResponse({\n description: `An unknown error has occurred in the event stream`,\n }),\n );\n eventStreamSubscription?.unsubscribe();\n stopStreamingMessages();\n\n rejectOutputMessagesPromise(err);\n },\n complete: async () => {\n logger.debug(\"Event stream completed\");\n if (data.cloud?.guardrails) {\n logger.debug(\"Guardrails is enabled, waiting for guardrails result\");\n await firstValueFrom(guardrailsResult$);\n }\n responseStatus$.next(new SuccessResponseStatus());\n eventStreamSubscription?.unsubscribe();\n stopStreamingMessages();\n\n resolveOutputMessagesPromise(outputMessages);\n },\n });\n }),\n };\n\n return response;\n }\n}\n","import { Field, InputType } from \"type-graphql\";\nimport { MessageInput } from \"./message.input\";\nimport { FrontendInput } from \"./frontend.input\";\nimport { CloudInput } from \"./cloud.input\";\nimport { CopilotRequestType } from \"../types/enums\";\nimport { ForwardedParametersInput } from \"./forwarded-parameters.input\";\nimport { AgentSessionInput } from \"./agent-session.input\";\nimport { AgentStateInput } from \"./agent-state.input\";\nimport { ExtensionsInput } from \"./extensions.input\";\nimport { MetaEventInput } from \"./meta-event.input\";\nimport { CopilotContextInput } from \"./copilot-context.input\";\n\n@InputType()\nexport class GenerateCopilotResponseMetadataInput {\n @Field(() => CopilotRequestType, { nullable: true })\n requestType: CopilotRequestType;\n}\n\n@InputType()\nexport class GenerateCopilotResponseInput {\n @Field(() => GenerateCopilotResponseMetadataInput, { nullable: false })\n metadata: GenerateCopilotResponseMetadataInput;\n\n @Field(() => String, { nullable: true })\n threadId?: string;\n\n @Field(() => String, { nullable: true })\n runId?: string;\n\n @Field(() => [MessageInput])\n messages: MessageInput[];\n\n @Field(() => FrontendInput)\n frontend: FrontendInput;\n\n @Field(() => CloudInput, { nullable: true })\n cloud?: CloudInput;\n\n @Field(() => ForwardedParametersInput, { nullable: true })\n forwardedParameters?: ForwardedParametersInput;\n\n @Field(() => AgentSessionInput, { nullable: true })\n agentSession?: AgentSessionInput;\n\n @Field(() => AgentStateInput, { nullable: true })\n agentState?: AgentStateInput;\n\n @Field(() => [AgentStateInput], { nullable: true })\n agentStates?: AgentStateInput[];\n\n @Field(() => ExtensionsInput, { nullable: true })\n extensions?: ExtensionsInput;\n\n @Field(() => [MetaEventInput], { nullable: true })\n metaEvents?: MetaEventInput[];\n\n @Field(() => [CopilotContextInput], { nullable: true })\n context?: CopilotContextInput[];\n}\n","import { Field, InputType } from \"type-graphql\";\nimport { MessageRole } from \"../types/enums\";\nimport { BaseMessageInput } from \"../types/base\";\n\n// GraphQL does not support union types in inputs, so we need to use\n// optional fields for the different subtypes.\n@InputType()\nexport class MessageInput extends BaseMessageInput {\n @Field(() => TextMessageInput, { nullable: true })\n textMessage?: TextMessageInput;\n\n @Field(() => ActionExecutionMessageInput, { nullable: true })\n actionExecutionMessage?: ActionExecutionMessageInput;\n\n @Field(() => ResultMessageInput, { nullable: true })\n resultMessage?: ResultMessageInput;\n\n @Field(() => AgentStateMessageInput, { nullable: true })\n agentStateMessage?: AgentStateMessageInput;\n\n @Field(() => ImageMessageInput, { nullable: true })\n imageMessage?: ImageMessageInput;\n}\n\n@InputType()\nexport class TextMessageInput {\n @Field(() => String)\n content: string;\n\n @Field(() => String, { nullable: true })\n parentMessageId?: string;\n\n @Field(() => MessageRole)\n role: MessageRole;\n}\n\n@InputType()\nexport class ActionExecutionMessageInput {\n @Field(() => String)\n name: string;\n\n @Field(() => String)\n arguments: string;\n\n @Field(() => String, { nullable: true })\n parentMessageId?: string;\n\n @Field(() => String, {\n nullable: true,\n deprecationReason: \"This field will be removed in a future version\",\n })\n scope?: String;\n}\n\n@InputType()\nexport class ResultMessageInput {\n @Field(() => String)\n actionExecutionId: string;\n\n @Field(() => String)\n actionName: string;\n\n @Field(() => String, { nullable: true })\n parentMessageId?: string;\n\n @Field(() => String)\n result: string;\n}\n\n@InputType()\nexport class AgentStateMessageInput {\n @Field(() => String)\n threadId: string;\n\n @Field(() => String)\n agentName: string;\n\n @Field(() => MessageRole)\n role: MessageRole;\n\n @Field(() => String)\n state: string;\n\n @Field(() => Boolean)\n running: boolean;\n\n @Field(() => String)\n nodeName: string;\n\n @Field(() => String)\n runId: string;\n\n @Field(() => Boolean)\n active: boolean;\n}\n\n@InputType()\nexport class ImageMessageInput {\n @Field(() => String)\n format: string;\n\n @Field(() => String)\n bytes: string;\n\n @Field(() => String, { nullable: true })\n parentMessageId?: string;\n\n @Field(() => MessageRole)\n role: MessageRole;\n}\n","import { registerEnumType } from \"type-graphql\";\n\nexport enum MessageRole {\n user = \"user\",\n assistant = \"assistant\",\n system = \"system\",\n tool = \"tool\",\n developer = \"developer\",\n}\n\nexport enum CopilotRequestType {\n Chat = \"Chat\",\n Task = \"Task\",\n TextareaCompletion = \"TextareaCompletion\",\n TextareaPopover = \"TextareaPopover\",\n Suggestion = \"Suggestion\",\n}\n\nexport enum ActionInputAvailability {\n disabled = \"disabled\",\n enabled = \"enabled\",\n remote = \"remote\",\n}\n\nregisterEnumType(MessageRole, {\n name: \"MessageRole\",\n description: \"The role of the message\",\n});\n\nregisterEnumType(CopilotRequestType, {\n name: \"CopilotRequestType\",\n description: \"The type of Copilot request\",\n});\n\nregisterEnumType(ActionInputAvailability, {\n name: \"ActionInputAvailability\",\n description: \"The availability of the frontend action\",\n});\n","import { Field, InputType } from \"type-graphql\";\n\n@InputType()\nexport class BaseMessageInput {\n @Field(() => String)\n id: string;\n\n @Field(() => Date)\n createdAt: Date;\n}\n","import { Field, InputType } from \"type-graphql\";\nimport { ActionInput } from \"./action.input\";\n\n@InputType()\nexport class FrontendInput {\n @Field(() => String, { nullable: true })\n toDeprecate_fullContext?: string;\n\n @Field(() => [ActionInput])\n actions: ActionInput[];\n\n @Field(() => String, { nullable: true })\n url?: string;\n}\n","import { Field, InputType } from \"type-graphql\";\nimport { ActionInputAvailability } from \"../types/enums\";\n@InputType()\nexport class ActionInput {\n @Field(() => String)\n name: string;\n\n @Field(() => String)\n description: string;\n\n @Field(() => String)\n jsonSchema: string;\n\n @Field(() => ActionInputAvailability, { nullable: true })\n available?: ActionInputAvailability;\n}\n","import { Field, InputType } from \"type-graphql\";\nimport { GuardrailsInput } from \"./cloud-guardrails.input\";\n\n@InputType()\nexport class CloudInput {\n @Field(() => GuardrailsInput, { nullable: true })\n guardrails?: GuardrailsInput;\n}\n","import { Field, InputType } from \"type-graphql\";\n\n@InputType()\nexport class GuardrailsRuleInput {\n @Field(() => [String], { nullable: true })\n allowList?: string[] = [];\n\n @Field(() => [String], { nullable: true })\n denyList?: string[] = [];\n}\n\n@InputType()\nexport class GuardrailsInput {\n @Field(() => GuardrailsRuleInput, { nullable: false })\n inputValidationRules: GuardrailsRuleInput;\n}\n","import { Field, InputType } from \"type-graphql\";\n\n@InputType()\nexport class ForwardedParametersInput {\n @Field(() => String, { nullable: true })\n model?: string;\n\n @Field(() => Number, { nullable: true })\n maxTokens?: number;\n\n @Field(() => [String], { nullable: true })\n stop?: string[];\n\n @Field(() => String, { nullable: true })\n toolChoice?: String;\n\n @Field(() => String, { nullable: true })\n toolChoiceFunctionName?: string;\n\n @Field(() => Number, { nullable: true })\n temperature?: number;\n}\n","import { Field, InputType } from \"type-graphql\";\n\n@InputType()\nexport class AgentSessionInput {\n @Field(() => String)\n agentName: string;\n\n @Field(() => String, { nullable: true })\n threadId?: string;\n\n @Field(() => String, { nullable: true })\n nodeName?: string;\n}\n","import { Field, InputType } from \"type-graphql\";\n\n@InputType()\nexport class AgentStateInput {\n @Field(() => String)\n agentName: string;\n\n @Field(() => String)\n state: string;\n\n @Field(() => String, { nullable: true })\n config?: string;\n}\n","import { Field, InputType } from \"type-graphql\";\n\n/**\n * The extensions input is used to pass additional information to the copilot runtime, specific to a\n * service adapter or agent framework.\n */\n\n@InputType()\nexport class ExtensionsInput {\n @Field(() => OpenAIApiAssistantAPIInput, { nullable: true })\n openaiAssistantAPI?: OpenAIApiAssistantAPIInput;\n}\n\n@InputType()\nexport class OpenAIApiAssistantAPIInput {\n @Field(() => String, { nullable: true })\n runId?: string;\n\n @Field(() => String, { nullable: true })\n threadId?: string;\n}\n","import { Field, InputType } from \"type-graphql\";\nimport { MetaEventName } from \"../types/meta-events.type\";\nimport { MessageInput } from \"./message.input\";\n\n@InputType()\nexport class MetaEventInput {\n @Field(() => MetaEventName)\n name: MetaEventName;\n\n @Field(() => String)\n value?: string;\n\n @Field(() => String, { nullable: true })\n response?: string;\n\n @Field(() => [MessageInput], { nullable: true })\n messages?: MessageInput[];\n}\n","import { createUnionType, Field, InterfaceType, ObjectType, registerEnumType } from \"type-graphql\";\nimport {\n ActionExecutionMessageOutput,\n AgentStateMessageOutput,\n BaseMessageOutput,\n ResultMessageOutput,\n TextMessageOutput,\n} from \"./copilot-response.type\";\n\nexport enum MetaEventName {\n LangGraphInterruptEvent = \"LangGraphInterruptEvent\",\n CopilotKitLangGraphInterruptEvent = \"CopilotKitLangGraphInterruptEvent\",\n}\n\nregisterEnumType(MetaEventName, {\n name: \"MetaEventName\",\n description: \"Meta event types\",\n});\n\n@InterfaceType({\n resolveType(value) {\n if (value.name === MetaEventName.LangGraphInterruptEvent) {\n return LangGraphInterruptEvent;\n } else if (value.name === MetaEventName.CopilotKitLangGraphInterruptEvent) {\n return CopilotKitLangGraphInterruptEvent;\n }\n return undefined;\n },\n})\n@InterfaceType()\nexport abstract class BaseMetaEvent {\n @Field(() => String)\n type: \"MetaEvent\" = \"MetaEvent\";\n\n @Field(() => MetaEventName)\n name: MetaEventName;\n}\n\n@ObjectType()\nexport class CopilotKitLangGraphInterruptEventData {\n @Field(() => String)\n value: string;\n\n @Field(() => [BaseMessageOutput])\n messages: (typeof BaseMessageOutput)[];\n}\n\n@ObjectType({ implements: BaseMetaEvent })\nexport class LangGraphInterruptEvent {\n @Field(() => MetaEventName)\n name: MetaEventName.LangGraphInterruptEvent = MetaEventName.LangGraphInterruptEvent;\n\n @Field(() => String)\n value: string;\n\n @Field(() => String, { nullable: true })\n response?: string;\n}\n\n@ObjectType({ implements: BaseMetaEvent })\nexport class CopilotKitLangGraphInterruptEvent {\n @Field(() => MetaEventName)\n name: MetaEventName.CopilotKitLangGraphInterruptEvent =\n MetaEventName.CopilotKitLangGraphInterruptEvent;\n\n @Field(() => CopilotKitLangGraphInterruptEventData)\n data: CopilotKitLangGraphInterruptEventData;\n\n @Field(() => String, { nullable: true })\n response?: string;\n}\n","import { Field, InterfaceType, ObjectType } from \"type-graphql\";\nimport { MessageRole } from \"./enums\";\nimport { MessageStatusUnion } from \"./message-status.type\";\nimport { ResponseStatusUnion } from \"./response-status.type\";\nimport { ExtensionsResponse } from \"./extensions-response.type\";\nimport { BaseMetaEvent } from \"./meta-events.type\";\n\n@InterfaceType({\n resolveType(value) {\n if (value.hasOwnProperty(\"content\")) {\n return TextMessageOutput;\n } else if (value.hasOwnProperty(\"name\")) {\n return ActionExecutionMessageOutput;\n } else if (value.hasOwnProperty(\"result\")) {\n return ResultMessageOutput;\n } else if (value.hasOwnProperty(\"state\")) {\n return AgentStateMessageOutput;\n } else if (value.hasOwnProperty(\"format\") && value.hasOwnProperty(\"bytes\")) {\n return ImageMessageOutput;\n }\n return undefined;\n },\n})\nexport abstract class BaseMessageOutput {\n @Field(() => String)\n id: string;\n\n @Field(() => Date)\n createdAt: Date;\n\n @Field(() => MessageStatusUnion)\n status: typeof MessageStatusUnion;\n}\n\n@ObjectType({ implements: BaseMessageOutput })\nexport class TextMessageOutput {\n @Field(() => MessageRole)\n role: MessageRole;\n\n @Field(() => [String])\n content: string[];\n\n @Field(() => String, { nullable: true })\n parentMessageId?: string;\n}\n\n@ObjectType({ implements: BaseMessageOutput })\nexport class ActionExecutionMessageOutput {\n @Field(() => String)\n name: string;\n\n @Field(() => String, {\n nullable: true,\n deprecationReason: \"This field will be removed in a future version\",\n })\n scope?: string;\n\n @Field(() => [String])\n arguments: string[];\n\n @Field(() => String, { nullable: true })\n parentMessageId?: string;\n}\n\n@ObjectType({ implements: BaseMessageOutput })\nexport class ResultMessageOutput {\n @Field(() => String)\n actionExecutionId: string;\n\n @Field(() => String)\n actionName: string;\n\n @Field(() => String)\n result: string;\n}\n\n@ObjectType({ implements: BaseMessageOutput })\nexport class AgentStateMessageOutput {\n @Field(() => String)\n threadId: string;\n\n @Field(() => String)\n agentName: string;\n\n @Field(() => String)\n nodeName: string;\n\n @Field(() => String)\n runId: string;\n\n @Field(() => Boolean)\n active: boolean;\n\n @Field(() => MessageRole)\n role: MessageRole;\n\n @Field(() => String)\n state: string;\n\n @Field(() => Boolean)\n running: boolean;\n}\n\n@ObjectType({ implements: BaseMessageOutput })\nexport class ImageMessageOutput {\n @Field(() => String)\n format: string;\n\n @Field(() => String)\n bytes: string;\n\n @Field(() => MessageRole)\n role: MessageRole;\n\n @Field(() => String, { nullable: true })\n parentMessageId?: string;\n}\n\n@ObjectType()\nexport class CopilotResponse {\n @Field(() => String)\n threadId!: string;\n\n @Field(() => ResponseStatusUnion)\n status: typeof ResponseStatusUnion;\n\n @Field({ nullable: true })\n runId?: string;\n\n @Field(() => [BaseMessageOutput])\n messages: (typeof BaseMessageOutput)[];\n\n @Field(() => ExtensionsResponse, { nullable: true })\n extensions?: ExtensionsResponse;\n\n @Field(() => [BaseMetaEvent], { nullable: true })\n metaEvents?: (typeof BaseMetaEvent)[];\n}\n","import { Field, ObjectType, createUnionType, registerEnumType } from \"type-graphql\";\n\nexport enum MessageStatusCode {\n Pending = \"pending\",\n Success = \"success\",\n Failed = \"failed\",\n}\n\nregisterEnumType(MessageStatusCode, {\n name: \"MessageStatusCode\",\n});\n\n@ObjectType()\nclass BaseMessageStatus {\n @Field(() => MessageStatusCode)\n code: MessageStatusCode;\n}\n\n@ObjectType()\nexport class PendingMessageStatus extends BaseMessageStatus {\n code: MessageStatusCode = MessageStatusCode.Pending;\n}\n\n@ObjectType()\nexport class SuccessMessageStatus extends BaseMessageStatus {\n code: MessageStatusCode = MessageStatusCode.Success;\n}\n\n@ObjectType()\nexport class FailedMessageStatus extends BaseMessageStatus {\n code: MessageStatusCode = MessageStatusCode.Failed;\n\n @Field(() => String)\n reason: string;\n}\n\nexport const MessageStatusUnion = createUnionType({\n name: \"MessageStatus\",\n types: () => [PendingMessageStatus, SuccessMessageStatus, FailedMessageStatus] as const,\n});\n","import { GraphQLJSON } from \"graphql-scalars\";\nimport { Field, InterfaceType, ObjectType, createUnionType, registerEnumType } from \"type-graphql\";\n\nexport enum ResponseStatusCode {\n Pending = \"pending\",\n Success = \"success\",\n Failed = \"failed\",\n}\n\nregisterEnumType(ResponseStatusCode, {\n name: \"ResponseStatusCode\",\n});\n\n@InterfaceType({\n resolveType(value) {\n if (value.code === ResponseStatusCode.Success) {\n return SuccessResponseStatus;\n } else if (value.code === ResponseStatusCode.Failed) {\n return FailedResponseStatus;\n } else if (value.code === ResponseStatusCode.Pending) {\n return PendingResponseStatus;\n }\n return undefined;\n },\n})\n@ObjectType()\nabstract class BaseResponseStatus {\n @Field(() => ResponseStatusCode)\n code: ResponseStatusCode;\n}\n\n@ObjectType({ implements: BaseResponseStatus })\nexport class PendingResponseStatus extends BaseResponseStatus {\n code: ResponseStatusCode = ResponseStatusCode.Pending;\n}\n\n@ObjectType({ implements: BaseResponseStatus })\nexport class SuccessResponseStatus extends BaseResponseStatus {\n code: ResponseStatusCode = ResponseStatusCode.Success;\n}\n\nexport enum FailedResponseStatusReason {\n GUARDRAILS_VALIDATION_FAILED = \"GUARDRAILS_VALIDATION_FAILED\",\n MESSAGE_STREAM_INTERRUPTED = \"MESSAGE_STREAM_INTERRUPTED\",\n UNKNOWN_ERROR = \"UNKNOWN_ERROR\",\n}\n\nregisterEnumType(FailedResponseStatusReason, {\n name: \"FailedResponseStatusReason\",\n});\n\n@ObjectType({ implements: BaseResponseStatus })\nexport class FailedResponseStatus extends BaseResponseStatus {\n code: ResponseStatusCode = ResponseStatusCode.Failed;\n\n @Field(() => FailedResponseStatusReason)\n reason: FailedResponseStatusReason;\n\n @Field(() => GraphQLJSON, { nullable: true })\n details?: Record<string, any> = null;\n}\n\nexport const ResponseStatusUnion = createUnionType({\n name: \"ResponseStatus\",\n types: () => [PendingResponseStatus, SuccessResponseStatus, FailedResponseStatus] as const,\n});\n","import { Field, ObjectType } from \"type-graphql\";\n\n/**\n * The extensions response is used to receive additional information from the copilot runtime, specific to a\n * service adapter or agent framework.\n *\n * Next time a request to the runtime is made, the extensions response will be included in the request as input.\n */\n\n@ObjectType()\nexport class ExtensionsResponse {\n @Field(() => OpenAIApiAssistantAPIResponse, { nullable: true })\n openaiAssistantAPI?: OpenAIApiAssistantAPIResponse;\n}\n\n@ObjectType()\nexport class OpenAIApiAssistantAPIResponse {\n @Field(() => String, { nullable: true })\n runId?: string;\n\n @Field(() => String, { nullable: true })\n threadId?: string;\n}\n","import { Field, InputType } from \"type-graphql\";\n\n@InputType()\nexport class CopilotContextInput {\n @Field(() => String)\n description: string;\n\n @Field(() => String)\n value: string;\n}\n","import {\n Action,\n CopilotKitError,\n CopilotKitErrorCode,\n CopilotKitLowLevelError,\n ensureStructuredError,\n randomId,\n Severity,\n} from \"@copilotkit/shared\";\nimport { plainToInstance } from \"class-transformer\";\nimport {\n catchError,\n concat,\n concatMap,\n EMPTY,\n firstValueFrom,\n from,\n of,\n ReplaySubject,\n scan,\n Subject,\n} from \"rxjs\";\nimport { ActionInput } from \"../graphql/inputs/action.input\";\nimport { ActionExecutionMessage, ResultMessage, TextMessage } from \"../graphql/types/converted\";\nimport { GuardrailsResult } from \"../graphql/types/guardrails-result.type\";\nimport { isRemoteAgentAction } from \"../lib/runtime/remote-actions\";\nimport { generateHelpfulErrorMessage } from \"../lib/streaming\";\nimport telemetry from \"../lib/telemetry-client\";\nimport { streamLangChainResponse } from \"./langchain/utils\";\n\nexport enum RuntimeEventTypes {\n TextMessageStart = \"TextMessageStart\",\n TextMessageContent = \"TextMessageContent\",\n TextMessageEnd = \"TextMessageEnd\",\n ActionExecutionStart = \"ActionExecutionStart\",\n ActionExecutionArgs = \"ActionExecutionArgs\",\n ActionExecutionEnd = \"ActionExecutionEnd\",\n ActionExecutionResult = \"ActionExecutionResult\",\n AgentStateMessage = \"AgentStateMessage\",\n MetaEvent = \"MetaEvent\",\n RunError = \"RunError\",\n}\n\nexport enum RuntimeMetaEventName {\n LangGraphInterruptEvent = \"LangGraphInterruptEvent\",\n LangGraphInterruptResumeEvent = \"LangGraphInterruptResumeEvent\",\n CopilotKitLangGraphInterruptEvent = \"CopilotKitLangGraphInterruptEvent\",\n}\n\nexport type RunTimeMetaEvent =\n | {\n type: RuntimeEventTypes.MetaEvent;\n name: RuntimeMetaEventName.LangGraphInterruptEvent;\n value: string;\n }\n | {\n type: RuntimeEventTypes.MetaEvent;\n name: RuntimeMetaEventName.CopilotKitLangGraphInterruptEvent;\n data: { value: string; messages: (TextMessage | ActionExecutionMessage | ResultMessage)[] };\n }\n | {\n type: RuntimeEventTypes.MetaEvent;\n name: RuntimeMetaEventName.LangGraphInterruptResumeEvent;\n data: string;\n };\n\nexport type RuntimeErrorEvent = {\n type: RuntimeEventTypes.RunError;\n message: string;\n code?: string;\n};\n\nexport type RuntimeEvent =\n | { type: RuntimeEventTypes.TextMessageStart; messageId: string; parentMessageId?: string }\n | {\n type: RuntimeEventTypes.TextMessageContent;\n messageId: string;\n content: string;\n }\n | { type: RuntimeEventTypes.TextMessageEnd; messageId: string }\n | {\n type: RuntimeEventTypes.ActionExecutionStart;\n actionExecutionId: string;\n actionName: string;\n parentMessageId?: string;\n }\n | { type: RuntimeEventTypes.ActionExecutionArgs; actionExecutionId: string; args: string }\n | { type: RuntimeEventTypes.ActionExecutionEnd; actionExecutionId: string }\n | {\n type: RuntimeEventTypes.ActionExecutionResult;\n actionName: string;\n actionExecutionId: string;\n result: string;\n }\n | {\n type: RuntimeEventTypes.AgentStateMessage;\n threadId: string;\n agentName: string;\n nodeName: string;\n runId: string;\n active: boolean;\n role: string;\n state: string;\n running: boolean;\n }\n | RunTimeMetaEvent\n | RuntimeErrorEvent;\n\ninterface RuntimeEventWithState {\n event: RuntimeEvent | null;\n callActionServerSide: boolean;\n action: Action<any> | null;\n actionExecutionId: string | null;\n args: string;\n actionExecutionParentMessageId: string | null;\n}\n\ntype EventSourceCallback = (eventStream$: RuntimeEventSubject) => Promise<void>;\n\nexport class RuntimeEventSubject extends ReplaySubject<RuntimeEvent> {\n constructor() {\n super();\n }\n\n sendTextMessageStart({\n messageId,\n parentMessageId,\n }: {\n messageId: string;\n parentMessageId?: string;\n }) {\n this.next({ type: RuntimeEventTypes.TextMessageStart, messageId, parentMessageId });\n }\n\n sendTextMessageContent({ messageId, content }: { messageId: string; content: string }) {\n this.next({ type: RuntimeEventTypes.TextMessageContent, content, messageId });\n }\n\n sendTextMessageEnd({ messageId }: { messageId: string }) {\n this.next({ type: RuntimeEventTypes.TextMessageEnd, messageId });\n }\n\n sendTextMessage(messageId: string, content: string) {\n this.sendTextMessageStart({ messageId });\n this.sendTextMessageContent({ messageId, content });\n this.sendTextMessageEnd({ messageId });\n }\n\n sendActionExecutionStart({\n actionExecutionId,\n actionName,\n parentMessageId,\n }: {\n actionExecutionId: string;\n actionName: string;\n parentMessageId?: string;\n }) {\n this.next({\n type: RuntimeEventTypes.ActionExecutionStart,\n actionExecutionId,\n actionName,\n parentMessageId,\n });\n }\n\n sendActionExecutionArgs({\n actionExecutionId,\n args,\n }: {\n actionExecutionId: string;\n args: string;\n }) {\n this.next({ type: RuntimeEventTypes.ActionExecutionArgs, args, actionExecutionId });\n }\n\n sendActionExecutionEnd({ actionExecutionId }: { actionExecutionId: string }) {\n this.next({ type: RuntimeEventTypes.ActionExecutionEnd, actionExecutionId });\n }\n\n sendActionExecution({\n actionExecutionId,\n actionName,\n args,\n parentMessageId,\n }: {\n actionExecutionId: string;\n actionName: string;\n args: string;\n parentMessageId?: string;\n }) {\n this.sendActionExecutionStart({ actionExecutionId, actionName, parentMessageId });\n this.sendActionExecutionArgs({ actionExecutionId, args });\n this.sendActionExecutionEnd({ actionExecutionId });\n }\n\n sendActionExecutionResult({\n actionExecutionId,\n actionName,\n result,\n error,\n }: {\n actionExecutionId: string;\n actionName: string;\n result?: string;\n error?: { code: string; message: string };\n }) {\n this.next({\n type: RuntimeEventTypes.ActionExecutionResult,\n actionName,\n actionExecutionId,\n result: ResultMessage.encodeResult(result, error),\n });\n }\n\n sendAgentStateMessage({\n threadId,\n agentName,\n nodeName,\n runId,\n active,\n role,\n state,\n running,\n }: {\n threadId: string;\n agentName: string;\n nodeName: string;\n runId: string;\n active: boolean;\n role: string;\n state: string;\n running: boolean;\n }) {\n this.next({\n type: RuntimeEventTypes.AgentStateMessage,\n threadId,\n agentName,\n nodeName,\n runId,\n active,\n role,\n state,\n running,\n });\n }\n}\n\nexport class RuntimeEventSource {\n private eventStream$ = new RuntimeEventSubject();\n private callback!: EventSourceCallback;\n private errorHandler?: (error: any, context: any) => Promise<void>;\n private errorContext?: any;\n\n constructor(params?: {\n errorHandler?: (error: any, context: any) => Promise<void>;\n errorContext?: any;\n }) {\n this.errorHandler = params?.errorHandler;\n this.errorContext = params?.errorContext;\n }\n\n async stream(callback: EventSourceCallback): Promise<void> {\n this.callback = callback;\n }\n\n sendErrorMessageToChat(message = \"An error occurred. Please try again.\") {\n const errorMessage = `❌ ${message}`;\n if (!this.callback) {\n this.stream(async (eventStream$) => {\n eventStream$.sendTextMessage(randomId(), errorMessage);\n });\n } else {\n this.eventStream$.sendTextMessage(randomId(), errorMessage);\n }\n }\n\n processRuntimeEvents({\n serverSideActions,\n guardrailsResult$,\n actionInputsWithoutAgents,\n threadId,\n }: {\n serverSideActions: Action<any>[];\n guardrailsResult$?: Subject<GuardrailsResult>;\n actionInputsWithoutAgents: ActionInput[];\n threadId: string;\n }) {\n this.callback(this.eventStream$).catch(async (error) => {\n // Convert streaming errors to structured errors, but preserve already structured ones\n const structuredError = ensureStructuredError(error, convertStreamingErrorToStructured);\n\n // Call the runtime error handler if provided\n if (this.errorHandler && this.errorContext) {\n try {\n await this.errorHandler(structuredError, this.errorContext);\n } catch (errorHandlerError) {\n console.error(\"Error in streaming error handler:\", errorHandlerError);\n }\n }\n\n this.eventStream$.error(structuredError);\n this.eventStream$.complete();\n });\n return this.eventStream$.pipe(\n // track state\n scan(\n (acc, event) => {\n // It seems like this is needed so that rxjs recognizes the object has changed\n // This fixes an issue where action were executed multiple times\n // Not investigating further for now (Markus)\n acc = { ...acc };\n\n if (event.type === RuntimeEventTypes.ActionExecutionStart) {\n acc.callActionServerSide =\n serverSideActions.find((action) => action.name === event.actionName) !== undefined;\n acc.args = \"\";\n acc.actionExecutionId = event.actionExecutionId;\n if (acc.callActionServerSide) {\n acc.action = serverSideActions.find((action) => action.name === event.actionName);\n }\n acc.actionExecutionParentMessageId = event.parentMessageId;\n } else if (event.type === RuntimeEventTypes.ActionExecutionArgs) {\n acc.args += event.args;\n }\n\n acc.event = event;\n\n return acc;\n },\n {\n event: null,\n callActionServerSide: false,\n args: \"\",\n actionExecutionId: null,\n action: null,\n actionExecutionParentMessageId: null,\n } as RuntimeEventWithState,\n ),\n concatMap((eventWithState) => {\n if (\n eventWithState.event!.type === RuntimeEventTypes.ActionExecutionEnd &&\n eventWithState.callActionServerSide\n ) {\n const toolCallEventStream$ = new RuntimeEventSubject();\n executeAction(\n toolCallEventStream$,\n guardrailsResult$ ? guardrailsResult$ : null,\n eventWithState.action!,\n eventWithState.args,\n eventWithState.actionExecutionParentMessageId,\n eventWithState.actionExecutionId,\n actionInputsWithoutAgents,\n threadId,\n ).catch((error) => {});\n\n telemetry.capture(\"oss.runtime.server_action_executed\", {});\n return concat(of(eventWithState.event!), toolCallEventStream$).pipe(\n catchError((error) => {\n // Convert streaming errors to structured errors and send as action result, but preserve already structured ones\n const structuredError = ensureStructuredError(\n error,\n convertStreamingErrorToStructured,\n );\n\n // Call the runtime error handler if provided\n if (this.errorHandler && this.errorContext) {\n // Use from() to handle async error handler\n from(\n this.errorHandler(structuredError, {\n ...this.errorContext,\n action: {\n name: eventWithState.action!.name,\n executionId: eventWithState.actionExecutionId,\n },\n }),\n ).subscribe({\n error: (errorHandlerError) => {\n console.error(\"Error in action execution error handler:\", errorHandlerError);\n },\n });\n }\n\n toolCallEventStream$.sendActionExecutionResult({\n actionExecutionId: eventWithState.actionExecutionId!,\n actionName: eventWithState.action!.name,\n error: {\n code: structuredError.code,\n message: structuredError.message,\n },\n });\n\n return EMPTY;\n }),\n );\n } else {\n return of(eventWithState.event!);\n }\n }),\n );\n }\n}\n\nasync function executeAction(\n eventStream$: RuntimeEventSubject,\n guardrailsResult$: Subject<GuardrailsResult> | null,\n action: Action<any>,\n actionArguments: string,\n actionExecutionParentMessageId: string | null,\n actionExecutionId: string,\n actionInputsWithoutAgents: ActionInput[],\n threadId: string,\n) {\n if (guardrailsResult$) {\n const { status } = await firstValueFrom(guardrailsResult$);\n\n if (status === \"denied\") {\n eventStream$.complete();\n return;\n }\n }\n\n // Prepare arguments for function calling\n let args: Record<string, any>[] = [];\n if (actionArguments) {\n try {\n args = JSON.parse(actionArguments);\n } catch (e) {\n console.error(\"Action argument unparsable\", { actionArguments });\n eventStream$.sendActionExecutionResult({\n actionExecutionId,\n actionName: action.name,\n error: {\n code: \"INVALID_ARGUMENTS\",\n message: \"Failed to parse action arguments\",\n },\n });\n return;\n }\n }\n\n // handle LangGraph agents\n if (isRemoteAgentAction(action)) {\n const result = `${action.name} agent started`;\n\n const agentExecution = plainToInstance(ActionExecutionMessage, {\n id: actionExecutionId,\n createdAt: new Date(),\n name: action.name,\n arguments: JSON.parse(actionArguments),\n parentMessageId: actionExecutionParentMessageId ?? actionExecutionId,\n });\n\n const agentExecutionResult = plainToInstance(ResultMessage, {\n id: \"result-\" + actionExecutionId,\n createdAt: new Date(),\n actionExecutionId,\n actionName: action.name,\n result,\n });\n\n eventStream$.sendActionExecutionResult({\n actionExecutionId,\n actionName: action.name,\n result,\n });\n\n const stream = await action.remoteAgentHandler({\n name: action.name,\n threadId,\n actionInputsWithoutAgents,\n additionalMessages: [agentExecution, agentExecutionResult],\n });\n\n // forward to eventStream$\n from(stream).subscribe({\n next: (event) => eventStream$.next(event),\n error: (err) => {\n // Preserve already structured CopilotKit errors, only convert unstructured errors\n const structuredError = ensureStructuredError(err, convertStreamingErrorToStructured);\n eventStream$.sendActionExecutionResult({\n actionExecutionId,\n actionName: action.name,\n error: {\n code: structuredError.code,\n message: structuredError.message,\n },\n });\n eventStream$.complete();\n },\n complete: () => eventStream$.complete(),\n });\n } else {\n // call the function\n try {\n const result = await action.handler?.(args);\n await streamLangChainResponse({\n result,\n eventStream$,\n actionExecution: {\n name: action.name,\n id: actionExecutionId,\n returnDirect: action.additionalConfig?.returnDirect,\n },\n });\n } catch (e) {\n console.error(\"Error in action handler\", e);\n eventStream$.sendActionExecutionResult({\n actionExecutionId,\n actionName: action.name,\n error: {\n code: \"HANDLER_ERROR\",\n message: e.message,\n },\n });\n eventStream$.complete();\n }\n }\n}\n\nfunction convertStreamingErrorToStructured(error: any): CopilotKitError {\n // Determine a more helpful error message based on context\n let helpfulMessage = generateHelpfulErrorMessage(error, \"event streaming connection\");\n\n // For network-related errors, use CopilotKitLowLevelError to preserve the original error\n if (\n error?.message?.includes(\"fetch failed\") ||\n error?.message?.includes(\"ECONNREFUSED\") ||\n error?.message?.includes(\"ENOTFOUND\") ||\n error?.message?.includes(\"ETIMEDOUT\") ||\n error?.message?.includes(\"terminated\") ||\n error?.cause?.code === \"UND_ERR_SOCKET\" ||\n error?.message?.includes(\"other side closed\") ||\n error?.code === \"UND_ERR_SOCKET\"\n ) {\n return new CopilotKitLowLevelError({\n error: error instanceof Error ? error : new Error(String(error)),\n url: \"event streaming connection\",\n message: helpfulMessage,\n });\n }\n\n // For all other errors, preserve the raw error in a basic CopilotKitError\n return new CopilotKitError({\n message: helpfulMessage,\n code: CopilotKitErrorCode.UNKNOWN,\n severity: Severity.CRITICAL,\n });\n}\n","import {\n ActionExecutionMessageInput,\n ResultMessageInput,\n TextMessageInput,\n AgentStateMessageInput,\n ImageMessageInput,\n} from \"../../inputs/message.input\";\nimport { BaseMessageInput } from \"../base\";\nimport { MessageRole } from \"../enums\";\n\nexport type MessageType =\n | \"TextMessage\"\n | \"ActionExecutionMessage\"\n | \"ResultMessage\"\n | \"AgentStateMessage\"\n | \"ImageMessage\";\n\nexport class Message extends BaseMessageInput {\n type: MessageType;\n\n isTextMessage(): this is TextMessage {\n return this.type === \"TextMessage\";\n }\n\n isActionExecutionMessage(): this is ActionExecutionMessage {\n return this.type === \"ActionExecutionMessage\";\n }\n\n isResultMessage(): this is ResultMessage {\n return this.type === \"ResultMessage\";\n }\n\n isAgentStateMessage(): this is AgentStateMessage {\n return this.type === \"AgentStateMessage\";\n }\n\n isImageMessage(): this is ImageMessage {\n return this.type === \"ImageMessage\";\n }\n}\n\nexport class TextMessage extends Message implements TextMessageInput {\n type: MessageType = \"TextMessage\";\n content: string;\n role: MessageRole;\n parentMessageId?: string;\n}\n\nexport class ActionExecutionMessage\n extends Message\n implements Omit<ActionExecutionMessageInput, \"arguments\" | \"scope\">\n{\n type: MessageType = \"ActionExecutionMessage\";\n name: string;\n arguments: Record<string, any>;\n parentMessageId?: string;\n}\n\nexport class ResultMessage extends Message implements ResultMessageInput {\n type: MessageType = \"ResultMessage\";\n actionExecutionId: string;\n actionName: string;\n result: string;\n\n static encodeResult(\n result: any,\n error?: { code: string; message: string } | string | Error,\n ): string {\n const errorObj = error\n ? typeof error === \"string\"\n ? { code: \"ERROR\", message: error }\n : error instanceof Error\n ? { code: \"ERROR\", message: error.message }\n : error\n : undefined;\n\n if (errorObj) {\n return JSON.stringify({\n error: errorObj,\n result: result || \"\",\n });\n }\n if (result === undefined) {\n return \"\";\n }\n return typeof result === \"string\" ? result : JSON.stringify(result);\n }\n\n static decodeResult(result: string): {\n error?: { code: string; message: string };\n result: string;\n } {\n if (!result) {\n return { result: \"\" };\n }\n try {\n const parsed = JSON.parse(result);\n if (parsed && typeof parsed === \"object\") {\n if (\"error\" in parsed) {\n return {\n error: parsed.error,\n result: parsed.result || \"\",\n };\n }\n return { result: JSON.stringify(parsed) };\n }\n return { result };\n } catch (e) {\n return { result };\n }\n }\n\n hasError(): boolean {\n try {\n const { error } = ResultMessage.decodeResult(this.result);\n return !!error;\n } catch {\n return false;\n }\n }\n\n getError(): { code: string; message: string } | undefined {\n try {\n const { error } = ResultMessage.decodeResult(this.result);\n return error;\n } catch {\n return undefined;\n }\n }\n}\n\nexport class AgentStateMessage extends Message implements Omit<AgentStateMessageInput, \"state\"> {\n type: MessageType = \"AgentStateMessage\";\n threadId: string;\n agentName: string;\n nodeName: string;\n runId: string;\n active: boolean;\n role: MessageRole;\n state: any;\n running: boolean;\n}\n\nexport class ImageMessage extends Message implements ImageMessageInput {\n type: MessageType = \"ImageMessage\";\n format: string;\n bytes: string;\n role: MessageRole;\n parentMessageId?: string;\n}\n","import { Action, CopilotKitErrorCode } from \"@copilotkit/shared\";\nimport { GraphQLContext } from \"../integrations/shared\";\nimport { Logger } from \"pino\";\nimport { Message } from \"../../graphql/types/converted\";\nimport { ActionInput } from \"../../graphql/inputs/action.input\";\nimport { AgentStateInput } from \"../../graphql/inputs/agent-state.input\";\nimport {\n constructLGCRemoteAction,\n constructRemoteActions,\n createHeaders,\n} from \"./remote-action-constructors\";\nimport {\n CopilotKitLowLevelError,\n ResolvedCopilotKitError,\n CopilotKitError,\n} from \"@copilotkit/shared\";\nimport { MetaEventInput } from \"../../graphql/inputs/meta-event.input\";\nimport { AbstractAgent } from \"@ag-ui/client\";\nimport { constructAGUIRemoteAction, RemoteAgentAction } from \"./agui-action\";\nimport { CopilotContextInput } from \"../../graphql/inputs/copilot-context.input\";\n\nexport type EndpointDefinition = CopilotKitEndpoint | LangGraphPlatformEndpoint;\n\nexport enum EndpointType {\n CopilotKit = \"copilotKit\",\n LangGraphPlatform = \"langgraph-platform\",\n}\n\nexport interface BaseEndpointDefinition<TActionType extends EndpointType> {\n type?: TActionType;\n}\n\nexport interface CopilotKitEndpoint extends BaseEndpointDefinition<EndpointType.CopilotKit> {\n url: string;\n onBeforeRequest?: ({ ctx }: { ctx: GraphQLContext }) => {\n headers?: Record<string, string> | undefined;\n };\n}\n\nexport interface LangGraphPlatformAgent {\n name: string;\n description: string;\n assistantId?: string;\n}\n\nexport interface LangGraphPlatformEndpoint\n extends BaseEndpointDefinition<EndpointType.LangGraphPlatform> {\n deploymentUrl: string;\n langsmithApiKey?: string | null;\n agents: LangGraphPlatformAgent[];\n}\n\nexport type RemoteActionInfoResponse = {\n actions: any[];\n agents: any[];\n};\n\nexport type RemoteAgentHandlerParams = {\n name: string;\n actionInputsWithoutAgents: ActionInput[];\n threadId?: string;\n nodeName?: string;\n additionalMessages?: Message[];\n metaEvents?: MetaEventInput[];\n};\n\nexport function isRemoteAgentAction(action: Action<any>): action is RemoteAgentAction {\n if (!action) {\n return false;\n }\n return typeof (action as RemoteAgentAction).remoteAgentHandler === \"function\";\n}\n\nasync function fetchRemoteInfo({\n url,\n onBeforeRequest,\n graphqlContext,\n logger,\n frontendUrl,\n}: {\n url: string;\n onBeforeRequest?: CopilotKitEndpoint[\"onBeforeRequest\"];\n graphqlContext: GraphQLContext;\n logger: Logger;\n frontendUrl?: string;\n}): Promise<RemoteActionInfoResponse> {\n logger.debug({ url }, \"Fetching actions from url\");\n const headers = createHeaders(onBeforeRequest, graphqlContext);\n\n const fetchUrl = `${url}/info`;\n try {\n const response = await fetch(fetchUrl, {\n method: \"POST\",\n headers,\n body: JSON.stringify({ properties: graphqlContext.properties, frontendUrl }),\n });\n\n if (!response.ok) {\n logger.error(\n { url, status: response.status, body: await response.text() },\n \"Failed to fetch actions from url\",\n );\n throw new ResolvedCopilotKitError({\n status: response.status,\n url: fetchUrl,\n isRemoteEndpoint: true,\n });\n }\n\n const json = await response.json();\n logger.debug({ json }, \"Fetched actions from url\");\n return json;\n } catch (error) {\n if (error instanceof CopilotKitError) {\n throw error;\n }\n throw new CopilotKitLowLevelError({ error, url: fetchUrl });\n }\n}\n\nexport async function setupRemoteActions({\n remoteEndpointDefinitions,\n graphqlContext,\n messages,\n agentStates,\n frontendUrl,\n agents,\n metaEvents,\n nodeName,\n context,\n}: {\n remoteEndpointDefinitions: EndpointDefinition[];\n graphqlContext: GraphQLContext;\n messages: Message[];\n agentStates?: AgentStateInput[];\n frontendUrl?: string;\n agents: Record<string, AbstractAgent>;\n metaEvents?: MetaEventInput[];\n nodeName?: string;\n context?: CopilotContextInput[];\n}): Promise<Action<any>[]> {\n const logger = graphqlContext.logger.child({ component: \"remote-actions.fetchRemoteActions\" });\n logger.debug({ remoteEndpointDefinitions }, \"Fetching from remote endpoints\");\n\n const threadMetadata = (graphqlContext.properties?.threadMetadata as Record<string, any>) || {};\n\n // Remove duplicates of remoteEndpointDefinitions.url\n const filtered = remoteEndpointDefinitions.filter((value, index, self) => {\n if (value.type === EndpointType.LangGraphPlatform) {\n return value;\n }\n return index === self.findIndex((t: CopilotKitEndpoint) => t.url === value.url);\n });\n\n const result = await Promise.all(\n filtered.map(async (endpoint) => {\n // Check for properties that can distinguish LG platform from other actions\n if (endpoint.type === EndpointType.LangGraphPlatform) {\n return constructLGCRemoteAction({\n endpoint,\n messages,\n graphqlContext,\n logger: logger.child({\n component: \"remote-actions.constructLGCRemoteAction\",\n endpoint,\n }),\n agentStates,\n });\n }\n\n const json = await fetchRemoteInfo({\n url: endpoint.url,\n onBeforeRequest: endpoint.onBeforeRequest,\n graphqlContext,\n logger: logger.child({ component: \"remote-actions.fetchActionsFromUrl\", endpoint }),\n frontendUrl,\n });\n\n return constructRemoteActions({\n json,\n messages,\n url: endpoint.url,\n onBeforeRequest: endpoint.onBeforeRequest,\n graphqlContext,\n logger: logger.child({ component: \"remote-actions.constructActions\", endpoint }),\n agentStates,\n });\n }),\n );\n\n for (const [key, agent] of Object.entries(agents)) {\n if (agent.agentId !== undefined && agent.agentId !== key) {\n throw new CopilotKitError({\n message: `Agent ${key} has agentId ${agent.agentId} which does not match the key ${key}`,\n code: CopilotKitErrorCode.UNKNOWN,\n });\n } else if (agent.agentId === undefined) {\n agent.agentId = key;\n }\n\n result.push(\n constructAGUIRemoteAction({\n logger,\n messages,\n agentStates,\n agent: agent,\n metaEvents,\n threadMetadata,\n nodeName,\n graphqlContext,\n context,\n }),\n );\n }\n\n return result.flat();\n}\n","import { TelemetryClient } from \"@copilotkit/shared\";\nimport { EndpointType, LangGraphPlatformEndpoint } from \"./runtime/remote-actions\";\nimport { createHash } from \"node:crypto\";\nimport { CopilotRuntime, resolveEndpointType } from \"./runtime/copilot-runtime\";\nimport { RuntimeInstanceCreatedInfo } from \"@copilotkit/shared/src/telemetry/events\";\nimport { CreateCopilotRuntimeServerOptions } from \"./integrations/shared\";\nconst packageJson = require(\"../../package.json\");\n\nconst telemetryClient = new TelemetryClient({\n packageName: packageJson.name,\n packageVersion: packageJson.version,\n});\n\nexport function getRuntimeInstanceTelemetryInfo(\n options: CreateCopilotRuntimeServerOptions,\n): RuntimeInstanceCreatedInfo {\n const runtime = options.runtime;\n const endpointsInfo = runtime.remoteEndpointDefinitions.reduce(\n (acc, endpoint) => {\n let info = { ...acc };\n\n const endpointType = resolveEndpointType(endpoint);\n if (!info.endpointTypes.includes(endpointType)) {\n info = {\n ...info,\n endpointTypes: [...info.endpointTypes, endpointType],\n };\n }\n\n if (endpointType === EndpointType.LangGraphPlatform) {\n // When type is resolved, recreating a const with casting of type\n const ep = endpoint as LangGraphPlatformEndpoint;\n info = {\n ...info,\n agentsAmount: ep.agents.length,\n hashedKey: ep.langsmithApiKey\n ? createHash(\"sha256\").update(ep.langsmithApiKey).digest(\"hex\")\n : null,\n };\n }\n\n return info;\n },\n { endpointTypes: [], agentsAmount: null, hashedKey: null },\n );\n\n // Get public API key from options.cloud.publicApiKey\n const publicApiKey = options.cloud?.publicApiKey;\n const apiKeyProvided = !!publicApiKey && publicApiKey.trim().length > 0;\n\n return {\n actionsAmount: runtime.actions.length,\n endpointsAmount: runtime.remoteEndpointDefinitions.length,\n endpointTypes: endpointsInfo.endpointTypes,\n agentsAmount: endpointsInfo.agentsAmount,\n hashedLgcKey: endpointsInfo.hashedKey,\n \"cloud.api_key_provided\": apiKeyProvided,\n ...(apiKeyProvided ? { \"cloud.public_api_key\": publicApiKey } : {}),\n ...(options.cloud?.baseUrl ? { \"cloud.base_url\": options.cloud.baseUrl } : {}),\n } as RuntimeInstanceCreatedInfo;\n}\n\nexport default telemetryClient;\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](/concepts/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 Action,\n actionParametersToJsonSchema,\n Parameter,\n ResolvedCopilotKitError,\n CopilotKitApiDiscoveryError,\n randomId,\n CopilotKitError,\n CopilotKitAgentDiscoveryError,\n CopilotKitMisuseError,\n CopilotKitErrorCode,\n CopilotKitLowLevelError,\n CopilotErrorHandler,\n CopilotErrorEvent,\n CopilotRequestContext,\n ensureStructuredError,\n} from \"@copilotkit/shared\";\nimport {\n CopilotServiceAdapter,\n EmptyAdapter,\n RemoteChain,\n RemoteChainParameters,\n} from \"../../service-adapters\";\n\nimport { MessageInput } from \"../../graphql/inputs/message.input\";\nimport { ActionInput } from \"../../graphql/inputs/action.input\";\nimport { RuntimeEventSource, RuntimeEventTypes } from \"../../service-adapters/events\";\nimport { convertGqlInputToMessages } from \"../../service-adapters/conversion\";\nimport { Message } from \"../../graphql/types/converted\";\nimport { ForwardedParametersInput } from \"../../graphql/inputs/forwarded-parameters.input\";\n\nimport {\n isRemoteAgentAction,\n EndpointType,\n setupRemoteActions,\n EndpointDefinition,\n CopilotKitEndpoint,\n LangGraphPlatformEndpoint,\n} from \"./remote-actions\";\n\nimport { GraphQLContext } from \"../integrations/shared\";\nimport { AgentSessionInput } from \"../../graphql/inputs/agent-session.input\";\nimport { from } from \"rxjs\";\nimport { AgentStateInput } from \"../../graphql/inputs/agent-state.input\";\nimport { ActionInputAvailability } from \"../../graphql/types/enums\";\nimport { createHeaders } from \"./remote-action-constructors\";\nimport { fetchWithRetry } from \"./retry-utils\";\nimport { Agent } from \"../../graphql/types/agents-response.type\";\nimport { ExtensionsInput } from \"../../graphql/inputs/extensions.input\";\nimport { ExtensionsResponse } from \"../../graphql/types/extensions-response.type\";\nimport { LoadAgentStateResponse } from \"../../graphql/types/load-agent-state-response.type\";\nimport { Client as LangGraphClient } from \"@langchain/langgraph-sdk\";\nimport { langchainMessagesToCopilotKit } from \"./remote-lg-action\";\nimport { MetaEventInput } from \"../../graphql/inputs/meta-event.input\";\nimport {\n CopilotObservabilityConfig,\n LLMRequestData,\n LLMResponseData,\n LLMErrorData,\n} from \"../observability\";\nimport { AbstractAgent } from \"@ag-ui/client\";\nimport { MessageRole } from \"../../graphql/types/enums\";\n\n// +++ MCP Imports +++\nimport {\n MCPClient,\n MCPEndpointConfig,\n MCPTool,\n convertMCPToolsToActions,\n generateMcpToolInstructions,\n} from \"./mcp-tools-utils\";\nimport { LangGraphAgent } from \"./langgraph/langgraph-agent\";\n// Define the function type alias here or import if defined elsewhere\ntype CreateMCPClientFunction = (config: MCPEndpointConfig) => Promise<MCPClient>;\n// --- MCP Imports ---\n\nimport { generateHelpfulErrorMessage } from \"../streaming\";\nimport { CopilotContextInput } from \"../../graphql/inputs/copilot-context.input\";\nimport { RemoteAgentAction } from \"./agui-action\";\n\nexport interface CopilotRuntimeRequest {\n serviceAdapter: CopilotServiceAdapter;\n messages: MessageInput[];\n actions: ActionInput[];\n agentSession?: AgentSessionInput;\n agentStates?: AgentStateInput[];\n outputMessagesPromise: Promise<Message[]>;\n threadId?: string;\n runId?: string;\n publicApiKey?: string;\n graphqlContext: GraphQLContext;\n forwardedParameters?: ForwardedParametersInput;\n url?: string;\n extensions?: ExtensionsInput;\n metaEvents?: MetaEventInput[];\n context?: CopilotContextInput[];\n}\n\ninterface CopilotRuntimeResponse {\n threadId: string;\n runId?: string;\n eventSource: RuntimeEventSource;\n serverSideActions: Action<any>[];\n actionInputsWithoutAgents: ActionInput[];\n extensions?: ExtensionsResponse;\n}\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 = (options: OnBeforeRequestOptions) => 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 = (options: OnAfterRequestOptions) => void | Promise<void>;\n\ninterface OnStopGenerationOptions {\n threadId: string;\n runId?: string;\n url?: string;\n agentName?: string;\n lastMessage: MessageInput;\n}\ntype OnStopGenerationHandler = (options: OnStopGenerationOptions) => void | Promise<void>;\n\ninterface Middleware {\n /**\n * A function that is called before the request is processed.\n */\n onBeforeRequest?: OnBeforeRequestHandler;\n\n /**\n * A function that is called after the request is processed.\n */\n onAfterRequest?: OnAfterRequestHandler;\n}\n\ntype AgentWithEndpoint = Agent & { endpoint: EndpointDefinition };\n\nexport interface CopilotRuntimeConstructorParams<T extends Parameter[] | [] = []> {\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 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 * 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 * Requires publicApiKey from CopilotKit component to be set:\n *\n * ```tsx\n * <CopilotKit publicApiKey=\"ck_pub_...\" />\n * ```\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 * **Requires publicApiKey**: Error handling only works when requests include a valid publicApiKey.\n * This is a premium Copilot Cloud feature.\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\nexport class CopilotRuntime<const T extends Parameter[] | [] = []> {\n public actions: ActionsConfiguration<T>;\n public agents: Record<string, AbstractAgent>;\n public remoteEndpointDefinitions: EndpointDefinition[];\n private langserve: Promise<Action<any>>[] = [];\n private onBeforeRequest?: OnBeforeRequestHandler;\n private onAfterRequest?: OnAfterRequestHandler;\n private onStopGeneration?: OnStopGenerationHandler;\n private delegateAgentProcessingToServiceAdapter: boolean;\n private observability?: CopilotObservabilityConfig;\n private availableAgents: Pick<AgentWithEndpoint, \"name\" | \"id\">[];\n private onError?: CopilotErrorHandler;\n private hasWarnedAboutError = false;\n\n // +++ MCP Properties +++\n private readonly mcpServersConfig?: MCPEndpointConfig[];\n private mcpActionCache = new Map<string, Action<any>[]>();\n // --- MCP Properties ---\n\n // +++ MCP Client Factory +++\n private readonly createMCPClientImpl?: CreateMCPClientFunction;\n // --- MCP Client Factory ---\n\n constructor(params?: CopilotRuntimeConstructorParams<T>) {\n if (\n params?.remoteEndpoints &&\n params?.remoteEndpoints.some((e) => e.type === EndpointType.LangGraphPlatform)\n ) {\n throw new CopilotKitMisuseError({\n message:\n \"LangGraph Platform remote endpoints are deprecated in favor of the `agents` property. Refer to https://docs.copilotkit.ai/langgraph for more information.\",\n });\n }\n\n if (\n params?.actions &&\n params?.remoteEndpoints &&\n params?.remoteEndpoints.some((e) => e.type === EndpointType.LangGraphPlatform)\n ) {\n console.warn(\"Actions set in runtime instance will not be available for the agent\");\n console.warn(\n `LangGraph Platform remote endpoints are deprecated in favor of the \"agents\" property`,\n );\n }\n\n // TODO: finalize\n // if (\n // params?.agents &&\n // Object.values(params.agents).some((agent) => {\n // return agent instanceof AguiLangGraphAgent && !(agent instanceof LangGraphAgent);\n // })\n // ) {\n // console.warn('LangGraph Agent class should be imported from @copilotkit/runtime. ')\n // }\n\n this.actions = params?.actions || [];\n this.availableAgents = [];\n\n for (const chain of params?.langserve || []) {\n const remoteChain = new RemoteChain(chain);\n this.langserve.push(remoteChain.toAction());\n }\n\n this.remoteEndpointDefinitions = params?.remoteEndpoints ?? params?.remoteActions ?? [];\n\n this.onBeforeRequest = params?.middleware?.onBeforeRequest;\n this.onAfterRequest = params?.middleware?.onAfterRequest;\n this.onStopGeneration = params?.onStopGeneration;\n this.delegateAgentProcessingToServiceAdapter =\n params?.delegateAgentProcessingToServiceAdapter || false;\n this.observability = params?.observability_c;\n this.agents = params?.agents ?? {};\n this.onError = params?.onError;\n // +++ MCP Initialization +++\n this.mcpServersConfig = params?.mcpServers;\n this.createMCPClientImpl = params?.createMCPClient;\n\n // Validate: If mcpServers are provided, createMCPClient must also be provided\n if (this.mcpServersConfig && this.mcpServersConfig.length > 0 && !this.createMCPClientImpl) {\n throw new CopilotKitMisuseError({\n message:\n \"MCP Integration Error: `mcpServers` were provided, but the `createMCPClient` function was not passed to the CopilotRuntime constructor. \" +\n \"Please provide an implementation for `createMCPClient`.\",\n });\n }\n\n // Warning if actions are defined alongside LangGraph platform (potentially MCP too?)\n if (\n params?.actions &&\n (params?.remoteEndpoints?.some((e) => e.type === EndpointType.LangGraphPlatform) ||\n this.mcpServersConfig?.length)\n ) {\n console.warn(\n \"Local 'actions' defined in CopilotRuntime might not be available to remote agents (LangGraph, MCP). Consider defining actions closer to the agent implementation if needed.\",\n );\n }\n }\n\n // +++ MCP Instruction Injection Method +++\n private injectMCPToolInstructions(\n messages: MessageInput[],\n currentActions: Action<any>[],\n ): MessageInput[] {\n // Filter the *passed-in* actions for MCP tools\n const mcpActionsForRequest = currentActions.filter((action) => (action as any)._isMCPTool);\n\n if (!mcpActionsForRequest || mcpActionsForRequest.length === 0) {\n return messages; // No MCP tools for this specific request\n }\n\n // Create a map to deduplicate tools by name (keeping the last one if duplicates exist)\n const uniqueMcpTools = new Map<string, Action<any>>();\n\n // Add all MCP tools to the map with their names as keys\n mcpActionsForRequest.forEach((action) => {\n uniqueMcpTools.set(action.name, action);\n });\n\n // Format instructions from the unique tools map\n // Convert Action objects to MCPTool format for the instruction generator\n const toolsMap: Record<string, MCPTool> = {};\n Array.from(uniqueMcpTools.values()).forEach((action) => {\n toolsMap[action.name] = {\n description: action.description || \"\",\n schema: action.parameters\n ? {\n parameters: {\n properties: action.parameters.reduce(\n (acc, p) => ({\n ...acc,\n [p.name]: { type: p.type, description: p.description },\n }),\n {},\n ),\n required: action.parameters.filter((p) => p.required).map((p) => p.name),\n },\n }\n : {},\n execute: async () => ({}), // Placeholder, not used for instructions\n };\n });\n\n // Generate instructions using the exported helper\n const mcpToolInstructions = generateMcpToolInstructions(toolsMap);\n\n if (!mcpToolInstructions) {\n return messages; // No MCP tools to describe\n }\n\n const instructions =\n mcpToolInstructions + \"\\nUse them when appropriate to fulfill the user's request.\";\n\n const systemMessageIndex = messages.findIndex((msg) => msg.textMessage?.role === \"system\");\n\n const newMessages = [...messages]; // Create a mutable copy\n\n if (systemMessageIndex !== -1) {\n const existingMsg = newMessages[systemMessageIndex];\n if (existingMsg.textMessage) {\n existingMsg.textMessage.content =\n (existingMsg.textMessage.content ? existingMsg.textMessage.content + \"\\n\\n\" : \"\") +\n instructions;\n }\n } else {\n newMessages.unshift({\n id: randomId(),\n createdAt: new Date(),\n textMessage: {\n role: MessageRole.system,\n content: instructions,\n },\n actionExecutionMessage: undefined,\n resultMessage: undefined,\n agentStateMessage: undefined,\n });\n }\n\n return newMessages;\n }\n\n async processRuntimeRequest(request: CopilotRuntimeRequest): Promise<CopilotRuntimeResponse> {\n const {\n serviceAdapter,\n messages: rawMessages,\n actions: clientSideActionsInput,\n threadId,\n runId,\n outputMessagesPromise,\n graphqlContext,\n forwardedParameters,\n url,\n extensions,\n agentSession,\n agentStates,\n publicApiKey,\n context,\n } = request;\n graphqlContext.request.signal.addEventListener(\n \"abort\",\n () =>\n this.onStopGeneration?.({\n threadId,\n runId,\n url,\n agentName: agentSession?.agentName,\n lastMessage: rawMessages[rawMessages.length - 1],\n }),\n { once: true }, // optional: fire only once\n );\n\n const eventSource = new RuntimeEventSource({\n errorHandler: async (error, context) => {\n await this.error(\"error\", context, error, publicApiKey);\n },\n errorContext: {\n threadId,\n runId,\n source: \"runtime\",\n request: {\n operation: \"processRuntimeRequest\",\n method: \"POST\",\n url: url,\n startTime: Date.now(),\n },\n agent: agentSession ? { name: agentSession.agentName } : undefined,\n technical: {\n environment: process.env.NODE_ENV,\n },\n },\n });\n // Track request start time for logging\n const requestStartTime = Date.now();\n // For storing streamed chunks if progressive logging is enabled\n const streamedChunks: any[] = [];\n\n try {\n if (\n Object.keys(this.agents).length &&\n agentSession?.agentName &&\n !this.delegateAgentProcessingToServiceAdapter\n ) {\n this.agents = { [agentSession.agentName]: this.agents[agentSession.agentName] };\n }\n\n if (agentSession && !this.delegateAgentProcessingToServiceAdapter) {\n return await this.processAgentRequest(request);\n }\n if (serviceAdapter instanceof EmptyAdapter) {\n throw new CopilotKitMisuseError({\n message: `Invalid adapter configuration: EmptyAdapter is only meant to be used with agent lock mode. \nFor non-agent components like useCopilotChatSuggestions, CopilotTextarea, or CopilotTask, \nplease use an LLM adapter instead.`,\n });\n }\n\n // +++ Get Server Side Actions (including dynamic MCP) EARLY +++\n const serverSideActions = await this.getServerSideActions(request);\n // --- Get Server Side Actions (including dynamic MCP) EARLY ---\n\n // Filter raw messages *before* injection\n const filteredRawMessages = rawMessages.filter((message) => !message.agentStateMessage);\n\n // +++ Inject MCP Instructions based on current actions +++\n const messagesWithInjectedInstructions = this.injectMCPToolInstructions(\n filteredRawMessages,\n serverSideActions,\n );\n const inputMessages = convertGqlInputToMessages(messagesWithInjectedInstructions);\n // --- Inject MCP Instructions based on current actions ---\n\n // Log LLM request if logging is enabled\n if (this.observability?.enabled && publicApiKey) {\n try {\n const requestData: LLMRequestData = {\n threadId,\n runId,\n model: forwardedParameters?.model,\n messages: inputMessages,\n actions: clientSideActionsInput,\n forwardedParameters,\n timestamp: requestStartTime,\n provider: this.detectProvider(serviceAdapter),\n };\n\n await this.observability.hooks.handleRequest(requestData);\n } catch (error) {\n console.error(\"Error logging LLM request:\", error);\n }\n }\n\n const serverSideActionsInput: ActionInput[] = serverSideActions.map((action) => ({\n name: action.name,\n description: action.description,\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters)),\n additionalConfig: action.additionalConfig,\n }));\n\n const actionInputs = flattenToolCallsNoDuplicates([\n ...serverSideActionsInput,\n ...clientSideActionsInput.filter(\n // Filter remote actions from CopilotKit core loop\n (action) => action.available !== ActionInputAvailability.remote,\n ),\n ]);\n\n await this.onBeforeRequest?.({\n threadId,\n runId,\n inputMessages,\n properties: graphqlContext.properties,\n url,\n });\n\n const result = await serviceAdapter.process({\n messages: inputMessages,\n actions: actionInputs,\n threadId,\n runId,\n eventSource,\n forwardedParameters,\n extensions,\n agentSession,\n agentStates,\n });\n\n // for backwards compatibility, we deal with the case that no threadId is provided\n // by the frontend, by using the threadId from the response\n const nonEmptyThreadId = threadId ?? result.threadId;\n\n outputMessagesPromise\n .then((outputMessages) => {\n this.onAfterRequest?.({\n threadId: nonEmptyThreadId,\n runId: result.runId,\n inputMessages,\n outputMessages,\n properties: graphqlContext.properties,\n url,\n });\n })\n .catch((_error) => {});\n\n // After getting the response, log it if logging is enabled\n if (this.observability?.enabled && publicApiKey) {\n try {\n outputMessagesPromise\n .then((outputMessages) => {\n const responseData: LLMResponseData = {\n threadId: result.threadId,\n runId: result.runId,\n model: forwardedParameters?.model,\n // Use collected chunks for progressive mode or outputMessages for regular mode\n output: this.observability.progressive ? streamedChunks : outputMessages,\n latency: Date.now() - requestStartTime,\n timestamp: Date.now(),\n provider: this.detectProvider(serviceAdapter),\n // Indicate this is the final response\n isFinalResponse: true,\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 // Add progressive logging if enabled\n if (this.observability?.enabled && this.observability.progressive && publicApiKey) {\n // Keep reference to original stream function\n const originalStream = eventSource.stream.bind(eventSource);\n\n // Wrap the stream function to intercept events\n eventSource.stream = async (callback) => {\n await originalStream(async (eventStream$) => {\n // Create subscription to capture streaming events\n eventStream$.subscribe({\n next: (event) => {\n // Only log content chunks\n if (event.type === RuntimeEventTypes.TextMessageContent) {\n // Store the chunk\n streamedChunks.push(event.content);\n\n // Log each chunk separately for progressive mode\n try {\n const progressiveData: LLMResponseData = {\n threadId: threadId || \"\",\n runId,\n model: forwardedParameters?.model,\n output: event.content,\n latency: Date.now() - requestStartTime,\n timestamp: Date.now(),\n provider: this.detectProvider(serviceAdapter),\n isProgressiveChunk: true,\n };\n\n // Use Promise to handle async logger without awaiting\n Promise.resolve()\n .then(() => {\n this.observability.hooks.handleResponse(progressiveData);\n })\n .catch((error) => {\n console.error(\"Error in progressive logging:\", error);\n });\n } catch (error) {\n console.error(\"Error preparing progressive log data:\", error);\n }\n }\n },\n });\n\n // Call the original callback with the event stream\n await callback(eventStream$);\n });\n };\n }\n\n return {\n threadId: nonEmptyThreadId,\n runId: result.runId,\n eventSource,\n serverSideActions,\n actionInputsWithoutAgents: actionInputs.filter(\n (action) =>\n // TODO-AGENTS: do not exclude ALL server side actions\n !serverSideActions.find((serverSideAction) => serverSideAction.name == action.name),\n // !isRemoteAgentAction(\n // serverSideActions.find((serverSideAction) => serverSideAction.name == action.name),\n // ),\n ),\n extensions: result.extensions,\n };\n } catch (error) {\n // Log error if logging is enabled\n if (this.observability?.enabled && publicApiKey) {\n try {\n const errorData: LLMErrorData = {\n threadId,\n runId,\n model: forwardedParameters?.model,\n error: error instanceof Error ? error : String(error),\n timestamp: Date.now(),\n latency: Date.now() - requestStartTime,\n provider: this.detectProvider(serviceAdapter),\n };\n\n await this.observability.hooks.handleError(errorData);\n } catch (logError) {\n console.error(\"Error logging LLM error:\", logError);\n }\n }\n\n let structuredError: CopilotKitError;\n\n if (error instanceof CopilotKitError) {\n structuredError = error;\n } else {\n // Convert non-CopilotKitErrors to structured errors, but preserve already structured ones\n structuredError = ensureStructuredError(error, (err) =>\n this.convertStreamingErrorToStructured(err),\n );\n }\n\n // Track the error\n await this.error(\n \"error\",\n {\n threadId,\n runId,\n source: \"runtime\",\n request: {\n operation: \"processRuntimeRequest\",\n method: \"POST\",\n url: url,\n startTime: requestStartTime,\n },\n response: {\n endTime: Date.now(),\n latency: Date.now() - requestStartTime,\n },\n agent: agentSession ? { name: agentSession.agentName } : undefined,\n technical: {\n environment: process.env.NODE_ENV,\n stackTrace: error instanceof Error ? error.stack : undefined,\n },\n },\n structuredError,\n publicApiKey,\n );\n\n throw structuredError;\n }\n }\n\n async getAllAgents(graphqlContext: GraphQLContext): Promise<(AgentWithEndpoint | Agent)[]> {\n const agentsWithEndpoints = await this.discoverAgentsFromEndpoints(graphqlContext);\n const aguiAgents = this.discoverAgentsFromAgui();\n\n this.availableAgents = [...agentsWithEndpoints, ...aguiAgents].map((a) => ({\n name: a.name,\n id: a.id,\n }));\n\n return [...agentsWithEndpoints, ...aguiAgents];\n }\n\n async discoverAgentsFromEndpoints(graphqlContext: GraphQLContext): Promise<AgentWithEndpoint[]> {\n const agents: Promise<AgentWithEndpoint[]> = this.remoteEndpointDefinitions.reduce(\n async (acc: Promise<Agent[]>, endpoint) => {\n const agents = await acc;\n if (endpoint.type === EndpointType.LangGraphPlatform) {\n const propertyHeaders = graphqlContext.properties.authorization\n ? { authorization: `Bearer ${graphqlContext.properties.authorization}` }\n : null;\n\n const client = new LangGraphClient({\n apiUrl: endpoint.deploymentUrl,\n apiKey: endpoint.langsmithApiKey,\n defaultHeaders: { ...propertyHeaders },\n });\n let data: Array<{ assistant_id: string; graph_id: string }> | { detail: string } = [];\n try {\n data = await client.assistants.search();\n\n if (data && \"detail\" in data && (data.detail as string).toLowerCase() === \"not found\") {\n throw new CopilotKitAgentDiscoveryError({ availableAgents: this.availableAgents });\n }\n } catch (e) {\n throw new CopilotKitMisuseError({\n message: `\n Failed to find or contact remote endpoint at url ${endpoint.deploymentUrl}.\n Make sure the API is running and that it's indeed a LangGraph platform url.\n \n See more: https://docs.copilotkit.ai/troubleshooting/common-issues`,\n });\n }\n const endpointAgents = data.map((entry) => ({\n name: entry.graph_id,\n id: entry.assistant_id,\n description: \"\",\n endpoint,\n }));\n return [...agents, ...endpointAgents];\n }\n\n interface InfoResponse {\n agents?: Array<{\n name: string;\n description: string;\n }>;\n }\n const cpkEndpoint = endpoint as CopilotKitEndpoint;\n const fetchUrl = `${endpoint.url}/info`;\n try {\n const response = await fetchWithRetry(fetchUrl, {\n method: \"POST\",\n headers: createHeaders(cpkEndpoint.onBeforeRequest, graphqlContext),\n body: JSON.stringify({ properties: graphqlContext.properties }),\n });\n if (!response.ok) {\n if (response.status === 404) {\n throw new CopilotKitApiDiscoveryError({ url: fetchUrl });\n }\n throw new ResolvedCopilotKitError({\n status: response.status,\n url: fetchUrl,\n isRemoteEndpoint: true,\n });\n }\n\n const data: InfoResponse = await response.json();\n const endpointAgents = (data?.agents ?? []).map((agent) => ({\n name: agent.name,\n description: agent.description ?? \"\" ?? \"\",\n id: randomId(), // Required by Agent type\n endpoint,\n }));\n return [...agents, ...endpointAgents];\n } catch (error) {\n if (error instanceof CopilotKitError) {\n throw error;\n }\n throw new CopilotKitLowLevelError({ error: error as Error, url: fetchUrl });\n }\n },\n Promise.resolve([]),\n );\n\n return agents;\n }\n\n discoverAgentsFromAgui(): Agent[] {\n return Object.entries(this.agents ?? []).map(([key, agent]: [string, AbstractAgent]) => ({\n name: (agent as any).agentName ?? key,\n id: agent.agentId ?? key,\n description: agent.description ?? \"\",\n }));\n }\n\n async loadAgentState(\n graphqlContext: GraphQLContext,\n threadId: string,\n agentName: string,\n ): Promise<LoadAgentStateResponse> {\n const agents = await this.getAllAgents(graphqlContext);\n\n const agent = agents.find((agent) => agent.name === agentName);\n if (!agent) {\n throw new Error(\"Agent not found\");\n }\n\n if (\n \"endpoint\" in agent &&\n (agent.endpoint.type === EndpointType.CopilotKit || !(\"type\" in agent.endpoint))\n ) {\n const cpkEndpoint = agent.endpoint as CopilotKitEndpoint;\n const fetchUrl = `${cpkEndpoint.url}/agents/state`;\n try {\n const response = await fetchWithRetry(fetchUrl, {\n method: \"POST\",\n headers: createHeaders(cpkEndpoint.onBeforeRequest, graphqlContext),\n body: JSON.stringify({\n properties: graphqlContext.properties,\n threadId,\n name: agentName,\n }),\n });\n if (!response.ok) {\n if (response.status === 404) {\n throw new CopilotKitApiDiscoveryError({ url: fetchUrl });\n }\n\n // Extract semantic error information from response body\n let errorMessage = `HTTP ${response.status} error`;\n try {\n const errorBody = await response.text();\n const parsedError = JSON.parse(errorBody);\n if (parsedError.error && typeof parsedError.error === \"string\") {\n errorMessage = parsedError.error;\n }\n } catch {\n // If parsing fails, fall back to generic message\n }\n\n throw new ResolvedCopilotKitError({\n status: response.status,\n url: fetchUrl,\n isRemoteEndpoint: true,\n message: errorMessage,\n });\n }\n\n const data: LoadAgentStateResponse = await response.json();\n\n return {\n ...data,\n state: JSON.stringify(data.state),\n messages: JSON.stringify(data.messages),\n };\n } catch (error) {\n if (error instanceof CopilotKitError) {\n throw error;\n }\n throw new CopilotKitLowLevelError({ error, url: fetchUrl });\n }\n }\n\n const propertyHeaders = graphqlContext.properties.authorization\n ? { authorization: `Bearer ${graphqlContext.properties.authorization}` }\n : null;\n\n let state: any = {};\n try {\n let client: LangGraphClient | null;\n if (\"endpoint\" in agent && agent.endpoint.type === EndpointType.LangGraphPlatform) {\n client = new LangGraphClient({\n apiUrl: agent.endpoint.deploymentUrl,\n apiKey: agent.endpoint.langsmithApiKey,\n defaultHeaders: { ...propertyHeaders },\n });\n } else {\n const aguiAgent = graphqlContext._copilotkit.runtime.agents[agent.name] as LangGraphAgent;\n if (!aguiAgent) {\n throw new Error(`Agent: ${agent.name} could not be resolved`);\n }\n // @ts-expect-error -- both clients are the same\n client = aguiAgent.client ?? null;\n }\n\n state = client ? ((await client.threads.getState(threadId)).values as any) : {};\n } catch (error) {\n // All errors from agent state loading are user configuration issues\n const errorMessage = error instanceof Error ? error.message : String(error);\n const errorStatus = error?.response?.status || error?.status;\n\n if (errorStatus === 404) {\n state = {};\n } else {\n // Log user configuration errors at debug level to reduce noise\n console.debug(`Agent '${agentName}' configuration issue: ${errorMessage}`);\n\n // Throw a configuration error - all agent state loading failures are user setup issues\n throw new ResolvedCopilotKitError({\n status: 400,\n message: `Agent '${agentName}' failed to execute: ${errorMessage}`,\n code: CopilotKitErrorCode.CONFIGURATION_ERROR,\n });\n }\n }\n\n if (Object.keys(state).length === 0) {\n return {\n threadId: threadId || \"\",\n threadExists: false,\n state: JSON.stringify({}),\n messages: JSON.stringify([]),\n };\n } else {\n const { messages, ...stateWithoutMessages } = state;\n const copilotkitMessages = langchainMessagesToCopilotKit(messages);\n return {\n threadId: threadId || \"\",\n threadExists: true,\n state: JSON.stringify(stateWithoutMessages),\n messages: JSON.stringify(copilotkitMessages),\n };\n }\n\n throw new Error(`Agent: ${agent.name} could not be resolved`);\n }\n\n private async processAgentRequest(\n request: CopilotRuntimeRequest,\n ): Promise<CopilotRuntimeResponse> {\n const {\n messages: rawMessages,\n outputMessagesPromise,\n graphqlContext,\n agentSession,\n threadId: threadIdFromRequest,\n metaEvents,\n publicApiKey,\n forwardedParameters,\n context,\n } = request;\n const { agentName, nodeName } = agentSession;\n\n // Track request start time for observability\n const requestStartTime = Date.now();\n // For storing streamed chunks if progressive logging is enabled\n const streamedChunks: any[] = [];\n\n // for backwards compatibility, deal with the case when no threadId is provided\n const threadId = threadIdFromRequest ?? agentSession.threadId;\n\n // Track agent request start\n await this.error(\n \"agent_state\",\n {\n threadId,\n source: \"agent\",\n request: {\n operation: \"processAgentRequest\",\n method: \"POST\",\n startTime: requestStartTime,\n },\n agent: {\n name: agentName,\n nodeName: nodeName,\n },\n messages: {\n input: rawMessages,\n messageCount: rawMessages.length,\n },\n technical: {\n environment: process.env.NODE_ENV,\n },\n },\n undefined,\n publicApiKey,\n );\n\n const serverSideActions = await this.getServerSideActions(request);\n\n const messages = convertGqlInputToMessages(rawMessages);\n\n const currentAgent = serverSideActions.find(\n (action) => action.name === agentName && isRemoteAgentAction(action),\n ) as RemoteAgentAction;\n\n if (!currentAgent) {\n throw new CopilotKitAgentDiscoveryError({ agentName, availableAgents: this.availableAgents });\n }\n\n // Filter actions to include:\n // 1. Regular (non-agent) actions\n // 2. Other agents' actions (but prevent self-calls to avoid infinite loops)\n const availableActionsForCurrentAgent: ActionInput[] = serverSideActions\n .filter(\n (action) =>\n // Case 1: Keep all regular (non-agent) actions\n !isRemoteAgentAction(action) ||\n // Case 2: For agent actions, keep all except self (prevent infinite loops)\n (isRemoteAgentAction(action) && action.name !== agentName) /* prevent self-calls */,\n )\n .map((action) => ({\n name: action.name,\n description: action.description,\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters)),\n }));\n\n const allAvailableActions = flattenToolCallsNoDuplicates([\n ...availableActionsForCurrentAgent,\n ...request.actions,\n ]);\n\n // Log agent request if observability is enabled\n if (this.observability?.enabled && publicApiKey) {\n try {\n const requestData: LLMRequestData = {\n threadId,\n runId: undefined,\n model: forwardedParameters?.model,\n messages,\n actions: allAvailableActions,\n forwardedParameters,\n timestamp: requestStartTime,\n provider: \"agent\",\n agentName, // Add agent-specific context\n nodeName,\n };\n\n await this.observability.hooks.handleRequest(requestData);\n } catch (error) {\n console.error(\"Error logging agent request:\", error);\n }\n }\n\n await this.onBeforeRequest?.({\n threadId,\n runId: undefined,\n inputMessages: messages,\n properties: graphqlContext.properties,\n });\n\n try {\n const eventSource = new RuntimeEventSource({\n errorHandler: async (error, context) => {\n await this.error(\"error\", context, error, publicApiKey);\n },\n errorContext: {\n threadId,\n source: \"agent\",\n request: {\n operation: \"processAgentRequest\",\n method: \"POST\",\n startTime: requestStartTime,\n },\n agent: {\n name: agentName,\n nodeName: nodeName,\n },\n technical: {\n environment: process.env.NODE_ENV,\n },\n },\n });\n const stream = await currentAgent.remoteAgentHandler({\n name: agentName,\n threadId,\n nodeName,\n metaEvents,\n actionInputsWithoutAgents: allAvailableActions,\n });\n\n // Add progressive observability if enabled\n if (this.observability?.enabled && this.observability.progressive && publicApiKey) {\n // Wrap the stream function to intercept events for observability without changing core logic\n const originalStream = eventSource.stream.bind(eventSource);\n\n eventSource.stream = async (callback) => {\n await originalStream(async (eventStream$) => {\n // Create subscription to capture streaming events\n eventStream$.subscribe({\n next: (event) => {\n // Only log content chunks\n if (event.type === RuntimeEventTypes.TextMessageContent) {\n // Store the chunk\n streamedChunks.push(event.content);\n\n // Log each chunk separately for progressive mode\n try {\n const progressiveData: LLMResponseData = {\n threadId: threadId || \"\",\n runId: undefined,\n model: forwardedParameters?.model,\n output: event.content,\n latency: Date.now() - requestStartTime,\n timestamp: Date.now(),\n provider: \"agent\",\n isProgressiveChunk: true,\n agentName,\n nodeName,\n };\n\n // Use Promise to handle async logger without awaiting\n Promise.resolve()\n .then(() => {\n this.observability.hooks.handleResponse(progressiveData);\n })\n .catch((error) => {\n console.error(\"Error in progressive agent logging:\", error);\n });\n } catch (error) {\n console.error(\"Error preparing progressive agent log data:\", error);\n }\n }\n },\n });\n\n // Call the original callback with the event stream\n await callback(eventStream$);\n });\n };\n }\n\n eventSource.stream(async (eventStream$) => {\n from(stream).subscribe({\n next: (event) => eventStream$.next(event),\n error: async (err) => {\n // Log error with observability if enabled\n if (this.observability?.enabled && publicApiKey) {\n try {\n const errorData: LLMErrorData = {\n threadId,\n runId: undefined,\n model: forwardedParameters?.model,\n error: err instanceof Error ? err : String(err),\n timestamp: Date.now(),\n latency: Date.now() - requestStartTime,\n provider: \"agent\",\n agentName,\n nodeName,\n };\n\n this.observability.hooks.handleError(errorData);\n } catch (logError) {\n console.error(\"Error logging agent error:\", logError);\n }\n }\n\n // Preserve structured CopilotKit errors, only convert unstructured errors\n const structuredError = ensureStructuredError(err, (error) =>\n this.convertStreamingErrorToStructured(error),\n );\n\n // Track streaming errors\n await this.error(\n \"error\",\n {\n threadId,\n source: \"agent\",\n request: {\n operation: \"processAgentRequest\",\n method: \"POST\",\n startTime: requestStartTime,\n },\n response: {\n endTime: Date.now(),\n latency: Date.now() - requestStartTime,\n },\n agent: {\n name: agentName,\n nodeName: nodeName,\n },\n technical: {\n environment: process.env.NODE_ENV,\n stackTrace: err instanceof Error ? err.stack : undefined,\n },\n },\n structuredError,\n publicApiKey,\n );\n\n eventStream$.error(structuredError);\n eventStream$.complete();\n },\n complete: () => eventStream$.complete(),\n });\n });\n\n // Log final agent response when outputs are available\n if (this.observability?.enabled && publicApiKey) {\n outputMessagesPromise\n .then((outputMessages) => {\n const responseData: LLMResponseData = {\n threadId,\n runId: undefined,\n model: forwardedParameters?.model,\n // Use collected chunks for progressive mode or outputMessages for regular mode\n output: this.observability.progressive ? streamedChunks : outputMessages,\n latency: Date.now() - requestStartTime,\n timestamp: Date.now(),\n provider: \"agent\",\n isFinalResponse: true,\n agentName,\n nodeName,\n };\n\n try {\n this.observability.hooks.handleResponse(responseData);\n } catch (logError) {\n console.error(\"Error logging agent response:\", logError);\n }\n })\n .catch((error) => {\n console.error(\"Failed to get output messages for agent logging:\", error);\n });\n }\n\n outputMessagesPromise\n .then((outputMessages) => {\n this.onAfterRequest?.({\n threadId,\n runId: undefined,\n inputMessages: messages,\n outputMessages,\n properties: graphqlContext.properties,\n });\n })\n .catch((_error) => {});\n\n return {\n threadId,\n runId: undefined,\n eventSource,\n serverSideActions,\n actionInputsWithoutAgents: allAvailableActions,\n };\n } catch (error) {\n // Log error with observability if enabled\n if (this.observability?.enabled && publicApiKey) {\n try {\n const errorData: LLMErrorData = {\n threadId,\n runId: undefined,\n model: forwardedParameters?.model,\n error: error instanceof Error ? error : String(error),\n timestamp: Date.now(),\n latency: Date.now() - requestStartTime,\n provider: \"agent\",\n agentName,\n nodeName,\n };\n\n await this.observability.hooks.handleError(errorData);\n } catch (logError) {\n console.error(\"Error logging agent error:\", logError);\n }\n }\n\n // Ensure error is structured\n const structuredError = ensureStructuredError(error, (err) =>\n this.convertStreamingErrorToStructured(err),\n );\n\n // Track the agent error\n await this.error(\n \"error\",\n {\n threadId,\n source: \"agent\",\n request: {\n operation: \"processAgentRequest\",\n method: \"POST\",\n startTime: requestStartTime,\n },\n response: {\n endTime: Date.now(),\n latency: Date.now() - requestStartTime,\n },\n agent: {\n name: agentName,\n nodeName: nodeName,\n },\n technical: {\n environment: process.env.NODE_ENV,\n stackTrace: error instanceof Error ? error.stack : undefined,\n },\n },\n structuredError,\n publicApiKey,\n );\n\n console.error(\"Error getting response:\", error);\n throw structuredError;\n }\n }\n\n private async getServerSideActions(request: CopilotRuntimeRequest): Promise<Action<any>[]> {\n const { graphqlContext, messages: rawMessages, agentStates, url } = request;\n\n // --- Standard Action Fetching (unchanged) ---\n const inputMessages = convertGqlInputToMessages(rawMessages);\n const langserveFunctions: Action<any>[] = [];\n for (const chainPromise of this.langserve) {\n try {\n const chain = await chainPromise;\n langserveFunctions.push(chain);\n } catch (error) {\n console.error(\"Error loading langserve chain:\", error);\n }\n }\n\n const remoteEndpointDefinitions = this.remoteEndpointDefinitions.map(\n (endpoint) => ({ ...endpoint, type: resolveEndpointType(endpoint) }) as EndpointDefinition,\n );\n\n const remoteActions = await setupRemoteActions({\n remoteEndpointDefinitions,\n graphqlContext,\n messages: inputMessages,\n agentStates,\n frontendUrl: url,\n agents: this.agents,\n metaEvents: request.metaEvents,\n nodeName: request.agentSession?.nodeName,\n context: request.context,\n });\n\n const configuredActions =\n typeof this.actions === \"function\"\n ? this.actions({ properties: graphqlContext.properties, url })\n : this.actions;\n // --- Standard Action Fetching (unchanged) ---\n\n // +++ Dynamic MCP Action Fetching +++\n const requestSpecificMCPActions: Action<any>[] = [];\n if (this.createMCPClientImpl) {\n // 1. Determine effective MCP endpoints for this request\n const baseEndpoints = this.mcpServersConfig || [];\n // Assuming frontend passes config via properties.mcpServers\n const requestEndpoints = (graphqlContext.properties?.mcpServers ||\n graphqlContext.properties?.mcpEndpoints ||\n []) as MCPEndpointConfig[];\n\n // Merge and deduplicate endpoints based on URL\n const effectiveEndpointsMap = new Map<string, MCPEndpointConfig>();\n\n // First add base endpoints (from runtime configuration)\n [...baseEndpoints].forEach((ep) => {\n if (ep && ep.endpoint) {\n effectiveEndpointsMap.set(ep.endpoint, ep);\n }\n });\n\n // Then add request endpoints (from frontend), which will override duplicates\n [...requestEndpoints].forEach((ep) => {\n if (ep && ep.endpoint) {\n effectiveEndpointsMap.set(ep.endpoint, ep);\n }\n });\n\n const effectiveEndpoints = Array.from(effectiveEndpointsMap.values());\n\n // 2. Fetch/Cache actions for effective endpoints\n for (const config of effectiveEndpoints) {\n const endpointUrl = config.endpoint;\n let actionsForEndpoint: Action<any>[] | undefined = this.mcpActionCache.get(endpointUrl);\n\n if (!actionsForEndpoint) {\n // Not cached, fetch now\n let client: MCPClient | null = null;\n try {\n client = await this.createMCPClientImpl(config);\n const tools = await client.tools();\n actionsForEndpoint = convertMCPToolsToActions(tools, endpointUrl);\n this.mcpActionCache.set(endpointUrl, actionsForEndpoint); // Store in cache\n } catch (error) {\n console.error(\n `MCP: Failed to fetch tools from endpoint ${endpointUrl}. Skipping. Error:`,\n error,\n );\n actionsForEndpoint = []; // Assign empty array on error to prevent re-fetching constantly\n this.mcpActionCache.set(endpointUrl, actionsForEndpoint); // Cache the failure (empty array)\n }\n }\n requestSpecificMCPActions.push(...(actionsForEndpoint || []));\n }\n }\n // --- Dynamic MCP Action Fetching ---\n\n // Combine all action sources, including the dynamically fetched MCP actions\n return [\n ...configuredActions,\n ...langserveFunctions,\n ...remoteActions,\n ...requestSpecificMCPActions,\n ];\n }\n\n // Add helper method to detect provider\n private detectProvider(serviceAdapter: CopilotServiceAdapter): string | undefined {\n const adapterName = serviceAdapter.constructor.name;\n if (adapterName.includes(\"OpenAI\")) return \"openai\";\n if (adapterName.includes(\"Anthropic\")) return \"anthropic\";\n if (adapterName.includes(\"Google\")) return \"google\";\n if (adapterName.includes(\"Groq\")) return \"groq\";\n if (adapterName.includes(\"LangChain\")) return \"langchain\";\n return undefined;\n }\n\n private convertStreamingErrorToStructured(error: any): CopilotKitError {\n // Determine a more helpful error message based on context\n let helpfulMessage = generateHelpfulErrorMessage(error, \"agent streaming connection\");\n\n // For network-related errors, use CopilotKitLowLevelError to preserve the original error\n if (\n error?.message?.includes(\"fetch failed\") ||\n error?.message?.includes(\"ECONNREFUSED\") ||\n error?.message?.includes(\"ENOTFOUND\") ||\n error?.message?.includes(\"ETIMEDOUT\") ||\n error?.message?.includes(\"terminated\") ||\n error?.cause?.code === \"UND_ERR_SOCKET\" ||\n error?.message?.includes(\"other side closed\") ||\n error?.code === \"UND_ERR_SOCKET\"\n ) {\n return new CopilotKitLowLevelError({\n error: error instanceof Error ? error : new Error(String(error)),\n url: \"agent streaming connection\",\n message: helpfulMessage,\n });\n }\n\n // For all other errors, preserve the raw error in a basic CopilotKitError\n return new CopilotKitError({\n message: helpfulMessage,\n code: CopilotKitErrorCode.UNKNOWN,\n });\n }\n\n private async error(\n type: CopilotErrorEvent[\"type\"],\n context: CopilotRequestContext,\n error?: any,\n publicApiKey?: string,\n ): Promise<void> {\n if (!this.onError) return;\n\n // Just check if publicApiKey is defined (regardless of validity)\n if (!publicApiKey) {\n if (!this.hasWarnedAboutError) {\n console.warn(\n \"CopilotKit: onError handler provided but requires publicApiKey to be defined for error handling to work.\",\n );\n this.hasWarnedAboutError = true;\n }\n return;\n }\n\n try {\n const errorEvent: CopilotErrorEvent = {\n type,\n timestamp: Date.now(),\n context,\n ...(error && { error }),\n };\n\n await this.onError(errorEvent);\n } catch (errorHandlerError) {\n // Don't let error handler errors break the main flow\n console.error(\"Error in onError handler:\", errorHandlerError);\n }\n }\n\n /**\n * Public method to handle GraphQL validation errors\n * This allows the GraphQL resolver to send validation errors through the error system\n */\n public async errorGraphQLError(\n error: { message: string; code: string; type: string },\n context: {\n operation: string;\n cloudConfigPresent: boolean;\n guardrailsEnabled: boolean;\n },\n ): Promise<void> {\n if (!this.onError) return;\n\n try {\n await this.onError({\n type: \"error\",\n timestamp: Date.now(),\n context: {\n source: \"runtime\",\n request: {\n operation: context.operation,\n startTime: Date.now(),\n },\n technical: {\n environment: process.env.NODE_ENV,\n },\n metadata: {\n errorType: \"GraphQLValidationError\",\n cloudConfigPresent: context.cloudConfigPresent,\n guardrailsEnabled: context.guardrailsEnabled,\n },\n },\n error,\n });\n } catch (errorHandlerError) {\n // Don't let error handler errors break the main flow\n console.error(\"Error in onError handler:\", errorHandlerError);\n }\n }\n}\n\nexport function flattenToolCallsNoDuplicates(toolsByPriority: ActionInput[]): ActionInput[] {\n let allTools: ActionInput[] = [];\n const allToolNames: string[] = [];\n for (const tool of toolsByPriority) {\n if (!allToolNames.includes(tool.name)) {\n allTools.push(tool);\n allToolNames.push(tool.name);\n }\n }\n return allTools;\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(config: Omit<CopilotKitEndpoint, \"type\">): 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","import { ActionExecutionMessage, ResultMessage, TextMessage } from \"../../graphql/types/converted\";\n\nexport enum LangGraphEventTypes {\n OnChainStart = \"on_chain_start\",\n OnChainStream = \"on_chain_stream\",\n OnChainEnd = \"on_chain_end\",\n OnChatModelStart = \"on_chat_model_start\",\n OnChatModelStream = \"on_chat_model_stream\",\n OnChatModelEnd = \"on_chat_model_end\",\n OnToolStart = \"on_tool_start\",\n OnToolEnd = \"on_tool_end\",\n OnCopilotKitStateSync = \"on_copilotkit_state_sync\",\n OnCopilotKitEmitMessage = \"on_copilotkit_emit_message\",\n OnCopilotKitEmitToolCall = \"on_copilotkit_emit_tool_call\",\n OnCustomEvent = \"on_custom_event\",\n OnInterrupt = \"on_interrupt\",\n OnCopilotKitInterrupt = \"on_copilotkit_interrupt\",\n OnCopilotKitError = \"on_copilotkit_error\",\n}\n\nexport enum MetaEventNames {\n LangGraphInterruptEvent = \"LangGraphInterruptEvent\",\n CopilotKitLangGraphInterruptEvent = \"CopilotKitLangGraphInterruptEvent\",\n}\n\nexport enum CustomEventNames {\n CopilotKitManuallyEmitMessage = \"copilotkit_manually_emit_message\",\n CopilotKitManuallyEmitToolCall = \"copilotkit_manually_emit_tool_call\",\n CopilotKitManuallyEmitIntermediateState = \"copilotkit_manually_emit_intermediate_state\",\n CopilotKitExit = \"copilotkit_exit\",\n}\n\ntype LangGraphOnCopilotKitStateSyncEvent = {\n event: LangGraphEventTypes.OnCopilotKitStateSync;\n thread_id: string;\n agent_name: string;\n node_name: string;\n run_id: string;\n active: boolean;\n role: string;\n state: any;\n running: boolean;\n};\n\ntype LangGraphOnChainStartEvent = {\n event: LangGraphEventTypes.OnChainStart;\n run_id: string;\n name: string;\n tags: string[];\n metadata: { thread_id: string };\n data: {\n input: any;\n };\n parent_ids: string[];\n};\n\ntype LangGraphOnChainEndEvent = {\n event: LangGraphEventTypes.OnChainEnd;\n name: string;\n run_id: string;\n tags: string[];\n metadata: {\n thread_id: string;\n langgraph_step: number;\n langgraph_node: string;\n langgraph_triggers: string[];\n langgraph_task_idx: number;\n thread_ts: string;\n };\n data: {\n input: any;\n output: any;\n };\n parent_ids: string[];\n};\n\ntype LangGraphOnChatModelStartEvent = {\n event: LangGraphEventTypes.OnChatModelStart;\n name: string;\n run_id: string;\n tags: string[];\n metadata: {\n thread_id: string;\n langgraph_step: number;\n langgraph_node: string;\n langgraph_triggers: string[];\n langgraph_task_idx: number;\n thread_ts: string;\n ls_provider: string;\n ls_model_name: string;\n ls_model_type: string;\n ls_temperature: number;\n };\n data: {\n input: {\n messages: {\n lc: number;\n type: string;\n id: string[];\n kwargs: {\n content: string;\n type: string;\n id: string;\n };\n }[][];\n };\n };\n parent_ids: string[];\n};\n\ntype LangGraphOnChatModelStreamEvent = {\n event: LangGraphEventTypes.OnChatModelStream;\n name: string;\n run_id: string;\n tags: string[];\n metadata: {\n thread_id: string;\n langgraph_step: number;\n langgraph_node: string;\n langgraph_triggers: string[];\n langgraph_task_idx: number;\n thread_ts: string;\n ls_provider: string;\n ls_model_name: string;\n ls_model_type: string;\n ls_temperature: number;\n };\n data: {\n chunk: {\n lc: number;\n type: string;\n id: string;\n kwargs: {\n content: string | { text: string; type: string; index: number }[];\n additional_kwargs: {\n tool_calls: {\n index: number;\n id: string;\n function: { arguments: string; name: string };\n type: string;\n }[];\n };\n type: string;\n id: string;\n tool_calls: { name: string; args: {}; id: string; type: string }[];\n tool_call_chunks: {\n name: string;\n args: string;\n id: string;\n index: number;\n type: string;\n }[];\n invalid_tool_calls: any[];\n };\n };\n };\n parent_ids: string[];\n};\n\ntype LangGraphOnChatModelEndEvent = {\n event: LangGraphEventTypes.OnChatModelEnd;\n name: string;\n run_id: string;\n tags: string[];\n metadata: {\n thread_id: string;\n langgraph_step: number;\n langgraph_node: string;\n langgraph_triggers: string[];\n langgraph_task_idx: number;\n thread_ts: string;\n ls_provider: string;\n ls_model_name: string;\n ls_model_type: string;\n ls_temperature: number;\n };\n data: {\n input: any;\n output: {\n generations: {\n text: string;\n generation_info: {\n finish_reason: string;\n model_name: string;\n system_fingerprint: string;\n };\n type: string;\n message: {\n lc: number;\n type: string;\n id: string[];\n kwargs: {\n content: string;\n additional_kwargs: {\n tool_calls: {\n index: number;\n id: string;\n function: { arguments: string; name: string };\n type: string;\n }[];\n };\n response_metadata: {\n finish_reason: string;\n model_name: string;\n system_fingerprint: string;\n };\n type: string;\n id: string;\n tool_calls: { name: string; args: { query: string }; id: string; type: string }[];\n invalid_tool_calls: any[];\n };\n };\n }[][];\n llm_output: any;\n run: any;\n };\n };\n parent_ids: string[];\n};\n\ntype LangGraphOnChainStreamEvent = {\n event: LangGraphEventTypes.OnChainStream;\n name: string;\n run_id: string;\n tags: string[];\n metadata: {\n thread_id: string;\n langgraph_step?: number;\n langgraph_node?: string;\n langgraph_triggers?: string[];\n langgraph_task_idx?: number;\n thread_ts?: string;\n };\n data: {\n chunk: {\n messages: {\n lc: number;\n type: string;\n id: string[];\n kwargs: {\n content: string;\n additional_kwargs?: {\n tool_calls?: {\n index: number;\n id: string;\n function: { arguments: string; name: string };\n type: string;\n }[];\n };\n response_metadata?: {\n finish_reason: string;\n model_name: string;\n system_fingerprint: string;\n };\n type: string;\n id: string;\n tool_calls?: { name: string; args: { query: string }; id: string; type: string }[];\n invalid_tool_calls?: any[];\n };\n }[];\n };\n };\n parent_ids: string[];\n};\n\ntype LangGraphOnToolStartEvent = {\n event: LangGraphEventTypes.OnToolStart;\n name: string;\n run_id: string;\n tags: string[];\n metadata: {\n thread_id: string;\n langgraph_step: number;\n langgraph_node: string;\n langgraph_triggers: string[];\n langgraph_task_idx: number;\n thread_ts: string;\n };\n data: {\n input: {\n query: string;\n };\n };\n parent_ids: string[];\n};\n\ntype LangGraphOnToolEndEvent = {\n event: LangGraphEventTypes.OnToolEnd;\n name: string;\n run_id: string;\n tags: string[];\n metadata: {\n thread_id: string;\n langgraph_step: number;\n langgraph_node: string;\n langgraph_triggers: string[];\n langgraph_task_idx: number;\n thread_ts: string;\n };\n data: {\n input: {\n query: string;\n };\n output: {\n lc: number;\n type: string;\n id: string[];\n kwargs: {\n content: string[];\n type: string;\n name: string;\n tool_call_id: string;\n status: string;\n };\n };\n };\n parent_ids: string[];\n};\n\ntype LangGraphOnCustomEvent = {\n event: LangGraphEventTypes.OnCustomEvent;\n run_id: string;\n name: string;\n tags: string[];\n metadata: {\n thread_id: string;\n langgraph_step: number;\n langgraph_node: string;\n langgraph_triggers: string[];\n langgraph_path: [string, string];\n langgraph_checkpoint_ns: string;\n checkpoint_ns: string;\n };\n data: any;\n parent_ids: string[];\n};\n\ninterface LangGraphInterruptEvent {\n event: LangGraphEventTypes.OnInterrupt;\n value: string;\n}\n\ninterface CopilotKitLangGraphInterruptEvent {\n event: LangGraphEventTypes.OnCopilotKitInterrupt;\n data: { value: string; messages: (TextMessage | ActionExecutionMessage | ResultMessage)[] };\n}\n\ninterface CopilotKitLangGraphErrorEvent {\n event: LangGraphEventTypes.OnCopilotKitError;\n data: {\n error: {\n message: string;\n type: string;\n agent_name: string;\n status_code?: number;\n response_data?: any;\n };\n thread_id: string;\n agent_name: string;\n node_name: string;\n };\n}\n\nexport type LangGraphEvent =\n | LangGraphOnChainStartEvent\n | LangGraphOnChainStreamEvent\n | LangGraphOnChainEndEvent\n | LangGraphOnChatModelStartEvent\n | LangGraphOnChatModelStreamEvent\n | LangGraphOnChatModelEndEvent\n | LangGraphOnToolStartEvent\n | LangGraphOnToolEndEvent\n | LangGraphOnCopilotKitStateSyncEvent\n | LangGraphOnCustomEvent\n | LangGraphInterruptEvent\n | CopilotKitLangGraphInterruptEvent\n | CopilotKitLangGraphErrorEvent;\n","import {\n FailedResponseStatus,\n FailedResponseStatusReason,\n} from \"../graphql/types/response-status.type\";\n\nexport class GuardrailsValidationFailureResponse extends FailedResponseStatus {\n reason = FailedResponseStatusReason.GUARDRAILS_VALIDATION_FAILED;\n declare details: {\n guardrailsReason: string;\n };\n\n constructor({ guardrailsReason }) {\n super();\n this.details = {\n guardrailsReason,\n };\n }\n}\n\nexport class MessageStreamInterruptedResponse extends FailedResponseStatus {\n reason = FailedResponseStatusReason.MESSAGE_STREAM_INTERRUPTED;\n declare details: {\n messageId: string;\n description: string;\n };\n\n constructor({ messageId }: { messageId: string }) {\n super();\n this.details = {\n messageId,\n description: \"Check the message for mode details\",\n };\n }\n}\n\nexport class UnknownErrorResponse extends FailedResponseStatus {\n reason = FailedResponseStatusReason.UNKNOWN_ERROR;\n declare details: {\n description?: string;\n originalError?: {\n code?: string;\n statusCode?: number;\n severity?: string;\n visibility?: string;\n originalErrorType?: string;\n extensions?: any;\n };\n };\n\n constructor({\n description,\n originalError,\n }: {\n description?: string;\n originalError?: {\n code?: string;\n statusCode?: number;\n severity?: string;\n visibility?: string;\n originalErrorType?: string;\n extensions?: any;\n };\n }) {\n super();\n this.details = {\n description,\n originalError,\n };\n }\n}\n","import { Field, ObjectType } from \"type-graphql\";\n\n@ObjectType()\nexport class Agent {\n @Field(() => String)\n id: string;\n\n @Field(() => String)\n name: string;\n\n @Field(() => String)\n description?: string;\n}\n\n@ObjectType()\nexport class AgentsResponse {\n @Field(() => [Agent])\n agents: Agent[];\n}\n","import createPinoLogger from \"pino\";\nimport pretty from \"pino-pretty\";\n\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nexport type CopilotRuntimeLogger = ReturnType<typeof createLogger>;\n\nexport function createLogger(options?: { level?: LogLevel; component?: string }) {\n const { level, component } = options || {};\n const stream = pretty({ colorize: true });\n\n const logger = createPinoLogger(\n {\n level: process.env.LOG_LEVEL || level || \"error\",\n redact: {\n paths: [\"pid\", \"hostname\"],\n remove: true,\n },\n },\n stream,\n );\n\n if (component) {\n return logger.child({ component });\n } else {\n return logger;\n }\n}\n","import { Arg, Resolver } from \"type-graphql\";\nimport { Ctx } from \"type-graphql\";\nimport { Query } from \"type-graphql\";\nimport { LoadAgentStateResponse } from \"../types/load-agent-state-response.type\";\nimport type { GraphQLContext } from \"../../lib/integrations\";\nimport { LoadAgentStateInput } from \"../inputs/load-agent-state.input\";\nimport { CopilotKitAgentDiscoveryError } from \"@copilotkit/shared\";\n\n@Resolver(() => LoadAgentStateResponse)\nexport class StateResolver {\n @Query(() => LoadAgentStateResponse)\n async loadAgentState(@Ctx() ctx: GraphQLContext, @Arg(\"data\") data: LoadAgentStateInput) {\n const agents = await ctx._copilotkit.runtime.getAllAgents(ctx);\n const hasAgent = agents.some((agent) => agent.name === data.agentName);\n if (!hasAgent) {\n throw new CopilotKitAgentDiscoveryError({\n agentName: data.agentName,\n availableAgents: agents.map((a) => ({ name: a.name, id: a.name })),\n });\n }\n\n const state = await ctx._copilotkit.runtime.loadAgentState(ctx, data.threadId, data.agentName);\n\n return state;\n }\n}\n","import { Field, ObjectType } from \"type-graphql\";\nimport { BaseMessageOutput } from \"./copilot-response.type\";\n\n@ObjectType()\nexport class LoadAgentStateResponse {\n @Field(() => String)\n threadId: string;\n\n @Field(() => Boolean)\n threadExists: boolean;\n\n @Field(() => String)\n state: string;\n\n @Field(() => String)\n messages: string;\n}\n","import { Field, InputType } from \"type-graphql\";\n\n@InputType()\nexport class LoadAgentStateInput {\n @Field(() => String)\n threadId: string;\n\n @Field(() => String)\n agentName: string;\n}\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pC,eAAOA;MACT;IACF;EACF;AACF;AAzEgB9B;;;ADnFT,SAASwC,+BAA+BC,SAA0C;AAJzF;AAKE,QAAMC,eAAeC,gBAAgBF,OAAAA;AAErCG,2BAAUC,oBAAoB;IAC5BC,SAAS;MACPC,WAAW;IACb;EACF,CAAA;AAEA,OAAIN,aAAQO,eAARP,mBAAoBQ,aAAa;AACnCL,6BAAUC,oBAAoB;MAC5BI,aAAaR,QAAQO,WAAWC;IAClC,CAAA;EACF;AAEAL,2BAAUM,QAAQ,gCAAgCC,gCAAgCV,OAAAA,CAAAA;AAElF,QAAMW,UAASV,aAAaW;AAC5BD,EAAAA,QAAOE,MAAM,6BAAA;AAEb,QAAMC,WAAOC,iCAAW;IACtB,GAAGd;IACHe,iBAAiBhB,QAAQiB;EAC3B,CAAA;AAEA,SAAOH;AACT;AA1BgBf;;;ADAT,SAASmB,2BAA2BC,SAA0C;AACnFC,2BAAUC,oBAAoB;IAC5BC,SAAS;MACPC,WAAW;IACb;EACF,CAAA;AAEAH,2BAAUI,QAAQ,gCAAgCC,gCAAgCN,OAAAA,CAAAA;AAClF,SAAOO,+BAA+BP,OAAAA;AACxC;AATgBD;","names":["module","import_graphql_yoga","import_type_graphql","import_type_graphql","import_rxjs","import_type_graphql","import_type_graphql","MessageRole","CopilotRequestType","ActionInputAvailability","registerEnumType","name","description","import_type_graphql","BaseMessageInput","id","createdAt","Field","String","Date","InputType","MessageInput","BaseMessageInput","textMessage","actionExecutionMessage","resultMessage","agentStateMessage","imageMessage","Field","TextMessageInput","nullable","ActionExecutionMessageInput","ResultMessageInput","AgentStateMessageInput","ImageMessageInput","InputType","content","parentMessageId","role","String","MessageRole","name","arguments","scope","deprecationReason","actionExecutionId","actionName","result","threadId","agentName","state","running","nodeName","runId","active","Boolean","format","bytes","import_type_graphql","import_type_graphql","ActionInput","name","description","jsonSchema","available","Field","String","ActionInputAvailability","nullable","InputType","FrontendInput","toDeprecate_fullContext","actions","url","Field","String","nullable","ActionInput","InputType","import_type_graphql","import_type_graphql","GuardrailsRuleInput","allowList","denyList","Field","String","nullable","InputType","GuardrailsInput","inputValidationRules","CloudInput","guardrails","Field","GuardrailsInput","nullable","InputType","import_type_graphql","ForwardedParametersInput","model","maxTokens","stop","toolChoice","toolChoiceFunctionName","temperature","Field","String","nullable","Number","InputType","import_type_graphql","AgentSessionInput","agentName","threadId","nodeName","Field","String","nullable","InputType","import_type_graphql","AgentStateInput","agentName","state","config","Field","String","nullable","InputType","import_type_graphql","ExtensionsInput","openaiAssistantAPI","Field","OpenAIApiAssistantAPIInput","nullable","InputType","runId","threadId","String","import_type_graphql","import_type_graphql","import_type_graphql","import_type_graphql","MessageStatusCode","registerEnumType","name","BaseMessageStatus","code","Field","ObjectType","PendingMessageStatus","SuccessMessageStatus","FailedMessageStatus","reason","String","MessageStatusUnion","createUnionType","types","import_type_graphql","ResponseStatusCode","registerEnumType","name","BaseResponseStatus","code","Field","InterfaceType","resolveType","value","SuccessResponseStatus","FailedResponseStatus","PendingResponseStatus","undefined","ObjectType","implements","FailedResponseStatusReason","reason","details","GraphQLJSON","nullable","ResponseStatusUnion","createUnionType","types","import_type_graphql","ExtensionsResponse","openaiAssistantAPI","Field","OpenAIApiAssistantAPIResponse","nullable","ObjectType","runId","threadId","String","BaseMessageOutput","id","createdAt","status","Field","String","Date","MessageStatusUnion","InterfaceType","resolveType","value","hasOwnProperty","TextMessageOutput","ActionExecutionMessageOutput","ResultMessageOutput","AgentStateMessageOutput","ImageMessageOutput","undefined","role","content","parentMessageId","MessageRole","nullable","ObjectType","implements","name","scope","arguments","deprecationReason","actionExecutionId","actionName","result","threadId","agentName","nodeName","runId","active","state","running","Boolean","format","bytes","CopilotResponse","messages","extensions","metaEvents","ResponseStatusUnion","ExtensionsResponse","BaseMetaEvent","MetaEventName","registerEnumType","name","description","BaseMetaEvent","type","Field","String","InterfaceType","resolveType","value","LangGraphInterruptEvent","CopilotKitLangGraphInterruptEvent","undefined","CopilotKitLangGraphInterruptEventData","messages","BaseMessageOutput","ObjectType","response","nullable","implements","data","MetaEventInput","name","value","response","messages","Field","MetaEventName","String","nullable","MessageInput","InputType","import_type_graphql","CopilotContextInput","description","value","Field","String","InputType","GenerateCopilotResponseMetadataInput","requestType","Field","CopilotRequestType","nullable","InputType","GenerateCopilotResponseInput","metadata","threadId","runId","messages","frontend","cloud","forwardedParameters","agentSession","agentState","agentStates","extensions","metaEvents","context","String","MessageInput","FrontendInput","CloudInput","ForwardedParametersInput","AgentSessionInput","AgentStateInput","ExtensionsInput","MetaEventInput","CopilotContextInput","import_shared","import_rxjs","Message","BaseMessageInput","type","isTextMessage","isActionExecutionMessage","isResultMessage","isAgentStateMessage","isImageMessage","TextMessage","content","role","parentMessageId","ActionExecutionMessage","name","arguments","ResultMessage","actionExecutionId","actionName","result","encodeResult","error","errorObj","code","message","Error","undefined","JSON","stringify","decodeResult","parsed","parse","e","hasError","getError","AgentStateMessage","threadId","agentName","nodeName","runId","active","state","running","import_shared","import_shared","LangGraphEventTypes","MetaEventNames","CustomEventNames","resolveEndpointType","endpoint","type","EndpointType","LangGraphPlatform","CopilotKit","packageJson","require","telemetryClient","TelemetryClient","packageName","name","packageVersion","version","getRuntimeInstanceTelemetryInfo","options","runtime","endpointsInfo","remoteEndpointDefinitions","reduce","acc","endpoint","info","endpointType","resolveEndpointType","endpointTypes","includes","EndpointType","LangGraphPlatform","ep","agentsAmount","agents","length","hashedKey","langsmithApiKey","createHash","update","digest","publicApiKey","cloud","apiKeyProvided","trim","actionsAmount","actions","endpointsAmount","hashedLgcKey","baseUrl","import_shared","EndpointType","RuntimeEventTypes","RuntimeMetaEventName","import_graphql_scalars","import_class_transformer","GuardrailsValidationFailureResponse","FailedResponseStatus","reason","FailedResponseStatusReason","GUARDRAILS_VALIDATION_FAILED","constructor","guardrailsReason","details","MessageStreamInterruptedResponse","MESSAGE_STREAM_INTERRUPTED","messageId","description","UnknownErrorResponse","UNKNOWN_ERROR","originalError","import_shared","import_type_graphql","Agent","id","name","description","Field","String","ObjectType","AgentsResponse","agents","import_shared","invokeGuardrails","baseUrl","copilotCloudPublicApiKey","data","onResult","onError","messages","length","textMessage","role","MessageRole","user","filter","m","undefined","assistant","map","content","lastMessage","restOfMessages","slice","body","input","validTopics","cloud","guardrails","inputValidationRules","allowList","invalidTopics","denyList","guardrailsResult","fetch","method","headers","JSON","stringify","ok","resultJson","json","CopilotResolver","hello","availableAgents","ctx","logger","child","component","debug","agentsWithEndpoints","_copilotkit","runtime","discoverAgentsFromEndpoints","agents","endpoint","agentWithoutEndpoint","generateCopilotResponse","properties","telemetry","capture","requestType","metadata","request","get","copilotRuntime","serviceAdapter","copilotCloudBaseUrl","publicApiKeyFromHeaders","error","errorGraphQLError","message","code","type","operation","cloudConfigPresent","Boolean","guardrailsEnabled","GraphQLError","process","env","COPILOT_CLOUD_BASE_URL","responseStatus$","ReplaySubject","interruptStreaming$","guardrailsResult$","outputMessages","resolveOutputMessagesPromise","rejectOutputMessagesPromise","outputMessagesPromise","Promise","resolve","reject","runtimeResponse","processRuntimeRequest","actions","frontend","action","available","ActionInputAvailability","disabled","threadId","runId","publicApiKey","graphqlContext","forwardedParameters","agentSession","agentStates","url","extensions","metaEvents","context","isStructuredCopilotKitError","visibility","originalError","eventSource","randomId","serverSideActions","actionInputsWithoutAgents","eventStream","processRuntimeEvents","find","serverSideAction","name","pipe","shareReplay","finalize","response","status","firstValueFrom","Repeater","push","stop","eventStreamSubscription","subscribe","next","event","RuntimeEventTypes","MetaEvent","LangGraphEventTypes","OnInterrupt","plainToInstance","LangGraphInterruptEvent","RuntimeMetaEventName","value","CopilotKitLangGraphInterruptEvent","TextMessage","id","createdAt","Date","SuccessMessageStatus","ActionExecutionMessage","arguments","Error","err","includes","UnknownErrorResponse","description","unsubscribe","complete","SuccessResponseStatus","pushMessage","stopStreamingMessages","result","GuardrailsValidationFailureResponse","guardrailsReason","reason","TextMessageStart","textMessageContentStream","skipWhile","e","takeWhile","TextMessageEnd","messageId","TextMessageContent","streamingTextStatus","Subject","parentMessageId","pushTextChunk","stopStreamingText","textChunks","textSubscription","take","tap","FailedMessageStatus","MessageStreamInterruptedResponse","join","ActionExecutionStart","actionExecutionArgumentStream","ActionExecutionEnd","actionExecutionId","ActionExecutionArgs","streamingArgumentsStatus","actionName","pushArgumentsChunk","stopStreamingArguments","argumentChunks","actionExecutionArgumentSubscription","args","ActionExecutionResult","ResultMessage","AgentStateMessage","agentName","nodeName","active","state","running","CopilotKitError","CopilotKitLowLevelError","statusCode","severity","originalErrorType","Query","String","AgentsResponse","Ctx","Mutation","CopilotResponse","Arg","GraphQLJSONObject","nullable","Resolver","createLogger","options","level","component","stream","pretty","colorize","logger","createPinoLogger","process","env","LOG_LEVEL","redact","paths","remove","child","import_type_graphql","import_type_graphql","LoadAgentStateResponse","threadId","threadExists","state","messages","Field","String","Boolean","ObjectType","import_type_graphql","LoadAgentStateInput","threadId","agentName","Field","String","InputType","import_shared","StateResolver","loadAgentState","ctx","data","agents","_copilotkit","runtime","getAllAgents","hasAgent","some","agent","name","agentName","CopilotKitAgentDiscoveryError","availableAgents","map","a","id","state","threadId","Query","LoadAgentStateResponse","Ctx","Arg","Resolver","packageJson","import_shared","logger","createLogger","addCustomHeaderPlugin","onResponse","response","headers","set","version","createContext","initialContext","copilotKitContext","contextLogger","properties","debug","ctx","_copilotkit","buildSchema","options","schema","buildSchemaSync","resolvers","CopilotResolver","StateResolver","emitSchemaFile","getCommonConfig","logLevel","process","env","LOG_LEVEL","level","component","cloud","telemetry","setCloudConfiguration","publicApiKey","baseUrl","setGlobalProperties","runtime","serviceAdapter","constructor","name","userErrorCodes","CopilotKitErrorCode","AGENT_NOT_FOUND","API_NOT_FOUND","REMOTE_ENDPOINT_NOT_FOUND","CONFIGURATION_ERROR","MISSING_PUBLIC_API_KEY_ERROR","logging","plugins","useDeferStream","context","maskedErrors","maskError","error","message","isDev","originalError","extensions","errorCode","code","includes","console","CopilotKitError","copilotRuntimeNodeHttpEndpoint","options","commonConfig","getCommonConfig","telemetry","setGlobalProperties","runtime","framework","properties","_copilotkit","capture","getRuntimeInstanceTelemetryInfo","logger","logging","debug","yoga","createYoga","graphqlEndpoint","endpoint","copilotRuntimeNestEndpoint","options","telemetry","setGlobalProperties","runtime","framework","capture","getRuntimeInstanceTelemetryInfo","copilotRuntimeNodeHttpEndpoint"]}
@@ -0,0 +1,14 @@
1
+ import {
2
+ copilotRuntimeNestEndpoint
3
+ } from "../../../chunk-CB2OJXF6.mjs";
4
+ import "../../../chunk-A555KEAD.mjs";
5
+ import "../../../chunk-27JKTS6P.mjs";
6
+ import "../../../chunk-XWBDEXDA.mjs";
7
+ import "../../../chunk-AMUJQ6IR.mjs";
8
+ import "../../../chunk-SHBDMA63.mjs";
9
+ import "../../../chunk-2OZAGFV3.mjs";
10
+ import "../../../chunk-FHD4JECV.mjs";
11
+ export {
12
+ copilotRuntimeNestEndpoint
13
+ };
14
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -0,0 +1,15 @@
1
+ import * as graphql_yoga from 'graphql-yoga';
2
+ import { b as CreateCopilotRuntimeServerOptions, G as GraphQLContext } from '../../../shared-0a7346ce.js';
3
+ import 'graphql';
4
+ import 'pino';
5
+ import '@copilotkit/shared';
6
+ import '../../../langserve-0c6100e3.js';
7
+ import '../../../index-96b330da.js';
8
+ import '../../../graphql/types/base/index.js';
9
+ import 'rxjs';
10
+ import '../../cloud/index.js';
11
+ import '@ag-ui/client';
12
+
13
+ declare function copilotRuntimeNodeExpressEndpoint(options: CreateCopilotRuntimeServerOptions): graphql_yoga.YogaServerInstance<{}, Partial<GraphQLContext>>;
14
+
15
+ export { copilotRuntimeNodeExpressEndpoint };