@uselemma/tracing 7.15.3 → 7.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/dist/client.d.ts +129 -56
  2. package/dist/client.d.ts.map +1 -1
  3. package/dist/client.js +596 -200
  4. package/dist/client.js.map +1 -1
  5. package/dist/coding-agent.d.ts +4 -1
  6. package/dist/coding-agent.d.ts.map +1 -1
  7. package/dist/coding-agent.js +73 -31
  8. package/dist/coding-agent.js.map +1 -1
  9. package/dist/index.d.ts +2 -2
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +16 -1
  12. package/dist/index.js.map +1 -1
  13. package/dist/integration-client.d.ts +1 -1
  14. package/dist/integration-client.d.ts.map +1 -1
  15. package/dist/integration-client.js.map +1 -1
  16. package/dist/langchain.d.ts +15 -17
  17. package/dist/langchain.d.ts.map +1 -1
  18. package/dist/langchain.js +327 -87
  19. package/dist/langchain.js.map +1 -1
  20. package/dist/mastra.d.ts.map +1 -1
  21. package/dist/mastra.js +225 -24
  22. package/dist/mastra.js.map +1 -1
  23. package/dist/messages.d.ts +84 -0
  24. package/dist/messages.d.ts.map +1 -0
  25. package/dist/messages.js +1102 -0
  26. package/dist/messages.js.map +1 -0
  27. package/dist/openai-agents-containers.d.ts +1 -0
  28. package/dist/openai-agents-containers.d.ts.map +1 -1
  29. package/dist/openai-agents-containers.js.map +1 -1
  30. package/dist/openai-agents-generation.d.ts +8 -5
  31. package/dist/openai-agents-generation.d.ts.map +1 -1
  32. package/dist/openai-agents-generation.js +92 -44
  33. package/dist/openai-agents-generation.js.map +1 -1
  34. package/dist/openai-agents-tool-calls.d.ts +24 -0
  35. package/dist/openai-agents-tool-calls.d.ts.map +1 -0
  36. package/dist/openai-agents-tool-calls.js +207 -0
  37. package/dist/openai-agents-tool-calls.js.map +1 -0
  38. package/dist/openai-agents.d.ts +2 -7
  39. package/dist/openai-agents.d.ts.map +1 -1
  40. package/dist/openai-agents.js +259 -20
  41. package/dist/openai-agents.js.map +1 -1
  42. package/dist/payload.d.ts +30 -0
  43. package/dist/payload.d.ts.map +1 -0
  44. package/dist/payload.js +413 -0
  45. package/dist/payload.js.map +1 -0
  46. package/dist/release.d.ts +12 -0
  47. package/dist/release.d.ts.map +1 -1
  48. package/dist/release.js +41 -7
  49. package/dist/release.js.map +1 -1
  50. package/dist/tool-call-id.d.ts +14 -0
  51. package/dist/tool-call-id.d.ts.map +1 -0
  52. package/dist/tool-call-id.js +56 -0
  53. package/dist/tool-call-id.js.map +1 -0
  54. package/dist/turn.d.ts +25 -1
  55. package/dist/turn.d.ts.map +1 -1
  56. package/dist/turn.js +97 -14
  57. package/dist/turn.js.map +1 -1
  58. package/dist/usage.d.ts +5 -3
  59. package/dist/usage.d.ts.map +1 -1
  60. package/dist/usage.js +38 -35
  61. package/dist/usage.js.map +1 -1
  62. package/dist/vercel-ai-events.d.ts +46 -9
  63. package/dist/vercel-ai-events.d.ts.map +1 -1
  64. package/dist/vercel-ai-events.js +81 -7
  65. package/dist/vercel-ai-events.js.map +1 -1
  66. package/dist/vercel-ai-run.d.ts +7 -0
  67. package/dist/vercel-ai-run.d.ts.map +1 -1
  68. package/dist/vercel-ai-run.js +191 -47
  69. package/dist/vercel-ai-run.js.map +1 -1
  70. package/dist/version.d.ts +1 -1
  71. package/dist/version.js +1 -1
  72. package/package.json +2 -2
@@ -0,0 +1,1102 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.normalizeFinishReason = normalizeFinishReason;
4
+ exports.stringifyToolArguments = stringifyToolArguments;
5
+ exports.stringifyToolContent = stringifyToolContent;
6
+ exports.normalizeMessages = normalizeMessages;
7
+ exports.normalizeToolDefinitions = normalizeToolDefinitions;
8
+ exports.normalizeDocuments = normalizeDocuments;
9
+ /**
10
+ * Shared canonical v1 message, tool definition, document, and finish-reason
11
+ * normalizer for all TypeScript SDK callers and framework integrations
12
+ * (manual, vercel-ai, openai-agents, langchain, mastra, coding-agent).
13
+ */
14
+ const serialize_1 = require("./serialize");
15
+ const tool_call_id_1 = require("./tool-call-id");
16
+ const tool_result_1 = require("./tool-result");
17
+ const DATA_URI_RE = /^\s*data:([^;,]*)(?:;[^;,=]+=[^;,]*)*(;base64)?,([\s\S]*)$/i;
18
+ const EXTERNAL_URI_RE = /^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]+$/;
19
+ const RFC3986_DISALLOWED_CHARS_RE = /[\s"<>\\^`{|}\u0000-\u001F\u007F]/;
20
+ function asRecord(value) {
21
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
22
+ return undefined;
23
+ }
24
+ return value;
25
+ }
26
+ function asNonNegativeInt(value) {
27
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
28
+ return undefined;
29
+ }
30
+ return Math.trunc(value);
31
+ }
32
+ function binaryLength(value) {
33
+ if (value === null || typeof value !== "object")
34
+ return undefined;
35
+ if (ArrayBuffer.isView(value))
36
+ return value.byteLength;
37
+ const tag = Object.prototype.toString.call(value);
38
+ if (tag === "[object ArrayBuffer]" || tag === "[object SharedArrayBuffer]") {
39
+ const { byteLength } = value;
40
+ if (typeof byteLength === "number" && Number.isFinite(byteLength)) {
41
+ return byteLength;
42
+ }
43
+ }
44
+ if (typeof Blob !== "undefined" && value instanceof Blob)
45
+ return value.size;
46
+ return undefined;
47
+ }
48
+ function base64ByteLength(encoded) {
49
+ const cleaned = encoded.replace(/\s+/g, "");
50
+ if (!cleaned)
51
+ return 0;
52
+ let padding = 0;
53
+ if (cleaned.endsWith("=="))
54
+ padding = 2;
55
+ else if (cleaned.endsWith("="))
56
+ padding = 1;
57
+ return Math.max(0, Math.floor((cleaned.length * 3) / 4) - padding);
58
+ }
59
+ function utf8ByteLength(text) {
60
+ return new TextEncoder().encode(text).length;
61
+ }
62
+ function parseDataUri(uri) {
63
+ const match = DATA_URI_RE.exec(uri);
64
+ if (!match)
65
+ return null;
66
+ const rawMime = match[1]?.trim();
67
+ const isBase64 = Boolean(match[2]);
68
+ const payload = match[3] ?? "";
69
+ return {
70
+ mimeType: (0, tool_call_id_1.normalizeSingleLineTrimmed)(rawMime),
71
+ byteLength: isBase64 ? base64ByteLength(payload) : utf8ByteLength(payload),
72
+ };
73
+ }
74
+ function isRfc3986SafeHref(href) {
75
+ if (!href || /^\s*data:/i.test(href))
76
+ return false;
77
+ if (RFC3986_DISALLOWED_CHARS_RE.test(href))
78
+ return false;
79
+ // Reject unescaped brackets outside an IPv6 authority host.
80
+ const withoutScheme = href.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:/, "");
81
+ const pathPart = withoutScheme.startsWith("//")
82
+ ? withoutScheme.slice(2).replace(/^[^/?#]*/, "")
83
+ : withoutScheme;
84
+ if (/[[\]]/.test(pathPart))
85
+ return false;
86
+ return true;
87
+ }
88
+ function sanitizeExternalUrl(value) {
89
+ if (value instanceof URL) {
90
+ return isRfc3986SafeHref(value.href) ? value.href : undefined;
91
+ }
92
+ if (typeof value !== "string")
93
+ return undefined;
94
+ const trimmed = value.trim();
95
+ if (!trimmed || /^\s*data:/i.test(trimmed))
96
+ return undefined;
97
+ if (!EXTERNAL_URI_RE.test(trimmed))
98
+ return undefined;
99
+ try {
100
+ // Use percent-encoded href and verify RFC 3986 compatibility for ajv-formats "uri".
101
+ const parsed = new URL(trimmed);
102
+ return isRfc3986SafeHref(parsed.href) ? parsed.href : undefined;
103
+ }
104
+ catch {
105
+ return undefined;
106
+ }
107
+ }
108
+ function normalizeFinishReason(value) {
109
+ if (typeof value !== "string")
110
+ return undefined;
111
+ const normalized = value.trim().toLowerCase().replace(/[\s-]+/g, "_");
112
+ if (!normalized)
113
+ return undefined;
114
+ switch (normalized) {
115
+ case "stop":
116
+ case "end_turn":
117
+ case "completed":
118
+ case "stop_sequence":
119
+ case "complete":
120
+ return "stop";
121
+ case "length":
122
+ case "max_tokens":
123
+ case "max_output_tokens":
124
+ case "incomplete":
125
+ case "token_limit":
126
+ return "length";
127
+ case "tool_calls":
128
+ case "tool_use":
129
+ case "function_call":
130
+ case "function_calls":
131
+ return "tool_calls";
132
+ case "content_filter":
133
+ case "safety":
134
+ case "recitation":
135
+ case "refusal":
136
+ case "guardrail":
137
+ return "content_filter";
138
+ case "error":
139
+ case "failed":
140
+ return "error";
141
+ case "other":
142
+ case "unknown":
143
+ return "other";
144
+ default:
145
+ return "other";
146
+ }
147
+ }
148
+ /**
149
+ * Serialize tool call arguments as a string. Existing strings (even invalid JSON)
150
+ * are preserved verbatim; structured objects are JSON-encoded.
151
+ */
152
+ function stringifyToolArguments(value) {
153
+ if (typeof value === "string")
154
+ return value;
155
+ if (value === undefined || value === null)
156
+ return "{}";
157
+ return (0, serialize_1.stringifyTraceJson)(value) ?? "{}";
158
+ }
159
+ /**
160
+ * Serialize a tool result payload to a canonical string.
161
+ */
162
+ function stringifyToolContent(value) {
163
+ if (value === undefined || value === null)
164
+ return "";
165
+ if (typeof value === "string")
166
+ return value;
167
+ return (0, serialize_1.stringifyTraceJson)(value) ?? "";
168
+ }
169
+ function normalizeImageBlock(record) {
170
+ const block = { type: "image" };
171
+ let mimeType = (0, tool_call_id_1.normalizeSingleLineTrimmed)(record.mime_type ?? record.mimeType ?? record.mediaType ?? record.media_type);
172
+ let byteLength = asNonNegativeInt(record.byte_length ?? record.byteLength);
173
+ let url;
174
+ const nestedImageUrl = asRecord(record.image_url);
175
+ const candidateSources = [
176
+ record.url,
177
+ nestedImageUrl?.url,
178
+ typeof record.image_url === "string" ? record.image_url : undefined,
179
+ record.image,
180
+ record.data,
181
+ record.source,
182
+ ];
183
+ for (const source of candidateSources) {
184
+ if (source === undefined || source === null)
185
+ continue;
186
+ const binLen = binaryLength(source);
187
+ if (binLen !== undefined) {
188
+ byteLength ??= binLen;
189
+ continue;
190
+ }
191
+ if (source instanceof URL) {
192
+ const safe = sanitizeExternalUrl(source);
193
+ if (safe)
194
+ url ??= safe;
195
+ else {
196
+ const parsed = parseDataUri(source.href);
197
+ if (parsed) {
198
+ mimeType ??= parsed.mimeType;
199
+ byteLength ??= parsed.byteLength;
200
+ }
201
+ }
202
+ continue;
203
+ }
204
+ if (typeof source === "string") {
205
+ const parsed = parseDataUri(source);
206
+ if (parsed) {
207
+ mimeType ??= parsed.mimeType;
208
+ byteLength ??= parsed.byteLength;
209
+ continue;
210
+ }
211
+ const safe = sanitizeExternalUrl(source);
212
+ if (safe) {
213
+ url ??= safe;
214
+ }
215
+ else if (source.length > 0) {
216
+ // Raw base64 or inline bytes string: measure size, never emit raw bytes.
217
+ byteLength ??= base64ByteLength(source);
218
+ }
219
+ continue;
220
+ }
221
+ const sourceRecord = asRecord(source);
222
+ if (sourceRecord) {
223
+ mimeType ??= (0, tool_call_id_1.normalizeSingleLineTrimmed)(sourceRecord.media_type ??
224
+ sourceRecord.mime_type ??
225
+ sourceRecord.mimeType);
226
+ if (typeof sourceRecord.url === "string") {
227
+ const safe = sanitizeExternalUrl(sourceRecord.url);
228
+ if (safe)
229
+ url ??= safe;
230
+ else {
231
+ const parsed = parseDataUri(sourceRecord.url);
232
+ if (parsed) {
233
+ mimeType ??= parsed.mimeType;
234
+ byteLength ??= parsed.byteLength;
235
+ }
236
+ }
237
+ }
238
+ if (typeof sourceRecord.data === "string") {
239
+ byteLength ??= base64ByteLength(sourceRecord.data);
240
+ }
241
+ else {
242
+ const nestedBin = binaryLength(sourceRecord.data);
243
+ if (nestedBin !== undefined)
244
+ byteLength ??= nestedBin;
245
+ }
246
+ }
247
+ }
248
+ if (mimeType)
249
+ block.mime_type = mimeType;
250
+ if (url)
251
+ block.url = url;
252
+ if (byteLength !== undefined)
253
+ block.byte_length = byteLength;
254
+ return block;
255
+ }
256
+ function normalizeMediaBlock(type, record) {
257
+ const block = { type };
258
+ let mimeType = (0, tool_call_id_1.normalizeSingleLineTrimmed)(record.mime_type ?? record.mimeType ?? record.mediaType ?? record.media_type);
259
+ let filename = (0, tool_call_id_1.normalizeSingleLineTrimmed)(record.filename ?? record.file_name ?? record.name);
260
+ let byteLength = asNonNegativeInt(record.byte_length ?? record.byteLength);
261
+ const nestedAudio = asRecord(record.input_audio);
262
+ const nestedFile = asRecord(record.file);
263
+ if (nestedAudio) {
264
+ const format = (0, tool_call_id_1.normalizeSingleLineTrimmed)(nestedAudio.format);
265
+ if (format && !mimeType)
266
+ mimeType = `audio/${format}`;
267
+ if (typeof nestedAudio.data === "string") {
268
+ byteLength ??= base64ByteLength(nestedAudio.data);
269
+ }
270
+ }
271
+ if (nestedFile) {
272
+ filename ??= (0, tool_call_id_1.normalizeSingleLineTrimmed)(nestedFile.filename ?? nestedFile.file_name ?? nestedFile.name);
273
+ if (typeof nestedFile.file_data === "string") {
274
+ const parsed = parseDataUri(nestedFile.file_data);
275
+ if (parsed) {
276
+ mimeType ??= parsed.mimeType;
277
+ byteLength ??= parsed.byteLength;
278
+ }
279
+ else {
280
+ byteLength ??= base64ByteLength(nestedFile.file_data);
281
+ }
282
+ }
283
+ }
284
+ for (const dataField of [record.data, record.file_data, record.audio]) {
285
+ if (dataField === undefined || dataField === null)
286
+ continue;
287
+ const binLen = binaryLength(dataField);
288
+ if (binLen !== undefined) {
289
+ byteLength ??= binLen;
290
+ }
291
+ else if (typeof dataField === "string" && dataField.length > 0) {
292
+ const parsed = parseDataUri(dataField);
293
+ if (parsed) {
294
+ mimeType ??= parsed.mimeType;
295
+ byteLength ??= parsed.byteLength;
296
+ }
297
+ else if (!sanitizeExternalUrl(dataField)) {
298
+ byteLength ??= base64ByteLength(dataField);
299
+ }
300
+ }
301
+ }
302
+ if (mimeType)
303
+ block.mime_type = mimeType;
304
+ if (filename)
305
+ block.filename = filename;
306
+ if (byteLength !== undefined)
307
+ block.byte_length = byteLength;
308
+ return block;
309
+ }
310
+ function normalizeContentBlock(part) {
311
+ if (typeof part === "string") {
312
+ return { type: "text", text: part };
313
+ }
314
+ const record = asRecord(part);
315
+ if (!record)
316
+ return null;
317
+ const type = typeof record.type === "string" ? record.type : undefined;
318
+ switch (type) {
319
+ case "text":
320
+ case "input_text":
321
+ case "output_text": {
322
+ const text = typeof record.text === "string"
323
+ ? record.text
324
+ : typeof record.content === "string"
325
+ ? record.content
326
+ : "";
327
+ return { type: "text", text };
328
+ }
329
+ case "refusal": {
330
+ const text = typeof record.refusal === "string"
331
+ ? record.refusal
332
+ : typeof record.text === "string"
333
+ ? record.text
334
+ : "";
335
+ return { type: "text", text };
336
+ }
337
+ case "reasoning":
338
+ case "reasoning_text":
339
+ case "reasoning_content":
340
+ case "summary_text":
341
+ case "thinking": {
342
+ const nestedReasoning = asRecord(record.reasoning_content);
343
+ const text = typeof record.text === "string"
344
+ ? record.text
345
+ : typeof record.thinking === "string"
346
+ ? record.thinking
347
+ : typeof record.reasoning === "string"
348
+ ? record.reasoning
349
+ : typeof nestedReasoning?.text === "string"
350
+ ? nestedReasoning.text
351
+ : extractReasoningItemText(record);
352
+ return { type: "reasoning", text };
353
+ }
354
+ case "redacted_thinking":
355
+ return { type: "reasoning", text: "[redacted]" };
356
+ case "image":
357
+ case "image_url":
358
+ case "input_image":
359
+ return normalizeImageBlock(record);
360
+ case "file":
361
+ case "input_file":
362
+ case "document":
363
+ return normalizeMediaBlock("file", record);
364
+ case "audio":
365
+ case "input_audio":
366
+ return normalizeMediaBlock("audio", record);
367
+ default: {
368
+ if (typeof record.text === "string") {
369
+ return { type: "text", text: record.text };
370
+ }
371
+ if (typeof record.thinking === "string") {
372
+ return { type: "reasoning", text: record.thinking };
373
+ }
374
+ const serialized = (0, serialize_1.stringifyTraceJson)(record);
375
+ return serialized ? { type: "text", text: serialized } : null;
376
+ }
377
+ }
378
+ }
379
+ function extractReasoningItemText(record) {
380
+ const parts = [];
381
+ if (typeof record.text === "string" && record.text)
382
+ parts.push(record.text);
383
+ if (typeof record.thinking === "string" && record.thinking) {
384
+ parts.push(record.thinking);
385
+ }
386
+ if (Array.isArray(record.summary)) {
387
+ for (const entry of record.summary) {
388
+ const r = asRecord(entry);
389
+ if (r && typeof r.text === "string" && r.text)
390
+ parts.push(r.text);
391
+ }
392
+ }
393
+ if (Array.isArray(record.content)) {
394
+ for (const entry of record.content) {
395
+ if (typeof entry === "string" && entry) {
396
+ parts.push(entry);
397
+ continue;
398
+ }
399
+ const r = asRecord(entry);
400
+ if (r && typeof r.text === "string" && r.text)
401
+ parts.push(r.text);
402
+ }
403
+ }
404
+ return parts.join("\n");
405
+ }
406
+ function collapseContentBlocks(blocks) {
407
+ if (blocks.length === 0)
408
+ return "";
409
+ if (blocks.every((block) => block.type === "text")) {
410
+ return blocks
411
+ .map((block) => block.text)
412
+ .join("");
413
+ }
414
+ return blocks;
415
+ }
416
+ function normalizeMessageContent(value) {
417
+ if (value === undefined || value === null)
418
+ return "";
419
+ if (typeof value === "string")
420
+ return value;
421
+ if (Array.isArray(value)) {
422
+ const blocks = [];
423
+ for (const part of value) {
424
+ const block = normalizeContentBlock(part);
425
+ if (block)
426
+ blocks.push(block);
427
+ }
428
+ return collapseContentBlocks(blocks);
429
+ }
430
+ return (0, serialize_1.stringifyTraceJson)(value) ?? "";
431
+ }
432
+ function normalizeToolCallEntry(entry, fallbackIndex, knownToolNames) {
433
+ const record = asRecord(entry);
434
+ if (!record)
435
+ return null;
436
+ const fn = asRecord(record.function);
437
+ const rawName = fn?.name ?? record.toolName ?? record.tool_name ?? record.name;
438
+ const name = (0, tool_call_id_1.normalizeSingleLineTrimmed)(rawName) ?? "unknown_tool";
439
+ const rawId = (0, tool_call_id_1.resolveToolCallIdFromSources)([record], [
440
+ "call_id",
441
+ "callId",
442
+ "tool_call_id",
443
+ "toolCallId",
444
+ "id",
445
+ ]) ?? `call_${fallbackIndex}`;
446
+ const rawArgs = fn?.arguments ?? record.arguments ?? record.args ?? record.input;
447
+ const call = {
448
+ id: rawId,
449
+ name,
450
+ arguments: stringifyToolArguments(rawArgs),
451
+ };
452
+ if (name !== "unknown_tool") {
453
+ knownToolNames.set(rawId, name);
454
+ }
455
+ return call;
456
+ }
457
+ function rawToolCallsFromRecord(record, kwargs) {
458
+ if (Array.isArray(record.tool_calls) && record.tool_calls.length > 0) {
459
+ return record.tool_calls;
460
+ }
461
+ if (Array.isArray(record.toolCalls) && record.toolCalls.length > 0) {
462
+ return record.toolCalls;
463
+ }
464
+ const additional = asRecord(record.additional_kwargs);
465
+ if (Array.isArray(additional?.tool_calls) && additional.tool_calls.length > 0) {
466
+ return additional.tool_calls;
467
+ }
468
+ if (kwargs) {
469
+ if (Array.isArray(kwargs.tool_calls) && kwargs.tool_calls.length > 0) {
470
+ return kwargs.tool_calls;
471
+ }
472
+ if (Array.isArray(kwargs.toolCalls) && kwargs.toolCalls.length > 0) {
473
+ return kwargs.toolCalls;
474
+ }
475
+ const kwAdditional = asRecord(kwargs.additional_kwargs);
476
+ if (Array.isArray(kwAdditional?.tool_calls) &&
477
+ kwAdditional.tool_calls.length > 0) {
478
+ return kwAdditional.tool_calls;
479
+ }
480
+ }
481
+ return undefined;
482
+ }
483
+ function roleFromClassName(name) {
484
+ const lower = name.toLowerCase();
485
+ if (lower.includes("human") || lower === "user")
486
+ return "user";
487
+ if (lower.includes("ai") || lower.includes("assistant"))
488
+ return "assistant";
489
+ if (lower.includes("system"))
490
+ return "system";
491
+ if (lower.includes("developer"))
492
+ return "developer";
493
+ if (lower.includes("tool") || lower.includes("function"))
494
+ return "tool";
495
+ return undefined;
496
+ }
497
+ function resolveMessageRole(record, kwargs) {
498
+ const candidates = [
499
+ record.role,
500
+ kwargs?.role,
501
+ record.type,
502
+ record._type,
503
+ typeof record.getType === "function"
504
+ ? record.getType()
505
+ : undefined,
506
+ kwargs?.type,
507
+ kwargs?._type,
508
+ ];
509
+ for (const candidate of candidates) {
510
+ if (typeof candidate !== "string" || !candidate.trim())
511
+ continue;
512
+ const lower = candidate.trim().toLowerCase();
513
+ switch (lower) {
514
+ case "system":
515
+ return "system";
516
+ case "developer":
517
+ return "developer";
518
+ case "user":
519
+ case "human":
520
+ return "user";
521
+ case "assistant":
522
+ case "ai":
523
+ return "assistant";
524
+ case "tool":
525
+ case "function":
526
+ return "tool";
527
+ default: {
528
+ // Ignore envelope types like "message" when role wasn't found yet.
529
+ if (lower === "message")
530
+ continue;
531
+ const fromName = roleFromClassName(lower);
532
+ if (fromName)
533
+ return fromName;
534
+ }
535
+ }
536
+ }
537
+ if (Array.isArray(record.id) && record.id.length > 0) {
538
+ const fromId = roleFromClassName(String(record.id[record.id.length - 1]));
539
+ if (fromId)
540
+ return fromId;
541
+ }
542
+ const ctorName = typeof record.constructor === "function" &&
543
+ typeof record.constructor.name === "string"
544
+ ? record.constructor.name
545
+ : undefined;
546
+ if (ctorName && ctorName !== "Object") {
547
+ return roleFromClassName(ctorName);
548
+ }
549
+ return undefined;
550
+ }
551
+ function unwrapAiSdkToolOutput(rawOutput) {
552
+ const record = asRecord(rawOutput);
553
+ if (!record || typeof record.type !== "string") {
554
+ return { value: rawOutput, explicitError: false };
555
+ }
556
+ switch (record.type) {
557
+ case "text":
558
+ case "json":
559
+ return { value: record.value, explicitError: false };
560
+ case "error-text":
561
+ case "error-json":
562
+ return { value: record.value, explicitError: true };
563
+ case "execution-denied":
564
+ return {
565
+ value: typeof record.reason === "string" && record.reason.trim()
566
+ ? record.reason
567
+ : "Tool execution denied",
568
+ explicitError: true,
569
+ };
570
+ case "content": {
571
+ if (Array.isArray(record.value)) {
572
+ const text = record.value
573
+ .map((item) => {
574
+ const r = asRecord(item);
575
+ return r && typeof r.text === "string" ? r.text : "";
576
+ })
577
+ .filter(Boolean)
578
+ .join("\n");
579
+ return {
580
+ value: text || record.value,
581
+ explicitError: false,
582
+ };
583
+ }
584
+ return { value: record.value, explicitError: false };
585
+ }
586
+ default:
587
+ return { value: rawOutput, explicitError: false };
588
+ }
589
+ }
590
+ function buildToolResultMessage(options, knownToolNames, ctx) {
591
+ const toolCallId = (0, tool_call_id_1.normalizeToolCallId)(options.toolCallId) ?? `call_${options.fallbackIndex}`;
592
+ const name = (0, tool_call_id_1.normalizeSingleLineTrimmed)(options.name) ??
593
+ knownToolNames.get(toolCallId) ??
594
+ (0, tool_call_id_1.normalizeSingleLineTrimmed)(ctx.toolNamesByCallId?.get(toolCallId)) ??
595
+ "unknown_tool";
596
+ const unwrapped = unwrapAiSdkToolOutput(options.rawContent);
597
+ const isError = options.explicitError ||
598
+ unwrapped.explicitError ||
599
+ Boolean(ctx.failedToolCallIds?.has(toolCallId)) ||
600
+ (0, tool_result_1.toolResultError)(unwrapped.value) !== null ||
601
+ (0, tool_result_1.toolResultError)(options.rawContent) !== null;
602
+ const content = stringifyToolContent(unwrapped.value);
603
+ return {
604
+ role: "tool",
605
+ tool_call_id: toolCallId,
606
+ name,
607
+ content,
608
+ is_error: isError,
609
+ };
610
+ }
611
+ function appendContentBlock(target, block) {
612
+ if (target.content === undefined || target.content === "") {
613
+ target.content = block.type === "text" ? block.text : [block];
614
+ return;
615
+ }
616
+ if (typeof target.content === "string") {
617
+ if (block.type === "text") {
618
+ target.content = `${target.content}${block.text}`;
619
+ return;
620
+ }
621
+ target.content = [{ type: "text", text: target.content }, block];
622
+ return;
623
+ }
624
+ target.content.push(block);
625
+ }
626
+ function mergeAssistantInto(target, incoming) {
627
+ if (incoming.content !== undefined && incoming.content !== "") {
628
+ if (typeof incoming.content === "string") {
629
+ appendContentBlock(target, { type: "text", text: incoming.content });
630
+ }
631
+ else {
632
+ for (const block of incoming.content) {
633
+ appendContentBlock(target, block);
634
+ }
635
+ }
636
+ }
637
+ if (incoming.tool_calls && incoming.tool_calls.length > 0) {
638
+ target.tool_calls = [...(target.tool_calls ?? []), ...incoming.tool_calls];
639
+ }
640
+ if (target.content === undefined) {
641
+ target.content = "";
642
+ }
643
+ }
644
+ function isAssistantMergeCandidate(item) {
645
+ const record = asRecord(item);
646
+ if (!record)
647
+ return false;
648
+ return (record.type === "reasoning" ||
649
+ record.type === "function_call" ||
650
+ (record.type === "message" && record.role === "assistant"));
651
+ }
652
+ /**
653
+ * Normalize a list of framework/provider messages or Responses items into
654
+ * canonical v1 `CanonicalMessage[]` strictly matching `trace-contract.v1.schema.json`.
655
+ */
656
+ function normalizeMessages(rawMessages, options = {}) {
657
+ const result = [];
658
+ const knownToolNames = new Map();
659
+ let callCounter = 0;
660
+ // Track whether the previous emitted message came from OpenAI Responses items
661
+ // so consecutive reasoning + message + function_call items merge into one assistant turn.
662
+ let lastWasResponsesAssistant = false;
663
+ const emitAssistant = (msg, mergeable) => {
664
+ if (mergeable &&
665
+ lastWasResponsesAssistant &&
666
+ result.length > 0 &&
667
+ result[result.length - 1].role === "assistant") {
668
+ mergeAssistantInto(result[result.length - 1], msg);
669
+ return;
670
+ }
671
+ // Schema requires AssistantMessage to have at least content or tool_calls.
672
+ if (msg.content === undefined && !msg.tool_calls?.length) {
673
+ msg.content = "";
674
+ }
675
+ // Always include content: "" when only tool_calls are present for clarity.
676
+ if (msg.content === undefined) {
677
+ msg.content = "";
678
+ }
679
+ result.push(msg);
680
+ lastWasResponsesAssistant = mergeable;
681
+ };
682
+ const fallbackRole = options?.defaultRole ?? "user";
683
+ const processItem = (item, depth) => {
684
+ if (depth > 4 || item === undefined || item === null)
685
+ return;
686
+ if (typeof item === "string") {
687
+ if (fallbackRole === "assistant") {
688
+ emitAssistant({ role: "assistant", content: item }, false);
689
+ }
690
+ else {
691
+ lastWasResponsesAssistant = false;
692
+ result.push({ role: fallbackRole, content: item });
693
+ }
694
+ return;
695
+ }
696
+ const record = asRecord(item);
697
+ if (!record) {
698
+ const text = (0, serialize_1.stringifyTraceJson)(item) ?? "";
699
+ if (fallbackRole === "assistant") {
700
+ emitAssistant({ role: "assistant", content: text }, false);
701
+ }
702
+ else {
703
+ lastWasResponsesAssistant = false;
704
+ result.push({ role: fallbackRole, content: text });
705
+ }
706
+ return;
707
+ }
708
+ // ChatCompletions wrapper: `{ choices: [{ message: { ... } }] }`
709
+ if (Array.isArray(record.choices) && !record.role && !record.type) {
710
+ for (const choice of record.choices) {
711
+ const choiceRec = asRecord(choice);
712
+ if (!choiceRec)
713
+ continue;
714
+ if (choiceRec.message)
715
+ processItem(choiceRec.message, depth + 1);
716
+ }
717
+ return;
718
+ }
719
+ // Streamed Responses wrapper: `{ output: [...] }`
720
+ if (Array.isArray(record.output) &&
721
+ !record.role &&
722
+ record.type !== "function_call_output" &&
723
+ record.type !== "function_call_result") {
724
+ for (const nested of record.output) {
725
+ processItem(nested, depth + 1);
726
+ }
727
+ return;
728
+ }
729
+ // OpenAI Responses reasoning item
730
+ if (record.type === "reasoning") {
731
+ const text = extractReasoningItemText(record);
732
+ if (text) {
733
+ emitAssistant({ role: "assistant", content: [{ type: "reasoning", text }] }, true);
734
+ }
735
+ else if (typeof record.encrypted_content === "string") {
736
+ emitAssistant({ role: "assistant", content: [{ type: "reasoning", text: "[encrypted]" }] }, true);
737
+ }
738
+ return;
739
+ }
740
+ // OpenAI Responses function_call item
741
+ if (record.type === "function_call") {
742
+ callCounter += 1;
743
+ const call = normalizeToolCallEntry(record, callCounter, knownToolNames);
744
+ if (call) {
745
+ emitAssistant({ role: "assistant", content: "", tool_calls: [call] }, true);
746
+ }
747
+ return;
748
+ }
749
+ // OpenAI Responses function_call_output / function_call_result item
750
+ if (record.type === "function_call_output" ||
751
+ record.type === "function_call_result") {
752
+ lastWasResponsesAssistant = false;
753
+ callCounter += 1;
754
+ const toolCallId = (0, tool_call_id_1.resolveToolCallIdFromSources)([record], tool_call_id_1.OPENAI_TOOL_CALL_ID_KEYS);
755
+ const rawOutput = "output" in record
756
+ ? record.output
757
+ : "content" in record
758
+ ? record.content
759
+ : record.result;
760
+ const explicitError = record.is_error === true ||
761
+ record.isError === true ||
762
+ record.status === "error" ||
763
+ record.status === "failed";
764
+ result.push(buildToolResultMessage({
765
+ toolCallId,
766
+ name: typeof record.name === "string"
767
+ ? record.name
768
+ : typeof record.tool_name === "string"
769
+ ? record.tool_name
770
+ : undefined,
771
+ rawContent: rawOutput,
772
+ explicitError,
773
+ fallbackIndex: callCounter,
774
+ }, knownToolNames, options));
775
+ return;
776
+ }
777
+ // Serialized LangChain message: unwrap kwargs
778
+ const kwargs = asRecord(record.kwargs);
779
+ const role = resolveMessageRole(record, kwargs) ?? fallbackRole;
780
+ const rawContent = "content" in record
781
+ ? record.content
782
+ : kwargs && "content" in kwargs
783
+ ? kwargs.content
784
+ : typeof record.text === "string"
785
+ ? record.text
786
+ : "";
787
+ if (role === "tool") {
788
+ lastWasResponsesAssistant = false;
789
+ // AI SDK packs N tool-result parts into one `role: "tool"` message.
790
+ if (Array.isArray(rawContent)) {
791
+ const toolResultParts = rawContent.filter((part) => {
792
+ const p = asRecord(part);
793
+ return (p !== undefined &&
794
+ (p.type === "tool-result" ||
795
+ p.type === "tool-error" ||
796
+ p.type === "tool_result"));
797
+ });
798
+ if (toolResultParts.length > 0) {
799
+ for (const part of toolResultParts) {
800
+ const p = asRecord(part);
801
+ callCounter += 1;
802
+ const partCallId = (0, tool_call_id_1.resolveToolCallIdFromSources)([p, record, kwargs], [...tool_call_id_1.OPENAI_TOOL_CALL_ID_KEYS, "tool_use_id"]);
803
+ const partName = typeof p.toolName === "string"
804
+ ? p.toolName
805
+ : typeof p.tool_name === "string"
806
+ ? p.tool_name
807
+ : typeof p.name === "string"
808
+ ? p.name
809
+ : typeof record.name === "string"
810
+ ? record.name
811
+ : typeof kwargs?.name === "string"
812
+ ? kwargs.name
813
+ : undefined;
814
+ const partOutput = p.type === "tool-error"
815
+ ? (p.error ?? p.output ?? p.result ?? p.content)
816
+ : "output" in p
817
+ ? p.output
818
+ : "result" in p
819
+ ? p.result
820
+ : p.content;
821
+ const partError = p.type === "tool-error" ||
822
+ p.isError === true ||
823
+ p.is_error === true ||
824
+ p.status === "error" ||
825
+ p.status === "failed";
826
+ result.push(buildToolResultMessage({
827
+ toolCallId: partCallId,
828
+ name: partName,
829
+ rawContent: partOutput,
830
+ explicitError: partError,
831
+ fallbackIndex: callCounter,
832
+ }, knownToolNames, options));
833
+ }
834
+ return;
835
+ }
836
+ }
837
+ // Single 1-to-1 tool message (canonical, LangChain ToolMessage, OpenAI Chat)
838
+ callCounter += 1;
839
+ const toolCallId = (0, tool_call_id_1.resolveToolCallIdFromSources)([record, kwargs], tool_call_id_1.OPENAI_TOOL_CALL_ID_KEYS);
840
+ const name = typeof record.name === "string"
841
+ ? record.name
842
+ : typeof kwargs?.name === "string"
843
+ ? kwargs.name
844
+ : typeof record.tool_name === "string"
845
+ ? record.tool_name
846
+ : undefined;
847
+ const status = record.status ?? kwargs?.status;
848
+ const explicitError = record.is_error === true ||
849
+ record.isError === true ||
850
+ kwargs?.is_error === true ||
851
+ kwargs?.isError === true ||
852
+ status === "error" ||
853
+ status === "failed";
854
+ result.push(buildToolResultMessage({
855
+ toolCallId,
856
+ name,
857
+ rawContent,
858
+ explicitError,
859
+ fallbackIndex: callCounter,
860
+ }, knownToolNames, options));
861
+ return;
862
+ }
863
+ if (role === "assistant") {
864
+ const blocks = [];
865
+ const extractedToolCalls = [];
866
+ // Explicit reasoning field (e.g. Mastra `{ reasoning, text }` or OpenAI)
867
+ if (typeof record.reasoning === "string" && record.reasoning) {
868
+ blocks.push({ type: "reasoning", text: record.reasoning });
869
+ }
870
+ else if (typeof record.reasoningText === "string" &&
871
+ record.reasoningText) {
872
+ blocks.push({ type: "reasoning", text: record.reasoningText });
873
+ }
874
+ if (Array.isArray(rawContent)) {
875
+ for (const part of rawContent) {
876
+ const p = asRecord(part);
877
+ if (p &&
878
+ (p.type === "tool-call" ||
879
+ p.type === "tool_use" ||
880
+ p.type === "function_call")) {
881
+ callCounter += 1;
882
+ const call = normalizeToolCallEntry(p, callCounter, knownToolNames);
883
+ if (call)
884
+ extractedToolCalls.push(call);
885
+ continue;
886
+ }
887
+ // AI SDK step content arrays include executed tool-result / tool-error
888
+ // entries beside tool-call parts; do not serialize them as assistant text.
889
+ if (p &&
890
+ (p.type === "tool-result" ||
891
+ p.type === "tool-error" ||
892
+ p.type === "tool_result")) {
893
+ continue;
894
+ }
895
+ const block = normalizeContentBlock(part);
896
+ if (block)
897
+ blocks.push(block);
898
+ }
899
+ }
900
+ else if (typeof rawContent === "string") {
901
+ if (rawContent.length > 0 || blocks.length === 0) {
902
+ blocks.push({ type: "text", text: rawContent });
903
+ }
904
+ }
905
+ else if (rawContent !== undefined && rawContent !== null) {
906
+ const serialized = (0, serialize_1.stringifyTraceJson)(rawContent);
907
+ if (serialized !== undefined) {
908
+ blocks.push({ type: "text", text: serialized });
909
+ }
910
+ }
911
+ const rawCalls = rawToolCallsFromRecord(record, kwargs);
912
+ if (rawCalls) {
913
+ for (const entry of rawCalls) {
914
+ callCounter += 1;
915
+ const call = normalizeToolCallEntry(entry, callCounter, knownToolNames);
916
+ if (call)
917
+ extractedToolCalls.push(call);
918
+ }
919
+ }
920
+ const content = collapseContentBlocks(blocks);
921
+ const assistantMsg = {
922
+ role: "assistant",
923
+ content,
924
+ ...(extractedToolCalls.length > 0
925
+ ? { tool_calls: extractedToolCalls }
926
+ : {}),
927
+ };
928
+ emitAssistant(assistantMsg, isAssistantMergeCandidate(record));
929
+ return;
930
+ }
931
+ // system | developer | user
932
+ lastWasResponsesAssistant = false;
933
+ // Anthropic user messages can contain tool_result blocks — split them cleanly.
934
+ if (role === "user" && Array.isArray(rawContent)) {
935
+ const nonToolParts = [];
936
+ const toolResultParts = [];
937
+ for (const part of rawContent) {
938
+ const p = asRecord(part);
939
+ if (p && (p.type === "tool_result" || p.type === "tool-result")) {
940
+ toolResultParts.push(p);
941
+ }
942
+ else {
943
+ nonToolParts.push(part);
944
+ }
945
+ }
946
+ if (toolResultParts.length > 0) {
947
+ if (nonToolParts.length > 0) {
948
+ result.push({
949
+ role: "user",
950
+ content: normalizeMessageContent(nonToolParts),
951
+ });
952
+ }
953
+ for (const p of toolResultParts) {
954
+ callCounter += 1;
955
+ const partCallId = (0, tool_call_id_1.resolveToolCallIdFromSources)([p], ["tool_use_id", ...tool_call_id_1.OPENAI_TOOL_CALL_ID_KEYS]);
956
+ result.push(buildToolResultMessage({
957
+ toolCallId: partCallId,
958
+ name: typeof p.toolName === "string"
959
+ ? p.toolName
960
+ : typeof p.name === "string"
961
+ ? p.name
962
+ : undefined,
963
+ rawContent: "output" in p ? p.output : p.content,
964
+ explicitError: p.is_error === true || p.isError === true,
965
+ fallbackIndex: callCounter,
966
+ }, knownToolNames, options));
967
+ }
968
+ return;
969
+ }
970
+ }
971
+ result.push({
972
+ role,
973
+ content: normalizeMessageContent(rawContent),
974
+ });
975
+ };
976
+ for (const item of rawMessages) {
977
+ processItem(item, 0);
978
+ }
979
+ return result;
980
+ }
981
+ function asPlainJsonObject(value) {
982
+ const record = asRecord(value);
983
+ if (!record)
984
+ return undefined;
985
+ // Avoid attaching live schema objects (e.g. Zod v3/v4) that aren't plain JSON schemas.
986
+ if (("_def" in record || "_zod" in record) &&
987
+ typeof record.parse === "function") {
988
+ return undefined;
989
+ }
990
+ if ("jsonSchema" in record && asRecord(record.jsonSchema)) {
991
+ return record.jsonSchema;
992
+ }
993
+ return record;
994
+ }
995
+ /**
996
+ * Normalize framework tool definitions into canonical v1 `ToolDefinition[]`.
997
+ */
998
+ function normalizeToolDefinitions(rawTools) {
999
+ if (rawTools == null)
1000
+ return undefined;
1001
+ const entries = [];
1002
+ if (Array.isArray(rawTools)) {
1003
+ for (const entry of rawTools)
1004
+ entries.push({ raw: entry });
1005
+ }
1006
+ else {
1007
+ const map = asRecord(rawTools);
1008
+ if (!map)
1009
+ return undefined;
1010
+ for (const [key, value] of Object.entries(map)) {
1011
+ entries.push({ fallbackName: key, raw: value });
1012
+ }
1013
+ }
1014
+ const normalized = [];
1015
+ for (const { fallbackName, raw } of entries) {
1016
+ const record = asRecord(raw);
1017
+ if (!record) {
1018
+ const name = (0, tool_call_id_1.normalizeSingleLineTrimmed)(fallbackName);
1019
+ if (name)
1020
+ normalized.push({ name });
1021
+ continue;
1022
+ }
1023
+ const fn = asRecord(record.function);
1024
+ const name = (0, tool_call_id_1.normalizeSingleLineTrimmed)(fn?.name ?? record.name ?? record.toolName ?? fallbackName);
1025
+ if (!name)
1026
+ continue;
1027
+ const description = typeof fn?.description === "string"
1028
+ ? fn.description
1029
+ : typeof record.description === "string"
1030
+ ? record.description
1031
+ : undefined;
1032
+ const parameters = asPlainJsonObject(fn?.parameters ??
1033
+ record.parameters ??
1034
+ record.inputSchema ??
1035
+ record.input_schema);
1036
+ const def = { name };
1037
+ if (description !== undefined)
1038
+ def.description = description;
1039
+ if (parameters !== undefined)
1040
+ def.parameters = parameters;
1041
+ normalized.push(def);
1042
+ }
1043
+ return normalized.length > 0 ? normalized : undefined;
1044
+ }
1045
+ /**
1046
+ * Normalize retrieval / reranker documents into canonical v1 `CanonicalDocument[]`.
1047
+ */
1048
+ function normalizeDocuments(rawDocs) {
1049
+ if (!Array.isArray(rawDocs))
1050
+ return undefined;
1051
+ const normalized = [];
1052
+ for (const entry of rawDocs) {
1053
+ if (typeof entry === "string") {
1054
+ normalized.push({ content: entry });
1055
+ continue;
1056
+ }
1057
+ const record = asRecord(entry);
1058
+ if (!record)
1059
+ continue;
1060
+ const kwargs = asRecord(record.kwargs);
1061
+ const nestedDoc = asRecord(record.document);
1062
+ const rawContent = record.content ??
1063
+ record.pageContent ??
1064
+ record.page_content ??
1065
+ record.text ??
1066
+ kwargs?.pageContent ??
1067
+ kwargs?.page_content ??
1068
+ kwargs?.content ??
1069
+ nestedDoc?.text ??
1070
+ nestedDoc?.content;
1071
+ const content = typeof rawContent === "string"
1072
+ ? rawContent
1073
+ : rawContent !== undefined && rawContent !== null
1074
+ ? ((0, serialize_1.stringifyTraceJson)(rawContent) ?? "")
1075
+ : "";
1076
+ const metadata = asRecord(record.metadata ?? kwargs?.metadata ?? nestedDoc?.metadata);
1077
+ const rawId = record.id ?? kwargs?.id ?? nestedDoc?.id ?? metadata?.id;
1078
+ const id = typeof rawId === "string" && rawId.trim().length > 0
1079
+ ? rawId.trim()
1080
+ : typeof rawId === "number" && Number.isFinite(rawId)
1081
+ ? String(rawId)
1082
+ : undefined;
1083
+ const rawScore = record.score ??
1084
+ record.relevance_score ??
1085
+ record.relevanceScore ??
1086
+ metadata?.score ??
1087
+ metadata?.relevance_score;
1088
+ const score = typeof rawScore === "number" && Number.isFinite(rawScore)
1089
+ ? rawScore
1090
+ : undefined;
1091
+ const doc = { content };
1092
+ if (id !== undefined)
1093
+ doc.id = id;
1094
+ if (score !== undefined)
1095
+ doc.score = score;
1096
+ if (metadata !== undefined)
1097
+ doc.metadata = metadata;
1098
+ normalized.push(doc);
1099
+ }
1100
+ return normalized.length > 0 ? normalized : undefined;
1101
+ }
1102
+ //# sourceMappingURL=messages.js.map