pi-charset 0.1.7 → 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 +27 -0
- package/CHANGELOG.zh-CN.md +27 -0
- package/dist/config.js +14 -0
- package/dist/diagnostics/incidents.js +436 -0
- package/dist/edit/diagnostics.js +27 -0
- package/dist/encoding/classify.js +26 -5
- package/dist/encoding/fast-codec.js +95 -44
- package/dist/faults.js +67 -0
- package/dist/mcp/server.js +303 -65
- package/dist/operations.js +172 -35
- package/dist/setup/adapters.js +625 -0
- package/dist/version.js +1 -1
- package/docs/MCP-AND-MULTI-AGENT.md +17 -2
- package/docs/zh-CN/MCP-AND-MULTI-AGENT.md +17 -2
- package/package.json +1 -1
- package/src/config.ts +13 -0
- package/src/diagnostics/incidents.ts +474 -0
- package/src/edit/diagnostics.ts +31 -0
- package/src/encoding/classify.ts +25 -5
- package/src/encoding/fast-codec.ts +81 -39
- package/src/faults.ts +165 -0
- package/src/mcp/server.ts +356 -65
- package/src/operations.ts +180 -37
- package/src/setup/adapters.ts +701 -0
- package/src/version.ts +1 -1
- package/tools/pi-charset-cli.mjs +233 -22
- package/tools/pi-charset-mcp.mjs +3 -1
|
@@ -0,0 +1,625 @@
|
|
|
1
|
+
// Host Adapter Registry for idempotent, non-destructive `pi-charset setup`, `uninstall`, `rollback`, and `doctor`.
|
|
2
|
+
// Uses permanent absolute Node + MCP entrypoints (no npx cache flakiness, no shell interpolation, no network on startup)
|
|
3
|
+
// and strictly distinguishes registered vs handshake_verified vs degraded states.
|
|
4
|
+
import { spawnSync } from "node:child_process";
|
|
5
|
+
import { randomBytes } from "node:crypto";
|
|
6
|
+
import * as fs from "node:fs";
|
|
7
|
+
import * as os from "node:os";
|
|
8
|
+
import * as path from "node:path";
|
|
9
|
+
import iconv from "iconv-lite";
|
|
10
|
+
import { PLUGIN_VERSION } from "../version.js";
|
|
11
|
+
export function checkNodeRequirement(versionStr = process.versions.node) {
|
|
12
|
+
const [maj, min] = versionStr.split(".").map((n) => Number(n) || 0);
|
|
13
|
+
const ok = maj > 22 || (maj === 22 && min >= 19);
|
|
14
|
+
return { ok, current: versionStr, required: ">=22.19.0" };
|
|
15
|
+
}
|
|
16
|
+
function defaultHome(override) {
|
|
17
|
+
return path.resolve(override || process.env.PI_CHARSET_HOME || os.homedir());
|
|
18
|
+
}
|
|
19
|
+
function defaultBackupRoot(home, stateOverride) {
|
|
20
|
+
if (stateOverride)
|
|
21
|
+
return path.resolve(stateOverride);
|
|
22
|
+
if (process.platform === "win32") {
|
|
23
|
+
return path.join(process.env.LOCALAPPDATA || path.join(home, "AppData", "Local"), "pi-charset", "setup-backups");
|
|
24
|
+
}
|
|
25
|
+
if (process.platform === "darwin") {
|
|
26
|
+
return path.join(home, "Library", "Application Support", "pi-charset", "setup-backups");
|
|
27
|
+
}
|
|
28
|
+
return path.join(process.env.XDG_STATE_HOME || path.join(home, ".local", "state"), "pi-charset", "setup-backups");
|
|
29
|
+
}
|
|
30
|
+
/** Resolve a CLI executable from PATH without spawning slow `--version` subprocesses (supports Windows .exe/.cmd/.bat/.ps1 shims). */
|
|
31
|
+
function probeBinary(cmd) {
|
|
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 */ }
|
|
64
|
+
}
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
67
|
+
function atomicWriteText(targetPath, content) {
|
|
68
|
+
const dir = path.dirname(targetPath);
|
|
69
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
70
|
+
let mode;
|
|
71
|
+
try {
|
|
72
|
+
const st = fs.lstatSync(targetPath);
|
|
73
|
+
if (st.isSymbolicLink())
|
|
74
|
+
throw new Error(`Refused to write symbolic link: ${targetPath}`);
|
|
75
|
+
mode = st.mode & 0o777;
|
|
76
|
+
}
|
|
77
|
+
catch (e) {
|
|
78
|
+
if (e?.code !== "ENOENT")
|
|
79
|
+
throw e;
|
|
80
|
+
}
|
|
81
|
+
const tmp = `${targetPath}.${randomBytes(6).toString("hex")}.pi-charset.tmp`;
|
|
82
|
+
try {
|
|
83
|
+
fs.writeFileSync(tmp, content, { encoding: "utf8", flag: "wx", ...(mode !== undefined ? { mode } : {}) });
|
|
84
|
+
fs.renameSync(tmp, targetPath);
|
|
85
|
+
}
|
|
86
|
+
finally {
|
|
87
|
+
try {
|
|
88
|
+
fs.unlinkSync(tmp);
|
|
89
|
+
}
|
|
90
|
+
catch { /* cleaned up */ }
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
function buildMcpArgs(mcpEntryPath, client, opts) {
|
|
94
|
+
const args = [mcpEntryPath, "--client", client];
|
|
95
|
+
if (opts.encoding)
|
|
96
|
+
args.push("--encoding", opts.encoding);
|
|
97
|
+
if (opts.eol)
|
|
98
|
+
args.push("--eol", opts.eol);
|
|
99
|
+
if (opts.preferLegacy)
|
|
100
|
+
args.push("--prefer-legacy");
|
|
101
|
+
if (opts.hashlines)
|
|
102
|
+
args.push("--hashlines");
|
|
103
|
+
if (opts.autoCommit)
|
|
104
|
+
args.push("--auto-commit");
|
|
105
|
+
return args;
|
|
106
|
+
}
|
|
107
|
+
function sameStringArray(a, b) {
|
|
108
|
+
if (!Array.isArray(a) || a.length !== b.length)
|
|
109
|
+
return false;
|
|
110
|
+
for (let i = 0; i < a.length; i++)
|
|
111
|
+
if (a[i] !== b[i])
|
|
112
|
+
return false;
|
|
113
|
+
return true;
|
|
114
|
+
}
|
|
115
|
+
function isRunnableEntrypoint(command, args) {
|
|
116
|
+
if (!command || !Array.isArray(args) || args.length === 0)
|
|
117
|
+
return false;
|
|
118
|
+
const cmdOk = command === "node" || command === "npx" || fs.existsSync(command);
|
|
119
|
+
const entry = args[0];
|
|
120
|
+
const entryOk = command === "npx" ? true : typeof entry === "string" && fs.existsSync(entry);
|
|
121
|
+
return cmdOk && entryOk;
|
|
122
|
+
}
|
|
123
|
+
function readJsonMcpEntry(configPath) {
|
|
124
|
+
if (!fs.existsSync(configPath))
|
|
125
|
+
return { exists: false };
|
|
126
|
+
try {
|
|
127
|
+
const raw = fs.readFileSync(configPath, "utf8");
|
|
128
|
+
const parsed = JSON.parse(raw);
|
|
129
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
130
|
+
return { exists: true, parseError: "Root JSON value is not an object" };
|
|
131
|
+
}
|
|
132
|
+
const root = parsed;
|
|
133
|
+
const servers = root.mcpServers;
|
|
134
|
+
if (servers !== undefined && (typeof servers !== "object" || servers === null || Array.isArray(servers))) {
|
|
135
|
+
return { exists: true, parseError: `"mcpServers" is not an object` };
|
|
136
|
+
}
|
|
137
|
+
const entry = servers?.["pi-charset"];
|
|
138
|
+
return { exists: true, root, entry };
|
|
139
|
+
}
|
|
140
|
+
catch (e) {
|
|
141
|
+
return { exists: true, parseError: e.message };
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
function saveBackup(backupRoot, id, previous) {
|
|
145
|
+
fs.mkdirSync(backupRoot, { recursive: true, mode: 0o700 });
|
|
146
|
+
const file = path.join(backupRoot, `${id}.json`);
|
|
147
|
+
atomicWriteText(file, JSON.stringify({ id, savedAt: new Date().toISOString(), previous }, null, 2) + "\n");
|
|
148
|
+
}
|
|
149
|
+
function readBackup(backupRoot, id) {
|
|
150
|
+
const file = path.join(backupRoot, `${id}.json`);
|
|
151
|
+
if (!fs.existsSync(file))
|
|
152
|
+
return { found: false };
|
|
153
|
+
try {
|
|
154
|
+
const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
155
|
+
return { found: true, previous: parsed.previous };
|
|
156
|
+
}
|
|
157
|
+
catch {
|
|
158
|
+
return { found: false };
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
function updateJsonMcpConfig(id, configPath, backupRoot, desired, dryRun) {
|
|
162
|
+
const cur = readJsonMcpEntry(configPath);
|
|
163
|
+
if (cur.parseError) {
|
|
164
|
+
return { action: "failed", detail: `Refused to modify invalid JSON at ${configPath}: ${cur.parseError}` };
|
|
165
|
+
}
|
|
166
|
+
const root = cur.root ? { ...cur.root } : {};
|
|
167
|
+
const servers = root.mcpServers && typeof root.mcpServers === "object" && !Array.isArray(root.mcpServers)
|
|
168
|
+
? { ...root.mcpServers }
|
|
169
|
+
: {};
|
|
170
|
+
const prev = servers["pi-charset"];
|
|
171
|
+
if (desired === null) {
|
|
172
|
+
if (!prev)
|
|
173
|
+
return { action: "unchanged", detail: `Not registered in ${configPath}` };
|
|
174
|
+
if (dryRun)
|
|
175
|
+
return { action: "uninstalled", detail: `[dry-run] Would remove pi-charset from ${configPath}` };
|
|
176
|
+
saveBackup(backupRoot, id, prev);
|
|
177
|
+
delete servers["pi-charset"];
|
|
178
|
+
root.mcpServers = servers;
|
|
179
|
+
atomicWriteText(configPath, JSON.stringify(root, null, 2) + "\n");
|
|
180
|
+
return { action: "uninstalled", detail: `Removed pi-charset from ${configPath} (other MCP servers preserved)` };
|
|
181
|
+
}
|
|
182
|
+
if (prev && prev.command === desired.command && sameStringArray(prev.args, desired.args)) {
|
|
183
|
+
return { action: "unchanged", detail: `Already registered with current entrypoint in ${configPath}` };
|
|
184
|
+
}
|
|
185
|
+
const action = prev ? "updated" : "registered";
|
|
186
|
+
if (dryRun) {
|
|
187
|
+
return { action, detail: `[dry-run] Would ${action === "updated" ? "update" : "add"} pi-charset in ${configPath}` };
|
|
188
|
+
}
|
|
189
|
+
saveBackup(backupRoot, id, prev ?? null);
|
|
190
|
+
servers["pi-charset"] = { command: desired.command, args: desired.args };
|
|
191
|
+
root.mcpServers = servers;
|
|
192
|
+
atomicWriteText(configPath, JSON.stringify(root, null, 2) + "\n");
|
|
193
|
+
return { action, detail: `${action === "updated" ? "Updated" : "Registered"} pi-charset in ${configPath}` };
|
|
194
|
+
}
|
|
195
|
+
// --- Codex TOML helpers (~/.codex/config.toml) ---
|
|
196
|
+
// Scoped surgical section edit affecting ONLY `[mcp_servers.pi-charset]` / `[mcp_servers."pi-charset"]`,
|
|
197
|
+
// preserving all comments, formatting, and third-party TOML sections verbatim.
|
|
198
|
+
const CODEX_SECTION_HEADER = /^\s*\[mcp_servers\.(?:"pi-charset"|'pi-charset'|pi-charset)\]\s*(?:#.*)?$/;
|
|
199
|
+
const ANY_TOML_SECTION = /^\s*\[[^\]]+\]\s*(?:#.*)?$/;
|
|
200
|
+
function findCodexSection(lines) {
|
|
201
|
+
let start = -1;
|
|
202
|
+
for (let i = 0; i < lines.length; i++) {
|
|
203
|
+
if (CODEX_SECTION_HEADER.test(lines[i])) {
|
|
204
|
+
start = i;
|
|
205
|
+
break;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
if (start === -1)
|
|
209
|
+
return null;
|
|
210
|
+
let end = lines.length;
|
|
211
|
+
for (let i = start + 1; i < lines.length; i++) {
|
|
212
|
+
if (ANY_TOML_SECTION.test(lines[i])) {
|
|
213
|
+
end = i;
|
|
214
|
+
break;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
return { start, end };
|
|
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
|
+
}
|
|
282
|
+
function parseCodexSectionEntry(sectionLines) {
|
|
283
|
+
let command;
|
|
284
|
+
let args;
|
|
285
|
+
let defaultToolsApprovalMode;
|
|
286
|
+
for (const line of sectionLines) {
|
|
287
|
+
const cm = /^\s*command\s*=\s*("(?:[^"\\]|\\.)*"|'[^']*')\s*(?:#.*)?$/.exec(line);
|
|
288
|
+
if (cm)
|
|
289
|
+
command = parseTomlStringToken(cm[1]);
|
|
290
|
+
const am = /^\s*args\s*=\s*(\[.*\])\s*(?:#.*)?$/.exec(line);
|
|
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]);
|
|
296
|
+
}
|
|
297
|
+
return command || args ? { command, args, ...(defaultToolsApprovalMode ? { defaultToolsApprovalMode } : {}) } : undefined;
|
|
298
|
+
}
|
|
299
|
+
function readCodexTomlEntry(configPath) {
|
|
300
|
+
if (!fs.existsSync(configPath))
|
|
301
|
+
return { exists: false, raw: "" };
|
|
302
|
+
const raw = fs.readFileSync(configPath, "utf8");
|
|
303
|
+
const lines = raw.split(/\r?\n/);
|
|
304
|
+
const span = findCodexSection(lines);
|
|
305
|
+
if (!span)
|
|
306
|
+
return { exists: true, raw };
|
|
307
|
+
const sectionLines = lines.slice(span.start, span.end);
|
|
308
|
+
return { exists: true, raw, entry: parseCodexSectionEntry(sectionLines), sectionText: sectionLines.join("\n") };
|
|
309
|
+
}
|
|
310
|
+
function formatCodexSection(desired) {
|
|
311
|
+
return [
|
|
312
|
+
`[mcp_servers.pi-charset]`,
|
|
313
|
+
`command = ${JSON.stringify(desired.command)}`,
|
|
314
|
+
`args = ${JSON.stringify(desired.args)}`,
|
|
315
|
+
...(desired.defaultToolsApprovalMode !== undefined
|
|
316
|
+
? [`default_tools_approval_mode = ${JSON.stringify(desired.defaultToolsApprovalMode)}`]
|
|
317
|
+
: []),
|
|
318
|
+
];
|
|
319
|
+
}
|
|
320
|
+
function updateCodexTomlConfig(configPath, backupRoot, desired, dryRun, isRollback = false) {
|
|
321
|
+
const cur = readCodexTomlEntry(configPath);
|
|
322
|
+
const eol = cur.raw.includes("\r\n") ? "\r\n" : "\n";
|
|
323
|
+
const lines = cur.raw ? cur.raw.split(/\r?\n/) : [];
|
|
324
|
+
const span = findCodexSection(lines);
|
|
325
|
+
if (desired === null) {
|
|
326
|
+
if (!span)
|
|
327
|
+
return { action: "unchanged", detail: `Not registered in ${configPath}` };
|
|
328
|
+
if (dryRun)
|
|
329
|
+
return { action: "uninstalled", detail: `[dry-run] Would remove [mcp_servers.pi-charset] from ${configPath}` };
|
|
330
|
+
saveBackup(backupRoot, "codex", cur.entry ?? null);
|
|
331
|
+
let end = span.end;
|
|
332
|
+
while (end < lines.length && lines[end].trim() === "")
|
|
333
|
+
end++;
|
|
334
|
+
const next = [...lines.slice(0, span.start), ...lines.slice(end)].join(eol).replace(/(\r?\n){3,}/g, `${eol}${eol}`);
|
|
335
|
+
atomicWriteText(configPath, next.endsWith(eol) || next === "" ? next : next + eol);
|
|
336
|
+
return { action: "uninstalled", detail: `Removed [mcp_servers.pi-charset] from ${configPath}` };
|
|
337
|
+
}
|
|
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) {
|
|
347
|
+
return { action: "unchanged", detail: `Already registered with current entrypoint in ${configPath}` };
|
|
348
|
+
}
|
|
349
|
+
const action = span ? "updated" : "registered";
|
|
350
|
+
if (dryRun) {
|
|
351
|
+
return { action, detail: `[dry-run] Would ${action === "updated" ? "update" : "add"} [mcp_servers.pi-charset] in ${configPath}` };
|
|
352
|
+
}
|
|
353
|
+
saveBackup(backupRoot, "codex", cur.entry ?? null);
|
|
354
|
+
const block = formatCodexSection({ ...desired, defaultToolsApprovalMode: targetApprovalMode });
|
|
355
|
+
let nextLines;
|
|
356
|
+
if (span) {
|
|
357
|
+
nextLines = [...lines.slice(0, span.start), ...block, "", ...lines.slice(span.end)];
|
|
358
|
+
}
|
|
359
|
+
else {
|
|
360
|
+
const trimmed = [...lines];
|
|
361
|
+
while (trimmed.length > 0 && trimmed[trimmed.length - 1].trim() === "")
|
|
362
|
+
trimmed.pop();
|
|
363
|
+
nextLines = trimmed.length > 0 ? [...trimmed, "", ...block, ""] : [...block, ""];
|
|
364
|
+
}
|
|
365
|
+
atomicWriteText(configPath, nextLines.join(eol));
|
|
366
|
+
return { action, detail: `${action === "updated" ? "Updated" : "Registered"} [mcp_servers.pi-charset] in ${configPath}` };
|
|
367
|
+
}
|
|
368
|
+
function adapterPaths(home) {
|
|
369
|
+
return {
|
|
370
|
+
pi: { label: "Pi", configPath: path.join(home, ".pi", "agent", "settings.json"), dirHint: path.join(home, ".pi"), cliBin: "pi" },
|
|
371
|
+
codex: { label: "Codex CLI/IDE", configPath: path.join(home, ".codex", "config.toml"), dirHint: path.join(home, ".codex"), cliBin: "codex" },
|
|
372
|
+
agy: { label: "Antigravity CLI", configPath: path.join(home, ".gemini", "config", "mcp_config.json"), dirHint: path.join(home, ".gemini"), cliBin: "agy" },
|
|
373
|
+
claude: { label: "Claude Code", configPath: path.join(home, ".claude.json"), dirHint: path.join(home, ".claude"), cliBin: "claude" },
|
|
374
|
+
cursor: { label: "Cursor", configPath: path.join(home, ".cursor", "mcp.json"), dirHint: path.join(home, ".cursor") },
|
|
375
|
+
};
|
|
376
|
+
}
|
|
377
|
+
/** Run an isolated synthetic GBK+CRLF MCP stdio handshake + read/edit/undo smoke test in os.tmpdir(). */
|
|
378
|
+
export function verifyMcpSmoke(nodePath, mcpEntryPath) {
|
|
379
|
+
const t0 = performance.now();
|
|
380
|
+
if (!fs.existsSync(mcpEntryPath)) {
|
|
381
|
+
return { ok: false, latencyMs: 0, detail: `MCP entrypoint missing: ${mcpEntryPath}` };
|
|
382
|
+
}
|
|
383
|
+
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "pi-charset-setup-smoke-"));
|
|
384
|
+
try {
|
|
385
|
+
const sample = path.join(tmp, "smoke.c");
|
|
386
|
+
const origBytes = iconv.encode("// 电机编码自检\r\nint speed = 100;\r\n", "GBK");
|
|
387
|
+
fs.writeFileSync(sample, origBytes);
|
|
388
|
+
const runRpc = (lines) => spawnSync(nodePath, [mcpEntryPath, "--cwd", tmp, "--client", "generic"], {
|
|
389
|
+
input: lines.map((l) => JSON.stringify(l)).join("\n") + "\n",
|
|
390
|
+
encoding: "utf8",
|
|
391
|
+
windowsHide: true,
|
|
392
|
+
timeout: 12000,
|
|
393
|
+
});
|
|
394
|
+
// Step 1: initialize + tools/list + read + edit + undo in ONE live stdio session.
|
|
395
|
+
const r1 = runRpc([
|
|
396
|
+
{ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-03-26", capabilities: {}, clientInfo: { name: "pi-charset-setup", version: PLUGIN_VERSION } } },
|
|
397
|
+
{ jsonrpc: "2.0", id: 2, method: "tools/list", params: {} },
|
|
398
|
+
{ jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "charset_read", arguments: { path: "smoke.c" } } },
|
|
399
|
+
{ jsonrpc: "2.0", id: 4, method: "tools/call", params: { name: "charset_edit", arguments: { path: "smoke.c", edits: [{ oldText: "int speed = 100;", newText: "int speed = 200;" }] } } },
|
|
400
|
+
{ jsonrpc: "2.0", id: 5, method: "tools/call", params: { name: "charset_fix", arguments: { action: "undo" } } },
|
|
401
|
+
]);
|
|
402
|
+
const latencyMs = Math.round(performance.now() - t0);
|
|
403
|
+
if (r1.status !== 0) {
|
|
404
|
+
return { ok: false, latencyMs, detail: `MCP exited with code ${r1.status}: ${(r1.stderr || "").trim().slice(0, 160)}` };
|
|
405
|
+
}
|
|
406
|
+
const replies = r1.stdout.trim().split(/\r?\n/).filter(Boolean).map((l) => JSON.parse(l));
|
|
407
|
+
if (replies.length !== 5) {
|
|
408
|
+
return { ok: false, latencyMs, detail: `Expected 5 JSON-RPC replies, got ${replies.length}` };
|
|
409
|
+
}
|
|
410
|
+
const protocolVersion = replies[0]?.result?.protocolVersion;
|
|
411
|
+
const toolCount = Array.isArray(replies[1]?.result?.tools) ? replies[1].result.tools.length : 0;
|
|
412
|
+
const readText = replies[2]?.result?.content?.[0]?.text ?? "";
|
|
413
|
+
if (!readText.includes("电机编码自检")) {
|
|
414
|
+
return { ok: false, latencyMs, detail: "GBK read verification failed" };
|
|
415
|
+
}
|
|
416
|
+
if (replies[3]?.result?.isError || replies[4]?.result?.isError) {
|
|
417
|
+
return { ok: false, latencyMs, detail: "GBK edit/undo verification returned isError" };
|
|
418
|
+
}
|
|
419
|
+
if (!fs.readFileSync(sample).equals(origBytes)) {
|
|
420
|
+
return { ok: false, latencyMs, detail: "GBK undo did not restore exact original bytes" };
|
|
421
|
+
}
|
|
422
|
+
return {
|
|
423
|
+
ok: true,
|
|
424
|
+
latencyMs,
|
|
425
|
+
protocolVersion,
|
|
426
|
+
toolCount,
|
|
427
|
+
detail: `read/edit/undo GBK+CRLF round-trip verified (${latencyMs}ms, ${toolCount} tools)`,
|
|
428
|
+
};
|
|
429
|
+
}
|
|
430
|
+
catch (e) {
|
|
431
|
+
return { ok: false, latencyMs: Math.round(performance.now() - t0), detail: e.message };
|
|
432
|
+
}
|
|
433
|
+
finally {
|
|
434
|
+
fs.rmSync(tmp, { recursive: true, force: true });
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
export function inspectClients(opts = {}) {
|
|
438
|
+
const home = defaultHome(opts.homeDir);
|
|
439
|
+
const paths = adapterPaths(home);
|
|
440
|
+
const out = [];
|
|
441
|
+
for (const id of ["pi", "codex", "agy", "claude", "cursor"]) {
|
|
442
|
+
const info = paths[id];
|
|
443
|
+
const cliPath = !opts.skipCliProbe && info.cliBin ? probeBinary(info.cliBin) : null;
|
|
444
|
+
const dirExists = fs.existsSync(info.dirHint) || fs.existsSync(info.configPath);
|
|
445
|
+
const detected = Boolean(cliPath || dirExists);
|
|
446
|
+
if (id === "pi") {
|
|
447
|
+
if (!detected) {
|
|
448
|
+
out.push({ id, label: info.label, detected: false, cliPath, configPath: info.configPath, status: "not_installed", detail: "Pi CLI / ~/.pi not detected" });
|
|
449
|
+
continue;
|
|
450
|
+
}
|
|
451
|
+
let hasExt = false;
|
|
452
|
+
if (fs.existsSync(info.configPath)) {
|
|
453
|
+
try {
|
|
454
|
+
const raw = fs.readFileSync(info.configPath, "utf8");
|
|
455
|
+
hasExt = raw.includes("pi-charset");
|
|
456
|
+
}
|
|
457
|
+
catch { /* ignore */ }
|
|
458
|
+
}
|
|
459
|
+
out.push({
|
|
460
|
+
id,
|
|
461
|
+
label: info.label,
|
|
462
|
+
detected: true,
|
|
463
|
+
cliPath,
|
|
464
|
+
configPath: info.configPath,
|
|
465
|
+
status: hasExt ? "registered" : "unregistered",
|
|
466
|
+
detail: hasExt ? "pi-charset referenced in Pi settings" : "Install via `pi install npm:pi-charset`",
|
|
467
|
+
});
|
|
468
|
+
continue;
|
|
469
|
+
}
|
|
470
|
+
if (id === "codex") {
|
|
471
|
+
const cur = readCodexTomlEntry(info.configPath);
|
|
472
|
+
if (!detected && !cur.exists) {
|
|
473
|
+
out.push({ id, label: info.label, detected: false, cliPath, configPath: info.configPath, status: "not_installed", detail: "Codex CLI / ~/.codex not detected" });
|
|
474
|
+
continue;
|
|
475
|
+
}
|
|
476
|
+
if (!cur.entry) {
|
|
477
|
+
out.push({ id, label: info.label, detected: true, cliPath, configPath: info.configPath, status: "unregistered", detail: "Detected; pi-charset MCP not yet registered" });
|
|
478
|
+
continue;
|
|
479
|
+
}
|
|
480
|
+
const runnable = isRunnableEntrypoint(cur.entry.command, cur.entry.args);
|
|
481
|
+
const missingApprovalMode = runnable && !cur.entry.defaultToolsApprovalMode;
|
|
482
|
+
out.push({
|
|
483
|
+
id,
|
|
484
|
+
label: info.label,
|
|
485
|
+
detected: true,
|
|
486
|
+
cliPath,
|
|
487
|
+
configPath: info.configPath,
|
|
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)`,
|
|
494
|
+
entrypoint: cur.entry.command && cur.entry.args ? { command: cur.entry.command, args: cur.entry.args } : undefined,
|
|
495
|
+
});
|
|
496
|
+
continue;
|
|
497
|
+
}
|
|
498
|
+
// JSON-based MCP clients (agy, claude, cursor)
|
|
499
|
+
const cur = readJsonMcpEntry(info.configPath);
|
|
500
|
+
if (!detected && !cur.exists) {
|
|
501
|
+
out.push({ id, label: info.label, detected: false, cliPath, configPath: info.configPath, status: "not_installed", detail: `${info.label} not detected` });
|
|
502
|
+
continue;
|
|
503
|
+
}
|
|
504
|
+
if (cur.parseError) {
|
|
505
|
+
out.push({ id, label: info.label, detected: true, cliPath, configPath: info.configPath, status: "degraded", detail: `Invalid JSON in ${info.configPath}: ${cur.parseError}` });
|
|
506
|
+
continue;
|
|
507
|
+
}
|
|
508
|
+
if (!cur.entry) {
|
|
509
|
+
out.push({ id, label: info.label, detected: true, cliPath, configPath: info.configPath, status: "unregistered", detail: "Detected; pi-charset MCP not yet registered" });
|
|
510
|
+
continue;
|
|
511
|
+
}
|
|
512
|
+
const runnable = isRunnableEntrypoint(cur.entry.command, cur.entry.args);
|
|
513
|
+
out.push({
|
|
514
|
+
id,
|
|
515
|
+
label: info.label,
|
|
516
|
+
detected: true,
|
|
517
|
+
cliPath,
|
|
518
|
+
configPath: info.configPath,
|
|
519
|
+
status: runnable ? "registered" : "degraded",
|
|
520
|
+
detail: runnable ? `Registered in ${info.configPath}` : "Registered entrypoint is missing or stale; run `pi-charset doctor --fix`",
|
|
521
|
+
entrypoint: cur.entry.command && cur.entry.args ? { command: cur.entry.command, args: cur.entry.args } : undefined,
|
|
522
|
+
});
|
|
523
|
+
}
|
|
524
|
+
return out;
|
|
525
|
+
}
|
|
526
|
+
export function runSetup(opts = {}) {
|
|
527
|
+
const node = checkNodeRequirement();
|
|
528
|
+
const home = defaultHome(opts.homeDir);
|
|
529
|
+
const backupRoot = defaultBackupRoot(home, opts.stateDir);
|
|
530
|
+
const nodePath = opts.nodePath || process.execPath;
|
|
531
|
+
const mcpEntryPath = opts.mcpEntryPath || path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, "$1")), "..", "..", "tools", "pi-charset-mcp.mjs");
|
|
532
|
+
const dryRun = opts.dryRun === true;
|
|
533
|
+
if (!node.ok && !opts.uninstall && !opts.rollback) {
|
|
534
|
+
return {
|
|
535
|
+
ok: false,
|
|
536
|
+
node,
|
|
537
|
+
results: [{ id: "codex", label: "Runtime", configPath: "", action: "failed", status: "degraded", detail: `Node ${node.current} does not meet ${node.required}. Upgrade Node.js and re-run.` }],
|
|
538
|
+
smoke: null,
|
|
539
|
+
};
|
|
540
|
+
}
|
|
541
|
+
const inspections = inspectClients({ homeDir: home, skipCliProbe: Boolean(opts.homeDir) });
|
|
542
|
+
const targetIds = opts.clients?.length
|
|
543
|
+
? [...opts.clients]
|
|
544
|
+
: inspections.filter((c) => c.detected && c.id !== "pi").map((c) => c.id);
|
|
545
|
+
// If no clients were auto-detected and none explicitly specified, report cleanly without silently inventing configs.
|
|
546
|
+
const results = [];
|
|
547
|
+
const paths = adapterPaths(home);
|
|
548
|
+
for (const id of targetIds) {
|
|
549
|
+
const info = paths[id];
|
|
550
|
+
if (id === "pi") {
|
|
551
|
+
const piInsp = inspections.find((c) => c.id === "pi");
|
|
552
|
+
results.push({
|
|
553
|
+
id,
|
|
554
|
+
label: info.label,
|
|
555
|
+
configPath: info.configPath,
|
|
556
|
+
action: "skipped",
|
|
557
|
+
status: piInsp.status,
|
|
558
|
+
detail: piInsp.status === "registered" ? "Already configured in Pi" : "Manage Pi extension via `pi install npm:pi-charset`",
|
|
559
|
+
});
|
|
560
|
+
continue;
|
|
561
|
+
}
|
|
562
|
+
if (opts.rollback) {
|
|
563
|
+
const bak = readBackup(backupRoot, id);
|
|
564
|
+
if (!bak.found) {
|
|
565
|
+
results.push({ id, label: info.label, configPath: info.configPath, action: "skipped", status: "unregistered", detail: `No setup backup found for ${info.label}` });
|
|
566
|
+
continue;
|
|
567
|
+
}
|
|
568
|
+
const prev = bak.previous;
|
|
569
|
+
const upd = id === "codex"
|
|
570
|
+
? updateCodexTomlConfig(info.configPath, backupRoot, prev, dryRun, true)
|
|
571
|
+
: updateJsonMcpConfig(id, info.configPath, backupRoot, prev, dryRun);
|
|
572
|
+
results.push({
|
|
573
|
+
id,
|
|
574
|
+
label: info.label,
|
|
575
|
+
configPath: info.configPath,
|
|
576
|
+
action: upd.action === "failed" ? "failed" : "rolled_back",
|
|
577
|
+
status: upd.action === "failed" ? "degraded" : prev ? "registered" : "unregistered",
|
|
578
|
+
detail: upd.detail,
|
|
579
|
+
});
|
|
580
|
+
continue;
|
|
581
|
+
}
|
|
582
|
+
const desired = opts.uninstall ? null : { command: nodePath, args: buildMcpArgs(mcpEntryPath, id, opts) };
|
|
583
|
+
const upd = id === "codex"
|
|
584
|
+
? updateCodexTomlConfig(info.configPath, backupRoot, desired, dryRun)
|
|
585
|
+
: updateJsonMcpConfig(id, info.configPath, backupRoot, desired, dryRun);
|
|
586
|
+
const status = upd.action === "failed" ? "degraded" : opts.uninstall ? "unregistered" : "registered";
|
|
587
|
+
results.push({
|
|
588
|
+
id,
|
|
589
|
+
label: info.label,
|
|
590
|
+
configPath: info.configPath,
|
|
591
|
+
action: upd.action,
|
|
592
|
+
status,
|
|
593
|
+
detail: upd.detail,
|
|
594
|
+
});
|
|
595
|
+
}
|
|
596
|
+
let smoke = null;
|
|
597
|
+
if (!opts.uninstall && !opts.rollback && !dryRun && !opts.skipSmokeTest) {
|
|
598
|
+
smoke = verifyMcpSmoke(nodePath, mcpEntryPath);
|
|
599
|
+
if (smoke.ok) {
|
|
600
|
+
for (let i = 0; i < results.length; i++) {
|
|
601
|
+
if (results[i].status === "registered") {
|
|
602
|
+
results[i] = { ...results[i], status: "handshake_verified" };
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
const ok = results.every((r) => r.action !== "failed") && (smoke === null || smoke.ok);
|
|
608
|
+
return { ok, node, results, smoke };
|
|
609
|
+
}
|
|
610
|
+
/** Repair ONLY pi-charset-owned stale/degraded MCP registrations (never touches user source files or custom hooks). */
|
|
611
|
+
export function repairDegradedRegistrations(opts = {}) {
|
|
612
|
+
const inspections = inspectClients({ homeDir: opts.homeDir, skipCliProbe: Boolean(opts.homeDir) });
|
|
613
|
+
const degraded = inspections.filter((c) => c.id !== "pi" && c.status === "degraded" && c.entrypoint !== undefined);
|
|
614
|
+
if (degraded.length === 0)
|
|
615
|
+
return [];
|
|
616
|
+
const res = runSetup({
|
|
617
|
+
clients: degraded.map((c) => c.id),
|
|
618
|
+
homeDir: opts.homeDir,
|
|
619
|
+
stateDir: opts.stateDir,
|
|
620
|
+
nodePath: opts.nodePath,
|
|
621
|
+
mcpEntryPath: opts.mcpEntryPath,
|
|
622
|
+
skipSmokeTest: true,
|
|
623
|
+
});
|
|
624
|
+
return res.results;
|
|
625
|
+
}
|
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";
|
|
@@ -18,14 +18,29 @@ When a team maintains a permanent legacy-encoded codebase (such as GBK embedded
|
|
|
18
18
|
|
|
19
19
|
If you want to pin defaults for a strict GBK repo **without adding a `.pi-charset.json` file**, pass CLI flags (`--encoding GBK --eol CRLF --prefer-legacy --hashlines --auto-commit`) or `PI_CHARSET_*` environment variables directly to `pi-charset-mcp`.
|
|
20
20
|
|
|
21
|
-
Print ready-to-paste snippets or one-command
|
|
21
|
+
Print ready-to-paste snippets or run one-command idempotent setup (registers permanent absolute `node` + `pi-charset-mcp.mjs` paths without touching third-party MCP servers, and verifies GBK/CRLF round-trip in an isolated temp dir):
|
|
22
22
|
|
|
23
23
|
```bash
|
|
24
|
+
# Automatic detection & registration for Codex / Antigravity / Claude / Cursor
|
|
25
|
+
npx pi-charset setup --dry-run
|
|
26
|
+
npx pi-charset setup
|
|
27
|
+
npx pi-charset setup --uninstall
|
|
28
|
+
npx pi-charset setup --rollback
|
|
29
|
+
|
|
30
|
+
# Diagnostics, health JSON, and safe repair of stale pi-charset entries
|
|
31
|
+
npx pi-charset doctor --json
|
|
32
|
+
npx pi-charset doctor --fix
|
|
33
|
+
|
|
34
|
+
# Local-only sanitized incident feedback (never uploads or opens browsers; set PI_CHARSET_DIAGNOSTICS=0 to disable)
|
|
35
|
+
npx pi-charset feedback list
|
|
36
|
+
npx pi-charset feedback preview <fingerprint>
|
|
37
|
+
npx pi-charset feedback issue-url <fingerprint>
|
|
38
|
+
|
|
39
|
+
# Or print config snippets manually
|
|
24
40
|
npx pi-charset mcp-config --client codex
|
|
25
41
|
npx pi-charset mcp-config --client cursor --local
|
|
26
42
|
npx pi-charset mcp-config --client antigravity
|
|
27
43
|
npx pi-charset mcp-config --client claude
|
|
28
|
-
npx pi-charset doctor
|
|
29
44
|
```
|
|
30
45
|
|
|
31
46
|
### Codex (one-command CLI or `~/.codex/config.toml`)
|