@maskera/mcp 0.4.7 → 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 CHANGED
@@ -3,7 +3,7 @@ import { readFile, unlink, mkdir, writeFile, stat, access, appendFile, realpath,
3
3
  import { delimiter, join, dirname, resolve, isAbsolute, relative, sep, posix, extname } from 'path';
4
4
  import { createInterface } from 'readline';
5
5
  import { format } from 'util';
6
- import { constants } from 'fs';
6
+ import { constants, existsSync } from 'fs';
7
7
  import { createRequire } from 'module';
8
8
  import { MASKERA_SV_NER_MODEL, MASKERA_SV_NER_REVISION, redactFromDetections, hybridDefaultDetectors, canonicalize, runDetectors, clinicalPrecisionFilter, redact, redactWithNer, restore, createNerRecognizer } from 'maskera';
9
9
  import { randomUUID, createHash } from 'crypto';
@@ -87,6 +87,7 @@ function normalizeMixedScriptHomoglyphs(text) {
87
87
  });
88
88
  return { text: normalized, changed };
89
89
  }
90
+ var COMPOUND_WINDOW_RADIUS = 120;
90
91
  async function detectHyphenatedCompoundPrefixes(text, ner, detectors, profile, existing) {
91
92
  const candidates = [];
92
93
  SWEDISH_HYPHEN_COMPOUND_RE.lastIndex = 0;
@@ -101,28 +102,47 @@ async function detectHyphenatedCompoundPrefixes(text, ner, detectors, profile, e
101
102
  }
102
103
  }
103
104
  if (candidates.length === 0) return [];
104
- const chars = text.split("");
105
+ const windows = [];
105
106
  for (const c of candidates) {
106
- chars[c.hyphenIndex] = " ";
107
+ let winStart = Math.max(0, c.prefixStart - COMPOUND_WINDOW_RADIUS);
108
+ while (winStart > 0 && WORD_CHAR.test(text[winStart - 1] ?? "")) winStart--;
109
+ let winEnd = Math.min(text.length, c.hyphenIndex + 1 + COMPOUND_WINDOW_RADIUS);
110
+ while (winEnd < text.length && WORD_CHAR.test(text[winEnd] ?? "")) winEnd++;
111
+ const prev = windows[windows.length - 1];
112
+ if (prev && winStart <= prev.end + 40) {
113
+ prev.end = Math.max(prev.end, winEnd);
114
+ prev.items.push(c);
115
+ } else {
116
+ windows.push({ start: winStart, end: winEnd, items: [c] });
117
+ }
107
118
  }
108
- const probeText = chars.join("");
109
- const probeRes = await redactWithNer(probeText, {
110
- recognizer: ner,
111
- detectors: [...detectors],
112
- profile
113
- });
114
119
  const extra = [];
115
- for (const r of probeRes.redactions) {
116
- if (!COMPOUND_NER_LABELS.has(r.label)) continue;
117
- for (const c of candidates) {
118
- if (r.start <= c.prefixStart && r.end >= c.prefixEnd && r.end <= c.hyphenIndex) {
119
- extra.push({
120
- start: c.prefixStart,
121
- end: c.prefixEnd,
122
- label: r.label,
123
- value: text.slice(c.prefixStart, c.prefixEnd)
124
- });
125
- break;
120
+ for (const win of windows) {
121
+ const slice = text.slice(win.start, win.end);
122
+ const chars = slice.split("");
123
+ for (const c of win.items) {
124
+ chars[c.hyphenIndex - win.start] = " ";
125
+ }
126
+ const probeText = chars.join("");
127
+ const probeRes = await redactWithNer(probeText, {
128
+ recognizer: ner,
129
+ detectors: [...detectors],
130
+ profile
131
+ });
132
+ for (const r of probeRes.redactions) {
133
+ if (!COMPOUND_NER_LABELS.has(r.label)) continue;
134
+ const absStart = win.start + r.start;
135
+ const absEnd = win.start + r.end;
136
+ for (const c of win.items) {
137
+ if (absStart <= c.prefixStart && absEnd >= c.prefixEnd && absEnd <= c.hyphenIndex) {
138
+ extra.push({
139
+ start: c.prefixStart,
140
+ end: c.prefixEnd,
141
+ label: r.label,
142
+ value: text.slice(c.prefixStart, c.prefixEnd)
143
+ });
144
+ break;
145
+ }
126
146
  }
127
147
  }
128
148
  }
@@ -178,47 +198,54 @@ function createMaskeraEngine(options = {}) {
178
198
  const model = options.nerOptions?.model ?? MASKERA_SV_NER_MODEL;
179
199
  const revision = options.nerOptions?.revision ?? (model === MASKERA_SV_NER_MODEL ? MASKERA_SV_NER_REVISION : void 0);
180
200
  const maxCacheEntries = Math.max(0, options.maxCacheEntries ?? DEFAULT_MAX_CACHE_ENTRIES);
181
- let recognizer = options.recognizer ?? null;
182
- let nerLoaded = false;
183
- let nerError = null;
184
- let warmupStarted = false;
201
+ const localPath = options.nerOptions?.localModelPath;
202
+ const hasLocalQ8 = typeof localPath === "string" && existsSync(join(localPath, model, "onnx", "model_quantized.onnx"));
203
+ const dtype = options.nerOptions?.dtype ?? (localPath && !hasLocalQ8 ? "q4" : "q8");
204
+ let lifecycle = { phase: "idle", recognizer: options.recognizer ?? null };
205
+ let loadAttempt = 0;
185
206
  const spanCache = /* @__PURE__ */ new Map();
186
207
  const customDetectorCache = /* @__PURE__ */ new Map();
187
208
  let cacheHits = 0;
188
209
  let cacheMisses = 0;
189
- function getRecognizer() {
190
- if (!recognizer) {
191
- const dtype = options.nerOptions?.dtype ?? (options.nerOptions?.localModelPath ? "q4" : "q8");
192
- const loadStartedAt = Date.now();
193
- options.onModelStatus?.({ phase: "loading", model, dtype });
194
- recognizer = createNerRecognizer({
195
- ...options.nerOptions,
196
- model,
197
- revision,
198
- dtype
199
- });
200
- void recognizer.ready.then(
201
- () => {
202
- nerLoaded = true;
203
- nerError = null;
210
+ function ensureRecognizerLoading() {
211
+ if (lifecycle.phase === "loading" || lifecycle.phase === "ready") {
212
+ return lifecycle.recognizer;
213
+ }
214
+ const recognizer = lifecycle.recognizer ?? createNerRecognizer({
215
+ ...options.nerOptions,
216
+ model,
217
+ revision,
218
+ dtype
219
+ });
220
+ loadAttempt += 1;
221
+ const attempt = loadAttempt;
222
+ const startedAt = Date.now();
223
+ lifecycle = { phase: "loading", recognizer, startedAt, attempt };
224
+ options.onModelStatus?.({ phase: "loading", model, dtype });
225
+ void recognizer.ready.then(
226
+ () => {
227
+ if (lifecycle.phase === "loading" && lifecycle.attempt === attempt) {
228
+ lifecycle = { phase: "ready", recognizer };
204
229
  options.onModelStatus?.({
205
230
  phase: "ready",
206
231
  model,
207
- elapsedMs: Date.now() - loadStartedAt
232
+ elapsedMs: Date.now() - startedAt
208
233
  });
209
- },
210
- (err) => {
211
- const message = err instanceof Error ? err.message : String(err);
212
- nerError = message;
234
+ }
235
+ },
236
+ (err) => {
237
+ const message = err instanceof Error ? err.message : String(err);
238
+ if (lifecycle.phase === "loading" && lifecycle.attempt === attempt) {
239
+ lifecycle = { phase: "failed", recognizer, error: message };
213
240
  options.onModelStatus?.({
214
241
  phase: "error",
215
242
  model,
216
- elapsedMs: Date.now() - loadStartedAt,
243
+ elapsedMs: Date.now() - startedAt,
217
244
  error: message
218
245
  });
219
246
  }
220
- );
221
- }
247
+ }
248
+ );
222
249
  return recognizer;
223
250
  }
224
251
  function getCustomDetector(rawTerms) {
@@ -245,19 +272,9 @@ function createMaskeraEngine(options = {}) {
245
272
  }
246
273
  return {
247
274
  warmup() {
248
- if (defaultMode !== "auto" || warmupStarted || nerLoaded) return;
249
- warmupStarted = true;
250
- const ner = getRecognizer();
251
- void ner.ready.then(
252
- () => {
253
- nerLoaded = true;
254
- nerError = null;
255
- },
256
- (err) => {
257
- warmupStarted = false;
258
- nerError = err instanceof Error ? err.message : String(err);
259
- }
260
- );
275
+ if (defaultMode !== "auto") return;
276
+ if (lifecycle.phase === "loading" || lifecycle.phase === "ready") return;
277
+ ensureRecognizerLoading();
261
278
  },
262
279
  clearCache() {
263
280
  spanCache.clear();
@@ -330,8 +347,8 @@ function createMaskeraEngine(options = {}) {
330
347
  modeUsed: "rules"
331
348
  };
332
349
  }
350
+ const ner = ensureRecognizerLoading();
333
351
  try {
334
- const ner = getRecognizer();
335
352
  const canonical = canonicalize(text);
336
353
  const homoglyph = normalizeMixedScriptHomoglyphs(canonical.text);
337
354
  const isIdentity = canonical.identity && !homoglyph.changed;
@@ -362,8 +379,13 @@ function createMaskeraEngine(options = {}) {
362
379
  return end > start ? [{ start, end, label: d.label, value: text.slice(start, end) }] : [];
363
380
  })
364
381
  );
365
- nerLoaded = true;
366
- nerError = null;
382
+ if (lifecycle.phase === "loading") {
383
+ const elapsedMs = Date.now() - lifecycle.startedAt;
384
+ lifecycle = { phase: "ready", recognizer: ner };
385
+ options.onModelStatus?.({ phase: "ready", model, elapsedMs });
386
+ } else if (lifecycle.phase !== "ready") {
387
+ lifecycle = { phase: "ready", recognizer: ner };
388
+ }
367
389
  if (cacheKey) {
368
390
  if (spanCache.size >= maxCacheEntries) {
369
391
  const oldest = spanCache.keys().next().value;
@@ -381,7 +403,13 @@ function createMaskeraEngine(options = {}) {
381
403
  return { result, modeUsed: "hybrid" };
382
404
  } catch (err) {
383
405
  const message = err instanceof Error ? err.message : String(err);
384
- nerError = message;
406
+ if (lifecycle.phase === "loading") {
407
+ const elapsedMs = Date.now() - lifecycle.startedAt;
408
+ lifecycle = { phase: "failed", recognizer: ner, error: message };
409
+ options.onModelStatus?.({ phase: "error", model, elapsedMs, error: message });
410
+ } else {
411
+ lifecycle = { phase: "failed", recognizer: ner, error: message };
412
+ }
385
413
  throw new Error(
386
414
  `Hybrid NER failed to run (${message}). Pass mode="rules" explicitly if you only want deterministic structured redaction.`
387
415
  );
@@ -392,8 +420,9 @@ function createMaskeraEngine(options = {}) {
392
420
  defaultMode,
393
421
  model,
394
422
  revision: revision ?? "local",
395
- nerLoaded,
396
- nerError,
423
+ nerPhase: lifecycle.phase,
424
+ nerLoaded: lifecycle.phase === "ready",
425
+ nerError: lifecycle.phase === "failed" ? lifecycle.error : null,
397
426
  cacheSize: spanCache.size,
398
427
  cacheHits,
399
428
  cacheMisses
@@ -408,31 +437,39 @@ function downloadSize(dtype) {
408
437
  }
409
438
  function createModelProgressLogger(write = (line) => process.stderr.write(`${line}
410
439
  `), delayMs = 350) {
411
- let timer = null;
412
- let announcedLoading = false;
440
+ let state = { tag: "quiet" };
413
441
  return (event) => {
414
- if (event.phase === "loading") {
415
- if (timer) clearTimeout(timer);
416
- announcedLoading = false;
417
- timer = setTimeout(() => {
418
- announcedLoading = true;
419
- write(
420
- `[maskera] Loading Swedish ONNX model (${event.model}${downloadSize(event.dtype)}, cached locally)...`
421
- );
422
- }, delayMs);
423
- timer.unref?.();
424
- return;
425
- }
426
- if (timer) {
427
- clearTimeout(timer);
428
- timer = null;
429
- }
430
- if (event.phase === "ready" && announcedLoading) {
431
- write(`[maskera] Swedish ONNX model ready (${event.elapsedMs ?? 0}ms).`);
432
- announcedLoading = false;
433
- } else if (event.phase === "error" && announcedLoading) {
434
- write(`[maskera] Swedish ONNX model load failed: ${event.error ?? "unknown error"}`);
435
- announcedLoading = false;
442
+ switch (event.phase) {
443
+ case "loading": {
444
+ if (state.tag === "delayed") clearTimeout(state.timer);
445
+ const timer = setTimeout(() => {
446
+ state = { tag: "announced" };
447
+ write(
448
+ `[maskera] Loading Swedish ONNX model (${event.model}${downloadSize(event.dtype)}, cached locally)...`
449
+ );
450
+ }, delayMs);
451
+ timer.unref?.();
452
+ state = { tag: "delayed", timer };
453
+ return;
454
+ }
455
+ case "ready": {
456
+ if (state.tag === "delayed") {
457
+ clearTimeout(state.timer);
458
+ } else if (state.tag === "announced") {
459
+ write(`[maskera] Swedish ONNX model ready (${event.elapsedMs ?? 0}ms).`);
460
+ }
461
+ state = { tag: "quiet" };
462
+ return;
463
+ }
464
+ case "error": {
465
+ if (state.tag === "delayed") {
466
+ clearTimeout(state.timer);
467
+ } else if (state.tag === "announced") {
468
+ write(`[maskera] Swedish ONNX model load failed: ${event.error ?? "unknown error"}`);
469
+ }
470
+ state = { tag: "quiet" };
471
+ return;
472
+ }
436
473
  }
437
474
  };
438
475
  }
@@ -1698,6 +1735,7 @@ function enforceSessionSecretsRedacted(text, sessionMap) {
1698
1735
  }
1699
1736
  return { text: out, extraRedactions };
1700
1737
  }
1738
+ var MAX_CLIENT_SESSIONS = 500;
1701
1739
  function createMaskeraMcpServer(options = {}) {
1702
1740
  const engine = options.engine ?? createMaskeraEngine();
1703
1741
  const vault = options.vault ?? new SessionVault();
@@ -1708,8 +1746,24 @@ function createMaskeraMcpServer(options = {}) {
1708
1746
  const approvalBaseUrl = options.approvalBaseUrl;
1709
1747
  const requestElicitation = options.requestElicitation;
1710
1748
  const onToolCall = options.onToolCall;
1711
- let clientSupportsElicitation = false;
1749
+ const clientSessions = /* @__PURE__ */ new Map();
1712
1750
  const ownerPathAliases = /* @__PURE__ */ new Map();
1751
+ function getClientHandshake(owner) {
1752
+ return clientSessions.get(owner) ?? { status: "uninitialized" };
1753
+ }
1754
+ function setClientInitialized(owner, protocolVersion, supportsElicitation) {
1755
+ if (clientSessions.has(owner)) {
1756
+ clientSessions.delete(owner);
1757
+ } else if (clientSessions.size >= MAX_CLIENT_SESSIONS) {
1758
+ const oldest = clientSessions.keys().next().value;
1759
+ if (oldest !== void 0) clientSessions.delete(oldest);
1760
+ }
1761
+ clientSessions.set(owner, {
1762
+ status: "initialized",
1763
+ protocolVersion,
1764
+ supportsElicitation
1765
+ });
1766
+ }
1713
1767
  function getPathAliasBucket(owner) {
1714
1768
  let bucket = ownerPathAliases.get(owner);
1715
1769
  if (!bucket) {
@@ -1900,7 +1954,8 @@ function createMaskeraMcpServer(options = {}) {
1900
1954
  return toolOk(await input.execute());
1901
1955
  }
1902
1956
  if (policy.approvalMode === "native") {
1903
- if (!requestElicitation || !clientSupportsElicitation) {
1957
+ const handshake = getClientHandshake(policy.sessionOwner);
1958
+ if (!requestElicitation || handshake.status !== "initialized" || !handshake.supportsElicitation) {
1904
1959
  return toolError(
1905
1960
  `Approval mode "native" requires an MCP client with elicitation support. Reconnect with approval_mode=browser or write restored output directly via maskera_write_file.`
1906
1961
  );
@@ -2065,6 +2120,9 @@ function createMaskeraMcpServer(options = {}) {
2065
2120
  if (resumed.status === "not_found") {
2066
2121
  return finish(toolError(`Unknown approval request_id "${requestId}".`));
2067
2122
  }
2123
+ if (resumed.status === "failed") {
2124
+ return finish(toolError(`Approval request "${requestId}" failed: ${resumed.error}`));
2125
+ }
2068
2126
  if (resumed.status === "completed") {
2069
2127
  return finish(
2070
2128
  toolOk({
@@ -2291,6 +2349,17 @@ function createMaskeraMcpServer(options = {}) {
2291
2349
  }
2292
2350
  return {
2293
2351
  vault,
2352
+ getClientState(owner) {
2353
+ return getClientHandshake(owner ?? options.sessionOwner ?? "default");
2354
+ },
2355
+ clearOwner(owner) {
2356
+ clientSessions.delete(owner);
2357
+ ownerPathAliases.delete(owner);
2358
+ },
2359
+ clearAllOwners() {
2360
+ clientSessions.clear();
2361
+ ownerPathAliases.clear();
2362
+ },
2294
2363
  async handleMessage(raw, policyOverride) {
2295
2364
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
2296
2365
  return {
@@ -2317,9 +2386,10 @@ function createMaskeraMcpServer(options = {}) {
2317
2386
  if (req.method === "initialize") {
2318
2387
  const params = asObject(req.params);
2319
2388
  const clientCaps = asObject(params.capabilities);
2320
- clientSupportsElicitation = Boolean("elicitation" in clientCaps && clientCaps.elicitation);
2389
+ const supportsElicitation = Boolean("elicitation" in clientCaps && clientCaps.elicitation);
2321
2390
  const requested = typeof params.protocolVersion === "string" ? params.protocolVersion : void 0;
2322
2391
  const protocolVersion = requested && SUPPORTED_PROTOCOLS.includes(requested) ? requested : SUPPORTED_PROTOCOLS[0];
2392
+ setClientInitialized(policy.sessionOwner, protocolVersion, supportsElicitation);
2323
2393
  return {
2324
2394
  jsonrpc: "2.0",
2325
2395
  id,
@@ -3283,6 +3353,22 @@ function normalizeOwner2(owner) {
3283
3353
  const trimmed = owner?.trim();
3284
3354
  return trimmed || DEFAULT_OWNER2;
3285
3355
  }
3356
+ function toSummary(record) {
3357
+ const { state } = record;
3358
+ const decidedAt = state.status === "pending" ? null : state.decidedAt;
3359
+ const base = {
3360
+ id: record.id,
3361
+ tool: record.tool,
3362
+ reason: record.reason,
3363
+ sessionId: record.sessionId,
3364
+ placeholderCount: record.placeholderCount,
3365
+ status: state.status,
3366
+ createdAt: record.createdAt,
3367
+ expiresAt: record.expiresAt,
3368
+ decidedAt
3369
+ };
3370
+ return state.status === "failed" ? { ...base, error: state.error } : base;
3371
+ }
3286
3372
  var ApprovalBroker = class {
3287
3373
  constructor(ttlMs = DEFAULT_TTL_MS) {
3288
3374
  this.records = /* @__PURE__ */ new Map();
@@ -3292,9 +3378,9 @@ var ApprovalBroker = class {
3292
3378
  expireStale(now = Date.now()) {
3293
3379
  let changed = false;
3294
3380
  for (const record of this.records.values()) {
3295
- if (record.summary.status === "pending" && now >= record.expiresAtMs) {
3296
- record.summary.status = "expired";
3297
- record.execute = null;
3381
+ if ((record.state.status === "pending" || record.state.status === "approved") && now >= record.state.expiresAtMs) {
3382
+ const decidedAt = record.state.status === "approved" ? record.state.decidedAt : null;
3383
+ record.state = { status: "expired", decidedAt };
3298
3384
  changed = true;
3299
3385
  }
3300
3386
  }
@@ -3323,70 +3409,93 @@ var ApprovalBroker = class {
3323
3409
  }
3324
3410
  const now = Date.now();
3325
3411
  const id = `apr_${randomUUID().slice(0, 12)}`;
3326
- const summary = {
3412
+ const expiresAtMs = now + this.ttlMs;
3413
+ const record = {
3327
3414
  id,
3415
+ owner: normalizeOwner2(input.owner),
3328
3416
  tool: input.tool,
3329
3417
  reason: input.reason,
3330
3418
  sessionId: input.sessionId ?? null,
3331
3419
  placeholderCount: input.placeholderCount,
3332
- status: "pending",
3333
3420
  createdAt: new Date(now).toISOString(),
3334
- expiresAt: new Date(now + this.ttlMs).toISOString(),
3335
- decidedAt: null
3421
+ expiresAt: new Date(expiresAtMs).toISOString(),
3422
+ state: {
3423
+ status: "pending",
3424
+ expiresAtMs,
3425
+ execute: input.execute
3426
+ }
3336
3427
  };
3337
- this.records.set(id, {
3338
- owner: normalizeOwner2(input.owner),
3339
- summary,
3340
- expiresAtMs: now + this.ttlMs,
3341
- execute: input.execute
3342
- });
3428
+ this.records.set(id, record);
3343
3429
  this.notify();
3344
- return { ...summary };
3430
+ return toSummary(record);
3345
3431
  }
3346
3432
  list() {
3347
3433
  this.expireStale();
3348
- return [...this.records.values()].map((r) => ({ ...r.summary })).reverse();
3434
+ return [...this.records.values()].map(toSummary).reverse();
3349
3435
  }
3350
3436
  decide(id, decision) {
3351
3437
  this.expireStale();
3352
3438
  const record = this.records.get(id.trim());
3353
3439
  if (!record) return null;
3354
- if (record.summary.status !== "pending") return { ...record.summary };
3355
- record.summary.status = decision === "approve" ? "approved" : "declined";
3356
- record.summary.decidedAt = (/* @__PURE__ */ new Date()).toISOString();
3357
- if (decision === "decline") {
3358
- record.execute = null;
3440
+ if (record.state.status !== "pending") return toSummary(record);
3441
+ const decidedAt = (/* @__PURE__ */ new Date()).toISOString();
3442
+ if (decision === "approve") {
3443
+ record.state = {
3444
+ status: "approved",
3445
+ expiresAtMs: record.state.expiresAtMs,
3446
+ decidedAt,
3447
+ execute: record.state.execute
3448
+ };
3449
+ } else {
3450
+ record.state = { status: "declined", decidedAt };
3359
3451
  }
3360
3452
  this.notify();
3361
- return { ...record.summary };
3453
+ return toSummary(record);
3362
3454
  }
3363
3455
  async resume(id, owner) {
3364
3456
  this.expireStale();
3365
- const record = this.records.get(id.trim());
3457
+ const key = id.trim();
3458
+ const record = this.records.get(key);
3366
3459
  if (!record) return { status: "not_found" };
3367
3460
  if (owner !== void 0 && record.owner !== normalizeOwner2(owner)) {
3368
3461
  return { status: "not_found" };
3369
3462
  }
3370
- const { status } = record.summary;
3371
- if (status === "pending" || status === "declined" || status === "expired") {
3372
- return { status, summary: { ...record.summary } };
3373
- }
3374
- if (status === "completed" || !record.execute) {
3375
- return { status: "expired", summary: { ...record.summary } };
3463
+ switch (record.state.status) {
3464
+ case "pending":
3465
+ case "executing":
3466
+ case "declined":
3467
+ case "expired":
3468
+ return { status: record.state.status, summary: toSummary(record) };
3469
+ case "completed":
3470
+ return { status: "already_completed", summary: toSummary(record) };
3471
+ case "failed":
3472
+ return { status: "failed", error: record.state.error, summary: toSummary(record) };
3473
+ case "approved": {
3474
+ const { decidedAt, execute } = record.state;
3475
+ const inFlight = (async () => {
3476
+ try {
3477
+ const result = await execute();
3478
+ record.state = { status: "completed", decidedAt };
3479
+ if (this.records.get(key) === record) this.notify();
3480
+ return { status: "completed", result, summary: toSummary(record) };
3481
+ } catch (err) {
3482
+ const error = err instanceof Error ? err.message : String(err);
3483
+ record.state = { status: "failed", decidedAt, error };
3484
+ if (this.records.get(key) === record) this.notify();
3485
+ return { status: "failed", error, summary: toSummary(record) };
3486
+ }
3487
+ })();
3488
+ record.state = { status: "executing", decidedAt, inFlight };
3489
+ this.notify();
3490
+ return await inFlight;
3491
+ }
3376
3492
  }
3377
- const run = record.execute;
3378
- record.execute = null;
3379
- const result = await run();
3380
- record.summary.status = "completed";
3381
- this.notify();
3382
- return { status: "completed", result, summary: { ...record.summary } };
3383
3493
  }
3384
3494
  clearOwner(owner) {
3385
3495
  const resolvedOwner = normalizeOwner2(owner);
3386
3496
  let changed = false;
3387
3497
  for (const [id, record] of this.records.entries()) {
3388
3498
  if (record.owner === resolvedOwner) {
3389
- record.execute = null;
3390
3499
  this.records.delete(id);
3391
3500
  changed = true;
3392
3501
  }
@@ -3775,13 +3884,93 @@ function renderInspectorHtml(info) {
3775
3884
  const stUniq = document.getElementById("st-uniq");
3776
3885
  const stModel = document.getElementById("st-model");
3777
3886
  const SAMPLE_PROMPT = "Skriv ett kort mejl till Anna Lindqvist (provnamn.maskera@example.com, 19900101-2385) och bekr\xE4fta m\xF6tet.";
3778
- let items = [];
3779
- let approvals = [];
3780
- let lastReceipt = null;
3781
- let reveal = false;
3782
- let userToggled = false;
3783
- const openIds = new Set();
3784
- const seenIds = new Set();
3887
+ const VISIBLE_APPROVAL_STATUSES = new Set(["pending", "approved", "executing", "declined", "failed"]);
3888
+ const state = {
3889
+ connection: "connecting",
3890
+ items: [],
3891
+ approvals: [],
3892
+ selfTest: { phase: "idle" },
3893
+ vaultView: "hidden",
3894
+ expansion: { mode: "auto" },
3895
+ };
3896
+
3897
+ function isExpanded(itemId, index) {
3898
+ if (state.expansion.mode === "auto") return index === 0;
3899
+ return state.expansion.openIds.has(itemId);
3900
+ }
3901
+
3902
+ function transition(event) {
3903
+ switch (event.type) {
3904
+ case "sse_open":
3905
+ state.connection = "live";
3906
+ return;
3907
+ case "sse_error":
3908
+ state.connection = "reconnecting";
3909
+ return;
3910
+ case "sse_init":
3911
+ state.connection = "live";
3912
+ state.items = event.items || [];
3913
+ state.approvals = event.approvals || [];
3914
+ renderApprovals();
3915
+ render();
3916
+ void refreshStatus();
3917
+ return;
3918
+ case "sse_approvals":
3919
+ state.approvals = event.approvals || [];
3920
+ renderApprovals();
3921
+ void refreshStatus();
3922
+ return;
3923
+ case "sse_request":
3924
+ state.items.unshift(event.item);
3925
+ if (state.items.length > 100) state.items.length = 100;
3926
+ render();
3927
+ void refreshStatus();
3928
+ if (state.vaultView === "revealed") void refreshVault();
3929
+ return;
3930
+ case "cleared":
3931
+ state.items = [];
3932
+ state.approvals = [];
3933
+ state.expansion = { mode: "auto" };
3934
+ renderApprovals();
3935
+ render();
3936
+ void refreshStatus();
3937
+ void refreshVault();
3938
+ return;
3939
+ case "toggle_item": {
3940
+ const openIds =
3941
+ state.expansion.mode === "manual"
3942
+ ? new Set(state.expansion.openIds)
3943
+ : new Set(state.items[0]?.id ? [state.items[0].id] : []);
3944
+ if (event.open) openIds.add(event.id);
3945
+ else openIds.delete(event.id);
3946
+ state.expansion = { mode: "manual", openIds };
3947
+ return;
3948
+ }
3949
+ case "toggle_vault":
3950
+ state.vaultView = state.vaultView === "revealed" ? "hidden" : "revealed";
3951
+ revealBtn.classList.toggle("active", state.vaultView === "revealed");
3952
+ revealBtn.textContent = state.vaultView === "revealed" ? "D\xF6lj originalv\xE4rden" : "Visa originalv\xE4rden";
3953
+ void refreshVault();
3954
+ return;
3955
+ case "selftest_start":
3956
+ state.selfTest = { phase: "running" };
3957
+ renderReceipt();
3958
+ return;
3959
+ case "selftest_done":
3960
+ state.selfTest = { phase: "done", receipt: event.receipt };
3961
+ renderReceipt();
3962
+ void refreshStatus();
3963
+ return;
3964
+ case "selftest_error":
3965
+ state.selfTest = { phase: "error", message: event.message };
3966
+ renderReceipt();
3967
+ return;
3968
+ case "selftest_close":
3969
+ state.selfTest = { phase: "idle" };
3970
+ renderReceipt();
3971
+ return;
3972
+ }
3973
+ }
3785
3974
 
3786
3975
  const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ "&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;" }[c]));
3787
3976
  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>");
@@ -3797,11 +3986,17 @@ function renderInspectorHtml(info) {
3797
3986
  };
3798
3987
 
3799
3988
  function renderReceipt() {
3800
- if (!lastReceipt) {
3801
- receiptRoot.innerHTML = "";
3989
+ selftestBtn.disabled = state.selfTest.phase === "running";
3990
+ selftestBtn.textContent = state.selfTest.phase === "running" ? "K\xF6r sj\xE4lvtest..." : "K\xF6r sj\xE4lvtest";
3991
+ if (state.selfTest.phase === "idle" || state.selfTest.phase === "running") {
3992
+ if (state.selfTest.phase === "idle") receiptRoot.innerHTML = "";
3802
3993
  return;
3803
3994
  }
3804
- const r = lastReceipt;
3995
+ if (state.selfTest.phase === "error") {
3996
+ receiptRoot.innerHTML = '<section class="receipt-box"><h2>Sj\xE4lvtest misslyckades</h2><p>' + esc(state.selfTest.message) + '</p></section>';
3997
+ return;
3998
+ }
3999
+ const r = state.selfTest.receipt;
3805
4000
  const checksHtml = (r.checks || []).map((c) => {
3806
4001
  const cls = c.status === "fail" ? " fail" : "";
3807
4002
  return '<li><span class="receipt-tag' + cls + '">[' + esc(c.status) + ']</span><span><strong>' + esc(c.name) + ':</strong> ' + esc(c.detail) + '</span></li>';
@@ -3827,29 +4022,22 @@ function renderInspectorHtml(info) {
3827
4022
  const closeBtn = document.getElementById("close-receipt-btn");
3828
4023
  if (closeBtn) {
3829
4024
  closeBtn.addEventListener("click", () => {
3830
- lastReceipt = null;
3831
- renderReceipt();
4025
+ transition({ type: "selftest_close" });
3832
4026
  });
3833
4027
  }
3834
4028
  }
3835
4029
 
3836
4030
  selftestBtn.addEventListener("click", async () => {
3837
- selftestBtn.disabled = true;
3838
- const prevText = selftestBtn.textContent;
3839
- selftestBtn.textContent = "K\xF6r sj\xE4lvtest...";
4031
+ if (state.selfTest.phase === "running") return;
4032
+ transition({ type: "selftest_start" });
3840
4033
  try {
3841
4034
  const r = await fetch("/_maskera/self-test", {
3842
4035
  method: "POST",
3843
4036
  headers: { "x-maskera-action": "self-test" },
3844
4037
  });
3845
- lastReceipt = await r.json();
3846
- renderReceipt();
3847
- await refreshStatus();
4038
+ transition({ type: "selftest_done", receipt: await r.json() });
3848
4039
  } catch (err) {
3849
- receiptRoot.innerHTML = '<section class="receipt-box"><h2>Sj\xE4lvtest misslyckades</h2><p>' + esc(err) + '</p></section>';
3850
- } finally {
3851
- selftestBtn.disabled = false;
3852
- selftestBtn.textContent = prevText;
4040
+ transition({ type: "selftest_error", message: String(err) });
3853
4041
  }
3854
4042
  });
3855
4043
 
@@ -3877,7 +4065,7 @@ function renderInspectorHtml(info) {
3877
4065
  }
3878
4066
 
3879
4067
  function renderApprovals() {
3880
- const visible = (approvals || []).filter((a) => a.status === "pending" || a.status === "approved" || a.status === "declined");
4068
+ const visible = (state.approvals || []).filter((a) => VISIBLE_APPROVAL_STATUSES.has(a.status));
3881
4069
  if (!visible.length) {
3882
4070
  approvalsRoot.innerHTML = "";
3883
4071
  return;
@@ -3885,7 +4073,7 @@ function renderInspectorHtml(info) {
3885
4073
  const rows = visible.map((a) => {
3886
4074
  const btns = a.status === "pending"
3887
4075
  ? '<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>'
3888
- : '<span class="badge">' + esc(a.status) + "</span>";
4076
+ : '<span class="badge' + (a.status === "failed" ? " err" : "") + '">' + esc(a.status) + "</span>";
3889
4077
  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>';
3890
4078
  }).join("");
3891
4079
  approvalsRoot.innerHTML = '<section class="approvals"><h2>V\xE4ntande godk\xE4nnanden (r\xE5 PII)</h2>' + rows + "</section>";
@@ -3899,7 +4087,7 @@ function renderInspectorHtml(info) {
3899
4087
  }
3900
4088
 
3901
4089
  async function refreshVault() {
3902
- if (!reveal) { vaultRoot.innerHTML = ""; return; }
4090
+ if (state.vaultView !== "revealed") { vaultRoot.innerHTML = ""; return; }
3903
4091
  try {
3904
4092
  const r = await fetch("/_maskera/vault", { headers: { "x-maskera-reveal": "1" } });
3905
4093
  const d = await r.json();
@@ -3911,7 +4099,7 @@ function renderInspectorHtml(info) {
3911
4099
  }
3912
4100
 
3913
4101
  function render() {
3914
- if (!items.length) {
4102
+ if (!state.items.length) {
3915
4103
  feedEl.innerHTML =
3916
4104
  '<div class="empty"><p class="empty-title">Inga anrop \xE4nnu.</p>' +
3917
4105
  'Skicka ett prov fr\xE5n din klient s\xE5 visas maskeringen h\xE4r:' +
@@ -3929,17 +4117,13 @@ function renderInspectorHtml(info) {
3929
4117
  }
3930
4118
  return;
3931
4119
  }
3932
- if (seenIds.size === 0 && items[0]?.id) {
3933
- openIds.add(items[0].id);
3934
- }
3935
- for (const it of items) seenIds.add(it.id);
3936
- feedEl.innerHTML = '<div class="list">' + items.map((it) => {
4120
+ feedEl.innerHTML = '<div class="list">' + state.items.map((it, idx) => {
3937
4121
  const time = formatLocalTime(it.timestamp);
3938
4122
  const tags = Object.entries(it.counts || {}).map(([k, v]) => '<span class="count-tag">' + esc(k) + " \xD7" + v + "</span>").join("");
3939
4123
  const previews = (it.redactedPreview || []).map((p) => '<pre class="preview">' + highlightTokens(p) + "</pre>").join("");
3940
4124
  const errBlock = it.errorDetail ? '<p class="body-label">Svar fr\xE5n API (fel):</p><pre class="preview err-preview">' + esc(it.errorDetail) + "</pre>" : "";
3941
4125
  const statusCls = it.status >= 200 && it.status < 400 ? "" : " err";
3942
- const isOpen = openIds.has(it.id);
4126
+ const isOpen = isExpanded(it.id, idx);
3943
4127
  return '<details class="item" data-id="' + esc(it.id) + '"' + (isOpen ? " open" : "") + '>' +
3944
4128
  '<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>' +
3945
4129
  '<span class="right"><span>' + (it.streamed ? "SSE" : "JSON") + '</span><span>' + it.durationMs + ' ms</span><span>' + esc(time) + '</span></span></summary>' +
@@ -3949,67 +4133,36 @@ function renderInspectorHtml(info) {
3949
4133
  det.addEventListener("toggle", () => {
3950
4134
  const id = det.getAttribute("data-id");
3951
4135
  if (!id) return;
3952
- userToggled = true;
3953
- if (det.open) openIds.add(id);
3954
- else openIds.delete(id);
4136
+ transition({ type: "toggle_item", id, open: det.open });
3955
4137
  });
3956
4138
  }
3957
4139
  }
3958
4140
 
3959
4141
  revealBtn.addEventListener("click", () => {
3960
- reveal = !reveal;
3961
- revealBtn.classList.toggle("active", reveal);
3962
- revealBtn.textContent = reveal ? "D\xF6lj originalv\xE4rden" : "Visa originalv\xE4rden";
3963
- void refreshVault();
4142
+ transition({ type: "toggle_vault" });
3964
4143
  });
3965
4144
 
3966
4145
  clearBtn.addEventListener("click", async () => {
3967
4146
  await fetch("/_maskera/clear", { method: "POST", headers: { "x-maskera-action": "clear" } });
3968
- items = [];
3969
- approvals = [];
3970
- userToggled = false;
3971
- openIds.clear();
3972
- seenIds.clear();
3973
- renderApprovals();
3974
- render();
3975
- await refreshStatus();
3976
- await refreshVault();
4147
+ transition({ type: "cleared" });
3977
4148
  });
3978
4149
 
3979
4150
  const es = new EventSource("/_maskera/events");
4151
+ es.addEventListener("open", () => transition({ type: "sse_open" }));
4152
+ es.addEventListener("error", () => transition({ type: "sse_error" }));
3980
4153
  es.addEventListener("init", (ev) => {
3981
4154
  const data = JSON.parse(ev.data);
3982
- items = data.items || [];
3983
- approvals = data.approvals || [];
3984
- renderApprovals();
3985
- render();
3986
- void refreshStatus();
4155
+ transition({ type: "sse_init", items: data.items, approvals: data.approvals });
3987
4156
  });
3988
4157
  es.addEventListener("approvals", (ev) => {
3989
4158
  const data = JSON.parse(ev.data);
3990
- approvals = data.approvals || [];
3991
- renderApprovals();
3992
- void refreshStatus();
4159
+ transition({ type: "sse_approvals", approvals: data.approvals });
3993
4160
  });
3994
4161
  es.addEventListener("request", (ev) => {
3995
- const next = JSON.parse(ev.data);
3996
- items.unshift(next);
3997
- if (items.length > 100) items.length = 100;
3998
- if (!userToggled && openIds.size === 0 && next?.id) openIds.add(next.id);
3999
- render();
4000
- void refreshStatus();
4001
- if (reveal) void refreshVault();
4162
+ transition({ type: "sse_request", item: JSON.parse(ev.data) });
4002
4163
  });
4003
4164
  es.addEventListener("cleared", () => {
4004
- items = [];
4005
- approvals = [];
4006
- userToggled = false;
4007
- openIds.clear();
4008
- seenIds.clear();
4009
- renderApprovals();
4010
- render();
4011
- void refreshStatus();
4012
- void refreshVault();
4165
+ transition({ type: "cleared" });
4013
4166
  });
4014
4167
  void refreshStatus();
4015
4168
  })();
@@ -4951,173 +5104,229 @@ function restoreLlmResponseBody(body, map, options = {}) {
4951
5104
  }
4952
5105
  return clone;
4953
5106
  }
4954
- function createSseRestorer(map, options = {}) {
4955
- const reasoningMap = filterMapExcluding(map, options.reasoningExcludedTokens);
4956
- const streams = /* @__PURE__ */ new Map();
4957
- const toolNames = /* @__PURE__ */ new Map();
4958
- const bufferedToolArgs = /* @__PURE__ */ new Map();
4959
- const getStream = (key, escapeForJsonString = false, useReasoningMap = false) => {
4960
- let r = streams.get(key);
4961
- if (!r) {
4962
- r = new StreamingRestorer(useReasoningMap ? reasoningMap : map, { escapeForJsonString });
4963
- streams.set(key, r);
4964
- }
4965
- return r;
4966
- };
4967
- function flushStream(key) {
4968
- const r = streams.get(key);
4969
- if (!r) return "";
4970
- streams.delete(key);
4971
- return r.flush();
4972
- }
4973
- function flushBufferedToolArgs(key) {
4974
- const raw = bufferedToolArgs.get(key);
4975
- if (raw === void 0) return "";
4976
- bufferedToolArgs.delete(key);
4977
- const name = toolNames.get(key);
4978
- if (shouldSkipToolArgRestore(name, raw)) return raw;
4979
- return restoreJsonEncodedText(raw, map);
5107
+ function channelKey(d) {
5108
+ switch (d.protocol) {
5109
+ case "anthropic":
5110
+ return `anthropic:${d.kind}:${d.index}`;
5111
+ case "openai_chat":
5112
+ return d.kind === "tool_args" ? `openai_chat:tool_args:${d.choiceIndex}:${d.toolIndex}` : `openai_chat:${d.kind}:${d.choiceIndex}`;
5113
+ case "openai_responses":
5114
+ switch (d.kind) {
5115
+ case "text":
5116
+ return `openai_responses:text:${d.outputIndex}:${d.contentIndex}`;
5117
+ case "reasoning":
5118
+ return `openai_responses:reasoning:${d.outputIndex}:${d.summaryIndex}`;
5119
+ case "tool_args":
5120
+ return `openai_responses:tool_args:${d.outputIndex}`;
5121
+ }
4980
5122
  }
4981
- function drainRemainingStreams() {
4982
- const events = [];
4983
- for (const key of [...bufferedToolArgs.keys()]) {
4984
- const full = flushBufferedToolArgs(key);
4985
- if (!full) continue;
4986
- if (key.startsWith("openai_chat_tool:")) {
4987
- const [, cIdx, tIdx] = key.split(":");
4988
- events.push(
4989
- `data: ${JSON.stringify({
4990
- choices: [
4991
- {
4992
- index: Number(cIdx ?? 0),
4993
- delta: {
4994
- tool_calls: [{ index: Number(tIdx ?? 0), function: { arguments: full } }]
4995
- }
4996
- }
4997
- ]
4998
- })}`
4999
- );
5000
- } else if (key.startsWith("anth_json:")) {
5001
- const idx = Number(key.split(":")[1] ?? 0);
5002
- events.push(
5003
- `event: content_block_delta
5123
+ }
5124
+ function formatChannelEvent(descriptor, payload) {
5125
+ switch (descriptor.protocol) {
5126
+ case "anthropic":
5127
+ switch (descriptor.kind) {
5128
+ case "text":
5129
+ return `event: content_block_delta
5004
5130
  data: ${JSON.stringify({
5005
5131
  type: "content_block_delta",
5006
- index: idx,
5007
- delta: { type: "input_json_delta", partial_json: full }
5008
- })}`
5009
- );
5010
- } else if (key.startsWith("resp_args:")) {
5011
- const outputIdx = Number(key.split(":")[1] ?? 0);
5012
- events.push(
5013
- `event: response.function_call_arguments.delta
5132
+ index: descriptor.index,
5133
+ delta: { type: "text_delta", text: payload }
5134
+ })}`;
5135
+ case "thinking":
5136
+ return `event: content_block_delta
5014
5137
  data: ${JSON.stringify({
5015
- type: "response.function_call_arguments.delta",
5016
- output_index: outputIdx,
5017
- delta: full
5018
- })}`
5019
- );
5138
+ type: "content_block_delta",
5139
+ index: descriptor.index,
5140
+ delta: { type: "thinking_delta", thinking: payload }
5141
+ })}`;
5142
+ case "tool_json":
5143
+ return `event: content_block_delta
5144
+ data: ${JSON.stringify({
5145
+ type: "content_block_delta",
5146
+ index: descriptor.index,
5147
+ delta: { type: "input_json_delta", partial_json: payload }
5148
+ })}`;
5020
5149
  }
5021
- }
5022
- for (const key of [...streams.keys()]) {
5023
- const tail = flushStream(key);
5024
- if (!tail) continue;
5025
- if (key.startsWith("openai_chat_text:")) {
5026
- const idx = Number(key.split(":")[1] ?? 0);
5027
- events.push(
5028
- `data: ${JSON.stringify({ choices: [{ index: idx, delta: { content: tail } }] })}`
5029
- );
5030
- } else if (key.startsWith("openai_chat_tool:")) {
5031
- const [, cIdx, tIdx] = key.split(":");
5032
- events.push(
5033
- `data: ${JSON.stringify({
5150
+ break;
5151
+ case "openai_chat":
5152
+ switch (descriptor.kind) {
5153
+ case "text":
5154
+ return `data: ${JSON.stringify({
5155
+ choices: [{ index: descriptor.choiceIndex, delta: { content: payload } }]
5156
+ })}`;
5157
+ case "reasoning":
5158
+ return `data: ${JSON.stringify({
5159
+ choices: [{ index: descriptor.choiceIndex, delta: { reasoning_content: payload } }]
5160
+ })}`;
5161
+ case "reasoning_plain":
5162
+ return `data: ${JSON.stringify({
5163
+ choices: [{ index: descriptor.choiceIndex, delta: { reasoning: payload } }]
5164
+ })}`;
5165
+ case "tool_args":
5166
+ return `data: ${JSON.stringify({
5034
5167
  choices: [
5035
5168
  {
5036
- index: Number(cIdx ?? 0),
5169
+ index: descriptor.choiceIndex,
5037
5170
  delta: {
5038
- tool_calls: [{ index: Number(tIdx ?? 0), function: { arguments: tail } }]
5171
+ tool_calls: [{ index: descriptor.toolIndex, function: { arguments: payload } }]
5039
5172
  }
5040
5173
  }
5041
5174
  ]
5042
- })}`
5043
- );
5044
- } else if (key.startsWith("anth_text:")) {
5045
- const idx = Number(key.split(":")[1] ?? 0);
5046
- events.push(
5047
- `event: content_block_delta
5048
- data: ${JSON.stringify({
5049
- type: "content_block_delta",
5050
- index: idx,
5051
- delta: { type: "text_delta", text: tail }
5052
- })}`
5053
- );
5054
- } else if (key.startsWith("anth_thinking:")) {
5055
- const idx = Number(key.split(":")[1] ?? 0);
5056
- events.push(
5057
- `event: content_block_delta
5058
- data: ${JSON.stringify({
5059
- type: "content_block_delta",
5060
- index: idx,
5061
- delta: { type: "thinking_delta", thinking: tail }
5062
- })}`
5063
- );
5064
- } else if (key.startsWith("anth_json:")) {
5065
- const idx = Number(key.split(":")[1] ?? 0);
5066
- events.push(
5067
- `event: content_block_delta
5068
- data: ${JSON.stringify({
5069
- type: "content_block_delta",
5070
- index: idx,
5071
- delta: { type: "input_json_delta", partial_json: tail }
5072
- })}`
5073
- );
5074
- } else if (key.startsWith("resp_text:")) {
5075
- const [, outputIdx, contentIdx] = key.split(":");
5076
- events.push(
5077
- `event: response.output_text.delta
5175
+ })}`;
5176
+ }
5177
+ break;
5178
+ case "openai_responses":
5179
+ switch (descriptor.kind) {
5180
+ case "text":
5181
+ return `event: response.output_text.delta
5078
5182
  data: ${JSON.stringify({
5079
5183
  type: "response.output_text.delta",
5080
- output_index: Number(outputIdx ?? 0),
5081
- content_index: Number(contentIdx ?? 0),
5082
- delta: tail
5083
- })}`
5084
- );
5085
- } else if (key.startsWith("openai_chat_reasoning:")) {
5086
- const idx = Number(key.split(":")[1] ?? 0);
5087
- events.push(
5088
- `data: ${JSON.stringify({ choices: [{ index: idx, delta: { reasoning_content: tail } }] })}`
5089
- );
5090
- } else if (key.startsWith("openai_chat_reasoning_plain:")) {
5091
- const idx = Number(key.split(":")[1] ?? 0);
5092
- events.push(
5093
- `data: ${JSON.stringify({ choices: [{ index: idx, delta: { reasoning: tail } }] })}`
5094
- );
5095
- } else if (key.startsWith("resp_reasoning:")) {
5096
- const [, outputIdx, summaryIdx] = key.split(":");
5097
- events.push(
5098
- `event: response.reasoning_summary_text.delta
5184
+ output_index: descriptor.outputIndex,
5185
+ content_index: descriptor.contentIndex,
5186
+ delta: payload
5187
+ })}`;
5188
+ case "reasoning":
5189
+ return `event: response.reasoning_summary_text.delta
5099
5190
  data: ${JSON.stringify({
5100
5191
  type: "response.reasoning_summary_text.delta",
5101
- output_index: Number(outputIdx ?? 0),
5102
- summary_index: Number(summaryIdx ?? 0),
5103
- delta: tail
5104
- })}`
5105
- );
5106
- } else if (key.startsWith("resp_args:")) {
5107
- const outputIdx = Number(key.split(":")[1] ?? 0);
5108
- events.push(
5109
- `event: response.function_call_arguments.delta
5192
+ output_index: descriptor.outputIndex,
5193
+ summary_index: descriptor.summaryIndex,
5194
+ delta: payload
5195
+ })}`;
5196
+ case "tool_args":
5197
+ return `event: response.function_call_arguments.delta
5110
5198
  data: ${JSON.stringify({
5111
5199
  type: "response.function_call_arguments.delta",
5112
- output_index: outputIdx,
5113
- delta: tail
5114
- })}`
5115
- );
5200
+ output_index: descriptor.outputIndex,
5201
+ delta: payload
5202
+ })}`;
5116
5203
  }
5204
+ }
5205
+ }
5206
+ function createSseRestorer(map, options = {}) {
5207
+ const reasoningMap = filterMapExcluding(map, options.reasoningExcludedTokens);
5208
+ const channels = /* @__PURE__ */ new Map();
5209
+ const frame = { buffer: "", pendingCr: false };
5210
+ function pushStream(descriptor, chunk, useReasoningMap = false) {
5211
+ const key = channelKey(descriptor);
5212
+ let entry = channels.get(key);
5213
+ if (entry?.category !== "stream") {
5214
+ entry = {
5215
+ category: "stream",
5216
+ descriptor,
5217
+ restorer: new StreamingRestorer(useReasoningMap ? reasoningMap : map)
5218
+ };
5219
+ channels.set(key, entry);
5220
+ }
5221
+ return entry.restorer.push(chunk);
5222
+ }
5223
+ function closeStream(descriptor) {
5224
+ const key = channelKey(descriptor);
5225
+ const entry = channels.get(key);
5226
+ if (entry?.category !== "stream") return "";
5227
+ channels.delete(key);
5228
+ return entry.restorer.flush();
5229
+ }
5230
+ function createToolState(toolName) {
5231
+ if (isMaskeraVaultToolName(toolName)) {
5232
+ return { mode: "passthrough", toolName };
5117
5233
  }
5118
- return events;
5234
+ if (toolName === "execute") {
5235
+ return { mode: "buffering_execute", toolName, raw: "" };
5236
+ }
5237
+ return {
5238
+ mode: "streaming",
5239
+ toolName,
5240
+ restorer: new StreamingRestorer(map, { escapeForJsonString: true })
5241
+ };
5242
+ }
5243
+ function setToolName(descriptor, toolName) {
5244
+ const key = channelKey(descriptor);
5245
+ const existing = channels.get(key);
5246
+ if (existing?.category === "tool" && existing.state.toolName === toolName) {
5247
+ return;
5248
+ }
5249
+ channels.set(key, {
5250
+ category: "tool",
5251
+ descriptor,
5252
+ state: createToolState(toolName)
5253
+ });
5254
+ }
5255
+ function pushToolDelta(descriptor, delta) {
5256
+ const key = channelKey(descriptor);
5257
+ let entry = channels.get(key);
5258
+ if (entry?.category !== "tool") {
5259
+ entry = {
5260
+ category: "tool",
5261
+ descriptor,
5262
+ state: {
5263
+ mode: "streaming",
5264
+ toolName: null,
5265
+ restorer: new StreamingRestorer(map, { escapeForJsonString: true })
5266
+ }
5267
+ };
5268
+ channels.set(key, entry);
5269
+ }
5270
+ switch (entry.state.mode) {
5271
+ case "passthrough":
5272
+ return delta;
5273
+ case "buffering_execute":
5274
+ entry.state.raw += delta;
5275
+ return "";
5276
+ case "streaming":
5277
+ return entry.state.restorer.push(delta);
5278
+ case "closed":
5279
+ return delta;
5280
+ }
5281
+ }
5282
+ function flushToolState(state) {
5283
+ switch (state.mode) {
5284
+ case "passthrough":
5285
+ case "closed":
5286
+ return "";
5287
+ case "buffering_execute":
5288
+ if (!state.raw) return "";
5289
+ return shouldSkipToolArgRestore(state.toolName, state.raw) ? state.raw : restoreJsonEncodedText(state.raw, map);
5290
+ case "streaming":
5291
+ return state.restorer.flush();
5292
+ }
5293
+ }
5294
+ function closeTool(descriptor, retainNameUntilItemDone = false) {
5295
+ const key = channelKey(descriptor);
5296
+ const entry = channels.get(key);
5297
+ if (entry?.category !== "tool") return { tail: "", toolName: null };
5298
+ const toolName = entry.state.toolName;
5299
+ const tail = flushToolState(entry.state);
5300
+ if (retainNameUntilItemDone) {
5301
+ entry.state = { mode: "closed", toolName };
5302
+ } else {
5303
+ channels.delete(key);
5304
+ }
5305
+ return { tail, toolName };
5306
+ }
5307
+ function consumeToolName(descriptor) {
5308
+ const key = channelKey(descriptor);
5309
+ const entry = channels.get(key);
5310
+ if (entry?.category !== "tool") return null;
5311
+ const name = entry.state.toolName;
5312
+ channels.delete(key);
5313
+ return name;
5314
+ }
5315
+ function drainRemainingStreams() {
5316
+ const toolEvents = [];
5317
+ const streamEvents = [];
5318
+ for (const [key, entry] of [...channels.entries()]) {
5319
+ channels.delete(key);
5320
+ if (entry.category === "tool") {
5321
+ const tail = flushToolState(entry.state);
5322
+ if (tail) toolEvents.push(formatChannelEvent(entry.descriptor, tail));
5323
+ } else {
5324
+ const tail = entry.restorer.flush();
5325
+ if (tail) streamEvents.push(formatChannelEvent(entry.descriptor, tail));
5326
+ }
5327
+ }
5328
+ return [...toolEvents, ...streamEvents];
5119
5329
  }
5120
- let sseBuffer = "";
5121
5330
  function processEventBlock(block) {
5122
5331
  const lines = block.split("\n");
5123
5332
  const outLines = [];
@@ -5145,177 +5354,136 @@ data: ${JSON.stringify({
5145
5354
  continue;
5146
5355
  }
5147
5356
  if (parsed.type === "content_block_start" && isPlainObject(parsed.content_block)) {
5148
- const idx = typeof parsed.index === "number" ? parsed.index : 0;
5357
+ const index = typeof parsed.index === "number" ? parsed.index : 0;
5149
5358
  if (parsed.content_block.type === "tool_use" && typeof parsed.content_block.name === "string") {
5150
- toolNames.set(`anth_json:${idx}`, parsed.content_block.name);
5359
+ setToolName(
5360
+ { protocol: "anthropic", kind: "tool_json", index },
5361
+ parsed.content_block.name
5362
+ );
5151
5363
  }
5152
5364
  outLines.push(`data: ${JSON.stringify(parsed)}`);
5153
5365
  continue;
5154
5366
  }
5155
5367
  if (parsed.type === "content_block_delta" && isPlainObject(parsed.delta)) {
5156
- const idx = typeof parsed.index === "number" ? parsed.index : 0;
5368
+ const index = typeof parsed.index === "number" ? parsed.index : 0;
5157
5369
  if (parsed.delta.type === "text_delta" && typeof parsed.delta.text === "string") {
5158
- parsed.delta.text = getStream(`anth_text:${idx}`).push(parsed.delta.text);
5370
+ parsed.delta.text = pushStream(
5371
+ { protocol: "anthropic", kind: "text", index },
5372
+ parsed.delta.text
5373
+ );
5159
5374
  } else if (parsed.delta.type === "thinking_delta" && typeof parsed.delta.thinking === "string") {
5160
- parsed.delta.thinking = getStream(`anth_thinking:${idx}`, false, true).push(
5161
- parsed.delta.thinking
5375
+ parsed.delta.thinking = pushStream(
5376
+ { protocol: "anthropic", kind: "thinking", index },
5377
+ parsed.delta.thinking,
5378
+ true
5162
5379
  );
5163
5380
  } else if (parsed.delta.type === "input_json_delta" && typeof parsed.delta.partial_json === "string") {
5164
- const key = `anth_json:${idx}`;
5165
- const name = toolNames.get(key);
5166
- if (isMaskeraVaultToolName(name)) ; else if (name === "execute") {
5167
- bufferedToolArgs.set(key, (bufferedToolArgs.get(key) ?? "") + parsed.delta.partial_json);
5168
- parsed.delta.partial_json = "";
5169
- } else {
5170
- parsed.delta.partial_json = getStream(key, true).push(parsed.delta.partial_json);
5171
- }
5381
+ parsed.delta.partial_json = pushToolDelta(
5382
+ { protocol: "anthropic", kind: "tool_json", index },
5383
+ parsed.delta.partial_json
5384
+ );
5172
5385
  }
5173
5386
  outLines.push(`data: ${JSON.stringify(parsed)}`);
5174
5387
  continue;
5175
5388
  }
5176
5389
  if (parsed.type === "content_block_stop") {
5177
- const idx = typeof parsed.index === "number" ? parsed.index : 0;
5178
- const textTail = flushStream(`anth_text:${idx}`);
5179
- if (textTail) {
5180
- extraEvents.push(
5181
- `event: content_block_delta
5182
- data: ${JSON.stringify({
5183
- type: "content_block_delta",
5184
- index: idx,
5185
- delta: { type: "text_delta", text: textTail }
5186
- })}`
5187
- );
5188
- }
5189
- const thinkingTail = flushStream(`anth_thinking:${idx}`);
5190
- if (thinkingTail) {
5191
- extraEvents.push(
5192
- `event: content_block_delta
5193
- data: ${JSON.stringify({
5194
- type: "content_block_delta",
5195
- index: idx,
5196
- delta: { type: "thinking_delta", thinking: thinkingTail }
5197
- })}`
5198
- );
5199
- }
5200
- const jsonKey = `anth_json:${idx}`;
5201
- const jsonTail = flushBufferedToolArgs(jsonKey) || flushStream(jsonKey);
5202
- toolNames.delete(jsonKey);
5203
- if (jsonTail) {
5204
- extraEvents.push(
5205
- `event: content_block_delta
5206
- data: ${JSON.stringify({
5207
- type: "content_block_delta",
5208
- index: idx,
5209
- delta: { type: "input_json_delta", partial_json: jsonTail }
5210
- })}`
5211
- );
5212
- }
5390
+ const index = typeof parsed.index === "number" ? parsed.index : 0;
5391
+ const textDesc = { protocol: "anthropic", kind: "text", index };
5392
+ const textTail = closeStream(textDesc);
5393
+ if (textTail) extraEvents.push(formatChannelEvent(textDesc, textTail));
5394
+ const thinkingDesc = {
5395
+ protocol: "anthropic",
5396
+ kind: "thinking",
5397
+ index
5398
+ };
5399
+ const thinkingTail = closeStream(thinkingDesc);
5400
+ if (thinkingTail) extraEvents.push(formatChannelEvent(thinkingDesc, thinkingTail));
5401
+ const toolDesc = { protocol: "anthropic", kind: "tool_json", index };
5402
+ const { tail: jsonTail } = closeTool(toolDesc);
5403
+ if (jsonTail) extraEvents.push(formatChannelEvent(toolDesc, jsonTail));
5213
5404
  outLines.push(`data: ${JSON.stringify(parsed)}`);
5214
5405
  continue;
5215
5406
  }
5216
5407
  if (Array.isArray(parsed.choices)) {
5217
5408
  for (const choice of parsed.choices) {
5218
5409
  if (!isPlainObject(choice)) continue;
5219
- const cIdx = typeof choice.index === "number" ? choice.index : 0;
5410
+ const choiceIndex = typeof choice.index === "number" ? choice.index : 0;
5220
5411
  const delta = choice.delta;
5221
5412
  if (isPlainObject(delta)) {
5222
5413
  if (typeof delta.content === "string") {
5223
- delta.content = getStream(`openai_chat_text:${cIdx}`).push(delta.content);
5414
+ delta.content = pushStream(
5415
+ { protocol: "openai_chat", kind: "text", choiceIndex },
5416
+ delta.content
5417
+ );
5224
5418
  }
5225
5419
  if (typeof delta.reasoning_content === "string") {
5226
- delta.reasoning_content = getStream(
5227
- `openai_chat_reasoning:${cIdx}`,
5228
- false,
5420
+ delta.reasoning_content = pushStream(
5421
+ { protocol: "openai_chat", kind: "reasoning", choiceIndex },
5422
+ delta.reasoning_content,
5229
5423
  true
5230
- ).push(delta.reasoning_content);
5424
+ );
5231
5425
  }
5232
5426
  if (typeof delta.reasoning === "string") {
5233
- delta.reasoning = getStream(`openai_chat_reasoning_plain:${cIdx}`, false, true).push(
5234
- delta.reasoning
5427
+ delta.reasoning = pushStream(
5428
+ { protocol: "openai_chat", kind: "reasoning_plain", choiceIndex },
5429
+ delta.reasoning,
5430
+ true
5235
5431
  );
5236
5432
  }
5237
5433
  if (Array.isArray(delta.tool_calls)) {
5238
5434
  for (const call of delta.tool_calls) {
5239
5435
  if (!isPlainObject(call)) continue;
5240
- const tIdx = typeof call.index === "number" ? call.index : 0;
5241
- const key = `openai_chat_tool:${cIdx}:${tIdx}`;
5436
+ const toolIndex = typeof call.index === "number" ? call.index : 0;
5437
+ const toolDesc = {
5438
+ protocol: "openai_chat",
5439
+ kind: "tool_args",
5440
+ choiceIndex,
5441
+ toolIndex
5442
+ };
5242
5443
  if (isPlainObject(call.function)) {
5243
5444
  if (typeof call.function.name === "string" && call.function.name) {
5244
- toolNames.set(key, call.function.name);
5445
+ setToolName(toolDesc, call.function.name);
5245
5446
  }
5246
5447
  if (typeof call.function.arguments === "string") {
5247
- const name = toolNames.get(key);
5248
- if (isMaskeraVaultToolName(name)) ; else if (name === "execute") {
5249
- bufferedToolArgs.set(
5250
- key,
5251
- (bufferedToolArgs.get(key) ?? "") + call.function.arguments
5252
- );
5253
- call.function.arguments = "";
5254
- } else {
5255
- call.function.arguments = getStream(key, true).push(call.function.arguments);
5256
- }
5448
+ call.function.arguments = pushToolDelta(toolDesc, call.function.arguments);
5257
5449
  }
5258
5450
  }
5259
5451
  }
5260
5452
  }
5261
5453
  }
5262
5454
  if (typeof choice.finish_reason === "string" && choice.finish_reason.length > 0) {
5263
- const textTail = flushStream(`openai_chat_text:${cIdx}`);
5455
+ const textTail = closeStream({ protocol: "openai_chat", kind: "text", choiceIndex });
5264
5456
  if (textTail) {
5265
5457
  if (!isPlainObject(choice.delta)) choice.delta = {};
5266
5458
  const d = choice.delta;
5267
5459
  d.content = (typeof d.content === "string" ? d.content : "") + textTail;
5268
5460
  }
5269
- const reasoningTail = flushStream(`openai_chat_reasoning:${cIdx}`);
5461
+ const reasoningTail = closeStream({
5462
+ protocol: "openai_chat",
5463
+ kind: "reasoning",
5464
+ choiceIndex
5465
+ });
5270
5466
  if (reasoningTail) {
5271
5467
  if (!isPlainObject(choice.delta)) choice.delta = {};
5272
5468
  const d = choice.delta;
5273
5469
  d.reasoning_content = (typeof d.reasoning_content === "string" ? d.reasoning_content : "") + reasoningTail;
5274
5470
  }
5275
- const reasoningPlainTail = flushStream(`openai_chat_reasoning_plain:${cIdx}`);
5471
+ const reasoningPlainTail = closeStream({
5472
+ protocol: "openai_chat",
5473
+ kind: "reasoning_plain",
5474
+ choiceIndex
5475
+ });
5276
5476
  if (reasoningPlainTail) {
5277
5477
  if (!isPlainObject(choice.delta)) choice.delta = {};
5278
5478
  const d = choice.delta;
5279
5479
  d.reasoning = (typeof d.reasoning === "string" ? d.reasoning : "") + reasoningPlainTail;
5280
5480
  }
5281
- const toolPrefix = `openai_chat_tool:${cIdx}:`;
5282
- for (const key of [...bufferedToolArgs.keys()]) {
5283
- if (!key.startsWith(toolPrefix)) continue;
5284
- const tIdx = Number(key.slice(toolPrefix.length) || 0);
5285
- const fullArgs = flushBufferedToolArgs(key);
5286
- toolNames.delete(key);
5287
- if (!fullArgs) continue;
5288
- extraEvents.push(
5289
- `data: ${JSON.stringify({
5290
- choices: [
5291
- {
5292
- index: cIdx,
5293
- delta: {
5294
- tool_calls: [{ index: tIdx, function: { arguments: fullArgs } }]
5295
- }
5296
- }
5297
- ]
5298
- })}`
5299
- );
5300
- }
5301
- for (const key of [...streams.keys()]) {
5302
- if (!key.startsWith(toolPrefix)) continue;
5303
- const tIdx = Number(key.slice(toolPrefix.length) || 0);
5304
- const toolTail = flushStream(key);
5305
- toolNames.delete(key);
5306
- if (!toolTail) continue;
5307
- extraEvents.push(
5308
- `data: ${JSON.stringify({
5309
- choices: [
5310
- {
5311
- index: cIdx,
5312
- delta: {
5313
- tool_calls: [{ index: tIdx, function: { arguments: toolTail } }]
5314
- }
5315
- }
5316
- ]
5317
- })}`
5318
- );
5481
+ for (const [key, entry] of [...channels.entries()]) {
5482
+ if (entry.category === "tool" && entry.descriptor.protocol === "openai_chat" && entry.descriptor.choiceIndex === choiceIndex) {
5483
+ channels.delete(key);
5484
+ const tail = flushToolState(entry.state);
5485
+ if (tail) extraEvents.push(formatChannelEvent(entry.descriptor, tail));
5486
+ }
5319
5487
  }
5320
5488
  }
5321
5489
  }
@@ -5324,31 +5492,36 @@ data: ${JSON.stringify({
5324
5492
  }
5325
5493
  if (parsed.type === "response.output_item.added" && isPlainObject(parsed.item)) {
5326
5494
  if (parsed.item.type === "function_call" && typeof parsed.item.name === "string") {
5327
- toolNames.set(`resp_args:${String(parsed.output_index ?? 0)}`, parsed.item.name);
5495
+ const outputIndex = typeof parsed.output_index === "number" ? parsed.output_index : 0;
5496
+ setToolName(
5497
+ { protocol: "openai_responses", kind: "tool_args", outputIndex },
5498
+ parsed.item.name
5499
+ );
5328
5500
  }
5329
5501
  outLines.push(`data: ${JSON.stringify(parsed)}`);
5330
5502
  continue;
5331
5503
  }
5332
5504
  if (parsed.type === "response.output_text.delta" && typeof parsed.delta === "string") {
5333
- const key = `resp_text:${String(parsed.output_index ?? 0)}:${String(parsed.content_index ?? 0)}`;
5334
- parsed.delta = getStream(key).push(parsed.delta);
5505
+ const outputIndex = typeof parsed.output_index === "number" ? parsed.output_index : 0;
5506
+ const contentIndex = typeof parsed.content_index === "number" ? parsed.content_index : 0;
5507
+ parsed.delta = pushStream(
5508
+ { protocol: "openai_responses", kind: "text", outputIndex, contentIndex },
5509
+ parsed.delta
5510
+ );
5335
5511
  outLines.push(`data: ${JSON.stringify(parsed)}`);
5336
5512
  continue;
5337
5513
  }
5338
5514
  if (parsed.type === "response.output_text.done") {
5339
- const key = `resp_text:${String(parsed.output_index ?? 0)}:${String(parsed.content_index ?? 0)}`;
5340
- const tail = flushStream(key);
5341
- if (tail) {
5342
- extraEvents.push(
5343
- `event: response.output_text.delta
5344
- data: ${JSON.stringify({
5345
- type: "response.output_text.delta",
5346
- output_index: parsed.output_index ?? 0,
5347
- content_index: parsed.content_index ?? 0,
5348
- delta: tail
5349
- })}`
5350
- );
5351
- }
5515
+ const outputIndex = typeof parsed.output_index === "number" ? parsed.output_index : 0;
5516
+ const contentIndex = typeof parsed.content_index === "number" ? parsed.content_index : 0;
5517
+ const desc = {
5518
+ protocol: "openai_responses",
5519
+ kind: "text",
5520
+ outputIndex,
5521
+ contentIndex
5522
+ };
5523
+ const tail = closeStream(desc);
5524
+ if (tail) extraEvents.push(formatChannelEvent(desc, tail));
5352
5525
  if (typeof parsed.text === "string") {
5353
5526
  parsed.text = restorePlainText(parsed.text, map);
5354
5527
  }
@@ -5356,25 +5529,26 @@ data: ${JSON.stringify({
5356
5529
  continue;
5357
5530
  }
5358
5531
  if (parsed.type === "response.reasoning_summary_text.delta" && typeof parsed.delta === "string") {
5359
- const key = `resp_reasoning:${String(parsed.output_index ?? 0)}:${String(parsed.summary_index ?? 0)}`;
5360
- parsed.delta = getStream(key).push(parsed.delta);
5532
+ const outputIndex = typeof parsed.output_index === "number" ? parsed.output_index : 0;
5533
+ const summaryIndex = typeof parsed.summary_index === "number" ? parsed.summary_index : 0;
5534
+ parsed.delta = pushStream(
5535
+ { protocol: "openai_responses", kind: "reasoning", outputIndex, summaryIndex },
5536
+ parsed.delta
5537
+ );
5361
5538
  outLines.push(`data: ${JSON.stringify(parsed)}`);
5362
5539
  continue;
5363
5540
  }
5364
5541
  if (parsed.type === "response.reasoning_summary_text.done") {
5365
- const key = `resp_reasoning:${String(parsed.output_index ?? 0)}:${String(parsed.summary_index ?? 0)}`;
5366
- const tail = flushStream(key);
5367
- if (tail) {
5368
- extraEvents.push(
5369
- `event: response.reasoning_summary_text.delta
5370
- data: ${JSON.stringify({
5371
- type: "response.reasoning_summary_text.delta",
5372
- output_index: parsed.output_index ?? 0,
5373
- summary_index: parsed.summary_index ?? 0,
5374
- delta: tail
5375
- })}`
5376
- );
5377
- }
5542
+ const outputIndex = typeof parsed.output_index === "number" ? parsed.output_index : 0;
5543
+ const summaryIndex = typeof parsed.summary_index === "number" ? parsed.summary_index : 0;
5544
+ const desc = {
5545
+ protocol: "openai_responses",
5546
+ kind: "reasoning",
5547
+ outputIndex,
5548
+ summaryIndex
5549
+ };
5550
+ const tail = closeStream(desc);
5551
+ if (tail) extraEvents.push(formatChannelEvent(desc, tail));
5378
5552
  if (typeof parsed.text === "string") {
5379
5553
  parsed.text = restorePlainText(parsed.text, map);
5380
5554
  }
@@ -5382,32 +5556,24 @@ data: ${JSON.stringify({
5382
5556
  continue;
5383
5557
  }
5384
5558
  if (parsed.type === "response.function_call_arguments.delta" && typeof parsed.delta === "string") {
5385
- const key = `resp_args:${String(parsed.output_index ?? 0)}`;
5386
- const name = toolNames.get(key);
5387
- if (isMaskeraVaultToolName(name)) ; else if (name === "execute") {
5388
- bufferedToolArgs.set(key, (bufferedToolArgs.get(key) ?? "") + parsed.delta);
5389
- parsed.delta = "";
5390
- } else {
5391
- parsed.delta = getStream(key, true).push(parsed.delta);
5392
- }
5559
+ const outputIndex = typeof parsed.output_index === "number" ? parsed.output_index : 0;
5560
+ parsed.delta = pushToolDelta(
5561
+ { protocol: "openai_responses", kind: "tool_args", outputIndex },
5562
+ parsed.delta
5563
+ );
5393
5564
  outLines.push(`data: ${JSON.stringify(parsed)}`);
5394
5565
  continue;
5395
5566
  }
5396
5567
  if (parsed.type === "response.function_call_arguments.done") {
5397
- const key = `resp_args:${String(parsed.output_index ?? 0)}`;
5398
- const name = toolNames.get(key);
5399
- const tail = flushBufferedToolArgs(key) || flushStream(key);
5400
- if (tail) {
5401
- extraEvents.push(
5402
- `event: response.function_call_arguments.delta
5403
- data: ${JSON.stringify({
5404
- type: "response.function_call_arguments.delta",
5405
- output_index: parsed.output_index ?? 0,
5406
- delta: tail
5407
- })}`
5408
- );
5409
- }
5410
- if (typeof parsed.arguments === "string" && !shouldSkipToolArgRestore(name, parsed.arguments)) {
5568
+ const outputIndex = typeof parsed.output_index === "number" ? parsed.output_index : 0;
5569
+ const desc = {
5570
+ protocol: "openai_responses",
5571
+ kind: "tool_args",
5572
+ outputIndex
5573
+ };
5574
+ const { tail, toolName } = closeTool(desc, true);
5575
+ if (tail) extraEvents.push(formatChannelEvent(desc, tail));
5576
+ if (typeof parsed.arguments === "string" && !shouldSkipToolArgRestore(toolName, parsed.arguments)) {
5411
5577
  parsed.arguments = restoreJsonEncodedText(parsed.arguments, map);
5412
5578
  }
5413
5579
  outLines.push(`data: ${JSON.stringify(parsed)}`);
@@ -5427,9 +5593,13 @@ data: ${JSON.stringify({
5427
5593
  }
5428
5594
  if (parsed.type === "response.output_item.done" && isPlainObject(parsed.item)) {
5429
5595
  const item = parsed.item;
5430
- const key = `resp_args:${String(parsed.output_index ?? 0)}`;
5431
- const name = typeof item.name === "string" ? item.name : toolNames.get(key);
5432
- toolNames.delete(key);
5596
+ const outputIndex = typeof parsed.output_index === "number" ? parsed.output_index : 0;
5597
+ const trackedName = consumeToolName({
5598
+ protocol: "openai_responses",
5599
+ kind: "tool_args",
5600
+ outputIndex
5601
+ });
5602
+ const name = typeof item.name === "string" ? item.name : trackedName;
5433
5603
  if (typeof item.arguments === "string" && !shouldSkipToolArgRestore(name, item.arguments)) {
5434
5604
  item.arguments = restoreJsonEncodedText(item.arguments, map);
5435
5605
  }
@@ -5462,19 +5632,18 @@ data: ${JSON.stringify({
5462
5632
 
5463
5633
  ${joined}` : joined;
5464
5634
  }
5465
- let pendingCr = false;
5466
5635
  return {
5467
5636
  push(chunk) {
5468
- let text = pendingCr ? `\r${chunk}` : chunk;
5469
- pendingCr = text.endsWith("\r");
5470
- if (pendingCr) text = text.slice(0, -1);
5471
- sseBuffer += text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
5637
+ let text = frame.pendingCr ? `\r${chunk}` : chunk;
5638
+ frame.pendingCr = text.endsWith("\r");
5639
+ if (frame.pendingCr) text = text.slice(0, -1);
5640
+ frame.buffer += text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
5472
5641
  let out = "";
5473
5642
  for (; ; ) {
5474
- const sep3 = sseBuffer.indexOf("\n\n");
5643
+ const sep3 = frame.buffer.indexOf("\n\n");
5475
5644
  if (sep3 < 0) break;
5476
- const block = sseBuffer.slice(0, sep3);
5477
- sseBuffer = sseBuffer.slice(sep3 + 2);
5645
+ const block = frame.buffer.slice(0, sep3);
5646
+ frame.buffer = frame.buffer.slice(sep3 + 2);
5478
5647
  out += `${processEventBlock(block)}
5479
5648
 
5480
5649
  `;
@@ -5482,14 +5651,14 @@ ${joined}` : joined;
5482
5651
  return out;
5483
5652
  },
5484
5653
  flush() {
5485
- if (pendingCr) {
5486
- sseBuffer += "\n";
5487
- pendingCr = false;
5654
+ if (frame.pendingCr) {
5655
+ frame.buffer += "\n";
5656
+ frame.pendingCr = false;
5488
5657
  }
5489
5658
  const parts = [];
5490
- if (sseBuffer) {
5491
- parts.push(processEventBlock(sseBuffer));
5492
- sseBuffer = "";
5659
+ if (frame.buffer) {
5660
+ parts.push(processEventBlock(frame.buffer));
5661
+ frame.buffer = "";
5493
5662
  }
5494
5663
  const drained = drainRemainingStreams();
5495
5664
  if (drained.length > 0) {
@@ -5692,6 +5861,42 @@ function parseScopedMcpPolicy(urlPath, base) {
5692
5861
  }
5693
5862
  return { allowRawRestore, readOnly, approvalMode };
5694
5863
  }
5864
+ var McpSessionStore = class {
5865
+ constructor(onDispose, options = {}) {
5866
+ this.active = /* @__PURE__ */ new Map();
5867
+ this.closed = /* @__PURE__ */ new Set();
5868
+ this.onDispose = onDispose;
5869
+ this.maxActive = options.maxActive ?? 200;
5870
+ this.maxClosed = options.maxClosed ?? 500;
5871
+ }
5872
+ open(policy) {
5873
+ const id = `mcp_${randomUUID().slice(0, 16)}`;
5874
+ if (this.active.size >= this.maxActive) {
5875
+ const oldest = this.active.keys().next().value;
5876
+ if (oldest !== void 0) {
5877
+ this.close(oldest);
5878
+ }
5879
+ }
5880
+ this.closed.delete(id);
5881
+ this.active.set(id, policy);
5882
+ return id;
5883
+ }
5884
+ lookup(id) {
5885
+ const policy = this.active.get(id);
5886
+ if (policy) return { status: "active", policy };
5887
+ if (this.closed.has(id)) return { status: "closed" };
5888
+ return { status: "unknown" };
5889
+ }
5890
+ close(id) {
5891
+ this.active.delete(id);
5892
+ this.closed.add(id);
5893
+ this.onDispose(id);
5894
+ if (this.closed.size > this.maxClosed) {
5895
+ const first = this.closed.values().next().value;
5896
+ if (first !== void 0) this.closed.delete(first);
5897
+ }
5898
+ }
5899
+ };
5695
5900
  async function startMaskeraProxy(options = {}) {
5696
5901
  const host = options.host ?? "127.0.0.1";
5697
5902
  if (!options.allowNonLoopback && !isLoopbackBindHost(host)) {
@@ -5718,8 +5923,12 @@ async function startMaskeraProxy(options = {}) {
5718
5923
  readOnly: options.readOnly ?? false,
5719
5924
  approvalMode: options.approvalMode ?? "automatic"
5720
5925
  };
5721
- const mcpSessions = /* @__PURE__ */ new Map();
5722
- const closedMcpSessions = /* @__PURE__ */ new Set();
5926
+ const mcpSessionStore = new McpSessionStore((sessionId) => {
5927
+ const owner = `mcp:${sessionId}`;
5928
+ vault.clearOwner(owner);
5929
+ approvals.clearOwner(owner);
5930
+ mcpServerInstance?.clearOwner(owner);
5931
+ });
5723
5932
  const messageTokensBySession = /* @__PURE__ */ new Map();
5724
5933
  const externalToolTokensBySession = /* @__PURE__ */ new Map();
5725
5934
  if (auditLogPath) {
@@ -5901,6 +6110,7 @@ async function startMaskeraProxy(options = {}) {
5901
6110
  }
5902
6111
  vault.clearAll();
5903
6112
  approvals.clearAll();
6113
+ mcpServerInstance?.clearAllOwners();
5904
6114
  engine.clearCache();
5905
6115
  inspector.clear();
5906
6116
  messageTokensBySession.clear();
@@ -6051,14 +6261,7 @@ async function startMaskeraProxy(options = {}) {
6051
6261
  const incomingSessionId = typeof req.headers["mcp-session-id"] === "string" ? req.headers["mcp-session-id"].trim() : "";
6052
6262
  if (method === "DELETE") {
6053
6263
  if (incomingSessionId) {
6054
- mcpSessions.delete(incomingSessionId);
6055
- closedMcpSessions.add(incomingSessionId);
6056
- vault.clearOwner(`mcp:${incomingSessionId}`);
6057
- approvals.clearOwner(`mcp:${incomingSessionId}`);
6058
- if (closedMcpSessions.size > 500) {
6059
- const first = closedMcpSessions.values().next().value;
6060
- if (first !== void 0) closedMcpSessions.delete(first);
6061
- }
6264
+ mcpSessionStore.close(incomingSessionId);
6062
6265
  }
6063
6266
  res.writeHead(204, INSPECTOR_SECURITY_HEADERS);
6064
6267
  res.end();
@@ -6086,7 +6289,8 @@ async function startMaskeraProxy(options = {}) {
6086
6289
  res.end(JSON.stringify({ error: `Unsupported HTTP method ${method} for /mcp.` }));
6087
6290
  return;
6088
6291
  }
6089
- if (incomingSessionId && closedMcpSessions.has(incomingSessionId)) {
6292
+ const incomingSessionState = incomingSessionId ? mcpSessionStore.lookup(incomingSessionId) : null;
6293
+ if (incomingSessionState?.status === "closed") {
6090
6294
  res.writeHead(404, {
6091
6295
  ...INSPECTOR_SECURITY_HEADERS,
6092
6296
  "content-type": "application/json; charset=utf-8"
@@ -6114,7 +6318,7 @@ async function startMaskeraProxy(options = {}) {
6114
6318
  }
6115
6319
  const messages = Array.isArray(parsedMcp) ? parsedMcp : [parsedMcp];
6116
6320
  const isInit = messages.some((m) => isPlainObject(m) && m.method === "initialize");
6117
- if (!isInit && incomingSessionId && !mcpSessions.has(incomingSessionId)) {
6321
+ if (!isInit && incomingSessionState?.status === "unknown") {
6118
6322
  res.writeHead(404, {
6119
6323
  ...INSPECTOR_SECURITY_HEADERS,
6120
6324
  "content-type": "application/json; charset=utf-8"
@@ -6122,22 +6326,10 @@ async function startMaskeraProxy(options = {}) {
6122
6326
  res.end(JSON.stringify({ error: "Unknown MCP session." }));
6123
6327
  return;
6124
6328
  }
6125
- const sessionBasePolicy = (incomingSessionId ? mcpSessions.get(incomingSessionId) : void 0) ?? baseMcpPolicy;
6329
+ const sessionBasePolicy = incomingSessionState?.status === "active" ? incomingSessionState.policy : baseMcpPolicy;
6126
6330
  const effectivePolicy = parseScopedMcpPolicy(urlPath, sessionBasePolicy);
6127
6331
  const mcpServer = getMcpServer();
6128
- let responseSessionId = incomingSessionId;
6129
- if (isInit) {
6130
- responseSessionId = `mcp_${randomUUID().slice(0, 16)}`;
6131
- if (mcpSessions.size >= 200) {
6132
- const oldest = mcpSessions.keys().next().value;
6133
- if (oldest !== void 0) {
6134
- mcpSessions.delete(oldest);
6135
- vault.clearOwner(`mcp:${oldest}`);
6136
- approvals.clearOwner(`mcp:${oldest}`);
6137
- }
6138
- }
6139
- mcpSessions.set(responseSessionId, effectivePolicy);
6140
- }
6332
+ const responseSessionId = isInit ? mcpSessionStore.open(effectivePolicy) : incomingSessionId;
6141
6333
  const sessionOwner = responseSessionId ? `mcp:${responseSessionId}` : "mcp:stateless";
6142
6334
  const scopedPolicy = { ...effectivePolicy, sessionOwner };
6143
6335
  const responses = [];
@@ -6604,6 +6796,7 @@ ${body}`
6604
6796
  const actualPort = typeof addr === "object" && addr ? addr.port : requestedPort;
6605
6797
  boundPort = actualPort;
6606
6798
  boundUrl = `http://${host}:${actualPort}`;
6799
+ let lifecycle = { phase: "listening" };
6607
6800
  return {
6608
6801
  host,
6609
6802
  port: actualPort,
@@ -6621,12 +6814,22 @@ ${body}`
6621
6814
  sessions: vault.list().length
6622
6815
  }),
6623
6816
  close: async () => {
6624
- unsubscribeApprovals();
6625
- inspector.closeAll();
6626
- await new Promise((resolveClose, rejectClose) => {
6627
- server.close((err) => err ? rejectClose(err) : resolveClose());
6628
- });
6629
- await auditChain;
6817
+ if (lifecycle.phase === "closed") return;
6818
+ if (lifecycle.phase === "closing") return lifecycle.promise;
6819
+ const closingPromise = (async () => {
6820
+ try {
6821
+ unsubscribeApprovals();
6822
+ inspector.closeAll();
6823
+ await new Promise((resolveClose, rejectClose) => {
6824
+ server.close((err) => err ? rejectClose(err) : resolveClose());
6825
+ });
6826
+ await auditChain;
6827
+ } finally {
6828
+ lifecycle = { phase: "closed" };
6829
+ }
6830
+ })();
6831
+ lifecycle = { phase: "closing", promise: closingPromise };
6832
+ return closingPromise;
6630
6833
  }
6631
6834
  };
6632
6835
  }
@@ -6901,6 +7104,113 @@ async function runService(options) {
6901
7104
  detail: running ? `Installed and started ${serviceName} (${serviceFile}). Listening on ${proxyUrl}.` : `Installed ${serviceName} (${serviceFile}). Check logs if ${proxyUrl} is still warming up.`
6902
7105
  };
6903
7106
  }
7107
+
7108
+ // src/stdio.ts
7109
+ function parseElicitationResponse(resp) {
7110
+ if (resp.error) return { action: "cancel" };
7111
+ const resultObj = resp.result && typeof resp.result === "object" ? resp.result : {};
7112
+ const action = resultObj.action === "accept" || resultObj.action === "decline" || resultObj.action === "cancel" ? resultObj.action : "cancel";
7113
+ const content = resultObj.content && typeof resultObj.content === "object" && !Array.isArray(resultObj.content) ? resultObj.content : void 0;
7114
+ return { action, content };
7115
+ }
7116
+ function createStdioMcpTransport(options) {
7117
+ let state = {
7118
+ phase: "open",
7119
+ nextServerReqId: 1,
7120
+ pending: /* @__PURE__ */ new Map()
7121
+ };
7122
+ let chain = Promise.resolve();
7123
+ return {
7124
+ get phase() {
7125
+ return state.phase;
7126
+ },
7127
+ requestElicitation(req) {
7128
+ if (state.phase === "closed") {
7129
+ return Promise.resolve({ action: "cancel" });
7130
+ }
7131
+ const id = `maskera_elicit_${state.nextServerReqId++}`;
7132
+ const pending = state.pending;
7133
+ return new Promise((resolveReq) => {
7134
+ pending.set(id, resolveReq);
7135
+ options.writeStdout(
7136
+ `${JSON.stringify({
7137
+ jsonrpc: "2.0",
7138
+ id,
7139
+ method: "elicitation/create",
7140
+ params: req
7141
+ })}
7142
+ `
7143
+ );
7144
+ });
7145
+ },
7146
+ handleLine(line, handleMessage) {
7147
+ if (state.phase === "closed") return;
7148
+ const trimmed = line.trim();
7149
+ if (!trimmed) return;
7150
+ let parsed;
7151
+ try {
7152
+ parsed = JSON.parse(trimmed);
7153
+ } catch {
7154
+ chain = chain.then(() => {
7155
+ options.writeStdout(
7156
+ `${JSON.stringify({
7157
+ jsonrpc: "2.0",
7158
+ id: null,
7159
+ error: { code: -32700, message: "Parse error" }
7160
+ })}
7161
+ `
7162
+ );
7163
+ });
7164
+ return;
7165
+ }
7166
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed) && !("method" in parsed) && typeof parsed.id === "string") {
7167
+ const resp = parsed;
7168
+ const resolvePending = state.pending.get(resp.id);
7169
+ if (resolvePending) {
7170
+ state.pending.delete(resp.id);
7171
+ resolvePending(parseElicitationResponse(resp));
7172
+ return;
7173
+ }
7174
+ }
7175
+ chain = chain.then(async () => {
7176
+ try {
7177
+ const response = await handleMessage(parsed);
7178
+ if (response) {
7179
+ options.writeStdout(`${JSON.stringify(response)}
7180
+ `);
7181
+ }
7182
+ } catch (err) {
7183
+ const message = err instanceof Error ? err.message : String(err);
7184
+ options.writeStderr(`[maskera-mcp] internal error: ${message}
7185
+ `);
7186
+ const maybeId = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed.id : void 0;
7187
+ if (typeof maybeId === "string" || typeof maybeId === "number" || maybeId === null) {
7188
+ options.writeStdout(
7189
+ `${JSON.stringify({
7190
+ jsonrpc: "2.0",
7191
+ id: maybeId,
7192
+ error: { code: -32603, message: "Internal error" }
7193
+ })}
7194
+ `
7195
+ );
7196
+ }
7197
+ }
7198
+ });
7199
+ },
7200
+ close() {
7201
+ if (state.phase === "closed") return;
7202
+ const pendingResolvers = [...state.pending.values()];
7203
+ state.pending.clear();
7204
+ state = { phase: "closed" };
7205
+ for (const resolvePending of pendingResolvers) {
7206
+ resolvePending({ action: "cancel" });
7207
+ }
7208
+ },
7209
+ whenIdle() {
7210
+ return chain;
7211
+ }
7212
+ };
7213
+ }
6904
7214
  function openUrlInBrowser(url, platform = process.platform) {
6905
7215
  try {
6906
7216
  let cmd;
@@ -6994,25 +7304,33 @@ async function runWrap(options) {
6994
7304
  stdio: "inherit",
6995
7305
  env: childEnv
6996
7306
  });
6997
- const forwardSigInt = () => {
6998
- if (!child.killed) child.kill("SIGINT");
6999
- };
7000
- const forwardSigTerm = () => {
7001
- if (!child.killed) child.kill("SIGTERM");
7307
+ let childState = { phase: "running" };
7308
+ const forwardSignal = (sig) => {
7309
+ if (childState.phase !== "running") return;
7310
+ if (!child.killed) child.kill(sig);
7002
7311
  };
7312
+ const forwardSigInt = () => forwardSignal("SIGINT");
7313
+ const forwardSigTerm = () => forwardSignal("SIGTERM");
7003
7314
  process.on("SIGINT", forwardSigInt);
7004
7315
  process.on("SIGTERM", forwardSigTerm);
7005
7316
  const { exitCode, signal } = await new Promise((resolveExit, rejectExit) => {
7006
- child.on("error", rejectExit);
7317
+ const cleanupSignals = () => {
7318
+ process.off("SIGINT", forwardSigInt);
7319
+ process.off("SIGTERM", forwardSigTerm);
7320
+ };
7321
+ child.on("error", (err) => {
7322
+ if (childState.phase !== "running") return;
7323
+ childState = { phase: "failed", error: err };
7324
+ cleanupSignals();
7325
+ rejectExit(err);
7326
+ });
7007
7327
  child.on("exit", (code, sig) => {
7008
- resolveExit({
7009
- exitCode: code ?? (sig ? 1 : 0),
7010
- signal: sig
7011
- });
7328
+ if (childState.phase !== "running") return;
7329
+ const resolvedCode = code ?? (sig ? 1 : 0);
7330
+ childState = { phase: "exited", exitCode: resolvedCode, signal: sig };
7331
+ cleanupSignals();
7332
+ resolveExit({ exitCode: resolvedCode, signal: sig });
7012
7333
  });
7013
- }).finally(() => {
7014
- process.off("SIGINT", forwardSigInt);
7015
- process.off("SIGTERM", forwardSigTerm);
7016
7334
  });
7017
7335
  const session = running.stats();
7018
7336
  let receiptSavedPath;
@@ -7736,30 +8054,24 @@ Verify: ${primary.verifyStep}
7736
8054
  if (args.openInspector) {
7737
8055
  openUrlInBrowser(running.inspectorUrl);
7738
8056
  }
8057
+ let shutdownState = "running";
7739
8058
  const shutdown = () => {
8059
+ if (shutdownState !== "running") return;
8060
+ shutdownState = "shutting_down";
7740
8061
  void running.close().finally(() => process.exit(0));
7741
8062
  };
7742
8063
  process.on("SIGINT", shutdown);
7743
8064
  process.on("SIGTERM", shutdown);
7744
8065
  return;
7745
8066
  }
7746
- let nextServerReqId = 1;
7747
- const pendingClientResponses = /* @__PURE__ */ new Map();
7748
- const requestElicitation = (req) => {
7749
- const id = `maskera_elicit_${nextServerReqId++}`;
7750
- return new Promise((resolveReq, rejectReq) => {
7751
- pendingClientResponses.set(id, { resolve: resolveReq, reject: rejectReq });
7752
- process.stdout.write(
7753
- `${JSON.stringify({
7754
- jsonrpc: "2.0",
7755
- id,
7756
- method: "elicitation/create",
7757
- params: req
7758
- })}
7759
- `
7760
- );
7761
- });
7762
- };
8067
+ const transport = createStdioMcpTransport({
8068
+ writeStdout: (line) => {
8069
+ process.stdout.write(line);
8070
+ },
8071
+ writeStderr: (line) => {
8072
+ process.stderr.write(line);
8073
+ }
8074
+ });
7763
8075
  const server = createMaskeraMcpServer({
7764
8076
  engine,
7765
8077
  allowedRoots: args.roots,
@@ -7768,76 +8080,15 @@ Verify: ${primary.verifyStep}
7768
8080
  allowRawRestore: args.allowRawRestore,
7769
8081
  readOnly: args.readOnly,
7770
8082
  approvalMode: args.approvalMode,
7771
- requestElicitation
8083
+ requestElicitation: (req) => transport.requestElicitation(req)
7772
8084
  });
7773
8085
  engine.warmup();
7774
- let chain = Promise.resolve();
7775
8086
  const rl = createInterface({ input: process.stdin, crlfDelay: Number.POSITIVE_INFINITY });
7776
8087
  rl.on("line", (line) => {
7777
- const trimmed = line.trim();
7778
- if (!trimmed) return;
7779
- let parsed;
7780
- try {
7781
- parsed = JSON.parse(trimmed);
7782
- } catch {
7783
- chain = chain.then(() => {
7784
- process.stdout.write(
7785
- `${JSON.stringify({
7786
- jsonrpc: "2.0",
7787
- id: null,
7788
- error: { code: -32700, message: "Parse error" }
7789
- })}
7790
- `
7791
- );
7792
- });
7793
- return;
7794
- }
7795
- if (parsed && typeof parsed === "object" && !Array.isArray(parsed) && !("method" in parsed) && typeof parsed.id === "string") {
7796
- const resp = parsed;
7797
- const pending = pendingClientResponses.get(resp.id);
7798
- if (pending) {
7799
- pendingClientResponses.delete(resp.id);
7800
- if (resp.error) {
7801
- pending.resolve({ action: "cancel" });
7802
- } else {
7803
- const resultObj = resp.result && typeof resp.result === "object" ? resp.result : {};
7804
- const action = resultObj.action === "accept" || resultObj.action === "decline" || resultObj.action === "cancel" ? resultObj.action : "cancel";
7805
- const content = resultObj.content && typeof resultObj.content === "object" && !Array.isArray(resultObj.content) ? resultObj.content : void 0;
7806
- pending.resolve({ action, content });
7807
- }
7808
- return;
7809
- }
7810
- }
7811
- chain = chain.then(async () => {
7812
- try {
7813
- const response = await server.handleMessage(parsed);
7814
- if (response) {
7815
- process.stdout.write(`${JSON.stringify(response)}
7816
- `);
7817
- }
7818
- } catch (err) {
7819
- const message = err instanceof Error ? err.message : String(err);
7820
- process.stderr.write(`[maskera-mcp] internal error: ${message}
7821
- `);
7822
- const maybeId = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed.id : void 0;
7823
- if (typeof maybeId === "string" || typeof maybeId === "number" || maybeId === null) {
7824
- process.stdout.write(
7825
- `${JSON.stringify({
7826
- jsonrpc: "2.0",
7827
- id: maybeId,
7828
- error: { code: -32603, message: "Internal error" }
7829
- })}
7830
- `
7831
- );
7832
- }
7833
- }
7834
- });
8088
+ transport.handleLine(line, (msg) => server.handleMessage(msg));
7835
8089
  });
7836
8090
  rl.on("close", () => {
7837
- for (const pending of pendingClientResponses.values()) {
7838
- pending.resolve({ action: "cancel" });
7839
- }
7840
- pendingClientResponses.clear();
8091
+ transport.close();
7841
8092
  });
7842
8093
  }
7843
8094
  var isGuardCommand = process.argv[2] === "guard";