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.
@@ -1,9 +1,3 @@
1
- // src/lib/inject-als.ts
2
- import { AsyncLocalStorage } from "async_hooks";
3
- if (!globalThis.RAINDROP_ASYNC_LOCAL_STORAGE) {
4
- globalThis.RAINDROP_ASYNC_LOCAL_STORAGE = AsyncLocalStorage;
5
- }
6
-
7
1
  // ../core/dist/chunk-ZCB62SIO.js
8
2
  var __create = Object.create;
9
3
  var __defProp = Object.defineProperty;
@@ -2313,11 +2307,11 @@ function isPlainObject(value) {
2313
2307
  function isThenable(value) {
2314
2308
  return typeof value === "object" && value !== null && "then" in value && typeof value.then === "function";
2315
2309
  }
2316
- function warn(prefix, context7, reason) {
2310
+ function warn(prefix, context, reason) {
2317
2311
  rateLimitedLog(
2318
2312
  `${prefix}.mask_failed`,
2319
2313
  () => console.warn(
2320
- `${prefix} mask function failed on ${context7.kind} ${context7.field} (${reason}); sending ${MASK_FAILED} in its place.`
2314
+ `${prefix} mask function failed on ${context.kind} ${context.field} (${reason}); sending ${MASK_FAILED} in its place.`
2321
2315
  )
2322
2316
  );
2323
2317
  }
@@ -2331,14 +2325,14 @@ function failed(shape) {
2331
2325
  if (shape === "object") return { error: MASK_FAILED };
2332
2326
  return [];
2333
2327
  }
2334
- function maskValue(value, context7, mask, prefix) {
2328
+ function maskValue(value, context, mask, prefix) {
2335
2329
  const shape = typeof value === "string" ? "string" : Array.isArray(value) ? "array" : "object";
2336
2330
  try {
2337
- const result = mask(shape === "string" ? value : jsonCopy(value), context7);
2331
+ const result = mask(shape === "string" ? value : jsonCopy(value), context);
2338
2332
  if (isThenable(result)) {
2339
2333
  Promise.resolve(result).catch(() => {
2340
2334
  });
2341
- warn(prefix, context7, "it returned a promise; mask must be synchronous");
2335
+ warn(prefix, context, "it returned a promise; mask must be synchronous");
2342
2336
  return failed(shape);
2343
2337
  }
2344
2338
  if (shape === "string") {
@@ -2347,32 +2341,32 @@ function maskValue(value, context7, mask, prefix) {
2347
2341
  const copy = jsonCopy(result);
2348
2342
  if (shape === "array" ? Array.isArray(copy) : isPlainObject(copy)) return copy;
2349
2343
  }
2350
- warn(prefix, context7, `it returned a value that is not ${shape === "string" ? "a string" : `an ${shape}`}`);
2344
+ warn(prefix, context, `it returned a value that is not ${shape === "string" ? "a string" : `an ${shape}`}`);
2351
2345
  } catch (err) {
2352
- warn(prefix, context7, err instanceof Error ? err.name : "threw");
2346
+ warn(prefix, context, err instanceof Error ? err.name : "threw");
2353
2347
  }
2354
2348
  return failed(shape);
2355
2349
  }
2356
- function maskAt(node, path, context7, mask, prefix) {
2350
+ function maskAt(node, path, context, mask, prefix) {
2357
2351
  const [head, ...rest] = path;
2358
2352
  if (head === void 0 || !Object.prototype.hasOwnProperty.call(node, head)) return node;
2359
2353
  const child = node[head];
2360
2354
  if (rest.length > 0) {
2361
2355
  if (!isPlainObject(child)) return node;
2362
- const next = maskAt(child, rest, context7, mask, prefix);
2356
+ const next = maskAt(child, rest, context, mask, prefix);
2363
2357
  return next === child ? node : { ...node, [head]: next };
2364
2358
  }
2365
2359
  if (child === void 0 || child === null) return node;
2366
2360
  if (typeof child !== "string" && typeof child !== "object") return node;
2367
- if (context7.kind !== "event" || head !== "properties" || !isPlainObject(child)) {
2368
- return { ...node, [head]: maskValue(child, context7, mask, prefix) };
2361
+ if (context.kind !== "event" || head !== "properties" || !isPlainObject(child)) {
2362
+ return { ...node, [head]: maskValue(child, context, mask, prefix) };
2369
2363
  }
2370
2364
  const own2 = {};
2371
2365
  const sdk = {};
2372
2366
  for (const [key, value] of Object.entries(child)) {
2373
2367
  (SDK_PROPERTY_KEYS.includes(key) ? sdk : own2)[key] = value;
2374
2368
  }
2375
- const masked = maskValue(own2, context7, mask, prefix);
2369
+ const masked = maskValue(own2, context, mask, prefix);
2376
2370
  return { ...node, [head]: isPlainObject(masked) ? { ...masked, ...sdk } : sdk };
2377
2371
  }
2378
2372
  function maskPayload(kind, payload, mask, logPrefix = "[raindrop-ai/core]") {
@@ -2383,17 +2377,17 @@ function maskPayload(kind, payload, mask, logPrefix = "[raindrop-ai/core]") {
2383
2377
  }
2384
2378
  return out;
2385
2379
  }
2386
- function maskOtlpValue(value, context7, mask, prefix) {
2380
+ function maskOtlpValue(value, context, mask, prefix) {
2387
2381
  var _a;
2388
2382
  if (typeof value.stringValue === "string") {
2389
- const masked = maskValue(value.stringValue, context7, mask, prefix);
2383
+ const masked = maskValue(value.stringValue, context, mask, prefix);
2390
2384
  return typeof masked === "string" && masked !== value.stringValue ? { ...value, stringValue: masked } : value;
2391
2385
  }
2392
2386
  const values = (_a = value.arrayValue) == null ? void 0 : _a.values;
2393
2387
  if (!values) return value;
2394
2388
  let changed = false;
2395
2389
  const next = values.map((item) => {
2396
- const masked = maskOtlpValue(item, context7, mask, prefix);
2390
+ const masked = maskOtlpValue(item, context, mask, prefix);
2397
2391
  if (masked !== item) changed = true;
2398
2392
  return masked;
2399
2393
  });
@@ -2432,15 +2426,15 @@ function maskAttributeMap(attributes, mask, fields, logPrefix = "[raindrop-ai/co
2432
2426
  let next;
2433
2427
  for (const [key, value] of Object.entries(attributes)) {
2434
2428
  if (!isSpanContentAttributeKey(key, fields)) continue;
2435
- const context7 = { kind: "span", field: key };
2429
+ const context = { kind: "span", field: key };
2436
2430
  let masked = value;
2437
2431
  if (typeof value === "string") {
2438
- masked = maskValue(value, context7, mask, logPrefix);
2432
+ masked = maskValue(value, context, mask, logPrefix);
2439
2433
  } else if (Array.isArray(value)) {
2440
2434
  let changed = false;
2441
2435
  const items = value.map((item) => {
2442
2436
  if (typeof item !== "string") return item;
2443
- const out = maskValue(item, context7, mask, logPrefix);
2437
+ const out = maskValue(item, context, mask, logPrefix);
2444
2438
  if (out !== item) changed = true;
2445
2439
  return out;
2446
2440
  });
@@ -4052,7 +4046,7 @@ function promptToolsFromTraceloopAttributes(attributes) {
4052
4046
  }
4053
4047
 
4054
4048
  // ../core/dist/index.node.js
4055
- import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
4049
+ import { AsyncLocalStorage } from "async_hooks";
4056
4050
  import { execFile } from "child_process";
4057
4051
  import { resolve } from "path";
4058
4052
  var resolveLocal = (sourceDirectory, detectBranch, completed) => {
@@ -4184,7 +4178,7 @@ var EventShipper2 = class extends EventShipper {
4184
4178
  if (ownsAppGitContext) this.ownAppGitContextForShutdown();
4185
4179
  }
4186
4180
  };
4187
- globalThis.RAINDROP_ASYNC_LOCAL_STORAGE = AsyncLocalStorage2;
4181
+ globalThis.RAINDROP_ASYNC_LOCAL_STORAGE = AsyncLocalStorage;
4188
4182
  var SUPPRESS_TRACING_KEY = /* @__PURE__ */ Symbol.for(
4189
4183
  "OpenTelemetry SDK Context Key SUPPRESS_TRACING"
4190
4184
  );
@@ -4211,4115 +4205,6 @@ function installTracingSuppressionHook() {
4211
4205
  }
4212
4206
  installTracingSuppressionHook();
4213
4207
 
4214
- // package.json
4215
- var package_default = {
4216
- name: "raindrop-ai",
4217
- version: "1.1.1",
4218
- main: "dist/index.js",
4219
- module: "dist/index.mjs",
4220
- types: "dist/index.d.ts",
4221
- bin: {
4222
- "raindrop-evals": "dist/evals/cli.js"
4223
- },
4224
- license: "MIT",
4225
- homepage: "https://www.raindrop.ai/docs/sdk/typescript/",
4226
- bugs: {
4227
- url: "https://www.raindrop.ai/docs/support/"
4228
- },
4229
- exports: {
4230
- ".": {
4231
- import: {
4232
- types: "./dist/index.d.mts",
4233
- default: "./dist/index.mjs"
4234
- },
4235
- require: {
4236
- types: "./dist/index.d.ts",
4237
- default: "./dist/index.js"
4238
- }
4239
- },
4240
- "./tracing": {
4241
- types: "./dist/tracing/index.d.ts",
4242
- node: "./dist/tracing/index.js",
4243
- import: "./dist/tracing/index.mjs",
4244
- require: "./dist/tracing/index.js"
4245
- },
4246
- "./otel": {
4247
- types: "./dist/otel/index.d.ts",
4248
- node: "./dist/otel/index.js",
4249
- import: "./dist/otel/index.mjs",
4250
- require: "./dist/otel/index.js"
4251
- }
4252
- },
4253
- files: [
4254
- "dist/**"
4255
- ],
4256
- scripts: {
4257
- build: "tsup",
4258
- dev: "tsup --watch",
4259
- clean: "rm -rf .turbo && rm -rf dist",
4260
- try: "tsx ./src/example/index.ts",
4261
- test: "vitest run",
4262
- smoke: "tsx ./scripts/smoke.ts",
4263
- "smoke:ai-sdk-self-diagnostics": "tsx ./scripts/smoke.ai-sdk-self-diagnostics.ts",
4264
- "smoke:self-diagnostics:v4": "pnpm build && cd tests/v4 && pnpm install --ignore-workspace --lockfile=false && pnpm smoke",
4265
- "smoke:self-diagnostics:v5": "pnpm build && cd tests/v5 && pnpm install --ignore-workspace --lockfile=false && pnpm smoke",
4266
- "smoke:self-diagnostics:v6": "pnpm build && cd tests/v6 && pnpm install --ignore-workspace --lockfile=false && pnpm smoke",
4267
- "smoke:self-diagnostics:ai-sdk:all": "pnpm smoke:self-diagnostics:v4 && pnpm smoke:self-diagnostics:v5 && pnpm smoke:self-diagnostics:v6",
4268
- "smoke:self-diagnostics:openai-sdk": "pnpm build && cd tests/openai && pnpm install --ignore-workspace --lockfile=false && pnpm smoke",
4269
- "smoke:self-diagnostics:anthropic-sdk": "pnpm build && cd tests/anthropic && pnpm install --ignore-workspace --lockfile=false && pnpm smoke",
4270
- "smoke:self-diagnostics:all": "pnpm smoke:self-diagnostics:ai-sdk:all && pnpm smoke:self-diagnostics:openai-sdk && pnpm smoke:self-diagnostics:anthropic-sdk",
4271
- "test:otelv1-local-debugger": "pnpm build && cd tests/otelv1-local-debugger && pnpm install --ignore-workspace --lockfile=false && pnpm test",
4272
- "test:otelv2-local-debugger": "pnpm build && cd tests/otelv2-local-debugger && pnpm install --ignore-workspace --lockfile=false && pnpm test"
4273
- },
4274
- devDependencies: {
4275
- "@raindrop-ai/core": "workspace:*",
4276
- "@raindrop-ai/redact-pii": "workspace:*",
4277
- "@raindrop-ai/schemas": "workspace:*",
4278
- "@types/node": "^20.11.17",
4279
- ai: "^6.0.214",
4280
- msw: "^2.12.8",
4281
- tsup: "^9.0.0",
4282
- tsx: "^4.22.0",
4283
- typescript: "^5.3.3",
4284
- vite: "^7.3.7",
4285
- vitest: "^4.1.12",
4286
- "zod-4-copy": "npm:zod@4.1.8"
4287
- },
4288
- dependencies: {
4289
- "@jitl/quickjs-singlefile-cjs-release-sync": "0.32.0",
4290
- "@opentelemetry/api": "^1.9.0",
4291
- "@opentelemetry/core": "^1.30.1",
4292
- "@opentelemetry/exporter-trace-otlp-http": "^0.57.2",
4293
- "@opentelemetry/exporter-trace-otlp-proto": "^0.57.2",
4294
- "@opentelemetry/instrumentation": "^0.57.2",
4295
- "@opentelemetry/resources": "^1.30.1",
4296
- "@opentelemetry/sdk-trace-base": "^1.30.1",
4297
- "@opentelemetry/sdk-trace-node": "^1.30.1",
4298
- "@traceloop/ai-semantic-conventions": "0.19.0-otel-v1",
4299
- "@traceloop/instrumentation-anthropic": "0.19.0-otel-v1",
4300
- "@traceloop/instrumentation-bedrock": "0.19.0-otel-v1",
4301
- "@traceloop/instrumentation-chromadb": "0.19.0-otel-v1",
4302
- "@traceloop/instrumentation-cohere": "0.19.0-otel-v1",
4303
- "@traceloop/instrumentation-langchain": "0.19.0-otel-v1",
4304
- "@traceloop/instrumentation-llamaindex": "0.19.0-otel-v1",
4305
- "@traceloop/instrumentation-openai": "0.19.0-otel-v1",
4306
- "@traceloop/instrumentation-pinecone": "0.19.0-otel-v1",
4307
- "@traceloop/instrumentation-qdrant": "0.19.0-otel-v1",
4308
- "@traceloop/instrumentation-together": "0.19.0-otel-v1",
4309
- "@traceloop/instrumentation-vertexai": "0.19.0-otel-v1",
4310
- "quickjs-emscripten-core": "0.32.0",
4311
- weakref: "^0.2.1",
4312
- zod: "^3.25.76 || ^4.0.0"
4313
- },
4314
- publishConfig: {
4315
- access: "public",
4316
- provenance: false
4317
- },
4318
- tsup: {
4319
- entry: [
4320
- "src/index.ts",
4321
- "src/evals/cli.ts",
4322
- "src/tracing/index.ts",
4323
- "src/otel/index.ts"
4324
- ],
4325
- format: [
4326
- "cjs",
4327
- "esm"
4328
- ],
4329
- external: [
4330
- "@traceloop/instrumentation-anthropic",
4331
- "@traceloop/instrumentation-openai",
4332
- "@traceloop/instrumentation-cohere",
4333
- "@traceloop/instrumentation-bedrock",
4334
- "@traceloop/instrumentation-vertexai",
4335
- "@traceloop/instrumentation-pinecone",
4336
- "@traceloop/instrumentation-chromadb",
4337
- "@traceloop/instrumentation-qdrant",
4338
- "@traceloop/instrumentation-together",
4339
- "@traceloop/instrumentation-langchain",
4340
- "@traceloop/instrumentation-llamaindex",
4341
- "@traceloop/ai-semantic-conventions",
4342
- "@opentelemetry/api",
4343
- "@opentelemetry/core",
4344
- "@opentelemetry/instrumentation",
4345
- "@opentelemetry/exporter-trace-otlp-http",
4346
- "@opentelemetry/exporter-trace-otlp-proto",
4347
- "@opentelemetry/resources",
4348
- "@opentelemetry/sdk-trace-base",
4349
- "@opentelemetry/sdk-trace-node"
4350
- ],
4351
- noExternal: [
4352
- "@raindrop-ai/core",
4353
- "@raindrop-ai/redact-pii",
4354
- "@raindrop-ai/schemas"
4355
- ],
4356
- dts: {
4357
- resolve: true
4358
- },
4359
- clean: true
4360
- }
4361
- };
4362
-
4363
- // src/tracing/multi-project.ts
4364
- import { createHash } from "crypto";
4365
- import { OTLPTraceExporter as OTLPProtoTraceExporter2 } from "@opentelemetry/exporter-trace-otlp-proto";
4366
-
4367
- // src/tracing/replay-routing.ts
4368
- import { OTLPTraceExporter as OTLPProtoTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
4369
- var EXPORT_SUCCESS = 0;
4370
- var EXPORT_FAILED = 1;
4371
- function recordExportedSpan(destination, span) {
4372
- if (typeof span !== "object" && typeof span !== "function" || span === null) return;
4373
- const spanContext = span.spanContext;
4374
- if (typeof spanContext !== "function") return;
4375
- const context7 = spanContext.call(span);
4376
- if (typeof (context7 == null ? void 0 : context7.spanId) === "string" && typeof context7.traceId === "string") {
4377
- recordReplayExportedSpan(destination, context7.spanId, context7.traceId);
4378
- }
4379
- }
4380
- function createReplayExporter(destination) {
4381
- var _a;
4382
- if (destination.kind === "workshop") {
4383
- return new OTLPProtoTraceExporter({
4384
- url: replayTraceUrl(destination.url)
4385
- });
4386
- }
4387
- return new OTLPProtoTraceExporter({
4388
- url: replayTraceUrl(destination.url),
4389
- headers: {
4390
- Authorization: `Bearer ${destination.apiKey}`,
4391
- "X-Raindrop-Replay-Id": destination.replayId,
4392
- "X-Raindrop-Project-Id": (_a = destination.projectId) != null ? _a : "default"
4393
- }
4394
- });
4395
- }
4396
- var ReplayRoutingSpanExporter = class {
4397
- constructor(normal, replayExporter = createReplayExporter) {
4398
- this.normal = normal;
4399
- this.replayExporter = replayExporter;
4400
- }
4401
- export(spans, resultCallback) {
4402
- const replayGroups = /* @__PURE__ */ new Map();
4403
- const normalSpans = [];
4404
- for (const span of spans) {
4405
- const destination = replayTraceDestinationFor(span);
4406
- if (!destination) {
4407
- normalSpans.push(span);
4408
- continue;
4409
- }
4410
- const group = replayGroups.get(destination);
4411
- recordExportedSpan(destination, span);
4412
- if (group) group.push(span);
4413
- else replayGroups.set(destination, [span]);
4414
- }
4415
- if (replayGroups.size === 0) {
4416
- this.normal.export(spans, resultCallback);
4417
- return;
4418
- }
4419
- let remaining = replayGroups.size + (normalSpans.length > 0 ? 1 : 0);
4420
- let failed2 = false;
4421
- let firstError;
4422
- const finish = (result) => {
4423
- if (result.code !== EXPORT_SUCCESS) {
4424
- failed2 = true;
4425
- firstError != null ? firstError : firstError = result.error;
4426
- }
4427
- remaining -= 1;
4428
- if (remaining === 0) {
4429
- resultCallback(
4430
- firstError ? { code: EXPORT_FAILED, error: firstError } : { code: failed2 ? EXPORT_FAILED : EXPORT_SUCCESS }
4431
- );
4432
- }
4433
- };
4434
- if (normalSpans.length > 0) {
4435
- try {
4436
- this.normal.export(normalSpans, finish);
4437
- } catch (cause) {
4438
- finish({
4439
- code: EXPORT_FAILED,
4440
- error: cause instanceof Error ? cause : new Error(String(cause))
4441
- });
4442
- }
4443
- }
4444
- for (const [destination, replaySpans] of replayGroups) {
4445
- let exporter;
4446
- try {
4447
- exporter = this.replayExporter(destination);
4448
- } catch (cause) {
4449
- finish({
4450
- code: EXPORT_FAILED,
4451
- error: cause instanceof Error ? cause : new Error(String(cause))
4452
- });
4453
- continue;
4454
- }
4455
- try {
4456
- exporter.export(replaySpans, (result) => {
4457
- finish(result);
4458
- void exporter.shutdown().catch(() => {
4459
- });
4460
- });
4461
- } catch (cause) {
4462
- finish({
4463
- code: EXPORT_FAILED,
4464
- error: cause instanceof Error ? cause : new Error(String(cause))
4465
- });
4466
- void exporter.shutdown().catch(() => {
4467
- });
4468
- }
4469
- }
4470
- }
4471
- forceFlush() {
4472
- return this.normal.forceFlush ? this.normal.forceFlush() : Promise.resolve();
4473
- }
4474
- shutdown() {
4475
- return this.normal.shutdown();
4476
- }
4477
- };
4478
-
4479
- // src/tracing/multi-project.ts
4480
- var PROJECT_ID_SPAN_ATTRIBUTE = "raindrop.project_id";
4481
- var AUTH_HINT_SPAN_ATTRIBUTE = "raindrop.auth_hint";
4482
- var EXPORT_SUCCESS2 = 0;
4483
- var EXPORT_FAILED2 = 1;
4484
- var SPAN_STATUS_ERROR = 2;
4485
- function authHintForKey(writeKey) {
4486
- if (!writeKey) return void 0;
4487
- return createHash("sha256").update(writeKey, "utf8").digest("hex").slice(0, 8);
4488
- }
4489
- var STATE_KEY3 = /* @__PURE__ */ Symbol.for("raindrop.tracing.multiProjectState");
4490
- function getState() {
4491
- const holder = globalThis;
4492
- let state2 = holder[STATE_KEY3];
4493
- if (!state2) {
4494
- state2 = {
4495
- foreignClientSeen: false,
4496
- seenClientHints: /* @__PURE__ */ new Set(),
4497
- ownerAuthHint: void 0,
4498
- ownerProjectId: void 0,
4499
- pipelineClaimed: false,
4500
- traceloopConfiguredWithoutClaim: false,
4501
- multiKeyWarned: false,
4502
- pendingMultiKeyWarning: false
4503
- };
4504
- holder[STATE_KEY3] = state2;
4505
- }
4506
- return state2;
4507
- }
4508
- function emitMultiKeyWarningOnce() {
4509
- const state2 = getState();
4510
- if (state2.multiKeyWarned) return;
4511
- state2.multiKeyWarned = true;
4512
- state2.pendingMultiKeyWarning = false;
4513
- console.warn(
4514
- "[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."
4515
- );
4516
- }
4517
- function registerClientKey(authHint, tracingEnabled = false) {
4518
- if (!authHint) return;
4519
- const state2 = getState();
4520
- state2.seenClientHints.add(authHint);
4521
- if (state2.seenClientHints.size > 1) {
4522
- state2.foreignClientSeen = true;
4523
- if (tracingEnabled || state2.pipelineClaimed) {
4524
- emitMultiKeyWarningOnce();
4525
- } else {
4526
- state2.pendingMultiKeyWarning = true;
4527
- }
4528
- }
4529
- }
4530
- function markForeignClient() {
4531
- getState().foreignClientSeen = true;
4532
- }
4533
- function foreignClientSeen() {
4534
- return getState().foreignClientSeen;
4535
- }
4536
- function stampSpan(span, projectId, authHint) {
4537
- try {
4538
- if (projectId) {
4539
- span.setAttribute(PROJECT_ID_SPAN_ATTRIBUTE, projectId);
4540
- }
4541
- if (authHint && foreignClientSeen()) {
4542
- span.setAttribute(AUTH_HINT_SPAN_ATTRIBUTE, authHint);
4543
- }
4544
- } catch (e) {
4545
- }
4546
- }
4547
- function stampContextAttributes(span) {
4548
- try {
4549
- applySpanAttributeFrames(span, (key, value) => span.setAttribute(key, value));
4550
- for (const [key, value] of Object.entries(evalScopeAttributes())) {
4551
- span.setAttribute(key, value);
4552
- }
4553
- } catch (e) {
4554
- }
4555
- }
4556
- var RaindropContextSpanProcessor = class {
4557
- constructor(appGitSnapshot) {
4558
- this.appGitSnapshot = appGitSnapshot;
4559
- this.appGitAdded = /* @__PURE__ */ new WeakMap();
4560
- }
4561
- onStart(span) {
4562
- var _a, _b, _c, _d;
4563
- try {
4564
- stampContextAttributes(span);
4565
- rememberReplayTraceDestination(span);
4566
- const bound = currentRoutingBinding();
4567
- const keys = ["raindrop.app.commit_sha", "raindrop.app.commit_dirty", "raindrop.app.branch"];
4568
- const attrs = (_a = span.attributes) != null ? _a : {};
4569
- const properties = {};
4570
- for (const key of keys) {
4571
- const existing = [key, `ai.telemetry.metadata.${key}`, `traceloop.association.properties.${key}`].find((name) => Object.prototype.hasOwnProperty.call(attrs, name));
4572
- if (existing) properties[key] = attrs[existing];
4573
- }
4574
- const source = { ...(_d = (_c = (_b = this.appGitSnapshot) == null ? void 0 : _b.call(this, properties)) != null ? _c : bound == null ? void 0 : bound.appGit) != null ? _d : {} };
4575
- if (Object.prototype.hasOwnProperty.call(properties, "raindrop.app.commit_sha") && properties["raindrop.app.commit_sha"] !== source["raindrop.app.commit_sha"]) {
4576
- delete source["raindrop.app.commit_dirty"];
4577
- delete source["raindrop.app.branch"];
4578
- }
4579
- const added = /* @__PURE__ */ new Map();
4580
- for (const key of keys) {
4581
- if ([key, `ai.telemetry.metadata.${key}`, `traceloop.association.properties.${key}`].some((name) => Object.prototype.hasOwnProperty.call(attrs, name))) continue;
4582
- const value = source == null ? void 0 : source[key];
4583
- if (typeof value === "string" || typeof value === "boolean") {
4584
- span.setAttribute(key, value);
4585
- added.set(key, value);
4586
- }
4587
- }
4588
- this.appGitAdded.set(span, added);
4589
- if (!bound) return;
4590
- stampSpan(span, bound.projectId, bound.authHint);
4591
- } catch (e) {
4592
- }
4593
- }
4594
- onEnd(span) {
4595
- var _a;
4596
- try {
4597
- if (span == null ? void 0 : span.attributes) {
4598
- const attrs = span.attributes;
4599
- const added = this.appGitAdded.get(span);
4600
- const shaKey = "raindrop.app.commit_sha";
4601
- const hasAlias = (key) => [`ai.telemetry.metadata.${key}`, `traceloop.association.properties.${key}`].some((name) => Object.prototype.hasOwnProperty.call(attrs, name));
4602
- const shaChanged = (added == null ? void 0 : added.has(shaKey)) && (attrs[shaKey] !== added.get(shaKey) || hasAlias(shaKey));
4603
- for (const [key, value] of added != null ? added : []) {
4604
- if (attrs[key] === value && (hasAlias(key) || shaChanged && key !== shaKey)) delete attrs[key];
4605
- }
4606
- }
4607
- if (((_a = span == null ? void 0 : span.status) == null ? void 0 : _a.code) !== SPAN_STATUS_ERROR) return;
4608
- markErrorSpanSeen(span);
4609
- } catch (e) {
4610
- }
4611
- }
4612
- async forceFlush() {
4613
- }
4614
- async shutdown() {
4615
- }
4616
- };
4617
- var GuardedSpanExporter = class {
4618
- constructor(inner, ownerAuthHint) {
4619
- this.droppedTotal = 0;
4620
- this.inner = inner;
4621
- this.ownerAuthHint = ownerAuthHint;
4622
- }
4623
- partition(spans) {
4624
- var _a;
4625
- const allowed = [];
4626
- let dropped = 0;
4627
- const requirePositive = foreignClientSeen();
4628
- for (const span of spans) {
4629
- const attrs = (_a = span.attributes) != null ? _a : {};
4630
- const hint = attrs[AUTH_HINT_SPAN_ATTRIBUTE];
4631
- const keep = requirePositive ? hint === this.ownerAuthHint : hint === void 0 || hint === this.ownerAuthHint;
4632
- if (keep) {
4633
- allowed.push(span);
4634
- } else {
4635
- dropped += 1;
4636
- }
4637
- }
4638
- return { allowed, dropped };
4639
- }
4640
- warnDropped(dropped) {
4641
- this.droppedTotal += dropped;
4642
- const total = this.droppedTotal;
4643
- rateLimitedLog(
4644
- "js-sdk.multi-project.dropped",
4645
- () => console.warn(
4646
- `[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.`
4647
- )
4648
- );
4649
- }
4650
- export(spans, resultCallback) {
4651
- let allowed;
4652
- let dropped;
4653
- try {
4654
- ({ allowed, dropped } = this.partition(spans));
4655
- } catch (e) {
4656
- if (foreignClientSeen()) {
4657
- this.warnDropped(spans.length);
4658
- resultCallback({ code: EXPORT_FAILED2 });
4659
- return;
4660
- }
4661
- this.inner.export(spans, resultCallback);
4662
- return;
4663
- }
4664
- if (dropped) {
4665
- this.warnDropped(dropped);
4666
- }
4667
- if (allowed.length === 0) {
4668
- resultCallback({ code: EXPORT_SUCCESS2 });
4669
- return;
4670
- }
4671
- this.inner.export(allowed, resultCallback);
4672
- }
4673
- shutdown() {
4674
- return this.inner.shutdown();
4675
- }
4676
- forceFlush() {
4677
- return this.inner.forceFlush ? this.inner.forceFlush() : Promise.resolve();
4678
- }
4679
- };
4680
- function buildGuardedExporter(baseUrl, headers, ownerAuthHint) {
4681
- const inner = new OTLPProtoTraceExporter2({
4682
- url: `${baseUrl}/v1/traces`,
4683
- headers
4684
- });
4685
- return new GuardedSpanExporter(inner, ownerAuthHint);
4686
- }
4687
- function pipelineOwnerHint() {
4688
- return getState().ownerAuthHint;
4689
- }
4690
- function claimPipeline(authHint, projectId) {
4691
- const state2 = getState();
4692
- if (state2.pipelineClaimed) {
4693
- return false;
4694
- }
4695
- state2.pipelineClaimed = true;
4696
- state2.ownerAuthHint = authHint;
4697
- state2.ownerProjectId = projectId;
4698
- if (state2.foreignClientSeen && state2.pendingMultiKeyWarning) {
4699
- emitMultiKeyWarningOnce();
4700
- }
4701
- return true;
4702
- }
4703
- function releasePipelineClaim() {
4704
- const state2 = getState();
4705
- state2.pipelineClaimed = false;
4706
- state2.ownerAuthHint = void 0;
4707
- state2.ownerProjectId = void 0;
4708
- }
4709
- function markTraceloopConfiguredWithoutClaim() {
4710
- getState().traceloopConfiguredWithoutClaim = true;
4711
- }
4712
- function traceloopConfiguredWithoutClaim() {
4713
- return getState().traceloopConfiguredWithoutClaim;
4714
- }
4715
-
4716
- // src/tracing/tracer-core.ts
4717
- import { SpanStatusCode as SpanStatusCode5, context as context6, trace as trace6 } from "@opentelemetry/api";
4718
- import { OTLPTraceExporter as OTLPHttpTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
4719
- import { AnthropicInstrumentation } from "@traceloop/instrumentation-anthropic";
4720
- import { BedrockInstrumentation } from "@traceloop/instrumentation-bedrock";
4721
- import { ChromaDBInstrumentation } from "@traceloop/instrumentation-chromadb";
4722
- import { CohereInstrumentation } from "@traceloop/instrumentation-cohere";
4723
- import { LangChainInstrumentation } from "@traceloop/instrumentation-langchain";
4724
- import { LlamaIndexInstrumentation } from "@traceloop/instrumentation-llamaindex";
4725
- import { OpenAIInstrumentation } from "@traceloop/instrumentation-openai";
4726
- import { PineconeInstrumentation } from "@traceloop/instrumentation-pinecone";
4727
- import { QdrantInstrumentation } from "@traceloop/instrumentation-qdrant";
4728
- import { TogetherInstrumentation } from "@traceloop/instrumentation-together";
4729
- import {
4730
- AIPlatformInstrumentation,
4731
- VertexAIInstrumentation
4732
- } from "@traceloop/instrumentation-vertexai";
4733
- import { WeakValueMap } from "weakref";
4734
-
4735
- // src/tracing/direct/context.ts
4736
- import { TraceFlags, context, isValidSpanId, isValidTraceId, trace } from "@opentelemetry/api";
4737
-
4738
- // src/tracing/direct/ids.ts
4739
- function getCrypto2() {
4740
- const c = globalThis.crypto;
4741
- return c;
4742
- }
4743
- function randomBytes2(length) {
4744
- const cryptoObj = getCrypto2();
4745
- const out = new Uint8Array(length);
4746
- if (cryptoObj && typeof cryptoObj.getRandomValues === "function") {
4747
- cryptoObj.getRandomValues(out);
4748
- return out;
4749
- }
4750
- for (let i = 0; i < out.length; i++) out[i] = Math.floor(Math.random() * 256);
4751
- return out;
4752
- }
4753
- function base64Encode2(bytes) {
4754
- const maybeBuffer = globalThis.Buffer;
4755
- if (maybeBuffer) {
4756
- return maybeBuffer.from(bytes).toString("base64");
4757
- }
4758
- let binary = "";
4759
- for (let i2 = 0; i2 < bytes.length; i2++) {
4760
- binary += String.fromCharCode(bytes[i2]);
4761
- }
4762
- const btoaFn = globalThis.btoa;
4763
- if (typeof btoaFn === "function") return btoaFn(binary);
4764
- const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
4765
- let out = "";
4766
- let i = 0;
4767
- while (i < binary.length) {
4768
- const c1 = binary.charCodeAt(i++) & 255;
4769
- const c2 = i < binary.length ? binary.charCodeAt(i++) & 255 : NaN;
4770
- const c3 = i < binary.length ? binary.charCodeAt(i++) & 255 : NaN;
4771
- const e1 = c1 >> 2;
4772
- const e2 = (c1 & 3) << 4 | (Number.isNaN(c2) ? 0 : c2 >> 4);
4773
- const e3 = Number.isNaN(c2) ? 64 : (c2 & 15) << 2 | (Number.isNaN(c3) ? 0 : c3 >> 6);
4774
- const e4 = Number.isNaN(c3) ? 64 : c3 & 63;
4775
- out += alphabet.charAt(e1);
4776
- out += alphabet.charAt(e2);
4777
- out += e3 === 64 ? "=" : alphabet.charAt(e3);
4778
- out += e4 === 64 ? "=" : alphabet.charAt(e4);
4779
- }
4780
- return out;
4781
- }
4782
- function base64ToHex2(base64) {
4783
- const maybeBuffer = globalThis.Buffer;
4784
- if (maybeBuffer) {
4785
- return maybeBuffer.from(base64, "base64").toString("hex");
4786
- }
4787
- const atobFn = globalThis.atob;
4788
- if (typeof atobFn === "function") {
4789
- const binary = atobFn(base64);
4790
- let hex = "";
4791
- for (let i = 0; i < binary.length; i++) {
4792
- hex += binary.charCodeAt(i).toString(16).padStart(2, "0");
4793
- }
4794
- return hex;
4795
- }
4796
- throw new Error("No base64 decoder available in this runtime");
4797
- }
4798
-
4799
- // src/tracing/direct/context.ts
4800
- var INVALID_TRACE_ID = "00000000000000000000000000000000";
4801
- var INVALID_SPAN_ID = "0000000000000000";
4802
- function hexToBase64(hex) {
4803
- const bytes = new Uint8Array(hex.length / 2);
4804
- for (let i = 0; i < hex.length; i += 2) {
4805
- bytes[i / 2] = parseInt(hex.substring(i, i + 2), 16);
4806
- }
4807
- return base64Encode2(bytes);
4808
- }
4809
- function getExplicitTraceContext(traceId, parentSpanId) {
4810
- if (!traceId || !parentSpanId || !isValidTraceId(traceId) || !isValidSpanId(parentSpanId)) {
4811
- return void 0;
4812
- }
4813
- return {
4814
- traceIdB64: hexToBase64(traceId),
4815
- parentSpanIdB64: hexToBase64(parentSpanId)
4816
- };
4817
- }
4818
- function getActiveTraceContext() {
4819
- const activeSpan = trace.getSpan(context.active());
4820
- if (!activeSpan) return {};
4821
- const spanContext = activeSpan.spanContext();
4822
- const traceIdHex = spanContext.traceId;
4823
- const spanIdHex = spanContext.spanId;
4824
- if (traceIdHex === INVALID_TRACE_ID) return {};
4825
- return {
4826
- traceIdB64: hexToBase64(traceIdHex),
4827
- parentSpanIdB64: spanIdHex !== INVALID_SPAN_ID ? hexToBase64(spanIdHex) : void 0
4828
- };
4829
- }
4830
- function savedParentContext(traceId, parentSpanId) {
4831
- if (!traceId || !parentSpanId || !isValidTraceId(traceId) || !isValidSpanId(parentSpanId)) {
4832
- return void 0;
4833
- }
4834
- return trace.setSpanContext(context.active(), {
4835
- traceId,
4836
- spanId: parentSpanId,
4837
- traceFlags: TraceFlags.SAMPLED,
4838
- isRemote: true
4839
- });
4840
- }
4841
-
4842
- // src/tracing/direct/http.ts
4843
- function formatEndpoint2(endpoint) {
4844
- if (!endpoint) return void 0;
4845
- return endpoint.endsWith("/") ? endpoint : `${endpoint}/`;
4846
- }
4847
-
4848
- // src/tracing/direct/otlp.ts
4849
- var libraryVersion = package_default.version;
4850
- var SERVICE_NAME = "raindrop-ai";
4851
- function attrString2(key, value) {
4852
- if (value === void 0) return void 0;
4853
- return { key, value: { stringValue: value } };
4854
- }
4855
- function attrInt2(key, value) {
4856
- if (value === void 0) return void 0;
4857
- if (!Number.isFinite(value)) return void 0;
4858
- return { key, value: { intValue: String(Math.trunc(value)) } };
4859
- }
4860
- function buildOtlpSpan2(args) {
4861
- const attrs = args.attributes.filter((x) => x !== void 0);
4862
- const span = {
4863
- traceId: args.ids.traceIdB64,
4864
- spanId: args.ids.spanIdB64,
4865
- name: args.name,
4866
- startTimeUnixNano: args.startTimeUnixNano,
4867
- endTimeUnixNano: args.endTimeUnixNano
4868
- };
4869
- if (args.ids.parentSpanIdB64) span.parentSpanId = args.ids.parentSpanIdB64;
4870
- if (attrs.length) span.attributes = attrs;
4871
- if (args.status) span.status = args.status;
4872
- return span;
4873
- }
4874
- function buildExportTraceServiceRequest2(spans) {
4875
- return {
4876
- resourceSpans: [
4877
- {
4878
- resource: {
4879
- attributes: [{ key: "service.name", value: { stringValue: SERVICE_NAME } }]
4880
- },
4881
- scopeSpans: [
4882
- {
4883
- scope: { name: SERVICE_NAME, version: libraryVersion },
4884
- spans
4885
- }
4886
- ]
4887
- }
4888
- ]
4889
- };
4890
- }
4891
-
4892
- // src/tracing/direct/shipper.ts
4893
- function serializeAssociationValue(value) {
4894
- return stringifyBounded(value);
4895
- }
4896
- var DirectTraceShipper = class {
4897
- constructor(opts) {
4898
- this.queue = [];
4899
- this.inFlight = /* @__PURE__ */ new Set();
4900
- /** Cuts off sends still running at a flush or shutdown deadline. */
4901
- this.cutOff = new InFlightCutOff();
4902
- /**
4903
- * Set once `shutdown()` begins and never cleared. Sends issued after the
4904
- * drain window (stragglers, or flush work the deadline abandoned
4905
- * mid-drain) run as a single short attempt instead of regaining the full
4906
- * retry schedule.
4907
- */
4908
- this.hasShutdown = false;
4909
- var _a, _b, _c, _d, _e, _f;
4910
- this.appGitSnapshot = opts.appGitSnapshot;
4911
- this.writeKey = opts.writeKey;
4912
- this.baseUrl = (_a = formatEndpoint2(opts.endpoint)) != null ? _a : "https://api.raindrop.ai/v1/";
4913
- this.enabled = (_b = opts.enabled) != null ? _b : true;
4914
- this.cloudEnabled = (_c = opts.cloudEnabled) != null ? _c : true;
4915
- this.debug = opts.debug;
4916
- this.projectId = opts.projectId;
4917
- this.redactTracePii = opts.redactTracePii;
4918
- this.remotePiiConfig = opts.remotePiiConfig;
4919
- this.spanPiiFields = opts.spanPiiFields;
4920
- this.mask = opts.mask;
4921
- this.flushIntervalMs = (_d = opts.flushIntervalMs) != null ? _d : 1e3;
4922
- this.maxBatchSize = (_e = opts.maxBatchSize) != null ? _e : 50;
4923
- this.maxQueueSize = (_f = opts.maxQueueSize) != null ? _f : 5e3;
4924
- this.flushTimeoutMs = resolveFlushTimeoutMs(opts.flushTimeoutMs);
4925
- const resolved = resolveLocalDebuggerBaseUrl(opts.localDebuggerUrl);
4926
- if (resolved && resolved !== this.baseUrl) {
4927
- this.localDebuggerUrl = resolved;
4928
- }
4929
- }
4930
- applicationGitSnapshot(properties) {
4931
- var _a, _b, _c, _d;
4932
- try {
4933
- return (_d = (_c = (_a = this.appGitSnapshot) == null ? void 0 : _a.call(this, properties)) != null ? _c : (_b = currentRoutingBinding()) == null ? void 0 : _b.appGit) != null ? _d : {};
4934
- } catch (e) {
4935
- return {};
4936
- }
4937
- }
4938
- /**
4939
- * Build and enqueue an OTLP span for a trackTool call.
4940
- *
4941
- * Reads the active OTEL context if traceId/parentSpanId are not provided,
4942
- * so spans still appear as children in the trace tree.
4943
- */
4944
- sendSpan(params) {
4945
- var _a, _b, _c;
4946
- if (!this.enabled) return;
4947
- let traceIdB64 = params.traceId;
4948
- let parentSpanIdB64 = params.parentSpanId;
4949
- if (!traceIdB64) {
4950
- const activeCtx = getActiveTraceContext();
4951
- traceIdB64 = activeCtx.traceIdB64;
4952
- parentSpanIdB64 = activeCtx.parentSpanIdB64;
4953
- }
4954
- const spanIdB64 = (_a = params.spanId) != null ? _a : base64Encode2(randomBytes2(8));
4955
- if (!traceIdB64) {
4956
- traceIdB64 = base64Encode2(randomBytes2(16));
4957
- }
4958
- const startTimeUnixNano = String(params.startTimeMs * 1e6);
4959
- const endTimeUnixNano = String(params.endTimeMs * 1e6);
4960
- const attributes = [
4961
- // Required: passes hasAIOperation() filter in backend (parseSpan.ts)
4962
- attrString2("traceloop.span.kind", (_b = params.spanKind) != null ? _b : "tool"),
4963
- // Parsed by backend for input/output payloads
4964
- attrString2("traceloop.entity.input", params.input),
4965
- attrString2("traceloop.entity.output", params.output),
4966
- // Duration tracking
4967
- attrInt2("traceloop.entity.duration_ms", params.durationMs),
4968
- // Per-span project routing: the ingest boundary routes on this attribute
4969
- // (org-validated) and falls back to the request's project header. Direct
4970
- // spans ship on this instance's own key, so no cross-key auth hint.
4971
- attrString2(PROJECT_ID_SPAN_ATTRIBUTE, this.projectId)
4972
- ];
4973
- for (const [key, value] of Object.entries(params.properties)) {
4974
- if (value === void 0) {
4975
- continue;
4976
- }
4977
- attributes.push(
4978
- attrString2(`traceloop.association.properties.${key}`, serializeAssociationValue(value))
4979
- );
4980
- }
4981
- const spanIdentity = { spanIdB64 };
4982
- claimSpanForFrames(spanIdentity);
4983
- for (const [key, value] of Object.entries({
4984
- ...currentSpanAttributes(),
4985
- ...params.attributes,
4986
- // Last, so neither a bound frame nor an explicit caller attribute can
4987
- // shadow the replay row a span belongs to.
4988
- ...evalScopeAttributes()
4989
- })) {
4990
- attributes.push(attrString2(key, value));
4991
- }
4992
- attributes.push(...(_c = params.otlpAttributes) != null ? _c : []);
4993
- let status;
4994
- if (params.error) {
4995
- status = { code: 2, message: params.error };
4996
- markErrorSpanSeen(spanIdentity);
4997
- } else {
4998
- status = {
4999
- code: 1
5000
- /* STATUS_CODE_OK */
5001
- };
5002
- }
5003
- const span = buildOtlpSpan2({
5004
- ids: {
5005
- traceIdB64,
5006
- spanIdB64,
5007
- parentSpanIdB64
5008
- },
5009
- name: params.name,
5010
- startTimeUnixNano,
5011
- endTimeUnixNano,
5012
- attributes: withAppGitAttributes(
5013
- attributes,
5014
- params.appGitSnapshot !== void 0 ? params.appGitSnapshot : this.applicationGitSnapshot(params.properties)
5015
- ),
5016
- status
5017
- });
5018
- const replayDestination = currentReplayTraceDestination();
5019
- recordReplayExportedSpan(
5020
- replayDestination,
5021
- base64ToHex2(span.spanId),
5022
- base64ToHex2(span.traceId)
5023
- );
5024
- const mirrorUrl = (replayDestination == null ? void 0 : replayDestination.kind) === "workshop" ? replayDestination.url : replayDestination ? void 0 : this.localDebuggerUrl;
5025
- const mirrored = mirrorUrl && this.redactsNow() ? this.redactSpanPii(span) : span;
5026
- if (mirrorUrl && mirrored) {
5027
- const body = buildExportTraceServiceRequest2([maskOtlpSpan(mirrored, this.mask, this.spanPiiFields, "[raindrop]")]);
5028
- const mirror = mirrorTraceExportToLocalDebugger(body, {
5029
- baseUrl: mirrorUrl,
5030
- debug: false,
5031
- sdkName: "js-sdk"
5032
- });
5033
- this.inFlight.add(mirror);
5034
- void mirror.finally(() => this.inFlight.delete(mirror));
5035
- }
5036
- this.enqueue({ span, replayDestination });
5037
- if (this.debug) {
5038
- console.log(`[raindrop] direct shipper: enqueued span "${params.name}"`);
5039
- }
5040
- }
5041
- /**
5042
- * Whether to redact, never waiting: a local mirror uses what is known now,
5043
- * and a remote setting still being looked up counts as unknown.
5044
- */
5045
- redactsNow() {
5046
- var _a;
5047
- const writeKey = this.cloudEnabled ? this.writeKey : void 0;
5048
- return (_a = piiRedactionNow(this.redactTracePii, this.remotePiiConfig, this.baseUrl, writeKey)) != null ? _a : resolvePiiRedaction(this.redactTracePii, this.remotePiiConfig, "unknown");
5049
- }
5050
- /** The span with PII redacted from its input and output; undefined if redaction failed. */
5051
- redactSpanPii(span) {
5052
- try {
5053
- return redactPiiInOtlpSpan(span, this.spanPiiFields, resolveMaxTextFieldChars(void 0));
5054
- } catch (e) {
5055
- return void 0;
5056
- }
5057
- }
5058
- sendToolSpan(params) {
5059
- this.sendSpan({
5060
- ...params,
5061
- spanKind: "tool"
5062
- });
5063
- }
5064
- enqueue(queued) {
5065
- if (!this.enabled) return;
5066
- if (this.queue.length >= this.maxQueueSize) {
5067
- this.queue.shift();
5068
- }
5069
- this.queue.push(queued);
5070
- if (this.queue.length >= this.maxBatchSize) {
5071
- void this.drain().catch(() => {
5072
- });
5073
- return;
5074
- }
5075
- this.scheduleDrain(this.flushIntervalMs);
5076
- }
5077
- scheduleDrain(delayMs) {
5078
- if (this.timer) return;
5079
- this.timer = setTimeout(() => {
5080
- this.timer = void 0;
5081
- void this.drain().catch(() => {
5082
- });
5083
- }, delayMs);
5084
- }
5085
- /**
5086
- * Send every queued span within `flushTimeoutMs` (CONTRACT 1.2.1). Resolves,
5087
- * never rejects; spans not yet sent at the deadline stay queued.
5088
- */
5089
- async flush() {
5090
- const result = await this.drainWithin(Date.now() + this.flushTimeoutMs);
5091
- if (!result.delivered && this.shutdownDeadlineAt === void 0) {
5092
- rateLimitedLog(
5093
- "js-sdk.direct.flush_undelivered",
5094
- () => console.warn(`[raindrop] direct: ${describeUndelivered("flush()", result)}`)
5095
- );
5096
- }
5097
- return asCompat(result);
5098
- }
5099
- async drainWithin(deadlineAt) {
5100
- const earlier = [...this.inFlight];
5101
- const fates = this.enabled ? await this.drain(deadlineAt) : [];
5102
- const { settled, stillRunning } = await awaitEarlierSends(
5103
- earlier,
5104
- deadlineAt,
5105
- this.cutOff,
5106
- (p) => this.inFlight.has(p)
5107
- );
5108
- return summarize2(fates, stillRunning, !settled);
5109
- }
5110
- async drain(deadlineAt) {
5111
- var _a, _b;
5112
- const fates = [];
5113
- if (!this.enabled) return fates;
5114
- if (this.timer) {
5115
- clearTimeout(this.timer);
5116
- this.timer = void 0;
5117
- }
5118
- if (this.queue.length === 0) return fates;
5119
- const writeKey = this.cloudEnabled ? this.writeKey : void 0;
5120
- const redactPii = (_a = piiRedactionNow(this.redactTracePii, this.remotePiiConfig, this.baseUrl, writeKey)) != null ? _a : await piiRedaction(
5121
- this.redactTracePii,
5122
- this.remotePiiConfig,
5123
- this.baseUrl,
5124
- writeKey,
5125
- deadlineAt
5126
- );
5127
- while (this.queue.length > 0) {
5128
- const batch = this.queue.splice(0, this.maxBatchSize);
5129
- const opts = this.requestOpts(deadlineAt);
5130
- if (!opts) {
5131
- rateLimitedLog(
5132
- "js-sdk.direct.shutdown_deadline",
5133
- () => console.warn(
5134
- `[raindrop] direct: shutdown flush deadline exceeded; dropping ${batch.length} spans`
5135
- )
5136
- );
5137
- fates.push("dropped");
5138
- continue;
5139
- }
5140
- const groups = /* @__PURE__ */ new Map();
5141
- for (const queued of batch) {
5142
- const spans = groups.get(queued.replayDestination);
5143
- if (spans) spans.push(queued);
5144
- else groups.set(queued.replayDestination, [queued]);
5145
- }
5146
- const requeue = [];
5147
- let retryAtMs;
5148
- for (const [replayDestination, queuedSpans] of groups) {
5149
- if (!replayDestination && !this.cloudEnabled) continue;
5150
- if ((replayDestination == null ? void 0 : replayDestination.kind) === "workshop") continue;
5151
- const spans = queuedSpans.map((q) => q.span);
5152
- const outgoing = (redactPii ? spans.flatMap((span) => {
5153
- var _a2;
5154
- return (_a2 = this.redactSpanPii(span)) != null ? _a2 : [];
5155
- }) : spans).map((span) => maskOtlpSpan(span, this.mask, this.spanPiiFields, "[raindrop]"));
5156
- if (outgoing.length === 0) continue;
5157
- const body = buildExportTraceServiceRequest2(outgoing);
5158
- const url = replayDestination ? replayTraceUrl(replayDestination.url) : `${this.baseUrl}traces`;
5159
- const headers = replayDestination ? {
5160
- Authorization: `Bearer ${replayDestination.apiKey}`,
5161
- "X-Raindrop-Replay-Id": replayDestination.replayId,
5162
- "X-Raindrop-Project-Id": (_b = replayDestination.projectId) != null ? _b : "default"
5163
- } : { Authorization: `Bearer ${this.writeKey}`, ...projectIdHeaders(this.projectId) };
5164
- const sending = sendJson(url, body, headers, opts);
5165
- const tracked = sending.then(() => void 0);
5166
- this.inFlight.add(tracked);
5167
- let outcome;
5168
- try {
5169
- outcome = await sending;
5170
- } finally {
5171
- this.inFlight.delete(tracked);
5172
- }
5173
- const fate = fateOf(outcome, this.shutdownDeadlineAt !== void 0 || this.hasShutdown);
5174
- fates.push(fate);
5175
- if (fate === "queued") {
5176
- requeue.push(...queuedSpans);
5177
- if (outcome.status === "deferred" && outcome.retryAtMs !== void 0) {
5178
- retryAtMs = Math.max(retryAtMs != null ? retryAtMs : 0, outcome.retryAtMs);
5179
- }
5180
- } else if (fate === "dropped") {
5181
- 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;
5182
- rateLimitedLog(
5183
- "js-sdk.direct.send_failed",
5184
- () => console.warn(
5185
- `[raindrop] direct: failed to send ${queuedSpans.length} spans (dropping): ${reason}`
5186
- )
5187
- );
5188
- } else if (this.debug) {
5189
- console.log(`[raindrop] direct: sent ${queuedSpans.length} spans`);
5190
- }
5191
- }
5192
- if (requeue.length > 0) {
5193
- this.queue.unshift(...requeue);
5194
- if (this.queue.length > this.maxQueueSize) this.queue.splice(this.maxQueueSize);
5195
- this.scheduleDrain(Math.max(this.flushIntervalMs, (retryAtMs != null ? retryAtMs : 0) - Date.now()));
5196
- break;
5197
- }
5198
- }
5199
- return fates;
5200
- }
5201
- /**
5202
- * Retry/timeout options for one batch POST: the normal 3-attempt schedule,
5203
- * bounded by a flush deadline when given; during shutdown, retries within
5204
- * the shutdown window; `null` once the window is spent (caller drops the
5205
- * batch). After shutdown() returns, stragglers run as a single short attempt.
5206
- */
5207
- requestOpts(deadlineAt) {
5208
- const opts = this.scheduleFor(deadlineAt);
5209
- return opts && { ...opts, cutOff: this.cutOff.signal };
5210
- }
5211
- scheduleFor(deadlineAt) {
5212
- if (this.shutdownDeadlineAt !== void 0) {
5213
- if (this.shutdownDeadlineAt - Date.now() <= 0) return null;
5214
- return {
5215
- maxAttempts: 3,
5216
- debug: this.debug,
5217
- deadlineAt: Math.min(this.shutdownDeadlineAt, deadlineAt != null ? deadlineAt : Infinity)
5218
- };
5219
- }
5220
- if (this.hasShutdown) {
5221
- return { maxAttempts: 1, debug: this.debug, timeoutMs: POST_SHUTDOWN_TIMEOUT_MS };
5222
- }
5223
- return { maxAttempts: 3, debug: this.debug, deadlineAt };
5224
- }
5225
- /** Flush within `flushTimeoutMs` and stop; spans left at the deadline are dropped. */
5226
- async shutdown() {
5227
- this.hasShutdown = true;
5228
- const deadlineAt = Date.now() + this.flushTimeoutMs;
5229
- this.shutdownDeadlineAt = deadlineAt;
5230
- let result = { ...DELIVERED };
5231
- try {
5232
- if (this.timer) {
5233
- clearTimeout(this.timer);
5234
- this.timer = void 0;
5235
- }
5236
- result = await this.drainWithin(deadlineAt);
5237
- if (!result.delivered) {
5238
- rateLimitedLog(
5239
- "js-sdk.direct.shutdown_deadline",
5240
- () => console.warn(`[raindrop] direct: ${describeUndelivered("shutdown()", result)}`)
5241
- );
5242
- }
5243
- } finally {
5244
- this.shutdownDeadlineAt = void 0;
5245
- }
5246
- return asCompat(result);
5247
- }
5248
- };
5249
-
5250
- // src/tracing/otel-core/index.ts
5251
- import {
5252
- DiagConsoleLogger,
5253
- DiagLogLevel,
5254
- context as context2,
5255
- diag,
5256
- trace as trace2
5257
- } from "@opentelemetry/api";
5258
- import { suppressTracing } from "@opentelemetry/core";
5259
- import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
5260
- import { registerInstrumentations } from "@opentelemetry/instrumentation";
5261
- import * as resourceModule from "@opentelemetry/resources";
5262
- import {
5263
- BatchSpanProcessor,
5264
- SimpleSpanProcessor
5265
- } from "@opentelemetry/sdk-trace-base";
5266
- import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node";
5267
- import {
5268
- CONTEXT_KEY_ALLOW_TRACE_CONTENT,
5269
- SpanAttributes,
5270
- TraceloopSpanKindValues
5271
- } from "@traceloop/ai-semantic-conventions";
5272
- var ALL_INSTRUMENTATION_LIBRARIES = "all";
5273
- function redactSpanPii(span, fields) {
5274
- const attributes = redactPiiInAttributeMap(span.attributes, fields);
5275
- const message = span.status.message;
5276
- const redactedMessage = message === void 0 ? void 0 : redactSpanContent(message);
5277
- let eventsChanged = false;
5278
- const events = span.events.map((event) => {
5279
- const eventAttributes = event.attributes && redactPiiInAttributeMap(event.attributes, fields);
5280
- if (!eventAttributes) return event;
5281
- eventsChanged = true;
5282
- return { ...event, attributes: eventAttributes };
5283
- });
5284
- if (!attributes && redactedMessage === message && !eventsChanged) return span;
5285
- const view = Object.create(span);
5286
- if (attributes) {
5287
- Object.defineProperty(view, "attributes", { value: attributes, enumerable: true });
5288
- }
5289
- if (redactedMessage !== message) {
5290
- Object.defineProperty(view, "status", {
5291
- value: { ...span.status, message: redactedMessage },
5292
- enumerable: true
5293
- });
5294
- }
5295
- if (eventsChanged) {
5296
- Object.defineProperty(view, "events", { value: events, enumerable: true });
5297
- }
5298
- copyReplayTraceDestination(span, view);
5299
- return view;
5300
- }
5301
- function maskSpan(span, mask, fields) {
5302
- const attributes = maskAttributeMap(span.attributes, mask, fields, "[raindrop]");
5303
- const message = span.status.message;
5304
- const nextMessage = message === void 0 ? void 0 : maskSpanStatusMessage(message, mask, "[raindrop]");
5305
- let eventsChanged = false;
5306
- const events = span.events.map((event) => {
5307
- const eventAttributes = event.attributes && maskAttributeMap(event.attributes, mask, fields, "[raindrop]");
5308
- if (!eventAttributes) return event;
5309
- eventsChanged = true;
5310
- return { ...event, attributes: eventAttributes };
5311
- });
5312
- if (!attributes && nextMessage === message && !eventsChanged) return span;
5313
- const view = Object.create(span);
5314
- if (attributes) {
5315
- Object.defineProperty(view, "attributes", { value: attributes, enumerable: true });
5316
- }
5317
- if (nextMessage !== message) {
5318
- Object.defineProperty(view, "status", {
5319
- value: { ...span.status, message: nextMessage },
5320
- enumerable: true
5321
- });
5322
- }
5323
- if (eventsChanged) {
5324
- Object.defineProperty(view, "events", { value: events, enumerable: true });
5325
- }
5326
- copyReplayTraceDestination(span, view);
5327
- return view;
5328
- }
5329
- var PiiRedactingSpanExporter = class {
5330
- constructor(inner, options) {
5331
- this.inner = inner;
5332
- this.options = options;
5333
- /** Exports waiting for the org lookup; flush and shutdown wait for them. */
5334
- this.pending = /* @__PURE__ */ new Set();
5335
- }
5336
- export(spans, resultCallback) {
5337
- const { local, remote, apiUrl, writeKey, spanFields, mask } = this.options;
5338
- const exportContext = context2.active();
5339
- const run = (redact) => {
5340
- let outgoing = spans;
5341
- if (redact) {
5342
- outgoing = [];
5343
- for (const span of spans) {
5344
- try {
5345
- outgoing.push(redactSpanPii(span, spanFields));
5346
- } catch (e) {
5347
- }
5348
- }
5349
- }
5350
- if (mask) outgoing = outgoing.map((span) => maskSpan(span, mask, spanFields));
5351
- try {
5352
- context2.with(exportContext, () => this.inner.export(outgoing, resultCallback));
5353
- } catch (e) {
5354
- resultCallback({ code: 1 });
5355
- }
5356
- };
5357
- const sharedRequest = localTracePiiRedactionRequested(apiUrl, writeKey);
5358
- const known = sharedRequest || piiRedactionNow(local, remote, apiUrl, writeKey);
5359
- if (known !== void 0) {
5360
- run(known);
5361
- return;
5362
- }
5363
- const handedOff = piiRedaction(local, remote, apiUrl, writeKey).then(
5364
- (redact) => new Promise((resolve2) => {
5365
- const callback = resultCallback;
5366
- resultCallback = (result) => {
5367
- resolve2();
5368
- callback(result);
5369
- };
5370
- run(redact || localTracePiiRedactionRequested(apiUrl, writeKey));
5371
- })
5372
- );
5373
- this.pending.add(handedOff);
5374
- void handedOff.finally(() => this.pending.delete(handedOff));
5375
- }
5376
- async drainPending() {
5377
- if (this.pending.size > 0) await Promise.allSettled([...this.pending]);
5378
- }
5379
- async shutdown() {
5380
- await this.drainPending();
5381
- return this.inner.shutdown();
5382
- }
5383
- async forceFlush() {
5384
- var _a, _b, _c;
5385
- await this.drainPending();
5386
- return (_c = (_b = (_a = this.inner).forceFlush) == null ? void 0 : _b.call(_a)) != null ? _c : Promise.resolve();
5387
- }
5388
- };
5389
- var TRACER_NAME = "@traceloop/node-server-sdk";
5390
- var WORKFLOW_NAME_KEY = /* @__PURE__ */ Symbol.for("raindrop.otelCore.workflowName");
5391
- var ENTITY_NAME_KEY = /* @__PURE__ */ Symbol.for("raindrop.otelCore.entityName");
5392
- var ASSOCIATION_PROPERTIES_KEY = /* @__PURE__ */ Symbol.for("raindrop.otelCore.associationProperties");
5393
- var INSTRUMENTATION_LIBRARIES = [
5394
- "ai",
5395
- "@traceloop/node-server-sdk",
5396
- "@traceloop/instrumentation-openai",
5397
- "@traceloop/instrumentation-langchain",
5398
- "@traceloop/instrumentation-chroma",
5399
- "@traceloop/instrumentation-chromadb",
5400
- "@traceloop/instrumentation-anthropic",
5401
- "@traceloop/instrumentation-llamaindex",
5402
- "@traceloop/instrumentation-vertexai",
5403
- "@traceloop/instrumentation-bedrock",
5404
- "@traceloop/instrumentation-cohere",
5405
- "@traceloop/instrumentation-pinecone",
5406
- "@traceloop/instrumentation-qdrant",
5407
- "@traceloop/instrumentation-together",
5408
- TRACER_NAME,
5409
- "traceloop.tracer"
5410
- ];
5411
- var AI_GENERATE_TEXT = "ai.generateText.doGenerate";
5412
- var AI_STREAM_TEXT = "ai.streamText.doStream";
5413
- var AI_RESPONSE_TEXT = "ai.response.text";
5414
- var AI_PROMPT_MESSAGES = "ai.prompt.messages";
5415
- var AI_PROMPT_TOKENS = "ai.usage.promptTokens";
5416
- var AI_COMPLETION_TOKENS = "ai.usage.completionTokens";
5417
- var AI_MODEL_PROVIDER = "ai.model.provider";
5418
- var STATE_KEY4 = /* @__PURE__ */ Symbol.for("raindrop.otelCore.state");
5419
- function getState2() {
5420
- var _a;
5421
- const holder = globalThis;
5422
- (_a = holder[STATE_KEY4]) != null ? _a : holder[STATE_KEY4] = {};
5423
- return holder[STATE_KEY4];
5424
- }
5425
- function parseHeaders(value) {
5426
- const headers = {};
5427
- if (!value) return headers;
5428
- for (const pair of value.split(",")) {
5429
- const separator = pair.indexOf("=");
5430
- if (separator <= 0) continue;
5431
- try {
5432
- const key = decodeURIComponent(pair.slice(0, separator).trim());
5433
- const val = decodeURIComponent(pair.slice(separator + 1).trim());
5434
- if (key && val) headers[key] = val;
5435
- } catch (e) {
5436
- }
5437
- }
5438
- return headers;
5439
- }
5440
- function safeStringify(value) {
5441
- try {
5442
- const result = JSON.stringify(value);
5443
- return result === void 0 ? String(value) : result;
5444
- } catch (e) {
5445
- return "[unserializable]";
5446
- }
5447
- }
5448
- function createResource(attributes) {
5449
- if ("resourceFromAttributes" in resourceModule) {
5450
- const factory = resourceModule.resourceFromAttributes;
5451
- if (typeof factory === "function") return factory(attributes);
5452
- }
5453
- return new resourceModule.Resource(attributes);
5454
- }
5455
- function detectRuntimeResource() {
5456
- try {
5457
- if ("detectResourcesSync" in resourceModule && typeof resourceModule.detectResourcesSync === "function" && "envDetectorSync" in resourceModule) {
5458
- return resourceModule.detectResourcesSync({
5459
- detectors: [
5460
- resourceModule.envDetectorSync,
5461
- resourceModule.processDetectorSync,
5462
- resourceModule.hostDetectorSync
5463
- ]
5464
- });
5465
- }
5466
- if ("detectResources" in resourceModule && typeof resourceModule.detectResources === "function" && "envDetector" in resourceModule) {
5467
- const detected = resourceModule.detectResources({
5468
- detectors: [
5469
- resourceModule.envDetector,
5470
- resourceModule.processDetector,
5471
- resourceModule.hostDetector
5472
- ]
5473
- });
5474
- if (!(detected instanceof Promise)) {
5475
- return detected;
5476
- }
5477
- }
5478
- } catch (e) {
5479
- }
5480
- return void 0;
5481
- }
5482
- function logLevel(level) {
5483
- switch (level) {
5484
- case "debug":
5485
- return DiagLogLevel.DEBUG;
5486
- case "info":
5487
- return DiagLogLevel.INFO;
5488
- case "warn":
5489
- return DiagLogLevel.WARN;
5490
- default:
5491
- return DiagLogLevel.ERROR;
5492
- }
5493
- }
5494
- function transformAiSdkSpan(span) {
5495
- const names = {
5496
- [AI_GENERATE_TEXT]: "ai.generateText.generate",
5497
- [AI_STREAM_TEXT]: "ai.streamText.stream"
5498
- };
5499
- if (!(span.name in names)) return span;
5500
- const attributes = span.attributes;
5501
- if (AI_RESPONSE_TEXT in attributes) {
5502
- const response = attributes[AI_RESPONSE_TEXT];
5503
- if (typeof response === "string") {
5504
- attributes[`${SpanAttributes.LLM_COMPLETIONS}.0.content`] = response;
5505
- }
5506
- attributes[`${SpanAttributes.LLM_COMPLETIONS}.0.role`] = "assistant";
5507
- delete attributes[AI_RESPONSE_TEXT];
5508
- }
5509
- if (AI_PROMPT_MESSAGES in attributes) {
5510
- try {
5511
- const parsed = JSON.parse(String(attributes[AI_PROMPT_MESSAGES]));
5512
- if (Array.isArray(parsed)) {
5513
- parsed.forEach((message, index) => {
5514
- if (!message || typeof message !== "object") return;
5515
- const content = "content" in message ? message.content : void 0;
5516
- const role = "role" in message ? message.role : void 0;
5517
- attributes[`${SpanAttributes.LLM_PROMPTS}.${index}.content`] = typeof content === "string" ? content : safeStringify(content);
5518
- if (typeof role === "string") {
5519
- attributes[`${SpanAttributes.LLM_PROMPTS}.${index}.role`] = role;
5520
- }
5521
- });
5522
- }
5523
- delete attributes[AI_PROMPT_MESSAGES];
5524
- } catch (e) {
5525
- }
5526
- }
5527
- if (AI_PROMPT_TOKENS in attributes) {
5528
- attributes[SpanAttributes.LLM_USAGE_PROMPT_TOKENS] = Number(attributes[AI_PROMPT_TOKENS]);
5529
- delete attributes[AI_PROMPT_TOKENS];
5530
- }
5531
- if (AI_COMPLETION_TOKENS in attributes) {
5532
- attributes[SpanAttributes.LLM_USAGE_COMPLETION_TOKENS] = Number(
5533
- attributes[AI_COMPLETION_TOKENS]
5534
- );
5535
- delete attributes[AI_COMPLETION_TOKENS];
5536
- }
5537
- const prompt = attributes[SpanAttributes.LLM_USAGE_PROMPT_TOKENS];
5538
- const completion = attributes[SpanAttributes.LLM_USAGE_COMPLETION_TOKENS];
5539
- if (prompt !== void 0 && completion !== void 0) {
5540
- attributes[SpanAttributes.LLM_USAGE_TOTAL_TOKENS] = Number(prompt) + Number(completion);
5541
- }
5542
- if (AI_MODEL_PROVIDER in attributes) {
5543
- const vendor = String(attributes[AI_MODEL_PROVIDER]);
5544
- attributes[SpanAttributes.LLM_SYSTEM] = vendor.startsWith("openai") ? "OpenAI" : vendor;
5545
- delete attributes[AI_MODEL_PROVIDER];
5546
- }
5547
- Object.defineProperty(span, "name", {
5548
- configurable: true,
5549
- value: names[span.name],
5550
- writable: true
5551
- });
5552
- return span;
5553
- }
5554
- function scopeName(span) {
5555
- var _a;
5556
- if ("instrumentationScope" in span) {
5557
- const scope = span.instrumentationScope;
5558
- if (scope && typeof scope === "object" && "name" in scope && typeof scope.name === "string") {
5559
- return scope.name;
5560
- }
5561
- }
5562
- return (_a = span.instrumentationLibrary) == null ? void 0 : _a.name;
5563
- }
5564
- function contentCaptureDisabled(options) {
5565
- return options.traceContent === false || (process.env.TRACELOOP_TRACE_CONTENT || "true").toLowerCase() === "false";
5566
- }
5567
- function shouldSendTraceContent() {
5568
- var _a;
5569
- const contextual = context2.active().getValue(CONTEXT_KEY_ALLOW_TRACE_CONTENT);
5570
- if (typeof contextual === "boolean") return contextual;
5571
- if (((_a = getState2().configuration) == null ? void 0 : _a.traceContent) === false) return false;
5572
- return (process.env.TRACELOOP_TRACE_CONTENT || "true").toLowerCase() !== "false";
5573
- }
5574
- function enrichStart(span) {
5575
- const active = context2.active();
5576
- const workflow = active.getValue(WORKFLOW_NAME_KEY);
5577
- if (typeof workflow === "string")
5578
- span.setAttribute(SpanAttributes.TRACELOOP_WORKFLOW_NAME, workflow);
5579
- const entity = active.getValue(ENTITY_NAME_KEY);
5580
- if (typeof entity === "string") span.setAttribute(SpanAttributes.TRACELOOP_ENTITY_PATH, entity);
5581
- const properties = active.getValue(ASSOCIATION_PROPERTIES_KEY);
5582
- if (properties && typeof properties === "object") {
5583
- for (const [key, value] of Object.entries(properties)) {
5584
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
5585
- span.setAttribute(`${SpanAttributes.TRACELOOP_ASSOCIATION_PROPERTIES}.${key}`, value);
5586
- }
5587
- }
5588
- }
5589
- }
5590
- var PROMPT_TOOLS_OVERRIDE_MARKER = "raindrop.prompt_tools.override";
5591
- var MODEL_SPAN_ATTRIBUTES = ["llm.request.type", "gen_ai.request.model", "ai.model.id"];
5592
- function isModelSpan(attributes) {
5593
- return MODEL_SPAN_ATTRIBUTES.some((key) => attributes[key] !== void 0);
5594
- }
5595
- function applyPromptTools(span) {
5596
- var _a;
5597
- const attributes = span.attributes;
5598
- const marker = attributes[PROMPT_TOOLS_OVERRIDE_MARKER];
5599
- if (marker !== void 0) {
5600
- delete attributes[PROMPT_TOOLS_OVERRIDE_MARKER];
5601
- if (!isModelSpan(attributes) || !shouldSendTraceContent()) return;
5602
- let parsed;
5603
- try {
5604
- parsed = JSON.parse(String(marker));
5605
- } catch (e) {
5606
- return;
5607
- }
5608
- const tools = (_a = normalizeToolDeclarations(parsed)) != null ? _a : [];
5609
- attributes[PROMPT_TOOLS_ATTRIBUTE] = promptToolsAttributeValue(tools);
5610
- return;
5611
- }
5612
- if (attributes[PROMPT_TOOLS_ATTRIBUTE] !== void 0) return;
5613
- if (!shouldSendTraceContent()) return;
5614
- const inferred = promptToolsFromTraceloopAttributes(attributes);
5615
- if (inferred === void 0) return;
5616
- attributes[PROMPT_TOOLS_ATTRIBUTE] = promptToolsAttributeValue(inferred);
5617
- }
5618
- function createSpanProcessor(options) {
5619
- var _a, _b;
5620
- const baseUrl = options.baseUrl || process.env.TRACELOOP_BASE_URL || "https://api.traceloop.com";
5621
- const apiKey = options.apiKey || process.env.TRACELOOP_API_KEY;
5622
- const resolvedHeaders = (_a = options.headers) != null ? _a : process.env.TRACELOOP_HEADERS ? parseHeaders(process.env.TRACELOOP_HEADERS) : { Authorization: `Bearer ${apiKey}` };
5623
- const baseExporter = (_b = options.exporter) != null ? _b : new OTLPTraceExporter({ url: `${baseUrl}/v1/traces`, headers: resolvedHeaders });
5624
- const routed = options.routeReplayTraces ? new ReplayRoutingSpanExporter(baseExporter) : baseExporter;
5625
- const exporter = options.piiRedaction ? new PiiRedactingSpanExporter(routed, options.piiRedaction) : routed;
5626
- const processor = options.disableBatch ? new SimpleSpanProcessor(exporter) : new BatchSpanProcessor(exporter);
5627
- const originalOnStart = processor.onStart.bind(processor);
5628
- const originalOnEnd = processor.onEnd.bind(processor);
5629
- processor.onStart = (span, parentContext) => {
5630
- try {
5631
- enrichStart(span);
5632
- originalOnStart(span, parentContext);
5633
- } catch (e) {
5634
- }
5635
- };
5636
- processor.onEnd = (span) => {
5637
- var _a2;
5638
- let outgoing = span;
5639
- try {
5640
- const allowed = options.allowedInstrumentationLibraries;
5641
- if (allowed !== ALL_INSTRUMENTATION_LIBRARIES && ![...INSTRUMENTATION_LIBRARIES, ...allowed != null ? allowed : []].includes((_a2 = scopeName(span)) != null ? _a2 : "")) {
5642
- return;
5643
- }
5644
- applyPromptTools(span);
5645
- outgoing = transformAiSdkSpan(span);
5646
- if (outgoing !== span) copyReplayTraceDestination(span, outgoing);
5647
- } catch (e) {
5648
- }
5649
- try {
5650
- originalOnEnd(outgoing);
5651
- } catch (e) {
5652
- }
5653
- };
5654
- return processor;
5655
- }
5656
- function initialize(options = {}) {
5657
- var _a;
5658
- const state2 = getState2();
5659
- if (state2.configuration) return;
5660
- state2.configuration = Object.freeze({ ...options });
5661
- if (options.logLevel) diag.setLogger(new DiagConsoleLogger(), logLevel(options.logLevel));
5662
- if (options.tracingEnabled === false) return;
5663
- const baseUrl = options.baseUrl || process.env.TRACELOOP_BASE_URL || "https://api.traceloop.com";
5664
- state2.defaultProcessor = createSpanProcessor({
5665
- ...options,
5666
- baseUrl,
5667
- allowedInstrumentationLibraries: ALL_INSTRUMENTATION_LIBRARIES
5668
- });
5669
- const serviceResource = createResource({
5670
- "service.name": options.appName || process.env.npm_package_name || "unknown_service"
5671
- });
5672
- const detectedResource = detectRuntimeResource();
5673
- state2.provider = new NodeTracerProvider({
5674
- // Detected attributes win over the configured resource, matching
5675
- // sdk-node's `this._resource.merge(detectResourcesSync(...))` so
5676
- // OTEL_SERVICE_NAME / OTEL_RESOURCE_ATTRIBUTES can still override appName.
5677
- resource: detectedResource ? serviceResource.merge(detectedResource) : serviceResource,
5678
- spanProcessors: [state2.defaultProcessor, ...options.processor ? [options.processor] : []]
5679
- });
5680
- state2.provider.register({
5681
- contextManager: options.contextManager,
5682
- propagator: options.propagator
5683
- });
5684
- const instrumentations = (_a = options.instrumentations) != null ? _a : [];
5685
- if (contentCaptureDisabled(options)) {
5686
- for (const instrumentation of instrumentations) {
5687
- try {
5688
- const config = {
5689
- ...instrumentation.getConfig(),
5690
- traceContent: false
5691
- };
5692
- instrumentation.setConfig(config);
5693
- } catch (e) {
5694
- }
5695
- }
5696
- }
5697
- registerInstrumentations({ instrumentations });
5698
- }
5699
- async function forceFlush() {
5700
- var _a, _b;
5701
- const state2 = getState2();
5702
- try {
5703
- await ((_a = state2.provider) == null ? void 0 : _a.forceFlush());
5704
- await ((_b = state2.defaultProcessor) == null ? void 0 : _b.forceFlush());
5705
- } catch (e) {
5706
- }
5707
- }
5708
- function withEntity(type, config, fn, args) {
5709
- let entityContext = context2.active();
5710
- if (type === TraceloopSpanKindValues.WORKFLOW) {
5711
- entityContext = entityContext.setValue(WORKFLOW_NAME_KEY, config.name);
5712
- }
5713
- const parentPath = entityContext.getValue(ENTITY_NAME_KEY);
5714
- if (type === TraceloopSpanKindValues.TASK || type === TraceloopSpanKindValues.TOOL) {
5715
- entityContext = entityContext.setValue(
5716
- ENTITY_NAME_KEY,
5717
- `${typeof parentPath === "string" ? `${parentPath}.` : ""}${config.name}`
5718
- );
5719
- }
5720
- if (config.traceContent !== void 0) {
5721
- entityContext = entityContext.setValue(CONTEXT_KEY_ALLOW_TRACE_CONTENT, config.traceContent);
5722
- }
5723
- if (config.associationProperties) {
5724
- entityContext = entityContext.setValue(
5725
- ASSOCIATION_PROPERTIES_KEY,
5726
- config.associationProperties
5727
- );
5728
- }
5729
- if (config.suppressTracing) {
5730
- entityContext = suppressTracing(entityContext);
5731
- }
5732
- let callbackStarted = false;
5733
- const run = (span) => {
5734
- var _a;
5735
- try {
5736
- span.setAttribute(SpanAttributes.TRACELOOP_ENTITY_NAME, config.name);
5737
- span.setAttribute(
5738
- SpanAttributes.TRACELOOP_ENTITY_PATH,
5739
- typeof parentPath === "string" ? parentPath : ""
5740
- );
5741
- span.setAttribute(SpanAttributes.TRACELOOP_SPAN_KIND, type);
5742
- if (type === TraceloopSpanKindValues.WORKFLOW) {
5743
- span.setAttribute(SpanAttributes.TRACELOOP_WORKFLOW_NAME, config.name);
5744
- }
5745
- if (config.version !== void 0)
5746
- span.setAttribute(SpanAttributes.TRACELOOP_ENTITY_VERSION, config.version);
5747
- const input = (_a = config.inputParameters) != null ? _a : args;
5748
- if (shouldSendTraceContent()) {
5749
- span.setAttribute(
5750
- SpanAttributes.TRACELOOP_ENTITY_INPUT,
5751
- safeStringify(
5752
- input.length === 1 && input[0] !== null && typeof input[0] === "object" && !(input[0] instanceof Map) ? { args: [], kwargs: input[0] } : { args: input, kwargs: {} }
5753
- )
5754
- );
5755
- }
5756
- } catch (e) {
5757
- }
5758
- let result;
5759
- try {
5760
- callbackStarted = true;
5761
- result = fn(...args);
5762
- } catch (error) {
5763
- try {
5764
- span.end();
5765
- } catch (e) {
5766
- }
5767
- throw error;
5768
- }
5769
- if (result instanceof Promise) {
5770
- return result.then(
5771
- (value) => {
5772
- try {
5773
- if (shouldSendTraceContent())
5774
- span.setAttribute(SpanAttributes.TRACELOOP_ENTITY_OUTPUT, safeStringify(value));
5775
- span.end();
5776
- } catch (e) {
5777
- }
5778
- return value;
5779
- },
5780
- (error) => {
5781
- try {
5782
- span.end();
5783
- } catch (e) {
5784
- }
5785
- throw error;
5786
- }
5787
- );
5788
- }
5789
- try {
5790
- if (shouldSendTraceContent())
5791
- span.setAttribute(SpanAttributes.TRACELOOP_ENTITY_OUTPUT, safeStringify(result));
5792
- span.end();
5793
- } catch (e) {
5794
- }
5795
- return result;
5796
- };
5797
- try {
5798
- const tracer = trace2.getTracer(TRACER_NAME);
5799
- return context2.with(
5800
- entityContext,
5801
- () => tracer.startActiveSpan(`${config.name}.${type}`, {}, entityContext, run)
5802
- );
5803
- } catch (error) {
5804
- if (callbackStarted) throw error;
5805
- return fn(...args);
5806
- }
5807
- }
5808
- function withTask(config, fn, ...args) {
5809
- return withEntity(TraceloopSpanKindValues.TASK, config, fn, args);
5810
- }
5811
- function withTool(config, fn, ...args) {
5812
- return withEntity(TraceloopSpanKindValues.TOOL, config, fn, args);
5813
- }
5814
-
5815
- // src/tracing/exit-flush.ts
5816
- var STATE_KEY5 = /* @__PURE__ */ Symbol.for("raindrop.tracing.exitFlushState");
5817
- function getState3() {
5818
- const holder = globalThis;
5819
- let state2 = holder[STATE_KEY5];
5820
- if (!state2) {
5821
- state2 = {
5822
- clientFlushers: /* @__PURE__ */ new Set(),
5823
- pipelineFlushNeeded: false,
5824
- handlerRegistered: false
5825
- };
5826
- holder[STATE_KEY5] = state2;
5827
- }
5828
- return state2;
5829
- }
5830
- function ensureExitHandler(state2) {
5831
- if (state2.handlerRegistered) return;
5832
- if (typeof process === "undefined" || typeof process.once !== "function") return;
5833
- state2.handlerRegistered = true;
5834
- process.once("beforeExit", () => {
5835
- void flushAll();
5836
- });
5837
- }
5838
- function registerClientFlusher(flush) {
5839
- const state2 = getState3();
5840
- state2.clientFlushers.add(flush);
5841
- ensureExitHandler(state2);
5842
- return () => {
5843
- state2.clientFlushers.delete(flush);
5844
- };
5845
- }
5846
- function markPipelineForExitFlush() {
5847
- const state2 = getState3();
5848
- state2.pipelineFlushNeeded = true;
5849
- ensureExitHandler(state2);
5850
- }
5851
- async function flushAll() {
5852
- const state2 = getState3();
5853
- const tasks = [];
5854
- for (const flush of state2.clientFlushers) {
5855
- tasks.push(Promise.resolve().then(flush).catch(() => {
5856
- }));
5857
- }
5858
- if (state2.pipelineFlushNeeded) {
5859
- tasks.push(
5860
- Promise.resolve().then(() => forceFlush()).catch(() => {
5861
- })
5862
- );
5863
- }
5864
- await Promise.all(tasks);
5865
- }
5866
-
5867
- // src/tracing/liveInteraction.ts
5868
- import {
5869
- SpanStatusCode as SpanStatusCode3,
5870
- TraceFlags as TraceFlags2,
5871
- context as context4,
5872
- isValidSpanId as isValidSpanId2,
5873
- isValidTraceId as isValidTraceId2,
5874
- trace as trace4
5875
- } from "@opentelemetry/api";
5876
-
5877
- // src/tracing/tool-timing.ts
5878
- function toMs(value) {
5879
- return value instanceof Date ? value.getTime() : value;
5880
- }
5881
- function resolveToolTiming(input, now = Date.now()) {
5882
- var _a, _b, _c;
5883
- if (input.endTime !== void 0) {
5884
- const endTimeMs = toMs(input.endTime);
5885
- const startTimeMs2 = input.startTime !== void 0 ? toMs(input.startTime) : endTimeMs - ((_a = input.durationMs) != null ? _a : 0);
5886
- return { startTimeMs: startTimeMs2, endTimeMs, durationMs: endTimeMs - startTimeMs2 };
5887
- }
5888
- const startTimeMs = input.startTime !== void 0 ? toMs(input.startTime) : now - ((_b = input.durationMs) != null ? _b : 0);
5889
- return { startTimeMs, endTimeMs: startTimeMs + ((_c = input.durationMs) != null ? _c : 0), durationMs: input.durationMs };
5890
- }
5891
-
5892
- // src/tracing/subagents.ts
5893
- import { SpanStatusCode as SpanStatusCode2, context as context3, trace as trace3 } from "@opentelemetry/api";
5894
- var DEFAULT_SUBAGENT_NAME = "subagent";
5895
- var DISPATCH_ACCEPTED = "accepted";
5896
- function reasonText(reason) {
5897
- var _a;
5898
- if (reason instanceof Error) return `${reason.name}: ${reason.message}`;
5899
- if (typeof reason === "string") return reason;
5900
- if (reason === void 0 || reason === null) return "";
5901
- try {
5902
- return (_a = JSON.stringify(reason)) != null ? _a : String(reason);
5903
- } catch (e) {
5904
- return String(reason);
5905
- }
5906
- }
5907
- function stampCurrentSpan(attributes) {
5908
- try {
5909
- const span = trace3.getSpan(context3.active());
5910
- if (!(span == null ? void 0 : span.isRecording())) return;
5911
- for (const [key, value] of Object.entries(attributes)) {
5912
- span.setAttribute(key, value);
5913
- }
5914
- } catch (e) {
5915
- }
5916
- }
5917
- function stampOwnSpan(attributes, frame) {
5918
- if (!frame) return;
5919
- try {
5920
- const span = trace3.getSpan(context3.active());
5921
- if (!(span == null ? void 0 : span.isRecording()) || !frame.ownsSpan(span)) return;
5922
- for (const [key, value] of Object.entries(attributes)) {
5923
- span.setAttribute(key, value);
5924
- }
5925
- } catch (e) {
5926
- }
5927
- }
5928
- function failOwnSpan(reason, frame) {
5929
- try {
5930
- const span = trace3.getSpan(context3.active());
5931
- if (!(span == null ? void 0 : span.isRecording())) return false;
5932
- if (!(frame == null ? void 0 : frame.ownsSpan(span))) return false;
5933
- const message = reasonText(reason);
5934
- span.setStatus({ code: SpanStatusCode2.ERROR, message });
5935
- span.recordException(reason instanceof Error ? reason : new Error(message));
5936
- return true;
5937
- } catch (e) {
5938
- return false;
5939
- }
5940
- }
5941
- function allowToolEvents(interaction) {
5942
- const attributes = withMetadataPrefix(toolEventsAllowMetadata());
5943
- interaction.bindToolEventsOptIn(attributes);
5944
- stampCurrentSpan(attributes);
5945
- }
5946
- function recordSubagentDispatch(interaction, options) {
5947
- var _a;
5948
- const childEventId = options.childEventId || randomUUID();
5949
- const name = options.name || DEFAULT_SUBAGENT_NAME;
5950
- const parentEventId = (_a = interaction.getEventId()) != null ? _a : "";
5951
- let traceIdHex;
5952
- let dispatchSpanId;
5953
- try {
5954
- allowToolEvents(interaction);
5955
- const recorded = interaction.recordDispatchSpan({
5956
- name: options.toolName || DEFAULT_DISPATCH_SPAN_NAME,
5957
- input: options.input,
5958
- // A launch's "result" is the job handle; the answer belongs to the
5959
- // child's event and never appears here.
5960
- output: { jobId: childEventId, status: DISPATCH_ACCEPTED },
5961
- properties: options.properties,
5962
- attributes: detachedDispatchMetadata({ childEventId, name })
5963
- });
5964
- traceIdHex = recorded.traceIdHex;
5965
- dispatchSpanId = recorded.spanIdHex;
5966
- if (!dispatchSpanId) {
5967
- console.warn(
5968
- `[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.`
5969
- );
5970
- }
5971
- } catch (error) {
5972
- console.warn(
5973
- `[raindrop] subagent(${name}) failed to record the dispatch; returning a carrier so the child still links back.`,
5974
- error instanceof Error ? error.message : error
5975
- );
5976
- }
5977
- if (!traceIdHex || !dispatchSpanId) {
5978
- return {
5979
- childEventId,
5980
- name,
5981
- parentEventId,
5982
- dispatchSpanId: void 0,
5983
- carrier: null,
5984
- headers: {},
5985
- langsmithHeaders: {}
5986
- };
5987
- }
5988
- const carrier = {
5989
- traceId: traceIdHex,
5990
- spanId: dispatchSpanId,
5991
- eventId: parentEventId,
5992
- childEventId,
5993
- name,
5994
- ...interaction.getConvoId() ? { convoId: interaction.getConvoId() } : {},
5995
- ...interaction.getUserId() ? { userId: interaction.getUserId() } : {}
5996
- };
5997
- return {
5998
- childEventId,
5999
- name,
6000
- parentEventId,
6001
- dispatchSpanId,
6002
- carrier,
6003
- headers: toHeaders(carrier),
6004
- langsmithHeaders: toLangSmithHeaders(carrier)
6005
- };
6006
- }
6007
- function carrierFirst(local, carried, field) {
6008
- if (carried && local && local !== carried) {
6009
- console.warn(
6010
- `[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.`
6011
- );
6012
- }
6013
- return carried || local;
6014
- }
6015
- function isTraceCarrier(value) {
6016
- const candidate = value;
6017
- return typeof candidate.traceId === "string" && typeof candidate.spanId === "string" && typeof candidate.eventId === "string";
6018
- }
6019
- function readCarrier(carrierOrHeaders) {
6020
- if (!carrierOrHeaders) return null;
6021
- try {
6022
- if (isTraceCarrier(carrierOrHeaders)) return carrierOrHeaders;
6023
- return fromHeaders(carrierOrHeaders);
6024
- } catch (error) {
6025
- console.warn(
6026
- `[raindrop] resumeSubagent: ignoring an unreadable hand-off carrier; the run reports as an unlinked event.`,
6027
- error instanceof Error ? error.message : error
6028
- );
6029
- return null;
6030
- }
6031
- }
6032
- function resolveSubagentResume(carrierOrHeaders, options = {}) {
6033
- const parentStated = options.parent !== void 0;
6034
- const parent = parentStated ? options.parent : readCarrier(carrierOrHeaders);
6035
- if (!parentStated) warnUnresolvedCarrier(carrierOrHeaders, parent);
6036
- const name = carrierFirst(options.name, parent == null ? void 0 : parent.name, "name") || DEFAULT_SUBAGENT_NAME;
6037
- const eventId = carrierFirst(options.eventId, parent == null ? void 0 : parent.childEventId, "eventId") || randomUUID();
6038
- const userId = carrierFirst(options.userId, parent == null ? void 0 : parent.userId, "userId") || "";
6039
- const convoId = carrierFirst(options.convoId, parent == null ? void 0 : parent.convoId, "convoId");
6040
- const link = parent ? {
6041
- parentEventId: parent.eventId,
6042
- ...parent.spanId ? { parentSpanId: parent.spanId } : {},
6043
- name
6044
- } : null;
6045
- return {
6046
- parent,
6047
- link,
6048
- name,
6049
- eventId,
6050
- event: options.event || `subagent.${name}`,
6051
- userId,
6052
- ...convoId ? { convoId } : {}
6053
- };
6054
- }
6055
- function bindSubagentLink(link, owner) {
6056
- if (!link) return void 0;
6057
- return bindSpanAttributes(detachedChildMetadata(link), owner);
6058
- }
6059
- var LiveSubagentRun = class {
6060
- constructor(params) {
6061
- this.settled = false;
6062
- this.interaction = params.interaction;
6063
- this.eventId = params.eventId;
6064
- this.name = params.name;
6065
- this.convoId = params.convoId;
6066
- this.parent = params.parent;
6067
- this.frame = params.frame;
6068
- this.frameOwner = params.frameOwner;
6069
- }
6070
- get linked() {
6071
- return this.parent !== null;
6072
- }
6073
- async finish(result) {
6074
- await this.close(result);
6075
- }
6076
- async fail(reason) {
6077
- await this.abort(reason);
6078
- }
6079
- async cancel(reason) {
6080
- const text = reason === void 0 ? "cancelled by caller" : reasonText(reason);
6081
- const cancelled = cancelledTerminalAttributes();
6082
- stampOwnSpan(cancelled, this.frame);
6083
- await this.close({
6084
- output: `Cancelled: ${text}`,
6085
- // The caller's view of the child is its EVENT, not its spans, so the
6086
- // marker has to be a property of the event as well.
6087
- properties: { [HANDOFF_TERMINAL_PROPERTY_KEY]: HANDOFF_TERMINAL_CANCELLED }
6088
- });
6089
- }
6090
- /**
6091
- * Close the run with an abort reason, having first made sure the failure is
6092
- * visible on a span.
6093
- *
6094
- * A failure has to leave an errored span behind or it is derived as finished.
6095
- * Mark whatever is open; if nothing is and the child has not errored a span
6096
- * already, record one — the killed-before-it-reached-the-model case, which is
6097
- * much of what aborting is.
6098
- */
6099
- async abort(reason) {
6100
- var _a, _b, _c;
6101
- const text = reasonText(reason);
6102
- if (!this.settled && !failOwnSpan(reason, this.frame)) {
6103
- if (!((_a = this.frame) == null ? void 0 : _a.sawErrorSpan())) {
6104
- this.interaction.recordSubagentAbortSpan({
6105
- reason,
6106
- message: text,
6107
- attributes: {
6108
- [HANDOFF_ATTRIBUTE_SUFFIXES.name]: this.name,
6109
- // The name explicitly, not only via the frame: an UNLINKED run has
6110
- // no frame, and since the span is named for the operation
6111
- // (`ai.subagent.failed`) rather than the sub-agent, this attribute
6112
- // is the only thing left that says which sub-agent failed.
6113
- ...(_c = (_b = this.frame) == null ? void 0 : _b.attributes) != null ? _c : {}
6114
- }
6115
- });
6116
- }
6117
- }
6118
- await this.close({ output: text ? `Aborted: ${text}` : "Aborted before producing a result." });
6119
- }
6120
- async close(result) {
6121
- if (this.settled) return;
6122
- this.settled = true;
6123
- try {
6124
- await this.interaction.finish({ ...result, eventId: this.eventId });
6125
- } finally {
6126
- unbindSpanAttributes(this.frame);
6127
- this.frame = void 0;
6128
- this.frameOwner = void 0;
6129
- }
6130
- }
6131
- /**
6132
- * Run `fn` and guarantee the run reports an outcome, mirroring the Python
6133
- * SDK's `with rd.resume_subagent(...) as run:`.
6134
- *
6135
- * A run that leaves without reporting output is closed with its abort reason.
6136
- * That is not cosmetic: an event is created only from a run with non-empty
6137
- * output, so a child that dies silently produces no event at all and the
6138
- * caller's launch stays `queued` forever — indistinguishable from a job that
6139
- * never started.
6140
- */
6141
- async use(fn) {
6142
- try {
6143
- const result = await fn(this);
6144
- if (!this.settled) {
6145
- console.warn(
6146
- `[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.`
6147
- );
6148
- await this.abortQuietly("sub-agent ended without reporting output");
6149
- }
6150
- return result;
6151
- } catch (error) {
6152
- await this.abortQuietly(error);
6153
- throw error;
6154
- }
6155
- }
6156
- /**
6157
- * {@link abort} for the outcomes this class reports on the caller's behalf.
6158
- *
6159
- * `abort()` ends in `interaction.finish()`, which awaits the terminal event
6160
- * POST and rejects when it fails. An explicit `fail()` may surface that — the
6161
- * caller awaited it — but an implicit one must not: rejecting on the error
6162
- * path replaces the caller's exception with a telemetry one, and rejecting on
6163
- * the success path loses a result `fn` already produced.
6164
- */
6165
- async abortQuietly(reason) {
6166
- try {
6167
- await this.abort(reason);
6168
- } catch (error) {
6169
- console.warn(
6170
- `[raindrop] sub-agent run ${this.eventId} (${this.name}) could not report its outcome; the run itself is unaffected.`,
6171
- error instanceof Error ? error.message : error
6172
- );
6173
- }
6174
- }
6175
- };
6176
-
6177
- // src/tracing/liveInteraction.ts
6178
- function getPropertiesFromContext(context7) {
6179
- const properties = {
6180
- ...context7.userId && { user_id: context7.userId },
6181
- ...context7.convoId && { convo_id: context7.convoId },
6182
- ...context7.eventId && { event_id: context7.eventId },
6183
- ...context7.event && { event_name: context7.event },
6184
- ...context7.properties || {}
6185
- };
6186
- if (context7.attachments && context7.attachments.length > 0) {
6187
- properties.attachments = stringifyBounded(context7.attachments);
6188
- }
6189
- return properties;
6190
- }
6191
- function setAssociationProperties(span, properties) {
6192
- Object.entries(properties).forEach(([key, value]) => {
6193
- if (value === void 0) {
6194
- return;
6195
- }
6196
- span.setAttribute("traceloop.association.properties." + key, serializeSpanValue(value));
6197
- });
6198
- }
6199
- function serializeAssociationProperties(properties) {
6200
- return Object.fromEntries(
6201
- Object.entries(properties).filter(([, value]) => value !== void 0).map(([key, value]) => [key, serializeSpanValue(value)])
6202
- );
6203
- }
6204
- function serializeSpanValue(value) {
6205
- return stringifyBounded(value);
6206
- }
6207
- function getLocalDebuggerMetadata(context7) {
6208
- return {
6209
- ...context7.eventId ? { eventId: context7.eventId } : {},
6210
- ...context7.event ? { eventName: context7.event } : {},
6211
- ...context7.userId ? { userId: context7.userId } : {},
6212
- ...context7.convoId ? { convoId: context7.convoId } : {}
6213
- };
6214
- }
6215
- var LiveToolSpan = class {
6216
- constructor(params) {
6217
- this.hasError = false;
6218
- this.span = params.span;
6219
- this.name = params.name;
6220
- this.emitLiveEvent = params.emitLiveEvent;
6221
- }
6222
- spanIdHex() {
6223
- const ctx = this.span.spanContext();
6224
- return isValidSpanId2(ctx.spanId) ? ctx.spanId : void 0;
6225
- }
6226
- setInput(input) {
6227
- this.span.setAttribute("traceloop.entity.input", serializeSpanValue(input));
6228
- }
6229
- setOutput(output) {
6230
- this.output = output;
6231
- this.span.setAttribute("traceloop.entity.output", serializeSpanValue(output));
6232
- }
6233
- setError(error) {
6234
- this.hasError = true;
6235
- this.errorMessage = error instanceof Error ? error.message : String(error);
6236
- this.span.setStatus({ code: SpanStatusCode3.ERROR, message: this.errorMessage });
6237
- this.span.recordException(error instanceof Error ? error : new Error(this.errorMessage));
6238
- }
6239
- end() {
6240
- var _a;
6241
- if (!this.hasError) {
6242
- this.span.setStatus({ code: SpanStatusCode3.OK });
6243
- }
6244
- this.span.end();
6245
- (_a = this.emitLiveEvent) == null ? void 0 : _a.call(this, {
6246
- type: "tool_result",
6247
- content: this.name,
6248
- spanId: this.spanIdHex(),
6249
- metadata: {
6250
- ...this.output !== void 0 ? { result: this.output } : {},
6251
- ...this.errorMessage ? { error: this.errorMessage } : {}
6252
- }
6253
- });
6254
- }
6255
- };
6256
- var DirectToolSpan = class {
6257
- constructor(params) {
6258
- this.ended = false;
6259
- this.name = params.name;
6260
- this.properties = params.properties;
6261
- this.directShipper = params.directShipper;
6262
- this.traceId = params.traceId;
6263
- this.spanId = params.spanId;
6264
- this.parentSpanId = params.parentSpanId;
6265
- this.startTimeMs = Date.now();
6266
- this.input = params.input !== void 0 ? serializeSpanValue(params.input) : void 0;
6267
- this.emitLiveEvent = params.emitLiveEvent;
6268
- }
6269
- setInput(input) {
6270
- this.input = serializeSpanValue(input);
6271
- }
6272
- setOutput(output) {
6273
- this.rawOutput = output;
6274
- this.output = serializeSpanValue(output);
6275
- }
6276
- setError(error) {
6277
- this.error = error instanceof Error ? error.message : String(error);
6278
- }
6279
- end() {
6280
- var _a;
6281
- if (this.ended) {
6282
- return;
6283
- }
6284
- this.ended = true;
6285
- const endTimeMs = Date.now();
6286
- this.directShipper.sendToolSpan({
6287
- name: this.name,
6288
- spanId: this.spanId,
6289
- input: this.input,
6290
- output: this.output,
6291
- durationMs: endTimeMs - this.startTimeMs,
6292
- startTimeMs: this.startTimeMs,
6293
- endTimeMs,
6294
- error: this.error,
6295
- properties: this.properties,
6296
- traceId: this.traceId,
6297
- parentSpanId: this.parentSpanId
6298
- });
6299
- (_a = this.emitLiveEvent) == null ? void 0 : _a.call(this, {
6300
- traceId: this.traceId,
6301
- spanId: this.spanId,
6302
- type: "tool_result",
6303
- content: this.name,
6304
- timestamp: endTimeMs,
6305
- metadata: {
6306
- ...this.rawOutput !== void 0 ? { result: this.rawOutput } : {},
6307
- ...this.error ? { error: this.error } : {}
6308
- }
6309
- });
6310
- }
6311
- };
6312
- var LiveInteraction = class {
6313
- constructor(context7, traceId, analytics, directShipper, routing) {
6314
- this.usageEmitted = false;
6315
- this.context = context7;
6316
- this.analytics = analytics;
6317
- this.tracer = trace4.getTracer("traceloop.tracer");
6318
- this.traceId = traceId;
6319
- this.directShipper = directShipper;
6320
- this.routing = routing;
6321
- }
6322
- /**
6323
- * Record the routing binding this interaction pushed onto the context stack
6324
- * (via {@link bindRoutingContext} in `begin()`) so {@link finish} removes
6325
- * exactly its own entry — non-LIFO safe, and leaving any still-open sibling's
6326
- * binding intact.
6327
- */
6328
- setBoundContext(bound) {
6329
- this.boundContext = bound;
6330
- }
6331
- /** Stamp a manually-created OTel span with this interaction's routing. */
6332
- stampRouting(span) {
6333
- if (!this.routing) return;
6334
- stampSpan(span, this.routing.projectId, this.routing.authHint);
6335
- }
6336
- ensureTraceId(preferred) {
6337
- if (preferred) {
6338
- this.traceId = preferred;
6339
- return preferred;
6340
- }
6341
- if (this.traceId) {
6342
- return this.traceId;
6343
- }
6344
- this.traceId = base64Encode2(randomBytes2(16));
6345
- return this.traceId;
6346
- }
6347
- resolveLiveTraceId(explicitTraceId) {
6348
- if (explicitTraceId) {
6349
- this.traceId = explicitTraceId;
6350
- return explicitTraceId;
6351
- }
6352
- const activeSpan = trace4.getSpan(context4.active());
6353
- const activeTraceId = activeSpan == null ? void 0 : activeSpan.spanContext().traceId;
6354
- if (activeTraceId) {
6355
- this.traceId = activeTraceId;
6356
- return activeTraceId;
6357
- }
6358
- return this.traceId;
6359
- }
6360
- emitLiveEvent(event) {
6361
- var _a, _b;
6362
- const traceId = (_a = this.resolveLiveTraceId(event.traceId)) != null ? _a : this.ensureTraceId();
6363
- sendLocalDebuggerLiveEvent({
6364
- ...event,
6365
- traceId,
6366
- metadata: {
6367
- ...getLocalDebuggerMetadata(this.context),
6368
- ...(_b = event.metadata) != null ? _b : {}
6369
- }
6370
- });
6371
- }
6372
- getTraceId() {
6373
- return this.traceId;
6374
- }
6375
- async withSpan(params, fn, thisArg, ...args) {
6376
- var _a;
6377
- const taskName = typeof params === "string" ? params : params.name;
6378
- const properties = typeof params === "string" ? {
6379
- ...getPropertiesFromContext(this.context)
6380
- } : {
6381
- ...getPropertiesFromContext(this.context),
6382
- ...params.properties || {}
6383
- };
6384
- const inputParameters = typeof params === "string" ? void 0 : params.inputParameters;
6385
- if ((_a = this.analytics) == null ? void 0 : _a.debugLogs) {
6386
- console.log("[raindrop] using withSpan in liveInteraction");
6387
- }
6388
- if (this.directShipper) {
6389
- const activeContext = getActiveTraceContext();
6390
- const traceIdB64 = this.ensureTraceId(activeContext.traceIdB64);
6391
- const parentSpanIdB64 = activeContext.parentSpanIdB64;
6392
- const spanIdB64 = base64Encode2(randomBytes2(8));
6393
- const startTimeMs = Date.now();
6394
- const spanContext = {
6395
- traceId: base64ToHex2(traceIdB64),
6396
- spanId: base64ToHex2(spanIdB64),
6397
- traceFlags: TraceFlags2.SAMPLED
6398
- };
6399
- const wrappedContext = trace4.setSpan(context4.active(), trace4.wrapSpanContext(spanContext));
6400
- const invoke = () => this.routing ? withRoutingContext(this.routing, () => fn.apply(thisArg, args)) : fn.apply(thisArg, args);
6401
- try {
6402
- const result = await context4.with(wrappedContext, invoke);
6403
- const endTimeMs = Date.now();
6404
- this.directShipper.sendSpan({
6405
- name: taskName,
6406
- spanKind: "task",
6407
- spanId: spanIdB64,
6408
- input: inputParameters !== void 0 ? serializeSpanValue(inputParameters) : void 0,
6409
- output: result !== void 0 ? serializeSpanValue(result) : void 0,
6410
- durationMs: endTimeMs - startTimeMs,
6411
- startTimeMs,
6412
- endTimeMs,
6413
- properties,
6414
- traceId: traceIdB64,
6415
- parentSpanId: parentSpanIdB64
6416
- });
6417
- return result;
6418
- } catch (error) {
6419
- const endTimeMs = Date.now();
6420
- this.directShipper.sendSpan({
6421
- name: taskName,
6422
- spanKind: "task",
6423
- spanId: spanIdB64,
6424
- input: inputParameters !== void 0 ? serializeSpanValue(inputParameters) : void 0,
6425
- durationMs: endTimeMs - startTimeMs,
6426
- startTimeMs,
6427
- endTimeMs,
6428
- error: error instanceof Error ? error.message : String(error),
6429
- properties,
6430
- traceId: traceIdB64,
6431
- parentSpanId: parentSpanIdB64
6432
- });
6433
- throw error;
6434
- }
6435
- }
6436
- const wrappedFn = (...fnArgs) => {
6437
- const activeSpan = trace4.getSpan(context4.active());
6438
- const activeTraceId = activeSpan == null ? void 0 : activeSpan.spanContext().traceId;
6439
- if (activeTraceId) {
6440
- this.traceId = activeTraceId;
6441
- }
6442
- if (activeSpan) {
6443
- this.stampRouting(activeSpan);
6444
- }
6445
- if (this.routing) {
6446
- return withRoutingContext(this.routing, () => fn.apply(thisArg, fnArgs));
6447
- }
6448
- return fn.apply(thisArg, fnArgs);
6449
- };
6450
- return withTask(
6451
- {
6452
- name: taskName,
6453
- associationProperties: serializeAssociationProperties(properties),
6454
- inputParameters,
6455
- traceContent: params.traceContent,
6456
- suppressTracing: params.suppressTracing
6457
- },
6458
- wrappedFn,
6459
- ...args
6460
- );
6461
- }
6462
- async withTool(params, fn, thisArg, ...args) {
6463
- var _a;
6464
- const toolName = params.name;
6465
- const properties = {
6466
- ...getPropertiesFromContext(this.context),
6467
- ...params.properties || {}
6468
- };
6469
- if ((_a = this.analytics) == null ? void 0 : _a.debugLogs) {
6470
- console.log("[raindrop] using withTool in liveInteraction");
6471
- }
6472
- if (this.directShipper) {
6473
- const activeContext = getActiveTraceContext();
6474
- const traceIdB64 = this.ensureTraceId(activeContext.traceIdB64);
6475
- const { parentSpanIdB64 } = activeContext;
6476
- const spanIdB64 = base64Encode2(randomBytes2(8));
6477
- const startTimeMs = Date.now();
6478
- this.emitLiveEvent({
6479
- traceId: traceIdB64,
6480
- spanId: spanIdB64,
6481
- type: "tool_start",
6482
- content: toolName,
6483
- timestamp: startTimeMs,
6484
- metadata: params.inputParameters ? { args: params.inputParameters } : void 0
6485
- });
6486
- const spanContext = {
6487
- traceId: base64ToHex2(traceIdB64),
6488
- spanId: base64ToHex2(spanIdB64),
6489
- traceFlags: TraceFlags2.SAMPLED
6490
- };
6491
- const wrappedContext = trace4.setSpan(context4.active(), trace4.wrapSpanContext(spanContext));
6492
- const invoke = () => this.routing ? withRoutingContext(this.routing, () => fn.apply(thisArg, args)) : fn.apply(thisArg, args);
6493
- let result;
6494
- let error;
6495
- try {
6496
- result = await context4.with(wrappedContext, invoke);
6497
- } catch (err) {
6498
- error = err instanceof Error ? err.message : String(err);
6499
- const endTimeMs2 = Date.now();
6500
- const durationMs2 = endTimeMs2 - startTimeMs;
6501
- const inputStr2 = params.inputParameters ? stringifyBounded(params.inputParameters) : void 0;
6502
- this.directShipper.sendToolSpan({
6503
- name: toolName,
6504
- spanId: spanIdB64,
6505
- input: inputStr2,
6506
- output: void 0,
6507
- durationMs: durationMs2,
6508
- startTimeMs,
6509
- endTimeMs: endTimeMs2,
6510
- error,
6511
- properties,
6512
- traceId: traceIdB64,
6513
- parentSpanId: parentSpanIdB64
6514
- });
6515
- this.emitLiveEvent({
6516
- traceId: traceIdB64,
6517
- spanId: spanIdB64,
6518
- type: "tool_result",
6519
- content: toolName,
6520
- timestamp: endTimeMs2,
6521
- metadata: {
6522
- ...params.inputParameters ? { args: params.inputParameters } : {},
6523
- error
6524
- }
6525
- });
6526
- throw err;
6527
- }
6528
- const endTimeMs = Date.now();
6529
- const durationMs = endTimeMs - startTimeMs;
6530
- const inputStr = params.inputParameters ? stringifyBounded(params.inputParameters) : void 0;
6531
- const outputStr = result !== void 0 ? stringifyBounded(result) : void 0;
6532
- this.directShipper.sendToolSpan({
6533
- name: toolName,
6534
- spanId: spanIdB64,
6535
- input: inputStr,
6536
- output: outputStr,
6537
- durationMs,
6538
- startTimeMs,
6539
- endTimeMs,
6540
- error: void 0,
6541
- properties,
6542
- traceId: traceIdB64,
6543
- parentSpanId: parentSpanIdB64
6544
- });
6545
- this.emitLiveEvent({
6546
- traceId: traceIdB64,
6547
- spanId: spanIdB64,
6548
- type: "tool_result",
6549
- content: toolName,
6550
- timestamp: endTimeMs,
6551
- metadata: {
6552
- ...params.inputParameters ? { args: params.inputParameters } : {},
6553
- ...result !== void 0 ? { result } : {}
6554
- }
6555
- });
6556
- return result;
6557
- }
6558
- const inputParams = params.inputParameters ? [params.inputParameters] : void 0;
6559
- const emitLive = (event) => this.emitLiveEvent(event);
6560
- const wrapped = async (...wrappedArgs) => {
6561
- const activeSpan = trace4.getSpan(context4.active());
6562
- const ctx = activeSpan == null ? void 0 : activeSpan.spanContext();
6563
- const liveSpanId = ctx && isValidSpanId2(ctx.spanId) ? ctx.spanId : void 0;
6564
- if (activeSpan) {
6565
- this.stampRouting(activeSpan);
6566
- }
6567
- emitLive({
6568
- type: "tool_start",
6569
- spanId: liveSpanId,
6570
- content: toolName,
6571
- timestamp: Date.now(),
6572
- metadata: params.inputParameters ? { args: params.inputParameters } : void 0
6573
- });
6574
- try {
6575
- const r = this.routing ? await withRoutingContext(this.routing, () => fn.apply(thisArg, wrappedArgs)) : await fn.apply(thisArg, wrappedArgs);
6576
- emitLive({
6577
- type: "tool_result",
6578
- spanId: liveSpanId,
6579
- content: toolName,
6580
- timestamp: Date.now(),
6581
- metadata: {
6582
- ...params.inputParameters ? { args: params.inputParameters } : {},
6583
- ...r !== void 0 ? { result: r } : {}
6584
- }
6585
- });
6586
- return r;
6587
- } catch (error) {
6588
- emitLive({
6589
- type: "tool_result",
6590
- spanId: liveSpanId,
6591
- content: toolName,
6592
- timestamp: Date.now(),
6593
- metadata: {
6594
- ...params.inputParameters ? { args: params.inputParameters } : {},
6595
- error: error instanceof Error ? error.message : String(error)
6596
- }
6597
- });
6598
- throw error;
6599
- }
6600
- };
6601
- return withTool(
6602
- {
6603
- name: toolName,
6604
- associationProperties: serializeAssociationProperties(properties),
6605
- inputParameters: inputParams,
6606
- version: params.version,
6607
- traceContent: params.traceContent,
6608
- suppressTracing: params.suppressTracing
6609
- },
6610
- wrapped,
6611
- ...args
6612
- );
6613
- }
6614
- startSpan(params) {
6615
- const { name, properties = {} } = params;
6616
- const span = this.tracer.startSpan(name);
6617
- const contextProperties = getPropertiesFromContext(this.context);
6618
- setAssociationProperties(span, contextProperties);
6619
- span.setAttribute("traceloop.span.kind", "task");
6620
- setAssociationProperties(span, properties);
6621
- this.stampRouting(span);
6622
- return span;
6623
- }
6624
- startToolSpan(params) {
6625
- var _a, _b;
6626
- const { name, properties = {}, inputParameters } = params;
6627
- const contextProperties = getPropertiesFromContext(this.context);
6628
- const mergedProperties = {
6629
- ...contextProperties,
6630
- ...properties
6631
- };
6632
- if (this.directShipper) {
6633
- const activeTraceContext = getActiveTraceContext();
6634
- const traceIdB64 = this.ensureTraceId(activeTraceContext.traceIdB64);
6635
- const { parentSpanIdB64 } = activeTraceContext;
6636
- const spanIdB64 = base64Encode2(randomBytes2(8));
6637
- if ((_a = this.analytics) == null ? void 0 : _a.debugLogs) {
6638
- console.log(`[raindrop] startToolSpan (direct): started tool span "${name}"`);
6639
- }
6640
- this.emitLiveEvent({
6641
- traceId: traceIdB64,
6642
- spanId: spanIdB64,
6643
- type: "tool_start",
6644
- content: name,
6645
- timestamp: Date.now(),
6646
- metadata: inputParameters !== void 0 ? { args: inputParameters } : void 0
6647
- });
6648
- return new DirectToolSpan({
6649
- name,
6650
- properties: mergedProperties,
6651
- directShipper: this.directShipper,
6652
- traceId: traceIdB64,
6653
- spanId: spanIdB64,
6654
- parentSpanId: parentSpanIdB64,
6655
- input: inputParameters,
6656
- emitLiveEvent: (event) => this.emitLiveEvent(event)
6657
- });
6658
- }
6659
- const span = this.tracer.startSpan(name);
6660
- setAssociationProperties(span, contextProperties);
6661
- span.setAttribute("traceloop.span.kind", "tool");
6662
- setAssociationProperties(span, properties);
6663
- this.stampRouting(span);
6664
- if (inputParameters !== void 0) {
6665
- span.setAttribute("traceloop.entity.input", serializeSpanValue(inputParameters));
6666
- }
6667
- if ((_b = this.analytics) == null ? void 0 : _b.debugLogs) {
6668
- console.log(`[raindrop] startToolSpan: started tool span "${name}"`);
6669
- }
6670
- const startSpanCtx = span.spanContext();
6671
- const startSpanIdHex = isValidSpanId2(startSpanCtx.spanId) ? startSpanCtx.spanId : void 0;
6672
- this.emitLiveEvent({
6673
- type: "tool_start",
6674
- spanId: startSpanIdHex,
6675
- content: name,
6676
- timestamp: Date.now(),
6677
- metadata: inputParameters !== void 0 ? { args: inputParameters } : void 0
6678
- });
6679
- return new LiveToolSpan({
6680
- span,
6681
- name,
6682
- emitLiveEvent: (event) => this.emitLiveEvent(event)
6683
- });
6684
- }
6685
- setProperties(properties) {
6686
- var _a;
6687
- this.context.properties = { ...this.context.properties, ...properties };
6688
- (_a = this.analytics) == null ? void 0 : _a._trackAiPartial({
6689
- eventId: this.context.eventId,
6690
- properties
6691
- });
6692
- }
6693
- setProperty(key, value) {
6694
- var _a;
6695
- this.context.properties = { ...this.context.properties, [key]: value };
6696
- (_a = this.analytics) == null ? void 0 : _a._trackAiPartial({
6697
- eventId: this.context.eventId,
6698
- properties: { [key]: value }
6699
- });
6700
- }
6701
- addAttachments(attachments) {
6702
- var _a;
6703
- this.context.attachments = [...this.context.attachments || [], ...attachments];
6704
- (_a = this.analytics) == null ? void 0 : _a._trackAiPartial({
6705
- eventId: this.context.eventId,
6706
- attachments
6707
- });
6708
- }
6709
- setFeatureFlag(name, value) {
6710
- var _a;
6711
- const normalized = String(value != null ? value : "true");
6712
- const existing = this.context.featureFlags ? normalizeFeatureFlags(this.context.featureFlags) : {};
6713
- this.context.featureFlags = { ...existing, [name]: normalized };
6714
- (_a = this.analytics) == null ? void 0 : _a._trackAiPartial({
6715
- eventId: this.context.eventId,
6716
- featureFlags: { [name]: normalized }
6717
- });
6718
- }
6719
- setFeatureFlags(flags) {
6720
- var _a;
6721
- const normalized = normalizeFeatureFlags(flags);
6722
- const existing = this.context.featureFlags ? normalizeFeatureFlags(this.context.featureFlags) : {};
6723
- this.context.featureFlags = { ...existing, ...normalized };
6724
- (_a = this.analytics) == null ? void 0 : _a._trackAiPartial({
6725
- eventId: this.context.eventId,
6726
- featureFlags: normalized
6727
- });
6728
- }
6729
- setInput(input) {
6730
- var _a;
6731
- this.context.input = input;
6732
- (_a = this.analytics) == null ? void 0 : _a._trackAiPartial({
6733
- eventId: this.context.eventId,
6734
- input
6735
- });
6736
- }
6737
- vercelAiSdkMetadata() {
6738
- const metadata = {};
6739
- if (this.context.userId) {
6740
- metadata["traceloop.association.properties.user_id"] = this.context.userId;
6741
- }
6742
- if (this.context.convoId) {
6743
- metadata["traceloop.association.properties.convo_id"] = this.context.convoId;
6744
- }
6745
- if (this.context.eventId) {
6746
- metadata["traceloop.association.properties.event_id"] = this.context.eventId;
6747
- }
6748
- if (this.context.event) {
6749
- metadata["traceloop.association.properties.event_name"] = this.context.event;
6750
- }
6751
- if (this.context.properties) {
6752
- for (const [key, value] of Object.entries(this.context.properties)) {
6753
- if (value === void 0) {
6754
- continue;
6755
- }
6756
- metadata[`traceloop.association.properties.${key}`] = serializeSpanValue(value);
6757
- }
6758
- }
6759
- return metadata;
6760
- }
6761
- getEventId() {
6762
- return this.context.eventId;
6763
- }
6764
- getUserId() {
6765
- return this.context.userId;
6766
- }
6767
- getConvoId() {
6768
- return this.context.convoId;
6769
- }
6770
- /**
6771
- * Bind this turn's tool-call event opt-in, once.
6772
- *
6773
- * Owned by the interaction rather than by the execution context: the frame
6774
- * lives exactly as long as the turn does (removed by `finish()`, and dead once
6775
- * this interaction is collected), instead of outliving it on a context the
6776
- * host may reuse for unrelated work.
6777
- */
6778
- bindToolEventsOptIn(attributes) {
6779
- if (this.toolEventsFrame) return;
6780
- this.toolEventsFrame = bindSpanAttributes(attributes, this);
6781
- }
6782
- /**
6783
- * Carry a `begin({ tools })` override to every span started inside this
6784
- * interaction. Frames stamp strings, so the normalized catalog rides as one
6785
- * JSON marker attribute; the span processor turns it into `ai.prompt.tools`
6786
- * on model spans (and drops it from every other span) when the span ends.
6787
- * Same lifetime as the tool-events frame: removed by `finish()`.
6788
- */
6789
- bindPromptToolsOverride(tools) {
6790
- var _a;
6791
- if (tools === void 0 || this.promptToolsFrame) return;
6792
- const declarations = (_a = normalizeToolDeclarations(tools)) != null ? _a : [];
6793
- this.promptToolsFrame = bindSpanAttributes(
6794
- { [PROMPT_TOOLS_OVERRIDE_MARKER]: JSON.stringify(declarations) },
6795
- this
6796
- );
6797
- }
6798
- subagent(options) {
6799
- return recordSubagentDispatch(this, options);
6800
- }
6801
- /**
6802
- * Record the tool span a detached dispatch is written on.
6803
- *
6804
- * Distinct from {@link startToolSpan} in the two ways the hand-off needs:
6805
- * the contract's keys are set as RAW span attributes (under the
6806
- * `traceloop.association.properties.` prefix the backend's reader cannot see
6807
- * them), and the caller needs the span's ids to build the carrier.
6808
- *
6809
- * @internal
6810
- */
6811
- recordDispatchSpan(params) {
6812
- var _a;
6813
- const properties = {
6814
- ...getPropertiesFromContext(this.context),
6815
- ...(_a = params.properties) != null ? _a : {}
6816
- };
6817
- const input = params.input !== void 0 ? serializeSpanValue(params.input) : void 0;
6818
- const output = serializeSpanValue(params.output);
6819
- if (this.directShipper) {
6820
- const activeContext = getActiveTraceContext();
6821
- const traceIdB64 = this.ensureTraceId(activeContext.traceIdB64);
6822
- const spanIdB64 = base64Encode2(randomBytes2(8));
6823
- const timeMs = Date.now();
6824
- this.directShipper.sendToolSpan({
6825
- name: params.name,
6826
- spanId: spanIdB64,
6827
- input,
6828
- output,
6829
- durationMs: 0,
6830
- startTimeMs: timeMs,
6831
- endTimeMs: timeMs,
6832
- properties,
6833
- traceId: traceIdB64,
6834
- parentSpanId: activeContext.parentSpanIdB64,
6835
- attributes: params.attributes
6836
- });
6837
- this.emitLiveEvent({
6838
- traceId: traceIdB64,
6839
- spanId: spanIdB64,
6840
- type: "tool_result",
6841
- content: params.name,
6842
- timestamp: timeMs,
6843
- metadata: { result: params.output }
6844
- });
6845
- return { traceIdHex: base64ToHex2(traceIdB64), spanIdHex: base64ToHex2(spanIdB64) };
6846
- }
6847
- const span = this.tracer.startSpan(params.name);
6848
- setAssociationProperties(span, properties);
6849
- span.setAttribute("traceloop.span.kind", "tool");
6850
- this.stampRouting(span);
6851
- for (const [key, value] of Object.entries(params.attributes)) {
6852
- span.setAttribute(key, value);
6853
- }
6854
- if (input !== void 0) {
6855
- span.setAttribute("traceloop.entity.input", input);
6856
- }
6857
- span.setAttribute("traceloop.entity.output", output);
6858
- span.setStatus({ code: SpanStatusCode3.OK });
6859
- const spanContext = span.spanContext();
6860
- span.end();
6861
- this.emitLiveEvent({
6862
- spanId: isValidSpanId2(spanContext.spanId) ? spanContext.spanId : void 0,
6863
- type: "tool_result",
6864
- content: params.name,
6865
- timestamp: Date.now(),
6866
- metadata: { result: params.output }
6867
- });
6868
- return {
6869
- traceIdHex: isValidTraceId2(spanContext.traceId) ? spanContext.traceId : void 0,
6870
- spanIdHex: isValidSpanId2(spanContext.spanId) ? spanContext.spanId : void 0
6871
- };
6872
- }
6873
- /**
6874
- * Record the errored span a detached sub-agent's failure needs when nothing
6875
- * else is open.
6876
- *
6877
- * Frequently the child's ONLY span, so it carries the full reverse reference:
6878
- * anything reading it alone still knows which launch it belongs to. Those
6879
- * attributes come from the run's own frame rather than the ambient stack,
6880
- * because `fail()` is often called from a different task than the one that
6881
- * opened the run and this is the span that can least afford to lose the link.
6882
- *
6883
- * @internal
6884
- */
6885
- recordSubagentAbortSpan(params) {
6886
- const { reason, message, attributes } = params;
6887
- const properties = getPropertiesFromContext(this.context);
6888
- if (this.directShipper) {
6889
- const activeContext = getActiveTraceContext();
6890
- const timeMs = Date.now();
6891
- this.directShipper.sendSpan({
6892
- name: SUBAGENT_ABORT_SPAN_NAME,
6893
- // Not "tool": the run died, it did not call anything. `ai.operationId`
6894
- // below is what keeps the span (see the attribute's docs in core).
6895
- spanKind: "task",
6896
- spanId: base64Encode2(randomBytes2(8)),
6897
- durationMs: 0,
6898
- startTimeMs: timeMs,
6899
- endTimeMs: timeMs,
6900
- error: message,
6901
- properties,
6902
- traceId: this.ensureTraceId(activeContext.traceIdB64),
6903
- parentSpanId: activeContext.parentSpanIdB64,
6904
- attributes: { ...attributes, [OPERATION_ID_ATTRIBUTE]: SUBAGENT_ABORT_OPERATION_ID }
6905
- });
6906
- return;
6907
- }
6908
- const span = this.tracer.startSpan(SUBAGENT_ABORT_SPAN_NAME);
6909
- span.setAttribute(OPERATION_ID_ATTRIBUTE, SUBAGENT_ABORT_OPERATION_ID);
6910
- setAssociationProperties(span, properties);
6911
- this.stampRouting(span);
6912
- for (const [key, value] of Object.entries(attributes)) {
6913
- span.setAttribute(key, value);
6914
- }
6915
- span.setStatus({ code: SpanStatusCode3.ERROR, message });
6916
- span.recordException(reason instanceof Error ? reason : new Error(message));
6917
- span.end();
6918
- }
6919
- async finish(resultEvent) {
6920
- var _a, _b, _c, _d, _e, _f, _g, _h, _i;
6921
- unbindRoutingContext(this.boundContext);
6922
- this.boundContext = void 0;
6923
- unbindSpanAttributes(this.toolEventsFrame);
6924
- this.toolEventsFrame = void 0;
6925
- unbindSpanAttributes(this.promptToolsFrame);
6926
- this.promptToolsFrame = void 0;
6927
- if (!this.traceId) {
6928
- this.resolveLiveTraceId();
6929
- }
6930
- const eventId = resultEvent.eventId || this.context.eventId;
6931
- if (!this.usageEmitted) {
6932
- const appGitSnapshot = (_b = (_a = this.analytics) == null ? void 0 : _a.getAppGitSnapshot(resultEvent.properties, eventId)) != null ? _b : {};
6933
- const usageProperties = {};
6934
- for (const key of [APP_COMMIT_SHA, APP_COMMIT_DIRTY, APP_BRANCH]) {
6935
- if (resultEvent.properties && Object.prototype.hasOwnProperty.call(resultEvent.properties, key)) {
6936
- usageProperties[key] = resultEvent.properties[key];
6937
- }
6938
- }
6939
- (_e = this.analytics) == null ? void 0 : _e._recordModelUsage(
6940
- eventId,
6941
- (_c = resultEvent.model) != null ? _c : this.context.model,
6942
- (_d = resultEvent.usage) != null ? _d : this.context.usage,
6943
- withAppGitProperties(usageProperties, appGitSnapshot),
6944
- appGitSnapshot
6945
- );
6946
- this.usageEmitted = true;
6947
- }
6948
- const spanFlush = (async () => {
6949
- var _a2;
6950
- try {
6951
- await ((_a2 = this.analytics) == null ? void 0 : _a2._flushTracingSpans());
6952
- } catch (e) {
6953
- }
6954
- })();
6955
- if ((_g = (_f = this.analytics) == null ? void 0 : _f._shouldBlockFinishFlush()) != null ? _g : true) {
6956
- await spanFlush;
6957
- } else {
6958
- void spanFlush.catch(() => {
6959
- });
6960
- }
6961
- try {
6962
- await ((_h = this.analytics) == null ? void 0 : _h._drainInFlightPartials(eventId));
6963
- } catch (e) {
6964
- }
6965
- if (this.traceId) {
6966
- this.setProperty("trace_id", this.traceId);
6967
- }
6968
- await ((_i = this.analytics) == null ? void 0 : _i._trackAiPartial({
6969
- ...resultEvent,
6970
- eventId,
6971
- isPending: false
6972
- }));
6973
- }
6974
- trackTool(params) {
6975
- var _a, _b, _c;
6976
- const {
6977
- name,
6978
- input,
6979
- output,
6980
- error,
6981
- properties = {},
6982
- traceId: explicitTraceId,
6983
- parentSpanId: explicitParentSpanId
6984
- } = params;
6985
- const { startTimeMs, endTimeMs, durationMs } = resolveToolTiming(params);
6986
- if (this.directShipper) {
6987
- const activeContext = (_a = getExplicitTraceContext(explicitTraceId, explicitParentSpanId)) != null ? _a : getActiveTraceContext();
6988
- const traceIdB64 = this.ensureTraceId(activeContext.traceIdB64);
6989
- const { parentSpanIdB64 } = activeContext;
6990
- const spanIdB64 = base64Encode2(randomBytes2(8));
6991
- const inputStr = input !== void 0 ? stringifyBounded(input) : void 0;
6992
- const outputStr = output !== void 0 ? stringifyBounded(output) : void 0;
6993
- this.directShipper.sendToolSpan({
6994
- name,
6995
- spanId: spanIdB64,
6996
- input: inputStr,
6997
- output: outputStr,
6998
- durationMs,
6999
- startTimeMs,
7000
- endTimeMs,
7001
- error: error ? error instanceof Error ? error.message : String(error) : void 0,
7002
- properties: {
7003
- ...getPropertiesFromContext(this.context),
7004
- ...properties
7005
- },
7006
- traceId: traceIdB64,
7007
- parentSpanId: parentSpanIdB64
7008
- });
7009
- if ((_b = this.analytics) == null ? void 0 : _b.debugLogs) {
7010
- console.log(`[raindrop] trackTool (direct): logged tool span "${name}"`, {
7011
- input,
7012
- output,
7013
- durationMs,
7014
- error: error ? String(error) : void 0
7015
- });
7016
- }
7017
- this.emitLiveEvent({
7018
- traceId: traceIdB64,
7019
- spanId: spanIdB64,
7020
- type: "tool_result",
7021
- content: name,
7022
- timestamp: endTimeMs,
7023
- metadata: {
7024
- ...input !== void 0 ? { input } : {},
7025
- ...output !== void 0 ? { result: output } : {},
7026
- ...error ? { error: error instanceof Error ? error.message : String(error) } : {}
7027
- }
7028
- });
7029
- return;
7030
- }
7031
- const savedParent = savedParentContext(explicitTraceId, explicitParentSpanId);
7032
- const span = this.tracer.startSpan(
7033
- name,
7034
- {
7035
- startTime: startTimeMs
7036
- },
7037
- savedParent
7038
- );
7039
- const contextProperties = getPropertiesFromContext(this.context);
7040
- setAssociationProperties(span, contextProperties);
7041
- span.setAttribute("traceloop.span.kind", "tool");
7042
- setAssociationProperties(span, properties);
7043
- this.stampRouting(span);
7044
- if (input !== void 0) {
7045
- span.setAttribute("traceloop.entity.input", stringifyBounded(input));
7046
- }
7047
- if (output !== void 0) {
7048
- span.setAttribute("traceloop.entity.output", stringifyBounded(output));
7049
- }
7050
- if (durationMs !== void 0) {
7051
- span.setAttribute("traceloop.entity.duration_ms", durationMs);
7052
- }
7053
- if (error) {
7054
- const errorMessage = error instanceof Error ? error.message : String(error);
7055
- span.setStatus({ code: SpanStatusCode3.ERROR, message: errorMessage });
7056
- span.recordException(error instanceof Error ? error : new Error(errorMessage));
7057
- } else {
7058
- span.setStatus({ code: SpanStatusCode3.OK });
7059
- }
7060
- span.end(endTimeMs);
7061
- if ((_c = this.analytics) == null ? void 0 : _c.debugLogs) {
7062
- console.log(`[raindrop] trackTool: logged tool span "${name}"`, {
7063
- input,
7064
- output,
7065
- durationMs,
7066
- error: error ? String(error) : void 0
7067
- });
7068
- }
7069
- const trackToolCtx = span.spanContext();
7070
- const trackToolSpanIdHex = isValidSpanId2(trackToolCtx.spanId) ? trackToolCtx.spanId : void 0;
7071
- this.emitLiveEvent({
7072
- type: "tool_result",
7073
- spanId: trackToolSpanIdHex,
7074
- content: name,
7075
- timestamp: endTimeMs,
7076
- metadata: {
7077
- ...input !== void 0 ? { input } : {},
7078
- ...output !== void 0 ? { result: output } : {},
7079
- ...error ? { error: error instanceof Error ? error.message : String(error) } : {}
7080
- }
7081
- });
7082
- }
7083
- };
7084
-
7085
- // src/tracing/liveTracer.ts
7086
- import { context as context5, isValidSpanId as isValidSpanId3, SpanStatusCode as SpanStatusCode4, trace as trace5 } from "@opentelemetry/api";
7087
- var LiveTracer = class {
7088
- constructor(globalProperties, directShipper, routing) {
7089
- this.tracer = trace5.getTracer("traceloop.tracer");
7090
- this.globalProperties = globalProperties || {};
7091
- this.directShipper = directShipper;
7092
- this.routing = routing;
7093
- }
7094
- /** Stamp a manually-created OTel span with this tracer's client routing. */
7095
- stampRouting(span) {
7096
- if (!this.routing) return;
7097
- stampSpan(span, this.routing.projectId, this.routing.authHint);
7098
- }
7099
- emitLiveEvent(event) {
7100
- var _a, _b;
7101
- const activeSpan = trace5.getSpan(context5.active());
7102
- const activeTraceId = activeSpan == null ? void 0 : activeSpan.spanContext().traceId;
7103
- const active = getActiveTraceContext();
7104
- const traceId = (_b = (_a = event.traceId) != null ? _a : activeTraceId) != null ? _b : active.traceIdB64;
7105
- if (!traceId) return;
7106
- sendLocalDebuggerLiveEvent({
7107
- ...event,
7108
- traceId
7109
- });
7110
- }
7111
- async withSpan(params, fn, thisArg, ...args) {
7112
- const taskName = typeof params === "string" ? params : params.name;
7113
- const properties = typeof params === "string" ? {
7114
- ...this.globalProperties
7115
- } : {
7116
- ...this.globalProperties,
7117
- ...params.properties || {}
7118
- };
7119
- const inputParameters = typeof params === "string" ? void 0 : params.inputParameters;
7120
- const wrappedFn = (...fnArgs) => {
7121
- const activeSpan = trace5.getSpan(context5.active());
7122
- if (activeSpan) {
7123
- this.stampRouting(activeSpan);
7124
- }
7125
- if (this.routing) {
7126
- return withRoutingContext(this.routing, () => fn.apply(thisArg, fnArgs));
7127
- }
7128
- return fn.apply(thisArg, fnArgs);
7129
- };
7130
- return withTask(
7131
- {
7132
- name: taskName,
7133
- associationProperties: properties,
7134
- inputParameters,
7135
- traceContent: params.traceContent,
7136
- suppressTracing: params.suppressTracing
7137
- },
7138
- wrappedFn,
7139
- ...args
7140
- );
7141
- }
7142
- trackTool(params) {
7143
- var _a, _b;
7144
- const {
7145
- name,
7146
- input,
7147
- output,
7148
- error,
7149
- properties = {},
7150
- traceId: explicitTraceId,
7151
- parentSpanId: explicitParentSpanId
7152
- } = params;
7153
- const { startTimeMs, endTimeMs, durationMs } = resolveToolTiming(params);
7154
- if (this.directShipper) {
7155
- const { traceIdB64, parentSpanIdB64 } = (_a = getExplicitTraceContext(explicitTraceId, explicitParentSpanId)) != null ? _a : getActiveTraceContext();
7156
- const spanIdB64 = base64Encode2(randomBytes2(8));
7157
- const inputStr = input !== void 0 ? stringifyBounded(input) : void 0;
7158
- const outputStr = output !== void 0 ? stringifyBounded(output) : void 0;
7159
- this.directShipper.sendToolSpan({
7160
- name,
7161
- spanId: spanIdB64,
7162
- input: inputStr,
7163
- output: outputStr,
7164
- durationMs,
7165
- startTimeMs,
7166
- endTimeMs,
7167
- error: error ? error instanceof Error ? error.message : String(error) : void 0,
7168
- properties: {
7169
- ...this.globalProperties,
7170
- ...properties
7171
- },
7172
- traceId: traceIdB64,
7173
- parentSpanId: parentSpanIdB64
7174
- });
7175
- if (traceIdB64) {
7176
- this.emitLiveEvent({
7177
- traceId: traceIdB64,
7178
- spanId: spanIdB64,
7179
- type: "tool_result",
7180
- content: name,
7181
- timestamp: endTimeMs,
7182
- metadata: {
7183
- ...input !== void 0 ? { input } : {},
7184
- ...output !== void 0 ? { result: output } : {},
7185
- ...error ? { error: error instanceof Error ? error.message : String(error) } : {}
7186
- }
7187
- });
7188
- }
7189
- return;
7190
- }
7191
- const span = this.tracer.startSpan(
7192
- name,
7193
- {
7194
- startTime: startTimeMs
7195
- },
7196
- savedParentContext(explicitTraceId, explicitParentSpanId)
7197
- );
7198
- this.stampRouting(span);
7199
- Object.entries(this.globalProperties).forEach(([key, value]) => {
7200
- span.setAttribute("traceloop.association.properties." + key, String(value));
7201
- });
7202
- Object.entries(properties).forEach(([key, value]) => {
7203
- span.setAttribute("traceloop.association.properties." + key, String(value));
7204
- });
7205
- span.setAttribute("traceloop.span.kind", "tool");
7206
- if (input !== void 0) {
7207
- span.setAttribute("traceloop.entity.input", stringifyBounded(input));
7208
- }
7209
- if (output !== void 0) {
7210
- span.setAttribute("traceloop.entity.output", stringifyBounded(output));
7211
- }
7212
- if (durationMs !== void 0) {
7213
- span.setAttribute("traceloop.entity.duration_ms", durationMs);
7214
- }
7215
- if (error) {
7216
- const errorMessage = error instanceof Error ? error.message : String(error);
7217
- span.setStatus({ code: SpanStatusCode4.ERROR, message: errorMessage });
7218
- span.recordException(error instanceof Error ? error : new Error(errorMessage));
7219
- } else {
7220
- span.setStatus({ code: SpanStatusCode4.OK });
7221
- }
7222
- span.end(endTimeMs);
7223
- const ctx = span.spanContext();
7224
- const traceId = ctx.traceId || ((_b = trace5.getSpan(context5.active())) == null ? void 0 : _b.spanContext().traceId);
7225
- const spanIdHex = isValidSpanId3(ctx.spanId) ? ctx.spanId : void 0;
7226
- if (traceId) {
7227
- this.emitLiveEvent({
7228
- traceId,
7229
- spanId: spanIdHex,
7230
- type: "tool_result",
7231
- content: name,
7232
- timestamp: endTimeMs,
7233
- metadata: {
7234
- ...input !== void 0 ? { input } : {},
7235
- ...output !== void 0 ? { result: output } : {},
7236
- ...error ? { error: error instanceof Error ? error.message : String(error) } : {}
7237
- }
7238
- });
7239
- }
7240
- }
7241
- };
7242
-
7243
- // src/tracing/tracer-core.ts
7244
- if (localDebuggerEnabled()) {
7245
- if (!process.env.OTEL_EXPORTER_OTLP_PROTOCOL) {
7246
- process.env.OTEL_EXPORTER_OTLP_PROTOCOL = "http/json";
7247
- }
7248
- if (!process.env.OTEL_EXPORTER_OTLP_TRACES_PROTOCOL) {
7249
- process.env.OTEL_EXPORTER_OTLP_TRACES_PROTOCOL = "http/json";
7250
- }
7251
- }
7252
- var DropSpanExporter = class {
7253
- export(_spans, resultCallback) {
7254
- resultCallback({ code: 0 });
7255
- }
7256
- shutdown() {
7257
- return Promise.resolve();
7258
- }
7259
- };
7260
- var CompositeSpanProcessor = class {
7261
- constructor(requiredProcessors, bestEffortProcessors) {
7262
- this.requiredProcessors = requiredProcessors;
7263
- this.bestEffortProcessors = bestEffortProcessors;
7264
- }
7265
- onStart(span, parentContext) {
7266
- for (const processor of this.requiredProcessors) {
7267
- processor.onStart(span, parentContext);
7268
- }
7269
- for (const processor of this.bestEffortProcessors) {
7270
- try {
7271
- processor.onStart(span, parentContext);
7272
- } catch (e) {
7273
- }
7274
- }
7275
- }
7276
- onEnd(span) {
7277
- for (const processor of this.requiredProcessors) {
7278
- processor.onEnd(span);
7279
- }
7280
- for (const processor of this.bestEffortProcessors) {
7281
- try {
7282
- processor.onEnd(span);
7283
- } catch (e) {
7284
- }
7285
- }
7286
- }
7287
- async forceFlush() {
7288
- const requiredFlushes = this.requiredProcessors.map(
7289
- (processor) => callProcessorLifecycle(processor, "forceFlush")
7290
- );
7291
- const bestEffortFlushes = this.bestEffortProcessors.map(
7292
- (processor) => callBestEffortProcessorLifecycle(processor, "forceFlush")
7293
- );
7294
- const [requiredResults] = await Promise.all([
7295
- Promise.allSettled(requiredFlushes),
7296
- Promise.allSettled(bestEffortFlushes)
7297
- ]);
7298
- throwFirstRejected(requiredResults);
7299
- }
7300
- async shutdown() {
7301
- const requiredShutdowns = this.requiredProcessors.map(
7302
- (processor) => callProcessorLifecycle(processor, "shutdown")
7303
- );
7304
- const bestEffortShutdowns = this.bestEffortProcessors.map(
7305
- (processor) => callBestEffortProcessorLifecycle(processor, "shutdown")
7306
- );
7307
- const [requiredResults] = await Promise.all([
7308
- Promise.allSettled(requiredShutdowns),
7309
- Promise.allSettled(bestEffortShutdowns)
7310
- ]);
7311
- throwFirstRejected(requiredResults);
7312
- }
7313
- };
7314
- function callProcessorLifecycle(processor, method) {
7315
- try {
7316
- return processor[method]();
7317
- } catch (error) {
7318
- return Promise.reject(error);
7319
- }
7320
- }
7321
- function callBestEffortProcessorLifecycle(processor, method) {
7322
- try {
7323
- return processor[method]().catch(() => {
7324
- });
7325
- } catch (e) {
7326
- return Promise.resolve();
7327
- }
7328
- }
7329
- function throwFirstRejected(results) {
7330
- const rejected = results.find(
7331
- (result) => result.status === "rejected"
7332
- );
7333
- if (rejected) {
7334
- throw rejected.reason;
7335
- }
7336
- }
7337
- function isLocalDebuggerUrl(baseUrl) {
7338
- try {
7339
- const url = new URL(baseUrl);
7340
- if (url.protocol !== "http:" && url.protocol !== "https:") {
7341
- return false;
7342
- }
7343
- const hostname = url.hostname.toLowerCase();
7344
- return hostname === "localhost" || hostname.endsWith(".localhost") || hostname === "0.0.0.0" || hostname === "127.0.0.1" || hostname.startsWith("127.") || hostname === "::1" || hostname === "[::1]";
7345
- } catch (e) {
7346
- return false;
7347
- }
7348
- }
7349
- function resolveLocalDebuggerExporterBaseUrl(baseUrlOpt) {
7350
- const localDebuggerUrl = resolveLocalDebuggerBaseUrl(baseUrlOpt);
7351
- if (!localDebuggerUrl || !isLocalDebuggerUrl(localDebuggerUrl)) {
7352
- return null;
7353
- }
7354
- return localDebuggerUrl;
7355
- }
7356
- function createLocalDebuggerOtlpExporter(config) {
7357
- return new OTLPHttpTraceExporter(config);
7358
- }
7359
- function parseTraceloopHeaders(value) {
7360
- const headers = {};
7361
- for (const entry of value.split(",")) {
7362
- const keyPairPart = entry.split(";")[0];
7363
- const sep = keyPairPart.indexOf("=");
7364
- if (sep <= 0) continue;
7365
- try {
7366
- const key = decodeURIComponent(keyPairPart.slice(0, sep).trim());
7367
- const val = decodeURIComponent(keyPairPart.slice(sep + 1).trim());
7368
- if (key.length > 0 && val.length > 0) headers[key] = val;
7369
- } catch (e) {
7370
- }
7371
- }
7372
- return headers;
7373
- }
7374
- function traceloopDefaultHeaders(writeKey) {
7375
- const env = process.env.TRACELOOP_HEADERS;
7376
- if (env) {
7377
- const parsed = parseTraceloopHeaders(env);
7378
- if (Object.keys(parsed).length > 0) return parsed;
7379
- }
7380
- return { Authorization: `Bearer ${writeKey}` };
7381
- }
7382
- function createLocalDebuggerSpanProcessor(options) {
7383
- const localDebuggerUrl = resolveLocalDebuggerExporterBaseUrl(options.localDebuggerUrlOpt);
7384
- if (!localDebuggerUrl) {
7385
- return void 0;
7386
- }
7387
- const localExporter = createLocalDebuggerOtlpExporter({
7388
- url: `${localDebuggerUrl}traces`,
7389
- headers: {}
7390
- });
7391
- if (!options.routeReplayTraces) {
7392
- const exportLocal = localExporter.export.bind(localExporter);
7393
- localExporter.export = (spans, callback) => {
7394
- const localSpans = spans.filter(
7395
- (span) => {
7396
- var _a;
7397
- return ((_a = replayTraceDestinationFor(span)) == null ? void 0 : _a.kind) !== "raindrop";
7398
- }
7399
- );
7400
- if (localSpans.length === 0) callback({ code: 0 });
7401
- else exportLocal(localSpans, callback);
7402
- };
7403
- }
7404
- try {
7405
- return createSpanProcessor({
7406
- apiKey: options.writeKey,
7407
- baseUrl: localDebuggerUrl,
7408
- routeReplayTraces: options.routeReplayTraces,
7409
- disableBatch: options.disableBatching,
7410
- exporter: localExporter,
7411
- headers: {},
7412
- piiRedaction: options.piiRedaction,
7413
- allowedInstrumentationLibraries: options.allowedInstrumentationLibraries
7414
- });
7415
- } catch (error) {
7416
- console.warn(
7417
- "[raindrop] Failed to initialize local debugger trace exporter.",
7418
- error instanceof Error ? error.message : error
7419
- );
7420
- return void 0;
7421
- }
7422
- }
7423
- var warnedSpanNormalizeFailure = false;
7424
- var INVALID_OTEL_SPAN_ID = "0000000000000000";
7425
- function normalizeSpanForV1Exporter(span) {
7426
- var _a;
7427
- if (!span) {
7428
- return;
7429
- }
7430
- if (span.instrumentationLibrary == null && span.instrumentationScope != null) {
7431
- try {
7432
- span.instrumentationLibrary = span.instrumentationScope;
7433
- } catch (error) {
7434
- if (!warnedSpanNormalizeFailure) {
7435
- warnedSpanNormalizeFailure = true;
7436
- console.warn(
7437
- "[raindrop] Could not normalize an OTEL v2 span for export (instrumentationLibrary alias failed). Spans may not reach Raindrop.",
7438
- error instanceof Error ? error.message : error
7439
- );
7440
- }
7441
- }
7442
- }
7443
- if (span.parentSpanId == null && ((_a = span.parentSpanContext) == null ? void 0 : _a.spanId) != null && span.parentSpanContext.spanId !== INVALID_OTEL_SPAN_ID) {
7444
- try {
7445
- span.parentSpanId = span.parentSpanContext.spanId;
7446
- } catch (e) {
7447
- }
7448
- }
7449
- }
7450
- function withV2SpanCompat(processor) {
7451
- return {
7452
- onStart(span, parentContext) {
7453
- processor.onStart(span, parentContext);
7454
- },
7455
- onEnd(span) {
7456
- try {
7457
- normalizeSpanForV1Exporter(span);
7458
- } catch (e) {
7459
- }
7460
- processor.onEnd(span);
7461
- },
7462
- forceFlush() {
7463
- return processor.forceFlush();
7464
- },
7465
- shutdown() {
7466
- return processor.shutdown();
7467
- }
7468
- };
7469
- }
7470
- try {
7471
- const _bedrockProto = BedrockInstrumentation.prototype;
7472
- _bedrockProto._wrapPromise = function(span, promise) {
7473
- const inst = this;
7474
- return promise.then(async (result) => {
7475
- const rec = result;
7476
- const body = rec == null ? void 0 : rec.body;
7477
- const isStreamBody = body != null && typeof body === "object" && Symbol.asyncIterator in body && !(body instanceof Uint8Array);
7478
- if (!isStreamBody) {
7479
- try {
7480
- await inst._endSpan({ span, result });
7481
- } catch (e) {
7482
- console.warn(
7483
- "[raindrop] Bedrock instrumentation could not process response \u2014 passing through unchanged.",
7484
- e instanceof Error ? e.message : e
7485
- );
7486
- span.setStatus({
7487
- code: SpanStatusCode5.ERROR,
7488
- message: e instanceof Error ? e.message : String(e)
7489
- });
7490
- span.end();
7491
- }
7492
- return result;
7493
- }
7494
- const origIterator = body[Symbol.asyncIterator]();
7495
- const chunks = [];
7496
- let spanEnded = false;
7497
- rec.body = {
7498
- [Symbol.asyncIterator]() {
7499
- return {
7500
- async next() {
7501
- try {
7502
- const iterResult = await origIterator.next();
7503
- if (iterResult.done) {
7504
- try {
7505
- async function* replay() {
7506
- for (const c of chunks) yield c;
7507
- }
7508
- await inst._endSpan({
7509
- span,
7510
- result: { ...rec, body: replay() }
7511
- });
7512
- } catch (e) {
7513
- console.warn(
7514
- "[raindrop] Bedrock instrumentation could not process streaming response \u2014 passing through unchanged.",
7515
- e instanceof Error ? e.message : e
7516
- );
7517
- if (!spanEnded) {
7518
- span.setStatus({
7519
- code: SpanStatusCode5.ERROR,
7520
- message: e instanceof Error ? e.message : String(e)
7521
- });
7522
- span.end();
7523
- }
7524
- }
7525
- spanEnded = true;
7526
- return { done: true, value: void 0 };
7527
- }
7528
- chunks.push(iterResult.value);
7529
- return { done: false, value: iterResult.value };
7530
- } catch (error) {
7531
- if (!spanEnded) {
7532
- const msg = error instanceof Error ? error.message : String(error);
7533
- span.setStatus({ code: SpanStatusCode5.ERROR, message: msg });
7534
- span.recordException(error);
7535
- span.end();
7536
- spanEnded = true;
7537
- }
7538
- throw error;
7539
- }
7540
- },
7541
- async return(value) {
7542
- var _a;
7543
- if (!spanEnded) {
7544
- span.end();
7545
- spanEnded = true;
7546
- }
7547
- await ((_a = origIterator.return) == null ? void 0 : _a.call(origIterator, value));
7548
- return { done: true, value: void 0 };
7549
- }
7550
- };
7551
- }
7552
- };
7553
- return result;
7554
- }).catch((error) => {
7555
- span.setStatus({
7556
- code: SpanStatusCode5.ERROR,
7557
- message: error.message
7558
- });
7559
- span.recordException(error);
7560
- span.end();
7561
- throw error;
7562
- });
7563
- };
7564
- _bedrockProto._extractVendorAndModel = function(modelId) {
7565
- if (!modelId) {
7566
- return { modelVendor: "", model: "" };
7567
- }
7568
- const parts = modelId.split(".");
7569
- if (parts.length >= 3 && /^[a-z]{2}$/.test(parts[0])) {
7570
- return {
7571
- modelVendor: parts[1] || "",
7572
- model: parts.slice(2).join(".")
7573
- };
7574
- }
7575
- return {
7576
- modelVendor: parts[0] || "",
7577
- model: parts[1] || ""
7578
- };
7579
- };
7580
- } catch (e) {
7581
- }
7582
- function patchBedrockStreamingBug(inst) {
7583
- const anyInst = inst;
7584
- const origEndSpan = anyInst._endSpan.bind(anyInst);
7585
- anyInst._wrapPromise = function(span, promise) {
7586
- return promise.then(async (result) => {
7587
- const rec = result;
7588
- const body = rec == null ? void 0 : rec.body;
7589
- const isStreamBody = body != null && typeof body === "object" && Symbol.asyncIterator in body && !(body instanceof Uint8Array);
7590
- if (!isStreamBody) {
7591
- await origEndSpan({ span, result });
7592
- return result;
7593
- }
7594
- const origIterator = body[Symbol.asyncIterator]();
7595
- const chunks = [];
7596
- let spanEnded = false;
7597
- rec.body = {
7598
- [Symbol.asyncIterator]() {
7599
- return {
7600
- async next() {
7601
- try {
7602
- const iterResult = await origIterator.next();
7603
- if (iterResult.done) {
7604
- async function* replay() {
7605
- for (const c of chunks) yield c;
7606
- }
7607
- await origEndSpan({
7608
- span,
7609
- result: { ...rec, body: replay() }
7610
- });
7611
- spanEnded = true;
7612
- return { done: true, value: void 0 };
7613
- }
7614
- chunks.push(iterResult.value);
7615
- return { done: false, value: iterResult.value };
7616
- } catch (error) {
7617
- if (!spanEnded) {
7618
- const msg = error instanceof Error ? error.message : String(error);
7619
- span.setStatus({ code: SpanStatusCode5.ERROR, message: msg });
7620
- span.recordException(error);
7621
- span.end();
7622
- spanEnded = true;
7623
- }
7624
- throw error;
7625
- }
7626
- },
7627
- async return(value) {
7628
- var _a;
7629
- if (!spanEnded) {
7630
- span.end();
7631
- spanEnded = true;
7632
- }
7633
- await ((_a = origIterator.return) == null ? void 0 : _a.call(origIterator, value));
7634
- return { done: true, value: void 0 };
7635
- }
7636
- };
7637
- }
7638
- };
7639
- return result;
7640
- }).catch((error) => {
7641
- span.setStatus({
7642
- code: SpanStatusCode5.ERROR,
7643
- message: error.message
7644
- });
7645
- span.recordException(error);
7646
- span.end();
7647
- throw error;
7648
- });
7649
- };
7650
- }
7651
- function createDefaultInstrumentations() {
7652
- const bedrockInst = new BedrockInstrumentation();
7653
- patchBedrockStreamingBug(bedrockInst);
7654
- return [
7655
- new OpenAIInstrumentation({
7656
- enrichTokens: (process.env.TRACELOOP_ENRICH_TOKENS || "true").toLowerCase() === "true"
7657
- }),
7658
- new AnthropicInstrumentation(),
7659
- new CohereInstrumentation(),
7660
- bedrockInst,
7661
- new VertexAIInstrumentation(),
7662
- new AIPlatformInstrumentation(),
7663
- new PineconeInstrumentation(),
7664
- new TogetherInstrumentation(),
7665
- new ChromaDBInstrumentation(),
7666
- new QdrantInstrumentation(),
7667
- new LangChainInstrumentation(),
7668
- new LlamaIndexInstrumentation()
7669
- ];
7670
- }
7671
- function createManualInstrumentations(instrumentModules) {
7672
- const instrumentations = [];
7673
- if (instrumentModules.openAI) {
7674
- const inst = new OpenAIInstrumentation();
7675
- inst.manuallyInstrument(instrumentModules.openAI);
7676
- instrumentations.push(inst);
7677
- }
7678
- if (instrumentModules.anthropic) {
7679
- const inst = new AnthropicInstrumentation();
7680
- inst.manuallyInstrument(instrumentModules.anthropic);
7681
- instrumentations.push(inst);
7682
- }
7683
- if (instrumentModules.cohere) {
7684
- const inst = new CohereInstrumentation();
7685
- inst.manuallyInstrument(instrumentModules.cohere);
7686
- instrumentations.push(inst);
7687
- }
7688
- if (instrumentModules.bedrock) {
7689
- const inst = new BedrockInstrumentation();
7690
- patchBedrockStreamingBug(inst);
7691
- inst.manuallyInstrument(instrumentModules.bedrock);
7692
- instrumentations.push(inst);
7693
- }
7694
- if (instrumentModules.google_vertexai) {
7695
- const inst = new VertexAIInstrumentation();
7696
- inst.manuallyInstrument(instrumentModules.google_vertexai);
7697
- instrumentations.push(inst);
7698
- }
7699
- if (instrumentModules.google_aiplatform) {
7700
- const inst = new AIPlatformInstrumentation();
7701
- inst.manuallyInstrument(instrumentModules.google_aiplatform);
7702
- instrumentations.push(inst);
7703
- }
7704
- if (instrumentModules.pinecone) {
7705
- const inst = new PineconeInstrumentation();
7706
- inst.manuallyInstrument(instrumentModules.pinecone);
7707
- instrumentations.push(inst);
7708
- }
7709
- if (instrumentModules.together) {
7710
- const inst = new TogetherInstrumentation();
7711
- inst.manuallyInstrument(instrumentModules.together);
7712
- instrumentations.push(inst);
7713
- }
7714
- if (instrumentModules.chromadb) {
7715
- const inst = new ChromaDBInstrumentation();
7716
- inst.manuallyInstrument(instrumentModules.chromadb);
7717
- instrumentations.push(inst);
7718
- }
7719
- if (instrumentModules.qdrant) {
7720
- const inst = new QdrantInstrumentation();
7721
- inst.manuallyInstrument(instrumentModules.qdrant);
7722
- instrumentations.push(inst);
7723
- }
7724
- instrumentations.push(new LangChainInstrumentation());
7725
- if (instrumentModules.llamaIndex) {
7726
- const inst = new LlamaIndexInstrumentation();
7727
- inst.manuallyInstrument(instrumentModules.llamaIndex);
7728
- instrumentations.push(inst);
7729
- }
7730
- return instrumentations;
7731
- }
7732
- function createConfiguredInstrumentations(options) {
7733
- if (options.instrumentModules && Object.keys(options.instrumentModules).length > 0) {
7734
- return createManualInstrumentations(options.instrumentModules);
7735
- }
7736
- return createDefaultInstrumentations();
7737
- }
7738
- function getCurrentTraceId() {
7739
- var _a;
7740
- return (_a = trace6.getSpan(context6.active())) == null ? void 0 : _a.spanContext().traceId;
7741
- }
7742
- var tracing = (analytics, apiUrl, writeKey, options, isDebug = false) => {
7743
- var _a;
7744
- process.env.TRACELOOP_TELEMETRY = "false";
7745
- const {
7746
- logLevel: logLevel2,
7747
- useExternalOtel,
7748
- tracingEnabled,
7749
- disableBatching,
7750
- bypassOtelForTools,
7751
- directEndpoint,
7752
- localDebuggerUrl,
7753
- cloudEnabled,
7754
- projectId,
7755
- flushTimeoutMs,
7756
- redactTracePii,
7757
- redactPiiFields,
7758
- remotePiiConfig,
7759
- mask,
7760
- ...otherOptions
7761
- } = options;
7762
- const cloudEnabledResolved = cloudEnabled != null ? cloudEnabled : true;
7763
- const localTracePii = typeof redactTracePii === "boolean" ? redactTracePii : void 0;
7764
- const spanPiiFields = compileSpanPiiFields(redactPiiFields == null ? void 0 : redactPiiFields.span, "[raindrop]");
7765
- if ((redactPiiFields == null ? void 0 : redactPiiFields.span) && localTracePii !== true && !remotePiiConfig) {
7766
- rateLimitedLog(
7767
- "js-sdk.pii_span_fields_without_redaction",
7768
- () => console.warn(
7769
- "[raindrop] redactPiiFields.span is set but redactTracePii is off; no span is redacted. Set redactTracePii: true to use it."
7770
- )
7771
- );
7772
- }
7773
- const piiRedaction2 = {
7774
- local: localTracePii,
7775
- remote: remotePiiConfig,
7776
- apiUrl: directEndpoint != null ? directEndpoint : apiUrl,
7777
- writeKey: cloudEnabledResolved ? writeKey : void 0,
7778
- spanFields: spanPiiFields,
7779
- mask: typeof mask === "function" ? mask : void 0
7780
- };
7781
- if (localTracePii === true) {
7782
- requestLocalTracePiiRedaction(piiRedaction2.apiUrl, piiRedaction2.writeKey);
7783
- }
7784
- const authHint = authHintForKey(writeKey);
7785
- const clientTracingExports = !useExternalOtel && cloudEnabledResolved && tracingEnabled !== false;
7786
- registerClientKey(authHint, clientTracingExports);
7787
- const withProjectIdHeaders = (existing) => {
7788
- if (!projectId) {
7789
- return existing;
7790
- }
7791
- return {
7792
- ...traceloopDefaultHeaders(writeKey),
7793
- ...existing != null ? existing : {},
7794
- ...projectIdHeaders(projectId)
7795
- };
7796
- };
7797
- if (isDebug) {
7798
- const mode = useExternalOtel ? "(external OTEL mode)" : tracingEnabled === false ? "(tracing disabled)" : "";
7799
- console.log("[raindrop] Initializing tracing", mode);
7800
- if (bypassOtelForTools) {
7801
- console.log("[raindrop] bypassOtelForTools enabled \u2014 tool spans ship directly via HTTP");
7802
- }
7803
- }
7804
- const directShipper = bypassOtelForTools ? new DirectTraceShipper({
7805
- appGitSnapshot: (properties) => analytics.getAppGitSnapshot(properties),
7806
- writeKey,
7807
- endpoint: directEndpoint != null ? directEndpoint : apiUrl,
7808
- debug: isDebug,
7809
- enabled: tracingEnabled !== false,
7810
- localDebuggerUrl,
7811
- cloudEnabled: cloudEnabledResolved,
7812
- projectId,
7813
- flushTimeoutMs,
7814
- redactTracePii: localTracePii,
7815
- remotePiiConfig,
7816
- spanPiiFields,
7817
- mask: piiRedaction2.mask
7818
- }) : void 0;
7819
- let traceloopInitialized = false;
7820
- let claimedPipeline = false;
7821
- const activeInteractions = new WeakValueMap();
7822
- const activeInteractionsByEventId = new WeakValueMap();
7823
- try {
7824
- if (useExternalOtel) {
7825
- initialize({
7826
- baseUrl: apiUrl,
7827
- apiKey: writeKey,
7828
- logLevel: logLevel2,
7829
- // Traceloop's init banner ("Traceloop exporting traces to <baseUrl>") is
7830
- // misleading inside our wrapper: in external-OTEL mode we create no
7831
- // exporter at all (tracingEnabled: false). Suppress it.
7832
- silenceInitializationMessage: true,
7833
- tracingEnabled: false
7834
- // DO NOT create NodeSDK - customer has their own
7835
- });
7836
- traceloopInitialized = true;
7837
- markTraceloopConfiguredWithoutClaim();
7838
- if (isDebug) {
7839
- console.log(
7840
- "[raindrop] External OTEL mode active. Add raindrop.createSpanProcessor() to your NodeSDK's spanProcessors. Register instrumentations (AnthropicInstrumentation, etc.) on your NodeSDK."
7841
- );
7842
- }
7843
- if (otherOptions.instrumentModules && Object.keys(otherOptions.instrumentModules).length > 0) {
7844
- if (isDebug) {
7845
- console.log(
7846
- "[raindrop] instrumentModules configured. Call raindrop.getInstrumentations() to get instrumentation instances for your NodeSDK."
7847
- );
7848
- }
7849
- }
7850
- } else {
7851
- const localDebuggerProcessor = createLocalDebuggerSpanProcessor({
7852
- writeKey,
7853
- disableBatching,
7854
- allowedInstrumentationLibraries: ALL_INSTRUMENTATION_LIBRARIES,
7855
- localDebuggerUrlOpt: localDebuggerUrl,
7856
- routeReplayTraces: !cloudEnabledResolved,
7857
- piiRedaction: piiRedaction2
7858
- });
7859
- if (!cloudEnabledResolved) {
7860
- if (localDebuggerProcessor) {
7861
- initialize({
7862
- baseUrl: apiUrl,
7863
- apiKey: writeKey,
7864
- ...otherOptions,
7865
- exporter: new DropSpanExporter(),
7866
- logLevel: logLevel2,
7867
- silenceInitializationMessage: true,
7868
- tracingEnabled: tracingEnabled !== false,
7869
- disableBatch: disableBatching,
7870
- processor: new CompositeSpanProcessor(
7871
- [new RaindropContextSpanProcessor((properties) => analytics.getAppGitSnapshot(properties)), localDebuggerProcessor],
7872
- []
7873
- ),
7874
- instrumentations: createConfiguredInstrumentations(otherOptions)
7875
- });
7876
- traceloopInitialized = true;
7877
- markTraceloopConfiguredWithoutClaim();
7878
- } else {
7879
- const replayOnlyProcessor = createSpanProcessor({
7880
- exporter: new DropSpanExporter(),
7881
- routeReplayTraces: true,
7882
- disableBatch: disableBatching,
7883
- allowedInstrumentationLibraries: ALL_INSTRUMENTATION_LIBRARIES,
7884
- piiRedaction: piiRedaction2
7885
- });
7886
- initialize({
7887
- baseUrl: apiUrl,
7888
- apiKey: writeKey,
7889
- ...otherOptions,
7890
- exporter: new DropSpanExporter(),
7891
- logLevel: logLevel2,
7892
- silenceInitializationMessage: true,
7893
- tracingEnabled: tracingEnabled !== false,
7894
- disableBatch: disableBatching,
7895
- processor: new CompositeSpanProcessor(
7896
- [new RaindropContextSpanProcessor((properties) => analytics.getAppGitSnapshot(properties)), replayOnlyProcessor],
7897
- []
7898
- ),
7899
- instrumentations: createConfiguredInstrumentations(otherOptions)
7900
- });
7901
- traceloopInitialized = true;
7902
- markTraceloopConfiguredWithoutClaim();
7903
- }
7904
- } else if (tracingEnabled === false) {
7905
- traceloopInitialized = false;
7906
- } else {
7907
- const claimed = claimPipeline(authHint, projectId);
7908
- claimedPipeline = claimed;
7909
- const ownerHint = pipelineOwnerHint();
7910
- if (!claimed && authHint !== ownerHint) {
7911
- markForeignClient();
7912
- console.warn(
7913
- "[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."
7914
- );
7915
- }
7916
- if (claimed && traceloopConfiguredWithoutClaim()) {
7917
- releasePipelineClaim();
7918
- claimedPipeline = false;
7919
- console.warn(
7920
- "[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."
7921
- );
7922
- } else if (claimed) {
7923
- const exporterHeaders = (_a = withProjectIdHeaders(otherOptions.headers)) != null ? _a : traceloopDefaultHeaders(writeKey);
7924
- let guardedExporter;
7925
- try {
7926
- const callerExporter = otherOptions.exporter;
7927
- const guarded = callerExporter ? new GuardedSpanExporter(callerExporter, ownerHint) : buildGuardedExporter(apiUrl, exporterHeaders, ownerHint);
7928
- guardedExporter = new ReplayRoutingSpanExporter(guarded);
7929
- } catch (guardError) {
7930
- releasePipelineClaim();
7931
- claimedPipeline = false;
7932
- console.warn(
7933
- `[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.`
7934
- );
7935
- }
7936
- if (guardedExporter) {
7937
- const contextProcessor = new RaindropContextSpanProcessor((properties) => analytics.getAppGitSnapshot(properties));
7938
- const callerProcessor = otherOptions.processor;
7939
- const processor = new CompositeSpanProcessor(
7940
- callerProcessor ? [contextProcessor, callerProcessor] : [contextProcessor],
7941
- localDebuggerProcessor ? [localDebuggerProcessor] : []
7942
- );
7943
- try {
7944
- initialize({
7945
- baseUrl: apiUrl,
7946
- apiKey: writeKey,
7947
- ...otherOptions,
7948
- logLevel: logLevel2,
7949
- silenceInitializationMessage: true,
7950
- // This branch only runs when tracing is enabled (the disabled
7951
- // case is handled above), so tracing is always on here.
7952
- tracingEnabled: true,
7953
- disableBatch: disableBatching,
7954
- processor,
7955
- exporter: guardedExporter,
7956
- piiRedaction: piiRedaction2,
7957
- instrumentations: createConfiguredInstrumentations(otherOptions)
7958
- });
7959
- traceloopInitialized = true;
7960
- } catch (initError) {
7961
- releasePipelineClaim();
7962
- claimedPipeline = false;
7963
- throw initError;
7964
- }
7965
- }
7966
- } else {
7967
- traceloopInitialized = true;
7968
- }
7969
- }
7970
- }
7971
- } catch (error) {
7972
- if (claimedPipeline && !traceloopInitialized) {
7973
- releasePipelineClaim();
7974
- claimedPipeline = false;
7975
- }
7976
- console.warn(
7977
- "[raindrop] Failed to initialize traceloop. Spans will not be sent.",
7978
- error instanceof Error ? error.message : error
7979
- );
7980
- }
7981
- if (traceloopInitialized) {
7982
- markPipelineForExitFlush();
7983
- }
7984
- const deregisterExitFlusher = directShipper ? registerClientFlusher(async () => {
7985
- try {
7986
- await directShipper.flush();
7987
- } catch (e) {
7988
- }
7989
- }) : void 0;
7990
- const beginInteraction = (params) => {
7991
- var _a2;
7992
- const { tools, ...traceContext } = params;
7993
- if (!traceContext.eventId) {
7994
- traceContext.eventId = crypto.randomUUID();
7995
- }
7996
- const traceId = getCurrentTraceId();
7997
- const interaction = new LiveInteraction(
7998
- traceContext,
7999
- traceId,
8000
- analytics,
8001
- directShipper,
8002
- { projectId, authHint, appGit: analytics.getAppGitSnapshot(traceContext.properties, traceContext.eventId) }
8003
- );
8004
- const bound = bindRoutingContext({ projectId, authHint, appGit: analytics.getAppGitSnapshot(traceContext.properties, traceContext.eventId) }, interaction);
8005
- interaction.setBoundContext(bound);
8006
- interaction.bindPromptToolsOverride(tools);
8007
- try {
8008
- analytics._trackAiPartial({
8009
- ...traceContext,
8010
- properties: {
8011
- ...(_a2 = traceContext.properties) != null ? _a2 : {},
8012
- ...interaction.getTraceId() ? { trace_id: interaction.getTraceId() } : {}
8013
- }
8014
- });
8015
- if (interaction.getTraceId()) {
8016
- activeInteractions.set(interaction.getTraceId(), interaction);
8017
- }
8018
- activeInteractionsByEventId.set(traceContext.eventId, interaction);
8019
- } catch (error) {
8020
- unbindRoutingContext(bound);
8021
- throw error;
8022
- }
8023
- return interaction;
8024
- };
8025
- const openSubagentRun = (carrierOrHeaders, options2) => {
8026
- const resolved = resolveSubagentResume(carrierOrHeaders, options2);
8027
- if (!resolved.parent && isDebug) {
8028
- console.log(
8029
- `[raindrop] resumeSubagent(${resolved.name}): no hand-off carrier on the request; reporting as an unlinked event ${resolved.eventId}.`
8030
- );
8031
- }
8032
- const frameOwner = { subagentEventId: resolved.eventId };
8033
- const frame = bindSubagentLink(resolved.link, frameOwner);
8034
- let interaction;
8035
- try {
8036
- interaction = beginInteraction({
8037
- eventId: resolved.eventId,
8038
- event: resolved.event,
8039
- userId: resolved.userId,
8040
- ...resolved.convoId ? { convoId: resolved.convoId } : {},
8041
- ...options2.input !== void 0 ? { input: options2.input } : {},
8042
- ...options2.model !== void 0 ? { model: options2.model } : {},
8043
- ...options2.properties ? { properties: options2.properties } : {}
8044
- });
8045
- } catch (error) {
8046
- unbindSpanAttributes(frame);
8047
- throw error;
8048
- }
8049
- return new LiveSubagentRun({
8050
- interaction,
8051
- eventId: resolved.eventId,
8052
- name: resolved.name,
8053
- ...resolved.convoId ? { convoId: resolved.convoId } : {},
8054
- parent: resolved.link,
8055
- ...frame ? { frame, frameOwner } : {}
8056
- });
8057
- };
8058
- const recordModelUsage = (params) => {
8059
- try {
8060
- const attributes = [
8061
- attrString(MODEL_USAGE_ATTRIBUTES.usageSource, "manual"),
8062
- attrString(
8063
- MODEL_USAGE_ATTRIBUTES.providerName,
8064
- canonicalModelProvider(params.usage.provider)
8065
- ),
8066
- attrString(MODEL_USAGE_ATTRIBUTES.requestModel, params.model),
8067
- attrString(MODEL_USAGE_ATTRIBUTES.responseModel, params.model),
8068
- ...buildRawModelUsageAttributes({
8069
- inputTokens: params.usage.inputTokens,
8070
- outputTokens: params.usage.outputTokens,
8071
- cacheReadInputTokens: params.usage.cacheReadTokens,
8072
- cacheWriteInputTokens: params.usage.cacheWriteTokens,
8073
- reasoningTokens: params.usage.reasoningTokens,
8074
- providerReportedCost: params.usage.providerReportedCost
8075
- })
8076
- ].filter((attribute) => attribute !== void 0);
8077
- if (directShipper) {
8078
- const timeMs = Date.now();
8079
- directShipper.sendSpan({
8080
- name: "ai.model.usage",
8081
- spanKind: "llm",
8082
- properties: { ...params.appGitProperties, event_id: params.eventId },
8083
- appGitSnapshot: params.appGitSnapshot,
8084
- startTimeMs: timeMs,
8085
- endTimeMs: timeMs,
8086
- durationMs: 0,
8087
- otlpAttributes: attributes
8088
- });
8089
- return;
8090
- }
8091
- const initialAttributes = {
8092
- "traceloop.span.kind": "llm"
8093
- };
8094
- for (const [key, value] of Object.entries({
8095
- ...params.appGitProperties,
8096
- event_id: params.eventId
8097
- })) {
8098
- if (value !== void 0) {
8099
- initialAttributes[`traceloop.association.properties.${key}`] = stringifyBounded(value);
8100
- }
8101
- }
8102
- for (const [key, value] of Object.entries(params.appGitSnapshot)) {
8103
- if (typeof value === "string" || typeof value === "boolean") {
8104
- initialAttributes[key] = value;
8105
- }
8106
- }
8107
- const span = trace6.getTracer("traceloop.tracer").startSpan("ai.model.usage", { attributes: initialAttributes });
8108
- stampSpan(span, projectId, authHint);
8109
- for (const attribute of attributes) {
8110
- const value = attribute.value;
8111
- if (value.stringValue !== void 0) {
8112
- span.setAttribute(attribute.key, value.stringValue);
8113
- } else if (value.intValue !== void 0) {
8114
- const parsed = Number(value.intValue);
8115
- if (Number.isSafeInteger(parsed)) span.setAttribute(attribute.key, parsed);
8116
- } else if (value.doubleValue !== void 0) {
8117
- span.setAttribute(attribute.key, value.doubleValue);
8118
- } else if (value.boolValue !== void 0) {
8119
- span.setAttribute(attribute.key, value.boolValue);
8120
- }
8121
- }
8122
- span.end();
8123
- } catch (e) {
8124
- }
8125
- };
8126
- return {
8127
- /**
8128
- * Returns instrumentation instances for your NodeSDK.
8129
- * Add these to your NodeSDK when using useExternalOtel: true.
8130
- *
8131
- * - If `instrumentModules` is provided: returns only those specific instrumentations
8132
- * - If `instrumentModules` is NOT provided: returns ALL default instrumentations (auto-instrumentation)
8133
- *
8134
- * @example
8135
- * ```typescript
8136
- * const raindrop = new Raindrop({
8137
- * useExternalOtel: true,
8138
- * // instrumentModules is optional - if omitted, all instrumentations are returned
8139
- * });
8140
- *
8141
- * const sdk = new NodeSDK({
8142
- * spanProcessors: [raindrop.createSpanProcessor()],
8143
- * instrumentations: raindrop.getInstrumentations(),
8144
- * });
8145
- * sdk.start();
8146
- * ```
8147
- */
8148
- getInstrumentations() {
8149
- if (!useExternalOtel) {
8150
- console.warn(
8151
- "[raindrop] getInstrumentations() is meant for useExternalOtel: true. In default mode, instrumentations are automatically registered."
8152
- );
8153
- }
8154
- if (otherOptions.instrumentModules && Object.keys(otherOptions.instrumentModules).length > 0) {
8155
- return createManualInstrumentations(
8156
- otherOptions.instrumentModules
8157
- );
8158
- }
8159
- return createDefaultInstrumentations();
8160
- },
8161
- /**
8162
- * Creates a span processor to add to your NodeSDK.
8163
- * This sends spans to Raindrop.
8164
- *
8165
- * @example
8166
- * ```typescript
8167
- * const sdk = new NodeSDK({
8168
- * spanProcessors: [raindrop.createSpanProcessor()],
8169
- * instrumentations: raindrop.getInstrumentations(),
8170
- * });
8171
- * ```
8172
- */
8173
- createSpanProcessor(processorOptions) {
8174
- if (!useExternalOtel) {
8175
- console.warn(
8176
- "[raindrop] createSpanProcessor() is meant for useExternalOtel: true. In default mode, spans are automatically sent to Raindrop."
8177
- );
8178
- }
8179
- if (!traceloopInitialized) {
8180
- console.error("[raindrop] Cannot create span processor - traceloop failed to initialize.");
8181
- return {
8182
- forceFlush: async () => {
8183
- },
8184
- onStart: () => {
8185
- },
8186
- onEnd: () => {
8187
- },
8188
- shutdown: async () => {
8189
- }
8190
- };
8191
- }
8192
- if (!cloudEnabledResolved) {
8193
- const localOnlyProcessor = createLocalDebuggerSpanProcessor({
8194
- writeKey,
8195
- disableBatching,
8196
- allowedInstrumentationLibraries: processorOptions == null ? void 0 : processorOptions.allowedInstrumentationLibraries,
8197
- localDebuggerUrlOpt: localDebuggerUrl,
8198
- routeReplayTraces: true,
8199
- piiRedaction: piiRedaction2
8200
- });
8201
- return withV2SpanCompat(
8202
- localOnlyProcessor != null ? localOnlyProcessor : {
8203
- forceFlush: async () => {
8204
- },
8205
- onStart: () => {
8206
- },
8207
- onEnd: () => {
8208
- },
8209
- shutdown: async () => {
8210
- }
8211
- }
8212
- );
8213
- }
8214
- const headers = withProjectIdHeaders(processorOptions == null ? void 0 : processorOptions.headers);
8215
- const productionProcessor = createSpanProcessor({
8216
- baseUrl: apiUrl,
8217
- apiKey: writeKey,
8218
- disableBatch: disableBatching,
8219
- ...processorOptions != null ? processorOptions : {},
8220
- routeReplayTraces: true,
8221
- ...headers ? { headers } : {},
8222
- piiRedaction: piiRedaction2
8223
- });
8224
- const localDebuggerProcessor = createLocalDebuggerSpanProcessor({
8225
- writeKey,
8226
- disableBatching,
8227
- allowedInstrumentationLibraries: processorOptions == null ? void 0 : processorOptions.allowedInstrumentationLibraries,
8228
- localDebuggerUrlOpt: localDebuggerUrl,
8229
- piiRedaction: piiRedaction2
8230
- });
8231
- const contextProcessor = new RaindropContextSpanProcessor((properties) => analytics.getAppGitSnapshot(properties));
8232
- return withV2SpanCompat(
8233
- new CompositeSpanProcessor(
8234
- [contextProcessor, productionProcessor],
8235
- localDebuggerProcessor ? [localDebuggerProcessor] : []
8236
- )
8237
- );
8238
- },
8239
- begin(traceContext) {
8240
- return beginInteraction(traceContext);
8241
- },
8242
- recordModelUsage,
8243
- resumeSubagent(carrierOrHeaders, options2 = {}) {
8244
- return openSubagentRun(carrierOrHeaders, options2);
8245
- },
8246
- withSubagentRun(carrierOrHeaders, fn, options2 = {}) {
8247
- return openSubagentRun(carrierOrHeaders, options2).use(fn);
8248
- },
8249
- getActiveInteraction(eventId) {
8250
- const interactionByEventId = activeInteractionsByEventId.get(eventId);
8251
- if (interactionByEventId) {
8252
- return interactionByEventId;
8253
- }
8254
- const traceId = getCurrentTraceId();
8255
- if (traceId) {
8256
- const interactionByTraceId = activeInteractions.get(traceId);
8257
- if (interactionByTraceId) {
8258
- return interactionByTraceId;
8259
- }
8260
- }
8261
- const interaction = new LiveInteraction({ eventId }, traceId, analytics, directShipper, {
8262
- projectId,
8263
- authHint
8264
- });
8265
- activeInteractionsByEventId.set(eventId, interaction);
8266
- return interaction;
8267
- },
8268
- tracer(globalProperties) {
8269
- return new LiveTracer(globalProperties, directShipper, { projectId, authHint });
8270
- },
8271
- /**
8272
- * Best-effort drain of in-flight OTel spans and direct shipper batches.
8273
- * Safe to call when nothing is in flight; never throws.
8274
- */
8275
- async forceFlush() {
8276
- const deadlineAt = Date.now() + resolveFlushTimeoutMs(flushTimeoutMs);
8277
- let result = { ...DELIVERED };
8278
- if (directShipper) {
8279
- try {
8280
- result = await directShipper.flush();
8281
- } catch (e) {
8282
- }
8283
- }
8284
- if (traceloopInitialized) {
8285
- const settled = await raceWithTimeout(
8286
- forceFlush().catch(() => {
8287
- }),
8288
- deadlineAt - Date.now()
8289
- );
8290
- if (!settled) {
8291
- result = combineResults(result, {
8292
- ...DELIVERED,
8293
- delivered: false,
8294
- timedOut: true,
8295
- inFlight: 1
8296
- });
8297
- }
8298
- }
8299
- return asCompat(result);
8300
- },
8301
- /** Drain and stop; resolves (never rejects) to the direct shipper's result. */
8302
- async close() {
8303
- var _a2;
8304
- deregisterExitFlusher == null ? void 0 : deregisterExitFlusher();
8305
- activeInteractions.clear();
8306
- activeInteractionsByEventId.clear();
8307
- let result = { ...DELIVERED };
8308
- try {
8309
- result = (_a2 = await (directShipper == null ? void 0 : directShipper.shutdown())) != null ? _a2 : result;
8310
- } catch (e) {
8311
- }
8312
- if (traceloopInitialized) {
8313
- try {
8314
- await forceFlush();
8315
- } catch (e) {
8316
- }
8317
- }
8318
- return result;
8319
- }
8320
- };
8321
- };
8322
-
8323
4208
  export {
8324
4209
  EVAL_CORRELATION_ID_ATTRIBUTE,
8325
4210
  withEvalScope,
@@ -8327,15 +4212,45 @@ export {
8327
4212
  evalScopeAttributes,
8328
4213
  withReplayTraceDestination,
8329
4214
  currentReplayTraceDestination,
4215
+ rememberReplayTraceDestination,
4216
+ copyReplayTraceDestination,
4217
+ replayTraceDestinationFor,
4218
+ recordReplayExportedSpan,
4219
+ replayTraceUrl,
4220
+ bindRoutingContext,
4221
+ unbindRoutingContext,
8330
4222
  withRoutingContext,
8331
4223
  currentRoutingBinding,
4224
+ bindSpanAttributes,
4225
+ unbindSpanAttributes,
4226
+ applySpanAttributeFrames,
4227
+ claimSpanForFrames,
4228
+ currentSpanAttributes,
4229
+ markErrorSpanSeen,
8332
4230
  APP_COMMIT_SHA,
8333
4231
  APP_COMMIT_DIRTY,
8334
4232
  APP_BRANCH,
8335
4233
  validAppCommitSha,
8336
4234
  withAppGitProperties,
4235
+ withAppGitAttributes,
8337
4236
  normalizeFeatureFlags,
8338
4237
  randomUUID,
4238
+ HANDOFF_ATTRIBUTE_SUFFIXES,
4239
+ HANDOFF_TERMINAL_CANCELLED,
4240
+ OPERATION_ID_ATTRIBUTE,
4241
+ SUBAGENT_ABORT_OPERATION_ID,
4242
+ SUBAGENT_ABORT_SPAN_NAME,
4243
+ DEFAULT_DISPATCH_SPAN_NAME,
4244
+ HANDOFF_TERMINAL_PROPERTY_KEY,
4245
+ detachedDispatchMetadata,
4246
+ detachedChildMetadata,
4247
+ cancelledTerminalAttributes,
4248
+ toolEventsAllowMetadata,
4249
+ withMetadataPrefix,
4250
+ toHeaders,
4251
+ toLangSmithHeaders,
4252
+ fromHeaders,
4253
+ warnUnresolvedCarrier,
8339
4254
  runWithTracingSuppressed,
8340
4255
  DEFAULT_REQUEST_TIMEOUT_MS,
8341
4256
  redactUrlForLog,
@@ -8353,22 +4268,39 @@ export {
8353
4268
  setDefaultMaxTextFieldChars,
8354
4269
  resolveMaxTextFieldChars,
8355
4270
  capText,
4271
+ stringifyBounded,
4272
+ attrString,
8356
4273
  resolveLocalDebuggerBaseUrl,
8357
4274
  localDebuggerEnabled,
4275
+ mirrorTraceExportToLocalDebugger,
4276
+ sendLocalDebuggerLiveEvent,
8358
4277
  normalizeProjectId,
8359
4278
  projectIdHeaders,
4279
+ redactSpanContent,
4280
+ compileSpanPiiFields,
4281
+ redactPiiInOtlpSpan,
4282
+ redactPiiInAttributeMap,
8360
4283
  maskPayload,
4284
+ maskSpanStatusMessage,
4285
+ maskOtlpSpan,
4286
+ maskAttributeMap,
8361
4287
  PiiFieldRedactor,
4288
+ resolvePiiRedaction,
8362
4289
  piiRedactionNow,
8363
4290
  piiRedaction,
4291
+ requestLocalTracePiiRedaction,
4292
+ localTracePiiRedactionRequested,
8364
4293
  isMissingUserId,
8365
4294
  snapshotPayload,
8366
4295
  POST_SHUTDOWN_TIMEOUT_MS,
8367
4296
  resolveFlushTimeoutMs,
4297
+ MODEL_USAGE_ATTRIBUTES,
4298
+ canonicalModelProvider,
4299
+ buildRawModelUsageAttributes,
4300
+ PROMPT_TOOLS_ATTRIBUTE,
4301
+ normalizeToolDeclarations,
4302
+ promptToolsAttributeValue,
4303
+ promptToolsFromTraceloopAttributes,
8368
4304
  createAppGitContext2 as createAppGitContext,
8369
- EventShipper2,
8370
- package_default,
8371
- authHintForKey,
8372
- withTask,
8373
- tracing
4305
+ EventShipper2
8374
4306
  };