@copilotkit/shared 1.72.1-canary.sp-longthread-perf → 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.
@@ -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,EAAE;CAEhC,MAAM,iCAAiB,IAAI,KAAa;CACxC,MAAM,gCAAgB,IAAI,KAMvB;AAEH,MAAK,MAAM,SAAS,OAClB,SAAQ,MAAM,MAAd;EACE,KAAKA,wBAAU,oBAAoB;GACjC,MAAM,YAAa,MAAiC;AACpD,OAAI,OAAO,cAAc,SACvB,gBA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AO,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,CAC9C,eAAc,IAAI,YAAY;KAAE,QAAQ;KAAO,WAAW;KAAO,CAAC;AAEpE;;GAEF,KAAKA,wBAAU;GACf,KAAKA,wBAAU,kBAAkB;IAC/B,MAAM,aAAc,MAAkC;AACtD,QAAI,CAAC,WAAY;IACjB,MAAM,OAAO,cAAc,IAAI,WAAW;AAC1C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AY,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,SAAQ,MAAM,MAAd;EACE,KAAK,UAAU,oBAAoB;GACjC,MAAM,YAAa,MAAiC;AACpD,OAAI,OAAO,cAAc,SACvB,gBAAe,IAAI,UAAU;AAE/B;;EAEF,KAAK,UAAU,kBAAkB;GAC/B,MAAM,YAAa,MAAiC;AACpD,OAAI,OAAO,cAAc,SAC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Ac;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,QAAI,CAAC,WAAY;IACjB,MAAM,OAAO,cAAc,IAAI,WAAW;AAC1C,QAAI,CAAC,KAAM;AAEX,QAAI,MAAM,SAAS,UAAU,cAAe,MAAK,SAAS;QACrD,MAAK,YAAY;AACtB,QAAI,KAAK,UAAU,KAAK,UAAW,eAAc,OAAO,WAAW;AACnE;;G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
@@ -110,6 +110,7 @@ exports.computeSamplingMeta = require_sampling.computeSamplingMeta;
110
110
  exports.convertJsonSchemaToZodSchema = require_json_schema.convertJsonSchemaToZodSchema;
111
111
  exports.copyToClipboard = require_clipboard.copyToClipboard;
112
112
  exports.createLicenseContextValue = createLicenseContextValue;
113
+ exports.createRunEventFinalizer = require_finalize_events.createRunEventFinalizer;
113
114
  exports.dataToUUID = require_random_id.dataToUUID;
114
115
  exports.ensureStructuredError = require_errors.ensureStructuredError;
115
116
  exports.exceedsMaxSize = require_utils.exceedsMaxSize;
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["export * from \"./types\";\nexport * from \"./utils\";\nexport * from \"./constants\";\n// Telemetry is split deliberately. `TelemetryClient` imports\n// `@segment/analytics-node`, which imports `node-fetch`, which imports the\n// Node built-ins `stream`, `http`, `https` and `zlib`. Browser bundlers\n// resolve the whole module graph before they tree-shake, so re-exporting\n// that module here made every browser build of a dependent package print\n// \"Module ... has been externalized for browser compatibility\" warnings,\n// even when the consumer never touched telemetry (#4151). Only the\n// browser-safe telemetry surface is re-exported from this entry. Server\n// code that needs the client imports it from `@copilotkit/shared/telemetry`.\n// This mirrors the license-verifier note below.\nexport { isTelemetryDisabled } from \"./telemetry/telemetry-disabled\";\nexport * from \"./telemetry/sampling\";\n// Pure string classification with no imports, so it carries no runtime edge\n// into browser builds — same reasoning as `sampling` above.\nexport * from \"./telemetry/model-host\";\nexport {\n firstNonBlankTelemetryId,\n lambdaClient,\n parseTelemetryIdFromLicense,\n parseAndWarnTelemetryId,\n} from \"./telemetry/lambda-client\";\nexport type { LambdaSendOptions } from \"./telemetry/lambda-client\";\n// Types only: erased at build time, so they add no runtime edge to\n// `telemetry-client.ts` and therefore none to @segment/analytics-node.\nexport type {\n TelemetryCapture,\n TelemetryIdentity,\n} from \"./telemetry/telemetry-client\";\nexport * from \"./debug\";\nexport * from \"./standard-schema\";\nexport * from \"./attachments\";\n\nexport { logger } from \"./logger\";\nexport { finalizeRunEvents } from \"./finalize-events\";\n\nexport {\n TranscriptionErrorCode,\n TranscriptionErrors,\n type TranscriptionErrorResponse,\n} from \"./transcription-errors\";\n\nimport * as packageJson from \"../package.json\";\nexport const COPILOTKIT_VERSION = packageJson.version;\n\n// Re-export only types from license-verifier (types are erased at compile time,\n// so they don't pull in the Node-only `crypto` dependency into client bundles).\n// Server-side packages (e.g. @copilotkit/runtime) should import runtime functions\n// like createLicenseChecker and getLicenseWarningHeader directly from\n// @copilotkit/license-verifier.\nexport type {\n LicenseChecker,\n LicenseStatus,\n LicensePayload,\n LicenseFeatures,\n LicenseTier,\n LicenseOwner,\n} from \"@copilotkit/license-verifier\";\n\nimport type { LicensePayload } from \"@copilotkit/license-verifier\";\nimport type {\n RuntimeEntitlementResponse,\n RuntimeLicenseStatus,\n} from \"./utils/types\";\n\n// LicenseContextValue was dropped from license-verifier's public API in\n// 0.3.0, so it is defined here. The context shape is owned by this package\n// anyway via createLicenseContextValue below.\n\n/**\n * License context value exposed to child components.\n * Frontend providers create their own context using this shape.\n */\nexport interface LicenseContextValue {\n /** Effective license status after structured entitlement precedence. Null until known. */\n status: RuntimeLicenseStatus | null;\n /** The license payload if available. Always null on the client; the payload stays server-side. */\n license: LicensePayload | null;\n /** Whether a feature is licensed. Ready entitlements override legacy status behavior. */\n checkFeature: (feature: string) => boolean;\n /** Get a numeric feature limit. Zero means unlimited; null means not applicable. */\n getLimit: (feature: string) => number | null;\n}\n\n/** Read a record value without traversing its prototype chain. */\nfunction getOwnRecordValue<Value>(\n record: Readonly<Record<string, Value>>,\n key: string,\n): Value | undefined {\n return Object.prototype.hasOwnProperty.call(record, key)\n ? record[key]\n : undefined;\n}\n\n/** Legacy UI surfaces that remain available for every active entitlement. */\nfunction isLegacyUiFeature(feature: string): boolean {\n return feature === \"chat\" || feature === \"popup\" || feature === \"sidebar\";\n}\n\n/**\n * Client-safe license context factory, driven by the license authority the\n * runtime reports via /info.\n *\n * A ready managed entitlement is authoritative in both directions. A ready\n * active self-hosted entitlement is also authoritative, while an inactive\n * self-hosted response preserves the legacy signed-license fallback. Active\n * entitlements supply feature grants and limits; authoritative inactive\n * entitlements deny every feature and limit. Older runtimes that report only a\n * status retain the legacy behavior: features are enabled unless the status is\n * \"expired\" or \"invalid\", and no limits are reported. This is inlined here to\n * avoid importing the full license-verifier bundle (which depends on Node's\n * `crypto`) into browser bundles.\n */\nexport function createLicenseContextValue(\n status: RuntimeLicenseStatus | null | undefined,\n runtimeEntitlements?: RuntimeEntitlementResponse,\n): LicenseContextValue {\n const readyEntitlement =\n runtimeEntitlements?.status === \"ready\"\n ? runtimeEntitlements.entitlement\n : null;\n const hasUsableSelfHostedLegacyFallback =\n readyEntitlement &&\n !readyEntitlement.active &&\n readyEntitlement.source === \"selfHostedDeploymentLicense\" &&\n (status === \"valid\" || status === \"expiring\");\n const featureAuthority =\n readyEntitlement && !hasUsableSelfHostedLegacyFallback\n ? readyEntitlement\n : null;\n const activeEntitlement = featureAuthority?.active ? featureAuthority : null;\n const resolvedStatus = activeEntitlement\n ? \"valid\"\n : readyEntitlement?.source === \"managedOrgSubscription\" ||\n readyEntitlement?.source === \"awsMarketplaceDeploymentLicense\"\n ? \"none\"\n : featureAuthority\n ? (status ?? \"none\")\n : (status ?? null);\n const featuresEnabled =\n resolvedStatus !== \"expired\" && resolvedStatus !== \"invalid\";\n\n return {\n status: resolvedStatus,\n license: null,\n checkFeature: (feature) =>\n featureAuthority\n ? activeEntitlement\n ? feature === \"threads\" &&\n Object.prototype.hasOwnProperty.call(\n activeEntitlement.limits,\n \"threads.max_count\",\n )\n ? true\n : (getOwnRecordValue(activeEntitlement.features, feature) ??\n isLegacyUiFeature(feature))\n : false\n : featuresEnabled,\n getLimit: (feature) =>\n activeEntitlement\n ? (getOwnRecordValue(activeEntitlement.limits, feature) ?? null)\n : null,\n };\n}\n\nexport {\n A2UI_DEFAULT_GENERATION_GUIDELINES,\n A2UI_DEFAULT_DESIGN_GUIDELINES,\n} from \"./a2ui-prompts\";\n\nexport type { DebugEventEnvelope } from \"./debug-event-envelope\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,MAAa;;AA0Cb,SAAS,kBACP,QACA,KACmB;AACnB,QAAO,OAAO,UAAU,eAAe,KAAK,QAAQ,IAAI,GACpD,OAAO,OACP;;;AAIN,SAAS,kBAAkB,SAA0B;AACnD,QAAO,YAAY,UAAU,YAAY,WAAW,YAAY;;;;;;;;;;;;;;;;AAiBlE,SAAgB,0BACd,QACA,qBACqB;CACrB,MAAM,mBACJ,qBAAqB,WAAW,UAC5B,oBAAoB,cACpB;CACN,MAAM,oCACJ,oBACA,CAAC,iBAAiB,UAClB,iBAAiB,WAAW,kCAC3B,WAAW,WAAW,WAAW;CACpC,MAAM,mBACJ,oBAAoB,CAAC,oCACjB,mBACA;CACN,MAAM,oBAAoB,kBAAkB,SAAS,mBAAmB;CACxE,MAAM,iBAAiB,oBACnB,UACA,kBAAkB,WAAW,4BAC3B,kBAAkB,WAAW,oCAC7B,SACA,mBACG,UAAU,SACV,UAAU;CACnB,MAAM,kBACJ,mBAAmB,aAAa,mBAAmB;AAErD,QAAO;EACL,QAAQ;EACR,SAAS;EACT,eAAe,YACb,mBACI,oBACE,YAAY,aACZ,OAAO,UAAU,eAAe,KAC9B,kBAAkB,QAClB,oBACD,GACC,OACC,kBAAkB,kBAAkB,UAAU,QAAQ,IACvD,kBAAkB,QAAQ,GAC5B,QACF;EACN,WAAW,YACT,oBACK,kBAAkB,kBAAkB,QAAQ,QAAQ,IAAI,OACzD;EACP"}
1
+ {"version":3,"file":"index.cjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["export * from \"./types\";\nexport * from \"./utils\";\nexport * from \"./constants\";\n// Telemetry is split deliberately. `TelemetryClient` imports\n// `@segment/analytics-node`, which imports `node-fetch`, which imports the\n// Node built-ins `stream`, `http`, `https` and `zlib`. Browser bundlers\n// resolve the whole module graph before they tree-shake, so re-exporting\n// that module here made every browser build of a dependent package print\n// \"Module ... has been externalized for browser compatibility\" warnings,\n// even when the consumer never touched telemetry (#4151). Only the\n// browser-safe telemetry surface is re-exported from this entry. Server\n// code that needs the client imports it from `@copilotkit/shared/telemetry`.\n// This mirrors the license-verifier note below.\nexport { isTelemetryDisabled } from \"./telemetry/telemetry-disabled\";\nexport * from \"./telemetry/sampling\";\n// Pure string classification with no imports, so it carries no runtime edge\n// into browser builds — same reasoning as `sampling` above.\nexport * from \"./telemetry/model-host\";\nexport {\n firstNonBlankTelemetryId,\n lambdaClient,\n parseTelemetryIdFromLicense,\n parseAndWarnTelemetryId,\n} from \"./telemetry/lambda-client\";\nexport type { LambdaSendOptions } from \"./telemetry/lambda-client\";\n// Types only: erased at build time, so they add no runtime edge to\n// `telemetry-client.ts` and therefore none to @segment/analytics-node.\nexport type {\n TelemetryCapture,\n TelemetryIdentity,\n} from \"./telemetry/telemetry-client\";\nexport * from \"./debug\";\nexport * from \"./standard-schema\";\nexport * from \"./attachments\";\n\nexport { logger } from \"./logger\";\nexport {\n createRunEventFinalizer,\n finalizeRunEvents,\n type FinalizeRunOptions,\n type RunEventFinalizer,\n} from \"./finalize-events\";\n\nexport {\n TranscriptionErrorCode,\n TranscriptionErrors,\n type TranscriptionErrorResponse,\n} from \"./transcription-errors\";\n\nimport * as packageJson from \"../package.json\";\nexport const COPILOTKIT_VERSION = packageJson.version;\n\n// Re-export only types from license-verifier (types are erased at compile time,\n// so they don't pull in the Node-only `crypto` dependency into client bundles).\n// Server-side packages (e.g. @copilotkit/runtime) should import runtime functions\n// like createLicenseChecker and getLicenseWarningHeader directly from\n// @copilotkit/license-verifier.\nexport type {\n LicenseChecker,\n LicenseStatus,\n LicensePayload,\n LicenseFeatures,\n LicenseTier,\n LicenseOwner,\n} from \"@copilotkit/license-verifier\";\n\nimport type { LicensePayload } from \"@copilotkit/license-verifier\";\nimport type {\n RuntimeEntitlementResponse,\n RuntimeLicenseStatus,\n} from \"./utils/types\";\n\n// LicenseContextValue was dropped from license-verifier's public API in\n// 0.3.0, so it is defined here. The context shape is owned by this package\n// anyway via createLicenseContextValue below.\n\n/**\n * License context value exposed to child components.\n * Frontend providers create their own context using this shape.\n */\nexport interface LicenseContextValue {\n /** Effective license status after structured entitlement precedence. Null until known. */\n status: RuntimeLicenseStatus | null;\n /** The license payload if available. Always null on the client; the payload stays server-side. */\n license: LicensePayload | null;\n /** Whether a feature is licensed. Ready entitlements override legacy status behavior. */\n checkFeature: (feature: string) => boolean;\n /** Get a numeric feature limit. Zero means unlimited; null means not applicable. */\n getLimit: (feature: string) => number | null;\n}\n\n/** Read a record value without traversing its prototype chain. */\nfunction getOwnRecordValue<Value>(\n record: Readonly<Record<string, Value>>,\n key: string,\n): Value | undefined {\n return Object.prototype.hasOwnProperty.call(record, key)\n ? record[key]\n : undefined;\n}\n\n/** Legacy UI surfaces that remain available for every active entitlement. */\nfunction isLegacyUiFeature(feature: string): boolean {\n return feature === \"chat\" || feature === \"popup\" || feature === \"sidebar\";\n}\n\n/**\n * Client-safe license context factory, driven by the license authority the\n * runtime reports via /info.\n *\n * A ready managed entitlement is authoritative in both directions. A ready\n * active self-hosted entitlement is also authoritative, while an inactive\n * self-hosted response preserves the legacy signed-license fallback. Active\n * entitlements supply feature grants and limits; authoritative inactive\n * entitlements deny every feature and limit. Older runtimes that report only a\n * status retain the legacy behavior: features are enabled unless the status is\n * \"expired\" or \"invalid\", and no limits are reported. This is inlined here to\n * avoid importing the full license-verifier bundle (which depends on Node's\n * `crypto`) into browser bundles.\n */\nexport function createLicenseContextValue(\n status: RuntimeLicenseStatus | null | undefined,\n runtimeEntitlements?: RuntimeEntitlementResponse,\n): LicenseContextValue {\n const readyEntitlement =\n runtimeEntitlements?.status === \"ready\"\n ? runtimeEntitlements.entitlement\n : null;\n const hasUsableSelfHostedLegacyFallback =\n readyEntitlement &&\n !readyEntitlement.active &&\n readyEntitlement.source === \"selfHostedDeploymentLicense\" &&\n (status === \"valid\" || status === \"expiring\");\n const featureAuthority =\n readyEntitlement && !hasUsableSelfHostedLegacyFallback\n ? readyEntitlement\n : null;\n const activeEntitlement = featureAuthority?.active ? featureAuthority : null;\n const resolvedStatus = activeEntitlement\n ? \"valid\"\n : readyEntitlement?.source === \"managedOrgSubscription\" ||\n readyEntitlement?.source === \"awsMarketplaceDeploymentLicense\"\n ? \"none\"\n : featureAuthority\n ? (status ?? \"none\")\n : (status ?? null);\n const featuresEnabled =\n resolvedStatus !== \"expired\" && resolvedStatus !== \"invalid\";\n\n return {\n status: resolvedStatus,\n license: null,\n checkFeature: (feature) =>\n featureAuthority\n ? activeEntitlement\n ? feature === \"threads\" &&\n Object.prototype.hasOwnProperty.call(\n activeEntitlement.limits,\n \"threads.max_count\",\n )\n ? true\n : (getOwnRecordValue(activeEntitlement.features, feature) ??\n isLegacyUiFeature(feature))\n : false\n : featuresEnabled,\n getLimit: (feature) =>\n activeEntitlement\n ? (getOwnRecordValue(activeEntitlement.limits, feature) ?? null)\n : null,\n };\n}\n\nexport {\n A2UI_DEFAULT_GENERATION_GUIDELINES,\n A2UI_DEFAULT_DESIGN_GUIDELINES,\n} from \"./a2ui-prompts\";\n\nexport type { DebugEventEnvelope } from \"./debug-event-envelope\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDA,MAAa;;AA0Cb,SAAS,kBACP,QACA,KACmB;AACnB,QAAO,OAAO,UAAU,eAAe,KAAK,QAAQ,IAAI,GACpD,OAAO,OACP;;;AAIN,SAAS,kBAAkB,SAA0B;AACnD,QAAO,YAAY,UAAU,YAAY,WAAW,YAAY;;;;;;;;;;;;;;;;AAiBlE,SAAgB,0BACd,QACA,qBACqB;CACrB,MAAM,mBACJ,qBAAqB,WAAW,UAC5B,oBAAoB,cACpB;CACN,MAAM,oCACJ,oBACA,CAAC,iBAAiB,UAClB,iBAAiB,WAAW,kCAC3B,WAAW,WAAW,WAAW;CACpC,MAAM,mBACJ,oBAAoB,CAAC,oCACjB,mBACA;CACN,MAAM,oBAAoB,kBAAkB,SAAS,mBAAmB;CACxE,MAAM,iBAAiB,oBACnB,UACA,kBAAkB,WAAW,4BAC3B,kBAAkB,WAAW,oCAC7B,SACA,mBACG,UAAU,SACV,UAAU;CACnB,MAAM,kBACJ,mBAAmB,aAAa,mBAAmB;AAErD,QAAO;EACL,QAAQ;EACR,SAAS;EACT,eAAe,YACb,mBACI,oBACE,YAAY,aACZ,OAAO,UAAU,eAAe,KAC9B,kBAAkB,QAClB,oBACD,GACC,OACC,kBAAkB,kBAAkB,UAAU,QAAQ,IACvD,kBAAkB,QAAQ,GAC5B,QACF;EACN,WAAW,YACT,oBACK,kBAAkB,kBAAkB,QAAQ,QAAQ,IAAI,OACzD;EACP"}