@maskera/mcp 0.4.3 → 0.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -190,7 +190,7 @@ function createMaskeraEngine(options = {}) {
190
190
  if (!recognizer) {
191
191
  const dtype = options.nerOptions?.dtype ?? (options.nerOptions?.localModelPath ? "q4" : "q8");
192
192
  const loadStartedAt = Date.now();
193
- options.onModelStatus?.({ phase: "loading", model });
193
+ options.onModelStatus?.({ phase: "loading", model, dtype });
194
194
  recognizer = createNerRecognizer({
195
195
  ...options.nerOptions,
196
196
  model,
@@ -401,6 +401,11 @@ function createMaskeraEngine(options = {}) {
401
401
  }
402
402
  };
403
403
  }
404
+ var MODEL_DOWNLOAD_MB = { q4: 43, q8: 59 };
405
+ function downloadSize(dtype) {
406
+ const mb = dtype ? MODEL_DOWNLOAD_MB[dtype] : void 0;
407
+ return mb ? `, ~${mb} MB on first run` : "";
408
+ }
404
409
  function createModelProgressLogger(write = (line) => process.stderr.write(`${line}
405
410
  `), delayMs = 350) {
406
411
  let timer = null;
@@ -412,7 +417,7 @@ function createModelProgressLogger(write = (line) => process.stderr.write(`${lin
412
417
  timer = setTimeout(() => {
413
418
  announcedLoading = true;
414
419
  write(
415
- `[maskera] Loading Swedish ONNX model (${event.model}, ~43 MB on first run, cached locally)...`
420
+ `[maskera] Loading Swedish ONNX model (${event.model}${downloadSize(event.dtype)}, cached locally)...`
416
421
  );
417
422
  }, delayMs);
418
423
  timer.unref?.();
@@ -754,7 +759,7 @@ description: Redact Swedish personal data (names, personnummer, addresses, phone
754
759
 
755
760
  # Maskera: local Swedish PII redaction
756
761
 
757
- Maskera runs 100% locally on-device using deterministic Swedish rules plus the 43 MB Swedish ONNX NER model (\`joelhagvall/maskera-sv-ner\`). Raw PII and restore maps stay local so cloud LLMs only see placeholders such as \`[NAMN_1]\` and \`[PERSONNUMMER_1]\`.
762
+ Maskera runs 100% locally on-device using deterministic Swedish rules plus the Swedish ONNX NER model (\`joelhagvall/maskera-sv-ner\`). Raw PII and restore maps stay local so cloud LLMs only see placeholders such as \`[NAMN_1]\` and \`[PERSONNUMMER_1]\`.
758
763
 
759
764
  ## Choose the right mode
760
765
 
@@ -775,7 +780,7 @@ Pick by where the text comes from: **proxy for text typed straight into the chat
775
780
  # Same warm process also serves Streamable HTTP MCP:
776
781
  # http://127.0.0.1:8787/mcp (supports ?no_raw_restore=1&read_only=1&approval_mode=browser)
777
782
  \`\`\`
778
- - Claude Desktop: Help -> Troubleshooting -> Enable Developer Mode, then Developer -> Configure Third-Party Inference. Set Inference provider to **Gateway**, Credential kind **Static API key**, Gateway base URL \`http://127.0.0.1:8787\` (no \`/v1\`), Gateway API key = the user's Anthropic API key, Gateway auth scheme **x-api-key**. Apply Changes, then Save & Restart. Full guide: \`https://maskera.dev/docs/guides\`.
783
+ - Claude Desktop: Help -> Troubleshooting -> Enable Developer Mode, then Developer -> Configure Third-Party Inference. Set Inference provider to **Gateway**, Credential kind **Static API key**, Gateway base URL \`http://127.0.0.1:8787\` (no \`/v1\`), Gateway API key = the user's Anthropic API key, Gateway auth scheme **x-api-key**. Apply Changes, then Save & Restart. Full guide: \`https://maskera.dev/en/docs/clients#claude-desktop\`.
779
784
  - Routes Anthropic (\`/v1/messages\`) and OpenAI (\`/v1/chat/completions\`, \`/v1/responses\`) automatically, or set \`--upstream <url>\`.
780
785
  - Restores placeholders transparently in JSON, tool arguments and chunk-split SSE streams.
781
786
  - Fails closed (\`502\`) if local redaction fails. Inspect counts only at \`http://127.0.0.1:8787/_maskera/status\`.
@@ -1162,7 +1167,7 @@ var COUNTS_SCHEMA = {
1162
1167
  var TOOLS = [
1163
1168
  {
1164
1169
  name: "maskera_redact",
1165
- description: "Redact Swedish PII (names, personnummer, addresses, emails, phones, IBAN, etc.) locally on-device using Maskera's 43 MB Swedish NER model and deterministic rules. Stores the restore map locally under session_id so placeholders stay consistent across calls and can be restored later without exposing raw PII to the LLM.",
1170
+ description: "Redact Swedish PII (names, personnummer, addresses, emails, phones, IBAN, etc.) locally on-device using Maskera's Swedish NER model and deterministic rules. Stores the restore map locally under session_id so placeholders stay consistent across calls and can be restored later without exposing raw PII to the LLM.",
1166
1171
  annotations: {
1167
1172
  title: "Redact Swedish PII locally",
1168
1173
  readOnlyHint: true,
@@ -1901,7 +1906,7 @@ function createMaskeraMcpServer(options = {}) {
1901
1906
  );
1902
1907
  }
1903
1908
  const response = await requestElicitation({
1904
- message: `${input.tool} wants to release ${input.placeholderCount} original Swedish PII value(s) into the model context (${input.reason}). Approve only if you intend to send raw PII to the LLM.`,
1909
+ message: `${input.tool} wants to release ${input.placeholderCount} original Swedish PII value(s) into the model context (${input.reason}).`,
1905
1910
  requestedSchema: {
1906
1911
  type: "object",
1907
1912
  properties: {
@@ -3702,6 +3707,11 @@ function renderInspectorHtml(info) {
3702
3707
  white-space: pre-wrap;
3703
3708
  word-break: break-word;
3704
3709
  }
3710
+ .preview.err-preview {
3711
+ border-color: var(--err);
3712
+ background: var(--err-bg);
3713
+ color: var(--err);
3714
+ }
3705
3715
  .tok {
3706
3716
  display: inline-block;
3707
3717
  padding: 0 4px;
@@ -3734,7 +3744,7 @@ function renderInspectorHtml(info) {
3734
3744
  </div>
3735
3745
  <div class="actions">
3736
3746
  <button id="selftest-btn" type="button" class="primary">K\xF6r sj\xE4lvtest</button>
3737
- <button id="reveal-btn" type="button">Visa originalv\xE4rden lokalt</button>
3747
+ <button id="reveal-btn" type="button">Visa originalv\xE4rden</button>
3738
3748
  <button id="clear-btn" type="button">Rensa minne</button>
3739
3749
  </div>
3740
3750
  </header>
@@ -3775,6 +3785,16 @@ function renderInspectorHtml(info) {
3775
3785
 
3776
3786
  const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ "&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;" }[c]));
3777
3787
  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>");
3788
+ const formatLocalTime = (iso) => {
3789
+ if (!iso) return "";
3790
+ const d = new Date(iso);
3791
+ if (Number.isNaN(d.getTime())) return String(iso).slice(11, 19);
3792
+ try {
3793
+ return d.toLocaleTimeString("sv-SE", { hour12: false });
3794
+ } catch {
3795
+ return String(iso).slice(11, 19);
3796
+ }
3797
+ };
3778
3798
 
3779
3799
  function renderReceipt() {
3780
3800
  if (!lastReceipt) {
@@ -3787,7 +3807,7 @@ function renderInspectorHtml(info) {
3787
3807
  return '<li><span class="receipt-tag' + cls + '">[' + esc(c.status) + ']</span><span><strong>' + esc(c.name) + ':</strong> ' + esc(c.detail) + '</span></li>';
3788
3808
  }).join("");
3789
3809
  const proofHtml = r.sampleProof && !r.sampleProof.rawPiiLeaked
3790
- ? '<p class="body-label">Verifierat maskerat utdata (0 l\xE4ckor, \xE5terst\xE4llning klar):</p><pre class="preview">' + highlightTokens(r.sampleProof.redactedPreview) + '</pre>'
3810
+ ? '<p class="body-label">Maskerat utdata:</p><pre class="preview">' + highlightTokens(r.sampleProof.redactedPreview) + '</pre>'
3791
3811
  : "";
3792
3812
  receiptRoot.innerHTML =
3793
3813
  '<section class="receipt-box"><div class="receipt-head"><h2>Setup-kvitto (' + (r.ok ? "OK" : "FEL") + ' \xB7 v' + esc(r.version) + ' \xB7 ' + esc(r.sampleProof?.modeUsed || r.mode) + ')</h2>' +
@@ -3884,7 +3904,7 @@ function renderInspectorHtml(info) {
3884
3904
  const r = await fetch("/_maskera/vault", { headers: { "x-maskera-reveal": "1" } });
3885
3905
  const d = await r.json();
3886
3906
  const rows = (d.entries || []).map((e) => "<tr><td>" + esc(e.sessionId) + "</td><td><span class=\\"tok\\">" + esc(e.token) + "</span></td><td>" + esc(e.value) + "</td></tr>").join("");
3887
- vaultRoot.innerHTML = '<section class="vault-box"><h2>Lokal \xE5terst\xE4llningsnyckel (stannar i RAM)</h2><p>D\xF6lj den h\xE4r vyn innan du delar sk\xE4rm.</p>' +
3907
+ vaultRoot.innerHTML = '<section class="vault-box"><h2>\xC5terst\xE4llningsnyckel</h2>' +
3888
3908
  (rows ? "<table><thead><tr><th>Session</th><th>Platsh\xE5llare</th><th>Originalv\xE4rde</th></tr></thead><tbody>" + rows + "</tbody></table>" : "<p>Inga lagrade v\xE4rden \xE4n.</p>") +
3889
3909
  "</section>";
3890
3910
  } catch {}
@@ -3893,8 +3913,8 @@ function renderInspectorHtml(info) {
3893
3913
  function render() {
3894
3914
  if (!items.length) {
3895
3915
  feedEl.innerHTML =
3896
- '<div class="empty"><p class="empty-title">V\xE4ntar p\xE5 f\xF6rsta riktiga anropet fr\xE5n din AI-klient.</p>' +
3897
- 'Klicka p\xE5 <strong>K\xF6r sj\xE4lvtest</strong> ovan f\xF6r ett omedelbart kvitto, eller klistra in testmeningen i din klient och se platsh\xE5llarna dyka upp h\xE4r:' +
3916
+ '<div class="empty"><p class="empty-title">Inga anrop \xE4nnu.</p>' +
3917
+ 'Skicka ett prov fr\xE5n din klient s\xE5 visas maskeringen h\xE4r:' +
3898
3918
  '<div class="sample-row"><span class="sample-text">' + esc(SAMPLE_PROMPT) + '</span><button id="copy-sample-btn" type="button">Kopiera testmening</button></div>' +
3899
3919
  '<code>npx -y @maskera/mcp wrap -- claude\\nANTHROPIC_BASE_URL=${safeUrl} claude\\nOPENAI_BASE_URL=${safeUrl}/v1 codex\\nclaude mcp add --transport http maskera ${safeMcpUrl}</code></div>';
3900
3920
  const copyBtn = document.getElementById("copy-sample-btn");
@@ -3914,15 +3934,16 @@ function renderInspectorHtml(info) {
3914
3934
  }
3915
3935
  for (const it of items) seenIds.add(it.id);
3916
3936
  feedEl.innerHTML = '<div class="list">' + items.map((it) => {
3917
- const time = (it.timestamp || "").slice(11, 19);
3937
+ const time = formatLocalTime(it.timestamp);
3918
3938
  const tags = Object.entries(it.counts || {}).map(([k, v]) => '<span class="count-tag">' + esc(k) + " \xD7" + v + "</span>").join("");
3919
3939
  const previews = (it.redactedPreview || []).map((p) => '<pre class="preview">' + highlightTokens(p) + "</pre>").join("");
3940
+ const errBlock = it.errorDetail ? '<p class="body-label">Svar fr\xE5n API (fel):</p><pre class="preview err-preview">' + esc(it.errorDetail) + "</pre>" : "";
3920
3941
  const statusCls = it.status >= 200 && it.status < 400 ? "" : " err";
3921
3942
  const isOpen = openIds.has(it.id);
3922
3943
  return '<details class="item" data-id="' + esc(it.id) + '"' + (isOpen ? " open" : "") + '>' +
3923
3944
  '<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>' +
3924
3945
  '<span class="right"><span>' + (it.streamed ? "SSE" : "JSON") + '</span><span>' + it.durationMs + ' ms</span><span>' + esc(time) + '</span></span></summary>' +
3925
- '<div class="body"><p class="body-label">Vad som skickades vidare (0 r\xE5 PII):</p>' + (previews || '<pre class="preview">(ingen text i anropet)</pre>') + '</div></details>';
3946
+ '<div class="body">' + errBlock + '<p class="body-label">Skickat vidare:</p>' + (previews || '<pre class="preview">(ingen text i anropet)</pre>') + '</div></details>';
3926
3947
  }).join("") + "</div>";
3927
3948
  for (const det of feedEl.querySelectorAll("details.item")) {
3928
3949
  det.addEventListener("toggle", () => {
@@ -3938,7 +3959,7 @@ function renderInspectorHtml(info) {
3938
3959
  revealBtn.addEventListener("click", () => {
3939
3960
  reveal = !reveal;
3940
3961
  revealBtn.classList.toggle("active", reveal);
3941
- revealBtn.textContent = reveal ? "D\xF6lj originalv\xE4rden" : "Visa originalv\xE4rden lokalt";
3962
+ revealBtn.textContent = reveal ? "D\xF6lj originalv\xE4rden" : "Visa originalv\xE4rden";
3942
3963
  void refreshVault();
3943
3964
  });
3944
3965
 
@@ -4125,7 +4146,7 @@ function restoreJsonLeaves(value, map) {
4125
4146
  }
4126
4147
  return value;
4127
4148
  }
4128
- var MASKERA_VAULT_TOOL_RE = /(?:^|__)maskera_(?:write_file|restore|clear_session)$/;
4149
+ var MASKERA_VAULT_TOOL_RE = /(?:^|[^a-zA-Z0-9]|_)maskera_(?:write_file|restore|clear_session)$/;
4129
4150
  var MASKERA_VAULT_CODE_RE = /\bmaskera_(?:write_file|restore)\b/;
4130
4151
  function isMaskeraVaultToolName(name) {
4131
4152
  return typeof name === "string" && MASKERA_VAULT_TOOL_RE.test(name);
@@ -4136,10 +4157,80 @@ function shouldSkipToolArgRestore(toolName, argsText) {
4136
4157
  return false;
4137
4158
  }
4138
4159
  var SWEDISH_DIACRITIC_RE = /[åäöÅÄÖ]/;
4139
- var SWEDISH_SIGNAL_WORD_RE = /\b(?:och|inte|ska|eller|enligt|kund|personnummer|svenska|sekretess|arbetsgivare|utbetalning|sammanfatta|skriv|svara|nedan|uppgifter)\b/i;
4160
+ var SWEDISH_STOP_WORDS = /* @__PURE__ */ new Set([
4161
+ "och",
4162
+ "att",
4163
+ "det",
4164
+ "som",
4165
+ "f\xF6r",
4166
+ "med",
4167
+ "har",
4168
+ "inte",
4169
+ "p\xE5",
4170
+ "\xE4r",
4171
+ "av",
4172
+ "till",
4173
+ "ett",
4174
+ "fr\xE5n",
4175
+ "kan",
4176
+ "ska",
4177
+ "eller",
4178
+ "vid",
4179
+ "s\xE5",
4180
+ "men",
4181
+ "den",
4182
+ "jag",
4183
+ "din",
4184
+ "ditt",
4185
+ "mitt",
4186
+ "var",
4187
+ "blev",
4188
+ "enligt",
4189
+ "kund",
4190
+ "personnummer",
4191
+ "svenska",
4192
+ "sekretess",
4193
+ "arbetsgivare",
4194
+ "utbetalning",
4195
+ "sammanfatta",
4196
+ "skriv",
4197
+ "svara",
4198
+ "nedan",
4199
+ "uppgifter",
4200
+ "v\xE4nliga",
4201
+ "h\xE4lsningar",
4202
+ "\xE4rendet",
4203
+ "\xE4rende",
4204
+ "mejl",
4205
+ "brev",
4206
+ "patient",
4207
+ "namn",
4208
+ "telefon",
4209
+ "adress"
4210
+ ]);
4211
+ var CLI_SYSTEM_HEADER_RE = /^(?:x-anthropic-billing-header:|you are claude code\b|you are a claude agent\b|you are codex\b|you are opencode\b|sessionstart:|# gitstatus\b|current branch:|recent commits:|status:)/i;
4140
4212
  var ENGLISH_BOILERPLATE_WORDS = /* @__PURE__ */ new Set([
4141
4213
  "the",
4142
4214
  "and",
4215
+ "to",
4216
+ "of",
4217
+ "in",
4218
+ "is",
4219
+ "it",
4220
+ "on",
4221
+ "as",
4222
+ "be",
4223
+ "by",
4224
+ "or",
4225
+ "an",
4226
+ "at",
4227
+ "if",
4228
+ "do",
4229
+ "no",
4230
+ "yes",
4231
+ "so",
4232
+ "but",
4233
+ "not",
4143
4234
  "you",
4144
4235
  "your",
4145
4236
  "with",
@@ -4147,7 +4238,6 @@ var ENGLISH_BOILERPLATE_WORDS = /* @__PURE__ */ new Set([
4147
4238
  "this",
4148
4239
  "from",
4149
4240
  "are",
4150
- "not",
4151
4241
  "when",
4152
4242
  "use",
4153
4243
  "must",
@@ -4155,7 +4245,9 @@ var ENGLISH_BOILERPLATE_WORDS = /* @__PURE__ */ new Set([
4155
4245
  "never",
4156
4246
  "always",
4157
4247
  "tools",
4248
+ "tool",
4158
4249
  "files",
4250
+ "file",
4159
4251
  "code",
4160
4252
  "return",
4161
4253
  "output",
@@ -4163,24 +4255,296 @@ var ENGLISH_BOILERPLATE_WORDS = /* @__PURE__ */ new Set([
4163
4255
  "assistant",
4164
4256
  "instructions",
4165
4257
  "command",
4166
- "user"
4258
+ "commands",
4259
+ "user",
4260
+ "for",
4261
+ "into",
4262
+ "only",
4263
+ "before",
4264
+ "after",
4265
+ "run",
4266
+ "check",
4267
+ "edit",
4268
+ "read",
4269
+ "write",
4270
+ "git",
4271
+ "branch",
4272
+ "commit",
4273
+ "push",
4274
+ "test",
4275
+ "tests",
4276
+ "error",
4277
+ "path",
4278
+ "directory",
4279
+ "repository",
4280
+ "session",
4281
+ "agent",
4282
+ "prompt",
4283
+ "message",
4284
+ "system",
4285
+ "default",
4286
+ "without",
4287
+ "can",
4288
+ "will",
4289
+ "each",
4290
+ "all",
4291
+ "any",
4292
+ "every",
4293
+ "about",
4294
+ "more",
4295
+ "also",
4296
+ "make",
4297
+ "keep",
4298
+ "does",
4299
+ "have",
4300
+ "has",
4301
+ "been",
4302
+ "its",
4303
+ "their",
4304
+ "them",
4305
+ "then",
4306
+ "than",
4307
+ "using",
4308
+ "following",
4309
+ "other",
4310
+ "same",
4311
+ "first",
4312
+ "next",
4313
+ "existing",
4314
+ "changes",
4315
+ "where",
4316
+ "which",
4317
+ "what",
4318
+ "how",
4319
+ "why",
4320
+ "because",
4321
+ "unless",
4322
+ "instead",
4323
+ "below",
4324
+ "above",
4325
+ "work",
4326
+ "working",
4327
+ "task",
4328
+ "tasks",
4329
+ "skill",
4330
+ "skills",
4331
+ "rule",
4332
+ "rules",
4333
+ "repo",
4334
+ "project",
4335
+ "build",
4336
+ "lint",
4337
+ "hook",
4338
+ "hooks",
4339
+ "memory",
4340
+ "local",
4341
+ "remote",
4342
+ "status",
4343
+ "current",
4344
+ "recent"
4167
4345
  ]);
4168
- var ASCII_WORD_RE = /\b[a-z]{2,}\b/g;
4169
- function isLikelyEnglishSystemPrompt(text) {
4170
- if (text.length < 240) return false;
4171
- if (SWEDISH_DIACRITIC_RE.test(text)) return false;
4172
- if (SWEDISH_SIGNAL_WORD_RE.test(text)) return false;
4173
- const found = /* @__PURE__ */ new Set();
4174
- const lower = text.toLowerCase();
4175
- ASCII_WORD_RE.lastIndex = 0;
4176
- for (let m = ASCII_WORD_RE.exec(lower); m !== null; m = ASCII_WORD_RE.exec(lower)) {
4346
+ var WORD_TOKEN_RE2 = /[a-zåäö]{2,}/gi;
4347
+ var SYSTEM_REMINDER_SPLIT_RE = /(<system-reminder>[\s\S]*?<\/system-reminder>)/g;
4348
+ var FENCED_CODE_SPLIT_RE = /(```[\s\S]*?```)/g;
4349
+ var GIT_STATUS_LINE_RE = /^(?:[MADRCU?!]{1,2}\s+\S|[0-9a-f]{7,40}\s+\S)/;
4350
+ var XML_TAG_ONLY_RE = /^<\/?[a-z][a-z0-9_-]*(?:\s[^>]*)?>$/i;
4351
+ var MARKDOWN_HEADING_RE = /^#{1,6}\s+\S/;
4352
+ var CODE_SIGNATURE_RE = /(?:\/\*\*|\?\s*:\s*(?:string|number|boolean|object|unknown|any|Record|Array)\b|\b(?:string|number|boolean)\s*\||\b(?:interface|namespace|type)\s+[A-Z]\w*|\bPromise<|=>\s*\{)/;
4353
+ var BROWSER_PROBE_PATHS = /* @__PURE__ */ new Set([
4354
+ "/favicon.ico",
4355
+ "/apple-touch-icon.png",
4356
+ "/apple-touch-icon-precomposed.png",
4357
+ "/robots.txt"
4358
+ ]);
4359
+ var PLACEHOLDER_TOKEN_RE = /\[[A-ZÅÄÖ][A-ZÅÄÖ0-9_]*_\d+\]/g;
4360
+ function collectPlaceholdersFromUnknown(value, out) {
4361
+ if (typeof value === "string") {
4362
+ if (!value.includes("[")) return;
4363
+ const matches = value.match(PLACEHOLDER_TOKEN_RE);
4364
+ if (matches) {
4365
+ for (const tok of matches) out.add(tok);
4366
+ }
4367
+ return;
4368
+ }
4369
+ if (Array.isArray(value)) {
4370
+ for (const item of value) collectPlaceholdersFromUnknown(item, out);
4371
+ return;
4372
+ }
4373
+ if (isPlainObject(value)) {
4374
+ for (const v of Object.values(value)) collectPlaceholdersFromUnknown(v, out);
4375
+ }
4376
+ }
4377
+ function collectExternalToolResultPlaceholders(body, out) {
4378
+ if (Array.isArray(body.messages)) {
4379
+ for (const msg of body.messages) {
4380
+ if (!isPlainObject(msg)) continue;
4381
+ if (msg.role === "tool") {
4382
+ collectPlaceholdersFromUnknown(msg.content, out);
4383
+ continue;
4384
+ }
4385
+ if (Array.isArray(msg.content)) {
4386
+ for (const block of msg.content) {
4387
+ if (isPlainObject(block) && block.type === "tool_result") {
4388
+ collectPlaceholdersFromUnknown(block.content, out);
4389
+ }
4390
+ }
4391
+ }
4392
+ }
4393
+ }
4394
+ if (Array.isArray(body.input)) {
4395
+ for (const item of body.input) {
4396
+ if (isPlainObject(item) && item.type === "function_call_output") {
4397
+ collectPlaceholdersFromUnknown(item.output, out);
4398
+ }
4399
+ }
4400
+ }
4401
+ }
4402
+ function isToolCatalogJson(text) {
4403
+ const trimmed = text.trim();
4404
+ if (!trimmed.startsWith("{") || !trimmed.includes('"items"') || !trimmed.includes('"tools.')) {
4405
+ return false;
4406
+ }
4407
+ try {
4408
+ const parsed = JSON.parse(trimmed);
4409
+ if (!isPlainObject(parsed) || !Array.isArray(parsed.items) || parsed.items.length === 0) {
4410
+ return false;
4411
+ }
4412
+ return parsed.items.every(
4413
+ (item) => isPlainObject(item) && typeof item.path === "string" && item.path.startsWith("tools.") && (item.description === void 0 || typeof item.description === "string")
4414
+ );
4415
+ } catch {
4416
+ return false;
4417
+ }
4418
+ }
4419
+ function isEnglishSystemParagraph(paragraph) {
4420
+ const trimmed = paragraph.trim();
4421
+ if (!trimmed) return true;
4422
+ if (XML_TAG_ONLY_RE.test(trimmed)) return true;
4423
+ if (trimmed.startsWith("```") && trimmed.endsWith("```")) return true;
4424
+ if (CLI_SYSTEM_HEADER_RE.test(trimmed)) return true;
4425
+ const nonEmptyLines = trimmed.split("\n").map((l) => l.trim()).filter(Boolean);
4426
+ if (nonEmptyLines.length > 0 && nonEmptyLines.every(
4427
+ (l) => GIT_STATUS_LINE_RE.test(l) || XML_TAG_ONLY_RE.test(l) || CLI_SYSTEM_HEADER_RE.test(l) || l.startsWith("(use ")
4428
+ )) {
4429
+ return true;
4430
+ }
4431
+ let enTotal = 0;
4432
+ const enDistinct = /* @__PURE__ */ new Set();
4433
+ let svTotal = 0;
4434
+ let svDiacriticWords = 0;
4435
+ const lower = trimmed.toLowerCase();
4436
+ WORD_TOKEN_RE2.lastIndex = 0;
4437
+ for (let m = WORD_TOKEN_RE2.exec(lower); m !== null; m = WORD_TOKEN_RE2.exec(lower)) {
4177
4438
  const word = m[0];
4178
- if (word && ENGLISH_BOILERPLATE_WORDS.has(word)) {
4179
- found.add(word);
4180
- if (found.size >= 6) return true;
4439
+ if (!word) continue;
4440
+ if (SWEDISH_STOP_WORDS.has(word)) {
4441
+ svTotal += 1;
4442
+ }
4443
+ if (SWEDISH_DIACRITIC_RE.test(word)) {
4444
+ svDiacriticWords += 1;
4445
+ }
4446
+ if (ENGLISH_BOILERPLATE_WORDS.has(word)) {
4447
+ enTotal += 1;
4448
+ enDistinct.add(word);
4181
4449
  }
4182
4450
  }
4183
- return false;
4451
+ if (nonEmptyLines.length === 1 && MARKDOWN_HEADING_RE.test(trimmed) && svTotal === 0 && svDiacriticWords === 0 && trimmed.length < 120) {
4452
+ return true;
4453
+ }
4454
+ if (svTotal === 0 && svDiacriticWords === 0 && CODE_SIGNATURE_RE.test(trimmed)) {
4455
+ return true;
4456
+ }
4457
+ if (trimmed.length < 60 && enDistinct.size < 4) return false;
4458
+ const svSignal = svTotal + svDiacriticWords;
4459
+ if (svSignal === 0) {
4460
+ const minDistinct = trimmed.length >= 240 ? 5 : 3;
4461
+ return enDistinct.size >= minDistinct;
4462
+ }
4463
+ return enTotal >= 12 && enDistinct.size >= 6 && enTotal >= svSignal * 6;
4464
+ }
4465
+ function isLikelyEnglishSystemPrompt(text) {
4466
+ const trimmed = text.trim();
4467
+ if (!trimmed) return false;
4468
+ if (trimmed.includes("\n\n")) {
4469
+ const paragraphs = trimmed.split(/\n{2,}/).map((p) => p.trim()).filter(Boolean);
4470
+ return paragraphs.length > 0 && paragraphs.every((p) => isEnglishSystemParagraph(p));
4471
+ }
4472
+ return isEnglishSystemParagraph(trimmed);
4473
+ }
4474
+ async function redactSystemText(text, redactChunk) {
4475
+ if (isLikelyEnglishSystemPrompt(text)) {
4476
+ return redactChunk(text, true, false);
4477
+ }
4478
+ const redactSegment = async (segment) => {
4479
+ if (!segment.trim()) return segment;
4480
+ if (segment.startsWith("```") && segment.endsWith("```")) {
4481
+ return redactChunk(segment, true, false);
4482
+ }
4483
+ if (!segment.includes("\n\n")) {
4484
+ return redactChunk(segment, isEnglishSystemParagraph(segment), false);
4485
+ }
4486
+ const parts = segment.split(/(\n{2,})/);
4487
+ for (let i = 0; i < parts.length; i += 2) {
4488
+ const para = parts[i] ?? "";
4489
+ if (!para.trim()) continue;
4490
+ parts[i] = await redactChunk(para, isEnglishSystemParagraph(para), false);
4491
+ }
4492
+ return parts.join("");
4493
+ };
4494
+ if (!text.includes("```")) {
4495
+ return redactSegment(text);
4496
+ }
4497
+ const codeParts = text.split(FENCED_CODE_SPLIT_RE);
4498
+ for (let i = 0; i < codeParts.length; i += 1) {
4499
+ const part = codeParts[i] ?? "";
4500
+ if (!part.trim()) continue;
4501
+ codeParts[i] = await redactSegment(part);
4502
+ }
4503
+ return codeParts.join("");
4504
+ }
4505
+ async function redactMessageText(text, redactChunk) {
4506
+ if (!text.includes("<system-reminder>")) {
4507
+ return redactChunk(text, false, true);
4508
+ }
4509
+ const parts = text.split(SYSTEM_REMINDER_SPLIT_RE);
4510
+ for (let i = 0; i < parts.length; i += 1) {
4511
+ const segment = parts[i] ?? "";
4512
+ if (!segment.trim()) continue;
4513
+ if (segment.startsWith("<system-reminder>") && segment.endsWith("</system-reminder>")) {
4514
+ parts[i] = await redactSystemText(segment, redactChunk);
4515
+ } else {
4516
+ parts[i] = await redactChunk(segment, false, true);
4517
+ }
4518
+ }
4519
+ return parts.join("");
4520
+ }
4521
+ async function extractSafeUpstreamError(resBuf, status, engine) {
4522
+ if (status < 400 || resBuf.byteLength === 0) return void 0;
4523
+ let summary = "";
4524
+ try {
4525
+ const parsed = JSON.parse(resBuf.toString("utf8"));
4526
+ if (isPlainObject(parsed)) {
4527
+ const errObj = isPlainObject(parsed.error) ? parsed.error : parsed;
4528
+ const parts = [];
4529
+ if (typeof errObj.type === "string" && errObj.type.trim()) parts.push(errObj.type.trim());
4530
+ if (typeof errObj.code === "string" && errObj.code.trim()) parts.push(errObj.code.trim());
4531
+ if (typeof errObj.message === "string" && errObj.message.trim()) {
4532
+ parts.push(errObj.message.trim());
4533
+ }
4534
+ summary = parts.join(": ");
4535
+ }
4536
+ } catch {
4537
+ const raw = resBuf.toString("utf8").trim();
4538
+ if (raw && !raw.startsWith("<")) summary = raw;
4539
+ }
4540
+ if (!summary) return void 0;
4541
+ const trimmed = summary.length > 240 ? `${summary.slice(0, 240)}...` : summary;
4542
+ try {
4543
+ const { result } = await engine.redact(trimmed, { mode: "rules" });
4544
+ return result.text;
4545
+ } catch {
4546
+ return `HTTP ${status}`;
4547
+ }
4184
4548
  }
4185
4549
  function headerFirst(headers, name) {
4186
4550
  const value = headers[name];
@@ -4251,13 +4615,14 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
4251
4615
  noteBinary("input_audio");
4252
4616
  }
4253
4617
  if (typeof block.text === "string") {
4254
- block.text = await redactString(block.text, kind);
4618
+ const blockKind = kind === "message" && isToolCatalogJson(block.text) ? "tool_description" : kind;
4619
+ block.text = await redactString(block.text, blockKind);
4255
4620
  }
4256
4621
  if (typeof block.refusal === "string") {
4257
4622
  block.refusal = await redactString(block.refusal, kind);
4258
4623
  }
4259
4624
  if (typeof block.thinking === "string") {
4260
- const redactedThinking = await redactString(block.thinking, kind);
4625
+ const redactedThinking = await redactString(block.thinking, "reasoning");
4261
4626
  if (redactedThinking !== block.thinking) {
4262
4627
  block.thinking = redactedThinking;
4263
4628
  delete block.signature;
@@ -4270,12 +4635,14 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
4270
4635
  block.context = await redactString(block.context, kind);
4271
4636
  }
4272
4637
  if (typeof block.content === "string") {
4273
- block.content = await redactString(block.content, kind);
4638
+ const blockKind = blockType === "tool_result" && isToolCatalogJson(block.content) ? "tool_description" : kind;
4639
+ block.content = await redactString(block.content, blockKind);
4274
4640
  } else if (Array.isArray(block.content)) {
4275
4641
  await redactContentBlocks(block.content, kind);
4276
4642
  }
4277
4643
  if (typeof block.output === "string") {
4278
- block.output = await redactString(block.output, kind);
4644
+ const blockKind = kind === "message" && isToolCatalogJson(block.output) ? "tool_description" : kind;
4645
+ block.output = await redactString(block.output, blockKind);
4279
4646
  } else if (Array.isArray(block.output)) {
4280
4647
  await redactContentBlocks(block.output, kind);
4281
4648
  }
@@ -4414,15 +4781,16 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
4414
4781
  msg.name = await redactString(msg.name, "tool_description");
4415
4782
  }
4416
4783
  if (typeof msg.content === "string") {
4417
- msg.content = await redactString(msg.content, msgKind);
4784
+ const contentKind = msg.role === "tool" && isToolCatalogJson(msg.content) ? "tool_description" : msgKind;
4785
+ msg.content = await redactString(msg.content, contentKind);
4418
4786
  } else if (Array.isArray(msg.content)) {
4419
4787
  await redactContentBlocks(msg.content, msgKind);
4420
4788
  }
4421
4789
  if (typeof msg.reasoning_content === "string") {
4422
- msg.reasoning_content = await redactString(msg.reasoning_content, msgKind);
4790
+ msg.reasoning_content = await redactString(msg.reasoning_content, "reasoning");
4423
4791
  }
4424
4792
  if (typeof msg.reasoning === "string") {
4425
- msg.reasoning = await redactString(msg.reasoning, msgKind);
4793
+ msg.reasoning = await redactString(msg.reasoning, "reasoning");
4426
4794
  }
4427
4795
  if (typeof msg.refusal === "string") {
4428
4796
  msg.refusal = await redactString(msg.refusal, msgKind);
@@ -4463,7 +4831,8 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
4463
4831
  await redactContentBlocks(item.content, itemKind);
4464
4832
  }
4465
4833
  if (typeof item.output === "string") {
4466
- item.output = await redactString(item.output, itemKind);
4834
+ const outKind = item.type === "function_call_output" && isToolCatalogJson(item.output) ? "tool_description" : itemKind;
4835
+ item.output = await redactString(item.output, outKind);
4467
4836
  } else if (Array.isArray(item.output)) {
4468
4837
  await redactContentBlocks(item.output, itemKind);
4469
4838
  }
@@ -4473,10 +4842,10 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
4473
4842
  item.input = await redactObjectStrings(item.input, itemKind);
4474
4843
  }
4475
4844
  if (typeof item.reasoning_content === "string") {
4476
- item.reasoning_content = await redactString(item.reasoning_content, itemKind);
4845
+ item.reasoning_content = await redactString(item.reasoning_content, "reasoning");
4477
4846
  }
4478
4847
  if (typeof item.reasoning === "string") {
4479
- item.reasoning = await redactString(item.reasoning, itemKind);
4848
+ item.reasoning = await redactString(item.reasoning, "reasoning");
4480
4849
  }
4481
4850
  if (typeof item.refusal === "string") {
4482
4851
  item.refusal = await redactString(item.refusal, itemKind);
@@ -4492,9 +4861,18 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
4492
4861
  }
4493
4862
  return clone;
4494
4863
  }
4864
+ function filterMapExcluding(map, excluded) {
4865
+ if (!excluded || excluded.size === 0) return map;
4866
+ const out = {};
4867
+ for (const [token, value] of Object.entries(map)) {
4868
+ if (!excluded.has(token)) out[token] = value;
4869
+ }
4870
+ return out;
4871
+ }
4495
4872
  function restoreLlmResponseBody(body, map, options = {}) {
4496
4873
  if (!isPlainObject(body) || Object.keys(map).length === 0) return body;
4497
4874
  const clone = options.mutate ? body : structuredClone(body);
4875
+ const reasoningMap = filterMapExcluding(map, options.reasoningExcludedTokens);
4498
4876
  if (Array.isArray(clone.content)) {
4499
4877
  for (const block of clone.content) {
4500
4878
  if (!isPlainObject(block)) continue;
@@ -4502,7 +4880,7 @@ function restoreLlmResponseBody(body, map, options = {}) {
4502
4880
  block.text = restorePlainText(block.text, map);
4503
4881
  }
4504
4882
  if (typeof block.thinking === "string" && typeof block.signature !== "string") {
4505
- block.thinking = restorePlainText(block.thinking, map);
4883
+ block.thinking = restorePlainText(block.thinking, reasoningMap);
4506
4884
  }
4507
4885
  if (isPlainObject(block.input)) {
4508
4886
  const skipRestore = isMaskeraVaultToolName(block.name) || block.name === "execute" && typeof block.input.code === "string" && MASKERA_VAULT_CODE_RE.test(block.input.code);
@@ -4521,10 +4899,10 @@ function restoreLlmResponseBody(body, map, options = {}) {
4521
4899
  msg.content = restorePlainText(msg.content, map);
4522
4900
  }
4523
4901
  if (typeof msg.reasoning_content === "string") {
4524
- msg.reasoning_content = restorePlainText(msg.reasoning_content, map);
4902
+ msg.reasoning_content = restorePlainText(msg.reasoning_content, reasoningMap);
4525
4903
  }
4526
4904
  if (typeof msg.reasoning === "string") {
4527
- msg.reasoning = restorePlainText(msg.reasoning, map);
4905
+ msg.reasoning = restorePlainText(msg.reasoning, reasoningMap);
4528
4906
  }
4529
4907
  if (Array.isArray(msg.tool_calls)) {
4530
4908
  for (const call of msg.tool_calls) {
@@ -4573,14 +4951,15 @@ function restoreLlmResponseBody(body, map, options = {}) {
4573
4951
  }
4574
4952
  return clone;
4575
4953
  }
4576
- function createSseRestorer(map) {
4954
+ function createSseRestorer(map, options = {}) {
4955
+ const reasoningMap = filterMapExcluding(map, options.reasoningExcludedTokens);
4577
4956
  const streams = /* @__PURE__ */ new Map();
4578
4957
  const toolNames = /* @__PURE__ */ new Map();
4579
4958
  const bufferedToolArgs = /* @__PURE__ */ new Map();
4580
- const getStream = (key, escapeForJsonString = false) => {
4959
+ const getStream = (key, escapeForJsonString = false, useReasoningMap = false) => {
4581
4960
  let r = streams.get(key);
4582
4961
  if (!r) {
4583
- r = new StreamingRestorer(map, { escapeForJsonString });
4962
+ r = new StreamingRestorer(useReasoningMap ? reasoningMap : map, { escapeForJsonString });
4584
4963
  streams.set(key, r);
4585
4964
  }
4586
4965
  return r;
@@ -4778,7 +5157,9 @@ data: ${JSON.stringify({
4778
5157
  if (parsed.delta.type === "text_delta" && typeof parsed.delta.text === "string") {
4779
5158
  parsed.delta.text = getStream(`anth_text:${idx}`).push(parsed.delta.text);
4780
5159
  } else if (parsed.delta.type === "thinking_delta" && typeof parsed.delta.thinking === "string") {
4781
- parsed.delta.thinking = getStream(`anth_thinking:${idx}`).push(parsed.delta.thinking);
5160
+ parsed.delta.thinking = getStream(`anth_thinking:${idx}`, false, true).push(
5161
+ parsed.delta.thinking
5162
+ );
4782
5163
  } else if (parsed.delta.type === "input_json_delta" && typeof parsed.delta.partial_json === "string") {
4783
5164
  const key = `anth_json:${idx}`;
4784
5165
  const name = toolNames.get(key);
@@ -4842,12 +5223,14 @@ data: ${JSON.stringify({
4842
5223
  delta.content = getStream(`openai_chat_text:${cIdx}`).push(delta.content);
4843
5224
  }
4844
5225
  if (typeof delta.reasoning_content === "string") {
4845
- delta.reasoning_content = getStream(`openai_chat_reasoning:${cIdx}`).push(
4846
- delta.reasoning_content
4847
- );
5226
+ delta.reasoning_content = getStream(
5227
+ `openai_chat_reasoning:${cIdx}`,
5228
+ false,
5229
+ true
5230
+ ).push(delta.reasoning_content);
4848
5231
  }
4849
5232
  if (typeof delta.reasoning === "string") {
4850
- delta.reasoning = getStream(`openai_chat_reasoning_plain:${cIdx}`).push(
5233
+ delta.reasoning = getStream(`openai_chat_reasoning_plain:${cIdx}`, false, true).push(
4851
5234
  delta.reasoning
4852
5235
  );
4853
5236
  }
@@ -4876,7 +5259,7 @@ data: ${JSON.stringify({
4876
5259
  }
4877
5260
  }
4878
5261
  }
4879
- if (choice.finish_reason !== null && choice.finish_reason !== void 0) {
5262
+ if (typeof choice.finish_reason === "string" && choice.finish_reason.length > 0) {
4880
5263
  const textTail = flushStream(`openai_chat_text:${cIdx}`);
4881
5264
  if (textTail) {
4882
5265
  if (!isPlainObject(choice.delta)) choice.delta = {};
@@ -5337,6 +5720,8 @@ async function startMaskeraProxy(options = {}) {
5337
5720
  };
5338
5721
  const mcpSessions = /* @__PURE__ */ new Map();
5339
5722
  const closedMcpSessions = /* @__PURE__ */ new Set();
5723
+ const messageTokensBySession = /* @__PURE__ */ new Map();
5724
+ const externalToolTokensBySession = /* @__PURE__ */ new Map();
5340
5725
  if (auditLogPath) {
5341
5726
  await mkdir(dirname(auditLogPath), { recursive: true });
5342
5727
  await appendFile(auditLogPath, "", { encoding: "utf8", mode: 384 });
@@ -5518,6 +5903,8 @@ async function startMaskeraProxy(options = {}) {
5518
5903
  approvals.clearAll();
5519
5904
  engine.clearCache();
5520
5905
  inspector.clear();
5906
+ messageTokensBySession.clear();
5907
+ externalToolTokensBySession.clear();
5521
5908
  totalRequests = 0;
5522
5909
  totalRedactions = 0;
5523
5910
  totalCounts = {};
@@ -5637,6 +6024,11 @@ async function startMaskeraProxy(options = {}) {
5637
6024
  res.end(JSON.stringify({ error: "Unknown inspector route." }));
5638
6025
  return;
5639
6026
  }
6027
+ if ((method === "GET" || method === "HEAD") && BROWSER_PROBE_PATHS.has(normalizedPath)) {
6028
+ res.writeHead(204, INSPECTOR_SECURITY_HEADERS);
6029
+ res.end();
6030
+ return;
6031
+ }
5640
6032
  if (normalizedPath === "/mcp" || normalizedPath === "/mcp/") {
5641
6033
  if (!isLoopbackRemoteAddress(req.socket.remoteAddress) || !isLoopbackHost(req.headers.host, host, boundPort, true)) {
5642
6034
  res.writeHead(403, {
@@ -5866,9 +6258,22 @@ async function startMaskeraProxy(options = {}) {
5866
6258
  return;
5867
6259
  }
5868
6260
  sessionId = deriveProxySessionId(req.headers, parsed);
6261
+ let externalTokensForSession = externalToolTokensBySession.get(sessionId);
6262
+ const incomingToolTokens = /* @__PURE__ */ new Set();
6263
+ collectExternalToolResultPlaceholders(parsed, incomingToolTokens);
6264
+ if (incomingToolTokens.size > 0) {
6265
+ if (!externalTokensForSession) {
6266
+ externalTokensForSession = /* @__PURE__ */ new Set();
6267
+ externalToolTokensBySession.set(sessionId, externalTokensForSession);
6268
+ }
6269
+ for (const tok of incomingToolTokens) externalTokensForSession.add(tok);
6270
+ }
6271
+ let messageTokensForSession = messageTokensBySession.get(sessionId);
5869
6272
  let redactedObj;
5870
6273
  try {
5871
- const redactChunk = async (chunk, forceRules) => {
6274
+ const messagePreviews = [];
6275
+ const fallbackPreviews = [];
6276
+ const redactChunk = async (chunk, forceRules, previewable) => {
5872
6277
  if (!chunk.trim()) return chunk;
5873
6278
  const { result } = await engine.redact(chunk, {
5874
6279
  mode: forceRules ? "rules" : void 0,
@@ -5878,9 +6283,20 @@ async function startMaskeraProxy(options = {}) {
5878
6283
  const applied = vault.apply(chunk, result, sessionId, proxyVaultOwner);
5879
6284
  stats.redactions += applied.totalRedactions;
5880
6285
  mergeCounts(stats.counts, applied.counts);
5881
- if (redactedPreview.length < 6) {
5882
- const snippet = applied.redacted.length > 1200 ? `${applied.redacted.slice(0, 1200)}...` : applied.redacted;
5883
- redactedPreview.push(snippet);
6286
+ if (previewable && applied.totalRedactions > 0) {
6287
+ if (!messageTokensForSession) {
6288
+ messageTokensForSession = /* @__PURE__ */ new Set();
6289
+ messageTokensBySession.set(sessionId, messageTokensForSession);
6290
+ }
6291
+ for (const tok of Object.keys(applied.map)) {
6292
+ messageTokensForSession.add(tok);
6293
+ }
6294
+ }
6295
+ const snippet = applied.redacted.length > 1200 ? `${applied.redacted.slice(0, 1200)}...` : applied.redacted;
6296
+ if (previewable) {
6297
+ if (messagePreviews.length < 6) messagePreviews.push(snippet);
6298
+ } else if (applied.totalRedactions > 0 && fallbackPreviews.length < 4) {
6299
+ fallbackPreviews.push(snippet);
5884
6300
  }
5885
6301
  return applied.redacted;
5886
6302
  };
@@ -5889,21 +6305,12 @@ async function startMaskeraProxy(options = {}) {
5889
6305
  async (text, kind) => {
5890
6306
  if (!text.trim()) return text;
5891
6307
  if (kind === "tool_description") {
5892
- return redactChunk(text, true);
6308
+ return redactChunk(text, true, false);
5893
6309
  }
5894
- if (kind === "system") {
5895
- if (text.length >= 600 && text.includes("\n\n")) {
5896
- const parts = text.split(/(\n{2,})/);
5897
- for (let i = 0; i < parts.length; i += 2) {
5898
- const para = parts[i] ?? "";
5899
- if (!para.trim()) continue;
5900
- parts[i] = await redactChunk(para, isLikelyEnglishSystemPrompt(para));
5901
- }
5902
- return parts.join("");
5903
- }
5904
- return redactChunk(text, isLikelyEnglishSystemPrompt(text));
6310
+ if (kind === "system" || kind === "reasoning") {
6311
+ return redactSystemText(text, redactChunk);
5905
6312
  }
5906
- return redactChunk(text, false);
6313
+ return redactMessageText(text, redactChunk);
5907
6314
  },
5908
6315
  {
5909
6316
  mutate: true,
@@ -5912,6 +6319,7 @@ async function startMaskeraProxy(options = {}) {
5912
6319
  }
5913
6320
  }
5914
6321
  );
6322
+ redactedPreview.push(...messagePreviews.length > 0 ? messagePreviews : fallbackPreviews);
5915
6323
  } catch (err) {
5916
6324
  recordAuditAndInspector({
5917
6325
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
@@ -6023,13 +6431,23 @@ async function startMaskeraProxy(options = {}) {
6023
6431
  if (requestWarnings) {
6024
6432
  outHeaders["x-maskera-warning"] = "uninspectable-binary-attachment";
6025
6433
  }
6026
- const sessionMap = restoreResponses ? vault.getMap(sessionId, proxyVaultOwner) : {};
6434
+ const rawSessionMap = restoreResponses ? vault.getMap(sessionId, proxyVaultOwner) : {};
6435
+ const externalTokens = externalToolTokensBySession.get(sessionId);
6436
+ const messageTokens = messageTokensBySession.get(sessionId);
6437
+ let sessionMap = rawSessionMap;
6438
+ if (externalTokens && externalTokens.size > 0) {
6439
+ sessionMap = {};
6440
+ for (const [token, value] of Object.entries(rawSessionMap)) {
6441
+ if (externalTokens.has(token) && !messageTokens?.has(token)) continue;
6442
+ sessionMap[token] = value;
6443
+ }
6444
+ }
6027
6445
  const hasMap = Object.keys(sessionMap).length > 0;
6028
6446
  const resContentType = (upstreamRes.headers.get("content-type") ?? "").toLowerCase();
6029
6447
  const isSse = resContentType.includes("text/event-stream");
6030
6448
  if (isSse && upstreamRes.body) {
6031
6449
  res.writeHead(upstreamRes.status, outHeaders);
6032
- const sse = hasMap ? createSseRestorer(sessionMap) : null;
6450
+ const sse = hasMap ? createSseRestorer(sessionMap, { reasoningExcludedTokens: externalTokens }) : null;
6033
6451
  const decoder = sse ? new TextDecoder() : null;
6034
6452
  const reader = upstreamRes.body.getReader();
6035
6453
  const onStreamAbort = () => {
@@ -6088,10 +6506,14 @@ async function startMaskeraProxy(options = {}) {
6088
6506
  } finally {
6089
6507
  res.off("close", onClientClose);
6090
6508
  }
6509
+ const errorDetail = await extractSafeUpstreamError(resBuf, upstreamRes.status, engine);
6091
6510
  if (hasMap && resContentType.includes("application/json")) {
6092
6511
  try {
6093
6512
  const parsed = JSON.parse(resBuf.toString("utf8"));
6094
- const restored = restoreLlmResponseBody(parsed, sessionMap, { mutate: true });
6513
+ const restored = restoreLlmResponseBody(parsed, sessionMap, {
6514
+ mutate: true,
6515
+ reasoningExcludedTokens: externalTokens
6516
+ });
6095
6517
  const restoredBuf = Buffer.from(JSON.stringify(restored), "utf8");
6096
6518
  res.writeHead(upstreamRes.status, outHeaders);
6097
6519
  res.end(restoredBuf);
@@ -6108,6 +6530,7 @@ async function startMaskeraProxy(options = {}) {
6108
6530
  redactions: stats.redactions,
6109
6531
  counts: stats.counts,
6110
6532
  redactedPreview,
6533
+ ...errorDetail ? { errorDetail } : {},
6111
6534
  ...requestWarnings ? { warnings: requestWarnings } : {}
6112
6535
  });
6113
6536
  log(
@@ -6132,6 +6555,7 @@ async function startMaskeraProxy(options = {}) {
6132
6555
  redactions: stats.redactions,
6133
6556
  counts: stats.counts,
6134
6557
  redactedPreview,
6558
+ ...errorDetail ? { errorDetail } : {},
6135
6559
  ...requestWarnings ? { warnings: requestWarnings } : {}
6136
6560
  });
6137
6561
  log(
@@ -6889,12 +7313,12 @@ function printHelp() {
6889
7313
  process.stdout.write(
6890
7314
  [
6891
7315
  `${SERVER_NAME} ${SERVER_VERSION}`,
6892
- "Local Swedish PII redaction for any AI agent: MCP server (stdio + Streamable HTTP), LLM proxy, wrap launcher, hook guard, installer, doctor, and background service.",
7316
+ "Local Swedish PII redaction for AI agents.",
6893
7317
  "",
6894
7318
  "Usage:",
6895
7319
  " maskera-mcp [mcp] [--root <dir>] [--no-raw-restore] [--read-only] [--approval-mode automatic|native] [--rules-only]",
6896
7320
  " maskera-mcp proxy [--port 8787] [--host 127.0.0.1] [--root <dir>] [--open] [--upstream <url>] [--audit-log <file.jsonl>] [--no-raw-restore] [--read-only] [--approval-mode automatic|browser] [--rules-only] [--no-restore] [--block-binary]",
6897
- " maskera-mcp wrap [flags] -- <cmd> [args...] Start local proxy, verify, inject ANTHROPIC_BASE_URL/OPENAI_BASE_URL, and run <cmd>",
7321
+ " maskera-mcp wrap [flags] -- <cmd> [args...]",
6898
7322
  " maskera-mcp guard [--redact] [--file <path>] [--proxy-url <url>] [--no-proxy] [--rules-only]",
6899
7323
  ` maskera-mcp install [client|all] [--transport stdio|http] [--url <http://127.0.0.1:8787/mcp>] [--root <dir>] [--apply] [--project] [--with-hook] [--no-raw-restore] [--read-only] [--config <path>] [--receipt <file.json>] [--no-verify] [--dry-run]`,
6900
7324
  " maskera-mcp doctor [--root <dir>] [--proxy-url <url>] [--receipt <file.json>] [--rules-only] [--json]",
@@ -7301,11 +7725,10 @@ Verify: ${primary.verifyStep}
7301
7725
  process.stderr.write(
7302
7726
  [
7303
7727
  `[maskera-proxy] listening on ${running.url} (mode=${args.defaultMode}, restore=${args.restoreResponses})`,
7304
- ` Local live inspector: ${running.inspectorUrl}`,
7728
+ ` Inspector: ${running.inspectorUrl}`,
7305
7729
  ` Streamable HTTP MCP: ${running.mcpUrl}`,
7306
7730
  ` Claude Code / Anthropic: ANTHROPIC_BASE_URL=${running.url}`,
7307
7731
  ` Codex / Cursor / OpenAI: OPENAI_BASE_URL=${running.url}/v1`,
7308
- ` Or one-command launch: npx -y @maskera/mcp wrap -- claude`,
7309
7732
  ...args.auditLogPath ? [` Local audit log (JSONL): ${args.auditLogPath}`] : [],
7310
7733
  ""
7311
7734
  ].join("\n")