@copilotkit/runtime 1.56.2 → 1.56.4-canary.1777529757

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 (203) hide show
  1. package/dist/agent/converters/tanstack.cjs +121 -25
  2. package/dist/agent/converters/tanstack.cjs.map +1 -1
  3. package/dist/agent/converters/tanstack.d.cts.map +1 -1
  4. package/dist/agent/converters/tanstack.d.mts.map +1 -1
  5. package/dist/agent/converters/tanstack.mjs +121 -25
  6. package/dist/agent/converters/tanstack.mjs.map +1 -1
  7. package/dist/graphql/resolvers/copilot.resolver.cjs +2 -1
  8. package/dist/graphql/resolvers/copilot.resolver.cjs.map +1 -1
  9. package/dist/graphql/resolvers/copilot.resolver.mjs +2 -1
  10. package/dist/graphql/resolvers/copilot.resolver.mjs.map +1 -1
  11. package/dist/graphql/resolvers/resolve-message-id.cjs +19 -0
  12. package/dist/graphql/resolvers/resolve-message-id.cjs.map +1 -0
  13. package/dist/graphql/resolvers/resolve-message-id.mjs +18 -0
  14. package/dist/graphql/resolvers/resolve-message-id.mjs.map +1 -0
  15. package/dist/lib/runtime/agent-integrations/langgraph/agent.cjs +8 -1
  16. package/dist/lib/runtime/agent-integrations/langgraph/agent.cjs.map +1 -1
  17. package/dist/lib/runtime/agent-integrations/langgraph/agent.d.cts.map +1 -1
  18. package/dist/lib/runtime/agent-integrations/langgraph/agent.d.mts.map +1 -1
  19. package/dist/lib/runtime/agent-integrations/langgraph/agent.mjs +8 -1
  20. package/dist/lib/runtime/agent-integrations/langgraph/agent.mjs.map +1 -1
  21. package/dist/lib/runtime/copilot-runtime.cjs +4 -2
  22. package/dist/lib/runtime/copilot-runtime.cjs.map +1 -1
  23. package/dist/lib/runtime/copilot-runtime.d.cts.map +1 -1
  24. package/dist/lib/runtime/copilot-runtime.d.mts.map +1 -1
  25. package/dist/lib/runtime/copilot-runtime.mjs +4 -2
  26. package/dist/lib/runtime/copilot-runtime.mjs.map +1 -1
  27. package/dist/package.cjs +7 -7
  28. package/dist/package.mjs +7 -7
  29. package/dist/v2/index.d.cts +2 -2
  30. package/dist/v2/index.d.mts +2 -2
  31. package/dist/v2/runtime/core/debug-event-bus.cjs +36 -0
  32. package/dist/v2/runtime/core/debug-event-bus.cjs.map +1 -0
  33. package/dist/v2/runtime/core/debug-event-bus.d.cts +19 -0
  34. package/dist/v2/runtime/core/debug-event-bus.d.cts.map +1 -0
  35. package/dist/v2/runtime/core/debug-event-bus.d.mts +19 -0
  36. package/dist/v2/runtime/core/debug-event-bus.d.mts.map +1 -0
  37. package/dist/v2/runtime/core/debug-event-bus.mjs +35 -0
  38. package/dist/v2/runtime/core/debug-event-bus.mjs.map +1 -0
  39. package/dist/v2/runtime/core/fetch-handler.cjs +8 -0
  40. package/dist/v2/runtime/core/fetch-handler.cjs.map +1 -1
  41. package/dist/v2/runtime/core/fetch-handler.d.cts.map +1 -1
  42. package/dist/v2/runtime/core/fetch-handler.d.mts.map +1 -1
  43. package/dist/v2/runtime/core/fetch-handler.mjs +8 -0
  44. package/dist/v2/runtime/core/fetch-handler.mjs.map +1 -1
  45. package/dist/v2/runtime/core/fetch-router.cjs +1 -0
  46. package/dist/v2/runtime/core/fetch-router.cjs.map +1 -1
  47. package/dist/v2/runtime/core/fetch-router.mjs +1 -0
  48. package/dist/v2/runtime/core/fetch-router.mjs.map +1 -1
  49. package/dist/v2/runtime/core/hooks.cjs.map +1 -1
  50. package/dist/v2/runtime/core/hooks.d.cts +2 -0
  51. package/dist/v2/runtime/core/hooks.d.cts.map +1 -1
  52. package/dist/v2/runtime/core/hooks.d.mts +2 -0
  53. package/dist/v2/runtime/core/hooks.d.mts.map +1 -1
  54. package/dist/v2/runtime/core/hooks.mjs.map +1 -1
  55. package/dist/v2/runtime/core/runtime.cjs +5 -0
  56. package/dist/v2/runtime/core/runtime.cjs.map +1 -1
  57. package/dist/v2/runtime/core/runtime.d.cts +5 -0
  58. package/dist/v2/runtime/core/runtime.d.cts.map +1 -1
  59. package/dist/v2/runtime/core/runtime.d.mts +5 -1
  60. package/dist/v2/runtime/core/runtime.d.mts.map +1 -1
  61. package/dist/v2/runtime/core/runtime.mjs +5 -0
  62. package/dist/v2/runtime/core/runtime.mjs.map +1 -1
  63. package/dist/v2/runtime/endpoints/express.cjs +5 -5
  64. package/dist/v2/runtime/endpoints/express.cjs.map +1 -1
  65. package/dist/v2/runtime/endpoints/express.mjs +5 -5
  66. package/dist/v2/runtime/endpoints/express.mjs.map +1 -1
  67. package/dist/v2/runtime/handlers/handle-connect.cjs +3 -2
  68. package/dist/v2/runtime/handlers/handle-connect.cjs.map +1 -1
  69. package/dist/v2/runtime/handlers/handle-connect.mjs +3 -2
  70. package/dist/v2/runtime/handlers/handle-connect.mjs.map +1 -1
  71. package/dist/v2/runtime/handlers/handle-debug-events.cjs +33 -0
  72. package/dist/v2/runtime/handlers/handle-debug-events.cjs.map +1 -0
  73. package/dist/v2/runtime/handlers/handle-debug-events.mjs +32 -0
  74. package/dist/v2/runtime/handlers/handle-debug-events.mjs.map +1 -0
  75. package/dist/v2/runtime/handlers/handle-run.cjs +1 -0
  76. package/dist/v2/runtime/handlers/handle-run.cjs.map +1 -1
  77. package/dist/v2/runtime/handlers/handle-run.mjs +1 -0
  78. package/dist/v2/runtime/handlers/handle-run.mjs.map +1 -1
  79. package/dist/v2/runtime/handlers/intelligence/connect.cjs +24 -4
  80. package/dist/v2/runtime/handlers/intelligence/connect.cjs.map +1 -1
  81. package/dist/v2/runtime/handlers/intelligence/connect.mjs +25 -5
  82. package/dist/v2/runtime/handlers/intelligence/connect.mjs.map +1 -1
  83. package/dist/v2/runtime/handlers/intelligence/run.cjs +111 -26
  84. package/dist/v2/runtime/handlers/intelligence/run.cjs.map +1 -1
  85. package/dist/v2/runtime/handlers/intelligence/run.mjs +111 -26
  86. package/dist/v2/runtime/handlers/intelligence/run.mjs.map +1 -1
  87. package/dist/v2/runtime/handlers/shared/intelligence-utils.cjs +7 -3
  88. package/dist/v2/runtime/handlers/shared/intelligence-utils.cjs.map +1 -1
  89. package/dist/v2/runtime/handlers/shared/intelligence-utils.mjs +7 -3
  90. package/dist/v2/runtime/handlers/shared/intelligence-utils.mjs.map +1 -1
  91. package/dist/v2/runtime/handlers/shared/resolve-intelligence-user.cjs +5 -1
  92. package/dist/v2/runtime/handlers/shared/resolve-intelligence-user.cjs.map +1 -1
  93. package/dist/v2/runtime/handlers/shared/resolve-intelligence-user.mjs +5 -1
  94. package/dist/v2/runtime/handlers/shared/resolve-intelligence-user.mjs.map +1 -1
  95. package/dist/v2/runtime/handlers/shared/sse-response.cjs +21 -1
  96. package/dist/v2/runtime/handlers/shared/sse-response.cjs.map +1 -1
  97. package/dist/v2/runtime/handlers/shared/sse-response.mjs +21 -1
  98. package/dist/v2/runtime/handlers/shared/sse-response.mjs.map +1 -1
  99. package/dist/v2/runtime/handlers/sse/connect.cjs +3 -1
  100. package/dist/v2/runtime/handlers/sse/connect.cjs.map +1 -1
  101. package/dist/v2/runtime/handlers/sse/connect.mjs +3 -1
  102. package/dist/v2/runtime/handlers/sse/connect.mjs.map +1 -1
  103. package/dist/v2/runtime/handlers/sse/run.cjs +3 -1
  104. package/dist/v2/runtime/handlers/sse/run.cjs.map +1 -1
  105. package/dist/v2/runtime/handlers/sse/run.mjs +3 -1
  106. package/dist/v2/runtime/handlers/sse/run.mjs.map +1 -1
  107. package/dist/v2/runtime/index.d.cts +1 -1
  108. package/dist/v2/runtime/index.d.mts +1 -2
  109. package/dist/v2/runtime/index.d.mts.map +1 -1
  110. package/dist/v2/runtime/intelligence-platform/client.cjs +6 -8
  111. package/dist/v2/runtime/intelligence-platform/client.cjs.map +1 -1
  112. package/dist/v2/runtime/intelligence-platform/client.d.cts +16 -21
  113. package/dist/v2/runtime/intelligence-platform/client.d.cts.map +1 -1
  114. package/dist/v2/runtime/intelligence-platform/client.d.mts +16 -21
  115. package/dist/v2/runtime/intelligence-platform/client.d.mts.map +1 -1
  116. package/dist/v2/runtime/intelligence-platform/client.mjs +6 -8
  117. package/dist/v2/runtime/intelligence-platform/client.mjs.map +1 -1
  118. package/dist/v2/runtime/runner/agent-runner.cjs.map +1 -1
  119. package/dist/v2/runtime/runner/agent-runner.d.cts +0 -1
  120. package/dist/v2/runtime/runner/agent-runner.d.cts.map +1 -1
  121. package/dist/v2/runtime/runner/agent-runner.d.mts +0 -1
  122. package/dist/v2/runtime/runner/agent-runner.d.mts.map +1 -1
  123. package/dist/v2/runtime/runner/agent-runner.mjs.map +1 -1
  124. package/dist/v2/runtime/runner/index.d.cts +1 -1
  125. package/dist/v2/runtime/runner/index.d.mts +1 -1
  126. package/dist/v2/runtime/runner/intelligence.cjs +47 -10
  127. package/dist/v2/runtime/runner/intelligence.cjs.map +1 -1
  128. package/dist/v2/runtime/runner/intelligence.d.cts +8 -1
  129. package/dist/v2/runtime/runner/intelligence.d.cts.map +1 -1
  130. package/dist/v2/runtime/runner/intelligence.d.mts +8 -1
  131. package/dist/v2/runtime/runner/intelligence.d.mts.map +1 -1
  132. package/dist/v2/runtime/runner/intelligence.mjs +47 -10
  133. package/dist/v2/runtime/runner/intelligence.mjs.map +1 -1
  134. package/dist/v2/runtime/telemetry/instance-created.cjs +33 -0
  135. package/dist/v2/runtime/telemetry/instance-created.cjs.map +1 -0
  136. package/dist/v2/runtime/telemetry/instance-created.mjs +33 -0
  137. package/dist/v2/runtime/telemetry/instance-created.mjs.map +1 -0
  138. package/dist/v2/runtime/telemetry/telemetry-client.cjs +1 -38
  139. package/dist/v2/runtime/telemetry/telemetry-client.cjs.map +1 -1
  140. package/dist/v2/runtime/telemetry/telemetry-client.mjs +1 -37
  141. package/dist/v2/runtime/telemetry/telemetry-client.mjs.map +1 -1
  142. package/package.json +8 -8
  143. package/src/agent/__tests__/agent-test-helpers.ts +31 -1
  144. package/src/agent/__tests__/converter-tanstack.test.ts +280 -0
  145. package/src/agent/converters/tanstack.ts +167 -10
  146. package/src/agents/langgraph/__tests__/event-source.test.ts +256 -0
  147. package/src/graphql/resolvers/__tests__/resolve-message-id.test.ts +25 -0
  148. package/src/graphql/resolvers/copilot.resolver.ts +2 -1
  149. package/src/graphql/resolvers/resolve-message-id.ts +14 -0
  150. package/src/lib/runtime/__tests__/handle-service-adapter.test.ts +108 -0
  151. package/src/lib/runtime/__tests__/retry-utils.test.ts +137 -0
  152. package/src/lib/runtime/agent-integrations/langgraph/__tests__/dispatch-event-filtering.test.ts +190 -0
  153. package/src/lib/runtime/agent-integrations/langgraph/agent.ts +8 -1
  154. package/src/lib/runtime/copilot-runtime.ts +20 -4
  155. package/src/lib/runtime/retry-utils.ts +41 -1
  156. package/src/v2/runtime/__tests__/express-fetch-bridge.test.ts +1 -1
  157. package/src/v2/runtime/__tests__/express-single-telemetry.integration.test.ts +65 -0
  158. package/src/v2/runtime/__tests__/express-telemetry.integration.test.ts +101 -0
  159. package/src/v2/runtime/__tests__/fetch-router.test.ts +22 -0
  160. package/src/v2/runtime/__tests__/handle-connect.test.ts +183 -23
  161. package/src/v2/runtime/__tests__/handle-run.test.ts +411 -33
  162. package/src/v2/runtime/__tests__/handle-threads.test.ts +66 -4
  163. package/src/v2/runtime/__tests__/hono-single-telemetry.integration.test.ts +46 -0
  164. package/src/v2/runtime/__tests__/hono-telemetry.integration.test.ts +99 -0
  165. package/src/v2/runtime/__tests__/integration/node-servers.integration.test.ts +19 -0
  166. package/src/v2/runtime/__tests__/integration/suites/debug-events.suite.ts +253 -0
  167. package/src/v2/runtime/__tests__/intelligence-run-telemetry.test.ts +194 -0
  168. package/src/v2/runtime/__tests__/runtime.test.ts +3 -1
  169. package/src/v2/runtime/__tests__/sse-response-telemetry.test.ts +108 -0
  170. package/src/v2/runtime/__tests__/telemetry.test.ts +0 -61
  171. package/src/v2/runtime/core/__tests__/debug-event-bus.test.ts +156 -0
  172. package/src/v2/runtime/core/debug-event-bus.ts +45 -0
  173. package/src/v2/runtime/core/fetch-handler.ts +7 -0
  174. package/src/v2/runtime/core/fetch-router.ts +11 -0
  175. package/src/v2/runtime/core/hooks.ts +2 -1
  176. package/src/v2/runtime/core/runtime.ts +12 -0
  177. package/src/v2/runtime/endpoints/express.ts +9 -3
  178. package/src/v2/runtime/handlers/__tests__/handle-debug-events.test.ts +176 -0
  179. package/src/v2/runtime/handlers/handle-connect.ts +2 -1
  180. package/src/v2/runtime/handlers/handle-debug-events.ts +52 -0
  181. package/src/v2/runtime/handlers/handle-run.ts +1 -0
  182. package/src/v2/runtime/handlers/intelligence/connect.ts +48 -11
  183. package/src/v2/runtime/handlers/intelligence/run.ts +162 -21
  184. package/src/v2/runtime/handlers/shared/intelligence-utils.ts +21 -1
  185. package/src/v2/runtime/handlers/shared/resolve-intelligence-user.ts +4 -1
  186. package/src/v2/runtime/handlers/shared/sse-response.ts +46 -0
  187. package/src/v2/runtime/handlers/sse/__tests__/sse-connect-agent-id.test.ts +71 -0
  188. package/src/v2/runtime/handlers/sse/connect.ts +6 -0
  189. package/src/v2/runtime/handlers/sse/run.ts +4 -0
  190. package/src/v2/runtime/intelligence-platform/__tests__/client.test.ts +33 -37
  191. package/src/v2/runtime/intelligence-platform/client.ts +37 -40
  192. package/src/v2/runtime/runner/__tests__/intelligence-runner.test.ts +66 -8
  193. package/src/v2/runtime/runner/agent-runner.ts +0 -1
  194. package/src/v2/runtime/runner/intelligence.ts +74 -15
  195. package/src/v2/runtime/telemetry/__tests__/instance-created.test.ts +96 -0
  196. package/src/v2/runtime/telemetry/instance-created.ts +44 -0
  197. package/src/v2/runtime/telemetry/telemetry-client.ts +1 -57
  198. package/dist/v2/runtime/intelligence-platform/index.d.mts +0 -2
  199. package/dist/v2/runtime/telemetry/utils.cjs +0 -15
  200. package/dist/v2/runtime/telemetry/utils.cjs.map +0 -1
  201. package/dist/v2/runtime/telemetry/utils.mjs +0 -14
  202. package/dist/v2/runtime/telemetry/utils.mjs.map +0 -1
  203. package/src/v2/runtime/telemetry/utils.ts +0 -15
@@ -4,8 +4,21 @@ import { isHandlerResponse } from "../shared/json-response.mjs";
4
4
  import { generateThreadNameForNewThread } from "./thread-names.mjs";
5
5
  import { resolveIntelligenceUser } from "../shared/resolve-intelligence-user.mjs";
6
6
  import { logger } from "@copilotkit/shared";
7
+ import { EventType } from "@ag-ui/client";
7
8
 
8
9
  //#region src/v2/runtime/handlers/intelligence/run.ts
10
+ /**
11
+ * Builds browser-facing realtime connection metadata owned by the runtime.
12
+ */
13
+ function buildRealtimeConnectionInfo(params) {
14
+ return {
15
+ clientUrl: params.clientUrl,
16
+ topic: `thread:${params.threadId}`
17
+ };
18
+ }
19
+ function hasRunnerStartupBoundary(runner) {
20
+ return typeof runner.runWithStartupBoundary === "function" && (Object.prototype.hasOwnProperty.call(runner, "runWithStartupBoundary") || Object.prototype.hasOwnProperty.call(runner, "threads"));
21
+ }
9
22
  async function handleIntelligenceRun({ runtime, request, agentId, agent, input }) {
10
23
  if (!runtime.intelligence) return Response.json({
11
24
  error: "Intelligence not configured",
@@ -37,45 +50,72 @@ async function handleIntelligenceRun({ runtime, request, agentId, agent, input }
37
50
  logger.error("Failed to get or create thread:", error);
38
51
  return Response.json({ error: "Failed to initialize thread" }, { status: 502 });
39
52
  }
40
- let joinCode;
53
+ let canonicalThreadId = input.threadId;
54
+ let canonicalRunId = input.runId;
41
55
  let joinToken;
42
56
  try {
43
57
  const lockResult = await runtime.intelligence.ɵacquireThreadLock({
44
58
  threadId: input.threadId,
45
59
  runId: input.runId,
46
60
  userId,
61
+ agentId,
47
62
  ...runtime.lockKeyPrefix !== void 0 ? { lockKeyPrefix: runtime.lockKeyPrefix } : {},
48
63
  ttlSeconds: runtime.lockTtlSeconds
49
64
  });
65
+ canonicalThreadId = lockResult.threadId;
66
+ canonicalRunId = lockResult.runId;
50
67
  joinToken = lockResult.joinToken;
51
- joinCode = lockResult.joinCode;
52
68
  } catch (error) {
53
69
  logger.error("Thread lock denied:", error);
54
70
  return Response.json({ error: "Thread lock denied" }, { status: 409 });
55
71
  }
56
- if (!joinToken) return Response.json({
57
- error: "Join token not available",
58
- message: "Intelligence platform did not return a join token"
59
- }, { status: 502 });
72
+ const cleanupLock = (reason) => runtime.intelligence.ɵcleanupThreadLock({
73
+ threadId: canonicalThreadId || input.threadId,
74
+ runId: canonicalRunId || input.runId
75
+ }).catch((cleanupError) => {
76
+ logger.error({
77
+ err: cleanupError,
78
+ reason
79
+ }, "Failed to cleanup thread lock");
80
+ });
81
+ if (!canonicalThreadId || !canonicalRunId || !joinToken) {
82
+ await cleanupLock("malformed-lock-response");
83
+ return Response.json({
84
+ error: "Run connection credentials not available",
85
+ message: "Intelligence platform did not return canonical threadId, runId, and joinToken"
86
+ }, { status: 502 });
87
+ }
88
+ const canonicalInput = {
89
+ ...input,
90
+ threadId: canonicalThreadId,
91
+ runId: canonicalRunId
92
+ };
60
93
  let persistedInputMessages;
61
94
  if (Array.isArray(input.messages)) try {
62
- const history = await runtime.intelligence.getThreadMessages({ threadId: input.threadId });
95
+ const history = await runtime.intelligence.getThreadMessages({ threadId: canonicalThreadId });
63
96
  const historicMessageIds = new Set(history.messages.map((message) => message.id));
64
97
  persistedInputMessages = input.messages.filter((message) => !historicMessageIds.has(message.id));
65
98
  } catch (error) {
66
99
  logger.error("Thread history lookup failed:", error);
100
+ await cleanupLock("thread-history-lookup-failed");
67
101
  return Response.json({ error: "Thread history lookup failed" }, { status: 502 });
68
102
  }
69
103
  telemetry.capture("oss.runtime.agent_execution_stream_started", {});
70
104
  let heartbeatTimer;
71
105
  heartbeatTimer = setInterval(() => {
72
106
  runtime.intelligence.ɵrenewThreadLock({
73
- threadId: input.threadId,
74
- runId: input.runId,
107
+ threadId: canonicalThreadId,
108
+ runId: canonicalRunId,
75
109
  ttlSeconds: runtime.lockTtlSeconds,
76
110
  ...runtime.lockKeyPrefix !== void 0 ? { lockKeyPrefix: runtime.lockKeyPrefix } : {}
77
111
  }).catch((err) => {
78
112
  logger.error("Failed to renew thread lock:", err);
113
+ clearHeartbeat();
114
+ try {
115
+ agent.abortRun();
116
+ } catch (abortError) {
117
+ logger.error("Failed to abort agent after lock renewal failure:", abortError);
118
+ }
79
119
  });
80
120
  }, runtime.lockHeartbeatIntervalSeconds * 1e3);
81
121
  const clearHeartbeat = () => {
@@ -84,24 +124,69 @@ async function handleIntelligenceRun({ runtime, request, agentId, agent, input }
84
124
  heartbeatTimer = void 0;
85
125
  }
86
126
  };
87
- runtime.runner.run({
88
- threadId: input.threadId,
127
+ const runStarted = { current: false };
128
+ let immediateStartupErrorMessage;
129
+ let immediateStartupCleanup;
130
+ const runRequest = {
131
+ threadId: canonicalThreadId,
89
132
  agent,
90
- input,
91
- ...persistedInputMessages !== void 0 ? { persistedInputMessages } : {},
92
- ...joinCode ? { joinCode } : {}
93
- }).subscribe({
94
- error: (error) => {
95
- clearHeartbeat();
96
- telemetry.capture("oss.runtime.agent_execution_stream_errored", { error: error instanceof Error ? error.message : String(error) });
97
- logger.error("Error running agent:", error);
98
- },
99
- complete: () => {
100
- clearHeartbeat();
101
- telemetry.capture("oss.runtime.agent_execution_stream_ended", {});
102
- }
103
- });
104
- return Response.json({ joinToken }, { headers: { "Cache-Control": "no-cache" } });
133
+ input: canonicalInput,
134
+ ...persistedInputMessages !== void 0 ? { persistedInputMessages } : {}
135
+ };
136
+ try {
137
+ const runStart = hasRunnerStartupBoundary(runtime.runner) ? runtime.runner.runWithStartupBoundary(runRequest) : {
138
+ events: runtime.runner.run(runRequest),
139
+ startup: Promise.resolve()
140
+ };
141
+ runStart.events.subscribe({
142
+ next: (event) => {
143
+ if (event.type === EventType.RUN_STARTED) runStarted.current = true;
144
+ if (event.type === EventType.RUN_ERROR && !runStarted.current) {
145
+ clearHeartbeat();
146
+ immediateStartupErrorMessage = "message" in event && typeof event.message === "string" ? event.message : "Runner failed before the run started";
147
+ immediateStartupCleanup = cleanupLock("runner-start-failed");
148
+ }
149
+ },
150
+ error: (error) => {
151
+ clearHeartbeat();
152
+ if (!runStarted.current) {
153
+ immediateStartupErrorMessage = error instanceof Error ? error.message : String(error);
154
+ immediateStartupCleanup = cleanupLock("runner-start-error");
155
+ } else cleanupLock("runner-error");
156
+ telemetry.capture("oss.runtime.agent_execution_stream_errored", { error: error instanceof Error ? error.message : String(error) });
157
+ logger.error("Error running agent:", error);
158
+ },
159
+ complete: () => {
160
+ clearHeartbeat();
161
+ telemetry.capture("oss.runtime.agent_execution_stream_ended", {});
162
+ }
163
+ });
164
+ await runStart.startup;
165
+ } catch (error) {
166
+ clearHeartbeat();
167
+ await (immediateStartupCleanup ?? cleanupLock("runner-start-threw"));
168
+ logger.error("Error starting agent runner:", error);
169
+ return Response.json({
170
+ error: "Failed to start runner",
171
+ message: error instanceof Error ? error.message : String(error)
172
+ }, { status: 502 });
173
+ }
174
+ if (immediateStartupErrorMessage) {
175
+ await immediateStartupCleanup;
176
+ return Response.json({
177
+ error: "Failed to start runner",
178
+ message: immediateStartupErrorMessage
179
+ }, { status: 502 });
180
+ }
181
+ return Response.json({
182
+ threadId: canonicalThreadId,
183
+ runId: canonicalRunId,
184
+ joinToken,
185
+ realtime: buildRealtimeConnectionInfo({
186
+ clientUrl: runtime.intelligence.ɵgetClientWsUrl(),
187
+ threadId: canonicalThreadId
188
+ })
189
+ }, { headers: { "Cache-Control": "no-cache" } });
105
190
  }
106
191
 
107
192
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"run.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/intelligence/run.ts"],"sourcesContent":["import { AbstractAgent, Message, RunAgentInput } from \"@ag-ui/client\";\nimport { CopilotIntelligenceRuntimeLike } from \"../../core/runtime\";\nimport { generateThreadNameForNewThread } from \"./thread-names\";\nimport { logger } from \"@copilotkit/shared\";\nimport { telemetry } from \"../../telemetry\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { isHandlerResponse } from \"../shared/json-response\";\n\ninterface HandleIntelligenceRunParams {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n agent: AbstractAgent;\n input: RunAgentInput;\n}\n\nexport async function handleIntelligenceRun({\n runtime,\n request,\n agentId,\n agent,\n input,\n}: HandleIntelligenceRunParams): Promise<Response> {\n if (!runtime.intelligence) {\n return Response.json(\n {\n error: \"Intelligence not configured\",\n message: \"Intelligence mode requires a CopilotKitIntelligence\",\n },\n { status: 500 },\n );\n }\n\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) {\n return user;\n }\n const userId = user.id;\n\n try {\n const { thread, created } = await runtime.intelligence.getOrCreateThread({\n threadId: input.threadId,\n userId,\n agentId,\n });\n\n if (created && runtime.generateThreadNames && !thread.name?.trim()) {\n void generateThreadNameForNewThread({\n runtime,\n request,\n agentId,\n sourceInput: input,\n thread,\n userId,\n }).catch((nameError) => {\n logger.error(\"Failed to generate thread name:\", nameError);\n });\n }\n } catch (error) {\n logger.error(\"Failed to get or create thread:\", error);\n return Response.json(\n {\n error: \"Failed to initialize thread\",\n },\n { status: 502 },\n );\n }\n\n let joinCode: string | undefined;\n let joinToken: string | undefined;\n try {\n const lockResult = await runtime.intelligence.ɵacquireThreadLock({\n threadId: input.threadId,\n runId: input.runId,\n userId,\n ...(runtime.lockKeyPrefix !== undefined\n ? { lockKeyPrefix: runtime.lockKeyPrefix }\n : {}),\n ttlSeconds: runtime.lockTtlSeconds,\n });\n joinToken = lockResult.joinToken;\n joinCode = lockResult.joinCode;\n } catch (error) {\n logger.error(\"Thread lock denied:\", error);\n return Response.json(\n {\n error: \"Thread lock denied\",\n },\n { status: 409 },\n );\n }\n\n if (!joinToken) {\n return Response.json(\n {\n error: \"Join token not available\",\n message: \"Intelligence platform did not return a join token\",\n },\n { status: 502 },\n );\n }\n\n let persistedInputMessages: Message[] | undefined;\n if (Array.isArray(input.messages)) {\n try {\n const history = await runtime.intelligence.getThreadMessages({\n threadId: input.threadId,\n });\n const historicMessageIds = new Set(\n history.messages.map((message) => message.id),\n );\n persistedInputMessages = input.messages.filter(\n (message) => !historicMessageIds.has(message.id),\n );\n } catch (error) {\n logger.error(\"Thread history lookup failed:\", error);\n return Response.json(\n {\n error: \"Thread history lookup failed\",\n },\n { status: 502 },\n );\n }\n }\n\n telemetry.capture(\"oss.runtime.agent_execution_stream_started\", {});\n\n // Start heartbeat timer to renew the thread lock.\n let heartbeatTimer: ReturnType<typeof setInterval> | undefined;\n heartbeatTimer = setInterval(() => {\n runtime.intelligence\n .ɵrenewThreadLock({\n threadId: input.threadId,\n runId: input.runId,\n ttlSeconds: runtime.lockTtlSeconds,\n ...(runtime.lockKeyPrefix !== undefined\n ? { lockKeyPrefix: runtime.lockKeyPrefix }\n : {}),\n })\n .catch((err) => {\n logger.error(\"Failed to renew thread lock:\", err);\n });\n }, runtime.lockHeartbeatIntervalSeconds * 1_000);\n\n const clearHeartbeat = () => {\n if (heartbeatTimer !== undefined) {\n clearInterval(heartbeatTimer);\n heartbeatTimer = undefined;\n }\n };\n\n runtime.runner\n .run({\n threadId: input.threadId,\n agent,\n input,\n ...(persistedInputMessages !== undefined\n ? { persistedInputMessages }\n : {}),\n ...(joinCode ? { joinCode } : {}),\n })\n .subscribe({\n error: (error) => {\n clearHeartbeat();\n telemetry.capture(\"oss.runtime.agent_execution_stream_errored\", {\n error: error instanceof Error ? error.message : String(error),\n });\n logger.error(\"Error running agent:\", error);\n },\n complete: () => {\n clearHeartbeat();\n telemetry.capture(\"oss.runtime.agent_execution_stream_ended\", {});\n },\n });\n\n return Response.json(\n { joinToken },\n {\n headers: { \"Cache-Control\": \"no-cache\" },\n },\n );\n}\n"],"mappings":";;;;;;;;AAgBA,eAAsB,sBAAsB,EAC1C,SACA,SACA,SACA,OACA,SACiD;AACjD,KAAI,CAAC,QAAQ,aACX,QAAO,SAAS,KACd;EACE,OAAO;EACP,SAAS;EACV,EACD,EAAE,QAAQ,KAAK,CAChB;CAGH,MAAM,OAAO,MAAM,wBAAwB;EAAE;EAAS;EAAS,CAAC;AAChE,KAAI,kBAAkB,KAAK,CACzB,QAAO;CAET,MAAM,SAAS,KAAK;AAEpB,KAAI;EACF,MAAM,EAAE,QAAQ,YAAY,MAAM,QA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AAIL,WAAU,QAAQ,8CAA8C,EAAE,CAAC;CAGnE,IAAI;AACJ,kBAAiB,kBAAkB;AACjC,UAAQ,aACL,iBAAiB;GAChB,UAAU,MAAM;GAChB,OAAO,MAAM;GACb,YAAY,QAAQ;GACpB,GAAI,QAAQ,kBAAkB,SAC1B,EAAE,eAAe,QAAQ,eAAe,GACxC,EAAE;GACP,CAAC,CACD,OAAO,QAAQ;AACd,UAAO,MAAM,gCAAgC,IAAI;IACjD;IACH,QAAQ,+BAA+B,IAAM;CAEhD,MAAM,uBAAuB;AAC3B,MAAI,mBAAmB,QAAW;AAChC,iBAAc,eAAe;AAC7B,oBAAiB;;;AAIrB,SAAQ,OACL,IAAI;EACH,UAAU,MAAM;EAChB;EACA;EACA,GAAI,2BAA2B,SAC3B,EAAE,wBAAwB,GAC1B,EAAE;EACN,GAAI,WAAW,EAAE,UAAU,GAAG,EAAE;EACjC,CAAC,CACD,UAAU;EACT,QAAQ,UAAU;AAChB,mBAAgB;AAChB,aAAU,QAAQ,8CAA8C,EAC9D,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,EAC9D,CAAC;AACF,UAAO,MAAM,wBAAwB,MAAM;;EAE7C,gBAAgB;AACd,mBAAgB;AAChB,aAAU,QAAQ,4CAA4C,EAAE,CAAC;;EAEpE,CAAC;AAEJ,QAAO,SAAS,KACd,EAAE,WAAW,EACb,EACE,SAAS,EAAE,iBAAiB,YAAY,EACzC,CACF"}
1
+ {"version":3,"file":"run.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/intelligence/run.ts"],"sourcesContent":["import {\n AbstractAgent,\n BaseEvent,\n EventType,\n Message,\n RunAgentInput,\n} from \"@ag-ui/client\";\nimport { CopilotIntelligenceRuntimeLike } from \"../../core/runtime\";\nimport { generateThreadNameForNewThread } from \"./thread-names\";\nimport { logger } from \"@copilotkit/shared\";\nimport { telemetry } from \"../../telemetry\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { isHandlerResponse } from \"../shared/json-response\";\nimport { AgentRunnerRunRequest } from \"../../runner/agent-runner\";\nimport { Observable } from \"rxjs\";\n\n/**\n * Builds browser-facing realtime connection metadata owned by the runtime.\n */\nfunction buildRealtimeConnectionInfo(params: {\n clientUrl: string;\n threadId: string;\n}): { clientUrl: string; topic: string } {\n return {\n clientUrl: params.clientUrl,\n topic: `thread:${params.threadId}`,\n };\n}\n\ninterface RunnerStartupBoundary {\n events: Observable<BaseEvent>;\n startup: Promise<void>;\n}\n\ninterface RunnerWithStartupBoundary {\n runWithStartupBoundary(request: AgentRunnerRunRequest): RunnerStartupBoundary;\n}\n\nfunction hasRunnerStartupBoundary(\n runner: CopilotIntelligenceRuntimeLike[\"runner\"],\n): runner is CopilotIntelligenceRuntimeLike[\"runner\"] &\n RunnerWithStartupBoundary {\n const candidate = runner as { runWithStartupBoundary?: unknown };\n\n return (\n typeof candidate.runWithStartupBoundary === \"function\" &&\n (Object.prototype.hasOwnProperty.call(runner, \"runWithStartupBoundary\") ||\n Object.prototype.hasOwnProperty.call(runner, \"threads\"))\n );\n}\n\ninterface HandleIntelligenceRunParams {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n agent: AbstractAgent;\n input: RunAgentInput;\n}\n\nexport async function handleIntelligenceRun({\n runtime,\n request,\n agentId,\n agent,\n input,\n}: HandleIntelligenceRunParams): Promise<Response> {\n if (!runtime.intelligence) {\n return Response.json(\n {\n error: \"Intelligence not configured\",\n message: \"Intelligence mode requires a CopilotKitIntelligence\",\n },\n { status: 500 },\n );\n }\n\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) {\n return user;\n }\n const userId = user.id;\n\n try {\n const { thread, created } = await runtime.intelligence.getOrCreateThread({\n threadId: input.threadId,\n userId,\n agentId,\n });\n\n if (created && runtime.generateThreadNames && !thread.name?.trim()) {\n void generateThreadNameForNewThread({\n runtime,\n request,\n agentId,\n sourceInput: input,\n thread,\n userId,\n }).catch((nameError) => {\n logger.error(\"Failed to generate thread name:\", nameError);\n });\n }\n } catch (error) {\n logger.error(\"Failed to get or create thread:\", error);\n return Response.json(\n {\n error: \"Failed to initialize thread\",\n },\n { status: 502 },\n );\n }\n\n let canonicalThreadId = input.threadId;\n let canonicalRunId = input.runId;\n let joinToken: string | undefined;\n try {\n const lockResult = await runtime.intelligence.ɵacquireThreadLock({\n threadId: input.threadId,\n runId: input.runId,\n userId,\n agentId,\n ...(runtime.lockKeyPrefix !== undefined\n ? { lockKeyPrefix: runtime.lockKeyPrefix }\n : {}),\n ttlSeconds: runtime.lockTtlSeconds,\n });\n canonicalThreadId = lockResult.threadId;\n canonicalRunId = lockResult.runId;\n joinToken = lockResult.joinToken;\n } catch (error) {\n logger.error(\"Thread lock denied:\", error);\n return Response.json(\n {\n error: \"Thread lock denied\",\n },\n { status: 409 },\n );\n }\n\n const cleanupLock = (reason: string): Promise<void> =>\n runtime.intelligence\n .ɵcleanupThreadLock({\n threadId: canonicalThreadId || input.threadId,\n runId: canonicalRunId || input.runId,\n })\n .catch((cleanupError) => {\n logger.error(\n { err: cleanupError, reason },\n \"Failed to cleanup thread lock\",\n );\n });\n\n if (!canonicalThreadId || !canonicalRunId || !joinToken) {\n await cleanupLock(\"malformed-lock-response\");\n return Response.json(\n {\n error: \"Run connection credentials not available\",\n message:\n \"Intelligence platform did not return canonical threadId, runId, and joinToken\",\n },\n { status: 502 },\n );\n }\n\n const canonicalInput: RunAgentInput = {\n ...input,\n threadId: canonicalThreadId,\n runId: canonicalRunId,\n };\n\n let persistedInputMessages: Message[] | undefined;\n if (Array.isArray(input.messages)) {\n try {\n const history = await runtime.intelligence.getThreadMessages({\n threadId: canonicalThreadId,\n });\n const historicMessageIds = new Set(\n history.messages.map((message) => message.id),\n );\n persistedInputMessages = input.messages.filter(\n (message) => !historicMessageIds.has(message.id),\n );\n } catch (error) {\n logger.error(\"Thread history lookup failed:\", error);\n await cleanupLock(\"thread-history-lookup-failed\");\n return Response.json(\n {\n error: \"Thread history lookup failed\",\n },\n { status: 502 },\n );\n }\n }\n\n telemetry.capture(\"oss.runtime.agent_execution_stream_started\", {});\n\n // Start heartbeat timer to renew the thread lock.\n let heartbeatTimer: ReturnType<typeof setInterval> | undefined;\n heartbeatTimer = setInterval(() => {\n runtime.intelligence\n .ɵrenewThreadLock({\n threadId: canonicalThreadId,\n runId: canonicalRunId,\n ttlSeconds: runtime.lockTtlSeconds,\n ...(runtime.lockKeyPrefix !== undefined\n ? { lockKeyPrefix: runtime.lockKeyPrefix }\n : {}),\n })\n .catch((err) => {\n logger.error(\"Failed to renew thread lock:\", err);\n clearHeartbeat();\n try {\n agent.abortRun();\n } catch (abortError) {\n logger.error(\n \"Failed to abort agent after lock renewal failure:\",\n abortError,\n );\n }\n });\n }, runtime.lockHeartbeatIntervalSeconds * 1_000);\n\n const clearHeartbeat = () => {\n if (heartbeatTimer !== undefined) {\n clearInterval(heartbeatTimer);\n heartbeatTimer = undefined;\n }\n };\n\n const runStarted = { current: false };\n let immediateStartupErrorMessage: string | undefined;\n let immediateStartupCleanup: Promise<void> | undefined;\n\n const runRequest: AgentRunnerRunRequest = {\n threadId: canonicalThreadId,\n agent,\n input: canonicalInput,\n ...(persistedInputMessages !== undefined ? { persistedInputMessages } : {}),\n };\n\n try {\n const runStart = hasRunnerStartupBoundary(runtime.runner)\n ? runtime.runner.runWithStartupBoundary(runRequest)\n : {\n events: runtime.runner.run(runRequest),\n startup: Promise.resolve(),\n };\n\n runStart.events.subscribe({\n next: (event: BaseEvent) => {\n if (event.type === EventType.RUN_STARTED) {\n runStarted.current = true;\n }\n if (event.type === EventType.RUN_ERROR && !runStarted.current) {\n clearHeartbeat();\n immediateStartupErrorMessage =\n \"message\" in event && typeof event.message === \"string\"\n ? event.message\n : \"Runner failed before the run started\";\n immediateStartupCleanup = cleanupLock(\"runner-start-failed\");\n }\n },\n error: (error) => {\n clearHeartbeat();\n if (!runStarted.current) {\n immediateStartupErrorMessage =\n error instanceof Error ? error.message : String(error);\n immediateStartupCleanup = cleanupLock(\"runner-start-error\");\n } else {\n cleanupLock(\"runner-error\");\n }\n telemetry.capture(\"oss.runtime.agent_execution_stream_errored\", {\n error: error instanceof Error ? error.message : String(error),\n });\n logger.error(\"Error running agent:\", error);\n },\n complete: () => {\n clearHeartbeat();\n telemetry.capture(\"oss.runtime.agent_execution_stream_ended\", {});\n },\n });\n\n await runStart.startup;\n } catch (error) {\n clearHeartbeat();\n await (immediateStartupCleanup ?? cleanupLock(\"runner-start-threw\"));\n logger.error(\"Error starting agent runner:\", error);\n return Response.json(\n {\n error: \"Failed to start runner\",\n message: error instanceof Error ? error.message : String(error),\n },\n { status: 502 },\n );\n }\n\n if (immediateStartupErrorMessage) {\n await immediateStartupCleanup;\n return Response.json(\n {\n error: \"Failed to start runner\",\n message: immediateStartupErrorMessage,\n },\n { status: 502 },\n );\n }\n\n // IntelligenceAgentRunner resolves this boundary after Phoenix channel join.\n // Other runner implementations fall back to construction/subscription errors.\n return Response.json(\n {\n threadId: canonicalThreadId,\n runId: canonicalRunId,\n joinToken,\n realtime: buildRealtimeConnectionInfo({\n clientUrl: runtime.intelligence.ɵgetClientWsUrl(),\n threadId: canonicalThreadId,\n }),\n },\n {\n headers: { \"Cache-Control\": \"no-cache\" },\n },\n );\n}\n"],"mappings":";;;;;;;;;;;;AAmBA,SAAS,4BAA4B,QAGI;AACvC,QAAO;EACL,WAAW,OAAO;EAClB,OAAO,UAAU,OAAO;EACzB;;AAYH,SAAS,yBACP,QAE0B;AAG1B,QACE,OAHgB,OAGC,2BAA2B,eAC3C,OAAO,UAAU,eAAe,KAAK,QAAQ,yBAAyB,IACrE,OAAO,UAAU,eAAe,KAAK,QAAQ,UAAU;;AAY7D,eAAsB,sBAAsB,EAC1C,SACA,SACA,SACA,OACA,SACiD;AACjD,KAAI,CAAC,QAAQ,aACX,QAAO,SAAS,KACd;EACE,OAAO;EACP,SAAS;EACV,EACD,EAAE,QAAQ,KAAK,CAChB;CAGH,MAAM,OAA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ACH,EACD,EACE,SAAS,EAAE,iBAAiB,YAAY,EACzC,CACF"}
@@ -2,8 +2,12 @@ require("reflect-metadata");
2
2
  const require_client = require('../../intelligence-platform/client.cjs');
3
3
 
4
4
  //#region src/v2/runtime/handlers/shared/intelligence-utils.ts
5
- function isPlatformNotFoundError(error) {
6
- return error instanceof require_client.PlatformRequestError && error.status === 404;
5
+ /**
6
+ * Returns the HTTP status carried by platform request errors.
7
+ */
8
+ function getPlatformErrorStatus(error) {
9
+ if (error instanceof require_client.PlatformRequestError) return error.status;
10
+ if (error !== null && typeof error === "object" && "status" in error && typeof error.status === "number") return error.status;
7
11
  }
8
12
  const MAX_ID_LENGTH = 128;
9
13
  const SAFE_ID_PATTERN = /^[\w.@:=-]+$/;
@@ -16,6 +20,6 @@ function isValidIdentifier(value) {
16
20
  }
17
21
 
18
22
  //#endregion
19
- exports.isPlatformNotFoundError = isPlatformNotFoundError;
23
+ exports.getPlatformErrorStatus = getPlatformErrorStatus;
20
24
  exports.isValidIdentifier = isValidIdentifier;
21
25
  //# sourceMappingURL=intelligence-utils.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"intelligence-utils.cjs","names":["PlatformRequestError"],"sources":["../../../../../src/v2/runtime/handlers/shared/intelligence-utils.ts"],"sourcesContent":["import { PlatformRequestError } from \"../../intelligence-platform/client\";\n\nexport function isPlatformNotFoundError(error: unknown): boolean {\n return error instanceof PlatformRequestError && error.status === 404;\n}\n\nconst MAX_ID_LENGTH = 128;\nconst SAFE_ID_PATTERN = /^[\\w.@:=-]+$/;\n\n/**\n * Validates that a string identifier (userId, agentId) is safe to pass through.\n * Returns `true` if valid, `false` otherwise.\n */\nexport function isValidIdentifier(value: unknown): value is string {\n return (\n typeof value === \"string\" &&\n value.length > 0 &&\n value.length <= MAX_ID_LENGTH &&\n SAFE_ID_PATTERN.test(value)\n );\n}\n"],"mappings":";;;;AAEA,SAAgB,wBAAwB,OAAyB;AAC/D,QAAO,iBAAiBA,uCAAwB,MAAM,WAAW;;AAGnE,MAAM,gBAAgB;AACtB,MAAM,kBAAkB;;;;;AAMxB,SAAgB,kBAAkB,OAAiC;AACjE,QACE,OAAO,UAAU,YACjB,MAAM,SAAS,KACf,MAAM,UAAU,iBAChB,gBAAgB,KAAK,MAAM"}
1
+ {"version":3,"file":"intelligence-utils.cjs","names":["PlatformRequestError"],"sources":["../../../../../src/v2/runtime/handlers/shared/intelligence-utils.ts"],"sourcesContent":["import { PlatformRequestError } from \"../../intelligence-platform/client\";\n\n/**\n * Returns the HTTP status carried by platform request errors.\n */\nexport function getPlatformErrorStatus(error: unknown): number | undefined {\n if (error instanceof PlatformRequestError) {\n return error.status;\n }\n\n if (\n error !== null &&\n typeof error === \"object\" &&\n \"status\" in error &&\n typeof error.status === \"number\"\n ) {\n return error.status;\n }\n\n return undefined;\n}\n\nexport function isPlatformNotFoundError(error: unknown): boolean {\n return getPlatformErrorStatus(error) === 404;\n}\n\nconst MAX_ID_LENGTH = 128;\nconst SAFE_ID_PATTERN = /^[\\w.@:=-]+$/;\n\n/**\n * Validates that a string identifier (userId, agentId) is safe to pass through.\n * Returns `true` if valid, `false` otherwise.\n */\nexport function isValidIdentifier(value: unknown): value is string {\n return (\n typeof value === \"string\" &&\n value.length > 0 &&\n value.length <= MAX_ID_LENGTH &&\n SAFE_ID_PATTERN.test(value)\n );\n}\n"],"mappings":";;;;;;;AAKA,SAAgB,uBAAuB,OAAoC;AACzE,KAAI,iBAAiBA,oCACnB,QAAO,MAAM;AAGf,KACE,UAAU,QACV,OAAO,UAAU,YACjB,YAAY,SACZ,OAAO,MAAM,WAAW,SAExB,QAAO,MAAM;;AAUjB,MAAM,gBAAgB;AACtB,MAAM,kBAAkB;;;;;AAMxB,SAAgB,kBAAkB,OAAiC;AACjE,QACE,OAAO,UAAU,YACjB,MAAM,SAAS,KACf,MAAM,UAAU,iBAChB,gBAAgB,KAAK,MAAM"}
@@ -2,8 +2,12 @@ import "reflect-metadata";
2
2
  import { PlatformRequestError } from "../../intelligence-platform/client.mjs";
3
3
 
4
4
  //#region src/v2/runtime/handlers/shared/intelligence-utils.ts
5
- function isPlatformNotFoundError(error) {
6
- return error instanceof PlatformRequestError && error.status === 404;
5
+ /**
6
+ * Returns the HTTP status carried by platform request errors.
7
+ */
8
+ function getPlatformErrorStatus(error) {
9
+ if (error instanceof PlatformRequestError) return error.status;
10
+ if (error !== null && typeof error === "object" && "status" in error && typeof error.status === "number") return error.status;
7
11
  }
8
12
  const MAX_ID_LENGTH = 128;
9
13
  const SAFE_ID_PATTERN = /^[\w.@:=-]+$/;
@@ -16,5 +20,5 @@ function isValidIdentifier(value) {
16
20
  }
17
21
 
18
22
  //#endregion
19
- export { isPlatformNotFoundError, isValidIdentifier };
23
+ export { getPlatformErrorStatus, isValidIdentifier };
20
24
  //# sourceMappingURL=intelligence-utils.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"intelligence-utils.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/shared/intelligence-utils.ts"],"sourcesContent":["import { PlatformRequestError } from \"../../intelligence-platform/client\";\n\nexport function isPlatformNotFoundError(error: unknown): boolean {\n return error instanceof PlatformRequestError && error.status === 404;\n}\n\nconst MAX_ID_LENGTH = 128;\nconst SAFE_ID_PATTERN = /^[\\w.@:=-]+$/;\n\n/**\n * Validates that a string identifier (userId, agentId) is safe to pass through.\n * Returns `true` if valid, `false` otherwise.\n */\nexport function isValidIdentifier(value: unknown): value is string {\n return (\n typeof value === \"string\" &&\n value.length > 0 &&\n value.length <= MAX_ID_LENGTH &&\n SAFE_ID_PATTERN.test(value)\n );\n}\n"],"mappings":";;;;AAEA,SAAgB,wBAAwB,OAAyB;AAC/D,QAAO,iBAAiB,wBAAwB,MAAM,WAAW;;AAGnE,MAAM,gBAAgB;AACtB,MAAM,kBAAkB;;;;;AAMxB,SAAgB,kBAAkB,OAAiC;AACjE,QACE,OAAO,UAAU,YACjB,MAAM,SAAS,KACf,MAAM,UAAU,iBAChB,gBAAgB,KAAK,MAAM"}
1
+ {"version":3,"file":"intelligence-utils.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/shared/intelligence-utils.ts"],"sourcesContent":["import { PlatformRequestError } from \"../../intelligence-platform/client\";\n\n/**\n * Returns the HTTP status carried by platform request errors.\n */\nexport function getPlatformErrorStatus(error: unknown): number | undefined {\n if (error instanceof PlatformRequestError) {\n return error.status;\n }\n\n if (\n error !== null &&\n typeof error === \"object\" &&\n \"status\" in error &&\n typeof error.status === \"number\"\n ) {\n return error.status;\n }\n\n return undefined;\n}\n\nexport function isPlatformNotFoundError(error: unknown): boolean {\n return getPlatformErrorStatus(error) === 404;\n}\n\nconst MAX_ID_LENGTH = 128;\nconst SAFE_ID_PATTERN = /^[\\w.@:=-]+$/;\n\n/**\n * Validates that a string identifier (userId, agentId) is safe to pass through.\n * Returns `true` if valid, `false` otherwise.\n */\nexport function isValidIdentifier(value: unknown): value is string {\n return (\n typeof value === \"string\" &&\n value.length > 0 &&\n value.length <= MAX_ID_LENGTH &&\n SAFE_ID_PATTERN.test(value)\n );\n}\n"],"mappings":";;;;;;;AAKA,SAAgB,uBAAuB,OAAoC;AACzE,KAAI,iBAAiB,qBACnB,QAAO,MAAM;AAGf,KACE,UAAU,QACV,OAAO,UAAU,YACjB,YAAY,SACZ,OAAO,MAAM,WAAW,SAExB,QAAO,MAAM;;AAUjB,MAAM,gBAAgB;AACtB,MAAM,kBAAkB;;;;;AAMxB,SAAgB,kBAAkB,OAAiC;AACjE,QACE,OAAO,UAAU,YACjB,MAAM,SAAS,KACf,MAAM,UAAU,iBAChB,gBAAgB,KAAK,MAAM"}
@@ -8,7 +8,11 @@ async function resolveIntelligenceUser(params) {
8
8
  try {
9
9
  const user = await runtime.identifyUser(request);
10
10
  if (!require_intelligence_utils.isValidIdentifier(user?.id)) return require_json_response.errorResponse("identifyUser must return a valid user id", 400);
11
- return { id: user.id };
11
+ if (typeof user?.name !== "string" || user.name.trim().length === 0) return require_json_response.errorResponse("identifyUser must return a valid user name", 400);
12
+ return {
13
+ id: user.id,
14
+ name: user.name
15
+ };
12
16
  } catch (error) {
13
17
  console.error("Error identifying intelligence user:", error);
14
18
  return require_json_response.errorResponse("Failed to identify user", 500);
@@ -1 +1 @@
1
- {"version":3,"file":"resolve-intelligence-user.cjs","names":["isValidIdentifier","errorResponse"],"sources":["../../../../../src/v2/runtime/handlers/shared/resolve-intelligence-user.ts"],"sourcesContent":["import {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeUser,\n} from \"../../core/runtime\";\nimport { errorResponse } from \"./json-response\";\nimport { isValidIdentifier } from \"./intelligence-utils\";\n\nexport async function resolveIntelligenceUser(params: {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n}): Promise<CopilotRuntimeUser | Response> {\n const { runtime, request } = params;\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\n return { id: user.id };\n } catch (error) {\n console.error(\"Error identifying intelligence user:\", error);\n return errorResponse(\"Failed to identify user\", 500);\n }\n}\n"],"mappings":";;;;;AAOA,eAAsB,wBAAwB,QAGH;CACzC,MAAM,EAAE,SAAS,YAAY;AAE7B,KAAI;EACF,MAAM,OAAO,MAAM,QAAQ,aAAa,QAAQ;AAChD,MAAI,CAACA,6CAAkB,MAAM,GAAG,CAC9B,QAAOC,oCAAc,4CAA4C,IAAI;AAGvE,SAAO,EAAE,IAAI,KAAK,IAAI;UACf,OAAO;AACd,UAAQ,MAAM,wCAAwC,MAAM;AAC5D,SAAOA,oCAAc,2BAA2B,IAAI"}
1
+ {"version":3,"file":"resolve-intelligence-user.cjs","names":["isValidIdentifier","errorResponse"],"sources":["../../../../../src/v2/runtime/handlers/shared/resolve-intelligence-user.ts"],"sourcesContent":["import {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeUser,\n} from \"../../core/runtime\";\nimport { errorResponse } from \"./json-response\";\nimport { isValidIdentifier } from \"./intelligence-utils\";\n\nexport async function resolveIntelligenceUser(params: {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n}): Promise<CopilotRuntimeUser | Response> {\n const { runtime, request } = params;\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 if (typeof user?.name !== \"string\" || user.name.trim().length === 0) {\n return errorResponse(\"identifyUser must return a valid user name\", 400);\n }\n\n return { id: user.id, name: user.name };\n } catch (error) {\n console.error(\"Error identifying intelligence user:\", error);\n return errorResponse(\"Failed to identify user\", 500);\n }\n}\n"],"mappings":";;;;;AAOA,eAAsB,wBAAwB,QAGH;CACzC,MAAM,EAAE,SAAS,YAAY;AAE7B,KAAI;EACF,MAAM,OAAO,MAAM,QAAQ,aAAa,QAAQ;AAChD,MAAI,CAACA,6CAAkB,MAAM,GAAG,CAC9B,QAAOC,oCAAc,4CAA4C,IAAI;AAEvE,MAAI,OAAO,MAAM,SAAS,YAAY,KAAK,KAAK,MAAM,CAAC,WAAW,EAChE,QAAOA,oCAAc,8CAA8C,IAAI;AAGzE,SAAO;GAAE,IAAI,KAAK;GAAI,MAAM,KAAK;GAAM;UAChC,OAAO;AACd,UAAQ,MAAM,wCAAwC,MAAM;AAC5D,SAAOA,oCAAc,2BAA2B,IAAI"}
@@ -8,7 +8,11 @@ async function resolveIntelligenceUser(params) {
8
8
  try {
9
9
  const user = await runtime.identifyUser(request);
10
10
  if (!isValidIdentifier(user?.id)) return errorResponse("identifyUser must return a valid user id", 400);
11
- return { id: user.id };
11
+ if (typeof user?.name !== "string" || user.name.trim().length === 0) return errorResponse("identifyUser must return a valid user name", 400);
12
+ return {
13
+ id: user.id,
14
+ name: user.name
15
+ };
12
16
  } catch (error) {
13
17
  console.error("Error identifying intelligence user:", error);
14
18
  return errorResponse("Failed to identify user", 500);
@@ -1 +1 @@
1
- {"version":3,"file":"resolve-intelligence-user.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/shared/resolve-intelligence-user.ts"],"sourcesContent":["import {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeUser,\n} from \"../../core/runtime\";\nimport { errorResponse } from \"./json-response\";\nimport { isValidIdentifier } from \"./intelligence-utils\";\n\nexport async function resolveIntelligenceUser(params: {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n}): Promise<CopilotRuntimeUser | Response> {\n const { runtime, request } = params;\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\n return { id: user.id };\n } catch (error) {\n console.error(\"Error identifying intelligence user:\", error);\n return errorResponse(\"Failed to identify user\", 500);\n }\n}\n"],"mappings":";;;;;AAOA,eAAsB,wBAAwB,QAGH;CACzC,MAAM,EAAE,SAAS,YAAY;AAE7B,KAAI;EACF,MAAM,OAAO,MAAM,QAAQ,aAAa,QAAQ;AAChD,MAAI,CAAC,kBAAkB,MAAM,GAAG,CAC9B,QAAO,cAAc,4CAA4C,IAAI;AAGvE,SAAO,EAAE,IAAI,KAAK,IAAI;UACf,OAAO;AACd,UAAQ,MAAM,wCAAwC,MAAM;AAC5D,SAAO,cAAc,2BAA2B,IAAI"}
1
+ {"version":3,"file":"resolve-intelligence-user.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/shared/resolve-intelligence-user.ts"],"sourcesContent":["import {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeUser,\n} from \"../../core/runtime\";\nimport { errorResponse } from \"./json-response\";\nimport { isValidIdentifier } from \"./intelligence-utils\";\n\nexport async function resolveIntelligenceUser(params: {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n}): Promise<CopilotRuntimeUser | Response> {\n const { runtime, request } = params;\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 if (typeof user?.name !== \"string\" || user.name.trim().length === 0) {\n return errorResponse(\"identifyUser must return a valid user name\", 400);\n }\n\n return { id: user.id, name: user.name };\n } catch (error) {\n console.error(\"Error identifying intelligence user:\", error);\n return errorResponse(\"Failed to identify user\", 500);\n }\n}\n"],"mappings":";;;;;AAOA,eAAsB,wBAAwB,QAGH;CACzC,MAAM,EAAE,SAAS,YAAY;AAE7B,KAAI;EACF,MAAM,OAAO,MAAM,QAAQ,aAAa,QAAQ;AAChD,MAAI,CAAC,kBAAkB,MAAM,GAAG,CAC9B,QAAO,cAAc,4CAA4C,IAAI;AAEvE,MAAI,OAAO,MAAM,SAAS,YAAY,KAAK,KAAK,MAAM,CAAC,WAAW,EAChE,QAAO,cAAc,8CAA8C,IAAI;AAGzE,SAAO;GAAE,IAAI,KAAK;GAAI,MAAM,KAAK;GAAM;UAChC,OAAO;AACd,UAAQ,MAAM,wCAAwC,MAAM;AAC5D,SAAO,cAAc,2BAA2B,IAAI"}
@@ -5,11 +5,13 @@ const require_telemetry_client = require('../../telemetry/telemetry-client.cjs')
5
5
  let _ag_ui_encoder = require("@ag-ui/encoder");
6
6
 
7
7
  //#region src/v2/runtime/handlers/shared/sse-response.ts
8
- function createSseEventResponse({ request, observableFactory, debug, logger }) {
8
+ function createSseEventResponse({ request, observableFactory, debugEventBus, agentId, debug, logger }) {
9
9
  const stream = new TransformStream();
10
10
  const writer = stream.writable.getWriter();
11
11
  const encoder = new _ag_ui_encoder.EventEncoder();
12
12
  let streamClosed = false;
13
+ let debugThreadId = "";
14
+ let debugRunId = "";
13
15
  const debugLogger = debug?.enabled ? logger ?? require_logger.createLogger({
14
16
  level: "debug",
15
17
  component: "copilotkit-debug"
@@ -38,6 +40,20 @@ function createSseEventResponse({ request, observableFactory, debug, logger }) {
38
40
  let loggedEventCount = 0;
39
41
  subscription = observable.subscribe({
40
42
  next: async (event) => {
43
+ if (event.type === "RUN_STARTED") {
44
+ const e = event;
45
+ debugThreadId = e.threadId ?? "";
46
+ debugRunId = e.runId ?? "";
47
+ }
48
+ if (debugEventBus) try {
49
+ debugEventBus.broadcast(event, {
50
+ agentId: agentId ?? "",
51
+ threadId: debugThreadId,
52
+ runId: debugRunId
53
+ });
54
+ } catch (broadcastError) {
55
+ logError(broadcastError);
56
+ }
41
57
  if (!request.signal.aborted && !streamClosed) try {
42
58
  eventCount++;
43
59
  if (debug?.events) {
@@ -51,6 +67,10 @@ function createSseEventResponse({ request, observableFactory, debug, logger }) {
51
67
  await writer.write(encoder.encode(event));
52
68
  } catch (error) {
53
69
  if (error instanceof Error && error.name === "AbortError") streamClosed = true;
70
+ else {
71
+ logError(error);
72
+ streamClosed = true;
73
+ }
54
74
  }
55
75
  },
56
76
  error: async (error) => {
@@ -1 +1 @@
1
- {"version":3,"file":"sse-response.cjs","names":["EventEncoder","createLogger"],"sources":["../../../../../src/v2/runtime/handlers/shared/sse-response.ts"],"sourcesContent":["import { BaseEvent } from \"@ag-ui/client\";\nimport { EventEncoder } from \"@ag-ui/encoder\";\nimport { Observable, Subscription } from \"rxjs\";\nimport { ResolvedDebugConfig } from \"@copilotkit/shared\";\nimport {\n createLogger,\n type CopilotRuntimeLogger,\n} from \"../../../../lib/logger\";\nimport { telemetry } from \"../../telemetry\";\n\ninterface CreateSseEventResponseParams {\n request: Request;\n observableFactory: () =>\n | Promise<Observable<BaseEvent>>\n | Observable<BaseEvent>;\n debug?: ResolvedDebugConfig;\n /** Pre-created logger instance to avoid creating a new pino logger per request. */\n logger?: CopilotRuntimeLogger;\n}\n\nexport function createSseEventResponse({\n request,\n observableFactory,\n debug,\n logger,\n}: CreateSseEventResponseParams): Response {\n const stream = new TransformStream();\n const writer = stream.writable.getWriter();\n const encoder = new EventEncoder();\n let streamClosed = false;\n\n const debugLogger = debug?.enabled\n ? (logger ??\n createLogger({ level: \"debug\", component: \"copilotkit-debug\" }))\n : undefined;\n\n const closeStream = async () => {\n if (!streamClosed) {\n try {\n await writer.close();\n streamClosed = true;\n } catch {\n // Stream already closed.\n }\n }\n };\n\n const logError = (error: unknown) => {\n console.error(\"Error running agent:\", error);\n console.error(\n \"Error stack:\",\n error instanceof Error ? error.stack : \"No stack trace\",\n );\n console.error(\"Error details:\", {\n name: error instanceof Error ? error.name : \"Unknown\",\n message: error instanceof Error ? error.message : String(error),\n cause: error instanceof Error ? error.cause : undefined,\n });\n };\n\n let subscription: Subscription | undefined;\n\n (async () => {\n const observable = await observableFactory();\n\n telemetry.capture(\"oss.runtime.agent_execution_stream_started\", {});\n\n if (debug?.lifecycle) {\n debugLogger!.debug(\"SSE stream opened\");\n }\n\n let eventCount = 0;\n let loggedEventCount = 0;\n\n subscription = observable.subscribe({\n next: async (event) => {\n if (!request.signal.aborted && !streamClosed) {\n try {\n eventCount++;\n if (debug?.events) {\n loggedEventCount++;\n if (debug.verbose) {\n debugLogger!.debug({ event }, \"Event emitted\");\n } else {\n debugLogger!.debug(\n { type: event.type, ...summarizeEvent(event) },\n \"Event emitted\",\n );\n }\n }\n await writer.write(encoder.encode(event));\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n streamClosed = true;\n }\n }\n }\n },\n error: async (error) => {\n telemetry.capture(\"oss.runtime.agent_execution_stream_errored\", {\n error: error instanceof Error ? error.message : String(error),\n });\n if (debug?.lifecycle) {\n debugLogger!.debug(\n { error: error instanceof Error ? error.message : String(error) },\n \"SSE stream errored\",\n );\n }\n logError(error);\n await closeStream();\n },\n complete: async () => {\n telemetry.capture(\"oss.runtime.agent_execution_stream_ended\", {});\n if (debug?.lifecycle) {\n debugLogger!.debug(\n { eventCount, loggedEventCount },\n \"SSE stream completed\",\n );\n }\n await closeStream();\n },\n });\n\n // If the client disconnected before the subscription was created,\n // unsubscribe immediately to avoid leaking the observable.\n if (request.signal.aborted) {\n subscription.unsubscribe();\n }\n })().catch(async (error) => {\n logError(error);\n await closeStream();\n });\n\n request.signal.addEventListener(\"abort\", () => {\n subscription?.unsubscribe();\n });\n\n return new Response(stream.readable, {\n status: 200,\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n },\n });\n}\n\nfunction summarizeEvent(event: BaseEvent): Record<string, unknown> {\n const e = event as any;\n const summary: Record<string, unknown> = {};\n\n if (e.messageId) summary.messageId = e.messageId;\n if (e.toolCallId) summary.toolCallId = e.toolCallId;\n if (e.toolCallName) summary.toolCallName = e.toolCallName;\n if (e.role) summary.role = e.role;\n if (e.delta != null && typeof e.delta === \"string\")\n summary.deltaLength = e.delta.length;\n if (e.snapshot && typeof e.snapshot === \"object\")\n summary.snapshotKeys = Object.keys(e.snapshot);\n if (e.delta && Array.isArray(e.delta))\n summary.operationCount = e.delta.length;\n if (e.threadId) summary.threadId = e.threadId;\n if (e.runId) summary.runId = e.runId;\n if (e.message) summary.message = e.message;\n if (e.code) summary.code = e.code;\n if (e.stepName) summary.stepName = e.stepName;\n\n return summary;\n}\n"],"mappings":";;;;;;;AAoBA,SAAgB,uBAAuB,EACrC,SACA,mBACA,OACA,UACyC;CACzC,MAAM,SAAS,IAAI,iBAAiB;CACpC,MAAM,SAAS,OAAO,SAAS,WAAW;CAC1C,MAAM,UAAU,IAAIA,6BAAc;CAClC,IAAI,eAAe;CAEnB,MAAM,cAAc,OAAO,UACtB,UACDC,4BAAa;EAAE,OAAO;EAAS,WAAW;EAAoB,CAAC,GAC/D;CAEJ,MAAM,cAAc,YAAY;AAC9B,MAAI,CAAC,aACH,KAAI;AACF,SAAM,OAAO,OAAO;AACpB,kBAAe;UACT;;CAMZ,MAAM,YAAY,UAAmB;AACnC,UAAQ,MAAM,wBAAwB,MAAM;AAC5C,UAAQ,MACN,gBACA,iBAAiB,QAAQ,MAAM,QAAQ,iBACxC;AACD,UAAQ,MAAM,kBAAkB;GAC9B,MAAM,iBAAiB,QAAQ,MAAM,OAAO;GAC5C,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAC/D,OAAO,iBAAiB,QAAQ,MAAM,QAAQ;GAC/C,CAAC;;CAGJ,IAAI;AAEJ,EAAC,YAAY;EACX,MAAM,aAAa,MAAM,mBAA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AAC;;AAGJ,SAAS,eAAe,OAA2C;CACjE,MAAM,IAAI;CACV,MAAM,UAAmC,EAAE;AAE3C,KAAI,EAAE,UAAW,SAAQ,YAAY,EAAE;AACvC,KAAI,EAAE,WAAY,SAAQ,aAAa,EAAE;AACzC,KAAI,EAAE,aAAc,SAAQ,eAAe,EAAE;AAC7C,KAAI,EAAE,KAAM,SAAQ,OAAO,EAAE;AAC7B,KAAI,EAAE,SAAS,QAAQ,OAAO,EAAE,UAAU,SACxC,SAAQ,cAAc,EAAE,MAAM;AAChC,KAAI,EAAE,YAAY,OAAO,EAAE,aAAa,SACtC,SAAQ,eAAe,OAAO,KAAK,EAAE,SAAS;AAChD,KAAI,EAAE,SAAS,MAAM,QAAQ,EAAE,MAAM,CACnC,SAAQ,iBAAiB,EAAE,MAAM;AACnC,KAAI,EAAE,SAAU,SAAQ,WAAW,EAAE;AACrC,KAAI,EAAE,MAAO,SAAQ,QAAQ,EAAE;AAC/B,KAAI,EAAE,QAAS,SAAQ,UAAU,EAAE;AACnC,KAAI,EAAE,KAAM,SAAQ,OAAO,EAAE;AAC7B,KAAI,EAAE,SAAU,SAAQ,WAAW,EAAE;AAErC,QAAO"}
1
+ {"version":3,"file":"sse-response.cjs","names":["EventEncoder","createLogger"],"sources":["../../../../../src/v2/runtime/handlers/shared/sse-response.ts"],"sourcesContent":["import { BaseEvent } from \"@ag-ui/client\";\nimport { EventEncoder } from \"@ag-ui/encoder\";\nimport { Observable, Subscription } from \"rxjs\";\nimport { ResolvedDebugConfig } from \"@copilotkit/shared\";\nimport {\n createLogger,\n type CopilotRuntimeLogger,\n} from \"../../../../lib/logger\";\nimport { telemetry } from \"../../telemetry\";\nimport { DebugEventBus } from \"../../core/debug-event-bus\";\n\ninterface CreateSseEventResponseParams {\n request: Request;\n observableFactory: () =>\n | Promise<Observable<BaseEvent>>\n | Observable<BaseEvent>;\n debugEventBus?: DebugEventBus;\n agentId?: string;\n debug?: ResolvedDebugConfig;\n /** Pre-created logger instance to avoid creating a new pino logger per request. */\n logger?: CopilotRuntimeLogger;\n}\n\nexport function createSseEventResponse({\n request,\n observableFactory,\n debugEventBus,\n agentId,\n debug,\n logger,\n}: CreateSseEventResponseParams): Response {\n const stream = new TransformStream();\n const writer = stream.writable.getWriter();\n const encoder = new EventEncoder();\n let streamClosed = false;\n let debugThreadId = \"\";\n let debugRunId = \"\";\n\n const debugLogger = debug?.enabled\n ? (logger ??\n createLogger({ level: \"debug\", component: \"copilotkit-debug\" }))\n : undefined;\n\n const closeStream = async () => {\n if (!streamClosed) {\n try {\n await writer.close();\n streamClosed = true;\n } catch {\n // Stream already closed.\n }\n }\n };\n\n const logError = (error: unknown) => {\n console.error(\"Error running agent:\", error);\n console.error(\n \"Error stack:\",\n error instanceof Error ? error.stack : \"No stack trace\",\n );\n console.error(\"Error details:\", {\n name: error instanceof Error ? error.name : \"Unknown\",\n message: error instanceof Error ? error.message : String(error),\n cause: error instanceof Error ? error.cause : undefined,\n });\n };\n\n let subscription: Subscription | undefined;\n\n (async () => {\n const observable = await observableFactory();\n\n telemetry.capture(\"oss.runtime.agent_execution_stream_started\", {});\n\n if (debug?.lifecycle) {\n debugLogger!.debug(\"SSE stream opened\");\n }\n\n let eventCount = 0;\n let loggedEventCount = 0;\n\n subscription = observable.subscribe({\n next: async (event) => {\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 // Broadcast to debug listeners BEFORE the stream-closed gate below.\n // Intentional: debug subscribers (e.g. the VS Code Inspector panel)\n // should still receive trailing events after the SSE client for\n // this request closed its connection — they're independent\n // consumers observing the underlying runtime, not the request's\n // response stream.\n //\n // Wrapped in try/catch so a buggy debug subscriber can't propagate\n // an exception into this observer — if the throw reached the\n // `next` callback it would get routed to `error` by RxJS, closing\n // the SSE stream for an unrelated reason. Log via `logError` and\n // move on.\n if (debugEventBus) {\n try {\n debugEventBus.broadcast(event, {\n agentId: agentId ?? \"\",\n threadId: debugThreadId,\n runId: debugRunId,\n });\n } catch (broadcastError) {\n logError(broadcastError);\n }\n }\n\n if (!request.signal.aborted && !streamClosed) {\n try {\n eventCount++;\n if (debug?.events) {\n loggedEventCount++;\n if (debug.verbose) {\n debugLogger!.debug({ event }, \"Event emitted\");\n } else {\n debugLogger!.debug(\n { type: event.type, ...summarizeEvent(event) },\n \"Event emitted\",\n );\n }\n }\n await writer.write(encoder.encode(event));\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n streamClosed = true;\n } else {\n // Non-abort write failures (backpressure disconnects,\n // transform-stream exceptions, …) were previously swallowed\n // silently — `streamClosed` stayed `false` and the next\n // event re-attempted a broken writer. Log and mark the\n // stream closed so we stop trying.\n logError(error);\n streamClosed = true;\n }\n }\n }\n },\n error: async (error) => {\n telemetry.capture(\"oss.runtime.agent_execution_stream_errored\", {\n error: error instanceof Error ? error.message : String(error),\n });\n if (debug?.lifecycle) {\n debugLogger!.debug(\n { error: error instanceof Error ? error.message : String(error) },\n \"SSE stream errored\",\n );\n }\n logError(error);\n await closeStream();\n },\n complete: async () => {\n telemetry.capture(\"oss.runtime.agent_execution_stream_ended\", {});\n if (debug?.lifecycle) {\n debugLogger!.debug(\n { eventCount, loggedEventCount },\n \"SSE stream completed\",\n );\n }\n await closeStream();\n },\n });\n\n // If the client disconnected before the subscription was created,\n // unsubscribe immediately to avoid leaking the observable.\n if (request.signal.aborted) {\n subscription.unsubscribe();\n }\n })().catch(async (error) => {\n logError(error);\n await closeStream();\n });\n\n request.signal.addEventListener(\"abort\", () => {\n subscription?.unsubscribe();\n });\n\n return new Response(stream.readable, {\n status: 200,\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n },\n });\n}\n\nfunction summarizeEvent(event: BaseEvent): Record<string, unknown> {\n const e = event as any;\n const summary: Record<string, unknown> = {};\n\n if (e.messageId) summary.messageId = e.messageId;\n if (e.toolCallId) summary.toolCallId = e.toolCallId;\n if (e.toolCallName) summary.toolCallName = e.toolCallName;\n if (e.role) summary.role = e.role;\n if (e.delta != null && typeof e.delta === \"string\")\n summary.deltaLength = e.delta.length;\n if (e.snapshot && typeof e.snapshot === \"object\")\n summary.snapshotKeys = Object.keys(e.snapshot);\n if (e.delta && Array.isArray(e.delta))\n summary.operationCount = e.delta.length;\n if (e.threadId) summary.threadId = e.threadId;\n if (e.runId) summary.runId = e.runId;\n if (e.message) summary.message = e.message;\n if (e.code) summary.code = e.code;\n if (e.stepName) summary.stepName = e.stepName;\n\n return summary;\n}\n"],"mappings":";;;;;;;AAuBA,SAAgB,uBAAuB,EACrC,SACA,mBACA,eACA,SACA,OACA,UACyC;CACzC,MAAM,SAAS,IAAI,iBAAiB;CACpC,MAAM,SAAS,OAAO,SAAS,WAAW;CAC1C,MAAM,UAAU,IAAIA,6BAAc;CAClC,IAAI,eAAe;CACnB,IAAI,gBAAgB;CACpB,IAAI,aAAa;CAEjB,MAAM,cAAc,OAAO,UACtB,UACDC,4BAAa;EAAE,OAAO;EAAS,WAAW;EAAoB,CAAC,GAC/D;CAEJ,MAAM,cAAc,YAAY;AAC9B,MAAI,CAAC,aACH,KAAI;AACF,SAAM,OAAO,OAAO;AACpB,kBAAe;UACT;;CAMZ,MAAM,YAAY,UAAmB;AACnC,UAAQ,MAAM,wBAAwB,MAAM;AAC5C,UAAQ,MACN,gBACA,iBAAiB,QAAQ,MAAM,QAAQ,iBACxC;AACD,UAAQ,MAAM,kBAAkB;GAC9B,MAAM,iBAAiB,QAAQ,MAAM,OAAO;GAC5C,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAC/D,OAAO,iBAAiB,QAAQ,MAAM,QAAQ;GAC/C,CAAC;;CAGJ,IAAI;AAEJ,EAAC,YAAY;EACX,MAAM,aAAa,MAAM,mBAAmB;AAE5C,mCAAU,QAAQ,8CAA8C,EAAE,CAAC;AAEnE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AAU;AAC1B,WAAS,MAAM;AACf,QAAM,aAAa;GACnB;AAEF,SAAQ,OAAO,iBAAiB,eAAe;AAC7C,gBAAc,aAAa;GAC3B;AAEF,QAAO,IAAI,SAAS,OAAO,UAAU;EACnC,QAAQ;EACR,SAAS;GACP,gBAAgB;GAChB,iBAAiB;GACjB,YAAY;GACb;EACF,CAAC;;AAGJ,SAAS,eAAe,OAA2C;CACjE,MAAM,IAAI;CACV,MAAM,UAAmC,EAAE;AAE3C,KAAI,EAAE,UAAW,SAAQ,YAAY,EAAE;AACvC,KAAI,EAAE,WAAY,SAAQ,aAAa,EAAE;AACzC,KAAI,EAAE,aAAc,SAAQ,eAAe,EAAE;AAC7C,KAAI,EAAE,KAAM,SAAQ,OAAO,EAAE;AAC7B,KAAI,EAAE,SAAS,QAAQ,OAAO,EAAE,UAAU,SACxC,SAAQ,cAAc,EAAE,MAAM;AAChC,KAAI,EAAE,YAAY,OAAO,EAAE,aAAa,SACtC,SAAQ,eAAe,OAAO,KAAK,EAAE,SAAS;AAChD,KAAI,EAAE,SAAS,MAAM,QAAQ,EAAE,MAAM,CACnC,SAAQ,iBAAiB,EAAE,MAAM;AACnC,KAAI,EAAE,SAAU,SAAQ,WAAW,EAAE;AACrC,KAAI,EAAE,MAAO,SAAQ,QAAQ,EAAE;AAC/B,KAAI,EAAE,QAAS,SAAQ,UAAU,EAAE;AACnC,KAAI,EAAE,KAAM,SAAQ,OAAO,EAAE;AAC7B,KAAI,EAAE,SAAU,SAAQ,WAAW,EAAE;AAErC,QAAO"}
@@ -4,11 +4,13 @@ import telemetry from "../../telemetry/telemetry-client.mjs";
4
4
  import { EventEncoder } from "@ag-ui/encoder";
5
5
 
6
6
  //#region src/v2/runtime/handlers/shared/sse-response.ts
7
- function createSseEventResponse({ request, observableFactory, debug, logger }) {
7
+ function createSseEventResponse({ request, observableFactory, debugEventBus, agentId, debug, logger }) {
8
8
  const stream = new TransformStream();
9
9
  const writer = stream.writable.getWriter();
10
10
  const encoder = new EventEncoder();
11
11
  let streamClosed = false;
12
+ let debugThreadId = "";
13
+ let debugRunId = "";
12
14
  const debugLogger = debug?.enabled ? logger ?? createLogger({
13
15
  level: "debug",
14
16
  component: "copilotkit-debug"
@@ -37,6 +39,20 @@ function createSseEventResponse({ request, observableFactory, debug, logger }) {
37
39
  let loggedEventCount = 0;
38
40
  subscription = observable.subscribe({
39
41
  next: async (event) => {
42
+ if (event.type === "RUN_STARTED") {
43
+ const e = event;
44
+ debugThreadId = e.threadId ?? "";
45
+ debugRunId = e.runId ?? "";
46
+ }
47
+ if (debugEventBus) try {
48
+ debugEventBus.broadcast(event, {
49
+ agentId: agentId ?? "",
50
+ threadId: debugThreadId,
51
+ runId: debugRunId
52
+ });
53
+ } catch (broadcastError) {
54
+ logError(broadcastError);
55
+ }
40
56
  if (!request.signal.aborted && !streamClosed) try {
41
57
  eventCount++;
42
58
  if (debug?.events) {
@@ -50,6 +66,10 @@ function createSseEventResponse({ request, observableFactory, debug, logger }) {
50
66
  await writer.write(encoder.encode(event));
51
67
  } catch (error) {
52
68
  if (error instanceof Error && error.name === "AbortError") streamClosed = true;
69
+ else {
70
+ logError(error);
71
+ streamClosed = true;
72
+ }
53
73
  }
54
74
  },
55
75
  error: async (error) => {
@@ -1 +1 @@
1
- {"version":3,"file":"sse-response.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/shared/sse-response.ts"],"sourcesContent":["import { BaseEvent } from \"@ag-ui/client\";\nimport { EventEncoder } from \"@ag-ui/encoder\";\nimport { Observable, Subscription } from \"rxjs\";\nimport { ResolvedDebugConfig } from \"@copilotkit/shared\";\nimport {\n createLogger,\n type CopilotRuntimeLogger,\n} from \"../../../../lib/logger\";\nimport { telemetry } from \"../../telemetry\";\n\ninterface CreateSseEventResponseParams {\n request: Request;\n observableFactory: () =>\n | Promise<Observable<BaseEvent>>\n | Observable<BaseEvent>;\n debug?: ResolvedDebugConfig;\n /** Pre-created logger instance to avoid creating a new pino logger per request. */\n logger?: CopilotRuntimeLogger;\n}\n\nexport function createSseEventResponse({\n request,\n observableFactory,\n debug,\n logger,\n}: CreateSseEventResponseParams): Response {\n const stream = new TransformStream();\n const writer = stream.writable.getWriter();\n const encoder = new EventEncoder();\n let streamClosed = false;\n\n const debugLogger = debug?.enabled\n ? (logger ??\n createLogger({ level: \"debug\", component: \"copilotkit-debug\" }))\n : undefined;\n\n const closeStream = async () => {\n if (!streamClosed) {\n try {\n await writer.close();\n streamClosed = true;\n } catch {\n // Stream already closed.\n }\n }\n };\n\n const logError = (error: unknown) => {\n console.error(\"Error running agent:\", error);\n console.error(\n \"Error stack:\",\n error instanceof Error ? error.stack : \"No stack trace\",\n );\n console.error(\"Error details:\", {\n name: error instanceof Error ? error.name : \"Unknown\",\n message: error instanceof Error ? error.message : String(error),\n cause: error instanceof Error ? error.cause : undefined,\n });\n };\n\n let subscription: Subscription | undefined;\n\n (async () => {\n const observable = await observableFactory();\n\n telemetry.capture(\"oss.runtime.agent_execution_stream_started\", {});\n\n if (debug?.lifecycle) {\n debugLogger!.debug(\"SSE stream opened\");\n }\n\n let eventCount = 0;\n let loggedEventCount = 0;\n\n subscription = observable.subscribe({\n next: async (event) => {\n if (!request.signal.aborted && !streamClosed) {\n try {\n eventCount++;\n if (debug?.events) {\n loggedEventCount++;\n if (debug.verbose) {\n debugLogger!.debug({ event }, \"Event emitted\");\n } else {\n debugLogger!.debug(\n { type: event.type, ...summarizeEvent(event) },\n \"Event emitted\",\n );\n }\n }\n await writer.write(encoder.encode(event));\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n streamClosed = true;\n }\n }\n }\n },\n error: async (error) => {\n telemetry.capture(\"oss.runtime.agent_execution_stream_errored\", {\n error: error instanceof Error ? error.message : String(error),\n });\n if (debug?.lifecycle) {\n debugLogger!.debug(\n { error: error instanceof Error ? error.message : String(error) },\n \"SSE stream errored\",\n );\n }\n logError(error);\n await closeStream();\n },\n complete: async () => {\n telemetry.capture(\"oss.runtime.agent_execution_stream_ended\", {});\n if (debug?.lifecycle) {\n debugLogger!.debug(\n { eventCount, loggedEventCount },\n \"SSE stream completed\",\n );\n }\n await closeStream();\n },\n });\n\n // If the client disconnected before the subscription was created,\n // unsubscribe immediately to avoid leaking the observable.\n if (request.signal.aborted) {\n subscription.unsubscribe();\n }\n })().catch(async (error) => {\n logError(error);\n await closeStream();\n });\n\n request.signal.addEventListener(\"abort\", () => {\n subscription?.unsubscribe();\n });\n\n return new Response(stream.readable, {\n status: 200,\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n },\n });\n}\n\nfunction summarizeEvent(event: BaseEvent): Record<string, unknown> {\n const e = event as any;\n const summary: Record<string, unknown> = {};\n\n if (e.messageId) summary.messageId = e.messageId;\n if (e.toolCallId) summary.toolCallId = e.toolCallId;\n if (e.toolCallName) summary.toolCallName = e.toolCallName;\n if (e.role) summary.role = e.role;\n if (e.delta != null && typeof e.delta === \"string\")\n summary.deltaLength = e.delta.length;\n if (e.snapshot && typeof e.snapshot === \"object\")\n summary.snapshotKeys = Object.keys(e.snapshot);\n if (e.delta && Array.isArray(e.delta))\n summary.operationCount = e.delta.length;\n if (e.threadId) summary.threadId = e.threadId;\n if (e.runId) summary.runId = e.runId;\n if (e.message) summary.message = e.message;\n if (e.code) summary.code = e.code;\n if (e.stepName) summary.stepName = e.stepName;\n\n return summary;\n}\n"],"mappings":";;;;;;AAoBA,SAAgB,uBAAuB,EACrC,SACA,mBACA,OACA,UACyC;CACzC,MAAM,SAAS,IAAI,iBAAiB;CACpC,MAAM,SAAS,OAAO,SAAS,WAAW;CAC1C,MAAM,UAAU,IAAI,cAAc;CAClC,IAAI,eAAe;CAEnB,MAAM,cAAc,OAAO,UACtB,UACD,aAAa;EAAE,OAAO;EAAS,WAAW;EAAoB,CAAC,GAC/D;CAEJ,MAAM,cAAc,YAAY;AAC9B,MAAI,CAAC,aACH,KAAI;AACF,SAAM,OAAO,OAAO;AACpB,kBAAe;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Aa,MACX;KAAE;KAAY;KAAkB,EAChC,uBACD;AAEH,UAAM,aAAa;;GAEtB,CAAC;AAIF,MAAI,QAAQ,OAAO,QACjB,cAAa,aAAa;KAE1B,CAAC,MAAM,OAAO,UAAU;AAC1B,WAAS,MAAM;AACf,QAAM,aAAa;GACnB;AAEF,SAAQ,OAAO,iBAAiB,eAAe;AAC7C,gBAAc,aAAa;GAC3B;AAEF,QAAO,IAAI,SAAS,OAAO,UAAU;EACnC,QAAQ;EACR,SAAS;GACP,gBAAgB;GAChB,iBAAiB;GACjB,YAAY;GACb;EACF,CAAC;;AAGJ,SAAS,eAAe,OAA2C;CACjE,MAAM,IAAI;CACV,MAAM,UAAmC,EAAE;AAE3C,KAAI,EAAE,UAAW,SAAQ,YAAY,EAAE;AACvC,KAAI,EAAE,WAAY,SAAQ,aAAa,EAAE;AACzC,KAAI,EAAE,aAAc,SAAQ,eAAe,EAAE;AAC7C,KAAI,EAAE,KAAM,SAAQ,OAAO,EAAE;AAC7B,KAAI,EAAE,SAAS,QAAQ,OAAO,EAAE,UAAU,SACxC,SAAQ,cAAc,EAAE,MAAM;AAChC,KAAI,EAAE,YAAY,OAAO,EAAE,aAAa,SACtC,SAAQ,eAAe,OAAO,KAAK,EAAE,SAAS;AAChD,KAAI,EAAE,SAAS,MAAM,QAAQ,EAAE,MAAM,CACnC,SAAQ,iBAAiB,EAAE,MAAM;AACnC,KAAI,EAAE,SAAU,SAAQ,WAAW,EAAE;AACrC,KAAI,EAAE,MAAO,SAAQ,QAAQ,EAAE;AAC/B,KAAI,EAAE,QAAS,SAAQ,UAAU,EAAE;AACnC,KAAI,EAAE,KAAM,SAAQ,OAAO,EAAE;AAC7B,KAAI,EAAE,SAAU,SAAQ,WAAW,EAAE;AAErC,QAAO"}
1
+ {"version":3,"file":"sse-response.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/shared/sse-response.ts"],"sourcesContent":["import { BaseEvent } from \"@ag-ui/client\";\nimport { EventEncoder } from \"@ag-ui/encoder\";\nimport { Observable, Subscription } from \"rxjs\";\nimport { ResolvedDebugConfig } from \"@copilotkit/shared\";\nimport {\n createLogger,\n type CopilotRuntimeLogger,\n} from \"../../../../lib/logger\";\nimport { telemetry } from \"../../telemetry\";\nimport { DebugEventBus } from \"../../core/debug-event-bus\";\n\ninterface CreateSseEventResponseParams {\n request: Request;\n observableFactory: () =>\n | Promise<Observable<BaseEvent>>\n | Observable<BaseEvent>;\n debugEventBus?: DebugEventBus;\n agentId?: string;\n debug?: ResolvedDebugConfig;\n /** Pre-created logger instance to avoid creating a new pino logger per request. */\n logger?: CopilotRuntimeLogger;\n}\n\nexport function createSseEventResponse({\n request,\n observableFactory,\n debugEventBus,\n agentId,\n debug,\n logger,\n}: CreateSseEventResponseParams): Response {\n const stream = new TransformStream();\n const writer = stream.writable.getWriter();\n const encoder = new EventEncoder();\n let streamClosed = false;\n let debugThreadId = \"\";\n let debugRunId = \"\";\n\n const debugLogger = debug?.enabled\n ? (logger ??\n createLogger({ level: \"debug\", component: \"copilotkit-debug\" }))\n : undefined;\n\n const closeStream = async () => {\n if (!streamClosed) {\n try {\n await writer.close();\n streamClosed = true;\n } catch {\n // Stream already closed.\n }\n }\n };\n\n const logError = (error: unknown) => {\n console.error(\"Error running agent:\", error);\n console.error(\n \"Error stack:\",\n error instanceof Error ? error.stack : \"No stack trace\",\n );\n console.error(\"Error details:\", {\n name: error instanceof Error ? error.name : \"Unknown\",\n message: error instanceof Error ? error.message : String(error),\n cause: error instanceof Error ? error.cause : undefined,\n });\n };\n\n let subscription: Subscription | undefined;\n\n (async () => {\n const observable = await observableFactory();\n\n telemetry.capture(\"oss.runtime.agent_execution_stream_started\", {});\n\n if (debug?.lifecycle) {\n debugLogger!.debug(\"SSE stream opened\");\n }\n\n let eventCount = 0;\n let loggedEventCount = 0;\n\n subscription = observable.subscribe({\n next: async (event) => {\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 // Broadcast to debug listeners BEFORE the stream-closed gate below.\n // Intentional: debug subscribers (e.g. the VS Code Inspector panel)\n // should still receive trailing events after the SSE client for\n // this request closed its connection — they're independent\n // consumers observing the underlying runtime, not the request's\n // response stream.\n //\n // Wrapped in try/catch so a buggy debug subscriber can't propagate\n // an exception into this observer — if the throw reached the\n // `next` callback it would get routed to `error` by RxJS, closing\n // the SSE stream for an unrelated reason. Log via `logError` and\n // move on.\n if (debugEventBus) {\n try {\n debugEventBus.broadcast(event, {\n agentId: agentId ?? \"\",\n threadId: debugThreadId,\n runId: debugRunId,\n });\n } catch (broadcastError) {\n logError(broadcastError);\n }\n }\n\n if (!request.signal.aborted && !streamClosed) {\n try {\n eventCount++;\n if (debug?.events) {\n loggedEventCount++;\n if (debug.verbose) {\n debugLogger!.debug({ event }, \"Event emitted\");\n } else {\n debugLogger!.debug(\n { type: event.type, ...summarizeEvent(event) },\n \"Event emitted\",\n );\n }\n }\n await writer.write(encoder.encode(event));\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n streamClosed = true;\n } else {\n // Non-abort write failures (backpressure disconnects,\n // transform-stream exceptions, …) were previously swallowed\n // silently — `streamClosed` stayed `false` and the next\n // event re-attempted a broken writer. Log and mark the\n // stream closed so we stop trying.\n logError(error);\n streamClosed = true;\n }\n }\n }\n },\n error: async (error) => {\n telemetry.capture(\"oss.runtime.agent_execution_stream_errored\", {\n error: error instanceof Error ? error.message : String(error),\n });\n if (debug?.lifecycle) {\n debugLogger!.debug(\n { error: error instanceof Error ? error.message : String(error) },\n \"SSE stream errored\",\n );\n }\n logError(error);\n await closeStream();\n },\n complete: async () => {\n telemetry.capture(\"oss.runtime.agent_execution_stream_ended\", {});\n if (debug?.lifecycle) {\n debugLogger!.debug(\n { eventCount, loggedEventCount },\n \"SSE stream completed\",\n );\n }\n await closeStream();\n },\n });\n\n // If the client disconnected before the subscription was created,\n // unsubscribe immediately to avoid leaking the observable.\n if (request.signal.aborted) {\n subscription.unsubscribe();\n }\n })().catch(async (error) => {\n logError(error);\n await closeStream();\n });\n\n request.signal.addEventListener(\"abort\", () => {\n subscription?.unsubscribe();\n });\n\n return new Response(stream.readable, {\n status: 200,\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n },\n });\n}\n\nfunction summarizeEvent(event: BaseEvent): Record<string, unknown> {\n const e = event as any;\n const summary: Record<string, unknown> = {};\n\n if (e.messageId) summary.messageId = e.messageId;\n if (e.toolCallId) summary.toolCallId = e.toolCallId;\n if (e.toolCallName) summary.toolCallName = e.toolCallName;\n if (e.role) summary.role = e.role;\n if (e.delta != null && typeof e.delta === \"string\")\n summary.deltaLength = e.delta.length;\n if (e.snapshot && typeof e.snapshot === \"object\")\n summary.snapshotKeys = Object.keys(e.snapshot);\n if (e.delta && Array.isArray(e.delta))\n summary.operationCount = e.delta.length;\n if (e.threadId) summary.threadId = e.threadId;\n if (e.runId) summary.runId = e.runId;\n if (e.message) summary.message = e.message;\n if (e.code) summary.code = e.code;\n if (e.stepName) summary.stepName = e.stepName;\n\n return summary;\n}\n"],"mappings":";;;;;;AAuBA,SAAgB,uBAAuB,EACrC,SACA,mBACA,eACA,SACA,OACA,UACyC;CACzC,MAAM,SAAS,IAAI,iBAAiB;CACpC,MAAM,SAAS,OAAO,SAAS,WAAW;CAC1C,MAAM,UAAU,IAAI,cAAc;CAClC,IAAI,eAAe;CACnB,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,aACH,KAAI;AACF,SAAM,OAAO,OAAO;AACpB,kBAAe;UACT;;CAMZ,MAAM,YAAY,UAAmB;AACnC,UAAQ,MAAM,wBAAwB,MAAM;AAC5C,UA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AAC7B,KAAI,EAAE,SAAU,SAAQ,WAAW,EAAE;AAErC,QAAO"}
@@ -3,9 +3,11 @@ const require_header_utils = require('../header-utils.cjs');
3
3
  const require_sse_response = require('../shared/sse-response.cjs');
4
4
 
5
5
  //#region src/v2/runtime/handlers/sse/connect.ts
6
- function handleSseConnect({ runtime, request, threadId }) {
6
+ function handleSseConnect({ runtime, request, agentId, threadId }) {
7
7
  return require_sse_response.createSseEventResponse({
8
8
  request,
9
+ debugEventBus: runtime.debugEventBus,
10
+ agentId,
9
11
  observableFactory: () => runtime.runner.connect({
10
12
  threadId,
11
13
  headers: require_header_utils.extractForwardableHeaders(request)
@@ -1 +1 @@
1
- {"version":3,"file":"connect.cjs","names":["createSseEventResponse","extractForwardableHeaders"],"sources":["../../../../../src/v2/runtime/handlers/sse/connect.ts"],"sourcesContent":["import { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { createSseEventResponse } from \"../shared/sse-response\";\nimport { extractForwardableHeaders } from \"../header-utils\";\n\ninterface HandleSseConnectParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n threadId: string;\n}\n\nexport function handleSseConnect({\n runtime,\n request,\n threadId,\n}: HandleSseConnectParams): Response {\n return createSseEventResponse({\n request,\n observableFactory: () =>\n runtime.runner.connect({\n threadId,\n headers: extractForwardableHeaders(request),\n }),\n });\n}\n"],"mappings":";;;;;AAUA,SAAgB,iBAAiB,EAC/B,SACA,SACA,YACmC;AACnC,QAAOA,4CAAuB;EAC5B;EACA,yBACE,QAAQ,OAAO,QAAQ;GACrB;GACA,SAASC,+CAA0B,QAAQ;GAC5C,CAAC;EACL,CAAC"}
1
+ {"version":3,"file":"connect.cjs","names":["createSseEventResponse","extractForwardableHeaders"],"sources":["../../../../../src/v2/runtime/handlers/sse/connect.ts"],"sourcesContent":["import { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { createSseEventResponse } from \"../shared/sse-response\";\nimport { extractForwardableHeaders } from \"../header-utils\";\n\ninterface HandleSseConnectParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n agentId: string;\n threadId: string;\n}\n\nexport function handleSseConnect({\n runtime,\n request,\n agentId,\n threadId,\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 observableFactory: () =>\n runtime.runner.connect({\n threadId,\n headers: extractForwardableHeaders(request),\n }),\n });\n}\n"],"mappings":";;;;;AAWA,SAAgB,iBAAiB,EAC/B,SACA,SACA,SACA,YACmC;AACnC,QAAOA,4CAAuB;EAC5B;EACA,eAAe,QAAQ;EAGvB;EACA,yBACE,QAAQ,OAAO,QAAQ;GACrB;GACA,SAASC,+CAA0B,QAAQ;GAC5C,CAAC;EACL,CAAC"}
@@ -3,9 +3,11 @@ import { extractForwardableHeaders } from "../header-utils.mjs";
3
3
  import { createSseEventResponse } from "../shared/sse-response.mjs";
4
4
 
5
5
  //#region src/v2/runtime/handlers/sse/connect.ts
6
- function handleSseConnect({ runtime, request, threadId }) {
6
+ function handleSseConnect({ runtime, request, agentId, threadId }) {
7
7
  return createSseEventResponse({
8
8
  request,
9
+ debugEventBus: runtime.debugEventBus,
10
+ agentId,
9
11
  observableFactory: () => runtime.runner.connect({
10
12
  threadId,
11
13
  headers: extractForwardableHeaders(request)
@@ -1 +1 @@
1
- {"version":3,"file":"connect.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/sse/connect.ts"],"sourcesContent":["import { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { createSseEventResponse } from \"../shared/sse-response\";\nimport { extractForwardableHeaders } from \"../header-utils\";\n\ninterface HandleSseConnectParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n threadId: string;\n}\n\nexport function handleSseConnect({\n runtime,\n request,\n threadId,\n}: HandleSseConnectParams): Response {\n return createSseEventResponse({\n request,\n observableFactory: () =>\n runtime.runner.connect({\n threadId,\n headers: extractForwardableHeaders(request),\n }),\n });\n}\n"],"mappings":";;;;;AAUA,SAAgB,iBAAiB,EAC/B,SACA,SACA,YACmC;AACnC,QAAO,uBAAuB;EAC5B;EACA,yBACE,QAAQ,OAAO,QAAQ;GACrB;GACA,SAAS,0BAA0B,QAAQ;GAC5C,CAAC;EACL,CAAC"}
1
+ {"version":3,"file":"connect.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/sse/connect.ts"],"sourcesContent":["import { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { createSseEventResponse } from \"../shared/sse-response\";\nimport { extractForwardableHeaders } from \"../header-utils\";\n\ninterface HandleSseConnectParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n agentId: string;\n threadId: string;\n}\n\nexport function handleSseConnect({\n runtime,\n request,\n agentId,\n threadId,\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 observableFactory: () =>\n runtime.runner.connect({\n threadId,\n headers: extractForwardableHeaders(request),\n }),\n });\n}\n"],"mappings":";;;;;AAWA,SAAgB,iBAAiB,EAC/B,SACA,SACA,SACA,YACmC;AACnC,QAAO,uBAAuB;EAC5B;EACA,eAAe,QAAQ;EAGvB;EACA,yBACE,QAAQ,OAAO,QAAQ;GACrB;GACA,SAAS,0BAA0B,QAAQ;GAC5C,CAAC;EACL,CAAC"}
@@ -2,9 +2,11 @@ require("reflect-metadata");
2
2
  const require_sse_response = require('../shared/sse-response.cjs');
3
3
 
4
4
  //#region src/v2/runtime/handlers/sse/run.ts
5
- function handleSseRun({ runtime, request, agent, input, debug, logger }) {
5
+ function handleSseRun({ runtime, request, agent, input, agentId, debug, logger }) {
6
6
  return require_sse_response.createSseEventResponse({
7
7
  request,
8
+ debugEventBus: runtime.debugEventBus,
9
+ agentId,
8
10
  debug,
9
11
  logger,
10
12
  observableFactory: () => runtime.runner.run({
@@ -1 +1 @@
1
- {"version":3,"file":"run.cjs","names":["createSseEventResponse"],"sources":["../../../../../src/v2/runtime/handlers/sse/run.ts"],"sourcesContent":["import { AbstractAgent, RunAgentInput } from \"@ag-ui/client\";\nimport { ResolvedDebugConfig } from \"@copilotkit/shared\";\nimport { type CopilotRuntimeLogger } from \"../../../../lib/logger\";\nimport { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { createSseEventResponse } from \"../shared/sse-response\";\n\ninterface HandleSseRunParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n agent: AbstractAgent;\n input: RunAgentInput;\n debug?: ResolvedDebugConfig;\n /** Pre-created logger instance to avoid creating a new pino logger per request. */\n logger?: CopilotRuntimeLogger;\n}\n\nexport function handleSseRun({\n runtime,\n request,\n agent,\n input,\n debug,\n logger,\n}: HandleSseRunParams): Response {\n return createSseEventResponse({\n request,\n debug,\n logger,\n observableFactory: () =>\n runtime.runner.run({\n threadId: input.threadId,\n agent,\n input,\n }),\n });\n}\n"],"mappings":";;;;AAgBA,SAAgB,aAAa,EAC3B,SACA,SACA,OACA,OACA,OACA,UAC+B;AAC/B,QAAOA,4CAAuB;EAC5B;EACA;EACA;EACA,yBACE,QAAQ,OAAO,IAAI;GACjB,UAAU,MAAM;GAChB;GACA;GACD,CAAC;EACL,CAAC"}
1
+ {"version":3,"file":"run.cjs","names":["createSseEventResponse"],"sources":["../../../../../src/v2/runtime/handlers/sse/run.ts"],"sourcesContent":["import { AbstractAgent, RunAgentInput } from \"@ag-ui/client\";\nimport { ResolvedDebugConfig } from \"@copilotkit/shared\";\nimport { type CopilotRuntimeLogger } from \"../../../../lib/logger\";\nimport { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { createSseEventResponse } from \"../shared/sse-response\";\n\ninterface HandleSseRunParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n agent: AbstractAgent;\n input: RunAgentInput;\n agentId: string;\n debug?: ResolvedDebugConfig;\n /** Pre-created logger instance to avoid creating a new pino logger per request. */\n logger?: CopilotRuntimeLogger;\n}\n\nexport function handleSseRun({\n runtime,\n request,\n agent,\n input,\n agentId,\n debug,\n logger,\n}: HandleSseRunParams): Response {\n return createSseEventResponse({\n request,\n debugEventBus: runtime.debugEventBus,\n agentId,\n debug,\n logger,\n observableFactory: () =>\n runtime.runner.run({\n threadId: input.threadId,\n agent,\n input,\n }),\n });\n}\n"],"mappings":";;;;AAiBA,SAAgB,aAAa,EAC3B,SACA,SACA,OACA,OACA,SACA,OACA,UAC+B;AAC/B,QAAOA,4CAAuB;EAC5B;EACA,eAAe,QAAQ;EACvB;EACA;EACA;EACA,yBACE,QAAQ,OAAO,IAAI;GACjB,UAAU,MAAM;GAChB;GACA;GACD,CAAC;EACL,CAAC"}