@sandbaseai/cli 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.
@@ -2,10 +2,119 @@
2
2
  import { readFile } from "node:fs/promises";
3
3
  import { homedir } from "node:os";
4
4
  import { join } from "node:path";
5
- const client = process.argv[process.argv.indexOf("--client") + 1];
6
- const store = join(process.env.SANDBASE_HOME || join(homedir(), ".sandbase"), "credentials.json");
7
- let record;
8
- try { record = JSON.parse(await readFile(store, "utf8"))[client]; } catch { process.stderr.write("SandBase credential is unavailable. Run sandbase connect again.\n"); process.exit(1); }
9
- if (!record?.credential || !record?.mcpUrl) { process.stderr.write("SandBase credential is unavailable.\n"); process.exit(1); }
10
- let buffer = Buffer.alloc(0), session;
11
- process.stdin.on("data", async chunk => { buffer = Buffer.concat([buffer, chunk]); for (;;) { const split = buffer.indexOf("\n"); if (split < 0) break; const line = buffer.subarray(0, split).toString().trim(); buffer = buffer.subarray(split + 1); if (!line) continue; let request; try { request = JSON.parse(line); } catch { continue; } try { const headers = { authorization: `Bearer ${record.credential}`, "content-type": "application/json", accept: "application/json, text/event-stream" }; if (session) headers["mcp-session-id"] = session; const response = await fetch(record.mcpUrl, { method: "POST", headers, body: JSON.stringify(request) }); session = response.headers.get("mcp-session-id") || session; const text = await response.text(); for (const part of text.split("\n")) { const payload = part.startsWith("data:") ? part.slice(5).trim() : part.trim(); if (payload.startsWith("{")) process.stdout.write(payload + "\n"); } if (!response.ok && request.id !== undefined) process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: request.id, error: { code: -32000, message: `SandBase MCP request failed (${response.status})` } }) + "\n"); } catch { if (request.id !== undefined) process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: request.id, error: { code: -32000, message: "SandBase MCP is unavailable" } }) + "\n"); } } });
5
+ import { pathToFileURL } from "node:url";
6
+
7
+ // This file is both the installed standalone bridge and the runtime loaded by
8
+ // dist/cli.js. Keep the proxy implementation here so the two launchers cannot
9
+ // drift.
10
+ const allowedClients = new Set(["codex", "claude-code", "cursor", "gemini-cli", "hermes", "openclaw", "opencode", "qwen-code", "windsurf", "cursor-cli", "kimi-cli", "kiro", "kiro-cli", "amp", "crush", "iflow-cli", "warp", "claude-desktop", "cowork", "antigravity", "trae", "qoder", "workbuddy", "pi"]);
11
+
12
+ function bridgeError(message) { return new Error(message); }
13
+ function responseError(id, message) { return JSON.stringify({ jsonrpc: "2.0", id, error: { code: -32000, message } }) + "\n"; }
14
+ function validEndpoint(value) {
15
+ try {
16
+ const url = new URL(value);
17
+ return ["http:", "https:"].includes(url.protocol) && !url.username && !url.password && !url.hash && url.pathname === "/v1/mcp" ? url.href : undefined;
18
+ } catch { return undefined; }
19
+ }
20
+ function parseCredential(raw, client) {
21
+ let all;
22
+ try { all = JSON.parse(raw); } catch { throw bridgeError("SandBase credential store is invalid. Run sandbase connect again."); }
23
+ const record = all && typeof all === "object" && !Array.isArray(all) ? all[client] : undefined;
24
+ const mcpUrl = typeof record?.mcpUrl === "string" ? validEndpoint(record.mcpUrl) : undefined;
25
+ if (record?.client !== client || typeof record?.credential !== "string" || !record.credential || !mcpUrl) throw bridgeError("SandBase credential is unavailable. Run sandbase connect again.");
26
+ return { credential: record.credential, mcpUrl };
27
+ }
28
+ function emitPayload(text, contentType, output) {
29
+ if (!text.trim()) return;
30
+ if (contentType.includes("text/event-stream")) {
31
+ for (const line of text.split(/\r?\n/)) {
32
+ if (!line.startsWith("data:")) continue;
33
+ const payload = line.slice(5).trim();
34
+ if (payload && payload !== "[DONE]") output.write(payload + "\n");
35
+ }
36
+ return;
37
+ }
38
+ try { output.write(JSON.stringify(JSON.parse(text)) + "\n"); }
39
+ catch {
40
+ for (const line of text.split(/\r?\n/)) {
41
+ const payload = line.trim();
42
+ if (!payload) continue;
43
+ try { output.write(JSON.stringify(JSON.parse(payload)) + "\n"); } catch { /* Never forward an untrusted non-JSON body to the client. */ }
44
+ }
45
+ }
46
+ }
47
+
48
+ export async function runMCPBridge(options = {}) {
49
+ const client = options.client;
50
+ const input = options.input || process.stdin;
51
+ const output = options.output || process.stdout;
52
+ const signal = options.signal;
53
+ const env = options.env || process.env;
54
+ const fetchImpl = options.fetchImpl || globalThis.fetch;
55
+ if (!allowedClients.has(client)) throw bridgeError("SandBase bridge client is invalid.");
56
+
57
+ const store = join(env.SANDBASE_HOME || join(homedir(), ".sandbase"), "credentials.json");
58
+ let raw;
59
+ try { raw = await readFile(store, "utf8"); }
60
+ catch { throw bridgeError("SandBase credential is unavailable. Run sandbase connect again."); }
61
+ const record = parseCredential(raw, client);
62
+ let buffer = Buffer.alloc(0);
63
+ let session;
64
+
65
+ const forward = async line => {
66
+ let request;
67
+ try { request = JSON.parse(line); } catch { return; }
68
+ if (!request || typeof request !== "object" || Array.isArray(request)) return;
69
+ try {
70
+ const headers = { authorization: `Bearer ${record.credential}`, "content-type": "application/json", accept: "application/json, text/event-stream" };
71
+ if (session) headers["mcp-session-id"] = session;
72
+ const response = await fetchImpl(record.mcpUrl, { method: "POST", headers, body: JSON.stringify(request), ...(signal ? { signal } : {}) });
73
+ const nextSession = response.headers.get("mcp-session-id");
74
+ if (nextSession) session = nextSession;
75
+ const text = await response.text();
76
+ if (!response.ok) {
77
+ if (request.id !== undefined) output.write(responseError(request.id, `SandBase MCP request failed (${response.status})`));
78
+ return;
79
+ }
80
+ emitPayload(text, response.headers.get("content-type") || "", output);
81
+ } catch {
82
+ if (!signal?.aborted && request.id !== undefined) output.write(responseError(request.id, "SandBase MCP is unavailable"));
83
+ }
84
+ };
85
+
86
+ const stopInput = () => { if (typeof input.destroy === "function") input.destroy(); };
87
+ signal?.addEventListener("abort", stopInput, { once: true });
88
+ try {
89
+ for await (const chunk of input) {
90
+ if (signal?.aborted) break;
91
+ buffer = Buffer.concat([buffer, Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)]);
92
+ for (;;) {
93
+ const split = buffer.indexOf("\n");
94
+ if (split < 0) break;
95
+ const line = buffer.subarray(0, split).toString("utf8").trim();
96
+ buffer = buffer.subarray(split + 1);
97
+ if (line) await forward(line);
98
+ }
99
+ }
100
+ const finalLine = buffer.toString("utf8").trim();
101
+ if (!signal?.aborted && finalLine) await forward(finalLine);
102
+ } catch (error) {
103
+ if (!signal?.aborted) throw error;
104
+ } finally { signal?.removeEventListener("abort", stopInput); }
105
+ }
106
+
107
+ function mainClient(argv) {
108
+ return argv.length === 2 && argv[0] === "--client" && allowedClients.has(argv[1]) ? argv[1] : undefined;
109
+ }
110
+ const isMain = !!process.argv[1] && pathToFileURL(process.argv[1]).href === import.meta.url;
111
+ if (isMain) {
112
+ const client = mainClient(process.argv.slice(2));
113
+ if (!client) { process.stderr.write("Usage: sandbase-mcp-bridge --client <supported-client>\n"); process.exitCode = 2; }
114
+ else {
115
+ const controller = new AbortController();
116
+ for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, () => controller.abort());
117
+ try { await runMCPBridge({ client, signal: controller.signal }); }
118
+ catch (error) { process.stderr.write(`${error instanceof Error ? error.message : "SandBase bridge failed."}\n`); process.exitCode = 1; }
119
+ }
120
+ }
@@ -0,0 +1,40 @@
1
+ export declare const a1Clients: readonly ["opencode", "qwen-code", "windsurf"];
2
+ export type A1Client = typeof a1Clients[number];
3
+ export declare function isA1Client(client: string): client is A1Client;
4
+ export interface A1CommandResult {
5
+ code: number | null;
6
+ stdout: string;
7
+ stderr: string;
8
+ }
9
+ export type A1CommandRunner = (client: Extract<A1Client, "opencode" | "qwen-code">, args: readonly string[]) => Promise<A1CommandResult>;
10
+ export interface A1AdapterResult {
11
+ path: string;
12
+ backup?: string;
13
+ changed: boolean;
14
+ credentialPath?: string;
15
+ credentialBackup?: string;
16
+ credentialChanged?: boolean;
17
+ identityPath?: string;
18
+ identityPrevious?: string;
19
+ identityChanged?: boolean;
20
+ }
21
+ export type A1Inspection = {
22
+ state: "configured" | "missing" | "conflict" | "invalid";
23
+ detail: string;
24
+ };
25
+ export interface A1UnregisterSnapshot {
26
+ client: A1Client;
27
+ path: string;
28
+ config: string;
29
+ identityPath: string;
30
+ identity?: string;
31
+ credentialPath?: string;
32
+ credential?: string;
33
+ }
34
+ export declare const defaultA1Runner: A1CommandRunner;
35
+ export declare function inspectA1(client: A1Client, env?: NodeJS.ProcessEnv, runner?: A1CommandRunner): Promise<A1Inspection>;
36
+ export declare function installA1(client: A1Client, bridge: string, credential: string, mcpUrl: string, env?: NodeJS.ProcessEnv, runner?: A1CommandRunner): Promise<A1AdapterResult>;
37
+ export declare function rollbackA1(result: A1AdapterResult): Promise<void>;
38
+ export declare function snapshotA1Unregister(client: A1Client, env?: NodeJS.ProcessEnv): Promise<A1UnregisterSnapshot | undefined>;
39
+ export declare function restoreA1Unregister(snapshot: A1UnregisterSnapshot): Promise<void>;
40
+ export declare function unregisterA1(client: A1Client, env?: NodeJS.ProcessEnv, runner?: A1CommandRunner): Promise<boolean>;
@@ -0,0 +1,313 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { chmod, mkdir, rm, stat } from "node:fs/promises";
3
+ import { dirname, isAbsolute, join } from "node:path";
4
+ import { applyEdits, modify, parse } from "jsonc-parser";
5
+ import { atomicWrite, backup, readOptional, restore } from "./fs-safe.js";
6
+ import { configPath, sandbaseHome } from "./paths.js";
7
+ export const a1Clients = ["opencode", "qwen-code", "windsurf"];
8
+ export function isA1Client(client) { return a1Clients.includes(client); }
9
+ const executable = { opencode: "opencode2", "qwen-code": "qwen" };
10
+ export const defaultA1Runner = async (client, args) => {
11
+ const result = spawnSync(executable[client], [...args], { encoding: "utf8", timeout: 10_000 });
12
+ return { code: result.status, stdout: result.stdout || "", stderr: result.stderr || "" };
13
+ };
14
+ function parseObject(raw, label) {
15
+ const errors = [];
16
+ const value = parse(raw, errors, { allowTrailingComma: true, disallowComments: false });
17
+ if (errors.length || !value || typeof value !== "object" || Array.isArray(value))
18
+ throw new Error(`${label} configuration is invalid; no changes were made`);
19
+ return value;
20
+ }
21
+ function objectMap(value, label) {
22
+ if (!value || typeof value !== "object" || Array.isArray(value))
23
+ throw new Error(`${label} configuration is invalid; no changes were made`);
24
+ return value;
25
+ }
26
+ function identityPath(client, env = process.env) { return join(sandbaseHome(env), "ownership", `${client}.json`); }
27
+ async function readIdentity(client, env = process.env) {
28
+ const raw = await readOptional(identityPath(client, env));
29
+ if (raw === undefined)
30
+ return undefined;
31
+ try {
32
+ const value = JSON.parse(raw);
33
+ if (value.marker !== "sandbase-cli-a1-v1" || value.client !== client || (value.bridge !== undefined && !isAbsolute(value.bridge)))
34
+ throw new Error();
35
+ return value;
36
+ }
37
+ catch {
38
+ throw new Error(`${client} SandBase ownership identity is invalid; no changes were made`);
39
+ }
40
+ }
41
+ function defaultBridge(env = process.env) { return join(sandbaseHome(env), "bin", "sandbase-mcp-bridge.mjs"); }
42
+ function bridgeCommand(value, client, allowedPaths) {
43
+ if (!value || typeof value !== "object" || Array.isArray(value))
44
+ return false;
45
+ const entry = value;
46
+ const command = Array.isArray(entry.command) ? entry.command : entry.command === "node" && Array.isArray(entry.args) ? [entry.command, ...entry.args] : undefined;
47
+ return !!command && command.length === 4 && command[0] === "node" && typeof command[1] === "string" && isAbsolute(command[1]) && allowedPaths.includes(command[1]) && command[2] === "--client" && command[3] === client;
48
+ }
49
+ function openCodeOwned(value, allowedPaths) { return bridgeCommand(value, "opencode", allowedPaths) && value.type === "local"; }
50
+ function qwenOwned(value, allowedPaths) { return bridgeCommand(value, "qwen-code", allowedPaths); }
51
+ function credentialPath(env = process.env) { return join(sandbaseHome(env), "credentials", "windsurf.token"); }
52
+ function windsurfAuthorization(env = process.env) { return `Bearer \${file:${credentialPath(env)}}`; }
53
+ function controlledEndpoint(value) { try {
54
+ const url = new URL(value);
55
+ return url.protocol === "https:" && !url.username && !url.password && !url.search && !url.hash && url.pathname.replace(/\/$/, "") === "/v1/mcp";
56
+ }
57
+ catch {
58
+ return false;
59
+ } }
60
+ function windsurfOwned(value, allowedEndpoints, env = process.env) {
61
+ if (!value || typeof value !== "object" || Array.isArray(value))
62
+ return false;
63
+ const entry = value;
64
+ if (typeof entry.serverUrl !== "string" || !controlledEndpoint(entry.serverUrl) || !allowedEndpoints.includes(entry.serverUrl.replace(/\/$/, "")))
65
+ return false;
66
+ const headers = entry.headers;
67
+ return !!headers && typeof headers === "object" && !Array.isArray(headers) && headers.Authorization === windsurfAuthorization(env);
68
+ }
69
+ function applyJsonc(raw, path, value) {
70
+ return applyEdits(raw, modify(raw, path, value, { formattingOptions: { insertSpaces: true, tabSize: 2, eol: "\n" } }));
71
+ }
72
+ function initial(raw) { return raw === undefined || !raw.trim() ? "{}\n" : raw; }
73
+ async function restoreSnapshot(path, backupPath) { await restore(path, backupPath); }
74
+ async function inspectConfig(client, env = process.env, expectedBridge, expectedEndpoint) {
75
+ const path = configPath(client, env);
76
+ const raw = await readOptional(path);
77
+ if (raw === undefined)
78
+ return { state: "missing", detail: "configuration is missing" };
79
+ try {
80
+ const identity = await readIdentity(client, env);
81
+ const root = parseObject(raw, client);
82
+ const bridges = [...new Set([defaultBridge(env), identity?.bridge, expectedBridge].filter((value) => !!value))];
83
+ if (client === "opencode") {
84
+ const mcp = root.mcp === undefined ? undefined : objectMap(root.mcp, client);
85
+ const servers = mcp?.servers === undefined ? undefined : objectMap(mcp.servers, client);
86
+ const entry = servers?.sandbase;
87
+ return entry === undefined ? { state: "missing", detail: "SandBase is not registered" } : openCodeOwned(entry, bridges) ? { state: "configured", detail: "global configuration ownership verified" } : { state: "conflict", detail: "the sandbase entry is not SandBase-owned" };
88
+ }
89
+ const servers = root.mcpServers === undefined ? undefined : objectMap(root.mcpServers, client);
90
+ const entry = servers?.sandbase;
91
+ const endpoints = [...new Set(["https://sandbase.ai/v1/mcp", identity?.endpoint?.replace(/\/$/, ""), expectedEndpoint?.replace(/\/$/, "")].filter((value) => !!value))];
92
+ const owned = client === "qwen-code" ? qwenOwned(entry, bridges) : windsurfOwned(entry, endpoints, env);
93
+ if (entry === undefined)
94
+ return { state: "missing", detail: "SandBase is not registered" };
95
+ if (!owned)
96
+ return { state: "conflict", detail: "the sandbase entry is not SandBase-owned" };
97
+ if (client === "windsurf") {
98
+ try {
99
+ const info = await stat(credentialPath(env));
100
+ if ((info.mode & 0o077) !== 0)
101
+ return { state: "invalid", detail: "credential reference permissions are unsafe" };
102
+ }
103
+ catch {
104
+ return { state: "invalid", detail: "credential reference is missing" };
105
+ }
106
+ }
107
+ return { state: "configured", detail: client === "qwen-code" ? "user settings ownership verified; confirm tools in /mcp" : "remote configuration ownership verified" };
108
+ }
109
+ catch (error) {
110
+ return { state: "invalid", detail: error instanceof Error ? error.message : `${client} configuration is invalid` };
111
+ }
112
+ }
113
+ export async function inspectA1(client, env = process.env, runner = defaultA1Runner) {
114
+ const state = await inspectConfig(client, env);
115
+ if (state.state !== "configured" || client !== "opencode")
116
+ return state;
117
+ const listed = await runner("opencode", ["mcp", "list"]);
118
+ return listed.code === 0 && /(^|\W)sandbase(\W|$)/i.test(`${listed.stdout}\n${listed.stderr}`) ? state : { state: "invalid", detail: "opencode2 mcp list did not read back SandBase" };
119
+ }
120
+ async function assertQwenCapability(runner) {
121
+ const add = await runner("qwen-code", ["mcp", "add", "--help"]);
122
+ const remove = await runner("qwen-code", ["mcp", "remove", "--help"]);
123
+ if (add.code !== 0 || remove.code !== 0 || !/--scope/.test(`${add.stdout}${add.stderr}`) || !/--scope/.test(`${remove.stdout}${remove.stderr}`))
124
+ throw new Error("Qwen Code does not expose user-scope MCP add/remove capability; no changes were made");
125
+ }
126
+ export async function installA1(client, bridge, credential, mcpUrl, env = process.env, runner = defaultA1Runner) {
127
+ const path = configPath(client, env);
128
+ const raw = await readOptional(path);
129
+ const text = initial(raw);
130
+ if ((client === "opencode" || client === "qwen-code") && !isAbsolute(bridge))
131
+ throw new Error(`${client}: managed bridge path must be absolute; no changes were made`);
132
+ if (client === "windsurf" && !controlledEndpoint(mcpUrl))
133
+ throw new Error("windsurf: MCP endpoint is not controlled; no changes were made");
134
+ const before = await inspectConfig(client, env, bridge, mcpUrl);
135
+ if (before.state === "conflict" || before.state === "invalid")
136
+ throw new Error(`${client}: ${before.detail}; no changes were made`);
137
+ const ownerPath = identityPath(client, env);
138
+ const identityPrevious = await readOptional(ownerPath);
139
+ const identity = client === "windsurf" ? { marker: "sandbase-cli-a1-v1", client, endpoint: mcpUrl.replace(/\/$/, "") } : { marker: "sandbase-cli-a1-v1", client, bridge };
140
+ const identityNext = JSON.stringify(identity, null, 2) + "\n";
141
+ const identityChanged = identityPrevious !== identityNext;
142
+ const writeIdentity = async () => { if (identityChanged)
143
+ await atomicWrite(ownerPath, identityNext); };
144
+ const identityResult = { identityPath: ownerPath, ...(identityPrevious === undefined ? {} : { identityPrevious }), identityChanged };
145
+ if (client === "qwen-code") {
146
+ await assertQwenCapability(runner);
147
+ if (before.state === "configured") {
148
+ await writeIdentity();
149
+ return { path, changed: false, ...identityResult };
150
+ }
151
+ const backupPath = await backup(path);
152
+ const args = ["mcp", "add", "--scope", "user", "--transport", "stdio", "sandbase", "node", bridge, "--client", "qwen-code"];
153
+ try {
154
+ await writeIdentity();
155
+ const added = await runner("qwen-code", args);
156
+ if (added.code !== 0)
157
+ throw new Error("qwen mcp add failed");
158
+ const after = await inspectConfig(client, env);
159
+ if (after.state !== "configured")
160
+ throw new Error("Qwen user settings readback did not match the managed bridge");
161
+ return backupPath ? { path, backup: backupPath, changed: true, ...identityResult } : { path, changed: true, ...identityResult };
162
+ }
163
+ catch (error) {
164
+ await restoreSnapshot(path, backupPath);
165
+ if (identityChanged)
166
+ identityPrevious === undefined ? await rm(ownerPath, { force: true }) : await atomicWrite(ownerPath, identityPrevious);
167
+ throw error;
168
+ }
169
+ }
170
+ if (client === "opencode") {
171
+ const probe = await runner("opencode", ["mcp", "list"]);
172
+ if (probe.code !== 0)
173
+ throw new Error("OpenCode global MCP capability is unavailable; no changes were made");
174
+ const root = parseObject(text, client);
175
+ const mcp = root.mcp === undefined ? {} : objectMap(root.mcp, client);
176
+ const servers = mcp.servers === undefined ? {} : objectMap(mcp.servers, client);
177
+ const existing = servers.sandbase;
178
+ if (existing !== undefined && !openCodeOwned(existing, [defaultBridge(env), bridge]))
179
+ throw new Error("opencode: the sandbase entry is not SandBase-owned; no changes were made");
180
+ const desired = { type: "local", command: ["node", bridge, "--client", "opencode"], enabled: true };
181
+ const next = applyJsonc(text, ["mcp", "servers", "sandbase"], desired);
182
+ if (next === raw) {
183
+ await writeIdentity();
184
+ return { path, changed: false, ...identityResult };
185
+ }
186
+ const backupPath = await backup(path);
187
+ try {
188
+ await writeIdentity();
189
+ await atomicWrite(path, next);
190
+ const after = await inspectA1(client, env, runner);
191
+ if (after.state !== "configured")
192
+ throw new Error(after.detail);
193
+ return backupPath ? { path, backup: backupPath, changed: true, ...identityResult } : { path, changed: true, ...identityResult };
194
+ }
195
+ catch (error) {
196
+ await restoreSnapshot(path, backupPath);
197
+ if (identityChanged)
198
+ identityPrevious === undefined ? await rm(ownerPath, { force: true }) : await atomicWrite(ownerPath, identityPrevious);
199
+ throw error;
200
+ }
201
+ }
202
+ const root = parseObject(text, client);
203
+ const servers = root.mcpServers === undefined ? {} : objectMap(root.mcpServers, client);
204
+ const existing = servers.sandbase;
205
+ if (existing !== undefined && !windsurfOwned(existing, ["https://sandbase.ai/v1/mcp", mcpUrl.replace(/\/$/, "")], env))
206
+ throw new Error("windsurf: the sandbase entry is not SandBase-owned; no changes were made");
207
+ const desired = { serverUrl: mcpUrl, headers: { Authorization: windsurfAuthorization(env) } };
208
+ const next = applyJsonc(text, ["mcpServers", "sandbase"], desired);
209
+ const secretPath = credentialPath(env);
210
+ const currentSecret = await readOptional(secretPath);
211
+ const configBackup = next === raw ? undefined : await backup(path);
212
+ const secretBackup = currentSecret === credential ? undefined : await backup(secretPath);
213
+ try {
214
+ await writeIdentity();
215
+ if (currentSecret !== credential) {
216
+ await mkdir(dirname(secretPath), { recursive: true, mode: 0o700 });
217
+ await atomicWrite(secretPath, credential, 0o600);
218
+ await chmod(secretPath, 0o600);
219
+ }
220
+ if (next !== raw)
221
+ await atomicWrite(path, next);
222
+ const after = await inspectConfig(client, env);
223
+ if (after.state !== "configured")
224
+ throw new Error(after.detail);
225
+ return { path, ...(configBackup ? { backup: configBackup } : {}), changed: next !== raw, credentialPath: secretPath, ...(secretBackup ? { credentialBackup: secretBackup } : {}), credentialChanged: currentSecret !== credential, ...identityResult };
226
+ }
227
+ catch (error) {
228
+ if (next !== raw)
229
+ await restoreSnapshot(path, configBackup);
230
+ if (currentSecret !== credential)
231
+ await restoreSnapshot(secretPath, secretBackup);
232
+ if (identityChanged)
233
+ identityPrevious === undefined ? await rm(ownerPath, { force: true }) : await atomicWrite(ownerPath, identityPrevious);
234
+ throw error;
235
+ }
236
+ }
237
+ export async function rollbackA1(result) {
238
+ if (result.changed)
239
+ await restoreSnapshot(result.path, result.backup);
240
+ if (result.credentialPath && result.credentialChanged)
241
+ await restoreSnapshot(result.credentialPath, result.credentialBackup);
242
+ if (result.identityPath && result.identityChanged)
243
+ result.identityPrevious === undefined ? await rm(result.identityPath, { force: true }) : await atomicWrite(result.identityPath, result.identityPrevious);
244
+ }
245
+ export async function snapshotA1Unregister(client, env = process.env) {
246
+ const inspected = await inspectConfig(client, env);
247
+ if (inspected.state === "missing")
248
+ return undefined;
249
+ if (inspected.state !== "configured")
250
+ throw new Error(`${client}: ${inspected.detail}; no changes were made`);
251
+ const path = configPath(client, env);
252
+ const config = (await readOptional(path));
253
+ const ownerPath = identityPath(client, env);
254
+ const identity = await readOptional(ownerPath);
255
+ const tokenPath = client === "windsurf" ? credentialPath(env) : undefined;
256
+ const credential = tokenPath ? await readOptional(tokenPath) : undefined;
257
+ return { client, path, config, identityPath: ownerPath, ...(identity === undefined ? {} : { identity }), ...(tokenPath ? { credentialPath: tokenPath } : {}), ...(credential === undefined ? {} : { credential }) };
258
+ }
259
+ async function restoreContent(path, value) { if (value === undefined)
260
+ await rm(path, { force: true });
261
+ else
262
+ await atomicWrite(path, value, 0o600); }
263
+ export async function restoreA1Unregister(snapshot) {
264
+ await restoreContent(snapshot.path, snapshot.config);
265
+ await restoreContent(snapshot.identityPath, snapshot.identity);
266
+ if (snapshot.credentialPath)
267
+ await restoreContent(snapshot.credentialPath, snapshot.credential);
268
+ }
269
+ export async function unregisterA1(client, env = process.env, runner = defaultA1Runner) {
270
+ const snapshot = await snapshotA1Unregister(client, env);
271
+ if (!snapshot)
272
+ return false;
273
+ const path = snapshot.path;
274
+ const raw = snapshot.config;
275
+ if (client === "qwen-code") {
276
+ await assertQwenCapability(runner);
277
+ try {
278
+ const removed = await runner("qwen-code", ["mcp", "remove", "sandbase", "--scope", "user"]);
279
+ if (removed.code !== 0)
280
+ throw new Error("qwen mcp remove failed");
281
+ await rm(snapshot.identityPath, { force: true });
282
+ const after = await inspectConfig(client, env);
283
+ if (after.state !== "missing")
284
+ throw new Error("Qwen user settings still contains SandBase");
285
+ return true;
286
+ }
287
+ catch (error) {
288
+ await restoreA1Unregister(snapshot);
289
+ throw error;
290
+ }
291
+ }
292
+ const jsonPath = client === "opencode" ? ["mcp", "servers", "sandbase"] : ["mcpServers", "sandbase"];
293
+ const next = applyJsonc(raw, jsonPath, undefined);
294
+ try {
295
+ await atomicWrite(path, next);
296
+ if (snapshot.credentialPath)
297
+ await rm(snapshot.credentialPath, { force: true });
298
+ await rm(snapshot.identityPath, { force: true });
299
+ const after = await inspectConfig(client, env);
300
+ if (after.state !== "missing")
301
+ throw new Error(`${client} removal readback failed`);
302
+ if (client === "opencode") {
303
+ const listed = await runner("opencode", ["mcp", "list"]);
304
+ if (listed.code !== 0 || /(^|\W)sandbase(\W|$)/i.test(`${listed.stdout}\n${listed.stderr}`))
305
+ throw new Error("opencode2 mcp list still reports SandBase");
306
+ }
307
+ return true;
308
+ }
309
+ catch (error) {
310
+ await restoreA1Unregister(snapshot);
311
+ throw error;
312
+ }
313
+ }
@@ -16,6 +16,7 @@ export declare function detectClient(client: Client): {
16
16
  detail: string;
17
17
  };
18
18
  export declare function installBridge(home?: string): Promise<BridgeResult>;
19
+ export declare function inspectBridge(home?: string): Promise<"ready" | "missing" | "invalid">;
19
20
  export declare function rollbackBridge(result: BridgeResult): Promise<void>;
20
21
  export declare function configure(client: Client, bridge: string, env?: NodeJS.ProcessEnv, io?: AdapterIO): Promise<AdapterResult>;
21
22
  export declare function rollback(result: AdapterResult): Promise<void>;
@@ -10,10 +10,66 @@ import { clientProfiles } from "../clients.js";
10
10
  import { configPath, sandbaseHome } from "../paths.js";
11
11
  const defaultIO = { backup, write: atomicWrite, restore };
12
12
  const ownershipEnvironment = "SANDBASE_CLI_MANAGED";
13
- export function detectClient(client) { const profile = clientProfiles[client]; const path = configPath(client); if (!profile.executable)
14
- return profile.mode === "auto" && existsSync(path) ? { installed: true, detail: "existing configuration" } : { installed: false, detail: "not detected" }; const result = spawnSync(profile.executable, ["--version"], { encoding: "utf8", timeout: 5000 }); const detail = (result.stdout || result.stderr || "").trim().split("\n")[0] || "not found"; if (result.status === 0)
15
- return { installed: true, detail }; if (client === "codex" && existsSync(path))
16
- return { installed: true, detail: "Codex CLI probe failed; existing Codex configuration detected" }; return { installed: false, detail }; }
13
+ async function bridgeSource() { let failure; for (const relative of ["../../assets/mcp-bridge.mjs", "../../../assets/mcp-bridge.mjs"]) {
14
+ try {
15
+ return await readFile(fileURLToPath(new URL(relative, import.meta.url)), "utf8");
16
+ }
17
+ catch (error) {
18
+ failure = error;
19
+ }
20
+ } throw failure; }
21
+ export function detectClient(client) {
22
+ const profile = clientProfiles[client];
23
+ const path = configPath(client);
24
+ if (client === "opencode") {
25
+ const result = spawnSync("opencode2", ["mcp", "list"], { encoding: "utf8", timeout: 5000 });
26
+ return result.status === 0 ? { installed: true, detail: "opencode2 global MCP capability detected" } : { installed: false, detail: "opencode2 mcp list is unavailable" };
27
+ }
28
+ if (client === "qwen-code") {
29
+ const add = spawnSync("qwen", ["mcp", "add", "--help"], { encoding: "utf8", timeout: 5000 });
30
+ const remove = spawnSync("qwen", ["mcp", "remove", "--help"], { encoding: "utf8", timeout: 5000 });
31
+ const help = `${add.stdout || add.stderr || ""}${remove.stdout || remove.stderr || ""}`;
32
+ return add.status === 0 && remove.status === 0 && /--scope/.test(help) ? { installed: true, detail: "qwen user-scope MCP add/remove capability detected" } : { installed: false, detail: "qwen user-scope MCP capability is unavailable" };
33
+ }
34
+ if (client === "windsurf") {
35
+ const result = spawnSync("windsurf", ["--version"], { encoding: "utf8", timeout: 5000 });
36
+ const app = process.platform === "darwin" && (existsSync("/Applications/Windsurf.app") || existsSync(join(process.env.HOME || "", "Applications", "Windsurf.app")));
37
+ return result.status === 0 || app || existsSync(path) ? { installed: true, detail: result.status === 0 ? ((result.stdout || result.stderr || "").trim().split("\n")[0] || "Windsurf detected") : app ? "Windsurf application detected" : "existing Windsurf configuration detected" } : { installed: false, detail: "Windsurf is not detected" };
38
+ }
39
+ if (client === "warp") {
40
+ const result = spawnSync("warp", ["--version"], { encoding: "utf8", timeout: 5000 });
41
+ const app = process.platform === "darwin" && (existsSync("/Applications/Warp.app") || existsSync(join(process.env.HOME || "", "Applications", "Warp.app")));
42
+ return result.status === 0 || app || existsSync(path) ? { installed: true, detail: result.status === 0 ? ((result.stdout || result.stderr || "").trim().split("\n")[0] || "Warp detected") : app ? "Warp application detected" : "existing Warp user configuration detected" } : { installed: false, detail: "Warp is not detected" };
43
+ }
44
+ if (client === "kiro") {
45
+ const home = process.env.HOME || "", app = process.platform === "darwin" && (existsSync("/Applications/Kiro.app") || existsSync(join(home, "Applications", "Kiro.app")));
46
+ return app || existsSync(path) ? { installed: true, detail: app ? "Kiro IDE application detected" : "existing Kiro IDE user configuration detected" } : { installed: false, detail: "Kiro IDE is not detected" };
47
+ }
48
+ if (["gemini-cli", "cursor-cli", "kimi-cli", "kiro-cli"].includes(client)) {
49
+ const exe = client === "gemini-cli" ? "gemini" : client === "cursor-cli" ? "cursor-agent" : client === "kimi-cli" ? "kimi" : "kiro-cli";
50
+ const probes = client === "gemini-cli" ? [["--version"], ["mcp", "add", "--help"], ["mcp", "list", "--help"], ["mcp", "remove", "--help"]] : client === "cursor-cli" ? [["--version"], ["mcp", "list", "--help"], ["mcp", "list-tools", "--help"]] : client === "kimi-cli" ? [["--version"], ["mcp", "add", "--help"], ["mcp", "list", "--help"], ["mcp", "remove", "--help"], ["mcp", "test", "--help"]] : [["--version"], ["mcp", "add", "--help"], ["mcp", "list", "--help"], ["mcp", "status", "--help"], ["mcp", "remove", "--help"]];
51
+ const results = probes.map(args => spawnSync(exe, args, { encoding: "utf8", timeout: 5000 }));
52
+ const scope = client !== "gemini-cli" || [results[1], results[3]].every(result => /--scope/.test(`${result?.stdout || ""}${result?.stderr || ""}`));
53
+ return results.every(result => result.status === 0) && scope ? { installed: true, detail: `${exe} persistent MCP capability detected` } : { installed: false, detail: `${exe} persistent MCP capability is unavailable` };
54
+ }
55
+ if (["amp", "crush", "iflow-cli"].includes(client)) {
56
+ const exe = client === "iflow-cli" ? "iflow" : client;
57
+ const probes = client === "amp" ? [["--version"], ["mcp", "add", "--help"], ["mcp", "doctor", "--help"]] : client === "crush" ? [["--version"]] : [["--version"], ["mcp", "add-json", "--help"], ["mcp", "get", "--help"], ["mcp", "list", "--help"], ["mcp", "remove", "--help"]];
58
+ const results = probes.map(args => spawnSync(exe, args, { encoding: "utf8", timeout: 5000 }));
59
+ const scope = client !== "iflow-cli" || /--scope/.test(`${results[1]?.stdout || ""}${results[1]?.stderr || ""}`);
60
+ const runtime = client !== "iflow-cli" || Number(process.versions.node.split(".")[0]) >= 22;
61
+ return results.every(result => result.status === 0) && scope && runtime ? { installed: true, detail: client === "iflow-cli" ? "legacy iflow user-scope MCP capability detected; vendor service ended 2026-04-17" : `${exe} persistent MCP capability detected` } : { installed: false, detail: client === "iflow-cli" ? "legacy iflow requires Node.js 22+ and add-json/get/list/remove capability; vendor service ended 2026-04-17" : `${exe} persistent MCP capability is unavailable` };
62
+ }
63
+ if (!profile.executable)
64
+ return profile.mode === "auto" && existsSync(path) ? { installed: true, detail: "existing configuration" } : { installed: false, detail: "not detected" };
65
+ const result = spawnSync(profile.executable, ["--version"], { encoding: "utf8", timeout: 5000 });
66
+ const detail = (result.stdout || result.stderr || "").trim().split("\n")[0] || "not found";
67
+ if (result.status === 0)
68
+ return { installed: true, detail };
69
+ if (client === "codex" && existsSync(path))
70
+ return { installed: true, detail: "Codex CLI probe failed; existing Codex configuration detected" };
71
+ return { installed: false, detail };
72
+ }
17
73
  const start = "# >>> sandbase managed >>>", end = "# <<< sandbase managed <<<";
18
74
  function block(client, bridge) {
19
75
  if (client === "codex")
@@ -61,7 +117,7 @@ function validateText(client, text) { if (!text.trim())
61
117
  if (!value || typeof value !== "object" || Array.isArray(value))
62
118
  throw new Error("YAML root must be a mapping");
63
119
  } }
64
- export async function installBridge(home = sandbaseHome()) { const dir = join(home, "bin"); await mkdir(dir, { recursive: true, mode: 0o700 }); const target = join(dir, "sandbase-mcp-bridge.mjs"); const source = fileURLToPath(new URL("../../assets/mcp-bridge.mjs", import.meta.url)); const next = await readFile(source, "utf8"); const current = await readOptional(target); if (current === next)
120
+ export async function installBridge(home = sandbaseHome()) { const dir = join(home, "bin"); await mkdir(dir, { recursive: true, mode: 0o700 }); const target = join(dir, "sandbase-mcp-bridge.mjs"); const next = await bridgeSource(); const current = await readOptional(target); if (current === next)
65
121
  return { path: target, changed: false }; const backupPath = await backup(target); try {
66
122
  await atomicWrite(target, next, 0o600);
67
123
  }
@@ -69,9 +125,12 @@ catch (e) {
69
125
  await restore(target, backupPath);
70
126
  throw e;
71
127
  } return backupPath ? { path: target, backup: backupPath, changed: true } : { path: target, changed: true }; }
128
+ export async function inspectBridge(home = sandbaseHome()) { const target = join(home, "bin", "sandbase-mcp-bridge.mjs"); const current = await readOptional(target); if (current === undefined)
129
+ return "missing"; return current === await bridgeSource() ? "ready" : "invalid"; }
72
130
  export async function rollbackBridge(result) { await rollback(result); }
73
131
  export async function configure(client, bridge, env = process.env, io = defaultIO) { const profile = clientProfiles[client]; if (profile.mode !== "auto" || !profile.adapter)
74
- return { path: configPath(client, env), changed: false }; const path = configPath(client, env); const raw = await readOptional(path); let next; try {
132
+ return { path: configPath(client, env), changed: false }; if (profile.adapter === "a1" || profile.adapter === "b" || profile.adapter === "c")
133
+ throw new Error(`${client} requires its isolated ${profile.adapter.toUpperCase()} adapter`); const path = configPath(client, env); const raw = await readOptional(path); let next; try {
75
134
  const text = raw || "";
76
135
  validateText(client, text);
77
136
  if (profile.adapter === "codex" && /\[mcp_servers\.sandbase\]/.test(text)) {
@@ -97,7 +156,8 @@ catch (e) {
97
156
  export async function rollback(result) { if (result.changed)
98
157
  await restore(result.path, result.backup); }
99
158
  export async function unregister(client, env = process.env) { const profile = clientProfiles[client]; if (profile.mode !== "auto" || !profile.adapter)
100
- return false; const path = configPath(client, env); const raw = await readOptional(path); if (!raw)
159
+ return false; if (profile.adapter === "a1" || profile.adapter === "b" || profile.adapter === "c")
160
+ throw new Error(`${client} requires its isolated ${profile.adapter.toUpperCase()} adapter`); const path = configPath(client, env); const raw = await readOptional(path); if (!raw)
101
161
  return false; let next; try {
102
162
  validateText(client, raw);
103
163
  if (profile.adapter !== "json" && !raw.includes(start))
@@ -120,7 +180,7 @@ catch (e) {
120
180
  await restore(path, backupPath);
121
181
  throw e;
122
182
  } return true; }
123
- export async function isConfigured(client, env = process.env) { const profile = clientProfiles[client]; if (profile.mode !== "auto" || !profile.adapter)
183
+ export async function isConfigured(client, env = process.env) { const profile = clientProfiles[client]; if (profile.mode !== "auto" || !profile.adapter || profile.adapter === "a1" || profile.adapter === "b" || profile.adapter === "c")
124
184
  return false; const raw = await readOptional(configPath(client, env)); if (!raw)
125
185
  return false; if (profile.adapter === "json") {
126
186
  try {