@uselemma/tracing 7.15.3 → 7.16.1
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/dist/client.d.ts +129 -56
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +597 -200
- package/dist/client.js.map +1 -1
- package/dist/coding-agent.d.ts +4 -1
- package/dist/coding-agent.d.ts.map +1 -1
- package/dist/coding-agent.js +73 -31
- package/dist/coding-agent.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +16 -1
- package/dist/index.js.map +1 -1
- package/dist/integration-client.d.ts +1 -1
- package/dist/integration-client.d.ts.map +1 -1
- package/dist/integration-client.js.map +1 -1
- package/dist/langchain.d.ts +15 -17
- package/dist/langchain.d.ts.map +1 -1
- package/dist/langchain.js +327 -87
- package/dist/langchain.js.map +1 -1
- package/dist/mastra-message-enrichment.d.ts +14 -0
- package/dist/mastra-message-enrichment.d.ts.map +1 -0
- package/dist/mastra-message-enrichment.js +124 -0
- package/dist/mastra-message-enrichment.js.map +1 -0
- package/dist/mastra.d.ts.map +1 -1
- package/dist/mastra.js +238 -24
- package/dist/mastra.js.map +1 -1
- package/dist/messages.d.ts +84 -0
- package/dist/messages.d.ts.map +1 -0
- package/dist/messages.js +1102 -0
- package/dist/messages.js.map +1 -0
- package/dist/openai-agents-containers.d.ts +1 -0
- package/dist/openai-agents-containers.d.ts.map +1 -1
- package/dist/openai-agents-containers.js.map +1 -1
- package/dist/openai-agents-generation.d.ts +8 -5
- package/dist/openai-agents-generation.d.ts.map +1 -1
- package/dist/openai-agents-generation.js +92 -44
- package/dist/openai-agents-generation.js.map +1 -1
- package/dist/openai-agents-tool-calls.d.ts +24 -0
- package/dist/openai-agents-tool-calls.d.ts.map +1 -0
- package/dist/openai-agents-tool-calls.js +207 -0
- package/dist/openai-agents-tool-calls.js.map +1 -0
- package/dist/openai-agents.d.ts +2 -7
- package/dist/openai-agents.d.ts.map +1 -1
- package/dist/openai-agents.js +259 -20
- package/dist/openai-agents.js.map +1 -1
- package/dist/payload.d.ts +30 -0
- package/dist/payload.d.ts.map +1 -0
- package/dist/payload.js +413 -0
- package/dist/payload.js.map +1 -0
- package/dist/release.d.ts +12 -0
- package/dist/release.d.ts.map +1 -1
- package/dist/release.js +41 -7
- package/dist/release.js.map +1 -1
- package/dist/span-tree.d.ts +15 -0
- package/dist/span-tree.d.ts.map +1 -0
- package/dist/span-tree.js +143 -0
- package/dist/span-tree.js.map +1 -0
- package/dist/tool-call-id.d.ts +14 -0
- package/dist/tool-call-id.d.ts.map +1 -0
- package/dist/tool-call-id.js +56 -0
- package/dist/tool-call-id.js.map +1 -0
- package/dist/turn.d.ts +25 -1
- package/dist/turn.d.ts.map +1 -1
- package/dist/turn.js +97 -14
- package/dist/turn.js.map +1 -1
- package/dist/usage.d.ts +5 -3
- package/dist/usage.d.ts.map +1 -1
- package/dist/usage.js +38 -35
- package/dist/usage.js.map +1 -1
- package/dist/vercel-ai-events.d.ts +46 -9
- package/dist/vercel-ai-events.d.ts.map +1 -1
- package/dist/vercel-ai-events.js +81 -7
- package/dist/vercel-ai-events.js.map +1 -1
- package/dist/vercel-ai-run.d.ts +7 -0
- package/dist/vercel-ai-run.d.ts.map +1 -1
- package/dist/vercel-ai-run.js +191 -47
- package/dist/vercel-ai-run.js.map +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +2 -2
package/dist/client.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.Lemma = exports.TraceHandle = exports.TraceContext = exports.NoopSpanHandle = exports.SpanHandle = exports.toWireTokenUsage = exports.normalizeTokenUsage = exports.attachResultUsage = void 0;
|
|
3
|
+
exports.Lemma = exports.TraceHandle = exports.TraceContext = exports.NoopSpanHandle = exports.SpanHandle = exports.TRACE_CONTRACT_SCHEMA_VERSION = exports.TRUNCATION_MARKER_KEY = exports.STRUCTURAL_PAYLOAD_KEYS = exports.DEDUP_MARKER_KEY = exports.normalizeToolDefinitions = exports.normalizeMessages = exports.normalizeFinishReason = exports.normalizeDocuments = exports.toWireTokenUsage = exports.normalizeTokenUsage = exports.attachResultUsage = exports.normalizeToolCallId = void 0;
|
|
4
4
|
exports.startBackgroundTrace = startBackgroundTrace;
|
|
5
5
|
const debug_delivery_1 = require("./debug-delivery");
|
|
6
6
|
const debug_mode_1 = require("./debug-mode");
|
|
@@ -8,27 +8,120 @@ const delivery_1 = require("./delivery");
|
|
|
8
8
|
const dropped_traces_1 = require("./dropped-traces");
|
|
9
9
|
const env_1 = require("./env");
|
|
10
10
|
const error_message_1 = require("./error-message");
|
|
11
|
+
const span_tree_1 = require("./span-tree");
|
|
12
|
+
const messages_1 = require("./messages");
|
|
13
|
+
const payload_1 = require("./payload");
|
|
11
14
|
const release_1 = require("./release");
|
|
12
15
|
const serialize_1 = require("./serialize");
|
|
13
16
|
const stream_result_1 = require("./stream-result");
|
|
17
|
+
const tool_call_id_1 = require("./tool-call-id");
|
|
14
18
|
const usage_1 = require("./usage");
|
|
15
19
|
const version_1 = require("./version");
|
|
20
|
+
var tool_call_id_2 = require("./tool-call-id");
|
|
21
|
+
Object.defineProperty(exports, "normalizeToolCallId", { enumerable: true, get: function () { return tool_call_id_2.normalizeToolCallId; } });
|
|
16
22
|
var usage_2 = require("./usage");
|
|
17
23
|
Object.defineProperty(exports, "attachResultUsage", { enumerable: true, get: function () { return usage_2.attachResultUsage; } });
|
|
18
24
|
Object.defineProperty(exports, "normalizeTokenUsage", { enumerable: true, get: function () { return usage_2.normalizeTokenUsage; } });
|
|
19
25
|
Object.defineProperty(exports, "toWireTokenUsage", { enumerable: true, get: function () { return usage_2.toWireTokenUsage; } });
|
|
26
|
+
var messages_2 = require("./messages");
|
|
27
|
+
Object.defineProperty(exports, "normalizeDocuments", { enumerable: true, get: function () { return messages_2.normalizeDocuments; } });
|
|
28
|
+
Object.defineProperty(exports, "normalizeFinishReason", { enumerable: true, get: function () { return messages_2.normalizeFinishReason; } });
|
|
29
|
+
Object.defineProperty(exports, "normalizeMessages", { enumerable: true, get: function () { return messages_2.normalizeMessages; } });
|
|
30
|
+
Object.defineProperty(exports, "normalizeToolDefinitions", { enumerable: true, get: function () { return messages_2.normalizeToolDefinitions; } });
|
|
31
|
+
var payload_2 = require("./payload");
|
|
32
|
+
Object.defineProperty(exports, "DEDUP_MARKER_KEY", { enumerable: true, get: function () { return payload_2.DEDUP_MARKER_KEY; } });
|
|
33
|
+
Object.defineProperty(exports, "STRUCTURAL_PAYLOAD_KEYS", { enumerable: true, get: function () { return payload_2.STRUCTURAL_PAYLOAD_KEYS; } });
|
|
34
|
+
Object.defineProperty(exports, "TRUNCATION_MARKER_KEY", { enumerable: true, get: function () { return payload_2.TRUNCATION_MARKER_KEY; } });
|
|
35
|
+
exports.TRACE_CONTRACT_SCHEMA_VERSION = 1;
|
|
20
36
|
const SDK_LANGUAGE = "typescript";
|
|
21
37
|
const SDK_INTEGRATION_ATTR = "lemma.sdk.integration";
|
|
22
38
|
const SDK_LANGUAGE_ATTR = "lemma.sdk.language";
|
|
39
|
+
const FINISH_REASON_ERROR_MESSAGE = 'Model call ended with finishReason "error"';
|
|
23
40
|
function required(value, envName) {
|
|
24
41
|
if (value?.trim())
|
|
25
42
|
return value.trim();
|
|
26
43
|
throw new Error(`@uselemma/tracing: Missing ${envName}`);
|
|
27
44
|
}
|
|
45
|
+
function nonBlankString(value) {
|
|
46
|
+
if (typeof value !== "string")
|
|
47
|
+
return undefined;
|
|
48
|
+
return value.trim().length > 0 ? value : undefined;
|
|
49
|
+
}
|
|
50
|
+
function nonNegativeNumber(value) {
|
|
51
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
|
|
52
|
+
return undefined;
|
|
53
|
+
}
|
|
54
|
+
return value;
|
|
55
|
+
}
|
|
56
|
+
function asPlainObject(value) {
|
|
57
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
58
|
+
return undefined;
|
|
59
|
+
}
|
|
60
|
+
return value;
|
|
61
|
+
}
|
|
62
|
+
const RFC3339_TIMESTAMP_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/i;
|
|
28
63
|
function iso(value) {
|
|
29
64
|
if (value == null)
|
|
30
65
|
return value;
|
|
31
|
-
|
|
66
|
+
if (value instanceof Date) {
|
|
67
|
+
return Number.isNaN(value.getTime()) ? undefined : value.toISOString();
|
|
68
|
+
}
|
|
69
|
+
const trimmed = value.trim();
|
|
70
|
+
if (!trimmed)
|
|
71
|
+
return undefined;
|
|
72
|
+
const parsed = new Date(trimmed);
|
|
73
|
+
if (Number.isNaN(parsed.getTime()))
|
|
74
|
+
return undefined;
|
|
75
|
+
return RFC3339_TIMESTAMP_RE.test(trimmed) ? trimmed : parsed.toISOString();
|
|
76
|
+
}
|
|
77
|
+
function firstTrimmed(...values) {
|
|
78
|
+
for (const value of values) {
|
|
79
|
+
const normalized = (0, tool_call_id_1.normalizeSingleLineTrimmed)(value);
|
|
80
|
+
if (normalized !== undefined)
|
|
81
|
+
return normalized;
|
|
82
|
+
}
|
|
83
|
+
return undefined;
|
|
84
|
+
}
|
|
85
|
+
function firstNonBlank(...values) {
|
|
86
|
+
for (const value of values) {
|
|
87
|
+
const normalized = nonBlankString(value);
|
|
88
|
+
if (normalized !== undefined)
|
|
89
|
+
return normalized;
|
|
90
|
+
}
|
|
91
|
+
return undefined;
|
|
92
|
+
}
|
|
93
|
+
function cloneForTransform(value, seen = new WeakMap()) {
|
|
94
|
+
if (value === null || typeof value !== "object")
|
|
95
|
+
return value;
|
|
96
|
+
if (value instanceof Date ||
|
|
97
|
+
value instanceof RegExp ||
|
|
98
|
+
value instanceof URL ||
|
|
99
|
+
value instanceof Error ||
|
|
100
|
+
ArrayBuffer.isView(value)) {
|
|
101
|
+
return value;
|
|
102
|
+
}
|
|
103
|
+
const tag = Object.prototype.toString.call(value);
|
|
104
|
+
if (tag === "[object ArrayBuffer]" || tag === "[object SharedArrayBuffer]") {
|
|
105
|
+
return value;
|
|
106
|
+
}
|
|
107
|
+
if (typeof Blob !== "undefined" && value instanceof Blob)
|
|
108
|
+
return value;
|
|
109
|
+
if (seen.has(value))
|
|
110
|
+
return seen.get(value);
|
|
111
|
+
if (Array.isArray(value)) {
|
|
112
|
+
const copy = [];
|
|
113
|
+
seen.set(value, copy);
|
|
114
|
+
for (let i = 0; i < value.length; i += 1) {
|
|
115
|
+
copy[i] = cloneForTransform(value[i], seen);
|
|
116
|
+
}
|
|
117
|
+
return copy;
|
|
118
|
+
}
|
|
119
|
+
const copy = {};
|
|
120
|
+
seen.set(value, copy);
|
|
121
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
122
|
+
copy[key] = cloneForTransform(entry, seen);
|
|
123
|
+
}
|
|
124
|
+
return copy;
|
|
32
125
|
}
|
|
33
126
|
function timestampMs(value) {
|
|
34
127
|
if (value == null)
|
|
@@ -53,123 +146,255 @@ function summarizeSpanForDebug(span, index) {
|
|
|
53
146
|
status: span.status,
|
|
54
147
|
durationMs: span.duration_ms,
|
|
55
148
|
model: span.model,
|
|
56
|
-
hasInput: span.input !== undefined,
|
|
57
|
-
hasOutput: span.output !== undefined,
|
|
149
|
+
hasInput: span.input !== undefined || span.llm_input_messages !== undefined,
|
|
150
|
+
hasOutput: span.output !== undefined || span.llm_output_messages !== undefined,
|
|
58
151
|
hasError: Boolean(span.error),
|
|
59
152
|
}).filter(([, value]) => value !== undefined));
|
|
60
153
|
}
|
|
61
|
-
function serializeAttribute(value) {
|
|
62
|
-
if (value == null)
|
|
63
|
-
return value;
|
|
64
|
-
if (typeof value === "string" ||
|
|
65
|
-
typeof value === "number" ||
|
|
66
|
-
typeof value === "boolean")
|
|
67
|
-
return value;
|
|
68
|
-
return (0, serialize_1.stringifyTraceJson)(value);
|
|
69
|
-
}
|
|
70
|
-
function addDefined(attributes, key, value) {
|
|
71
|
-
if (value !== undefined)
|
|
72
|
-
attributes[key] = value;
|
|
73
|
-
}
|
|
74
|
-
function flattenMessage(attributes, prefix, message) {
|
|
75
|
-
if (message && typeof message === "object" && !Array.isArray(message)) {
|
|
76
|
-
for (const [key, value] of Object.entries(message)) {
|
|
77
|
-
addDefined(attributes, `${prefix}.message.${key}`, serializeAttribute(value));
|
|
78
|
-
}
|
|
79
|
-
return;
|
|
80
|
-
}
|
|
81
|
-
addDefined(attributes, `${prefix}.message.content`, serializeAttribute(message));
|
|
82
|
-
}
|
|
83
|
-
function flattenDocument(attributes, prefix, document) {
|
|
84
|
-
if (document && typeof document === "object" && !Array.isArray(document)) {
|
|
85
|
-
for (const [key, value] of Object.entries(document)) {
|
|
86
|
-
addDefined(attributes, `${prefix}.document.${key}`, serializeAttribute(value));
|
|
87
|
-
}
|
|
88
|
-
return;
|
|
89
|
-
}
|
|
90
|
-
addDefined(attributes, `${prefix}.document.content`, serializeAttribute(document));
|
|
91
|
-
}
|
|
92
154
|
function resolveUsage(options) {
|
|
93
155
|
return (0, usage_1.normalizeTokenUsage)(options.usage);
|
|
94
156
|
}
|
|
95
|
-
function contractAttributes(options) {
|
|
96
|
-
const attributes = {};
|
|
97
|
-
addDefined(attributes, "input.mime_type", options.inputMimeType);
|
|
98
|
-
addDefined(attributes, "output.mime_type", options.outputMimeType);
|
|
99
|
-
const modelIdentity = options.llmModelName ?? options.model;
|
|
100
|
-
addDefined(attributes, "llm.model_name", modelIdentity);
|
|
101
|
-
addDefined(attributes, "gen_ai.request.model", modelIdentity);
|
|
102
|
-
addDefined(attributes, "ai.model.id", modelIdentity);
|
|
103
|
-
addDefined(attributes, "llm.provider", options.llmProvider);
|
|
104
|
-
// llm.system from explicit llmSystem; gen_ai.system from llmSystem or llmProvider.
|
|
105
|
-
addDefined(attributes, "llm.system", options.llmSystem);
|
|
106
|
-
addDefined(attributes, "gen_ai.system", options.llmSystem ?? options.llmProvider);
|
|
107
|
-
Object.assign(attributes, (0, usage_1.tokenUsageAttributes)(resolveUsage(options)));
|
|
108
|
-
addDefined(attributes, "llm.invocation_parameters", serializeAttribute(options.llmInvocationParameters));
|
|
109
|
-
addDefined(attributes, "llm.tools", serializeAttribute(options.llmTools));
|
|
110
|
-
addDefined(attributes, "llm.prompt_template.template", options.llmPromptTemplate);
|
|
111
|
-
addDefined(attributes, "llm.prompt_template.variables", serializeAttribute(options.llmPromptTemplateVariables));
|
|
112
|
-
addDefined(attributes, "llm.prompt_template.version", options.llmPromptTemplateVersion);
|
|
113
|
-
addDefined(attributes, "tool.description", options.toolDescription);
|
|
114
|
-
addDefined(attributes, "tool.parameters", serializeAttribute(options.toolParameters));
|
|
115
|
-
if (options.userFacingMessage !== undefined) {
|
|
116
|
-
attributes["lemma.tool.kind"] = "user_message";
|
|
117
|
-
attributes["lemma.tool.message"] = options.userFacingMessage;
|
|
118
|
-
}
|
|
119
|
-
addDefined(attributes, "embedding.model_name", options.embeddingModelName);
|
|
120
|
-
addDefined(attributes, "embedding.invocation_parameters", serializeAttribute(options.embeddingInvocationParameters));
|
|
121
|
-
addDefined(attributes, "embedding.embeddings", serializeAttribute(options.embeddingEmbeddings));
|
|
122
|
-
addDefined(attributes, "reranker.model_name", options.rerankerModelName);
|
|
123
|
-
options.llmInputMessages?.forEach((message, index) => {
|
|
124
|
-
flattenMessage(attributes, `llm.input_messages.${index}`, message);
|
|
125
|
-
});
|
|
126
|
-
options.llmOutputMessages?.forEach((message, index) => {
|
|
127
|
-
flattenMessage(attributes, `llm.output_messages.${index}`, message);
|
|
128
|
-
});
|
|
129
|
-
options.rerankerInputDocuments?.forEach((document, index) => {
|
|
130
|
-
flattenDocument(attributes, `reranker.input_documents.${index}`, document);
|
|
131
|
-
});
|
|
132
|
-
options.rerankerOutputDocuments?.forEach((document, index) => {
|
|
133
|
-
flattenDocument(attributes, `reranker.output_documents.${index}`, document);
|
|
134
|
-
});
|
|
135
|
-
return attributes;
|
|
136
|
-
}
|
|
137
157
|
function spanAttributes(options) {
|
|
138
158
|
const callerAttributes = options.attributes ?? {};
|
|
139
|
-
const integration = typeof callerAttributes[SDK_INTEGRATION_ATTR] === "string"
|
|
159
|
+
const integration = typeof callerAttributes[SDK_INTEGRATION_ATTR] === "string" &&
|
|
160
|
+
callerAttributes[SDK_INTEGRATION_ATTR].trim()
|
|
140
161
|
? callerAttributes[SDK_INTEGRATION_ATTR]
|
|
141
162
|
: "manual";
|
|
142
|
-
|
|
163
|
+
return {
|
|
143
164
|
...callerAttributes,
|
|
144
|
-
...contractAttributes(options),
|
|
145
165
|
[SDK_LANGUAGE_ATTR]: SDK_LANGUAGE,
|
|
146
166
|
[SDK_INTEGRATION_ATTR]: integration,
|
|
147
167
|
};
|
|
148
|
-
|
|
168
|
+
}
|
|
169
|
+
function isSameJson(a, b) {
|
|
170
|
+
if (a === b)
|
|
171
|
+
return true;
|
|
172
|
+
if (a === undefined || b === undefined)
|
|
173
|
+
return false;
|
|
174
|
+
return (0, serialize_1.stringifyTraceJson)(a) === (0, serialize_1.stringifyTraceJson)(b);
|
|
175
|
+
}
|
|
176
|
+
function isRedundantGenerationInput(rawInput, rawMessages, canonicalMessages) {
|
|
177
|
+
if (rawInput === undefined)
|
|
178
|
+
return true;
|
|
179
|
+
if (!canonicalMessages)
|
|
180
|
+
return false;
|
|
181
|
+
if (isSameJson(rawInput, rawMessages) || isSameJson(rawInput, canonicalMessages)) {
|
|
182
|
+
return true;
|
|
183
|
+
}
|
|
184
|
+
if (canonicalMessages.length === 1 &&
|
|
185
|
+
canonicalMessages[0].role === "user" &&
|
|
186
|
+
typeof canonicalMessages[0].content === "string" &&
|
|
187
|
+
rawInput === canonicalMessages[0].content) {
|
|
188
|
+
return true;
|
|
189
|
+
}
|
|
190
|
+
return false;
|
|
191
|
+
}
|
|
192
|
+
function isRedundantGenerationOutput(rawOutput, rawMessages, canonicalMessages) {
|
|
193
|
+
if (rawOutput === undefined)
|
|
194
|
+
return true;
|
|
195
|
+
if (!canonicalMessages)
|
|
196
|
+
return false;
|
|
197
|
+
if (isSameJson(rawOutput, rawMessages) ||
|
|
198
|
+
isSameJson(rawOutput, canonicalMessages)) {
|
|
199
|
+
return true;
|
|
200
|
+
}
|
|
201
|
+
if (canonicalMessages.length === 1 &&
|
|
202
|
+
canonicalMessages[0].role === "assistant" &&
|
|
203
|
+
!canonicalMessages[0].tool_calls?.length &&
|
|
204
|
+
typeof canonicalMessages[0].content === "string" &&
|
|
205
|
+
rawOutput === canonicalMessages[0].content) {
|
|
206
|
+
return true;
|
|
207
|
+
}
|
|
208
|
+
return false;
|
|
149
209
|
}
|
|
150
210
|
function normalizeSpan(options, fallbackType) {
|
|
211
|
+
const type = options.type ?? fallbackType;
|
|
151
212
|
const startedAt = options.startedAt === undefined ? new Date() : options.startedAt;
|
|
152
213
|
const endedAt = options.endedAt === undefined ? new Date() : options.endedAt;
|
|
153
|
-
const
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
214
|
+
const finishReason = type === "generation"
|
|
215
|
+
? (0, messages_1.normalizeFinishReason)(options.finishReason)
|
|
216
|
+
: undefined;
|
|
217
|
+
const rawError = (0, error_message_1.failureMessage)(options.error) ?? undefined;
|
|
218
|
+
const error = rawError ??
|
|
219
|
+
(finishReason === "error" ? FINISH_REASON_ERROR_MESSAGE : undefined);
|
|
220
|
+
const status = error
|
|
221
|
+
? "ERROR"
|
|
222
|
+
: options.status === "OK" || options.status === "ERROR"
|
|
223
|
+
? options.status
|
|
224
|
+
: undefined;
|
|
225
|
+
const isError = status === "ERROR" || error !== undefined;
|
|
226
|
+
const span = {
|
|
227
|
+
name: nonBlankString(options.name) ?? type,
|
|
228
|
+
type,
|
|
163
229
|
attributes: spanAttributes(options),
|
|
164
|
-
...(startedAt === null ? {} : { started_at: iso(startedAt) }),
|
|
165
|
-
...(endedAt === null ? {} : { ended_at: iso(endedAt) }),
|
|
166
|
-
duration_ms: options.durationMs,
|
|
167
|
-
status: options.status ?? (error ? "ERROR" : undefined),
|
|
168
|
-
error,
|
|
169
|
-
model: options.model,
|
|
170
|
-
tool_name: options.toolName,
|
|
171
|
-
...(usage ? { usage } : {}),
|
|
172
230
|
};
|
|
231
|
+
const id = nonBlankString(options.id);
|
|
232
|
+
if (id !== undefined)
|
|
233
|
+
span.id = id;
|
|
234
|
+
const rawParentId = options.parentId !== undefined ? options.parentId : options.parentSpanId;
|
|
235
|
+
if (rawParentId === null) {
|
|
236
|
+
span.parent_id = null;
|
|
237
|
+
}
|
|
238
|
+
else {
|
|
239
|
+
const parentId = nonBlankString(rawParentId);
|
|
240
|
+
if (parentId !== undefined)
|
|
241
|
+
span.parent_id = parentId;
|
|
242
|
+
}
|
|
243
|
+
if (startedAt !== null && startedAt !== undefined) {
|
|
244
|
+
const startedIso = iso(startedAt);
|
|
245
|
+
if (startedIso)
|
|
246
|
+
span.started_at = startedIso;
|
|
247
|
+
}
|
|
248
|
+
if (endedAt !== null && endedAt !== undefined) {
|
|
249
|
+
const endedIso = iso(endedAt);
|
|
250
|
+
if (endedIso)
|
|
251
|
+
span.ended_at = endedIso;
|
|
252
|
+
}
|
|
253
|
+
const durationMs = nonNegativeNumber(options.durationMs);
|
|
254
|
+
if (durationMs !== undefined)
|
|
255
|
+
span.duration_ms = durationMs;
|
|
256
|
+
if (status !== undefined)
|
|
257
|
+
span.status = status;
|
|
258
|
+
if (error !== undefined)
|
|
259
|
+
span.error = error;
|
|
260
|
+
const inputMimeType = (0, tool_call_id_1.normalizeSingleLineTrimmed)(options.inputMimeType);
|
|
261
|
+
if (inputMimeType !== undefined)
|
|
262
|
+
span.input_mime_type = inputMimeType;
|
|
263
|
+
const outputMimeType = (0, tool_call_id_1.normalizeSingleLineTrimmed)(options.outputMimeType);
|
|
264
|
+
if (outputMimeType !== undefined)
|
|
265
|
+
span.output_mime_type = outputMimeType;
|
|
266
|
+
const metadata = asPlainObject(options.metadata);
|
|
267
|
+
if (metadata !== undefined)
|
|
268
|
+
span.metadata = metadata;
|
|
269
|
+
const provider = firstTrimmed(options.provider, options.llmProvider, options.llmSystem);
|
|
270
|
+
const usage = (0, usage_1.toWireTokenUsage)(resolveUsage(options));
|
|
271
|
+
if (type === "generation") {
|
|
272
|
+
const model = firstNonBlank(options.model, options.llmModelName);
|
|
273
|
+
if (model !== undefined)
|
|
274
|
+
span.model = model;
|
|
275
|
+
if (provider !== undefined)
|
|
276
|
+
span.provider = provider;
|
|
277
|
+
const invocationParameters = asPlainObject(options.invocationParameters ?? options.llmInvocationParameters);
|
|
278
|
+
if (invocationParameters !== undefined) {
|
|
279
|
+
span.invocation_parameters = invocationParameters;
|
|
280
|
+
}
|
|
281
|
+
const tools = (0, messages_1.normalizeToolDefinitions)(options.tools ?? options.llmTools);
|
|
282
|
+
if (tools !== undefined)
|
|
283
|
+
span.tools = tools;
|
|
284
|
+
const llmInputMessages = Array.isArray(options.llmInputMessages)
|
|
285
|
+
? (0, messages_1.normalizeMessages)(options.llmInputMessages)
|
|
286
|
+
: undefined;
|
|
287
|
+
if (llmInputMessages !== undefined) {
|
|
288
|
+
span.llm_input_messages = llmInputMessages;
|
|
289
|
+
}
|
|
290
|
+
const llmOutputMessages = Array.isArray(options.llmOutputMessages)
|
|
291
|
+
? (0, messages_1.normalizeMessages)(options.llmOutputMessages, {
|
|
292
|
+
defaultRole: "assistant",
|
|
293
|
+
})
|
|
294
|
+
: undefined;
|
|
295
|
+
if (llmOutputMessages !== undefined) {
|
|
296
|
+
span.llm_output_messages = llmOutputMessages;
|
|
297
|
+
}
|
|
298
|
+
if (usage !== undefined)
|
|
299
|
+
span.usage = usage;
|
|
300
|
+
if (finishReason !== undefined)
|
|
301
|
+
span.finish_reason = finishReason;
|
|
302
|
+
const ttft = nonNegativeNumber(options.timeToFirstTokenMs);
|
|
303
|
+
if (ttft !== undefined) {
|
|
304
|
+
const bound = durationMs ??
|
|
305
|
+
(span.started_at !== undefined && span.ended_at !== undefined
|
|
306
|
+
? elapsedMs(span.started_at, span.ended_at)
|
|
307
|
+
: undefined);
|
|
308
|
+
span.time_to_first_token_ms =
|
|
309
|
+
bound !== undefined ? Math.min(ttft, bound) : ttft;
|
|
310
|
+
}
|
|
311
|
+
const promptTemplate = options.promptTemplate ?? options.llmPromptTemplate;
|
|
312
|
+
if (typeof promptTemplate === "string") {
|
|
313
|
+
span.prompt_template = promptTemplate;
|
|
314
|
+
}
|
|
315
|
+
const promptTemplateVariables = asPlainObject(options.promptTemplateVariables ?? options.llmPromptTemplateVariables);
|
|
316
|
+
if (promptTemplateVariables !== undefined) {
|
|
317
|
+
span.prompt_template_variables = promptTemplateVariables;
|
|
318
|
+
}
|
|
319
|
+
const promptTemplateVersion = (0, tool_call_id_1.normalizeSingleLineTrimmed)(options.promptTemplateVersion ?? options.llmPromptTemplateVersion);
|
|
320
|
+
if (promptTemplateVersion !== undefined) {
|
|
321
|
+
span.prompt_template_version = promptTemplateVersion;
|
|
322
|
+
}
|
|
323
|
+
if (!isRedundantGenerationInput(options.input, options.llmInputMessages, llmInputMessages)) {
|
|
324
|
+
span.input = options.input;
|
|
325
|
+
}
|
|
326
|
+
if (!isError &&
|
|
327
|
+
!isRedundantGenerationOutput(options.output, options.llmOutputMessages, llmOutputMessages)) {
|
|
328
|
+
span.output = options.output;
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
else {
|
|
332
|
+
if (options.input !== undefined)
|
|
333
|
+
span.input = options.input;
|
|
334
|
+
if (!isError && options.output !== undefined)
|
|
335
|
+
span.output = options.output;
|
|
336
|
+
if (type === "tool") {
|
|
337
|
+
const toolName = (0, tool_call_id_1.normalizeSingleLineTrimmed)(options.toolName);
|
|
338
|
+
if (toolName !== undefined)
|
|
339
|
+
span.tool_name = toolName;
|
|
340
|
+
const toolCallId = (0, tool_call_id_1.normalizeToolCallId)(options.toolCallId);
|
|
341
|
+
if (toolCallId !== undefined)
|
|
342
|
+
span.tool_call_id = toolCallId;
|
|
343
|
+
if (typeof options.toolDescription === "string") {
|
|
344
|
+
span.tool_description = options.toolDescription;
|
|
345
|
+
}
|
|
346
|
+
const toolParameters = asPlainObject(options.toolParameters);
|
|
347
|
+
if (toolParameters !== undefined)
|
|
348
|
+
span.tool_parameters = toolParameters;
|
|
349
|
+
if (typeof options.userFacingMessage === "string") {
|
|
350
|
+
span.user_facing_message = options.userFacingMessage;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
else if (type === "retrieval") {
|
|
354
|
+
const docs = (0, messages_1.normalizeDocuments)(options.retrievalDocuments);
|
|
355
|
+
if (docs !== undefined)
|
|
356
|
+
span.retrieval_documents = docs;
|
|
357
|
+
}
|
|
358
|
+
else if (type === "embedding") {
|
|
359
|
+
const model = nonBlankString(options.model ?? options.embeddingModelName);
|
|
360
|
+
if (model !== undefined)
|
|
361
|
+
span.model = model;
|
|
362
|
+
if (provider !== undefined)
|
|
363
|
+
span.provider = provider;
|
|
364
|
+
const invocationParameters = asPlainObject(options.invocationParameters ?? options.embeddingInvocationParameters);
|
|
365
|
+
if (invocationParameters !== undefined) {
|
|
366
|
+
span.invocation_parameters = invocationParameters;
|
|
367
|
+
}
|
|
368
|
+
if (usage !== undefined)
|
|
369
|
+
span.usage = usage;
|
|
370
|
+
}
|
|
371
|
+
else if (type === "reranker") {
|
|
372
|
+
const model = nonBlankString(options.model ?? options.rerankerModelName);
|
|
373
|
+
if (model !== undefined)
|
|
374
|
+
span.model = model;
|
|
375
|
+
if (provider !== undefined)
|
|
376
|
+
span.provider = provider;
|
|
377
|
+
const inputDocs = (0, messages_1.normalizeDocuments)(options.rerankerInputDocuments);
|
|
378
|
+
if (inputDocs !== undefined)
|
|
379
|
+
span.reranker_input_documents = inputDocs;
|
|
380
|
+
const outputDocs = (0, messages_1.normalizeDocuments)(options.rerankerOutputDocuments);
|
|
381
|
+
if (outputDocs !== undefined)
|
|
382
|
+
span.reranker_output_documents = outputDocs;
|
|
383
|
+
}
|
|
384
|
+
else if (type === "guardrail") {
|
|
385
|
+
if (typeof options.guardrailTriggered === "boolean") {
|
|
386
|
+
span.guardrail_triggered = options.guardrailTriggered;
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
return span;
|
|
391
|
+
}
|
|
392
|
+
/** Replace all own enumerable properties of `target` with `source`. */
|
|
393
|
+
function replaceSpanPayload(target, source) {
|
|
394
|
+
for (const key of Object.keys(target)) {
|
|
395
|
+
delete target[key];
|
|
396
|
+
}
|
|
397
|
+
Object.assign(target, source);
|
|
173
398
|
}
|
|
174
399
|
/** JSON for a built payload, which is a plain object and always serializes. */
|
|
175
400
|
function payloadBody(payload) {
|
|
@@ -178,6 +403,16 @@ function payloadBody(payload) {
|
|
|
178
403
|
throw new Error("trace payload is empty");
|
|
179
404
|
return body;
|
|
180
405
|
}
|
|
406
|
+
async function gzipString(body) {
|
|
407
|
+
const bytes = new TextEncoder().encode(body);
|
|
408
|
+
if (typeof CompressionStream === "undefined") {
|
|
409
|
+
throw new Error("@uselemma/tracing: gzip compression requires CompressionStream support in this runtime");
|
|
410
|
+
}
|
|
411
|
+
const stream = new Blob([bytes])
|
|
412
|
+
.stream()
|
|
413
|
+
.pipeThrough(new CompressionStream("gzip"));
|
|
414
|
+
return new Uint8Array(await new Response(stream).arrayBuffer());
|
|
415
|
+
}
|
|
181
416
|
function warnNoop(message) {
|
|
182
417
|
console.warn(`@uselemma/tracing: ${message}`);
|
|
183
418
|
}
|
|
@@ -223,16 +458,24 @@ class SpanHandle {
|
|
|
223
458
|
if (this.ended)
|
|
224
459
|
return;
|
|
225
460
|
this.ended = true;
|
|
226
|
-
|
|
461
|
+
const next = normalizeSpan({
|
|
227
462
|
...this.options,
|
|
228
463
|
...options,
|
|
229
464
|
id: this.id,
|
|
230
465
|
startedAt: this.options.startedAt,
|
|
231
466
|
endedAt: options.endedAt ?? new Date(),
|
|
232
|
-
//
|
|
233
|
-
//
|
|
234
|
-
|
|
235
|
-
|
|
467
|
+
// Prefer a resolved response model passed to end() over start-time model,
|
|
468
|
+
// without letting undefined/blank erase start-time model or letting
|
|
469
|
+
// deprecated llmModelName override an explicit model.
|
|
470
|
+
model: firstNonBlank(options.model, this.options.model, options.llmModelName, this.options.llmModelName),
|
|
471
|
+
// Prefer end-time provider when non-blank, otherwise keep start-time provider.
|
|
472
|
+
provider: firstTrimmed(options.provider, options.llmProvider, options.llmSystem, this.options.provider, this.options.llmProvider, this.options.llmSystem),
|
|
473
|
+
// Keep a start-time toolCallId when end() omits or blanks it; fill in
|
|
474
|
+
// at end when unset (e.g. OpenAI Agents recovering call_id on span end).
|
|
475
|
+
toolCallId: (0, tool_call_id_1.normalizeToolCallId)(this.options.toolCallId) ??
|
|
476
|
+
(0, tool_call_id_1.normalizeToolCallId)(options.toolCallId),
|
|
477
|
+
}, this.options.type ?? "span");
|
|
478
|
+
replaceSpanPayload(this.payload, next);
|
|
236
479
|
this.trace.spanEnded(this.payload);
|
|
237
480
|
this.trace.changed();
|
|
238
481
|
}
|
|
@@ -254,7 +497,7 @@ class SpanHandle {
|
|
|
254
497
|
/**
|
|
255
498
|
* Fill input or output after end() when a child model call finishes later.
|
|
256
499
|
* Input is written only while this span still has none. Output is replaced
|
|
257
|
-
* when the span did not carry its own output.
|
|
500
|
+
* when the span did not carry its own output and did not fail.
|
|
258
501
|
*/
|
|
259
502
|
fillContainerIo(input, output, ownOutput) {
|
|
260
503
|
if (!this.ended)
|
|
@@ -262,7 +505,8 @@ class SpanHandle {
|
|
|
262
505
|
if (this.payload.input === undefined && input !== undefined) {
|
|
263
506
|
this.payload.input = input;
|
|
264
507
|
}
|
|
265
|
-
|
|
508
|
+
const isError = this.payload.status === "ERROR" || this.payload.error !== undefined;
|
|
509
|
+
if (!ownOutput && !isError && output !== undefined) {
|
|
266
510
|
this.payload.output = output;
|
|
267
511
|
}
|
|
268
512
|
this.trace.changed();
|
|
@@ -307,6 +551,34 @@ class SpanHandle {
|
|
|
307
551
|
parentId: toolOptions.parentId ?? this.id,
|
|
308
552
|
});
|
|
309
553
|
}
|
|
554
|
+
startRetrieval(options) {
|
|
555
|
+
const retrievalOptions = typeof options === "string" ? { name: options } : options;
|
|
556
|
+
return this.trace.startRetrieval({
|
|
557
|
+
...retrievalOptions,
|
|
558
|
+
parentId: retrievalOptions.parentId ?? this.id,
|
|
559
|
+
});
|
|
560
|
+
}
|
|
561
|
+
startEmbedding(options) {
|
|
562
|
+
const embeddingOptions = typeof options === "string" ? { name: options } : options;
|
|
563
|
+
return this.trace.startEmbedding({
|
|
564
|
+
...embeddingOptions,
|
|
565
|
+
parentId: embeddingOptions.parentId ?? this.id,
|
|
566
|
+
});
|
|
567
|
+
}
|
|
568
|
+
startReranker(options) {
|
|
569
|
+
const rerankerOptions = typeof options === "string" ? { name: options } : options;
|
|
570
|
+
return this.trace.startReranker({
|
|
571
|
+
...rerankerOptions,
|
|
572
|
+
parentId: rerankerOptions.parentId ?? this.id,
|
|
573
|
+
});
|
|
574
|
+
}
|
|
575
|
+
startGuardrail(options) {
|
|
576
|
+
const guardrailOptions = typeof options === "string" ? { name: options } : options;
|
|
577
|
+
return this.trace.startGuardrail({
|
|
578
|
+
...guardrailOptions,
|
|
579
|
+
parentId: guardrailOptions.parentId ?? this.id,
|
|
580
|
+
});
|
|
581
|
+
}
|
|
310
582
|
recordSpan(options) {
|
|
311
583
|
const spanOptions = typeof options === "string" ? { name: options } : options;
|
|
312
584
|
return this.trace.recordSpan({
|
|
@@ -328,6 +600,34 @@ class SpanHandle {
|
|
|
328
600
|
parentId: toolOptions.parentId ?? this.id,
|
|
329
601
|
});
|
|
330
602
|
}
|
|
603
|
+
recordRetrieval(options) {
|
|
604
|
+
const retrievalOptions = typeof options === "string" ? { name: options } : options;
|
|
605
|
+
this.trace.recordRetrieval({
|
|
606
|
+
...retrievalOptions,
|
|
607
|
+
parentId: retrievalOptions.parentId ?? this.id,
|
|
608
|
+
});
|
|
609
|
+
}
|
|
610
|
+
recordEmbedding(options) {
|
|
611
|
+
const embeddingOptions = typeof options === "string" ? { name: options } : options;
|
|
612
|
+
this.trace.recordEmbedding({
|
|
613
|
+
...embeddingOptions,
|
|
614
|
+
parentId: embeddingOptions.parentId ?? this.id,
|
|
615
|
+
});
|
|
616
|
+
}
|
|
617
|
+
recordReranker(options) {
|
|
618
|
+
const rerankerOptions = typeof options === "string" ? { name: options } : options;
|
|
619
|
+
this.trace.recordReranker({
|
|
620
|
+
...rerankerOptions,
|
|
621
|
+
parentId: rerankerOptions.parentId ?? this.id,
|
|
622
|
+
});
|
|
623
|
+
}
|
|
624
|
+
recordGuardrail(options) {
|
|
625
|
+
const guardrailOptions = typeof options === "string" ? { name: options } : options;
|
|
626
|
+
this.trace.recordGuardrail({
|
|
627
|
+
...guardrailOptions,
|
|
628
|
+
parentId: guardrailOptions.parentId ?? this.id,
|
|
629
|
+
});
|
|
630
|
+
}
|
|
331
631
|
span(options) {
|
|
332
632
|
return typeof options === "string"
|
|
333
633
|
? this.startSpan(options)
|
|
@@ -358,11 +658,27 @@ class NoopSpanHandle {
|
|
|
358
658
|
startTool() {
|
|
359
659
|
return this;
|
|
360
660
|
}
|
|
661
|
+
startRetrieval() {
|
|
662
|
+
return this;
|
|
663
|
+
}
|
|
664
|
+
startEmbedding() {
|
|
665
|
+
return this;
|
|
666
|
+
}
|
|
667
|
+
startReranker() {
|
|
668
|
+
return this;
|
|
669
|
+
}
|
|
670
|
+
startGuardrail() {
|
|
671
|
+
return this;
|
|
672
|
+
}
|
|
361
673
|
recordSpan() {
|
|
362
674
|
return this;
|
|
363
675
|
}
|
|
364
676
|
recordGeneration() { }
|
|
365
677
|
recordTool() { }
|
|
678
|
+
recordRetrieval() { }
|
|
679
|
+
recordEmbedding() { }
|
|
680
|
+
recordReranker() { }
|
|
681
|
+
recordGuardrail() { }
|
|
366
682
|
span() {
|
|
367
683
|
return this;
|
|
368
684
|
}
|
|
@@ -377,7 +693,8 @@ class TraceContext {
|
|
|
377
693
|
spanHandles = new Map();
|
|
378
694
|
/** Boxed, so an output set to undefined still counts as set. */
|
|
379
695
|
rootOutput;
|
|
380
|
-
traceError
|
|
696
|
+
traceError;
|
|
697
|
+
traceStatus;
|
|
381
698
|
/** Set by {@link markPayloadFinal}; cleared by the first change after it. */
|
|
382
699
|
sent = false;
|
|
383
700
|
id;
|
|
@@ -389,6 +706,8 @@ class TraceContext {
|
|
|
389
706
|
this.id = this.options.id;
|
|
390
707
|
this.rootOutput =
|
|
391
708
|
options.output === undefined ? undefined : { value: options.output };
|
|
709
|
+
this.traceError = (0, error_message_1.failureMessage)(options.error) ?? undefined;
|
|
710
|
+
this.traceStatus = options.status;
|
|
392
711
|
}
|
|
393
712
|
input(value) {
|
|
394
713
|
this.options.input = value;
|
|
@@ -414,12 +733,20 @@ class TraceContext {
|
|
|
414
733
|
this.options.userId = value;
|
|
415
734
|
this.changed();
|
|
416
735
|
}
|
|
736
|
+
environment(value) {
|
|
737
|
+
this.options.environment = value;
|
|
738
|
+
this.changed();
|
|
739
|
+
}
|
|
740
|
+
tags(value) {
|
|
741
|
+
this.options.tags = value;
|
|
742
|
+
this.changed();
|
|
743
|
+
}
|
|
417
744
|
duration(durationMs) {
|
|
418
745
|
this.options.durationMs = durationMs;
|
|
419
746
|
this.changed();
|
|
420
747
|
}
|
|
421
748
|
fail(error) {
|
|
422
|
-
this.traceError = (0, error_message_1.failureMessage)(error);
|
|
749
|
+
this.traceError = (0, error_message_1.failureMessage)(error) ?? undefined;
|
|
423
750
|
this.changed();
|
|
424
751
|
}
|
|
425
752
|
/** Root identity for a versioned turn context token. */
|
|
@@ -505,6 +832,34 @@ class TraceContext {
|
|
|
505
832
|
this.debugSpan("span recorded", span);
|
|
506
833
|
this.changed();
|
|
507
834
|
}
|
|
835
|
+
recordRetrieval(options) {
|
|
836
|
+
const retrievalOptions = typeof options === "string" ? { name: options } : options;
|
|
837
|
+
const span = normalizeSpan({ ...retrievalOptions, type: "retrieval" }, "retrieval");
|
|
838
|
+
this.spans.push(span);
|
|
839
|
+
this.debugSpan("span recorded", span);
|
|
840
|
+
this.changed();
|
|
841
|
+
}
|
|
842
|
+
recordEmbedding(options) {
|
|
843
|
+
const embeddingOptions = typeof options === "string" ? { name: options } : options;
|
|
844
|
+
const span = normalizeSpan({ ...embeddingOptions, type: "embedding" }, "embedding");
|
|
845
|
+
this.spans.push(span);
|
|
846
|
+
this.debugSpan("span recorded", span);
|
|
847
|
+
this.changed();
|
|
848
|
+
}
|
|
849
|
+
recordReranker(options) {
|
|
850
|
+
const rerankerOptions = typeof options === "string" ? { name: options } : options;
|
|
851
|
+
const span = normalizeSpan({ ...rerankerOptions, type: "reranker" }, "reranker");
|
|
852
|
+
this.spans.push(span);
|
|
853
|
+
this.debugSpan("span recorded", span);
|
|
854
|
+
this.changed();
|
|
855
|
+
}
|
|
856
|
+
recordGuardrail(options) {
|
|
857
|
+
const guardrailOptions = typeof options === "string" ? { name: options } : options;
|
|
858
|
+
const span = normalizeSpan({ ...guardrailOptions, type: "guardrail" }, "guardrail");
|
|
859
|
+
this.spans.push(span);
|
|
860
|
+
this.debugSpan("span recorded", span);
|
|
861
|
+
this.changed();
|
|
862
|
+
}
|
|
508
863
|
startSpan(options) {
|
|
509
864
|
const spanOptions = typeof options === "string" ? { name: options } : options;
|
|
510
865
|
return new SpanHandle(this, {
|
|
@@ -524,6 +879,18 @@ class TraceContext {
|
|
|
524
879
|
startedAt: options.startedAt ?? new Date(),
|
|
525
880
|
});
|
|
526
881
|
}
|
|
882
|
+
startRetrieval(options) {
|
|
883
|
+
return this.startSpan({ ...options, type: "retrieval" });
|
|
884
|
+
}
|
|
885
|
+
startEmbedding(options) {
|
|
886
|
+
return this.startSpan({ ...options, type: "embedding" });
|
|
887
|
+
}
|
|
888
|
+
startReranker(options) {
|
|
889
|
+
return this.startSpan({ ...options, type: "reranker" });
|
|
890
|
+
}
|
|
891
|
+
startGuardrail(options) {
|
|
892
|
+
return this.startSpan({ ...options, type: "guardrail" });
|
|
893
|
+
}
|
|
527
894
|
span(options) {
|
|
528
895
|
return typeof options === "string"
|
|
529
896
|
? this.startSpan(options)
|
|
@@ -549,23 +916,50 @@ class TraceContext {
|
|
|
549
916
|
return stamped;
|
|
550
917
|
}
|
|
551
918
|
toPayload(projectId, startedAt, endedAt) {
|
|
919
|
+
const error = this.traceError;
|
|
920
|
+
const status = error ? "ERROR" : this.traceStatus;
|
|
921
|
+
const isError = status === "ERROR" || error !== undefined;
|
|
922
|
+
const threadId = nonBlankString(this.options.threadId);
|
|
923
|
+
const userId = nonBlankString(this.options.userId);
|
|
924
|
+
const environment = (0, release_1.normalizeEnvironment)(this.options.environment);
|
|
925
|
+
const tags = (0, release_1.normalizeTags)(this.options.tags);
|
|
926
|
+
const durationMs = nonNegativeNumber(this.options.durationMs) ??
|
|
927
|
+
elapsedMs(startedAt, endedAt);
|
|
928
|
+
const metadata = asPlainObject(this.options.metadata);
|
|
929
|
+
const trace = {
|
|
930
|
+
name: nonBlankString(this.options.name) ?? "trace",
|
|
931
|
+
started_at: startedAt.toISOString(),
|
|
932
|
+
ended_at: endedAt.toISOString(),
|
|
933
|
+
spans: (0, span_tree_1.normalizeSpanTree)(this.spans),
|
|
934
|
+
};
|
|
935
|
+
const id = nonBlankString(this.options.id);
|
|
936
|
+
if (id !== undefined)
|
|
937
|
+
trace.id = id;
|
|
938
|
+
if (this.options.input !== undefined)
|
|
939
|
+
trace.input = this.options.input;
|
|
940
|
+
if (!isError && this.rootOutput?.value !== undefined) {
|
|
941
|
+
trace.output = this.rootOutput.value;
|
|
942
|
+
}
|
|
943
|
+
if (status !== undefined)
|
|
944
|
+
trace.status = status;
|
|
945
|
+
if (error !== undefined)
|
|
946
|
+
trace.error = error;
|
|
947
|
+
if (threadId !== undefined)
|
|
948
|
+
trace.thread_id = threadId;
|
|
949
|
+
if (userId !== undefined)
|
|
950
|
+
trace.user_id = userId;
|
|
951
|
+
if (environment !== undefined)
|
|
952
|
+
trace.environment = environment;
|
|
953
|
+
if (tags !== undefined)
|
|
954
|
+
trace.tags = tags;
|
|
955
|
+
if (durationMs !== undefined)
|
|
956
|
+
trace.duration_ms = durationMs;
|
|
957
|
+
if (metadata !== undefined)
|
|
958
|
+
trace.metadata = metadata;
|
|
552
959
|
return {
|
|
960
|
+
schema_version: exports.TRACE_CONTRACT_SCHEMA_VERSION,
|
|
553
961
|
project_id: projectId,
|
|
554
|
-
trace
|
|
555
|
-
id: this.options.id,
|
|
556
|
-
name: this.options.name ?? "trace",
|
|
557
|
-
input: this.options.input,
|
|
558
|
-
output: this.rootOutput?.value,
|
|
559
|
-
metadata: this.options.metadata,
|
|
560
|
-
thread_id: this.options.threadId,
|
|
561
|
-
user_id: this.options.userId,
|
|
562
|
-
started_at: startedAt.toISOString(),
|
|
563
|
-
ended_at: endedAt.toISOString(),
|
|
564
|
-
duration_ms: this.options.durationMs ?? elapsedMs(startedAt, endedAt),
|
|
565
|
-
status: this.traceError ? "ERROR" : undefined,
|
|
566
|
-
error: this.traceError,
|
|
567
|
-
spans: this.spans,
|
|
568
|
-
},
|
|
962
|
+
trace,
|
|
569
963
|
};
|
|
570
964
|
}
|
|
571
965
|
}
|
|
@@ -581,27 +975,14 @@ class TraceHandle extends TraceContext {
|
|
|
581
975
|
super(options);
|
|
582
976
|
this.sendFn = sendFn;
|
|
583
977
|
this.startedAt = startedAt ?? coerceDate(options.startedAt) ?? new Date();
|
|
584
|
-
// A trace is delivered only when it is explicitly ended (`end()`). We
|
|
585
|
-
// deliberately do NOT auto-send on construction or on every recorded span:
|
|
586
|
-
// the ingest API is append-only and treats each submission's spans as new,
|
|
587
|
-
// so streaming partial snapshots re-sends every prior span and accumulates
|
|
588
|
-
// duplicates. Recording mutates the in-memory trace only; the single
|
|
589
|
-
// terminal send from `end()` carries the complete trace.
|
|
590
978
|
}
|
|
591
979
|
end(outputOrOptions) {
|
|
592
|
-
// A second end() returns the first send, so a delivered trace's spans
|
|
593
|
-
// are never sent twice. Only a failed strict send lets end() send again.
|
|
594
980
|
if (this.sending)
|
|
595
981
|
return this.sending;
|
|
596
982
|
this.rootTiming ??= this.applyEnd(outputOrOptions, arguments.length > 0);
|
|
597
983
|
const { startedAt, endedAt } = this.rootTiming;
|
|
598
|
-
// Started now, not on a later tick, so a flush() called right after
|
|
599
|
-
// end() already waits for this send.
|
|
600
984
|
const sending = this.startSend(startedAt, endedAt);
|
|
601
985
|
this.sending = sending;
|
|
602
|
-
// Registered before the caller's own handler, so a caller that catches
|
|
603
|
-
// the failure can call end() again at once. It also observes the
|
|
604
|
-
// rejection, so an end() nobody awaits is not an unhandled rejection.
|
|
605
986
|
sending.catch(() => {
|
|
606
987
|
this.sending = undefined;
|
|
607
988
|
});
|
|
@@ -656,6 +1037,12 @@ class Lemma {
|
|
|
656
1037
|
/** Identity and credentials on every request; spread last so nothing overrides them. */
|
|
657
1038
|
baseHeaders;
|
|
658
1039
|
release;
|
|
1040
|
+
environment;
|
|
1041
|
+
tags;
|
|
1042
|
+
gzip;
|
|
1043
|
+
beforeSend;
|
|
1044
|
+
maxPayloadBytes;
|
|
1045
|
+
deduplicateSpanInputs;
|
|
659
1046
|
traces = new Map();
|
|
660
1047
|
/** Sends in flight, and callback traces held open by a returned stream. */
|
|
661
1048
|
pending = new Set();
|
|
@@ -665,11 +1052,6 @@ class Lemma {
|
|
|
665
1052
|
this.projectId = required(options.projectId ?? (0, env_1.readEnv)(() => process.env.LEMMA_PROJECT_ID), "LEMMA_PROJECT_ID");
|
|
666
1053
|
this.baseUrl = (options.baseUrl ??
|
|
667
1054
|
((0, env_1.readEnv)(() => process.env.LEMMA_BASE_URL)?.trim() || debug_delivery_1.PRODUCTION_BASE_URL)).replace(/\/+$/, "");
|
|
668
|
-
// Workers' fetch throws "Illegal invocation" when it is called with a
|
|
669
|
-
// receiver other than the global object, so neither the global nor a
|
|
670
|
-
// passed-in fetch is called as a method of this client. The global is
|
|
671
|
-
// read per call, so a fetch that instrumentation installs after the
|
|
672
|
-
// client is built is the one used.
|
|
673
1055
|
const customFetch = options.fetch;
|
|
674
1056
|
this.fetchImpl = (input, init) => (customFetch ?? fetch)(input, init);
|
|
675
1057
|
this.baseHeaders = {
|
|
@@ -677,6 +1059,18 @@ class Lemma {
|
|
|
677
1059
|
Authorization: `Bearer ${this.apiKey}`,
|
|
678
1060
|
};
|
|
679
1061
|
this.release = (0, release_1.normalizeRelease)(options.release ?? (0, env_1.readEnv)(() => process.env.LEMMA_RELEASE));
|
|
1062
|
+
this.environment = (0, release_1.normalizeEnvironment)(options.environment ?? (0, env_1.readEnv)(() => process.env.LEMMA_ENVIRONMENT));
|
|
1063
|
+
this.tags = (0, release_1.normalizeTags)(options.tags);
|
|
1064
|
+
this.gzip = options.gzip === true;
|
|
1065
|
+
this.beforeSend = options.beforeSend;
|
|
1066
|
+
if (options.maxPayloadBytes !== undefined) {
|
|
1067
|
+
if (!Number.isFinite(options.maxPayloadBytes) ||
|
|
1068
|
+
options.maxPayloadBytes <= 0) {
|
|
1069
|
+
throw new Error("@uselemma/tracing: maxPayloadBytes must be > 0");
|
|
1070
|
+
}
|
|
1071
|
+
this.maxPayloadBytes = options.maxPayloadBytes;
|
|
1072
|
+
}
|
|
1073
|
+
this.deduplicateSpanInputs = options.deduplicateSpanInputs === true;
|
|
680
1074
|
this.logInitConfigOnce();
|
|
681
1075
|
}
|
|
682
1076
|
/**
|
|
@@ -703,12 +1097,13 @@ class Lemma {
|
|
|
703
1097
|
});
|
|
704
1098
|
context.output("ok");
|
|
705
1099
|
const startedAt = new Date();
|
|
706
|
-
const payload = this.
|
|
1100
|
+
const payload = this.stampClientDefaults(context.toPayload(this.projectId, startedAt, new Date()));
|
|
707
1101
|
const body = payloadBody(payload);
|
|
1102
|
+
const wireBody = this.gzip ? await gzipString(body) : body;
|
|
708
1103
|
const url = `${this.baseUrl}${debug_delivery_1.INGEST_PATH}`;
|
|
709
1104
|
let response;
|
|
710
1105
|
try {
|
|
711
|
-
response = await (0, delivery_1.withIngestTimeout)((signal) => this.postIngest(
|
|
1106
|
+
response = await (0, delivery_1.withIngestTimeout)((signal) => this.postIngest(wireBody, signal));
|
|
712
1107
|
}
|
|
713
1108
|
catch (error) {
|
|
714
1109
|
hints.push(`ingest request failed (network error): ${(0, delivery_1.describeSendError)(error)}`);
|
|
@@ -722,8 +1117,6 @@ class Lemma {
|
|
|
722
1117
|
const ingestWarnings = [];
|
|
723
1118
|
if (response.status !== debug_delivery_1.EXPECTED_INGEST_SUCCESS_STATUS) {
|
|
724
1119
|
ingestWarnings.push(`expected status ${debug_delivery_1.EXPECTED_INGEST_SUCCESS_STATUS}, got ${response.status}`);
|
|
725
|
-
// Best effort under its own timeout: a stalled body must neither hang
|
|
726
|
-
// the smoke test nor hide the status Lemma returned.
|
|
727
1120
|
const failureBody = await (0, delivery_1.withIngestTimeout)(() => response.text()).catch(() => "");
|
|
728
1121
|
hints.push(...(0, delivery_1.ingestFailureHints)(response.status, failureBody));
|
|
729
1122
|
}
|
|
@@ -773,24 +1166,18 @@ class Lemma {
|
|
|
773
1166
|
result = await fn(context);
|
|
774
1167
|
}
|
|
775
1168
|
catch (error) {
|
|
776
|
-
// Only the agent's own failure belongs in this branch.
|
|
777
1169
|
context.fail(error);
|
|
778
1170
|
await this.flushTraceAutomatic(context, startedAt, new Date(), delivery_1.AWAITED_DELIVERY);
|
|
779
1171
|
throw error;
|
|
780
1172
|
}
|
|
781
1173
|
const held = (0, stream_result_1.holdTraceForStream)(result, context, () => this.flushTraceAutomatic(context, startedAt, new Date(), delivery_1.BACKGROUND_DELIVERY));
|
|
782
1174
|
if (held) {
|
|
783
|
-
// Tracked from now, so a flush() called while the stream is still
|
|
784
|
-
// being read waits for its trace.
|
|
785
1175
|
this.track(held.sent);
|
|
786
1176
|
return held.stream;
|
|
787
1177
|
}
|
|
788
1178
|
if (!context.hasOutput) {
|
|
789
1179
|
context.output(result);
|
|
790
1180
|
}
|
|
791
|
-
// Automatic delivery is outside the agent's try: a transport failure
|
|
792
|
-
// must not be recorded as an agent failure. Fail-open so Lemma being
|
|
793
|
-
// down cannot fail the caller's app; ingest() stays strict for retries.
|
|
794
1181
|
await this.flushTraceAutomatic(context, startedAt, new Date(), delivery_1.AWAITED_DELIVERY);
|
|
795
1182
|
return result;
|
|
796
1183
|
})();
|
|
@@ -800,11 +1187,6 @@ class Lemma {
|
|
|
800
1187
|
* dropped, including each callback trace whose returned stream is still
|
|
801
1188
|
* being read. Never rejects. A trace handle that hasn't been ended yet is
|
|
802
1189
|
* not waited for.
|
|
803
|
-
*
|
|
804
|
-
* Pass it to the runtime so delivery outlives the response:
|
|
805
|
-
* `ctx.waitUntil(lemma.flush())` on Cloudflare Workers,
|
|
806
|
-
* `after(() => lemma.flush())` in Next.js. On AWS Lambda, await it before
|
|
807
|
-
* the handler returns.
|
|
808
1190
|
*/
|
|
809
1191
|
async flush() {
|
|
810
1192
|
await Promise.allSettled(Array.from(this.pending));
|
|
@@ -828,8 +1210,6 @@ class Lemma {
|
|
|
828
1210
|
await this.flushTraceAutomatic(trace, startedAt, endedAt, budget);
|
|
829
1211
|
}
|
|
830
1212
|
finally {
|
|
831
|
-
// Drop the handle once ended so long-lived clients don't retain
|
|
832
|
-
// every historical TraceHandle (and its spans/payloads) forever.
|
|
833
1213
|
this.traces.delete(trace.id);
|
|
834
1214
|
}
|
|
835
1215
|
});
|
|
@@ -842,22 +1222,6 @@ class Lemma {
|
|
|
842
1222
|
}
|
|
843
1223
|
/**
|
|
844
1224
|
* Deliver a trace you assembled yourself, in a single request.
|
|
845
|
-
*
|
|
846
|
-
* This is the manual counterpart to {@link Lemma.trace}: instead of the client
|
|
847
|
-
* owning the lifecycle, you build a {@link TraceContext} — recording spans,
|
|
848
|
-
* output, and status on it — and hand it back to be sent. Use it for producers
|
|
849
|
-
* that live outside a single process (cross-process buffers, queues, batch
|
|
850
|
-
* backfills) where a long-lived handle can't be held.
|
|
851
|
-
*
|
|
852
|
-
* Deliver **one complete trace** when the execution (agent turn) finishes:
|
|
853
|
-
* root input/output, thread/user, and all child spans in a single call. This
|
|
854
|
-
* is required — patching a trace over time is not supported. Omitted root
|
|
855
|
-
* fields do not preserve prior values, and after Lemma processes the trace
|
|
856
|
-
* once, a later re-delivery does not re-run issue extraction (late new span
|
|
857
|
-
* IDs may still append for display). Retries of the same complete payload are
|
|
858
|
-
* safe: already-stored span IDs are skipped. Throws an `IngestError` on
|
|
859
|
-
* a non-2xx response, and never mutates the trace's status, so a failed send
|
|
860
|
-
* can be retried as-is.
|
|
861
1225
|
*/
|
|
862
1226
|
async ingest(context, options) {
|
|
863
1227
|
const failure = await this.sendTrace(context, options.startedAt, options.endedAt ?? new Date(), delivery_1.STRICT_DELIVERY);
|
|
@@ -967,13 +1331,6 @@ class Lemma {
|
|
|
967
1331
|
tool(options) {
|
|
968
1332
|
this.recordTool(options);
|
|
969
1333
|
}
|
|
970
|
-
traceFor(traceId) {
|
|
971
|
-
const trace = this.traces.get(traceId);
|
|
972
|
-
if (!trace) {
|
|
973
|
-
throw new Error(`@uselemma/tracing: unknown trace id "${traceId}"`);
|
|
974
|
-
}
|
|
975
|
-
return trace;
|
|
976
|
-
}
|
|
977
1334
|
detachedTraceFor(traceId, kind) {
|
|
978
1335
|
if (!traceId) {
|
|
979
1336
|
warnNoop(`${kind} handle requires traceId; skipping ${kind}`);
|
|
@@ -1000,20 +1357,28 @@ class Lemma {
|
|
|
1000
1357
|
...(warnings.length ? { warnings } : {}),
|
|
1001
1358
|
});
|
|
1002
1359
|
}
|
|
1003
|
-
|
|
1360
|
+
stampClientDefaults(payload) {
|
|
1004
1361
|
if (this.release)
|
|
1005
1362
|
payload.trace.release = this.release;
|
|
1363
|
+
if (this.environment && !payload.trace.environment) {
|
|
1364
|
+
payload.trace.environment = this.environment;
|
|
1365
|
+
}
|
|
1366
|
+
if (this.tags) {
|
|
1367
|
+
const merged = (0, release_1.normalizeTags)([
|
|
1368
|
+
...this.tags,
|
|
1369
|
+
...(payload.trace.tags ?? []),
|
|
1370
|
+
]);
|
|
1371
|
+
if (merged)
|
|
1372
|
+
payload.trace.tags = merged;
|
|
1373
|
+
}
|
|
1006
1374
|
return payload;
|
|
1007
1375
|
}
|
|
1008
1376
|
/**
|
|
1009
1377
|
* Automatic SDK delivery. Retries transient failures, then fails open with
|
|
1010
1378
|
* a rate-limited warning so Lemma being down cannot fail the caller's app.
|
|
1011
|
-
* {@link Lemma.ingest} sends once and throws, because queue/plugin producers
|
|
1012
|
-
* keep their own retry backlog.
|
|
1013
1379
|
*/
|
|
1014
1380
|
async flushTraceAutomatic(context, startedAt, endedAt, budget) {
|
|
1015
1381
|
const sending = this.sendTrace(context, startedAt, endedAt, budget);
|
|
1016
|
-
// Built by now, and never resent, so a later change isn't delivered.
|
|
1017
1382
|
context.markPayloadFinal();
|
|
1018
1383
|
const failure = await sending;
|
|
1019
1384
|
if (failure)
|
|
@@ -1024,19 +1389,18 @@ class Lemma {
|
|
|
1024
1389
|
return this.track(this.buildAndSend(context, startedAt, endedAt, budget));
|
|
1025
1390
|
}
|
|
1026
1391
|
/**
|
|
1027
|
-
* Build, send, and check one trace; undefined when it was delivered
|
|
1028
|
-
*
|
|
1029
|
-
* automatic delivery handle it once.
|
|
1392
|
+
* Build, send, and check one trace; undefined when it was delivered or
|
|
1393
|
+
* intentionally dropped by `beforeSend`.
|
|
1030
1394
|
*/
|
|
1031
1395
|
async buildAndSend(context, startedAt, endedAt, budget) {
|
|
1032
|
-
const built = this.buildIngestBody(context, startedAt, endedAt);
|
|
1396
|
+
const built = await this.buildIngestBody(context, startedAt, endedAt);
|
|
1033
1397
|
if (!built.ok)
|
|
1034
1398
|
return built;
|
|
1035
|
-
|
|
1399
|
+
if (built.dropped)
|
|
1400
|
+
return undefined;
|
|
1401
|
+
const result = await (0, delivery_1.deliver)((signal) => this.postIngest(built.wireBody, signal), { traceId: context.id, projectId: this.projectId }, budget);
|
|
1036
1402
|
if (!result.ok)
|
|
1037
1403
|
return result;
|
|
1038
|
-
// Debug-only checks; the trace is already stored, so a failure here
|
|
1039
|
-
// must neither fail the caller nor count as a dropped trace.
|
|
1040
1404
|
try {
|
|
1041
1405
|
await this.afterTraceSent(built.payload, result.response);
|
|
1042
1406
|
}
|
|
@@ -1046,23 +1410,51 @@ class Lemma {
|
|
|
1046
1410
|
return undefined;
|
|
1047
1411
|
}
|
|
1048
1412
|
/**
|
|
1049
|
-
*
|
|
1050
|
-
*
|
|
1413
|
+
* Build, shape (`deduplicateSpanInputs`, `beforeSend`, `maxPayloadBytes`),
|
|
1414
|
+
* and serialize once so retries send identical bytes.
|
|
1051
1415
|
*/
|
|
1052
|
-
buildIngestBody(context, startedAt, endedAt) {
|
|
1416
|
+
async buildIngestBody(context, startedAt, endedAt) {
|
|
1053
1417
|
try {
|
|
1054
|
-
const
|
|
1418
|
+
const rawPayload = this.stampClientDefaults(context.toPayload(this.projectId, startedAt, endedAt));
|
|
1419
|
+
const needsTransform = this.deduplicateSpanInputs ||
|
|
1420
|
+
this.beforeSend !== undefined ||
|
|
1421
|
+
this.maxPayloadBytes !== undefined;
|
|
1422
|
+
// Clone container objects before dedup/beforeSend/cap so live TraceContext
|
|
1423
|
+
// spans and caller-owned metadata are never mutated, without double-running
|
|
1424
|
+
// stringifyTraceJson's string cap.
|
|
1425
|
+
let payload = needsTransform ? cloneForTransform(rawPayload) : rawPayload;
|
|
1426
|
+
if (this.deduplicateSpanInputs) {
|
|
1427
|
+
payload = (0, payload_1.applySpanContentDedup)(payload);
|
|
1428
|
+
}
|
|
1429
|
+
if (this.beforeSend) {
|
|
1430
|
+
const next = (0, payload_1.applyBeforeSend)(payload, this.beforeSend);
|
|
1431
|
+
if (next === null) {
|
|
1432
|
+
(0, debug_mode_1.lemmaDebug)("client", "trace dropped by beforeSend", {
|
|
1433
|
+
traceId: context.id,
|
|
1434
|
+
projectId: this.projectId,
|
|
1435
|
+
});
|
|
1436
|
+
return { ok: true, dropped: true };
|
|
1437
|
+
}
|
|
1438
|
+
payload = next;
|
|
1439
|
+
}
|
|
1440
|
+
if (this.maxPayloadBytes !== undefined) {
|
|
1441
|
+
payload = (0, payload_1.applyPayloadCap)(payload, this.maxPayloadBytes);
|
|
1442
|
+
}
|
|
1055
1443
|
const body = payloadBody(payload);
|
|
1444
|
+
const wireBody = this.gzip ? await gzipString(body) : body;
|
|
1056
1445
|
(0, debug_mode_1.lemmaDebug)("client", "sending trace", {
|
|
1057
1446
|
traceId: payload.trace.id,
|
|
1058
1447
|
name: payload.trace.name,
|
|
1059
1448
|
spanCount: payload.trace.spans.length,
|
|
1060
1449
|
projectId: payload.project_id,
|
|
1061
|
-
bodyBytes:
|
|
1450
|
+
bodyBytes: typeof wireBody === "string"
|
|
1451
|
+
? new TextEncoder().encode(wireBody).length
|
|
1452
|
+
: wireBody.byteLength,
|
|
1453
|
+
...(this.gzip ? { contentEncoding: "gzip" } : {}),
|
|
1062
1454
|
requestedAt: new Date().toISOString(),
|
|
1063
1455
|
url: `${this.baseUrl}${debug_delivery_1.INGEST_PATH}`,
|
|
1064
1456
|
});
|
|
1065
|
-
return { ok: true, payload,
|
|
1457
|
+
return { ok: true, dropped: false, payload, wireBody };
|
|
1066
1458
|
}
|
|
1067
1459
|
catch (error) {
|
|
1068
1460
|
(0, debug_mode_1.lemmaDebug)("client", "trace ingest failed", {
|
|
@@ -1074,10 +1466,15 @@ class Lemma {
|
|
|
1074
1466
|
}
|
|
1075
1467
|
}
|
|
1076
1468
|
postIngest(body, signal) {
|
|
1469
|
+
const headers = {
|
|
1470
|
+
"Content-Type": "application/json",
|
|
1471
|
+
...(this.gzip ? { "Content-Encoding": "gzip" } : {}),
|
|
1472
|
+
...this.baseHeaders,
|
|
1473
|
+
};
|
|
1077
1474
|
return this.fetchImpl(`${this.baseUrl}${debug_delivery_1.INGEST_PATH}`, {
|
|
1078
1475
|
method: "POST",
|
|
1079
|
-
headers
|
|
1080
|
-
body,
|
|
1476
|
+
headers,
|
|
1477
|
+
body: body,
|
|
1081
1478
|
signal,
|
|
1082
1479
|
});
|
|
1083
1480
|
}
|