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,613 @@
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";
11
+
12
+ export type HostClientId = "pi" | "codex" | "agy" | "claude" | "cursor";
13
+
14
+ export type AdapterStatus =
15
+ | "not_installed"
16
+ | "unregistered"
17
+ | "registered"
18
+ | "handshake_verified"
19
+ | "degraded";
20
+
21
+ export interface ClientInspection {
22
+ readonly id: HostClientId;
23
+ readonly label: string;
24
+ readonly detected: boolean;
25
+ readonly cliPath: string | null;
26
+ readonly configPath: string;
27
+ readonly status: AdapterStatus;
28
+ readonly detail: string;
29
+ readonly entrypoint?: { readonly command: string; readonly args: readonly string[] };
30
+ }
31
+
32
+ export interface SetupActionResult {
33
+ readonly id: HostClientId;
34
+ readonly label: string;
35
+ readonly configPath: string;
36
+ readonly action: "registered" | "updated" | "unchanged" | "uninstalled" | "rolled_back" | "skipped" | "failed";
37
+ readonly status: AdapterStatus;
38
+ readonly detail: string;
39
+ }
40
+
41
+ export interface SetupOptions {
42
+ readonly clients?: readonly HostClientId[];
43
+ readonly dryRun?: boolean;
44
+ readonly uninstall?: boolean;
45
+ readonly rollback?: boolean;
46
+ readonly encoding?: string;
47
+ readonly eol?: "CRLF" | "LF";
48
+ readonly preferLegacy?: boolean;
49
+ readonly hashlines?: boolean;
50
+ readonly autoCommit?: boolean;
51
+ readonly homeDir?: string;
52
+ readonly stateDir?: string;
53
+ readonly nodePath?: string;
54
+ readonly mcpEntryPath?: string;
55
+ readonly skipSmokeTest?: boolean;
56
+ }
57
+
58
+ export interface SmokeTestResult {
59
+ readonly ok: boolean;
60
+ readonly latencyMs: number;
61
+ readonly protocolVersion?: string;
62
+ readonly toolCount?: number;
63
+ readonly detail: string;
64
+ }
65
+
66
+ export function checkNodeRequirement(versionStr = process.versions.node): { ok: boolean; current: string; required: string } {
67
+ const [maj, min] = versionStr.split(".").map((n) => Number(n) || 0);
68
+ const ok = maj > 22 || (maj === 22 && min >= 19);
69
+ return { ok, current: versionStr, required: ">=22.19.0" };
70
+ }
71
+
72
+ function defaultHome(override?: string): string {
73
+ return path.resolve(override || process.env.PI_CHARSET_HOME || os.homedir());
74
+ }
75
+
76
+ function defaultBackupRoot(home: string, stateOverride?: string): string {
77
+ if (stateOverride) return path.resolve(stateOverride);
78
+ if (process.platform === "win32") {
79
+ return path.join(process.env.LOCALAPPDATA || path.join(home, "AppData", "Local"), "pi-charset", "setup-backups");
80
+ }
81
+ if (process.platform === "darwin") {
82
+ return path.join(home, "Library", "Application Support", "pi-charset", "setup-backups");
83
+ }
84
+ return path.join(process.env.XDG_STATE_HOME || path.join(home, ".local", "state"), "pi-charset", "setup-backups");
85
+ }
86
+
87
+ function probeBinary(cmd: string): string | null {
88
+ try {
89
+ const r = spawnSync(cmd, ["--version"], { stdio: "ignore", windowsHide: true, timeout: 2500 });
90
+ if (!r.error && r.status === 0) return cmd;
91
+ } catch { /* not found */ }
92
+ return null;
93
+ }
94
+
95
+ function atomicWriteText(targetPath: string, content: string): void {
96
+ const dir = path.dirname(targetPath);
97
+ fs.mkdirSync(dir, { recursive: true });
98
+ let mode: number | undefined;
99
+ try {
100
+ const st = fs.lstatSync(targetPath);
101
+ if (st.isSymbolicLink()) throw new Error(`Refused to write symbolic link: ${targetPath}`);
102
+ mode = st.mode & 0o777;
103
+ } catch (e) {
104
+ if ((e as NodeJS.ErrnoException)?.code !== "ENOENT") throw e;
105
+ }
106
+ const tmp = `${targetPath}.${randomBytes(6).toString("hex")}.pi-charset.tmp`;
107
+ try {
108
+ fs.writeFileSync(tmp, content, { encoding: "utf8", flag: "wx", ...(mode !== undefined ? { mode } : {}) });
109
+ fs.renameSync(tmp, targetPath);
110
+ } finally {
111
+ try { fs.unlinkSync(tmp); } catch { /* cleaned up */ }
112
+ }
113
+ }
114
+
115
+ function buildMcpArgs(mcpEntryPath: string, client: HostClientId, opts: SetupOptions): string[] {
116
+ const args = [mcpEntryPath, "--client", client];
117
+ if (opts.encoding) args.push("--encoding", opts.encoding);
118
+ if (opts.eol) args.push("--eol", opts.eol);
119
+ if (opts.preferLegacy) args.push("--prefer-legacy");
120
+ if (opts.hashlines) args.push("--hashlines");
121
+ if (opts.autoCommit) args.push("--auto-commit");
122
+ return args;
123
+ }
124
+
125
+ function sameStringArray(a: readonly string[] | undefined, b: readonly string[]): boolean {
126
+ if (!Array.isArray(a) || a.length !== b.length) return false;
127
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
128
+ return true;
129
+ }
130
+
131
+ function isRunnableEntrypoint(command: string | undefined, args: readonly string[] | undefined): boolean {
132
+ if (!command || !Array.isArray(args) || args.length === 0) return false;
133
+ const cmdOk = command === "node" || command === "npx" || fs.existsSync(command);
134
+ const entry = args[0];
135
+ const entryOk = command === "npx" ? true : typeof entry === "string" && fs.existsSync(entry);
136
+ return cmdOk && entryOk;
137
+ }
138
+
139
+ // --- JSON MCP config helpers (Antigravity CLI ~/.gemini/config/mcp_config.json, Claude ~/.claude.json, Cursor ~/.cursor/mcp.json) ---
140
+
141
+ interface JsonMcpRecord {
142
+ command?: string;
143
+ args?: string[];
144
+ }
145
+
146
+ function readJsonMcpEntry(configPath: string): {
147
+ exists: boolean;
148
+ parseError?: string;
149
+ root?: Record<string, unknown>;
150
+ entry?: JsonMcpRecord;
151
+ } {
152
+ if (!fs.existsSync(configPath)) return { exists: false };
153
+ try {
154
+ const raw = fs.readFileSync(configPath, "utf8");
155
+ const parsed = JSON.parse(raw);
156
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
157
+ return { exists: true, parseError: "Root JSON value is not an object" };
158
+ }
159
+ const root = parsed as Record<string, unknown>;
160
+ const servers = root.mcpServers;
161
+ if (servers !== undefined && (typeof servers !== "object" || servers === null || Array.isArray(servers))) {
162
+ return { exists: true, parseError: `"mcpServers" is not an object` };
163
+ }
164
+ const entry = (servers as Record<string, unknown> | undefined)?.["pi-charset"] as JsonMcpRecord | undefined;
165
+ return { exists: true, root, entry };
166
+ } catch (e) {
167
+ return { exists: true, parseError: (e as Error).message };
168
+ }
169
+ }
170
+
171
+ function saveBackup(backupRoot: string, id: HostClientId, previous: unknown): void {
172
+ fs.mkdirSync(backupRoot, { recursive: true, mode: 0o700 });
173
+ const file = path.join(backupRoot, `${id}.json`);
174
+ atomicWriteText(file, JSON.stringify({ id, savedAt: new Date().toISOString(), previous }, null, 2) + "\n");
175
+ }
176
+
177
+ function readBackup(backupRoot: string, id: HostClientId): { found: boolean; previous?: unknown } {
178
+ const file = path.join(backupRoot, `${id}.json`);
179
+ if (!fs.existsSync(file)) return { found: false };
180
+ try {
181
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
182
+ return { found: true, previous: parsed.previous };
183
+ } catch {
184
+ return { found: false };
185
+ }
186
+ }
187
+
188
+ function updateJsonMcpConfig(
189
+ id: HostClientId,
190
+ configPath: string,
191
+ backupRoot: string,
192
+ desired: { command: string; args: string[] } | null,
193
+ dryRun: boolean,
194
+ ): { action: SetupActionResult["action"]; detail: string } {
195
+ const cur = readJsonMcpEntry(configPath);
196
+ if (cur.parseError) {
197
+ return { action: "failed", detail: `Refused to modify invalid JSON at ${configPath}: ${cur.parseError}` };
198
+ }
199
+ const root: Record<string, unknown> = cur.root ? { ...cur.root } : {};
200
+ const servers: Record<string, unknown> =
201
+ root.mcpServers && typeof root.mcpServers === "object" && !Array.isArray(root.mcpServers)
202
+ ? { ...(root.mcpServers as Record<string, unknown>) }
203
+ : {};
204
+ const prev = servers["pi-charset"] as JsonMcpRecord | undefined;
205
+
206
+ if (desired === null) {
207
+ if (!prev) return { action: "unchanged", detail: `Not registered in ${configPath}` };
208
+ if (dryRun) return { action: "uninstalled", detail: `[dry-run] Would remove pi-charset from ${configPath}` };
209
+ saveBackup(backupRoot, id, prev);
210
+ delete servers["pi-charset"];
211
+ root.mcpServers = servers;
212
+ atomicWriteText(configPath, JSON.stringify(root, null, 2) + "\n");
213
+ return { action: "uninstalled", detail: `Removed pi-charset from ${configPath} (other MCP servers preserved)` };
214
+ }
215
+
216
+ if (prev && prev.command === desired.command && sameStringArray(prev.args, desired.args)) {
217
+ return { action: "unchanged", detail: `Already registered with current entrypoint in ${configPath}` };
218
+ }
219
+ const action = prev ? "updated" : "registered";
220
+ if (dryRun) {
221
+ return { action, detail: `[dry-run] Would ${action === "updated" ? "update" : "add"} pi-charset in ${configPath}` };
222
+ }
223
+ saveBackup(backupRoot, id, prev ?? null);
224
+ servers["pi-charset"] = { command: desired.command, args: desired.args };
225
+ root.mcpServers = servers;
226
+ atomicWriteText(configPath, JSON.stringify(root, null, 2) + "\n");
227
+ return { action, detail: `${action === "updated" ? "Updated" : "Registered"} pi-charset in ${configPath}` };
228
+ }
229
+
230
+ // --- Codex TOML helpers (~/.codex/config.toml) ---
231
+ // Scoped surgical section edit affecting ONLY `[mcp_servers.pi-charset]` / `[mcp_servers."pi-charset"]`,
232
+ // preserving all comments, formatting, and third-party TOML sections verbatim.
233
+
234
+ const CODEX_SECTION_HEADER = /^\s*\[mcp_servers\.(?:"pi-charset"|'pi-charset'|pi-charset)\]\s*(?:#.*)?$/;
235
+ const ANY_TOML_SECTION = /^\s*\[[^\]]+\]\s*(?:#.*)?$/;
236
+
237
+ function findCodexSection(lines: readonly string[]): { start: number; end: number } | null {
238
+ let start = -1;
239
+ for (let i = 0; i < lines.length; i++) {
240
+ if (CODEX_SECTION_HEADER.test(lines[i])) {
241
+ start = i;
242
+ break;
243
+ }
244
+ }
245
+ if (start === -1) return null;
246
+ let end = lines.length;
247
+ for (let i = start + 1; i < lines.length; i++) {
248
+ if (ANY_TOML_SECTION.test(lines[i])) {
249
+ end = i;
250
+ break;
251
+ }
252
+ }
253
+ return { start, end };
254
+ }
255
+
256
+ function parseCodexSectionEntry(sectionLines: readonly string[]): JsonMcpRecord | undefined {
257
+ let command: string | undefined;
258
+ let args: string[] | undefined;
259
+ for (const line of sectionLines) {
260
+ const cm = /^\s*command\s*=\s*("(?:[^"\\]|\\.)*")/.exec(line);
261
+ if (cm) {
262
+ try { command = JSON.parse(cm[1]); } catch { /* ignore */ }
263
+ }
264
+ const am = /^\s*args\s*=\s*(\[.*\])\s*(?:#.*)?$/.exec(line);
265
+ if (am) {
266
+ try {
267
+ const parsed = JSON.parse(am[1]);
268
+ if (Array.isArray(parsed) && parsed.every((x) => typeof x === "string")) args = parsed;
269
+ } catch { /* ignore */ }
270
+ }
271
+ }
272
+ return command || args ? { command, args } : undefined;
273
+ }
274
+
275
+ function readCodexTomlEntry(configPath: string): { exists: boolean; raw: string; entry?: JsonMcpRecord; sectionText?: string } {
276
+ if (!fs.existsSync(configPath)) return { exists: false, raw: "" };
277
+ const raw = fs.readFileSync(configPath, "utf8");
278
+ const lines = raw.split(/\r?\n/);
279
+ const span = findCodexSection(lines);
280
+ if (!span) return { exists: true, raw };
281
+ const sectionLines = lines.slice(span.start, span.end);
282
+ return { exists: true, raw, entry: parseCodexSectionEntry(sectionLines), sectionText: sectionLines.join("\n") };
283
+ }
284
+
285
+ function formatCodexSection(desired: { command: string; args: string[] }): string[] {
286
+ return [
287
+ `[mcp_servers.pi-charset]`,
288
+ `command = ${JSON.stringify(desired.command)}`,
289
+ `args = ${JSON.stringify(desired.args)}`,
290
+ ];
291
+ }
292
+
293
+ function updateCodexTomlConfig(
294
+ configPath: string,
295
+ backupRoot: string,
296
+ desired: { command: string; args: string[] } | null,
297
+ dryRun: boolean,
298
+ ): { action: SetupActionResult["action"]; detail: string } {
299
+ const cur = readCodexTomlEntry(configPath);
300
+ const eol = cur.raw.includes("\r\n") ? "\r\n" : "\n";
301
+ const lines = cur.raw ? cur.raw.split(/\r?\n/) : [];
302
+ const span = findCodexSection(lines);
303
+
304
+ if (desired === null) {
305
+ if (!span) return { action: "unchanged", detail: `Not registered in ${configPath}` };
306
+ if (dryRun) return { action: "uninstalled", detail: `[dry-run] Would remove [mcp_servers.pi-charset] from ${configPath}` };
307
+ saveBackup(backupRoot, "codex", cur.entry ?? null);
308
+ let end = span.end;
309
+ while (end < lines.length && lines[end].trim() === "") end++;
310
+ const next = [...lines.slice(0, span.start), ...lines.slice(end)].join(eol).replace(/(\r?\n){3,}/g, `${eol}${eol}`);
311
+ atomicWriteText(configPath, next.endsWith(eol) || next === "" ? next : next + eol);
312
+ return { action: "uninstalled", detail: `Removed [mcp_servers.pi-charset] from ${configPath}` };
313
+ }
314
+
315
+ if (cur.entry && cur.entry.command === desired.command && sameStringArray(cur.entry.args, desired.args)) {
316
+ return { action: "unchanged", detail: `Already registered with current entrypoint in ${configPath}` };
317
+ }
318
+ const action = span ? "updated" : "registered";
319
+ if (dryRun) {
320
+ return { action, detail: `[dry-run] Would ${action === "updated" ? "update" : "add"} [mcp_servers.pi-charset] in ${configPath}` };
321
+ }
322
+ saveBackup(backupRoot, "codex", cur.entry ?? null);
323
+ const block = formatCodexSection(desired);
324
+ let nextLines: string[];
325
+ if (span) {
326
+ nextLines = [...lines.slice(0, span.start), ...block, "", ...lines.slice(span.end)];
327
+ } else {
328
+ const trimmed = [...lines];
329
+ while (trimmed.length > 0 && trimmed[trimmed.length - 1].trim() === "") trimmed.pop();
330
+ nextLines = trimmed.length > 0 ? [...trimmed, "", ...block, ""] : [...block, ""];
331
+ }
332
+ atomicWriteText(configPath, nextLines.join(eol));
333
+ return { action, detail: `${action === "updated" ? "Updated" : "Registered"} [mcp_servers.pi-charset] in ${configPath}` };
334
+ }
335
+
336
+ function adapterPaths(home: string): Record<HostClientId, { label: string; configPath: string; dirHint: string; cliBin?: string }> {
337
+ return {
338
+ pi: { label: "Pi", configPath: path.join(home, ".pi", "agent", "settings.json"), dirHint: path.join(home, ".pi"), cliBin: "pi" },
339
+ codex: { label: "Codex CLI/IDE", configPath: path.join(home, ".codex", "config.toml"), dirHint: path.join(home, ".codex"), cliBin: "codex" },
340
+ agy: { label: "Antigravity CLI", configPath: path.join(home, ".gemini", "config", "mcp_config.json"), dirHint: path.join(home, ".gemini"), cliBin: "agy" },
341
+ claude: { label: "Claude Code", configPath: path.join(home, ".claude.json"), dirHint: path.join(home, ".claude"), cliBin: "claude" },
342
+ cursor: { label: "Cursor", configPath: path.join(home, ".cursor", "mcp.json"), dirHint: path.join(home, ".cursor") },
343
+ };
344
+ }
345
+
346
+ /** Run an isolated synthetic GBK+CRLF MCP stdio handshake + read/edit/undo smoke test in os.tmpdir(). */
347
+ export function verifyMcpSmoke(nodePath: string, mcpEntryPath: string): SmokeTestResult {
348
+ const t0 = performance.now();
349
+ if (!fs.existsSync(mcpEntryPath)) {
350
+ return { ok: false, latencyMs: 0, detail: `MCP entrypoint missing: ${mcpEntryPath}` };
351
+ }
352
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "pi-charset-setup-smoke-"));
353
+ try {
354
+ const sample = path.join(tmp, "smoke.c");
355
+ const origBytes = iconv.encode("// 电机编码自检\r\nint speed = 100;\r\n", "GBK");
356
+ fs.writeFileSync(sample, origBytes);
357
+
358
+ const runRpc = (lines: unknown[]) =>
359
+ spawnSync(nodePath, [mcpEntryPath, "--cwd", tmp, "--client", "generic"], {
360
+ input: lines.map((l) => JSON.stringify(l)).join("\n") + "\n",
361
+ encoding: "utf8",
362
+ windowsHide: true,
363
+ timeout: 12000,
364
+ });
365
+
366
+ // Step 1: initialize + tools/list + read + edit + undo in ONE live stdio session.
367
+ const r1 = runRpc([
368
+ { jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-03-26", capabilities: {}, clientInfo: { name: "pi-charset-setup", version: PLUGIN_VERSION } } },
369
+ { jsonrpc: "2.0", id: 2, method: "tools/list", params: {} },
370
+ { jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "charset_read", arguments: { path: "smoke.c" } } },
371
+ { 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;" }] } } },
372
+ { jsonrpc: "2.0", id: 5, method: "tools/call", params: { name: "charset_fix", arguments: { action: "undo" } } },
373
+ ]);
374
+ const latencyMs = Math.round(performance.now() - t0);
375
+ if (r1.status !== 0) {
376
+ return { ok: false, latencyMs, detail: `MCP exited with code ${r1.status}: ${(r1.stderr || "").trim().slice(0, 160)}` };
377
+ }
378
+ const replies = r1.stdout.trim().split(/\r?\n/).filter(Boolean).map((l) => JSON.parse(l));
379
+ if (replies.length !== 5) {
380
+ return { ok: false, latencyMs, detail: `Expected 5 JSON-RPC replies, got ${replies.length}` };
381
+ }
382
+ const protocolVersion = replies[0]?.result?.protocolVersion;
383
+ const toolCount = Array.isArray(replies[1]?.result?.tools) ? replies[1].result.tools.length : 0;
384
+ const readText = replies[2]?.result?.content?.[0]?.text ?? "";
385
+ if (!readText.includes("电机编码自检")) {
386
+ return { ok: false, latencyMs, detail: "GBK read verification failed" };
387
+ }
388
+ if (replies[3]?.result?.isError || replies[4]?.result?.isError) {
389
+ return { ok: false, latencyMs, detail: "GBK edit/undo verification returned isError" };
390
+ }
391
+ if (!fs.readFileSync(sample).equals(origBytes)) {
392
+ return { ok: false, latencyMs, detail: "GBK undo did not restore exact original bytes" };
393
+ }
394
+ return {
395
+ ok: true,
396
+ latencyMs,
397
+ protocolVersion,
398
+ toolCount,
399
+ detail: `read/edit/undo GBK+CRLF round-trip verified (${latencyMs}ms, ${toolCount} tools)`,
400
+ };
401
+ } catch (e) {
402
+ return { ok: false, latencyMs: Math.round(performance.now() - t0), detail: (e as Error).message };
403
+ } finally {
404
+ fs.rmSync(tmp, { recursive: true, force: true });
405
+ }
406
+ }
407
+
408
+ export function inspectClients(opts: { homeDir?: string; skipCliProbe?: boolean } = {}): ClientInspection[] {
409
+ const home = defaultHome(opts.homeDir);
410
+ const paths = adapterPaths(home);
411
+ const out: ClientInspection[] = [];
412
+
413
+ for (const id of ["pi", "codex", "agy", "claude", "cursor"] as const) {
414
+ const info = paths[id];
415
+ const cliPath = !opts.skipCliProbe && info.cliBin ? probeBinary(info.cliBin) : null;
416
+ const dirExists = fs.existsSync(info.dirHint) || fs.existsSync(info.configPath);
417
+ const detected = Boolean(cliPath || dirExists);
418
+
419
+ if (id === "pi") {
420
+ if (!detected) {
421
+ out.push({ id, label: info.label, detected: false, cliPath, configPath: info.configPath, status: "not_installed", detail: "Pi CLI / ~/.pi not detected" });
422
+ continue;
423
+ }
424
+ let hasExt = false;
425
+ if (fs.existsSync(info.configPath)) {
426
+ try {
427
+ const raw = fs.readFileSync(info.configPath, "utf8");
428
+ hasExt = raw.includes("pi-charset");
429
+ } catch { /* ignore */ }
430
+ }
431
+ out.push({
432
+ id,
433
+ label: info.label,
434
+ detected: true,
435
+ cliPath,
436
+ configPath: info.configPath,
437
+ status: hasExt ? "registered" : "unregistered",
438
+ detail: hasExt ? "pi-charset referenced in Pi settings" : "Install via `pi install npm:pi-charset`",
439
+ });
440
+ continue;
441
+ }
442
+
443
+ if (id === "codex") {
444
+ const cur = readCodexTomlEntry(info.configPath);
445
+ if (!detected && !cur.exists) {
446
+ out.push({ id, label: info.label, detected: false, cliPath, configPath: info.configPath, status: "not_installed", detail: "Codex CLI / ~/.codex not detected" });
447
+ continue;
448
+ }
449
+ if (!cur.entry) {
450
+ out.push({ id, label: info.label, detected: true, cliPath, configPath: info.configPath, status: "unregistered", detail: "Detected; pi-charset MCP not yet registered" });
451
+ continue;
452
+ }
453
+ const runnable = isRunnableEntrypoint(cur.entry.command, cur.entry.args);
454
+ out.push({
455
+ id,
456
+ label: info.label,
457
+ detected: true,
458
+ cliPath,
459
+ configPath: info.configPath,
460
+ status: runnable ? "registered" : "degraded",
461
+ 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`",
462
+ entrypoint: cur.entry.command && cur.entry.args ? { command: cur.entry.command, args: cur.entry.args } : undefined,
463
+ });
464
+ continue;
465
+ }
466
+
467
+ // JSON-based MCP clients (agy, claude, cursor)
468
+ const cur = readJsonMcpEntry(info.configPath);
469
+ if (!detected && !cur.exists) {
470
+ out.push({ id, label: info.label, detected: false, cliPath, configPath: info.configPath, status: "not_installed", detail: `${info.label} not detected` });
471
+ continue;
472
+ }
473
+ if (cur.parseError) {
474
+ out.push({ id, label: info.label, detected: true, cliPath, configPath: info.configPath, status: "degraded", detail: `Invalid JSON in ${info.configPath}: ${cur.parseError}` });
475
+ continue;
476
+ }
477
+ if (!cur.entry) {
478
+ out.push({ id, label: info.label, detected: true, cliPath, configPath: info.configPath, status: "unregistered", detail: "Detected; pi-charset MCP not yet registered" });
479
+ continue;
480
+ }
481
+ const runnable = isRunnableEntrypoint(cur.entry.command, cur.entry.args);
482
+ out.push({
483
+ id,
484
+ label: info.label,
485
+ detected: true,
486
+ cliPath,
487
+ configPath: info.configPath,
488
+ status: runnable ? "registered" : "degraded",
489
+ detail: runnable ? `Registered in ${info.configPath}` : "Registered entrypoint is missing or stale; run `pi-charset doctor --fix`",
490
+ entrypoint: cur.entry.command && cur.entry.args ? { command: cur.entry.command, args: cur.entry.args } : undefined,
491
+ });
492
+ }
493
+
494
+ return out;
495
+ }
496
+
497
+ export function runSetup(opts: SetupOptions = {}): {
498
+ ok: boolean;
499
+ node: ReturnType<typeof checkNodeRequirement>;
500
+ results: SetupActionResult[];
501
+ smoke: SmokeTestResult | null;
502
+ } {
503
+ const node = checkNodeRequirement();
504
+ const home = defaultHome(opts.homeDir);
505
+ const backupRoot = defaultBackupRoot(home, opts.stateDir);
506
+ const nodePath = opts.nodePath || process.execPath;
507
+ const mcpEntryPath = opts.mcpEntryPath || path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, "$1")), "..", "..", "tools", "pi-charset-mcp.mjs");
508
+ const dryRun = opts.dryRun === true;
509
+
510
+ if (!node.ok && !opts.uninstall && !opts.rollback) {
511
+ return {
512
+ ok: false,
513
+ node,
514
+ 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.` }],
515
+ smoke: null,
516
+ };
517
+ }
518
+
519
+ const inspections = inspectClients({ homeDir: home, skipCliProbe: Boolean(opts.homeDir) });
520
+ const targetIds: HostClientId[] = opts.clients?.length
521
+ ? [...opts.clients]
522
+ : inspections.filter((c) => c.detected && c.id !== "pi").map((c) => c.id);
523
+
524
+ // If no clients were auto-detected and none explicitly specified, report cleanly without silently inventing configs.
525
+ const results: SetupActionResult[] = [];
526
+ const paths = adapterPaths(home);
527
+
528
+ for (const id of targetIds) {
529
+ const info = paths[id];
530
+ if (id === "pi") {
531
+ const piInsp = inspections.find((c) => c.id === "pi")!;
532
+ results.push({
533
+ id,
534
+ label: info.label,
535
+ configPath: info.configPath,
536
+ action: "skipped",
537
+ status: piInsp.status,
538
+ detail: piInsp.status === "registered" ? "Already configured in Pi" : "Manage Pi extension via `pi install npm:pi-charset`",
539
+ });
540
+ continue;
541
+ }
542
+
543
+ if (opts.rollback) {
544
+ const bak = readBackup(backupRoot, id);
545
+ if (!bak.found) {
546
+ results.push({ id, label: info.label, configPath: info.configPath, action: "skipped", status: "unregistered", detail: `No setup backup found for ${info.label}` });
547
+ continue;
548
+ }
549
+ const prev = bak.previous as { command: string; args: string[] } | null;
550
+ const upd =
551
+ id === "codex"
552
+ ? updateCodexTomlConfig(info.configPath, backupRoot, prev, dryRun)
553
+ : updateJsonMcpConfig(id, info.configPath, backupRoot, prev, dryRun);
554
+ results.push({
555
+ id,
556
+ label: info.label,
557
+ configPath: info.configPath,
558
+ action: upd.action === "failed" ? "failed" : "rolled_back",
559
+ status: upd.action === "failed" ? "degraded" : prev ? "registered" : "unregistered",
560
+ detail: upd.detail,
561
+ });
562
+ continue;
563
+ }
564
+
565
+ const desired = opts.uninstall ? null : { command: nodePath, args: buildMcpArgs(mcpEntryPath, id, opts) };
566
+ const upd =
567
+ id === "codex"
568
+ ? updateCodexTomlConfig(info.configPath, backupRoot, desired, dryRun)
569
+ : updateJsonMcpConfig(id, info.configPath, backupRoot, desired, dryRun);
570
+
571
+ const status: AdapterStatus =
572
+ upd.action === "failed" ? "degraded" : opts.uninstall ? "unregistered" : "registered";
573
+ results.push({
574
+ id,
575
+ label: info.label,
576
+ configPath: info.configPath,
577
+ action: upd.action,
578
+ status,
579
+ detail: upd.detail,
580
+ });
581
+ }
582
+
583
+ let smoke: SmokeTestResult | null = null;
584
+ if (!opts.uninstall && !opts.rollback && !dryRun && !opts.skipSmokeTest) {
585
+ smoke = verifyMcpSmoke(nodePath, mcpEntryPath);
586
+ if (smoke.ok) {
587
+ for (let i = 0; i < results.length; i++) {
588
+ if (results[i].status === "registered") {
589
+ results[i] = { ...results[i], status: "handshake_verified" };
590
+ }
591
+ }
592
+ }
593
+ }
594
+
595
+ const ok = results.every((r) => r.action !== "failed") && (smoke === null || smoke.ok);
596
+ return { ok, node, results, smoke };
597
+ }
598
+
599
+ /** Repair ONLY pi-charset-owned stale/degraded MCP registrations (never touches user source files or custom hooks). */
600
+ export function repairDegradedRegistrations(opts: { homeDir?: string; stateDir?: string; nodePath?: string; mcpEntryPath?: string } = {}): SetupActionResult[] {
601
+ const inspections = inspectClients({ homeDir: opts.homeDir, skipCliProbe: Boolean(opts.homeDir) });
602
+ const degraded = inspections.filter((c) => c.id !== "pi" && c.status === "degraded" && c.entrypoint !== undefined);
603
+ if (degraded.length === 0) return [];
604
+ const res = runSetup({
605
+ clients: degraded.map((c) => c.id),
606
+ homeDir: opts.homeDir,
607
+ stateDir: opts.stateDir,
608
+ nodePath: opts.nodePath,
609
+ mcpEntryPath: opts.mcpEntryPath,
610
+ skipSmokeTest: true,
611
+ });
612
+ return res.results;
613
+ }
package/src/version.ts 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";