@maskera/mcp 0.1.0 → 0.2.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.
package/dist/cli.js CHANGED
@@ -1,17 +1,20 @@
1
1
  #!/usr/bin/env node
2
- import { readFile, mkdir, writeFile, realpath, stat } from 'fs/promises';
3
- import { delimiter, resolve, dirname, isAbsolute, relative } from 'path';
2
+ import { readFile, mkdir, appendFile, realpath, writeFile, stat, lstat, readlink } from 'fs/promises';
3
+ import { delimiter, dirname, resolve, isAbsolute, relative, sep } from 'path';
4
4
  import { createInterface } from 'readline';
5
5
  import { format } from 'util';
6
- import { MASKERA_SV_NER_MODEL, MASKERA_SV_NER_REVISION, hybridDefaultDetectors, redactFromDetections, runDetectors, clinicalPrecisionFilter, redact, redactWithNer, restore, createNerRecognizer } from 'maskera';
6
+ import { randomUUID, createHash } from 'crypto';
7
+ import { MASKERA_SV_NER_MODEL, MASKERA_SV_NER_REVISION, redactFromDetections, hybridDefaultDetectors, runDetectors, clinicalPrecisionFilter, redact, redactWithNer, restore, createNerRecognizer } from 'maskera';
7
8
  import { createServer } from 'http';
8
- import { randomUUID } from 'crypto';
9
+ import * as zlib from 'zlib';
9
10
 
10
11
  var WORD_CHAR = /[\p{L}\p{N}_]/u;
12
+ var DEFAULT_MAX_CACHE_ENTRIES = 512;
13
+ var MAX_CUSTOM_DETECTOR_CACHE = 64;
11
14
  function escapeRegExp(value) {
12
15
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
13
16
  }
14
- function buildCustomTermsDetector(rawTerms) {
17
+ function normalizeCustomTerms(rawTerms) {
15
18
  const unique = /* @__PURE__ */ new Map();
16
19
  for (const raw of rawTerms) {
17
20
  if (typeof raw !== "string") continue;
@@ -21,9 +24,20 @@ function buildCustomTermsDetector(rawTerms) {
21
24
  if (!unique.has(folded)) unique.set(folded, trimmed);
22
25
  if (unique.size >= 200) break;
23
26
  }
24
- if (unique.size === 0) return null;
25
- const sorted = [...unique.values()].sort((a, b) => b.length - a.length);
26
- const pattern = new RegExp(sorted.map(escapeRegExp).join("|"), "giu");
27
+ return [...unique.values()].sort((a, b) => b.length - a.length);
28
+ }
29
+ function buildCustomTermsDetector(rawTerms) {
30
+ const sorted = normalizeCustomTerms(rawTerms);
31
+ if (sorted.length === 0) return null;
32
+ const pattern = new RegExp(
33
+ sorted.map((term) => {
34
+ const escaped = escapeRegExp(term);
35
+ const startGuard = WORD_CHAR.test(term[0] ?? "") ? "(?<![\\p{L}\\p{N}_])" : "";
36
+ const endGuard = WORD_CHAR.test(term[term.length - 1] ?? "") ? "(?![\\p{L}\\p{N}_])" : "";
37
+ return `${startGuard}${escaped}${endGuard}`;
38
+ }).join("|"),
39
+ "giu"
40
+ );
27
41
  return {
28
42
  label: "EGENT",
29
43
  detect(text) {
@@ -32,13 +46,11 @@ function buildCustomTermsDetector(rawTerms) {
32
46
  for (let m = pattern.exec(text); m !== null; m = pattern.exec(text)) {
33
47
  const start = m.index;
34
48
  const value = m[0];
35
- const end = start + value.length;
36
- const before = start > 0 ? text[start - 1] ?? "" : "";
37
- const after = end < text.length ? text[end] ?? "" : "";
38
- if (WORD_CHAR.test(value[0] ?? "") && WORD_CHAR.test(before) || WORD_CHAR.test(value[value.length - 1] ?? "") && WORD_CHAR.test(after)) {
49
+ if (!value) {
50
+ pattern.lastIndex += 1;
39
51
  continue;
40
52
  }
41
- out.push({ start, end, value });
53
+ out.push({ start, end: start + value.length, value });
42
54
  }
43
55
  return out;
44
56
  }
@@ -48,23 +60,93 @@ function createMaskeraEngine(options = {}) {
48
60
  const defaultMode = options.defaultMode ?? "auto";
49
61
  const model = options.nerOptions?.model ?? MASKERA_SV_NER_MODEL;
50
62
  const revision = options.nerOptions?.revision ?? (model === MASKERA_SV_NER_MODEL ? MASKERA_SV_NER_REVISION : void 0);
63
+ const maxCacheEntries = Math.max(0, options.maxCacheEntries ?? DEFAULT_MAX_CACHE_ENTRIES);
51
64
  let recognizer = options.recognizer ?? null;
52
65
  let nerLoaded = false;
53
66
  let nerError = null;
67
+ let warmupStarted = false;
68
+ const spanCache = /* @__PURE__ */ new Map();
69
+ const customDetectorCache = /* @__PURE__ */ new Map();
70
+ let cacheHits = 0;
71
+ let cacheMisses = 0;
54
72
  function getRecognizer() {
55
73
  if (!recognizer) {
74
+ const dtype = options.nerOptions?.dtype ?? (options.nerOptions?.localModelPath ? "q4" : "q8");
56
75
  recognizer = createNerRecognizer({
57
76
  ...options.nerOptions,
58
77
  model,
59
- revision
78
+ revision,
79
+ dtype
60
80
  });
61
81
  }
62
82
  return recognizer;
63
83
  }
84
+ function getCustomDetector(rawTerms) {
85
+ if (!rawTerms || rawTerms.length === 0) return { detector: null, termsKey: "" };
86
+ const sorted = normalizeCustomTerms(rawTerms);
87
+ if (sorted.length === 0) return { detector: null, termsKey: "" };
88
+ const termsKey = sorted.map((t) => `${t.length}:${t.toLowerCase()}`).join("|");
89
+ if (customDetectorCache.has(termsKey)) {
90
+ const hit = customDetectorCache.get(termsKey) ?? null;
91
+ customDetectorCache.delete(termsKey);
92
+ customDetectorCache.set(termsKey, hit);
93
+ return { detector: hit, termsKey };
94
+ }
95
+ const detector = buildCustomTermsDetector(sorted);
96
+ if (customDetectorCache.size >= MAX_CUSTOM_DETECTOR_CACHE) {
97
+ const oldest = customDetectorCache.keys().next().value;
98
+ if (oldest !== void 0) customDetectorCache.delete(oldest);
99
+ }
100
+ customDetectorCache.set(termsKey, detector);
101
+ return { detector, termsKey };
102
+ }
103
+ function makeCacheKey(mode, profile, termsKey, text) {
104
+ return createHash("sha256").update(mode).update("\0").update(profile ?? "").update("\0").update(termsKey).update("\0").update(text).digest("base64url");
105
+ }
64
106
  return {
107
+ warmup() {
108
+ if (defaultMode !== "auto" || warmupStarted || nerLoaded) return;
109
+ warmupStarted = true;
110
+ const ner = getRecognizer();
111
+ void ner.ready.then(
112
+ () => {
113
+ nerLoaded = true;
114
+ nerError = null;
115
+ },
116
+ (err) => {
117
+ warmupStarted = false;
118
+ nerError = err instanceof Error ? err.message : String(err);
119
+ }
120
+ );
121
+ },
122
+ clearCache() {
123
+ spanCache.clear();
124
+ cacheHits = 0;
125
+ cacheMisses = 0;
126
+ },
65
127
  async redact(text, req = {}) {
66
128
  const requestedMode = req.mode ?? defaultMode;
67
- const customDetector = req.customTerms ? buildCustomTermsDetector(req.customTerms) : null;
129
+ const { detector: customDetector, termsKey } = getCustomDetector(req.customTerms);
130
+ const cacheKey = maxCacheEntries > 0 && text.length > 0 ? makeCacheKey(requestedMode, req.profile, termsKey, text) : null;
131
+ if (cacheKey) {
132
+ const cached = spanCache.get(cacheKey);
133
+ if (cached) {
134
+ spanCache.delete(cacheKey);
135
+ spanCache.set(cacheKey, cached);
136
+ cacheHits += 1;
137
+ const result = cached.spans.length === 0 ? redactFromDetections(text, []) : redactFromDetections(
138
+ text,
139
+ cached.spans.map((s) => ({
140
+ start: s.start,
141
+ end: s.end,
142
+ label: s.label,
143
+ value: text.slice(s.start, s.end)
144
+ }))
145
+ );
146
+ return { result, modeUsed: cached.modeUsed };
147
+ }
148
+ cacheMisses += 1;
149
+ }
68
150
  const detectors = customDetector ? [...hybridDefaultDetectors, customDetector] : hybridDefaultDetectors;
69
151
  if (requestedMode === "rules") {
70
152
  const result = req.profile === "clinical" ? redactFromDetections(
@@ -73,6 +155,20 @@ function createMaskeraEngine(options = {}) {
73
155
  (d) => clinicalPrecisionFilter(d, text, "rule")
74
156
  )
75
157
  ) : redact(text, { detectors });
158
+ if (cacheKey) {
159
+ if (spanCache.size >= maxCacheEntries) {
160
+ const oldest = spanCache.keys().next().value;
161
+ if (oldest !== void 0) spanCache.delete(oldest);
162
+ }
163
+ spanCache.set(cacheKey, {
164
+ spans: result.redactions.map((r) => ({
165
+ start: r.start,
166
+ end: r.end,
167
+ label: r.label
168
+ })),
169
+ modeUsed: "rules"
170
+ });
171
+ }
76
172
  return {
77
173
  result,
78
174
  modeUsed: "rules"
@@ -87,6 +183,20 @@ function createMaskeraEngine(options = {}) {
87
183
  });
88
184
  nerLoaded = true;
89
185
  nerError = null;
186
+ if (cacheKey) {
187
+ if (spanCache.size >= maxCacheEntries) {
188
+ const oldest = spanCache.keys().next().value;
189
+ if (oldest !== void 0) spanCache.delete(oldest);
190
+ }
191
+ spanCache.set(cacheKey, {
192
+ spans: result.redactions.map((r) => ({
193
+ start: r.start,
194
+ end: r.end,
195
+ label: r.label
196
+ })),
197
+ modeUsed: "hybrid"
198
+ });
199
+ }
90
200
  return { result, modeUsed: "hybrid" };
91
201
  } catch (err) {
92
202
  const message = err instanceof Error ? err.message : String(err);
@@ -102,33 +212,57 @@ function createMaskeraEngine(options = {}) {
102
212
  model,
103
213
  revision: revision ?? "local",
104
214
  nerLoaded,
105
- nerError
215
+ nerError,
216
+ cacheSize: spanCache.size,
217
+ cacheHits,
218
+ cacheMisses
106
219
  };
107
220
  }
108
221
  };
109
222
  }
110
223
 
111
224
  // src/guard.ts
225
+ var HOOK_PAYLOAD_KEYS = [
226
+ "prompt",
227
+ "user_prompt",
228
+ "tool_input",
229
+ "tool_response",
230
+ "tool_output",
231
+ "command",
232
+ "content",
233
+ "edits",
234
+ "attachments"
235
+ ];
236
+ var HOOK_META_SKIP_KEYS = /* @__PURE__ */ new Set([
237
+ "hook_event_name",
238
+ "tool_name",
239
+ "permission_mode",
240
+ "session_id"
241
+ ]);
242
+ function collectScalars(value, parts, skipKey) {
243
+ if (skipKey && HOOK_META_SKIP_KEYS.has(skipKey)) return;
244
+ if (typeof value === "string") {
245
+ if (value.trim()) parts.push(value);
246
+ } else if (typeof value === "number" && Number.isFinite(value)) {
247
+ parts.push(String(value));
248
+ } else if (Array.isArray(value)) {
249
+ for (const item of value) collectScalars(item, parts);
250
+ } else if (value && typeof value === "object") {
251
+ for (const [k, v] of Object.entries(value)) collectScalars(v, parts, k);
252
+ }
253
+ }
112
254
  function extractGuardText(rawInput) {
113
255
  const trimmed = rawInput.trim();
114
256
  if (trimmed.startsWith("{") && trimmed.endsWith("}")) {
115
257
  try {
116
258
  const parsed = JSON.parse(trimmed);
117
- if (typeof parsed.prompt === "string") {
118
- return { text: parsed.prompt, isHookEnvelope: true };
119
- }
120
- if (typeof parsed.user_prompt === "string") {
121
- return { text: parsed.user_prompt, isHookEnvelope: true };
122
- }
123
- if (parsed.tool_input && typeof parsed.tool_input === "object") {
124
- const parts = [];
125
- const walk = (v) => {
126
- if (typeof v === "string") parts.push(v);
127
- else if (Array.isArray(v)) v.forEach(walk);
128
- else if (v && typeof v === "object") Object.values(v).forEach(walk);
129
- };
130
- walk(parsed.tool_input);
131
- return { text: parts.join("\n"), isHookEnvelope: true };
259
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
260
+ const isHookEnvelope = HOOK_PAYLOAD_KEYS.some((key) => key in parsed);
261
+ if (isHookEnvelope) {
262
+ const parts = [];
263
+ collectScalars(parsed, parts);
264
+ return { text: parts.join("\n"), isHookEnvelope: true };
265
+ }
132
266
  }
133
267
  } catch {
134
268
  }
@@ -136,6 +270,56 @@ function extractGuardText(rawInput) {
136
270
  return { text: rawInput, isHookEnvelope: false };
137
271
  }
138
272
  async function runGuard(rawInput, engine, options = {}) {
273
+ const trimmed = rawInput.trim();
274
+ if (options.preserveJsonStructure && trimmed.startsWith("{") && trimmed.endsWith("}")) {
275
+ try {
276
+ const parsed = JSON.parse(trimmed);
277
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
278
+ const counts2 = {};
279
+ let totalRedactions = 0;
280
+ let modeUsed2 = options.mode === "rules" ? "rules" : "hybrid";
281
+ const redactJson = async (value, key) => {
282
+ if (key && HOOK_META_SKIP_KEYS.has(key)) return value;
283
+ if (typeof value === "string") {
284
+ if (!value.trim()) return value;
285
+ const out = await engine.redact(value, {
286
+ mode: options.mode,
287
+ profile: options.profile,
288
+ customTerms: options.customTerms
289
+ });
290
+ modeUsed2 = out.modeUsed;
291
+ totalRedactions += out.result.redactions.length;
292
+ for (const r of out.result.redactions) {
293
+ counts2[r.label] = (counts2[r.label] ?? 0) + 1;
294
+ }
295
+ return out.result.text;
296
+ }
297
+ if (Array.isArray(value)) {
298
+ const arr = [];
299
+ for (const item of value) arr.push(await redactJson(item));
300
+ return arr;
301
+ }
302
+ if (value && typeof value === "object") {
303
+ const obj = {};
304
+ for (const [k, v] of Object.entries(value)) {
305
+ obj[k] = await redactJson(v, k);
306
+ }
307
+ return obj;
308
+ }
309
+ return value;
310
+ };
311
+ const redactedObj = await redactJson(parsed);
312
+ return {
313
+ blocked: totalRedactions > 0,
314
+ totalRedactions,
315
+ counts: counts2,
316
+ redacted: JSON.stringify(redactedObj),
317
+ modeUsed: modeUsed2
318
+ };
319
+ }
320
+ } catch {
321
+ }
322
+ }
139
323
  const { text } = extractGuardText(rawInput);
140
324
  if (!text.trim()) {
141
325
  return {
@@ -163,14 +347,429 @@ async function runGuard(rawInput, engine, options = {}) {
163
347
  modeUsed
164
348
  };
165
349
  }
350
+
351
+ // src/inspector.ts
352
+ var MAX_EVENTS = 100;
353
+ var ProxyInspector = class {
354
+ constructor() {
355
+ this.items = [];
356
+ this.subscribers = /* @__PURE__ */ new Set();
357
+ this.seq = 0;
358
+ }
359
+ record(entry) {
360
+ this.seq += 1;
361
+ const item = { id: `req_${this.seq}`, ...entry };
362
+ this.items.unshift(item);
363
+ if (this.items.length > MAX_EVENTS) this.items.length = MAX_EVENTS;
364
+ const payload = `event: request
365
+ data: ${JSON.stringify(item)}
366
+
367
+ `;
368
+ for (const res of [...this.subscribers]) {
369
+ if (res.writableEnded || res.destroyed) {
370
+ this.subscribers.delete(res);
371
+ continue;
372
+ }
373
+ res.write(payload);
374
+ }
375
+ return item;
376
+ }
377
+ list() {
378
+ return this.items;
379
+ }
380
+ clear() {
381
+ this.items.length = 0;
382
+ const payload = `event: cleared
383
+ data: {}
384
+
385
+ `;
386
+ for (const res of [...this.subscribers]) {
387
+ if (res.writableEnded || res.destroyed) {
388
+ this.subscribers.delete(res);
389
+ continue;
390
+ }
391
+ res.write(payload);
392
+ }
393
+ }
394
+ subscribe(res, extraHeaders = {}) {
395
+ res.writeHead(200, {
396
+ ...extraHeaders,
397
+ "content-type": "text/event-stream; charset=utf-8",
398
+ "cache-control": "no-cache, no-transform",
399
+ connection: "keep-alive"
400
+ });
401
+ res.write(`event: init
402
+ data: ${JSON.stringify({ items: this.items })}
403
+
404
+ `);
405
+ this.subscribers.add(res);
406
+ res.on("close", () => {
407
+ this.subscribers.delete(res);
408
+ });
409
+ }
410
+ closeAll() {
411
+ for (const res of [...this.subscribers]) {
412
+ try {
413
+ res.end();
414
+ } catch {
415
+ }
416
+ }
417
+ this.subscribers.clear();
418
+ }
419
+ };
420
+ function renderInspectorHtml(info) {
421
+ const safeUrl = info.url.replace(/[<>&"']/g, "");
422
+ return `<!doctype html>
423
+ <html lang="sv">
424
+ <head>
425
+ <meta charset="utf-8" />
426
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
427
+ <title>Maskera Proxy Inspector</title>
428
+ <style>
429
+ :root {
430
+ --bg: #ffffff;
431
+ --bg-subtle: #f7f7f8;
432
+ --fg: #111113;
433
+ --muted: #666670;
434
+ --border: #e4e4e7;
435
+ --ok: #15803d;
436
+ --ok-bg: #f0fdf4;
437
+ --err: #b91c1c;
438
+ --err-bg: #fef2f2;
439
+ --tok-bg: #eff6ff;
440
+ --tok-fg: #1d4ed8;
441
+ --tok-border: #bfdbfe;
442
+ --mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
443
+ --sans: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
444
+ }
445
+ @media (prefers-color-scheme: dark) {
446
+ :root {
447
+ --bg: #0c0c0e;
448
+ --bg-subtle: #16161a;
449
+ --fg: #f4f4f5;
450
+ --muted: #a1a1aa;
451
+ --border: #27272a;
452
+ --ok: #4ade80;
453
+ --ok-bg: #052e16;
454
+ --err: #f87171;
455
+ --err-bg: #450a0a;
456
+ --tok-bg: #172554;
457
+ --tok-fg: #93c5fd;
458
+ --tok-border: #1e3a8a;
459
+ }
460
+ }
461
+ * { box-sizing: border-box; }
462
+ body {
463
+ margin: 0;
464
+ font-family: var(--sans);
465
+ background: var(--bg);
466
+ color: var(--fg);
467
+ line-height: 1.5;
468
+ }
469
+ .wrap { max-width: 960px; margin: 0 auto; padding: 24px 20px 64px; }
470
+ header {
471
+ display: flex;
472
+ align-items: flex-start;
473
+ justify-content: space-between;
474
+ gap: 16px;
475
+ flex-wrap: wrap;
476
+ padding-bottom: 18px;
477
+ border-bottom: 1px solid var(--border);
478
+ }
479
+ h1 { margin: 0; font-size: 18px; font-weight: 650; letter-spacing: -0.02em; }
480
+ .sub { margin: 4px 0 0; font-size: 13px; color: var(--muted); }
481
+ .dot {
482
+ display: inline-block; width: 8px; height: 8px; border-radius: 50%;
483
+ background: var(--ok); margin-right: 6px; vertical-align: middle;
484
+ }
485
+ .actions { display: flex; gap: 8px; flex-wrap: wrap; }
486
+ button {
487
+ font-family: var(--sans);
488
+ font-weight: 500;
489
+ font-size: 12.5px;
490
+ padding: 7px 12px;
491
+ border-radius: 7px;
492
+ border: 1px solid var(--border);
493
+ background: var(--bg);
494
+ color: var(--fg);
495
+ cursor: pointer;
496
+ }
497
+ button:hover { background: var(--bg-subtle); }
498
+ button.active { background: var(--fg); color: var(--bg); border-color: var(--fg); }
499
+ .stats {
500
+ display: grid;
501
+ grid-template-columns: repeat(4, minmax(0, 1fr));
502
+ gap: 10px;
503
+ margin: 18px 0 22px;
504
+ }
505
+ @media (max-width: 640px) { .stats { grid-template-columns: repeat(2, 1fr); } }
506
+ .stat {
507
+ border: 1px solid var(--border);
508
+ border-radius: 8px;
509
+ padding: 12px 14px;
510
+ background: var(--bg-subtle);
511
+ }
512
+ .stat-k { font-size: 11.5px; color: var(--muted); }
513
+ .stat-v { font-size: 20px; font-weight: 650; margin-top: 2px; font-variant-numeric: tabular-nums; }
514
+ .empty {
515
+ border: 1px dashed var(--border);
516
+ border-radius: 8px;
517
+ padding: 28px 20px;
518
+ text-align: center;
519
+ color: var(--muted);
520
+ font-size: 13.5px;
521
+ }
522
+ .empty code {
523
+ display: block; margin: 10px auto 0; max-width: 560px; padding: 10px 12px;
524
+ background: var(--bg-subtle); border: 1px solid var(--border); border-radius: 6px;
525
+ font: 12px/1.6 var(--mono); color: var(--fg); text-align: left; white-space: pre-wrap;
526
+ }
527
+ .list { display: flex; flex-direction: column; gap: 8px; }
528
+ details.item {
529
+ border: 1px solid var(--border);
530
+ border-radius: 8px;
531
+ background: var(--bg);
532
+ overflow: hidden;
533
+ }
534
+ summary {
535
+ list-style: none;
536
+ cursor: pointer;
537
+ display: flex;
538
+ align-items: center;
539
+ justify-content: space-between;
540
+ gap: 10px;
541
+ flex-wrap: wrap;
542
+ padding: 11px 14px;
543
+ font-size: 13px;
544
+ }
545
+ summary::-webkit-details-marker { display: none; }
546
+ summary:hover { background: var(--bg-subtle); }
547
+ .left { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
548
+ .right { display: flex; align-items: center; gap: 8px; color: var(--muted); font-size: 12px; font-variant-numeric: tabular-nums; }
549
+ .badge {
550
+ font-family: var(--mono);
551
+ font-weight: 600;
552
+ font-size: 11px;
553
+ padding: 2px 6px;
554
+ border-radius: 5px;
555
+ }
556
+ .badge.ok { background: var(--ok-bg); color: var(--ok); }
557
+ .badge.err { background: var(--err-bg); color: var(--err); }
558
+ .path { font-family: var(--mono); font-weight: 500; font-size: 12.5px; }
559
+ .pill {
560
+ font-family: var(--mono);
561
+ font-weight: 500;
562
+ font-size: 11px;
563
+ padding: 2px 6px;
564
+ border-radius: 5px;
565
+ background: var(--tok-bg);
566
+ color: var(--tok-fg);
567
+ border: 1px solid var(--tok-border);
568
+ }
569
+ .body {
570
+ border-top: 1px solid var(--border);
571
+ padding: 12px 14px;
572
+ background: var(--bg-subtle);
573
+ }
574
+ .body-label { font-size: 11.5px; color: var(--muted); margin: 0 0 8px; }
575
+ .preview {
576
+ margin: 0 0 8px;
577
+ padding: 10px 12px;
578
+ border: 1px solid var(--border);
579
+ border-radius: 6px;
580
+ background: var(--bg);
581
+ font: 12.5px/1.6 var(--mono);
582
+ white-space: pre-wrap;
583
+ word-break: break-word;
584
+ }
585
+ .tok {
586
+ display: inline-block;
587
+ padding: 0 4px;
588
+ border-radius: 4px;
589
+ background: var(--tok-bg);
590
+ color: var(--tok-fg);
591
+ border: 1px solid var(--tok-border);
592
+ font-weight: 600;
593
+ }
594
+ .vault-box {
595
+ margin-top: 24px;
596
+ border: 1px solid var(--border);
597
+ border-radius: 8px;
598
+ padding: 14px 16px;
599
+ background: var(--bg-subtle);
600
+ }
601
+ .vault-box h2 { margin: 0 0 6px; font-size: 14px; }
602
+ .vault-box p { margin: 0 0 10px; font-size: 12.5px; color: var(--muted); }
603
+ table { width: 100%; border-collapse: collapse; font-size: 12.5px; }
604
+ th, td { text-align: left; padding: 6px 8px; border-bottom: 1px solid var(--border); font-family: var(--mono); }
605
+ th { font-family: var(--sans); font-size: 11.5px; color: var(--muted); }
606
+ </style>
607
+ </head>
608
+ <body>
609
+ <div class="wrap">
610
+ <header>
611
+ <div>
612
+ <h1><span class="dot"></span>Maskera lokal proxy-inspekt\xF6r</h1>
613
+ <p class="sub">K\xF6rs enbart p\xE5 ${safeUrl} \xB7 l\xE4ge: ${info.defaultMode} \xB7 \xE5terst\xE4llning: ${info.restoreResponses ? "p\xE5" : "av"} \xB7 allt lagras bara i lokalt RAM</p>
614
+ </div>
615
+ <div class="actions">
616
+ <button id="reveal-btn" type="button">Visa originalv\xE4rden lokalt</button>
617
+ <button id="clear-btn" type="button">Rensa minne</button>
618
+ </div>
619
+ </header>
620
+
621
+ <section class="stats">
622
+ <div class="stat"><div class="stat-k">Anrop</div><div class="stat-v" id="st-req">0</div></div>
623
+ <div class="stat"><div class="stat-k">Maskerade uppgifter</div><div class="stat-v" id="st-red">0</div></div>
624
+ <div class="stat"><div class="stat-k">Unika i sessionsvalvet</div><div class="stat-v" id="st-uniq">0</div></div>
625
+ <div class="stat"><div class="stat-k">AI-modell</div><div class="stat-v" id="st-model">Redo</div></div>
626
+ </section>
627
+
628
+ <div id="feed"></div>
629
+ <div id="vault-root"></div>
630
+ </div>
631
+ <script>
632
+ (() => {
633
+ const feedEl = document.getElementById("feed");
634
+ const vaultRoot = document.getElementById("vault-root");
635
+ const revealBtn = document.getElementById("reveal-btn");
636
+ const clearBtn = document.getElementById("clear-btn");
637
+ const stReq = document.getElementById("st-req");
638
+ const stRed = document.getElementById("st-red");
639
+ const stUniq = document.getElementById("st-uniq");
640
+ const stModel = document.getElementById("st-model");
641
+ let items = [];
642
+ let reveal = false;
643
+ let userToggled = false;
644
+ const openIds = new Set();
645
+ const seenIds = new Set();
646
+
647
+ const esc = (s) => s.replace(/[&<>"']/g, (c) => ({ "&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;" }[c]));
648
+ const highlightTokens = (s) => esc(s).replace(/\\[[A-Z\xC5\xC4\xD6][A-Z\xC5\xC4\xD60-9_]*_\\d+\\]/g, (m) => '<span class="tok">' + m + "</span>");
649
+
650
+ async function refreshStatus() {
651
+ try {
652
+ const r = await fetch("/_maskera/status");
653
+ const d = await r.json();
654
+ stReq.textContent = String(d.requests_proxied ?? 0);
655
+ stRed.textContent = String(d.total_redactions ?? 0);
656
+ const uniq = (d.sessions || []).reduce((sum, s) => sum + (s.entityCount || 0), 0);
657
+ stUniq.textContent = String(uniq);
658
+ stModel.textContent = d.engine?.defaultMode === "rules"
659
+ ? "Regler"
660
+ : (d.engine?.nerError ? "Fel" : (d.engine?.nerLoaded ? "ONNX aktiv" : "V\xE4ntar"));
661
+ } catch {}
662
+ }
663
+
664
+ async function refreshVault() {
665
+ if (!reveal) { vaultRoot.innerHTML = ""; return; }
666
+ try {
667
+ const r = await fetch("/_maskera/vault", { headers: { "x-maskera-reveal": "1" } });
668
+ const d = await r.json();
669
+ const rows = (d.entries || []).map((e) => "<tr><td>" + esc(e.sessionId) + "</td><td><span class=\\"tok\\">" + esc(e.token) + "</span></td><td>" + esc(e.value) + "</td></tr>").join("");
670
+ vaultRoot.innerHTML = '<section class="vault-box"><h2>Lokal \xE5terst\xE4llningsnyckel (stannar i RAM)</h2><p>D\xF6lj den h\xE4r vyn innan du delar sk\xE4rm.</p>' +
671
+ (rows ? "<table><thead><tr><th>Session</th><th>Platsh\xE5llare</th><th>Originalv\xE4rde</th></tr></thead><tbody>" + rows + "</tbody></table>" : "<p>Inga lagrade v\xE4rden \xE4n.</p>") +
672
+ "</section>";
673
+ } catch {}
674
+ }
675
+
676
+ function render() {
677
+ if (!items.length) {
678
+ feedEl.innerHTML = '<div class="empty">Inga proxade AI-anrop \xE4nnu. Peka din agent hit f\xF6r att se maskeringen i realtid:<code>ANTHROPIC_BASE_URL=${safeUrl} claude\\nOPENAI_BASE_URL=${safeUrl}/v1 codex</code></div>';
679
+ return;
680
+ }
681
+ if (seenIds.size === 0 && items[0]?.id) {
682
+ openIds.add(items[0].id);
683
+ }
684
+ for (const it of items) seenIds.add(it.id);
685
+ feedEl.innerHTML = '<div class="list">' + items.map((it) => {
686
+ const time = (it.timestamp || "").slice(11, 19);
687
+ const pills = Object.entries(it.counts || {}).map(([k, v]) => '<span class="pill">' + esc(k) + " \xD7" + v + "</span>").join("");
688
+ const previews = (it.redactedPreview || []).map((p) => '<pre class="preview">' + highlightTokens(p) + "</pre>").join("");
689
+ const statusCls = it.status >= 200 && it.status < 400 ? "ok" : "err";
690
+ const isOpen = openIds.has(it.id);
691
+ return '<details class="item" data-id="' + esc(it.id) + '"' + (isOpen ? " open" : "") + '>' +
692
+ '<summary><span class="left"><span class="badge ' + statusCls + '">' + it.status + '</span><span class="path">' + esc(it.method + " " + it.path) + '</span>' + pills + (it.redactions === 0 ? '<span style="color:var(--muted);font-size:12px">0 PII</span>' : "") + '</span>' +
693
+ '<span class="right"><span>' + (it.streamed ? "SSE" : "JSON") + '</span><span>' + it.durationMs + ' ms</span><span>' + esc(time) + '</span></span></summary>' +
694
+ '<div class="body"><p class="body-label">Vad som skickades vidare till molnet (0 r\xE5 PII):</p>' + (previews || '<pre class="preview">(ingen text i anropet)</pre>') + '</div></details>';
695
+ }).join("") + "</div>";
696
+ for (const det of feedEl.querySelectorAll("details.item")) {
697
+ det.addEventListener("toggle", () => {
698
+ const id = det.getAttribute("data-id");
699
+ if (!id) return;
700
+ userToggled = true;
701
+ if (det.open) openIds.add(id);
702
+ else openIds.delete(id);
703
+ });
704
+ }
705
+ }
706
+
707
+ revealBtn.addEventListener("click", () => {
708
+ reveal = !reveal;
709
+ revealBtn.classList.toggle("active", reveal);
710
+ revealBtn.textContent = reveal ? "D\xF6lj originalv\xE4rden" : "Visa originalv\xE4rden lokalt";
711
+ void refreshVault();
712
+ });
713
+
714
+ clearBtn.addEventListener("click", async () => {
715
+ await fetch("/_maskera/clear", { method: "POST", headers: { "x-maskera-action": "clear" } });
716
+ items = [];
717
+ userToggled = false;
718
+ openIds.clear();
719
+ seenIds.clear();
720
+ render();
721
+ await refreshStatus();
722
+ await refreshVault();
723
+ });
724
+
725
+ const es = new EventSource("/_maskera/events");
726
+ es.addEventListener("init", (ev) => {
727
+ items = JSON.parse(ev.data).items || [];
728
+ render();
729
+ void refreshStatus();
730
+ });
731
+ es.addEventListener("request", (ev) => {
732
+ const next = JSON.parse(ev.data);
733
+ items.unshift(next);
734
+ if (items.length > 100) items.length = 100;
735
+ if (!userToggled && openIds.size === 0 && next?.id) openIds.add(next.id);
736
+ render();
737
+ void refreshStatus();
738
+ if (reveal) void refreshVault();
739
+ });
740
+ es.addEventListener("cleared", () => {
741
+ items = [];
742
+ userToggled = false;
743
+ openIds.clear();
744
+ seenIds.clear();
745
+ render();
746
+ void refreshStatus();
747
+ void refreshVault();
748
+ });
749
+ void refreshStatus();
750
+ })();
751
+ </script>
752
+ </body>
753
+ </html>`;
754
+ }
166
755
  var DEFAULT_MAX_SESSIONS = 100;
756
+ var DEFAULT_MAX_ENTITIES_PER_SESSION = 5e3;
757
+ var EXISTING_TOKEN_RE = /\[[A-ZÅÄÖ][A-ZÅÄÖ0-9_]*_\d+\]/g;
167
758
  function valueKey(label, value) {
168
759
  return `${label.length}:${label}:${value}`;
169
760
  }
761
+ function labelFromKey(key) {
762
+ const firstColon = key.indexOf(":");
763
+ if (firstColon < 1) return null;
764
+ const len = Number(key.slice(0, firstColon));
765
+ if (!Number.isInteger(len) || len <= 0) return null;
766
+ return key.slice(firstColon + 1, firstColon + 1 + len);
767
+ }
170
768
  var SessionVault = class {
171
- constructor(maxSessions = DEFAULT_MAX_SESSIONS) {
769
+ constructor(maxSessions = DEFAULT_MAX_SESSIONS, maxEntitiesPerSession = DEFAULT_MAX_ENTITIES_PER_SESSION) {
172
770
  this.sessions = /* @__PURE__ */ new Map();
173
771
  this.maxSessions = Math.max(1, maxSessions);
772
+ this.maxEntitiesPerSession = Math.max(1, maxEntitiesPerSession);
174
773
  }
175
774
  getOrCreate(sessionId) {
176
775
  const id = sessionId?.trim() || `s_${randomUUID().slice(0, 12)}`;
@@ -205,23 +804,49 @@ var SessionVault = class {
205
804
  */
206
805
  apply(originalInput, result, sessionId) {
207
806
  const session = this.getOrCreate(sessionId);
807
+ if (result.redactions.length === 0) {
808
+ return {
809
+ sessionId: session.id,
810
+ redacted: originalInput,
811
+ counts: {},
812
+ totalRedactions: 0,
813
+ map: {}
814
+ };
815
+ }
208
816
  const counts = {};
209
817
  const localMap = {};
818
+ const existingTokens = originalInput.includes("[") ? new Set(originalInput.match(EXISTING_TOKEN_RE) ?? []) : null;
210
819
  let redacted = "";
211
820
  let cursor = 0;
212
821
  for (const r of result.redactions) {
213
822
  const key = valueKey(r.label, r.value);
214
823
  let token = session.tokenByKey.get(key);
215
- if (!token) {
824
+ if (token) {
825
+ session.tokenByKey.delete(key);
826
+ session.tokenByKey.set(key, token);
827
+ } else {
216
828
  let next = session.counters.get(r.label) ?? 0;
217
829
  for (; ; ) {
218
830
  next += 1;
219
831
  const candidate = `[${r.label}_${next}]`;
220
- if (!(candidate in session.map) && !originalInput.includes(candidate)) {
832
+ if (!(candidate in session.map) && !existingTokens?.has(candidate)) {
221
833
  token = candidate;
222
834
  break;
223
835
  }
224
836
  }
837
+ if (session.tokenByKey.size >= this.maxEntitiesPerSession) {
838
+ const oldestEntry = session.tokenByKey.entries().next().value;
839
+ if (oldestEntry) {
840
+ const [oldestKey, oldestToken] = oldestEntry;
841
+ session.tokenByKey.delete(oldestKey);
842
+ delete session.map[oldestToken];
843
+ const oldLabel = labelFromKey(oldestKey);
844
+ if (oldLabel && session.countsByLabel[oldLabel]) {
845
+ session.countsByLabel[oldLabel] -= 1;
846
+ if (session.countsByLabel[oldLabel] <= 0) delete session.countsByLabel[oldLabel];
847
+ }
848
+ }
849
+ }
225
850
  session.counters.set(r.label, next);
226
851
  session.tokenByKey.set(key, token);
227
852
  session.map[token] = r.value;
@@ -242,19 +867,20 @@ var SessionVault = class {
242
867
  };
243
868
  }
244
869
  restore(text, options) {
870
+ const normalizedId = options.sessionId?.trim() || void 0;
245
871
  if (options.map && Object.keys(options.map).length > 0) {
246
872
  return {
247
873
  restored: restore(text, options.map),
248
- sessionId: options.sessionId ?? null,
874
+ sessionId: normalizedId ?? null,
249
875
  knownPlaceholders: Object.keys(options.map).length
250
876
  };
251
877
  }
252
- if (!options.sessionId) {
878
+ if (!normalizedId) {
253
879
  throw new Error("Provide either session_id or map to restore placeholders.");
254
880
  }
255
- const session = this.sessions.get(options.sessionId);
881
+ const session = this.sessions.get(normalizedId);
256
882
  if (!session) {
257
- throw new Error(`Unknown session_id "${options.sessionId}".`);
883
+ throw new Error(`Unknown session_id "${normalizedId}".`);
258
884
  }
259
885
  return {
260
886
  restored: restore(text, session.map),
@@ -263,9 +889,21 @@ var SessionVault = class {
263
889
  };
264
890
  }
265
891
  getMap(sessionId) {
266
- const session = this.sessions.get(sessionId);
892
+ const session = this.sessions.get(sessionId.trim());
267
893
  return session ? { ...session.map } : {};
268
894
  }
895
+ entries() {
896
+ const out = [];
897
+ for (const s of this.sessions.values()) {
898
+ for (const [token, value] of Object.entries(s.map)) {
899
+ out.push({ sessionId: s.id, token, value });
900
+ }
901
+ }
902
+ return out;
903
+ }
904
+ clearAll() {
905
+ this.sessions.clear();
906
+ }
269
907
  list() {
270
908
  return [...this.sessions.values()].map((s) => ({
271
909
  sessionId: s.id,
@@ -276,7 +914,7 @@ var SessionVault = class {
276
914
  }));
277
915
  }
278
916
  clear(sessionId) {
279
- return this.sessions.delete(sessionId);
917
+ return this.sessions.delete(sessionId.trim());
280
918
  }
281
919
  get size() {
282
920
  return this.sessions.size;
@@ -326,6 +964,7 @@ var StreamingRestorer = class {
326
964
  }
327
965
  push(chunk) {
328
966
  if (!chunk || this.tokens.length === 0) return chunk;
967
+ if (!this.buffer && !chunk.includes("[")) return chunk;
329
968
  this.buffer += chunk;
330
969
  return this.drain(false);
331
970
  }
@@ -383,12 +1022,12 @@ function mergeCounts(target, delta) {
383
1022
  }
384
1023
  }
385
1024
  function restorePlainText(text, map) {
386
- if (!text || Object.keys(map).length === 0) return text;
1025
+ if (!text || !text.includes("[") || Object.keys(map).length === 0) return text;
387
1026
  const r = new StreamingRestorer(map);
388
1027
  return r.push(text) + r.flush();
389
1028
  }
390
1029
  function restoreJsonEncodedText(text, map) {
391
- if (!text || Object.keys(map).length === 0) return text;
1030
+ if (!text || !text.includes("[") || Object.keys(map).length === 0) return text;
392
1031
  try {
393
1032
  const parsed = JSON.parse(text);
394
1033
  const restored = restoreJsonLeaves(parsed, map);
@@ -410,76 +1049,135 @@ function restoreJsonLeaves(value, map) {
410
1049
  }
411
1050
  return value;
412
1051
  }
413
- async function redactLlmRequestBody(body, redactString) {
414
- const clone = structuredClone(body);
415
- async function redactContentBlocks(blocks) {
1052
+ var MASKERA_VAULT_TOOL_RE = /(?:^|__)maskera_(?:write_file|restore|clear_session)$/;
1053
+ var MASKERA_VAULT_CODE_RE = /\bmaskera_(?:write_file|restore)\b/;
1054
+ function isMaskeraVaultToolName(name) {
1055
+ return typeof name === "string" && MASKERA_VAULT_TOOL_RE.test(name);
1056
+ }
1057
+ function shouldSkipToolArgRestore(toolName, argsText) {
1058
+ if (isMaskeraVaultToolName(toolName)) return true;
1059
+ if (toolName === "execute" && MASKERA_VAULT_CODE_RE.test(argsText)) return true;
1060
+ return false;
1061
+ }
1062
+ async function redactLlmRequestBody(body, redactString, options = {}) {
1063
+ const clone = options.mutate ? body : structuredClone(body);
1064
+ async function redactContentBlocks(blocks, kind) {
416
1065
  for (const block of blocks) {
417
1066
  if (!isPlainObject(block)) continue;
418
1067
  if (typeof block.text === "string") {
419
- block.text = await redactString(block.text);
1068
+ block.text = await redactString(block.text, kind);
1069
+ }
1070
+ if (typeof block.thinking === "string") {
1071
+ const redactedThinking = await redactString(block.thinking, kind);
1072
+ if (redactedThinking !== block.thinking) {
1073
+ block.thinking = redactedThinking;
1074
+ delete block.signature;
1075
+ }
1076
+ }
1077
+ if (typeof block.title === "string") {
1078
+ block.title = await redactString(block.title, kind);
1079
+ }
1080
+ if (typeof block.context === "string") {
1081
+ block.context = await redactString(block.context, kind);
420
1082
  }
421
1083
  if (typeof block.content === "string") {
422
- block.content = await redactString(block.content);
1084
+ block.content = await redactString(block.content, kind);
423
1085
  } else if (Array.isArray(block.content)) {
424
- await redactContentBlocks(block.content);
1086
+ await redactContentBlocks(block.content, kind);
425
1087
  }
426
1088
  if (typeof block.output === "string") {
427
- block.output = await redactString(block.output);
1089
+ block.output = await redactString(block.output, kind);
1090
+ } else if (Array.isArray(block.output)) {
1091
+ await redactContentBlocks(block.output, kind);
1092
+ }
1093
+ if (isPlainObject(block.source)) {
1094
+ if (block.source.type === "text" && typeof block.source.data === "string") {
1095
+ block.source.data = await redactString(block.source.data, kind);
1096
+ }
1097
+ if (typeof block.source.content === "string") {
1098
+ block.source.content = await redactString(block.source.content, kind);
1099
+ } else if (Array.isArray(block.source.content)) {
1100
+ await redactContentBlocks(block.source.content, kind);
1101
+ }
428
1102
  }
429
1103
  if (typeof block.arguments === "string") {
430
- block.arguments = await redactJsonStringOrText(block.arguments);
1104
+ block.arguments = await redactJsonStringOrText(block.arguments, kind);
431
1105
  }
432
1106
  if (isPlainObject(block.input)) {
433
- block.input = await redactObjectStrings(block.input);
1107
+ block.input = await redactObjectStrings(block.input, kind);
434
1108
  }
435
1109
  }
436
1110
  }
437
- async function redactObjectStrings(value) {
438
- if (typeof value === "string") return redactString(value);
1111
+ async function redactObjectStrings(value, kind) {
1112
+ if (typeof value === "string") return redactString(value, kind);
439
1113
  if (Array.isArray(value)) {
440
1114
  const out = [];
441
- for (const item of value) out.push(await redactObjectStrings(item));
1115
+ for (const item of value) out.push(await redactObjectStrings(item, kind));
442
1116
  return out;
443
1117
  }
444
1118
  if (isPlainObject(value)) {
445
1119
  const out = {};
446
1120
  for (const [k, v] of Object.entries(value)) {
447
- out[k] = await redactObjectStrings(v);
1121
+ out[k] = await redactObjectStrings(v, kind);
448
1122
  }
449
1123
  return out;
450
1124
  }
451
1125
  return value;
452
1126
  }
453
- async function redactJsonStringOrText(raw) {
1127
+ async function redactJsonStringOrText(raw, kind) {
454
1128
  try {
455
1129
  const parsed = JSON.parse(raw);
456
- const redacted = await redactObjectStrings(parsed);
1130
+ const redacted = await redactObjectStrings(parsed, kind);
457
1131
  return JSON.stringify(redacted);
458
1132
  } catch {
459
- return redactString(raw);
1133
+ return redactString(raw, kind);
460
1134
  }
461
1135
  }
462
1136
  if (typeof clone.system === "string") {
463
- clone.system = await redactString(clone.system);
1137
+ clone.system = await redactString(clone.system, "system");
464
1138
  } else if (Array.isArray(clone.system)) {
465
- await redactContentBlocks(clone.system);
1139
+ await redactContentBlocks(clone.system, "system");
466
1140
  }
467
1141
  if (typeof clone.instructions === "string") {
468
- clone.instructions = await redactString(clone.instructions);
1142
+ clone.instructions = await redactString(clone.instructions, "system");
1143
+ }
1144
+ async function redactToolEntries(entries) {
1145
+ for (const tool of entries) {
1146
+ if (!isPlainObject(tool)) continue;
1147
+ if (typeof tool.description === "string") {
1148
+ tool.description = await redactString(tool.description, "tool_description");
1149
+ }
1150
+ if (isPlainObject(tool.function) && typeof tool.function.description === "string") {
1151
+ tool.function.description = await redactString(
1152
+ tool.function.description,
1153
+ "tool_description"
1154
+ );
1155
+ }
1156
+ if (Array.isArray(tool.tools)) {
1157
+ await redactToolEntries(tool.tools);
1158
+ }
1159
+ }
1160
+ }
1161
+ if (Array.isArray(clone.tools)) {
1162
+ await redactToolEntries(clone.tools);
469
1163
  }
470
1164
  if (Array.isArray(clone.messages)) {
471
1165
  for (const msg of clone.messages) {
472
1166
  if (!isPlainObject(msg)) continue;
1167
+ const msgKind = msg.role === "system" || msg.role === "developer" ? "system" : "message";
473
1168
  if (typeof msg.content === "string") {
474
- msg.content = await redactString(msg.content);
1169
+ msg.content = await redactString(msg.content, msgKind);
475
1170
  } else if (Array.isArray(msg.content)) {
476
- await redactContentBlocks(msg.content);
1171
+ await redactContentBlocks(msg.content, msgKind);
477
1172
  }
478
1173
  if (Array.isArray(msg.tool_calls)) {
479
1174
  for (const call of msg.tool_calls) {
480
1175
  if (isPlainObject(call) && isPlainObject(call.function)) {
481
1176
  if (typeof call.function.arguments === "string") {
482
- call.function.arguments = await redactJsonStringOrText(call.function.arguments);
1177
+ call.function.arguments = await redactJsonStringOrText(
1178
+ call.function.arguments,
1179
+ msgKind
1180
+ );
483
1181
  }
484
1182
  }
485
1183
  }
@@ -487,44 +1185,53 @@ async function redactLlmRequestBody(body, redactString) {
487
1185
  }
488
1186
  }
489
1187
  if (typeof clone.input === "string") {
490
- clone.input = await redactString(clone.input);
1188
+ clone.input = await redactString(clone.input, "message");
491
1189
  } else if (Array.isArray(clone.input)) {
492
1190
  for (let i = 0; i < clone.input.length; i++) {
493
1191
  const item = clone.input[i];
494
1192
  if (typeof item === "string") {
495
- clone.input[i] = await redactString(item);
1193
+ clone.input[i] = await redactString(item, "message");
496
1194
  } else if (isPlainObject(item)) {
497
- if (typeof item.text === "string") item.text = await redactString(item.text);
1195
+ const itemKind = item.role === "system" || item.role === "developer" ? "system" : "message";
1196
+ if (typeof item.text === "string") item.text = await redactString(item.text, itemKind);
498
1197
  if (typeof item.content === "string") {
499
- item.content = await redactString(item.content);
1198
+ item.content = await redactString(item.content, itemKind);
500
1199
  } else if (Array.isArray(item.content)) {
501
- await redactContentBlocks(item.content);
1200
+ await redactContentBlocks(item.content, itemKind);
502
1201
  }
503
1202
  if (typeof item.output === "string") {
504
- item.output = await redactString(item.output);
1203
+ item.output = await redactString(item.output, itemKind);
1204
+ } else if (Array.isArray(item.output)) {
1205
+ await redactContentBlocks(item.output, itemKind);
1206
+ }
1207
+ if (Array.isArray(item.summary)) {
1208
+ await redactContentBlocks(item.summary, itemKind);
505
1209
  }
506
1210
  if (typeof item.arguments === "string") {
507
- item.arguments = await redactJsonStringOrText(item.arguments);
1211
+ item.arguments = await redactJsonStringOrText(item.arguments, itemKind);
508
1212
  }
509
1213
  }
510
1214
  }
511
1215
  }
512
1216
  return clone;
513
1217
  }
514
- function restoreLlmResponseBody(body, map) {
1218
+ function restoreLlmResponseBody(body, map, options = {}) {
515
1219
  if (!isPlainObject(body) || Object.keys(map).length === 0) return body;
516
- const clone = structuredClone(body);
1220
+ const clone = options.mutate ? body : structuredClone(body);
517
1221
  if (Array.isArray(clone.content)) {
518
1222
  for (const block of clone.content) {
519
1223
  if (!isPlainObject(block)) continue;
520
1224
  if (typeof block.text === "string") {
521
1225
  block.text = restorePlainText(block.text, map);
522
1226
  }
523
- if (typeof block.thinking === "string") {
1227
+ if (typeof block.thinking === "string" && typeof block.signature !== "string") {
524
1228
  block.thinking = restorePlainText(block.thinking, map);
525
1229
  }
526
1230
  if (isPlainObject(block.input)) {
527
- block.input = restoreJsonLeaves(block.input, map);
1231
+ const skipRestore = isMaskeraVaultToolName(block.name) || block.name === "execute" && typeof block.input.code === "string" && MASKERA_VAULT_CODE_RE.test(block.input.code);
1232
+ if (!skipRestore) {
1233
+ block.input = restoreJsonLeaves(block.input, map);
1234
+ }
528
1235
  }
529
1236
  }
530
1237
  }
@@ -536,10 +1243,13 @@ function restoreLlmResponseBody(body, map) {
536
1243
  if (typeof msg.content === "string") {
537
1244
  msg.content = restorePlainText(msg.content, map);
538
1245
  }
1246
+ if (typeof msg.reasoning_content === "string") {
1247
+ msg.reasoning_content = restorePlainText(msg.reasoning_content, map);
1248
+ }
539
1249
  if (Array.isArray(msg.tool_calls)) {
540
1250
  for (const call of msg.tool_calls) {
541
1251
  if (isPlainObject(call) && isPlainObject(call.function)) {
542
- if (typeof call.function.arguments === "string") {
1252
+ if (typeof call.function.arguments === "string" && !shouldSkipToolArgRestore(call.function.name, call.function.arguments)) {
543
1253
  call.function.arguments = restoreJsonEncodedText(call.function.arguments, map);
544
1254
  }
545
1255
  }
@@ -557,7 +1267,7 @@ function restoreLlmResponseBody(body, map) {
557
1267
  if (Array.isArray(clone.output)) {
558
1268
  for (const item of clone.output) {
559
1269
  if (!isPlainObject(item)) continue;
560
- if (typeof item.arguments === "string") {
1270
+ if (typeof item.arguments === "string" && !shouldSkipToolArgRestore(item.name, item.arguments)) {
561
1271
  item.arguments = restoreJsonEncodedText(item.arguments, map);
562
1272
  }
563
1273
  if (Array.isArray(item.content)) {
@@ -567,12 +1277,21 @@ function restoreLlmResponseBody(body, map) {
567
1277
  }
568
1278
  }
569
1279
  }
1280
+ if (Array.isArray(item.summary)) {
1281
+ for (const part of item.summary) {
1282
+ if (isPlainObject(part) && typeof part.text === "string") {
1283
+ part.text = restorePlainText(part.text, map);
1284
+ }
1285
+ }
1286
+ }
570
1287
  }
571
1288
  }
572
1289
  return clone;
573
1290
  }
574
1291
  function createSseRestorer(map) {
575
1292
  const streams = /* @__PURE__ */ new Map();
1293
+ const toolNames = /* @__PURE__ */ new Map();
1294
+ const bufferedToolArgs = /* @__PURE__ */ new Map();
576
1295
  const getStream = (key, escapeForJsonString = false) => {
577
1296
  let r = streams.get(key);
578
1297
  if (!r) {
@@ -587,6 +1306,148 @@ function createSseRestorer(map) {
587
1306
  streams.delete(key);
588
1307
  return r.flush();
589
1308
  }
1309
+ function flushBufferedToolArgs(key) {
1310
+ const raw = bufferedToolArgs.get(key);
1311
+ if (raw === void 0) return "";
1312
+ bufferedToolArgs.delete(key);
1313
+ const name = toolNames.get(key);
1314
+ if (shouldSkipToolArgRestore(name, raw)) return raw;
1315
+ return restoreJsonEncodedText(raw, map);
1316
+ }
1317
+ function drainRemainingStreams() {
1318
+ const events = [];
1319
+ for (const key of [...bufferedToolArgs.keys()]) {
1320
+ const full = flushBufferedToolArgs(key);
1321
+ if (!full) continue;
1322
+ if (key.startsWith("openai_chat_tool:")) {
1323
+ const [, cIdx, tIdx] = key.split(":");
1324
+ events.push(
1325
+ `data: ${JSON.stringify({
1326
+ choices: [
1327
+ {
1328
+ index: Number(cIdx ?? 0),
1329
+ delta: {
1330
+ tool_calls: [{ index: Number(tIdx ?? 0), function: { arguments: full } }]
1331
+ }
1332
+ }
1333
+ ]
1334
+ })}`
1335
+ );
1336
+ } else if (key.startsWith("anth_json:")) {
1337
+ const idx = Number(key.split(":")[1] ?? 0);
1338
+ events.push(
1339
+ `event: content_block_delta
1340
+ data: ${JSON.stringify({
1341
+ type: "content_block_delta",
1342
+ index: idx,
1343
+ delta: { type: "input_json_delta", partial_json: full }
1344
+ })}`
1345
+ );
1346
+ } else if (key.startsWith("resp_args:")) {
1347
+ const outputIdx = Number(key.split(":")[1] ?? 0);
1348
+ events.push(
1349
+ `event: response.function_call_arguments.delta
1350
+ data: ${JSON.stringify({
1351
+ type: "response.function_call_arguments.delta",
1352
+ output_index: outputIdx,
1353
+ delta: full
1354
+ })}`
1355
+ );
1356
+ }
1357
+ }
1358
+ for (const key of [...streams.keys()]) {
1359
+ const tail = flushStream(key);
1360
+ if (!tail) continue;
1361
+ if (key.startsWith("openai_chat_text:")) {
1362
+ const idx = Number(key.split(":")[1] ?? 0);
1363
+ events.push(
1364
+ `data: ${JSON.stringify({ choices: [{ index: idx, delta: { content: tail } }] })}`
1365
+ );
1366
+ } else if (key.startsWith("openai_chat_tool:")) {
1367
+ const [, cIdx, tIdx] = key.split(":");
1368
+ events.push(
1369
+ `data: ${JSON.stringify({
1370
+ choices: [
1371
+ {
1372
+ index: Number(cIdx ?? 0),
1373
+ delta: {
1374
+ tool_calls: [{ index: Number(tIdx ?? 0), function: { arguments: tail } }]
1375
+ }
1376
+ }
1377
+ ]
1378
+ })}`
1379
+ );
1380
+ } else if (key.startsWith("anth_text:")) {
1381
+ const idx = Number(key.split(":")[1] ?? 0);
1382
+ events.push(
1383
+ `event: content_block_delta
1384
+ data: ${JSON.stringify({
1385
+ type: "content_block_delta",
1386
+ index: idx,
1387
+ delta: { type: "text_delta", text: tail }
1388
+ })}`
1389
+ );
1390
+ } else if (key.startsWith("anth_thinking:")) {
1391
+ const idx = Number(key.split(":")[1] ?? 0);
1392
+ events.push(
1393
+ `event: content_block_delta
1394
+ data: ${JSON.stringify({
1395
+ type: "content_block_delta",
1396
+ index: idx,
1397
+ delta: { type: "thinking_delta", thinking: tail }
1398
+ })}`
1399
+ );
1400
+ } else if (key.startsWith("anth_json:")) {
1401
+ const idx = Number(key.split(":")[1] ?? 0);
1402
+ events.push(
1403
+ `event: content_block_delta
1404
+ data: ${JSON.stringify({
1405
+ type: "content_block_delta",
1406
+ index: idx,
1407
+ delta: { type: "input_json_delta", partial_json: tail }
1408
+ })}`
1409
+ );
1410
+ } else if (key.startsWith("resp_text:")) {
1411
+ const [, outputIdx, contentIdx] = key.split(":");
1412
+ events.push(
1413
+ `event: response.output_text.delta
1414
+ data: ${JSON.stringify({
1415
+ type: "response.output_text.delta",
1416
+ output_index: Number(outputIdx ?? 0),
1417
+ content_index: Number(contentIdx ?? 0),
1418
+ delta: tail
1419
+ })}`
1420
+ );
1421
+ } else if (key.startsWith("openai_chat_reasoning:")) {
1422
+ const idx = Number(key.split(":")[1] ?? 0);
1423
+ events.push(
1424
+ `data: ${JSON.stringify({ choices: [{ index: idx, delta: { reasoning_content: tail } }] })}`
1425
+ );
1426
+ } else if (key.startsWith("resp_reasoning:")) {
1427
+ const [, outputIdx, summaryIdx] = key.split(":");
1428
+ events.push(
1429
+ `event: response.reasoning_summary_text.delta
1430
+ data: ${JSON.stringify({
1431
+ type: "response.reasoning_summary_text.delta",
1432
+ output_index: Number(outputIdx ?? 0),
1433
+ summary_index: Number(summaryIdx ?? 0),
1434
+ delta: tail
1435
+ })}`
1436
+ );
1437
+ } else if (key.startsWith("resp_args:")) {
1438
+ const outputIdx = Number(key.split(":")[1] ?? 0);
1439
+ events.push(
1440
+ `event: response.function_call_arguments.delta
1441
+ data: ${JSON.stringify({
1442
+ type: "response.function_call_arguments.delta",
1443
+ output_index: outputIdx,
1444
+ delta: tail
1445
+ })}`
1446
+ );
1447
+ }
1448
+ }
1449
+ return events;
1450
+ }
590
1451
  let sseBuffer = "";
591
1452
  function processEventBlock(block) {
592
1453
  const lines = block.split("\n");
@@ -599,30 +1460,7 @@ function createSseRestorer(map) {
599
1460
  }
600
1461
  const rawData = line.slice("data:".length).trimStart();
601
1462
  if (!rawData || rawData === "[DONE]") {
602
- for (const key of [...streams.keys()]) {
603
- const tail = flushStream(key);
604
- if (!tail) continue;
605
- if (key.startsWith("openai_chat_text:")) {
606
- const idx = Number(key.split(":")[1] ?? 0);
607
- extraEvents.push(
608
- `data: ${JSON.stringify({ choices: [{ index: idx, delta: { content: tail } }] })}`
609
- );
610
- } else if (key.startsWith("openai_chat_tool:")) {
611
- const [, cIdx, tIdx] = key.split(":");
612
- extraEvents.push(
613
- `data: ${JSON.stringify({
614
- choices: [
615
- {
616
- index: Number(cIdx ?? 0),
617
- delta: {
618
- tool_calls: [{ index: Number(tIdx ?? 0), function: { arguments: tail } }]
619
- }
620
- }
621
- ]
622
- })}`
623
- );
624
- }
625
- }
1463
+ extraEvents.push(...drainRemainingStreams());
626
1464
  outLines.push(line);
627
1465
  continue;
628
1466
  }
@@ -637,14 +1475,29 @@ function createSseRestorer(map) {
637
1475
  outLines.push(line);
638
1476
  continue;
639
1477
  }
1478
+ if (parsed.type === "content_block_start" && isPlainObject(parsed.content_block)) {
1479
+ const idx = typeof parsed.index === "number" ? parsed.index : 0;
1480
+ if (parsed.content_block.type === "tool_use" && typeof parsed.content_block.name === "string") {
1481
+ toolNames.set(`anth_json:${idx}`, parsed.content_block.name);
1482
+ }
1483
+ outLines.push(`data: ${JSON.stringify(parsed)}`);
1484
+ continue;
1485
+ }
640
1486
  if (parsed.type === "content_block_delta" && isPlainObject(parsed.delta)) {
641
1487
  const idx = typeof parsed.index === "number" ? parsed.index : 0;
642
1488
  if (parsed.delta.type === "text_delta" && typeof parsed.delta.text === "string") {
643
1489
  parsed.delta.text = getStream(`anth_text:${idx}`).push(parsed.delta.text);
1490
+ } else if (parsed.delta.type === "thinking_delta" && typeof parsed.delta.thinking === "string") {
1491
+ parsed.delta.thinking = getStream(`anth_thinking:${idx}`).push(parsed.delta.thinking);
644
1492
  } else if (parsed.delta.type === "input_json_delta" && typeof parsed.delta.partial_json === "string") {
645
- parsed.delta.partial_json = getStream(`anth_json:${idx}`, true).push(
646
- parsed.delta.partial_json
647
- );
1493
+ const key = `anth_json:${idx}`;
1494
+ const name = toolNames.get(key);
1495
+ if (isMaskeraVaultToolName(name)) ; else if (name === "execute") {
1496
+ bufferedToolArgs.set(key, (bufferedToolArgs.get(key) ?? "") + parsed.delta.partial_json);
1497
+ parsed.delta.partial_json = "";
1498
+ } else {
1499
+ parsed.delta.partial_json = getStream(key, true).push(parsed.delta.partial_json);
1500
+ }
648
1501
  }
649
1502
  outLines.push(`data: ${JSON.stringify(parsed)}`);
650
1503
  continue;
@@ -662,7 +1515,20 @@ data: ${JSON.stringify({
662
1515
  })}`
663
1516
  );
664
1517
  }
665
- const jsonTail = flushStream(`anth_json:${idx}`);
1518
+ const thinkingTail = flushStream(`anth_thinking:${idx}`);
1519
+ if (thinkingTail) {
1520
+ extraEvents.push(
1521
+ `event: content_block_delta
1522
+ data: ${JSON.stringify({
1523
+ type: "content_block_delta",
1524
+ index: idx,
1525
+ delta: { type: "thinking_delta", thinking: thinkingTail }
1526
+ })}`
1527
+ );
1528
+ }
1529
+ const jsonKey = `anth_json:${idx}`;
1530
+ const jsonTail = flushBufferedToolArgs(jsonKey) || flushStream(jsonKey);
1531
+ toolNames.delete(jsonKey);
666
1532
  if (jsonTail) {
667
1533
  extraEvents.push(
668
1534
  `event: content_block_delta
@@ -685,15 +1551,32 @@ data: ${JSON.stringify({
685
1551
  if (typeof delta.content === "string") {
686
1552
  delta.content = getStream(`openai_chat_text:${cIdx}`).push(delta.content);
687
1553
  }
1554
+ if (typeof delta.reasoning_content === "string") {
1555
+ delta.reasoning_content = getStream(`openai_chat_reasoning:${cIdx}`).push(
1556
+ delta.reasoning_content
1557
+ );
1558
+ }
688
1559
  if (Array.isArray(delta.tool_calls)) {
689
1560
  for (const call of delta.tool_calls) {
690
1561
  if (!isPlainObject(call)) continue;
691
1562
  const tIdx = typeof call.index === "number" ? call.index : 0;
692
- if (isPlainObject(call.function) && typeof call.function.arguments === "string") {
693
- call.function.arguments = getStream(
694
- `openai_chat_tool:${cIdx}:${tIdx}`,
695
- true
696
- ).push(call.function.arguments);
1563
+ const key = `openai_chat_tool:${cIdx}:${tIdx}`;
1564
+ if (isPlainObject(call.function)) {
1565
+ if (typeof call.function.name === "string" && call.function.name) {
1566
+ toolNames.set(key, call.function.name);
1567
+ }
1568
+ if (typeof call.function.arguments === "string") {
1569
+ const name = toolNames.get(key);
1570
+ if (isMaskeraVaultToolName(name)) ; else if (name === "execute") {
1571
+ bufferedToolArgs.set(
1572
+ key,
1573
+ (bufferedToolArgs.get(key) ?? "") + call.function.arguments
1574
+ );
1575
+ call.function.arguments = "";
1576
+ } else {
1577
+ call.function.arguments = getStream(key, true).push(call.function.arguments);
1578
+ }
1579
+ }
697
1580
  }
698
1581
  }
699
1582
  }
@@ -705,11 +1588,63 @@ data: ${JSON.stringify({
705
1588
  const d = choice.delta;
706
1589
  d.content = (typeof d.content === "string" ? d.content : "") + textTail;
707
1590
  }
1591
+ const reasoningTail = flushStream(`openai_chat_reasoning:${cIdx}`);
1592
+ if (reasoningTail) {
1593
+ if (!isPlainObject(choice.delta)) choice.delta = {};
1594
+ const d = choice.delta;
1595
+ d.reasoning_content = (typeof d.reasoning_content === "string" ? d.reasoning_content : "") + reasoningTail;
1596
+ }
1597
+ const toolPrefix = `openai_chat_tool:${cIdx}:`;
1598
+ for (const key of [...bufferedToolArgs.keys()]) {
1599
+ if (!key.startsWith(toolPrefix)) continue;
1600
+ const tIdx = Number(key.slice(toolPrefix.length) || 0);
1601
+ const fullArgs = flushBufferedToolArgs(key);
1602
+ toolNames.delete(key);
1603
+ if (!fullArgs) continue;
1604
+ extraEvents.push(
1605
+ `data: ${JSON.stringify({
1606
+ choices: [
1607
+ {
1608
+ index: cIdx,
1609
+ delta: {
1610
+ tool_calls: [{ index: tIdx, function: { arguments: fullArgs } }]
1611
+ }
1612
+ }
1613
+ ]
1614
+ })}`
1615
+ );
1616
+ }
1617
+ for (const key of [...streams.keys()]) {
1618
+ if (!key.startsWith(toolPrefix)) continue;
1619
+ const tIdx = Number(key.slice(toolPrefix.length) || 0);
1620
+ const toolTail = flushStream(key);
1621
+ toolNames.delete(key);
1622
+ if (!toolTail) continue;
1623
+ extraEvents.push(
1624
+ `data: ${JSON.stringify({
1625
+ choices: [
1626
+ {
1627
+ index: cIdx,
1628
+ delta: {
1629
+ tool_calls: [{ index: tIdx, function: { arguments: toolTail } }]
1630
+ }
1631
+ }
1632
+ ]
1633
+ })}`
1634
+ );
1635
+ }
708
1636
  }
709
1637
  }
710
1638
  outLines.push(`data: ${JSON.stringify(parsed)}`);
711
1639
  continue;
712
1640
  }
1641
+ if (parsed.type === "response.output_item.added" && isPlainObject(parsed.item)) {
1642
+ if (parsed.item.type === "function_call" && typeof parsed.item.name === "string") {
1643
+ toolNames.set(`resp_args:${String(parsed.output_index ?? 0)}`, parsed.item.name);
1644
+ }
1645
+ outLines.push(`data: ${JSON.stringify(parsed)}`);
1646
+ continue;
1647
+ }
713
1648
  if (parsed.type === "response.output_text.delta" && typeof parsed.delta === "string") {
714
1649
  const key = `resp_text:${String(parsed.output_index ?? 0)}:${String(parsed.content_index ?? 0)}`;
715
1650
  parsed.delta = getStream(key).push(parsed.delta);
@@ -736,15 +1671,48 @@ data: ${JSON.stringify({
736
1671
  outLines.push(`data: ${JSON.stringify(parsed)}`);
737
1672
  continue;
738
1673
  }
1674
+ if (parsed.type === "response.reasoning_summary_text.delta" && typeof parsed.delta === "string") {
1675
+ const key = `resp_reasoning:${String(parsed.output_index ?? 0)}:${String(parsed.summary_index ?? 0)}`;
1676
+ parsed.delta = getStream(key).push(parsed.delta);
1677
+ outLines.push(`data: ${JSON.stringify(parsed)}`);
1678
+ continue;
1679
+ }
1680
+ if (parsed.type === "response.reasoning_summary_text.done") {
1681
+ const key = `resp_reasoning:${String(parsed.output_index ?? 0)}:${String(parsed.summary_index ?? 0)}`;
1682
+ const tail = flushStream(key);
1683
+ if (tail) {
1684
+ extraEvents.push(
1685
+ `event: response.reasoning_summary_text.delta
1686
+ data: ${JSON.stringify({
1687
+ type: "response.reasoning_summary_text.delta",
1688
+ output_index: parsed.output_index ?? 0,
1689
+ summary_index: parsed.summary_index ?? 0,
1690
+ delta: tail
1691
+ })}`
1692
+ );
1693
+ }
1694
+ if (typeof parsed.text === "string") {
1695
+ parsed.text = restorePlainText(parsed.text, map);
1696
+ }
1697
+ outLines.push(`data: ${JSON.stringify(parsed)}`);
1698
+ continue;
1699
+ }
739
1700
  if (parsed.type === "response.function_call_arguments.delta" && typeof parsed.delta === "string") {
740
1701
  const key = `resp_args:${String(parsed.output_index ?? 0)}`;
741
- parsed.delta = getStream(key, true).push(parsed.delta);
1702
+ const name = toolNames.get(key);
1703
+ if (isMaskeraVaultToolName(name)) ; else if (name === "execute") {
1704
+ bufferedToolArgs.set(key, (bufferedToolArgs.get(key) ?? "") + parsed.delta);
1705
+ parsed.delta = "";
1706
+ } else {
1707
+ parsed.delta = getStream(key, true).push(parsed.delta);
1708
+ }
742
1709
  outLines.push(`data: ${JSON.stringify(parsed)}`);
743
1710
  continue;
744
1711
  }
745
1712
  if (parsed.type === "response.function_call_arguments.done") {
746
1713
  const key = `resp_args:${String(parsed.output_index ?? 0)}`;
747
- const tail = flushStream(key);
1714
+ const name = toolNames.get(key);
1715
+ const tail = flushBufferedToolArgs(key) || flushStream(key);
748
1716
  if (tail) {
749
1717
  extraEvents.push(
750
1718
  `event: response.function_call_arguments.delta
@@ -755,13 +1723,50 @@ data: ${JSON.stringify({
755
1723
  })}`
756
1724
  );
757
1725
  }
758
- if (typeof parsed.arguments === "string") {
1726
+ if (typeof parsed.arguments === "string" && !shouldSkipToolArgRestore(name, parsed.arguments)) {
759
1727
  parsed.arguments = restoreJsonEncodedText(parsed.arguments, map);
760
1728
  }
761
1729
  outLines.push(`data: ${JSON.stringify(parsed)}`);
762
1730
  continue;
763
1731
  }
764
- if (parsed.type === "response.completed" && isPlainObject(parsed.response)) {
1732
+ if (parsed.type === "error") {
1733
+ extraEvents.push(...drainRemainingStreams());
1734
+ outLines.push(`data: ${JSON.stringify(parsed)}`);
1735
+ continue;
1736
+ }
1737
+ if (parsed.type === "response.content_part.done" && isPlainObject(parsed.part)) {
1738
+ if (typeof parsed.part.text === "string") {
1739
+ parsed.part.text = restorePlainText(parsed.part.text, map);
1740
+ }
1741
+ outLines.push(`data: ${JSON.stringify(parsed)}`);
1742
+ continue;
1743
+ }
1744
+ if (parsed.type === "response.output_item.done" && isPlainObject(parsed.item)) {
1745
+ const item = parsed.item;
1746
+ const key = `resp_args:${String(parsed.output_index ?? 0)}`;
1747
+ const name = typeof item.name === "string" ? item.name : toolNames.get(key);
1748
+ toolNames.delete(key);
1749
+ if (typeof item.arguments === "string" && !shouldSkipToolArgRestore(name, item.arguments)) {
1750
+ item.arguments = restoreJsonEncodedText(item.arguments, map);
1751
+ }
1752
+ if (Array.isArray(item.content)) {
1753
+ for (const part of item.content) {
1754
+ if (isPlainObject(part) && typeof part.text === "string") {
1755
+ part.text = restorePlainText(part.text, map);
1756
+ }
1757
+ }
1758
+ }
1759
+ if (Array.isArray(item.summary)) {
1760
+ for (const part of item.summary) {
1761
+ if (isPlainObject(part) && typeof part.text === "string") {
1762
+ part.text = restorePlainText(part.text, map);
1763
+ }
1764
+ }
1765
+ }
1766
+ outLines.push(`data: ${JSON.stringify(parsed)}`);
1767
+ continue;
1768
+ }
1769
+ if ((parsed.type === "response.completed" || parsed.type === "response.incomplete") && isPlainObject(parsed.response)) {
765
1770
  parsed.response = restoreLlmResponseBody(parsed.response, map);
766
1771
  outLines.push(`data: ${JSON.stringify(parsed)}`);
767
1772
  continue;
@@ -773,15 +1778,19 @@ data: ${JSON.stringify({
773
1778
 
774
1779
  ${joined}` : joined;
775
1780
  }
1781
+ let pendingCr = false;
776
1782
  return {
777
1783
  push(chunk) {
778
- sseBuffer += chunk.replace(/\r\n/g, "\n");
1784
+ let text = pendingCr ? `\r${chunk}` : chunk;
1785
+ pendingCr = text.endsWith("\r");
1786
+ if (pendingCr) text = text.slice(0, -1);
1787
+ sseBuffer += text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
779
1788
  let out = "";
780
1789
  for (; ; ) {
781
- const sep = sseBuffer.indexOf("\n\n");
782
- if (sep < 0) break;
783
- const block = sseBuffer.slice(0, sep);
784
- sseBuffer = sseBuffer.slice(sep + 2);
1790
+ const sep2 = sseBuffer.indexOf("\n\n");
1791
+ if (sep2 < 0) break;
1792
+ const block = sseBuffer.slice(0, sep2);
1793
+ sseBuffer = sseBuffer.slice(sep2 + 2);
785
1794
  out += `${processEventBlock(block)}
786
1795
 
787
1796
  `;
@@ -789,13 +1798,113 @@ ${joined}` : joined;
789
1798
  return out;
790
1799
  },
791
1800
  flush() {
792
- if (!sseBuffer) return "";
793
- const tail = processEventBlock(sseBuffer);
794
- sseBuffer = "";
795
- return tail;
1801
+ if (pendingCr) {
1802
+ sseBuffer += "\n";
1803
+ pendingCr = false;
1804
+ }
1805
+ const parts = [];
1806
+ if (sseBuffer) {
1807
+ parts.push(processEventBlock(sseBuffer));
1808
+ sseBuffer = "";
1809
+ }
1810
+ const drained = drainRemainingStreams();
1811
+ if (drained.length > 0) {
1812
+ parts.push(`${drained.join("\n\n")}
1813
+
1814
+ `);
1815
+ }
1816
+ return parts.join("");
796
1817
  }
797
1818
  };
798
1819
  }
1820
+ var PayloadTooLargeError = class extends Error {
1821
+ constructor() {
1822
+ super(...arguments);
1823
+ this.statusCode = 413;
1824
+ }
1825
+ };
1826
+ var INSPECTOR_SECURITY_HEADERS = {
1827
+ "x-frame-options": "DENY",
1828
+ "content-security-policy": "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; frame-ancestors 'none'",
1829
+ "x-content-type-options": "nosniff",
1830
+ "referrer-policy": "no-referrer",
1831
+ "cache-control": "no-store"
1832
+ };
1833
+ var LOOPBACK_HOST_RE = /^(127\.0\.0\.1|localhost|\[::1\])(?::(\d{1,5}))?$/i;
1834
+ function isLoopbackHost(hostHeader, boundHost, boundPort, requirePresent = false) {
1835
+ if (!hostHeader) return !requirePresent;
1836
+ const raw = hostHeader.trim().toLowerCase();
1837
+ const match = LOOPBACK_HOST_RE.exec(raw);
1838
+ if (match) {
1839
+ const portStr = match[2];
1840
+ if (portStr !== void 0) {
1841
+ const p = Number(portStr);
1842
+ if (!Number.isInteger(p) || p < 1 || p > 65535) return false;
1843
+ if (boundPort > 0 && p !== boundPort) return false;
1844
+ }
1845
+ return true;
1846
+ }
1847
+ const boundLower = boundHost.toLowerCase();
1848
+ if (raw === boundLower || boundPort > 0 && raw === `${boundLower}:${boundPort}`) {
1849
+ return true;
1850
+ }
1851
+ return false;
1852
+ }
1853
+ function isSameOriginLoopbackRequest(req, boundHost, boundPort) {
1854
+ if (!isLoopbackHost(req.headers.host, boundHost, boundPort, true)) {
1855
+ return false;
1856
+ }
1857
+ const secFetchSite = String(req.headers["sec-fetch-site"] ?? "").toLowerCase();
1858
+ if (secFetchSite && secFetchSite !== "same-origin" && secFetchSite !== "none") {
1859
+ return false;
1860
+ }
1861
+ const origin = req.headers.origin;
1862
+ if (typeof origin === "string" && origin.trim()) {
1863
+ try {
1864
+ const parsed = new URL(origin);
1865
+ if (!isLoopbackHost(parsed.host, boundHost, boundPort, true)) return false;
1866
+ if (boundPort > 0 && parsed.port !== String(boundPort)) return false;
1867
+ if (req.headers.host && parsed.host.toLowerCase() !== req.headers.host.trim().toLowerCase()) {
1868
+ return false;
1869
+ }
1870
+ } catch {
1871
+ return false;
1872
+ }
1873
+ }
1874
+ return true;
1875
+ }
1876
+ function normalizeInspectorPath(rawPathname) {
1877
+ let decoded = rawPathname;
1878
+ try {
1879
+ decoded = decodeURIComponent(rawPathname);
1880
+ } catch {
1881
+ }
1882
+ return decoded.replace(/\/{2,}/g, "/").toLowerCase();
1883
+ }
1884
+ var UnsupportedContentEncodingError = class extends Error {
1885
+ constructor() {
1886
+ super(...arguments);
1887
+ this.statusCode = 415;
1888
+ }
1889
+ };
1890
+ var zstdDecompressSync2 = zlib.zstdDecompressSync;
1891
+ function decodeRequestBody(rawBody, encodingHeader) {
1892
+ const enc = (encodingHeader ?? "").trim().toLowerCase();
1893
+ if (!enc || enc === "identity") return rawBody;
1894
+ if (enc === "gzip") {
1895
+ return zlib.gunzipSync(rawBody, { maxOutputLength: MAX_BODY_BYTES });
1896
+ }
1897
+ if (enc === "deflate") {
1898
+ return zlib.inflateSync(rawBody, { maxOutputLength: MAX_BODY_BYTES });
1899
+ }
1900
+ if (enc === "br") {
1901
+ return zlib.brotliDecompressSync(rawBody, { maxOutputLength: MAX_BODY_BYTES });
1902
+ }
1903
+ if (enc === "zstd" && typeof zstdDecompressSync2 === "function") {
1904
+ return zstdDecompressSync2(rawBody, { maxOutputLength: MAX_BODY_BYTES });
1905
+ }
1906
+ throw new UnsupportedContentEncodingError(`Unsupported content-encoding: "${enc}".`);
1907
+ }
799
1908
  function resolveUpstreamTarget(urlPath, headers, options) {
800
1909
  if (urlPath.startsWith("/anthropic/")) {
801
1910
  return {
@@ -815,7 +1924,7 @@ function resolveUpstreamTarget(urlPath, headers, options) {
815
1924
  forwardPath: urlPath
816
1925
  };
817
1926
  }
818
- const isAnthropic = urlPath.startsWith("/v1/messages") || typeof headers["anthropic-version"] === "string" || typeof headers["x-api-key"] === "string";
1927
+ const isAnthropic = urlPath.startsWith("/v1/messages") || urlPath.startsWith("/api/") || typeof headers["anthropic-version"] === "string" || typeof headers["anthropic-beta"] === "string" || typeof headers["x-api-key"] === "string";
819
1928
  return {
820
1929
  baseUrl: (isAnthropic ? options.anthropicUpstream : options.openaiUpstream).replace(/\/$/, ""),
821
1930
  forwardPath: urlPath
@@ -828,44 +1937,176 @@ async function readRequestBody(req) {
828
1937
  const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
829
1938
  total += buf.byteLength;
830
1939
  if (total > MAX_BODY_BYTES) {
831
- throw new Error(`Request body exceeds ${MAX_BODY_BYTES} bytes.`);
1940
+ req.resume();
1941
+ throw new PayloadTooLargeError(`Request body exceeds ${MAX_BODY_BYTES} bytes.`);
832
1942
  }
833
1943
  chunks.push(buf);
834
1944
  }
835
1945
  return Buffer.concat(chunks);
836
1946
  }
837
1947
  function shouldRedactPath(pathname) {
838
- const clean = pathname.split("?")[0] ?? pathname;
839
- return clean.endsWith("/messages") || clean.endsWith("/chat/completions") || clean.endsWith("/responses");
1948
+ const clean = (pathname.split("?")[0] ?? pathname).replace(/\/+$/, "").toLowerCase();
1949
+ return clean.endsWith("/messages") || clean.endsWith("/messages/count_tokens") || clean.endsWith("/chat/completions") || clean.endsWith("/responses");
840
1950
  }
841
1951
  async function startMaskeraProxy(options = {}) {
842
1952
  const host = options.host ?? "127.0.0.1";
843
1953
  const requestedPort = options.port ?? 8787;
844
1954
  const engine = options.engine ?? createMaskeraEngine({ defaultMode: options.defaultMode });
845
1955
  const vault = options.vault ?? new SessionVault();
1956
+ const inspector = new ProxyInspector();
846
1957
  const restoreResponses = options.restoreResponses !== false;
847
1958
  const anthropicUpstream = options.anthropicUpstream ?? DEFAULT_ANTHROPIC_UPSTREAM;
848
1959
  const openaiUpstream = options.openaiUpstream ?? DEFAULT_OPENAI_UPSTREAM;
1960
+ const auditLogPath = options.auditLogPath;
849
1961
  const log = options.onLog ?? (() => {
850
1962
  });
1963
+ if (auditLogPath) {
1964
+ await mkdir(dirname(auditLogPath), { recursive: true });
1965
+ await appendFile(auditLogPath, "", "utf8");
1966
+ }
851
1967
  let totalRequests = 0;
852
1968
  let totalRedactions = 0;
1969
+ let boundPort = requestedPort;
1970
+ let boundUrl = `http://${host}:${requestedPort}`;
1971
+ let auditChain = Promise.resolve();
1972
+ function recordAuditAndInspector(entry) {
1973
+ totalRequests += 1;
1974
+ totalRedactions += entry.redactions;
1975
+ inspector.record(entry);
1976
+ if (auditLogPath) {
1977
+ const auditLine = JSON.stringify({
1978
+ timestamp: entry.timestamp,
1979
+ method: entry.method,
1980
+ path: entry.path,
1981
+ upstream: entry.upstream,
1982
+ status: entry.status,
1983
+ streamed: entry.streamed,
1984
+ durationMs: entry.durationMs,
1985
+ redactions: entry.redactions,
1986
+ counts: entry.counts
1987
+ });
1988
+ auditChain = auditChain.then(
1989
+ () => appendFile(auditLogPath, `${auditLine}
1990
+ `, "utf8").catch((err) => {
1991
+ log(
1992
+ `[maskera-proxy] audit log write error: ${err instanceof Error ? err.message : String(err)}`
1993
+ );
1994
+ })
1995
+ );
1996
+ }
1997
+ }
853
1998
  async function handleRequest(req, res) {
854
1999
  const startedAt = Date.now();
855
2000
  const method = req.method ?? "GET";
856
2001
  const urlPath = req.url ?? "/";
857
- if (method === "GET" && (urlPath === "/healthz" || urlPath === "/_maskera/status")) {
2002
+ const pathname = urlPath.split("?")[0] ?? urlPath;
2003
+ const normalizedPath = normalizeInspectorPath(pathname);
2004
+ const isInspectorRoute = normalizedPath === "/_maskera" || normalizedPath.startsWith("/_maskera/") || normalizedPath.includes("/_maskera/") || normalizedPath.endsWith("/_maskera");
2005
+ if (isInspectorRoute || pathname === "/healthz") {
2006
+ if (!isLoopbackHost(req.headers.host, host, boundPort)) {
2007
+ res.writeHead(403, {
2008
+ ...INSPECTOR_SECURITY_HEADERS,
2009
+ "content-type": "application/json; charset=utf-8"
2010
+ });
2011
+ res.end(JSON.stringify({ error: "Forbidden host header for local inspector route." }));
2012
+ return;
2013
+ }
2014
+ }
2015
+ if (method === "GET" && (pathname === "/_maskera" || pathname === "/_maskera/")) {
2016
+ res.writeHead(200, {
2017
+ ...INSPECTOR_SECURITY_HEADERS,
2018
+ "content-type": "text/html; charset=utf-8"
2019
+ });
2020
+ res.end(
2021
+ renderInspectorHtml({
2022
+ url: boundUrl,
2023
+ defaultMode: engine.status().defaultMode,
2024
+ restoreResponses
2025
+ })
2026
+ );
2027
+ return;
2028
+ }
2029
+ if (method === "GET" && pathname === "/_maskera/events") {
2030
+ inspector.subscribe(res, INSPECTOR_SECURITY_HEADERS);
2031
+ return;
2032
+ }
2033
+ if (method === "GET" && pathname === "/_maskera/vault") {
2034
+ if (req.headers["x-maskera-reveal"] !== "1" || !isSameOriginLoopbackRequest(req, host, boundPort)) {
2035
+ res.writeHead(403, {
2036
+ ...INSPECTOR_SECURITY_HEADERS,
2037
+ "content-type": "application/json; charset=utf-8"
2038
+ });
2039
+ res.end(JSON.stringify({ error: "Pass x-maskera-reveal: 1 to read local vault values." }));
2040
+ return;
2041
+ }
2042
+ res.writeHead(200, {
2043
+ ...INSPECTOR_SECURITY_HEADERS,
2044
+ "content-type": "application/json; charset=utf-8"
2045
+ });
2046
+ res.end(JSON.stringify({ entries: vault.entries() }));
2047
+ return;
2048
+ }
2049
+ if (method === "POST" && pathname === "/_maskera/clear") {
2050
+ if (req.headers["x-maskera-action"] !== "clear" || !isSameOriginLoopbackRequest(req, host, boundPort)) {
2051
+ res.writeHead(403, {
2052
+ ...INSPECTOR_SECURITY_HEADERS,
2053
+ "content-type": "application/json; charset=utf-8"
2054
+ });
2055
+ res.end(
2056
+ JSON.stringify({ error: "Pass x-maskera-action: clear from same-origin loopback." })
2057
+ );
2058
+ return;
2059
+ }
2060
+ vault.clearAll();
2061
+ engine.clearCache();
2062
+ inspector.clear();
2063
+ totalRequests = 0;
2064
+ totalRedactions = 0;
2065
+ res.writeHead(200, {
2066
+ ...INSPECTOR_SECURITY_HEADERS,
2067
+ "content-type": "application/json; charset=utf-8"
2068
+ });
2069
+ res.end(JSON.stringify({ cleared: true }));
2070
+ return;
2071
+ }
2072
+ if (method === "GET" && (pathname === "/healthz" || pathname === "/_maskera/status")) {
858
2073
  const payload = {
859
2074
  status: "ok",
2075
+ inspector_url: `${boundUrl}/_maskera`,
860
2076
  engine: engine.status(),
861
2077
  requests_proxied: totalRequests,
862
2078
  total_redactions: totalRedactions,
863
2079
  sessions: vault.list()
864
2080
  };
865
- res.writeHead(200, { "content-type": "application/json; charset=utf-8" });
2081
+ res.writeHead(200, {
2082
+ ...INSPECTOR_SECURITY_HEADERS,
2083
+ "content-type": "application/json; charset=utf-8"
2084
+ });
866
2085
  res.end(JSON.stringify(payload, null, 2));
867
2086
  return;
868
2087
  }
2088
+ if (isInspectorRoute) {
2089
+ res.writeHead(404, {
2090
+ ...INSPECTOR_SECURITY_HEADERS,
2091
+ "content-type": "application/json; charset=utf-8"
2092
+ });
2093
+ res.end(JSON.stringify({ error: "Unknown inspector route." }));
2094
+ return;
2095
+ }
2096
+ if (String(req.headers.upgrade ?? "").toLowerCase() === "websocket") {
2097
+ res.writeHead(426, {
2098
+ "content-type": "application/json; charset=utf-8",
2099
+ connection: "close"
2100
+ });
2101
+ res.end(
2102
+ JSON.stringify({
2103
+ error: {
2104
+ message: "WebSocket transport is not supported by maskera-proxy; retry over HTTP SSE."
2105
+ }
2106
+ })
2107
+ );
2108
+ return;
2109
+ }
869
2110
  const { baseUrl, forwardPath } = resolveUpstreamTarget(urlPath, req.headers, {
870
2111
  explicitUpstream: options.upstream,
871
2112
  anthropicUpstream,
@@ -876,39 +2117,84 @@ async function startMaskeraProxy(options = {}) {
876
2117
  const sessionHeader = req.headers["x-maskera-session"];
877
2118
  const sessionId = typeof sessionHeader === "string" && sessionHeader.trim() ? sessionHeader.trim() : "proxy";
878
2119
  const stats = { redactions: 0, counts: {} };
2120
+ const redactedPreview = [];
879
2121
  let outgoingBody = rawBody;
880
- const contentType = String(req.headers["content-type"] ?? "");
881
- if (rawBody && rawBody.byteLength > 0 && shouldRedactPath(forwardPath) && contentType.includes("application/json")) {
2122
+ let rewroteRequestBody = false;
2123
+ const contentType = String(req.headers["content-type"] ?? "").trim().toLowerCase();
2124
+ const contentEncoding = typeof req.headers["content-encoding"] === "string" ? req.headers["content-encoding"] : void 0;
2125
+ const mayBeJson = contentType === "" || contentType.includes("json") || contentType.startsWith("text/plain");
2126
+ if (rawBody && rawBody.byteLength > 0 && shouldRedactPath(forwardPath) && mayBeJson) {
2127
+ let decodedBody;
2128
+ try {
2129
+ decodedBody = decodeRequestBody(rawBody, contentEncoding);
2130
+ } catch (err) {
2131
+ if (err instanceof UnsupportedContentEncodingError) {
2132
+ res.writeHead(415, { "content-type": "application/json; charset=utf-8" });
2133
+ res.end(JSON.stringify({ error: { message: err.message } }));
2134
+ return;
2135
+ }
2136
+ res.writeHead(400, { "content-type": "application/json; charset=utf-8" });
2137
+ res.end(JSON.stringify({ error: { message: "Invalid compressed request body." } }));
2138
+ return;
2139
+ }
882
2140
  let parsed;
883
2141
  try {
884
- parsed = JSON.parse(rawBody.toString("utf8"));
2142
+ parsed = JSON.parse(decodedBody.toString("utf8"));
885
2143
  } catch {
886
2144
  res.writeHead(400, { "content-type": "application/json; charset=utf-8" });
887
2145
  res.end(JSON.stringify({ error: { message: "Invalid JSON request body." } }));
888
2146
  return;
889
2147
  }
890
2148
  if (isPlainObject(parsed)) {
891
- const redactedObj = await redactLlmRequestBody(parsed, async (text) => {
892
- if (!text.trim()) return text;
893
- const { result } = await engine.redact(text, {
894
- profile: options.profile,
895
- customTerms: options.customTerms
2149
+ let redactedObj;
2150
+ try {
2151
+ redactedObj = await redactLlmRequestBody(
2152
+ parsed,
2153
+ async (text, kind) => {
2154
+ if (!text.trim()) return text;
2155
+ const { result } = await engine.redact(text, {
2156
+ mode: kind === "tool_description" ? "rules" : void 0,
2157
+ profile: options.profile,
2158
+ customTerms: options.customTerms
2159
+ });
2160
+ const applied = vault.apply(text, result, sessionId);
2161
+ stats.redactions += applied.totalRedactions;
2162
+ mergeCounts(stats.counts, applied.counts);
2163
+ if (redactedPreview.length < 6) {
2164
+ const snippet = applied.redacted.length > 1200 ? `${applied.redacted.slice(0, 1200)}...` : applied.redacted;
2165
+ redactedPreview.push(snippet);
2166
+ }
2167
+ return applied.redacted;
2168
+ },
2169
+ { mutate: true }
2170
+ );
2171
+ } catch (err) {
2172
+ recordAuditAndInspector({
2173
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2174
+ method,
2175
+ path: forwardPath,
2176
+ upstream: baseUrl,
2177
+ sessionId,
2178
+ status: 502,
2179
+ streamed: false,
2180
+ durationMs: Date.now() - startedAt,
2181
+ redactions: stats.redactions,
2182
+ counts: stats.counts,
2183
+ redactedPreview
896
2184
  });
897
- const applied = vault.apply(text, result, sessionId);
898
- stats.redactions += applied.totalRedactions;
899
- mergeCounts(stats.counts, applied.counts);
900
- return applied.redacted;
901
- });
2185
+ throw err;
2186
+ }
902
2187
  outgoingBody = Buffer.from(JSON.stringify(redactedObj), "utf8");
2188
+ rewroteRequestBody = true;
903
2189
  }
904
2190
  }
905
- totalRequests += 1;
906
- totalRedactions += stats.redactions;
907
2191
  const forwardHeaders = new Headers();
908
2192
  for (const [k, v] of Object.entries(req.headers)) {
909
2193
  if (v === void 0) continue;
910
2194
  const lower = k.toLowerCase();
911
- if (HOP_BY_HOP_REQUEST_HEADERS.has(lower) || lower === "x-maskera-session") continue;
2195
+ if (HOP_BY_HOP_REQUEST_HEADERS.has(lower) || lower === "x-maskera-session" || rewroteRequestBody && lower === "content-encoding") {
2196
+ continue;
2197
+ }
912
2198
  if (Array.isArray(v)) {
913
2199
  for (const item of v) forwardHeaders.append(k, item);
914
2200
  } else {
@@ -916,11 +2202,39 @@ async function startMaskeraProxy(options = {}) {
916
2202
  }
917
2203
  }
918
2204
  forwardHeaders.set("accept-encoding", "identity");
919
- const upstreamRes = await fetch(upstreamUrl, {
920
- method,
921
- headers: forwardHeaders,
922
- body: outgoingBody ? new Uint8Array(outgoingBody) : void 0
923
- });
2205
+ const abortController = new AbortController();
2206
+ const onClientClose = () => {
2207
+ if (!res.writableEnded) abortController.abort();
2208
+ };
2209
+ res.on("close", onClientClose);
2210
+ let upstreamRes;
2211
+ try {
2212
+ upstreamRes = await fetch(upstreamUrl, {
2213
+ method,
2214
+ headers: forwardHeaders,
2215
+ body: outgoingBody ? new Uint8Array(outgoingBody) : void 0,
2216
+ signal: abortController.signal
2217
+ });
2218
+ } catch (err) {
2219
+ res.off("close", onClientClose);
2220
+ if (!abortController.signal.aborted) {
2221
+ const durationMs2 = Date.now() - startedAt;
2222
+ recordAuditAndInspector({
2223
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2224
+ method,
2225
+ path: forwardPath,
2226
+ upstream: baseUrl,
2227
+ sessionId,
2228
+ status: 502,
2229
+ streamed: false,
2230
+ durationMs: durationMs2,
2231
+ redactions: stats.redactions,
2232
+ counts: stats.counts,
2233
+ redactedPreview
2234
+ });
2235
+ }
2236
+ throw err;
2237
+ }
924
2238
  const outHeaders = {};
925
2239
  upstreamRes.headers.forEach((value, key) => {
926
2240
  if (!HOP_BY_HOP_RESPONSE_HEADERS.has(key.toLowerCase())) {
@@ -930,42 +2244,91 @@ async function startMaskeraProxy(options = {}) {
930
2244
  outHeaders["x-maskera-redacted"] = String(stats.redactions);
931
2245
  const sessionMap = restoreResponses ? vault.getMap(sessionId) : {};
932
2246
  const hasMap = Object.keys(sessionMap).length > 0;
933
- const resContentType = upstreamRes.headers.get("content-type") ?? "";
934
- if (hasMap && resContentType.includes("text/event-stream") && upstreamRes.body) {
2247
+ const resContentType = (upstreamRes.headers.get("content-type") ?? "").toLowerCase();
2248
+ const isSse = resContentType.includes("text/event-stream");
2249
+ if (isSse && upstreamRes.body) {
935
2250
  res.writeHead(upstreamRes.status, outHeaders);
936
- const sse = createSseRestorer(sessionMap);
937
- const decoder = new TextDecoder();
2251
+ const sse = hasMap ? createSseRestorer(sessionMap) : null;
2252
+ const decoder = sse ? new TextDecoder() : null;
938
2253
  const reader = upstreamRes.body.getReader();
2254
+ const onStreamAbort = () => {
2255
+ void reader.cancel().catch(() => {
2256
+ });
2257
+ };
2258
+ abortController.signal.addEventListener("abort", onStreamAbort, { once: true });
939
2259
  try {
940
2260
  for (; ; ) {
941
2261
  const { done, value } = await reader.read();
942
2262
  if (done) break;
943
- const chunkText = decoder.decode(value, { stream: true });
944
- const transformed = sse.push(chunkText);
945
- if (transformed) res.write(transformed);
2263
+ if (sse && decoder) {
2264
+ const chunkText = decoder.decode(value, { stream: true });
2265
+ const transformed = sse.push(chunkText);
2266
+ if (transformed) res.write(transformed);
2267
+ } else if (value) {
2268
+ res.write(value);
2269
+ }
2270
+ }
2271
+ if (sse && decoder) {
2272
+ const finalText = decoder.decode();
2273
+ const tail = (finalText ? sse.push(finalText) : "") + sse.flush();
2274
+ if (tail) res.write(tail);
946
2275
  }
947
- const finalText = decoder.decode();
948
- const tail = (finalText ? sse.push(finalText) : "") + sse.flush();
949
- if (tail) res.write(tail);
2276
+ } catch (err) {
2277
+ if (!abortController.signal.aborted) throw err;
950
2278
  } finally {
2279
+ abortController.signal.removeEventListener("abort", onStreamAbort);
2280
+ res.off("close", onClientClose);
951
2281
  reader.releaseLock();
952
- res.end();
953
- }
2282
+ if (!res.writableEnded) res.end();
2283
+ }
2284
+ const durationMs2 = Date.now() - startedAt;
2285
+ recordAuditAndInspector({
2286
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2287
+ method,
2288
+ path: forwardPath,
2289
+ upstream: baseUrl,
2290
+ sessionId,
2291
+ status: upstreamRes.status,
2292
+ streamed: true,
2293
+ durationMs: durationMs2,
2294
+ redactions: stats.redactions,
2295
+ counts: stats.counts,
2296
+ redactedPreview
2297
+ });
954
2298
  log(
955
- `[maskera-proxy] ${method} ${forwardPath} ${upstreamRes.status} sse redacted=${stats.redactions} ${Date.now() - startedAt}ms`
2299
+ `[maskera-proxy] ${method} ${forwardPath} ${upstreamRes.status} sse redacted=${stats.redactions} ${durationMs2}ms`
956
2300
  );
957
2301
  return;
958
2302
  }
959
- const resBuf = Buffer.from(await upstreamRes.arrayBuffer());
2303
+ let resBuf;
2304
+ try {
2305
+ resBuf = Buffer.from(await upstreamRes.arrayBuffer());
2306
+ } finally {
2307
+ res.off("close", onClientClose);
2308
+ }
960
2309
  if (hasMap && resContentType.includes("application/json")) {
961
2310
  try {
962
2311
  const parsed = JSON.parse(resBuf.toString("utf8"));
963
- const restored = restoreLlmResponseBody(parsed, sessionMap);
2312
+ const restored = restoreLlmResponseBody(parsed, sessionMap, { mutate: true });
964
2313
  const restoredBuf = Buffer.from(JSON.stringify(restored), "utf8");
965
2314
  res.writeHead(upstreamRes.status, outHeaders);
966
2315
  res.end(restoredBuf);
2316
+ const durationMs2 = Date.now() - startedAt;
2317
+ recordAuditAndInspector({
2318
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2319
+ method,
2320
+ path: forwardPath,
2321
+ upstream: baseUrl,
2322
+ sessionId,
2323
+ status: upstreamRes.status,
2324
+ streamed: false,
2325
+ durationMs: durationMs2,
2326
+ redactions: stats.redactions,
2327
+ counts: stats.counts,
2328
+ redactedPreview
2329
+ });
967
2330
  log(
968
- `[maskera-proxy] ${method} ${forwardPath} ${upstreamRes.status} json redacted=${stats.redactions} ${Date.now() - startedAt}ms`
2331
+ `[maskera-proxy] ${method} ${forwardPath} ${upstreamRes.status} json redacted=${stats.redactions} ${durationMs2}ms`
969
2332
  );
970
2333
  return;
971
2334
  } catch {
@@ -973,22 +2336,55 @@ async function startMaskeraProxy(options = {}) {
973
2336
  }
974
2337
  res.writeHead(upstreamRes.status, outHeaders);
975
2338
  res.end(resBuf);
2339
+ const durationMs = Date.now() - startedAt;
2340
+ recordAuditAndInspector({
2341
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2342
+ method,
2343
+ path: forwardPath,
2344
+ upstream: baseUrl,
2345
+ sessionId,
2346
+ status: upstreamRes.status,
2347
+ streamed: isSse,
2348
+ durationMs,
2349
+ redactions: stats.redactions,
2350
+ counts: stats.counts,
2351
+ redactedPreview
2352
+ });
976
2353
  log(
977
- `[maskera-proxy] ${method} ${forwardPath} ${upstreamRes.status} redacted=${stats.redactions} ${Date.now() - startedAt}ms`
2354
+ `[maskera-proxy] ${method} ${forwardPath} ${upstreamRes.status} redacted=${stats.redactions} ${durationMs}ms`
978
2355
  );
979
2356
  }
980
2357
  const server = createServer((req, res) => {
981
2358
  void handleRequest(req, res).catch((err) => {
2359
+ if (res.destroyed || req.aborted) return;
2360
+ const statusCode = err instanceof PayloadTooLargeError ? err.statusCode : 502;
982
2361
  const message = err instanceof Error ? err.message : String(err);
983
2362
  log(`[maskera-proxy] error: ${message}`);
984
2363
  if (!res.headersSent) {
985
- res.writeHead(502, { "content-type": "application/json; charset=utf-8" });
2364
+ res.writeHead(statusCode, { "content-type": "application/json; charset=utf-8" });
986
2365
  res.end(JSON.stringify({ error: { message: `maskera-proxy error: ${message}` } }));
987
- } else {
2366
+ } else if (!res.writableEnded) {
988
2367
  res.end();
989
2368
  }
990
2369
  });
991
2370
  });
2371
+ server.on("upgrade", (req, socket) => {
2372
+ const body = JSON.stringify({
2373
+ error: {
2374
+ message: "WebSocket transport is not supported by maskera-proxy; retry over HTTP SSE."
2375
+ }
2376
+ });
2377
+ socket.write(
2378
+ `HTTP/1.1 426 Upgrade Required\r
2379
+ Content-Type: application/json; charset=utf-8\r
2380
+ Connection: close\r
2381
+ Content-Length: ${Buffer.byteLength(body)}\r
2382
+ \r
2383
+ ${body}`
2384
+ );
2385
+ socket.end();
2386
+ log(`[maskera-proxy] UPGRADE ${req.url ?? "/"} 426 (HTTP SSE fallback)`);
2387
+ });
992
2388
  await new Promise((resolveListen, rejectListen) => {
993
2389
  server.once("error", rejectListen);
994
2390
  server.listen(requestedPort, host, () => {
@@ -998,21 +2394,31 @@ async function startMaskeraProxy(options = {}) {
998
2394
  });
999
2395
  const addr = server.address();
1000
2396
  const actualPort = typeof addr === "object" && addr ? addr.port : requestedPort;
2397
+ boundPort = actualPort;
2398
+ boundUrl = `http://${host}:${actualPort}`;
1001
2399
  return {
1002
2400
  host,
1003
2401
  port: actualPort,
1004
- url: `http://${host}:${actualPort}`,
2402
+ url: boundUrl,
2403
+ inspectorUrl: `${boundUrl}/_maskera`,
1005
2404
  server,
1006
2405
  vault,
1007
- close: () => new Promise((resolveClose, rejectClose) => {
1008
- server.close((err) => err ? rejectClose(err) : resolveClose());
1009
- })
2406
+ inspector,
2407
+ close: async () => {
2408
+ inspector.closeAll();
2409
+ await new Promise((resolveClose, rejectClose) => {
2410
+ server.close((err) => err ? rejectClose(err) : resolveClose());
2411
+ });
2412
+ await auditChain;
2413
+ }
1010
2414
  };
1011
2415
  }
1012
2416
  var MAX_FILE_BYTES = 2 * 1024 * 1024;
2417
+ var MAX_SYMLINK_HOPS = 40;
2418
+ var UTF8_DECODER = new TextDecoder("utf-8", { fatal: true });
1013
2419
  function isWithinRoot(root, target) {
1014
2420
  const rel = relative(root, target);
1015
- return rel === "" || !rel.startsWith("..") && !isAbsolute(rel);
2421
+ return rel === "" || rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
1016
2422
  }
1017
2423
  async function resolveExistingAncestor(target) {
1018
2424
  let current = resolve(target);
@@ -1020,7 +2426,7 @@ async function resolveExistingAncestor(target) {
1020
2426
  for (; ; ) {
1021
2427
  try {
1022
2428
  const real = await realpath(current);
1023
- return { ancestor: real, tail: segments.reverse().join("/") };
2429
+ return { ancestor: real, tail: segments.reverse().join(sep) };
1024
2430
  } catch {
1025
2431
  const parent = dirname(current);
1026
2432
  if (parent === current) {
@@ -1031,6 +2437,27 @@ async function resolveExistingAncestor(target) {
1031
2437
  }
1032
2438
  }
1033
2439
  }
2440
+ async function resolveCanonicalTarget(target) {
2441
+ let current = resolve(target);
2442
+ for (let hop = 0; hop < MAX_SYMLINK_HOPS; hop++) {
2443
+ const { ancestor, tail } = await resolveExistingAncestor(current);
2444
+ const candidate = tail ? resolve(ancestor, tail) : ancestor;
2445
+ try {
2446
+ const info = await lstat(candidate);
2447
+ if (!info.isSymbolicLink()) {
2448
+ return candidate;
2449
+ }
2450
+ const linkTarget = await readlink(candidate);
2451
+ current = resolve(dirname(candidate), linkTarget);
2452
+ } catch (err) {
2453
+ if (err.code === "ENOENT") {
2454
+ return candidate;
2455
+ }
2456
+ throw err;
2457
+ }
2458
+ }
2459
+ throw new Error(`Too many symlink hops while resolving "${target}".`);
2460
+ }
1034
2461
  function createFileGuard(roots = [process.cwd()]) {
1035
2462
  const rawRoots = roots.length > 0 ? roots : [process.cwd()];
1036
2463
  let canonicalRootsPromise = null;
@@ -1042,7 +2469,12 @@ function createFileGuard(roots = [process.cwd()]) {
1042
2469
  try {
1043
2470
  return await realpath(abs);
1044
2471
  } catch {
1045
- return abs;
2472
+ try {
2473
+ const { ancestor, tail } = await resolveExistingAncestor(abs);
2474
+ return tail ? resolve(ancestor, tail) : ancestor;
2475
+ } catch {
2476
+ return abs;
2477
+ }
1046
2478
  }
1047
2479
  })
1048
2480
  );
@@ -1087,17 +2519,24 @@ function createFileGuard(roots = [process.cwd()]) {
1087
2519
  if (buffer.includes(0)) {
1088
2520
  throw new Error(`"${filePath}" appears to be a binary file; only UTF-8 text is supported.`);
1089
2521
  }
2522
+ let content;
2523
+ try {
2524
+ content = UTF8_DECODER.decode(buffer);
2525
+ } catch {
2526
+ throw new Error(
2527
+ `"${filePath}" is not valid UTF-8 text; convert it to UTF-8 before redacting.`
2528
+ );
2529
+ }
1090
2530
  return {
1091
2531
  resolvedPath: real,
1092
- content: buffer.toString("utf8"),
2532
+ content,
1093
2533
  bytes: buffer.byteLength
1094
2534
  };
1095
2535
  },
1096
2536
  async writeText(filePath, content, options = {}) {
1097
2537
  const rootsList = await getCanonicalRoots();
1098
2538
  const candidate = resolveAgainstBase(filePath);
1099
- const { ancestor, tail } = await resolveExistingAncestor(candidate);
1100
- const targetReal = tail ? resolve(ancestor, tail) : ancestor;
2539
+ const targetReal = await resolveCanonicalTarget(candidate);
1101
2540
  if (!rootsList.some((root) => isWithinRoot(root, targetReal))) {
1102
2541
  throw new Error(
1103
2542
  `Access denied: "${filePath}" is outside allowed workspace roots (${rootsList.join(", ")}).`
@@ -1108,6 +2547,12 @@ function createFileGuard(roots = [process.cwd()]) {
1108
2547
  throw new Error(`Output exceeds max allowed size (${MAX_FILE_BYTES} bytes).`);
1109
2548
  }
1110
2549
  await mkdir(dirname(targetReal), { recursive: true });
2550
+ const parentReal = await realpath(dirname(targetReal));
2551
+ if (!rootsList.some((root) => isWithinRoot(root, parentReal))) {
2552
+ throw new Error(
2553
+ `Access denied: "${filePath}" is outside allowed workspace roots (${rootsList.join(", ")}).`
2554
+ );
2555
+ }
1111
2556
  await writeFile(targetReal, content, {
1112
2557
  encoding: "utf8",
1113
2558
  flag: options.overwrite ? "w" : "wx"
@@ -1124,12 +2569,19 @@ function createFileGuard(roots = [process.cwd()]) {
1124
2569
 
1125
2570
  // src/server.ts
1126
2571
  var SERVER_NAME = "maskera-mcp";
1127
- var SERVER_VERSION = "0.1.0";
1128
- var SUPPORTED_PROTOCOLS = ["2025-03-26", "2024-11-05"];
2572
+ var SERVER_VERSION = "0.2.0";
2573
+ var SUPPORTED_PROTOCOLS = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"];
1129
2574
  var TOOLS = [
1130
2575
  {
1131
2576
  name: "maskera_redact",
1132
2577
  description: "Redact Swedish PII (names, personnummer, addresses, emails, phones, IBAN, etc.) locally on-device using Maskera's 43 MB Swedish NER model and deterministic rules. Stores the restore map locally under session_id so placeholders stay consistent across calls and can be restored later without exposing raw PII to the LLM.",
2578
+ annotations: {
2579
+ title: "Redact Swedish PII locally",
2580
+ readOnlyHint: true,
2581
+ destructiveHint: false,
2582
+ idempotentHint: false,
2583
+ openWorldHint: false
2584
+ },
1133
2585
  inputSchema: {
1134
2586
  type: "object",
1135
2587
  properties: {
@@ -1164,6 +2616,13 @@ var TOOLS = [
1164
2616
  {
1165
2617
  name: "maskera_restore",
1166
2618
  description: "Restore Maskera placeholders (e.g. [NAMN_1], [PERSONNUMMER_1]) in text using a locally stored session_id or an explicit map.",
2619
+ annotations: {
2620
+ title: "Restore Maskera placeholders",
2621
+ readOnlyHint: true,
2622
+ destructiveHint: false,
2623
+ idempotentHint: true,
2624
+ openWorldHint: false
2625
+ },
1167
2626
  inputSchema: {
1168
2627
  type: "object",
1169
2628
  properties: {
@@ -1184,6 +2643,13 @@ var TOOLS = [
1184
2643
  {
1185
2644
  name: "maskera_read_file",
1186
2645
  description: "Read a local UTF-8 text file and redact Swedish PII BEFORE returning its contents to the model. Keeps raw PII strictly in local memory under session_id so the cloud LLM never sees real names or personal IDs.",
2646
+ annotations: {
2647
+ title: "Read local file with PII redaction",
2648
+ readOnlyHint: true,
2649
+ destructiveHint: false,
2650
+ idempotentHint: false,
2651
+ openWorldHint: false
2652
+ },
1187
2653
  inputSchema: {
1188
2654
  type: "object",
1189
2655
  properties: {
@@ -1217,6 +2683,13 @@ var TOOLS = [
1217
2683
  {
1218
2684
  name: "maskera_write_file",
1219
2685
  description: "Restore Maskera placeholders from a local session_id and write the restored text directly to a local file without echoing raw PII back into the LLM context.",
2686
+ annotations: {
2687
+ title: "Restore placeholders and write local file",
2688
+ readOnlyHint: false,
2689
+ destructiveHint: false,
2690
+ idempotentHint: false,
2691
+ openWorldHint: false
2692
+ },
1220
2693
  inputSchema: {
1221
2694
  type: "object",
1222
2695
  properties: {
@@ -1243,11 +2716,25 @@ var TOOLS = [
1243
2716
  {
1244
2717
  name: "maskera_list_sessions",
1245
2718
  description: "List active local redaction sessions and entity counts (never returns raw PII values).",
2719
+ annotations: {
2720
+ title: "List active Maskera sessions",
2721
+ readOnlyHint: true,
2722
+ destructiveHint: false,
2723
+ idempotentHint: true,
2724
+ openWorldHint: false
2725
+ },
1246
2726
  inputSchema: { type: "object", properties: {} }
1247
2727
  },
1248
2728
  {
1249
2729
  name: "maskera_clear_session",
1250
2730
  description: "Erase a session's local in-memory restore map immediately.",
2731
+ annotations: {
2732
+ title: "Clear Maskera session vault",
2733
+ readOnlyHint: false,
2734
+ destructiveHint: true,
2735
+ idempotentHint: true,
2736
+ openWorldHint: false
2737
+ },
1251
2738
  inputSchema: {
1252
2739
  type: "object",
1253
2740
  properties: {
@@ -1259,6 +2746,13 @@ var TOOLS = [
1259
2746
  {
1260
2747
  name: "maskera_status",
1261
2748
  description: "Report local Maskera MCP server status: model pin, readiness, active sessions, and allowed file roots.",
2749
+ annotations: {
2750
+ title: "Maskera MCP server status",
2751
+ readOnlyHint: true,
2752
+ destructiveHint: false,
2753
+ idempotentHint: true,
2754
+ openWorldHint: false
2755
+ },
1262
2756
  inputSchema: { type: "object", properties: {} }
1263
2757
  }
1264
2758
  ];
@@ -1298,6 +2792,13 @@ function createMaskeraMcpServer(options = {}) {
1298
2792
  const engine = options.engine ?? createMaskeraEngine();
1299
2793
  const vault = options.vault ?? new SessionVault();
1300
2794
  const files = options.files ?? createFileGuard(options.allowedRoots);
2795
+ const defaultProfile = options.defaultProfile;
2796
+ const defaultCustomTerms = options.defaultCustomTerms;
2797
+ function mergeCustomTerms(callTerms) {
2798
+ if (!defaultCustomTerms?.length) return callTerms;
2799
+ if (!callTerms?.length) return defaultCustomTerms;
2800
+ return [...defaultCustomTerms, ...callTerms];
2801
+ }
1301
2802
  async function callTool(name, rawArgs) {
1302
2803
  const args = asObject(rawArgs);
1303
2804
  try {
@@ -1305,8 +2806,8 @@ function createMaskeraMcpServer(options = {}) {
1305
2806
  if (typeof args.text !== "string") return toolError("Missing required string: text");
1306
2807
  const { result, modeUsed } = await engine.redact(args.text, {
1307
2808
  mode: asMode(args.mode),
1308
- profile: asProfile(args.profile),
1309
- customTerms: asStringArray(args.custom_terms)
2809
+ profile: asProfile(args.profile) ?? defaultProfile,
2810
+ customTerms: mergeCustomTerms(asStringArray(args.custom_terms))
1310
2811
  });
1311
2812
  const applied = vault.apply(
1312
2813
  args.text,
@@ -1345,8 +2846,8 @@ function createMaskeraMcpServer(options = {}) {
1345
2846
  const file = await files.readText(args.path);
1346
2847
  const { result, modeUsed } = await engine.redact(file.content, {
1347
2848
  mode: asMode(args.mode),
1348
- profile: asProfile(args.profile),
1349
- customTerms: asStringArray(args.custom_terms)
2849
+ profile: asProfile(args.profile) ?? defaultProfile,
2850
+ customTerms: mergeCustomTerms(asStringArray(args.custom_terms))
1350
2851
  });
1351
2852
  const applied = vault.apply(
1352
2853
  file.content,
@@ -1366,11 +2867,12 @@ function createMaskeraMcpServer(options = {}) {
1366
2867
  if (name === "maskera_write_file") {
1367
2868
  if (typeof args.path !== "string") return toolError("Missing required string: path");
1368
2869
  if (typeof args.text !== "string") return toolError("Missing required string: text");
1369
- if (typeof args.session_id !== "string") {
1370
- return toolError("Missing required string: session_id");
2870
+ if (typeof args.session_id !== "string" || !args.session_id.trim()) {
2871
+ return toolError("Missing required non-empty string: session_id");
1371
2872
  }
2873
+ const normalizedSessionId = args.session_id.trim();
1372
2874
  const { restored, knownPlaceholders } = vault.restore(args.text, {
1373
- sessionId: args.session_id
2875
+ sessionId: normalizedSessionId
1374
2876
  });
1375
2877
  const written = await files.writeText(args.path, restored, {
1376
2878
  overwrite: args.overwrite === true
@@ -1378,7 +2880,7 @@ function createMaskeraMcpServer(options = {}) {
1378
2880
  return toolOk({
1379
2881
  path: written.resolvedPath,
1380
2882
  bytes: written.bytes,
1381
- session_id: args.session_id,
2883
+ session_id: normalizedSessionId,
1382
2884
  known_placeholders: knownPlaceholders
1383
2885
  });
1384
2886
  }
@@ -1386,12 +2888,13 @@ function createMaskeraMcpServer(options = {}) {
1386
2888
  return toolOk({ sessions: vault.list() });
1387
2889
  }
1388
2890
  if (name === "maskera_clear_session") {
1389
- if (typeof args.session_id !== "string") {
1390
- return toolError("Missing required string: session_id");
2891
+ if (typeof args.session_id !== "string" || !args.session_id.trim()) {
2892
+ return toolError("Missing required non-empty string: session_id");
1391
2893
  }
2894
+ const normalizedSessionId = args.session_id.trim();
1392
2895
  return toolOk({
1393
- session_id: args.session_id,
1394
- cleared: vault.clear(args.session_id)
2896
+ session_id: normalizedSessionId,
2897
+ cleared: vault.clear(normalizedSessionId)
1395
2898
  });
1396
2899
  }
1397
2900
  if (name === "maskera_status") {
@@ -1419,15 +2922,16 @@ function createMaskeraMcpServer(options = {}) {
1419
2922
  };
1420
2923
  }
1421
2924
  const req = raw;
1422
- const id = typeof req.id === "string" || typeof req.id === "number" || req.id === null ? req.id : void 0;
1423
- if (req.jsonrpc !== "2.0" || typeof req.method !== "string") {
1424
- if (id === void 0) return null;
2925
+ const hasIdProp = Object.prototype.hasOwnProperty.call(req, "id");
2926
+ const validId = typeof req.id === "string" || typeof req.id === "number" || req.id === null ? req.id : void 0;
2927
+ if (req.jsonrpc !== "2.0" || typeof req.method !== "string" || hasIdProp && validId === void 0) {
1425
2928
  return {
1426
2929
  jsonrpc: "2.0",
1427
- id,
2930
+ id: validId ?? null,
1428
2931
  error: { code: -32600, message: "Invalid Request" }
1429
2932
  };
1430
2933
  }
2934
+ const id = validId;
1431
2935
  if (id === void 0) {
1432
2936
  return null;
1433
2937
  }
@@ -1493,6 +2997,7 @@ function parseArgs(argv) {
1493
2997
  let anthropicUpstream = process.env.MASKERA_ANTHROPIC_UPSTREAM || void 0;
1494
2998
  let openaiUpstream = process.env.MASKERA_OPENAI_UPSTREAM || void 0;
1495
2999
  let restoreResponses = true;
3000
+ let auditLogPath = process.env.MASKERA_AUDIT_LOG || void 0;
1496
3001
  let redact2 = false;
1497
3002
  let file;
1498
3003
  const envRoots = process.env.MASKERA_MCP_ROOTS;
@@ -1502,50 +3007,88 @@ function parseArgs(argv) {
1502
3007
  if (trimmed) roots.push(trimmed);
1503
3008
  }
1504
3009
  }
3010
+ const takeValue = (flag, arg, index, allowLeadingDash = false) => {
3011
+ const eq = arg.indexOf("=");
3012
+ if (eq >= 0) {
3013
+ const value = arg.slice(eq + 1);
3014
+ if (!value.trim()) throw new Error(`Flag ${flag} requires a non-empty value.`);
3015
+ return { value, nextIndex: index };
3016
+ }
3017
+ const next = argv[index + 1];
3018
+ if (next === void 0 || !next.trim() || !allowLeadingDash && next.startsWith("-")) {
3019
+ throw new Error(`Flag ${flag} requires a non-empty value.`);
3020
+ }
3021
+ return { value: next, nextIndex: index + 1 };
3022
+ };
1505
3023
  for (let i = startIndex; i < argv.length; i++) {
1506
- const arg = argv[i];
1507
- if (arg === "--help" || arg === "-h") {
3024
+ const arg = argv[i] ?? "";
3025
+ const eq = arg.indexOf("=");
3026
+ const flag = eq >= 0 ? arg.slice(0, eq) : arg;
3027
+ if (flag === "--help" || flag === "-h") {
1508
3028
  help = true;
1509
- } else if (arg === "--version" || arg === "-v") {
3029
+ } else if (flag === "--version" || flag === "-v") {
1510
3030
  version = true;
1511
- } else if (arg === "--rules-only") {
3031
+ } else if (flag === "--rules-only") {
1512
3032
  defaultMode = "rules";
1513
- } else if (arg === "--no-restore") {
3033
+ } else if (flag === "--no-restore") {
1514
3034
  restoreResponses = false;
1515
- } else if (arg === "--redact") {
3035
+ } else if (flag === "--redact") {
1516
3036
  redact2 = true;
1517
- } else if (arg === "--root" && argv[i + 1]) {
1518
- roots.push(argv[++i]);
1519
- } else if (arg?.startsWith("--root=")) {
1520
- const value = arg.slice("--root=".length).trim();
1521
- if (value) roots.push(value);
1522
- } else if (arg === "--host" && argv[i + 1]) {
1523
- host = argv[++i];
1524
- } else if (arg?.startsWith("--host=")) {
1525
- host = arg.slice("--host=".length).trim();
1526
- } else if (arg === "--port" && argv[i + 1]) {
1527
- port = Number(argv[++i]);
1528
- } else if (arg?.startsWith("--port=")) {
1529
- port = Number(arg.slice("--port=".length).trim());
1530
- } else if (arg === "--upstream" && argv[i + 1]) {
1531
- upstream = argv[++i];
1532
- } else if (arg?.startsWith("--upstream=")) {
1533
- upstream = arg.slice("--upstream=".length).trim();
1534
- } else if (arg === "--anthropic-upstream" && argv[i + 1]) {
1535
- anthropicUpstream = argv[++i];
1536
- } else if (arg === "--openai-upstream" && argv[i + 1]) {
1537
- openaiUpstream = argv[++i];
1538
- } else if (arg === "--profile" && argv[i + 1]) {
1539
- const val = argv[++i];
1540
- if (val === "general" || val === "clinical") profile = val;
1541
- } else if (arg === "--custom-term" && argv[i + 1]) {
1542
- customTerms.push(argv[++i]);
1543
- } else if (arg === "--file" && argv[i + 1]) {
1544
- file = argv[++i];
3037
+ } else if (flag === "--root") {
3038
+ const { value, nextIndex } = takeValue(flag, arg, i);
3039
+ i = nextIndex;
3040
+ if (value.trim()) roots.push(value.trim());
3041
+ } else if (flag === "--host") {
3042
+ const { value, nextIndex } = takeValue(flag, arg, i);
3043
+ i = nextIndex;
3044
+ host = value.trim();
3045
+ } else if (flag === "--port") {
3046
+ const { value, nextIndex } = takeValue(flag, arg, i);
3047
+ i = nextIndex;
3048
+ const parsedPort = Number(value.trim());
3049
+ if (!Number.isInteger(parsedPort) || parsedPort < 0 || parsedPort > 65535) {
3050
+ throw new Error(`Invalid --port "${value}": expected integer 0..65535.`);
3051
+ }
3052
+ port = parsedPort;
3053
+ } else if (flag === "--upstream") {
3054
+ const { value, nextIndex } = takeValue(flag, arg, i);
3055
+ i = nextIndex;
3056
+ upstream = value.trim();
3057
+ } else if (flag === "--anthropic-upstream") {
3058
+ const { value, nextIndex } = takeValue(flag, arg, i);
3059
+ i = nextIndex;
3060
+ anthropicUpstream = value.trim();
3061
+ } else if (flag === "--openai-upstream") {
3062
+ const { value, nextIndex } = takeValue(flag, arg, i);
3063
+ i = nextIndex;
3064
+ openaiUpstream = value.trim();
3065
+ } else if (flag === "--profile") {
3066
+ const { value, nextIndex } = takeValue(flag, arg, i);
3067
+ i = nextIndex;
3068
+ if (value !== "general" && value !== "clinical") {
3069
+ throw new Error(`Invalid --profile "${value}": expected "general" or "clinical".`);
3070
+ }
3071
+ profile = value;
3072
+ } else if (flag === "--custom-term") {
3073
+ const { value, nextIndex } = takeValue(flag, arg, i, true);
3074
+ i = nextIndex;
3075
+ customTerms.push(value);
3076
+ } else if (flag === "--audit-log") {
3077
+ const { value, nextIndex } = takeValue(flag, arg, i);
3078
+ i = nextIndex;
3079
+ auditLogPath = value.trim() || void 0;
3080
+ } else if (flag === "--file") {
3081
+ const { value, nextIndex } = takeValue(flag, arg, i, true);
3082
+ i = nextIndex;
3083
+ file = value;
3084
+ } else {
3085
+ throw new Error(`Unknown option "${arg}". Run with --help for usage.`);
1545
3086
  }
1546
3087
  }
1547
3088
  if (roots.length === 0) roots.push(process.cwd());
1548
- if (!Number.isFinite(port) || port < 0 || port > 65535) port = 8787;
3089
+ if (!Number.isInteger(port) || port < 0 || port > 65535) {
3090
+ throw new Error(`Invalid port "${String(port)}": expected integer 0..65535.`);
3091
+ }
1549
3092
  return {
1550
3093
  command,
1551
3094
  roots,
@@ -1560,6 +3103,7 @@ function parseArgs(argv) {
1560
3103
  anthropicUpstream,
1561
3104
  openaiUpstream,
1562
3105
  restoreResponses,
3106
+ auditLogPath,
1563
3107
  redact: redact2,
1564
3108
  file
1565
3109
  };
@@ -1572,7 +3116,7 @@ function printHelp() {
1572
3116
  "",
1573
3117
  "Usage:",
1574
3118
  " maskera-mcp [mcp] [--root <dir>] [--rules-only]",
1575
- " maskera-mcp proxy [--port 8787] [--host 127.0.0.1] [--upstream <url>] [--rules-only] [--no-restore]",
3119
+ " maskera-mcp proxy [--port 8787] [--host 127.0.0.1] [--upstream <url>] [--audit-log <file.jsonl>] [--rules-only] [--no-restore]",
1576
3120
  " maskera-mcp guard [--redact] [--file <path>] [--rules-only]",
1577
3121
  "",
1578
3122
  "Subcommands:",
@@ -1592,6 +3136,7 @@ function printHelp() {
1592
3136
  " MASKERA_MCP_MODE 'auto' (default) or 'rules'",
1593
3137
  " MASKERA_MODEL_PATH Local ONNX model directory base path",
1594
3138
  " MASKERA_MODEL_ID Model id (defaults to joelhagvall/maskera-sv-ner)",
3139
+ " MASKERA_DTYPE ONNX dtype: 'q8' (default on Node, ~2.5x faster), 'q4', or 'fp32'",
1595
3140
  " MASKERA_CACHE_DIR Transformers.js cache directory",
1596
3141
  " MASKERA_ALLOW_REMOTE_MODELS '0' to disable Hugging Face Hub downloads",
1597
3142
  ""
@@ -1604,6 +3149,7 @@ function buildEngine(args) {
1604
3149
  nerOptions: {
1605
3150
  localModelPath: process.env.MASKERA_MODEL_PATH || void 0,
1606
3151
  model: process.env.MASKERA_MODEL_ID || void 0,
3152
+ dtype: process.env.MASKERA_DTYPE || void 0,
1607
3153
  cacheDir: process.env.MASKERA_CACHE_DIR || void 0,
1608
3154
  allowRemoteModels: process.env.MASKERA_ALLOW_REMOTE_MODELS === "0" ? false : process.env.MASKERA_ALLOW_REMOTE_MODELS === "1" ? true : void 0
1609
3155
  }
@@ -1647,15 +3193,18 @@ async function main() {
1647
3193
  profile: args.profile,
1648
3194
  customTerms: args.customTerms.length > 0 ? args.customTerms : void 0,
1649
3195
  restoreResponses: args.restoreResponses,
3196
+ auditLogPath: args.auditLogPath,
1650
3197
  onLog: (line) => process.stderr.write(`${line}
1651
3198
  `)
1652
3199
  });
3200
+ engine.warmup();
1653
3201
  process.stderr.write(
1654
3202
  [
1655
3203
  `[maskera-proxy] listening on ${running.url} (mode=${args.defaultMode}, restore=${args.restoreResponses})`,
3204
+ ` Local live inspector: ${running.inspectorUrl}`,
1656
3205
  ` Claude Code / Anthropic: ANTHROPIC_BASE_URL=${running.url}`,
1657
3206
  ` Codex / Cursor / OpenAI: OPENAI_BASE_URL=${running.url}/v1`,
1658
- ` Status (counts only): ${running.url}/_maskera/status`,
3207
+ ...args.auditLogPath ? [` Local audit log (JSONL): ${args.auditLogPath}`] : [],
1659
3208
  ""
1660
3209
  ].join("\n")
1661
3210
  );
@@ -1667,11 +3216,25 @@ async function main() {
1667
3216
  return;
1668
3217
  }
1669
3218
  if (args.command === "guard") {
1670
- const raw = args.file ? await readFile(args.file, "utf8") : await readStdinAll();
3219
+ let raw;
3220
+ if (args.file) {
3221
+ const buf = await readFile(args.file);
3222
+ if (buf.includes(0)) {
3223
+ throw new Error(`"${args.file}" appears to be a binary file; only UTF-8 text is supported.`);
3224
+ }
3225
+ try {
3226
+ raw = new TextDecoder("utf-8", { fatal: true }).decode(buf);
3227
+ } catch {
3228
+ throw new Error(`"${args.file}" is not valid UTF-8 text; convert it to UTF-8 first.`);
3229
+ }
3230
+ } else {
3231
+ raw = await readStdinAll();
3232
+ }
1671
3233
  const result = await runGuard(raw, engine, {
1672
3234
  mode: args.defaultMode,
1673
3235
  profile: args.profile,
1674
- customTerms: args.customTerms.length > 0 ? args.customTerms : void 0
3236
+ customTerms: args.customTerms.length > 0 ? args.customTerms : void 0,
3237
+ preserveJsonStructure: args.redact
1675
3238
  });
1676
3239
  if (args.redact) {
1677
3240
  process.stdout.write(result.redacted);
@@ -1687,7 +3250,13 @@ async function main() {
1687
3250
  }
1688
3251
  return;
1689
3252
  }
1690
- const server = createMaskeraMcpServer({ engine, allowedRoots: args.roots });
3253
+ const server = createMaskeraMcpServer({
3254
+ engine,
3255
+ allowedRoots: args.roots,
3256
+ defaultProfile: args.profile,
3257
+ defaultCustomTerms: args.customTerms.length > 0 ? args.customTerms : void 0
3258
+ });
3259
+ engine.warmup();
1691
3260
  let chain = Promise.resolve();
1692
3261
  const rl = createInterface({ input: process.stdin, crlfDelay: Number.POSITIVE_INFINITY });
1693
3262
  rl.on("line", (line) => {
@@ -1715,18 +3284,29 @@ async function main() {
1715
3284
  `);
1716
3285
  }
1717
3286
  } catch (err) {
1718
- process.stderr.write(
1719
- `[maskera-mcp] internal error: ${err instanceof Error ? err.message : String(err)}
3287
+ const message = err instanceof Error ? err.message : String(err);
3288
+ process.stderr.write(`[maskera-mcp] internal error: ${message}
3289
+ `);
3290
+ const maybeId = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed.id : void 0;
3291
+ if (typeof maybeId === "string" || typeof maybeId === "number" || maybeId === null) {
3292
+ process.stdout.write(
3293
+ `${JSON.stringify({
3294
+ jsonrpc: "2.0",
3295
+ id: maybeId,
3296
+ error: { code: -32603, message: "Internal error" }
3297
+ })}
1720
3298
  `
1721
- );
3299
+ );
3300
+ }
1722
3301
  }
1723
3302
  });
1724
3303
  });
1725
3304
  }
3305
+ var isGuardCommand = process.argv[2] === "guard";
1726
3306
  void main().catch((err) => {
1727
3307
  process.stderr.write(`[maskera-mcp] fatal: ${err instanceof Error ? err.message : String(err)}
1728
3308
  `);
1729
- process.exit(1);
3309
+ process.exit(isGuardCommand ? 2 : 1);
1730
3310
  });
1731
3311
  //# sourceMappingURL=cli.js.map
1732
3312
  //# sourceMappingURL=cli.js.map