@sandbaseai/cli 0.1.2 → 0.1.3

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,14 +2,16 @@ import { mkdir, readFile } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import { spawnSync } from "node:child_process";
5
+ import { existsSync } from "node:fs";
5
6
  import { parse as parseToml } from "smol-toml";
6
7
  import { parseDocument } from "yaml";
7
8
  import { atomicWrite, backup, readOptional, restore } from "../fs-safe.js";
8
9
  import { clientProfiles } from "../clients.js";
9
10
  import { configPath, sandbaseHome } from "../paths.js";
10
11
  const defaultIO = { backup, write: atomicWrite, restore };
11
- export function detectClient(client) { const profile = clientProfiles[client]; if (!profile.executable || profile.mode !== "auto")
12
- return { installed: true, detail: "manual setup" }; const result = spawnSync(profile.executable, ["--version"], { encoding: "utf8", timeout: 5000 }); const detail = (result.stdout || result.stderr || "").trim().split("\n")[0] || "not found"; return { installed: result.status === 0, detail }; }
12
+ export function detectClient(client) { const profile = clientProfiles[client]; if (profile.mode !== "auto")
13
+ return { installed: true, detail: "manual setup" }; if (!profile.executable)
14
+ return existsSync(configPath(client)) ? { installed: true, detail: "existing configuration" } : { installed: false, detail: "configuration not found" }; const result = spawnSync(profile.executable, ["--version"], { encoding: "utf8", timeout: 5000 }); const detail = (result.stdout || result.stderr || "").trim().split("\n")[0] || "not found"; return { installed: result.status === 0, detail }; }
13
15
  const start = "# >>> sandbase managed >>>", end = "# <<< sandbase managed <<<";
14
16
  function block(client, bridge) {
15
17
  if (client === "codex")
@@ -1,4 +1,4 @@
1
- import type { Client, Exchange, Grant } from "../types.js";
1
+ import type { ConnectClient, Exchange, Grant } from "../types.js";
2
2
  export interface Secrets {
3
3
  requestId: string;
4
4
  deviceSecret: string;
@@ -17,7 +17,7 @@ export declare class AuthorizationApi {
17
17
  private readonly fetcher;
18
18
  constructor(baseUrl: string, fetcher?: typeof fetch);
19
19
  private request;
20
- create(client: Client, s: Secrets): Promise<Grant>;
20
+ create(client: ConnectClient, s: Secrets): Promise<Grant>;
21
21
  status(id: string, secret: string): Promise<{
22
22
  status: string;
23
23
  interval: number;
@@ -1,4 +1,4 @@
1
- import type { Client, Exchange } from "../types.js";
1
+ import type { ConnectClient, Exchange } from "../types.js";
2
2
  import { AuthorizationApi } from "./api.js";
3
3
  export interface FlowOptions {
4
4
  signal?: AbortSignal;
@@ -6,7 +6,7 @@ export interface FlowOptions {
6
6
  sleep(ms: number, signal?: AbortSignal): Promise<void>;
7
7
  log(message: string): void;
8
8
  }
9
- export declare function authorize(api: AuthorizationApi, client: Client, options: FlowOptions): Promise<{
9
+ export declare function authorize(api: AuthorizationApi, client: ConnectClient, options: FlowOptions): Promise<{
10
10
  authorizationId: string;
11
11
  exchange: Exchange;
12
12
  }>;
package/dist/cli.js CHANGED
@@ -1,8 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { connect, doctor, unregister } from "./commands.js";
3
- import { detectClient } from "./adapters/index.js";
4
- import { clientList, clientProfiles } from "./clients.js";
5
- import { clients, isClient } from "./types.js";
3
+ import { clientList } from "./clients.js";
4
+ import { isClient } from "./types.js";
6
5
  if (Number(process.versions.node.split(".")[0]) < 20) {
7
6
  console.error("SandBase CLI requires Node.js 20 or newer. Upgrade Node.js and retry.");
8
7
  process.exit(1);
@@ -10,15 +9,9 @@ if (Number(process.versions.node.split(".")[0]) < 20) {
10
9
  const [command, ...args] = process.argv.slice(2);
11
10
  const at = args.indexOf("--client");
12
11
  const value = at >= 0 ? args[at + 1] : undefined;
13
- function autoClient() {
14
- return clients.find(client => {
15
- const profile = clientProfiles[client];
16
- return profile.mode === "auto" && !!profile.executable && detectClient(client).installed;
17
- });
18
- }
19
- const resolved = value === "auto" || (!value && command === "connect") ? autoClient() : value && isClient(value) ? value : undefined;
20
- if (!command || !resolved || (command !== "connect" && !value) || !["connect", "doctor", "unregister"].includes(command)) {
21
- console.error(`Usage: sandbase <connect|doctor|unregister> --client <${clientList()}|auto>`);
12
+ const client = value === undefined || value === "auto" ? "auto" : isClient(value) ? value : undefined;
13
+ if (!command || !client || !["connect", "doctor", "unregister"].includes(command) || (at >= 0 && !value)) {
14
+ console.error(`Usage: sandbase <connect|doctor|unregister> [--client <${clientList()}|auto>]`);
22
15
  process.exit(2);
23
16
  }
24
17
  const controller = new AbortController();
@@ -26,19 +19,19 @@ for (const signal of ["SIGINT", "SIGTERM"])
26
19
  process.once(signal, () => controller.abort());
27
20
  try {
28
21
  if (command === "connect")
29
- await connect(resolved, { signal: controller.signal });
22
+ await connect(client, { signal: controller.signal });
30
23
  else if (command === "doctor") {
31
- if (!(await doctor(resolved)))
24
+ if (!(await doctor(client)))
32
25
  process.exitCode = 1;
33
26
  }
34
27
  else
35
- await unregister(resolved);
28
+ await unregister(client);
36
29
  }
37
30
  catch (e) {
38
31
  const message = e instanceof Error ? e.message : "Unknown failure";
39
32
  if (message.includes("fetch failed"))
40
33
  console.error("Authorization response may have been lost. Check SandBase Dashboard for a newly created CLI credential, revoke it if present, then retry.");
41
34
  else
42
- console.error(message.replace(/sk-[A-Za-z0-9_-]+/g, "[REDACTED]"));
35
+ console.error(message.replace(/(?:sk|cln)-[A-Za-z0-9_-]+/g, "[REDACTED]"));
43
36
  process.exitCode = 1;
44
37
  }
package/dist/clients.d.ts CHANGED
@@ -9,3 +9,4 @@ export interface ClientProfile {
9
9
  }
10
10
  export declare const clientProfiles: Record<Client, ClientProfile>;
11
11
  export declare function clientList(): string;
12
+ export declare function autoClients(): Client[];
package/dist/clients.js CHANGED
@@ -27,3 +27,6 @@ export const clientProfiles = {
27
27
  export function clientList() {
28
28
  return Object.keys(clientProfiles).join("|");
29
29
  }
30
+ export function autoClients() {
31
+ return Object.values(clientProfiles).filter(profile => profile.mode === "auto" && !!profile.adapter).map(profile => profile.id);
32
+ }
@@ -1,17 +1,20 @@
1
- import type { Client } from "./types.js";
1
+ import type { Client, ConnectClient } from "./types.js";
2
2
  import { AuthorizationApi } from "./auth/api.js";
3
- import { FileCredentialStore } from "./credentials/store.js";
4
- export declare function openBrowser(url: string): Promise<void>;
5
- export declare function connect(client: Client, deps?: {
3
+ import { type CredentialStore } from "./credentials/store.js";
4
+ type Detection = {
5
+ installed: boolean;
6
+ detail: string;
7
+ };
8
+ export interface CommandDependencies {
6
9
  api?: AuthorizationApi;
7
- store?: FileCredentialStore;
10
+ store?: CredentialStore;
8
11
  open?: (url: string) => Promise<void>;
9
12
  signal?: AbortSignal;
10
13
  log?: (s: string) => void;
11
- detect?: (client: Client) => {
12
- installed: boolean;
13
- detail: string;
14
- };
15
- }): Promise<void>;
16
- export declare function doctor(client: Client, store?: FileCredentialStore): Promise<boolean>;
17
- export declare function unregister(client: Client, store?: FileCredentialStore): Promise<void>;
14
+ detect?: (client: Client) => Detection;
15
+ }
16
+ export declare function openBrowser(url: string): Promise<void>;
17
+ export declare function connect(client?: ConnectClient, deps?: CommandDependencies): Promise<void>;
18
+ export declare function doctor(client?: ConnectClient, store?: CredentialStore, detect?: (client: Client) => Detection): Promise<boolean>;
19
+ export declare function unregister(client?: ConnectClient, store?: CredentialStore, detect?: (client: Client) => Detection): Promise<void>;
20
+ export {};
package/dist/commands.js CHANGED
@@ -2,7 +2,7 @@ import { spawn } from "node:child_process";
2
2
  import { platform } from "node:os";
3
3
  import { AuthorizationApi } from "./auth/api.js";
4
4
  import { authorize } from "./auth/flow.js";
5
- import { clientProfiles } from "./clients.js";
5
+ import { autoClients, clientProfiles } from "./clients.js";
6
6
  import { FileCredentialStore } from "./credentials/store.js";
7
7
  import { configure, detectClient, installBridge, isConfigured, rollback, rollbackBridge, unregister as removeAdapter } from "./adapters/index.js";
8
8
  const sleep = (ms, signal) => new Promise((resolve, reject) => { const t = setTimeout(resolve, ms); signal?.addEventListener("abort", () => { clearTimeout(t); reject(new Error("Authorization cancelled")); }, { once: true }); });
@@ -16,36 +16,39 @@ async function compensate(api, authorizationId, token) { for (const delay of [0,
16
16
  catch { /* bounded retry inside the five-minute capability window */ }
17
17
  } return false; }
18
18
  export async function openBrowser(url) { const cmd = platform() === "darwin" ? "open" : platform() === "win32" ? "cmd" : "xdg-open"; const args = platform() === "win32" ? ["/c", "start", "", url] : [url]; const child = spawn(cmd, args, { detached: true, stdio: "ignore" }); child.unref(); }
19
- function mcpServerSnippet(client, bridgePath) {
20
- return JSON.stringify({ mcpServers: { sandbase: { command: "node", args: [bridgePath, "--client", client] } } }, null, 2);
21
- }
22
- function nextStepPrompts(label) {
23
- return [`2. In ${label}, try asking:`, ` - List the available SandBase MCP tools.`, ` - Use SandBase to fetch Elon Musk's latest 10 posts on Twitter.`];
24
- }
19
+ function mcpServerSnippet(client, bridgePath) { return JSON.stringify({ mcpServers: { sandbase: { command: "node", args: [bridgePath, "--client", client] } } }, null, 2); }
20
+ function nextStepPrompts(label) { return [`2. In ${label}, try asking:`, " - List the available SandBase MCP tools.", " - Use SandBase to fetch Elon Musk's latest 10 posts on Twitter."]; }
25
21
  function successMessage(client, record, bridgePath, configuredPath) {
26
22
  const profile = clientProfiles[client];
27
23
  const label = profile.label;
28
- const common = [``, `SandBase MCP is connected.`, ``, `Client: ${label} (${client})`, `MCP URL: ${record.mcpUrl}`, `Credential: ${record.keyPrefix}... (${record.scope.join(",")})`, `Bridge: ${bridgePath}`];
24
+ const common = ["", "SandBase MCP is connected.", "", `Client: ${label} (${client})`, `MCP URL: ${record.mcpUrl}`, `Credential: ${record.keyPrefix}... (${record.scope.join(",")})`, `Bridge: ${bridgePath}`];
29
25
  if (profile.mode === "auto")
30
- return [...common, `Config: ${configuredPath || "updated"}`, ``, `Next steps:`, `1. Restart or reload ${label} so it picks up the new MCP configuration.`, ...nextStepPrompts(label), ``, `Manage access: revoke the "CLI Login" key in SandBase Dashboard when you no longer need it.`].join("\n");
26
+ return [...common, `Config: ${configuredPath || "updated"}`, "", "Next steps:", `1. Restart or reload ${label} so it picks up the new MCP configuration.`, ...nextStepPrompts(label), "", 'Manage access: revoke the "CLI Login" key in SandBase Dashboard when you no longer need it.'].join("\n");
31
27
  if (profile.mode === "skill")
32
- return [...common, ``, `Skill/prompt setup required.`, `Copy the following instruction into ${label}:`, ``, `Install the SandBase MCP bridge for ${label}. Use this local MCP server configuration and keep the scope limited to SandBase:`, mcpServerSnippet(client, bridgePath), `After setup, reload ${label} if needed.`, ``, `Next steps:`, `1. Finish the skill/prompt setup in ${label}.`, ...nextStepPrompts(label), ``, `Manage access: revoke the "CLI Login" key in SandBase Dashboard when you no longer need it.`].join("\n");
33
- return [...common, ``, `Manual MCP configuration required.`, `Add this MCP server configuration to ${label}:`, ``, mcpServerSnippet(client, bridgePath), ``, `Next steps:`, `1. Save the configuration and restart or reload ${label}.`, ...nextStepPrompts(label), ``, `Manage access: revoke the "CLI Login" key in SandBase Dashboard when you no longer need it.`].join("\n");
28
+ return [...common, "", "Skill/prompt setup required.", `Copy the following instruction into ${label}:`, "", `Install the SandBase MCP bridge for ${label}. Use this local MCP server configuration and keep the scope limited to SandBase:`, mcpServerSnippet(client, bridgePath), `After setup, reload ${label} if needed.`, "", "Next steps:", "1. Finish the skill/prompt setup in ${label}.", ...nextStepPrompts(label), "", 'Manage access: revoke the "CLI Login" key in SandBase Dashboard when you no longer need it.'].join("\n");
29
+ return [...common, "", "Manual MCP configuration required.", `Add this MCP server configuration to ${label}:`, "", mcpServerSnippet(client, bridgePath), "", "Next steps:", `1. Save the configuration and restart or reload ${label}.`, ...nextStepPrompts(label), "", 'Manage access: revoke the "CLI Login" key in SandBase Dashboard when you no longer need it.'].join("\n");
34
30
  }
35
- export async function connect(client, deps = {}) {
31
+ function plannedAutoClients(detect) { return autoClients().filter(client => detect(client).installed); }
32
+ function recordFor(client, exchange) { return { credential: exchange.credential, credentialId: exchange.credential_id, keyPrefix: exchange.key_prefix, client, scope: exchange.scope, mcpUrl: exchange.mcp_url, createdAt: exchange.created_at }; }
33
+ async function restoreCredential(store, client, previous) { if (previous)
34
+ await store.save(previous);
35
+ else
36
+ await store.remove(client); }
37
+ async function connectOne(client, deps) {
36
38
  const api = deps.api || new AuthorizationApi((process.env.SANDBASE_API_URL || "https://sandbase.ai").replace(/\/$/, ""));
37
39
  const store = deps.store || new FileCredentialStore();
38
40
  const log = deps.log || console.log;
41
+ const detect = deps.detect || detectClient;
39
42
  const profile = clientProfiles[client];
40
- const detected = (deps.detect || detectClient)(client);
43
+ const detected = detect(client);
41
44
  if (!detected.installed)
42
- throw new Error(`${profile.label} is not installed or is incompatible (${detected.detail}). Install a supported version, then retry.`);
45
+ throw new Error(`${profile.label} is not installed or is incompatible. Install a supported version, then retry.`);
43
46
  const previous = await store.get(client);
44
47
  const { authorizationId, exchange } = await authorize(api, client, { open: deps.open || openBrowser, sleep, log, ...(deps.signal ? { signal: deps.signal } : {}) });
45
48
  let configured;
46
49
  let bridgeResult;
47
50
  try {
48
- const record = { credential: exchange.credential, credentialId: exchange.credential_id, keyPrefix: exchange.key_prefix, client, scope: exchange.scope, mcpUrl: exchange.mcp_url, createdAt: exchange.created_at };
51
+ const record = recordFor(client, exchange);
49
52
  await store.save(record);
50
53
  bridgeResult = await installBridge();
51
54
  configured = await configure(client, bridgeResult.path);
@@ -59,15 +62,90 @@ export async function connect(client, deps = {}) {
59
62
  await rollback(configured).catch(() => undefined);
60
63
  if (bridgeResult)
61
64
  await rollbackBridge(bridgeResult).catch(() => undefined);
62
- if (previous)
63
- await store.save(previous).catch(() => undefined);
64
- else
65
- await store.remove(client).catch(() => undefined);
65
+ await restoreCredential(store, client, previous).catch(() => undefined);
66
+ if (!(await compensate(api, authorizationId, exchange.cleanup_token)))
67
+ console.error("WARNING: automatic credential cleanup failed. Revoke the new CLI credential in SandBase Dashboard immediately.");
68
+ exchange.cleanup_token = "";
69
+ throw e;
70
+ }
71
+ }
72
+ async function connectAuto(deps) {
73
+ const api = deps.api || new AuthorizationApi((process.env.SANDBASE_API_URL || "https://sandbase.ai").replace(/\/$/, ""));
74
+ const store = deps.store || new FileCredentialStore();
75
+ const log = deps.log || console.log;
76
+ const detect = deps.detect || detectClient;
77
+ const targets = plannedAutoClients(detect);
78
+ if (!targets.length) {
79
+ log("No installed compatible clients support automatic configuration. Use --client <client> for manual or skill setup guidance.");
80
+ return;
81
+ }
82
+ const { authorizationId, exchange } = await authorize(api, "auto", { open: deps.open || openBrowser, sleep, log, ...(deps.signal ? { signal: deps.signal } : {}) });
83
+ let bridgeResult;
84
+ const succeeded = [], failed = [];
85
+ try {
86
+ bridgeResult = await installBridge();
87
+ for (const client of targets) {
88
+ const previous = await store.get(client);
89
+ let configured;
90
+ try {
91
+ const record = recordFor(client, exchange);
92
+ await store.save(record);
93
+ configured = await configure(client, bridgeResult.path);
94
+ if (!(await isConfigured(client)))
95
+ throw new Error("Client configuration verification failed");
96
+ succeeded.push(client);
97
+ }
98
+ catch {
99
+ if (configured)
100
+ await rollback(configured).catch(() => undefined);
101
+ await restoreCredential(store, client, previous).catch(() => undefined);
102
+ failed.push(client);
103
+ }
104
+ }
105
+ if (!succeeded.length)
106
+ throw new Error("No clients were configured successfully.");
107
+ log(`Configured clients: ${succeeded.join(", ")}.`);
108
+ if (failed.length)
109
+ log(`Partial success: failed clients were rolled back: ${failed.join(", ")}.`);
110
+ exchange.cleanup_token = "";
111
+ }
112
+ catch (e) {
113
+ if (bridgeResult)
114
+ await rollbackBridge(bridgeResult).catch(() => undefined);
66
115
  if (!(await compensate(api, authorizationId, exchange.cleanup_token)))
67
116
  console.error("WARNING: automatic credential cleanup failed. Revoke the new CLI credential in SandBase Dashboard immediately.");
68
117
  exchange.cleanup_token = "";
69
118
  throw e;
70
119
  }
71
120
  }
72
- export async function doctor(client, store = new FileCredentialStore()) { const credential = await store.get(client); const profile = clientProfiles[client]; const configured = profile.mode === "auto" ? await isConfigured(client) : !!credential; const detected = detectClient(client); console.log(`${client}: mode=${profile.mode}, installed=${detected.installed ? "yes" : "no"}, config=${configured ? profile.mode === "auto" ? "ok" : "manual" : "missing"}, credential=${credential ? credential.keyPrefix + "…" : "missing"}, url=${credential?.mcpUrl || "unknown"}, scope=${credential?.scope.join(",") || "unknown"}`); return detected.installed && !!credential && configured; }
73
- export async function unregister(client, store = new FileCredentialStore()) { const removed = await removeAdapter(client); await store.remove(client); console.log(`Removed local SandBase registration for ${client}.${removed ? "" : " No managed client configuration was changed."} Revoke the server credential in SandBase Dashboard if it is no longer needed.`); }
121
+ export async function connect(client = "auto", deps = {}) { if (client === "auto")
122
+ return connectAuto(deps); return connectOne(client, deps); }
123
+ export async function doctor(client = "auto", store = new FileCredentialStore(), detect = detectClient) {
124
+ const targets = client === "auto" ? plannedAutoClients(detect) : [client];
125
+ if (!targets.length) {
126
+ console.log("No installed compatible clients support automatic configuration.");
127
+ return false;
128
+ }
129
+ let healthy = true;
130
+ for (const target of targets) {
131
+ const credential = await store.get(target);
132
+ const profile = clientProfiles[target];
133
+ const configured = profile.mode === "auto" ? await isConfigured(target) : !!credential;
134
+ const detected = detect(target);
135
+ console.log(`${target}: mode=${profile.mode}, installed=${detected.installed ? "yes" : "no"}, config=${configured ? profile.mode === "auto" ? "ok" : "manual" : "missing"}, credential=${credential ? credential.keyPrefix + "…" : "missing"}, url=${credential?.mcpUrl || "unknown"}, scope=${credential?.scope.join(",") || "unknown"}`);
136
+ healthy = healthy && detected.installed && !!credential && configured;
137
+ }
138
+ return healthy;
139
+ }
140
+ export async function unregister(client = "auto", store = new FileCredentialStore(), detect = detectClient) {
141
+ const targets = client === "auto" ? plannedAutoClients(detect) : [client];
142
+ if (!targets.length) {
143
+ console.log("No installed compatible clients support automatic configuration.");
144
+ return;
145
+ }
146
+ for (const target of targets) {
147
+ const removed = await removeAdapter(target);
148
+ await store.remove(target);
149
+ console.log(`Removed local SandBase registration for ${target}.${removed ? "" : " No managed client configuration was changed."} Revoke the server credential in SandBase Dashboard if it is no longer needed.`);
150
+ }
151
+ }
package/dist/types.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export declare const clients: readonly ["codex", "claude-code", "cursor", "windsurf", "gemini-cli", "opencode", "chatgpt", "hermes", "openclaw", "antigravity", "claude-desktop", "cursor-cli", "warp", "trae", "kimi-cli", "qwen-code", "kiro-cli", "amp", "crush", "iflow-cli", "qoder", "workbuddy", "cowork", "pi"];
2
2
  export type Client = typeof clients[number];
3
+ export type ConnectClient = Client | "auto";
3
4
  export declare function isClient(value: string): value is Client;
4
5
  export interface CredentialRecord {
5
6
  credential: string;
@@ -21,7 +22,7 @@ export interface Exchange {
21
22
  credential: string;
22
23
  credential_id: string;
23
24
  key_prefix: string;
24
- client: Client;
25
+ client: ConnectClient;
25
26
  scope: string[];
26
27
  mcp_url: string;
27
28
  created_at: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sandbaseai/cli",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "description": "Secure SandBase MCP onboarding CLI",
5
5
  "type": "module",
6
6
  "bin": {