@copilotkit/runtime 2.0.0-rc.49 → 2.0.0-rc.50

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 (170) hide show
  1. package/README.md +1 -1
  2. package/dist/index.cjs +8 -3
  3. package/dist/index.d.cts +9 -9
  4. package/dist/index.d.mts +9 -9
  5. package/dist/index.mjs +4 -3
  6. package/dist/node.cjs +2 -0
  7. package/dist/node.d.cts +3 -3
  8. package/dist/node.d.mts +3 -3
  9. package/dist/node.mjs +3 -3
  10. package/dist/runtime/core/channel-manager.cjs.map +1 -1
  11. package/dist/runtime/core/channel-manager.mjs.map +1 -1
  12. package/dist/runtime/core/debug-event-bus.cjs.map +1 -1
  13. package/dist/runtime/core/debug-event-bus.d.cts +2 -2
  14. package/dist/runtime/core/debug-event-bus.d.cts.map +1 -1
  15. package/dist/runtime/core/debug-event-bus.d.mts +2 -2
  16. package/dist/runtime/core/debug-event-bus.d.mts.map +1 -1
  17. package/dist/runtime/core/debug-event-bus.mjs.map +1 -1
  18. package/dist/runtime/core/fetch-cors.cjs.map +1 -1
  19. package/dist/runtime/core/fetch-cors.d.cts +2 -2
  20. package/dist/runtime/core/fetch-cors.d.cts.map +1 -1
  21. package/dist/runtime/core/fetch-cors.d.mts +2 -2
  22. package/dist/runtime/core/fetch-cors.d.mts.map +1 -1
  23. package/dist/runtime/core/fetch-cors.mjs.map +1 -1
  24. package/dist/runtime/core/fetch-handler.cjs +9 -1
  25. package/dist/runtime/core/fetch-handler.cjs.map +1 -1
  26. package/dist/runtime/core/fetch-handler.d.cts +27 -14
  27. package/dist/runtime/core/fetch-handler.d.cts.map +1 -1
  28. package/dist/runtime/core/fetch-handler.d.mts +27 -14
  29. package/dist/runtime/core/fetch-handler.d.mts.map +1 -1
  30. package/dist/runtime/core/fetch-handler.mjs +9 -2
  31. package/dist/runtime/core/fetch-handler.mjs.map +1 -1
  32. package/dist/runtime/core/hooks.cjs.map +1 -1
  33. package/dist/runtime/core/hooks.d.cts +5 -5
  34. package/dist/runtime/core/hooks.d.cts.map +1 -1
  35. package/dist/runtime/core/hooks.d.mts +5 -5
  36. package/dist/runtime/core/hooks.d.mts.map +1 -1
  37. package/dist/runtime/core/hooks.mjs.map +1 -1
  38. package/dist/runtime/core/learning.cjs.map +1 -1
  39. package/dist/runtime/core/learning.d.cts +8 -8
  40. package/dist/runtime/core/learning.d.cts.map +1 -1
  41. package/dist/runtime/core/learning.d.mts +8 -8
  42. package/dist/runtime/core/learning.d.mts.map +1 -1
  43. package/dist/runtime/core/learning.mjs.map +1 -1
  44. package/dist/runtime/core/logger.cjs.map +1 -1
  45. package/dist/runtime/core/logger.d.cts +3 -3
  46. package/dist/runtime/core/logger.d.cts.map +1 -1
  47. package/dist/runtime/core/logger.d.mts +3 -3
  48. package/dist/runtime/core/logger.d.mts.map +1 -1
  49. package/dist/runtime/core/logger.mjs.map +1 -1
  50. package/dist/runtime/core/middleware-sse-parser.cjs.map +1 -1
  51. package/dist/runtime/core/middleware-sse-parser.mjs.map +1 -1
  52. package/dist/runtime/core/middleware.cjs.map +1 -1
  53. package/dist/runtime/core/middleware.d.cts +3 -3
  54. package/dist/runtime/core/middleware.d.cts.map +1 -1
  55. package/dist/runtime/core/middleware.d.mts +3 -3
  56. package/dist/runtime/core/middleware.d.mts.map +1 -1
  57. package/dist/runtime/core/middleware.mjs.map +1 -1
  58. package/dist/runtime/core/package-info.cjs +1 -1
  59. package/dist/runtime/core/package-info.mjs +1 -1
  60. package/dist/runtime/core/runtime-error-reporter.cjs.map +1 -1
  61. package/dist/runtime/core/runtime-error-reporter.mjs.map +1 -1
  62. package/dist/runtime/core/runtime.cjs +17 -17
  63. package/dist/runtime/core/runtime.cjs.map +1 -1
  64. package/dist/runtime/core/runtime.d.cts +65 -65
  65. package/dist/runtime/core/runtime.d.cts.map +1 -1
  66. package/dist/runtime/core/runtime.d.mts +65 -65
  67. package/dist/runtime/core/runtime.d.mts.map +1 -1
  68. package/dist/runtime/core/runtime.mjs +15 -15
  69. package/dist/runtime/core/runtime.mjs.map +1 -1
  70. package/dist/runtime/endpoints/auto-start-channels.cjs.map +1 -1
  71. package/dist/runtime/endpoints/auto-start-channels.mjs.map +1 -1
  72. package/dist/runtime/endpoints/node-fetch-handler.cjs +9 -1
  73. package/dist/runtime/endpoints/node-fetch-handler.cjs.map +1 -1
  74. package/dist/runtime/endpoints/node-fetch-handler.d.cts +9 -4
  75. package/dist/runtime/endpoints/node-fetch-handler.d.cts.map +1 -1
  76. package/dist/runtime/endpoints/node-fetch-handler.d.mts +9 -4
  77. package/dist/runtime/endpoints/node-fetch-handler.d.mts.map +1 -1
  78. package/dist/runtime/endpoints/node-fetch-handler.mjs +9 -2
  79. package/dist/runtime/endpoints/node-fetch-handler.mjs.map +1 -1
  80. package/dist/runtime/endpoints/node.cjs +11 -3
  81. package/dist/runtime/endpoints/node.cjs.map +1 -1
  82. package/dist/runtime/endpoints/node.d.cts +39 -16
  83. package/dist/runtime/endpoints/node.d.cts.map +1 -1
  84. package/dist/runtime/endpoints/node.d.mts +39 -16
  85. package/dist/runtime/endpoints/node.d.mts.map +1 -1
  86. package/dist/runtime/endpoints/node.mjs +13 -6
  87. package/dist/runtime/endpoints/node.mjs.map +1 -1
  88. package/dist/runtime/generative-ui/a2ui-v09-middleware.cjs.map +1 -1
  89. package/dist/runtime/generative-ui/a2ui-v09-middleware.mjs.map +1 -1
  90. package/dist/runtime/handlers/get-runtime-info.cjs.map +1 -1
  91. package/dist/runtime/handlers/get-runtime-info.mjs.map +1 -1
  92. package/dist/runtime/handlers/handle-debug-events.cjs.map +1 -1
  93. package/dist/runtime/handlers/handle-debug-events.mjs.map +1 -1
  94. package/dist/runtime/handlers/handle-inspector-learning.cjs.map +1 -1
  95. package/dist/runtime/handlers/handle-inspector-learning.mjs.map +1 -1
  96. package/dist/runtime/handlers/handle-inspector-metadata.cjs.map +1 -1
  97. package/dist/runtime/handlers/handle-inspector-metadata.mjs.map +1 -1
  98. package/dist/runtime/handlers/handle-stop.cjs.map +1 -1
  99. package/dist/runtime/handlers/handle-stop.mjs.map +1 -1
  100. package/dist/runtime/handlers/handle-suggest.cjs.map +1 -1
  101. package/dist/runtime/handlers/handle-suggest.mjs.map +1 -1
  102. package/dist/runtime/handlers/handle-trajectory-connect.cjs.map +1 -1
  103. package/dist/runtime/handlers/handle-trajectory-connect.mjs.map +1 -1
  104. package/dist/runtime/handlers/handle-transcribe.cjs.map +1 -1
  105. package/dist/runtime/handlers/handle-transcribe.mjs.map +1 -1
  106. package/dist/runtime/handlers/intelligence/annotate.cjs +1 -1
  107. package/dist/runtime/handlers/intelligence/annotate.cjs.map +1 -1
  108. package/dist/runtime/handlers/intelligence/annotate.mjs +1 -1
  109. package/dist/runtime/handlers/intelligence/annotate.mjs.map +1 -1
  110. package/dist/runtime/handlers/intelligence/connect.cjs.map +1 -1
  111. package/dist/runtime/handlers/intelligence/connect.mjs.map +1 -1
  112. package/dist/runtime/handlers/intelligence/memories.cjs +1 -1
  113. package/dist/runtime/handlers/intelligence/memories.cjs.map +1 -1
  114. package/dist/runtime/handlers/intelligence/memories.mjs +1 -1
  115. package/dist/runtime/handlers/intelligence/memories.mjs.map +1 -1
  116. package/dist/runtime/handlers/intelligence/run.cjs.map +1 -1
  117. package/dist/runtime/handlers/intelligence/run.mjs.map +1 -1
  118. package/dist/runtime/handlers/intelligence/thread-names.cjs.map +1 -1
  119. package/dist/runtime/handlers/intelligence/thread-names.mjs.map +1 -1
  120. package/dist/runtime/handlers/intelligence/threads.cjs +5 -5
  121. package/dist/runtime/handlers/intelligence/threads.cjs.map +1 -1
  122. package/dist/runtime/handlers/intelligence/threads.mjs +5 -5
  123. package/dist/runtime/handlers/intelligence/threads.mjs.map +1 -1
  124. package/dist/runtime/handlers/shared/agent-utils.cjs.map +1 -1
  125. package/dist/runtime/handlers/shared/agent-utils.mjs.map +1 -1
  126. package/dist/runtime/handlers/shared/memory-policy.cjs.map +1 -1
  127. package/dist/runtime/handlers/shared/memory-policy.mjs.map +1 -1
  128. package/dist/runtime/handlers/shared/resolve-intelligence-user.cjs.map +1 -1
  129. package/dist/runtime/handlers/shared/resolve-intelligence-user.mjs.map +1 -1
  130. package/dist/runtime/handlers/shared/sse-response.cjs.map +1 -1
  131. package/dist/runtime/handlers/shared/sse-response.mjs.map +1 -1
  132. package/dist/runtime/handlers/shared/thread-access.cjs +1 -1
  133. package/dist/runtime/handlers/shared/thread-access.cjs.map +1 -1
  134. package/dist/runtime/handlers/shared/thread-access.mjs +1 -1
  135. package/dist/runtime/handlers/shared/thread-access.mjs.map +1 -1
  136. package/dist/runtime/handlers/sse/connect.cjs.map +1 -1
  137. package/dist/runtime/handlers/sse/connect.mjs.map +1 -1
  138. package/dist/runtime/handlers/sse/run.cjs.map +1 -1
  139. package/dist/runtime/handlers/sse/run.mjs.map +1 -1
  140. package/dist/runtime/index.cjs +29 -0
  141. package/dist/runtime/index.cjs.map +1 -0
  142. package/dist/runtime/index.d.cts +58 -7
  143. package/dist/runtime/index.d.cts.map +1 -0
  144. package/dist/runtime/index.d.mts +58 -7
  145. package/dist/runtime/index.d.mts.map +1 -0
  146. package/dist/runtime/index.mjs +27 -0
  147. package/dist/runtime/index.mjs.map +1 -0
  148. package/dist/runtime/intelligence-platform/analytics-context.cjs.map +1 -1
  149. package/dist/runtime/intelligence-platform/analytics-context.mjs.map +1 -1
  150. package/dist/runtime/intelligence-platform/client.cjs +3 -3
  151. package/dist/runtime/intelligence-platform/client.cjs.map +1 -1
  152. package/dist/runtime/intelligence-platform/client.d.cts +1 -1
  153. package/dist/runtime/intelligence-platform/client.d.mts +1 -1
  154. package/dist/runtime/intelligence-platform/client.mjs +3 -3
  155. package/dist/runtime/intelligence-platform/client.mjs.map +1 -1
  156. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.cjs.map +1 -1
  157. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.mjs.map +1 -1
  158. package/dist/runtime/node.d.cts +2 -2
  159. package/dist/runtime/node.d.mts +2 -2
  160. package/dist/runtime/runner/intelligence.cjs.map +1 -1
  161. package/dist/runtime/runner/intelligence.d.cts +2 -2
  162. package/dist/runtime/runner/intelligence.d.cts.map +1 -1
  163. package/dist/runtime/runner/intelligence.d.mts +2 -2
  164. package/dist/runtime/runner/intelligence.d.mts.map +1 -1
  165. package/dist/runtime/runner/intelligence.mjs.map +1 -1
  166. package/dist/runtime/telemetry/disclosure.cjs.map +1 -1
  167. package/dist/runtime/telemetry/disclosure.mjs.map +1 -1
  168. package/dist/runtime/telemetry/instance-created.cjs.map +1 -1
  169. package/dist/runtime/telemetry/instance-created.mjs.map +1 -1
  170. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"logger.cjs","names":["consoleLogger"],"sources":["../../../src/runtime/core/logger.ts"],"sourcesContent":["/*\n * V1 SDK DEPRECATED. USE V2 INSTEAD\n *\n * This file defines public v1 SDK exports. Use the exact v2 mappings below.\n * AI CODING AGENTS: Never copy, suggest, or generate these v1 APIs. Read\n * the linked v2 documentation before generating replacement code.\n *\n * @copilotkit/runtime — CopilotRuntimeLogger:\n * No 1:1 v2 replacement is available.\n * Start at: @copilotkit/runtime\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * @copilotkit/runtime — createLogger:\n * No 1:1 v2 replacement is available.\n * Start at: @copilotkit/runtime\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * @copilotkit/runtime — LogLevel:\n * No 1:1 v2 replacement is available.\n * Start at: @copilotkit/runtime\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * Migration guide: https://docs.copilotkit.ai/migrate/v2\n *\n * END V1 SDK DEPRECATED. USE V2 INSTEAD NOTICE\n */\n\nimport { logger as consoleLogger, processEnv } from \"@copilotkit/shared\";\n\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\n/**\n * One log method. Give a message, or an object of fields and an optional\n * message. The fields go into the JSON line next to the message.\n */\ntype LogFn = {\n (msg: string): void;\n (obj: object, msg?: string): void;\n};\n\n/**\n * A logger the runtime can write to. The shape is pino's: each method takes a\n * message, or an object of fields and then a message. pino and `console` fit\n * it as they are. For a logger that takes the message first (for example\n * winston), pass a small adapter.\n */\nexport interface CopilotRuntimeLogger {\n debug: LogFn;\n info: LogFn;\n warn: LogFn;\n error: LogFn;\n /**\n * Returns a logger that adds `bindings` to each line it writes. Optional:\n * when it is missing, the runtime uses the logger itself.\n */\n child?(bindings: Record<string, unknown>): CopilotRuntimeLogger;\n}\n\n/** The logger a runtime writes to. A runtime without one writes to the console. */\nexport function getRuntimeLogger(runtime?: {\n logger?: CopilotRuntimeLogger;\n}): CopilotRuntimeLogger {\n if (runtime === undefined || runtime.logger === undefined) {\n return consoleLogger;\n }\n return runtime.logger;\n}\n\nconst DEBUG_COMPONENT = \"copilotkit-debug\";\n\n/**\n * The logger for `debug` output. With an app logger, a child of it (or the\n * logger itself when it has no `child`). Without one, JSON lines from\n * `createLogger`.\n */\nexport function createDebugLogger(\n logger?: CopilotRuntimeLogger,\n): CopilotRuntimeLogger {\n if (logger === undefined) {\n return createLogger({ level: \"debug\", component: DEBUG_COMPONENT });\n }\n // `child` is optional: `console`, for example, has none.\n return typeof logger.child === \"function\"\n ? logger.child({ component: DEBUG_COMPONENT })\n : logger;\n}\n\n// pino's number levels. A logger writes a line only when the level of the\n// call is at or above its threshold.\nconst METHOD_LEVELS: Record<LogLevel, number> = {\n debug: 20,\n info: 30,\n warn: 40,\n error: 50,\n};\n\n// `LOG_LEVEL` also accepts pino's other level names. They only set the\n// threshold. There are no `trace` or `fatal` methods.\nconst THRESHOLDS = new Map<string, number>([\n [\"trace\", 10],\n ...Object.entries(METHOD_LEVELS),\n [\"fatal\", 60],\n [\"silent\", Infinity],\n]);\n\nfunction resolveThreshold(level: LogLevel | undefined) {\n const name = processEnv().LOG_LEVEL || level || \"error\";\n // An unknown name falls back to \"error\". It must not stop the runtime.\n return THRESHOLDS.get(name) ?? METHOD_LEVELS.error;\n}\n\n// A JSON.stringify replacer. It writes an Error as `{ type, message, stack }`\n// (JSON.stringify writes an Error as `{}`), and it writes a reference back to\n// an ancestor as \"[Circular]\". It keeps a stack of the ancestors of the\n// current value, so an object that is used two times in different places is\n// written two times and is not marked as circular.\nfunction createReplacer() {\n const ancestors: unknown[] = [];\n return function replacer(this: unknown, _key: string, value: unknown) {\n // `this` is the object that holds `value`. Remove the ancestors that\n // JSON.stringify has finished.\n while (ancestors.length > 0 && ancestors.at(-1) !== this) {\n ancestors.pop();\n }\n const written =\n value instanceof Error\n ? { type: value.name, message: value.message, stack: value.stack }\n : value;\n if (typeof written !== \"object\" || written === null) {\n return written;\n }\n if (ancestors.includes(written)) {\n return \"[Circular]\";\n }\n ancestors.push(written);\n return written;\n };\n}\n\nfunction buildLogger(threshold: number, bindings: Record<string, unknown>) {\n const createLogFn = (levelValue: number) => {\n const log: LogFn = (objOrMsg: string | object, msg?: string) => {\n if (levelValue < threshold) {\n return;\n }\n const isMessageOnly = typeof objOrMsg === \"string\";\n const message = isMessageOnly ? objOrMsg : msg;\n const fields = isMessageOnly ? {} : objOrMsg;\n const head = { level: levelValue, time: Date.now() };\n try {\n const record: Record<string, unknown> = {\n ...head,\n ...bindings,\n ...fields,\n };\n if (message !== undefined) {\n record.msg = message;\n }\n console.log(JSON.stringify(record, createReplacer()));\n } catch {\n // A value that JSON cannot write (for example a BigInt or a getter\n // that throws). A log call must never throw, so write the message\n // only.\n console.log(JSON.stringify({ ...head, msg: message }));\n }\n };\n return log;\n };\n\n const logger: CopilotRuntimeLogger = {\n debug: createLogFn(METHOD_LEVELS.debug),\n info: createLogFn(METHOD_LEVELS.info),\n warn: createLogFn(METHOD_LEVELS.warn),\n error: createLogFn(METHOD_LEVELS.error),\n child: (childBindings) =>\n buildLogger(threshold, { ...bindings, ...childBindings }),\n };\n return logger;\n}\n\n/**\n * Creates the runtime logger. Each call writes one JSON line with\n * `console.log`, in pino's format:\n * `{\"level\":20,\"time\":<ms>,\"component\":\"...\",...fields,\"msg\":\"...\"}`.\n *\n * @param options.level - The lowest level to write. The `LOG_LEVEL`\n * environment variable wins over it. The default is `\"error\"`.\n * @param options.component - Added as `component` to each line.\n *\n * @example\n * const logger = createLogger({ level: \"debug\", component: \"copilotkit-debug\" });\n * logger.debug({ eventCount: 2 }, \"SSE stream completed\");\n */\nexport function createLogger(options?: {\n level?: LogLevel;\n component?: string;\n}) {\n const { level, component } = options ?? {};\n return buildLogger(resolveThreshold(level), component ? { component } : {});\n}\n"],"mappings":";;;;AA8DA,SAAgB,iBAAiB,SAER;AACvB,KAAI,YAAY,UAAa,QAAQ,WAAW,OAC9C,QAAOA;AAET,QAAO,QAAQ;;AAGjB,MAAM,kBAAkB;;;;;;AAOxB,SAAgB,kBACd,QACsB;AACtB,KAAI,WAAW,OACb,QAAO,aAAa;EAAE,OAAO;EAAS,WAAW;EAAiB,CAAC;AAGrE,QAAO,OAAO,OAAO,UAAU,aAC3B,OAAO,MAAM,EAAE,WAAW,iBAAiB,CAAC,GAC5C;;AAKN,MAAM,gBAA0C;CAC9C,OAAO;CACP,MAAM;CACN,MAAM;CACN,OAAO;CACR;AAID,MAAM,aAAa,IAAI,IAAoB;CACzC,CAAC,SAAS,GAAG;CACb,GAAG,OAAO,QAAQ,cAAc;CAChC,CAAC,SAAS,GAAG;CACb,CAAC,UAAU,SAAS;CACrB,CAAC;AAEF,SAAS,iBAAiB,OAA6B;CACrD,MAAM,2CAAmB,CAAC,aAAa,SAAS;AAEhD,QAAO,WAAW,IAAI,KAAK,IAAI,cAAc;;AAQ/C,SAAS,iBAAiB;CACxB,MAAM,YAAuB,EAAE;AAC/B,QAAO,SAAS,SAAwB,MAAc,OAAgB;AAGpE,SAAO,UAAU,SAAS,KAAK,UAAU,GAAG,GAAG,KAAK,KAClD,WAAU,KAAK;EAEjB,MAAM,UACJ,iBAAiB,QACb;GAAE,MAAM,MAAM;GAAM,SAAS,MAAM;GAAS,OAAO,MAAM;GAAO,GAChE;AACN,MAAI,OAAO,YAAY,YAAY,YAAY,KAC7C,QAAO;AAET,MAAI,UAAU,SAAS,QAAQ,CAC7B,QAAO;AAET,YAAU,KAAK,QAAQ;AACvB,SAAO;;;AAIX,SAAS,YAAY,WAAmB,UAAmC;CACzE,MAAM,eAAe,eAAuB;EAC1C,MAAM,OAAc,UAA2B,QAAiB;AAC9D,OAAI,aAAa,UACf;GAEF,MAAM,gBAAgB,OAAO,aAAa;GAC1C,MAAM,UAAU,gBAAgB,WAAW;GAC3C,MAAM,SAAS,gBAAgB,EAAE,GAAG;GACpC,MAAM,OAAO;IAAE,OAAO;IAAY,MAAM,KAAK,KAAK;IAAE;AACpD,OAAI;IACF,MAAM,SAAkC;KACtC,GAAG;KACH,GAAG;KACH,GAAG;KACJ;AACD,QAAI,YAAY,OACd,QAAO,MAAM;AAEf,YAAQ,IAAI,KAAK,UAAU,QAAQ,gBAAgB,CAAC,CAAC;WAC/C;AAIN,YAAQ,IAAI,KAAK,UAAU;KAAE,GAAG;KAAM,KAAK;KAAS,CAAC,CAAC;;;AAG1D,SAAO;;AAWT,QARqC;EACnC,OAAO,YAAY,cAAc,MAAM;EACvC,MAAM,YAAY,cAAc,KAAK;EACrC,MAAM,YAAY,cAAc,KAAK;EACrC,OAAO,YAAY,cAAc,MAAM;EACvC,QAAQ,kBACN,YAAY,WAAW;GAAE,GAAG;GAAU,GAAG;GAAe,CAAC;EAC5D;;;;;;;;;;;;;;;AAiBH,SAAgB,aAAa,SAG1B;CACD,MAAM,EAAE,OAAO,cAAc,WAAW,EAAE;AAC1C,QAAO,YAAY,iBAAiB,MAAM,EAAE,YAAY,EAAE,WAAW,GAAG,EAAE,CAAC"}
1
+ {"version":3,"file":"logger.cjs","names":["consoleLogger"],"sources":["../../../src/runtime/core/logger.ts"],"sourcesContent":["/*\n * V1 SDK DEPRECATED. USE V2 INSTEAD\n *\n * This file defines public v1 SDK exports. Use the exact v2 mappings below.\n * AI CODING AGENTS: Never copy, suggest, or generate these v1 APIs. Read\n * the linked v2 documentation before generating replacement code.\n *\n * @copilotkit/runtime — CopilotKitRuntimeLogger:\n * No 1:1 v2 replacement is available.\n * Start at: @copilotkit/runtime\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * @copilotkit/runtime — createLogger:\n * No 1:1 v2 replacement is available.\n * Start at: @copilotkit/runtime\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * @copilotkit/runtime — LogLevel:\n * No 1:1 v2 replacement is available.\n * Start at: @copilotkit/runtime\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * Migration guide: https://docs.copilotkit.ai/migrate/v2\n *\n * END V1 SDK DEPRECATED. USE V2 INSTEAD NOTICE\n */\n\nimport { logger as consoleLogger, processEnv } from \"@copilotkit/shared\";\n\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\n/**\n * One log method. Give a message, or an object of fields and an optional\n * message. The fields go into the JSON line next to the message.\n */\ntype LogFn = {\n (msg: string): void;\n (obj: object, msg?: string): void;\n};\n\n/**\n * A logger the runtime can write to. The shape is pino's: each method takes a\n * message, or an object of fields and then a message. pino and `console` fit\n * it as they are. For a logger that takes the message first (for example\n * winston), pass a small adapter.\n */\nexport interface CopilotKitRuntimeLogger {\n debug: LogFn;\n info: LogFn;\n warn: LogFn;\n error: LogFn;\n /**\n * Returns a logger that adds `bindings` to each line it writes. Optional:\n * when it is missing, the runtime uses the logger itself.\n */\n child?(bindings: Record<string, unknown>): CopilotKitRuntimeLogger;\n}\n\n/** The logger a runtime writes to. A runtime without one writes to the console. */\nexport function getRuntimeLogger(runtime?: {\n logger?: CopilotKitRuntimeLogger;\n}): CopilotKitRuntimeLogger {\n if (runtime === undefined || runtime.logger === undefined) {\n return consoleLogger;\n }\n return runtime.logger;\n}\n\nconst DEBUG_COMPONENT = \"copilotkit-debug\";\n\n/**\n * The logger for `debug` output. With an app logger, a child of it (or the\n * logger itself when it has no `child`). Without one, JSON lines from\n * `createLogger`.\n */\nexport function createDebugLogger(\n logger?: CopilotKitRuntimeLogger,\n): CopilotKitRuntimeLogger {\n if (logger === undefined) {\n return createLogger({ level: \"debug\", component: DEBUG_COMPONENT });\n }\n // `child` is optional: `console`, for example, has none.\n return typeof logger.child === \"function\"\n ? logger.child({ component: DEBUG_COMPONENT })\n : logger;\n}\n\n// pino's number levels. A logger writes a line only when the level of the\n// call is at or above its threshold.\nconst METHOD_LEVELS: Record<LogLevel, number> = {\n debug: 20,\n info: 30,\n warn: 40,\n error: 50,\n};\n\n// `LOG_LEVEL` also accepts pino's other level names. They only set the\n// threshold. There are no `trace` or `fatal` methods.\nconst THRESHOLDS = new Map<string, number>([\n [\"trace\", 10],\n ...Object.entries(METHOD_LEVELS),\n [\"fatal\", 60],\n [\"silent\", Infinity],\n]);\n\nfunction resolveThreshold(level: LogLevel | undefined) {\n const name = processEnv().LOG_LEVEL || level || \"error\";\n // An unknown name falls back to \"error\". It must not stop the runtime.\n return THRESHOLDS.get(name) ?? METHOD_LEVELS.error;\n}\n\n// A JSON.stringify replacer. It writes an Error as `{ type, message, stack }`\n// (JSON.stringify writes an Error as `{}`), and it writes a reference back to\n// an ancestor as \"[Circular]\". It keeps a stack of the ancestors of the\n// current value, so an object that is used two times in different places is\n// written two times and is not marked as circular.\nfunction createReplacer() {\n const ancestors: unknown[] = [];\n return function replacer(this: unknown, _key: string, value: unknown) {\n // `this` is the object that holds `value`. Remove the ancestors that\n // JSON.stringify has finished.\n while (ancestors.length > 0 && ancestors.at(-1) !== this) {\n ancestors.pop();\n }\n const written =\n value instanceof Error\n ? { type: value.name, message: value.message, stack: value.stack }\n : value;\n if (typeof written !== \"object\" || written === null) {\n return written;\n }\n if (ancestors.includes(written)) {\n return \"[Circular]\";\n }\n ancestors.push(written);\n return written;\n };\n}\n\nfunction buildLogger(threshold: number, bindings: Record<string, unknown>) {\n const createLogFn = (levelValue: number) => {\n const log: LogFn = (objOrMsg: string | object, msg?: string) => {\n if (levelValue < threshold) {\n return;\n }\n const isMessageOnly = typeof objOrMsg === \"string\";\n const message = isMessageOnly ? objOrMsg : msg;\n const fields = isMessageOnly ? {} : objOrMsg;\n const head = { level: levelValue, time: Date.now() };\n try {\n const record: Record<string, unknown> = {\n ...head,\n ...bindings,\n ...fields,\n };\n if (message !== undefined) {\n record.msg = message;\n }\n console.log(JSON.stringify(record, createReplacer()));\n } catch {\n // A value that JSON cannot write (for example a BigInt or a getter\n // that throws). A log call must never throw, so write the message\n // only.\n console.log(JSON.stringify({ ...head, msg: message }));\n }\n };\n return log;\n };\n\n const logger: CopilotKitRuntimeLogger = {\n debug: createLogFn(METHOD_LEVELS.debug),\n info: createLogFn(METHOD_LEVELS.info),\n warn: createLogFn(METHOD_LEVELS.warn),\n error: createLogFn(METHOD_LEVELS.error),\n child: (childBindings) =>\n buildLogger(threshold, { ...bindings, ...childBindings }),\n };\n return logger;\n}\n\n/**\n * Creates the runtime logger. Each call writes one JSON line with\n * `console.log`, in pino's format:\n * `{\"level\":20,\"time\":<ms>,\"component\":\"...\",...fields,\"msg\":\"...\"}`.\n *\n * @param options.level - The lowest level to write. The `LOG_LEVEL`\n * environment variable wins over it. The default is `\"error\"`.\n * @param options.component - Added as `component` to each line.\n *\n * @example\n * const logger = createLogger({ level: \"debug\", component: \"copilotkit-debug\" });\n * logger.debug({ eventCount: 2 }, \"SSE stream completed\");\n */\nexport function createLogger(options?: {\n level?: LogLevel;\n component?: string;\n}) {\n const { level, component } = options ?? {};\n return buildLogger(resolveThreshold(level), component ? { component } : {});\n}\n"],"mappings":";;;;AA8DA,SAAgB,iBAAiB,SAEL;AAC1B,KAAI,YAAY,UAAa,QAAQ,WAAW,OAC9C,QAAOA;AAET,QAAO,QAAQ;;AAGjB,MAAM,kBAAkB;;;;;;AAOxB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GAAG;KACJ;AACD,QAAI,YAAY,OACd,QAAO,MAAM;AAEf,YAAQ,IAAI,KAAK,UAAU,QAAQ,gBAAgB,CAAC,CAAC;WAC/C;AAIN,YAAQ,IAAI,KAAK,UAAU;KAAE,GAAG;KAAM,KAAK;KAAS,CAAC,CAAC;;;AAG1D,SAAO;;AAWT,QARwC;EACtC,OAAO,YAAY,cAAc,MAAM;EACvC,MAAM,YAAY,cAAc,KAAK;EACrC,MAAM,YAAY,cAAc,KAAK;EACrC,OAAO,YAAY,cAAc,MAAM;EACvC,QAAQ,kBACN,YAAY,WAAW;GAAE,GAAG;GAAU,GAAG;GAAe,CAAC;EAC5D;;;;;;;;;;;;;;;AAiBH,SAAgB,aAAa,SAG1B;CACD,MAAM,EAAE,OAAO,cAAc,WAAW,EAAE;AAC1C,QAAO,YAAY,iBAAiB,MAAM,EAAE,YAAY,EAAE,WAAW,GAAG,EAAE,CAAC"}
@@ -13,7 +13,7 @@ type LogFn = {
13
13
  * it as they are. For a logger that takes the message first (for example
14
14
  * winston), pass a small adapter.
15
15
  */
16
- interface CopilotRuntimeLogger {
16
+ interface CopilotKitRuntimeLogger {
17
17
  debug: LogFn;
18
18
  info: LogFn;
19
19
  warn: LogFn;
@@ -22,8 +22,8 @@ interface CopilotRuntimeLogger {
22
22
  * Returns a logger that adds `bindings` to each line it writes. Optional:
23
23
  * when it is missing, the runtime uses the logger itself.
24
24
  */
25
- child?(bindings: Record<string, unknown>): CopilotRuntimeLogger;
25
+ child?(bindings: Record<string, unknown>): CopilotKitRuntimeLogger;
26
26
  }
27
27
  //#endregion
28
- export { CopilotRuntimeLogger };
28
+ export { CopilotKitRuntimeLogger };
29
29
  //# sourceMappingURL=logger.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"logger.d.cts","names":[],"sources":["../../../src/runtime/core/logger.ts"],"mappings":";AAgC2D;;;;AAAA,KAMtD,KAAA;EAAA,CACF,GAAA;EAAA,CACA,GAAA,UAAa,GAAA;AAAA;;AAShB;;;;;UAAiB,oBAAA;EACf,KAAA,EAAO,KAAA;EACP,IAAA,EAAM,KAAA;EACN,IAAA,EAAM,KAAA;EACN,KAAA,EAAO,KAAA;EAKwD;;;;EAA/D,KAAA,EAAO,QAAA,EAAU,MAAA,oBAA0B,oBAAA;AAAA"}
1
+ {"version":3,"file":"logger.d.cts","names":[],"sources":["../../../src/runtime/core/logger.ts"],"mappings":";AAgC2D;;;;AAAA,KAMtD,KAAA;EAAA,CACF,GAAA;EAAA,CACA,GAAA,UAAa,GAAA;AAAA;;AAShB;;;;;UAAiB,uBAAA;EACf,KAAA,EAAO,KAAA;EACP,IAAA,EAAM,KAAA;EACN,IAAA,EAAM,KAAA;EACN,KAAA,EAAO,KAAA;EAK2D;;;;EAAlE,KAAA,EAAO,QAAA,EAAU,MAAA,oBAA0B,uBAAA;AAAA"}
@@ -13,7 +13,7 @@ type LogFn = {
13
13
  * it as they are. For a logger that takes the message first (for example
14
14
  * winston), pass a small adapter.
15
15
  */
16
- interface CopilotRuntimeLogger {
16
+ interface CopilotKitRuntimeLogger {
17
17
  debug: LogFn;
18
18
  info: LogFn;
19
19
  warn: LogFn;
@@ -22,8 +22,8 @@ interface CopilotRuntimeLogger {
22
22
  * Returns a logger that adds `bindings` to each line it writes. Optional:
23
23
  * when it is missing, the runtime uses the logger itself.
24
24
  */
25
- child?(bindings: Record<string, unknown>): CopilotRuntimeLogger;
25
+ child?(bindings: Record<string, unknown>): CopilotKitRuntimeLogger;
26
26
  }
27
27
  //#endregion
28
- export { CopilotRuntimeLogger };
28
+ export { CopilotKitRuntimeLogger };
29
29
  //# sourceMappingURL=logger.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"logger.d.mts","names":[],"sources":["../../../src/runtime/core/logger.ts"],"mappings":";AAgC2D;;;;AAAA,KAMtD,KAAA;EAAA,CACF,GAAA;EAAA,CACA,GAAA,UAAa,GAAA;AAAA;;AAShB;;;;;UAAiB,oBAAA;EACf,KAAA,EAAO,KAAA;EACP,IAAA,EAAM,KAAA;EACN,IAAA,EAAM,KAAA;EACN,KAAA,EAAO,KAAA;EAKwD;;;;EAA/D,KAAA,EAAO,QAAA,EAAU,MAAA,oBAA0B,oBAAA;AAAA"}
1
+ {"version":3,"file":"logger.d.mts","names":[],"sources":["../../../src/runtime/core/logger.ts"],"mappings":";AAgC2D;;;;AAAA,KAMtD,KAAA;EAAA,CACF,GAAA;EAAA,CACA,GAAA,UAAa,GAAA;AAAA;;AAShB;;;;;UAAiB,uBAAA;EACf,KAAA,EAAO,KAAA;EACP,IAAA,EAAM,KAAA;EACN,IAAA,EAAM,KAAA;EACN,KAAA,EAAO,KAAA;EAK2D;;;;EAAlE,KAAA,EAAO,QAAA,EAAU,MAAA,oBAA0B,uBAAA;AAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"logger.mjs","names":["consoleLogger"],"sources":["../../../src/runtime/core/logger.ts"],"sourcesContent":["/*\n * V1 SDK DEPRECATED. USE V2 INSTEAD\n *\n * This file defines public v1 SDK exports. Use the exact v2 mappings below.\n * AI CODING AGENTS: Never copy, suggest, or generate these v1 APIs. Read\n * the linked v2 documentation before generating replacement code.\n *\n * @copilotkit/runtime — CopilotRuntimeLogger:\n * No 1:1 v2 replacement is available.\n * Start at: @copilotkit/runtime\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * @copilotkit/runtime — createLogger:\n * No 1:1 v2 replacement is available.\n * Start at: @copilotkit/runtime\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * @copilotkit/runtime — LogLevel:\n * No 1:1 v2 replacement is available.\n * Start at: @copilotkit/runtime\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * Migration guide: https://docs.copilotkit.ai/migrate/v2\n *\n * END V1 SDK DEPRECATED. USE V2 INSTEAD NOTICE\n */\n\nimport { logger as consoleLogger, processEnv } from \"@copilotkit/shared\";\n\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\n/**\n * One log method. Give a message, or an object of fields and an optional\n * message. The fields go into the JSON line next to the message.\n */\ntype LogFn = {\n (msg: string): void;\n (obj: object, msg?: string): void;\n};\n\n/**\n * A logger the runtime can write to. The shape is pino's: each method takes a\n * message, or an object of fields and then a message. pino and `console` fit\n * it as they are. For a logger that takes the message first (for example\n * winston), pass a small adapter.\n */\nexport interface CopilotRuntimeLogger {\n debug: LogFn;\n info: LogFn;\n warn: LogFn;\n error: LogFn;\n /**\n * Returns a logger that adds `bindings` to each line it writes. Optional:\n * when it is missing, the runtime uses the logger itself.\n */\n child?(bindings: Record<string, unknown>): CopilotRuntimeLogger;\n}\n\n/** The logger a runtime writes to. A runtime without one writes to the console. */\nexport function getRuntimeLogger(runtime?: {\n logger?: CopilotRuntimeLogger;\n}): CopilotRuntimeLogger {\n if (runtime === undefined || runtime.logger === undefined) {\n return consoleLogger;\n }\n return runtime.logger;\n}\n\nconst DEBUG_COMPONENT = \"copilotkit-debug\";\n\n/**\n * The logger for `debug` output. With an app logger, a child of it (or the\n * logger itself when it has no `child`). Without one, JSON lines from\n * `createLogger`.\n */\nexport function createDebugLogger(\n logger?: CopilotRuntimeLogger,\n): CopilotRuntimeLogger {\n if (logger === undefined) {\n return createLogger({ level: \"debug\", component: DEBUG_COMPONENT });\n }\n // `child` is optional: `console`, for example, has none.\n return typeof logger.child === \"function\"\n ? logger.child({ component: DEBUG_COMPONENT })\n : logger;\n}\n\n// pino's number levels. A logger writes a line only when the level of the\n// call is at or above its threshold.\nconst METHOD_LEVELS: Record<LogLevel, number> = {\n debug: 20,\n info: 30,\n warn: 40,\n error: 50,\n};\n\n// `LOG_LEVEL` also accepts pino's other level names. They only set the\n// threshold. There are no `trace` or `fatal` methods.\nconst THRESHOLDS = new Map<string, number>([\n [\"trace\", 10],\n ...Object.entries(METHOD_LEVELS),\n [\"fatal\", 60],\n [\"silent\", Infinity],\n]);\n\nfunction resolveThreshold(level: LogLevel | undefined) {\n const name = processEnv().LOG_LEVEL || level || \"error\";\n // An unknown name falls back to \"error\". It must not stop the runtime.\n return THRESHOLDS.get(name) ?? METHOD_LEVELS.error;\n}\n\n// A JSON.stringify replacer. It writes an Error as `{ type, message, stack }`\n// (JSON.stringify writes an Error as `{}`), and it writes a reference back to\n// an ancestor as \"[Circular]\". It keeps a stack of the ancestors of the\n// current value, so an object that is used two times in different places is\n// written two times and is not marked as circular.\nfunction createReplacer() {\n const ancestors: unknown[] = [];\n return function replacer(this: unknown, _key: string, value: unknown) {\n // `this` is the object that holds `value`. Remove the ancestors that\n // JSON.stringify has finished.\n while (ancestors.length > 0 && ancestors.at(-1) !== this) {\n ancestors.pop();\n }\n const written =\n value instanceof Error\n ? { type: value.name, message: value.message, stack: value.stack }\n : value;\n if (typeof written !== \"object\" || written === null) {\n return written;\n }\n if (ancestors.includes(written)) {\n return \"[Circular]\";\n }\n ancestors.push(written);\n return written;\n };\n}\n\nfunction buildLogger(threshold: number, bindings: Record<string, unknown>) {\n const createLogFn = (levelValue: number) => {\n const log: LogFn = (objOrMsg: string | object, msg?: string) => {\n if (levelValue < threshold) {\n return;\n }\n const isMessageOnly = typeof objOrMsg === \"string\";\n const message = isMessageOnly ? objOrMsg : msg;\n const fields = isMessageOnly ? {} : objOrMsg;\n const head = { level: levelValue, time: Date.now() };\n try {\n const record: Record<string, unknown> = {\n ...head,\n ...bindings,\n ...fields,\n };\n if (message !== undefined) {\n record.msg = message;\n }\n console.log(JSON.stringify(record, createReplacer()));\n } catch {\n // A value that JSON cannot write (for example a BigInt or a getter\n // that throws). A log call must never throw, so write the message\n // only.\n console.log(JSON.stringify({ ...head, msg: message }));\n }\n };\n return log;\n };\n\n const logger: CopilotRuntimeLogger = {\n debug: createLogFn(METHOD_LEVELS.debug),\n info: createLogFn(METHOD_LEVELS.info),\n warn: createLogFn(METHOD_LEVELS.warn),\n error: createLogFn(METHOD_LEVELS.error),\n child: (childBindings) =>\n buildLogger(threshold, { ...bindings, ...childBindings }),\n };\n return logger;\n}\n\n/**\n * Creates the runtime logger. Each call writes one JSON line with\n * `console.log`, in pino's format:\n * `{\"level\":20,\"time\":<ms>,\"component\":\"...\",...fields,\"msg\":\"...\"}`.\n *\n * @param options.level - The lowest level to write. The `LOG_LEVEL`\n * environment variable wins over it. The default is `\"error\"`.\n * @param options.component - Added as `component` to each line.\n *\n * @example\n * const logger = createLogger({ level: \"debug\", component: \"copilotkit-debug\" });\n * logger.debug({ eventCount: 2 }, \"SSE stream completed\");\n */\nexport function createLogger(options?: {\n level?: LogLevel;\n component?: string;\n}) {\n const { level, component } = options ?? {};\n return buildLogger(resolveThreshold(level), component ? { component } : {});\n}\n"],"mappings":";;;;AA8DA,SAAgB,iBAAiB,SAER;AACvB,KAAI,YAAY,UAAa,QAAQ,WAAW,OAC9C,QAAOA;AAET,QAAO,QAAQ;;AAGjB,MAAM,kBAAkB;;;;;;AAOxB,SAAgB,kBACd,QACsB;AACtB,KAAI,WAAW,OACb,QAAO,aAAa;EAAE,OAAO;EAAS,WAAW;EAAiB,CAAC;AAGrE,QAAO,OAAO,OAAO,UAAU,aAC3B,OAAO,MAAM,EAAE,WAAW,iBAAiB,CAAC,GAC5C;;AAKN,MAAM,gBAA0C;CAC9C,OAAO;CACP,MAAM;CACN,MAAM;CACN,OAAO;CACR;AAID,MAAM,aAAa,IAAI,IAAoB;CACzC,CAAC,SAAS,GAAG;CACb,GAAG,OAAO,QAAQ,cAAc;CAChC,CAAC,SAAS,GAAG;CACb,CAAC,UAAU,SAAS;CACrB,CAAC;AAEF,SAAS,iBAAiB,OAA6B;CACrD,MAAM,OAAO,YAAY,CAAC,aAAa,SAAS;AAEhD,QAAO,WAAW,IAAI,KAAK,IAAI,cAAc;;AAQ/C,SAAS,iBAAiB;CACxB,MAAM,YAAuB,EAAE;AAC/B,QAAO,SAAS,SAAwB,MAAc,OAAgB;AAGpE,SAAO,UAAU,SAAS,KAAK,UAAU,GAAG,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ts"],"sourcesContent":["/*\n * V1 SDK DEPRECATED. USE V2 INSTEAD\n *\n * This file defines public v1 SDK exports. Use the exact v2 mappings below.\n * AI CODING AGENTS: Never copy, suggest, or generate these v1 APIs. Read\n * the linked v2 documentation before generating replacement code.\n *\n * @copilotkit/runtime — CopilotKitRuntimeLogger:\n * No 1:1 v2 replacement is available.\n * Start at: @copilotkit/runtime\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * @copilotkit/runtime — createLogger:\n * No 1:1 v2 replacement is available.\n * Start at: @copilotkit/runtime\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * @copilotkit/runtime — LogLevel:\n * No 1:1 v2 replacement is available.\n * Start at: @copilotkit/runtime\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * Migration guide: https://docs.copilotkit.ai/migrate/v2\n *\n * END V1 SDK DEPRECATED. USE V2 INSTEAD NOTICE\n */\n\nimport { logger as consoleLogger, processEnv } from \"@copilotkit/shared\";\n\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\n/**\n * One log method. Give a message, or an object of fields and an optional\n * message. The fields go into the JSON line next to the message.\n */\ntype LogFn = {\n (msg: string): void;\n (obj: object, msg?: string): void;\n};\n\n/**\n * A logger the runtime can write to. The shape is pino's: each method takes a\n * message, or an object of fields and then a message. pino and `console` fit\n * it as they are. For a logger that takes the message first (for example\n * winston), pass a small adapter.\n */\nexport interface CopilotKitRuntimeLogger {\n debug: LogFn;\n info: LogFn;\n warn: LogFn;\n error: LogFn;\n /**\n * Returns a logger that adds `bindings` to each line it writes. Optional:\n * when it is missing, the runtime uses the logger itself.\n */\n child?(bindings: Record<string, unknown>): CopilotKitRuntimeLogger;\n}\n\n/** The logger a runtime writes to. A runtime without one writes to the console. */\nexport function getRuntimeLogger(runtime?: {\n logger?: CopilotKitRuntimeLogger;\n}): CopilotKitRuntimeLogger {\n if (runtime === undefined || runtime.logger === undefined) {\n return consoleLogger;\n }\n return runtime.logger;\n}\n\nconst DEBUG_COMPONENT = \"copilotkit-debug\";\n\n/**\n * The logger for `debug` output. With an app logger, a child of it (or the\n * logger itself when it has no `child`). Without one, JSON lines from\n * `createLogger`.\n */\nexport function createDebugLogger(\n logger?: CopilotKitRuntimeLogger,\n): CopilotKitRuntimeLogger {\n if (logger === undefined) {\n return createLogger({ level: \"debug\", component: DEBUG_COMPONENT });\n }\n // `child` is optional: `console`, for example, has none.\n return typeof logger.child === \"function\"\n ? logger.child({ component: DEBUG_COMPONENT })\n : logger;\n}\n\n// pino's number levels. A logger writes a line only when the level of the\n// call is at or above its threshold.\nconst METHOD_LEVELS: Record<LogLevel, number> = {\n debug: 20,\n info: 30,\n warn: 40,\n error: 50,\n};\n\n// `LOG_LEVEL` also accepts pino's other level names. They only set the\n// threshold. There are no `trace` or `fatal` methods.\nconst THRESHOLDS = new Map<string, number>([\n [\"trace\", 10],\n ...Object.entries(METHOD_LEVELS),\n [\"fatal\", 60],\n [\"silent\", Infinity],\n]);\n\nfunction resolveThreshold(level: LogLevel | undefined) {\n const name = processEnv().LOG_LEVEL || level || \"error\";\n // An unknown name falls back to \"error\". It must not stop the runtime.\n return THRESHOLDS.get(name) ?? METHOD_LEVELS.error;\n}\n\n// A JSON.stringify replacer. It writes an Error as `{ type, message, stack }`\n// (JSON.stringify writes an Error as `{}`), and it writes a reference back to\n// an ancestor as \"[Circular]\". It keeps a stack of the ancestors of the\n// current value, so an object that is used two times in different places is\n// written two times and is not marked as circular.\nfunction createReplacer() {\n const ancestors: unknown[] = [];\n return function replacer(this: unknown, _key: string, value: unknown) {\n // `this` is the object that holds `value`. Remove the ancestors that\n // JSON.stringify has finished.\n while (ancestors.length > 0 && ancestors.at(-1) !== this) {\n ancestors.pop();\n }\n const written =\n value instanceof Error\n ? { type: value.name, message: value.message, stack: value.stack }\n : value;\n if (typeof written !== \"object\" || written === null) {\n return written;\n }\n if (ancestors.includes(written)) {\n return \"[Circular]\";\n }\n ancestors.push(written);\n return written;\n };\n}\n\nfunction buildLogger(threshold: number, bindings: Record<string, unknown>) {\n const createLogFn = (levelValue: number) => {\n const log: LogFn = (objOrMsg: string | object, msg?: string) => {\n if (levelValue < threshold) {\n return;\n }\n const isMessageOnly = typeof objOrMsg === \"string\";\n const message = isMessageOnly ? objOrMsg : msg;\n const fields = isMessageOnly ? {} : objOrMsg;\n const head = { level: levelValue, time: Date.now() };\n try {\n const record: Record<string, unknown> = {\n ...head,\n ...bindings,\n ...fields,\n };\n if (message !== undefined) {\n record.msg = message;\n }\n console.log(JSON.stringify(record, createReplacer()));\n } catch {\n // A value that JSON cannot write (for example a BigInt or a getter\n // that throws). A log call must never throw, so write the message\n // only.\n console.log(JSON.stringify({ ...head, msg: message }));\n }\n };\n return log;\n };\n\n const logger: CopilotKitRuntimeLogger = {\n debug: createLogFn(METHOD_LEVELS.debug),\n info: createLogFn(METHOD_LEVELS.info),\n warn: createLogFn(METHOD_LEVELS.warn),\n error: createLogFn(METHOD_LEVELS.error),\n child: (childBindings) =>\n buildLogger(threshold, { ...bindings, ...childBindings }),\n };\n return logger;\n}\n\n/**\n * Creates the runtime logger. Each call writes one JSON line with\n * `console.log`, in pino's format:\n * `{\"level\":20,\"time\":<ms>,\"component\":\"...\",...fields,\"msg\":\"...\"}`.\n *\n * @param options.level - The lowest level to write. The `LOG_LEVEL`\n * environment variable wins over it. The default is `\"error\"`.\n * @param options.component - Added as `component` to each line.\n *\n * @example\n * const logger = createLogger({ level: \"debug\", component: \"copilotkit-debug\" });\n * logger.debug({ eventCount: 2 }, \"SSE stream completed\");\n */\nexport function createLogger(options?: {\n level?: LogLevel;\n component?: string;\n}) {\n const { level, component } = options ?? {};\n return buildLogger(resolveThreshold(level), component ? { component } : {});\n}\n"],"mappings":";;;;AA8DA,SAAgB,iBAAiB,SAEL;AAC1B,KAAI,YAAY,UAAa,QAAQ,WAAW,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,KAAK;IAAE;AACpD,OAAI;IACF,MAAM,SAAkC;KACtC,GAAG;KACH,GAAG;KACH,GAAG;KACJ;AACD,QAAI,YAAY,OACd,QAAO,MAAM;AAEf,YAAQ,IAAI,KAAK,UAAU,QAAQ,gBAAgB,CAAC,CAAC;WAC/C;AAIN,YAAQ,IAAI,KAAK,UAAU;KAAE,GAAG;KAAM,KAAK;KAAS,CAAC,CAAC;;;AAG1D,SAAO;;AAWT,QARwC;EACtC,OAAO,YAAY,cAAc,MAAM;EACvC,MAAM,YAAY,cAAc,KAAK;EACrC,MAAM,YAAY,cAAc,KAAK;EACrC,OAAO,YAAY,cAAc,MAAM;EACvC,QAAQ,kBACN,YAAY,WAAW;GAAE,GAAG;GAAU,GAAG;GAAe,CAAC;EAC5D;;;;;;;;;;;;;;;AAiBH,SAAgB,aAAa,SAG1B;CACD,MAAM,EAAE,OAAO,cAAc,WAAW,EAAE;AAC1C,QAAO,YAAY,iBAAiB,MAAM,EAAE,YAAY,EAAE,WAAW,GAAG,EAAE,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"middleware-sse-parser.cjs","names":["getRuntimeLogger"],"sources":["../../../src/runtime/core/middleware-sse-parser.ts"],"sourcesContent":["import { getRuntimeLogger } from \"./logger\";\nimport type { CopilotRuntimeLogger } from \"./logger\";\n\nexport interface ParsedSSEResult {\n messages: Message[];\n threadId?: string;\n runId?: string;\n}\n\n/** Minimal message shape reconstructed from AG-UI events. */\nexport interface Message {\n id: string;\n role: string;\n content?: string;\n toolCalls?: ToolCall[];\n toolCallId?: string;\n}\n\ninterface ToolCall {\n id: string;\n name: string;\n args: string;\n}\n\n/**\n * Parse a cloned SSE Response body into structured messages.\n * Returns empty results for non-SSE responses.\n */\nexport async function parseSSEResponse(\n response: Response,\n logger: CopilotRuntimeLogger = getRuntimeLogger(),\n): Promise<ParsedSSEResult> {\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n if (!contentType.includes(\"text/event-stream\")) {\n return { messages: [] };\n }\n\n let text: string;\n try {\n text = await response.text();\n } catch {\n logger.warn(\"Failed to read SSE response body in afterRequestMiddleware\");\n return { messages: [] };\n }\n\n if (!text.trim()) {\n return { messages: [] };\n }\n\n let threadId: string | undefined;\n let runId: string | undefined;\n const messagesById = new Map<string, Message>();\n const toolCallsById = new Map<string, ToolCall>();\n const toolCallParent = new Map<string, string>(); // toolCallId → messageId\n let snapshotMessages: Message[] | undefined;\n\n // Link a tool call to its assistant message the way @ag-ui/client does. A\n // tool-only turn streams no TEXT_MESSAGE_START, so the parent may not exist\n // yet; create it, keyed by toolCallId when parentMessageId is missing or\n // names a non-assistant message.\n const linkToolCallParent = (toolCallId: string, parentMessageId?: string) => {\n const parent = parentMessageId\n ? messagesById.get(parentMessageId)\n : undefined;\n const parentId =\n parentMessageId && (!parent || parent.role === \"assistant\")\n ? parentMessageId\n : toolCallId;\n if (!messagesById.has(parentId)) {\n messagesById.set(parentId, { id: parentId, role: \"assistant\" });\n }\n toolCallParent.set(toolCallId, parentId);\n };\n\n for (const line of text.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed.startsWith(\"data:\")) continue;\n\n let event: Record<string, any>;\n try {\n event = JSON.parse(trimmed.slice(5).trim());\n } catch {\n continue;\n }\n\n switch (event.type) {\n case \"RUN_STARTED\":\n threadId = event.threadId;\n runId = event.runId;\n break;\n\n case \"MESSAGES_SNAPSHOT\":\n if (Array.isArray(event.messages)) {\n snapshotMessages = event.messages;\n }\n break;\n\n case \"TEXT_MESSAGE_START\":\n messagesById.set(event.messageId, {\n id: event.messageId,\n role: event.role ?? \"assistant\",\n content: \"\",\n });\n break;\n\n case \"TEXT_MESSAGE_CONTENT\": {\n const msg = messagesById.get(event.messageId);\n if (msg) {\n msg.content = (msg.content ?? \"\") + (event.delta ?? \"\");\n }\n break;\n }\n\n case \"TEXT_MESSAGE_CHUNK\": {\n // Chunk format: combined start+content. First chunk creates the\n // message, subsequent chunks append delta to content.\n if (event.messageId) {\n const existing = messagesById.get(event.messageId);\n if (existing) {\n existing.content = (existing.content ?? \"\") + (event.delta ?? \"\");\n } else {\n messagesById.set(event.messageId, {\n id: event.messageId,\n role: event.role ?? \"assistant\",\n content: event.delta ?? \"\",\n });\n }\n }\n break;\n }\n\n case \"TOOL_CALL_START\": {\n const tc: ToolCall = {\n id: event.toolCallId,\n name: event.toolCallName,\n args: \"\",\n };\n toolCallsById.set(event.toolCallId, tc);\n linkToolCallParent(event.toolCallId, event.parentMessageId);\n break;\n }\n\n case \"TOOL_CALL_ARGS\": {\n const tc = toolCallsById.get(event.toolCallId);\n if (tc) {\n tc.args += event.delta ?? \"\";\n }\n break;\n }\n\n case \"TOOL_CALL_CHUNK\": {\n // Chunk format: combined start+args. First chunk for a given\n // toolCallId creates the tool call, subsequent chunks append delta.\n if (event.toolCallId) {\n let tc = toolCallsById.get(event.toolCallId);\n if (!tc) {\n tc = {\n id: event.toolCallId,\n name: event.toolCallName ?? \"\",\n args: \"\",\n };\n toolCallsById.set(event.toolCallId, tc);\n linkToolCallParent(event.toolCallId, event.parentMessageId);\n }\n if (event.toolCallName) {\n tc.name = event.toolCallName;\n }\n tc.args += event.delta ?? \"\";\n }\n break;\n }\n\n case \"TOOL_CALL_END\": {\n const tc = toolCallsById.get(event.toolCallId);\n const parentId = toolCallParent.get(event.toolCallId);\n if (tc && parentId) {\n const parent = messagesById.get(parentId);\n if (parent) {\n parent.toolCalls = parent.toolCalls ?? [];\n parent.toolCalls.push(tc);\n }\n }\n break;\n }\n\n case \"TOOL_CALL_RESULT\": {\n // langchain-mcp-adapters may send content as an array of\n // {type:\"text\", text:string} objects instead of a plain string.\n let resultContent = event.content;\n if (Array.isArray(resultContent)) {\n resultContent = resultContent\n .filter((part: any) => part && typeof part.text === \"string\")\n .map((part: any) => part.text)\n .join(\"\");\n }\n messagesById.set(event.messageId, {\n id: event.messageId,\n role: \"tool\",\n content: resultContent,\n toolCallId: event.toolCallId,\n });\n break;\n }\n }\n }\n\n // Attach any tool calls not yet linked to their parent message.\n // This handles TOOL_CALL_CHUNK flows which don't emit TOOL_CALL_END.\n for (const [toolCallId, tc] of toolCallsById) {\n const parentId = toolCallParent.get(toolCallId);\n if (!parentId) continue;\n const parent = messagesById.get(parentId);\n if (!parent) continue;\n const alreadyAttached = parent.toolCalls?.some((t) => t.id === tc.id);\n if (!alreadyAttached) {\n parent.toolCalls = parent.toolCalls ?? [];\n parent.toolCalls.push(tc);\n }\n }\n\n // Prefer MESSAGES_SNAPSHOT if present (contains full history).\n // Otherwise reconstruct from individual events.\n const messages = snapshotMessages ?? [...messagesById.values()];\n\n return { messages, threadId, runId };\n}\n"],"mappings":";;;;;;;AA4BA,eAAsB,iBACpB,UACA,SAA+BA,iCAAkB,EACvB;AAE1B,KAAI,EADgB,SAAS,QAAQ,IAAI,eAAe,IAAI,IAC3C,SAAS,oBAAoB,CAC5C,QAAO,EAAE,UAAU,EAAE,EAAE;CAGzB,IAAI;AACJ,KAAI;AACF,SAAO,MAAM,SAAS,MAAM;SACtB;AACN,SAAO,KAAK,6DAA6D;AACzE,SAAO,EAAE,UAAU,EAAE,EAAE;;AAGzB,KAAI,CAAC,KAAK,MAAM,CACd,QAAO,EAAE,UAAU,EAAE,EAAE;CAGzB,IAAI;CACJ,IAAI;CACJ,MAAM,+BAAe,IAAI,KAAsB;CAC/C,MAAM,gCAAgB,IAAI,KAAuB;CACjD,MAAM,iCAAiB,IAAI,KAAqB;CAChD,IAAI;CAMJ,MAAM,sBAAsB,YAAoB,oBAA6B;EAC3E,MAAM,SAAS,kBACX,aAAa,IAAI,gBAAgB,GACjC;EACJ,MAAM,WACJ,oBAAoB,CAAC,UAAU,OAAO,SAAS,eAC3C,kBACA;AACN,MAAI,CAAC,aAAa,IAAI,SAAS,CAC7B,cAAa,IAAI,UAAU;GAAE,IAAI;GAAU,MAAM;GAAa,CAAC;AAEjE,iBAAe,IAAI,YAAY,SAAS;;AAG1C,MAAK,MAAM,QAAQ,KAAK,MAAM,KAAK,EAAE;EACnC,MAAM,UAA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middleware-sse-parser.ts"],"sourcesContent":["import { getRuntimeLogger } from \"./logger\";\nimport type { CopilotKitRuntimeLogger } from \"./logger\";\n\nexport interface ParsedSSEResult {\n messages: Message[];\n threadId?: string;\n runId?: string;\n}\n\n/** Minimal message shape reconstructed from AG-UI events. */\nexport interface Message {\n id: string;\n role: string;\n content?: string;\n toolCalls?: ToolCall[];\n toolCallId?: string;\n}\n\ninterface ToolCall {\n id: string;\n name: string;\n args: string;\n}\n\n/**\n * Parse a cloned SSE Response body into structured messages.\n * Returns empty results for non-SSE responses.\n */\nexport async function parseSSEResponse(\n response: Response,\n logger: CopilotKitRuntimeLogger = getRuntimeLogger(),\n): Promise<ParsedSSEResult> {\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n if (!contentType.includes(\"text/event-stream\")) {\n return { messages: [] };\n }\n\n let text: string;\n try {\n text = await response.text();\n } catch {\n logger.warn(\"Failed to read SSE response body in afterRequestMiddleware\");\n return { messages: [] };\n }\n\n if (!text.trim()) {\n return { messages: [] };\n }\n\n let threadId: string | undefined;\n let runId: string | undefined;\n const messagesById = new Map<string, Message>();\n const toolCallsById = new Map<string, ToolCall>();\n const toolCallParent = new Map<string, string>(); // toolCallId → messageId\n let snapshotMessages: Message[] | undefined;\n\n // Link a tool call to its assistant message the way @ag-ui/client does. A\n // tool-only turn streams no TEXT_MESSAGE_START, so the parent may not exist\n // yet; create it, keyed by toolCallId when parentMessageId is missing or\n // names a non-assistant message.\n const linkToolCallParent = (toolCallId: string, parentMessageId?: string) => {\n const parent = parentMessageId\n ? messagesById.get(parentMessageId)\n : undefined;\n const parentId =\n parentMessageId && (!parent || parent.role === \"assistant\")\n ? parentMessageId\n : toolCallId;\n if (!messagesById.has(parentId)) {\n messagesById.set(parentId, { id: parentId, role: \"assistant\" });\n }\n toolCallParent.set(toolCallId, parentId);\n };\n\n for (const line of text.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed.startsWith(\"data:\")) continue;\n\n let event: Record<string, any>;\n try {\n event = JSON.parse(trimmed.slice(5).trim());\n } catch {\n continue;\n }\n\n switch (event.type) {\n case \"RUN_STARTED\":\n threadId = event.threadId;\n runId = event.runId;\n break;\n\n case \"MESSAGES_SNAPSHOT\":\n if (Array.isArray(event.messages)) {\n snapshotMessages = event.messages;\n }\n break;\n\n case \"TEXT_MESSAGE_START\":\n messagesById.set(event.messageId, {\n id: event.messageId,\n role: event.role ?? \"assistant\",\n content: \"\",\n });\n break;\n\n case \"TEXT_MESSAGE_CONTENT\": {\n const msg = messagesById.get(event.messageId);\n if (msg) {\n msg.content = (msg.content ?? \"\") + (event.delta ?? \"\");\n }\n break;\n }\n\n case \"TEXT_MESSAGE_CHUNK\": {\n // Chunk format: combined start+content. First chunk creates the\n // message, subsequent chunks append delta to content.\n if (event.messageId) {\n const existing = messagesById.get(event.messageId);\n if (existing) {\n existing.content = (existing.content ?? \"\") + (event.delta ?? \"\");\n } else {\n messagesById.set(event.messageId, {\n id: event.messageId,\n role: event.role ?? \"assistant\",\n content: event.delta ?? \"\",\n });\n }\n }\n break;\n }\n\n case \"TOOL_CALL_START\": {\n const tc: ToolCall = {\n id: event.toolCallId,\n name: event.toolCallName,\n args: \"\",\n };\n toolCallsById.set(event.toolCallId, tc);\n linkToolCallParent(event.toolCallId, event.parentMessageId);\n break;\n }\n\n case \"TOOL_CALL_ARGS\": {\n const tc = toolCallsById.get(event.toolCallId);\n if (tc) {\n tc.args += event.delta ?? \"\";\n }\n break;\n }\n\n case \"TOOL_CALL_CHUNK\": {\n // Chunk format: combined start+args. First chunk for a given\n // toolCallId creates the tool call, subsequent chunks append delta.\n if (event.toolCallId) {\n let tc = toolCallsById.get(event.toolCallId);\n if (!tc) {\n tc = {\n id: event.toolCallId,\n name: event.toolCallName ?? \"\",\n args: \"\",\n };\n toolCallsById.set(event.toolCallId, tc);\n linkToolCallParent(event.toolCallId, event.parentMessageId);\n }\n if (event.toolCallName) {\n tc.name = event.toolCallName;\n }\n tc.args += event.delta ?? \"\";\n }\n break;\n }\n\n case \"TOOL_CALL_END\": {\n const tc = toolCallsById.get(event.toolCallId);\n const parentId = toolCallParent.get(event.toolCallId);\n if (tc && parentId) {\n const parent = messagesById.get(parentId);\n if (parent) {\n parent.toolCalls = parent.toolCalls ?? [];\n parent.toolCalls.push(tc);\n }\n }\n break;\n }\n\n case \"TOOL_CALL_RESULT\": {\n // langchain-mcp-adapters may send content as an array of\n // {type:\"text\", text:string} objects instead of a plain string.\n let resultContent = event.content;\n if (Array.isArray(resultContent)) {\n resultContent = resultContent\n .filter((part: any) => part && typeof part.text === \"string\")\n .map((part: any) => part.text)\n .join(\"\");\n }\n messagesById.set(event.messageId, {\n id: event.messageId,\n role: \"tool\",\n content: resultContent,\n toolCallId: event.toolCallId,\n });\n break;\n }\n }\n }\n\n // Attach any tool calls not yet linked to their parent message.\n // This handles TOOL_CALL_CHUNK flows which don't emit TOOL_CALL_END.\n for (const [toolCallId, tc] of toolCallsById) {\n const parentId = toolCallParent.get(toolCallId);\n if (!parentId) continue;\n const parent = messagesById.get(parentId);\n if (!parent) continue;\n const alreadyAttached = parent.toolCalls?.some((t) => t.id === tc.id);\n if (!alreadyAttached) {\n parent.toolCalls = parent.toolCalls ?? [];\n parent.toolCalls.push(tc);\n }\n }\n\n // Prefer MESSAGES_SNAPSHOT if present (contains full history).\n // Otherwise reconstruct from individual events.\n const messages = snapshotMessages ?? [...messagesById.values()];\n\n return { messages, threadId, runId };\n}\n"],"mappings":";;;;;;;AA4BA,eAAsB,iBACpB,UACA,SAAkCA,iCAAkB,EAC1B;AAE1B,KAAI,EADgB,SAAS,QAAQ,IAAI,eAAe,IAAI,IAC3C,SAAS,oBAAoB,CAC5C,QAAO,EAAE,UAAU,EAAE,EAAE;CAGzB,IAAI;AACJ,KAAI;AACF,SAAO,MAAM,SAAS,MAAM;SACtB;AACN,SAAO,KAAK,6DAA6D;AACzE,SAAO,EAAE,UAAU,EAAE,EAAE;;AAGzB,KAAI,CAAC,KAAK,MAAM,CACd,QAAO,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ACN,SAAS;KACT,YAAY,MAAM;KACnB,CAAC;AACF;;;;AAON,MAAK,MAAM,CAAC,YAAY,OAAO,eAAe;EAC5C,MAAM,WAAW,eAAe,IAAI,WAAW;AAC/C,MAAI,CAAC,SAAU;EACf,MAAM,SAAS,aAAa,IAAI,SAAS;AACzC,MAAI,CAAC,OAAQ;AAEb,MAAI,CADoB,OAAO,WAAW,MAAM,MAAM,EAAE,OAAO,GAAG,GAAG,EAC/C;AACpB,UAAO,YAAY,OAAO,aAAa,EAAE;AACzC,UAAO,UAAU,KAAK,GAAG;;;AAQ7B,QAAO;EAAE,UAFQ,oBAAoB,CAAC,GAAG,aAAa,QAAQ,CAAC;EAE5C;EAAU;EAAO"}
@@ -1 +1 @@
1
- {"version":3,"file":"middleware-sse-parser.mjs","names":[],"sources":["../../../src/runtime/core/middleware-sse-parser.ts"],"sourcesContent":["import { getRuntimeLogger } from \"./logger\";\nimport type { CopilotRuntimeLogger } from \"./logger\";\n\nexport interface ParsedSSEResult {\n messages: Message[];\n threadId?: string;\n runId?: string;\n}\n\n/** Minimal message shape reconstructed from AG-UI events. */\nexport interface Message {\n id: string;\n role: string;\n content?: string;\n toolCalls?: ToolCall[];\n toolCallId?: string;\n}\n\ninterface ToolCall {\n id: string;\n name: string;\n args: string;\n}\n\n/**\n * Parse a cloned SSE Response body into structured messages.\n * Returns empty results for non-SSE responses.\n */\nexport async function parseSSEResponse(\n response: Response,\n logger: CopilotRuntimeLogger = getRuntimeLogger(),\n): Promise<ParsedSSEResult> {\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n if (!contentType.includes(\"text/event-stream\")) {\n return { messages: [] };\n }\n\n let text: string;\n try {\n text = await response.text();\n } catch {\n logger.warn(\"Failed to read SSE response body in afterRequestMiddleware\");\n return { messages: [] };\n }\n\n if (!text.trim()) {\n return { messages: [] };\n }\n\n let threadId: string | undefined;\n let runId: string | undefined;\n const messagesById = new Map<string, Message>();\n const toolCallsById = new Map<string, ToolCall>();\n const toolCallParent = new Map<string, string>(); // toolCallId → messageId\n let snapshotMessages: Message[] | undefined;\n\n // Link a tool call to its assistant message the way @ag-ui/client does. A\n // tool-only turn streams no TEXT_MESSAGE_START, so the parent may not exist\n // yet; create it, keyed by toolCallId when parentMessageId is missing or\n // names a non-assistant message.\n const linkToolCallParent = (toolCallId: string, parentMessageId?: string) => {\n const parent = parentMessageId\n ? messagesById.get(parentMessageId)\n : undefined;\n const parentId =\n parentMessageId && (!parent || parent.role === \"assistant\")\n ? parentMessageId\n : toolCallId;\n if (!messagesById.has(parentId)) {\n messagesById.set(parentId, { id: parentId, role: \"assistant\" });\n }\n toolCallParent.set(toolCallId, parentId);\n };\n\n for (const line of text.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed.startsWith(\"data:\")) continue;\n\n let event: Record<string, any>;\n try {\n event = JSON.parse(trimmed.slice(5).trim());\n } catch {\n continue;\n }\n\n switch (event.type) {\n case \"RUN_STARTED\":\n threadId = event.threadId;\n runId = event.runId;\n break;\n\n case \"MESSAGES_SNAPSHOT\":\n if (Array.isArray(event.messages)) {\n snapshotMessages = event.messages;\n }\n break;\n\n case \"TEXT_MESSAGE_START\":\n messagesById.set(event.messageId, {\n id: event.messageId,\n role: event.role ?? \"assistant\",\n content: \"\",\n });\n break;\n\n case \"TEXT_MESSAGE_CONTENT\": {\n const msg = messagesById.get(event.messageId);\n if (msg) {\n msg.content = (msg.content ?? \"\") + (event.delta ?? \"\");\n }\n break;\n }\n\n case \"TEXT_MESSAGE_CHUNK\": {\n // Chunk format: combined start+content. First chunk creates the\n // message, subsequent chunks append delta to content.\n if (event.messageId) {\n const existing = messagesById.get(event.messageId);\n if (existing) {\n existing.content = (existing.content ?? \"\") + (event.delta ?? \"\");\n } else {\n messagesById.set(event.messageId, {\n id: event.messageId,\n role: event.role ?? \"assistant\",\n content: event.delta ?? \"\",\n });\n }\n }\n break;\n }\n\n case \"TOOL_CALL_START\": {\n const tc: ToolCall = {\n id: event.toolCallId,\n name: event.toolCallName,\n args: \"\",\n };\n toolCallsById.set(event.toolCallId, tc);\n linkToolCallParent(event.toolCallId, event.parentMessageId);\n break;\n }\n\n case \"TOOL_CALL_ARGS\": {\n const tc = toolCallsById.get(event.toolCallId);\n if (tc) {\n tc.args += event.delta ?? \"\";\n }\n break;\n }\n\n case \"TOOL_CALL_CHUNK\": {\n // Chunk format: combined start+args. First chunk for a given\n // toolCallId creates the tool call, subsequent chunks append delta.\n if (event.toolCallId) {\n let tc = toolCallsById.get(event.toolCallId);\n if (!tc) {\n tc = {\n id: event.toolCallId,\n name: event.toolCallName ?? \"\",\n args: \"\",\n };\n toolCallsById.set(event.toolCallId, tc);\n linkToolCallParent(event.toolCallId, event.parentMessageId);\n }\n if (event.toolCallName) {\n tc.name = event.toolCallName;\n }\n tc.args += event.delta ?? \"\";\n }\n break;\n }\n\n case \"TOOL_CALL_END\": {\n const tc = toolCallsById.get(event.toolCallId);\n const parentId = toolCallParent.get(event.toolCallId);\n if (tc && parentId) {\n const parent = messagesById.get(parentId);\n if (parent) {\n parent.toolCalls = parent.toolCalls ?? [];\n parent.toolCalls.push(tc);\n }\n }\n break;\n }\n\n case \"TOOL_CALL_RESULT\": {\n // langchain-mcp-adapters may send content as an array of\n // {type:\"text\", text:string} objects instead of a plain string.\n let resultContent = event.content;\n if (Array.isArray(resultContent)) {\n resultContent = resultContent\n .filter((part: any) => part && typeof part.text === \"string\")\n .map((part: any) => part.text)\n .join(\"\");\n }\n messagesById.set(event.messageId, {\n id: event.messageId,\n role: \"tool\",\n content: resultContent,\n toolCallId: event.toolCallId,\n });\n break;\n }\n }\n }\n\n // Attach any tool calls not yet linked to their parent message.\n // This handles TOOL_CALL_CHUNK flows which don't emit TOOL_CALL_END.\n for (const [toolCallId, tc] of toolCallsById) {\n const parentId = toolCallParent.get(toolCallId);\n if (!parentId) continue;\n const parent = messagesById.get(parentId);\n if (!parent) continue;\n const alreadyAttached = parent.toolCalls?.some((t) => t.id === tc.id);\n if (!alreadyAttached) {\n parent.toolCalls = parent.toolCalls ?? [];\n parent.toolCalls.push(tc);\n }\n }\n\n // Prefer MESSAGES_SNAPSHOT if present (contains full history).\n // Otherwise reconstruct from individual events.\n const messages = snapshotMessages ?? [...messagesById.values()];\n\n return { messages, threadId, runId };\n}\n"],"mappings":";;;;;;;AA4BA,eAAsB,iBACpB,UACA,SAA+B,kBAAkB,EACvB;AAE1B,KAAI,EADgB,SAAS,QAAQ,IAAI,eAAe,IAAI,IAC3C,SAAS,oBAAoB,CAC5C,QAAO,EAAE,UAAU,EAAE,EAAE;CAGzB,IAAI;AACJ,KAAI;AACF,SAAO,MAAM,SAAS,MAAM;SACtB;AACN,SAAO,KAAK,6DAA6D;AACzE,SAAO,EAAE,UAAU,EAAE,EAAE;;AAGzB,KAAI,CAAC,KAAK,MAAM,CACd,QAAO,EAAE,UAAU,EAAE,EAAE;CAGzB,IAAI;CACJ,IAAI;CACJ,MAAM,+BAAe,IAAI,KAAsB;CAC/C,MAAM,gCAAgB,IAAI,KAAuB;CACjD,MAAM,iCAAiB,IAAI,KAAqB;CAChD,IAAI;CAMJ,MAAM,sBAAsB,YAAoB,oBAA6B;EAC3E,MAAM,SAAS,kBACX,aAAa,IAAI,gBAAgB,GACjC;EACJ,MAAM,WACJ,oBAAoB,CAAC,UAAU,OAAO,SAAS,eAC3C,kBACA;AACN,MAAI,CAAC,aAAa,IAAI,SAAS,CAC7B,cAAa,IAAI,UAAU;GAAE,IAAI;GAAU,MAAM;GAAa,CAAC;AAEjE,iBAAe,IAAI,YAAY,SAAS;;AAG1C,MAAK,MAAM,QAAQ,KAAK,MAAM,KAAK,EAAE;EACnC,MAAM,UAAU,KAAK,MAAM;AAC3B,MAAI,CAAC,QAAQ,WAAW,QAAQ,CAAE;EAElC,IAAI;AACJ,MAAI;AACF,WAAQ,KAAK,MAAM,QAAQ,MAAM,EAAE,CAAC,MAAM,CAAC;UACrC;AACN;;AAGF,UAAQ,MAAM,MAAd;GACE,KAAK;AACH,eAAW,MAAM;AACjB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BAAiB;IACpB,MAAM,KAAK,cAAc,IAAI,MAAM,WAAW;IAC9C,MAAM,WAAW,eAAe,IAAI,MAAM,WAAW;AACrD,QAAI,MAAM,UAAU;KAClB,MAAM,SAAS,aAAa,IAAI,SAAS;AACzC,SAAI,QAAQ;AACV,aAAO,YAAY,OAAO,aAAa,EAAE;AACzC,aAAO,UAAU,KAAK,GAAG;;;AAG7B;;GAGF,KAAK,oBAAoB;IAGvB,IAAI,gBAAgB,MAAM;AAC1B,QAAI,MAAM,QAAQ,cAAc,CAC9B,iBAAgB,cACb,QAAQ,SAAc,QAAQ,OAAO,KAAK,SAAS,SAAS,CAC5D,KAAK,SAAc,KAAK,KAAK,CAC7B,KAAK,GAAG;AAEb,iBAAa,IAAI,MAAM,WAAW;KAChC,IAAI,MAAM;KACV,MAAM;KACN,SAAS;KACT,YAAY,MAAM;KACnB,CAAC;AACF;;;;AAON,MAAK,MAAM,CAAC,YAAY,OAAO,eAAe;EAC5C,MAAM,WAAW,eAAe,IAAI,WAAW;AAC/C,MAAI,CAAC,SAAU;EACf,MAAM,SAAS,aAAa,IAAI,SAAS;AACzC,MAAI,CAAC,OAAQ;AAEb,MAAI,CADoB,OAAO,WAAW,MAAM,MAAM,EAAE,OAAO,GAAG,GAAG,EAC/C;AACpB,UAAO,YAAY,OAAO,aAAa,EAAE;AACzC,UAAO,UAAU,KAAK,GAAG;;;AAQ7B,QAAO;EAAE,UAFQ,oBAAoB,CAAC,GAAG,aAAa,QAAQ,CAAC;EAE5C;EAAU;EAAO"}
1
+ {"version":3,"file":"middleware-sse-parser.mjs","names":[],"sources":["../../../src/runtime/core/middleware-sse-parser.ts"],"sourcesContent":["import { getRuntimeLogger } from \"./logger\";\nimport type { CopilotKitRuntimeLogger } from \"./logger\";\n\nexport interface ParsedSSEResult {\n messages: Message[];\n threadId?: string;\n runId?: string;\n}\n\n/** Minimal message shape reconstructed from AG-UI events. */\nexport interface Message {\n id: string;\n role: string;\n content?: string;\n toolCalls?: ToolCall[];\n toolCallId?: string;\n}\n\ninterface ToolCall {\n id: string;\n name: string;\n args: string;\n}\n\n/**\n * Parse a cloned SSE Response body into structured messages.\n * Returns empty results for non-SSE responses.\n */\nexport async function parseSSEResponse(\n response: Response,\n logger: CopilotKitRuntimeLogger = getRuntimeLogger(),\n): Promise<ParsedSSEResult> {\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n if (!contentType.includes(\"text/event-stream\")) {\n return { messages: [] };\n }\n\n let text: string;\n try {\n text = await response.text();\n } catch {\n logger.warn(\"Failed to read SSE response body in afterRequestMiddleware\");\n return { messages: [] };\n }\n\n if (!text.trim()) {\n return { messages: [] };\n }\n\n let threadId: string | undefined;\n let runId: string | undefined;\n const messagesById = new Map<string, Message>();\n const toolCallsById = new Map<string, ToolCall>();\n const toolCallParent = new Map<string, string>(); // toolCallId → messageId\n let snapshotMessages: Message[] | undefined;\n\n // Link a tool call to its assistant message the way @ag-ui/client does. A\n // tool-only turn streams no TEXT_MESSAGE_START, so the parent may not exist\n // yet; create it, keyed by toolCallId when parentMessageId is missing or\n // names a non-assistant message.\n const linkToolCallParent = (toolCallId: string, parentMessageId?: string) => {\n const parent = parentMessageId\n ? messagesById.get(parentMessageId)\n : undefined;\n const parentId =\n parentMessageId && (!parent || parent.role === \"assistant\")\n ? parentMessageId\n : toolCallId;\n if (!messagesById.has(parentId)) {\n messagesById.set(parentId, { id: parentId, role: \"assistant\" });\n }\n toolCallParent.set(toolCallId, parentId);\n };\n\n for (const line of text.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed.startsWith(\"data:\")) continue;\n\n let event: Record<string, any>;\n try {\n event = JSON.parse(trimmed.slice(5).trim());\n } catch {\n continue;\n }\n\n switch (event.type) {\n case \"RUN_STARTED\":\n threadId = event.threadId;\n runId = event.runId;\n break;\n\n case \"MESSAGES_SNAPSHOT\":\n if (Array.isArray(event.messages)) {\n snapshotMessages = event.messages;\n }\n break;\n\n case \"TEXT_MESSAGE_START\":\n messagesById.set(event.messageId, {\n id: event.messageId,\n role: event.role ?? \"assistant\",\n content: \"\",\n });\n break;\n\n case \"TEXT_MESSAGE_CONTENT\": {\n const msg = messagesById.get(event.messageId);\n if (msg) {\n msg.content = (msg.content ?? \"\") + (event.delta ?? \"\");\n }\n break;\n }\n\n case \"TEXT_MESSAGE_CHUNK\": {\n // Chunk format: combined start+content. First chunk creates the\n // message, subsequent chunks append delta to content.\n if (event.messageId) {\n const existing = messagesById.get(event.messageId);\n if (existing) {\n existing.content = (existing.content ?? \"\") + (event.delta ?? \"\");\n } else {\n messagesById.set(event.messageId, {\n id: event.messageId,\n role: event.role ?? \"assistant\",\n content: event.delta ?? \"\",\n });\n }\n }\n break;\n }\n\n case \"TOOL_CALL_START\": {\n const tc: ToolCall = {\n id: event.toolCallId,\n name: event.toolCallName,\n args: \"\",\n };\n toolCallsById.set(event.toolCallId, tc);\n linkToolCallParent(event.toolCallId, event.parentMessageId);\n break;\n }\n\n case \"TOOL_CALL_ARGS\": {\n const tc = toolCallsById.get(event.toolCallId);\n if (tc) {\n tc.args += event.delta ?? \"\";\n }\n break;\n }\n\n case \"TOOL_CALL_CHUNK\": {\n // Chunk format: combined start+args. First chunk for a given\n // toolCallId creates the tool call, subsequent chunks append delta.\n if (event.toolCallId) {\n let tc = toolCallsById.get(event.toolCallId);\n if (!tc) {\n tc = {\n id: event.toolCallId,\n name: event.toolCallName ?? \"\",\n args: \"\",\n };\n toolCallsById.set(event.toolCallId, tc);\n linkToolCallParent(event.toolCallId, event.parentMessageId);\n }\n if (event.toolCallName) {\n tc.name = event.toolCallName;\n }\n tc.args += event.delta ?? \"\";\n }\n break;\n }\n\n case \"TOOL_CALL_END\": {\n const tc = toolCallsById.get(event.toolCallId);\n const parentId = toolCallParent.get(event.toolCallId);\n if (tc && parentId) {\n const parent = messagesById.get(parentId);\n if (parent) {\n parent.toolCalls = parent.toolCalls ?? [];\n parent.toolCalls.push(tc);\n }\n }\n break;\n }\n\n case \"TOOL_CALL_RESULT\": {\n // langchain-mcp-adapters may send content as an array of\n // {type:\"text\", text:string} objects instead of a plain string.\n let resultContent = event.content;\n if (Array.isArray(resultContent)) {\n resultContent = resultContent\n .filter((part: any) => part && typeof part.text === \"string\")\n .map((part: any) => part.text)\n .join(\"\");\n }\n messagesById.set(event.messageId, {\n id: event.messageId,\n role: \"tool\",\n content: resultContent,\n toolCallId: event.toolCallId,\n });\n break;\n }\n }\n }\n\n // Attach any tool calls not yet linked to their parent message.\n // This handles TOOL_CALL_CHUNK flows which don't emit TOOL_CALL_END.\n for (const [toolCallId, tc] of toolCallsById) {\n const parentId = toolCallParent.get(toolCallId);\n if (!parentId) continue;\n const parent = messagesById.get(parentId);\n if (!parent) continue;\n const alreadyAttached = parent.toolCalls?.some((t) => t.id === tc.id);\n if (!alreadyAttached) {\n parent.toolCalls = parent.toolCalls ?? [];\n parent.toolCalls.push(tc);\n }\n }\n\n // Prefer MESSAGES_SNAPSHOT if present (contains full history).\n // Otherwise reconstruct from individual events.\n const messages = snapshotMessages ?? [...messagesById.values()];\n\n return { messages, threadId, runId };\n}\n"],"mappings":";;;;;;;AA4BA,eAAsB,iBACpB,UACA,SAAkC,kBAAkB,EAC1B;AAE1B,KAAI,EADgB,SAAS,QAAQ,IAAI,eAAe,IAAI,IAC3C,SAAS,oBAAoB,CAC5C,QAAO,EAAE,UAAU,EAAE,EAAE;CAGzB,IAAI;AACJ,KAAI;AACF,SAAO,MAAM,SAAS,MAAM;SACtB;AACN,SAAO,KAAK,6DAA6D;AACzE,SAAO,EAAE,UAAU,EAAE,EAAE;;AAGzB,KAAI,CAAC,KAAK,MAAM,CACd,QAAO,EAAE,UAAU,EAAE,EAAE;CAGzB,IAAI;CACJ,IAAI;CACJ,MAAM,+BAAe,IAAI,KAAsB;CAC/C,MAAM,gCAAgB,IAAI,KAAuB;CACjD,MAAM,iCAAiB,IAAI,KAAqB;CAChD,IAAI;CAMJ,MAAM,sBAAsB,YAAoB,oBAA6B;EAC3E,MAAM,SAAS,kBACX,aAA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OAAO,WAAW,MAAM,MAAM,EAAE,OAAO,GAAG,GAAG,EAC/C;AACpB,UAAO,YAAY,OAAO,aAAa,EAAE;AACzC,UAAO,UAAU,KAAK,GAAG;;;AAQ7B,QAAO;EAAE,UAFQ,oBAAoB,CAAC,GAAG,aAAa,QAAQ,CAAC;EAE5C;EAAU;EAAO"}
@@ -1 +1 @@
1
- {"version":3,"file":"middleware.cjs","names":["getRuntimeLogger","parseSSEResponse"],"sources":["../../../src/runtime/core/middleware.ts"],"sourcesContent":["/**\n * Middleware support for CopilotKit Runtime.\n *\n * A middleware hook can be provided as either:\n * 1. A **callback function** executed in-process.\n * 2. A **webhook URL** (http/https). The runtime will `POST` a JSON payload\n * to the URL and, for *before* hooks, accept an optional modified\n * `Request` object in the response body.\n *\n * Two lifecycle hooks are available:\n * • `BEFORE_REQUEST` – runs *before* the request handler.\n * • `AFTER_REQUEST` – runs *after* the handler returns a `Response`.\n */\n\nimport type { CopilotRuntimeLike } from \"./runtime\";\nimport type { MaybePromise } from \"@copilotkit/shared\";\nimport { getRuntimeLogger } from \"./logger\";\nimport { parseSSEResponse } from \"./middleware-sse-parser\";\nimport type { Message } from \"./middleware-sse-parser\";\n\n/* ------------------------------------------------------------------------------------------------\n * Public types\n * --------------------------------------------------------------------------------------------- */\n\nexport interface BeforeRequestMiddlewareParameters {\n runtime: CopilotRuntimeLike;\n request: Request;\n path: string;\n}\nexport interface AfterRequestMiddlewareParameters {\n runtime: CopilotRuntimeLike;\n response: Response;\n path: string;\n /** Reconstructed messages from the SSE stream (empty for non-SSE responses). */\n messages?: Message[];\n /** Thread ID extracted from the RUN_STARTED event. */\n threadId?: string;\n /** Run ID extracted from the RUN_STARTED event. */\n runId?: string;\n}\n\nexport type BeforeRequestMiddlewareFn = (\n params: BeforeRequestMiddlewareParameters,\n) => MaybePromise<Request | void>;\nexport type AfterRequestMiddlewareFn = (\n params: AfterRequestMiddlewareParameters,\n) => MaybePromise<void>;\n\n/**\n * A middleware value can be either a callback function or a webhook URL.\n */\nexport type BeforeRequestMiddleware = BeforeRequestMiddlewareFn;\nexport type AfterRequestMiddleware = AfterRequestMiddlewareFn;\n\n/** Lifecycle events emitted to webhook middleware. */\nexport enum CopilotKitMiddlewareEvent {\n BeforeRequest = \"BEFORE_REQUEST\",\n AfterRequest = \"AFTER_REQUEST\",\n}\n\n/** Stages used by the Middleware Webhook Protocol */\n/** Stages used by the CopilotKit webhook protocol */\nexport enum WebhookStage {\n BeforeRequest = \"before_request\",\n AfterRequest = \"after_request\",\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Internal helpers – (de)serialisation\n * --------------------------------------------------------------------------------------------- */\n\nexport async function callBeforeRequestMiddleware({\n runtime,\n request,\n path,\n}: BeforeRequestMiddlewareParameters): Promise<Request | void> {\n const mw = runtime.beforeRequestMiddleware;\n if (!mw) return;\n\n // Function-based middleware (in-process)\n if (typeof mw === \"function\") {\n return (mw as BeforeRequestMiddlewareFn)({ runtime, request, path });\n }\n\n getRuntimeLogger(runtime).warn(\n { mw },\n \"Unsupported beforeRequestMiddleware value – skipped\",\n );\n return;\n}\n\nexport async function callAfterRequestMiddleware({\n runtime,\n response,\n path,\n}: {\n runtime: CopilotRuntimeLike;\n response: Response;\n path: string;\n}): Promise<void> {\n const mw = runtime.afterRequestMiddleware;\n if (!mw) return;\n\n const logger = getRuntimeLogger(runtime);\n const { messages, threadId, runId } = await parseSSEResponse(\n response,\n logger,\n );\n\n if (typeof mw === \"function\") {\n return (mw as AfterRequestMiddlewareFn)({\n runtime,\n response,\n path,\n messages,\n threadId,\n runId,\n });\n }\n\n logger.warn({ mw }, \"Unsupported afterRequestMiddleware value – skipped\");\n}\n"],"mappings":";;;;AAuEA,eAAsB,4BAA4B,EAChD,SACA,SACA,QAC6D;CAC7D,MAAM,KAAK,QAAQ;AACnB,KAAI,CAAC,GAAI;AAGT,KAAI,OAAO,OAAO,WAChB,QAAQ,GAAiC;EAAE;EAAS;EAAS;EAAM,CAAC;AAGtE,iCAAiB,QAAQ,CAAC,KACxB,EAAE,IAAI,EACN,sDACD;;AAIH,eAAsB,2BAA2B,EAC/C,SACA,UACA,QAKgB;CAChB,MAAM,KAAK,QAAQ;AACnB,KAAI,CAAC,GAAI;CAET,MAAM,SAASA,gCAAiB,QAAQ;CACxC,MAAM,EAAE,UAAU,UAAU,UAAU,MAAMC,+CAC1C,UACA,OACD;AAED,KAAI,OAAO,OAAO,WAChB,QAAQ,GAAgC;EACtC;EACA;EACA;EACA;EACA;EACA;EACD,CAAC;AAGJ,QAAO,KAAK,EAAE,IAAI,EAAE,qDAAqD"}
1
+ {"version":3,"file":"middleware.cjs","names":["getRuntimeLogger","parseSSEResponse"],"sources":["../../../src/runtime/core/middleware.ts"],"sourcesContent":["/**\n * Middleware support for CopilotKit Runtime.\n *\n * A middleware hook can be provided as either:\n * 1. A **callback function** executed in-process.\n * 2. A **webhook URL** (http/https). The runtime will `POST` a JSON payload\n * to the URL and, for *before* hooks, accept an optional modified\n * `Request` object in the response body.\n *\n * Two lifecycle hooks are available:\n * • `BEFORE_REQUEST` – runs *before* the request handler.\n * • `AFTER_REQUEST` – runs *after* the handler returns a `Response`.\n */\n\nimport type { CopilotKitRuntimeLike } from \"./runtime\";\nimport type { MaybePromise } from \"@copilotkit/shared\";\nimport { getRuntimeLogger } from \"./logger\";\nimport { parseSSEResponse } from \"./middleware-sse-parser\";\nimport type { Message } from \"./middleware-sse-parser\";\n\n/* ------------------------------------------------------------------------------------------------\n * Public types\n * --------------------------------------------------------------------------------------------- */\n\nexport interface BeforeRequestMiddlewareParameters {\n runtime: CopilotKitRuntimeLike;\n request: Request;\n path: string;\n}\nexport interface AfterRequestMiddlewareParameters {\n runtime: CopilotKitRuntimeLike;\n response: Response;\n path: string;\n /** Reconstructed messages from the SSE stream (empty for non-SSE responses). */\n messages?: Message[];\n /** Thread ID extracted from the RUN_STARTED event. */\n threadId?: string;\n /** Run ID extracted from the RUN_STARTED event. */\n runId?: string;\n}\n\nexport type BeforeRequestMiddlewareFn = (\n params: BeforeRequestMiddlewareParameters,\n) => MaybePromise<Request | void>;\nexport type AfterRequestMiddlewareFn = (\n params: AfterRequestMiddlewareParameters,\n) => MaybePromise<void>;\n\n/**\n * A middleware value can be either a callback function or a webhook URL.\n */\nexport type BeforeRequestMiddleware = BeforeRequestMiddlewareFn;\nexport type AfterRequestMiddleware = AfterRequestMiddlewareFn;\n\n/** Lifecycle events emitted to webhook middleware. */\nexport enum CopilotKitMiddlewareEvent {\n BeforeRequest = \"BEFORE_REQUEST\",\n AfterRequest = \"AFTER_REQUEST\",\n}\n\n/** Stages used by the Middleware Webhook Protocol */\n/** Stages used by the CopilotKit webhook protocol */\nexport enum WebhookStage {\n BeforeRequest = \"before_request\",\n AfterRequest = \"after_request\",\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Internal helpers – (de)serialisation\n * --------------------------------------------------------------------------------------------- */\n\nexport async function callBeforeRequestMiddleware({\n runtime,\n request,\n path,\n}: BeforeRequestMiddlewareParameters): Promise<Request | void> {\n const mw = runtime.beforeRequestMiddleware;\n if (!mw) return;\n\n // Function-based middleware (in-process)\n if (typeof mw === \"function\") {\n return (mw as BeforeRequestMiddlewareFn)({ runtime, request, path });\n }\n\n getRuntimeLogger(runtime).warn(\n { mw },\n \"Unsupported beforeRequestMiddleware value – skipped\",\n );\n return;\n}\n\nexport async function callAfterRequestMiddleware({\n runtime,\n response,\n path,\n}: {\n runtime: CopilotKitRuntimeLike;\n response: Response;\n path: string;\n}): Promise<void> {\n const mw = runtime.afterRequestMiddleware;\n if (!mw) return;\n\n const logger = getRuntimeLogger(runtime);\n const { messages, threadId, runId } = await parseSSEResponse(\n response,\n logger,\n );\n\n if (typeof mw === \"function\") {\n return (mw as AfterRequestMiddlewareFn)({\n runtime,\n response,\n path,\n messages,\n threadId,\n runId,\n });\n }\n\n logger.warn({ mw }, \"Unsupported afterRequestMiddleware value – skipped\");\n}\n"],"mappings":";;;;AAuEA,eAAsB,4BAA4B,EAChD,SACA,SACA,QAC6D;CAC7D,MAAM,KAAK,QAAQ;AACnB,KAAI,CAAC,GAAI;AAGT,KAAI,OAAO,OAAO,WAChB,QAAQ,GAAiC;EAAE;EAAS;EAAS;EAAM,CAAC;AAGtE,iCAAiB,QAAQ,CAAC,KACxB,EAAE,IAAI,EACN,sDACD;;AAIH,eAAsB,2BAA2B,EAC/C,SACA,UACA,QAKgB;CAChB,MAAM,KAAK,QAAQ;AACnB,KAAI,CAAC,GAAI;CAET,MAAM,SAASA,gCAAiB,QAAQ;CACxC,MAAM,EAAE,UAAU,UAAU,UAAU,MAAMC,+CAC1C,UACA,OACD;AAED,KAAI,OAAO,OAAO,WAChB,QAAQ,GAAgC;EACtC;EACA;EACA;EACA;EACA;EACA;EACD,CAAC;AAGJ,QAAO,KAAK,EAAE,IAAI,EAAE,qDAAqD"}
@@ -1,15 +1,15 @@
1
1
  import { Message } from "./middleware-sse-parser.cjs";
2
- import { CopilotRuntimeLike } from "./runtime.cjs";
2
+ import { CopilotKitRuntimeLike } from "./runtime.cjs";
3
3
  import { MaybePromise } from "@copilotkit/shared";
4
4
 
5
5
  //#region src/runtime/core/middleware.d.ts
6
6
  interface BeforeRequestMiddlewareParameters {
7
- runtime: CopilotRuntimeLike;
7
+ runtime: CopilotKitRuntimeLike;
8
8
  request: Request;
9
9
  path: string;
10
10
  }
11
11
  interface AfterRequestMiddlewareParameters {
12
- runtime: CopilotRuntimeLike;
12
+ runtime: CopilotKitRuntimeLike;
13
13
  response: Response;
14
14
  path: string;
15
15
  /** Reconstructed messages from the SSE stream (empty for non-SSE responses). */
@@ -1 +1 @@
1
- {"version":3,"file":"middleware.d.cts","names":[],"sources":["../../../src/runtime/core/middleware.ts"],"mappings":";;;;;UAwBiB,iCAAA;EACf,OAAA,EAAS,kBAAA;EACT,OAAA,EAAS,OAAA;EACT,IAAA;AAAA;AAAA,UAEe,gCAAA;EACf,OAAA,EAAS,kBAAA;EACT,QAAA,EAAU,QAAA;EACV,IAAA;EAFS;EAIT,QAAA,GAAW,OAAA;EAHD;EAKV,QAAA;EAFA;EAIA,KAAA;AAAA;AAAA,KAGU,yBAAA,IACV,MAAA,EAAQ,iCAAA,KACL,YAAA,CAAa,OAAA;AAAA,KACN,wBAAA,IACV,MAAA,EAAQ,gCAAA,KACL,YAAA;;AALL;;KAUY,uBAAA,GAA0B,yBAAA;AAAA,KAC1B,sBAAA,GAAyB,wBAAA"}
1
+ {"version":3,"file":"middleware.d.cts","names":[],"sources":["../../../src/runtime/core/middleware.ts"],"mappings":";;;;;UAwBiB,iCAAA;EACf,OAAA,EAAS,qBAAA;EACT,OAAA,EAAS,OAAA;EACT,IAAA;AAAA;AAAA,UAEe,gCAAA;EACf,OAAA,EAAS,qBAAA;EACT,QAAA,EAAU,QAAA;EACV,IAAA;EAFS;EAIT,QAAA,GAAW,OAAA;EAHD;EAKV,QAAA;EAFA;EAIA,KAAA;AAAA;AAAA,KAGU,yBAAA,IACV,MAAA,EAAQ,iCAAA,KACL,YAAA,CAAa,OAAA;AAAA,KACN,wBAAA,IACV,MAAA,EAAQ,gCAAA,KACL,YAAA;;AALL;;KAUY,uBAAA,GAA0B,yBAAA;AAAA,KAC1B,sBAAA,GAAyB,wBAAA"}
@@ -1,15 +1,15 @@
1
1
  import { Message } from "./middleware-sse-parser.mjs";
2
- import { CopilotRuntimeLike } from "./runtime.mjs";
2
+ import { CopilotKitRuntimeLike } from "./runtime.mjs";
3
3
  import { MaybePromise } from "@copilotkit/shared";
4
4
 
5
5
  //#region src/runtime/core/middleware.d.ts
6
6
  interface BeforeRequestMiddlewareParameters {
7
- runtime: CopilotRuntimeLike;
7
+ runtime: CopilotKitRuntimeLike;
8
8
  request: Request;
9
9
  path: string;
10
10
  }
11
11
  interface AfterRequestMiddlewareParameters {
12
- runtime: CopilotRuntimeLike;
12
+ runtime: CopilotKitRuntimeLike;
13
13
  response: Response;
14
14
  path: string;
15
15
  /** Reconstructed messages from the SSE stream (empty for non-SSE responses). */
@@ -1 +1 @@
1
- {"version":3,"file":"middleware.d.mts","names":[],"sources":["../../../src/runtime/core/middleware.ts"],"mappings":";;;;;UAwBiB,iCAAA;EACf,OAAA,EAAS,kBAAA;EACT,OAAA,EAAS,OAAA;EACT,IAAA;AAAA;AAAA,UAEe,gCAAA;EACf,OAAA,EAAS,kBAAA;EACT,QAAA,EAAU,QAAA;EACV,IAAA;EAFS;EAIT,QAAA,GAAW,OAAA;EAHD;EAKV,QAAA;EAFA;EAIA,KAAA;AAAA;AAAA,KAGU,yBAAA,IACV,MAAA,EAAQ,iCAAA,KACL,YAAA,CAAa,OAAA;AAAA,KACN,wBAAA,IACV,MAAA,EAAQ,gCAAA,KACL,YAAA;;AALL;;KAUY,uBAAA,GAA0B,yBAAA;AAAA,KAC1B,sBAAA,GAAyB,wBAAA"}
1
+ {"version":3,"file":"middleware.d.mts","names":[],"sources":["../../../src/runtime/core/middleware.ts"],"mappings":";;;;;UAwBiB,iCAAA;EACf,OAAA,EAAS,qBAAA;EACT,OAAA,EAAS,OAAA;EACT,IAAA;AAAA;AAAA,UAEe,gCAAA;EACf,OAAA,EAAS,qBAAA;EACT,QAAA,EAAU,QAAA;EACV,IAAA;EAFS;EAIT,QAAA,GAAW,OAAA;EAHD;EAKV,QAAA;EAFA;EAIA,KAAA;AAAA;AAAA,KAGU,yBAAA,IACV,MAAA,EAAQ,iCAAA,KACL,YAAA,CAAa,OAAA;AAAA,KACN,wBAAA,IACV,MAAA,EAAQ,gCAAA,KACL,YAAA;;AALL;;KAUY,uBAAA,GAA0B,yBAAA;AAAA,KAC1B,sBAAA,GAAyB,wBAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"middleware.mjs","names":[],"sources":["../../../src/runtime/core/middleware.ts"],"sourcesContent":["/**\n * Middleware support for CopilotKit Runtime.\n *\n * A middleware hook can be provided as either:\n * 1. A **callback function** executed in-process.\n * 2. A **webhook URL** (http/https). The runtime will `POST` a JSON payload\n * to the URL and, for *before* hooks, accept an optional modified\n * `Request` object in the response body.\n *\n * Two lifecycle hooks are available:\n * • `BEFORE_REQUEST` – runs *before* the request handler.\n * • `AFTER_REQUEST` – runs *after* the handler returns a `Response`.\n */\n\nimport type { CopilotRuntimeLike } from \"./runtime\";\nimport type { MaybePromise } from \"@copilotkit/shared\";\nimport { getRuntimeLogger } from \"./logger\";\nimport { parseSSEResponse } from \"./middleware-sse-parser\";\nimport type { Message } from \"./middleware-sse-parser\";\n\n/* ------------------------------------------------------------------------------------------------\n * Public types\n * --------------------------------------------------------------------------------------------- */\n\nexport interface BeforeRequestMiddlewareParameters {\n runtime: CopilotRuntimeLike;\n request: Request;\n path: string;\n}\nexport interface AfterRequestMiddlewareParameters {\n runtime: CopilotRuntimeLike;\n response: Response;\n path: string;\n /** Reconstructed messages from the SSE stream (empty for non-SSE responses). */\n messages?: Message[];\n /** Thread ID extracted from the RUN_STARTED event. */\n threadId?: string;\n /** Run ID extracted from the RUN_STARTED event. */\n runId?: string;\n}\n\nexport type BeforeRequestMiddlewareFn = (\n params: BeforeRequestMiddlewareParameters,\n) => MaybePromise<Request | void>;\nexport type AfterRequestMiddlewareFn = (\n params: AfterRequestMiddlewareParameters,\n) => MaybePromise<void>;\n\n/**\n * A middleware value can be either a callback function or a webhook URL.\n */\nexport type BeforeRequestMiddleware = BeforeRequestMiddlewareFn;\nexport type AfterRequestMiddleware = AfterRequestMiddlewareFn;\n\n/** Lifecycle events emitted to webhook middleware. */\nexport enum CopilotKitMiddlewareEvent {\n BeforeRequest = \"BEFORE_REQUEST\",\n AfterRequest = \"AFTER_REQUEST\",\n}\n\n/** Stages used by the Middleware Webhook Protocol */\n/** Stages used by the CopilotKit webhook protocol */\nexport enum WebhookStage {\n BeforeRequest = \"before_request\",\n AfterRequest = \"after_request\",\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Internal helpers – (de)serialisation\n * --------------------------------------------------------------------------------------------- */\n\nexport async function callBeforeRequestMiddleware({\n runtime,\n request,\n path,\n}: BeforeRequestMiddlewareParameters): Promise<Request | void> {\n const mw = runtime.beforeRequestMiddleware;\n if (!mw) return;\n\n // Function-based middleware (in-process)\n if (typeof mw === \"function\") {\n return (mw as BeforeRequestMiddlewareFn)({ runtime, request, path });\n }\n\n getRuntimeLogger(runtime).warn(\n { mw },\n \"Unsupported beforeRequestMiddleware value – skipped\",\n );\n return;\n}\n\nexport async function callAfterRequestMiddleware({\n runtime,\n response,\n path,\n}: {\n runtime: CopilotRuntimeLike;\n response: Response;\n path: string;\n}): Promise<void> {\n const mw = runtime.afterRequestMiddleware;\n if (!mw) return;\n\n const logger = getRuntimeLogger(runtime);\n const { messages, threadId, runId } = await parseSSEResponse(\n response,\n logger,\n );\n\n if (typeof mw === \"function\") {\n return (mw as AfterRequestMiddlewareFn)({\n runtime,\n response,\n path,\n messages,\n threadId,\n runId,\n });\n }\n\n logger.warn({ mw }, \"Unsupported afterRequestMiddleware value – skipped\");\n}\n"],"mappings":";;;;AAuEA,eAAsB,4BAA4B,EAChD,SACA,SACA,QAC6D;CAC7D,MAAM,KAAK,QAAQ;AACnB,KAAI,CAAC,GAAI;AAGT,KAAI,OAAO,OAAO,WAChB,QAAQ,GAAiC;EAAE;EAAS;EAAS;EAAM,CAAC;AAGtE,kBAAiB,QAAQ,CAAC,KACxB,EAAE,IAAI,EACN,sDACD;;AAIH,eAAsB,2BAA2B,EAC/C,SACA,UACA,QAKgB;CAChB,MAAM,KAAK,QAAQ;AACnB,KAAI,CAAC,GAAI;CAET,MAAM,SAAS,iBAAiB,QAAQ;CACxC,MAAM,EAAE,UAAU,UAAU,UAAU,MAAM,iBAC1C,UACA,OACD;AAED,KAAI,OAAO,OAAO,WAChB,QAAQ,GAAgC;EACtC;EACA;EACA;EACA;EACA;EACA;EACD,CAAC;AAGJ,QAAO,KAAK,EAAE,IAAI,EAAE,qDAAqD"}
1
+ {"version":3,"file":"middleware.mjs","names":[],"sources":["../../../src/runtime/core/middleware.ts"],"sourcesContent":["/**\n * Middleware support for CopilotKit Runtime.\n *\n * A middleware hook can be provided as either:\n * 1. A **callback function** executed in-process.\n * 2. A **webhook URL** (http/https). The runtime will `POST` a JSON payload\n * to the URL and, for *before* hooks, accept an optional modified\n * `Request` object in the response body.\n *\n * Two lifecycle hooks are available:\n * • `BEFORE_REQUEST` – runs *before* the request handler.\n * • `AFTER_REQUEST` – runs *after* the handler returns a `Response`.\n */\n\nimport type { CopilotKitRuntimeLike } from \"./runtime\";\nimport type { MaybePromise } from \"@copilotkit/shared\";\nimport { getRuntimeLogger } from \"./logger\";\nimport { parseSSEResponse } from \"./middleware-sse-parser\";\nimport type { Message } from \"./middleware-sse-parser\";\n\n/* ------------------------------------------------------------------------------------------------\n * Public types\n * --------------------------------------------------------------------------------------------- */\n\nexport interface BeforeRequestMiddlewareParameters {\n runtime: CopilotKitRuntimeLike;\n request: Request;\n path: string;\n}\nexport interface AfterRequestMiddlewareParameters {\n runtime: CopilotKitRuntimeLike;\n response: Response;\n path: string;\n /** Reconstructed messages from the SSE stream (empty for non-SSE responses). */\n messages?: Message[];\n /** Thread ID extracted from the RUN_STARTED event. */\n threadId?: string;\n /** Run ID extracted from the RUN_STARTED event. */\n runId?: string;\n}\n\nexport type BeforeRequestMiddlewareFn = (\n params: BeforeRequestMiddlewareParameters,\n) => MaybePromise<Request | void>;\nexport type AfterRequestMiddlewareFn = (\n params: AfterRequestMiddlewareParameters,\n) => MaybePromise<void>;\n\n/**\n * A middleware value can be either a callback function or a webhook URL.\n */\nexport type BeforeRequestMiddleware = BeforeRequestMiddlewareFn;\nexport type AfterRequestMiddleware = AfterRequestMiddlewareFn;\n\n/** Lifecycle events emitted to webhook middleware. */\nexport enum CopilotKitMiddlewareEvent {\n BeforeRequest = \"BEFORE_REQUEST\",\n AfterRequest = \"AFTER_REQUEST\",\n}\n\n/** Stages used by the Middleware Webhook Protocol */\n/** Stages used by the CopilotKit webhook protocol */\nexport enum WebhookStage {\n BeforeRequest = \"before_request\",\n AfterRequest = \"after_request\",\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Internal helpers – (de)serialisation\n * --------------------------------------------------------------------------------------------- */\n\nexport async function callBeforeRequestMiddleware({\n runtime,\n request,\n path,\n}: BeforeRequestMiddlewareParameters): Promise<Request | void> {\n const mw = runtime.beforeRequestMiddleware;\n if (!mw) return;\n\n // Function-based middleware (in-process)\n if (typeof mw === \"function\") {\n return (mw as BeforeRequestMiddlewareFn)({ runtime, request, path });\n }\n\n getRuntimeLogger(runtime).warn(\n { mw },\n \"Unsupported beforeRequestMiddleware value – skipped\",\n );\n return;\n}\n\nexport async function callAfterRequestMiddleware({\n runtime,\n response,\n path,\n}: {\n runtime: CopilotKitRuntimeLike;\n response: Response;\n path: string;\n}): Promise<void> {\n const mw = runtime.afterRequestMiddleware;\n if (!mw) return;\n\n const logger = getRuntimeLogger(runtime);\n const { messages, threadId, runId } = await parseSSEResponse(\n response,\n logger,\n );\n\n if (typeof mw === \"function\") {\n return (mw as AfterRequestMiddlewareFn)({\n runtime,\n response,\n path,\n messages,\n threadId,\n runId,\n });\n }\n\n logger.warn({ mw }, \"Unsupported afterRequestMiddleware value – skipped\");\n}\n"],"mappings":";;;;AAuEA,eAAsB,4BAA4B,EAChD,SACA,SACA,QAC6D;CAC7D,MAAM,KAAK,QAAQ;AACnB,KAAI,CAAC,GAAI;AAGT,KAAI,OAAO,OAAO,WAChB,QAAQ,GAAiC;EAAE;EAAS;EAAS;EAAM,CAAC;AAGtE,kBAAiB,QAAQ,CAAC,KACxB,EAAE,IAAI,EACN,sDACD;;AAIH,eAAsB,2BAA2B,EAC/C,SACA,UACA,QAKgB;CAChB,MAAM,KAAK,QAAQ;AACnB,KAAI,CAAC,GAAI;CAET,MAAM,SAAS,iBAAiB,QAAQ;CACxC,MAAM,EAAE,UAAU,UAAU,UAAU,MAAM,iBAC1C,UACA,OACD;AAED,KAAI,OAAO,OAAO,WAChB,QAAQ,GAAgC;EACtC;EACA;EACA;EACA;EACA;EACA;EACD,CAAC;AAGJ,QAAO,KAAK,EAAE,IAAI,EAAE,qDAAqD"}
@@ -1,7 +1,7 @@
1
1
 
2
2
  //#region src/runtime/core/package-info.ts
3
3
  const RUNTIME_PACKAGE_NAME = "@copilotkit/runtime";
4
- const RUNTIME_PACKAGE_VERSION = "2.0.0-rc.49";
4
+ const RUNTIME_PACKAGE_VERSION = "2.0.0-rc.50";
5
5
 
6
6
  //#endregion
7
7
  exports.RUNTIME_PACKAGE_NAME = RUNTIME_PACKAGE_NAME;
@@ -1,6 +1,6 @@
1
1
  //#region src/runtime/core/package-info.ts
2
2
  const RUNTIME_PACKAGE_NAME = "@copilotkit/runtime";
3
- const RUNTIME_PACKAGE_VERSION = "2.0.0-rc.49";
3
+ const RUNTIME_PACKAGE_VERSION = "2.0.0-rc.50";
4
4
 
5
5
  //#endregion
6
6
  export { RUNTIME_PACKAGE_NAME, RUNTIME_PACKAGE_VERSION };
@@ -1 +1 @@
1
- {"version":3,"file":"runtime-error-reporter.cjs","names":[],"sources":["../../../src/runtime/core/runtime-error-reporter.ts"],"sourcesContent":["import type {\n CopilotErrorEvent,\n CopilotErrorHandler,\n} from \"@copilotkit/shared\";\n\nimport type { CopilotRuntimeLike } from \"./runtime\";\n\nexport const runtimeErrorReporterOption = Symbol(\n \"copilotkit.runtimeErrorReporter\",\n);\n\nexport type RuntimeErrorPhase =\n | \"common\"\n | \"sse.factory\"\n | \"sse.subscription\"\n | \"intelligence.startup\"\n | \"intelligence.subscription\";\n\nexport interface RuntimeErrorReportParams {\n request: Request;\n error: unknown;\n operation: string;\n agentId?: string;\n threadId?: string;\n runId?: string;\n phase?: RuntimeErrorPhase;\n startTime?: number;\n}\n\nexport interface RuntimeErrorReporter {\n report(params: RuntimeErrorReportParams): void;\n}\n\nexport interface RuntimeErrorReporterOptions {\n [runtimeErrorReporterOption]?: RuntimeErrorReporter;\n}\n\nconst SENSITIVE_REQUEST_HEADERS = new Set([\n \"authorization\",\n \"proxy-authorization\",\n \"cookie\",\n \"set-cookie\",\n \"x-api-key\",\n \"api-key\",\n \"x-copilotcloud-public-api-key\",\n]);\n\nfunction sanitizeRequestHeaders(headers: Headers): Record<string, string> {\n const sanitized: Record<string, string> = {};\n headers.forEach((value, key) => {\n if (!SENSITIVE_REQUEST_HEADERS.has(key.toLowerCase())) {\n sanitized[key] = value;\n }\n });\n return sanitized;\n}\n\nexport function createRuntimeErrorReporter(\n handler?: CopilotErrorHandler,\n): RuntimeErrorReporter {\n return {\n report({\n request,\n error,\n operation,\n agentId,\n threadId,\n runId,\n phase,\n startTime,\n }) {\n if (!handler) return;\n\n try {\n const event: CopilotErrorEvent = {\n type: \"error\",\n timestamp: Date.now(),\n context: {\n source: \"runtime\",\n ...(threadId ? { threadId } : {}),\n ...(runId ? { runId } : {}),\n request: {\n operation,\n method: request.method,\n url: request.url,\n path: new URL(request.url).pathname,\n headers: sanitizeRequestHeaders(request.headers),\n startTime: startTime ?? Date.now(),\n },\n ...(agentId ? { agent: { name: agentId } } : {}),\n ...(phase ? { metadata: { phase } } : {}),\n },\n error,\n };\n\n const result = handler(event);\n if (result && typeof (result as Promise<void>).catch === \"function\") {\n void (result as Promise<void>).catch((handlerError) => {\n console.error(\n \"CopilotRuntime onError reporting failed:\",\n handlerError,\n );\n });\n }\n } catch (handlerError) {\n console.error(\"CopilotRuntime onError reporting failed:\", handlerError);\n }\n },\n };\n}\n\nexport function getRuntimeErrorReporterFromOptions(\n options: object,\n): RuntimeErrorReporter | undefined {\n return (options as RuntimeErrorReporterOptions)[runtimeErrorReporterOption];\n}\n\nexport function attachRuntimeErrorReporter(\n runtime: object,\n reporter: RuntimeErrorReporter,\n): void {\n Object.defineProperty(runtime, runtimeErrorReporterOption, {\n configurable: true,\n value: reporter,\n });\n}\n\nexport function getRuntimeErrorReporter(\n runtime: CopilotRuntimeLike,\n): RuntimeErrorReporter | undefined {\n return (runtime as CopilotRuntimeLike & RuntimeErrorReporterOptions)[\n runtimeErrorReporterOption\n ];\n}\n"],"mappings":";;AAOA,MAAa,6BAA6B,OACxC,kCACD;AAsGD,SAAgB,mCACd,SACkC;AAClC,QAAQ,QAAwC;;AAGlD,SAAgB,2BACd,SACA,UACM;AACN,QAAO,eAAe,SAAS,4BAA4B;EACzD,cAAc;EACd,OAAO;EACR,CAAC;;AAGJ,SAAgB,wBACd,SACkC;AAClC,QAAQ,QACN"}
1
+ {"version":3,"file":"runtime-error-reporter.cjs","names":[],"sources":["../../../src/runtime/core/runtime-error-reporter.ts"],"sourcesContent":["import type {\n CopilotErrorEvent,\n CopilotErrorHandler,\n} from \"@copilotkit/shared\";\n\nimport type { CopilotKitRuntimeLike } from \"./runtime\";\n\nexport const runtimeErrorReporterOption = Symbol(\n \"copilotkit.runtimeErrorReporter\",\n);\n\nexport type RuntimeErrorPhase =\n | \"common\"\n | \"sse.factory\"\n | \"sse.subscription\"\n | \"intelligence.startup\"\n | \"intelligence.subscription\";\n\nexport interface RuntimeErrorReportParams {\n request: Request;\n error: unknown;\n operation: string;\n agentId?: string;\n threadId?: string;\n runId?: string;\n phase?: RuntimeErrorPhase;\n startTime?: number;\n}\n\nexport interface RuntimeErrorReporter {\n report(params: RuntimeErrorReportParams): void;\n}\n\nexport interface RuntimeErrorReporterOptions {\n [runtimeErrorReporterOption]?: RuntimeErrorReporter;\n}\n\nconst SENSITIVE_REQUEST_HEADERS = new Set([\n \"authorization\",\n \"proxy-authorization\",\n \"cookie\",\n \"set-cookie\",\n \"x-api-key\",\n \"api-key\",\n \"x-copilotcloud-public-api-key\",\n]);\n\nfunction sanitizeRequestHeaders(headers: Headers): Record<string, string> {\n const sanitized: Record<string, string> = {};\n headers.forEach((value, key) => {\n if (!SENSITIVE_REQUEST_HEADERS.has(key.toLowerCase())) {\n sanitized[key] = value;\n }\n });\n return sanitized;\n}\n\nexport function createRuntimeErrorReporter(\n handler?: CopilotErrorHandler,\n): RuntimeErrorReporter {\n return {\n report({\n request,\n error,\n operation,\n agentId,\n threadId,\n runId,\n phase,\n startTime,\n }) {\n if (!handler) return;\n\n try {\n const event: CopilotErrorEvent = {\n type: \"error\",\n timestamp: Date.now(),\n context: {\n source: \"runtime\",\n ...(threadId ? { threadId } : {}),\n ...(runId ? { runId } : {}),\n request: {\n operation,\n method: request.method,\n url: request.url,\n path: new URL(request.url).pathname,\n headers: sanitizeRequestHeaders(request.headers),\n startTime: startTime ?? Date.now(),\n },\n ...(agentId ? { agent: { name: agentId } } : {}),\n ...(phase ? { metadata: { phase } } : {}),\n },\n error,\n };\n\n const result = handler(event);\n if (result && typeof (result as Promise<void>).catch === \"function\") {\n void (result as Promise<void>).catch((handlerError) => {\n console.error(\n \"CopilotKitRuntime onError reporting failed:\",\n handlerError,\n );\n });\n }\n } catch (handlerError) {\n console.error(\n \"CopilotKitRuntime onError reporting failed:\",\n handlerError,\n );\n }\n },\n };\n}\n\nexport function getRuntimeErrorReporterFromOptions(\n options: object,\n): RuntimeErrorReporter | undefined {\n return (options as RuntimeErrorReporterOptions)[runtimeErrorReporterOption];\n}\n\nexport function attachRuntimeErrorReporter(\n runtime: object,\n reporter: RuntimeErrorReporter,\n): void {\n Object.defineProperty(runtime, runtimeErrorReporterOption, {\n configurable: true,\n value: reporter,\n });\n}\n\nexport function getRuntimeErrorReporter(\n runtime: CopilotKitRuntimeLike,\n): RuntimeErrorReporter | undefined {\n return (runtime as CopilotKitRuntimeLike & RuntimeErrorReporterOptions)[\n runtimeErrorReporterOption\n ];\n}\n"],"mappings":";;AAOA,MAAa,6BAA6B,OACxC,kCACD;AAyGD,SAAgB,mCACd,SACkC;AAClC,QAAQ,QAAwC;;AAGlD,SAAgB,2BACd,SACA,UACM;AACN,QAAO,eAAe,SAAS,4BAA4B;EACzD,cAAc;EACd,OAAO;EACR,CAAC;;AAGJ,SAAgB,wBACd,SACkC;AAClC,QAAQ,QACN"}
@@ -1 +1 @@
1
- {"version":3,"file":"runtime-error-reporter.mjs","names":[],"sources":["../../../src/runtime/core/runtime-error-reporter.ts"],"sourcesContent":["import type {\n CopilotErrorEvent,\n CopilotErrorHandler,\n} from \"@copilotkit/shared\";\n\nimport type { CopilotRuntimeLike } from \"./runtime\";\n\nexport const runtimeErrorReporterOption = Symbol(\n \"copilotkit.runtimeErrorReporter\",\n);\n\nexport type RuntimeErrorPhase =\n | \"common\"\n | \"sse.factory\"\n | \"sse.subscription\"\n | \"intelligence.startup\"\n | \"intelligence.subscription\";\n\nexport interface RuntimeErrorReportParams {\n request: Request;\n error: unknown;\n operation: string;\n agentId?: string;\n threadId?: string;\n runId?: string;\n phase?: RuntimeErrorPhase;\n startTime?: number;\n}\n\nexport interface RuntimeErrorReporter {\n report(params: RuntimeErrorReportParams): void;\n}\n\nexport interface RuntimeErrorReporterOptions {\n [runtimeErrorReporterOption]?: RuntimeErrorReporter;\n}\n\nconst SENSITIVE_REQUEST_HEADERS = new Set([\n \"authorization\",\n \"proxy-authorization\",\n \"cookie\",\n \"set-cookie\",\n \"x-api-key\",\n \"api-key\",\n \"x-copilotcloud-public-api-key\",\n]);\n\nfunction sanitizeRequestHeaders(headers: Headers): Record<string, string> {\n const sanitized: Record<string, string> = {};\n headers.forEach((value, key) => {\n if (!SENSITIVE_REQUEST_HEADERS.has(key.toLowerCase())) {\n sanitized[key] = value;\n }\n });\n return sanitized;\n}\n\nexport function createRuntimeErrorReporter(\n handler?: CopilotErrorHandler,\n): RuntimeErrorReporter {\n return {\n report({\n request,\n error,\n operation,\n agentId,\n threadId,\n runId,\n phase,\n startTime,\n }) {\n if (!handler) return;\n\n try {\n const event: CopilotErrorEvent = {\n type: \"error\",\n timestamp: Date.now(),\n context: {\n source: \"runtime\",\n ...(threadId ? { threadId } : {}),\n ...(runId ? { runId } : {}),\n request: {\n operation,\n method: request.method,\n url: request.url,\n path: new URL(request.url).pathname,\n headers: sanitizeRequestHeaders(request.headers),\n startTime: startTime ?? Date.now(),\n },\n ...(agentId ? { agent: { name: agentId } } : {}),\n ...(phase ? { metadata: { phase } } : {}),\n },\n error,\n };\n\n const result = handler(event);\n if (result && typeof (result as Promise<void>).catch === \"function\") {\n void (result as Promise<void>).catch((handlerError) => {\n console.error(\n \"CopilotRuntime onError reporting failed:\",\n handlerError,\n );\n });\n }\n } catch (handlerError) {\n console.error(\"CopilotRuntime onError reporting failed:\", handlerError);\n }\n },\n };\n}\n\nexport function getRuntimeErrorReporterFromOptions(\n options: object,\n): RuntimeErrorReporter | undefined {\n return (options as RuntimeErrorReporterOptions)[runtimeErrorReporterOption];\n}\n\nexport function attachRuntimeErrorReporter(\n runtime: object,\n reporter: RuntimeErrorReporter,\n): void {\n Object.defineProperty(runtime, runtimeErrorReporterOption, {\n configurable: true,\n value: reporter,\n });\n}\n\nexport function getRuntimeErrorReporter(\n runtime: CopilotRuntimeLike,\n): RuntimeErrorReporter | undefined {\n return (runtime as CopilotRuntimeLike & RuntimeErrorReporterOptions)[\n runtimeErrorReporterOption\n ];\n}\n"],"mappings":";AAOA,MAAa,6BAA6B,OACxC,kCACD;AAsGD,SAAgB,mCACd,SACkC;AAClC,QAAQ,QAAwC;;AAGlD,SAAgB,2BACd,SACA,UACM;AACN,QAAO,eAAe,SAAS,4BAA4B;EACzD,cAAc;EACd,OAAO;EACR,CAAC;;AAGJ,SAAgB,wBACd,SACkC;AAClC,QAAQ,QACN"}
1
+ {"version":3,"file":"runtime-error-reporter.mjs","names":[],"sources":["../../../src/runtime/core/runtime-error-reporter.ts"],"sourcesContent":["import type {\n CopilotErrorEvent,\n CopilotErrorHandler,\n} from \"@copilotkit/shared\";\n\nimport type { CopilotKitRuntimeLike } from \"./runtime\";\n\nexport const runtimeErrorReporterOption = Symbol(\n \"copilotkit.runtimeErrorReporter\",\n);\n\nexport type RuntimeErrorPhase =\n | \"common\"\n | \"sse.factory\"\n | \"sse.subscription\"\n | \"intelligence.startup\"\n | \"intelligence.subscription\";\n\nexport interface RuntimeErrorReportParams {\n request: Request;\n error: unknown;\n operation: string;\n agentId?: string;\n threadId?: string;\n runId?: string;\n phase?: RuntimeErrorPhase;\n startTime?: number;\n}\n\nexport interface RuntimeErrorReporter {\n report(params: RuntimeErrorReportParams): void;\n}\n\nexport interface RuntimeErrorReporterOptions {\n [runtimeErrorReporterOption]?: RuntimeErrorReporter;\n}\n\nconst SENSITIVE_REQUEST_HEADERS = new Set([\n \"authorization\",\n \"proxy-authorization\",\n \"cookie\",\n \"set-cookie\",\n \"x-api-key\",\n \"api-key\",\n \"x-copilotcloud-public-api-key\",\n]);\n\nfunction sanitizeRequestHeaders(headers: Headers): Record<string, string> {\n const sanitized: Record<string, string> = {};\n headers.forEach((value, key) => {\n if (!SENSITIVE_REQUEST_HEADERS.has(key.toLowerCase())) {\n sanitized[key] = value;\n }\n });\n return sanitized;\n}\n\nexport function createRuntimeErrorReporter(\n handler?: CopilotErrorHandler,\n): RuntimeErrorReporter {\n return {\n report({\n request,\n error,\n operation,\n agentId,\n threadId,\n runId,\n phase,\n startTime,\n }) {\n if (!handler) return;\n\n try {\n const event: CopilotErrorEvent = {\n type: \"error\",\n timestamp: Date.now(),\n context: {\n source: \"runtime\",\n ...(threadId ? { threadId } : {}),\n ...(runId ? { runId } : {}),\n request: {\n operation,\n method: request.method,\n url: request.url,\n path: new URL(request.url).pathname,\n headers: sanitizeRequestHeaders(request.headers),\n startTime: startTime ?? Date.now(),\n },\n ...(agentId ? { agent: { name: agentId } } : {}),\n ...(phase ? { metadata: { phase } } : {}),\n },\n error,\n };\n\n const result = handler(event);\n if (result && typeof (result as Promise<void>).catch === \"function\") {\n void (result as Promise<void>).catch((handlerError) => {\n console.error(\n \"CopilotKitRuntime onError reporting failed:\",\n handlerError,\n );\n });\n }\n } catch (handlerError) {\n console.error(\n \"CopilotKitRuntime onError reporting failed:\",\n handlerError,\n );\n }\n },\n };\n}\n\nexport function getRuntimeErrorReporterFromOptions(\n options: object,\n): RuntimeErrorReporter | undefined {\n return (options as RuntimeErrorReporterOptions)[runtimeErrorReporterOption];\n}\n\nexport function attachRuntimeErrorReporter(\n runtime: object,\n reporter: RuntimeErrorReporter,\n): void {\n Object.defineProperty(runtime, runtimeErrorReporterOption, {\n configurable: true,\n value: reporter,\n });\n}\n\nexport function getRuntimeErrorReporter(\n runtime: CopilotKitRuntimeLike,\n): RuntimeErrorReporter | undefined {\n return (runtime as CopilotKitRuntimeLike & RuntimeErrorReporterOptions)[\n runtimeErrorReporterOption\n ];\n}\n"],"mappings":";AAOA,MAAa,6BAA6B,OACxC,kCACD;AAyGD,SAAgB,mCACd,SACkC;AAClC,QAAQ,QAAwC;;AAGlD,SAAgB,2BACd,SACA,UACM;AACN,QAAO,eAAe,SAAS,4BAA4B;EACzD,cAAc;EACd,OAAO;EACR,CAAC;;AAGJ,SAAgB,wBACd,SACkC;AAClC,QAAQ,QACN"}
@@ -59,7 +59,7 @@ var BaseCopilotRuntime = class {
59
59
  this.threadAccess = require_thread_access.resolveThreadAccessMode(options.threads);
60
60
  }
61
61
  };
62
- var CopilotSseRuntime = class extends BaseCopilotRuntime {
62
+ var CopilotKitSseRuntime = class extends BaseCopilotRuntime {
63
63
  constructor(options) {
64
64
  const channels = options.channels;
65
65
  if (Array.isArray(channels) && channels.length > 0) throw new Error("`channels` requires the Intelligence runtime (pass `intelligence`); Intelligence Channels are not available in SSE mode.");
@@ -73,7 +73,7 @@ var CopilotSseRuntime = class extends BaseCopilotRuntime {
73
73
  require_thread_access.warnIfThreadListRefused(this);
74
74
  }
75
75
  };
76
- var CopilotIntelligenceRuntime = class CopilotIntelligenceRuntime extends BaseCopilotRuntime {
76
+ var CopilotKitIntelligenceRuntime = class CopilotKitIntelligenceRuntime extends BaseCopilotRuntime {
77
77
  static {
78
78
  this.MAX_LOCK_TTL_SECONDS = 3600;
79
79
  }
@@ -92,7 +92,7 @@ var CopilotIntelligenceRuntime = class CopilotIntelligenceRuntime extends BaseCo
92
92
  if (rawOptions.memory !== void 0 && (typeof rawOptions.memory !== "object" || rawOptions.memory === null || typeof rawOptions.memory.access !== "function")) throw new Error("Intelligence Runtime `memory.access` must be a callback");
93
93
  if (rawOptions.memory !== void 0 && !hasWebIdentity) throw new Error("Intelligence Runtime web `memory` requires `identifyUser`");
94
94
  if (rawOptions.ɵlearning !== void 0 && (typeof rawOptions.ɵlearning !== "object" || rawOptions.ɵlearning === null || !(typeof rawOptions.ɵlearning.containerId === "string" || typeof rawOptions.ɵlearning.containerId === "function"))) throw new Error("Intelligence Runtime `ɵlearning.containerId` must be a stable ID or callback");
95
- if (rawOptions.ɵlearning !== void 0 && options.intelligence.ɵgetLearningContainerId?.() !== void 0) throw new Error("Configure Learning Containers with `getLearningContainerId` on `CopilotKitIntelligence`; do not also pass deprecated `ɵlearning` to `CopilotRuntime`");
95
+ if (rawOptions.ɵlearning !== void 0 && options.intelligence.ɵgetLearningContainerId?.() !== void 0) throw new Error("Configure Learning Containers with `getLearningContainerId` on `CopilotKitIntelligence`; do not also pass deprecated `ɵlearning` to `CopilotKitRuntime`");
96
96
  if (typeof rawOptions.ɵlearning?.containerId === "string") require_learning.assertStableLearningContainerId(rawOptions.ɵlearning.containerId);
97
97
  super(options, new require_intelligence.IntelligenceAgentRunner({
98
98
  url: options.intelligence.ɵgetRunnerWsUrl(),
@@ -107,9 +107,9 @@ var CopilotIntelligenceRuntime = class CopilotIntelligenceRuntime extends BaseCo
107
107
  this.learning = options.ɵlearning;
108
108
  this.identifyUser = hasWebIdentity ? rawOptions.identifyUser : void 0;
109
109
  this.generateThreadNames = options.generateThreadNames ?? true;
110
- this.lockTtlSeconds = Math.min(options.lockTtlSeconds ?? 20, CopilotIntelligenceRuntime.MAX_LOCK_TTL_SECONDS);
110
+ this.lockTtlSeconds = Math.min(options.lockTtlSeconds ?? 20, CopilotKitIntelligenceRuntime.MAX_LOCK_TTL_SECONDS);
111
111
  this.lockKeyPrefix = options.lockKeyPrefix;
112
- this.lockHeartbeatIntervalSeconds = Math.min(options.lockHeartbeatIntervalSeconds ?? 15, CopilotIntelligenceRuntime.MAX_HEARTBEAT_INTERVAL_SECONDS);
112
+ this.lockHeartbeatIntervalSeconds = Math.min(options.lockHeartbeatIntervalSeconds ?? 15, CopilotKitIntelligenceRuntime.MAX_HEARTBEAT_INTERVAL_SECONDS);
113
113
  this.channels = [...rawOptions.channels ?? []];
114
114
  for (const c of this.channels) if (!c || typeof c !== "object" || !c.name) throw new Error("Intelligence Channel is missing a `name` — pass createChannel({ name }) for each Channel in `channels`");
115
115
  }
@@ -132,16 +132,16 @@ function isIntelligenceRuntime(runtime) {
132
132
  return runtime.mode === _copilotkit_shared.RUNTIME_MODE_INTELLIGENCE && !!runtime.intelligence;
133
133
  }
134
134
  /**
135
- * Compatibility shim that preserves the legacy `CopilotRuntime` entrypoint.
136
- * New code should prefer `CopilotSseRuntime` or `CopilotIntelligenceRuntime`.
135
+ * Compatibility shim that preserves the legacy `CopilotKitRuntime` entrypoint.
136
+ * New code should prefer `CopilotKitSseRuntime` or `CopilotKitIntelligenceRuntime`.
137
137
  *
138
- * Exported to consumers as the {@link CopilotRuntime} value (typed as
139
- * {@link CopilotRuntimeConstructor}) rather than as a class, so that the
138
+ * Exported to consumers as the {@link CopilotKitRuntime} value (typed as
139
+ * {@link CopilotKitRuntimeConstructor}) rather than as a class, so that the
140
140
  * channel-presence brand can flow from construction into the handler type.
141
141
  */
142
142
  var CopilotRuntimeShim = class {
143
143
  constructor(options) {
144
- this.delegate = hasIntelligenceOptions(options) ? new CopilotIntelligenceRuntime(options) : new CopilotSseRuntime(options);
144
+ this.delegate = hasIntelligenceOptions(options) ? new CopilotKitIntelligenceRuntime(options) : new CopilotKitSseRuntime(options);
145
145
  const reporter = require_runtime_error_reporter.getRuntimeErrorReporterFromOptions(options);
146
146
  if (reporter) require_runtime_error_reporter.attachRuntimeErrorReporter(this, reporter);
147
147
  }
@@ -231,22 +231,22 @@ var CopilotRuntimeShim = class {
231
231
  }
232
232
  };
233
233
  /**
234
- * The public `CopilotRuntime` constructor. Backed by {@link CopilotRuntimeShim}
235
- * but typed as {@link CopilotRuntimeConstructor} so that constructing with a
234
+ * The public `CopilotKitRuntime` constructor. Backed by {@link CopilotRuntimeShim}
235
+ * but typed as {@link CopilotKitRuntimeConstructor} so that constructing with a
236
236
  * non-empty `channels` array yields a {@link RuntimeWithDeclaredChannels}-branded
237
237
  * runtime type.
238
238
  *
239
239
  * The `as unknown as` cast is required (not dishonest widening): the brand is a
240
240
  * phantom, compile-time-only marker with no runtime representation, so the shim
241
241
  * instances legitimately do not carry the brand property. Behavior is identical
242
- * to the former `class CopilotRuntime` — this only refines the static type.
242
+ * to the former `class CopilotKitRuntime` — this only refines the static type.
243
243
  */
244
- const CopilotRuntime = CopilotRuntimeShim;
244
+ const CopilotKitRuntime = CopilotRuntimeShim;
245
245
 
246
246
  //#endregion
247
- exports.CopilotIntelligenceRuntime = CopilotIntelligenceRuntime;
248
- exports.CopilotRuntime = CopilotRuntime;
249
- exports.CopilotSseRuntime = CopilotSseRuntime;
247
+ exports.CopilotKitIntelligenceRuntime = CopilotKitIntelligenceRuntime;
248
+ exports.CopilotKitRuntime = CopilotKitRuntime;
249
+ exports.CopilotKitSseRuntime = CopilotKitSseRuntime;
250
250
  exports.VERSION = VERSION;
251
251
  exports.isIntelligenceRuntime = isIntelligenceRuntime;
252
252
  exports.resolveAgents = resolveAgents;