@sandbaseai/cli 0.1.6 → 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,35 @@
1
+ export declare const bClients: readonly ["gemini-cli", "cursor-cli", "kimi-cli", "kiro-cli"];
2
+ export type BClient = typeof bClients[number];
3
+ export declare function isBClient(client: string): client is BClient;
4
+ export interface BCommandResult {
5
+ code: number | null;
6
+ stdout: string;
7
+ stderr: string;
8
+ }
9
+ export type BCommandRunner = (client: BClient, args: readonly string[]) => Promise<BCommandResult>;
10
+ export interface BAdapterResult {
11
+ path: string;
12
+ backup?: string;
13
+ changed: boolean;
14
+ identityPath: string;
15
+ identityPrevious?: string;
16
+ identityChanged: boolean;
17
+ }
18
+ export interface BUnregisterSnapshot {
19
+ client: BClient;
20
+ path: string;
21
+ config: string;
22
+ identityPath: string;
23
+ identity?: string;
24
+ }
25
+ export type BInspection = {
26
+ state: "configured" | "missing" | "conflict" | "invalid" | "confirmation_required";
27
+ detail: string;
28
+ };
29
+ export declare const defaultBRunner: BCommandRunner;
30
+ export declare function inspectB(client: BClient, env?: NodeJS.ProcessEnv, runner?: BCommandRunner): Promise<BInspection>;
31
+ export declare function installB(client: BClient, bridge: string, env?: NodeJS.ProcessEnv, runner?: BCommandRunner): Promise<BAdapterResult>;
32
+ export declare function rollbackB(result: BAdapterResult): Promise<void>;
33
+ export declare function snapshotBUnregister(client: BClient, env?: NodeJS.ProcessEnv): Promise<BUnregisterSnapshot | undefined>;
34
+ export declare function restoreBUnregister(snapshot: BUnregisterSnapshot): Promise<void>;
35
+ export declare function unregisterB(client: BClient, env?: NodeJS.ProcessEnv, runner?: BCommandRunner): Promise<boolean>;
@@ -0,0 +1,167 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { rm } from "node:fs/promises";
3
+ import { 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 bClients = ["gemini-cli", "cursor-cli", "kimi-cli", "kiro-cli"];
8
+ export function isBClient(client) { return bClients.includes(client); }
9
+ const executables = { "gemini-cli": "gemini", "cursor-cli": "cursor-agent", "kimi-cli": "kimi", "kiro-cli": "kiro-cli" };
10
+ export const defaultBRunner = async (client, args) => { const result = spawnSync(executables[client], [...args], { encoding: "utf8", timeout: 10_000 }); return { code: result.status, stdout: result.stdout || "", stderr: result.stderr || "" }; };
11
+ function ownerPath(client, env = process.env) { return join(sandbaseHome(env), "ownership", `${client}.json`); }
12
+ function defaultBridge(env = process.env) { return join(sandbaseHome(env), "bin", "sandbase-mcp-bridge.mjs"); }
13
+ async function identity(client, env = process.env) { const raw = await readOptional(ownerPath(client, env)); if (raw === undefined)
14
+ return undefined; try {
15
+ const value = JSON.parse(raw);
16
+ if (value.marker !== "sandbase-cli-b-v1" || value.client !== client || !isAbsolute(value.bridge))
17
+ throw new Error();
18
+ return value;
19
+ }
20
+ catch {
21
+ throw new Error(`${client} ownership identity is invalid; no changes were made`);
22
+ } }
23
+ function parseObject(raw, client) { const errors = []; const value = parse(raw, errors, { allowTrailingComma: true, disallowComments: false }); if (errors.length || !value || typeof value !== "object" || Array.isArray(value))
24
+ throw new Error(`${client} configuration is invalid; no changes were made`); return value; }
25
+ function map(value, client) { if (!value || typeof value !== "object" || Array.isArray(value))
26
+ throw new Error(`${client} configuration is invalid; no changes were made`); return value; }
27
+ function commandString(bridge) { return `node ${JSON.stringify(bridge)} --client kiro-cli`; }
28
+ function owned(value, client, allowed) {
29
+ if (!value || typeof value !== "object" || Array.isArray(value))
30
+ return false;
31
+ const entry = value;
32
+ if (client === "kiro-cli" && typeof entry.command === "string" && entry.args === undefined)
33
+ return allowed.some(path => entry.command === commandString(path));
34
+ return entry.command === "node" && Array.isArray(entry.args) && entry.args.length === 3 && typeof entry.args[0] === "string" && isAbsolute(entry.args[0]) && allowed.includes(entry.args[0]) && entry.args[1] === "--client" && entry.args[2] === client;
35
+ }
36
+ function update(raw, value) { return applyEdits(raw, modify(raw, ["mcpServers", "sandbase"], value, { formattingOptions: { insertSpaces: true, tabSize: 2, eol: "\n" } })); }
37
+ function projectOverlay(client, env = process.env) { const root = env.PWD || process.cwd(); if (client === "cursor-cli")
38
+ return join(root, ".cursor", "mcp.json"); if (client === "kiro-cli")
39
+ return join(root, ".kiro", "settings", "mcp.json"); return undefined; }
40
+ async function overlayConflict(client, env = process.env) { const path = projectOverlay(client, env); if (!path || path === configPath(client, env))
41
+ return false; const raw = await readOptional(path); if (raw === undefined)
42
+ return false; const root = parseObject(raw, client); const servers = root.mcpServers === undefined ? undefined : map(root.mcpServers, client); return servers?.sandbase !== undefined; }
43
+ async function inspectConfig(client, env = process.env, expected) {
44
+ try {
45
+ if (await overlayConflict(client, env))
46
+ return { state: "confirmation_required", detail: "a higher-priority workspace SandBase entry was left untouched" };
47
+ const raw = await readOptional(configPath(client, env));
48
+ if (raw === undefined)
49
+ return { state: "missing", detail: "configuration is missing" };
50
+ const root = parseObject(raw, client);
51
+ if (client === "gemini-cli") {
52
+ const mcp = root.mcp;
53
+ const allowed = Array.isArray(mcp?.allowed) ? mcp.allowed : undefined;
54
+ const excluded = Array.isArray(mcp?.excluded) ? mcp.excluded : undefined;
55
+ if ((allowed && !allowed.includes("sandbase")) || excluded?.includes("sandbase"))
56
+ return { state: "confirmation_required", detail: "Gemini MCP policy does not allow SandBase" };
57
+ }
58
+ const servers = root.mcpServers === undefined ? undefined : map(root.mcpServers, client);
59
+ const entry = servers?.sandbase;
60
+ if (entry === undefined)
61
+ return { state: "missing", detail: "SandBase is not registered" };
62
+ const id = await identity(client, env);
63
+ const allowed = [...new Set([defaultBridge(env), id?.bridge, expected].filter((v) => !!v))];
64
+ return owned(entry, client, allowed) ? { state: "configured", detail: "managed bridge ownership verified" } : { state: "conflict", detail: "the sandbase entry is not SandBase-owned" };
65
+ }
66
+ catch (error) {
67
+ return { state: "invalid", detail: error instanceof Error ? error.message : `${client} configuration is invalid` };
68
+ }
69
+ }
70
+ async function capability(client, runner) {
71
+ const probes = {
72
+ "gemini-cli": [["--version"], ["mcp", "add", "--help"], ["mcp", "list", "--help"], ["mcp", "remove", "--help"]],
73
+ "cursor-cli": [["--version"], ["mcp", "list", "--help"], ["mcp", "list-tools", "--help"]],
74
+ "kimi-cli": [["--version"], ["mcp", "add", "--help"], ["mcp", "list", "--help"], ["mcp", "remove", "--help"], ["mcp", "test", "--help"]],
75
+ "kiro-cli": [["--version"], ["mcp", "add", "--help"], ["mcp", "list", "--help"], ["mcp", "status", "--help"], ["mcp", "remove", "--help"]],
76
+ };
77
+ const results = await Promise.all(probes[client].map(args => runner(client, args)));
78
+ if (results.some(result => result.code !== 0))
79
+ throw new Error(`${client} persistent MCP capability is unavailable; no changes were made`);
80
+ if (client === "gemini-cli" && ![results[1], results[3]].every(result => /--scope/.test(`${result?.stdout}${result?.stderr}`)))
81
+ throw new Error("Gemini user-scope MCP capability is unavailable; no changes were made");
82
+ }
83
+ async function readback(client, runner) {
84
+ if (client === "gemini-cli") {
85
+ const list = await runner(client, ["mcp", "list"]);
86
+ return list.code === 0 && /(^|\W)sandbase(\W|$)/i.test(`${list.stdout}${list.stderr}`);
87
+ }
88
+ if (client === "cursor-cli") {
89
+ const list = await runner(client, ["mcp", "list"]), tools = await runner(client, ["mcp", "list-tools", "sandbase"]);
90
+ return list.code === 0 && tools.code === 0 && /(^|\W)sandbase(\W|$)/i.test(`${list.stdout}${list.stderr}`);
91
+ }
92
+ if (client === "kimi-cli") {
93
+ const list = await runner(client, ["mcp", "list"]), test = await runner(client, ["mcp", "test", "sandbase"]);
94
+ return list.code === 0 && test.code === 0 && /(^|\W)sandbase(\W|$)/i.test(`${list.stdout}${list.stderr}`);
95
+ }
96
+ const list = await runner(client, ["mcp", "list", "global"]), status = await runner(client, ["mcp", "status", "--name", "sandbase"]);
97
+ return list.code === 0 && status.code === 0 && /(^|\W)sandbase(\W|$)/i.test(`${list.stdout}${list.stderr}`);
98
+ }
99
+ export async function inspectB(client, env = process.env, runner = defaultBRunner) { const state = await inspectConfig(client, env); if (state.state !== "configured")
100
+ return state; return await readback(client, runner) ? state : { state: "invalid", detail: `${client} CLI readback failed` }; }
101
+ export async function installB(client, bridge, env = process.env, runner = defaultBRunner) {
102
+ if (!isAbsolute(bridge))
103
+ throw new Error(`${client} managed bridge path must be absolute; no changes were made`);
104
+ await capability(client, runner);
105
+ const before = await inspectConfig(client, env, bridge);
106
+ if (before.state === "conflict" || before.state === "invalid" || before.state === "confirmation_required")
107
+ throw new Error(`${client}: ${before.detail}; no changes were made`);
108
+ const path = configPath(client, env), raw = await readOptional(path), text = raw === undefined || !raw.trim() ? "{}\n" : raw, backupPath = before.state === "configured" ? undefined : await backup(path);
109
+ const idPath = ownerPath(client, env), idPrevious = await readOptional(idPath), idNext = JSON.stringify({ marker: "sandbase-cli-b-v1", client, bridge }, null, 2) + "\n", identityChanged = idPrevious !== idNext;
110
+ const result = { path, ...(backupPath ? { backup: backupPath } : {}), changed: before.state !== "configured", identityPath: idPath, ...(idPrevious === undefined ? {} : { identityPrevious: idPrevious }), identityChanged };
111
+ try {
112
+ if (identityChanged)
113
+ await atomicWrite(idPath, idNext);
114
+ if (before.state !== "configured") {
115
+ if (client === "cursor-cli")
116
+ await atomicWrite(path, update(text, { command: "node", args: [bridge, "--client", client] }));
117
+ else {
118
+ const args = client === "gemini-cli" ? ["mcp", "add", "--scope", "user", "--transport", "stdio", "sandbase", "node", bridge, "--client", client] : client === "kimi-cli" ? ["mcp", "add", "--transport", "stdio", "sandbase", "--", "node", bridge, "--client", client] : ["mcp", "add", "--name", "sandbase", "--scope", "global", "--command", commandString(bridge)];
119
+ const added = await runner(client, args);
120
+ if (added.code !== 0)
121
+ throw new Error(`${client} persistent MCP add failed`);
122
+ }
123
+ }
124
+ const configured = await inspectConfig(client, env);
125
+ if (configured.state !== "configured" || !(await readback(client, runner)))
126
+ throw new Error(`${client} MCP readback failed`);
127
+ return result;
128
+ }
129
+ catch (error) {
130
+ if (before.state !== "configured")
131
+ await restore(path, backupPath);
132
+ if (identityChanged)
133
+ idPrevious === undefined ? await rm(idPath, { force: true }) : await atomicWrite(idPath, idPrevious);
134
+ throw error;
135
+ }
136
+ }
137
+ export async function rollbackB(result) { if (result.changed)
138
+ await restore(result.path, result.backup); if (result.identityChanged)
139
+ result.identityPrevious === undefined ? await rm(result.identityPath, { force: true }) : await atomicWrite(result.identityPath, result.identityPrevious); }
140
+ export async function snapshotBUnregister(client, env = process.env) { const state = await inspectConfig(client, env); if (state.state === "missing")
141
+ return undefined; if (state.state !== "configured")
142
+ throw new Error(`${client}: ${state.detail}; no changes were made`); const path = configPath(client, env), config = (await readOptional(path)), idPath = ownerPath(client, env), id = await readOptional(idPath); return { client, path, config, identityPath: idPath, ...(id === undefined ? {} : { identity: id }) }; }
143
+ async function restoreContent(path, value) { if (value === undefined)
144
+ await rm(path, { force: true });
145
+ else
146
+ await atomicWrite(path, value); }
147
+ export async function restoreBUnregister(snapshot) { await restoreContent(snapshot.path, snapshot.config); await restoreContent(snapshot.identityPath, snapshot.identity); }
148
+ export async function unregisterB(client, env = process.env, runner = defaultBRunner) { const snapshot = await snapshotBUnregister(client, env); if (!snapshot)
149
+ return false; await capability(client, runner); try {
150
+ if (client === "cursor-cli")
151
+ await atomicWrite(snapshot.path, update(snapshot.config, undefined));
152
+ else {
153
+ const args = client === "gemini-cli" ? ["mcp", "remove", "sandbase", "--scope", "user"] : client === "kimi-cli" ? ["mcp", "remove", "sandbase"] : ["mcp", "remove", "--name", "sandbase", "--scope", "global"];
154
+ const removed = await runner(client, args);
155
+ if (removed.code !== 0)
156
+ throw new Error(`${client} persistent MCP remove failed`);
157
+ }
158
+ await rm(snapshot.identityPath, { force: true });
159
+ const after = await inspectConfig(client, env);
160
+ if (after.state !== "missing")
161
+ throw new Error(`${client} removal readback failed`);
162
+ return true;
163
+ }
164
+ catch (error) {
165
+ await restoreBUnregister(snapshot);
166
+ throw error;
167
+ } }
@@ -0,0 +1,41 @@
1
+ export declare const cClients: readonly ["amp", "crush", "iflow-cli"];
2
+ export type CClient = typeof cClients[number];
3
+ export declare function isCClient(client: string): client is CClient;
4
+ export interface CCommandResult {
5
+ code: number | null;
6
+ stdout: string;
7
+ stderr: string;
8
+ }
9
+ export type CCommandRunner = (client: CClient, args: readonly string[]) => Promise<CCommandResult>;
10
+ export interface CAdapterResult {
11
+ client: CClient;
12
+ path: string;
13
+ backup?: string;
14
+ changed: boolean;
15
+ identityPath: string;
16
+ identityPrevious?: string;
17
+ identityChanged: boolean;
18
+ }
19
+ export interface CUnregisterSnapshot {
20
+ client: CClient;
21
+ path: string;
22
+ config?: string;
23
+ entry?: string;
24
+ identityPath: string;
25
+ identity?: string;
26
+ }
27
+ export type CInspection = {
28
+ state: "configured" | "missing" | "conflict" | "invalid" | "confirmation_required";
29
+ detail: string;
30
+ };
31
+ export interface CAdapterOptions {
32
+ ampManagedPaths?: readonly string[];
33
+ }
34
+ export declare const defaultCRunner: CCommandRunner;
35
+ export declare function ampManagedSettingsPaths(env?: NodeJS.ProcessEnv, platform?: NodeJS.Platform): string[];
36
+ export declare function inspectC(client: CClient, env?: NodeJS.ProcessEnv, runner?: CCommandRunner, options?: CAdapterOptions): Promise<CInspection>;
37
+ export declare function installC(client: CClient, bridge: string, env?: NodeJS.ProcessEnv, runner?: CCommandRunner, options?: CAdapterOptions): Promise<CAdapterResult>;
38
+ export declare function rollbackC(result: CAdapterResult, env?: NodeJS.ProcessEnv, runner?: CCommandRunner): Promise<void>;
39
+ export declare function snapshotCUnregister(client: CClient, env?: NodeJS.ProcessEnv, runner?: CCommandRunner): Promise<CUnregisterSnapshot | undefined>;
40
+ export declare function restoreCUnregister(snapshot: CUnregisterSnapshot, env?: NodeJS.ProcessEnv, runner?: CCommandRunner): Promise<void>;
41
+ export declare function unregisterC(client: CClient, env?: NodeJS.ProcessEnv, runner?: CCommandRunner): Promise<boolean>;
@@ -0,0 +1,269 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import { rm } from "node:fs/promises";
4
+ import { dirname, isAbsolute, join, resolve, win32 } from "node:path";
5
+ import { applyEdits, modify, parse } from "jsonc-parser";
6
+ import { atomicWrite, backup, readOptional, restore } from "./fs-safe.js";
7
+ import { configPath, sandbaseHome } from "./paths.js";
8
+ export const cClients = ["amp", "crush", "iflow-cli"];
9
+ export function isCClient(client) { return cClients.includes(client); }
10
+ const executables = { amp: "amp", crush: "crush", "iflow-cli": "iflow" };
11
+ export const defaultCRunner = async (client, args) => { const result = spawnSync(executables[client], [...args], { encoding: "utf8", timeout: 10_000 }); return { code: result.status, stdout: result.stdout || "", stderr: result.stderr || "" }; };
12
+ const ownerPath = (client, env = process.env) => join(sandbaseHome(env), "ownership", `${client}.json`);
13
+ const defaultBridge = (env = process.env) => join(sandbaseHome(env), "bin", "sandbase-mcp-bridge.mjs");
14
+ const entry = (client, bridge) => client === "crush" ? { type: "stdio", command: "node", args: [bridge, "--client", client] } : { command: "node", args: [bridge, "--client", client] };
15
+ function parseObject(raw, client) { const errors = []; const value = parse(raw, errors, { allowTrailingComma: true, disallowComments: false }); if (errors.length || !value || typeof value !== "object" || Array.isArray(value))
16
+ throw new Error(`${client} configuration is invalid; no changes were made`); return value; }
17
+ function object(value, client) { if (!value || typeof value !== "object" || Array.isArray(value))
18
+ throw new Error(`${client} configuration is invalid; no changes were made`); return value; }
19
+ function owned(value, client, allowed) { if (!value || typeof value !== "object" || Array.isArray(value))
20
+ return false; const item = value; return (client !== "crush" || item.type === "stdio") && item.command === "node" && Array.isArray(item.args) && item.args.length === 3 && typeof item.args[0] === "string" && isAbsolute(item.args[0]) && allowed.includes(item.args[0]) && item.args[1] === "--client" && item.args[2] === client && item.env === undefined && item.url === undefined && item.headers === undefined; }
21
+ async function identity(client, env = process.env) { const raw = await readOptional(ownerPath(client, env)); if (raw === undefined)
22
+ return undefined; try {
23
+ const value = JSON.parse(raw);
24
+ if (value.marker !== "sandbase-cli-c-v1" || value.client !== client || !isAbsolute(value.bridge))
25
+ throw new Error();
26
+ return value;
27
+ }
28
+ catch {
29
+ throw new Error(`${client} ownership identity is invalid; no changes were made`);
30
+ } }
31
+ function update(raw, path, value) { return applyEdits(raw, modify(raw, path, value, { formattingOptions: { insertSpaces: true, tabSize: 2, eol: "\n" } })); }
32
+ function ampPolicyDenied(root) { const policy = root["amp.mcpPermissions"]; if (policy === undefined)
33
+ return false; if (policy === false || policy === "deny")
34
+ return true; if (policy && typeof policy === "object" && !Array.isArray(policy)) {
35
+ const sandbase = policy.sandbase;
36
+ return sandbase === false || sandbase === "deny";
37
+ } return false; }
38
+ function ancestorDirectories(env = process.env) { const directories = []; let current = resolve(env.PWD || process.cwd()); while (true) {
39
+ directories.push(current);
40
+ if (existsAt(join(current, ".git")))
41
+ break;
42
+ const parent = dirname(current);
43
+ if (parent === current)
44
+ break;
45
+ current = parent;
46
+ } return directories; }
47
+ function existsAt(path) { try {
48
+ return requireExists(path);
49
+ }
50
+ catch {
51
+ return false;
52
+ } }
53
+ // Kept behind a tiny wrapper so path discovery remains read-only and can
54
+ // handle files as well as a repository's .git directory or worktree file.
55
+ function requireExists(path) { return existsSync(path); }
56
+ function overlayPaths(client, env = process.env) { for (const directory of ancestorDirectories(env)) {
57
+ const candidates = client === "amp" ? [join(directory, ".amp", "settings.json"), join(directory, ".amp", "settings.jsonc")] : [join(directory, ".crush.json"), join(directory, "crush.json")];
58
+ const found = candidates.filter(existsAt);
59
+ if (found.length)
60
+ return found;
61
+ } return []; }
62
+ export function ampManagedSettingsPaths(env = process.env, platform = process.platform) { if (platform === "darwin")
63
+ return ["/Library/Application Support/ampcode/managed-settings.json"]; if (platform === "win32")
64
+ return [win32.join(env.PROGRAMDATA || "C:\\ProgramData", "ampcode", "managed-settings.json")]; return ["/etc/ampcode/managed-settings.json"]; }
65
+ function configEntry(root, client) { if (client === "amp") {
66
+ const servers = root["amp.mcpServers"] === undefined ? undefined : object(root["amp.mcpServers"], client);
67
+ return servers?.sandbase;
68
+ } const servers = root.mcp === undefined ? undefined : object(root.mcp, client); return servers?.sandbase; }
69
+ async function overlayConflict(client, env = process.env) { for (const path of overlayPaths(client, env)) {
70
+ const raw = await readOptional(path);
71
+ if (raw === undefined)
72
+ continue;
73
+ const root = parseObject(raw, client);
74
+ if (configEntry(root, client) !== undefined)
75
+ return true;
76
+ } return false; }
77
+ async function ampManagedConflict(env = process.env, options = {}) { for (const path of options.ampManagedPaths || ampManagedSettingsPaths(env)) {
78
+ const raw = await readOptional(path);
79
+ if (raw === undefined)
80
+ continue;
81
+ const root = parseObject(raw, "amp");
82
+ if (configEntry(root, "amp") !== undefined || ampPolicyDenied(root))
83
+ return true;
84
+ } return false; }
85
+ async function capability(client, runner) { const probes = { amp: [["--version"], ["mcp", "add", "--help"], ["mcp", "doctor", "--help"]], crush: [["--version"]], "iflow-cli": [["--version"], ["mcp", "add-json", "--help"], ["mcp", "get", "--help"], ["mcp", "list", "--help"], ["mcp", "remove", "--help"]] }; const results = await Promise.all(probes[client].map(args => runner(client, args))); if (results.some(result => result.code !== 0))
86
+ throw new Error(`${client} persistent MCP capability is unavailable; no changes were made`); if (client === "iflow-cli" && !/--scope/.test(`${results[1]?.stdout}${results[1]?.stderr}`))
87
+ throw new Error("iFlow user-scope add-json capability is unavailable; no changes were made"); }
88
+ function iflowValue(output) { const value = JSON.parse(output); if (value && typeof value === "object" && !Array.isArray(value)) {
89
+ const root = value;
90
+ if (root.mcpServers && typeof root.mcpServers === "object")
91
+ return root.mcpServers.sandbase;
92
+ if (root.server && typeof root.server === "object")
93
+ return root.server;
94
+ if (root.command !== undefined)
95
+ return root;
96
+ } return undefined; }
97
+ async function iflowInspection(env = process.env, runner = defaultCRunner, expected) { try {
98
+ const result = await runner("iflow-cli", ["mcp", "get", "sandbase"]);
99
+ if (result.code !== 0)
100
+ return { state: "missing", detail: "legacy iFlow user-scope SandBase server is not registered" };
101
+ const value = iflowValue(result.stdout);
102
+ const id = await identity("iflow-cli", env);
103
+ const allowed = [...new Set([defaultBridge(env), id?.bridge, expected].filter((item) => !!item))];
104
+ return owned(value, "iflow-cli", allowed) ? { state: "configured", detail: "legacy iFlow user-scope bridge ownership verified; vendor service ended 2026-04-17" } : { state: "conflict", detail: "legacy iFlow sandbase entry is not SandBase-owned" };
105
+ }
106
+ catch (error) {
107
+ return { state: "invalid", detail: error instanceof Error ? error.message : "iFlow readback is invalid" };
108
+ } }
109
+ async function fileInspection(client, env = process.env, expected, options = {}) { try {
110
+ if (client === "amp" && await ampManagedConflict(env, options))
111
+ return { state: "confirmation_required", detail: "higher-priority Amp managed settings override SandBase MCP or permissions" };
112
+ if (await overlayConflict(client, env))
113
+ return { state: "confirmation_required", detail: `a higher-priority nearest ${client === "amp" ? "workspace" : "project"} SandBase entry was left untouched` };
114
+ const raw = await readOptional(configPath(client, env));
115
+ if (raw === undefined)
116
+ return { state: "missing", detail: "configuration is missing" };
117
+ const root = parseObject(raw, client);
118
+ if (client === "amp" && ampPolicyDenied(root))
119
+ return { state: "confirmation_required", detail: "Amp MCP permissions deny SandBase" };
120
+ const value = configEntry(root, client);
121
+ if (value === undefined)
122
+ return { state: "missing", detail: "SandBase is not registered" };
123
+ const id = await identity(client, env), allowed = [...new Set([defaultBridge(env), id?.bridge, expected].filter((item) => !!item))];
124
+ return owned(value, client, allowed) ? { state: "configured", detail: "managed static stdio bridge ownership verified" } : { state: "conflict", detail: "the sandbase entry is not SandBase-owned" };
125
+ }
126
+ catch (error) {
127
+ return { state: "invalid", detail: error instanceof Error ? error.message : `${client} configuration is invalid` };
128
+ } }
129
+ async function ampReadback(runner) { const result = await runner("amp", ["mcp", "doctor"]); return result.code === 0 && /(^|\W)sandbase(\W|$)/i.test(`${result.stdout}${result.stderr}`); }
130
+ async function iflowReadback(runner) { const [get, list] = await Promise.all([runner("iflow-cli", ["mcp", "get", "sandbase"]), runner("iflow-cli", ["mcp", "list"])]); return get.code === 0 && list.code === 0 && /(^|\W)sandbase(\W|$)/i.test(`${list.stdout}${list.stderr}`); }
131
+ export async function inspectC(client, env = process.env, runner = defaultCRunner, options = {}) { const state = client === "iflow-cli" ? await iflowInspection(env, runner) : await fileInspection(client, env, undefined, options); if (state.state !== "configured")
132
+ return state; if (client === "amp" && !(await ampReadback(runner)))
133
+ return { state: "invalid", detail: "Amp MCP doctor readback failed" }; if (client === "iflow-cli" && !(await iflowReadback(runner)))
134
+ return { state: "invalid", detail: "legacy iFlow get/list readback failed" }; return state; }
135
+ export async function installC(client, bridge, env = process.env, runner = defaultCRunner, options = {}) {
136
+ if (!isAbsolute(bridge))
137
+ throw new Error(`${client} managed bridge path must be absolute; no changes were made`);
138
+ await capability(client, runner);
139
+ const before = client === "iflow-cli" ? await iflowInspection(env, runner, bridge) : await fileInspection(client, env, bridge, options);
140
+ if (before.state === "conflict" || before.state === "invalid" || before.state === "confirmation_required")
141
+ throw new Error(`${client}: ${before.detail}; no changes were made`);
142
+ const path = configPath(client, env), idPath = ownerPath(client, env), idPrevious = await readOptional(idPath), idNext = JSON.stringify({ marker: "sandbase-cli-c-v1", client, bridge }, null, 2) + "\n", identityChanged = idPrevious !== idNext, changed = before.state !== "configured";
143
+ let backupPath;
144
+ const result = { client, path, changed, identityPath: idPath, ...(idPrevious === undefined ? {} : { identityPrevious: idPrevious }), identityChanged };
145
+ try {
146
+ if (identityChanged)
147
+ await atomicWrite(idPath, idNext);
148
+ if (changed) {
149
+ if (client === "iflow-cli") {
150
+ const added = await runner(client, ["mcp", "add-json", "--scope", "user", "sandbase", JSON.stringify(entry(client, bridge))]);
151
+ if (added.code !== 0)
152
+ throw new Error("legacy iFlow persistent MCP add-json failed");
153
+ }
154
+ else {
155
+ const raw = await readOptional(path), text = raw === undefined || !raw.trim() ? "{}\n" : raw;
156
+ parseObject(text, client);
157
+ backupPath = await backup(path);
158
+ if (backupPath !== undefined)
159
+ result.backup = backupPath;
160
+ await atomicWrite(path, update(text, client === "amp" ? ["amp.mcpServers", "sandbase"] : ["mcp", "sandbase"], entry(client, bridge)));
161
+ }
162
+ }
163
+ const checked = await inspectC(client, env, runner, options);
164
+ if (checked.state !== "configured")
165
+ throw new Error(`${client} MCP readback failed`);
166
+ return result;
167
+ }
168
+ catch (error) {
169
+ let compensationIncomplete = false;
170
+ if (changed) {
171
+ if (client === "iflow-cli") {
172
+ try {
173
+ const removed = await runner(client, ["mcp", "remove", "sandbase"]);
174
+ if (removed.code !== 0)
175
+ compensationIncomplete = true;
176
+ else {
177
+ const [get, list] = await Promise.all([runner(client, ["mcp", "get", "sandbase"]), runner(client, ["mcp", "list"])]);
178
+ if (get.code === 0 || list.code !== 0 || /(^|\W)sandbase(\W|$)/i.test(`${list.stdout}${list.stderr}`))
179
+ compensationIncomplete = true;
180
+ }
181
+ }
182
+ catch {
183
+ compensationIncomplete = true;
184
+ }
185
+ }
186
+ else {
187
+ try {
188
+ await restore(path, backupPath);
189
+ }
190
+ catch {
191
+ compensationIncomplete = true;
192
+ }
193
+ }
194
+ }
195
+ if (identityChanged) {
196
+ try {
197
+ idPrevious === undefined ? await rm(idPath, { force: true }) : await atomicWrite(idPath, idPrevious);
198
+ }
199
+ catch {
200
+ compensationIncomplete = true;
201
+ }
202
+ }
203
+ if (compensationIncomplete)
204
+ throw new Error(`${error instanceof Error ? error.message : `${client} installation failed`}; compensation was incomplete`);
205
+ throw error;
206
+ }
207
+ }
208
+ export async function rollbackC(result, env = process.env, runner = defaultCRunner) { if (result.changed) {
209
+ if (result.client === "iflow-cli") {
210
+ const removed = await runner(result.client, ["mcp", "remove", "sandbase"]);
211
+ if (removed.code !== 0)
212
+ throw new Error("legacy iFlow rollback remove failed");
213
+ }
214
+ else
215
+ await restore(result.path, result.backup);
216
+ } if (result.identityChanged)
217
+ result.identityPrevious === undefined ? await rm(result.identityPath, { force: true }) : await atomicWrite(result.identityPath, result.identityPrevious); }
218
+ export async function snapshotCUnregister(client, env = process.env, runner = defaultCRunner) { const state = client === "iflow-cli" ? await iflowInspection(env, runner) : await fileInspection(client, env); if (state.state === "missing")
219
+ return undefined; if (state.state !== "configured")
220
+ throw new Error(`${client}: ${state.detail}; no changes were made`); const path = configPath(client, env), idPath = ownerPath(client, env), id = await readOptional(idPath); if (client === "iflow-cli") {
221
+ const got = await runner(client, ["mcp", "get", "sandbase"]);
222
+ if (got.code !== 0)
223
+ throw new Error("legacy iFlow get readback failed; no changes were made");
224
+ const value = iflowValue(got.stdout);
225
+ return { client, path, entry: JSON.stringify(value), identityPath: idPath, ...(id === undefined ? {} : { identity: id }) };
226
+ } return { client, path, config: (await readOptional(path)), identityPath: idPath, ...(id === undefined ? {} : { identity: id }) }; }
227
+ async function restoreContent(path, value) { if (value === undefined)
228
+ await rm(path, { force: true });
229
+ else
230
+ await atomicWrite(path, value); }
231
+ export async function restoreCUnregister(snapshot, env = process.env, runner = defaultCRunner) { if (snapshot.client === "iflow-cli") {
232
+ if (!snapshot.entry)
233
+ throw new Error("legacy iFlow snapshot is incomplete");
234
+ const restored = await runner(snapshot.client, ["mcp", "add-json", "--scope", "user", "sandbase", snapshot.entry]);
235
+ if (restored.code !== 0)
236
+ throw new Error("legacy iFlow unregister compensation failed");
237
+ }
238
+ else
239
+ await restoreContent(snapshot.path, snapshot.config); await restoreContent(snapshot.identityPath, snapshot.identity); }
240
+ export async function unregisterC(client, env = process.env, runner = defaultCRunner) { const snapshot = await snapshotCUnregister(client, env, runner); if (!snapshot)
241
+ return false; await capability(client, runner); try {
242
+ if (client === "iflow-cli") {
243
+ const removed = await runner(client, ["mcp", "remove", "sandbase"]);
244
+ if (removed.code !== 0)
245
+ throw new Error("legacy iFlow persistent MCP remove failed");
246
+ const [get, list] = await Promise.all([runner(client, ["mcp", "get", "sandbase"]), runner(client, ["mcp", "list"])]);
247
+ if (get.code === 0 || list.code !== 0 || /(^|\W)sandbase(\W|$)/i.test(`${list.stdout}${list.stderr}`))
248
+ throw new Error("legacy iFlow removal readback failed");
249
+ }
250
+ else {
251
+ const text = snapshot.config;
252
+ const next = update(text, client === "amp" ? ["amp.mcpServers", "sandbase"] : ["mcp", "sandbase"], undefined);
253
+ await atomicWrite(snapshot.path, next);
254
+ const checked = await fileInspection(client, env);
255
+ if (checked.state !== "missing")
256
+ throw new Error(`${client} removal readback failed`);
257
+ if (client === "amp") {
258
+ const doctor = await runner(client, ["mcp", "doctor"]);
259
+ if (doctor.code !== 0)
260
+ throw new Error("Amp doctor removal readback failed");
261
+ }
262
+ }
263
+ await rm(snapshot.identityPath, { force: true });
264
+ return true;
265
+ }
266
+ catch (error) {
267
+ await restoreCUnregister(snapshot, env, runner);
268
+ throw error;
269
+ } }
@@ -0,0 +1,61 @@
1
+ declare const owner = "sandbase-cli/claude-desktop-artifacts";
2
+ declare const skillDigest = "4e32edb4f2f158333a19c7f64e777f354914adccd61314250770e2db7ff93087";
3
+ export declare const claudeDesktopMCPConfig = "{\n \"mcpServers\": {\n \"sandbase\": {\n \"command\": \"npx\",\n \"args\": [\"-y\", \"@sandbaseai/cli\", \"mcp-bridge\", \"--client\", \"claude-desktop\"]\n }\n }\n}\n";
4
+ declare const mcpDigest = "24a37a92885f1168745e7c4b5ddf1c8c8759f9be1d4c73f359436f8dfe410eeb";
5
+ interface Source {
6
+ repository: string;
7
+ ref: string;
8
+ commit: string;
9
+ path: string;
10
+ }
11
+ interface Artifact {
12
+ kind: string;
13
+ version: string;
14
+ filename: string;
15
+ media_type: string;
16
+ sha256: string;
17
+ download_url: string;
18
+ source?: Source;
19
+ }
20
+ export interface ClaudeDesktopManifest {
21
+ client: string;
22
+ artifacts: Artifact[];
23
+ }
24
+ export type ArtifactReadbackStatus = "ready" | "missing" | "invalid";
25
+ export interface ClaudeDesktopArtifactReadback {
26
+ mcp: ArtifactReadbackStatus;
27
+ skill: ArtifactReadbackStatus;
28
+ }
29
+ export interface ClaudeDesktopArtifactState {
30
+ schemaVersion: 1;
31
+ owner: typeof owner;
32
+ client: "claude-desktop";
33
+ mcp?: {
34
+ version: "1";
35
+ sha256: typeof mcpDigest;
36
+ };
37
+ skill?: {
38
+ version: "a43b227";
39
+ sha256: typeof skillDigest;
40
+ source: Source;
41
+ };
42
+ }
43
+ export interface StoredArtifactReadback extends ClaudeDesktopArtifactReadback {
44
+ ownership: "ready" | "missing" | "invalid";
45
+ }
46
+ export declare function claudeDesktopArtifactPath(home?: string): string;
47
+ export declare function inspectClaudeDesktopArtifacts(manifest?: ClaudeDesktopManifest, mcpBytes?: Uint8Array, skillBytes?: Uint8Array): ClaudeDesktopArtifactReadback;
48
+ export declare function readClaudeDesktopArtifactState(home?: string): Promise<StoredArtifactReadback>;
49
+ export declare function recordClaudeDesktopArtifacts(manifest: ClaudeDesktopManifest, mcpBytes?: Uint8Array, skillBytes?: Uint8Array, home?: string): Promise<{
50
+ path: string;
51
+ previous?: string;
52
+ changed: boolean;
53
+ readback: ClaudeDesktopArtifactReadback;
54
+ }>;
55
+ export declare function rollbackClaudeDesktopArtifacts(result: {
56
+ path: string;
57
+ previous?: string;
58
+ changed: boolean;
59
+ }): Promise<void>;
60
+ export declare function removeClaudeDesktopArtifacts(home?: string): Promise<boolean>;
61
+ export {};
@@ -0,0 +1,50 @@
1
+ import { createHash } from "node:crypto";
2
+ import { rm } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { atomicWrite, readOptional } from "./fs-safe.js";
5
+ import { sandbaseHome } from "./paths.js";
6
+ const owner = "sandbase-cli/claude-desktop-artifacts";
7
+ const repository = "https://github.com/sandbaseai/sandbase-skills";
8
+ const commit = "a43b2272473615137c86637423285a641f64f64c";
9
+ const skillDigest = "4e32edb4f2f158333a19c7f64e777f354914adccd61314250770e2db7ff93087";
10
+ export const claudeDesktopMCPConfig = '{\n "mcpServers": {\n "sandbase": {\n "command": "npx",\n "args": ["-y", "@sandbaseai/cli", "mcp-bridge", "--client", "claude-desktop"]\n }\n }\n}\n';
11
+ const mcpDigest = "24a37a92885f1168745e7c4b5ddf1c8c8759f9be1d4c73f359436f8dfe410eeb";
12
+ const sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex");
13
+ export function claudeDesktopArtifactPath(home = sandbaseHome()) { return join(home, "desktop", "claude-desktop-artifacts.json"); }
14
+ function artifacts(manifest) { return { mcp: manifest?.artifacts?.find(item => item.kind === "mcp-config"), skill: manifest?.artifacts?.find(item => item.kind === "skill") }; }
15
+ function validMCP(item, bytes) { if (!item || !bytes)
16
+ return false; return item.version === "1" && item.filename === "sandbase-claude-desktop-mcp.json" && item.media_type === "application/json" && item.sha256 === mcpDigest && item.download_url === "/default/v1/desktop-onboarding/claude-desktop/artifacts/mcp-config" && sha256(bytes) === mcpDigest && Buffer.from(bytes).toString("utf8") === claudeDesktopMCPConfig; }
17
+ function validSkill(item, bytes) { const source = item?.source; if (!item || !bytes || !source)
18
+ return false; return item.version === "a43b227" && item.filename === "sandbase-skill.zip" && item.media_type === "application/zip" && item.sha256 === skillDigest && item.download_url === "/default/v1/desktop-onboarding/claude-desktop/artifacts/skill" && source.repository === repository && source.ref === commit && source.commit === commit && source.path === "SKILL.md" && sha256(bytes) === skillDigest; }
19
+ export function inspectClaudeDesktopArtifacts(manifest, mcpBytes, skillBytes) { if (manifest?.client !== "claude-desktop" || !Array.isArray(manifest.artifacts) || manifest.artifacts.length !== 2)
20
+ return { mcp: manifest ? "invalid" : "missing", skill: manifest ? "invalid" : "missing" }; const found = artifacts(manifest); return { mcp: !found.mcp || !mcpBytes ? "missing" : validMCP(found.mcp, mcpBytes) ? "ready" : "invalid", skill: !found.skill || !skillBytes ? "missing" : validSkill(found.skill, skillBytes) ? "ready" : "invalid" }; }
21
+ const mcpState = { version: "1", sha256: mcpDigest };
22
+ const skillState = { version: "a43b227", sha256: skillDigest, source: { repository, ref: commit, commit, path: "SKILL.md" } };
23
+ function validStored(value) { if (!value || typeof value !== "object" || Array.isArray(value))
24
+ return false; const state = value; if (state.schemaVersion !== 1 || state.owner !== owner || state.client !== "claude-desktop" || (!state.mcp && !state.skill))
25
+ return false; return (!state.mcp || JSON.stringify(state.mcp) === JSON.stringify(mcpState)) && (!state.skill || JSON.stringify(state.skill) === JSON.stringify(skillState)); }
26
+ export async function readClaudeDesktopArtifactState(home = sandbaseHome()) { const raw = await readOptional(claudeDesktopArtifactPath(home)); if (!raw)
27
+ return { ownership: "missing", mcp: "missing", skill: "missing" }; try {
28
+ const state = JSON.parse(raw);
29
+ if (!validStored(state))
30
+ return { ownership: "invalid", mcp: "invalid", skill: "invalid" };
31
+ return { ownership: "ready", mcp: state.mcp ? "ready" : "missing", skill: state.skill ? "ready" : "missing" };
32
+ }
33
+ catch {
34
+ return { ownership: "invalid", mcp: "invalid", skill: "invalid" };
35
+ } }
36
+ export async function recordClaudeDesktopArtifacts(manifest, mcpBytes, skillBytes, home = sandbaseHome()) { const readback = inspectClaudeDesktopArtifacts(manifest, mcpBytes, skillBytes); const path = claudeDesktopArtifactPath(home); if (readback.mcp !== "ready" && readback.skill !== "ready")
37
+ return { path, changed: false, readback }; const previous = await readOptional(path); const stored = await readClaudeDesktopArtifactState(home); if (previous && stored.ownership === "invalid")
38
+ throw new Error("Claude Desktop artifact ownership is unrecognized; no changes were made"); let current = { schemaVersion: 1, owner, client: "claude-desktop" }; if (previous)
39
+ current = JSON.parse(previous); if (readback.mcp === "ready")
40
+ current.mcp = mcpState; if (readback.skill === "ready")
41
+ current.skill = skillState; const next = JSON.stringify(current, null, 2) + "\n"; if (previous === next)
42
+ return { path, previous, changed: false, readback }; await atomicWrite(path, next, 0o600); return { path, ...(previous === undefined ? {} : { previous }), changed: true, readback }; }
43
+ export async function rollbackClaudeDesktopArtifacts(result) { if (!result.changed)
44
+ return; if (result.previous === undefined)
45
+ await rm(result.path, { force: true });
46
+ else
47
+ await atomicWrite(result.path, result.previous, 0o600); }
48
+ export async function removeClaudeDesktopArtifacts(home = sandbaseHome()) { const state = await readClaudeDesktopArtifactState(home); if (state.ownership === "missing")
49
+ return false; if (state.ownership === "invalid")
50
+ throw new Error("Claude Desktop artifact ownership is unrecognized; no changes were made"); await rm(claudeDesktopArtifactPath(home)); return true; }