@copilotkit/shared 1.73.0 → 1.73.2-canary.1790068297
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -0
- package/dist/attachments/content.cjs +17 -0
- package/dist/attachments/content.cjs.map +1 -0
- package/dist/attachments/content.d.cts +9 -0
- package/dist/attachments/content.d.cts.map +1 -0
- package/dist/attachments/content.d.mts +9 -0
- package/dist/attachments/content.d.mts.map +1 -0
- package/dist/attachments/content.mjs +16 -0
- package/dist/attachments/content.mjs.map +1 -0
- package/dist/event-transforms/index.cjs +15 -0
- package/dist/event-transforms/index.d.cts +4 -0
- package/dist/event-transforms/index.d.mts +4 -0
- package/dist/event-transforms/index.mjs +5 -0
- package/dist/event-transforms/open-generative-ui-middleware.cjs +286 -0
- package/dist/event-transforms/open-generative-ui-middleware.cjs.map +1 -0
- package/dist/event-transforms/open-generative-ui-middleware.d.cts +60 -0
- package/dist/event-transforms/open-generative-ui-middleware.d.cts.map +1 -0
- package/dist/event-transforms/open-generative-ui-middleware.d.mts +60 -0
- package/dist/event-transforms/open-generative-ui-middleware.d.mts.map +1 -0
- package/dist/event-transforms/open-generative-ui-middleware.mjs +283 -0
- package/dist/event-transforms/open-generative-ui-middleware.mjs.map +1 -0
- package/dist/event-transforms/recorded-events.cjs +59 -0
- package/dist/event-transforms/recorded-events.cjs.map +1 -0
- package/dist/event-transforms/recorded-events.d.cts +23 -0
- package/dist/event-transforms/recorded-events.d.cts.map +1 -0
- package/dist/event-transforms/recorded-events.d.mts +23 -0
- package/dist/event-transforms/recorded-events.d.mts.map +1 -0
- package/dist/event-transforms/recorded-events.mjs +58 -0
- package/dist/event-transforms/recorded-events.mjs.map +1 -0
- package/dist/index.cjs +8 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -1
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +3 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +3 -1
- package/dist/index.mjs.map +1 -1
- package/dist/index.umd.js +224 -1
- package/dist/index.umd.js.map +1 -1
- package/dist/package.cjs +1 -1
- package/dist/package.mjs +1 -1
- package/dist/types/message.d.cts +3 -3
- package/dist/types/message.d.cts.map +1 -1
- package/dist/types/message.d.mts +3 -3
- package/dist/types/message.d.mts.map +1 -1
- package/dist/utils/index.cjs +1 -0
- package/dist/utils/index.cjs.map +1 -1
- package/dist/utils/index.d.cts +1 -0
- package/dist/utils/index.d.cts.map +1 -1
- package/dist/utils/index.d.mts +1 -0
- package/dist/utils/index.d.mts.map +1 -1
- package/dist/utils/index.mjs +1 -0
- package/dist/utils/index.mjs.map +1 -1
- package/dist/utils/row-render-keys.cjs +206 -0
- package/dist/utils/row-render-keys.cjs.map +1 -0
- package/dist/utils/row-render-keys.d.cts +65 -0
- package/dist/utils/row-render-keys.d.cts.map +1 -0
- package/dist/utils/row-render-keys.d.mts +65 -0
- package/dist/utils/row-render-keys.d.mts.map +1 -0
- package/dist/utils/row-render-keys.mjs +201 -0
- package/dist/utils/row-render-keys.mjs.map +1 -0
- package/package.json +12 -1
- package/src/__tests__/root-entry-browser-safety.test.ts +7 -1
- package/src/attachments/content.test.ts +48 -0
- package/src/attachments/content.ts +16 -0
- package/src/attachments/index.ts +2 -0
- package/src/event-transforms/index.ts +5 -0
- package/src/event-transforms/open-generative-ui-middleware.ts +392 -0
- package/src/event-transforms/recorded-events.test.ts +166 -0
- package/src/event-transforms/recorded-events.ts +74 -0
- package/src/utils/__tests__/row-render-keys.test.ts +388 -0
- package/src/utils/index.ts +1 -0
- package/src/utils/row-render-keys.ts +263 -0
- package/tsdown.config.ts +7 -4
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
import { EventType, Middleware } from "@ag-ui/client";
|
|
2
|
+
import { Observable } from "rxjs";
|
|
3
|
+
import clarinet from "clarinet";
|
|
4
|
+
|
|
5
|
+
//#region src/event-transforms/open-generative-ui-middleware.ts
|
|
6
|
+
const TOOL_NAME = "generateSandboxedUi";
|
|
7
|
+
const ACTIVITY_TYPE = "open-generative-ui";
|
|
8
|
+
/**
|
|
9
|
+
* Tracks incremental JSON parsing state for a single tool call's arguments.
|
|
10
|
+
* Emits activity events via the onEvent callback as parameters complete.
|
|
11
|
+
*/
|
|
12
|
+
var ArgsParser = class {
|
|
13
|
+
constructor(toolCallId, onEvent) {
|
|
14
|
+
this.currentKey = null;
|
|
15
|
+
this.depth = 0;
|
|
16
|
+
this.currentArrayKey = null;
|
|
17
|
+
this.snapshotEmitted = false;
|
|
18
|
+
this.streamingHtmlKey = false;
|
|
19
|
+
this.htmlEmittedLength = 0;
|
|
20
|
+
this.htmlArrayEmitted = false;
|
|
21
|
+
this.params = {};
|
|
22
|
+
this.messageId = `${toolCallId}-activity`;
|
|
23
|
+
this.onEvent = onEvent;
|
|
24
|
+
this.parser = clarinet.parser();
|
|
25
|
+
this.parser.onopenobject = (key) => {
|
|
26
|
+
this.depth++;
|
|
27
|
+
if (key !== void 0 && this.depth === 1) {
|
|
28
|
+
this.currentKey = key;
|
|
29
|
+
this.initHtmlStreaming(key);
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
this.parser.onkey = (key) => {
|
|
33
|
+
if (this.depth === 1) {
|
|
34
|
+
this.currentKey = key;
|
|
35
|
+
this.initHtmlStreaming(key);
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
this.parser.onvalue = (value) => {
|
|
39
|
+
if (this.depth === 1 && this.currentKey) if (this.currentArrayKey) {
|
|
40
|
+
const strValue = String(value);
|
|
41
|
+
if (this.currentArrayKey === "jsExpressions") {
|
|
42
|
+
if (!this.params.jsExpressions) this.params.jsExpressions = [];
|
|
43
|
+
this.params.jsExpressions.push(strValue);
|
|
44
|
+
} else if (this.currentArrayKey === "placeholderMessages") {
|
|
45
|
+
if (!this.params.placeholderMessages) this.params.placeholderMessages = [];
|
|
46
|
+
this.params.placeholderMessages.push(strValue);
|
|
47
|
+
}
|
|
48
|
+
this.emitArrayItemDelta(this.currentArrayKey, strValue);
|
|
49
|
+
} else if (this.streamingHtmlKey) {
|
|
50
|
+
const fullHtml = value != null ? String(value) : "";
|
|
51
|
+
this.params.html = fullHtml || void 0;
|
|
52
|
+
this.emitPendingHtml(fullHtml);
|
|
53
|
+
this.emitParamDelta("htmlComplete", true);
|
|
54
|
+
this.streamingHtmlKey = false;
|
|
55
|
+
} else this.setParam(this.currentKey, value);
|
|
56
|
+
};
|
|
57
|
+
this.parser.onopenarray = () => {
|
|
58
|
+
if (this.depth === 1 && this.currentKey) {
|
|
59
|
+
const key = this.currentKey;
|
|
60
|
+
if (key === "jsExpressions" || key === "placeholderMessages") {
|
|
61
|
+
this.currentArrayKey = key;
|
|
62
|
+
if (key === "jsExpressions") this.params.jsExpressions = [];
|
|
63
|
+
else this.params.placeholderMessages = [];
|
|
64
|
+
this.emitParamDelta(key, []);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
this.parser.onclosearray = () => {
|
|
69
|
+
if (this.depth === 1) {
|
|
70
|
+
if (this.currentArrayKey === "jsExpressions") this.emitParamDelta("jsExpressionsComplete", true);
|
|
71
|
+
this.currentArrayKey = null;
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
this.parser.oncloseobject = () => {
|
|
75
|
+
this.depth--;
|
|
76
|
+
};
|
|
77
|
+
this.parser.onerror = (err) => {
|
|
78
|
+
console.warn("[OpenGenerativeUI] JSON parse error in streaming args, resuming:", err?.message ?? err);
|
|
79
|
+
this.parser.error = null;
|
|
80
|
+
this.parser.resume();
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
write(chunk) {
|
|
84
|
+
this.parser.write(chunk);
|
|
85
|
+
this.flushHtmlChunks();
|
|
86
|
+
}
|
|
87
|
+
initHtmlStreaming(key) {
|
|
88
|
+
if (key === "html") {
|
|
89
|
+
this.streamingHtmlKey = true;
|
|
90
|
+
this.htmlEmittedLength = 0;
|
|
91
|
+
this.htmlArrayEmitted = false;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Read clarinet's internal textNode buffer to emit html chunks incrementally.
|
|
96
|
+
* Called after every write() so partial string content is emitted as it streams in.
|
|
97
|
+
*/
|
|
98
|
+
flushHtmlChunks() {
|
|
99
|
+
if (!this.streamingHtmlKey) return;
|
|
100
|
+
const textNode = this.parser.textNode;
|
|
101
|
+
if (typeof textNode !== "string") return;
|
|
102
|
+
if (textNode.length === this.htmlEmittedLength) return;
|
|
103
|
+
this.emitPendingHtml(textNode);
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Emit accumulated html content since the last emission.
|
|
107
|
+
* Called by flushHtmlChunks and directly when html completes.
|
|
108
|
+
*/
|
|
109
|
+
emitPendingHtml(textNode) {
|
|
110
|
+
const newContent = textNode.slice(this.htmlEmittedLength);
|
|
111
|
+
if (newContent.length === 0) return;
|
|
112
|
+
if (!this.htmlArrayEmitted) {
|
|
113
|
+
this.htmlArrayEmitted = true;
|
|
114
|
+
this.emitParamDelta("html", []);
|
|
115
|
+
}
|
|
116
|
+
this.emitArrayItemDelta("html", newContent);
|
|
117
|
+
this.htmlEmittedLength = textNode.length;
|
|
118
|
+
}
|
|
119
|
+
setParam(key, value) {
|
|
120
|
+
switch (key) {
|
|
121
|
+
case "initialHeight":
|
|
122
|
+
this.params.initialHeight = typeof value === "number" ? value : void 0;
|
|
123
|
+
if (this.snapshotEmitted) this.emitParamDelta("initialHeight", this.params.initialHeight);
|
|
124
|
+
else this.emitSnapshot();
|
|
125
|
+
break;
|
|
126
|
+
case "css":
|
|
127
|
+
this.params.css = value != null ? String(value) : void 0;
|
|
128
|
+
this.emitParamDelta("css", this.params.css);
|
|
129
|
+
this.emitParamDelta("cssComplete", true);
|
|
130
|
+
break;
|
|
131
|
+
case "jsFunctions":
|
|
132
|
+
this.params.jsFunctions = value != null ? String(value) : void 0;
|
|
133
|
+
this.emitParamDelta("jsFunctions", this.params.jsFunctions);
|
|
134
|
+
this.emitParamDelta("jsFunctionsComplete", true);
|
|
135
|
+
break;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
emitSnapshot() {
|
|
139
|
+
if (this.snapshotEmitted) return;
|
|
140
|
+
this.snapshotEmitted = true;
|
|
141
|
+
const event = {
|
|
142
|
+
type: EventType.ACTIVITY_SNAPSHOT,
|
|
143
|
+
messageId: this.messageId,
|
|
144
|
+
activityType: ACTIVITY_TYPE,
|
|
145
|
+
content: {
|
|
146
|
+
initialHeight: this.params.initialHeight,
|
|
147
|
+
generating: true
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
this.onEvent(event);
|
|
151
|
+
}
|
|
152
|
+
emitParamDelta(key, value) {
|
|
153
|
+
if (value === void 0) return;
|
|
154
|
+
this.emitSnapshot();
|
|
155
|
+
const event = {
|
|
156
|
+
type: EventType.ACTIVITY_DELTA,
|
|
157
|
+
messageId: this.messageId,
|
|
158
|
+
activityType: ACTIVITY_TYPE,
|
|
159
|
+
patch: [{
|
|
160
|
+
op: "add",
|
|
161
|
+
path: `/${key}`,
|
|
162
|
+
value
|
|
163
|
+
}]
|
|
164
|
+
};
|
|
165
|
+
this.onEvent(event);
|
|
166
|
+
}
|
|
167
|
+
emitArrayItemDelta(arrayKey, value) {
|
|
168
|
+
this.emitSnapshot();
|
|
169
|
+
const event = {
|
|
170
|
+
type: EventType.ACTIVITY_DELTA,
|
|
171
|
+
messageId: this.messageId,
|
|
172
|
+
activityType: ACTIVITY_TYPE,
|
|
173
|
+
patch: [{
|
|
174
|
+
op: "add",
|
|
175
|
+
path: `/${arrayKey}/-`,
|
|
176
|
+
value
|
|
177
|
+
}]
|
|
178
|
+
};
|
|
179
|
+
this.onEvent(event);
|
|
180
|
+
}
|
|
181
|
+
};
|
|
182
|
+
var OpenGenerativeUIMiddleware = class extends Middleware {
|
|
183
|
+
run(input, next) {
|
|
184
|
+
return this.processStream(this.runNextWithState(input, next));
|
|
185
|
+
}
|
|
186
|
+
processStream(source) {
|
|
187
|
+
return new Observable((subscriber) => {
|
|
188
|
+
let heldRunFinished = null;
|
|
189
|
+
const activeParsers = /* @__PURE__ */ new Map();
|
|
190
|
+
const heldToolCallEvents = /* @__PURE__ */ new Map();
|
|
191
|
+
const flushedToolCalls = /* @__PURE__ */ new Set();
|
|
192
|
+
const flushHeldEvents = (toolCallId) => {
|
|
193
|
+
if (flushedToolCalls.has(toolCallId)) return;
|
|
194
|
+
flushedToolCalls.add(toolCallId);
|
|
195
|
+
const held = heldToolCallEvents.get(toolCallId);
|
|
196
|
+
if (held) {
|
|
197
|
+
for (const e of held) subscriber.next(e);
|
|
198
|
+
heldToolCallEvents.delete(toolCallId);
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
const subscription = source.subscribe({
|
|
202
|
+
next: (eventWithState) => {
|
|
203
|
+
const event = eventWithState.event;
|
|
204
|
+
if (heldRunFinished) {
|
|
205
|
+
subscriber.next(heldRunFinished.event);
|
|
206
|
+
heldRunFinished = null;
|
|
207
|
+
}
|
|
208
|
+
if (event.type === EventType.RUN_FINISHED) {
|
|
209
|
+
heldRunFinished = eventWithState;
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
if (event.type === EventType.TOOL_CALL_START) {
|
|
213
|
+
const startEvent = event;
|
|
214
|
+
if (startEvent.toolCallName === TOOL_NAME) {
|
|
215
|
+
heldToolCallEvents.set(startEvent.toolCallId, [event]);
|
|
216
|
+
activeParsers.set(startEvent.toolCallId, new ArgsParser(startEvent.toolCallId, (activityEvent) => {
|
|
217
|
+
subscriber.next(activityEvent);
|
|
218
|
+
flushHeldEvents(startEvent.toolCallId);
|
|
219
|
+
}));
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
if (event.type === EventType.TOOL_CALL_ARGS) {
|
|
224
|
+
const argsEvent = event;
|
|
225
|
+
const parser = activeParsers.get(argsEvent.toolCallId);
|
|
226
|
+
if (parser) {
|
|
227
|
+
if (!flushedToolCalls.has(argsEvent.toolCallId)) heldToolCallEvents.get(argsEvent.toolCallId).push(event);
|
|
228
|
+
else subscriber.next(event);
|
|
229
|
+
parser.write(argsEvent.delta);
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
if (event.type === EventType.TOOL_CALL_END) {
|
|
234
|
+
const endEvent = event;
|
|
235
|
+
const parser = activeParsers.get(endEvent.toolCallId);
|
|
236
|
+
if (parser) {
|
|
237
|
+
const completeEvent = {
|
|
238
|
+
type: EventType.ACTIVITY_DELTA,
|
|
239
|
+
messageId: parser.messageId,
|
|
240
|
+
activityType: ACTIVITY_TYPE,
|
|
241
|
+
patch: [{
|
|
242
|
+
op: "add",
|
|
243
|
+
path: "/generating",
|
|
244
|
+
value: false
|
|
245
|
+
}]
|
|
246
|
+
};
|
|
247
|
+
subscriber.next(completeEvent);
|
|
248
|
+
if (!flushedToolCalls.has(endEvent.toolCallId)) heldToolCallEvents.get(endEvent.toolCallId).push(event);
|
|
249
|
+
else subscriber.next(event);
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
subscriber.next(event);
|
|
254
|
+
},
|
|
255
|
+
error: (err) => {
|
|
256
|
+
for (const [, events] of heldToolCallEvents) for (const event of events) subscriber.next(event);
|
|
257
|
+
heldToolCallEvents.clear();
|
|
258
|
+
if (heldRunFinished) {
|
|
259
|
+
subscriber.next(heldRunFinished.event);
|
|
260
|
+
heldRunFinished = null;
|
|
261
|
+
}
|
|
262
|
+
subscriber.error(err);
|
|
263
|
+
},
|
|
264
|
+
complete: () => {
|
|
265
|
+
heldToolCallEvents.forEach((_, toolCallId) => {
|
|
266
|
+
flushHeldEvents(toolCallId);
|
|
267
|
+
});
|
|
268
|
+
if (heldRunFinished) {
|
|
269
|
+
subscriber.next(heldRunFinished.event);
|
|
270
|
+
heldRunFinished = null;
|
|
271
|
+
}
|
|
272
|
+
activeParsers.clear();
|
|
273
|
+
subscriber.complete();
|
|
274
|
+
}
|
|
275
|
+
});
|
|
276
|
+
return () => subscription.unsubscribe();
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
};
|
|
280
|
+
|
|
281
|
+
//#endregion
|
|
282
|
+
export { ArgsParser, OpenGenerativeUIMiddleware };
|
|
283
|
+
//# sourceMappingURL=open-generative-ui-middleware.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"open-generative-ui-middleware.mjs","names":[],"sources":["../../src/event-transforms/open-generative-ui-middleware.ts"],"sourcesContent":["import type {\n RunAgentInput,\n AbstractAgent,\n BaseEvent,\n ToolCallStartEvent,\n ToolCallArgsEvent,\n ActivitySnapshotEventProps,\n ActivityDeltaEvent,\n} from \"@ag-ui/client\";\nimport { Middleware, EventType } from \"@ag-ui/client\";\nimport { Observable } from \"rxjs\";\nimport clarinet from \"clarinet\";\n\nconst TOOL_NAME = \"generateSandboxedUi\";\nconst ACTIVITY_TYPE = \"open-generative-ui\";\n\n/**\n * Parsed parameters from the generateSandboxedUi tool call.\n */\nexport interface GenerateSandboxedUIParams {\n initialHeight?: number;\n placeholderMessages?: string[];\n css?: string;\n html?: string;\n jsFunctions?: string;\n jsExpressions?: string[];\n}\n\n/**\n * Callback invoked by ArgsParser whenever a parameter (or array item) finishes parsing.\n */\nexport type OnParamEvent = (event: BaseEvent) => void;\n\n/**\n * Tracks incremental JSON parsing state for a single tool call's arguments.\n * Emits activity events via the onEvent callback as parameters complete.\n */\nexport class ArgsParser {\n private parser: ReturnType<typeof clarinet.parser> & {\n error?: Error | null;\n textNode?: string;\n };\n private currentKey: string | null = null;\n private depth = 0;\n private currentArrayKey: string | null = null;\n private snapshotEmitted = false;\n\n // Streaming html state — reads parser.textNode to emit incremental chunks\n private streamingHtmlKey = false;\n private htmlEmittedLength = 0;\n private htmlArrayEmitted = false;\n\n public readonly params: GenerateSandboxedUIParams = {};\n public readonly messageId: string;\n private readonly onEvent: OnParamEvent;\n\n constructor(toolCallId: string, onEvent: OnParamEvent) {\n this.messageId = `${toolCallId}-activity`;\n this.onEvent = onEvent;\n this.parser = clarinet.parser();\n\n this.parser.onopenobject = (key: string | undefined) => {\n this.depth++;\n if (key !== undefined && this.depth === 1) {\n this.currentKey = key;\n this.initHtmlStreaming(key);\n }\n };\n\n this.parser.onkey = (key: string) => {\n if (this.depth === 1) {\n this.currentKey = key;\n this.initHtmlStreaming(key);\n }\n };\n\n this.parser.onvalue = (value: string | boolean | number | null) => {\n if (this.depth === 1 && this.currentKey) {\n if (this.currentArrayKey) {\n const strValue = String(value);\n if (this.currentArrayKey === \"jsExpressions\") {\n if (!this.params.jsExpressions) this.params.jsExpressions = [];\n this.params.jsExpressions.push(strValue);\n } else if (this.currentArrayKey === \"placeholderMessages\") {\n if (!this.params.placeholderMessages)\n this.params.placeholderMessages = [];\n this.params.placeholderMessages.push(strValue);\n }\n this.emitArrayItemDelta(this.currentArrayKey, strValue);\n } else if (this.streamingHtmlKey) {\n // HTML string completed — flush any remaining content immediately + htmlComplete\n const fullHtml = value != null ? String(value) : \"\";\n this.params.html = fullHtml || undefined;\n this.emitPendingHtml(fullHtml);\n this.emitParamDelta(\"htmlComplete\", true);\n this.streamingHtmlKey = false;\n } else {\n this.setParam(this.currentKey, value);\n }\n }\n };\n\n this.parser.onopenarray = () => {\n if (this.depth === 1 && this.currentKey) {\n const key = this.currentKey;\n if (key === \"jsExpressions\" || key === \"placeholderMessages\") {\n this.currentArrayKey = key;\n if (key === \"jsExpressions\") this.params.jsExpressions = [];\n else this.params.placeholderMessages = [];\n // Emit a delta to create the array in the activity content.\n // Subsequent \"add\" ops with path \"/<key>/-\" append to this array.\n this.emitParamDelta(key, []);\n }\n }\n };\n\n this.parser.onclosearray = () => {\n if (this.depth === 1) {\n if (this.currentArrayKey === \"jsExpressions\") {\n this.emitParamDelta(\"jsExpressionsComplete\", true);\n }\n this.currentArrayKey = null;\n }\n };\n\n this.parser.oncloseobject = () => {\n this.depth--;\n };\n\n this.parser.onerror = (err: Error) => {\n console.warn(\n \"[OpenGenerativeUI] JSON parse error in streaming args, resuming:\",\n err?.message ?? err,\n );\n // Reset error state so parsing can continue with the next chunk\n this.parser.error = null;\n this.parser.resume();\n };\n }\n\n write(chunk: string): void {\n this.parser.write(chunk);\n this.flushHtmlChunks();\n }\n\n private initHtmlStreaming(key: string): void {\n if (key === \"html\") {\n this.streamingHtmlKey = true;\n this.htmlEmittedLength = 0;\n this.htmlArrayEmitted = false;\n }\n }\n\n /**\n * Read clarinet's internal textNode buffer to emit html chunks incrementally.\n * Called after every write() so partial string content is emitted as it streams in.\n */\n private flushHtmlChunks(): void {\n if (!this.streamingHtmlKey) return;\n const textNode = this.parser.textNode;\n if (typeof textNode !== \"string\") return;\n if (textNode.length === this.htmlEmittedLength) return;\n\n this.emitPendingHtml(textNode);\n }\n\n /**\n * Emit accumulated html content since the last emission.\n * Called by flushHtmlChunks and directly when html completes.\n */\n private emitPendingHtml(textNode: string): void {\n const newContent = textNode.slice(this.htmlEmittedLength);\n if (newContent.length === 0) return;\n\n if (!this.htmlArrayEmitted) {\n this.htmlArrayEmitted = true;\n this.emitParamDelta(\"html\", []);\n }\n this.emitArrayItemDelta(\"html\", newContent);\n this.htmlEmittedLength = textNode.length;\n }\n\n private setParam(key: string, value: string | boolean | number | null): void {\n switch (key) {\n case \"initialHeight\":\n this.params.initialHeight =\n typeof value === \"number\" ? value : undefined;\n if (this.snapshotEmitted) {\n // Snapshot already went out (another param parsed first) — deliver\n // the height as a delta instead.\n this.emitParamDelta(\"initialHeight\", this.params.initialHeight);\n } else {\n this.emitSnapshot();\n }\n break;\n case \"css\":\n this.params.css = value != null ? String(value) : undefined;\n this.emitParamDelta(\"css\", this.params.css);\n this.emitParamDelta(\"cssComplete\", true);\n break;\n case \"jsFunctions\":\n this.params.jsFunctions = value != null ? String(value) : undefined;\n this.emitParamDelta(\"jsFunctions\", this.params.jsFunctions);\n this.emitParamDelta(\"jsFunctionsComplete\", true);\n break;\n }\n }\n\n private emitSnapshot(): void {\n if (this.snapshotEmitted) return;\n this.snapshotEmitted = true;\n\n const event = {\n type: EventType.ACTIVITY_SNAPSHOT,\n messageId: this.messageId,\n activityType: ACTIVITY_TYPE,\n content: { initialHeight: this.params.initialHeight, generating: true },\n } satisfies ActivitySnapshotEventProps;\n this.onEvent(event);\n }\n\n private emitParamDelta(key: string, value: unknown): void {\n // A JSON Patch \"add\" requires a value; emitting one without it (e.g. when\n // the LLM sends a null/empty jsFunctions or css) makes fast-json-patch\n // reject the whole patch client-side with OPERATION_VALUE_REQUIRED and\n // drops it. Skip the delta when there's nothing to add.\n if (value === undefined) return;\n // The activity message must exist before any delta can be applied —\n // the client silently drops ACTIVITY_DELTA events whose messageId has\n // no prior ACTIVITY_SNAPSHOT. The LLM controls the key order of the\n // streamed args, so the snapshot cannot wait for initialHeight.\n this.emitSnapshot();\n const event: ActivityDeltaEvent = {\n type: EventType.ACTIVITY_DELTA,\n messageId: this.messageId,\n activityType: ACTIVITY_TYPE,\n patch: [{ op: \"add\", path: `/${key}`, value }],\n };\n this.onEvent(event);\n }\n\n private emitArrayItemDelta(arrayKey: string, value: string): void {\n this.emitSnapshot();\n const event: ActivityDeltaEvent = {\n type: EventType.ACTIVITY_DELTA,\n messageId: this.messageId,\n activityType: ACTIVITY_TYPE,\n patch: [{ op: \"add\", path: `/${arrayKey}/-`, value }],\n };\n this.onEvent(event);\n }\n}\n\n/**\n * Extract EventWithState type from Middleware.runNextWithState return type\n */\ntype ExtractObservableType<T> = T extends Observable<infer U> ? U : never;\ntype RunNextWithStateReturn = ReturnType<Middleware[\"runNextWithState\"]>;\ntype EventWithState = ExtractObservableType<RunNextWithStateReturn>;\n\nexport class OpenGenerativeUIMiddleware extends Middleware {\n run(input: RunAgentInput, next: AbstractAgent): Observable<BaseEvent> {\n return this.processStream(this.runNextWithState(input, next));\n }\n\n private processStream(\n source: Observable<EventWithState>,\n ): Observable<BaseEvent> {\n return new Observable<BaseEvent>((subscriber) => {\n let heldRunFinished: EventWithState | null = null;\n // Track active generateSandboxedUi tool call IDs → their streaming parser\n const activeParsers = new Map<string, ArgsParser>();\n // Hold genui tool call events until the first activity event is emitted\n const heldToolCallEvents = new Map<string, BaseEvent[]>();\n const flushedToolCalls = new Set<string>();\n\n const flushHeldEvents = (toolCallId: string) => {\n if (flushedToolCalls.has(toolCallId)) return;\n flushedToolCalls.add(toolCallId);\n const held = heldToolCallEvents.get(toolCallId);\n if (held) {\n for (const e of held) {\n subscriber.next(e);\n }\n heldToolCallEvents.delete(toolCallId);\n }\n };\n\n const subscription = source.subscribe({\n next: (eventWithState) => {\n const event = eventWithState.event;\n\n if (heldRunFinished) {\n subscriber.next(heldRunFinished.event);\n heldRunFinished = null;\n }\n\n if (event.type === EventType.RUN_FINISHED) {\n heldRunFinished = eventWithState;\n return;\n }\n\n // Hold TOOL_CALL_START for genui until the first activity event\n if (event.type === EventType.TOOL_CALL_START) {\n const startEvent = event as ToolCallStartEvent;\n if (startEvent.toolCallName === TOOL_NAME) {\n heldToolCallEvents.set(startEvent.toolCallId, [event]);\n activeParsers.set(\n startEvent.toolCallId,\n new ArgsParser(startEvent.toolCallId, (activityEvent) => {\n subscriber.next(activityEvent);\n flushHeldEvents(startEvent.toolCallId);\n }),\n );\n return;\n }\n }\n\n // Hold or emit TOOL_CALL_ARGS for genui tool calls\n if (event.type === EventType.TOOL_CALL_ARGS) {\n const argsEvent = event as ToolCallArgsEvent;\n const parser = activeParsers.get(argsEvent.toolCallId);\n if (parser) {\n if (!flushedToolCalls.has(argsEvent.toolCallId)) {\n heldToolCallEvents.get(argsEvent.toolCallId)!.push(event);\n } else {\n subscriber.next(event);\n }\n parser.write(argsEvent.delta);\n return;\n }\n }\n\n // Hold or emit TOOL_CALL_END for genui tool calls\n if (event.type === EventType.TOOL_CALL_END) {\n const endEvent = event as { toolCallId: string } & BaseEvent;\n const parser = activeParsers.get(endEvent.toolCallId);\n if (parser) {\n // Mark generation complete\n const completeEvent: ActivityDeltaEvent = {\n type: EventType.ACTIVITY_DELTA,\n messageId: parser.messageId,\n activityType: ACTIVITY_TYPE,\n patch: [{ op: \"add\", path: \"/generating\", value: false }],\n };\n subscriber.next(completeEvent);\n\n if (!flushedToolCalls.has(endEvent.toolCallId)) {\n heldToolCallEvents.get(endEvent.toolCallId)!.push(event);\n } else {\n subscriber.next(event);\n }\n return;\n }\n }\n\n subscriber.next(event);\n },\n error: (err) => {\n // Flush any held tool call events so downstream sees them before the error\n for (const [, events] of heldToolCallEvents) {\n for (const event of events) {\n subscriber.next(event);\n }\n }\n heldToolCallEvents.clear();\n\n if (heldRunFinished) {\n subscriber.next(heldRunFinished.event);\n heldRunFinished = null;\n }\n subscriber.error(err);\n },\n complete: () => {\n // Flush any remaining held tool call events (e.g. parser never emitted)\n heldToolCallEvents.forEach((_, toolCallId) => {\n flushHeldEvents(toolCallId);\n });\n\n if (heldRunFinished) {\n subscriber.next(heldRunFinished.event);\n heldRunFinished = null;\n }\n activeParsers.clear();\n subscriber.complete();\n },\n });\n\n return () => subscription.unsubscribe();\n });\n }\n}\n"],"mappings":";;;;;AAaA,MAAM,YAAY;AAClB,MAAM,gBAAgB;;;;;AAuBtB,IAAa,aAAb,MAAwB;CAmBtB,YAAY,YAAoB,SAAuB;oBAdnB;eACpB;yBACyB;yBACf;0BAGC;2BACC;0BACD;gBAEyB,EAAE;AAKpD,OAAK,YAAY,GAAG,WAAW;AAC/B,OAAK,UAAU;AACf,OAAK,SAAS,SAAS,QAAQ;AAE/B,OAAK,OAAO,gBAAgB,QAA4B;AACtD,QAAK;AACL,OAAI,QAAQ,UAAa,KAAK,UAAU,GAAG;AACzC,SAAK,aAAa;AAClB,SAAK,kBAAkB,IAAI;;;AAI/B,OAAK,OAAO,SAAS,QAAgB;AACnC,OAAI,KAAK,UAAU,GAAG;AACpB,SAAK,aAAa;AAClB,SAAK,kBAAkB,IAAI;;;AAI/B,OAAK,OAAO,WAAW,UAA4C;AACjE,OAAI,KAAK,UAAU,KAAK,KAAK,WAC3B,KAAI,KAAK,iBAAiB;IACxB,MA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AAM,IAAI;;IAEvB,gBAAgB;AAEd,wBAAmB,SAAS,GAAG,eAAe;AAC5C,sBAAgB,WAAW;OAC3B;AAEF,SAAI,iBAAiB;AACnB,iBAAW,KAAK,gBAAgB,MAAM;AACtC,wBAAkB;;AAEpB,mBAAc,OAAO;AACrB,gBAAW,UAAU;;IAExB,CAAC;AAEF,gBAAa,aAAa,aAAa;IACvC"}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
|
|
2
|
+
const require_open_generative_ui_middleware = require('./open-generative-ui-middleware.cjs');
|
|
3
|
+
let _ag_ui_client = require("@ag-ui/client");
|
|
4
|
+
let _ag_ui_a2ui_middleware = require("@ag-ui/a2ui-middleware");
|
|
5
|
+
let rxjs = require("rxjs");
|
|
6
|
+
|
|
7
|
+
//#region src/event-transforms/recorded-events.ts
|
|
8
|
+
/** An inert event source: it cannot contact an agent or execute tools. */
|
|
9
|
+
var RecordedEventAgent = class RecordedEventAgent extends _ag_ui_client.AbstractAgent {
|
|
10
|
+
constructor(input, stream) {
|
|
11
|
+
super({
|
|
12
|
+
threadId: input.threadId,
|
|
13
|
+
initialMessages: input.messages,
|
|
14
|
+
initialState: input.state
|
|
15
|
+
});
|
|
16
|
+
this.input = input;
|
|
17
|
+
this.stream = stream;
|
|
18
|
+
}
|
|
19
|
+
/** Emit recorded events through this layer without contacting an agent. */
|
|
20
|
+
run(input) {
|
|
21
|
+
return this.stream(input);
|
|
22
|
+
}
|
|
23
|
+
/** Retain the current replay history and state in an independent agent. */
|
|
24
|
+
clone() {
|
|
25
|
+
return new RecordedEventAgent({
|
|
26
|
+
...this.input,
|
|
27
|
+
messages: this.messages,
|
|
28
|
+
state: this.state
|
|
29
|
+
}, this.stream);
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* Apply CPK's rich-UI middleware to one recorded, pre-middleware run.
|
|
34
|
+
* Supply complete AG-UI run events and the original input/configuration. This
|
|
35
|
+
* does not run an agent, fetch resources, or execute tools. Already transformed
|
|
36
|
+
* histories must not be passed through a second time.
|
|
37
|
+
*
|
|
38
|
+
* Returns events in runtime order, including generated activity events and any
|
|
39
|
+
* synthetic A2UI tool results. Persistence IDs, timestamps, and provenance are
|
|
40
|
+
* the caller's responsibility (A2UI can generate random result message IDs).
|
|
41
|
+
*/
|
|
42
|
+
async function transformRecordedEvents(input, events, options) {
|
|
43
|
+
let agent = new RecordedEventAgent(input, () => (0, rxjs.from)(events));
|
|
44
|
+
if (options.openGenerativeUI) {
|
|
45
|
+
const next = agent;
|
|
46
|
+
const middleware = new require_open_generative_ui_middleware.OpenGenerativeUIMiddleware();
|
|
47
|
+
agent = new RecordedEventAgent(input, (runInput) => middleware.run(runInput, next));
|
|
48
|
+
}
|
|
49
|
+
if (options.a2ui) {
|
|
50
|
+
const next = agent;
|
|
51
|
+
const middleware = new _ag_ui_a2ui_middleware.A2UIMiddleware(options.a2ui);
|
|
52
|
+
agent = new RecordedEventAgent(input, (runInput) => middleware.run(runInput, next));
|
|
53
|
+
}
|
|
54
|
+
return (0, rxjs.firstValueFrom)(agent.run(input).pipe((0, rxjs.toArray)()));
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
//#endregion
|
|
58
|
+
exports.transformRecordedEvents = transformRecordedEvents;
|
|
59
|
+
//# sourceMappingURL=recorded-events.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"recorded-events.cjs","names":["AbstractAgent","OpenGenerativeUIMiddleware","A2UIMiddleware"],"sources":["../../src/event-transforms/recorded-events.ts"],"sourcesContent":["import { AbstractAgent } from \"@ag-ui/client\";\nimport type { BaseEvent, RunAgentInput } from \"@ag-ui/client\";\nimport { A2UIMiddleware } from \"@ag-ui/a2ui-middleware\";\nimport type { A2UIMiddlewareConfig } from \"@ag-ui/a2ui-middleware\";\nimport { firstValueFrom, from, toArray } from \"rxjs\";\nimport type { Observable } from \"rxjs\";\nimport { OpenGenerativeUIMiddleware } from \"./open-generative-ui-middleware\";\n\nexport interface RecordedEventTransformOptions {\n /** Use the original runtime configuration, including its catalog when known. */\n a2ui?: A2UIMiddlewareConfig;\n openGenerativeUI?: boolean;\n}\n\n/** An inert event source: it cannot contact an agent or execute tools. */\nclass RecordedEventAgent extends AbstractAgent {\n constructor(\n private readonly input: RunAgentInput,\n private readonly stream: (input: RunAgentInput) => Observable<BaseEvent>,\n ) {\n super({\n threadId: input.threadId,\n initialMessages: input.messages,\n initialState: input.state,\n });\n }\n\n /** Emit recorded events through this layer without contacting an agent. */\n run(input: RunAgentInput): Observable<BaseEvent> {\n return this.stream(input);\n }\n\n /** Retain the current replay history and state in an independent agent. */\n clone(): AbstractAgent {\n return new RecordedEventAgent(\n { ...this.input, messages: this.messages, state: this.state },\n this.stream,\n );\n }\n}\n\n/**\n * Apply CPK's rich-UI middleware to one recorded, pre-middleware run.\n * Supply complete AG-UI run events and the original input/configuration. This\n * does not run an agent, fetch resources, or execute tools. Already transformed\n * histories must not be passed through a second time.\n *\n * Returns events in runtime order, including generated activity events and any\n * synthetic A2UI tool results. Persistence IDs, timestamps, and provenance are\n * the caller's responsibility (A2UI can generate random result message IDs).\n */\nexport async function transformRecordedEvents(\n input: RunAgentInput,\n events: readonly BaseEvent[],\n options: RecordedEventTransformOptions,\n): Promise<BaseEvent[]> {\n let agent: AbstractAgent = new RecordedEventAgent(input, () => from(events));\n // Runtime registers A2UI before Open GenUI; the first middleware is outermost.\n if (options.openGenerativeUI) {\n const next = agent;\n const middleware = new OpenGenerativeUIMiddleware();\n agent = new RecordedEventAgent(input, (runInput) =>\n middleware.run(runInput, next),\n );\n }\n if (options.a2ui) {\n const next = agent;\n const middleware = new A2UIMiddleware(options.a2ui);\n agent = new RecordedEventAgent(input, (runInput) =>\n middleware.run(runInput, next),\n );\n }\n return firstValueFrom(agent.run(input).pipe(toArray()));\n}\n"],"mappings":";;;;;;;;AAeA,IAAM,qBAAN,MAAM,2BAA2BA,4BAAc;CAC7C,YACE,AAAiB,OACjB,AAAiB,QACjB;AACA,QAAM;GACJ,UAAU,MAAM;GAChB,iBAAiB,MAAM;GACvB,cAAc,MAAM;GACrB,CAAC;EAPe;EACA;;;CAUnB,IAAI,OAA6C;AAC/C,SAAO,KAAK,OAAO,MAAM;;;CAI3B,QAAuB;AACrB,SAAO,IAAI,mBACT;GAAE,GAAG,KAAK;GAAO,UAAU,KAAK;GAAU,OAAO,KAAK;GAAO,EAC7D,KAAK,OACN;;;;;;;;;;;;;AAcL,eAAsB,wBACpB,OACA,QACA,SACsB;CACtB,IAAI,QAAuB,IAAI,mBAAmB,4BAAkB,OAAO,CAAC;AAE5E,KAAI,QAAQ,kBAAkB;EAC5B,MAAM,OAAO;EACb,MAAM,aAAa,IAAIC,kEAA4B;AACnD,UAAQ,IAAI,mBAAmB,QAAQ,aACrC,WAAW,IAAI,UAAU,KAAK,CAC/B;;AAEH,KAAI,QAAQ,MAAM;EAChB,MAAM,OAAO;EACb,MAAM,aAAa,IAAIC,sCAAe,QAAQ,KAAK;AACnD,UAAQ,IAAI,mBAAmB,QAAQ,aACrC,WAAW,IAAI,UAAU,KAAK,CAC/B;;AAEH,iCAAsB,MAAM,IAAI,MAAM,CAAC,wBAAc,CAAC,CAAC"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { A2UIMiddlewareConfig } from "@ag-ui/a2ui-middleware";
|
|
2
|
+
import { BaseEvent, RunAgentInput } from "@ag-ui/client";
|
|
3
|
+
|
|
4
|
+
//#region src/event-transforms/recorded-events.d.ts
|
|
5
|
+
interface RecordedEventTransformOptions {
|
|
6
|
+
/** Use the original runtime configuration, including its catalog when known. */
|
|
7
|
+
a2ui?: A2UIMiddlewareConfig;
|
|
8
|
+
openGenerativeUI?: boolean;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Apply CPK's rich-UI middleware to one recorded, pre-middleware run.
|
|
12
|
+
* Supply complete AG-UI run events and the original input/configuration. This
|
|
13
|
+
* does not run an agent, fetch resources, or execute tools. Already transformed
|
|
14
|
+
* histories must not be passed through a second time.
|
|
15
|
+
*
|
|
16
|
+
* Returns events in runtime order, including generated activity events and any
|
|
17
|
+
* synthetic A2UI tool results. Persistence IDs, timestamps, and provenance are
|
|
18
|
+
* the caller's responsibility (A2UI can generate random result message IDs).
|
|
19
|
+
*/
|
|
20
|
+
declare function transformRecordedEvents(input: RunAgentInput, events: readonly BaseEvent[], options: RecordedEventTransformOptions): Promise<BaseEvent[]>;
|
|
21
|
+
//#endregion
|
|
22
|
+
export { RecordedEventTransformOptions, transformRecordedEvents };
|
|
23
|
+
//# sourceMappingURL=recorded-events.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"recorded-events.d.cts","names":[],"sources":["../../src/event-transforms/recorded-events.ts"],"mappings":";;;;UAQiB,6BAAA;;EAEf,IAAA,GAAO,oBAAA;EACP,gBAAA;AAAA;;;;;;;AAwCF;;;;iBAAsB,uBAAA,CACpB,KAAA,EAAO,aAAA,EACP,MAAA,WAAiB,SAAA,IACjB,OAAA,EAAS,6BAAA,GACR,OAAA,CAAQ,SAAA"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { BaseEvent, RunAgentInput } from "@ag-ui/client";
|
|
2
|
+
import { A2UIMiddlewareConfig } from "@ag-ui/a2ui-middleware";
|
|
3
|
+
|
|
4
|
+
//#region src/event-transforms/recorded-events.d.ts
|
|
5
|
+
interface RecordedEventTransformOptions {
|
|
6
|
+
/** Use the original runtime configuration, including its catalog when known. */
|
|
7
|
+
a2ui?: A2UIMiddlewareConfig;
|
|
8
|
+
openGenerativeUI?: boolean;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Apply CPK's rich-UI middleware to one recorded, pre-middleware run.
|
|
12
|
+
* Supply complete AG-UI run events and the original input/configuration. This
|
|
13
|
+
* does not run an agent, fetch resources, or execute tools. Already transformed
|
|
14
|
+
* histories must not be passed through a second time.
|
|
15
|
+
*
|
|
16
|
+
* Returns events in runtime order, including generated activity events and any
|
|
17
|
+
* synthetic A2UI tool results. Persistence IDs, timestamps, and provenance are
|
|
18
|
+
* the caller's responsibility (A2UI can generate random result message IDs).
|
|
19
|
+
*/
|
|
20
|
+
declare function transformRecordedEvents(input: RunAgentInput, events: readonly BaseEvent[], options: RecordedEventTransformOptions): Promise<BaseEvent[]>;
|
|
21
|
+
//#endregion
|
|
22
|
+
export { RecordedEventTransformOptions, transformRecordedEvents };
|
|
23
|
+
//# sourceMappingURL=recorded-events.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"recorded-events.d.mts","names":[],"sources":["../../src/event-transforms/recorded-events.ts"],"mappings":";;;;UAQiB,6BAAA;;EAEf,IAAA,GAAO,oBAAA;EACP,gBAAA;AAAA;;;;;;;AAwCF;;;;iBAAsB,uBAAA,CACpB,KAAA,EAAO,aAAA,EACP,MAAA,WAAiB,SAAA,IACjB,OAAA,EAAS,6BAAA,GACR,OAAA,CAAQ,SAAA"}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { OpenGenerativeUIMiddleware } from "./open-generative-ui-middleware.mjs";
|
|
2
|
+
import { AbstractAgent } from "@ag-ui/client";
|
|
3
|
+
import { A2UIMiddleware } from "@ag-ui/a2ui-middleware";
|
|
4
|
+
import { firstValueFrom, from, toArray } from "rxjs";
|
|
5
|
+
|
|
6
|
+
//#region src/event-transforms/recorded-events.ts
|
|
7
|
+
/** An inert event source: it cannot contact an agent or execute tools. */
|
|
8
|
+
var RecordedEventAgent = class RecordedEventAgent extends AbstractAgent {
|
|
9
|
+
constructor(input, stream) {
|
|
10
|
+
super({
|
|
11
|
+
threadId: input.threadId,
|
|
12
|
+
initialMessages: input.messages,
|
|
13
|
+
initialState: input.state
|
|
14
|
+
});
|
|
15
|
+
this.input = input;
|
|
16
|
+
this.stream = stream;
|
|
17
|
+
}
|
|
18
|
+
/** Emit recorded events through this layer without contacting an agent. */
|
|
19
|
+
run(input) {
|
|
20
|
+
return this.stream(input);
|
|
21
|
+
}
|
|
22
|
+
/** Retain the current replay history and state in an independent agent. */
|
|
23
|
+
clone() {
|
|
24
|
+
return new RecordedEventAgent({
|
|
25
|
+
...this.input,
|
|
26
|
+
messages: this.messages,
|
|
27
|
+
state: this.state
|
|
28
|
+
}, this.stream);
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
/**
|
|
32
|
+
* Apply CPK's rich-UI middleware to one recorded, pre-middleware run.
|
|
33
|
+
* Supply complete AG-UI run events and the original input/configuration. This
|
|
34
|
+
* does not run an agent, fetch resources, or execute tools. Already transformed
|
|
35
|
+
* histories must not be passed through a second time.
|
|
36
|
+
*
|
|
37
|
+
* Returns events in runtime order, including generated activity events and any
|
|
38
|
+
* synthetic A2UI tool results. Persistence IDs, timestamps, and provenance are
|
|
39
|
+
* the caller's responsibility (A2UI can generate random result message IDs).
|
|
40
|
+
*/
|
|
41
|
+
async function transformRecordedEvents(input, events, options) {
|
|
42
|
+
let agent = new RecordedEventAgent(input, () => from(events));
|
|
43
|
+
if (options.openGenerativeUI) {
|
|
44
|
+
const next = agent;
|
|
45
|
+
const middleware = new OpenGenerativeUIMiddleware();
|
|
46
|
+
agent = new RecordedEventAgent(input, (runInput) => middleware.run(runInput, next));
|
|
47
|
+
}
|
|
48
|
+
if (options.a2ui) {
|
|
49
|
+
const next = agent;
|
|
50
|
+
const middleware = new A2UIMiddleware(options.a2ui);
|
|
51
|
+
agent = new RecordedEventAgent(input, (runInput) => middleware.run(runInput, next));
|
|
52
|
+
}
|
|
53
|
+
return firstValueFrom(agent.run(input).pipe(toArray()));
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
//#endregion
|
|
57
|
+
export { transformRecordedEvents };
|
|
58
|
+
//# sourceMappingURL=recorded-events.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"recorded-events.mjs","names":[],"sources":["../../src/event-transforms/recorded-events.ts"],"sourcesContent":["import { AbstractAgent } from \"@ag-ui/client\";\nimport type { BaseEvent, RunAgentInput } from \"@ag-ui/client\";\nimport { A2UIMiddleware } from \"@ag-ui/a2ui-middleware\";\nimport type { A2UIMiddlewareConfig } from \"@ag-ui/a2ui-middleware\";\nimport { firstValueFrom, from, toArray } from \"rxjs\";\nimport type { Observable } from \"rxjs\";\nimport { OpenGenerativeUIMiddleware } from \"./open-generative-ui-middleware\";\n\nexport interface RecordedEventTransformOptions {\n /** Use the original runtime configuration, including its catalog when known. */\n a2ui?: A2UIMiddlewareConfig;\n openGenerativeUI?: boolean;\n}\n\n/** An inert event source: it cannot contact an agent or execute tools. */\nclass RecordedEventAgent extends AbstractAgent {\n constructor(\n private readonly input: RunAgentInput,\n private readonly stream: (input: RunAgentInput) => Observable<BaseEvent>,\n ) {\n super({\n threadId: input.threadId,\n initialMessages: input.messages,\n initialState: input.state,\n });\n }\n\n /** Emit recorded events through this layer without contacting an agent. */\n run(input: RunAgentInput): Observable<BaseEvent> {\n return this.stream(input);\n }\n\n /** Retain the current replay history and state in an independent agent. */\n clone(): AbstractAgent {\n return new RecordedEventAgent(\n { ...this.input, messages: this.messages, state: this.state },\n this.stream,\n );\n }\n}\n\n/**\n * Apply CPK's rich-UI middleware to one recorded, pre-middleware run.\n * Supply complete AG-UI run events and the original input/configuration. This\n * does not run an agent, fetch resources, or execute tools. Already transformed\n * histories must not be passed through a second time.\n *\n * Returns events in runtime order, including generated activity events and any\n * synthetic A2UI tool results. Persistence IDs, timestamps, and provenance are\n * the caller's responsibility (A2UI can generate random result message IDs).\n */\nexport async function transformRecordedEvents(\n input: RunAgentInput,\n events: readonly BaseEvent[],\n options: RecordedEventTransformOptions,\n): Promise<BaseEvent[]> {\n let agent: AbstractAgent = new RecordedEventAgent(input, () => from(events));\n // Runtime registers A2UI before Open GenUI; the first middleware is outermost.\n if (options.openGenerativeUI) {\n const next = agent;\n const middleware = new OpenGenerativeUIMiddleware();\n agent = new RecordedEventAgent(input, (runInput) =>\n middleware.run(runInput, next),\n );\n }\n if (options.a2ui) {\n const next = agent;\n const middleware = new A2UIMiddleware(options.a2ui);\n agent = new RecordedEventAgent(input, (runInput) =>\n middleware.run(runInput, next),\n );\n }\n return firstValueFrom(agent.run(input).pipe(toArray()));\n}\n"],"mappings":";;;;;;;AAeA,IAAM,qBAAN,MAAM,2BAA2B,cAAc;CAC7C,YACE,AAAiB,OACjB,AAAiB,QACjB;AACA,QAAM;GACJ,UAAU,MAAM;GAChB,iBAAiB,MAAM;GACvB,cAAc,MAAM;GACrB,CAAC;EAPe;EACA;;;CAUnB,IAAI,OAA6C;AAC/C,SAAO,KAAK,OAAO,MAAM;;;CAI3B,QAAuB;AACrB,SAAO,IAAI,mBACT;GAAE,GAAG,KAAK;GAAO,UAAU,KAAK;GAAU,OAAO,KAAK;GAAO,EAC7D,KAAK,OACN;;;;;;;;;;;;;AAcL,eAAsB,wBACpB,OACA,QACA,SACsB;CACtB,IAAI,QAAuB,IAAI,mBAAmB,aAAa,KAAK,OAAO,CAAC;AAE5E,KAAI,QAAQ,kBAAkB;EAC5B,MAAM,OAAO;EACb,MAAM,aAAa,IAAI,4BAA4B;AACnD,UAAQ,IAAI,mBAAmB,QAAQ,aACrC,WAAW,IAAI,UAAU,KAAK,CAC/B;;AAEH,KAAI,QAAQ,MAAM;EAChB,MAAM,OAAO;EACb,MAAM,aAAa,IAAI,eAAe,QAAQ,KAAK;AACnD,UAAQ,IAAI,mBAAmB,QAAQ,aACrC,WAAW,IAAI,UAAU,KAAK,CAC/B;;AAEH,QAAO,eAAe,MAAM,IAAI,MAAM,CAAC,KAAK,SAAS,CAAC,CAAC"}
|
package/dist/index.cjs
CHANGED
|
@@ -10,6 +10,7 @@ const require_inspector_visibility = require('./utils/inspector-visibility.cjs')
|
|
|
10
10
|
const require_types = require('./utils/types.cjs');
|
|
11
11
|
const require_random_id = require('./utils/random-id.cjs');
|
|
12
12
|
const require_requests = require('./utils/requests.cjs');
|
|
13
|
+
const require_row_render_keys = require('./utils/row-render-keys.cjs');
|
|
13
14
|
const require_index = require('./utils/index.cjs');
|
|
14
15
|
const require_index$1 = require('./constants/index.cjs');
|
|
15
16
|
const require_telemetry_disabled = require('./telemetry/telemetry-disabled.cjs');
|
|
@@ -18,6 +19,7 @@ const require_model_host = require('./telemetry/model-host.cjs');
|
|
|
18
19
|
const require_lambda_client = require('./telemetry/lambda-client.cjs');
|
|
19
20
|
const require_debug = require('./debug.cjs');
|
|
20
21
|
const require_standard_schema = require('./standard-schema.cjs');
|
|
22
|
+
const require_content = require('./attachments/content.cjs');
|
|
21
23
|
const require_utils = require('./attachments/utils.cjs');
|
|
22
24
|
const require_logger = require('./logger.cjs');
|
|
23
25
|
const require_finalize_events = require('./finalize-events.cjs');
|
|
@@ -106,10 +108,13 @@ exports.UNSAMPLED_RATE = require_sampling.UNSAMPLED_RATE;
|
|
|
106
108
|
exports.UpgradeRequiredError = require_errors.UpgradeRequiredError;
|
|
107
109
|
exports.actionParametersToJsonSchema = require_json_schema.actionParametersToJsonSchema;
|
|
108
110
|
exports.classifyModelHost = require_model_host.classifyModelHost;
|
|
111
|
+
exports.commitRowKeyStore = require_row_render_keys.commitRowKeyStore;
|
|
109
112
|
exports.computeSamplingMeta = require_sampling.computeSamplingMeta;
|
|
110
113
|
exports.convertJsonSchemaToZodSchema = require_json_schema.convertJsonSchemaToZodSchema;
|
|
111
114
|
exports.copyToClipboard = require_clipboard.copyToClipboard;
|
|
115
|
+
exports.createAttachmentContent = require_content.createAttachmentContent;
|
|
112
116
|
exports.createLicenseContextValue = createLicenseContextValue;
|
|
117
|
+
exports.createRowKeyStore = require_row_render_keys.createRowKeyStore;
|
|
113
118
|
exports.createRunEventFinalizer = require_finalize_events.createRunEventFinalizer;
|
|
114
119
|
exports.dataToUUID = require_random_id.dataToUUID;
|
|
115
120
|
exports.ensureStructuredError = require_errors.ensureStructuredError;
|
|
@@ -143,12 +148,15 @@ exports.parseJson = require_index.parseJson;
|
|
|
143
148
|
exports.parseTelemetryIdFromLicense = require_lambda_client.parseTelemetryIdFromLicense;
|
|
144
149
|
exports.partialJSONParse = require_index.partialJSONParse;
|
|
145
150
|
exports.phoenixExponentialBackoff = require_index.phoenixExponentialBackoff;
|
|
151
|
+
exports.pruneRowKeyStore = require_row_render_keys.pruneRowKeyStore;
|
|
146
152
|
exports.publicApiKeyRequired = require_console_styling.publicApiKeyRequired;
|
|
147
153
|
exports.randomId = require_random_id.randomId;
|
|
148
154
|
exports.randomUUID = require_random_id.randomUUID;
|
|
149
155
|
exports.readBody = require_requests.readBody;
|
|
150
156
|
exports.readFileAsBase64 = require_utils.readFileAsBase64;
|
|
151
157
|
exports.resolveDebugConfig = require_debug.resolveDebugConfig;
|
|
158
|
+
exports.resolveRowRenderKeys = require_row_render_keys.resolveRowRenderKeys;
|
|
159
|
+
exports.resolveRowRenderKeysById = require_row_render_keys.resolveRowRenderKeysById;
|
|
152
160
|
exports.safeParseToolArgs = require_index.safeParseToolArgs;
|
|
153
161
|
exports.schemaToJsonSchema = require_standard_schema.schemaToJsonSchema;
|
|
154
162
|
exports.shouldEnableInspector = require_inspector_visibility.shouldEnableInspector;
|
package/dist/index.cjs.map
CHANGED
|
@@ -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 {\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":"
|
|
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"}
|