@maskera/mcp 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +72 -2
- package/dist/cli.js +1732 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.d.ts +237 -0
- package/dist/index.js +1476 -0
- package/dist/index.js.map +1 -0
- package/package.json +60 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,1476 @@
|
|
|
1
|
+
import { MASKERA_SV_NER_MODEL, MASKERA_SV_NER_REVISION, hybridDefaultDetectors, redactFromDetections, runDetectors, clinicalPrecisionFilter, redact, redactWithNer, restore, createNerRecognizer } from 'maskera';
|
|
2
|
+
import { mkdir, writeFile, realpath, stat, readFile } from 'fs/promises';
|
|
3
|
+
import { resolve, dirname, isAbsolute, relative } from 'path';
|
|
4
|
+
import { createServer } from 'http';
|
|
5
|
+
import { randomUUID } from 'crypto';
|
|
6
|
+
|
|
7
|
+
// src/engine.ts
|
|
8
|
+
var WORD_CHAR = /[\p{L}\p{N}_]/u;
|
|
9
|
+
function escapeRegExp(value) {
|
|
10
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
11
|
+
}
|
|
12
|
+
function buildCustomTermsDetector(rawTerms) {
|
|
13
|
+
const unique = /* @__PURE__ */ new Map();
|
|
14
|
+
for (const raw of rawTerms) {
|
|
15
|
+
if (typeof raw !== "string") continue;
|
|
16
|
+
const trimmed = raw.trim();
|
|
17
|
+
if (trimmed.length < 2 || trimmed.length > 160) continue;
|
|
18
|
+
const folded = trimmed.toLowerCase();
|
|
19
|
+
if (!unique.has(folded)) unique.set(folded, trimmed);
|
|
20
|
+
if (unique.size >= 200) break;
|
|
21
|
+
}
|
|
22
|
+
if (unique.size === 0) return null;
|
|
23
|
+
const sorted = [...unique.values()].sort((a, b) => b.length - a.length);
|
|
24
|
+
const pattern = new RegExp(sorted.map(escapeRegExp).join("|"), "giu");
|
|
25
|
+
return {
|
|
26
|
+
label: "EGENT",
|
|
27
|
+
detect(text) {
|
|
28
|
+
const out = [];
|
|
29
|
+
pattern.lastIndex = 0;
|
|
30
|
+
for (let m = pattern.exec(text); m !== null; m = pattern.exec(text)) {
|
|
31
|
+
const start = m.index;
|
|
32
|
+
const value = m[0];
|
|
33
|
+
const end = start + value.length;
|
|
34
|
+
const before = start > 0 ? text[start - 1] ?? "" : "";
|
|
35
|
+
const after = end < text.length ? text[end] ?? "" : "";
|
|
36
|
+
if (WORD_CHAR.test(value[0] ?? "") && WORD_CHAR.test(before) || WORD_CHAR.test(value[value.length - 1] ?? "") && WORD_CHAR.test(after)) {
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
out.push({ start, end, value });
|
|
40
|
+
}
|
|
41
|
+
return out;
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
function createMaskeraEngine(options = {}) {
|
|
46
|
+
const defaultMode = options.defaultMode ?? "auto";
|
|
47
|
+
const model = options.nerOptions?.model ?? MASKERA_SV_NER_MODEL;
|
|
48
|
+
const revision = options.nerOptions?.revision ?? (model === MASKERA_SV_NER_MODEL ? MASKERA_SV_NER_REVISION : void 0);
|
|
49
|
+
let recognizer = options.recognizer ?? null;
|
|
50
|
+
let nerLoaded = false;
|
|
51
|
+
let nerError = null;
|
|
52
|
+
function getRecognizer() {
|
|
53
|
+
if (!recognizer) {
|
|
54
|
+
recognizer = createNerRecognizer({
|
|
55
|
+
...options.nerOptions,
|
|
56
|
+
model,
|
|
57
|
+
revision
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
return recognizer;
|
|
61
|
+
}
|
|
62
|
+
return {
|
|
63
|
+
async redact(text, req = {}) {
|
|
64
|
+
const requestedMode = req.mode ?? defaultMode;
|
|
65
|
+
const customDetector = req.customTerms ? buildCustomTermsDetector(req.customTerms) : null;
|
|
66
|
+
const detectors = customDetector ? [...hybridDefaultDetectors, customDetector] : hybridDefaultDetectors;
|
|
67
|
+
if (requestedMode === "rules") {
|
|
68
|
+
const result = req.profile === "clinical" ? redactFromDetections(
|
|
69
|
+
text,
|
|
70
|
+
runDetectors(text, detectors).filter(
|
|
71
|
+
(d) => clinicalPrecisionFilter(d, text, "rule")
|
|
72
|
+
)
|
|
73
|
+
) : redact(text, { detectors });
|
|
74
|
+
return {
|
|
75
|
+
result,
|
|
76
|
+
modeUsed: "rules"
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
try {
|
|
80
|
+
const ner = getRecognizer();
|
|
81
|
+
const result = await redactWithNer(text, {
|
|
82
|
+
recognizer: ner,
|
|
83
|
+
detectors,
|
|
84
|
+
profile: req.profile
|
|
85
|
+
});
|
|
86
|
+
nerLoaded = true;
|
|
87
|
+
nerError = null;
|
|
88
|
+
return { result, modeUsed: "hybrid" };
|
|
89
|
+
} catch (err) {
|
|
90
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
91
|
+
nerError = message;
|
|
92
|
+
throw new Error(
|
|
93
|
+
`Hybrid NER failed to run (${message}). Pass mode="rules" explicitly if you only want deterministic structured redaction.`
|
|
94
|
+
);
|
|
95
|
+
}
|
|
96
|
+
},
|
|
97
|
+
status() {
|
|
98
|
+
return {
|
|
99
|
+
defaultMode,
|
|
100
|
+
model,
|
|
101
|
+
revision: revision ?? "local",
|
|
102
|
+
nerLoaded,
|
|
103
|
+
nerError
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
var MAX_FILE_BYTES = 2 * 1024 * 1024;
|
|
109
|
+
function isWithinRoot(root, target) {
|
|
110
|
+
const rel = relative(root, target);
|
|
111
|
+
return rel === "" || !rel.startsWith("..") && !isAbsolute(rel);
|
|
112
|
+
}
|
|
113
|
+
async function resolveExistingAncestor(target) {
|
|
114
|
+
let current = resolve(target);
|
|
115
|
+
const segments = [];
|
|
116
|
+
for (; ; ) {
|
|
117
|
+
try {
|
|
118
|
+
const real = await realpath(current);
|
|
119
|
+
return { ancestor: real, tail: segments.reverse().join("/") };
|
|
120
|
+
} catch {
|
|
121
|
+
const parent = dirname(current);
|
|
122
|
+
if (parent === current) {
|
|
123
|
+
throw new Error(`Cannot resolve path "${target}".`);
|
|
124
|
+
}
|
|
125
|
+
segments.push(relative(parent, current));
|
|
126
|
+
current = parent;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
function createFileGuard(roots = [process.cwd()]) {
|
|
131
|
+
const rawRoots = roots.length > 0 ? roots : [process.cwd()];
|
|
132
|
+
let canonicalRootsPromise = null;
|
|
133
|
+
function getCanonicalRoots() {
|
|
134
|
+
if (!canonicalRootsPromise) {
|
|
135
|
+
canonicalRootsPromise = Promise.all(
|
|
136
|
+
rawRoots.map(async (root) => {
|
|
137
|
+
const abs = resolve(root);
|
|
138
|
+
try {
|
|
139
|
+
return await realpath(abs);
|
|
140
|
+
} catch {
|
|
141
|
+
return abs;
|
|
142
|
+
}
|
|
143
|
+
})
|
|
144
|
+
);
|
|
145
|
+
}
|
|
146
|
+
return canonicalRootsPromise;
|
|
147
|
+
}
|
|
148
|
+
function resolveAgainstBase(filePath) {
|
|
149
|
+
const trimmed = filePath.trim();
|
|
150
|
+
if (!trimmed) throw new Error("Path must not be empty.");
|
|
151
|
+
return isAbsolute(trimmed) ? resolve(trimmed) : resolve(rawRoots[0] ?? process.cwd(), trimmed);
|
|
152
|
+
}
|
|
153
|
+
return {
|
|
154
|
+
allowedRoots: rawRoots.map((r) => resolve(r)),
|
|
155
|
+
async readText(filePath) {
|
|
156
|
+
const rootsList = await getCanonicalRoots();
|
|
157
|
+
const candidate = resolveAgainstBase(filePath);
|
|
158
|
+
const { ancestor, tail } = await resolveExistingAncestor(candidate);
|
|
159
|
+
const candidateReal = tail ? resolve(ancestor, tail) : ancestor;
|
|
160
|
+
if (!rootsList.some((root) => isWithinRoot(root, candidateReal))) {
|
|
161
|
+
throw new Error(
|
|
162
|
+
`Access denied: "${filePath}" is outside allowed workspace roots (${rootsList.join(", ")}).`
|
|
163
|
+
);
|
|
164
|
+
}
|
|
165
|
+
const real = await realpath(candidate).catch(() => {
|
|
166
|
+
throw new Error(`File not found: "${filePath}".`);
|
|
167
|
+
});
|
|
168
|
+
if (!rootsList.some((root) => isWithinRoot(root, real))) {
|
|
169
|
+
throw new Error(
|
|
170
|
+
`Access denied: "${filePath}" is outside allowed workspace roots (${rootsList.join(", ")}).`
|
|
171
|
+
);
|
|
172
|
+
}
|
|
173
|
+
const info = await stat(real);
|
|
174
|
+
if (!info.isFile()) {
|
|
175
|
+
throw new Error(`"${filePath}" is not a regular file.`);
|
|
176
|
+
}
|
|
177
|
+
if (info.size > MAX_FILE_BYTES) {
|
|
178
|
+
throw new Error(
|
|
179
|
+
`File "${filePath}" is ${info.size} bytes (max ${MAX_FILE_BYTES} bytes for local redaction).`
|
|
180
|
+
);
|
|
181
|
+
}
|
|
182
|
+
const buffer = await readFile(real);
|
|
183
|
+
if (buffer.includes(0)) {
|
|
184
|
+
throw new Error(`"${filePath}" appears to be a binary file; only UTF-8 text is supported.`);
|
|
185
|
+
}
|
|
186
|
+
return {
|
|
187
|
+
resolvedPath: real,
|
|
188
|
+
content: buffer.toString("utf8"),
|
|
189
|
+
bytes: buffer.byteLength
|
|
190
|
+
};
|
|
191
|
+
},
|
|
192
|
+
async writeText(filePath, content, options = {}) {
|
|
193
|
+
const rootsList = await getCanonicalRoots();
|
|
194
|
+
const candidate = resolveAgainstBase(filePath);
|
|
195
|
+
const { ancestor, tail } = await resolveExistingAncestor(candidate);
|
|
196
|
+
const targetReal = tail ? resolve(ancestor, tail) : ancestor;
|
|
197
|
+
if (!rootsList.some((root) => isWithinRoot(root, targetReal))) {
|
|
198
|
+
throw new Error(
|
|
199
|
+
`Access denied: "${filePath}" is outside allowed workspace roots (${rootsList.join(", ")}).`
|
|
200
|
+
);
|
|
201
|
+
}
|
|
202
|
+
const bytes = Buffer.byteLength(content, "utf8");
|
|
203
|
+
if (bytes > MAX_FILE_BYTES) {
|
|
204
|
+
throw new Error(`Output exceeds max allowed size (${MAX_FILE_BYTES} bytes).`);
|
|
205
|
+
}
|
|
206
|
+
await mkdir(dirname(targetReal), { recursive: true });
|
|
207
|
+
await writeFile(targetReal, content, {
|
|
208
|
+
encoding: "utf8",
|
|
209
|
+
flag: options.overwrite ? "w" : "wx"
|
|
210
|
+
}).catch((err) => {
|
|
211
|
+
if (err.code === "EEXIST") {
|
|
212
|
+
throw new Error(`File already exists: "${filePath}". Pass overwrite=true to replace it.`);
|
|
213
|
+
}
|
|
214
|
+
throw err;
|
|
215
|
+
});
|
|
216
|
+
return { resolvedPath: targetReal, bytes };
|
|
217
|
+
}
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// src/guard.ts
|
|
222
|
+
function extractGuardText(rawInput) {
|
|
223
|
+
const trimmed = rawInput.trim();
|
|
224
|
+
if (trimmed.startsWith("{") && trimmed.endsWith("}")) {
|
|
225
|
+
try {
|
|
226
|
+
const parsed = JSON.parse(trimmed);
|
|
227
|
+
if (typeof parsed.prompt === "string") {
|
|
228
|
+
return { text: parsed.prompt, isHookEnvelope: true };
|
|
229
|
+
}
|
|
230
|
+
if (typeof parsed.user_prompt === "string") {
|
|
231
|
+
return { text: parsed.user_prompt, isHookEnvelope: true };
|
|
232
|
+
}
|
|
233
|
+
if (parsed.tool_input && typeof parsed.tool_input === "object") {
|
|
234
|
+
const parts = [];
|
|
235
|
+
const walk = (v) => {
|
|
236
|
+
if (typeof v === "string") parts.push(v);
|
|
237
|
+
else if (Array.isArray(v)) v.forEach(walk);
|
|
238
|
+
else if (v && typeof v === "object") Object.values(v).forEach(walk);
|
|
239
|
+
};
|
|
240
|
+
walk(parsed.tool_input);
|
|
241
|
+
return { text: parts.join("\n"), isHookEnvelope: true };
|
|
242
|
+
}
|
|
243
|
+
} catch {
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
return { text: rawInput, isHookEnvelope: false };
|
|
247
|
+
}
|
|
248
|
+
async function runGuard(rawInput, engine, options = {}) {
|
|
249
|
+
const { text } = extractGuardText(rawInput);
|
|
250
|
+
if (!text.trim()) {
|
|
251
|
+
return {
|
|
252
|
+
blocked: false,
|
|
253
|
+
totalRedactions: 0,
|
|
254
|
+
counts: {},
|
|
255
|
+
redacted: text,
|
|
256
|
+
modeUsed: options.mode === "rules" ? "rules" : "hybrid"
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
const { result, modeUsed } = await engine.redact(text, {
|
|
260
|
+
mode: options.mode,
|
|
261
|
+
profile: options.profile,
|
|
262
|
+
customTerms: options.customTerms
|
|
263
|
+
});
|
|
264
|
+
const counts = {};
|
|
265
|
+
for (const r of result.redactions) {
|
|
266
|
+
counts[r.label] = (counts[r.label] ?? 0) + 1;
|
|
267
|
+
}
|
|
268
|
+
return {
|
|
269
|
+
blocked: result.redactions.length > 0,
|
|
270
|
+
totalRedactions: result.redactions.length,
|
|
271
|
+
counts,
|
|
272
|
+
redacted: result.text,
|
|
273
|
+
modeUsed
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
var DEFAULT_MAX_SESSIONS = 100;
|
|
277
|
+
function valueKey(label, value) {
|
|
278
|
+
return `${label.length}:${label}:${value}`;
|
|
279
|
+
}
|
|
280
|
+
var SessionVault = class {
|
|
281
|
+
constructor(maxSessions = DEFAULT_MAX_SESSIONS) {
|
|
282
|
+
this.sessions = /* @__PURE__ */ new Map();
|
|
283
|
+
this.maxSessions = Math.max(1, maxSessions);
|
|
284
|
+
}
|
|
285
|
+
getOrCreate(sessionId) {
|
|
286
|
+
const id = sessionId?.trim() || `s_${randomUUID().slice(0, 12)}`;
|
|
287
|
+
const existing = this.sessions.get(id);
|
|
288
|
+
if (existing) {
|
|
289
|
+
this.sessions.delete(id);
|
|
290
|
+
this.sessions.set(id, existing);
|
|
291
|
+
existing.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
292
|
+
return existing;
|
|
293
|
+
}
|
|
294
|
+
if (this.sessions.size >= this.maxSessions) {
|
|
295
|
+
const oldestKey = this.sessions.keys().next().value;
|
|
296
|
+
if (oldestKey !== void 0) this.sessions.delete(oldestKey);
|
|
297
|
+
}
|
|
298
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
299
|
+
const created = {
|
|
300
|
+
id,
|
|
301
|
+
createdAt: now,
|
|
302
|
+
updatedAt: now,
|
|
303
|
+
tokenByKey: /* @__PURE__ */ new Map(),
|
|
304
|
+
map: {},
|
|
305
|
+
counters: /* @__PURE__ */ new Map(),
|
|
306
|
+
countsByLabel: {}
|
|
307
|
+
};
|
|
308
|
+
this.sessions.set(id, created);
|
|
309
|
+
return created;
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Re-number a RedactResult's replacements into a persistent session so that
|
|
313
|
+
* the same entity receives the exact same placeholder across multiple calls
|
|
314
|
+
* and files in the same session, while avoiding collisions with literal text.
|
|
315
|
+
*/
|
|
316
|
+
apply(originalInput, result, sessionId) {
|
|
317
|
+
const session = this.getOrCreate(sessionId);
|
|
318
|
+
const counts = {};
|
|
319
|
+
const localMap = {};
|
|
320
|
+
let redacted = "";
|
|
321
|
+
let cursor = 0;
|
|
322
|
+
for (const r of result.redactions) {
|
|
323
|
+
const key = valueKey(r.label, r.value);
|
|
324
|
+
let token = session.tokenByKey.get(key);
|
|
325
|
+
if (!token) {
|
|
326
|
+
let next = session.counters.get(r.label) ?? 0;
|
|
327
|
+
for (; ; ) {
|
|
328
|
+
next += 1;
|
|
329
|
+
const candidate = `[${r.label}_${next}]`;
|
|
330
|
+
if (!(candidate in session.map) && !originalInput.includes(candidate)) {
|
|
331
|
+
token = candidate;
|
|
332
|
+
break;
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
session.counters.set(r.label, next);
|
|
336
|
+
session.tokenByKey.set(key, token);
|
|
337
|
+
session.map[token] = r.value;
|
|
338
|
+
session.countsByLabel[r.label] = (session.countsByLabel[r.label] ?? 0) + 1;
|
|
339
|
+
}
|
|
340
|
+
localMap[token] = r.value;
|
|
341
|
+
counts[r.label] = (counts[r.label] ?? 0) + 1;
|
|
342
|
+
redacted += originalInput.slice(cursor, r.start) + token;
|
|
343
|
+
cursor = r.end;
|
|
344
|
+
}
|
|
345
|
+
redacted += originalInput.slice(cursor);
|
|
346
|
+
return {
|
|
347
|
+
sessionId: session.id,
|
|
348
|
+
redacted,
|
|
349
|
+
counts,
|
|
350
|
+
totalRedactions: result.redactions.length,
|
|
351
|
+
map: localMap
|
|
352
|
+
};
|
|
353
|
+
}
|
|
354
|
+
restore(text, options) {
|
|
355
|
+
if (options.map && Object.keys(options.map).length > 0) {
|
|
356
|
+
return {
|
|
357
|
+
restored: restore(text, options.map),
|
|
358
|
+
sessionId: options.sessionId ?? null,
|
|
359
|
+
knownPlaceholders: Object.keys(options.map).length
|
|
360
|
+
};
|
|
361
|
+
}
|
|
362
|
+
if (!options.sessionId) {
|
|
363
|
+
throw new Error("Provide either session_id or map to restore placeholders.");
|
|
364
|
+
}
|
|
365
|
+
const session = this.sessions.get(options.sessionId);
|
|
366
|
+
if (!session) {
|
|
367
|
+
throw new Error(`Unknown session_id "${options.sessionId}".`);
|
|
368
|
+
}
|
|
369
|
+
return {
|
|
370
|
+
restored: restore(text, session.map),
|
|
371
|
+
sessionId: session.id,
|
|
372
|
+
knownPlaceholders: Object.keys(session.map).length
|
|
373
|
+
};
|
|
374
|
+
}
|
|
375
|
+
getMap(sessionId) {
|
|
376
|
+
const session = this.sessions.get(sessionId);
|
|
377
|
+
return session ? { ...session.map } : {};
|
|
378
|
+
}
|
|
379
|
+
list() {
|
|
380
|
+
return [...this.sessions.values()].map((s) => ({
|
|
381
|
+
sessionId: s.id,
|
|
382
|
+
entityCount: Object.keys(s.map).length,
|
|
383
|
+
countsByLabel: { ...s.countsByLabel },
|
|
384
|
+
createdAt: s.createdAt,
|
|
385
|
+
updatedAt: s.updatedAt
|
|
386
|
+
}));
|
|
387
|
+
}
|
|
388
|
+
clear(sessionId) {
|
|
389
|
+
return this.sessions.delete(sessionId);
|
|
390
|
+
}
|
|
391
|
+
get size() {
|
|
392
|
+
return this.sessions.size;
|
|
393
|
+
}
|
|
394
|
+
};
|
|
395
|
+
|
|
396
|
+
// src/proxy.ts
|
|
397
|
+
var DEFAULT_ANTHROPIC_UPSTREAM = "https://api.anthropic.com";
|
|
398
|
+
var DEFAULT_OPENAI_UPSTREAM = "https://api.openai.com";
|
|
399
|
+
var MAX_BODY_BYTES = 16 * 1024 * 1024;
|
|
400
|
+
var HOP_BY_HOP_REQUEST_HEADERS = /* @__PURE__ */ new Set([
|
|
401
|
+
"connection",
|
|
402
|
+
"keep-alive",
|
|
403
|
+
"proxy-authenticate",
|
|
404
|
+
"proxy-authorization",
|
|
405
|
+
"te",
|
|
406
|
+
"trailers",
|
|
407
|
+
"transfer-encoding",
|
|
408
|
+
"upgrade",
|
|
409
|
+
"host",
|
|
410
|
+
"content-length",
|
|
411
|
+
"accept-encoding"
|
|
412
|
+
]);
|
|
413
|
+
var HOP_BY_HOP_RESPONSE_HEADERS = /* @__PURE__ */ new Set([
|
|
414
|
+
"connection",
|
|
415
|
+
"keep-alive",
|
|
416
|
+
"proxy-authenticate",
|
|
417
|
+
"proxy-authorization",
|
|
418
|
+
"te",
|
|
419
|
+
"trailers",
|
|
420
|
+
"transfer-encoding",
|
|
421
|
+
"upgrade",
|
|
422
|
+
"content-length",
|
|
423
|
+
"content-encoding"
|
|
424
|
+
]);
|
|
425
|
+
var StreamingRestorer = class {
|
|
426
|
+
constructor(map, options = {}) {
|
|
427
|
+
this.buffer = "";
|
|
428
|
+
this.map = map;
|
|
429
|
+
this.tokens = Object.keys(map).sort((a, b) => b.length - a.length);
|
|
430
|
+
this.maxTokenLength = this.tokens.reduce((max, t) => Math.max(max, t.length), 0);
|
|
431
|
+
this.escapeForJsonString = options.escapeForJsonString === true;
|
|
432
|
+
}
|
|
433
|
+
formatReplacement(value) {
|
|
434
|
+
if (!this.escapeForJsonString) return value;
|
|
435
|
+
return JSON.stringify(value).slice(1, -1);
|
|
436
|
+
}
|
|
437
|
+
push(chunk) {
|
|
438
|
+
if (!chunk || this.tokens.length === 0) return chunk;
|
|
439
|
+
this.buffer += chunk;
|
|
440
|
+
return this.drain(false);
|
|
441
|
+
}
|
|
442
|
+
flush() {
|
|
443
|
+
if (!this.buffer) return "";
|
|
444
|
+
return this.drain(true);
|
|
445
|
+
}
|
|
446
|
+
drain(final) {
|
|
447
|
+
let out = "";
|
|
448
|
+
let cursor = 0;
|
|
449
|
+
const buf = this.buffer;
|
|
450
|
+
while (cursor < buf.length) {
|
|
451
|
+
const bracket = buf.indexOf("[", cursor);
|
|
452
|
+
if (bracket < 0) {
|
|
453
|
+
out += buf.slice(cursor);
|
|
454
|
+
cursor = buf.length;
|
|
455
|
+
break;
|
|
456
|
+
}
|
|
457
|
+
if (bracket > cursor) {
|
|
458
|
+
out += buf.slice(cursor, bracket);
|
|
459
|
+
cursor = bracket;
|
|
460
|
+
}
|
|
461
|
+
const remaining = buf.slice(cursor);
|
|
462
|
+
let matchedToken = null;
|
|
463
|
+
for (const token of this.tokens) {
|
|
464
|
+
if (remaining.startsWith(token)) {
|
|
465
|
+
matchedToken = token;
|
|
466
|
+
break;
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
if (matchedToken) {
|
|
470
|
+
out += this.formatReplacement(this.map[matchedToken] ?? matchedToken);
|
|
471
|
+
cursor += matchedToken.length;
|
|
472
|
+
continue;
|
|
473
|
+
}
|
|
474
|
+
if (!final && remaining.length < this.maxTokenLength) {
|
|
475
|
+
const couldMatch = this.tokens.some((token) => token.startsWith(remaining));
|
|
476
|
+
if (couldMatch) {
|
|
477
|
+
break;
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
out += "[";
|
|
481
|
+
cursor += 1;
|
|
482
|
+
}
|
|
483
|
+
this.buffer = buf.slice(cursor);
|
|
484
|
+
return out;
|
|
485
|
+
}
|
|
486
|
+
};
|
|
487
|
+
function isPlainObject(value) {
|
|
488
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
489
|
+
}
|
|
490
|
+
function mergeCounts(target, delta) {
|
|
491
|
+
for (const [k, v] of Object.entries(delta)) {
|
|
492
|
+
target[k] = (target[k] ?? 0) + v;
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
function restorePlainText(text, map) {
|
|
496
|
+
if (!text || Object.keys(map).length === 0) return text;
|
|
497
|
+
const r = new StreamingRestorer(map);
|
|
498
|
+
return r.push(text) + r.flush();
|
|
499
|
+
}
|
|
500
|
+
function restoreJsonEncodedText(text, map) {
|
|
501
|
+
if (!text || Object.keys(map).length === 0) return text;
|
|
502
|
+
try {
|
|
503
|
+
const parsed = JSON.parse(text);
|
|
504
|
+
const restored = restoreJsonLeaves(parsed, map);
|
|
505
|
+
return JSON.stringify(restored);
|
|
506
|
+
} catch {
|
|
507
|
+
const r = new StreamingRestorer(map, { escapeForJsonString: true });
|
|
508
|
+
return r.push(text) + r.flush();
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
function restoreJsonLeaves(value, map) {
|
|
512
|
+
if (typeof value === "string") return restorePlainText(value, map);
|
|
513
|
+
if (Array.isArray(value)) return value.map((item) => restoreJsonLeaves(item, map));
|
|
514
|
+
if (isPlainObject(value)) {
|
|
515
|
+
const out = {};
|
|
516
|
+
for (const [k, v] of Object.entries(value)) {
|
|
517
|
+
out[k] = restoreJsonLeaves(v, map);
|
|
518
|
+
}
|
|
519
|
+
return out;
|
|
520
|
+
}
|
|
521
|
+
return value;
|
|
522
|
+
}
|
|
523
|
+
async function redactLlmRequestBody(body, redactString) {
|
|
524
|
+
const clone = structuredClone(body);
|
|
525
|
+
async function redactContentBlocks(blocks) {
|
|
526
|
+
for (const block of blocks) {
|
|
527
|
+
if (!isPlainObject(block)) continue;
|
|
528
|
+
if (typeof block.text === "string") {
|
|
529
|
+
block.text = await redactString(block.text);
|
|
530
|
+
}
|
|
531
|
+
if (typeof block.content === "string") {
|
|
532
|
+
block.content = await redactString(block.content);
|
|
533
|
+
} else if (Array.isArray(block.content)) {
|
|
534
|
+
await redactContentBlocks(block.content);
|
|
535
|
+
}
|
|
536
|
+
if (typeof block.output === "string") {
|
|
537
|
+
block.output = await redactString(block.output);
|
|
538
|
+
}
|
|
539
|
+
if (typeof block.arguments === "string") {
|
|
540
|
+
block.arguments = await redactJsonStringOrText(block.arguments);
|
|
541
|
+
}
|
|
542
|
+
if (isPlainObject(block.input)) {
|
|
543
|
+
block.input = await redactObjectStrings(block.input);
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
async function redactObjectStrings(value) {
|
|
548
|
+
if (typeof value === "string") return redactString(value);
|
|
549
|
+
if (Array.isArray(value)) {
|
|
550
|
+
const out = [];
|
|
551
|
+
for (const item of value) out.push(await redactObjectStrings(item));
|
|
552
|
+
return out;
|
|
553
|
+
}
|
|
554
|
+
if (isPlainObject(value)) {
|
|
555
|
+
const out = {};
|
|
556
|
+
for (const [k, v] of Object.entries(value)) {
|
|
557
|
+
out[k] = await redactObjectStrings(v);
|
|
558
|
+
}
|
|
559
|
+
return out;
|
|
560
|
+
}
|
|
561
|
+
return value;
|
|
562
|
+
}
|
|
563
|
+
async function redactJsonStringOrText(raw) {
|
|
564
|
+
try {
|
|
565
|
+
const parsed = JSON.parse(raw);
|
|
566
|
+
const redacted = await redactObjectStrings(parsed);
|
|
567
|
+
return JSON.stringify(redacted);
|
|
568
|
+
} catch {
|
|
569
|
+
return redactString(raw);
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
if (typeof clone.system === "string") {
|
|
573
|
+
clone.system = await redactString(clone.system);
|
|
574
|
+
} else if (Array.isArray(clone.system)) {
|
|
575
|
+
await redactContentBlocks(clone.system);
|
|
576
|
+
}
|
|
577
|
+
if (typeof clone.instructions === "string") {
|
|
578
|
+
clone.instructions = await redactString(clone.instructions);
|
|
579
|
+
}
|
|
580
|
+
if (Array.isArray(clone.messages)) {
|
|
581
|
+
for (const msg of clone.messages) {
|
|
582
|
+
if (!isPlainObject(msg)) continue;
|
|
583
|
+
if (typeof msg.content === "string") {
|
|
584
|
+
msg.content = await redactString(msg.content);
|
|
585
|
+
} else if (Array.isArray(msg.content)) {
|
|
586
|
+
await redactContentBlocks(msg.content);
|
|
587
|
+
}
|
|
588
|
+
if (Array.isArray(msg.tool_calls)) {
|
|
589
|
+
for (const call of msg.tool_calls) {
|
|
590
|
+
if (isPlainObject(call) && isPlainObject(call.function)) {
|
|
591
|
+
if (typeof call.function.arguments === "string") {
|
|
592
|
+
call.function.arguments = await redactJsonStringOrText(call.function.arguments);
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
if (typeof clone.input === "string") {
|
|
600
|
+
clone.input = await redactString(clone.input);
|
|
601
|
+
} else if (Array.isArray(clone.input)) {
|
|
602
|
+
for (let i = 0; i < clone.input.length; i++) {
|
|
603
|
+
const item = clone.input[i];
|
|
604
|
+
if (typeof item === "string") {
|
|
605
|
+
clone.input[i] = await redactString(item);
|
|
606
|
+
} else if (isPlainObject(item)) {
|
|
607
|
+
if (typeof item.text === "string") item.text = await redactString(item.text);
|
|
608
|
+
if (typeof item.content === "string") {
|
|
609
|
+
item.content = await redactString(item.content);
|
|
610
|
+
} else if (Array.isArray(item.content)) {
|
|
611
|
+
await redactContentBlocks(item.content);
|
|
612
|
+
}
|
|
613
|
+
if (typeof item.output === "string") {
|
|
614
|
+
item.output = await redactString(item.output);
|
|
615
|
+
}
|
|
616
|
+
if (typeof item.arguments === "string") {
|
|
617
|
+
item.arguments = await redactJsonStringOrText(item.arguments);
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
return clone;
|
|
623
|
+
}
|
|
624
|
+
function restoreLlmResponseBody(body, map) {
|
|
625
|
+
if (!isPlainObject(body) || Object.keys(map).length === 0) return body;
|
|
626
|
+
const clone = structuredClone(body);
|
|
627
|
+
if (Array.isArray(clone.content)) {
|
|
628
|
+
for (const block of clone.content) {
|
|
629
|
+
if (!isPlainObject(block)) continue;
|
|
630
|
+
if (typeof block.text === "string") {
|
|
631
|
+
block.text = restorePlainText(block.text, map);
|
|
632
|
+
}
|
|
633
|
+
if (typeof block.thinking === "string") {
|
|
634
|
+
block.thinking = restorePlainText(block.thinking, map);
|
|
635
|
+
}
|
|
636
|
+
if (isPlainObject(block.input)) {
|
|
637
|
+
block.input = restoreJsonLeaves(block.input, map);
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
if (Array.isArray(clone.choices)) {
|
|
642
|
+
for (const choice of clone.choices) {
|
|
643
|
+
if (!isPlainObject(choice)) continue;
|
|
644
|
+
const msg = choice.message;
|
|
645
|
+
if (isPlainObject(msg)) {
|
|
646
|
+
if (typeof msg.content === "string") {
|
|
647
|
+
msg.content = restorePlainText(msg.content, map);
|
|
648
|
+
}
|
|
649
|
+
if (Array.isArray(msg.tool_calls)) {
|
|
650
|
+
for (const call of msg.tool_calls) {
|
|
651
|
+
if (isPlainObject(call) && isPlainObject(call.function)) {
|
|
652
|
+
if (typeof call.function.arguments === "string") {
|
|
653
|
+
call.function.arguments = restoreJsonEncodedText(call.function.arguments, map);
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
if (typeof choice.text === "string") {
|
|
660
|
+
choice.text = restorePlainText(choice.text, map);
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
if (typeof clone.output_text === "string") {
|
|
665
|
+
clone.output_text = restorePlainText(clone.output_text, map);
|
|
666
|
+
}
|
|
667
|
+
if (Array.isArray(clone.output)) {
|
|
668
|
+
for (const item of clone.output) {
|
|
669
|
+
if (!isPlainObject(item)) continue;
|
|
670
|
+
if (typeof item.arguments === "string") {
|
|
671
|
+
item.arguments = restoreJsonEncodedText(item.arguments, map);
|
|
672
|
+
}
|
|
673
|
+
if (Array.isArray(item.content)) {
|
|
674
|
+
for (const part of item.content) {
|
|
675
|
+
if (isPlainObject(part) && typeof part.text === "string") {
|
|
676
|
+
part.text = restorePlainText(part.text, map);
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
return clone;
|
|
683
|
+
}
|
|
684
|
+
function createSseRestorer(map) {
|
|
685
|
+
const streams = /* @__PURE__ */ new Map();
|
|
686
|
+
const getStream = (key, escapeForJsonString = false) => {
|
|
687
|
+
let r = streams.get(key);
|
|
688
|
+
if (!r) {
|
|
689
|
+
r = new StreamingRestorer(map, { escapeForJsonString });
|
|
690
|
+
streams.set(key, r);
|
|
691
|
+
}
|
|
692
|
+
return r;
|
|
693
|
+
};
|
|
694
|
+
function flushStream(key) {
|
|
695
|
+
const r = streams.get(key);
|
|
696
|
+
if (!r) return "";
|
|
697
|
+
streams.delete(key);
|
|
698
|
+
return r.flush();
|
|
699
|
+
}
|
|
700
|
+
let sseBuffer = "";
|
|
701
|
+
function processEventBlock(block) {
|
|
702
|
+
const lines = block.split("\n");
|
|
703
|
+
const outLines = [];
|
|
704
|
+
const extraEvents = [];
|
|
705
|
+
for (const line of lines) {
|
|
706
|
+
if (!line.startsWith("data:")) {
|
|
707
|
+
outLines.push(line);
|
|
708
|
+
continue;
|
|
709
|
+
}
|
|
710
|
+
const rawData = line.slice("data:".length).trimStart();
|
|
711
|
+
if (!rawData || rawData === "[DONE]") {
|
|
712
|
+
for (const key of [...streams.keys()]) {
|
|
713
|
+
const tail = flushStream(key);
|
|
714
|
+
if (!tail) continue;
|
|
715
|
+
if (key.startsWith("openai_chat_text:")) {
|
|
716
|
+
const idx = Number(key.split(":")[1] ?? 0);
|
|
717
|
+
extraEvents.push(
|
|
718
|
+
`data: ${JSON.stringify({ choices: [{ index: idx, delta: { content: tail } }] })}`
|
|
719
|
+
);
|
|
720
|
+
} else if (key.startsWith("openai_chat_tool:")) {
|
|
721
|
+
const [, cIdx, tIdx] = key.split(":");
|
|
722
|
+
extraEvents.push(
|
|
723
|
+
`data: ${JSON.stringify({
|
|
724
|
+
choices: [
|
|
725
|
+
{
|
|
726
|
+
index: Number(cIdx ?? 0),
|
|
727
|
+
delta: {
|
|
728
|
+
tool_calls: [{ index: Number(tIdx ?? 0), function: { arguments: tail } }]
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
]
|
|
732
|
+
})}`
|
|
733
|
+
);
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
outLines.push(line);
|
|
737
|
+
continue;
|
|
738
|
+
}
|
|
739
|
+
let parsed;
|
|
740
|
+
try {
|
|
741
|
+
parsed = JSON.parse(rawData);
|
|
742
|
+
} catch {
|
|
743
|
+
outLines.push(line);
|
|
744
|
+
continue;
|
|
745
|
+
}
|
|
746
|
+
if (!isPlainObject(parsed)) {
|
|
747
|
+
outLines.push(line);
|
|
748
|
+
continue;
|
|
749
|
+
}
|
|
750
|
+
if (parsed.type === "content_block_delta" && isPlainObject(parsed.delta)) {
|
|
751
|
+
const idx = typeof parsed.index === "number" ? parsed.index : 0;
|
|
752
|
+
if (parsed.delta.type === "text_delta" && typeof parsed.delta.text === "string") {
|
|
753
|
+
parsed.delta.text = getStream(`anth_text:${idx}`).push(parsed.delta.text);
|
|
754
|
+
} else if (parsed.delta.type === "input_json_delta" && typeof parsed.delta.partial_json === "string") {
|
|
755
|
+
parsed.delta.partial_json = getStream(`anth_json:${idx}`, true).push(
|
|
756
|
+
parsed.delta.partial_json
|
|
757
|
+
);
|
|
758
|
+
}
|
|
759
|
+
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
760
|
+
continue;
|
|
761
|
+
}
|
|
762
|
+
if (parsed.type === "content_block_stop") {
|
|
763
|
+
const idx = typeof parsed.index === "number" ? parsed.index : 0;
|
|
764
|
+
const textTail = flushStream(`anth_text:${idx}`);
|
|
765
|
+
if (textTail) {
|
|
766
|
+
extraEvents.push(
|
|
767
|
+
`event: content_block_delta
|
|
768
|
+
data: ${JSON.stringify({
|
|
769
|
+
type: "content_block_delta",
|
|
770
|
+
index: idx,
|
|
771
|
+
delta: { type: "text_delta", text: textTail }
|
|
772
|
+
})}`
|
|
773
|
+
);
|
|
774
|
+
}
|
|
775
|
+
const jsonTail = flushStream(`anth_json:${idx}`);
|
|
776
|
+
if (jsonTail) {
|
|
777
|
+
extraEvents.push(
|
|
778
|
+
`event: content_block_delta
|
|
779
|
+
data: ${JSON.stringify({
|
|
780
|
+
type: "content_block_delta",
|
|
781
|
+
index: idx,
|
|
782
|
+
delta: { type: "input_json_delta", partial_json: jsonTail }
|
|
783
|
+
})}`
|
|
784
|
+
);
|
|
785
|
+
}
|
|
786
|
+
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
787
|
+
continue;
|
|
788
|
+
}
|
|
789
|
+
if (Array.isArray(parsed.choices)) {
|
|
790
|
+
for (const choice of parsed.choices) {
|
|
791
|
+
if (!isPlainObject(choice)) continue;
|
|
792
|
+
const cIdx = typeof choice.index === "number" ? choice.index : 0;
|
|
793
|
+
const delta = choice.delta;
|
|
794
|
+
if (isPlainObject(delta)) {
|
|
795
|
+
if (typeof delta.content === "string") {
|
|
796
|
+
delta.content = getStream(`openai_chat_text:${cIdx}`).push(delta.content);
|
|
797
|
+
}
|
|
798
|
+
if (Array.isArray(delta.tool_calls)) {
|
|
799
|
+
for (const call of delta.tool_calls) {
|
|
800
|
+
if (!isPlainObject(call)) continue;
|
|
801
|
+
const tIdx = typeof call.index === "number" ? call.index : 0;
|
|
802
|
+
if (isPlainObject(call.function) && typeof call.function.arguments === "string") {
|
|
803
|
+
call.function.arguments = getStream(
|
|
804
|
+
`openai_chat_tool:${cIdx}:${tIdx}`,
|
|
805
|
+
true
|
|
806
|
+
).push(call.function.arguments);
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
if (choice.finish_reason !== null && choice.finish_reason !== void 0) {
|
|
812
|
+
const textTail = flushStream(`openai_chat_text:${cIdx}`);
|
|
813
|
+
if (textTail) {
|
|
814
|
+
if (!isPlainObject(choice.delta)) choice.delta = {};
|
|
815
|
+
const d = choice.delta;
|
|
816
|
+
d.content = (typeof d.content === "string" ? d.content : "") + textTail;
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
821
|
+
continue;
|
|
822
|
+
}
|
|
823
|
+
if (parsed.type === "response.output_text.delta" && typeof parsed.delta === "string") {
|
|
824
|
+
const key = `resp_text:${String(parsed.output_index ?? 0)}:${String(parsed.content_index ?? 0)}`;
|
|
825
|
+
parsed.delta = getStream(key).push(parsed.delta);
|
|
826
|
+
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
827
|
+
continue;
|
|
828
|
+
}
|
|
829
|
+
if (parsed.type === "response.output_text.done") {
|
|
830
|
+
const key = `resp_text:${String(parsed.output_index ?? 0)}:${String(parsed.content_index ?? 0)}`;
|
|
831
|
+
const tail = flushStream(key);
|
|
832
|
+
if (tail) {
|
|
833
|
+
extraEvents.push(
|
|
834
|
+
`event: response.output_text.delta
|
|
835
|
+
data: ${JSON.stringify({
|
|
836
|
+
type: "response.output_text.delta",
|
|
837
|
+
output_index: parsed.output_index ?? 0,
|
|
838
|
+
content_index: parsed.content_index ?? 0,
|
|
839
|
+
delta: tail
|
|
840
|
+
})}`
|
|
841
|
+
);
|
|
842
|
+
}
|
|
843
|
+
if (typeof parsed.text === "string") {
|
|
844
|
+
parsed.text = restorePlainText(parsed.text, map);
|
|
845
|
+
}
|
|
846
|
+
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
847
|
+
continue;
|
|
848
|
+
}
|
|
849
|
+
if (parsed.type === "response.function_call_arguments.delta" && typeof parsed.delta === "string") {
|
|
850
|
+
const key = `resp_args:${String(parsed.output_index ?? 0)}`;
|
|
851
|
+
parsed.delta = getStream(key, true).push(parsed.delta);
|
|
852
|
+
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
853
|
+
continue;
|
|
854
|
+
}
|
|
855
|
+
if (parsed.type === "response.function_call_arguments.done") {
|
|
856
|
+
const key = `resp_args:${String(parsed.output_index ?? 0)}`;
|
|
857
|
+
const tail = flushStream(key);
|
|
858
|
+
if (tail) {
|
|
859
|
+
extraEvents.push(
|
|
860
|
+
`event: response.function_call_arguments.delta
|
|
861
|
+
data: ${JSON.stringify({
|
|
862
|
+
type: "response.function_call_arguments.delta",
|
|
863
|
+
output_index: parsed.output_index ?? 0,
|
|
864
|
+
delta: tail
|
|
865
|
+
})}`
|
|
866
|
+
);
|
|
867
|
+
}
|
|
868
|
+
if (typeof parsed.arguments === "string") {
|
|
869
|
+
parsed.arguments = restoreJsonEncodedText(parsed.arguments, map);
|
|
870
|
+
}
|
|
871
|
+
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
872
|
+
continue;
|
|
873
|
+
}
|
|
874
|
+
if (parsed.type === "response.completed" && isPlainObject(parsed.response)) {
|
|
875
|
+
parsed.response = restoreLlmResponseBody(parsed.response, map);
|
|
876
|
+
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
877
|
+
continue;
|
|
878
|
+
}
|
|
879
|
+
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
880
|
+
}
|
|
881
|
+
const joined = outLines.join("\n");
|
|
882
|
+
return extraEvents.length > 0 ? `${extraEvents.join("\n\n")}
|
|
883
|
+
|
|
884
|
+
${joined}` : joined;
|
|
885
|
+
}
|
|
886
|
+
return {
|
|
887
|
+
push(chunk) {
|
|
888
|
+
sseBuffer += chunk.replace(/\r\n/g, "\n");
|
|
889
|
+
let out = "";
|
|
890
|
+
for (; ; ) {
|
|
891
|
+
const sep = sseBuffer.indexOf("\n\n");
|
|
892
|
+
if (sep < 0) break;
|
|
893
|
+
const block = sseBuffer.slice(0, sep);
|
|
894
|
+
sseBuffer = sseBuffer.slice(sep + 2);
|
|
895
|
+
out += `${processEventBlock(block)}
|
|
896
|
+
|
|
897
|
+
`;
|
|
898
|
+
}
|
|
899
|
+
return out;
|
|
900
|
+
},
|
|
901
|
+
flush() {
|
|
902
|
+
if (!sseBuffer) return "";
|
|
903
|
+
const tail = processEventBlock(sseBuffer);
|
|
904
|
+
sseBuffer = "";
|
|
905
|
+
return tail;
|
|
906
|
+
}
|
|
907
|
+
};
|
|
908
|
+
}
|
|
909
|
+
function resolveUpstreamTarget(urlPath, headers, options) {
|
|
910
|
+
if (urlPath.startsWith("/anthropic/")) {
|
|
911
|
+
return {
|
|
912
|
+
baseUrl: options.anthropicUpstream.replace(/\/$/, ""),
|
|
913
|
+
forwardPath: urlPath.slice("/anthropic".length)
|
|
914
|
+
};
|
|
915
|
+
}
|
|
916
|
+
if (urlPath.startsWith("/openai/")) {
|
|
917
|
+
return {
|
|
918
|
+
baseUrl: options.openaiUpstream.replace(/\/$/, ""),
|
|
919
|
+
forwardPath: urlPath.slice("/openai".length)
|
|
920
|
+
};
|
|
921
|
+
}
|
|
922
|
+
if (options.explicitUpstream) {
|
|
923
|
+
return {
|
|
924
|
+
baseUrl: options.explicitUpstream.replace(/\/$/, ""),
|
|
925
|
+
forwardPath: urlPath
|
|
926
|
+
};
|
|
927
|
+
}
|
|
928
|
+
const isAnthropic = urlPath.startsWith("/v1/messages") || typeof headers["anthropic-version"] === "string" || typeof headers["x-api-key"] === "string";
|
|
929
|
+
return {
|
|
930
|
+
baseUrl: (isAnthropic ? options.anthropicUpstream : options.openaiUpstream).replace(/\/$/, ""),
|
|
931
|
+
forwardPath: urlPath
|
|
932
|
+
};
|
|
933
|
+
}
|
|
934
|
+
async function readRequestBody(req) {
|
|
935
|
+
const chunks = [];
|
|
936
|
+
let total = 0;
|
|
937
|
+
for await (const chunk of req) {
|
|
938
|
+
const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
939
|
+
total += buf.byteLength;
|
|
940
|
+
if (total > MAX_BODY_BYTES) {
|
|
941
|
+
throw new Error(`Request body exceeds ${MAX_BODY_BYTES} bytes.`);
|
|
942
|
+
}
|
|
943
|
+
chunks.push(buf);
|
|
944
|
+
}
|
|
945
|
+
return Buffer.concat(chunks);
|
|
946
|
+
}
|
|
947
|
+
function shouldRedactPath(pathname) {
|
|
948
|
+
const clean = pathname.split("?")[0] ?? pathname;
|
|
949
|
+
return clean.endsWith("/messages") || clean.endsWith("/chat/completions") || clean.endsWith("/responses");
|
|
950
|
+
}
|
|
951
|
+
async function startMaskeraProxy(options = {}) {
|
|
952
|
+
const host = options.host ?? "127.0.0.1";
|
|
953
|
+
const requestedPort = options.port ?? 8787;
|
|
954
|
+
const engine = options.engine ?? createMaskeraEngine({ defaultMode: options.defaultMode });
|
|
955
|
+
const vault = options.vault ?? new SessionVault();
|
|
956
|
+
const restoreResponses = options.restoreResponses !== false;
|
|
957
|
+
const anthropicUpstream = options.anthropicUpstream ?? DEFAULT_ANTHROPIC_UPSTREAM;
|
|
958
|
+
const openaiUpstream = options.openaiUpstream ?? DEFAULT_OPENAI_UPSTREAM;
|
|
959
|
+
const log = options.onLog ?? (() => {
|
|
960
|
+
});
|
|
961
|
+
let totalRequests = 0;
|
|
962
|
+
let totalRedactions = 0;
|
|
963
|
+
async function handleRequest(req, res) {
|
|
964
|
+
const startedAt = Date.now();
|
|
965
|
+
const method = req.method ?? "GET";
|
|
966
|
+
const urlPath = req.url ?? "/";
|
|
967
|
+
if (method === "GET" && (urlPath === "/healthz" || urlPath === "/_maskera/status")) {
|
|
968
|
+
const payload = {
|
|
969
|
+
status: "ok",
|
|
970
|
+
engine: engine.status(),
|
|
971
|
+
requests_proxied: totalRequests,
|
|
972
|
+
total_redactions: totalRedactions,
|
|
973
|
+
sessions: vault.list()
|
|
974
|
+
};
|
|
975
|
+
res.writeHead(200, { "content-type": "application/json; charset=utf-8" });
|
|
976
|
+
res.end(JSON.stringify(payload, null, 2));
|
|
977
|
+
return;
|
|
978
|
+
}
|
|
979
|
+
const { baseUrl, forwardPath } = resolveUpstreamTarget(urlPath, req.headers, {
|
|
980
|
+
explicitUpstream: options.upstream,
|
|
981
|
+
anthropicUpstream,
|
|
982
|
+
openaiUpstream
|
|
983
|
+
});
|
|
984
|
+
const upstreamUrl = `${baseUrl}${forwardPath}`;
|
|
985
|
+
const rawBody = method === "GET" || method === "HEAD" ? void 0 : await readRequestBody(req);
|
|
986
|
+
const sessionHeader = req.headers["x-maskera-session"];
|
|
987
|
+
const sessionId = typeof sessionHeader === "string" && sessionHeader.trim() ? sessionHeader.trim() : "proxy";
|
|
988
|
+
const stats = { redactions: 0, counts: {} };
|
|
989
|
+
let outgoingBody = rawBody;
|
|
990
|
+
const contentType = String(req.headers["content-type"] ?? "");
|
|
991
|
+
if (rawBody && rawBody.byteLength > 0 && shouldRedactPath(forwardPath) && contentType.includes("application/json")) {
|
|
992
|
+
let parsed;
|
|
993
|
+
try {
|
|
994
|
+
parsed = JSON.parse(rawBody.toString("utf8"));
|
|
995
|
+
} catch {
|
|
996
|
+
res.writeHead(400, { "content-type": "application/json; charset=utf-8" });
|
|
997
|
+
res.end(JSON.stringify({ error: { message: "Invalid JSON request body." } }));
|
|
998
|
+
return;
|
|
999
|
+
}
|
|
1000
|
+
if (isPlainObject(parsed)) {
|
|
1001
|
+
const redactedObj = await redactLlmRequestBody(parsed, async (text) => {
|
|
1002
|
+
if (!text.trim()) return text;
|
|
1003
|
+
const { result } = await engine.redact(text, {
|
|
1004
|
+
profile: options.profile,
|
|
1005
|
+
customTerms: options.customTerms
|
|
1006
|
+
});
|
|
1007
|
+
const applied = vault.apply(text, result, sessionId);
|
|
1008
|
+
stats.redactions += applied.totalRedactions;
|
|
1009
|
+
mergeCounts(stats.counts, applied.counts);
|
|
1010
|
+
return applied.redacted;
|
|
1011
|
+
});
|
|
1012
|
+
outgoingBody = Buffer.from(JSON.stringify(redactedObj), "utf8");
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
totalRequests += 1;
|
|
1016
|
+
totalRedactions += stats.redactions;
|
|
1017
|
+
const forwardHeaders = new Headers();
|
|
1018
|
+
for (const [k, v] of Object.entries(req.headers)) {
|
|
1019
|
+
if (v === void 0) continue;
|
|
1020
|
+
const lower = k.toLowerCase();
|
|
1021
|
+
if (HOP_BY_HOP_REQUEST_HEADERS.has(lower) || lower === "x-maskera-session") continue;
|
|
1022
|
+
if (Array.isArray(v)) {
|
|
1023
|
+
for (const item of v) forwardHeaders.append(k, item);
|
|
1024
|
+
} else {
|
|
1025
|
+
forwardHeaders.set(k, v);
|
|
1026
|
+
}
|
|
1027
|
+
}
|
|
1028
|
+
forwardHeaders.set("accept-encoding", "identity");
|
|
1029
|
+
const upstreamRes = await fetch(upstreamUrl, {
|
|
1030
|
+
method,
|
|
1031
|
+
headers: forwardHeaders,
|
|
1032
|
+
body: outgoingBody ? new Uint8Array(outgoingBody) : void 0
|
|
1033
|
+
});
|
|
1034
|
+
const outHeaders = {};
|
|
1035
|
+
upstreamRes.headers.forEach((value, key) => {
|
|
1036
|
+
if (!HOP_BY_HOP_RESPONSE_HEADERS.has(key.toLowerCase())) {
|
|
1037
|
+
outHeaders[key] = value;
|
|
1038
|
+
}
|
|
1039
|
+
});
|
|
1040
|
+
outHeaders["x-maskera-redacted"] = String(stats.redactions);
|
|
1041
|
+
const sessionMap = restoreResponses ? vault.getMap(sessionId) : {};
|
|
1042
|
+
const hasMap = Object.keys(sessionMap).length > 0;
|
|
1043
|
+
const resContentType = upstreamRes.headers.get("content-type") ?? "";
|
|
1044
|
+
if (hasMap && resContentType.includes("text/event-stream") && upstreamRes.body) {
|
|
1045
|
+
res.writeHead(upstreamRes.status, outHeaders);
|
|
1046
|
+
const sse = createSseRestorer(sessionMap);
|
|
1047
|
+
const decoder = new TextDecoder();
|
|
1048
|
+
const reader = upstreamRes.body.getReader();
|
|
1049
|
+
try {
|
|
1050
|
+
for (; ; ) {
|
|
1051
|
+
const { done, value } = await reader.read();
|
|
1052
|
+
if (done) break;
|
|
1053
|
+
const chunkText = decoder.decode(value, { stream: true });
|
|
1054
|
+
const transformed = sse.push(chunkText);
|
|
1055
|
+
if (transformed) res.write(transformed);
|
|
1056
|
+
}
|
|
1057
|
+
const finalText = decoder.decode();
|
|
1058
|
+
const tail = (finalText ? sse.push(finalText) : "") + sse.flush();
|
|
1059
|
+
if (tail) res.write(tail);
|
|
1060
|
+
} finally {
|
|
1061
|
+
reader.releaseLock();
|
|
1062
|
+
res.end();
|
|
1063
|
+
}
|
|
1064
|
+
log(
|
|
1065
|
+
`[maskera-proxy] ${method} ${forwardPath} ${upstreamRes.status} sse redacted=${stats.redactions} ${Date.now() - startedAt}ms`
|
|
1066
|
+
);
|
|
1067
|
+
return;
|
|
1068
|
+
}
|
|
1069
|
+
const resBuf = Buffer.from(await upstreamRes.arrayBuffer());
|
|
1070
|
+
if (hasMap && resContentType.includes("application/json")) {
|
|
1071
|
+
try {
|
|
1072
|
+
const parsed = JSON.parse(resBuf.toString("utf8"));
|
|
1073
|
+
const restored = restoreLlmResponseBody(parsed, sessionMap);
|
|
1074
|
+
const restoredBuf = Buffer.from(JSON.stringify(restored), "utf8");
|
|
1075
|
+
res.writeHead(upstreamRes.status, outHeaders);
|
|
1076
|
+
res.end(restoredBuf);
|
|
1077
|
+
log(
|
|
1078
|
+
`[maskera-proxy] ${method} ${forwardPath} ${upstreamRes.status} json redacted=${stats.redactions} ${Date.now() - startedAt}ms`
|
|
1079
|
+
);
|
|
1080
|
+
return;
|
|
1081
|
+
} catch {
|
|
1082
|
+
}
|
|
1083
|
+
}
|
|
1084
|
+
res.writeHead(upstreamRes.status, outHeaders);
|
|
1085
|
+
res.end(resBuf);
|
|
1086
|
+
log(
|
|
1087
|
+
`[maskera-proxy] ${method} ${forwardPath} ${upstreamRes.status} redacted=${stats.redactions} ${Date.now() - startedAt}ms`
|
|
1088
|
+
);
|
|
1089
|
+
}
|
|
1090
|
+
const server = createServer((req, res) => {
|
|
1091
|
+
void handleRequest(req, res).catch((err) => {
|
|
1092
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
1093
|
+
log(`[maskera-proxy] error: ${message}`);
|
|
1094
|
+
if (!res.headersSent) {
|
|
1095
|
+
res.writeHead(502, { "content-type": "application/json; charset=utf-8" });
|
|
1096
|
+
res.end(JSON.stringify({ error: { message: `maskera-proxy error: ${message}` } }));
|
|
1097
|
+
} else {
|
|
1098
|
+
res.end();
|
|
1099
|
+
}
|
|
1100
|
+
});
|
|
1101
|
+
});
|
|
1102
|
+
await new Promise((resolveListen, rejectListen) => {
|
|
1103
|
+
server.once("error", rejectListen);
|
|
1104
|
+
server.listen(requestedPort, host, () => {
|
|
1105
|
+
server.off("error", rejectListen);
|
|
1106
|
+
resolveListen();
|
|
1107
|
+
});
|
|
1108
|
+
});
|
|
1109
|
+
const addr = server.address();
|
|
1110
|
+
const actualPort = typeof addr === "object" && addr ? addr.port : requestedPort;
|
|
1111
|
+
return {
|
|
1112
|
+
host,
|
|
1113
|
+
port: actualPort,
|
|
1114
|
+
url: `http://${host}:${actualPort}`,
|
|
1115
|
+
server,
|
|
1116
|
+
vault,
|
|
1117
|
+
close: () => new Promise((resolveClose, rejectClose) => {
|
|
1118
|
+
server.close((err) => err ? rejectClose(err) : resolveClose());
|
|
1119
|
+
})
|
|
1120
|
+
};
|
|
1121
|
+
}
|
|
1122
|
+
|
|
1123
|
+
// src/server.ts
|
|
1124
|
+
var SERVER_NAME = "maskera-mcp";
|
|
1125
|
+
var SERVER_VERSION = "0.1.0";
|
|
1126
|
+
var SUPPORTED_PROTOCOLS = ["2025-03-26", "2024-11-05"];
|
|
1127
|
+
var TOOLS = [
|
|
1128
|
+
{
|
|
1129
|
+
name: "maskera_redact",
|
|
1130
|
+
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.",
|
|
1131
|
+
inputSchema: {
|
|
1132
|
+
type: "object",
|
|
1133
|
+
properties: {
|
|
1134
|
+
text: { type: "string", description: "Text to redact locally." },
|
|
1135
|
+
session_id: {
|
|
1136
|
+
type: "string",
|
|
1137
|
+
description: "Optional session ID to reuse consistent placeholder numbering across calls."
|
|
1138
|
+
},
|
|
1139
|
+
mode: {
|
|
1140
|
+
type: "string",
|
|
1141
|
+
enum: ["auto", "rules"],
|
|
1142
|
+
description: '"auto" (default) runs hybrid Swedish NER + rules; "rules" runs fast deterministic rules only.'
|
|
1143
|
+
},
|
|
1144
|
+
profile: {
|
|
1145
|
+
type: "string",
|
|
1146
|
+
enum: ["general", "clinical"],
|
|
1147
|
+
description: 'Optional built-in precision profile (default "general").'
|
|
1148
|
+
},
|
|
1149
|
+
custom_terms: {
|
|
1150
|
+
type: "array",
|
|
1151
|
+
items: { type: "string" },
|
|
1152
|
+
description: "Optional extra protected words (client names, case IDs, codenames)."
|
|
1153
|
+
},
|
|
1154
|
+
include_map: {
|
|
1155
|
+
type: "boolean",
|
|
1156
|
+
description: "Set true only when the caller explicitly needs the raw placeholder->value map returned. Default false (recommended so raw PII stays local)."
|
|
1157
|
+
}
|
|
1158
|
+
},
|
|
1159
|
+
required: ["text"]
|
|
1160
|
+
}
|
|
1161
|
+
},
|
|
1162
|
+
{
|
|
1163
|
+
name: "maskera_restore",
|
|
1164
|
+
description: "Restore Maskera placeholders (e.g. [NAMN_1], [PERSONNUMMER_1]) in text using a locally stored session_id or an explicit map.",
|
|
1165
|
+
inputSchema: {
|
|
1166
|
+
type: "object",
|
|
1167
|
+
properties: {
|
|
1168
|
+
text: { type: "string", description: "Text containing Maskera placeholders." },
|
|
1169
|
+
session_id: {
|
|
1170
|
+
type: "string",
|
|
1171
|
+
description: "Session ID returned by maskera_redact or maskera_read_file."
|
|
1172
|
+
},
|
|
1173
|
+
map: {
|
|
1174
|
+
type: "object",
|
|
1175
|
+
additionalProperties: { type: "string" },
|
|
1176
|
+
description: "Optional explicit placeholder -> original value map."
|
|
1177
|
+
}
|
|
1178
|
+
},
|
|
1179
|
+
required: ["text"]
|
|
1180
|
+
}
|
|
1181
|
+
},
|
|
1182
|
+
{
|
|
1183
|
+
name: "maskera_read_file",
|
|
1184
|
+
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.",
|
|
1185
|
+
inputSchema: {
|
|
1186
|
+
type: "object",
|
|
1187
|
+
properties: {
|
|
1188
|
+
path: {
|
|
1189
|
+
type: "string",
|
|
1190
|
+
description: "Path to a UTF-8 file inside the allowed workspace roots."
|
|
1191
|
+
},
|
|
1192
|
+
session_id: {
|
|
1193
|
+
type: "string",
|
|
1194
|
+
description: "Optional session ID to share placeholder numbering across multiple files."
|
|
1195
|
+
},
|
|
1196
|
+
mode: {
|
|
1197
|
+
type: "string",
|
|
1198
|
+
enum: ["auto", "rules"],
|
|
1199
|
+
description: '"auto" (default) runs hybrid NER + rules; "rules" runs rules only.'
|
|
1200
|
+
},
|
|
1201
|
+
profile: {
|
|
1202
|
+
type: "string",
|
|
1203
|
+
enum: ["general", "clinical"],
|
|
1204
|
+
description: 'Optional built-in precision profile (default "general").'
|
|
1205
|
+
},
|
|
1206
|
+
custom_terms: {
|
|
1207
|
+
type: "array",
|
|
1208
|
+
items: { type: "string" },
|
|
1209
|
+
description: "Optional extra protected words (client names, project codenames)."
|
|
1210
|
+
}
|
|
1211
|
+
},
|
|
1212
|
+
required: ["path"]
|
|
1213
|
+
}
|
|
1214
|
+
},
|
|
1215
|
+
{
|
|
1216
|
+
name: "maskera_write_file",
|
|
1217
|
+
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.",
|
|
1218
|
+
inputSchema: {
|
|
1219
|
+
type: "object",
|
|
1220
|
+
properties: {
|
|
1221
|
+
path: {
|
|
1222
|
+
type: "string",
|
|
1223
|
+
description: "Destination path inside the allowed workspace roots."
|
|
1224
|
+
},
|
|
1225
|
+
text: {
|
|
1226
|
+
type: "string",
|
|
1227
|
+
description: "Draft text containing Maskera placeholders to restore before writing."
|
|
1228
|
+
},
|
|
1229
|
+
session_id: {
|
|
1230
|
+
type: "string",
|
|
1231
|
+
description: "Session ID containing the local restore map."
|
|
1232
|
+
},
|
|
1233
|
+
overwrite: {
|
|
1234
|
+
type: "boolean",
|
|
1235
|
+
description: "Allow overwriting an existing file. Default false."
|
|
1236
|
+
}
|
|
1237
|
+
},
|
|
1238
|
+
required: ["path", "text", "session_id"]
|
|
1239
|
+
}
|
|
1240
|
+
},
|
|
1241
|
+
{
|
|
1242
|
+
name: "maskera_list_sessions",
|
|
1243
|
+
description: "List active local redaction sessions and entity counts (never returns raw PII values).",
|
|
1244
|
+
inputSchema: { type: "object", properties: {} }
|
|
1245
|
+
},
|
|
1246
|
+
{
|
|
1247
|
+
name: "maskera_clear_session",
|
|
1248
|
+
description: "Erase a session's local in-memory restore map immediately.",
|
|
1249
|
+
inputSchema: {
|
|
1250
|
+
type: "object",
|
|
1251
|
+
properties: {
|
|
1252
|
+
session_id: { type: "string", description: "Session ID to erase." }
|
|
1253
|
+
},
|
|
1254
|
+
required: ["session_id"]
|
|
1255
|
+
}
|
|
1256
|
+
},
|
|
1257
|
+
{
|
|
1258
|
+
name: "maskera_status",
|
|
1259
|
+
description: "Report local Maskera MCP server status: model pin, readiness, active sessions, and allowed file roots.",
|
|
1260
|
+
inputSchema: { type: "object", properties: {} }
|
|
1261
|
+
}
|
|
1262
|
+
];
|
|
1263
|
+
function asObject(value) {
|
|
1264
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
1265
|
+
}
|
|
1266
|
+
function asMode(value) {
|
|
1267
|
+
if (value === void 0) return void 0;
|
|
1268
|
+
if (value === "auto" || value === "rules") return value;
|
|
1269
|
+
throw new Error('Invalid mode: expected "auto" or "rules".');
|
|
1270
|
+
}
|
|
1271
|
+
function asProfile(value) {
|
|
1272
|
+
if (value === void 0) return void 0;
|
|
1273
|
+
if (value === "general" || value === "clinical") return value;
|
|
1274
|
+
throw new Error('Invalid profile: expected "general" or "clinical".');
|
|
1275
|
+
}
|
|
1276
|
+
function asStringArray(value) {
|
|
1277
|
+
if (value === void 0) return void 0;
|
|
1278
|
+
if (!Array.isArray(value) || value.some((v) => typeof v !== "string")) {
|
|
1279
|
+
throw new Error("custom_terms must be an array of strings.");
|
|
1280
|
+
}
|
|
1281
|
+
return value;
|
|
1282
|
+
}
|
|
1283
|
+
function toolOk(payload) {
|
|
1284
|
+
return {
|
|
1285
|
+
content: [{ type: "text", text: JSON.stringify(payload, null, 2) }],
|
|
1286
|
+
structuredContent: payload
|
|
1287
|
+
};
|
|
1288
|
+
}
|
|
1289
|
+
function toolError(message) {
|
|
1290
|
+
return {
|
|
1291
|
+
isError: true,
|
|
1292
|
+
content: [{ type: "text", text: message }]
|
|
1293
|
+
};
|
|
1294
|
+
}
|
|
1295
|
+
function createMaskeraMcpServer(options = {}) {
|
|
1296
|
+
const engine = options.engine ?? createMaskeraEngine();
|
|
1297
|
+
const vault = options.vault ?? new SessionVault();
|
|
1298
|
+
const files = options.files ?? createFileGuard(options.allowedRoots);
|
|
1299
|
+
async function callTool(name, rawArgs) {
|
|
1300
|
+
const args = asObject(rawArgs);
|
|
1301
|
+
try {
|
|
1302
|
+
if (name === "maskera_redact") {
|
|
1303
|
+
if (typeof args.text !== "string") return toolError("Missing required string: text");
|
|
1304
|
+
const { result, modeUsed } = await engine.redact(args.text, {
|
|
1305
|
+
mode: asMode(args.mode),
|
|
1306
|
+
profile: asProfile(args.profile),
|
|
1307
|
+
customTerms: asStringArray(args.custom_terms)
|
|
1308
|
+
});
|
|
1309
|
+
const applied = vault.apply(
|
|
1310
|
+
args.text,
|
|
1311
|
+
result,
|
|
1312
|
+
typeof args.session_id === "string" ? args.session_id : void 0
|
|
1313
|
+
);
|
|
1314
|
+
const payload = {
|
|
1315
|
+
redacted: applied.redacted,
|
|
1316
|
+
session_id: applied.sessionId,
|
|
1317
|
+
counts: applied.counts,
|
|
1318
|
+
total_redactions: applied.totalRedactions,
|
|
1319
|
+
mode: modeUsed
|
|
1320
|
+
};
|
|
1321
|
+
if (args.include_map === true) payload.map = applied.map;
|
|
1322
|
+
return toolOk(payload);
|
|
1323
|
+
}
|
|
1324
|
+
if (name === "maskera_restore") {
|
|
1325
|
+
if (typeof args.text !== "string") return toolError("Missing required string: text");
|
|
1326
|
+
const explicitMap = args.map && typeof args.map === "object" && !Array.isArray(args.map) ? Object.fromEntries(
|
|
1327
|
+
Object.entries(args.map).filter(
|
|
1328
|
+
(entry) => typeof entry[1] === "string"
|
|
1329
|
+
)
|
|
1330
|
+
) : void 0;
|
|
1331
|
+
const out = vault.restore(args.text, {
|
|
1332
|
+
sessionId: typeof args.session_id === "string" ? args.session_id : void 0,
|
|
1333
|
+
map: explicitMap
|
|
1334
|
+
});
|
|
1335
|
+
return toolOk({
|
|
1336
|
+
restored: out.restored,
|
|
1337
|
+
session_id: out.sessionId,
|
|
1338
|
+
known_placeholders: out.knownPlaceholders
|
|
1339
|
+
});
|
|
1340
|
+
}
|
|
1341
|
+
if (name === "maskera_read_file") {
|
|
1342
|
+
if (typeof args.path !== "string") return toolError("Missing required string: path");
|
|
1343
|
+
const file = await files.readText(args.path);
|
|
1344
|
+
const { result, modeUsed } = await engine.redact(file.content, {
|
|
1345
|
+
mode: asMode(args.mode),
|
|
1346
|
+
profile: asProfile(args.profile),
|
|
1347
|
+
customTerms: asStringArray(args.custom_terms)
|
|
1348
|
+
});
|
|
1349
|
+
const applied = vault.apply(
|
|
1350
|
+
file.content,
|
|
1351
|
+
result,
|
|
1352
|
+
typeof args.session_id === "string" ? args.session_id : void 0
|
|
1353
|
+
);
|
|
1354
|
+
return toolOk({
|
|
1355
|
+
path: file.resolvedPath,
|
|
1356
|
+
bytes: file.bytes,
|
|
1357
|
+
redacted: applied.redacted,
|
|
1358
|
+
session_id: applied.sessionId,
|
|
1359
|
+
counts: applied.counts,
|
|
1360
|
+
total_redactions: applied.totalRedactions,
|
|
1361
|
+
mode: modeUsed
|
|
1362
|
+
});
|
|
1363
|
+
}
|
|
1364
|
+
if (name === "maskera_write_file") {
|
|
1365
|
+
if (typeof args.path !== "string") return toolError("Missing required string: path");
|
|
1366
|
+
if (typeof args.text !== "string") return toolError("Missing required string: text");
|
|
1367
|
+
if (typeof args.session_id !== "string") {
|
|
1368
|
+
return toolError("Missing required string: session_id");
|
|
1369
|
+
}
|
|
1370
|
+
const { restored, knownPlaceholders } = vault.restore(args.text, {
|
|
1371
|
+
sessionId: args.session_id
|
|
1372
|
+
});
|
|
1373
|
+
const written = await files.writeText(args.path, restored, {
|
|
1374
|
+
overwrite: args.overwrite === true
|
|
1375
|
+
});
|
|
1376
|
+
return toolOk({
|
|
1377
|
+
path: written.resolvedPath,
|
|
1378
|
+
bytes: written.bytes,
|
|
1379
|
+
session_id: args.session_id,
|
|
1380
|
+
known_placeholders: knownPlaceholders
|
|
1381
|
+
});
|
|
1382
|
+
}
|
|
1383
|
+
if (name === "maskera_list_sessions") {
|
|
1384
|
+
return toolOk({ sessions: vault.list() });
|
|
1385
|
+
}
|
|
1386
|
+
if (name === "maskera_clear_session") {
|
|
1387
|
+
if (typeof args.session_id !== "string") {
|
|
1388
|
+
return toolError("Missing required string: session_id");
|
|
1389
|
+
}
|
|
1390
|
+
return toolOk({
|
|
1391
|
+
session_id: args.session_id,
|
|
1392
|
+
cleared: vault.clear(args.session_id)
|
|
1393
|
+
});
|
|
1394
|
+
}
|
|
1395
|
+
if (name === "maskera_status") {
|
|
1396
|
+
return toolOk({
|
|
1397
|
+
server: SERVER_NAME,
|
|
1398
|
+
version: SERVER_VERSION,
|
|
1399
|
+
engine: engine.status(),
|
|
1400
|
+
active_sessions: vault.size,
|
|
1401
|
+
allowed_roots: files.allowedRoots
|
|
1402
|
+
});
|
|
1403
|
+
}
|
|
1404
|
+
return toolError(`Unknown tool "${name}".`);
|
|
1405
|
+
} catch (err) {
|
|
1406
|
+
return toolError(err instanceof Error ? err.message : String(err));
|
|
1407
|
+
}
|
|
1408
|
+
}
|
|
1409
|
+
return {
|
|
1410
|
+
vault,
|
|
1411
|
+
async handleMessage(raw) {
|
|
1412
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
|
|
1413
|
+
return {
|
|
1414
|
+
jsonrpc: "2.0",
|
|
1415
|
+
id: null,
|
|
1416
|
+
error: { code: -32600, message: "Invalid Request" }
|
|
1417
|
+
};
|
|
1418
|
+
}
|
|
1419
|
+
const req = raw;
|
|
1420
|
+
const id = typeof req.id === "string" || typeof req.id === "number" || req.id === null ? req.id : void 0;
|
|
1421
|
+
if (req.jsonrpc !== "2.0" || typeof req.method !== "string") {
|
|
1422
|
+
if (id === void 0) return null;
|
|
1423
|
+
return {
|
|
1424
|
+
jsonrpc: "2.0",
|
|
1425
|
+
id,
|
|
1426
|
+
error: { code: -32600, message: "Invalid Request" }
|
|
1427
|
+
};
|
|
1428
|
+
}
|
|
1429
|
+
if (id === void 0) {
|
|
1430
|
+
return null;
|
|
1431
|
+
}
|
|
1432
|
+
if (req.method === "initialize") {
|
|
1433
|
+
const params = asObject(req.params);
|
|
1434
|
+
const requested = typeof params.protocolVersion === "string" ? params.protocolVersion : void 0;
|
|
1435
|
+
const protocolVersion = requested && SUPPORTED_PROTOCOLS.includes(requested) ? requested : SUPPORTED_PROTOCOLS[0];
|
|
1436
|
+
return {
|
|
1437
|
+
jsonrpc: "2.0",
|
|
1438
|
+
id,
|
|
1439
|
+
result: {
|
|
1440
|
+
protocolVersion,
|
|
1441
|
+
capabilities: { tools: { listChanged: false } },
|
|
1442
|
+
serverInfo: { name: SERVER_NAME, version: SERVER_VERSION },
|
|
1443
|
+
instructions: "Use maskera_read_file to read sensitive local files already redacted, maskera_redact for raw snippets, and maskera_write_file to restore placeholders directly to disk without exposing real PII to the model."
|
|
1444
|
+
}
|
|
1445
|
+
};
|
|
1446
|
+
}
|
|
1447
|
+
if (req.method === "ping") {
|
|
1448
|
+
return { jsonrpc: "2.0", id, result: {} };
|
|
1449
|
+
}
|
|
1450
|
+
if (req.method === "tools/list") {
|
|
1451
|
+
return { jsonrpc: "2.0", id, result: { tools: TOOLS } };
|
|
1452
|
+
}
|
|
1453
|
+
if (req.method === "tools/call") {
|
|
1454
|
+
const params = asObject(req.params);
|
|
1455
|
+
if (typeof params.name !== "string") {
|
|
1456
|
+
return {
|
|
1457
|
+
jsonrpc: "2.0",
|
|
1458
|
+
id,
|
|
1459
|
+
error: { code: -32602, message: "Invalid params: missing tool name" }
|
|
1460
|
+
};
|
|
1461
|
+
}
|
|
1462
|
+
const result = await callTool(params.name, params.arguments);
|
|
1463
|
+
return { jsonrpc: "2.0", id, result };
|
|
1464
|
+
}
|
|
1465
|
+
return {
|
|
1466
|
+
jsonrpc: "2.0",
|
|
1467
|
+
id,
|
|
1468
|
+
error: { code: -32601, message: `Method not found: ${req.method}` }
|
|
1469
|
+
};
|
|
1470
|
+
}
|
|
1471
|
+
};
|
|
1472
|
+
}
|
|
1473
|
+
|
|
1474
|
+
export { SERVER_NAME, SERVER_VERSION, SessionVault, StreamingRestorer, buildCustomTermsDetector, createFileGuard, createMaskeraEngine, createMaskeraMcpServer, createSseRestorer, extractGuardText, redactLlmRequestBody, restoreLlmResponseBody, runGuard, startMaskeraProxy };
|
|
1475
|
+
//# sourceMappingURL=index.js.map
|
|
1476
|
+
//# sourceMappingURL=index.js.map
|