raindrop-ai 1.0.8 → 1.0.9

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-R5EQZAA5.js
111
+ // ../core/dist/chunk-5OUEKTIO.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 });
@@ -202,7 +202,37 @@ var require_SimpleRegexpRedactor = __commonJS({
202
202
  this.replaceWith = replaceWith;
203
203
  this.regexpMatcher = regexpMatcher;
204
204
  }
205
- redact(textToRedact) {
205
+ redact(textToRedact, observe) {
206
+ if (observe) {
207
+ observe(0, 0, "");
208
+ let out = "";
209
+ let end = 0;
210
+ const matcher = new RegExp(this.regexpMatcher.source, this.regexpMatcher.flags);
211
+ let match;
212
+ while ((match = matcher.exec(textToRedact)) !== null) {
213
+ out += textToRedact.slice(end, match.index);
214
+ const captured = match;
215
+ const replacement = this.replaceWith.replace(/\$(\$|&|`|'|[1-9][0-9]?)/g, (token, key) => {
216
+ if (key === "$")
217
+ return "$";
218
+ if (key === "&")
219
+ return captured[0];
220
+ if (key === "`")
221
+ return textToRedact.slice(0, captured.index);
222
+ if (key === "'")
223
+ return textToRedact.slice(captured.index + captured[0].length);
224
+ return Number(key) < captured.length ? captured[Number(key)] || "" : token;
225
+ });
226
+ observe(out.length, match[0].length, replacement);
227
+ out += replacement;
228
+ end = match.index + match[0].length;
229
+ if (!matcher.global)
230
+ break;
231
+ if (match[0].length === 0)
232
+ matcher.lastIndex += 1;
233
+ }
234
+ return out + textToRedact.slice(end);
235
+ }
206
236
  return textToRedact.replace(this.regexpMatcher, this.replaceWith);
207
237
  }
208
238
  };
@@ -308,9 +338,9 @@ var require_SyncCompositeRedactor = __commonJS({
308
338
  var SyncCompositeRedactor = class {
309
339
  constructor(opts) {
310
340
  this.childRedactors = [];
311
- this.redact = (textToRedact) => {
341
+ this.redact = (textToRedact, observe) => {
312
342
  for (const redactor2 of this.childRedactors) {
313
- textToRedact = redactor2.redact(textToRedact);
343
+ textToRedact = redactor2.redact(textToRedact, observe);
314
344
  }
315
345
  return textToRedact;
316
346
  };
@@ -1830,8 +1860,62 @@ function normalizeProjectId(raw, opts) {
1830
1860
  function projectIdHeaders(projectId) {
1831
1861
  return projectId ? { [PROJECT_ID_HEADER]: projectId } : {};
1832
1862
  }
1863
+ var PII_MARKERS = /<REDACTED (?:CREDENTIALS|CREDIT CARD NUMBER|EMAIL|SECRET|PHONE NUMBER|ADDRESS|SOCIAL SECURITY NUMBER|DATE OF BIRTH|MEDICAL RECORD NUMBER)>/g;
1864
+ function replacePiiMatches(text, pattern, replace, observe, preservePrefix = true) {
1865
+ observe == null ? void 0 : observe(0, 0, "");
1866
+ let out = "";
1867
+ let end = 0;
1868
+ for (const match of text.matchAll(pattern)) {
1869
+ out += text.slice(end, match.index);
1870
+ const replacement = replace(match);
1871
+ if (replacement !== match[0]) {
1872
+ let prefix = 0;
1873
+ if (preservePrefix) {
1874
+ while (prefix < match[0].length && prefix < replacement.length && match[0][prefix] === replacement[prefix]) prefix++;
1875
+ }
1876
+ observe == null ? void 0 : observe(out.length + prefix, match[0].length - prefix, replacement.slice(prefix));
1877
+ }
1878
+ out += replacement;
1879
+ end = match.index + match[0].length;
1880
+ }
1881
+ return out + text.slice(end);
1882
+ }
1883
+ function redactWithinOriginalLimit(text, maxChars, redact) {
1884
+ let cutoff = Math.min(text.length, maxChars);
1885
+ const redacted = redact(text.slice(0, maxChars + 256), (start, length, replacement) => {
1886
+ if (start >= cutoff) return;
1887
+ cutoff = start + length >= cutoff ? start + replacement.length : cutoff + replacement.length - length;
1888
+ });
1889
+ let prefix = redacted.slice(0, cutoff);
1890
+ if (text.length <= maxChars && prefix.length <= maxChars) return prefix;
1891
+ if (maxChars < TRUNCATION_MARKER.length) return "";
1892
+ const budget = Math.max(0, maxChars - TRUNCATION_MARKER.length);
1893
+ let end = Math.min(prefix.length, budget);
1894
+ for (const marker of prefix.matchAll(PII_MARKERS)) {
1895
+ if (marker.index < end && marker.index + marker[0].length > end) end = marker.index;
1896
+ }
1897
+ prefix = prefix.slice(0, end);
1898
+ return prefix + TRUNCATION_MARKER;
1899
+ }
1900
+ var day = "(?:0?[1-9]|[12][0-9]|3[01])";
1901
+ var month = "(?:0?[1-9]|1[0-2])";
1902
+ var year = "(?:18|19|20)[0-9]{2}";
1903
+ var monthName = "(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)";
1904
+ var date = `(?:${month}/${day}/${year}|${day}-${month}-${year}|${year}-${month}-${day}|${monthName} ${day},? ${year}|${day} ${monthName} ${year})`;
1905
+ var birthDate = new RegExp(
1906
+ `(\\b(?:d\\.?o\\.?b\\.?|date[ _]?of[ _]?birth|born|birthday)[\\t :="']{0,8}(?:on[ ]{1,3})?)${date}(?![\\p{L}\\p{N}_]|T[0-9])`,
1907
+ "giu"
1908
+ );
1909
+ var mrn = /\b((?:MRN|medical record(?: number)?)["']?[\t :#=]{1,8}["']?)([a-z0-9][a-z0-9-]{2,39})\b/gi;
1910
+ var contextualPiiRedactor = {
1911
+ redact(text, observe) {
1912
+ text = replacePiiMatches(text, birthDate, (m) => `${m[1]}<REDACTED DATE OF BIRTH>`, observe);
1913
+ return replacePiiMatches(text, mrn, (m) => /[0-9]/.test(m[2]) ? `${m[1]}<REDACTED MEDICAL RECORD NUMBER>` : m[0], observe);
1914
+ }
1915
+ };
1833
1916
  var import_redact_pii = __toESM(require_dist(), 1);
1834
1917
  var DEFAULT_PII_REDACTION_OPTIONS = {
1918
+ customRedactors: { after: [contextualPiiRedactor] },
1835
1919
  builtInRedactors: {
1836
1920
  credentials: { replaceWith: "<REDACTED CREDENTIALS>" },
1837
1921
  creditCardNumber: { replaceWith: "<REDACTED CREDIT CARD NUMBER>" },
@@ -1851,9 +1935,522 @@ var DEFAULT_PII_REDACTION_OPTIONS = {
1851
1935
  }
1852
1936
  };
1853
1937
  var redactor;
1854
- function redactPiiText(text) {
1938
+ function redactPiiText(text, observe) {
1855
1939
  redactor != null ? redactor : redactor = new import_redact_pii.SyncRedactor(DEFAULT_PII_REDACTION_OPTIONS);
1856
- return redactor.redact(text);
1940
+ let out = "";
1941
+ let start = 0;
1942
+ for (const marker of text.matchAll(PII_MARKERS)) {
1943
+ const offset2 = out.length;
1944
+ out += redactor.redact(text.slice(start, marker.index), observe && ((at, length, replacement) => observe(offset2 + at, length, replacement))) + marker[0];
1945
+ start = marker.index + marker[0].length;
1946
+ }
1947
+ const offset = out.length;
1948
+ return out + redactor.redact(text.slice(start), observe && ((at, length, replacement) => observe(offset + at, length, replacement)));
1949
+ }
1950
+ 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)$/;
1951
+ var CONTENT_KEYS = /* @__PURE__ */ new Set([
1952
+ "ai.prompt.system",
1953
+ "ai.subagent.result",
1954
+ "agent.session.title",
1955
+ // Failed tool calls carry the tool's output in their error text.
1956
+ "error.message",
1957
+ "exception.message",
1958
+ "exception.stacktrace"
1959
+ ]);
1960
+ var NON_CONTENT_PREFIXES = [
1961
+ "traceloop.association.properties.",
1962
+ "ai.telemetry.metadata.",
1963
+ "ai.settings.context.",
1964
+ "raindrop.app."
1965
+ ];
1966
+ var ASSOCIATION_PROPERTY = /^(?:ai\.telemetry\.metadata\.)?traceloop\.association\.properties\.(.+)$/;
1967
+ var SDK_ASSOCIATION_PROPERTIES = /* @__PURE__ */ new Set([
1968
+ "user_id",
1969
+ "event_id",
1970
+ "convo_id",
1971
+ "event_name"
1972
+ ]);
1973
+ function isEventPropertyCopy(key) {
1974
+ var _a;
1975
+ if (key === "ai.telemetry.metadata.raindrop.properties") return true;
1976
+ const name = (_a = ASSOCIATION_PROPERTY.exec(key)) == null ? void 0 : _a[1];
1977
+ return name !== void 0 && !SDK_ASSOCIATION_PROPERTIES.has(name) && !name.startsWith("raindrop.");
1978
+ }
1979
+ var JSON_SIMPLE_ESCAPES = {
1980
+ '"': '"',
1981
+ "\\": "\\",
1982
+ "/": "/",
1983
+ b: "\b",
1984
+ f: "\f",
1985
+ n: "\n",
1986
+ r: "\r",
1987
+ t: " "
1988
+ };
1989
+ function decodeJsonEscapes(text, observe) {
1990
+ if (!text.includes("\\")) return text;
1991
+ let out = "";
1992
+ for (let i = 0; i < text.length; i++) {
1993
+ const ch = text[i];
1994
+ if (ch !== "\\" || i + 1 >= text.length) {
1995
+ out += ch;
1996
+ continue;
1997
+ }
1998
+ const next = text[i + 1];
1999
+ const simple = JSON_SIMPLE_ESCAPES[next];
2000
+ if (simple !== void 0) {
2001
+ observe == null ? void 0 : observe(out.length, 2, simple);
2002
+ out += simple;
2003
+ i += 1;
2004
+ } else if (next === "u" && /^[0-9a-fA-F]{4}$/.test(text.slice(i + 2, i + 6))) {
2005
+ observe == null ? void 0 : observe(out.length, 6, String.fromCharCode(Number.parseInt(text.slice(i + 2, i + 6), 16)));
2006
+ out += String.fromCharCode(Number.parseInt(text.slice(i + 2, i + 6), 16));
2007
+ i += 5;
2008
+ } else {
2009
+ out += ch;
2010
+ }
2011
+ }
2012
+ return out;
2013
+ }
2014
+ function jsonStringBody(value, observe) {
2015
+ if (!observe) return JSON.stringify(value).slice(1, -1);
2016
+ return replacePiiMatches(
2017
+ value,
2018
+ /[\u0000-\u001f"\\]|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g,
2019
+ (m) => JSON.stringify(m[0]).slice(1, -1),
2020
+ observe,
2021
+ false
2022
+ );
2023
+ }
2024
+ function redactEncodedBody(raw, cue, observe) {
2025
+ const decoded = decodeJsonEscapes(raw);
2026
+ const edits = [];
2027
+ const redacted = redactCuedValue(decoded, cue, observe && ((...edit) => edits.push(edit)));
2028
+ if (redacted === decoded) return raw;
2029
+ decodeJsonEscapes(raw, observe);
2030
+ for (const edit of edits) observe == null ? void 0 : observe(...edit);
2031
+ return jsonStringBody(redacted, observe);
2032
+ }
2033
+ function redactStringToken(token, cue, observe) {
2034
+ const body = redactEncodedBody(token.slice(1, -1), cue, observe && ((at, length, replacement) => observe(at + 1, length, replacement)));
2035
+ return `"${body}"`;
2036
+ }
2037
+ function contextualCue(key) {
2038
+ switch (key.trim().toLowerCase().replace(/[\s_.\-]/g, "")) {
2039
+ case "dob":
2040
+ case "dateofbirth":
2041
+ case "birthday":
2042
+ case "born":
2043
+ return "DOB: ";
2044
+ case "mrn":
2045
+ case "medicalrecord":
2046
+ case "medicalrecordnumber":
2047
+ return "MRN: ";
2048
+ default:
2049
+ return void 0;
2050
+ }
2051
+ }
2052
+ function redactCuedValue(value, cue, observe) {
2053
+ const redacted = redactPiiText(value, observe);
2054
+ return cue === void 0 ? redacted : contextualPiiRedactor.redact(cue + redacted, observe && ((at, length, replacement) => {
2055
+ if (length === 0 && replacement === "") {
2056
+ observe(0, 0, "");
2057
+ return;
2058
+ }
2059
+ const prefix = Math.max(0, cue.length - at);
2060
+ observe(Math.max(0, at - cue.length), length - prefix, replacement.slice(prefix));
2061
+ })).slice(cue.length);
2062
+ }
2063
+ function redactLooseJsonText(text, observe) {
2064
+ var _a;
2065
+ if (text.startsWith('"')) {
2066
+ return `"${redactEncodedBody(text.slice(1), void 0, observe && ((at, length, replacement) => observe(at + 1, length, replacement)))}`;
2067
+ }
2068
+ if (!text.includes("\\")) return redactPiiText(text, observe);
2069
+ let pieces = (_a = text.match(/\\u[0-9a-fA-F]{4}|\\["\\/bfnrt]|[\s\S]/g)) != null ? _a : [];
2070
+ const decoded = pieces.map((piece) => decodeJsonEscapes(piece)).join("");
2071
+ let next = [];
2072
+ let read = 0;
2073
+ let delta = 0;
2074
+ let written = 0;
2075
+ const copyTo = (end) => {
2076
+ while (read < end) {
2077
+ const piece = pieces[read++];
2078
+ next.push(piece);
2079
+ written += piece.length;
2080
+ }
2081
+ };
2082
+ const finishPass = () => {
2083
+ copyTo(pieces.length);
2084
+ pieces = next;
2085
+ next = [];
2086
+ read = 0;
2087
+ delta = 0;
2088
+ written = 0;
2089
+ };
2090
+ redactPiiText(decoded, (start, length, replacement) => {
2091
+ if (length === 0 && replacement === "") {
2092
+ finishPass();
2093
+ return;
2094
+ }
2095
+ const at = start - delta;
2096
+ copyTo(at);
2097
+ let rawLength = 0;
2098
+ for (let index = at; index < at + length; index++) rawLength += pieces[index].length;
2099
+ observe == null ? void 0 : observe(written, rawLength, replacement);
2100
+ for (let index = 0; index < replacement.length; index++) next.push(replacement[index]);
2101
+ written += replacement.length;
2102
+ read = at + length;
2103
+ delta += replacement.length - length;
2104
+ });
2105
+ finishPass();
2106
+ return pieces.join("");
2107
+ }
2108
+ function stringTokenEnd(text, start) {
2109
+ for (let i = start + 1; i < text.length; i++) {
2110
+ const ch = text[i];
2111
+ if (ch === "\\") i += 1;
2112
+ else if (ch === '"') return i + 1;
2113
+ }
2114
+ return -1;
2115
+ }
2116
+ function redactJsonLike(text, complete, observe) {
2117
+ var _a, _b;
2118
+ let out = "";
2119
+ let looseStart = 0;
2120
+ const flushLoose = (end) => {
2121
+ if (end > looseStart) {
2122
+ const loose = text.slice(looseStart, end);
2123
+ const offset = out.length;
2124
+ out += complete ? loose : redactLooseJsonText(loose, observe && ((at, length, replacement) => observe(offset + at, length, replacement)));
2125
+ }
2126
+ };
2127
+ let i = text.indexOf('"');
2128
+ while (i !== -1) {
2129
+ const end = stringTokenEnd(text, i);
2130
+ if (end === -1) break;
2131
+ flushLoose(i);
2132
+ let after = end;
2133
+ while (after < text.length && /\s/.test(text[after])) after += 1;
2134
+ const token = text.slice(i, end);
2135
+ if (text[after] === ":") {
2136
+ const cue = contextualCue(decodeJsonEscapes(token.slice(1, -1)));
2137
+ if (cue !== void 0) {
2138
+ let start = after + 1;
2139
+ while (/\s/.test((_a = text[start]) != null ? _a : "")) start += 1;
2140
+ let valueEnd = start;
2141
+ let replacement;
2142
+ const offset2 = out.length + start - i;
2143
+ const valueObserver = observe && ((at, length, replacement2) => observe(offset2 + at, length, replacement2));
2144
+ if (text[start] === '"') {
2145
+ valueEnd = stringTokenEnd(text, start);
2146
+ if (valueEnd === -1) {
2147
+ valueEnd = text.length;
2148
+ replacement = `"${redactEncodedBody(text.slice(start + 1), cue, valueObserver && ((at, length, replacement2) => valueObserver(at + 1, length, replacement2)))}`;
2149
+ } else {
2150
+ replacement = redactStringToken(text.slice(start, valueEnd), cue, valueObserver);
2151
+ }
2152
+ } else if (/[-0-9]/.test((_b = text[start]) != null ? _b : "")) {
2153
+ while (valueEnd < text.length && !/[\s,}\]]/.test(text[valueEnd])) valueEnd += 1;
2154
+ const value = text.slice(start, valueEnd);
2155
+ const redacted = redactCuedValue(value, cue);
2156
+ if (redacted !== value) {
2157
+ replacement = JSON.stringify(redacted);
2158
+ valueObserver == null ? void 0 : valueObserver(0, value.length, replacement);
2159
+ }
2160
+ }
2161
+ if (replacement !== void 0) {
2162
+ out += text.slice(i, start) + replacement;
2163
+ looseStart = valueEnd;
2164
+ i = text.indexOf('"', valueEnd);
2165
+ continue;
2166
+ }
2167
+ }
2168
+ }
2169
+ const offset = out.length;
2170
+ out += complete && text[after] === ":" ? token : redactStringToken(token, void 0, observe && ((at, length, replacement) => observe(offset + at, length, replacement)));
2171
+ looseStart = end;
2172
+ i = text.indexOf('"', end);
2173
+ }
2174
+ if (i === -1) {
2175
+ flushLoose(text.length);
2176
+ } else {
2177
+ flushLoose(i);
2178
+ looseStart = i;
2179
+ flushLoose(text.length);
2180
+ }
2181
+ return out;
2182
+ }
2183
+ function redactSpanContent(text, observe) {
2184
+ const head = text.trimStart()[0];
2185
+ if (head !== "{" && head !== "[" && head !== '"') return redactPiiText(text, observe);
2186
+ let complete = true;
2187
+ try {
2188
+ JSON.parse(text);
2189
+ } catch (e) {
2190
+ complete = false;
2191
+ }
2192
+ return redactJsonLike(text, complete, observe);
2193
+ }
2194
+ function isCompleteJsonContainer(text) {
2195
+ const head = text.trimStart()[0];
2196
+ if (head !== "{" && head !== "[") return false;
2197
+ try {
2198
+ JSON.parse(text);
2199
+ return true;
2200
+ } catch (e) {
2201
+ return false;
2202
+ }
2203
+ }
2204
+ function redactJsonEventContent(text, observe) {
2205
+ if (!/^\s*(?:\{\s*"|\[\s*["{\[])/.test(text) && !isCompleteJsonContainer(text)) return text;
2206
+ return redactSpanContent(text, observe);
2207
+ }
2208
+ var NO_SPAN_PII_FIELDS = { exact: /* @__PURE__ */ new Set(), prefixes: [] };
2209
+ function compileSpanPiiFields(names, logPrefix = "[raindrop-ai/core]") {
2210
+ if (!Array.isArray(names) || names.length === 0) return NO_SPAN_PII_FIELDS;
2211
+ const exact = /* @__PURE__ */ new Set();
2212
+ const prefixes = [];
2213
+ for (const name of names) {
2214
+ const valid = typeof name === "string" && !/\s/.test(name) && /^[^*]+\*?$/.test(name);
2215
+ if (!valid) {
2216
+ rateLimitedLog(
2217
+ `${logPrefix}.pii_span_field_invalid`,
2218
+ () => console.warn(
2219
+ `${logPrefix} redactPiiFields: ignoring invalid span attribute ${JSON.stringify(name)}`
2220
+ )
2221
+ );
2222
+ continue;
2223
+ }
2224
+ if (name.endsWith("*")) prefixes.push(name.slice(0, -1));
2225
+ else exact.add(name);
2226
+ }
2227
+ return { exact, prefixes };
2228
+ }
2229
+ function isCallerSelected(key, fields) {
2230
+ return fields.exact.has(key) || fields.prefixes.some((prefix) => key.startsWith(prefix));
2231
+ }
2232
+ function isSpanContentAttributeKey(key, fields = NO_SPAN_PII_FIELDS) {
2233
+ if (isCallerSelected(key, fields) || isEventPropertyCopy(key)) return true;
2234
+ if (NON_CONTENT_PREFIXES.some((prefix) => key.startsWith(prefix))) return false;
2235
+ return CONTENT_KEYS.has(key) || CONTENT_KEY_SUFFIX.test(key);
2236
+ }
2237
+ function redactBoundedContent(text, maxChars) {
2238
+ if (maxChars === void 0) return redactSpanContent(text);
2239
+ return redactWithinOriginalLimit(text, maxChars, redactSpanContent);
2240
+ }
2241
+ function redactOtlpValue(value, maxChars) {
2242
+ var _a;
2243
+ if (typeof value.stringValue === "string") {
2244
+ const redacted = redactBoundedContent(value.stringValue, maxChars);
2245
+ return redacted === value.stringValue ? value : { ...value, stringValue: redacted };
2246
+ }
2247
+ const values = (_a = value.arrayValue) == null ? void 0 : _a.values;
2248
+ if (!values) return value;
2249
+ let changed = false;
2250
+ const next = values.map((item) => {
2251
+ const redacted = redactOtlpValue(item, maxChars);
2252
+ if (redacted !== item) changed = true;
2253
+ return redacted;
2254
+ });
2255
+ return changed ? { ...value, arrayValue: { values: next } } : value;
2256
+ }
2257
+ function redactPiiInOtlpAttributes(attributes, fields = NO_SPAN_PII_FIELDS, maxChars) {
2258
+ let next;
2259
+ for (let i = 0; i < attributes.length; i++) {
2260
+ const attr = attributes[i];
2261
+ if (!attr.value || !isSpanContentAttributeKey(attr.key, fields)) continue;
2262
+ const value = redactOtlpValue(attr.value, maxChars);
2263
+ if (value === attr.value) continue;
2264
+ next != null ? next : next = attributes.slice();
2265
+ next[i] = { ...attr, value };
2266
+ }
2267
+ return next != null ? next : attributes;
2268
+ }
2269
+ function redactPiiInOtlpSpan(span, fields = NO_SPAN_PII_FIELDS, maxChars) {
2270
+ var _a;
2271
+ const attributes = span.attributes && redactPiiInOtlpAttributes(span.attributes, fields, maxChars);
2272
+ const message = (_a = span.status) == null ? void 0 : _a.message;
2273
+ const redactedMessage = message === void 0 ? void 0 : redactBoundedContent(message, maxChars);
2274
+ if (attributes === span.attributes && redactedMessage === message) return span;
2275
+ const status = span.status && redactedMessage !== message ? { ...span.status, message: redactedMessage } : span.status;
2276
+ return { ...span, attributes, status };
2277
+ }
2278
+ function redactPiiInAttributeMap(attributes, fields = NO_SPAN_PII_FIELDS) {
2279
+ let next;
2280
+ for (const [key, value] of Object.entries(attributes)) {
2281
+ if (!isSpanContentAttributeKey(key, fields)) continue;
2282
+ let redacted = value;
2283
+ if (typeof value === "string") {
2284
+ redacted = redactSpanContent(value);
2285
+ } else if (Array.isArray(value)) {
2286
+ let changed = false;
2287
+ const items = value.map((item) => {
2288
+ if (typeof item !== "string") return item;
2289
+ const out = redactSpanContent(item);
2290
+ if (out !== item) changed = true;
2291
+ return out;
2292
+ });
2293
+ if (changed) redacted = items;
2294
+ }
2295
+ if (redacted === value) continue;
2296
+ next != null ? next : next = { ...attributes };
2297
+ next[key] = redacted;
2298
+ }
2299
+ return next;
2300
+ }
2301
+ var MASK_FAILED = "<MASK FAILED>";
2302
+ var EVENT_FIELDS = {
2303
+ event: [["ai_data", "input"], ["ai_data", "output"], ["properties"], ["attachments"]],
2304
+ signal: [["properties"]],
2305
+ identify: [["traits"]]
2306
+ };
2307
+ var SDK_PROPERTY_KEYS = ["$context"];
2308
+ function isPlainObject(value) {
2309
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
2310
+ const proto = Object.getPrototypeOf(value);
2311
+ return proto === Object.prototype || proto === null;
2312
+ }
2313
+ function isThenable(value) {
2314
+ return typeof value === "object" && value !== null && "then" in value && typeof value.then === "function";
2315
+ }
2316
+ function warn(prefix, context7, reason) {
2317
+ rateLimitedLog(
2318
+ `${prefix}.mask_failed`,
2319
+ () => console.warn(
2320
+ `${prefix} mask function failed on ${context7.kind} ${context7.field} (${reason}); sending ${MASK_FAILED} in its place.`
2321
+ )
2322
+ );
2323
+ }
2324
+ function jsonCopy(value) {
2325
+ const json = JSON.stringify(value);
2326
+ if (json === void 0) throw new TypeError("not JSON-serializable");
2327
+ return JSON.parse(json);
2328
+ }
2329
+ function failed(shape) {
2330
+ if (shape === "string") return MASK_FAILED;
2331
+ if (shape === "object") return { error: MASK_FAILED };
2332
+ return [];
2333
+ }
2334
+ function maskValue(value, context7, mask, prefix) {
2335
+ const shape = typeof value === "string" ? "string" : Array.isArray(value) ? "array" : "object";
2336
+ try {
2337
+ const result = mask(shape === "string" ? value : jsonCopy(value), context7);
2338
+ if (isThenable(result)) {
2339
+ Promise.resolve(result).catch(() => {
2340
+ });
2341
+ warn(prefix, context7, "it returned a promise; mask must be synchronous");
2342
+ return failed(shape);
2343
+ }
2344
+ if (shape === "string") {
2345
+ if (typeof result === "string") return result;
2346
+ } else {
2347
+ const copy = jsonCopy(result);
2348
+ if (shape === "array" ? Array.isArray(copy) : isPlainObject(copy)) return copy;
2349
+ }
2350
+ warn(prefix, context7, `it returned a value that is not ${shape === "string" ? "a string" : `an ${shape}`}`);
2351
+ } catch (err) {
2352
+ warn(prefix, context7, err instanceof Error ? err.name : "threw");
2353
+ }
2354
+ return failed(shape);
2355
+ }
2356
+ function maskAt(node, path, context7, mask, prefix) {
2357
+ const [head, ...rest] = path;
2358
+ if (head === void 0 || !Object.prototype.hasOwnProperty.call(node, head)) return node;
2359
+ const child = node[head];
2360
+ if (rest.length > 0) {
2361
+ if (!isPlainObject(child)) return node;
2362
+ const next = maskAt(child, rest, context7, mask, prefix);
2363
+ return next === child ? node : { ...node, [head]: next };
2364
+ }
2365
+ if (child === void 0 || child === null) return node;
2366
+ if (typeof child !== "string" && typeof child !== "object") return node;
2367
+ if (context7.kind !== "event" || head !== "properties" || !isPlainObject(child)) {
2368
+ return { ...node, [head]: maskValue(child, context7, mask, prefix) };
2369
+ }
2370
+ const own2 = {};
2371
+ const sdk = {};
2372
+ for (const [key, value] of Object.entries(child)) {
2373
+ (SDK_PROPERTY_KEYS.includes(key) ? sdk : own2)[key] = value;
2374
+ }
2375
+ const masked = maskValue(own2, context7, mask, prefix);
2376
+ return { ...node, [head]: isPlainObject(masked) ? { ...masked, ...sdk } : sdk };
2377
+ }
2378
+ function maskPayload(kind, payload, mask, logPrefix = "[raindrop-ai/core]") {
2379
+ if (!mask) return payload;
2380
+ let out = payload;
2381
+ for (const path of EVENT_FIELDS[kind]) {
2382
+ out = maskAt(out, path, { kind, field: path.join(".") }, mask, logPrefix);
2383
+ }
2384
+ return out;
2385
+ }
2386
+ function maskOtlpValue(value, context7, mask, prefix) {
2387
+ var _a;
2388
+ if (typeof value.stringValue === "string") {
2389
+ const masked = maskValue(value.stringValue, context7, mask, prefix);
2390
+ return typeof masked === "string" && masked !== value.stringValue ? { ...value, stringValue: masked } : value;
2391
+ }
2392
+ const values = (_a = value.arrayValue) == null ? void 0 : _a.values;
2393
+ if (!values) return value;
2394
+ let changed = false;
2395
+ const next = values.map((item) => {
2396
+ const masked = maskOtlpValue(item, context7, mask, prefix);
2397
+ if (masked !== item) changed = true;
2398
+ return masked;
2399
+ });
2400
+ return changed ? { ...value, arrayValue: { values: next } } : value;
2401
+ }
2402
+ function maskSpanStatusMessage(message, mask, logPrefix = "[raindrop-ai/core]") {
2403
+ if (!mask) return message;
2404
+ const masked = maskValue(message, { kind: "span", field: "status.message" }, mask, logPrefix);
2405
+ return typeof masked === "string" ? masked : MASK_FAILED;
2406
+ }
2407
+ function maskOtlpAttributes(attributes, mask, fields, logPrefix = "[raindrop-ai/core]") {
2408
+ if (!mask) return attributes;
2409
+ let next;
2410
+ for (let i = 0; i < attributes.length; i++) {
2411
+ const attr = attributes[i];
2412
+ if (!attr.value || !isSpanContentAttributeKey(attr.key, fields)) continue;
2413
+ const value = maskOtlpValue(attr.value, { kind: "span", field: attr.key }, mask, logPrefix);
2414
+ if (value === attr.value) continue;
2415
+ next != null ? next : next = attributes.slice();
2416
+ next[i] = { ...attr, value };
2417
+ }
2418
+ return next != null ? next : attributes;
2419
+ }
2420
+ function maskOtlpSpan(span, mask, fields, logPrefix = "[raindrop-ai/core]") {
2421
+ var _a;
2422
+ if (!mask) return span;
2423
+ const attributes = span.attributes && maskOtlpAttributes(span.attributes, mask, fields, logPrefix);
2424
+ const message = (_a = span.status) == null ? void 0 : _a.message;
2425
+ const nextMessage = message === void 0 ? void 0 : maskSpanStatusMessage(message, mask, logPrefix);
2426
+ if (attributes === span.attributes && nextMessage === message) return span;
2427
+ const status = span.status && nextMessage !== message ? { ...span.status, message: nextMessage } : span.status;
2428
+ return { ...span, attributes, status };
2429
+ }
2430
+ function maskAttributeMap(attributes, mask, fields, logPrefix = "[raindrop-ai/core]") {
2431
+ if (!mask) return void 0;
2432
+ let next;
2433
+ for (const [key, value] of Object.entries(attributes)) {
2434
+ if (!isSpanContentAttributeKey(key, fields)) continue;
2435
+ const context7 = { kind: "span", field: key };
2436
+ let masked = value;
2437
+ if (typeof value === "string") {
2438
+ masked = maskValue(value, context7, mask, logPrefix);
2439
+ } else if (Array.isArray(value)) {
2440
+ let changed = false;
2441
+ const items = value.map((item) => {
2442
+ if (typeof item !== "string") return item;
2443
+ const out = maskValue(item, context7, mask, logPrefix);
2444
+ if (out !== item) changed = true;
2445
+ return out;
2446
+ });
2447
+ if (changed) masked = items;
2448
+ }
2449
+ if (masked === value) continue;
2450
+ next != null ? next : next = { ...attributes };
2451
+ next[key] = masked;
2452
+ }
2453
+ return next;
1857
2454
  }
1858
2455
  var KINDS = ["event", "signal", "identify"];
1859
2456
  var DEFAULT_PII_FIELDS = {
@@ -1949,7 +2546,7 @@ function mergePiiFieldMaps(...maps) {
1949
2546
  }
1950
2547
  return out;
1951
2548
  }
1952
- function isPlainObject(value) {
2549
+ function isPlainObject2(value) {
1953
2550
  if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
1954
2551
  const proto = Object.getPrototypeOf(value);
1955
2552
  return proto === Object.prototype || proto === null;
@@ -1957,30 +2554,35 @@ function isPlainObject(value) {
1957
2554
  function isProtected(location) {
1958
2555
  return PROTECTED_LOCATIONS.has(JSON.stringify(location));
1959
2556
  }
1960
- function redactAll(value, location) {
2557
+ function redactAll(value, location, maxChars) {
1961
2558
  if (location !== null && isProtected(location)) return value;
1962
- if (typeof value === "string") return redactPiiText(value);
1963
- if (Array.isArray(value)) return value.map((item) => redactAll(item, null));
1964
- if (isPlainObject(value)) {
2559
+ if (typeof value === "string") {
2560
+ if (maxChars !== void 0 && (location == null ? void 0 : location.length) === 2 && location[0] === "ai_data" && (location[1] === "input" || location[1] === "output")) {
2561
+ return redactWithinOriginalLimit(value, maxChars, (text, observe) => redactPiiText(redactJsonEventContent(text, observe), observe));
2562
+ }
2563
+ return redactPiiText(redactJsonEventContent(value));
2564
+ }
2565
+ if (Array.isArray(value)) return value.map((item) => redactAll(item, null, maxChars));
2566
+ if (isPlainObject2(value)) {
1965
2567
  const out = {};
1966
2568
  for (const [key, child] of Object.entries(value)) {
1967
- out[key] = redactAll(child, location === null ? null : [...location, key]);
2569
+ out[key] = redactAll(child, location === null ? null : [...location, key], maxChars);
1968
2570
  }
1969
2571
  return out;
1970
2572
  }
1971
2573
  return value;
1972
2574
  }
1973
- function applyPath(value, segments, location) {
1974
- if (segments.length === 0) return redactAll(value, location);
2575
+ function applyPath(value, segments, location, maxChars) {
2576
+ if (segments.length === 0) return redactAll(value, location, maxChars);
1975
2577
  const [head, ...rest] = segments;
1976
2578
  if (head.kind === "key" || head.kind === "any_key") {
1977
- if (!isPlainObject(value)) return value;
2579
+ if (!isPlainObject2(value)) return value;
1978
2580
  const keys = head.kind === "key" ? [head.key] : Object.keys(value);
1979
2581
  let out2;
1980
2582
  for (const key of keys) {
1981
2583
  if (!Object.prototype.hasOwnProperty.call(value, key)) continue;
1982
2584
  const child = value[key];
1983
- const next = applyPath(child, rest, location === null ? null : [...location, key]);
2585
+ const next = applyPath(child, rest, location === null ? null : [...location, key], maxChars);
1984
2586
  if (next !== child) {
1985
2587
  out2 != null ? out2 : out2 = { ...value };
1986
2588
  out2[key] = next;
@@ -1993,7 +2595,7 @@ function applyPath(value, segments, location) {
1993
2595
  let out;
1994
2596
  for (const index of indices) {
1995
2597
  const child = value[index];
1996
- const next = applyPath(child, rest, null);
2598
+ const next = applyPath(child, rest, null, maxChars);
1997
2599
  if (next !== child) {
1998
2600
  out != null ? out : out = [...value];
1999
2601
  out[index] = next;
@@ -2043,9 +2645,9 @@ var PiiFieldRedactor = class {
2043
2645
  return out;
2044
2646
  }
2045
2647
  /** The payload with every selected field redacted (a copy where changed). */
2046
- redact(kind, payload) {
2648
+ redact(kind, payload, maxChars) {
2047
2649
  let out = payload;
2048
- for (const segments of this.compile()[kind]) out = applyPath(out, segments, []);
2650
+ for (const segments of this.compile()[kind]) out = applyPath(out, segments, [], maxChars);
2049
2651
  return out;
2050
2652
  }
2051
2653
  };
@@ -2226,13 +2828,13 @@ function earliestIsoTimestamp(...values) {
2226
2828
  let earliest;
2227
2829
  for (const value of values) {
2228
2830
  if (value === void 0) continue;
2229
- const date = new Date(value);
2230
- if (Number.isNaN(date.getTime())) continue;
2231
- if (earliest === void 0 || date < earliest) earliest = date;
2831
+ const date2 = new Date(value);
2832
+ if (Number.isNaN(date2.getTime())) continue;
2833
+ if (earliest === void 0 || date2 < earliest) earliest = date2;
2232
2834
  }
2233
2835
  return earliest == null ? void 0 : earliest.toISOString();
2234
2836
  }
2235
- function isPlainObject2(value) {
2837
+ function isPlainObject3(value) {
2236
2838
  if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
2237
2839
  const proto = Object.getPrototypeOf(value);
2238
2840
  return proto === Object.prototype || proto === null;
@@ -2243,7 +2845,7 @@ function deepMergeProperties(target, source) {
2243
2845
  for (const [key, value] of Object.entries(source)) {
2244
2846
  if (value === void 0 || UNSAFE_MERGE_KEYS.has(key)) continue;
2245
2847
  const existing = out[key];
2246
- out[key] = isPlainObject2(existing) && isPlainObject2(value) ? deepMergeProperties(existing, value) : value;
2848
+ out[key] = isPlainObject3(existing) && isPlainObject3(value) ? deepMergeProperties(existing, value) : value;
2247
2849
  }
2248
2850
  return out;
2249
2851
  }
@@ -2343,6 +2945,7 @@ var EventShipper = class {
2343
2945
  });
2344
2946
  this.redactPii = typeof opts.redactPii === "boolean" ? opts.redactPii : void 0;
2345
2947
  this.remotePiiConfig = opts.remotePiiConfig;
2948
+ this.mask = typeof opts.mask === "function" ? opts.mask : void 0;
2346
2949
  this.piiFields = new PiiFieldRedactor({
2347
2950
  startupFieldMap: opts.redactPiiFields,
2348
2951
  logPrefix: this.prefix
@@ -2503,11 +3106,12 @@ var EventShipper = class {
2503
3106
  return void 0;
2504
3107
  }
2505
3108
  const maxChars = resolveMaxTextFieldChars(this.maxTextFieldCharsOpt);
2506
- if (typeof patch.input === "string" && patch.input.length > maxChars) {
2507
- patch = { ...patch, input: capText(patch.input, maxChars) };
2508
- }
2509
- if (typeof patch.output === "string" && patch.output.length > maxChars) {
2510
- patch = { ...patch, output: capText(patch.output, maxChars) };
3109
+ const mayRedact = this.redactPii === true || this.redactPii !== false && this.remotePiiConfig;
3110
+ for (const field of ["input", "output"]) {
3111
+ const text = patch[field];
3112
+ if (typeof text !== "string" || text.length <= maxChars) continue;
3113
+ const bounded = mayRedact ? text.slice(0, maxChars + 256) : capText(text, maxChars);
3114
+ patch = { ...patch, [field]: bounded };
2511
3115
  }
2512
3116
  if (this.debug) {
2513
3117
  console.log(`${this.prefix} queue patch`, {
@@ -2720,7 +3324,7 @@ var EventShipper = class {
2720
3324
  ];
2721
3325
  const known = piiRedactionNow(this.redactPii, this.remotePiiConfig, this.baseUrl, this.writeKey);
2722
3326
  if (known !== void 0) {
2723
- const body = known ? items.map((item) => this.piiFields.redact("signal", item)) : items;
3327
+ const body = items.map((item) => this.outgoing("signal", item, known));
2724
3328
  if (!this.writeKey) return;
2725
3329
  await this.sendDirect("signal", `${this.baseUrl}signals/track`, body);
2726
3330
  return;
@@ -2728,7 +3332,7 @@ var EventShipper = class {
2728
3332
  const snapshot = items.map(snapshotPayload);
2729
3333
  await this.tracked(async () => {
2730
3334
  const redact = await this.shouldRedactPii();
2731
- const body = redact ? snapshot.map((item) => this.piiFields.redact("signal", item)) : snapshot;
3335
+ const body = snapshot.map((item) => this.outgoing("signal", item, redact));
2732
3336
  if (!this.writeKey) return;
2733
3337
  await this.sendDirect("signal", `${this.baseUrl}signals/track`, body, void 0, false);
2734
3338
  });
@@ -2757,14 +3361,14 @@ var EventShipper = class {
2757
3361
  if (rows.length === 0) return;
2758
3362
  const known = piiRedactionNow(this.redactPii, this.remotePiiConfig, this.baseUrl, this.writeKey);
2759
3363
  if (known !== void 0) {
2760
- const body = known ? rows.map((user) => this.piiFields.redact("identify", user)) : rows;
3364
+ const body = rows.map((user) => this.outgoing("identify", user, known));
2761
3365
  await this.sendDirect("identify", `${this.baseUrl}users/identify`, body);
2762
3366
  return;
2763
3367
  }
2764
3368
  const snapshot = rows.map(snapshotPayload);
2765
3369
  await this.tracked(async () => {
2766
3370
  const redact = await this.shouldRedactPii();
2767
- const body = redact ? snapshot.map((user) => this.piiFields.redact("identify", user)) : snapshot;
3371
+ const body = snapshot.map((user) => this.outgoing("identify", user, redact));
2768
3372
  await this.sendDirect("identify", `${this.baseUrl}users/identify`, body, void 0, false);
2769
3373
  });
2770
3374
  }
@@ -2827,6 +3431,12 @@ var EventShipper = class {
2827
3431
  () => console.warn(`${this.prefix} failed to send ${what} (dropping): ${reason}`)
2828
3432
  );
2829
3433
  }
3434
+ /** A payload as it is sent: built-in redaction when on, then the caller's `mask`. */
3435
+ outgoing(kind, payload, redact) {
3436
+ const maxChars = kind === "event" ? resolveMaxTextFieldChars(this.maxTextFieldCharsOpt) : void 0;
3437
+ const redacted = redact ? this.piiFields.redact(kind, payload, maxChars) : payload;
3438
+ return isPlainObject3(redacted) ? maskPayload(kind, redacted, this.mask, this.prefix) : redacted;
3439
+ }
2830
3440
  /**
2831
3441
  * Whether to redact PII: `redactPii`, or when it is unset and
2832
3442
  * `remotePiiConfig` is on, the org's setting. Waits for the org's answer
@@ -2979,7 +3589,7 @@ var EventShipper = class {
2979
3589
  };
2980
3590
  const known = piiRedactionNow(this.redactPii, this.remotePiiConfig, this.baseUrl, this.writeKey);
2981
3591
  if (known !== void 0) {
2982
- const payload = known ? this.piiFields.redact("event", unredacted) : unredacted;
3592
+ const payload = this.outgoing("event", unredacted, known);
2983
3593
  return this.shipPartial(eventId, accumulated, payload, { eventName, userId, convoId, isPending }, deadlineAt, true);
2984
3594
  }
2985
3595
  const snapshot = snapshotPayload(unredacted);
@@ -2987,7 +3597,7 @@ var EventShipper = class {
2987
3597
  (redact) => this.shipPartial(
2988
3598
  eventId,
2989
3599
  accumulated,
2990
- redact ? this.piiFields.redact("event", snapshot) : snapshot,
3600
+ this.outgoing("event", snapshot, redact),
2991
3601
  { eventName, userId, convoId, isPending },
2992
3602
  deadlineAt,
2993
3603
  false
@@ -3009,6 +3619,20 @@ var EventShipper = class {
3009
3619
  var _a, _b, _c, _d, _e, _f;
3010
3620
  const { eventName, userId, convoId, isPending } = meta;
3011
3621
  const url = `${this.baseUrl}events/track_partial`;
3622
+ if (payload !== null && typeof payload === "object" && "ai_data" in payload) {
3623
+ const data = payload.ai_data;
3624
+ if (data !== null && typeof data === "object") {
3625
+ const maxChars = resolveMaxTextFieldChars(this.maxTextFieldCharsOpt);
3626
+ payload = {
3627
+ ...payload,
3628
+ ai_data: {
3629
+ ...data,
3630
+ input: capText("input" in data ? data.input : void 0, maxChars),
3631
+ output: capText("output" in data ? data.output : void 0, maxChars)
3632
+ }
3633
+ };
3634
+ }
3635
+ }
3012
3636
  if (this.debug) {
3013
3637
  const sent = payload;
3014
3638
  const preview = (v, n) => typeof v === "string" ? v.slice(0, n) : void 0;
@@ -3083,7 +3707,7 @@ function overriddenKeys(derived, caller) {
3083
3707
  for (const [key, value] of Object.entries(caller)) {
3084
3708
  if (value === void 0 || !(key in derived)) continue;
3085
3709
  const existing = derived[key];
3086
- if (isPlainObject2(existing) && isPlainObject2(value)) {
3710
+ if (isPlainObject3(existing) && isPlainObject3(value)) {
3087
3711
  if (overriddenKeys(existing, value).length > 0) keys.push(key);
3088
3712
  } else if (JSON.stringify(existing) !== JSON.stringify(value)) {
3089
3713
  keys.push(key);
@@ -3247,211 +3871,6 @@ var DEFAULT_REDACT_ATTRIBUTE_KEYS = [
3247
3871
  "ai.response.providerMetadata"
3248
3872
  ];
3249
3873
  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
- }
3455
3874
  var UNDELIVERED = Object.freeze({
3456
3875
  delivered: false,
3457
3876
  timedOut: false,
@@ -3795,7 +4214,7 @@ installTracingSuppressionHook();
3795
4214
  // package.json
3796
4215
  var package_default = {
3797
4216
  name: "raindrop-ai",
3798
- version: "1.0.8",
4217
+ version: "1.0.9",
3799
4218
  main: "dist/index.js",
3800
4219
  module: "dist/index.mjs",
3801
4220
  types: "dist/index.d.ts",
@@ -3997,17 +4416,17 @@ var ReplayRoutingSpanExporter = class {
3997
4416
  return;
3998
4417
  }
3999
4418
  let remaining = replayGroups.size + (normalSpans.length > 0 ? 1 : 0);
4000
- let failed = false;
4419
+ let failed2 = false;
4001
4420
  let firstError;
4002
4421
  const finish = (result) => {
4003
4422
  if (result.code !== EXPORT_SUCCESS) {
4004
- failed = true;
4423
+ failed2 = true;
4005
4424
  firstError != null ? firstError : firstError = result.error;
4006
4425
  }
4007
4426
  remaining -= 1;
4008
4427
  if (remaining === 0) {
4009
4428
  resultCallback(
4010
- firstError ? { code: EXPORT_FAILED, error: firstError } : { code: failed ? EXPORT_FAILED : EXPORT_SUCCESS }
4429
+ firstError ? { code: EXPORT_FAILED, error: firstError } : { code: failed2 ? EXPORT_FAILED : EXPORT_SUCCESS }
4011
4430
  );
4012
4431
  }
4013
4432
  };
@@ -4497,6 +4916,7 @@ var DirectTraceShipper = class {
4497
4916
  this.redactTracePii = opts.redactTracePii;
4498
4917
  this.remotePiiConfig = opts.remotePiiConfig;
4499
4918
  this.spanPiiFields = opts.spanPiiFields;
4919
+ this.mask = opts.mask;
4500
4920
  this.flushIntervalMs = (_d = opts.flushIntervalMs) != null ? _d : 1e3;
4501
4921
  this.maxBatchSize = (_e = opts.maxBatchSize) != null ? _e : 50;
4502
4922
  this.maxQueueSize = (_f = opts.maxQueueSize) != null ? _f : 5e3;
@@ -4603,7 +5023,7 @@ var DirectTraceShipper = class {
4603
5023
  const mirrorUrl = (replayDestination == null ? void 0 : replayDestination.kind) === "workshop" ? replayDestination.url : replayDestination ? void 0 : this.localDebuggerUrl;
4604
5024
  const mirrored = mirrorUrl && this.redactsNow() ? this.redactSpanPii(span) : span;
4605
5025
  if (mirrorUrl && mirrored) {
4606
- const body = buildExportTraceServiceRequest2([mirrored]);
5026
+ const body = buildExportTraceServiceRequest2([maskOtlpSpan(mirrored, this.mask, this.spanPiiFields, "[raindrop]")]);
4607
5027
  const mirror = mirrorTraceExportToLocalDebugger(body, {
4608
5028
  baseUrl: mirrorUrl,
4609
5029
  debug: false,
@@ -4629,7 +5049,7 @@ var DirectTraceShipper = class {
4629
5049
  /** The span with PII redacted from its input and output; undefined if redaction failed. */
4630
5050
  redactSpanPii(span) {
4631
5051
  try {
4632
- return redactPiiInOtlpSpan(span, this.spanPiiFields);
5052
+ return redactPiiInOtlpSpan(span, this.spanPiiFields, resolveMaxTextFieldChars(void 0));
4633
5053
  } catch (e) {
4634
5054
  return void 0;
4635
5055
  }
@@ -4728,10 +5148,10 @@ var DirectTraceShipper = class {
4728
5148
  if (!replayDestination && !this.cloudEnabled) continue;
4729
5149
  if ((replayDestination == null ? void 0 : replayDestination.kind) === "workshop") continue;
4730
5150
  const spans = queuedSpans.map((q) => q.span);
4731
- const outgoing = redactPii ? spans.flatMap((span) => {
5151
+ const outgoing = (redactPii ? spans.flatMap((span) => {
4732
5152
  var _a2;
4733
5153
  return (_a2 = this.redactSpanPii(span)) != null ? _a2 : [];
4734
- }) : spans;
5154
+ }) : spans).map((span) => maskOtlpSpan(span, this.mask, this.spanPiiFields, "[raindrop]"));
4735
5155
  if (outgoing.length === 0) continue;
4736
5156
  const body = buildExportTraceServiceRequest2(outgoing);
4737
5157
  const url = replayDestination ? replayTraceUrl(replayDestination.url) : `${this.baseUrl}traces`;
@@ -4877,6 +5297,34 @@ function redactSpanPii(span, fields) {
4877
5297
  copyReplayTraceDestination(span, view);
4878
5298
  return view;
4879
5299
  }
5300
+ function maskSpan(span, mask, fields) {
5301
+ const attributes = maskAttributeMap(span.attributes, mask, fields, "[raindrop]");
5302
+ const message = span.status.message;
5303
+ const nextMessage = message === void 0 ? void 0 : maskSpanStatusMessage(message, mask, "[raindrop]");
5304
+ let eventsChanged = false;
5305
+ const events = span.events.map((event) => {
5306
+ const eventAttributes = event.attributes && maskAttributeMap(event.attributes, mask, fields, "[raindrop]");
5307
+ if (!eventAttributes) return event;
5308
+ eventsChanged = true;
5309
+ return { ...event, attributes: eventAttributes };
5310
+ });
5311
+ if (!attributes && nextMessage === message && !eventsChanged) return span;
5312
+ const view = Object.create(span);
5313
+ if (attributes) {
5314
+ Object.defineProperty(view, "attributes", { value: attributes, enumerable: true });
5315
+ }
5316
+ if (nextMessage !== message) {
5317
+ Object.defineProperty(view, "status", {
5318
+ value: { ...span.status, message: nextMessage },
5319
+ enumerable: true
5320
+ });
5321
+ }
5322
+ if (eventsChanged) {
5323
+ Object.defineProperty(view, "events", { value: events, enumerable: true });
5324
+ }
5325
+ copyReplayTraceDestination(span, view);
5326
+ return view;
5327
+ }
4880
5328
  var PiiRedactingSpanExporter = class {
4881
5329
  constructor(inner, options) {
4882
5330
  this.inner = inner;
@@ -4885,7 +5333,7 @@ var PiiRedactingSpanExporter = class {
4885
5333
  this.pending = /* @__PURE__ */ new Set();
4886
5334
  }
4887
5335
  export(spans, resultCallback) {
4888
- const { local, remote, apiUrl, writeKey, spanFields } = this.options;
5336
+ const { local, remote, apiUrl, writeKey, spanFields, mask } = this.options;
4889
5337
  const exportContext = context2.active();
4890
5338
  const run = (redact) => {
4891
5339
  let outgoing = spans;
@@ -4898,6 +5346,7 @@ var PiiRedactingSpanExporter = class {
4898
5346
  }
4899
5347
  }
4900
5348
  }
5349
+ if (mask) outgoing = outgoing.map((span) => maskSpan(span, mask, spanFields));
4901
5350
  try {
4902
5351
  context2.with(exportContext, () => this.inner.export(outgoing, resultCallback));
4903
5352
  } catch (e) {
@@ -7306,6 +7755,7 @@ var tracing = (analytics, apiUrl, writeKey, options, isDebug = false) => {
7306
7755
  redactTracePii,
7307
7756
  redactPiiFields,
7308
7757
  remotePiiConfig,
7758
+ mask,
7309
7759
  ...otherOptions
7310
7760
  } = options;
7311
7761
  const cloudEnabledResolved = cloudEnabled != null ? cloudEnabled : true;
@@ -7324,7 +7774,8 @@ var tracing = (analytics, apiUrl, writeKey, options, isDebug = false) => {
7324
7774
  remote: remotePiiConfig,
7325
7775
  apiUrl: directEndpoint != null ? directEndpoint : apiUrl,
7326
7776
  writeKey: cloudEnabledResolved ? writeKey : void 0,
7327
- spanFields: spanPiiFields
7777
+ spanFields: spanPiiFields,
7778
+ mask: typeof mask === "function" ? mask : void 0
7328
7779
  };
7329
7780
  if (localTracePii === true) {
7330
7781
  requestLocalTracePiiRedaction(piiRedaction2.apiUrl, piiRedaction2.writeKey);
@@ -7361,7 +7812,8 @@ var tracing = (analytics, apiUrl, writeKey, options, isDebug = false) => {
7361
7812
  flushTimeoutMs,
7362
7813
  redactTracePii: localTracePii,
7363
7814
  remotePiiConfig,
7364
- spanPiiFields
7815
+ spanPiiFields,
7816
+ mask: piiRedaction2.mask
7365
7817
  }) : void 0;
7366
7818
  let traceloopInitialized = false;
7367
7819
  let claimedPipeline = false;
@@ -7904,6 +8356,7 @@ export {
7904
8356
  localDebuggerEnabled,
7905
8357
  normalizeProjectId,
7906
8358
  projectIdHeaders,
8359
+ maskPayload,
7907
8360
  PiiFieldRedactor,
7908
8361
  piiRedactionNow,
7909
8362
  piiRedaction,