pi-charset 0.1.7 → 0.1.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.
@@ -6,10 +6,12 @@ import { once } from "node:events";
6
6
  import { mkdir } from "node:fs/promises";
7
7
  import * as path from "node:path";
8
8
  import { findNearestConfig, getRuntimeDefaults } from "../config.js";
9
+ import { getIncidentRecorder } from "../diagnostics/incidents.js";
9
10
  import { containsNul } from "../encoding/classify.js";
10
11
  import { detectSupportedImageMimeType } from "../encoding/mime.js";
11
12
  import { compactRangeDiff, executeApplyPatch } from "../edit/apply-patch-core.js";
12
13
  import { EditError } from "../edit/diagnostics.js";
14
+ import { CharsetFault, isCharsetFault, REPORTABLE_FAULT_CODES, toMcpErrorEnvelope } from "../faults.js";
13
15
  import { formatUpdatedHashlines, planHashlineEdits } from "../edit/hashline.js";
14
16
  import { planPatchEdits } from "../edit/patch.js";
15
17
  import { resolveEditPath, resolveReadPathCompat } from "../edit/paths.js";
@@ -29,12 +31,77 @@ const MCP_INSTRUCTIONS = "pi-charset-mcp works out-of-the-box with zero configur
29
31
  "Use charset_read, charset_edit, charset_apply_patch, charset_write, charset_grep, charset_check, and charset_fix " +
30
32
  "for all text file operations to preserve exact encodings (GBK/GB18030/Big5/Shift_JIS/EUC-KR/UTF-16/UTF-8), BOM, and CRLF/LF line endings. " +
31
33
  "When multiple agents share a workspace, pass the `version` returned by charset_read as `expectedVersion` to charset_write/charset_edit.";
32
- class InputValidationError extends Error {
34
+ class InputValidationError extends CharsetFault {
33
35
  constructor(message) {
34
- super(`[INVALID_INPUT; not_applied] ${message}`);
36
+ super(`[INVALID_INPUT; not_applied] ${message}`, {
37
+ code: "INVALID_INPUT",
38
+ category: "input",
39
+ phase: "validate",
40
+ outcome: "not_applied",
41
+ retryable: false,
42
+ actionHint: "Fix the tool input parameters and retry.",
43
+ });
35
44
  this.name = "InputValidationError";
36
45
  }
37
46
  }
47
+ function mapClientName(raw) {
48
+ if (typeof raw !== "string")
49
+ return "generic";
50
+ const s = raw.trim().toLowerCase();
51
+ if (s.includes("codex"))
52
+ return "codex";
53
+ if (s.includes("antigravity-ide"))
54
+ return "antigravity-ide";
55
+ if (s.includes("antigravity-app"))
56
+ return "antigravity-app";
57
+ if (s.includes("antigravity") || s === "agy")
58
+ return "agy";
59
+ if (s.includes("claude"))
60
+ return "claude";
61
+ if (s.includes("cursor"))
62
+ return "cursor";
63
+ if (s.includes("windsurf"))
64
+ return "windsurf";
65
+ if (s === "pi")
66
+ return "pi";
67
+ return "generic";
68
+ }
69
+ function toolToOperation(toolName) {
70
+ switch (toolName) {
71
+ case "charset_read": return "read";
72
+ case "charset_write": return "write";
73
+ case "charset_edit": return "edit";
74
+ case "charset_apply_patch": return "apply_patch";
75
+ case "charset_grep": return "grep";
76
+ case "charset_check": return "check";
77
+ case "charset_fix": return "fix";
78
+ default: return "unknown";
79
+ }
80
+ }
81
+ function faultFromCaught(err) {
82
+ if (isCharsetFault(err))
83
+ return err.fault;
84
+ if (err instanceof EditError)
85
+ return err.toFaultMetadata();
86
+ const code = err?.code;
87
+ if (code === "ENOENT") {
88
+ return { code: "NOT_FOUND", category: "io", phase: "detect", outcome: "not_applied", retryable: false, actionHint: "Check the file path and retry." };
89
+ }
90
+ if (code === "EACCES" || code === "EPERM") {
91
+ return { code: "PERMISSION_DENIED", category: "io", phase: "validate", outcome: "not_applied", retryable: false, actionHint: "Check file permissions and retry." };
92
+ }
93
+ if (code === "EBUSY") {
94
+ return { code: "LOCK_BUSY", category: "io", phase: "commit", retryable: true, outcome: "not_applied", actionHint: "Close external editors locking the file and retry." };
95
+ }
96
+ return {
97
+ code: "INTERNAL",
98
+ category: "engine",
99
+ phase: "unknown",
100
+ outcome: "unknown",
101
+ retryable: false,
102
+ actionHint: "Re-read the target file to verify on-disk state; run `pi-charset feedback list` to inspect sanitized local diagnostics.",
103
+ };
104
+ }
38
105
  function coercePathArg(args) {
39
106
  const raw = typeof args.path === "string" ? args.path : typeof args.file_path === "string" ? args.file_path : undefined;
40
107
  return raw && raw.trim() ? raw : undefined;
@@ -103,6 +170,7 @@ export const MCP_TOOLS = [
103
170
  {
104
171
  name: "charset_read",
105
172
  description: "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.",
173
+ _meta: { "antigravity/alwaysLoad": true },
106
174
  inputSchema: {
107
175
  type: "object",
108
176
  additionalProperties: false,
@@ -144,6 +212,7 @@ export const MCP_TOOLS = [
144
212
  {
145
213
  name: "charset_edit",
146
214
  description: "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.",
215
+ _meta: { "antigravity/alwaysLoad": true },
147
216
  inputSchema: {
148
217
  type: "object",
149
218
  additionalProperties: false,
@@ -191,6 +260,7 @@ export const MCP_TOOLS = [
191
260
  {
192
261
  name: "charset_grep",
193
262
  description: "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.",
263
+ _meta: { "antigravity/alwaysLoad": true },
194
264
  inputSchema: {
195
265
  type: "object",
196
266
  additionalProperties: false,
@@ -271,7 +341,30 @@ function validateRpcEnvelope(raw) {
271
341
  }
272
342
  return { ok: true, req: obj };
273
343
  }
274
- export function createMcpDispatcher(defaultCwd, scope = createReadScope()) {
344
+ export function createMcpDispatcher(defaultCwd, scope = createReadScope(), opts) {
345
+ let activeClient = mapClientName(opts?.client);
346
+ const recordFault = (fault, operation) => {
347
+ if (!REPORTABLE_FAULT_CODES.has(fault.code))
348
+ return;
349
+ const rec = opts?.recorder ?? getIncidentRecorder(activeClient);
350
+ rec.record({
351
+ code: fault.code,
352
+ operation,
353
+ phase: fault.phase,
354
+ outcome: fault.outcome,
355
+ encoding: fault.encoding,
356
+ eol: fault.eol,
357
+ fileBytes: fault.fileBytes,
358
+ });
359
+ };
360
+ const failTool = (message, fault, operation) => {
361
+ recordFault(fault, operation);
362
+ return {
363
+ text: message,
364
+ isError: true,
365
+ structuredContent: toMcpErrorEnvelope(fault),
366
+ };
367
+ };
275
368
  const resolveCwd = (args) => {
276
369
  const cwdArg = coerceOptionalString(args, "cwd");
277
370
  return cwdArg && cwdArg.trim() ? path.resolve(defaultCwd, cwdArg) : defaultCwd;
@@ -281,7 +374,7 @@ export function createMcpDispatcher(defaultCwd, scope = createReadScope()) {
281
374
  if (name === "charset_read") {
282
375
  const pathArg = coercePathArg(args);
283
376
  if (!pathArg) {
284
- return { text: "[INVALID_INPUT; not_applied] path is required.", isError: true };
377
+ return failTool("[INVALID_INPUT; not_applied] path is required.", { code: "INVALID_INPUT", category: "input", phase: "validate", outcome: "not_applied", retryable: false, actionHint: "Pass path or file_path." }, "edit");
285
378
  }
286
379
  const outlineArg = coerceOptionalBoolean(args, "outline") ?? false;
287
380
  const hashlinesOpt = coerceOptionalBoolean(args, "hashlines");
@@ -297,18 +390,10 @@ export function createMcpDispatcher(defaultCwd, scope = createReadScope()) {
297
390
  notes.push(note); }, (m) => { meta = m; });
298
391
  const buf = await readOps.readFile(absPath);
299
392
  if (detectSupportedImageMimeType(buf)) {
300
- return {
301
- text: `[BINARY_IMAGE] ${absPath} (${buf.length}B) is an image file; use a binary/image reader.`,
302
- isError: true,
303
- structuredContent: { path: absPath, kind: "image", bytesOnDisk: buf.length },
304
- };
393
+ return failTool(`[BINARY_IMAGE] ${absPath} (${buf.length}B) is an image file; use a binary/image reader.`, { code: "BINARY_FILE", category: "policy", phase: "detect", outcome: "not_applied", retryable: false, actionHint: "Use an image/binary reader for image files.", fileBytes: buf.length }, "read");
305
394
  }
306
395
  if (containsNul(buf)) {
307
- return {
308
- text: `[BINARY_FILE] ${absPath} (${buf.length}B) contains NUL bytes and cannot be displayed as text.`,
309
- isError: true,
310
- structuredContent: { path: absPath, kind: "binary", bytesOnDisk: buf.length },
311
- };
396
+ return failTool(`[BINARY_FILE] ${absPath} (${buf.length}B) contains NUL bytes and cannot be displayed as text.`, { code: "BINARY_FILE", category: "policy", phase: "detect", outcome: "not_applied", retryable: false, actionHint: "Binary files are refused by text tools.", fileBytes: buf.length }, "read");
312
397
  }
313
398
  if (scope.epoch === epoch && observed)
314
399
  scope.baselines.set(observed.key, observed.version);
@@ -364,7 +449,7 @@ export function createMcpDispatcher(defaultCwd, scope = createReadScope()) {
364
449
  if (name === "charset_write") {
365
450
  const pathArg = coercePathArg(args);
366
451
  if (!pathArg || typeof args.content !== "string") {
367
- return { text: "[INVALID_INPUT; not_applied] path and content are required.", isError: true };
452
+ return failTool("[INVALID_INPUT; not_applied] path and content are required.", { code: "INVALID_INPUT", category: "input", phase: "validate", outcome: "not_applied", retryable: false, actionHint: "Pass path (or file_path) and content." }, "write");
368
453
  }
369
454
  const expectedVersion = coerceOptionalString(args, "expectedVersion");
370
455
  const absPath = resolveEditPath(pathArg, baseCwd);
@@ -379,7 +464,7 @@ export function createMcpDispatcher(defaultCwd, scope = createReadScope()) {
379
464
  if (name === "charset_edit") {
380
465
  const pathArg = coercePathArg(args);
381
466
  if (!pathArg) {
382
- return { text: "[INVALID_INPUT; not_applied] path is required.", isError: true };
467
+ return failTool("[INVALID_INPUT; not_applied] path is required.", { code: "INVALID_INPUT", category: "input", phase: "validate", outcome: "not_applied", retryable: false, actionHint: "Pass path or file_path." }, "edit");
383
468
  }
384
469
  const expectedVersion = coerceOptionalString(args, "expectedVersion");
385
470
  const presentModes = [
@@ -389,10 +474,7 @@ export function createMcpDispatcher(defaultCwd, scope = createReadScope()) {
389
474
  args.wholeFile !== undefined ? "wholeFile" : null,
390
475
  ].filter((m) => m !== null);
391
476
  if (presentModes.length !== 1) {
392
- return {
393
- text: "[INVALID_INPUT; not_applied] Supply exactly one of: edits, hashlines, patch, or wholeFile.",
394
- isError: true,
395
- };
477
+ return failTool("[INVALID_INPUT; not_applied] Supply exactly one of: edits, hashlines, patch, or wholeFile.", { code: "INVALID_INPUT", category: "input", phase: "validate", outcome: "not_applied", retryable: false, actionHint: "Pass exactly one edit payload: edits, hashlines, patch, or wholeFile." }, "edit");
396
478
  }
397
479
  const mode = presentModes[0];
398
480
  const editsArg = mode === "edits" ? coerceArrayArg(args.edits, "edits", true) : undefined;
@@ -438,7 +520,7 @@ export function createMcpDispatcher(defaultCwd, scope = createReadScope()) {
438
520
  }
439
521
  if (name === "charset_apply_patch") {
440
522
  if (typeof args.patch !== "string" || !args.patch.trim()) {
441
- return { text: "[INVALID_INPUT; not_applied] patch is required.", isError: true };
523
+ return failTool("[INVALID_INPUT; not_applied] patch is required.", { code: "INVALID_INPUT", category: "input", phase: "validate", outcome: "not_applied", retryable: false, actionHint: "Pass a non-empty patch string." }, "apply_patch");
442
524
  }
443
525
  const res = await executeApplyPatch(baseCwd, args.patch, scope, signal);
444
526
  return {
@@ -456,7 +538,7 @@ export function createMcpDispatcher(defaultCwd, scope = createReadScope()) {
456
538
  }
457
539
  if (name === "charset_grep") {
458
540
  if (typeof args.pattern !== "string" || !args.pattern) {
459
- return { text: "[INVALID_INPUT; not_applied] pattern is required.", isError: true };
541
+ return failTool("[INVALID_INPUT; not_applied] pattern is required.", { code: "INVALID_INPUT", category: "input", phase: "validate", outcome: "not_applied", retryable: false, actionHint: "Pass a non-empty search pattern." }, "grep");
460
542
  }
461
543
  const ignoreCase = coerceOptionalBoolean(args, "ignoreCase") ?? false;
462
544
  const literal = coerceOptionalBoolean(args, "literal") ?? false;
@@ -477,23 +559,13 @@ export function createMcpDispatcher(defaultCwd, scope = createReadScope()) {
477
559
  filesOnly,
478
560
  }, signal);
479
561
  if (!res) {
480
- return {
481
- text: "[GREP_UNAVAILABLE] ripgrep (rg) was not found or search path is invalid.",
482
- isError: true,
483
- structuredContent: { status: "failed", error: "ripgrep unavailable or invalid path" },
484
- };
562
+ return failTool("[GREP_UNAVAILABLE] ripgrep (rg) was not found or search path is invalid.", { code: "SEARCH_ENGINE_FAILED", category: "compatibility", phase: "search", outcome: "not_applied", retryable: false, actionHint: "Run `pi-charset doctor` to verify ripgrep availability and search path." }, "grep");
485
563
  }
486
564
  if (res.status === "failed") {
487
- return {
488
- text: res.text,
489
- isError: true,
490
- structuredContent: {
491
- status: "failed",
492
- error: res.error,
493
- searchedWith: res.searchedWith,
494
- failedPasses: res.failedPasses,
495
- },
496
- };
565
+ const isSyntax = /regex parse error/i.test(res.error ?? "");
566
+ return failTool(res.text, isSyntax
567
+ ? { code: "INVALID_INPUT", category: "input", phase: "search", outcome: "not_applied", retryable: false, actionHint: "Fix the regular expression or pass literal=true." }
568
+ : { code: "SEARCH_ENGINE_FAILED", category: "compatibility", phase: "search", outcome: "not_applied", retryable: true, actionHint: "Check search pattern and ripgrep status via `pi-charset doctor`." }, "grep");
497
569
  }
498
570
  return {
499
571
  text: res.text,
@@ -533,7 +605,7 @@ export function createMcpDispatcher(defaultCwd, scope = createReadScope()) {
533
605
  if (action === "normalize_eol") {
534
606
  const to = (toArg ?? "").toUpperCase();
535
607
  if (!pathArg || (to !== "CRLF" && to !== "LF")) {
536
- return { text: "[INVALID_INPUT; not_applied] normalize_eol requires path and to='CRLF'|'LF'.", isError: true };
608
+ return failTool("[INVALID_INPUT; not_applied] normalize_eol requires path and to='CRLF'|'LF'.", { code: "INVALID_INPUT", category: "input", phase: "validate", outcome: "not_applied", retryable: false, actionHint: "Pass path and to='CRLF' or to='LF'." }, "fix");
537
609
  }
538
610
  const absPath = resolveEditPath(pathArg, baseCwd);
539
611
  const res = await normalizeFileLineEndings(absPath, to, scope, dryRun);
@@ -545,7 +617,7 @@ export function createMcpDispatcher(defaultCwd, scope = createReadScope()) {
545
617
  }
546
618
  if (action === "convert") {
547
619
  if (!pathArg || !toArg || !toArg.trim()) {
548
- return { text: "[INVALID_INPUT; not_applied] convert requires path and to='<encoding>'.", isError: true };
620
+ return failTool("[INVALID_INPUT; not_applied] convert requires path and to='<encoding>'.", { code: "INVALID_INPUT", category: "input", phase: "validate", outcome: "not_applied", retryable: false, actionHint: "Pass path and target encoding in to." }, "fix");
549
621
  }
550
622
  const absPath = resolveEditPath(pathArg, baseCwd);
551
623
  const res = await convertFileEncoding(absPath, toArg, scope, { bom, dryRun });
@@ -571,7 +643,20 @@ export function createMcpDispatcher(defaultCwd, scope = createReadScope()) {
571
643
  return {
572
644
  text: res.reason,
573
645
  isError: true,
574
- structuredContent: { ok: false, action: "undo", dryRun, applied: false, reason: res.reason },
646
+ structuredContent: {
647
+ ...toMcpErrorEnvelope({
648
+ code: "CONFLICT",
649
+ category: "conflict",
650
+ phase: "rollback",
651
+ outcome: "not_applied",
652
+ retryable: false,
653
+ actionHint: "Inspect the file and session journal before retrying undo.",
654
+ }),
655
+ ok: false,
656
+ action: "undo",
657
+ dryRun,
658
+ reason: res.reason,
659
+ },
575
660
  };
576
661
  }
577
662
  const items = res.entries ?? [{ entry: res.entry, action: res.action }];
@@ -596,9 +681,9 @@ export function createMcpDispatcher(defaultCwd, scope = createReadScope()) {
596
681
  },
597
682
  };
598
683
  }
599
- return { text: `[INVALID_INPUT; not_applied] Unknown action "${action}".`, isError: true };
684
+ return failTool(`[INVALID_INPUT; not_applied] Unknown action "${action}".`, { code: "INVALID_INPUT", category: "input", phase: "validate", outcome: "not_applied", retryable: false, actionHint: "Use action: normalize_eol, convert, auto_fix_eol, or undo." }, "fix");
600
685
  }
601
- return { text: `Unknown tool: ${name}`, isError: true };
686
+ return failTool(`[INVALID_INPUT; not_applied] Unknown tool: ${name}`, { code: "INVALID_INPUT", category: "input", phase: "validate", outcome: "not_applied", retryable: false, actionHint: "Call tools/list to inspect available tool names." }, "unknown");
602
687
  }
603
688
  async function handleRequest(rawReq, signal) {
604
689
  const validated = validateRpcEnvelope(rawReq);
@@ -611,6 +696,10 @@ export function createMcpDispatcher(defaultCwd, scope = createReadScope()) {
611
696
  return null;
612
697
  }
613
698
  if (req.method === "initialize") {
699
+ if (!opts?.client) {
700
+ const clientInfo = req.params?.clientInfo;
701
+ activeClient = mapClientName(clientInfo?.name);
702
+ }
614
703
  const requested = typeof req.params?.protocolVersion === "string" ? req.params.protocolVersion : "2024-11-05";
615
704
  const protocolVersion = SUPPORTED_PROTOCOLS.has(requested) ? requested : "2024-11-05";
616
705
  return {
@@ -664,7 +753,9 @@ export function createMcpDispatcher(defaultCwd, scope = createReadScope()) {
664
753
  };
665
754
  }
666
755
  catch (err) {
667
- const msg = err instanceof EditError || err instanceof InputValidationError || err instanceof Error ? err.message : String(err);
756
+ const fault = faultFromCaught(err);
757
+ recordFault(fault, toolToOperation(toolName));
758
+ const msg = err instanceof EditError || err instanceof CharsetFault || err instanceof Error ? err.message : String(err);
668
759
  return isNotification
669
760
  ? null
670
761
  : {
@@ -672,6 +763,7 @@ export function createMcpDispatcher(defaultCwd, scope = createReadScope()) {
672
763
  id: id ?? null,
673
764
  result: {
674
765
  content: [{ type: "text", text: msg }],
766
+ structuredContent: toMcpErrorEnvelope(fault),
675
767
  isError: true,
676
768
  },
677
769
  };
@@ -688,8 +780,8 @@ export function createMcpDispatcher(defaultCwd, scope = createReadScope()) {
688
780
  return { handleRequest, scope };
689
781
  }
690
782
  /** Run the MCP server over stdin/stdout (supports newline-delimited JSON-RPC and Content-Length framing, backpressure drain, cancellation, and error isolation). */
691
- export function startMcpStdioServer(defaultCwd = process.cwd()) {
692
- const { handleRequest } = createMcpDispatcher(defaultCwd);
783
+ export function startMcpStdioServer(defaultCwd = process.cwd(), opts) {
784
+ const { handleRequest } = createMcpDispatcher(defaultCwd, createReadScope(), { client: opts?.client });
693
785
  let buf = Buffer.alloc(0);
694
786
  let useContentLength = false;
695
787
  let chain = Promise.resolve();
@@ -859,6 +951,7 @@ export function startMcpStdioServer(defaultCwd = process.cwd()) {
859
951
  if (rest)
860
952
  dispatchRaw(rest);
861
953
  void chain.finally(async () => {
954
+ await getIncidentRecorder(mapClientName(opts?.client)).flush(500).catch(() => undefined);
862
955
  await flushStdout();
863
956
  process.exitCode = 0;
864
957
  });