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.
- package/CHANGELOG.md +17 -0
- package/CHANGELOG.zh-CN.md +17 -0
- package/dist/config.js +14 -0
- package/dist/encoding/classify.js +26 -5
- package/dist/encoding/fast-codec.js +95 -44
- package/dist/mcp/server.js +166 -21
- package/dist/operations.js +3 -0
- package/dist/setup/adapters.js +128 -27
- package/dist/version.js +1 -1
- package/package.json +1 -1
- package/src/config.ts +13 -0
- package/src/encoding/classify.ts +25 -5
- package/src/encoding/fast-codec.ts +81 -39
- package/src/mcp/server.ts +166 -21
- package/src/operations.ts +2 -0
- package/src/setup/adapters.ts +111 -23
- package/src/version.ts +1 -1
- package/tools/pi-charset-cli.mjs +1 -0
package/dist/mcp/server.js
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.js";
|
|
9
8
|
import { getIncidentRecorder } from "../diagnostics/incidents.js";
|
|
@@ -27,6 +26,9 @@ const SUPPORTED_PROTOCOLS = new Set(["2025-06-18", "2025-03-26", "2024-11-05"]);
|
|
|
27
26
|
const DEFAULT_READ_LIMIT = 2000;
|
|
28
27
|
const MAX_READ_BYTES = 50 * 1024;
|
|
29
28
|
const MAX_PENDING_REQUESTS = 64;
|
|
29
|
+
const MAX_CONCURRENT_READS = 8;
|
|
30
|
+
const MAX_FRAME_BYTES = 32 * 1024 * 1024;
|
|
31
|
+
const READ_ONLY_TOOLS = new Set(["charset_read", "charset_grep", "charset_check"]);
|
|
30
32
|
const MCP_INSTRUCTIONS = "pi-charset-mcp works out-of-the-box with zero configuration (no .pi-charset.json needed). " +
|
|
31
33
|
"Use charset_read, charset_edit, charset_apply_patch, charset_write, charset_grep, charset_check, and charset_fix " +
|
|
32
34
|
"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. " +
|
|
@@ -170,6 +172,13 @@ export const MCP_TOOLS = [
|
|
|
170
172
|
{
|
|
171
173
|
name: "charset_read",
|
|
172
174
|
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.",
|
|
175
|
+
annotations: {
|
|
176
|
+
title: "Read File (Encoding-Safe)",
|
|
177
|
+
readOnlyHint: true,
|
|
178
|
+
destructiveHint: false,
|
|
179
|
+
idempotentHint: true,
|
|
180
|
+
openWorldHint: false,
|
|
181
|
+
},
|
|
173
182
|
_meta: { "antigravity/alwaysLoad": true },
|
|
174
183
|
inputSchema: {
|
|
175
184
|
type: "object",
|
|
@@ -193,6 +202,13 @@ export const MCP_TOOLS = [
|
|
|
193
202
|
{
|
|
194
203
|
name: "charset_write",
|
|
195
204
|
description: "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).",
|
|
205
|
+
annotations: {
|
|
206
|
+
title: "Write File (Encoding-Safe)",
|
|
207
|
+
readOnlyHint: false,
|
|
208
|
+
destructiveHint: false,
|
|
209
|
+
idempotentHint: true,
|
|
210
|
+
openWorldHint: false,
|
|
211
|
+
},
|
|
196
212
|
inputSchema: {
|
|
197
213
|
type: "object",
|
|
198
214
|
additionalProperties: false,
|
|
@@ -212,6 +228,13 @@ export const MCP_TOOLS = [
|
|
|
212
228
|
{
|
|
213
229
|
name: "charset_edit",
|
|
214
230
|
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.",
|
|
231
|
+
annotations: {
|
|
232
|
+
title: "Edit File (Encoding-Safe)",
|
|
233
|
+
readOnlyHint: false,
|
|
234
|
+
destructiveHint: false,
|
|
235
|
+
idempotentHint: false,
|
|
236
|
+
openWorldHint: false,
|
|
237
|
+
},
|
|
215
238
|
_meta: { "antigravity/alwaysLoad": true },
|
|
216
239
|
inputSchema: {
|
|
217
240
|
type: "object",
|
|
@@ -247,6 +270,13 @@ export const MCP_TOOLS = [
|
|
|
247
270
|
{
|
|
248
271
|
name: "charset_apply_patch",
|
|
249
272
|
description: "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.",
|
|
273
|
+
annotations: {
|
|
274
|
+
title: "Apply Multi-File Patch (Encoding-Safe)",
|
|
275
|
+
readOnlyHint: false,
|
|
276
|
+
destructiveHint: true,
|
|
277
|
+
idempotentHint: false,
|
|
278
|
+
openWorldHint: false,
|
|
279
|
+
},
|
|
250
280
|
inputSchema: {
|
|
251
281
|
type: "object",
|
|
252
282
|
additionalProperties: false,
|
|
@@ -260,6 +290,13 @@ export const MCP_TOOLS = [
|
|
|
260
290
|
{
|
|
261
291
|
name: "charset_grep",
|
|
262
292
|
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.",
|
|
293
|
+
annotations: {
|
|
294
|
+
title: "Search Files (Multi-Encoding)",
|
|
295
|
+
readOnlyHint: true,
|
|
296
|
+
destructiveHint: false,
|
|
297
|
+
idempotentHint: true,
|
|
298
|
+
openWorldHint: false,
|
|
299
|
+
},
|
|
263
300
|
_meta: { "antigravity/alwaysLoad": true },
|
|
264
301
|
inputSchema: {
|
|
265
302
|
type: "object",
|
|
@@ -283,6 +320,13 @@ export const MCP_TOOLS = [
|
|
|
283
320
|
{
|
|
284
321
|
name: "charset_check",
|
|
285
322
|
description: "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.",
|
|
323
|
+
annotations: {
|
|
324
|
+
title: "Check Encoding & Health",
|
|
325
|
+
readOnlyHint: true,
|
|
326
|
+
destructiveHint: false,
|
|
327
|
+
idempotentHint: true,
|
|
328
|
+
openWorldHint: false,
|
|
329
|
+
},
|
|
286
330
|
inputSchema: {
|
|
287
331
|
type: "object",
|
|
288
332
|
additionalProperties: false,
|
|
@@ -296,6 +340,13 @@ export const MCP_TOOLS = [
|
|
|
296
340
|
{
|
|
297
341
|
name: "charset_fix",
|
|
298
342
|
description: "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).",
|
|
343
|
+
annotations: {
|
|
344
|
+
title: "Fix Encoding / EOL / Undo",
|
|
345
|
+
readOnlyHint: false,
|
|
346
|
+
destructiveHint: false,
|
|
347
|
+
idempotentHint: false,
|
|
348
|
+
openWorldHint: false,
|
|
349
|
+
},
|
|
299
350
|
inputSchema: {
|
|
300
351
|
type: "object",
|
|
301
352
|
additionalProperties: false,
|
|
@@ -374,7 +425,7 @@ export function createMcpDispatcher(defaultCwd, scope = createReadScope(), opts)
|
|
|
374
425
|
if (name === "charset_read") {
|
|
375
426
|
const pathArg = coercePathArg(args);
|
|
376
427
|
if (!pathArg) {
|
|
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." }, "
|
|
428
|
+
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." }, "read");
|
|
378
429
|
}
|
|
379
430
|
const outlineArg = coerceOptionalBoolean(args, "outline") ?? false;
|
|
380
431
|
const hashlinesOpt = coerceOptionalBoolean(args, "hashlines");
|
|
@@ -453,7 +504,7 @@ export function createMcpDispatcher(defaultCwd, scope = createReadScope(), opts)
|
|
|
453
504
|
}
|
|
454
505
|
const expectedVersion = coerceOptionalString(args, "expectedVersion");
|
|
455
506
|
const absPath = resolveEditPath(pathArg, baseCwd);
|
|
456
|
-
|
|
507
|
+
// Parent directory creation happens inside writeFileDetailed ONLY after expectedVersion + Gate 1/3 pass.
|
|
457
508
|
const outcome = await writeFileDetailed(absPath, args.content, scope, expectedVersion);
|
|
458
509
|
const suffix = notesToSuffix(drainEncodingNotes(absPath));
|
|
459
510
|
return {
|
|
@@ -779,13 +830,33 @@ export function createMcpDispatcher(defaultCwd, scope = createReadScope(), opts)
|
|
|
779
830
|
}
|
|
780
831
|
return { handleRequest, scope };
|
|
781
832
|
}
|
|
782
|
-
|
|
833
|
+
function isConcurrentReadOnlyMessage(parsed) {
|
|
834
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
835
|
+
return false;
|
|
836
|
+
const req = parsed;
|
|
837
|
+
const method = req.method;
|
|
838
|
+
if (method === "ping" || method === "tools/list" || method === "resources/list" || method === "resources/templates/list" || method === "prompts/list") {
|
|
839
|
+
return true;
|
|
840
|
+
}
|
|
841
|
+
if (method === "tools/call") {
|
|
842
|
+
const params = req.params;
|
|
843
|
+
return typeof params?.name === "string" && READ_ONLY_TOOLS.has(params.name);
|
|
844
|
+
}
|
|
845
|
+
return false;
|
|
846
|
+
}
|
|
847
|
+
/** 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). */
|
|
783
848
|
export function startMcpStdioServer(defaultCwd = process.cwd(), opts) {
|
|
784
849
|
const { handleRequest } = createMcpDispatcher(defaultCwd, createReadScope(), { client: opts?.client });
|
|
785
850
|
let buf = Buffer.alloc(0);
|
|
786
851
|
let useContentLength = false;
|
|
787
|
-
let
|
|
852
|
+
let sendChain = Promise.resolve();
|
|
853
|
+
let mutatingChain = Promise.resolve();
|
|
854
|
+
let initBarrier = Promise.resolve();
|
|
788
855
|
let pendingCount = 0;
|
|
856
|
+
let activeReads = 0;
|
|
857
|
+
const readWaiters = [];
|
|
858
|
+
const activeReadPromises = new Set();
|
|
859
|
+
const activeTasks = new Set();
|
|
789
860
|
const inFlight = new Map();
|
|
790
861
|
let stdoutClosed = false;
|
|
791
862
|
process.stdout.on("error", (err) => {
|
|
@@ -794,24 +865,47 @@ export function startMcpStdioServer(defaultCwd = process.cwd(), opts) {
|
|
|
794
865
|
process.exitCode = 0;
|
|
795
866
|
}
|
|
796
867
|
});
|
|
797
|
-
const send =
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
868
|
+
const send = (payload) => {
|
|
869
|
+
sendChain = sendChain.then(async () => {
|
|
870
|
+
if (stdoutClosed || process.stdout.destroyed)
|
|
871
|
+
return;
|
|
872
|
+
const json = JSON.stringify(payload);
|
|
873
|
+
const frame = useContentLength
|
|
874
|
+
? `Content-Length: ${Buffer.byteLength(json, "utf8")}\r\n\r\n${json}`
|
|
875
|
+
: `${json}\n`;
|
|
876
|
+
if (!process.stdout.write(frame)) {
|
|
877
|
+
await once(process.stdout, "drain").catch(() => undefined);
|
|
878
|
+
}
|
|
879
|
+
});
|
|
880
|
+
return sendChain;
|
|
807
881
|
};
|
|
808
882
|
const flushStdout = async () => {
|
|
883
|
+
await sendChain;
|
|
809
884
|
if (stdoutClosed || process.stdout.destroyed)
|
|
810
885
|
return;
|
|
811
886
|
await new Promise((resolve) => {
|
|
812
887
|
process.stdout.write("", () => resolve());
|
|
813
888
|
});
|
|
814
889
|
};
|
|
890
|
+
const acquireReadSlot = async () => {
|
|
891
|
+
if (activeReads < MAX_CONCURRENT_READS) {
|
|
892
|
+
activeReads++;
|
|
893
|
+
return;
|
|
894
|
+
}
|
|
895
|
+
await new Promise((resolve) => readWaiters.push(resolve));
|
|
896
|
+
activeReads++;
|
|
897
|
+
};
|
|
898
|
+
const releaseReadSlot = () => {
|
|
899
|
+
activeReads--;
|
|
900
|
+
const next = readWaiters.shift();
|
|
901
|
+
if (next)
|
|
902
|
+
next();
|
|
903
|
+
};
|
|
904
|
+
const trackTask = (p) => {
|
|
905
|
+
activeTasks.add(p);
|
|
906
|
+
p.finally(() => activeTasks.delete(p));
|
|
907
|
+
return p;
|
|
908
|
+
};
|
|
815
909
|
const cancelIfNotification = (parsed) => {
|
|
816
910
|
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
817
911
|
return false;
|
|
@@ -854,7 +948,7 @@ export function startMcpStdioServer(defaultCwd = process.cwd(), opts) {
|
|
|
854
948
|
parsed = JSON.parse(raw);
|
|
855
949
|
}
|
|
856
950
|
catch (e) {
|
|
857
|
-
|
|
951
|
+
void trackTask(send({ jsonrpc: "2.0", id: null, error: { code: -32700, message: `Parse error: ${e.message}` } }));
|
|
858
952
|
return;
|
|
859
953
|
}
|
|
860
954
|
// Handle cancellation notifications immediately out-of-band so they can abort an in-flight call.
|
|
@@ -865,12 +959,50 @@ export function startMcpStdioServer(defaultCwd = process.cwd(), opts) {
|
|
|
865
959
|
(typeof parsed.id === "string" || typeof parsed.id === "number")
|
|
866
960
|
? parsed.id
|
|
867
961
|
: null;
|
|
868
|
-
|
|
962
|
+
void trackTask(send({ jsonrpc: "2.0", id: idVal, error: { code: -32000, message: `Server busy: queue limit (${MAX_PENDING_REQUESTS}) exceeded.` } }));
|
|
869
963
|
return;
|
|
870
964
|
}
|
|
871
965
|
pendingCount++;
|
|
872
|
-
|
|
966
|
+
// Run read-only tool calls & metadata queries concurrently (after initialize and any prior mutations) so multi-file
|
|
967
|
+
// reads/greps do not head-of-line block each other and can be cancelled out-of-band immediately.
|
|
968
|
+
if (isConcurrentReadOnlyMessage(parsed)) {
|
|
969
|
+
const waitForMutations = mutatingChain;
|
|
970
|
+
const waitForInit = initBarrier;
|
|
971
|
+
const readPromise = (async () => {
|
|
972
|
+
try {
|
|
973
|
+
await waitForInit;
|
|
974
|
+
await waitForMutations;
|
|
975
|
+
await acquireReadSlot();
|
|
976
|
+
try {
|
|
977
|
+
const res = await runSingle(parsed);
|
|
978
|
+
if (res)
|
|
979
|
+
await send(res);
|
|
980
|
+
}
|
|
981
|
+
finally {
|
|
982
|
+
releaseReadSlot();
|
|
983
|
+
}
|
|
984
|
+
}
|
|
985
|
+
catch (err) {
|
|
986
|
+
await send({ jsonrpc: "2.0", id: null, error: { code: -32603, message: `Internal error: ${err instanceof Error ? err.message : String(err)}` } });
|
|
987
|
+
}
|
|
988
|
+
finally {
|
|
989
|
+
pendingCount--;
|
|
990
|
+
}
|
|
991
|
+
})();
|
|
992
|
+
activeReadPromises.add(readPromise);
|
|
993
|
+
readPromise.finally(() => activeReadPromises.delete(readPromise));
|
|
994
|
+
void trackTask(readPromise);
|
|
995
|
+
return;
|
|
996
|
+
}
|
|
997
|
+
const isInit = !Array.isArray(parsed) && parsed !== null && typeof parsed === "object" && parsed.method === "initialize";
|
|
998
|
+
const waitForInit = initBarrier;
|
|
999
|
+
const waitForReads = [...activeReadPromises];
|
|
1000
|
+
const task = mutatingChain.then(async () => {
|
|
873
1001
|
try {
|
|
1002
|
+
if (!isInit)
|
|
1003
|
+
await waitForInit;
|
|
1004
|
+
if (waitForReads.length > 0)
|
|
1005
|
+
await Promise.allSettled(waitForReads);
|
|
874
1006
|
if (Array.isArray(parsed)) {
|
|
875
1007
|
if (parsed.length === 0) {
|
|
876
1008
|
await send({ jsonrpc: "2.0", id: null, error: { code: -32600, message: "Invalid Request: empty batch." } });
|
|
@@ -899,6 +1031,10 @@ export function startMcpStdioServer(defaultCwd = process.cwd(), opts) {
|
|
|
899
1031
|
pendingCount--;
|
|
900
1032
|
}
|
|
901
1033
|
});
|
|
1034
|
+
mutatingChain = task;
|
|
1035
|
+
if (isInit)
|
|
1036
|
+
initBarrier = task;
|
|
1037
|
+
void trackTask(task);
|
|
902
1038
|
};
|
|
903
1039
|
const drain = () => {
|
|
904
1040
|
while (buf.length > 0) {
|
|
@@ -910,7 +1046,7 @@ export function startMcpStdioServer(defaultCwd = process.cwd(), opts) {
|
|
|
910
1046
|
if (buf.length === 0)
|
|
911
1047
|
break;
|
|
912
1048
|
const head = buf.subarray(0, Math.min(buf.length, 32)).toString("ascii");
|
|
913
|
-
if (/^content-length:/i.test(head)) {
|
|
1049
|
+
if (/^(?:content-length|content-type):/i.test(head)) {
|
|
914
1050
|
useContentLength = true;
|
|
915
1051
|
const sep = buf.indexOf("\r\n\r\n");
|
|
916
1052
|
const sepAlt = sep === -1 ? buf.indexOf("\n\n") : -1;
|
|
@@ -922,9 +1058,15 @@ export function startMcpStdioServer(defaultCwd = process.cwd(), opts) {
|
|
|
922
1058
|
const m = /content-length:\s*(\d+)/i.exec(headerText);
|
|
923
1059
|
if (!m) {
|
|
924
1060
|
buf = buf.subarray(headerEnd + sepLen);
|
|
1061
|
+
void trackTask(send({ jsonrpc: "2.0", id: null, error: { code: -32600, message: "Invalid Request: missing Content-Length header." } }));
|
|
925
1062
|
continue;
|
|
926
1063
|
}
|
|
927
1064
|
const bodyLen = Number(m[1]);
|
|
1065
|
+
if (!Number.isSafeInteger(bodyLen) || bodyLen < 0 || bodyLen > MAX_FRAME_BYTES) {
|
|
1066
|
+
buf = Buffer.alloc(0);
|
|
1067
|
+
void trackTask(send({ jsonrpc: "2.0", id: null, error: { code: -32600, message: `Invalid Request: Content-Length (${m[1]}) out of allowed bounds.` } }));
|
|
1068
|
+
break;
|
|
1069
|
+
}
|
|
928
1070
|
const bodyStart = headerEnd + sepLen;
|
|
929
1071
|
if (buf.length < bodyStart + bodyLen)
|
|
930
1072
|
break;
|
|
@@ -950,10 +1092,13 @@ export function startMcpStdioServer(defaultCwd = process.cwd(), opts) {
|
|
|
950
1092
|
const rest = buf.toString("utf8").trim();
|
|
951
1093
|
if (rest)
|
|
952
1094
|
dispatchRaw(rest);
|
|
953
|
-
void
|
|
1095
|
+
void (async () => {
|
|
1096
|
+
while (activeTasks.size > 0) {
|
|
1097
|
+
await Promise.allSettled([...activeTasks]);
|
|
1098
|
+
}
|
|
954
1099
|
await getIncidentRecorder(mapClientName(opts?.client)).flush(500).catch(() => undefined);
|
|
955
1100
|
await flushStdout();
|
|
956
1101
|
process.exitCode = 0;
|
|
957
|
-
});
|
|
1102
|
+
})();
|
|
958
1103
|
});
|
|
959
1104
|
}
|
package/dist/operations.js
CHANGED
|
@@ -543,6 +543,9 @@ async function writeEncodedLocked(absPath, utf8content, seam, scope, epoch, expe
|
|
|
543
543
|
const verify = plan.rule?.verifyWrite !== false;
|
|
544
544
|
const existed = prevRaw !== null;
|
|
545
545
|
try {
|
|
546
|
+
// Ensure parent directory exists ONLY after all validation gates (expectedVersion, Gate 3, Gate 1, STALE_READ) pass.
|
|
547
|
+
if (!existed)
|
|
548
|
+
await mkdir(path.dirname(absPath), { recursive: true });
|
|
546
549
|
await seam.writeBytes(absPath, bytes, prevRaw);
|
|
547
550
|
}
|
|
548
551
|
catch (e) {
|
package/dist/setup/adapters.js
CHANGED
|
@@ -27,13 +27,41 @@ function defaultBackupRoot(home, stateOverride) {
|
|
|
27
27
|
}
|
|
28
28
|
return path.join(process.env.XDG_STATE_HOME || path.join(home, ".local", "state"), "pi-charset", "setup-backups");
|
|
29
29
|
}
|
|
30
|
+
/** Resolve a CLI executable from PATH without spawning slow `--version` subprocesses (supports Windows .exe/.cmd/.bat/.ps1 shims). */
|
|
30
31
|
function probeBinary(cmd) {
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
32
|
+
const pathEnv = process.env.PATH || process.env.Path || "";
|
|
33
|
+
const dirs = pathEnv.split(path.delimiter).filter(Boolean);
|
|
34
|
+
if (process.platform === "win32") {
|
|
35
|
+
const exts = (process.env.PATHEXT || ".COM;.EXE;.BAT;.CMD")
|
|
36
|
+
.split(";")
|
|
37
|
+
.map((e) => e.trim())
|
|
38
|
+
.filter(Boolean);
|
|
39
|
+
if (!exts.some((e) => e.toUpperCase() === ".PS1"))
|
|
40
|
+
exts.push(".PS1");
|
|
41
|
+
for (const dir of dirs) {
|
|
42
|
+
const cleanDir = dir.replace(/^"|"$/g, "");
|
|
43
|
+
if (!cleanDir)
|
|
44
|
+
continue;
|
|
45
|
+
for (const ext of exts) {
|
|
46
|
+
const candidate = path.join(cleanDir, `${cmd}${ext.toLowerCase()}`);
|
|
47
|
+
try {
|
|
48
|
+
if (fs.statSync(candidate).isFile())
|
|
49
|
+
return candidate;
|
|
50
|
+
}
|
|
51
|
+
catch { /* next */ }
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
for (const dir of dirs) {
|
|
57
|
+
const candidate = path.join(dir, cmd);
|
|
58
|
+
try {
|
|
59
|
+
fs.accessSync(candidate, fs.constants.X_OK);
|
|
60
|
+
if (fs.statSync(candidate).isFile())
|
|
61
|
+
return candidate;
|
|
62
|
+
}
|
|
63
|
+
catch { /* next */ }
|
|
35
64
|
}
|
|
36
|
-
catch { /* not found */ }
|
|
37
65
|
return null;
|
|
38
66
|
}
|
|
39
67
|
function atomicWriteText(targetPath, content) {
|
|
@@ -188,28 +216,85 @@ function findCodexSection(lines) {
|
|
|
188
216
|
}
|
|
189
217
|
return { start, end };
|
|
190
218
|
}
|
|
219
|
+
function parseTomlStringToken(raw) {
|
|
220
|
+
const s = raw.trim();
|
|
221
|
+
if (s.startsWith("'") && s.endsWith("'") && s.length >= 2) {
|
|
222
|
+
// TOML literal string: backslashes are literal characters (used by Codex CLI on Windows paths).
|
|
223
|
+
return s.slice(1, -1);
|
|
224
|
+
}
|
|
225
|
+
if (s.startsWith('"') && s.endsWith('"') && s.length >= 2) {
|
|
226
|
+
try {
|
|
227
|
+
return JSON.parse(s);
|
|
228
|
+
}
|
|
229
|
+
catch {
|
|
230
|
+
return undefined;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
return undefined;
|
|
234
|
+
}
|
|
235
|
+
function parseTomlStringArray(raw) {
|
|
236
|
+
const s = raw.trim();
|
|
237
|
+
if (!s.startsWith("[") || !s.endsWith("]"))
|
|
238
|
+
return undefined;
|
|
239
|
+
const inner = s.slice(1, -1).trim();
|
|
240
|
+
if (!inner)
|
|
241
|
+
return [];
|
|
242
|
+
const items = [];
|
|
243
|
+
let i = 0;
|
|
244
|
+
while (i < inner.length) {
|
|
245
|
+
while (i < inner.length && /[\s,]/.test(inner[i]))
|
|
246
|
+
i++;
|
|
247
|
+
if (i >= inner.length)
|
|
248
|
+
break;
|
|
249
|
+
const q = inner[i];
|
|
250
|
+
if (q === "'") {
|
|
251
|
+
const end = inner.indexOf("'", i + 1);
|
|
252
|
+
if (end === -1)
|
|
253
|
+
return undefined;
|
|
254
|
+
items.push(inner.slice(i + 1, end));
|
|
255
|
+
i = end + 1;
|
|
256
|
+
}
|
|
257
|
+
else if (q === '"') {
|
|
258
|
+
let j = i + 1;
|
|
259
|
+
while (j < inner.length) {
|
|
260
|
+
if (inner[j] === "\\") {
|
|
261
|
+
j += 2;
|
|
262
|
+
continue;
|
|
263
|
+
}
|
|
264
|
+
if (inner[j] === '"')
|
|
265
|
+
break;
|
|
266
|
+
j++;
|
|
267
|
+
}
|
|
268
|
+
if (j >= inner.length)
|
|
269
|
+
return undefined;
|
|
270
|
+
const parsed = parseTomlStringToken(inner.slice(i, j + 1));
|
|
271
|
+
if (parsed === undefined)
|
|
272
|
+
return undefined;
|
|
273
|
+
items.push(parsed);
|
|
274
|
+
i = j + 1;
|
|
275
|
+
}
|
|
276
|
+
else {
|
|
277
|
+
return undefined;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
return items;
|
|
281
|
+
}
|
|
191
282
|
function parseCodexSectionEntry(sectionLines) {
|
|
192
283
|
let command;
|
|
193
284
|
let args;
|
|
285
|
+
let defaultToolsApprovalMode;
|
|
194
286
|
for (const line of sectionLines) {
|
|
195
|
-
const cm = /^\s*command\s*=\s*("(?:[^"\\]|\\.)*")
|
|
196
|
-
if (cm)
|
|
197
|
-
|
|
198
|
-
command = JSON.parse(cm[1]);
|
|
199
|
-
}
|
|
200
|
-
catch { /* ignore */ }
|
|
201
|
-
}
|
|
287
|
+
const cm = /^\s*command\s*=\s*("(?:[^"\\]|\\.)*"|'[^']*')\s*(?:#.*)?$/.exec(line);
|
|
288
|
+
if (cm)
|
|
289
|
+
command = parseTomlStringToken(cm[1]);
|
|
202
290
|
const am = /^\s*args\s*=\s*(\[.*\])\s*(?:#.*)?$/.exec(line);
|
|
203
|
-
if (am)
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
}
|
|
209
|
-
catch { /* ignore */ }
|
|
210
|
-
}
|
|
291
|
+
if (am)
|
|
292
|
+
args = parseTomlStringArray(am[1]);
|
|
293
|
+
const dm = /^\s*default_tools_approval_mode\s*=\s*("(?:[^"\\]|\\.)*"|'[^']*')\s*(?:#.*)?$/.exec(line);
|
|
294
|
+
if (dm)
|
|
295
|
+
defaultToolsApprovalMode = parseTomlStringToken(dm[1]);
|
|
211
296
|
}
|
|
212
|
-
return command || args ? { command, args } : undefined;
|
|
297
|
+
return command || args ? { command, args, ...(defaultToolsApprovalMode ? { defaultToolsApprovalMode } : {}) } : undefined;
|
|
213
298
|
}
|
|
214
299
|
function readCodexTomlEntry(configPath) {
|
|
215
300
|
if (!fs.existsSync(configPath))
|
|
@@ -227,9 +312,12 @@ function formatCodexSection(desired) {
|
|
|
227
312
|
`[mcp_servers.pi-charset]`,
|
|
228
313
|
`command = ${JSON.stringify(desired.command)}`,
|
|
229
314
|
`args = ${JSON.stringify(desired.args)}`,
|
|
315
|
+
...(desired.defaultToolsApprovalMode !== undefined
|
|
316
|
+
? [`default_tools_approval_mode = ${JSON.stringify(desired.defaultToolsApprovalMode)}`]
|
|
317
|
+
: []),
|
|
230
318
|
];
|
|
231
319
|
}
|
|
232
|
-
function updateCodexTomlConfig(configPath, backupRoot, desired, dryRun) {
|
|
320
|
+
function updateCodexTomlConfig(configPath, backupRoot, desired, dryRun, isRollback = false) {
|
|
233
321
|
const cur = readCodexTomlEntry(configPath);
|
|
234
322
|
const eol = cur.raw.includes("\r\n") ? "\r\n" : "\n";
|
|
235
323
|
const lines = cur.raw ? cur.raw.split(/\r?\n/) : [];
|
|
@@ -247,7 +335,15 @@ function updateCodexTomlConfig(configPath, backupRoot, desired, dryRun) {
|
|
|
247
335
|
atomicWriteText(configPath, next.endsWith(eol) || next === "" ? next : next + eol);
|
|
248
336
|
return { action: "uninstalled", detail: `Removed [mcp_servers.pi-charset] from ${configPath}` };
|
|
249
337
|
}
|
|
250
|
-
|
|
338
|
+
// Default to `approve` so local encoding tools work in Codex `workspace-write` / `codex exec` without spurious blocks,
|
|
339
|
+
// while preserving any explicit user-chosen `default_tools_approval_mode` (and honoring exact backup values on rollback).
|
|
340
|
+
const targetApprovalMode = isRollback
|
|
341
|
+
? desired.defaultToolsApprovalMode
|
|
342
|
+
: desired.defaultToolsApprovalMode ?? cur.entry?.defaultToolsApprovalMode ?? "approve";
|
|
343
|
+
if (cur.entry &&
|
|
344
|
+
cur.entry.command === desired.command &&
|
|
345
|
+
sameStringArray(cur.entry.args, desired.args) &&
|
|
346
|
+
cur.entry.defaultToolsApprovalMode === targetApprovalMode) {
|
|
251
347
|
return { action: "unchanged", detail: `Already registered with current entrypoint in ${configPath}` };
|
|
252
348
|
}
|
|
253
349
|
const action = span ? "updated" : "registered";
|
|
@@ -255,7 +351,7 @@ function updateCodexTomlConfig(configPath, backupRoot, desired, dryRun) {
|
|
|
255
351
|
return { action, detail: `[dry-run] Would ${action === "updated" ? "update" : "add"} [mcp_servers.pi-charset] in ${configPath}` };
|
|
256
352
|
}
|
|
257
353
|
saveBackup(backupRoot, "codex", cur.entry ?? null);
|
|
258
|
-
const block = formatCodexSection(desired);
|
|
354
|
+
const block = formatCodexSection({ ...desired, defaultToolsApprovalMode: targetApprovalMode });
|
|
259
355
|
let nextLines;
|
|
260
356
|
if (span) {
|
|
261
357
|
nextLines = [...lines.slice(0, span.start), ...block, "", ...lines.slice(span.end)];
|
|
@@ -382,14 +478,19 @@ export function inspectClients(opts = {}) {
|
|
|
382
478
|
continue;
|
|
383
479
|
}
|
|
384
480
|
const runnable = isRunnableEntrypoint(cur.entry.command, cur.entry.args);
|
|
481
|
+
const missingApprovalMode = runnable && !cur.entry.defaultToolsApprovalMode;
|
|
385
482
|
out.push({
|
|
386
483
|
id,
|
|
387
484
|
label: info.label,
|
|
388
485
|
detected: true,
|
|
389
486
|
cliPath,
|
|
390
487
|
configPath: info.configPath,
|
|
391
|
-
status: runnable ? "
|
|
392
|
-
detail: runnable
|
|
488
|
+
status: !runnable || missingApprovalMode ? "degraded" : "registered",
|
|
489
|
+
detail: !runnable
|
|
490
|
+
? "Registered entrypoint is missing or stale; run `pi-charset doctor --fix`"
|
|
491
|
+
: missingApprovalMode
|
|
492
|
+
? "Missing `default_tools_approval_mode` in ~/.codex/config.toml (Codex workspace-write/exec may block MCP calls); run `pi-charset doctor --fix`"
|
|
493
|
+
: `Registered in ~/.codex/config.toml (approval=${cur.entry.defaultToolsApprovalMode}; MCP guarded; native tools require rules/hooks)`,
|
|
393
494
|
entrypoint: cur.entry.command && cur.entry.args ? { command: cur.entry.command, args: cur.entry.args } : undefined,
|
|
394
495
|
});
|
|
395
496
|
continue;
|
|
@@ -466,7 +567,7 @@ export function runSetup(opts = {}) {
|
|
|
466
567
|
}
|
|
467
568
|
const prev = bak.previous;
|
|
468
569
|
const upd = id === "codex"
|
|
469
|
-
? updateCodexTomlConfig(info.configPath, backupRoot, prev, dryRun)
|
|
570
|
+
? updateCodexTomlConfig(info.configPath, backupRoot, prev, dryRun, true)
|
|
470
571
|
: updateJsonMcpConfig(id, info.configPath, backupRoot, prev, dryRun);
|
|
471
572
|
results.push({
|
|
472
573
|
id,
|
package/dist/version.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// Synchronized with package.json version.
|
|
2
|
-
export const PLUGIN_VERSION = "0.1.
|
|
2
|
+
export const PLUGIN_VERSION = "0.1.9";
|
package/package.json
CHANGED
package/src/config.ts
CHANGED
|
@@ -528,7 +528,19 @@ function nextParentDir(cur: string): string | null {
|
|
|
528
528
|
* Scan up to 16 sibling text files in `dir` (falling back up to 3 parent dirs for newly created/empty subdirectories)
|
|
529
529
|
* to infer the dominant encoding and line-ending style when creating a new file or adding non-ASCII text to a pure-ASCII file.
|
|
530
530
|
*/
|
|
531
|
+
// Formats whose specifications or modern toolchains mandate UTF-8: in zero-config mode, new or pure-ASCII files
|
|
532
|
+
// with these extensions never inherit legacy CJK encodings from unrelated sibling files (e.g. `.c`/`.h`/`.txt`).
|
|
533
|
+
// Existing files that already contain non-ASCII legacy bytes on disk are still classified by their own bytes.
|
|
534
|
+
const UTF8_NATIVE_EXT = new Set([
|
|
535
|
+
".json", ".jsonc", ".json5", ".jsonl",
|
|
536
|
+
".toml", ".yaml", ".yml",
|
|
537
|
+
".ts", ".tsx", ".mts", ".cts", ".mjs",
|
|
538
|
+
".rs", ".go",
|
|
539
|
+
".md", ".mdx", ".svg",
|
|
540
|
+
]);
|
|
541
|
+
|
|
531
542
|
function inferFromSiblings(dir: string, targetExt: string, excludeBase: string): { encoding: string; eol: NewFileLineEnding | null } {
|
|
543
|
+
if (UTF8_NATIVE_EXT.has(targetExt)) return { encoding: "UTF-8", eol: null };
|
|
532
544
|
let cur: string | null = path.resolve(dir);
|
|
533
545
|
for (let depth = 0; cur && depth <= MAX_PARENT_SIBLING_DEPTH; depth++) {
|
|
534
546
|
if (depth > 0 && isBoundaryDir(cur)) break;
|
|
@@ -561,6 +573,7 @@ function inferFromSiblings(dir: string, targetExt: string, excludeBase: string):
|
|
|
561
573
|
|
|
562
574
|
/** Non-blocking sibling inference (with parent & project-file fallback for empty/new subdirectories) used on async hot paths. */
|
|
563
575
|
async function inferFromSiblingsAsync(dir: string, targetExt: string, excludeBase: string): Promise<{ encoding: string; eol: NewFileLineEnding | null }> {
|
|
576
|
+
if (UTF8_NATIVE_EXT.has(targetExt)) return { encoding: "UTF-8", eol: null };
|
|
564
577
|
let cur: string | null = path.resolve(dir);
|
|
565
578
|
for (let depth = 0; cur && depth <= MAX_PARENT_SIBLING_DEPTH; depth++) {
|
|
566
579
|
if (depth > 0 && isBoundaryDir(cur)) break;
|
package/src/encoding/classify.ts
CHANGED
|
@@ -117,7 +117,10 @@ export function decideFamilyFromBuffers(
|
|
|
117
117
|
// bonuses only count when the decoded script itself looks real: kana capped below a strong hanzi score,
|
|
118
118
|
// Hangul gated by its own frequency skew.
|
|
119
119
|
// Frequency carries twice the weight of commonness: GBK text read as Big5 still looks "common".
|
|
120
|
-
|
|
120
|
+
// When Hangul is present, scale the Hanzi term by (1 - hangulRatio) so EUC-KR mojibake (mostly garbage
|
|
121
|
+
// Hangul plus 2-3 stray Hanja) cannot double-count 100% Hanzi + Hangul bonus above 100% total weight.
|
|
122
|
+
const hanWeight = hangul > 0 ? 1 - hangulRatio : 1;
|
|
123
|
+
let score = hanWeight * (common / Math.max(1, han) + (2 * top) / Math.max(1, han)) - (2 * fffd) / nonAscii;
|
|
121
124
|
// Script bonuses need enough evidence: a handful of noise syllables can hit the common set by chance.
|
|
122
125
|
if ((family === "Shift_JIS" || family === "EUC-JP") && kana >= 4) {
|
|
123
126
|
// Kana rows are shared with GB2312, so the kanji decide: real Japanese kanji are common words.
|
|
@@ -125,7 +128,7 @@ export function decideFamilyFromBuffers(
|
|
|
125
128
|
}
|
|
126
129
|
if (family === "EUC-KR" && hangul >= 3) {
|
|
127
130
|
const pure = commonHangul / hangul;
|
|
128
|
-
score += hangulRatio * ((hangul >= 8 && pure >= 0.
|
|
131
|
+
score += hangulRatio * ((hangul >= 8 && pure >= 0.35) || pure >= 0.5 ? 1.5 : 0.2);
|
|
129
132
|
}
|
|
130
133
|
scores.push([family, score]);
|
|
131
134
|
}
|
|
@@ -368,13 +371,30 @@ function classifyUncached(B: Buffer, cfg: ClassifyConfig | null, opts: ClassifyO
|
|
|
368
371
|
return { ...configVerdict(B, pref, "undecidable"), kind: "config" };
|
|
369
372
|
return { kind: "unknown", encoding: "UNKNOWN", ambiguous: false, hasFffd: true, candidates: [], exhaustive: true, bom: false };
|
|
370
373
|
}
|
|
371
|
-
|
|
374
|
+
let finalPass = pass;
|
|
375
|
+
if (exhaustive && crossFamilyAmbiguous) {
|
|
376
|
+
const passFamilies = new Set(pass.map(familyOf));
|
|
377
|
+
if (passFamilies.size <= 1) {
|
|
378
|
+
// Only a single encoding family round-tripped losslessly; impossible families cannot create cross-family ambiguity.
|
|
379
|
+
crossFamilyAmbiguous = false;
|
|
380
|
+
family = [...passFamilies][0] ?? family;
|
|
381
|
+
} else {
|
|
382
|
+
// Re-score strictly among families that actually passed lossless round-trip so failing families cannot spoil the margin.
|
|
383
|
+
const narrowed = decideFamily(B, passFamilies);
|
|
384
|
+
if (narrowed.confident && narrowed.family) {
|
|
385
|
+
crossFamilyAmbiguous = false;
|
|
386
|
+
family = narrowed.family;
|
|
387
|
+
finalPass = preferFamily(pass, narrowed.family);
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
const chosen = pref && finalPass.includes(pref) ? pref : finalPass[0];
|
|
372
392
|
return {
|
|
373
393
|
kind: "cjk",
|
|
374
394
|
encoding: chosen,
|
|
375
|
-
ambiguous: exhaustive ?
|
|
395
|
+
ambiguous: exhaustive ? finalPass.length > 1 : finalPass.length > 1 || order.length > finalPass.length,
|
|
376
396
|
hasFffd: false,
|
|
377
|
-
candidates:
|
|
397
|
+
candidates: finalPass,
|
|
378
398
|
exhaustive,
|
|
379
399
|
bom: false,
|
|
380
400
|
family,
|