@maskera/mcp 0.4.6 → 0.4.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +906 -655
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +43 -3
- package/dist/index.js +894 -576
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { randomUUID, createHash } from 'crypto';
|
|
2
|
-
import { constants } from 'fs';
|
|
2
|
+
import { existsSync, constants } from 'fs';
|
|
3
3
|
import { readFile, mkdir, realpath, writeFile, stat, access, appendFile, unlink, readdir, lstat, readlink } from 'fs/promises';
|
|
4
|
-
import { dirname, resolve,
|
|
4
|
+
import { join, dirname, resolve, isAbsolute, relative, sep, delimiter, extname, posix } from 'path';
|
|
5
5
|
import { createRequire } from 'module';
|
|
6
6
|
import { MASKERA_SV_NER_MODEL, MASKERA_SV_NER_REVISION, redactFromDetections, hybridDefaultDetectors, canonicalize, runDetectors, clinicalPrecisionFilter, redact, redactWithNer, restore, createNerRecognizer } from 'maskera';
|
|
7
7
|
import { spawn, spawnSync } from 'child_process';
|
|
@@ -17,6 +17,22 @@ function normalizeOwner(owner) {
|
|
|
17
17
|
const trimmed = owner?.trim();
|
|
18
18
|
return trimmed || DEFAULT_OWNER;
|
|
19
19
|
}
|
|
20
|
+
function toSummary(record) {
|
|
21
|
+
const { state } = record;
|
|
22
|
+
const decidedAt = state.status === "pending" ? null : state.decidedAt;
|
|
23
|
+
const base = {
|
|
24
|
+
id: record.id,
|
|
25
|
+
tool: record.tool,
|
|
26
|
+
reason: record.reason,
|
|
27
|
+
sessionId: record.sessionId,
|
|
28
|
+
placeholderCount: record.placeholderCount,
|
|
29
|
+
status: state.status,
|
|
30
|
+
createdAt: record.createdAt,
|
|
31
|
+
expiresAt: record.expiresAt,
|
|
32
|
+
decidedAt
|
|
33
|
+
};
|
|
34
|
+
return state.status === "failed" ? { ...base, error: state.error } : base;
|
|
35
|
+
}
|
|
20
36
|
var ApprovalBroker = class {
|
|
21
37
|
constructor(ttlMs = DEFAULT_TTL_MS) {
|
|
22
38
|
this.records = /* @__PURE__ */ new Map();
|
|
@@ -26,9 +42,9 @@ var ApprovalBroker = class {
|
|
|
26
42
|
expireStale(now = Date.now()) {
|
|
27
43
|
let changed = false;
|
|
28
44
|
for (const record of this.records.values()) {
|
|
29
|
-
if (record.
|
|
30
|
-
record.
|
|
31
|
-
record.
|
|
45
|
+
if ((record.state.status === "pending" || record.state.status === "approved") && now >= record.state.expiresAtMs) {
|
|
46
|
+
const decidedAt = record.state.status === "approved" ? record.state.decidedAt : null;
|
|
47
|
+
record.state = { status: "expired", decidedAt };
|
|
32
48
|
changed = true;
|
|
33
49
|
}
|
|
34
50
|
}
|
|
@@ -57,70 +73,93 @@ var ApprovalBroker = class {
|
|
|
57
73
|
}
|
|
58
74
|
const now = Date.now();
|
|
59
75
|
const id = `apr_${randomUUID().slice(0, 12)}`;
|
|
60
|
-
const
|
|
76
|
+
const expiresAtMs = now + this.ttlMs;
|
|
77
|
+
const record = {
|
|
61
78
|
id,
|
|
79
|
+
owner: normalizeOwner(input.owner),
|
|
62
80
|
tool: input.tool,
|
|
63
81
|
reason: input.reason,
|
|
64
82
|
sessionId: input.sessionId ?? null,
|
|
65
83
|
placeholderCount: input.placeholderCount,
|
|
66
|
-
status: "pending",
|
|
67
84
|
createdAt: new Date(now).toISOString(),
|
|
68
|
-
expiresAt: new Date(
|
|
69
|
-
|
|
85
|
+
expiresAt: new Date(expiresAtMs).toISOString(),
|
|
86
|
+
state: {
|
|
87
|
+
status: "pending",
|
|
88
|
+
expiresAtMs,
|
|
89
|
+
execute: input.execute
|
|
90
|
+
}
|
|
70
91
|
};
|
|
71
|
-
this.records.set(id,
|
|
72
|
-
owner: normalizeOwner(input.owner),
|
|
73
|
-
summary,
|
|
74
|
-
expiresAtMs: now + this.ttlMs,
|
|
75
|
-
execute: input.execute
|
|
76
|
-
});
|
|
92
|
+
this.records.set(id, record);
|
|
77
93
|
this.notify();
|
|
78
|
-
return
|
|
94
|
+
return toSummary(record);
|
|
79
95
|
}
|
|
80
96
|
list() {
|
|
81
97
|
this.expireStale();
|
|
82
|
-
return [...this.records.values()].map(
|
|
98
|
+
return [...this.records.values()].map(toSummary).reverse();
|
|
83
99
|
}
|
|
84
100
|
decide(id, decision) {
|
|
85
101
|
this.expireStale();
|
|
86
102
|
const record = this.records.get(id.trim());
|
|
87
103
|
if (!record) return null;
|
|
88
|
-
if (record.
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
104
|
+
if (record.state.status !== "pending") return toSummary(record);
|
|
105
|
+
const decidedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
106
|
+
if (decision === "approve") {
|
|
107
|
+
record.state = {
|
|
108
|
+
status: "approved",
|
|
109
|
+
expiresAtMs: record.state.expiresAtMs,
|
|
110
|
+
decidedAt,
|
|
111
|
+
execute: record.state.execute
|
|
112
|
+
};
|
|
113
|
+
} else {
|
|
114
|
+
record.state = { status: "declined", decidedAt };
|
|
93
115
|
}
|
|
94
116
|
this.notify();
|
|
95
|
-
return
|
|
117
|
+
return toSummary(record);
|
|
96
118
|
}
|
|
97
119
|
async resume(id, owner) {
|
|
98
120
|
this.expireStale();
|
|
99
|
-
const
|
|
121
|
+
const key = id.trim();
|
|
122
|
+
const record = this.records.get(key);
|
|
100
123
|
if (!record) return { status: "not_found" };
|
|
101
124
|
if (owner !== void 0 && record.owner !== normalizeOwner(owner)) {
|
|
102
125
|
return { status: "not_found" };
|
|
103
126
|
}
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
127
|
+
switch (record.state.status) {
|
|
128
|
+
case "pending":
|
|
129
|
+
case "executing":
|
|
130
|
+
case "declined":
|
|
131
|
+
case "expired":
|
|
132
|
+
return { status: record.state.status, summary: toSummary(record) };
|
|
133
|
+
case "completed":
|
|
134
|
+
return { status: "already_completed", summary: toSummary(record) };
|
|
135
|
+
case "failed":
|
|
136
|
+
return { status: "failed", error: record.state.error, summary: toSummary(record) };
|
|
137
|
+
case "approved": {
|
|
138
|
+
const { decidedAt, execute } = record.state;
|
|
139
|
+
const inFlight = (async () => {
|
|
140
|
+
try {
|
|
141
|
+
const result = await execute();
|
|
142
|
+
record.state = { status: "completed", decidedAt };
|
|
143
|
+
if (this.records.get(key) === record) this.notify();
|
|
144
|
+
return { status: "completed", result, summary: toSummary(record) };
|
|
145
|
+
} catch (err) {
|
|
146
|
+
const error = err instanceof Error ? err.message : String(err);
|
|
147
|
+
record.state = { status: "failed", decidedAt, error };
|
|
148
|
+
if (this.records.get(key) === record) this.notify();
|
|
149
|
+
return { status: "failed", error, summary: toSummary(record) };
|
|
150
|
+
}
|
|
151
|
+
})();
|
|
152
|
+
record.state = { status: "executing", decidedAt, inFlight };
|
|
153
|
+
this.notify();
|
|
154
|
+
return await inFlight;
|
|
155
|
+
}
|
|
110
156
|
}
|
|
111
|
-
const run = record.execute;
|
|
112
|
-
record.execute = null;
|
|
113
|
-
const result = await run();
|
|
114
|
-
record.summary.status = "completed";
|
|
115
|
-
this.notify();
|
|
116
|
-
return { status: "completed", result, summary: { ...record.summary } };
|
|
117
157
|
}
|
|
118
158
|
clearOwner(owner) {
|
|
119
159
|
const resolvedOwner = normalizeOwner(owner);
|
|
120
160
|
let changed = false;
|
|
121
161
|
for (const [id, record] of this.records.entries()) {
|
|
122
162
|
if (record.owner === resolvedOwner) {
|
|
123
|
-
record.execute = null;
|
|
124
163
|
this.records.delete(id);
|
|
125
164
|
changed = true;
|
|
126
165
|
}
|
|
@@ -207,6 +246,7 @@ function normalizeMixedScriptHomoglyphs(text) {
|
|
|
207
246
|
});
|
|
208
247
|
return { text: normalized, changed };
|
|
209
248
|
}
|
|
249
|
+
var COMPOUND_WINDOW_RADIUS = 120;
|
|
210
250
|
async function detectHyphenatedCompoundPrefixes(text, ner, detectors, profile, existing) {
|
|
211
251
|
const candidates = [];
|
|
212
252
|
SWEDISH_HYPHEN_COMPOUND_RE.lastIndex = 0;
|
|
@@ -221,28 +261,47 @@ async function detectHyphenatedCompoundPrefixes(text, ner, detectors, profile, e
|
|
|
221
261
|
}
|
|
222
262
|
}
|
|
223
263
|
if (candidates.length === 0) return [];
|
|
224
|
-
const
|
|
264
|
+
const windows = [];
|
|
225
265
|
for (const c of candidates) {
|
|
226
|
-
|
|
266
|
+
let winStart = Math.max(0, c.prefixStart - COMPOUND_WINDOW_RADIUS);
|
|
267
|
+
while (winStart > 0 && WORD_CHAR.test(text[winStart - 1] ?? "")) winStart--;
|
|
268
|
+
let winEnd = Math.min(text.length, c.hyphenIndex + 1 + COMPOUND_WINDOW_RADIUS);
|
|
269
|
+
while (winEnd < text.length && WORD_CHAR.test(text[winEnd] ?? "")) winEnd++;
|
|
270
|
+
const prev = windows[windows.length - 1];
|
|
271
|
+
if (prev && winStart <= prev.end + 40) {
|
|
272
|
+
prev.end = Math.max(prev.end, winEnd);
|
|
273
|
+
prev.items.push(c);
|
|
274
|
+
} else {
|
|
275
|
+
windows.push({ start: winStart, end: winEnd, items: [c] });
|
|
276
|
+
}
|
|
227
277
|
}
|
|
228
|
-
const probeText = chars.join("");
|
|
229
|
-
const probeRes = await redactWithNer(probeText, {
|
|
230
|
-
recognizer: ner,
|
|
231
|
-
detectors: [...detectors],
|
|
232
|
-
profile
|
|
233
|
-
});
|
|
234
278
|
const extra = [];
|
|
235
|
-
for (const
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
279
|
+
for (const win of windows) {
|
|
280
|
+
const slice = text.slice(win.start, win.end);
|
|
281
|
+
const chars = slice.split("");
|
|
282
|
+
for (const c of win.items) {
|
|
283
|
+
chars[c.hyphenIndex - win.start] = " ";
|
|
284
|
+
}
|
|
285
|
+
const probeText = chars.join("");
|
|
286
|
+
const probeRes = await redactWithNer(probeText, {
|
|
287
|
+
recognizer: ner,
|
|
288
|
+
detectors: [...detectors],
|
|
289
|
+
profile
|
|
290
|
+
});
|
|
291
|
+
for (const r of probeRes.redactions) {
|
|
292
|
+
if (!COMPOUND_NER_LABELS.has(r.label)) continue;
|
|
293
|
+
const absStart = win.start + r.start;
|
|
294
|
+
const absEnd = win.start + r.end;
|
|
295
|
+
for (const c of win.items) {
|
|
296
|
+
if (absStart <= c.prefixStart && absEnd >= c.prefixEnd && absEnd <= c.hyphenIndex) {
|
|
297
|
+
extra.push({
|
|
298
|
+
start: c.prefixStart,
|
|
299
|
+
end: c.prefixEnd,
|
|
300
|
+
label: r.label,
|
|
301
|
+
value: text.slice(c.prefixStart, c.prefixEnd)
|
|
302
|
+
});
|
|
303
|
+
break;
|
|
304
|
+
}
|
|
246
305
|
}
|
|
247
306
|
}
|
|
248
307
|
}
|
|
@@ -298,47 +357,54 @@ function createMaskeraEngine(options = {}) {
|
|
|
298
357
|
const model = options.nerOptions?.model ?? MASKERA_SV_NER_MODEL;
|
|
299
358
|
const revision = options.nerOptions?.revision ?? (model === MASKERA_SV_NER_MODEL ? MASKERA_SV_NER_REVISION : void 0);
|
|
300
359
|
const maxCacheEntries = Math.max(0, options.maxCacheEntries ?? DEFAULT_MAX_CACHE_ENTRIES);
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
let
|
|
360
|
+
const localPath = options.nerOptions?.localModelPath;
|
|
361
|
+
const hasLocalQ8 = typeof localPath === "string" && existsSync(join(localPath, model, "onnx", "model_quantized.onnx"));
|
|
362
|
+
const dtype = options.nerOptions?.dtype ?? (localPath && !hasLocalQ8 ? "q4" : "q8");
|
|
363
|
+
let lifecycle = { phase: "idle", recognizer: options.recognizer ?? null };
|
|
364
|
+
let loadAttempt = 0;
|
|
305
365
|
const spanCache = /* @__PURE__ */ new Map();
|
|
306
366
|
const customDetectorCache = /* @__PURE__ */ new Map();
|
|
307
367
|
let cacheHits = 0;
|
|
308
368
|
let cacheMisses = 0;
|
|
309
|
-
function
|
|
310
|
-
if (
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
369
|
+
function ensureRecognizerLoading() {
|
|
370
|
+
if (lifecycle.phase === "loading" || lifecycle.phase === "ready") {
|
|
371
|
+
return lifecycle.recognizer;
|
|
372
|
+
}
|
|
373
|
+
const recognizer = lifecycle.recognizer ?? createNerRecognizer({
|
|
374
|
+
...options.nerOptions,
|
|
375
|
+
model,
|
|
376
|
+
revision,
|
|
377
|
+
dtype
|
|
378
|
+
});
|
|
379
|
+
loadAttempt += 1;
|
|
380
|
+
const attempt = loadAttempt;
|
|
381
|
+
const startedAt = Date.now();
|
|
382
|
+
lifecycle = { phase: "loading", recognizer, startedAt, attempt };
|
|
383
|
+
options.onModelStatus?.({ phase: "loading", model, dtype });
|
|
384
|
+
void recognizer.ready.then(
|
|
385
|
+
() => {
|
|
386
|
+
if (lifecycle.phase === "loading" && lifecycle.attempt === attempt) {
|
|
387
|
+
lifecycle = { phase: "ready", recognizer };
|
|
324
388
|
options.onModelStatus?.({
|
|
325
389
|
phase: "ready",
|
|
326
390
|
model,
|
|
327
|
-
elapsedMs: Date.now() -
|
|
391
|
+
elapsedMs: Date.now() - startedAt
|
|
328
392
|
});
|
|
329
|
-
}
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
393
|
+
}
|
|
394
|
+
},
|
|
395
|
+
(err) => {
|
|
396
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
397
|
+
if (lifecycle.phase === "loading" && lifecycle.attempt === attempt) {
|
|
398
|
+
lifecycle = { phase: "failed", recognizer, error: message };
|
|
333
399
|
options.onModelStatus?.({
|
|
334
400
|
phase: "error",
|
|
335
401
|
model,
|
|
336
|
-
elapsedMs: Date.now() -
|
|
402
|
+
elapsedMs: Date.now() - startedAt,
|
|
337
403
|
error: message
|
|
338
404
|
});
|
|
339
405
|
}
|
|
340
|
-
|
|
341
|
-
|
|
406
|
+
}
|
|
407
|
+
);
|
|
342
408
|
return recognizer;
|
|
343
409
|
}
|
|
344
410
|
function getCustomDetector(rawTerms) {
|
|
@@ -365,19 +431,9 @@ function createMaskeraEngine(options = {}) {
|
|
|
365
431
|
}
|
|
366
432
|
return {
|
|
367
433
|
warmup() {
|
|
368
|
-
if (defaultMode !== "auto"
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
void ner.ready.then(
|
|
372
|
-
() => {
|
|
373
|
-
nerLoaded = true;
|
|
374
|
-
nerError = null;
|
|
375
|
-
},
|
|
376
|
-
(err) => {
|
|
377
|
-
warmupStarted = false;
|
|
378
|
-
nerError = err instanceof Error ? err.message : String(err);
|
|
379
|
-
}
|
|
380
|
-
);
|
|
434
|
+
if (defaultMode !== "auto") return;
|
|
435
|
+
if (lifecycle.phase === "loading" || lifecycle.phase === "ready") return;
|
|
436
|
+
ensureRecognizerLoading();
|
|
381
437
|
},
|
|
382
438
|
clearCache() {
|
|
383
439
|
spanCache.clear();
|
|
@@ -450,8 +506,8 @@ function createMaskeraEngine(options = {}) {
|
|
|
450
506
|
modeUsed: "rules"
|
|
451
507
|
};
|
|
452
508
|
}
|
|
509
|
+
const ner = ensureRecognizerLoading();
|
|
453
510
|
try {
|
|
454
|
-
const ner = getRecognizer();
|
|
455
511
|
const canonical = canonicalize(text);
|
|
456
512
|
const homoglyph = normalizeMixedScriptHomoglyphs(canonical.text);
|
|
457
513
|
const isIdentity = canonical.identity && !homoglyph.changed;
|
|
@@ -482,8 +538,13 @@ function createMaskeraEngine(options = {}) {
|
|
|
482
538
|
return end > start ? [{ start, end, label: d.label, value: text.slice(start, end) }] : [];
|
|
483
539
|
})
|
|
484
540
|
);
|
|
485
|
-
|
|
486
|
-
|
|
541
|
+
if (lifecycle.phase === "loading") {
|
|
542
|
+
const elapsedMs = Date.now() - lifecycle.startedAt;
|
|
543
|
+
lifecycle = { phase: "ready", recognizer: ner };
|
|
544
|
+
options.onModelStatus?.({ phase: "ready", model, elapsedMs });
|
|
545
|
+
} else if (lifecycle.phase !== "ready") {
|
|
546
|
+
lifecycle = { phase: "ready", recognizer: ner };
|
|
547
|
+
}
|
|
487
548
|
if (cacheKey) {
|
|
488
549
|
if (spanCache.size >= maxCacheEntries) {
|
|
489
550
|
const oldest = spanCache.keys().next().value;
|
|
@@ -501,7 +562,13 @@ function createMaskeraEngine(options = {}) {
|
|
|
501
562
|
return { result, modeUsed: "hybrid" };
|
|
502
563
|
} catch (err) {
|
|
503
564
|
const message = err instanceof Error ? err.message : String(err);
|
|
504
|
-
|
|
565
|
+
if (lifecycle.phase === "loading") {
|
|
566
|
+
const elapsedMs = Date.now() - lifecycle.startedAt;
|
|
567
|
+
lifecycle = { phase: "failed", recognizer: ner, error: message };
|
|
568
|
+
options.onModelStatus?.({ phase: "error", model, elapsedMs, error: message });
|
|
569
|
+
} else {
|
|
570
|
+
lifecycle = { phase: "failed", recognizer: ner, error: message };
|
|
571
|
+
}
|
|
505
572
|
throw new Error(
|
|
506
573
|
`Hybrid NER failed to run (${message}). Pass mode="rules" explicitly if you only want deterministic structured redaction.`
|
|
507
574
|
);
|
|
@@ -512,8 +579,9 @@ function createMaskeraEngine(options = {}) {
|
|
|
512
579
|
defaultMode,
|
|
513
580
|
model,
|
|
514
581
|
revision: revision ?? "local",
|
|
515
|
-
|
|
516
|
-
|
|
582
|
+
nerPhase: lifecycle.phase,
|
|
583
|
+
nerLoaded: lifecycle.phase === "ready",
|
|
584
|
+
nerError: lifecycle.phase === "failed" ? lifecycle.error : null,
|
|
517
585
|
cacheSize: spanCache.size,
|
|
518
586
|
cacheHits,
|
|
519
587
|
cacheMisses
|
|
@@ -528,31 +596,39 @@ function downloadSize(dtype) {
|
|
|
528
596
|
}
|
|
529
597
|
function createModelProgressLogger(write = (line) => process.stderr.write(`${line}
|
|
530
598
|
`), delayMs = 350) {
|
|
531
|
-
let
|
|
532
|
-
let announcedLoading = false;
|
|
599
|
+
let state = { tag: "quiet" };
|
|
533
600
|
return (event) => {
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
601
|
+
switch (event.phase) {
|
|
602
|
+
case "loading": {
|
|
603
|
+
if (state.tag === "delayed") clearTimeout(state.timer);
|
|
604
|
+
const timer = setTimeout(() => {
|
|
605
|
+
state = { tag: "announced" };
|
|
606
|
+
write(
|
|
607
|
+
`[maskera] Loading Swedish ONNX model (${event.model}${downloadSize(event.dtype)}, cached locally)...`
|
|
608
|
+
);
|
|
609
|
+
}, delayMs);
|
|
610
|
+
timer.unref?.();
|
|
611
|
+
state = { tag: "delayed", timer };
|
|
612
|
+
return;
|
|
613
|
+
}
|
|
614
|
+
case "ready": {
|
|
615
|
+
if (state.tag === "delayed") {
|
|
616
|
+
clearTimeout(state.timer);
|
|
617
|
+
} else if (state.tag === "announced") {
|
|
618
|
+
write(`[maskera] Swedish ONNX model ready (${event.elapsedMs ?? 0}ms).`);
|
|
619
|
+
}
|
|
620
|
+
state = { tag: "quiet" };
|
|
621
|
+
return;
|
|
622
|
+
}
|
|
623
|
+
case "error": {
|
|
624
|
+
if (state.tag === "delayed") {
|
|
625
|
+
clearTimeout(state.timer);
|
|
626
|
+
} else if (state.tag === "announced") {
|
|
627
|
+
write(`[maskera] Swedish ONNX model load failed: ${event.error ?? "unknown error"}`);
|
|
628
|
+
}
|
|
629
|
+
state = { tag: "quiet" };
|
|
630
|
+
return;
|
|
631
|
+
}
|
|
556
632
|
}
|
|
557
633
|
};
|
|
558
634
|
}
|
|
@@ -1818,6 +1894,7 @@ function enforceSessionSecretsRedacted(text, sessionMap) {
|
|
|
1818
1894
|
}
|
|
1819
1895
|
return { text: out, extraRedactions };
|
|
1820
1896
|
}
|
|
1897
|
+
var MAX_CLIENT_SESSIONS = 500;
|
|
1821
1898
|
function createMaskeraMcpServer(options = {}) {
|
|
1822
1899
|
const engine = options.engine ?? createMaskeraEngine();
|
|
1823
1900
|
const vault = options.vault ?? new SessionVault();
|
|
@@ -1828,8 +1905,24 @@ function createMaskeraMcpServer(options = {}) {
|
|
|
1828
1905
|
const approvalBaseUrl = options.approvalBaseUrl;
|
|
1829
1906
|
const requestElicitation = options.requestElicitation;
|
|
1830
1907
|
const onToolCall = options.onToolCall;
|
|
1831
|
-
|
|
1908
|
+
const clientSessions = /* @__PURE__ */ new Map();
|
|
1832
1909
|
const ownerPathAliases = /* @__PURE__ */ new Map();
|
|
1910
|
+
function getClientHandshake(owner) {
|
|
1911
|
+
return clientSessions.get(owner) ?? { status: "uninitialized" };
|
|
1912
|
+
}
|
|
1913
|
+
function setClientInitialized(owner, protocolVersion, supportsElicitation) {
|
|
1914
|
+
if (clientSessions.has(owner)) {
|
|
1915
|
+
clientSessions.delete(owner);
|
|
1916
|
+
} else if (clientSessions.size >= MAX_CLIENT_SESSIONS) {
|
|
1917
|
+
const oldest = clientSessions.keys().next().value;
|
|
1918
|
+
if (oldest !== void 0) clientSessions.delete(oldest);
|
|
1919
|
+
}
|
|
1920
|
+
clientSessions.set(owner, {
|
|
1921
|
+
status: "initialized",
|
|
1922
|
+
protocolVersion,
|
|
1923
|
+
supportsElicitation
|
|
1924
|
+
});
|
|
1925
|
+
}
|
|
1833
1926
|
function getPathAliasBucket(owner) {
|
|
1834
1927
|
let bucket = ownerPathAliases.get(owner);
|
|
1835
1928
|
if (!bucket) {
|
|
@@ -2020,7 +2113,8 @@ function createMaskeraMcpServer(options = {}) {
|
|
|
2020
2113
|
return toolOk(await input.execute());
|
|
2021
2114
|
}
|
|
2022
2115
|
if (policy.approvalMode === "native") {
|
|
2023
|
-
|
|
2116
|
+
const handshake = getClientHandshake(policy.sessionOwner);
|
|
2117
|
+
if (!requestElicitation || handshake.status !== "initialized" || !handshake.supportsElicitation) {
|
|
2024
2118
|
return toolError(
|
|
2025
2119
|
`Approval mode "native" requires an MCP client with elicitation support. Reconnect with approval_mode=browser or write restored output directly via maskera_write_file.`
|
|
2026
2120
|
);
|
|
@@ -2185,6 +2279,9 @@ function createMaskeraMcpServer(options = {}) {
|
|
|
2185
2279
|
if (resumed.status === "not_found") {
|
|
2186
2280
|
return finish(toolError(`Unknown approval request_id "${requestId}".`));
|
|
2187
2281
|
}
|
|
2282
|
+
if (resumed.status === "failed") {
|
|
2283
|
+
return finish(toolError(`Approval request "${requestId}" failed: ${resumed.error}`));
|
|
2284
|
+
}
|
|
2188
2285
|
if (resumed.status === "completed") {
|
|
2189
2286
|
return finish(
|
|
2190
2287
|
toolOk({
|
|
@@ -2411,6 +2508,17 @@ function createMaskeraMcpServer(options = {}) {
|
|
|
2411
2508
|
}
|
|
2412
2509
|
return {
|
|
2413
2510
|
vault,
|
|
2511
|
+
getClientState(owner) {
|
|
2512
|
+
return getClientHandshake(owner ?? options.sessionOwner ?? "default");
|
|
2513
|
+
},
|
|
2514
|
+
clearOwner(owner) {
|
|
2515
|
+
clientSessions.delete(owner);
|
|
2516
|
+
ownerPathAliases.delete(owner);
|
|
2517
|
+
},
|
|
2518
|
+
clearAllOwners() {
|
|
2519
|
+
clientSessions.clear();
|
|
2520
|
+
ownerPathAliases.clear();
|
|
2521
|
+
},
|
|
2414
2522
|
async handleMessage(raw, policyOverride) {
|
|
2415
2523
|
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
|
|
2416
2524
|
return {
|
|
@@ -2437,9 +2545,10 @@ function createMaskeraMcpServer(options = {}) {
|
|
|
2437
2545
|
if (req.method === "initialize") {
|
|
2438
2546
|
const params = asObject(req.params);
|
|
2439
2547
|
const clientCaps = asObject(params.capabilities);
|
|
2440
|
-
|
|
2548
|
+
const supportsElicitation = Boolean("elicitation" in clientCaps && clientCaps.elicitation);
|
|
2441
2549
|
const requested = typeof params.protocolVersion === "string" ? params.protocolVersion : void 0;
|
|
2442
2550
|
const protocolVersion = requested && SUPPORTED_PROTOCOLS.includes(requested) ? requested : SUPPORTED_PROTOCOLS[0];
|
|
2551
|
+
setClientInitialized(policy.sessionOwner, protocolVersion, supportsElicitation);
|
|
2443
2552
|
return {
|
|
2444
2553
|
jsonrpc: "2.0",
|
|
2445
2554
|
id,
|
|
@@ -3391,13 +3500,93 @@ function renderInspectorHtml(info) {
|
|
|
3391
3500
|
const stUniq = document.getElementById("st-uniq");
|
|
3392
3501
|
const stModel = document.getElementById("st-model");
|
|
3393
3502
|
const SAMPLE_PROMPT = "Skriv ett kort mejl till Anna Lindqvist (provnamn.maskera@example.com, 19900101-2385) och bekr\xE4fta m\xF6tet.";
|
|
3394
|
-
|
|
3395
|
-
|
|
3396
|
-
|
|
3397
|
-
|
|
3398
|
-
|
|
3399
|
-
|
|
3400
|
-
|
|
3503
|
+
const VISIBLE_APPROVAL_STATUSES = new Set(["pending", "approved", "executing", "declined", "failed"]);
|
|
3504
|
+
const state = {
|
|
3505
|
+
connection: "connecting",
|
|
3506
|
+
items: [],
|
|
3507
|
+
approvals: [],
|
|
3508
|
+
selfTest: { phase: "idle" },
|
|
3509
|
+
vaultView: "hidden",
|
|
3510
|
+
expansion: { mode: "auto" },
|
|
3511
|
+
};
|
|
3512
|
+
|
|
3513
|
+
function isExpanded(itemId, index) {
|
|
3514
|
+
if (state.expansion.mode === "auto") return index === 0;
|
|
3515
|
+
return state.expansion.openIds.has(itemId);
|
|
3516
|
+
}
|
|
3517
|
+
|
|
3518
|
+
function transition(event) {
|
|
3519
|
+
switch (event.type) {
|
|
3520
|
+
case "sse_open":
|
|
3521
|
+
state.connection = "live";
|
|
3522
|
+
return;
|
|
3523
|
+
case "sse_error":
|
|
3524
|
+
state.connection = "reconnecting";
|
|
3525
|
+
return;
|
|
3526
|
+
case "sse_init":
|
|
3527
|
+
state.connection = "live";
|
|
3528
|
+
state.items = event.items || [];
|
|
3529
|
+
state.approvals = event.approvals || [];
|
|
3530
|
+
renderApprovals();
|
|
3531
|
+
render();
|
|
3532
|
+
void refreshStatus();
|
|
3533
|
+
return;
|
|
3534
|
+
case "sse_approvals":
|
|
3535
|
+
state.approvals = event.approvals || [];
|
|
3536
|
+
renderApprovals();
|
|
3537
|
+
void refreshStatus();
|
|
3538
|
+
return;
|
|
3539
|
+
case "sse_request":
|
|
3540
|
+
state.items.unshift(event.item);
|
|
3541
|
+
if (state.items.length > 100) state.items.length = 100;
|
|
3542
|
+
render();
|
|
3543
|
+
void refreshStatus();
|
|
3544
|
+
if (state.vaultView === "revealed") void refreshVault();
|
|
3545
|
+
return;
|
|
3546
|
+
case "cleared":
|
|
3547
|
+
state.items = [];
|
|
3548
|
+
state.approvals = [];
|
|
3549
|
+
state.expansion = { mode: "auto" };
|
|
3550
|
+
renderApprovals();
|
|
3551
|
+
render();
|
|
3552
|
+
void refreshStatus();
|
|
3553
|
+
void refreshVault();
|
|
3554
|
+
return;
|
|
3555
|
+
case "toggle_item": {
|
|
3556
|
+
const openIds =
|
|
3557
|
+
state.expansion.mode === "manual"
|
|
3558
|
+
? new Set(state.expansion.openIds)
|
|
3559
|
+
: new Set(state.items[0]?.id ? [state.items[0].id] : []);
|
|
3560
|
+
if (event.open) openIds.add(event.id);
|
|
3561
|
+
else openIds.delete(event.id);
|
|
3562
|
+
state.expansion = { mode: "manual", openIds };
|
|
3563
|
+
return;
|
|
3564
|
+
}
|
|
3565
|
+
case "toggle_vault":
|
|
3566
|
+
state.vaultView = state.vaultView === "revealed" ? "hidden" : "revealed";
|
|
3567
|
+
revealBtn.classList.toggle("active", state.vaultView === "revealed");
|
|
3568
|
+
revealBtn.textContent = state.vaultView === "revealed" ? "D\xF6lj originalv\xE4rden" : "Visa originalv\xE4rden";
|
|
3569
|
+
void refreshVault();
|
|
3570
|
+
return;
|
|
3571
|
+
case "selftest_start":
|
|
3572
|
+
state.selfTest = { phase: "running" };
|
|
3573
|
+
renderReceipt();
|
|
3574
|
+
return;
|
|
3575
|
+
case "selftest_done":
|
|
3576
|
+
state.selfTest = { phase: "done", receipt: event.receipt };
|
|
3577
|
+
renderReceipt();
|
|
3578
|
+
void refreshStatus();
|
|
3579
|
+
return;
|
|
3580
|
+
case "selftest_error":
|
|
3581
|
+
state.selfTest = { phase: "error", message: event.message };
|
|
3582
|
+
renderReceipt();
|
|
3583
|
+
return;
|
|
3584
|
+
case "selftest_close":
|
|
3585
|
+
state.selfTest = { phase: "idle" };
|
|
3586
|
+
renderReceipt();
|
|
3587
|
+
return;
|
|
3588
|
+
}
|
|
3589
|
+
}
|
|
3401
3590
|
|
|
3402
3591
|
const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ "&":"&","<":"<",">":">",'"':""","'":"'" }[c]));
|
|
3403
3592
|
const highlightTokens = (s) => esc(s).replace(/\\[[A-Z\xC5\xC4\xD6][A-Z\xC5\xC4\xD60-9_]*_\\d+\\]/g, (m) => '<span class="tok">' + m + "</span>");
|
|
@@ -3413,11 +3602,17 @@ function renderInspectorHtml(info) {
|
|
|
3413
3602
|
};
|
|
3414
3603
|
|
|
3415
3604
|
function renderReceipt() {
|
|
3416
|
-
|
|
3417
|
-
|
|
3605
|
+
selftestBtn.disabled = state.selfTest.phase === "running";
|
|
3606
|
+
selftestBtn.textContent = state.selfTest.phase === "running" ? "K\xF6r sj\xE4lvtest..." : "K\xF6r sj\xE4lvtest";
|
|
3607
|
+
if (state.selfTest.phase === "idle" || state.selfTest.phase === "running") {
|
|
3608
|
+
if (state.selfTest.phase === "idle") receiptRoot.innerHTML = "";
|
|
3609
|
+
return;
|
|
3610
|
+
}
|
|
3611
|
+
if (state.selfTest.phase === "error") {
|
|
3612
|
+
receiptRoot.innerHTML = '<section class="receipt-box"><h2>Sj\xE4lvtest misslyckades</h2><p>' + esc(state.selfTest.message) + '</p></section>';
|
|
3418
3613
|
return;
|
|
3419
3614
|
}
|
|
3420
|
-
const r =
|
|
3615
|
+
const r = state.selfTest.receipt;
|
|
3421
3616
|
const checksHtml = (r.checks || []).map((c) => {
|
|
3422
3617
|
const cls = c.status === "fail" ? " fail" : "";
|
|
3423
3618
|
return '<li><span class="receipt-tag' + cls + '">[' + esc(c.status) + ']</span><span><strong>' + esc(c.name) + ':</strong> ' + esc(c.detail) + '</span></li>';
|
|
@@ -3443,29 +3638,22 @@ function renderInspectorHtml(info) {
|
|
|
3443
3638
|
const closeBtn = document.getElementById("close-receipt-btn");
|
|
3444
3639
|
if (closeBtn) {
|
|
3445
3640
|
closeBtn.addEventListener("click", () => {
|
|
3446
|
-
|
|
3447
|
-
renderReceipt();
|
|
3641
|
+
transition({ type: "selftest_close" });
|
|
3448
3642
|
});
|
|
3449
3643
|
}
|
|
3450
3644
|
}
|
|
3451
3645
|
|
|
3452
3646
|
selftestBtn.addEventListener("click", async () => {
|
|
3453
|
-
|
|
3454
|
-
|
|
3455
|
-
selftestBtn.textContent = "K\xF6r sj\xE4lvtest...";
|
|
3647
|
+
if (state.selfTest.phase === "running") return;
|
|
3648
|
+
transition({ type: "selftest_start" });
|
|
3456
3649
|
try {
|
|
3457
3650
|
const r = await fetch("/_maskera/self-test", {
|
|
3458
3651
|
method: "POST",
|
|
3459
3652
|
headers: { "x-maskera-action": "self-test" },
|
|
3460
3653
|
});
|
|
3461
|
-
|
|
3462
|
-
renderReceipt();
|
|
3463
|
-
await refreshStatus();
|
|
3654
|
+
transition({ type: "selftest_done", receipt: await r.json() });
|
|
3464
3655
|
} catch (err) {
|
|
3465
|
-
|
|
3466
|
-
} finally {
|
|
3467
|
-
selftestBtn.disabled = false;
|
|
3468
|
-
selftestBtn.textContent = prevText;
|
|
3656
|
+
transition({ type: "selftest_error", message: String(err) });
|
|
3469
3657
|
}
|
|
3470
3658
|
});
|
|
3471
3659
|
|
|
@@ -3493,7 +3681,7 @@ function renderInspectorHtml(info) {
|
|
|
3493
3681
|
}
|
|
3494
3682
|
|
|
3495
3683
|
function renderApprovals() {
|
|
3496
|
-
const visible = (approvals || []).filter((a) =>
|
|
3684
|
+
const visible = (state.approvals || []).filter((a) => VISIBLE_APPROVAL_STATUSES.has(a.status));
|
|
3497
3685
|
if (!visible.length) {
|
|
3498
3686
|
approvalsRoot.innerHTML = "";
|
|
3499
3687
|
return;
|
|
@@ -3501,7 +3689,7 @@ function renderInspectorHtml(info) {
|
|
|
3501
3689
|
const rows = visible.map((a) => {
|
|
3502
3690
|
const btns = a.status === "pending"
|
|
3503
3691
|
? '<div class="actions"><button type="button" class="primary" data-apr="' + esc(a.id) + '" data-act="approve">Godk\xE4nn</button><button type="button" data-apr="' + esc(a.id) + '" data-act="decline">Neka</button></div>'
|
|
3504
|
-
: '<span class="badge">' + esc(a.status) + "</span>";
|
|
3692
|
+
: '<span class="badge' + (a.status === "failed" ? " err" : "") + '">' + esc(a.status) + "</span>";
|
|
3505
3693
|
return '<div class="approval-row" id="approval-' + esc(a.id) + '"><div><strong>' + esc(a.tool) + '</strong> \xB7 ' + esc(a.reason) + '<div class="approval-meta">F\xF6rfr\xE5gan ' + esc(a.id) + (a.sessionId ? ' \xB7 session ' + esc(a.sessionId) : '') + ' \xB7 ' + esc(a.placeholderCount) + ' v\xE4rden</div></div>' + btns + '</div>';
|
|
3506
3694
|
}).join("");
|
|
3507
3695
|
approvalsRoot.innerHTML = '<section class="approvals"><h2>V\xE4ntande godk\xE4nnanden (r\xE5 PII)</h2>' + rows + "</section>";
|
|
@@ -3515,7 +3703,7 @@ function renderInspectorHtml(info) {
|
|
|
3515
3703
|
}
|
|
3516
3704
|
|
|
3517
3705
|
async function refreshVault() {
|
|
3518
|
-
if (
|
|
3706
|
+
if (state.vaultView !== "revealed") { vaultRoot.innerHTML = ""; return; }
|
|
3519
3707
|
try {
|
|
3520
3708
|
const r = await fetch("/_maskera/vault", { headers: { "x-maskera-reveal": "1" } });
|
|
3521
3709
|
const d = await r.json();
|
|
@@ -3527,7 +3715,7 @@ function renderInspectorHtml(info) {
|
|
|
3527
3715
|
}
|
|
3528
3716
|
|
|
3529
3717
|
function render() {
|
|
3530
|
-
if (!items.length) {
|
|
3718
|
+
if (!state.items.length) {
|
|
3531
3719
|
feedEl.innerHTML =
|
|
3532
3720
|
'<div class="empty"><p class="empty-title">Inga anrop \xE4nnu.</p>' +
|
|
3533
3721
|
'Skicka ett prov fr\xE5n din klient s\xE5 visas maskeringen h\xE4r:' +
|
|
@@ -3545,17 +3733,13 @@ function renderInspectorHtml(info) {
|
|
|
3545
3733
|
}
|
|
3546
3734
|
return;
|
|
3547
3735
|
}
|
|
3548
|
-
|
|
3549
|
-
openIds.add(items[0].id);
|
|
3550
|
-
}
|
|
3551
|
-
for (const it of items) seenIds.add(it.id);
|
|
3552
|
-
feedEl.innerHTML = '<div class="list">' + items.map((it) => {
|
|
3736
|
+
feedEl.innerHTML = '<div class="list">' + state.items.map((it, idx) => {
|
|
3553
3737
|
const time = formatLocalTime(it.timestamp);
|
|
3554
3738
|
const tags = Object.entries(it.counts || {}).map(([k, v]) => '<span class="count-tag">' + esc(k) + " \xD7" + v + "</span>").join("");
|
|
3555
3739
|
const previews = (it.redactedPreview || []).map((p) => '<pre class="preview">' + highlightTokens(p) + "</pre>").join("");
|
|
3556
3740
|
const errBlock = it.errorDetail ? '<p class="body-label">Svar fr\xE5n API (fel):</p><pre class="preview err-preview">' + esc(it.errorDetail) + "</pre>" : "";
|
|
3557
3741
|
const statusCls = it.status >= 200 && it.status < 400 ? "" : " err";
|
|
3558
|
-
const isOpen =
|
|
3742
|
+
const isOpen = isExpanded(it.id, idx);
|
|
3559
3743
|
return '<details class="item" data-id="' + esc(it.id) + '"' + (isOpen ? " open" : "") + '>' +
|
|
3560
3744
|
'<summary><span class="left"><span class="badge' + statusCls + '">' + it.status + '</span><span class="path">' + esc(it.method + " " + it.path) + '</span>' + tags + (it.redactions === 0 ? '<span style="color:var(--muted);font-size:12px">0 PII</span>' : "") + '</span>' +
|
|
3561
3745
|
'<span class="right"><span>' + (it.streamed ? "SSE" : "JSON") + '</span><span>' + it.durationMs + ' ms</span><span>' + esc(time) + '</span></span></summary>' +
|
|
@@ -3565,67 +3749,36 @@ function renderInspectorHtml(info) {
|
|
|
3565
3749
|
det.addEventListener("toggle", () => {
|
|
3566
3750
|
const id = det.getAttribute("data-id");
|
|
3567
3751
|
if (!id) return;
|
|
3568
|
-
|
|
3569
|
-
if (det.open) openIds.add(id);
|
|
3570
|
-
else openIds.delete(id);
|
|
3752
|
+
transition({ type: "toggle_item", id, open: det.open });
|
|
3571
3753
|
});
|
|
3572
3754
|
}
|
|
3573
3755
|
}
|
|
3574
3756
|
|
|
3575
3757
|
revealBtn.addEventListener("click", () => {
|
|
3576
|
-
|
|
3577
|
-
revealBtn.classList.toggle("active", reveal);
|
|
3578
|
-
revealBtn.textContent = reveal ? "D\xF6lj originalv\xE4rden" : "Visa originalv\xE4rden";
|
|
3579
|
-
void refreshVault();
|
|
3758
|
+
transition({ type: "toggle_vault" });
|
|
3580
3759
|
});
|
|
3581
3760
|
|
|
3582
3761
|
clearBtn.addEventListener("click", async () => {
|
|
3583
3762
|
await fetch("/_maskera/clear", { method: "POST", headers: { "x-maskera-action": "clear" } });
|
|
3584
|
-
|
|
3585
|
-
approvals = [];
|
|
3586
|
-
userToggled = false;
|
|
3587
|
-
openIds.clear();
|
|
3588
|
-
seenIds.clear();
|
|
3589
|
-
renderApprovals();
|
|
3590
|
-
render();
|
|
3591
|
-
await refreshStatus();
|
|
3592
|
-
await refreshVault();
|
|
3763
|
+
transition({ type: "cleared" });
|
|
3593
3764
|
});
|
|
3594
3765
|
|
|
3595
3766
|
const es = new EventSource("/_maskera/events");
|
|
3767
|
+
es.addEventListener("open", () => transition({ type: "sse_open" }));
|
|
3768
|
+
es.addEventListener("error", () => transition({ type: "sse_error" }));
|
|
3596
3769
|
es.addEventListener("init", (ev) => {
|
|
3597
3770
|
const data = JSON.parse(ev.data);
|
|
3598
|
-
items
|
|
3599
|
-
approvals = data.approvals || [];
|
|
3600
|
-
renderApprovals();
|
|
3601
|
-
render();
|
|
3602
|
-
void refreshStatus();
|
|
3771
|
+
transition({ type: "sse_init", items: data.items, approvals: data.approvals });
|
|
3603
3772
|
});
|
|
3604
3773
|
es.addEventListener("approvals", (ev) => {
|
|
3605
3774
|
const data = JSON.parse(ev.data);
|
|
3606
|
-
approvals
|
|
3607
|
-
renderApprovals();
|
|
3608
|
-
void refreshStatus();
|
|
3775
|
+
transition({ type: "sse_approvals", approvals: data.approvals });
|
|
3609
3776
|
});
|
|
3610
3777
|
es.addEventListener("request", (ev) => {
|
|
3611
|
-
|
|
3612
|
-
items.unshift(next);
|
|
3613
|
-
if (items.length > 100) items.length = 100;
|
|
3614
|
-
if (!userToggled && openIds.size === 0 && next?.id) openIds.add(next.id);
|
|
3615
|
-
render();
|
|
3616
|
-
void refreshStatus();
|
|
3617
|
-
if (reveal) void refreshVault();
|
|
3778
|
+
transition({ type: "sse_request", item: JSON.parse(ev.data) });
|
|
3618
3779
|
});
|
|
3619
3780
|
es.addEventListener("cleared", () => {
|
|
3620
|
-
|
|
3621
|
-
approvals = [];
|
|
3622
|
-
userToggled = false;
|
|
3623
|
-
openIds.clear();
|
|
3624
|
-
seenIds.clear();
|
|
3625
|
-
renderApprovals();
|
|
3626
|
-
render();
|
|
3627
|
-
void refreshStatus();
|
|
3628
|
-
void refreshVault();
|
|
3781
|
+
transition({ type: "cleared" });
|
|
3629
3782
|
});
|
|
3630
3783
|
void refreshStatus();
|
|
3631
3784
|
})();
|
|
@@ -4947,173 +5100,229 @@ function restoreLlmResponseBody(body, map, options = {}) {
|
|
|
4947
5100
|
}
|
|
4948
5101
|
return clone;
|
|
4949
5102
|
}
|
|
4950
|
-
function
|
|
4951
|
-
|
|
4952
|
-
|
|
4953
|
-
|
|
4954
|
-
|
|
4955
|
-
|
|
4956
|
-
|
|
4957
|
-
|
|
4958
|
-
|
|
4959
|
-
|
|
4960
|
-
|
|
4961
|
-
|
|
4962
|
-
|
|
4963
|
-
|
|
4964
|
-
|
|
4965
|
-
if (!r) return "";
|
|
4966
|
-
streams.delete(key);
|
|
4967
|
-
return r.flush();
|
|
4968
|
-
}
|
|
4969
|
-
function flushBufferedToolArgs(key) {
|
|
4970
|
-
const raw = bufferedToolArgs.get(key);
|
|
4971
|
-
if (raw === void 0) return "";
|
|
4972
|
-
bufferedToolArgs.delete(key);
|
|
4973
|
-
const name = toolNames.get(key);
|
|
4974
|
-
if (shouldSkipToolArgRestore(name, raw)) return raw;
|
|
4975
|
-
return restoreJsonEncodedText(raw, map);
|
|
5103
|
+
function channelKey(d) {
|
|
5104
|
+
switch (d.protocol) {
|
|
5105
|
+
case "anthropic":
|
|
5106
|
+
return `anthropic:${d.kind}:${d.index}`;
|
|
5107
|
+
case "openai_chat":
|
|
5108
|
+
return d.kind === "tool_args" ? `openai_chat:tool_args:${d.choiceIndex}:${d.toolIndex}` : `openai_chat:${d.kind}:${d.choiceIndex}`;
|
|
5109
|
+
case "openai_responses":
|
|
5110
|
+
switch (d.kind) {
|
|
5111
|
+
case "text":
|
|
5112
|
+
return `openai_responses:text:${d.outputIndex}:${d.contentIndex}`;
|
|
5113
|
+
case "reasoning":
|
|
5114
|
+
return `openai_responses:reasoning:${d.outputIndex}:${d.summaryIndex}`;
|
|
5115
|
+
case "tool_args":
|
|
5116
|
+
return `openai_responses:tool_args:${d.outputIndex}`;
|
|
5117
|
+
}
|
|
4976
5118
|
}
|
|
4977
|
-
|
|
4978
|
-
|
|
4979
|
-
|
|
4980
|
-
|
|
4981
|
-
|
|
4982
|
-
|
|
4983
|
-
|
|
4984
|
-
events.push(
|
|
4985
|
-
`data: ${JSON.stringify({
|
|
4986
|
-
choices: [
|
|
4987
|
-
{
|
|
4988
|
-
index: Number(cIdx ?? 0),
|
|
4989
|
-
delta: {
|
|
4990
|
-
tool_calls: [{ index: Number(tIdx ?? 0), function: { arguments: full } }]
|
|
4991
|
-
}
|
|
4992
|
-
}
|
|
4993
|
-
]
|
|
4994
|
-
})}`
|
|
4995
|
-
);
|
|
4996
|
-
} else if (key.startsWith("anth_json:")) {
|
|
4997
|
-
const idx = Number(key.split(":")[1] ?? 0);
|
|
4998
|
-
events.push(
|
|
4999
|
-
`event: content_block_delta
|
|
5119
|
+
}
|
|
5120
|
+
function formatChannelEvent(descriptor, payload) {
|
|
5121
|
+
switch (descriptor.protocol) {
|
|
5122
|
+
case "anthropic":
|
|
5123
|
+
switch (descriptor.kind) {
|
|
5124
|
+
case "text":
|
|
5125
|
+
return `event: content_block_delta
|
|
5000
5126
|
data: ${JSON.stringify({
|
|
5001
5127
|
type: "content_block_delta",
|
|
5002
|
-
index:
|
|
5003
|
-
delta: { type: "
|
|
5004
|
-
})}
|
|
5005
|
-
|
|
5006
|
-
|
|
5007
|
-
const outputIdx = Number(key.split(":")[1] ?? 0);
|
|
5008
|
-
events.push(
|
|
5009
|
-
`event: response.function_call_arguments.delta
|
|
5128
|
+
index: descriptor.index,
|
|
5129
|
+
delta: { type: "text_delta", text: payload }
|
|
5130
|
+
})}`;
|
|
5131
|
+
case "thinking":
|
|
5132
|
+
return `event: content_block_delta
|
|
5010
5133
|
data: ${JSON.stringify({
|
|
5011
|
-
type: "
|
|
5012
|
-
|
|
5013
|
-
delta:
|
|
5014
|
-
})}
|
|
5015
|
-
|
|
5134
|
+
type: "content_block_delta",
|
|
5135
|
+
index: descriptor.index,
|
|
5136
|
+
delta: { type: "thinking_delta", thinking: payload }
|
|
5137
|
+
})}`;
|
|
5138
|
+
case "tool_json":
|
|
5139
|
+
return `event: content_block_delta
|
|
5140
|
+
data: ${JSON.stringify({
|
|
5141
|
+
type: "content_block_delta",
|
|
5142
|
+
index: descriptor.index,
|
|
5143
|
+
delta: { type: "input_json_delta", partial_json: payload }
|
|
5144
|
+
})}`;
|
|
5016
5145
|
}
|
|
5017
|
-
|
|
5018
|
-
|
|
5019
|
-
|
|
5020
|
-
|
|
5021
|
-
|
|
5022
|
-
|
|
5023
|
-
|
|
5024
|
-
|
|
5025
|
-
|
|
5026
|
-
|
|
5027
|
-
|
|
5028
|
-
|
|
5029
|
-
`data: ${JSON.stringify({
|
|
5146
|
+
break;
|
|
5147
|
+
case "openai_chat":
|
|
5148
|
+
switch (descriptor.kind) {
|
|
5149
|
+
case "text":
|
|
5150
|
+
return `data: ${JSON.stringify({
|
|
5151
|
+
choices: [{ index: descriptor.choiceIndex, delta: { content: payload } }]
|
|
5152
|
+
})}`;
|
|
5153
|
+
case "reasoning":
|
|
5154
|
+
return `data: ${JSON.stringify({
|
|
5155
|
+
choices: [{ index: descriptor.choiceIndex, delta: { reasoning_content: payload } }]
|
|
5156
|
+
})}`;
|
|
5157
|
+
case "reasoning_plain":
|
|
5158
|
+
return `data: ${JSON.stringify({
|
|
5159
|
+
choices: [{ index: descriptor.choiceIndex, delta: { reasoning: payload } }]
|
|
5160
|
+
})}`;
|
|
5161
|
+
case "tool_args":
|
|
5162
|
+
return `data: ${JSON.stringify({
|
|
5030
5163
|
choices: [
|
|
5031
5164
|
{
|
|
5032
|
-
index:
|
|
5165
|
+
index: descriptor.choiceIndex,
|
|
5033
5166
|
delta: {
|
|
5034
|
-
tool_calls: [{ index:
|
|
5167
|
+
tool_calls: [{ index: descriptor.toolIndex, function: { arguments: payload } }]
|
|
5035
5168
|
}
|
|
5036
5169
|
}
|
|
5037
5170
|
]
|
|
5038
|
-
})}
|
|
5039
|
-
|
|
5040
|
-
|
|
5041
|
-
|
|
5042
|
-
|
|
5043
|
-
|
|
5044
|
-
|
|
5045
|
-
type: "content_block_delta",
|
|
5046
|
-
index: idx,
|
|
5047
|
-
delta: { type: "text_delta", text: tail }
|
|
5048
|
-
})}`
|
|
5049
|
-
);
|
|
5050
|
-
} else if (key.startsWith("anth_thinking:")) {
|
|
5051
|
-
const idx = Number(key.split(":")[1] ?? 0);
|
|
5052
|
-
events.push(
|
|
5053
|
-
`event: content_block_delta
|
|
5054
|
-
data: ${JSON.stringify({
|
|
5055
|
-
type: "content_block_delta",
|
|
5056
|
-
index: idx,
|
|
5057
|
-
delta: { type: "thinking_delta", thinking: tail }
|
|
5058
|
-
})}`
|
|
5059
|
-
);
|
|
5060
|
-
} else if (key.startsWith("anth_json:")) {
|
|
5061
|
-
const idx = Number(key.split(":")[1] ?? 0);
|
|
5062
|
-
events.push(
|
|
5063
|
-
`event: content_block_delta
|
|
5064
|
-
data: ${JSON.stringify({
|
|
5065
|
-
type: "content_block_delta",
|
|
5066
|
-
index: idx,
|
|
5067
|
-
delta: { type: "input_json_delta", partial_json: tail }
|
|
5068
|
-
})}`
|
|
5069
|
-
);
|
|
5070
|
-
} else if (key.startsWith("resp_text:")) {
|
|
5071
|
-
const [, outputIdx, contentIdx] = key.split(":");
|
|
5072
|
-
events.push(
|
|
5073
|
-
`event: response.output_text.delta
|
|
5171
|
+
})}`;
|
|
5172
|
+
}
|
|
5173
|
+
break;
|
|
5174
|
+
case "openai_responses":
|
|
5175
|
+
switch (descriptor.kind) {
|
|
5176
|
+
case "text":
|
|
5177
|
+
return `event: response.output_text.delta
|
|
5074
5178
|
data: ${JSON.stringify({
|
|
5075
5179
|
type: "response.output_text.delta",
|
|
5076
|
-
output_index:
|
|
5077
|
-
content_index:
|
|
5078
|
-
delta:
|
|
5079
|
-
})}
|
|
5080
|
-
|
|
5081
|
-
|
|
5082
|
-
const idx = Number(key.split(":")[1] ?? 0);
|
|
5083
|
-
events.push(
|
|
5084
|
-
`data: ${JSON.stringify({ choices: [{ index: idx, delta: { reasoning_content: tail } }] })}`
|
|
5085
|
-
);
|
|
5086
|
-
} else if (key.startsWith("openai_chat_reasoning_plain:")) {
|
|
5087
|
-
const idx = Number(key.split(":")[1] ?? 0);
|
|
5088
|
-
events.push(
|
|
5089
|
-
`data: ${JSON.stringify({ choices: [{ index: idx, delta: { reasoning: tail } }] })}`
|
|
5090
|
-
);
|
|
5091
|
-
} else if (key.startsWith("resp_reasoning:")) {
|
|
5092
|
-
const [, outputIdx, summaryIdx] = key.split(":");
|
|
5093
|
-
events.push(
|
|
5094
|
-
`event: response.reasoning_summary_text.delta
|
|
5180
|
+
output_index: descriptor.outputIndex,
|
|
5181
|
+
content_index: descriptor.contentIndex,
|
|
5182
|
+
delta: payload
|
|
5183
|
+
})}`;
|
|
5184
|
+
case "reasoning":
|
|
5185
|
+
return `event: response.reasoning_summary_text.delta
|
|
5095
5186
|
data: ${JSON.stringify({
|
|
5096
5187
|
type: "response.reasoning_summary_text.delta",
|
|
5097
|
-
output_index:
|
|
5098
|
-
summary_index:
|
|
5099
|
-
delta:
|
|
5100
|
-
})}
|
|
5101
|
-
|
|
5102
|
-
|
|
5103
|
-
const outputIdx = Number(key.split(":")[1] ?? 0);
|
|
5104
|
-
events.push(
|
|
5105
|
-
`event: response.function_call_arguments.delta
|
|
5188
|
+
output_index: descriptor.outputIndex,
|
|
5189
|
+
summary_index: descriptor.summaryIndex,
|
|
5190
|
+
delta: payload
|
|
5191
|
+
})}`;
|
|
5192
|
+
case "tool_args":
|
|
5193
|
+
return `event: response.function_call_arguments.delta
|
|
5106
5194
|
data: ${JSON.stringify({
|
|
5107
5195
|
type: "response.function_call_arguments.delta",
|
|
5108
|
-
output_index:
|
|
5109
|
-
delta:
|
|
5110
|
-
})}
|
|
5111
|
-
|
|
5196
|
+
output_index: descriptor.outputIndex,
|
|
5197
|
+
delta: payload
|
|
5198
|
+
})}`;
|
|
5199
|
+
}
|
|
5200
|
+
}
|
|
5201
|
+
}
|
|
5202
|
+
function createSseRestorer(map, options = {}) {
|
|
5203
|
+
const reasoningMap = filterMapExcluding(map, options.reasoningExcludedTokens);
|
|
5204
|
+
const channels = /* @__PURE__ */ new Map();
|
|
5205
|
+
const frame = { buffer: "", pendingCr: false };
|
|
5206
|
+
function pushStream(descriptor, chunk, useReasoningMap = false) {
|
|
5207
|
+
const key = channelKey(descriptor);
|
|
5208
|
+
let entry = channels.get(key);
|
|
5209
|
+
if (entry?.category !== "stream") {
|
|
5210
|
+
entry = {
|
|
5211
|
+
category: "stream",
|
|
5212
|
+
descriptor,
|
|
5213
|
+
restorer: new StreamingRestorer(useReasoningMap ? reasoningMap : map)
|
|
5214
|
+
};
|
|
5215
|
+
channels.set(key, entry);
|
|
5216
|
+
}
|
|
5217
|
+
return entry.restorer.push(chunk);
|
|
5218
|
+
}
|
|
5219
|
+
function closeStream(descriptor) {
|
|
5220
|
+
const key = channelKey(descriptor);
|
|
5221
|
+
const entry = channels.get(key);
|
|
5222
|
+
if (entry?.category !== "stream") return "";
|
|
5223
|
+
channels.delete(key);
|
|
5224
|
+
return entry.restorer.flush();
|
|
5225
|
+
}
|
|
5226
|
+
function createToolState(toolName) {
|
|
5227
|
+
if (isMaskeraVaultToolName(toolName)) {
|
|
5228
|
+
return { mode: "passthrough", toolName };
|
|
5229
|
+
}
|
|
5230
|
+
if (toolName === "execute") {
|
|
5231
|
+
return { mode: "buffering_execute", toolName, raw: "" };
|
|
5232
|
+
}
|
|
5233
|
+
return {
|
|
5234
|
+
mode: "streaming",
|
|
5235
|
+
toolName,
|
|
5236
|
+
restorer: new StreamingRestorer(map, { escapeForJsonString: true })
|
|
5237
|
+
};
|
|
5238
|
+
}
|
|
5239
|
+
function setToolName(descriptor, toolName) {
|
|
5240
|
+
const key = channelKey(descriptor);
|
|
5241
|
+
const existing = channels.get(key);
|
|
5242
|
+
if (existing?.category === "tool" && existing.state.toolName === toolName) {
|
|
5243
|
+
return;
|
|
5244
|
+
}
|
|
5245
|
+
channels.set(key, {
|
|
5246
|
+
category: "tool",
|
|
5247
|
+
descriptor,
|
|
5248
|
+
state: createToolState(toolName)
|
|
5249
|
+
});
|
|
5250
|
+
}
|
|
5251
|
+
function pushToolDelta(descriptor, delta) {
|
|
5252
|
+
const key = channelKey(descriptor);
|
|
5253
|
+
let entry = channels.get(key);
|
|
5254
|
+
if (entry?.category !== "tool") {
|
|
5255
|
+
entry = {
|
|
5256
|
+
category: "tool",
|
|
5257
|
+
descriptor,
|
|
5258
|
+
state: {
|
|
5259
|
+
mode: "streaming",
|
|
5260
|
+
toolName: null,
|
|
5261
|
+
restorer: new StreamingRestorer(map, { escapeForJsonString: true })
|
|
5262
|
+
}
|
|
5263
|
+
};
|
|
5264
|
+
channels.set(key, entry);
|
|
5265
|
+
}
|
|
5266
|
+
switch (entry.state.mode) {
|
|
5267
|
+
case "passthrough":
|
|
5268
|
+
return delta;
|
|
5269
|
+
case "buffering_execute":
|
|
5270
|
+
entry.state.raw += delta;
|
|
5271
|
+
return "";
|
|
5272
|
+
case "streaming":
|
|
5273
|
+
return entry.state.restorer.push(delta);
|
|
5274
|
+
case "closed":
|
|
5275
|
+
return delta;
|
|
5276
|
+
}
|
|
5277
|
+
}
|
|
5278
|
+
function flushToolState(state) {
|
|
5279
|
+
switch (state.mode) {
|
|
5280
|
+
case "passthrough":
|
|
5281
|
+
case "closed":
|
|
5282
|
+
return "";
|
|
5283
|
+
case "buffering_execute":
|
|
5284
|
+
if (!state.raw) return "";
|
|
5285
|
+
return shouldSkipToolArgRestore(state.toolName, state.raw) ? state.raw : restoreJsonEncodedText(state.raw, map);
|
|
5286
|
+
case "streaming":
|
|
5287
|
+
return state.restorer.flush();
|
|
5288
|
+
}
|
|
5289
|
+
}
|
|
5290
|
+
function closeTool(descriptor, retainNameUntilItemDone = false) {
|
|
5291
|
+
const key = channelKey(descriptor);
|
|
5292
|
+
const entry = channels.get(key);
|
|
5293
|
+
if (entry?.category !== "tool") return { tail: "", toolName: null };
|
|
5294
|
+
const toolName = entry.state.toolName;
|
|
5295
|
+
const tail = flushToolState(entry.state);
|
|
5296
|
+
if (retainNameUntilItemDone) {
|
|
5297
|
+
entry.state = { mode: "closed", toolName };
|
|
5298
|
+
} else {
|
|
5299
|
+
channels.delete(key);
|
|
5300
|
+
}
|
|
5301
|
+
return { tail, toolName };
|
|
5302
|
+
}
|
|
5303
|
+
function consumeToolName(descriptor) {
|
|
5304
|
+
const key = channelKey(descriptor);
|
|
5305
|
+
const entry = channels.get(key);
|
|
5306
|
+
if (entry?.category !== "tool") return null;
|
|
5307
|
+
const name = entry.state.toolName;
|
|
5308
|
+
channels.delete(key);
|
|
5309
|
+
return name;
|
|
5310
|
+
}
|
|
5311
|
+
function drainRemainingStreams() {
|
|
5312
|
+
const toolEvents = [];
|
|
5313
|
+
const streamEvents = [];
|
|
5314
|
+
for (const [key, entry] of [...channels.entries()]) {
|
|
5315
|
+
channels.delete(key);
|
|
5316
|
+
if (entry.category === "tool") {
|
|
5317
|
+
const tail = flushToolState(entry.state);
|
|
5318
|
+
if (tail) toolEvents.push(formatChannelEvent(entry.descriptor, tail));
|
|
5319
|
+
} else {
|
|
5320
|
+
const tail = entry.restorer.flush();
|
|
5321
|
+
if (tail) streamEvents.push(formatChannelEvent(entry.descriptor, tail));
|
|
5112
5322
|
}
|
|
5113
5323
|
}
|
|
5114
|
-
return
|
|
5324
|
+
return [...toolEvents, ...streamEvents];
|
|
5115
5325
|
}
|
|
5116
|
-
let sseBuffer = "";
|
|
5117
5326
|
function processEventBlock(block) {
|
|
5118
5327
|
const lines = block.split("\n");
|
|
5119
5328
|
const outLines = [];
|
|
@@ -5141,177 +5350,136 @@ data: ${JSON.stringify({
|
|
|
5141
5350
|
continue;
|
|
5142
5351
|
}
|
|
5143
5352
|
if (parsed.type === "content_block_start" && isPlainObject(parsed.content_block)) {
|
|
5144
|
-
const
|
|
5353
|
+
const index = typeof parsed.index === "number" ? parsed.index : 0;
|
|
5145
5354
|
if (parsed.content_block.type === "tool_use" && typeof parsed.content_block.name === "string") {
|
|
5146
|
-
|
|
5355
|
+
setToolName(
|
|
5356
|
+
{ protocol: "anthropic", kind: "tool_json", index },
|
|
5357
|
+
parsed.content_block.name
|
|
5358
|
+
);
|
|
5147
5359
|
}
|
|
5148
5360
|
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
5149
5361
|
continue;
|
|
5150
5362
|
}
|
|
5151
5363
|
if (parsed.type === "content_block_delta" && isPlainObject(parsed.delta)) {
|
|
5152
|
-
const
|
|
5364
|
+
const index = typeof parsed.index === "number" ? parsed.index : 0;
|
|
5153
5365
|
if (parsed.delta.type === "text_delta" && typeof parsed.delta.text === "string") {
|
|
5154
|
-
parsed.delta.text =
|
|
5366
|
+
parsed.delta.text = pushStream(
|
|
5367
|
+
{ protocol: "anthropic", kind: "text", index },
|
|
5368
|
+
parsed.delta.text
|
|
5369
|
+
);
|
|
5155
5370
|
} else if (parsed.delta.type === "thinking_delta" && typeof parsed.delta.thinking === "string") {
|
|
5156
|
-
parsed.delta.thinking =
|
|
5157
|
-
|
|
5371
|
+
parsed.delta.thinking = pushStream(
|
|
5372
|
+
{ protocol: "anthropic", kind: "thinking", index },
|
|
5373
|
+
parsed.delta.thinking,
|
|
5374
|
+
true
|
|
5158
5375
|
);
|
|
5159
5376
|
} else if (parsed.delta.type === "input_json_delta" && typeof parsed.delta.partial_json === "string") {
|
|
5160
|
-
|
|
5161
|
-
|
|
5162
|
-
|
|
5163
|
-
|
|
5164
|
-
parsed.delta.partial_json = "";
|
|
5165
|
-
} else {
|
|
5166
|
-
parsed.delta.partial_json = getStream(key, true).push(parsed.delta.partial_json);
|
|
5167
|
-
}
|
|
5377
|
+
parsed.delta.partial_json = pushToolDelta(
|
|
5378
|
+
{ protocol: "anthropic", kind: "tool_json", index },
|
|
5379
|
+
parsed.delta.partial_json
|
|
5380
|
+
);
|
|
5168
5381
|
}
|
|
5169
5382
|
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
5170
5383
|
continue;
|
|
5171
5384
|
}
|
|
5172
5385
|
if (parsed.type === "content_block_stop") {
|
|
5173
|
-
const
|
|
5174
|
-
const
|
|
5175
|
-
|
|
5176
|
-
|
|
5177
|
-
|
|
5178
|
-
|
|
5179
|
-
|
|
5180
|
-
|
|
5181
|
-
|
|
5182
|
-
|
|
5183
|
-
|
|
5184
|
-
}
|
|
5185
|
-
const
|
|
5186
|
-
if (
|
|
5187
|
-
extraEvents.push(
|
|
5188
|
-
`event: content_block_delta
|
|
5189
|
-
data: ${JSON.stringify({
|
|
5190
|
-
type: "content_block_delta",
|
|
5191
|
-
index: idx,
|
|
5192
|
-
delta: { type: "thinking_delta", thinking: thinkingTail }
|
|
5193
|
-
})}`
|
|
5194
|
-
);
|
|
5195
|
-
}
|
|
5196
|
-
const jsonKey = `anth_json:${idx}`;
|
|
5197
|
-
const jsonTail = flushBufferedToolArgs(jsonKey) || flushStream(jsonKey);
|
|
5198
|
-
toolNames.delete(jsonKey);
|
|
5199
|
-
if (jsonTail) {
|
|
5200
|
-
extraEvents.push(
|
|
5201
|
-
`event: content_block_delta
|
|
5202
|
-
data: ${JSON.stringify({
|
|
5203
|
-
type: "content_block_delta",
|
|
5204
|
-
index: idx,
|
|
5205
|
-
delta: { type: "input_json_delta", partial_json: jsonTail }
|
|
5206
|
-
})}`
|
|
5207
|
-
);
|
|
5208
|
-
}
|
|
5386
|
+
const index = typeof parsed.index === "number" ? parsed.index : 0;
|
|
5387
|
+
const textDesc = { protocol: "anthropic", kind: "text", index };
|
|
5388
|
+
const textTail = closeStream(textDesc);
|
|
5389
|
+
if (textTail) extraEvents.push(formatChannelEvent(textDesc, textTail));
|
|
5390
|
+
const thinkingDesc = {
|
|
5391
|
+
protocol: "anthropic",
|
|
5392
|
+
kind: "thinking",
|
|
5393
|
+
index
|
|
5394
|
+
};
|
|
5395
|
+
const thinkingTail = closeStream(thinkingDesc);
|
|
5396
|
+
if (thinkingTail) extraEvents.push(formatChannelEvent(thinkingDesc, thinkingTail));
|
|
5397
|
+
const toolDesc = { protocol: "anthropic", kind: "tool_json", index };
|
|
5398
|
+
const { tail: jsonTail } = closeTool(toolDesc);
|
|
5399
|
+
if (jsonTail) extraEvents.push(formatChannelEvent(toolDesc, jsonTail));
|
|
5209
5400
|
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
5210
5401
|
continue;
|
|
5211
5402
|
}
|
|
5212
5403
|
if (Array.isArray(parsed.choices)) {
|
|
5213
5404
|
for (const choice of parsed.choices) {
|
|
5214
5405
|
if (!isPlainObject(choice)) continue;
|
|
5215
|
-
const
|
|
5406
|
+
const choiceIndex = typeof choice.index === "number" ? choice.index : 0;
|
|
5216
5407
|
const delta = choice.delta;
|
|
5217
5408
|
if (isPlainObject(delta)) {
|
|
5218
5409
|
if (typeof delta.content === "string") {
|
|
5219
|
-
delta.content =
|
|
5410
|
+
delta.content = pushStream(
|
|
5411
|
+
{ protocol: "openai_chat", kind: "text", choiceIndex },
|
|
5412
|
+
delta.content
|
|
5413
|
+
);
|
|
5220
5414
|
}
|
|
5221
5415
|
if (typeof delta.reasoning_content === "string") {
|
|
5222
|
-
delta.reasoning_content =
|
|
5223
|
-
|
|
5224
|
-
|
|
5416
|
+
delta.reasoning_content = pushStream(
|
|
5417
|
+
{ protocol: "openai_chat", kind: "reasoning", choiceIndex },
|
|
5418
|
+
delta.reasoning_content,
|
|
5225
5419
|
true
|
|
5226
|
-
)
|
|
5420
|
+
);
|
|
5227
5421
|
}
|
|
5228
5422
|
if (typeof delta.reasoning === "string") {
|
|
5229
|
-
delta.reasoning =
|
|
5230
|
-
|
|
5423
|
+
delta.reasoning = pushStream(
|
|
5424
|
+
{ protocol: "openai_chat", kind: "reasoning_plain", choiceIndex },
|
|
5425
|
+
delta.reasoning,
|
|
5426
|
+
true
|
|
5231
5427
|
);
|
|
5232
5428
|
}
|
|
5233
5429
|
if (Array.isArray(delta.tool_calls)) {
|
|
5234
5430
|
for (const call of delta.tool_calls) {
|
|
5235
5431
|
if (!isPlainObject(call)) continue;
|
|
5236
|
-
const
|
|
5237
|
-
const
|
|
5432
|
+
const toolIndex = typeof call.index === "number" ? call.index : 0;
|
|
5433
|
+
const toolDesc = {
|
|
5434
|
+
protocol: "openai_chat",
|
|
5435
|
+
kind: "tool_args",
|
|
5436
|
+
choiceIndex,
|
|
5437
|
+
toolIndex
|
|
5438
|
+
};
|
|
5238
5439
|
if (isPlainObject(call.function)) {
|
|
5239
5440
|
if (typeof call.function.name === "string" && call.function.name) {
|
|
5240
|
-
|
|
5441
|
+
setToolName(toolDesc, call.function.name);
|
|
5241
5442
|
}
|
|
5242
5443
|
if (typeof call.function.arguments === "string") {
|
|
5243
|
-
|
|
5244
|
-
if (isMaskeraVaultToolName(name)) ; else if (name === "execute") {
|
|
5245
|
-
bufferedToolArgs.set(
|
|
5246
|
-
key,
|
|
5247
|
-
(bufferedToolArgs.get(key) ?? "") + call.function.arguments
|
|
5248
|
-
);
|
|
5249
|
-
call.function.arguments = "";
|
|
5250
|
-
} else {
|
|
5251
|
-
call.function.arguments = getStream(key, true).push(call.function.arguments);
|
|
5252
|
-
}
|
|
5444
|
+
call.function.arguments = pushToolDelta(toolDesc, call.function.arguments);
|
|
5253
5445
|
}
|
|
5254
5446
|
}
|
|
5255
5447
|
}
|
|
5256
5448
|
}
|
|
5257
5449
|
}
|
|
5258
5450
|
if (typeof choice.finish_reason === "string" && choice.finish_reason.length > 0) {
|
|
5259
|
-
const textTail =
|
|
5451
|
+
const textTail = closeStream({ protocol: "openai_chat", kind: "text", choiceIndex });
|
|
5260
5452
|
if (textTail) {
|
|
5261
5453
|
if (!isPlainObject(choice.delta)) choice.delta = {};
|
|
5262
5454
|
const d = choice.delta;
|
|
5263
5455
|
d.content = (typeof d.content === "string" ? d.content : "") + textTail;
|
|
5264
5456
|
}
|
|
5265
|
-
const reasoningTail =
|
|
5457
|
+
const reasoningTail = closeStream({
|
|
5458
|
+
protocol: "openai_chat",
|
|
5459
|
+
kind: "reasoning",
|
|
5460
|
+
choiceIndex
|
|
5461
|
+
});
|
|
5266
5462
|
if (reasoningTail) {
|
|
5267
5463
|
if (!isPlainObject(choice.delta)) choice.delta = {};
|
|
5268
5464
|
const d = choice.delta;
|
|
5269
5465
|
d.reasoning_content = (typeof d.reasoning_content === "string" ? d.reasoning_content : "") + reasoningTail;
|
|
5270
5466
|
}
|
|
5271
|
-
const reasoningPlainTail =
|
|
5467
|
+
const reasoningPlainTail = closeStream({
|
|
5468
|
+
protocol: "openai_chat",
|
|
5469
|
+
kind: "reasoning_plain",
|
|
5470
|
+
choiceIndex
|
|
5471
|
+
});
|
|
5272
5472
|
if (reasoningPlainTail) {
|
|
5273
5473
|
if (!isPlainObject(choice.delta)) choice.delta = {};
|
|
5274
5474
|
const d = choice.delta;
|
|
5275
5475
|
d.reasoning = (typeof d.reasoning === "string" ? d.reasoning : "") + reasoningPlainTail;
|
|
5276
5476
|
}
|
|
5277
|
-
const
|
|
5278
|
-
|
|
5279
|
-
|
|
5280
|
-
|
|
5281
|
-
|
|
5282
|
-
|
|
5283
|
-
if (!fullArgs) continue;
|
|
5284
|
-
extraEvents.push(
|
|
5285
|
-
`data: ${JSON.stringify({
|
|
5286
|
-
choices: [
|
|
5287
|
-
{
|
|
5288
|
-
index: cIdx,
|
|
5289
|
-
delta: {
|
|
5290
|
-
tool_calls: [{ index: tIdx, function: { arguments: fullArgs } }]
|
|
5291
|
-
}
|
|
5292
|
-
}
|
|
5293
|
-
]
|
|
5294
|
-
})}`
|
|
5295
|
-
);
|
|
5296
|
-
}
|
|
5297
|
-
for (const key of [...streams.keys()]) {
|
|
5298
|
-
if (!key.startsWith(toolPrefix)) continue;
|
|
5299
|
-
const tIdx = Number(key.slice(toolPrefix.length) || 0);
|
|
5300
|
-
const toolTail = flushStream(key);
|
|
5301
|
-
toolNames.delete(key);
|
|
5302
|
-
if (!toolTail) continue;
|
|
5303
|
-
extraEvents.push(
|
|
5304
|
-
`data: ${JSON.stringify({
|
|
5305
|
-
choices: [
|
|
5306
|
-
{
|
|
5307
|
-
index: cIdx,
|
|
5308
|
-
delta: {
|
|
5309
|
-
tool_calls: [{ index: tIdx, function: { arguments: toolTail } }]
|
|
5310
|
-
}
|
|
5311
|
-
}
|
|
5312
|
-
]
|
|
5313
|
-
})}`
|
|
5314
|
-
);
|
|
5477
|
+
for (const [key, entry] of [...channels.entries()]) {
|
|
5478
|
+
if (entry.category === "tool" && entry.descriptor.protocol === "openai_chat" && entry.descriptor.choiceIndex === choiceIndex) {
|
|
5479
|
+
channels.delete(key);
|
|
5480
|
+
const tail = flushToolState(entry.state);
|
|
5481
|
+
if (tail) extraEvents.push(formatChannelEvent(entry.descriptor, tail));
|
|
5482
|
+
}
|
|
5315
5483
|
}
|
|
5316
5484
|
}
|
|
5317
5485
|
}
|
|
@@ -5320,31 +5488,36 @@ data: ${JSON.stringify({
|
|
|
5320
5488
|
}
|
|
5321
5489
|
if (parsed.type === "response.output_item.added" && isPlainObject(parsed.item)) {
|
|
5322
5490
|
if (parsed.item.type === "function_call" && typeof parsed.item.name === "string") {
|
|
5323
|
-
|
|
5491
|
+
const outputIndex = typeof parsed.output_index === "number" ? parsed.output_index : 0;
|
|
5492
|
+
setToolName(
|
|
5493
|
+
{ protocol: "openai_responses", kind: "tool_args", outputIndex },
|
|
5494
|
+
parsed.item.name
|
|
5495
|
+
);
|
|
5324
5496
|
}
|
|
5325
5497
|
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
5326
5498
|
continue;
|
|
5327
5499
|
}
|
|
5328
5500
|
if (parsed.type === "response.output_text.delta" && typeof parsed.delta === "string") {
|
|
5329
|
-
const
|
|
5330
|
-
parsed.
|
|
5501
|
+
const outputIndex = typeof parsed.output_index === "number" ? parsed.output_index : 0;
|
|
5502
|
+
const contentIndex = typeof parsed.content_index === "number" ? parsed.content_index : 0;
|
|
5503
|
+
parsed.delta = pushStream(
|
|
5504
|
+
{ protocol: "openai_responses", kind: "text", outputIndex, contentIndex },
|
|
5505
|
+
parsed.delta
|
|
5506
|
+
);
|
|
5331
5507
|
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
5332
5508
|
continue;
|
|
5333
5509
|
}
|
|
5334
5510
|
if (parsed.type === "response.output_text.done") {
|
|
5335
|
-
const
|
|
5336
|
-
const
|
|
5337
|
-
|
|
5338
|
-
|
|
5339
|
-
|
|
5340
|
-
|
|
5341
|
-
|
|
5342
|
-
|
|
5343
|
-
|
|
5344
|
-
|
|
5345
|
-
})}`
|
|
5346
|
-
);
|
|
5347
|
-
}
|
|
5511
|
+
const outputIndex = typeof parsed.output_index === "number" ? parsed.output_index : 0;
|
|
5512
|
+
const contentIndex = typeof parsed.content_index === "number" ? parsed.content_index : 0;
|
|
5513
|
+
const desc = {
|
|
5514
|
+
protocol: "openai_responses",
|
|
5515
|
+
kind: "text",
|
|
5516
|
+
outputIndex,
|
|
5517
|
+
contentIndex
|
|
5518
|
+
};
|
|
5519
|
+
const tail = closeStream(desc);
|
|
5520
|
+
if (tail) extraEvents.push(formatChannelEvent(desc, tail));
|
|
5348
5521
|
if (typeof parsed.text === "string") {
|
|
5349
5522
|
parsed.text = restorePlainText(parsed.text, map);
|
|
5350
5523
|
}
|
|
@@ -5352,25 +5525,26 @@ data: ${JSON.stringify({
|
|
|
5352
5525
|
continue;
|
|
5353
5526
|
}
|
|
5354
5527
|
if (parsed.type === "response.reasoning_summary_text.delta" && typeof parsed.delta === "string") {
|
|
5355
|
-
const
|
|
5356
|
-
parsed.
|
|
5528
|
+
const outputIndex = typeof parsed.output_index === "number" ? parsed.output_index : 0;
|
|
5529
|
+
const summaryIndex = typeof parsed.summary_index === "number" ? parsed.summary_index : 0;
|
|
5530
|
+
parsed.delta = pushStream(
|
|
5531
|
+
{ protocol: "openai_responses", kind: "reasoning", outputIndex, summaryIndex },
|
|
5532
|
+
parsed.delta
|
|
5533
|
+
);
|
|
5357
5534
|
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
5358
5535
|
continue;
|
|
5359
5536
|
}
|
|
5360
5537
|
if (parsed.type === "response.reasoning_summary_text.done") {
|
|
5361
|
-
const
|
|
5362
|
-
const
|
|
5363
|
-
|
|
5364
|
-
|
|
5365
|
-
|
|
5366
|
-
|
|
5367
|
-
|
|
5368
|
-
|
|
5369
|
-
|
|
5370
|
-
|
|
5371
|
-
})}`
|
|
5372
|
-
);
|
|
5373
|
-
}
|
|
5538
|
+
const outputIndex = typeof parsed.output_index === "number" ? parsed.output_index : 0;
|
|
5539
|
+
const summaryIndex = typeof parsed.summary_index === "number" ? parsed.summary_index : 0;
|
|
5540
|
+
const desc = {
|
|
5541
|
+
protocol: "openai_responses",
|
|
5542
|
+
kind: "reasoning",
|
|
5543
|
+
outputIndex,
|
|
5544
|
+
summaryIndex
|
|
5545
|
+
};
|
|
5546
|
+
const tail = closeStream(desc);
|
|
5547
|
+
if (tail) extraEvents.push(formatChannelEvent(desc, tail));
|
|
5374
5548
|
if (typeof parsed.text === "string") {
|
|
5375
5549
|
parsed.text = restorePlainText(parsed.text, map);
|
|
5376
5550
|
}
|
|
@@ -5378,32 +5552,24 @@ data: ${JSON.stringify({
|
|
|
5378
5552
|
continue;
|
|
5379
5553
|
}
|
|
5380
5554
|
if (parsed.type === "response.function_call_arguments.delta" && typeof parsed.delta === "string") {
|
|
5381
|
-
const
|
|
5382
|
-
|
|
5383
|
-
|
|
5384
|
-
|
|
5385
|
-
|
|
5386
|
-
} else {
|
|
5387
|
-
parsed.delta = getStream(key, true).push(parsed.delta);
|
|
5388
|
-
}
|
|
5555
|
+
const outputIndex = typeof parsed.output_index === "number" ? parsed.output_index : 0;
|
|
5556
|
+
parsed.delta = pushToolDelta(
|
|
5557
|
+
{ protocol: "openai_responses", kind: "tool_args", outputIndex },
|
|
5558
|
+
parsed.delta
|
|
5559
|
+
);
|
|
5389
5560
|
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
5390
5561
|
continue;
|
|
5391
5562
|
}
|
|
5392
5563
|
if (parsed.type === "response.function_call_arguments.done") {
|
|
5393
|
-
const
|
|
5394
|
-
const
|
|
5395
|
-
|
|
5396
|
-
|
|
5397
|
-
|
|
5398
|
-
|
|
5399
|
-
|
|
5400
|
-
|
|
5401
|
-
|
|
5402
|
-
delta: tail
|
|
5403
|
-
})}`
|
|
5404
|
-
);
|
|
5405
|
-
}
|
|
5406
|
-
if (typeof parsed.arguments === "string" && !shouldSkipToolArgRestore(name, parsed.arguments)) {
|
|
5564
|
+
const outputIndex = typeof parsed.output_index === "number" ? parsed.output_index : 0;
|
|
5565
|
+
const desc = {
|
|
5566
|
+
protocol: "openai_responses",
|
|
5567
|
+
kind: "tool_args",
|
|
5568
|
+
outputIndex
|
|
5569
|
+
};
|
|
5570
|
+
const { tail, toolName } = closeTool(desc, true);
|
|
5571
|
+
if (tail) extraEvents.push(formatChannelEvent(desc, tail));
|
|
5572
|
+
if (typeof parsed.arguments === "string" && !shouldSkipToolArgRestore(toolName, parsed.arguments)) {
|
|
5407
5573
|
parsed.arguments = restoreJsonEncodedText(parsed.arguments, map);
|
|
5408
5574
|
}
|
|
5409
5575
|
outLines.push(`data: ${JSON.stringify(parsed)}`);
|
|
@@ -5423,9 +5589,13 @@ data: ${JSON.stringify({
|
|
|
5423
5589
|
}
|
|
5424
5590
|
if (parsed.type === "response.output_item.done" && isPlainObject(parsed.item)) {
|
|
5425
5591
|
const item = parsed.item;
|
|
5426
|
-
const
|
|
5427
|
-
const
|
|
5428
|
-
|
|
5592
|
+
const outputIndex = typeof parsed.output_index === "number" ? parsed.output_index : 0;
|
|
5593
|
+
const trackedName = consumeToolName({
|
|
5594
|
+
protocol: "openai_responses",
|
|
5595
|
+
kind: "tool_args",
|
|
5596
|
+
outputIndex
|
|
5597
|
+
});
|
|
5598
|
+
const name = typeof item.name === "string" ? item.name : trackedName;
|
|
5429
5599
|
if (typeof item.arguments === "string" && !shouldSkipToolArgRestore(name, item.arguments)) {
|
|
5430
5600
|
item.arguments = restoreJsonEncodedText(item.arguments, map);
|
|
5431
5601
|
}
|
|
@@ -5458,19 +5628,18 @@ data: ${JSON.stringify({
|
|
|
5458
5628
|
|
|
5459
5629
|
${joined}` : joined;
|
|
5460
5630
|
}
|
|
5461
|
-
let pendingCr = false;
|
|
5462
5631
|
return {
|
|
5463
5632
|
push(chunk) {
|
|
5464
|
-
let text = pendingCr ? `\r${chunk}` : chunk;
|
|
5465
|
-
pendingCr = text.endsWith("\r");
|
|
5466
|
-
if (pendingCr) text = text.slice(0, -1);
|
|
5467
|
-
|
|
5633
|
+
let text = frame.pendingCr ? `\r${chunk}` : chunk;
|
|
5634
|
+
frame.pendingCr = text.endsWith("\r");
|
|
5635
|
+
if (frame.pendingCr) text = text.slice(0, -1);
|
|
5636
|
+
frame.buffer += text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
5468
5637
|
let out = "";
|
|
5469
5638
|
for (; ; ) {
|
|
5470
|
-
const sep3 =
|
|
5639
|
+
const sep3 = frame.buffer.indexOf("\n\n");
|
|
5471
5640
|
if (sep3 < 0) break;
|
|
5472
|
-
const block =
|
|
5473
|
-
|
|
5641
|
+
const block = frame.buffer.slice(0, sep3);
|
|
5642
|
+
frame.buffer = frame.buffer.slice(sep3 + 2);
|
|
5474
5643
|
out += `${processEventBlock(block)}
|
|
5475
5644
|
|
|
5476
5645
|
`;
|
|
@@ -5478,14 +5647,14 @@ ${joined}` : joined;
|
|
|
5478
5647
|
return out;
|
|
5479
5648
|
},
|
|
5480
5649
|
flush() {
|
|
5481
|
-
if (pendingCr) {
|
|
5482
|
-
|
|
5483
|
-
pendingCr = false;
|
|
5650
|
+
if (frame.pendingCr) {
|
|
5651
|
+
frame.buffer += "\n";
|
|
5652
|
+
frame.pendingCr = false;
|
|
5484
5653
|
}
|
|
5485
5654
|
const parts = [];
|
|
5486
|
-
if (
|
|
5487
|
-
parts.push(processEventBlock(
|
|
5488
|
-
|
|
5655
|
+
if (frame.buffer) {
|
|
5656
|
+
parts.push(processEventBlock(frame.buffer));
|
|
5657
|
+
frame.buffer = "";
|
|
5489
5658
|
}
|
|
5490
5659
|
const drained = drainRemainingStreams();
|
|
5491
5660
|
if (drained.length > 0) {
|
|
@@ -5688,6 +5857,42 @@ function parseScopedMcpPolicy(urlPath, base) {
|
|
|
5688
5857
|
}
|
|
5689
5858
|
return { allowRawRestore, readOnly, approvalMode };
|
|
5690
5859
|
}
|
|
5860
|
+
var McpSessionStore = class {
|
|
5861
|
+
constructor(onDispose, options = {}) {
|
|
5862
|
+
this.active = /* @__PURE__ */ new Map();
|
|
5863
|
+
this.closed = /* @__PURE__ */ new Set();
|
|
5864
|
+
this.onDispose = onDispose;
|
|
5865
|
+
this.maxActive = options.maxActive ?? 200;
|
|
5866
|
+
this.maxClosed = options.maxClosed ?? 500;
|
|
5867
|
+
}
|
|
5868
|
+
open(policy) {
|
|
5869
|
+
const id = `mcp_${randomUUID().slice(0, 16)}`;
|
|
5870
|
+
if (this.active.size >= this.maxActive) {
|
|
5871
|
+
const oldest = this.active.keys().next().value;
|
|
5872
|
+
if (oldest !== void 0) {
|
|
5873
|
+
this.close(oldest);
|
|
5874
|
+
}
|
|
5875
|
+
}
|
|
5876
|
+
this.closed.delete(id);
|
|
5877
|
+
this.active.set(id, policy);
|
|
5878
|
+
return id;
|
|
5879
|
+
}
|
|
5880
|
+
lookup(id) {
|
|
5881
|
+
const policy = this.active.get(id);
|
|
5882
|
+
if (policy) return { status: "active", policy };
|
|
5883
|
+
if (this.closed.has(id)) return { status: "closed" };
|
|
5884
|
+
return { status: "unknown" };
|
|
5885
|
+
}
|
|
5886
|
+
close(id) {
|
|
5887
|
+
this.active.delete(id);
|
|
5888
|
+
this.closed.add(id);
|
|
5889
|
+
this.onDispose(id);
|
|
5890
|
+
if (this.closed.size > this.maxClosed) {
|
|
5891
|
+
const first = this.closed.values().next().value;
|
|
5892
|
+
if (first !== void 0) this.closed.delete(first);
|
|
5893
|
+
}
|
|
5894
|
+
}
|
|
5895
|
+
};
|
|
5691
5896
|
async function startMaskeraProxy(options = {}) {
|
|
5692
5897
|
const host = options.host ?? "127.0.0.1";
|
|
5693
5898
|
if (!options.allowNonLoopback && !isLoopbackBindHost(host)) {
|
|
@@ -5714,8 +5919,12 @@ async function startMaskeraProxy(options = {}) {
|
|
|
5714
5919
|
readOnly: options.readOnly ?? false,
|
|
5715
5920
|
approvalMode: options.approvalMode ?? "automatic"
|
|
5716
5921
|
};
|
|
5717
|
-
const
|
|
5718
|
-
|
|
5922
|
+
const mcpSessionStore = new McpSessionStore((sessionId) => {
|
|
5923
|
+
const owner = `mcp:${sessionId}`;
|
|
5924
|
+
vault.clearOwner(owner);
|
|
5925
|
+
approvals.clearOwner(owner);
|
|
5926
|
+
mcpServerInstance?.clearOwner(owner);
|
|
5927
|
+
});
|
|
5719
5928
|
const messageTokensBySession = /* @__PURE__ */ new Map();
|
|
5720
5929
|
const externalToolTokensBySession = /* @__PURE__ */ new Map();
|
|
5721
5930
|
if (auditLogPath) {
|
|
@@ -5897,6 +6106,7 @@ async function startMaskeraProxy(options = {}) {
|
|
|
5897
6106
|
}
|
|
5898
6107
|
vault.clearAll();
|
|
5899
6108
|
approvals.clearAll();
|
|
6109
|
+
mcpServerInstance?.clearAllOwners();
|
|
5900
6110
|
engine.clearCache();
|
|
5901
6111
|
inspector.clear();
|
|
5902
6112
|
messageTokensBySession.clear();
|
|
@@ -6047,14 +6257,7 @@ async function startMaskeraProxy(options = {}) {
|
|
|
6047
6257
|
const incomingSessionId = typeof req.headers["mcp-session-id"] === "string" ? req.headers["mcp-session-id"].trim() : "";
|
|
6048
6258
|
if (method === "DELETE") {
|
|
6049
6259
|
if (incomingSessionId) {
|
|
6050
|
-
|
|
6051
|
-
closedMcpSessions.add(incomingSessionId);
|
|
6052
|
-
vault.clearOwner(`mcp:${incomingSessionId}`);
|
|
6053
|
-
approvals.clearOwner(`mcp:${incomingSessionId}`);
|
|
6054
|
-
if (closedMcpSessions.size > 500) {
|
|
6055
|
-
const first = closedMcpSessions.values().next().value;
|
|
6056
|
-
if (first !== void 0) closedMcpSessions.delete(first);
|
|
6057
|
-
}
|
|
6260
|
+
mcpSessionStore.close(incomingSessionId);
|
|
6058
6261
|
}
|
|
6059
6262
|
res.writeHead(204, INSPECTOR_SECURITY_HEADERS);
|
|
6060
6263
|
res.end();
|
|
@@ -6082,7 +6285,8 @@ async function startMaskeraProxy(options = {}) {
|
|
|
6082
6285
|
res.end(JSON.stringify({ error: `Unsupported HTTP method ${method} for /mcp.` }));
|
|
6083
6286
|
return;
|
|
6084
6287
|
}
|
|
6085
|
-
|
|
6288
|
+
const incomingSessionState = incomingSessionId ? mcpSessionStore.lookup(incomingSessionId) : null;
|
|
6289
|
+
if (incomingSessionState?.status === "closed") {
|
|
6086
6290
|
res.writeHead(404, {
|
|
6087
6291
|
...INSPECTOR_SECURITY_HEADERS,
|
|
6088
6292
|
"content-type": "application/json; charset=utf-8"
|
|
@@ -6110,7 +6314,7 @@ async function startMaskeraProxy(options = {}) {
|
|
|
6110
6314
|
}
|
|
6111
6315
|
const messages = Array.isArray(parsedMcp) ? parsedMcp : [parsedMcp];
|
|
6112
6316
|
const isInit = messages.some((m) => isPlainObject(m) && m.method === "initialize");
|
|
6113
|
-
if (!isInit &&
|
|
6317
|
+
if (!isInit && incomingSessionState?.status === "unknown") {
|
|
6114
6318
|
res.writeHead(404, {
|
|
6115
6319
|
...INSPECTOR_SECURITY_HEADERS,
|
|
6116
6320
|
"content-type": "application/json; charset=utf-8"
|
|
@@ -6118,22 +6322,10 @@ async function startMaskeraProxy(options = {}) {
|
|
|
6118
6322
|
res.end(JSON.stringify({ error: "Unknown MCP session." }));
|
|
6119
6323
|
return;
|
|
6120
6324
|
}
|
|
6121
|
-
const sessionBasePolicy =
|
|
6325
|
+
const sessionBasePolicy = incomingSessionState?.status === "active" ? incomingSessionState.policy : baseMcpPolicy;
|
|
6122
6326
|
const effectivePolicy = parseScopedMcpPolicy(urlPath, sessionBasePolicy);
|
|
6123
6327
|
const mcpServer = getMcpServer();
|
|
6124
|
-
|
|
6125
|
-
if (isInit) {
|
|
6126
|
-
responseSessionId = `mcp_${randomUUID().slice(0, 16)}`;
|
|
6127
|
-
if (mcpSessions.size >= 200) {
|
|
6128
|
-
const oldest = mcpSessions.keys().next().value;
|
|
6129
|
-
if (oldest !== void 0) {
|
|
6130
|
-
mcpSessions.delete(oldest);
|
|
6131
|
-
vault.clearOwner(`mcp:${oldest}`);
|
|
6132
|
-
approvals.clearOwner(`mcp:${oldest}`);
|
|
6133
|
-
}
|
|
6134
|
-
}
|
|
6135
|
-
mcpSessions.set(responseSessionId, effectivePolicy);
|
|
6136
|
-
}
|
|
6328
|
+
const responseSessionId = isInit ? mcpSessionStore.open(effectivePolicy) : incomingSessionId;
|
|
6137
6329
|
const sessionOwner = responseSessionId ? `mcp:${responseSessionId}` : "mcp:stateless";
|
|
6138
6330
|
const scopedPolicy = { ...effectivePolicy, sessionOwner };
|
|
6139
6331
|
const responses = [];
|
|
@@ -6600,6 +6792,7 @@ ${body}`
|
|
|
6600
6792
|
const actualPort = typeof addr === "object" && addr ? addr.port : requestedPort;
|
|
6601
6793
|
boundPort = actualPort;
|
|
6602
6794
|
boundUrl = `http://${host}:${actualPort}`;
|
|
6795
|
+
let lifecycle = { phase: "listening" };
|
|
6603
6796
|
return {
|
|
6604
6797
|
host,
|
|
6605
6798
|
port: actualPort,
|
|
@@ -6617,12 +6810,22 @@ ${body}`
|
|
|
6617
6810
|
sessions: vault.list().length
|
|
6618
6811
|
}),
|
|
6619
6812
|
close: async () => {
|
|
6620
|
-
|
|
6621
|
-
|
|
6622
|
-
|
|
6623
|
-
|
|
6624
|
-
|
|
6625
|
-
|
|
6813
|
+
if (lifecycle.phase === "closed") return;
|
|
6814
|
+
if (lifecycle.phase === "closing") return lifecycle.promise;
|
|
6815
|
+
const closingPromise = (async () => {
|
|
6816
|
+
try {
|
|
6817
|
+
unsubscribeApprovals();
|
|
6818
|
+
inspector.closeAll();
|
|
6819
|
+
await new Promise((resolveClose, rejectClose) => {
|
|
6820
|
+
server.close((err) => err ? rejectClose(err) : resolveClose());
|
|
6821
|
+
});
|
|
6822
|
+
await auditChain;
|
|
6823
|
+
} finally {
|
|
6824
|
+
lifecycle = { phase: "closed" };
|
|
6825
|
+
}
|
|
6826
|
+
})();
|
|
6827
|
+
lifecycle = { phase: "closing", promise: closingPromise };
|
|
6828
|
+
return closingPromise;
|
|
6626
6829
|
}
|
|
6627
6830
|
};
|
|
6628
6831
|
}
|
|
@@ -6897,6 +7100,113 @@ async function runService(options) {
|
|
|
6897
7100
|
detail: running ? `Installed and started ${serviceName} (${serviceFile}). Listening on ${proxyUrl}.` : `Installed ${serviceName} (${serviceFile}). Check logs if ${proxyUrl} is still warming up.`
|
|
6898
7101
|
};
|
|
6899
7102
|
}
|
|
7103
|
+
|
|
7104
|
+
// src/stdio.ts
|
|
7105
|
+
function parseElicitationResponse(resp) {
|
|
7106
|
+
if (resp.error) return { action: "cancel" };
|
|
7107
|
+
const resultObj = resp.result && typeof resp.result === "object" ? resp.result : {};
|
|
7108
|
+
const action = resultObj.action === "accept" || resultObj.action === "decline" || resultObj.action === "cancel" ? resultObj.action : "cancel";
|
|
7109
|
+
const content = resultObj.content && typeof resultObj.content === "object" && !Array.isArray(resultObj.content) ? resultObj.content : void 0;
|
|
7110
|
+
return { action, content };
|
|
7111
|
+
}
|
|
7112
|
+
function createStdioMcpTransport(options) {
|
|
7113
|
+
let state = {
|
|
7114
|
+
phase: "open",
|
|
7115
|
+
nextServerReqId: 1,
|
|
7116
|
+
pending: /* @__PURE__ */ new Map()
|
|
7117
|
+
};
|
|
7118
|
+
let chain = Promise.resolve();
|
|
7119
|
+
return {
|
|
7120
|
+
get phase() {
|
|
7121
|
+
return state.phase;
|
|
7122
|
+
},
|
|
7123
|
+
requestElicitation(req) {
|
|
7124
|
+
if (state.phase === "closed") {
|
|
7125
|
+
return Promise.resolve({ action: "cancel" });
|
|
7126
|
+
}
|
|
7127
|
+
const id = `maskera_elicit_${state.nextServerReqId++}`;
|
|
7128
|
+
const pending = state.pending;
|
|
7129
|
+
return new Promise((resolveReq) => {
|
|
7130
|
+
pending.set(id, resolveReq);
|
|
7131
|
+
options.writeStdout(
|
|
7132
|
+
`${JSON.stringify({
|
|
7133
|
+
jsonrpc: "2.0",
|
|
7134
|
+
id,
|
|
7135
|
+
method: "elicitation/create",
|
|
7136
|
+
params: req
|
|
7137
|
+
})}
|
|
7138
|
+
`
|
|
7139
|
+
);
|
|
7140
|
+
});
|
|
7141
|
+
},
|
|
7142
|
+
handleLine(line, handleMessage) {
|
|
7143
|
+
if (state.phase === "closed") return;
|
|
7144
|
+
const trimmed = line.trim();
|
|
7145
|
+
if (!trimmed) return;
|
|
7146
|
+
let parsed;
|
|
7147
|
+
try {
|
|
7148
|
+
parsed = JSON.parse(trimmed);
|
|
7149
|
+
} catch {
|
|
7150
|
+
chain = chain.then(() => {
|
|
7151
|
+
options.writeStdout(
|
|
7152
|
+
`${JSON.stringify({
|
|
7153
|
+
jsonrpc: "2.0",
|
|
7154
|
+
id: null,
|
|
7155
|
+
error: { code: -32700, message: "Parse error" }
|
|
7156
|
+
})}
|
|
7157
|
+
`
|
|
7158
|
+
);
|
|
7159
|
+
});
|
|
7160
|
+
return;
|
|
7161
|
+
}
|
|
7162
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed) && !("method" in parsed) && typeof parsed.id === "string") {
|
|
7163
|
+
const resp = parsed;
|
|
7164
|
+
const resolvePending = state.pending.get(resp.id);
|
|
7165
|
+
if (resolvePending) {
|
|
7166
|
+
state.pending.delete(resp.id);
|
|
7167
|
+
resolvePending(parseElicitationResponse(resp));
|
|
7168
|
+
return;
|
|
7169
|
+
}
|
|
7170
|
+
}
|
|
7171
|
+
chain = chain.then(async () => {
|
|
7172
|
+
try {
|
|
7173
|
+
const response = await handleMessage(parsed);
|
|
7174
|
+
if (response) {
|
|
7175
|
+
options.writeStdout(`${JSON.stringify(response)}
|
|
7176
|
+
`);
|
|
7177
|
+
}
|
|
7178
|
+
} catch (err) {
|
|
7179
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
7180
|
+
options.writeStderr(`[maskera-mcp] internal error: ${message}
|
|
7181
|
+
`);
|
|
7182
|
+
const maybeId = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed.id : void 0;
|
|
7183
|
+
if (typeof maybeId === "string" || typeof maybeId === "number" || maybeId === null) {
|
|
7184
|
+
options.writeStdout(
|
|
7185
|
+
`${JSON.stringify({
|
|
7186
|
+
jsonrpc: "2.0",
|
|
7187
|
+
id: maybeId,
|
|
7188
|
+
error: { code: -32603, message: "Internal error" }
|
|
7189
|
+
})}
|
|
7190
|
+
`
|
|
7191
|
+
);
|
|
7192
|
+
}
|
|
7193
|
+
}
|
|
7194
|
+
});
|
|
7195
|
+
},
|
|
7196
|
+
close() {
|
|
7197
|
+
if (state.phase === "closed") return;
|
|
7198
|
+
const pendingResolvers = [...state.pending.values()];
|
|
7199
|
+
state.pending.clear();
|
|
7200
|
+
state = { phase: "closed" };
|
|
7201
|
+
for (const resolvePending of pendingResolvers) {
|
|
7202
|
+
resolvePending({ action: "cancel" });
|
|
7203
|
+
}
|
|
7204
|
+
},
|
|
7205
|
+
whenIdle() {
|
|
7206
|
+
return chain;
|
|
7207
|
+
}
|
|
7208
|
+
};
|
|
7209
|
+
}
|
|
6900
7210
|
function openUrlInBrowser(url, platform = process.platform) {
|
|
6901
7211
|
try {
|
|
6902
7212
|
let cmd;
|
|
@@ -6990,25 +7300,33 @@ async function runWrap(options) {
|
|
|
6990
7300
|
stdio: "inherit",
|
|
6991
7301
|
env: childEnv
|
|
6992
7302
|
});
|
|
6993
|
-
|
|
6994
|
-
|
|
6995
|
-
|
|
6996
|
-
|
|
6997
|
-
if (!child.killed) child.kill("SIGTERM");
|
|
7303
|
+
let childState = { phase: "running" };
|
|
7304
|
+
const forwardSignal = (sig) => {
|
|
7305
|
+
if (childState.phase !== "running") return;
|
|
7306
|
+
if (!child.killed) child.kill(sig);
|
|
6998
7307
|
};
|
|
7308
|
+
const forwardSigInt = () => forwardSignal("SIGINT");
|
|
7309
|
+
const forwardSigTerm = () => forwardSignal("SIGTERM");
|
|
6999
7310
|
process.on("SIGINT", forwardSigInt);
|
|
7000
7311
|
process.on("SIGTERM", forwardSigTerm);
|
|
7001
7312
|
const { exitCode, signal } = await new Promise((resolveExit, rejectExit) => {
|
|
7002
|
-
|
|
7313
|
+
const cleanupSignals = () => {
|
|
7314
|
+
process.off("SIGINT", forwardSigInt);
|
|
7315
|
+
process.off("SIGTERM", forwardSigTerm);
|
|
7316
|
+
};
|
|
7317
|
+
child.on("error", (err) => {
|
|
7318
|
+
if (childState.phase !== "running") return;
|
|
7319
|
+
childState = { phase: "failed", error: err };
|
|
7320
|
+
cleanupSignals();
|
|
7321
|
+
rejectExit(err);
|
|
7322
|
+
});
|
|
7003
7323
|
child.on("exit", (code, sig) => {
|
|
7004
|
-
|
|
7005
|
-
|
|
7006
|
-
|
|
7007
|
-
|
|
7324
|
+
if (childState.phase !== "running") return;
|
|
7325
|
+
const resolvedCode = code ?? (sig ? 1 : 0);
|
|
7326
|
+
childState = { phase: "exited", exitCode: resolvedCode, signal: sig };
|
|
7327
|
+
cleanupSignals();
|
|
7328
|
+
resolveExit({ exitCode: resolvedCode, signal: sig });
|
|
7008
7329
|
});
|
|
7009
|
-
}).finally(() => {
|
|
7010
|
-
process.off("SIGINT", forwardSigInt);
|
|
7011
|
-
process.off("SIGTERM", forwardSigTerm);
|
|
7012
7330
|
});
|
|
7013
7331
|
const session = running.stats();
|
|
7014
7332
|
let receiptSavedPath;
|
|
@@ -7045,6 +7363,6 @@ async function runWrap(options) {
|
|
|
7045
7363
|
}
|
|
7046
7364
|
}
|
|
7047
7365
|
|
|
7048
|
-
export { ApprovalBroker, LAUNCHD_LABEL, MASKERA_PROMPTS, MASKERA_SKILL_MARKDOWN, MASKERA_SKILL_URI, MASKERA_STATUS_URI, ProxyInspector, SERVER_NAME, SERVER_VERSION, SUPPORTED_CLIENTS, SYSTEMD_UNIT, SessionVault, StreamingRestorer, buildCustomTermsDetector, createFileGuard, createMaskeraEngine, createMaskeraMcpServer, createModelProgressLogger, createSseRestorer, deriveProxySessionId, detectInstalledClients, extractGuardText, formatDoctorReport, isInstallClient, isLikelyEnglishSystemPrompt, normalizeMixedScriptHomoglyphs, openUrlInBrowser, redactLlmRequestBody, renderInspectorHtml, renderLaunchdPlist, renderMaskeraPrompt, renderSystemdUnit, restoreLlmResponseBody, runDoctor, runGuard, runGuardViaWarmProxy, runInstall, runService, runWrap, startMaskeraProxy, writeDoctorReceipt };
|
|
7366
|
+
export { ApprovalBroker, LAUNCHD_LABEL, MASKERA_PROMPTS, MASKERA_SKILL_MARKDOWN, MASKERA_SKILL_URI, MASKERA_STATUS_URI, ProxyInspector, SERVER_NAME, SERVER_VERSION, SUPPORTED_CLIENTS, SYSTEMD_UNIT, SessionVault, StreamingRestorer, buildCustomTermsDetector, createFileGuard, createMaskeraEngine, createMaskeraMcpServer, createModelProgressLogger, createSseRestorer, createStdioMcpTransport, deriveProxySessionId, detectInstalledClients, extractGuardText, formatDoctorReport, isInstallClient, isLikelyEnglishSystemPrompt, normalizeMixedScriptHomoglyphs, openUrlInBrowser, redactLlmRequestBody, renderInspectorHtml, renderLaunchdPlist, renderMaskeraPrompt, renderSystemdUnit, restoreLlmResponseBody, runDoctor, runGuard, runGuardViaWarmProxy, runInstall, runService, runWrap, startMaskeraProxy, writeDoctorReceipt };
|
|
7049
7367
|
//# sourceMappingURL=index.js.map
|
|
7050
7368
|
//# sourceMappingURL=index.js.map
|