@copilotkit/runtime 2.0.0-rc.2 → 2.0.0-rc.20
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.
- package/README.md +19 -1
- package/dist/agent/converters/aisdk.cjs +0 -1
- package/dist/agent/converters/aisdk.cjs.map +1 -1
- package/dist/agent/converters/tanstack.cjs +1 -2
- package/dist/agent/converters/tanstack.cjs.map +1 -1
- package/dist/agent/converters/tanstack.mjs +1 -1
- package/dist/agent/converters/tanstack.mjs.map +1 -1
- package/dist/agent/index.cjs +23 -33
- package/dist/agent/index.cjs.map +1 -1
- package/dist/agent/index.d.cts +1 -9
- package/dist/agent/index.d.cts.map +1 -1
- package/dist/agent/index.d.mts +1 -9
- package/dist/agent/index.d.mts.map +1 -1
- package/dist/agent/index.mjs +25 -33
- package/dist/agent/index.mjs.map +1 -1
- package/dist/agent/learned-skills.cjs +0 -1
- package/dist/agent/learned-skills.cjs.map +1 -1
- package/dist/agent/state-delta.cjs +0 -1
- package/dist/agent/state-delta.cjs.map +1 -1
- package/dist/agent/url-download.cjs +10 -12
- package/dist/agent/url-download.cjs.map +1 -1
- package/dist/agent/url-download.d.cts.map +1 -1
- package/dist/agent/url-download.d.mts.map +1 -1
- package/dist/agent/url-download.mjs +10 -11
- package/dist/agent/url-download.mjs.map +1 -1
- package/dist/index.cjs +20 -10
- package/dist/index.d.cts +6 -3
- package/dist/index.d.mts +6 -3
- package/dist/index.mjs +5 -2
- package/dist/node.cjs +1 -2
- package/dist/node.d.cts +2 -2
- package/dist/node.d.mts +2 -2
- package/dist/node.mjs +2 -2
- package/dist/runtime/core/channel-manager.cjs +4 -5
- package/dist/runtime/core/channel-manager.cjs.map +1 -1
- package/dist/runtime/core/channel-manager.mjs +4 -4
- package/dist/runtime/core/channel-manager.mjs.map +1 -1
- package/dist/runtime/core/debug-event-bus.cjs +2 -1
- package/dist/runtime/core/debug-event-bus.cjs.map +1 -1
- package/dist/runtime/core/debug-event-bus.d.cts.map +1 -1
- package/dist/runtime/core/debug-event-bus.d.mts.map +1 -1
- package/dist/runtime/core/debug-event-bus.mjs +3 -1
- package/dist/runtime/core/debug-event-bus.mjs.map +1 -1
- package/dist/runtime/core/fetch-handler.cjs +3 -4
- package/dist/runtime/core/fetch-handler.cjs.map +1 -1
- package/dist/runtime/core/fetch-handler.mjs.map +1 -1
- package/dist/runtime/core/logger.cjs +86 -13
- package/dist/runtime/core/logger.cjs.map +1 -1
- package/dist/runtime/core/logger.d.cts +21 -8
- package/dist/runtime/core/logger.d.cts.map +1 -1
- package/dist/runtime/core/logger.d.mts +21 -8
- package/dist/runtime/core/logger.d.mts.map +1 -1
- package/dist/runtime/core/logger.mjs +86 -10
- package/dist/runtime/core/logger.mjs.map +1 -1
- package/dist/runtime/core/middleware-sse-parser.cjs +0 -1
- package/dist/runtime/core/middleware-sse-parser.cjs.map +1 -1
- package/dist/runtime/core/middleware.cjs +0 -1
- package/dist/runtime/core/middleware.cjs.map +1 -1
- package/dist/runtime/core/package-info.cjs +1 -1
- package/dist/runtime/core/package-info.mjs +1 -1
- package/dist/runtime/core/runtime.cjs +19 -6
- package/dist/runtime/core/runtime.cjs.map +1 -1
- package/dist/runtime/core/runtime.d.cts +19 -3
- package/dist/runtime/core/runtime.d.cts.map +1 -1
- package/dist/runtime/core/runtime.d.mts +20 -4
- package/dist/runtime/core/runtime.d.mts.map +1 -1
- package/dist/runtime/core/runtime.mjs +20 -6
- package/dist/runtime/core/runtime.mjs.map +1 -1
- package/dist/runtime/core/web-crypto.cjs +22 -0
- package/dist/runtime/core/web-crypto.cjs.map +1 -0
- package/dist/runtime/core/web-crypto.mjs +20 -0
- package/dist/runtime/core/web-crypto.mjs.map +1 -0
- package/dist/runtime/endpoints/auto-start-channels.cjs +0 -1
- package/dist/runtime/endpoints/auto-start-channels.cjs.map +1 -1
- package/dist/runtime/endpoints/node-fetch-handler.cjs +0 -4
- package/dist/runtime/endpoints/node-fetch-handler.cjs.map +1 -1
- package/dist/runtime/endpoints/node-fetch-handler.d.cts +1 -3
- package/dist/runtime/endpoints/node-fetch-handler.d.cts.map +1 -1
- package/dist/runtime/endpoints/node-fetch-handler.d.mts +1 -3
- package/dist/runtime/endpoints/node-fetch-handler.d.mts.map +1 -1
- package/dist/runtime/endpoints/node-fetch-handler.mjs +1 -3
- package/dist/runtime/endpoints/node-fetch-handler.mjs.map +1 -1
- package/dist/runtime/event-transforms/index.d.cts +4 -0
- package/dist/runtime/event-transforms/index.d.mts +4 -0
- package/dist/runtime/event-transforms/index.mjs +5 -0
- package/dist/runtime/event-transforms/open-generative-ui-middleware.cjs +277 -0
- package/dist/runtime/event-transforms/open-generative-ui-middleware.cjs.map +1 -0
- package/dist/runtime/event-transforms/open-generative-ui-middleware.d.cts +61 -0
- package/dist/runtime/event-transforms/open-generative-ui-middleware.d.cts.map +1 -0
- package/dist/runtime/event-transforms/open-generative-ui-middleware.d.mts +61 -0
- package/dist/runtime/event-transforms/open-generative-ui-middleware.d.mts.map +1 -0
- package/dist/runtime/event-transforms/open-generative-ui-middleware.mjs +276 -0
- package/dist/runtime/event-transforms/open-generative-ui-middleware.mjs.map +1 -0
- package/dist/runtime/event-transforms/recorded-events.cjs +58 -0
- package/dist/runtime/event-transforms/recorded-events.cjs.map +1 -0
- package/dist/runtime/event-transforms/recorded-events.d.cts +23 -0
- package/dist/runtime/event-transforms/recorded-events.d.cts.map +1 -0
- package/dist/runtime/event-transforms/recorded-events.d.mts +23 -0
- package/dist/runtime/event-transforms/recorded-events.d.mts.map +1 -0
- package/dist/runtime/event-transforms/recorded-events.mjs +58 -0
- package/dist/runtime/event-transforms/recorded-events.mjs.map +1 -0
- package/dist/runtime/event-transforms/streaming-json-scanner.cjs +289 -0
- package/dist/runtime/event-transforms/streaming-json-scanner.cjs.map +1 -0
- package/dist/runtime/event-transforms/streaming-json-scanner.mjs +288 -0
- package/dist/runtime/event-transforms/streaming-json-scanner.mjs.map +1 -0
- package/dist/runtime/generative-ui/generative-ui-middleware.cjs +0 -1
- package/dist/runtime/generative-ui/generative-ui-middleware.cjs.map +1 -1
- package/dist/runtime/generative-ui/surface-writer.cjs +4 -5
- package/dist/runtime/generative-ui/surface-writer.cjs.map +1 -1
- package/dist/runtime/generative-ui/surface-writer.d.cts.map +1 -1
- package/dist/runtime/generative-ui/surface-writer.d.mts.map +1 -1
- package/dist/runtime/generative-ui/surface-writer.mjs +5 -5
- package/dist/runtime/generative-ui/surface-writer.mjs.map +1 -1
- package/dist/runtime/handlers/get-runtime-info.cjs +7 -6
- package/dist/runtime/handlers/get-runtime-info.cjs.map +1 -1
- package/dist/runtime/handlers/get-runtime-info.mjs +7 -6
- package/dist/runtime/handlers/get-runtime-info.mjs.map +1 -1
- package/dist/runtime/handlers/handle-connect.cjs.map +1 -1
- package/dist/runtime/handlers/handle-connect.mjs.map +1 -1
- package/dist/runtime/handlers/handle-inspector-learning.cjs +2 -3
- package/dist/runtime/handlers/handle-inspector-learning.cjs.map +1 -1
- package/dist/runtime/handlers/handle-inspector-metadata.cjs +2 -3
- package/dist/runtime/handlers/handle-inspector-metadata.cjs.map +1 -1
- package/dist/runtime/handlers/handle-run.cjs +3 -4
- package/dist/runtime/handlers/handle-run.cjs.map +1 -1
- package/dist/runtime/handlers/handle-run.mjs.map +1 -1
- package/dist/runtime/handlers/handle-stop.cjs +3 -4
- package/dist/runtime/handlers/handle-stop.cjs.map +1 -1
- package/dist/runtime/handlers/handle-suggest.cjs +0 -1
- package/dist/runtime/handlers/handle-suggest.cjs.map +1 -1
- package/dist/runtime/handlers/handle-transcribe.cjs +0 -1
- package/dist/runtime/handlers/handle-transcribe.cjs.map +1 -1
- package/dist/runtime/handlers/intelligence/annotate.cjs +2 -3
- package/dist/runtime/handlers/intelligence/annotate.cjs.map +1 -1
- package/dist/runtime/handlers/intelligence/memories.cjs +7 -8
- package/dist/runtime/handlers/intelligence/memories.cjs.map +1 -1
- package/dist/runtime/handlers/intelligence/run.cjs +0 -1
- package/dist/runtime/handlers/intelligence/run.cjs.map +1 -1
- package/dist/runtime/handlers/intelligence/run.mjs.map +1 -1
- package/dist/runtime/handlers/intelligence/thread-names.cjs +3 -5
- package/dist/runtime/handlers/intelligence/thread-names.cjs.map +1 -1
- package/dist/runtime/handlers/intelligence/thread-names.mjs +3 -4
- package/dist/runtime/handlers/intelligence/thread-names.mjs.map +1 -1
- package/dist/runtime/handlers/intelligence/threads.cjs +6 -7
- package/dist/runtime/handlers/intelligence/threads.cjs.map +1 -1
- package/dist/runtime/handlers/intelligence/threads.mjs.map +1 -1
- package/dist/runtime/handlers/shared/agent-utils.cjs +10 -10
- package/dist/runtime/handlers/shared/agent-utils.cjs.map +1 -1
- package/dist/runtime/handlers/shared/agent-utils.mjs +4 -3
- package/dist/runtime/handlers/shared/agent-utils.mjs.map +1 -1
- package/dist/runtime/handlers/shared/cloud-telemetry.cjs +0 -1
- package/dist/runtime/handlers/shared/cloud-telemetry.cjs.map +1 -1
- package/dist/runtime/handlers/shared/resolve-intelligence-user.cjs +1 -1
- package/dist/runtime/handlers/shared/resolve-intelligence-user.cjs.map +1 -1
- package/dist/runtime/handlers/shared/resolve-intelligence-user.mjs +1 -1
- package/dist/runtime/handlers/shared/resolve-intelligence-user.mjs.map +1 -1
- package/dist/runtime/handlers/shared/sse-response.cjs +72 -64
- package/dist/runtime/handlers/shared/sse-response.cjs.map +1 -1
- package/dist/runtime/handlers/shared/sse-response.mjs +72 -63
- package/dist/runtime/handlers/shared/sse-response.mjs.map +1 -1
- package/dist/runtime/handlers/sse/run.cjs.map +1 -1
- package/dist/runtime/handlers/sse/run.mjs.map +1 -1
- package/dist/runtime/index.d.cts +4 -9
- package/dist/runtime/index.d.mts +4 -9
- package/dist/runtime/intelligence-platform/client.cjs +1 -3
- package/dist/runtime/intelligence-platform/client.cjs.map +1 -1
- package/dist/runtime/intelligence-platform/client.d.cts.map +1 -1
- package/dist/runtime/intelligence-platform/client.d.mts.map +1 -1
- package/dist/runtime/intelligence-platform/client.mjs +1 -2
- package/dist/runtime/intelligence-platform/client.mjs.map +1 -1
- package/dist/runtime/intelligence-platform/learning-management.cjs +7 -8
- package/dist/runtime/intelligence-platform/learning-management.cjs.map +1 -1
- package/dist/runtime/intelligence-platform/learning-management.mjs +7 -7
- package/dist/runtime/intelligence-platform/learning-management.mjs.map +1 -1
- package/dist/runtime/intelligence-platform/skill-registry/archive.cjs +104 -110
- package/dist/runtime/intelligence-platform/skill-registry/archive.cjs.map +1 -1
- package/dist/runtime/intelligence-platform/skill-registry/archive.d.cts +8 -2
- package/dist/runtime/intelligence-platform/skill-registry/archive.d.cts.map +1 -1
- package/dist/runtime/intelligence-platform/skill-registry/archive.d.mts +8 -2
- package/dist/runtime/intelligence-platform/skill-registry/archive.d.mts.map +1 -1
- package/dist/runtime/intelligence-platform/skill-registry/archive.mjs +104 -109
- package/dist/runtime/intelligence-platform/skill-registry/archive.mjs.map +1 -1
- package/dist/runtime/intelligence-platform/skill-registry/config.cjs +2 -1
- package/dist/runtime/intelligence-platform/skill-registry/config.cjs.map +1 -1
- package/dist/runtime/intelligence-platform/skill-registry/config.d.cts.map +1 -1
- package/dist/runtime/intelligence-platform/skill-registry/config.d.mts.map +1 -1
- package/dist/runtime/intelligence-platform/skill-registry/config.mjs +2 -1
- package/dist/runtime/intelligence-platform/skill-registry/config.mjs.map +1 -1
- package/dist/runtime/intelligence-platform/skill-registry/registry.cjs +26 -24
- package/dist/runtime/intelligence-platform/skill-registry/registry.cjs.map +1 -1
- package/dist/runtime/intelligence-platform/skill-registry/registry.d.cts.map +1 -1
- package/dist/runtime/intelligence-platform/skill-registry/registry.d.mts.map +1 -1
- package/dist/runtime/intelligence-platform/skill-registry/registry.mjs +26 -23
- package/dist/runtime/intelligence-platform/skill-registry/registry.mjs.map +1 -1
- package/dist/runtime/intelligence-platform/skill-registry/snapshot.cjs +3 -7
- package/dist/runtime/intelligence-platform/skill-registry/snapshot.cjs.map +1 -1
- package/dist/runtime/intelligence-platform/skill-registry/snapshot.d.cts.map +1 -1
- package/dist/runtime/intelligence-platform/skill-registry/snapshot.d.mts.map +1 -1
- package/dist/runtime/intelligence-platform/skill-registry/snapshot.mjs +3 -6
- package/dist/runtime/intelligence-platform/skill-registry/snapshot.mjs.map +1 -1
- package/dist/runtime/intelligence-platform/thread-lock-heartbeat.cjs +0 -1
- package/dist/runtime/intelligence-platform/thread-lock-heartbeat.cjs.map +1 -1
- package/dist/runtime/intelligence-platform/trajectories.cjs +2 -3
- package/dist/runtime/intelligence-platform/trajectories.cjs.map +1 -1
- package/dist/runtime/intelligence-platform/trajectories.mjs +2 -2
- package/dist/runtime/intelligence-platform/trajectories.mjs.map +1 -1
- package/dist/runtime/node.d.cts +1 -1
- package/dist/runtime/node.d.mts +1 -1
- package/dist/runtime/runner/agent-runner.cjs +0 -1
- package/dist/runtime/runner/agent-runner.cjs.map +1 -1
- package/dist/runtime/runner/in-memory.cjs +0 -1
- package/dist/runtime/runner/in-memory.cjs.map +1 -1
- package/dist/runtime/runner/intelligence.cjs +1 -3
- package/dist/runtime/runner/intelligence.cjs.map +1 -1
- package/dist/runtime/runner/intelligence.d.cts.map +1 -1
- package/dist/runtime/runner/intelligence.d.mts.map +1 -1
- package/dist/runtime/runner/intelligence.mjs +1 -2
- package/dist/runtime/runner/intelligence.mjs.map +1 -1
- package/dist/runtime/telemetry/disclosure.cjs +2 -1
- package/dist/runtime/telemetry/disclosure.cjs.map +1 -1
- package/dist/runtime/telemetry/disclosure.mjs +3 -1
- package/dist/runtime/telemetry/disclosure.mjs.map +1 -1
- package/dist/runtime/telemetry/instance-created.cjs +7 -9
- package/dist/runtime/telemetry/instance-created.cjs.map +1 -1
- package/dist/runtime/telemetry/instance-created.mjs +7 -9
- package/dist/runtime/telemetry/instance-created.mjs.map +1 -1
- package/dist/runtime/telemetry/telemetry-client.cjs +2 -7
- package/dist/runtime/telemetry/telemetry-client.cjs.map +1 -1
- package/dist/runtime/telemetry/telemetry-client.d.cts.map +1 -1
- package/dist/runtime/telemetry/telemetry-client.d.mts.map +1 -1
- package/dist/runtime/telemetry/telemetry-client.mjs +3 -7
- package/dist/runtime/telemetry/telemetry-client.mjs.map +1 -1
- package/dist/runtime/telemetry/telemetry-identity.cjs +0 -1
- package/dist/runtime/telemetry/telemetry-identity.cjs.map +1 -1
- package/package.json +10 -18
- package/dist/_virtual/_rolldown/runtime.cjs +0 -29
- package/dist/runtime/index.d.cts.map +0 -1
- package/dist/runtime/index.d.mts.map +0 -1
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
const require_runtime = require('../../../_virtual/_rolldown/runtime.cjs');
|
|
2
1
|
const require_sse_keep_alive = require('./sse-keep-alive.cjs');
|
|
3
2
|
const require_agent_runner = require('../../runner/agent-runner.cjs');
|
|
4
3
|
const require_logger = require('../../core/logger.cjs');
|
|
@@ -98,74 +97,83 @@ function createSseEventResponse({ request, observableFactory, debugEventBus, age
|
|
|
98
97
|
let eventCount = 0;
|
|
99
98
|
let loggedEventCount = 0;
|
|
100
99
|
const executionInfo = { ...executionSeed };
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
}, "Event emitted");
|
|
133
|
-
}
|
|
134
|
-
if (event.type === _ag_ui_client.EventType.RUN_STARTED) terminalEventWritten = false;
|
|
135
|
-
else if (event.type === _ag_ui_client.EventType.RUN_FINISHED || event.type === _ag_ui_client.EventType.RUN_ERROR) terminalEventWritten = true;
|
|
136
|
-
await writer.write(encoder.encodeBinary(event));
|
|
137
|
-
} catch (error) {
|
|
138
|
-
if (error instanceof Error && error.name === "AbortError") streamClosed = true;
|
|
139
|
-
else {
|
|
140
|
-
logError(error);
|
|
141
|
-
streamClosed = true;
|
|
142
|
-
}
|
|
100
|
+
const onNext = async (event) => {
|
|
101
|
+
collectExecutionInfo(event, executionInfo);
|
|
102
|
+
if (event.type === "RUN_STARTED") {
|
|
103
|
+
const e = event;
|
|
104
|
+
debugThreadId = e.threadId ?? "";
|
|
105
|
+
debugRunId = e.runId ?? "";
|
|
106
|
+
}
|
|
107
|
+
if (event.type === "RUN_ERROR") {
|
|
108
|
+
const e = event;
|
|
109
|
+
debugThreadId = e.threadId ?? debugThreadId;
|
|
110
|
+
debugRunId = e.runId ?? debugRunId;
|
|
111
|
+
reportAgentError(new Error(typeof e.message === "string" ? e.message : "Runner reported a run error"), "sse.subscription");
|
|
112
|
+
}
|
|
113
|
+
if (debugEventBus) try {
|
|
114
|
+
debugEventBus.broadcast(event, {
|
|
115
|
+
agentId: agentId ?? "",
|
|
116
|
+
threadId: debugThreadId,
|
|
117
|
+
runId: debugRunId
|
|
118
|
+
});
|
|
119
|
+
} catch (broadcastError) {
|
|
120
|
+
logError(broadcastError);
|
|
121
|
+
}
|
|
122
|
+
if (!request.signal.aborted && !streamClosed) try {
|
|
123
|
+
eventCount++;
|
|
124
|
+
if (debug?.events) {
|
|
125
|
+
loggedEventCount++;
|
|
126
|
+
if (debug.verbose) debugLogger.debug({ event }, "Event emitted");
|
|
127
|
+
else debugLogger.debug({
|
|
128
|
+
type: event.type,
|
|
129
|
+
...summarizeEvent(event)
|
|
130
|
+
}, "Event emitted");
|
|
143
131
|
}
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
132
|
+
if (event.type === _ag_ui_client.EventType.RUN_STARTED) terminalEventWritten = false;
|
|
133
|
+
else if (event.type === _ag_ui_client.EventType.RUN_FINISHED || event.type === _ag_ui_client.EventType.RUN_ERROR) terminalEventWritten = true;
|
|
134
|
+
await writer.write(encoder.encodeBinary(event));
|
|
135
|
+
} catch (error) {
|
|
136
|
+
if (error instanceof Error && error.name === "AbortError") streamClosed = true;
|
|
137
|
+
else {
|
|
138
|
+
logError(error);
|
|
139
|
+
streamClosed = true;
|
|
151
140
|
}
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
if (debug?.lifecycle) debugLogger.debug({ error: error instanceof Error ? error.message : String(error) }, "SSE stream errored");
|
|
158
|
-
logError(error);
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
const onError = async (error) => {
|
|
144
|
+
if (require_agent_runner.isThreadAccessDeniedError(error)) {
|
|
145
|
+
logAccessDenied(error);
|
|
159
146
|
await writeRunError(error);
|
|
160
147
|
await closeStream();
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
reportAgentError(error, "sse.subscription");
|
|
151
|
+
if (captureTelemetry) telemetry$1.capture("oss.runtime.agent_execution_stream_errored", {
|
|
152
|
+
...executionInfo,
|
|
153
|
+
error: "AGENT_EXECUTION_FAILED"
|
|
154
|
+
});
|
|
155
|
+
if (debug?.lifecycle) debugLogger.debug({ error: error instanceof Error ? error.message : String(error) }, "SSE stream errored");
|
|
156
|
+
logError(error);
|
|
157
|
+
await writeRunError(error);
|
|
158
|
+
await closeStream();
|
|
159
|
+
};
|
|
160
|
+
const onComplete = async () => {
|
|
161
|
+
if (captureTelemetry) telemetry$1.capture("oss.runtime.agent_execution_stream_ended", executionInfo);
|
|
162
|
+
if (debug?.lifecycle) debugLogger.debug({
|
|
163
|
+
eventCount,
|
|
164
|
+
loggedEventCount
|
|
165
|
+
}, "SSE stream completed");
|
|
166
|
+
await closeStream();
|
|
167
|
+
};
|
|
168
|
+
subscription = observable.subscribe({
|
|
169
|
+
next: (event) => {
|
|
170
|
+
onNext(event);
|
|
161
171
|
},
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
}, "SSE stream completed");
|
|
168
|
-
await closeStream();
|
|
172
|
+
error: (error) => {
|
|
173
|
+
onError(error);
|
|
174
|
+
},
|
|
175
|
+
complete: () => {
|
|
176
|
+
onComplete();
|
|
169
177
|
}
|
|
170
178
|
});
|
|
171
179
|
if (request.signal.aborted) subscription.unsubscribe();
|
|
@@ -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","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 pino logger per request. */\n logger?: CopilotRuntimeLogger;\n /** Runtime-bound telemetry capture. Falls back for external direct callers. */\n telemetry?: TelemetryCapture;\n /**\n * Execution facts known before the stream opens, merged under anything the\n * upstream reports as it runs. Carries `llmHostClass`, which is knowable\n * from the agent's configuration and never appears on a streamed event.\n */\n executionSeed?: AgentExecutionResponseInfo;\n /**\n * Whether to emit `oss.runtime.agent_execution_stream_*` telemetry for this\n * stream. Defaults to `true`. The stateless `/suggest` path sets this to\n * `false`: a suggestion is a side-effect-free structured completion, not a\n * tracked run, and under `available: \"always\"` it fires often enough to flood\n * run telemetry.\n */\n captureTelemetry?: boolean;\n runtimeErrorReporter?: RuntimeErrorReporter;\n startTime?: number;\n /**\n * Seconds of silence before a `: keep-alive` SSE comment is written.\n * `0` disables the keep-alive. Resolved by\n * {@link resolveSseKeepAliveIntervalSeconds}, which supplies the default\n * and enforces the timer bound for every caller.\n */\n keepAliveIntervalSeconds?: number;\n}\n\nexport function createSseEventResponse({\n request,\n observableFactory,\n debugEventBus,\n agentId,\n debug,\n logger,\n telemetry = defaultTelemetry,\n executionSeed,\n captureTelemetry = true,\n runtimeErrorReporter,\n startTime,\n keepAliveIntervalSeconds,\n}: CreateSseEventResponseParams): Response {\n const keepAliveSeconds = resolveSseKeepAliveIntervalSeconds(\n keepAliveIntervalSeconds,\n );\n const stream = new TransformStream();\n const writer = stream.writable.getWriter();\n const encoder = new EventEncoder();\n let streamClosed = false;\n // 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 telemetry.capture(\"oss.runtime.agent_execution_stream_started\", {});\n }\n\n if (debug?.lifecycle) {\n debugLogger!.debug(\"SSE stream opened\");\n }\n\n let eventCount = 0;\n let loggedEventCount = 0;\n\n // Provider/model/LangGraph facts, scraped off raw upstream events as\n // they pass and reported once the stream finishes. This moved here from\n // the v1 TelemetryAgentRunner, which wrapped the runner purely to\n // collect it and emitted its own duplicate copy of every stream event\n // to carry it. v2 callers had no equivalent and reported `{}`.\n // Seeded rather than empty: `llmHostClass` comes from the agent's config,\n // not from the wire, so nothing streamed will ever fill it in. Scraped\n // fields still win, since `collectExecutionInfo` writes over this.\n const executionInfo: AgentExecutionResponseInfo = { ...executionSeed };\n\n subscription = observable.subscribe({\n next: async (event) => {\n collectExecutionInfo(event, executionInfo);\n\n // Extract threadId/runId from RUN_STARTED\n if (event.type === \"RUN_STARTED\") {\n const e = event as { threadId?: string; runId?: string };\n debugThreadId = e.threadId ?? \"\";\n debugRunId = e.runId ?? \"\";\n }\n\n if (event.type === \"RUN_ERROR\") {\n const e = event as {\n message?: unknown;\n threadId?: string;\n runId?: string;\n };\n debugThreadId = e.threadId ?? debugThreadId;\n debugRunId = e.runId ?? debugRunId;\n reportAgentError(\n new Error(\n typeof e.message === \"string\"\n ? e.message\n : \"Runner reported a run error\",\n ),\n \"sse.subscription\",\n );\n }\n\n // Broadcast to debug listeners BEFORE the stream-closed gate below.\n // Intentional: debug subscribers (e.g. the VS Code Inspector panel)\n // should still receive trailing events after the SSE client for\n // this request closed its connection — they're independent\n // consumers observing the underlying runtime, not the request's\n // response stream.\n //\n // Wrapped in try/catch so a buggy debug subscriber can't propagate\n // an exception into this observer — if the throw reached the\n // `next` callback it would get routed to `error` by RxJS, closing\n // the SSE stream for an unrelated reason. Log via `logError` and\n // move on.\n if (debugEventBus) {\n try {\n debugEventBus.broadcast(event, {\n agentId: agentId ?? \"\",\n threadId: debugThreadId,\n runId: debugRunId,\n });\n } catch (broadcastError) {\n logError(broadcastError);\n }\n }\n\n if (!request.signal.aborted && !streamClosed) {\n try {\n eventCount++;\n if (debug?.events) {\n loggedEventCount++;\n if (debug.verbose) {\n debugLogger!.debug({ event }, \"Event emitted\");\n } else {\n debugLogger!.debug(\n { type: event.type, ...summarizeEvent(event) },\n \"Event emitted\",\n );\n }\n }\n // /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 error: async (error) => {\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 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 complete: async () => {\n if (captureTelemetry) {\n telemetry.capture(\n \"oss.runtime.agent_execution_stream_ended\",\n executionInfo,\n );\n }\n if (debug?.lifecycle) {\n debugLogger!.debug(\n { eventCount, loggedEventCount },\n \"SSE stream completed\",\n );\n }\n await closeStream();\n },\n });\n\n // If the client disconnected before the subscription was created,\n // unsubscribe immediately to avoid leaking the observable.\n if (request.signal.aborted) {\n subscription.unsubscribe();\n }\n })().catch(async (error) => {\n 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;;AAyCxB,SAAgB,uBAAuB,EACrC,SACA,mBACA,eACA,SACA,OACA,QACA,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,IAAI,uBAAuB;CAC3B,IAAI,gBAAgB;CACpB,IAAI,aAAa;CAEjB,MA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AAQ,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.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,iBAAiB,UACf,MAA6B,SAASA,wDACtC,MAAM,YAAY;;AAyCxB,SAAgB,uBAAuB,EACrC,SACA,mBACA,eACA,SACA,OACA,QACA,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,IAAI,uBAAuB;CAC3B,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;;CAYZ,MAAM,gBAAgB,OAAO,UAAmB;AAC9C,MAAI,wBAAwB,gBAAgB,QAAQ,OAAO,QACzD;AAEF,yBAAuB;EACvB,MAAM,QAAQ,uBAAuB,MAAM,GACvC;GACE,MAAMC,wBAAU;GAChB,SAAS;GACT,MAAML;GACP,GACDM,+CAA0B,MAAM,GAC9B;GACE,MAAMD,wBAAU;GAChB,SAAS;GACT,MAAME;GACP,GACD;GA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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"}
|
|
@@ -97,74 +97,83 @@ function createSseEventResponse({ request, observableFactory, debugEventBus, age
|
|
|
97
97
|
let eventCount = 0;
|
|
98
98
|
let loggedEventCount = 0;
|
|
99
99
|
const executionInfo = { ...executionSeed };
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
}, "Event emitted");
|
|
132
|
-
}
|
|
133
|
-
if (event.type === EventType.RUN_STARTED) terminalEventWritten = false;
|
|
134
|
-
else if (event.type === EventType.RUN_FINISHED || event.type === EventType.RUN_ERROR) terminalEventWritten = true;
|
|
135
|
-
await writer.write(encoder.encodeBinary(event));
|
|
136
|
-
} catch (error) {
|
|
137
|
-
if (error instanceof Error && error.name === "AbortError") streamClosed = true;
|
|
138
|
-
else {
|
|
139
|
-
logError(error);
|
|
140
|
-
streamClosed = true;
|
|
141
|
-
}
|
|
100
|
+
const onNext = async (event) => {
|
|
101
|
+
collectExecutionInfo(event, executionInfo);
|
|
102
|
+
if (event.type === "RUN_STARTED") {
|
|
103
|
+
const e = event;
|
|
104
|
+
debugThreadId = e.threadId ?? "";
|
|
105
|
+
debugRunId = e.runId ?? "";
|
|
106
|
+
}
|
|
107
|
+
if (event.type === "RUN_ERROR") {
|
|
108
|
+
const e = event;
|
|
109
|
+
debugThreadId = e.threadId ?? debugThreadId;
|
|
110
|
+
debugRunId = e.runId ?? debugRunId;
|
|
111
|
+
reportAgentError(new Error(typeof e.message === "string" ? e.message : "Runner reported a run error"), "sse.subscription");
|
|
112
|
+
}
|
|
113
|
+
if (debugEventBus) try {
|
|
114
|
+
debugEventBus.broadcast(event, {
|
|
115
|
+
agentId: agentId ?? "",
|
|
116
|
+
threadId: debugThreadId,
|
|
117
|
+
runId: debugRunId
|
|
118
|
+
});
|
|
119
|
+
} catch (broadcastError) {
|
|
120
|
+
logError(broadcastError);
|
|
121
|
+
}
|
|
122
|
+
if (!request.signal.aborted && !streamClosed) try {
|
|
123
|
+
eventCount++;
|
|
124
|
+
if (debug?.events) {
|
|
125
|
+
loggedEventCount++;
|
|
126
|
+
if (debug.verbose) debugLogger.debug({ event }, "Event emitted");
|
|
127
|
+
else debugLogger.debug({
|
|
128
|
+
type: event.type,
|
|
129
|
+
...summarizeEvent(event)
|
|
130
|
+
}, "Event emitted");
|
|
142
131
|
}
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
132
|
+
if (event.type === EventType.RUN_STARTED) terminalEventWritten = false;
|
|
133
|
+
else if (event.type === EventType.RUN_FINISHED || event.type === EventType.RUN_ERROR) terminalEventWritten = true;
|
|
134
|
+
await writer.write(encoder.encodeBinary(event));
|
|
135
|
+
} catch (error) {
|
|
136
|
+
if (error instanceof Error && error.name === "AbortError") streamClosed = true;
|
|
137
|
+
else {
|
|
138
|
+
logError(error);
|
|
139
|
+
streamClosed = true;
|
|
150
140
|
}
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
if (debug?.lifecycle) debugLogger.debug({ error: error instanceof Error ? error.message : String(error) }, "SSE stream errored");
|
|
157
|
-
logError(error);
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
const onError = async (error) => {
|
|
144
|
+
if (isThreadAccessDeniedError(error)) {
|
|
145
|
+
logAccessDenied(error);
|
|
158
146
|
await writeRunError(error);
|
|
159
147
|
await closeStream();
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
reportAgentError(error, "sse.subscription");
|
|
151
|
+
if (captureTelemetry) telemetry$1.capture("oss.runtime.agent_execution_stream_errored", {
|
|
152
|
+
...executionInfo,
|
|
153
|
+
error: "AGENT_EXECUTION_FAILED"
|
|
154
|
+
});
|
|
155
|
+
if (debug?.lifecycle) debugLogger.debug({ error: error instanceof Error ? error.message : String(error) }, "SSE stream errored");
|
|
156
|
+
logError(error);
|
|
157
|
+
await writeRunError(error);
|
|
158
|
+
await closeStream();
|
|
159
|
+
};
|
|
160
|
+
const onComplete = async () => {
|
|
161
|
+
if (captureTelemetry) telemetry$1.capture("oss.runtime.agent_execution_stream_ended", executionInfo);
|
|
162
|
+
if (debug?.lifecycle) debugLogger.debug({
|
|
163
|
+
eventCount,
|
|
164
|
+
loggedEventCount
|
|
165
|
+
}, "SSE stream completed");
|
|
166
|
+
await closeStream();
|
|
167
|
+
};
|
|
168
|
+
subscription = observable.subscribe({
|
|
169
|
+
next: (event) => {
|
|
170
|
+
onNext(event);
|
|
160
171
|
},
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
}, "SSE stream completed");
|
|
167
|
-
await closeStream();
|
|
172
|
+
error: (error) => {
|
|
173
|
+
onError(error);
|
|
174
|
+
},
|
|
175
|
+
complete: () => {
|
|
176
|
+
onComplete();
|
|
168
177
|
}
|
|
169
178
|
});
|
|
170
179
|
if (request.signal.aborted) subscription.unsubscribe();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sse-response.mjs","names":["defaultTelemetry"],"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 pino logger per request. */\n logger?: CopilotRuntimeLogger;\n /** Runtime-bound telemetry capture. Falls back for external direct callers. */\n telemetry?: TelemetryCapture;\n /**\n * Execution facts known before the stream opens, merged under anything the\n * upstream reports as it runs. Carries `llmHostClass`, which is knowable\n * from the agent's configuration and never appears on a streamed event.\n */\n executionSeed?: AgentExecutionResponseInfo;\n /**\n * Whether to emit `oss.runtime.agent_execution_stream_*` telemetry for this\n * stream. Defaults to `true`. The stateless `/suggest` path sets this to\n * `false`: a suggestion is a side-effect-free structured completion, not a\n * tracked run, and under `available: \"always\"` it fires often enough to flood\n * run telemetry.\n */\n captureTelemetry?: boolean;\n runtimeErrorReporter?: RuntimeErrorReporter;\n startTime?: number;\n /**\n * Seconds of silence before a `: keep-alive` SSE comment is written.\n * `0` disables the keep-alive. Resolved by\n * {@link resolveSseKeepAliveIntervalSeconds}, which supplies the default\n * and enforces the timer bound for every caller.\n */\n keepAliveIntervalSeconds?: number;\n}\n\nexport function createSseEventResponse({\n request,\n observableFactory,\n debugEventBus,\n agentId,\n debug,\n logger,\n telemetry = defaultTelemetry,\n executionSeed,\n captureTelemetry = true,\n runtimeErrorReporter,\n startTime,\n keepAliveIntervalSeconds,\n}: CreateSseEventResponseParams): Response {\n const keepAliveSeconds = resolveSseKeepAliveIntervalSeconds(\n keepAliveIntervalSeconds,\n );\n const stream = new TransformStream();\n const writer = stream.writable.getWriter();\n const encoder = new EventEncoder();\n let streamClosed = false;\n // 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 telemetry.capture(\"oss.runtime.agent_execution_stream_started\", {});\n }\n\n if (debug?.lifecycle) {\n debugLogger!.debug(\"SSE stream opened\");\n }\n\n let eventCount = 0;\n let loggedEventCount = 0;\n\n // Provider/model/LangGraph facts, scraped off raw upstream events as\n // they pass and reported once the stream finishes. This moved here from\n // the v1 TelemetryAgentRunner, which wrapped the runner purely to\n // collect it and emitted its own duplicate copy of every stream event\n // to carry it. v2 callers had no equivalent and reported `{}`.\n // Seeded rather than empty: `llmHostClass` comes from the agent's config,\n // not from the wire, so nothing streamed will ever fill it in. Scraped\n // fields still win, since `collectExecutionInfo` writes over this.\n const executionInfo: AgentExecutionResponseInfo = { ...executionSeed };\n\n subscription = observable.subscribe({\n next: async (event) => {\n collectExecutionInfo(event, executionInfo);\n\n // Extract threadId/runId from RUN_STARTED\n if (event.type === \"RUN_STARTED\") {\n const e = event as { threadId?: string; runId?: string };\n debugThreadId = e.threadId ?? \"\";\n debugRunId = e.runId ?? \"\";\n }\n\n if (event.type === \"RUN_ERROR\") {\n const e = event as {\n message?: unknown;\n threadId?: string;\n runId?: string;\n };\n debugThreadId = e.threadId ?? debugThreadId;\n debugRunId = e.runId ?? debugRunId;\n reportAgentError(\n new Error(\n typeof e.message === \"string\"\n ? e.message\n : \"Runner reported a run error\",\n ),\n \"sse.subscription\",\n );\n }\n\n // Broadcast to debug listeners BEFORE the stream-closed gate below.\n // Intentional: debug subscribers (e.g. the VS Code Inspector panel)\n // should still receive trailing events after the SSE client for\n // this request closed its connection — they're independent\n // consumers observing the underlying runtime, not the request's\n // response stream.\n //\n // Wrapped in try/catch so a buggy debug subscriber can't propagate\n // an exception into this observer — if the throw reached the\n // `next` callback it would get routed to `error` by RxJS, closing\n // the SSE stream for an unrelated reason. Log via `logError` and\n // move on.\n if (debugEventBus) {\n try {\n debugEventBus.broadcast(event, {\n agentId: agentId ?? \"\",\n threadId: debugThreadId,\n runId: debugRunId,\n });\n } catch (broadcastError) {\n logError(broadcastError);\n }\n }\n\n if (!request.signal.aborted && !streamClosed) {\n try {\n eventCount++;\n if (debug?.events) {\n loggedEventCount++;\n if (debug.verbose) {\n debugLogger!.debug({ event }, \"Event emitted\");\n } else {\n debugLogger!.debug(\n { type: event.type, ...summarizeEvent(event) },\n \"Event emitted\",\n );\n }\n }\n // /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 error: async (error) => {\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 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 complete: async () => {\n if (captureTelemetry) {\n telemetry.capture(\n \"oss.runtime.agent_execution_stream_ended\",\n executionInfo,\n );\n }\n if (debug?.lifecycle) {\n debugLogger!.debug(\n { eventCount, loggedEventCount },\n \"SSE stream completed\",\n );\n }\n await closeStream();\n },\n });\n\n // If the client disconnected before the subscription was created,\n // unsubscribe immediately to avoid leaking the observable.\n if (request.signal.aborted) {\n subscription.unsubscribe();\n }\n })().catch(async (error) => {\n 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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,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 { 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,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,MAAM,QAAQ,aAAa,MAAmB,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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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run.cjs","names":["isThreadAccessDeniedError","threadAccessDeniedResponse","createSseEventResponse","getRuntimeErrorReporter"],"sources":["../../../../src/runtime/handlers/sse/run.ts"],"sourcesContent":["import type { AbstractAgent, BaseEvent, RunAgentInput } from \"@ag-ui/client\";\nimport type { Observable } from \"rxjs\";\nimport { isThreadAccessDeniedError } from \"../../runner/agent-runner\";\nimport { threadAccessDeniedResponse } from \"../shared/thread-access\";\nimport type { ResolvedDebugConfig, ModelHostClass } from \"@copilotkit/shared\";\nimport type { CopilotRuntimeLogger } from \"../../core/logger\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { getRuntimeErrorReporter } from \"../../core/runtime-error-reporter\";\nimport { createSseEventResponse } from \"../shared/sse-response\";\n\ninterface HandleSseRunParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n agent: AbstractAgent;\n input: RunAgentInput;\n agentId: string;\n debug?: ResolvedDebugConfig;\n /** Pre-created logger instance to avoid creating a new
|
|
1
|
+
{"version":3,"file":"run.cjs","names":["isThreadAccessDeniedError","threadAccessDeniedResponse","createSseEventResponse","getRuntimeErrorReporter"],"sources":["../../../../src/runtime/handlers/sse/run.ts"],"sourcesContent":["import type { AbstractAgent, BaseEvent, RunAgentInput } from \"@ag-ui/client\";\nimport type { Observable } from \"rxjs\";\nimport { isThreadAccessDeniedError } from \"../../runner/agent-runner\";\nimport { threadAccessDeniedResponse } from \"../shared/thread-access\";\nimport type { ResolvedDebugConfig, ModelHostClass } from \"@copilotkit/shared\";\nimport type { CopilotRuntimeLogger } from \"../../core/logger\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { getRuntimeErrorReporter } from \"../../core/runtime-error-reporter\";\nimport { createSseEventResponse } from \"../shared/sse-response\";\n\ninterface HandleSseRunParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n agent: AbstractAgent;\n input: RunAgentInput;\n agentId: string;\n debug?: ResolvedDebugConfig;\n /** Pre-created logger instance to avoid creating a new logger per request. */\n logger?: CopilotRuntimeLogger;\n startTime?: number;\n /** Identity the run acts as; the runner records it as the thread owner. */\n ownerId?: string;\n}\n\nexport function handleSseRun({\n runtime,\n request,\n agent,\n input,\n agentId,\n debug,\n logger,\n startTime,\n ownerId,\n}: HandleSseRunParams): Response {\n // Start the run before the stream opens. When another identity claimed the\n // thread after the handler's owner check, the runner refuses at once, and\n // that refusal becomes the same HTTP error as the check's, not a streamed\n // agent failure. Any other start error still reaches the client as a\n // RUN_ERROR on the stream, as before.\n let started: Observable<BaseEvent> | undefined;\n let startError: unknown;\n try {\n started = runtime.runner.run({\n threadId: input.threadId,\n agent,\n input,\n ...(ownerId === undefined ? {} : { ownerId }),\n });\n } catch (error) {\n if (isThreadAccessDeniedError(error)) {\n console.warn(\n \"[CopilotKit] Run refused: the thread belongs to another identity.\",\n );\n return threadAccessDeniedResponse();\n }\n startError = error;\n }\n\n return createSseEventResponse({\n request,\n debugEventBus: runtime.debugEventBus,\n agentId,\n debug,\n logger,\n runtimeErrorReporter: getRuntimeErrorReporter(runtime),\n startTime,\n telemetry: runtime.telemetry,\n keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,\n // Read structurally rather than via `instanceof BuiltInAgent`, which would\n // pull the agent module into this handler. Any agent can opt in by\n // exposing the same property.\n executionSeed: {\n llmHostClass:\n (agent as { modelHostClass?: ModelHostClass }).modelHostClass ??\n \"unknown\",\n },\n observableFactory: () => {\n if (started === undefined) throw startError;\n return started;\n },\n });\n}\n"],"mappings":";;;;;;AAwBA,SAAgB,aAAa,EAC3B,SACA,SACA,OACA,OACA,SACA,OACA,QACA,WACA,WAC+B;CAM/B,IAAI;CACJ,IAAI;AACJ,KAAI;AACF,YAAU,QAAQ,OAAO,IAAI;GAC3B,UAAU,MAAM;GAChB;GACA;GACA,GAAI,YAAY,SAAY,EAAE,GAAG,EAAE,SAAS;GAC7C,CAAC;UACK,OAAO;AACd,MAAIA,+CAA0B,MAAM,EAAE;AACpC,WAAQ,KACN,oEACD;AACD,UAAOC,kDAA4B;;AAErC,eAAa;;AAGf,QAAOC,4CAAuB;EAC5B;EACA,eAAe,QAAQ;EACvB;EACA;EACA;EACA,sBAAsBC,uDAAwB,QAAQ;EACtD;EACA,WAAW,QAAQ;EACnB,0BAA0B,QAAQ;EAIlC,eAAe,EACb,cACG,MAA8C,kBAC/C,WACH;EACD,yBAAyB;AACvB,OAAI,YAAY,OAAW,OAAM;AACjC,UAAO;;EAEV,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run.mjs","names":[],"sources":["../../../../src/runtime/handlers/sse/run.ts"],"sourcesContent":["import type { AbstractAgent, BaseEvent, RunAgentInput } from \"@ag-ui/client\";\nimport type { Observable } from \"rxjs\";\nimport { isThreadAccessDeniedError } from \"../../runner/agent-runner\";\nimport { threadAccessDeniedResponse } from \"../shared/thread-access\";\nimport type { ResolvedDebugConfig, ModelHostClass } from \"@copilotkit/shared\";\nimport type { CopilotRuntimeLogger } from \"../../core/logger\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { getRuntimeErrorReporter } from \"../../core/runtime-error-reporter\";\nimport { createSseEventResponse } from \"../shared/sse-response\";\n\ninterface HandleSseRunParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n agent: AbstractAgent;\n input: RunAgentInput;\n agentId: string;\n debug?: ResolvedDebugConfig;\n /** Pre-created logger instance to avoid creating a new
|
|
1
|
+
{"version":3,"file":"run.mjs","names":[],"sources":["../../../../src/runtime/handlers/sse/run.ts"],"sourcesContent":["import type { AbstractAgent, BaseEvent, RunAgentInput } from \"@ag-ui/client\";\nimport type { Observable } from \"rxjs\";\nimport { isThreadAccessDeniedError } from \"../../runner/agent-runner\";\nimport { threadAccessDeniedResponse } from \"../shared/thread-access\";\nimport type { ResolvedDebugConfig, ModelHostClass } from \"@copilotkit/shared\";\nimport type { CopilotRuntimeLogger } from \"../../core/logger\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { getRuntimeErrorReporter } from \"../../core/runtime-error-reporter\";\nimport { createSseEventResponse } from \"../shared/sse-response\";\n\ninterface HandleSseRunParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n agent: AbstractAgent;\n input: RunAgentInput;\n agentId: string;\n debug?: ResolvedDebugConfig;\n /** Pre-created logger instance to avoid creating a new logger per request. */\n logger?: CopilotRuntimeLogger;\n startTime?: number;\n /** Identity the run acts as; the runner records it as the thread owner. */\n ownerId?: string;\n}\n\nexport function handleSseRun({\n runtime,\n request,\n agent,\n input,\n agentId,\n debug,\n logger,\n startTime,\n ownerId,\n}: HandleSseRunParams): Response {\n // Start the run before the stream opens. When another identity claimed the\n // thread after the handler's owner check, the runner refuses at once, and\n // that refusal becomes the same HTTP error as the check's, not a streamed\n // agent failure. Any other start error still reaches the client as a\n // RUN_ERROR on the stream, as before.\n let started: Observable<BaseEvent> | undefined;\n let startError: unknown;\n try {\n started = runtime.runner.run({\n threadId: input.threadId,\n agent,\n input,\n ...(ownerId === undefined ? {} : { ownerId }),\n });\n } catch (error) {\n if (isThreadAccessDeniedError(error)) {\n console.warn(\n \"[CopilotKit] Run refused: the thread belongs to another identity.\",\n );\n return threadAccessDeniedResponse();\n }\n startError = error;\n }\n\n return createSseEventResponse({\n request,\n debugEventBus: runtime.debugEventBus,\n agentId,\n debug,\n logger,\n runtimeErrorReporter: getRuntimeErrorReporter(runtime),\n startTime,\n telemetry: runtime.telemetry,\n keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,\n // Read structurally rather than via `instanceof BuiltInAgent`, which would\n // pull the agent module into this handler. Any agent can opt in by\n // exposing the same property.\n executionSeed: {\n llmHostClass:\n (agent as { modelHostClass?: ModelHostClass }).modelHostClass ??\n \"unknown\",\n },\n observableFactory: () => {\n if (started === undefined) throw startError;\n return started;\n },\n });\n}\n"],"mappings":";;;;;;AAwBA,SAAgB,aAAa,EAC3B,SACA,SACA,OACA,OACA,SACA,OACA,QACA,WACA,WAC+B;CAM/B,IAAI;CACJ,IAAI;AACJ,KAAI;AACF,YAAU,QAAQ,OAAO,IAAI;GAC3B,UAAU,MAAM;GAChB;GACA;GACA,GAAI,YAAY,SAAY,EAAE,GAAG,EAAE,SAAS;GAC7C,CAAC;UACK,OAAO;AACd,MAAI,0BAA0B,MAAM,EAAE;AACpC,WAAQ,KACN,oEACD;AACD,UAAO,4BAA4B;;AAErC,eAAa;;AAGf,QAAO,uBAAuB;EAC5B;EACA,eAAe,QAAQ;EACvB;EACA;EACA;EACA,sBAAsB,wBAAwB,QAAQ;EACtD;EACA,WAAW,QAAQ;EACnB,0BAA0B,QAAQ;EAIlC,eAAe,EACb,cACG,MAA8C,kBAC/C,WACH;EACD,yBAAyB;AACvB,OAAI,YAAY,OAAW,OAAM;AACjC,UAAO;;EAEV,CAAC"}
|
package/dist/runtime/index.d.cts
CHANGED
|
@@ -10,6 +10,9 @@ import { AgentFactoryContext, AgentsConfig, AgentsFactory, CopilotIntelligenceRu
|
|
|
10
10
|
import { GenerativeUIMiddleware } from "./generative-ui/generative-ui-middleware.cjs";
|
|
11
11
|
import { GenerativeUISurfaceWriter, createSurfaceWriter } from "./generative-ui/surface-writer.cjs";
|
|
12
12
|
import "./generative-ui/index.cjs";
|
|
13
|
+
import { ArgsParser, GenerateSandboxedUIParams, OnParamEvent, OpenGenerativeUIMiddleware } from "./event-transforms/open-generative-ui-middleware.cjs";
|
|
14
|
+
import { RecordedEventTransformOptions, transformRecordedEvents } from "./event-transforms/recorded-events.cjs";
|
|
15
|
+
import { A2UIMiddleware, A2UIMiddlewareConfig } from "./event-transforms/index.cjs";
|
|
13
16
|
import { InMemoryAgentRunner, InMemoryAgentRunnerOptions, InMemoryLimits, InMemoryThread, ɵBoundedThreadStore, ɵGLOBAL_STORE, ɵINMEMORY_DEFAULTS, ɵOWNER_RETENTION_DEFAULTS, ɵOwnerRetention, ɵestimateBytes, ɵnormalizeLimits } from "./runner/in-memory.cjs";
|
|
14
17
|
import { IntelligenceAgentRunner, IntelligenceAgentRunnerOptions, RunnerStartupBoundary } from "./runner/intelligence.cjs";
|
|
15
18
|
import { FinalizeRunOptions, RunEventFinalizer, createRunEventFinalizer, finalizeRunEvents } from "./runner/index.cjs";
|
|
@@ -18,12 +21,4 @@ import { CopilotRuntimeHooks, ErrorHookContext, HandlerHookContext, HookContext,
|
|
|
18
21
|
import { CopilotCorsConfig } from "./core/fetch-cors.cjs";
|
|
19
22
|
import { CopilotRuntimeFetchHandler, CopilotRuntimeFetchHandlerWithChannels, CopilotRuntimeHandlerOptions, createCopilotRuntimeHandler } from "./core/fetch-handler.cjs";
|
|
20
23
|
import { MCPClient, MCPTransport } from "@ai-sdk/mcp";
|
|
21
|
-
|
|
22
|
-
//#region src/runtime/index.d.ts
|
|
23
|
-
/** @deprecated Use `CopilotRuntimeFetchHandler` instead. Note: the new type takes `Request` directly, not `{ request: Request }`. */
|
|
24
|
-
type CopilotKitRequestHandler = (params: {
|
|
25
|
-
request: Request;
|
|
26
|
-
}) => Promise<Response>;
|
|
27
|
-
//#endregion
|
|
28
|
-
export { CopilotKitRequestHandler, type MCPClient, type MCPTransport };
|
|
29
|
-
//# sourceMappingURL=index.d.cts.map
|
|
24
|
+
export { type MCPClient, type MCPTransport };
|
package/dist/runtime/index.d.mts
CHANGED
|
@@ -10,6 +10,9 @@ import { AgentFactoryContext, AgentsConfig, AgentsFactory, CopilotIntelligenceRu
|
|
|
10
10
|
import { GenerativeUIMiddleware } from "./generative-ui/generative-ui-middleware.mjs";
|
|
11
11
|
import { GenerativeUISurfaceWriter, createSurfaceWriter } from "./generative-ui/surface-writer.mjs";
|
|
12
12
|
import "./generative-ui/index.mjs";
|
|
13
|
+
import { ArgsParser, GenerateSandboxedUIParams, OnParamEvent, OpenGenerativeUIMiddleware } from "./event-transforms/open-generative-ui-middleware.mjs";
|
|
14
|
+
import { RecordedEventTransformOptions, transformRecordedEvents } from "./event-transforms/recorded-events.mjs";
|
|
15
|
+
import { A2UIMiddleware, A2UIMiddlewareConfig } from "./event-transforms/index.mjs";
|
|
13
16
|
import { InMemoryAgentRunner, InMemoryAgentRunnerOptions, InMemoryLimits, InMemoryThread, ɵBoundedThreadStore, ɵGLOBAL_STORE, ɵINMEMORY_DEFAULTS, ɵOWNER_RETENTION_DEFAULTS, ɵOwnerRetention, ɵestimateBytes, ɵnormalizeLimits } from "./runner/in-memory.mjs";
|
|
14
17
|
import { IntelligenceAgentRunner, IntelligenceAgentRunnerOptions, RunnerStartupBoundary } from "./runner/intelligence.mjs";
|
|
15
18
|
import { FinalizeRunOptions, RunEventFinalizer, createRunEventFinalizer, finalizeRunEvents } from "./runner/index.mjs";
|
|
@@ -18,12 +21,4 @@ import { CopilotRuntimeHooks, ErrorHookContext, HandlerHookContext, HookContext,
|
|
|
18
21
|
import { CopilotCorsConfig } from "./core/fetch-cors.mjs";
|
|
19
22
|
import { CopilotRuntimeFetchHandler, CopilotRuntimeFetchHandlerWithChannels, CopilotRuntimeHandlerOptions, createCopilotRuntimeHandler } from "./core/fetch-handler.mjs";
|
|
20
23
|
import { MCPClient, MCPTransport } from "@ai-sdk/mcp";
|
|
21
|
-
|
|
22
|
-
//#region src/runtime/index.d.ts
|
|
23
|
-
/** @deprecated Use `CopilotRuntimeFetchHandler` instead. Note: the new type takes `Request` directly, not `{ request: Request }`. */
|
|
24
|
-
type CopilotKitRequestHandler = (params: {
|
|
25
|
-
request: Request;
|
|
26
|
-
}) => Promise<Response>;
|
|
27
|
-
//#endregion
|
|
28
|
-
export { CopilotKitRequestHandler, type MCPClient, type MCPTransport };
|
|
29
|
-
//# sourceMappingURL=index.d.mts.map
|
|
24
|
+
export { type MCPClient, type MCPTransport };
|