@agentsky/sky 3.48.2 → 3.49.0

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.
Files changed (35) hide show
  1. package/dist/{chunk-W24YSGH4.js → chunk-2YUZZ5VG.js} +7 -856
  2. package/dist/{chunk-ZRV3UUW5.js → chunk-6LRSRXQI.js} +1 -1
  3. package/dist/{chunk-PGX3AGCZ.js → chunk-7JFTEJ7B.js} +1 -1
  4. package/dist/chunk-BKNZQZZD.js +857 -0
  5. package/dist/{chunk-RKMMLSGJ.js → chunk-CK7N635F.js} +1 -1
  6. package/dist/{chunk-NAIYHS6Q.js → chunk-HFWHVU72.js} +2 -1
  7. package/dist/{chunk-A45NGV2Q.js → chunk-HGL7TLNA.js} +2 -2
  8. package/dist/{chunk-ZF2P6PKM.js → chunk-HNUY5PBQ.js} +2 -2
  9. package/dist/{chunk-OJ5ERABF.js → chunk-IO2N34S2.js} +1 -1
  10. package/dist/{chunk-UJS4JIE2.js → chunk-JMGVHVOS.js} +10 -10
  11. package/dist/{chunk-CV2ZRIF7.js → chunk-QTE5OMZY.js} +4 -4
  12. package/dist/{chunk-FVIPGI3E.js → chunk-RVI7ZWR2.js} +5 -5
  13. package/dist/chunk-TGU7T4O7.js +1363 -0
  14. package/dist/{chunk-NJPIE762.js → chunk-UYBKORXA.js} +43 -24
  15. package/dist/chunk-YO2XUCCF.js +30 -0
  16. package/dist/{chunk-6D36IT7T.js → chunk-ZOXE2XNH.js} +2 -2
  17. package/dist/{compute-AERPKXJ3.js → compute-4MMGFJGE.js} +2 -2
  18. package/dist/{compute-report-CTT4WBSQ.js → compute-report-LIMMRQY3.js} +15 -13
  19. package/dist/grok-bot-export-7LSTXWJW.js +57 -0
  20. package/dist/index.js +599 -1770
  21. package/dist/{local-skills-E56TR7O6.js → local-skills-5LJST7EP.js} +3 -3
  22. package/dist/{local-skills-run-TST44QSA.js → local-skills-run-6SZJQSVF.js} +9 -9
  23. package/dist/{mcp-register-HDOVT4QT.js → mcp-register-XY4MR3ZZ.js} +3 -3
  24. package/dist/{mcp-serve-2LBAEAJX.js → mcp-serve-QROKKUJV.js} +6 -6
  25. package/dist/{trace-S2XZC75N.js → trace-SJZ25T35.js} +4 -3
  26. package/dist/{trace-exclusions-JEGMUPWQ.js → trace-exclusions-IC6OA2ND.js} +3 -2
  27. package/dist/trace-handoff-CD5LOS7B.js +116 -0
  28. package/dist/{trace-library-HN5TU5EJ.js → trace-library-V23TEXG4.js} +14 -8
  29. package/dist/trace-privacy-DU3TL5EO.js +11 -0
  30. package/package.json +1 -1
  31. package/vendor/trace-collect/SOURCE.json +2 -1
  32. package/vendor/trace-collect/sources/_pii.mjs +56 -0
  33. package/vendor/trace-collect/sources/grok-bot.mjs +180 -0
  34. package/vendor/trace-collect/sources/index.mjs +4 -2
  35. package/vendor/trace-collect/sources/muse-agent.mjs +95 -0
@@ -0,0 +1,857 @@
1
+ // ../../packages/spec/src/import-base64.ts
2
+ function isCanonicalBase64(value) {
3
+ if (value.length === 0 || value.length % 4 !== 0) return false;
4
+ const padding = value.endsWith("==") ? 2 : value.endsWith("=") ? 1 : 0;
5
+ for (let index = 0; index < value.length - padding; index += 1) {
6
+ const code = value.charCodeAt(index);
7
+ const alphabet = code >= 65 && code <= 90 || code >= 97 && code <= 122 || code >= 48 && code <= 57 || code === 43 || code === 47;
8
+ if (!alphabet) return false;
9
+ }
10
+ return Buffer.from(value, "base64").toString("base64") === value;
11
+ }
12
+
13
+ // ../../packages/spec/src/card-scrub.ts
14
+ var CARD_NUMBER_MASK = "[card number]";
15
+ var CARD_CODE_MASK = "[card code]";
16
+ var DIGIT_RUN = /(?<![\d])(?:\d[ -]?){12,18}\d(?![\d])/g;
17
+ var CODE_FIELD = /\b(cvc|cvv|cvc2|cvv2|security[ _-]?code|card[ _-]?code)\b(["']?\s*[:=]\s*["']?)(\d{3,4})\b/gi;
18
+ function luhnValid(digits) {
19
+ let sum = 0;
20
+ let double = false;
21
+ for (let i = digits.length - 1; i >= 0; i -= 1) {
22
+ let d = digits.charCodeAt(i) - 48;
23
+ if (d < 0 || d > 9) return false;
24
+ if (double) {
25
+ d *= 2;
26
+ if (d > 9) d -= 9;
27
+ }
28
+ sum += d;
29
+ double = !double;
30
+ }
31
+ return digits.length >= 13 && sum % 10 === 0;
32
+ }
33
+ var digitsOf = (run) => run.replace(/[ -]/g, "");
34
+ function isCardNumber(run, known) {
35
+ const digits = digitsOf(run);
36
+ return known.has(digits) || luhnValid(digits);
37
+ }
38
+ function scrubCardData(text, known = []) {
39
+ const knownDigits = new Set([...known].map(digitsOf));
40
+ return text.replace(DIGIT_RUN, (run) => isCardNumber(run, knownDigits) ? CARD_NUMBER_MASK : run).replace(CODE_FIELD, (_all, label, sep) => `${label}${sep}${CARD_CODE_MASK}`);
41
+ }
42
+ function holdsCardNumber(text, known = []) {
43
+ const knownDigits = new Set([...known].map(digitsOf));
44
+ for (const match of text.matchAll(DIGIT_RUN)) if (isCardNumber(match[0], knownDigits)) return true;
45
+ return false;
46
+ }
47
+
48
+ // ../../packages/spec/src/import-redact.ts
49
+ function ci(word) {
50
+ return word.split("").map((c) => /[a-z]/i.test(c) ? `[${c.toUpperCase()}${c.toLowerCase()}]` : c).join("");
51
+ }
52
+ var UnsafeImportError = class extends Error {
53
+ };
54
+ var TEXT_ATTACHMENT_MEDIA_TYPES = [
55
+ "application/json",
56
+ "application/xml",
57
+ "application/javascript",
58
+ "application/ecmascript",
59
+ "application/x-javascript",
60
+ "application/yaml",
61
+ "application/x-yaml",
62
+ "application/x-www-form-urlencoded",
63
+ "image/svg+xml",
64
+ "application/toml",
65
+ "application/x-toml",
66
+ "application/sql",
67
+ "application/x-sql",
68
+ "application/pem-certificate-chain",
69
+ "application/x-pem-file",
70
+ "application/x-pem-key",
71
+ "application/x-ndjson",
72
+ "application/ndjson"
73
+ ];
74
+ var textAttachmentMediaTypes = new Set(TEXT_ATTACHMENT_MEDIA_TYPES);
75
+ function isTextMediaType(value) {
76
+ const media = typeof value === "string" ? value.split(";", 1)[0].trim().toLowerCase() : "";
77
+ return media.startsWith("text/") || textAttachmentMediaTypes.has(media) || /\+(?:json|xml)$/.test(media);
78
+ }
79
+ var MASK = "\u25CF\u25CF\u25CF\u25CF\u25CF";
80
+ var SECRET_PATTERNS = [
81
+ { name: "anthropic key", source: "(?<![A-Za-z0-9_])(sk-ant-)[A-Za-z0-9_-]{10,}", replacement: `\\1${MASK}` },
82
+ { name: "openai key", source: "(?<![A-Za-z0-9_])(sk-proj-|sk-)[A-Za-z0-9_-]{8,}", replacement: `\\1${MASK}` },
83
+ { name: "github token", source: "(?<![A-Za-z0-9_])(gh[pousr]_)[A-Za-z0-9]{16,}", replacement: `\\1${MASK}` },
84
+ { name: "github fine-grained token", source: "(?<![A-Za-z0-9_])(github_pat_)[A-Za-z0-9_]{20,}", replacement: `\\1${MASK}` },
85
+ { name: "slack token", source: "(?<![A-Za-z0-9_])(xox[abeprs]-|xapp-)[A-Za-z0-9-]{10,}", replacement: `\\1${MASK}` },
86
+ { name: "agentsky token", source: "(?<![A-Za-z0-9_])(ast_)[A-Za-z0-9_-]{10,}", replacement: `\\1${MASK}` },
87
+ { name: "guild broker token", source: "(?<![A-Za-z0-9_])(gbk_)[A-Za-z0-9_-]{10,}", replacement: `\\1${MASK}` },
88
+ { name: "jwt", source: "(?<![A-Za-z0-9_])eyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]*", replacement: MASK },
89
+ { name: "private key", source: "-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\\s\\S]*?(?:-----END [A-Z0-9 ]*PRIVATE KEY-----|$)", replacement: MASK },
90
+ { name: "google oauth token", source: "(ya29\\.)[A-Za-z0-9_-]{20,}", replacement: `\\1${MASK}` },
91
+ { name: "google api key", source: "(?<![A-Za-z0-9_])(AIza)[A-Za-z0-9_-]{30,}", replacement: `\\1${MASK}` },
92
+ { name: "aws key id", source: "(?<![A-Za-z0-9_])(AKIA)[0-9A-Z]{16}(?![A-Za-z0-9_])", replacement: `\\1${MASK}` },
93
+ { name: "import key", source: "(agt_)[A-Za-z0-9_-]{20,}", replacement: `\\1${MASK}` },
94
+ {
95
+ name: "database url",
96
+ source: "(postgres://|postgresql://|mysql://|mongodb\\+srv://|mongodb://|redis://)([^:@/ ]+):[^@ ]+@",
97
+ replacement: `\\1\\2:${MASK}@`
98
+ },
99
+ { name: "bearer header", source: `(?<![A-Za-z0-9_])(${ci("bearer")}\\s+)[A-Za-z0-9._~+/=-]{16,}`, replacement: `\\1${MASK}` },
100
+ { name: "api key header", source: `(${ci("x-api-key")}: )[A-Za-z0-9_.=-]{16,}`, replacement: `\\1${MASK}` }
101
+ ];
102
+ var compiled = SECRET_PATTERNS.map((p) => ({
103
+ name: p.name,
104
+ re: new RegExp(p.source, "g"),
105
+ replacement: p.replacement.replace(/\\(\d)/g, "$$$1")
106
+ }));
107
+ function asPlainDecimal(token) {
108
+ const m = /^([+-]?)(\d+)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/.exec(token);
109
+ if (!m) return null;
110
+ const [, sign, whole, fraction = "", exponent = "0"] = m;
111
+ const digits = whole + fraction;
112
+ if (Math.abs(Number(exponent)) > 400) return /[1-9]/.test(digits) ? null : "0";
113
+ let pointAt = whole.length + Number(exponent);
114
+ let padded = digits;
115
+ if (pointAt <= 0) {
116
+ padded = "0".repeat(1 - pointAt) + digits;
117
+ pointAt += 1 - pointAt;
118
+ }
119
+ if (pointAt >= padded.length) padded += "0".repeat(pointAt - padded.length + 1);
120
+ const intPart = padded.slice(0, pointAt).replace(/^0+(?=\d)/, "");
121
+ const fracPart = padded.slice(pointAt).replace(/0+$/, "");
122
+ const value = fracPart ? `${intPart}.${fracPart}` : intPart;
123
+ return (sign === "-" && /[1-9]/.test(digits) ? "-" : "") + value;
124
+ }
125
+ function changesWhenRead(token) {
126
+ const value = Number(token);
127
+ if (!Number.isFinite(value)) return true;
128
+ const mine = asPlainDecimal(token);
129
+ const theirs = asPlainDecimal(String(value));
130
+ if (mine === null) return /[1-9]/.test(token);
131
+ if (theirs === null) return true;
132
+ return mine !== theirs;
133
+ }
134
+ function unsafeNumberSpans(line) {
135
+ const spans = [];
136
+ let inString = false;
137
+ for (let i = 0; i < line.length; i += 1) {
138
+ const c = line[i];
139
+ if (inString) {
140
+ if (c === "\\") i += 1;
141
+ else if (c === '"') inString = false;
142
+ continue;
143
+ }
144
+ if (c === '"') {
145
+ inString = true;
146
+ continue;
147
+ }
148
+ if (c !== "-" && (c < "0" || c > "9")) continue;
149
+ const start = i;
150
+ if (c === "-") i += 1;
151
+ while (i < line.length && line[i] >= "0" && line[i] <= "9") i += 1;
152
+ if (line[i] === ".") {
153
+ i += 1;
154
+ while (i < line.length && line[i] >= "0" && line[i] <= "9") i += 1;
155
+ }
156
+ if (line[i] === "e" || line[i] === "E") {
157
+ i += 1;
158
+ if (line[i] === "+" || line[i] === "-") i += 1;
159
+ while (i < line.length && line[i] >= "0" && line[i] <= "9") i += 1;
160
+ }
161
+ const token = line.slice(start, i);
162
+ if (changesWhenRead(token)) spans.push([start, i]);
163
+ i -= 1;
164
+ }
165
+ return spans;
166
+ }
167
+ function withPreservedNumbers(line) {
168
+ const spans = unsafeNumberSpans(line);
169
+ if (spans.length === 0) return { parse: () => JSON.parse(line), serialize: (v) => JSON.stringify(v) };
170
+ let sentinel = "n";
171
+ while (line.includes(`@@${sentinel}`)) sentinel += "n";
172
+ const token = (index) => `@@${sentinel}${index}@@`;
173
+ let out = "";
174
+ let cursor = 0;
175
+ const originals = [];
176
+ spans.forEach(([start, end], index) => {
177
+ out += line.slice(cursor, start) + JSON.stringify(token(index));
178
+ originals.push(line.slice(start, end));
179
+ cursor = end;
180
+ });
181
+ out += line.slice(cursor);
182
+ return {
183
+ parse: () => JSON.parse(out),
184
+ serialize: (value) => {
185
+ let text = JSON.stringify(value);
186
+ originals.forEach((original, index) => {
187
+ text = text.split(JSON.stringify(token(index))).join(original);
188
+ });
189
+ return text;
190
+ }
191
+ };
192
+ }
193
+ function hasDuplicateJsonKeys(line) {
194
+ const stack = [];
195
+ const skipSpace = (at) => {
196
+ while (at < line.length && /\s/.test(line[at])) at += 1;
197
+ return at;
198
+ };
199
+ for (let i = 0; i < line.length; i += 1) {
200
+ const c = line[i];
201
+ if (c === '"') {
202
+ const start = i;
203
+ i += 1;
204
+ while (i < line.length) {
205
+ if (line[i] === "\\") {
206
+ i += 2;
207
+ continue;
208
+ }
209
+ if (line[i] === '"') break;
210
+ i += 1;
211
+ }
212
+ const frame = stack[stack.length - 1];
213
+ const colon = skipSpace(i + 1);
214
+ if (frame?.kind === "object" && frame.expectingKey && line[colon] === ":") {
215
+ try {
216
+ const key = JSON.parse(line.slice(start, i + 1));
217
+ if (frame.keys.has(key)) return true;
218
+ frame.keys.add(key);
219
+ frame.expectingKey = false;
220
+ } catch {
221
+ }
222
+ }
223
+ continue;
224
+ }
225
+ if (c === "{") stack.push({ kind: "object", expectingKey: true, keys: /* @__PURE__ */ new Set() });
226
+ else if (c === "[") stack.push({ kind: "array", expectingKey: false });
227
+ else if (c === "}" || c === "]") stack.pop();
228
+ else if (c === "," && stack.at(-1)?.kind === "object") stack.at(-1).expectingKey = true;
229
+ }
230
+ return false;
231
+ }
232
+ var FIELD_ASSIGNMENTS = new RegExp(
233
+ String.raw`(?<![A-Za-z0-9_.])(\\{0,8}["']?([A-Za-z_][A-Za-z0-9_.-]{0,255})\\{0,8}["']?\s{0,8}\\{0,8}[:=]\\{0,8}\s{0,8}\\{0,8}(["']?))`,
234
+ "g"
235
+ );
236
+ var JSON_NUMBER = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/;
237
+ var COMPLETE_MASKED_VALUE = new RegExp(`^(?:${MASK}|${ci("bearer")} ${MASK})$`);
238
+ function codeIdentifierEnd(value, at) {
239
+ if (!/[A-Za-z_$]/.test(value[at] ?? "")) return -1;
240
+ at += 1;
241
+ while (/[A-Za-z0-9_$]/.test(value[at] ?? "")) at += 1;
242
+ return at;
243
+ }
244
+ function codeGroupEnd(value, at) {
245
+ const pairs = { "(": ")", "[": "]", "{": "}" };
246
+ const stack = [pairs[value[at]]];
247
+ for (let i = at + 1; i < value.length; i += 1) {
248
+ const c = value[i];
249
+ if (c === '"' || c === "'" || c === "`") {
250
+ for (i += 1; i < value.length; i += 1) {
251
+ if (value[i] === "\\") i += 1;
252
+ else if (value[i] === c) break;
253
+ }
254
+ if (i >= value.length) return -1;
255
+ continue;
256
+ }
257
+ if (pairs[c]) stack.push(pairs[c]);
258
+ else if (c === ")" || c === "]" || c === "}") {
259
+ if (stack.pop() !== c) return -1;
260
+ if (stack.length === 0) return i + 1;
261
+ }
262
+ }
263
+ return -1;
264
+ }
265
+ function credentialRhsBoundary(value, start, lineEnd) {
266
+ const pairs = { "(": ")", "[": "]", "{": "}" };
267
+ const stack = [];
268
+ for (let i = start; i < lineEnd; i += 1) {
269
+ const c = value[i];
270
+ if (c === '"' || c === "'" || c === "`") {
271
+ for (i += 1; i < lineEnd; i += 1) {
272
+ if (value[i] === "\\") i += 1;
273
+ else if (value[i] === c) break;
274
+ }
275
+ if (i >= lineEnd) return { end: lineEnd, unsafe: true };
276
+ continue;
277
+ }
278
+ if (c === "/") return { end: lineEnd, unsafe: true };
279
+ if (pairs[c]) stack.push(pairs[c]);
280
+ else if (c === ")" || c === "]" || c === "}") {
281
+ if (stack.pop() !== c) return { end: lineEnd, unsafe: true };
282
+ }
283
+ }
284
+ return { end: lineEnd, unsafe: stack.length > 0 };
285
+ }
286
+ function maskExpressionLiterals(value) {
287
+ let out = "";
288
+ const groups = [];
289
+ let previousNonWhitespace = "";
290
+ for (let i = 0; i < value.length; i += 1) {
291
+ const c = value[i];
292
+ if (c === "(" || c === "{") {
293
+ groups.push(c);
294
+ out += c;
295
+ previousNonWhitespace = c;
296
+ continue;
297
+ }
298
+ if (c === "[") {
299
+ let kind = /[A-Za-z0-9_$.)\]}]/.test(previousNonWhitespace) ? "index" : "array";
300
+ if (kind === "index") {
301
+ const end = codeGroupEnd(value, i);
302
+ if (end < 0) return null;
303
+ const content = value.slice(i + 1, end - 1).trim();
304
+ if (/^[-+.0-9]/.test(content) && !/^(?:0|[1-9][0-9]*)$/.test(content)) return null;
305
+ if (/^(?:0|[1-9][0-9]*)$/.test(content)) kind = "index-number";
306
+ }
307
+ groups.push(kind);
308
+ out += c;
309
+ previousNonWhitespace = c;
310
+ continue;
311
+ }
312
+ if (c === ")" || c === "]" || c === "}") {
313
+ groups.pop();
314
+ out += c;
315
+ previousNonWhitespace = c;
316
+ continue;
317
+ }
318
+ const previousIsIdentifier = i > 0 && /[A-Za-z0-9_$]/.test(value[i - 1]);
319
+ const numberLooking = !previousIsIdentifier && (/[0-9]/.test(c) || c === "." && /[0-9]/.test(value[i + 1] ?? "") || (c === "+" || c === "-") && (/[0-9]/.test(value[i + 1] ?? "") || value[i + 1] === "." && /[0-9]/.test(value[i + 2] ?? "")));
320
+ if (numberLooking && groups.at(-1) !== "index-number") return null;
321
+ if (c !== '"' && c !== "'" && c !== "`") {
322
+ out += c;
323
+ if (!/\s/.test(c)) previousNonWhitespace = c;
324
+ continue;
325
+ }
326
+ const start = i;
327
+ for (i += 1; i < value.length; i += 1) {
328
+ if (value[i] === "\\") i += 1;
329
+ else if (value[i] === c) break;
330
+ }
331
+ const literal = value.slice(start, i + 1);
332
+ out += groups.at(-1)?.startsWith("index") ? literal : `${c}${MASK}${c}`;
333
+ previousNonWhitespace = c;
334
+ }
335
+ return out;
336
+ }
337
+ function rewriteCodeExpression(value, declaration) {
338
+ let source = value.trim();
339
+ const semicolon = source.endsWith(";");
340
+ if (semicolon) source = source.slice(0, -1).trimEnd();
341
+ if (/^(?:null|undefined)$/.test(source)) return value;
342
+ if (source.startsWith("`")) {
343
+ if (codeGroupEnd(`(${source})`, 0) !== source.length + 2) return null;
344
+ return value.replace(source, `\`${MASK}\``);
345
+ }
346
+ const awaitPrefix = /^await\s+/.exec(source)?.[0] ?? "";
347
+ if (awaitPrefix) source = source.slice(awaitPrefix.length);
348
+ if (source.startsWith("[") || source.startsWith("{")) {
349
+ if (codeGroupEnd(source, 0) !== source.length) return null;
350
+ const full2 = semicolon ? `${MASK};` : MASK;
351
+ return value.replace(value.trim(), full2);
352
+ }
353
+ let at = codeIdentifierEnd(source, 0);
354
+ if (at < 0) return null;
355
+ let syntax = false;
356
+ while (at < source.length) {
357
+ if (source.startsWith("?.", at)) {
358
+ at += 2;
359
+ if (source[at] === "[" || source[at] === "(") {
360
+ const end2 = codeGroupEnd(source, at);
361
+ if (end2 < 0) return null;
362
+ syntax = true;
363
+ at = end2;
364
+ continue;
365
+ }
366
+ } else if (source[at] === ".") at += 1;
367
+ else if (source[at] === "[" || source[at] === "(") {
368
+ const end2 = codeGroupEnd(source, at);
369
+ if (end2 < 0) return null;
370
+ syntax = true;
371
+ at = end2;
372
+ continue;
373
+ } else return null;
374
+ const end = codeIdentifierEnd(source, at);
375
+ if (end < 0) return null;
376
+ syntax = true;
377
+ at = end;
378
+ }
379
+ if (!syntax && !declaration) return null;
380
+ const rewritten = maskExpressionLiterals(source);
381
+ if (rewritten === null) return null;
382
+ const full = semicolon ? `${awaitPrefix}${rewritten};` : `${awaitPrefix}${rewritten}`;
383
+ return value.replace(value.trim(), full);
384
+ }
385
+ function redactSecretValues(text) {
386
+ const hits = {};
387
+ let out = text;
388
+ for (const p of compiled) {
389
+ p.re.lastIndex = 0;
390
+ out = out.replace(p.re, (...m) => {
391
+ hits[p.name] = (hits[p.name] ?? 0) + 1;
392
+ return p.replacement.replace(/\$(\d)/g, (_, i) => String(m[Number(i)] ?? ""));
393
+ });
394
+ }
395
+ return { text: out, hits };
396
+ }
397
+ function redactPlainText(text) {
398
+ const hits = {};
399
+ let out = redactFieldAssignments(text, () => {
400
+ hits["secret field"] = (hits["secret field"] ?? 0) + 1;
401
+ });
402
+ if (holdsCardNumber(out)) {
403
+ hits["card number"] = (hits["card number"] ?? 0) + 1;
404
+ out = scrubCardData(out);
405
+ }
406
+ for (const p of compiled) {
407
+ p.re.lastIndex = 0;
408
+ out = out.replace(p.re, (...m) => {
409
+ hits[p.name] = (hits[p.name] ?? 0) + 1;
410
+ return p.replacement.replace(/\$(\d)/g, (_, i) => String(m[Number(i)] ?? ""));
411
+ });
412
+ }
413
+ return { text: out, hits };
414
+ }
415
+ function nameSegments(name) {
416
+ return name.replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").replace(/([a-z0-9])([A-Z])/g, "$1 $2").split(/[^A-Za-z0-9]+/).filter(Boolean).map((part) => part.toLowerCase());
417
+ }
418
+ var CREDENTIAL_WORDS = /* @__PURE__ */ new Set([
419
+ "token",
420
+ "secret",
421
+ "secrets",
422
+ "password",
423
+ "passwords",
424
+ "passwd",
425
+ "credential",
426
+ "credentials",
427
+ "authorization",
428
+ "cookie",
429
+ "cookies"
430
+ ]);
431
+ var KEY_OWNERS = /* @__PURE__ */ new Set(["api", "access", "private", "secret", "signing", "encryption"]);
432
+ var COUNT_QUALIFIERS = /* @__PURE__ */ new Set(["max", "min", "num", "total", "input", "output", "cache", "prompt", "completion", "reasoning", "thinking", "used", "remaining", "limit", "budget"]);
433
+ var COUNT_SUFFIXES = /* @__PURE__ */ new Set(["count", "counts", "used", "usage", "remaining", "limit", "limits", "budget", "price", "cost", "total", "size", "length"]);
434
+ var PLAN_LOGIN = /model-subscriptions\/(?:[^\s"'`/?]+\/)?logins\/[^\s"'`/?]+\/code|submit_model_subscription_login_code/;
435
+ var PLAN_LOGIN_ID = /["'\\]login_id["'\\]/;
436
+ function namesPlanLogin(node) {
437
+ return "login_id" in node || Object.values(node).some((item) => typeof item === "string" && PLAN_LOGIN.test(item));
438
+ }
439
+ function ownsKey(segment) {
440
+ if (!segment) return false;
441
+ for (const owner of KEY_OWNERS) if (segment === owner || segment.endsWith(owner)) return true;
442
+ return false;
443
+ }
444
+ function isCredentialField(name) {
445
+ const segments = nameSegments(name);
446
+ for (let i = 0; i < segments.length; i += 1) {
447
+ const segment = segments[i];
448
+ if (segment === "token") {
449
+ if (!COUNT_QUALIFIERS.has(segments[i - 1] ?? "") && !COUNT_SUFFIXES.has(segments[i + 1] ?? "")) return true;
450
+ continue;
451
+ }
452
+ if (CREDENTIAL_WORDS.has(segment)) return true;
453
+ if ((segment === "key" || segment === "keys") && i > 0 && ownsKey(segments[i - 1])) return true;
454
+ if (segment === "id" && i > 0 && segments[i - 1] === "session") return true;
455
+ if (segment === "sessionid" || segment === "apikey" || segment === "accesskey" || segment === "privatekey") return true;
456
+ }
457
+ return false;
458
+ }
459
+ function redactFieldAssignments(value, onHit, inPlanLogin = false) {
460
+ FIELD_ASSIGNMENTS.lastIndex = 0;
461
+ const planLogin = inPlanLogin || PLAN_LOGIN.test(value) || PLAN_LOGIN_ID.test(value);
462
+ let out = "";
463
+ let copiedThrough = 0;
464
+ for (let match = FIELD_ASSIGNMENTS.exec(value); match; match = FIELD_ASSIGNMENTS.exec(value)) {
465
+ const name = match[2];
466
+ if (!isCredentialField(name) && !(planLogin && name === "code")) continue;
467
+ const valueStart = FIELD_ASSIGNMENTS.lastIndex;
468
+ const quote = match[3];
469
+ const limit = value.length;
470
+ const lineEnd = value.slice(valueStart, limit).search(/[\r\n]/);
471
+ const boundedLineEnd = lineEnd < 0 ? limit : valueStart + lineEnd;
472
+ const boundary = quote ? { end: boundedLineEnd, unsafe: false } : credentialRhsBoundary(value, valueStart, boundedLineEnd);
473
+ const expressionEnd = boundary.end;
474
+ const lineStart = value.lastIndexOf("\n", match.index - 1) + 1;
475
+ const declaration = /(?:^|[;{}]\s*)(?:const|let|var)\s+$/.test(value.slice(lineStart, match.index));
476
+ const expression = quote || boundary.unsafe ? null : rewriteCodeExpression(value.slice(valueStart, expressionEnd), declaration);
477
+ if (expression !== null) {
478
+ if (expression !== value.slice(valueStart, expressionEnd)) {
479
+ out += value.slice(copiedThrough, valueStart) + expression;
480
+ copiedThrough = expressionEnd;
481
+ onHit(value.slice(valueStart, expressionEnd));
482
+ }
483
+ FIELD_ASSIGNMENTS.lastIndex = expressionEnd;
484
+ continue;
485
+ }
486
+ if (!quote) {
487
+ const fieldValue2 = value.slice(valueStart, expressionEnd);
488
+ const trimmed2 = fieldValue2.trim();
489
+ if (!COMPLETE_MASKED_VALUE.test(trimmed2)) {
490
+ out += value.slice(copiedThrough, valueStart) + (JSON_NUMBER.test(trimmed2) ? `"${MASK}"` : MASK);
491
+ copiedThrough = expressionEnd;
492
+ onHit(fieldValue2);
493
+ }
494
+ FIELD_ASSIGNMENTS.lastIndex = expressionEnd;
495
+ continue;
496
+ }
497
+ let valueEnd = valueStart;
498
+ if (quote) {
499
+ let openingSlashes = 0;
500
+ for (let i = match[1].length - 2; i >= 0 && match[1][i] === "\\"; i -= 1) openingSlashes += 1;
501
+ while (valueEnd < limit && value[valueEnd] !== "\r" && value[valueEnd] !== "\n") {
502
+ if (value[valueEnd] === quote) {
503
+ let syntaxStart = valueEnd;
504
+ while (syntaxStart > valueStart && value[syntaxStart - 1] === "\\") syntaxStart -= 1;
505
+ if (valueEnd - syntaxStart === openingSlashes) {
506
+ valueEnd = syntaxStart;
507
+ break;
508
+ }
509
+ }
510
+ valueEnd += 1;
511
+ }
512
+ } else {
513
+ while (valueEnd < limit && !/["'\r\n,}]/.test(value[valueEnd])) valueEnd += 1;
514
+ }
515
+ if (valueEnd === valueStart) continue;
516
+ const fieldValue = value.slice(valueStart, valueEnd);
517
+ const trimmed = fieldValue.trim();
518
+ if (COMPLETE_MASKED_VALUE.test(trimmed)) continue;
519
+ out += value.slice(copiedThrough, valueStart) + (!match[3] && JSON_NUMBER.test(trimmed) ? `"${MASK}"` : MASK);
520
+ copiedThrough = valueEnd;
521
+ onHit(fieldValue);
522
+ FIELD_ASSIGNMENTS.lastIndex = valueEnd;
523
+ }
524
+ return copiedThrough ? out + value.slice(copiedThrough) : value;
525
+ }
526
+ var B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
527
+ function base64Bytes(value) {
528
+ const clean = value.endsWith("==") ? value.slice(0, -2) : value.endsWith("=") ? value.slice(0, -1) : value;
529
+ const out = [];
530
+ let bits = 0;
531
+ let acc = 0;
532
+ for (const ch of clean) {
533
+ const index = B64.indexOf(ch);
534
+ if (index < 0) throw new Error("not base64");
535
+ acc = acc << 6 | index;
536
+ bits += 6;
537
+ if (bits >= 8) {
538
+ bits -= 8;
539
+ out.push(acc >> bits & 255);
540
+ }
541
+ }
542
+ return Uint8Array.from(out);
543
+ }
544
+ function bytesBase64(bytes) {
545
+ let out = "";
546
+ for (let i = 0; i < bytes.length; i += 3) {
547
+ const a = bytes[i], b = bytes[i + 1], c = bytes[i + 2];
548
+ out += B64[a >> 2] + B64[(a & 3) << 4 | (b ?? 0) >> 4] + (b === void 0 ? "=" : B64[(b & 15) << 2 | (c ?? 0) >> 6]) + (c === void 0 ? "=" : B64[c & 63]);
549
+ }
550
+ return out;
551
+ }
552
+ function redactLine(line, options = {}) {
553
+ const hits = {};
554
+ function traceIdentityPaths(root) {
555
+ if (!options.preserveTraceSessionIds || !root || typeof root !== "object" || Array.isArray(root)) return /* @__PURE__ */ new Set();
556
+ const node = root;
557
+ if (typeof node.type === "string" && /^(?:auth(?:entication|orization)?|login|logout|oauth|credentials?|session[_-]token|cookie)(?:[./:_-]|$)/i.test(node.type)) return /* @__PURE__ */ new Set();
558
+ const nativeTypes = /* @__PURE__ */ new Set([
559
+ "user",
560
+ "assistant",
561
+ "system",
562
+ "progress",
563
+ "summary",
564
+ "file-history-snapshot",
565
+ "queue-operation",
566
+ "custom-title",
567
+ "last-prompt",
568
+ "agent-name",
569
+ "agent-color",
570
+ "session_meta",
571
+ "response_item",
572
+ "event_msg",
573
+ "turn_context",
574
+ "compacted",
575
+ "session",
576
+ "attachment",
577
+ "atis-latch",
578
+ "api-request-shape",
579
+ "api-request-blob",
580
+ "api-request",
581
+ "bridge-session",
582
+ "relocated",
583
+ "worktree-state",
584
+ "pr-link",
585
+ "cost-state"
586
+ ]);
587
+ const native = node.format === "trace/v1" || node.type === void 0 && (Array.isArray(node.messages) || Array.isArray(node.history)) || typeof node.type === "string" && (nativeTypes.has(node.type) || /^(?:user|assistant|tool|hook|session|turn|reasoning)\//.test(node.type));
588
+ if (native) return /* @__PURE__ */ new Set(["session_id", "sessionId"]);
589
+ const relationTables = /* @__PURE__ */ new Set(["messages", "session_model_usage", "compression_locks", "intermediate_events"]);
590
+ if (typeof node.table === "string" && relationTables.has(node.table) && node.row && typeof node.row === "object" && options.expectedTraceSessionId) {
591
+ return /* @__PURE__ */ new Set(["row\0session_id", "row\0sessionId"]);
592
+ }
593
+ return /* @__PURE__ */ new Set();
594
+ }
595
+ function preserveIdentity(identities, path, key, value) {
596
+ return typeof value === "string" && identities.has([...path, key].join("\0")) && (path.length === 0 || value === options.expectedTraceSessionId);
597
+ }
598
+ function fieldCredentials(value, inPlanLogin) {
599
+ return redactFieldAssignments(value, (fieldValue) => {
600
+ const kind = /^[A-Za-z0-9_/+.=-]{12,}$/.test(fieldValue) ? "env assignment" : "secret field";
601
+ hits[kind] = (hits[kind] ?? 0) + 1;
602
+ }, inPlanLogin);
603
+ }
604
+ function redactPatterns(value, inPlanLogin = false) {
605
+ let out = value;
606
+ for (const p of compiled) {
607
+ p.re.lastIndex = 0;
608
+ out = out.replace(p.re, (...m) => {
609
+ hits[p.name] = (hits[p.name] ?? 0) + 1;
610
+ return p.replacement.replace(/\$(\d)/g, (_, i) => String(m[Number(i)] ?? ""));
611
+ });
612
+ }
613
+ return fieldCredentials(out, inPlanLogin);
614
+ }
615
+ function redactDuplicateRecord(value) {
616
+ let at = 0;
617
+ const space = () => {
618
+ while (/[ \t\r\n]/.test(value[at] ?? "") && at < value.length) at += 1;
619
+ };
620
+ const invalid = () => {
621
+ throw new UnsafeImportError("Invalid JSON in a duplicate-key record.");
622
+ };
623
+ const string = () => {
624
+ const start = at++;
625
+ while (at < value.length) {
626
+ if (value[at] === "\\") {
627
+ at += 2;
628
+ continue;
629
+ }
630
+ if (value[at++] === '"') {
631
+ try {
632
+ return { start, end: at, kind: "string", text: JSON.parse(value.slice(start, at)) };
633
+ } catch {
634
+ return invalid();
635
+ }
636
+ }
637
+ }
638
+ return invalid();
639
+ };
640
+ const parse = () => {
641
+ space();
642
+ const start = at;
643
+ if (value[at] === '"') return string();
644
+ if (value[at] === "{") {
645
+ at += 1;
646
+ space();
647
+ const properties = [];
648
+ if (value[at] !== "}") while (true) {
649
+ if (value[at] !== '"') return invalid();
650
+ const key = string();
651
+ space();
652
+ if (value[at++] !== ":") return invalid();
653
+ properties.push({ key, value: parse() });
654
+ space();
655
+ if (value[at] === "}") break;
656
+ if (value[at++] !== ",") return invalid();
657
+ space();
658
+ }
659
+ at += 1;
660
+ return { start, end: at, kind: "object", properties };
661
+ }
662
+ if (value[at] === "[") {
663
+ at += 1;
664
+ space();
665
+ const items = [];
666
+ if (value[at] !== "]") while (true) {
667
+ items.push(parse());
668
+ space();
669
+ if (value[at] === "]") break;
670
+ if (value[at++] !== ",") return invalid();
671
+ }
672
+ at += 1;
673
+ return { start, end: at, kind: "array", items };
674
+ }
675
+ const literal = /^(?:null|true|false|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)/.exec(value.slice(at));
676
+ if (!literal) return invalid();
677
+ at += literal[0].length;
678
+ return { start, end: at, kind: "literal" };
679
+ };
680
+ const tree = parse();
681
+ space();
682
+ if (at !== value.length) return invalid();
683
+ const rootContext = /* @__PURE__ */ Object.create(null);
684
+ let ambiguousIdentity = false;
685
+ for (const property of tree.properties ?? []) {
686
+ const key = property.key.text;
687
+ const item = property.value.kind === "string" ? property.value.text : property.value.kind === "array" ? [] : property.value.kind === "object" ? Object.fromEntries(property.value.properties.filter((p) => p.value.kind === "string").map((p) => [p.key.text, p.value.text])) : void 0;
688
+ if (["type", "format", "table", "messages", "history", "row"].includes(key) && key in rootContext && rootContext[key] !== item) ambiguousIdentity = true;
689
+ rootContext[key] = item;
690
+ }
691
+ const identities = ambiguousIdentity ? /* @__PURE__ */ new Set() : traceIdentityPaths(rootContext);
692
+ const replacements = [];
693
+ const replace = (node, text) => {
694
+ if (node.kind === "string" && text === node.text) return;
695
+ replacements.push({ start: node.start, end: node.end, text: JSON.stringify(text) });
696
+ };
697
+ const visit = (node, path = [], inPlanLogin = false) => {
698
+ if (node.kind === "string") {
699
+ replace(node, redactText(node.text, inPlanLogin));
700
+ return;
701
+ }
702
+ if (node.kind === "array") {
703
+ node.items.forEach((item, index) => visit(item, [...path, String(index)], inPlanLogin));
704
+ return;
705
+ }
706
+ if (node.kind !== "object") return;
707
+ const context = /* @__PURE__ */ Object.create(null);
708
+ const attachment = node.properties.some(({ key, value: child }) => ["media_type", "mime_type"].includes(key.text) || key.text === "type" && ["base64", "import.resource"].includes(child.text ?? ""));
709
+ for (const property of node.properties) {
710
+ const key = property.key.text;
711
+ const text = property.value.kind === "string" ? property.value.text : void 0;
712
+ if (attachment && ["data", "media_type", "mime_type", "type"].includes(key) && key in context && context[key] !== text) {
713
+ throw new UnsafeImportError("Conflicting attachment metadata in a duplicate-key record.");
714
+ }
715
+ context[key] = text;
716
+ }
717
+ const payload = isFilePayload(context);
718
+ const planLogin = inPlanLogin || namesPlanLogin(context);
719
+ for (const property of node.properties) {
720
+ const key = property.key.text, child = property.value;
721
+ replace(property.key, redactText(key));
722
+ if (payload && key === "data") {
723
+ replace(child, recodePayload(child.text, context.media_type ?? context.mime_type));
724
+ } else if ((isCredentialField(key) || planLogin && key === "code") && !preserveIdentity(identities, path, key, child.kind === "string" ? child.text : void 0) && value.slice(child.start, child.end) !== "null") {
725
+ if (child.kind !== "string" || child.text !== MASK) {
726
+ hits["secret field"] = (hits["secret field"] ?? 0) + 1;
727
+ replace(child, MASK);
728
+ }
729
+ } else visit(child, [...path, key], planLogin);
730
+ }
731
+ };
732
+ visit(tree);
733
+ let out = value;
734
+ for (const replacement of replacements.sort((a, b) => b.start - a.start)) {
735
+ out = out.slice(0, replacement.start) + replacement.text + out.slice(replacement.end);
736
+ }
737
+ return out;
738
+ }
739
+ function restoreHits(snapshot) {
740
+ for (const key of Object.keys(hits)) delete hits[key];
741
+ Object.assign(hits, snapshot);
742
+ }
743
+ function redactText(value, inPlanLogin = false) {
744
+ const uri = BASE64_DATA_URI_PREFIX.exec(value);
745
+ if (uri && isCanonicalBase64(uri[2])) {
746
+ const prefix = uri[1];
747
+ const metadata = redactPlainText(prefix.slice(0, -8));
748
+ for (const [kind, n] of Object.entries(metadata.hits)) hits[kind] = (hits[kind] ?? 0) + n;
749
+ const mediaType = /^data:([^;,]*)/i.exec(prefix)?.[1] || "text/plain";
750
+ return metadata.text + prefix.slice(-8) + recodePayload(uri[2], mediaType);
751
+ }
752
+ const trimmed = value.trim();
753
+ if (trimmed.startsWith("{") && trimmed.endsWith("}") || trimmed.startsWith("[") && trimmed.endsWith("]")) {
754
+ if (hasDuplicateJsonKeys(value)) throw new UnsafeImportError("Duplicate keys in serialized JSON are not safe to import.");
755
+ const snapshot = { ...hits };
756
+ try {
757
+ const json2 = withPreservedNumbers(value);
758
+ if (json2) {
759
+ const parsed = json2.parse();
760
+ const walked = walk(parsed, /* @__PURE__ */ new Set(), [], inPlanLogin);
761
+ if (JSON.stringify(walked) !== JSON.stringify(parsed)) return json2.serialize(walked);
762
+ restoreHits(snapshot);
763
+ return value;
764
+ }
765
+ } catch (error) {
766
+ if (error instanceof UnsafeImportError) throw error;
767
+ restoreHits(snapshot);
768
+ }
769
+ }
770
+ return redactPatterns(value, inPlanLogin);
771
+ }
772
+ function recodePayload(data, mediaType) {
773
+ const bytes = base64Bytes(data);
774
+ if (!isTextMediaType(mediaType)) return data;
775
+ let content;
776
+ try {
777
+ content = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
778
+ } catch {
779
+ throw new UnsafeImportError("A declared text attachment is not valid UTF-8.");
780
+ }
781
+ const cleaned = redactText(content);
782
+ return cleaned === content ? data : bytesBase64(new TextEncoder().encode(cleaned));
783
+ }
784
+ function maskDescendants(value) {
785
+ if (typeof value === "string") return value === MASK ? value : MASK;
786
+ if (typeof value === "number" || typeof value === "boolean") return MASK;
787
+ if (Array.isArray(value)) return value.map(maskDescendants);
788
+ if (value && typeof value === "object") {
789
+ const result = {};
790
+ for (const [key, item] of Object.entries(value)) {
791
+ const name = redactText(key);
792
+ let at = name;
793
+ for (let n = 2; at in result; n += 1) at = `${name} (${n})`;
794
+ result[at] = maskDescendants(item);
795
+ }
796
+ return result;
797
+ }
798
+ return value;
799
+ }
800
+ function walk(value, identities = /* @__PURE__ */ new Set(), path = [], inPlanLogin = false) {
801
+ if (typeof value === "string") return redactText(value, inPlanLogin);
802
+ if (Array.isArray(value)) return value.map((item, index) => walk(item, identities, [...path, String(index)], inPlanLogin));
803
+ if (!value || typeof value !== "object") return value;
804
+ const node = value;
805
+ const payload = isFilePayload(node);
806
+ const planLogin = inPlanLogin || namesPlanLogin(node);
807
+ const out = {};
808
+ const place = (name, item) => {
809
+ let at = name;
810
+ for (let n = 2; at in out; n += 1) at = `${name} (${n})`;
811
+ out[at] = item;
812
+ };
813
+ for (const [key, item] of Object.entries(node)) {
814
+ const name = redactText(key);
815
+ if (payload && key === "data") {
816
+ place(name, recodePayload(item, node.media_type ?? node.mime_type));
817
+ continue;
818
+ }
819
+ if ((isCredentialField(key) || planLogin && key === "code") && !preserveIdentity(identities, path, key, item) && item !== null && item !== void 0) {
820
+ const masked = maskDescendants(item);
821
+ if (JSON.stringify(masked) !== JSON.stringify(item)) {
822
+ hits["secret field"] = (hits["secret field"] ?? 0) + 1;
823
+ }
824
+ place(name, masked);
825
+ continue;
826
+ }
827
+ place(name, walk(item, identities, [...path, key], planLogin));
828
+ }
829
+ return out;
830
+ }
831
+ if (hasDuplicateJsonKeys(line)) return { line: redactDuplicateRecord(line), hits };
832
+ const json = withPreservedNumbers(line);
833
+ if (!json) {
834
+ if (options.requireStructured) throw new Error("Could not preserve JSON numbers during redaction.");
835
+ return { line: redactPatterns(line), hits };
836
+ }
837
+ try {
838
+ const parsed = json.parse();
839
+ const walked = json.serialize(walk(parsed, traceIdentityPaths(parsed)));
840
+ return { line: Object.keys(hits).length ? walked : line, hits };
841
+ } catch (error) {
842
+ if (options.requireStructured || error instanceof UnsafeImportError) throw error;
843
+ return { line: redactPatterns(line), hits };
844
+ }
845
+ }
846
+ var BASE64_DATA_URI_PREFIX = /^(data:[^,]*;base64,)([\s\S]*)(?![\s\S])/i;
847
+ function isFilePayload(node) {
848
+ return typeof node.data === "string" && node.data !== "" && (typeof node.media_type === "string" || typeof node.mime_type === "string" || node.type === "import.resource" || node.type === "base64");
849
+ }
850
+
851
+ export {
852
+ UnsafeImportError,
853
+ unsafeNumberSpans,
854
+ redactSecretValues,
855
+ redactPlainText,
856
+ redactLine
857
+ };