pi-charset 0.1.8 → 0.1.9

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.
@@ -53,8 +53,10 @@ interface CompiledDbcs {
53
53
  dfa: Int16Array[];
54
54
  asciiFast: boolean;
55
55
  gb18030: Gb18030Ranges | null;
56
+ decodeTables: number[][];
56
57
  encodeTable: (number[] | undefined)[];
57
- bmpEncodable: Uint8Array;
58
+ /** Lazily populated 8 KiB BMP round-trip encodability bitset (only needed on write/edit, never on read/classify). */
59
+ bmpEncodable: Uint8Array | null;
58
60
  hasEncodeSeq: boolean;
59
61
  asciiEncodable: boolean;
60
62
  /** Lazily populated flat BMP -> 1/2-byte DBCS table (0 means NUL or fallback to iconv). */
@@ -205,36 +207,28 @@ function compileDbcs(encoding: string): CompiledDbcs | null {
205
207
  }
206
208
  }
207
209
 
208
- const bmpEncodable = new Uint8Array(8192);
209
210
  let asciiIdentity = true;
210
- for (let cp = 0; cp < 0x10000; cp++) {
211
- if (cp >= 0xd800 && cp <= 0xdfff) continue;
212
- const bucket = encodeTable[cp >> 8];
213
- const mb = bucket !== undefined ? bucket[cp & 0xff] : UNASSIGNED;
211
+ let asciiEncodable = true;
212
+ const asciiBucket = encodeTable[0];
213
+ for (let cp = 0; cp < 128; cp++) {
214
+ const mb = asciiBucket !== undefined ? asciiBucket[cp] : UNASSIGNED;
215
+ if (mb !== cp) asciiIdentity = false;
214
216
  let ok = false;
215
217
  if (mb >= 0 && (gb18030 || mb < 0x1000000)) {
216
218
  ok = decodeMbCode(decodeTables, mb) === cp;
217
219
  } else if (mb === UNASSIGNED && gb18030) {
218
220
  ok = gb18030CodePointEncodable(cp, gb18030, encodeTable);
219
221
  }
220
- if (ok) bmpEncodable[cp >> 3] |= 1 << (cp & 7);
221
- if (cp < 128 && mb !== cp) asciiIdentity = false;
222
- }
223
-
224
- let asciiEncodable = true;
225
- for (let cp = 0; cp < 128; cp++) {
226
- if ((bmpEncodable[cp >> 3] & (1 << (cp & 7))) === 0) {
227
- asciiEncodable = false;
228
- break;
229
- }
222
+ if (!ok) asciiEncodable = false;
230
223
  }
231
224
 
232
225
  const compiled: CompiledDbcs = {
233
226
  dfa,
234
227
  asciiFast,
235
228
  gb18030,
229
+ decodeTables,
236
230
  encodeTable,
237
- bmpEncodable,
231
+ bmpEncodable: null,
238
232
  hasEncodeSeq,
239
233
  asciiEncodable,
240
234
  bmpToMb: null,
@@ -245,6 +239,26 @@ function compileDbcs(encoding: string): CompiledDbcs | null {
245
239
  return compiled;
246
240
  }
247
241
 
242
+ function getBmpEncodable(c: CompiledDbcs): Uint8Array {
243
+ if (c.bmpEncodable) return c.bmpEncodable;
244
+ const bits = new Uint8Array(8192);
245
+ const { encodeTable, decodeTables, gb18030 } = c;
246
+ for (let cp = 0; cp < 0x10000; cp++) {
247
+ if (cp >= 0xd800 && cp <= 0xdfff) continue;
248
+ const bucket = encodeTable[cp >> 8];
249
+ const mb = bucket !== undefined ? bucket[cp & 0xff] : UNASSIGNED;
250
+ let ok = false;
251
+ if (mb >= 0 && (gb18030 || mb < 0x1000000)) {
252
+ ok = decodeMbCode(decodeTables, mb) === cp;
253
+ } else if (mb === UNASSIGNED && gb18030) {
254
+ ok = gb18030CodePointEncodable(cp, gb18030, encodeTable);
255
+ }
256
+ if (ok) bits[cp >> 3] |= 1 << (cp & 7);
257
+ }
258
+ c.bmpEncodable = bits;
259
+ return bits;
260
+ }
261
+
248
262
  function getBmpEncodeTable(c: CompiledDbcs): Uint16Array {
249
263
  if (c.bmpToMb) return c.bmpToMb;
250
264
  const table = new Uint16Array(65536);
@@ -271,28 +285,56 @@ export function fastExactRoundTrip(buf: Buffer, encoding: string): boolean | nul
271
285
  const root = dfa[0];
272
286
  let node = root;
273
287
  const len = buf.length;
274
- const asciiFast = c.asciiFast;
275
288
  let icuSafe = c.icuDecoder !== null;
276
- for (let i = 0; i < len; i++) {
277
- const b = buf[i];
278
- if (asciiFast && node === root && b < 0x80) continue;
279
- const v = node[b];
280
- if (v === DFA_VALID) {
281
- node = root;
282
- } else if (v < 0) {
283
- node = dfa[-v];
284
- } else if (v === DFA_VALID_ICU_DIFF) {
285
- icuSafe = false;
286
- node = root;
287
- } else if (v === DFA_GB18030 && c.gb18030 && i >= 3) {
288
- icuSafe = false;
289
- const ptr = (buf[i - 3] - 0x81) * 12600 + (buf[i - 2] - 0x30) * 1260 + (buf[i - 1] - 0x81) * 10 + (b - 0x30);
290
- if (!gb18030PtrValid(ptr, c.gb18030, c.encodeTable)) return false;
291
- node = root;
292
- } else if (v === DFA_FALLBACK) {
293
- return null;
294
- } else {
295
- return false;
289
+ if (c.asciiFast) {
290
+ let i = 0;
291
+ while (i < len) {
292
+ if (node === root) {
293
+ while (i < len && buf[i] < 0x80) i++;
294
+ if (i >= len) break;
295
+ }
296
+ const b = buf[i];
297
+ const v = node[b];
298
+ if (v === DFA_VALID) {
299
+ node = root;
300
+ } else if (v < 0) {
301
+ node = dfa[-v];
302
+ } else if (v === DFA_VALID_ICU_DIFF) {
303
+ icuSafe = false;
304
+ node = root;
305
+ } else if (v === DFA_GB18030 && c.gb18030 && i >= 3) {
306
+ icuSafe = false;
307
+ const ptr = (buf[i - 3] - 0x81) * 12600 + (buf[i - 2] - 0x30) * 1260 + (buf[i - 1] - 0x81) * 10 + (b - 0x30);
308
+ if (!gb18030PtrValid(ptr, c.gb18030, c.encodeTable)) return false;
309
+ node = root;
310
+ } else if (v === DFA_FALLBACK) {
311
+ return null;
312
+ } else {
313
+ return false;
314
+ }
315
+ i++;
316
+ }
317
+ } else {
318
+ for (let i = 0; i < len; i++) {
319
+ const b = buf[i];
320
+ const v = node[b];
321
+ if (v === DFA_VALID) {
322
+ node = root;
323
+ } else if (v < 0) {
324
+ node = dfa[-v];
325
+ } else if (v === DFA_VALID_ICU_DIFF) {
326
+ icuSafe = false;
327
+ node = root;
328
+ } else if (v === DFA_GB18030 && c.gb18030 && i >= 3) {
329
+ icuSafe = false;
330
+ const ptr = (buf[i - 3] - 0x81) * 12600 + (buf[i - 2] - 0x30) * 1260 + (buf[i - 1] - 0x81) * 10 + (b - 0x30);
331
+ if (!gb18030PtrValid(ptr, c.gb18030, c.encodeTable)) return false;
332
+ node = root;
333
+ } else if (v === DFA_FALLBACK) {
334
+ return null;
335
+ } else {
336
+ return false;
337
+ }
296
338
  }
297
339
  }
298
340
  if (node !== root) return false;
@@ -428,7 +470,7 @@ export function fastCanEncodeAll(text: string, encoding: string): boolean | null
428
470
  const c = compileDbcs(encoding);
429
471
  if (!c || c.hasEncodeSeq) return null;
430
472
  if (c.asciiEncodable && !NON_ASCII_STR.test(text)) return true;
431
- const bits = c.bmpEncodable;
473
+ const bits = getBmpEncodable(c);
432
474
  const asciiOk = c.asciiEncodable;
433
475
  const len = text.length;
434
476
  for (let i = 0; i < len; i++) {
package/src/mcp/server.ts CHANGED
@@ -3,7 +3,6 @@
3
3
  // expectedVersion concurrency, atomic Windows retries, 4 edit modes, multi-file apply_patch, multi-encoding grep,
4
4
  // bounded outline/ranges/window views, controlled repair, and zero-side-effect dry-run undo).
5
5
  import { once } from "node:events";
6
- import { mkdir } from "node:fs/promises";
7
6
  import * as path from "node:path";
8
7
  import { findNearestConfig, getRuntimeDefaults } from "../config";
9
8
  import { getIncidentRecorder, type IncidentRecorder } from "../diagnostics/incidents";
@@ -43,6 +42,9 @@ const SUPPORTED_PROTOCOLS = new Set(["2025-06-18", "2025-03-26", "2024-11-05"]);
43
42
  const DEFAULT_READ_LIMIT = 2000;
44
43
  const MAX_READ_BYTES = 50 * 1024;
45
44
  const MAX_PENDING_REQUESTS = 64;
45
+ const MAX_CONCURRENT_READS = 8;
46
+ const MAX_FRAME_BYTES = 32 * 1024 * 1024;
47
+ const READ_ONLY_TOOLS = new Set(["charset_read", "charset_grep", "charset_check"]);
46
48
  const MCP_INSTRUCTIONS =
47
49
  "pi-charset-mcp works out-of-the-box with zero configuration (no .pi-charset.json needed). " +
48
50
  "Use charset_read, charset_edit, charset_apply_patch, charset_write, charset_grep, charset_check, and charset_fix " +
@@ -195,6 +197,13 @@ export const MCP_TOOLS = [
195
197
  name: "charset_read",
196
198
  description:
197
199
  "Read a text file preserving exact encoding/BOM/EOL (GBK, GB18030, Big5, Shift_JIS, EUC-KR, UTF-16, UTF-8) and return its SHA-1 version for safe edits. Supports outline=true, ranges=[[start,end],...], offset/limit, and hashlines=true. Output is strictly bounded.",
200
+ annotations: {
201
+ title: "Read File (Encoding-Safe)",
202
+ readOnlyHint: true,
203
+ destructiveHint: false,
204
+ idempotentHint: true,
205
+ openWorldHint: false,
206
+ },
198
207
  _meta: { "antigravity/alwaysLoad": true },
199
208
  inputSchema: {
200
209
  type: "object",
@@ -219,6 +228,13 @@ export const MCP_TOOLS = [
219
228
  name: "charset_write",
220
229
  description:
221
230
  "Write a file through pi-charset's Gate 1/2/3 safety pipeline (preserves existing encoding/BOM/EOL or inherits sibling/config encoding, atomic temp-file replace with Windows lock retries, SHA-1 baseline & optional expectedVersion check, and session undo).",
231
+ annotations: {
232
+ title: "Write File (Encoding-Safe)",
233
+ readOnlyHint: false,
234
+ destructiveHint: false,
235
+ idempotentHint: true,
236
+ openWorldHint: false,
237
+ },
222
238
  inputSchema: {
223
239
  type: "object",
224
240
  additionalProperties: false,
@@ -239,6 +255,13 @@ export const MCP_TOOLS = [
239
255
  name: "charset_edit",
240
256
  description:
241
257
  "Edit a file atomically while preserving its exact encoding, BOM, line endings, and untouched bytes. Supply exactly one of: edits ([{oldText, newText}]), hashlines (anchored replace/delete/insert_after/insert_before), patch (unified/Codex/Aider diff), or wholeFile.",
258
+ annotations: {
259
+ title: "Edit File (Encoding-Safe)",
260
+ readOnlyHint: false,
261
+ destructiveHint: false,
262
+ idempotentHint: false,
263
+ openWorldHint: false,
264
+ },
242
265
  _meta: { "antigravity/alwaysLoad": true },
243
266
  inputSchema: {
244
267
  type: "object",
@@ -275,6 +298,13 @@ export const MCP_TOOLS = [
275
298
  name: "charset_apply_patch",
276
299
  description:
277
300
  "Pre-validate and apply a multi-file patch (Codex `*** Begin Patch` with Update/Hashline/Add/Delete/Move, Aider multi-file SEARCH/REPLACE, or unified `diff --git`) across mixed GBK/UTF-8 files with deadlock-free path locking and batch undo.",
301
+ annotations: {
302
+ title: "Apply Multi-File Patch (Encoding-Safe)",
303
+ readOnlyHint: false,
304
+ destructiveHint: true,
305
+ idempotentHint: false,
306
+ openWorldHint: false,
307
+ },
278
308
  inputSchema: {
279
309
  type: "object",
280
310
  additionalProperties: false,
@@ -289,6 +319,13 @@ export const MCP_TOOLS = [
289
319
  name: "charset_grep",
290
320
  description:
291
321
  "Search files across UTF-8, GBK, GB18030, Big5, Shift_JIS, EUC-KR, EUC-JP, and UTF-16 using encoding-verified multi-pass ripgrep. Supports filesOnly=true and hashlines=true. Propagates ripgrep errors explicitly.",
322
+ annotations: {
323
+ title: "Search Files (Multi-Encoding)",
324
+ readOnlyHint: true,
325
+ destructiveHint: false,
326
+ idempotentHint: true,
327
+ openWorldHint: false,
328
+ },
292
329
  _meta: { "antigravity/alwaysLoad": true },
293
330
  inputSchema: {
294
331
  type: "object",
@@ -313,6 +350,13 @@ export const MCP_TOOLS = [
313
350
  name: "charset_check",
314
351
  description:
315
352
  "Read-only encoding diagnostics: pass `path` to explain a single file's byte verdict, matched rule, BOM/EOL, and write status; omit `path` to run a workspace health scan for mixed line endings and damaged/unknown files.",
353
+ annotations: {
354
+ title: "Check Encoding & Health",
355
+ readOnlyHint: true,
356
+ destructiveHint: false,
357
+ idempotentHint: true,
358
+ openWorldHint: false,
359
+ },
316
360
  inputSchema: {
317
361
  type: "object",
318
362
  additionalProperties: false,
@@ -327,6 +371,13 @@ export const MCP_TOOLS = [
327
371
  name: "charset_fix",
328
372
  description:
329
373
  "Controlled, Gate-1/2-verified encoding maintenance & undo: normalize_eol (single file CRLF/LF), auto_fix_eol (batch mixed-EOL repair to majority style), convert (verified transcoding with BOM control), or undo (revert latest session write/batch; supports zero-side-effect dryRun=true preview).",
374
+ annotations: {
375
+ title: "Fix Encoding / EOL / Undo",
376
+ readOnlyHint: false,
377
+ destructiveHint: false,
378
+ idempotentHint: false,
379
+ openWorldHint: false,
380
+ },
330
381
  inputSchema: {
331
382
  type: "object",
332
383
  additionalProperties: false,
@@ -419,7 +470,7 @@ export function createMcpDispatcher(
419
470
  return failTool(
420
471
  "[INVALID_INPUT; not_applied] path is required.",
421
472
  { code: "INVALID_INPUT", category: "input", phase: "validate", outcome: "not_applied", retryable: false, actionHint: "Pass path or file_path." },
422
- "edit",
473
+ "read",
423
474
  );
424
475
  }
425
476
  const outlineArg = coerceOptionalBoolean(args, "outline") ?? false;
@@ -522,7 +573,7 @@ export function createMcpDispatcher(
522
573
  }
523
574
  const expectedVersion = coerceOptionalString(args, "expectedVersion");
524
575
  const absPath = resolveEditPath(pathArg, baseCwd);
525
- await mkdir(path.dirname(absPath), { recursive: true });
576
+ // Parent directory creation happens inside writeFileDetailed ONLY after expectedVersion + Gate 1/3 pass.
526
577
  const outcome = await writeFileDetailed(absPath, args.content, scope, expectedVersion);
527
578
  const suffix = notesToSuffix(drainEncodingNotes(absPath));
528
579
  return {
@@ -901,13 +952,33 @@ export function createMcpDispatcher(
901
952
  return { handleRequest, scope };
902
953
  }
903
954
 
904
- /** Run the MCP server over stdin/stdout (supports newline-delimited JSON-RPC and Content-Length framing, backpressure drain, cancellation, and error isolation). */
955
+ function isConcurrentReadOnlyMessage(parsed: unknown): boolean {
956
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return false;
957
+ const req = parsed as Record<string, unknown>;
958
+ const method = req.method;
959
+ if (method === "ping" || method === "tools/list" || method === "resources/list" || method === "resources/templates/list" || method === "prompts/list") {
960
+ return true;
961
+ }
962
+ if (method === "tools/call") {
963
+ const params = req.params as Record<string, unknown> | undefined;
964
+ return typeof params?.name === "string" && READ_ONLY_TOOLS.has(params.name);
965
+ }
966
+ return false;
967
+ }
968
+
969
+ /** Run the MCP server over stdin/stdout (supports newline-delimited JSON-RPC and Content-Length framing, concurrent read-only dispatch, backpressure drain, cancellation, and error isolation). */
905
970
  export function startMcpStdioServer(defaultCwd = process.cwd(), opts?: { client?: string }): void {
906
971
  const { handleRequest } = createMcpDispatcher(defaultCwd, createReadScope(), { client: opts?.client });
907
972
  let buf: Buffer = Buffer.alloc(0);
908
973
  let useContentLength = false;
909
- let chain = Promise.resolve();
974
+ let sendChain = Promise.resolve();
975
+ let mutatingChain = Promise.resolve();
976
+ let initBarrier = Promise.resolve();
910
977
  let pendingCount = 0;
978
+ let activeReads = 0;
979
+ const readWaiters: Array<() => void> = [];
980
+ const activeReadPromises = new Set<Promise<void>>();
981
+ const activeTasks = new Set<Promise<void>>();
911
982
  const inFlight = new Map<string, AbortController>();
912
983
 
913
984
  let stdoutClosed = false;
@@ -918,24 +989,49 @@ export function startMcpStdioServer(defaultCwd = process.cwd(), opts?: { client?
918
989
  }
919
990
  });
920
991
 
921
- const send = async (payload: JsonRpcResponse | JsonRpcResponse[]): Promise<void> => {
922
- if (stdoutClosed || process.stdout.destroyed) return;
923
- const json = JSON.stringify(payload);
924
- const frame = useContentLength
925
- ? `Content-Length: ${Buffer.byteLength(json, "utf8")}\r\n\r\n${json}`
926
- : `${json}\n`;
927
- if (!process.stdout.write(frame)) {
928
- await once(process.stdout, "drain").catch(() => undefined);
929
- }
992
+ const send = (payload: JsonRpcResponse | JsonRpcResponse[]): Promise<void> => {
993
+ sendChain = sendChain.then(async () => {
994
+ if (stdoutClosed || process.stdout.destroyed) return;
995
+ const json = JSON.stringify(payload);
996
+ const frame = useContentLength
997
+ ? `Content-Length: ${Buffer.byteLength(json, "utf8")}\r\n\r\n${json}`
998
+ : `${json}\n`;
999
+ if (!process.stdout.write(frame)) {
1000
+ await once(process.stdout, "drain").catch(() => undefined);
1001
+ }
1002
+ });
1003
+ return sendChain;
930
1004
  };
931
1005
 
932
1006
  const flushStdout = async (): Promise<void> => {
1007
+ await sendChain;
933
1008
  if (stdoutClosed || process.stdout.destroyed) return;
934
1009
  await new Promise<void>((resolve) => {
935
1010
  process.stdout.write("", () => resolve());
936
1011
  });
937
1012
  };
938
1013
 
1014
+ const acquireReadSlot = async (): Promise<void> => {
1015
+ if (activeReads < MAX_CONCURRENT_READS) {
1016
+ activeReads++;
1017
+ return;
1018
+ }
1019
+ await new Promise<void>((resolve) => readWaiters.push(resolve));
1020
+ activeReads++;
1021
+ };
1022
+
1023
+ const releaseReadSlot = (): void => {
1024
+ activeReads--;
1025
+ const next = readWaiters.shift();
1026
+ if (next) next();
1027
+ };
1028
+
1029
+ const trackTask = (p: Promise<void>): Promise<void> => {
1030
+ activeTasks.add(p);
1031
+ p.finally(() => activeTasks.delete(p));
1032
+ return p;
1033
+ };
1034
+
939
1035
  const cancelIfNotification = (parsed: unknown): boolean => {
940
1036
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return false;
941
1037
  const obj = parsed as Record<string, unknown>;
@@ -975,7 +1071,7 @@ export function startMcpStdioServer(defaultCwd = process.cwd(), opts?: { client?
975
1071
  try {
976
1072
  parsed = JSON.parse(raw);
977
1073
  } catch (e) {
978
- chain = chain.then(() => send({ jsonrpc: "2.0", id: null, error: { code: -32700, message: `Parse error: ${(e as Error).message}` } }));
1074
+ void trackTask(send({ jsonrpc: "2.0", id: null, error: { code: -32700, message: `Parse error: ${(e as Error).message}` } }));
979
1075
  return;
980
1076
  }
981
1077
  // Handle cancellation notifications immediately out-of-band so they can abort an in-flight call.
@@ -987,13 +1083,47 @@ export function startMcpStdioServer(defaultCwd = process.cwd(), opts?: { client?
987
1083
  (typeof (parsed as Record<string, unknown>).id === "string" || typeof (parsed as Record<string, unknown>).id === "number")
988
1084
  ? ((parsed as Record<string, unknown>).id as string | number)
989
1085
  : null;
990
- chain = chain.then(() => send({ jsonrpc: "2.0", id: idVal, error: { code: -32000, message: `Server busy: queue limit (${MAX_PENDING_REQUESTS}) exceeded.` } }));
1086
+ void trackTask(send({ jsonrpc: "2.0", id: idVal, error: { code: -32000, message: `Server busy: queue limit (${MAX_PENDING_REQUESTS}) exceeded.` } }));
991
1087
  return;
992
1088
  }
993
1089
 
994
1090
  pendingCount++;
995
- chain = chain.then(async () => {
1091
+
1092
+ // Run read-only tool calls & metadata queries concurrently (after initialize and any prior mutations) so multi-file
1093
+ // reads/greps do not head-of-line block each other and can be cancelled out-of-band immediately.
1094
+ if (isConcurrentReadOnlyMessage(parsed)) {
1095
+ const waitForMutations = mutatingChain;
1096
+ const waitForInit = initBarrier;
1097
+ const readPromise = (async () => {
1098
+ try {
1099
+ await waitForInit;
1100
+ await waitForMutations;
1101
+ await acquireReadSlot();
1102
+ try {
1103
+ const res = await runSingle(parsed);
1104
+ if (res) await send(res);
1105
+ } finally {
1106
+ releaseReadSlot();
1107
+ }
1108
+ } catch (err) {
1109
+ await send({ jsonrpc: "2.0", id: null, error: { code: -32603, message: `Internal error: ${err instanceof Error ? err.message : String(err)}` } });
1110
+ } finally {
1111
+ pendingCount--;
1112
+ }
1113
+ })();
1114
+ activeReadPromises.add(readPromise);
1115
+ readPromise.finally(() => activeReadPromises.delete(readPromise));
1116
+ void trackTask(readPromise);
1117
+ return;
1118
+ }
1119
+
1120
+ const isInit = !Array.isArray(parsed) && parsed !== null && typeof parsed === "object" && (parsed as Record<string, unknown>).method === "initialize";
1121
+ const waitForInit = initBarrier;
1122
+ const waitForReads = [...activeReadPromises];
1123
+ const task = mutatingChain.then(async () => {
996
1124
  try {
1125
+ if (!isInit) await waitForInit;
1126
+ if (waitForReads.length > 0) await Promise.allSettled(waitForReads);
997
1127
  if (Array.isArray(parsed)) {
998
1128
  if (parsed.length === 0) {
999
1129
  await send({ jsonrpc: "2.0", id: null, error: { code: -32600, message: "Invalid Request: empty batch." } });
@@ -1016,6 +1146,9 @@ export function startMcpStdioServer(defaultCwd = process.cwd(), opts?: { client?
1016
1146
  pendingCount--;
1017
1147
  }
1018
1148
  });
1149
+ mutatingChain = task;
1150
+ if (isInit) initBarrier = task;
1151
+ void trackTask(task);
1019
1152
  };
1020
1153
 
1021
1154
  const drain = () => {
@@ -1026,7 +1159,7 @@ export function startMcpStdioServer(defaultCwd = process.cwd(), opts?: { client?
1026
1159
  if (buf.length === 0) break;
1027
1160
 
1028
1161
  const head = buf.subarray(0, Math.min(buf.length, 32)).toString("ascii");
1029
- if (/^content-length:/i.test(head)) {
1162
+ if (/^(?:content-length|content-type):/i.test(head)) {
1030
1163
  useContentLength = true;
1031
1164
  const sep = buf.indexOf("\r\n\r\n");
1032
1165
  const sepAlt = sep === -1 ? buf.indexOf("\n\n") : -1;
@@ -1035,8 +1168,17 @@ export function startMcpStdioServer(defaultCwd = process.cwd(), opts?: { client?
1035
1168
  if (headerEnd === -1) break;
1036
1169
  const headerText = buf.subarray(0, headerEnd).toString("ascii");
1037
1170
  const m = /content-length:\s*(\d+)/i.exec(headerText);
1038
- if (!m) { buf = buf.subarray(headerEnd + sepLen); continue; }
1171
+ if (!m) {
1172
+ buf = buf.subarray(headerEnd + sepLen);
1173
+ void trackTask(send({ jsonrpc: "2.0", id: null, error: { code: -32600, message: "Invalid Request: missing Content-Length header." } }));
1174
+ continue;
1175
+ }
1039
1176
  const bodyLen = Number(m[1]);
1177
+ if (!Number.isSafeInteger(bodyLen) || bodyLen < 0 || bodyLen > MAX_FRAME_BYTES) {
1178
+ buf = Buffer.alloc(0);
1179
+ void trackTask(send({ jsonrpc: "2.0", id: null, error: { code: -32600, message: `Invalid Request: Content-Length (${m[1]}) out of allowed bounds.` } }));
1180
+ break;
1181
+ }
1040
1182
  const bodyStart = headerEnd + sepLen;
1041
1183
  if (buf.length < bodyStart + bodyLen) break;
1042
1184
  const body = buf.subarray(bodyStart, bodyStart + bodyLen).toString("utf8");
@@ -1060,10 +1202,13 @@ export function startMcpStdioServer(defaultCwd = process.cwd(), opts?: { client?
1060
1202
  process.stdin.on("end", () => {
1061
1203
  const rest = buf.toString("utf8").trim();
1062
1204
  if (rest) dispatchRaw(rest);
1063
- void chain.finally(async () => {
1205
+ void (async () => {
1206
+ while (activeTasks.size > 0) {
1207
+ await Promise.allSettled([...activeTasks]);
1208
+ }
1064
1209
  await getIncidentRecorder(mapClientName(opts?.client)).flush(500).catch(() => undefined);
1065
1210
  await flushStdout();
1066
1211
  process.exitCode = 0;
1067
- });
1212
+ })();
1068
1213
  });
1069
1214
  }
package/src/operations.ts CHANGED
@@ -723,6 +723,8 @@ async function writeEncodedLocked(
723
723
  const verify = plan.rule?.verifyWrite !== false;
724
724
  const existed = prevRaw !== null;
725
725
  try {
726
+ // Ensure parent directory exists ONLY after all validation gates (expectedVersion, Gate 3, Gate 1, STALE_READ) pass.
727
+ if (!existed) await mkdir(path.dirname(absPath), { recursive: true });
726
728
  await seam.writeBytes(absPath, bytes, prevRaw);
727
729
  } catch (e) {
728
730
  if (e instanceof CharsetFault || e instanceof EditError) throw e;