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.
package/dist/index.js CHANGED
@@ -1770,7 +1770,7 @@ function evalScopeAttributes() {
1770
1770
  return { [EVAL_CORRELATION_ID_ATTRIBUTE]: scope.correlationId };
1771
1771
  }
1772
1772
 
1773
- // ../core/dist/chunk-R5EQZAA5.js
1773
+ // ../core/dist/chunk-5OUEKTIO.js
1774
1774
  var require_NameRedactor = __commonJS({
1775
1775
  "../redact-pii/dist/built-ins/NameRedactor.js"(exports2) {
1776
1776
  Object.defineProperty(exports2, "__esModule", { value: true });
@@ -1864,7 +1864,37 @@ var require_SimpleRegexpRedactor = __commonJS({
1864
1864
  this.replaceWith = replaceWith;
1865
1865
  this.regexpMatcher = regexpMatcher;
1866
1866
  }
1867
- redact(textToRedact) {
1867
+ redact(textToRedact, observe) {
1868
+ if (observe) {
1869
+ observe(0, 0, "");
1870
+ let out = "";
1871
+ let end = 0;
1872
+ const matcher = new RegExp(this.regexpMatcher.source, this.regexpMatcher.flags);
1873
+ let match;
1874
+ while ((match = matcher.exec(textToRedact)) !== null) {
1875
+ out += textToRedact.slice(end, match.index);
1876
+ const captured = match;
1877
+ const replacement = this.replaceWith.replace(/\$(\$|&|`|'|[1-9][0-9]?)/g, (token, key) => {
1878
+ if (key === "$")
1879
+ return "$";
1880
+ if (key === "&")
1881
+ return captured[0];
1882
+ if (key === "`")
1883
+ return textToRedact.slice(0, captured.index);
1884
+ if (key === "'")
1885
+ return textToRedact.slice(captured.index + captured[0].length);
1886
+ return Number(key) < captured.length ? captured[Number(key)] || "" : token;
1887
+ });
1888
+ observe(out.length, match[0].length, replacement);
1889
+ out += replacement;
1890
+ end = match.index + match[0].length;
1891
+ if (!matcher.global)
1892
+ break;
1893
+ if (match[0].length === 0)
1894
+ matcher.lastIndex += 1;
1895
+ }
1896
+ return out + textToRedact.slice(end);
1897
+ }
1868
1898
  return textToRedact.replace(this.regexpMatcher, this.replaceWith);
1869
1899
  }
1870
1900
  };
@@ -1970,9 +2000,9 @@ var require_SyncCompositeRedactor = __commonJS({
1970
2000
  var SyncCompositeRedactor = class {
1971
2001
  constructor(opts) {
1972
2002
  this.childRedactors = [];
1973
- this.redact = (textToRedact) => {
2003
+ this.redact = (textToRedact, observe) => {
1974
2004
  for (const redactor2 of this.childRedactors) {
1975
- textToRedact = redactor2.redact(textToRedact);
2005
+ textToRedact = redactor2.redact(textToRedact, observe);
1976
2006
  }
1977
2007
  return textToRedact;
1978
2008
  };
@@ -3492,8 +3522,62 @@ function normalizeProjectId(raw, opts) {
3492
3522
  function projectIdHeaders(projectId) {
3493
3523
  return projectId ? { [PROJECT_ID_HEADER]: projectId } : {};
3494
3524
  }
3525
+ var PII_MARKERS = /<REDACTED (?:CREDENTIALS|CREDIT CARD NUMBER|EMAIL|SECRET|PHONE NUMBER|ADDRESS|SOCIAL SECURITY NUMBER|DATE OF BIRTH|MEDICAL RECORD NUMBER)>/g;
3526
+ function replacePiiMatches(text, pattern, replace, observe, preservePrefix = true) {
3527
+ observe == null ? void 0 : observe(0, 0, "");
3528
+ let out = "";
3529
+ let end = 0;
3530
+ for (const match of text.matchAll(pattern)) {
3531
+ out += text.slice(end, match.index);
3532
+ const replacement = replace(match);
3533
+ if (replacement !== match[0]) {
3534
+ let prefix = 0;
3535
+ if (preservePrefix) {
3536
+ while (prefix < match[0].length && prefix < replacement.length && match[0][prefix] === replacement[prefix]) prefix++;
3537
+ }
3538
+ observe == null ? void 0 : observe(out.length + prefix, match[0].length - prefix, replacement.slice(prefix));
3539
+ }
3540
+ out += replacement;
3541
+ end = match.index + match[0].length;
3542
+ }
3543
+ return out + text.slice(end);
3544
+ }
3545
+ function redactWithinOriginalLimit(text, maxChars, redact) {
3546
+ let cutoff = Math.min(text.length, maxChars);
3547
+ const redacted = redact(text.slice(0, maxChars + 256), (start, length, replacement) => {
3548
+ if (start >= cutoff) return;
3549
+ cutoff = start + length >= cutoff ? start + replacement.length : cutoff + replacement.length - length;
3550
+ });
3551
+ let prefix = redacted.slice(0, cutoff);
3552
+ if (text.length <= maxChars && prefix.length <= maxChars) return prefix;
3553
+ if (maxChars < TRUNCATION_MARKER.length) return "";
3554
+ const budget = Math.max(0, maxChars - TRUNCATION_MARKER.length);
3555
+ let end = Math.min(prefix.length, budget);
3556
+ for (const marker of prefix.matchAll(PII_MARKERS)) {
3557
+ if (marker.index < end && marker.index + marker[0].length > end) end = marker.index;
3558
+ }
3559
+ prefix = prefix.slice(0, end);
3560
+ return prefix + TRUNCATION_MARKER;
3561
+ }
3562
+ var day = "(?:0?[1-9]|[12][0-9]|3[01])";
3563
+ var month = "(?:0?[1-9]|1[0-2])";
3564
+ var year = "(?:18|19|20)[0-9]{2}";
3565
+ 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)?)";
3566
+ var date = `(?:${month}/${day}/${year}|${day}-${month}-${year}|${year}-${month}-${day}|${monthName} ${day},? ${year}|${day} ${monthName} ${year})`;
3567
+ var birthDate = new RegExp(
3568
+ `(\\b(?:d\\.?o\\.?b\\.?|date[ _]?of[ _]?birth|born|birthday)[\\t :="']{0,8}(?:on[ ]{1,3})?)${date}(?![\\p{L}\\p{N}_]|T[0-9])`,
3569
+ "giu"
3570
+ );
3571
+ var mrn = /\b((?:MRN|medical record(?: number)?)["']?[\t :#=]{1,8}["']?)([a-z0-9][a-z0-9-]{2,39})\b/gi;
3572
+ var contextualPiiRedactor = {
3573
+ redact(text, observe) {
3574
+ text = replacePiiMatches(text, birthDate, (m) => `${m[1]}<REDACTED DATE OF BIRTH>`, observe);
3575
+ return replacePiiMatches(text, mrn, (m) => /[0-9]/.test(m[2]) ? `${m[1]}<REDACTED MEDICAL RECORD NUMBER>` : m[0], observe);
3576
+ }
3577
+ };
3495
3578
  var import_redact_pii = __toESM2(require_dist(), 1);
3496
3579
  var DEFAULT_PII_REDACTION_OPTIONS = {
3580
+ customRedactors: { after: [contextualPiiRedactor] },
3497
3581
  builtInRedactors: {
3498
3582
  credentials: { replaceWith: "<REDACTED CREDENTIALS>" },
3499
3583
  creditCardNumber: { replaceWith: "<REDACTED CREDIT CARD NUMBER>" },
@@ -3513,9 +3597,522 @@ var DEFAULT_PII_REDACTION_OPTIONS = {
3513
3597
  }
3514
3598
  };
3515
3599
  var redactor;
3516
- function redactPiiText(text) {
3600
+ function redactPiiText(text, observe) {
3517
3601
  redactor != null ? redactor : redactor = new import_redact_pii.SyncRedactor(DEFAULT_PII_REDACTION_OPTIONS);
3518
- return redactor.redact(text);
3602
+ let out = "";
3603
+ let start = 0;
3604
+ for (const marker of text.matchAll(PII_MARKERS)) {
3605
+ const offset2 = out.length;
3606
+ out += redactor.redact(text.slice(start, marker.index), observe && ((at, length, replacement) => observe(offset2 + at, length, replacement))) + marker[0];
3607
+ start = marker.index + marker[0].length;
3608
+ }
3609
+ const offset = out.length;
3610
+ return out + redactor.redact(text.slice(start), observe && ((at, length, replacement) => observe(offset + at, length, replacement)));
3611
+ }
3612
+ 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)$/;
3613
+ var CONTENT_KEYS = /* @__PURE__ */ new Set([
3614
+ "ai.prompt.system",
3615
+ "ai.subagent.result",
3616
+ "agent.session.title",
3617
+ // Failed tool calls carry the tool's output in their error text.
3618
+ "error.message",
3619
+ "exception.message",
3620
+ "exception.stacktrace"
3621
+ ]);
3622
+ var NON_CONTENT_PREFIXES = [
3623
+ "traceloop.association.properties.",
3624
+ "ai.telemetry.metadata.",
3625
+ "ai.settings.context.",
3626
+ "raindrop.app."
3627
+ ];
3628
+ var ASSOCIATION_PROPERTY = /^(?:ai\.telemetry\.metadata\.)?traceloop\.association\.properties\.(.+)$/;
3629
+ var SDK_ASSOCIATION_PROPERTIES = /* @__PURE__ */ new Set([
3630
+ "user_id",
3631
+ "event_id",
3632
+ "convo_id",
3633
+ "event_name"
3634
+ ]);
3635
+ function isEventPropertyCopy(key) {
3636
+ var _a;
3637
+ if (key === "ai.telemetry.metadata.raindrop.properties") return true;
3638
+ const name = (_a = ASSOCIATION_PROPERTY.exec(key)) == null ? void 0 : _a[1];
3639
+ return name !== void 0 && !SDK_ASSOCIATION_PROPERTIES.has(name) && !name.startsWith("raindrop.");
3640
+ }
3641
+ var JSON_SIMPLE_ESCAPES = {
3642
+ '"': '"',
3643
+ "\\": "\\",
3644
+ "/": "/",
3645
+ b: "\b",
3646
+ f: "\f",
3647
+ n: "\n",
3648
+ r: "\r",
3649
+ t: " "
3650
+ };
3651
+ function decodeJsonEscapes(text, observe) {
3652
+ if (!text.includes("\\")) return text;
3653
+ let out = "";
3654
+ for (let i = 0; i < text.length; i++) {
3655
+ const ch = text[i];
3656
+ if (ch !== "\\" || i + 1 >= text.length) {
3657
+ out += ch;
3658
+ continue;
3659
+ }
3660
+ const next = text[i + 1];
3661
+ const simple = JSON_SIMPLE_ESCAPES[next];
3662
+ if (simple !== void 0) {
3663
+ observe == null ? void 0 : observe(out.length, 2, simple);
3664
+ out += simple;
3665
+ i += 1;
3666
+ } else if (next === "u" && /^[0-9a-fA-F]{4}$/.test(text.slice(i + 2, i + 6))) {
3667
+ observe == null ? void 0 : observe(out.length, 6, String.fromCharCode(Number.parseInt(text.slice(i + 2, i + 6), 16)));
3668
+ out += String.fromCharCode(Number.parseInt(text.slice(i + 2, i + 6), 16));
3669
+ i += 5;
3670
+ } else {
3671
+ out += ch;
3672
+ }
3673
+ }
3674
+ return out;
3675
+ }
3676
+ function jsonStringBody(value, observe) {
3677
+ if (!observe) return JSON.stringify(value).slice(1, -1);
3678
+ return replacePiiMatches(
3679
+ value,
3680
+ /[\u0000-\u001f"\\]|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g,
3681
+ (m) => JSON.stringify(m[0]).slice(1, -1),
3682
+ observe,
3683
+ false
3684
+ );
3685
+ }
3686
+ function redactEncodedBody(raw, cue, observe) {
3687
+ const decoded = decodeJsonEscapes(raw);
3688
+ const edits = [];
3689
+ const redacted = redactCuedValue(decoded, cue, observe && ((...edit) => edits.push(edit)));
3690
+ if (redacted === decoded) return raw;
3691
+ decodeJsonEscapes(raw, observe);
3692
+ for (const edit of edits) observe == null ? void 0 : observe(...edit);
3693
+ return jsonStringBody(redacted, observe);
3694
+ }
3695
+ function redactStringToken(token, cue, observe) {
3696
+ const body = redactEncodedBody(token.slice(1, -1), cue, observe && ((at, length, replacement) => observe(at + 1, length, replacement)));
3697
+ return `"${body}"`;
3698
+ }
3699
+ function contextualCue(key) {
3700
+ switch (key.trim().toLowerCase().replace(/[\s_.\-]/g, "")) {
3701
+ case "dob":
3702
+ case "dateofbirth":
3703
+ case "birthday":
3704
+ case "born":
3705
+ return "DOB: ";
3706
+ case "mrn":
3707
+ case "medicalrecord":
3708
+ case "medicalrecordnumber":
3709
+ return "MRN: ";
3710
+ default:
3711
+ return void 0;
3712
+ }
3713
+ }
3714
+ function redactCuedValue(value, cue, observe) {
3715
+ const redacted = redactPiiText(value, observe);
3716
+ return cue === void 0 ? redacted : contextualPiiRedactor.redact(cue + redacted, observe && ((at, length, replacement) => {
3717
+ if (length === 0 && replacement === "") {
3718
+ observe(0, 0, "");
3719
+ return;
3720
+ }
3721
+ const prefix = Math.max(0, cue.length - at);
3722
+ observe(Math.max(0, at - cue.length), length - prefix, replacement.slice(prefix));
3723
+ })).slice(cue.length);
3724
+ }
3725
+ function redactLooseJsonText(text, observe) {
3726
+ var _a;
3727
+ if (text.startsWith('"')) {
3728
+ return `"${redactEncodedBody(text.slice(1), void 0, observe && ((at, length, replacement) => observe(at + 1, length, replacement)))}`;
3729
+ }
3730
+ if (!text.includes("\\")) return redactPiiText(text, observe);
3731
+ let pieces = (_a = text.match(/\\u[0-9a-fA-F]{4}|\\["\\/bfnrt]|[\s\S]/g)) != null ? _a : [];
3732
+ const decoded = pieces.map((piece) => decodeJsonEscapes(piece)).join("");
3733
+ let next = [];
3734
+ let read = 0;
3735
+ let delta = 0;
3736
+ let written = 0;
3737
+ const copyTo = (end) => {
3738
+ while (read < end) {
3739
+ const piece = pieces[read++];
3740
+ next.push(piece);
3741
+ written += piece.length;
3742
+ }
3743
+ };
3744
+ const finishPass = () => {
3745
+ copyTo(pieces.length);
3746
+ pieces = next;
3747
+ next = [];
3748
+ read = 0;
3749
+ delta = 0;
3750
+ written = 0;
3751
+ };
3752
+ redactPiiText(decoded, (start, length, replacement) => {
3753
+ if (length === 0 && replacement === "") {
3754
+ finishPass();
3755
+ return;
3756
+ }
3757
+ const at = start - delta;
3758
+ copyTo(at);
3759
+ let rawLength = 0;
3760
+ for (let index = at; index < at + length; index++) rawLength += pieces[index].length;
3761
+ observe == null ? void 0 : observe(written, rawLength, replacement);
3762
+ for (let index = 0; index < replacement.length; index++) next.push(replacement[index]);
3763
+ written += replacement.length;
3764
+ read = at + length;
3765
+ delta += replacement.length - length;
3766
+ });
3767
+ finishPass();
3768
+ return pieces.join("");
3769
+ }
3770
+ function stringTokenEnd(text, start) {
3771
+ for (let i = start + 1; i < text.length; i++) {
3772
+ const ch = text[i];
3773
+ if (ch === "\\") i += 1;
3774
+ else if (ch === '"') return i + 1;
3775
+ }
3776
+ return -1;
3777
+ }
3778
+ function redactJsonLike(text, complete, observe) {
3779
+ var _a, _b;
3780
+ let out = "";
3781
+ let looseStart = 0;
3782
+ const flushLoose = (end) => {
3783
+ if (end > looseStart) {
3784
+ const loose = text.slice(looseStart, end);
3785
+ const offset = out.length;
3786
+ out += complete ? loose : redactLooseJsonText(loose, observe && ((at, length, replacement) => observe(offset + at, length, replacement)));
3787
+ }
3788
+ };
3789
+ let i = text.indexOf('"');
3790
+ while (i !== -1) {
3791
+ const end = stringTokenEnd(text, i);
3792
+ if (end === -1) break;
3793
+ flushLoose(i);
3794
+ let after = end;
3795
+ while (after < text.length && /\s/.test(text[after])) after += 1;
3796
+ const token = text.slice(i, end);
3797
+ if (text[after] === ":") {
3798
+ const cue = contextualCue(decodeJsonEscapes(token.slice(1, -1)));
3799
+ if (cue !== void 0) {
3800
+ let start = after + 1;
3801
+ while (/\s/.test((_a = text[start]) != null ? _a : "")) start += 1;
3802
+ let valueEnd = start;
3803
+ let replacement;
3804
+ const offset2 = out.length + start - i;
3805
+ const valueObserver = observe && ((at, length, replacement2) => observe(offset2 + at, length, replacement2));
3806
+ if (text[start] === '"') {
3807
+ valueEnd = stringTokenEnd(text, start);
3808
+ if (valueEnd === -1) {
3809
+ valueEnd = text.length;
3810
+ replacement = `"${redactEncodedBody(text.slice(start + 1), cue, valueObserver && ((at, length, replacement2) => valueObserver(at + 1, length, replacement2)))}`;
3811
+ } else {
3812
+ replacement = redactStringToken(text.slice(start, valueEnd), cue, valueObserver);
3813
+ }
3814
+ } else if (/[-0-9]/.test((_b = text[start]) != null ? _b : "")) {
3815
+ while (valueEnd < text.length && !/[\s,}\]]/.test(text[valueEnd])) valueEnd += 1;
3816
+ const value = text.slice(start, valueEnd);
3817
+ const redacted = redactCuedValue(value, cue);
3818
+ if (redacted !== value) {
3819
+ replacement = JSON.stringify(redacted);
3820
+ valueObserver == null ? void 0 : valueObserver(0, value.length, replacement);
3821
+ }
3822
+ }
3823
+ if (replacement !== void 0) {
3824
+ out += text.slice(i, start) + replacement;
3825
+ looseStart = valueEnd;
3826
+ i = text.indexOf('"', valueEnd);
3827
+ continue;
3828
+ }
3829
+ }
3830
+ }
3831
+ const offset = out.length;
3832
+ out += complete && text[after] === ":" ? token : redactStringToken(token, void 0, observe && ((at, length, replacement) => observe(offset + at, length, replacement)));
3833
+ looseStart = end;
3834
+ i = text.indexOf('"', end);
3835
+ }
3836
+ if (i === -1) {
3837
+ flushLoose(text.length);
3838
+ } else {
3839
+ flushLoose(i);
3840
+ looseStart = i;
3841
+ flushLoose(text.length);
3842
+ }
3843
+ return out;
3844
+ }
3845
+ function redactSpanContent(text, observe) {
3846
+ const head = text.trimStart()[0];
3847
+ if (head !== "{" && head !== "[" && head !== '"') return redactPiiText(text, observe);
3848
+ let complete = true;
3849
+ try {
3850
+ JSON.parse(text);
3851
+ } catch (e) {
3852
+ complete = false;
3853
+ }
3854
+ return redactJsonLike(text, complete, observe);
3855
+ }
3856
+ function isCompleteJsonContainer(text) {
3857
+ const head = text.trimStart()[0];
3858
+ if (head !== "{" && head !== "[") return false;
3859
+ try {
3860
+ JSON.parse(text);
3861
+ return true;
3862
+ } catch (e) {
3863
+ return false;
3864
+ }
3865
+ }
3866
+ function redactJsonEventContent(text, observe) {
3867
+ if (!/^\s*(?:\{\s*"|\[\s*["{\[])/.test(text) && !isCompleteJsonContainer(text)) return text;
3868
+ return redactSpanContent(text, observe);
3869
+ }
3870
+ var NO_SPAN_PII_FIELDS = { exact: /* @__PURE__ */ new Set(), prefixes: [] };
3871
+ function compileSpanPiiFields(names, logPrefix = "[raindrop-ai/core]") {
3872
+ if (!Array.isArray(names) || names.length === 0) return NO_SPAN_PII_FIELDS;
3873
+ const exact = /* @__PURE__ */ new Set();
3874
+ const prefixes = [];
3875
+ for (const name of names) {
3876
+ const valid = typeof name === "string" && !/\s/.test(name) && /^[^*]+\*?$/.test(name);
3877
+ if (!valid) {
3878
+ rateLimitedLog(
3879
+ `${logPrefix}.pii_span_field_invalid`,
3880
+ () => console.warn(
3881
+ `${logPrefix} redactPiiFields: ignoring invalid span attribute ${JSON.stringify(name)}`
3882
+ )
3883
+ );
3884
+ continue;
3885
+ }
3886
+ if (name.endsWith("*")) prefixes.push(name.slice(0, -1));
3887
+ else exact.add(name);
3888
+ }
3889
+ return { exact, prefixes };
3890
+ }
3891
+ function isCallerSelected(key, fields) {
3892
+ return fields.exact.has(key) || fields.prefixes.some((prefix) => key.startsWith(prefix));
3893
+ }
3894
+ function isSpanContentAttributeKey(key, fields = NO_SPAN_PII_FIELDS) {
3895
+ if (isCallerSelected(key, fields) || isEventPropertyCopy(key)) return true;
3896
+ if (NON_CONTENT_PREFIXES.some((prefix) => key.startsWith(prefix))) return false;
3897
+ return CONTENT_KEYS.has(key) || CONTENT_KEY_SUFFIX.test(key);
3898
+ }
3899
+ function redactBoundedContent(text, maxChars) {
3900
+ if (maxChars === void 0) return redactSpanContent(text);
3901
+ return redactWithinOriginalLimit(text, maxChars, redactSpanContent);
3902
+ }
3903
+ function redactOtlpValue(value, maxChars) {
3904
+ var _a;
3905
+ if (typeof value.stringValue === "string") {
3906
+ const redacted = redactBoundedContent(value.stringValue, maxChars);
3907
+ return redacted === value.stringValue ? value : { ...value, stringValue: redacted };
3908
+ }
3909
+ const values = (_a = value.arrayValue) == null ? void 0 : _a.values;
3910
+ if (!values) return value;
3911
+ let changed = false;
3912
+ const next = values.map((item) => {
3913
+ const redacted = redactOtlpValue(item, maxChars);
3914
+ if (redacted !== item) changed = true;
3915
+ return redacted;
3916
+ });
3917
+ return changed ? { ...value, arrayValue: { values: next } } : value;
3918
+ }
3919
+ function redactPiiInOtlpAttributes(attributes, fields = NO_SPAN_PII_FIELDS, maxChars) {
3920
+ let next;
3921
+ for (let i = 0; i < attributes.length; i++) {
3922
+ const attr = attributes[i];
3923
+ if (!attr.value || !isSpanContentAttributeKey(attr.key, fields)) continue;
3924
+ const value = redactOtlpValue(attr.value, maxChars);
3925
+ if (value === attr.value) continue;
3926
+ next != null ? next : next = attributes.slice();
3927
+ next[i] = { ...attr, value };
3928
+ }
3929
+ return next != null ? next : attributes;
3930
+ }
3931
+ function redactPiiInOtlpSpan(span, fields = NO_SPAN_PII_FIELDS, maxChars) {
3932
+ var _a;
3933
+ const attributes = span.attributes && redactPiiInOtlpAttributes(span.attributes, fields, maxChars);
3934
+ const message = (_a = span.status) == null ? void 0 : _a.message;
3935
+ const redactedMessage = message === void 0 ? void 0 : redactBoundedContent(message, maxChars);
3936
+ if (attributes === span.attributes && redactedMessage === message) return span;
3937
+ const status = span.status && redactedMessage !== message ? { ...span.status, message: redactedMessage } : span.status;
3938
+ return { ...span, attributes, status };
3939
+ }
3940
+ function redactPiiInAttributeMap(attributes, fields = NO_SPAN_PII_FIELDS) {
3941
+ let next;
3942
+ for (const [key, value] of Object.entries(attributes)) {
3943
+ if (!isSpanContentAttributeKey(key, fields)) continue;
3944
+ let redacted = value;
3945
+ if (typeof value === "string") {
3946
+ redacted = redactSpanContent(value);
3947
+ } else if (Array.isArray(value)) {
3948
+ let changed = false;
3949
+ const items = value.map((item) => {
3950
+ if (typeof item !== "string") return item;
3951
+ const out = redactSpanContent(item);
3952
+ if (out !== item) changed = true;
3953
+ return out;
3954
+ });
3955
+ if (changed) redacted = items;
3956
+ }
3957
+ if (redacted === value) continue;
3958
+ next != null ? next : next = { ...attributes };
3959
+ next[key] = redacted;
3960
+ }
3961
+ return next;
3962
+ }
3963
+ var MASK_FAILED = "<MASK FAILED>";
3964
+ var EVENT_FIELDS = {
3965
+ event: [["ai_data", "input"], ["ai_data", "output"], ["properties"], ["attachments"]],
3966
+ signal: [["properties"]],
3967
+ identify: [["traits"]]
3968
+ };
3969
+ var SDK_PROPERTY_KEYS = ["$context"];
3970
+ function isPlainObject(value) {
3971
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
3972
+ const proto = Object.getPrototypeOf(value);
3973
+ return proto === Object.prototype || proto === null;
3974
+ }
3975
+ function isThenable(value) {
3976
+ return typeof value === "object" && value !== null && "then" in value && typeof value.then === "function";
3977
+ }
3978
+ function warn(prefix, context8, reason) {
3979
+ rateLimitedLog(
3980
+ `${prefix}.mask_failed`,
3981
+ () => console.warn(
3982
+ `${prefix} mask function failed on ${context8.kind} ${context8.field} (${reason}); sending ${MASK_FAILED} in its place.`
3983
+ )
3984
+ );
3985
+ }
3986
+ function jsonCopy(value) {
3987
+ const json = JSON.stringify(value);
3988
+ if (json === void 0) throw new TypeError("not JSON-serializable");
3989
+ return JSON.parse(json);
3990
+ }
3991
+ function failed(shape) {
3992
+ if (shape === "string") return MASK_FAILED;
3993
+ if (shape === "object") return { error: MASK_FAILED };
3994
+ return [];
3995
+ }
3996
+ function maskValue(value, context8, mask, prefix) {
3997
+ const shape = typeof value === "string" ? "string" : Array.isArray(value) ? "array" : "object";
3998
+ try {
3999
+ const result = mask(shape === "string" ? value : jsonCopy(value), context8);
4000
+ if (isThenable(result)) {
4001
+ Promise.resolve(result).catch(() => {
4002
+ });
4003
+ warn(prefix, context8, "it returned a promise; mask must be synchronous");
4004
+ return failed(shape);
4005
+ }
4006
+ if (shape === "string") {
4007
+ if (typeof result === "string") return result;
4008
+ } else {
4009
+ const copy = jsonCopy(result);
4010
+ if (shape === "array" ? Array.isArray(copy) : isPlainObject(copy)) return copy;
4011
+ }
4012
+ warn(prefix, context8, `it returned a value that is not ${shape === "string" ? "a string" : `an ${shape}`}`);
4013
+ } catch (err) {
4014
+ warn(prefix, context8, err instanceof Error ? err.name : "threw");
4015
+ }
4016
+ return failed(shape);
4017
+ }
4018
+ function maskAt(node, path, context8, mask, prefix) {
4019
+ const [head, ...rest] = path;
4020
+ if (head === void 0 || !Object.prototype.hasOwnProperty.call(node, head)) return node;
4021
+ const child = node[head];
4022
+ if (rest.length > 0) {
4023
+ if (!isPlainObject(child)) return node;
4024
+ const next = maskAt(child, rest, context8, mask, prefix);
4025
+ return next === child ? node : { ...node, [head]: next };
4026
+ }
4027
+ if (child === void 0 || child === null) return node;
4028
+ if (typeof child !== "string" && typeof child !== "object") return node;
4029
+ if (context8.kind !== "event" || head !== "properties" || !isPlainObject(child)) {
4030
+ return { ...node, [head]: maskValue(child, context8, mask, prefix) };
4031
+ }
4032
+ const own2 = {};
4033
+ const sdk = {};
4034
+ for (const [key, value] of Object.entries(child)) {
4035
+ (SDK_PROPERTY_KEYS.includes(key) ? sdk : own2)[key] = value;
4036
+ }
4037
+ const masked = maskValue(own2, context8, mask, prefix);
4038
+ return { ...node, [head]: isPlainObject(masked) ? { ...masked, ...sdk } : sdk };
4039
+ }
4040
+ function maskPayload(kind, payload, mask, logPrefix = "[raindrop-ai/core]") {
4041
+ if (!mask) return payload;
4042
+ let out = payload;
4043
+ for (const path of EVENT_FIELDS[kind]) {
4044
+ out = maskAt(out, path, { kind, field: path.join(".") }, mask, logPrefix);
4045
+ }
4046
+ return out;
4047
+ }
4048
+ function maskOtlpValue(value, context8, mask, prefix) {
4049
+ var _a;
4050
+ if (typeof value.stringValue === "string") {
4051
+ const masked = maskValue(value.stringValue, context8, mask, prefix);
4052
+ return typeof masked === "string" && masked !== value.stringValue ? { ...value, stringValue: masked } : value;
4053
+ }
4054
+ const values = (_a = value.arrayValue) == null ? void 0 : _a.values;
4055
+ if (!values) return value;
4056
+ let changed = false;
4057
+ const next = values.map((item) => {
4058
+ const masked = maskOtlpValue(item, context8, mask, prefix);
4059
+ if (masked !== item) changed = true;
4060
+ return masked;
4061
+ });
4062
+ return changed ? { ...value, arrayValue: { values: next } } : value;
4063
+ }
4064
+ function maskSpanStatusMessage(message, mask, logPrefix = "[raindrop-ai/core]") {
4065
+ if (!mask) return message;
4066
+ const masked = maskValue(message, { kind: "span", field: "status.message" }, mask, logPrefix);
4067
+ return typeof masked === "string" ? masked : MASK_FAILED;
4068
+ }
4069
+ function maskOtlpAttributes(attributes, mask, fields, logPrefix = "[raindrop-ai/core]") {
4070
+ if (!mask) return attributes;
4071
+ let next;
4072
+ for (let i = 0; i < attributes.length; i++) {
4073
+ const attr = attributes[i];
4074
+ if (!attr.value || !isSpanContentAttributeKey(attr.key, fields)) continue;
4075
+ const value = maskOtlpValue(attr.value, { kind: "span", field: attr.key }, mask, logPrefix);
4076
+ if (value === attr.value) continue;
4077
+ next != null ? next : next = attributes.slice();
4078
+ next[i] = { ...attr, value };
4079
+ }
4080
+ return next != null ? next : attributes;
4081
+ }
4082
+ function maskOtlpSpan(span, mask, fields, logPrefix = "[raindrop-ai/core]") {
4083
+ var _a;
4084
+ if (!mask) return span;
4085
+ const attributes = span.attributes && maskOtlpAttributes(span.attributes, mask, fields, logPrefix);
4086
+ const message = (_a = span.status) == null ? void 0 : _a.message;
4087
+ const nextMessage = message === void 0 ? void 0 : maskSpanStatusMessage(message, mask, logPrefix);
4088
+ if (attributes === span.attributes && nextMessage === message) return span;
4089
+ const status = span.status && nextMessage !== message ? { ...span.status, message: nextMessage } : span.status;
4090
+ return { ...span, attributes, status };
4091
+ }
4092
+ function maskAttributeMap(attributes, mask, fields, logPrefix = "[raindrop-ai/core]") {
4093
+ if (!mask) return void 0;
4094
+ let next;
4095
+ for (const [key, value] of Object.entries(attributes)) {
4096
+ if (!isSpanContentAttributeKey(key, fields)) continue;
4097
+ const context8 = { kind: "span", field: key };
4098
+ let masked = value;
4099
+ if (typeof value === "string") {
4100
+ masked = maskValue(value, context8, mask, logPrefix);
4101
+ } else if (Array.isArray(value)) {
4102
+ let changed = false;
4103
+ const items = value.map((item) => {
4104
+ if (typeof item !== "string") return item;
4105
+ const out = maskValue(item, context8, mask, logPrefix);
4106
+ if (out !== item) changed = true;
4107
+ return out;
4108
+ });
4109
+ if (changed) masked = items;
4110
+ }
4111
+ if (masked === value) continue;
4112
+ next != null ? next : next = { ...attributes };
4113
+ next[key] = masked;
4114
+ }
4115
+ return next;
3519
4116
  }
3520
4117
  var KINDS = ["event", "signal", "identify"];
3521
4118
  var DEFAULT_PII_FIELDS = {
@@ -3611,7 +4208,7 @@ function mergePiiFieldMaps(...maps) {
3611
4208
  }
3612
4209
  return out;
3613
4210
  }
3614
- function isPlainObject(value) {
4211
+ function isPlainObject2(value) {
3615
4212
  if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
3616
4213
  const proto = Object.getPrototypeOf(value);
3617
4214
  return proto === Object.prototype || proto === null;
@@ -3619,30 +4216,35 @@ function isPlainObject(value) {
3619
4216
  function isProtected(location) {
3620
4217
  return PROTECTED_LOCATIONS.has(JSON.stringify(location));
3621
4218
  }
3622
- function redactAll(value, location) {
4219
+ function redactAll(value, location, maxChars) {
3623
4220
  if (location !== null && isProtected(location)) return value;
3624
- if (typeof value === "string") return redactPiiText(value);
3625
- if (Array.isArray(value)) return value.map((item) => redactAll(item, null));
3626
- if (isPlainObject(value)) {
4221
+ if (typeof value === "string") {
4222
+ if (maxChars !== void 0 && (location == null ? void 0 : location.length) === 2 && location[0] === "ai_data" && (location[1] === "input" || location[1] === "output")) {
4223
+ return redactWithinOriginalLimit(value, maxChars, (text, observe) => redactPiiText(redactJsonEventContent(text, observe), observe));
4224
+ }
4225
+ return redactPiiText(redactJsonEventContent(value));
4226
+ }
4227
+ if (Array.isArray(value)) return value.map((item) => redactAll(item, null, maxChars));
4228
+ if (isPlainObject2(value)) {
3627
4229
  const out = {};
3628
4230
  for (const [key, child] of Object.entries(value)) {
3629
- out[key] = redactAll(child, location === null ? null : [...location, key]);
4231
+ out[key] = redactAll(child, location === null ? null : [...location, key], maxChars);
3630
4232
  }
3631
4233
  return out;
3632
4234
  }
3633
4235
  return value;
3634
4236
  }
3635
- function applyPath(value, segments, location) {
3636
- if (segments.length === 0) return redactAll(value, location);
4237
+ function applyPath(value, segments, location, maxChars) {
4238
+ if (segments.length === 0) return redactAll(value, location, maxChars);
3637
4239
  const [head, ...rest] = segments;
3638
4240
  if (head.kind === "key" || head.kind === "any_key") {
3639
- if (!isPlainObject(value)) return value;
4241
+ if (!isPlainObject2(value)) return value;
3640
4242
  const keys = head.kind === "key" ? [head.key] : Object.keys(value);
3641
4243
  let out2;
3642
4244
  for (const key of keys) {
3643
4245
  if (!Object.prototype.hasOwnProperty.call(value, key)) continue;
3644
4246
  const child = value[key];
3645
- const next = applyPath(child, rest, location === null ? null : [...location, key]);
4247
+ const next = applyPath(child, rest, location === null ? null : [...location, key], maxChars);
3646
4248
  if (next !== child) {
3647
4249
  out2 != null ? out2 : out2 = { ...value };
3648
4250
  out2[key] = next;
@@ -3655,7 +4257,7 @@ function applyPath(value, segments, location) {
3655
4257
  let out;
3656
4258
  for (const index of indices) {
3657
4259
  const child = value[index];
3658
- const next = applyPath(child, rest, null);
4260
+ const next = applyPath(child, rest, null, maxChars);
3659
4261
  if (next !== child) {
3660
4262
  out != null ? out : out = [...value];
3661
4263
  out[index] = next;
@@ -3705,9 +4307,9 @@ var PiiFieldRedactor = class {
3705
4307
  return out;
3706
4308
  }
3707
4309
  /** The payload with every selected field redacted (a copy where changed). */
3708
- redact(kind, payload) {
4310
+ redact(kind, payload, maxChars) {
3709
4311
  let out = payload;
3710
- for (const segments of this.compile()[kind]) out = applyPath(out, segments, []);
4312
+ for (const segments of this.compile()[kind]) out = applyPath(out, segments, [], maxChars);
3711
4313
  return out;
3712
4314
  }
3713
4315
  };
@@ -3888,13 +4490,13 @@ function earliestIsoTimestamp(...values) {
3888
4490
  let earliest;
3889
4491
  for (const value of values) {
3890
4492
  if (value === void 0) continue;
3891
- const date = new Date(value);
3892
- if (Number.isNaN(date.getTime())) continue;
3893
- if (earliest === void 0 || date < earliest) earliest = date;
4493
+ const date2 = new Date(value);
4494
+ if (Number.isNaN(date2.getTime())) continue;
4495
+ if (earliest === void 0 || date2 < earliest) earliest = date2;
3894
4496
  }
3895
4497
  return earliest == null ? void 0 : earliest.toISOString();
3896
4498
  }
3897
- function isPlainObject2(value) {
4499
+ function isPlainObject3(value) {
3898
4500
  if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
3899
4501
  const proto = Object.getPrototypeOf(value);
3900
4502
  return proto === Object.prototype || proto === null;
@@ -3905,7 +4507,7 @@ function deepMergeProperties(target, source) {
3905
4507
  for (const [key, value] of Object.entries(source)) {
3906
4508
  if (value === void 0 || UNSAFE_MERGE_KEYS.has(key)) continue;
3907
4509
  const existing = out[key];
3908
- out[key] = isPlainObject2(existing) && isPlainObject2(value) ? deepMergeProperties(existing, value) : value;
4510
+ out[key] = isPlainObject3(existing) && isPlainObject3(value) ? deepMergeProperties(existing, value) : value;
3909
4511
  }
3910
4512
  return out;
3911
4513
  }
@@ -4005,6 +4607,7 @@ var EventShipper = class {
4005
4607
  });
4006
4608
  this.redactPii = typeof opts.redactPii === "boolean" ? opts.redactPii : void 0;
4007
4609
  this.remotePiiConfig = opts.remotePiiConfig;
4610
+ this.mask = typeof opts.mask === "function" ? opts.mask : void 0;
4008
4611
  this.piiFields = new PiiFieldRedactor({
4009
4612
  startupFieldMap: opts.redactPiiFields,
4010
4613
  logPrefix: this.prefix
@@ -4165,11 +4768,12 @@ var EventShipper = class {
4165
4768
  return void 0;
4166
4769
  }
4167
4770
  const maxChars = resolveMaxTextFieldChars(this.maxTextFieldCharsOpt);
4168
- if (typeof patch.input === "string" && patch.input.length > maxChars) {
4169
- patch = { ...patch, input: capText(patch.input, maxChars) };
4170
- }
4171
- if (typeof patch.output === "string" && patch.output.length > maxChars) {
4172
- patch = { ...patch, output: capText(patch.output, maxChars) };
4771
+ const mayRedact = this.redactPii === true || this.redactPii !== false && this.remotePiiConfig;
4772
+ for (const field of ["input", "output"]) {
4773
+ const text = patch[field];
4774
+ if (typeof text !== "string" || text.length <= maxChars) continue;
4775
+ const bounded = mayRedact ? text.slice(0, maxChars + 256) : capText(text, maxChars);
4776
+ patch = { ...patch, [field]: bounded };
4173
4777
  }
4174
4778
  if (this.debug) {
4175
4779
  console.log(`${this.prefix} queue patch`, {
@@ -4382,7 +4986,7 @@ var EventShipper = class {
4382
4986
  ];
4383
4987
  const known = piiRedactionNow(this.redactPii, this.remotePiiConfig, this.baseUrl, this.writeKey);
4384
4988
  if (known !== void 0) {
4385
- const body = known ? items.map((item) => this.piiFields.redact("signal", item)) : items;
4989
+ const body = items.map((item) => this.outgoing("signal", item, known));
4386
4990
  if (!this.writeKey) return;
4387
4991
  await this.sendDirect("signal", `${this.baseUrl}signals/track`, body);
4388
4992
  return;
@@ -4390,7 +4994,7 @@ var EventShipper = class {
4390
4994
  const snapshot = items.map(snapshotPayload);
4391
4995
  await this.tracked(async () => {
4392
4996
  const redact = await this.shouldRedactPii();
4393
- const body = redact ? snapshot.map((item) => this.piiFields.redact("signal", item)) : snapshot;
4997
+ const body = snapshot.map((item) => this.outgoing("signal", item, redact));
4394
4998
  if (!this.writeKey) return;
4395
4999
  await this.sendDirect("signal", `${this.baseUrl}signals/track`, body, void 0, false);
4396
5000
  });
@@ -4419,14 +5023,14 @@ var EventShipper = class {
4419
5023
  if (rows.length === 0) return;
4420
5024
  const known = piiRedactionNow(this.redactPii, this.remotePiiConfig, this.baseUrl, this.writeKey);
4421
5025
  if (known !== void 0) {
4422
- const body = known ? rows.map((user) => this.piiFields.redact("identify", user)) : rows;
5026
+ const body = rows.map((user) => this.outgoing("identify", user, known));
4423
5027
  await this.sendDirect("identify", `${this.baseUrl}users/identify`, body);
4424
5028
  return;
4425
5029
  }
4426
5030
  const snapshot = rows.map(snapshotPayload);
4427
5031
  await this.tracked(async () => {
4428
5032
  const redact = await this.shouldRedactPii();
4429
- const body = redact ? snapshot.map((user) => this.piiFields.redact("identify", user)) : snapshot;
5033
+ const body = snapshot.map((user) => this.outgoing("identify", user, redact));
4430
5034
  await this.sendDirect("identify", `${this.baseUrl}users/identify`, body, void 0, false);
4431
5035
  });
4432
5036
  }
@@ -4489,6 +5093,12 @@ var EventShipper = class {
4489
5093
  () => console.warn(`${this.prefix} failed to send ${what} (dropping): ${reason}`)
4490
5094
  );
4491
5095
  }
5096
+ /** A payload as it is sent: built-in redaction when on, then the caller's `mask`. */
5097
+ outgoing(kind, payload, redact) {
5098
+ const maxChars = kind === "event" ? resolveMaxTextFieldChars(this.maxTextFieldCharsOpt) : void 0;
5099
+ const redacted = redact ? this.piiFields.redact(kind, payload, maxChars) : payload;
5100
+ return isPlainObject3(redacted) ? maskPayload(kind, redacted, this.mask, this.prefix) : redacted;
5101
+ }
4492
5102
  /**
4493
5103
  * Whether to redact PII: `redactPii`, or when it is unset and
4494
5104
  * `remotePiiConfig` is on, the org's setting. Waits for the org's answer
@@ -4641,7 +5251,7 @@ var EventShipper = class {
4641
5251
  };
4642
5252
  const known = piiRedactionNow(this.redactPii, this.remotePiiConfig, this.baseUrl, this.writeKey);
4643
5253
  if (known !== void 0) {
4644
- const payload = known ? this.piiFields.redact("event", unredacted) : unredacted;
5254
+ const payload = this.outgoing("event", unredacted, known);
4645
5255
  return this.shipPartial(eventId, accumulated, payload, { eventName, userId, convoId, isPending }, deadlineAt, true);
4646
5256
  }
4647
5257
  const snapshot = snapshotPayload(unredacted);
@@ -4649,7 +5259,7 @@ var EventShipper = class {
4649
5259
  (redact) => this.shipPartial(
4650
5260
  eventId,
4651
5261
  accumulated,
4652
- redact ? this.piiFields.redact("event", snapshot) : snapshot,
5262
+ this.outgoing("event", snapshot, redact),
4653
5263
  { eventName, userId, convoId, isPending },
4654
5264
  deadlineAt,
4655
5265
  false
@@ -4671,6 +5281,20 @@ var EventShipper = class {
4671
5281
  var _a, _b, _c, _d, _e, _f;
4672
5282
  const { eventName, userId, convoId, isPending } = meta;
4673
5283
  const url = `${this.baseUrl}events/track_partial`;
5284
+ if (payload !== null && typeof payload === "object" && "ai_data" in payload) {
5285
+ const data = payload.ai_data;
5286
+ if (data !== null && typeof data === "object") {
5287
+ const maxChars = resolveMaxTextFieldChars(this.maxTextFieldCharsOpt);
5288
+ payload = {
5289
+ ...payload,
5290
+ ai_data: {
5291
+ ...data,
5292
+ input: capText("input" in data ? data.input : void 0, maxChars),
5293
+ output: capText("output" in data ? data.output : void 0, maxChars)
5294
+ }
5295
+ };
5296
+ }
5297
+ }
4674
5298
  if (this.debug) {
4675
5299
  const sent = payload;
4676
5300
  const preview = (v, n) => typeof v === "string" ? v.slice(0, n) : void 0;
@@ -4745,7 +5369,7 @@ function overriddenKeys(derived, caller) {
4745
5369
  for (const [key, value] of Object.entries(caller)) {
4746
5370
  if (value === void 0 || !(key in derived)) continue;
4747
5371
  const existing = derived[key];
4748
- if (isPlainObject2(existing) && isPlainObject2(value)) {
5372
+ if (isPlainObject3(existing) && isPlainObject3(value)) {
4749
5373
  if (overriddenKeys(existing, value).length > 0) keys.push(key);
4750
5374
  } else if (JSON.stringify(existing) !== JSON.stringify(value)) {
4751
5375
  keys.push(key);
@@ -4909,211 +5533,6 @@ var DEFAULT_REDACT_ATTRIBUTE_KEYS = [
4909
5533
  "ai.response.providerMetadata"
4910
5534
  ];
4911
5535
  var REDACT_JSON_ATTRIBUTE_KEYS = new Set(DEFAULT_REDACT_ATTRIBUTE_KEYS);
4912
- 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)$/;
4913
- var CONTENT_KEYS = /* @__PURE__ */ new Set([
4914
- "ai.prompt.system",
4915
- "ai.subagent.result",
4916
- "agent.session.title",
4917
- // Failed tool calls carry the tool's output in their error text.
4918
- "error.message",
4919
- "exception.message",
4920
- "exception.stacktrace"
4921
- ]);
4922
- var NON_CONTENT_PREFIXES = [
4923
- "traceloop.association.properties.",
4924
- "ai.telemetry.metadata.",
4925
- "ai.settings.context.",
4926
- "raindrop.app."
4927
- ];
4928
- var JSON_SIMPLE_ESCAPES = {
4929
- '"': '"',
4930
- "\\": "\\",
4931
- "/": "/",
4932
- b: "\b",
4933
- f: "\f",
4934
- n: "\n",
4935
- r: "\r",
4936
- t: " "
4937
- };
4938
- function decodeJsonEscapes(text) {
4939
- if (!text.includes("\\")) return text;
4940
- let out = "";
4941
- for (let i = 0; i < text.length; i++) {
4942
- const ch = text[i];
4943
- if (ch !== "\\" || i + 1 >= text.length) {
4944
- out += ch;
4945
- continue;
4946
- }
4947
- const next = text[i + 1];
4948
- const simple = JSON_SIMPLE_ESCAPES[next];
4949
- if (simple !== void 0) {
4950
- out += simple;
4951
- i += 1;
4952
- } else if (next === "u" && /^[0-9a-fA-F]{4}$/.test(text.slice(i + 2, i + 6))) {
4953
- out += String.fromCharCode(Number.parseInt(text.slice(i + 2, i + 6), 16));
4954
- i += 5;
4955
- } else {
4956
- out += ch;
4957
- }
4958
- }
4959
- return out;
4960
- }
4961
- function jsonStringBody(value) {
4962
- return JSON.stringify(value).slice(1, -1);
4963
- }
4964
- function redactStringToken(token) {
4965
- const decoded = decodeJsonEscapes(token.slice(1, -1));
4966
- const redacted = redactPiiText(decoded);
4967
- return redacted === decoded ? token : `"${jsonStringBody(redacted)}"`;
4968
- }
4969
- function redactLooseJsonText(text) {
4970
- if (text.startsWith('"')) {
4971
- const decoded2 = decodeJsonEscapes(text.slice(1));
4972
- const redacted2 = redactPiiText(decoded2);
4973
- return redacted2 === decoded2 ? text : `"${jsonStringBody(redacted2)}`;
4974
- }
4975
- const decoded = decodeJsonEscapes(text);
4976
- const redacted = redactPiiText(decoded);
4977
- return redacted === decoded ? text : redacted;
4978
- }
4979
- function stringTokenEnd(text, start) {
4980
- for (let i = start + 1; i < text.length; i++) {
4981
- const ch = text[i];
4982
- if (ch === "\\") i += 1;
4983
- else if (ch === '"') return i + 1;
4984
- }
4985
- return -1;
4986
- }
4987
- function redactJsonLike(text, complete) {
4988
- let out = "";
4989
- let looseStart = 0;
4990
- const flushLoose = (end) => {
4991
- if (end > looseStart) {
4992
- const loose = text.slice(looseStart, end);
4993
- out += complete ? loose : redactLooseJsonText(loose);
4994
- }
4995
- };
4996
- let i = text.indexOf('"');
4997
- while (i !== -1) {
4998
- const end = stringTokenEnd(text, i);
4999
- if (end === -1) break;
5000
- flushLoose(i);
5001
- let after = end;
5002
- while (after < text.length && /\s/.test(text[after])) after += 1;
5003
- const token = text.slice(i, end);
5004
- out += complete && text[after] === ":" ? token : redactStringToken(token);
5005
- looseStart = end;
5006
- i = text.indexOf('"', end);
5007
- }
5008
- if (i === -1) {
5009
- flushLoose(text.length);
5010
- } else {
5011
- flushLoose(i);
5012
- looseStart = i;
5013
- flushLoose(text.length);
5014
- }
5015
- return out;
5016
- }
5017
- function redactSpanContent(text) {
5018
- const head = text.trimStart()[0];
5019
- if (head !== "{" && head !== "[" && head !== '"') return redactPiiText(text);
5020
- let complete = true;
5021
- try {
5022
- JSON.parse(text);
5023
- } catch (e) {
5024
- complete = false;
5025
- }
5026
- return redactJsonLike(text, complete);
5027
- }
5028
- var NO_SPAN_PII_FIELDS = { exact: /* @__PURE__ */ new Set(), prefixes: [] };
5029
- function compileSpanPiiFields(names, logPrefix = "[raindrop-ai/core]") {
5030
- if (!Array.isArray(names) || names.length === 0) return NO_SPAN_PII_FIELDS;
5031
- const exact = /* @__PURE__ */ new Set();
5032
- const prefixes = [];
5033
- for (const name of names) {
5034
- const valid = typeof name === "string" && !/\s/.test(name) && /^[^*]+\*?$/.test(name);
5035
- if (!valid) {
5036
- rateLimitedLog(
5037
- `${logPrefix}.pii_span_field_invalid`,
5038
- () => console.warn(
5039
- `${logPrefix} redactPiiFields: ignoring invalid span attribute ${JSON.stringify(name)}`
5040
- )
5041
- );
5042
- continue;
5043
- }
5044
- if (name.endsWith("*")) prefixes.push(name.slice(0, -1));
5045
- else exact.add(name);
5046
- }
5047
- return { exact, prefixes };
5048
- }
5049
- function isCallerSelected(key, fields) {
5050
- return fields.exact.has(key) || fields.prefixes.some((prefix) => key.startsWith(prefix));
5051
- }
5052
- function isSpanContentAttributeKey(key, fields = NO_SPAN_PII_FIELDS) {
5053
- if (isCallerSelected(key, fields)) return true;
5054
- if (NON_CONTENT_PREFIXES.some((prefix) => key.startsWith(prefix))) return false;
5055
- return CONTENT_KEYS.has(key) || CONTENT_KEY_SUFFIX.test(key);
5056
- }
5057
- function redactOtlpValue(value) {
5058
- var _a;
5059
- if (typeof value.stringValue === "string") {
5060
- const redacted = redactSpanContent(value.stringValue);
5061
- return redacted === value.stringValue ? value : { ...value, stringValue: redacted };
5062
- }
5063
- const values = (_a = value.arrayValue) == null ? void 0 : _a.values;
5064
- if (!values) return value;
5065
- let changed = false;
5066
- const next = values.map((item) => {
5067
- const redacted = redactOtlpValue(item);
5068
- if (redacted !== item) changed = true;
5069
- return redacted;
5070
- });
5071
- return changed ? { ...value, arrayValue: { values: next } } : value;
5072
- }
5073
- function redactPiiInOtlpAttributes(attributes, fields = NO_SPAN_PII_FIELDS) {
5074
- let next;
5075
- for (let i = 0; i < attributes.length; i++) {
5076
- const attr = attributes[i];
5077
- if (!attr.value || !isSpanContentAttributeKey(attr.key, fields)) continue;
5078
- const value = redactOtlpValue(attr.value);
5079
- if (value === attr.value) continue;
5080
- next != null ? next : next = attributes.slice();
5081
- next[i] = { ...attr, value };
5082
- }
5083
- return next != null ? next : attributes;
5084
- }
5085
- function redactPiiInOtlpSpan(span, fields = NO_SPAN_PII_FIELDS) {
5086
- var _a;
5087
- const attributes = span.attributes && redactPiiInOtlpAttributes(span.attributes, fields);
5088
- const message = (_a = span.status) == null ? void 0 : _a.message;
5089
- const redactedMessage = message === void 0 ? void 0 : redactSpanContent(message);
5090
- if (attributes === span.attributes && redactedMessage === message) return span;
5091
- const status = span.status && redactedMessage !== message ? { ...span.status, message: redactedMessage } : span.status;
5092
- return { ...span, attributes, status };
5093
- }
5094
- function redactPiiInAttributeMap(attributes, fields = NO_SPAN_PII_FIELDS) {
5095
- let next;
5096
- for (const [key, value] of Object.entries(attributes)) {
5097
- if (!isSpanContentAttributeKey(key, fields)) continue;
5098
- let redacted = value;
5099
- if (typeof value === "string") {
5100
- redacted = redactSpanContent(value);
5101
- } else if (Array.isArray(value)) {
5102
- let changed = false;
5103
- const items = value.map((item) => {
5104
- if (typeof item !== "string") return item;
5105
- const out = redactSpanContent(item);
5106
- if (out !== item) changed = true;
5107
- return out;
5108
- });
5109
- if (changed) redacted = items;
5110
- }
5111
- if (redacted === value) continue;
5112
- next != null ? next : next = { ...attributes };
5113
- next[key] = redacted;
5114
- }
5115
- return next;
5116
- }
5117
5536
  var UNDELIVERED = Object.freeze({
5118
5537
  delivered: false,
5119
5538
  timedOut: false,
@@ -9571,7 +9990,7 @@ var SignalEventSchema = external_exports.object({
9571
9990
  // package.json
9572
9991
  var package_default = {
9573
9992
  name: "raindrop-ai",
9574
- version: "1.0.8",
9993
+ version: "1.0.9",
9575
9994
  main: "dist/index.js",
9576
9995
  module: "dist/index.mjs",
9577
9996
  types: "dist/index.d.ts",
@@ -9797,17 +10216,17 @@ var ReplayRoutingSpanExporter = class {
9797
10216
  return;
9798
10217
  }
9799
10218
  let remaining = replayGroups.size + (normalSpans.length > 0 ? 1 : 0);
9800
- let failed = false;
10219
+ let failed2 = false;
9801
10220
  let firstError;
9802
10221
  const finish = (result) => {
9803
10222
  if (result.code !== EXPORT_SUCCESS) {
9804
- failed = true;
10223
+ failed2 = true;
9805
10224
  firstError != null ? firstError : firstError = result.error;
9806
10225
  }
9807
10226
  remaining -= 1;
9808
10227
  if (remaining === 0) {
9809
10228
  resultCallback(
9810
- firstError ? { code: EXPORT_FAILED, error: firstError } : { code: failed ? EXPORT_FAILED : EXPORT_SUCCESS }
10229
+ firstError ? { code: EXPORT_FAILED, error: firstError } : { code: failed2 ? EXPORT_FAILED : EXPORT_SUCCESS }
9811
10230
  );
9812
10231
  }
9813
10232
  };
@@ -10294,6 +10713,7 @@ var DirectTraceShipper = class {
10294
10713
  this.redactTracePii = opts.redactTracePii;
10295
10714
  this.remotePiiConfig = opts.remotePiiConfig;
10296
10715
  this.spanPiiFields = opts.spanPiiFields;
10716
+ this.mask = opts.mask;
10297
10717
  this.flushIntervalMs = (_d = opts.flushIntervalMs) != null ? _d : 1e3;
10298
10718
  this.maxBatchSize = (_e = opts.maxBatchSize) != null ? _e : 50;
10299
10719
  this.maxQueueSize = (_f = opts.maxQueueSize) != null ? _f : 5e3;
@@ -10400,7 +10820,7 @@ var DirectTraceShipper = class {
10400
10820
  const mirrorUrl = (replayDestination == null ? void 0 : replayDestination.kind) === "workshop" ? replayDestination.url : replayDestination ? void 0 : this.localDebuggerUrl;
10401
10821
  const mirrored = mirrorUrl && this.redactsNow() ? this.redactSpanPii(span) : span;
10402
10822
  if (mirrorUrl && mirrored) {
10403
- const body = buildExportTraceServiceRequest2([mirrored]);
10823
+ const body = buildExportTraceServiceRequest2([maskOtlpSpan(mirrored, this.mask, this.spanPiiFields, "[raindrop]")]);
10404
10824
  const mirror = mirrorTraceExportToLocalDebugger(body, {
10405
10825
  baseUrl: mirrorUrl,
10406
10826
  debug: false,
@@ -10426,7 +10846,7 @@ var DirectTraceShipper = class {
10426
10846
  /** The span with PII redacted from its input and output; undefined if redaction failed. */
10427
10847
  redactSpanPii(span) {
10428
10848
  try {
10429
- return redactPiiInOtlpSpan(span, this.spanPiiFields);
10849
+ return redactPiiInOtlpSpan(span, this.spanPiiFields, resolveMaxTextFieldChars(void 0));
10430
10850
  } catch (e) {
10431
10851
  return void 0;
10432
10852
  }
@@ -10525,10 +10945,10 @@ var DirectTraceShipper = class {
10525
10945
  if (!replayDestination && !this.cloudEnabled) continue;
10526
10946
  if ((replayDestination == null ? void 0 : replayDestination.kind) === "workshop") continue;
10527
10947
  const spans = queuedSpans.map((q) => q.span);
10528
- const outgoing = redactPii ? spans.flatMap((span) => {
10948
+ const outgoing = (redactPii ? spans.flatMap((span) => {
10529
10949
  var _a2;
10530
10950
  return (_a2 = this.redactSpanPii(span)) != null ? _a2 : [];
10531
- }) : spans;
10951
+ }) : spans).map((span) => maskOtlpSpan(span, this.mask, this.spanPiiFields, "[raindrop]"));
10532
10952
  if (outgoing.length === 0) continue;
10533
10953
  const body = buildExportTraceServiceRequest2(outgoing);
10534
10954
  const url = replayDestination ? replayTraceUrl(replayDestination.url) : `${this.baseUrl}traces`;
@@ -10661,6 +11081,34 @@ function redactSpanPii(span, fields) {
10661
11081
  copyReplayTraceDestination(span, view);
10662
11082
  return view;
10663
11083
  }
11084
+ function maskSpan(span, mask, fields) {
11085
+ const attributes = maskAttributeMap(span.attributes, mask, fields, "[raindrop]");
11086
+ const message = span.status.message;
11087
+ const nextMessage = message === void 0 ? void 0 : maskSpanStatusMessage(message, mask, "[raindrop]");
11088
+ let eventsChanged = false;
11089
+ const events = span.events.map((event) => {
11090
+ const eventAttributes = event.attributes && maskAttributeMap(event.attributes, mask, fields, "[raindrop]");
11091
+ if (!eventAttributes) return event;
11092
+ eventsChanged = true;
11093
+ return { ...event, attributes: eventAttributes };
11094
+ });
11095
+ if (!attributes && nextMessage === message && !eventsChanged) return span;
11096
+ const view = Object.create(span);
11097
+ if (attributes) {
11098
+ Object.defineProperty(view, "attributes", { value: attributes, enumerable: true });
11099
+ }
11100
+ if (nextMessage !== message) {
11101
+ Object.defineProperty(view, "status", {
11102
+ value: { ...span.status, message: nextMessage },
11103
+ enumerable: true
11104
+ });
11105
+ }
11106
+ if (eventsChanged) {
11107
+ Object.defineProperty(view, "events", { value: events, enumerable: true });
11108
+ }
11109
+ copyReplayTraceDestination(span, view);
11110
+ return view;
11111
+ }
10664
11112
  var PiiRedactingSpanExporter = class {
10665
11113
  constructor(inner, options) {
10666
11114
  this.inner = inner;
@@ -10669,7 +11117,7 @@ var PiiRedactingSpanExporter = class {
10669
11117
  this.pending = /* @__PURE__ */ new Set();
10670
11118
  }
10671
11119
  export(spans, resultCallback) {
10672
- const { local, remote, apiUrl, writeKey, spanFields } = this.options;
11120
+ const { local, remote, apiUrl, writeKey, spanFields, mask } = this.options;
10673
11121
  const exportContext = import_api2.context.active();
10674
11122
  const run = (redact) => {
10675
11123
  let outgoing = spans;
@@ -10682,6 +11130,7 @@ var PiiRedactingSpanExporter = class {
10682
11130
  }
10683
11131
  }
10684
11132
  }
11133
+ if (mask) outgoing = outgoing.map((span) => maskSpan(span, mask, spanFields));
10685
11134
  try {
10686
11135
  import_api2.context.with(exportContext, () => this.inner.export(outgoing, resultCallback));
10687
11136
  } catch (e) {
@@ -13083,6 +13532,7 @@ var tracing = (analytics, apiUrl, writeKey, options, isDebug = false) => {
13083
13532
  redactTracePii,
13084
13533
  redactPiiFields,
13085
13534
  remotePiiConfig,
13535
+ mask,
13086
13536
  ...otherOptions
13087
13537
  } = options;
13088
13538
  const cloudEnabledResolved = cloudEnabled != null ? cloudEnabled : true;
@@ -13101,7 +13551,8 @@ var tracing = (analytics, apiUrl, writeKey, options, isDebug = false) => {
13101
13551
  remote: remotePiiConfig,
13102
13552
  apiUrl: directEndpoint != null ? directEndpoint : apiUrl,
13103
13553
  writeKey: cloudEnabledResolved ? writeKey : void 0,
13104
- spanFields: spanPiiFields
13554
+ spanFields: spanPiiFields,
13555
+ mask: typeof mask === "function" ? mask : void 0
13105
13556
  };
13106
13557
  if (localTracePii === true) {
13107
13558
  requestLocalTracePiiRedaction(piiRedaction2.apiUrl, piiRedaction2.writeKey);
@@ -13138,7 +13589,8 @@ var tracing = (analytics, apiUrl, writeKey, options, isDebug = false) => {
13138
13589
  flushTimeoutMs,
13139
13590
  redactTracePii: localTracePii,
13140
13591
  remotePiiConfig,
13141
- spanPiiFields
13592
+ spanPiiFields,
13593
+ mask: piiRedaction2.mask
13142
13594
  }) : void 0;
13143
13595
  let traceloopInitialized = false;
13144
13596
  let claimedPipeline = false;
@@ -17128,6 +17580,7 @@ var Raindrop = class {
17128
17580
  prefix: "[raindrop]"
17129
17581
  });
17130
17582
  this.redactPii = config.redactPii;
17583
+ this.mask = typeof config.mask === "function" ? config.mask : void 0;
17131
17584
  this.remotePiiConfig = config.remotePiiConfig;
17132
17585
  this.piiFields = new PiiFieldRedactor({
17133
17586
  startupFieldMap: config.redactPiiFields,
@@ -17168,6 +17621,7 @@ var Raindrop = class {
17168
17621
  maxTextFieldChars: config.maxTextFieldChars,
17169
17622
  redactPii: this.redactPii,
17170
17623
  redactPiiFields: config.redactPiiFields,
17624
+ mask: this.mask,
17171
17625
  remotePiiConfig: this.remotePiiConfig,
17172
17626
  wizardSession: (_j = this.wizardSession) != null ? _j : void 0,
17173
17627
  flushTimeoutMs: this.flushTimeoutMs
@@ -17196,7 +17650,8 @@ var Raindrop = class {
17196
17650
  flushTimeoutMs: this.flushTimeoutMs,
17197
17651
  redactTracePii: config.redactTracePii,
17198
17652
  redactPiiFields: config.redactPiiFields,
17199
- remotePiiConfig: this.remotePiiConfig
17653
+ remotePiiConfig: this.remotePiiConfig,
17654
+ mask: this.mask
17200
17655
  },
17201
17656
  this.debugLogs
17202
17657
  );
@@ -17805,7 +18260,10 @@ var Raindrop = class {
17805
18260
  rows = rows.map(snapshotPayload);
17806
18261
  redact = await piiRedaction(this.redactPii, this.remotePiiConfig, this.apiUrl, writeKey, deadlineAt);
17807
18262
  }
17808
- const body = rows.map((event) => redact && kind ? this.piiFields.redact(kind, event) : event);
18263
+ const body = rows.map((event) => {
18264
+ const redacted = redact && kind ? this.piiFields.redact(kind, event) : event;
18265
+ return kind && isRecord3(redacted) ? maskPayload(kind, redacted, this.mask, "[raindrop]") : redacted;
18266
+ });
17809
18267
  this.mirrorBatchToLocalDebugger(endpoint, body);
17810
18268
  if (this.localOnly) {
17811
18269
  return void 0;