@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.
package/dist/commands.js CHANGED
@@ -1,12 +1,23 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { platform } from "node:os";
3
- import { clients } from "./types.js";
3
+ import { dirname, join } from "node:path";
4
+ import { clients, isPromptAssistedClient } from "./types.js";
4
5
  import { AuthorizationApi } from "./auth/api.js";
5
6
  import { authorize } from "./auth/flow.js";
6
7
  import { autoClients, capabilityRegistry, clientProfiles, nativeCapabilities } from "./clients.js";
7
8
  import { FileCredentialStore } from "./credentials/store.js";
8
- import { configure, detectClient, installBridge, isConfigured, rollback, rollbackBridge, unregister as removeAdapter } from "./adapters/index.js";
9
- import { inspectSkill, installSkill, removeSkill, sharedSkillReferences, skillFallback, skillInvocation } from "./skills.js";
9
+ import { configure, detectClient, inspectBridge, installBridge, isConfigured, rollback, rollbackBridge, unregister as removeAdapter } from "./adapters/index.js";
10
+ import { inspectA1, installA1, isA1Client, rollbackA1, restoreA1Unregister, snapshotA1Unregister, unregisterA1 } from "./a1-adapters.js";
11
+ import { inspectB, installB, isBClient, rollbackB, restoreBUnregister, snapshotBUnregister, unregisterB } from "./b-adapters.js";
12
+ import { inspectC, installC, isCClient, rollbackC, restoreCUnregister, snapshotCUnregister, unregisterC } from "./c-adapters.js";
13
+ import { inspectWarp, installWarp, rollbackWarp, restoreWarpUnregister, snapshotWarpUnregister, unregisterWarp } from "./warp-adapter.js";
14
+ import { inspectKiroIDE, installKiroIDE, rollbackKiroIDE, restoreKiroIDEUnregister, snapshotKiroIDEUnregister, unregisterKiroIDE } from "./kiro-ide.js";
15
+ import { inspectSkill, installSkill, removeSkill, sharedSkillReferences, skillFallback, skillInvocation, skillPath } from "./skills.js";
16
+ import { executeNativeSkillRemoval, inspectNativeSkill, installNativeSkill, planNativeSkillRemoval, removeNativeSkill, skillsAgentRegistry, inspectOpenClawMcp, inspectOpenClawSkill, installOpenClawMcp, installOpenClawSkill, removeOpenClawMcp, removeOpenClawSkill } from "./skills-cli.js";
17
+ import { desktopIdentityPath, isDesktopClient, readDesktopIdentity, removeDesktopIdentity, rollbackDesktopIdentity, writeDesktopIdentity } from "./desktop-bridge.js";
18
+ import { claudeDesktopArtifactPath, readClaudeDesktopArtifactState, removeClaudeDesktopArtifacts, rollbackClaudeDesktopArtifacts } from "./claude-desktop.js";
19
+ import { coworkStatePath, readCoworkState, removeCoworkState, rollbackCoworkState } from "./cowork.js";
20
+ import { atomicWrite, readOptional, restore } from "./fs-safe.js";
10
21
  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 }); });
11
22
  async function compensate(api, authorizationId, token) { for (const delay of [0, 250, 750]) {
12
23
  if (delay)
@@ -19,10 +30,13 @@ async function compensate(api, authorizationId, token) { for (const delay of [0,
19
30
  } return false; }
20
31
  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(); }
21
32
  function mcpServerSnippet(client, bridgePath) { return JSON.stringify({ mcpServers: { sandbase: { command: "node", args: [bridgePath, "--client", client] } } }, null, 2); }
33
+ function promptAssistedLauncher(client) { return JSON.stringify({ command: "npx", args: ["-y", "@sandbaseai/cli", "mcp-bridge", "--client", client] }, null, 2); }
22
34
  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."]; }
23
35
  function successMessage(client, bridgePath) {
24
36
  const profile = clientProfiles[client];
25
37
  const label = profile.label;
38
+ if (client === "warp")
39
+ return ["", "SandBase MCP configuration is staged for Warp.", "", "Client: Warp (warp)", "Credential was stored locally with restricted permissions.", "", "Next steps:", "1. Open Warp and use /agent-add-mcp to review and approve the SandBase server.", "2. Read back SandBase in Warp's MCP server list and inspect its tools before treating it as connected.", "3. If a project .warp/.mcp.json defines sandbase, remove or rename that override first; SandBase leaves it untouched.", "", 'Manage access: revoke the "CLI Login" key in SandBase Dashboard when you no longer need it.'].join("\n");
26
40
  const common = ["", "SandBase MCP is connected.", "", `Client: ${label} (${client})`, "Credential was stored locally with restricted permissions."];
27
41
  if (profile.mode === "auto")
28
42
  return [...common, "", "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");
@@ -35,6 +49,8 @@ function logDetectedActionRequired(detect, log) {
35
49
  for (const client of clients) {
36
50
  const capability = nativeCapabilities[client];
37
51
  const v2 = capabilityRegistry[client];
52
+ if (skillsAgentRegistry[client])
53
+ continue;
38
54
  if (!detect(client).installed || (v2.implementation === "implemented" && (capability.mcpMode === "auto" || capability.mcpMode === "desktop")))
39
55
  continue;
40
56
  log(`${client}: status=${v2.status}, mcp=not_configured, skill=not_configured, invocation=${capability.invocation}, next_step=${v2.nextStep}`);
@@ -45,6 +61,20 @@ async function restoreCredential(store, client, previous) { if (previous)
45
61
  await store.save(previous);
46
62
  else
47
63
  await store.remove(client); }
64
+ async function configureMCP(client, bridge, exchange, a1Runner, bRunner, cRunner) { return client === "kiro" ? installKiroIDE(bridge) : client === "warp" ? installWarp(bridge) : isA1Client(client) ? installA1(client, bridge, exchange.credential, exchange.mcp_url, process.env, a1Runner) : isBClient(client) ? installB(client, bridge, process.env, bRunner) : isCClient(client) ? installC(client, bridge, process.env, cRunner) : configure(client, bridge); }
65
+ async function verifyMCP(client, a1Runner, bRunner, cRunner) { return client === "kiro" ? (await inspectKiroIDE()).state === "configured" : client === "warp" ? (await inspectWarp()).state === "configured" : isA1Client(client) ? (await inspectA1(client, process.env, a1Runner)).state === "configured" : isBClient(client) ? (await inspectB(client, process.env, bRunner)).state === "configured" : isCClient(client) ? (await inspectC(client, process.env, cRunner)).state === "configured" : isConfigured(client); }
66
+ async function rollbackMCP(client, result, cRunner) { if (client === "kiro")
67
+ await rollbackKiroIDE(result);
68
+ else if (client === "warp")
69
+ await rollbackWarp(result);
70
+ else if (isA1Client(client))
71
+ await rollbackA1(result);
72
+ else if (isBClient(client))
73
+ await rollbackB(result);
74
+ else if (isCClient(client))
75
+ await rollbackC(result, process.env, cRunner);
76
+ else
77
+ await rollback(result); }
48
78
  async function configureSkill(client, log) {
49
79
  try {
50
80
  const result = await installSkill(client);
@@ -58,6 +88,111 @@ async function configureSkill(client, log) {
58
88
  return "failed";
59
89
  }
60
90
  }
91
+ async function configureNativeSkill(client, detected, log, runner, verify) {
92
+ if (!skillsAgentRegistry[client])
93
+ return;
94
+ if (client === "kiro-cli" && (await inspectSkill("kiro")) !== "missing") {
95
+ log("kiro-cli: status=confirmation_required, mcp=not_configured, skill=confirmation_required, invocation=mcp_chat, next_step=Kiro IDE already has a local SandBase Skill; the Kiro CLI Skill installer was not run to avoid taking over the shared Kiro Skill path.");
96
+ return;
97
+ }
98
+ if (!detected.installed) {
99
+ log(`${client}: status=confirmation_required, mcp=not_configured, skill=confirmation_required, invocation=${nativeCapabilities[client].invocation}, next_step=${clientProfiles[client].label} is not locally detected; no Skills CLI invocation was attempted.`);
100
+ return;
101
+ }
102
+ const result = await installNativeSkill(client, runner, verify);
103
+ const status = result.status === "failed" ? "failed" : "confirmation_required";
104
+ log(`${client}: status=${status}, mcp=not_configured, skill=${result.status}, invocation=${nativeCapabilities[client].invocation}, next_step=${result.message}`);
105
+ }
106
+ async function prepareOpenClawSkill(detected, log, runner, verify) {
107
+ if (!detected.installed) {
108
+ log("openclaw: status=confirmation_required, mcp=not_configured, skill=confirmation_required, invocation=mcp_chat, next_step=OpenClaw is not locally detected; no SandBase configuration was attempted.");
109
+ return false;
110
+ }
111
+ const result = await installOpenClawSkill(runner, verify);
112
+ if (result.status === "installed" || result.status === "already_installed")
113
+ return true;
114
+ log(`openclaw: status=${result.status === "failed" ? "failed" : "confirmation_required"}, mcp=not_configured, skill=${result.status}, invocation=mcp_chat, next_step=${result.message}`);
115
+ return false;
116
+ }
117
+ async function connectOpenClaw(deps) {
118
+ const api = deps.api || new AuthorizationApi((process.env.SANDBASE_API_URL || "https://sandbase.ai").replace(/\/$/, ""));
119
+ const store = deps.store || new FileCredentialStore();
120
+ const log = deps.log || console.log;
121
+ const detect = deps.detect || detectClient;
122
+ if (!(await prepareOpenClawSkill(detect("openclaw"), log, deps.openClawRunner, deps.openClawReadbackVerifier)))
123
+ return;
124
+ const previous = await store.get("openclaw");
125
+ const { authorizationId, exchange } = await authorize(api, "openclaw", { open: deps.open || openBrowser, sleep, log, ...(deps.signal ? { signal: deps.signal } : {}) });
126
+ let bridgeResult;
127
+ try {
128
+ await store.save(recordFor("openclaw", exchange));
129
+ bridgeResult = await installBridge();
130
+ const mcp = await installOpenClawMcp(bridgeResult.path, deps.openClawRunner);
131
+ if (mcp.status !== "configured" && mcp.status !== "already_configured")
132
+ throw new Error(mcp.message);
133
+ log(`openclaw: status=configured, mcp=${mcp.status}, skill=already_installed, invocation=mcp_chat, next_step=Restart OpenClaw, then make a natural-language request that needs SandBase.`);
134
+ exchange.cleanup_token = "";
135
+ }
136
+ catch (error) {
137
+ if (bridgeResult)
138
+ await rollbackBridge(bridgeResult).catch(() => undefined);
139
+ await restoreCredential(store, "openclaw", previous).catch(() => undefined);
140
+ if (!(await compensate(api, authorizationId, exchange.cleanup_token)))
141
+ console.error("WARNING: automatic credential cleanup failed. Revoke the new CLI credential in SandBase Dashboard immediately.");
142
+ exchange.cleanup_token = "";
143
+ throw error;
144
+ }
145
+ }
146
+ async function connectDesktop(client, deps) {
147
+ const api = deps.api || new AuthorizationApi((process.env.SANDBASE_API_URL || "https://sandbase.ai").replace(/\/$/, ""));
148
+ const store = deps.store || new FileCredentialStore();
149
+ const log = deps.log || console.log;
150
+ const previous = await store.get(client);
151
+ const { authorizationId, exchange } = await authorize(api, client, { open: deps.open || openBrowser, sleep, log, ...(deps.signal ? { signal: deps.signal } : {}) });
152
+ let bridgeResult;
153
+ let identityResult;
154
+ try {
155
+ await store.save(recordFor(client, exchange));
156
+ bridgeResult = await installBridge();
157
+ identityResult = await writeDesktopIdentity(client);
158
+ log(`${client}: status=client_confirmation_required, credential=ready, bridge=ready, mcp_artifact=not_read_back, skill_artifact=not_read_back, next_step=${client === "cowork" ? "Download and verify both artifacts, then obtain explicit account/workspace administrator approval before import." : "Download the versioned artifacts from SandBase Dashboard and complete the client-specific import."} MCP and Skill are not yet verified.`);
159
+ exchange.cleanup_token = "";
160
+ }
161
+ catch (error) {
162
+ if (identityResult)
163
+ await rollbackDesktopIdentity(identityResult).catch(() => undefined);
164
+ if (bridgeResult)
165
+ await rollbackBridge(bridgeResult).catch(() => undefined);
166
+ await restoreCredential(store, client, previous).catch(() => undefined);
167
+ if (!(await compensate(api, authorizationId, exchange.cleanup_token)))
168
+ console.error("WARNING: automatic credential cleanup failed. Revoke the new CLI credential in SandBase Dashboard immediately.");
169
+ exchange.cleanup_token = "";
170
+ throw error;
171
+ }
172
+ }
173
+ async function connectPromptAssisted(client, deps) {
174
+ const api = deps.api || new AuthorizationApi((process.env.SANDBASE_API_URL || "https://sandbase.ai").replace(/\/$/, ""));
175
+ const store = deps.store || new FileCredentialStore();
176
+ const log = deps.log || console.log;
177
+ const previous = await store.get(client);
178
+ const { authorizationId, exchange } = await authorize(api, client, { open: deps.open || openBrowser, sleep, log, ...(deps.signal ? { signal: deps.signal } : {}) });
179
+ let bridgeResult;
180
+ try {
181
+ await store.save(recordFor(client, exchange));
182
+ bridgeResult = await installBridge();
183
+ log(`${client}: status=action_required, authorization=completed, credential=stored, bridge=ready, registration=registration_required, verification=real_client_matrix\nUse these generic stdio launcher fields in ${clientProfiles[client].label}'s existing MCP manager; no client settings were changed:\n${promptAssistedLauncher(client)}\nReload the client, read back the SandBase MCP server and tool list, then make one safe SandBase tool call. Until all three checks pass, status remains action_required.`);
184
+ exchange.cleanup_token = "";
185
+ }
186
+ catch (error) {
187
+ if (bridgeResult)
188
+ await rollbackBridge(bridgeResult).catch(() => undefined);
189
+ await restoreCredential(store, client, previous).catch(() => undefined);
190
+ if (!(await compensate(api, authorizationId, exchange.cleanup_token)))
191
+ console.error("WARNING: automatic credential cleanup failed. Revoke the new CLI credential in SandBase Dashboard immediately.");
192
+ exchange.cleanup_token = "";
193
+ throw error;
194
+ }
195
+ }
61
196
  async function connectOne(client, deps) {
62
197
  const api = deps.api || new AuthorizationApi((process.env.SANDBASE_API_URL || "https://sandbase.ai").replace(/\/$/, ""));
63
198
  const store = deps.store || new FileCredentialStore();
@@ -66,11 +201,35 @@ async function connectOne(client, deps) {
66
201
  const profile = clientProfiles[client];
67
202
  const capability = nativeCapabilities[client];
68
203
  const v2 = capabilityRegistry[client];
204
+ if (isPromptAssistedClient(client)) {
205
+ await connectPromptAssisted(client, deps);
206
+ return;
207
+ }
208
+ if (isDesktopClient(client)) {
209
+ await connectDesktop(client, deps);
210
+ return;
211
+ }
212
+ if (client === "openclaw") {
213
+ await connectOpenClaw(deps);
214
+ return;
215
+ }
216
+ if (skillsAgentRegistry[client]) {
217
+ await configureNativeSkill(client, detect(client), log, deps.skillsRunner, deps.skillsReadbackVerifier);
218
+ // Kiro has both a native Skill lifecycle and a persistent MCP adapter.
219
+ // Keep the two lifecycles independent, but do not skip its MCP setup.
220
+ if (!isBClient(client))
221
+ return;
222
+ }
69
223
  if (v2.implementation === "blocked") {
70
224
  log(`${client}: status=failed, mcp=not_configured, skill=not_configured, invocation=${capability.invocation}, next_step=${v2.nextStep}`);
71
225
  return;
72
226
  }
73
227
  if (capability.mcpMode === "manual" || capability.mcpMode === "none") {
228
+ const detected = detect(client);
229
+ if (skillsAgentRegistry[client]) {
230
+ await configureNativeSkill(client, detected, log, deps.skillsRunner, deps.skillsReadbackVerifier);
231
+ return;
232
+ }
74
233
  const v2 = capabilityRegistry[client];
75
234
  log(`${client}: status=${v2.status}, mcp=not_configured, skill=not_configured, invocation=${capability.invocation}, next_step=${v2.nextStep}`);
76
235
  return;
@@ -86,16 +245,25 @@ async function connectOne(client, deps) {
86
245
  const record = recordFor(client, exchange);
87
246
  await store.save(record);
88
247
  bridgeResult = await installBridge();
89
- configured = await configure(client, bridgeResult.path);
90
- if (profile.mode === "auto" && !(await isConfigured(client)))
248
+ configured = await configureMCP(client, bridgeResult.path, exchange, deps.a1Runner, deps.bRunner, deps.cRunner);
249
+ if (profile.mode === "auto" && !(await verifyMCP(client, deps.a1Runner, deps.bRunner, deps.cRunner)))
91
250
  throw new Error("Client configuration verification failed");
92
- log(successMessage(client, bridgeResult.path));
93
- await configureSkill(client, log);
251
+ if (client === "kiro") {
252
+ const skill = await installSkill("kiro");
253
+ if (skill.state !== "configured" && skill.state !== "already_configured")
254
+ throw new Error("Kiro IDE Skill installation was not verified");
255
+ log(`kiro: status=confirmation_required, mcp=configured, skill=${skill.state}, invocation=desktop_ui, next_step=Reload Kiro IDE, verify the SandBase server and tools, then complete one safe tool call.`);
256
+ }
257
+ else {
258
+ log(successMessage(client, bridgeResult.path));
259
+ if (!skillsAgentRegistry[client])
260
+ await configureSkill(client, log);
261
+ }
94
262
  exchange.cleanup_token = "";
95
263
  }
96
264
  catch (e) {
97
265
  if (configured)
98
- await rollback(configured).catch(() => undefined);
266
+ await rollbackMCP(client, configured, deps.cRunner).catch(() => undefined);
99
267
  if (bridgeResult)
100
268
  await rollbackBridge(bridgeResult).catch(() => undefined);
101
269
  await restoreCredential(store, client, previous).catch(() => undefined);
@@ -110,9 +278,19 @@ async function connectAuto(deps) {
110
278
  const store = deps.store || new FileCredentialStore();
111
279
  const log = deps.log || console.log;
112
280
  const detect = deps.detect || detectClient;
113
- const targets = plannedAutoClients(detect);
281
+ const targets = plannedAutoClients(detect).filter(client => client !== "openclaw");
282
+ const nativeSkillTargets = clients.filter(target => !!skillsAgentRegistry[target] && detect(target).installed);
283
+ // Native Skills are an independent local lifecycle: do not let their result
284
+ // change MCP authorization, configuration, or rollback decisions.
285
+ for (const target of nativeSkillTargets)
286
+ await configureNativeSkill(target, detect(target), log, deps.skillsRunner, deps.skillsReadbackVerifier);
287
+ // ClawHub Skill installation must succeed before OpenClaw joins the same
288
+ // one-time authorization transaction used by the other automatic clients.
289
+ const openClawReady = detect("openclaw").installed && await prepareOpenClawSkill(detect("openclaw"), log, deps.openClawRunner, deps.openClawReadbackVerifier);
290
+ if (openClawReady)
291
+ targets.push("openclaw");
114
292
  if (!targets.length) {
115
- log("No installed compatible clients support automatic configuration. Use --client <client> for manual or skill setup guidance.");
293
+ log("No installed compatible clients support automatic MCP configuration. Use --client <client> for manual or skill setup guidance.");
116
294
  logDetectedActionRequired(detect, log);
117
295
  return;
118
296
  }
@@ -127,15 +305,30 @@ async function connectAuto(deps) {
127
305
  try {
128
306
  const record = recordFor(client, exchange);
129
307
  await store.save(record);
130
- configured = await configure(client, bridgeResult.path);
131
- if (!(await isConfigured(client)))
132
- throw new Error("Client configuration verification failed");
133
- await configureSkill(client, log);
308
+ if (client === "openclaw") {
309
+ const mcp = await installOpenClawMcp(bridgeResult.path, deps.openClawRunner);
310
+ if (mcp.status !== "configured" && mcp.status !== "already_configured")
311
+ throw new Error(mcp.message);
312
+ log(`openclaw: status=configured, mcp=${mcp.status}, skill=already_installed, invocation=mcp_chat, next_step=Restart OpenClaw, then make a natural-language request that needs SandBase.`);
313
+ }
314
+ else {
315
+ configured = await configureMCP(client, bridgeResult.path, exchange, deps.a1Runner, deps.bRunner, deps.cRunner);
316
+ if (!(await verifyMCP(client, deps.a1Runner, deps.bRunner, deps.cRunner)))
317
+ throw new Error("Client configuration verification failed");
318
+ if (client === "kiro") {
319
+ const skill = await installSkill("kiro");
320
+ if (skill.state !== "configured" && skill.state !== "already_configured")
321
+ throw new Error("Kiro IDE Skill installation was not verified");
322
+ log(`kiro: status=confirmation_required, mcp=configured, skill=${skill.state}, invocation=desktop_ui, next_step=Reload Kiro IDE and verify server/tools plus one safe call.`);
323
+ }
324
+ else if (!skillsAgentRegistry[client])
325
+ await configureSkill(client, log);
326
+ }
134
327
  succeeded.push(client);
135
328
  }
136
329
  catch {
137
330
  if (configured)
138
- await rollback(configured).catch(() => undefined);
331
+ await rollbackMCP(client, configured, deps.cRunner).catch(() => undefined);
139
332
  await restoreCredential(store, client, previous).catch(() => undefined);
140
333
  failed.push(client);
141
334
  }
@@ -159,14 +352,278 @@ async function connectAuto(deps) {
159
352
  }
160
353
  export async function connect(client = "auto", deps = {}) { if (client === "auto")
161
354
  return connectAuto(deps); return connectOne(client, deps); }
162
- export async function doctor(client = "auto", store = new FileCredentialStore(), detect = detectClient) {
163
- const targets = client === "auto" ? plannedAutoClients(detect) : [client];
355
+ async function unregisterClaudeDesktop(store) {
356
+ const [artifactState, identityState, credential, artifactPrevious, identityPrevious] = await Promise.all([readClaudeDesktopArtifactState(), readDesktopIdentity("claude-desktop"), store.get("claude-desktop"), readOptional(claudeDesktopArtifactPath()), readOptional(desktopIdentityPath("claude-desktop"))]);
357
+ if (artifactState.ownership === "invalid")
358
+ throw new Error("Claude Desktop artifact ownership is unrecognized; no changes were made");
359
+ if (identityState === "invalid")
360
+ throw new Error("claude-desktop SandBase artifact identity is unrecognized; no changes were made");
361
+ if (credential && (credential.client !== "claude-desktop" || !credential.credential || !credential.credentialId || !credential.scope.includes("mcp:invoke") || !credential.mcpUrl))
362
+ throw new Error("Claude Desktop credential ownership is unrecognized; no changes were made");
363
+ try {
364
+ const removedArtifact = await removeClaudeDesktopArtifacts();
365
+ const removedIdentity = await removeDesktopIdentity("claude-desktop");
366
+ if (credential)
367
+ await store.remove("claude-desktop");
368
+ return removedArtifact || removedIdentity || !!credential;
369
+ }
370
+ catch (error) {
371
+ await Promise.allSettled([rollbackClaudeDesktopArtifacts({ path: claudeDesktopArtifactPath(), ...(artifactPrevious === undefined ? {} : { previous: artifactPrevious }), changed: true }), rollbackDesktopIdentity({ path: desktopIdentityPath("claude-desktop"), ...(identityPrevious === undefined ? {} : { previous: identityPrevious }), changed: true }), credential ? store.save(credential) : store.remove("claude-desktop")]);
372
+ throw error;
373
+ }
374
+ }
375
+ async function unregisterCowork(store) {
376
+ const [connector, identity, credential, connectorPrevious, identityPrevious] = await Promise.all([readCoworkState(), readDesktopIdentity("cowork"), store.get("cowork"), readOptional(coworkStatePath()), readOptional(desktopIdentityPath("cowork"))]);
377
+ if (connector.ownership === "invalid")
378
+ throw new Error("Cowork connector ownership is unrecognized; no changes were made");
379
+ if (identity === "invalid")
380
+ throw new Error("cowork SandBase artifact identity is unrecognized; no changes were made");
381
+ if (credential && (credential.client !== "cowork" || !credential.credential || !credential.credentialId || !credential.scope.includes("mcp:invoke") || !credential.mcpUrl))
382
+ throw new Error("Cowork credential ownership is unrecognized; no changes were made");
383
+ try {
384
+ const removedConnector = await removeCoworkState();
385
+ const removedIdentity = await removeDesktopIdentity("cowork");
386
+ if (credential)
387
+ await store.remove("cowork");
388
+ return removedConnector || removedIdentity || !!credential;
389
+ }
390
+ catch (error) {
391
+ await Promise.allSettled([rollbackCoworkState({ path: coworkStatePath(), ...(connectorPrevious === undefined ? {} : { previous: connectorPrevious }), changed: true }), rollbackDesktopIdentity({ path: desktopIdentityPath("cowork"), ...(identityPrevious === undefined ? {} : { previous: identityPrevious }), changed: true }), credential ? store.save(credential) : store.remove("cowork")]);
392
+ throw error;
393
+ }
394
+ }
395
+ function validOwnedCredential(client, credential) { return !credential || (credential.client === client && !!credential.credential && !!credential.credentialId && credential.scope.includes("mcp:invoke") && !!credential.mcpUrl); }
396
+ async function unregisterA1Transaction(client, store, runner) {
397
+ const [snapshot, credential] = await Promise.all([snapshotA1Unregister(client), store.get(client)]);
398
+ if (!snapshot)
399
+ return false;
400
+ if (!validOwnedCredential(client, credential))
401
+ throw new Error(`${client} credential ownership is unrecognized; no changes were made`);
402
+ try {
403
+ const removed = await unregisterA1(client, process.env, runner);
404
+ if (removed && credential)
405
+ await store.remove(client);
406
+ return removed;
407
+ }
408
+ catch (error) {
409
+ const restored = await Promise.allSettled([restoreA1Unregister(snapshot), credential ? store.save(credential) : store.remove(client)]);
410
+ if (restored.some(result => result.status === "rejected"))
411
+ throw new Error(`${error instanceof Error ? error.message : "A1 unregister failed"}; compensation was incomplete`);
412
+ throw error;
413
+ }
414
+ }
415
+ async function unregisterBTransaction(client, store, runner) {
416
+ const snapshot = await snapshotBUnregister(client);
417
+ if (!snapshot)
418
+ return false;
419
+ const credential = await store.get(client);
420
+ if (!validOwnedCredential(client, credential))
421
+ throw new Error(`${client} credential ownership is unrecognized; no changes were made`);
422
+ try {
423
+ const removed = await unregisterB(client, process.env, runner);
424
+ if (removed && credential)
425
+ await store.remove(client);
426
+ return removed;
427
+ }
428
+ catch (error) {
429
+ const restored = await Promise.allSettled([restoreBUnregister(snapshot), credential ? store.save(credential) : store.remove(client)]);
430
+ if (restored.some(result => result.status === "rejected"))
431
+ throw new Error(`${error instanceof Error ? error.message : "Module B unregister failed"}; compensation was incomplete`);
432
+ throw error;
433
+ }
434
+ }
435
+ async function unregisterCTransaction(client, store, runner) {
436
+ const snapshot = await snapshotCUnregister(client, process.env, runner);
437
+ if (!snapshot)
438
+ return false;
439
+ const credential = await store.get(client);
440
+ if (!validOwnedCredential(client, credential))
441
+ throw new Error(`${client} credential ownership is unrecognized; no changes were made`);
442
+ try {
443
+ const removed = await unregisterC(client, process.env, runner);
444
+ if (removed && credential)
445
+ await store.remove(client);
446
+ return removed;
447
+ }
448
+ catch (error) {
449
+ const restored = await Promise.allSettled([restoreCUnregister(snapshot, process.env, runner), credential ? store.save(credential) : store.remove(client)]);
450
+ if (restored.some(result => result.status === "rejected"))
451
+ throw new Error(`${error instanceof Error ? error.message : "Module C unregister failed"}; compensation was incomplete`);
452
+ throw error;
453
+ }
454
+ }
455
+ async function unregisterWarpTransaction(store) {
456
+ const snapshot = await snapshotWarpUnregister();
457
+ if (!snapshot)
458
+ return false;
459
+ const credential = await store.get("warp");
460
+ if (!validOwnedCredential("warp", credential))
461
+ throw new Error("warp credential ownership is unrecognized; no changes were made");
462
+ try {
463
+ const removed = await unregisterWarp();
464
+ if (removed && credential)
465
+ await store.remove("warp");
466
+ return removed;
467
+ }
468
+ catch (error) {
469
+ const restored = await Promise.allSettled([restoreWarpUnregister(snapshot), credential ? store.save(credential) : store.remove("warp")]);
470
+ if (restored.some(result => result.status === "rejected"))
471
+ throw new Error(`${error instanceof Error ? error.message : "Warp unregister failed"}; compensation was incomplete`);
472
+ throw error;
473
+ }
474
+ }
475
+ async function unregisterKiroIDETransaction(store) {
476
+ const mcp = await snapshotKiroIDEUnregister(), state = await inspectSkill("kiro"), path = skillPath("kiro"), meta = join(dirname(path), ".sandbase-managed.json");
477
+ if (state === "modified")
478
+ throw new Error("kiro Skill ownership is unrecognized; no changes were made");
479
+ const [skillPrevious, metaPrevious, credential] = await Promise.all([readOptional(path), readOptional(meta), store.get("kiro")]);
480
+ if (!validOwnedCredential("kiro", credential))
481
+ throw new Error("kiro credential ownership is unrecognized; no changes were made");
482
+ let mcpRemoved = false, skillRemoved = false;
483
+ try {
484
+ if (mcp) {
485
+ mcpRemoved = await unregisterKiroIDE();
486
+ if (mcpRemoved && credential)
487
+ await store.remove("kiro");
488
+ }
489
+ if (state === "installed")
490
+ skillRemoved = await removeSkill("kiro");
491
+ return { mcp: mcpRemoved, skill: skillRemoved };
492
+ }
493
+ catch (error) {
494
+ const work = [];
495
+ if (mcpRemoved && mcp)
496
+ work.push(restoreKiroIDEUnregister(mcp), credential ? store.save(credential) : store.remove("kiro"));
497
+ if (skillRemoved) {
498
+ work.push(skillPrevious === undefined ? restore(path) : atomicWrite(path, skillPrevious), metaPrevious === undefined ? restore(meta) : atomicWrite(meta, metaPrevious));
499
+ }
500
+ const settled = await Promise.allSettled(work);
501
+ if (settled.some(item => item.status === "rejected"))
502
+ throw new Error(`${error instanceof Error ? error.message : "Kiro IDE unregister failed"}; compensation was incomplete`);
503
+ throw error;
504
+ }
505
+ }
506
+ async function unregisterKiroTransaction(store, skillsRunner, skillsReadbackVerifier, bRunner) {
507
+ // Preflight every MCP-owned state before either lifecycle mutates anything.
508
+ // Skills CLI performs its own immutable-source ownership check immediately
509
+ // before remove, so an absent or third-party Skill is never deleted.
510
+ const ideSkill = await inspectSkill("kiro"), protectedPlan = { owned: false, result: { status: "confirmation_required", message: "Kiro IDE owns the shared local Skill path; Kiro CLI Skill removal was skipped." } };
511
+ const [snapshot, skillPlan] = await Promise.all([snapshotBUnregister("kiro-cli"), ideSkill === "missing" ? planNativeSkillRemoval("kiro-cli", skillsRunner, skillsReadbackVerifier) : Promise.resolve(protectedPlan)]);
512
+ const credential = snapshot ? await store.get("kiro-cli") : undefined;
513
+ if (!validOwnedCredential("kiro-cli", credential))
514
+ throw new Error("kiro-cli credential ownership is unrecognized; no changes were made");
515
+ let mcpRemoved = false;
516
+ let skill;
517
+ try {
518
+ if (snapshot) {
519
+ mcpRemoved = await unregisterB("kiro-cli", process.env, bRunner);
520
+ if (mcpRemoved && credential)
521
+ await store.remove("kiro-cli");
522
+ }
523
+ skill = await executeNativeSkillRemoval(skillPlan, skillsRunner, skillsReadbackVerifier);
524
+ if (skill.code === "readback_failed")
525
+ throw new Error(skill.message);
526
+ return { mcp: mcpRemoved ? "removed" : "missing", skill };
527
+ }
528
+ catch (error) {
529
+ const compensation = [];
530
+ if (mcpRemoved && snapshot)
531
+ compensation.push(restoreBUnregister(snapshot), credential ? store.save(credential) : store.remove("kiro-cli"));
532
+ // A removal readback failure is the only Skill failure that may occur after
533
+ // deletion. Reinstalling the same immutable source is its safe compensation.
534
+ if (skill?.code === "readback_failed")
535
+ compensation.push(installNativeSkill("kiro-cli", skillsRunner, skillsReadbackVerifier).then(result => {
536
+ if (result.status !== "installed" && result.status !== "already_installed")
537
+ throw new Error(result.message);
538
+ }));
539
+ const restored = await Promise.allSettled(compensation);
540
+ if (restored.some(result => result.status === "rejected"))
541
+ throw new Error(`${error instanceof Error ? error.message : "Kiro unregister failed"}; compensation was incomplete`);
542
+ throw error;
543
+ }
544
+ }
545
+ export async function doctor(client = "auto", store = new FileCredentialStore(), detect = detectClient, skillsRunner, skillsReadbackVerifier, openClawRunner, openClawReadbackVerifier, a1Runner, bRunner, cRunner) {
546
+ const targets = client === "auto" ? [...new Set([...plannedAutoClients(detect), ...clients.filter(target => !!skillsAgentRegistry[target] && detect(target).installed), ...(detect("openclaw").installed ? ["openclaw"] : [])])] : [client];
164
547
  if (!targets.length) {
165
548
  console.log("No installed compatible clients support automatic configuration.");
166
549
  return false;
167
550
  }
168
551
  let healthy = true;
169
552
  for (const target of targets) {
553
+ if (isDesktopClient(target)) {
554
+ const [credential, identity, bridge, artifact] = await Promise.all([store.get(target), readDesktopIdentity(target), inspectBridge(), target === "claude-desktop" ? readClaudeDesktopArtifactState() : readCoworkState()]);
555
+ const credentialReady = !!credential && validOwnedCredential(target, credential);
556
+ const artifactInvalid = artifact.ownership === "invalid" || artifact.mcp === "invalid" || artifact.skill === "invalid" || ("admin" in artifact && artifact.admin === "invalid");
557
+ const locallyHealthy = credentialReady && identity === "ready" && bridge === "ready" && !artifactInvalid;
558
+ const observable = (state) => state === "missing" ? "not_observable" : state;
559
+ const admin = target === "cowork" && "admin" in artifact ? artifact.admin === "required" ? "not_observable" : artifact.admin : "not_applicable";
560
+ console.log(`${target}: status=${locallyHealthy ? "client_confirmation_required" : "failed"}, credential=${credentialReady ? "present" : credential ? "invalid" : "missing"}, bridge_identity=${identity}, bridge_runtime=${bridge}, mcp_artifact=${observable(artifact.mcp)}, skill_artifact=${observable(artifact.skill)}, admin_confirmation=${admin}, verification=real_client_matrix, next_step=${locallyHealthy ? target === "cowork" ? "Complete the supported Cowork account/workspace administrator import and verify MCP and Skill in a fresh session; local client state is not observable." : "Import both artifacts, restart Claude Desktop, and verify MCP and Skill independently; local client state is not observable." : "Run sandbase connect for this client again or repair the managed bridge; invalid local state was left untouched."}`);
561
+ healthy = healthy && locallyHealthy;
562
+ continue;
563
+ }
564
+ if (target === "openclaw") {
565
+ const [credential, mcp, skill] = await Promise.all([store.get("openclaw"), inspectOpenClawMcp(openClawRunner), inspectOpenClawSkill(openClawRunner, openClawReadbackVerifier)]);
566
+ const mcpReady = mcp.status === "already_configured";
567
+ const skillReady = skill.status === "already_installed";
568
+ console.log(`openclaw: status=${credential && mcpReady && skillReady ? "configured" : "failed"}, credential=${credential ? "present" : "missing"}, mcp=${mcp.status}, skill=${skill.status}, invocation=mcp_chat, verification=read_back, next_step=${mcpReady && skillReady ? "Restart OpenClaw, then make a natural-language request that needs SandBase." : `${mcp.message} ${skill.message}`}`);
569
+ healthy = healthy && !!credential && mcpReady && skillReady;
570
+ continue;
571
+ }
572
+ if (isA1Client(target)) {
573
+ const inspection = await inspectA1(target, process.env, a1Runner);
574
+ const credential = await store.get(target);
575
+ const ready = inspection.state === "configured" && !!credential;
576
+ console.log(`${target}: status=${ready ? "configured" : inspection.state === "conflict" ? "confirmation_required" : "failed"}, credential=${credential ? "present" : "missing"}, mcp=${inspection.state}, verification=read_back, next_step=${inspection.detail}`);
577
+ healthy = healthy && detect(target).installed && ready;
578
+ continue;
579
+ }
580
+ if (target === "kiro") {
581
+ const [inspection, skill, credential, bridge] = await Promise.all([inspectKiroIDE(), inspectSkill("kiro"), store.get("kiro"), inspectBridge()]), local = inspection.state === "configured" && skill === "installed" && !!credential && bridge === "ready", status = local ? "confirmation_required" : inspection.state === "confirmation_required" || inspection.state === "conflict" || skill === "modified" ? "confirmation_required" : "failed";
582
+ console.log(`kiro: status=${status}, app=${detect(target).installed ? "detected" : "not_detected"}, credential=${credential ? "present" : "missing"}, bridge=${bridge}, mcp=${inspection.state}, skill=${skill}, ide_verification=not_observable, next_step=${local ? "Reload Kiro IDE, read back SandBase server/tools, and complete one safe tool call." : inspection.detail}`);
583
+ healthy = false;
584
+ continue;
585
+ }
586
+ if (isBClient(target)) {
587
+ const inspection = await inspectB(target, process.env, bRunner);
588
+ // A missing MCP registration has no credential ownership to inspect.
589
+ // This also keeps the native Kiro Skill lifecycle independent.
590
+ const credential = inspection.state === "configured" ? await store.get(target) : undefined;
591
+ if (target === "kiro-cli") {
592
+ const native = await inspectNativeSkill(target, skillsRunner, skillsReadbackVerifier);
593
+ const mcpReady = inspection.state === "configured" && !!credential;
594
+ const mcpMissing = inspection.state === "missing";
595
+ const skillReady = native.status === "already_installed";
596
+ const skillMissing = native.status === "confirmation_required";
597
+ const ready = (mcpReady || skillReady) && (mcpReady || mcpMissing) && (skillReady || skillMissing);
598
+ const status = ready ? "configured" : inspection.state === "conflict" || inspection.state === "confirmation_required" || native.status === "confirmation_required" ? "confirmation_required" : "failed";
599
+ console.log(`${target}: status=${status}, credential=${credential ? "present" : "missing"}, mcp=${mcpMissing ? "not_configured" : inspection.state}, skill=${native.status}, verification=read_back, next_step=${inspection.detail} ${native.message}`);
600
+ healthy = healthy && detect(target).installed && ready;
601
+ continue;
602
+ }
603
+ const ready = inspection.state === "configured" && !!credential;
604
+ console.log(`${target}: status=${ready ? "configured" : inspection.state === "conflict" || inspection.state === "confirmation_required" ? "confirmation_required" : "failed"}, credential=${credential ? "present" : "missing"}, mcp=${inspection.state}, verification=read_back, next_step=${inspection.detail}`);
605
+ healthy = healthy && detect(target).installed && ready;
606
+ continue;
607
+ }
608
+ if (isCClient(target)) {
609
+ const inspection = await inspectC(target, process.env, cRunner), credential = inspection.state === "configured" ? await store.get(target) : undefined, ready = inspection.state === "configured" && !!credential;
610
+ const legacy = target === "iflow-cli" ? ", lifecycle=legacy_vendor_discontinued_2026-04-17, real_client=post_release_user_validation" : "";
611
+ console.log(`${target}: status=${ready ? "configured" : inspection.state === "conflict" || inspection.state === "confirmation_required" ? "confirmation_required" : "failed"}, credential=${credential ? "present" : "missing"}, mcp=${inspection.state}, verification=read_back${legacy}, next_step=${inspection.detail}`);
612
+ healthy = healthy && detect(target).installed && ready;
613
+ continue;
614
+ }
615
+ if (target === "warp") {
616
+ const inspection = await inspectWarp(), credential = inspection.state === "configured" ? await store.get(target) : undefined, staged = inspection.state === "configured" && !!credential;
617
+ console.log(`warp: status=${staged ? "confirmation_required" : inspection.state === "confirmation_required" || inspection.state === "conflict" ? "confirmation_required" : "failed"}, credential=${credential ? "present" : "missing"}, mcp=${inspection.state}, approval=not_observable, verification=read_back, next_step=${staged ? "Use /agent-add-mcp in Warp, approve SandBase, then inspect the MCP server and tools before treating it as connected." : inspection.detail}`);
618
+ healthy = false;
619
+ continue;
620
+ }
621
+ if (skillsAgentRegistry[target]) {
622
+ const native = await inspectNativeSkill(target, skillsRunner, skillsReadbackVerifier);
623
+ console.log(`${target}: status=${native.status === "failed" ? "failed" : "confirmation_required"}, mcp=not_configured, skill=${native.status}, invocation=${nativeCapabilities[target].invocation}, verification=read_only_probe, next_step=${native.message}`);
624
+ healthy = healthy && native.status === "already_installed";
625
+ continue;
626
+ }
170
627
  const credential = await store.get(target);
171
628
  const profile = clientProfiles[target];
172
629
  const configured = profile.mode === "auto" ? await isConfigured(target) : !!credential;
@@ -181,13 +638,61 @@ export async function doctor(client = "auto", store = new FileCredentialStore(),
181
638
  }
182
639
  return healthy;
183
640
  }
184
- export async function unregister(client = "auto", store = new FileCredentialStore(), detect = detectClient) {
185
- const targets = client === "auto" ? plannedAutoClients(detect) : [client];
641
+ export async function unregister(client = "auto", store = new FileCredentialStore(), detect = detectClient, skillsRunner, skillsReadbackVerifier, openClawRunner, openClawReadbackVerifier, a1Runner, bRunner, cRunner) {
642
+ const targets = client === "auto" ? [...new Set([...plannedAutoClients(detect), ...clients.filter(target => !!skillsAgentRegistry[target] && detect(target).installed), ...(detect("openclaw").installed ? ["openclaw"] : [])])] : [client];
186
643
  if (!targets.length) {
187
644
  console.log("No installed compatible clients support automatic configuration.");
188
645
  return;
189
646
  }
190
647
  for (const target of targets) {
648
+ if (isDesktopClient(target)) {
649
+ const removed = target === "claude-desktop" ? await unregisterClaudeDesktop(store) : await unregisterCowork(store);
650
+ console.log(`Removed local SandBase bridge identity for ${target}.${removed ? "" : " No managed identity was changed."} Desktop product settings were left untouched; revoke the server credential in SandBase Dashboard if it is no longer needed.`);
651
+ continue;
652
+ }
653
+ if (target === "openclaw") {
654
+ const mcp = await removeOpenClawMcp(openClawRunner);
655
+ const skill = await removeOpenClawSkill(openClawRunner, openClawReadbackVerifier);
656
+ if (mcp.status === "removed" || mcp.status === "missing")
657
+ await store.remove("openclaw");
658
+ console.log(`openclaw: mcp=${mcp.status}, skill=${skill.status}, next_step=${mcp.message} ${skill.message}`);
659
+ continue;
660
+ }
661
+ if (isA1Client(target)) {
662
+ const removed = await unregisterA1Transaction(target, store, a1Runner);
663
+ console.log(`${target}: status=${removed ? "removed" : "confirmation_required"}, next_step=${removed ? "Managed SandBase registration was removed. The shared managed bridge was retained for other clients." : "No SandBase-owned registration was found; credential, bridge, and third-party configuration were left untouched."}`);
664
+ continue;
665
+ }
666
+ if (target === "kiro-cli") {
667
+ const result = await unregisterKiroTransaction(store, skillsRunner, skillsReadbackVerifier, bRunner);
668
+ console.log(`${target}: mcp=${result.mcp}, skill=${result.skill.status}, next_step=${result.mcp === "removed" ? "Managed persistent SandBase registration was removed; the shared bridge was retained." : "No SandBase-owned MCP registration was found."} ${result.skill.message}`);
669
+ continue;
670
+ }
671
+ if (isBClient(target)) {
672
+ const removed = await unregisterBTransaction(target, store, bRunner);
673
+ console.log(`${target}: status=${removed ? "removed" : "confirmation_required"}, next_step=${removed ? "Managed persistent SandBase registration was removed; the shared bridge was retained." : "No owned registration was found; all local state was left untouched."}`);
674
+ continue;
675
+ }
676
+ if (isCClient(target)) {
677
+ const removed = await unregisterCTransaction(target, store, cRunner);
678
+ console.log(`${target}: status=${removed ? "removed" : "confirmation_required"}, next_step=${removed ? `Managed ${target === "iflow-cli" ? "legacy user-scope " : "global "}SandBase registration was removed; the shared bridge was retained.` : "No owned registration was found; all local state was left untouched."}`);
679
+ continue;
680
+ }
681
+ if (target === "warp") {
682
+ const removed = await unregisterWarpTransaction(store);
683
+ console.log(`warp: status=${removed ? "removed" : "confirmation_required"}, next_step=${removed ? "Managed Warp user registration was removed; project files and the shared bridge were retained." : "No SandBase-owned Warp registration was found; all local state was left untouched."}`);
684
+ continue;
685
+ }
686
+ if (target === "kiro") {
687
+ const removed = await unregisterKiroIDETransaction(store);
688
+ console.log(`kiro: mcp=${removed.mcp ? "removed" : "missing"}, skill=${removed.skill ? "removed" : "missing"}, next_step=Only Kiro IDE-owned state was changed; kiro-cli credentials and configuration were retained.`);
689
+ continue;
690
+ }
691
+ if (skillsAgentRegistry[target]) {
692
+ const result = await removeNativeSkill(target, skillsRunner, skillsReadbackVerifier);
693
+ console.log(`${target}: mcp=not_configured, skill=${result.status}, next_step=${result.message}`);
694
+ continue;
695
+ }
191
696
  if (capabilityRegistry[target].implementation === "blocked") {
192
697
  console.log(`${target}: status=failed, next_step=${capabilityRegistry[target].nextStep}`);
193
698
  continue;