@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/index.js CHANGED
@@ -310,7 +310,7 @@ function createMaskeraEngine(options = {}) {
310
310
  if (!recognizer) {
311
311
  const dtype = options.nerOptions?.dtype ?? (options.nerOptions?.localModelPath ? "q4" : "q8");
312
312
  const loadStartedAt = Date.now();
313
- options.onModelStatus?.({ phase: "loading", model });
313
+ options.onModelStatus?.({ phase: "loading", model, dtype });
314
314
  recognizer = createNerRecognizer({
315
315
  ...options.nerOptions,
316
316
  model,
@@ -521,6 +521,11 @@ function createMaskeraEngine(options = {}) {
521
521
  }
522
522
  };
523
523
  }
524
+ var MODEL_DOWNLOAD_MB = { q4: 43, q8: 59 };
525
+ function downloadSize(dtype) {
526
+ const mb = dtype ? MODEL_DOWNLOAD_MB[dtype] : void 0;
527
+ return mb ? `, ~${mb} MB on first run` : "";
528
+ }
524
529
  function createModelProgressLogger(write = (line) => process.stderr.write(`${line}
525
530
  `), delayMs = 350) {
526
531
  let timer = null;
@@ -532,7 +537,7 @@ function createModelProgressLogger(write = (line) => process.stderr.write(`${lin
532
537
  timer = setTimeout(() => {
533
538
  announcedLoading = true;
534
539
  write(
535
- `[maskera] Loading Swedish ONNX model (${event.model}, ~43 MB on first run, cached locally)...`
540
+ `[maskera] Loading Swedish ONNX model (${event.model}${downloadSize(event.dtype)}, cached locally)...`
536
541
  );
537
542
  }, delayMs);
538
543
  timer.unref?.();
@@ -874,7 +879,7 @@ description: Redact Swedish personal data (names, personnummer, addresses, phone
874
879
 
875
880
  # Maskera: local Swedish PII redaction
876
881
 
877
- 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]\`.
882
+ 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]\`.
878
883
 
879
884
  ## Choose the right mode
880
885
 
@@ -895,7 +900,7 @@ Pick by where the text comes from: **proxy for text typed straight into the chat
895
900
  # Same warm process also serves Streamable HTTP MCP:
896
901
  # http://127.0.0.1:8787/mcp (supports ?no_raw_restore=1&read_only=1&approval_mode=browser)
897
902
  \`\`\`
898
- - 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\`.
903
+ - 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\`.
899
904
  - Routes Anthropic (\`/v1/messages\`) and OpenAI (\`/v1/chat/completions\`, \`/v1/responses\`) automatically, or set \`--upstream <url>\`.
900
905
  - Restores placeholders transparently in JSON, tool arguments and chunk-split SSE streams.
901
906
  - Fails closed (\`502\`) if local redaction fails. Inspect counts only at \`http://127.0.0.1:8787/_maskera/status\`.
@@ -1282,7 +1287,7 @@ var COUNTS_SCHEMA = {
1282
1287
  var TOOLS = [
1283
1288
  {
1284
1289
  name: "maskera_redact",
1285
- 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.",
1290
+ 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.",
1286
1291
  annotations: {
1287
1292
  title: "Redact Swedish PII locally",
1288
1293
  readOnlyHint: true,
@@ -2021,7 +2026,7 @@ function createMaskeraMcpServer(options = {}) {
2021
2026
  );
2022
2027
  }
2023
2028
  const response = await requestElicitation({
2024
- 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.`,
2029
+ message: `${input.tool} wants to release ${input.placeholderCount} original Swedish PII value(s) into the model context (${input.reason}).`,
2025
2030
  requestedSchema: {
2026
2031
  type: "object",
2027
2032
  properties: {
@@ -3318,6 +3323,11 @@ function renderInspectorHtml(info) {
3318
3323
  white-space: pre-wrap;
3319
3324
  word-break: break-word;
3320
3325
  }
3326
+ .preview.err-preview {
3327
+ border-color: var(--err);
3328
+ background: var(--err-bg);
3329
+ color: var(--err);
3330
+ }
3321
3331
  .tok {
3322
3332
  display: inline-block;
3323
3333
  padding: 0 4px;
@@ -3350,7 +3360,7 @@ function renderInspectorHtml(info) {
3350
3360
  </div>
3351
3361
  <div class="actions">
3352
3362
  <button id="selftest-btn" type="button" class="primary">K\xF6r sj\xE4lvtest</button>
3353
- <button id="reveal-btn" type="button">Visa originalv\xE4rden lokalt</button>
3363
+ <button id="reveal-btn" type="button">Visa originalv\xE4rden</button>
3354
3364
  <button id="clear-btn" type="button">Rensa minne</button>
3355
3365
  </div>
3356
3366
  </header>
@@ -3391,6 +3401,16 @@ function renderInspectorHtml(info) {
3391
3401
 
3392
3402
  const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ "&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;" }[c]));
3393
3403
  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>");
3404
+ const formatLocalTime = (iso) => {
3405
+ if (!iso) return "";
3406
+ const d = new Date(iso);
3407
+ if (Number.isNaN(d.getTime())) return String(iso).slice(11, 19);
3408
+ try {
3409
+ return d.toLocaleTimeString("sv-SE", { hour12: false });
3410
+ } catch {
3411
+ return String(iso).slice(11, 19);
3412
+ }
3413
+ };
3394
3414
 
3395
3415
  function renderReceipt() {
3396
3416
  if (!lastReceipt) {
@@ -3403,7 +3423,7 @@ function renderInspectorHtml(info) {
3403
3423
  return '<li><span class="receipt-tag' + cls + '">[' + esc(c.status) + ']</span><span><strong>' + esc(c.name) + ':</strong> ' + esc(c.detail) + '</span></li>';
3404
3424
  }).join("");
3405
3425
  const proofHtml = r.sampleProof && !r.sampleProof.rawPiiLeaked
3406
- ? '<p class="body-label">Verifierat maskerat utdata (0 l\xE4ckor, \xE5terst\xE4llning klar):</p><pre class="preview">' + highlightTokens(r.sampleProof.redactedPreview) + '</pre>'
3426
+ ? '<p class="body-label">Maskerat utdata:</p><pre class="preview">' + highlightTokens(r.sampleProof.redactedPreview) + '</pre>'
3407
3427
  : "";
3408
3428
  receiptRoot.innerHTML =
3409
3429
  '<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>' +
@@ -3500,7 +3520,7 @@ function renderInspectorHtml(info) {
3500
3520
  const r = await fetch("/_maskera/vault", { headers: { "x-maskera-reveal": "1" } });
3501
3521
  const d = await r.json();
3502
3522
  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("");
3503
- 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>' +
3523
+ vaultRoot.innerHTML = '<section class="vault-box"><h2>\xC5terst\xE4llningsnyckel</h2>' +
3504
3524
  (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>") +
3505
3525
  "</section>";
3506
3526
  } catch {}
@@ -3509,8 +3529,8 @@ function renderInspectorHtml(info) {
3509
3529
  function render() {
3510
3530
  if (!items.length) {
3511
3531
  feedEl.innerHTML =
3512
- '<div class="empty"><p class="empty-title">V\xE4ntar p\xE5 f\xF6rsta riktiga anropet fr\xE5n din AI-klient.</p>' +
3513
- '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:' +
3532
+ '<div class="empty"><p class="empty-title">Inga anrop \xE4nnu.</p>' +
3533
+ 'Skicka ett prov fr\xE5n din klient s\xE5 visas maskeringen h\xE4r:' +
3514
3534
  '<div class="sample-row"><span class="sample-text">' + esc(SAMPLE_PROMPT) + '</span><button id="copy-sample-btn" type="button">Kopiera testmening</button></div>' +
3515
3535
  '<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>';
3516
3536
  const copyBtn = document.getElementById("copy-sample-btn");
@@ -3530,15 +3550,16 @@ function renderInspectorHtml(info) {
3530
3550
  }
3531
3551
  for (const it of items) seenIds.add(it.id);
3532
3552
  feedEl.innerHTML = '<div class="list">' + items.map((it) => {
3533
- const time = (it.timestamp || "").slice(11, 19);
3553
+ const time = formatLocalTime(it.timestamp);
3534
3554
  const tags = Object.entries(it.counts || {}).map(([k, v]) => '<span class="count-tag">' + esc(k) + " \xD7" + v + "</span>").join("");
3535
3555
  const previews = (it.redactedPreview || []).map((p) => '<pre class="preview">' + highlightTokens(p) + "</pre>").join("");
3556
+ const errBlock = it.errorDetail ? '<p class="body-label">Svar fr\xE5n API (fel):</p><pre class="preview err-preview">' + esc(it.errorDetail) + "</pre>" : "";
3536
3557
  const statusCls = it.status >= 200 && it.status < 400 ? "" : " err";
3537
3558
  const isOpen = openIds.has(it.id);
3538
3559
  return '<details class="item" data-id="' + esc(it.id) + '"' + (isOpen ? " open" : "") + '>' +
3539
3560
  '<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>' +
3540
3561
  '<span class="right"><span>' + (it.streamed ? "SSE" : "JSON") + '</span><span>' + it.durationMs + ' ms</span><span>' + esc(time) + '</span></span></summary>' +
3541
- '<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>';
3562
+ '<div class="body">' + errBlock + '<p class="body-label">Skickat vidare:</p>' + (previews || '<pre class="preview">(ingen text i anropet)</pre>') + '</div></details>';
3542
3563
  }).join("") + "</div>";
3543
3564
  for (const det of feedEl.querySelectorAll("details.item")) {
3544
3565
  det.addEventListener("toggle", () => {
@@ -3554,7 +3575,7 @@ function renderInspectorHtml(info) {
3554
3575
  revealBtn.addEventListener("click", () => {
3555
3576
  reveal = !reveal;
3556
3577
  revealBtn.classList.toggle("active", reveal);
3557
- revealBtn.textContent = reveal ? "D\xF6lj originalv\xE4rden" : "Visa originalv\xE4rden lokalt";
3578
+ revealBtn.textContent = reveal ? "D\xF6lj originalv\xE4rden" : "Visa originalv\xE4rden";
3558
3579
  void refreshVault();
3559
3580
  });
3560
3581
 
@@ -4121,7 +4142,7 @@ function restoreJsonLeaves(value, map) {
4121
4142
  }
4122
4143
  return value;
4123
4144
  }
4124
- var MASKERA_VAULT_TOOL_RE = /(?:^|__)maskera_(?:write_file|restore|clear_session)$/;
4145
+ var MASKERA_VAULT_TOOL_RE = /(?:^|[^a-zA-Z0-9]|_)maskera_(?:write_file|restore|clear_session)$/;
4125
4146
  var MASKERA_VAULT_CODE_RE = /\bmaskera_(?:write_file|restore)\b/;
4126
4147
  function isMaskeraVaultToolName(name) {
4127
4148
  return typeof name === "string" && MASKERA_VAULT_TOOL_RE.test(name);
@@ -4132,10 +4153,80 @@ function shouldSkipToolArgRestore(toolName, argsText) {
4132
4153
  return false;
4133
4154
  }
4134
4155
  var SWEDISH_DIACRITIC_RE = /[åäöÅÄÖ]/;
4135
- var SWEDISH_SIGNAL_WORD_RE = /\b(?:och|inte|ska|eller|enligt|kund|personnummer|svenska|sekretess|arbetsgivare|utbetalning|sammanfatta|skriv|svara|nedan|uppgifter)\b/i;
4156
+ var SWEDISH_STOP_WORDS = /* @__PURE__ */ new Set([
4157
+ "och",
4158
+ "att",
4159
+ "det",
4160
+ "som",
4161
+ "f\xF6r",
4162
+ "med",
4163
+ "har",
4164
+ "inte",
4165
+ "p\xE5",
4166
+ "\xE4r",
4167
+ "av",
4168
+ "till",
4169
+ "ett",
4170
+ "fr\xE5n",
4171
+ "kan",
4172
+ "ska",
4173
+ "eller",
4174
+ "vid",
4175
+ "s\xE5",
4176
+ "men",
4177
+ "den",
4178
+ "jag",
4179
+ "din",
4180
+ "ditt",
4181
+ "mitt",
4182
+ "var",
4183
+ "blev",
4184
+ "enligt",
4185
+ "kund",
4186
+ "personnummer",
4187
+ "svenska",
4188
+ "sekretess",
4189
+ "arbetsgivare",
4190
+ "utbetalning",
4191
+ "sammanfatta",
4192
+ "skriv",
4193
+ "svara",
4194
+ "nedan",
4195
+ "uppgifter",
4196
+ "v\xE4nliga",
4197
+ "h\xE4lsningar",
4198
+ "\xE4rendet",
4199
+ "\xE4rende",
4200
+ "mejl",
4201
+ "brev",
4202
+ "patient",
4203
+ "namn",
4204
+ "telefon",
4205
+ "adress"
4206
+ ]);
4207
+ 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;
4136
4208
  var ENGLISH_BOILERPLATE_WORDS = /* @__PURE__ */ new Set([
4137
4209
  "the",
4138
4210
  "and",
4211
+ "to",
4212
+ "of",
4213
+ "in",
4214
+ "is",
4215
+ "it",
4216
+ "on",
4217
+ "as",
4218
+ "be",
4219
+ "by",
4220
+ "or",
4221
+ "an",
4222
+ "at",
4223
+ "if",
4224
+ "do",
4225
+ "no",
4226
+ "yes",
4227
+ "so",
4228
+ "but",
4229
+ "not",
4139
4230
  "you",
4140
4231
  "your",
4141
4232
  "with",
@@ -4143,7 +4234,6 @@ var ENGLISH_BOILERPLATE_WORDS = /* @__PURE__ */ new Set([
4143
4234
  "this",
4144
4235
  "from",
4145
4236
  "are",
4146
- "not",
4147
4237
  "when",
4148
4238
  "use",
4149
4239
  "must",
@@ -4151,7 +4241,9 @@ var ENGLISH_BOILERPLATE_WORDS = /* @__PURE__ */ new Set([
4151
4241
  "never",
4152
4242
  "always",
4153
4243
  "tools",
4244
+ "tool",
4154
4245
  "files",
4246
+ "file",
4155
4247
  "code",
4156
4248
  "return",
4157
4249
  "output",
@@ -4159,24 +4251,296 @@ var ENGLISH_BOILERPLATE_WORDS = /* @__PURE__ */ new Set([
4159
4251
  "assistant",
4160
4252
  "instructions",
4161
4253
  "command",
4162
- "user"
4254
+ "commands",
4255
+ "user",
4256
+ "for",
4257
+ "into",
4258
+ "only",
4259
+ "before",
4260
+ "after",
4261
+ "run",
4262
+ "check",
4263
+ "edit",
4264
+ "read",
4265
+ "write",
4266
+ "git",
4267
+ "branch",
4268
+ "commit",
4269
+ "push",
4270
+ "test",
4271
+ "tests",
4272
+ "error",
4273
+ "path",
4274
+ "directory",
4275
+ "repository",
4276
+ "session",
4277
+ "agent",
4278
+ "prompt",
4279
+ "message",
4280
+ "system",
4281
+ "default",
4282
+ "without",
4283
+ "can",
4284
+ "will",
4285
+ "each",
4286
+ "all",
4287
+ "any",
4288
+ "every",
4289
+ "about",
4290
+ "more",
4291
+ "also",
4292
+ "make",
4293
+ "keep",
4294
+ "does",
4295
+ "have",
4296
+ "has",
4297
+ "been",
4298
+ "its",
4299
+ "their",
4300
+ "them",
4301
+ "then",
4302
+ "than",
4303
+ "using",
4304
+ "following",
4305
+ "other",
4306
+ "same",
4307
+ "first",
4308
+ "next",
4309
+ "existing",
4310
+ "changes",
4311
+ "where",
4312
+ "which",
4313
+ "what",
4314
+ "how",
4315
+ "why",
4316
+ "because",
4317
+ "unless",
4318
+ "instead",
4319
+ "below",
4320
+ "above",
4321
+ "work",
4322
+ "working",
4323
+ "task",
4324
+ "tasks",
4325
+ "skill",
4326
+ "skills",
4327
+ "rule",
4328
+ "rules",
4329
+ "repo",
4330
+ "project",
4331
+ "build",
4332
+ "lint",
4333
+ "hook",
4334
+ "hooks",
4335
+ "memory",
4336
+ "local",
4337
+ "remote",
4338
+ "status",
4339
+ "current",
4340
+ "recent"
4163
4341
  ]);
4164
- var ASCII_WORD_RE = /\b[a-z]{2,}\b/g;
4165
- function isLikelyEnglishSystemPrompt(text) {
4166
- if (text.length < 240) return false;
4167
- if (SWEDISH_DIACRITIC_RE.test(text)) return false;
4168
- if (SWEDISH_SIGNAL_WORD_RE.test(text)) return false;
4169
- const found = /* @__PURE__ */ new Set();
4170
- const lower = text.toLowerCase();
4171
- ASCII_WORD_RE.lastIndex = 0;
4172
- for (let m = ASCII_WORD_RE.exec(lower); m !== null; m = ASCII_WORD_RE.exec(lower)) {
4342
+ var WORD_TOKEN_RE2 = /[a-zåäö]{2,}/gi;
4343
+ var SYSTEM_REMINDER_SPLIT_RE = /(<system-reminder>[\s\S]*?<\/system-reminder>)/g;
4344
+ var FENCED_CODE_SPLIT_RE = /(```[\s\S]*?```)/g;
4345
+ var GIT_STATUS_LINE_RE = /^(?:[MADRCU?!]{1,2}\s+\S|[0-9a-f]{7,40}\s+\S)/;
4346
+ var XML_TAG_ONLY_RE = /^<\/?[a-z][a-z0-9_-]*(?:\s[^>]*)?>$/i;
4347
+ var MARKDOWN_HEADING_RE = /^#{1,6}\s+\S/;
4348
+ 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*\{)/;
4349
+ var BROWSER_PROBE_PATHS = /* @__PURE__ */ new Set([
4350
+ "/favicon.ico",
4351
+ "/apple-touch-icon.png",
4352
+ "/apple-touch-icon-precomposed.png",
4353
+ "/robots.txt"
4354
+ ]);
4355
+ var PLACEHOLDER_TOKEN_RE = /\[[A-ZÅÄÖ][A-ZÅÄÖ0-9_]*_\d+\]/g;
4356
+ function collectPlaceholdersFromUnknown(value, out) {
4357
+ if (typeof value === "string") {
4358
+ if (!value.includes("[")) return;
4359
+ const matches = value.match(PLACEHOLDER_TOKEN_RE);
4360
+ if (matches) {
4361
+ for (const tok of matches) out.add(tok);
4362
+ }
4363
+ return;
4364
+ }
4365
+ if (Array.isArray(value)) {
4366
+ for (const item of value) collectPlaceholdersFromUnknown(item, out);
4367
+ return;
4368
+ }
4369
+ if (isPlainObject(value)) {
4370
+ for (const v of Object.values(value)) collectPlaceholdersFromUnknown(v, out);
4371
+ }
4372
+ }
4373
+ function collectExternalToolResultPlaceholders(body, out) {
4374
+ if (Array.isArray(body.messages)) {
4375
+ for (const msg of body.messages) {
4376
+ if (!isPlainObject(msg)) continue;
4377
+ if (msg.role === "tool") {
4378
+ collectPlaceholdersFromUnknown(msg.content, out);
4379
+ continue;
4380
+ }
4381
+ if (Array.isArray(msg.content)) {
4382
+ for (const block of msg.content) {
4383
+ if (isPlainObject(block) && block.type === "tool_result") {
4384
+ collectPlaceholdersFromUnknown(block.content, out);
4385
+ }
4386
+ }
4387
+ }
4388
+ }
4389
+ }
4390
+ if (Array.isArray(body.input)) {
4391
+ for (const item of body.input) {
4392
+ if (isPlainObject(item) && item.type === "function_call_output") {
4393
+ collectPlaceholdersFromUnknown(item.output, out);
4394
+ }
4395
+ }
4396
+ }
4397
+ }
4398
+ function isToolCatalogJson(text) {
4399
+ const trimmed = text.trim();
4400
+ if (!trimmed.startsWith("{") || !trimmed.includes('"items"') || !trimmed.includes('"tools.')) {
4401
+ return false;
4402
+ }
4403
+ try {
4404
+ const parsed = JSON.parse(trimmed);
4405
+ if (!isPlainObject(parsed) || !Array.isArray(parsed.items) || parsed.items.length === 0) {
4406
+ return false;
4407
+ }
4408
+ return parsed.items.every(
4409
+ (item) => isPlainObject(item) && typeof item.path === "string" && item.path.startsWith("tools.") && (item.description === void 0 || typeof item.description === "string")
4410
+ );
4411
+ } catch {
4412
+ return false;
4413
+ }
4414
+ }
4415
+ function isEnglishSystemParagraph(paragraph) {
4416
+ const trimmed = paragraph.trim();
4417
+ if (!trimmed) return true;
4418
+ if (XML_TAG_ONLY_RE.test(trimmed)) return true;
4419
+ if (trimmed.startsWith("```") && trimmed.endsWith("```")) return true;
4420
+ if (CLI_SYSTEM_HEADER_RE.test(trimmed)) return true;
4421
+ const nonEmptyLines = trimmed.split("\n").map((l) => l.trim()).filter(Boolean);
4422
+ if (nonEmptyLines.length > 0 && nonEmptyLines.every(
4423
+ (l) => GIT_STATUS_LINE_RE.test(l) || XML_TAG_ONLY_RE.test(l) || CLI_SYSTEM_HEADER_RE.test(l) || l.startsWith("(use ")
4424
+ )) {
4425
+ return true;
4426
+ }
4427
+ let enTotal = 0;
4428
+ const enDistinct = /* @__PURE__ */ new Set();
4429
+ let svTotal = 0;
4430
+ let svDiacriticWords = 0;
4431
+ const lower = trimmed.toLowerCase();
4432
+ WORD_TOKEN_RE2.lastIndex = 0;
4433
+ for (let m = WORD_TOKEN_RE2.exec(lower); m !== null; m = WORD_TOKEN_RE2.exec(lower)) {
4173
4434
  const word = m[0];
4174
- if (word && ENGLISH_BOILERPLATE_WORDS.has(word)) {
4175
- found.add(word);
4176
- if (found.size >= 6) return true;
4435
+ if (!word) continue;
4436
+ if (SWEDISH_STOP_WORDS.has(word)) {
4437
+ svTotal += 1;
4438
+ }
4439
+ if (SWEDISH_DIACRITIC_RE.test(word)) {
4440
+ svDiacriticWords += 1;
4441
+ }
4442
+ if (ENGLISH_BOILERPLATE_WORDS.has(word)) {
4443
+ enTotal += 1;
4444
+ enDistinct.add(word);
4177
4445
  }
4178
4446
  }
4179
- return false;
4447
+ if (nonEmptyLines.length === 1 && MARKDOWN_HEADING_RE.test(trimmed) && svTotal === 0 && svDiacriticWords === 0 && trimmed.length < 120) {
4448
+ return true;
4449
+ }
4450
+ if (svTotal === 0 && svDiacriticWords === 0 && CODE_SIGNATURE_RE.test(trimmed)) {
4451
+ return true;
4452
+ }
4453
+ if (trimmed.length < 60 && enDistinct.size < 4) return false;
4454
+ const svSignal = svTotal + svDiacriticWords;
4455
+ if (svSignal === 0) {
4456
+ const minDistinct = trimmed.length >= 240 ? 5 : 3;
4457
+ return enDistinct.size >= minDistinct;
4458
+ }
4459
+ return enTotal >= 12 && enDistinct.size >= 6 && enTotal >= svSignal * 6;
4460
+ }
4461
+ function isLikelyEnglishSystemPrompt(text) {
4462
+ const trimmed = text.trim();
4463
+ if (!trimmed) return false;
4464
+ if (trimmed.includes("\n\n")) {
4465
+ const paragraphs = trimmed.split(/\n{2,}/).map((p) => p.trim()).filter(Boolean);
4466
+ return paragraphs.length > 0 && paragraphs.every((p) => isEnglishSystemParagraph(p));
4467
+ }
4468
+ return isEnglishSystemParagraph(trimmed);
4469
+ }
4470
+ async function redactSystemText(text, redactChunk) {
4471
+ if (isLikelyEnglishSystemPrompt(text)) {
4472
+ return redactChunk(text, true, false);
4473
+ }
4474
+ const redactSegment = async (segment) => {
4475
+ if (!segment.trim()) return segment;
4476
+ if (segment.startsWith("```") && segment.endsWith("```")) {
4477
+ return redactChunk(segment, true, false);
4478
+ }
4479
+ if (!segment.includes("\n\n")) {
4480
+ return redactChunk(segment, isEnglishSystemParagraph(segment), false);
4481
+ }
4482
+ const parts = segment.split(/(\n{2,})/);
4483
+ for (let i = 0; i < parts.length; i += 2) {
4484
+ const para = parts[i] ?? "";
4485
+ if (!para.trim()) continue;
4486
+ parts[i] = await redactChunk(para, isEnglishSystemParagraph(para), false);
4487
+ }
4488
+ return parts.join("");
4489
+ };
4490
+ if (!text.includes("```")) {
4491
+ return redactSegment(text);
4492
+ }
4493
+ const codeParts = text.split(FENCED_CODE_SPLIT_RE);
4494
+ for (let i = 0; i < codeParts.length; i += 1) {
4495
+ const part = codeParts[i] ?? "";
4496
+ if (!part.trim()) continue;
4497
+ codeParts[i] = await redactSegment(part);
4498
+ }
4499
+ return codeParts.join("");
4500
+ }
4501
+ async function redactMessageText(text, redactChunk) {
4502
+ if (!text.includes("<system-reminder>")) {
4503
+ return redactChunk(text, false, true);
4504
+ }
4505
+ const parts = text.split(SYSTEM_REMINDER_SPLIT_RE);
4506
+ for (let i = 0; i < parts.length; i += 1) {
4507
+ const segment = parts[i] ?? "";
4508
+ if (!segment.trim()) continue;
4509
+ if (segment.startsWith("<system-reminder>") && segment.endsWith("</system-reminder>")) {
4510
+ parts[i] = await redactSystemText(segment, redactChunk);
4511
+ } else {
4512
+ parts[i] = await redactChunk(segment, false, true);
4513
+ }
4514
+ }
4515
+ return parts.join("");
4516
+ }
4517
+ async function extractSafeUpstreamError(resBuf, status, engine) {
4518
+ if (status < 400 || resBuf.byteLength === 0) return void 0;
4519
+ let summary = "";
4520
+ try {
4521
+ const parsed = JSON.parse(resBuf.toString("utf8"));
4522
+ if (isPlainObject(parsed)) {
4523
+ const errObj = isPlainObject(parsed.error) ? parsed.error : parsed;
4524
+ const parts = [];
4525
+ if (typeof errObj.type === "string" && errObj.type.trim()) parts.push(errObj.type.trim());
4526
+ if (typeof errObj.code === "string" && errObj.code.trim()) parts.push(errObj.code.trim());
4527
+ if (typeof errObj.message === "string" && errObj.message.trim()) {
4528
+ parts.push(errObj.message.trim());
4529
+ }
4530
+ summary = parts.join(": ");
4531
+ }
4532
+ } catch {
4533
+ const raw = resBuf.toString("utf8").trim();
4534
+ if (raw && !raw.startsWith("<")) summary = raw;
4535
+ }
4536
+ if (!summary) return void 0;
4537
+ const trimmed = summary.length > 240 ? `${summary.slice(0, 240)}...` : summary;
4538
+ try {
4539
+ const { result } = await engine.redact(trimmed, { mode: "rules" });
4540
+ return result.text;
4541
+ } catch {
4542
+ return `HTTP ${status}`;
4543
+ }
4180
4544
  }
4181
4545
  function headerFirst(headers, name) {
4182
4546
  const value = headers[name];
@@ -4247,13 +4611,14 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
4247
4611
  noteBinary("input_audio");
4248
4612
  }
4249
4613
  if (typeof block.text === "string") {
4250
- block.text = await redactString(block.text, kind);
4614
+ const blockKind = kind === "message" && isToolCatalogJson(block.text) ? "tool_description" : kind;
4615
+ block.text = await redactString(block.text, blockKind);
4251
4616
  }
4252
4617
  if (typeof block.refusal === "string") {
4253
4618
  block.refusal = await redactString(block.refusal, kind);
4254
4619
  }
4255
4620
  if (typeof block.thinking === "string") {
4256
- const redactedThinking = await redactString(block.thinking, kind);
4621
+ const redactedThinking = await redactString(block.thinking, "reasoning");
4257
4622
  if (redactedThinking !== block.thinking) {
4258
4623
  block.thinking = redactedThinking;
4259
4624
  delete block.signature;
@@ -4266,12 +4631,14 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
4266
4631
  block.context = await redactString(block.context, kind);
4267
4632
  }
4268
4633
  if (typeof block.content === "string") {
4269
- block.content = await redactString(block.content, kind);
4634
+ const blockKind = blockType === "tool_result" && isToolCatalogJson(block.content) ? "tool_description" : kind;
4635
+ block.content = await redactString(block.content, blockKind);
4270
4636
  } else if (Array.isArray(block.content)) {
4271
4637
  await redactContentBlocks(block.content, kind);
4272
4638
  }
4273
4639
  if (typeof block.output === "string") {
4274
- block.output = await redactString(block.output, kind);
4640
+ const blockKind = kind === "message" && isToolCatalogJson(block.output) ? "tool_description" : kind;
4641
+ block.output = await redactString(block.output, blockKind);
4275
4642
  } else if (Array.isArray(block.output)) {
4276
4643
  await redactContentBlocks(block.output, kind);
4277
4644
  }
@@ -4410,15 +4777,16 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
4410
4777
  msg.name = await redactString(msg.name, "tool_description");
4411
4778
  }
4412
4779
  if (typeof msg.content === "string") {
4413
- msg.content = await redactString(msg.content, msgKind);
4780
+ const contentKind = msg.role === "tool" && isToolCatalogJson(msg.content) ? "tool_description" : msgKind;
4781
+ msg.content = await redactString(msg.content, contentKind);
4414
4782
  } else if (Array.isArray(msg.content)) {
4415
4783
  await redactContentBlocks(msg.content, msgKind);
4416
4784
  }
4417
4785
  if (typeof msg.reasoning_content === "string") {
4418
- msg.reasoning_content = await redactString(msg.reasoning_content, msgKind);
4786
+ msg.reasoning_content = await redactString(msg.reasoning_content, "reasoning");
4419
4787
  }
4420
4788
  if (typeof msg.reasoning === "string") {
4421
- msg.reasoning = await redactString(msg.reasoning, msgKind);
4789
+ msg.reasoning = await redactString(msg.reasoning, "reasoning");
4422
4790
  }
4423
4791
  if (typeof msg.refusal === "string") {
4424
4792
  msg.refusal = await redactString(msg.refusal, msgKind);
@@ -4459,7 +4827,8 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
4459
4827
  await redactContentBlocks(item.content, itemKind);
4460
4828
  }
4461
4829
  if (typeof item.output === "string") {
4462
- item.output = await redactString(item.output, itemKind);
4830
+ const outKind = item.type === "function_call_output" && isToolCatalogJson(item.output) ? "tool_description" : itemKind;
4831
+ item.output = await redactString(item.output, outKind);
4463
4832
  } else if (Array.isArray(item.output)) {
4464
4833
  await redactContentBlocks(item.output, itemKind);
4465
4834
  }
@@ -4469,10 +4838,10 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
4469
4838
  item.input = await redactObjectStrings(item.input, itemKind);
4470
4839
  }
4471
4840
  if (typeof item.reasoning_content === "string") {
4472
- item.reasoning_content = await redactString(item.reasoning_content, itemKind);
4841
+ item.reasoning_content = await redactString(item.reasoning_content, "reasoning");
4473
4842
  }
4474
4843
  if (typeof item.reasoning === "string") {
4475
- item.reasoning = await redactString(item.reasoning, itemKind);
4844
+ item.reasoning = await redactString(item.reasoning, "reasoning");
4476
4845
  }
4477
4846
  if (typeof item.refusal === "string") {
4478
4847
  item.refusal = await redactString(item.refusal, itemKind);
@@ -4488,9 +4857,18 @@ async function redactLlmRequestBody(body, redactString, options = {}) {
4488
4857
  }
4489
4858
  return clone;
4490
4859
  }
4860
+ function filterMapExcluding(map, excluded) {
4861
+ if (!excluded || excluded.size === 0) return map;
4862
+ const out = {};
4863
+ for (const [token, value] of Object.entries(map)) {
4864
+ if (!excluded.has(token)) out[token] = value;
4865
+ }
4866
+ return out;
4867
+ }
4491
4868
  function restoreLlmResponseBody(body, map, options = {}) {
4492
4869
  if (!isPlainObject(body) || Object.keys(map).length === 0) return body;
4493
4870
  const clone = options.mutate ? body : structuredClone(body);
4871
+ const reasoningMap = filterMapExcluding(map, options.reasoningExcludedTokens);
4494
4872
  if (Array.isArray(clone.content)) {
4495
4873
  for (const block of clone.content) {
4496
4874
  if (!isPlainObject(block)) continue;
@@ -4498,7 +4876,7 @@ function restoreLlmResponseBody(body, map, options = {}) {
4498
4876
  block.text = restorePlainText(block.text, map);
4499
4877
  }
4500
4878
  if (typeof block.thinking === "string" && typeof block.signature !== "string") {
4501
- block.thinking = restorePlainText(block.thinking, map);
4879
+ block.thinking = restorePlainText(block.thinking, reasoningMap);
4502
4880
  }
4503
4881
  if (isPlainObject(block.input)) {
4504
4882
  const skipRestore = isMaskeraVaultToolName(block.name) || block.name === "execute" && typeof block.input.code === "string" && MASKERA_VAULT_CODE_RE.test(block.input.code);
@@ -4517,10 +4895,10 @@ function restoreLlmResponseBody(body, map, options = {}) {
4517
4895
  msg.content = restorePlainText(msg.content, map);
4518
4896
  }
4519
4897
  if (typeof msg.reasoning_content === "string") {
4520
- msg.reasoning_content = restorePlainText(msg.reasoning_content, map);
4898
+ msg.reasoning_content = restorePlainText(msg.reasoning_content, reasoningMap);
4521
4899
  }
4522
4900
  if (typeof msg.reasoning === "string") {
4523
- msg.reasoning = restorePlainText(msg.reasoning, map);
4901
+ msg.reasoning = restorePlainText(msg.reasoning, reasoningMap);
4524
4902
  }
4525
4903
  if (Array.isArray(msg.tool_calls)) {
4526
4904
  for (const call of msg.tool_calls) {
@@ -4569,14 +4947,15 @@ function restoreLlmResponseBody(body, map, options = {}) {
4569
4947
  }
4570
4948
  return clone;
4571
4949
  }
4572
- function createSseRestorer(map) {
4950
+ function createSseRestorer(map, options = {}) {
4951
+ const reasoningMap = filterMapExcluding(map, options.reasoningExcludedTokens);
4573
4952
  const streams = /* @__PURE__ */ new Map();
4574
4953
  const toolNames = /* @__PURE__ */ new Map();
4575
4954
  const bufferedToolArgs = /* @__PURE__ */ new Map();
4576
- const getStream = (key, escapeForJsonString = false) => {
4955
+ const getStream = (key, escapeForJsonString = false, useReasoningMap = false) => {
4577
4956
  let r = streams.get(key);
4578
4957
  if (!r) {
4579
- r = new StreamingRestorer(map, { escapeForJsonString });
4958
+ r = new StreamingRestorer(useReasoningMap ? reasoningMap : map, { escapeForJsonString });
4580
4959
  streams.set(key, r);
4581
4960
  }
4582
4961
  return r;
@@ -4774,7 +5153,9 @@ data: ${JSON.stringify({
4774
5153
  if (parsed.delta.type === "text_delta" && typeof parsed.delta.text === "string") {
4775
5154
  parsed.delta.text = getStream(`anth_text:${idx}`).push(parsed.delta.text);
4776
5155
  } else if (parsed.delta.type === "thinking_delta" && typeof parsed.delta.thinking === "string") {
4777
- parsed.delta.thinking = getStream(`anth_thinking:${idx}`).push(parsed.delta.thinking);
5156
+ parsed.delta.thinking = getStream(`anth_thinking:${idx}`, false, true).push(
5157
+ parsed.delta.thinking
5158
+ );
4778
5159
  } else if (parsed.delta.type === "input_json_delta" && typeof parsed.delta.partial_json === "string") {
4779
5160
  const key = `anth_json:${idx}`;
4780
5161
  const name = toolNames.get(key);
@@ -4838,12 +5219,14 @@ data: ${JSON.stringify({
4838
5219
  delta.content = getStream(`openai_chat_text:${cIdx}`).push(delta.content);
4839
5220
  }
4840
5221
  if (typeof delta.reasoning_content === "string") {
4841
- delta.reasoning_content = getStream(`openai_chat_reasoning:${cIdx}`).push(
4842
- delta.reasoning_content
4843
- );
5222
+ delta.reasoning_content = getStream(
5223
+ `openai_chat_reasoning:${cIdx}`,
5224
+ false,
5225
+ true
5226
+ ).push(delta.reasoning_content);
4844
5227
  }
4845
5228
  if (typeof delta.reasoning === "string") {
4846
- delta.reasoning = getStream(`openai_chat_reasoning_plain:${cIdx}`).push(
5229
+ delta.reasoning = getStream(`openai_chat_reasoning_plain:${cIdx}`, false, true).push(
4847
5230
  delta.reasoning
4848
5231
  );
4849
5232
  }
@@ -4872,7 +5255,7 @@ data: ${JSON.stringify({
4872
5255
  }
4873
5256
  }
4874
5257
  }
4875
- if (choice.finish_reason !== null && choice.finish_reason !== void 0) {
5258
+ if (typeof choice.finish_reason === "string" && choice.finish_reason.length > 0) {
4876
5259
  const textTail = flushStream(`openai_chat_text:${cIdx}`);
4877
5260
  if (textTail) {
4878
5261
  if (!isPlainObject(choice.delta)) choice.delta = {};
@@ -5333,6 +5716,8 @@ async function startMaskeraProxy(options = {}) {
5333
5716
  };
5334
5717
  const mcpSessions = /* @__PURE__ */ new Map();
5335
5718
  const closedMcpSessions = /* @__PURE__ */ new Set();
5719
+ const messageTokensBySession = /* @__PURE__ */ new Map();
5720
+ const externalToolTokensBySession = /* @__PURE__ */ new Map();
5336
5721
  if (auditLogPath) {
5337
5722
  await mkdir(dirname(auditLogPath), { recursive: true });
5338
5723
  await appendFile(auditLogPath, "", { encoding: "utf8", mode: 384 });
@@ -5514,6 +5899,8 @@ async function startMaskeraProxy(options = {}) {
5514
5899
  approvals.clearAll();
5515
5900
  engine.clearCache();
5516
5901
  inspector.clear();
5902
+ messageTokensBySession.clear();
5903
+ externalToolTokensBySession.clear();
5517
5904
  totalRequests = 0;
5518
5905
  totalRedactions = 0;
5519
5906
  totalCounts = {};
@@ -5633,6 +6020,11 @@ async function startMaskeraProxy(options = {}) {
5633
6020
  res.end(JSON.stringify({ error: "Unknown inspector route." }));
5634
6021
  return;
5635
6022
  }
6023
+ if ((method === "GET" || method === "HEAD") && BROWSER_PROBE_PATHS.has(normalizedPath)) {
6024
+ res.writeHead(204, INSPECTOR_SECURITY_HEADERS);
6025
+ res.end();
6026
+ return;
6027
+ }
5636
6028
  if (normalizedPath === "/mcp" || normalizedPath === "/mcp/") {
5637
6029
  if (!isLoopbackRemoteAddress(req.socket.remoteAddress) || !isLoopbackHost(req.headers.host, host, boundPort, true)) {
5638
6030
  res.writeHead(403, {
@@ -5862,9 +6254,22 @@ async function startMaskeraProxy(options = {}) {
5862
6254
  return;
5863
6255
  }
5864
6256
  sessionId = deriveProxySessionId(req.headers, parsed);
6257
+ let externalTokensForSession = externalToolTokensBySession.get(sessionId);
6258
+ const incomingToolTokens = /* @__PURE__ */ new Set();
6259
+ collectExternalToolResultPlaceholders(parsed, incomingToolTokens);
6260
+ if (incomingToolTokens.size > 0) {
6261
+ if (!externalTokensForSession) {
6262
+ externalTokensForSession = /* @__PURE__ */ new Set();
6263
+ externalToolTokensBySession.set(sessionId, externalTokensForSession);
6264
+ }
6265
+ for (const tok of incomingToolTokens) externalTokensForSession.add(tok);
6266
+ }
6267
+ let messageTokensForSession = messageTokensBySession.get(sessionId);
5865
6268
  let redactedObj;
5866
6269
  try {
5867
- const redactChunk = async (chunk, forceRules) => {
6270
+ const messagePreviews = [];
6271
+ const fallbackPreviews = [];
6272
+ const redactChunk = async (chunk, forceRules, previewable) => {
5868
6273
  if (!chunk.trim()) return chunk;
5869
6274
  const { result } = await engine.redact(chunk, {
5870
6275
  mode: forceRules ? "rules" : void 0,
@@ -5874,9 +6279,20 @@ async function startMaskeraProxy(options = {}) {
5874
6279
  const applied = vault.apply(chunk, result, sessionId, proxyVaultOwner);
5875
6280
  stats.redactions += applied.totalRedactions;
5876
6281
  mergeCounts(stats.counts, applied.counts);
5877
- if (redactedPreview.length < 6) {
5878
- const snippet = applied.redacted.length > 1200 ? `${applied.redacted.slice(0, 1200)}...` : applied.redacted;
5879
- redactedPreview.push(snippet);
6282
+ if (previewable && applied.totalRedactions > 0) {
6283
+ if (!messageTokensForSession) {
6284
+ messageTokensForSession = /* @__PURE__ */ new Set();
6285
+ messageTokensBySession.set(sessionId, messageTokensForSession);
6286
+ }
6287
+ for (const tok of Object.keys(applied.map)) {
6288
+ messageTokensForSession.add(tok);
6289
+ }
6290
+ }
6291
+ const snippet = applied.redacted.length > 1200 ? `${applied.redacted.slice(0, 1200)}...` : applied.redacted;
6292
+ if (previewable) {
6293
+ if (messagePreviews.length < 6) messagePreviews.push(snippet);
6294
+ } else if (applied.totalRedactions > 0 && fallbackPreviews.length < 4) {
6295
+ fallbackPreviews.push(snippet);
5880
6296
  }
5881
6297
  return applied.redacted;
5882
6298
  };
@@ -5885,21 +6301,12 @@ async function startMaskeraProxy(options = {}) {
5885
6301
  async (text, kind) => {
5886
6302
  if (!text.trim()) return text;
5887
6303
  if (kind === "tool_description") {
5888
- return redactChunk(text, true);
6304
+ return redactChunk(text, true, false);
5889
6305
  }
5890
- if (kind === "system") {
5891
- if (text.length >= 600 && text.includes("\n\n")) {
5892
- const parts = text.split(/(\n{2,})/);
5893
- for (let i = 0; i < parts.length; i += 2) {
5894
- const para = parts[i] ?? "";
5895
- if (!para.trim()) continue;
5896
- parts[i] = await redactChunk(para, isLikelyEnglishSystemPrompt(para));
5897
- }
5898
- return parts.join("");
5899
- }
5900
- return redactChunk(text, isLikelyEnglishSystemPrompt(text));
6306
+ if (kind === "system" || kind === "reasoning") {
6307
+ return redactSystemText(text, redactChunk);
5901
6308
  }
5902
- return redactChunk(text, false);
6309
+ return redactMessageText(text, redactChunk);
5903
6310
  },
5904
6311
  {
5905
6312
  mutate: true,
@@ -5908,6 +6315,7 @@ async function startMaskeraProxy(options = {}) {
5908
6315
  }
5909
6316
  }
5910
6317
  );
6318
+ redactedPreview.push(...messagePreviews.length > 0 ? messagePreviews : fallbackPreviews);
5911
6319
  } catch (err) {
5912
6320
  recordAuditAndInspector({
5913
6321
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
@@ -6019,13 +6427,23 @@ async function startMaskeraProxy(options = {}) {
6019
6427
  if (requestWarnings) {
6020
6428
  outHeaders["x-maskera-warning"] = "uninspectable-binary-attachment";
6021
6429
  }
6022
- const sessionMap = restoreResponses ? vault.getMap(sessionId, proxyVaultOwner) : {};
6430
+ const rawSessionMap = restoreResponses ? vault.getMap(sessionId, proxyVaultOwner) : {};
6431
+ const externalTokens = externalToolTokensBySession.get(sessionId);
6432
+ const messageTokens = messageTokensBySession.get(sessionId);
6433
+ let sessionMap = rawSessionMap;
6434
+ if (externalTokens && externalTokens.size > 0) {
6435
+ sessionMap = {};
6436
+ for (const [token, value] of Object.entries(rawSessionMap)) {
6437
+ if (externalTokens.has(token) && !messageTokens?.has(token)) continue;
6438
+ sessionMap[token] = value;
6439
+ }
6440
+ }
6023
6441
  const hasMap = Object.keys(sessionMap).length > 0;
6024
6442
  const resContentType = (upstreamRes.headers.get("content-type") ?? "").toLowerCase();
6025
6443
  const isSse = resContentType.includes("text/event-stream");
6026
6444
  if (isSse && upstreamRes.body) {
6027
6445
  res.writeHead(upstreamRes.status, outHeaders);
6028
- const sse = hasMap ? createSseRestorer(sessionMap) : null;
6446
+ const sse = hasMap ? createSseRestorer(sessionMap, { reasoningExcludedTokens: externalTokens }) : null;
6029
6447
  const decoder = sse ? new TextDecoder() : null;
6030
6448
  const reader = upstreamRes.body.getReader();
6031
6449
  const onStreamAbort = () => {
@@ -6084,10 +6502,14 @@ async function startMaskeraProxy(options = {}) {
6084
6502
  } finally {
6085
6503
  res.off("close", onClientClose);
6086
6504
  }
6505
+ const errorDetail = await extractSafeUpstreamError(resBuf, upstreamRes.status, engine);
6087
6506
  if (hasMap && resContentType.includes("application/json")) {
6088
6507
  try {
6089
6508
  const parsed = JSON.parse(resBuf.toString("utf8"));
6090
- const restored = restoreLlmResponseBody(parsed, sessionMap, { mutate: true });
6509
+ const restored = restoreLlmResponseBody(parsed, sessionMap, {
6510
+ mutate: true,
6511
+ reasoningExcludedTokens: externalTokens
6512
+ });
6091
6513
  const restoredBuf = Buffer.from(JSON.stringify(restored), "utf8");
6092
6514
  res.writeHead(upstreamRes.status, outHeaders);
6093
6515
  res.end(restoredBuf);
@@ -6104,6 +6526,7 @@ async function startMaskeraProxy(options = {}) {
6104
6526
  redactions: stats.redactions,
6105
6527
  counts: stats.counts,
6106
6528
  redactedPreview,
6529
+ ...errorDetail ? { errorDetail } : {},
6107
6530
  ...requestWarnings ? { warnings: requestWarnings } : {}
6108
6531
  });
6109
6532
  log(
@@ -6128,6 +6551,7 @@ async function startMaskeraProxy(options = {}) {
6128
6551
  redactions: stats.redactions,
6129
6552
  counts: stats.counts,
6130
6553
  redactedPreview,
6554
+ ...errorDetail ? { errorDetail } : {},
6131
6555
  ...requestWarnings ? { warnings: requestWarnings } : {}
6132
6556
  });
6133
6557
  log(