raindrop-ai 1.1.1 → 2.0.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.
- package/dist/chunk-BU322D7Q.mjs +1953 -0
- package/dist/{chunk-7HPYMPNJ.mjs → chunk-CSH7U5JZ.mjs} +72 -4140
- package/dist/chunk-F5TJSGNA.mjs +4204 -0
- package/dist/{chunk-6575YF3B.mjs → chunk-PYMV6B3M.mjs} +4326 -1246
- package/dist/evals/cli.js +25704 -25358
- package/dist/evals/cli.mjs +13 -13
- package/dist/{index-mM4Ls3Kv.d.ts → index-BJJ273dz.d.mts} +8434 -4087
- package/dist/{index-mM4Ls3Kv.d.mts → index-BJJ273dz.d.ts} +8434 -4087
- package/dist/index.d.mts +2 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +26461 -26184
- package/dist/index.mjs +24 -21
- package/dist/{portable-runtime-M4PGODCX.mjs → portable-runtime-G27RYK6P.mjs} +7 -11
- package/dist/tracing/index.d.mts +2 -1
- package/dist/tracing/index.d.ts +2 -1
- package/dist/tracing/index.js +1 -1
- package/dist/tracing/index.mjs +2 -1
- package/package.json +1 -1
- package/dist/chunk-HEJQOFNN.mjs +0 -4799
|
@@ -0,0 +1,4204 @@
|
|
|
1
|
+
import {
|
|
2
|
+
APP_BRANCH,
|
|
3
|
+
APP_COMMIT_DIRTY,
|
|
4
|
+
APP_COMMIT_SHA,
|
|
5
|
+
DEFAULT_DISPATCH_SPAN_NAME,
|
|
6
|
+
DELIVERED,
|
|
7
|
+
HANDOFF_ATTRIBUTE_SUFFIXES,
|
|
8
|
+
HANDOFF_TERMINAL_CANCELLED,
|
|
9
|
+
HANDOFF_TERMINAL_PROPERTY_KEY,
|
|
10
|
+
InFlightCutOff,
|
|
11
|
+
MODEL_USAGE_ATTRIBUTES,
|
|
12
|
+
OPERATION_ID_ATTRIBUTE,
|
|
13
|
+
POST_SHUTDOWN_TIMEOUT_MS,
|
|
14
|
+
PROMPT_TOOLS_ATTRIBUTE,
|
|
15
|
+
SUBAGENT_ABORT_OPERATION_ID,
|
|
16
|
+
SUBAGENT_ABORT_SPAN_NAME,
|
|
17
|
+
applySpanAttributeFrames,
|
|
18
|
+
asCompat,
|
|
19
|
+
attrString,
|
|
20
|
+
awaitEarlierSends,
|
|
21
|
+
bindRoutingContext,
|
|
22
|
+
bindSpanAttributes,
|
|
23
|
+
buildRawModelUsageAttributes,
|
|
24
|
+
cancelledTerminalAttributes,
|
|
25
|
+
canonicalModelProvider,
|
|
26
|
+
claimSpanForFrames,
|
|
27
|
+
combineResults,
|
|
28
|
+
compileSpanPiiFields,
|
|
29
|
+
copyReplayTraceDestination,
|
|
30
|
+
currentReplayTraceDestination,
|
|
31
|
+
currentRoutingBinding,
|
|
32
|
+
currentSpanAttributes,
|
|
33
|
+
describeUndelivered,
|
|
34
|
+
detachedChildMetadata,
|
|
35
|
+
detachedDispatchMetadata,
|
|
36
|
+
evalScopeAttributes,
|
|
37
|
+
fateOf,
|
|
38
|
+
fromHeaders,
|
|
39
|
+
localDebuggerEnabled,
|
|
40
|
+
localTracePiiRedactionRequested,
|
|
41
|
+
markErrorSpanSeen,
|
|
42
|
+
maskAttributeMap,
|
|
43
|
+
maskOtlpSpan,
|
|
44
|
+
maskSpanStatusMessage,
|
|
45
|
+
mirrorTraceExportToLocalDebugger,
|
|
46
|
+
normalizeFeatureFlags,
|
|
47
|
+
normalizeToolDeclarations,
|
|
48
|
+
piiRedaction,
|
|
49
|
+
piiRedactionNow,
|
|
50
|
+
projectIdHeaders,
|
|
51
|
+
promptToolsAttributeValue,
|
|
52
|
+
promptToolsFromTraceloopAttributes,
|
|
53
|
+
raceWithTimeout,
|
|
54
|
+
randomUUID,
|
|
55
|
+
rateLimitedLog,
|
|
56
|
+
recordReplayExportedSpan,
|
|
57
|
+
redactPiiInAttributeMap,
|
|
58
|
+
redactPiiInOtlpSpan,
|
|
59
|
+
redactSpanContent,
|
|
60
|
+
rememberReplayTraceDestination,
|
|
61
|
+
replayTraceDestinationFor,
|
|
62
|
+
replayTraceUrl,
|
|
63
|
+
requestLocalTracePiiRedaction,
|
|
64
|
+
resolveFlushTimeoutMs,
|
|
65
|
+
resolveLocalDebuggerBaseUrl,
|
|
66
|
+
resolveMaxTextFieldChars,
|
|
67
|
+
resolvePiiRedaction,
|
|
68
|
+
sendJson,
|
|
69
|
+
sendLocalDebuggerLiveEvent,
|
|
70
|
+
stringifyBounded,
|
|
71
|
+
summarize2,
|
|
72
|
+
toHeaders,
|
|
73
|
+
toLangSmithHeaders,
|
|
74
|
+
toolEventsAllowMetadata,
|
|
75
|
+
unbindRoutingContext,
|
|
76
|
+
unbindSpanAttributes,
|
|
77
|
+
warnUnresolvedCarrier,
|
|
78
|
+
withAppGitAttributes,
|
|
79
|
+
withAppGitProperties,
|
|
80
|
+
withMetadataPrefix,
|
|
81
|
+
withRoutingContext
|
|
82
|
+
} from "./chunk-CSH7U5JZ.mjs";
|
|
83
|
+
|
|
84
|
+
// src/lib/inject-als.ts
|
|
85
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
86
|
+
if (!globalThis.RAINDROP_ASYNC_LOCAL_STORAGE) {
|
|
87
|
+
globalThis.RAINDROP_ASYNC_LOCAL_STORAGE = AsyncLocalStorage;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// package.json
|
|
91
|
+
var package_default = {
|
|
92
|
+
name: "raindrop-ai",
|
|
93
|
+
version: "2.0.0",
|
|
94
|
+
main: "dist/index.js",
|
|
95
|
+
module: "dist/index.mjs",
|
|
96
|
+
types: "dist/index.d.ts",
|
|
97
|
+
bin: {
|
|
98
|
+
"raindrop-evals": "dist/evals/cli.js"
|
|
99
|
+
},
|
|
100
|
+
license: "MIT",
|
|
101
|
+
homepage: "https://www.raindrop.ai/docs/sdk/typescript/",
|
|
102
|
+
bugs: {
|
|
103
|
+
url: "https://www.raindrop.ai/docs/support/"
|
|
104
|
+
},
|
|
105
|
+
exports: {
|
|
106
|
+
".": {
|
|
107
|
+
import: {
|
|
108
|
+
types: "./dist/index.d.mts",
|
|
109
|
+
default: "./dist/index.mjs"
|
|
110
|
+
},
|
|
111
|
+
require: {
|
|
112
|
+
types: "./dist/index.d.ts",
|
|
113
|
+
default: "./dist/index.js"
|
|
114
|
+
}
|
|
115
|
+
},
|
|
116
|
+
"./tracing": {
|
|
117
|
+
types: "./dist/tracing/index.d.ts",
|
|
118
|
+
node: "./dist/tracing/index.js",
|
|
119
|
+
import: "./dist/tracing/index.mjs",
|
|
120
|
+
require: "./dist/tracing/index.js"
|
|
121
|
+
},
|
|
122
|
+
"./otel": {
|
|
123
|
+
types: "./dist/otel/index.d.ts",
|
|
124
|
+
node: "./dist/otel/index.js",
|
|
125
|
+
import: "./dist/otel/index.mjs",
|
|
126
|
+
require: "./dist/otel/index.js"
|
|
127
|
+
}
|
|
128
|
+
},
|
|
129
|
+
files: [
|
|
130
|
+
"dist/**"
|
|
131
|
+
],
|
|
132
|
+
scripts: {
|
|
133
|
+
build: "tsup",
|
|
134
|
+
dev: "tsup --watch",
|
|
135
|
+
clean: "rm -rf .turbo && rm -rf dist",
|
|
136
|
+
try: "tsx ./src/example/index.ts",
|
|
137
|
+
test: "vitest run",
|
|
138
|
+
smoke: "tsx ./scripts/smoke.ts",
|
|
139
|
+
"smoke:ai-sdk-self-diagnostics": "tsx ./scripts/smoke.ai-sdk-self-diagnostics.ts",
|
|
140
|
+
"smoke:self-diagnostics:v4": "pnpm build && cd tests/v4 && pnpm install --ignore-workspace --lockfile=false && pnpm smoke",
|
|
141
|
+
"smoke:self-diagnostics:v5": "pnpm build && cd tests/v5 && pnpm install --ignore-workspace --lockfile=false && pnpm smoke",
|
|
142
|
+
"smoke:self-diagnostics:v6": "pnpm build && cd tests/v6 && pnpm install --ignore-workspace --lockfile=false && pnpm smoke",
|
|
143
|
+
"smoke:self-diagnostics:ai-sdk:all": "pnpm smoke:self-diagnostics:v4 && pnpm smoke:self-diagnostics:v5 && pnpm smoke:self-diagnostics:v6",
|
|
144
|
+
"smoke:self-diagnostics:openai-sdk": "pnpm build && cd tests/openai && pnpm install --ignore-workspace --lockfile=false && pnpm smoke",
|
|
145
|
+
"smoke:self-diagnostics:anthropic-sdk": "pnpm build && cd tests/anthropic && pnpm install --ignore-workspace --lockfile=false && pnpm smoke",
|
|
146
|
+
"smoke:self-diagnostics:all": "pnpm smoke:self-diagnostics:ai-sdk:all && pnpm smoke:self-diagnostics:openai-sdk && pnpm smoke:self-diagnostics:anthropic-sdk",
|
|
147
|
+
"test:otelv1-local-debugger": "pnpm build && cd tests/otelv1-local-debugger && pnpm install --ignore-workspace --lockfile=false && pnpm test",
|
|
148
|
+
"test:otelv2-local-debugger": "pnpm build && cd tests/otelv2-local-debugger && pnpm install --ignore-workspace --lockfile=false && pnpm test"
|
|
149
|
+
},
|
|
150
|
+
devDependencies: {
|
|
151
|
+
"@raindrop-ai/core": "workspace:*",
|
|
152
|
+
"@raindrop-ai/redact-pii": "workspace:*",
|
|
153
|
+
"@raindrop-ai/schemas": "workspace:*",
|
|
154
|
+
"@types/node": "^20.11.17",
|
|
155
|
+
ai: "^6.0.214",
|
|
156
|
+
msw: "^2.12.8",
|
|
157
|
+
tsup: "^9.0.0",
|
|
158
|
+
tsx: "^4.22.0",
|
|
159
|
+
typescript: "^5.3.3",
|
|
160
|
+
vite: "^7.3.7",
|
|
161
|
+
vitest: "^4.1.12",
|
|
162
|
+
"zod-4-copy": "npm:zod@4.1.8"
|
|
163
|
+
},
|
|
164
|
+
dependencies: {
|
|
165
|
+
"@jitl/quickjs-singlefile-cjs-release-sync": "0.32.0",
|
|
166
|
+
"@opentelemetry/api": "^1.9.0",
|
|
167
|
+
"@opentelemetry/core": "^1.30.1",
|
|
168
|
+
"@opentelemetry/exporter-trace-otlp-http": "^0.57.2",
|
|
169
|
+
"@opentelemetry/exporter-trace-otlp-proto": "^0.57.2",
|
|
170
|
+
"@opentelemetry/instrumentation": "^0.57.2",
|
|
171
|
+
"@opentelemetry/resources": "^1.30.1",
|
|
172
|
+
"@opentelemetry/sdk-trace-base": "^1.30.1",
|
|
173
|
+
"@opentelemetry/sdk-trace-node": "^1.30.1",
|
|
174
|
+
"@traceloop/ai-semantic-conventions": "0.19.0-otel-v1",
|
|
175
|
+
"@traceloop/instrumentation-anthropic": "0.19.0-otel-v1",
|
|
176
|
+
"@traceloop/instrumentation-bedrock": "0.19.0-otel-v1",
|
|
177
|
+
"@traceloop/instrumentation-chromadb": "0.19.0-otel-v1",
|
|
178
|
+
"@traceloop/instrumentation-cohere": "0.19.0-otel-v1",
|
|
179
|
+
"@traceloop/instrumentation-langchain": "0.19.0-otel-v1",
|
|
180
|
+
"@traceloop/instrumentation-llamaindex": "0.19.0-otel-v1",
|
|
181
|
+
"@traceloop/instrumentation-openai": "0.19.0-otel-v1",
|
|
182
|
+
"@traceloop/instrumentation-pinecone": "0.19.0-otel-v1",
|
|
183
|
+
"@traceloop/instrumentation-qdrant": "0.19.0-otel-v1",
|
|
184
|
+
"@traceloop/instrumentation-together": "0.19.0-otel-v1",
|
|
185
|
+
"@traceloop/instrumentation-vertexai": "0.19.0-otel-v1",
|
|
186
|
+
"quickjs-emscripten-core": "0.32.0",
|
|
187
|
+
weakref: "^0.2.1",
|
|
188
|
+
zod: "^3.25.76 || ^4.0.0"
|
|
189
|
+
},
|
|
190
|
+
publishConfig: {
|
|
191
|
+
access: "public",
|
|
192
|
+
provenance: false
|
|
193
|
+
},
|
|
194
|
+
tsup: {
|
|
195
|
+
entry: [
|
|
196
|
+
"src/index.ts",
|
|
197
|
+
"src/evals/cli.ts",
|
|
198
|
+
"src/tracing/index.ts",
|
|
199
|
+
"src/otel/index.ts"
|
|
200
|
+
],
|
|
201
|
+
format: [
|
|
202
|
+
"cjs",
|
|
203
|
+
"esm"
|
|
204
|
+
],
|
|
205
|
+
external: [
|
|
206
|
+
"@traceloop/instrumentation-anthropic",
|
|
207
|
+
"@traceloop/instrumentation-openai",
|
|
208
|
+
"@traceloop/instrumentation-cohere",
|
|
209
|
+
"@traceloop/instrumentation-bedrock",
|
|
210
|
+
"@traceloop/instrumentation-vertexai",
|
|
211
|
+
"@traceloop/instrumentation-pinecone",
|
|
212
|
+
"@traceloop/instrumentation-chromadb",
|
|
213
|
+
"@traceloop/instrumentation-qdrant",
|
|
214
|
+
"@traceloop/instrumentation-together",
|
|
215
|
+
"@traceloop/instrumentation-langchain",
|
|
216
|
+
"@traceloop/instrumentation-llamaindex",
|
|
217
|
+
"@traceloop/ai-semantic-conventions",
|
|
218
|
+
"@opentelemetry/api",
|
|
219
|
+
"@opentelemetry/core",
|
|
220
|
+
"@opentelemetry/instrumentation",
|
|
221
|
+
"@opentelemetry/exporter-trace-otlp-http",
|
|
222
|
+
"@opentelemetry/exporter-trace-otlp-proto",
|
|
223
|
+
"@opentelemetry/resources",
|
|
224
|
+
"@opentelemetry/sdk-trace-base",
|
|
225
|
+
"@opentelemetry/sdk-trace-node"
|
|
226
|
+
],
|
|
227
|
+
noExternal: [
|
|
228
|
+
"@raindrop-ai/core",
|
|
229
|
+
"@raindrop-ai/redact-pii",
|
|
230
|
+
"@raindrop-ai/schemas"
|
|
231
|
+
],
|
|
232
|
+
dts: {
|
|
233
|
+
resolve: true
|
|
234
|
+
},
|
|
235
|
+
clean: true
|
|
236
|
+
}
|
|
237
|
+
};
|
|
238
|
+
|
|
239
|
+
// src/tracing/multi-project.ts
|
|
240
|
+
import { createHash } from "crypto";
|
|
241
|
+
import { OTLPTraceExporter as OTLPProtoTraceExporter2 } from "@opentelemetry/exporter-trace-otlp-proto";
|
|
242
|
+
|
|
243
|
+
// src/tracing/replay-routing.ts
|
|
244
|
+
import { OTLPTraceExporter as OTLPProtoTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
|
|
245
|
+
var EXPORT_SUCCESS = 0;
|
|
246
|
+
var EXPORT_FAILED = 1;
|
|
247
|
+
function recordExportedSpan(destination, span) {
|
|
248
|
+
if (typeof span !== "object" && typeof span !== "function" || span === null) return;
|
|
249
|
+
const spanContext = span.spanContext;
|
|
250
|
+
if (typeof spanContext !== "function") return;
|
|
251
|
+
const context7 = spanContext.call(span);
|
|
252
|
+
if (typeof (context7 == null ? void 0 : context7.spanId) === "string" && typeof context7.traceId === "string") {
|
|
253
|
+
recordReplayExportedSpan(destination, context7.spanId, context7.traceId);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
function createReplayExporter(destination) {
|
|
257
|
+
var _a;
|
|
258
|
+
if (destination.kind === "workshop") {
|
|
259
|
+
return new OTLPProtoTraceExporter({
|
|
260
|
+
url: replayTraceUrl(destination.url)
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
return new OTLPProtoTraceExporter({
|
|
264
|
+
url: replayTraceUrl(destination.url),
|
|
265
|
+
headers: {
|
|
266
|
+
Authorization: `Bearer ${destination.apiKey}`,
|
|
267
|
+
"X-Raindrop-Replay-Id": destination.replayId,
|
|
268
|
+
"X-Raindrop-Project-Id": (_a = destination.projectId) != null ? _a : "default"
|
|
269
|
+
}
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
var ReplayRoutingSpanExporter = class {
|
|
273
|
+
constructor(normal, replayExporter = createReplayExporter) {
|
|
274
|
+
this.normal = normal;
|
|
275
|
+
this.replayExporter = replayExporter;
|
|
276
|
+
}
|
|
277
|
+
export(spans, resultCallback) {
|
|
278
|
+
const replayGroups = /* @__PURE__ */ new Map();
|
|
279
|
+
const normalSpans = [];
|
|
280
|
+
for (const span of spans) {
|
|
281
|
+
const destination = replayTraceDestinationFor(span);
|
|
282
|
+
if (!destination) {
|
|
283
|
+
normalSpans.push(span);
|
|
284
|
+
continue;
|
|
285
|
+
}
|
|
286
|
+
const group = replayGroups.get(destination);
|
|
287
|
+
recordExportedSpan(destination, span);
|
|
288
|
+
if (group) group.push(span);
|
|
289
|
+
else replayGroups.set(destination, [span]);
|
|
290
|
+
}
|
|
291
|
+
if (replayGroups.size === 0) {
|
|
292
|
+
this.normal.export(spans, resultCallback);
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
let remaining = replayGroups.size + (normalSpans.length > 0 ? 1 : 0);
|
|
296
|
+
let failed = false;
|
|
297
|
+
let firstError;
|
|
298
|
+
const finish = (result) => {
|
|
299
|
+
if (result.code !== EXPORT_SUCCESS) {
|
|
300
|
+
failed = true;
|
|
301
|
+
firstError != null ? firstError : firstError = result.error;
|
|
302
|
+
}
|
|
303
|
+
remaining -= 1;
|
|
304
|
+
if (remaining === 0) {
|
|
305
|
+
resultCallback(
|
|
306
|
+
firstError ? { code: EXPORT_FAILED, error: firstError } : { code: failed ? EXPORT_FAILED : EXPORT_SUCCESS }
|
|
307
|
+
);
|
|
308
|
+
}
|
|
309
|
+
};
|
|
310
|
+
if (normalSpans.length > 0) {
|
|
311
|
+
try {
|
|
312
|
+
this.normal.export(normalSpans, finish);
|
|
313
|
+
} catch (cause) {
|
|
314
|
+
finish({
|
|
315
|
+
code: EXPORT_FAILED,
|
|
316
|
+
error: cause instanceof Error ? cause : new Error(String(cause))
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
for (const [destination, replaySpans] of replayGroups) {
|
|
321
|
+
let exporter;
|
|
322
|
+
try {
|
|
323
|
+
exporter = this.replayExporter(destination);
|
|
324
|
+
} catch (cause) {
|
|
325
|
+
finish({
|
|
326
|
+
code: EXPORT_FAILED,
|
|
327
|
+
error: cause instanceof Error ? cause : new Error(String(cause))
|
|
328
|
+
});
|
|
329
|
+
continue;
|
|
330
|
+
}
|
|
331
|
+
try {
|
|
332
|
+
exporter.export(replaySpans, (result) => {
|
|
333
|
+
finish(result);
|
|
334
|
+
void exporter.shutdown().catch(() => {
|
|
335
|
+
});
|
|
336
|
+
});
|
|
337
|
+
} catch (cause) {
|
|
338
|
+
finish({
|
|
339
|
+
code: EXPORT_FAILED,
|
|
340
|
+
error: cause instanceof Error ? cause : new Error(String(cause))
|
|
341
|
+
});
|
|
342
|
+
void exporter.shutdown().catch(() => {
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
forceFlush() {
|
|
348
|
+
return this.normal.forceFlush ? this.normal.forceFlush() : Promise.resolve();
|
|
349
|
+
}
|
|
350
|
+
shutdown() {
|
|
351
|
+
return this.normal.shutdown();
|
|
352
|
+
}
|
|
353
|
+
};
|
|
354
|
+
|
|
355
|
+
// src/tracing/multi-project.ts
|
|
356
|
+
var PROJECT_ID_SPAN_ATTRIBUTE = "raindrop.project_id";
|
|
357
|
+
var AUTH_HINT_SPAN_ATTRIBUTE = "raindrop.auth_hint";
|
|
358
|
+
var EXPORT_SUCCESS2 = 0;
|
|
359
|
+
var EXPORT_FAILED2 = 1;
|
|
360
|
+
var SPAN_STATUS_ERROR = 2;
|
|
361
|
+
function authHintForKey(writeKey) {
|
|
362
|
+
if (!writeKey) return void 0;
|
|
363
|
+
return createHash("sha256").update(writeKey, "utf8").digest("hex").slice(0, 8);
|
|
364
|
+
}
|
|
365
|
+
var STATE_KEY = /* @__PURE__ */ Symbol.for("raindrop.tracing.multiProjectState");
|
|
366
|
+
function getState() {
|
|
367
|
+
const holder = globalThis;
|
|
368
|
+
let state = holder[STATE_KEY];
|
|
369
|
+
if (!state) {
|
|
370
|
+
state = {
|
|
371
|
+
foreignClientSeen: false,
|
|
372
|
+
seenClientHints: /* @__PURE__ */ new Set(),
|
|
373
|
+
ownerAuthHint: void 0,
|
|
374
|
+
ownerProjectId: void 0,
|
|
375
|
+
pipelineClaimed: false,
|
|
376
|
+
traceloopConfiguredWithoutClaim: false,
|
|
377
|
+
multiKeyWarned: false,
|
|
378
|
+
pendingMultiKeyWarning: false
|
|
379
|
+
};
|
|
380
|
+
holder[STATE_KEY] = state;
|
|
381
|
+
}
|
|
382
|
+
return state;
|
|
383
|
+
}
|
|
384
|
+
function emitMultiKeyWarningOnce() {
|
|
385
|
+
const state = getState();
|
|
386
|
+
if (state.multiKeyWarned) return;
|
|
387
|
+
state.multiKeyWarned = true;
|
|
388
|
+
state.pendingMultiKeyWarning = false;
|
|
389
|
+
console.warn(
|
|
390
|
+
"[raindrop] Multiple API keys detected in one process. The OTel export guard now requires positive attribution: spans not bound to any client (no begin()/asCurrent()) are dropped, and spans bound to a non-owner key are dropped. Manual events are unaffected."
|
|
391
|
+
);
|
|
392
|
+
}
|
|
393
|
+
function registerClientKey(authHint, tracingEnabled = false) {
|
|
394
|
+
if (!authHint) return;
|
|
395
|
+
const state = getState();
|
|
396
|
+
state.seenClientHints.add(authHint);
|
|
397
|
+
if (state.seenClientHints.size > 1) {
|
|
398
|
+
state.foreignClientSeen = true;
|
|
399
|
+
if (tracingEnabled || state.pipelineClaimed) {
|
|
400
|
+
emitMultiKeyWarningOnce();
|
|
401
|
+
} else {
|
|
402
|
+
state.pendingMultiKeyWarning = true;
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
function markForeignClient() {
|
|
407
|
+
getState().foreignClientSeen = true;
|
|
408
|
+
}
|
|
409
|
+
function foreignClientSeen() {
|
|
410
|
+
return getState().foreignClientSeen;
|
|
411
|
+
}
|
|
412
|
+
function stampSpan(span, projectId, authHint) {
|
|
413
|
+
try {
|
|
414
|
+
if (projectId) {
|
|
415
|
+
span.setAttribute(PROJECT_ID_SPAN_ATTRIBUTE, projectId);
|
|
416
|
+
}
|
|
417
|
+
if (authHint && foreignClientSeen()) {
|
|
418
|
+
span.setAttribute(AUTH_HINT_SPAN_ATTRIBUTE, authHint);
|
|
419
|
+
}
|
|
420
|
+
} catch (e) {
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
function stampContextAttributes(span) {
|
|
424
|
+
try {
|
|
425
|
+
applySpanAttributeFrames(span, (key, value) => span.setAttribute(key, value));
|
|
426
|
+
for (const [key, value] of Object.entries(evalScopeAttributes())) {
|
|
427
|
+
span.setAttribute(key, value);
|
|
428
|
+
}
|
|
429
|
+
} catch (e) {
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
var RaindropContextSpanProcessor = class {
|
|
433
|
+
constructor(appGitSnapshot) {
|
|
434
|
+
this.appGitSnapshot = appGitSnapshot;
|
|
435
|
+
this.appGitAdded = /* @__PURE__ */ new WeakMap();
|
|
436
|
+
}
|
|
437
|
+
onStart(span) {
|
|
438
|
+
var _a, _b, _c, _d;
|
|
439
|
+
try {
|
|
440
|
+
stampContextAttributes(span);
|
|
441
|
+
rememberReplayTraceDestination(span);
|
|
442
|
+
const bound = currentRoutingBinding();
|
|
443
|
+
const keys = ["raindrop.app.commit_sha", "raindrop.app.commit_dirty", "raindrop.app.branch"];
|
|
444
|
+
const attrs = (_a = span.attributes) != null ? _a : {};
|
|
445
|
+
const properties = {};
|
|
446
|
+
for (const key of keys) {
|
|
447
|
+
const existing = [key, `ai.telemetry.metadata.${key}`, `traceloop.association.properties.${key}`].find((name) => Object.prototype.hasOwnProperty.call(attrs, name));
|
|
448
|
+
if (existing) properties[key] = attrs[existing];
|
|
449
|
+
}
|
|
450
|
+
const source = { ...(_d = (_c = (_b = this.appGitSnapshot) == null ? void 0 : _b.call(this, properties)) != null ? _c : bound == null ? void 0 : bound.appGit) != null ? _d : {} };
|
|
451
|
+
if (Object.prototype.hasOwnProperty.call(properties, "raindrop.app.commit_sha") && properties["raindrop.app.commit_sha"] !== source["raindrop.app.commit_sha"]) {
|
|
452
|
+
delete source["raindrop.app.commit_dirty"];
|
|
453
|
+
delete source["raindrop.app.branch"];
|
|
454
|
+
}
|
|
455
|
+
const added = /* @__PURE__ */ new Map();
|
|
456
|
+
for (const key of keys) {
|
|
457
|
+
if ([key, `ai.telemetry.metadata.${key}`, `traceloop.association.properties.${key}`].some((name) => Object.prototype.hasOwnProperty.call(attrs, name))) continue;
|
|
458
|
+
const value = source == null ? void 0 : source[key];
|
|
459
|
+
if (typeof value === "string" || typeof value === "boolean") {
|
|
460
|
+
span.setAttribute(key, value);
|
|
461
|
+
added.set(key, value);
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
this.appGitAdded.set(span, added);
|
|
465
|
+
if (!bound) return;
|
|
466
|
+
stampSpan(span, bound.projectId, bound.authHint);
|
|
467
|
+
} catch (e) {
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
onEnd(span) {
|
|
471
|
+
var _a;
|
|
472
|
+
try {
|
|
473
|
+
if (span == null ? void 0 : span.attributes) {
|
|
474
|
+
const attrs = span.attributes;
|
|
475
|
+
const added = this.appGitAdded.get(span);
|
|
476
|
+
const shaKey = "raindrop.app.commit_sha";
|
|
477
|
+
const hasAlias = (key) => [`ai.telemetry.metadata.${key}`, `traceloop.association.properties.${key}`].some((name) => Object.prototype.hasOwnProperty.call(attrs, name));
|
|
478
|
+
const shaChanged = (added == null ? void 0 : added.has(shaKey)) && (attrs[shaKey] !== added.get(shaKey) || hasAlias(shaKey));
|
|
479
|
+
for (const [key, value] of added != null ? added : []) {
|
|
480
|
+
if (attrs[key] === value && (hasAlias(key) || shaChanged && key !== shaKey)) delete attrs[key];
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
if (((_a = span == null ? void 0 : span.status) == null ? void 0 : _a.code) !== SPAN_STATUS_ERROR) return;
|
|
484
|
+
markErrorSpanSeen(span);
|
|
485
|
+
} catch (e) {
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
async forceFlush() {
|
|
489
|
+
}
|
|
490
|
+
async shutdown() {
|
|
491
|
+
}
|
|
492
|
+
};
|
|
493
|
+
var GuardedSpanExporter = class {
|
|
494
|
+
constructor(inner, ownerAuthHint) {
|
|
495
|
+
this.droppedTotal = 0;
|
|
496
|
+
this.inner = inner;
|
|
497
|
+
this.ownerAuthHint = ownerAuthHint;
|
|
498
|
+
}
|
|
499
|
+
partition(spans) {
|
|
500
|
+
var _a;
|
|
501
|
+
const allowed = [];
|
|
502
|
+
let dropped = 0;
|
|
503
|
+
const requirePositive = foreignClientSeen();
|
|
504
|
+
for (const span of spans) {
|
|
505
|
+
const attrs = (_a = span.attributes) != null ? _a : {};
|
|
506
|
+
const hint = attrs[AUTH_HINT_SPAN_ATTRIBUTE];
|
|
507
|
+
const keep = requirePositive ? hint === this.ownerAuthHint : hint === void 0 || hint === this.ownerAuthHint;
|
|
508
|
+
if (keep) {
|
|
509
|
+
allowed.push(span);
|
|
510
|
+
} else {
|
|
511
|
+
dropped += 1;
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
return { allowed, dropped };
|
|
515
|
+
}
|
|
516
|
+
warnDropped(dropped) {
|
|
517
|
+
this.droppedTotal += dropped;
|
|
518
|
+
const total = this.droppedTotal;
|
|
519
|
+
rateLimitedLog(
|
|
520
|
+
"js-sdk.multi-project.dropped",
|
|
521
|
+
() => console.warn(
|
|
522
|
+
`[raindrop] Dropped ${dropped} span(s) produced under a different API key than the tracing pipeline's (total dropped: ${total}). One process has ONE OTel pipeline authenticating with the first tracing-enabled client's key; tracing for a different key/org in the same process is unsupported \u2014 run it in its own process. Manual events (track_ai/begin/finish/signals/identify) are unaffected.`
|
|
523
|
+
)
|
|
524
|
+
);
|
|
525
|
+
}
|
|
526
|
+
export(spans, resultCallback) {
|
|
527
|
+
let allowed;
|
|
528
|
+
let dropped;
|
|
529
|
+
try {
|
|
530
|
+
({ allowed, dropped } = this.partition(spans));
|
|
531
|
+
} catch (e) {
|
|
532
|
+
if (foreignClientSeen()) {
|
|
533
|
+
this.warnDropped(spans.length);
|
|
534
|
+
resultCallback({ code: EXPORT_FAILED2 });
|
|
535
|
+
return;
|
|
536
|
+
}
|
|
537
|
+
this.inner.export(spans, resultCallback);
|
|
538
|
+
return;
|
|
539
|
+
}
|
|
540
|
+
if (dropped) {
|
|
541
|
+
this.warnDropped(dropped);
|
|
542
|
+
}
|
|
543
|
+
if (allowed.length === 0) {
|
|
544
|
+
resultCallback({ code: EXPORT_SUCCESS2 });
|
|
545
|
+
return;
|
|
546
|
+
}
|
|
547
|
+
this.inner.export(allowed, resultCallback);
|
|
548
|
+
}
|
|
549
|
+
shutdown() {
|
|
550
|
+
return this.inner.shutdown();
|
|
551
|
+
}
|
|
552
|
+
forceFlush() {
|
|
553
|
+
return this.inner.forceFlush ? this.inner.forceFlush() : Promise.resolve();
|
|
554
|
+
}
|
|
555
|
+
};
|
|
556
|
+
function buildGuardedExporter(baseUrl, headers, ownerAuthHint) {
|
|
557
|
+
const inner = new OTLPProtoTraceExporter2({
|
|
558
|
+
url: `${baseUrl}/v1/traces`,
|
|
559
|
+
headers
|
|
560
|
+
});
|
|
561
|
+
return new GuardedSpanExporter(inner, ownerAuthHint);
|
|
562
|
+
}
|
|
563
|
+
function pipelineOwnerHint() {
|
|
564
|
+
return getState().ownerAuthHint;
|
|
565
|
+
}
|
|
566
|
+
function claimPipeline(authHint, projectId) {
|
|
567
|
+
const state = getState();
|
|
568
|
+
if (state.pipelineClaimed) {
|
|
569
|
+
return false;
|
|
570
|
+
}
|
|
571
|
+
state.pipelineClaimed = true;
|
|
572
|
+
state.ownerAuthHint = authHint;
|
|
573
|
+
state.ownerProjectId = projectId;
|
|
574
|
+
if (state.foreignClientSeen && state.pendingMultiKeyWarning) {
|
|
575
|
+
emitMultiKeyWarningOnce();
|
|
576
|
+
}
|
|
577
|
+
return true;
|
|
578
|
+
}
|
|
579
|
+
function releasePipelineClaim() {
|
|
580
|
+
const state = getState();
|
|
581
|
+
state.pipelineClaimed = false;
|
|
582
|
+
state.ownerAuthHint = void 0;
|
|
583
|
+
state.ownerProjectId = void 0;
|
|
584
|
+
}
|
|
585
|
+
function markTraceloopConfiguredWithoutClaim() {
|
|
586
|
+
getState().traceloopConfiguredWithoutClaim = true;
|
|
587
|
+
}
|
|
588
|
+
function traceloopConfiguredWithoutClaim() {
|
|
589
|
+
return getState().traceloopConfiguredWithoutClaim;
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
// src/tracing/tracer-core.ts
|
|
593
|
+
import { SpanStatusCode as SpanStatusCode4, context as context6, trace as trace6 } from "@opentelemetry/api";
|
|
594
|
+
import { OTLPTraceExporter as OTLPHttpTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
|
|
595
|
+
import { AnthropicInstrumentation } from "@traceloop/instrumentation-anthropic";
|
|
596
|
+
import { BedrockInstrumentation } from "@traceloop/instrumentation-bedrock";
|
|
597
|
+
import { ChromaDBInstrumentation } from "@traceloop/instrumentation-chromadb";
|
|
598
|
+
import { CohereInstrumentation } from "@traceloop/instrumentation-cohere";
|
|
599
|
+
import { LangChainInstrumentation } from "@traceloop/instrumentation-langchain";
|
|
600
|
+
import { LlamaIndexInstrumentation } from "@traceloop/instrumentation-llamaindex";
|
|
601
|
+
import { OpenAIInstrumentation } from "@traceloop/instrumentation-openai";
|
|
602
|
+
import { PineconeInstrumentation } from "@traceloop/instrumentation-pinecone";
|
|
603
|
+
import { QdrantInstrumentation } from "@traceloop/instrumentation-qdrant";
|
|
604
|
+
import { TogetherInstrumentation } from "@traceloop/instrumentation-together";
|
|
605
|
+
import {
|
|
606
|
+
AIPlatformInstrumentation,
|
|
607
|
+
VertexAIInstrumentation
|
|
608
|
+
} from "@traceloop/instrumentation-vertexai";
|
|
609
|
+
import { WeakValueMap } from "weakref";
|
|
610
|
+
|
|
611
|
+
// src/tracing/direct/context.ts
|
|
612
|
+
import { TraceFlags, context, isValidSpanId, isValidTraceId, trace } from "@opentelemetry/api";
|
|
613
|
+
|
|
614
|
+
// src/tracing/direct/ids.ts
|
|
615
|
+
function getCrypto() {
|
|
616
|
+
const c = globalThis.crypto;
|
|
617
|
+
return c;
|
|
618
|
+
}
|
|
619
|
+
function randomBytes(length) {
|
|
620
|
+
const cryptoObj = getCrypto();
|
|
621
|
+
const out = new Uint8Array(length);
|
|
622
|
+
if (cryptoObj && typeof cryptoObj.getRandomValues === "function") {
|
|
623
|
+
cryptoObj.getRandomValues(out);
|
|
624
|
+
return out;
|
|
625
|
+
}
|
|
626
|
+
for (let i = 0; i < out.length; i++) out[i] = Math.floor(Math.random() * 256);
|
|
627
|
+
return out;
|
|
628
|
+
}
|
|
629
|
+
function base64Encode(bytes) {
|
|
630
|
+
const maybeBuffer = globalThis.Buffer;
|
|
631
|
+
if (maybeBuffer) {
|
|
632
|
+
return maybeBuffer.from(bytes).toString("base64");
|
|
633
|
+
}
|
|
634
|
+
let binary = "";
|
|
635
|
+
for (let i2 = 0; i2 < bytes.length; i2++) {
|
|
636
|
+
binary += String.fromCharCode(bytes[i2]);
|
|
637
|
+
}
|
|
638
|
+
const btoaFn = globalThis.btoa;
|
|
639
|
+
if (typeof btoaFn === "function") return btoaFn(binary);
|
|
640
|
+
const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
641
|
+
let out = "";
|
|
642
|
+
let i = 0;
|
|
643
|
+
while (i < binary.length) {
|
|
644
|
+
const c1 = binary.charCodeAt(i++) & 255;
|
|
645
|
+
const c2 = i < binary.length ? binary.charCodeAt(i++) & 255 : NaN;
|
|
646
|
+
const c3 = i < binary.length ? binary.charCodeAt(i++) & 255 : NaN;
|
|
647
|
+
const e1 = c1 >> 2;
|
|
648
|
+
const e2 = (c1 & 3) << 4 | (Number.isNaN(c2) ? 0 : c2 >> 4);
|
|
649
|
+
const e3 = Number.isNaN(c2) ? 64 : (c2 & 15) << 2 | (Number.isNaN(c3) ? 0 : c3 >> 6);
|
|
650
|
+
const e4 = Number.isNaN(c3) ? 64 : c3 & 63;
|
|
651
|
+
out += alphabet.charAt(e1);
|
|
652
|
+
out += alphabet.charAt(e2);
|
|
653
|
+
out += e3 === 64 ? "=" : alphabet.charAt(e3);
|
|
654
|
+
out += e4 === 64 ? "=" : alphabet.charAt(e4);
|
|
655
|
+
}
|
|
656
|
+
return out;
|
|
657
|
+
}
|
|
658
|
+
function base64ToHex(base64) {
|
|
659
|
+
const maybeBuffer = globalThis.Buffer;
|
|
660
|
+
if (maybeBuffer) {
|
|
661
|
+
return maybeBuffer.from(base64, "base64").toString("hex");
|
|
662
|
+
}
|
|
663
|
+
const atobFn = globalThis.atob;
|
|
664
|
+
if (typeof atobFn === "function") {
|
|
665
|
+
const binary = atobFn(base64);
|
|
666
|
+
let hex = "";
|
|
667
|
+
for (let i = 0; i < binary.length; i++) {
|
|
668
|
+
hex += binary.charCodeAt(i).toString(16).padStart(2, "0");
|
|
669
|
+
}
|
|
670
|
+
return hex;
|
|
671
|
+
}
|
|
672
|
+
throw new Error("No base64 decoder available in this runtime");
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
// src/tracing/direct/context.ts
|
|
676
|
+
var INVALID_TRACE_ID = "00000000000000000000000000000000";
|
|
677
|
+
var INVALID_SPAN_ID = "0000000000000000";
|
|
678
|
+
function hexToBase64(hex) {
|
|
679
|
+
const bytes = new Uint8Array(hex.length / 2);
|
|
680
|
+
for (let i = 0; i < hex.length; i += 2) {
|
|
681
|
+
bytes[i / 2] = parseInt(hex.substring(i, i + 2), 16);
|
|
682
|
+
}
|
|
683
|
+
return base64Encode(bytes);
|
|
684
|
+
}
|
|
685
|
+
function getExplicitTraceContext(traceId, parentSpanId) {
|
|
686
|
+
if (!traceId || !parentSpanId || !isValidTraceId(traceId) || !isValidSpanId(parentSpanId)) {
|
|
687
|
+
return void 0;
|
|
688
|
+
}
|
|
689
|
+
return {
|
|
690
|
+
traceIdB64: hexToBase64(traceId),
|
|
691
|
+
parentSpanIdB64: hexToBase64(parentSpanId)
|
|
692
|
+
};
|
|
693
|
+
}
|
|
694
|
+
function getActiveTraceContext() {
|
|
695
|
+
const activeSpan = trace.getSpan(context.active());
|
|
696
|
+
if (!activeSpan) return {};
|
|
697
|
+
const spanContext = activeSpan.spanContext();
|
|
698
|
+
const traceIdHex = spanContext.traceId;
|
|
699
|
+
const spanIdHex = spanContext.spanId;
|
|
700
|
+
if (traceIdHex === INVALID_TRACE_ID) return {};
|
|
701
|
+
return {
|
|
702
|
+
traceIdB64: hexToBase64(traceIdHex),
|
|
703
|
+
parentSpanIdB64: spanIdHex !== INVALID_SPAN_ID ? hexToBase64(spanIdHex) : void 0
|
|
704
|
+
};
|
|
705
|
+
}
|
|
706
|
+
function savedParentContext(traceId, parentSpanId) {
|
|
707
|
+
if (!traceId || !parentSpanId || !isValidTraceId(traceId) || !isValidSpanId(parentSpanId)) {
|
|
708
|
+
return void 0;
|
|
709
|
+
}
|
|
710
|
+
return trace.setSpanContext(context.active(), {
|
|
711
|
+
traceId,
|
|
712
|
+
spanId: parentSpanId,
|
|
713
|
+
traceFlags: TraceFlags.SAMPLED,
|
|
714
|
+
isRemote: true
|
|
715
|
+
});
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
// src/tracing/direct/http.ts
|
|
719
|
+
function formatEndpoint(endpoint) {
|
|
720
|
+
if (!endpoint) return void 0;
|
|
721
|
+
return endpoint.endsWith("/") ? endpoint : `${endpoint}/`;
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
// src/tracing/direct/otlp.ts
|
|
725
|
+
var libraryVersion = package_default.version;
|
|
726
|
+
var SERVICE_NAME = "raindrop-ai";
|
|
727
|
+
function attrString2(key, value) {
|
|
728
|
+
if (value === void 0) return void 0;
|
|
729
|
+
return { key, value: { stringValue: value } };
|
|
730
|
+
}
|
|
731
|
+
function attrInt(key, value) {
|
|
732
|
+
if (value === void 0) return void 0;
|
|
733
|
+
if (!Number.isFinite(value)) return void 0;
|
|
734
|
+
return { key, value: { intValue: String(Math.trunc(value)) } };
|
|
735
|
+
}
|
|
736
|
+
function buildOtlpSpan(args) {
|
|
737
|
+
const attrs = args.attributes.filter((x) => x !== void 0);
|
|
738
|
+
const span = {
|
|
739
|
+
traceId: args.ids.traceIdB64,
|
|
740
|
+
spanId: args.ids.spanIdB64,
|
|
741
|
+
name: args.name,
|
|
742
|
+
startTimeUnixNano: args.startTimeUnixNano,
|
|
743
|
+
endTimeUnixNano: args.endTimeUnixNano
|
|
744
|
+
};
|
|
745
|
+
if (args.ids.parentSpanIdB64) span.parentSpanId = args.ids.parentSpanIdB64;
|
|
746
|
+
if (attrs.length) span.attributes = attrs;
|
|
747
|
+
if (args.status) span.status = args.status;
|
|
748
|
+
return span;
|
|
749
|
+
}
|
|
750
|
+
function buildExportTraceServiceRequest(spans) {
|
|
751
|
+
return {
|
|
752
|
+
resourceSpans: [
|
|
753
|
+
{
|
|
754
|
+
resource: {
|
|
755
|
+
attributes: [{ key: "service.name", value: { stringValue: SERVICE_NAME } }]
|
|
756
|
+
},
|
|
757
|
+
scopeSpans: [
|
|
758
|
+
{
|
|
759
|
+
scope: { name: SERVICE_NAME, version: libraryVersion },
|
|
760
|
+
spans
|
|
761
|
+
}
|
|
762
|
+
]
|
|
763
|
+
}
|
|
764
|
+
]
|
|
765
|
+
};
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
// src/tracing/direct/shipper.ts
|
|
769
|
+
function serializeAssociationValue(value) {
|
|
770
|
+
return stringifyBounded(value);
|
|
771
|
+
}
|
|
772
|
+
var DirectTraceShipper = class {
|
|
773
|
+
constructor(opts) {
|
|
774
|
+
this.queue = [];
|
|
775
|
+
this.inFlight = /* @__PURE__ */ new Set();
|
|
776
|
+
/** Cuts off sends still running at a flush or shutdown deadline. */
|
|
777
|
+
this.cutOff = new InFlightCutOff();
|
|
778
|
+
/**
|
|
779
|
+
* Set once `shutdown()` begins and never cleared. Sends issued after the
|
|
780
|
+
* drain window (stragglers, or flush work the deadline abandoned
|
|
781
|
+
* mid-drain) run as a single short attempt instead of regaining the full
|
|
782
|
+
* retry schedule.
|
|
783
|
+
*/
|
|
784
|
+
this.hasShutdown = false;
|
|
785
|
+
var _a, _b, _c, _d, _e, _f;
|
|
786
|
+
this.appGitSnapshot = opts.appGitSnapshot;
|
|
787
|
+
this.writeKey = opts.writeKey;
|
|
788
|
+
this.baseUrl = (_a = formatEndpoint(opts.endpoint)) != null ? _a : "https://api.raindrop.ai/v1/";
|
|
789
|
+
this.enabled = (_b = opts.enabled) != null ? _b : true;
|
|
790
|
+
this.cloudEnabled = (_c = opts.cloudEnabled) != null ? _c : true;
|
|
791
|
+
this.debug = opts.debug;
|
|
792
|
+
this.projectId = opts.projectId;
|
|
793
|
+
this.redactTracePii = opts.redactTracePii;
|
|
794
|
+
this.remotePiiConfig = opts.remotePiiConfig;
|
|
795
|
+
this.spanPiiFields = opts.spanPiiFields;
|
|
796
|
+
this.mask = opts.mask;
|
|
797
|
+
this.flushIntervalMs = (_d = opts.flushIntervalMs) != null ? _d : 1e3;
|
|
798
|
+
this.maxBatchSize = (_e = opts.maxBatchSize) != null ? _e : 50;
|
|
799
|
+
this.maxQueueSize = (_f = opts.maxQueueSize) != null ? _f : 5e3;
|
|
800
|
+
this.flushTimeoutMs = resolveFlushTimeoutMs(opts.flushTimeoutMs);
|
|
801
|
+
const resolved = resolveLocalDebuggerBaseUrl(opts.localDebuggerUrl);
|
|
802
|
+
if (resolved && resolved !== this.baseUrl) {
|
|
803
|
+
this.localDebuggerUrl = resolved;
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
applicationGitSnapshot(properties) {
|
|
807
|
+
var _a, _b, _c, _d;
|
|
808
|
+
try {
|
|
809
|
+
return (_d = (_c = (_a = this.appGitSnapshot) == null ? void 0 : _a.call(this, properties)) != null ? _c : (_b = currentRoutingBinding()) == null ? void 0 : _b.appGit) != null ? _d : {};
|
|
810
|
+
} catch (e) {
|
|
811
|
+
return {};
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
/**
|
|
815
|
+
* Build and enqueue an OTLP span for a trackTool call.
|
|
816
|
+
*
|
|
817
|
+
* Reads the active OTEL context if traceId/parentSpanId are not provided,
|
|
818
|
+
* so spans still appear as children in the trace tree.
|
|
819
|
+
*/
|
|
820
|
+
sendSpan(params) {
|
|
821
|
+
var _a, _b, _c;
|
|
822
|
+
if (!this.enabled) return;
|
|
823
|
+
let traceIdB64 = params.traceId;
|
|
824
|
+
let parentSpanIdB64 = params.parentSpanId;
|
|
825
|
+
if (!traceIdB64) {
|
|
826
|
+
const activeCtx = getActiveTraceContext();
|
|
827
|
+
traceIdB64 = activeCtx.traceIdB64;
|
|
828
|
+
parentSpanIdB64 = activeCtx.parentSpanIdB64;
|
|
829
|
+
}
|
|
830
|
+
const spanIdB64 = (_a = params.spanId) != null ? _a : base64Encode(randomBytes(8));
|
|
831
|
+
if (!traceIdB64) {
|
|
832
|
+
traceIdB64 = base64Encode(randomBytes(16));
|
|
833
|
+
}
|
|
834
|
+
const startTimeUnixNano = String(params.startTimeMs * 1e6);
|
|
835
|
+
const endTimeUnixNano = String(params.endTimeMs * 1e6);
|
|
836
|
+
const attributes = [
|
|
837
|
+
// Required: passes hasAIOperation() filter in backend (parseSpan.ts)
|
|
838
|
+
attrString2("traceloop.span.kind", (_b = params.spanKind) != null ? _b : "tool"),
|
|
839
|
+
// Parsed by backend for input/output payloads
|
|
840
|
+
attrString2("traceloop.entity.input", params.input),
|
|
841
|
+
attrString2("traceloop.entity.output", params.output),
|
|
842
|
+
// Duration tracking
|
|
843
|
+
attrInt("traceloop.entity.duration_ms", params.durationMs),
|
|
844
|
+
// Per-span project routing: the ingest boundary routes on this attribute
|
|
845
|
+
// (org-validated) and falls back to the request's project header. Direct
|
|
846
|
+
// spans ship on this instance's own key, so no cross-key auth hint.
|
|
847
|
+
attrString2(PROJECT_ID_SPAN_ATTRIBUTE, this.projectId)
|
|
848
|
+
];
|
|
849
|
+
for (const [key, value] of Object.entries(params.properties)) {
|
|
850
|
+
if (value === void 0) {
|
|
851
|
+
continue;
|
|
852
|
+
}
|
|
853
|
+
attributes.push(
|
|
854
|
+
attrString2(`traceloop.association.properties.${key}`, serializeAssociationValue(value))
|
|
855
|
+
);
|
|
856
|
+
}
|
|
857
|
+
const spanIdentity = { spanIdB64 };
|
|
858
|
+
claimSpanForFrames(spanIdentity);
|
|
859
|
+
for (const [key, value] of Object.entries({
|
|
860
|
+
...currentSpanAttributes(),
|
|
861
|
+
...params.attributes,
|
|
862
|
+
// Last, so neither a bound frame nor an explicit caller attribute can
|
|
863
|
+
// shadow the replay row a span belongs to.
|
|
864
|
+
...evalScopeAttributes()
|
|
865
|
+
})) {
|
|
866
|
+
attributes.push(attrString2(key, value));
|
|
867
|
+
}
|
|
868
|
+
attributes.push(...(_c = params.otlpAttributes) != null ? _c : []);
|
|
869
|
+
let status;
|
|
870
|
+
if (params.error) {
|
|
871
|
+
status = { code: 2, message: params.error };
|
|
872
|
+
markErrorSpanSeen(spanIdentity);
|
|
873
|
+
} else {
|
|
874
|
+
status = {
|
|
875
|
+
code: 1
|
|
876
|
+
/* STATUS_CODE_OK */
|
|
877
|
+
};
|
|
878
|
+
}
|
|
879
|
+
const span = buildOtlpSpan({
|
|
880
|
+
ids: {
|
|
881
|
+
traceIdB64,
|
|
882
|
+
spanIdB64,
|
|
883
|
+
parentSpanIdB64
|
|
884
|
+
},
|
|
885
|
+
name: params.name,
|
|
886
|
+
startTimeUnixNano,
|
|
887
|
+
endTimeUnixNano,
|
|
888
|
+
attributes: withAppGitAttributes(
|
|
889
|
+
attributes,
|
|
890
|
+
params.appGitSnapshot !== void 0 ? params.appGitSnapshot : this.applicationGitSnapshot(params.properties)
|
|
891
|
+
),
|
|
892
|
+
status
|
|
893
|
+
});
|
|
894
|
+
const replayDestination = currentReplayTraceDestination();
|
|
895
|
+
recordReplayExportedSpan(
|
|
896
|
+
replayDestination,
|
|
897
|
+
base64ToHex(span.spanId),
|
|
898
|
+
base64ToHex(span.traceId)
|
|
899
|
+
);
|
|
900
|
+
const mirrorUrl = (replayDestination == null ? void 0 : replayDestination.kind) === "workshop" ? replayDestination.url : replayDestination ? void 0 : this.localDebuggerUrl;
|
|
901
|
+
const mirrored = mirrorUrl && this.redactsNow() ? this.redactSpanPii(span) : span;
|
|
902
|
+
if (mirrorUrl && mirrored) {
|
|
903
|
+
const body = buildExportTraceServiceRequest([maskOtlpSpan(mirrored, this.mask, this.spanPiiFields, "[raindrop]")]);
|
|
904
|
+
const mirror = mirrorTraceExportToLocalDebugger(body, {
|
|
905
|
+
baseUrl: mirrorUrl,
|
|
906
|
+
debug: false,
|
|
907
|
+
sdkName: "js-sdk"
|
|
908
|
+
});
|
|
909
|
+
this.inFlight.add(mirror);
|
|
910
|
+
void mirror.finally(() => this.inFlight.delete(mirror));
|
|
911
|
+
}
|
|
912
|
+
this.enqueue({ span, replayDestination });
|
|
913
|
+
if (this.debug) {
|
|
914
|
+
console.log(`[raindrop] direct shipper: enqueued span "${params.name}"`);
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
/**
|
|
918
|
+
* Whether to redact, never waiting: a local mirror uses what is known now,
|
|
919
|
+
* and a remote setting still being looked up counts as unknown.
|
|
920
|
+
*/
|
|
921
|
+
redactsNow() {
|
|
922
|
+
var _a;
|
|
923
|
+
const writeKey = this.cloudEnabled ? this.writeKey : void 0;
|
|
924
|
+
return (_a = piiRedactionNow(this.redactTracePii, this.remotePiiConfig, this.baseUrl, writeKey)) != null ? _a : resolvePiiRedaction(this.redactTracePii, this.remotePiiConfig, "unknown");
|
|
925
|
+
}
|
|
926
|
+
/** The span with PII redacted from its input and output; undefined if redaction failed. */
|
|
927
|
+
redactSpanPii(span) {
|
|
928
|
+
try {
|
|
929
|
+
return redactPiiInOtlpSpan(span, this.spanPiiFields, resolveMaxTextFieldChars(void 0));
|
|
930
|
+
} catch (e) {
|
|
931
|
+
return void 0;
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
sendToolSpan(params) {
|
|
935
|
+
this.sendSpan({
|
|
936
|
+
...params,
|
|
937
|
+
spanKind: "tool"
|
|
938
|
+
});
|
|
939
|
+
}
|
|
940
|
+
enqueue(queued) {
|
|
941
|
+
if (!this.enabled) return;
|
|
942
|
+
if (this.queue.length >= this.maxQueueSize) {
|
|
943
|
+
this.queue.shift();
|
|
944
|
+
}
|
|
945
|
+
this.queue.push(queued);
|
|
946
|
+
if (this.queue.length >= this.maxBatchSize) {
|
|
947
|
+
void this.drain().catch(() => {
|
|
948
|
+
});
|
|
949
|
+
return;
|
|
950
|
+
}
|
|
951
|
+
this.scheduleDrain(this.flushIntervalMs);
|
|
952
|
+
}
|
|
953
|
+
scheduleDrain(delayMs) {
|
|
954
|
+
if (this.timer) return;
|
|
955
|
+
this.timer = setTimeout(() => {
|
|
956
|
+
this.timer = void 0;
|
|
957
|
+
void this.drain().catch(() => {
|
|
958
|
+
});
|
|
959
|
+
}, delayMs);
|
|
960
|
+
}
|
|
961
|
+
/**
|
|
962
|
+
* Send every queued span within `flushTimeoutMs` (CONTRACT 1.2.1). Resolves,
|
|
963
|
+
* never rejects; spans not yet sent at the deadline stay queued.
|
|
964
|
+
*/
|
|
965
|
+
async flush() {
|
|
966
|
+
const result = await this.drainWithin(Date.now() + this.flushTimeoutMs);
|
|
967
|
+
if (!result.delivered && this.shutdownDeadlineAt === void 0) {
|
|
968
|
+
rateLimitedLog(
|
|
969
|
+
"js-sdk.direct.flush_undelivered",
|
|
970
|
+
() => console.warn(`[raindrop] direct: ${describeUndelivered("flush()", result)}`)
|
|
971
|
+
);
|
|
972
|
+
}
|
|
973
|
+
return asCompat(result);
|
|
974
|
+
}
|
|
975
|
+
async drainWithin(deadlineAt) {
|
|
976
|
+
const earlier = [...this.inFlight];
|
|
977
|
+
const fates = this.enabled ? await this.drain(deadlineAt) : [];
|
|
978
|
+
const { settled, stillRunning } = await awaitEarlierSends(
|
|
979
|
+
earlier,
|
|
980
|
+
deadlineAt,
|
|
981
|
+
this.cutOff,
|
|
982
|
+
(p) => this.inFlight.has(p)
|
|
983
|
+
);
|
|
984
|
+
return summarize2(fates, stillRunning, !settled);
|
|
985
|
+
}
|
|
986
|
+
async drain(deadlineAt) {
|
|
987
|
+
var _a, _b;
|
|
988
|
+
const fates = [];
|
|
989
|
+
if (!this.enabled) return fates;
|
|
990
|
+
if (this.timer) {
|
|
991
|
+
clearTimeout(this.timer);
|
|
992
|
+
this.timer = void 0;
|
|
993
|
+
}
|
|
994
|
+
if (this.queue.length === 0) return fates;
|
|
995
|
+
const writeKey = this.cloudEnabled ? this.writeKey : void 0;
|
|
996
|
+
const redactPii = (_a = piiRedactionNow(this.redactTracePii, this.remotePiiConfig, this.baseUrl, writeKey)) != null ? _a : await piiRedaction(
|
|
997
|
+
this.redactTracePii,
|
|
998
|
+
this.remotePiiConfig,
|
|
999
|
+
this.baseUrl,
|
|
1000
|
+
writeKey,
|
|
1001
|
+
deadlineAt
|
|
1002
|
+
);
|
|
1003
|
+
while (this.queue.length > 0) {
|
|
1004
|
+
const batch = this.queue.splice(0, this.maxBatchSize);
|
|
1005
|
+
const opts = this.requestOpts(deadlineAt);
|
|
1006
|
+
if (!opts) {
|
|
1007
|
+
rateLimitedLog(
|
|
1008
|
+
"js-sdk.direct.shutdown_deadline",
|
|
1009
|
+
() => console.warn(
|
|
1010
|
+
`[raindrop] direct: shutdown flush deadline exceeded; dropping ${batch.length} spans`
|
|
1011
|
+
)
|
|
1012
|
+
);
|
|
1013
|
+
fates.push("dropped");
|
|
1014
|
+
continue;
|
|
1015
|
+
}
|
|
1016
|
+
const groups = /* @__PURE__ */ new Map();
|
|
1017
|
+
for (const queued of batch) {
|
|
1018
|
+
const spans = groups.get(queued.replayDestination);
|
|
1019
|
+
if (spans) spans.push(queued);
|
|
1020
|
+
else groups.set(queued.replayDestination, [queued]);
|
|
1021
|
+
}
|
|
1022
|
+
const requeue = [];
|
|
1023
|
+
let retryAtMs;
|
|
1024
|
+
for (const [replayDestination, queuedSpans] of groups) {
|
|
1025
|
+
if (!replayDestination && !this.cloudEnabled) continue;
|
|
1026
|
+
if ((replayDestination == null ? void 0 : replayDestination.kind) === "workshop") continue;
|
|
1027
|
+
const spans = queuedSpans.map((q) => q.span);
|
|
1028
|
+
const outgoing = (redactPii ? spans.flatMap((span) => {
|
|
1029
|
+
var _a2;
|
|
1030
|
+
return (_a2 = this.redactSpanPii(span)) != null ? _a2 : [];
|
|
1031
|
+
}) : spans).map((span) => maskOtlpSpan(span, this.mask, this.spanPiiFields, "[raindrop]"));
|
|
1032
|
+
if (outgoing.length === 0) continue;
|
|
1033
|
+
const body = buildExportTraceServiceRequest(outgoing);
|
|
1034
|
+
const url = replayDestination ? replayTraceUrl(replayDestination.url) : `${this.baseUrl}traces`;
|
|
1035
|
+
const headers = replayDestination ? {
|
|
1036
|
+
Authorization: `Bearer ${replayDestination.apiKey}`,
|
|
1037
|
+
"X-Raindrop-Replay-Id": replayDestination.replayId,
|
|
1038
|
+
"X-Raindrop-Project-Id": (_b = replayDestination.projectId) != null ? _b : "default"
|
|
1039
|
+
} : { Authorization: `Bearer ${this.writeKey}`, ...projectIdHeaders(this.projectId) };
|
|
1040
|
+
const sending = sendJson(url, body, headers, opts);
|
|
1041
|
+
const tracked = sending.then(() => void 0);
|
|
1042
|
+
this.inFlight.add(tracked);
|
|
1043
|
+
let outcome;
|
|
1044
|
+
try {
|
|
1045
|
+
outcome = await sending;
|
|
1046
|
+
} finally {
|
|
1047
|
+
this.inFlight.delete(tracked);
|
|
1048
|
+
}
|
|
1049
|
+
const fate = fateOf(outcome, this.shutdownDeadlineAt !== void 0 || this.hasShutdown);
|
|
1050
|
+
fates.push(fate);
|
|
1051
|
+
if (fate === "queued") {
|
|
1052
|
+
requeue.push(...queuedSpans);
|
|
1053
|
+
if (outcome.status === "deferred" && outcome.retryAtMs !== void 0) {
|
|
1054
|
+
retryAtMs = Math.max(retryAtMs != null ? retryAtMs : 0, outcome.retryAtMs);
|
|
1055
|
+
}
|
|
1056
|
+
} else if (fate === "dropped") {
|
|
1057
|
+
const reason = outcome.status === "cut_off" ? "cut off at the flush deadline (not resent: it may have reached ingest)" : outcome.status === "deferred" ? "not sent before the shutdown deadline" : "error" in outcome && outcome.error ? outcome.error.message : outcome.status;
|
|
1058
|
+
rateLimitedLog(
|
|
1059
|
+
"js-sdk.direct.send_failed",
|
|
1060
|
+
() => console.warn(
|
|
1061
|
+
`[raindrop] direct: failed to send ${queuedSpans.length} spans (dropping): ${reason}`
|
|
1062
|
+
)
|
|
1063
|
+
);
|
|
1064
|
+
} else if (this.debug) {
|
|
1065
|
+
console.log(`[raindrop] direct: sent ${queuedSpans.length} spans`);
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
if (requeue.length > 0) {
|
|
1069
|
+
this.queue.unshift(...requeue);
|
|
1070
|
+
if (this.queue.length > this.maxQueueSize) this.queue.splice(this.maxQueueSize);
|
|
1071
|
+
this.scheduleDrain(Math.max(this.flushIntervalMs, (retryAtMs != null ? retryAtMs : 0) - Date.now()));
|
|
1072
|
+
break;
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
return fates;
|
|
1076
|
+
}
|
|
1077
|
+
/**
|
|
1078
|
+
* Retry/timeout options for one batch POST: the normal 3-attempt schedule,
|
|
1079
|
+
* bounded by a flush deadline when given; during shutdown, retries within
|
|
1080
|
+
* the shutdown window; `null` once the window is spent (caller drops the
|
|
1081
|
+
* batch). After shutdown() returns, stragglers run as a single short attempt.
|
|
1082
|
+
*/
|
|
1083
|
+
requestOpts(deadlineAt) {
|
|
1084
|
+
const opts = this.scheduleFor(deadlineAt);
|
|
1085
|
+
return opts && { ...opts, cutOff: this.cutOff.signal };
|
|
1086
|
+
}
|
|
1087
|
+
scheduleFor(deadlineAt) {
|
|
1088
|
+
if (this.shutdownDeadlineAt !== void 0) {
|
|
1089
|
+
if (this.shutdownDeadlineAt - Date.now() <= 0) return null;
|
|
1090
|
+
return {
|
|
1091
|
+
maxAttempts: 3,
|
|
1092
|
+
debug: this.debug,
|
|
1093
|
+
deadlineAt: Math.min(this.shutdownDeadlineAt, deadlineAt != null ? deadlineAt : Infinity)
|
|
1094
|
+
};
|
|
1095
|
+
}
|
|
1096
|
+
if (this.hasShutdown) {
|
|
1097
|
+
return { maxAttempts: 1, debug: this.debug, timeoutMs: POST_SHUTDOWN_TIMEOUT_MS };
|
|
1098
|
+
}
|
|
1099
|
+
return { maxAttempts: 3, debug: this.debug, deadlineAt };
|
|
1100
|
+
}
|
|
1101
|
+
/** Flush within `flushTimeoutMs` and stop; spans left at the deadline are dropped. */
|
|
1102
|
+
async shutdown() {
|
|
1103
|
+
this.hasShutdown = true;
|
|
1104
|
+
const deadlineAt = Date.now() + this.flushTimeoutMs;
|
|
1105
|
+
this.shutdownDeadlineAt = deadlineAt;
|
|
1106
|
+
let result = { ...DELIVERED };
|
|
1107
|
+
try {
|
|
1108
|
+
if (this.timer) {
|
|
1109
|
+
clearTimeout(this.timer);
|
|
1110
|
+
this.timer = void 0;
|
|
1111
|
+
}
|
|
1112
|
+
result = await this.drainWithin(deadlineAt);
|
|
1113
|
+
if (!result.delivered) {
|
|
1114
|
+
rateLimitedLog(
|
|
1115
|
+
"js-sdk.direct.shutdown_deadline",
|
|
1116
|
+
() => console.warn(`[raindrop] direct: ${describeUndelivered("shutdown()", result)}`)
|
|
1117
|
+
);
|
|
1118
|
+
}
|
|
1119
|
+
} finally {
|
|
1120
|
+
this.shutdownDeadlineAt = void 0;
|
|
1121
|
+
}
|
|
1122
|
+
return asCompat(result);
|
|
1123
|
+
}
|
|
1124
|
+
};
|
|
1125
|
+
|
|
1126
|
+
// src/tracing/otel-core/index.ts
|
|
1127
|
+
import {
|
|
1128
|
+
DiagConsoleLogger,
|
|
1129
|
+
DiagLogLevel,
|
|
1130
|
+
context as context2,
|
|
1131
|
+
diag,
|
|
1132
|
+
trace as trace2
|
|
1133
|
+
} from "@opentelemetry/api";
|
|
1134
|
+
import { suppressTracing } from "@opentelemetry/core";
|
|
1135
|
+
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
|
|
1136
|
+
import { registerInstrumentations } from "@opentelemetry/instrumentation";
|
|
1137
|
+
import * as resourceModule from "@opentelemetry/resources";
|
|
1138
|
+
import {
|
|
1139
|
+
BatchSpanProcessor,
|
|
1140
|
+
SimpleSpanProcessor
|
|
1141
|
+
} from "@opentelemetry/sdk-trace-base";
|
|
1142
|
+
import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node";
|
|
1143
|
+
import {
|
|
1144
|
+
CONTEXT_KEY_ALLOW_TRACE_CONTENT,
|
|
1145
|
+
SpanAttributes,
|
|
1146
|
+
TraceloopSpanKindValues
|
|
1147
|
+
} from "@traceloop/ai-semantic-conventions";
|
|
1148
|
+
var ALL_INSTRUMENTATION_LIBRARIES = "all";
|
|
1149
|
+
function redactSpanPii(span, fields) {
|
|
1150
|
+
const attributes = redactPiiInAttributeMap(span.attributes, fields);
|
|
1151
|
+
const message = span.status.message;
|
|
1152
|
+
const redactedMessage = message === void 0 ? void 0 : redactSpanContent(message);
|
|
1153
|
+
let eventsChanged = false;
|
|
1154
|
+
const events = span.events.map((event) => {
|
|
1155
|
+
const eventAttributes = event.attributes && redactPiiInAttributeMap(event.attributes, fields);
|
|
1156
|
+
if (!eventAttributes) return event;
|
|
1157
|
+
eventsChanged = true;
|
|
1158
|
+
return { ...event, attributes: eventAttributes };
|
|
1159
|
+
});
|
|
1160
|
+
if (!attributes && redactedMessage === message && !eventsChanged) return span;
|
|
1161
|
+
const view = Object.create(span);
|
|
1162
|
+
if (attributes) {
|
|
1163
|
+
Object.defineProperty(view, "attributes", { value: attributes, enumerable: true });
|
|
1164
|
+
}
|
|
1165
|
+
if (redactedMessage !== message) {
|
|
1166
|
+
Object.defineProperty(view, "status", {
|
|
1167
|
+
value: { ...span.status, message: redactedMessage },
|
|
1168
|
+
enumerable: true
|
|
1169
|
+
});
|
|
1170
|
+
}
|
|
1171
|
+
if (eventsChanged) {
|
|
1172
|
+
Object.defineProperty(view, "events", { value: events, enumerable: true });
|
|
1173
|
+
}
|
|
1174
|
+
copyReplayTraceDestination(span, view);
|
|
1175
|
+
return view;
|
|
1176
|
+
}
|
|
1177
|
+
function maskSpan(span, mask, fields) {
|
|
1178
|
+
const attributes = maskAttributeMap(span.attributes, mask, fields, "[raindrop]");
|
|
1179
|
+
const message = span.status.message;
|
|
1180
|
+
const nextMessage = message === void 0 ? void 0 : maskSpanStatusMessage(message, mask, "[raindrop]");
|
|
1181
|
+
let eventsChanged = false;
|
|
1182
|
+
const events = span.events.map((event) => {
|
|
1183
|
+
const eventAttributes = event.attributes && maskAttributeMap(event.attributes, mask, fields, "[raindrop]");
|
|
1184
|
+
if (!eventAttributes) return event;
|
|
1185
|
+
eventsChanged = true;
|
|
1186
|
+
return { ...event, attributes: eventAttributes };
|
|
1187
|
+
});
|
|
1188
|
+
if (!attributes && nextMessage === message && !eventsChanged) return span;
|
|
1189
|
+
const view = Object.create(span);
|
|
1190
|
+
if (attributes) {
|
|
1191
|
+
Object.defineProperty(view, "attributes", { value: attributes, enumerable: true });
|
|
1192
|
+
}
|
|
1193
|
+
if (nextMessage !== message) {
|
|
1194
|
+
Object.defineProperty(view, "status", {
|
|
1195
|
+
value: { ...span.status, message: nextMessage },
|
|
1196
|
+
enumerable: true
|
|
1197
|
+
});
|
|
1198
|
+
}
|
|
1199
|
+
if (eventsChanged) {
|
|
1200
|
+
Object.defineProperty(view, "events", { value: events, enumerable: true });
|
|
1201
|
+
}
|
|
1202
|
+
copyReplayTraceDestination(span, view);
|
|
1203
|
+
return view;
|
|
1204
|
+
}
|
|
1205
|
+
var PiiRedactingSpanExporter = class {
|
|
1206
|
+
constructor(inner, options) {
|
|
1207
|
+
this.inner = inner;
|
|
1208
|
+
this.options = options;
|
|
1209
|
+
/** Exports waiting for the org lookup; flush and shutdown wait for them. */
|
|
1210
|
+
this.pending = /* @__PURE__ */ new Set();
|
|
1211
|
+
}
|
|
1212
|
+
export(spans, resultCallback) {
|
|
1213
|
+
const { local, remote, apiUrl, writeKey, spanFields, mask } = this.options;
|
|
1214
|
+
const exportContext = context2.active();
|
|
1215
|
+
const run = (redact) => {
|
|
1216
|
+
let outgoing = spans;
|
|
1217
|
+
if (redact) {
|
|
1218
|
+
outgoing = [];
|
|
1219
|
+
for (const span of spans) {
|
|
1220
|
+
try {
|
|
1221
|
+
outgoing.push(redactSpanPii(span, spanFields));
|
|
1222
|
+
} catch (e) {
|
|
1223
|
+
}
|
|
1224
|
+
}
|
|
1225
|
+
}
|
|
1226
|
+
if (mask) outgoing = outgoing.map((span) => maskSpan(span, mask, spanFields));
|
|
1227
|
+
try {
|
|
1228
|
+
context2.with(exportContext, () => this.inner.export(outgoing, resultCallback));
|
|
1229
|
+
} catch (e) {
|
|
1230
|
+
resultCallback({ code: 1 });
|
|
1231
|
+
}
|
|
1232
|
+
};
|
|
1233
|
+
const sharedRequest = localTracePiiRedactionRequested(apiUrl, writeKey);
|
|
1234
|
+
const known = sharedRequest || piiRedactionNow(local, remote, apiUrl, writeKey);
|
|
1235
|
+
if (known !== void 0) {
|
|
1236
|
+
run(known);
|
|
1237
|
+
return;
|
|
1238
|
+
}
|
|
1239
|
+
const handedOff = piiRedaction(local, remote, apiUrl, writeKey).then(
|
|
1240
|
+
(redact) => new Promise((resolve) => {
|
|
1241
|
+
const callback = resultCallback;
|
|
1242
|
+
resultCallback = (result) => {
|
|
1243
|
+
resolve();
|
|
1244
|
+
callback(result);
|
|
1245
|
+
};
|
|
1246
|
+
run(redact || localTracePiiRedactionRequested(apiUrl, writeKey));
|
|
1247
|
+
})
|
|
1248
|
+
);
|
|
1249
|
+
this.pending.add(handedOff);
|
|
1250
|
+
void handedOff.finally(() => this.pending.delete(handedOff));
|
|
1251
|
+
}
|
|
1252
|
+
async drainPending() {
|
|
1253
|
+
if (this.pending.size > 0) await Promise.allSettled([...this.pending]);
|
|
1254
|
+
}
|
|
1255
|
+
async shutdown() {
|
|
1256
|
+
await this.drainPending();
|
|
1257
|
+
return this.inner.shutdown();
|
|
1258
|
+
}
|
|
1259
|
+
async forceFlush() {
|
|
1260
|
+
var _a, _b, _c;
|
|
1261
|
+
await this.drainPending();
|
|
1262
|
+
return (_c = (_b = (_a = this.inner).forceFlush) == null ? void 0 : _b.call(_a)) != null ? _c : Promise.resolve();
|
|
1263
|
+
}
|
|
1264
|
+
};
|
|
1265
|
+
var TRACER_NAME = "@traceloop/node-server-sdk";
|
|
1266
|
+
var WORKFLOW_NAME_KEY = /* @__PURE__ */ Symbol.for("raindrop.otelCore.workflowName");
|
|
1267
|
+
var ENTITY_NAME_KEY = /* @__PURE__ */ Symbol.for("raindrop.otelCore.entityName");
|
|
1268
|
+
var ASSOCIATION_PROPERTIES_KEY = /* @__PURE__ */ Symbol.for("raindrop.otelCore.associationProperties");
|
|
1269
|
+
var INSTRUMENTATION_LIBRARIES = [
|
|
1270
|
+
"ai",
|
|
1271
|
+
"@traceloop/node-server-sdk",
|
|
1272
|
+
"@traceloop/instrumentation-openai",
|
|
1273
|
+
"@traceloop/instrumentation-langchain",
|
|
1274
|
+
"@traceloop/instrumentation-chroma",
|
|
1275
|
+
"@traceloop/instrumentation-chromadb",
|
|
1276
|
+
"@traceloop/instrumentation-anthropic",
|
|
1277
|
+
"@traceloop/instrumentation-llamaindex",
|
|
1278
|
+
"@traceloop/instrumentation-vertexai",
|
|
1279
|
+
"@traceloop/instrumentation-bedrock",
|
|
1280
|
+
"@traceloop/instrumentation-cohere",
|
|
1281
|
+
"@traceloop/instrumentation-pinecone",
|
|
1282
|
+
"@traceloop/instrumentation-qdrant",
|
|
1283
|
+
"@traceloop/instrumentation-together",
|
|
1284
|
+
TRACER_NAME,
|
|
1285
|
+
"traceloop.tracer"
|
|
1286
|
+
];
|
|
1287
|
+
var AI_GENERATE_TEXT = "ai.generateText.doGenerate";
|
|
1288
|
+
var AI_STREAM_TEXT = "ai.streamText.doStream";
|
|
1289
|
+
var AI_RESPONSE_TEXT = "ai.response.text";
|
|
1290
|
+
var AI_PROMPT_MESSAGES = "ai.prompt.messages";
|
|
1291
|
+
var AI_PROMPT_TOKENS = "ai.usage.promptTokens";
|
|
1292
|
+
var AI_COMPLETION_TOKENS = "ai.usage.completionTokens";
|
|
1293
|
+
var AI_MODEL_PROVIDER = "ai.model.provider";
|
|
1294
|
+
var STATE_KEY2 = /* @__PURE__ */ Symbol.for("raindrop.otelCore.state");
|
|
1295
|
+
function getState2() {
|
|
1296
|
+
var _a;
|
|
1297
|
+
const holder = globalThis;
|
|
1298
|
+
(_a = holder[STATE_KEY2]) != null ? _a : holder[STATE_KEY2] = {};
|
|
1299
|
+
return holder[STATE_KEY2];
|
|
1300
|
+
}
|
|
1301
|
+
function parseHeaders(value) {
|
|
1302
|
+
const headers = {};
|
|
1303
|
+
if (!value) return headers;
|
|
1304
|
+
for (const pair of value.split(",")) {
|
|
1305
|
+
const separator = pair.indexOf("=");
|
|
1306
|
+
if (separator <= 0) continue;
|
|
1307
|
+
try {
|
|
1308
|
+
const key = decodeURIComponent(pair.slice(0, separator).trim());
|
|
1309
|
+
const val = decodeURIComponent(pair.slice(separator + 1).trim());
|
|
1310
|
+
if (key && val) headers[key] = val;
|
|
1311
|
+
} catch (e) {
|
|
1312
|
+
}
|
|
1313
|
+
}
|
|
1314
|
+
return headers;
|
|
1315
|
+
}
|
|
1316
|
+
function safeStringify(value) {
|
|
1317
|
+
try {
|
|
1318
|
+
const result = JSON.stringify(value);
|
|
1319
|
+
return result === void 0 ? String(value) : result;
|
|
1320
|
+
} catch (e) {
|
|
1321
|
+
return "[unserializable]";
|
|
1322
|
+
}
|
|
1323
|
+
}
|
|
1324
|
+
function createResource(attributes) {
|
|
1325
|
+
if ("resourceFromAttributes" in resourceModule) {
|
|
1326
|
+
const factory = resourceModule.resourceFromAttributes;
|
|
1327
|
+
if (typeof factory === "function") return factory(attributes);
|
|
1328
|
+
}
|
|
1329
|
+
return new resourceModule.Resource(attributes);
|
|
1330
|
+
}
|
|
1331
|
+
function detectRuntimeResource() {
|
|
1332
|
+
try {
|
|
1333
|
+
if ("detectResourcesSync" in resourceModule && typeof resourceModule.detectResourcesSync === "function" && "envDetectorSync" in resourceModule) {
|
|
1334
|
+
return resourceModule.detectResourcesSync({
|
|
1335
|
+
detectors: [
|
|
1336
|
+
resourceModule.envDetectorSync,
|
|
1337
|
+
resourceModule.processDetectorSync,
|
|
1338
|
+
resourceModule.hostDetectorSync
|
|
1339
|
+
]
|
|
1340
|
+
});
|
|
1341
|
+
}
|
|
1342
|
+
if ("detectResources" in resourceModule && typeof resourceModule.detectResources === "function" && "envDetector" in resourceModule) {
|
|
1343
|
+
const detected = resourceModule.detectResources({
|
|
1344
|
+
detectors: [
|
|
1345
|
+
resourceModule.envDetector,
|
|
1346
|
+
resourceModule.processDetector,
|
|
1347
|
+
resourceModule.hostDetector
|
|
1348
|
+
]
|
|
1349
|
+
});
|
|
1350
|
+
if (!(detected instanceof Promise)) {
|
|
1351
|
+
return detected;
|
|
1352
|
+
}
|
|
1353
|
+
}
|
|
1354
|
+
} catch (e) {
|
|
1355
|
+
}
|
|
1356
|
+
return void 0;
|
|
1357
|
+
}
|
|
1358
|
+
function logLevel(level) {
|
|
1359
|
+
switch (level) {
|
|
1360
|
+
case "debug":
|
|
1361
|
+
return DiagLogLevel.DEBUG;
|
|
1362
|
+
case "info":
|
|
1363
|
+
return DiagLogLevel.INFO;
|
|
1364
|
+
case "warn":
|
|
1365
|
+
return DiagLogLevel.WARN;
|
|
1366
|
+
default:
|
|
1367
|
+
return DiagLogLevel.ERROR;
|
|
1368
|
+
}
|
|
1369
|
+
}
|
|
1370
|
+
function transformAiSdkSpan(span) {
|
|
1371
|
+
const names = {
|
|
1372
|
+
[AI_GENERATE_TEXT]: "ai.generateText.generate",
|
|
1373
|
+
[AI_STREAM_TEXT]: "ai.streamText.stream"
|
|
1374
|
+
};
|
|
1375
|
+
if (!(span.name in names)) return span;
|
|
1376
|
+
const attributes = span.attributes;
|
|
1377
|
+
if (AI_RESPONSE_TEXT in attributes) {
|
|
1378
|
+
const response = attributes[AI_RESPONSE_TEXT];
|
|
1379
|
+
if (typeof response === "string") {
|
|
1380
|
+
attributes[`${SpanAttributes.LLM_COMPLETIONS}.0.content`] = response;
|
|
1381
|
+
}
|
|
1382
|
+
attributes[`${SpanAttributes.LLM_COMPLETIONS}.0.role`] = "assistant";
|
|
1383
|
+
delete attributes[AI_RESPONSE_TEXT];
|
|
1384
|
+
}
|
|
1385
|
+
if (AI_PROMPT_MESSAGES in attributes) {
|
|
1386
|
+
try {
|
|
1387
|
+
const parsed = JSON.parse(String(attributes[AI_PROMPT_MESSAGES]));
|
|
1388
|
+
if (Array.isArray(parsed)) {
|
|
1389
|
+
parsed.forEach((message, index) => {
|
|
1390
|
+
if (!message || typeof message !== "object") return;
|
|
1391
|
+
const content = "content" in message ? message.content : void 0;
|
|
1392
|
+
const role = "role" in message ? message.role : void 0;
|
|
1393
|
+
attributes[`${SpanAttributes.LLM_PROMPTS}.${index}.content`] = typeof content === "string" ? content : safeStringify(content);
|
|
1394
|
+
if (typeof role === "string") {
|
|
1395
|
+
attributes[`${SpanAttributes.LLM_PROMPTS}.${index}.role`] = role;
|
|
1396
|
+
}
|
|
1397
|
+
});
|
|
1398
|
+
}
|
|
1399
|
+
delete attributes[AI_PROMPT_MESSAGES];
|
|
1400
|
+
} catch (e) {
|
|
1401
|
+
}
|
|
1402
|
+
}
|
|
1403
|
+
if (AI_PROMPT_TOKENS in attributes) {
|
|
1404
|
+
attributes[SpanAttributes.LLM_USAGE_PROMPT_TOKENS] = Number(attributes[AI_PROMPT_TOKENS]);
|
|
1405
|
+
delete attributes[AI_PROMPT_TOKENS];
|
|
1406
|
+
}
|
|
1407
|
+
if (AI_COMPLETION_TOKENS in attributes) {
|
|
1408
|
+
attributes[SpanAttributes.LLM_USAGE_COMPLETION_TOKENS] = Number(
|
|
1409
|
+
attributes[AI_COMPLETION_TOKENS]
|
|
1410
|
+
);
|
|
1411
|
+
delete attributes[AI_COMPLETION_TOKENS];
|
|
1412
|
+
}
|
|
1413
|
+
const prompt = attributes[SpanAttributes.LLM_USAGE_PROMPT_TOKENS];
|
|
1414
|
+
const completion = attributes[SpanAttributes.LLM_USAGE_COMPLETION_TOKENS];
|
|
1415
|
+
if (prompt !== void 0 && completion !== void 0) {
|
|
1416
|
+
attributes[SpanAttributes.LLM_USAGE_TOTAL_TOKENS] = Number(prompt) + Number(completion);
|
|
1417
|
+
}
|
|
1418
|
+
if (AI_MODEL_PROVIDER in attributes) {
|
|
1419
|
+
const vendor = String(attributes[AI_MODEL_PROVIDER]);
|
|
1420
|
+
attributes[SpanAttributes.LLM_SYSTEM] = vendor.startsWith("openai") ? "OpenAI" : vendor;
|
|
1421
|
+
delete attributes[AI_MODEL_PROVIDER];
|
|
1422
|
+
}
|
|
1423
|
+
Object.defineProperty(span, "name", {
|
|
1424
|
+
configurable: true,
|
|
1425
|
+
value: names[span.name],
|
|
1426
|
+
writable: true
|
|
1427
|
+
});
|
|
1428
|
+
return span;
|
|
1429
|
+
}
|
|
1430
|
+
function scopeName(span) {
|
|
1431
|
+
var _a;
|
|
1432
|
+
if ("instrumentationScope" in span) {
|
|
1433
|
+
const scope = span.instrumentationScope;
|
|
1434
|
+
if (scope && typeof scope === "object" && "name" in scope && typeof scope.name === "string") {
|
|
1435
|
+
return scope.name;
|
|
1436
|
+
}
|
|
1437
|
+
}
|
|
1438
|
+
return (_a = span.instrumentationLibrary) == null ? void 0 : _a.name;
|
|
1439
|
+
}
|
|
1440
|
+
function contentCaptureDisabled(options) {
|
|
1441
|
+
return options.traceContent === false || (process.env.TRACELOOP_TRACE_CONTENT || "true").toLowerCase() === "false";
|
|
1442
|
+
}
|
|
1443
|
+
function shouldSendTraceContent() {
|
|
1444
|
+
var _a;
|
|
1445
|
+
const contextual = context2.active().getValue(CONTEXT_KEY_ALLOW_TRACE_CONTENT);
|
|
1446
|
+
if (typeof contextual === "boolean") return contextual;
|
|
1447
|
+
if (((_a = getState2().configuration) == null ? void 0 : _a.traceContent) === false) return false;
|
|
1448
|
+
return (process.env.TRACELOOP_TRACE_CONTENT || "true").toLowerCase() !== "false";
|
|
1449
|
+
}
|
|
1450
|
+
function enrichStart(span) {
|
|
1451
|
+
const active = context2.active();
|
|
1452
|
+
const workflow = active.getValue(WORKFLOW_NAME_KEY);
|
|
1453
|
+
if (typeof workflow === "string")
|
|
1454
|
+
span.setAttribute(SpanAttributes.TRACELOOP_WORKFLOW_NAME, workflow);
|
|
1455
|
+
const entity = active.getValue(ENTITY_NAME_KEY);
|
|
1456
|
+
if (typeof entity === "string") span.setAttribute(SpanAttributes.TRACELOOP_ENTITY_PATH, entity);
|
|
1457
|
+
const properties = active.getValue(ASSOCIATION_PROPERTIES_KEY);
|
|
1458
|
+
if (properties && typeof properties === "object") {
|
|
1459
|
+
for (const [key, value] of Object.entries(properties)) {
|
|
1460
|
+
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
|
|
1461
|
+
span.setAttribute(`${SpanAttributes.TRACELOOP_ASSOCIATION_PROPERTIES}.${key}`, value);
|
|
1462
|
+
}
|
|
1463
|
+
}
|
|
1464
|
+
}
|
|
1465
|
+
}
|
|
1466
|
+
var PROMPT_TOOLS_OVERRIDE_MARKER = "raindrop.prompt_tools.override";
|
|
1467
|
+
var MODEL_SPAN_ATTRIBUTES = ["llm.request.type", "gen_ai.request.model", "ai.model.id"];
|
|
1468
|
+
function isModelSpan(attributes) {
|
|
1469
|
+
return MODEL_SPAN_ATTRIBUTES.some((key) => attributes[key] !== void 0);
|
|
1470
|
+
}
|
|
1471
|
+
function applyPromptTools(span) {
|
|
1472
|
+
var _a;
|
|
1473
|
+
const attributes = span.attributes;
|
|
1474
|
+
const marker = attributes[PROMPT_TOOLS_OVERRIDE_MARKER];
|
|
1475
|
+
if (marker !== void 0) {
|
|
1476
|
+
delete attributes[PROMPT_TOOLS_OVERRIDE_MARKER];
|
|
1477
|
+
if (!isModelSpan(attributes) || !shouldSendTraceContent()) return;
|
|
1478
|
+
let parsed;
|
|
1479
|
+
try {
|
|
1480
|
+
parsed = JSON.parse(String(marker));
|
|
1481
|
+
} catch (e) {
|
|
1482
|
+
return;
|
|
1483
|
+
}
|
|
1484
|
+
const tools = (_a = normalizeToolDeclarations(parsed)) != null ? _a : [];
|
|
1485
|
+
attributes[PROMPT_TOOLS_ATTRIBUTE] = promptToolsAttributeValue(tools);
|
|
1486
|
+
return;
|
|
1487
|
+
}
|
|
1488
|
+
if (attributes[PROMPT_TOOLS_ATTRIBUTE] !== void 0) return;
|
|
1489
|
+
if (!shouldSendTraceContent()) return;
|
|
1490
|
+
const inferred = promptToolsFromTraceloopAttributes(attributes);
|
|
1491
|
+
if (inferred === void 0) return;
|
|
1492
|
+
attributes[PROMPT_TOOLS_ATTRIBUTE] = promptToolsAttributeValue(inferred);
|
|
1493
|
+
}
|
|
1494
|
+
function createSpanProcessor(options) {
|
|
1495
|
+
var _a, _b;
|
|
1496
|
+
const baseUrl = options.baseUrl || process.env.TRACELOOP_BASE_URL || "https://api.traceloop.com";
|
|
1497
|
+
const apiKey = options.apiKey || process.env.TRACELOOP_API_KEY;
|
|
1498
|
+
const resolvedHeaders = (_a = options.headers) != null ? _a : process.env.TRACELOOP_HEADERS ? parseHeaders(process.env.TRACELOOP_HEADERS) : { Authorization: `Bearer ${apiKey}` };
|
|
1499
|
+
const baseExporter = (_b = options.exporter) != null ? _b : new OTLPTraceExporter({ url: `${baseUrl}/v1/traces`, headers: resolvedHeaders });
|
|
1500
|
+
const routed = options.routeReplayTraces ? new ReplayRoutingSpanExporter(baseExporter) : baseExporter;
|
|
1501
|
+
const exporter = options.piiRedaction ? new PiiRedactingSpanExporter(routed, options.piiRedaction) : routed;
|
|
1502
|
+
const processor = options.disableBatch ? new SimpleSpanProcessor(exporter) : new BatchSpanProcessor(exporter);
|
|
1503
|
+
const originalOnStart = processor.onStart.bind(processor);
|
|
1504
|
+
const originalOnEnd = processor.onEnd.bind(processor);
|
|
1505
|
+
processor.onStart = (span, parentContext) => {
|
|
1506
|
+
try {
|
|
1507
|
+
enrichStart(span);
|
|
1508
|
+
originalOnStart(span, parentContext);
|
|
1509
|
+
} catch (e) {
|
|
1510
|
+
}
|
|
1511
|
+
};
|
|
1512
|
+
processor.onEnd = (span) => {
|
|
1513
|
+
var _a2;
|
|
1514
|
+
let outgoing = span;
|
|
1515
|
+
try {
|
|
1516
|
+
const allowed = options.allowedInstrumentationLibraries;
|
|
1517
|
+
if (allowed !== ALL_INSTRUMENTATION_LIBRARIES && ![...INSTRUMENTATION_LIBRARIES, ...allowed != null ? allowed : []].includes((_a2 = scopeName(span)) != null ? _a2 : "")) {
|
|
1518
|
+
return;
|
|
1519
|
+
}
|
|
1520
|
+
applyPromptTools(span);
|
|
1521
|
+
outgoing = transformAiSdkSpan(span);
|
|
1522
|
+
if (outgoing !== span) copyReplayTraceDestination(span, outgoing);
|
|
1523
|
+
} catch (e) {
|
|
1524
|
+
}
|
|
1525
|
+
try {
|
|
1526
|
+
originalOnEnd(outgoing);
|
|
1527
|
+
} catch (e) {
|
|
1528
|
+
}
|
|
1529
|
+
};
|
|
1530
|
+
return processor;
|
|
1531
|
+
}
|
|
1532
|
+
function initialize(options = {}) {
|
|
1533
|
+
var _a;
|
|
1534
|
+
const state = getState2();
|
|
1535
|
+
if (state.configuration) return;
|
|
1536
|
+
state.configuration = Object.freeze({ ...options });
|
|
1537
|
+
if (options.logLevel) diag.setLogger(new DiagConsoleLogger(), logLevel(options.logLevel));
|
|
1538
|
+
if (options.tracingEnabled === false) return;
|
|
1539
|
+
const baseUrl = options.baseUrl || process.env.TRACELOOP_BASE_URL || "https://api.traceloop.com";
|
|
1540
|
+
state.defaultProcessor = createSpanProcessor({
|
|
1541
|
+
...options,
|
|
1542
|
+
baseUrl,
|
|
1543
|
+
allowedInstrumentationLibraries: ALL_INSTRUMENTATION_LIBRARIES
|
|
1544
|
+
});
|
|
1545
|
+
const serviceResource = createResource({
|
|
1546
|
+
"service.name": options.appName || process.env.npm_package_name || "unknown_service"
|
|
1547
|
+
});
|
|
1548
|
+
const detectedResource = detectRuntimeResource();
|
|
1549
|
+
state.provider = new NodeTracerProvider({
|
|
1550
|
+
// Detected attributes win over the configured resource, matching
|
|
1551
|
+
// sdk-node's `this._resource.merge(detectResourcesSync(...))` so
|
|
1552
|
+
// OTEL_SERVICE_NAME / OTEL_RESOURCE_ATTRIBUTES can still override appName.
|
|
1553
|
+
resource: detectedResource ? serviceResource.merge(detectedResource) : serviceResource,
|
|
1554
|
+
spanProcessors: [state.defaultProcessor, ...options.processor ? [options.processor] : []]
|
|
1555
|
+
});
|
|
1556
|
+
state.provider.register({
|
|
1557
|
+
contextManager: options.contextManager,
|
|
1558
|
+
propagator: options.propagator
|
|
1559
|
+
});
|
|
1560
|
+
const instrumentations = (_a = options.instrumentations) != null ? _a : [];
|
|
1561
|
+
if (contentCaptureDisabled(options)) {
|
|
1562
|
+
for (const instrumentation of instrumentations) {
|
|
1563
|
+
try {
|
|
1564
|
+
const config = {
|
|
1565
|
+
...instrumentation.getConfig(),
|
|
1566
|
+
traceContent: false
|
|
1567
|
+
};
|
|
1568
|
+
instrumentation.setConfig(config);
|
|
1569
|
+
} catch (e) {
|
|
1570
|
+
}
|
|
1571
|
+
}
|
|
1572
|
+
}
|
|
1573
|
+
registerInstrumentations({ instrumentations });
|
|
1574
|
+
}
|
|
1575
|
+
async function forceFlush() {
|
|
1576
|
+
var _a, _b;
|
|
1577
|
+
const state = getState2();
|
|
1578
|
+
try {
|
|
1579
|
+
await ((_a = state.provider) == null ? void 0 : _a.forceFlush());
|
|
1580
|
+
await ((_b = state.defaultProcessor) == null ? void 0 : _b.forceFlush());
|
|
1581
|
+
} catch (e) {
|
|
1582
|
+
}
|
|
1583
|
+
}
|
|
1584
|
+
function withEntity(type, config, fn, args) {
|
|
1585
|
+
let entityContext = context2.active();
|
|
1586
|
+
if (type === TraceloopSpanKindValues.WORKFLOW) {
|
|
1587
|
+
entityContext = entityContext.setValue(WORKFLOW_NAME_KEY, config.name);
|
|
1588
|
+
}
|
|
1589
|
+
const parentPath = entityContext.getValue(ENTITY_NAME_KEY);
|
|
1590
|
+
if (type === TraceloopSpanKindValues.TASK || type === TraceloopSpanKindValues.TOOL) {
|
|
1591
|
+
entityContext = entityContext.setValue(
|
|
1592
|
+
ENTITY_NAME_KEY,
|
|
1593
|
+
`${typeof parentPath === "string" ? `${parentPath}.` : ""}${config.name}`
|
|
1594
|
+
);
|
|
1595
|
+
}
|
|
1596
|
+
if (config.traceContent !== void 0) {
|
|
1597
|
+
entityContext = entityContext.setValue(CONTEXT_KEY_ALLOW_TRACE_CONTENT, config.traceContent);
|
|
1598
|
+
}
|
|
1599
|
+
if (config.associationProperties) {
|
|
1600
|
+
entityContext = entityContext.setValue(
|
|
1601
|
+
ASSOCIATION_PROPERTIES_KEY,
|
|
1602
|
+
config.associationProperties
|
|
1603
|
+
);
|
|
1604
|
+
}
|
|
1605
|
+
if (config.suppressTracing) {
|
|
1606
|
+
entityContext = suppressTracing(entityContext);
|
|
1607
|
+
}
|
|
1608
|
+
let callbackStarted = false;
|
|
1609
|
+
const run = (span) => {
|
|
1610
|
+
var _a;
|
|
1611
|
+
try {
|
|
1612
|
+
span.setAttribute(SpanAttributes.TRACELOOP_ENTITY_NAME, config.name);
|
|
1613
|
+
span.setAttribute(
|
|
1614
|
+
SpanAttributes.TRACELOOP_ENTITY_PATH,
|
|
1615
|
+
typeof parentPath === "string" ? parentPath : ""
|
|
1616
|
+
);
|
|
1617
|
+
span.setAttribute(SpanAttributes.TRACELOOP_SPAN_KIND, type);
|
|
1618
|
+
if (type === TraceloopSpanKindValues.WORKFLOW) {
|
|
1619
|
+
span.setAttribute(SpanAttributes.TRACELOOP_WORKFLOW_NAME, config.name);
|
|
1620
|
+
}
|
|
1621
|
+
if (config.version !== void 0)
|
|
1622
|
+
span.setAttribute(SpanAttributes.TRACELOOP_ENTITY_VERSION, config.version);
|
|
1623
|
+
const input = (_a = config.inputParameters) != null ? _a : args;
|
|
1624
|
+
if (shouldSendTraceContent()) {
|
|
1625
|
+
span.setAttribute(
|
|
1626
|
+
SpanAttributes.TRACELOOP_ENTITY_INPUT,
|
|
1627
|
+
safeStringify(
|
|
1628
|
+
input.length === 1 && input[0] !== null && typeof input[0] === "object" && !(input[0] instanceof Map) ? { args: [], kwargs: input[0] } : { args: input, kwargs: {} }
|
|
1629
|
+
)
|
|
1630
|
+
);
|
|
1631
|
+
}
|
|
1632
|
+
} catch (e) {
|
|
1633
|
+
}
|
|
1634
|
+
let result;
|
|
1635
|
+
try {
|
|
1636
|
+
callbackStarted = true;
|
|
1637
|
+
result = fn(...args);
|
|
1638
|
+
} catch (error) {
|
|
1639
|
+
try {
|
|
1640
|
+
span.end();
|
|
1641
|
+
} catch (e) {
|
|
1642
|
+
}
|
|
1643
|
+
throw error;
|
|
1644
|
+
}
|
|
1645
|
+
if (result instanceof Promise) {
|
|
1646
|
+
return result.then(
|
|
1647
|
+
(value) => {
|
|
1648
|
+
try {
|
|
1649
|
+
if (shouldSendTraceContent())
|
|
1650
|
+
span.setAttribute(SpanAttributes.TRACELOOP_ENTITY_OUTPUT, safeStringify(value));
|
|
1651
|
+
span.end();
|
|
1652
|
+
} catch (e) {
|
|
1653
|
+
}
|
|
1654
|
+
return value;
|
|
1655
|
+
},
|
|
1656
|
+
(error) => {
|
|
1657
|
+
try {
|
|
1658
|
+
span.end();
|
|
1659
|
+
} catch (e) {
|
|
1660
|
+
}
|
|
1661
|
+
throw error;
|
|
1662
|
+
}
|
|
1663
|
+
);
|
|
1664
|
+
}
|
|
1665
|
+
try {
|
|
1666
|
+
if (shouldSendTraceContent())
|
|
1667
|
+
span.setAttribute(SpanAttributes.TRACELOOP_ENTITY_OUTPUT, safeStringify(result));
|
|
1668
|
+
span.end();
|
|
1669
|
+
} catch (e) {
|
|
1670
|
+
}
|
|
1671
|
+
return result;
|
|
1672
|
+
};
|
|
1673
|
+
try {
|
|
1674
|
+
const tracer = trace2.getTracer(TRACER_NAME);
|
|
1675
|
+
return context2.with(
|
|
1676
|
+
entityContext,
|
|
1677
|
+
() => tracer.startActiveSpan(`${config.name}.${type}`, {}, entityContext, run)
|
|
1678
|
+
);
|
|
1679
|
+
} catch (error) {
|
|
1680
|
+
if (callbackStarted) throw error;
|
|
1681
|
+
return fn(...args);
|
|
1682
|
+
}
|
|
1683
|
+
}
|
|
1684
|
+
function withTask(config, fn, ...args) {
|
|
1685
|
+
return withEntity(TraceloopSpanKindValues.TASK, config, fn, args);
|
|
1686
|
+
}
|
|
1687
|
+
function withTool(config, fn, ...args) {
|
|
1688
|
+
return withEntity(TraceloopSpanKindValues.TOOL, config, fn, args);
|
|
1689
|
+
}
|
|
1690
|
+
|
|
1691
|
+
// src/tracing/exit-flush.ts
|
|
1692
|
+
var STATE_KEY3 = /* @__PURE__ */ Symbol.for("raindrop.tracing.exitFlushState");
|
|
1693
|
+
function getState3() {
|
|
1694
|
+
const holder = globalThis;
|
|
1695
|
+
let state = holder[STATE_KEY3];
|
|
1696
|
+
if (!state) {
|
|
1697
|
+
state = {
|
|
1698
|
+
clientFlushers: /* @__PURE__ */ new Set(),
|
|
1699
|
+
pipelineFlushNeeded: false,
|
|
1700
|
+
handlerRegistered: false
|
|
1701
|
+
};
|
|
1702
|
+
holder[STATE_KEY3] = state;
|
|
1703
|
+
}
|
|
1704
|
+
return state;
|
|
1705
|
+
}
|
|
1706
|
+
function ensureExitHandler(state) {
|
|
1707
|
+
if (state.handlerRegistered) return;
|
|
1708
|
+
if (typeof process === "undefined" || typeof process.once !== "function") return;
|
|
1709
|
+
state.handlerRegistered = true;
|
|
1710
|
+
process.once("beforeExit", () => {
|
|
1711
|
+
void flushAll();
|
|
1712
|
+
});
|
|
1713
|
+
}
|
|
1714
|
+
function registerClientFlusher(flush) {
|
|
1715
|
+
const state = getState3();
|
|
1716
|
+
state.clientFlushers.add(flush);
|
|
1717
|
+
ensureExitHandler(state);
|
|
1718
|
+
return () => {
|
|
1719
|
+
state.clientFlushers.delete(flush);
|
|
1720
|
+
};
|
|
1721
|
+
}
|
|
1722
|
+
function markPipelineForExitFlush() {
|
|
1723
|
+
const state = getState3();
|
|
1724
|
+
state.pipelineFlushNeeded = true;
|
|
1725
|
+
ensureExitHandler(state);
|
|
1726
|
+
}
|
|
1727
|
+
async function flushAll() {
|
|
1728
|
+
const state = getState3();
|
|
1729
|
+
const tasks = [];
|
|
1730
|
+
for (const flush of state.clientFlushers) {
|
|
1731
|
+
tasks.push(Promise.resolve().then(flush).catch(() => {
|
|
1732
|
+
}));
|
|
1733
|
+
}
|
|
1734
|
+
if (state.pipelineFlushNeeded) {
|
|
1735
|
+
tasks.push(
|
|
1736
|
+
Promise.resolve().then(() => forceFlush()).catch(() => {
|
|
1737
|
+
})
|
|
1738
|
+
);
|
|
1739
|
+
}
|
|
1740
|
+
await Promise.all(tasks);
|
|
1741
|
+
}
|
|
1742
|
+
|
|
1743
|
+
// src/tracing/liveInteraction.ts
|
|
1744
|
+
import {
|
|
1745
|
+
SpanStatusCode as SpanStatusCode2,
|
|
1746
|
+
TraceFlags as TraceFlags2,
|
|
1747
|
+
context as context4,
|
|
1748
|
+
isValidSpanId as isValidSpanId2,
|
|
1749
|
+
isValidTraceId as isValidTraceId2,
|
|
1750
|
+
trace as trace4
|
|
1751
|
+
} from "@opentelemetry/api";
|
|
1752
|
+
|
|
1753
|
+
// src/tracing/tool-timing.ts
|
|
1754
|
+
function toMs(value) {
|
|
1755
|
+
return value instanceof Date ? value.getTime() : value;
|
|
1756
|
+
}
|
|
1757
|
+
function resolveToolTiming(input, now = Date.now()) {
|
|
1758
|
+
var _a, _b, _c;
|
|
1759
|
+
if (input.endTime !== void 0) {
|
|
1760
|
+
const endTimeMs = toMs(input.endTime);
|
|
1761
|
+
const startTimeMs2 = input.startTime !== void 0 ? toMs(input.startTime) : endTimeMs - ((_a = input.durationMs) != null ? _a : 0);
|
|
1762
|
+
return { startTimeMs: startTimeMs2, endTimeMs, durationMs: endTimeMs - startTimeMs2 };
|
|
1763
|
+
}
|
|
1764
|
+
const startTimeMs = input.startTime !== void 0 ? toMs(input.startTime) : now - ((_b = input.durationMs) != null ? _b : 0);
|
|
1765
|
+
return { startTimeMs, endTimeMs: startTimeMs + ((_c = input.durationMs) != null ? _c : 0), durationMs: input.durationMs };
|
|
1766
|
+
}
|
|
1767
|
+
|
|
1768
|
+
// src/tracing/subagents.ts
|
|
1769
|
+
import { SpanStatusCode, context as context3, trace as trace3 } from "@opentelemetry/api";
|
|
1770
|
+
var DEFAULT_SUBAGENT_NAME = "subagent";
|
|
1771
|
+
var DISPATCH_ACCEPTED = "accepted";
|
|
1772
|
+
function reasonText(reason) {
|
|
1773
|
+
var _a;
|
|
1774
|
+
if (reason instanceof Error) return `${reason.name}: ${reason.message}`;
|
|
1775
|
+
if (typeof reason === "string") return reason;
|
|
1776
|
+
if (reason === void 0 || reason === null) return "";
|
|
1777
|
+
try {
|
|
1778
|
+
return (_a = JSON.stringify(reason)) != null ? _a : String(reason);
|
|
1779
|
+
} catch (e) {
|
|
1780
|
+
return String(reason);
|
|
1781
|
+
}
|
|
1782
|
+
}
|
|
1783
|
+
function stampCurrentSpan(attributes) {
|
|
1784
|
+
try {
|
|
1785
|
+
const span = trace3.getSpan(context3.active());
|
|
1786
|
+
if (!(span == null ? void 0 : span.isRecording())) return;
|
|
1787
|
+
for (const [key, value] of Object.entries(attributes)) {
|
|
1788
|
+
span.setAttribute(key, value);
|
|
1789
|
+
}
|
|
1790
|
+
} catch (e) {
|
|
1791
|
+
}
|
|
1792
|
+
}
|
|
1793
|
+
function stampOwnSpan(attributes, frame) {
|
|
1794
|
+
if (!frame) return;
|
|
1795
|
+
try {
|
|
1796
|
+
const span = trace3.getSpan(context3.active());
|
|
1797
|
+
if (!(span == null ? void 0 : span.isRecording()) || !frame.ownsSpan(span)) return;
|
|
1798
|
+
for (const [key, value] of Object.entries(attributes)) {
|
|
1799
|
+
span.setAttribute(key, value);
|
|
1800
|
+
}
|
|
1801
|
+
} catch (e) {
|
|
1802
|
+
}
|
|
1803
|
+
}
|
|
1804
|
+
function failOwnSpan(reason, frame) {
|
|
1805
|
+
try {
|
|
1806
|
+
const span = trace3.getSpan(context3.active());
|
|
1807
|
+
if (!(span == null ? void 0 : span.isRecording())) return false;
|
|
1808
|
+
if (!(frame == null ? void 0 : frame.ownsSpan(span))) return false;
|
|
1809
|
+
const message = reasonText(reason);
|
|
1810
|
+
span.setStatus({ code: SpanStatusCode.ERROR, message });
|
|
1811
|
+
span.recordException(reason instanceof Error ? reason : new Error(message));
|
|
1812
|
+
return true;
|
|
1813
|
+
} catch (e) {
|
|
1814
|
+
return false;
|
|
1815
|
+
}
|
|
1816
|
+
}
|
|
1817
|
+
function allowToolEvents(interaction) {
|
|
1818
|
+
const attributes = withMetadataPrefix(toolEventsAllowMetadata());
|
|
1819
|
+
interaction.bindToolEventsOptIn(attributes);
|
|
1820
|
+
stampCurrentSpan(attributes);
|
|
1821
|
+
}
|
|
1822
|
+
function recordSubagentDispatch(interaction, options) {
|
|
1823
|
+
var _a;
|
|
1824
|
+
const childEventId = options.childEventId || randomUUID();
|
|
1825
|
+
const name = options.name || DEFAULT_SUBAGENT_NAME;
|
|
1826
|
+
const parentEventId = (_a = interaction.getEventId()) != null ? _a : "";
|
|
1827
|
+
let traceIdHex;
|
|
1828
|
+
let dispatchSpanId;
|
|
1829
|
+
try {
|
|
1830
|
+
allowToolEvents(interaction);
|
|
1831
|
+
const recorded = interaction.recordDispatchSpan({
|
|
1832
|
+
name: options.toolName || DEFAULT_DISPATCH_SPAN_NAME,
|
|
1833
|
+
input: options.input,
|
|
1834
|
+
// A launch's "result" is the job handle; the answer belongs to the
|
|
1835
|
+
// child's event and never appears here.
|
|
1836
|
+
output: { jobId: childEventId, status: DISPATCH_ACCEPTED },
|
|
1837
|
+
properties: options.properties,
|
|
1838
|
+
attributes: detachedDispatchMetadata({ childEventId, name })
|
|
1839
|
+
});
|
|
1840
|
+
traceIdHex = recorded.traceIdHex;
|
|
1841
|
+
dispatchSpanId = recorded.spanIdHex;
|
|
1842
|
+
if (!dispatchSpanId) {
|
|
1843
|
+
console.warn(
|
|
1844
|
+
`[raindrop] subagent(${name}): no dispatch span was recorded, so event ${parentEventId} will not show the launch and NO carrier is returned \u2014 there is no span for the child to reference. Pass childEventId (${childEventId}) to the worker yourself if it must still report under that id. Tracing must be enabled for dispatches to be recorded.`
|
|
1845
|
+
);
|
|
1846
|
+
}
|
|
1847
|
+
} catch (error) {
|
|
1848
|
+
console.warn(
|
|
1849
|
+
`[raindrop] subagent(${name}) failed to record the dispatch; returning a carrier so the child still links back.`,
|
|
1850
|
+
error instanceof Error ? error.message : error
|
|
1851
|
+
);
|
|
1852
|
+
}
|
|
1853
|
+
if (!traceIdHex || !dispatchSpanId) {
|
|
1854
|
+
return {
|
|
1855
|
+
childEventId,
|
|
1856
|
+
name,
|
|
1857
|
+
parentEventId,
|
|
1858
|
+
dispatchSpanId: void 0,
|
|
1859
|
+
carrier: null,
|
|
1860
|
+
headers: {},
|
|
1861
|
+
langsmithHeaders: {}
|
|
1862
|
+
};
|
|
1863
|
+
}
|
|
1864
|
+
const carrier = {
|
|
1865
|
+
traceId: traceIdHex,
|
|
1866
|
+
spanId: dispatchSpanId,
|
|
1867
|
+
eventId: parentEventId,
|
|
1868
|
+
childEventId,
|
|
1869
|
+
name,
|
|
1870
|
+
...interaction.getConvoId() ? { convoId: interaction.getConvoId() } : {},
|
|
1871
|
+
...interaction.getUserId() ? { userId: interaction.getUserId() } : {}
|
|
1872
|
+
};
|
|
1873
|
+
return {
|
|
1874
|
+
childEventId,
|
|
1875
|
+
name,
|
|
1876
|
+
parentEventId,
|
|
1877
|
+
dispatchSpanId,
|
|
1878
|
+
carrier,
|
|
1879
|
+
headers: toHeaders(carrier),
|
|
1880
|
+
langsmithHeaders: toLangSmithHeaders(carrier)
|
|
1881
|
+
};
|
|
1882
|
+
}
|
|
1883
|
+
function carrierFirst(local, carried, field) {
|
|
1884
|
+
if (carried && local && local !== carried) {
|
|
1885
|
+
console.warn(
|
|
1886
|
+
`[raindrop] resumeSubagent: ignoring ${field}="${local}" in favor of the launcher's "${carried}" from the carrier; the launcher allocated it, and a child that substitutes its own breaks the link back to it.`
|
|
1887
|
+
);
|
|
1888
|
+
}
|
|
1889
|
+
return carried || local;
|
|
1890
|
+
}
|
|
1891
|
+
function isTraceCarrier(value) {
|
|
1892
|
+
const candidate = value;
|
|
1893
|
+
return typeof candidate.traceId === "string" && typeof candidate.spanId === "string" && typeof candidate.eventId === "string";
|
|
1894
|
+
}
|
|
1895
|
+
function readCarrier(carrierOrHeaders) {
|
|
1896
|
+
if (!carrierOrHeaders) return null;
|
|
1897
|
+
try {
|
|
1898
|
+
if (isTraceCarrier(carrierOrHeaders)) return carrierOrHeaders;
|
|
1899
|
+
return fromHeaders(carrierOrHeaders);
|
|
1900
|
+
} catch (error) {
|
|
1901
|
+
console.warn(
|
|
1902
|
+
`[raindrop] resumeSubagent: ignoring an unreadable hand-off carrier; the run reports as an unlinked event.`,
|
|
1903
|
+
error instanceof Error ? error.message : error
|
|
1904
|
+
);
|
|
1905
|
+
return null;
|
|
1906
|
+
}
|
|
1907
|
+
}
|
|
1908
|
+
function resolveSubagentResume(carrierOrHeaders, options = {}) {
|
|
1909
|
+
const parentStated = options.parent !== void 0;
|
|
1910
|
+
const parent = parentStated ? options.parent : readCarrier(carrierOrHeaders);
|
|
1911
|
+
if (!parentStated) warnUnresolvedCarrier(carrierOrHeaders, parent);
|
|
1912
|
+
const name = carrierFirst(options.name, parent == null ? void 0 : parent.name, "name") || DEFAULT_SUBAGENT_NAME;
|
|
1913
|
+
const eventId = carrierFirst(options.eventId, parent == null ? void 0 : parent.childEventId, "eventId") || randomUUID();
|
|
1914
|
+
const userId = carrierFirst(options.userId, parent == null ? void 0 : parent.userId, "userId") || "";
|
|
1915
|
+
const convoId = carrierFirst(options.convoId, parent == null ? void 0 : parent.convoId, "convoId");
|
|
1916
|
+
const link = parent ? {
|
|
1917
|
+
parentEventId: parent.eventId,
|
|
1918
|
+
...parent.spanId ? { parentSpanId: parent.spanId } : {},
|
|
1919
|
+
name
|
|
1920
|
+
} : null;
|
|
1921
|
+
return {
|
|
1922
|
+
parent,
|
|
1923
|
+
link,
|
|
1924
|
+
name,
|
|
1925
|
+
eventId,
|
|
1926
|
+
event: options.event || `subagent.${name}`,
|
|
1927
|
+
userId,
|
|
1928
|
+
...convoId ? { convoId } : {}
|
|
1929
|
+
};
|
|
1930
|
+
}
|
|
1931
|
+
function bindSubagentLink(link, owner) {
|
|
1932
|
+
if (!link) return void 0;
|
|
1933
|
+
return bindSpanAttributes(detachedChildMetadata(link), owner);
|
|
1934
|
+
}
|
|
1935
|
+
var LiveSubagentRun = class {
|
|
1936
|
+
constructor(params) {
|
|
1937
|
+
this.settled = false;
|
|
1938
|
+
this.interaction = params.interaction;
|
|
1939
|
+
this.eventId = params.eventId;
|
|
1940
|
+
this.name = params.name;
|
|
1941
|
+
this.convoId = params.convoId;
|
|
1942
|
+
this.parent = params.parent;
|
|
1943
|
+
this.frame = params.frame;
|
|
1944
|
+
this.frameOwner = params.frameOwner;
|
|
1945
|
+
}
|
|
1946
|
+
get linked() {
|
|
1947
|
+
return this.parent !== null;
|
|
1948
|
+
}
|
|
1949
|
+
async finish(result) {
|
|
1950
|
+
await this.close(result);
|
|
1951
|
+
}
|
|
1952
|
+
async fail(reason) {
|
|
1953
|
+
await this.abort(reason);
|
|
1954
|
+
}
|
|
1955
|
+
async cancel(reason) {
|
|
1956
|
+
const text = reason === void 0 ? "cancelled by caller" : reasonText(reason);
|
|
1957
|
+
const cancelled = cancelledTerminalAttributes();
|
|
1958
|
+
stampOwnSpan(cancelled, this.frame);
|
|
1959
|
+
await this.close({
|
|
1960
|
+
output: `Cancelled: ${text}`,
|
|
1961
|
+
// The caller's view of the child is its EVENT, not its spans, so the
|
|
1962
|
+
// marker has to be a property of the event as well.
|
|
1963
|
+
properties: { [HANDOFF_TERMINAL_PROPERTY_KEY]: HANDOFF_TERMINAL_CANCELLED }
|
|
1964
|
+
});
|
|
1965
|
+
}
|
|
1966
|
+
/**
|
|
1967
|
+
* Close the run with an abort reason, having first made sure the failure is
|
|
1968
|
+
* visible on a span.
|
|
1969
|
+
*
|
|
1970
|
+
* A failure has to leave an errored span behind or it is derived as finished.
|
|
1971
|
+
* Mark whatever is open; if nothing is and the child has not errored a span
|
|
1972
|
+
* already, record one — the killed-before-it-reached-the-model case, which is
|
|
1973
|
+
* much of what aborting is.
|
|
1974
|
+
*/
|
|
1975
|
+
async abort(reason) {
|
|
1976
|
+
var _a, _b, _c;
|
|
1977
|
+
const text = reasonText(reason);
|
|
1978
|
+
if (!this.settled && !failOwnSpan(reason, this.frame)) {
|
|
1979
|
+
if (!((_a = this.frame) == null ? void 0 : _a.sawErrorSpan())) {
|
|
1980
|
+
this.interaction.recordSubagentAbortSpan({
|
|
1981
|
+
reason,
|
|
1982
|
+
message: text,
|
|
1983
|
+
attributes: {
|
|
1984
|
+
[HANDOFF_ATTRIBUTE_SUFFIXES.name]: this.name,
|
|
1985
|
+
// The name explicitly, not only via the frame: an UNLINKED run has
|
|
1986
|
+
// no frame, and since the span is named for the operation
|
|
1987
|
+
// (`ai.subagent.failed`) rather than the sub-agent, this attribute
|
|
1988
|
+
// is the only thing left that says which sub-agent failed.
|
|
1989
|
+
...(_c = (_b = this.frame) == null ? void 0 : _b.attributes) != null ? _c : {}
|
|
1990
|
+
}
|
|
1991
|
+
});
|
|
1992
|
+
}
|
|
1993
|
+
}
|
|
1994
|
+
await this.close({ output: text ? `Aborted: ${text}` : "Aborted before producing a result." });
|
|
1995
|
+
}
|
|
1996
|
+
async close(result) {
|
|
1997
|
+
if (this.settled) return;
|
|
1998
|
+
this.settled = true;
|
|
1999
|
+
try {
|
|
2000
|
+
await this.interaction.finish({ ...result, eventId: this.eventId });
|
|
2001
|
+
} finally {
|
|
2002
|
+
unbindSpanAttributes(this.frame);
|
|
2003
|
+
this.frame = void 0;
|
|
2004
|
+
this.frameOwner = void 0;
|
|
2005
|
+
}
|
|
2006
|
+
}
|
|
2007
|
+
/**
|
|
2008
|
+
* Run `fn` and guarantee the run reports an outcome, mirroring the Python
|
|
2009
|
+
* SDK's `with rd.resume_subagent(...) as run:`.
|
|
2010
|
+
*
|
|
2011
|
+
* A run that leaves without reporting output is closed with its abort reason.
|
|
2012
|
+
* That is not cosmetic: an event is created only from a run with non-empty
|
|
2013
|
+
* output, so a child that dies silently produces no event at all and the
|
|
2014
|
+
* caller's launch stays `queued` forever — indistinguishable from a job that
|
|
2015
|
+
* never started.
|
|
2016
|
+
*/
|
|
2017
|
+
async use(fn) {
|
|
2018
|
+
try {
|
|
2019
|
+
const result = await fn(this);
|
|
2020
|
+
if (!this.settled) {
|
|
2021
|
+
console.warn(
|
|
2022
|
+
`[raindrop] sub-agent run ${this.eventId} (${this.name}) ended without reporting output; closing it with an abort reason. An event needs non-empty output to exist, so a silent child leaves its launcher showing "queued" forever \u2014 call finish({ output }), fail(reason) or cancel() before returning.`
|
|
2023
|
+
);
|
|
2024
|
+
await this.abortQuietly("sub-agent ended without reporting output");
|
|
2025
|
+
}
|
|
2026
|
+
return result;
|
|
2027
|
+
} catch (error) {
|
|
2028
|
+
await this.abortQuietly(error);
|
|
2029
|
+
throw error;
|
|
2030
|
+
}
|
|
2031
|
+
}
|
|
2032
|
+
/**
|
|
2033
|
+
* {@link abort} for the outcomes this class reports on the caller's behalf.
|
|
2034
|
+
*
|
|
2035
|
+
* `abort()` ends in `interaction.finish()`, which awaits the terminal event
|
|
2036
|
+
* POST and rejects when it fails. An explicit `fail()` may surface that — the
|
|
2037
|
+
* caller awaited it — but an implicit one must not: rejecting on the error
|
|
2038
|
+
* path replaces the caller's exception with a telemetry one, and rejecting on
|
|
2039
|
+
* the success path loses a result `fn` already produced.
|
|
2040
|
+
*/
|
|
2041
|
+
async abortQuietly(reason) {
|
|
2042
|
+
try {
|
|
2043
|
+
await this.abort(reason);
|
|
2044
|
+
} catch (error) {
|
|
2045
|
+
console.warn(
|
|
2046
|
+
`[raindrop] sub-agent run ${this.eventId} (${this.name}) could not report its outcome; the run itself is unaffected.`,
|
|
2047
|
+
error instanceof Error ? error.message : error
|
|
2048
|
+
);
|
|
2049
|
+
}
|
|
2050
|
+
}
|
|
2051
|
+
};
|
|
2052
|
+
|
|
2053
|
+
// src/tracing/liveInteraction.ts
|
|
2054
|
+
function getPropertiesFromContext(context7) {
|
|
2055
|
+
const properties = {
|
|
2056
|
+
...context7.userId && { user_id: context7.userId },
|
|
2057
|
+
...context7.convoId && { convo_id: context7.convoId },
|
|
2058
|
+
...context7.eventId && { event_id: context7.eventId },
|
|
2059
|
+
...context7.event && { event_name: context7.event },
|
|
2060
|
+
...context7.properties || {}
|
|
2061
|
+
};
|
|
2062
|
+
if (context7.attachments && context7.attachments.length > 0) {
|
|
2063
|
+
properties.attachments = stringifyBounded(context7.attachments);
|
|
2064
|
+
}
|
|
2065
|
+
return properties;
|
|
2066
|
+
}
|
|
2067
|
+
function setAssociationProperties(span, properties) {
|
|
2068
|
+
Object.entries(properties).forEach(([key, value]) => {
|
|
2069
|
+
if (value === void 0) {
|
|
2070
|
+
return;
|
|
2071
|
+
}
|
|
2072
|
+
span.setAttribute("traceloop.association.properties." + key, serializeSpanValue(value));
|
|
2073
|
+
});
|
|
2074
|
+
}
|
|
2075
|
+
function serializeAssociationProperties(properties) {
|
|
2076
|
+
return Object.fromEntries(
|
|
2077
|
+
Object.entries(properties).filter(([, value]) => value !== void 0).map(([key, value]) => [key, serializeSpanValue(value)])
|
|
2078
|
+
);
|
|
2079
|
+
}
|
|
2080
|
+
function serializeSpanValue(value) {
|
|
2081
|
+
return stringifyBounded(value);
|
|
2082
|
+
}
|
|
2083
|
+
function getLocalDebuggerMetadata(context7) {
|
|
2084
|
+
return {
|
|
2085
|
+
...context7.eventId ? { eventId: context7.eventId } : {},
|
|
2086
|
+
...context7.event ? { eventName: context7.event } : {},
|
|
2087
|
+
...context7.userId ? { userId: context7.userId } : {},
|
|
2088
|
+
...context7.convoId ? { convoId: context7.convoId } : {}
|
|
2089
|
+
};
|
|
2090
|
+
}
|
|
2091
|
+
var LiveToolSpan = class {
|
|
2092
|
+
constructor(params) {
|
|
2093
|
+
this.hasError = false;
|
|
2094
|
+
this.span = params.span;
|
|
2095
|
+
this.name = params.name;
|
|
2096
|
+
this.emitLiveEvent = params.emitLiveEvent;
|
|
2097
|
+
}
|
|
2098
|
+
spanIdHex() {
|
|
2099
|
+
const ctx = this.span.spanContext();
|
|
2100
|
+
return isValidSpanId2(ctx.spanId) ? ctx.spanId : void 0;
|
|
2101
|
+
}
|
|
2102
|
+
setInput(input) {
|
|
2103
|
+
this.span.setAttribute("traceloop.entity.input", serializeSpanValue(input));
|
|
2104
|
+
}
|
|
2105
|
+
setOutput(output) {
|
|
2106
|
+
this.output = output;
|
|
2107
|
+
this.span.setAttribute("traceloop.entity.output", serializeSpanValue(output));
|
|
2108
|
+
}
|
|
2109
|
+
setError(error) {
|
|
2110
|
+
this.hasError = true;
|
|
2111
|
+
this.errorMessage = error instanceof Error ? error.message : String(error);
|
|
2112
|
+
this.span.setStatus({ code: SpanStatusCode2.ERROR, message: this.errorMessage });
|
|
2113
|
+
this.span.recordException(error instanceof Error ? error : new Error(this.errorMessage));
|
|
2114
|
+
}
|
|
2115
|
+
end() {
|
|
2116
|
+
var _a;
|
|
2117
|
+
if (!this.hasError) {
|
|
2118
|
+
this.span.setStatus({ code: SpanStatusCode2.OK });
|
|
2119
|
+
}
|
|
2120
|
+
this.span.end();
|
|
2121
|
+
(_a = this.emitLiveEvent) == null ? void 0 : _a.call(this, {
|
|
2122
|
+
type: "tool_result",
|
|
2123
|
+
content: this.name,
|
|
2124
|
+
spanId: this.spanIdHex(),
|
|
2125
|
+
metadata: {
|
|
2126
|
+
...this.output !== void 0 ? { result: this.output } : {},
|
|
2127
|
+
...this.errorMessage ? { error: this.errorMessage } : {}
|
|
2128
|
+
}
|
|
2129
|
+
});
|
|
2130
|
+
}
|
|
2131
|
+
};
|
|
2132
|
+
var DirectToolSpan = class {
|
|
2133
|
+
constructor(params) {
|
|
2134
|
+
this.ended = false;
|
|
2135
|
+
this.name = params.name;
|
|
2136
|
+
this.properties = params.properties;
|
|
2137
|
+
this.directShipper = params.directShipper;
|
|
2138
|
+
this.traceId = params.traceId;
|
|
2139
|
+
this.spanId = params.spanId;
|
|
2140
|
+
this.parentSpanId = params.parentSpanId;
|
|
2141
|
+
this.startTimeMs = Date.now();
|
|
2142
|
+
this.input = params.input !== void 0 ? serializeSpanValue(params.input) : void 0;
|
|
2143
|
+
this.emitLiveEvent = params.emitLiveEvent;
|
|
2144
|
+
}
|
|
2145
|
+
setInput(input) {
|
|
2146
|
+
this.input = serializeSpanValue(input);
|
|
2147
|
+
}
|
|
2148
|
+
setOutput(output) {
|
|
2149
|
+
this.rawOutput = output;
|
|
2150
|
+
this.output = serializeSpanValue(output);
|
|
2151
|
+
}
|
|
2152
|
+
setError(error) {
|
|
2153
|
+
this.error = error instanceof Error ? error.message : String(error);
|
|
2154
|
+
}
|
|
2155
|
+
end() {
|
|
2156
|
+
var _a;
|
|
2157
|
+
if (this.ended) {
|
|
2158
|
+
return;
|
|
2159
|
+
}
|
|
2160
|
+
this.ended = true;
|
|
2161
|
+
const endTimeMs = Date.now();
|
|
2162
|
+
this.directShipper.sendToolSpan({
|
|
2163
|
+
name: this.name,
|
|
2164
|
+
spanId: this.spanId,
|
|
2165
|
+
input: this.input,
|
|
2166
|
+
output: this.output,
|
|
2167
|
+
durationMs: endTimeMs - this.startTimeMs,
|
|
2168
|
+
startTimeMs: this.startTimeMs,
|
|
2169
|
+
endTimeMs,
|
|
2170
|
+
error: this.error,
|
|
2171
|
+
properties: this.properties,
|
|
2172
|
+
traceId: this.traceId,
|
|
2173
|
+
parentSpanId: this.parentSpanId
|
|
2174
|
+
});
|
|
2175
|
+
(_a = this.emitLiveEvent) == null ? void 0 : _a.call(this, {
|
|
2176
|
+
traceId: this.traceId,
|
|
2177
|
+
spanId: this.spanId,
|
|
2178
|
+
type: "tool_result",
|
|
2179
|
+
content: this.name,
|
|
2180
|
+
timestamp: endTimeMs,
|
|
2181
|
+
metadata: {
|
|
2182
|
+
...this.rawOutput !== void 0 ? { result: this.rawOutput } : {},
|
|
2183
|
+
...this.error ? { error: this.error } : {}
|
|
2184
|
+
}
|
|
2185
|
+
});
|
|
2186
|
+
}
|
|
2187
|
+
};
|
|
2188
|
+
var LiveInteraction = class {
|
|
2189
|
+
constructor(context7, traceId, analytics, directShipper, routing) {
|
|
2190
|
+
this.usageEmitted = false;
|
|
2191
|
+
this.context = context7;
|
|
2192
|
+
this.analytics = analytics;
|
|
2193
|
+
this.tracer = trace4.getTracer("traceloop.tracer");
|
|
2194
|
+
this.traceId = traceId;
|
|
2195
|
+
this.directShipper = directShipper;
|
|
2196
|
+
this.routing = routing;
|
|
2197
|
+
}
|
|
2198
|
+
/**
|
|
2199
|
+
* Record the routing binding this interaction pushed onto the context stack
|
|
2200
|
+
* (via {@link bindRoutingContext} in `begin()`) so {@link finish} removes
|
|
2201
|
+
* exactly its own entry — non-LIFO safe, and leaving any still-open sibling's
|
|
2202
|
+
* binding intact.
|
|
2203
|
+
*/
|
|
2204
|
+
setBoundContext(bound) {
|
|
2205
|
+
this.boundContext = bound;
|
|
2206
|
+
}
|
|
2207
|
+
/** Stamp a manually-created OTel span with this interaction's routing. */
|
|
2208
|
+
stampRouting(span) {
|
|
2209
|
+
if (!this.routing) return;
|
|
2210
|
+
stampSpan(span, this.routing.projectId, this.routing.authHint);
|
|
2211
|
+
}
|
|
2212
|
+
ensureTraceId(preferred) {
|
|
2213
|
+
if (preferred) {
|
|
2214
|
+
this.traceId = preferred;
|
|
2215
|
+
return preferred;
|
|
2216
|
+
}
|
|
2217
|
+
if (this.traceId) {
|
|
2218
|
+
return this.traceId;
|
|
2219
|
+
}
|
|
2220
|
+
this.traceId = base64Encode(randomBytes(16));
|
|
2221
|
+
return this.traceId;
|
|
2222
|
+
}
|
|
2223
|
+
resolveLiveTraceId(explicitTraceId) {
|
|
2224
|
+
if (explicitTraceId) {
|
|
2225
|
+
this.traceId = explicitTraceId;
|
|
2226
|
+
return explicitTraceId;
|
|
2227
|
+
}
|
|
2228
|
+
const activeSpan = trace4.getSpan(context4.active());
|
|
2229
|
+
const activeTraceId = activeSpan == null ? void 0 : activeSpan.spanContext().traceId;
|
|
2230
|
+
if (activeTraceId) {
|
|
2231
|
+
this.traceId = activeTraceId;
|
|
2232
|
+
return activeTraceId;
|
|
2233
|
+
}
|
|
2234
|
+
return this.traceId;
|
|
2235
|
+
}
|
|
2236
|
+
emitLiveEvent(event) {
|
|
2237
|
+
var _a, _b;
|
|
2238
|
+
const traceId = (_a = this.resolveLiveTraceId(event.traceId)) != null ? _a : this.ensureTraceId();
|
|
2239
|
+
sendLocalDebuggerLiveEvent({
|
|
2240
|
+
...event,
|
|
2241
|
+
traceId,
|
|
2242
|
+
metadata: {
|
|
2243
|
+
...getLocalDebuggerMetadata(this.context),
|
|
2244
|
+
...(_b = event.metadata) != null ? _b : {}
|
|
2245
|
+
}
|
|
2246
|
+
});
|
|
2247
|
+
}
|
|
2248
|
+
getTraceId() {
|
|
2249
|
+
return this.traceId;
|
|
2250
|
+
}
|
|
2251
|
+
async withSpan(params, fn, thisArg, ...args) {
|
|
2252
|
+
var _a;
|
|
2253
|
+
const taskName = typeof params === "string" ? params : params.name;
|
|
2254
|
+
const properties = typeof params === "string" ? {
|
|
2255
|
+
...getPropertiesFromContext(this.context)
|
|
2256
|
+
} : {
|
|
2257
|
+
...getPropertiesFromContext(this.context),
|
|
2258
|
+
...params.properties || {}
|
|
2259
|
+
};
|
|
2260
|
+
const inputParameters = typeof params === "string" ? void 0 : params.inputParameters;
|
|
2261
|
+
if ((_a = this.analytics) == null ? void 0 : _a.debugLogs) {
|
|
2262
|
+
console.log("[raindrop] using withSpan in liveInteraction");
|
|
2263
|
+
}
|
|
2264
|
+
if (this.directShipper) {
|
|
2265
|
+
const activeContext = getActiveTraceContext();
|
|
2266
|
+
const traceIdB64 = this.ensureTraceId(activeContext.traceIdB64);
|
|
2267
|
+
const parentSpanIdB64 = activeContext.parentSpanIdB64;
|
|
2268
|
+
const spanIdB64 = base64Encode(randomBytes(8));
|
|
2269
|
+
const startTimeMs = Date.now();
|
|
2270
|
+
const spanContext = {
|
|
2271
|
+
traceId: base64ToHex(traceIdB64),
|
|
2272
|
+
spanId: base64ToHex(spanIdB64),
|
|
2273
|
+
traceFlags: TraceFlags2.SAMPLED
|
|
2274
|
+
};
|
|
2275
|
+
const wrappedContext = trace4.setSpan(context4.active(), trace4.wrapSpanContext(spanContext));
|
|
2276
|
+
const invoke = () => this.routing ? withRoutingContext(this.routing, () => fn.apply(thisArg, args)) : fn.apply(thisArg, args);
|
|
2277
|
+
try {
|
|
2278
|
+
const result = await context4.with(wrappedContext, invoke);
|
|
2279
|
+
const endTimeMs = Date.now();
|
|
2280
|
+
this.directShipper.sendSpan({
|
|
2281
|
+
name: taskName,
|
|
2282
|
+
spanKind: "task",
|
|
2283
|
+
spanId: spanIdB64,
|
|
2284
|
+
input: inputParameters !== void 0 ? serializeSpanValue(inputParameters) : void 0,
|
|
2285
|
+
output: result !== void 0 ? serializeSpanValue(result) : void 0,
|
|
2286
|
+
durationMs: endTimeMs - startTimeMs,
|
|
2287
|
+
startTimeMs,
|
|
2288
|
+
endTimeMs,
|
|
2289
|
+
properties,
|
|
2290
|
+
traceId: traceIdB64,
|
|
2291
|
+
parentSpanId: parentSpanIdB64
|
|
2292
|
+
});
|
|
2293
|
+
return result;
|
|
2294
|
+
} catch (error) {
|
|
2295
|
+
const endTimeMs = Date.now();
|
|
2296
|
+
this.directShipper.sendSpan({
|
|
2297
|
+
name: taskName,
|
|
2298
|
+
spanKind: "task",
|
|
2299
|
+
spanId: spanIdB64,
|
|
2300
|
+
input: inputParameters !== void 0 ? serializeSpanValue(inputParameters) : void 0,
|
|
2301
|
+
durationMs: endTimeMs - startTimeMs,
|
|
2302
|
+
startTimeMs,
|
|
2303
|
+
endTimeMs,
|
|
2304
|
+
error: error instanceof Error ? error.message : String(error),
|
|
2305
|
+
properties,
|
|
2306
|
+
traceId: traceIdB64,
|
|
2307
|
+
parentSpanId: parentSpanIdB64
|
|
2308
|
+
});
|
|
2309
|
+
throw error;
|
|
2310
|
+
}
|
|
2311
|
+
}
|
|
2312
|
+
const wrappedFn = (...fnArgs) => {
|
|
2313
|
+
const activeSpan = trace4.getSpan(context4.active());
|
|
2314
|
+
const activeTraceId = activeSpan == null ? void 0 : activeSpan.spanContext().traceId;
|
|
2315
|
+
if (activeTraceId) {
|
|
2316
|
+
this.traceId = activeTraceId;
|
|
2317
|
+
}
|
|
2318
|
+
if (activeSpan) {
|
|
2319
|
+
this.stampRouting(activeSpan);
|
|
2320
|
+
}
|
|
2321
|
+
if (this.routing) {
|
|
2322
|
+
return withRoutingContext(this.routing, () => fn.apply(thisArg, fnArgs));
|
|
2323
|
+
}
|
|
2324
|
+
return fn.apply(thisArg, fnArgs);
|
|
2325
|
+
};
|
|
2326
|
+
return withTask(
|
|
2327
|
+
{
|
|
2328
|
+
name: taskName,
|
|
2329
|
+
associationProperties: serializeAssociationProperties(properties),
|
|
2330
|
+
inputParameters,
|
|
2331
|
+
traceContent: params.traceContent,
|
|
2332
|
+
suppressTracing: params.suppressTracing
|
|
2333
|
+
},
|
|
2334
|
+
wrappedFn,
|
|
2335
|
+
...args
|
|
2336
|
+
);
|
|
2337
|
+
}
|
|
2338
|
+
async withTool(params, fn, thisArg, ...args) {
|
|
2339
|
+
var _a;
|
|
2340
|
+
const toolName = params.name;
|
|
2341
|
+
const properties = {
|
|
2342
|
+
...getPropertiesFromContext(this.context),
|
|
2343
|
+
...params.properties || {}
|
|
2344
|
+
};
|
|
2345
|
+
if ((_a = this.analytics) == null ? void 0 : _a.debugLogs) {
|
|
2346
|
+
console.log("[raindrop] using withTool in liveInteraction");
|
|
2347
|
+
}
|
|
2348
|
+
if (this.directShipper) {
|
|
2349
|
+
const activeContext = getActiveTraceContext();
|
|
2350
|
+
const traceIdB64 = this.ensureTraceId(activeContext.traceIdB64);
|
|
2351
|
+
const { parentSpanIdB64 } = activeContext;
|
|
2352
|
+
const spanIdB64 = base64Encode(randomBytes(8));
|
|
2353
|
+
const startTimeMs = Date.now();
|
|
2354
|
+
this.emitLiveEvent({
|
|
2355
|
+
traceId: traceIdB64,
|
|
2356
|
+
spanId: spanIdB64,
|
|
2357
|
+
type: "tool_start",
|
|
2358
|
+
content: toolName,
|
|
2359
|
+
timestamp: startTimeMs,
|
|
2360
|
+
metadata: params.inputParameters ? { args: params.inputParameters } : void 0
|
|
2361
|
+
});
|
|
2362
|
+
const spanContext = {
|
|
2363
|
+
traceId: base64ToHex(traceIdB64),
|
|
2364
|
+
spanId: base64ToHex(spanIdB64),
|
|
2365
|
+
traceFlags: TraceFlags2.SAMPLED
|
|
2366
|
+
};
|
|
2367
|
+
const wrappedContext = trace4.setSpan(context4.active(), trace4.wrapSpanContext(spanContext));
|
|
2368
|
+
const invoke = () => this.routing ? withRoutingContext(this.routing, () => fn.apply(thisArg, args)) : fn.apply(thisArg, args);
|
|
2369
|
+
let result;
|
|
2370
|
+
let error;
|
|
2371
|
+
try {
|
|
2372
|
+
result = await context4.with(wrappedContext, invoke);
|
|
2373
|
+
} catch (err) {
|
|
2374
|
+
error = err instanceof Error ? err.message : String(err);
|
|
2375
|
+
const endTimeMs2 = Date.now();
|
|
2376
|
+
const durationMs2 = endTimeMs2 - startTimeMs;
|
|
2377
|
+
const inputStr2 = params.inputParameters ? stringifyBounded(params.inputParameters) : void 0;
|
|
2378
|
+
this.directShipper.sendToolSpan({
|
|
2379
|
+
name: toolName,
|
|
2380
|
+
spanId: spanIdB64,
|
|
2381
|
+
input: inputStr2,
|
|
2382
|
+
output: void 0,
|
|
2383
|
+
durationMs: durationMs2,
|
|
2384
|
+
startTimeMs,
|
|
2385
|
+
endTimeMs: endTimeMs2,
|
|
2386
|
+
error,
|
|
2387
|
+
properties,
|
|
2388
|
+
traceId: traceIdB64,
|
|
2389
|
+
parentSpanId: parentSpanIdB64
|
|
2390
|
+
});
|
|
2391
|
+
this.emitLiveEvent({
|
|
2392
|
+
traceId: traceIdB64,
|
|
2393
|
+
spanId: spanIdB64,
|
|
2394
|
+
type: "tool_result",
|
|
2395
|
+
content: toolName,
|
|
2396
|
+
timestamp: endTimeMs2,
|
|
2397
|
+
metadata: {
|
|
2398
|
+
...params.inputParameters ? { args: params.inputParameters } : {},
|
|
2399
|
+
error
|
|
2400
|
+
}
|
|
2401
|
+
});
|
|
2402
|
+
throw err;
|
|
2403
|
+
}
|
|
2404
|
+
const endTimeMs = Date.now();
|
|
2405
|
+
const durationMs = endTimeMs - startTimeMs;
|
|
2406
|
+
const inputStr = params.inputParameters ? stringifyBounded(params.inputParameters) : void 0;
|
|
2407
|
+
const outputStr = result !== void 0 ? stringifyBounded(result) : void 0;
|
|
2408
|
+
this.directShipper.sendToolSpan({
|
|
2409
|
+
name: toolName,
|
|
2410
|
+
spanId: spanIdB64,
|
|
2411
|
+
input: inputStr,
|
|
2412
|
+
output: outputStr,
|
|
2413
|
+
durationMs,
|
|
2414
|
+
startTimeMs,
|
|
2415
|
+
endTimeMs,
|
|
2416
|
+
error: void 0,
|
|
2417
|
+
properties,
|
|
2418
|
+
traceId: traceIdB64,
|
|
2419
|
+
parentSpanId: parentSpanIdB64
|
|
2420
|
+
});
|
|
2421
|
+
this.emitLiveEvent({
|
|
2422
|
+
traceId: traceIdB64,
|
|
2423
|
+
spanId: spanIdB64,
|
|
2424
|
+
type: "tool_result",
|
|
2425
|
+
content: toolName,
|
|
2426
|
+
timestamp: endTimeMs,
|
|
2427
|
+
metadata: {
|
|
2428
|
+
...params.inputParameters ? { args: params.inputParameters } : {},
|
|
2429
|
+
...result !== void 0 ? { result } : {}
|
|
2430
|
+
}
|
|
2431
|
+
});
|
|
2432
|
+
return result;
|
|
2433
|
+
}
|
|
2434
|
+
const inputParams = params.inputParameters ? [params.inputParameters] : void 0;
|
|
2435
|
+
const emitLive = (event) => this.emitLiveEvent(event);
|
|
2436
|
+
const wrapped = async (...wrappedArgs) => {
|
|
2437
|
+
const activeSpan = trace4.getSpan(context4.active());
|
|
2438
|
+
const ctx = activeSpan == null ? void 0 : activeSpan.spanContext();
|
|
2439
|
+
const liveSpanId = ctx && isValidSpanId2(ctx.spanId) ? ctx.spanId : void 0;
|
|
2440
|
+
if (activeSpan) {
|
|
2441
|
+
this.stampRouting(activeSpan);
|
|
2442
|
+
}
|
|
2443
|
+
emitLive({
|
|
2444
|
+
type: "tool_start",
|
|
2445
|
+
spanId: liveSpanId,
|
|
2446
|
+
content: toolName,
|
|
2447
|
+
timestamp: Date.now(),
|
|
2448
|
+
metadata: params.inputParameters ? { args: params.inputParameters } : void 0
|
|
2449
|
+
});
|
|
2450
|
+
try {
|
|
2451
|
+
const r = this.routing ? await withRoutingContext(this.routing, () => fn.apply(thisArg, wrappedArgs)) : await fn.apply(thisArg, wrappedArgs);
|
|
2452
|
+
emitLive({
|
|
2453
|
+
type: "tool_result",
|
|
2454
|
+
spanId: liveSpanId,
|
|
2455
|
+
content: toolName,
|
|
2456
|
+
timestamp: Date.now(),
|
|
2457
|
+
metadata: {
|
|
2458
|
+
...params.inputParameters ? { args: params.inputParameters } : {},
|
|
2459
|
+
...r !== void 0 ? { result: r } : {}
|
|
2460
|
+
}
|
|
2461
|
+
});
|
|
2462
|
+
return r;
|
|
2463
|
+
} catch (error) {
|
|
2464
|
+
emitLive({
|
|
2465
|
+
type: "tool_result",
|
|
2466
|
+
spanId: liveSpanId,
|
|
2467
|
+
content: toolName,
|
|
2468
|
+
timestamp: Date.now(),
|
|
2469
|
+
metadata: {
|
|
2470
|
+
...params.inputParameters ? { args: params.inputParameters } : {},
|
|
2471
|
+
error: error instanceof Error ? error.message : String(error)
|
|
2472
|
+
}
|
|
2473
|
+
});
|
|
2474
|
+
throw error;
|
|
2475
|
+
}
|
|
2476
|
+
};
|
|
2477
|
+
return withTool(
|
|
2478
|
+
{
|
|
2479
|
+
name: toolName,
|
|
2480
|
+
associationProperties: serializeAssociationProperties(properties),
|
|
2481
|
+
inputParameters: inputParams,
|
|
2482
|
+
version: params.version,
|
|
2483
|
+
traceContent: params.traceContent,
|
|
2484
|
+
suppressTracing: params.suppressTracing
|
|
2485
|
+
},
|
|
2486
|
+
wrapped,
|
|
2487
|
+
...args
|
|
2488
|
+
);
|
|
2489
|
+
}
|
|
2490
|
+
startSpan(params) {
|
|
2491
|
+
const { name, properties = {} } = params;
|
|
2492
|
+
const span = this.tracer.startSpan(name);
|
|
2493
|
+
const contextProperties = getPropertiesFromContext(this.context);
|
|
2494
|
+
setAssociationProperties(span, contextProperties);
|
|
2495
|
+
span.setAttribute("traceloop.span.kind", "task");
|
|
2496
|
+
setAssociationProperties(span, properties);
|
|
2497
|
+
this.stampRouting(span);
|
|
2498
|
+
return span;
|
|
2499
|
+
}
|
|
2500
|
+
startToolSpan(params) {
|
|
2501
|
+
var _a, _b;
|
|
2502
|
+
const { name, properties = {}, inputParameters } = params;
|
|
2503
|
+
const contextProperties = getPropertiesFromContext(this.context);
|
|
2504
|
+
const mergedProperties = {
|
|
2505
|
+
...contextProperties,
|
|
2506
|
+
...properties
|
|
2507
|
+
};
|
|
2508
|
+
if (this.directShipper) {
|
|
2509
|
+
const activeTraceContext = getActiveTraceContext();
|
|
2510
|
+
const traceIdB64 = this.ensureTraceId(activeTraceContext.traceIdB64);
|
|
2511
|
+
const { parentSpanIdB64 } = activeTraceContext;
|
|
2512
|
+
const spanIdB64 = base64Encode(randomBytes(8));
|
|
2513
|
+
if ((_a = this.analytics) == null ? void 0 : _a.debugLogs) {
|
|
2514
|
+
console.log(`[raindrop] startToolSpan (direct): started tool span "${name}"`);
|
|
2515
|
+
}
|
|
2516
|
+
this.emitLiveEvent({
|
|
2517
|
+
traceId: traceIdB64,
|
|
2518
|
+
spanId: spanIdB64,
|
|
2519
|
+
type: "tool_start",
|
|
2520
|
+
content: name,
|
|
2521
|
+
timestamp: Date.now(),
|
|
2522
|
+
metadata: inputParameters !== void 0 ? { args: inputParameters } : void 0
|
|
2523
|
+
});
|
|
2524
|
+
return new DirectToolSpan({
|
|
2525
|
+
name,
|
|
2526
|
+
properties: mergedProperties,
|
|
2527
|
+
directShipper: this.directShipper,
|
|
2528
|
+
traceId: traceIdB64,
|
|
2529
|
+
spanId: spanIdB64,
|
|
2530
|
+
parentSpanId: parentSpanIdB64,
|
|
2531
|
+
input: inputParameters,
|
|
2532
|
+
emitLiveEvent: (event) => this.emitLiveEvent(event)
|
|
2533
|
+
});
|
|
2534
|
+
}
|
|
2535
|
+
const span = this.tracer.startSpan(name);
|
|
2536
|
+
setAssociationProperties(span, contextProperties);
|
|
2537
|
+
span.setAttribute("traceloop.span.kind", "tool");
|
|
2538
|
+
setAssociationProperties(span, properties);
|
|
2539
|
+
this.stampRouting(span);
|
|
2540
|
+
if (inputParameters !== void 0) {
|
|
2541
|
+
span.setAttribute("traceloop.entity.input", serializeSpanValue(inputParameters));
|
|
2542
|
+
}
|
|
2543
|
+
if ((_b = this.analytics) == null ? void 0 : _b.debugLogs) {
|
|
2544
|
+
console.log(`[raindrop] startToolSpan: started tool span "${name}"`);
|
|
2545
|
+
}
|
|
2546
|
+
const startSpanCtx = span.spanContext();
|
|
2547
|
+
const startSpanIdHex = isValidSpanId2(startSpanCtx.spanId) ? startSpanCtx.spanId : void 0;
|
|
2548
|
+
this.emitLiveEvent({
|
|
2549
|
+
type: "tool_start",
|
|
2550
|
+
spanId: startSpanIdHex,
|
|
2551
|
+
content: name,
|
|
2552
|
+
timestamp: Date.now(),
|
|
2553
|
+
metadata: inputParameters !== void 0 ? { args: inputParameters } : void 0
|
|
2554
|
+
});
|
|
2555
|
+
return new LiveToolSpan({
|
|
2556
|
+
span,
|
|
2557
|
+
name,
|
|
2558
|
+
emitLiveEvent: (event) => this.emitLiveEvent(event)
|
|
2559
|
+
});
|
|
2560
|
+
}
|
|
2561
|
+
setProperties(properties) {
|
|
2562
|
+
var _a;
|
|
2563
|
+
this.context.properties = { ...this.context.properties, ...properties };
|
|
2564
|
+
(_a = this.analytics) == null ? void 0 : _a._trackAiPartial({
|
|
2565
|
+
eventId: this.context.eventId,
|
|
2566
|
+
properties
|
|
2567
|
+
});
|
|
2568
|
+
}
|
|
2569
|
+
setProperty(key, value) {
|
|
2570
|
+
var _a;
|
|
2571
|
+
this.context.properties = { ...this.context.properties, [key]: value };
|
|
2572
|
+
(_a = this.analytics) == null ? void 0 : _a._trackAiPartial({
|
|
2573
|
+
eventId: this.context.eventId,
|
|
2574
|
+
properties: { [key]: value }
|
|
2575
|
+
});
|
|
2576
|
+
}
|
|
2577
|
+
addAttachments(attachments) {
|
|
2578
|
+
var _a;
|
|
2579
|
+
this.context.attachments = [...this.context.attachments || [], ...attachments];
|
|
2580
|
+
(_a = this.analytics) == null ? void 0 : _a._trackAiPartial({
|
|
2581
|
+
eventId: this.context.eventId,
|
|
2582
|
+
attachments
|
|
2583
|
+
});
|
|
2584
|
+
}
|
|
2585
|
+
setFeatureFlag(name, value) {
|
|
2586
|
+
var _a;
|
|
2587
|
+
const normalized = String(value != null ? value : "true");
|
|
2588
|
+
const existing = this.context.featureFlags ? normalizeFeatureFlags(this.context.featureFlags) : {};
|
|
2589
|
+
this.context.featureFlags = { ...existing, [name]: normalized };
|
|
2590
|
+
(_a = this.analytics) == null ? void 0 : _a._trackAiPartial({
|
|
2591
|
+
eventId: this.context.eventId,
|
|
2592
|
+
featureFlags: { [name]: normalized }
|
|
2593
|
+
});
|
|
2594
|
+
}
|
|
2595
|
+
setFeatureFlags(flags) {
|
|
2596
|
+
var _a;
|
|
2597
|
+
const normalized = normalizeFeatureFlags(flags);
|
|
2598
|
+
const existing = this.context.featureFlags ? normalizeFeatureFlags(this.context.featureFlags) : {};
|
|
2599
|
+
this.context.featureFlags = { ...existing, ...normalized };
|
|
2600
|
+
(_a = this.analytics) == null ? void 0 : _a._trackAiPartial({
|
|
2601
|
+
eventId: this.context.eventId,
|
|
2602
|
+
featureFlags: normalized
|
|
2603
|
+
});
|
|
2604
|
+
}
|
|
2605
|
+
setInput(input) {
|
|
2606
|
+
var _a;
|
|
2607
|
+
this.context.input = input;
|
|
2608
|
+
(_a = this.analytics) == null ? void 0 : _a._trackAiPartial({
|
|
2609
|
+
eventId: this.context.eventId,
|
|
2610
|
+
input
|
|
2611
|
+
});
|
|
2612
|
+
}
|
|
2613
|
+
vercelAiSdkMetadata() {
|
|
2614
|
+
const metadata = {};
|
|
2615
|
+
if (this.context.userId) {
|
|
2616
|
+
metadata["traceloop.association.properties.user_id"] = this.context.userId;
|
|
2617
|
+
}
|
|
2618
|
+
if (this.context.convoId) {
|
|
2619
|
+
metadata["traceloop.association.properties.convo_id"] = this.context.convoId;
|
|
2620
|
+
}
|
|
2621
|
+
if (this.context.eventId) {
|
|
2622
|
+
metadata["traceloop.association.properties.event_id"] = this.context.eventId;
|
|
2623
|
+
}
|
|
2624
|
+
if (this.context.event) {
|
|
2625
|
+
metadata["traceloop.association.properties.event_name"] = this.context.event;
|
|
2626
|
+
}
|
|
2627
|
+
if (this.context.properties) {
|
|
2628
|
+
for (const [key, value] of Object.entries(this.context.properties)) {
|
|
2629
|
+
if (value === void 0) {
|
|
2630
|
+
continue;
|
|
2631
|
+
}
|
|
2632
|
+
metadata[`traceloop.association.properties.${key}`] = serializeSpanValue(value);
|
|
2633
|
+
}
|
|
2634
|
+
}
|
|
2635
|
+
return metadata;
|
|
2636
|
+
}
|
|
2637
|
+
getEventId() {
|
|
2638
|
+
return this.context.eventId;
|
|
2639
|
+
}
|
|
2640
|
+
getUserId() {
|
|
2641
|
+
return this.context.userId;
|
|
2642
|
+
}
|
|
2643
|
+
getConvoId() {
|
|
2644
|
+
return this.context.convoId;
|
|
2645
|
+
}
|
|
2646
|
+
/**
|
|
2647
|
+
* Bind this turn's tool-call event opt-in, once.
|
|
2648
|
+
*
|
|
2649
|
+
* Owned by the interaction rather than by the execution context: the frame
|
|
2650
|
+
* lives exactly as long as the turn does (removed by `finish()`, and dead once
|
|
2651
|
+
* this interaction is collected), instead of outliving it on a context the
|
|
2652
|
+
* host may reuse for unrelated work.
|
|
2653
|
+
*/
|
|
2654
|
+
bindToolEventsOptIn(attributes) {
|
|
2655
|
+
if (this.toolEventsFrame) return;
|
|
2656
|
+
this.toolEventsFrame = bindSpanAttributes(attributes, this);
|
|
2657
|
+
}
|
|
2658
|
+
/**
|
|
2659
|
+
* Carry a `begin({ tools })` override to every span started inside this
|
|
2660
|
+
* interaction. Frames stamp strings, so the normalized catalog rides as one
|
|
2661
|
+
* JSON marker attribute; the span processor turns it into `ai.prompt.tools`
|
|
2662
|
+
* on model spans (and drops it from every other span) when the span ends.
|
|
2663
|
+
* Same lifetime as the tool-events frame: removed by `finish()`.
|
|
2664
|
+
*/
|
|
2665
|
+
bindPromptToolsOverride(tools) {
|
|
2666
|
+
var _a;
|
|
2667
|
+
if (tools === void 0 || this.promptToolsFrame) return;
|
|
2668
|
+
const declarations = (_a = normalizeToolDeclarations(tools)) != null ? _a : [];
|
|
2669
|
+
this.promptToolsFrame = bindSpanAttributes(
|
|
2670
|
+
{ [PROMPT_TOOLS_OVERRIDE_MARKER]: JSON.stringify(declarations) },
|
|
2671
|
+
this
|
|
2672
|
+
);
|
|
2673
|
+
}
|
|
2674
|
+
subagent(options) {
|
|
2675
|
+
return recordSubagentDispatch(this, options);
|
|
2676
|
+
}
|
|
2677
|
+
/**
|
|
2678
|
+
* Record the tool span a detached dispatch is written on.
|
|
2679
|
+
*
|
|
2680
|
+
* Distinct from {@link startToolSpan} in the two ways the hand-off needs:
|
|
2681
|
+
* the contract's keys are set as RAW span attributes (under the
|
|
2682
|
+
* `traceloop.association.properties.` prefix the backend's reader cannot see
|
|
2683
|
+
* them), and the caller needs the span's ids to build the carrier.
|
|
2684
|
+
*
|
|
2685
|
+
* @internal
|
|
2686
|
+
*/
|
|
2687
|
+
recordDispatchSpan(params) {
|
|
2688
|
+
var _a;
|
|
2689
|
+
const properties = {
|
|
2690
|
+
...getPropertiesFromContext(this.context),
|
|
2691
|
+
...(_a = params.properties) != null ? _a : {}
|
|
2692
|
+
};
|
|
2693
|
+
const input = params.input !== void 0 ? serializeSpanValue(params.input) : void 0;
|
|
2694
|
+
const output = serializeSpanValue(params.output);
|
|
2695
|
+
if (this.directShipper) {
|
|
2696
|
+
const activeContext = getActiveTraceContext();
|
|
2697
|
+
const traceIdB64 = this.ensureTraceId(activeContext.traceIdB64);
|
|
2698
|
+
const spanIdB64 = base64Encode(randomBytes(8));
|
|
2699
|
+
const timeMs = Date.now();
|
|
2700
|
+
this.directShipper.sendToolSpan({
|
|
2701
|
+
name: params.name,
|
|
2702
|
+
spanId: spanIdB64,
|
|
2703
|
+
input,
|
|
2704
|
+
output,
|
|
2705
|
+
durationMs: 0,
|
|
2706
|
+
startTimeMs: timeMs,
|
|
2707
|
+
endTimeMs: timeMs,
|
|
2708
|
+
properties,
|
|
2709
|
+
traceId: traceIdB64,
|
|
2710
|
+
parentSpanId: activeContext.parentSpanIdB64,
|
|
2711
|
+
attributes: params.attributes
|
|
2712
|
+
});
|
|
2713
|
+
this.emitLiveEvent({
|
|
2714
|
+
traceId: traceIdB64,
|
|
2715
|
+
spanId: spanIdB64,
|
|
2716
|
+
type: "tool_result",
|
|
2717
|
+
content: params.name,
|
|
2718
|
+
timestamp: timeMs,
|
|
2719
|
+
metadata: { result: params.output }
|
|
2720
|
+
});
|
|
2721
|
+
return { traceIdHex: base64ToHex(traceIdB64), spanIdHex: base64ToHex(spanIdB64) };
|
|
2722
|
+
}
|
|
2723
|
+
const span = this.tracer.startSpan(params.name);
|
|
2724
|
+
setAssociationProperties(span, properties);
|
|
2725
|
+
span.setAttribute("traceloop.span.kind", "tool");
|
|
2726
|
+
this.stampRouting(span);
|
|
2727
|
+
for (const [key, value] of Object.entries(params.attributes)) {
|
|
2728
|
+
span.setAttribute(key, value);
|
|
2729
|
+
}
|
|
2730
|
+
if (input !== void 0) {
|
|
2731
|
+
span.setAttribute("traceloop.entity.input", input);
|
|
2732
|
+
}
|
|
2733
|
+
span.setAttribute("traceloop.entity.output", output);
|
|
2734
|
+
span.setStatus({ code: SpanStatusCode2.OK });
|
|
2735
|
+
const spanContext = span.spanContext();
|
|
2736
|
+
span.end();
|
|
2737
|
+
this.emitLiveEvent({
|
|
2738
|
+
spanId: isValidSpanId2(spanContext.spanId) ? spanContext.spanId : void 0,
|
|
2739
|
+
type: "tool_result",
|
|
2740
|
+
content: params.name,
|
|
2741
|
+
timestamp: Date.now(),
|
|
2742
|
+
metadata: { result: params.output }
|
|
2743
|
+
});
|
|
2744
|
+
return {
|
|
2745
|
+
traceIdHex: isValidTraceId2(spanContext.traceId) ? spanContext.traceId : void 0,
|
|
2746
|
+
spanIdHex: isValidSpanId2(spanContext.spanId) ? spanContext.spanId : void 0
|
|
2747
|
+
};
|
|
2748
|
+
}
|
|
2749
|
+
/**
|
|
2750
|
+
* Record the errored span a detached sub-agent's failure needs when nothing
|
|
2751
|
+
* else is open.
|
|
2752
|
+
*
|
|
2753
|
+
* Frequently the child's ONLY span, so it carries the full reverse reference:
|
|
2754
|
+
* anything reading it alone still knows which launch it belongs to. Those
|
|
2755
|
+
* attributes come from the run's own frame rather than the ambient stack,
|
|
2756
|
+
* because `fail()` is often called from a different task than the one that
|
|
2757
|
+
* opened the run and this is the span that can least afford to lose the link.
|
|
2758
|
+
*
|
|
2759
|
+
* @internal
|
|
2760
|
+
*/
|
|
2761
|
+
recordSubagentAbortSpan(params) {
|
|
2762
|
+
const { reason, message, attributes } = params;
|
|
2763
|
+
const properties = getPropertiesFromContext(this.context);
|
|
2764
|
+
if (this.directShipper) {
|
|
2765
|
+
const activeContext = getActiveTraceContext();
|
|
2766
|
+
const timeMs = Date.now();
|
|
2767
|
+
this.directShipper.sendSpan({
|
|
2768
|
+
name: SUBAGENT_ABORT_SPAN_NAME,
|
|
2769
|
+
// Not "tool": the run died, it did not call anything. `ai.operationId`
|
|
2770
|
+
// below is what keeps the span (see the attribute's docs in core).
|
|
2771
|
+
spanKind: "task",
|
|
2772
|
+
spanId: base64Encode(randomBytes(8)),
|
|
2773
|
+
durationMs: 0,
|
|
2774
|
+
startTimeMs: timeMs,
|
|
2775
|
+
endTimeMs: timeMs,
|
|
2776
|
+
error: message,
|
|
2777
|
+
properties,
|
|
2778
|
+
traceId: this.ensureTraceId(activeContext.traceIdB64),
|
|
2779
|
+
parentSpanId: activeContext.parentSpanIdB64,
|
|
2780
|
+
attributes: { ...attributes, [OPERATION_ID_ATTRIBUTE]: SUBAGENT_ABORT_OPERATION_ID }
|
|
2781
|
+
});
|
|
2782
|
+
return;
|
|
2783
|
+
}
|
|
2784
|
+
const span = this.tracer.startSpan(SUBAGENT_ABORT_SPAN_NAME);
|
|
2785
|
+
span.setAttribute(OPERATION_ID_ATTRIBUTE, SUBAGENT_ABORT_OPERATION_ID);
|
|
2786
|
+
setAssociationProperties(span, properties);
|
|
2787
|
+
this.stampRouting(span);
|
|
2788
|
+
for (const [key, value] of Object.entries(attributes)) {
|
|
2789
|
+
span.setAttribute(key, value);
|
|
2790
|
+
}
|
|
2791
|
+
span.setStatus({ code: SpanStatusCode2.ERROR, message });
|
|
2792
|
+
span.recordException(reason instanceof Error ? reason : new Error(message));
|
|
2793
|
+
span.end();
|
|
2794
|
+
}
|
|
2795
|
+
async finish(resultEvent) {
|
|
2796
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _i;
|
|
2797
|
+
unbindRoutingContext(this.boundContext);
|
|
2798
|
+
this.boundContext = void 0;
|
|
2799
|
+
unbindSpanAttributes(this.toolEventsFrame);
|
|
2800
|
+
this.toolEventsFrame = void 0;
|
|
2801
|
+
unbindSpanAttributes(this.promptToolsFrame);
|
|
2802
|
+
this.promptToolsFrame = void 0;
|
|
2803
|
+
if (!this.traceId) {
|
|
2804
|
+
this.resolveLiveTraceId();
|
|
2805
|
+
}
|
|
2806
|
+
const eventId = resultEvent.eventId || this.context.eventId;
|
|
2807
|
+
if (!this.usageEmitted) {
|
|
2808
|
+
const appGitSnapshot = (_b = (_a = this.analytics) == null ? void 0 : _a.getAppGitSnapshot(resultEvent.properties, eventId)) != null ? _b : {};
|
|
2809
|
+
const usageProperties = {};
|
|
2810
|
+
for (const key of [APP_COMMIT_SHA, APP_COMMIT_DIRTY, APP_BRANCH]) {
|
|
2811
|
+
if (resultEvent.properties && Object.prototype.hasOwnProperty.call(resultEvent.properties, key)) {
|
|
2812
|
+
usageProperties[key] = resultEvent.properties[key];
|
|
2813
|
+
}
|
|
2814
|
+
}
|
|
2815
|
+
(_e = this.analytics) == null ? void 0 : _e._recordModelUsage(
|
|
2816
|
+
eventId,
|
|
2817
|
+
(_c = resultEvent.model) != null ? _c : this.context.model,
|
|
2818
|
+
(_d = resultEvent.usage) != null ? _d : this.context.usage,
|
|
2819
|
+
withAppGitProperties(usageProperties, appGitSnapshot),
|
|
2820
|
+
appGitSnapshot
|
|
2821
|
+
);
|
|
2822
|
+
this.usageEmitted = true;
|
|
2823
|
+
}
|
|
2824
|
+
const spanFlush = (async () => {
|
|
2825
|
+
var _a2;
|
|
2826
|
+
try {
|
|
2827
|
+
await ((_a2 = this.analytics) == null ? void 0 : _a2._flushTracingSpans());
|
|
2828
|
+
} catch (e) {
|
|
2829
|
+
}
|
|
2830
|
+
})();
|
|
2831
|
+
if ((_g = (_f = this.analytics) == null ? void 0 : _f._shouldBlockFinishFlush()) != null ? _g : true) {
|
|
2832
|
+
await spanFlush;
|
|
2833
|
+
} else {
|
|
2834
|
+
void spanFlush.catch(() => {
|
|
2835
|
+
});
|
|
2836
|
+
}
|
|
2837
|
+
try {
|
|
2838
|
+
await ((_h = this.analytics) == null ? void 0 : _h._drainInFlightPartials(eventId));
|
|
2839
|
+
} catch (e) {
|
|
2840
|
+
}
|
|
2841
|
+
if (this.traceId) {
|
|
2842
|
+
this.setProperty("trace_id", this.traceId);
|
|
2843
|
+
}
|
|
2844
|
+
await ((_i = this.analytics) == null ? void 0 : _i._trackAiPartial({
|
|
2845
|
+
...resultEvent,
|
|
2846
|
+
eventId,
|
|
2847
|
+
isPending: false
|
|
2848
|
+
}));
|
|
2849
|
+
}
|
|
2850
|
+
trackTool(params) {
|
|
2851
|
+
var _a, _b, _c;
|
|
2852
|
+
const {
|
|
2853
|
+
name,
|
|
2854
|
+
input,
|
|
2855
|
+
output,
|
|
2856
|
+
error,
|
|
2857
|
+
properties = {},
|
|
2858
|
+
traceId: explicitTraceId,
|
|
2859
|
+
parentSpanId: explicitParentSpanId
|
|
2860
|
+
} = params;
|
|
2861
|
+
const { startTimeMs, endTimeMs, durationMs } = resolveToolTiming(params);
|
|
2862
|
+
if (this.directShipper) {
|
|
2863
|
+
const activeContext = (_a = getExplicitTraceContext(explicitTraceId, explicitParentSpanId)) != null ? _a : getActiveTraceContext();
|
|
2864
|
+
const traceIdB64 = this.ensureTraceId(activeContext.traceIdB64);
|
|
2865
|
+
const { parentSpanIdB64 } = activeContext;
|
|
2866
|
+
const spanIdB64 = base64Encode(randomBytes(8));
|
|
2867
|
+
const inputStr = input !== void 0 ? stringifyBounded(input) : void 0;
|
|
2868
|
+
const outputStr = output !== void 0 ? stringifyBounded(output) : void 0;
|
|
2869
|
+
this.directShipper.sendToolSpan({
|
|
2870
|
+
name,
|
|
2871
|
+
spanId: spanIdB64,
|
|
2872
|
+
input: inputStr,
|
|
2873
|
+
output: outputStr,
|
|
2874
|
+
durationMs,
|
|
2875
|
+
startTimeMs,
|
|
2876
|
+
endTimeMs,
|
|
2877
|
+
error: error ? error instanceof Error ? error.message : String(error) : void 0,
|
|
2878
|
+
properties: {
|
|
2879
|
+
...getPropertiesFromContext(this.context),
|
|
2880
|
+
...properties
|
|
2881
|
+
},
|
|
2882
|
+
traceId: traceIdB64,
|
|
2883
|
+
parentSpanId: parentSpanIdB64
|
|
2884
|
+
});
|
|
2885
|
+
if ((_b = this.analytics) == null ? void 0 : _b.debugLogs) {
|
|
2886
|
+
console.log(`[raindrop] trackTool (direct): logged tool span "${name}"`, {
|
|
2887
|
+
input,
|
|
2888
|
+
output,
|
|
2889
|
+
durationMs,
|
|
2890
|
+
error: error ? String(error) : void 0
|
|
2891
|
+
});
|
|
2892
|
+
}
|
|
2893
|
+
this.emitLiveEvent({
|
|
2894
|
+
traceId: traceIdB64,
|
|
2895
|
+
spanId: spanIdB64,
|
|
2896
|
+
type: "tool_result",
|
|
2897
|
+
content: name,
|
|
2898
|
+
timestamp: endTimeMs,
|
|
2899
|
+
metadata: {
|
|
2900
|
+
...input !== void 0 ? { input } : {},
|
|
2901
|
+
...output !== void 0 ? { result: output } : {},
|
|
2902
|
+
...error ? { error: error instanceof Error ? error.message : String(error) } : {}
|
|
2903
|
+
}
|
|
2904
|
+
});
|
|
2905
|
+
return;
|
|
2906
|
+
}
|
|
2907
|
+
const savedParent = savedParentContext(explicitTraceId, explicitParentSpanId);
|
|
2908
|
+
const span = this.tracer.startSpan(
|
|
2909
|
+
name,
|
|
2910
|
+
{
|
|
2911
|
+
startTime: startTimeMs
|
|
2912
|
+
},
|
|
2913
|
+
savedParent
|
|
2914
|
+
);
|
|
2915
|
+
const contextProperties = getPropertiesFromContext(this.context);
|
|
2916
|
+
setAssociationProperties(span, contextProperties);
|
|
2917
|
+
span.setAttribute("traceloop.span.kind", "tool");
|
|
2918
|
+
setAssociationProperties(span, properties);
|
|
2919
|
+
this.stampRouting(span);
|
|
2920
|
+
if (input !== void 0) {
|
|
2921
|
+
span.setAttribute("traceloop.entity.input", stringifyBounded(input));
|
|
2922
|
+
}
|
|
2923
|
+
if (output !== void 0) {
|
|
2924
|
+
span.setAttribute("traceloop.entity.output", stringifyBounded(output));
|
|
2925
|
+
}
|
|
2926
|
+
if (durationMs !== void 0) {
|
|
2927
|
+
span.setAttribute("traceloop.entity.duration_ms", durationMs);
|
|
2928
|
+
}
|
|
2929
|
+
if (error) {
|
|
2930
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
2931
|
+
span.setStatus({ code: SpanStatusCode2.ERROR, message: errorMessage });
|
|
2932
|
+
span.recordException(error instanceof Error ? error : new Error(errorMessage));
|
|
2933
|
+
} else {
|
|
2934
|
+
span.setStatus({ code: SpanStatusCode2.OK });
|
|
2935
|
+
}
|
|
2936
|
+
span.end(endTimeMs);
|
|
2937
|
+
if ((_c = this.analytics) == null ? void 0 : _c.debugLogs) {
|
|
2938
|
+
console.log(`[raindrop] trackTool: logged tool span "${name}"`, {
|
|
2939
|
+
input,
|
|
2940
|
+
output,
|
|
2941
|
+
durationMs,
|
|
2942
|
+
error: error ? String(error) : void 0
|
|
2943
|
+
});
|
|
2944
|
+
}
|
|
2945
|
+
const trackToolCtx = span.spanContext();
|
|
2946
|
+
const trackToolSpanIdHex = isValidSpanId2(trackToolCtx.spanId) ? trackToolCtx.spanId : void 0;
|
|
2947
|
+
this.emitLiveEvent({
|
|
2948
|
+
type: "tool_result",
|
|
2949
|
+
spanId: trackToolSpanIdHex,
|
|
2950
|
+
content: name,
|
|
2951
|
+
timestamp: endTimeMs,
|
|
2952
|
+
metadata: {
|
|
2953
|
+
...input !== void 0 ? { input } : {},
|
|
2954
|
+
...output !== void 0 ? { result: output } : {},
|
|
2955
|
+
...error ? { error: error instanceof Error ? error.message : String(error) } : {}
|
|
2956
|
+
}
|
|
2957
|
+
});
|
|
2958
|
+
}
|
|
2959
|
+
};
|
|
2960
|
+
|
|
2961
|
+
// src/tracing/liveTracer.ts
|
|
2962
|
+
import { context as context5, isValidSpanId as isValidSpanId3, SpanStatusCode as SpanStatusCode3, trace as trace5 } from "@opentelemetry/api";
|
|
2963
|
+
var LiveTracer = class {
|
|
2964
|
+
constructor(globalProperties, directShipper, routing) {
|
|
2965
|
+
this.tracer = trace5.getTracer("traceloop.tracer");
|
|
2966
|
+
this.globalProperties = globalProperties || {};
|
|
2967
|
+
this.directShipper = directShipper;
|
|
2968
|
+
this.routing = routing;
|
|
2969
|
+
}
|
|
2970
|
+
/** Stamp a manually-created OTel span with this tracer's client routing. */
|
|
2971
|
+
stampRouting(span) {
|
|
2972
|
+
if (!this.routing) return;
|
|
2973
|
+
stampSpan(span, this.routing.projectId, this.routing.authHint);
|
|
2974
|
+
}
|
|
2975
|
+
emitLiveEvent(event) {
|
|
2976
|
+
var _a, _b;
|
|
2977
|
+
const activeSpan = trace5.getSpan(context5.active());
|
|
2978
|
+
const activeTraceId = activeSpan == null ? void 0 : activeSpan.spanContext().traceId;
|
|
2979
|
+
const active = getActiveTraceContext();
|
|
2980
|
+
const traceId = (_b = (_a = event.traceId) != null ? _a : activeTraceId) != null ? _b : active.traceIdB64;
|
|
2981
|
+
if (!traceId) return;
|
|
2982
|
+
sendLocalDebuggerLiveEvent({
|
|
2983
|
+
...event,
|
|
2984
|
+
traceId
|
|
2985
|
+
});
|
|
2986
|
+
}
|
|
2987
|
+
async withSpan(params, fn, thisArg, ...args) {
|
|
2988
|
+
const taskName = typeof params === "string" ? params : params.name;
|
|
2989
|
+
const properties = typeof params === "string" ? {
|
|
2990
|
+
...this.globalProperties
|
|
2991
|
+
} : {
|
|
2992
|
+
...this.globalProperties,
|
|
2993
|
+
...params.properties || {}
|
|
2994
|
+
};
|
|
2995
|
+
const inputParameters = typeof params === "string" ? void 0 : params.inputParameters;
|
|
2996
|
+
const wrappedFn = (...fnArgs) => {
|
|
2997
|
+
const activeSpan = trace5.getSpan(context5.active());
|
|
2998
|
+
if (activeSpan) {
|
|
2999
|
+
this.stampRouting(activeSpan);
|
|
3000
|
+
}
|
|
3001
|
+
if (this.routing) {
|
|
3002
|
+
return withRoutingContext(this.routing, () => fn.apply(thisArg, fnArgs));
|
|
3003
|
+
}
|
|
3004
|
+
return fn.apply(thisArg, fnArgs);
|
|
3005
|
+
};
|
|
3006
|
+
return withTask(
|
|
3007
|
+
{
|
|
3008
|
+
name: taskName,
|
|
3009
|
+
associationProperties: properties,
|
|
3010
|
+
inputParameters,
|
|
3011
|
+
traceContent: params.traceContent,
|
|
3012
|
+
suppressTracing: params.suppressTracing
|
|
3013
|
+
},
|
|
3014
|
+
wrappedFn,
|
|
3015
|
+
...args
|
|
3016
|
+
);
|
|
3017
|
+
}
|
|
3018
|
+
trackTool(params) {
|
|
3019
|
+
var _a, _b;
|
|
3020
|
+
const {
|
|
3021
|
+
name,
|
|
3022
|
+
input,
|
|
3023
|
+
output,
|
|
3024
|
+
error,
|
|
3025
|
+
properties = {},
|
|
3026
|
+
traceId: explicitTraceId,
|
|
3027
|
+
parentSpanId: explicitParentSpanId
|
|
3028
|
+
} = params;
|
|
3029
|
+
const { startTimeMs, endTimeMs, durationMs } = resolveToolTiming(params);
|
|
3030
|
+
if (this.directShipper) {
|
|
3031
|
+
const { traceIdB64, parentSpanIdB64 } = (_a = getExplicitTraceContext(explicitTraceId, explicitParentSpanId)) != null ? _a : getActiveTraceContext();
|
|
3032
|
+
const spanIdB64 = base64Encode(randomBytes(8));
|
|
3033
|
+
const inputStr = input !== void 0 ? stringifyBounded(input) : void 0;
|
|
3034
|
+
const outputStr = output !== void 0 ? stringifyBounded(output) : void 0;
|
|
3035
|
+
this.directShipper.sendToolSpan({
|
|
3036
|
+
name,
|
|
3037
|
+
spanId: spanIdB64,
|
|
3038
|
+
input: inputStr,
|
|
3039
|
+
output: outputStr,
|
|
3040
|
+
durationMs,
|
|
3041
|
+
startTimeMs,
|
|
3042
|
+
endTimeMs,
|
|
3043
|
+
error: error ? error instanceof Error ? error.message : String(error) : void 0,
|
|
3044
|
+
properties: {
|
|
3045
|
+
...this.globalProperties,
|
|
3046
|
+
...properties
|
|
3047
|
+
},
|
|
3048
|
+
traceId: traceIdB64,
|
|
3049
|
+
parentSpanId: parentSpanIdB64
|
|
3050
|
+
});
|
|
3051
|
+
if (traceIdB64) {
|
|
3052
|
+
this.emitLiveEvent({
|
|
3053
|
+
traceId: traceIdB64,
|
|
3054
|
+
spanId: spanIdB64,
|
|
3055
|
+
type: "tool_result",
|
|
3056
|
+
content: name,
|
|
3057
|
+
timestamp: endTimeMs,
|
|
3058
|
+
metadata: {
|
|
3059
|
+
...input !== void 0 ? { input } : {},
|
|
3060
|
+
...output !== void 0 ? { result: output } : {},
|
|
3061
|
+
...error ? { error: error instanceof Error ? error.message : String(error) } : {}
|
|
3062
|
+
}
|
|
3063
|
+
});
|
|
3064
|
+
}
|
|
3065
|
+
return;
|
|
3066
|
+
}
|
|
3067
|
+
const span = this.tracer.startSpan(
|
|
3068
|
+
name,
|
|
3069
|
+
{
|
|
3070
|
+
startTime: startTimeMs
|
|
3071
|
+
},
|
|
3072
|
+
savedParentContext(explicitTraceId, explicitParentSpanId)
|
|
3073
|
+
);
|
|
3074
|
+
this.stampRouting(span);
|
|
3075
|
+
Object.entries(this.globalProperties).forEach(([key, value]) => {
|
|
3076
|
+
span.setAttribute("traceloop.association.properties." + key, String(value));
|
|
3077
|
+
});
|
|
3078
|
+
Object.entries(properties).forEach(([key, value]) => {
|
|
3079
|
+
span.setAttribute("traceloop.association.properties." + key, String(value));
|
|
3080
|
+
});
|
|
3081
|
+
span.setAttribute("traceloop.span.kind", "tool");
|
|
3082
|
+
if (input !== void 0) {
|
|
3083
|
+
span.setAttribute("traceloop.entity.input", stringifyBounded(input));
|
|
3084
|
+
}
|
|
3085
|
+
if (output !== void 0) {
|
|
3086
|
+
span.setAttribute("traceloop.entity.output", stringifyBounded(output));
|
|
3087
|
+
}
|
|
3088
|
+
if (durationMs !== void 0) {
|
|
3089
|
+
span.setAttribute("traceloop.entity.duration_ms", durationMs);
|
|
3090
|
+
}
|
|
3091
|
+
if (error) {
|
|
3092
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
3093
|
+
span.setStatus({ code: SpanStatusCode3.ERROR, message: errorMessage });
|
|
3094
|
+
span.recordException(error instanceof Error ? error : new Error(errorMessage));
|
|
3095
|
+
} else {
|
|
3096
|
+
span.setStatus({ code: SpanStatusCode3.OK });
|
|
3097
|
+
}
|
|
3098
|
+
span.end(endTimeMs);
|
|
3099
|
+
const ctx = span.spanContext();
|
|
3100
|
+
const traceId = ctx.traceId || ((_b = trace5.getSpan(context5.active())) == null ? void 0 : _b.spanContext().traceId);
|
|
3101
|
+
const spanIdHex = isValidSpanId3(ctx.spanId) ? ctx.spanId : void 0;
|
|
3102
|
+
if (traceId) {
|
|
3103
|
+
this.emitLiveEvent({
|
|
3104
|
+
traceId,
|
|
3105
|
+
spanId: spanIdHex,
|
|
3106
|
+
type: "tool_result",
|
|
3107
|
+
content: name,
|
|
3108
|
+
timestamp: endTimeMs,
|
|
3109
|
+
metadata: {
|
|
3110
|
+
...input !== void 0 ? { input } : {},
|
|
3111
|
+
...output !== void 0 ? { result: output } : {},
|
|
3112
|
+
...error ? { error: error instanceof Error ? error.message : String(error) } : {}
|
|
3113
|
+
}
|
|
3114
|
+
});
|
|
3115
|
+
}
|
|
3116
|
+
}
|
|
3117
|
+
};
|
|
3118
|
+
|
|
3119
|
+
// src/tracing/tracer-core.ts
|
|
3120
|
+
if (localDebuggerEnabled()) {
|
|
3121
|
+
if (!process.env.OTEL_EXPORTER_OTLP_PROTOCOL) {
|
|
3122
|
+
process.env.OTEL_EXPORTER_OTLP_PROTOCOL = "http/json";
|
|
3123
|
+
}
|
|
3124
|
+
if (!process.env.OTEL_EXPORTER_OTLP_TRACES_PROTOCOL) {
|
|
3125
|
+
process.env.OTEL_EXPORTER_OTLP_TRACES_PROTOCOL = "http/json";
|
|
3126
|
+
}
|
|
3127
|
+
}
|
|
3128
|
+
var DropSpanExporter = class {
|
|
3129
|
+
export(_spans, resultCallback) {
|
|
3130
|
+
resultCallback({ code: 0 });
|
|
3131
|
+
}
|
|
3132
|
+
shutdown() {
|
|
3133
|
+
return Promise.resolve();
|
|
3134
|
+
}
|
|
3135
|
+
};
|
|
3136
|
+
var CompositeSpanProcessor = class {
|
|
3137
|
+
constructor(requiredProcessors, bestEffortProcessors) {
|
|
3138
|
+
this.requiredProcessors = requiredProcessors;
|
|
3139
|
+
this.bestEffortProcessors = bestEffortProcessors;
|
|
3140
|
+
}
|
|
3141
|
+
onStart(span, parentContext) {
|
|
3142
|
+
for (const processor of this.requiredProcessors) {
|
|
3143
|
+
processor.onStart(span, parentContext);
|
|
3144
|
+
}
|
|
3145
|
+
for (const processor of this.bestEffortProcessors) {
|
|
3146
|
+
try {
|
|
3147
|
+
processor.onStart(span, parentContext);
|
|
3148
|
+
} catch (e) {
|
|
3149
|
+
}
|
|
3150
|
+
}
|
|
3151
|
+
}
|
|
3152
|
+
onEnd(span) {
|
|
3153
|
+
for (const processor of this.requiredProcessors) {
|
|
3154
|
+
processor.onEnd(span);
|
|
3155
|
+
}
|
|
3156
|
+
for (const processor of this.bestEffortProcessors) {
|
|
3157
|
+
try {
|
|
3158
|
+
processor.onEnd(span);
|
|
3159
|
+
} catch (e) {
|
|
3160
|
+
}
|
|
3161
|
+
}
|
|
3162
|
+
}
|
|
3163
|
+
async forceFlush() {
|
|
3164
|
+
const requiredFlushes = this.requiredProcessors.map(
|
|
3165
|
+
(processor) => callProcessorLifecycle(processor, "forceFlush")
|
|
3166
|
+
);
|
|
3167
|
+
const bestEffortFlushes = this.bestEffortProcessors.map(
|
|
3168
|
+
(processor) => callBestEffortProcessorLifecycle(processor, "forceFlush")
|
|
3169
|
+
);
|
|
3170
|
+
const [requiredResults] = await Promise.all([
|
|
3171
|
+
Promise.allSettled(requiredFlushes),
|
|
3172
|
+
Promise.allSettled(bestEffortFlushes)
|
|
3173
|
+
]);
|
|
3174
|
+
throwFirstRejected(requiredResults);
|
|
3175
|
+
}
|
|
3176
|
+
async shutdown() {
|
|
3177
|
+
const requiredShutdowns = this.requiredProcessors.map(
|
|
3178
|
+
(processor) => callProcessorLifecycle(processor, "shutdown")
|
|
3179
|
+
);
|
|
3180
|
+
const bestEffortShutdowns = this.bestEffortProcessors.map(
|
|
3181
|
+
(processor) => callBestEffortProcessorLifecycle(processor, "shutdown")
|
|
3182
|
+
);
|
|
3183
|
+
const [requiredResults] = await Promise.all([
|
|
3184
|
+
Promise.allSettled(requiredShutdowns),
|
|
3185
|
+
Promise.allSettled(bestEffortShutdowns)
|
|
3186
|
+
]);
|
|
3187
|
+
throwFirstRejected(requiredResults);
|
|
3188
|
+
}
|
|
3189
|
+
};
|
|
3190
|
+
function callProcessorLifecycle(processor, method) {
|
|
3191
|
+
try {
|
|
3192
|
+
return processor[method]();
|
|
3193
|
+
} catch (error) {
|
|
3194
|
+
return Promise.reject(error);
|
|
3195
|
+
}
|
|
3196
|
+
}
|
|
3197
|
+
function callBestEffortProcessorLifecycle(processor, method) {
|
|
3198
|
+
try {
|
|
3199
|
+
return processor[method]().catch(() => {
|
|
3200
|
+
});
|
|
3201
|
+
} catch (e) {
|
|
3202
|
+
return Promise.resolve();
|
|
3203
|
+
}
|
|
3204
|
+
}
|
|
3205
|
+
function throwFirstRejected(results) {
|
|
3206
|
+
const rejected = results.find(
|
|
3207
|
+
(result) => result.status === "rejected"
|
|
3208
|
+
);
|
|
3209
|
+
if (rejected) {
|
|
3210
|
+
throw rejected.reason;
|
|
3211
|
+
}
|
|
3212
|
+
}
|
|
3213
|
+
function isLocalDebuggerUrl(baseUrl) {
|
|
3214
|
+
try {
|
|
3215
|
+
const url = new URL(baseUrl);
|
|
3216
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
|
3217
|
+
return false;
|
|
3218
|
+
}
|
|
3219
|
+
const hostname = url.hostname.toLowerCase();
|
|
3220
|
+
return hostname === "localhost" || hostname.endsWith(".localhost") || hostname === "0.0.0.0" || hostname === "127.0.0.1" || hostname.startsWith("127.") || hostname === "::1" || hostname === "[::1]";
|
|
3221
|
+
} catch (e) {
|
|
3222
|
+
return false;
|
|
3223
|
+
}
|
|
3224
|
+
}
|
|
3225
|
+
function resolveLocalDebuggerExporterBaseUrl(baseUrlOpt) {
|
|
3226
|
+
const localDebuggerUrl = resolveLocalDebuggerBaseUrl(baseUrlOpt);
|
|
3227
|
+
if (!localDebuggerUrl || !isLocalDebuggerUrl(localDebuggerUrl)) {
|
|
3228
|
+
return null;
|
|
3229
|
+
}
|
|
3230
|
+
return localDebuggerUrl;
|
|
3231
|
+
}
|
|
3232
|
+
function createLocalDebuggerOtlpExporter(config) {
|
|
3233
|
+
return new OTLPHttpTraceExporter(config);
|
|
3234
|
+
}
|
|
3235
|
+
function parseTraceloopHeaders(value) {
|
|
3236
|
+
const headers = {};
|
|
3237
|
+
for (const entry of value.split(",")) {
|
|
3238
|
+
const keyPairPart = entry.split(";")[0];
|
|
3239
|
+
const sep = keyPairPart.indexOf("=");
|
|
3240
|
+
if (sep <= 0) continue;
|
|
3241
|
+
try {
|
|
3242
|
+
const key = decodeURIComponent(keyPairPart.slice(0, sep).trim());
|
|
3243
|
+
const val = decodeURIComponent(keyPairPart.slice(sep + 1).trim());
|
|
3244
|
+
if (key.length > 0 && val.length > 0) headers[key] = val;
|
|
3245
|
+
} catch (e) {
|
|
3246
|
+
}
|
|
3247
|
+
}
|
|
3248
|
+
return headers;
|
|
3249
|
+
}
|
|
3250
|
+
function traceloopDefaultHeaders(writeKey) {
|
|
3251
|
+
const env = process.env.TRACELOOP_HEADERS;
|
|
3252
|
+
if (env) {
|
|
3253
|
+
const parsed = parseTraceloopHeaders(env);
|
|
3254
|
+
if (Object.keys(parsed).length > 0) return parsed;
|
|
3255
|
+
}
|
|
3256
|
+
return { Authorization: `Bearer ${writeKey}` };
|
|
3257
|
+
}
|
|
3258
|
+
function createLocalDebuggerSpanProcessor(options) {
|
|
3259
|
+
const localDebuggerUrl = resolveLocalDebuggerExporterBaseUrl(options.localDebuggerUrlOpt);
|
|
3260
|
+
if (!localDebuggerUrl) {
|
|
3261
|
+
return void 0;
|
|
3262
|
+
}
|
|
3263
|
+
const localExporter = createLocalDebuggerOtlpExporter({
|
|
3264
|
+
url: `${localDebuggerUrl}traces`,
|
|
3265
|
+
headers: {}
|
|
3266
|
+
});
|
|
3267
|
+
if (!options.routeReplayTraces) {
|
|
3268
|
+
const exportLocal = localExporter.export.bind(localExporter);
|
|
3269
|
+
localExporter.export = (spans, callback) => {
|
|
3270
|
+
const localSpans = spans.filter(
|
|
3271
|
+
(span) => {
|
|
3272
|
+
var _a;
|
|
3273
|
+
return ((_a = replayTraceDestinationFor(span)) == null ? void 0 : _a.kind) !== "raindrop";
|
|
3274
|
+
}
|
|
3275
|
+
);
|
|
3276
|
+
if (localSpans.length === 0) callback({ code: 0 });
|
|
3277
|
+
else exportLocal(localSpans, callback);
|
|
3278
|
+
};
|
|
3279
|
+
}
|
|
3280
|
+
try {
|
|
3281
|
+
return createSpanProcessor({
|
|
3282
|
+
apiKey: options.writeKey,
|
|
3283
|
+
baseUrl: localDebuggerUrl,
|
|
3284
|
+
routeReplayTraces: options.routeReplayTraces,
|
|
3285
|
+
disableBatch: options.disableBatching,
|
|
3286
|
+
exporter: localExporter,
|
|
3287
|
+
headers: {},
|
|
3288
|
+
piiRedaction: options.piiRedaction,
|
|
3289
|
+
allowedInstrumentationLibraries: options.allowedInstrumentationLibraries
|
|
3290
|
+
});
|
|
3291
|
+
} catch (error) {
|
|
3292
|
+
console.warn(
|
|
3293
|
+
"[raindrop] Failed to initialize local debugger trace exporter.",
|
|
3294
|
+
error instanceof Error ? error.message : error
|
|
3295
|
+
);
|
|
3296
|
+
return void 0;
|
|
3297
|
+
}
|
|
3298
|
+
}
|
|
3299
|
+
var warnedSpanNormalizeFailure = false;
|
|
3300
|
+
var INVALID_OTEL_SPAN_ID = "0000000000000000";
|
|
3301
|
+
function normalizeSpanForV1Exporter(span) {
|
|
3302
|
+
var _a;
|
|
3303
|
+
if (!span) {
|
|
3304
|
+
return;
|
|
3305
|
+
}
|
|
3306
|
+
if (span.instrumentationLibrary == null && span.instrumentationScope != null) {
|
|
3307
|
+
try {
|
|
3308
|
+
span.instrumentationLibrary = span.instrumentationScope;
|
|
3309
|
+
} catch (error) {
|
|
3310
|
+
if (!warnedSpanNormalizeFailure) {
|
|
3311
|
+
warnedSpanNormalizeFailure = true;
|
|
3312
|
+
console.warn(
|
|
3313
|
+
"[raindrop] Could not normalize an OTEL v2 span for export (instrumentationLibrary alias failed). Spans may not reach Raindrop.",
|
|
3314
|
+
error instanceof Error ? error.message : error
|
|
3315
|
+
);
|
|
3316
|
+
}
|
|
3317
|
+
}
|
|
3318
|
+
}
|
|
3319
|
+
if (span.parentSpanId == null && ((_a = span.parentSpanContext) == null ? void 0 : _a.spanId) != null && span.parentSpanContext.spanId !== INVALID_OTEL_SPAN_ID) {
|
|
3320
|
+
try {
|
|
3321
|
+
span.parentSpanId = span.parentSpanContext.spanId;
|
|
3322
|
+
} catch (e) {
|
|
3323
|
+
}
|
|
3324
|
+
}
|
|
3325
|
+
}
|
|
3326
|
+
function withV2SpanCompat(processor) {
|
|
3327
|
+
return {
|
|
3328
|
+
onStart(span, parentContext) {
|
|
3329
|
+
processor.onStart(span, parentContext);
|
|
3330
|
+
},
|
|
3331
|
+
onEnd(span) {
|
|
3332
|
+
try {
|
|
3333
|
+
normalizeSpanForV1Exporter(span);
|
|
3334
|
+
} catch (e) {
|
|
3335
|
+
}
|
|
3336
|
+
processor.onEnd(span);
|
|
3337
|
+
},
|
|
3338
|
+
forceFlush() {
|
|
3339
|
+
return processor.forceFlush();
|
|
3340
|
+
},
|
|
3341
|
+
shutdown() {
|
|
3342
|
+
return processor.shutdown();
|
|
3343
|
+
}
|
|
3344
|
+
};
|
|
3345
|
+
}
|
|
3346
|
+
try {
|
|
3347
|
+
const _bedrockProto = BedrockInstrumentation.prototype;
|
|
3348
|
+
_bedrockProto._wrapPromise = function(span, promise) {
|
|
3349
|
+
const inst = this;
|
|
3350
|
+
return promise.then(async (result) => {
|
|
3351
|
+
const rec = result;
|
|
3352
|
+
const body = rec == null ? void 0 : rec.body;
|
|
3353
|
+
const isStreamBody = body != null && typeof body === "object" && Symbol.asyncIterator in body && !(body instanceof Uint8Array);
|
|
3354
|
+
if (!isStreamBody) {
|
|
3355
|
+
try {
|
|
3356
|
+
await inst._endSpan({ span, result });
|
|
3357
|
+
} catch (e) {
|
|
3358
|
+
console.warn(
|
|
3359
|
+
"[raindrop] Bedrock instrumentation could not process response \u2014 passing through unchanged.",
|
|
3360
|
+
e instanceof Error ? e.message : e
|
|
3361
|
+
);
|
|
3362
|
+
span.setStatus({
|
|
3363
|
+
code: SpanStatusCode4.ERROR,
|
|
3364
|
+
message: e instanceof Error ? e.message : String(e)
|
|
3365
|
+
});
|
|
3366
|
+
span.end();
|
|
3367
|
+
}
|
|
3368
|
+
return result;
|
|
3369
|
+
}
|
|
3370
|
+
const origIterator = body[Symbol.asyncIterator]();
|
|
3371
|
+
const chunks = [];
|
|
3372
|
+
let spanEnded = false;
|
|
3373
|
+
rec.body = {
|
|
3374
|
+
[Symbol.asyncIterator]() {
|
|
3375
|
+
return {
|
|
3376
|
+
async next() {
|
|
3377
|
+
try {
|
|
3378
|
+
const iterResult = await origIterator.next();
|
|
3379
|
+
if (iterResult.done) {
|
|
3380
|
+
try {
|
|
3381
|
+
async function* replay() {
|
|
3382
|
+
for (const c of chunks) yield c;
|
|
3383
|
+
}
|
|
3384
|
+
await inst._endSpan({
|
|
3385
|
+
span,
|
|
3386
|
+
result: { ...rec, body: replay() }
|
|
3387
|
+
});
|
|
3388
|
+
} catch (e) {
|
|
3389
|
+
console.warn(
|
|
3390
|
+
"[raindrop] Bedrock instrumentation could not process streaming response \u2014 passing through unchanged.",
|
|
3391
|
+
e instanceof Error ? e.message : e
|
|
3392
|
+
);
|
|
3393
|
+
if (!spanEnded) {
|
|
3394
|
+
span.setStatus({
|
|
3395
|
+
code: SpanStatusCode4.ERROR,
|
|
3396
|
+
message: e instanceof Error ? e.message : String(e)
|
|
3397
|
+
});
|
|
3398
|
+
span.end();
|
|
3399
|
+
}
|
|
3400
|
+
}
|
|
3401
|
+
spanEnded = true;
|
|
3402
|
+
return { done: true, value: void 0 };
|
|
3403
|
+
}
|
|
3404
|
+
chunks.push(iterResult.value);
|
|
3405
|
+
return { done: false, value: iterResult.value };
|
|
3406
|
+
} catch (error) {
|
|
3407
|
+
if (!spanEnded) {
|
|
3408
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
3409
|
+
span.setStatus({ code: SpanStatusCode4.ERROR, message: msg });
|
|
3410
|
+
span.recordException(error);
|
|
3411
|
+
span.end();
|
|
3412
|
+
spanEnded = true;
|
|
3413
|
+
}
|
|
3414
|
+
throw error;
|
|
3415
|
+
}
|
|
3416
|
+
},
|
|
3417
|
+
async return(value) {
|
|
3418
|
+
var _a;
|
|
3419
|
+
if (!spanEnded) {
|
|
3420
|
+
span.end();
|
|
3421
|
+
spanEnded = true;
|
|
3422
|
+
}
|
|
3423
|
+
await ((_a = origIterator.return) == null ? void 0 : _a.call(origIterator, value));
|
|
3424
|
+
return { done: true, value: void 0 };
|
|
3425
|
+
}
|
|
3426
|
+
};
|
|
3427
|
+
}
|
|
3428
|
+
};
|
|
3429
|
+
return result;
|
|
3430
|
+
}).catch((error) => {
|
|
3431
|
+
span.setStatus({
|
|
3432
|
+
code: SpanStatusCode4.ERROR,
|
|
3433
|
+
message: error.message
|
|
3434
|
+
});
|
|
3435
|
+
span.recordException(error);
|
|
3436
|
+
span.end();
|
|
3437
|
+
throw error;
|
|
3438
|
+
});
|
|
3439
|
+
};
|
|
3440
|
+
_bedrockProto._extractVendorAndModel = function(modelId) {
|
|
3441
|
+
if (!modelId) {
|
|
3442
|
+
return { modelVendor: "", model: "" };
|
|
3443
|
+
}
|
|
3444
|
+
const parts = modelId.split(".");
|
|
3445
|
+
if (parts.length >= 3 && /^[a-z]{2}$/.test(parts[0])) {
|
|
3446
|
+
return {
|
|
3447
|
+
modelVendor: parts[1] || "",
|
|
3448
|
+
model: parts.slice(2).join(".")
|
|
3449
|
+
};
|
|
3450
|
+
}
|
|
3451
|
+
return {
|
|
3452
|
+
modelVendor: parts[0] || "",
|
|
3453
|
+
model: parts[1] || ""
|
|
3454
|
+
};
|
|
3455
|
+
};
|
|
3456
|
+
} catch (e) {
|
|
3457
|
+
}
|
|
3458
|
+
function patchBedrockStreamingBug(inst) {
|
|
3459
|
+
const anyInst = inst;
|
|
3460
|
+
const origEndSpan = anyInst._endSpan.bind(anyInst);
|
|
3461
|
+
anyInst._wrapPromise = function(span, promise) {
|
|
3462
|
+
return promise.then(async (result) => {
|
|
3463
|
+
const rec = result;
|
|
3464
|
+
const body = rec == null ? void 0 : rec.body;
|
|
3465
|
+
const isStreamBody = body != null && typeof body === "object" && Symbol.asyncIterator in body && !(body instanceof Uint8Array);
|
|
3466
|
+
if (!isStreamBody) {
|
|
3467
|
+
await origEndSpan({ span, result });
|
|
3468
|
+
return result;
|
|
3469
|
+
}
|
|
3470
|
+
const origIterator = body[Symbol.asyncIterator]();
|
|
3471
|
+
const chunks = [];
|
|
3472
|
+
let spanEnded = false;
|
|
3473
|
+
rec.body = {
|
|
3474
|
+
[Symbol.asyncIterator]() {
|
|
3475
|
+
return {
|
|
3476
|
+
async next() {
|
|
3477
|
+
try {
|
|
3478
|
+
const iterResult = await origIterator.next();
|
|
3479
|
+
if (iterResult.done) {
|
|
3480
|
+
async function* replay() {
|
|
3481
|
+
for (const c of chunks) yield c;
|
|
3482
|
+
}
|
|
3483
|
+
await origEndSpan({
|
|
3484
|
+
span,
|
|
3485
|
+
result: { ...rec, body: replay() }
|
|
3486
|
+
});
|
|
3487
|
+
spanEnded = true;
|
|
3488
|
+
return { done: true, value: void 0 };
|
|
3489
|
+
}
|
|
3490
|
+
chunks.push(iterResult.value);
|
|
3491
|
+
return { done: false, value: iterResult.value };
|
|
3492
|
+
} catch (error) {
|
|
3493
|
+
if (!spanEnded) {
|
|
3494
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
3495
|
+
span.setStatus({ code: SpanStatusCode4.ERROR, message: msg });
|
|
3496
|
+
span.recordException(error);
|
|
3497
|
+
span.end();
|
|
3498
|
+
spanEnded = true;
|
|
3499
|
+
}
|
|
3500
|
+
throw error;
|
|
3501
|
+
}
|
|
3502
|
+
},
|
|
3503
|
+
async return(value) {
|
|
3504
|
+
var _a;
|
|
3505
|
+
if (!spanEnded) {
|
|
3506
|
+
span.end();
|
|
3507
|
+
spanEnded = true;
|
|
3508
|
+
}
|
|
3509
|
+
await ((_a = origIterator.return) == null ? void 0 : _a.call(origIterator, value));
|
|
3510
|
+
return { done: true, value: void 0 };
|
|
3511
|
+
}
|
|
3512
|
+
};
|
|
3513
|
+
}
|
|
3514
|
+
};
|
|
3515
|
+
return result;
|
|
3516
|
+
}).catch((error) => {
|
|
3517
|
+
span.setStatus({
|
|
3518
|
+
code: SpanStatusCode4.ERROR,
|
|
3519
|
+
message: error.message
|
|
3520
|
+
});
|
|
3521
|
+
span.recordException(error);
|
|
3522
|
+
span.end();
|
|
3523
|
+
throw error;
|
|
3524
|
+
});
|
|
3525
|
+
};
|
|
3526
|
+
}
|
|
3527
|
+
function createDefaultInstrumentations() {
|
|
3528
|
+
const bedrockInst = new BedrockInstrumentation();
|
|
3529
|
+
patchBedrockStreamingBug(bedrockInst);
|
|
3530
|
+
return [
|
|
3531
|
+
new OpenAIInstrumentation({
|
|
3532
|
+
enrichTokens: (process.env.TRACELOOP_ENRICH_TOKENS || "true").toLowerCase() === "true"
|
|
3533
|
+
}),
|
|
3534
|
+
new AnthropicInstrumentation(),
|
|
3535
|
+
new CohereInstrumentation(),
|
|
3536
|
+
bedrockInst,
|
|
3537
|
+
new VertexAIInstrumentation(),
|
|
3538
|
+
new AIPlatformInstrumentation(),
|
|
3539
|
+
new PineconeInstrumentation(),
|
|
3540
|
+
new TogetherInstrumentation(),
|
|
3541
|
+
new ChromaDBInstrumentation(),
|
|
3542
|
+
new QdrantInstrumentation(),
|
|
3543
|
+
new LangChainInstrumentation(),
|
|
3544
|
+
new LlamaIndexInstrumentation()
|
|
3545
|
+
];
|
|
3546
|
+
}
|
|
3547
|
+
function createManualInstrumentations(instrumentModules) {
|
|
3548
|
+
const instrumentations = [];
|
|
3549
|
+
if (instrumentModules.openAI) {
|
|
3550
|
+
const inst = new OpenAIInstrumentation();
|
|
3551
|
+
inst.manuallyInstrument(instrumentModules.openAI);
|
|
3552
|
+
instrumentations.push(inst);
|
|
3553
|
+
}
|
|
3554
|
+
if (instrumentModules.anthropic) {
|
|
3555
|
+
const inst = new AnthropicInstrumentation();
|
|
3556
|
+
inst.manuallyInstrument(instrumentModules.anthropic);
|
|
3557
|
+
instrumentations.push(inst);
|
|
3558
|
+
}
|
|
3559
|
+
if (instrumentModules.cohere) {
|
|
3560
|
+
const inst = new CohereInstrumentation();
|
|
3561
|
+
inst.manuallyInstrument(instrumentModules.cohere);
|
|
3562
|
+
instrumentations.push(inst);
|
|
3563
|
+
}
|
|
3564
|
+
if (instrumentModules.bedrock) {
|
|
3565
|
+
const inst = new BedrockInstrumentation();
|
|
3566
|
+
patchBedrockStreamingBug(inst);
|
|
3567
|
+
inst.manuallyInstrument(instrumentModules.bedrock);
|
|
3568
|
+
instrumentations.push(inst);
|
|
3569
|
+
}
|
|
3570
|
+
if (instrumentModules.google_vertexai) {
|
|
3571
|
+
const inst = new VertexAIInstrumentation();
|
|
3572
|
+
inst.manuallyInstrument(instrumentModules.google_vertexai);
|
|
3573
|
+
instrumentations.push(inst);
|
|
3574
|
+
}
|
|
3575
|
+
if (instrumentModules.google_aiplatform) {
|
|
3576
|
+
const inst = new AIPlatformInstrumentation();
|
|
3577
|
+
inst.manuallyInstrument(instrumentModules.google_aiplatform);
|
|
3578
|
+
instrumentations.push(inst);
|
|
3579
|
+
}
|
|
3580
|
+
if (instrumentModules.pinecone) {
|
|
3581
|
+
const inst = new PineconeInstrumentation();
|
|
3582
|
+
inst.manuallyInstrument(instrumentModules.pinecone);
|
|
3583
|
+
instrumentations.push(inst);
|
|
3584
|
+
}
|
|
3585
|
+
if (instrumentModules.together) {
|
|
3586
|
+
const inst = new TogetherInstrumentation();
|
|
3587
|
+
inst.manuallyInstrument(instrumentModules.together);
|
|
3588
|
+
instrumentations.push(inst);
|
|
3589
|
+
}
|
|
3590
|
+
if (instrumentModules.chromadb) {
|
|
3591
|
+
const inst = new ChromaDBInstrumentation();
|
|
3592
|
+
inst.manuallyInstrument(instrumentModules.chromadb);
|
|
3593
|
+
instrumentations.push(inst);
|
|
3594
|
+
}
|
|
3595
|
+
if (instrumentModules.qdrant) {
|
|
3596
|
+
const inst = new QdrantInstrumentation();
|
|
3597
|
+
inst.manuallyInstrument(instrumentModules.qdrant);
|
|
3598
|
+
instrumentations.push(inst);
|
|
3599
|
+
}
|
|
3600
|
+
instrumentations.push(new LangChainInstrumentation());
|
|
3601
|
+
if (instrumentModules.llamaIndex) {
|
|
3602
|
+
const inst = new LlamaIndexInstrumentation();
|
|
3603
|
+
inst.manuallyInstrument(instrumentModules.llamaIndex);
|
|
3604
|
+
instrumentations.push(inst);
|
|
3605
|
+
}
|
|
3606
|
+
return instrumentations;
|
|
3607
|
+
}
|
|
3608
|
+
function createConfiguredInstrumentations(options) {
|
|
3609
|
+
if (options.instrumentModules && Object.keys(options.instrumentModules).length > 0) {
|
|
3610
|
+
return createManualInstrumentations(options.instrumentModules);
|
|
3611
|
+
}
|
|
3612
|
+
return createDefaultInstrumentations();
|
|
3613
|
+
}
|
|
3614
|
+
function getCurrentTraceId() {
|
|
3615
|
+
var _a;
|
|
3616
|
+
return (_a = trace6.getSpan(context6.active())) == null ? void 0 : _a.spanContext().traceId;
|
|
3617
|
+
}
|
|
3618
|
+
var tracing = (analytics, apiUrl, writeKey, options, isDebug = false) => {
|
|
3619
|
+
var _a;
|
|
3620
|
+
process.env.TRACELOOP_TELEMETRY = "false";
|
|
3621
|
+
const {
|
|
3622
|
+
logLevel: logLevel2,
|
|
3623
|
+
useExternalOtel,
|
|
3624
|
+
tracingEnabled,
|
|
3625
|
+
disableBatching,
|
|
3626
|
+
bypassOtelForTools,
|
|
3627
|
+
directEndpoint,
|
|
3628
|
+
localDebuggerUrl,
|
|
3629
|
+
cloudEnabled,
|
|
3630
|
+
projectId,
|
|
3631
|
+
flushTimeoutMs,
|
|
3632
|
+
redactTracePii,
|
|
3633
|
+
redactPiiFields,
|
|
3634
|
+
remotePiiConfig,
|
|
3635
|
+
mask,
|
|
3636
|
+
...otherOptions
|
|
3637
|
+
} = options;
|
|
3638
|
+
const cloudEnabledResolved = cloudEnabled != null ? cloudEnabled : true;
|
|
3639
|
+
const localTracePii = typeof redactTracePii === "boolean" ? redactTracePii : void 0;
|
|
3640
|
+
const spanPiiFields = compileSpanPiiFields(redactPiiFields == null ? void 0 : redactPiiFields.span, "[raindrop]");
|
|
3641
|
+
if ((redactPiiFields == null ? void 0 : redactPiiFields.span) && localTracePii !== true && !remotePiiConfig) {
|
|
3642
|
+
rateLimitedLog(
|
|
3643
|
+
"js-sdk.pii_span_fields_without_redaction",
|
|
3644
|
+
() => console.warn(
|
|
3645
|
+
"[raindrop] redactPiiFields.span is set but redactTracePii is off; no span is redacted. Set redactTracePii: true to use it."
|
|
3646
|
+
)
|
|
3647
|
+
);
|
|
3648
|
+
}
|
|
3649
|
+
const piiRedaction2 = {
|
|
3650
|
+
local: localTracePii,
|
|
3651
|
+
remote: remotePiiConfig,
|
|
3652
|
+
apiUrl: directEndpoint != null ? directEndpoint : apiUrl,
|
|
3653
|
+
writeKey: cloudEnabledResolved ? writeKey : void 0,
|
|
3654
|
+
spanFields: spanPiiFields,
|
|
3655
|
+
mask: typeof mask === "function" ? mask : void 0
|
|
3656
|
+
};
|
|
3657
|
+
if (localTracePii === true) {
|
|
3658
|
+
requestLocalTracePiiRedaction(piiRedaction2.apiUrl, piiRedaction2.writeKey);
|
|
3659
|
+
}
|
|
3660
|
+
const authHint = authHintForKey(writeKey);
|
|
3661
|
+
const clientTracingExports = !useExternalOtel && cloudEnabledResolved && tracingEnabled !== false;
|
|
3662
|
+
registerClientKey(authHint, clientTracingExports);
|
|
3663
|
+
const withProjectIdHeaders = (existing) => {
|
|
3664
|
+
if (!projectId) {
|
|
3665
|
+
return existing;
|
|
3666
|
+
}
|
|
3667
|
+
return {
|
|
3668
|
+
...traceloopDefaultHeaders(writeKey),
|
|
3669
|
+
...existing != null ? existing : {},
|
|
3670
|
+
...projectIdHeaders(projectId)
|
|
3671
|
+
};
|
|
3672
|
+
};
|
|
3673
|
+
if (isDebug) {
|
|
3674
|
+
const mode = useExternalOtel ? "(external OTEL mode)" : tracingEnabled === false ? "(tracing disabled)" : "";
|
|
3675
|
+
console.log("[raindrop] Initializing tracing", mode);
|
|
3676
|
+
if (bypassOtelForTools) {
|
|
3677
|
+
console.log("[raindrop] bypassOtelForTools enabled \u2014 tool spans ship directly via HTTP");
|
|
3678
|
+
}
|
|
3679
|
+
}
|
|
3680
|
+
const directShipper = bypassOtelForTools ? new DirectTraceShipper({
|
|
3681
|
+
appGitSnapshot: (properties) => analytics.getAppGitSnapshot(properties),
|
|
3682
|
+
writeKey,
|
|
3683
|
+
endpoint: directEndpoint != null ? directEndpoint : apiUrl,
|
|
3684
|
+
debug: isDebug,
|
|
3685
|
+
enabled: tracingEnabled !== false,
|
|
3686
|
+
localDebuggerUrl,
|
|
3687
|
+
cloudEnabled: cloudEnabledResolved,
|
|
3688
|
+
projectId,
|
|
3689
|
+
flushTimeoutMs,
|
|
3690
|
+
redactTracePii: localTracePii,
|
|
3691
|
+
remotePiiConfig,
|
|
3692
|
+
spanPiiFields,
|
|
3693
|
+
mask: piiRedaction2.mask
|
|
3694
|
+
}) : void 0;
|
|
3695
|
+
let traceloopInitialized = false;
|
|
3696
|
+
let claimedPipeline = false;
|
|
3697
|
+
const activeInteractions = new WeakValueMap();
|
|
3698
|
+
const activeInteractionsByEventId = new WeakValueMap();
|
|
3699
|
+
try {
|
|
3700
|
+
if (useExternalOtel) {
|
|
3701
|
+
initialize({
|
|
3702
|
+
baseUrl: apiUrl,
|
|
3703
|
+
apiKey: writeKey,
|
|
3704
|
+
logLevel: logLevel2,
|
|
3705
|
+
// Traceloop's init banner ("Traceloop exporting traces to <baseUrl>") is
|
|
3706
|
+
// misleading inside our wrapper: in external-OTEL mode we create no
|
|
3707
|
+
// exporter at all (tracingEnabled: false). Suppress it.
|
|
3708
|
+
silenceInitializationMessage: true,
|
|
3709
|
+
tracingEnabled: false
|
|
3710
|
+
// DO NOT create NodeSDK - customer has their own
|
|
3711
|
+
});
|
|
3712
|
+
traceloopInitialized = true;
|
|
3713
|
+
markTraceloopConfiguredWithoutClaim();
|
|
3714
|
+
if (isDebug) {
|
|
3715
|
+
console.log(
|
|
3716
|
+
"[raindrop] External OTEL mode active. Add raindrop.createSpanProcessor() to your NodeSDK's spanProcessors. Register instrumentations (AnthropicInstrumentation, etc.) on your NodeSDK."
|
|
3717
|
+
);
|
|
3718
|
+
}
|
|
3719
|
+
if (otherOptions.instrumentModules && Object.keys(otherOptions.instrumentModules).length > 0) {
|
|
3720
|
+
if (isDebug) {
|
|
3721
|
+
console.log(
|
|
3722
|
+
"[raindrop] instrumentModules configured. Call raindrop.getInstrumentations() to get instrumentation instances for your NodeSDK."
|
|
3723
|
+
);
|
|
3724
|
+
}
|
|
3725
|
+
}
|
|
3726
|
+
} else {
|
|
3727
|
+
const localDebuggerProcessor = createLocalDebuggerSpanProcessor({
|
|
3728
|
+
writeKey,
|
|
3729
|
+
disableBatching,
|
|
3730
|
+
allowedInstrumentationLibraries: ALL_INSTRUMENTATION_LIBRARIES,
|
|
3731
|
+
localDebuggerUrlOpt: localDebuggerUrl,
|
|
3732
|
+
routeReplayTraces: !cloudEnabledResolved,
|
|
3733
|
+
piiRedaction: piiRedaction2
|
|
3734
|
+
});
|
|
3735
|
+
if (!cloudEnabledResolved) {
|
|
3736
|
+
if (localDebuggerProcessor) {
|
|
3737
|
+
initialize({
|
|
3738
|
+
baseUrl: apiUrl,
|
|
3739
|
+
apiKey: writeKey,
|
|
3740
|
+
...otherOptions,
|
|
3741
|
+
exporter: new DropSpanExporter(),
|
|
3742
|
+
logLevel: logLevel2,
|
|
3743
|
+
silenceInitializationMessage: true,
|
|
3744
|
+
tracingEnabled: tracingEnabled !== false,
|
|
3745
|
+
disableBatch: disableBatching,
|
|
3746
|
+
processor: new CompositeSpanProcessor(
|
|
3747
|
+
[new RaindropContextSpanProcessor((properties) => analytics.getAppGitSnapshot(properties)), localDebuggerProcessor],
|
|
3748
|
+
[]
|
|
3749
|
+
),
|
|
3750
|
+
instrumentations: createConfiguredInstrumentations(otherOptions)
|
|
3751
|
+
});
|
|
3752
|
+
traceloopInitialized = true;
|
|
3753
|
+
markTraceloopConfiguredWithoutClaim();
|
|
3754
|
+
} else {
|
|
3755
|
+
const replayOnlyProcessor = createSpanProcessor({
|
|
3756
|
+
exporter: new DropSpanExporter(),
|
|
3757
|
+
routeReplayTraces: true,
|
|
3758
|
+
disableBatch: disableBatching,
|
|
3759
|
+
allowedInstrumentationLibraries: ALL_INSTRUMENTATION_LIBRARIES,
|
|
3760
|
+
piiRedaction: piiRedaction2
|
|
3761
|
+
});
|
|
3762
|
+
initialize({
|
|
3763
|
+
baseUrl: apiUrl,
|
|
3764
|
+
apiKey: writeKey,
|
|
3765
|
+
...otherOptions,
|
|
3766
|
+
exporter: new DropSpanExporter(),
|
|
3767
|
+
logLevel: logLevel2,
|
|
3768
|
+
silenceInitializationMessage: true,
|
|
3769
|
+
tracingEnabled: tracingEnabled !== false,
|
|
3770
|
+
disableBatch: disableBatching,
|
|
3771
|
+
processor: new CompositeSpanProcessor(
|
|
3772
|
+
[new RaindropContextSpanProcessor((properties) => analytics.getAppGitSnapshot(properties)), replayOnlyProcessor],
|
|
3773
|
+
[]
|
|
3774
|
+
),
|
|
3775
|
+
instrumentations: createConfiguredInstrumentations(otherOptions)
|
|
3776
|
+
});
|
|
3777
|
+
traceloopInitialized = true;
|
|
3778
|
+
markTraceloopConfiguredWithoutClaim();
|
|
3779
|
+
}
|
|
3780
|
+
} else if (tracingEnabled === false) {
|
|
3781
|
+
traceloopInitialized = false;
|
|
3782
|
+
} else {
|
|
3783
|
+
const claimed = claimPipeline(authHint, projectId);
|
|
3784
|
+
claimedPipeline = claimed;
|
|
3785
|
+
const ownerHint = pipelineOwnerHint();
|
|
3786
|
+
if (!claimed && authHint !== ownerHint) {
|
|
3787
|
+
markForeignClient();
|
|
3788
|
+
console.warn(
|
|
3789
|
+
"[raindrop] The OTel tracing pipeline is already initialized with a DIFFERENT api key. One process supports one tracing key/org: auto-instrumented spans from this client will be dropped at export, and spans not bound to any client (no begin()/asCurrent()) will be dropped as unattributable (manual events are unaffected and route normally). Run this client in its own process for tracing."
|
|
3790
|
+
);
|
|
3791
|
+
}
|
|
3792
|
+
if (claimed && traceloopConfiguredWithoutClaim()) {
|
|
3793
|
+
releasePipelineClaim();
|
|
3794
|
+
claimedPipeline = false;
|
|
3795
|
+
console.warn(
|
|
3796
|
+
"[raindrop] Cannot initialize the cloud tracing pipeline: OpenTelemetry was already configured in this process by an earlier Raindrop client (external-OTEL mode, or a local-only/Workshop client with no write key). Traceloop's tracer provider is fixed once per process, so this client's auto-instrumented spans will NOT be exported. Construct the cloud tracing-enabled client FIRST, or run it in its own process. Manual events (track_ai/begin/finish/signals/identify) are unaffected."
|
|
3797
|
+
);
|
|
3798
|
+
} else if (claimed) {
|
|
3799
|
+
const exporterHeaders = (_a = withProjectIdHeaders(otherOptions.headers)) != null ? _a : traceloopDefaultHeaders(writeKey);
|
|
3800
|
+
let guardedExporter;
|
|
3801
|
+
try {
|
|
3802
|
+
const callerExporter = otherOptions.exporter;
|
|
3803
|
+
const guarded = callerExporter ? new GuardedSpanExporter(callerExporter, ownerHint) : buildGuardedExporter(apiUrl, exporterHeaders, ownerHint);
|
|
3804
|
+
guardedExporter = new ReplayRoutingSpanExporter(guarded);
|
|
3805
|
+
} catch (guardError) {
|
|
3806
|
+
releasePipelineClaim();
|
|
3807
|
+
claimedPipeline = false;
|
|
3808
|
+
console.warn(
|
|
3809
|
+
`[raindrop] could not install the guarded span exporter (${guardError instanceof Error ? guardError.message : guardError}); disabling tracing rather than running an unguarded pipeline. Manual events are unaffected.`
|
|
3810
|
+
);
|
|
3811
|
+
}
|
|
3812
|
+
if (guardedExporter) {
|
|
3813
|
+
const contextProcessor = new RaindropContextSpanProcessor((properties) => analytics.getAppGitSnapshot(properties));
|
|
3814
|
+
const callerProcessor = otherOptions.processor;
|
|
3815
|
+
const processor = new CompositeSpanProcessor(
|
|
3816
|
+
callerProcessor ? [contextProcessor, callerProcessor] : [contextProcessor],
|
|
3817
|
+
localDebuggerProcessor ? [localDebuggerProcessor] : []
|
|
3818
|
+
);
|
|
3819
|
+
try {
|
|
3820
|
+
initialize({
|
|
3821
|
+
baseUrl: apiUrl,
|
|
3822
|
+
apiKey: writeKey,
|
|
3823
|
+
...otherOptions,
|
|
3824
|
+
logLevel: logLevel2,
|
|
3825
|
+
silenceInitializationMessage: true,
|
|
3826
|
+
// This branch only runs when tracing is enabled (the disabled
|
|
3827
|
+
// case is handled above), so tracing is always on here.
|
|
3828
|
+
tracingEnabled: true,
|
|
3829
|
+
disableBatch: disableBatching,
|
|
3830
|
+
processor,
|
|
3831
|
+
exporter: guardedExporter,
|
|
3832
|
+
piiRedaction: piiRedaction2,
|
|
3833
|
+
instrumentations: createConfiguredInstrumentations(otherOptions)
|
|
3834
|
+
});
|
|
3835
|
+
traceloopInitialized = true;
|
|
3836
|
+
} catch (initError) {
|
|
3837
|
+
releasePipelineClaim();
|
|
3838
|
+
claimedPipeline = false;
|
|
3839
|
+
throw initError;
|
|
3840
|
+
}
|
|
3841
|
+
}
|
|
3842
|
+
} else {
|
|
3843
|
+
traceloopInitialized = true;
|
|
3844
|
+
}
|
|
3845
|
+
}
|
|
3846
|
+
}
|
|
3847
|
+
} catch (error) {
|
|
3848
|
+
if (claimedPipeline && !traceloopInitialized) {
|
|
3849
|
+
releasePipelineClaim();
|
|
3850
|
+
claimedPipeline = false;
|
|
3851
|
+
}
|
|
3852
|
+
console.warn(
|
|
3853
|
+
"[raindrop] Failed to initialize traceloop. Spans will not be sent.",
|
|
3854
|
+
error instanceof Error ? error.message : error
|
|
3855
|
+
);
|
|
3856
|
+
}
|
|
3857
|
+
if (traceloopInitialized) {
|
|
3858
|
+
markPipelineForExitFlush();
|
|
3859
|
+
}
|
|
3860
|
+
const deregisterExitFlusher = directShipper ? registerClientFlusher(async () => {
|
|
3861
|
+
try {
|
|
3862
|
+
await directShipper.flush();
|
|
3863
|
+
} catch (e) {
|
|
3864
|
+
}
|
|
3865
|
+
}) : void 0;
|
|
3866
|
+
const beginInteraction = (params) => {
|
|
3867
|
+
var _a2;
|
|
3868
|
+
const { tools, ...traceContext } = params;
|
|
3869
|
+
if (!traceContext.eventId) {
|
|
3870
|
+
traceContext.eventId = crypto.randomUUID();
|
|
3871
|
+
}
|
|
3872
|
+
const traceId = getCurrentTraceId();
|
|
3873
|
+
const interaction = new LiveInteraction(
|
|
3874
|
+
traceContext,
|
|
3875
|
+
traceId,
|
|
3876
|
+
analytics,
|
|
3877
|
+
directShipper,
|
|
3878
|
+
{ projectId, authHint, appGit: analytics.getAppGitSnapshot(traceContext.properties, traceContext.eventId) }
|
|
3879
|
+
);
|
|
3880
|
+
const bound = bindRoutingContext({ projectId, authHint, appGit: analytics.getAppGitSnapshot(traceContext.properties, traceContext.eventId) }, interaction);
|
|
3881
|
+
interaction.setBoundContext(bound);
|
|
3882
|
+
interaction.bindPromptToolsOverride(tools);
|
|
3883
|
+
try {
|
|
3884
|
+
analytics._trackAiPartial({
|
|
3885
|
+
...traceContext,
|
|
3886
|
+
properties: {
|
|
3887
|
+
...(_a2 = traceContext.properties) != null ? _a2 : {},
|
|
3888
|
+
...interaction.getTraceId() ? { trace_id: interaction.getTraceId() } : {}
|
|
3889
|
+
}
|
|
3890
|
+
});
|
|
3891
|
+
if (interaction.getTraceId()) {
|
|
3892
|
+
activeInteractions.set(interaction.getTraceId(), interaction);
|
|
3893
|
+
}
|
|
3894
|
+
activeInteractionsByEventId.set(traceContext.eventId, interaction);
|
|
3895
|
+
} catch (error) {
|
|
3896
|
+
unbindRoutingContext(bound);
|
|
3897
|
+
throw error;
|
|
3898
|
+
}
|
|
3899
|
+
return interaction;
|
|
3900
|
+
};
|
|
3901
|
+
const openSubagentRun = (carrierOrHeaders, options2) => {
|
|
3902
|
+
const resolved = resolveSubagentResume(carrierOrHeaders, options2);
|
|
3903
|
+
if (!resolved.parent && isDebug) {
|
|
3904
|
+
console.log(
|
|
3905
|
+
`[raindrop] resumeSubagent(${resolved.name}): no hand-off carrier on the request; reporting as an unlinked event ${resolved.eventId}.`
|
|
3906
|
+
);
|
|
3907
|
+
}
|
|
3908
|
+
const frameOwner = { subagentEventId: resolved.eventId };
|
|
3909
|
+
const frame = bindSubagentLink(resolved.link, frameOwner);
|
|
3910
|
+
let interaction;
|
|
3911
|
+
try {
|
|
3912
|
+
interaction = beginInteraction({
|
|
3913
|
+
eventId: resolved.eventId,
|
|
3914
|
+
event: resolved.event,
|
|
3915
|
+
userId: resolved.userId,
|
|
3916
|
+
...resolved.convoId ? { convoId: resolved.convoId } : {},
|
|
3917
|
+
...options2.input !== void 0 ? { input: options2.input } : {},
|
|
3918
|
+
...options2.model !== void 0 ? { model: options2.model } : {},
|
|
3919
|
+
...options2.properties ? { properties: options2.properties } : {}
|
|
3920
|
+
});
|
|
3921
|
+
} catch (error) {
|
|
3922
|
+
unbindSpanAttributes(frame);
|
|
3923
|
+
throw error;
|
|
3924
|
+
}
|
|
3925
|
+
return new LiveSubagentRun({
|
|
3926
|
+
interaction,
|
|
3927
|
+
eventId: resolved.eventId,
|
|
3928
|
+
name: resolved.name,
|
|
3929
|
+
...resolved.convoId ? { convoId: resolved.convoId } : {},
|
|
3930
|
+
parent: resolved.link,
|
|
3931
|
+
...frame ? { frame, frameOwner } : {}
|
|
3932
|
+
});
|
|
3933
|
+
};
|
|
3934
|
+
const recordModelUsage = (params) => {
|
|
3935
|
+
try {
|
|
3936
|
+
const attributes = [
|
|
3937
|
+
attrString(MODEL_USAGE_ATTRIBUTES.usageSource, "manual"),
|
|
3938
|
+
attrString(
|
|
3939
|
+
MODEL_USAGE_ATTRIBUTES.providerName,
|
|
3940
|
+
canonicalModelProvider(params.usage.provider)
|
|
3941
|
+
),
|
|
3942
|
+
attrString(MODEL_USAGE_ATTRIBUTES.requestModel, params.model),
|
|
3943
|
+
attrString(MODEL_USAGE_ATTRIBUTES.responseModel, params.model),
|
|
3944
|
+
...buildRawModelUsageAttributes({
|
|
3945
|
+
inputTokens: params.usage.inputTokens,
|
|
3946
|
+
outputTokens: params.usage.outputTokens,
|
|
3947
|
+
cacheReadInputTokens: params.usage.cacheReadTokens,
|
|
3948
|
+
cacheWriteInputTokens: params.usage.cacheWriteTokens,
|
|
3949
|
+
reasoningTokens: params.usage.reasoningTokens,
|
|
3950
|
+
providerReportedCost: params.usage.providerReportedCost
|
|
3951
|
+
})
|
|
3952
|
+
].filter((attribute) => attribute !== void 0);
|
|
3953
|
+
if (directShipper) {
|
|
3954
|
+
const timeMs = Date.now();
|
|
3955
|
+
directShipper.sendSpan({
|
|
3956
|
+
name: "ai.model.usage",
|
|
3957
|
+
spanKind: "llm",
|
|
3958
|
+
properties: { ...params.appGitProperties, event_id: params.eventId },
|
|
3959
|
+
appGitSnapshot: params.appGitSnapshot,
|
|
3960
|
+
startTimeMs: timeMs,
|
|
3961
|
+
endTimeMs: timeMs,
|
|
3962
|
+
durationMs: 0,
|
|
3963
|
+
otlpAttributes: attributes
|
|
3964
|
+
});
|
|
3965
|
+
return;
|
|
3966
|
+
}
|
|
3967
|
+
const initialAttributes = {
|
|
3968
|
+
"traceloop.span.kind": "llm"
|
|
3969
|
+
};
|
|
3970
|
+
for (const [key, value] of Object.entries({
|
|
3971
|
+
...params.appGitProperties,
|
|
3972
|
+
event_id: params.eventId
|
|
3973
|
+
})) {
|
|
3974
|
+
if (value !== void 0) {
|
|
3975
|
+
initialAttributes[`traceloop.association.properties.${key}`] = stringifyBounded(value);
|
|
3976
|
+
}
|
|
3977
|
+
}
|
|
3978
|
+
for (const [key, value] of Object.entries(params.appGitSnapshot)) {
|
|
3979
|
+
if (typeof value === "string" || typeof value === "boolean") {
|
|
3980
|
+
initialAttributes[key] = value;
|
|
3981
|
+
}
|
|
3982
|
+
}
|
|
3983
|
+
const span = trace6.getTracer("traceloop.tracer").startSpan("ai.model.usage", { attributes: initialAttributes });
|
|
3984
|
+
stampSpan(span, projectId, authHint);
|
|
3985
|
+
for (const attribute of attributes) {
|
|
3986
|
+
const value = attribute.value;
|
|
3987
|
+
if (value.stringValue !== void 0) {
|
|
3988
|
+
span.setAttribute(attribute.key, value.stringValue);
|
|
3989
|
+
} else if (value.intValue !== void 0) {
|
|
3990
|
+
const parsed = Number(value.intValue);
|
|
3991
|
+
if (Number.isSafeInteger(parsed)) span.setAttribute(attribute.key, parsed);
|
|
3992
|
+
} else if (value.doubleValue !== void 0) {
|
|
3993
|
+
span.setAttribute(attribute.key, value.doubleValue);
|
|
3994
|
+
} else if (value.boolValue !== void 0) {
|
|
3995
|
+
span.setAttribute(attribute.key, value.boolValue);
|
|
3996
|
+
}
|
|
3997
|
+
}
|
|
3998
|
+
span.end();
|
|
3999
|
+
} catch (e) {
|
|
4000
|
+
}
|
|
4001
|
+
};
|
|
4002
|
+
return {
|
|
4003
|
+
/**
|
|
4004
|
+
* Returns instrumentation instances for your NodeSDK.
|
|
4005
|
+
* Add these to your NodeSDK when using useExternalOtel: true.
|
|
4006
|
+
*
|
|
4007
|
+
* - If `instrumentModules` is provided: returns only those specific instrumentations
|
|
4008
|
+
* - If `instrumentModules` is NOT provided: returns ALL default instrumentations (auto-instrumentation)
|
|
4009
|
+
*
|
|
4010
|
+
* @example
|
|
4011
|
+
* ```typescript
|
|
4012
|
+
* const raindrop = new Raindrop({
|
|
4013
|
+
* useExternalOtel: true,
|
|
4014
|
+
* // instrumentModules is optional - if omitted, all instrumentations are returned
|
|
4015
|
+
* });
|
|
4016
|
+
*
|
|
4017
|
+
* const sdk = new NodeSDK({
|
|
4018
|
+
* spanProcessors: [raindrop.createSpanProcessor()],
|
|
4019
|
+
* instrumentations: raindrop.getInstrumentations(),
|
|
4020
|
+
* });
|
|
4021
|
+
* sdk.start();
|
|
4022
|
+
* ```
|
|
4023
|
+
*/
|
|
4024
|
+
getInstrumentations() {
|
|
4025
|
+
if (!useExternalOtel) {
|
|
4026
|
+
console.warn(
|
|
4027
|
+
"[raindrop] getInstrumentations() is meant for useExternalOtel: true. In default mode, instrumentations are automatically registered."
|
|
4028
|
+
);
|
|
4029
|
+
}
|
|
4030
|
+
if (otherOptions.instrumentModules && Object.keys(otherOptions.instrumentModules).length > 0) {
|
|
4031
|
+
return createManualInstrumentations(
|
|
4032
|
+
otherOptions.instrumentModules
|
|
4033
|
+
);
|
|
4034
|
+
}
|
|
4035
|
+
return createDefaultInstrumentations();
|
|
4036
|
+
},
|
|
4037
|
+
/**
|
|
4038
|
+
* Creates a span processor to add to your NodeSDK.
|
|
4039
|
+
* This sends spans to Raindrop.
|
|
4040
|
+
*
|
|
4041
|
+
* @example
|
|
4042
|
+
* ```typescript
|
|
4043
|
+
* const sdk = new NodeSDK({
|
|
4044
|
+
* spanProcessors: [raindrop.createSpanProcessor()],
|
|
4045
|
+
* instrumentations: raindrop.getInstrumentations(),
|
|
4046
|
+
* });
|
|
4047
|
+
* ```
|
|
4048
|
+
*/
|
|
4049
|
+
createSpanProcessor(processorOptions) {
|
|
4050
|
+
if (!useExternalOtel) {
|
|
4051
|
+
console.warn(
|
|
4052
|
+
"[raindrop] createSpanProcessor() is meant for useExternalOtel: true. In default mode, spans are automatically sent to Raindrop."
|
|
4053
|
+
);
|
|
4054
|
+
}
|
|
4055
|
+
if (!traceloopInitialized) {
|
|
4056
|
+
console.error("[raindrop] Cannot create span processor - traceloop failed to initialize.");
|
|
4057
|
+
return {
|
|
4058
|
+
forceFlush: async () => {
|
|
4059
|
+
},
|
|
4060
|
+
onStart: () => {
|
|
4061
|
+
},
|
|
4062
|
+
onEnd: () => {
|
|
4063
|
+
},
|
|
4064
|
+
shutdown: async () => {
|
|
4065
|
+
}
|
|
4066
|
+
};
|
|
4067
|
+
}
|
|
4068
|
+
if (!cloudEnabledResolved) {
|
|
4069
|
+
const localOnlyProcessor = createLocalDebuggerSpanProcessor({
|
|
4070
|
+
writeKey,
|
|
4071
|
+
disableBatching,
|
|
4072
|
+
allowedInstrumentationLibraries: processorOptions == null ? void 0 : processorOptions.allowedInstrumentationLibraries,
|
|
4073
|
+
localDebuggerUrlOpt: localDebuggerUrl,
|
|
4074
|
+
routeReplayTraces: true,
|
|
4075
|
+
piiRedaction: piiRedaction2
|
|
4076
|
+
});
|
|
4077
|
+
return withV2SpanCompat(
|
|
4078
|
+
localOnlyProcessor != null ? localOnlyProcessor : {
|
|
4079
|
+
forceFlush: async () => {
|
|
4080
|
+
},
|
|
4081
|
+
onStart: () => {
|
|
4082
|
+
},
|
|
4083
|
+
onEnd: () => {
|
|
4084
|
+
},
|
|
4085
|
+
shutdown: async () => {
|
|
4086
|
+
}
|
|
4087
|
+
}
|
|
4088
|
+
);
|
|
4089
|
+
}
|
|
4090
|
+
const headers = withProjectIdHeaders(processorOptions == null ? void 0 : processorOptions.headers);
|
|
4091
|
+
const productionProcessor = createSpanProcessor({
|
|
4092
|
+
baseUrl: apiUrl,
|
|
4093
|
+
apiKey: writeKey,
|
|
4094
|
+
disableBatch: disableBatching,
|
|
4095
|
+
...processorOptions != null ? processorOptions : {},
|
|
4096
|
+
routeReplayTraces: true,
|
|
4097
|
+
...headers ? { headers } : {},
|
|
4098
|
+
piiRedaction: piiRedaction2
|
|
4099
|
+
});
|
|
4100
|
+
const localDebuggerProcessor = createLocalDebuggerSpanProcessor({
|
|
4101
|
+
writeKey,
|
|
4102
|
+
disableBatching,
|
|
4103
|
+
allowedInstrumentationLibraries: processorOptions == null ? void 0 : processorOptions.allowedInstrumentationLibraries,
|
|
4104
|
+
localDebuggerUrlOpt: localDebuggerUrl,
|
|
4105
|
+
piiRedaction: piiRedaction2
|
|
4106
|
+
});
|
|
4107
|
+
const contextProcessor = new RaindropContextSpanProcessor((properties) => analytics.getAppGitSnapshot(properties));
|
|
4108
|
+
return withV2SpanCompat(
|
|
4109
|
+
new CompositeSpanProcessor(
|
|
4110
|
+
[contextProcessor, productionProcessor],
|
|
4111
|
+
localDebuggerProcessor ? [localDebuggerProcessor] : []
|
|
4112
|
+
)
|
|
4113
|
+
);
|
|
4114
|
+
},
|
|
4115
|
+
begin(traceContext) {
|
|
4116
|
+
return beginInteraction(traceContext);
|
|
4117
|
+
},
|
|
4118
|
+
recordModelUsage,
|
|
4119
|
+
resumeSubagent(carrierOrHeaders, options2 = {}) {
|
|
4120
|
+
return openSubagentRun(carrierOrHeaders, options2);
|
|
4121
|
+
},
|
|
4122
|
+
withSubagentRun(carrierOrHeaders, fn, options2 = {}) {
|
|
4123
|
+
return openSubagentRun(carrierOrHeaders, options2).use(fn);
|
|
4124
|
+
},
|
|
4125
|
+
getActiveInteraction(eventId) {
|
|
4126
|
+
const interactionByEventId = activeInteractionsByEventId.get(eventId);
|
|
4127
|
+
if (interactionByEventId) {
|
|
4128
|
+
return interactionByEventId;
|
|
4129
|
+
}
|
|
4130
|
+
const traceId = getCurrentTraceId();
|
|
4131
|
+
if (traceId) {
|
|
4132
|
+
const interactionByTraceId = activeInteractions.get(traceId);
|
|
4133
|
+
if (interactionByTraceId) {
|
|
4134
|
+
return interactionByTraceId;
|
|
4135
|
+
}
|
|
4136
|
+
}
|
|
4137
|
+
const interaction = new LiveInteraction({ eventId }, traceId, analytics, directShipper, {
|
|
4138
|
+
projectId,
|
|
4139
|
+
authHint
|
|
4140
|
+
});
|
|
4141
|
+
activeInteractionsByEventId.set(eventId, interaction);
|
|
4142
|
+
return interaction;
|
|
4143
|
+
},
|
|
4144
|
+
tracer(globalProperties) {
|
|
4145
|
+
return new LiveTracer(globalProperties, directShipper, { projectId, authHint });
|
|
4146
|
+
},
|
|
4147
|
+
/**
|
|
4148
|
+
* Best-effort drain of in-flight OTel spans and direct shipper batches.
|
|
4149
|
+
* Safe to call when nothing is in flight; never throws.
|
|
4150
|
+
*/
|
|
4151
|
+
async forceFlush() {
|
|
4152
|
+
const deadlineAt = Date.now() + resolveFlushTimeoutMs(flushTimeoutMs);
|
|
4153
|
+
let result = { ...DELIVERED };
|
|
4154
|
+
if (directShipper) {
|
|
4155
|
+
try {
|
|
4156
|
+
result = await directShipper.flush();
|
|
4157
|
+
} catch (e) {
|
|
4158
|
+
}
|
|
4159
|
+
}
|
|
4160
|
+
if (traceloopInitialized) {
|
|
4161
|
+
const settled = await raceWithTimeout(
|
|
4162
|
+
forceFlush().catch(() => {
|
|
4163
|
+
}),
|
|
4164
|
+
deadlineAt - Date.now()
|
|
4165
|
+
);
|
|
4166
|
+
if (!settled) {
|
|
4167
|
+
result = combineResults(result, {
|
|
4168
|
+
...DELIVERED,
|
|
4169
|
+
delivered: false,
|
|
4170
|
+
timedOut: true,
|
|
4171
|
+
inFlight: 1
|
|
4172
|
+
});
|
|
4173
|
+
}
|
|
4174
|
+
}
|
|
4175
|
+
return asCompat(result);
|
|
4176
|
+
},
|
|
4177
|
+
/** Drain and stop; resolves (never rejects) to the direct shipper's result. */
|
|
4178
|
+
async close() {
|
|
4179
|
+
var _a2;
|
|
4180
|
+
deregisterExitFlusher == null ? void 0 : deregisterExitFlusher();
|
|
4181
|
+
activeInteractions.clear();
|
|
4182
|
+
activeInteractionsByEventId.clear();
|
|
4183
|
+
let result = { ...DELIVERED };
|
|
4184
|
+
try {
|
|
4185
|
+
result = (_a2 = await (directShipper == null ? void 0 : directShipper.shutdown())) != null ? _a2 : result;
|
|
4186
|
+
} catch (e) {
|
|
4187
|
+
}
|
|
4188
|
+
if (traceloopInitialized) {
|
|
4189
|
+
try {
|
|
4190
|
+
await forceFlush();
|
|
4191
|
+
} catch (e) {
|
|
4192
|
+
}
|
|
4193
|
+
}
|
|
4194
|
+
return result;
|
|
4195
|
+
}
|
|
4196
|
+
};
|
|
4197
|
+
};
|
|
4198
|
+
|
|
4199
|
+
export {
|
|
4200
|
+
package_default,
|
|
4201
|
+
authHintForKey,
|
|
4202
|
+
withTask,
|
|
4203
|
+
tracing
|
|
4204
|
+
};
|