raindrop-ai 0.0.88 → 0.0.89

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.
@@ -49,7 +49,7 @@ var import_instrumentation_vertexai = require("@traceloop/instrumentation-vertex
49
49
  var traceloop3 = __toESM(require("@traceloop/node-server-sdk"));
50
50
  var import_weakref = require("weakref");
51
51
 
52
- // src/tracing/direct/http.ts
52
+ // ../core/dist/chunk-4UCYIEH4.js
53
53
  function wait(ms) {
54
54
  return new Promise((resolve) => setTimeout(resolve, ms));
55
55
  }
@@ -62,7 +62,7 @@ function parseRetryAfter(headers) {
62
62
  const value = (_a = headers.get("Retry-After")) != null ? _a : headers.get("retry-after");
63
63
  if (!value) return void 0;
64
64
  const asNumber = Number(value);
65
- if (!Number.isNaN(asNumber)) return asNumber * 1e3;
65
+ if (value.trim() !== "" && !Number.isNaN(asNumber)) return asNumber * 1e3;
66
66
  const asDate = new Date(value).getTime();
67
67
  if (!Number.isNaN(asDate)) {
68
68
  const delta = asDate - Date.now();
@@ -81,18 +81,19 @@ function getRetryDelayMs(attemptNumber, previousError) {
81
81
  return base * factor;
82
82
  }
83
83
  async function withRetry(operation, opName, opts) {
84
+ const prefix = opts.sdkName ? `[raindrop-ai/${opts.sdkName}]` : "[raindrop-ai/core]";
84
85
  let lastError = void 0;
85
86
  for (let attemptNumber = 1; attemptNumber <= opts.maxAttempts; attemptNumber++) {
86
87
  if (attemptNumber > 1) {
87
88
  const delay = getRetryDelayMs(attemptNumber, lastError);
88
89
  if (opts.debug) {
89
90
  console.warn(
90
- `[raindrop] ${opName} retry ${attemptNumber}/${opts.maxAttempts} in ${delay}ms`
91
+ `${prefix} ${opName} retry ${attemptNumber}/${opts.maxAttempts} in ${delay}ms`
91
92
  );
92
93
  }
93
94
  if (delay > 0) await wait(delay);
94
95
  } else if (opts.debug) {
95
- console.log(`[raindrop] ${opName} attempt ${attemptNumber}/${opts.maxAttempts}`);
96
+ console.log(`${prefix} ${opName} attempt ${attemptNumber}/${opts.maxAttempts}`);
96
97
  }
97
98
  try {
98
99
  return await operation();
@@ -101,9 +102,11 @@ async function withRetry(operation, opName, opts) {
101
102
  if (opts.debug) {
102
103
  const msg = err instanceof Error ? err.message : String(err);
103
104
  console.warn(
104
- `[raindrop] ${opName} attempt ${attemptNumber} failed: ${msg}${attemptNumber === opts.maxAttempts ? " (no more retries)" : ""}`
105
+ `${prefix} ${opName} attempt ${attemptNumber} failed: ${msg}${attemptNumber === opts.maxAttempts ? " (no more retries)" : ""}`
105
106
  );
106
107
  }
108
+ if (lastError && typeof lastError === "object" && "retryable" in lastError && !lastError.retryable)
109
+ break;
107
110
  if (attemptNumber === opts.maxAttempts) break;
108
111
  }
109
112
  }
@@ -128,6 +131,153 @@ async function postJson(url, body, headers, opts) {
128
131
  );
129
132
  const retryAfterMs = parseRetryAfter(resp.headers);
130
133
  if (typeof retryAfterMs === "number") err.retryAfterMs = retryAfterMs;
134
+ err.retryable = resp.status === 429 || resp.status >= 500;
135
+ throw err;
136
+ }
137
+ },
138
+ opName,
139
+ opts
140
+ );
141
+ }
142
+ var LOCAL_DEBUGGER_ENV_VAR = "RAINDROP_LOCAL_DEBUGGER";
143
+ function resolveLocalDebuggerBaseUrl(baseUrl) {
144
+ var _a, _b, _c;
145
+ const resolved = (_b = baseUrl != null ? baseUrl : typeof process !== "undefined" ? (_a = process.env) == null ? void 0 : _a[LOCAL_DEBUGGER_ENV_VAR] : void 0) != null ? _b : null;
146
+ return resolved ? (_c = formatEndpoint(resolved)) != null ? _c : null : null;
147
+ }
148
+ function localDebuggerEnabled(baseUrl) {
149
+ return resolveLocalDebuggerBaseUrl(baseUrl) !== null;
150
+ }
151
+ function normalizeLocalDebuggerLiveEventType(type) {
152
+ switch (type) {
153
+ case "text-delta":
154
+ return "text_delta";
155
+ case "reasoning":
156
+ case "reasoning-delta":
157
+ return "reasoning_delta";
158
+ case "tool-call":
159
+ return "tool_start";
160
+ case "tool-result":
161
+ return "tool_result";
162
+ default:
163
+ return type;
164
+ }
165
+ }
166
+ function mirrorTraceExportToLocalDebugger(body, options = {}) {
167
+ var _a;
168
+ const baseUrl = resolveLocalDebuggerBaseUrl(options.baseUrl);
169
+ if (!baseUrl) return;
170
+ void postJson(`${baseUrl}traces`, body, {}, {
171
+ maxAttempts: 1,
172
+ debug: (_a = options.debug) != null ? _a : false,
173
+ sdkName: options.sdkName
174
+ }).catch(() => {
175
+ });
176
+ }
177
+ function sendLocalDebuggerLiveEvent(event, options = {}) {
178
+ var _a, _b;
179
+ const baseUrl = resolveLocalDebuggerBaseUrl(options.baseUrl);
180
+ if (!baseUrl) return;
181
+ void postJson(
182
+ `${baseUrl}live`,
183
+ {
184
+ ...event,
185
+ type: normalizeLocalDebuggerLiveEventType(event.type),
186
+ timestamp: (_a = event.timestamp) != null ? _a : Date.now()
187
+ },
188
+ {},
189
+ {
190
+ maxAttempts: 1,
191
+ debug: (_b = options.debug) != null ? _b : false,
192
+ sdkName: options.sdkName
193
+ }
194
+ ).catch(() => {
195
+ });
196
+ }
197
+
198
+ // ../core/dist/index.node.js
199
+ var import_async_hooks = require("async_hooks");
200
+ globalThis.RAINDROP_ASYNC_LOCAL_STORAGE = import_async_hooks.AsyncLocalStorage;
201
+
202
+ // src/tracing/direct/http.ts
203
+ function wait2(ms) {
204
+ return new Promise((resolve) => setTimeout(resolve, ms));
205
+ }
206
+ function formatEndpoint2(endpoint) {
207
+ if (!endpoint) return void 0;
208
+ return endpoint.endsWith("/") ? endpoint : `${endpoint}/`;
209
+ }
210
+ function parseRetryAfter2(headers) {
211
+ var _a;
212
+ const value = (_a = headers.get("Retry-After")) != null ? _a : headers.get("retry-after");
213
+ if (!value) return void 0;
214
+ const asNumber = Number(value);
215
+ if (!Number.isNaN(asNumber)) return asNumber * 1e3;
216
+ const asDate = new Date(value).getTime();
217
+ if (!Number.isNaN(asDate)) {
218
+ const delta = asDate - Date.now();
219
+ return delta > 0 ? delta : 0;
220
+ }
221
+ return void 0;
222
+ }
223
+ function getRetryDelayMs2(attemptNumber, previousError) {
224
+ if (previousError && typeof previousError === "object" && previousError !== null && "retryAfterMs" in previousError) {
225
+ const v = previousError.retryAfterMs;
226
+ if (typeof v === "number") return Math.max(0, v);
227
+ }
228
+ if (attemptNumber <= 1) return 0;
229
+ const base = 500;
230
+ const factor = Math.pow(2, attemptNumber - 2);
231
+ return base * factor;
232
+ }
233
+ async function withRetry2(operation, opName, opts) {
234
+ let lastError = void 0;
235
+ for (let attemptNumber = 1; attemptNumber <= opts.maxAttempts; attemptNumber++) {
236
+ if (attemptNumber > 1) {
237
+ const delay = getRetryDelayMs2(attemptNumber, lastError);
238
+ if (opts.debug) {
239
+ console.warn(
240
+ `[raindrop] ${opName} retry ${attemptNumber}/${opts.maxAttempts} in ${delay}ms`
241
+ );
242
+ }
243
+ if (delay > 0) await wait2(delay);
244
+ } else if (opts.debug) {
245
+ console.log(`[raindrop] ${opName} attempt ${attemptNumber}/${opts.maxAttempts}`);
246
+ }
247
+ try {
248
+ return await operation();
249
+ } catch (err) {
250
+ lastError = err;
251
+ if (opts.debug) {
252
+ const msg = err instanceof Error ? err.message : String(err);
253
+ console.warn(
254
+ `[raindrop] ${opName} attempt ${attemptNumber} failed: ${msg}${attemptNumber === opts.maxAttempts ? " (no more retries)" : ""}`
255
+ );
256
+ }
257
+ if (attemptNumber === opts.maxAttempts) break;
258
+ }
259
+ }
260
+ throw lastError instanceof Error ? lastError : new Error(String(lastError));
261
+ }
262
+ async function postJson2(url, body, headers, opts) {
263
+ const opName = `POST ${url}`;
264
+ await withRetry2(
265
+ async () => {
266
+ const resp = await fetch(url, {
267
+ method: "POST",
268
+ headers: {
269
+ "Content-Type": "application/json",
270
+ ...headers
271
+ },
272
+ body: JSON.stringify(body)
273
+ });
274
+ if (!resp.ok) {
275
+ const text = await resp.text().catch(() => "");
276
+ const err = new Error(
277
+ `HTTP ${resp.status} ${resp.statusText}${text ? `: ${text}` : ""}`
278
+ );
279
+ const retryAfterMs = parseRetryAfter2(resp.headers);
280
+ if (typeof retryAfterMs === "number") err.retryAfterMs = retryAfterMs;
131
281
  throw err;
132
282
  }
133
283
  },
@@ -141,7 +291,7 @@ function getCrypto() {
141
291
  const c = globalThis.crypto;
142
292
  return c;
143
293
  }
144
- function randomBytes(length) {
294
+ function randomBytes2(length) {
145
295
  const cryptoObj = getCrypto();
146
296
  const out = new Uint8Array(length);
147
297
  if (cryptoObj && typeof cryptoObj.getRandomValues === "function") {
@@ -151,7 +301,7 @@ function randomBytes(length) {
151
301
  for (let i = 0; i < out.length; i++) out[i] = Math.floor(Math.random() * 256);
152
302
  return out;
153
303
  }
154
- function base64Encode(bytes) {
304
+ function base64Encode2(bytes) {
155
305
  const maybeBuffer = globalThis.Buffer;
156
306
  if (maybeBuffer) {
157
307
  return maybeBuffer.from(bytes).toString("base64");
@@ -180,15 +330,40 @@ function base64Encode(bytes) {
180
330
  }
181
331
  return out;
182
332
  }
333
+ function base64ToHex(base64) {
334
+ const maybeBuffer = globalThis.Buffer;
335
+ if (maybeBuffer) {
336
+ return maybeBuffer.from(base64, "base64").toString("hex");
337
+ }
338
+ const atobFn = globalThis.atob;
339
+ if (typeof atobFn === "function") {
340
+ const binary = atobFn(base64);
341
+ let hex = "";
342
+ for (let i = 0; i < binary.length; i++) {
343
+ hex += binary.charCodeAt(i).toString(16).padStart(2, "0");
344
+ }
345
+ return hex;
346
+ }
347
+ throw new Error("No base64 decoder available in this runtime");
348
+ }
183
349
 
184
350
  // package.json
185
351
  var package_default = {
186
352
  name: "raindrop-ai",
187
- version: "0.0.88",
353
+ version: "0.0.89",
188
354
  main: "dist/index.js",
189
355
  module: "dist/index.mjs",
190
356
  types: "dist/index.d.ts",
191
357
  license: "MIT",
358
+ repository: {
359
+ type: "git",
360
+ url: "git+https://github.com/raindrop-ai/raindrop-js.git",
361
+ directory: "packages/js-sdk"
362
+ },
363
+ homepage: "https://github.com/raindrop-ai/raindrop-js/tree/main/packages/js-sdk#readme",
364
+ bugs: {
365
+ url: "https://github.com/raindrop-ai/raindrop-js/issues"
366
+ },
192
367
  exports: {
193
368
  ".": {
194
369
  types: "./dist/index.d.ts",
@@ -228,15 +403,18 @@ var package_default = {
228
403
  "smoke:self-diagnostics:all": "pnpm smoke:self-diagnostics:ai-sdk:all && pnpm smoke:self-diagnostics:openai-sdk && pnpm smoke:self-diagnostics:anthropic-sdk"
229
404
  },
230
405
  devDependencies: {
406
+ "@raindrop-ai/redact-pii": "workspace:*",
407
+ "@raindrop-ai/schemas": "workspace:*",
408
+ ai: "^6.0.0",
231
409
  "@types/node": "^20.11.17",
232
410
  msw: "^2.12.8",
233
411
  tsup: "^8.4.0",
234
412
  tsx: "^4.20.3",
235
413
  typescript: "^5.3.3",
414
+ vite: "^6.4.1",
236
415
  vitest: "^4.0.10"
237
416
  },
238
417
  dependencies: {
239
- "@dawn-analytics/redact-pii": "workspace:*",
240
418
  "@opentelemetry/api": "^1.9.0",
241
419
  "@opentelemetry/resources": "^2.0.1",
242
420
  "@traceloop/node-server-sdk": "0.19.0-otel-v1",
@@ -272,7 +450,8 @@ var package_default = {
272
450
  "@opentelemetry/sdk-trace-base"
273
451
  ],
274
452
  noExternal: [
275
- "@dawn/schemas"
453
+ "@raindrop-ai/redact-pii",
454
+ "@raindrop-ai/schemas"
276
455
  ],
277
456
  dts: {
278
457
  resolve: true
@@ -284,16 +463,16 @@ var package_default = {
284
463
  // src/tracing/direct/otlp.ts
285
464
  var libraryVersion = package_default.version;
286
465
  var SERVICE_NAME = "raindrop-ai";
287
- function attrString(key, value) {
466
+ function attrString2(key, value) {
288
467
  if (value === void 0) return void 0;
289
468
  return { key, value: { stringValue: value } };
290
469
  }
291
- function attrInt(key, value) {
470
+ function attrInt2(key, value) {
292
471
  if (value === void 0) return void 0;
293
472
  if (!Number.isFinite(value)) return void 0;
294
473
  return { key, value: { intValue: String(Math.trunc(value)) } };
295
474
  }
296
- function buildOtlpSpan(args) {
475
+ function buildOtlpSpan2(args) {
297
476
  const attrs = args.attributes.filter((x) => x !== void 0);
298
477
  const span = {
299
478
  traceId: args.ids.traceIdB64,
@@ -307,7 +486,7 @@ function buildOtlpSpan(args) {
307
486
  if (args.status) span.status = args.status;
308
487
  return span;
309
488
  }
310
- function buildExportTraceServiceRequest(spans) {
489
+ function buildExportTraceServiceRequest2(spans) {
311
490
  return {
312
491
  resourceSpans: [
313
492
  {
@@ -334,7 +513,7 @@ function hexToBase64(hex) {
334
513
  for (let i = 0; i < hex.length; i += 2) {
335
514
  bytes[i / 2] = parseInt(hex.substring(i, i + 2), 16);
336
515
  }
337
- return base64Encode(bytes);
516
+ return base64Encode2(bytes);
338
517
  }
339
518
  function getActiveTraceContext() {
340
519
  const activeSpan = import_api.trace.getSpan(import_api.context.active());
@@ -363,12 +542,18 @@ var DirectTraceShipper = class {
363
542
  this.inFlight = /* @__PURE__ */ new Set();
364
543
  var _a, _b, _c, _d, _e;
365
544
  this.writeKey = opts.writeKey;
366
- this.baseUrl = (_a = formatEndpoint(opts.endpoint)) != null ? _a : "https://api.raindrop.ai/v1/";
545
+ this.baseUrl = (_a = formatEndpoint2(opts.endpoint)) != null ? _a : "https://api.raindrop.ai/v1/";
367
546
  this.enabled = (_b = opts.enabled) != null ? _b : true;
368
547
  this.debug = opts.debug;
369
548
  this.flushIntervalMs = (_c = opts.flushIntervalMs) != null ? _c : 1e3;
370
549
  this.maxBatchSize = (_d = opts.maxBatchSize) != null ? _d : 50;
371
550
  this.maxQueueSize = (_e = opts.maxQueueSize) != null ? _e : 5e3;
551
+ if (localDebuggerEnabled()) {
552
+ const resolved = resolveLocalDebuggerBaseUrl();
553
+ if (resolved && resolved !== this.baseUrl) {
554
+ this.localDebuggerUrl = resolved;
555
+ }
556
+ }
372
557
  }
373
558
  /**
374
559
  * Build and enqueue an OTLP span for a trackTool call.
@@ -376,7 +561,8 @@ var DirectTraceShipper = class {
376
561
  * Reads the active OTEL context if traceId/parentSpanId are not provided,
377
562
  * so spans still appear as children in the trace tree.
378
563
  */
379
- sendToolSpan(params) {
564
+ sendSpan(params) {
565
+ var _a, _b;
380
566
  if (!this.enabled) return;
381
567
  let traceIdB64 = params.traceId;
382
568
  let parentSpanIdB64 = params.parentSpanId;
@@ -385,27 +571,27 @@ var DirectTraceShipper = class {
385
571
  traceIdB64 = activeCtx.traceIdB64;
386
572
  parentSpanIdB64 = activeCtx.parentSpanIdB64;
387
573
  }
388
- const spanIdB64 = base64Encode(randomBytes(8));
574
+ const spanIdB64 = (_a = params.spanId) != null ? _a : base64Encode2(randomBytes2(8));
389
575
  if (!traceIdB64) {
390
- traceIdB64 = base64Encode(randomBytes(16));
576
+ traceIdB64 = base64Encode2(randomBytes2(16));
391
577
  }
392
578
  const startTimeUnixNano = String(params.startTimeMs * 1e6);
393
579
  const endTimeUnixNano = String(params.endTimeMs * 1e6);
394
580
  const attributes = [
395
581
  // Required: passes hasAIOperation() filter in backend (parseSpan.ts)
396
- attrString("traceloop.span.kind", "tool"),
582
+ attrString2("traceloop.span.kind", (_b = params.spanKind) != null ? _b : "tool"),
397
583
  // Parsed by backend for input/output payloads
398
- attrString("traceloop.entity.input", params.input),
399
- attrString("traceloop.entity.output", params.output),
584
+ attrString2("traceloop.entity.input", params.input),
585
+ attrString2("traceloop.entity.output", params.output),
400
586
  // Duration tracking
401
- attrInt("traceloop.entity.duration_ms", params.durationMs)
587
+ attrInt2("traceloop.entity.duration_ms", params.durationMs)
402
588
  ];
403
589
  for (const [key, value] of Object.entries(params.properties)) {
404
590
  if (value === void 0) {
405
591
  continue;
406
592
  }
407
593
  attributes.push(
408
- attrString(`traceloop.association.properties.${key}`, serializeAssociationValue(value))
594
+ attrString2(`traceloop.association.properties.${key}`, serializeAssociationValue(value))
409
595
  );
410
596
  }
411
597
  let status;
@@ -417,7 +603,7 @@ var DirectTraceShipper = class {
417
603
  /* STATUS_CODE_OK */
418
604
  };
419
605
  }
420
- const span = buildOtlpSpan({
606
+ const span = buildOtlpSpan2({
421
607
  ids: {
422
608
  traceIdB64,
423
609
  spanIdB64,
@@ -429,11 +615,25 @@ var DirectTraceShipper = class {
429
615
  attributes,
430
616
  status
431
617
  });
618
+ if (this.localDebuggerUrl) {
619
+ const body = buildExportTraceServiceRequest2([span]);
620
+ mirrorTraceExportToLocalDebugger(body, {
621
+ baseUrl: this.localDebuggerUrl,
622
+ debug: false,
623
+ sdkName: "js-sdk"
624
+ });
625
+ }
432
626
  this.enqueue(span);
433
627
  if (this.debug) {
434
628
  console.log(`[raindrop] direct shipper: enqueued span "${params.name}"`);
435
629
  }
436
630
  }
631
+ sendToolSpan(params) {
632
+ this.sendSpan({
633
+ ...params,
634
+ spanKind: "tool"
635
+ });
636
+ }
437
637
  enqueue(span) {
438
638
  if (!this.enabled) return;
439
639
  if (this.queue.length >= this.maxQueueSize) {
@@ -461,9 +661,9 @@ var DirectTraceShipper = class {
461
661
  }
462
662
  while (this.queue.length > 0) {
463
663
  const batch = this.queue.splice(0, this.maxBatchSize);
464
- const body = buildExportTraceServiceRequest(batch);
664
+ const body = buildExportTraceServiceRequest2(batch);
465
665
  const url = `${this.baseUrl}traces`;
466
- const p = postJson(
666
+ const p = postJson2(
467
667
  url,
468
668
  body,
469
669
  { Authorization: `Bearer ${this.writeKey}` },
@@ -499,15 +699,16 @@ var DirectTraceShipper = class {
499
699
  // src/tracing/liveInteraction.ts
500
700
  var import_api2 = require("@opentelemetry/api");
501
701
  var traceloop = __toESM(require("@traceloop/node-server-sdk"));
502
- function getPropertiesFromContext(context3) {
702
+ function getPropertiesFromContext(context5) {
503
703
  const properties = {
504
- ...context3.userId && { user_id: context3.userId },
505
- ...context3.convoId && { convo_id: context3.convoId },
506
- ...context3.eventId && { event_id: context3.eventId },
507
- ...context3.properties || {}
704
+ ...context5.userId && { user_id: context5.userId },
705
+ ...context5.convoId && { convo_id: context5.convoId },
706
+ ...context5.eventId && { event_id: context5.eventId },
707
+ ...context5.event && { event_name: context5.event },
708
+ ...context5.properties || {}
508
709
  };
509
- if (context3.attachments && context3.attachments.length > 0) {
510
- properties.attachments = JSON.stringify(context3.attachments);
710
+ if (context5.attachments && context5.attachments.length > 0) {
711
+ properties.attachments = JSON.stringify(context5.attachments);
511
712
  }
512
713
  return properties;
513
714
  }
@@ -531,28 +732,48 @@ function serializeSpanValue(value) {
531
732
  const jsonValue = JSON.stringify(value);
532
733
  return jsonValue === void 0 ? String(value) : jsonValue;
533
734
  }
735
+ function getLocalDebuggerMetadata(context5) {
736
+ return {
737
+ ...context5.eventId ? { eventId: context5.eventId } : {},
738
+ ...context5.event ? { eventName: context5.event } : {},
739
+ ...context5.userId ? { userId: context5.userId } : {},
740
+ ...context5.convoId ? { convoId: context5.convoId } : {}
741
+ };
742
+ }
534
743
  var LiveToolSpan = class {
535
- constructor(span) {
744
+ constructor(params) {
536
745
  this.hasError = false;
537
- this.span = span;
746
+ this.span = params.span;
747
+ this.name = params.name;
748
+ this.emitLiveEvent = params.emitLiveEvent;
538
749
  }
539
750
  setInput(input) {
540
751
  this.span.setAttribute("traceloop.entity.input", serializeSpanValue(input));
541
752
  }
542
753
  setOutput(output) {
754
+ this.output = output;
543
755
  this.span.setAttribute("traceloop.entity.output", serializeSpanValue(output));
544
756
  }
545
757
  setError(error) {
546
758
  this.hasError = true;
547
- const errorMessage = error instanceof Error ? error.message : String(error);
548
- this.span.setStatus({ code: import_api2.SpanStatusCode.ERROR, message: errorMessage });
549
- this.span.recordException(error instanceof Error ? error : new Error(errorMessage));
759
+ this.errorMessage = error instanceof Error ? error.message : String(error);
760
+ this.span.setStatus({ code: import_api2.SpanStatusCode.ERROR, message: this.errorMessage });
761
+ this.span.recordException(error instanceof Error ? error : new Error(this.errorMessage));
550
762
  }
551
763
  end() {
764
+ var _a;
552
765
  if (!this.hasError) {
553
766
  this.span.setStatus({ code: import_api2.SpanStatusCode.OK });
554
767
  }
555
768
  this.span.end();
769
+ (_a = this.emitLiveEvent) == null ? void 0 : _a.call(this, {
770
+ type: "tool_result",
771
+ content: this.name,
772
+ metadata: {
773
+ ...this.output !== void 0 ? { result: this.output } : {},
774
+ ...this.errorMessage ? { error: this.errorMessage } : {}
775
+ }
776
+ });
556
777
  }
557
778
  };
558
779
  var DirectToolSpan = class {
@@ -565,17 +786,20 @@ var DirectToolSpan = class {
565
786
  this.parentSpanId = params.parentSpanId;
566
787
  this.startTimeMs = Date.now();
567
788
  this.input = params.input !== void 0 ? serializeSpanValue(params.input) : void 0;
789
+ this.emitLiveEvent = params.emitLiveEvent;
568
790
  }
569
791
  setInput(input) {
570
792
  this.input = serializeSpanValue(input);
571
793
  }
572
794
  setOutput(output) {
795
+ this.rawOutput = output;
573
796
  this.output = serializeSpanValue(output);
574
797
  }
575
798
  setError(error) {
576
799
  this.error = error instanceof Error ? error.message : String(error);
577
800
  }
578
801
  end() {
802
+ var _a;
579
803
  if (this.ended) {
580
804
  return;
581
805
  }
@@ -593,16 +817,65 @@ var DirectToolSpan = class {
593
817
  traceId: this.traceId,
594
818
  parentSpanId: this.parentSpanId
595
819
  });
820
+ (_a = this.emitLiveEvent) == null ? void 0 : _a.call(this, {
821
+ traceId: this.traceId,
822
+ type: "tool_result",
823
+ content: this.name,
824
+ timestamp: endTimeMs,
825
+ metadata: {
826
+ ...this.rawOutput !== void 0 ? { result: this.rawOutput } : {},
827
+ ...this.error ? { error: this.error } : {}
828
+ }
829
+ });
596
830
  }
597
831
  };
598
832
  var LiveInteraction = class {
599
- constructor(context3, traceId, analytics, directShipper) {
600
- this.context = context3;
833
+ constructor(context5, traceId, analytics, directShipper) {
834
+ this.context = context5;
601
835
  this.analytics = analytics;
602
836
  this.tracer = import_api2.trace.getTracer("traceloop.tracer");
603
837
  this.traceId = traceId;
604
838
  this.directShipper = directShipper;
605
839
  }
840
+ ensureTraceId(preferred) {
841
+ if (preferred) {
842
+ this.traceId = preferred;
843
+ return preferred;
844
+ }
845
+ if (this.traceId) {
846
+ return this.traceId;
847
+ }
848
+ this.traceId = base64Encode2(randomBytes2(16));
849
+ return this.traceId;
850
+ }
851
+ resolveLiveTraceId(explicitTraceId) {
852
+ if (explicitTraceId) {
853
+ this.traceId = explicitTraceId;
854
+ return explicitTraceId;
855
+ }
856
+ const activeSpan = import_api2.trace.getSpan(import_api2.context.active());
857
+ const activeTraceId = activeSpan == null ? void 0 : activeSpan.spanContext().traceId;
858
+ if (activeTraceId) {
859
+ this.traceId = activeTraceId;
860
+ return activeTraceId;
861
+ }
862
+ return this.traceId;
863
+ }
864
+ emitLiveEvent(event) {
865
+ var _a, _b;
866
+ const traceId = (_a = this.resolveLiveTraceId(event.traceId)) != null ? _a : this.ensureTraceId();
867
+ sendLocalDebuggerLiveEvent({
868
+ ...event,
869
+ traceId,
870
+ metadata: {
871
+ ...getLocalDebuggerMetadata(this.context),
872
+ ...(_b = event.metadata) != null ? _b : {}
873
+ }
874
+ });
875
+ }
876
+ getTraceId() {
877
+ return this.traceId;
878
+ }
606
879
  async withSpan(params, fn, thisArg, ...args) {
607
880
  var _a;
608
881
  const taskName = typeof params === "string" ? params : params.name;
@@ -616,6 +889,64 @@ var LiveInteraction = class {
616
889
  if ((_a = this.analytics) == null ? void 0 : _a.debugLogs) {
617
890
  console.log("[raindrop] using withSpan in liveInteraction");
618
891
  }
892
+ if (this.directShipper) {
893
+ const activeContext = getActiveTraceContext();
894
+ const traceIdB64 = this.ensureTraceId(activeContext.traceIdB64);
895
+ const parentSpanIdB64 = activeContext.parentSpanIdB64;
896
+ const spanIdB64 = base64Encode2(randomBytes2(8));
897
+ const startTimeMs = Date.now();
898
+ const spanContext = {
899
+ traceId: base64ToHex(traceIdB64),
900
+ spanId: base64ToHex(spanIdB64),
901
+ traceFlags: import_api2.TraceFlags.SAMPLED
902
+ };
903
+ const wrappedContext = import_api2.trace.setSpan(
904
+ import_api2.context.active(),
905
+ import_api2.trace.wrapSpanContext(spanContext)
906
+ );
907
+ try {
908
+ const result = await import_api2.context.with(wrappedContext, () => fn.apply(thisArg, args));
909
+ const endTimeMs = Date.now();
910
+ this.directShipper.sendSpan({
911
+ name: taskName,
912
+ spanKind: "task",
913
+ spanId: spanIdB64,
914
+ input: inputParameters !== void 0 ? serializeSpanValue(inputParameters) : void 0,
915
+ output: result !== void 0 ? serializeSpanValue(result) : void 0,
916
+ durationMs: endTimeMs - startTimeMs,
917
+ startTimeMs,
918
+ endTimeMs,
919
+ properties,
920
+ traceId: traceIdB64,
921
+ parentSpanId: parentSpanIdB64
922
+ });
923
+ return result;
924
+ } catch (error) {
925
+ const endTimeMs = Date.now();
926
+ this.directShipper.sendSpan({
927
+ name: taskName,
928
+ spanKind: "task",
929
+ spanId: spanIdB64,
930
+ input: inputParameters !== void 0 ? serializeSpanValue(inputParameters) : void 0,
931
+ durationMs: endTimeMs - startTimeMs,
932
+ startTimeMs,
933
+ endTimeMs,
934
+ error: error instanceof Error ? error.message : String(error),
935
+ properties,
936
+ traceId: traceIdB64,
937
+ parentSpanId: parentSpanIdB64
938
+ });
939
+ throw error;
940
+ }
941
+ }
942
+ const wrappedFn = (...fnArgs) => {
943
+ var _a2;
944
+ const activeTraceId = (_a2 = import_api2.trace.getSpan(import_api2.context.active())) == null ? void 0 : _a2.spanContext().traceId;
945
+ if (activeTraceId) {
946
+ this.traceId = activeTraceId;
947
+ }
948
+ return fn.apply(thisArg, fnArgs);
949
+ };
619
950
  return traceloop.withTask(
620
951
  {
621
952
  name: taskName,
@@ -624,8 +955,8 @@ var LiveInteraction = class {
624
955
  traceContent: params.traceContent,
625
956
  suppressTracing: params.suppressTracing
626
957
  },
627
- fn,
628
- thisArg,
958
+ wrappedFn,
959
+ void 0,
629
960
  ...args
630
961
  );
631
962
  }
@@ -640,12 +971,31 @@ var LiveInteraction = class {
640
971
  console.log("[raindrop] using withTool in liveInteraction");
641
972
  }
642
973
  if (this.directShipper) {
643
- const { traceIdB64, parentSpanIdB64 } = getActiveTraceContext();
974
+ const activeContext = getActiveTraceContext();
975
+ this.emitLiveEvent({
976
+ traceId: activeContext.traceIdB64,
977
+ type: "tool_start",
978
+ content: toolName,
979
+ timestamp: Date.now(),
980
+ metadata: params.inputParameters ? { args: params.inputParameters } : void 0
981
+ });
982
+ const traceIdB64 = this.ensureTraceId(activeContext.traceIdB64);
983
+ const { parentSpanIdB64 } = activeContext;
984
+ const spanIdB64 = base64Encode2(randomBytes2(8));
644
985
  const startTimeMs = Date.now();
986
+ const spanContext = {
987
+ traceId: base64ToHex(traceIdB64),
988
+ spanId: base64ToHex(spanIdB64),
989
+ traceFlags: import_api2.TraceFlags.SAMPLED
990
+ };
991
+ const wrappedContext = import_api2.trace.setSpan(
992
+ import_api2.context.active(),
993
+ import_api2.trace.wrapSpanContext(spanContext)
994
+ );
645
995
  let result;
646
996
  let error;
647
997
  try {
648
- result = await fn.apply(thisArg, args);
998
+ result = await import_api2.context.with(wrappedContext, () => fn.apply(thisArg, args));
649
999
  } catch (err) {
650
1000
  error = err instanceof Error ? err.message : String(err);
651
1001
  const endTimeMs2 = Date.now();
@@ -653,6 +1003,7 @@ var LiveInteraction = class {
653
1003
  const inputStr2 = params.inputParameters ? JSON.stringify(params.inputParameters) : void 0;
654
1004
  this.directShipper.sendToolSpan({
655
1005
  name: toolName,
1006
+ spanId: spanIdB64,
656
1007
  input: inputStr2,
657
1008
  output: void 0,
658
1009
  durationMs: durationMs2,
@@ -663,6 +1014,16 @@ var LiveInteraction = class {
663
1014
  traceId: traceIdB64,
664
1015
  parentSpanId: parentSpanIdB64
665
1016
  });
1017
+ this.emitLiveEvent({
1018
+ traceId: traceIdB64,
1019
+ type: "tool_result",
1020
+ content: toolName,
1021
+ timestamp: endTimeMs2,
1022
+ metadata: {
1023
+ ...params.inputParameters ? { args: params.inputParameters } : {},
1024
+ error
1025
+ }
1026
+ });
666
1027
  throw err;
667
1028
  }
668
1029
  const endTimeMs = Date.now();
@@ -671,6 +1032,7 @@ var LiveInteraction = class {
671
1032
  const outputStr = result !== void 0 ? typeof result === "string" ? result : JSON.stringify(result) : void 0;
672
1033
  this.directShipper.sendToolSpan({
673
1034
  name: toolName,
1035
+ spanId: spanIdB64,
674
1036
  input: inputStr,
675
1037
  output: outputStr,
676
1038
  durationMs,
@@ -681,22 +1043,61 @@ var LiveInteraction = class {
681
1043
  traceId: traceIdB64,
682
1044
  parentSpanId: parentSpanIdB64
683
1045
  });
1046
+ this.emitLiveEvent({
1047
+ traceId: traceIdB64,
1048
+ type: "tool_result",
1049
+ content: toolName,
1050
+ timestamp: endTimeMs,
1051
+ metadata: {
1052
+ ...params.inputParameters ? { args: params.inputParameters } : {},
1053
+ ...result !== void 0 ? { result } : {}
1054
+ }
1055
+ });
684
1056
  return result;
685
1057
  }
1058
+ this.emitLiveEvent({
1059
+ type: "tool_start",
1060
+ content: toolName,
1061
+ timestamp: Date.now(),
1062
+ metadata: params.inputParameters ? { args: params.inputParameters } : void 0
1063
+ });
686
1064
  const inputParams = params.inputParameters ? [params.inputParameters] : void 0;
687
- return traceloop.withTool(
688
- {
689
- name: toolName,
690
- associationProperties: serializeAssociationProperties(properties),
691
- inputParameters: inputParams,
692
- version: params.version,
693
- traceContent: params.traceContent,
694
- suppressTracing: params.suppressTracing
695
- },
696
- fn,
697
- thisArg,
698
- ...args
699
- );
1065
+ try {
1066
+ const result = await traceloop.withTool(
1067
+ {
1068
+ name: toolName,
1069
+ associationProperties: serializeAssociationProperties(properties),
1070
+ inputParameters: inputParams,
1071
+ version: params.version,
1072
+ traceContent: params.traceContent,
1073
+ suppressTracing: params.suppressTracing
1074
+ },
1075
+ fn,
1076
+ thisArg,
1077
+ ...args
1078
+ );
1079
+ this.emitLiveEvent({
1080
+ type: "tool_result",
1081
+ content: toolName,
1082
+ timestamp: Date.now(),
1083
+ metadata: {
1084
+ ...params.inputParameters ? { args: params.inputParameters } : {},
1085
+ ...result !== void 0 ? { result } : {}
1086
+ }
1087
+ });
1088
+ return result;
1089
+ } catch (error) {
1090
+ this.emitLiveEvent({
1091
+ type: "tool_result",
1092
+ content: toolName,
1093
+ timestamp: Date.now(),
1094
+ metadata: {
1095
+ ...params.inputParameters ? { args: params.inputParameters } : {},
1096
+ error: error instanceof Error ? error.message : String(error)
1097
+ }
1098
+ });
1099
+ throw error;
1100
+ }
700
1101
  }
701
1102
  startSpan(params) {
702
1103
  const { name, properties = {} } = params;
@@ -716,17 +1117,27 @@ var LiveInteraction = class {
716
1117
  ...properties
717
1118
  };
718
1119
  if (this.directShipper) {
719
- const { traceIdB64, parentSpanIdB64 } = getActiveTraceContext();
1120
+ const activeTraceContext = getActiveTraceContext();
1121
+ const traceIdB64 = this.ensureTraceId(activeTraceContext.traceIdB64);
1122
+ const { parentSpanIdB64 } = activeTraceContext;
720
1123
  if ((_a = this.analytics) == null ? void 0 : _a.debugLogs) {
721
1124
  console.log(`[raindrop] startToolSpan (direct): started tool span "${name}"`);
722
1125
  }
1126
+ this.emitLiveEvent({
1127
+ traceId: traceIdB64,
1128
+ type: "tool_start",
1129
+ content: name,
1130
+ timestamp: Date.now(),
1131
+ metadata: inputParameters !== void 0 ? { args: inputParameters } : void 0
1132
+ });
723
1133
  return new DirectToolSpan({
724
1134
  name,
725
1135
  properties: mergedProperties,
726
1136
  directShipper: this.directShipper,
727
1137
  traceId: traceIdB64,
728
1138
  parentSpanId: parentSpanIdB64,
729
- input: inputParameters
1139
+ input: inputParameters,
1140
+ emitLiveEvent: (event) => this.emitLiveEvent(event)
730
1141
  });
731
1142
  }
732
1143
  const span = this.tracer.startSpan(name);
@@ -739,7 +1150,17 @@ var LiveInteraction = class {
739
1150
  if ((_b = this.analytics) == null ? void 0 : _b.debugLogs) {
740
1151
  console.log(`[raindrop] startToolSpan: started tool span "${name}"`);
741
1152
  }
742
- return new LiveToolSpan(span);
1153
+ this.emitLiveEvent({
1154
+ type: "tool_start",
1155
+ content: name,
1156
+ timestamp: Date.now(),
1157
+ metadata: inputParameters !== void 0 ? { args: inputParameters } : void 0
1158
+ });
1159
+ return new LiveToolSpan({
1160
+ span,
1161
+ name,
1162
+ emitLiveEvent: (event) => this.emitLiveEvent(event)
1163
+ });
743
1164
  }
744
1165
  setProperties(properties) {
745
1166
  var _a;
@@ -784,6 +1205,9 @@ var LiveInteraction = class {
784
1205
  if (this.context.eventId) {
785
1206
  metadata["traceloop.association.properties.event_id"] = this.context.eventId;
786
1207
  }
1208
+ if (this.context.event) {
1209
+ metadata["traceloop.association.properties.event_name"] = this.context.event;
1210
+ }
787
1211
  if (this.context.properties) {
788
1212
  for (const [key, value] of Object.entries(this.context.properties)) {
789
1213
  if (value === void 0) {
@@ -814,7 +1238,9 @@ var LiveInteraction = class {
814
1238
  const startTimeMs = startTime instanceof Date ? startTime.getTime() : typeof startTime === "number" ? startTime : Date.now() - (durationMs != null ? durationMs : 0);
815
1239
  const endTimeMs = startTimeMs + (durationMs != null ? durationMs : 0);
816
1240
  if (this.directShipper) {
817
- const { traceIdB64, parentSpanIdB64 } = getActiveTraceContext();
1241
+ const activeContext = getActiveTraceContext();
1242
+ const traceIdB64 = this.ensureTraceId(activeContext.traceIdB64);
1243
+ const { parentSpanIdB64 } = activeContext;
818
1244
  const inputStr = input !== void 0 ? typeof input === "string" ? input : JSON.stringify(input) : void 0;
819
1245
  const outputStr = output !== void 0 ? typeof output === "string" ? output : JSON.stringify(output) : void 0;
820
1246
  this.directShipper.sendToolSpan({
@@ -840,6 +1266,17 @@ var LiveInteraction = class {
840
1266
  error: error ? String(error) : void 0
841
1267
  });
842
1268
  }
1269
+ this.emitLiveEvent({
1270
+ traceId: traceIdB64,
1271
+ type: "tool_result",
1272
+ content: name,
1273
+ timestamp: endTimeMs,
1274
+ metadata: {
1275
+ ...input !== void 0 ? { input } : {},
1276
+ ...output !== void 0 ? { result: output } : {},
1277
+ ...error ? { error: error instanceof Error ? error.message : String(error) } : {}
1278
+ }
1279
+ });
843
1280
  return;
844
1281
  }
845
1282
  const span = this.tracer.startSpan(name, {
@@ -876,6 +1313,16 @@ var LiveInteraction = class {
876
1313
  error: error ? String(error) : void 0
877
1314
  });
878
1315
  }
1316
+ this.emitLiveEvent({
1317
+ type: "tool_result",
1318
+ content: name,
1319
+ timestamp: endTimeMs,
1320
+ metadata: {
1321
+ ...input !== void 0 ? { input } : {},
1322
+ ...output !== void 0 ? { result: output } : {},
1323
+ ...error ? { error: error instanceof Error ? error.message : String(error) } : {}
1324
+ }
1325
+ });
879
1326
  }
880
1327
  };
881
1328
 
@@ -888,6 +1335,18 @@ var LiveTracer = class {
888
1335
  this.globalProperties = globalProperties || {};
889
1336
  this.directShipper = directShipper;
890
1337
  }
1338
+ emitLiveEvent(event) {
1339
+ var _a, _b;
1340
+ const activeSpan = import_api3.trace.getSpan(import_api3.context.active());
1341
+ const activeTraceId = activeSpan == null ? void 0 : activeSpan.spanContext().traceId;
1342
+ const active = getActiveTraceContext();
1343
+ const traceId = (_b = (_a = event.traceId) != null ? _a : activeTraceId) != null ? _b : active.traceIdB64;
1344
+ if (!traceId) return;
1345
+ sendLocalDebuggerLiveEvent({
1346
+ ...event,
1347
+ traceId
1348
+ });
1349
+ }
891
1350
  async withSpan(params, fn, thisArg, ...args) {
892
1351
  const taskName = typeof params === "string" ? params : params.name;
893
1352
  const properties = typeof params === "string" ? {
@@ -911,6 +1370,7 @@ var LiveTracer = class {
911
1370
  );
912
1371
  }
913
1372
  trackTool(params) {
1373
+ var _a;
914
1374
  const { name, input, output, durationMs, startTime, error, properties = {} } = params;
915
1375
  const startTimeMs = startTime instanceof Date ? startTime.getTime() : typeof startTime === "number" ? startTime : Date.now() - (durationMs != null ? durationMs : 0);
916
1376
  const endTimeMs = startTimeMs + (durationMs != null ? durationMs : 0);
@@ -933,6 +1393,19 @@ var LiveTracer = class {
933
1393
  traceId: traceIdB64,
934
1394
  parentSpanId: parentSpanIdB64
935
1395
  });
1396
+ if (traceIdB64) {
1397
+ this.emitLiveEvent({
1398
+ traceId: traceIdB64,
1399
+ type: "tool_result",
1400
+ content: name,
1401
+ timestamp: endTimeMs,
1402
+ metadata: {
1403
+ ...input !== void 0 ? { input } : {},
1404
+ ...output !== void 0 ? { result: output } : {},
1405
+ ...error ? { error: error instanceof Error ? error.message : String(error) } : {}
1406
+ }
1407
+ });
1408
+ }
936
1409
  return;
937
1410
  }
938
1411
  const span = this.tracer.startSpan(name, {
@@ -964,10 +1437,32 @@ var LiveTracer = class {
964
1437
  span.setStatus({ code: import_api3.SpanStatusCode.OK });
965
1438
  }
966
1439
  span.end(endTimeMs);
1440
+ const traceId = span.spanContext().traceId || ((_a = import_api3.trace.getSpan(import_api3.context.active())) == null ? void 0 : _a.spanContext().traceId);
1441
+ if (traceId) {
1442
+ this.emitLiveEvent({
1443
+ traceId,
1444
+ type: "tool_result",
1445
+ content: name,
1446
+ timestamp: endTimeMs,
1447
+ metadata: {
1448
+ ...input !== void 0 ? { input } : {},
1449
+ ...output !== void 0 ? { result: output } : {},
1450
+ ...error ? { error: error instanceof Error ? error.message : String(error) } : {}
1451
+ }
1452
+ });
1453
+ }
967
1454
  }
968
1455
  };
969
1456
 
970
1457
  // src/tracing/tracer-core.ts
1458
+ if (localDebuggerEnabled()) {
1459
+ if (!process.env.OTEL_EXPORTER_OTLP_PROTOCOL) {
1460
+ process.env.OTEL_EXPORTER_OTLP_PROTOCOL = "http/json";
1461
+ }
1462
+ if (!process.env.OTEL_EXPORTER_OTLP_TRACES_PROTOCOL) {
1463
+ process.env.OTEL_EXPORTER_OTLP_TRACES_PROTOCOL = "http/json";
1464
+ }
1465
+ }
971
1466
  try {
972
1467
  const _bedrockProto = import_instrumentation_bedrock.BedrockInstrumentation.prototype;
973
1468
  _bedrockProto._wrapPromise = function(span, promise) {
@@ -1355,21 +1850,26 @@ var tracing = (analytics, apiUrl, writeKey, options, isDebug = false) => {
1355
1850
  });
1356
1851
  },
1357
1852
  begin(traceContext) {
1853
+ var _a;
1358
1854
  if (!traceContext.eventId) {
1359
1855
  traceContext.eventId = crypto.randomUUID();
1360
1856
  }
1361
1857
  const traceId = getCurrentTraceId();
1362
- analytics._trackAiPartial({
1363
- ...traceContext
1364
- });
1365
1858
  const interaction = new LiveInteraction(
1366
1859
  traceContext,
1367
1860
  traceId,
1368
1861
  analytics,
1369
1862
  directShipper
1370
1863
  );
1371
- if (traceId) {
1372
- activeInteractions.set(traceId, interaction);
1864
+ analytics._trackAiPartial({
1865
+ ...traceContext,
1866
+ properties: {
1867
+ ...(_a = traceContext.properties) != null ? _a : {},
1868
+ ...interaction.getTraceId() ? { trace_id: interaction.getTraceId() } : {}
1869
+ }
1870
+ });
1871
+ if (interaction.getTraceId()) {
1872
+ activeInteractions.set(interaction.getTraceId(), interaction);
1373
1873
  }
1374
1874
  activeInteractionsByEventId.set(traceContext.eventId, interaction);
1375
1875
  return interaction;