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/evals/cli.js CHANGED
@@ -1095,7 +1095,7 @@ function evalScopeAttributes() {
1095
1095
  return { [EVAL_CORRELATION_ID_ATTRIBUTE]: scope.correlationId };
1096
1096
  }
1097
1097
 
1098
- // ../core/dist/chunk-R5EQZAA5.js
1098
+ // ../core/dist/chunk-5OUEKTIO.js
1099
1099
  var require_NameRedactor = __commonJS({
1100
1100
  "../redact-pii/dist/built-ins/NameRedactor.js"(exports2) {
1101
1101
  Object.defineProperty(exports2, "__esModule", { value: true });
@@ -1189,7 +1189,37 @@ var require_SimpleRegexpRedactor = __commonJS({
1189
1189
  this.replaceWith = replaceWith;
1190
1190
  this.regexpMatcher = regexpMatcher;
1191
1191
  }
1192
- redact(textToRedact) {
1192
+ redact(textToRedact, observe) {
1193
+ if (observe) {
1194
+ observe(0, 0, "");
1195
+ let out = "";
1196
+ let end = 0;
1197
+ const matcher = new RegExp(this.regexpMatcher.source, this.regexpMatcher.flags);
1198
+ let match;
1199
+ while ((match = matcher.exec(textToRedact)) !== null) {
1200
+ out += textToRedact.slice(end, match.index);
1201
+ const captured = match;
1202
+ const replacement = this.replaceWith.replace(/\$(\$|&|`|'|[1-9][0-9]?)/g, (token, key) => {
1203
+ if (key === "$")
1204
+ return "$";
1205
+ if (key === "&")
1206
+ return captured[0];
1207
+ if (key === "`")
1208
+ return textToRedact.slice(0, captured.index);
1209
+ if (key === "'")
1210
+ return textToRedact.slice(captured.index + captured[0].length);
1211
+ return Number(key) < captured.length ? captured[Number(key)] || "" : token;
1212
+ });
1213
+ observe(out.length, match[0].length, replacement);
1214
+ out += replacement;
1215
+ end = match.index + match[0].length;
1216
+ if (!matcher.global)
1217
+ break;
1218
+ if (match[0].length === 0)
1219
+ matcher.lastIndex += 1;
1220
+ }
1221
+ return out + textToRedact.slice(end);
1222
+ }
1193
1223
  return textToRedact.replace(this.regexpMatcher, this.replaceWith);
1194
1224
  }
1195
1225
  };
@@ -1295,9 +1325,9 @@ var require_SyncCompositeRedactor = __commonJS({
1295
1325
  var SyncCompositeRedactor = class {
1296
1326
  constructor(opts) {
1297
1327
  this.childRedactors = [];
1298
- this.redact = (textToRedact) => {
1328
+ this.redact = (textToRedact, observe) => {
1299
1329
  for (const redactor2 of this.childRedactors) {
1300
- textToRedact = redactor2.redact(textToRedact);
1330
+ textToRedact = redactor2.redact(textToRedact, observe);
1301
1331
  }
1302
1332
  return textToRedact;
1303
1333
  };
@@ -2817,8 +2847,62 @@ function normalizeProjectId(raw, opts) {
2817
2847
  function projectIdHeaders(projectId) {
2818
2848
  return projectId ? { [PROJECT_ID_HEADER]: projectId } : {};
2819
2849
  }
2850
+ var PII_MARKERS = /<REDACTED (?:CREDENTIALS|CREDIT CARD NUMBER|EMAIL|SECRET|PHONE NUMBER|ADDRESS|SOCIAL SECURITY NUMBER|DATE OF BIRTH|MEDICAL RECORD NUMBER)>/g;
2851
+ function replacePiiMatches(text, pattern, replace, observe, preservePrefix = true) {
2852
+ observe == null ? void 0 : observe(0, 0, "");
2853
+ let out = "";
2854
+ let end = 0;
2855
+ for (const match of text.matchAll(pattern)) {
2856
+ out += text.slice(end, match.index);
2857
+ const replacement = replace(match);
2858
+ if (replacement !== match[0]) {
2859
+ let prefix = 0;
2860
+ if (preservePrefix) {
2861
+ while (prefix < match[0].length && prefix < replacement.length && match[0][prefix] === replacement[prefix]) prefix++;
2862
+ }
2863
+ observe == null ? void 0 : observe(out.length + prefix, match[0].length - prefix, replacement.slice(prefix));
2864
+ }
2865
+ out += replacement;
2866
+ end = match.index + match[0].length;
2867
+ }
2868
+ return out + text.slice(end);
2869
+ }
2870
+ function redactWithinOriginalLimit(text, maxChars, redact) {
2871
+ let cutoff = Math.min(text.length, maxChars);
2872
+ const redacted = redact(text.slice(0, maxChars + 256), (start, length, replacement) => {
2873
+ if (start >= cutoff) return;
2874
+ cutoff = start + length >= cutoff ? start + replacement.length : cutoff + replacement.length - length;
2875
+ });
2876
+ let prefix = redacted.slice(0, cutoff);
2877
+ if (text.length <= maxChars && prefix.length <= maxChars) return prefix;
2878
+ if (maxChars < TRUNCATION_MARKER.length) return "";
2879
+ const budget = Math.max(0, maxChars - TRUNCATION_MARKER.length);
2880
+ let end = Math.min(prefix.length, budget);
2881
+ for (const marker of prefix.matchAll(PII_MARKERS)) {
2882
+ if (marker.index < end && marker.index + marker[0].length > end) end = marker.index;
2883
+ }
2884
+ prefix = prefix.slice(0, end);
2885
+ return prefix + TRUNCATION_MARKER;
2886
+ }
2887
+ var day = "(?:0?[1-9]|[12][0-9]|3[01])";
2888
+ var month = "(?:0?[1-9]|1[0-2])";
2889
+ var year = "(?:18|19|20)[0-9]{2}";
2890
+ 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)?)";
2891
+ var date = `(?:${month}/${day}/${year}|${day}-${month}-${year}|${year}-${month}-${day}|${monthName} ${day},? ${year}|${day} ${monthName} ${year})`;
2892
+ var birthDate = new RegExp(
2893
+ `(\\b(?:d\\.?o\\.?b\\.?|date[ _]?of[ _]?birth|born|birthday)[\\t :="']{0,8}(?:on[ ]{1,3})?)${date}(?![\\p{L}\\p{N}_]|T[0-9])`,
2894
+ "giu"
2895
+ );
2896
+ var mrn = /\b((?:MRN|medical record(?: number)?)["']?[\t :#=]{1,8}["']?)([a-z0-9][a-z0-9-]{2,39})\b/gi;
2897
+ var contextualPiiRedactor = {
2898
+ redact(text, observe) {
2899
+ text = replacePiiMatches(text, birthDate, (m) => `${m[1]}<REDACTED DATE OF BIRTH>`, observe);
2900
+ return replacePiiMatches(text, mrn, (m) => /[0-9]/.test(m[2]) ? `${m[1]}<REDACTED MEDICAL RECORD NUMBER>` : m[0], observe);
2901
+ }
2902
+ };
2820
2903
  var import_redact_pii = __toESM2(require_dist(), 1);
2821
2904
  var DEFAULT_PII_REDACTION_OPTIONS = {
2905
+ customRedactors: { after: [contextualPiiRedactor] },
2822
2906
  builtInRedactors: {
2823
2907
  credentials: { replaceWith: "<REDACTED CREDENTIALS>" },
2824
2908
  creditCardNumber: { replaceWith: "<REDACTED CREDIT CARD NUMBER>" },
@@ -2838,9 +2922,522 @@ var DEFAULT_PII_REDACTION_OPTIONS = {
2838
2922
  }
2839
2923
  };
2840
2924
  var redactor;
2841
- function redactPiiText(text) {
2925
+ function redactPiiText(text, observe) {
2842
2926
  redactor != null ? redactor : redactor = new import_redact_pii.SyncRedactor(DEFAULT_PII_REDACTION_OPTIONS);
2843
- return redactor.redact(text);
2927
+ let out = "";
2928
+ let start = 0;
2929
+ for (const marker of text.matchAll(PII_MARKERS)) {
2930
+ const offset2 = out.length;
2931
+ out += redactor.redact(text.slice(start, marker.index), observe && ((at, length, replacement) => observe(offset2 + at, length, replacement))) + marker[0];
2932
+ start = marker.index + marker[0].length;
2933
+ }
2934
+ const offset = out.length;
2935
+ return out + redactor.redact(text.slice(start), observe && ((at, length, replacement) => observe(offset + at, length, replacement)));
2936
+ }
2937
+ 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)$/;
2938
+ var CONTENT_KEYS = /* @__PURE__ */ new Set([
2939
+ "ai.prompt.system",
2940
+ "ai.subagent.result",
2941
+ "agent.session.title",
2942
+ // Failed tool calls carry the tool's output in their error text.
2943
+ "error.message",
2944
+ "exception.message",
2945
+ "exception.stacktrace"
2946
+ ]);
2947
+ var NON_CONTENT_PREFIXES = [
2948
+ "traceloop.association.properties.",
2949
+ "ai.telemetry.metadata.",
2950
+ "ai.settings.context.",
2951
+ "raindrop.app."
2952
+ ];
2953
+ var ASSOCIATION_PROPERTY = /^(?:ai\.telemetry\.metadata\.)?traceloop\.association\.properties\.(.+)$/;
2954
+ var SDK_ASSOCIATION_PROPERTIES = /* @__PURE__ */ new Set([
2955
+ "user_id",
2956
+ "event_id",
2957
+ "convo_id",
2958
+ "event_name"
2959
+ ]);
2960
+ function isEventPropertyCopy(key) {
2961
+ var _a;
2962
+ if (key === "ai.telemetry.metadata.raindrop.properties") return true;
2963
+ const name = (_a = ASSOCIATION_PROPERTY.exec(key)) == null ? void 0 : _a[1];
2964
+ return name !== void 0 && !SDK_ASSOCIATION_PROPERTIES.has(name) && !name.startsWith("raindrop.");
2965
+ }
2966
+ var JSON_SIMPLE_ESCAPES = {
2967
+ '"': '"',
2968
+ "\\": "\\",
2969
+ "/": "/",
2970
+ b: "\b",
2971
+ f: "\f",
2972
+ n: "\n",
2973
+ r: "\r",
2974
+ t: " "
2975
+ };
2976
+ function decodeJsonEscapes(text, observe) {
2977
+ if (!text.includes("\\")) return text;
2978
+ let out = "";
2979
+ for (let i = 0; i < text.length; i++) {
2980
+ const ch = text[i];
2981
+ if (ch !== "\\" || i + 1 >= text.length) {
2982
+ out += ch;
2983
+ continue;
2984
+ }
2985
+ const next = text[i + 1];
2986
+ const simple = JSON_SIMPLE_ESCAPES[next];
2987
+ if (simple !== void 0) {
2988
+ observe == null ? void 0 : observe(out.length, 2, simple);
2989
+ out += simple;
2990
+ i += 1;
2991
+ } else if (next === "u" && /^[0-9a-fA-F]{4}$/.test(text.slice(i + 2, i + 6))) {
2992
+ observe == null ? void 0 : observe(out.length, 6, String.fromCharCode(Number.parseInt(text.slice(i + 2, i + 6), 16)));
2993
+ out += String.fromCharCode(Number.parseInt(text.slice(i + 2, i + 6), 16));
2994
+ i += 5;
2995
+ } else {
2996
+ out += ch;
2997
+ }
2998
+ }
2999
+ return out;
3000
+ }
3001
+ function jsonStringBody(value, observe) {
3002
+ if (!observe) return JSON.stringify(value).slice(1, -1);
3003
+ return replacePiiMatches(
3004
+ value,
3005
+ /[\u0000-\u001f"\\]|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g,
3006
+ (m) => JSON.stringify(m[0]).slice(1, -1),
3007
+ observe,
3008
+ false
3009
+ );
3010
+ }
3011
+ function redactEncodedBody(raw, cue, observe) {
3012
+ const decoded = decodeJsonEscapes(raw);
3013
+ const edits = [];
3014
+ const redacted = redactCuedValue(decoded, cue, observe && ((...edit) => edits.push(edit)));
3015
+ if (redacted === decoded) return raw;
3016
+ decodeJsonEscapes(raw, observe);
3017
+ for (const edit of edits) observe == null ? void 0 : observe(...edit);
3018
+ return jsonStringBody(redacted, observe);
3019
+ }
3020
+ function redactStringToken(token, cue, observe) {
3021
+ const body = redactEncodedBody(token.slice(1, -1), cue, observe && ((at, length, replacement) => observe(at + 1, length, replacement)));
3022
+ return `"${body}"`;
3023
+ }
3024
+ function contextualCue(key) {
3025
+ switch (key.trim().toLowerCase().replace(/[\s_.\-]/g, "")) {
3026
+ case "dob":
3027
+ case "dateofbirth":
3028
+ case "birthday":
3029
+ case "born":
3030
+ return "DOB: ";
3031
+ case "mrn":
3032
+ case "medicalrecord":
3033
+ case "medicalrecordnumber":
3034
+ return "MRN: ";
3035
+ default:
3036
+ return void 0;
3037
+ }
3038
+ }
3039
+ function redactCuedValue(value, cue, observe) {
3040
+ const redacted = redactPiiText(value, observe);
3041
+ return cue === void 0 ? redacted : contextualPiiRedactor.redact(cue + redacted, observe && ((at, length, replacement) => {
3042
+ if (length === 0 && replacement === "") {
3043
+ observe(0, 0, "");
3044
+ return;
3045
+ }
3046
+ const prefix = Math.max(0, cue.length - at);
3047
+ observe(Math.max(0, at - cue.length), length - prefix, replacement.slice(prefix));
3048
+ })).slice(cue.length);
3049
+ }
3050
+ function redactLooseJsonText(text, observe) {
3051
+ var _a;
3052
+ if (text.startsWith('"')) {
3053
+ return `"${redactEncodedBody(text.slice(1), void 0, observe && ((at, length, replacement) => observe(at + 1, length, replacement)))}`;
3054
+ }
3055
+ if (!text.includes("\\")) return redactPiiText(text, observe);
3056
+ let pieces = (_a = text.match(/\\u[0-9a-fA-F]{4}|\\["\\/bfnrt]|[\s\S]/g)) != null ? _a : [];
3057
+ const decoded = pieces.map((piece) => decodeJsonEscapes(piece)).join("");
3058
+ let next = [];
3059
+ let read = 0;
3060
+ let delta = 0;
3061
+ let written = 0;
3062
+ const copyTo = (end) => {
3063
+ while (read < end) {
3064
+ const piece = pieces[read++];
3065
+ next.push(piece);
3066
+ written += piece.length;
3067
+ }
3068
+ };
3069
+ const finishPass = () => {
3070
+ copyTo(pieces.length);
3071
+ pieces = next;
3072
+ next = [];
3073
+ read = 0;
3074
+ delta = 0;
3075
+ written = 0;
3076
+ };
3077
+ redactPiiText(decoded, (start, length, replacement) => {
3078
+ if (length === 0 && replacement === "") {
3079
+ finishPass();
3080
+ return;
3081
+ }
3082
+ const at = start - delta;
3083
+ copyTo(at);
3084
+ let rawLength = 0;
3085
+ for (let index = at; index < at + length; index++) rawLength += pieces[index].length;
3086
+ observe == null ? void 0 : observe(written, rawLength, replacement);
3087
+ for (let index = 0; index < replacement.length; index++) next.push(replacement[index]);
3088
+ written += replacement.length;
3089
+ read = at + length;
3090
+ delta += replacement.length - length;
3091
+ });
3092
+ finishPass();
3093
+ return pieces.join("");
3094
+ }
3095
+ function stringTokenEnd(text, start) {
3096
+ for (let i = start + 1; i < text.length; i++) {
3097
+ const ch = text[i];
3098
+ if (ch === "\\") i += 1;
3099
+ else if (ch === '"') return i + 1;
3100
+ }
3101
+ return -1;
3102
+ }
3103
+ function redactJsonLike(text, complete, observe) {
3104
+ var _a, _b;
3105
+ let out = "";
3106
+ let looseStart = 0;
3107
+ const flushLoose = (end) => {
3108
+ if (end > looseStart) {
3109
+ const loose = text.slice(looseStart, end);
3110
+ const offset = out.length;
3111
+ out += complete ? loose : redactLooseJsonText(loose, observe && ((at, length, replacement) => observe(offset + at, length, replacement)));
3112
+ }
3113
+ };
3114
+ let i = text.indexOf('"');
3115
+ while (i !== -1) {
3116
+ const end = stringTokenEnd(text, i);
3117
+ if (end === -1) break;
3118
+ flushLoose(i);
3119
+ let after = end;
3120
+ while (after < text.length && /\s/.test(text[after])) after += 1;
3121
+ const token = text.slice(i, end);
3122
+ if (text[after] === ":") {
3123
+ const cue = contextualCue(decodeJsonEscapes(token.slice(1, -1)));
3124
+ if (cue !== void 0) {
3125
+ let start = after + 1;
3126
+ while (/\s/.test((_a = text[start]) != null ? _a : "")) start += 1;
3127
+ let valueEnd = start;
3128
+ let replacement;
3129
+ const offset2 = out.length + start - i;
3130
+ const valueObserver = observe && ((at, length, replacement2) => observe(offset2 + at, length, replacement2));
3131
+ if (text[start] === '"') {
3132
+ valueEnd = stringTokenEnd(text, start);
3133
+ if (valueEnd === -1) {
3134
+ valueEnd = text.length;
3135
+ replacement = `"${redactEncodedBody(text.slice(start + 1), cue, valueObserver && ((at, length, replacement2) => valueObserver(at + 1, length, replacement2)))}`;
3136
+ } else {
3137
+ replacement = redactStringToken(text.slice(start, valueEnd), cue, valueObserver);
3138
+ }
3139
+ } else if (/[-0-9]/.test((_b = text[start]) != null ? _b : "")) {
3140
+ while (valueEnd < text.length && !/[\s,}\]]/.test(text[valueEnd])) valueEnd += 1;
3141
+ const value = text.slice(start, valueEnd);
3142
+ const redacted = redactCuedValue(value, cue);
3143
+ if (redacted !== value) {
3144
+ replacement = JSON.stringify(redacted);
3145
+ valueObserver == null ? void 0 : valueObserver(0, value.length, replacement);
3146
+ }
3147
+ }
3148
+ if (replacement !== void 0) {
3149
+ out += text.slice(i, start) + replacement;
3150
+ looseStart = valueEnd;
3151
+ i = text.indexOf('"', valueEnd);
3152
+ continue;
3153
+ }
3154
+ }
3155
+ }
3156
+ const offset = out.length;
3157
+ out += complete && text[after] === ":" ? token : redactStringToken(token, void 0, observe && ((at, length, replacement) => observe(offset + at, length, replacement)));
3158
+ looseStart = end;
3159
+ i = text.indexOf('"', end);
3160
+ }
3161
+ if (i === -1) {
3162
+ flushLoose(text.length);
3163
+ } else {
3164
+ flushLoose(i);
3165
+ looseStart = i;
3166
+ flushLoose(text.length);
3167
+ }
3168
+ return out;
3169
+ }
3170
+ function redactSpanContent(text, observe) {
3171
+ const head = text.trimStart()[0];
3172
+ if (head !== "{" && head !== "[" && head !== '"') return redactPiiText(text, observe);
3173
+ let complete = true;
3174
+ try {
3175
+ JSON.parse(text);
3176
+ } catch (e) {
3177
+ complete = false;
3178
+ }
3179
+ return redactJsonLike(text, complete, observe);
3180
+ }
3181
+ function isCompleteJsonContainer(text) {
3182
+ const head = text.trimStart()[0];
3183
+ if (head !== "{" && head !== "[") return false;
3184
+ try {
3185
+ JSON.parse(text);
3186
+ return true;
3187
+ } catch (e) {
3188
+ return false;
3189
+ }
3190
+ }
3191
+ function redactJsonEventContent(text, observe) {
3192
+ if (!/^\s*(?:\{\s*"|\[\s*["{\[])/.test(text) && !isCompleteJsonContainer(text)) return text;
3193
+ return redactSpanContent(text, observe);
3194
+ }
3195
+ var NO_SPAN_PII_FIELDS = { exact: /* @__PURE__ */ new Set(), prefixes: [] };
3196
+ function compileSpanPiiFields(names, logPrefix = "[raindrop-ai/core]") {
3197
+ if (!Array.isArray(names) || names.length === 0) return NO_SPAN_PII_FIELDS;
3198
+ const exact = /* @__PURE__ */ new Set();
3199
+ const prefixes = [];
3200
+ for (const name of names) {
3201
+ const valid = typeof name === "string" && !/\s/.test(name) && /^[^*]+\*?$/.test(name);
3202
+ if (!valid) {
3203
+ rateLimitedLog(
3204
+ `${logPrefix}.pii_span_field_invalid`,
3205
+ () => console.warn(
3206
+ `${logPrefix} redactPiiFields: ignoring invalid span attribute ${JSON.stringify(name)}`
3207
+ )
3208
+ );
3209
+ continue;
3210
+ }
3211
+ if (name.endsWith("*")) prefixes.push(name.slice(0, -1));
3212
+ else exact.add(name);
3213
+ }
3214
+ return { exact, prefixes };
3215
+ }
3216
+ function isCallerSelected(key, fields) {
3217
+ return fields.exact.has(key) || fields.prefixes.some((prefix) => key.startsWith(prefix));
3218
+ }
3219
+ function isSpanContentAttributeKey(key, fields = NO_SPAN_PII_FIELDS) {
3220
+ if (isCallerSelected(key, fields) || isEventPropertyCopy(key)) return true;
3221
+ if (NON_CONTENT_PREFIXES.some((prefix) => key.startsWith(prefix))) return false;
3222
+ return CONTENT_KEYS.has(key) || CONTENT_KEY_SUFFIX.test(key);
3223
+ }
3224
+ function redactBoundedContent(text, maxChars) {
3225
+ if (maxChars === void 0) return redactSpanContent(text);
3226
+ return redactWithinOriginalLimit(text, maxChars, redactSpanContent);
3227
+ }
3228
+ function redactOtlpValue(value, maxChars) {
3229
+ var _a;
3230
+ if (typeof value.stringValue === "string") {
3231
+ const redacted = redactBoundedContent(value.stringValue, maxChars);
3232
+ return redacted === value.stringValue ? value : { ...value, stringValue: redacted };
3233
+ }
3234
+ const values = (_a = value.arrayValue) == null ? void 0 : _a.values;
3235
+ if (!values) return value;
3236
+ let changed = false;
3237
+ const next = values.map((item) => {
3238
+ const redacted = redactOtlpValue(item, maxChars);
3239
+ if (redacted !== item) changed = true;
3240
+ return redacted;
3241
+ });
3242
+ return changed ? { ...value, arrayValue: { values: next } } : value;
3243
+ }
3244
+ function redactPiiInOtlpAttributes(attributes, fields = NO_SPAN_PII_FIELDS, maxChars) {
3245
+ let next;
3246
+ for (let i = 0; i < attributes.length; i++) {
3247
+ const attr = attributes[i];
3248
+ if (!attr.value || !isSpanContentAttributeKey(attr.key, fields)) continue;
3249
+ const value = redactOtlpValue(attr.value, maxChars);
3250
+ if (value === attr.value) continue;
3251
+ next != null ? next : next = attributes.slice();
3252
+ next[i] = { ...attr, value };
3253
+ }
3254
+ return next != null ? next : attributes;
3255
+ }
3256
+ function redactPiiInOtlpSpan(span, fields = NO_SPAN_PII_FIELDS, maxChars) {
3257
+ var _a;
3258
+ const attributes = span.attributes && redactPiiInOtlpAttributes(span.attributes, fields, maxChars);
3259
+ const message = (_a = span.status) == null ? void 0 : _a.message;
3260
+ const redactedMessage = message === void 0 ? void 0 : redactBoundedContent(message, maxChars);
3261
+ if (attributes === span.attributes && redactedMessage === message) return span;
3262
+ const status = span.status && redactedMessage !== message ? { ...span.status, message: redactedMessage } : span.status;
3263
+ return { ...span, attributes, status };
3264
+ }
3265
+ function redactPiiInAttributeMap(attributes, fields = NO_SPAN_PII_FIELDS) {
3266
+ let next;
3267
+ for (const [key, value] of Object.entries(attributes)) {
3268
+ if (!isSpanContentAttributeKey(key, fields)) continue;
3269
+ let redacted = value;
3270
+ if (typeof value === "string") {
3271
+ redacted = redactSpanContent(value);
3272
+ } else if (Array.isArray(value)) {
3273
+ let changed = false;
3274
+ const items = value.map((item) => {
3275
+ if (typeof item !== "string") return item;
3276
+ const out = redactSpanContent(item);
3277
+ if (out !== item) changed = true;
3278
+ return out;
3279
+ });
3280
+ if (changed) redacted = items;
3281
+ }
3282
+ if (redacted === value) continue;
3283
+ next != null ? next : next = { ...attributes };
3284
+ next[key] = redacted;
3285
+ }
3286
+ return next;
3287
+ }
3288
+ var MASK_FAILED = "<MASK FAILED>";
3289
+ var EVENT_FIELDS = {
3290
+ event: [["ai_data", "input"], ["ai_data", "output"], ["properties"], ["attachments"]],
3291
+ signal: [["properties"]],
3292
+ identify: [["traits"]]
3293
+ };
3294
+ var SDK_PROPERTY_KEYS = ["$context"];
3295
+ function isPlainObject(value) {
3296
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
3297
+ const proto = Object.getPrototypeOf(value);
3298
+ return proto === Object.prototype || proto === null;
3299
+ }
3300
+ function isThenable(value) {
3301
+ return typeof value === "object" && value !== null && "then" in value && typeof value.then === "function";
3302
+ }
3303
+ function warn(prefix, context8, reason) {
3304
+ rateLimitedLog(
3305
+ `${prefix}.mask_failed`,
3306
+ () => console.warn(
3307
+ `${prefix} mask function failed on ${context8.kind} ${context8.field} (${reason}); sending ${MASK_FAILED} in its place.`
3308
+ )
3309
+ );
3310
+ }
3311
+ function jsonCopy(value) {
3312
+ const json = JSON.stringify(value);
3313
+ if (json === void 0) throw new TypeError("not JSON-serializable");
3314
+ return JSON.parse(json);
3315
+ }
3316
+ function failed(shape) {
3317
+ if (shape === "string") return MASK_FAILED;
3318
+ if (shape === "object") return { error: MASK_FAILED };
3319
+ return [];
3320
+ }
3321
+ function maskValue(value, context8, mask, prefix) {
3322
+ const shape = typeof value === "string" ? "string" : Array.isArray(value) ? "array" : "object";
3323
+ try {
3324
+ const result = mask(shape === "string" ? value : jsonCopy(value), context8);
3325
+ if (isThenable(result)) {
3326
+ Promise.resolve(result).catch(() => {
3327
+ });
3328
+ warn(prefix, context8, "it returned a promise; mask must be synchronous");
3329
+ return failed(shape);
3330
+ }
3331
+ if (shape === "string") {
3332
+ if (typeof result === "string") return result;
3333
+ } else {
3334
+ const copy = jsonCopy(result);
3335
+ if (shape === "array" ? Array.isArray(copy) : isPlainObject(copy)) return copy;
3336
+ }
3337
+ warn(prefix, context8, `it returned a value that is not ${shape === "string" ? "a string" : `an ${shape}`}`);
3338
+ } catch (err) {
3339
+ warn(prefix, context8, err instanceof Error ? err.name : "threw");
3340
+ }
3341
+ return failed(shape);
3342
+ }
3343
+ function maskAt(node, path, context8, mask, prefix) {
3344
+ const [head, ...rest] = path;
3345
+ if (head === void 0 || !Object.prototype.hasOwnProperty.call(node, head)) return node;
3346
+ const child = node[head];
3347
+ if (rest.length > 0) {
3348
+ if (!isPlainObject(child)) return node;
3349
+ const next = maskAt(child, rest, context8, mask, prefix);
3350
+ return next === child ? node : { ...node, [head]: next };
3351
+ }
3352
+ if (child === void 0 || child === null) return node;
3353
+ if (typeof child !== "string" && typeof child !== "object") return node;
3354
+ if (context8.kind !== "event" || head !== "properties" || !isPlainObject(child)) {
3355
+ return { ...node, [head]: maskValue(child, context8, mask, prefix) };
3356
+ }
3357
+ const own2 = {};
3358
+ const sdk = {};
3359
+ for (const [key, value] of Object.entries(child)) {
3360
+ (SDK_PROPERTY_KEYS.includes(key) ? sdk : own2)[key] = value;
3361
+ }
3362
+ const masked = maskValue(own2, context8, mask, prefix);
3363
+ return { ...node, [head]: isPlainObject(masked) ? { ...masked, ...sdk } : sdk };
3364
+ }
3365
+ function maskPayload(kind, payload, mask, logPrefix = "[raindrop-ai/core]") {
3366
+ if (!mask) return payload;
3367
+ let out = payload;
3368
+ for (const path of EVENT_FIELDS[kind]) {
3369
+ out = maskAt(out, path, { kind, field: path.join(".") }, mask, logPrefix);
3370
+ }
3371
+ return out;
3372
+ }
3373
+ function maskOtlpValue(value, context8, mask, prefix) {
3374
+ var _a;
3375
+ if (typeof value.stringValue === "string") {
3376
+ const masked = maskValue(value.stringValue, context8, mask, prefix);
3377
+ return typeof masked === "string" && masked !== value.stringValue ? { ...value, stringValue: masked } : value;
3378
+ }
3379
+ const values = (_a = value.arrayValue) == null ? void 0 : _a.values;
3380
+ if (!values) return value;
3381
+ let changed = false;
3382
+ const next = values.map((item) => {
3383
+ const masked = maskOtlpValue(item, context8, mask, prefix);
3384
+ if (masked !== item) changed = true;
3385
+ return masked;
3386
+ });
3387
+ return changed ? { ...value, arrayValue: { values: next } } : value;
3388
+ }
3389
+ function maskSpanStatusMessage(message, mask, logPrefix = "[raindrop-ai/core]") {
3390
+ if (!mask) return message;
3391
+ const masked = maskValue(message, { kind: "span", field: "status.message" }, mask, logPrefix);
3392
+ return typeof masked === "string" ? masked : MASK_FAILED;
3393
+ }
3394
+ function maskOtlpAttributes(attributes, mask, fields, logPrefix = "[raindrop-ai/core]") {
3395
+ if (!mask) return attributes;
3396
+ let next;
3397
+ for (let i = 0; i < attributes.length; i++) {
3398
+ const attr = attributes[i];
3399
+ if (!attr.value || !isSpanContentAttributeKey(attr.key, fields)) continue;
3400
+ const value = maskOtlpValue(attr.value, { kind: "span", field: attr.key }, mask, logPrefix);
3401
+ if (value === attr.value) continue;
3402
+ next != null ? next : next = attributes.slice();
3403
+ next[i] = { ...attr, value };
3404
+ }
3405
+ return next != null ? next : attributes;
3406
+ }
3407
+ function maskOtlpSpan(span, mask, fields, logPrefix = "[raindrop-ai/core]") {
3408
+ var _a;
3409
+ if (!mask) return span;
3410
+ const attributes = span.attributes && maskOtlpAttributes(span.attributes, mask, fields, logPrefix);
3411
+ const message = (_a = span.status) == null ? void 0 : _a.message;
3412
+ const nextMessage = message === void 0 ? void 0 : maskSpanStatusMessage(message, mask, logPrefix);
3413
+ if (attributes === span.attributes && nextMessage === message) return span;
3414
+ const status = span.status && nextMessage !== message ? { ...span.status, message: nextMessage } : span.status;
3415
+ return { ...span, attributes, status };
3416
+ }
3417
+ function maskAttributeMap(attributes, mask, fields, logPrefix = "[raindrop-ai/core]") {
3418
+ if (!mask) return void 0;
3419
+ let next;
3420
+ for (const [key, value] of Object.entries(attributes)) {
3421
+ if (!isSpanContentAttributeKey(key, fields)) continue;
3422
+ const context8 = { kind: "span", field: key };
3423
+ let masked = value;
3424
+ if (typeof value === "string") {
3425
+ masked = maskValue(value, context8, mask, logPrefix);
3426
+ } else if (Array.isArray(value)) {
3427
+ let changed = false;
3428
+ const items = value.map((item) => {
3429
+ if (typeof item !== "string") return item;
3430
+ const out = maskValue(item, context8, mask, logPrefix);
3431
+ if (out !== item) changed = true;
3432
+ return out;
3433
+ });
3434
+ if (changed) masked = items;
3435
+ }
3436
+ if (masked === value) continue;
3437
+ next != null ? next : next = { ...attributes };
3438
+ next[key] = masked;
3439
+ }
3440
+ return next;
2844
3441
  }
2845
3442
  var KINDS = ["event", "signal", "identify"];
2846
3443
  var DEFAULT_PII_FIELDS = {
@@ -2936,7 +3533,7 @@ function mergePiiFieldMaps(...maps) {
2936
3533
  }
2937
3534
  return out;
2938
3535
  }
2939
- function isPlainObject(value) {
3536
+ function isPlainObject2(value) {
2940
3537
  if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
2941
3538
  const proto = Object.getPrototypeOf(value);
2942
3539
  return proto === Object.prototype || proto === null;
@@ -2944,30 +3541,35 @@ function isPlainObject(value) {
2944
3541
  function isProtected(location) {
2945
3542
  return PROTECTED_LOCATIONS.has(JSON.stringify(location));
2946
3543
  }
2947
- function redactAll(value, location) {
3544
+ function redactAll(value, location, maxChars) {
2948
3545
  if (location !== null && isProtected(location)) return value;
2949
- if (typeof value === "string") return redactPiiText(value);
2950
- if (Array.isArray(value)) return value.map((item) => redactAll(item, null));
2951
- if (isPlainObject(value)) {
3546
+ if (typeof value === "string") {
3547
+ if (maxChars !== void 0 && (location == null ? void 0 : location.length) === 2 && location[0] === "ai_data" && (location[1] === "input" || location[1] === "output")) {
3548
+ return redactWithinOriginalLimit(value, maxChars, (text, observe) => redactPiiText(redactJsonEventContent(text, observe), observe));
3549
+ }
3550
+ return redactPiiText(redactJsonEventContent(value));
3551
+ }
3552
+ if (Array.isArray(value)) return value.map((item) => redactAll(item, null, maxChars));
3553
+ if (isPlainObject2(value)) {
2952
3554
  const out = {};
2953
3555
  for (const [key, child] of Object.entries(value)) {
2954
- out[key] = redactAll(child, location === null ? null : [...location, key]);
3556
+ out[key] = redactAll(child, location === null ? null : [...location, key], maxChars);
2955
3557
  }
2956
3558
  return out;
2957
3559
  }
2958
3560
  return value;
2959
3561
  }
2960
- function applyPath(value, segments, location) {
2961
- if (segments.length === 0) return redactAll(value, location);
3562
+ function applyPath(value, segments, location, maxChars) {
3563
+ if (segments.length === 0) return redactAll(value, location, maxChars);
2962
3564
  const [head, ...rest] = segments;
2963
3565
  if (head.kind === "key" || head.kind === "any_key") {
2964
- if (!isPlainObject(value)) return value;
3566
+ if (!isPlainObject2(value)) return value;
2965
3567
  const keys = head.kind === "key" ? [head.key] : Object.keys(value);
2966
3568
  let out2;
2967
3569
  for (const key of keys) {
2968
3570
  if (!Object.prototype.hasOwnProperty.call(value, key)) continue;
2969
3571
  const child = value[key];
2970
- const next = applyPath(child, rest, location === null ? null : [...location, key]);
3572
+ const next = applyPath(child, rest, location === null ? null : [...location, key], maxChars);
2971
3573
  if (next !== child) {
2972
3574
  out2 != null ? out2 : out2 = { ...value };
2973
3575
  out2[key] = next;
@@ -2980,7 +3582,7 @@ function applyPath(value, segments, location) {
2980
3582
  let out;
2981
3583
  for (const index of indices) {
2982
3584
  const child = value[index];
2983
- const next = applyPath(child, rest, null);
3585
+ const next = applyPath(child, rest, null, maxChars);
2984
3586
  if (next !== child) {
2985
3587
  out != null ? out : out = [...value];
2986
3588
  out[index] = next;
@@ -3030,9 +3632,9 @@ var PiiFieldRedactor = class {
3030
3632
  return out;
3031
3633
  }
3032
3634
  /** The payload with every selected field redacted (a copy where changed). */
3033
- redact(kind, payload) {
3635
+ redact(kind, payload, maxChars) {
3034
3636
  let out = payload;
3035
- for (const segments of this.compile()[kind]) out = applyPath(out, segments, []);
3637
+ for (const segments of this.compile()[kind]) out = applyPath(out, segments, [], maxChars);
3036
3638
  return out;
3037
3639
  }
3038
3640
  };
@@ -3213,13 +3815,13 @@ function earliestIsoTimestamp(...values) {
3213
3815
  let earliest;
3214
3816
  for (const value of values) {
3215
3817
  if (value === void 0) continue;
3216
- const date = new Date(value);
3217
- if (Number.isNaN(date.getTime())) continue;
3218
- if (earliest === void 0 || date < earliest) earliest = date;
3818
+ const date2 = new Date(value);
3819
+ if (Number.isNaN(date2.getTime())) continue;
3820
+ if (earliest === void 0 || date2 < earliest) earliest = date2;
3219
3821
  }
3220
3822
  return earliest == null ? void 0 : earliest.toISOString();
3221
3823
  }
3222
- function isPlainObject2(value) {
3824
+ function isPlainObject3(value) {
3223
3825
  if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
3224
3826
  const proto = Object.getPrototypeOf(value);
3225
3827
  return proto === Object.prototype || proto === null;
@@ -3230,7 +3832,7 @@ function deepMergeProperties(target, source) {
3230
3832
  for (const [key, value] of Object.entries(source)) {
3231
3833
  if (value === void 0 || UNSAFE_MERGE_KEYS.has(key)) continue;
3232
3834
  const existing = out[key];
3233
- out[key] = isPlainObject2(existing) && isPlainObject2(value) ? deepMergeProperties(existing, value) : value;
3835
+ out[key] = isPlainObject3(existing) && isPlainObject3(value) ? deepMergeProperties(existing, value) : value;
3234
3836
  }
3235
3837
  return out;
3236
3838
  }
@@ -3330,6 +3932,7 @@ var EventShipper = class {
3330
3932
  });
3331
3933
  this.redactPii = typeof opts.redactPii === "boolean" ? opts.redactPii : void 0;
3332
3934
  this.remotePiiConfig = opts.remotePiiConfig;
3935
+ this.mask = typeof opts.mask === "function" ? opts.mask : void 0;
3333
3936
  this.piiFields = new PiiFieldRedactor({
3334
3937
  startupFieldMap: opts.redactPiiFields,
3335
3938
  logPrefix: this.prefix
@@ -3490,11 +4093,12 @@ var EventShipper = class {
3490
4093
  return void 0;
3491
4094
  }
3492
4095
  const maxChars = resolveMaxTextFieldChars(this.maxTextFieldCharsOpt);
3493
- if (typeof patch.input === "string" && patch.input.length > maxChars) {
3494
- patch = { ...patch, input: capText(patch.input, maxChars) };
3495
- }
3496
- if (typeof patch.output === "string" && patch.output.length > maxChars) {
3497
- patch = { ...patch, output: capText(patch.output, maxChars) };
4096
+ const mayRedact = this.redactPii === true || this.redactPii !== false && this.remotePiiConfig;
4097
+ for (const field of ["input", "output"]) {
4098
+ const text = patch[field];
4099
+ if (typeof text !== "string" || text.length <= maxChars) continue;
4100
+ const bounded = mayRedact ? text.slice(0, maxChars + 256) : capText(text, maxChars);
4101
+ patch = { ...patch, [field]: bounded };
3498
4102
  }
3499
4103
  if (this.debug) {
3500
4104
  console.log(`${this.prefix} queue patch`, {
@@ -3707,7 +4311,7 @@ var EventShipper = class {
3707
4311
  ];
3708
4312
  const known = piiRedactionNow(this.redactPii, this.remotePiiConfig, this.baseUrl, this.writeKey);
3709
4313
  if (known !== void 0) {
3710
- const body = known ? items.map((item) => this.piiFields.redact("signal", item)) : items;
4314
+ const body = items.map((item) => this.outgoing("signal", item, known));
3711
4315
  if (!this.writeKey) return;
3712
4316
  await this.sendDirect("signal", `${this.baseUrl}signals/track`, body);
3713
4317
  return;
@@ -3715,7 +4319,7 @@ var EventShipper = class {
3715
4319
  const snapshot = items.map(snapshotPayload);
3716
4320
  await this.tracked(async () => {
3717
4321
  const redact = await this.shouldRedactPii();
3718
- const body = redact ? snapshot.map((item) => this.piiFields.redact("signal", item)) : snapshot;
4322
+ const body = snapshot.map((item) => this.outgoing("signal", item, redact));
3719
4323
  if (!this.writeKey) return;
3720
4324
  await this.sendDirect("signal", `${this.baseUrl}signals/track`, body, void 0, false);
3721
4325
  });
@@ -3744,14 +4348,14 @@ var EventShipper = class {
3744
4348
  if (rows.length === 0) return;
3745
4349
  const known = piiRedactionNow(this.redactPii, this.remotePiiConfig, this.baseUrl, this.writeKey);
3746
4350
  if (known !== void 0) {
3747
- const body = known ? rows.map((user) => this.piiFields.redact("identify", user)) : rows;
4351
+ const body = rows.map((user) => this.outgoing("identify", user, known));
3748
4352
  await this.sendDirect("identify", `${this.baseUrl}users/identify`, body);
3749
4353
  return;
3750
4354
  }
3751
4355
  const snapshot = rows.map(snapshotPayload);
3752
4356
  await this.tracked(async () => {
3753
4357
  const redact = await this.shouldRedactPii();
3754
- const body = redact ? snapshot.map((user) => this.piiFields.redact("identify", user)) : snapshot;
4358
+ const body = snapshot.map((user) => this.outgoing("identify", user, redact));
3755
4359
  await this.sendDirect("identify", `${this.baseUrl}users/identify`, body, void 0, false);
3756
4360
  });
3757
4361
  }
@@ -3814,6 +4418,12 @@ var EventShipper = class {
3814
4418
  () => console.warn(`${this.prefix} failed to send ${what} (dropping): ${reason}`)
3815
4419
  );
3816
4420
  }
4421
+ /** A payload as it is sent: built-in redaction when on, then the caller's `mask`. */
4422
+ outgoing(kind, payload, redact) {
4423
+ const maxChars = kind === "event" ? resolveMaxTextFieldChars(this.maxTextFieldCharsOpt) : void 0;
4424
+ const redacted = redact ? this.piiFields.redact(kind, payload, maxChars) : payload;
4425
+ return isPlainObject3(redacted) ? maskPayload(kind, redacted, this.mask, this.prefix) : redacted;
4426
+ }
3817
4427
  /**
3818
4428
  * Whether to redact PII: `redactPii`, or when it is unset and
3819
4429
  * `remotePiiConfig` is on, the org's setting. Waits for the org's answer
@@ -3966,7 +4576,7 @@ var EventShipper = class {
3966
4576
  };
3967
4577
  const known = piiRedactionNow(this.redactPii, this.remotePiiConfig, this.baseUrl, this.writeKey);
3968
4578
  if (known !== void 0) {
3969
- const payload = known ? this.piiFields.redact("event", unredacted) : unredacted;
4579
+ const payload = this.outgoing("event", unredacted, known);
3970
4580
  return this.shipPartial(eventId, accumulated, payload, { eventName, userId, convoId, isPending }, deadlineAt, true);
3971
4581
  }
3972
4582
  const snapshot = snapshotPayload(unredacted);
@@ -3974,7 +4584,7 @@ var EventShipper = class {
3974
4584
  (redact) => this.shipPartial(
3975
4585
  eventId,
3976
4586
  accumulated,
3977
- redact ? this.piiFields.redact("event", snapshot) : snapshot,
4587
+ this.outgoing("event", snapshot, redact),
3978
4588
  { eventName, userId, convoId, isPending },
3979
4589
  deadlineAt,
3980
4590
  false
@@ -3996,6 +4606,20 @@ var EventShipper = class {
3996
4606
  var _a, _b, _c, _d, _e, _f;
3997
4607
  const { eventName, userId, convoId, isPending } = meta;
3998
4608
  const url = `${this.baseUrl}events/track_partial`;
4609
+ if (payload !== null && typeof payload === "object" && "ai_data" in payload) {
4610
+ const data = payload.ai_data;
4611
+ if (data !== null && typeof data === "object") {
4612
+ const maxChars = resolveMaxTextFieldChars(this.maxTextFieldCharsOpt);
4613
+ payload = {
4614
+ ...payload,
4615
+ ai_data: {
4616
+ ...data,
4617
+ input: capText("input" in data ? data.input : void 0, maxChars),
4618
+ output: capText("output" in data ? data.output : void 0, maxChars)
4619
+ }
4620
+ };
4621
+ }
4622
+ }
3999
4623
  if (this.debug) {
4000
4624
  const sent = payload;
4001
4625
  const preview = (v, n) => typeof v === "string" ? v.slice(0, n) : void 0;
@@ -4070,7 +4694,7 @@ function overriddenKeys(derived, caller) {
4070
4694
  for (const [key, value] of Object.entries(caller)) {
4071
4695
  if (value === void 0 || !(key in derived)) continue;
4072
4696
  const existing = derived[key];
4073
- if (isPlainObject2(existing) && isPlainObject2(value)) {
4697
+ if (isPlainObject3(existing) && isPlainObject3(value)) {
4074
4698
  if (overriddenKeys(existing, value).length > 0) keys.push(key);
4075
4699
  } else if (JSON.stringify(existing) !== JSON.stringify(value)) {
4076
4700
  keys.push(key);
@@ -4234,211 +4858,6 @@ var DEFAULT_REDACT_ATTRIBUTE_KEYS = [
4234
4858
  "ai.response.providerMetadata"
4235
4859
  ];
4236
4860
  var REDACT_JSON_ATTRIBUTE_KEYS = new Set(DEFAULT_REDACT_ATTRIBUTE_KEYS);
4237
- 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)$/;
4238
- var CONTENT_KEYS = /* @__PURE__ */ new Set([
4239
- "ai.prompt.system",
4240
- "ai.subagent.result",
4241
- "agent.session.title",
4242
- // Failed tool calls carry the tool's output in their error text.
4243
- "error.message",
4244
- "exception.message",
4245
- "exception.stacktrace"
4246
- ]);
4247
- var NON_CONTENT_PREFIXES = [
4248
- "traceloop.association.properties.",
4249
- "ai.telemetry.metadata.",
4250
- "ai.settings.context.",
4251
- "raindrop.app."
4252
- ];
4253
- var JSON_SIMPLE_ESCAPES = {
4254
- '"': '"',
4255
- "\\": "\\",
4256
- "/": "/",
4257
- b: "\b",
4258
- f: "\f",
4259
- n: "\n",
4260
- r: "\r",
4261
- t: " "
4262
- };
4263
- function decodeJsonEscapes(text) {
4264
- if (!text.includes("\\")) return text;
4265
- let out = "";
4266
- for (let i = 0; i < text.length; i++) {
4267
- const ch = text[i];
4268
- if (ch !== "\\" || i + 1 >= text.length) {
4269
- out += ch;
4270
- continue;
4271
- }
4272
- const next = text[i + 1];
4273
- const simple = JSON_SIMPLE_ESCAPES[next];
4274
- if (simple !== void 0) {
4275
- out += simple;
4276
- i += 1;
4277
- } else if (next === "u" && /^[0-9a-fA-F]{4}$/.test(text.slice(i + 2, i + 6))) {
4278
- out += String.fromCharCode(Number.parseInt(text.slice(i + 2, i + 6), 16));
4279
- i += 5;
4280
- } else {
4281
- out += ch;
4282
- }
4283
- }
4284
- return out;
4285
- }
4286
- function jsonStringBody(value) {
4287
- return JSON.stringify(value).slice(1, -1);
4288
- }
4289
- function redactStringToken(token) {
4290
- const decoded = decodeJsonEscapes(token.slice(1, -1));
4291
- const redacted = redactPiiText(decoded);
4292
- return redacted === decoded ? token : `"${jsonStringBody(redacted)}"`;
4293
- }
4294
- function redactLooseJsonText(text) {
4295
- if (text.startsWith('"')) {
4296
- const decoded2 = decodeJsonEscapes(text.slice(1));
4297
- const redacted2 = redactPiiText(decoded2);
4298
- return redacted2 === decoded2 ? text : `"${jsonStringBody(redacted2)}`;
4299
- }
4300
- const decoded = decodeJsonEscapes(text);
4301
- const redacted = redactPiiText(decoded);
4302
- return redacted === decoded ? text : redacted;
4303
- }
4304
- function stringTokenEnd(text, start) {
4305
- for (let i = start + 1; i < text.length; i++) {
4306
- const ch = text[i];
4307
- if (ch === "\\") i += 1;
4308
- else if (ch === '"') return i + 1;
4309
- }
4310
- return -1;
4311
- }
4312
- function redactJsonLike(text, complete) {
4313
- let out = "";
4314
- let looseStart = 0;
4315
- const flushLoose = (end) => {
4316
- if (end > looseStart) {
4317
- const loose = text.slice(looseStart, end);
4318
- out += complete ? loose : redactLooseJsonText(loose);
4319
- }
4320
- };
4321
- let i = text.indexOf('"');
4322
- while (i !== -1) {
4323
- const end = stringTokenEnd(text, i);
4324
- if (end === -1) break;
4325
- flushLoose(i);
4326
- let after = end;
4327
- while (after < text.length && /\s/.test(text[after])) after += 1;
4328
- const token = text.slice(i, end);
4329
- out += complete && text[after] === ":" ? token : redactStringToken(token);
4330
- looseStart = end;
4331
- i = text.indexOf('"', end);
4332
- }
4333
- if (i === -1) {
4334
- flushLoose(text.length);
4335
- } else {
4336
- flushLoose(i);
4337
- looseStart = i;
4338
- flushLoose(text.length);
4339
- }
4340
- return out;
4341
- }
4342
- function redactSpanContent(text) {
4343
- const head = text.trimStart()[0];
4344
- if (head !== "{" && head !== "[" && head !== '"') return redactPiiText(text);
4345
- let complete = true;
4346
- try {
4347
- JSON.parse(text);
4348
- } catch (e) {
4349
- complete = false;
4350
- }
4351
- return redactJsonLike(text, complete);
4352
- }
4353
- var NO_SPAN_PII_FIELDS = { exact: /* @__PURE__ */ new Set(), prefixes: [] };
4354
- function compileSpanPiiFields(names, logPrefix = "[raindrop-ai/core]") {
4355
- if (!Array.isArray(names) || names.length === 0) return NO_SPAN_PII_FIELDS;
4356
- const exact = /* @__PURE__ */ new Set();
4357
- const prefixes = [];
4358
- for (const name of names) {
4359
- const valid = typeof name === "string" && !/\s/.test(name) && /^[^*]+\*?$/.test(name);
4360
- if (!valid) {
4361
- rateLimitedLog(
4362
- `${logPrefix}.pii_span_field_invalid`,
4363
- () => console.warn(
4364
- `${logPrefix} redactPiiFields: ignoring invalid span attribute ${JSON.stringify(name)}`
4365
- )
4366
- );
4367
- continue;
4368
- }
4369
- if (name.endsWith("*")) prefixes.push(name.slice(0, -1));
4370
- else exact.add(name);
4371
- }
4372
- return { exact, prefixes };
4373
- }
4374
- function isCallerSelected(key, fields) {
4375
- return fields.exact.has(key) || fields.prefixes.some((prefix) => key.startsWith(prefix));
4376
- }
4377
- function isSpanContentAttributeKey(key, fields = NO_SPAN_PII_FIELDS) {
4378
- if (isCallerSelected(key, fields)) return true;
4379
- if (NON_CONTENT_PREFIXES.some((prefix) => key.startsWith(prefix))) return false;
4380
- return CONTENT_KEYS.has(key) || CONTENT_KEY_SUFFIX.test(key);
4381
- }
4382
- function redactOtlpValue(value) {
4383
- var _a;
4384
- if (typeof value.stringValue === "string") {
4385
- const redacted = redactSpanContent(value.stringValue);
4386
- return redacted === value.stringValue ? value : { ...value, stringValue: redacted };
4387
- }
4388
- const values = (_a = value.arrayValue) == null ? void 0 : _a.values;
4389
- if (!values) return value;
4390
- let changed = false;
4391
- const next = values.map((item) => {
4392
- const redacted = redactOtlpValue(item);
4393
- if (redacted !== item) changed = true;
4394
- return redacted;
4395
- });
4396
- return changed ? { ...value, arrayValue: { values: next } } : value;
4397
- }
4398
- function redactPiiInOtlpAttributes(attributes, fields = NO_SPAN_PII_FIELDS) {
4399
- let next;
4400
- for (let i = 0; i < attributes.length; i++) {
4401
- const attr = attributes[i];
4402
- if (!attr.value || !isSpanContentAttributeKey(attr.key, fields)) continue;
4403
- const value = redactOtlpValue(attr.value);
4404
- if (value === attr.value) continue;
4405
- next != null ? next : next = attributes.slice();
4406
- next[i] = { ...attr, value };
4407
- }
4408
- return next != null ? next : attributes;
4409
- }
4410
- function redactPiiInOtlpSpan(span, fields = NO_SPAN_PII_FIELDS) {
4411
- var _a;
4412
- const attributes = span.attributes && redactPiiInOtlpAttributes(span.attributes, fields);
4413
- const message = (_a = span.status) == null ? void 0 : _a.message;
4414
- const redactedMessage = message === void 0 ? void 0 : redactSpanContent(message);
4415
- if (attributes === span.attributes && redactedMessage === message) return span;
4416
- const status = span.status && redactedMessage !== message ? { ...span.status, message: redactedMessage } : span.status;
4417
- return { ...span, attributes, status };
4418
- }
4419
- function redactPiiInAttributeMap(attributes, fields = NO_SPAN_PII_FIELDS) {
4420
- let next;
4421
- for (const [key, value] of Object.entries(attributes)) {
4422
- if (!isSpanContentAttributeKey(key, fields)) continue;
4423
- let redacted = value;
4424
- if (typeof value === "string") {
4425
- redacted = redactSpanContent(value);
4426
- } else if (Array.isArray(value)) {
4427
- let changed = false;
4428
- const items = value.map((item) => {
4429
- if (typeof item !== "string") return item;
4430
- const out = redactSpanContent(item);
4431
- if (out !== item) changed = true;
4432
- return out;
4433
- });
4434
- if (changed) redacted = items;
4435
- }
4436
- if (redacted === value) continue;
4437
- next != null ? next : next = { ...attributes };
4438
- next[key] = redacted;
4439
- }
4440
- return next;
4441
- }
4442
4861
  var UNDELIVERED = Object.freeze({
4443
4862
  delivered: false,
4444
4863
  timedOut: false,
@@ -8896,7 +9315,7 @@ var SignalEventSchema = external_exports.object({
8896
9315
  // package.json
8897
9316
  var package_default = {
8898
9317
  name: "raindrop-ai",
8899
- version: "1.0.8",
9318
+ version: "1.0.9",
8900
9319
  main: "dist/index.js",
8901
9320
  module: "dist/index.mjs",
8902
9321
  types: "dist/index.d.ts",
@@ -9122,17 +9541,17 @@ var ReplayRoutingSpanExporter = class {
9122
9541
  return;
9123
9542
  }
9124
9543
  let remaining = replayGroups.size + (normalSpans.length > 0 ? 1 : 0);
9125
- let failed = false;
9544
+ let failed2 = false;
9126
9545
  let firstError;
9127
9546
  const finish = (result) => {
9128
9547
  if (result.code !== EXPORT_SUCCESS) {
9129
- failed = true;
9548
+ failed2 = true;
9130
9549
  firstError != null ? firstError : firstError = result.error;
9131
9550
  }
9132
9551
  remaining -= 1;
9133
9552
  if (remaining === 0) {
9134
9553
  resultCallback(
9135
- firstError ? { code: EXPORT_FAILED, error: firstError } : { code: failed ? EXPORT_FAILED : EXPORT_SUCCESS }
9554
+ firstError ? { code: EXPORT_FAILED, error: firstError } : { code: failed2 ? EXPORT_FAILED : EXPORT_SUCCESS }
9136
9555
  );
9137
9556
  }
9138
9557
  };
@@ -9619,6 +10038,7 @@ var DirectTraceShipper = class {
9619
10038
  this.redactTracePii = opts.redactTracePii;
9620
10039
  this.remotePiiConfig = opts.remotePiiConfig;
9621
10040
  this.spanPiiFields = opts.spanPiiFields;
10041
+ this.mask = opts.mask;
9622
10042
  this.flushIntervalMs = (_d = opts.flushIntervalMs) != null ? _d : 1e3;
9623
10043
  this.maxBatchSize = (_e = opts.maxBatchSize) != null ? _e : 50;
9624
10044
  this.maxQueueSize = (_f = opts.maxQueueSize) != null ? _f : 5e3;
@@ -9725,7 +10145,7 @@ var DirectTraceShipper = class {
9725
10145
  const mirrorUrl = (replayDestination == null ? void 0 : replayDestination.kind) === "workshop" ? replayDestination.url : replayDestination ? void 0 : this.localDebuggerUrl;
9726
10146
  const mirrored = mirrorUrl && this.redactsNow() ? this.redactSpanPii(span) : span;
9727
10147
  if (mirrorUrl && mirrored) {
9728
- const body = buildExportTraceServiceRequest2([mirrored]);
10148
+ const body = buildExportTraceServiceRequest2([maskOtlpSpan(mirrored, this.mask, this.spanPiiFields, "[raindrop]")]);
9729
10149
  const mirror = mirrorTraceExportToLocalDebugger(body, {
9730
10150
  baseUrl: mirrorUrl,
9731
10151
  debug: false,
@@ -9751,7 +10171,7 @@ var DirectTraceShipper = class {
9751
10171
  /** The span with PII redacted from its input and output; undefined if redaction failed. */
9752
10172
  redactSpanPii(span) {
9753
10173
  try {
9754
- return redactPiiInOtlpSpan(span, this.spanPiiFields);
10174
+ return redactPiiInOtlpSpan(span, this.spanPiiFields, resolveMaxTextFieldChars(void 0));
9755
10175
  } catch (e) {
9756
10176
  return void 0;
9757
10177
  }
@@ -9850,10 +10270,10 @@ var DirectTraceShipper = class {
9850
10270
  if (!replayDestination && !this.cloudEnabled) continue;
9851
10271
  if ((replayDestination == null ? void 0 : replayDestination.kind) === "workshop") continue;
9852
10272
  const spans = queuedSpans.map((q) => q.span);
9853
- const outgoing = redactPii ? spans.flatMap((span) => {
10273
+ const outgoing = (redactPii ? spans.flatMap((span) => {
9854
10274
  var _a2;
9855
10275
  return (_a2 = this.redactSpanPii(span)) != null ? _a2 : [];
9856
- }) : spans;
10276
+ }) : spans).map((span) => maskOtlpSpan(span, this.mask, this.spanPiiFields, "[raindrop]"));
9857
10277
  if (outgoing.length === 0) continue;
9858
10278
  const body = buildExportTraceServiceRequest2(outgoing);
9859
10279
  const url = replayDestination ? replayTraceUrl(replayDestination.url) : `${this.baseUrl}traces`;
@@ -9986,6 +10406,34 @@ function redactSpanPii(span, fields) {
9986
10406
  copyReplayTraceDestination(span, view);
9987
10407
  return view;
9988
10408
  }
10409
+ function maskSpan(span, mask, fields) {
10410
+ const attributes = maskAttributeMap(span.attributes, mask, fields, "[raindrop]");
10411
+ const message = span.status.message;
10412
+ const nextMessage = message === void 0 ? void 0 : maskSpanStatusMessage(message, mask, "[raindrop]");
10413
+ let eventsChanged = false;
10414
+ const events = span.events.map((event) => {
10415
+ const eventAttributes = event.attributes && maskAttributeMap(event.attributes, mask, fields, "[raindrop]");
10416
+ if (!eventAttributes) return event;
10417
+ eventsChanged = true;
10418
+ return { ...event, attributes: eventAttributes };
10419
+ });
10420
+ if (!attributes && nextMessage === message && !eventsChanged) return span;
10421
+ const view = Object.create(span);
10422
+ if (attributes) {
10423
+ Object.defineProperty(view, "attributes", { value: attributes, enumerable: true });
10424
+ }
10425
+ if (nextMessage !== message) {
10426
+ Object.defineProperty(view, "status", {
10427
+ value: { ...span.status, message: nextMessage },
10428
+ enumerable: true
10429
+ });
10430
+ }
10431
+ if (eventsChanged) {
10432
+ Object.defineProperty(view, "events", { value: events, enumerable: true });
10433
+ }
10434
+ copyReplayTraceDestination(span, view);
10435
+ return view;
10436
+ }
9989
10437
  var PiiRedactingSpanExporter = class {
9990
10438
  constructor(inner, options) {
9991
10439
  this.inner = inner;
@@ -9994,7 +10442,7 @@ var PiiRedactingSpanExporter = class {
9994
10442
  this.pending = /* @__PURE__ */ new Set();
9995
10443
  }
9996
10444
  export(spans, resultCallback) {
9997
- const { local, remote, apiUrl, writeKey, spanFields } = this.options;
10445
+ const { local, remote, apiUrl, writeKey, spanFields, mask } = this.options;
9998
10446
  const exportContext = import_api2.context.active();
9999
10447
  const run = (redact) => {
10000
10448
  let outgoing = spans;
@@ -10007,6 +10455,7 @@ var PiiRedactingSpanExporter = class {
10007
10455
  }
10008
10456
  }
10009
10457
  }
10458
+ if (mask) outgoing = outgoing.map((span) => maskSpan(span, mask, spanFields));
10010
10459
  try {
10011
10460
  import_api2.context.with(exportContext, () => this.inner.export(outgoing, resultCallback));
10012
10461
  } catch (e) {
@@ -12408,6 +12857,7 @@ var tracing = (analytics, apiUrl, writeKey, options, isDebug = false) => {
12408
12857
  redactTracePii,
12409
12858
  redactPiiFields,
12410
12859
  remotePiiConfig,
12860
+ mask,
12411
12861
  ...otherOptions
12412
12862
  } = options;
12413
12863
  const cloudEnabledResolved = cloudEnabled != null ? cloudEnabled : true;
@@ -12426,7 +12876,8 @@ var tracing = (analytics, apiUrl, writeKey, options, isDebug = false) => {
12426
12876
  remote: remotePiiConfig,
12427
12877
  apiUrl: directEndpoint != null ? directEndpoint : apiUrl,
12428
12878
  writeKey: cloudEnabledResolved ? writeKey : void 0,
12429
- spanFields: spanPiiFields
12879
+ spanFields: spanPiiFields,
12880
+ mask: typeof mask === "function" ? mask : void 0
12430
12881
  };
12431
12882
  if (localTracePii === true) {
12432
12883
  requestLocalTracePiiRedaction(piiRedaction2.apiUrl, piiRedaction2.writeKey);
@@ -12463,7 +12914,8 @@ var tracing = (analytics, apiUrl, writeKey, options, isDebug = false) => {
12463
12914
  flushTimeoutMs,
12464
12915
  redactTracePii: localTracePii,
12465
12916
  remotePiiConfig,
12466
- spanPiiFields
12917
+ spanPiiFields,
12918
+ mask: piiRedaction2.mask
12467
12919
  }) : void 0;
12468
12920
  let traceloopInitialized = false;
12469
12921
  let claimedPipeline = false;
@@ -16031,6 +16483,7 @@ var Raindrop = class {
16031
16483
  prefix: "[raindrop]"
16032
16484
  });
16033
16485
  this.redactPii = config.redactPii;
16486
+ this.mask = typeof config.mask === "function" ? config.mask : void 0;
16034
16487
  this.remotePiiConfig = config.remotePiiConfig;
16035
16488
  this.piiFields = new PiiFieldRedactor({
16036
16489
  startupFieldMap: config.redactPiiFields,
@@ -16071,6 +16524,7 @@ var Raindrop = class {
16071
16524
  maxTextFieldChars: config.maxTextFieldChars,
16072
16525
  redactPii: this.redactPii,
16073
16526
  redactPiiFields: config.redactPiiFields,
16527
+ mask: this.mask,
16074
16528
  remotePiiConfig: this.remotePiiConfig,
16075
16529
  wizardSession: (_j = this.wizardSession) != null ? _j : void 0,
16076
16530
  flushTimeoutMs: this.flushTimeoutMs
@@ -16099,7 +16553,8 @@ var Raindrop = class {
16099
16553
  flushTimeoutMs: this.flushTimeoutMs,
16100
16554
  redactTracePii: config.redactTracePii,
16101
16555
  redactPiiFields: config.redactPiiFields,
16102
- remotePiiConfig: this.remotePiiConfig
16556
+ remotePiiConfig: this.remotePiiConfig,
16557
+ mask: this.mask
16103
16558
  },
16104
16559
  this.debugLogs
16105
16560
  );
@@ -16708,7 +17163,10 @@ var Raindrop = class {
16708
17163
  rows = rows.map(snapshotPayload);
16709
17164
  redact = await piiRedaction(this.redactPii, this.remotePiiConfig, this.apiUrl, writeKey, deadlineAt);
16710
17165
  }
16711
- const body = rows.map((event) => redact && kind ? this.piiFields.redact(kind, event) : event);
17166
+ const body = rows.map((event) => {
17167
+ const redacted = redact && kind ? this.piiFields.redact(kind, event) : event;
17168
+ return kind && isRecord3(redacted) ? maskPayload(kind, redacted, this.mask, "[raindrop]") : redacted;
17169
+ });
16712
17170
  this.mirrorBatchToLocalDebugger(endpoint, body);
16713
17171
  if (this.localOnly) {
16714
17172
  return void 0;