@redocly/replay 0.27.0-next.4 → 0.27.0-next.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/dist/replay-AiChatProvider-BGXsZqW2.js +6 -0
  2. package/dist/replay-AiChatProvider-CVvR1kSd.js +1004 -0
  3. package/dist/replay-AiChatSqliteDBStorage-BFHRKFlk.js +88 -0
  4. package/dist/replay-AiChatSqliteDBStorage-DVJ9f2EK.js +1 -0
  5. package/dist/replay-AiPanel-CynVcVmm.js +2873 -0
  6. package/dist/replay-AiPanel-qVp_s4gD.js +849 -0
  7. package/dist/replay-HistorySqliteDBStorage-BrILW8Fu.js +1 -0
  8. package/dist/replay-HistorySqliteDBStorage-CtF6-vY8.js +113 -0
  9. package/dist/replay-SqliteDBStorage-CSz7NYH4.js +2857 -0
  10. package/dist/replay-SqliteDBStorage-eRBPh4E8.js +14 -0
  11. package/dist/replay-StepContextSqliteDBStorage-BSepLyBI.js +1 -0
  12. package/dist/replay-StepContextSqliteDBStorage-BfAAKDwA.js +83 -0
  13. package/dist/replay-agent-loop-C60p47KY.js +1 -0
  14. package/dist/replay-agent-loop-CEZz1kj-.js +1533 -0
  15. package/dist/replay-ai-chat-mappers-BAHU6JIc.js +99 -0
  16. package/dist/replay-ai-chat-mappers-Dqg-QVZy.js +1 -0
  17. package/dist/replay-ai-message-parts.schema-BBdjwldJ.js +1 -0
  18. package/dist/replay-ai-message-parts.schema-E9u9-nqr.js +60 -0
  19. package/dist/replay-create-model-C2NQtDcL.js +38224 -0
  20. package/dist/replay-create-model-CUL-l-eX.js +104 -0
  21. package/dist/replay-db-C4jAfGtc.js +64 -0
  22. package/dist/replay-db-Dw-X2WGx.js +306 -0
  23. package/dist/replay-defaults-CzR6jw9a.js +32 -0
  24. package/dist/replay-defaults-DVvOnvnR.js +27 -0
  25. package/dist/replay-external-resolver-DAkLV0nr.js +34 -0
  26. package/dist/replay-external-resolver-DN_PWq_2.js +2 -0
  27. package/dist/replay-history.schema-5ce6X0R1.js +28 -0
  28. package/dist/replay-history.schema-miM3Etuf.js +1 -0
  29. package/dist/replay-index-BmX1FPBL.js +6877 -0
  30. package/dist/replay-index-DR1uVBvc.js +503 -0
  31. package/dist/replay-index-DSKZHOXq.js +1 -0
  32. package/dist/{replay-index-DuAFN7X8.js → replay-index-DT5gdiBA.js} +1 -1
  33. package/dist/replay-index-O_Pq5an3.js +92924 -0
  34. package/dist/{replay-index-D6LeDb4M.js → replay-index-m00jnWFr.js} +6 -6
  35. package/dist/replay-index-qZlgEmbq.js +1 -0
  36. package/dist/replay-index-rRWvC2pp.js +1 -0
  37. package/dist/replay-indexes-CfsvVMi_.js +1242 -0
  38. package/dist/replay-indexes-Dqjl8m6C.js +1 -0
  39. package/dist/replay-lint-CcVVykW7.js +33217 -0
  40. package/dist/replay-lint-ON47l7Vu.js +184 -0
  41. package/dist/{replay-lint-graphql-8tMA-ttz.js → replay-lint-graphql-5cGt2KR_.js} +5 -5
  42. package/dist/{replay-lint-graphql-Cdmm_aJs.js → replay-lint-graphql-DlD7bblx.js} +2 -2
  43. package/dist/replay-resolve-BTzo-fSv.js +47 -0
  44. package/dist/replay-resolve-Ca3DUbGq.js +3683 -0
  45. package/dist/{replay-respect-run-DGe96SG3.js → replay-respect-run-BtC2agF9.js} +54 -54
  46. package/dist/{replay-respect-run-DrWWHTWp.js → replay-respect-run-eSRzH2dk.js} +447 -447
  47. package/dist/replay-step-context.schema-BuuXkAck.js +1 -0
  48. package/dist/replay-step-context.schema-DBk4jufr.js +21 -0
  49. package/dist/{replay-tauri-path-BQmCYwRI.js → replay-tauri-path-C-oxFOHe.js} +4 -4
  50. package/dist/{replay-tauri-path-BIIo3xjJ.js → replay-tauri-path-CKcvIl_h.js} +1 -1
  51. package/dist/replay-useAiChatQueries-CVTxcu2Z.js +192 -0
  52. package/dist/replay-useAiChatQueries-vdKvbmp2.js +3413 -0
  53. package/dist/replay-validate-key-CwIopif3.js +28 -0
  54. package/dist/replay-validate-key-VkgZoK1f.js +1 -0
  55. package/dist/replay.cjs +1 -1
  56. package/dist/replay.d.ts +2 -0
  57. package/dist/replay.js +21 -21
  58. package/package.json +2 -2
  59. package/dist/replay-index-BFggGnsX.js +0 -181252
  60. package/dist/replay-index-BWX4r5us.js +0 -8354
  61. package/dist/replay-index-DCclzbQl.js +0 -1
  62. package/dist/replay-index-tDvNtfHp.js +0 -1
@@ -0,0 +1,1533 @@
1
+ import { a as O, p as w, T as L, i as J, c as D, s as $ } from "./replay-create-model-C2NQtDcL.js";
2
+ import { t as g, p as _, S, w as M, x as z, y as I, D as W, z as K } from "./replay-index-O_Pq5an3.js";
3
+ import { g as U } from "./replay-db-Dw-X2WGx.js";
4
+ import { L as G, C as B } from "./replay-defaults-CzR6jw9a.js";
5
+ function y(t) {
6
+ const e = t.toLowerCase(), n = [
7
+ ["google.vertex", "gcp.vertex_ai"],
8
+ ["google.generative-ai", "gcp.gemini"],
9
+ ["google-vertex", "gcp.vertex_ai"],
10
+ ["amazon-bedrock", "aws.bedrock"],
11
+ ["azure-openai", "azure.ai.openai"],
12
+ ["anthropic", "anthropic"],
13
+ ["openai", "openai"],
14
+ ["azure", "azure.ai.inference"],
15
+ ["google", "gcp.gemini"],
16
+ ["mistral", "mistral_ai"],
17
+ ["cohere", "cohere"],
18
+ ["bedrock", "aws.bedrock"],
19
+ ["groq", "groq"],
20
+ ["deepseek", "deepseek"],
21
+ ["perplexity", "perplexity"],
22
+ ["xai", "x_ai"]
23
+ ];
24
+ for (const [o, s] of n)
25
+ if (e === o || e.startsWith(o + ".") || e.startsWith(o + "-"))
26
+ return s;
27
+ return t;
28
+ }
29
+ function N(t) {
30
+ var e;
31
+ return (e = {
32
+ "ai.generateText": "invoke_agent",
33
+ "ai.streamText": "invoke_agent",
34
+ "ai.generateObject": "invoke_agent",
35
+ "ai.streamObject": "invoke_agent",
36
+ "ai.embed": "embeddings",
37
+ "ai.embedMany": "embeddings",
38
+ "ai.rerank": "rerank"
39
+ }[t]) != null ? e : t;
40
+ }
41
+ function E(t) {
42
+ return typeof t == "string" ? [{ type: "text", content: t }] : Array.isArray(t) ? t.map((e) => ({ type: "text", content: e.content })) : [{ type: "text", content: t.content }];
43
+ }
44
+ function F(t) {
45
+ var e, n, o, s, a;
46
+ switch (t.type) {
47
+ case "text":
48
+ return { type: "text", content: t.text };
49
+ case "reasoning":
50
+ return { type: "reasoning", content: t.text };
51
+ case "tool-call":
52
+ return {
53
+ type: "tool_call",
54
+ id: (e = t.toolCallId) != null ? e : null,
55
+ name: t.toolName,
56
+ arguments: t.input
57
+ };
58
+ case "tool-result": {
59
+ const r = t.output;
60
+ let i;
61
+ return r && (r.type === "text" || r.type === "error-text" || r.type === "json" || r.type === "error-json" ? i = r.value : r.type === "execution-denied" ? i = { denied: !0, reason: r.reason } : i = r), {
62
+ type: "tool_call_response",
63
+ id: (n = t.toolCallId) != null ? n : null,
64
+ response: i
65
+ };
66
+ }
67
+ case "file": {
68
+ const r = t.data, i = (() => {
69
+ if (typeof r == "object" && r !== null && !(r instanceof URL) && !(r instanceof Uint8Array) && !(r instanceof ArrayBuffer) && "type" in r)
70
+ switch (r.type) {
71
+ case "data":
72
+ return r.data;
73
+ case "url":
74
+ return r.url;
75
+ case "text":
76
+ return r.text;
77
+ default:
78
+ return "";
79
+ }
80
+ return r;
81
+ })();
82
+ let p;
83
+ if (i instanceof Uint8Array)
84
+ p = O(i);
85
+ else if (typeof i == "string") {
86
+ if (i.startsWith("http://") || i.startsWith("https://"))
87
+ return {
88
+ type: "uri",
89
+ modality: h(t.mediaType),
90
+ mime_type: (o = t.mediaType) != null ? o : null,
91
+ uri: i
92
+ };
93
+ p = i;
94
+ } else {
95
+ if (i instanceof URL)
96
+ return {
97
+ type: "uri",
98
+ modality: h(t.mediaType),
99
+ mime_type: (s = t.mediaType) != null ? s : null,
100
+ uri: i.toString()
101
+ };
102
+ p = String(i);
103
+ }
104
+ return {
105
+ type: "blob",
106
+ modality: h(t.mediaType),
107
+ mime_type: (a = t.mediaType) != null ? a : null,
108
+ content: p
109
+ };
110
+ }
111
+ case "tool-approval-response":
112
+ return {
113
+ type: "tool_approval_response",
114
+ approval_id: t.approvalId,
115
+ approved: t.approved,
116
+ reason: t.reason
117
+ };
118
+ case "custom":
119
+ return { type: "custom", kind: t.kind };
120
+ case "reasoning-file":
121
+ return { type: String(t.type) };
122
+ default:
123
+ return { type: String(t.type) };
124
+ }
125
+ }
126
+ function h(t) {
127
+ return !t || t.startsWith("image/") ? "image" : t.startsWith("video/") ? "video" : t.startsWith("audio/") ? "audio" : "image";
128
+ }
129
+ function V(t) {
130
+ return t.filter((e) => e.role !== "system").map((e) => {
131
+ if (e.role === "system")
132
+ return {
133
+ role: "system",
134
+ parts: [{ type: "text", content: e.content }]
135
+ };
136
+ const n = e.content.map(F);
137
+ return { role: e.role, parts: n };
138
+ });
139
+ }
140
+ function A({
141
+ prompt: t,
142
+ messages: e
143
+ }) {
144
+ const n = [];
145
+ if (typeof t == "string")
146
+ n.push({
147
+ role: "user",
148
+ parts: [{ type: "text", content: t }]
149
+ });
150
+ else if (Array.isArray(t))
151
+ for (const o of t) {
152
+ const s = R(o);
153
+ s && n.push(s);
154
+ }
155
+ if (e)
156
+ for (const o of e) {
157
+ const s = R(o);
158
+ s && n.push(s);
159
+ }
160
+ return n;
161
+ }
162
+ function R(t) {
163
+ if (t.role !== "system") {
164
+ if (t.role === "user")
165
+ return typeof t.content == "string" ? {
166
+ role: "user",
167
+ parts: [{ type: "text", content: t.content }]
168
+ } : { role: "user", parts: t.content.map((n) => {
169
+ var o, s, a, r, i, p, d, m;
170
+ switch (n.type) {
171
+ case "text":
172
+ return { type: "text", content: n.text };
173
+ case "image": {
174
+ const l = n.image;
175
+ return l instanceof URL ? {
176
+ type: "uri",
177
+ modality: "image",
178
+ mime_type: (o = n.mediaType) != null ? o : null,
179
+ uri: l.toString()
180
+ } : typeof l == "string" ? l.startsWith("http://") || l.startsWith("https://") ? {
181
+ type: "uri",
182
+ modality: "image",
183
+ mime_type: (s = n.mediaType) != null ? s : null,
184
+ uri: l
185
+ } : {
186
+ type: "blob",
187
+ modality: "image",
188
+ mime_type: (a = n.mediaType) != null ? a : null,
189
+ content: l
190
+ } : {
191
+ type: "blob",
192
+ modality: "image",
193
+ mime_type: (r = n.mediaType) != null ? r : null,
194
+ content: O(l)
195
+ };
196
+ }
197
+ case "file": {
198
+ const l = n.data, f = (() => {
199
+ if (typeof l == "object" && l !== null && !(l instanceof URL) && !(l instanceof Uint8Array) && !(l instanceof ArrayBuffer) && "type" in l)
200
+ switch (l.type) {
201
+ case "data":
202
+ return l.data;
203
+ case "url":
204
+ return l.url;
205
+ case "text":
206
+ return l.text;
207
+ default:
208
+ return "";
209
+ }
210
+ return l;
211
+ })();
212
+ return f instanceof URL ? {
213
+ type: "uri",
214
+ modality: h(n.mediaType),
215
+ mime_type: (i = n.mediaType) != null ? i : null,
216
+ uri: f.toString()
217
+ } : typeof f == "string" ? f.startsWith("http://") || f.startsWith("https://") ? {
218
+ type: "uri",
219
+ modality: h(n.mediaType),
220
+ mime_type: (p = n.mediaType) != null ? p : null,
221
+ uri: f
222
+ } : {
223
+ type: "blob",
224
+ modality: h(n.mediaType),
225
+ mime_type: (d = n.mediaType) != null ? d : null,
226
+ content: f
227
+ } : {
228
+ type: "blob",
229
+ modality: h(n.mediaType),
230
+ mime_type: (m = n.mediaType) != null ? m : null,
231
+ content: O(f)
232
+ };
233
+ }
234
+ default:
235
+ return { type: String(n.type) };
236
+ }
237
+ }) };
238
+ if (t.role === "assistant")
239
+ return typeof t.content == "string" ? {
240
+ role: "assistant",
241
+ parts: [{ type: "text", content: t.content }]
242
+ } : { role: "assistant", parts: t.content.map((n) => {
243
+ var o, s;
244
+ switch (n.type) {
245
+ case "text":
246
+ return { type: "text", content: n.text };
247
+ case "reasoning":
248
+ return { type: "reasoning", content: n.text };
249
+ case "tool-call":
250
+ return {
251
+ type: "tool_call",
252
+ id: (o = n.toolCallId) != null ? o : null,
253
+ name: n.toolName,
254
+ arguments: n.input
255
+ };
256
+ case "tool-result": {
257
+ const a = n.output;
258
+ let r;
259
+ return a && (a.type === "text" || a.type === "error-text" || a.type === "json" || a.type === "error-json" ? r = a.value : a.type === "execution-denied" ? r = { denied: !0, reason: a.reason } : r = a), {
260
+ type: "tool_call_response",
261
+ id: (s = n.toolCallId) != null ? s : null,
262
+ response: r
263
+ };
264
+ }
265
+ default:
266
+ return { type: String(n.type) };
267
+ }
268
+ }) };
269
+ if (t.role === "tool")
270
+ return { role: "tool", parts: t.content.map((n) => {
271
+ var o;
272
+ if (n.type === "tool-result") {
273
+ const s = n.output;
274
+ let a;
275
+ return s && (s.type === "text" || s.type === "error-text" || s.type === "json" || s.type === "error-json" ? a = s.value : s.type === "execution-denied" ? a = { denied: !0, reason: s.reason } : a = s), {
276
+ type: "tool_call_response",
277
+ id: (o = n.toolCallId) != null ? o : null,
278
+ response: a
279
+ };
280
+ }
281
+ return { type: String(n.type) };
282
+ }) };
283
+ }
284
+ }
285
+ function q({
286
+ text: t,
287
+ reasoning: e,
288
+ toolCalls: n,
289
+ files: o,
290
+ finishReason: s
291
+ }) {
292
+ const a = [];
293
+ if (e)
294
+ for (const r of e)
295
+ "text" in r && r.text && a.push({ type: "reasoning", content: r.text });
296
+ if (t != null && t.length > 0 && a.push({ type: "text", content: t }), n)
297
+ for (const r of n)
298
+ a.push({
299
+ type: "tool_call",
300
+ id: r.toolCallId,
301
+ name: r.toolName,
302
+ arguments: r.input
303
+ });
304
+ if (o)
305
+ for (const r of o)
306
+ a.push({
307
+ type: "blob",
308
+ modality: h(r.mediaType),
309
+ mime_type: r.mediaType,
310
+ content: r.base64
311
+ });
312
+ return [
313
+ {
314
+ role: "assistant",
315
+ parts: a,
316
+ finish_reason: P(s)
317
+ }
318
+ ];
319
+ }
320
+ function j({
321
+ objectText: t,
322
+ finishReason: e
323
+ }) {
324
+ return [
325
+ {
326
+ role: "assistant",
327
+ parts: [{ type: "text", content: t }],
328
+ finish_reason: P(e)
329
+ }
330
+ ];
331
+ }
332
+ function P(t) {
333
+ var e;
334
+ return (e = {
335
+ stop: "stop",
336
+ length: "length",
337
+ "content-filter": "content_filter",
338
+ "tool-calls": "tool_call",
339
+ error: "error",
340
+ other: "stop",
341
+ unknown: "stop"
342
+ }[t]) != null ? e : t;
343
+ }
344
+ function b(t, e) {
345
+ e instanceof Error ? (t.recordException({
346
+ name: e.name,
347
+ message: e.message,
348
+ stack: e.stack
349
+ }), t.setStatus({
350
+ code: M.ERROR,
351
+ message: e.message
352
+ })) : t.setStatus({ code: M.ERROR });
353
+ }
354
+ function H(t) {
355
+ return typeof t == "string" || typeof t == "number" || typeof t == "boolean";
356
+ }
357
+ function k(t) {
358
+ if (!Array.isArray(t))
359
+ return t;
360
+ const e = new Set(
361
+ t.filter(H).map((o) => typeof o)
362
+ );
363
+ if (e.size !== 1)
364
+ return;
365
+ const [n] = e;
366
+ return n === "string" ? t.filter((o) => typeof o == "string") : n === "number" ? t.filter((o) => typeof o == "number") : t.filter((o) => typeof o == "boolean");
367
+ }
368
+ function X(t) {
369
+ const e = {};
370
+ for (const [n, o] of Object.entries(t ?? {})) {
371
+ if (o == null) continue;
372
+ const s = k(o);
373
+ s != null && (e[n] = s);
374
+ }
375
+ return e;
376
+ }
377
+ function Q(t) {
378
+ return t?.isEnabled !== !1;
379
+ }
380
+ function u(t, e) {
381
+ if (!Q(t))
382
+ return {};
383
+ const n = {};
384
+ for (const [o, s] of Object.entries(e)) {
385
+ if (s == null) continue;
386
+ if (typeof s == "object" && "input" in s && typeof s.input == "function") {
387
+ if (t?.recordInputs === !1) continue;
388
+ const r = s.input();
389
+ if (r != null) {
390
+ const i = k(r);
391
+ i != null && (n[o] = i);
392
+ }
393
+ continue;
394
+ }
395
+ if (typeof s == "object" && "output" in s && typeof s.output == "function") {
396
+ if (t?.recordOutputs === !1) continue;
397
+ const r = s.output();
398
+ if (r != null) {
399
+ const i = k(r);
400
+ i != null && (n[o] = i);
401
+ }
402
+ continue;
403
+ }
404
+ const a = k(s);
405
+ a != null && (n[o] = a);
406
+ }
407
+ return n;
408
+ }
409
+ var Y = {
410
+ usage: !1,
411
+ providerMetadata: !1,
412
+ embedding: !1,
413
+ reranking: !1,
414
+ runtimeContext: !1,
415
+ headers: !1,
416
+ toolChoice: !1,
417
+ schema: !1
418
+ };
419
+ function Z(t) {
420
+ var e, n, o, s, a, r, i, p;
421
+ return {
422
+ ...Y,
423
+ usage: (e = t.usage) != null ? e : !1,
424
+ providerMetadata: (n = t.providerMetadata) != null ? n : !1,
425
+ embedding: (o = t.embedding) != null ? o : !1,
426
+ reranking: (s = t.reranking) != null ? s : !1,
427
+ runtimeContext: (a = t.runtimeContext) != null ? a : !1,
428
+ headers: (r = t.headers) != null ? r : !1,
429
+ toolChoice: (i = t.toolChoice) != null ? i : !1,
430
+ schema: (p = t.schema) != null ? p : !1
431
+ };
432
+ }
433
+ function tt(t) {
434
+ const e = {};
435
+ for (const [n, o] of Object.entries(t ?? {}))
436
+ v(e, `ai.settings.context.${n}`, o);
437
+ return e;
438
+ }
439
+ function v(t, e, n) {
440
+ if (n != null) {
441
+ if (Array.isArray(n) || typeof n != "object") {
442
+ t[e] = n;
443
+ return;
444
+ }
445
+ for (const [o, s] of Object.entries(n))
446
+ v(t, `${e}.${o}`, s);
447
+ }
448
+ }
449
+ function C(t) {
450
+ return Object.fromEntries(
451
+ Object.entries(t ?? {}).filter(([, e]) => e != null).map(([e, n]) => [`ai.request.headers.${e}`, n])
452
+ );
453
+ }
454
+ function x(t) {
455
+ var e, n, o;
456
+ return {
457
+ "ai.usage.inputTokenDetails.noCacheTokens": (e = t.inputTokenDetails) == null ? void 0 : e.noCacheTokens,
458
+ "ai.usage.outputTokenDetails.textTokens": (n = t.outputTokenDetails) == null ? void 0 : n.textTokens,
459
+ "ai.usage.outputTokenDetails.reasoningTokens": (o = t.outputTokenDetails) == null ? void 0 : o.reasoningTokens
460
+ };
461
+ }
462
+ function c(t, e, n) {
463
+ const o = {};
464
+ for (const [s, a] of Object.entries(n))
465
+ !e[s] || a == null || Object.assign(o, u(t, a));
466
+ return o;
467
+ }
468
+ function T(t) {
469
+ return t == null ? void 0 : t / 1e3;
470
+ }
471
+ function et(t) {
472
+ var e;
473
+ return {
474
+ "gen_ai.client.operation.duration": T(t.responseTimeMs),
475
+ "gen_ai.client.operation.time_to_first_chunk": T(
476
+ t.timeToFirstOutputMs
477
+ ),
478
+ "gen_ai.client.operation.time_per_output_chunk": T(
479
+ (e = t.timeBetweenOutputChunksMs) == null ? void 0 : e.avg
480
+ )
481
+ };
482
+ }
483
+ var nt = class {
484
+ constructor(t = {}) {
485
+ this.callStates = /* @__PURE__ */ new Map();
486
+ var e;
487
+ this.tracer = (e = t.tracer) != null ? e : g.getTracer("gen_ai"), this.supplementalAttributes = Z(t), this.enrichSpan = t.enrichSpan;
488
+ }
489
+ getCallState(t) {
490
+ return this.callStates.get(t);
491
+ }
492
+ cleanupCallState(t) {
493
+ this.callStates.delete(t);
494
+ }
495
+ getSpanAttributes({
496
+ attributes: t,
497
+ spanType: e,
498
+ operationId: n,
499
+ callId: o,
500
+ runtimeContext: s
501
+ }) {
502
+ var a;
503
+ let r;
504
+ try {
505
+ r = (a = this.enrichSpan) == null ? void 0 : a.call(this, {
506
+ spanType: e,
507
+ operationId: n,
508
+ callId: o,
509
+ runtimeContext: s
510
+ });
511
+ } catch {
512
+ r = void 0;
513
+ }
514
+ return {
515
+ ...X(r),
516
+ ...t
517
+ };
518
+ }
519
+ executeTool({
520
+ callId: t,
521
+ toolCallId: e,
522
+ execute: n
523
+ }) {
524
+ var o;
525
+ const s = (o = this.getCallState(t)) == null ? void 0 : o.toolSpans.get(e);
526
+ return s == null ? n() : _.with(s.context, n);
527
+ }
528
+ /**
529
+ * Runs the provider `doGenerate`/`doStream` call with the active model-call
530
+ * context.
531
+ */
532
+ executeLanguageModelCall({
533
+ callId: t,
534
+ execute: e
535
+ }) {
536
+ var n;
537
+ const o = this.getCallState(t), s = (n = o?.inferenceContext) != null ? n : o?.stepContext;
538
+ return s == null ? e() : _.with(s, e);
539
+ }
540
+ onStart(t) {
541
+ if (t.operationId === "ai.embed" || t.operationId === "ai.embedMany") {
542
+ this.onEmbedOperationStart(t);
543
+ return;
544
+ }
545
+ if (t.operationId === "ai.rerank") {
546
+ this.onRerankOperationStart(
547
+ t
548
+ );
549
+ return;
550
+ }
551
+ if (t.operationId === "ai.generateObject" || t.operationId === "ai.streamObject") {
552
+ this.onObjectOperationStart(
553
+ t
554
+ );
555
+ return;
556
+ }
557
+ this.onGenerateStart(t);
558
+ }
559
+ onGenerateStart(t) {
560
+ var e;
561
+ const n = {
562
+ recordInputs: t.recordInputs,
563
+ recordOutputs: t.recordOutputs,
564
+ functionId: t.functionId
565
+ }, o = {
566
+ maxOutputTokens: t.maxOutputTokens,
567
+ temperature: t.temperature,
568
+ topP: t.topP,
569
+ topK: t.topK,
570
+ presencePenalty: t.presencePenalty,
571
+ frequencyPenalty: t.frequencyPenalty,
572
+ stopSequences: t.stopSequences,
573
+ seed: t.seed,
574
+ maxRetries: t.maxRetries
575
+ }, s = y(t.provider), a = N(t.operationId), r = t.runtimeContext, i = c(
576
+ n,
577
+ this.supplementalAttributes,
578
+ {
579
+ runtimeContext: tt(r),
580
+ headers: C(t.headers)
581
+ }
582
+ ), p = u(n, {
583
+ "gen_ai.operation.name": a,
584
+ "gen_ai.provider.name": s,
585
+ "gen_ai.request.model": t.modelId,
586
+ "gen_ai.agent.name": n.functionId,
587
+ "gen_ai.request.frequency_penalty": t.frequencyPenalty,
588
+ "gen_ai.request.max_tokens": t.maxOutputTokens,
589
+ "gen_ai.request.presence_penalty": t.presencePenalty,
590
+ "gen_ai.request.temperature": (e = t.temperature) != null ? e : void 0,
591
+ "gen_ai.request.top_k": t.topK,
592
+ "gen_ai.request.top_p": t.topP,
593
+ "gen_ai.request.stop_sequences": t.stopSequences,
594
+ "gen_ai.request.seed": t.seed,
595
+ "gen_ai.system_instructions": t.instructions ? {
596
+ input: () => JSON.stringify(E(t.instructions))
597
+ } : void 0,
598
+ "gen_ai.input.messages": {
599
+ input: () => JSON.stringify(
600
+ A({
601
+ prompt: void 0,
602
+ messages: t.messages
603
+ })
604
+ )
605
+ },
606
+ ...i
607
+ }), d = `${a} ${t.modelId}`, m = this.tracer.startSpan(d, {
608
+ attributes: this.getSpanAttributes({
609
+ attributes: p,
610
+ spanType: "operation",
611
+ operationId: t.operationId,
612
+ callId: t.callId,
613
+ runtimeContext: r
614
+ }),
615
+ kind: S.INTERNAL
616
+ }), l = g.setSpan(_.active(), m);
617
+ this.callStates.set(t.callId, {
618
+ operationId: t.operationId,
619
+ telemetry: n,
620
+ rootSpan: m,
621
+ rootContext: l,
622
+ stepSpan: void 0,
623
+ stepContext: void 0,
624
+ inferenceSpan: void 0,
625
+ inferenceContext: void 0,
626
+ embedSpans: /* @__PURE__ */ new Map(),
627
+ rerankSpan: void 0,
628
+ toolSpans: /* @__PURE__ */ new Map(),
629
+ settings: o,
630
+ provider: t.provider,
631
+ modelId: t.modelId,
632
+ runtimeContext: r,
633
+ baseSupplementalAttributes: i
634
+ });
635
+ }
636
+ onObjectOperationStart(t) {
637
+ var e;
638
+ const n = {
639
+ recordInputs: t.recordInputs,
640
+ recordOutputs: t.recordOutputs,
641
+ functionId: t.functionId
642
+ }, o = {
643
+ maxOutputTokens: t.maxOutputTokens,
644
+ temperature: t.temperature,
645
+ topP: t.topP,
646
+ topK: t.topK,
647
+ presencePenalty: t.presencePenalty,
648
+ frequencyPenalty: t.frequencyPenalty,
649
+ seed: t.seed,
650
+ maxRetries: t.maxRetries
651
+ }, s = y(t.provider), a = N(t.operationId), r = c(
652
+ n,
653
+ this.supplementalAttributes,
654
+ {
655
+ headers: C(t.headers)
656
+ }
657
+ ), i = u(n, {
658
+ "gen_ai.operation.name": a,
659
+ "gen_ai.provider.name": s,
660
+ "gen_ai.request.model": t.modelId,
661
+ "gen_ai.agent.name": n.functionId,
662
+ "gen_ai.output.type": "json",
663
+ "gen_ai.request.frequency_penalty": t.frequencyPenalty,
664
+ "gen_ai.request.max_tokens": t.maxOutputTokens,
665
+ "gen_ai.request.presence_penalty": t.presencePenalty,
666
+ "gen_ai.request.temperature": (e = t.temperature) != null ? e : void 0,
667
+ "gen_ai.request.top_k": t.topK,
668
+ "gen_ai.request.top_p": t.topP,
669
+ "gen_ai.request.seed": t.seed,
670
+ "gen_ai.system_instructions": t.system ? {
671
+ input: () => JSON.stringify(E(t.system))
672
+ } : void 0,
673
+ "gen_ai.input.messages": {
674
+ input: () => JSON.stringify(
675
+ A({
676
+ prompt: t.prompt,
677
+ messages: t.messages
678
+ })
679
+ )
680
+ },
681
+ ...r,
682
+ ...c(n, this.supplementalAttributes, {
683
+ schema: {
684
+ "ai.schema": t.schema ? { input: () => JSON.stringify(t.schema) } : void 0,
685
+ "ai.schema.name": t.schemaName,
686
+ "ai.schema.description": t.schemaDescription,
687
+ "ai.settings.output": t.output
688
+ }
689
+ })
690
+ }), p = `${a} ${t.modelId}`, d = this.tracer.startSpan(p, {
691
+ attributes: this.getSpanAttributes({
692
+ attributes: i,
693
+ spanType: "operation",
694
+ operationId: t.operationId,
695
+ callId: t.callId,
696
+ runtimeContext: void 0
697
+ }),
698
+ kind: S.INTERNAL
699
+ }), m = g.setSpan(_.active(), d);
700
+ this.callStates.set(t.callId, {
701
+ operationId: t.operationId,
702
+ telemetry: n,
703
+ rootSpan: d,
704
+ rootContext: m,
705
+ stepSpan: void 0,
706
+ stepContext: void 0,
707
+ inferenceSpan: void 0,
708
+ inferenceContext: void 0,
709
+ embedSpans: /* @__PURE__ */ new Map(),
710
+ rerankSpan: void 0,
711
+ toolSpans: /* @__PURE__ */ new Map(),
712
+ settings: o,
713
+ provider: t.provider,
714
+ modelId: t.modelId,
715
+ runtimeContext: void 0,
716
+ baseSupplementalAttributes: r
717
+ });
718
+ }
719
+ /** @deprecated */
720
+ onObjectStepStart(t) {
721
+ var e;
722
+ const n = this.getCallState(t.callId);
723
+ if (!n?.rootSpan || !n.rootContext) return;
724
+ const { telemetry: o } = n, s = y(t.provider), a = u(o, {
725
+ "gen_ai.operation.name": "chat",
726
+ "gen_ai.provider.name": s,
727
+ "gen_ai.request.model": t.modelId,
728
+ "gen_ai.output.type": "json",
729
+ "gen_ai.request.frequency_penalty": n.settings.frequencyPenalty,
730
+ "gen_ai.request.max_tokens": n.settings.maxOutputTokens,
731
+ "gen_ai.request.presence_penalty": n.settings.presencePenalty,
732
+ "gen_ai.request.temperature": (e = n.settings.temperature) != null ? e : void 0,
733
+ "gen_ai.request.top_k": n.settings.topK,
734
+ "gen_ai.request.top_p": n.settings.topP,
735
+ "gen_ai.input.messages": {
736
+ input: () => t.promptMessages ? JSON.stringify(V(t.promptMessages)) : void 0
737
+ },
738
+ ...n.baseSupplementalAttributes
739
+ }), r = `chat ${t.modelId}`;
740
+ n.inferenceSpan = this.tracer.startSpan(
741
+ r,
742
+ {
743
+ attributes: this.getSpanAttributes({
744
+ attributes: a,
745
+ spanType: "languageModel",
746
+ operationId: n.operationId,
747
+ callId: t.callId,
748
+ runtimeContext: n.runtimeContext
749
+ }),
750
+ kind: S.CLIENT
751
+ },
752
+ n.rootContext
753
+ ), n.inferenceContext = g.setSpan(
754
+ n.rootContext,
755
+ n.inferenceSpan
756
+ );
757
+ }
758
+ /** @deprecated */
759
+ onObjectStepEnd(t) {
760
+ var e;
761
+ const n = this.getCallState(t.callId);
762
+ if (!n?.inferenceSpan) return;
763
+ const { telemetry: o } = n;
764
+ n.inferenceSpan.setAttributes(
765
+ u(o, {
766
+ "gen_ai.response.finish_reasons": [t.finishReason],
767
+ "gen_ai.response.id": t.response.id,
768
+ "gen_ai.response.model": t.response.modelId,
769
+ "gen_ai.usage.input_tokens": t.usage.inputTokens,
770
+ "gen_ai.usage.output_tokens": t.usage.outputTokens,
771
+ "gen_ai.usage.cache_read.input_tokens": (e = t.usage.inputTokenDetails) == null ? void 0 : e.cacheReadTokens,
772
+ "gen_ai.output.messages": {
773
+ output: () => {
774
+ try {
775
+ return JSON.stringify(
776
+ j({
777
+ objectText: t.objectText,
778
+ finishReason: t.finishReason
779
+ })
780
+ );
781
+ } catch {
782
+ return t.objectText;
783
+ }
784
+ }
785
+ },
786
+ ...c(
787
+ o,
788
+ this.supplementalAttributes,
789
+ {
790
+ providerMetadata: {
791
+ "ai.response.providerMetadata": t.providerMetadata ? JSON.stringify(t.providerMetadata) : void 0
792
+ },
793
+ usage: x(t.usage)
794
+ }
795
+ )
796
+ })
797
+ ), n.inferenceSpan.end(), n.inferenceSpan = void 0, n.inferenceContext = void 0;
798
+ }
799
+ onEmbedOperationStart(t) {
800
+ const e = {
801
+ recordInputs: t.recordInputs,
802
+ recordOutputs: t.recordOutputs,
803
+ functionId: t.functionId
804
+ }, n = y(t.provider), o = c(
805
+ e,
806
+ this.supplementalAttributes,
807
+ {
808
+ headers: C(t.headers)
809
+ }
810
+ ), s = t.value, a = t.operationId === "ai.embedMany", r = u(e, {
811
+ "gen_ai.operation.name": "embeddings",
812
+ "gen_ai.provider.name": n,
813
+ "gen_ai.request.model": t.modelId,
814
+ ...o,
815
+ ...c(e, this.supplementalAttributes, {
816
+ embedding: a ? {
817
+ "ai.values": {
818
+ input: () => s.map((m) => JSON.stringify(m))
819
+ }
820
+ } : {
821
+ "ai.value": {
822
+ input: () => JSON.stringify(s)
823
+ }
824
+ }
825
+ })
826
+ }), i = `embeddings ${t.modelId}`, p = this.tracer.startSpan(i, {
827
+ attributes: this.getSpanAttributes({
828
+ attributes: r,
829
+ spanType: "operation",
830
+ operationId: t.operationId,
831
+ callId: t.callId,
832
+ runtimeContext: void 0
833
+ }),
834
+ kind: S.CLIENT
835
+ }), d = g.setSpan(_.active(), p);
836
+ this.callStates.set(t.callId, {
837
+ operationId: t.operationId,
838
+ telemetry: e,
839
+ rootSpan: p,
840
+ rootContext: d,
841
+ stepSpan: void 0,
842
+ stepContext: void 0,
843
+ inferenceSpan: void 0,
844
+ inferenceContext: void 0,
845
+ embedSpans: /* @__PURE__ */ new Map(),
846
+ rerankSpan: void 0,
847
+ toolSpans: /* @__PURE__ */ new Map(),
848
+ settings: { maxRetries: t.maxRetries },
849
+ provider: t.provider,
850
+ modelId: t.modelId,
851
+ runtimeContext: void 0,
852
+ baseSupplementalAttributes: o
853
+ });
854
+ }
855
+ onStepStart(t) {
856
+ const e = this.getCallState(t.callId);
857
+ if (!e?.rootSpan || !e.rootContext) return;
858
+ const { telemetry: n } = e;
859
+ e.runtimeContext = t.runtimeContext;
860
+ const o = u(n, {
861
+ "gen_ai.operation.name": "agent_step",
862
+ ...e.baseSupplementalAttributes,
863
+ ...c(n, this.supplementalAttributes, {
864
+ toolChoice: {
865
+ "ai.prompt.toolChoice": {
866
+ input: () => t.stepToolChoice != null ? JSON.stringify(t.stepToolChoice) : void 0
867
+ }
868
+ }
869
+ })
870
+ });
871
+ e.stepSpan = this.tracer.startSpan(
872
+ `step ${t.steps.length + 1}`,
873
+ {
874
+ attributes: this.getSpanAttributes({
875
+ attributes: o,
876
+ spanType: "step",
877
+ operationId: e.operationId,
878
+ callId: t.callId,
879
+ runtimeContext: e.runtimeContext
880
+ }),
881
+ kind: S.INTERNAL
882
+ },
883
+ e.rootContext
884
+ ), e.stepContext = g.setSpan(e.rootContext, e.stepSpan);
885
+ }
886
+ onLanguageModelCallStart(t) {
887
+ var e;
888
+ const n = this.getCallState(t.callId);
889
+ if (!n?.stepContext) return;
890
+ const { telemetry: o } = n, s = y(t.provider), a = u(o, {
891
+ "gen_ai.operation.name": "chat",
892
+ "gen_ai.provider.name": s,
893
+ "gen_ai.request.model": t.modelId,
894
+ "gen_ai.request.frequency_penalty": n.settings.frequencyPenalty,
895
+ "gen_ai.request.max_tokens": n.settings.maxOutputTokens,
896
+ "gen_ai.request.presence_penalty": n.settings.presencePenalty,
897
+ "gen_ai.request.stop_sequences": n.settings.stopSequences,
898
+ "gen_ai.request.temperature": (e = n.settings.temperature) != null ? e : void 0,
899
+ "gen_ai.request.top_k": n.settings.topK,
900
+ "gen_ai.request.top_p": n.settings.topP,
901
+ "gen_ai.input.messages": {
902
+ input: () => {
903
+ const r = A({
904
+ prompt: void 0,
905
+ messages: t.messages
906
+ });
907
+ return r.length > 0 ? JSON.stringify(r) : void 0;
908
+ }
909
+ },
910
+ "gen_ai.tool.definitions": {
911
+ input: () => t.tools ? JSON.stringify(t.tools) : void 0
912
+ }
913
+ });
914
+ n.inferenceSpan = this.tracer.startSpan(
915
+ `chat ${t.modelId}`,
916
+ {
917
+ attributes: this.getSpanAttributes({
918
+ attributes: a,
919
+ spanType: "languageModel",
920
+ operationId: n.operationId,
921
+ callId: t.callId,
922
+ runtimeContext: n.runtimeContext
923
+ }),
924
+ kind: S.CLIENT
925
+ },
926
+ n.stepContext
927
+ ), n.inferenceContext = g.setSpan(
928
+ n.stepContext,
929
+ n.inferenceSpan
930
+ );
931
+ }
932
+ onLanguageModelCallEnd(t) {
933
+ var e, n;
934
+ const o = this.getCallState(t.callId);
935
+ if (!o?.inferenceSpan) return;
936
+ const { telemetry: s } = o;
937
+ o.inferenceSpan.setAttributes(
938
+ u(s, {
939
+ ...et(t.performance),
940
+ "gen_ai.response.finish_reasons": [t.finishReason],
941
+ "gen_ai.response.id": t.responseId,
942
+ "gen_ai.usage.input_tokens": t.usage.inputTokens,
943
+ "gen_ai.usage.output_tokens": t.usage.outputTokens,
944
+ "gen_ai.usage.cache_read.input_tokens": (e = t.usage.inputTokenDetails) == null ? void 0 : e.cacheReadTokens,
945
+ "gen_ai.usage.cache_creation.input_tokens": (n = t.usage.inputTokenDetails) == null ? void 0 : n.cacheWriteTokens,
946
+ "gen_ai.output.messages": {
947
+ output: () => JSON.stringify(
948
+ q({
949
+ text: t.content.filter((a) => a.type === "text").map((a) => a.text).join("") || void 0,
950
+ reasoning: t.content.filter((a) => a.type === "reasoning"),
951
+ toolCalls: t.content.filter((a) => a.type === "tool-call"),
952
+ files: t.content.filter((a) => a.type === "file").map((a) => a.file),
953
+ finishReason: t.finishReason
954
+ })
955
+ )
956
+ },
957
+ ...c(
958
+ s,
959
+ this.supplementalAttributes,
960
+ {
961
+ usage: x(t.usage)
962
+ }
963
+ )
964
+ })
965
+ ), o.inferenceSpan.end(), o.inferenceSpan = void 0, o.inferenceContext = void 0;
966
+ }
967
+ onToolExecutionStart(t) {
968
+ const e = this.getCallState(t.callId);
969
+ if (!e?.stepContext) return;
970
+ const { telemetry: n } = e, { toolCall: o } = t, s = u(n, {
971
+ "gen_ai.operation.name": "execute_tool",
972
+ "gen_ai.tool.name": o.toolName,
973
+ "gen_ai.tool.call.id": o.toolCallId,
974
+ "gen_ai.tool.type": "function",
975
+ "gen_ai.tool.call.arguments": {
976
+ input: () => JSON.stringify(o.input)
977
+ }
978
+ }), a = `execute_tool ${o.toolName}`, r = this.tracer.startSpan(
979
+ a,
980
+ {
981
+ attributes: this.getSpanAttributes({
982
+ attributes: s,
983
+ spanType: "tool",
984
+ operationId: e.operationId,
985
+ callId: t.callId,
986
+ runtimeContext: e.runtimeContext
987
+ }),
988
+ kind: S.INTERNAL
989
+ },
990
+ e.stepContext
991
+ ), i = g.setSpan(e.stepContext, r);
992
+ e.toolSpans.set(o.toolCallId, {
993
+ span: r,
994
+ context: i
995
+ });
996
+ }
997
+ onToolExecutionEnd(t) {
998
+ const e = this.getCallState(t.callId);
999
+ if (!e) return;
1000
+ const n = e.toolSpans.get(t.toolCall.toolCallId);
1001
+ if (!n) return;
1002
+ const { span: o } = n, { telemetry: s } = e, { toolOutput: a } = t;
1003
+ if (o.setAttributes(
1004
+ u(s, {
1005
+ "gen_ai.execute_tool.duration": T(t.toolExecutionMs)
1006
+ })
1007
+ ), a.type === "tool-result")
1008
+ try {
1009
+ o.setAttributes(
1010
+ u(s, {
1011
+ "gen_ai.tool.call.result": {
1012
+ output: () => JSON.stringify(a.output)
1013
+ }
1014
+ })
1015
+ );
1016
+ } catch {
1017
+ }
1018
+ else
1019
+ b(o, a.error);
1020
+ o.end(), e.toolSpans.delete(t.toolCall.toolCallId);
1021
+ }
1022
+ onStepEnd(t) {
1023
+ const e = this.getCallState(t.callId);
1024
+ if (!e?.stepSpan) return;
1025
+ const { telemetry: n } = e;
1026
+ e.stepSpan.setAttributes(
1027
+ c(n, this.supplementalAttributes, {
1028
+ providerMetadata: {
1029
+ "ai.response.providerMetadata": t.providerMetadata ? JSON.stringify(t.providerMetadata) : void 0
1030
+ },
1031
+ usage: x(t.usage)
1032
+ })
1033
+ ), e.stepSpan.end(), e.stepSpan = void 0, e.stepContext = void 0;
1034
+ }
1035
+ /** @deprecated Use `onStepEnd` instead. */
1036
+ onStepFinish(t) {
1037
+ this.onStepEnd(t);
1038
+ }
1039
+ onEnd(t) {
1040
+ const e = this.getCallState(t.callId);
1041
+ if (e?.rootSpan) {
1042
+ if (e.operationId === "ai.embed" || e.operationId === "ai.embedMany") {
1043
+ this.onEmbedOperationEnd(t);
1044
+ return;
1045
+ }
1046
+ if (e.operationId === "ai.rerank") {
1047
+ this.onRerankOperationEnd(t);
1048
+ return;
1049
+ }
1050
+ if (e.operationId === "ai.generateObject" || e.operationId === "ai.streamObject") {
1051
+ this.onObjectOperationEnd(t);
1052
+ return;
1053
+ }
1054
+ this.onGenerateEnd(t);
1055
+ }
1056
+ }
1057
+ onGenerateEnd(t) {
1058
+ var e, n;
1059
+ const o = this.getCallState(t.callId);
1060
+ if (!o?.rootSpan) return;
1061
+ const { telemetry: s } = o;
1062
+ o.rootSpan.setAttributes(
1063
+ u(s, {
1064
+ "gen_ai.response.finish_reasons": [t.finishReason],
1065
+ "gen_ai.usage.input_tokens": t.usage.inputTokens,
1066
+ "gen_ai.usage.output_tokens": t.usage.outputTokens,
1067
+ "gen_ai.usage.cache_read.input_tokens": (e = t.usage.inputTokenDetails) == null ? void 0 : e.cacheReadTokens,
1068
+ "gen_ai.usage.cache_creation.input_tokens": (n = t.usage.inputTokenDetails) == null ? void 0 : n.cacheWriteTokens,
1069
+ "gen_ai.output.messages": {
1070
+ output: () => {
1071
+ var a;
1072
+ return JSON.stringify(
1073
+ q({
1074
+ text: (a = t.text) != null ? a : void 0,
1075
+ reasoning: t.finalStep.reasoning,
1076
+ toolCalls: t.toolCalls,
1077
+ files: t.files,
1078
+ finishReason: t.finishReason
1079
+ })
1080
+ );
1081
+ }
1082
+ },
1083
+ ...c(
1084
+ s,
1085
+ this.supplementalAttributes,
1086
+ {
1087
+ providerMetadata: {
1088
+ "ai.response.providerMetadata": t.finalStep.providerMetadata ? JSON.stringify(t.finalStep.providerMetadata) : void 0
1089
+ },
1090
+ usage: x(t.usage)
1091
+ }
1092
+ )
1093
+ })
1094
+ ), o.rootSpan.end(), this.cleanupCallState(t.callId);
1095
+ }
1096
+ onObjectOperationEnd(t) {
1097
+ var e;
1098
+ const n = this.getCallState(t.callId);
1099
+ if (!n?.rootSpan) return;
1100
+ const { telemetry: o } = n;
1101
+ n.rootSpan.setAttributes(
1102
+ u(o, {
1103
+ "gen_ai.response.finish_reasons": [t.finishReason],
1104
+ "gen_ai.usage.input_tokens": t.usage.inputTokens,
1105
+ "gen_ai.usage.output_tokens": t.usage.outputTokens,
1106
+ "gen_ai.usage.cache_read.input_tokens": (e = t.usage.inputTokenDetails) == null ? void 0 : e.cacheReadTokens,
1107
+ "gen_ai.output.messages": {
1108
+ output: () => t.object != null ? JSON.stringify(
1109
+ j({
1110
+ objectText: JSON.stringify(t.object),
1111
+ finishReason: t.finishReason
1112
+ })
1113
+ ) : void 0
1114
+ },
1115
+ ...c(
1116
+ o,
1117
+ this.supplementalAttributes,
1118
+ {
1119
+ providerMetadata: {
1120
+ "ai.response.providerMetadata": t.providerMetadata ? JSON.stringify(t.providerMetadata) : void 0
1121
+ },
1122
+ usage: x(t.usage)
1123
+ }
1124
+ )
1125
+ })
1126
+ ), n.rootSpan.end(), this.cleanupCallState(t.callId);
1127
+ }
1128
+ onEmbedOperationEnd(t) {
1129
+ const e = this.getCallState(t.callId);
1130
+ if (!e?.rootSpan) return;
1131
+ const { telemetry: n } = e, o = e.operationId === "ai.embedMany";
1132
+ e.rootSpan.setAttributes(
1133
+ u(n, {
1134
+ "gen_ai.usage.input_tokens": t.usage.tokens,
1135
+ ...c(
1136
+ n,
1137
+ this.supplementalAttributes,
1138
+ {
1139
+ embedding: o ? {
1140
+ "ai.embeddings": {
1141
+ output: () => t.embedding.map(
1142
+ (s) => JSON.stringify(s)
1143
+ )
1144
+ }
1145
+ } : {
1146
+ "ai.embedding": {
1147
+ output: () => JSON.stringify(t.embedding)
1148
+ }
1149
+ }
1150
+ }
1151
+ )
1152
+ })
1153
+ ), e.rootSpan.end(), this.cleanupCallState(t.callId);
1154
+ }
1155
+ onEmbedStart(t) {
1156
+ const e = this.getCallState(t.callId);
1157
+ if (!e?.rootSpan || !e.rootContext) return;
1158
+ const { telemetry: n } = e, o = y(e.provider), s = u(n, {
1159
+ "gen_ai.operation.name": "embeddings",
1160
+ "gen_ai.provider.name": o,
1161
+ "gen_ai.request.model": e.modelId,
1162
+ ...e.baseSupplementalAttributes,
1163
+ ...c(n, this.supplementalAttributes, {
1164
+ embedding: {
1165
+ "ai.values": {
1166
+ input: () => t.values.map((p) => JSON.stringify(p))
1167
+ }
1168
+ }
1169
+ })
1170
+ }), a = `embeddings ${e.modelId}`, r = this.tracer.startSpan(
1171
+ a,
1172
+ {
1173
+ attributes: this.getSpanAttributes({
1174
+ attributes: s,
1175
+ spanType: "embedding",
1176
+ operationId: e.operationId,
1177
+ callId: t.callId,
1178
+ runtimeContext: e.runtimeContext
1179
+ }),
1180
+ kind: S.CLIENT
1181
+ },
1182
+ e.rootContext
1183
+ ), i = g.setSpan(e.rootContext, r);
1184
+ e.embedSpans.set(t.embedCallId, {
1185
+ span: r,
1186
+ context: i
1187
+ });
1188
+ }
1189
+ onEmbedEnd(t) {
1190
+ const e = this.getCallState(t.callId);
1191
+ if (!e) return;
1192
+ const n = e.embedSpans.get(t.embedCallId);
1193
+ if (!n) return;
1194
+ const { span: o } = n, { telemetry: s } = e;
1195
+ o.setAttributes(
1196
+ u(s, {
1197
+ "gen_ai.usage.input_tokens": t.usage.tokens,
1198
+ ...c(
1199
+ s,
1200
+ this.supplementalAttributes,
1201
+ {
1202
+ embedding: {
1203
+ "ai.embeddings": {
1204
+ output: () => t.embeddings.map((a) => JSON.stringify(a))
1205
+ }
1206
+ }
1207
+ }
1208
+ )
1209
+ })
1210
+ ), o.end(), e.embedSpans.delete(t.embedCallId);
1211
+ }
1212
+ onRerankOperationStart(t) {
1213
+ const e = {
1214
+ recordInputs: t.recordInputs,
1215
+ recordOutputs: t.recordOutputs,
1216
+ functionId: t.functionId
1217
+ }, n = y(t.provider), o = c(
1218
+ e,
1219
+ this.supplementalAttributes,
1220
+ {
1221
+ headers: C(t.headers)
1222
+ }
1223
+ ), s = u(e, {
1224
+ "gen_ai.operation.name": "rerank",
1225
+ "gen_ai.provider.name": n,
1226
+ "gen_ai.request.model": t.modelId,
1227
+ ...o,
1228
+ ...c(e, this.supplementalAttributes, {
1229
+ reranking: {
1230
+ "ai.documents": {
1231
+ input: () => t.documents.map((p) => JSON.stringify(p))
1232
+ }
1233
+ }
1234
+ })
1235
+ }), a = `rerank ${t.modelId}`, r = this.tracer.startSpan(a, {
1236
+ attributes: this.getSpanAttributes({
1237
+ attributes: s,
1238
+ spanType: "operation",
1239
+ operationId: t.operationId,
1240
+ callId: t.callId,
1241
+ runtimeContext: void 0
1242
+ }),
1243
+ kind: S.CLIENT
1244
+ }), i = g.setSpan(_.active(), r);
1245
+ this.callStates.set(t.callId, {
1246
+ operationId: t.operationId,
1247
+ telemetry: e,
1248
+ rootSpan: r,
1249
+ rootContext: i,
1250
+ stepSpan: void 0,
1251
+ stepContext: void 0,
1252
+ inferenceSpan: void 0,
1253
+ inferenceContext: void 0,
1254
+ embedSpans: /* @__PURE__ */ new Map(),
1255
+ rerankSpan: void 0,
1256
+ toolSpans: /* @__PURE__ */ new Map(),
1257
+ settings: { maxRetries: t.maxRetries },
1258
+ provider: t.provider,
1259
+ modelId: t.modelId,
1260
+ runtimeContext: void 0,
1261
+ baseSupplementalAttributes: o
1262
+ });
1263
+ }
1264
+ onRerankOperationEnd(t) {
1265
+ const e = this.getCallState(t.callId);
1266
+ e?.rootSpan && (e.rootSpan.end(), this.cleanupCallState(t.callId));
1267
+ }
1268
+ onRerankStart(t) {
1269
+ const e = this.getCallState(t.callId);
1270
+ if (!e?.rootSpan || !e.rootContext) return;
1271
+ const { telemetry: n } = e, o = y(e.provider), s = u(n, {
1272
+ "gen_ai.operation.name": "rerank",
1273
+ "gen_ai.provider.name": o,
1274
+ "gen_ai.request.model": e.modelId,
1275
+ ...e.baseSupplementalAttributes,
1276
+ ...c(n, this.supplementalAttributes, {
1277
+ reranking: {
1278
+ "ai.documents": {
1279
+ input: () => t.documents.map((p) => JSON.stringify(p))
1280
+ }
1281
+ }
1282
+ })
1283
+ }), a = `rerank ${e.modelId}`, r = this.tracer.startSpan(
1284
+ a,
1285
+ {
1286
+ attributes: this.getSpanAttributes({
1287
+ attributes: s,
1288
+ spanType: "reranking",
1289
+ operationId: e.operationId,
1290
+ callId: t.callId,
1291
+ runtimeContext: e.runtimeContext
1292
+ }),
1293
+ kind: S.CLIENT
1294
+ },
1295
+ e.rootContext
1296
+ ), i = g.setSpan(e.rootContext, r);
1297
+ e.rerankSpan = { span: r, context: i };
1298
+ }
1299
+ onRerankEnd(t) {
1300
+ const e = this.getCallState(t.callId);
1301
+ if (!e?.rerankSpan) return;
1302
+ const { span: n } = e.rerankSpan, { telemetry: o } = e;
1303
+ n.setAttributes(
1304
+ c(o, this.supplementalAttributes, {
1305
+ reranking: {
1306
+ "ai.ranking.type": t.documentsType,
1307
+ "ai.ranking": {
1308
+ output: () => t.ranking.map((s) => JSON.stringify(s))
1309
+ }
1310
+ }
1311
+ })
1312
+ ), n.end(), e.rerankSpan = void 0;
1313
+ }
1314
+ onAbort(t) {
1315
+ const e = this.getCallState(t.callId);
1316
+ if (e?.rootSpan) {
1317
+ for (const { span: n } of e.toolSpans.values())
1318
+ n.end();
1319
+ e.toolSpans.clear(), e.inferenceSpan && (e.inferenceSpan.end(), e.inferenceSpan = void 0, e.inferenceContext = void 0), e.stepSpan && (e.stepSpan.end(), e.stepSpan = void 0, e.stepContext = void 0);
1320
+ for (const { span: n } of e.embedSpans.values())
1321
+ n.end();
1322
+ e.embedSpans.clear(), e.rerankSpan && (e.rerankSpan.span.end(), e.rerankSpan = void 0), e.rootSpan.end(), this.cleanupCallState(t.callId);
1323
+ }
1324
+ }
1325
+ onError(t) {
1326
+ var e;
1327
+ const n = t;
1328
+ if (!n?.callId) return;
1329
+ const o = this.getCallState(n.callId);
1330
+ if (!o?.rootSpan) return;
1331
+ const s = (e = n.error) != null ? e : t;
1332
+ for (const { span: a } of o.toolSpans.values())
1333
+ b(a, s), a.end();
1334
+ o.toolSpans.clear(), o.inferenceSpan && (b(o.inferenceSpan, s), o.inferenceSpan.end(), o.inferenceSpan = void 0, o.inferenceContext = void 0), o.stepSpan && (b(o.stepSpan, s), o.stepSpan.end(), o.stepSpan = void 0, o.stepContext = void 0);
1335
+ for (const { span: a } of o.embedSpans.values())
1336
+ b(a, s), a.end();
1337
+ o.embedSpans.clear(), o.rerankSpan && (b(o.rerankSpan.span, s), o.rerankSpan.span.end(), o.rerankSpan = void 0), b(o.rootSpan, s), o.rootSpan.end(), this.cleanupCallState(n.callId);
1338
+ }
1339
+ };
1340
+ function ot(t) {
1341
+ return w({
1342
+ messages: t,
1343
+ emptyMessages: "remove",
1344
+ reasoning: "none",
1345
+ toolCalls: `before-last-${z}-messages`
1346
+ });
1347
+ }
1348
+ function at(t) {
1349
+ return typeof t == "object" && t !== null && "role" in t && "content" in t;
1350
+ }
1351
+ function st(t) {
1352
+ return Array.isArray(t) && t.every(at);
1353
+ }
1354
+ function rt(t, { conversationId: e, getModel: n }) {
1355
+ let o = 0;
1356
+ const s = () => {
1357
+ const a = n?.();
1358
+ return a ? { model_provider: a.provider, model_id: a.modelId } : {};
1359
+ };
1360
+ return {
1361
+ onStepStart: () => {
1362
+ o += 1;
1363
+ },
1364
+ onToolExecutionStart: (a) => {
1365
+ t("com.redocly.aiChat.toolCallStarted", [
1366
+ {
1367
+ conversation_id: e,
1368
+ ...I("toolCall", a.toolCall.toolCallId, "ai"),
1369
+ tool_name: a.toolCall.toolName,
1370
+ input: a.toolCall.input,
1371
+ step_number: o,
1372
+ ...s()
1373
+ }
1374
+ ]);
1375
+ },
1376
+ onToolExecutionEnd: (a) => {
1377
+ const r = a.toolOutput.type === "tool-error";
1378
+ t("com.redocly.aiChat.toolCallFinished", [
1379
+ {
1380
+ conversation_id: e,
1381
+ ...I("toolCall", a.toolCall.toolCallId, "ai"),
1382
+ tool_name: a.toolCall.toolName,
1383
+ input: a.toolCall.input,
1384
+ step_number: o,
1385
+ success: !r,
1386
+ duration_ms: a.toolExecutionMs,
1387
+ ...s(),
1388
+ ...r && {
1389
+ error: a.toolOutput.error instanceof Error ? a.toolOutput.error.message : String(a.toolOutput.error)
1390
+ }
1391
+ }
1392
+ ]);
1393
+ },
1394
+ onStart: (a) => {
1395
+ o = 0, t("com.redocly.aiChat.conversationStarted", [
1396
+ {
1397
+ ...I("conversation", e, "ai"),
1398
+ model_provider: "provider" in a ? a.provider : "unknown",
1399
+ model_id: "modelId" in a ? a.modelId : "unknown"
1400
+ }
1401
+ ]);
1402
+ },
1403
+ onEnd: (a) => {
1404
+ if (!("steps" in a)) return;
1405
+ const r = a.usage;
1406
+ t("com.redocly.aiChat.conversationFinished", [
1407
+ {
1408
+ ...I("conversation", e, "ai"),
1409
+ model_provider: a.model.provider,
1410
+ model_id: a.model.modelId,
1411
+ success: !0,
1412
+ step_count: a.steps.length,
1413
+ finish_reason: a.finishReason,
1414
+ input_tokens: r.inputTokens,
1415
+ output_tokens: r.outputTokens,
1416
+ total_tokens: r.totalTokens
1417
+ }
1418
+ ]);
1419
+ }
1420
+ };
1421
+ }
1422
+ function it(t, e) {
1423
+ const n = () => g.getSpan(_.active()) ? _.active() : e;
1424
+ return {
1425
+ startSpan: (o, s, a) => t.startSpan(o, s, a ?? e),
1426
+ startActiveSpan: ((o, s, a, r) => {
1427
+ if (typeof s == "function")
1428
+ return t.startActiveSpan(o, {}, n(), s);
1429
+ if (typeof a == "function")
1430
+ return t.startActiveSpan(o, s, n(), a);
1431
+ if (r)
1432
+ return t.startActiveSpan(o, s, a, r);
1433
+ throw new Error("withParentContext: invalid startActiveSpan invocation");
1434
+ })
1435
+ };
1436
+ }
1437
+ class ct {
1438
+ model;
1439
+ tools;
1440
+ toolLoopAgent;
1441
+ maxSteps;
1442
+ context = [];
1443
+ systemInstructions = U();
1444
+ getActiveStateMessage;
1445
+ constructor(e) {
1446
+ const { activeConversationId: n, onFinish: o, onStepFinish: s, tools: a } = e;
1447
+ this.maxSteps = e.maxSteps ?? W, this.getActiveStateMessage = e.getActiveStateMessage, this.model = this.createModel(e.model);
1448
+ const r = ({ stepNumber: d, messages: m }) => {
1449
+ const l = [], f = this.buildActiveStateMessage();
1450
+ return f && l.push({ role: "user", content: f }), d === this.maxSteps - 1 && l.push({ role: "user", content: G }), l.length === 0 ? void 0 : { messages: [...m, ...l] };
1451
+ }, i = (d) => {
1452
+ const m = d.messages ? this.prepareMessages(d.messages) : void 0, l = d.prompt ? this.preparePrompt(d.prompt) : void 0;
1453
+ return {
1454
+ ...d,
1455
+ model: this.model,
1456
+ messages: m,
1457
+ prompt: l,
1458
+ instructions: [...this.systemInstructions, ...this.context],
1459
+ tools: this.tools ?? d.tools
1460
+ };
1461
+ }, p = new nt({
1462
+ ...e.parentCtx && {
1463
+ tracer: it(g.getTracer("ai"), e.parentCtx)
1464
+ }
1465
+ });
1466
+ this.toolLoopAgent = new L({
1467
+ model: this.model,
1468
+ tools: a,
1469
+ stopWhen: J(this.maxSteps),
1470
+ onStepFinish: s,
1471
+ onFinish: o,
1472
+ maxOutputTokens: e.maxOutputTokens,
1473
+ maxRetries: e.maxRetries ?? K,
1474
+ prepareStep: r,
1475
+ prepareCall: i,
1476
+ telemetry: {
1477
+ isEnabled: !0,
1478
+ recordInputs: !0,
1479
+ recordOutputs: !0,
1480
+ functionId: "replay-ai-chat",
1481
+ integrations: [
1482
+ p,
1483
+ rt(e.sendEvent, {
1484
+ conversationId: n,
1485
+ getModel: () => ({ provider: this.model.provider, modelId: this.model.modelId })
1486
+ })
1487
+ ]
1488
+ }
1489
+ });
1490
+ }
1491
+ createModel(e) {
1492
+ return D(e);
1493
+ }
1494
+ setModel(e) {
1495
+ this.model = this.createModel(e);
1496
+ }
1497
+ getAgent() {
1498
+ return this.toolLoopAgent;
1499
+ }
1500
+ addContext(e) {
1501
+ this.context.push(...e);
1502
+ }
1503
+ registerTools(e) {
1504
+ this.tools = e;
1505
+ }
1506
+ async generateTitle(e, n) {
1507
+ return $({
1508
+ model: this.model,
1509
+ system: B,
1510
+ prompt: e,
1511
+ temperature: 0,
1512
+ abortSignal: n
1513
+ }).text;
1514
+ }
1515
+ buildActiveStateMessage() {
1516
+ if (!this.getActiveStateMessage)
1517
+ return null;
1518
+ try {
1519
+ return this.getActiveStateMessage() || null;
1520
+ } catch (e) {
1521
+ return console.error(e), null;
1522
+ }
1523
+ }
1524
+ prepareMessages(e) {
1525
+ return ot(e);
1526
+ }
1527
+ preparePrompt(e) {
1528
+ return st(e) ? this.prepareMessages(e) : e;
1529
+ }
1530
+ }
1531
+ export {
1532
+ ct as AgentLoop
1533
+ };