@blackbelt-technology/pi-dashboard-apple-tools 0.7.0

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/src/env.ts ADDED
@@ -0,0 +1,146 @@
1
+ /**
2
+ * Real-environment factory for {@link InstallerEnv}. This is the ONLY module
3
+ * that touches the real OS — every probe and side effect is concentrated here
4
+ * so the state machine (`install.ts`) stays pure and Linux-testable.
5
+ *
6
+ * Security discipline (see change: add-apple-tools-imcp-plugin, Decision 4):
7
+ * - `brew` is invoked with an argv array via execFileSync — never a shell,
8
+ * so no probed value (path, sw_vers output) can reach a shell string.
9
+ * - config writes are temp-file + atomic rename.
10
+ */
11
+
12
+ import { randomBytes } from "node:crypto";
13
+ import {
14
+ closeSync,
15
+ existsSync,
16
+ fsyncSync,
17
+ mkdirSync,
18
+ openSync,
19
+ readFileSync,
20
+ renameSync,
21
+ unlinkSync,
22
+ writeSync,
23
+ } from "node:fs";
24
+ import { homedir } from "node:os";
25
+ import { dirname, join } from "node:path";
26
+ import { execFileSync } from "@blackbelt-technology/pi-dashboard-shared/platform/exec.js";
27
+ import { IMCP_BREW_CASK } from "./detect.js";
28
+ import type { BrewResult, InstallerEnv } from "./install.js";
29
+ import type { ConfigIO } from "./mcp-config.js";
30
+
31
+ /** 10-minute cap on the brew cask install (design X4). */
32
+ export const BREW_TIMEOUT_MS = 10 * 60 * 1000;
33
+
34
+ function probeOsVersion(): string | null {
35
+ try {
36
+ const out = execFileSync("sw_vers", ["-productVersion"], { encoding: "utf8" });
37
+ const v = out.trim();
38
+ return v === "" ? null : v;
39
+ } catch {
40
+ return null;
41
+ }
42
+ }
43
+
44
+ function brewPath(): string | null {
45
+ try {
46
+ const out = execFileSync("/usr/bin/which", ["brew"], { encoding: "utf8" });
47
+ const p = out.trim();
48
+ return p === "" ? null : p;
49
+ } catch {
50
+ return null;
51
+ }
52
+ }
53
+
54
+ function runBrewCask(brew: string): BrewResult {
55
+ try {
56
+ // argv array; NEVER a shell string. The cask ref is a constant, not a probe.
57
+ execFileSync(brew, ["install", "--cask", IMCP_BREW_CASK], {
58
+ encoding: "utf8",
59
+ timeout: BREW_TIMEOUT_MS,
60
+ stdio: ["ignore", "pipe", "pipe"],
61
+ });
62
+ return { code: 0, stderr: "" };
63
+ } catch (e) {
64
+ const err = e as { status?: number; signal?: string; stderr?: Buffer | string; code?: string };
65
+ const timedOut = err.signal === "SIGTERM" || err.code === "ETIMEDOUT";
66
+ const stderr = typeof err.stderr === "string" ? err.stderr : (err.stderr?.toString() ?? "");
67
+ return { code: err.status ?? 1, stderr, timedOut };
68
+ }
69
+ }
70
+
71
+ /**
72
+ * Atomic write: temp file in the target dir, fsync, then rename over the
73
+ * destination. Hardened per the security pass:
74
+ * - `wx` + a random name: never follow or clobber a pre-planted symlink.
75
+ * - mode 0600: a rename carries the temp file's mode onto the destination, so
76
+ * a default-umask temp would silently widen a 0600 user config that may hold
77
+ * another server's credential `env` block.
78
+ * - fsync before rename: a rename over unflushed data can surface as a
79
+ * zero-length config after a crash — the truncation this exists to prevent.
80
+ * - unlink the temp on failure: no leftovers on ENOSPC/EACCES.
81
+ */
82
+ function writeFileAtomic(path: string, content: string): void {
83
+ const dir = dirname(path);
84
+ mkdirSync(dir, { recursive: true });
85
+ const tmp = join(dir, `.${randomBytes(8).toString("hex")}.tmp`);
86
+ const fd = openSync(tmp, "wx", 0o600);
87
+ try {
88
+ // writeSync may perform a partial write; loop until the buffer is drained
89
+ // rather than assuming one call consumes it all.
90
+ const buf = Buffer.from(content, "utf8");
91
+ let off = 0;
92
+ while (off < buf.length) {
93
+ off += writeSync(fd, buf, off, buf.length - off);
94
+ }
95
+ fsyncSync(fd);
96
+ } catch (e) {
97
+ closeSync(fd);
98
+ try {
99
+ unlinkSync(tmp);
100
+ } catch {
101
+ /* best effort */
102
+ }
103
+ throw e;
104
+ }
105
+ closeSync(fd);
106
+ try {
107
+ renameSync(tmp, path);
108
+ } catch (e) {
109
+ try {
110
+ unlinkSync(tmp);
111
+ } catch {
112
+ /* best effort */
113
+ }
114
+ throw e;
115
+ }
116
+ }
117
+
118
+ const realConfigIO: ConfigIO = {
119
+ readFile: (p) => (existsSync(p) ? readFileSync(p, "utf8") : null),
120
+ writeFileAtomic,
121
+ };
122
+
123
+ export interface CreateEnvOptions {
124
+ /** Operator override for the imcp-server path. */
125
+ overridePath?: string;
126
+ /** Override the pi agent home (defaults to ~/.pi/agent). */
127
+ piAgentHome?: string;
128
+ }
129
+
130
+ /** Build a real InstallerEnv wired to the current host. */
131
+ export function createInstallerEnv(opts: CreateEnvOptions = {}): InstallerEnv {
132
+ const home = homedir();
133
+ const agentHome = opts.piAgentHome ?? join(home, ".pi", "agent");
134
+ return {
135
+ platform: process.platform,
136
+ homedir: home,
137
+ probeOsVersion,
138
+ pathExists: existsSync,
139
+ brewPath,
140
+ runBrewCask,
141
+ ...(opts.overridePath ? { overridePath: opts.overridePath } : {}),
142
+ mcpJsonPath: join(agentHome, "mcp.json"),
143
+ settingsJsonPath: join(agentHome, "settings.json"),
144
+ configIO: realConfigIO,
145
+ };
146
+ }
package/src/install.ts ADDED
@@ -0,0 +1,244 @@
1
+ /**
2
+ * iMCP provisioning state machine. One traversal, two modes: write (the CLI
3
+ * `bin`) and check (write-suppressed; backs the `--check` CLI flag, the doctor
4
+ * probe, and the settings-panel status readout). Every side effect and probe
5
+ * is injected so the suite runs on Linux CI without a real macOS host.
6
+ *
7
+ * See change: add-apple-tools-imcp-plugin (Decision 2).
8
+ */
9
+ import {
10
+ discoverServer,
11
+ IMCP_BREW_CASK,
12
+ IMCP_DOWNLOAD_URL,
13
+ IMCP_RELATIVE,
14
+ MIN_MACOS,
15
+ meetsMinimum,
16
+ } from "./detect.js";
17
+ import {
18
+ type ConfigIO,
19
+ type ConfigWriteResult,
20
+ ensureAdapterPackage,
21
+ ensureMcpEntry,
22
+ validateConfigShape,
23
+ } from "./mcp-config.js";
24
+
25
+ /** Closed, nine-member terminal-state enum. All three surfaces render these. */
26
+ export type TerminalState =
27
+ | "UNSUPPORTED_PLATFORM"
28
+ | "OS_VERSION_UNKNOWN"
29
+ | "OS_TOO_OLD"
30
+ | "NO_INSTALL_METHOD"
31
+ | "INSTALL_FAILED"
32
+ | "CONFIG_UNPARSEABLE"
33
+ | "CONFIG_WRITE_FAILED"
34
+ | "READY_PENDING_GRANTS"
35
+ | "READY";
36
+
37
+ export const TERMINAL_STATES: readonly TerminalState[] = [
38
+ "UNSUPPORTED_PLATFORM",
39
+ "OS_VERSION_UNKNOWN",
40
+ "OS_TOO_OLD",
41
+ "NO_INSTALL_METHOD",
42
+ "INSTALL_FAILED",
43
+ "CONFIG_UNPARSEABLE",
44
+ "CONFIG_WRITE_FAILED",
45
+ "READY_PENDING_GRANTS",
46
+ "READY",
47
+ ];
48
+
49
+ export interface BrewResult {
50
+ code: number;
51
+ stderr: string;
52
+ /** True when the invocation exceeded the timeout budget. */
53
+ timedOut?: boolean;
54
+ }
55
+
56
+ /** Every environment interaction, injected for deterministic cross-platform tests. */
57
+ export interface InstallerEnv {
58
+ platform: string;
59
+ homedir: string;
60
+ /** `sw_vers -productVersion`; null on absence / non-zero exit / empty stdout. */
61
+ probeOsVersion: () => string | null;
62
+ /** Existence check for a single path. */
63
+ pathExists: (p: string) => boolean;
64
+ /** Absolute path to `brew`, or null when not resolvable on PATH. */
65
+ brewPath: () => string | null;
66
+ /** Invoke `brew install --cask mattt/tap/iMCP` with an argv array + timeout. */
67
+ runBrewCask: (brew: string) => BrewResult;
68
+ /** Operator override for the imcp-server path (`imcpServerPath` config key). */
69
+ overridePath?: string;
70
+ /** Absolute path to `~/.pi/agent/mcp.json`. */
71
+ mcpJsonPath: string;
72
+ /** Absolute path to `~/.pi/agent/settings.json`. */
73
+ settingsJsonPath: string;
74
+ /** Injected config IO for the two writers. */
75
+ configIO: ConfigIO;
76
+ }
77
+
78
+ export interface InstallResult {
79
+ state: TerminalState;
80
+ exitCode: number;
81
+ message: string;
82
+ /**
83
+ * Resolved imcp-server path. Set ONLY when the binary actually exists — in
84
+ * check mode the traversal predicts what a write run would reach, and a
85
+ * prediction must never be reported as a discovered path.
86
+ */
87
+ resolvedPath?: string;
88
+ /**
89
+ * Whether iMCP.app is on disk right now. False in check mode when the app is
90
+ * absent but installable, which is precisely when `state` is a PREDICTION
91
+ * rather than an observation. Every surface (CLI, doctor, panel) uses this to
92
+ * avoid claiming a host is provisioned when it is not.
93
+ */
94
+ appPresent: boolean;
95
+ }
96
+
97
+ export interface RunOptions {
98
+ /** When true, suppress every mutation (no brew, no config write). */
99
+ check?: boolean;
100
+ }
101
+
102
+ const OK = 0;
103
+ const ERR = 1;
104
+
105
+ function fail(state: TerminalState, message: string): InstallResult {
106
+ return { state, exitCode: ERR, message, appPresent: false };
107
+ }
108
+
109
+ /**
110
+ * Traverse the provisioning graph. Pure over `env`; the only mutations are the
111
+ * brew invocation and the two config writes, both gated on `!check`.
112
+ */
113
+ // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: a provisioning state machine is intentionally branchy; each branch is one terminal state.
114
+ export function runInstaller(env: InstallerEnv, opts: RunOptions = {}): InstallResult {
115
+ const check = opts.check === true;
116
+
117
+ // 1. Platform gate — short-circuit before any subprocess or filesystem work.
118
+ if (env.platform !== "darwin") {
119
+ return {
120
+ state: "UNSUPPORTED_PLATFORM",
121
+ exitCode: OK,
122
+ message: "iMCP is macOS-only; nothing to provision on this platform.",
123
+ appPresent: false,
124
+ };
125
+ }
126
+
127
+ // 2. macOS version gate.
128
+ const version = env.probeOsVersion();
129
+ if (version === null) {
130
+ return fail(
131
+ "OS_VERSION_UNKNOWN",
132
+ "Could not determine the macOS version (sw_vers unavailable or empty). No version was detected.",
133
+ );
134
+ }
135
+ if (!meetsMinimum(version, MIN_MACOS)) {
136
+ return fail(
137
+ "OS_TOO_OLD",
138
+ `macOS ${version} is below the minimum supported ${MIN_MACOS}. Please upgrade.`,
139
+ );
140
+ }
141
+
142
+ // 3. Discover imcp-server (override-as-preference, ordered candidate list).
143
+ let resolved = discoverServer(env.homedir, env.pathExists, env.overridePath);
144
+ // Whether the app is really on disk, captured BEFORE any check-mode
145
+ // prediction overwrites `resolved`.
146
+ const appPresent = resolved !== null;
147
+
148
+ // 4. Install branch when the binary is absent.
149
+ if (!resolved) {
150
+ const brew = env.brewPath();
151
+ if (!brew) {
152
+ return fail(
153
+ "NO_INSTALL_METHOD",
154
+ `iMCP is not installed and Homebrew is unavailable. Install it from ${IMCP_DOWNLOAD_URL}`,
155
+ );
156
+ }
157
+ if (check) {
158
+ // Write-suppressed prediction: brew is present, so the install would
159
+ // proceed. Report the state write-mode would reach; brew never invoked.
160
+ resolved = `/Applications/${IMCP_RELATIVE}`;
161
+ } else {
162
+ const result = env.runBrewCask(brew);
163
+ if (result.timedOut) {
164
+ return fail(
165
+ "INSTALL_FAILED",
166
+ `\`brew install --cask ${IMCP_BREW_CASK}\` timed out after 10 minutes; aborted without writing any config.`,
167
+ );
168
+ }
169
+ if (result.code !== 0) {
170
+ return fail(
171
+ "INSTALL_FAILED",
172
+ `\`brew install --cask ${IMCP_BREW_CASK}\` failed (exit ${result.code}):\n${result.stderr}`,
173
+ );
174
+ }
175
+ // Post-brew re-discovery gate: a successful cask that left no binary at
176
+ // any candidate is a failure, NOT a config write pointing at nothing.
177
+ resolved = discoverServer(env.homedir, env.pathExists, env.overridePath);
178
+ if (!resolved) {
179
+ return fail(
180
+ "INSTALL_FAILED",
181
+ "brew reported success but no imcp-server binary was found at any known location.",
182
+ );
183
+ }
184
+ }
185
+ }
186
+
187
+ // 5. Config writes (suppressed in check mode).
188
+ if (!check) {
189
+ const mcp = ensureMcpEntry(env.configIO, env.mcpJsonPath, resolved);
190
+ if (!mcp.ok) return relayConfigFailure(mcp);
191
+ const pkg = ensureAdapterPackage(env.configIO, env.settingsJsonPath);
192
+ if (!pkg.ok) return relayConfigFailure(pkg);
193
+ } else {
194
+ // Predict a config failure the write would hit (unparseable existing file).
195
+ const predicted = predictConfigWritability(env);
196
+ if (predicted) return predicted;
197
+ }
198
+
199
+ // 6. Terminal success. The installer never claims READY — only a live adapter
200
+ // round-trip (a granted tool call) can distinguish READY from pending.
201
+ //
202
+ // In check mode with the app absent, `state` is a PREDICTION of what a
203
+ // write run would reach. Reporting it as "provisioned", or naming the
204
+ // predicted path as if discovered, would be a lie — so both are withheld.
205
+ if (check && !appPresent) {
206
+ return {
207
+ state: "READY_PENDING_GRANTS",
208
+ exitCode: OK,
209
+ appPresent: false,
210
+ message:
211
+ `iMCP is NOT installed. Homebrew is available, so running \`pi-apple-tools-install\` ` +
212
+ `would install it (cask ${IMCP_BREW_CASK}) and reach READY_PENDING_GRANTS — after which ` +
213
+ "the Apple permissions must be granted manually in the iMCP menu-bar app.",
214
+ };
215
+ }
216
+
217
+ return {
218
+ state: "READY_PENDING_GRANTS",
219
+ exitCode: OK,
220
+ resolvedPath: resolved,
221
+ appPresent: true,
222
+ message:
223
+ "iMCP provisioned. Final step (manual, unautomatable): open the iMCP menu-bar app and grant the Apple service permissions you need. Grants cannot be automated.",
224
+ };
225
+ }
226
+
227
+ function relayConfigFailure(r: Extract<ConfigWriteResult, { ok: false }>): InstallResult {
228
+ return fail(r.state, r.message);
229
+ }
230
+
231
+ /**
232
+ * Check-mode dry predicate. Delegates to the writers' OWN structural validators
233
+ * so check and write agree: a config that would fail a write (invalid JSON,
234
+ * non-object root, malformed `mcpServers` / `mcpServers.iMCP` / `packages`)
235
+ * must never be reported as healthy by `--check`. Write-permission failures
236
+ * (EACCES/ENOSPC) remain unpredictable without attempting a write.
237
+ */
238
+ function predictConfigWritability(env: InstallerEnv): InstallResult | null {
239
+ const mcp = validateConfigShape(env.configIO, env.mcpJsonPath, "mcp");
240
+ if (mcp) return fail(mcp.state, mcp.message);
241
+ const settings = validateConfigShape(env.configIO, env.settingsJsonPath, "settings");
242
+ if (settings) return fail(settings.state, settings.message);
243
+ return null;
244
+ }
@@ -0,0 +1,285 @@
1
+ /**
2
+ * Merge-only, atomic config writers for the two user-owned files the installer
3
+ * touches: `~/.pi/agent/mcp.json` (the `mcpServers.iMCP` entry) and
4
+ * `~/.pi/agent/settings.json` (the `packages[]` adapter entry).
5
+ *
6
+ * Discipline (see change: add-apple-tools-imcp-plugin, Decision 4):
7
+ * - read → deep-merge exactly one key → write. Never clobber siblings.
8
+ * - refuse to write a present-but-unparseable file (surface, don't "fix").
9
+ * - write via temp-file + atomic rename; never leave a truncated config.
10
+ * - never interpolate any probed value into a shell string.
11
+ *
12
+ * All filesystem access is injected (`ConfigIO`) so the suite runs on Linux CI
13
+ * without touching real user config.
14
+ */
15
+ import { sourcesMatch } from "@blackbelt-technology/pi-dashboard-shared/source-matching.js";
16
+
17
+ /** Injected filesystem surface. `readFile` returns null when the file is absent. */
18
+ export interface ConfigIO {
19
+ readFile: (path: string) => string | null;
20
+ /** Atomic write (temp-file + rename). Throws an Error whose `.code` may be EACCES/ENOSPC. */
21
+ writeFileAtomic: (path: string, content: string) => void;
22
+ }
23
+
24
+ /** Outcome of a config write; `state` is set only on a terminal failure. */
25
+ export type ConfigWriteResult =
26
+ | { ok: true }
27
+ | { ok: false; state: "CONFIG_UNPARSEABLE" | "CONFIG_WRITE_FAILED"; message: string };
28
+
29
+ /** The npm source string appended to settings.json packages[] for the adapter. */
30
+ export const ADAPTER_PACKAGE_SOURCE = "npm:pi-mcp-adapter";
31
+
32
+ function parseOrError(
33
+ io: ConfigIO,
34
+ path: string,
35
+ ): { parsed: Record<string, unknown> } | { error: ConfigWriteResult } {
36
+ const raw = io.readFile(path);
37
+ if (raw === null || raw.trim() === "") return { parsed: {} };
38
+ try {
39
+ const val = JSON.parse(raw);
40
+ if (val === null || typeof val !== "object" || Array.isArray(val)) {
41
+ return {
42
+ error: {
43
+ ok: false,
44
+ state: "CONFIG_UNPARSEABLE",
45
+ message: `${path} is not a JSON object`,
46
+ },
47
+ };
48
+ }
49
+ return { parsed: val as Record<string, unknown> };
50
+ } catch (e) {
51
+ return {
52
+ error: {
53
+ ok: false,
54
+ state: "CONFIG_UNPARSEABLE",
55
+ message: `${path} contains invalid JSON: ${(e as Error).message}`,
56
+ },
57
+ };
58
+ }
59
+ }
60
+
61
+ /**
62
+ * Read `mcpServers` as an object. A present-but-wrong-typed value (array,
63
+ * string) is refused rather than coerced to `{}` — coercing would silently
64
+ * drop the user's data on the next write.
65
+ */
66
+ function readServers(
67
+ config: Record<string, unknown>,
68
+ path: string,
69
+ ): { servers: Record<string, unknown> } | { error: ConfigWriteResult } {
70
+ const raw = config.mcpServers;
71
+ if (raw === undefined) return { servers: {} };
72
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
73
+ return {
74
+ error: {
75
+ ok: false,
76
+ state: "CONFIG_UNPARSEABLE",
77
+ message: `${path}: "mcpServers" must be an object`,
78
+ },
79
+ };
80
+ }
81
+ return { servers: raw as Record<string, unknown> };
82
+ }
83
+
84
+ /**
85
+ * Read the existing `mcpServers.iMCP` entry. A present-but-wrong-typed value
86
+ * (scalar, null, array) is REFUSED rather than coerced to `{}` — coercing would
87
+ * destroy the operator's parseable value on the next write.
88
+ */
89
+ function readExistingImcp(
90
+ servers: Record<string, unknown>,
91
+ path: string,
92
+ ): { existing: Record<string, unknown> } | { error: ConfigWriteResult } {
93
+ const raw = servers.iMCP;
94
+ if (raw === undefined) return { existing: {} };
95
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
96
+ return {
97
+ error: {
98
+ ok: false,
99
+ state: "CONFIG_UNPARSEABLE",
100
+ message: `${path}: "mcpServers.iMCP" must be an object`,
101
+ },
102
+ };
103
+ }
104
+ return { existing: raw as Record<string, unknown> };
105
+ }
106
+
107
+ function writeOrError(io: ConfigIO, path: string, obj: unknown): ConfigWriteResult {
108
+ try {
109
+ io.writeFileAtomic(path, `${JSON.stringify(obj, null, 2)}\n`);
110
+ return { ok: true };
111
+ } catch (e) {
112
+ return {
113
+ ok: false,
114
+ state: "CONFIG_WRITE_FAILED",
115
+ message: `failed to write ${path}: ${(e as Error).message}`,
116
+ };
117
+ }
118
+ }
119
+
120
+ /**
121
+ * Ensure `mcpServers.iMCP = { command: <imcpServerPath> }` in mcp.json,
122
+ * preserving every other server and unknown top-level key. imcp-server is a
123
+ * stdio server that takes no args — `command` alone is the full contract
124
+ * (verified against pi-mcp-adapter's documented mcpServers shape).
125
+ */
126
+ export function ensureMcpEntry(
127
+ io: ConfigIO,
128
+ mcpJsonPath: string,
129
+ imcpServerPath: string,
130
+ ): ConfigWriteResult {
131
+ const r = parseOrError(io, mcpJsonPath);
132
+ if ("error" in r) return r.error;
133
+ const config = r.parsed;
134
+ const sr = readServers(config, mcpJsonPath);
135
+ if ("error" in sr) return sr.error;
136
+ const { servers } = sr;
137
+ const er = readExistingImcp(servers, mcpJsonPath);
138
+ if ("error" in er) return er.error;
139
+ const { existing } = er;
140
+ // Merge-only: preserve any operator-added fields on the iMCP entry (e.g. a
141
+ // `disabled` flag), overriding just `command` with the re-discovered path.
142
+ const merged = { ...existing, command: imcpServerPath };
143
+ const next = { ...config, mcpServers: { ...servers, iMCP: merged } };
144
+ return writeOrError(io, mcpJsonPath, next);
145
+ }
146
+
147
+ /**
148
+ * Append the adapter to settings.json `packages[]` if absent. Presence is
149
+ * detected with the cross-kind `sourcesMatch()` (npm ↔ git ↔ raw), so a
150
+ * user who installed pi-mcp-adapter from git receives no duplicate npm entry.
151
+ * Never reorders or removes existing entries.
152
+ */
153
+ export function ensureAdapterPackage(io: ConfigIO, settingsJsonPath: string): ConfigWriteResult {
154
+ const r = parseOrError(io, settingsJsonPath);
155
+ if ("error" in r) return r.error;
156
+ const config = r.parsed;
157
+ if (config.packages !== undefined && !Array.isArray(config.packages)) {
158
+ return {
159
+ ok: false,
160
+ state: "CONFIG_UNPARSEABLE",
161
+ message: `${settingsJsonPath}: "packages" must be an array`,
162
+ };
163
+ }
164
+ const packages = Array.isArray(config.packages) ? (config.packages as unknown[]) : [];
165
+ const already = packages.some(
166
+ (p) => typeof p === "string" && sourcesMatch(p, ADAPTER_PACKAGE_SOURCE),
167
+ );
168
+ if (already) return { ok: true };
169
+ const next = { ...config, packages: [...packages, ADAPTER_PACKAGE_SOURCE] };
170
+ return writeOrError(io, settingsJsonPath, next);
171
+ }
172
+
173
+ /**
174
+ * Read-only structural validation of a config file, using the SAME rules the
175
+ * writers enforce. Check mode calls this so `--check` can never report a
176
+ * healthy state that write mode would fail on (parity: invalid JSON, non-object
177
+ * root, malformed `mcpServers` / `mcpServers.iMCP` / `packages`).
178
+ * Returns null when the file would be writable.
179
+ */
180
+ export function validateConfigShape(
181
+ io: ConfigIO,
182
+ path: string,
183
+ kind: "mcp" | "settings",
184
+ ): Extract<ConfigWriteResult, { ok: false }> | null {
185
+ const r = parseOrError(io, path);
186
+ if ("error" in r) return r.error as Extract<ConfigWriteResult, { ok: false }>;
187
+ if (kind === "mcp") {
188
+ const sr = readServers(r.parsed, path);
189
+ if ("error" in sr) return sr.error as Extract<ConfigWriteResult, { ok: false }>;
190
+ const er = readExistingImcp(sr.servers, path);
191
+ if ("error" in er) return er.error as Extract<ConfigWriteResult, { ok: false }>;
192
+ } else if (r.parsed.packages !== undefined && !Array.isArray(r.parsed.packages)) {
193
+ return {
194
+ ok: false,
195
+ state: "CONFIG_UNPARSEABLE",
196
+ message: `${path}: "packages" must be an array`,
197
+ };
198
+ }
199
+ return null;
200
+ }
201
+
202
+ /** Read the iMCP entry's operator-facing fields from a given mcp.json layer. */
203
+ export function readImcpEntry(
204
+ io: ConfigIO,
205
+ mcpJsonPath: string,
206
+ ): { disabled: boolean; directTools: string[] } {
207
+ const r = parseOrError(io, mcpJsonPath);
208
+ if ("error" in r) return { disabled: false, directTools: [] };
209
+ const servers = r.parsed.mcpServers;
210
+ if (!servers || typeof servers !== "object" || Array.isArray(servers)) {
211
+ return { disabled: false, directTools: [] };
212
+ }
213
+ const entry = (servers as Record<string, unknown>).iMCP;
214
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
215
+ return { disabled: false, directTools: [] };
216
+ }
217
+ const e = entry as Record<string, unknown>;
218
+ return {
219
+ // pi-mcp-adapter's isServerDisabled: only a literal `true` disables.
220
+ disabled: e.disabled === true,
221
+ directTools: Array.isArray(e.directTools)
222
+ ? (e.directTools as unknown[]).filter((t): t is string => typeof t === "string")
223
+ : [],
224
+ };
225
+ }
226
+
227
+ /** Merge a patch into `mcpServers.iMCP`; an `undefined` value removes the key. */
228
+ function patchImcpEntry(
229
+ io: ConfigIO,
230
+ mcpJsonPath: string,
231
+ patch: Record<string, unknown>,
232
+ ): ConfigWriteResult {
233
+ const r = parseOrError(io, mcpJsonPath);
234
+ if ("error" in r) return r.error;
235
+ const config = r.parsed;
236
+ const sr = readServers(config, mcpJsonPath);
237
+ if ("error" in sr) return sr.error;
238
+ const { servers } = sr;
239
+ const er = readExistingImcp(servers, mcpJsonPath);
240
+ if ("error" in er) return er.error;
241
+ const merged: Record<string, unknown> = { ...er.existing };
242
+ for (const [k, v] of Object.entries(patch)) {
243
+ if (v === undefined) delete merged[k];
244
+ else merged[k] = v;
245
+ }
246
+ const next = { ...config, mcpServers: { ...servers, iMCP: merged } };
247
+ return writeOrError(io, mcpJsonPath, next);
248
+ }
249
+
250
+ /**
251
+ * Write the iMCP `disabled` override into a given mcp.json layer. BOTH levels
252
+ * are supported and use the identical merge discipline:
253
+ * - global → `~/.pi/agent/mcp.json` (the layer the installer writes `command`
254
+ * to; the target for the dashboard's global settings panel)
255
+ * - project → `<cwd>/.pi/mcp.json` (the adapter's highest-precedence layer,
256
+ * so a project override folds over the global value without mutating it)
257
+ *
258
+ * Mirrors `writeProjectServerDisabledOverride` in the installed pi-mcp-adapter
259
+ * (`config.ts`): disabling writes `disabled: true`; ENABLING removes the key
260
+ * rather than writing `false`. `isServerDisabled` treats only a literal `true`
261
+ * as disabled (`types.ts:395`). Verified against adapter v2.19.0 (task 7.8).
262
+ */
263
+ export function setServerDisabled(
264
+ io: ConfigIO,
265
+ mcpJsonPath: string,
266
+ disabled: boolean,
267
+ ): ConfigWriteResult {
268
+ return patchImcpEntry(io, mcpJsonPath, { disabled: disabled ? true : undefined });
269
+ }
270
+
271
+ /**
272
+ * Write the adapter's per-server `directTools` filter onto the iMCP entry
273
+ * (`ServerEntry.directTools?: boolean | string[]`, consumed by the adapter's
274
+ * `direct-tools.ts`). An empty selection removes the key rather than writing
275
+ * `[]`, which the adapter would read as "promote nothing".
276
+ */
277
+ export function setDirectTools(
278
+ io: ConfigIO,
279
+ mcpJsonPath: string,
280
+ tools: string[],
281
+ ): ConfigWriteResult {
282
+ return patchImcpEntry(io, mcpJsonPath, {
283
+ directTools: tools.length > 0 ? tools : undefined,
284
+ });
285
+ }