@copilotkit/runtime 1.72.1-canary.sp-longthread-perf → 1.73.1

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 (206) hide show
  1. package/dist/agent/index.cjs +49 -9
  2. package/dist/agent/index.cjs.map +1 -1
  3. package/dist/agent/index.d.cts +20 -7
  4. package/dist/agent/index.d.cts.map +1 -1
  5. package/dist/agent/index.d.mts +19 -6
  6. package/dist/agent/index.d.mts.map +1 -1
  7. package/dist/agent/index.mjs +49 -9
  8. package/dist/agent/index.mjs.map +1 -1
  9. package/dist/agent/learned-skills.cjs +77 -0
  10. package/dist/agent/learned-skills.cjs.map +1 -0
  11. package/dist/agent/learned-skills.d.cts +16 -0
  12. package/dist/agent/learned-skills.d.cts.map +1 -0
  13. package/dist/agent/learned-skills.d.mts +16 -0
  14. package/dist/agent/learned-skills.d.mts.map +1 -0
  15. package/dist/agent/learned-skills.mjs +75 -0
  16. package/dist/agent/learned-skills.mjs.map +1 -0
  17. package/dist/index.d.cts +4 -4
  18. package/dist/index.d.mts +4 -4
  19. package/dist/internal/learned-skills.cjs +22 -0
  20. package/dist/internal/learned-skills.d.cts +10 -0
  21. package/dist/internal/learned-skills.d.mts +10 -0
  22. package/dist/internal/learned-skills.mjs +10 -0
  23. package/dist/lib/index.d.cts +2 -2
  24. package/dist/lib/index.d.mts +2 -2
  25. package/dist/lib/integrations/nextjs/app-router.cjs +1 -1
  26. package/dist/lib/integrations/nextjs/app-router.cjs.map +1 -1
  27. package/dist/lib/integrations/nextjs/app-router.mjs +1 -1
  28. package/dist/lib/integrations/nextjs/app-router.mjs.map +1 -1
  29. package/dist/lib/integrations/node-http/index.cjs +1 -1
  30. package/dist/lib/integrations/node-http/index.cjs.map +1 -1
  31. package/dist/lib/integrations/node-http/index.d.cts.map +1 -1
  32. package/dist/lib/integrations/node-http/index.d.mts.map +1 -1
  33. package/dist/lib/integrations/node-http/index.mjs +1 -1
  34. package/dist/lib/integrations/node-http/index.mjs.map +1 -1
  35. package/dist/lib/integrations/shared.cjs.map +1 -1
  36. package/dist/lib/integrations/shared.d.cts +1 -1
  37. package/dist/lib/integrations/shared.d.cts.map +1 -1
  38. package/dist/lib/integrations/shared.d.mts +1 -1
  39. package/dist/lib/integrations/shared.d.mts.map +1 -1
  40. package/dist/lib/integrations/shared.mjs.map +1 -1
  41. package/dist/lib/runtime/agent-integrations/langgraph/agent.d.cts +1 -1
  42. package/dist/lib/runtime/copilot-runtime.cjs +79 -37
  43. package/dist/lib/runtime/copilot-runtime.cjs.map +1 -1
  44. package/dist/lib/runtime/copilot-runtime.d.cts +54 -4
  45. package/dist/lib/runtime/copilot-runtime.d.cts.map +1 -1
  46. package/dist/lib/runtime/copilot-runtime.d.mts +56 -6
  47. package/dist/lib/runtime/copilot-runtime.d.mts.map +1 -1
  48. package/dist/lib/runtime/copilot-runtime.mjs +79 -37
  49. package/dist/lib/runtime/copilot-runtime.mjs.map +1 -1
  50. package/dist/lib/runtime/mcp-client-cache.cjs +135 -0
  51. package/dist/lib/runtime/mcp-client-cache.cjs.map +1 -0
  52. package/dist/lib/runtime/mcp-client-cache.mjs +132 -0
  53. package/dist/lib/runtime/mcp-client-cache.mjs.map +1 -0
  54. package/dist/lib/runtime/telemetry-agent-runner.cjs.map +1 -1
  55. package/dist/lib/runtime/telemetry-agent-runner.d.cts +1 -1
  56. package/dist/lib/runtime/telemetry-agent-runner.d.mts +1 -1
  57. package/dist/lib/runtime/telemetry-agent-runner.mjs.map +1 -1
  58. package/dist/package.cjs +15 -7
  59. package/dist/package.mjs +15 -7
  60. package/dist/service-adapters/anthropic/anthropic-adapter.cjs.map +1 -1
  61. package/dist/service-adapters/anthropic/anthropic-adapter.d.cts.map +1 -1
  62. package/dist/service-adapters/anthropic/anthropic-adapter.d.mts.map +1 -1
  63. package/dist/service-adapters/anthropic/anthropic-adapter.mjs.map +1 -1
  64. package/dist/service-adapters/shared/sdk-client-utils.cjs.map +1 -1
  65. package/dist/service-adapters/shared/sdk-client-utils.d.cts.map +1 -1
  66. package/dist/service-adapters/shared/sdk-client-utils.d.mts.map +1 -1
  67. package/dist/service-adapters/shared/sdk-client-utils.mjs.map +1 -1
  68. package/dist/v2/index.cjs +9 -3
  69. package/dist/v2/index.d.cts +12 -11
  70. package/dist/v2/index.d.mts +12 -11
  71. package/dist/v2/index.mjs +5 -5
  72. package/dist/v2/runtime/core/channel-manager.cjs +1 -1
  73. package/dist/v2/runtime/core/channel-manager.d.cts +1 -1
  74. package/dist/v2/runtime/core/channel-manager.d.mts +1 -1
  75. package/dist/v2/runtime/core/channel-manager.mjs +1 -1
  76. package/dist/v2/runtime/core/fetch-handler.cjs +1 -0
  77. package/dist/v2/runtime/core/fetch-handler.cjs.map +1 -1
  78. package/dist/v2/runtime/core/fetch-handler.d.cts +2 -2
  79. package/dist/v2/runtime/core/fetch-handler.d.mts +2 -2
  80. package/dist/v2/runtime/core/fetch-handler.mjs +1 -0
  81. package/dist/v2/runtime/core/fetch-handler.mjs.map +1 -1
  82. package/dist/v2/runtime/core/runtime.cjs +5 -0
  83. package/dist/v2/runtime/core/runtime.cjs.map +1 -1
  84. package/dist/v2/runtime/core/runtime.d.cts +18 -3
  85. package/dist/v2/runtime/core/runtime.d.cts.map +1 -1
  86. package/dist/v2/runtime/core/runtime.d.mts +17 -2
  87. package/dist/v2/runtime/core/runtime.d.mts.map +1 -1
  88. package/dist/v2/runtime/core/runtime.mjs +5 -0
  89. package/dist/v2/runtime/core/runtime.mjs.map +1 -1
  90. package/dist/v2/runtime/endpoints/express-single.cjs.map +1 -1
  91. package/dist/v2/runtime/endpoints/express-single.d.cts +2 -2
  92. package/dist/v2/runtime/endpoints/express-single.d.cts.map +1 -1
  93. package/dist/v2/runtime/endpoints/express-single.d.mts +2 -2
  94. package/dist/v2/runtime/endpoints/express-single.d.mts.map +1 -1
  95. package/dist/v2/runtime/endpoints/express-single.mjs.map +1 -1
  96. package/dist/v2/runtime/endpoints/express.cjs +2 -3
  97. package/dist/v2/runtime/endpoints/express.cjs.map +1 -1
  98. package/dist/v2/runtime/endpoints/express.d.cts +26 -7
  99. package/dist/v2/runtime/endpoints/express.d.cts.map +1 -1
  100. package/dist/v2/runtime/endpoints/express.d.mts +26 -7
  101. package/dist/v2/runtime/endpoints/express.d.mts.map +1 -1
  102. package/dist/v2/runtime/endpoints/express.mjs +2 -2
  103. package/dist/v2/runtime/endpoints/express.mjs.map +1 -1
  104. package/dist/v2/runtime/endpoints/hono.d.cts +2 -2
  105. package/dist/v2/runtime/endpoints/hono.d.mts +2 -2
  106. package/dist/v2/runtime/endpoints/index.d.cts +3 -3
  107. package/dist/v2/runtime/endpoints/index.d.mts +3 -3
  108. package/dist/v2/runtime/endpoints/load-express.cjs +36 -0
  109. package/dist/v2/runtime/endpoints/load-express.cjs.map +1 -0
  110. package/dist/v2/runtime/endpoints/load-express.mjs +35 -0
  111. package/dist/v2/runtime/endpoints/load-express.mjs.map +1 -0
  112. package/dist/v2/runtime/handlers/handle-stop.cjs +18 -14
  113. package/dist/v2/runtime/handlers/handle-stop.cjs.map +1 -1
  114. package/dist/v2/runtime/handlers/handle-stop.mjs +18 -14
  115. package/dist/v2/runtime/handlers/handle-stop.mjs.map +1 -1
  116. package/dist/v2/runtime/handlers/handle-suggest.cjs +4 -3
  117. package/dist/v2/runtime/handlers/handle-suggest.cjs.map +1 -1
  118. package/dist/v2/runtime/handlers/handle-suggest.mjs +5 -4
  119. package/dist/v2/runtime/handlers/handle-suggest.mjs.map +1 -1
  120. package/dist/v2/runtime/handlers/shared/agent-utils.cjs +3 -4
  121. package/dist/v2/runtime/handlers/shared/agent-utils.cjs.map +1 -1
  122. package/dist/v2/runtime/handlers/shared/agent-utils.mjs +1 -2
  123. package/dist/v2/runtime/handlers/shared/agent-utils.mjs.map +1 -1
  124. package/dist/v2/runtime/handlers/shared/sse-keep-alive.cjs +69 -0
  125. package/dist/v2/runtime/handlers/shared/sse-keep-alive.cjs.map +1 -0
  126. package/dist/v2/runtime/handlers/shared/sse-keep-alive.mjs +67 -0
  127. package/dist/v2/runtime/handlers/shared/sse-keep-alive.mjs.map +1 -0
  128. package/dist/v2/runtime/handlers/shared/sse-response.cjs +5 -2
  129. package/dist/v2/runtime/handlers/shared/sse-response.cjs.map +1 -1
  130. package/dist/v2/runtime/handlers/shared/sse-response.mjs +5 -2
  131. package/dist/v2/runtime/handlers/shared/sse-response.mjs.map +1 -1
  132. package/dist/v2/runtime/handlers/sse/connect.cjs +1 -0
  133. package/dist/v2/runtime/handlers/sse/connect.cjs.map +1 -1
  134. package/dist/v2/runtime/handlers/sse/connect.mjs +1 -0
  135. package/dist/v2/runtime/handlers/sse/connect.mjs.map +1 -1
  136. package/dist/v2/runtime/handlers/sse/run.cjs +1 -0
  137. package/dist/v2/runtime/handlers/sse/run.cjs.map +1 -1
  138. package/dist/v2/runtime/handlers/sse/run.mjs +1 -0
  139. package/dist/v2/runtime/handlers/sse/run.mjs.map +1 -1
  140. package/dist/v2/runtime/index.d.cts +9 -9
  141. package/dist/v2/runtime/index.d.mts +9 -9
  142. package/dist/v2/runtime/intelligence-platform/client.cjs +1 -1
  143. package/dist/v2/runtime/intelligence-platform/client.d.cts +1 -1
  144. package/dist/v2/runtime/intelligence-platform/client.d.mts +1 -1
  145. package/dist/v2/runtime/intelligence-platform/client.mjs +1 -1
  146. package/dist/v2/runtime/intelligence-platform/skill-registry/archive.cjs +132 -0
  147. package/dist/v2/runtime/intelligence-platform/skill-registry/archive.cjs.map +1 -0
  148. package/dist/v2/runtime/intelligence-platform/skill-registry/archive.d.cts +11 -0
  149. package/dist/v2/runtime/intelligence-platform/skill-registry/archive.d.cts.map +1 -0
  150. package/dist/v2/runtime/intelligence-platform/skill-registry/archive.d.mts +11 -0
  151. package/dist/v2/runtime/intelligence-platform/skill-registry/archive.d.mts.map +1 -0
  152. package/dist/v2/runtime/intelligence-platform/skill-registry/archive.mjs +128 -0
  153. package/dist/v2/runtime/intelligence-platform/skill-registry/archive.mjs.map +1 -0
  154. package/dist/v2/runtime/intelligence-platform/skill-registry/config.cjs +48 -0
  155. package/dist/v2/runtime/intelligence-platform/skill-registry/config.cjs.map +1 -0
  156. package/dist/v2/runtime/intelligence-platform/skill-registry/config.d.cts +27 -0
  157. package/dist/v2/runtime/intelligence-platform/skill-registry/config.d.cts.map +1 -0
  158. package/dist/v2/runtime/intelligence-platform/skill-registry/config.d.mts +27 -0
  159. package/dist/v2/runtime/intelligence-platform/skill-registry/config.d.mts.map +1 -0
  160. package/dist/v2/runtime/intelligence-platform/skill-registry/config.mjs +48 -0
  161. package/dist/v2/runtime/intelligence-platform/skill-registry/config.mjs.map +1 -0
  162. package/dist/v2/runtime/intelligence-platform/skill-registry/errors.cjs +11 -0
  163. package/dist/v2/runtime/intelligence-platform/skill-registry/errors.cjs.map +1 -0
  164. package/dist/v2/runtime/intelligence-platform/skill-registry/errors.d.cts +8 -0
  165. package/dist/v2/runtime/intelligence-platform/skill-registry/errors.d.cts.map +1 -0
  166. package/dist/v2/runtime/intelligence-platform/skill-registry/errors.d.mts +8 -0
  167. package/dist/v2/runtime/intelligence-platform/skill-registry/errors.d.mts.map +1 -0
  168. package/dist/v2/runtime/intelligence-platform/skill-registry/errors.mjs +11 -0
  169. package/dist/v2/runtime/intelligence-platform/skill-registry/errors.mjs.map +1 -0
  170. package/dist/v2/runtime/intelligence-platform/skill-registry/index.d.cts +8 -0
  171. package/dist/v2/runtime/intelligence-platform/skill-registry/index.d.mts +8 -0
  172. package/dist/v2/runtime/intelligence-platform/skill-registry/registry.cjs +132 -0
  173. package/dist/v2/runtime/intelligence-platform/skill-registry/registry.cjs.map +1 -0
  174. package/dist/v2/runtime/intelligence-platform/skill-registry/registry.d.cts +31 -0
  175. package/dist/v2/runtime/intelligence-platform/skill-registry/registry.d.cts.map +1 -0
  176. package/dist/v2/runtime/intelligence-platform/skill-registry/registry.d.mts +31 -0
  177. package/dist/v2/runtime/intelligence-platform/skill-registry/registry.d.mts.map +1 -0
  178. package/dist/v2/runtime/intelligence-platform/skill-registry/registry.mjs +132 -0
  179. package/dist/v2/runtime/intelligence-platform/skill-registry/registry.mjs.map +1 -0
  180. package/dist/v2/runtime/intelligence-platform/skill-registry/skill-content.cjs +42 -0
  181. package/dist/v2/runtime/intelligence-platform/skill-registry/skill-content.cjs.map +1 -0
  182. package/dist/v2/runtime/intelligence-platform/skill-registry/skill-content.d.cts +13 -0
  183. package/dist/v2/runtime/intelligence-platform/skill-registry/skill-content.d.cts.map +1 -0
  184. package/dist/v2/runtime/intelligence-platform/skill-registry/skill-content.d.mts +13 -0
  185. package/dist/v2/runtime/intelligence-platform/skill-registry/skill-content.d.mts.map +1 -0
  186. package/dist/v2/runtime/intelligence-platform/skill-registry/skill-content.mjs +39 -0
  187. package/dist/v2/runtime/intelligence-platform/skill-registry/skill-content.mjs.map +1 -0
  188. package/dist/v2/runtime/intelligence-platform/skill-registry/snapshot.cjs +93 -0
  189. package/dist/v2/runtime/intelligence-platform/skill-registry/snapshot.cjs.map +1 -0
  190. package/dist/v2/runtime/intelligence-platform/skill-registry/snapshot.d.cts +28 -0
  191. package/dist/v2/runtime/intelligence-platform/skill-registry/snapshot.d.cts.map +1 -0
  192. package/dist/v2/runtime/intelligence-platform/skill-registry/snapshot.d.mts +28 -0
  193. package/dist/v2/runtime/intelligence-platform/skill-registry/snapshot.d.mts.map +1 -0
  194. package/dist/v2/runtime/intelligence-platform/skill-registry/snapshot.mjs +92 -0
  195. package/dist/v2/runtime/intelligence-platform/skill-registry/snapshot.mjs.map +1 -0
  196. package/dist/v2/runtime/runner/agent-runner.d.cts +1 -1
  197. package/dist/v2/runtime/runner/in-memory.d.cts +1 -1
  198. package/dist/v2/runtime/runner/index.d.cts +2 -2
  199. package/dist/v2/runtime/runner/index.d.mts +2 -2
  200. package/dist/v2/runtime/runner/index.mjs +2 -2
  201. package/dist/v2/runtime/runner/intelligence.d.cts +1 -1
  202. package/package.json +17 -7
  203. package/dist/v2/runtime/open-generative-ui-middleware.cjs +0 -286
  204. package/dist/v2/runtime/open-generative-ui-middleware.cjs.map +0 -1
  205. package/dist/v2/runtime/open-generative-ui-middleware.mjs +0 -284
  206. package/dist/v2/runtime/open-generative-ui-middleware.mjs.map +0 -1
@@ -1,11 +1,13 @@
1
1
  require("reflect-metadata");
2
2
  const require_runtime = require('../../../../_virtual/_rolldown/runtime.cjs');
3
3
  const require_logger = require('../../../../lib/logger.cjs');
4
+ const require_sse_keep_alive = require('./sse-keep-alive.cjs');
4
5
  const require_telemetry_client = require('../../telemetry/telemetry-client.cjs');
5
6
  let _ag_ui_encoder = require("@ag-ui/encoder");
6
7
 
7
8
  //#region src/v2/runtime/handlers/shared/sse-response.ts
8
- function createSseEventResponse({ request, observableFactory, debugEventBus, agentId, debug, logger, telemetry: telemetry$1 = require_telemetry_client.default, executionSeed, captureTelemetry = true, runtimeErrorReporter, startTime }) {
9
+ function createSseEventResponse({ request, observableFactory, debugEventBus, agentId, debug, logger, telemetry: telemetry$1 = require_telemetry_client.default, executionSeed, captureTelemetry = true, runtimeErrorReporter, startTime, keepAliveIntervalSeconds }) {
10
+ const keepAliveSeconds = require_sse_keep_alive.resolveSseKeepAliveIntervalSeconds(keepAliveIntervalSeconds);
9
11
  const stream = new TransformStream();
10
12
  const writer = stream.writable.getWriter();
11
13
  const encoder = new _ag_ui_encoder.EventEncoder();
@@ -124,7 +126,8 @@ function createSseEventResponse({ request, observableFactory, debugEventBus, age
124
126
  request.signal.addEventListener("abort", () => {
125
127
  subscription?.unsubscribe();
126
128
  });
127
- return new Response(stream.readable, {
129
+ const body = keepAliveSeconds > 0 ? require_sse_keep_alive.keepAliveSse(stream.readable, keepAliveSeconds * 1e3) : stream.readable;
130
+ return new Response(body, {
128
131
  status: 200,
129
132
  headers: {
130
133
  "Content-Type": "text/event-stream",
@@ -1 +1 @@
1
- {"version":3,"file":"sse-response.cjs","names":["defaultTelemetry","EventEncoder","createLogger"],"sources":["../../../../../src/v2/runtime/handlers/shared/sse-response.ts"],"sourcesContent":["import type { BaseEvent } from \"@ag-ui/client\";\nimport { EventEncoder } from \"@ag-ui/encoder\";\nimport type { Observable, Subscription } from \"rxjs\";\nimport type { ResolvedDebugConfig } from \"@copilotkit/shared\";\nimport { createLogger } from \"../../../../v1-deprecated/lib/logger\";\nimport type { CopilotRuntimeLogger } from \"../../../../v1-deprecated/lib/logger\";\nimport { telemetry as defaultTelemetry } from \"../../telemetry\";\nimport type { TelemetryCapture } from \"../../telemetry/telemetry-client\";\nimport type { AgentExecutionResponseInfo } from \"../../telemetry/events\";\nimport type { DebugEventBus } from \"../../core/debug-event-bus\";\nimport type {\n RuntimeErrorPhase,\n RuntimeErrorReporter,\n} from \"../../core/runtime-error-reporter\";\n\ninterface CreateSseEventResponseParams {\n request: Request;\n observableFactory: () =>\n | Promise<Observable<BaseEvent>>\n | Observable<BaseEvent>;\n debugEventBus?: DebugEventBus;\n agentId?: string;\n debug?: ResolvedDebugConfig;\n /** Pre-created logger instance to avoid creating a new pino logger per request. */\n logger?: CopilotRuntimeLogger;\n /** Runtime-bound telemetry capture. Falls back for external direct callers. */\n telemetry?: TelemetryCapture;\n /**\n * Execution facts known before the stream opens, merged under anything the\n * upstream reports as it runs. Carries `llmHostClass`, which is knowable\n * from the agent's configuration and never appears on a streamed event.\n */\n executionSeed?: AgentExecutionResponseInfo;\n /**\n * Whether to emit `oss.runtime.agent_execution_stream_*` telemetry for this\n * stream. Defaults to `true`. The stateless `/suggest` path sets this to\n * `false`: a suggestion is a side-effect-free structured completion, not a\n * tracked run, and under `available: \"always\"` it fires often enough to flood\n * run telemetry.\n */\n captureTelemetry?: boolean;\n runtimeErrorReporter?: RuntimeErrorReporter;\n startTime?: number;\n}\n\nexport function createSseEventResponse({\n request,\n observableFactory,\n debugEventBus,\n agentId,\n debug,\n logger,\n telemetry = defaultTelemetry,\n executionSeed,\n captureTelemetry = true,\n runtimeErrorReporter,\n startTime,\n}: CreateSseEventResponseParams): Response {\n const stream = new TransformStream();\n const writer = stream.writable.getWriter();\n const encoder = new EventEncoder();\n let streamClosed = false;\n let debugThreadId = \"\";\n let debugRunId = \"\";\n\n const debugLogger = debug?.enabled\n ? (logger ??\n createLogger({ level: \"debug\", component: \"copilotkit-debug\" }))\n : undefined;\n\n const closeStream = async () => {\n if (!streamClosed) {\n try {\n await writer.close();\n streamClosed = true;\n } catch {\n // Stream already closed.\n }\n }\n };\n\n const logError = (error: unknown) => {\n console.error(\"Error running agent:\", error);\n console.error(\n \"Error stack:\",\n error instanceof Error ? error.stack : \"No stack trace\",\n );\n console.error(\"Error details:\", {\n name: error instanceof Error ? error.name : \"Unknown\",\n message: error instanceof Error ? error.message : String(error),\n cause: error instanceof Error ? error.cause : undefined,\n });\n };\n\n let subscription: Subscription | undefined;\n let agentErrorReported = false;\n\n const reportAgentError = (error: unknown, phase: RuntimeErrorPhase) => {\n if (agentErrorReported) return;\n agentErrorReported = true;\n runtimeErrorReporter?.report({\n request,\n error,\n operation: \"agent.run\",\n agentId,\n threadId: debugThreadId || undefined,\n runId: debugRunId || undefined,\n phase,\n startTime,\n });\n };\n\n (async () => {\n const observable = await observableFactory();\n\n if (captureTelemetry) {\n telemetry.capture(\"oss.runtime.agent_execution_stream_started\", {});\n }\n\n if (debug?.lifecycle) {\n debugLogger!.debug(\"SSE stream opened\");\n }\n\n let eventCount = 0;\n let loggedEventCount = 0;\n\n // Provider/model/LangGraph facts, scraped off raw upstream events as\n // they pass and reported once the stream finishes. This moved here from\n // the v1 TelemetryAgentRunner, which wrapped the runner purely to\n // collect it and emitted its own duplicate copy of every stream event\n // to carry it. v2 callers had no equivalent and reported `{}`.\n // Seeded rather than empty: `llmHostClass` comes from the agent's config,\n // not from the wire, so nothing streamed will ever fill it in. Scraped\n // fields still win, since `collectExecutionInfo` writes over this.\n const executionInfo: AgentExecutionResponseInfo = { ...executionSeed };\n\n subscription = observable.subscribe({\n next: async (event) => {\n collectExecutionInfo(event, executionInfo);\n\n // Extract threadId/runId from RUN_STARTED\n if (event.type === \"RUN_STARTED\") {\n const e = event as { threadId?: string; runId?: string };\n debugThreadId = e.threadId ?? \"\";\n debugRunId = e.runId ?? \"\";\n }\n\n if (event.type === \"RUN_ERROR\") {\n const e = event as {\n message?: unknown;\n threadId?: string;\n runId?: string;\n };\n debugThreadId = e.threadId ?? debugThreadId;\n debugRunId = e.runId ?? debugRunId;\n reportAgentError(\n new Error(\n typeof e.message === \"string\"\n ? e.message\n : \"Runner reported a run error\",\n ),\n \"sse.subscription\",\n );\n }\n\n // Broadcast to debug listeners BEFORE the stream-closed gate below.\n // Intentional: debug subscribers (e.g. the VS Code Inspector panel)\n // should still receive trailing events after the SSE client for\n // this request closed its connection — they're independent\n // consumers observing the underlying runtime, not the request's\n // response stream.\n //\n // Wrapped in try/catch so a buggy debug subscriber can't propagate\n // an exception into this observer — if the throw reached the\n // `next` callback it would get routed to `error` by RxJS, closing\n // the SSE stream for an unrelated reason. Log via `logError` and\n // move on.\n if (debugEventBus) {\n try {\n debugEventBus.broadcast(event, {\n agentId: agentId ?? \"\",\n threadId: debugThreadId,\n runId: debugRunId,\n });\n } catch (broadcastError) {\n logError(broadcastError);\n }\n }\n\n if (!request.signal.aborted && !streamClosed) {\n try {\n eventCount++;\n if (debug?.events) {\n loggedEventCount++;\n if (debug.verbose) {\n debugLogger!.debug({ event }, \"Event emitted\");\n } else {\n debugLogger!.debug(\n { type: event.type, ...summarizeEvent(event) },\n \"Event emitted\",\n );\n }\n }\n await writer.write(encoder.encodeBinary(event));\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n streamClosed = true;\n } else {\n // Non-abort write failures (backpressure disconnects,\n // transform-stream exceptions, …) were previously swallowed\n // silently — `streamClosed` stayed `false` and the next\n // event re-attempted a broken writer. Log and mark the\n // stream closed so we stop trying.\n logError(error);\n streamClosed = true;\n }\n }\n }\n },\n error: async (error) => {\n reportAgentError(error, \"sse.subscription\");\n if (captureTelemetry) {\n telemetry.capture(\"oss.runtime.agent_execution_stream_errored\", {\n ...executionInfo,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n if (debug?.lifecycle) {\n debugLogger!.debug(\n { error: error instanceof Error ? error.message : String(error) },\n \"SSE stream errored\",\n );\n }\n logError(error);\n await closeStream();\n },\n complete: async () => {\n if (captureTelemetry) {\n telemetry.capture(\n \"oss.runtime.agent_execution_stream_ended\",\n executionInfo,\n );\n }\n if (debug?.lifecycle) {\n debugLogger!.debug(\n { eventCount, loggedEventCount },\n \"SSE stream completed\",\n );\n }\n await closeStream();\n },\n });\n\n // If the client disconnected before the subscription was created,\n // unsubscribe immediately to avoid leaking the observable.\n if (request.signal.aborted) {\n subscription.unsubscribe();\n }\n })().catch(async (error) => {\n reportAgentError(error, \"sse.factory\");\n logError(error);\n await closeStream();\n });\n\n request.signal.addEventListener(\"abort\", () => {\n subscription?.unsubscribe();\n });\n\n return new Response(stream.readable, {\n status: 200,\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n },\n });\n}\n\nfunction summarizeEvent(event: BaseEvent): Record<string, unknown> {\n const e = event as any;\n const summary: Record<string, unknown> = {};\n\n if (e.messageId) summary.messageId = e.messageId;\n if (e.toolCallId) summary.toolCallId = e.toolCallId;\n if (e.toolCallName) summary.toolCallName = e.toolCallName;\n if (e.role) summary.role = e.role;\n if (e.delta != null && typeof e.delta === \"string\")\n summary.deltaLength = e.delta.length;\n if (e.snapshot && typeof e.snapshot === \"object\")\n summary.snapshotKeys = Object.keys(e.snapshot);\n if (e.delta && Array.isArray(e.delta))\n summary.operationCount = e.delta.length;\n if (e.threadId) summary.threadId = e.threadId;\n if (e.runId) summary.runId = e.runId;\n if (e.message) summary.message = e.message;\n if (e.code) summary.code = e.code;\n if (e.stepName) summary.stepName = e.stepName;\n\n return summary;\n}\n\n/**\n * Accumulate provider, model, and LangGraph facts from one upstream event.\n *\n * Mutates rather than returns so the caller keeps one record across the whole\n * stream: these arrive on different events and the last one wins. Only fields\n * the upstream actually sent are set, so an agent that reports none leaves the\n * record empty and the stream events carry `{}` as before.\n *\n * `rawEvent` is the untransformed upstream payload, present on AG-UI events\n * that wrap one. Its shape is the provider's, not ours, hence the narrowing.\n */\nfunction collectExecutionInfo(\n event: BaseEvent,\n into: AgentExecutionResponseInfo,\n): void {\n const rawEvent = (\n event as {\n rawEvent?: {\n metadata?: Record<string, unknown>;\n data?: Record<string, unknown>;\n };\n }\n ).rawEvent;\n if (!rawEvent) return;\n\n const model = (rawEvent.data as { output?: { model?: string } } | undefined)\n ?.output?.model;\n if (model) {\n into.model = model;\n // Carried forward from the v1 implementation, which set both from the\n // same field. The upstream sends no separate provider name.\n into.provider = model;\n }\n\n const metadata = rawEvent.metadata as\n | { langgraph_host?: string; langgraph_version?: string }\n | undefined;\n if (metadata?.langgraph_host) into.langGraphHost = metadata.langgraph_host;\n if (metadata?.langgraph_version) {\n into.langGraphVersion = metadata.langgraph_version;\n }\n}\n"],"mappings":";;;;;;;AA6CA,SAAgB,uBAAuB,EACrC,SACA,mBACA,eACA,SACA,OACA,QACA,yBAAYA,kCACZ,eACA,mBAAmB,MACnB,sBACA,aACyC;CACzC,MAAM,SAAS,IAAI,iBAAiB;CACpC,MAAM,SAAS,OAAO,SAAS,WAAW;CAC1C,MAAM,UAAU,IAAIC,6BAAc;CAClC,IAAI,eAAe;CACnB,IAAI,gBAAgB;CACpB,IAAI,aAAa;CAEjB,MAAM,cAAc,OAAO,UACtB,UACDC,4BAAa;EAAE,OAAO;EAAS,WAAW;EAAoB,CAAC,GAC/D;CAEJ,MAAM,cAAc,YAAY;AAC9B,MAAI,CAAC,aACH,KAAI;AACF,SAAM,OAAO,OAAO;AACpB,kBAAe;UACT;;CAMZ,MAAM,YAAY,UAAmB;AACnC,UAAQ,MAAM,wBAAwB,MAAM;AAC5C,UAAQ,MACN,gBACA,iBAAiB,QAAQ,MAAM,QAAQ,iBACxC;AACD,UAAQ,MAAM,kBAAkB;GAC9B,MAAM,iBAAiB,QAAQ,MAAM,OAAO;GAC5C,SAAS,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,SAAS,QAAQ,OAAO,EAAE,UAAU,SACxC,SAAQ,cAAc,EAAE,MAAM;AAChC,KAAI,EAAE,YAAY,OAAO,EAAE,aAAa,SACtC,SAAQ,eAAe,OAAO,KAAK,EAAE,SAAS;AAChD,KAAI,EAAE,SAAS,MAAM,QAAQ,EAAE,MAAM,CACnC,SAAQ,iBAAiB,EAAE,MAAM;AACnC,KAAI,EAAE,SAAU,SAAQ,WAAW,EAAE;AACrC,KAAI,EAAE,MAAO,SAAQ,QAAQ,EAAE;AAC/B,KAAI,EAAE,QAAS,SAAQ,UAAU,EAAE;AACnC,KAAI,EAAE,KAAM,SAAQ,OAAO,EAAE;AAC7B,KAAI,EAAE,SAAU,SAAQ,WAAW,EAAE;AAErC,QAAO;;;;;;;;;;;;;AAcT,SAAS,qBACP,OACA,MACM;CACN,MAAM,WACJ,MAMA;AACF,KAAI,CAAC,SAAU;CAEf,MAAM,QAAS,SAAS,MACpB,QAAQ;AACZ,KAAI,OAAO;AACT,OAAK,QAAQ;AAGb,OAAK,WAAW;;CAGlB,MAAM,WAAW,SAAS;AAG1B,KAAI,UAAU,eAAgB,MAAK,gBAAgB,SAAS;AAC5D,KAAI,UAAU,kBACZ,MAAK,mBAAmB,SAAS"}
1
+ {"version":3,"file":"sse-response.cjs","names":["defaultTelemetry","resolveSseKeepAliveIntervalSeconds","EventEncoder","createLogger","keepAliveSse"],"sources":["../../../../../src/v2/runtime/handlers/shared/sse-response.ts"],"sourcesContent":["import type { BaseEvent } from \"@ag-ui/client\";\nimport { EventEncoder } from \"@ag-ui/encoder\";\nimport type { Observable, Subscription } from \"rxjs\";\nimport {\n keepAliveSse,\n resolveSseKeepAliveIntervalSeconds,\n} from \"./sse-keep-alive\";\nimport type { ResolvedDebugConfig } from \"@copilotkit/shared\";\nimport { createLogger } from \"../../../../v1-deprecated/lib/logger\";\nimport type { CopilotRuntimeLogger } from \"../../../../v1-deprecated/lib/logger\";\nimport { telemetry as defaultTelemetry } from \"../../telemetry\";\nimport type { TelemetryCapture } from \"../../telemetry/telemetry-client\";\nimport type { AgentExecutionResponseInfo } from \"../../telemetry/events\";\nimport type { DebugEventBus } from \"../../core/debug-event-bus\";\nimport type {\n RuntimeErrorPhase,\n RuntimeErrorReporter,\n} from \"../../core/runtime-error-reporter\";\n\ninterface CreateSseEventResponseParams {\n request: Request;\n observableFactory: () =>\n | Promise<Observable<BaseEvent>>\n | Observable<BaseEvent>;\n debugEventBus?: DebugEventBus;\n agentId?: string;\n debug?: ResolvedDebugConfig;\n /** Pre-created logger instance to avoid creating a new pino logger per request. */\n logger?: CopilotRuntimeLogger;\n /** Runtime-bound telemetry capture. Falls back for external direct callers. */\n telemetry?: TelemetryCapture;\n /**\n * Execution facts known before the stream opens, merged under anything the\n * upstream reports as it runs. Carries `llmHostClass`, which is knowable\n * from the agent's configuration and never appears on a streamed event.\n */\n executionSeed?: AgentExecutionResponseInfo;\n /**\n * Whether to emit `oss.runtime.agent_execution_stream_*` telemetry for this\n * stream. Defaults to `true`. The stateless `/suggest` path sets this to\n * `false`: a suggestion is a side-effect-free structured completion, not a\n * tracked run, and under `available: \"always\"` it fires often enough to flood\n * run telemetry.\n */\n captureTelemetry?: boolean;\n runtimeErrorReporter?: RuntimeErrorReporter;\n startTime?: number;\n /**\n * Seconds of silence before a `: keep-alive` SSE comment is written.\n * `0` disables the keep-alive. Resolved by\n * {@link resolveSseKeepAliveIntervalSeconds}, which supplies the default\n * and enforces the timer bound for every caller.\n */\n keepAliveIntervalSeconds?: number;\n}\n\nexport function createSseEventResponse({\n request,\n observableFactory,\n debugEventBus,\n agentId,\n debug,\n logger,\n telemetry = defaultTelemetry,\n executionSeed,\n captureTelemetry = true,\n runtimeErrorReporter,\n startTime,\n keepAliveIntervalSeconds,\n}: CreateSseEventResponseParams): Response {\n const keepAliveSeconds = resolveSseKeepAliveIntervalSeconds(\n keepAliveIntervalSeconds,\n );\n const stream = new TransformStream();\n const writer = stream.writable.getWriter();\n const encoder = new EventEncoder();\n let streamClosed = false;\n let debugThreadId = \"\";\n let debugRunId = \"\";\n\n const debugLogger = debug?.enabled\n ? (logger ??\n createLogger({ level: \"debug\", component: \"copilotkit-debug\" }))\n : undefined;\n\n const closeStream = async () => {\n if (!streamClosed) {\n try {\n await writer.close();\n streamClosed = true;\n } catch {\n // Stream already closed.\n }\n }\n };\n\n const logError = (error: unknown) => {\n console.error(\"Error running agent:\", error);\n console.error(\n \"Error stack:\",\n error instanceof Error ? error.stack : \"No stack trace\",\n );\n console.error(\"Error details:\", {\n name: error instanceof Error ? error.name : \"Unknown\",\n message: error instanceof Error ? error.message : String(error),\n cause: error instanceof Error ? error.cause : undefined,\n });\n };\n\n let subscription: Subscription | undefined;\n let agentErrorReported = false;\n\n const reportAgentError = (error: unknown, phase: RuntimeErrorPhase) => {\n if (agentErrorReported) return;\n agentErrorReported = true;\n runtimeErrorReporter?.report({\n request,\n error,\n operation: \"agent.run\",\n agentId,\n threadId: debugThreadId || undefined,\n runId: debugRunId || undefined,\n phase,\n startTime,\n });\n };\n\n (async () => {\n const observable = await observableFactory();\n\n if (captureTelemetry) {\n telemetry.capture(\"oss.runtime.agent_execution_stream_started\", {});\n }\n\n if (debug?.lifecycle) {\n debugLogger!.debug(\"SSE stream opened\");\n }\n\n let eventCount = 0;\n let loggedEventCount = 0;\n\n // Provider/model/LangGraph facts, scraped off raw upstream events as\n // they pass and reported once the stream finishes. This moved here from\n // the v1 TelemetryAgentRunner, which wrapped the runner purely to\n // collect it and emitted its own duplicate copy of every stream event\n // to carry it. v2 callers had no equivalent and reported `{}`.\n // Seeded rather than empty: `llmHostClass` comes from the agent's config,\n // not from the wire, so nothing streamed will ever fill it in. Scraped\n // fields still win, since `collectExecutionInfo` writes over this.\n const executionInfo: AgentExecutionResponseInfo = { ...executionSeed };\n\n subscription = observable.subscribe({\n next: async (event) => {\n collectExecutionInfo(event, executionInfo);\n\n // Extract threadId/runId from RUN_STARTED\n if (event.type === \"RUN_STARTED\") {\n const e = event as { threadId?: string; runId?: string };\n debugThreadId = e.threadId ?? \"\";\n debugRunId = e.runId ?? \"\";\n }\n\n if (event.type === \"RUN_ERROR\") {\n const e = event as {\n message?: unknown;\n threadId?: string;\n runId?: string;\n };\n debugThreadId = e.threadId ?? debugThreadId;\n debugRunId = e.runId ?? debugRunId;\n reportAgentError(\n new Error(\n typeof e.message === \"string\"\n ? e.message\n : \"Runner reported a run error\",\n ),\n \"sse.subscription\",\n );\n }\n\n // Broadcast to debug listeners BEFORE the stream-closed gate below.\n // Intentional: debug subscribers (e.g. the VS Code Inspector panel)\n // should still receive trailing events after the SSE client for\n // this request closed its connection — they're independent\n // consumers observing the underlying runtime, not the request's\n // response stream.\n //\n // Wrapped in try/catch so a buggy debug subscriber can't propagate\n // an exception into this observer — if the throw reached the\n // `next` callback it would get routed to `error` by RxJS, closing\n // the SSE stream for an unrelated reason. Log via `logError` and\n // move on.\n if (debugEventBus) {\n try {\n debugEventBus.broadcast(event, {\n agentId: agentId ?? \"\",\n threadId: debugThreadId,\n runId: debugRunId,\n });\n } catch (broadcastError) {\n logError(broadcastError);\n }\n }\n\n if (!request.signal.aborted && !streamClosed) {\n try {\n eventCount++;\n if (debug?.events) {\n loggedEventCount++;\n if (debug.verbose) {\n debugLogger!.debug({ event }, \"Event emitted\");\n } else {\n debugLogger!.debug(\n { type: event.type, ...summarizeEvent(event) },\n \"Event emitted\",\n );\n }\n }\n await writer.write(encoder.encodeBinary(event));\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n streamClosed = true;\n } else {\n // Non-abort write failures (backpressure disconnects,\n // transform-stream exceptions, …) were previously swallowed\n // silently — `streamClosed` stayed `false` and the next\n // event re-attempted a broken writer. Log and mark the\n // stream closed so we stop trying.\n logError(error);\n streamClosed = true;\n }\n }\n }\n },\n error: async (error) => {\n reportAgentError(error, \"sse.subscription\");\n if (captureTelemetry) {\n telemetry.capture(\"oss.runtime.agent_execution_stream_errored\", {\n ...executionInfo,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n if (debug?.lifecycle) {\n debugLogger!.debug(\n { error: error instanceof Error ? error.message : String(error) },\n \"SSE stream errored\",\n );\n }\n logError(error);\n await closeStream();\n },\n complete: async () => {\n if (captureTelemetry) {\n telemetry.capture(\n \"oss.runtime.agent_execution_stream_ended\",\n executionInfo,\n );\n }\n if (debug?.lifecycle) {\n debugLogger!.debug(\n { eventCount, loggedEventCount },\n \"SSE stream completed\",\n );\n }\n await closeStream();\n },\n });\n\n // If the client disconnected before the subscription was created,\n // unsubscribe immediately to avoid leaking the observable.\n if (request.signal.aborted) {\n subscription.unsubscribe();\n }\n })().catch(async (error) => {\n reportAgentError(error, \"sse.factory\");\n logError(error);\n await closeStream();\n });\n\n request.signal.addEventListener(\"abort\", () => {\n subscription?.unsubscribe();\n });\n\n const body =\n keepAliveSeconds > 0\n ? keepAliveSse(stream.readable, keepAliveSeconds * 1_000)\n : stream.readable;\n\n return new Response(body, {\n status: 200,\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n },\n });\n}\n\nfunction summarizeEvent(event: BaseEvent): Record<string, unknown> {\n const e = event as any;\n const summary: Record<string, unknown> = {};\n\n if (e.messageId) summary.messageId = e.messageId;\n if (e.toolCallId) summary.toolCallId = e.toolCallId;\n if (e.toolCallName) summary.toolCallName = e.toolCallName;\n if (e.role) summary.role = e.role;\n if (e.delta != null && typeof e.delta === \"string\")\n summary.deltaLength = e.delta.length;\n if (e.snapshot && typeof e.snapshot === \"object\")\n summary.snapshotKeys = Object.keys(e.snapshot);\n if (e.delta && Array.isArray(e.delta))\n summary.operationCount = e.delta.length;\n if (e.threadId) summary.threadId = e.threadId;\n if (e.runId) summary.runId = e.runId;\n if (e.message) summary.message = e.message;\n if (e.code) summary.code = e.code;\n if (e.stepName) summary.stepName = e.stepName;\n\n return summary;\n}\n\n/**\n * Accumulate provider, model, and LangGraph facts from one upstream event.\n *\n * Mutates rather than returns so the caller keeps one record across the whole\n * stream: these arrive on different events and the last one wins. Only fields\n * the upstream actually sent are set, so an agent that reports none leaves the\n * record empty and the stream events carry `{}` as before.\n *\n * `rawEvent` is the untransformed upstream payload, present on AG-UI events\n * that wrap one. Its shape is the provider's, not ours, hence the narrowing.\n */\nfunction collectExecutionInfo(\n event: BaseEvent,\n into: AgentExecutionResponseInfo,\n): void {\n const rawEvent = (\n event as {\n rawEvent?: {\n metadata?: Record<string, unknown>;\n data?: Record<string, unknown>;\n };\n }\n ).rawEvent;\n if (!rawEvent) return;\n\n const model = (rawEvent.data as { output?: { model?: string } } | undefined)\n ?.output?.model;\n if (model) {\n into.model = model;\n // Carried forward from the v1 implementation, which set both from the\n // same field. The upstream sends no separate provider name.\n into.provider = model;\n }\n\n const metadata = rawEvent.metadata as\n | { langgraph_host?: string; langgraph_version?: string }\n | undefined;\n if (metadata?.langgraph_host) into.langGraphHost = metadata.langgraph_host;\n if (metadata?.langgraph_version) {\n into.langGraphVersion = metadata.langgraph_version;\n }\n}\n"],"mappings":";;;;;;;;AAwDA,SAAgB,uBAAuB,EACrC,SACA,mBACA,eACA,SACA,OACA,QACA,yBAAYA,kCACZ,eACA,mBAAmB,MACnB,sBACA,WACA,4BACyC;CACzC,MAAM,mBAAmBC,0DACvB,yBACD;CACD,MAAM,SAAS,IAAI,iBAAiB;CACpC,MAAM,SAAS,OAAO,SAAS,WAAW;CAC1C,MAAM,UAAU,IAAIC,6BAAc;CAClC,IAAI,eAAe;CACnB,IAAI,gBAAgB;CACpB,IAAI,aAAa;CAEjB,MAAM,cAAc,OAAO,UACtB,UACDC,4BAAa;EAAE,OAAO;EAAS,WAAW;EAAoB,CAAC,GAC/D;CAEJ,MAAM,cAAc,YAAY;AAC9B,MAAI,CAAC,aACH,KAAI;AACF,SAAM,OAAO,OAAO;AACpB,kBAAe;UACT;;CAMZ,MAAM,YAAY,UAAmB;AACnC,UAAQ,MAAM,wBAAwB,MAAM;AAC5C,UAAQ,MACN,gBACA,iBAAiB,QAAQ,MAAM,QAA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,YAAY,EAAE;AACvC,KAAI,EAAE,WAAY,SAAQ,aAAa,EAAE;AACzC,KAAI,EAAE,aAAc,SAAQ,eAAe,EAAE;AAC7C,KAAI,EAAE,KAAM,SAAQ,OAAO,EAAE;AAC7B,KAAI,EAAE,SAAS,QAAQ,OAAO,EAAE,UAAU,SACxC,SAAQ,cAAc,EAAE,MAAM;AAChC,KAAI,EAAE,YAAY,OAAO,EAAE,aAAa,SACtC,SAAQ,eAAe,OAAO,KAAK,EAAE,SAAS;AAChD,KAAI,EAAE,SAAS,MAAM,QAAQ,EAAE,MAAM,CACnC,SAAQ,iBAAiB,EAAE,MAAM;AACnC,KAAI,EAAE,SAAU,SAAQ,WAAW,EAAE;AACrC,KAAI,EAAE,MAAO,SAAQ,QAAQ,EAAE;AAC/B,KAAI,EAAE,QAAS,SAAQ,UAAU,EAAE;AACnC,KAAI,EAAE,KAAM,SAAQ,OAAO,EAAE;AAC7B,KAAI,EAAE,SAAU,SAAQ,WAAW,EAAE;AAErC,QAAO;;;;;;;;;;;;;AAcT,SAAS,qBACP,OACA,MACM;CACN,MAAM,WACJ,MAMA;AACF,KAAI,CAAC,SAAU;CAEf,MAAM,QAAS,SAAS,MACpB,QAAQ;AACZ,KAAI,OAAO;AACT,OAAK,QAAQ;AAGb,OAAK,WAAW;;CAGlB,MAAM,WAAW,SAAS;AAG1B,KAAI,UAAU,eAAgB,MAAK,gBAAgB,SAAS;AAC5D,KAAI,UAAU,kBACZ,MAAK,mBAAmB,SAAS"}
@@ -1,10 +1,12 @@
1
1
  import "reflect-metadata";
2
2
  import { createLogger } from "../../../../lib/logger.mjs";
3
+ import { keepAliveSse, resolveSseKeepAliveIntervalSeconds } from "./sse-keep-alive.mjs";
3
4
  import telemetry from "../../telemetry/telemetry-client.mjs";
4
5
  import { EventEncoder } from "@ag-ui/encoder";
5
6
 
6
7
  //#region src/v2/runtime/handlers/shared/sse-response.ts
7
- function createSseEventResponse({ request, observableFactory, debugEventBus, agentId, debug, logger, telemetry: telemetry$1 = telemetry, executionSeed, captureTelemetry = true, runtimeErrorReporter, startTime }) {
8
+ function createSseEventResponse({ request, observableFactory, debugEventBus, agentId, debug, logger, telemetry: telemetry$1 = telemetry, executionSeed, captureTelemetry = true, runtimeErrorReporter, startTime, keepAliveIntervalSeconds }) {
9
+ const keepAliveSeconds = resolveSseKeepAliveIntervalSeconds(keepAliveIntervalSeconds);
8
10
  const stream = new TransformStream();
9
11
  const writer = stream.writable.getWriter();
10
12
  const encoder = new EventEncoder();
@@ -123,7 +125,8 @@ function createSseEventResponse({ request, observableFactory, debugEventBus, age
123
125
  request.signal.addEventListener("abort", () => {
124
126
  subscription?.unsubscribe();
125
127
  });
126
- return new Response(stream.readable, {
128
+ const body = keepAliveSeconds > 0 ? keepAliveSse(stream.readable, keepAliveSeconds * 1e3) : stream.readable;
129
+ return new Response(body, {
127
130
  status: 200,
128
131
  headers: {
129
132
  "Content-Type": "text/event-stream",
@@ -1 +1 @@
1
- {"version":3,"file":"sse-response.mjs","names":["defaultTelemetry"],"sources":["../../../../../src/v2/runtime/handlers/shared/sse-response.ts"],"sourcesContent":["import type { BaseEvent } from \"@ag-ui/client\";\nimport { EventEncoder } from \"@ag-ui/encoder\";\nimport type { Observable, Subscription } from \"rxjs\";\nimport type { ResolvedDebugConfig } from \"@copilotkit/shared\";\nimport { createLogger } from \"../../../../v1-deprecated/lib/logger\";\nimport type { CopilotRuntimeLogger } from \"../../../../v1-deprecated/lib/logger\";\nimport { telemetry as defaultTelemetry } from \"../../telemetry\";\nimport type { TelemetryCapture } from \"../../telemetry/telemetry-client\";\nimport type { AgentExecutionResponseInfo } from \"../../telemetry/events\";\nimport type { DebugEventBus } from \"../../core/debug-event-bus\";\nimport type {\n RuntimeErrorPhase,\n RuntimeErrorReporter,\n} from \"../../core/runtime-error-reporter\";\n\ninterface CreateSseEventResponseParams {\n request: Request;\n observableFactory: () =>\n | Promise<Observable<BaseEvent>>\n | Observable<BaseEvent>;\n debugEventBus?: DebugEventBus;\n agentId?: string;\n debug?: ResolvedDebugConfig;\n /** Pre-created logger instance to avoid creating a new pino logger per request. */\n logger?: CopilotRuntimeLogger;\n /** Runtime-bound telemetry capture. Falls back for external direct callers. */\n telemetry?: TelemetryCapture;\n /**\n * Execution facts known before the stream opens, merged under anything the\n * upstream reports as it runs. Carries `llmHostClass`, which is knowable\n * from the agent's configuration and never appears on a streamed event.\n */\n executionSeed?: AgentExecutionResponseInfo;\n /**\n * Whether to emit `oss.runtime.agent_execution_stream_*` telemetry for this\n * stream. Defaults to `true`. The stateless `/suggest` path sets this to\n * `false`: a suggestion is a side-effect-free structured completion, not a\n * tracked run, and under `available: \"always\"` it fires often enough to flood\n * run telemetry.\n */\n captureTelemetry?: boolean;\n runtimeErrorReporter?: RuntimeErrorReporter;\n startTime?: number;\n}\n\nexport function createSseEventResponse({\n request,\n observableFactory,\n debugEventBus,\n agentId,\n debug,\n logger,\n telemetry = defaultTelemetry,\n executionSeed,\n captureTelemetry = true,\n runtimeErrorReporter,\n startTime,\n}: CreateSseEventResponseParams): Response {\n const stream = new TransformStream();\n const writer = stream.writable.getWriter();\n const encoder = new EventEncoder();\n let streamClosed = false;\n let debugThreadId = \"\";\n let debugRunId = \"\";\n\n const debugLogger = debug?.enabled\n ? (logger ??\n createLogger({ level: \"debug\", component: \"copilotkit-debug\" }))\n : undefined;\n\n const closeStream = async () => {\n if (!streamClosed) {\n try {\n await writer.close();\n streamClosed = true;\n } catch {\n // Stream already closed.\n }\n }\n };\n\n const logError = (error: unknown) => {\n console.error(\"Error running agent:\", error);\n console.error(\n \"Error stack:\",\n error instanceof Error ? error.stack : \"No stack trace\",\n );\n console.error(\"Error details:\", {\n name: error instanceof Error ? error.name : \"Unknown\",\n message: error instanceof Error ? error.message : String(error),\n cause: error instanceof Error ? error.cause : undefined,\n });\n };\n\n let subscription: Subscription | undefined;\n let agentErrorReported = false;\n\n const reportAgentError = (error: unknown, phase: RuntimeErrorPhase) => {\n if (agentErrorReported) return;\n agentErrorReported = true;\n runtimeErrorReporter?.report({\n request,\n error,\n operation: \"agent.run\",\n agentId,\n threadId: debugThreadId || undefined,\n runId: debugRunId || undefined,\n phase,\n startTime,\n });\n };\n\n (async () => {\n const observable = await observableFactory();\n\n if (captureTelemetry) {\n telemetry.capture(\"oss.runtime.agent_execution_stream_started\", {});\n }\n\n if (debug?.lifecycle) {\n debugLogger!.debug(\"SSE stream opened\");\n }\n\n let eventCount = 0;\n let loggedEventCount = 0;\n\n // Provider/model/LangGraph facts, scraped off raw upstream events as\n // they pass and reported once the stream finishes. This moved here from\n // the v1 TelemetryAgentRunner, which wrapped the runner purely to\n // collect it and emitted its own duplicate copy of every stream event\n // to carry it. v2 callers had no equivalent and reported `{}`.\n // Seeded rather than empty: `llmHostClass` comes from the agent's config,\n // not from the wire, so nothing streamed will ever fill it in. Scraped\n // fields still win, since `collectExecutionInfo` writes over this.\n const executionInfo: AgentExecutionResponseInfo = { ...executionSeed };\n\n subscription = observable.subscribe({\n next: async (event) => {\n collectExecutionInfo(event, executionInfo);\n\n // Extract threadId/runId from RUN_STARTED\n if (event.type === \"RUN_STARTED\") {\n const e = event as { threadId?: string; runId?: string };\n debugThreadId = e.threadId ?? \"\";\n debugRunId = e.runId ?? \"\";\n }\n\n if (event.type === \"RUN_ERROR\") {\n const e = event as {\n message?: unknown;\n threadId?: string;\n runId?: string;\n };\n debugThreadId = e.threadId ?? debugThreadId;\n debugRunId = e.runId ?? debugRunId;\n reportAgentError(\n new Error(\n typeof e.message === \"string\"\n ? e.message\n : \"Runner reported a run error\",\n ),\n \"sse.subscription\",\n );\n }\n\n // Broadcast to debug listeners BEFORE the stream-closed gate below.\n // Intentional: debug subscribers (e.g. the VS Code Inspector panel)\n // should still receive trailing events after the SSE client for\n // this request closed its connection — they're independent\n // consumers observing the underlying runtime, not the request's\n // response stream.\n //\n // Wrapped in try/catch so a buggy debug subscriber can't propagate\n // an exception into this observer — if the throw reached the\n // `next` callback it would get routed to `error` by RxJS, closing\n // the SSE stream for an unrelated reason. Log via `logError` and\n // move on.\n if (debugEventBus) {\n try {\n debugEventBus.broadcast(event, {\n agentId: agentId ?? \"\",\n threadId: debugThreadId,\n runId: debugRunId,\n });\n } catch (broadcastError) {\n logError(broadcastError);\n }\n }\n\n if (!request.signal.aborted && !streamClosed) {\n try {\n eventCount++;\n if (debug?.events) {\n loggedEventCount++;\n if (debug.verbose) {\n debugLogger!.debug({ event }, \"Event emitted\");\n } else {\n debugLogger!.debug(\n { type: event.type, ...summarizeEvent(event) },\n \"Event emitted\",\n );\n }\n }\n await writer.write(encoder.encodeBinary(event));\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n streamClosed = true;\n } else {\n // Non-abort write failures (backpressure disconnects,\n // transform-stream exceptions, …) were previously swallowed\n // silently — `streamClosed` stayed `false` and the next\n // event re-attempted a broken writer. Log and mark the\n // stream closed so we stop trying.\n logError(error);\n streamClosed = true;\n }\n }\n }\n },\n error: async (error) => {\n reportAgentError(error, \"sse.subscription\");\n if (captureTelemetry) {\n telemetry.capture(\"oss.runtime.agent_execution_stream_errored\", {\n ...executionInfo,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n if (debug?.lifecycle) {\n debugLogger!.debug(\n { error: error instanceof Error ? error.message : String(error) },\n \"SSE stream errored\",\n );\n }\n logError(error);\n await closeStream();\n },\n complete: async () => {\n if (captureTelemetry) {\n telemetry.capture(\n \"oss.runtime.agent_execution_stream_ended\",\n executionInfo,\n );\n }\n if (debug?.lifecycle) {\n debugLogger!.debug(\n { eventCount, loggedEventCount },\n \"SSE stream completed\",\n );\n }\n await closeStream();\n },\n });\n\n // If the client disconnected before the subscription was created,\n // unsubscribe immediately to avoid leaking the observable.\n if (request.signal.aborted) {\n subscription.unsubscribe();\n }\n })().catch(async (error) => {\n reportAgentError(error, \"sse.factory\");\n logError(error);\n await closeStream();\n });\n\n request.signal.addEventListener(\"abort\", () => {\n subscription?.unsubscribe();\n });\n\n return new Response(stream.readable, {\n status: 200,\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n },\n });\n}\n\nfunction summarizeEvent(event: BaseEvent): Record<string, unknown> {\n const e = event as any;\n const summary: Record<string, unknown> = {};\n\n if (e.messageId) summary.messageId = e.messageId;\n if (e.toolCallId) summary.toolCallId = e.toolCallId;\n if (e.toolCallName) summary.toolCallName = e.toolCallName;\n if (e.role) summary.role = e.role;\n if (e.delta != null && typeof e.delta === \"string\")\n summary.deltaLength = e.delta.length;\n if (e.snapshot && typeof e.snapshot === \"object\")\n summary.snapshotKeys = Object.keys(e.snapshot);\n if (e.delta && Array.isArray(e.delta))\n summary.operationCount = e.delta.length;\n if (e.threadId) summary.threadId = e.threadId;\n if (e.runId) summary.runId = e.runId;\n if (e.message) summary.message = e.message;\n if (e.code) summary.code = e.code;\n if (e.stepName) summary.stepName = e.stepName;\n\n return summary;\n}\n\n/**\n * Accumulate provider, model, and LangGraph facts from one upstream event.\n *\n * Mutates rather than returns so the caller keeps one record across the whole\n * stream: these arrive on different events and the last one wins. Only fields\n * the upstream actually sent are set, so an agent that reports none leaves the\n * record empty and the stream events carry `{}` as before.\n *\n * `rawEvent` is the untransformed upstream payload, present on AG-UI events\n * that wrap one. Its shape is the provider's, not ours, hence the narrowing.\n */\nfunction collectExecutionInfo(\n event: BaseEvent,\n into: AgentExecutionResponseInfo,\n): void {\n const rawEvent = (\n event as {\n rawEvent?: {\n metadata?: Record<string, unknown>;\n data?: Record<string, unknown>;\n };\n }\n ).rawEvent;\n if (!rawEvent) return;\n\n const model = (rawEvent.data as { output?: { model?: string } } | undefined)\n ?.output?.model;\n if (model) {\n into.model = model;\n // Carried forward from the v1 implementation, which set both from the\n // same field. The upstream sends no separate provider name.\n into.provider = model;\n }\n\n const metadata = rawEvent.metadata as\n | { langgraph_host?: string; langgraph_version?: string }\n | undefined;\n if (metadata?.langgraph_host) into.langGraphHost = metadata.langgraph_host;\n if (metadata?.langgraph_version) {\n into.langGraphV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AC,SAAU;CAEf,MAAM,QAAS,SAAS,MACpB,QAAQ;AACZ,KAAI,OAAO;AACT,OAAK,QAAQ;AAGb,OAAK,WAAW;;CAGlB,MAAM,WAAW,SAAS;AAG1B,KAAI,UAAU,eAAgB,MAAK,gBAAgB,SAAS;AAC5D,KAAI,UAAU,kBACZ,MAAK,mBAAmB,SAAS"}
1
+ {"version":3,"file":"sse-response.mjs","names":["defaultTelemetry"],"sources":["../../../../../src/v2/runtime/handlers/shared/sse-response.ts"],"sourcesContent":["import type { BaseEvent } from \"@ag-ui/client\";\nimport { EventEncoder } from \"@ag-ui/encoder\";\nimport type { Observable, Subscription } from \"rxjs\";\nimport {\n keepAliveSse,\n resolveSseKeepAliveIntervalSeconds,\n} from \"./sse-keep-alive\";\nimport type { ResolvedDebugConfig } from \"@copilotkit/shared\";\nimport { createLogger } from \"../../../../v1-deprecated/lib/logger\";\nimport type { CopilotRuntimeLogger } from \"../../../../v1-deprecated/lib/logger\";\nimport { telemetry as defaultTelemetry } from \"../../telemetry\";\nimport type { TelemetryCapture } from \"../../telemetry/telemetry-client\";\nimport type { AgentExecutionResponseInfo } from \"../../telemetry/events\";\nimport type { DebugEventBus } from \"../../core/debug-event-bus\";\nimport type {\n RuntimeErrorPhase,\n RuntimeErrorReporter,\n} from \"../../core/runtime-error-reporter\";\n\ninterface CreateSseEventResponseParams {\n request: Request;\n observableFactory: () =>\n | Promise<Observable<BaseEvent>>\n | Observable<BaseEvent>;\n debugEventBus?: DebugEventBus;\n agentId?: string;\n debug?: ResolvedDebugConfig;\n /** Pre-created logger instance to avoid creating a new pino logger per request. */\n logger?: CopilotRuntimeLogger;\n /** Runtime-bound telemetry capture. Falls back for external direct callers. */\n telemetry?: TelemetryCapture;\n /**\n * Execution facts known before the stream opens, merged under anything the\n * upstream reports as it runs. Carries `llmHostClass`, which is knowable\n * from the agent's configuration and never appears on a streamed event.\n */\n executionSeed?: AgentExecutionResponseInfo;\n /**\n * Whether to emit `oss.runtime.agent_execution_stream_*` telemetry for this\n * stream. Defaults to `true`. The stateless `/suggest` path sets this to\n * `false`: a suggestion is a side-effect-free structured completion, not a\n * tracked run, and under `available: \"always\"` it fires often enough to flood\n * run telemetry.\n */\n captureTelemetry?: boolean;\n runtimeErrorReporter?: RuntimeErrorReporter;\n startTime?: number;\n /**\n * Seconds of silence before a `: keep-alive` SSE comment is written.\n * `0` disables the keep-alive. Resolved by\n * {@link resolveSseKeepAliveIntervalSeconds}, which supplies the default\n * and enforces the timer bound for every caller.\n */\n keepAliveIntervalSeconds?: number;\n}\n\nexport function createSseEventResponse({\n request,\n observableFactory,\n debugEventBus,\n agentId,\n debug,\n logger,\n telemetry = defaultTelemetry,\n executionSeed,\n captureTelemetry = true,\n runtimeErrorReporter,\n startTime,\n keepAliveIntervalSeconds,\n}: CreateSseEventResponseParams): Response {\n const keepAliveSeconds = resolveSseKeepAliveIntervalSeconds(\n keepAliveIntervalSeconds,\n );\n const stream = new TransformStream();\n const writer = stream.writable.getWriter();\n const encoder = new EventEncoder();\n let streamClosed = false;\n let debugThreadId = \"\";\n let debugRunId = \"\";\n\n const debugLogger = debug?.enabled\n ? (logger ??\n createLogger({ level: \"debug\", component: \"copilotkit-debug\" }))\n : undefined;\n\n const closeStream = async () => {\n if (!streamClosed) {\n try {\n await writer.close();\n streamClosed = true;\n } catch {\n // Stream already closed.\n }\n }\n };\n\n const logError = (error: unknown) => {\n console.error(\"Error running agent:\", error);\n console.error(\n \"Error stack:\",\n error instanceof Error ? error.stack : \"No stack trace\",\n );\n console.error(\"Error details:\", {\n name: error instanceof Error ? error.name : \"Unknown\",\n message: error instanceof Error ? error.message : String(error),\n cause: error instanceof Error ? error.cause : undefined,\n });\n };\n\n let subscription: Subscription | undefined;\n let agentErrorReported = false;\n\n const reportAgentError = (error: unknown, phase: RuntimeErrorPhase) => {\n if (agentErrorReported) return;\n agentErrorReported = true;\n runtimeErrorReporter?.report({\n request,\n error,\n operation: \"agent.run\",\n agentId,\n threadId: debugThreadId || undefined,\n runId: debugRunId || undefined,\n phase,\n startTime,\n });\n };\n\n (async () => {\n const observable = await observableFactory();\n\n if (captureTelemetry) {\n telemetry.capture(\"oss.runtime.agent_execution_stream_started\", {});\n }\n\n if (debug?.lifecycle) {\n debugLogger!.debug(\"SSE stream opened\");\n }\n\n let eventCount = 0;\n let loggedEventCount = 0;\n\n // Provider/model/LangGraph facts, scraped off raw upstream events as\n // they pass and reported once the stream finishes. This moved here from\n // the v1 TelemetryAgentRunner, which wrapped the runner purely to\n // collect it and emitted its own duplicate copy of every stream event\n // to carry it. v2 callers had no equivalent and reported `{}`.\n // Seeded rather than empty: `llmHostClass` comes from the agent's config,\n // not from the wire, so nothing streamed will ever fill it in. Scraped\n // fields still win, since `collectExecutionInfo` writes over this.\n const executionInfo: AgentExecutionResponseInfo = { ...executionSeed };\n\n subscription = observable.subscribe({\n next: async (event) => {\n collectExecutionInfo(event, executionInfo);\n\n // Extract threadId/runId from RUN_STARTED\n if (event.type === \"RUN_STARTED\") {\n const e = event as { threadId?: string; runId?: string };\n debugThreadId = e.threadId ?? \"\";\n debugRunId = e.runId ?? \"\";\n }\n\n if (event.type === \"RUN_ERROR\") {\n const e = event as {\n message?: unknown;\n threadId?: string;\n runId?: string;\n };\n debugThreadId = e.threadId ?? debugThreadId;\n debugRunId = e.runId ?? debugRunId;\n reportAgentError(\n new Error(\n typeof e.message === \"string\"\n ? e.message\n : \"Runner reported a run error\",\n ),\n \"sse.subscription\",\n );\n }\n\n // Broadcast to debug listeners BEFORE the stream-closed gate below.\n // Intentional: debug subscribers (e.g. the VS Code Inspector panel)\n // should still receive trailing events after the SSE client for\n // this request closed its connection — they're independent\n // consumers observing the underlying runtime, not the request's\n // response stream.\n //\n // Wrapped in try/catch so a buggy debug subscriber can't propagate\n // an exception into this observer — if the throw reached the\n // `next` callback it would get routed to `error` by RxJS, closing\n // the SSE stream for an unrelated reason. Log via `logError` and\n // move on.\n if (debugEventBus) {\n try {\n debugEventBus.broadcast(event, {\n agentId: agentId ?? \"\",\n threadId: debugThreadId,\n runId: debugRunId,\n });\n } catch (broadcastError) {\n logError(broadcastError);\n }\n }\n\n if (!request.signal.aborted && !streamClosed) {\n try {\n eventCount++;\n if (debug?.events) {\n loggedEventCount++;\n if (debug.verbose) {\n debugLogger!.debug({ event }, \"Event emitted\");\n } else {\n debugLogger!.debug(\n { type: event.type, ...summarizeEvent(event) },\n \"Event emitted\",\n );\n }\n }\n await writer.write(encoder.encodeBinary(event));\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n streamClosed = true;\n } else {\n // Non-abort write failures (backpressure disconnects,\n // transform-stream exceptions, …) were previously swallowed\n // silently — `streamClosed` stayed `false` and the next\n // event re-attempted a broken writer. Log and mark the\n // stream closed so we stop trying.\n logError(error);\n streamClosed = true;\n }\n }\n }\n },\n error: async (error) => {\n reportAgentError(error, \"sse.subscription\");\n if (captureTelemetry) {\n telemetry.capture(\"oss.runtime.agent_execution_stream_errored\", {\n ...executionInfo,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n if (debug?.lifecycle) {\n debugLogger!.debug(\n { error: error instanceof Error ? error.message : String(error) },\n \"SSE stream errored\",\n );\n }\n logError(error);\n await closeStream();\n },\n complete: async () => {\n if (captureTelemetry) {\n telemetry.capture(\n \"oss.runtime.agent_execution_stream_ended\",\n executionInfo,\n );\n }\n if (debug?.lifecycle) {\n debugLogger!.debug(\n { eventCount, loggedEventCount },\n \"SSE stream completed\",\n );\n }\n await closeStream();\n },\n });\n\n // If the client disconnected before the subscription was created,\n // unsubscribe immediately to avoid leaking the observable.\n if (request.signal.aborted) {\n subscription.unsubscribe();\n }\n })().catch(async (error) => {\n reportAgentError(error, \"sse.factory\");\n logError(error);\n await closeStream();\n });\n\n request.signal.addEventListener(\"abort\", () => {\n subscription?.unsubscribe();\n });\n\n const body =\n keepAliveSeconds > 0\n ? keepAliveSse(stream.readable, keepAliveSeconds * 1_000)\n : stream.readable;\n\n return new Response(body, {\n status: 200,\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n },\n });\n}\n\nfunction summarizeEvent(event: BaseEvent): Record<string, unknown> {\n const e = event as any;\n const summary: Record<string, unknown> = {};\n\n if (e.messageId) summary.messageId = e.messageId;\n if (e.toolCallId) summary.toolCallId = e.toolCallId;\n if (e.toolCallName) summary.toolCallName = e.toolCallName;\n if (e.role) summary.role = e.role;\n if (e.delta != null && typeof e.delta === \"string\")\n summary.deltaLength = e.delta.length;\n if (e.snapshot && typeof e.snapshot === \"object\")\n summary.snapshotKeys = Object.keys(e.snapshot);\n if (e.delta && Array.isArray(e.delta))\n summary.operationCount = e.delta.length;\n if (e.threadId) summary.threadId = e.threadId;\n if (e.runId) summary.runId = e.runId;\n if (e.message) summary.message = e.message;\n if (e.code) summary.code = e.code;\n if (e.stepName) summary.stepName = e.stepName;\n\n return summary;\n}\n\n/**\n * Accumulate provider, model, and LangGraph facts from one upstream event.\n *\n * Mutates rather than returns so the caller keeps one record across the whole\n * stream: these arrive on different events and the last one wins. Only fields\n * the upstream actually sent are set, so an agent that reports none leaves the\n * record empty and the stream events carry `{}` as before.\n *\n * `rawEvent` is the untransformed upstream payload, present on AG-UI events\n * that wrap one. Its shape is the provider's, not ours, hence the narrowing.\n */\nfunction collectExecutionInfo(\n event: BaseEvent,\n into: AgentExecutionResponseInfo,\n): void {\n const rawEvent = (\n event as {\n rawEvent?: {\n metadata?: Record<string, unknown>;\n data?: Record<string, unknown>;\n };\n }\n ).rawEvent;\n if (!rawEvent) return;\n\n const model = (rawEvent.data as { output?: { model?: string } } | undefined)\n ?.output?.model;\n if (model) {\n into.model = model;\n // Carried forward from the v1 implementation, which set both from the\n // same field. The upstream sends no separate provider name.\n into.provider = model;\n }\n\n const metadata = rawEvent.metadata as\n | { langgraph_host?: string; langgraph_version?: string }\n | undefined;\n if (metadata?.langgraph_host) into.langGraphHost = metadata.langgraph_host;\n if (metadata?.langgraph_version) {\n into.langGraphVersion = met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,WAAW,EAAE;AAErC,QAAO;;;;;;;;;;;;;AAcT,SAAS,qBACP,OACA,MACM;CACN,MAAM,WACJ,MAMA;AACF,KAAI,CAAC,SAAU;CAEf,MAAM,QAAS,SAAS,MACpB,QAAQ;AACZ,KAAI,OAAO;AACT,OAAK,QAAQ;AAGb,OAAK,WAAW;;CAGlB,MAAM,WAAW,SAAS;AAG1B,KAAI,UAAU,eAAgB,MAAK,gBAAgB,SAAS;AAC5D,KAAI,UAAU,kBACZ,MAAK,mBAAmB,SAAS"}
@@ -9,6 +9,7 @@ function handleSseConnect({ runtime, request, agentId, threadId, agent }) {
9
9
  debugEventBus: runtime.debugEventBus,
10
10
  agentId,
11
11
  telemetry: runtime.telemetry,
12
+ keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,
12
13
  observableFactory: () => runtime.runner.connect({
13
14
  threadId,
14
15
  agentId,
@@ -1 +1 @@
1
- {"version":3,"file":"connect.cjs","names":["createSseEventResponse","mergeForwardableHeaders","resolveForwardHeadersPolicy"],"sources":["../../../../../src/v2/runtime/handlers/sse/connect.ts"],"sourcesContent":["import type { AbstractAgent } from \"@ag-ui/client\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { createSseEventResponse } from \"../shared/sse-response\";\nimport {\n mergeForwardableHeaders,\n resolveForwardHeadersPolicy,\n} from \"../header-utils\";\n\n/**\n * `headers` lives on the HTTP-backed agent configs (e.g. `HttpAgent`), not on\n * the base `AbstractAgent`. Mirror the runtime's own optional-headers shape so\n * we can read server-configured headers off the per-request clone without a\n * cast. See `agent-utils.ts`.\n */\ntype AgentWithHeaders = AbstractAgent & {\n headers?: Record<string, string>;\n};\n\ninterface HandleSseConnectParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n agentId: string;\n threadId: string;\n /**\n * The per-request agent clone, carrying any server-configured `agent.headers`\n * (e.g. service-to-service auth). Used only to compute the merged header set\n * threaded into `runner.connect` below — see the note there for why that\n * merge is forward-looking plumbing rather than active outbound auth today.\n */\n agent?: AgentWithHeaders;\n}\n\nexport function handleSseConnect({\n runtime,\n request,\n agentId,\n threadId,\n agent,\n}: HandleSseConnectParams): Response {\n return createSseEventResponse({\n request,\n debugEventBus: runtime.debugEventBus,\n // Forward the real agentId so debug envelopes reflect the agent the\n // route resolved to — not the literal string \"connect\".\n agentId,\n telemetry: runtime.telemetry,\n observableFactory: () =>\n runtime.runner.connect({\n threadId,\n agentId,\n // Forward-looking plumbing: we compute the merged header set (server\n // `agent.headers` win on collision, case-insensitively; non-colliding\n // inbound headers still forward — see `mergeForwardableHeaders`, #5712)\n // and thread it into `runner.connect`. NO shipped runner consumes the\n // `headers` field of `AgentRunnerConnectRequest` today — every runner\n // (in-memory, intelligence, telemetry, sqlite) reads only `threadId`.\n // The real outbound header forwarding is the /run path, where\n // `cloneAgentForRequest` mutates `agent.headers` directly\n // (agent-utils.ts). This wiring exists so a future outbound-connecting\n // runner can pick the merged headers up without a route change; the\n // collision precedence noted here is purely about that merge, not about\n // middleware/mutation parity with /run.\n headers: mergeForwardableHeaders(\n agent?.headers,\n request,\n // Optional on `CopilotRuntimeLike` (non-breaking minor release);\n // coalesce a policy-less external implementor to the default resolved\n // policy (default-on denylist) instead of dereffing undefined.\n runtime.forwardHeadersPolicy ??\n resolveForwardHeadersPolicy(undefined),\n ),\n }),\n });\n}\n"],"mappings":";;;;;AAgCA,SAAgB,iBAAiB,EAC/B,SACA,SACA,SACA,UACA,SACmC;AACnC,QAAOA,4CAAuB;EAC5B;EACA,eAAe,QAAQ;EAGvB;EACA,WAAW,QAAQ;EACnB,yBACE,QAAQ,OAAO,QAAQ;GACrB;GACA;GAaA,SAASC,6CACP,OAAO,SACP,SAIA,QAAQ,wBACNC,iDAA4B,OAAU,CACzC;GACF,CAAC;EACL,CAAC"}
1
+ {"version":3,"file":"connect.cjs","names":["createSseEventResponse","mergeForwardableHeaders","resolveForwardHeadersPolicy"],"sources":["../../../../../src/v2/runtime/handlers/sse/connect.ts"],"sourcesContent":["import type { AbstractAgent } from \"@ag-ui/client\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { createSseEventResponse } from \"../shared/sse-response\";\nimport {\n mergeForwardableHeaders,\n resolveForwardHeadersPolicy,\n} from \"../header-utils\";\n\n/**\n * `headers` lives on the HTTP-backed agent configs (e.g. `HttpAgent`), not on\n * the base `AbstractAgent`. Mirror the runtime's own optional-headers shape so\n * we can read server-configured headers off the per-request clone without a\n * cast. See `agent-utils.ts`.\n */\ntype AgentWithHeaders = AbstractAgent & {\n headers?: Record<string, string>;\n};\n\ninterface HandleSseConnectParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n agentId: string;\n threadId: string;\n /**\n * The per-request agent clone, carrying any server-configured `agent.headers`\n * (e.g. service-to-service auth). Used only to compute the merged header set\n * threaded into `runner.connect` below — see the note there for why that\n * merge is forward-looking plumbing rather than active outbound auth today.\n */\n agent?: AgentWithHeaders;\n}\n\nexport function handleSseConnect({\n runtime,\n request,\n agentId,\n threadId,\n agent,\n}: HandleSseConnectParams): Response {\n return createSseEventResponse({\n request,\n debugEventBus: runtime.debugEventBus,\n // Forward the real agentId so debug envelopes reflect the agent the\n // route resolved to — not the literal string \"connect\".\n agentId,\n telemetry: runtime.telemetry,\n keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,\n observableFactory: () =>\n runtime.runner.connect({\n threadId,\n agentId,\n // Forward-looking plumbing: we compute the merged header set (server\n // `agent.headers` win on collision, case-insensitively; non-colliding\n // inbound headers still forward — see `mergeForwardableHeaders`, #5712)\n // and thread it into `runner.connect`. NO shipped runner consumes the\n // `headers` field of `AgentRunnerConnectRequest` today — every runner\n // (in-memory, intelligence, telemetry, sqlite) reads only `threadId`.\n // The real outbound header forwarding is the /run path, where\n // `cloneAgentForRequest` mutates `agent.headers` directly\n // (agent-utils.ts). This wiring exists so a future outbound-connecting\n // runner can pick the merged headers up without a route change; the\n // collision precedence noted here is purely about that merge, not about\n // middleware/mutation parity with /run.\n headers: mergeForwardableHeaders(\n agent?.headers,\n request,\n // Optional on `CopilotRuntimeLike` (non-breaking minor release);\n // coalesce a policy-less external implementor to the default resolved\n // policy (default-on denylist) instead of dereffing undefined.\n runtime.forwardHeadersPolicy ??\n resolveForwardHeadersPolicy(undefined),\n ),\n }),\n });\n}\n"],"mappings":";;;;;AAgCA,SAAgB,iBAAiB,EAC/B,SACA,SACA,SACA,UACA,SACmC;AACnC,QAAOA,4CAAuB;EAC5B;EACA,eAAe,QAAQ;EAGvB;EACA,WAAW,QAAQ;EACnB,0BAA0B,QAAQ;EAClC,yBACE,QAAQ,OAAO,QAAQ;GACrB;GACA;GAaA,SAASC,6CACP,OAAO,SACP,SAIA,QAAQ,wBACNC,iDAA4B,OAAU,CACzC;GACF,CAAC;EACL,CAAC"}
@@ -9,6 +9,7 @@ function handleSseConnect({ runtime, request, agentId, threadId, agent }) {
9
9
  debugEventBus: runtime.debugEventBus,
10
10
  agentId,
11
11
  telemetry: runtime.telemetry,
12
+ keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,
12
13
  observableFactory: () => runtime.runner.connect({
13
14
  threadId,
14
15
  agentId,
@@ -1 +1 @@
1
- {"version":3,"file":"connect.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/sse/connect.ts"],"sourcesContent":["import type { AbstractAgent } from \"@ag-ui/client\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { createSseEventResponse } from \"../shared/sse-response\";\nimport {\n mergeForwardableHeaders,\n resolveForwardHeadersPolicy,\n} from \"../header-utils\";\n\n/**\n * `headers` lives on the HTTP-backed agent configs (e.g. `HttpAgent`), not on\n * the base `AbstractAgent`. Mirror the runtime's own optional-headers shape so\n * we can read server-configured headers off the per-request clone without a\n * cast. See `agent-utils.ts`.\n */\ntype AgentWithHeaders = AbstractAgent & {\n headers?: Record<string, string>;\n};\n\ninterface HandleSseConnectParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n agentId: string;\n threadId: string;\n /**\n * The per-request agent clone, carrying any server-configured `agent.headers`\n * (e.g. service-to-service auth). Used only to compute the merged header set\n * threaded into `runner.connect` below — see the note there for why that\n * merge is forward-looking plumbing rather than active outbound auth today.\n */\n agent?: AgentWithHeaders;\n}\n\nexport function handleSseConnect({\n runtime,\n request,\n agentId,\n threadId,\n agent,\n}: HandleSseConnectParams): Response {\n return createSseEventResponse({\n request,\n debugEventBus: runtime.debugEventBus,\n // Forward the real agentId so debug envelopes reflect the agent the\n // route resolved to — not the literal string \"connect\".\n agentId,\n telemetry: runtime.telemetry,\n observableFactory: () =>\n runtime.runner.connect({\n threadId,\n agentId,\n // Forward-looking plumbing: we compute the merged header set (server\n // `agent.headers` win on collision, case-insensitively; non-colliding\n // inbound headers still forward — see `mergeForwardableHeaders`, #5712)\n // and thread it into `runner.connect`. NO shipped runner consumes the\n // `headers` field of `AgentRunnerConnectRequest` today — every runner\n // (in-memory, intelligence, telemetry, sqlite) reads only `threadId`.\n // The real outbound header forwarding is the /run path, where\n // `cloneAgentForRequest` mutates `agent.headers` directly\n // (agent-utils.ts). This wiring exists so a future outbound-connecting\n // runner can pick the merged headers up without a route change; the\n // collision precedence noted here is purely about that merge, not about\n // middleware/mutation parity with /run.\n headers: mergeForwardableHeaders(\n agent?.headers,\n request,\n // Optional on `CopilotRuntimeLike` (non-breaking minor release);\n // coalesce a policy-less external implementor to the default resolved\n // policy (default-on denylist) instead of dereffing undefined.\n runtime.forwardHeadersPolicy ??\n resolveForwardHeadersPolicy(undefined),\n ),\n }),\n });\n}\n"],"mappings":";;;;;AAgCA,SAAgB,iBAAiB,EAC/B,SACA,SACA,SACA,UACA,SACmC;AACnC,QAAO,uBAAuB;EAC5B;EACA,eAAe,QAAQ;EAGvB;EACA,WAAW,QAAQ;EACnB,yBACE,QAAQ,OAAO,QAAQ;GACrB;GACA;GAaA,SAAS,wBACP,OAAO,SACP,SAIA,QAAQ,wBACN,4BAA4B,OAAU,CACzC;GACF,CAAC;EACL,CAAC"}
1
+ {"version":3,"file":"connect.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/sse/connect.ts"],"sourcesContent":["import type { AbstractAgent } from \"@ag-ui/client\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { createSseEventResponse } from \"../shared/sse-response\";\nimport {\n mergeForwardableHeaders,\n resolveForwardHeadersPolicy,\n} from \"../header-utils\";\n\n/**\n * `headers` lives on the HTTP-backed agent configs (e.g. `HttpAgent`), not on\n * the base `AbstractAgent`. Mirror the runtime's own optional-headers shape so\n * we can read server-configured headers off the per-request clone without a\n * cast. See `agent-utils.ts`.\n */\ntype AgentWithHeaders = AbstractAgent & {\n headers?: Record<string, string>;\n};\n\ninterface HandleSseConnectParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n agentId: string;\n threadId: string;\n /**\n * The per-request agent clone, carrying any server-configured `agent.headers`\n * (e.g. service-to-service auth). Used only to compute the merged header set\n * threaded into `runner.connect` below — see the note there for why that\n * merge is forward-looking plumbing rather than active outbound auth today.\n */\n agent?: AgentWithHeaders;\n}\n\nexport function handleSseConnect({\n runtime,\n request,\n agentId,\n threadId,\n agent,\n}: HandleSseConnectParams): Response {\n return createSseEventResponse({\n request,\n debugEventBus: runtime.debugEventBus,\n // Forward the real agentId so debug envelopes reflect the agent the\n // route resolved to — not the literal string \"connect\".\n agentId,\n telemetry: runtime.telemetry,\n keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,\n observableFactory: () =>\n runtime.runner.connect({\n threadId,\n agentId,\n // Forward-looking plumbing: we compute the merged header set (server\n // `agent.headers` win on collision, case-insensitively; non-colliding\n // inbound headers still forward — see `mergeForwardableHeaders`, #5712)\n // and thread it into `runner.connect`. NO shipped runner consumes the\n // `headers` field of `AgentRunnerConnectRequest` today — every runner\n // (in-memory, intelligence, telemetry, sqlite) reads only `threadId`.\n // The real outbound header forwarding is the /run path, where\n // `cloneAgentForRequest` mutates `agent.headers` directly\n // (agent-utils.ts). This wiring exists so a future outbound-connecting\n // runner can pick the merged headers up without a route change; the\n // collision precedence noted here is purely about that merge, not about\n // middleware/mutation parity with /run.\n headers: mergeForwardableHeaders(\n agent?.headers,\n request,\n // Optional on `CopilotRuntimeLike` (non-breaking minor release);\n // coalesce a policy-less external implementor to the default resolved\n // policy (default-on denylist) instead of dereffing undefined.\n runtime.forwardHeadersPolicy ??\n resolveForwardHeadersPolicy(undefined),\n ),\n }),\n });\n}\n"],"mappings":";;;;;AAgCA,SAAgB,iBAAiB,EAC/B,SACA,SACA,SACA,UACA,SACmC;AACnC,QAAO,uBAAuB;EAC5B;EACA,eAAe,QAAQ;EAGvB;EACA,WAAW,QAAQ;EACnB,0BAA0B,QAAQ;EAClC,yBACE,QAAQ,OAAO,QAAQ;GACrB;GACA;GAaA,SAAS,wBACP,OAAO,SACP,SAIA,QAAQ,wBACN,4BAA4B,OAAU,CACzC;GACF,CAAC;EACL,CAAC"}
@@ -13,6 +13,7 @@ function handleSseRun({ runtime, request, agent, input, agentId, debug, logger,
13
13
  runtimeErrorReporter: require_runtime_error_reporter.getRuntimeErrorReporter(runtime),
14
14
  startTime,
15
15
  telemetry: runtime.telemetry,
16
+ keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,
16
17
  executionSeed: { llmHostClass: agent.modelHostClass ?? "unknown" },
17
18
  observableFactory: () => runtime.runner.run({
18
19
  threadId: input.threadId,
@@ -1 +1 @@
1
- {"version":3,"file":"run.cjs","names":["createSseEventResponse","getRuntimeErrorReporter"],"sources":["../../../../../src/v2/runtime/handlers/sse/run.ts"],"sourcesContent":["import type { AbstractAgent, RunAgentInput } from \"@ag-ui/client\";\nimport type { ResolvedDebugConfig, ModelHostClass } from \"@copilotkit/shared\";\nimport type { CopilotRuntimeLogger } from \"../../../../v1-deprecated/lib/logger\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { getRuntimeErrorReporter } from \"../../core/runtime-error-reporter\";\nimport { createSseEventResponse } from \"../shared/sse-response\";\n\ninterface HandleSseRunParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n agent: AbstractAgent;\n input: RunAgentInput;\n agentId: string;\n debug?: ResolvedDebugConfig;\n /** Pre-created logger instance to avoid creating a new pino logger per request. */\n logger?: CopilotRuntimeLogger;\n startTime?: number;\n}\n\nexport function handleSseRun({\n runtime,\n request,\n agent,\n input,\n agentId,\n debug,\n logger,\n startTime,\n}: HandleSseRunParams): Response {\n return createSseEventResponse({\n request,\n debugEventBus: runtime.debugEventBus,\n agentId,\n debug,\n logger,\n runtimeErrorReporter: getRuntimeErrorReporter(runtime),\n startTime,\n telemetry: runtime.telemetry,\n // Read structurally rather than via `instanceof BuiltInAgent`, which would\n // pull the agent module into this handler. Any agent can opt in by\n // exposing the same property.\n executionSeed: {\n llmHostClass:\n (agent as { modelHostClass?: ModelHostClass }).modelHostClass ??\n \"unknown\",\n },\n observableFactory: () =>\n runtime.runner.run({\n threadId: input.threadId,\n agent,\n input,\n }),\n });\n}\n"],"mappings":";;;;;AAmBA,SAAgB,aAAa,EAC3B,SACA,SACA,OACA,OACA,SACA,OACA,QACA,aAC+B;AAC/B,QAAOA,4CAAuB;EAC5B;EACA,eAAe,QAAQ;EACvB;EACA;EACA;EACA,sBAAsBC,uDAAwB,QAAQ;EACtD;EACA,WAAW,QAAQ;EAInB,eAAe,EACb,cACG,MAA8C,kBAC/C,WACH;EACD,yBACE,QAAQ,OAAO,IAAI;GACjB,UAAU,MAAM;GAChB;GACA;GACD,CAAC;EACL,CAAC"}
1
+ {"version":3,"file":"run.cjs","names":["createSseEventResponse","getRuntimeErrorReporter"],"sources":["../../../../../src/v2/runtime/handlers/sse/run.ts"],"sourcesContent":["import type { AbstractAgent, RunAgentInput } from \"@ag-ui/client\";\nimport type { ResolvedDebugConfig, ModelHostClass } from \"@copilotkit/shared\";\nimport type { CopilotRuntimeLogger } from \"../../../../v1-deprecated/lib/logger\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { getRuntimeErrorReporter } from \"../../core/runtime-error-reporter\";\nimport { createSseEventResponse } from \"../shared/sse-response\";\n\ninterface HandleSseRunParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n agent: AbstractAgent;\n input: RunAgentInput;\n agentId: string;\n debug?: ResolvedDebugConfig;\n /** Pre-created logger instance to avoid creating a new pino logger per request. */\n logger?: CopilotRuntimeLogger;\n startTime?: number;\n}\n\nexport function handleSseRun({\n runtime,\n request,\n agent,\n input,\n agentId,\n debug,\n logger,\n startTime,\n}: HandleSseRunParams): Response {\n return createSseEventResponse({\n request,\n debugEventBus: runtime.debugEventBus,\n agentId,\n debug,\n logger,\n runtimeErrorReporter: getRuntimeErrorReporter(runtime),\n startTime,\n telemetry: runtime.telemetry,\n keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,\n // Read structurally rather than via `instanceof BuiltInAgent`, which would\n // pull the agent module into this handler. Any agent can opt in by\n // exposing the same property.\n executionSeed: {\n llmHostClass:\n (agent as { modelHostClass?: ModelHostClass }).modelHostClass ??\n \"unknown\",\n },\n observableFactory: () =>\n runtime.runner.run({\n threadId: input.threadId,\n agent,\n input,\n }),\n });\n}\n"],"mappings":";;;;;AAmBA,SAAgB,aAAa,EAC3B,SACA,SACA,OACA,OACA,SACA,OACA,QACA,aAC+B;AAC/B,QAAOA,4CAAuB;EAC5B;EACA,eAAe,QAAQ;EACvB;EACA;EACA;EACA,sBAAsBC,uDAAwB,QAAQ;EACtD;EACA,WAAW,QAAQ;EACnB,0BAA0B,QAAQ;EAIlC,eAAe,EACb,cACG,MAA8C,kBAC/C,WACH;EACD,yBACE,QAAQ,OAAO,IAAI;GACjB,UAAU,MAAM;GAChB;GACA;GACD,CAAC;EACL,CAAC"}
@@ -13,6 +13,7 @@ function handleSseRun({ runtime, request, agent, input, agentId, debug, logger,
13
13
  runtimeErrorReporter: getRuntimeErrorReporter(runtime),
14
14
  startTime,
15
15
  telemetry: runtime.telemetry,
16
+ keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,
16
17
  executionSeed: { llmHostClass: agent.modelHostClass ?? "unknown" },
17
18
  observableFactory: () => runtime.runner.run({
18
19
  threadId: input.threadId,
@@ -1 +1 @@
1
- {"version":3,"file":"run.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/sse/run.ts"],"sourcesContent":["import type { AbstractAgent, RunAgentInput } from \"@ag-ui/client\";\nimport type { ResolvedDebugConfig, ModelHostClass } from \"@copilotkit/shared\";\nimport type { CopilotRuntimeLogger } from \"../../../../v1-deprecated/lib/logger\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { getRuntimeErrorReporter } from \"../../core/runtime-error-reporter\";\nimport { createSseEventResponse } from \"../shared/sse-response\";\n\ninterface HandleSseRunParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n agent: AbstractAgent;\n input: RunAgentInput;\n agentId: string;\n debug?: ResolvedDebugConfig;\n /** Pre-created logger instance to avoid creating a new pino logger per request. */\n logger?: CopilotRuntimeLogger;\n startTime?: number;\n}\n\nexport function handleSseRun({\n runtime,\n request,\n agent,\n input,\n agentId,\n debug,\n logger,\n startTime,\n}: HandleSseRunParams): Response {\n return createSseEventResponse({\n request,\n debugEventBus: runtime.debugEventBus,\n agentId,\n debug,\n logger,\n runtimeErrorReporter: getRuntimeErrorReporter(runtime),\n startTime,\n telemetry: runtime.telemetry,\n // Read structurally rather than via `instanceof BuiltInAgent`, which would\n // pull the agent module into this handler. Any agent can opt in by\n // exposing the same property.\n executionSeed: {\n llmHostClass:\n (agent as { modelHostClass?: ModelHostClass }).modelHostClass ??\n \"unknown\",\n },\n observableFactory: () =>\n runtime.runner.run({\n threadId: input.threadId,\n agent,\n input,\n }),\n });\n}\n"],"mappings":";;;;;AAmBA,SAAgB,aAAa,EAC3B,SACA,SACA,OACA,OACA,SACA,OACA,QACA,aAC+B;AAC/B,QAAO,uBAAuB;EAC5B;EACA,eAAe,QAAQ;EACvB;EACA;EACA;EACA,sBAAsB,wBAAwB,QAAQ;EACtD;EACA,WAAW,QAAQ;EAInB,eAAe,EACb,cACG,MAA8C,kBAC/C,WACH;EACD,yBACE,QAAQ,OAAO,IAAI;GACjB,UAAU,MAAM;GAChB;GACA;GACD,CAAC;EACL,CAAC"}
1
+ {"version":3,"file":"run.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/sse/run.ts"],"sourcesContent":["import type { AbstractAgent, RunAgentInput } from \"@ag-ui/client\";\nimport type { ResolvedDebugConfig, ModelHostClass } from \"@copilotkit/shared\";\nimport type { CopilotRuntimeLogger } from \"../../../../v1-deprecated/lib/logger\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { getRuntimeErrorReporter } from \"../../core/runtime-error-reporter\";\nimport { createSseEventResponse } from \"../shared/sse-response\";\n\ninterface HandleSseRunParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n agent: AbstractAgent;\n input: RunAgentInput;\n agentId: string;\n debug?: ResolvedDebugConfig;\n /** Pre-created logger instance to avoid creating a new pino logger per request. */\n logger?: CopilotRuntimeLogger;\n startTime?: number;\n}\n\nexport function handleSseRun({\n runtime,\n request,\n agent,\n input,\n agentId,\n debug,\n logger,\n startTime,\n}: HandleSseRunParams): Response {\n return createSseEventResponse({\n request,\n debugEventBus: runtime.debugEventBus,\n agentId,\n debug,\n logger,\n runtimeErrorReporter: getRuntimeErrorReporter(runtime),\n startTime,\n telemetry: runtime.telemetry,\n keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,\n // Read structurally rather than via `instanceof BuiltInAgent`, which would\n // pull the agent module into this handler. Any agent can opt in by\n // exposing the same property.\n executionSeed: {\n llmHostClass:\n (agent as { modelHostClass?: ModelHostClass }).modelHostClass ??\n \"unknown\",\n },\n observableFactory: () =>\n runtime.runner.run({\n threadId: input.threadId,\n agent,\n input,\n }),\n });\n}\n"],"mappings":";;;;;AAmBA,SAAgB,aAAa,EAC3B,SACA,SACA,OACA,OACA,SACA,OACA,QACA,aAC+B;AAC/B,QAAO,uBAAuB;EAC5B;EACA,eAAe,QAAQ;EACvB;EACA;EACA;EACA,sBAAsB,wBAAwB,QAAQ;EACtD;EACA,WAAW,QAAQ;EACnB,0BAA0B,QAAQ;EAIlC,eAAe,EACb,cACG,MAA8C,kBAC/C,WACH;EACD,yBACE,QAAQ,OAAO,IAAI;GACjB,UAAU,MAAM;GAChB;GACA;GACD,CAAC;EACL,CAAC"}
@@ -1,22 +1,22 @@
1
1
 
2
2
  import { TranscribeFileOptions, TranscriptionService } from "./transcription-service/transcription-service.cjs";
3
3
  import { AgentRunner, AgentRunnerConnectRequest, AgentRunnerIsRunningRequest, AgentRunnerRunRequest, AgentRunnerStopRequest, LocalThreadEndpointRecord, LocalThreadEndpointRunner, supportsLocalThreadEndpoints } from "./runner/agent-runner.cjs";
4
- import { CopilotRuntimeLearningConfig, CopilotRuntimeLearningContext, CopilotRuntimeUser, GetLearningContainerId, LearningContainerSelectorInput } from "./core/learning.cjs";
5
4
  import { GetLearnedSkillsSnapshotRequest, LearnedSkillsError, LearnedSkillsErrorCode, LearnedSkillsSnapshotResult } from "./intelligence-platform/learned-skills.cjs";
6
- import { CopilotKitIntelligence, CopilotKitIntelligenceConfig, CreateThreadRequest, ListThreadsResponse, SubscribeToThreadsRequest, SubscribeToThreadsResponse, ThreadSummary, UpdateThreadRequest } from "./intelligence-platform/client.cjs";
7
5
  import "./intelligence-platform/index.cjs";
8
6
  import { AgentFactoryContext, AgentsConfig, AgentsFactory, CopilotIntelligenceRuntime, CopilotIntelligenceRuntimeLike, CopilotIntelligenceRuntimeOptions, CopilotRuntime, CopilotRuntimeConstructor, CopilotRuntimeLike, CopilotRuntimeMemoryConfig, CopilotRuntimeOptions, CopilotSseRuntime, CopilotSseRuntimeLike, CopilotSseRuntimeOptions, IdentifyUserCallback, McpAppsConfig, McpAppsServerConfig, MemoryAccess, MemoryConsumer, MemoryGrant, OpenGenerativeUIConfig, OpenGenerativeUIOptions, RuntimeWithDeclaredChannels, VERSION, isA2UIEnabled, isIntelligenceRuntime, resolveAgents } from "./core/runtime.cjs";
9
- import { CopilotCorsConfig } from "./core/fetch-cors.cjs";
10
- import { CopilotRuntimeHooks, ErrorHookContext, HandlerHookContext, HookContext, ResponseHookContext, RouteInfo } from "./core/hooks.cjs";
7
+ import { CopilotRuntimeLearningConfig, CopilotRuntimeLearningContext, CopilotRuntimeUser, GetLearningContainerId, LearningContainerSelectorInput } from "./core/learning.cjs";
8
+ import { CopilotKitIntelligence, CopilotKitIntelligenceConfig, CreateThreadRequest, ListThreadsResponse, SubscribeToThreadsRequest, SubscribeToThreadsResponse, ThreadSummary, UpdateThreadRequest } from "./intelligence-platform/client.cjs";
9
+ import { InMemoryAgentRunner, InMemoryAgentRunnerOptions, InMemoryLimits, InMemoryThread, ɵBoundedThreadStore, ɵGLOBAL_STORE, ɵINMEMORY_DEFAULTS, ɵestimateBytes, ɵnormalizeLimits } from "./runner/in-memory.cjs";
10
+ import { IntelligenceAgentRunner, IntelligenceAgentRunnerOptions, RunnerStartupBoundary } from "./runner/intelligence.cjs";
11
+ import { FinalizeRunOptions, RunEventFinalizer, createRunEventFinalizer, finalizeRunEvents } from "./runner/index.cjs";
11
12
  import { ChannelStatus, ChannelsControl } from "./core/channel-manager.cjs";
12
- import { CopilotEndpointCorsConfig, CopilotHonoApp, createCopilotEndpoint, createCopilotHonoHandler, toFetchCorsConfig } from "./endpoints/hono.cjs";
13
- import { createCopilotEndpointSingleRoute } from "./endpoints/hono-single.cjs";
13
+ import { CopilotRuntimeHooks, ErrorHookContext, HandlerHookContext, HookContext, ResponseHookContext, RouteInfo } from "./core/hooks.cjs";
14
14
  import { CopilotExpressEndpointParams, CopilotExpressRouter, createCopilotExpressHandler } from "./endpoints/express.cjs";
15
15
  import { createCopilotEndpointSingleRouteExpress } from "./endpoints/express-single.cjs";
16
+ import { CopilotCorsConfig } from "./core/fetch-cors.cjs";
17
+ import { CopilotEndpointCorsConfig, CopilotHonoApp, createCopilotEndpoint, createCopilotHonoHandler, toFetchCorsConfig } from "./endpoints/hono.cjs";
18
+ import { createCopilotEndpointSingleRoute } from "./endpoints/hono-single.cjs";
16
19
  import "./endpoints/index.cjs";
17
- import { InMemoryAgentRunner, InMemoryAgentRunnerOptions, InMemoryLimits, InMemoryThread, ɵBoundedThreadStore, ɵGLOBAL_STORE, ɵINMEMORY_DEFAULTS, ɵestimateBytes, ɵnormalizeLimits } from "./runner/in-memory.cjs";
18
- import { IntelligenceAgentRunner, IntelligenceAgentRunnerOptions, RunnerStartupBoundary } from "./runner/intelligence.cjs";
19
- import { finalizeRunEvents } from "./runner/index.cjs";
20
20
  import { CopilotRuntimeFetchHandler, CopilotRuntimeFetchHandlerWithChannels, CopilotRuntimeHandlerOptions, createCopilotRuntimeHandler } from "./core/fetch-handler.cjs";
21
21
  import { MCPClient, MCPTransport } from "@ai-sdk/mcp";
22
22
 
@@ -1,22 +1,22 @@
1
1
 
2
2
  import { TranscribeFileOptions, TranscriptionService } from "./transcription-service/transcription-service.mjs";
3
3
  import { AgentRunner, AgentRunnerConnectRequest, AgentRunnerIsRunningRequest, AgentRunnerRunRequest, AgentRunnerStopRequest, LocalThreadEndpointRecord, LocalThreadEndpointRunner, supportsLocalThreadEndpoints } from "./runner/agent-runner.mjs";
4
- import { CopilotRuntimeLearningConfig, CopilotRuntimeLearningContext, CopilotRuntimeUser, GetLearningContainerId, LearningContainerSelectorInput } from "./core/learning.mjs";
5
4
  import { GetLearnedSkillsSnapshotRequest, LearnedSkillsError, LearnedSkillsErrorCode, LearnedSkillsSnapshotResult } from "./intelligence-platform/learned-skills.mjs";
6
- import { CopilotKitIntelligence, CopilotKitIntelligenceConfig, CreateThreadRequest, ListThreadsResponse, SubscribeToThreadsRequest, SubscribeToThreadsResponse, ThreadSummary, UpdateThreadRequest } from "./intelligence-platform/client.mjs";
7
5
  import "./intelligence-platform/index.mjs";
8
6
  import { AgentFactoryContext, AgentsConfig, AgentsFactory, CopilotIntelligenceRuntime, CopilotIntelligenceRuntimeLike, CopilotIntelligenceRuntimeOptions, CopilotRuntime, CopilotRuntimeConstructor, CopilotRuntimeLike, CopilotRuntimeMemoryConfig, CopilotRuntimeOptions, CopilotSseRuntime, CopilotSseRuntimeLike, CopilotSseRuntimeOptions, IdentifyUserCallback, McpAppsConfig, McpAppsServerConfig, MemoryAccess, MemoryConsumer, MemoryGrant, OpenGenerativeUIConfig, OpenGenerativeUIOptions, RuntimeWithDeclaredChannels, VERSION, isA2UIEnabled, isIntelligenceRuntime, resolveAgents } from "./core/runtime.mjs";
9
- import { CopilotCorsConfig } from "./core/fetch-cors.mjs";
10
- import { CopilotRuntimeHooks, ErrorHookContext, HandlerHookContext, HookContext, ResponseHookContext, RouteInfo } from "./core/hooks.mjs";
7
+ import { CopilotRuntimeLearningConfig, CopilotRuntimeLearningContext, CopilotRuntimeUser, GetLearningContainerId, LearningContainerSelectorInput } from "./core/learning.mjs";
8
+ import { CopilotKitIntelligence, CopilotKitIntelligenceConfig, CreateThreadRequest, ListThreadsResponse, SubscribeToThreadsRequest, SubscribeToThreadsResponse, ThreadSummary, UpdateThreadRequest } from "./intelligence-platform/client.mjs";
9
+ import { InMemoryAgentRunner, InMemoryAgentRunnerOptions, InMemoryLimits, InMemoryThread, ɵBoundedThreadStore, ɵGLOBAL_STORE, ɵINMEMORY_DEFAULTS, ɵestimateBytes, ɵnormalizeLimits } from "./runner/in-memory.mjs";
10
+ import { IntelligenceAgentRunner, IntelligenceAgentRunnerOptions, RunnerStartupBoundary } from "./runner/intelligence.mjs";
11
+ import { FinalizeRunOptions, RunEventFinalizer, createRunEventFinalizer, finalizeRunEvents } from "./runner/index.mjs";
11
12
  import { ChannelStatus, ChannelsControl } from "./core/channel-manager.mjs";
12
- import { CopilotEndpointCorsConfig, CopilotHonoApp, createCopilotEndpoint, createCopilotHonoHandler, toFetchCorsConfig } from "./endpoints/hono.mjs";
13
- import { createCopilotEndpointSingleRoute } from "./endpoints/hono-single.mjs";
13
+ import { CopilotRuntimeHooks, ErrorHookContext, HandlerHookContext, HookContext, ResponseHookContext, RouteInfo } from "./core/hooks.mjs";
14
14
  import { CopilotExpressEndpointParams, CopilotExpressRouter, createCopilotExpressHandler } from "./endpoints/express.mjs";
15
15
  import { createCopilotEndpointSingleRouteExpress } from "./endpoints/express-single.mjs";
16
+ import { CopilotCorsConfig } from "./core/fetch-cors.mjs";
17
+ import { CopilotEndpointCorsConfig, CopilotHonoApp, createCopilotEndpoint, createCopilotHonoHandler, toFetchCorsConfig } from "./endpoints/hono.mjs";
18
+ import { createCopilotEndpointSingleRoute } from "./endpoints/hono-single.mjs";
16
19
  import "./endpoints/index.mjs";
17
- import { InMemoryAgentRunner, InMemoryAgentRunnerOptions, InMemoryLimits, InMemoryThread, ɵBoundedThreadStore, ɵGLOBAL_STORE, ɵINMEMORY_DEFAULTS, ɵestimateBytes, ɵnormalizeLimits } from "./runner/in-memory.mjs";
18
- import { IntelligenceAgentRunner, IntelligenceAgentRunnerOptions, RunnerStartupBoundary } from "./runner/intelligence.mjs";
19
- import { finalizeRunEvents } from "./runner/index.mjs";
20
20
  import { CopilotRuntimeFetchHandler, CopilotRuntimeFetchHandlerWithChannels, CopilotRuntimeHandlerOptions, createCopilotRuntimeHandler } from "./core/fetch-handler.mjs";
21
21
  import { MCPClient, MCPTransport } from "@ai-sdk/mcp";
22
22
 
@@ -2,8 +2,8 @@ require("reflect-metadata");
2
2
  const require_runtime = require('../../../_virtual/_rolldown/runtime.cjs');
3
3
  const require_learned_skills = require('./learned-skills.cjs');
4
4
  let _copilotkit_shared = require("@copilotkit/shared");
5
- let crypto = require("crypto");
6
5
  let zod = require("zod");
6
+ let crypto = require("crypto");
7
7
 
8
8
  //#region src/v2/runtime/intelligence-platform/client.ts
9
9
  /** Let a confirmed HTTP denial survive an error body that never completes. */
@@ -1,6 +1,6 @@
1
1
 
2
- import { GetLearningContainerId } from "../core/learning.cjs";
3
2
  import { GetLearnedSkillsSnapshotRequest, LearnedSkillsSnapshotResult } from "./learned-skills.cjs";
3
+ import { GetLearningContainerId } from "../core/learning.cjs";
4
4
  import { InspectorLearningRequestV1, InspectorLearningSnapshotV1, InspectorMetadataV1, RuntimeEntitlementResponse } from "@copilotkit/shared";
5
5
 
6
6
  //#region src/v2/runtime/intelligence-platform/client.d.ts
@@ -1,6 +1,6 @@
1
1
 
2
- import { GetLearningContainerId } from "../core/learning.mjs";
3
2
  import { GetLearnedSkillsSnapshotRequest, LearnedSkillsSnapshotResult } from "./learned-skills.mjs";
3
+ import { GetLearningContainerId } from "../core/learning.mjs";
4
4
  import { InspectorLearningRequestV1, InspectorLearningSnapshotV1, InspectorMetadataV1, RuntimeEntitlementResponse } from "@copilotkit/shared";
5
5
 
6
6
  //#region src/v2/runtime/intelligence-platform/client.d.ts
@@ -1,8 +1,8 @@
1
1
  import "reflect-metadata";
2
2
  import { LearnedSkillsError, learnedSkillsResponseError } from "./learned-skills.mjs";
3
3
  import { logger, parseInspectorLearningSnapshotV1, parseInspectorMetadataV1 } from "@copilotkit/shared";
4
- import { randomUUID as randomUUID$1 } from "crypto";
5
4
  import { z } from "zod";
5
+ import { randomUUID as randomUUID$1 } from "crypto";
6
6
 
7
7
  //#region src/v2/runtime/intelligence-platform/client.ts
8
8
  /** Let a confirmed HTTP denial survive an error body that never completes. */
@@ -0,0 +1,132 @@
1
+ require("reflect-metadata");
2
+ const require_runtime = require('../../../../_virtual/_rolldown/runtime.cjs');
3
+ const require_errors = require('./errors.cjs');
4
+ let yauzl = require("yauzl");
5
+
6
+ //#region src/v2/runtime/intelligence-platform/skill-registry/archive.ts
7
+ /** Internal corruption bounds, including manifest and directory entries. */
8
+ const MAX_ARCHIVE_ENTRIES = 1e3;
9
+ const MAX_SNAPSHOT_BYTES = 32 * 1024 * 1024;
10
+ function safeRelativePath(path) {
11
+ return path.length > 0 && !/[\\\x00-\x1f\x7f]/.test(path) && !/^[a-z]:/i.test(path) && path.split("/").every((part) => part !== "" && part !== "." && part !== "..");
12
+ }
13
+ /** Decode only the listed ZIP namespace. No filesystem is involved. */
14
+ function readArchive(bytes, signal) {
15
+ return new Promise((resolve, reject) => {
16
+ let archive;
17
+ let stream;
18
+ let settled = false;
19
+ const finish = (error) => {
20
+ if (settled) return;
21
+ settled = true;
22
+ signal?.removeEventListener("abort", abort);
23
+ stream?.destroy();
24
+ archive?.close();
25
+ if (error !== void 0) reject(error);
26
+ else resolve(files);
27
+ };
28
+ const abort = () => finish(signal?.reason ?? require_errors.invalidSnapshot());
29
+ const files = /* @__PURE__ */ new Map();
30
+ const names = /* @__PURE__ */ new Set();
31
+ let decodedBytes = 0;
32
+ signal?.addEventListener("abort", abort, { once: true });
33
+ if (signal?.aborted) {
34
+ abort();
35
+ return;
36
+ }
37
+ (0, yauzl.fromBuffer)(bytes, {
38
+ lazyEntries: true,
39
+ decodeStrings: false,
40
+ validateEntrySizes: true,
41
+ autoClose: false
42
+ }, (error, zip) => {
43
+ if (error) {
44
+ finish(require_errors.invalidSnapshot(error));
45
+ return;
46
+ }
47
+ archive = zip;
48
+ if (settled) {
49
+ zip.close();
50
+ return;
51
+ }
52
+ zip.on("error", (cause) => finish(require_errors.invalidSnapshot(cause)));
53
+ zip.on("end", () => finish());
54
+ if (zip.entryCount > MAX_ARCHIVE_ENTRIES) {
55
+ finish(require_errors.invalidSnapshot());
56
+ return;
57
+ }
58
+ zip.on("entry", (entry) => {
59
+ try {
60
+ const rawName = entry.fileName;
61
+ if (!Buffer.isBuffer(rawName)) throw require_errors.invalidSnapshot();
62
+ const name = new TextDecoder("utf-8", {
63
+ fatal: true,
64
+ ignoreBOM: true
65
+ }).decode(rawName);
66
+ const directory = name.endsWith("/");
67
+ if (!safeRelativePath(directory ? name.slice(0, -1) : name) || names.has(name)) throw require_errors.invalidSnapshot();
68
+ names.add(name);
69
+ const fileType = entry.externalFileAttributes >>> 16 & 61440;
70
+ if (fileType !== 0 && fileType !== (directory ? 16384 : 32768)) throw require_errors.invalidSnapshot();
71
+ if (entry.isEncrypted() || ![0, 8].includes(entry.compressionMethod)) throw require_errors.invalidSnapshot();
72
+ if (!Number.isSafeInteger(entry.uncompressedSize) || entry.uncompressedSize < 0) throw require_errors.invalidSnapshot();
73
+ decodedBytes += entry.uncompressedSize;
74
+ if (decodedBytes > MAX_SNAPSHOT_BYTES || directory && entry.uncompressedSize !== 0) throw require_errors.invalidSnapshot();
75
+ const local = entry.relativeOffsetOfLocalHeader;
76
+ if (local < 0 || local + 30 > bytes.length || bytes.readUInt32LE(local) !== 67324752) throw require_errors.invalidSnapshot();
77
+ if (bytes.readUInt16LE(local + 6) !== entry.generalPurposeBitFlag || bytes.readUInt16LE(local + 8) !== entry.compressionMethod) throw require_errors.invalidSnapshot();
78
+ const localNameLength = bytes.readUInt16LE(local + 26);
79
+ const localExtraLength = bytes.readUInt16LE(local + 28);
80
+ if (local + 30 + localNameLength + localExtraLength + entry.compressedSize > bytes.length || !bytes.subarray(local + 30, local + 30 + localNameLength).equals(rawName)) throw require_errors.invalidSnapshot();
81
+ if (!(entry.generalPurposeBitFlag & 8) && (bytes.readUInt32LE(local + 18) !== entry.compressedSize || bytes.readUInt32LE(local + 22) !== entry.uncompressedSize)) throw require_errors.invalidSnapshot();
82
+ if (directory) {
83
+ zip.readEntry();
84
+ return;
85
+ }
86
+ zip.openReadStream(entry, (readError, readStream) => {
87
+ if (readError) {
88
+ finish(require_errors.invalidSnapshot(readError));
89
+ return;
90
+ }
91
+ stream = readStream;
92
+ if (settled) {
93
+ readStream.destroy();
94
+ return;
95
+ }
96
+ const chunks = [];
97
+ let size = 0;
98
+ readStream.on("error", (cause) => finish(require_errors.invalidSnapshot(cause)));
99
+ readStream.on("data", (chunk) => {
100
+ size += chunk.length;
101
+ if (size > entry.uncompressedSize || size > MAX_SNAPSHOT_BYTES) {
102
+ finish(require_errors.invalidSnapshot());
103
+ return;
104
+ }
105
+ chunks.push(chunk);
106
+ });
107
+ readStream.on("end", () => {
108
+ if (settled) return;
109
+ if (size !== entry.uncompressedSize) {
110
+ finish(require_errors.invalidSnapshot());
111
+ return;
112
+ }
113
+ files.set(name, Buffer.concat(chunks, size));
114
+ stream = void 0;
115
+ zip.readEntry();
116
+ });
117
+ });
118
+ } catch (cause) {
119
+ finish(require_errors.invalidSnapshot(cause));
120
+ }
121
+ });
122
+ zip.readEntry();
123
+ });
124
+ });
125
+ }
126
+
127
+ //#endregion
128
+ exports.MAX_ARCHIVE_ENTRIES = MAX_ARCHIVE_ENTRIES;
129
+ exports.MAX_SNAPSHOT_BYTES = MAX_SNAPSHOT_BYTES;
130
+ exports.readArchive = readArchive;
131
+ exports.safeRelativePath = safeRelativePath;
132
+ //# sourceMappingURL=archive.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"archive.cjs","names":["invalidSnapshot"],"sources":["../../../../../src/v2/runtime/intelligence-platform/skill-registry/archive.ts"],"sourcesContent":["import { fromBuffer } from \"yauzl\";\nimport type { Entry, ZipFile } from \"yauzl\";\nimport type { Readable } from \"node:stream\";\nimport { invalidSnapshot } from \"./errors\";\n\n/** Internal corruption bounds, including manifest and directory entries. */\nexport const MAX_ARCHIVE_ENTRIES = 1_000;\nexport const MAX_SNAPSHOT_BYTES = 32 * 1024 * 1024;\n\nexport function safeRelativePath(path: string): boolean {\n return (\n path.length > 0 &&\n // Reject control bytes in archive paths, including NUL and DEL.\n // eslint-disable-next-line no-control-regex\n !/[\\\\\\x00-\\x1f\\x7f]/.test(path) &&\n !/^[a-z]:/i.test(path) &&\n path\n .split(\"/\")\n .every((part) => part !== \"\" && part !== \".\" && part !== \"..\")\n );\n}\n\n/** Decode only the listed ZIP namespace. No filesystem is involved. */\nexport function readArchive(\n bytes: Buffer,\n signal?: AbortSignal,\n): Promise<Map<string, Buffer>> {\n return new Promise((resolve, reject) => {\n let archive: ZipFile | undefined;\n let stream: Readable | undefined;\n let settled = false;\n const finish = (error?: unknown) => {\n if (settled) return;\n settled = true;\n signal?.removeEventListener(\"abort\", abort);\n stream?.destroy();\n archive?.close();\n if (error !== undefined) reject(error);\n else resolve(files);\n };\n const abort = () => finish(signal?.reason ?? invalidSnapshot());\n const files = new Map<string, Buffer>();\n const names = new Set<string>();\n let decodedBytes = 0;\n signal?.addEventListener(\"abort\", abort, { once: true });\n if (signal?.aborted) {\n abort();\n return;\n }\n fromBuffer(\n bytes,\n {\n lazyEntries: true,\n decodeStrings: false,\n validateEntrySizes: true,\n autoClose: false,\n },\n (error, zip) => {\n if (error) {\n finish(invalidSnapshot(error));\n return;\n }\n archive = zip;\n if (settled) {\n zip.close();\n return;\n }\n zip.on(\"error\", (cause: unknown) => finish(invalidSnapshot(cause)));\n zip.on(\"end\", () => finish());\n if (zip.entryCount > MAX_ARCHIVE_ENTRIES) {\n finish(invalidSnapshot());\n return;\n }\n zip.on(\"entry\", (entry: Entry) => {\n try {\n // decodeStrings:false preserves raw UTF-8 names instead of normalizing\n // backslashes or consulting alternate Unicode-path extra fields.\n const rawName: unknown = entry.fileName;\n if (!Buffer.isBuffer(rawName)) throw invalidSnapshot();\n const name = new TextDecoder(\"utf-8\", {\n fatal: true,\n ignoreBOM: true,\n }).decode(rawName);\n const directory = name.endsWith(\"/\");\n if (\n !safeRelativePath(directory ? name.slice(0, -1) : name) ||\n names.has(name)\n )\n throw invalidSnapshot();\n names.add(name);\n const fileType = (entry.externalFileAttributes >>> 16) & 0o170000;\n if (\n fileType !== 0 &&\n fileType !== (directory ? 0o040000 : 0o100000)\n )\n throw invalidSnapshot();\n if (\n entry.isEncrypted() ||\n ![0, 8].includes(entry.compressionMethod)\n )\n throw invalidSnapshot();\n if (\n !Number.isSafeInteger(entry.uncompressedSize) ||\n entry.uncompressedSize < 0\n )\n throw invalidSnapshot();\n decodedBytes += entry.uncompressedSize;\n if (\n decodedBytes > MAX_SNAPSHOT_BYTES ||\n (directory && entry.uncompressedSize !== 0)\n )\n throw invalidSnapshot();\n // Require the central directory and the local entry to name the same\n // bytes. ZIP data descriptors may leave local sizes unset.\n const local = entry.relativeOffsetOfLocalHeader;\n if (\n local < 0 ||\n local + 30 > bytes.length ||\n bytes.readUInt32LE(local) !== 0x04034b50\n )\n throw invalidSnapshot();\n if (\n bytes.readUInt16LE(local + 6) !== entry.generalPurposeBitFlag ||\n bytes.readUInt16LE(local + 8) !== entry.compressionMethod\n )\n throw invalidSnapshot();\n const localNameLength = bytes.readUInt16LE(local + 26);\n const localExtraLength = bytes.readUInt16LE(local + 28);\n const dataStart = local + 30 + localNameLength + localExtraLength;\n if (\n dataStart + entry.compressedSize > bytes.length ||\n !bytes\n .subarray(local + 30, local + 30 + localNameLength)\n .equals(rawName)\n )\n throw invalidSnapshot();\n if (\n !(entry.generalPurposeBitFlag & 8) &&\n (bytes.readUInt32LE(local + 18) !== entry.compressedSize ||\n bytes.readUInt32LE(local + 22) !== entry.uncompressedSize)\n )\n throw invalidSnapshot();\n if (directory) {\n zip.readEntry();\n return;\n }\n zip.openReadStream(entry, (readError, readStream) => {\n if (readError) {\n finish(invalidSnapshot(readError));\n return;\n }\n stream = readStream;\n if (settled) {\n readStream.destroy();\n return;\n }\n const chunks: Buffer[] = [];\n let size = 0;\n readStream.on(\"error\", (cause: unknown) =>\n finish(invalidSnapshot(cause)),\n );\n readStream.on(\"data\", (chunk: Buffer) => {\n size += chunk.length;\n if (\n size > entry.uncompressedSize ||\n size > MAX_SNAPSHOT_BYTES\n ) {\n finish(invalidSnapshot());\n return;\n }\n chunks.push(chunk);\n });\n readStream.on(\"end\", () => {\n if (settled) return;\n if (size !== entry.uncompressedSize) {\n finish(invalidSnapshot());\n return;\n }\n files.set(name, Buffer.concat(chunks, size));\n stream = undefined;\n zip.readEntry();\n });\n });\n } catch (cause) {\n finish(invalidSnapshot(cause));\n }\n });\n zip.readEntry();\n },\n );\n });\n}\n"],"mappings":";;;;;;;AAMA,MAAa,sBAAsB;AACnC,MAAa,qBAAqB,KAAK,OAAO;AAE9C,SAAgB,iBAAiB,MAAuB;AACtD,QACE,KAAK,SAAS,KAGd,CAAC,oBAAoB,KAAK,KAAK,IAC/B,CAAC,WAAW,KAAK,KAAK,IACtB,KACG,MAAM,IAAI,CACV,OAAO,SAAS,SAAS,M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