raindrop-ai 1.0.7 → 1.0.8

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.
@@ -108,7 +108,7 @@ function evalScopeAttributes() {
108
108
  return { [EVAL_CORRELATION_ID_ATTRIBUTE]: scope.correlationId };
109
109
  }
110
110
 
111
- // ../core/dist/chunk-AX36JKJL.js
111
+ // ../core/dist/chunk-R5EQZAA5.js
112
112
  var require_NameRedactor = __commonJS({
113
113
  "../redact-pii/dist/built-ins/NameRedactor.js"(exports) {
114
114
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -977,9 +977,9 @@ var SUBAGENT_ABORT_OPERATION_ID = "ai.subagent.failed";
977
977
  var SUBAGENT_ABORT_SPAN_NAME = SUBAGENT_ABORT_OPERATION_ID;
978
978
  var DEFAULT_DISPATCH_SPAN_NAME = "launch_subagent";
979
979
  var HANDOFF_TERMINAL_PROPERTY_KEY = HANDOFF_ATTRIBUTE_SUFFIXES.terminal;
980
- function defined(entries) {
980
+ function defined(entries2) {
981
981
  const out = {};
982
- for (const [key, value] of Object.entries(entries)) {
982
+ for (const [key, value] of Object.entries(entries2)) {
983
983
  if (typeof value === "string" && value.trim().length > 0) out[key] = value;
984
984
  }
985
985
  return out;
@@ -1053,8 +1053,8 @@ function warnNonConformantIdsOnce(traceId, spanId) {
1053
1053
  var HANDOFF_HEADER = "x-raindrop-handoff";
1054
1054
  var LANGSMITH_TRACE_HEADER = "langsmith-trace";
1055
1055
  var LANGSMITH_METADATA_BAGGAGE_KEY = "langsmith-metadata";
1056
- function encodeBaggage(entries) {
1057
- return Object.entries(entries).filter((entry) => Boolean(entry[1])).map(([key, value]) => `${key}=${encodeURIComponent(value)}`).join(",");
1056
+ function encodeBaggage(entries2) {
1057
+ return Object.entries(entries2).filter((entry) => Boolean(entry[1])).map(([key, value]) => `${key}=${encodeURIComponent(value)}`).join(",");
1058
1058
  }
1059
1059
  function decodeBaggage(header) {
1060
1060
  if (!header) return {};
@@ -1481,7 +1481,7 @@ async function sendJson(url, body, headers, opts) {
1481
1481
  resp = await runWithTracingSuppressed(
1482
1482
  () => fetch(url, {
1483
1483
  method: "POST",
1484
- redirect: headers["X-Raindrop-Replay-Id"] !== void 0 ? "error" : "follow",
1484
+ redirect: headers["X-Raindrop-Replay-Id"] !== void 0 || opts.followRedirects === false ? "error" : "follow",
1485
1485
  headers: {
1486
1486
  "Content-Type": "application/json",
1487
1487
  ...headers
@@ -1769,7 +1769,8 @@ function mirrorTraceExportToLocalDebugger(body, options = {}) {
1769
1769
  maxAttempts: 1,
1770
1770
  debug: (_a = options.debug) != null ? _a : false,
1771
1771
  sdkName: options.sdkName,
1772
- timeoutMs: LOCAL_DEBUGGER_MIRROR_TIMEOUT_MS
1772
+ timeoutMs: LOCAL_DEBUGGER_MIRROR_TIMEOUT_MS,
1773
+ followRedirects: options.followRedirects
1773
1774
  }).catch(() => {
1774
1775
  });
1775
1776
  }
@@ -1782,7 +1783,8 @@ function mirrorPartialEventToLocalDebugger(event, options = {}) {
1782
1783
  maxAttempts: 1,
1783
1784
  debug: (_a = options.debug) != null ? _a : false,
1784
1785
  sdkName: options.sdkName,
1785
- timeoutMs: LOCAL_DEBUGGER_MIRROR_TIMEOUT_MS
1786
+ timeoutMs: LOCAL_DEBUGGER_MIRROR_TIMEOUT_MS,
1787
+ followRedirects: options.followRedirects
1786
1788
  }).catch(() => {
1787
1789
  });
1788
1790
  }
@@ -1803,7 +1805,8 @@ function sendLocalDebuggerLiveEvent(event, options = {}) {
1803
1805
  {
1804
1806
  maxAttempts: 1,
1805
1807
  debug: (_b = options.debug) != null ? _b : false,
1806
- sdkName: options.sdkName
1808
+ sdkName: options.sdkName,
1809
+ followRedirects: options.followRedirects
1807
1810
  }
1808
1811
  ).catch(() => {
1809
1812
  });
@@ -2046,6 +2049,143 @@ var PiiFieldRedactor = class {
2046
2049
  return out;
2047
2050
  }
2048
2051
  };
2052
+ var REMOTE_PII_LOOKUP_TIMEOUT_MS = 3e3;
2053
+ var REFRESH_AFTER_MS = 5 * 6e4;
2054
+ var RETRY_AFTER_MS = 3e4;
2055
+ var STATE_KEY2 = /* @__PURE__ */ Symbol.for("raindrop.remotePiiConfig");
2056
+ function entries() {
2057
+ const holder = globalThis;
2058
+ let current = holder[STATE_KEY2];
2059
+ if (!current) {
2060
+ current = /* @__PURE__ */ new Map();
2061
+ holder[STATE_KEY2] = current;
2062
+ }
2063
+ return current;
2064
+ }
2065
+ function isRecord2(value) {
2066
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2067
+ }
2068
+ function baseUrlOf(endpoint) {
2069
+ return endpoint.endsWith("/") ? endpoint : `${endpoint}/`;
2070
+ }
2071
+ function cacheKey(endpoint, writeKey) {
2072
+ return `${baseUrlOf(endpoint)}
2073
+ ${writeKey}`;
2074
+ }
2075
+ function parseAnswer(body) {
2076
+ if (!isRecord2(body)) return "unknown";
2077
+ if (!("pii" in body)) return "not_enrolled";
2078
+ const pii = body.pii;
2079
+ if (!isRecord2(pii)) return "unknown";
2080
+ return pii.redact === "on" || pii.redact === "off" ? pii.redact : "unknown";
2081
+ }
2082
+ async function lookup(baseUrl, writeKey) {
2083
+ if (typeof fetch !== "function") return void 0;
2084
+ const controller = typeof AbortController === "function" ? new AbortController() : void 0;
2085
+ const timer = setTimeout(() => controller == null ? void 0 : controller.abort(), REMOTE_PII_LOOKUP_TIMEOUT_MS);
2086
+ if (typeof timer === "object" && "unref" in timer) timer.unref();
2087
+ try {
2088
+ const response = await runWithTracingSuppressed(
2089
+ () => fetch(`${baseUrl}auth`, {
2090
+ method: "POST",
2091
+ headers: { Authorization: `Bearer ${writeKey}`, "Content-Type": "application/json" },
2092
+ body: "{}",
2093
+ signal: controller == null ? void 0 : controller.signal
2094
+ })
2095
+ );
2096
+ if (!response.ok) return void 0;
2097
+ const body = await response.json();
2098
+ return parseAnswer(body);
2099
+ } catch (e) {
2100
+ return void 0;
2101
+ } finally {
2102
+ clearTimeout(timer);
2103
+ }
2104
+ }
2105
+ function entryFor(endpoint, writeKey) {
2106
+ const key = cacheKey(endpoint, writeKey);
2107
+ const all = entries();
2108
+ let entry = all.get(key);
2109
+ if (!entry) {
2110
+ entry = { known: void 0, pending: void 0, nextLookupAt: 0, settled: false };
2111
+ all.set(key, entry);
2112
+ }
2113
+ if (!entry.pending && Date.now() >= entry.nextLookupAt) {
2114
+ const current = entry;
2115
+ current.pending = lookup(baseUrlOf(endpoint), writeKey).then((answer) => {
2116
+ if (answer !== void 0) current.known = answer;
2117
+ current.nextLookupAt = Date.now() + (answer === void 0 ? RETRY_AFTER_MS : REFRESH_AFTER_MS);
2118
+ current.pending = void 0;
2119
+ current.settled = true;
2120
+ });
2121
+ }
2122
+ return entry;
2123
+ }
2124
+ function remotePiiAnswerNow(endpoint, writeKey) {
2125
+ const entry = entryFor(endpoint, writeKey);
2126
+ if (entry.known !== void 0) return entry.known;
2127
+ return entry.settled ? "unknown" : void 0;
2128
+ }
2129
+ async function remotePiiAnswer(endpoint, writeKey, deadlineAt) {
2130
+ var _a;
2131
+ const entry = entryFor(endpoint, writeKey);
2132
+ const now = remotePiiAnswerNow(endpoint, writeKey);
2133
+ if (now !== void 0 || !entry.pending) return now != null ? now : "unknown";
2134
+ const waitMs = Math.min(
2135
+ REMOTE_PII_LOOKUP_TIMEOUT_MS,
2136
+ deadlineAt === void 0 ? Infinity : Math.max(0, deadlineAt - Date.now())
2137
+ );
2138
+ let timer;
2139
+ await Promise.race([
2140
+ entry.pending,
2141
+ new Promise((resolve2) => {
2142
+ timer = setTimeout(resolve2, waitMs);
2143
+ })
2144
+ ]);
2145
+ clearTimeout(timer);
2146
+ return (_a = entry.known) != null ? _a : "unknown";
2147
+ }
2148
+ function resolvePiiRedaction(local, remote, answer) {
2149
+ if (local !== void 0) return local;
2150
+ if (!remote) return false;
2151
+ if (answer === "on") return true;
2152
+ if (answer === "off" || answer === "not_enrolled") return false;
2153
+ const whenUnknown = typeof remote === "object" ? remote.whenUnknown : void 0;
2154
+ return whenUnknown !== "local";
2155
+ }
2156
+ function needsLookup(local, remote, writeKey) {
2157
+ return local === void 0 && Boolean(remote) && Boolean(writeKey);
2158
+ }
2159
+ function piiRedactionNow(local, remote, endpoint, writeKey) {
2160
+ if (!needsLookup(local, remote, writeKey)) return local === true;
2161
+ try {
2162
+ const answer = remotePiiAnswerNow(endpoint, writeKey);
2163
+ return answer === void 0 ? void 0 : resolvePiiRedaction(local, remote, answer);
2164
+ } catch (e) {
2165
+ return resolvePiiRedaction(local, remote, "unknown");
2166
+ }
2167
+ }
2168
+ async function piiRedaction(local, remote, endpoint, writeKey, deadlineAt) {
2169
+ if (!needsLookup(local, remote, writeKey)) return local === true;
2170
+ try {
2171
+ return resolvePiiRedaction(local, remote, await remotePiiAnswer(endpoint, writeKey, deadlineAt));
2172
+ } catch (e) {
2173
+ return resolvePiiRedaction(local, remote, "unknown");
2174
+ }
2175
+ }
2176
+ var LOCAL_TRACE_KEY = /* @__PURE__ */ Symbol.for("raindrop.localTracePiiRedaction");
2177
+ function localTraceKeys() {
2178
+ var _a;
2179
+ const holder = globalThis;
2180
+ (_a = holder[LOCAL_TRACE_KEY]) != null ? _a : holder[LOCAL_TRACE_KEY] = /* @__PURE__ */ new Set();
2181
+ return holder[LOCAL_TRACE_KEY];
2182
+ }
2183
+ function requestLocalTracePiiRedaction(endpoint, writeKey) {
2184
+ localTraceKeys().add(cacheKey(endpoint, writeKey != null ? writeKey : ""));
2185
+ }
2186
+ function localTracePiiRedactionRequested(endpoint, writeKey) {
2187
+ return localTraceKeys().has(cacheKey(endpoint, writeKey != null ? writeKey : ""));
2188
+ }
2049
2189
  function detectRuntime() {
2050
2190
  if (typeof process === "object" && process && typeof process.env === "object" && process.env && typeof process.version === "string") {
2051
2191
  return "node";
@@ -2065,6 +2205,14 @@ function isMissingUserId(value) {
2065
2205
  const trimmed = value.trim();
2066
2206
  return trimmed === "" || PLACEHOLDER_USER_IDS.has(trimmed);
2067
2207
  }
2208
+ function snapshotPayload(payload) {
2209
+ try {
2210
+ const json = JSON.stringify(payload);
2211
+ return json === void 0 ? payload : JSON.parse(json);
2212
+ } catch (e) {
2213
+ return payload;
2214
+ }
2215
+ }
2068
2216
  var MAX_DEFERRED_SENDS = 1e3;
2069
2217
  var POST_SHUTDOWN_TIMEOUT_MS = 5e3;
2070
2218
  function appGitOwnerId(prefix) {
@@ -2171,7 +2319,7 @@ var EventShipper = class {
2171
2319
  this.sendChains = /* @__PURE__ */ new Map();
2172
2320
  this.deferredSends = /* @__PURE__ */ new Set();
2173
2321
  this.hasShutdown = false;
2174
- var _a, _b, _c, _d, _e, _f, _g, _h, _i;
2322
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
2175
2323
  this.appGitContext = (_a = opts.appGitContext) != null ? _a : createAppGitContext(opts.appGit);
2176
2324
  this.ownsAppGitContext = opts.appGitContext === void 0;
2177
2325
  this.writeKey = (_b = opts.writeKey) == null ? void 0 : _b.trim();
@@ -2185,6 +2333,7 @@ var EventShipper = class {
2185
2333
  this.maxTextFieldCharsOpt = opts.maxTextFieldChars;
2186
2334
  this.flushTimeoutMs = resolveFlushTimeoutMs(opts.flushTimeoutMs);
2187
2335
  this.localDebuggerUrl = (_g = resolveLocalDebuggerBaseUrl(opts.localDebuggerUrl)) != null ? _g : void 0;
2336
+ this.localDebuggerFollowRedirects = (_h = opts.localDebuggerFollowRedirects) != null ? _h : true;
2188
2337
  if (this.debug && this.localDebuggerUrl) {
2189
2338
  console.log(`${this.prefix} Local debugger mirroring: ${this.localDebuggerUrl}`);
2190
2339
  }
@@ -2192,12 +2341,15 @@ var EventShipper = class {
2192
2341
  debug: this.debug,
2193
2342
  prefix: this.prefix
2194
2343
  });
2195
- this.redactPii = opts.redactPii === true;
2344
+ this.redactPii = typeof opts.redactPii === "boolean" ? opts.redactPii : void 0;
2345
+ this.remotePiiConfig = opts.remotePiiConfig;
2196
2346
  this.piiFields = new PiiFieldRedactor({
2197
2347
  startupFieldMap: opts.redactPiiFields,
2198
2348
  logPrefix: this.prefix
2199
2349
  });
2200
- if (opts.redactPiiFields && !this.redactPii) {
2350
+ const fields = opts.redactPiiFields;
2351
+ const hasPayloadFields = Boolean(fields && (fields.event || fields.signal || fields.identify));
2352
+ if (hasPayloadFields && this.redactPii !== true && !this.remotePiiConfig) {
2201
2353
  rateLimitedLog(
2202
2354
  `${this.prefix}.pii_fields_without_redaction`,
2203
2355
  () => console.warn(
@@ -2209,8 +2361,8 @@ var EventShipper = class {
2209
2361
  const runtime = detectRuntime();
2210
2362
  this.context = {
2211
2363
  library: {
2212
- name: (_h = opts.libraryName) != null ? _h : "@raindrop-ai/core",
2213
- version: (_i = opts.libraryVersion) != null ? _i : "0.0.0"
2364
+ name: (_i = opts.libraryName) != null ? _i : "@raindrop-ai/core",
2365
+ version: (_j = opts.libraryVersion) != null ? _j : "0.0.0"
2214
2366
  },
2215
2367
  metadata: {
2216
2368
  jsRuntime: runtime,
@@ -2551,7 +2703,7 @@ var EventShipper = class {
2551
2703
  if (!this.enabled) return;
2552
2704
  const destination = currentReplayTraceDestination();
2553
2705
  if (destination && destination.kind !== "workshop") return;
2554
- const body = [
2706
+ const items = [
2555
2707
  {
2556
2708
  event_id: signal.eventId,
2557
2709
  signal_name: signal.name,
@@ -2565,16 +2717,28 @@ var EventShipper = class {
2565
2717
  ...signal.after ? { after: signal.after } : {}
2566
2718
  }
2567
2719
  }
2568
- ].map((item) => this.redactFields("signal", item));
2569
- if (!this.writeKey) return;
2570
- await this.sendDirect("signal", `${this.baseUrl}signals/track`, body);
2720
+ ];
2721
+ const known = piiRedactionNow(this.redactPii, this.remotePiiConfig, this.baseUrl, this.writeKey);
2722
+ if (known !== void 0) {
2723
+ const body = known ? items.map((item) => this.piiFields.redact("signal", item)) : items;
2724
+ if (!this.writeKey) return;
2725
+ await this.sendDirect("signal", `${this.baseUrl}signals/track`, body);
2726
+ return;
2727
+ }
2728
+ const snapshot = items.map(snapshotPayload);
2729
+ await this.tracked(async () => {
2730
+ const redact = await this.shouldRedactPii();
2731
+ const body = redact ? snapshot.map((item) => this.piiFields.redact("signal", item)) : snapshot;
2732
+ if (!this.writeKey) return;
2733
+ await this.sendDirect("signal", `${this.baseUrl}signals/track`, body, void 0, false);
2734
+ });
2571
2735
  }
2572
2736
  async identify(users) {
2573
2737
  if (!this.enabled) return;
2574
2738
  const destination = currentReplayTraceDestination();
2575
2739
  if (destination && destination.kind !== "workshop") return;
2576
2740
  const list = Array.isArray(users) ? users : [users];
2577
- const body = list.filter((user) => {
2741
+ const rows = list.filter((user) => {
2578
2742
  if (!(user == null ? void 0 : user.userId) || !user.userId.trim()) {
2579
2743
  if (this.debug) {
2580
2744
  console.warn(`${this.prefix} skipping identify: missing userId`);
@@ -2582,24 +2746,34 @@ var EventShipper = class {
2582
2746
  return false;
2583
2747
  }
2584
2748
  return true;
2585
- }).map(
2586
- (user) => {
2587
- var _a;
2588
- return this.redactFields("identify", {
2589
- user_id: user.userId,
2590
- traits: (_a = user.traits) != null ? _a : {}
2591
- });
2592
- }
2593
- );
2749
+ }).map((user) => {
2750
+ var _a;
2751
+ return {
2752
+ user_id: user.userId,
2753
+ traits: (_a = user.traits) != null ? _a : {}
2754
+ };
2755
+ });
2594
2756
  if (!this.writeKey) return;
2595
- if (body.length === 0) return;
2596
- await this.sendDirect("identify", `${this.baseUrl}users/identify`, body);
2757
+ if (rows.length === 0) return;
2758
+ const known = piiRedactionNow(this.redactPii, this.remotePiiConfig, this.baseUrl, this.writeKey);
2759
+ if (known !== void 0) {
2760
+ const body = known ? rows.map((user) => this.piiFields.redact("identify", user)) : rows;
2761
+ await this.sendDirect("identify", `${this.baseUrl}users/identify`, body);
2762
+ return;
2763
+ }
2764
+ const snapshot = rows.map(snapshotPayload);
2765
+ await this.tracked(async () => {
2766
+ const redact = await this.shouldRedactPii();
2767
+ const body = redact ? snapshot.map((user) => this.piiFields.redact("identify", user)) : snapshot;
2768
+ await this.sendDirect("identify", `${this.baseUrl}users/identify`, body, void 0, false);
2769
+ });
2597
2770
  }
2598
2771
  /**
2599
- * Send a signal or identify body. Tracked so `flush()` waits for it. A send
2600
- * a flush deadline deferred is kept and retried later (outside shutdown).
2772
+ * Send a signal or identify body. Tracked so `flush()` waits for it, unless
2773
+ * the caller already tracks it (`track: false`). A send a flush deadline
2774
+ * deferred is kept and retried later (outside shutdown).
2601
2775
  */
2602
- async sendDirect(kind, url, body, deadlineAt) {
2776
+ async sendDirect(kind, url, body, deadlineAt, track = true) {
2603
2777
  const opts = this.requestOpts(deadlineAt);
2604
2778
  if (!opts) {
2605
2779
  this.warnShutdownDrop(kind);
@@ -2607,7 +2781,7 @@ var EventShipper = class {
2607
2781
  }
2608
2782
  const sending = sendJson(url, body, this.requestHeaders(), opts);
2609
2783
  const tracked = sending.then(() => void 0);
2610
- this.inFlight.add(tracked);
2784
+ if (track) this.inFlight.add(tracked);
2611
2785
  let outcome;
2612
2786
  try {
2613
2787
  outcome = await sending;
@@ -2653,9 +2827,36 @@ var EventShipper = class {
2653
2827
  () => console.warn(`${this.prefix} failed to send ${what} (dropping): ${reason}`)
2654
2828
  );
2655
2829
  }
2656
- /** The payload with its PII fields redacted when `redactPii` is on (CONTRACT 11.2). */
2657
- redactFields(kind, payload) {
2658
- return this.redactPii ? this.piiFields.redact(kind, payload) : payload;
2830
+ /**
2831
+ * Whether to redact PII: `redactPii`, or when it is unset and
2832
+ * `remotePiiConfig` is on, the org's setting. Waits for the org's answer
2833
+ * before the first send, never past `deadlineAt`.
2834
+ */
2835
+ async shouldRedactPii(deadlineAt) {
2836
+ return piiRedaction(
2837
+ this.redactPii,
2838
+ this.remotePiiConfig,
2839
+ this.baseUrl,
2840
+ this.writeKey,
2841
+ deadlineAt != null ? deadlineAt : this.shutdownDeadlineAt
2842
+ );
2843
+ }
2844
+ /**
2845
+ * Runs `work` (the org lookup, then one `sendDirect` with `track: false`)
2846
+ * as one in-flight send, so a `flush()` started meanwhile waits for both.
2847
+ */
2848
+ async tracked(work) {
2849
+ const running = Promise.resolve().then(work);
2850
+ const done = running.then(
2851
+ () => void 0,
2852
+ () => void 0
2853
+ );
2854
+ this.inFlight.add(done);
2855
+ try {
2856
+ await running;
2857
+ } finally {
2858
+ this.inFlight.delete(done);
2859
+ }
2659
2860
  }
2660
2861
  warnShutdownDrop(what) {
2661
2862
  rateLimitedLog(
@@ -2720,7 +2921,7 @@ var EventShipper = class {
2720
2921
  return "queued";
2721
2922
  }
2722
2923
  async sendAccumulated(eventId, accumulated, deadlineAt) {
2723
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
2924
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
2724
2925
  const sticky = (_a = this.sticky.get(eventId)) != null ? _a : {};
2725
2926
  const isPending = (_c = (_b = accumulated.isPending) != null ? _b : sticky.isPending) != null ? _c : true;
2726
2927
  const knownEventName = (_d = accumulated.eventName) != null ? _d : sticky.eventName;
@@ -2776,7 +2977,37 @@ var EventShipper = class {
2776
2977
  attachments: accumulated.attachments,
2777
2978
  is_pending: isPending
2778
2979
  };
2779
- const payload = this.redactFields("event", unredacted);
2980
+ const known = piiRedactionNow(this.redactPii, this.remotePiiConfig, this.baseUrl, this.writeKey);
2981
+ if (known !== void 0) {
2982
+ const payload = known ? this.piiFields.redact("event", unredacted) : unredacted;
2983
+ return this.shipPartial(eventId, accumulated, payload, { eventName, userId, convoId, isPending }, deadlineAt, true);
2984
+ }
2985
+ const snapshot = snapshotPayload(unredacted);
2986
+ const running = this.shouldRedactPii(deadlineAt).then(
2987
+ (redact) => this.shipPartial(
2988
+ eventId,
2989
+ accumulated,
2990
+ redact ? this.piiFields.redact("event", snapshot) : snapshot,
2991
+ { eventName, userId, convoId, isPending },
2992
+ deadlineAt,
2993
+ false
2994
+ )
2995
+ );
2996
+ const done = running.then(
2997
+ () => void 0,
2998
+ () => void 0
2999
+ );
3000
+ this.inFlight.add(done);
3001
+ try {
3002
+ return await running;
3003
+ } finally {
3004
+ this.inFlight.delete(done);
3005
+ }
3006
+ }
3007
+ /** Sends one redacted partial payload; `track: false` when the caller already tracks it. */
3008
+ async shipPartial(eventId, accumulated, payload, meta, deadlineAt, track) {
3009
+ var _a, _b, _c, _d, _e, _f;
3010
+ const { eventName, userId, convoId, isPending } = meta;
2780
3011
  const url = `${this.baseUrl}events/track_partial`;
2781
3012
  if (this.debug) {
2782
3013
  const sent = payload;
@@ -2787,20 +3018,21 @@ var EventShipper = class {
2787
3018
  userId,
2788
3019
  convoId,
2789
3020
  isPending,
2790
- inputPreview: preview((_k = sent.ai_data) == null ? void 0 : _k.input, 120),
2791
- outputPreview: preview((_l = sent.ai_data) == null ? void 0 : _l.output, 120),
2792
- attachments: (_n = (_m = sent.attachments) == null ? void 0 : _m.length) != null ? _n : 0,
2793
- attachmentKinds: (_p = (_o = sent.attachments) == null ? void 0 : _o.map((a) => ({
3021
+ inputPreview: preview((_a = sent.ai_data) == null ? void 0 : _a.input, 120),
3022
+ outputPreview: preview((_b = sent.ai_data) == null ? void 0 : _b.output, 120),
3023
+ attachments: (_d = (_c = sent.attachments) == null ? void 0 : _c.length) != null ? _d : 0,
3024
+ attachmentKinds: (_f = (_e = sent.attachments) == null ? void 0 : _e.map((a) => ({
2794
3025
  type: a.type,
2795
3026
  role: a.role,
2796
3027
  name: a.name,
2797
3028
  valuePreview: preview(a.value, 60)
2798
- }))) != null ? _p : [],
3029
+ }))) != null ? _f : [],
2799
3030
  endpoint: url
2800
3031
  });
2801
3032
  }
2802
3033
  const mirror = this.localDebuggerUrl ? mirrorPartialEventToLocalDebugger(payload, {
2803
3034
  baseUrl: this.localDebuggerUrl,
3035
+ followRedirects: this.localDebuggerFollowRedirects,
2804
3036
  writeKey: this.writeKey,
2805
3037
  debug: this.debug,
2806
3038
  sdkName: this.sdkName
@@ -2819,7 +3051,7 @@ var EventShipper = class {
2819
3051
  }
2820
3052
  const sending = sendJson(url, payload, this.requestHeaders(), opts);
2821
3053
  const combined = Promise.all([mirror, sending.then(() => void 0)]).then(() => void 0);
2822
- this.inFlight.add(combined);
3054
+ if (track) this.inFlight.add(combined);
2823
3055
  let outcome;
2824
3056
  try {
2825
3057
  outcome = await sending;
@@ -3015,6 +3247,211 @@ var DEFAULT_REDACT_ATTRIBUTE_KEYS = [
3015
3247
  "ai.response.providerMetadata"
3016
3248
  ];
3017
3249
  var REDACT_JSON_ATTRIBUTE_KEYS = new Set(DEFAULT_REDACT_ATTRIBUTE_KEYS);
3250
+ var CONTENT_KEY_SUFFIX = /(^|\.)(input|output|inputs|outputs|args|arguments|result|results|content|text|messages|prompt|completion|instructions|system_instructions|reasoning|reasoningText|thinking|toolCalls|tool_calls|object|value|values|intent|query|tool_input)$/;
3251
+ var CONTENT_KEYS = /* @__PURE__ */ new Set([
3252
+ "ai.prompt.system",
3253
+ "ai.subagent.result",
3254
+ "agent.session.title",
3255
+ // Failed tool calls carry the tool's output in their error text.
3256
+ "error.message",
3257
+ "exception.message",
3258
+ "exception.stacktrace"
3259
+ ]);
3260
+ var NON_CONTENT_PREFIXES = [
3261
+ "traceloop.association.properties.",
3262
+ "ai.telemetry.metadata.",
3263
+ "ai.settings.context.",
3264
+ "raindrop.app."
3265
+ ];
3266
+ var JSON_SIMPLE_ESCAPES = {
3267
+ '"': '"',
3268
+ "\\": "\\",
3269
+ "/": "/",
3270
+ b: "\b",
3271
+ f: "\f",
3272
+ n: "\n",
3273
+ r: "\r",
3274
+ t: " "
3275
+ };
3276
+ function decodeJsonEscapes(text) {
3277
+ if (!text.includes("\\")) return text;
3278
+ let out = "";
3279
+ for (let i = 0; i < text.length; i++) {
3280
+ const ch = text[i];
3281
+ if (ch !== "\\" || i + 1 >= text.length) {
3282
+ out += ch;
3283
+ continue;
3284
+ }
3285
+ const next = text[i + 1];
3286
+ const simple = JSON_SIMPLE_ESCAPES[next];
3287
+ if (simple !== void 0) {
3288
+ out += simple;
3289
+ i += 1;
3290
+ } else if (next === "u" && /^[0-9a-fA-F]{4}$/.test(text.slice(i + 2, i + 6))) {
3291
+ out += String.fromCharCode(Number.parseInt(text.slice(i + 2, i + 6), 16));
3292
+ i += 5;
3293
+ } else {
3294
+ out += ch;
3295
+ }
3296
+ }
3297
+ return out;
3298
+ }
3299
+ function jsonStringBody(value) {
3300
+ return JSON.stringify(value).slice(1, -1);
3301
+ }
3302
+ function redactStringToken(token) {
3303
+ const decoded = decodeJsonEscapes(token.slice(1, -1));
3304
+ const redacted = redactPiiText(decoded);
3305
+ return redacted === decoded ? token : `"${jsonStringBody(redacted)}"`;
3306
+ }
3307
+ function redactLooseJsonText(text) {
3308
+ if (text.startsWith('"')) {
3309
+ const decoded2 = decodeJsonEscapes(text.slice(1));
3310
+ const redacted2 = redactPiiText(decoded2);
3311
+ return redacted2 === decoded2 ? text : `"${jsonStringBody(redacted2)}`;
3312
+ }
3313
+ const decoded = decodeJsonEscapes(text);
3314
+ const redacted = redactPiiText(decoded);
3315
+ return redacted === decoded ? text : redacted;
3316
+ }
3317
+ function stringTokenEnd(text, start) {
3318
+ for (let i = start + 1; i < text.length; i++) {
3319
+ const ch = text[i];
3320
+ if (ch === "\\") i += 1;
3321
+ else if (ch === '"') return i + 1;
3322
+ }
3323
+ return -1;
3324
+ }
3325
+ function redactJsonLike(text, complete) {
3326
+ let out = "";
3327
+ let looseStart = 0;
3328
+ const flushLoose = (end) => {
3329
+ if (end > looseStart) {
3330
+ const loose = text.slice(looseStart, end);
3331
+ out += complete ? loose : redactLooseJsonText(loose);
3332
+ }
3333
+ };
3334
+ let i = text.indexOf('"');
3335
+ while (i !== -1) {
3336
+ const end = stringTokenEnd(text, i);
3337
+ if (end === -1) break;
3338
+ flushLoose(i);
3339
+ let after = end;
3340
+ while (after < text.length && /\s/.test(text[after])) after += 1;
3341
+ const token = text.slice(i, end);
3342
+ out += complete && text[after] === ":" ? token : redactStringToken(token);
3343
+ looseStart = end;
3344
+ i = text.indexOf('"', end);
3345
+ }
3346
+ if (i === -1) {
3347
+ flushLoose(text.length);
3348
+ } else {
3349
+ flushLoose(i);
3350
+ looseStart = i;
3351
+ flushLoose(text.length);
3352
+ }
3353
+ return out;
3354
+ }
3355
+ function redactSpanContent(text) {
3356
+ const head = text.trimStart()[0];
3357
+ if (head !== "{" && head !== "[" && head !== '"') return redactPiiText(text);
3358
+ let complete = true;
3359
+ try {
3360
+ JSON.parse(text);
3361
+ } catch (e) {
3362
+ complete = false;
3363
+ }
3364
+ return redactJsonLike(text, complete);
3365
+ }
3366
+ var NO_SPAN_PII_FIELDS = { exact: /* @__PURE__ */ new Set(), prefixes: [] };
3367
+ function compileSpanPiiFields(names, logPrefix = "[raindrop-ai/core]") {
3368
+ if (!Array.isArray(names) || names.length === 0) return NO_SPAN_PII_FIELDS;
3369
+ const exact = /* @__PURE__ */ new Set();
3370
+ const prefixes = [];
3371
+ for (const name of names) {
3372
+ const valid = typeof name === "string" && !/\s/.test(name) && /^[^*]+\*?$/.test(name);
3373
+ if (!valid) {
3374
+ rateLimitedLog(
3375
+ `${logPrefix}.pii_span_field_invalid`,
3376
+ () => console.warn(
3377
+ `${logPrefix} redactPiiFields: ignoring invalid span attribute ${JSON.stringify(name)}`
3378
+ )
3379
+ );
3380
+ continue;
3381
+ }
3382
+ if (name.endsWith("*")) prefixes.push(name.slice(0, -1));
3383
+ else exact.add(name);
3384
+ }
3385
+ return { exact, prefixes };
3386
+ }
3387
+ function isCallerSelected(key, fields) {
3388
+ return fields.exact.has(key) || fields.prefixes.some((prefix) => key.startsWith(prefix));
3389
+ }
3390
+ function isSpanContentAttributeKey(key, fields = NO_SPAN_PII_FIELDS) {
3391
+ if (isCallerSelected(key, fields)) return true;
3392
+ if (NON_CONTENT_PREFIXES.some((prefix) => key.startsWith(prefix))) return false;
3393
+ return CONTENT_KEYS.has(key) || CONTENT_KEY_SUFFIX.test(key);
3394
+ }
3395
+ function redactOtlpValue(value) {
3396
+ var _a;
3397
+ if (typeof value.stringValue === "string") {
3398
+ const redacted = redactSpanContent(value.stringValue);
3399
+ return redacted === value.stringValue ? value : { ...value, stringValue: redacted };
3400
+ }
3401
+ const values = (_a = value.arrayValue) == null ? void 0 : _a.values;
3402
+ if (!values) return value;
3403
+ let changed = false;
3404
+ const next = values.map((item) => {
3405
+ const redacted = redactOtlpValue(item);
3406
+ if (redacted !== item) changed = true;
3407
+ return redacted;
3408
+ });
3409
+ return changed ? { ...value, arrayValue: { values: next } } : value;
3410
+ }
3411
+ function redactPiiInOtlpAttributes(attributes, fields = NO_SPAN_PII_FIELDS) {
3412
+ let next;
3413
+ for (let i = 0; i < attributes.length; i++) {
3414
+ const attr = attributes[i];
3415
+ if (!attr.value || !isSpanContentAttributeKey(attr.key, fields)) continue;
3416
+ const value = redactOtlpValue(attr.value);
3417
+ if (value === attr.value) continue;
3418
+ next != null ? next : next = attributes.slice();
3419
+ next[i] = { ...attr, value };
3420
+ }
3421
+ return next != null ? next : attributes;
3422
+ }
3423
+ function redactPiiInOtlpSpan(span, fields = NO_SPAN_PII_FIELDS) {
3424
+ var _a;
3425
+ const attributes = span.attributes && redactPiiInOtlpAttributes(span.attributes, fields);
3426
+ const message = (_a = span.status) == null ? void 0 : _a.message;
3427
+ const redactedMessage = message === void 0 ? void 0 : redactSpanContent(message);
3428
+ if (attributes === span.attributes && redactedMessage === message) return span;
3429
+ const status = span.status && redactedMessage !== message ? { ...span.status, message: redactedMessage } : span.status;
3430
+ return { ...span, attributes, status };
3431
+ }
3432
+ function redactPiiInAttributeMap(attributes, fields = NO_SPAN_PII_FIELDS) {
3433
+ let next;
3434
+ for (const [key, value] of Object.entries(attributes)) {
3435
+ if (!isSpanContentAttributeKey(key, fields)) continue;
3436
+ let redacted = value;
3437
+ if (typeof value === "string") {
3438
+ redacted = redactSpanContent(value);
3439
+ } else if (Array.isArray(value)) {
3440
+ let changed = false;
3441
+ const items = value.map((item) => {
3442
+ if (typeof item !== "string") return item;
3443
+ const out = redactSpanContent(item);
3444
+ if (out !== item) changed = true;
3445
+ return out;
3446
+ });
3447
+ if (changed) redacted = items;
3448
+ }
3449
+ if (redacted === value) continue;
3450
+ next != null ? next : next = { ...attributes };
3451
+ next[key] = redacted;
3452
+ }
3453
+ return next;
3454
+ }
3018
3455
  var UNDELIVERED = Object.freeze({
3019
3456
  delivered: false,
3020
3457
  timedOut: false,
@@ -3023,7 +3460,7 @@ var UNDELIVERED = Object.freeze({
3023
3460
  inFlight: 0
3024
3461
  });
3025
3462
  var PROMPT_TOOLS_ATTRIBUTE = "ai.prompt.tools";
3026
- function isRecord3(value) {
3463
+ function isRecord4(value) {
3027
3464
  return typeof value === "object" && value !== null && !Array.isArray(value);
3028
3465
  }
3029
3466
  var JSON_SCHEMA_KEYS = [
@@ -3041,17 +3478,17 @@ var JSON_SCHEMA_KEYS = [
3041
3478
  "required"
3042
3479
  ];
3043
3480
  function isJsonSchema(value) {
3044
- if (!isRecord3(value)) return false;
3481
+ if (!isRecord4(value)) return false;
3045
3482
  if (typeof value["~standard"] === "object") return false;
3046
- if (isRecord3(value._def) || isRecord3(value._zod)) return false;
3483
+ if (isRecord4(value._def) || isRecord4(value._zod)) return false;
3047
3484
  if (Object.keys(value).length === 0) return true;
3048
3485
  return JSON_SCHEMA_KEYS.some((key) => key in value);
3049
3486
  }
3050
3487
  function toJsonSchema(value, options) {
3051
3488
  if (value === void 0 || value === null) return void 0;
3052
3489
  if (isJsonSchema(value)) return value;
3053
- if (isRecord3(value) && isJsonSchema(value.jsonSchema)) return value.jsonSchema;
3054
- if (isRecord3(value) && isJsonSchema(value.json)) return value.json;
3490
+ if (isRecord4(value) && isJsonSchema(value.jsonSchema)) return value.jsonSchema;
3491
+ if (isRecord4(value) && isJsonSchema(value.json)) return value.json;
3055
3492
  if (options == null ? void 0 : options.schema) {
3056
3493
  try {
3057
3494
  return options.schema(value);
@@ -3074,23 +3511,23 @@ function functionTool(name, description, schema, options) {
3074
3511
  }
3075
3512
  function normalizeToolDeclaration(tool, options, fallbackName) {
3076
3513
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
3077
- if (!isRecord3(tool)) return void 0;
3514
+ if (!isRecord4(tool)) return void 0;
3078
3515
  if (tool.type === "provider-defined" || tool.type === "provider") {
3079
3516
  const name2 = (_b = (_a = pickString(tool.name)) != null ? _a : pickString(tool.id)) != null ? _b : fallbackName;
3080
3517
  if (name2 === void 0) return void 0;
3081
3518
  const declaration = { type: "provider-defined", name: name2 };
3082
3519
  const id = pickString(tool.id);
3083
3520
  if (id !== void 0) declaration.id = id;
3084
- if (isRecord3(tool.args)) declaration.args = tool.args;
3521
+ if (isRecord4(tool.args)) declaration.args = tool.args;
3085
3522
  return declaration;
3086
3523
  }
3087
- if (isRecord3(tool.toolSpec)) {
3524
+ if (isRecord4(tool.toolSpec)) {
3088
3525
  const spec = tool.toolSpec;
3089
3526
  const name2 = (_c = pickString(spec.name)) != null ? _c : fallbackName;
3090
3527
  if (name2 === void 0) return void 0;
3091
3528
  return functionTool(name2, spec.description, spec.inputSchema, options);
3092
3529
  }
3093
- if (isRecord3(tool.function)) {
3530
+ if (isRecord4(tool.function)) {
3094
3531
  const fn = tool.function;
3095
3532
  const name2 = (_d = pickString(fn.name)) != null ? _d : fallbackName;
3096
3533
  if (name2 === void 0) return void 0;
@@ -3116,7 +3553,7 @@ function isGeminiToolGroup(tool) {
3116
3553
  if (Array.isArray(tool.functionDeclarations)) return true;
3117
3554
  const keys = Object.keys(tool);
3118
3555
  if (keys.length === 0 || NOT_A_GEMINI_GROUP_KEYS.some((key) => key in tool)) return false;
3119
- return keys.every((key) => isRecord3(tool[key]));
3556
+ return keys.every((key) => isRecord4(tool[key]));
3120
3557
  }
3121
3558
  function expandGeminiTool(tool, options) {
3122
3559
  const declarations = [];
@@ -3126,7 +3563,7 @@ function expandGeminiTool(tool, options) {
3126
3563
  const normalized = normalizeToolDeclaration(declaration, options);
3127
3564
  if (normalized) declarations.push(normalized);
3128
3565
  }
3129
- } else if (isRecord3(value)) {
3566
+ } else if (isRecord4(value)) {
3130
3567
  declarations.push({ type: "provider-defined", id: key, name: key, args: value });
3131
3568
  }
3132
3569
  }
@@ -3136,14 +3573,14 @@ function normalizeToolDeclarations(tools, options) {
3136
3573
  if (tools === void 0 || tools === null) return void 0;
3137
3574
  if (Array.isArray(tools)) {
3138
3575
  return tools.flatMap((tool) => {
3139
- if (isRecord3(tool) && isGeminiToolGroup(tool)) {
3576
+ if (isRecord4(tool) && isGeminiToolGroup(tool)) {
3140
3577
  return expandGeminiTool(tool, options);
3141
3578
  }
3142
3579
  const declaration = normalizeToolDeclaration(tool, options);
3143
3580
  return declaration ? [declaration] : [];
3144
3581
  });
3145
3582
  }
3146
- if (!isRecord3(tools)) return void 0;
3583
+ if (!isRecord4(tools)) return void 0;
3147
3584
  return Object.entries(tools).flatMap(([key, tool]) => {
3148
3585
  const declaration = normalizeToolDeclaration(tool, options, key);
3149
3586
  return declaration ? [declaration] : [];
@@ -3358,7 +3795,7 @@ installTracingSuppressionHook();
3358
3795
  // package.json
3359
3796
  var package_default = {
3360
3797
  name: "raindrop-ai",
3361
- version: "1.0.7",
3798
+ version: "1.0.8",
3362
3799
  main: "dist/index.js",
3363
3800
  module: "dist/index.mjs",
3364
3801
  types: "dist/index.d.ts",
@@ -3629,10 +4066,10 @@ function authHintForKey(writeKey) {
3629
4066
  if (!writeKey) return void 0;
3630
4067
  return createHash("sha256").update(writeKey, "utf8").digest("hex").slice(0, 8);
3631
4068
  }
3632
- var STATE_KEY2 = /* @__PURE__ */ Symbol.for("raindrop.tracing.multiProjectState");
4069
+ var STATE_KEY3 = /* @__PURE__ */ Symbol.for("raindrop.tracing.multiProjectState");
3633
4070
  function getState() {
3634
4071
  const holder = globalThis;
3635
- let state2 = holder[STATE_KEY2];
4072
+ let state2 = holder[STATE_KEY3];
3636
4073
  if (!state2) {
3637
4074
  state2 = {
3638
4075
  foreignClientSeen: false,
@@ -3644,7 +4081,7 @@ function getState() {
3644
4081
  multiKeyWarned: false,
3645
4082
  pendingMultiKeyWarning: false
3646
4083
  };
3647
- holder[STATE_KEY2] = state2;
4084
+ holder[STATE_KEY3] = state2;
3648
4085
  }
3649
4086
  return state2;
3650
4087
  }
@@ -3875,11 +4312,8 @@ import {
3875
4312
  } from "@traceloop/instrumentation-vertexai";
3876
4313
  import { WeakValueMap } from "weakref";
3877
4314
 
3878
- // src/tracing/direct/http.ts
3879
- function formatEndpoint2(endpoint) {
3880
- if (!endpoint) return void 0;
3881
- return endpoint.endsWith("/") ? endpoint : `${endpoint}/`;
3882
- }
4315
+ // src/tracing/direct/context.ts
4316
+ import { TraceFlags, context, isValidSpanId, isValidTraceId, trace } from "@opentelemetry/api";
3883
4317
 
3884
4318
  // src/tracing/direct/ids.ts
3885
4319
  function getCrypto2() {
@@ -3942,6 +4376,55 @@ function base64ToHex2(base64) {
3942
4376
  throw new Error("No base64 decoder available in this runtime");
3943
4377
  }
3944
4378
 
4379
+ // src/tracing/direct/context.ts
4380
+ var INVALID_TRACE_ID = "00000000000000000000000000000000";
4381
+ var INVALID_SPAN_ID = "0000000000000000";
4382
+ function hexToBase64(hex) {
4383
+ const bytes = new Uint8Array(hex.length / 2);
4384
+ for (let i = 0; i < hex.length; i += 2) {
4385
+ bytes[i / 2] = parseInt(hex.substring(i, i + 2), 16);
4386
+ }
4387
+ return base64Encode2(bytes);
4388
+ }
4389
+ function getExplicitTraceContext(traceId, parentSpanId) {
4390
+ if (!traceId || !parentSpanId || !isValidTraceId(traceId) || !isValidSpanId(parentSpanId)) {
4391
+ return void 0;
4392
+ }
4393
+ return {
4394
+ traceIdB64: hexToBase64(traceId),
4395
+ parentSpanIdB64: hexToBase64(parentSpanId)
4396
+ };
4397
+ }
4398
+ function getActiveTraceContext() {
4399
+ const activeSpan = trace.getSpan(context.active());
4400
+ if (!activeSpan) return {};
4401
+ const spanContext = activeSpan.spanContext();
4402
+ const traceIdHex = spanContext.traceId;
4403
+ const spanIdHex = spanContext.spanId;
4404
+ if (traceIdHex === INVALID_TRACE_ID) return {};
4405
+ return {
4406
+ traceIdB64: hexToBase64(traceIdHex),
4407
+ parentSpanIdB64: spanIdHex !== INVALID_SPAN_ID ? hexToBase64(spanIdHex) : void 0
4408
+ };
4409
+ }
4410
+ function savedParentContext(traceId, parentSpanId) {
4411
+ if (!traceId || !parentSpanId || !isValidTraceId(traceId) || !isValidSpanId(parentSpanId)) {
4412
+ return void 0;
4413
+ }
4414
+ return trace.setSpanContext(context.active(), {
4415
+ traceId,
4416
+ spanId: parentSpanId,
4417
+ traceFlags: TraceFlags.SAMPLED,
4418
+ isRemote: true
4419
+ });
4420
+ }
4421
+
4422
+ // src/tracing/direct/http.ts
4423
+ function formatEndpoint2(endpoint) {
4424
+ if (!endpoint) return void 0;
4425
+ return endpoint.endsWith("/") ? endpoint : `${endpoint}/`;
4426
+ }
4427
+
3945
4428
  // src/tracing/direct/otlp.ts
3946
4429
  var libraryVersion = package_default.version;
3947
4430
  var SERVICE_NAME = "raindrop-ai";
@@ -3986,50 +4469,6 @@ function buildExportTraceServiceRequest2(spans) {
3986
4469
  };
3987
4470
  }
3988
4471
 
3989
- // src/tracing/direct/context.ts
3990
- import { TraceFlags, context, isValidSpanId, isValidTraceId, trace } from "@opentelemetry/api";
3991
- var INVALID_TRACE_ID = "00000000000000000000000000000000";
3992
- var INVALID_SPAN_ID = "0000000000000000";
3993
- function hexToBase64(hex) {
3994
- const bytes = new Uint8Array(hex.length / 2);
3995
- for (let i = 0; i < hex.length; i += 2) {
3996
- bytes[i / 2] = parseInt(hex.substring(i, i + 2), 16);
3997
- }
3998
- return base64Encode2(bytes);
3999
- }
4000
- function getExplicitTraceContext(traceId, parentSpanId) {
4001
- if (!traceId || !parentSpanId || !isValidTraceId(traceId) || !isValidSpanId(parentSpanId)) {
4002
- return void 0;
4003
- }
4004
- return {
4005
- traceIdB64: hexToBase64(traceId),
4006
- parentSpanIdB64: hexToBase64(parentSpanId)
4007
- };
4008
- }
4009
- function getActiveTraceContext() {
4010
- const activeSpan = trace.getSpan(context.active());
4011
- if (!activeSpan) return {};
4012
- const spanContext = activeSpan.spanContext();
4013
- const traceIdHex = spanContext.traceId;
4014
- const spanIdHex = spanContext.spanId;
4015
- if (traceIdHex === INVALID_TRACE_ID) return {};
4016
- return {
4017
- traceIdB64: hexToBase64(traceIdHex),
4018
- parentSpanIdB64: spanIdHex !== INVALID_SPAN_ID ? hexToBase64(spanIdHex) : void 0
4019
- };
4020
- }
4021
- function savedParentContext(traceId, parentSpanId) {
4022
- if (!traceId || !parentSpanId || !isValidTraceId(traceId) || !isValidSpanId(parentSpanId)) {
4023
- return void 0;
4024
- }
4025
- return trace.setSpanContext(context.active(), {
4026
- traceId,
4027
- spanId: parentSpanId,
4028
- traceFlags: TraceFlags.SAMPLED,
4029
- isRemote: true
4030
- });
4031
- }
4032
-
4033
4472
  // src/tracing/direct/shipper.ts
4034
4473
  function serializeAssociationValue(value) {
4035
4474
  return stringifyBounded(value);
@@ -4055,6 +4494,9 @@ var DirectTraceShipper = class {
4055
4494
  this.cloudEnabled = (_c = opts.cloudEnabled) != null ? _c : true;
4056
4495
  this.debug = opts.debug;
4057
4496
  this.projectId = opts.projectId;
4497
+ this.redactTracePii = opts.redactTracePii;
4498
+ this.remotePiiConfig = opts.remotePiiConfig;
4499
+ this.spanPiiFields = opts.spanPiiFields;
4058
4500
  this.flushIntervalMs = (_d = opts.flushIntervalMs) != null ? _d : 1e3;
4059
4501
  this.maxBatchSize = (_e = opts.maxBatchSize) != null ? _e : 50;
4060
4502
  this.maxQueueSize = (_f = opts.maxQueueSize) != null ? _f : 5e3;
@@ -4159,8 +4601,9 @@ var DirectTraceShipper = class {
4159
4601
  base64ToHex2(span.traceId)
4160
4602
  );
4161
4603
  const mirrorUrl = (replayDestination == null ? void 0 : replayDestination.kind) === "workshop" ? replayDestination.url : replayDestination ? void 0 : this.localDebuggerUrl;
4162
- if (mirrorUrl) {
4163
- const body = buildExportTraceServiceRequest2([span]);
4604
+ const mirrored = mirrorUrl && this.redactsNow() ? this.redactSpanPii(span) : span;
4605
+ if (mirrorUrl && mirrored) {
4606
+ const body = buildExportTraceServiceRequest2([mirrored]);
4164
4607
  const mirror = mirrorTraceExportToLocalDebugger(body, {
4165
4608
  baseUrl: mirrorUrl,
4166
4609
  debug: false,
@@ -4174,6 +4617,23 @@ var DirectTraceShipper = class {
4174
4617
  console.log(`[raindrop] direct shipper: enqueued span "${params.name}"`);
4175
4618
  }
4176
4619
  }
4620
+ /**
4621
+ * Whether to redact, never waiting: a local mirror uses what is known now,
4622
+ * and a remote setting still being looked up counts as unknown.
4623
+ */
4624
+ redactsNow() {
4625
+ var _a;
4626
+ const writeKey = this.cloudEnabled ? this.writeKey : void 0;
4627
+ return (_a = piiRedactionNow(this.redactTracePii, this.remotePiiConfig, this.baseUrl, writeKey)) != null ? _a : resolvePiiRedaction(this.redactTracePii, this.remotePiiConfig, "unknown");
4628
+ }
4629
+ /** The span with PII redacted from its input and output; undefined if redaction failed. */
4630
+ redactSpanPii(span) {
4631
+ try {
4632
+ return redactPiiInOtlpSpan(span, this.spanPiiFields);
4633
+ } catch (e) {
4634
+ return void 0;
4635
+ }
4636
+ }
4177
4637
  sendToolSpan(params) {
4178
4638
  this.sendSpan({
4179
4639
  ...params,
@@ -4227,13 +4687,22 @@ var DirectTraceShipper = class {
4227
4687
  return summarize2(fates, stillRunning, !settled);
4228
4688
  }
4229
4689
  async drain(deadlineAt) {
4230
- var _a;
4690
+ var _a, _b;
4231
4691
  const fates = [];
4232
4692
  if (!this.enabled) return fates;
4233
4693
  if (this.timer) {
4234
4694
  clearTimeout(this.timer);
4235
4695
  this.timer = void 0;
4236
4696
  }
4697
+ if (this.queue.length === 0) return fates;
4698
+ const writeKey = this.cloudEnabled ? this.writeKey : void 0;
4699
+ const redactPii = (_a = piiRedactionNow(this.redactTracePii, this.remotePiiConfig, this.baseUrl, writeKey)) != null ? _a : await piiRedaction(
4700
+ this.redactTracePii,
4701
+ this.remotePiiConfig,
4702
+ this.baseUrl,
4703
+ writeKey,
4704
+ deadlineAt
4705
+ );
4237
4706
  while (this.queue.length > 0) {
4238
4707
  const batch = this.queue.splice(0, this.maxBatchSize);
4239
4708
  const opts = this.requestOpts(deadlineAt);
@@ -4258,12 +4727,18 @@ var DirectTraceShipper = class {
4258
4727
  for (const [replayDestination, queuedSpans] of groups) {
4259
4728
  if (!replayDestination && !this.cloudEnabled) continue;
4260
4729
  if ((replayDestination == null ? void 0 : replayDestination.kind) === "workshop") continue;
4261
- const body = buildExportTraceServiceRequest2(queuedSpans.map((q) => q.span));
4730
+ const spans = queuedSpans.map((q) => q.span);
4731
+ const outgoing = redactPii ? spans.flatMap((span) => {
4732
+ var _a2;
4733
+ return (_a2 = this.redactSpanPii(span)) != null ? _a2 : [];
4734
+ }) : spans;
4735
+ if (outgoing.length === 0) continue;
4736
+ const body = buildExportTraceServiceRequest2(outgoing);
4262
4737
  const url = replayDestination ? replayTraceUrl(replayDestination.url) : `${this.baseUrl}traces`;
4263
4738
  const headers = replayDestination ? {
4264
4739
  Authorization: `Bearer ${replayDestination.apiKey}`,
4265
4740
  "X-Raindrop-Replay-Id": replayDestination.replayId,
4266
- "X-Raindrop-Project-Id": (_a = replayDestination.projectId) != null ? _a : "default"
4741
+ "X-Raindrop-Project-Id": (_b = replayDestination.projectId) != null ? _b : "default"
4267
4742
  } : { Authorization: `Bearer ${this.writeKey}`, ...projectIdHeaders(this.projectId) };
4268
4743
  const sending = sendJson(url, body, headers, opts);
4269
4744
  const tracked = sending.then(() => void 0);
@@ -4285,7 +4760,9 @@ var DirectTraceShipper = class {
4285
4760
  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;
4286
4761
  rateLimitedLog(
4287
4762
  "js-sdk.direct.send_failed",
4288
- () => console.warn(`[raindrop] direct: failed to send ${queuedSpans.length} spans (dropping): ${reason}`)
4763
+ () => console.warn(
4764
+ `[raindrop] direct: failed to send ${queuedSpans.length} spans (dropping): ${reason}`
4765
+ )
4289
4766
  );
4290
4767
  } else if (this.debug) {
4291
4768
  console.log(`[raindrop] direct: sent ${queuedSpans.length} spans`);
@@ -4372,6 +4849,93 @@ import {
4372
4849
  TraceloopSpanKindValues
4373
4850
  } from "@traceloop/ai-semantic-conventions";
4374
4851
  var ALL_INSTRUMENTATION_LIBRARIES = "all";
4852
+ function redactSpanPii(span, fields) {
4853
+ const attributes = redactPiiInAttributeMap(span.attributes, fields);
4854
+ const message = span.status.message;
4855
+ const redactedMessage = message === void 0 ? void 0 : redactSpanContent(message);
4856
+ let eventsChanged = false;
4857
+ const events = span.events.map((event) => {
4858
+ const eventAttributes = event.attributes && redactPiiInAttributeMap(event.attributes, fields);
4859
+ if (!eventAttributes) return event;
4860
+ eventsChanged = true;
4861
+ return { ...event, attributes: eventAttributes };
4862
+ });
4863
+ if (!attributes && redactedMessage === message && !eventsChanged) return span;
4864
+ const view = Object.create(span);
4865
+ if (attributes) {
4866
+ Object.defineProperty(view, "attributes", { value: attributes, enumerable: true });
4867
+ }
4868
+ if (redactedMessage !== message) {
4869
+ Object.defineProperty(view, "status", {
4870
+ value: { ...span.status, message: redactedMessage },
4871
+ enumerable: true
4872
+ });
4873
+ }
4874
+ if (eventsChanged) {
4875
+ Object.defineProperty(view, "events", { value: events, enumerable: true });
4876
+ }
4877
+ copyReplayTraceDestination(span, view);
4878
+ return view;
4879
+ }
4880
+ var PiiRedactingSpanExporter = class {
4881
+ constructor(inner, options) {
4882
+ this.inner = inner;
4883
+ this.options = options;
4884
+ /** Exports waiting for the org lookup; flush and shutdown wait for them. */
4885
+ this.pending = /* @__PURE__ */ new Set();
4886
+ }
4887
+ export(spans, resultCallback) {
4888
+ const { local, remote, apiUrl, writeKey, spanFields } = this.options;
4889
+ const exportContext = context2.active();
4890
+ const run = (redact) => {
4891
+ let outgoing = spans;
4892
+ if (redact) {
4893
+ outgoing = [];
4894
+ for (const span of spans) {
4895
+ try {
4896
+ outgoing.push(redactSpanPii(span, spanFields));
4897
+ } catch (e) {
4898
+ }
4899
+ }
4900
+ }
4901
+ try {
4902
+ context2.with(exportContext, () => this.inner.export(outgoing, resultCallback));
4903
+ } catch (e) {
4904
+ resultCallback({ code: 1 });
4905
+ }
4906
+ };
4907
+ const sharedRequest = localTracePiiRedactionRequested(apiUrl, writeKey);
4908
+ const known = sharedRequest || piiRedactionNow(local, remote, apiUrl, writeKey);
4909
+ if (known !== void 0) {
4910
+ run(known);
4911
+ return;
4912
+ }
4913
+ const handedOff = piiRedaction(local, remote, apiUrl, writeKey).then(
4914
+ (redact) => new Promise((resolve2) => {
4915
+ const callback = resultCallback;
4916
+ resultCallback = (result) => {
4917
+ resolve2();
4918
+ callback(result);
4919
+ };
4920
+ run(redact || localTracePiiRedactionRequested(apiUrl, writeKey));
4921
+ })
4922
+ );
4923
+ this.pending.add(handedOff);
4924
+ void handedOff.finally(() => this.pending.delete(handedOff));
4925
+ }
4926
+ async drainPending() {
4927
+ if (this.pending.size > 0) await Promise.allSettled([...this.pending]);
4928
+ }
4929
+ async shutdown() {
4930
+ await this.drainPending();
4931
+ return this.inner.shutdown();
4932
+ }
4933
+ async forceFlush() {
4934
+ var _a, _b, _c;
4935
+ await this.drainPending();
4936
+ return (_c = (_b = (_a = this.inner).forceFlush) == null ? void 0 : _b.call(_a)) != null ? _c : Promise.resolve();
4937
+ }
4938
+ };
4375
4939
  var TRACER_NAME = "@traceloop/node-server-sdk";
4376
4940
  var WORKFLOW_NAME_KEY = /* @__PURE__ */ Symbol.for("raindrop.otelCore.workflowName");
4377
4941
  var ENTITY_NAME_KEY = /* @__PURE__ */ Symbol.for("raindrop.otelCore.entityName");
@@ -4401,12 +4965,12 @@ var AI_PROMPT_MESSAGES = "ai.prompt.messages";
4401
4965
  var AI_PROMPT_TOKENS = "ai.usage.promptTokens";
4402
4966
  var AI_COMPLETION_TOKENS = "ai.usage.completionTokens";
4403
4967
  var AI_MODEL_PROVIDER = "ai.model.provider";
4404
- var STATE_KEY3 = /* @__PURE__ */ Symbol.for("raindrop.otelCore.state");
4968
+ var STATE_KEY4 = /* @__PURE__ */ Symbol.for("raindrop.otelCore.state");
4405
4969
  function getState2() {
4406
4970
  var _a;
4407
4971
  const holder = globalThis;
4408
- (_a = holder[STATE_KEY3]) != null ? _a : holder[STATE_KEY3] = {};
4409
- return holder[STATE_KEY3];
4972
+ (_a = holder[STATE_KEY4]) != null ? _a : holder[STATE_KEY4] = {};
4973
+ return holder[STATE_KEY4];
4410
4974
  }
4411
4975
  function parseHeaders(value) {
4412
4976
  const headers = {};
@@ -4607,7 +5171,8 @@ function createSpanProcessor(options) {
4607
5171
  const apiKey = options.apiKey || process.env.TRACELOOP_API_KEY;
4608
5172
  const resolvedHeaders = (_a = options.headers) != null ? _a : process.env.TRACELOOP_HEADERS ? parseHeaders(process.env.TRACELOOP_HEADERS) : { Authorization: `Bearer ${apiKey}` };
4609
5173
  const baseExporter = (_b = options.exporter) != null ? _b : new OTLPTraceExporter({ url: `${baseUrl}/v1/traces`, headers: resolvedHeaders });
4610
- const exporter = options.routeReplayTraces ? new ReplayRoutingSpanExporter(baseExporter) : baseExporter;
5174
+ const routed = options.routeReplayTraces ? new ReplayRoutingSpanExporter(baseExporter) : baseExporter;
5175
+ const exporter = options.piiRedaction ? new PiiRedactingSpanExporter(routed, options.piiRedaction) : routed;
4611
5176
  const processor = options.disableBatch ? new SimpleSpanProcessor(exporter) : new BatchSpanProcessor(exporter);
4612
5177
  const originalOnStart = processor.onStart.bind(processor);
4613
5178
  const originalOnEnd = processor.onEnd.bind(processor);
@@ -4798,17 +5363,17 @@ function withTool(config, fn, ...args) {
4798
5363
  }
4799
5364
 
4800
5365
  // src/tracing/exit-flush.ts
4801
- var STATE_KEY4 = /* @__PURE__ */ Symbol.for("raindrop.tracing.exitFlushState");
5366
+ var STATE_KEY5 = /* @__PURE__ */ Symbol.for("raindrop.tracing.exitFlushState");
4802
5367
  function getState3() {
4803
5368
  const holder = globalThis;
4804
- let state2 = holder[STATE_KEY4];
5369
+ let state2 = holder[STATE_KEY5];
4805
5370
  if (!state2) {
4806
5371
  state2 = {
4807
5372
  clientFlushers: /* @__PURE__ */ new Set(),
4808
5373
  pipelineFlushNeeded: false,
4809
5374
  handlerRegistered: false
4810
5375
  };
4811
- holder[STATE_KEY4] = state2;
5376
+ holder[STATE_KEY5] = state2;
4812
5377
  }
4813
5378
  return state2;
4814
5379
  }
@@ -6394,6 +6959,7 @@ function createLocalDebuggerSpanProcessor(options) {
6394
6959
  disableBatch: options.disableBatching,
6395
6960
  exporter: localExporter,
6396
6961
  headers: {},
6962
+ piiRedaction: options.piiRedaction,
6397
6963
  allowedInstrumentationLibraries: options.allowedInstrumentationLibraries
6398
6964
  });
6399
6965
  } catch (error) {
@@ -6737,9 +7303,32 @@ var tracing = (analytics, apiUrl, writeKey, options, isDebug = false) => {
6737
7303
  cloudEnabled,
6738
7304
  projectId,
6739
7305
  flushTimeoutMs,
7306
+ redactTracePii,
7307
+ redactPiiFields,
7308
+ remotePiiConfig,
6740
7309
  ...otherOptions
6741
7310
  } = options;
6742
7311
  const cloudEnabledResolved = cloudEnabled != null ? cloudEnabled : true;
7312
+ const localTracePii = typeof redactTracePii === "boolean" ? redactTracePii : void 0;
7313
+ const spanPiiFields = compileSpanPiiFields(redactPiiFields == null ? void 0 : redactPiiFields.span, "[raindrop]");
7314
+ if ((redactPiiFields == null ? void 0 : redactPiiFields.span) && localTracePii !== true && !remotePiiConfig) {
7315
+ rateLimitedLog(
7316
+ "js-sdk.pii_span_fields_without_redaction",
7317
+ () => console.warn(
7318
+ "[raindrop] redactPiiFields.span is set but redactTracePii is off; no span is redacted. Set redactTracePii: true to use it."
7319
+ )
7320
+ );
7321
+ }
7322
+ const piiRedaction2 = {
7323
+ local: localTracePii,
7324
+ remote: remotePiiConfig,
7325
+ apiUrl: directEndpoint != null ? directEndpoint : apiUrl,
7326
+ writeKey: cloudEnabledResolved ? writeKey : void 0,
7327
+ spanFields: spanPiiFields
7328
+ };
7329
+ if (localTracePii === true) {
7330
+ requestLocalTracePiiRedaction(piiRedaction2.apiUrl, piiRedaction2.writeKey);
7331
+ }
6743
7332
  const authHint = authHintForKey(writeKey);
6744
7333
  const clientTracingExports = !useExternalOtel && cloudEnabledResolved && tracingEnabled !== false;
6745
7334
  registerClientKey(authHint, clientTracingExports);
@@ -6769,7 +7358,10 @@ var tracing = (analytics, apiUrl, writeKey, options, isDebug = false) => {
6769
7358
  localDebuggerUrl,
6770
7359
  cloudEnabled: cloudEnabledResolved,
6771
7360
  projectId,
6772
- flushTimeoutMs
7361
+ flushTimeoutMs,
7362
+ redactTracePii: localTracePii,
7363
+ remotePiiConfig,
7364
+ spanPiiFields
6773
7365
  }) : void 0;
6774
7366
  let traceloopInitialized = false;
6775
7367
  let claimedPipeline = false;
@@ -6808,7 +7400,8 @@ var tracing = (analytics, apiUrl, writeKey, options, isDebug = false) => {
6808
7400
  disableBatching,
6809
7401
  allowedInstrumentationLibraries: ALL_INSTRUMENTATION_LIBRARIES,
6810
7402
  localDebuggerUrlOpt: localDebuggerUrl,
6811
- routeReplayTraces: !cloudEnabledResolved
7403
+ routeReplayTraces: !cloudEnabledResolved,
7404
+ piiRedaction: piiRedaction2
6812
7405
  });
6813
7406
  if (!cloudEnabledResolved) {
6814
7407
  if (localDebuggerProcessor) {
@@ -6834,7 +7427,8 @@ var tracing = (analytics, apiUrl, writeKey, options, isDebug = false) => {
6834
7427
  exporter: new DropSpanExporter(),
6835
7428
  routeReplayTraces: true,
6836
7429
  disableBatch: disableBatching,
6837
- allowedInstrumentationLibraries: ALL_INSTRUMENTATION_LIBRARIES
7430
+ allowedInstrumentationLibraries: ALL_INSTRUMENTATION_LIBRARIES,
7431
+ piiRedaction: piiRedaction2
6838
7432
  });
6839
7433
  initialize({
6840
7434
  baseUrl: apiUrl,
@@ -6906,6 +7500,7 @@ var tracing = (analytics, apiUrl, writeKey, options, isDebug = false) => {
6906
7500
  disableBatch: disableBatching,
6907
7501
  processor,
6908
7502
  exporter: guardedExporter,
7503
+ piiRedaction: piiRedaction2,
6909
7504
  instrumentations: createConfiguredInstrumentations(otherOptions)
6910
7505
  });
6911
7506
  traceloopInitialized = true;
@@ -7147,7 +7742,8 @@ var tracing = (analytics, apiUrl, writeKey, options, isDebug = false) => {
7147
7742
  disableBatching,
7148
7743
  allowedInstrumentationLibraries: processorOptions == null ? void 0 : processorOptions.allowedInstrumentationLibraries,
7149
7744
  localDebuggerUrlOpt: localDebuggerUrl,
7150
- routeReplayTraces: true
7745
+ routeReplayTraces: true,
7746
+ piiRedaction: piiRedaction2
7151
7747
  });
7152
7748
  return withV2SpanCompat(
7153
7749
  localOnlyProcessor != null ? localOnlyProcessor : {
@@ -7169,13 +7765,15 @@ var tracing = (analytics, apiUrl, writeKey, options, isDebug = false) => {
7169
7765
  disableBatch: disableBatching,
7170
7766
  ...processorOptions != null ? processorOptions : {},
7171
7767
  routeReplayTraces: true,
7172
- ...headers ? { headers } : {}
7768
+ ...headers ? { headers } : {},
7769
+ piiRedaction: piiRedaction2
7173
7770
  });
7174
7771
  const localDebuggerProcessor = createLocalDebuggerSpanProcessor({
7175
7772
  writeKey,
7176
7773
  disableBatching,
7177
7774
  allowedInstrumentationLibraries: processorOptions == null ? void 0 : processorOptions.allowedInstrumentationLibraries,
7178
- localDebuggerUrlOpt: localDebuggerUrl
7775
+ localDebuggerUrlOpt: localDebuggerUrl,
7776
+ piiRedaction: piiRedaction2
7179
7777
  });
7180
7778
  const contextProcessor = new RaindropContextSpanProcessor((properties) => analytics.getAppGitSnapshot(properties));
7181
7779
  return withV2SpanCompat(
@@ -7307,7 +7905,10 @@ export {
7307
7905
  normalizeProjectId,
7308
7906
  projectIdHeaders,
7309
7907
  PiiFieldRedactor,
7908
+ piiRedactionNow,
7909
+ piiRedaction,
7310
7910
  isMissingUserId,
7911
+ snapshotPayload,
7311
7912
  POST_SHUTDOWN_TIMEOUT_MS,
7312
7913
  resolveFlushTimeoutMs,
7313
7914
  createAppGitContext2 as createAppGitContext,