@copilotkit/runtime 2.0.0-rc.40 → 2.0.0-rc.41

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 (160) hide show
  1. package/README.md +2 -2
  2. package/dist/agent.cjs.map +1 -1
  3. package/dist/agent.d.cts +2 -2
  4. package/dist/agent.d.mts +2 -2
  5. package/dist/agent.mjs.map +1 -1
  6. package/dist/index.d.cts +2 -1
  7. package/dist/index.d.mts +2 -1
  8. package/dist/runtime/core/debug-event-bus.cjs +4 -2
  9. package/dist/runtime/core/debug-event-bus.cjs.map +1 -1
  10. package/dist/runtime/core/debug-event-bus.d.cts +4 -0
  11. package/dist/runtime/core/debug-event-bus.d.cts.map +1 -1
  12. package/dist/runtime/core/debug-event-bus.d.mts +4 -0
  13. package/dist/runtime/core/debug-event-bus.d.mts.map +1 -1
  14. package/dist/runtime/core/debug-event-bus.mjs +5 -3
  15. package/dist/runtime/core/debug-event-bus.mjs.map +1 -1
  16. package/dist/runtime/core/fetch-handler.cjs +8 -7
  17. package/dist/runtime/core/fetch-handler.cjs.map +1 -1
  18. package/dist/runtime/core/fetch-handler.d.cts.map +1 -1
  19. package/dist/runtime/core/fetch-handler.d.mts.map +1 -1
  20. package/dist/runtime/core/fetch-handler.mjs +3 -2
  21. package/dist/runtime/core/fetch-handler.mjs.map +1 -1
  22. package/dist/runtime/core/logger.cjs +20 -1
  23. package/dist/runtime/core/logger.cjs.map +1 -1
  24. package/dist/runtime/core/logger.d.cts +9 -5
  25. package/dist/runtime/core/logger.d.cts.map +1 -1
  26. package/dist/runtime/core/logger.d.mts +9 -5
  27. package/dist/runtime/core/logger.d.mts.map +1 -1
  28. package/dist/runtime/core/logger.mjs +20 -2
  29. package/dist/runtime/core/logger.mjs.map +1 -1
  30. package/dist/runtime/core/middleware-sse-parser.cjs +3 -3
  31. package/dist/runtime/core/middleware-sse-parser.cjs.map +1 -1
  32. package/dist/runtime/core/middleware-sse-parser.d.cts.map +1 -1
  33. package/dist/runtime/core/middleware-sse-parser.d.mts.map +1 -1
  34. package/dist/runtime/core/middleware-sse-parser.mjs +2 -2
  35. package/dist/runtime/core/middleware-sse-parser.mjs.map +1 -1
  36. package/dist/runtime/core/middleware.cjs +5 -4
  37. package/dist/runtime/core/middleware.cjs.map +1 -1
  38. package/dist/runtime/core/middleware.mjs +4 -3
  39. package/dist/runtime/core/middleware.mjs.map +1 -1
  40. package/dist/runtime/core/package-info.cjs +1 -1
  41. package/dist/runtime/core/package-info.mjs +1 -1
  42. package/dist/runtime/core/runtime.cjs +11 -9
  43. package/dist/runtime/core/runtime.cjs.map +1 -1
  44. package/dist/runtime/core/runtime.d.cts +19 -1
  45. package/dist/runtime/core/runtime.d.cts.map +1 -1
  46. package/dist/runtime/core/runtime.d.mts +19 -1
  47. package/dist/runtime/core/runtime.d.mts.map +1 -1
  48. package/dist/runtime/core/runtime.mjs +11 -9
  49. package/dist/runtime/core/runtime.mjs.map +1 -1
  50. package/dist/runtime/endpoints/auto-start-channels.cjs +3 -3
  51. package/dist/runtime/endpoints/auto-start-channels.cjs.map +1 -1
  52. package/dist/runtime/endpoints/auto-start-channels.mjs +2 -2
  53. package/dist/runtime/endpoints/auto-start-channels.mjs.map +1 -1
  54. package/dist/runtime/endpoints/node-fetch-handler.cjs +3 -3
  55. package/dist/runtime/endpoints/node-fetch-handler.cjs.map +1 -1
  56. package/dist/runtime/endpoints/node-fetch-handler.d.cts +2 -1
  57. package/dist/runtime/endpoints/node-fetch-handler.d.cts.map +1 -1
  58. package/dist/runtime/endpoints/node-fetch-handler.d.mts +2 -1
  59. package/dist/runtime/endpoints/node-fetch-handler.d.mts.map +1 -1
  60. package/dist/runtime/endpoints/node-fetch-handler.mjs +2 -2
  61. package/dist/runtime/endpoints/node-fetch-handler.mjs.map +1 -1
  62. package/dist/runtime/endpoints/node.cjs +4 -2
  63. package/dist/runtime/endpoints/node.cjs.map +1 -1
  64. package/dist/runtime/endpoints/node.d.cts.map +1 -1
  65. package/dist/runtime/endpoints/node.d.mts.map +1 -1
  66. package/dist/runtime/endpoints/node.mjs +4 -2
  67. package/dist/runtime/endpoints/node.mjs.map +1 -1
  68. package/dist/runtime/handlers/get-runtime-info.cjs +5 -1
  69. package/dist/runtime/handlers/get-runtime-info.cjs.map +1 -1
  70. package/dist/runtime/handlers/get-runtime-info.mjs +5 -1
  71. package/dist/runtime/handlers/get-runtime-info.mjs.map +1 -1
  72. package/dist/runtime/handlers/handle-connect.cjs +3 -8
  73. package/dist/runtime/handlers/handle-connect.cjs.map +1 -1
  74. package/dist/runtime/handlers/handle-connect.mjs +3 -8
  75. package/dist/runtime/handlers/handle-connect.mjs.map +1 -1
  76. package/dist/runtime/handlers/handle-run.cjs +4 -9
  77. package/dist/runtime/handlers/handle-run.cjs.map +1 -1
  78. package/dist/runtime/handlers/handle-run.mjs +4 -9
  79. package/dist/runtime/handlers/handle-run.mjs.map +1 -1
  80. package/dist/runtime/handlers/handle-stop.cjs +2 -1
  81. package/dist/runtime/handlers/handle-stop.cjs.map +1 -1
  82. package/dist/runtime/handlers/handle-stop.mjs +2 -1
  83. package/dist/runtime/handlers/handle-stop.mjs.map +1 -1
  84. package/dist/runtime/handlers/handle-suggest.cjs +3 -1
  85. package/dist/runtime/handlers/handle-suggest.cjs.map +1 -1
  86. package/dist/runtime/handlers/handle-suggest.mjs +3 -1
  87. package/dist/runtime/handlers/handle-suggest.mjs.map +1 -1
  88. package/dist/runtime/handlers/intelligence/annotate.cjs +6 -5
  89. package/dist/runtime/handlers/intelligence/annotate.cjs.map +1 -1
  90. package/dist/runtime/handlers/intelligence/annotate.mjs +4 -3
  91. package/dist/runtime/handlers/intelligence/annotate.mjs.map +1 -1
  92. package/dist/runtime/handlers/intelligence/connect.cjs +6 -2
  93. package/dist/runtime/handlers/intelligence/connect.cjs.map +1 -1
  94. package/dist/runtime/handlers/intelligence/connect.mjs +6 -2
  95. package/dist/runtime/handlers/intelligence/connect.mjs.map +1 -1
  96. package/dist/runtime/handlers/intelligence/memories.cjs +20 -14
  97. package/dist/runtime/handlers/intelligence/memories.cjs.map +1 -1
  98. package/dist/runtime/handlers/intelligence/memories.mjs +11 -5
  99. package/dist/runtime/handlers/intelligence/memories.mjs.map +1 -1
  100. package/dist/runtime/handlers/intelligence/run.cjs +15 -13
  101. package/dist/runtime/handlers/intelligence/run.cjs.map +1 -1
  102. package/dist/runtime/handlers/intelligence/run.mjs +14 -12
  103. package/dist/runtime/handlers/intelligence/run.mjs.map +1 -1
  104. package/dist/runtime/handlers/intelligence/thread-names.cjs +6 -4
  105. package/dist/runtime/handlers/intelligence/thread-names.cjs.map +1 -1
  106. package/dist/runtime/handlers/intelligence/thread-names.mjs +3 -1
  107. package/dist/runtime/handlers/intelligence/thread-names.mjs.map +1 -1
  108. package/dist/runtime/handlers/intelligence/threads.cjs +30 -20
  109. package/dist/runtime/handlers/intelligence/threads.cjs.map +1 -1
  110. package/dist/runtime/handlers/intelligence/threads.mjs +13 -3
  111. package/dist/runtime/handlers/intelligence/threads.mjs.map +1 -1
  112. package/dist/runtime/handlers/shared/agent-utils.cjs +26 -25
  113. package/dist/runtime/handlers/shared/agent-utils.cjs.map +1 -1
  114. package/dist/runtime/handlers/shared/agent-utils.mjs +27 -26
  115. package/dist/runtime/handlers/shared/agent-utils.mjs.map +1 -1
  116. package/dist/runtime/handlers/shared/resolve-intelligence-user.cjs +3 -2
  117. package/dist/runtime/handlers/shared/resolve-intelligence-user.cjs.map +1 -1
  118. package/dist/runtime/handlers/shared/resolve-intelligence-user.mjs +3 -2
  119. package/dist/runtime/handlers/shared/resolve-intelligence-user.mjs.map +1 -1
  120. package/dist/runtime/handlers/shared/sse-response.cjs +5 -14
  121. package/dist/runtime/handlers/shared/sse-response.cjs.map +1 -1
  122. package/dist/runtime/handlers/shared/sse-response.mjs +5 -14
  123. package/dist/runtime/handlers/shared/sse-response.mjs.map +1 -1
  124. package/dist/runtime/handlers/shared/thread-access.cjs +3 -2
  125. package/dist/runtime/handlers/shared/thread-access.cjs.map +1 -1
  126. package/dist/runtime/handlers/shared/thread-access.d.cts.map +1 -1
  127. package/dist/runtime/handlers/shared/thread-access.d.mts.map +1 -1
  128. package/dist/runtime/handlers/shared/thread-access.mjs +3 -2
  129. package/dist/runtime/handlers/shared/thread-access.mjs.map +1 -1
  130. package/dist/runtime/handlers/sse/connect.cjs +2 -0
  131. package/dist/runtime/handlers/sse/connect.cjs.map +1 -1
  132. package/dist/runtime/handlers/sse/connect.mjs +2 -0
  133. package/dist/runtime/handlers/sse/connect.mjs.map +1 -1
  134. package/dist/runtime/handlers/sse/run.cjs +5 -2
  135. package/dist/runtime/handlers/sse/run.cjs.map +1 -1
  136. package/dist/runtime/handlers/sse/run.mjs +5 -2
  137. package/dist/runtime/handlers/sse/run.mjs.map +1 -1
  138. package/dist/runtime/index.d.cts +1 -0
  139. package/dist/runtime/index.d.mts +1 -0
  140. package/dist/runtime/intelligence-platform/analytics-context.cjs +3 -3
  141. package/dist/runtime/intelligence-platform/analytics-context.cjs.map +1 -1
  142. package/dist/runtime/intelligence-platform/analytics-context.mjs +2 -2
  143. package/dist/runtime/intelligence-platform/analytics-context.mjs.map +1 -1
  144. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.cjs +3 -2
  145. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.cjs.map +1 -1
  146. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.mjs +2 -1
  147. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.mjs.map +1 -1
  148. package/dist/runtime/runner/intelligence.cjs +9 -7
  149. package/dist/runtime/runner/intelligence.cjs.map +1 -1
  150. package/dist/runtime/runner/intelligence.d.cts +4 -0
  151. package/dist/runtime/runner/intelligence.d.cts.map +1 -1
  152. package/dist/runtime/runner/intelligence.d.mts +4 -0
  153. package/dist/runtime/runner/intelligence.d.mts.map +1 -1
  154. package/dist/runtime/runner/intelligence.mjs +8 -6
  155. package/dist/runtime/runner/intelligence.mjs.map +1 -1
  156. package/dist/runtime/telemetry/disclosure.cjs +2 -2
  157. package/dist/runtime/telemetry/disclosure.cjs.map +1 -1
  158. package/dist/runtime/telemetry/disclosure.mjs +3 -3
  159. package/dist/runtime/telemetry/disclosure.mjs.map +1 -1
  160. package/package.json +7 -11
@@ -1 +1 @@
1
- {"version":3,"file":"resolve-intelligence-user.mjs","names":[],"sources":["../../../../src/runtime/handlers/shared/resolve-intelligence-user.ts"],"sourcesContent":["import type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n CopilotRuntimeUser,\n IdentifyUserCallback,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { errorResponse } from \"./json-response\";\nimport { isValidIdentifier } from \"./intelligence-utils\";\n\n/** A runtime whose `identifyUser` is known to be set. */\nexport type IdentifiedRuntimeLike = CopilotRuntimeLike & {\n identifyUser: IdentifyUserCallback;\n};\n\n/** Narrows a runtime to one that has `identifyUser`. */\nexport function hasIdentifyUser(\n runtime: CopilotRuntimeLike,\n): runtime is IdentifiedRuntimeLike {\n return typeof runtime.identifyUser === \"function\";\n}\n\nconst resolvedUsers = new WeakMap<\n Request,\n Promise<CopilotRuntimeUser | Response>\n>();\n\n/**\n * Resolves the request's user through `identifyUser`, once per request, for\n * both runtime kinds: the Intelligence runtime and an SSE runtime with\n * `identifyUser` (local Thread ownership). Only the Intelligence runtime\n * needs the user's `name`; an SSE runtime needs the `id` alone.\n *\n * A callback that throws gets a 500 on every route.\n */\nexport async function resolveIntelligenceUser(params: {\n runtime: CopilotIntelligenceRuntimeLike | IdentifiedRuntimeLike;\n request: Request;\n}): Promise<CopilotRuntimeUser | Response> {\n const { runtime, request } = params;\n\n const existing = resolvedUsers.get(request);\n if (existing !== undefined) return existing;\n\n const resolution = resolveUser(runtime, request);\n resolvedUsers.set(request, resolution);\n return resolution;\n}\n\nasync function resolveUser(\n runtime: CopilotRuntimeLike,\n request: Request,\n): Promise<CopilotRuntimeUser | Response> {\n if (!hasIdentifyUser(runtime)) {\n console.error(\"Error identifying user: identifyUser is not configured\");\n return errorResponse(\"Failed to identify user\", 500);\n }\n try {\n const user = await runtime.identifyUser(request);\n if (!isValidIdentifier(user?.id)) {\n return errorResponse(\"identifyUser must return a valid user id\", 400);\n }\n const hasName =\n typeof user?.name === \"string\" && user.name.trim().length > 0;\n if (!hasName && isIntelligenceRuntime(runtime)) {\n return errorResponse(\"identifyUser must return a valid user name\", 400);\n }\n\n return { id: user.id, name: hasName ? user.name : user.id };\n } catch (error) {\n console.error(\"Error identifying user:\", error);\n return errorResponse(\"Failed to identify user\", 500);\n }\n}\n"],"mappings":";;;;;;AAgBA,SAAgB,gBACd,SACkC;AAClC,QAAO,OAAO,QAAQ,iBAAiB;;AAGzC,MAAM,gCAAgB,IAAI,SAGvB;;;;;;;;;AAUH,eAAsB,wBAAwB,QAGH;CACzC,MAAM,EAAE,SAAS,YAAY;CAE7B,MAAM,WAAW,cAAc,IAAI,QAAQ;AAC3C,KAAI,aAAa,OAAW,QAAO;CAEnC,MAAM,aAAa,YAAY,SAAS,QAAQ;AAChD,eAAc,IAAI,SAAS,WAAW;AACtC,QAAO;;AAGT,eAAe,YACb,SACA,SACwC;AACxC,KAAI,CAAC,gBAAgB,QAAQ,EAAE;AAC7B,UAAQ,MAAM,yDAAyD;AACvE,SAAO,cAAc,2BAA2B,IAAI;;AAEtD,KAAI;EACF,MAAM,OAAO,MAAM,QAAQ,aAAa,QAAQ;AAChD,MAAI,CAAC,kBAAkB,MAAM,GAAG,CAC9B,QAAO,cAAc,4CAA4C,IAAI;EAEvE,MAAM,UACJ,OAAO,MAAM,SAAS,YAAY,KAAK,KAAK,MAAM,CAAC,SAAS;AAC9D,MAAI,CAAC,WAAW,sBAAsB,QAAQ,CAC5C,QAAO,cAAc,8CAA8C,IAAI;AAGzE,SAAO;GAAE,IAAI,KAAK;GAAI,MAAM,UAAU,KAAK,OAAO,KAAK;GAAI;UACpD,OAAO;AACd,UAAQ,MAAM,2BAA2B,MAAM;AAC/C,SAAO,cAAc,2BAA2B,IAAI"}
1
+ {"version":3,"file":"resolve-intelligence-user.mjs","names":[],"sources":["../../../../src/runtime/handlers/shared/resolve-intelligence-user.ts"],"sourcesContent":["import type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n CopilotRuntimeUser,\n IdentifyUserCallback,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { getRuntimeLogger } from \"../../core/logger\";\nimport { errorResponse } from \"./json-response\";\nimport { isValidIdentifier } from \"./intelligence-utils\";\n\n/** A runtime whose `identifyUser` is known to be set. */\nexport type IdentifiedRuntimeLike = CopilotRuntimeLike & {\n identifyUser: IdentifyUserCallback;\n};\n\n/** Narrows a runtime to one that has `identifyUser`. */\nexport function hasIdentifyUser(\n runtime: CopilotRuntimeLike,\n): runtime is IdentifiedRuntimeLike {\n return typeof runtime.identifyUser === \"function\";\n}\n\nconst resolvedUsers = new WeakMap<\n Request,\n Promise<CopilotRuntimeUser | Response>\n>();\n\n/**\n * Resolves the request's user through `identifyUser`, once per request, for\n * both runtime kinds: the Intelligence runtime and an SSE runtime with\n * `identifyUser` (local Thread ownership). Only the Intelligence runtime\n * needs the user's `name`; an SSE runtime needs the `id` alone.\n *\n * A callback that throws gets a 500 on every route.\n */\nexport async function resolveIntelligenceUser(params: {\n runtime: CopilotIntelligenceRuntimeLike | IdentifiedRuntimeLike;\n request: Request;\n}): Promise<CopilotRuntimeUser | Response> {\n const { runtime, request } = params;\n\n const existing = resolvedUsers.get(request);\n if (existing !== undefined) return existing;\n\n const resolution = resolveUser(runtime, request);\n resolvedUsers.set(request, resolution);\n return resolution;\n}\n\nasync function resolveUser(\n runtime: CopilotRuntimeLike,\n request: Request,\n): Promise<CopilotRuntimeUser | Response> {\n if (!hasIdentifyUser(runtime)) {\n getRuntimeLogger(runtime).error(\n \"Error identifying user: identifyUser is not configured\",\n );\n return errorResponse(\"Failed to identify user\", 500);\n }\n try {\n const user = await runtime.identifyUser(request);\n if (!isValidIdentifier(user?.id)) {\n return errorResponse(\"identifyUser must return a valid user id\", 400);\n }\n const hasName =\n typeof user?.name === \"string\" && user.name.trim().length > 0;\n if (!hasName && isIntelligenceRuntime(runtime)) {\n return errorResponse(\"identifyUser must return a valid user name\", 400);\n }\n\n return { id: user.id, name: hasName ? user.name : user.id };\n } catch (error) {\n getRuntimeLogger(runtime).error({ err: error }, \"Error identifying user\");\n return errorResponse(\"Failed to identify user\", 500);\n }\n}\n"],"mappings":";;;;;;;AAiBA,SAAgB,gBACd,SACkC;AAClC,QAAO,OAAO,QAAQ,iBAAiB;;AAGzC,MAAM,gCAAgB,IAAI,SAGvB;;;;;;;;;AAUH,eAAsB,wBAAwB,QAGH;CACzC,MAAM,EAAE,SAAS,YAAY;CAE7B,MAAM,WAAW,cAAc,IAAI,QAAQ;AAC3C,KAAI,aAAa,OAAW,QAAO;CAEnC,MAAM,aAAa,YAAY,SAAS,QAAQ;AAChD,eAAc,IAAI,SAAS,WAAW;AACtC,QAAO;;AAGT,eAAe,YACb,SACA,SACwC;AACxC,KAAI,CAAC,gBAAgB,QAAQ,EAAE;AAC7B,mBAAiB,QAAQ,CAAC,MACxB,yDACD;AACD,SAAO,cAAc,2BAA2B,IAAI;;AAEtD,KAAI;EACF,MAAM,OAAO,MAAM,QAAQ,aAAa,QAAQ;AAChD,MAAI,CAAC,kBAAkB,MAAM,GAAG,CAC9B,QAAO,cAAc,4CAA4C,IAAI;EAEvE,MAAM,UACJ,OAAO,MAAM,SAAS,YAAY,KAAK,KAAK,MAAM,CAAC,SAAS;AAC9D,MAAI,CAAC,WAAW,sBAAsB,QAAQ,CAC5C,QAAO,cAAc,8CAA8C,IAAI;AAGzE,SAAO;GAAE,IAAI,KAAK;GAAI,MAAM,UAAU,KAAK,OAAO,KAAK;GAAI;UACpD,OAAO;AACd,mBAAiB,QAAQ,CAAC,MAAM,EAAE,KAAK,OAAO,EAAE,yBAAyB;AACzE,SAAO,cAAc,2BAA2B,IAAI"}
@@ -1,6 +1,6 @@
1
1
  const require_sse_keep_alive = require('./sse-keep-alive.cjs');
2
- const require_agent_runner = require('../../runner/agent-runner.cjs');
3
2
  const require_logger = require('../../core/logger.cjs');
3
+ const require_agent_runner = require('../../runner/agent-runner.cjs');
4
4
  const require_telemetry_client = require('../../telemetry/telemetry-client.cjs');
5
5
  let _copilotkit_shared = require("@copilotkit/shared");
6
6
  let _ag_ui_client = require("@ag-ui/client");
@@ -15,7 +15,7 @@ let _ag_ui_encoder = require("@ag-ui/encoder");
15
15
  function isThreadAlreadyRunning(error) {
16
16
  return error instanceof Error && (error.code === _copilotkit_shared.THREAD_ALREADY_RUNNING_ERROR_CODE || error.message === "Thread already running");
17
17
  }
18
- function createSseEventResponse({ request, observableFactory, debugEventBus, agentId, debug, logger, telemetry: telemetry$1 = require_telemetry_client.default, executionSeed, captureTelemetry = true, runtimeErrorReporter, startTime, keepAliveIntervalSeconds }) {
18
+ function createSseEventResponse({ request, observableFactory, debugEventBus, agentId, debug, debugLogger: preCreatedDebugLogger, logger = require_logger.getRuntimeLogger(), telemetry: telemetry$1 = require_telemetry_client.default, executionSeed, captureTelemetry = true, runtimeErrorReporter, startTime, keepAliveIntervalSeconds }) {
19
19
  const keepAliveSeconds = require_sse_keep_alive.resolveSseKeepAliveIntervalSeconds(keepAliveIntervalSeconds);
20
20
  const stream = new TransformStream();
21
21
  const writer = stream.writable.getWriter();
@@ -24,10 +24,7 @@ function createSseEventResponse({ request, observableFactory, debugEventBus, age
24
24
  let terminalEventWritten = false;
25
25
  let debugThreadId = "";
26
26
  let debugRunId = "";
27
- const debugLogger = debug?.enabled ? logger ?? require_logger.createLogger({
28
- level: "debug",
29
- component: "copilotkit-debug"
30
- }) : void 0;
27
+ const debugLogger = debug?.enabled ? preCreatedDebugLogger ?? require_logger.createDebugLogger() : void 0;
31
28
  const closeStream = async () => {
32
29
  if (!streamClosed) try {
33
30
  await writer.close();
@@ -63,18 +60,12 @@ function createSseEventResponse({ request, observableFactory, debugEventBus, age
63
60
  } catch {}
64
61
  };
65
62
  const logError = (error) => {
66
- console.error("Error running agent:", error);
67
- console.error("Error stack:", error instanceof Error ? error.stack : "No stack trace");
68
- console.error("Error details:", {
69
- name: error instanceof Error ? error.name : "Unknown",
70
- message: error instanceof Error ? error.message : String(error),
71
- cause: error instanceof Error ? error.cause : void 0
72
- });
63
+ logger.error({ err: error }, "Error running agent");
73
64
  };
74
65
  let subscription;
75
66
  let agentErrorReported = false;
76
67
  const logAccessDenied = (error) => {
77
- console.warn("[CopilotKit] Run refused: the thread belongs to another identity.", error instanceof Error ? error.message : String(error));
68
+ logger.warn({ err: error }, "[CopilotKit] Run refused: the thread belongs to another identity.");
78
69
  };
79
70
  const reportAgentError = (error, phase) => {
80
71
  if (agentErrorReported) return;
@@ -1 +1 @@
1
- {"version":3,"file":"sse-response.cjs","names":["THREAD_ALREADY_RUNNING_ERROR_CODE","defaultTelemetry","resolveSseKeepAliveIntervalSeconds","EventEncoder","createLogger","EventType","isThreadAccessDeniedError","THREAD_ACCESS_DENIED_ERROR_CODE","telemetry","keepAliveSse"],"sources":["../../../../src/runtime/handlers/shared/sse-response.ts"],"sourcesContent":["import { EventType } from \"@ag-ui/client\";\nimport 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 { THREAD_ALREADY_RUNNING_ERROR_CODE } from \"@copilotkit/shared\";\nimport {\n THREAD_ACCESS_DENIED_ERROR_CODE,\n isThreadAccessDeniedError,\n} from \"../../runner/agent-runner\";\nimport type { ResolvedDebugConfig } from \"@copilotkit/shared\";\nimport { createLogger } from \"../../core/logger\";\nimport type { CopilotRuntimeLogger } from \"../../core/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\n/**\n * Whether a runner rejected the run because the thread is busy. Matches the\n * `code` of {@link ThreadAlreadyRunningError}, and the plain message that\n * custom runners copied from the built-in ones still throw.\n */\nfunction isThreadAlreadyRunning(error: unknown): boolean {\n return (\n error instanceof Error &&\n ((error as { code?: unknown }).code === THREAD_ALREADY_RUNNING_ERROR_CODE ||\n error.message === \"Thread already running\")\n );\n}\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 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 // Set once the current run's RUN_FINISHED or RUN_ERROR has been queued for\n // the client. AG-UI allows nothing after either until the next RUN_STARTED,\n // so a later failure must not add a RUN_ERROR.\n let terminalEventWritten = 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 // Report a failure to the client as a terminal RUN_ERROR. Without it the\n // client sees an empty stream that ends normally, so its run \"succeeds\"\n // with no reply and no error (e.g. \"Thread already running\" on a busy\n // thread). Only a busy thread is named, with a code clients can branch on;\n // anything else may carry internal detail, so the client gets a generic\n // message and the full error stays in the server log.\n const writeRunError = async (error: unknown) => {\n if (terminalEventWritten || streamClosed || request.signal.aborted) {\n return;\n }\n terminalEventWritten = true;\n const event = isThreadAlreadyRunning(error)\n ? {\n type: EventType.RUN_ERROR,\n message: \"Thread already running\",\n code: THREAD_ALREADY_RUNNING_ERROR_CODE,\n }\n : isThreadAccessDeniedError(error)\n ? {\n type: EventType.RUN_ERROR,\n message: \"Thread access denied\",\n code: THREAD_ACCESS_DENIED_ERROR_CODE,\n }\n : { type: EventType.RUN_ERROR, message: \"Agent run failed\" };\n // The inspector sees every streamed event, so it needs this one too or\n // the run it saw start never ends there. A run that never started has\n // no ids to file it under, so it is not sent.\n if (debugEventBus && debugRunId) {\n try {\n debugEventBus.broadcast(event as BaseEvent, {\n agentId: agentId ?? \"\",\n threadId: debugThreadId,\n runId: debugRunId,\n });\n } catch (broadcastError) {\n logError(broadcastError);\n }\n }\n try {\n await writer.write(encoder.encodeBinary(event as BaseEvent));\n } catch {\n // The client is already gone; closeStream() handles the rest.\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 // A refused run is an access decision, not an agent failure: log it as a\n // warning and keep it out of the error reporter.\n const logAccessDenied = (error: unknown) => {\n console.warn(\n \"[CopilotKit] Run refused: the thread belongs to another identity.\",\n error instanceof Error ? error.message : String(error),\n );\n };\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 void 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 // RxJS ignores what an observer returns, so these async handlers run\n // fire-and-forget.\n const onNext = async (event: BaseEvent) => {\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 // /connect replays finished runs before the live one, so a new\n // RUN_STARTED reopens the stream for a RUN_ERROR.\n if (event.type === EventType.RUN_STARTED) {\n terminalEventWritten = false;\n } else if (\n event.type === EventType.RUN_FINISHED ||\n event.type === EventType.RUN_ERROR\n ) {\n terminalEventWritten = true;\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 const onError = async (error: unknown) => {\n if (isThreadAccessDeniedError(error)) {\n logAccessDenied(error);\n await writeRunError(error);\n await closeStream();\n return;\n }\n reportAgentError(error, \"sse.subscription\");\n if (captureTelemetry) {\n // Analytics gets the outcome, not the message: provider and tool\n // errors can quote prompts, arguments or URLs. Same as Intelligence.\n void telemetry.capture(\"oss.runtime.agent_execution_stream_errored\", {\n ...executionInfo,\n error: \"AGENT_EXECUTION_FAILED\",\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 writeRunError(error);\n await closeStream();\n };\n const onComplete = async () => {\n if (captureTelemetry) {\n void 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 subscription = observable.subscribe({\n next: (event) => {\n void onNext(event);\n },\n error: (error: unknown) => {\n void onError(error);\n },\n complete: () => {\n void onComplete();\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 if (isThreadAccessDeniedError(error)) {\n logAccessDenied(error);\n } else {\n reportAgentError(error, \"sse.factory\");\n logError(error);\n }\n await writeRunError(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":";;;;;;;;;;;;;;AA8BA,SAAS,uBAAuB,OAAyB;AACvD,QACE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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":["THREAD_ALREADY_RUNNING_ERROR_CODE","getRuntimeLogger","defaultTelemetry","resolveSseKeepAliveIntervalSeconds","EventEncoder","createDebugLogger","EventType","isThreadAccessDeniedError","THREAD_ACCESS_DENIED_ERROR_CODE","telemetry","keepAliveSse"],"sources":["../../../../src/runtime/handlers/shared/sse-response.ts"],"sourcesContent":["import { EventType } from \"@ag-ui/client\";\nimport 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 { THREAD_ALREADY_RUNNING_ERROR_CODE } from \"@copilotkit/shared\";\nimport {\n THREAD_ACCESS_DENIED_ERROR_CODE,\n isThreadAccessDeniedError,\n} from \"../../runner/agent-runner\";\nimport type { ResolvedDebugConfig } from \"@copilotkit/shared\";\nimport { createDebugLogger, getRuntimeLogger } from \"../../core/logger\";\nimport type { CopilotRuntimeLogger } from \"../../core/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\n/**\n * Whether a runner rejected the run because the thread is busy. Matches the\n * `code` of {@link ThreadAlreadyRunningError}, and the plain message that\n * custom runners copied from the built-in ones still throw.\n */\nfunction isThreadAlreadyRunning(error: unknown): boolean {\n return (\n error instanceof Error &&\n ((error as { code?: unknown }).code === THREAD_ALREADY_RUNNING_ERROR_CODE ||\n error.message === \"Thread already running\")\n );\n}\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 debug logger, so a request does not create its own. */\n debugLogger?: CopilotRuntimeLogger;\n /** Where errors and warnings go. Default: the console. */\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 debugLogger: preCreatedDebugLogger,\n logger = getRuntimeLogger(),\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 // Set once the current run's RUN_FINISHED or RUN_ERROR has been queued for\n // the client. AG-UI allows nothing after either until the next RUN_STARTED,\n // so a later failure must not add a RUN_ERROR.\n let terminalEventWritten = false;\n let debugThreadId = \"\";\n let debugRunId = \"\";\n\n const debugLogger = debug?.enabled\n ? (preCreatedDebugLogger ?? createDebugLogger())\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 // Report a failure to the client as a terminal RUN_ERROR. Without it the\n // client sees an empty stream that ends normally, so its run \"succeeds\"\n // with no reply and no error (e.g. \"Thread already running\" on a busy\n // thread). Only a busy thread is named, with a code clients can branch on;\n // anything else may carry internal detail, so the client gets a generic\n // message and the full error stays in the server log.\n const writeRunError = async (error: unknown) => {\n if (terminalEventWritten || streamClosed || request.signal.aborted) {\n return;\n }\n terminalEventWritten = true;\n const event = isThreadAlreadyRunning(error)\n ? {\n type: EventType.RUN_ERROR,\n message: \"Thread already running\",\n code: THREAD_ALREADY_RUNNING_ERROR_CODE,\n }\n : isThreadAccessDeniedError(error)\n ? {\n type: EventType.RUN_ERROR,\n message: \"Thread access denied\",\n code: THREAD_ACCESS_DENIED_ERROR_CODE,\n }\n : { type: EventType.RUN_ERROR, message: \"Agent run failed\" };\n // The inspector sees every streamed event, so it needs this one too or\n // the run it saw start never ends there. A run that never started has\n // no ids to file it under, so it is not sent.\n if (debugEventBus && debugRunId) {\n try {\n debugEventBus.broadcast(event as BaseEvent, {\n agentId: agentId ?? \"\",\n threadId: debugThreadId,\n runId: debugRunId,\n });\n } catch (broadcastError) {\n logError(broadcastError);\n }\n }\n try {\n await writer.write(encoder.encodeBinary(event as BaseEvent));\n } catch {\n // The client is already gone; closeStream() handles the rest.\n }\n };\n\n const logError = (error: unknown) => {\n logger.error({ err: error }, \"Error running agent\");\n };\n\n let subscription: Subscription | undefined;\n let agentErrorReported = false;\n\n // A refused run is an access decision, not an agent failure: log it as a\n // warning and keep it out of the error reporter.\n const logAccessDenied = (error: unknown) => {\n logger.warn(\n { err: error },\n \"[CopilotKit] Run refused: the thread belongs to another identity.\",\n );\n };\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 void 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 // RxJS ignores what an observer returns, so these async handlers run\n // fire-and-forget.\n const onNext = async (event: BaseEvent) => {\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 // /connect replays finished runs before the live one, so a new\n // RUN_STARTED reopens the stream for a RUN_ERROR.\n if (event.type === EventType.RUN_STARTED) {\n terminalEventWritten = false;\n } else if (\n event.type === EventType.RUN_FINISHED ||\n event.type === EventType.RUN_ERROR\n ) {\n terminalEventWritten = true;\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 const onError = async (error: unknown) => {\n if (isThreadAccessDeniedError(error)) {\n logAccessDenied(error);\n await writeRunError(error);\n await closeStream();\n return;\n }\n reportAgentError(error, \"sse.subscription\");\n if (captureTelemetry) {\n // Analytics gets the outcome, not the message: provider and tool\n // errors can quote prompts, arguments or URLs. Same as Intelligence.\n void telemetry.capture(\"oss.runtime.agent_execution_stream_errored\", {\n ...executionInfo,\n error: \"AGENT_EXECUTION_FAILED\",\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 writeRunError(error);\n await closeStream();\n };\n const onComplete = async () => {\n if (captureTelemetry) {\n void 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 subscription = observable.subscribe({\n next: (event) => {\n void onNext(event);\n },\n error: (error: unknown) => {\n void onError(error);\n },\n complete: () => {\n void onComplete();\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 if (isThreadAccessDeniedError(error)) {\n logAccessDenied(error);\n } else {\n reportAgentError(error, \"sse.factory\");\n logError(error);\n }\n await writeRunError(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":";;;;;;;;;;;;;;AA8BA,SAAS,uBAAuB,OAAyB;AACvD,QACE,iBAAiB,UACf,MAA6B,SAASA,wDACtC,MAAM,YAAY;;AA2CxB,SAAgB,uBAAuB,EACrC,SACA,mBACA,eACA,SACA,OACA,aAAa,uBACb,SAASC,iCAAkB,EAC3B,yBAAYC,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;CAInB,IAA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AAe,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,6 +1,6 @@
1
1
  import { keepAliveSse, resolveSseKeepAliveIntervalSeconds } from "./sse-keep-alive.mjs";
2
+ import { createDebugLogger, getRuntimeLogger } from "../../core/logger.mjs";
2
3
  import { THREAD_ACCESS_DENIED_ERROR_CODE, isThreadAccessDeniedError } from "../../runner/agent-runner.mjs";
3
- import { createLogger } from "../../core/logger.mjs";
4
4
  import telemetry from "../../telemetry/telemetry-client.mjs";
5
5
  import { THREAD_ALREADY_RUNNING_ERROR_CODE } from "@copilotkit/shared";
6
6
  import { EventType } from "@ag-ui/client";
@@ -15,7 +15,7 @@ import { EventEncoder } from "@ag-ui/encoder";
15
15
  function isThreadAlreadyRunning(error) {
16
16
  return error instanceof Error && (error.code === THREAD_ALREADY_RUNNING_ERROR_CODE || error.message === "Thread already running");
17
17
  }
18
- function createSseEventResponse({ request, observableFactory, debugEventBus, agentId, debug, logger, telemetry: telemetry$1 = telemetry, executionSeed, captureTelemetry = true, runtimeErrorReporter, startTime, keepAliveIntervalSeconds }) {
18
+ function createSseEventResponse({ request, observableFactory, debugEventBus, agentId, debug, debugLogger: preCreatedDebugLogger, logger = getRuntimeLogger(), telemetry: telemetry$1 = telemetry, executionSeed, captureTelemetry = true, runtimeErrorReporter, startTime, keepAliveIntervalSeconds }) {
19
19
  const keepAliveSeconds = resolveSseKeepAliveIntervalSeconds(keepAliveIntervalSeconds);
20
20
  const stream = new TransformStream();
21
21
  const writer = stream.writable.getWriter();
@@ -24,10 +24,7 @@ function createSseEventResponse({ request, observableFactory, debugEventBus, age
24
24
  let terminalEventWritten = false;
25
25
  let debugThreadId = "";
26
26
  let debugRunId = "";
27
- const debugLogger = debug?.enabled ? logger ?? createLogger({
28
- level: "debug",
29
- component: "copilotkit-debug"
30
- }) : void 0;
27
+ const debugLogger = debug?.enabled ? preCreatedDebugLogger ?? createDebugLogger() : void 0;
31
28
  const closeStream = async () => {
32
29
  if (!streamClosed) try {
33
30
  await writer.close();
@@ -63,18 +60,12 @@ function createSseEventResponse({ request, observableFactory, debugEventBus, age
63
60
  } catch {}
64
61
  };
65
62
  const logError = (error) => {
66
- console.error("Error running agent:", error);
67
- console.error("Error stack:", error instanceof Error ? error.stack : "No stack trace");
68
- console.error("Error details:", {
69
- name: error instanceof Error ? error.name : "Unknown",
70
- message: error instanceof Error ? error.message : String(error),
71
- cause: error instanceof Error ? error.cause : void 0
72
- });
63
+ logger.error({ err: error }, "Error running agent");
73
64
  };
74
65
  let subscription;
75
66
  let agentErrorReported = false;
76
67
  const logAccessDenied = (error) => {
77
- console.warn("[CopilotKit] Run refused: the thread belongs to another identity.", error instanceof Error ? error.message : String(error));
68
+ logger.warn({ err: error }, "[CopilotKit] Run refused: the thread belongs to another identity.");
78
69
  };
79
70
  const reportAgentError = (error, phase) => {
80
71
  if (agentErrorReported) return;
@@ -1 +1 @@
1
- {"version":3,"file":"sse-response.mjs","names":["defaultTelemetry","telemetry"],"sources":["../../../../src/runtime/handlers/shared/sse-response.ts"],"sourcesContent":["import { EventType } from \"@ag-ui/client\";\nimport 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 { THREAD_ALREADY_RUNNING_ERROR_CODE } from \"@copilotkit/shared\";\nimport {\n THREAD_ACCESS_DENIED_ERROR_CODE,\n isThreadAccessDeniedError,\n} from \"../../runner/agent-runner\";\nimport type { ResolvedDebugConfig } from \"@copilotkit/shared\";\nimport { createLogger } from \"../../core/logger\";\nimport type { CopilotRuntimeLogger } from \"../../core/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\n/**\n * Whether a runner rejected the run because the thread is busy. Matches the\n * `code` of {@link ThreadAlreadyRunningError}, and the plain message that\n * custom runners copied from the built-in ones still throw.\n */\nfunction isThreadAlreadyRunning(error: unknown): boolean {\n return (\n error instanceof Error &&\n ((error as { code?: unknown }).code === THREAD_ALREADY_RUNNING_ERROR_CODE ||\n error.message === \"Thread already running\")\n );\n}\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 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 // Set once the current run's RUN_FINISHED or RUN_ERROR has been queued for\n // the client. AG-UI allows nothing after either until the next RUN_STARTED,\n // so a later failure must not add a RUN_ERROR.\n let terminalEventWritten = 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 // Report a failure to the client as a terminal RUN_ERROR. Without it the\n // client sees an empty stream that ends normally, so its run \"succeeds\"\n // with no reply and no error (e.g. \"Thread already running\" on a busy\n // thread). Only a busy thread is named, with a code clients can branch on;\n // anything else may carry internal detail, so the client gets a generic\n // message and the full error stays in the server log.\n const writeRunError = async (error: unknown) => {\n if (terminalEventWritten || streamClosed || request.signal.aborted) {\n return;\n }\n terminalEventWritten = true;\n const event = isThreadAlreadyRunning(error)\n ? {\n type: EventType.RUN_ERROR,\n message: \"Thread already running\",\n code: THREAD_ALREADY_RUNNING_ERROR_CODE,\n }\n : isThreadAccessDeniedError(error)\n ? {\n type: EventType.RUN_ERROR,\n message: \"Thread access denied\",\n code: THREAD_ACCESS_DENIED_ERROR_CODE,\n }\n : { type: EventType.RUN_ERROR, message: \"Agent run failed\" };\n // The inspector sees every streamed event, so it needs this one too or\n // the run it saw start never ends there. A run that never started has\n // no ids to file it under, so it is not sent.\n if (debugEventBus && debugRunId) {\n try {\n debugEventBus.broadcast(event as BaseEvent, {\n agentId: agentId ?? \"\",\n threadId: debugThreadId,\n runId: debugRunId,\n });\n } catch (broadcastError) {\n logError(broadcastError);\n }\n }\n try {\n await writer.write(encoder.encodeBinary(event as BaseEvent));\n } catch {\n // The client is already gone; closeStream() handles the rest.\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 // A refused run is an access decision, not an agent failure: log it as a\n // warning and keep it out of the error reporter.\n const logAccessDenied = (error: unknown) => {\n console.warn(\n \"[CopilotKit] Run refused: the thread belongs to another identity.\",\n error instanceof Error ? error.message : String(error),\n );\n };\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 void 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 // RxJS ignores what an observer returns, so these async handlers run\n // fire-and-forget.\n const onNext = async (event: BaseEvent) => {\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 // /connect replays finished runs before the live one, so a new\n // RUN_STARTED reopens the stream for a RUN_ERROR.\n if (event.type === EventType.RUN_STARTED) {\n terminalEventWritten = false;\n } else if (\n event.type === EventType.RUN_FINISHED ||\n event.type === EventType.RUN_ERROR\n ) {\n terminalEventWritten = true;\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 const onError = async (error: unknown) => {\n if (isThreadAccessDeniedError(error)) {\n logAccessDenied(error);\n await writeRunError(error);\n await closeStream();\n return;\n }\n reportAgentError(error, \"sse.subscription\");\n if (captureTelemetry) {\n // Analytics gets the outcome, not the message: provider and tool\n // errors can quote prompts, arguments or URLs. Same as Intelligence.\n void telemetry.capture(\"oss.runtime.agent_execution_stream_errored\", {\n ...executionInfo,\n error: \"AGENT_EXECUTION_FAILED\",\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 writeRunError(error);\n await closeStream();\n };\n const onComplete = async () => {\n if (captureTelemetry) {\n void 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 subscription = observable.subscribe({\n next: (event) => {\n void onNext(event);\n },\n error: (error: unknown) => {\n void onError(error);\n },\n complete: () => {\n void onComplete();\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 if (isThreadAccessDeniedError(error)) {\n logAccessDenied(error);\n } else {\n reportAgentError(error, \"sse.factory\");\n logError(error);\n }\n await writeRunError(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":";;;;;;;;;;;;;;AA8BA,SAAS,uBAAuB,OAAyB;AACvD,QACE,iBAAiB,UACf,MAA6B,SAAS,qCACtC,MAAM,YAAY;;AAyCxB,SAAgB,uBAAuB,EACrC,SACA,mBACA,eACA,SACA,OACA,QACA,yBAAYA,WACZ,eACA,mBAAmB,MACnB,sBACA,WACA,4BACyC;CACzC,MAAM,mBAAmB,mCACvB,yBACD;CACD,MAAM,SAAS,IAAI,iBAAiB;CACpC,MAAM,SAAS,OAAO,SAAS,WAAW;CAC1C,MAAM,UAAU,IAAI,cAAc;CAClC,IAAI,eAAe;CAInB,IAAI,uBAAuB;CAC3B,IAAI,gBAAgB;CACpB,IAAI,aAAa;CAEjB,MAAM,cAAc,OAAO,UACtB,UACD,aAAa;EAAE,OAAO;EAAS,WAAW;EAAoB,CAAC,GAC/D;CAEJ,MAAM,cAAc,YAAY;AAC9B,MAAI,CAAC,a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vC,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
+ {"version":3,"file":"sse-response.mjs","names":["defaultTelemetry","telemetry"],"sources":["../../../../src/runtime/handlers/shared/sse-response.ts"],"sourcesContent":["import { EventType } from \"@ag-ui/client\";\nimport 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 { THREAD_ALREADY_RUNNING_ERROR_CODE } from \"@copilotkit/shared\";\nimport {\n THREAD_ACCESS_DENIED_ERROR_CODE,\n isThreadAccessDeniedError,\n} from \"../../runner/agent-runner\";\nimport type { ResolvedDebugConfig } from \"@copilotkit/shared\";\nimport { createDebugLogger, getRuntimeLogger } from \"../../core/logger\";\nimport type { CopilotRuntimeLogger } from \"../../core/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\n/**\n * Whether a runner rejected the run because the thread is busy. Matches the\n * `code` of {@link ThreadAlreadyRunningError}, and the plain message that\n * custom runners copied from the built-in ones still throw.\n */\nfunction isThreadAlreadyRunning(error: unknown): boolean {\n return (\n error instanceof Error &&\n ((error as { code?: unknown }).code === THREAD_ALREADY_RUNNING_ERROR_CODE ||\n error.message === \"Thread already running\")\n );\n}\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 debug logger, so a request does not create its own. */\n debugLogger?: CopilotRuntimeLogger;\n /** Where errors and warnings go. Default: the console. */\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 debugLogger: preCreatedDebugLogger,\n logger = getRuntimeLogger(),\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 // Set once the current run's RUN_FINISHED or RUN_ERROR has been queued for\n // the client. AG-UI allows nothing after either until the next RUN_STARTED,\n // so a later failure must not add a RUN_ERROR.\n let terminalEventWritten = false;\n let debugThreadId = \"\";\n let debugRunId = \"\";\n\n const debugLogger = debug?.enabled\n ? (preCreatedDebugLogger ?? createDebugLogger())\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 // Report a failure to the client as a terminal RUN_ERROR. Without it the\n // client sees an empty stream that ends normally, so its run \"succeeds\"\n // with no reply and no error (e.g. \"Thread already running\" on a busy\n // thread). Only a busy thread is named, with a code clients can branch on;\n // anything else may carry internal detail, so the client gets a generic\n // message and the full error stays in the server log.\n const writeRunError = async (error: unknown) => {\n if (terminalEventWritten || streamClosed || request.signal.aborted) {\n return;\n }\n terminalEventWritten = true;\n const event = isThreadAlreadyRunning(error)\n ? {\n type: EventType.RUN_ERROR,\n message: \"Thread already running\",\n code: THREAD_ALREADY_RUNNING_ERROR_CODE,\n }\n : isThreadAccessDeniedError(error)\n ? {\n type: EventType.RUN_ERROR,\n message: \"Thread access denied\",\n code: THREAD_ACCESS_DENIED_ERROR_CODE,\n }\n : { type: EventType.RUN_ERROR, message: \"Agent run failed\" };\n // The inspector sees every streamed event, so it needs this one too or\n // the run it saw start never ends there. A run that never started has\n // no ids to file it under, so it is not sent.\n if (debugEventBus && debugRunId) {\n try {\n debugEventBus.broadcast(event as BaseEvent, {\n agentId: agentId ?? \"\",\n threadId: debugThreadId,\n runId: debugRunId,\n });\n } catch (broadcastError) {\n logError(broadcastError);\n }\n }\n try {\n await writer.write(encoder.encodeBinary(event as BaseEvent));\n } catch {\n // The client is already gone; closeStream() handles the rest.\n }\n };\n\n const logError = (error: unknown) => {\n logger.error({ err: error }, \"Error running agent\");\n };\n\n let subscription: Subscription | undefined;\n let agentErrorReported = false;\n\n // A refused run is an access decision, not an agent failure: log it as a\n // warning and keep it out of the error reporter.\n const logAccessDenied = (error: unknown) => {\n logger.warn(\n { err: error },\n \"[CopilotKit] Run refused: the thread belongs to another identity.\",\n );\n };\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 void 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 // RxJS ignores what an observer returns, so these async handlers run\n // fire-and-forget.\n const onNext = async (event: BaseEvent) => {\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 // /connect replays finished runs before the live one, so a new\n // RUN_STARTED reopens the stream for a RUN_ERROR.\n if (event.type === EventType.RUN_STARTED) {\n terminalEventWritten = false;\n } else if (\n event.type === EventType.RUN_FINISHED ||\n event.type === EventType.RUN_ERROR\n ) {\n terminalEventWritten = true;\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 const onError = async (error: unknown) => {\n if (isThreadAccessDeniedError(error)) {\n logAccessDenied(error);\n await writeRunError(error);\n await closeStream();\n return;\n }\n reportAgentError(error, \"sse.subscription\");\n if (captureTelemetry) {\n // Analytics gets the outcome, not the message: provider and tool\n // errors can quote prompts, arguments or URLs. Same as Intelligence.\n void telemetry.capture(\"oss.runtime.agent_execution_stream_errored\", {\n ...executionInfo,\n error: \"AGENT_EXECUTION_FAILED\",\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 writeRunError(error);\n await closeStream();\n };\n const onComplete = async () => {\n if (captureTelemetry) {\n void 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 subscription = observable.subscribe({\n next: (event) => {\n void onNext(event);\n },\n error: (error: unknown) => {\n void onError(error);\n },\n complete: () => {\n void onComplete();\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 if (isThreadAccessDeniedError(error)) {\n logAccessDenied(error);\n } else {\n reportAgentError(error, \"sse.factory\");\n logError(error);\n }\n await writeRunError(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":";;;;;;;;;;;;;;AA8BA,SAAS,uBAAuB,OAAyB;AACvD,QACE,iBAAiB,UACf,MAA6B,SAAS,qCACtC,MAAM,YAAY;;AA2CxB,SAAgB,uBAAuB,EACrC,SACA,mBACA,eACA,SACA,OACA,aAAa,uBACb,SAAS,kBAAkB,EAC3B,yBAAYA,WACZ,eACA,mBAAmB,MACnB,sBACA,WACA,4BACyC;CACzC,MAAM,mBAAmB,mCACvB,yBACD;CACD,MAAM,SAAS,IAAI,iBAAiB;CACpC,MAAM,SAAS,OAAO,SAAS,WAAW;CAC1C,MAAM,UAAU,IAAI,cAAc;CAClC,IAAI,eAAe;CAInB,IAAI,uBAAuB;CAC3B,IAAI,gBAAgB;CACpB,IAAI,aAAa;CAEjB,MAAM,cAAc,OAAO,UACtB,yBAAyB,mBAAmB,GAC7C;CAEJ,MAAM,cAAc,YAAY;AAC9B,MAAI,CAAC,aACH,KAAI;AACF,SAAM,OAAO,OAAO;AACpB,kBAAe;UACT;;CAYZ,MAAM,gBAAgB,OAAO,UAAmB;AAC9C,MAAI,wBAAwB,gBAAgB,QAAQ,OAAO,QACzD;AAEF,yBAAuB;EACvB,MAAM,QAAQ,uBAAuB,MAAM,GACvC;GACE,MAAM,UAAU;GAChB,SAAS;GACT,MAAM;GACP,GACD,0BAA0B,MAAM,GAC9B;GACE,MAAM,UAAU;GAChB,SAAS;GACT,MAAM;GACP,GACD;GAAE,MAAM,UAAU;GAAW,SAAS;GAAoB;AAIhE,MAAI,iBAAiB,WACnB,KAAI;AACF,iBAAc,UAAU,OAAoB;IAC1C,SAAS,WAAW;IACpB,UAAU;IACV,OAAO;IACR,CAAC;WACK,gBAAgB;AACvB,YAAS,eAAe;;AAG5B,MAAI;AACF,SAAM,OAAO,MAA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;AAGb,OAAK,WAAW;;CAGlB,MAAM,WAAW,SAAS;AAG1B,KAAI,UAAU,eAAgB,MAAK,gBAAgB,SAAS;AAC5D,KAAI,UAAU,kBACZ,MAAK,mBAAmB,SAAS"}
@@ -1,3 +1,4 @@
1
+ const require_logger = require('../../core/logger.cjs');
1
2
  const require_agent_runner = require('../../runner/agent-runner.cjs');
2
3
  const require_json_response = require('./json-response.cjs');
3
4
  const require_resolve_intelligence_user = require('./resolve-intelligence-user.cjs');
@@ -50,7 +51,7 @@ function threadOwnershipUnsupportedMessage(runner) {
50
51
  * does not enforce thread ownership. Requests then fail with the same message.
51
52
  */
52
53
  function warnIfThreadOwnershipUnenforced(runtime) {
53
- if (require_resolve_intelligence_user.hasIdentifyUser(runtime) && !require_agent_runner.enforcesThreadOwnership(runtime.runner)) console.warn(`[CopilotKit] ${threadOwnershipUnsupportedMessage(runtime.runner)}`);
54
+ if (require_resolve_intelligence_user.hasIdentifyUser(runtime) && !require_agent_runner.enforcesThreadOwnership(runtime.runner)) require_logger.getRuntimeLogger(runtime).warn(`[CopilotKit] ${threadOwnershipUnsupportedMessage(runtime.runner)}`);
54
55
  }
55
56
  /**
56
57
  * The access mode `threads` selects. Throws on anything but an object whose
@@ -76,7 +77,7 @@ function warnIfThreadListRefused(runtime) {
76
77
  if (!require_agent_runner.supportsLocalThreadEndpoints(runtime.runner)) return;
77
78
  if (isThreadOperationAvailable(runtime, "list")) return;
78
79
  threadListRefusalWarned = true;
79
- console.warn(`[CopilotKit] ${THREAD_ACCESS_NOT_CONFIGURED_MESSAGE} Until then, GET /threads and POST /threads/clear return HTTP 403.`);
80
+ require_logger.getRuntimeLogger(runtime).warn(`[CopilotKit] ${THREAD_ACCESS_NOT_CONFIGURED_MESSAGE} Until then, GET /threads and POST /threads/clear return HTTP 403.`);
80
81
  }
81
82
  /**
82
83
  * True when `operation` can serve requests on this runtime at all: always
@@ -1 +1 @@
1
- {"version":3,"file":"thread-access.cjs","names":["hasIdentifyUser","enforcesThreadOwnership","supportsLocalThreadEndpoints","resolveIntelligenceUser","errorResponse"],"sources":["../../../../src/runtime/handlers/shared/thread-access.ts"],"sourcesContent":["import type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport type { AgentRunner } from \"../../runner/agent-runner\";\nimport {\n enforcesThreadOwnership,\n supportsLocalThreadEndpoints,\n} from \"../../runner/agent-runner\";\nimport { errorResponse } from \"./json-response\";\nimport {\n hasIdentifyUser,\n resolveIntelligenceUser,\n} from \"./resolve-intelligence-user\";\n\n/**\n * How local (non-Intelligence) Threads are shared among callers that\n * `identifyUser` does not identify. The full policy is\n * {@link ANONYMOUS_THREAD_ACCESS}.\n *\n * - `\"owner\"` (default): a Thread created without identity is a capability.\n * Whoever holds its id may read, connect to, continue and stop it, but\n * nobody may list or bulk-clear such Threads.\n * - `\"open\"`: every caller without identity shares those Threads, list and\n * clear included, as in earlier releases. Insecure for any deployment that\n * more than one person can reach.\n *\n * Neither mode loosens identity: with `identifyUser`, every operation reaches\n * only the caller's own Threads, and a Thread that an identified user created\n * is never reachable by an anonymous caller or another identity.\n */\nexport type ThreadAccessMode = \"owner\" | \"open\";\n\nexport interface ThreadsConfig {\n /** @default \"owner\" */\n access?: ThreadAccessMode;\n}\n\n/** The one place that sets the default Thread access mode. */\nexport const DEFAULT_THREAD_ACCESS: ThreadAccessMode = \"owner\";\n\n/** Owner id of a Thread created without identity. */\nexport const ANONYMOUS_THREAD_OWNER = \"\";\n\n/**\n * Every operation on a local Thread. `read` covers\n * `/threads/:id/{messages,events,state}`; `stop` covers a stop by Thread and a\n * stop by run id. `isRunning` has no route; runners check it the same way.\n */\nexport type ThreadOperation =\n | \"list\"\n | \"clear\"\n | \"read\"\n | \"connect\"\n | \"run\"\n | \"stop\"\n | \"isRunning\";\n\n/**\n * THE anonymous-Thread policy: which operations a caller without identity\n * (no `identifyUser`) may perform, per access mode. Every such operation\n * still reaches only anonymous Threads, never a Thread an identified user\n * owns. To tighten the default, change the `owner` row; nothing else encodes\n * this policy.\n *\n * Callers identified by `identifyUser` are not in this table: every operation\n * is allowed and reaches only their own Threads.\n */\nexport const ANONYMOUS_THREAD_ACCESS: Readonly<\n Record<ThreadAccessMode, Readonly<Record<ThreadOperation, boolean>>>\n> = {\n // A Thread id works as a capability for the Thread it names. Enumerating or\n // wiping every anonymous Thread needs identity or an explicit opt-in.\n owner: {\n list: false,\n clear: false,\n read: true,\n connect: true,\n run: true,\n stop: true,\n isRunning: true,\n },\n open: {\n list: true,\n clear: true,\n read: true,\n connect: true,\n run: true,\n stop: true,\n isRunning: true,\n },\n};\n\nexport const THREAD_ACCESS_NOT_CONFIGURED_MESSAGE =\n \"Listing and clearing threads need a caller identity. Pass `identifyUser: (request) => ({ id, name })` \" +\n \"to CopilotRuntime so each user lists and clears only their own threads, or pass \" +\n '`threads: { access: \"open\" }` to let every caller share threads created without identity ' +\n \"(insecure for multi-user deployments).\";\n\n/**\n * The configuration error for `identifyUser` with a runner that cannot keep\n * users apart. Every Thread operation is refused rather than served unscoped.\n */\nexport function threadOwnershipUnsupportedMessage(runner: AgentRunner): string {\n const name = runner.constructor?.name || \"the configured runner\";\n return (\n `identifyUser is set, but the runner ${name} does not enforce thread ownership: ` +\n \"it has no isThreadAccessible method. Thread routes, run, connect and stop are refused \" +\n \"so that no user can reach another user's threads. Use InMemoryAgentRunner or \" +\n \"SqliteAgentRunner, or implement isThreadAccessible and honor ownerId in run, connect, \" +\n \"stop and isRunning.\"\n );\n}\n\n/**\n * Log once, at runtime construction, when `identifyUser` is set but the runner\n * does not enforce thread ownership. Requests then fail with the same message.\n */\nexport function warnIfThreadOwnershipUnenforced(\n runtime: CopilotRuntimeLike,\n): void {\n if (hasIdentifyUser(runtime) && !enforcesThreadOwnership(runtime.runner)) {\n console.warn(\n `[CopilotKit] ${threadOwnershipUnsupportedMessage(runtime.runner)}`,\n );\n }\n}\n\n/**\n * The access mode `threads` selects. Throws on anything but an object whose\n * `access` is `\"owner\"`, `\"open\"` or omitted: a typo must not silently fall\n * back to the default.\n */\nexport function resolveThreadAccessMode(\n config: ThreadsConfig | undefined,\n): ThreadAccessMode {\n if (config === undefined) return DEFAULT_THREAD_ACCESS;\n if (typeof config !== \"object\" || config === null) {\n throw new Error(\n '`threads` must be an object, such as `{ access: \"owner\" }`; got ' +\n JSON.stringify(config),\n );\n }\n const access: unknown = config.access;\n if (access === undefined) return DEFAULT_THREAD_ACCESS;\n if (access !== \"owner\" && access !== \"open\") {\n throw new Error(\n `threads.access must be \"owner\" or \"open\"; got ${JSON.stringify(access)}`,\n );\n }\n return access;\n}\n\nlet threadListRefusalWarned = false;\n\n/** Re-arm the once-per-process startup warnings. Internal: for tests. */\nexport function ɵresetThreadAccessWarnings(): void {\n threadListRefusalWarned = false;\n}\n\n/**\n * Log once per process, at runtime construction, when the configuration\n * refuses the Thread list and clear routes, so operators see why those\n * requests get 403.\n */\nexport function warnIfThreadListRefused(runtime: CopilotRuntimeLike): void {\n if (threadListRefusalWarned) return;\n if (!supportsLocalThreadEndpoints(runtime.runner)) return;\n if (isThreadOperationAvailable(runtime, \"list\")) return;\n threadListRefusalWarned = true;\n console.warn(\n `[CopilotKit] ${THREAD_ACCESS_NOT_CONFIGURED_MESSAGE} Until then, ` +\n \"GET /threads and POST /threads/clear return HTTP 403.\",\n );\n}\n\n/**\n * True when `operation` can serve requests on this runtime at all: always\n * with `identifyUser` (scoped to the caller), otherwise per\n * {@link ANONYMOUS_THREAD_ACCESS}.\n */\nexport function isThreadOperationAvailable(\n runtime: CopilotRuntimeLike,\n operation: ThreadOperation,\n): boolean {\n // The same identity test as resolveLocalThreadOwner, so a non-function\n // value is no identity everywhere and never opens list or clear.\n if (hasIdentifyUser(runtime)) {\n return enforcesThreadOwnership(runtime.runner);\n }\n return ANONYMOUS_THREAD_ACCESS[runtime.threadAccess ?? DEFAULT_THREAD_ACCESS][\n operation\n ];\n}\n\n/**\n * Resolves the owner id that a local Thread request acts as, or the error\n * Response that refuses it. Every local Thread handler goes through here.\n *\n * - With `identifyUser`: the identified user's id. Refused when the runner\n * cannot enforce owners, or when identification fails.\n * - Without it: the anonymous owner, when {@link ANONYMOUS_THREAD_ACCESS}\n * allows `operation` in the configured mode; otherwise a 403 that names the\n * options to set.\n */\nexport async function resolveLocalThreadOwner(params: {\n runtime: CopilotRuntimeLike;\n request: Request;\n operation: ThreadOperation;\n}): Promise<string | Response> {\n const { runtime, request, operation } = params;\n if (hasIdentifyUser(runtime)) {\n // Never serve an identified request through a runner that cannot keep\n // users apart: refuse it with the configuration error instead.\n if (!enforcesThreadOwnership(runtime.runner)) {\n return Response.json(\n {\n error: \"thread_ownership_unsupported\",\n message: threadOwnershipUnsupportedMessage(runtime.runner),\n },\n { status: 500 },\n );\n }\n const user = await resolveIntelligenceUser({ runtime, request });\n return user instanceof Response ? user : user.id;\n }\n if (!isThreadOperationAvailable(runtime, operation)) {\n return Response.json(\n {\n error: \"thread_access_not_configured\",\n message: THREAD_ACCESS_NOT_CONFIGURED_MESSAGE,\n },\n { status: 403 },\n );\n }\n return ANONYMOUS_THREAD_OWNER;\n}\n\n/**\n * The response to a run on a Thread that another identity owns, whether the\n * handler's check or the runner refused it. It is the same 404 and body as an\n * unknown Thread on the inspect routes, so it does not say that the Thread\n * belongs to someone. A run on an unknown Thread id creates the Thread, so a\n * refusal still shows that the id is taken; it never shows by whom.\n */\nexport function threadAccessDeniedResponse(): Response {\n return errorResponse(\"Thread not found\", 404);\n}\n"],"mappings":";;;;;;AAoCA,MAAa,wBAA0C;;AAGvD,MAAa,yBAAyB;;;;;;;;;;;AA0BtC,MAAa,0BAET;CAGF,OAAO;EACL,MAAM;EACN,OAAO;EACP,MAAM;EACN,SAAS;EACT,KAAK;EACL,MAAM;EACN,WAAW;EACZ;CACD,MAAM;EACJ,MAAM;EACN,OAAO;EACP,MAAM;EACN,SAAS;EACT,KAAK;EACL,MAAM;EACN,WAAW;EACZ;CACF;AAED,MAAa,uCACX;;;;;AASF,SAAgB,kCAAkC,QAA6B;AAE7E,QACE,uCAFW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AAS,UAAU,CACjD,QAAO,SAAS,KACd;EACE,OAAO;EACP,SAAS;EACV,EACD,EAAE,QAAQ,KAAK,CAChB;AAEH,QAAO;;;;;;;;;AAUT,SAAgB,6BAAuC;AACrD,QAAOC,oCAAc,oBAAoB,IAAI"}
1
+ {"version":3,"file":"thread-access.cjs","names":["hasIdentifyUser","enforcesThreadOwnership","supportsLocalThreadEndpoints","resolveIntelligenceUser","errorResponse"],"sources":["../../../../src/runtime/handlers/shared/thread-access.ts"],"sourcesContent":["import { getRuntimeLogger } from \"../../core/logger\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport type { AgentRunner } from \"../../runner/agent-runner\";\nimport {\n enforcesThreadOwnership,\n supportsLocalThreadEndpoints,\n} from \"../../runner/agent-runner\";\nimport { errorResponse } from \"./json-response\";\nimport {\n hasIdentifyUser,\n resolveIntelligenceUser,\n} from \"./resolve-intelligence-user\";\n\n/**\n * How local (non-Intelligence) Threads are shared among callers that\n * `identifyUser` does not identify. The full policy is\n * {@link ANONYMOUS_THREAD_ACCESS}.\n *\n * - `\"owner\"` (default): a Thread created without identity is a capability.\n * Whoever holds its id may read, connect to, continue and stop it, but\n * nobody may list or bulk-clear such Threads.\n * - `\"open\"`: every caller without identity shares those Threads, list and\n * clear included, as in earlier releases. Insecure for any deployment that\n * more than one person can reach.\n *\n * Neither mode loosens identity: with `identifyUser`, every operation reaches\n * only the caller's own Threads, and a Thread that an identified user created\n * is never reachable by an anonymous caller or another identity.\n */\nexport type ThreadAccessMode = \"owner\" | \"open\";\n\nexport interface ThreadsConfig {\n /** @default \"owner\" */\n access?: ThreadAccessMode;\n}\n\n/** The one place that sets the default Thread access mode. */\nexport const DEFAULT_THREAD_ACCESS: ThreadAccessMode = \"owner\";\n\n/** Owner id of a Thread created without identity. */\nexport const ANONYMOUS_THREAD_OWNER = \"\";\n\n/**\n * Every operation on a local Thread. `read` covers\n * `/threads/:id/{messages,events,state}`; `stop` covers a stop by Thread and a\n * stop by run id. `isRunning` has no route; runners check it the same way.\n */\nexport type ThreadOperation =\n | \"list\"\n | \"clear\"\n | \"read\"\n | \"connect\"\n | \"run\"\n | \"stop\"\n | \"isRunning\";\n\n/**\n * THE anonymous-Thread policy: which operations a caller without identity\n * (no `identifyUser`) may perform, per access mode. Every such operation\n * still reaches only anonymous Threads, never a Thread an identified user\n * owns. To tighten the default, change the `owner` row; nothing else encodes\n * this policy.\n *\n * Callers identified by `identifyUser` are not in this table: every operation\n * is allowed and reaches only their own Threads.\n */\nexport const ANONYMOUS_THREAD_ACCESS: Readonly<\n Record<ThreadAccessMode, Readonly<Record<ThreadOperation, boolean>>>\n> = {\n // A Thread id works as a capability for the Thread it names. Enumerating or\n // wiping every anonymous Thread needs identity or an explicit opt-in.\n owner: {\n list: false,\n clear: false,\n read: true,\n connect: true,\n run: true,\n stop: true,\n isRunning: true,\n },\n open: {\n list: true,\n clear: true,\n read: true,\n connect: true,\n run: true,\n stop: true,\n isRunning: true,\n },\n};\n\nexport const THREAD_ACCESS_NOT_CONFIGURED_MESSAGE =\n \"Listing and clearing threads need a caller identity. Pass `identifyUser: (request) => ({ id, name })` \" +\n \"to CopilotRuntime so each user lists and clears only their own threads, or pass \" +\n '`threads: { access: \"open\" }` to let every caller share threads created without identity ' +\n \"(insecure for multi-user deployments).\";\n\n/**\n * The configuration error for `identifyUser` with a runner that cannot keep\n * users apart. Every Thread operation is refused rather than served unscoped.\n */\nexport function threadOwnershipUnsupportedMessage(runner: AgentRunner): string {\n const name = runner.constructor?.name || \"the configured runner\";\n return (\n `identifyUser is set, but the runner ${name} does not enforce thread ownership: ` +\n \"it has no isThreadAccessible method. Thread routes, run, connect and stop are refused \" +\n \"so that no user can reach another user's threads. Use InMemoryAgentRunner or \" +\n \"SqliteAgentRunner, or implement isThreadAccessible and honor ownerId in run, connect, \" +\n \"stop and isRunning.\"\n );\n}\n\n/**\n * Log once, at runtime construction, when `identifyUser` is set but the runner\n * does not enforce thread ownership. Requests then fail with the same message.\n */\nexport function warnIfThreadOwnershipUnenforced(\n runtime: CopilotRuntimeLike,\n): void {\n if (hasIdentifyUser(runtime) && !enforcesThreadOwnership(runtime.runner)) {\n getRuntimeLogger(runtime).warn(\n `[CopilotKit] ${threadOwnershipUnsupportedMessage(runtime.runner)}`,\n );\n }\n}\n\n/**\n * The access mode `threads` selects. Throws on anything but an object whose\n * `access` is `\"owner\"`, `\"open\"` or omitted: a typo must not silently fall\n * back to the default.\n */\nexport function resolveThreadAccessMode(\n config: ThreadsConfig | undefined,\n): ThreadAccessMode {\n if (config === undefined) return DEFAULT_THREAD_ACCESS;\n if (typeof config !== \"object\" || config === null) {\n throw new Error(\n '`threads` must be an object, such as `{ access: \"owner\" }`; got ' +\n JSON.stringify(config),\n );\n }\n const access: unknown = config.access;\n if (access === undefined) return DEFAULT_THREAD_ACCESS;\n if (access !== \"owner\" && access !== \"open\") {\n throw new Error(\n `threads.access must be \"owner\" or \"open\"; got ${JSON.stringify(access)}`,\n );\n }\n return access;\n}\n\nlet threadListRefusalWarned = false;\n\n/** Re-arm the once-per-process startup warnings. Internal: for tests. */\nexport function ɵresetThreadAccessWarnings(): void {\n threadListRefusalWarned = false;\n}\n\n/**\n * Log once per process, at runtime construction, when the configuration\n * refuses the Thread list and clear routes, so operators see why those\n * requests get 403.\n */\nexport function warnIfThreadListRefused(runtime: CopilotRuntimeLike): void {\n if (threadListRefusalWarned) return;\n if (!supportsLocalThreadEndpoints(runtime.runner)) return;\n if (isThreadOperationAvailable(runtime, \"list\")) return;\n threadListRefusalWarned = true;\n getRuntimeLogger(runtime).warn(\n `[CopilotKit] ${THREAD_ACCESS_NOT_CONFIGURED_MESSAGE} Until then, ` +\n \"GET /threads and POST /threads/clear return HTTP 403.\",\n );\n}\n\n/**\n * True when `operation` can serve requests on this runtime at all: always\n * with `identifyUser` (scoped to the caller), otherwise per\n * {@link ANONYMOUS_THREAD_ACCESS}.\n */\nexport function isThreadOperationAvailable(\n runtime: CopilotRuntimeLike,\n operation: ThreadOperation,\n): boolean {\n // The same identity test as resolveLocalThreadOwner, so a non-function\n // value is no identity everywhere and never opens list or clear.\n if (hasIdentifyUser(runtime)) {\n return enforcesThreadOwnership(runtime.runner);\n }\n return ANONYMOUS_THREAD_ACCESS[runtime.threadAccess ?? DEFAULT_THREAD_ACCESS][\n operation\n ];\n}\n\n/**\n * Resolves the owner id that a local Thread request acts as, or the error\n * Response that refuses it. Every local Thread handler goes through here.\n *\n * - With `identifyUser`: the identified user's id. Refused when the runner\n * cannot enforce owners, or when identification fails.\n * - Without it: the anonymous owner, when {@link ANONYMOUS_THREAD_ACCESS}\n * allows `operation` in the configured mode; otherwise a 403 that names the\n * options to set.\n */\nexport async function resolveLocalThreadOwner(params: {\n runtime: CopilotRuntimeLike;\n request: Request;\n operation: ThreadOperation;\n}): Promise<string | Response> {\n const { runtime, request, operation } = params;\n if (hasIdentifyUser(runtime)) {\n // Never serve an identified request through a runner that cannot keep\n // users apart: refuse it with the configuration error instead.\n if (!enforcesThreadOwnership(runtime.runner)) {\n return Response.json(\n {\n error: \"thread_ownership_unsupported\",\n message: threadOwnershipUnsupportedMessage(runtime.runner),\n },\n { status: 500 },\n );\n }\n const user = await resolveIntelligenceUser({ runtime, request });\n return user instanceof Response ? user : user.id;\n }\n if (!isThreadOperationAvailable(runtime, operation)) {\n return Response.json(\n {\n error: \"thread_access_not_configured\",\n message: THREAD_ACCESS_NOT_CONFIGURED_MESSAGE,\n },\n { status: 403 },\n );\n }\n return ANONYMOUS_THREAD_OWNER;\n}\n\n/**\n * The response to a run on a Thread that another identity owns, whether the\n * handler's check or the runner refused it. It is the same 404 and body as an\n * unknown Thread on the inspect routes, so it does not say that the Thread\n * belongs to someone. A run on an unknown Thread id creates the Thread, so a\n * refusal still shows that the id is taken; it never shows by whom.\n */\nexport function threadAccessDeniedResponse(): Response {\n return errorResponse(\"Thread not found\", 404);\n}\n"],"mappings":";;;;;;;AAqCA,MAAa,wBAA0C;;AAGvD,MAAa,yBAAyB;;;;;;;;;;;A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cAAc;AACxC,KAAID,kDAAgB,QAAQ,EAAE;AAG5B,MAAI,CAACC,6CAAwB,QAAQ,OAAO,CAC1C,QAAO,SAAS,KACd;GACE,OAAO;GACP,SAAS,kCAAkC,QAAQ,OAAO;GAC3D,EACD,EAAE,QAAQ,KAAK,CAChB;EAEH,MAAM,OAAO,MAAME,0DAAwB;GAAE;GAAS;GAAS,CAAC;AAChE,SAAO,gBAAgB,WAAW,OAAO,KAAK;;AAEhD,KAAI,CAAC,2BAA2B,SAAS,UAAU,CACjD,QAAO,SAAS,KACd;EACE,OAAO;EACP,SAAS;EACV,EACD,EAAE,QAAQ,KAAK,CAChB;AAEH,QAAO;;;;;;;;;AAUT,SAAgB,6BAAuC;AACrD,QAAOC,oCAAc,oBAAoB,IAAI"}
@@ -1 +1 @@
1
- {"version":3,"file":"thread-access.d.cts","names":[],"sources":["../../../../src/runtime/handlers/shared/thread-access.ts"],"mappings":";;;;;;AA4BA;;;;;AAEA;;;;;;;;;KAFY,gBAAA;AAAA,UAEK,aAAA;;EAEf,MAAA,GAAS,gBAAA;AAAA"}
1
+ {"version":3,"file":"thread-access.d.cts","names":[],"sources":["../../../../src/runtime/handlers/shared/thread-access.ts"],"mappings":";;;;;;AA6BA;;;;;AAEA;;;;;;;;;KAFY,gBAAA;AAAA,UAEK,aAAA;;EAEf,MAAA,GAAS,gBAAA;AAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"thread-access.d.mts","names":[],"sources":["../../../../src/runtime/handlers/shared/thread-access.ts"],"mappings":";;;;;;AA4BA;;;;;AAEA;;;;;;;;;KAFY,gBAAA;AAAA,UAEK,aAAA;;EAEf,MAAA,GAAS,gBAAA;AAAA"}
1
+ {"version":3,"file":"thread-access.d.mts","names":[],"sources":["../../../../src/runtime/handlers/shared/thread-access.ts"],"mappings":";;;;;;AA6BA;;;;;AAEA;;;;;;;;;KAFY,gBAAA;AAAA,UAEK,aAAA;;EAEf,MAAA,GAAS,gBAAA;AAAA"}
@@ -1,3 +1,4 @@
1
+ import { getRuntimeLogger } from "../../core/logger.mjs";
1
2
  import { enforcesThreadOwnership, supportsLocalThreadEndpoints } from "../../runner/agent-runner.mjs";
2
3
  import { errorResponse } from "./json-response.mjs";
3
4
  import { hasIdentifyUser, resolveIntelligenceUser } from "./resolve-intelligence-user.mjs";
@@ -50,7 +51,7 @@ function threadOwnershipUnsupportedMessage(runner) {
50
51
  * does not enforce thread ownership. Requests then fail with the same message.
51
52
  */
52
53
  function warnIfThreadOwnershipUnenforced(runtime) {
53
- if (hasIdentifyUser(runtime) && !enforcesThreadOwnership(runtime.runner)) console.warn(`[CopilotKit] ${threadOwnershipUnsupportedMessage(runtime.runner)}`);
54
+ if (hasIdentifyUser(runtime) && !enforcesThreadOwnership(runtime.runner)) getRuntimeLogger(runtime).warn(`[CopilotKit] ${threadOwnershipUnsupportedMessage(runtime.runner)}`);
54
55
  }
55
56
  /**
56
57
  * The access mode `threads` selects. Throws on anything but an object whose
@@ -76,7 +77,7 @@ function warnIfThreadListRefused(runtime) {
76
77
  if (!supportsLocalThreadEndpoints(runtime.runner)) return;
77
78
  if (isThreadOperationAvailable(runtime, "list")) return;
78
79
  threadListRefusalWarned = true;
79
- console.warn(`[CopilotKit] ${THREAD_ACCESS_NOT_CONFIGURED_MESSAGE} Until then, GET /threads and POST /threads/clear return HTTP 403.`);
80
+ getRuntimeLogger(runtime).warn(`[CopilotKit] ${THREAD_ACCESS_NOT_CONFIGURED_MESSAGE} Until then, GET /threads and POST /threads/clear return HTTP 403.`);
80
81
  }
81
82
  /**
82
83
  * True when `operation` can serve requests on this runtime at all: always
@@ -1 +1 @@
1
- {"version":3,"file":"thread-access.mjs","names":[],"sources":["../../../../src/runtime/handlers/shared/thread-access.ts"],"sourcesContent":["import type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport type { AgentRunner } from \"../../runner/agent-runner\";\nimport {\n enforcesThreadOwnership,\n supportsLocalThreadEndpoints,\n} from \"../../runner/agent-runner\";\nimport { errorResponse } from \"./json-response\";\nimport {\n hasIdentifyUser,\n resolveIntelligenceUser,\n} from \"./resolve-intelligence-user\";\n\n/**\n * How local (non-Intelligence) Threads are shared among callers that\n * `identifyUser` does not identify. The full policy is\n * {@link ANONYMOUS_THREAD_ACCESS}.\n *\n * - `\"owner\"` (default): a Thread created without identity is a capability.\n * Whoever holds its id may read, connect to, continue and stop it, but\n * nobody may list or bulk-clear such Threads.\n * - `\"open\"`: every caller without identity shares those Threads, list and\n * clear included, as in earlier releases. Insecure for any deployment that\n * more than one person can reach.\n *\n * Neither mode loosens identity: with `identifyUser`, every operation reaches\n * only the caller's own Threads, and a Thread that an identified user created\n * is never reachable by an anonymous caller or another identity.\n */\nexport type ThreadAccessMode = \"owner\" | \"open\";\n\nexport interface ThreadsConfig {\n /** @default \"owner\" */\n access?: ThreadAccessMode;\n}\n\n/** The one place that sets the default Thread access mode. */\nexport const DEFAULT_THREAD_ACCESS: ThreadAccessMode = \"owner\";\n\n/** Owner id of a Thread created without identity. */\nexport const ANONYMOUS_THREAD_OWNER = \"\";\n\n/**\n * Every operation on a local Thread. `read` covers\n * `/threads/:id/{messages,events,state}`; `stop` covers a stop by Thread and a\n * stop by run id. `isRunning` has no route; runners check it the same way.\n */\nexport type ThreadOperation =\n | \"list\"\n | \"clear\"\n | \"read\"\n | \"connect\"\n | \"run\"\n | \"stop\"\n | \"isRunning\";\n\n/**\n * THE anonymous-Thread policy: which operations a caller without identity\n * (no `identifyUser`) may perform, per access mode. Every such operation\n * still reaches only anonymous Threads, never a Thread an identified user\n * owns. To tighten the default, change the `owner` row; nothing else encodes\n * this policy.\n *\n * Callers identified by `identifyUser` are not in this table: every operation\n * is allowed and reaches only their own Threads.\n */\nexport const ANONYMOUS_THREAD_ACCESS: Readonly<\n Record<ThreadAccessMode, Readonly<Record<ThreadOperation, boolean>>>\n> = {\n // A Thread id works as a capability for the Thread it names. Enumerating or\n // wiping every anonymous Thread needs identity or an explicit opt-in.\n owner: {\n list: false,\n clear: false,\n read: true,\n connect: true,\n run: true,\n stop: true,\n isRunning: true,\n },\n open: {\n list: true,\n clear: true,\n read: true,\n connect: true,\n run: true,\n stop: true,\n isRunning: true,\n },\n};\n\nexport const THREAD_ACCESS_NOT_CONFIGURED_MESSAGE =\n \"Listing and clearing threads need a caller identity. Pass `identifyUser: (request) => ({ id, name })` \" +\n \"to CopilotRuntime so each user lists and clears only their own threads, or pass \" +\n '`threads: { access: \"open\" }` to let every caller share threads created without identity ' +\n \"(insecure for multi-user deployments).\";\n\n/**\n * The configuration error for `identifyUser` with a runner that cannot keep\n * users apart. Every Thread operation is refused rather than served unscoped.\n */\nexport function threadOwnershipUnsupportedMessage(runner: AgentRunner): string {\n const name = runner.constructor?.name || \"the configured runner\";\n return (\n `identifyUser is set, but the runner ${name} does not enforce thread ownership: ` +\n \"it has no isThreadAccessible method. Thread routes, run, connect and stop are refused \" +\n \"so that no user can reach another user's threads. Use InMemoryAgentRunner or \" +\n \"SqliteAgentRunner, or implement isThreadAccessible and honor ownerId in run, connect, \" +\n \"stop and isRunning.\"\n );\n}\n\n/**\n * Log once, at runtime construction, when `identifyUser` is set but the runner\n * does not enforce thread ownership. Requests then fail with the same message.\n */\nexport function warnIfThreadOwnershipUnenforced(\n runtime: CopilotRuntimeLike,\n): void {\n if (hasIdentifyUser(runtime) && !enforcesThreadOwnership(runtime.runner)) {\n console.warn(\n `[CopilotKit] ${threadOwnershipUnsupportedMessage(runtime.runner)}`,\n );\n }\n}\n\n/**\n * The access mode `threads` selects. Throws on anything but an object whose\n * `access` is `\"owner\"`, `\"open\"` or omitted: a typo must not silently fall\n * back to the default.\n */\nexport function resolveThreadAccessMode(\n config: ThreadsConfig | undefined,\n): ThreadAccessMode {\n if (config === undefined) return DEFAULT_THREAD_ACCESS;\n if (typeof config !== \"object\" || config === null) {\n throw new Error(\n '`threads` must be an object, such as `{ access: \"owner\" }`; got ' +\n JSON.stringify(config),\n );\n }\n const access: unknown = config.access;\n if (access === undefined) return DEFAULT_THREAD_ACCESS;\n if (access !== \"owner\" && access !== \"open\") {\n throw new Error(\n `threads.access must be \"owner\" or \"open\"; got ${JSON.stringify(access)}`,\n );\n }\n return access;\n}\n\nlet threadListRefusalWarned = false;\n\n/** Re-arm the once-per-process startup warnings. Internal: for tests. */\nexport function ɵresetThreadAccessWarnings(): void {\n threadListRefusalWarned = false;\n}\n\n/**\n * Log once per process, at runtime construction, when the configuration\n * refuses the Thread list and clear routes, so operators see why those\n * requests get 403.\n */\nexport function warnIfThreadListRefused(runtime: CopilotRuntimeLike): void {\n if (threadListRefusalWarned) return;\n if (!supportsLocalThreadEndpoints(runtime.runner)) return;\n if (isThreadOperationAvailable(runtime, \"list\")) return;\n threadListRefusalWarned = true;\n console.warn(\n `[CopilotKit] ${THREAD_ACCESS_NOT_CONFIGURED_MESSAGE} Until then, ` +\n \"GET /threads and POST /threads/clear return HTTP 403.\",\n );\n}\n\n/**\n * True when `operation` can serve requests on this runtime at all: always\n * with `identifyUser` (scoped to the caller), otherwise per\n * {@link ANONYMOUS_THREAD_ACCESS}.\n */\nexport function isThreadOperationAvailable(\n runtime: CopilotRuntimeLike,\n operation: ThreadOperation,\n): boolean {\n // The same identity test as resolveLocalThreadOwner, so a non-function\n // value is no identity everywhere and never opens list or clear.\n if (hasIdentifyUser(runtime)) {\n return enforcesThreadOwnership(runtime.runner);\n }\n return ANONYMOUS_THREAD_ACCESS[runtime.threadAccess ?? DEFAULT_THREAD_ACCESS][\n operation\n ];\n}\n\n/**\n * Resolves the owner id that a local Thread request acts as, or the error\n * Response that refuses it. Every local Thread handler goes through here.\n *\n * - With `identifyUser`: the identified user's id. Refused when the runner\n * cannot enforce owners, or when identification fails.\n * - Without it: the anonymous owner, when {@link ANONYMOUS_THREAD_ACCESS}\n * allows `operation` in the configured mode; otherwise a 403 that names the\n * options to set.\n */\nexport async function resolveLocalThreadOwner(params: {\n runtime: CopilotRuntimeLike;\n request: Request;\n operation: ThreadOperation;\n}): Promise<string | Response> {\n const { runtime, request, operation } = params;\n if (hasIdentifyUser(runtime)) {\n // Never serve an identified request through a runner that cannot keep\n // users apart: refuse it with the configuration error instead.\n if (!enforcesThreadOwnership(runtime.runner)) {\n return Response.json(\n {\n error: \"thread_ownership_unsupported\",\n message: threadOwnershipUnsupportedMessage(runtime.runner),\n },\n { status: 500 },\n );\n }\n const user = await resolveIntelligenceUser({ runtime, request });\n return user instanceof Response ? user : user.id;\n }\n if (!isThreadOperationAvailable(runtime, operation)) {\n return Response.json(\n {\n error: \"thread_access_not_configured\",\n message: THREAD_ACCESS_NOT_CONFIGURED_MESSAGE,\n },\n { status: 403 },\n );\n }\n return ANONYMOUS_THREAD_OWNER;\n}\n\n/**\n * The response to a run on a Thread that another identity owns, whether the\n * handler's check or the runner refused it. It is the same 404 and body as an\n * unknown Thread on the inspect routes, so it does not say that the Thread\n * belongs to someone. A run on an unknown Thread id creates the Thread, so a\n * refusal still shows that the id is taken; it never shows by whom.\n */\nexport function threadAccessDeniedResponse(): Response {\n return errorResponse(\"Thread not found\", 404);\n}\n"],"mappings":";;;;;;AAoCA,MAAa,wBAA0C;;AAGvD,MAAa,yBAAyB;;;;;;;;;;;AA0BtC,MAAa,0BAET;CAGF,OAAO;EACL,MAAM;EACN,OAAO;EACP,MAAM;EACN,SAAS;EACT,KAAK;EACL,MAAM;EACN,WAAW;EACZ;CACD,MAAM;EACJ,MAAM;EACN,OAAO;EACP,MAAM;EACN,SAAS;EACT,KAAK;EACL,MAAM;EACN,WAAW;EACZ;CACF;AAED,MAAa,uCACX;;;;;AASF,SAAgB,kCAAkC,QAA6B;AAE7E,QACE,uCAFW,OAAO,aAAa,QAAQ,wBAEK;;;;;;AAYhD,SAAgB,gCACd,SACM;AACN,KAAI,gBAAgB,QAAQ,IAAI,CAAC,wBAAwB,QAAQ,OAAO,CACtE,SAAQ,KACN,gBAAgB,kCAAkC,QAAQ,OAAO,GAClE;;;;;;;AASL,SAAgB,wBACd,QACkB;AAClB,KAAI,WAAW,OAAW,QAAO;AACjC,KAAI,OAAO,WAAW,YAAY,WAAW,KAC3C,OAAM,IAAI,MACR,uEACE,KAAK,UAAU,OAAO,CACzB;CAEH,MAAM,SAAkB,OAAO;AAC/B,KAAI,WAAW,OAAW,QAAO;AACjC,KAAI,WAAW,WAAW,WAAW,OACnC,OAAM,IAAI,MACR,iDAAiD,KAAK,UAAU,OAAO,GACxE;AAEH,QAAO;;AAGT,IAAI,0BAA0B;;;;;;AAY9B,SAAgB,wBAAwB,SAAmC;AACzE,KAAI,wBAAyB;AAC7B,KAAI,CAAC,6BAA6B,QAAQ,OAAO,CAAE;AACnD,KAAI,2BAA2B,SAAS,OAAO,CAAE;AACjD,2BAA0B;AAC1B,SAAQ,KACN,gBAAgB,qCAAqC,oEAEtD;;;;;;;AAQH,SAAgB,2BACd,SACA,WACS;AAGT,KAAI,gBAAgB,QAAQ,CAC1B,QAAO,wBAAwB,QAAQ,OAAO;AAEhD,QAAO,wBAAwB,QAAQ,gBAAgB,uBACrD;;;;;;;;;;;;AAcJ,eAAsB,wBAAwB,QAIf;CAC7B,MAAM,EAAE,SAAS,SAAS,cAAc;AACxC,KAAI,gBAAgB,QAAQ,EAAE;AAG5B,MAAI,CAAC,wBAAwB,QAAQ,OAAO,CAC1C,QAAO,SAAS,KACd;GACE,OAAO;GACP,SAAS,kCAAkC,QAAQ,OAAO;GAC3D,EACD,EAAE,QAAQ,KAAK,CAChB;EAEH,MAAM,OAAO,MAAM,wBAAwB;GAAE;GAAS;GAAS,CAAC;AAChE,SAAO,gBAAgB,WAAW,OAAO,KAAK;;AAEhD,KAAI,CAAC,2BAA2B,SAAS,UAAU,CACjD,QAAO,SAAS,KACd;EACE,OAAO;EACP,SAAS;EACV,EACD,EAAE,QAAQ,KAAK,CAChB;AAEH,QAAO;;;;;;;;;AAUT,SAAgB,6BAAuC;AACrD,QAAO,cAAc,oBAAoB,IAAI"}
1
+ {"version":3,"file":"thread-access.mjs","names":[],"sources":["../../../../src/runtime/handlers/shared/thread-access.ts"],"sourcesContent":["import { getRuntimeLogger } from \"../../core/logger\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport type { AgentRunner } from \"../../runner/agent-runner\";\nimport {\n enforcesThreadOwnership,\n supportsLocalThreadEndpoints,\n} from \"../../runner/agent-runner\";\nimport { errorResponse } from \"./json-response\";\nimport {\n hasIdentifyUser,\n resolveIntelligenceUser,\n} from \"./resolve-intelligence-user\";\n\n/**\n * How local (non-Intelligence) Threads are shared among callers that\n * `identifyUser` does not identify. The full policy is\n * {@link ANONYMOUS_THREAD_ACCESS}.\n *\n * - `\"owner\"` (default): a Thread created without identity is a capability.\n * Whoever holds its id may read, connect to, continue and stop it, but\n * nobody may list or bulk-clear such Threads.\n * - `\"open\"`: every caller without identity shares those Threads, list and\n * clear included, as in earlier releases. Insecure for any deployment that\n * more than one person can reach.\n *\n * Neither mode loosens identity: with `identifyUser`, every operation reaches\n * only the caller's own Threads, and a Thread that an identified user created\n * is never reachable by an anonymous caller or another identity.\n */\nexport type ThreadAccessMode = \"owner\" | \"open\";\n\nexport interface ThreadsConfig {\n /** @default \"owner\" */\n access?: ThreadAccessMode;\n}\n\n/** The one place that sets the default Thread access mode. */\nexport const DEFAULT_THREAD_ACCESS: ThreadAccessMode = \"owner\";\n\n/** Owner id of a Thread created without identity. */\nexport const ANONYMOUS_THREAD_OWNER = \"\";\n\n/**\n * Every operation on a local Thread. `read` covers\n * `/threads/:id/{messages,events,state}`; `stop` covers a stop by Thread and a\n * stop by run id. `isRunning` has no route; runners check it the same way.\n */\nexport type ThreadOperation =\n | \"list\"\n | \"clear\"\n | \"read\"\n | \"connect\"\n | \"run\"\n | \"stop\"\n | \"isRunning\";\n\n/**\n * THE anonymous-Thread policy: which operations a caller without identity\n * (no `identifyUser`) may perform, per access mode. Every such operation\n * still reaches only anonymous Threads, never a Thread an identified user\n * owns. To tighten the default, change the `owner` row; nothing else encodes\n * this policy.\n *\n * Callers identified by `identifyUser` are not in this table: every operation\n * is allowed and reaches only their own Threads.\n */\nexport const ANONYMOUS_THREAD_ACCESS: Readonly<\n Record<ThreadAccessMode, Readonly<Record<ThreadOperation, boolean>>>\n> = {\n // A Thread id works as a capability for the Thread it names. Enumerating or\n // wiping every anonymous Thread needs identity or an explicit opt-in.\n owner: {\n list: false,\n clear: false,\n read: true,\n connect: true,\n run: true,\n stop: true,\n isRunning: true,\n },\n open: {\n list: true,\n clear: true,\n read: true,\n connect: true,\n run: true,\n stop: true,\n isRunning: true,\n },\n};\n\nexport const THREAD_ACCESS_NOT_CONFIGURED_MESSAGE =\n \"Listing and clearing threads need a caller identity. Pass `identifyUser: (request) => ({ id, name })` \" +\n \"to CopilotRuntime so each user lists and clears only their own threads, or pass \" +\n '`threads: { access: \"open\" }` to let every caller share threads created without identity ' +\n \"(insecure for multi-user deployments).\";\n\n/**\n * The configuration error for `identifyUser` with a runner that cannot keep\n * users apart. Every Thread operation is refused rather than served unscoped.\n */\nexport function threadOwnershipUnsupportedMessage(runner: AgentRunner): string {\n const name = runner.constructor?.name || \"the configured runner\";\n return (\n `identifyUser is set, but the runner ${name} does not enforce thread ownership: ` +\n \"it has no isThreadAccessible method. Thread routes, run, connect and stop are refused \" +\n \"so that no user can reach another user's threads. Use InMemoryAgentRunner or \" +\n \"SqliteAgentRunner, or implement isThreadAccessible and honor ownerId in run, connect, \" +\n \"stop and isRunning.\"\n );\n}\n\n/**\n * Log once, at runtime construction, when `identifyUser` is set but the runner\n * does not enforce thread ownership. Requests then fail with the same message.\n */\nexport function warnIfThreadOwnershipUnenforced(\n runtime: CopilotRuntimeLike,\n): void {\n if (hasIdentifyUser(runtime) && !enforcesThreadOwnership(runtime.runner)) {\n getRuntimeLogger(runtime).warn(\n `[CopilotKit] ${threadOwnershipUnsupportedMessage(runtime.runner)}`,\n );\n }\n}\n\n/**\n * The access mode `threads` selects. Throws on anything but an object whose\n * `access` is `\"owner\"`, `\"open\"` or omitted: a typo must not silently fall\n * back to the default.\n */\nexport function resolveThreadAccessMode(\n config: ThreadsConfig | undefined,\n): ThreadAccessMode {\n if (config === undefined) return DEFAULT_THREAD_ACCESS;\n if (typeof config !== \"object\" || config === null) {\n throw new Error(\n '`threads` must be an object, such as `{ access: \"owner\" }`; got ' +\n JSON.stringify(config),\n );\n }\n const access: unknown = config.access;\n if (access === undefined) return DEFAULT_THREAD_ACCESS;\n if (access !== \"owner\" && access !== \"open\") {\n throw new Error(\n `threads.access must be \"owner\" or \"open\"; got ${JSON.stringify(access)}`,\n );\n }\n return access;\n}\n\nlet threadListRefusalWarned = false;\n\n/** Re-arm the once-per-process startup warnings. Internal: for tests. */\nexport function ɵresetThreadAccessWarnings(): void {\n threadListRefusalWarned = false;\n}\n\n/**\n * Log once per process, at runtime construction, when the configuration\n * refuses the Thread list and clear routes, so operators see why those\n * requests get 403.\n */\nexport function warnIfThreadListRefused(runtime: CopilotRuntimeLike): void {\n if (threadListRefusalWarned) return;\n if (!supportsLocalThreadEndpoints(runtime.runner)) return;\n if (isThreadOperationAvailable(runtime, \"list\")) return;\n threadListRefusalWarned = true;\n getRuntimeLogger(runtime).warn(\n `[CopilotKit] ${THREAD_ACCESS_NOT_CONFIGURED_MESSAGE} Until then, ` +\n \"GET /threads and POST /threads/clear return HTTP 403.\",\n );\n}\n\n/**\n * True when `operation` can serve requests on this runtime at all: always\n * with `identifyUser` (scoped to the caller), otherwise per\n * {@link ANONYMOUS_THREAD_ACCESS}.\n */\nexport function isThreadOperationAvailable(\n runtime: CopilotRuntimeLike,\n operation: ThreadOperation,\n): boolean {\n // The same identity test as resolveLocalThreadOwner, so a non-function\n // value is no identity everywhere and never opens list or clear.\n if (hasIdentifyUser(runtime)) {\n return enforcesThreadOwnership(runtime.runner);\n }\n return ANONYMOUS_THREAD_ACCESS[runtime.threadAccess ?? DEFAULT_THREAD_ACCESS][\n operation\n ];\n}\n\n/**\n * Resolves the owner id that a local Thread request acts as, or the error\n * Response that refuses it. Every local Thread handler goes through here.\n *\n * - With `identifyUser`: the identified user's id. Refused when the runner\n * cannot enforce owners, or when identification fails.\n * - Without it: the anonymous owner, when {@link ANONYMOUS_THREAD_ACCESS}\n * allows `operation` in the configured mode; otherwise a 403 that names the\n * options to set.\n */\nexport async function resolveLocalThreadOwner(params: {\n runtime: CopilotRuntimeLike;\n request: Request;\n operation: ThreadOperation;\n}): Promise<string | Response> {\n const { runtime, request, operation } = params;\n if (hasIdentifyUser(runtime)) {\n // Never serve an identified request through a runner that cannot keep\n // users apart: refuse it with the configuration error instead.\n if (!enforcesThreadOwnership(runtime.runner)) {\n return Response.json(\n {\n error: \"thread_ownership_unsupported\",\n message: threadOwnershipUnsupportedMessage(runtime.runner),\n },\n { status: 500 },\n );\n }\n const user = await resolveIntelligenceUser({ runtime, request });\n return user instanceof Response ? user : user.id;\n }\n if (!isThreadOperationAvailable(runtime, operation)) {\n return Response.json(\n {\n error: \"thread_access_not_configured\",\n message: THREAD_ACCESS_NOT_CONFIGURED_MESSAGE,\n },\n { status: 403 },\n );\n }\n return ANONYMOUS_THREAD_OWNER;\n}\n\n/**\n * The response to a run on a Thread that another identity owns, whether the\n * handler's check or the runner refused it. It is the same 404 and body as an\n * unknown Thread on the inspect routes, so it does not say that the Thread\n * belongs to someone. A run on an unknown Thread id creates the Thread, so a\n * refusal still shows that the id is taken; it never shows by whom.\n */\nexport function threadAccessDeniedResponse(): Response {\n return errorResponse(\"Thread not found\", 404);\n}\n"],"mappings":";;;;;;;AAqCA,MAAa,wBAA0C;;AAGvD,MAAa,yBAAyB;;;;;;;;;;;AA0BtC,MAAa,0BAET;CAGF,OAAO;EACL,MAAM;EACN,OAAO;EACP,MAAM;EACN,SAAS;EACT,KAAK;EACL,MAAM;EACN,WAAW;EACZ;CACD,MAAM;EACJ,MAAM;EACN,OAAO;EACP,MAAM;EACN,SAAS;EACT,KAAK;EACL,MAAM;EACN,WAAW;EACZ;CACF;AAED,MAAa,uCACX;;;;;AASF,SAAgB,kCAAkC,QAA6B;AAE7E,QACE,uCAFW,OAAO,aAAa,QAAQ,wBAEK;;;;;;AAYhD,S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D,QAAO,SAAS,KACd;EACE,OAAO;EACP,SAAS;EACV,EACD,EAAE,QAAQ,KAAK,CAChB;AAEH,QAAO;;;;;;;;;AAUT,SAAgB,6BAAuC;AACrD,QAAO,cAAc,oBAAoB,IAAI"}
@@ -1,4 +1,5 @@
1
1
  const require_header_utils = require('../header-utils.cjs');
2
+ const require_logger = require('../../core/logger.cjs');
2
3
  const require_sse_response = require('../shared/sse-response.cjs');
3
4
 
4
5
  //#region src/runtime/handlers/sse/connect.ts
@@ -8,6 +9,7 @@ function handleSseConnect({ runtime, request, agentId, threadId, agent, ownerId
8
9
  debugEventBus: runtime.debugEventBus,
9
10
  agentId,
10
11
  telemetry: runtime.telemetry,
12
+ logger: require_logger.getRuntimeLogger(runtime),
11
13
  keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,
12
14
  observableFactory: () => runtime.runner.connect({
13
15
  threadId,
@@ -1 +1 @@
1
- {"version":3,"file":"connect.cjs","names":["createSseEventResponse","mergeForwardableHeaders","resolveForwardHeadersPolicy"],"sources":["../../../../src/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 /** Caller identity; the runner hides threads owned by anyone else. */\n ownerId?: string;\n}\n\nexport function handleSseConnect({\n runtime,\n request,\n agentId,\n threadId,\n agent,\n ownerId,\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 ...(ownerId === undefined ? {} : { ownerId }),\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) ignores it.\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":";;;;AAkCA,SAAgB,iBAAiB,EAC/B,SACA,SACA,SACA,UACA,OACA,WACmC;AACnC,QAAOA,4CAAuB;EAC5B;EACA,eAAe,QAAQ;EAGvB;EACA,WAAW,QAAQ;EACnB,0BAA0B,QAAQ;EAClC,yBACE,QAAQ,OAAO,QAAQ;GACrB;GACA;GACA,GAAI,YAAY,SAAY,EAAE,GAAG,EAAE,SAAS;GAa5C,SAASC,6CACP,OAAO,SACP,SAIA,QAAQ,wBACNC,iDAA4B,OAAU,CACzC;GACF,CAAC;EACL,CAAC"}
1
+ {"version":3,"file":"connect.cjs","names":["createSseEventResponse","getRuntimeLogger","mergeForwardableHeaders","resolveForwardHeadersPolicy"],"sources":["../../../../src/runtime/handlers/sse/connect.ts"],"sourcesContent":["import type { AbstractAgent } from \"@ag-ui/client\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { getRuntimeLogger } from \"../../core/logger\";\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 /** Caller identity; the runner hides threads owned by anyone else. */\n ownerId?: string;\n}\n\nexport function handleSseConnect({\n runtime,\n request,\n agentId,\n threadId,\n agent,\n ownerId,\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 logger: getRuntimeLogger(runtime),\n keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,\n observableFactory: () =>\n runtime.runner.connect({\n threadId,\n agentId,\n ...(ownerId === undefined ? {} : { ownerId }),\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) ignores it.\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":";;;;;AAmCA,SAAgB,iBAAiB,EAC/B,SACA,SACA,SACA,UACA,OACA,WACmC;AACnC,QAAOA,4CAAuB;EAC5B;EACA,eAAe,QAAQ;EAGvB;EACA,WAAW,QAAQ;EACnB,QAAQC,gCAAiB,QAAQ;EACjC,0BAA0B,QAAQ;EAClC,yBACE,QAAQ,OAAO,QAAQ;GACrB;GACA;GACA,GAAI,YAAY,SAAY,EAAE,GAAG,EAAE,SAAS;GAa5C,SAASC,6CACP,OAAO,SACP,SAIA,QAAQ,wBACNC,iDAA4B,OAAU,CACzC;GACF,CAAC;EACL,CAAC"}
@@ -1,4 +1,5 @@
1
1
  import { mergeForwardableHeaders, resolveForwardHeadersPolicy } from "../header-utils.mjs";
2
+ import { getRuntimeLogger } from "../../core/logger.mjs";
2
3
  import { createSseEventResponse } from "../shared/sse-response.mjs";
3
4
 
4
5
  //#region src/runtime/handlers/sse/connect.ts
@@ -8,6 +9,7 @@ function handleSseConnect({ runtime, request, agentId, threadId, agent, ownerId
8
9
  debugEventBus: runtime.debugEventBus,
9
10
  agentId,
10
11
  telemetry: runtime.telemetry,
12
+ logger: getRuntimeLogger(runtime),
11
13
  keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,
12
14
  observableFactory: () => runtime.runner.connect({
13
15
  threadId,
@@ -1 +1 @@
1
- {"version":3,"file":"connect.mjs","names":[],"sources":["../../../../src/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 /** Caller identity; the runner hides threads owned by anyone else. */\n ownerId?: string;\n}\n\nexport function handleSseConnect({\n runtime,\n request,\n agentId,\n threadId,\n agent,\n ownerId,\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 ...(ownerId === undefined ? {} : { ownerId }),\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) ignores it.\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":";;;;AAkCA,SAAgB,iBAAiB,EAC/B,SACA,SACA,SACA,UACA,OACA,WACmC;AACnC,QAAO,uBAAuB;EAC5B;EACA,eAAe,QAAQ;EAGvB;EACA,WAAW,QAAQ;EACnB,0BAA0B,QAAQ;EAClC,yBACE,QAAQ,OAAO,QAAQ;GACrB;GACA;GACA,GAAI,YAAY,SAAY,EAAE,GAAG,EAAE,SAAS;GAa5C,SAAS,wBACP,OAAO,SACP,SAIA,QAAQ,wBACN,4BAA4B,OAAU,CACzC;GACF,CAAC;EACL,CAAC"}
1
+ {"version":3,"file":"connect.mjs","names":[],"sources":["../../../../src/runtime/handlers/sse/connect.ts"],"sourcesContent":["import type { AbstractAgent } from \"@ag-ui/client\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { getRuntimeLogger } from \"../../core/logger\";\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 /** Caller identity; the runner hides threads owned by anyone else. */\n ownerId?: string;\n}\n\nexport function handleSseConnect({\n runtime,\n request,\n agentId,\n threadId,\n agent,\n ownerId,\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 logger: getRuntimeLogger(runtime),\n keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,\n observableFactory: () =>\n runtime.runner.connect({\n threadId,\n agentId,\n ...(ownerId === undefined ? {} : { ownerId }),\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) ignores it.\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":";;;;;AAmCA,SAAgB,iBAAiB,EAC/B,SACA,SACA,SACA,UACA,OACA,WACmC;AACnC,QAAO,uBAAuB;EAC5B;EACA,eAAe,QAAQ;EAGvB;EACA,WAAW,QAAQ;EACnB,QAAQ,iBAAiB,QAAQ;EACjC,0BAA0B,QAAQ;EAClC,yBACE,QAAQ,OAAO,QAAQ;GACrB;GACA;GACA,GAAI,YAAY,SAAY,EAAE,GAAG,EAAE,SAAS;GAa5C,SAAS,wBACP,OAAO,SACP,SAIA,QAAQ,wBACN,4BAA4B,OAAU,CACzC;GACF,CAAC;EACL,CAAC"}