@copilotkit/shared 1.72.0 → 1.73.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/LICENSE +21 -0
  2. package/dist/finalize-events.cjs +92 -71
  3. package/dist/finalize-events.cjs.map +1 -1
  4. package/dist/finalize-events.d.cts +20 -1
  5. package/dist/finalize-events.d.cts.map +1 -1
  6. package/dist/finalize-events.d.mts +20 -1
  7. package/dist/finalize-events.d.mts.map +1 -1
  8. package/dist/finalize-events.mjs +92 -72
  9. package/dist/finalize-events.mjs.map +1 -1
  10. package/dist/index.cjs +7 -0
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.d.cts +4 -3
  13. package/dist/index.d.cts.map +1 -1
  14. package/dist/index.d.mts +4 -3
  15. package/dist/index.d.mts.map +1 -1
  16. package/dist/index.mjs +4 -3
  17. package/dist/index.mjs.map +1 -1
  18. package/dist/index.umd.js +218 -72
  19. package/dist/index.umd.js.map +1 -1
  20. package/dist/package.cjs +1 -1
  21. package/dist/package.mjs +1 -1
  22. package/dist/telemetry/events.d.cts +33 -0
  23. package/dist/telemetry/events.d.cts.map +1 -1
  24. package/dist/telemetry/events.d.mts +33 -0
  25. package/dist/telemetry/events.d.mts.map +1 -1
  26. package/dist/telemetry/index.cjs +3 -0
  27. package/dist/telemetry/index.d.cts +2 -2
  28. package/dist/telemetry/index.d.mts +2 -2
  29. package/dist/telemetry/index.mjs +2 -2
  30. package/dist/telemetry/model-host.cjs +104 -0
  31. package/dist/telemetry/model-host.cjs.map +1 -0
  32. package/dist/telemetry/model-host.d.cts +26 -0
  33. package/dist/telemetry/model-host.d.cts.map +1 -0
  34. package/dist/telemetry/model-host.d.mts +26 -0
  35. package/dist/telemetry/model-host.d.mts.map +1 -0
  36. package/dist/telemetry/model-host.mjs +102 -0
  37. package/dist/telemetry/model-host.mjs.map +1 -0
  38. package/dist/telemetry/sampling.cjs +22 -0
  39. package/dist/telemetry/sampling.cjs.map +1 -1
  40. package/dist/telemetry/sampling.d.cts +22 -2
  41. package/dist/telemetry/sampling.d.cts.map +1 -1
  42. package/dist/telemetry/sampling.d.mts +22 -2
  43. package/dist/telemetry/sampling.d.mts.map +1 -1
  44. package/dist/telemetry/sampling.mjs +20 -1
  45. package/dist/telemetry/sampling.mjs.map +1 -1
  46. package/dist/telemetry/telemetry-client.cjs +18 -11
  47. package/dist/telemetry/telemetry-client.cjs.map +1 -1
  48. package/dist/telemetry/telemetry-client.d.cts +3 -3
  49. package/dist/telemetry/telemetry-client.d.cts.map +1 -1
  50. package/dist/telemetry/telemetry-client.d.mts +3 -3
  51. package/dist/telemetry/telemetry-client.d.mts.map +1 -1
  52. package/dist/telemetry/telemetry-client.mjs +19 -12
  53. package/dist/telemetry/telemetry-client.mjs.map +1 -1
  54. package/package.json +1 -1
  55. package/src/finalize-events.test.ts +146 -0
  56. package/src/finalize-events.ts +124 -124
  57. package/src/index.ts +9 -1
  58. package/src/telemetry/events.ts +33 -0
  59. package/src/telemetry/model-host.test.ts +145 -0
  60. package/src/telemetry/model-host.ts +155 -0
  61. package/src/telemetry/sampling.ts +39 -6
  62. package/src/telemetry/telemetry-blank-license-identity.test.ts +11 -4
  63. package/src/telemetry/telemetry-client.test.ts +107 -39
  64. package/src/telemetry/telemetry-client.ts +48 -27
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License
2
+
3
+ Copyright (c) Atai Barkai
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -1,73 +1,80 @@
1
1
  const require_runtime = require('./_virtual/_rolldown/runtime.cjs');
2
- const require_random_id = require('./utils/random-id.cjs');
3
2
  let _ag_ui_client = require("@ag-ui/client");
4
3
 
5
4
  //#region src/finalize-events.ts
6
5
  const defaultStopMessage = "Run stopped by user";
7
6
  const defaultAbruptEndMessage = "Run ended without emitting a terminal event";
8
- function finalizeRunEvents(events, options = {}) {
9
- const { stopRequested = false, interruptionMessage } = options;
10
- const resolvedStopMessage = interruptionMessage ?? defaultStopMessage;
11
- const resolvedAbruptMessage = interruptionMessage && interruptionMessage !== defaultStopMessage ? interruptionMessage : defaultAbruptEndMessage;
12
- const appended = [];
7
+ /**
8
+ * Incremental finalizer for a streamed AG-UI run. Feed every event to
9
+ * `observe`; when the stream ends without a terminal event, `finalize` returns
10
+ * the closers for text messages and tool calls still open plus a terminal
11
+ * event. Closed lifecycles are forgotten at once and payloads are never kept,
12
+ * so a caller does not have to retain the event array for this purpose.
13
+ */
14
+ function createRunEventFinalizer() {
13
15
  const openMessageIds = /* @__PURE__ */ new Set();
14
16
  const openToolCalls = /* @__PURE__ */ new Map();
15
- for (const event of events) switch (event.type) {
16
- case _ag_ui_client.EventType.TEXT_MESSAGE_START: {
17
- const messageId = event.messageId;
18
- if (typeof messageId === "string") openMessageIds.add(messageId);
19
- break;
20
- }
21
- case _ag_ui_client.EventType.TEXT_MESSAGE_END: {
22
- const messageId = event.messageId;
23
- if (typeof messageId === "string") openMessageIds.delete(messageId);
24
- break;
25
- }
26
- case _ag_ui_client.EventType.TOOL_CALL_START: {
27
- const toolCallId = event.toolCallId;
28
- if (typeof toolCallId === "string") openToolCalls.set(toolCallId, {
29
- hasEnd: false,
30
- hasResult: false
31
- });
32
- break;
17
+ let terminalEventObserved = false;
18
+ const observe = (event) => {
19
+ if (terminalEventObserved) return;
20
+ switch (event.type) {
21
+ case _ag_ui_client.EventType.TEXT_MESSAGE_START: {
22
+ const messageId = event.messageId;
23
+ if (messageId) openMessageIds.add(messageId);
24
+ break;
25
+ }
26
+ case _ag_ui_client.EventType.TEXT_MESSAGE_END: {
27
+ const messageId = event.messageId;
28
+ if (typeof messageId === "string") openMessageIds.delete(messageId);
29
+ break;
30
+ }
31
+ case _ag_ui_client.EventType.TOOL_CALL_START: {
32
+ const toolCallId = event.toolCallId;
33
+ if (toolCallId && !openToolCalls.has(toolCallId)) openToolCalls.set(toolCallId, {
34
+ hasEnd: false,
35
+ hasResult: false
36
+ });
37
+ break;
38
+ }
39
+ case _ag_ui_client.EventType.TOOL_CALL_END:
40
+ case _ag_ui_client.EventType.TOOL_CALL_RESULT: {
41
+ const toolCallId = event.toolCallId;
42
+ if (!toolCallId) break;
43
+ const info = openToolCalls.get(toolCallId);
44
+ if (!info) break;
45
+ if (event.type === _ag_ui_client.EventType.TOOL_CALL_END) info.hasEnd = true;
46
+ else info.hasResult = true;
47
+ if (info.hasEnd && info.hasResult) openToolCalls.delete(toolCallId);
48
+ break;
49
+ }
50
+ case _ag_ui_client.EventType.RUN_FINISHED:
51
+ case _ag_ui_client.EventType.RUN_ERROR:
52
+ terminalEventObserved = true;
53
+ openMessageIds.clear();
54
+ openToolCalls.clear();
55
+ break;
56
+ default: break;
33
57
  }
34
- case _ag_ui_client.EventType.TOOL_CALL_END: {
35
- const toolCallId = event.toolCallId;
36
- const info = toolCallId ? openToolCalls.get(toolCallId) : void 0;
37
- if (info) info.hasEnd = true;
38
- break;
39
- }
40
- case _ag_ui_client.EventType.TOOL_CALL_RESULT: {
41
- const toolCallId = event.toolCallId;
42
- const info = toolCallId ? openToolCalls.get(toolCallId) : void 0;
43
- if (info) info.hasResult = true;
44
- break;
45
- }
46
- default: break;
47
- }
48
- if (events.some((event) => event.type === _ag_ui_client.EventType.RUN_FINISHED || event.type === _ag_ui_client.EventType.RUN_ERROR)) return appended;
49
- for (const messageId of openMessageIds) {
50
- const endEvent = {
58
+ };
59
+ const finalize = (options = {}) => {
60
+ if (terminalEventObserved) return [];
61
+ const { stopRequested = false, interruptionMessage } = options;
62
+ const resolvedStopMessage = interruptionMessage ?? defaultStopMessage;
63
+ const resolvedAbruptMessage = interruptionMessage && interruptionMessage !== defaultStopMessage ? interruptionMessage : defaultAbruptEndMessage;
64
+ const appended = [];
65
+ for (const messageId of openMessageIds) appended.push({
51
66
  type: _ag_ui_client.EventType.TEXT_MESSAGE_END,
52
67
  messageId
53
- };
54
- events.push(endEvent);
55
- appended.push(endEvent);
56
- }
57
- for (const [toolCallId, info] of openToolCalls) {
58
- if (!info.hasEnd) {
59
- const endEvent = {
68
+ });
69
+ for (const [toolCallId, info] of openToolCalls) {
70
+ if (!info.hasEnd) appended.push({
60
71
  type: _ag_ui_client.EventType.TOOL_CALL_END,
61
72
  toolCallId
62
- };
63
- events.push(endEvent);
64
- appended.push(endEvent);
65
- }
66
- if (!info.hasResult) {
67
- const resultEvent = {
73
+ });
74
+ if (!info.hasResult) appended.push({
68
75
  type: _ag_ui_client.EventType.TOOL_CALL_RESULT,
69
76
  toolCallId,
70
- messageId: `${toolCallId ?? require_random_id.randomUUID()}-result`,
77
+ messageId: `${toolCallId}-result`,
71
78
  role: "tool",
72
79
  content: JSON.stringify(stopRequested ? {
73
80
  status: "stopped",
@@ -78,27 +85,41 @@ function finalizeRunEvents(events, options = {}) {
78
85
  reason: "missing_terminal_event",
79
86
  message: resolvedAbruptMessage
80
87
  })
88
+ });
89
+ }
90
+ if (stopRequested) appended.push({ type: _ag_ui_client.EventType.RUN_FINISHED });
91
+ else {
92
+ const errorEvent = {
93
+ type: _ag_ui_client.EventType.RUN_ERROR,
94
+ message: resolvedAbruptMessage,
95
+ code: "INCOMPLETE_STREAM"
81
96
  };
82
- events.push(resultEvent);
83
- appended.push(resultEvent);
97
+ appended.push(errorEvent);
84
98
  }
85
- }
86
- if (stopRequested) {
87
- const finishedEvent = { type: _ag_ui_client.EventType.RUN_FINISHED };
88
- events.push(finishedEvent);
89
- appended.push(finishedEvent);
90
- } else {
91
- const errorEvent = {
92
- type: _ag_ui_client.EventType.RUN_ERROR,
93
- message: resolvedAbruptMessage,
94
- code: "INCOMPLETE_STREAM"
95
- };
96
- events.push(errorEvent);
97
- appended.push(errorEvent);
98
- }
99
+ terminalEventObserved = true;
100
+ openMessageIds.clear();
101
+ openToolCalls.clear();
102
+ return appended;
103
+ };
104
+ return {
105
+ observe,
106
+ finalize
107
+ };
108
+ }
109
+ /**
110
+ * Array form of {@link createRunEventFinalizer} for callers that already keep
111
+ * the run's events (runners persist them). Appends the closers to `events` in
112
+ * place and returns them.
113
+ */
114
+ function finalizeRunEvents(events, options = {}) {
115
+ const finalizer = createRunEventFinalizer();
116
+ for (const event of events) finalizer.observe(event);
117
+ const appended = finalizer.finalize(options);
118
+ events.push(...appended);
99
119
  return appended;
100
120
  }
101
121
 
102
122
  //#endregion
123
+ exports.createRunEventFinalizer = createRunEventFinalizer;
103
124
  exports.finalizeRunEvents = finalizeRunEvents;
104
125
  //# sourceMappingURL=finalize-events.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"finalize-events.cjs","names":["EventType","randomUUID"],"sources":["../src/finalize-events.ts"],"sourcesContent":["import type { BaseEvent, RunErrorEvent } from \"@ag-ui/client\";\nimport { EventType } from \"@ag-ui/client\";\nimport { randomUUID } from \"./utils\";\n\ninterface FinalizeRunOptions {\n stopRequested?: boolean;\n interruptionMessage?: string;\n}\n\nconst defaultStopMessage = \"Run stopped by user\";\nconst defaultAbruptEndMessage = \"Run ended without emitting a terminal event\";\n\nexport function finalizeRunEvents(\n events: BaseEvent[],\n options: FinalizeRunOptions = {},\n): BaseEvent[] {\n const { stopRequested = false, interruptionMessage } = options;\n\n const resolvedStopMessage = interruptionMessage ?? defaultStopMessage;\n const resolvedAbruptMessage =\n interruptionMessage && interruptionMessage !== defaultStopMessage\n ? interruptionMessage\n : defaultAbruptEndMessage;\n\n const appended: BaseEvent[] = [];\n\n const openMessageIds = new Set<string>();\n const openToolCalls = new Map<\n string,\n {\n hasEnd: boolean;\n hasResult: boolean;\n }\n >();\n\n for (const event of events) {\n switch (event.type) {\n case EventType.TEXT_MESSAGE_START: {\n const messageId = (event as { messageId?: string }).messageId;\n if (typeof messageId === \"string\") {\n openMessageIds.add(messageId);\n }\n break;\n }\n case EventType.TEXT_MESSAGE_END: {\n const messageId = (event as { messageId?: string }).messageId;\n if (typeof messageId === \"string\") {\n openMessageIds.delete(messageId);\n }\n break;\n }\n case EventType.TOOL_CALL_START: {\n const toolCallId = (event as { toolCallId?: string }).toolCallId;\n if (typeof toolCallId === \"string\") {\n openToolCalls.set(toolCallId, {\n hasEnd: false,\n hasResult: false,\n });\n }\n break;\n }\n case EventType.TOOL_CALL_END: {\n const toolCallId = (event as { toolCallId?: string }).toolCallId;\n const info = toolCallId ? openToolCalls.get(toolCallId) : undefined;\n if (info) {\n info.hasEnd = true;\n }\n break;\n }\n case EventType.TOOL_CALL_RESULT: {\n const toolCallId = (event as { toolCallId?: string }).toolCallId;\n const info = toolCallId ? openToolCalls.get(toolCallId) : undefined;\n if (info) {\n info.hasResult = true;\n }\n break;\n }\n default:\n break;\n }\n }\n\n const hasTerminalEvent = events.some(\n (event) =>\n event.type === EventType.RUN_FINISHED ||\n event.type === EventType.RUN_ERROR,\n );\n\n // Once a run has emitted a terminal event (RUN_FINISHED or RUN_ERROR), the\n // AG-UI spec forbids any further events for that run — the verifier rejects a\n // trailing TEXT_MESSAGE_END / TOOL_CALL_END with \"the run has already\n // errored/finished with '…'. No further events can be sent.\" (issue #5812).\n // These finalization events are streamed *after* everything the agent already\n // emitted, so appending closers here would place them after that terminal.\n // When a terminal already exists we therefore append nothing: any message or\n // tool call still open when the terminal arrived is implicitly closed by the\n // terminal on the client. We only synthesize closers + a terminal for a\n // stream that ended abruptly without a terminal of its own (below).\n if (hasTerminalEvent) {\n return appended;\n }\n\n for (const messageId of openMessageIds) {\n const endEvent = {\n type: EventType.TEXT_MESSAGE_END,\n messageId,\n } as BaseEvent;\n events.push(endEvent);\n appended.push(endEvent);\n }\n\n for (const [toolCallId, info] of openToolCalls) {\n if (!info.hasEnd) {\n const endEvent = {\n type: EventType.TOOL_CALL_END,\n toolCallId,\n } as BaseEvent;\n events.push(endEvent);\n appended.push(endEvent);\n }\n\n if (!info.hasResult) {\n const resultEvent = {\n type: EventType.TOOL_CALL_RESULT,\n toolCallId,\n messageId: `${toolCallId ?? randomUUID()}-result`,\n role: \"tool\",\n content: JSON.stringify(\n stopRequested\n ? {\n status: \"stopped\",\n reason: \"stop_requested\",\n message: resolvedStopMessage,\n }\n : {\n status: \"error\",\n reason: \"missing_terminal_event\",\n message: resolvedAbruptMessage,\n },\n ),\n } as BaseEvent;\n events.push(resultEvent);\n appended.push(resultEvent);\n }\n }\n\n if (stopRequested) {\n const finishedEvent = {\n type: EventType.RUN_FINISHED,\n } as BaseEvent;\n events.push(finishedEvent);\n appended.push(finishedEvent);\n } else {\n const errorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message: resolvedAbruptMessage,\n code: \"INCOMPLETE_STREAM\",\n };\n events.push(errorEvent);\n appended.push(errorEvent);\n }\n\n return appended;\n}\n"],"mappings":";;;;;AASA,MAAM,qBAAqB;AAC3B,MAAM,0BAA0B;AAEhC,SAAgB,kBACd,QACA,UAA8B,EAAE,EACnB;CACb,MAAM,EAAE,gBAAgB,OAAO,wBAAwB;CAEvD,MAAM,sBAAsB,uBAAuB;CACnD,MAAM,wBACJ,uBAAuB,wBAAwB,qBAC3C,sBACA;CAEN,MAAM,WAAwB,EA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;IAClB,MAAMA,wBAAU;IAChB;IACA,WAAW,GAAG,cAAcC,8BAAY,CAAC;IACzC,MAAM;IACN,SAAS,KAAK,UACZ,gBACI;KACE,QAAQ;KACR,QAAQ;KACR,SAAS;KACV,GACD;KACE,QAAQ;KACR,QAAQ;KACR,SAAS;KACV,CACN;IACF;AACD,UAAO,KAAK,YAAY;AACxB,YAAS,KAAK,YAAY;;;AAI9B,KAAI,eAAe;EACjB,MAAM,gBAAgB,EACpB,MAAMD,wBAAU,cACjB;AACD,SAAO,KAAK,cAAc;AAC1B,WAAS,KAAK,cAAc;QACvB;EACL,MAAM,aAA4B;GAChC,MAAMA,wBAAU;GAChB,SAAS;GACT,MAAM;GACP;AACD,SAAO,KAAK,WAAW;AACvB,WAAS,KAAK,WAAW;;AAG3B,QAAO"}
1
+ {"version":3,"file":"finalize-events.cjs","names":["EventType"],"sources":["../src/finalize-events.ts"],"sourcesContent":["import type { BaseEvent, RunErrorEvent } from \"@ag-ui/client\";\nimport { EventType } from \"@ag-ui/client\";\n\nexport interface FinalizeRunOptions {\n stopRequested?: boolean;\n interruptionMessage?: string;\n}\n\nexport interface RunEventFinalizer {\n /** Observe one streamed event. Only the ids of open lifecycles are kept. */\n observe(event: BaseEvent): void;\n /** Return the events that close an interrupted or abruptly ended stream. */\n finalize(options?: FinalizeRunOptions): BaseEvent[];\n}\n\nconst defaultStopMessage = \"Run stopped by user\";\nconst defaultAbruptEndMessage = \"Run ended without emitting a terminal event\";\n\ninterface OpenToolCall {\n hasEnd: boolean;\n hasResult: boolean;\n}\n\n/**\n * Incremental finalizer for a streamed AG-UI run. Feed every event to\n * `observe`; when the stream ends without a terminal event, `finalize` returns\n * the closers for text messages and tool calls still open plus a terminal\n * event. Closed lifecycles are forgotten at once and payloads are never kept,\n * so a caller does not have to retain the event array for this purpose.\n */\nexport function createRunEventFinalizer(): RunEventFinalizer {\n const openMessageIds = new Set<string>();\n const openToolCalls = new Map<string, OpenToolCall>();\n let terminalEventObserved = false;\n\n const observe = (event: BaseEvent) => {\n if (terminalEventObserved) return;\n\n switch (event.type) {\n case EventType.TEXT_MESSAGE_START: {\n const messageId = (event as { messageId?: string }).messageId;\n if (messageId) openMessageIds.add(messageId);\n break;\n }\n case EventType.TEXT_MESSAGE_END: {\n const messageId = (event as { messageId?: string }).messageId;\n if (typeof messageId === \"string\") openMessageIds.delete(messageId);\n break;\n }\n case EventType.TOOL_CALL_START: {\n const toolCallId = (event as { toolCallId?: string }).toolCallId;\n if (toolCallId && !openToolCalls.has(toolCallId)) {\n openToolCalls.set(toolCallId, { hasEnd: false, hasResult: false });\n }\n break;\n }\n case EventType.TOOL_CALL_END:\n case EventType.TOOL_CALL_RESULT: {\n const toolCallId = (event as { toolCallId?: string }).toolCallId;\n if (!toolCallId) break;\n const info = openToolCalls.get(toolCallId);\n if (!info) break;\n\n if (event.type === EventType.TOOL_CALL_END) info.hasEnd = true;\n else info.hasResult = true;\n if (info.hasEnd && info.hasResult) openToolCalls.delete(toolCallId);\n break;\n }\n case EventType.RUN_FINISHED:\n case EventType.RUN_ERROR:\n terminalEventObserved = true;\n openMessageIds.clear();\n openToolCalls.clear();\n break;\n default:\n break;\n }\n };\n\n const finalize = (options: FinalizeRunOptions = {}): BaseEvent[] => {\n if (terminalEventObserved) return [];\n\n const { stopRequested = false, interruptionMessage } = options;\n const resolvedStopMessage = interruptionMessage ?? defaultStopMessage;\n const resolvedAbruptMessage =\n interruptionMessage && interruptionMessage !== defaultStopMessage\n ? interruptionMessage\n : defaultAbruptEndMessage;\n const appended: BaseEvent[] = [];\n\n for (const messageId of openMessageIds) {\n appended.push({\n type: EventType.TEXT_MESSAGE_END,\n messageId,\n } as BaseEvent);\n }\n\n for (const [toolCallId, info] of openToolCalls) {\n if (!info.hasEnd) {\n appended.push({\n type: EventType.TOOL_CALL_END,\n toolCallId,\n } as BaseEvent);\n }\n\n if (!info.hasResult) {\n appended.push({\n type: EventType.TOOL_CALL_RESULT,\n toolCallId,\n messageId: `${toolCallId}-result`,\n role: \"tool\",\n content: JSON.stringify(\n stopRequested\n ? {\n status: \"stopped\",\n reason: \"stop_requested\",\n message: resolvedStopMessage,\n }\n : {\n status: \"error\",\n reason: \"missing_terminal_event\",\n message: resolvedAbruptMessage,\n },\n ),\n } as BaseEvent);\n }\n }\n\n if (stopRequested) {\n appended.push({ type: EventType.RUN_FINISHED } as BaseEvent);\n } else {\n const errorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message: resolvedAbruptMessage,\n code: \"INCOMPLETE_STREAM\",\n };\n appended.push(errorEvent);\n }\n\n terminalEventObserved = true;\n openMessageIds.clear();\n openToolCalls.clear();\n return appended;\n };\n\n return { observe, finalize };\n}\n\n/**\n * Array form of {@link createRunEventFinalizer} for callers that already keep\n * the run's events (runners persist them). Appends the closers to `events` in\n * place and returns them.\n */\nexport function finalizeRunEvents(\n events: BaseEvent[],\n options: FinalizeRunOptions = {},\n): BaseEvent[] {\n const finalizer = createRunEventFinalizer();\n for (const event of events) finalizer.observe(event);\n\n const appended = finalizer.finalize(options);\n events.push(...appended);\n return appended;\n}\n"],"mappings":";;;;AAeA,MAAM,qBAAqB;AAC3B,MAAM,0BAA0B;;;;;;;;AAchC,SAAgB,0BAA6C;CAC3D,MAAM,iCAAiB,IAAI,KAAa;CACxC,MAAM,gCAAgB,IAAI,KAA2B;CACrD,IAAI,wBAAwB;CAE5B,MAAM,WAAW,UAAqB;AACpC,MAAI,sBAAuB;AAE3B,UAAQ,MAAM,MAAd;GACE,KAAKA,wBAAU,oBAAoB;IACjC,MAAM,YAAa,MAAiC;AACpD,QAAI,UAAW,gBAAe,IAAI,UAAU;AAC5C;;GAEF,KAAKA,wBAAU,kBAAkB;IAC/B,MAAM,YAAa,MAAiC;AACpD,QAAI,OAAO,cAAc,SAAU,gBAAe,OAAO,UAAU;AACnE;;GAEF,KAAKA,wBAAU,iBAAiB;IAC9B,MAAM,aAAc,MAAkC;AACtD,QAAI,cAAc,CAAC,cAAc,IAAI,WAAW,CAC9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AS;IACT,MAAM;IACP;AACD,YAAS,KAAK,WAAW;;AAG3B,0BAAwB;AACxB,iBAAe,OAAO;AACtB,gBAAc,OAAO;AACrB,SAAO;;AAGT,QAAO;EAAE;EAAS;EAAU;;;;;;;AAQ9B,SAAgB,kBACd,QACA,UAA8B,EAAE,EACnB;CACb,MAAM,YAAY,yBAAyB;AAC3C,MAAK,MAAM,SAAS,OAAQ,WAAU,QAAQ,MAAM;CAEpD,MAAM,WAAW,UAAU,SAAS,QAAQ;AAC5C,QAAO,KAAK,GAAG,SAAS;AACxB,QAAO"}
@@ -5,7 +5,26 @@ interface FinalizeRunOptions {
5
5
  stopRequested?: boolean;
6
6
  interruptionMessage?: string;
7
7
  }
8
+ interface RunEventFinalizer {
9
+ /** Observe one streamed event. Only the ids of open lifecycles are kept. */
10
+ observe(event: BaseEvent): void;
11
+ /** Return the events that close an interrupted or abruptly ended stream. */
12
+ finalize(options?: FinalizeRunOptions): BaseEvent[];
13
+ }
14
+ /**
15
+ * Incremental finalizer for a streamed AG-UI run. Feed every event to
16
+ * `observe`; when the stream ends without a terminal event, `finalize` returns
17
+ * the closers for text messages and tool calls still open plus a terminal
18
+ * event. Closed lifecycles are forgotten at once and payloads are never kept,
19
+ * so a caller does not have to retain the event array for this purpose.
20
+ */
21
+ declare function createRunEventFinalizer(): RunEventFinalizer;
22
+ /**
23
+ * Array form of {@link createRunEventFinalizer} for callers that already keep
24
+ * the run's events (runners persist them). Appends the closers to `events` in
25
+ * place and returns them.
26
+ */
8
27
  declare function finalizeRunEvents(events: BaseEvent[], options?: FinalizeRunOptions): BaseEvent[];
9
28
  //#endregion
10
- export { finalizeRunEvents };
29
+ export { FinalizeRunOptions, RunEventFinalizer, createRunEventFinalizer, finalizeRunEvents };
11
30
  //# sourceMappingURL=finalize-events.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"finalize-events.d.cts","names":[],"sources":["../src/finalize-events.ts"],"mappings":";;;UAIU,kBAAA;EACR,aAAA;EACA,mBAAA;AAAA;AAAA,iBAMc,iBAAA,CACd,MAAA,EAAQ,SAAA,IACR,OAAA,GAAS,kBAAA,GACR,SAAA"}
1
+ {"version":3,"file":"finalize-events.d.cts","names":[],"sources":["../src/finalize-events.ts"],"mappings":";;;UAGiB,kBAAA;EACf,aAAA;EACA,mBAAA;AAAA;AAAA,UAGe,iBAAA;EAJf;EAMA,OAAA,CAAQ,KAAA,EAAO,SAAA;EAFA;EAIf,QAAA,CAAS,OAAA,GAAU,kBAAA,GAAqB,SAAA;AAAA;;;;;;;;iBAkB1B,uBAAA,CAAA,GAA2B,iBAAA;;;;;;iBA2H3B,iBAAA,CACd,MAAA,EAAQ,SAAA,IACR,OAAA,GAAS,kBAAA,GACR,SAAA"}
@@ -5,7 +5,26 @@ interface FinalizeRunOptions {
5
5
  stopRequested?: boolean;
6
6
  interruptionMessage?: string;
7
7
  }
8
+ interface RunEventFinalizer {
9
+ /** Observe one streamed event. Only the ids of open lifecycles are kept. */
10
+ observe(event: BaseEvent): void;
11
+ /** Return the events that close an interrupted or abruptly ended stream. */
12
+ finalize(options?: FinalizeRunOptions): BaseEvent[];
13
+ }
14
+ /**
15
+ * Incremental finalizer for a streamed AG-UI run. Feed every event to
16
+ * `observe`; when the stream ends without a terminal event, `finalize` returns
17
+ * the closers for text messages and tool calls still open plus a terminal
18
+ * event. Closed lifecycles are forgotten at once and payloads are never kept,
19
+ * so a caller does not have to retain the event array for this purpose.
20
+ */
21
+ declare function createRunEventFinalizer(): RunEventFinalizer;
22
+ /**
23
+ * Array form of {@link createRunEventFinalizer} for callers that already keep
24
+ * the run's events (runners persist them). Appends the closers to `events` in
25
+ * place and returns them.
26
+ */
8
27
  declare function finalizeRunEvents(events: BaseEvent[], options?: FinalizeRunOptions): BaseEvent[];
9
28
  //#endregion
10
- export { finalizeRunEvents };
29
+ export { FinalizeRunOptions, RunEventFinalizer, createRunEventFinalizer, finalizeRunEvents };
11
30
  //# sourceMappingURL=finalize-events.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"finalize-events.d.mts","names":[],"sources":["../src/finalize-events.ts"],"mappings":";;;UAIU,kBAAA;EACR,aAAA;EACA,mBAAA;AAAA;AAAA,iBAMc,iBAAA,CACd,MAAA,EAAQ,SAAA,IACR,OAAA,GAAS,kBAAA,GACR,SAAA"}
1
+ {"version":3,"file":"finalize-events.d.mts","names":[],"sources":["../src/finalize-events.ts"],"mappings":";;;UAGiB,kBAAA;EACf,aAAA;EACA,mBAAA;AAAA;AAAA,UAGe,iBAAA;EAJf;EAMA,OAAA,CAAQ,KAAA,EAAO,SAAA;EAFA;EAIf,QAAA,CAAS,OAAA,GAAU,kBAAA,GAAqB,SAAA;AAAA;;;;;;;;iBAkB1B,uBAAA,CAAA,GAA2B,iBAAA;;;;;;iBA2H3B,iBAAA,CACd,MAAA,EAAQ,SAAA,IACR,OAAA,GAAS,kBAAA,GACR,SAAA"}
@@ -1,72 +1,79 @@
1
- import { randomUUID } from "./utils/random-id.mjs";
2
1
  import { EventType } from "@ag-ui/client";
3
2
 
4
3
  //#region src/finalize-events.ts
5
4
  const defaultStopMessage = "Run stopped by user";
6
5
  const defaultAbruptEndMessage = "Run ended without emitting a terminal event";
7
- function finalizeRunEvents(events, options = {}) {
8
- const { stopRequested = false, interruptionMessage } = options;
9
- const resolvedStopMessage = interruptionMessage ?? defaultStopMessage;
10
- const resolvedAbruptMessage = interruptionMessage && interruptionMessage !== defaultStopMessage ? interruptionMessage : defaultAbruptEndMessage;
11
- const appended = [];
6
+ /**
7
+ * Incremental finalizer for a streamed AG-UI run. Feed every event to
8
+ * `observe`; when the stream ends without a terminal event, `finalize` returns
9
+ * the closers for text messages and tool calls still open plus a terminal
10
+ * event. Closed lifecycles are forgotten at once and payloads are never kept,
11
+ * so a caller does not have to retain the event array for this purpose.
12
+ */
13
+ function createRunEventFinalizer() {
12
14
  const openMessageIds = /* @__PURE__ */ new Set();
13
15
  const openToolCalls = /* @__PURE__ */ new Map();
14
- for (const event of events) switch (event.type) {
15
- case EventType.TEXT_MESSAGE_START: {
16
- const messageId = event.messageId;
17
- if (typeof messageId === "string") openMessageIds.add(messageId);
18
- break;
19
- }
20
- case EventType.TEXT_MESSAGE_END: {
21
- const messageId = event.messageId;
22
- if (typeof messageId === "string") openMessageIds.delete(messageId);
23
- break;
24
- }
25
- case EventType.TOOL_CALL_START: {
26
- const toolCallId = event.toolCallId;
27
- if (typeof toolCallId === "string") openToolCalls.set(toolCallId, {
28
- hasEnd: false,
29
- hasResult: false
30
- });
31
- break;
16
+ let terminalEventObserved = false;
17
+ const observe = (event) => {
18
+ if (terminalEventObserved) return;
19
+ switch (event.type) {
20
+ case EventType.TEXT_MESSAGE_START: {
21
+ const messageId = event.messageId;
22
+ if (messageId) openMessageIds.add(messageId);
23
+ break;
24
+ }
25
+ case EventType.TEXT_MESSAGE_END: {
26
+ const messageId = event.messageId;
27
+ if (typeof messageId === "string") openMessageIds.delete(messageId);
28
+ break;
29
+ }
30
+ case EventType.TOOL_CALL_START: {
31
+ const toolCallId = event.toolCallId;
32
+ if (toolCallId && !openToolCalls.has(toolCallId)) openToolCalls.set(toolCallId, {
33
+ hasEnd: false,
34
+ hasResult: false
35
+ });
36
+ break;
37
+ }
38
+ case EventType.TOOL_CALL_END:
39
+ case EventType.TOOL_CALL_RESULT: {
40
+ const toolCallId = event.toolCallId;
41
+ if (!toolCallId) break;
42
+ const info = openToolCalls.get(toolCallId);
43
+ if (!info) break;
44
+ if (event.type === EventType.TOOL_CALL_END) info.hasEnd = true;
45
+ else info.hasResult = true;
46
+ if (info.hasEnd && info.hasResult) openToolCalls.delete(toolCallId);
47
+ break;
48
+ }
49
+ case EventType.RUN_FINISHED:
50
+ case EventType.RUN_ERROR:
51
+ terminalEventObserved = true;
52
+ openMessageIds.clear();
53
+ openToolCalls.clear();
54
+ break;
55
+ default: break;
32
56
  }
33
- case EventType.TOOL_CALL_END: {
34
- const toolCallId = event.toolCallId;
35
- const info = toolCallId ? openToolCalls.get(toolCallId) : void 0;
36
- if (info) info.hasEnd = true;
37
- break;
38
- }
39
- case EventType.TOOL_CALL_RESULT: {
40
- const toolCallId = event.toolCallId;
41
- const info = toolCallId ? openToolCalls.get(toolCallId) : void 0;
42
- if (info) info.hasResult = true;
43
- break;
44
- }
45
- default: break;
46
- }
47
- if (events.some((event) => event.type === EventType.RUN_FINISHED || event.type === EventType.RUN_ERROR)) return appended;
48
- for (const messageId of openMessageIds) {
49
- const endEvent = {
57
+ };
58
+ const finalize = (options = {}) => {
59
+ if (terminalEventObserved) return [];
60
+ const { stopRequested = false, interruptionMessage } = options;
61
+ const resolvedStopMessage = interruptionMessage ?? defaultStopMessage;
62
+ const resolvedAbruptMessage = interruptionMessage && interruptionMessage !== defaultStopMessage ? interruptionMessage : defaultAbruptEndMessage;
63
+ const appended = [];
64
+ for (const messageId of openMessageIds) appended.push({
50
65
  type: EventType.TEXT_MESSAGE_END,
51
66
  messageId
52
- };
53
- events.push(endEvent);
54
- appended.push(endEvent);
55
- }
56
- for (const [toolCallId, info] of openToolCalls) {
57
- if (!info.hasEnd) {
58
- const endEvent = {
67
+ });
68
+ for (const [toolCallId, info] of openToolCalls) {
69
+ if (!info.hasEnd) appended.push({
59
70
  type: EventType.TOOL_CALL_END,
60
71
  toolCallId
61
- };
62
- events.push(endEvent);
63
- appended.push(endEvent);
64
- }
65
- if (!info.hasResult) {
66
- const resultEvent = {
72
+ });
73
+ if (!info.hasResult) appended.push({
67
74
  type: EventType.TOOL_CALL_RESULT,
68
75
  toolCallId,
69
- messageId: `${toolCallId ?? randomUUID()}-result`,
76
+ messageId: `${toolCallId}-result`,
70
77
  role: "tool",
71
78
  content: JSON.stringify(stopRequested ? {
72
79
  status: "stopped",
@@ -77,27 +84,40 @@ function finalizeRunEvents(events, options = {}) {
77
84
  reason: "missing_terminal_event",
78
85
  message: resolvedAbruptMessage
79
86
  })
87
+ });
88
+ }
89
+ if (stopRequested) appended.push({ type: EventType.RUN_FINISHED });
90
+ else {
91
+ const errorEvent = {
92
+ type: EventType.RUN_ERROR,
93
+ message: resolvedAbruptMessage,
94
+ code: "INCOMPLETE_STREAM"
80
95
  };
81
- events.push(resultEvent);
82
- appended.push(resultEvent);
96
+ appended.push(errorEvent);
83
97
  }
84
- }
85
- if (stopRequested) {
86
- const finishedEvent = { type: EventType.RUN_FINISHED };
87
- events.push(finishedEvent);
88
- appended.push(finishedEvent);
89
- } else {
90
- const errorEvent = {
91
- type: EventType.RUN_ERROR,
92
- message: resolvedAbruptMessage,
93
- code: "INCOMPLETE_STREAM"
94
- };
95
- events.push(errorEvent);
96
- appended.push(errorEvent);
97
- }
98
+ terminalEventObserved = true;
99
+ openMessageIds.clear();
100
+ openToolCalls.clear();
101
+ return appended;
102
+ };
103
+ return {
104
+ observe,
105
+ finalize
106
+ };
107
+ }
108
+ /**
109
+ * Array form of {@link createRunEventFinalizer} for callers that already keep
110
+ * the run's events (runners persist them). Appends the closers to `events` in
111
+ * place and returns them.
112
+ */
113
+ function finalizeRunEvents(events, options = {}) {
114
+ const finalizer = createRunEventFinalizer();
115
+ for (const event of events) finalizer.observe(event);
116
+ const appended = finalizer.finalize(options);
117
+ events.push(...appended);
98
118
  return appended;
99
119
  }
100
120
 
101
121
  //#endregion
102
- export { finalizeRunEvents };
122
+ export { createRunEventFinalizer, finalizeRunEvents };
103
123
  //# sourceMappingURL=finalize-events.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"finalize-events.mjs","names":[],"sources":["../src/finalize-events.ts"],"sourcesContent":["import type { BaseEvent, RunErrorEvent } from \"@ag-ui/client\";\nimport { EventType } from \"@ag-ui/client\";\nimport { randomUUID } from \"./utils\";\n\ninterface FinalizeRunOptions {\n stopRequested?: boolean;\n interruptionMessage?: string;\n}\n\nconst defaultStopMessage = \"Run stopped by user\";\nconst defaultAbruptEndMessage = \"Run ended without emitting a terminal event\";\n\nexport function finalizeRunEvents(\n events: BaseEvent[],\n options: FinalizeRunOptions = {},\n): BaseEvent[] {\n const { stopRequested = false, interruptionMessage } = options;\n\n const resolvedStopMessage = interruptionMessage ?? defaultStopMessage;\n const resolvedAbruptMessage =\n interruptionMessage && interruptionMessage !== defaultStopMessage\n ? interruptionMessage\n : defaultAbruptEndMessage;\n\n const appended: BaseEvent[] = [];\n\n const openMessageIds = new Set<string>();\n const openToolCalls = new Map<\n string,\n {\n hasEnd: boolean;\n hasResult: boolean;\n }\n >();\n\n for (const event of events) {\n switch (event.type) {\n case EventType.TEXT_MESSAGE_START: {\n const messageId = (event as { messageId?: string }).messageId;\n if (typeof messageId === \"string\") {\n openMessageIds.add(messageId);\n }\n break;\n }\n case EventType.TEXT_MESSAGE_END: {\n const messageId = (event as { messageId?: string }).messageId;\n if (typeof messageId === \"string\") {\n openMessageIds.delete(messageId);\n }\n break;\n }\n case EventType.TOOL_CALL_START: {\n const toolCallId = (event as { toolCallId?: string }).toolCallId;\n if (typeof toolCallId === \"string\") {\n openToolCalls.set(toolCallId, {\n hasEnd: false,\n hasResult: false,\n });\n }\n break;\n }\n case EventType.TOOL_CALL_END: {\n const toolCallId = (event as { toolCallId?: string }).toolCallId;\n const info = toolCallId ? openToolCalls.get(toolCallId) : undefined;\n if (info) {\n info.hasEnd = true;\n }\n break;\n }\n case EventType.TOOL_CALL_RESULT: {\n const toolCallId = (event as { toolCallId?: string }).toolCallId;\n const info = toolCallId ? openToolCalls.get(toolCallId) : undefined;\n if (info) {\n info.hasResult = true;\n }\n break;\n }\n default:\n break;\n }\n }\n\n const hasTerminalEvent = events.some(\n (event) =>\n event.type === EventType.RUN_FINISHED ||\n event.type === EventType.RUN_ERROR,\n );\n\n // Once a run has emitted a terminal event (RUN_FINISHED or RUN_ERROR), the\n // AG-UI spec forbids any further events for that run — the verifier rejects a\n // trailing TEXT_MESSAGE_END / TOOL_CALL_END with \"the run has already\n // errored/finished with '…'. No further events can be sent.\" (issue #5812).\n // These finalization events are streamed *after* everything the agent already\n // emitted, so appending closers here would place them after that terminal.\n // When a terminal already exists we therefore append nothing: any message or\n // tool call still open when the terminal arrived is implicitly closed by the\n // terminal on the client. We only synthesize closers + a terminal for a\n // stream that ended abruptly without a terminal of its own (below).\n if (hasTerminalEvent) {\n return appended;\n }\n\n for (const messageId of openMessageIds) {\n const endEvent = {\n type: EventType.TEXT_MESSAGE_END,\n messageId,\n } as BaseEvent;\n events.push(endEvent);\n appended.push(endEvent);\n }\n\n for (const [toolCallId, info] of openToolCalls) {\n if (!info.hasEnd) {\n const endEvent = {\n type: EventType.TOOL_CALL_END,\n toolCallId,\n } as BaseEvent;\n events.push(endEvent);\n appended.push(endEvent);\n }\n\n if (!info.hasResult) {\n const resultEvent = {\n type: EventType.TOOL_CALL_RESULT,\n toolCallId,\n messageId: `${toolCallId ?? randomUUID()}-result`,\n role: \"tool\",\n content: JSON.stringify(\n stopRequested\n ? {\n status: \"stopped\",\n reason: \"stop_requested\",\n message: resolvedStopMessage,\n }\n : {\n status: \"error\",\n reason: \"missing_terminal_event\",\n message: resolvedAbruptMessage,\n },\n ),\n } as BaseEvent;\n events.push(resultEvent);\n appended.push(resultEvent);\n }\n }\n\n if (stopRequested) {\n const finishedEvent = {\n type: EventType.RUN_FINISHED,\n } as BaseEvent;\n events.push(finishedEvent);\n appended.push(finishedEvent);\n } else {\n const errorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message: resolvedAbruptMessage,\n code: \"INCOMPLETE_STREAM\",\n };\n events.push(errorEvent);\n appended.push(errorEvent);\n }\n\n return appended;\n}\n"],"mappings":";;;;AASA,MAAM,qBAAqB;AAC3B,MAAM,0BAA0B;AAEhC,SAAgB,kBACd,QACA,UAA8B,EAAE,EACnB;CACb,MAAM,EAAE,gBAAgB,OAAO,wBAAwB;CAEvD,MAAM,sBAAsB,uBAAuB;CACnD,MAAM,wBACJ,uBAAuB,wBAAwB,qBAC3C,sBACA;CAEN,MAAM,WAAwB,EAAE;CAEhC,MAAM,iCAAiB,IAAI,KAAa;CACxC,MAAM,gCAAgB,IAAI,KAMvB;AAEH,MAAK,MAAM,SAAS,OAClB,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AQ;KACR,SAAS;KACV,GACD;KACE,QAAQ;KACR,QAAQ;KACR,SAAS;KACV,CACN;IACF;AACD,UAAO,KAAK,YAAY;AACxB,YAAS,KAAK,YAAY;;;AAI9B,KAAI,eAAe;EACjB,MAAM,gBAAgB,EACpB,MAAM,UAAU,cACjB;AACD,SAAO,KAAK,cAAc;AAC1B,WAAS,KAAK,cAAc;QACvB;EACL,MAAM,aAA4B;GAChC,MAAM,UAAU;GAChB,SAAS;GACT,MAAM;GACP;AACD,SAAO,KAAK,WAAW;AACvB,WAAS,KAAK,WAAW;;AAG3B,QAAO"}
1
+ {"version":3,"file":"finalize-events.mjs","names":[],"sources":["../src/finalize-events.ts"],"sourcesContent":["import type { BaseEvent, RunErrorEvent } from \"@ag-ui/client\";\nimport { EventType } from \"@ag-ui/client\";\n\nexport interface FinalizeRunOptions {\n stopRequested?: boolean;\n interruptionMessage?: string;\n}\n\nexport interface RunEventFinalizer {\n /** Observe one streamed event. Only the ids of open lifecycles are kept. */\n observe(event: BaseEvent): void;\n /** Return the events that close an interrupted or abruptly ended stream. */\n finalize(options?: FinalizeRunOptions): BaseEvent[];\n}\n\nconst defaultStopMessage = \"Run stopped by user\";\nconst defaultAbruptEndMessage = \"Run ended without emitting a terminal event\";\n\ninterface OpenToolCall {\n hasEnd: boolean;\n hasResult: boolean;\n}\n\n/**\n * Incremental finalizer for a streamed AG-UI run. Feed every event to\n * `observe`; when the stream ends without a terminal event, `finalize` returns\n * the closers for text messages and tool calls still open plus a terminal\n * event. Closed lifecycles are forgotten at once and payloads are never kept,\n * so a caller does not have to retain the event array for this purpose.\n */\nexport function createRunEventFinalizer(): RunEventFinalizer {\n const openMessageIds = new Set<string>();\n const openToolCalls = new Map<string, OpenToolCall>();\n let terminalEventObserved = false;\n\n const observe = (event: BaseEvent) => {\n if (terminalEventObserved) return;\n\n switch (event.type) {\n case EventType.TEXT_MESSAGE_START: {\n const messageId = (event as { messageId?: string }).messageId;\n if (messageId) openMessageIds.add(messageId);\n break;\n }\n case EventType.TEXT_MESSAGE_END: {\n const messageId = (event as { messageId?: string }).messageId;\n if (typeof messageId === \"string\") openMessageIds.delete(messageId);\n break;\n }\n case EventType.TOOL_CALL_START: {\n const toolCallId = (event as { toolCallId?: string }).toolCallId;\n if (toolCallId && !openToolCalls.has(toolCallId)) {\n openToolCalls.set(toolCallId, { hasEnd: false, hasResult: false });\n }\n break;\n }\n case EventType.TOOL_CALL_END:\n case EventType.TOOL_CALL_RESULT: {\n const toolCallId = (event as { toolCallId?: string }).toolCallId;\n if (!toolCallId) break;\n const info = openToolCalls.get(toolCallId);\n if (!info) break;\n\n if (event.type === EventType.TOOL_CALL_END) info.hasEnd = true;\n else info.hasResult = true;\n if (info.hasEnd && info.hasResult) openToolCalls.delete(toolCallId);\n break;\n }\n case EventType.RUN_FINISHED:\n case EventType.RUN_ERROR:\n terminalEventObserved = true;\n openMessageIds.clear();\n openToolCalls.clear();\n break;\n default:\n break;\n }\n };\n\n const finalize = (options: FinalizeRunOptions = {}): BaseEvent[] => {\n if (terminalEventObserved) return [];\n\n const { stopRequested = false, interruptionMessage } = options;\n const resolvedStopMessage = interruptionMessage ?? defaultStopMessage;\n const resolvedAbruptMessage =\n interruptionMessage && interruptionMessage !== defaultStopMessage\n ? interruptionMessage\n : defaultAbruptEndMessage;\n const appended: BaseEvent[] = [];\n\n for (const messageId of openMessageIds) {\n appended.push({\n type: EventType.TEXT_MESSAGE_END,\n messageId,\n } as BaseEvent);\n }\n\n for (const [toolCallId, info] of openToolCalls) {\n if (!info.hasEnd) {\n appended.push({\n type: EventType.TOOL_CALL_END,\n toolCallId,\n } as BaseEvent);\n }\n\n if (!info.hasResult) {\n appended.push({\n type: EventType.TOOL_CALL_RESULT,\n toolCallId,\n messageId: `${toolCallId}-result`,\n role: \"tool\",\n content: JSON.stringify(\n stopRequested\n ? {\n status: \"stopped\",\n reason: \"stop_requested\",\n message: resolvedStopMessage,\n }\n : {\n status: \"error\",\n reason: \"missing_terminal_event\",\n message: resolvedAbruptMessage,\n },\n ),\n } as BaseEvent);\n }\n }\n\n if (stopRequested) {\n appended.push({ type: EventType.RUN_FINISHED } as BaseEvent);\n } else {\n const errorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message: resolvedAbruptMessage,\n code: \"INCOMPLETE_STREAM\",\n };\n appended.push(errorEvent);\n }\n\n terminalEventObserved = true;\n openMessageIds.clear();\n openToolCalls.clear();\n return appended;\n };\n\n return { observe, finalize };\n}\n\n/**\n * Array form of {@link createRunEventFinalizer} for callers that already keep\n * the run's events (runners persist them). Appends the closers to `events` in\n * place and returns them.\n */\nexport function finalizeRunEvents(\n events: BaseEvent[],\n options: FinalizeRunOptions = {},\n): BaseEvent[] {\n const finalizer = createRunEventFinalizer();\n for (const event of events) finalizer.observe(event);\n\n const appended = finalizer.finalize(options);\n events.push(...appended);\n return appended;\n}\n"],"mappings":";;;AAeA,MAAM,qBAAqB;AAC3B,MAAM,0BAA0B;;;;;;;;AAchC,SAAgB,0BAA6C;CAC3D,MAAM,iCAAiB,IAAI,KAAa;CACxC,MAAM,gCAAgB,IAAI,KAA2B;CACrD,IAAI,wBAAwB;CAE5B,MAAM,WAAW,UAAqB;AACpC,MAAI,sBAAuB;AAE3B,UAAQ,MAAM,MAAd;GACE,KAAK,UAAU,oBAAoB;IACjC,MAAM,YAAa,MAAiC;AACpD,QAAI,UAAW,gBAAe,IAAI,UAAU;AAC5C;;GAEF,KAAK,UAAU,kBAAkB;IAC/B,MAAM,YAAa,MAAiC;AACpD,QAAI,OAAO,cAAc,SAAU,gBAAe,OAAO,UAAU;AACnE;;GAEF,KAAK,UAAU,iBAAiB;IAC9B,MAAM,aAAc,MAAkC;AACtD,QAAI,cAAc,CAAC,cAAc,IAAI,WAAW,CAC9C,eAAc,IAAI,YAAY;KAAE,QAAQ;KAAO,WAAW;KAAO,CAAC;AAEpE;;GAEF,KAAK,UAAU;GACf,KAAK,UAAU,kBAAkB;IAC/B,MAAM,aAAc,MAAkC;AACtD,Q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ACd,QACA,UAA8B,EAAE,EACnB;CACb,MAAM,YAAY,yBAAyB;AAC3C,MAAK,MAAM,SAAS,OAAQ,WAAU,QAAQ,MAAM;CAEpD,MAAM,WAAW,UAAU,SAAS,QAAQ;AAC5C,QAAO,KAAK,GAAG,SAAS;AACxB,QAAO"}
package/dist/index.cjs CHANGED
@@ -14,6 +14,7 @@ const require_index = require('./utils/index.cjs');
14
14
  const require_index$1 = require('./constants/index.cjs');
15
15
  const require_telemetry_disabled = require('./telemetry/telemetry-disabled.cjs');
16
16
  const require_sampling = require('./telemetry/sampling.cjs');
17
+ const require_model_host = require('./telemetry/model-host.cjs');
17
18
  const require_lambda_client = require('./telemetry/lambda-client.cjs');
18
19
  const require_debug = require('./debug.cjs');
19
20
  const require_standard_schema = require('./standard-schema.cjs');
@@ -89,6 +90,7 @@ exports.DEFAULT_AGENT_ID = require_index$1.DEFAULT_AGENT_ID;
89
90
  exports.ERROR_CONFIG = require_errors.ERROR_CONFIG;
90
91
  exports.ERROR_NAMES = require_errors.ERROR_NAMES;
91
92
  exports.ErrorVisibility = require_errors.ErrorVisibility;
93
+ exports.MODEL_HOST_CLASSES = require_model_host.MODEL_HOST_CLASSES;
92
94
  exports.MissingPublicApiKeyError = require_errors.MissingPublicApiKeyError;
93
95
  exports.RUNTIME_MODE_INTELLIGENCE = require_types.RUNTIME_MODE_INTELLIGENCE;
94
96
  exports.RUNTIME_MODE_SSE = require_types.RUNTIME_MODE_SSE;
@@ -96,14 +98,19 @@ exports.ResolvedCopilotKitError = require_errors.ResolvedCopilotKitError;
96
98
  exports.Severity = require_errors.Severity;
97
99
  exports.TELEMETRY_EMITTER_V1 = require_sampling.TELEMETRY_EMITTER_V1;
98
100
  exports.TELEMETRY_EMITTER_V2 = require_sampling.TELEMETRY_EMITTER_V2;
101
+ exports.TELEMETRY_SURFACE_V1 = require_sampling.TELEMETRY_SURFACE_V1;
102
+ exports.TELEMETRY_SURFACE_V2 = require_sampling.TELEMETRY_SURFACE_V2;
99
103
  exports.TranscriptionErrorCode = require_transcription_errors.TranscriptionErrorCode;
100
104
  exports.TranscriptionErrors = require_transcription_errors.TranscriptionErrors;
105
+ exports.UNSAMPLED_RATE = require_sampling.UNSAMPLED_RATE;
101
106
  exports.UpgradeRequiredError = require_errors.UpgradeRequiredError;
102
107
  exports.actionParametersToJsonSchema = require_json_schema.actionParametersToJsonSchema;
108
+ exports.classifyModelHost = require_model_host.classifyModelHost;
103
109
  exports.computeSamplingMeta = require_sampling.computeSamplingMeta;
104
110
  exports.convertJsonSchemaToZodSchema = require_json_schema.convertJsonSchemaToZodSchema;
105
111
  exports.copyToClipboard = require_clipboard.copyToClipboard;
106
112
  exports.createLicenseContextValue = createLicenseContextValue;
113
+ exports.createRunEventFinalizer = require_finalize_events.createRunEventFinalizer;
107
114
  exports.dataToUUID = require_random_id.dataToUUID;
108
115
  exports.ensureStructuredError = require_errors.ensureStructuredError;
109
116
  exports.exceedsMaxSize = require_utils.exceedsMaxSize;