@maskera/mcp 0.4.7 → 0.5.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/index.js CHANGED
@@ -1,8 +1,10 @@
1
1
  import { randomUUID, createHash } from 'crypto';
2
- import { constants } from 'fs';
3
- import { readFile, mkdir, realpath, writeFile, stat, access, appendFile, unlink, readdir, lstat, readlink } from 'fs/promises';
4
- import { dirname, resolve, join, isAbsolute, relative, sep, delimiter, extname, posix } from 'path';
2
+ import { existsSync, constants } from 'fs';
3
+ import { readFile, stat, access, mkdir, writeFile, appendFile, unlink, realpath, readdir, lstat, readlink } from 'fs/promises';
4
+ import { join, resolve, dirname, relative, sep, delimiter, isAbsolute, extname, posix } from 'path';
5
5
  import { createRequire } from 'module';
6
+ import { unzipSync, zipSync } from 'fflate';
7
+ import { PDFDocument, PDFName } from 'pdf-lib';
6
8
  import { MASKERA_SV_NER_MODEL, MASKERA_SV_NER_REVISION, redactFromDetections, hybridDefaultDetectors, canonicalize, runDetectors, clinicalPrecisionFilter, redact, redactWithNer, restore, createNerRecognizer } from 'maskera';
7
9
  import { spawn, spawnSync } from 'child_process';
8
10
  import { homedir } from 'os';
@@ -17,6 +19,22 @@ function normalizeOwner(owner) {
17
19
  const trimmed = owner?.trim();
18
20
  return trimmed || DEFAULT_OWNER;
19
21
  }
22
+ function toSummary(record) {
23
+ const { state } = record;
24
+ const decidedAt = state.status === "pending" ? null : state.decidedAt;
25
+ const base = {
26
+ id: record.id,
27
+ tool: record.tool,
28
+ reason: record.reason,
29
+ sessionId: record.sessionId,
30
+ placeholderCount: record.placeholderCount,
31
+ status: state.status,
32
+ createdAt: record.createdAt,
33
+ expiresAt: record.expiresAt,
34
+ decidedAt
35
+ };
36
+ return state.status === "failed" ? { ...base, error: state.error } : base;
37
+ }
20
38
  var ApprovalBroker = class {
21
39
  constructor(ttlMs = DEFAULT_TTL_MS) {
22
40
  this.records = /* @__PURE__ */ new Map();
@@ -26,9 +44,9 @@ var ApprovalBroker = class {
26
44
  expireStale(now = Date.now()) {
27
45
  let changed = false;
28
46
  for (const record of this.records.values()) {
29
- if (record.summary.status === "pending" && now >= record.expiresAtMs) {
30
- record.summary.status = "expired";
31
- record.execute = null;
47
+ if ((record.state.status === "pending" || record.state.status === "approved") && now >= record.state.expiresAtMs) {
48
+ const decidedAt = record.state.status === "approved" ? record.state.decidedAt : null;
49
+ record.state = { status: "expired", decidedAt };
32
50
  changed = true;
33
51
  }
34
52
  }
@@ -57,81 +75,1812 @@ var ApprovalBroker = class {
57
75
  }
58
76
  const now = Date.now();
59
77
  const id = `apr_${randomUUID().slice(0, 12)}`;
60
- const summary = {
78
+ const expiresAtMs = now + this.ttlMs;
79
+ const record = {
61
80
  id,
81
+ owner: normalizeOwner(input.owner),
62
82
  tool: input.tool,
63
83
  reason: input.reason,
64
84
  sessionId: input.sessionId ?? null,
65
85
  placeholderCount: input.placeholderCount,
66
- status: "pending",
67
86
  createdAt: new Date(now).toISOString(),
68
- expiresAt: new Date(now + this.ttlMs).toISOString(),
69
- decidedAt: null
87
+ expiresAt: new Date(expiresAtMs).toISOString(),
88
+ state: {
89
+ status: "pending",
90
+ expiresAtMs,
91
+ execute: input.execute
92
+ }
70
93
  };
71
- this.records.set(id, {
72
- owner: normalizeOwner(input.owner),
73
- summary,
74
- expiresAtMs: now + this.ttlMs,
75
- execute: input.execute
76
- });
94
+ this.records.set(id, record);
95
+ this.notify();
96
+ return toSummary(record);
97
+ }
98
+ list() {
99
+ this.expireStale();
100
+ return [...this.records.values()].map(toSummary).reverse();
101
+ }
102
+ decide(id, decision) {
103
+ this.expireStale();
104
+ const record = this.records.get(id.trim());
105
+ if (!record) return null;
106
+ if (record.state.status !== "pending") return toSummary(record);
107
+ const decidedAt = (/* @__PURE__ */ new Date()).toISOString();
108
+ if (decision === "approve") {
109
+ record.state = {
110
+ status: "approved",
111
+ expiresAtMs: record.state.expiresAtMs,
112
+ decidedAt,
113
+ execute: record.state.execute
114
+ };
115
+ } else {
116
+ record.state = { status: "declined", decidedAt };
117
+ }
118
+ this.notify();
119
+ return toSummary(record);
120
+ }
121
+ async resume(id, owner) {
122
+ this.expireStale();
123
+ const key = id.trim();
124
+ const record = this.records.get(key);
125
+ if (!record) return { status: "not_found" };
126
+ if (owner !== void 0 && record.owner !== normalizeOwner(owner)) {
127
+ return { status: "not_found" };
128
+ }
129
+ switch (record.state.status) {
130
+ case "pending":
131
+ case "executing":
132
+ case "declined":
133
+ case "expired":
134
+ return { status: record.state.status, summary: toSummary(record) };
135
+ case "completed":
136
+ return { status: "already_completed", summary: toSummary(record) };
137
+ case "failed":
138
+ return { status: "failed", error: record.state.error, summary: toSummary(record) };
139
+ case "approved": {
140
+ const { decidedAt, execute } = record.state;
141
+ const inFlight = (async () => {
142
+ try {
143
+ const result = await execute();
144
+ record.state = { status: "completed", decidedAt };
145
+ if (this.records.get(key) === record) this.notify();
146
+ return { status: "completed", result, summary: toSummary(record) };
147
+ } catch (err) {
148
+ const error = err instanceof Error ? err.message : String(err);
149
+ record.state = { status: "failed", decidedAt, error };
150
+ if (this.records.get(key) === record) this.notify();
151
+ return { status: "failed", error, summary: toSummary(record) };
152
+ }
153
+ })();
154
+ record.state = { status: "executing", decidedAt, inFlight };
155
+ this.notify();
156
+ return await inFlight;
157
+ }
158
+ }
159
+ }
160
+ clearOwner(owner) {
161
+ const resolvedOwner = normalizeOwner(owner);
162
+ let changed = false;
163
+ for (const [id, record] of this.records.entries()) {
164
+ if (record.owner === resolvedOwner) {
165
+ this.records.delete(id);
166
+ changed = true;
167
+ }
168
+ }
169
+ if (changed) this.notify();
170
+ }
171
+ clearAll() {
172
+ this.records.clear();
77
173
  this.notify();
78
- return { ...summary };
79
174
  }
80
- list() {
81
- this.expireStale();
82
- return [...this.records.values()].map((r) => ({ ...r.summary })).reverse();
175
+ };
176
+ var MAX_DEFAULT_FILE_BYTES = 25 * 1024 * 1024;
177
+ var UTF8_DECODER = new TextDecoder("utf-8", { fatal: true });
178
+ var TEXT_MIME_BY_EXT = {
179
+ ".txt": "text/plain",
180
+ ".md": "text/markdown",
181
+ ".markdown": "text/markdown",
182
+ ".csv": "text/csv",
183
+ ".tsv": "text/tab-separated-values",
184
+ ".json": "application/json",
185
+ ".jsonl": "application/x-ndjson",
186
+ ".xml": "application/xml",
187
+ ".yaml": "application/yaml",
188
+ ".yml": "application/yaml",
189
+ ".html": "text/html",
190
+ ".htm": "text/html",
191
+ ".log": "text/plain",
192
+ ".sql": "text/plain",
193
+ ".ts": "text/plain",
194
+ ".tsx": "text/plain",
195
+ ".js": "text/plain",
196
+ ".mjs": "text/plain",
197
+ ".py": "text/plain"
198
+ };
199
+ function extractExtension(fileName) {
200
+ if (!fileName) return "";
201
+ const base = fileName.split(/[\\/]/).pop() ?? "";
202
+ const dot = base.lastIndexOf(".");
203
+ if (dot <= 0) return "";
204
+ return base.slice(dot).toLowerCase();
205
+ }
206
+ function hasPdfHeader(bytes) {
207
+ const limit = Math.min(bytes.byteLength, 1024);
208
+ for (let i = 0; i + 4 < limit; i++) {
209
+ if (bytes[i] === 37 && // %
210
+ bytes[i + 1] === 80 && // P
211
+ bytes[i + 2] === 68 && // D
212
+ bytes[i + 3] === 70 && // F
213
+ bytes[i + 4] === 45) {
214
+ return true;
215
+ }
216
+ }
217
+ return false;
218
+ }
219
+ function hasZipHeader(bytes) {
220
+ if (bytes.byteLength < 4) return false;
221
+ return bytes[0] === 80 && bytes[1] === 75 && (bytes[2] === 3 && bytes[3] === 4 || bytes[2] === 5 && bytes[3] === 6 || bytes[2] === 7 && bytes[3] === 8);
222
+ }
223
+ function detectOfficeZipFormat(bytes) {
224
+ try {
225
+ let isDocx = false;
226
+ let isXlsx = false;
227
+ let entriesSeen = 0;
228
+ unzipSync(bytes, {
229
+ filter(file) {
230
+ entriesSeen += 1;
231
+ if (entriesSeen > 2e3) return false;
232
+ const name = file.name.toLowerCase();
233
+ if (name === "word/document.xml") isDocx = true;
234
+ if (name === "xl/workbook.xml") isXlsx = true;
235
+ return false;
236
+ }
237
+ });
238
+ if (isDocx) return "docx";
239
+ if (isXlsx) return "xlsx";
240
+ return null;
241
+ } catch {
242
+ return null;
243
+ }
244
+ }
245
+ function mimeTypeForFormat(format, fileName) {
246
+ const ext = extractExtension(fileName);
247
+ return TEXT_MIME_BY_EXT[ext] ?? "text/plain";
248
+ }
249
+ function detectFileFormat(bytes, fileName, mimeType) {
250
+ const ext = extractExtension(fileName);
251
+ const normalizedMime = mimeType?.split(";")[0]?.trim().toLowerCase() ?? "";
252
+ if (hasPdfHeader(bytes)) {
253
+ return { format: "pdf", mimeType: "application/pdf", extension: ".pdf" };
254
+ }
255
+ if (hasZipHeader(bytes)) {
256
+ const office = detectOfficeZipFormat(bytes);
257
+ if (office === "docx") {
258
+ return {
259
+ format: "docx",
260
+ mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
261
+ extension: ".docx"
262
+ };
263
+ }
264
+ if (office === "xlsx") {
265
+ return {
266
+ format: "xlsx",
267
+ mimeType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
268
+ extension: ".xlsx"
269
+ };
270
+ }
271
+ return {
272
+ format: "binary",
273
+ mimeType: normalizedMime || "application/zip",
274
+ extension: ext || ".zip"
275
+ };
276
+ }
277
+ for (let i = 0; i < bytes.byteLength; i++) {
278
+ if (bytes[i] === 0) {
279
+ return {
280
+ format: "binary",
281
+ mimeType: normalizedMime || "application/octet-stream",
282
+ extension: ext
283
+ };
284
+ }
285
+ }
286
+ try {
287
+ UTF8_DECODER.decode(bytes);
288
+ return {
289
+ format: "text",
290
+ mimeType: normalizedMime && (normalizedMime.startsWith("text/") || normalizedMime.includes("json")) ? normalizedMime : mimeTypeForFormat("text", fileName),
291
+ extension: ext || ".txt"
292
+ };
293
+ } catch {
294
+ return {
295
+ format: "binary",
296
+ mimeType: normalizedMime || "application/octet-stream",
297
+ extension: ext
298
+ };
299
+ }
300
+ }
301
+ var MAX_ZIP_ENTRIES = 2e3;
302
+ var MAX_ZIP_UNCOMPRESSED_BYTES = 100 * 1024 * 1024;
303
+ var UTF8_DECODER2 = new TextDecoder("utf-8", { fatal: false });
304
+ var UTF8_ENCODER = new TextEncoder();
305
+ function decodeUtf8(bytes) {
306
+ return UTF8_DECODER2.decode(bytes);
307
+ }
308
+ function encodeUtf8(text) {
309
+ return UTF8_ENCODER.encode(text);
310
+ }
311
+ function unzipSafely(bytes) {
312
+ let entryCount = 0;
313
+ let totalUncompressed = 0;
314
+ const files = unzipSync(bytes, {
315
+ filter(file) {
316
+ entryCount += 1;
317
+ if (entryCount > MAX_ZIP_ENTRIES) {
318
+ throw new Error(`Archive exceeds max allowed entry count (${MAX_ZIP_ENTRIES}).`);
319
+ }
320
+ totalUncompressed += file.originalSize;
321
+ if (totalUncompressed > MAX_ZIP_UNCOMPRESSED_BYTES) {
322
+ throw new Error(
323
+ `Archive exceeds max allowed uncompressed size (${MAX_ZIP_UNCOMPRESSED_BYTES} bytes).`
324
+ );
325
+ }
326
+ return true;
327
+ }
328
+ });
329
+ let actualBytes = 0;
330
+ for (const data of Object.values(files)) {
331
+ actualBytes += data.byteLength;
332
+ if (actualBytes > MAX_ZIP_UNCOMPRESSED_BYTES) {
333
+ throw new Error(
334
+ `Archive exceeds max allowed uncompressed size (${MAX_ZIP_UNCOMPRESSED_BYTES} bytes).`
335
+ );
336
+ }
337
+ }
338
+ return files;
339
+ }
340
+ function zipFiles(files) {
341
+ return zipSync(files, { level: 6 });
342
+ }
343
+ function unescapeXml(value) {
344
+ return value.replace(
345
+ /&(#x[0-9a-fA-F]+|#[0-9]+|amp|lt|gt|quot|apos);/g,
346
+ (match, entity) => {
347
+ if (entity === "amp") return "&";
348
+ if (entity === "lt") return "<";
349
+ if (entity === "gt") return ">";
350
+ if (entity === "quot") return '"';
351
+ if (entity === "apos") return "'";
352
+ if (entity.startsWith("#x") || entity.startsWith("#X")) {
353
+ const code = Number.parseInt(entity.slice(2), 16);
354
+ return Number.isFinite(code) ? String.fromCodePoint(code) : match;
355
+ }
356
+ if (entity.startsWith("#")) {
357
+ const code = Number.parseInt(entity.slice(1), 10);
358
+ return Number.isFinite(code) ? String.fromCodePoint(code) : match;
359
+ }
360
+ return match;
361
+ }
362
+ );
363
+ }
364
+ function escapeXml(value) {
365
+ let out = "";
366
+ for (let i = 0; i < value.length; i++) {
367
+ const ch = value[i] ?? "";
368
+ const code = value.charCodeAt(i);
369
+ if (code < 32 && code !== 9 && code !== 10 && code !== 13) continue;
370
+ if (ch === "&") out += "&amp;";
371
+ else if (ch === "<") out += "&lt;";
372
+ else if (ch === ">") out += "&gt;";
373
+ else if (ch === '"') out += "&quot;";
374
+ else if (ch === "'") out += "&apos;";
375
+ else out += ch;
376
+ }
377
+ return out;
378
+ }
379
+ function escapeRegexLiteral(value) {
380
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
381
+ }
382
+ function extractXmlTextContainers(xml, containerTag, textTags, options) {
383
+ const escapedContainer = escapeRegexLiteral(containerTag);
384
+ const containerRe = new RegExp(
385
+ `<${escapedContainer}(?:\\s[^>]*)?>([\\s\\S]*?)<\\/${escapedContainer}>`,
386
+ "g"
387
+ );
388
+ const sepTags = options?.separatorTags ?? {};
389
+ const sepTagNames = Object.keys(sepTags);
390
+ const allTagAlternation = [...textTags, ...sepTagNames].map(escapeRegexLiteral).join("|");
391
+ const tokenRe = new RegExp(
392
+ `<(${allTagAlternation})(?:\\s[^>]*)?\\/>|<(${textTags.map(escapeRegexLiteral).join("|")})(\\s[^>]*)?>([\\s\\S]*?)<\\/\\2>`,
393
+ "g"
394
+ );
395
+ const containers = [];
396
+ let containerMatch = containerRe.exec(xml);
397
+ while (containerMatch !== null) {
398
+ const inner = containerMatch[1] ?? "";
399
+ const openEndOffset = containerMatch.index + containerMatch[0].indexOf(">") + 1;
400
+ const nodes = [];
401
+ let combined = "";
402
+ tokenRe.lastIndex = 0;
403
+ let tok = tokenRe.exec(inner);
404
+ while (tok !== null) {
405
+ const selfClosingName = tok[1];
406
+ if (selfClosingName !== void 0) {
407
+ const sepChar = sepTags[selfClosingName];
408
+ if (sepChar) {
409
+ combined += sepChar;
410
+ }
411
+ tok = tokenRe.exec(inner);
412
+ continue;
413
+ }
414
+ const tagName = tok[2] ?? "";
415
+ const attrs = tok[3] ?? "";
416
+ const rawContent = tok[4] ?? "";
417
+ const openTag = `<${tagName}${attrs}>`;
418
+ const unescaped = unescapeXml(rawContent);
419
+ const tagStart = openEndOffset + tok.index;
420
+ const contentStart = tagStart + openTag.length;
421
+ const contentEnd = contentStart + rawContent.length;
422
+ const combinedStart = combined.length;
423
+ combined += unescaped;
424
+ const combinedEnd = combined.length;
425
+ nodes.push({
426
+ tagStart,
427
+ contentStart,
428
+ contentEnd,
429
+ openTag,
430
+ text: unescaped,
431
+ combinedStart,
432
+ combinedEnd
433
+ });
434
+ tok = tokenRe.exec(inner);
435
+ }
436
+ if (nodes.length > 0) {
437
+ containers.push({ text: combined, nodes });
438
+ }
439
+ containerMatch = containerRe.exec(xml);
440
+ }
441
+ return containers;
442
+ }
443
+ function ensurePreserveSpace(openTag, nextText) {
444
+ if (!nextText) return openTag;
445
+ const needsPreserve = /^\s|\s$/.test(nextText);
446
+ if (!needsPreserve || openTag.includes("xml:space=")) return openTag;
447
+ return `${openTag.slice(0, -1)} xml:space="preserve">`;
448
+ }
449
+ function applyXmlContainerReplacements(xml, containers, replacementsByContainer) {
450
+ const rawPatches = [];
451
+ for (const [containerIndex, spans] of replacementsByContainer.entries()) {
452
+ if (spans.length === 0) continue;
453
+ const container = containers[containerIndex];
454
+ if (!container) continue;
455
+ const sortedSpans = [...spans].sort((a, b) => a.start - b.start);
456
+ const nextNodeTexts = container.nodes.map((node) => node.text);
457
+ for (let s = sortedSpans.length - 1; s >= 0; s--) {
458
+ const span = sortedSpans[s];
459
+ if (!span || span.end <= span.start) continue;
460
+ let placedReplacement = false;
461
+ for (let n = 0; n < container.nodes.length; n++) {
462
+ const node = container.nodes[n];
463
+ if (!node) continue;
464
+ const overlapStart = Math.max(span.start, node.combinedStart);
465
+ const overlapEnd = Math.min(span.end, node.combinedEnd);
466
+ if (overlapEnd <= overlapStart) continue;
467
+ const localStart = overlapStart - node.combinedStart;
468
+ const localEnd = overlapEnd - node.combinedStart;
469
+ const current = nextNodeTexts[n] ?? "";
470
+ const insert = placedReplacement ? "" : span.replacement;
471
+ placedReplacement = true;
472
+ nextNodeTexts[n] = current.slice(0, localStart) + insert + current.slice(localEnd);
473
+ }
474
+ }
475
+ for (let n = 0; n < container.nodes.length; n++) {
476
+ const node = container.nodes[n];
477
+ const nextText = nextNodeTexts[n];
478
+ if (!node || nextText === void 0 || nextText === node.text) continue;
479
+ const nextOpenTag = ensurePreserveSpace(node.openTag, nextText);
480
+ rawPatches.push({
481
+ start: node.tagStart,
482
+ end: node.contentEnd,
483
+ replacement: `${nextOpenTag}${escapeXml(nextText)}`
484
+ });
485
+ }
486
+ }
487
+ if (rawPatches.length === 0) return xml;
488
+ rawPatches.sort((a, b) => b.start - a.start);
489
+ let out = xml;
490
+ for (const patch of rawPatches) {
491
+ out = out.slice(0, patch.start) + patch.replacement + out.slice(patch.end);
492
+ }
493
+ return out;
494
+ }
495
+ function scrubXmlMetadata(xml, tagNames) {
496
+ const found = {};
497
+ const cleared = [];
498
+ let nextXml = xml;
499
+ for (const tag of tagNames) {
500
+ const escaped = escapeRegexLiteral(tag);
501
+ const re = new RegExp(`(<${escaped}(?:\\s[^>]*)?>)([\\s\\S]*?)(<\\/${escaped}>)`, "g");
502
+ nextXml = nextXml.replace(re, (_match, open, inner, close) => {
503
+ const text = unescapeXml(inner).trim();
504
+ if (text.length > 0) {
505
+ found[tag] = text;
506
+ cleared.push(tag);
507
+ }
508
+ return `${open}${close}`;
509
+ });
510
+ }
511
+ return { xml: nextXml, found, cleared };
512
+ }
513
+ var CORE_META_TAGS = [
514
+ "dc:creator",
515
+ "cp:lastModifiedBy",
516
+ "dc:title",
517
+ "dc:subject",
518
+ "dc:description",
519
+ "cp:keywords"
520
+ ];
521
+ var APP_META_TAGS = ["Company", "Manager"];
522
+ var DOCX_MIME = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
523
+ var XLSX_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
524
+ var DOCX_TEXT_PART_RE = /^word\/(?:document|header\d+|footer\d+|footnotes|endnotes|comments)\.xml$/i;
525
+ var XLSX_SHEET_PART_RE = /^xl\/worksheets\/sheet\d+\.xml$/i;
526
+ var XLSX_COMMENT_PART_RE = /^xl\/comments\d*\.xml$/i;
527
+ function countRedactionsByLabel(redactions) {
528
+ const counts = {};
529
+ for (const r of redactions) {
530
+ counts[r.label] = (counts[r.label] ?? 0) + 1;
531
+ }
532
+ return counts;
533
+ }
534
+ function scrubDocxReviewAuthors(xml) {
535
+ const stripped = [];
536
+ const next = xml.replace(
537
+ /(<w:(?:comment|ins|del|moveFrom|moveTo)\b[^>]*?\bw:author=")([^"]*)(")/g,
538
+ (_m, open, val, close) => {
539
+ const cleaned = unescapeXml(val).trim();
540
+ if (cleaned) stripped.push(cleaned);
541
+ return `${open}${close}`;
542
+ }
543
+ );
544
+ return { xml: next, stripped };
545
+ }
546
+ function scrubXlsxCommentAuthors(xml) {
547
+ const stripped = [];
548
+ const next = xml.replace(
549
+ /(<author(?:\s[^>]*)?>)([\s\S]*?)(<\/author>)/g,
550
+ (_m, open, inner, close) => {
551
+ const cleaned = unescapeXml(inner).trim();
552
+ if (cleaned) stripped.push(cleaned);
553
+ return `${open}${close}`;
554
+ }
555
+ );
556
+ return { xml: next, stripped };
557
+ }
558
+ async function redactRelsTargets(archive, redactFn) {
559
+ const cleared = [];
560
+ const originalValues = [];
561
+ for (const [entryName, raw] of Object.entries(archive)) {
562
+ if (!entryName.toLowerCase().endsWith(".rels")) continue;
563
+ const xml = decodeUtf8(raw);
564
+ const relRe = /<Relationship\b[^>]*>/g;
565
+ const patches = [];
566
+ let relMatch = relRe.exec(xml);
567
+ while (relMatch !== null) {
568
+ const tag = relMatch[0];
569
+ const targetMatch = /\bTarget="([^"]*)"/.exec(tag);
570
+ if (targetMatch?.[1]) {
571
+ const rawTarget = unescapeXml(targetMatch[1]);
572
+ const isExternal = /\bTargetMode="External"/i.test(tag) || /^(?:mailto:|tel:|https?:)/i.test(rawTarget);
573
+ if (isExternal) {
574
+ const res = await redactFn(rawTarget);
575
+ if (res.redactions.length > 0) {
576
+ for (const r of res.redactions) originalValues.push(r.value);
577
+ const nextTag = tag.replace(/\bTarget="([^"]*)"/, `Target="${escapeXml(res.text)}"`);
578
+ patches.push({
579
+ start: relMatch.index,
580
+ end: relMatch.index + tag.length,
581
+ replacement: nextTag
582
+ });
583
+ }
584
+ }
585
+ }
586
+ relMatch = relRe.exec(xml);
587
+ }
588
+ if (patches.length > 0) {
589
+ let nextXml = xml;
590
+ for (let i = patches.length - 1; i >= 0; i--) {
591
+ const p = patches[i];
592
+ if (!p) continue;
593
+ nextXml = nextXml.slice(0, p.start) + p.replacement + nextXml.slice(p.end);
594
+ }
595
+ archive[entryName] = encodeUtf8(nextXml);
596
+ cleared.push(`${entryName}:Target`);
597
+ }
598
+ }
599
+ return { cleared, originalValues };
600
+ }
601
+ async function redactDocxInstrText(xml, redactFn) {
602
+ const originalValues = [];
603
+ const instrRe = /(<w:instrText(?:\s[^>]*)?>)([\s\S]*?)(<\/w:instrText>)/g;
604
+ const patches = [];
605
+ let m = instrRe.exec(xml);
606
+ while (m !== null) {
607
+ const open = m[1] ?? "";
608
+ const rawInner = m[2] ?? "";
609
+ const close = m[3] ?? "";
610
+ const text = unescapeXml(rawInner);
611
+ if (text.trim().length > 0) {
612
+ const res = await redactFn(text);
613
+ if (res.redactions.length > 0) {
614
+ for (const r of res.redactions) originalValues.push(r.value);
615
+ patches.push({
616
+ start: m.index,
617
+ end: m.index + m[0].length,
618
+ replacement: `${open}${escapeXml(res.text)}${close}`
619
+ });
620
+ }
621
+ }
622
+ m = instrRe.exec(xml);
623
+ }
624
+ if (patches.length === 0) return { xml, originalValues };
625
+ let out = xml;
626
+ for (let i = patches.length - 1; i >= 0; i--) {
627
+ const p = patches[i];
628
+ if (!p) continue;
629
+ out = out.slice(0, p.start) + p.replacement + out.slice(p.end);
630
+ }
631
+ return { xml: out, originalValues };
632
+ }
633
+ function sanitizeExcelSheetName(raw, usedNames) {
634
+ let cleaned = raw.replace(/[\\/?*[\]:]/g, "").replace(/\s+/g, " ").trim();
635
+ if (!cleaned) cleaned = "Sheet";
636
+ if (cleaned.length > 31) cleaned = cleaned.slice(0, 31).trim();
637
+ let candidate = cleaned;
638
+ let suffix = 2;
639
+ while (usedNames.has(candidate.toLowerCase())) {
640
+ const tag = `_${suffix}`;
641
+ candidate = `${cleaned.slice(0, Math.max(1, 31 - tag.length))}${tag}`;
642
+ suffix += 1;
643
+ }
644
+ usedNames.add(candidate.toLowerCase());
645
+ return candidate;
646
+ }
647
+ async function redactXlsxWorkbookSheetNames(archive, redactFn) {
648
+ const wbKey = Object.keys(archive).find((k) => k.toLowerCase() === "xl/workbook.xml");
649
+ if (!wbKey || !archive[wbKey]) return { cleared: [], originalValues: [] };
650
+ const xml = decodeUtf8(archive[wbKey]);
651
+ const sheetRe = /<sheet\b[^>]*>/g;
652
+ const usedNames = /* @__PURE__ */ new Set();
653
+ const patches = [];
654
+ const originalValues = [];
655
+ let m = sheetRe.exec(xml);
656
+ while (m !== null) {
657
+ const tag = m[0];
658
+ const nameMatch = /\bname="([^"]*)"/.exec(tag);
659
+ if (nameMatch?.[1]) {
660
+ const sheetName = unescapeXml(nameMatch[1]);
661
+ const res = await redactFn(sheetName);
662
+ if (res.redactions.length > 0) {
663
+ for (const r of res.redactions) originalValues.push(r.value);
664
+ const safeName = sanitizeExcelSheetName(res.text, usedNames);
665
+ const nextTag = tag.replace(/\bname="([^"]*)"/, `name="${escapeXml(safeName)}"`);
666
+ patches.push({
667
+ start: m.index,
668
+ end: m.index + tag.length,
669
+ replacement: nextTag
670
+ });
671
+ } else {
672
+ usedNames.add(sheetName.toLowerCase());
673
+ }
674
+ }
675
+ m = sheetRe.exec(xml);
676
+ }
677
+ if (patches.length === 0) return { cleared: [], originalValues: [] };
678
+ let nextXml = xml;
679
+ for (let i = patches.length - 1; i >= 0; i--) {
680
+ const p = patches[i];
681
+ if (!p) continue;
682
+ nextXml = nextXml.slice(0, p.start) + p.replacement + nextXml.slice(p.end);
683
+ }
684
+ archive[wbKey] = encodeUtf8(nextXml);
685
+ return { cleared: [`${wbKey}:sheetName`], originalValues };
686
+ }
687
+ function listDocxTextParts(entryNames) {
688
+ return entryNames.filter((name) => DOCX_TEXT_PART_RE.test(name)).sort((a, b) => {
689
+ if (a.toLowerCase() === "word/document.xml") return -1;
690
+ if (b.toLowerCase() === "word/document.xml") return 1;
691
+ return a.localeCompare(b);
692
+ });
693
+ }
694
+ function listXlsxParts(entryNames) {
695
+ const sharedStrings = entryNames.find((n) => n.toLowerCase() === "xl/sharedstrings.xml");
696
+ const sheets = entryNames.filter((n) => XLSX_SHEET_PART_RE.test(n)).sort((a, b) => a.localeCompare(b, void 0, { numeric: true }));
697
+ const comments = entryNames.filter((n) => XLSX_COMMENT_PART_RE.test(n)).sort((a, b) => a.localeCompare(b, void 0, { numeric: true }));
698
+ return { sharedStrings, sheets, comments };
699
+ }
700
+ function extractOfficeMetadata(archive) {
701
+ const metadata = {};
702
+ const cleared = [];
703
+ const updatedArchive = { ...archive };
704
+ const coreKey = Object.keys(archive).find((k) => k.toLowerCase() === "docprops/core.xml");
705
+ if (coreKey && archive[coreKey]) {
706
+ const res = scrubXmlMetadata(decodeUtf8(archive[coreKey]), CORE_META_TAGS);
707
+ Object.assign(metadata, res.found);
708
+ cleared.push(...res.cleared);
709
+ updatedArchive[coreKey] = encodeUtf8(res.xml);
710
+ }
711
+ const appKey = Object.keys(archive).find((k) => k.toLowerCase() === "docprops/app.xml");
712
+ if (appKey && archive[appKey]) {
713
+ const res = scrubXmlMetadata(decodeUtf8(archive[appKey]), APP_META_TAGS);
714
+ Object.assign(metadata, res.found);
715
+ cleared.push(...res.cleared);
716
+ updatedArchive[appKey] = encodeUtf8(res.xml);
717
+ }
718
+ return { metadata, cleared, updatedArchive };
719
+ }
720
+ function mapRedactionsToPartContainers(parts, redactions) {
721
+ const byPart = /* @__PURE__ */ new Map();
722
+ for (const r of redactions) {
723
+ for (const part of parts) {
724
+ let partMap = byPart.get(part.partPath);
725
+ for (let i = 0; i < part.containerOffsets.length; i++) {
726
+ const range = part.containerOffsets[i];
727
+ if (!range) continue;
728
+ if (r.end <= range.start || r.start >= range.end) continue;
729
+ const localStart = Math.max(0, r.start - range.start);
730
+ const localEnd = Math.min(range.end - range.start, r.end - range.start);
731
+ if (localEnd <= localStart) continue;
732
+ if (!partMap) {
733
+ partMap = /* @__PURE__ */ new Map();
734
+ byPart.set(part.partPath, partMap);
735
+ }
736
+ const list = partMap.get(i) ?? [];
737
+ list.push({ start: localStart, end: localEnd, replacement: r.replacement });
738
+ partMap.set(i, list);
739
+ }
740
+ }
741
+ }
742
+ return byPart;
743
+ }
744
+ function extractDocx(bytes) {
745
+ const archive = unzipSafely(bytes);
746
+ const parts = listDocxTextParts(Object.keys(archive));
747
+ const sections = [];
748
+ for (const partPath of parts) {
749
+ const raw = archive[partPath];
750
+ if (!raw) continue;
751
+ const xml = decodeUtf8(raw);
752
+ const containers = extractXmlTextContainers(xml, "w:p", ["w:t", "w:delText"], {
753
+ separatorTags: { "w:tab": " ", "w:br": "\n", "w:cr": "\n" }
754
+ });
755
+ const partText = containers.map((c) => c.text).filter((t) => t.length > 0).join("\n\n");
756
+ if (partText.length > 0) {
757
+ sections.push({
758
+ id: partPath,
759
+ label: partPath.replace(/^word\//i, "").replace(/\.xml$/i, ""),
760
+ text: partText
761
+ });
762
+ }
763
+ }
764
+ const { metadata } = extractOfficeMetadata(archive);
765
+ const fullText = sections.map((s) => s.text).join("\n\n");
766
+ return {
767
+ format: "docx",
768
+ mimeType: DOCX_MIME,
769
+ text: fullText,
770
+ sections,
771
+ metadata,
772
+ warnings: [],
773
+ scannedPages: []
774
+ };
775
+ }
776
+ async function redactDocx(bytes, redactFn) {
777
+ const archive = unzipSafely(bytes);
778
+ const { metadata, cleared: metadataCleared, updatedArchive } = extractOfficeMetadata(archive);
779
+ const metadataValues = Object.values(metadata);
780
+ const partPaths = listDocxTextParts(Object.keys(updatedArchive));
781
+ const parts = [];
782
+ const textChunks = [];
783
+ let cursor = 0;
784
+ for (const partPath of partPaths) {
785
+ const raw = updatedArchive[partPath];
786
+ if (!raw) continue;
787
+ const rawXml = decodeUtf8(raw);
788
+ const { xml, stripped } = scrubDocxReviewAuthors(rawXml);
789
+ if (stripped.length > 0) {
790
+ metadataCleared.push(`${partPath}:w:author`);
791
+ metadataValues.push(...stripped);
792
+ }
793
+ const containers = extractXmlTextContainers(xml, "w:p", ["w:t", "w:delText"], {
794
+ separatorTags: { "w:tab": " ", "w:br": "\n", "w:cr": "\n" }
795
+ });
796
+ const containerOffsets = [];
797
+ for (const container of containers) {
798
+ if (container.text.length === 0) {
799
+ containerOffsets.push({ start: cursor, end: cursor });
800
+ continue;
801
+ }
802
+ if (textChunks.length > 0) {
803
+ textChunks.push("\n\n");
804
+ cursor += 2;
805
+ }
806
+ const start = cursor;
807
+ textChunks.push(container.text);
808
+ cursor += container.text.length;
809
+ containerOffsets.push({ start, end: cursor });
810
+ }
811
+ parts.push({ partPath, xml, containers, containerOffsets });
812
+ }
813
+ const combinedText = textChunks.join("");
814
+ const result = await redactFn(combinedText);
815
+ const replacementsByPart = mapRedactionsToPartContainers(parts, result.redactions);
816
+ for (const part of parts) {
817
+ const partMap = replacementsByPart.get(part.partPath);
818
+ let nextXml = partMap ? applyXmlContainerReplacements(part.xml, part.containers, partMap) : part.xml;
819
+ const instr = await redactDocxInstrText(nextXml, redactFn);
820
+ if (instr.originalValues.length > 0) {
821
+ nextXml = instr.xml;
822
+ metadataCleared.push(`${part.partPath}:w:instrText`);
823
+ metadataValues.push(...instr.originalValues);
824
+ }
825
+ updatedArchive[part.partPath] = encodeUtf8(nextXml);
826
+ }
827
+ const relsRes = await redactRelsTargets(updatedArchive, redactFn);
828
+ metadataCleared.push(...relsRes.cleared);
829
+ metadataValues.push(...relsRes.originalValues);
830
+ return {
831
+ bytes: zipFiles(updatedArchive),
832
+ extractedText: combinedText,
833
+ redactedText: result.text,
834
+ totalRedactions: result.redactions.length,
835
+ counts: countRedactionsByLabel(result.redactions),
836
+ redactions: result.redactions,
837
+ map: result.map,
838
+ metadataCleared,
839
+ metadataValues,
840
+ warnings: []
841
+ };
842
+ }
843
+ function extractXlsxCachedFormulaStrings(xml) {
844
+ const out = [];
845
+ const cellRe = /<c\b[^>]*\bt="str"[^>]*>([\s\S]*?)<\/c>/g;
846
+ let m = cellRe.exec(xml);
847
+ while (m !== null) {
848
+ const inner = m[1] ?? "";
849
+ const vMatch = /<v(?:\s[^>]*)?>([\s\S]*?)<\/v>/.exec(inner);
850
+ if (vMatch) {
851
+ const openEnd = m.index + m[0].indexOf(">") + 1;
852
+ const vOpenEnd = vMatch.index + vMatch[0].indexOf(">") + 1;
853
+ const rawContent = vMatch[1] ?? "";
854
+ const contentStart = openEnd + vOpenEnd;
855
+ const contentEnd = contentStart + rawContent.length;
856
+ out.push({ contentStart, contentEnd, text: unescapeXml(rawContent) });
857
+ }
858
+ m = cellRe.exec(xml);
859
+ }
860
+ return out;
861
+ }
862
+ function extractXlsx(bytes) {
863
+ const archive = unzipSafely(bytes);
864
+ const { sharedStrings, sheets, comments } = listXlsxParts(Object.keys(archive));
865
+ const sections = [];
866
+ if (sharedStrings && archive[sharedStrings]) {
867
+ const xml = decodeUtf8(archive[sharedStrings]);
868
+ const containers = extractXmlTextContainers(xml, "si", ["t"]);
869
+ const text = containers.map((c) => c.text).filter((t) => t.length > 0).join("\n\n");
870
+ if (text) {
871
+ sections.push({ id: sharedStrings, label: "sharedStrings", text });
872
+ }
873
+ }
874
+ for (const sheetPath of sheets) {
875
+ const raw = archive[sheetPath];
876
+ if (!raw) continue;
877
+ const xml = decodeUtf8(raw);
878
+ const inlineContainers = extractXmlTextContainers(xml, "is", ["t"]);
879
+ const formulaStrings = extractXlsxCachedFormulaStrings(xml);
880
+ const lines = [
881
+ ...inlineContainers.map((c) => c.text),
882
+ ...formulaStrings.map((f) => f.text)
883
+ ].filter((t) => t.length > 0);
884
+ if (lines.length > 0) {
885
+ sections.push({
886
+ id: sheetPath,
887
+ label: sheetPath.replace(/^xl\/worksheets\//i, "").replace(/\.xml$/i, ""),
888
+ text: lines.join("\n\n")
889
+ });
890
+ }
891
+ }
892
+ for (const commentPath of comments) {
893
+ const raw = archive[commentPath];
894
+ if (!raw) continue;
895
+ const xml = decodeUtf8(raw);
896
+ const commentContainers = extractXmlTextContainers(xml, "text", ["t"]);
897
+ const lines = commentContainers.map((c) => c.text).filter((t) => t.length > 0);
898
+ if (lines.length > 0) {
899
+ sections.push({
900
+ id: commentPath,
901
+ label: commentPath.replace(/^xl\//i, "").replace(/\.xml$/i, ""),
902
+ text: lines.join("\n\n")
903
+ });
904
+ }
905
+ }
906
+ const { metadata } = extractOfficeMetadata(archive);
907
+ return {
908
+ format: "xlsx",
909
+ mimeType: XLSX_MIME,
910
+ text: sections.map((s) => s.text).join("\n\n"),
911
+ sections,
912
+ metadata,
913
+ warnings: [],
914
+ scannedPages: []
915
+ };
916
+ }
917
+ async function redactXlsx(bytes, redactFn) {
918
+ const archive = unzipSafely(bytes);
919
+ const { metadata, cleared: metadataCleared, updatedArchive } = extractOfficeMetadata(archive);
920
+ const metadataValues = Object.values(metadata);
921
+ const { sharedStrings, sheets, comments } = listXlsxParts(Object.keys(updatedArchive));
922
+ const parts = [];
923
+ const formulaRecords = [];
924
+ const textChunks = [];
925
+ let cursor = 0;
926
+ const addPart = (partPath, xml, containerTag) => {
927
+ const containers = extractXmlTextContainers(xml, containerTag, ["t"]);
928
+ const containerOffsets = [];
929
+ for (const container of containers) {
930
+ if (container.text.length === 0) {
931
+ containerOffsets.push({ start: cursor, end: cursor });
932
+ continue;
933
+ }
934
+ if (textChunks.length > 0) {
935
+ textChunks.push("\n\n");
936
+ cursor += 2;
937
+ }
938
+ const start = cursor;
939
+ textChunks.push(container.text);
940
+ cursor += container.text.length;
941
+ containerOffsets.push({ start, end: cursor });
942
+ }
943
+ parts.push({ partPath, xml, containers, containerOffsets });
944
+ };
945
+ if (sharedStrings && updatedArchive[sharedStrings]) {
946
+ addPart(sharedStrings, decodeUtf8(updatedArchive[sharedStrings]), "si");
947
+ }
948
+ for (const sheetPath of sheets) {
949
+ const raw = updatedArchive[sheetPath];
950
+ if (!raw) continue;
951
+ const xml = decodeUtf8(raw);
952
+ addPart(sheetPath, xml, "is");
953
+ const formulas = extractXlsxCachedFormulaStrings(xml);
954
+ if (formulas.length > 0) {
955
+ const entries = [];
956
+ for (const f of formulas) {
957
+ if (textChunks.length > 0) {
958
+ textChunks.push("\n\n");
959
+ cursor += 2;
960
+ }
961
+ const start = cursor;
962
+ textChunks.push(f.text);
963
+ cursor += f.text.length;
964
+ entries.push({
965
+ contentStart: f.contentStart,
966
+ contentEnd: f.contentEnd,
967
+ start,
968
+ end: cursor
969
+ });
970
+ }
971
+ formulaRecords.push({ partPath: sheetPath, entries });
972
+ }
973
+ }
974
+ for (const commentPath of comments) {
975
+ const raw = updatedArchive[commentPath];
976
+ if (!raw) continue;
977
+ const { xml, stripped } = scrubXlsxCommentAuthors(decodeUtf8(raw));
978
+ if (stripped.length > 0) {
979
+ metadataCleared.push(`${commentPath}:author`);
980
+ metadataValues.push(...stripped);
981
+ }
982
+ addPart(commentPath, xml, "text");
983
+ }
984
+ const combinedText = textChunks.join("");
985
+ const result = await redactFn(combinedText);
986
+ const replacementsByPart = mapRedactionsToPartContainers(parts, result.redactions);
987
+ const formulaByPart = new Map(formulaRecords.map((f) => [f.partPath, f.entries]));
988
+ for (const part of parts) {
989
+ let nextXml = part.xml;
990
+ const formulaEntries = formulaByPart.get(part.partPath);
991
+ if (formulaEntries && formulaEntries.length > 0) {
992
+ const rawPatches = [];
993
+ for (const entry of formulaEntries) {
994
+ const overlapping = result.redactions.filter(
995
+ (r) => r.end > entry.start && r.start < entry.end
996
+ );
997
+ if (overlapping.length === 0) continue;
998
+ let text = combinedText.slice(entry.start, entry.end);
999
+ for (let i = overlapping.length - 1; i >= 0; i--) {
1000
+ const r = overlapping[i];
1001
+ if (!r) continue;
1002
+ const localStart = Math.max(0, r.start - entry.start);
1003
+ const localEnd = Math.min(text.length, r.end - entry.start);
1004
+ text = text.slice(0, localStart) + r.replacement + text.slice(localEnd);
1005
+ }
1006
+ rawPatches.push({
1007
+ start: entry.contentStart,
1008
+ end: entry.contentEnd,
1009
+ replacement: escapeXml(text)
1010
+ });
1011
+ }
1012
+ if (rawPatches.length > 0) {
1013
+ rawPatches.sort((a, b) => b.start - a.start);
1014
+ for (const p of rawPatches) {
1015
+ nextXml = nextXml.slice(0, p.start) + p.replacement + nextXml.slice(p.end);
1016
+ }
1017
+ const partMap2 = replacementsByPart.get(part.partPath);
1018
+ if (partMap2 && partMap2.size > 0) {
1019
+ const freshContainers = extractXmlTextContainers(nextXml, "is", ["t"]);
1020
+ nextXml = applyXmlContainerReplacements(nextXml, freshContainers, partMap2);
1021
+ }
1022
+ updatedArchive[part.partPath] = encodeUtf8(nextXml);
1023
+ continue;
1024
+ }
1025
+ }
1026
+ const partMap = replacementsByPart.get(part.partPath);
1027
+ if (partMap) {
1028
+ nextXml = applyXmlContainerReplacements(nextXml, part.containers, partMap);
1029
+ }
1030
+ updatedArchive[part.partPath] = encodeUtf8(nextXml);
1031
+ }
1032
+ const wbRes = await redactXlsxWorkbookSheetNames(updatedArchive, redactFn);
1033
+ metadataCleared.push(...wbRes.cleared);
1034
+ metadataValues.push(...wbRes.originalValues);
1035
+ const relsRes = await redactRelsTargets(updatedArchive, redactFn);
1036
+ metadataCleared.push(...relsRes.cleared);
1037
+ metadataValues.push(...relsRes.originalValues);
1038
+ return {
1039
+ bytes: zipFiles(updatedArchive),
1040
+ extractedText: combinedText,
1041
+ redactedText: result.text,
1042
+ totalRedactions: result.redactions.length,
1043
+ counts: countRedactionsByLabel(result.redactions),
1044
+ redactions: result.redactions,
1045
+ map: result.map,
1046
+ metadataCleared,
1047
+ metadataValues,
1048
+ warnings: []
1049
+ };
1050
+ }
1051
+ var configuredWorkerSrc;
1052
+ var cachedPdfjsPromise = null;
1053
+ async function loadPdfjs(workerSrcOverride) {
1054
+ if (!cachedPdfjsPromise) {
1055
+ cachedPdfjsPromise = import('pdfjs-dist/legacy/build/pdf.mjs');
1056
+ }
1057
+ const pdfjs = await cachedPdfjsPromise;
1058
+ const workerSrc = workerSrcOverride ?? configuredWorkerSrc;
1059
+ if (workerSrc && pdfjs.GlobalWorkerOptions.workerSrc !== workerSrc) {
1060
+ pdfjs.GlobalWorkerOptions.workerSrc = workerSrc;
1061
+ }
1062
+ return pdfjs;
1063
+ }
1064
+ function isPdfTextItem(item) {
1065
+ if (!item || typeof item !== "object") return false;
1066
+ const rec = item;
1067
+ return typeof rec.str === "string" && Array.isArray(rec.transform) && rec.transform.length >= 6;
1068
+ }
1069
+ function computeItemBounds(item) {
1070
+ const [a = 12, b = 0, c = 0, d = 12, e = 0, f = 0] = item.transform;
1071
+ const scaleX = Math.hypot(a, b);
1072
+ const scaleY = Math.hypot(c, d);
1073
+ const fontHeight = Math.max(scaleY, scaleX, item.height || 0, 6);
1074
+ const width = typeof item.width === "number" && item.width > 0 ? item.width : fontHeight * 0.55 * Math.max(1, item.str.length);
1075
+ const isHorizontal = Math.abs(b) < 0.05 && Math.abs(c) < 0.05;
1076
+ if (isHorizontal) {
1077
+ return {
1078
+ x1: e,
1079
+ y1: f - fontHeight * 0.3,
1080
+ x2: e + width,
1081
+ y2: f + fontHeight * 1.08,
1082
+ fontHeight,
1083
+ isHorizontal: true
1084
+ };
1085
+ }
1086
+ const lenX = scaleX || 1;
1087
+ const ux = a / lenX;
1088
+ const uy = b / lenX;
1089
+ const lenY = scaleY || 1;
1090
+ const vx = c / lenY;
1091
+ const vy = d / lenY;
1092
+ const asc = fontHeight * 1.08;
1093
+ const desc = -fontHeight * 0.3;
1094
+ const corners = [
1095
+ [e + vx * desc, f + vy * desc],
1096
+ [e + ux * width + vx * desc, f + uy * width + vy * desc],
1097
+ [e + vx * asc, f + vy * asc],
1098
+ [e + ux * width + vx * asc, f + uy * width + vy * asc]
1099
+ ];
1100
+ let x1 = Number.POSITIVE_INFINITY;
1101
+ let y1 = Number.POSITIVE_INFINITY;
1102
+ let x2 = Number.NEGATIVE_INFINITY;
1103
+ let y2 = Number.NEGATIVE_INFINITY;
1104
+ for (const [cx, cy] of corners) {
1105
+ if (cx < x1) x1 = cx;
1106
+ if (cy < y1) y1 = cy;
1107
+ if (cx > x2) x2 = cx;
1108
+ if (cy > y2) y2 = cy;
1109
+ }
1110
+ return { x1, y1, x2, y2, fontHeight, isHorizontal: false };
1111
+ }
1112
+ function buildPageTextAndMap(rawItems, styles) {
1113
+ const items = [];
1114
+ let text = "";
1115
+ let prevBaselineY = null;
1116
+ let prevRightX = 0;
1117
+ let prevHadEol = false;
1118
+ for (const raw of rawItems) {
1119
+ if (!isPdfTextItem(raw)) continue;
1120
+ if (raw.str.length === 0) {
1121
+ if (raw.hasEOL) prevHadEol = true;
1122
+ continue;
1123
+ }
1124
+ const bounds = computeItemBounds(raw);
1125
+ const baselineY = raw.transform[5] ?? 0;
1126
+ const leftX = raw.transform[4] ?? 0;
1127
+ const style = raw.fontName ? styles?.[raw.fontName] : void 0;
1128
+ const fontFamily = style?.fontFamily || "sans-serif";
1129
+ if (text.length > 0) {
1130
+ const lineChanged = prevHadEol || prevBaselineY !== null && Math.abs(baselineY - prevBaselineY) > bounds.fontHeight * 0.6;
1131
+ if (lineChanged) {
1132
+ if (!text.endsWith("\n")) text += "\n";
1133
+ } else {
1134
+ const gap = leftX - prevRightX;
1135
+ const needsSpace = gap > bounds.fontHeight * 0.16 && !/\s$/.test(text) && !/^\s/.test(raw.str);
1136
+ if (needsSpace) text += " ";
1137
+ }
1138
+ }
1139
+ const start = text.length;
1140
+ text += raw.str;
1141
+ const end = text.length;
1142
+ const [a = 12, b = 0, c = 0, d = 12, e = 0, f = 0] = raw.transform;
1143
+ const itemWidth = typeof raw.width === "number" && raw.width > 0 ? raw.width : bounds.fontHeight * 0.55 * Math.max(1, raw.str.length);
1144
+ items.push({
1145
+ str: raw.str,
1146
+ start,
1147
+ end,
1148
+ x1: bounds.x1,
1149
+ y1: bounds.y1,
1150
+ x2: bounds.x2,
1151
+ y2: bounds.y2,
1152
+ fontHeight: bounds.fontHeight,
1153
+ fontFamily,
1154
+ width: itemWidth,
1155
+ transform: [a, b, c, d, e, f],
1156
+ isHorizontal: bounds.isHorizontal
1157
+ });
1158
+ prevBaselineY = baselineY;
1159
+ prevRightX = bounds.x2;
1160
+ prevHadEol = raw.hasEOL === true;
1161
+ }
1162
+ return { text, items };
1163
+ }
1164
+ function extractAnnotationTexts(annotations) {
1165
+ const out = [];
1166
+ for (const raw of annotations) {
1167
+ if (!raw || typeof raw !== "object") continue;
1168
+ const rec = raw;
1169
+ const snippets = [];
1170
+ if (typeof rec.url === "string" && rec.url.trim()) {
1171
+ snippets.push(rec.url.trim());
1172
+ }
1173
+ if (typeof rec.fieldValue === "string" && rec.fieldValue.trim()) {
1174
+ snippets.push(rec.fieldValue.trim());
1175
+ } else if (Array.isArray(rec.fieldValue)) {
1176
+ for (const v of rec.fieldValue) {
1177
+ if (typeof v === "string" && v.trim()) snippets.push(v.trim());
1178
+ }
1179
+ }
1180
+ if (rec.contentsObj && typeof rec.contentsObj === "object") {
1181
+ const str = rec.contentsObj.str;
1182
+ if (typeof str === "string" && str.trim()) snippets.push(str.trim());
1183
+ }
1184
+ if (typeof rec.titleObj === "object" && rec.titleObj !== null) {
1185
+ const str = rec.titleObj.str;
1186
+ if (typeof str === "string" && str.trim()) snippets.push(str.trim());
1187
+ }
1188
+ if (typeof rec.alternativeText === "string" && rec.alternativeText.trim()) {
1189
+ snippets.push(rec.alternativeText.trim());
1190
+ }
1191
+ if (snippets.length === 0) continue;
1192
+ let rect;
1193
+ if (Array.isArray(rec.rect) && rec.rect.length === 4 && rec.rect.every((n) => typeof n === "number" && Number.isFinite(n))) {
1194
+ rect = [rec.rect[0], rec.rect[1], rec.rect[2], rec.rect[3]];
1195
+ }
1196
+ out.push({ text: snippets.join(" "), rect });
1197
+ }
1198
+ return out;
1199
+ }
1200
+ function collectPdfMetadataStrings(meta) {
1201
+ const out = {};
1202
+ const sensitiveInfoKeys = [
1203
+ "Title",
1204
+ "Author",
1205
+ "Subject",
1206
+ "Keywords",
1207
+ "Creator",
1208
+ "Producer"
1209
+ ];
1210
+ if (meta.info && typeof meta.info === "object") {
1211
+ const info = meta.info;
1212
+ for (const key of sensitiveInfoKeys) {
1213
+ const value = info[key];
1214
+ if (typeof value === "string" && value.trim()) {
1215
+ out[key] = value.trim();
1216
+ }
1217
+ }
1218
+ }
1219
+ return out;
1220
+ }
1221
+ async function resolveDefaultCanvasProvider() {
1222
+ if (typeof document !== "undefined" && typeof document.createElement === "function") {
1223
+ return {
1224
+ createCanvas(width, height) {
1225
+ const canvas = document.createElement("canvas");
1226
+ canvas.width = width;
1227
+ canvas.height = height;
1228
+ return canvas;
1229
+ },
1230
+ async toPngBytes(canvas) {
1231
+ const htmlCanvas = canvas;
1232
+ const blob = await new Promise((resolve5, reject) => {
1233
+ htmlCanvas.toBlob((b) => {
1234
+ if (b) resolve5(b);
1235
+ else reject(new Error("Failed to encode PDF page canvas to PNG."));
1236
+ }, "image/png");
1237
+ });
1238
+ return new Uint8Array(await blob.arrayBuffer());
1239
+ }
1240
+ };
1241
+ }
1242
+ if (typeof OffscreenCanvas !== "undefined") {
1243
+ return {
1244
+ createCanvas(width, height) {
1245
+ return new OffscreenCanvas(width, height);
1246
+ },
1247
+ async toPngBytes(canvas) {
1248
+ const off = canvas;
1249
+ const blob = await off.convertToBlob({ type: "image/png" });
1250
+ return new Uint8Array(await blob.arrayBuffer());
1251
+ }
1252
+ };
1253
+ }
1254
+ const canvasPkg = "@napi-rs/canvas";
1255
+ const mod = await import(
1256
+ /* @vite-ignore */
1257
+ canvasPkg
1258
+ );
1259
+ return {
1260
+ createCanvas(width, height) {
1261
+ return mod.createCanvas(width, height);
1262
+ },
1263
+ toPngBytes(canvas) {
1264
+ const napiCanvas = canvas;
1265
+ return new Uint8Array(napiCanvas.toBuffer("image/png"));
1266
+ }
1267
+ };
1268
+ }
1269
+ function mergeLineBoxes(boxes) {
1270
+ if (boxes.length <= 1) return [...boxes];
1271
+ const sorted = [...boxes].sort((a, b) => {
1272
+ const cyA = (a.y1 + a.y2) / 2;
1273
+ const cyB = (b.y1 + b.y2) / 2;
1274
+ if (Math.abs(cyA - cyB) > Math.min(a.y2 - a.y1, b.y2 - b.y1) * 0.5) {
1275
+ return cyB - cyA;
1276
+ }
1277
+ return a.x1 - b.x1;
1278
+ });
1279
+ const merged = [];
1280
+ for (const box of sorted) {
1281
+ const prev = merged[merged.length - 1];
1282
+ if (prev && prev.replacement === box.replacement) {
1283
+ const hPrev = prev.y2 - prev.y1;
1284
+ const hCur = box.y2 - box.y1;
1285
+ const yOverlap = Math.min(prev.y2, box.y2) - Math.max(prev.y1, box.y1);
1286
+ const minH = Math.min(hPrev, hCur);
1287
+ const xGap = box.x1 - prev.x2;
1288
+ if (minH > 0 && yOverlap > minH * 0.45 && xGap <= Math.max(hPrev, hCur) * 1.5) {
1289
+ prev.x1 = Math.min(prev.x1, box.x1);
1290
+ prev.y1 = Math.min(prev.y1, box.y1);
1291
+ prev.x2 = Math.max(prev.x2, box.x2);
1292
+ prev.y2 = Math.max(prev.y2, box.y2);
1293
+ continue;
1294
+ }
1295
+ }
1296
+ merged.push({ ...box });
1297
+ }
1298
+ return merged;
1299
+ }
1300
+ function measureSubspanFractions(ctx, str, localStart, localEnd, fontFamily) {
1301
+ const len = Math.max(1, str.length);
1302
+ if (localStart <= 0 && localEnd >= len) {
1303
+ return { startFrac: 0, endFrac: 1 };
1304
+ }
1305
+ const isMonospace = /\bmono/i.test(fontFamily);
1306
+ if (isMonospace || !ctx?.measureText) {
1307
+ return { startFrac: localStart / len, endFrac: localEnd / len };
1308
+ }
1309
+ const prefix = str.slice(0, localStart);
1310
+ const uptoEnd = str.slice(0, localEnd);
1311
+ const families = /* @__PURE__ */ new Set([
1312
+ fontFamily,
1313
+ "Helvetica, Arial, sans-serif",
1314
+ "Times New Roman, Times, serif"
1315
+ ]);
1316
+ let minStart = 1;
1317
+ let maxEnd = 0;
1318
+ let measuredAny = false;
1319
+ ctx.save();
1320
+ for (const family of families) {
1321
+ ctx.font = `100px ${family}`;
1322
+ const fullW = ctx.measureText(str).width;
1323
+ if (!(fullW > 0)) continue;
1324
+ const startW = localStart > 0 ? ctx.measureText(prefix).width : 0;
1325
+ const endW = localEnd < len ? ctx.measureText(uptoEnd).width : fullW;
1326
+ minStart = Math.min(minStart, Math.max(0, startW / fullW));
1327
+ maxEnd = Math.max(maxEnd, Math.min(1, endW / fullW));
1328
+ measuredAny = true;
1329
+ }
1330
+ ctx.restore();
1331
+ if (!measuredAny || maxEnd <= minStart) {
1332
+ return { startFrac: localStart / len, endFrac: localEnd / len };
1333
+ }
1334
+ return { startFrac: minStart, endFrac: maxEnd };
1335
+ }
1336
+ function computePageRedactionBoxes(items, pageRedactions, ctx) {
1337
+ const boxes = [];
1338
+ for (const r of pageRedactions) {
1339
+ const rawForSpan = [];
1340
+ for (const item of items) {
1341
+ if (item.end <= r.start || item.start >= r.end) continue;
1342
+ const len = Math.max(1, item.str.length);
1343
+ const localStart = Math.max(0, r.start - item.start);
1344
+ const localEnd = Math.min(len, r.end - item.start);
1345
+ const padX = Math.max(3, item.fontHeight * 0.25);
1346
+ const padY = Math.max(1.5, item.fontHeight * 0.12);
1347
+ const { startFrac, endFrac } = measureSubspanFractions(
1348
+ ctx,
1349
+ item.str,
1350
+ localStart,
1351
+ localEnd,
1352
+ item.fontFamily
1353
+ );
1354
+ if (item.isHorizontal) {
1355
+ const spanWidth = item.x2 - item.x1;
1356
+ const subX1 = item.x1 + startFrac * spanWidth;
1357
+ const subX2 = item.x1 + endFrac * spanWidth;
1358
+ rawForSpan.push({
1359
+ x1: subX1 - padX,
1360
+ y1: item.y1 - padY,
1361
+ x2: subX2 + padX,
1362
+ y2: item.y2 + padY,
1363
+ replacement: r.replacement
1364
+ });
1365
+ } else {
1366
+ const [a, b, c, d, e, f] = item.transform;
1367
+ const scaleX = Math.hypot(a, b) || 1;
1368
+ const scaleY = Math.hypot(c, d) || 1;
1369
+ const ux = a / scaleX;
1370
+ const uy = b / scaleX;
1371
+ const vx = c / scaleY;
1372
+ const vy = d / scaleY;
1373
+ const d1 = startFrac * item.width;
1374
+ const d2 = endFrac * item.width;
1375
+ const asc = item.fontHeight * 1.12;
1376
+ const desc = -item.fontHeight * 0.34;
1377
+ const corners = [
1378
+ [e + ux * d1 + vx * desc, f + uy * d1 + vy * desc],
1379
+ [e + ux * d2 + vx * desc, f + uy * d2 + vy * desc],
1380
+ [e + ux * d1 + vx * asc, f + uy * d1 + vy * asc],
1381
+ [e + ux * d2 + vx * asc, f + uy * d2 + vy * asc]
1382
+ ];
1383
+ let bx1 = Number.POSITIVE_INFINITY;
1384
+ let by1 = Number.POSITIVE_INFINITY;
1385
+ let bx2 = Number.NEGATIVE_INFINITY;
1386
+ let by2 = Number.NEGATIVE_INFINITY;
1387
+ for (const [cx, cy] of corners) {
1388
+ if (cx < bx1) bx1 = cx;
1389
+ if (cy < by1) by1 = cy;
1390
+ if (cx > bx2) bx2 = cx;
1391
+ if (cy > by2) by2 = cy;
1392
+ }
1393
+ rawForSpan.push({
1394
+ x1: bx1 - padX,
1395
+ y1: by1 - padY,
1396
+ x2: bx2 + padX,
1397
+ y2: by2 + padY,
1398
+ replacement: r.replacement
1399
+ });
1400
+ }
1401
+ }
1402
+ boxes.push(...mergeLineBoxes(rawForSpan));
1403
+ }
1404
+ return boxes;
1405
+ }
1406
+ function drawRedactionOverlay(ctx, viewport, boxes, style) {
1407
+ const fillColor = style.fillColor ?? "#111111";
1408
+ const textColor = style.textColor ?? "#ffffff";
1409
+ const showLabels = style.showLabels !== false;
1410
+ for (const box of boxes) {
1411
+ const corners = [
1412
+ viewport.convertToViewportPoint(box.x1, box.y1),
1413
+ viewport.convertToViewportPoint(box.x2, box.y1),
1414
+ viewport.convertToViewportPoint(box.x1, box.y2),
1415
+ viewport.convertToViewportPoint(box.x2, box.y2)
1416
+ ];
1417
+ let minX = Number.POSITIVE_INFINITY;
1418
+ let minY = Number.POSITIVE_INFINITY;
1419
+ let maxX = Number.NEGATIVE_INFINITY;
1420
+ let maxY = Number.NEGATIVE_INFINITY;
1421
+ for (const pt of corners) {
1422
+ const px = Number(pt[0] ?? 0);
1423
+ const py = Number(pt[1] ?? 0);
1424
+ if (px < minX) minX = px;
1425
+ if (py < minY) minY = py;
1426
+ if (px > maxX) maxX = px;
1427
+ if (py > maxY) maxY = py;
1428
+ }
1429
+ const rx = minX;
1430
+ const ry = minY;
1431
+ const rw = maxX - minX;
1432
+ const rh = maxY - minY;
1433
+ if (rw < 1 || rh < 1) continue;
1434
+ ctx.save();
1435
+ ctx.fillStyle = fillColor;
1436
+ ctx.fillRect(rx, ry, rw, rh);
1437
+ if (showLabels && box.replacement && rw >= 24 && rh >= 10) {
1438
+ const pad = Math.min(4, rw * 0.08);
1439
+ const maxTextWidth = Math.max(4, rw - pad * 2);
1440
+ const fontSize = Math.max(8, Math.min(rh * 0.62, 22));
1441
+ ctx.beginPath();
1442
+ ctx.rect(rx, ry, rw, rh);
1443
+ ctx.clip();
1444
+ ctx.fillStyle = textColor;
1445
+ ctx.font = `600 ${fontSize.toFixed(1)}px sans-serif`;
1446
+ ctx.textAlign = "center";
1447
+ ctx.textBaseline = "middle";
1448
+ ctx.fillText(box.replacement, rx + rw / 2, ry + rh / 2 + fontSize * 0.04, maxTextWidth);
1449
+ }
1450
+ ctx.restore();
1451
+ }
1452
+ }
1453
+ async function inspectPdfDocument(bytes, pdfWorkerSrc) {
1454
+ const pdfjs = await loadPdfjs(pdfWorkerSrc);
1455
+ const loadingTask = pdfjs.getDocument({
1456
+ data: bytes.slice(),
1457
+ useSystemFonts: true,
1458
+ verbosity: 0
1459
+ });
1460
+ const doc = await loadingTask.promise;
1461
+ const meta = await doc.getMetadata().catch(() => ({ info: {}, metadata: null }));
1462
+ const metadata = collectPdfMetadataStrings(meta);
1463
+ const pages = [];
1464
+ const scannedPages = [];
1465
+ const warnings = [];
1466
+ const ops = pdfjs.OPS;
1467
+ const imageOpSet = /* @__PURE__ */ new Set([
1468
+ ops.paintImageXObject,
1469
+ ops.paintInlineImageXObject,
1470
+ ops.paintImageMaskXObject
1471
+ ]);
1472
+ for (let pageNumber = 1; pageNumber <= doc.numPages; pageNumber++) {
1473
+ const page = await doc.getPage(pageNumber);
1474
+ const textContent = await page.getTextContent();
1475
+ const { text, items } = buildPageTextAndMap(
1476
+ textContent.items,
1477
+ textContent.styles
1478
+ );
1479
+ const rawAnnotations = await page.getAnnotations().catch(() => []);
1480
+ const annotations = extractAnnotationTexts(rawAnnotations);
1481
+ let scanned = false;
1482
+ if (text.trim().length < 10) {
1483
+ const opList = await page.getOperatorList().catch(() => null);
1484
+ if (opList?.fnArray.some((fn) => imageOpSet.has(fn))) {
1485
+ scanned = true;
1486
+ scannedPages.push(pageNumber);
1487
+ }
1488
+ }
1489
+ pages.push({ pageNumber, text, items, annotations, scanned });
1490
+ }
1491
+ if (scannedPages.length > 0) {
1492
+ warnings.push(
1493
+ `PDF page(s) ${scannedPages.join(", ")} appear to be scanned images without a text layer and cannot be inspected without OCR.`
1494
+ );
1495
+ }
1496
+ return { pdfjs, loadingTask, doc, pages, metadata, scannedPages, warnings };
1497
+ }
1498
+ async function extractPdf(bytes, options) {
1499
+ const inspected = await inspectPdfDocument(bytes, options?.pdfWorkerSrc);
1500
+ try {
1501
+ const sections = inspected.pages.map((p) => {
1502
+ const annotText = p.annotations.map((a) => a.text).join("\n");
1503
+ const combined = annotText ? `${p.text}${p.text ? "\n" : ""}${annotText}` : p.text;
1504
+ return {
1505
+ id: `page-${p.pageNumber}`,
1506
+ label: `Sida ${p.pageNumber}`,
1507
+ text: combined,
1508
+ pageIndex: p.pageNumber - 1,
1509
+ scanned: p.scanned
1510
+ };
1511
+ });
1512
+ return {
1513
+ format: "pdf",
1514
+ mimeType: "application/pdf",
1515
+ text: sections.map((s) => s.text).filter((t) => t.length > 0).join("\n\n"),
1516
+ sections,
1517
+ metadata: inspected.metadata,
1518
+ warnings: inspected.warnings,
1519
+ scannedPages: inspected.scannedPages,
1520
+ totalPages: inspected.doc.numPages
1521
+ };
1522
+ } finally {
1523
+ await inspected.loadingTask.destroy();
1524
+ }
1525
+ }
1526
+ function countByLabel(redactions) {
1527
+ const counts = {};
1528
+ for (const r of redactions) {
1529
+ counts[r.label] = (counts[r.label] ?? 0) + 1;
1530
+ }
1531
+ return counts;
1532
+ }
1533
+ async function redactPdf(bytes, redactFn, options) {
1534
+ const inspected = await inspectPdfDocument(bytes, options?.pdfWorkerSrc);
1535
+ try {
1536
+ const pageOffsets = [];
1537
+ const textChunks = [];
1538
+ let cursor = 0;
1539
+ for (let i = 0; i < inspected.pages.length; i++) {
1540
+ const page = inspected.pages[i];
1541
+ if (!page) continue;
1542
+ const hasAnyContent = page.text.length > 0 || page.annotations.some((a) => a.text.length > 0);
1543
+ if (!hasAnyContent) {
1544
+ pageOffsets.push({ pageIndex: i, textStart: cursor, textEnd: cursor, annotRanges: [] });
1545
+ continue;
1546
+ }
1547
+ if (textChunks.length > 0) {
1548
+ textChunks.push("\n\n");
1549
+ cursor += 2;
1550
+ }
1551
+ const textStart = cursor;
1552
+ if (page.text.length > 0) {
1553
+ textChunks.push(page.text);
1554
+ cursor += page.text.length;
1555
+ }
1556
+ const textEnd = cursor;
1557
+ const annotRanges = [];
1558
+ let wroteInPage = page.text.length > 0;
1559
+ for (const annot of page.annotations) {
1560
+ if (!annot.text) continue;
1561
+ if (wroteInPage) {
1562
+ textChunks.push("\n");
1563
+ cursor += 1;
1564
+ }
1565
+ const start = cursor;
1566
+ textChunks.push(annot.text);
1567
+ cursor += annot.text.length;
1568
+ wroteInPage = true;
1569
+ annotRanges.push({ start, end: cursor, rect: annot.rect });
1570
+ }
1571
+ pageOffsets.push({ pageIndex: i, textStart, textEnd, annotRanges });
1572
+ }
1573
+ const combinedText = textChunks.join("");
1574
+ const result = await redactFn(combinedText);
1575
+ const srcDoc = await PDFDocument.load(bytes, {
1576
+ ignoreEncryption: true,
1577
+ updateMetadata: false
1578
+ });
1579
+ const outDoc = await PDFDocument.create();
1580
+ const style = options?.pdfStyle ?? {};
1581
+ const scale = style.scale ?? 2.5;
1582
+ let canvasProvider = options?.canvasProvider;
1583
+ const redactedPages = [];
1584
+ for (let i = 0; i < inspected.pages.length; i++) {
1585
+ const pageInfo = inspected.pages[i];
1586
+ const offsetInfo = pageOffsets[i];
1587
+ if (!pageInfo || !offsetInfo) continue;
1588
+ const localTextRedactions = [];
1589
+ const annotBoxes = [];
1590
+ let hasAnnotPii = false;
1591
+ for (const r of result.redactions) {
1592
+ if (r.end > offsetInfo.textStart && r.start < offsetInfo.textEnd) {
1593
+ localTextRedactions.push({
1594
+ start: Math.max(0, r.start - offsetInfo.textStart),
1595
+ end: Math.min(offsetInfo.textEnd - offsetInfo.textStart, r.end - offsetInfo.textStart),
1596
+ replacement: r.replacement
1597
+ });
1598
+ }
1599
+ for (const ar of offsetInfo.annotRanges) {
1600
+ if (r.end > ar.start && r.start < ar.end) {
1601
+ hasAnnotPii = true;
1602
+ if (ar.rect) {
1603
+ annotBoxes.push({
1604
+ x1: ar.rect[0],
1605
+ y1: ar.rect[1],
1606
+ x2: ar.rect[2],
1607
+ y2: ar.rect[3],
1608
+ replacement: r.replacement
1609
+ });
1610
+ }
1611
+ }
1612
+ }
1613
+ }
1614
+ const shouldBurn = options?.burnAllPdfPages === true || localTextRedactions.length > 0 || annotBoxes.length > 0 || hasAnnotPii;
1615
+ if (!shouldBurn) {
1616
+ const [copied] = await outDoc.copyPages(srcDoc, [i]);
1617
+ if (copied) {
1618
+ copied.node.delete(PDFName.of("Annots"));
1619
+ outDoc.addPage(copied);
1620
+ }
1621
+ continue;
1622
+ }
1623
+ redactedPages.push(pageInfo.pageNumber);
1624
+ if (!canvasProvider) {
1625
+ canvasProvider = await resolveDefaultCanvasProvider();
1626
+ }
1627
+ const pdfjsPage = await inspected.doc.getPage(pageInfo.pageNumber);
1628
+ const unscaledViewport = pdfjsPage.getViewport({ scale: 1 });
1629
+ const renderViewport = pdfjsPage.getViewport({ scale });
1630
+ const canvas = canvasProvider.createCanvas(
1631
+ Math.max(1, Math.ceil(renderViewport.width)),
1632
+ Math.max(1, Math.ceil(renderViewport.height))
1633
+ );
1634
+ const ctx = canvas.getContext("2d");
1635
+ if (!ctx) {
1636
+ throw new Error("Could not acquire 2D canvas context for PDF redaction.");
1637
+ }
1638
+ await pdfjsPage.render({
1639
+ canvasContext: ctx,
1640
+ viewport: renderViewport,
1641
+ canvas,
1642
+ intent: "print"
1643
+ }).promise;
1644
+ const textBoxes = computePageRedactionBoxes(pageInfo.items, localTextRedactions, ctx);
1645
+ const allBoxes = [...textBoxes, ...annotBoxes];
1646
+ drawRedactionOverlay(ctx, renderViewport, allBoxes, style);
1647
+ const pngBytes = await canvasProvider.toPngBytes(canvas);
1648
+ const pngImage = await outDoc.embedPng(pngBytes);
1649
+ const newPage = outDoc.addPage([unscaledViewport.width, unscaledViewport.height]);
1650
+ newPage.drawImage(pngImage, {
1651
+ x: 0,
1652
+ y: 0,
1653
+ width: unscaledViewport.width,
1654
+ height: unscaledViewport.height
1655
+ });
1656
+ }
1657
+ outDoc.setTitle("");
1658
+ outDoc.setAuthor("");
1659
+ outDoc.setSubject("");
1660
+ outDoc.setKeywords([]);
1661
+ outDoc.setCreator("Maskera");
1662
+ outDoc.setProducer("Maskera");
1663
+ const outBytes = new Uint8Array(await outDoc.save({ useObjectStreams: true }));
1664
+ const metadataCleared = Object.keys(inspected.metadata);
1665
+ const metadataValues = Object.values(inspected.metadata);
1666
+ return {
1667
+ bytes: outBytes,
1668
+ extractedText: combinedText,
1669
+ redactedText: result.text,
1670
+ totalRedactions: result.redactions.length,
1671
+ counts: countByLabel(result.redactions),
1672
+ redactions: result.redactions,
1673
+ map: result.map,
1674
+ metadataCleared,
1675
+ metadataValues,
1676
+ warnings: inspected.warnings,
1677
+ scannedPages: inspected.scannedPages,
1678
+ redactedPages,
1679
+ totalPages: inspected.doc.numPages
1680
+ };
1681
+ } finally {
1682
+ await inspected.loadingTask.destroy();
1683
+ }
1684
+ }
1685
+ function normalizeForLeakCheck(value) {
1686
+ return value.replace(/\s+/g, " ").trim().toLowerCase();
1687
+ }
1688
+ function collectNonTrivialSecrets(secrets) {
1689
+ const seen = /* @__PURE__ */ new Set();
1690
+ const out = [];
1691
+ for (const raw of secrets) {
1692
+ const norm = normalizeForLeakCheck(raw);
1693
+ if (norm.length < 3 || seen.has(norm)) continue;
1694
+ seen.add(norm);
1695
+ out.push(raw.trim());
1696
+ }
1697
+ return out;
1698
+ }
1699
+ async function verifyRedactedFile(bytes, format, originalSecrets, options) {
1700
+ const candidates = collectNonTrivialSecrets(originalSecrets);
1701
+ if (candidates.length === 0) {
1702
+ return { verified: true, leaks: [] };
1703
+ }
1704
+ let haystack = "";
1705
+ if (format === "text") {
1706
+ haystack = normalizeForLeakCheck(decodeUtf8(bytes));
1707
+ } else if (format === "docx" || format === "xlsx") {
1708
+ const archive = unzipSafely(bytes);
1709
+ const parts = [];
1710
+ for (const [name, data] of Object.entries(archive)) {
1711
+ if (!/\.(?:xml|rels)$/i.test(name)) continue;
1712
+ const xml = decodeUtf8(data);
1713
+ parts.push(unescapeXml(xml));
1714
+ parts.push(unescapeXml(xml.replace(/<[^>]+>/g, "")));
1715
+ }
1716
+ haystack = normalizeForLeakCheck(parts.join("\n"));
1717
+ } else if (format === "pdf") {
1718
+ const extracted = await extractPdf(bytes, { pdfWorkerSrc: options?.pdfWorkerSrc });
1719
+ const metaValues = Object.values(extracted.metadata).join("\n");
1720
+ const rawLatin = new TextDecoder("latin1").decode(bytes);
1721
+ haystack = normalizeForLeakCheck(`${extracted.text}
1722
+ ${metaValues}
1723
+ ${rawLatin}`);
1724
+ }
1725
+ const leaks = [];
1726
+ for (const secret of candidates) {
1727
+ if (haystack.includes(normalizeForLeakCheck(secret))) {
1728
+ leaks.push(secret);
1729
+ }
1730
+ }
1731
+ return {
1732
+ verified: leaks.length === 0,
1733
+ leaks
1734
+ };
1735
+ }
1736
+ function assertSizeLimit(bytes, maxBytes, fileName) {
1737
+ if (bytes.byteLength > maxBytes) {
1738
+ const label = fileName ? `"${fileName}"` : "File";
1739
+ throw new Error(`${label} is ${bytes.byteLength} bytes (max ${maxBytes} bytes).`);
1740
+ }
1741
+ }
1742
+ function countByLabel2(redactions) {
1743
+ const counts = {};
1744
+ for (const r of redactions) {
1745
+ counts[r.label] = (counts[r.label] ?? 0) + 1;
1746
+ }
1747
+ return counts;
1748
+ }
1749
+ async function extractFileText(bytes, options = {}) {
1750
+ const maxBytes = options.maxBytes ?? MAX_DEFAULT_FILE_BYTES;
1751
+ assertSizeLimit(bytes, maxBytes, options.fileName);
1752
+ const detected = detectFileFormat(bytes, options.fileName, options.mimeType);
1753
+ if (detected.format === "binary") {
1754
+ const label = options.fileName ? `"${options.fileName}"` : "File";
1755
+ throw new Error(
1756
+ `${label} appears to be an unsupported binary file (${detected.mimeType}). Supported formats: UTF-8 text, PDF, DOCX, XLSX.`
1757
+ );
1758
+ }
1759
+ if (detected.format === "text") {
1760
+ const text = decodeUtf8(bytes);
1761
+ return {
1762
+ format: "text",
1763
+ mimeType: detected.mimeType,
1764
+ text,
1765
+ sections: [{ id: "body", label: options.fileName ?? "text", text }],
1766
+ metadata: {},
1767
+ warnings: [],
1768
+ scannedPages: []
1769
+ };
1770
+ }
1771
+ if (detected.format === "docx") {
1772
+ return extractDocx(bytes);
83
1773
  }
84
- decide(id, decision) {
85
- this.expireStale();
86
- const record = this.records.get(id.trim());
87
- if (!record) return null;
88
- if (record.summary.status !== "pending") return { ...record.summary };
89
- record.summary.status = decision === "approve" ? "approved" : "declined";
90
- record.summary.decidedAt = (/* @__PURE__ */ new Date()).toISOString();
91
- if (decision === "decline") {
92
- record.execute = null;
93
- }
94
- this.notify();
95
- return { ...record.summary };
1774
+ if (detected.format === "xlsx") {
1775
+ return extractXlsx(bytes);
96
1776
  }
97
- async resume(id, owner) {
98
- this.expireStale();
99
- const record = this.records.get(id.trim());
100
- if (!record) return { status: "not_found" };
101
- if (owner !== void 0 && record.owner !== normalizeOwner(owner)) {
102
- return { status: "not_found" };
103
- }
104
- const { status } = record.summary;
105
- if (status === "pending" || status === "declined" || status === "expired") {
106
- return { status, summary: { ...record.summary } };
107
- }
108
- if (status === "completed" || !record.execute) {
109
- return { status: "expired", summary: { ...record.summary } };
110
- }
111
- const run = record.execute;
112
- record.execute = null;
113
- const result = await run();
114
- record.summary.status = "completed";
115
- this.notify();
116
- return { status: "completed", result, summary: { ...record.summary } };
1777
+ return extractPdf(bytes, { pdfWorkerSrc: options.pdfWorkerSrc });
1778
+ }
1779
+ async function redactFile(bytes, redactFn, options = {}) {
1780
+ const maxBytes = options.maxBytes ?? MAX_DEFAULT_FILE_BYTES;
1781
+ assertSizeLimit(bytes, maxBytes, options.fileName);
1782
+ const detected = detectFileFormat(bytes, options.fileName, options.mimeType);
1783
+ if (detected.format === "binary") {
1784
+ const label = options.fileName ? `"${options.fileName}"` : "File";
1785
+ throw new Error(
1786
+ `${label} appears to be an unsupported binary file (${detected.mimeType}). Supported formats: UTF-8 text, PDF, DOCX, XLSX.`
1787
+ );
117
1788
  }
118
- clearOwner(owner) {
119
- const resolvedOwner = normalizeOwner(owner);
120
- let changed = false;
121
- for (const [id, record] of this.records.entries()) {
122
- if (record.owner === resolvedOwner) {
123
- record.execute = null;
124
- this.records.delete(id);
125
- changed = true;
126
- }
127
- }
128
- if (changed) this.notify();
1789
+ const shouldVerify = options.verify !== false;
1790
+ if (detected.format === "text") {
1791
+ const extractedText = decodeUtf8(bytes);
1792
+ const result = await redactFn(extractedText);
1793
+ const outBytes = encodeUtf8(result.text);
1794
+ const secrets2 = result.redactions.map((r) => r.value);
1795
+ const verification2 = shouldVerify ? await verifyRedactedFile(outBytes, "text", secrets2) : { verified: true, leaks: [] };
1796
+ return {
1797
+ format: "text",
1798
+ mimeType: detected.mimeType,
1799
+ bytes: outBytes,
1800
+ extractedText,
1801
+ redactedText: result.text,
1802
+ totalRedactions: result.redactions.length,
1803
+ counts: countByLabel2(result.redactions),
1804
+ redactions: result.redactions,
1805
+ map: result.map,
1806
+ metadataCleared: [],
1807
+ warnings: [],
1808
+ scannedPages: [],
1809
+ verified: verification2.verified,
1810
+ verificationLeaks: verification2.leaks
1811
+ };
129
1812
  }
130
- clearAll() {
131
- this.records.clear();
132
- this.notify();
1813
+ if (detected.format === "docx") {
1814
+ const doc = await redactDocx(bytes, redactFn);
1815
+ const secrets2 = [...doc.redactions.map((r) => r.value), ...doc.metadataValues];
1816
+ const verification2 = shouldVerify ? await verifyRedactedFile(doc.bytes, "docx", secrets2) : { verified: true, leaks: [] };
1817
+ return {
1818
+ format: "docx",
1819
+ mimeType: detected.mimeType,
1820
+ bytes: doc.bytes,
1821
+ extractedText: doc.extractedText,
1822
+ redactedText: doc.redactedText,
1823
+ totalRedactions: doc.totalRedactions,
1824
+ counts: doc.counts,
1825
+ redactions: doc.redactions,
1826
+ map: doc.map,
1827
+ metadataCleared: doc.metadataCleared,
1828
+ warnings: doc.warnings,
1829
+ scannedPages: [],
1830
+ verified: verification2.verified,
1831
+ verificationLeaks: verification2.leaks
1832
+ };
133
1833
  }
134
- };
1834
+ if (detected.format === "xlsx") {
1835
+ const sheet = await redactXlsx(bytes, redactFn);
1836
+ const secrets2 = [...sheet.redactions.map((r) => r.value), ...sheet.metadataValues];
1837
+ const verification2 = shouldVerify ? await verifyRedactedFile(sheet.bytes, "xlsx", secrets2) : { verified: true, leaks: [] };
1838
+ return {
1839
+ format: "xlsx",
1840
+ mimeType: detected.mimeType,
1841
+ bytes: sheet.bytes,
1842
+ extractedText: sheet.extractedText,
1843
+ redactedText: sheet.redactedText,
1844
+ totalRedactions: sheet.totalRedactions,
1845
+ counts: sheet.counts,
1846
+ redactions: sheet.redactions,
1847
+ map: sheet.map,
1848
+ metadataCleared: sheet.metadataCleared,
1849
+ warnings: sheet.warnings,
1850
+ scannedPages: [],
1851
+ verified: verification2.verified,
1852
+ verificationLeaks: verification2.leaks
1853
+ };
1854
+ }
1855
+ const pdf = await redactPdf(bytes, redactFn, {
1856
+ pdfStyle: options.pdfStyle,
1857
+ canvasProvider: options.canvasProvider,
1858
+ pdfWorkerSrc: options.pdfWorkerSrc,
1859
+ burnAllPdfPages: options.burnAllPdfPages
1860
+ });
1861
+ const secrets = [...pdf.redactions.map((r) => r.value), ...pdf.metadataValues];
1862
+ const verification = shouldVerify ? await verifyRedactedFile(pdf.bytes, "pdf", secrets, {
1863
+ pdfWorkerSrc: options.pdfWorkerSrc
1864
+ }) : { verified: true, leaks: [] };
1865
+ return {
1866
+ format: "pdf",
1867
+ mimeType: detected.mimeType,
1868
+ bytes: pdf.bytes,
1869
+ extractedText: pdf.extractedText,
1870
+ redactedText: pdf.redactedText,
1871
+ totalRedactions: pdf.totalRedactions,
1872
+ counts: pdf.counts,
1873
+ redactions: pdf.redactions,
1874
+ map: pdf.map,
1875
+ metadataCleared: pdf.metadataCleared,
1876
+ warnings: pdf.warnings,
1877
+ scannedPages: pdf.scannedPages,
1878
+ redactedPages: pdf.redactedPages,
1879
+ totalPages: pdf.totalPages,
1880
+ verified: verification.verified,
1881
+ verificationLeaks: verification.leaks
1882
+ };
1883
+ }
135
1884
  var WORD_CHAR = /[\p{L}\p{N}_]/u;
136
1885
  var DEFAULT_MAX_CACHE_ENTRIES = 512;
137
1886
  var MAX_CUSTOM_DETECTOR_CACHE = 64;
@@ -207,6 +1956,7 @@ function normalizeMixedScriptHomoglyphs(text) {
207
1956
  });
208
1957
  return { text: normalized, changed };
209
1958
  }
1959
+ var COMPOUND_WINDOW_RADIUS = 120;
210
1960
  async function detectHyphenatedCompoundPrefixes(text, ner, detectors, profile, existing) {
211
1961
  const candidates = [];
212
1962
  SWEDISH_HYPHEN_COMPOUND_RE.lastIndex = 0;
@@ -221,28 +1971,47 @@ async function detectHyphenatedCompoundPrefixes(text, ner, detectors, profile, e
221
1971
  }
222
1972
  }
223
1973
  if (candidates.length === 0) return [];
224
- const chars = text.split("");
1974
+ const windows = [];
225
1975
  for (const c of candidates) {
226
- chars[c.hyphenIndex] = " ";
1976
+ let winStart = Math.max(0, c.prefixStart - COMPOUND_WINDOW_RADIUS);
1977
+ while (winStart > 0 && WORD_CHAR.test(text[winStart - 1] ?? "")) winStart--;
1978
+ let winEnd = Math.min(text.length, c.hyphenIndex + 1 + COMPOUND_WINDOW_RADIUS);
1979
+ while (winEnd < text.length && WORD_CHAR.test(text[winEnd] ?? "")) winEnd++;
1980
+ const prev = windows[windows.length - 1];
1981
+ if (prev && winStart <= prev.end + 40) {
1982
+ prev.end = Math.max(prev.end, winEnd);
1983
+ prev.items.push(c);
1984
+ } else {
1985
+ windows.push({ start: winStart, end: winEnd, items: [c] });
1986
+ }
227
1987
  }
228
- const probeText = chars.join("");
229
- const probeRes = await redactWithNer(probeText, {
230
- recognizer: ner,
231
- detectors: [...detectors],
232
- profile
233
- });
234
1988
  const extra = [];
235
- for (const r of probeRes.redactions) {
236
- if (!COMPOUND_NER_LABELS.has(r.label)) continue;
237
- for (const c of candidates) {
238
- if (r.start <= c.prefixStart && r.end >= c.prefixEnd && r.end <= c.hyphenIndex) {
239
- extra.push({
240
- start: c.prefixStart,
241
- end: c.prefixEnd,
242
- label: r.label,
243
- value: text.slice(c.prefixStart, c.prefixEnd)
244
- });
245
- break;
1989
+ for (const win of windows) {
1990
+ const slice = text.slice(win.start, win.end);
1991
+ const chars = slice.split("");
1992
+ for (const c of win.items) {
1993
+ chars[c.hyphenIndex - win.start] = " ";
1994
+ }
1995
+ const probeText = chars.join("");
1996
+ const probeRes = await redactWithNer(probeText, {
1997
+ recognizer: ner,
1998
+ detectors: [...detectors],
1999
+ profile
2000
+ });
2001
+ for (const r of probeRes.redactions) {
2002
+ if (!COMPOUND_NER_LABELS.has(r.label)) continue;
2003
+ const absStart = win.start + r.start;
2004
+ const absEnd = win.start + r.end;
2005
+ for (const c of win.items) {
2006
+ if (absStart <= c.prefixStart && absEnd >= c.prefixEnd && absEnd <= c.hyphenIndex) {
2007
+ extra.push({
2008
+ start: c.prefixStart,
2009
+ end: c.prefixEnd,
2010
+ label: r.label,
2011
+ value: text.slice(c.prefixStart, c.prefixEnd)
2012
+ });
2013
+ break;
2014
+ }
246
2015
  }
247
2016
  }
248
2017
  }
@@ -298,47 +2067,54 @@ function createMaskeraEngine(options = {}) {
298
2067
  const model = options.nerOptions?.model ?? MASKERA_SV_NER_MODEL;
299
2068
  const revision = options.nerOptions?.revision ?? (model === MASKERA_SV_NER_MODEL ? MASKERA_SV_NER_REVISION : void 0);
300
2069
  const maxCacheEntries = Math.max(0, options.maxCacheEntries ?? DEFAULT_MAX_CACHE_ENTRIES);
301
- let recognizer = options.recognizer ?? null;
302
- let nerLoaded = false;
303
- let nerError = null;
304
- let warmupStarted = false;
2070
+ const localPath = options.nerOptions?.localModelPath;
2071
+ const hasLocalQ8 = typeof localPath === "string" && existsSync(join(localPath, model, "onnx", "model_quantized.onnx"));
2072
+ const dtype = options.nerOptions?.dtype ?? (localPath && !hasLocalQ8 ? "q4" : "q8");
2073
+ let lifecycle = { phase: "idle", recognizer: options.recognizer ?? null };
2074
+ let loadAttempt = 0;
305
2075
  const spanCache = /* @__PURE__ */ new Map();
306
2076
  const customDetectorCache = /* @__PURE__ */ new Map();
307
2077
  let cacheHits = 0;
308
2078
  let cacheMisses = 0;
309
- function getRecognizer() {
310
- if (!recognizer) {
311
- const dtype = options.nerOptions?.dtype ?? (options.nerOptions?.localModelPath ? "q4" : "q8");
312
- const loadStartedAt = Date.now();
313
- options.onModelStatus?.({ phase: "loading", model, dtype });
314
- recognizer = createNerRecognizer({
315
- ...options.nerOptions,
316
- model,
317
- revision,
318
- dtype
319
- });
320
- void recognizer.ready.then(
321
- () => {
322
- nerLoaded = true;
323
- nerError = null;
2079
+ function ensureRecognizerLoading() {
2080
+ if (lifecycle.phase === "loading" || lifecycle.phase === "ready") {
2081
+ return lifecycle.recognizer;
2082
+ }
2083
+ const recognizer = lifecycle.recognizer ?? createNerRecognizer({
2084
+ ...options.nerOptions,
2085
+ model,
2086
+ revision,
2087
+ dtype
2088
+ });
2089
+ loadAttempt += 1;
2090
+ const attempt = loadAttempt;
2091
+ const startedAt = Date.now();
2092
+ lifecycle = { phase: "loading", recognizer, startedAt, attempt };
2093
+ options.onModelStatus?.({ phase: "loading", model, dtype });
2094
+ void recognizer.ready.then(
2095
+ () => {
2096
+ if (lifecycle.phase === "loading" && lifecycle.attempt === attempt) {
2097
+ lifecycle = { phase: "ready", recognizer };
324
2098
  options.onModelStatus?.({
325
2099
  phase: "ready",
326
2100
  model,
327
- elapsedMs: Date.now() - loadStartedAt
2101
+ elapsedMs: Date.now() - startedAt
328
2102
  });
329
- },
330
- (err) => {
331
- const message = err instanceof Error ? err.message : String(err);
332
- nerError = message;
2103
+ }
2104
+ },
2105
+ (err) => {
2106
+ const message = err instanceof Error ? err.message : String(err);
2107
+ if (lifecycle.phase === "loading" && lifecycle.attempt === attempt) {
2108
+ lifecycle = { phase: "failed", recognizer, error: message };
333
2109
  options.onModelStatus?.({
334
2110
  phase: "error",
335
2111
  model,
336
- elapsedMs: Date.now() - loadStartedAt,
2112
+ elapsedMs: Date.now() - startedAt,
337
2113
  error: message
338
2114
  });
339
2115
  }
340
- );
341
- }
2116
+ }
2117
+ );
342
2118
  return recognizer;
343
2119
  }
344
2120
  function getCustomDetector(rawTerms) {
@@ -365,19 +2141,9 @@ function createMaskeraEngine(options = {}) {
365
2141
  }
366
2142
  return {
367
2143
  warmup() {
368
- if (defaultMode !== "auto" || warmupStarted || nerLoaded) return;
369
- warmupStarted = true;
370
- const ner = getRecognizer();
371
- void ner.ready.then(
372
- () => {
373
- nerLoaded = true;
374
- nerError = null;
375
- },
376
- (err) => {
377
- warmupStarted = false;
378
- nerError = err instanceof Error ? err.message : String(err);
379
- }
380
- );
2144
+ if (defaultMode !== "auto") return;
2145
+ if (lifecycle.phase === "loading" || lifecycle.phase === "ready") return;
2146
+ ensureRecognizerLoading();
381
2147
  },
382
2148
  clearCache() {
383
2149
  spanCache.clear();
@@ -450,8 +2216,8 @@ function createMaskeraEngine(options = {}) {
450
2216
  modeUsed: "rules"
451
2217
  };
452
2218
  }
2219
+ const ner = ensureRecognizerLoading();
453
2220
  try {
454
- const ner = getRecognizer();
455
2221
  const canonical = canonicalize(text);
456
2222
  const homoglyph = normalizeMixedScriptHomoglyphs(canonical.text);
457
2223
  const isIdentity = canonical.identity && !homoglyph.changed;
@@ -482,8 +2248,13 @@ function createMaskeraEngine(options = {}) {
482
2248
  return end > start ? [{ start, end, label: d.label, value: text.slice(start, end) }] : [];
483
2249
  })
484
2250
  );
485
- nerLoaded = true;
486
- nerError = null;
2251
+ if (lifecycle.phase === "loading") {
2252
+ const elapsedMs = Date.now() - lifecycle.startedAt;
2253
+ lifecycle = { phase: "ready", recognizer: ner };
2254
+ options.onModelStatus?.({ phase: "ready", model, elapsedMs });
2255
+ } else if (lifecycle.phase !== "ready") {
2256
+ lifecycle = { phase: "ready", recognizer: ner };
2257
+ }
487
2258
  if (cacheKey) {
488
2259
  if (spanCache.size >= maxCacheEntries) {
489
2260
  const oldest = spanCache.keys().next().value;
@@ -501,7 +2272,13 @@ function createMaskeraEngine(options = {}) {
501
2272
  return { result, modeUsed: "hybrid" };
502
2273
  } catch (err) {
503
2274
  const message = err instanceof Error ? err.message : String(err);
504
- nerError = message;
2275
+ if (lifecycle.phase === "loading") {
2276
+ const elapsedMs = Date.now() - lifecycle.startedAt;
2277
+ lifecycle = { phase: "failed", recognizer: ner, error: message };
2278
+ options.onModelStatus?.({ phase: "error", model, elapsedMs, error: message });
2279
+ } else {
2280
+ lifecycle = { phase: "failed", recognizer: ner, error: message };
2281
+ }
505
2282
  throw new Error(
506
2283
  `Hybrid NER failed to run (${message}). Pass mode="rules" explicitly if you only want deterministic structured redaction.`
507
2284
  );
@@ -512,8 +2289,9 @@ function createMaskeraEngine(options = {}) {
512
2289
  defaultMode,
513
2290
  model,
514
2291
  revision: revision ?? "local",
515
- nerLoaded,
516
- nerError,
2292
+ nerPhase: lifecycle.phase,
2293
+ nerLoaded: lifecycle.phase === "ready",
2294
+ nerError: lifecycle.phase === "failed" ? lifecycle.error : null,
517
2295
  cacheSize: spanCache.size,
518
2296
  cacheHits,
519
2297
  cacheMisses
@@ -528,35 +2306,44 @@ function downloadSize(dtype) {
528
2306
  }
529
2307
  function createModelProgressLogger(write = (line) => process.stderr.write(`${line}
530
2308
  `), delayMs = 350) {
531
- let timer = null;
532
- let announcedLoading = false;
2309
+ let state = { tag: "quiet" };
533
2310
  return (event) => {
534
- if (event.phase === "loading") {
535
- if (timer) clearTimeout(timer);
536
- announcedLoading = false;
537
- timer = setTimeout(() => {
538
- announcedLoading = true;
539
- write(
540
- `[maskera] Loading Swedish ONNX model (${event.model}${downloadSize(event.dtype)}, cached locally)...`
541
- );
542
- }, delayMs);
543
- timer.unref?.();
544
- return;
545
- }
546
- if (timer) {
547
- clearTimeout(timer);
548
- timer = null;
549
- }
550
- if (event.phase === "ready" && announcedLoading) {
551
- write(`[maskera] Swedish ONNX model ready (${event.elapsedMs ?? 0}ms).`);
552
- announcedLoading = false;
553
- } else if (event.phase === "error" && announcedLoading) {
554
- write(`[maskera] Swedish ONNX model load failed: ${event.error ?? "unknown error"}`);
555
- announcedLoading = false;
2311
+ switch (event.phase) {
2312
+ case "loading": {
2313
+ if (state.tag === "delayed") clearTimeout(state.timer);
2314
+ const timer = setTimeout(() => {
2315
+ state = { tag: "announced" };
2316
+ write(
2317
+ `[maskera] Loading Swedish ONNX model (${event.model}${downloadSize(event.dtype)}, cached locally)...`
2318
+ );
2319
+ }, delayMs);
2320
+ timer.unref?.();
2321
+ state = { tag: "delayed", timer };
2322
+ return;
2323
+ }
2324
+ case "ready": {
2325
+ if (state.tag === "delayed") {
2326
+ clearTimeout(state.timer);
2327
+ } else if (state.tag === "announced") {
2328
+ write(`[maskera] Swedish ONNX model ready (${event.elapsedMs ?? 0}ms).`);
2329
+ }
2330
+ state = { tag: "quiet" };
2331
+ return;
2332
+ }
2333
+ case "error": {
2334
+ if (state.tag === "delayed") {
2335
+ clearTimeout(state.timer);
2336
+ } else if (state.tag === "announced") {
2337
+ write(`[maskera] Swedish ONNX model load failed: ${event.error ?? "unknown error"}`);
2338
+ }
2339
+ state = { tag: "quiet" };
2340
+ return;
2341
+ }
556
2342
  }
557
2343
  };
558
2344
  }
559
2345
  var MAX_FILE_BYTES = 2 * 1024 * 1024;
2346
+ var MAX_DOCUMENT_BYTES = MAX_DEFAULT_FILE_BYTES;
560
2347
  var MAX_SYMLINK_HOPS = 40;
561
2348
  var DEFAULT_LIST_MAX_ENTRIES = 200;
562
2349
  var HARD_LIST_MAX_ENTRIES = 1e3;
@@ -565,7 +2352,7 @@ var HARD_LIST_MAX_DEPTH = 12;
565
2352
  var DEFAULT_SEARCH_MAX_MATCHES = 50;
566
2353
  var HARD_SEARCH_MAX_MATCHES = 200;
567
2354
  var DEFAULT_SEARCH_MAX_FILES = 500;
568
- var UTF8_DECODER = new TextDecoder("utf-8", { fatal: true });
2355
+ var UTF8_DECODER3 = new TextDecoder("utf-8", { fatal: true });
569
2356
  var SKIP_DIRS = /* @__PURE__ */ new Set([".git", "node_modules", "dist", "dist-ssr", ".next", ".turbo"]);
570
2357
  function isWithinRoot(root, target) {
571
2358
  const rel = relative(root, target);
@@ -709,84 +2496,144 @@ function createFileGuard(roots = [process.cwd()]) {
709
2496
  await visit(baseDir, 0);
710
2497
  return { files, truncated };
711
2498
  }
2499
+ async function resolveReadableFile(filePath, maxBytes) {
2500
+ const rootsList = await getCanonicalRoots();
2501
+ const candidate = resolveAgainstBase(filePath);
2502
+ const { ancestor, tail } = await resolveExistingAncestor(candidate);
2503
+ const candidateReal = tail ? resolve(ancestor, tail) : ancestor;
2504
+ if (!rootsList.some((root) => isWithinRoot(root, candidateReal))) {
2505
+ throw new Error(
2506
+ `Access denied: "${filePath}" is outside allowed workspace roots (${rootsList.join(", ")}).`
2507
+ );
2508
+ }
2509
+ const real = await realpath(candidate).catch(() => {
2510
+ throw new Error(`File not found: "${filePath}".`);
2511
+ });
2512
+ if (!rootsList.some((root) => isWithinRoot(root, real))) {
2513
+ throw new Error(
2514
+ `Access denied: "${filePath}" is outside allowed workspace roots (${rootsList.join(", ")}).`
2515
+ );
2516
+ }
2517
+ const info = await stat(real);
2518
+ if (!info.isFile()) {
2519
+ throw new Error(`"${filePath}" is not a regular file.`);
2520
+ }
2521
+ if (info.size > maxBytes) {
2522
+ throw new Error(
2523
+ `File "${filePath}" is ${info.size} bytes (max ${maxBytes} bytes for local redaction).`
2524
+ );
2525
+ }
2526
+ const buffer = await readFile(real);
2527
+ return { resolvedPath: real, buffer };
2528
+ }
2529
+ async function writeCheckedBytes(filePath, data, options) {
2530
+ const rootsList = await getCanonicalRoots();
2531
+ const candidate = resolveAgainstBase(filePath);
2532
+ const targetReal = await resolveCanonicalTarget(candidate);
2533
+ if (!rootsList.some((root) => isWithinRoot(root, targetReal))) {
2534
+ throw new Error(
2535
+ `Access denied: "${filePath}" is outside allowed workspace roots (${rootsList.join(", ")}).`
2536
+ );
2537
+ }
2538
+ const bytes = typeof data === "string" ? Buffer.byteLength(data, "utf8") : data.byteLength;
2539
+ if (bytes > options.maxBytes) {
2540
+ throw new Error(`Output exceeds max allowed size (${options.maxBytes} bytes).`);
2541
+ }
2542
+ await mkdir(dirname(targetReal), { recursive: true });
2543
+ const parentReal = await realpath(dirname(targetReal));
2544
+ if (!rootsList.some((root) => isWithinRoot(root, parentReal))) {
2545
+ throw new Error(
2546
+ `Access denied: "${filePath}" is outside allowed workspace roots (${rootsList.join(", ")}).`
2547
+ );
2548
+ }
2549
+ await writeFile(targetReal, data, {
2550
+ ...options.encoding ? { encoding: options.encoding } : {},
2551
+ flag: options.overwrite ? "w" : "wx",
2552
+ mode: 384
2553
+ }).catch((err) => {
2554
+ if (err.code === "EEXIST") {
2555
+ throw new Error(`File already exists: "${filePath}". Pass overwrite=true to replace it.`);
2556
+ }
2557
+ throw err;
2558
+ });
2559
+ return { resolvedPath: targetReal, bytes };
2560
+ }
712
2561
  return {
713
2562
  allowedRoots: rawRoots.map((r) => resolve(r)),
714
2563
  async readText(filePath) {
715
- const rootsList = await getCanonicalRoots();
716
- const candidate = resolveAgainstBase(filePath);
717
- const { ancestor, tail } = await resolveExistingAncestor(candidate);
718
- const candidateReal = tail ? resolve(ancestor, tail) : ancestor;
719
- if (!rootsList.some((root) => isWithinRoot(root, candidateReal))) {
720
- throw new Error(
721
- `Access denied: "${filePath}" is outside allowed workspace roots (${rootsList.join(", ")}).`
722
- );
723
- }
724
- const real = await realpath(candidate).catch(() => {
725
- throw new Error(`File not found: "${filePath}".`);
726
- });
727
- if (!rootsList.some((root) => isWithinRoot(root, real))) {
728
- throw new Error(
729
- `Access denied: "${filePath}" is outside allowed workspace roots (${rootsList.join(", ")}).`
730
- );
731
- }
732
- const info = await stat(real);
733
- if (!info.isFile()) {
734
- throw new Error(`"${filePath}" is not a regular file.`);
735
- }
736
- if (info.size > MAX_FILE_BYTES) {
737
- throw new Error(
738
- `File "${filePath}" is ${info.size} bytes (max ${MAX_FILE_BYTES} bytes for local redaction).`
739
- );
740
- }
741
- const buffer = await readFile(real);
2564
+ const { resolvedPath, buffer } = await resolveReadableFile(filePath, MAX_FILE_BYTES);
742
2565
  if (buffer.includes(0)) {
743
2566
  throw new Error(`"${filePath}" appears to be a binary file; only UTF-8 text is supported.`);
744
2567
  }
745
2568
  let content;
746
2569
  try {
747
- content = UTF8_DECODER.decode(buffer);
2570
+ content = UTF8_DECODER3.decode(buffer);
748
2571
  } catch {
749
2572
  throw new Error(
750
2573
  `"${filePath}" is not valid UTF-8 text; convert it to UTF-8 before redacting.`
751
2574
  );
752
2575
  }
753
2576
  return {
754
- resolvedPath: real,
2577
+ resolvedPath,
755
2578
  content,
756
2579
  bytes: buffer.byteLength
757
2580
  };
758
2581
  },
759
- async writeText(filePath, content, options = {}) {
760
- const rootsList = await getCanonicalRoots();
761
- const candidate = resolveAgainstBase(filePath);
762
- const targetReal = await resolveCanonicalTarget(candidate);
763
- if (!rootsList.some((root) => isWithinRoot(root, targetReal))) {
2582
+ async readDocument(filePath) {
2583
+ const { resolvedPath, buffer } = await resolveReadableFile(filePath, MAX_DOCUMENT_BYTES);
2584
+ const bytes = new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
2585
+ const detected = detectFileFormat(bytes, resolvedPath);
2586
+ if (detected.format === "text" && buffer.byteLength > MAX_FILE_BYTES) {
764
2587
  throw new Error(
765
- `Access denied: "${filePath}" is outside allowed workspace roots (${rootsList.join(", ")}).`
2588
+ `File "${filePath}" is ${buffer.byteLength} bytes (max ${MAX_FILE_BYTES} bytes for local text redaction).`
766
2589
  );
767
2590
  }
768
- const bytes = Buffer.byteLength(content, "utf8");
769
- if (bytes > MAX_FILE_BYTES) {
770
- throw new Error(`Output exceeds max allowed size (${MAX_FILE_BYTES} bytes).`);
771
- }
772
- await mkdir(dirname(targetReal), { recursive: true });
773
- const parentReal = await realpath(dirname(targetReal));
774
- if (!rootsList.some((root) => isWithinRoot(root, parentReal))) {
2591
+ if (detected.format === "binary") {
2592
+ if (!buffer.includes(0)) {
2593
+ throw new Error(
2594
+ `"${filePath}" is not valid UTF-8 text; convert it to UTF-8 before redacting.`
2595
+ );
2596
+ }
775
2597
  throw new Error(
776
- `Access denied: "${filePath}" is outside allowed workspace roots (${rootsList.join(", ")}).`
2598
+ `"${filePath}" appears to be an unsupported binary file (${detected.mimeType}); supported formats are UTF-8 text, PDF, DOCX, and XLSX.`
777
2599
  );
778
2600
  }
779
- await writeFile(targetReal, content, {
780
- encoding: "utf8",
781
- flag: options.overwrite ? "w" : "wx",
782
- mode: 384
783
- }).catch((err) => {
784
- if (err.code === "EEXIST") {
785
- throw new Error(`File already exists: "${filePath}". Pass overwrite=true to replace it.`);
786
- }
787
- throw err;
2601
+ const extracted = await extractFileText(bytes, {
2602
+ fileName: resolvedPath,
2603
+ maxBytes: MAX_DOCUMENT_BYTES
2604
+ });
2605
+ return {
2606
+ resolvedPath,
2607
+ content: extracted.text,
2608
+ bytes: buffer.byteLength,
2609
+ format: extracted.format,
2610
+ mimeType: extracted.mimeType,
2611
+ metadataFields: Object.keys(extracted.metadata),
2612
+ warnings: extracted.warnings,
2613
+ scannedPages: extracted.scannedPages,
2614
+ totalPages: extracted.totalPages
2615
+ };
2616
+ },
2617
+ async readBytes(filePath, options = {}) {
2618
+ const maxBytes = options.maxBytes ?? MAX_DOCUMENT_BYTES;
2619
+ const { resolvedPath, buffer } = await resolveReadableFile(filePath, maxBytes);
2620
+ return {
2621
+ resolvedPath,
2622
+ bytes: new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength)
2623
+ };
2624
+ },
2625
+ async writeText(filePath, content, options = {}) {
2626
+ return writeCheckedBytes(filePath, content, {
2627
+ overwrite: options.overwrite,
2628
+ maxBytes: MAX_FILE_BYTES,
2629
+ encoding: "utf8"
2630
+ });
2631
+ },
2632
+ async writeBytes(filePath, bytes, options = {}) {
2633
+ return writeCheckedBytes(filePath, bytes, {
2634
+ overwrite: options.overwrite,
2635
+ maxBytes: options.maxBytes ?? MAX_DOCUMENT_BYTES
788
2636
  });
789
- return { resolvedPath: targetReal, bytes };
790
2637
  },
791
2638
  async listFiles(dirPath, options = {}) {
792
2639
  const { rootsList, baseDir } = await resolveAllowedDirectory(dirPath);
@@ -832,19 +2679,36 @@ function createFileGuard(roots = [process.cwd()]) {
832
2679
  let scannedFiles = 0;
833
2680
  let truncated = walkTruncated;
834
2681
  for (const file of files) {
835
- if (file.bytes > MAX_FILE_BYTES) continue;
2682
+ if (file.bytes > MAX_DOCUMENT_BYTES) continue;
836
2683
  let buffer;
837
2684
  try {
838
2685
  buffer = await readFile(file.realPath);
839
2686
  } catch {
840
2687
  continue;
841
2688
  }
842
- if (buffer.includes(0)) continue;
843
2689
  let text;
844
- try {
845
- text = UTF8_DECODER.decode(buffer);
846
- } catch {
847
- continue;
2690
+ if (!buffer.includes(0)) {
2691
+ if (file.bytes > MAX_FILE_BYTES) continue;
2692
+ try {
2693
+ text = UTF8_DECODER3.decode(buffer);
2694
+ } catch {
2695
+ continue;
2696
+ }
2697
+ } else {
2698
+ const bytes = new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
2699
+ const detected = detectFileFormat(bytes, file.realPath);
2700
+ if (detected.format !== "pdf" && detected.format !== "docx" && detected.format !== "xlsx") {
2701
+ continue;
2702
+ }
2703
+ try {
2704
+ const extracted = await extractFileText(bytes, {
2705
+ fileName: file.realPath,
2706
+ maxBytes: MAX_DOCUMENT_BYTES
2707
+ });
2708
+ text = extracted.text;
2709
+ } catch {
2710
+ continue;
2711
+ }
848
2712
  }
849
2713
  scannedFiles += 1;
850
2714
  const lines = text.split(/\r?\n/);
@@ -1109,11 +2973,13 @@ var SessionVault = class {
1109
2973
  redacted: originalInput,
1110
2974
  counts: {},
1111
2975
  totalRedactions: 0,
1112
- map: {}
2976
+ map: {},
2977
+ redactions: []
1113
2978
  };
1114
2979
  }
1115
2980
  const counts = {};
1116
2981
  const localMap = {};
2982
+ const appliedRedactions = [];
1117
2983
  const existingTokens = originalInput.includes("[") ? new Set(originalInput.match(EXISTING_TOKEN_RE) ?? []) : null;
1118
2984
  let redacted = "";
1119
2985
  let cursor = 0;
@@ -1153,6 +3019,7 @@ var SessionVault = class {
1153
3019
  }
1154
3020
  localMap[token] = r.value;
1155
3021
  counts[r.label] = (counts[r.label] ?? 0) + 1;
3022
+ appliedRedactions.push({ ...r, replacement: token });
1156
3023
  redacted += originalInput.slice(cursor, r.start) + token;
1157
3024
  cursor = r.end;
1158
3025
  }
@@ -1162,7 +3029,8 @@ var SessionVault = class {
1162
3029
  redacted,
1163
3030
  counts,
1164
3031
  totalRedactions: result.redactions.length,
1165
- map: localMap
3032
+ map: localMap,
3033
+ redactions: appliedRedactions
1166
3034
  };
1167
3035
  }
1168
3036
  restore(text, options) {
@@ -1380,9 +3248,9 @@ var TOOLS = [
1380
3248
  },
1381
3249
  {
1382
3250
  name: "maskera_read_file",
1383
- 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.",
3251
+ description: "Read a local UTF-8 text, PDF, DOCX, or XLSX 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.",
1384
3252
  annotations: {
1385
- title: "Read local file with PII redaction",
3253
+ title: "Read local file or document with PII redaction",
1386
3254
  readOnlyHint: true,
1387
3255
  destructiveHint: false,
1388
3256
  idempotentHint: false,
@@ -1393,7 +3261,7 @@ var TOOLS = [
1393
3261
  properties: {
1394
3262
  path: {
1395
3263
  type: "string",
1396
- description: "Path to a UTF-8 file inside the allowed workspace roots."
3264
+ description: "Path to a UTF-8 text, PDF, DOCX, or XLSX file inside allowed workspace roots."
1397
3265
  },
1398
3266
  session_id: {
1399
3267
  type: "string",
@@ -1422,15 +3290,102 @@ var TOOLS = [
1422
3290
  properties: {
1423
3291
  path: { type: "string" },
1424
3292
  bytes: { type: "integer" },
3293
+ format: { type: "string", enum: ["text", "pdf", "docx", "xlsx"] },
1425
3294
  redacted: { type: "string" },
1426
3295
  session_id: { type: "string" },
1427
3296
  counts: COUNTS_SCHEMA,
1428
3297
  total_redactions: { type: "integer" },
1429
- mode: { type: "string", enum: ["hybrid", "rules"] }
3298
+ mode: { type: "string", enum: ["hybrid", "rules"] },
3299
+ total_pages: { type: "integer" },
3300
+ scanned_pages: { type: "array", items: { type: "integer" } },
3301
+ metadata_fields: { type: "array", items: { type: "string" } },
3302
+ warnings: { type: "array", items: { type: "string" } }
1430
3303
  },
1431
3304
  required: ["path", "bytes", "redacted", "session_id", "counts", "total_redactions", "mode"]
1432
3305
  }
1433
3306
  },
3307
+ {
3308
+ name: "maskera_redact_file",
3309
+ description: "Redact Swedish PII inside a local PDF, DOCX, XLSX, or UTF-8 text file and write a verified clean file directly to disk without exposing raw PII to the model. For PDFs, affected pages are rasterized and burned so zero raw text survives in the PDF stream; metadata is stripped.",
3310
+ annotations: {
3311
+ title: "Redact local PDF/DOCX/XLSX/text file to disk",
3312
+ readOnlyHint: false,
3313
+ destructiveHint: false,
3314
+ idempotentHint: false,
3315
+ openWorldHint: false
3316
+ },
3317
+ inputSchema: {
3318
+ type: "object",
3319
+ properties: {
3320
+ input_path: {
3321
+ type: "string",
3322
+ description: "Source file path (PDF, DOCX, XLSX, or UTF-8 text) inside allowed roots."
3323
+ },
3324
+ output_path: {
3325
+ type: "string",
3326
+ description: "Destination path for the redacted file inside allowed roots."
3327
+ },
3328
+ session_id: {
3329
+ type: "string",
3330
+ description: "Optional session ID to share placeholder numbering across files."
3331
+ },
3332
+ overwrite: {
3333
+ type: "boolean",
3334
+ description: "Allow overwriting an existing output file. Default false."
3335
+ },
3336
+ show_labels: {
3337
+ type: "boolean",
3338
+ description: "Draw placeholder labels (e.g. [NAMN_1]) inside burned PDF boxes. Default true."
3339
+ },
3340
+ mode: {
3341
+ type: "string",
3342
+ enum: ["auto", "rules"],
3343
+ description: '"auto" (default) runs hybrid NER + rules; "rules" runs rules only.'
3344
+ },
3345
+ profile: {
3346
+ type: "string",
3347
+ enum: ["general", "clinical"],
3348
+ description: 'Optional built-in precision profile (default "general").'
3349
+ },
3350
+ custom_terms: {
3351
+ type: "array",
3352
+ items: { type: "string" },
3353
+ description: "Optional extra protected words (client names, project codenames)."
3354
+ }
3355
+ },
3356
+ required: ["input_path", "output_path"]
3357
+ },
3358
+ outputSchema: {
3359
+ type: "object",
3360
+ properties: {
3361
+ input_path: { type: "string" },
3362
+ output_path: { type: "string" },
3363
+ format: { type: "string", enum: ["text", "pdf", "docx", "xlsx"] },
3364
+ bytes: { type: "integer" },
3365
+ session_id: { type: "string" },
3366
+ counts: COUNTS_SCHEMA,
3367
+ total_redactions: { type: "integer" },
3368
+ mode: { type: "string", enum: ["hybrid", "rules"] },
3369
+ verified: { type: "boolean" },
3370
+ metadata_cleared: { type: "array", items: { type: "string" } },
3371
+ redacted_pages: { type: "array", items: { type: "integer" } },
3372
+ total_pages: { type: "integer" },
3373
+ scanned_pages: { type: "array", items: { type: "integer" } },
3374
+ warnings: { type: "array", items: { type: "string" } }
3375
+ },
3376
+ required: [
3377
+ "input_path",
3378
+ "output_path",
3379
+ "format",
3380
+ "bytes",
3381
+ "session_id",
3382
+ "counts",
3383
+ "total_redactions",
3384
+ "mode",
3385
+ "verified"
3386
+ ]
3387
+ }
3388
+ },
1434
3389
  {
1435
3390
  name: "maskera_write_file",
1436
3391
  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.",
@@ -1725,7 +3680,7 @@ var TOOLS = [
1725
3680
  }
1726
3681
  }
1727
3682
  ];
1728
- var WRITE_TOOLS = /* @__PURE__ */ new Set(["maskera_write_file", "maskera_clear_session"]);
3683
+ var WRITE_TOOLS = /* @__PURE__ */ new Set(["maskera_write_file", "maskera_redact_file", "maskera_clear_session"]);
1729
3684
  var CODE_FILE_EXTENSIONS = /* @__PURE__ */ new Set([
1730
3685
  ".ts",
1731
3686
  ".tsx",
@@ -1818,6 +3773,7 @@ function enforceSessionSecretsRedacted(text, sessionMap) {
1818
3773
  }
1819
3774
  return { text: out, extraRedactions };
1820
3775
  }
3776
+ var MAX_CLIENT_SESSIONS = 500;
1821
3777
  function createMaskeraMcpServer(options = {}) {
1822
3778
  const engine = options.engine ?? createMaskeraEngine();
1823
3779
  const vault = options.vault ?? new SessionVault();
@@ -1828,8 +3784,24 @@ function createMaskeraMcpServer(options = {}) {
1828
3784
  const approvalBaseUrl = options.approvalBaseUrl;
1829
3785
  const requestElicitation = options.requestElicitation;
1830
3786
  const onToolCall = options.onToolCall;
1831
- let clientSupportsElicitation = false;
3787
+ const clientSessions = /* @__PURE__ */ new Map();
1832
3788
  const ownerPathAliases = /* @__PURE__ */ new Map();
3789
+ function getClientHandshake(owner) {
3790
+ return clientSessions.get(owner) ?? { status: "uninitialized" };
3791
+ }
3792
+ function setClientInitialized(owner, protocolVersion, supportsElicitation) {
3793
+ if (clientSessions.has(owner)) {
3794
+ clientSessions.delete(owner);
3795
+ } else if (clientSessions.size >= MAX_CLIENT_SESSIONS) {
3796
+ const oldest = clientSessions.keys().next().value;
3797
+ if (oldest !== void 0) clientSessions.delete(oldest);
3798
+ }
3799
+ clientSessions.set(owner, {
3800
+ status: "initialized",
3801
+ protocolVersion,
3802
+ supportsElicitation
3803
+ });
3804
+ }
1833
3805
  function getPathAliasBucket(owner) {
1834
3806
  let bucket = ownerPathAliases.get(owner);
1835
3807
  if (!bucket) {
@@ -2020,7 +3992,8 @@ function createMaskeraMcpServer(options = {}) {
2020
3992
  return toolOk(await input.execute());
2021
3993
  }
2022
3994
  if (policy.approvalMode === "native") {
2023
- if (!requestElicitation || !clientSupportsElicitation) {
3995
+ const handshake = getClientHandshake(policy.sessionOwner);
3996
+ if (!requestElicitation || handshake.status !== "initialized" || !handshake.supportsElicitation) {
2024
3997
  return toolError(
2025
3998
  `Approval mode "native" requires an MCP client with elicitation support. Reconnect with approval_mode=browser or write restored output directly via maskera_write_file.`
2026
3999
  );
@@ -2185,6 +4158,9 @@ function createMaskeraMcpServer(options = {}) {
2185
4158
  if (resumed.status === "not_found") {
2186
4159
  return finish(toolError(`Unknown approval request_id "${requestId}".`));
2187
4160
  }
4161
+ if (resumed.status === "failed") {
4162
+ return finish(toolError(`Approval request "${requestId}" failed: ${resumed.error}`));
4163
+ }
2188
4164
  if (resumed.status === "completed") {
2189
4165
  return finish(
2190
4166
  toolOk({
@@ -2207,40 +4183,138 @@ function createMaskeraMcpServer(options = {}) {
2207
4183
  if (engine.status().defaultMode === "auto" && requestedMode === "rules") {
2208
4184
  return finish(
2209
4185
  toolError(
2210
- 'Downgrading mode to "rules" is not allowed on maskera_read_file when the server runs in hybrid "auto" mode.'
4186
+ 'Downgrading mode to "rules" is not allowed on maskera_read_file when the server runs in hybrid "auto" mode.'
4187
+ )
4188
+ );
4189
+ }
4190
+ const requestedSession = typeof args.session_id === "string" ? args.session_id : void 0;
4191
+ const resolvedInputPath = resolveInputPath(args.path, owner, requestedSession);
4192
+ const file = await files.readDocument(resolvedInputPath);
4193
+ const profile = asProfile(args.profile) ?? defaultProfile;
4194
+ const customTerms = mergeCustomTerms(asStringArray(args.custom_terms));
4195
+ const { result, modeUsed } = await engine.redact(file.content, {
4196
+ mode: requestedMode,
4197
+ profile,
4198
+ customTerms
4199
+ });
4200
+ const applied = vault.apply(file.content, result, requestedSession, owner);
4201
+ const safePath = await redactResolvedPath(file.resolvedPath, {
4202
+ owner,
4203
+ sessionId: applied.sessionId,
4204
+ mode: requestedMode,
4205
+ profile,
4206
+ customTerms
4207
+ });
4208
+ telemetrySessionId = applied.sessionId;
4209
+ telemetryRedactions = applied.totalRedactions;
4210
+ telemetryCounts = applied.counts;
4211
+ return finish(
4212
+ toolOk({
4213
+ path: safePath,
4214
+ bytes: file.bytes,
4215
+ format: file.format,
4216
+ redacted: applied.redacted,
4217
+ session_id: applied.sessionId,
4218
+ counts: applied.counts,
4219
+ total_redactions: applied.totalRedactions,
4220
+ mode: modeUsed,
4221
+ ...file.totalPages !== void 0 ? { total_pages: file.totalPages } : {},
4222
+ ...file.scannedPages.length > 0 ? { scanned_pages: file.scannedPages } : {},
4223
+ ...file.metadataFields.length > 0 ? { metadata_fields: file.metadataFields } : {},
4224
+ ...file.warnings.length > 0 ? { warnings: file.warnings } : {}
4225
+ })
4226
+ );
4227
+ }
4228
+ if (name === "maskera_redact_file") {
4229
+ if (typeof args.input_path !== "string") {
4230
+ return finish(toolError("Missing required string: input_path"));
4231
+ }
4232
+ if (typeof args.output_path !== "string") {
4233
+ return finish(toolError("Missing required string: output_path"));
4234
+ }
4235
+ const requestedMode = asMode(args.mode);
4236
+ if (engine.status().defaultMode === "auto" && requestedMode === "rules") {
4237
+ return finish(
4238
+ toolError(
4239
+ 'Downgrading mode to "rules" is not allowed on maskera_redact_file when the server runs in hybrid "auto" mode.'
2211
4240
  )
2212
4241
  );
2213
4242
  }
2214
4243
  const requestedSession = typeof args.session_id === "string" ? args.session_id : void 0;
2215
- const resolvedInputPath = resolveInputPath(args.path, owner, requestedSession);
2216
- const file = await files.readText(resolvedInputPath);
4244
+ const resolvedInputPath = resolveInputPath(args.input_path, owner, requestedSession);
4245
+ const resolvedOutputPath = resolveInputPath(args.output_path, owner, requestedSession);
4246
+ const source = await files.readBytes(resolvedInputPath);
2217
4247
  const profile = asProfile(args.profile) ?? defaultProfile;
2218
4248
  const customTerms = mergeCustomTerms(asStringArray(args.custom_terms));
2219
- const { result, modeUsed } = await engine.redact(file.content, {
4249
+ let sessionId = requestedSession ?? "";
4250
+ let modeUsed = engine.status().defaultMode === "rules" ? "rules" : "hybrid";
4251
+ const redactedDoc = await redactFile(
4252
+ source.bytes,
4253
+ async (text) => {
4254
+ const eng = await engine.redact(text, {
4255
+ mode: requestedMode,
4256
+ profile,
4257
+ customTerms
4258
+ });
4259
+ modeUsed = eng.modeUsed;
4260
+ const applied = vault.apply(text, eng.result, sessionId || void 0, owner);
4261
+ sessionId = applied.sessionId;
4262
+ return {
4263
+ text: applied.redacted,
4264
+ redactions: applied.redactions,
4265
+ map: applied.map,
4266
+ restore: (t) => vault.restore(t, { sessionId: applied.sessionId, owner }).restored
4267
+ };
4268
+ },
4269
+ {
4270
+ fileName: source.resolvedPath,
4271
+ pdfStyle: { showLabels: args.show_labels !== false },
4272
+ verify: true
4273
+ }
4274
+ );
4275
+ if (!redactedDoc.verified) {
4276
+ return finish(
4277
+ toolError(
4278
+ `Post-redaction verification detected ${redactedDoc.verificationLeaks.length} residual item(s) in the output file; refused to write unverified output.`
4279
+ )
4280
+ );
4281
+ }
4282
+ const written = await files.writeBytes(resolvedOutputPath, redactedDoc.bytes, {
4283
+ overwrite: args.overwrite === true
4284
+ });
4285
+ const safeInputPath = await redactResolvedPath(source.resolvedPath, {
4286
+ owner,
4287
+ sessionId: sessionId || void 0,
2220
4288
  mode: requestedMode,
2221
4289
  profile,
2222
4290
  customTerms
2223
4291
  });
2224
- const applied = vault.apply(file.content, result, requestedSession, owner);
2225
- const safePath = await redactResolvedPath(file.resolvedPath, {
4292
+ const safeOutputPath = await redactResolvedPath(written.resolvedPath, {
2226
4293
  owner,
2227
- sessionId: applied.sessionId,
4294
+ sessionId: sessionId || void 0,
2228
4295
  mode: requestedMode,
2229
4296
  profile,
2230
4297
  customTerms
2231
4298
  });
2232
- telemetrySessionId = applied.sessionId;
2233
- telemetryRedactions = applied.totalRedactions;
2234
- telemetryCounts = applied.counts;
4299
+ telemetrySessionId = sessionId || void 0;
4300
+ telemetryRedactions = redactedDoc.totalRedactions;
4301
+ telemetryCounts = redactedDoc.counts;
2235
4302
  return finish(
2236
4303
  toolOk({
2237
- path: safePath,
2238
- bytes: file.bytes,
2239
- redacted: applied.redacted,
2240
- session_id: applied.sessionId,
2241
- counts: applied.counts,
2242
- total_redactions: applied.totalRedactions,
2243
- mode: modeUsed
4304
+ input_path: safeInputPath,
4305
+ output_path: safeOutputPath,
4306
+ format: redactedDoc.format,
4307
+ bytes: written.bytes,
4308
+ session_id: sessionId,
4309
+ counts: redactedDoc.counts,
4310
+ total_redactions: redactedDoc.totalRedactions,
4311
+ mode: modeUsed,
4312
+ verified: redactedDoc.verified,
4313
+ metadata_cleared: redactedDoc.metadataCleared,
4314
+ ...redactedDoc.redactedPages ? { redacted_pages: redactedDoc.redactedPages } : {},
4315
+ ...redactedDoc.totalPages !== void 0 ? { total_pages: redactedDoc.totalPages } : {},
4316
+ ...redactedDoc.scannedPages.length > 0 ? { scanned_pages: redactedDoc.scannedPages } : {},
4317
+ ...redactedDoc.warnings.length > 0 ? { warnings: redactedDoc.warnings } : {}
2244
4318
  })
2245
4319
  );
2246
4320
  }
@@ -2411,6 +4485,17 @@ function createMaskeraMcpServer(options = {}) {
2411
4485
  }
2412
4486
  return {
2413
4487
  vault,
4488
+ getClientState(owner) {
4489
+ return getClientHandshake(owner ?? options.sessionOwner ?? "default");
4490
+ },
4491
+ clearOwner(owner) {
4492
+ clientSessions.delete(owner);
4493
+ ownerPathAliases.delete(owner);
4494
+ },
4495
+ clearAllOwners() {
4496
+ clientSessions.clear();
4497
+ ownerPathAliases.clear();
4498
+ },
2414
4499
  async handleMessage(raw, policyOverride) {
2415
4500
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
2416
4501
  return {
@@ -2437,9 +4522,10 @@ function createMaskeraMcpServer(options = {}) {
2437
4522
  if (req.method === "initialize") {
2438
4523
  const params = asObject(req.params);
2439
4524
  const clientCaps = asObject(params.capabilities);
2440
- clientSupportsElicitation = Boolean("elicitation" in clientCaps && clientCaps.elicitation);
4525
+ const supportsElicitation = Boolean("elicitation" in clientCaps && clientCaps.elicitation);
2441
4526
  const requested = typeof params.protocolVersion === "string" ? params.protocolVersion : void 0;
2442
4527
  const protocolVersion = requested && SUPPORTED_PROTOCOLS.includes(requested) ? requested : SUPPORTED_PROTOCOLS[0];
4528
+ setClientInitialized(policy.sessionOwner, protocolVersion, supportsElicitation);
2443
4529
  return {
2444
4530
  jsonrpc: "2.0",
2445
4531
  id,
@@ -3391,13 +5477,93 @@ function renderInspectorHtml(info) {
3391
5477
  const stUniq = document.getElementById("st-uniq");
3392
5478
  const stModel = document.getElementById("st-model");
3393
5479
  const SAMPLE_PROMPT = "Skriv ett kort mejl till Anna Lindqvist (provnamn.maskera@example.com, 19900101-2385) och bekr\xE4fta m\xF6tet.";
3394
- let items = [];
3395
- let approvals = [];
3396
- let lastReceipt = null;
3397
- let reveal = false;
3398
- let userToggled = false;
3399
- const openIds = new Set();
3400
- const seenIds = new Set();
5480
+ const VISIBLE_APPROVAL_STATUSES = new Set(["pending", "approved", "executing", "declined", "failed"]);
5481
+ const state = {
5482
+ connection: "connecting",
5483
+ items: [],
5484
+ approvals: [],
5485
+ selfTest: { phase: "idle" },
5486
+ vaultView: "hidden",
5487
+ expansion: { mode: "auto" },
5488
+ };
5489
+
5490
+ function isExpanded(itemId, index) {
5491
+ if (state.expansion.mode === "auto") return index === 0;
5492
+ return state.expansion.openIds.has(itemId);
5493
+ }
5494
+
5495
+ function transition(event) {
5496
+ switch (event.type) {
5497
+ case "sse_open":
5498
+ state.connection = "live";
5499
+ return;
5500
+ case "sse_error":
5501
+ state.connection = "reconnecting";
5502
+ return;
5503
+ case "sse_init":
5504
+ state.connection = "live";
5505
+ state.items = event.items || [];
5506
+ state.approvals = event.approvals || [];
5507
+ renderApprovals();
5508
+ render();
5509
+ void refreshStatus();
5510
+ return;
5511
+ case "sse_approvals":
5512
+ state.approvals = event.approvals || [];
5513
+ renderApprovals();
5514
+ void refreshStatus();
5515
+ return;
5516
+ case "sse_request":
5517
+ state.items.unshift(event.item);
5518
+ if (state.items.length > 100) state.items.length = 100;
5519
+ render();
5520
+ void refreshStatus();
5521
+ if (state.vaultView === "revealed") void refreshVault();
5522
+ return;
5523
+ case "cleared":
5524
+ state.items = [];
5525
+ state.approvals = [];
5526
+ state.expansion = { mode: "auto" };
5527
+ renderApprovals();
5528
+ render();
5529
+ void refreshStatus();
5530
+ void refreshVault();
5531
+ return;
5532
+ case "toggle_item": {
5533
+ const openIds =
5534
+ state.expansion.mode === "manual"
5535
+ ? new Set(state.expansion.openIds)
5536
+ : new Set(state.items[0]?.id ? [state.items[0].id] : []);
5537
+ if (event.open) openIds.add(event.id);
5538
+ else openIds.delete(event.id);
5539
+ state.expansion = { mode: "manual", openIds };
5540
+ return;
5541
+ }
5542
+ case "toggle_vault":
5543
+ state.vaultView = state.vaultView === "revealed" ? "hidden" : "revealed";
5544
+ revealBtn.classList.toggle("active", state.vaultView === "revealed");
5545
+ revealBtn.textContent = state.vaultView === "revealed" ? "D\xF6lj originalv\xE4rden" : "Visa originalv\xE4rden";
5546
+ void refreshVault();
5547
+ return;
5548
+ case "selftest_start":
5549
+ state.selfTest = { phase: "running" };
5550
+ renderReceipt();
5551
+ return;
5552
+ case "selftest_done":
5553
+ state.selfTest = { phase: "done", receipt: event.receipt };
5554
+ renderReceipt();
5555
+ void refreshStatus();
5556
+ return;
5557
+ case "selftest_error":
5558
+ state.selfTest = { phase: "error", message: event.message };
5559
+ renderReceipt();
5560
+ return;
5561
+ case "selftest_close":
5562
+ state.selfTest = { phase: "idle" };
5563
+ renderReceipt();
5564
+ return;
5565
+ }
5566
+ }
3401
5567
 
3402
5568
  const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ "&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;" }[c]));
3403
5569
  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>");
@@ -3413,11 +5579,17 @@ function renderInspectorHtml(info) {
3413
5579
  };
3414
5580
 
3415
5581
  function renderReceipt() {
3416
- if (!lastReceipt) {
3417
- receiptRoot.innerHTML = "";
5582
+ selftestBtn.disabled = state.selfTest.phase === "running";
5583
+ selftestBtn.textContent = state.selfTest.phase === "running" ? "K\xF6r sj\xE4lvtest..." : "K\xF6r sj\xE4lvtest";
5584
+ if (state.selfTest.phase === "idle" || state.selfTest.phase === "running") {
5585
+ if (state.selfTest.phase === "idle") receiptRoot.innerHTML = "";
5586
+ return;
5587
+ }
5588
+ if (state.selfTest.phase === "error") {
5589
+ receiptRoot.innerHTML = '<section class="receipt-box"><h2>Sj\xE4lvtest misslyckades</h2><p>' + esc(state.selfTest.message) + '</p></section>';
3418
5590
  return;
3419
5591
  }
3420
- const r = lastReceipt;
5592
+ const r = state.selfTest.receipt;
3421
5593
  const checksHtml = (r.checks || []).map((c) => {
3422
5594
  const cls = c.status === "fail" ? " fail" : "";
3423
5595
  return '<li><span class="receipt-tag' + cls + '">[' + esc(c.status) + ']</span><span><strong>' + esc(c.name) + ':</strong> ' + esc(c.detail) + '</span></li>';
@@ -3443,29 +5615,22 @@ function renderInspectorHtml(info) {
3443
5615
  const closeBtn = document.getElementById("close-receipt-btn");
3444
5616
  if (closeBtn) {
3445
5617
  closeBtn.addEventListener("click", () => {
3446
- lastReceipt = null;
3447
- renderReceipt();
5618
+ transition({ type: "selftest_close" });
3448
5619
  });
3449
5620
  }
3450
5621
  }
3451
5622
 
3452
5623
  selftestBtn.addEventListener("click", async () => {
3453
- selftestBtn.disabled = true;
3454
- const prevText = selftestBtn.textContent;
3455
- selftestBtn.textContent = "K\xF6r sj\xE4lvtest...";
5624
+ if (state.selfTest.phase === "running") return;
5625
+ transition({ type: "selftest_start" });
3456
5626
  try {
3457
5627
  const r = await fetch("/_maskera/self-test", {
3458
5628
  method: "POST",
3459
5629
  headers: { "x-maskera-action": "self-test" },
3460
5630
  });
3461
- lastReceipt = await r.json();
3462
- renderReceipt();
3463
- await refreshStatus();
5631
+ transition({ type: "selftest_done", receipt: await r.json() });
3464
5632
  } catch (err) {
3465
- receiptRoot.innerHTML = '<section class="receipt-box"><h2>Sj\xE4lvtest misslyckades</h2><p>' + esc(err) + '</p></section>';
3466
- } finally {
3467
- selftestBtn.disabled = false;
3468
- selftestBtn.textContent = prevText;
5633
+ transition({ type: "selftest_error", message: String(err) });
3469
5634
  }
3470
5635
  });
3471
5636
 
@@ -3493,7 +5658,7 @@ function renderInspectorHtml(info) {
3493
5658
  }
3494
5659
 
3495
5660
  function renderApprovals() {
3496
- const visible = (approvals || []).filter((a) => a.status === "pending" || a.status === "approved" || a.status === "declined");
5661
+ const visible = (state.approvals || []).filter((a) => VISIBLE_APPROVAL_STATUSES.has(a.status));
3497
5662
  if (!visible.length) {
3498
5663
  approvalsRoot.innerHTML = "";
3499
5664
  return;
@@ -3501,7 +5666,7 @@ function renderInspectorHtml(info) {
3501
5666
  const rows = visible.map((a) => {
3502
5667
  const btns = a.status === "pending"
3503
5668
  ? '<div class="actions"><button type="button" class="primary" data-apr="' + esc(a.id) + '" data-act="approve">Godk\xE4nn</button><button type="button" data-apr="' + esc(a.id) + '" data-act="decline">Neka</button></div>'
3504
- : '<span class="badge">' + esc(a.status) + "</span>";
5669
+ : '<span class="badge' + (a.status === "failed" ? " err" : "") + '">' + esc(a.status) + "</span>";
3505
5670
  return '<div class="approval-row" id="approval-' + esc(a.id) + '"><div><strong>' + esc(a.tool) + '</strong> \xB7 ' + esc(a.reason) + '<div class="approval-meta">F\xF6rfr\xE5gan ' + esc(a.id) + (a.sessionId ? ' \xB7 session ' + esc(a.sessionId) : '') + ' \xB7 ' + esc(a.placeholderCount) + ' v\xE4rden</div></div>' + btns + '</div>';
3506
5671
  }).join("");
3507
5672
  approvalsRoot.innerHTML = '<section class="approvals"><h2>V\xE4ntande godk\xE4nnanden (r\xE5 PII)</h2>' + rows + "</section>";
@@ -3515,7 +5680,7 @@ function renderInspectorHtml(info) {
3515
5680
  }
3516
5681
 
3517
5682
  async function refreshVault() {
3518
- if (!reveal) { vaultRoot.innerHTML = ""; return; }
5683
+ if (state.vaultView !== "revealed") { vaultRoot.innerHTML = ""; return; }
3519
5684
  try {
3520
5685
  const r = await fetch("/_maskera/vault", { headers: { "x-maskera-reveal": "1" } });
3521
5686
  const d = await r.json();
@@ -3527,7 +5692,7 @@ function renderInspectorHtml(info) {
3527
5692
  }
3528
5693
 
3529
5694
  function render() {
3530
- if (!items.length) {
5695
+ if (!state.items.length) {
3531
5696
  feedEl.innerHTML =
3532
5697
  '<div class="empty"><p class="empty-title">Inga anrop \xE4nnu.</p>' +
3533
5698
  'Skicka ett prov fr\xE5n din klient s\xE5 visas maskeringen h\xE4r:' +
@@ -3545,17 +5710,13 @@ function renderInspectorHtml(info) {
3545
5710
  }
3546
5711
  return;
3547
5712
  }
3548
- if (seenIds.size === 0 && items[0]?.id) {
3549
- openIds.add(items[0].id);
3550
- }
3551
- for (const it of items) seenIds.add(it.id);
3552
- feedEl.innerHTML = '<div class="list">' + items.map((it) => {
5713
+ feedEl.innerHTML = '<div class="list">' + state.items.map((it, idx) => {
3553
5714
  const time = formatLocalTime(it.timestamp);
3554
5715
  const tags = Object.entries(it.counts || {}).map(([k, v]) => '<span class="count-tag">' + esc(k) + " \xD7" + v + "</span>").join("");
3555
5716
  const previews = (it.redactedPreview || []).map((p) => '<pre class="preview">' + highlightTokens(p) + "</pre>").join("");
3556
5717
  const errBlock = it.errorDetail ? '<p class="body-label">Svar fr\xE5n API (fel):</p><pre class="preview err-preview">' + esc(it.errorDetail) + "</pre>" : "";
3557
5718
  const statusCls = it.status >= 200 && it.status < 400 ? "" : " err";
3558
- const isOpen = openIds.has(it.id);
5719
+ const isOpen = isExpanded(it.id, idx);
3559
5720
  return '<details class="item" data-id="' + esc(it.id) + '"' + (isOpen ? " open" : "") + '>' +
3560
5721
  '<summary><span class="left"><span class="badge' + statusCls + '">' + it.status + '</span><span class="path">' + esc(it.method + " " + it.path) + '</span>' + tags + (it.redactions === 0 ? '<span style="color:var(--muted);font-size:12px">0 PII</span>' : "") + '</span>' +
3561
5722
  '<span class="right"><span>' + (it.streamed ? "SSE" : "JSON") + '</span><span>' + it.durationMs + ' ms</span><span>' + esc(time) + '</span></span></summary>' +
@@ -3565,67 +5726,36 @@ function renderInspectorHtml(info) {
3565
5726
  det.addEventListener("toggle", () => {
3566
5727
  const id = det.getAttribute("data-id");
3567
5728
  if (!id) return;
3568
- userToggled = true;
3569
- if (det.open) openIds.add(id);
3570
- else openIds.delete(id);
5729
+ transition({ type: "toggle_item", id, open: det.open });
3571
5730
  });
3572
5731
  }
3573
5732
  }
3574
5733
 
3575
5734
  revealBtn.addEventListener("click", () => {
3576
- reveal = !reveal;
3577
- revealBtn.classList.toggle("active", reveal);
3578
- revealBtn.textContent = reveal ? "D\xF6lj originalv\xE4rden" : "Visa originalv\xE4rden";
3579
- void refreshVault();
5735
+ transition({ type: "toggle_vault" });
3580
5736
  });
3581
5737
 
3582
5738
  clearBtn.addEventListener("click", async () => {
3583
5739
  await fetch("/_maskera/clear", { method: "POST", headers: { "x-maskera-action": "clear" } });
3584
- items = [];
3585
- approvals = [];
3586
- userToggled = false;
3587
- openIds.clear();
3588
- seenIds.clear();
3589
- renderApprovals();
3590
- render();
3591
- await refreshStatus();
3592
- await refreshVault();
5740
+ transition({ type: "cleared" });
3593
5741
  });
3594
5742
 
3595
5743
  const es = new EventSource("/_maskera/events");
5744
+ es.addEventListener("open", () => transition({ type: "sse_open" }));
5745
+ es.addEventListener("error", () => transition({ type: "sse_error" }));
3596
5746
  es.addEventListener("init", (ev) => {
3597
5747
  const data = JSON.parse(ev.data);
3598
- items = data.items || [];
3599
- approvals = data.approvals || [];
3600
- renderApprovals();
3601
- render();
3602
- void refreshStatus();
5748
+ transition({ type: "sse_init", items: data.items, approvals: data.approvals });
3603
5749
  });
3604
5750
  es.addEventListener("approvals", (ev) => {
3605
5751
  const data = JSON.parse(ev.data);
3606
- approvals = data.approvals || [];
3607
- renderApprovals();
3608
- void refreshStatus();
5752
+ transition({ type: "sse_approvals", approvals: data.approvals });
3609
5753
  });
3610
5754
  es.addEventListener("request", (ev) => {
3611
- const next = JSON.parse(ev.data);
3612
- items.unshift(next);
3613
- if (items.length > 100) items.length = 100;
3614
- if (!userToggled && openIds.size === 0 && next?.id) openIds.add(next.id);
3615
- render();
3616
- void refreshStatus();
3617
- if (reveal) void refreshVault();
5755
+ transition({ type: "sse_request", item: JSON.parse(ev.data) });
3618
5756
  });
3619
5757
  es.addEventListener("cleared", () => {
3620
- items = [];
3621
- approvals = [];
3622
- userToggled = false;
3623
- openIds.clear();
3624
- seenIds.clear();
3625
- renderApprovals();
3626
- render();
3627
- void refreshStatus();
3628
- void refreshVault();
5758
+ transition({ type: "cleared" });
3629
5759
  });
3630
5760
  void refreshStatus();
3631
5761
  })();
@@ -4580,7 +6710,38 @@ function deriveProxySessionId(headers, body) {
4580
6710
  }
4581
6711
  var TEXT_BASE64_MEDIA_RE = /^(?:text\/|application\/(?:json|xml|csv|x-ndjson|javascript|yaml|x-yaml))/i;
4582
6712
  var DATA_URI_TEXT_BASE64_RE = /^data:((?:text\/[a-z0-9.+-]+|application\/(?:json|xml|csv|x-ndjson|javascript))[^;,]*);base64,([A-Za-z0-9+/=\s]+)$/i;
4583
- var DATA_URI_ANY_RE = /^data:([^;,]+);base64,/i;
6713
+ var DATA_URI_ANY_RE = /^data:([^;,]+);base64,([A-Za-z0-9+/=\s]+)$/i;
6714
+ async function tryRedactBase64Document(encoded, mediaType, fileName, redactDocument, noteBinary) {
6715
+ if (!redactDocument) {
6716
+ noteBinary(mediaType);
6717
+ return encoded;
6718
+ }
6719
+ try {
6720
+ const rawBuf = Buffer.from(encoded, "base64");
6721
+ if (rawBuf.byteLength === 0 || rawBuf.byteLength > MAX_BODY_BYTES) {
6722
+ noteBinary(mediaType);
6723
+ return encoded;
6724
+ }
6725
+ const bytes = new Uint8Array(rawBuf.buffer, rawBuf.byteOffset, rawBuf.byteLength);
6726
+ const detected = detectFileFormat(bytes, fileName, mediaType);
6727
+ if (detected.format !== "pdf" && detected.format !== "docx" && detected.format !== "xlsx") {
6728
+ noteBinary(mediaType);
6729
+ return encoded;
6730
+ }
6731
+ const res = await redactDocument(bytes, { fileName, mimeType: mediaType });
6732
+ if (!res.verified) {
6733
+ noteBinary(`${mediaType} (unverified)`);
6734
+ return encoded;
6735
+ }
6736
+ if (res.scannedPages.length > 0) {
6737
+ noteBinary(`${mediaType} (scanned)`);
6738
+ }
6739
+ return Buffer.from(res.bytes).toString("base64");
6740
+ } catch {
6741
+ noteBinary(mediaType);
6742
+ return encoded;
6743
+ }
6744
+ }
4584
6745
  async function redactBase64Utf8(encoded, redactString, kind) {
4585
6746
  try {
4586
6747
  const rawBuf = Buffer.from(encoded, "base64");
@@ -4643,17 +6804,37 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
4643
6804
  await redactContentBlocks(block.output, kind);
4644
6805
  }
4645
6806
  if (typeof block.file_data === "string") {
6807
+ const fileName = typeof block.filename === "string" ? block.filename : void 0;
4646
6808
  const match = DATA_URI_TEXT_BASE64_RE.exec(block.file_data);
4647
6809
  if (match?.[1] && match[2]) {
4648
6810
  const nextB64 = await redactBase64Utf8(match[2], redactString, kind);
4649
6811
  block.file_data = `data:${match[1]};base64,${nextB64}`;
4650
6812
  } else if (block.file_data.startsWith("data:")) {
4651
- const anyMime = DATA_URI_ANY_RE.exec(block.file_data)?.[1] ?? "application/octet-stream";
4652
- noteBinary(anyMime);
6813
+ const anyMatch = DATA_URI_ANY_RE.exec(block.file_data);
6814
+ const anyMime = anyMatch?.[1] ?? "application/octet-stream";
6815
+ const b64Payload = anyMatch?.[2];
6816
+ if (b64Payload) {
6817
+ const nextB64 = await tryRedactBase64Document(
6818
+ b64Payload,
6819
+ anyMime,
6820
+ fileName,
6821
+ options.redactDocument,
6822
+ noteBinary
6823
+ );
6824
+ block.file_data = `data:${anyMime};base64,${nextB64}`;
6825
+ } else {
6826
+ noteBinary(anyMime);
6827
+ }
4653
6828
  } else {
4654
6829
  const rawBuf = Buffer.from(block.file_data, "base64");
4655
6830
  if (rawBuf.includes(0)) {
4656
- noteBinary("application/octet-stream");
6831
+ block.file_data = await tryRedactBase64Document(
6832
+ block.file_data,
6833
+ "application/octet-stream",
6834
+ fileName,
6835
+ options.redactDocument,
6836
+ noteBinary
6837
+ );
4657
6838
  } else {
4658
6839
  block.file_data = await redactBase64Utf8(block.file_data, redactString, kind);
4659
6840
  }
@@ -4664,6 +6845,18 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
4664
6845
  block.source.data = await redactString(block.source.data, kind);
4665
6846
  } else if (block.source.type === "base64" && typeof block.source.data === "string" && typeof block.source.media_type === "string" && TEXT_BASE64_MEDIA_RE.test(block.source.media_type)) {
4666
6847
  block.source.data = await redactBase64Utf8(block.source.data, redactString, kind);
6848
+ } else if (block.source.type === "base64" && typeof block.source.data === "string") {
6849
+ const mediaType = typeof block.source.media_type === "string" ? block.source.media_type : "application/octet-stream";
6850
+ if (blockType !== "image" && blockType !== "input_image") {
6851
+ const docTitle = typeof block.title === "string" ? block.title : void 0;
6852
+ block.source.data = await tryRedactBase64Document(
6853
+ block.source.data,
6854
+ mediaType,
6855
+ docTitle,
6856
+ options.redactDocument,
6857
+ noteBinary
6858
+ );
6859
+ }
4667
6860
  } else if (block.source.type === "base64") {
4668
6861
  const mediaType = typeof block.source.media_type === "string" ? block.source.media_type : "application/octet-stream";
4669
6862
  if (blockType !== "image" && blockType !== "input_image") {
@@ -4744,7 +6937,9 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
4744
6937
  for (const batchItem of clone.requests) {
4745
6938
  if (isPlainObject(batchItem) && isPlainObject(batchItem.params)) {
4746
6939
  batchItem.params = await redactLlmRequestBody(batchItem.params, redactString, {
4747
- mutate: true
6940
+ mutate: true,
6941
+ onBinaryAttachment: options.onBinaryAttachment,
6942
+ redactDocument: options.redactDocument
4748
6943
  });
4749
6944
  }
4750
6945
  }
@@ -4947,173 +7142,229 @@ function restoreLlmResponseBody(body, map, options = {}) {
4947
7142
  }
4948
7143
  return clone;
4949
7144
  }
4950
- function createSseRestorer(map, options = {}) {
4951
- const reasoningMap = filterMapExcluding(map, options.reasoningExcludedTokens);
4952
- const streams = /* @__PURE__ */ new Map();
4953
- const toolNames = /* @__PURE__ */ new Map();
4954
- const bufferedToolArgs = /* @__PURE__ */ new Map();
4955
- const getStream = (key, escapeForJsonString = false, useReasoningMap = false) => {
4956
- let r = streams.get(key);
4957
- if (!r) {
4958
- r = new StreamingRestorer(useReasoningMap ? reasoningMap : map, { escapeForJsonString });
4959
- streams.set(key, r);
4960
- }
4961
- return r;
4962
- };
4963
- function flushStream(key) {
4964
- const r = streams.get(key);
4965
- if (!r) return "";
4966
- streams.delete(key);
4967
- return r.flush();
4968
- }
4969
- function flushBufferedToolArgs(key) {
4970
- const raw = bufferedToolArgs.get(key);
4971
- if (raw === void 0) return "";
4972
- bufferedToolArgs.delete(key);
4973
- const name = toolNames.get(key);
4974
- if (shouldSkipToolArgRestore(name, raw)) return raw;
4975
- return restoreJsonEncodedText(raw, map);
7145
+ function channelKey(d) {
7146
+ switch (d.protocol) {
7147
+ case "anthropic":
7148
+ return `anthropic:${d.kind}:${d.index}`;
7149
+ case "openai_chat":
7150
+ return d.kind === "tool_args" ? `openai_chat:tool_args:${d.choiceIndex}:${d.toolIndex}` : `openai_chat:${d.kind}:${d.choiceIndex}`;
7151
+ case "openai_responses":
7152
+ switch (d.kind) {
7153
+ case "text":
7154
+ return `openai_responses:text:${d.outputIndex}:${d.contentIndex}`;
7155
+ case "reasoning":
7156
+ return `openai_responses:reasoning:${d.outputIndex}:${d.summaryIndex}`;
7157
+ case "tool_args":
7158
+ return `openai_responses:tool_args:${d.outputIndex}`;
7159
+ }
4976
7160
  }
4977
- function drainRemainingStreams() {
4978
- const events = [];
4979
- for (const key of [...bufferedToolArgs.keys()]) {
4980
- const full = flushBufferedToolArgs(key);
4981
- if (!full) continue;
4982
- if (key.startsWith("openai_chat_tool:")) {
4983
- const [, cIdx, tIdx] = key.split(":");
4984
- events.push(
4985
- `data: ${JSON.stringify({
4986
- choices: [
4987
- {
4988
- index: Number(cIdx ?? 0),
4989
- delta: {
4990
- tool_calls: [{ index: Number(tIdx ?? 0), function: { arguments: full } }]
4991
- }
4992
- }
4993
- ]
4994
- })}`
4995
- );
4996
- } else if (key.startsWith("anth_json:")) {
4997
- const idx = Number(key.split(":")[1] ?? 0);
4998
- events.push(
4999
- `event: content_block_delta
7161
+ }
7162
+ function formatChannelEvent(descriptor, payload) {
7163
+ switch (descriptor.protocol) {
7164
+ case "anthropic":
7165
+ switch (descriptor.kind) {
7166
+ case "text":
7167
+ return `event: content_block_delta
5000
7168
  data: ${JSON.stringify({
5001
7169
  type: "content_block_delta",
5002
- index: idx,
5003
- delta: { type: "input_json_delta", partial_json: full }
5004
- })}`
5005
- );
5006
- } else if (key.startsWith("resp_args:")) {
5007
- const outputIdx = Number(key.split(":")[1] ?? 0);
5008
- events.push(
5009
- `event: response.function_call_arguments.delta
7170
+ index: descriptor.index,
7171
+ delta: { type: "text_delta", text: payload }
7172
+ })}`;
7173
+ case "thinking":
7174
+ return `event: content_block_delta
5010
7175
  data: ${JSON.stringify({
5011
- type: "response.function_call_arguments.delta",
5012
- output_index: outputIdx,
5013
- delta: full
5014
- })}`
5015
- );
7176
+ type: "content_block_delta",
7177
+ index: descriptor.index,
7178
+ delta: { type: "thinking_delta", thinking: payload }
7179
+ })}`;
7180
+ case "tool_json":
7181
+ return `event: content_block_delta
7182
+ data: ${JSON.stringify({
7183
+ type: "content_block_delta",
7184
+ index: descriptor.index,
7185
+ delta: { type: "input_json_delta", partial_json: payload }
7186
+ })}`;
5016
7187
  }
5017
- }
5018
- for (const key of [...streams.keys()]) {
5019
- const tail = flushStream(key);
5020
- if (!tail) continue;
5021
- if (key.startsWith("openai_chat_text:")) {
5022
- const idx = Number(key.split(":")[1] ?? 0);
5023
- events.push(
5024
- `data: ${JSON.stringify({ choices: [{ index: idx, delta: { content: tail } }] })}`
5025
- );
5026
- } else if (key.startsWith("openai_chat_tool:")) {
5027
- const [, cIdx, tIdx] = key.split(":");
5028
- events.push(
5029
- `data: ${JSON.stringify({
7188
+ break;
7189
+ case "openai_chat":
7190
+ switch (descriptor.kind) {
7191
+ case "text":
7192
+ return `data: ${JSON.stringify({
7193
+ choices: [{ index: descriptor.choiceIndex, delta: { content: payload } }]
7194
+ })}`;
7195
+ case "reasoning":
7196
+ return `data: ${JSON.stringify({
7197
+ choices: [{ index: descriptor.choiceIndex, delta: { reasoning_content: payload } }]
7198
+ })}`;
7199
+ case "reasoning_plain":
7200
+ return `data: ${JSON.stringify({
7201
+ choices: [{ index: descriptor.choiceIndex, delta: { reasoning: payload } }]
7202
+ })}`;
7203
+ case "tool_args":
7204
+ return `data: ${JSON.stringify({
5030
7205
  choices: [
5031
7206
  {
5032
- index: Number(cIdx ?? 0),
7207
+ index: descriptor.choiceIndex,
5033
7208
  delta: {
5034
- tool_calls: [{ index: Number(tIdx ?? 0), function: { arguments: tail } }]
7209
+ tool_calls: [{ index: descriptor.toolIndex, function: { arguments: payload } }]
5035
7210
  }
5036
7211
  }
5037
7212
  ]
5038
- })}`
5039
- );
5040
- } else if (key.startsWith("anth_text:")) {
5041
- const idx = Number(key.split(":")[1] ?? 0);
5042
- events.push(
5043
- `event: content_block_delta
5044
- data: ${JSON.stringify({
5045
- type: "content_block_delta",
5046
- index: idx,
5047
- delta: { type: "text_delta", text: tail }
5048
- })}`
5049
- );
5050
- } else if (key.startsWith("anth_thinking:")) {
5051
- const idx = Number(key.split(":")[1] ?? 0);
5052
- events.push(
5053
- `event: content_block_delta
5054
- data: ${JSON.stringify({
5055
- type: "content_block_delta",
5056
- index: idx,
5057
- delta: { type: "thinking_delta", thinking: tail }
5058
- })}`
5059
- );
5060
- } else if (key.startsWith("anth_json:")) {
5061
- const idx = Number(key.split(":")[1] ?? 0);
5062
- events.push(
5063
- `event: content_block_delta
5064
- data: ${JSON.stringify({
5065
- type: "content_block_delta",
5066
- index: idx,
5067
- delta: { type: "input_json_delta", partial_json: tail }
5068
- })}`
5069
- );
5070
- } else if (key.startsWith("resp_text:")) {
5071
- const [, outputIdx, contentIdx] = key.split(":");
5072
- events.push(
5073
- `event: response.output_text.delta
7213
+ })}`;
7214
+ }
7215
+ break;
7216
+ case "openai_responses":
7217
+ switch (descriptor.kind) {
7218
+ case "text":
7219
+ return `event: response.output_text.delta
5074
7220
  data: ${JSON.stringify({
5075
7221
  type: "response.output_text.delta",
5076
- output_index: Number(outputIdx ?? 0),
5077
- content_index: Number(contentIdx ?? 0),
5078
- delta: tail
5079
- })}`
5080
- );
5081
- } else if (key.startsWith("openai_chat_reasoning:")) {
5082
- const idx = Number(key.split(":")[1] ?? 0);
5083
- events.push(
5084
- `data: ${JSON.stringify({ choices: [{ index: idx, delta: { reasoning_content: tail } }] })}`
5085
- );
5086
- } else if (key.startsWith("openai_chat_reasoning_plain:")) {
5087
- const idx = Number(key.split(":")[1] ?? 0);
5088
- events.push(
5089
- `data: ${JSON.stringify({ choices: [{ index: idx, delta: { reasoning: tail } }] })}`
5090
- );
5091
- } else if (key.startsWith("resp_reasoning:")) {
5092
- const [, outputIdx, summaryIdx] = key.split(":");
5093
- events.push(
5094
- `event: response.reasoning_summary_text.delta
7222
+ output_index: descriptor.outputIndex,
7223
+ content_index: descriptor.contentIndex,
7224
+ delta: payload
7225
+ })}`;
7226
+ case "reasoning":
7227
+ return `event: response.reasoning_summary_text.delta
5095
7228
  data: ${JSON.stringify({
5096
7229
  type: "response.reasoning_summary_text.delta",
5097
- output_index: Number(outputIdx ?? 0),
5098
- summary_index: Number(summaryIdx ?? 0),
5099
- delta: tail
5100
- })}`
5101
- );
5102
- } else if (key.startsWith("resp_args:")) {
5103
- const outputIdx = Number(key.split(":")[1] ?? 0);
5104
- events.push(
5105
- `event: response.function_call_arguments.delta
7230
+ output_index: descriptor.outputIndex,
7231
+ summary_index: descriptor.summaryIndex,
7232
+ delta: payload
7233
+ })}`;
7234
+ case "tool_args":
7235
+ return `event: response.function_call_arguments.delta
5106
7236
  data: ${JSON.stringify({
5107
7237
  type: "response.function_call_arguments.delta",
5108
- output_index: outputIdx,
5109
- delta: tail
5110
- })}`
5111
- );
7238
+ output_index: descriptor.outputIndex,
7239
+ delta: payload
7240
+ })}`;
7241
+ }
7242
+ }
7243
+ }
7244
+ function createSseRestorer(map, options = {}) {
7245
+ const reasoningMap = filterMapExcluding(map, options.reasoningExcludedTokens);
7246
+ const channels = /* @__PURE__ */ new Map();
7247
+ const frame = { buffer: "", pendingCr: false };
7248
+ function pushStream(descriptor, chunk, useReasoningMap = false) {
7249
+ const key = channelKey(descriptor);
7250
+ let entry = channels.get(key);
7251
+ if (entry?.category !== "stream") {
7252
+ entry = {
7253
+ category: "stream",
7254
+ descriptor,
7255
+ restorer: new StreamingRestorer(useReasoningMap ? reasoningMap : map)
7256
+ };
7257
+ channels.set(key, entry);
7258
+ }
7259
+ return entry.restorer.push(chunk);
7260
+ }
7261
+ function closeStream(descriptor) {
7262
+ const key = channelKey(descriptor);
7263
+ const entry = channels.get(key);
7264
+ if (entry?.category !== "stream") return "";
7265
+ channels.delete(key);
7266
+ return entry.restorer.flush();
7267
+ }
7268
+ function createToolState(toolName) {
7269
+ if (isMaskeraVaultToolName(toolName)) {
7270
+ return { mode: "passthrough", toolName };
7271
+ }
7272
+ if (toolName === "execute") {
7273
+ return { mode: "buffering_execute", toolName, raw: "" };
7274
+ }
7275
+ return {
7276
+ mode: "streaming",
7277
+ toolName,
7278
+ restorer: new StreamingRestorer(map, { escapeForJsonString: true })
7279
+ };
7280
+ }
7281
+ function setToolName(descriptor, toolName) {
7282
+ const key = channelKey(descriptor);
7283
+ const existing = channels.get(key);
7284
+ if (existing?.category === "tool" && existing.state.toolName === toolName) {
7285
+ return;
7286
+ }
7287
+ channels.set(key, {
7288
+ category: "tool",
7289
+ descriptor,
7290
+ state: createToolState(toolName)
7291
+ });
7292
+ }
7293
+ function pushToolDelta(descriptor, delta) {
7294
+ const key = channelKey(descriptor);
7295
+ let entry = channels.get(key);
7296
+ if (entry?.category !== "tool") {
7297
+ entry = {
7298
+ category: "tool",
7299
+ descriptor,
7300
+ state: {
7301
+ mode: "streaming",
7302
+ toolName: null,
7303
+ restorer: new StreamingRestorer(map, { escapeForJsonString: true })
7304
+ }
7305
+ };
7306
+ channels.set(key, entry);
7307
+ }
7308
+ switch (entry.state.mode) {
7309
+ case "passthrough":
7310
+ return delta;
7311
+ case "buffering_execute":
7312
+ entry.state.raw += delta;
7313
+ return "";
7314
+ case "streaming":
7315
+ return entry.state.restorer.push(delta);
7316
+ case "closed":
7317
+ return delta;
7318
+ }
7319
+ }
7320
+ function flushToolState(state) {
7321
+ switch (state.mode) {
7322
+ case "passthrough":
7323
+ case "closed":
7324
+ return "";
7325
+ case "buffering_execute":
7326
+ if (!state.raw) return "";
7327
+ return shouldSkipToolArgRestore(state.toolName, state.raw) ? state.raw : restoreJsonEncodedText(state.raw, map);
7328
+ case "streaming":
7329
+ return state.restorer.flush();
7330
+ }
7331
+ }
7332
+ function closeTool(descriptor, retainNameUntilItemDone = false) {
7333
+ const key = channelKey(descriptor);
7334
+ const entry = channels.get(key);
7335
+ if (entry?.category !== "tool") return { tail: "", toolName: null };
7336
+ const toolName = entry.state.toolName;
7337
+ const tail = flushToolState(entry.state);
7338
+ if (retainNameUntilItemDone) {
7339
+ entry.state = { mode: "closed", toolName };
7340
+ } else {
7341
+ channels.delete(key);
7342
+ }
7343
+ return { tail, toolName };
7344
+ }
7345
+ function consumeToolName(descriptor) {
7346
+ const key = channelKey(descriptor);
7347
+ const entry = channels.get(key);
7348
+ if (entry?.category !== "tool") return null;
7349
+ const name = entry.state.toolName;
7350
+ channels.delete(key);
7351
+ return name;
7352
+ }
7353
+ function drainRemainingStreams() {
7354
+ const toolEvents = [];
7355
+ const streamEvents = [];
7356
+ for (const [key, entry] of [...channels.entries()]) {
7357
+ channels.delete(key);
7358
+ if (entry.category === "tool") {
7359
+ const tail = flushToolState(entry.state);
7360
+ if (tail) toolEvents.push(formatChannelEvent(entry.descriptor, tail));
7361
+ } else {
7362
+ const tail = entry.restorer.flush();
7363
+ if (tail) streamEvents.push(formatChannelEvent(entry.descriptor, tail));
5112
7364
  }
5113
7365
  }
5114
- return events;
7366
+ return [...toolEvents, ...streamEvents];
5115
7367
  }
5116
- let sseBuffer = "";
5117
7368
  function processEventBlock(block) {
5118
7369
  const lines = block.split("\n");
5119
7370
  const outLines = [];
@@ -5141,177 +7392,136 @@ data: ${JSON.stringify({
5141
7392
  continue;
5142
7393
  }
5143
7394
  if (parsed.type === "content_block_start" && isPlainObject(parsed.content_block)) {
5144
- const idx = typeof parsed.index === "number" ? parsed.index : 0;
7395
+ const index = typeof parsed.index === "number" ? parsed.index : 0;
5145
7396
  if (parsed.content_block.type === "tool_use" && typeof parsed.content_block.name === "string") {
5146
- toolNames.set(`anth_json:${idx}`, parsed.content_block.name);
7397
+ setToolName(
7398
+ { protocol: "anthropic", kind: "tool_json", index },
7399
+ parsed.content_block.name
7400
+ );
5147
7401
  }
5148
7402
  outLines.push(`data: ${JSON.stringify(parsed)}`);
5149
7403
  continue;
5150
7404
  }
5151
7405
  if (parsed.type === "content_block_delta" && isPlainObject(parsed.delta)) {
5152
- const idx = typeof parsed.index === "number" ? parsed.index : 0;
7406
+ const index = typeof parsed.index === "number" ? parsed.index : 0;
5153
7407
  if (parsed.delta.type === "text_delta" && typeof parsed.delta.text === "string") {
5154
- parsed.delta.text = getStream(`anth_text:${idx}`).push(parsed.delta.text);
7408
+ parsed.delta.text = pushStream(
7409
+ { protocol: "anthropic", kind: "text", index },
7410
+ parsed.delta.text
7411
+ );
5155
7412
  } else if (parsed.delta.type === "thinking_delta" && typeof parsed.delta.thinking === "string") {
5156
- parsed.delta.thinking = getStream(`anth_thinking:${idx}`, false, true).push(
5157
- parsed.delta.thinking
7413
+ parsed.delta.thinking = pushStream(
7414
+ { protocol: "anthropic", kind: "thinking", index },
7415
+ parsed.delta.thinking,
7416
+ true
5158
7417
  );
5159
7418
  } else if (parsed.delta.type === "input_json_delta" && typeof parsed.delta.partial_json === "string") {
5160
- const key = `anth_json:${idx}`;
5161
- const name = toolNames.get(key);
5162
- if (isMaskeraVaultToolName(name)) ; else if (name === "execute") {
5163
- bufferedToolArgs.set(key, (bufferedToolArgs.get(key) ?? "") + parsed.delta.partial_json);
5164
- parsed.delta.partial_json = "";
5165
- } else {
5166
- parsed.delta.partial_json = getStream(key, true).push(parsed.delta.partial_json);
5167
- }
7419
+ parsed.delta.partial_json = pushToolDelta(
7420
+ { protocol: "anthropic", kind: "tool_json", index },
7421
+ parsed.delta.partial_json
7422
+ );
5168
7423
  }
5169
7424
  outLines.push(`data: ${JSON.stringify(parsed)}`);
5170
7425
  continue;
5171
7426
  }
5172
7427
  if (parsed.type === "content_block_stop") {
5173
- const idx = typeof parsed.index === "number" ? parsed.index : 0;
5174
- const textTail = flushStream(`anth_text:${idx}`);
5175
- if (textTail) {
5176
- extraEvents.push(
5177
- `event: content_block_delta
5178
- data: ${JSON.stringify({
5179
- type: "content_block_delta",
5180
- index: idx,
5181
- delta: { type: "text_delta", text: textTail }
5182
- })}`
5183
- );
5184
- }
5185
- const thinkingTail = flushStream(`anth_thinking:${idx}`);
5186
- if (thinkingTail) {
5187
- extraEvents.push(
5188
- `event: content_block_delta
5189
- data: ${JSON.stringify({
5190
- type: "content_block_delta",
5191
- index: idx,
5192
- delta: { type: "thinking_delta", thinking: thinkingTail }
5193
- })}`
5194
- );
5195
- }
5196
- const jsonKey = `anth_json:${idx}`;
5197
- const jsonTail = flushBufferedToolArgs(jsonKey) || flushStream(jsonKey);
5198
- toolNames.delete(jsonKey);
5199
- if (jsonTail) {
5200
- extraEvents.push(
5201
- `event: content_block_delta
5202
- data: ${JSON.stringify({
5203
- type: "content_block_delta",
5204
- index: idx,
5205
- delta: { type: "input_json_delta", partial_json: jsonTail }
5206
- })}`
5207
- );
5208
- }
7428
+ const index = typeof parsed.index === "number" ? parsed.index : 0;
7429
+ const textDesc = { protocol: "anthropic", kind: "text", index };
7430
+ const textTail = closeStream(textDesc);
7431
+ if (textTail) extraEvents.push(formatChannelEvent(textDesc, textTail));
7432
+ const thinkingDesc = {
7433
+ protocol: "anthropic",
7434
+ kind: "thinking",
7435
+ index
7436
+ };
7437
+ const thinkingTail = closeStream(thinkingDesc);
7438
+ if (thinkingTail) extraEvents.push(formatChannelEvent(thinkingDesc, thinkingTail));
7439
+ const toolDesc = { protocol: "anthropic", kind: "tool_json", index };
7440
+ const { tail: jsonTail } = closeTool(toolDesc);
7441
+ if (jsonTail) extraEvents.push(formatChannelEvent(toolDesc, jsonTail));
5209
7442
  outLines.push(`data: ${JSON.stringify(parsed)}`);
5210
7443
  continue;
5211
7444
  }
5212
7445
  if (Array.isArray(parsed.choices)) {
5213
7446
  for (const choice of parsed.choices) {
5214
7447
  if (!isPlainObject(choice)) continue;
5215
- const cIdx = typeof choice.index === "number" ? choice.index : 0;
7448
+ const choiceIndex = typeof choice.index === "number" ? choice.index : 0;
5216
7449
  const delta = choice.delta;
5217
7450
  if (isPlainObject(delta)) {
5218
7451
  if (typeof delta.content === "string") {
5219
- delta.content = getStream(`openai_chat_text:${cIdx}`).push(delta.content);
7452
+ delta.content = pushStream(
7453
+ { protocol: "openai_chat", kind: "text", choiceIndex },
7454
+ delta.content
7455
+ );
5220
7456
  }
5221
7457
  if (typeof delta.reasoning_content === "string") {
5222
- delta.reasoning_content = getStream(
5223
- `openai_chat_reasoning:${cIdx}`,
5224
- false,
7458
+ delta.reasoning_content = pushStream(
7459
+ { protocol: "openai_chat", kind: "reasoning", choiceIndex },
7460
+ delta.reasoning_content,
5225
7461
  true
5226
- ).push(delta.reasoning_content);
7462
+ );
5227
7463
  }
5228
7464
  if (typeof delta.reasoning === "string") {
5229
- delta.reasoning = getStream(`openai_chat_reasoning_plain:${cIdx}`, false, true).push(
5230
- delta.reasoning
7465
+ delta.reasoning = pushStream(
7466
+ { protocol: "openai_chat", kind: "reasoning_plain", choiceIndex },
7467
+ delta.reasoning,
7468
+ true
5231
7469
  );
5232
7470
  }
5233
7471
  if (Array.isArray(delta.tool_calls)) {
5234
7472
  for (const call of delta.tool_calls) {
5235
7473
  if (!isPlainObject(call)) continue;
5236
- const tIdx = typeof call.index === "number" ? call.index : 0;
5237
- const key = `openai_chat_tool:${cIdx}:${tIdx}`;
7474
+ const toolIndex = typeof call.index === "number" ? call.index : 0;
7475
+ const toolDesc = {
7476
+ protocol: "openai_chat",
7477
+ kind: "tool_args",
7478
+ choiceIndex,
7479
+ toolIndex
7480
+ };
5238
7481
  if (isPlainObject(call.function)) {
5239
7482
  if (typeof call.function.name === "string" && call.function.name) {
5240
- toolNames.set(key, call.function.name);
7483
+ setToolName(toolDesc, call.function.name);
5241
7484
  }
5242
7485
  if (typeof call.function.arguments === "string") {
5243
- const name = toolNames.get(key);
5244
- if (isMaskeraVaultToolName(name)) ; else if (name === "execute") {
5245
- bufferedToolArgs.set(
5246
- key,
5247
- (bufferedToolArgs.get(key) ?? "") + call.function.arguments
5248
- );
5249
- call.function.arguments = "";
5250
- } else {
5251
- call.function.arguments = getStream(key, true).push(call.function.arguments);
5252
- }
7486
+ call.function.arguments = pushToolDelta(toolDesc, call.function.arguments);
5253
7487
  }
5254
7488
  }
5255
7489
  }
5256
7490
  }
5257
7491
  }
5258
7492
  if (typeof choice.finish_reason === "string" && choice.finish_reason.length > 0) {
5259
- const textTail = flushStream(`openai_chat_text:${cIdx}`);
7493
+ const textTail = closeStream({ protocol: "openai_chat", kind: "text", choiceIndex });
5260
7494
  if (textTail) {
5261
7495
  if (!isPlainObject(choice.delta)) choice.delta = {};
5262
7496
  const d = choice.delta;
5263
7497
  d.content = (typeof d.content === "string" ? d.content : "") + textTail;
5264
7498
  }
5265
- const reasoningTail = flushStream(`openai_chat_reasoning:${cIdx}`);
7499
+ const reasoningTail = closeStream({
7500
+ protocol: "openai_chat",
7501
+ kind: "reasoning",
7502
+ choiceIndex
7503
+ });
5266
7504
  if (reasoningTail) {
5267
7505
  if (!isPlainObject(choice.delta)) choice.delta = {};
5268
7506
  const d = choice.delta;
5269
7507
  d.reasoning_content = (typeof d.reasoning_content === "string" ? d.reasoning_content : "") + reasoningTail;
5270
7508
  }
5271
- const reasoningPlainTail = flushStream(`openai_chat_reasoning_plain:${cIdx}`);
7509
+ const reasoningPlainTail = closeStream({
7510
+ protocol: "openai_chat",
7511
+ kind: "reasoning_plain",
7512
+ choiceIndex
7513
+ });
5272
7514
  if (reasoningPlainTail) {
5273
7515
  if (!isPlainObject(choice.delta)) choice.delta = {};
5274
7516
  const d = choice.delta;
5275
7517
  d.reasoning = (typeof d.reasoning === "string" ? d.reasoning : "") + reasoningPlainTail;
5276
7518
  }
5277
- const toolPrefix = `openai_chat_tool:${cIdx}:`;
5278
- for (const key of [...bufferedToolArgs.keys()]) {
5279
- if (!key.startsWith(toolPrefix)) continue;
5280
- const tIdx = Number(key.slice(toolPrefix.length) || 0);
5281
- const fullArgs = flushBufferedToolArgs(key);
5282
- toolNames.delete(key);
5283
- if (!fullArgs) continue;
5284
- extraEvents.push(
5285
- `data: ${JSON.stringify({
5286
- choices: [
5287
- {
5288
- index: cIdx,
5289
- delta: {
5290
- tool_calls: [{ index: tIdx, function: { arguments: fullArgs } }]
5291
- }
5292
- }
5293
- ]
5294
- })}`
5295
- );
5296
- }
5297
- for (const key of [...streams.keys()]) {
5298
- if (!key.startsWith(toolPrefix)) continue;
5299
- const tIdx = Number(key.slice(toolPrefix.length) || 0);
5300
- const toolTail = flushStream(key);
5301
- toolNames.delete(key);
5302
- if (!toolTail) continue;
5303
- extraEvents.push(
5304
- `data: ${JSON.stringify({
5305
- choices: [
5306
- {
5307
- index: cIdx,
5308
- delta: {
5309
- tool_calls: [{ index: tIdx, function: { arguments: toolTail } }]
5310
- }
5311
- }
5312
- ]
5313
- })}`
5314
- );
7519
+ for (const [key, entry] of [...channels.entries()]) {
7520
+ if (entry.category === "tool" && entry.descriptor.protocol === "openai_chat" && entry.descriptor.choiceIndex === choiceIndex) {
7521
+ channels.delete(key);
7522
+ const tail = flushToolState(entry.state);
7523
+ if (tail) extraEvents.push(formatChannelEvent(entry.descriptor, tail));
7524
+ }
5315
7525
  }
5316
7526
  }
5317
7527
  }
@@ -5320,31 +7530,36 @@ data: ${JSON.stringify({
5320
7530
  }
5321
7531
  if (parsed.type === "response.output_item.added" && isPlainObject(parsed.item)) {
5322
7532
  if (parsed.item.type === "function_call" && typeof parsed.item.name === "string") {
5323
- toolNames.set(`resp_args:${String(parsed.output_index ?? 0)}`, parsed.item.name);
7533
+ const outputIndex = typeof parsed.output_index === "number" ? parsed.output_index : 0;
7534
+ setToolName(
7535
+ { protocol: "openai_responses", kind: "tool_args", outputIndex },
7536
+ parsed.item.name
7537
+ );
5324
7538
  }
5325
7539
  outLines.push(`data: ${JSON.stringify(parsed)}`);
5326
7540
  continue;
5327
7541
  }
5328
7542
  if (parsed.type === "response.output_text.delta" && typeof parsed.delta === "string") {
5329
- const key = `resp_text:${String(parsed.output_index ?? 0)}:${String(parsed.content_index ?? 0)}`;
5330
- parsed.delta = getStream(key).push(parsed.delta);
7543
+ const outputIndex = typeof parsed.output_index === "number" ? parsed.output_index : 0;
7544
+ const contentIndex = typeof parsed.content_index === "number" ? parsed.content_index : 0;
7545
+ parsed.delta = pushStream(
7546
+ { protocol: "openai_responses", kind: "text", outputIndex, contentIndex },
7547
+ parsed.delta
7548
+ );
5331
7549
  outLines.push(`data: ${JSON.stringify(parsed)}`);
5332
7550
  continue;
5333
7551
  }
5334
7552
  if (parsed.type === "response.output_text.done") {
5335
- const key = `resp_text:${String(parsed.output_index ?? 0)}:${String(parsed.content_index ?? 0)}`;
5336
- const tail = flushStream(key);
5337
- if (tail) {
5338
- extraEvents.push(
5339
- `event: response.output_text.delta
5340
- data: ${JSON.stringify({
5341
- type: "response.output_text.delta",
5342
- output_index: parsed.output_index ?? 0,
5343
- content_index: parsed.content_index ?? 0,
5344
- delta: tail
5345
- })}`
5346
- );
5347
- }
7553
+ const outputIndex = typeof parsed.output_index === "number" ? parsed.output_index : 0;
7554
+ const contentIndex = typeof parsed.content_index === "number" ? parsed.content_index : 0;
7555
+ const desc = {
7556
+ protocol: "openai_responses",
7557
+ kind: "text",
7558
+ outputIndex,
7559
+ contentIndex
7560
+ };
7561
+ const tail = closeStream(desc);
7562
+ if (tail) extraEvents.push(formatChannelEvent(desc, tail));
5348
7563
  if (typeof parsed.text === "string") {
5349
7564
  parsed.text = restorePlainText(parsed.text, map);
5350
7565
  }
@@ -5352,25 +7567,26 @@ data: ${JSON.stringify({
5352
7567
  continue;
5353
7568
  }
5354
7569
  if (parsed.type === "response.reasoning_summary_text.delta" && typeof parsed.delta === "string") {
5355
- const key = `resp_reasoning:${String(parsed.output_index ?? 0)}:${String(parsed.summary_index ?? 0)}`;
5356
- parsed.delta = getStream(key).push(parsed.delta);
7570
+ const outputIndex = typeof parsed.output_index === "number" ? parsed.output_index : 0;
7571
+ const summaryIndex = typeof parsed.summary_index === "number" ? parsed.summary_index : 0;
7572
+ parsed.delta = pushStream(
7573
+ { protocol: "openai_responses", kind: "reasoning", outputIndex, summaryIndex },
7574
+ parsed.delta
7575
+ );
5357
7576
  outLines.push(`data: ${JSON.stringify(parsed)}`);
5358
7577
  continue;
5359
7578
  }
5360
7579
  if (parsed.type === "response.reasoning_summary_text.done") {
5361
- const key = `resp_reasoning:${String(parsed.output_index ?? 0)}:${String(parsed.summary_index ?? 0)}`;
5362
- const tail = flushStream(key);
5363
- if (tail) {
5364
- extraEvents.push(
5365
- `event: response.reasoning_summary_text.delta
5366
- data: ${JSON.stringify({
5367
- type: "response.reasoning_summary_text.delta",
5368
- output_index: parsed.output_index ?? 0,
5369
- summary_index: parsed.summary_index ?? 0,
5370
- delta: tail
5371
- })}`
5372
- );
5373
- }
7580
+ const outputIndex = typeof parsed.output_index === "number" ? parsed.output_index : 0;
7581
+ const summaryIndex = typeof parsed.summary_index === "number" ? parsed.summary_index : 0;
7582
+ const desc = {
7583
+ protocol: "openai_responses",
7584
+ kind: "reasoning",
7585
+ outputIndex,
7586
+ summaryIndex
7587
+ };
7588
+ const tail = closeStream(desc);
7589
+ if (tail) extraEvents.push(formatChannelEvent(desc, tail));
5374
7590
  if (typeof parsed.text === "string") {
5375
7591
  parsed.text = restorePlainText(parsed.text, map);
5376
7592
  }
@@ -5378,32 +7594,24 @@ data: ${JSON.stringify({
5378
7594
  continue;
5379
7595
  }
5380
7596
  if (parsed.type === "response.function_call_arguments.delta" && typeof parsed.delta === "string") {
5381
- const key = `resp_args:${String(parsed.output_index ?? 0)}`;
5382
- const name = toolNames.get(key);
5383
- if (isMaskeraVaultToolName(name)) ; else if (name === "execute") {
5384
- bufferedToolArgs.set(key, (bufferedToolArgs.get(key) ?? "") + parsed.delta);
5385
- parsed.delta = "";
5386
- } else {
5387
- parsed.delta = getStream(key, true).push(parsed.delta);
5388
- }
7597
+ const outputIndex = typeof parsed.output_index === "number" ? parsed.output_index : 0;
7598
+ parsed.delta = pushToolDelta(
7599
+ { protocol: "openai_responses", kind: "tool_args", outputIndex },
7600
+ parsed.delta
7601
+ );
5389
7602
  outLines.push(`data: ${JSON.stringify(parsed)}`);
5390
7603
  continue;
5391
7604
  }
5392
7605
  if (parsed.type === "response.function_call_arguments.done") {
5393
- const key = `resp_args:${String(parsed.output_index ?? 0)}`;
5394
- const name = toolNames.get(key);
5395
- const tail = flushBufferedToolArgs(key) || flushStream(key);
5396
- if (tail) {
5397
- extraEvents.push(
5398
- `event: response.function_call_arguments.delta
5399
- data: ${JSON.stringify({
5400
- type: "response.function_call_arguments.delta",
5401
- output_index: parsed.output_index ?? 0,
5402
- delta: tail
5403
- })}`
5404
- );
5405
- }
5406
- if (typeof parsed.arguments === "string" && !shouldSkipToolArgRestore(name, parsed.arguments)) {
7606
+ const outputIndex = typeof parsed.output_index === "number" ? parsed.output_index : 0;
7607
+ const desc = {
7608
+ protocol: "openai_responses",
7609
+ kind: "tool_args",
7610
+ outputIndex
7611
+ };
7612
+ const { tail, toolName } = closeTool(desc, true);
7613
+ if (tail) extraEvents.push(formatChannelEvent(desc, tail));
7614
+ if (typeof parsed.arguments === "string" && !shouldSkipToolArgRestore(toolName, parsed.arguments)) {
5407
7615
  parsed.arguments = restoreJsonEncodedText(parsed.arguments, map);
5408
7616
  }
5409
7617
  outLines.push(`data: ${JSON.stringify(parsed)}`);
@@ -5423,9 +7631,13 @@ data: ${JSON.stringify({
5423
7631
  }
5424
7632
  if (parsed.type === "response.output_item.done" && isPlainObject(parsed.item)) {
5425
7633
  const item = parsed.item;
5426
- const key = `resp_args:${String(parsed.output_index ?? 0)}`;
5427
- const name = typeof item.name === "string" ? item.name : toolNames.get(key);
5428
- toolNames.delete(key);
7634
+ const outputIndex = typeof parsed.output_index === "number" ? parsed.output_index : 0;
7635
+ const trackedName = consumeToolName({
7636
+ protocol: "openai_responses",
7637
+ kind: "tool_args",
7638
+ outputIndex
7639
+ });
7640
+ const name = typeof item.name === "string" ? item.name : trackedName;
5429
7641
  if (typeof item.arguments === "string" && !shouldSkipToolArgRestore(name, item.arguments)) {
5430
7642
  item.arguments = restoreJsonEncodedText(item.arguments, map);
5431
7643
  }
@@ -5458,19 +7670,18 @@ data: ${JSON.stringify({
5458
7670
 
5459
7671
  ${joined}` : joined;
5460
7672
  }
5461
- let pendingCr = false;
5462
7673
  return {
5463
7674
  push(chunk) {
5464
- let text = pendingCr ? `\r${chunk}` : chunk;
5465
- pendingCr = text.endsWith("\r");
5466
- if (pendingCr) text = text.slice(0, -1);
5467
- sseBuffer += text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
7675
+ let text = frame.pendingCr ? `\r${chunk}` : chunk;
7676
+ frame.pendingCr = text.endsWith("\r");
7677
+ if (frame.pendingCr) text = text.slice(0, -1);
7678
+ frame.buffer += text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
5468
7679
  let out = "";
5469
7680
  for (; ; ) {
5470
- const sep3 = sseBuffer.indexOf("\n\n");
7681
+ const sep3 = frame.buffer.indexOf("\n\n");
5471
7682
  if (sep3 < 0) break;
5472
- const block = sseBuffer.slice(0, sep3);
5473
- sseBuffer = sseBuffer.slice(sep3 + 2);
7683
+ const block = frame.buffer.slice(0, sep3);
7684
+ frame.buffer = frame.buffer.slice(sep3 + 2);
5474
7685
  out += `${processEventBlock(block)}
5475
7686
 
5476
7687
  `;
@@ -5478,14 +7689,14 @@ ${joined}` : joined;
5478
7689
  return out;
5479
7690
  },
5480
7691
  flush() {
5481
- if (pendingCr) {
5482
- sseBuffer += "\n";
5483
- pendingCr = false;
7692
+ if (frame.pendingCr) {
7693
+ frame.buffer += "\n";
7694
+ frame.pendingCr = false;
5484
7695
  }
5485
7696
  const parts = [];
5486
- if (sseBuffer) {
5487
- parts.push(processEventBlock(sseBuffer));
5488
- sseBuffer = "";
7697
+ if (frame.buffer) {
7698
+ parts.push(processEventBlock(frame.buffer));
7699
+ frame.buffer = "";
5489
7700
  }
5490
7701
  const drained = drainRemainingStreams();
5491
7702
  if (drained.length > 0) {
@@ -5688,6 +7899,42 @@ function parseScopedMcpPolicy(urlPath, base) {
5688
7899
  }
5689
7900
  return { allowRawRestore, readOnly, approvalMode };
5690
7901
  }
7902
+ var McpSessionStore = class {
7903
+ constructor(onDispose, options = {}) {
7904
+ this.active = /* @__PURE__ */ new Map();
7905
+ this.closed = /* @__PURE__ */ new Set();
7906
+ this.onDispose = onDispose;
7907
+ this.maxActive = options.maxActive ?? 200;
7908
+ this.maxClosed = options.maxClosed ?? 500;
7909
+ }
7910
+ open(policy) {
7911
+ const id = `mcp_${randomUUID().slice(0, 16)}`;
7912
+ if (this.active.size >= this.maxActive) {
7913
+ const oldest = this.active.keys().next().value;
7914
+ if (oldest !== void 0) {
7915
+ this.close(oldest);
7916
+ }
7917
+ }
7918
+ this.closed.delete(id);
7919
+ this.active.set(id, policy);
7920
+ return id;
7921
+ }
7922
+ lookup(id) {
7923
+ const policy = this.active.get(id);
7924
+ if (policy) return { status: "active", policy };
7925
+ if (this.closed.has(id)) return { status: "closed" };
7926
+ return { status: "unknown" };
7927
+ }
7928
+ close(id) {
7929
+ this.active.delete(id);
7930
+ this.closed.add(id);
7931
+ this.onDispose(id);
7932
+ if (this.closed.size > this.maxClosed) {
7933
+ const first = this.closed.values().next().value;
7934
+ if (first !== void 0) this.closed.delete(first);
7935
+ }
7936
+ }
7937
+ };
5691
7938
  async function startMaskeraProxy(options = {}) {
5692
7939
  const host = options.host ?? "127.0.0.1";
5693
7940
  if (!options.allowNonLoopback && !isLoopbackBindHost(host)) {
@@ -5714,8 +7961,12 @@ async function startMaskeraProxy(options = {}) {
5714
7961
  readOnly: options.readOnly ?? false,
5715
7962
  approvalMode: options.approvalMode ?? "automatic"
5716
7963
  };
5717
- const mcpSessions = /* @__PURE__ */ new Map();
5718
- const closedMcpSessions = /* @__PURE__ */ new Set();
7964
+ const mcpSessionStore = new McpSessionStore((sessionId) => {
7965
+ const owner = `mcp:${sessionId}`;
7966
+ vault.clearOwner(owner);
7967
+ approvals.clearOwner(owner);
7968
+ mcpServerInstance?.clearOwner(owner);
7969
+ });
5719
7970
  const messageTokensBySession = /* @__PURE__ */ new Map();
5720
7971
  const externalToolTokensBySession = /* @__PURE__ */ new Map();
5721
7972
  if (auditLogPath) {
@@ -5897,6 +8148,7 @@ async function startMaskeraProxy(options = {}) {
5897
8148
  }
5898
8149
  vault.clearAll();
5899
8150
  approvals.clearAll();
8151
+ mcpServerInstance?.clearAllOwners();
5900
8152
  engine.clearCache();
5901
8153
  inspector.clear();
5902
8154
  messageTokensBySession.clear();
@@ -6047,14 +8299,7 @@ async function startMaskeraProxy(options = {}) {
6047
8299
  const incomingSessionId = typeof req.headers["mcp-session-id"] === "string" ? req.headers["mcp-session-id"].trim() : "";
6048
8300
  if (method === "DELETE") {
6049
8301
  if (incomingSessionId) {
6050
- mcpSessions.delete(incomingSessionId);
6051
- closedMcpSessions.add(incomingSessionId);
6052
- vault.clearOwner(`mcp:${incomingSessionId}`);
6053
- approvals.clearOwner(`mcp:${incomingSessionId}`);
6054
- if (closedMcpSessions.size > 500) {
6055
- const first = closedMcpSessions.values().next().value;
6056
- if (first !== void 0) closedMcpSessions.delete(first);
6057
- }
8302
+ mcpSessionStore.close(incomingSessionId);
6058
8303
  }
6059
8304
  res.writeHead(204, INSPECTOR_SECURITY_HEADERS);
6060
8305
  res.end();
@@ -6082,7 +8327,8 @@ async function startMaskeraProxy(options = {}) {
6082
8327
  res.end(JSON.stringify({ error: `Unsupported HTTP method ${method} for /mcp.` }));
6083
8328
  return;
6084
8329
  }
6085
- if (incomingSessionId && closedMcpSessions.has(incomingSessionId)) {
8330
+ const incomingSessionState = incomingSessionId ? mcpSessionStore.lookup(incomingSessionId) : null;
8331
+ if (incomingSessionState?.status === "closed") {
6086
8332
  res.writeHead(404, {
6087
8333
  ...INSPECTOR_SECURITY_HEADERS,
6088
8334
  "content-type": "application/json; charset=utf-8"
@@ -6110,7 +8356,7 @@ async function startMaskeraProxy(options = {}) {
6110
8356
  }
6111
8357
  const messages = Array.isArray(parsedMcp) ? parsedMcp : [parsedMcp];
6112
8358
  const isInit = messages.some((m) => isPlainObject(m) && m.method === "initialize");
6113
- if (!isInit && incomingSessionId && !mcpSessions.has(incomingSessionId)) {
8359
+ if (!isInit && incomingSessionState?.status === "unknown") {
6114
8360
  res.writeHead(404, {
6115
8361
  ...INSPECTOR_SECURITY_HEADERS,
6116
8362
  "content-type": "application/json; charset=utf-8"
@@ -6118,22 +8364,10 @@ async function startMaskeraProxy(options = {}) {
6118
8364
  res.end(JSON.stringify({ error: "Unknown MCP session." }));
6119
8365
  return;
6120
8366
  }
6121
- const sessionBasePolicy = (incomingSessionId ? mcpSessions.get(incomingSessionId) : void 0) ?? baseMcpPolicy;
8367
+ const sessionBasePolicy = incomingSessionState?.status === "active" ? incomingSessionState.policy : baseMcpPolicy;
6122
8368
  const effectivePolicy = parseScopedMcpPolicy(urlPath, sessionBasePolicy);
6123
8369
  const mcpServer = getMcpServer();
6124
- let responseSessionId = incomingSessionId;
6125
- if (isInit) {
6126
- responseSessionId = `mcp_${randomUUID().slice(0, 16)}`;
6127
- if (mcpSessions.size >= 200) {
6128
- const oldest = mcpSessions.keys().next().value;
6129
- if (oldest !== void 0) {
6130
- mcpSessions.delete(oldest);
6131
- vault.clearOwner(`mcp:${oldest}`);
6132
- approvals.clearOwner(`mcp:${oldest}`);
6133
- }
6134
- }
6135
- mcpSessions.set(responseSessionId, effectivePolicy);
6136
- }
8370
+ const responseSessionId = isInit ? mcpSessionStore.open(effectivePolicy) : incomingSessionId;
6137
8371
  const sessionOwner = responseSessionId ? `mcp:${responseSessionId}` : "mcp:stateless";
6138
8372
  const scopedPolicy = { ...effectivePolicy, sessionOwner };
6139
8373
  const responses = [];
@@ -6312,7 +8546,43 @@ async function startMaskeraProxy(options = {}) {
6312
8546
  mutate: true,
6313
8547
  onBinaryAttachment: (kind) => {
6314
8548
  binaryAttachments.add(kind);
6315
- }
8549
+ },
8550
+ redactDocument: async (bytes, info) => redactFile(
8551
+ bytes,
8552
+ async (text) => {
8553
+ const { result } = await engine.redact(text, {
8554
+ profile: options.profile,
8555
+ customTerms: options.customTerms
8556
+ });
8557
+ const applied = vault.apply(text, result, sessionId, proxyVaultOwner);
8558
+ stats.redactions += applied.totalRedactions;
8559
+ mergeCounts(stats.counts, applied.counts);
8560
+ if (applied.totalRedactions > 0) {
8561
+ if (!messageTokensForSession) {
8562
+ messageTokensForSession = /* @__PURE__ */ new Set();
8563
+ messageTokensBySession.set(sessionId, messageTokensForSession);
8564
+ }
8565
+ for (const tok of Object.keys(applied.map)) {
8566
+ messageTokensForSession.add(tok);
8567
+ }
8568
+ }
8569
+ if (messagePreviews.length < 6 && applied.redacted.trim()) {
8570
+ const snippet = applied.redacted.length > 1200 ? `${applied.redacted.slice(0, 1200)}...` : applied.redacted;
8571
+ messagePreviews.push(snippet);
8572
+ }
8573
+ return {
8574
+ text: applied.redacted,
8575
+ redactions: applied.redactions,
8576
+ map: applied.map,
8577
+ restore: (t) => vault.restore(t, { sessionId, owner: proxyVaultOwner }).restored
8578
+ };
8579
+ },
8580
+ {
8581
+ fileName: info.fileName,
8582
+ mimeType: info.mimeType,
8583
+ verify: true
8584
+ }
8585
+ )
6316
8586
  }
6317
8587
  );
6318
8588
  redactedPreview.push(...messagePreviews.length > 0 ? messagePreviews : fallbackPreviews);
@@ -6600,6 +8870,7 @@ ${body}`
6600
8870
  const actualPort = typeof addr === "object" && addr ? addr.port : requestedPort;
6601
8871
  boundPort = actualPort;
6602
8872
  boundUrl = `http://${host}:${actualPort}`;
8873
+ let lifecycle = { phase: "listening" };
6603
8874
  return {
6604
8875
  host,
6605
8876
  port: actualPort,
@@ -6617,12 +8888,22 @@ ${body}`
6617
8888
  sessions: vault.list().length
6618
8889
  }),
6619
8890
  close: async () => {
6620
- unsubscribeApprovals();
6621
- inspector.closeAll();
6622
- await new Promise((resolveClose, rejectClose) => {
6623
- server.close((err) => err ? rejectClose(err) : resolveClose());
6624
- });
6625
- await auditChain;
8891
+ if (lifecycle.phase === "closed") return;
8892
+ if (lifecycle.phase === "closing") return lifecycle.promise;
8893
+ const closingPromise = (async () => {
8894
+ try {
8895
+ unsubscribeApprovals();
8896
+ inspector.closeAll();
8897
+ await new Promise((resolveClose, rejectClose) => {
8898
+ server.close((err) => err ? rejectClose(err) : resolveClose());
8899
+ });
8900
+ await auditChain;
8901
+ } finally {
8902
+ lifecycle = { phase: "closed" };
8903
+ }
8904
+ })();
8905
+ lifecycle = { phase: "closing", promise: closingPromise };
8906
+ return closingPromise;
6626
8907
  }
6627
8908
  };
6628
8909
  }
@@ -6897,6 +9178,113 @@ async function runService(options) {
6897
9178
  detail: running ? `Installed and started ${serviceName} (${serviceFile}). Listening on ${proxyUrl}.` : `Installed ${serviceName} (${serviceFile}). Check logs if ${proxyUrl} is still warming up.`
6898
9179
  };
6899
9180
  }
9181
+
9182
+ // src/stdio.ts
9183
+ function parseElicitationResponse(resp) {
9184
+ if (resp.error) return { action: "cancel" };
9185
+ const resultObj = resp.result && typeof resp.result === "object" ? resp.result : {};
9186
+ const action = resultObj.action === "accept" || resultObj.action === "decline" || resultObj.action === "cancel" ? resultObj.action : "cancel";
9187
+ const content = resultObj.content && typeof resultObj.content === "object" && !Array.isArray(resultObj.content) ? resultObj.content : void 0;
9188
+ return { action, content };
9189
+ }
9190
+ function createStdioMcpTransport(options) {
9191
+ let state = {
9192
+ phase: "open",
9193
+ nextServerReqId: 1,
9194
+ pending: /* @__PURE__ */ new Map()
9195
+ };
9196
+ let chain = Promise.resolve();
9197
+ return {
9198
+ get phase() {
9199
+ return state.phase;
9200
+ },
9201
+ requestElicitation(req) {
9202
+ if (state.phase === "closed") {
9203
+ return Promise.resolve({ action: "cancel" });
9204
+ }
9205
+ const id = `maskera_elicit_${state.nextServerReqId++}`;
9206
+ const pending = state.pending;
9207
+ return new Promise((resolveReq) => {
9208
+ pending.set(id, resolveReq);
9209
+ options.writeStdout(
9210
+ `${JSON.stringify({
9211
+ jsonrpc: "2.0",
9212
+ id,
9213
+ method: "elicitation/create",
9214
+ params: req
9215
+ })}
9216
+ `
9217
+ );
9218
+ });
9219
+ },
9220
+ handleLine(line, handleMessage) {
9221
+ if (state.phase === "closed") return;
9222
+ const trimmed = line.trim();
9223
+ if (!trimmed) return;
9224
+ let parsed;
9225
+ try {
9226
+ parsed = JSON.parse(trimmed);
9227
+ } catch {
9228
+ chain = chain.then(() => {
9229
+ options.writeStdout(
9230
+ `${JSON.stringify({
9231
+ jsonrpc: "2.0",
9232
+ id: null,
9233
+ error: { code: -32700, message: "Parse error" }
9234
+ })}
9235
+ `
9236
+ );
9237
+ });
9238
+ return;
9239
+ }
9240
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed) && !("method" in parsed) && typeof parsed.id === "string") {
9241
+ const resp = parsed;
9242
+ const resolvePending = state.pending.get(resp.id);
9243
+ if (resolvePending) {
9244
+ state.pending.delete(resp.id);
9245
+ resolvePending(parseElicitationResponse(resp));
9246
+ return;
9247
+ }
9248
+ }
9249
+ chain = chain.then(async () => {
9250
+ try {
9251
+ const response = await handleMessage(parsed);
9252
+ if (response) {
9253
+ options.writeStdout(`${JSON.stringify(response)}
9254
+ `);
9255
+ }
9256
+ } catch (err) {
9257
+ const message = err instanceof Error ? err.message : String(err);
9258
+ options.writeStderr(`[maskera-mcp] internal error: ${message}
9259
+ `);
9260
+ const maybeId = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed.id : void 0;
9261
+ if (typeof maybeId === "string" || typeof maybeId === "number" || maybeId === null) {
9262
+ options.writeStdout(
9263
+ `${JSON.stringify({
9264
+ jsonrpc: "2.0",
9265
+ id: maybeId,
9266
+ error: { code: -32603, message: "Internal error" }
9267
+ })}
9268
+ `
9269
+ );
9270
+ }
9271
+ }
9272
+ });
9273
+ },
9274
+ close() {
9275
+ if (state.phase === "closed") return;
9276
+ const pendingResolvers = [...state.pending.values()];
9277
+ state.pending.clear();
9278
+ state = { phase: "closed" };
9279
+ for (const resolvePending of pendingResolvers) {
9280
+ resolvePending({ action: "cancel" });
9281
+ }
9282
+ },
9283
+ whenIdle() {
9284
+ return chain;
9285
+ }
9286
+ };
9287
+ }
6900
9288
  function openUrlInBrowser(url, platform = process.platform) {
6901
9289
  try {
6902
9290
  let cmd;
@@ -6990,25 +9378,33 @@ async function runWrap(options) {
6990
9378
  stdio: "inherit",
6991
9379
  env: childEnv
6992
9380
  });
6993
- const forwardSigInt = () => {
6994
- if (!child.killed) child.kill("SIGINT");
6995
- };
6996
- const forwardSigTerm = () => {
6997
- if (!child.killed) child.kill("SIGTERM");
9381
+ let childState = { phase: "running" };
9382
+ const forwardSignal = (sig) => {
9383
+ if (childState.phase !== "running") return;
9384
+ if (!child.killed) child.kill(sig);
6998
9385
  };
9386
+ const forwardSigInt = () => forwardSignal("SIGINT");
9387
+ const forwardSigTerm = () => forwardSignal("SIGTERM");
6999
9388
  process.on("SIGINT", forwardSigInt);
7000
9389
  process.on("SIGTERM", forwardSigTerm);
7001
9390
  const { exitCode, signal } = await new Promise((resolveExit, rejectExit) => {
7002
- child.on("error", rejectExit);
9391
+ const cleanupSignals = () => {
9392
+ process.off("SIGINT", forwardSigInt);
9393
+ process.off("SIGTERM", forwardSigTerm);
9394
+ };
9395
+ child.on("error", (err) => {
9396
+ if (childState.phase !== "running") return;
9397
+ childState = { phase: "failed", error: err };
9398
+ cleanupSignals();
9399
+ rejectExit(err);
9400
+ });
7003
9401
  child.on("exit", (code, sig) => {
7004
- resolveExit({
7005
- exitCode: code ?? (sig ? 1 : 0),
7006
- signal: sig
7007
- });
9402
+ if (childState.phase !== "running") return;
9403
+ const resolvedCode = code ?? (sig ? 1 : 0);
9404
+ childState = { phase: "exited", exitCode: resolvedCode, signal: sig };
9405
+ cleanupSignals();
9406
+ resolveExit({ exitCode: resolvedCode, signal: sig });
7008
9407
  });
7009
- }).finally(() => {
7010
- process.off("SIGINT", forwardSigInt);
7011
- process.off("SIGTERM", forwardSigTerm);
7012
9408
  });
7013
9409
  const session = running.stats();
7014
9410
  let receiptSavedPath;
@@ -7045,6 +9441,6 @@ async function runWrap(options) {
7045
9441
  }
7046
9442
  }
7047
9443
 
7048
- export { ApprovalBroker, LAUNCHD_LABEL, MASKERA_PROMPTS, MASKERA_SKILL_MARKDOWN, MASKERA_SKILL_URI, MASKERA_STATUS_URI, ProxyInspector, SERVER_NAME, SERVER_VERSION, SUPPORTED_CLIENTS, SYSTEMD_UNIT, SessionVault, StreamingRestorer, buildCustomTermsDetector, createFileGuard, createMaskeraEngine, createMaskeraMcpServer, createModelProgressLogger, createSseRestorer, deriveProxySessionId, detectInstalledClients, extractGuardText, formatDoctorReport, isInstallClient, isLikelyEnglishSystemPrompt, normalizeMixedScriptHomoglyphs, openUrlInBrowser, redactLlmRequestBody, renderInspectorHtml, renderLaunchdPlist, renderMaskeraPrompt, renderSystemdUnit, restoreLlmResponseBody, runDoctor, runGuard, runGuardViaWarmProxy, runInstall, runService, runWrap, startMaskeraProxy, writeDoctorReceipt };
9444
+ export { ApprovalBroker, LAUNCHD_LABEL, MASKERA_PROMPTS, MASKERA_SKILL_MARKDOWN, MASKERA_SKILL_URI, MASKERA_STATUS_URI, ProxyInspector, SERVER_NAME, SERVER_VERSION, SUPPORTED_CLIENTS, SYSTEMD_UNIT, SessionVault, StreamingRestorer, buildCustomTermsDetector, createFileGuard, createMaskeraEngine, createMaskeraMcpServer, createModelProgressLogger, createSseRestorer, createStdioMcpTransport, deriveProxySessionId, detectInstalledClients, extractGuardText, formatDoctorReport, isInstallClient, isLikelyEnglishSystemPrompt, normalizeMixedScriptHomoglyphs, openUrlInBrowser, redactLlmRequestBody, renderInspectorHtml, renderLaunchdPlist, renderMaskeraPrompt, renderSystemdUnit, restoreLlmResponseBody, runDoctor, runGuard, runGuardViaWarmProxy, runInstall, runService, runWrap, startMaskeraProxy, writeDoctorReceipt };
7049
9445
  //# sourceMappingURL=index.js.map
7050
9446
  //# sourceMappingURL=index.js.map