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.
@@ -0,0 +1,524 @@
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
+ function probeBinary(cmd) {
31
+ try {
32
+ const r = spawnSync(cmd, ["--version"], { stdio: "ignore", windowsHide: true, timeout: 2500 });
33
+ if (!r.error && r.status === 0)
34
+ return cmd;
35
+ }
36
+ catch { /* not found */ }
37
+ return null;
38
+ }
39
+ function atomicWriteText(targetPath, content) {
40
+ const dir = path.dirname(targetPath);
41
+ fs.mkdirSync(dir, { recursive: true });
42
+ let mode;
43
+ try {
44
+ const st = fs.lstatSync(targetPath);
45
+ if (st.isSymbolicLink())
46
+ throw new Error(`Refused to write symbolic link: ${targetPath}`);
47
+ mode = st.mode & 0o777;
48
+ }
49
+ catch (e) {
50
+ if (e?.code !== "ENOENT")
51
+ throw e;
52
+ }
53
+ const tmp = `${targetPath}.${randomBytes(6).toString("hex")}.pi-charset.tmp`;
54
+ try {
55
+ fs.writeFileSync(tmp, content, { encoding: "utf8", flag: "wx", ...(mode !== undefined ? { mode } : {}) });
56
+ fs.renameSync(tmp, targetPath);
57
+ }
58
+ finally {
59
+ try {
60
+ fs.unlinkSync(tmp);
61
+ }
62
+ catch { /* cleaned up */ }
63
+ }
64
+ }
65
+ function buildMcpArgs(mcpEntryPath, client, opts) {
66
+ const args = [mcpEntryPath, "--client", client];
67
+ if (opts.encoding)
68
+ args.push("--encoding", opts.encoding);
69
+ if (opts.eol)
70
+ args.push("--eol", opts.eol);
71
+ if (opts.preferLegacy)
72
+ args.push("--prefer-legacy");
73
+ if (opts.hashlines)
74
+ args.push("--hashlines");
75
+ if (opts.autoCommit)
76
+ args.push("--auto-commit");
77
+ return args;
78
+ }
79
+ function sameStringArray(a, b) {
80
+ if (!Array.isArray(a) || a.length !== b.length)
81
+ return false;
82
+ for (let i = 0; i < a.length; i++)
83
+ if (a[i] !== b[i])
84
+ return false;
85
+ return true;
86
+ }
87
+ function isRunnableEntrypoint(command, args) {
88
+ if (!command || !Array.isArray(args) || args.length === 0)
89
+ return false;
90
+ const cmdOk = command === "node" || command === "npx" || fs.existsSync(command);
91
+ const entry = args[0];
92
+ const entryOk = command === "npx" ? true : typeof entry === "string" && fs.existsSync(entry);
93
+ return cmdOk && entryOk;
94
+ }
95
+ function readJsonMcpEntry(configPath) {
96
+ if (!fs.existsSync(configPath))
97
+ return { exists: false };
98
+ try {
99
+ const raw = fs.readFileSync(configPath, "utf8");
100
+ const parsed = JSON.parse(raw);
101
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
102
+ return { exists: true, parseError: "Root JSON value is not an object" };
103
+ }
104
+ const root = parsed;
105
+ const servers = root.mcpServers;
106
+ if (servers !== undefined && (typeof servers !== "object" || servers === null || Array.isArray(servers))) {
107
+ return { exists: true, parseError: `"mcpServers" is not an object` };
108
+ }
109
+ const entry = servers?.["pi-charset"];
110
+ return { exists: true, root, entry };
111
+ }
112
+ catch (e) {
113
+ return { exists: true, parseError: e.message };
114
+ }
115
+ }
116
+ function saveBackup(backupRoot, id, previous) {
117
+ fs.mkdirSync(backupRoot, { recursive: true, mode: 0o700 });
118
+ const file = path.join(backupRoot, `${id}.json`);
119
+ atomicWriteText(file, JSON.stringify({ id, savedAt: new Date().toISOString(), previous }, null, 2) + "\n");
120
+ }
121
+ function readBackup(backupRoot, id) {
122
+ const file = path.join(backupRoot, `${id}.json`);
123
+ if (!fs.existsSync(file))
124
+ return { found: false };
125
+ try {
126
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
127
+ return { found: true, previous: parsed.previous };
128
+ }
129
+ catch {
130
+ return { found: false };
131
+ }
132
+ }
133
+ function updateJsonMcpConfig(id, configPath, backupRoot, desired, dryRun) {
134
+ const cur = readJsonMcpEntry(configPath);
135
+ if (cur.parseError) {
136
+ return { action: "failed", detail: `Refused to modify invalid JSON at ${configPath}: ${cur.parseError}` };
137
+ }
138
+ const root = cur.root ? { ...cur.root } : {};
139
+ const servers = root.mcpServers && typeof root.mcpServers === "object" && !Array.isArray(root.mcpServers)
140
+ ? { ...root.mcpServers }
141
+ : {};
142
+ const prev = servers["pi-charset"];
143
+ if (desired === null) {
144
+ if (!prev)
145
+ return { action: "unchanged", detail: `Not registered in ${configPath}` };
146
+ if (dryRun)
147
+ return { action: "uninstalled", detail: `[dry-run] Would remove pi-charset from ${configPath}` };
148
+ saveBackup(backupRoot, id, prev);
149
+ delete servers["pi-charset"];
150
+ root.mcpServers = servers;
151
+ atomicWriteText(configPath, JSON.stringify(root, null, 2) + "\n");
152
+ return { action: "uninstalled", detail: `Removed pi-charset from ${configPath} (other MCP servers preserved)` };
153
+ }
154
+ if (prev && prev.command === desired.command && sameStringArray(prev.args, desired.args)) {
155
+ return { action: "unchanged", detail: `Already registered with current entrypoint in ${configPath}` };
156
+ }
157
+ const action = prev ? "updated" : "registered";
158
+ if (dryRun) {
159
+ return { action, detail: `[dry-run] Would ${action === "updated" ? "update" : "add"} pi-charset in ${configPath}` };
160
+ }
161
+ saveBackup(backupRoot, id, prev ?? null);
162
+ servers["pi-charset"] = { command: desired.command, args: desired.args };
163
+ root.mcpServers = servers;
164
+ atomicWriteText(configPath, JSON.stringify(root, null, 2) + "\n");
165
+ return { action, detail: `${action === "updated" ? "Updated" : "Registered"} pi-charset in ${configPath}` };
166
+ }
167
+ // --- Codex TOML helpers (~/.codex/config.toml) ---
168
+ // Scoped surgical section edit affecting ONLY `[mcp_servers.pi-charset]` / `[mcp_servers."pi-charset"]`,
169
+ // preserving all comments, formatting, and third-party TOML sections verbatim.
170
+ const CODEX_SECTION_HEADER = /^\s*\[mcp_servers\.(?:"pi-charset"|'pi-charset'|pi-charset)\]\s*(?:#.*)?$/;
171
+ const ANY_TOML_SECTION = /^\s*\[[^\]]+\]\s*(?:#.*)?$/;
172
+ function findCodexSection(lines) {
173
+ let start = -1;
174
+ for (let i = 0; i < lines.length; i++) {
175
+ if (CODEX_SECTION_HEADER.test(lines[i])) {
176
+ start = i;
177
+ break;
178
+ }
179
+ }
180
+ if (start === -1)
181
+ return null;
182
+ let end = lines.length;
183
+ for (let i = start + 1; i < lines.length; i++) {
184
+ if (ANY_TOML_SECTION.test(lines[i])) {
185
+ end = i;
186
+ break;
187
+ }
188
+ }
189
+ return { start, end };
190
+ }
191
+ function parseCodexSectionEntry(sectionLines) {
192
+ let command;
193
+ let args;
194
+ for (const line of sectionLines) {
195
+ const cm = /^\s*command\s*=\s*("(?:[^"\\]|\\.)*")/.exec(line);
196
+ if (cm) {
197
+ try {
198
+ command = JSON.parse(cm[1]);
199
+ }
200
+ catch { /* ignore */ }
201
+ }
202
+ const am = /^\s*args\s*=\s*(\[.*\])\s*(?:#.*)?$/.exec(line);
203
+ if (am) {
204
+ try {
205
+ const parsed = JSON.parse(am[1]);
206
+ if (Array.isArray(parsed) && parsed.every((x) => typeof x === "string"))
207
+ args = parsed;
208
+ }
209
+ catch { /* ignore */ }
210
+ }
211
+ }
212
+ return command || args ? { command, args } : undefined;
213
+ }
214
+ function readCodexTomlEntry(configPath) {
215
+ if (!fs.existsSync(configPath))
216
+ return { exists: false, raw: "" };
217
+ const raw = fs.readFileSync(configPath, "utf8");
218
+ const lines = raw.split(/\r?\n/);
219
+ const span = findCodexSection(lines);
220
+ if (!span)
221
+ return { exists: true, raw };
222
+ const sectionLines = lines.slice(span.start, span.end);
223
+ return { exists: true, raw, entry: parseCodexSectionEntry(sectionLines), sectionText: sectionLines.join("\n") };
224
+ }
225
+ function formatCodexSection(desired) {
226
+ return [
227
+ `[mcp_servers.pi-charset]`,
228
+ `command = ${JSON.stringify(desired.command)}`,
229
+ `args = ${JSON.stringify(desired.args)}`,
230
+ ];
231
+ }
232
+ function updateCodexTomlConfig(configPath, backupRoot, desired, dryRun) {
233
+ const cur = readCodexTomlEntry(configPath);
234
+ const eol = cur.raw.includes("\r\n") ? "\r\n" : "\n";
235
+ const lines = cur.raw ? cur.raw.split(/\r?\n/) : [];
236
+ const span = findCodexSection(lines);
237
+ if (desired === null) {
238
+ if (!span)
239
+ return { action: "unchanged", detail: `Not registered in ${configPath}` };
240
+ if (dryRun)
241
+ return { action: "uninstalled", detail: `[dry-run] Would remove [mcp_servers.pi-charset] from ${configPath}` };
242
+ saveBackup(backupRoot, "codex", cur.entry ?? null);
243
+ let end = span.end;
244
+ while (end < lines.length && lines[end].trim() === "")
245
+ end++;
246
+ const next = [...lines.slice(0, span.start), ...lines.slice(end)].join(eol).replace(/(\r?\n){3,}/g, `${eol}${eol}`);
247
+ atomicWriteText(configPath, next.endsWith(eol) || next === "" ? next : next + eol);
248
+ return { action: "uninstalled", detail: `Removed [mcp_servers.pi-charset] from ${configPath}` };
249
+ }
250
+ if (cur.entry && cur.entry.command === desired.command && sameStringArray(cur.entry.args, desired.args)) {
251
+ return { action: "unchanged", detail: `Already registered with current entrypoint in ${configPath}` };
252
+ }
253
+ const action = span ? "updated" : "registered";
254
+ if (dryRun) {
255
+ return { action, detail: `[dry-run] Would ${action === "updated" ? "update" : "add"} [mcp_servers.pi-charset] in ${configPath}` };
256
+ }
257
+ saveBackup(backupRoot, "codex", cur.entry ?? null);
258
+ const block = formatCodexSection(desired);
259
+ let nextLines;
260
+ if (span) {
261
+ nextLines = [...lines.slice(0, span.start), ...block, "", ...lines.slice(span.end)];
262
+ }
263
+ else {
264
+ const trimmed = [...lines];
265
+ while (trimmed.length > 0 && trimmed[trimmed.length - 1].trim() === "")
266
+ trimmed.pop();
267
+ nextLines = trimmed.length > 0 ? [...trimmed, "", ...block, ""] : [...block, ""];
268
+ }
269
+ atomicWriteText(configPath, nextLines.join(eol));
270
+ return { action, detail: `${action === "updated" ? "Updated" : "Registered"} [mcp_servers.pi-charset] in ${configPath}` };
271
+ }
272
+ function adapterPaths(home) {
273
+ return {
274
+ pi: { label: "Pi", configPath: path.join(home, ".pi", "agent", "settings.json"), dirHint: path.join(home, ".pi"), cliBin: "pi" },
275
+ codex: { label: "Codex CLI/IDE", configPath: path.join(home, ".codex", "config.toml"), dirHint: path.join(home, ".codex"), cliBin: "codex" },
276
+ agy: { label: "Antigravity CLI", configPath: path.join(home, ".gemini", "config", "mcp_config.json"), dirHint: path.join(home, ".gemini"), cliBin: "agy" },
277
+ claude: { label: "Claude Code", configPath: path.join(home, ".claude.json"), dirHint: path.join(home, ".claude"), cliBin: "claude" },
278
+ cursor: { label: "Cursor", configPath: path.join(home, ".cursor", "mcp.json"), dirHint: path.join(home, ".cursor") },
279
+ };
280
+ }
281
+ /** Run an isolated synthetic GBK+CRLF MCP stdio handshake + read/edit/undo smoke test in os.tmpdir(). */
282
+ export function verifyMcpSmoke(nodePath, mcpEntryPath) {
283
+ const t0 = performance.now();
284
+ if (!fs.existsSync(mcpEntryPath)) {
285
+ return { ok: false, latencyMs: 0, detail: `MCP entrypoint missing: ${mcpEntryPath}` };
286
+ }
287
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "pi-charset-setup-smoke-"));
288
+ try {
289
+ const sample = path.join(tmp, "smoke.c");
290
+ const origBytes = iconv.encode("// 电机编码自检\r\nint speed = 100;\r\n", "GBK");
291
+ fs.writeFileSync(sample, origBytes);
292
+ const runRpc = (lines) => spawnSync(nodePath, [mcpEntryPath, "--cwd", tmp, "--client", "generic"], {
293
+ input: lines.map((l) => JSON.stringify(l)).join("\n") + "\n",
294
+ encoding: "utf8",
295
+ windowsHide: true,
296
+ timeout: 12000,
297
+ });
298
+ // Step 1: initialize + tools/list + read + edit + undo in ONE live stdio session.
299
+ const r1 = runRpc([
300
+ { jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-03-26", capabilities: {}, clientInfo: { name: "pi-charset-setup", version: PLUGIN_VERSION } } },
301
+ { jsonrpc: "2.0", id: 2, method: "tools/list", params: {} },
302
+ { jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "charset_read", arguments: { path: "smoke.c" } } },
303
+ { 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;" }] } } },
304
+ { jsonrpc: "2.0", id: 5, method: "tools/call", params: { name: "charset_fix", arguments: { action: "undo" } } },
305
+ ]);
306
+ const latencyMs = Math.round(performance.now() - t0);
307
+ if (r1.status !== 0) {
308
+ return { ok: false, latencyMs, detail: `MCP exited with code ${r1.status}: ${(r1.stderr || "").trim().slice(0, 160)}` };
309
+ }
310
+ const replies = r1.stdout.trim().split(/\r?\n/).filter(Boolean).map((l) => JSON.parse(l));
311
+ if (replies.length !== 5) {
312
+ return { ok: false, latencyMs, detail: `Expected 5 JSON-RPC replies, got ${replies.length}` };
313
+ }
314
+ const protocolVersion = replies[0]?.result?.protocolVersion;
315
+ const toolCount = Array.isArray(replies[1]?.result?.tools) ? replies[1].result.tools.length : 0;
316
+ const readText = replies[2]?.result?.content?.[0]?.text ?? "";
317
+ if (!readText.includes("电机编码自检")) {
318
+ return { ok: false, latencyMs, detail: "GBK read verification failed" };
319
+ }
320
+ if (replies[3]?.result?.isError || replies[4]?.result?.isError) {
321
+ return { ok: false, latencyMs, detail: "GBK edit/undo verification returned isError" };
322
+ }
323
+ if (!fs.readFileSync(sample).equals(origBytes)) {
324
+ return { ok: false, latencyMs, detail: "GBK undo did not restore exact original bytes" };
325
+ }
326
+ return {
327
+ ok: true,
328
+ latencyMs,
329
+ protocolVersion,
330
+ toolCount,
331
+ detail: `read/edit/undo GBK+CRLF round-trip verified (${latencyMs}ms, ${toolCount} tools)`,
332
+ };
333
+ }
334
+ catch (e) {
335
+ return { ok: false, latencyMs: Math.round(performance.now() - t0), detail: e.message };
336
+ }
337
+ finally {
338
+ fs.rmSync(tmp, { recursive: true, force: true });
339
+ }
340
+ }
341
+ export function inspectClients(opts = {}) {
342
+ const home = defaultHome(opts.homeDir);
343
+ const paths = adapterPaths(home);
344
+ const out = [];
345
+ for (const id of ["pi", "codex", "agy", "claude", "cursor"]) {
346
+ const info = paths[id];
347
+ const cliPath = !opts.skipCliProbe && info.cliBin ? probeBinary(info.cliBin) : null;
348
+ const dirExists = fs.existsSync(info.dirHint) || fs.existsSync(info.configPath);
349
+ const detected = Boolean(cliPath || dirExists);
350
+ if (id === "pi") {
351
+ if (!detected) {
352
+ out.push({ id, label: info.label, detected: false, cliPath, configPath: info.configPath, status: "not_installed", detail: "Pi CLI / ~/.pi not detected" });
353
+ continue;
354
+ }
355
+ let hasExt = false;
356
+ if (fs.existsSync(info.configPath)) {
357
+ try {
358
+ const raw = fs.readFileSync(info.configPath, "utf8");
359
+ hasExt = raw.includes("pi-charset");
360
+ }
361
+ catch { /* ignore */ }
362
+ }
363
+ out.push({
364
+ id,
365
+ label: info.label,
366
+ detected: true,
367
+ cliPath,
368
+ configPath: info.configPath,
369
+ status: hasExt ? "registered" : "unregistered",
370
+ detail: hasExt ? "pi-charset referenced in Pi settings" : "Install via `pi install npm:pi-charset`",
371
+ });
372
+ continue;
373
+ }
374
+ if (id === "codex") {
375
+ const cur = readCodexTomlEntry(info.configPath);
376
+ if (!detected && !cur.exists) {
377
+ out.push({ id, label: info.label, detected: false, cliPath, configPath: info.configPath, status: "not_installed", detail: "Codex CLI / ~/.codex not detected" });
378
+ continue;
379
+ }
380
+ if (!cur.entry) {
381
+ out.push({ id, label: info.label, detected: true, cliPath, configPath: info.configPath, status: "unregistered", detail: "Detected; pi-charset MCP not yet registered" });
382
+ continue;
383
+ }
384
+ const runnable = isRunnableEntrypoint(cur.entry.command, cur.entry.args);
385
+ out.push({
386
+ id,
387
+ label: info.label,
388
+ detected: true,
389
+ cliPath,
390
+ configPath: info.configPath,
391
+ status: runnable ? "registered" : "degraded",
392
+ detail: runnable ? "Registered in ~/.codex/config.toml (MCP guarded; native tools require rules/hooks)" : "Registered entrypoint is missing or stale; run `pi-charset doctor --fix`",
393
+ entrypoint: cur.entry.command && cur.entry.args ? { command: cur.entry.command, args: cur.entry.args } : undefined,
394
+ });
395
+ continue;
396
+ }
397
+ // JSON-based MCP clients (agy, claude, cursor)
398
+ const cur = readJsonMcpEntry(info.configPath);
399
+ if (!detected && !cur.exists) {
400
+ out.push({ id, label: info.label, detected: false, cliPath, configPath: info.configPath, status: "not_installed", detail: `${info.label} not detected` });
401
+ continue;
402
+ }
403
+ if (cur.parseError) {
404
+ out.push({ id, label: info.label, detected: true, cliPath, configPath: info.configPath, status: "degraded", detail: `Invalid JSON in ${info.configPath}: ${cur.parseError}` });
405
+ continue;
406
+ }
407
+ if (!cur.entry) {
408
+ out.push({ id, label: info.label, detected: true, cliPath, configPath: info.configPath, status: "unregistered", detail: "Detected; pi-charset MCP not yet registered" });
409
+ continue;
410
+ }
411
+ const runnable = isRunnableEntrypoint(cur.entry.command, cur.entry.args);
412
+ out.push({
413
+ id,
414
+ label: info.label,
415
+ detected: true,
416
+ cliPath,
417
+ configPath: info.configPath,
418
+ status: runnable ? "registered" : "degraded",
419
+ detail: runnable ? `Registered in ${info.configPath}` : "Registered entrypoint is missing or stale; run `pi-charset doctor --fix`",
420
+ entrypoint: cur.entry.command && cur.entry.args ? { command: cur.entry.command, args: cur.entry.args } : undefined,
421
+ });
422
+ }
423
+ return out;
424
+ }
425
+ export function runSetup(opts = {}) {
426
+ const node = checkNodeRequirement();
427
+ const home = defaultHome(opts.homeDir);
428
+ const backupRoot = defaultBackupRoot(home, opts.stateDir);
429
+ const nodePath = opts.nodePath || process.execPath;
430
+ const mcpEntryPath = opts.mcpEntryPath || path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, "$1")), "..", "..", "tools", "pi-charset-mcp.mjs");
431
+ const dryRun = opts.dryRun === true;
432
+ if (!node.ok && !opts.uninstall && !opts.rollback) {
433
+ return {
434
+ ok: false,
435
+ node,
436
+ 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.` }],
437
+ smoke: null,
438
+ };
439
+ }
440
+ const inspections = inspectClients({ homeDir: home, skipCliProbe: Boolean(opts.homeDir) });
441
+ const targetIds = opts.clients?.length
442
+ ? [...opts.clients]
443
+ : inspections.filter((c) => c.detected && c.id !== "pi").map((c) => c.id);
444
+ // If no clients were auto-detected and none explicitly specified, report cleanly without silently inventing configs.
445
+ const results = [];
446
+ const paths = adapterPaths(home);
447
+ for (const id of targetIds) {
448
+ const info = paths[id];
449
+ if (id === "pi") {
450
+ const piInsp = inspections.find((c) => c.id === "pi");
451
+ results.push({
452
+ id,
453
+ label: info.label,
454
+ configPath: info.configPath,
455
+ action: "skipped",
456
+ status: piInsp.status,
457
+ detail: piInsp.status === "registered" ? "Already configured in Pi" : "Manage Pi extension via `pi install npm:pi-charset`",
458
+ });
459
+ continue;
460
+ }
461
+ if (opts.rollback) {
462
+ const bak = readBackup(backupRoot, id);
463
+ if (!bak.found) {
464
+ results.push({ id, label: info.label, configPath: info.configPath, action: "skipped", status: "unregistered", detail: `No setup backup found for ${info.label}` });
465
+ continue;
466
+ }
467
+ const prev = bak.previous;
468
+ const upd = id === "codex"
469
+ ? updateCodexTomlConfig(info.configPath, backupRoot, prev, dryRun)
470
+ : updateJsonMcpConfig(id, info.configPath, backupRoot, prev, dryRun);
471
+ results.push({
472
+ id,
473
+ label: info.label,
474
+ configPath: info.configPath,
475
+ action: upd.action === "failed" ? "failed" : "rolled_back",
476
+ status: upd.action === "failed" ? "degraded" : prev ? "registered" : "unregistered",
477
+ detail: upd.detail,
478
+ });
479
+ continue;
480
+ }
481
+ const desired = opts.uninstall ? null : { command: nodePath, args: buildMcpArgs(mcpEntryPath, id, opts) };
482
+ const upd = id === "codex"
483
+ ? updateCodexTomlConfig(info.configPath, backupRoot, desired, dryRun)
484
+ : updateJsonMcpConfig(id, info.configPath, backupRoot, desired, dryRun);
485
+ const status = upd.action === "failed" ? "degraded" : opts.uninstall ? "unregistered" : "registered";
486
+ results.push({
487
+ id,
488
+ label: info.label,
489
+ configPath: info.configPath,
490
+ action: upd.action,
491
+ status,
492
+ detail: upd.detail,
493
+ });
494
+ }
495
+ let smoke = null;
496
+ if (!opts.uninstall && !opts.rollback && !dryRun && !opts.skipSmokeTest) {
497
+ smoke = verifyMcpSmoke(nodePath, mcpEntryPath);
498
+ if (smoke.ok) {
499
+ for (let i = 0; i < results.length; i++) {
500
+ if (results[i].status === "registered") {
501
+ results[i] = { ...results[i], status: "handshake_verified" };
502
+ }
503
+ }
504
+ }
505
+ }
506
+ const ok = results.every((r) => r.action !== "failed") && (smoke === null || smoke.ok);
507
+ return { ok, node, results, smoke };
508
+ }
509
+ /** Repair ONLY pi-charset-owned stale/degraded MCP registrations (never touches user source files or custom hooks). */
510
+ export function repairDegradedRegistrations(opts = {}) {
511
+ const inspections = inspectClients({ homeDir: opts.homeDir, skipCliProbe: Boolean(opts.homeDir) });
512
+ const degraded = inspections.filter((c) => c.id !== "pi" && c.status === "degraded" && c.entrypoint !== undefined);
513
+ if (degraded.length === 0)
514
+ return [];
515
+ const res = runSetup({
516
+ clients: degraded.map((c) => c.id),
517
+ homeDir: opts.homeDir,
518
+ stateDir: opts.stateDir,
519
+ nodePath: opts.nodePath,
520
+ mcpEntryPath: opts.mcpEntryPath,
521
+ skipSmokeTest: true,
522
+ });
523
+ return res.results;
524
+ }
package/dist/version.js CHANGED
@@ -1,2 +1,2 @@
1
1
  // Synchronized with package.json version.
2
- export const PLUGIN_VERSION = "0.1.7";
2
+ export const PLUGIN_VERSION = "0.1.8";
@@ -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 installs:
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`)
@@ -18,14 +18,29 @@
18
18
 
19
19
  如果你希望为纯 GBK 老工程锁定默认编码/行尾且**不想在仓库里新建 JSON 文件**,直接通过启动参数(`--encoding GBK --eol CRLF --prefer-legacy --hashlines --auto-commit`)或 `PI_CHARSET_*` 环境变量传入即可。
20
20
 
21
- 一键打印安装命令或配置片段:
21
+ 推荐使用一条命令自动完成无损注册(写入永久绝对路径的 `node` + `pi-charset-mcp.mjs`,不覆盖第三方 MCP 与用户设置,并在隔离临时目录执行合成 GBK/CRLF 读写撤回自检):
22
22
 
23
23
  ```bash
24
+ # 自动探测并注册已安装的 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
+ # 结构化环境体检与仅限工具自有失效条目的安全修复
31
+ npx pi-charset doctor --json
32
+ npx pi-charset doctor --fix
33
+
34
+ # 纯本地脱敏故障诊断(默认零联网、零源码/路径收集;设 PI_CHARSET_DIAGNOSTICS=0 可彻底关闭)
35
+ npx pi-charset feedback list
36
+ npx pi-charset feedback preview <fingerprint>
37
+ npx pi-charset feedback issue-url <fingerprint>
38
+
39
+ # 或手动打印配置片段
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(一条命令装好,无需手改配置,也无需 `.pi-charset.json`)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-charset",
3
- "version": "0.1.7",
3
+ "version": "0.1.8",
4
4
  "description": "Encoding-aware read, write, edit, and grep extension for Pi",
5
5
  "type": "module",
6
6
  "license": "MIT",