@supabeast/mcp 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.mjs CHANGED
@@ -1,11 +1,15 @@
1
1
  import os from "node:os";
2
2
  import path from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ import { cliRequest, runBrowserFlow } from "./api.mjs";
5
+ import { openBrowser, startLoopbackCallbackServer } from "./browser.mjs";
3
6
  import { inspectLocalState, probeRemoteMcp } from "./check.mjs";
4
7
  import {
5
8
  applyClientConfig,
6
9
  detectInstalledClients,
7
10
  renderManualSnippets,
8
11
  resolveClientTarget,
12
+ resolveClientTargets,
9
13
  } from "./clients.mjs";
10
14
  import {
11
15
  buildCursorDeeplink,
@@ -13,30 +17,82 @@ import {
13
17
  DEFAULT_MCP_URL,
14
18
  PACKAGE_VERSION,
15
19
  SUPPORTED_CLIENTS,
20
+ resolveAppOrigin,
16
21
  validateMcpUrl,
17
22
  } from "./constants.mjs";
23
+ import {
24
+ clearCredential,
25
+ loadCredential,
26
+ resolveCredentialsPath,
27
+ saveCredential,
28
+ } from "./credentials.mjs";
29
+ import { detectLocalProject } from "./local-project.mjs";
30
+ import { createTerminalPrompter, isInteractiveTerminal } from "./prompt.mjs";
18
31
  import { installSkillFiles } from "./skill.mjs";
19
32
 
20
- const USAGE = `SupaBeast Remote MCP & Companion Skill Installer (v${PACKAGE_VERSION})
33
+ export {
34
+ DEFAULT_MCP_URL,
35
+ PACKAGE_VERSION,
36
+ SUPPORTED_CLIENTS,
37
+ applyClientConfig,
38
+ detectInstalledClients,
39
+ inspectLocalState,
40
+ probeRemoteMcp,
41
+ renderManualSnippets,
42
+ resolveAppOrigin,
43
+ resolveClientTarget,
44
+ resolveClientTargets,
45
+ validateMcpUrl,
46
+ };
47
+
48
+ const CLOUD_COMMANDS = new Set(["init", "login", "logout", "status", "connect"]);
49
+
50
+ const USAGE = `SupaBeast Remote MCP & CLI Onboarding (v${PACKAGE_VERSION})
21
51
 
22
52
  Usage:
23
- npx @supabeast/mcp [init|check] [options]
24
- npx supabeast [init|check] [options]
53
+ npx @supabeast/mcp [command] [options]
54
+ npx supabeast [command] [options]
55
+
56
+ Commands:
57
+ init Sign in, connect Supabase, link GitHub, and configure local agents (default)
58
+ login Sign in to SupaBeast via browser PKCE authorization
59
+ logout Revoke and clear stored CLI credentials
60
+ status Show signed-in workspace, Supabase connection, environments, and Remote MCP status
61
+ connect [target] Connect Supabase (\`supabase\`) or GitHub (\`github\`) to your workspace
62
+ check Verify Remote MCP endpoint discovery and local client configs
63
+ help Show this help message
25
64
 
26
65
  Options:
27
- -c, --client <list> Target clients (claude, cursor, codex, opencode, all)
28
- --scope <scope> Config scope: user (default) or project
66
+ -c, --client <list> Target clients (claude, cursor, codex, gemini, antigravity, t3, opencode, all)
67
+ -s, --scope <scope> Config scope: user (default) or project
68
+ --url <url> Override Remote MCP URL (default: ${DEFAULT_MCP_URL})
69
+ --setup Run cloud account/project setup even in non-interactive mode
70
+ --local-only Configure local coding agents and SKILL.md only (skip cloud login/setup)
71
+ --open Open the default browser automatically without waiting for Enter
72
+ --no-browser Print authorization URL instead of launching a browser window
73
+ --project <ref> Supabase project ref (or name) to connect
74
+ --repo <slug> GitHub repository (owner/repo) to link
75
+ --branch <name> Deployed Git branch running against your connected database (default: repo default)
76
+ --root <path> Optional subdirectory path inside a monorepo (default: repo root)
77
+ --skip-github Skip optional GitHub App repository connection during init
78
+ -y, --yes Accept detected defaults without extra confirmation prompts
29
79
  --skill-only Install only SKILL.md without editing MCP config files
30
80
  --mcp-only Configure only Remote MCP without installing SKILL.md
31
81
  --check Verify Remote MCP endpoint reachability and local setup
32
82
  --dry-run Preview planned file changes without writing to disk
33
- --url <url> Override Remote MCP URL (default: ${DEFAULT_MCP_URL})
34
83
  --json Emit machine-readable JSON output
35
84
  -v, --version Print version
36
85
  -h, --help Show this help message
37
86
  `;
38
87
 
39
- function parseClientsFlag(rawValue, set) {
88
+ const CLIENT_ALIASES = {
89
+ "gemini-cli": "gemini",
90
+ agy: "antigravity",
91
+ "t3-code": "t3",
92
+ t3code: "t3",
93
+ };
94
+
95
+ function parseClientsFlag(rawValue, opts) {
40
96
  const parts = rawValue
41
97
  .split(",")
42
98
  .map((p) => p.trim().toLowerCase())
@@ -45,10 +101,13 @@ function parseClientsFlag(rawValue, set) {
45
101
  throw Error("--client requires at least one client name");
46
102
  }
47
103
  for (const part of parts) {
48
- if (part === "all") {
49
- for (const id of SUPPORTED_CLIENTS) set.add(id);
50
- } else if (SUPPORTED_CLIENTS.includes(part)) {
51
- set.add(part);
104
+ const normalized = CLIENT_ALIASES[part] ?? part;
105
+ if (normalized === "all") {
106
+ opts.selectedAll = true;
107
+ for (const id of SUPPORTED_CLIENTS) opts.clients.add(id);
108
+ } else if (SUPPORTED_CLIENTS.includes(normalized)) {
109
+ opts.explicitNonAllClients.add(normalized);
110
+ opts.clients.add(normalized);
52
111
  } else {
53
112
  throw Error(
54
113
  `Unknown client "${part}". Supported clients: ${SUPPORTED_CLIENTS.join(", ")}, all`,
@@ -57,12 +116,47 @@ function parseClientsFlag(rawValue, set) {
57
116
  }
58
117
  }
59
118
 
119
+ function readNextValue(argv, index, flagName) {
120
+ const value = argv[index + 1];
121
+ if (value === undefined) {
122
+ throw Error(`${flagName} requires a value`);
123
+ }
124
+ return value;
125
+ }
126
+
127
+ function matchKeyValueFlag(arg, argv, index, names) {
128
+ for (const name of names) {
129
+ if (arg === name) {
130
+ return { matched: true, value: readNextValue(argv, index, name), advance: 1 };
131
+ }
132
+ if (arg.startsWith(`${name}=`)) {
133
+ return { matched: true, value: arg.slice(name.length + 1), advance: 0 };
134
+ }
135
+ }
136
+ return { matched: false };
137
+ }
138
+
60
139
  /** Parse CLI argv tokens into normalized options. */
61
140
  export function parseCliArgs(argv) {
62
141
  const opts = {
63
142
  command: "init",
64
143
  clients: new Set(),
144
+ explicitNonAllClients: new Set(),
145
+ selectedAll: false,
65
146
  scope: "user",
147
+ url: DEFAULT_MCP_URL,
148
+ connectTarget: null,
149
+ setup: false,
150
+ localOnly: false,
151
+ open: false,
152
+ noBrowser: false,
153
+ project: null,
154
+ repo: null,
155
+ branch: null,
156
+ fixBranch: null,
157
+ root: null,
158
+ skipGithub: false,
159
+ yes: false,
66
160
  skillOnly: false,
67
161
  mcpOnly: false,
68
162
  check: false,
@@ -70,7 +164,6 @@ export function parseCliArgs(argv) {
70
164
  json: false,
71
165
  help: false,
72
166
  version: false,
73
- url: DEFAULT_MCP_URL,
74
167
  };
75
168
  let seenCommand = false;
76
169
 
@@ -78,57 +171,151 @@ export function parseCliArgs(argv) {
78
171
  const arg = argv[i];
79
172
  if (arg === "-h" || arg === "--help") {
80
173
  opts.help = true;
81
- } else if (arg === "-v" || arg === "--version") {
174
+ continue;
175
+ }
176
+ if (arg === "-v" || arg === "--version") {
82
177
  opts.version = true;
83
- } else if (arg === "--skill-only") {
178
+ continue;
179
+ }
180
+ if (arg === "-y" || arg === "--yes") {
181
+ opts.yes = true;
182
+ continue;
183
+ }
184
+ if (arg === "--skill-only") {
84
185
  opts.skillOnly = true;
85
- } else if (arg === "--mcp-only") {
186
+ continue;
187
+ }
188
+ if (arg === "--mcp-only") {
86
189
  opts.mcpOnly = true;
87
- } else if (arg === "--check") {
190
+ continue;
191
+ }
192
+ if (arg === "--check") {
88
193
  opts.check = true;
89
- } else if (arg === "--dry-run") {
194
+ opts.command = "check";
195
+ seenCommand = true;
196
+ continue;
197
+ }
198
+ if (arg === "--dry-run") {
90
199
  opts.dryRun = true;
91
- } else if (arg === "--json") {
200
+ continue;
201
+ }
202
+ if (arg === "--json") {
92
203
  opts.json = true;
93
- } else if (arg === "-c" || arg === "--client") {
94
- const value = argv[++i];
95
- if (value === undefined) throw Error(`${arg} requires a value`);
96
- parseClientsFlag(value, opts.clients);
97
- } else if (arg.startsWith("--client=")) {
98
- parseClientsFlag(arg.slice("--client=".length), opts.clients);
99
- } else if (arg === "--scope") {
100
- const value = argv[++i];
101
- if (value !== "user" && value !== "project") {
102
- throw Error("--scope must be 'user' or 'project'");
103
- }
104
- opts.scope = value;
105
- } else if (arg.startsWith("--scope=")) {
106
- const value = arg.slice("--scope=".length);
107
- if (value !== "user" && value !== "project") {
204
+ continue;
205
+ }
206
+ if (arg === "--setup") {
207
+ opts.setup = true;
208
+ continue;
209
+ }
210
+ if (arg === "--local-only") {
211
+ opts.localOnly = true;
212
+ continue;
213
+ }
214
+ if (arg === "--open") {
215
+ opts.open = true;
216
+ continue;
217
+ }
218
+ if (arg === "--no-browser") {
219
+ opts.noBrowser = true;
220
+ continue;
221
+ }
222
+ if (arg === "--skip-github") {
223
+ opts.skipGithub = true;
224
+ continue;
225
+ }
226
+
227
+ const clientFlag = matchKeyValueFlag(arg, argv, i, ["-c", "--client"]);
228
+ if (clientFlag.matched) {
229
+ parseClientsFlag(clientFlag.value, opts);
230
+ i += clientFlag.advance;
231
+ continue;
232
+ }
233
+
234
+ const scopeFlag = matchKeyValueFlag(arg, argv, i, ["-s", "--scope"]);
235
+ if (scopeFlag.matched) {
236
+ if (scopeFlag.value !== "user" && scopeFlag.value !== "project") {
108
237
  throw Error("--scope must be 'user' or 'project'");
109
238
  }
110
- opts.scope = value;
111
- } else if (arg === "--url") {
112
- const value = argv[++i];
113
- if (value === undefined) throw Error("--url requires a value");
114
- opts.url = validateMcpUrl(value);
115
- } else if (arg.startsWith("--url=")) {
116
- opts.url = validateMcpUrl(arg.slice("--url=".length));
117
- } else if (arg.startsWith("-")) {
239
+ opts.scope = scopeFlag.value;
240
+ i += scopeFlag.advance;
241
+ continue;
242
+ }
243
+
244
+ const urlFlag = matchKeyValueFlag(arg, argv, i, ["--url"]);
245
+ if (urlFlag.matched) {
246
+ opts.url = validateMcpUrl(urlFlag.value);
247
+ i += urlFlag.advance;
248
+ continue;
249
+ }
250
+
251
+ const projectFlag = matchKeyValueFlag(arg, argv, i, ["--project"]);
252
+ if (projectFlag.matched) {
253
+ opts.project = projectFlag.value;
254
+ i += projectFlag.advance;
255
+ continue;
256
+ }
257
+
258
+ const repoFlag = matchKeyValueFlag(arg, argv, i, ["--repo"]);
259
+ if (repoFlag.matched) {
260
+ opts.repo = repoFlag.value;
261
+ i += repoFlag.advance;
262
+ continue;
263
+ }
264
+
265
+ const branchFlag = matchKeyValueFlag(arg, argv, i, ["--branch"]);
266
+ if (branchFlag.matched) {
267
+ opts.branch = branchFlag.value;
268
+ i += branchFlag.advance;
269
+ continue;
270
+ }
271
+
272
+ const fixBranchFlag = matchKeyValueFlag(arg, argv, i, ["--fix-branch"]);
273
+ if (fixBranchFlag.matched) {
274
+ opts.fixBranch = fixBranchFlag.value;
275
+ i += fixBranchFlag.advance;
276
+ continue;
277
+ }
278
+
279
+ const rootFlag = matchKeyValueFlag(arg, argv, i, ["--root"]);
280
+ if (rootFlag.matched) {
281
+ opts.root = rootFlag.value;
282
+ i += rootFlag.advance;
283
+ continue;
284
+ }
285
+
286
+ if (arg.startsWith("-")) {
118
287
  throw Error(`Unknown option: ${arg}`);
119
- } else if (!seenCommand && (arg === "init" || arg === "check" || arg === "help")) {
288
+ }
289
+
290
+ if (!seenCommand && (CLOUD_COMMANDS.has(arg) || arg === "check" || arg === "help")) {
120
291
  seenCommand = true;
121
292
  opts.command = arg;
122
293
  if (arg === "check") opts.check = true;
123
294
  if (arg === "help") opts.help = true;
124
- } else {
125
- throw Error(`Unexpected argument: ${arg}`);
295
+ continue;
296
+ }
297
+
298
+ if (
299
+ opts.command === "connect" &&
300
+ !opts.connectTarget &&
301
+ (arg === "supabase" || arg === "github")
302
+ ) {
303
+ opts.connectTarget = arg;
304
+ continue;
126
305
  }
306
+
307
+ throw Error(`Unexpected argument: ${arg}`);
127
308
  }
128
309
 
129
310
  if (opts.skillOnly && opts.mcpOnly) {
130
311
  throw Error("Cannot combine --skill-only and --mcp-only");
131
312
  }
313
+ if (opts.setup && opts.localOnly) {
314
+ throw Error("Cannot combine --setup and --local-only");
315
+ }
316
+ if (opts.open && opts.noBrowser) {
317
+ throw Error("Cannot combine --open and --no-browser");
318
+ }
132
319
 
133
320
  return opts;
134
321
  }
@@ -138,19 +325,27 @@ function formatStatusLabel(status) {
138
325
  return status;
139
326
  }
140
327
 
141
- function formatCheckText(remote, local) {
328
+ function formatCheckText(remote, local, cred) {
142
329
  const lines = [`SupaBeast Remote MCP Check (${remote.endpoint})`, ""];
143
330
  for (const item of remote.checks) {
144
331
  const marker = item.ok ? "[OK]" : "[FAIL]";
145
332
  lines.push(`${marker} ${item.label}: ${item.detail}`);
146
333
  }
334
+ lines.push("");
335
+ if (cred) {
336
+ const who = cred.user?.github_login ? ` as @${cred.user.github_login}` : "";
337
+ lines.push(`CLI session: signed in${who} (${cred.workspace?.name ?? "Personal"})`);
338
+ } else {
339
+ lines.push("CLI session: not signed in (run `npx supabeast login`)");
340
+ }
147
341
  lines.push("", "Local client configurations:");
148
342
  const configured = local.clients.filter((c) => c.configStatus !== "missing");
149
343
  if (configured.length === 0) {
150
344
  lines.push(" (none configured yet — run `npx @supabeast/mcp` or pass `--client <name>`)");
151
345
  } else {
152
346
  for (const c of configured) {
153
- lines.push(` [${c.configStatus}] ${c.label} (${c.scope}): ${c.configPath}`);
347
+ const authNote = c.authMode === "bearer" ? ", bearer" : "";
348
+ lines.push(` [${c.configStatus}${authNote}] ${c.label} (${c.scope}): ${c.configPath}`);
154
349
  }
155
350
  }
156
351
  lines.push("", "Installed SKILL.md paths:");
@@ -165,6 +360,14 @@ function formatCheckText(remote, local) {
165
360
  return lines.join("\n") + "\n";
166
361
  }
167
362
 
363
+ function formatGitHubSummary(gh) {
364
+ if (!gh?.repository) return "";
365
+ const branch = gh.branch ?? "main";
366
+ const root = gh.root;
367
+ const rootNote = root ? `, root: ${root}` : "";
368
+ return `${gh.repository} (branch: ${branch}${rootNote})`;
369
+ }
370
+
168
371
  function formatInitText(result) {
169
372
  const lines = [
170
373
  `SupaBeast Remote MCP Setup (${result.dryRun ? "dry run" : "configured"})`,
@@ -172,9 +375,25 @@ function formatInitText(result) {
172
375
  "",
173
376
  ];
174
377
 
378
+ if (result.cloud) {
379
+ lines.push("Cloud workspace:");
380
+ lines.push(
381
+ ` Account: ${result.cloud.user?.github_login ? `@${result.cloud.user.github_login}` : "signed in"} (${result.cloud.workspace?.name ?? "Personal"})`,
382
+ );
383
+ lines.push(
384
+ ` Supabase: ${result.cloud.supabase.project_name} (${result.cloud.supabase.project_ref}) — Remote MCP: ${result.cloud.supabase.mcp_enabled ? "enabled" : "disabled"}`,
385
+ );
386
+ if (result.cloud.github?.repository) {
387
+ lines.push(` GitHub: ${formatGitHubSummary(result.cloud.github)}`);
388
+ } else {
389
+ lines.push(" GitHub: skipped (link later with `npx supabeast connect github`)");
390
+ }
391
+ lines.push("");
392
+ }
393
+
175
394
  if (result.autoDetectedNone) {
176
395
  lines.push(
177
- "No installed Claude Code, Cursor, Codex CLI, or OpenCode config directory was auto-detected.",
396
+ "No installed Claude Code, Cursor, Codex CLI, Gemini CLI, Antigravity, T3 Code, or OpenCode config directory was auto-detected.",
178
397
  );
179
398
  if (result.skills.length > 0) {
180
399
  lines.push("Companion skill:");
@@ -188,8 +407,9 @@ function formatInitText(result) {
188
407
  "Connect your client using one of these snippets (or re-run with --client <name>):",
189
408
  ` Claude Code: ${snippets.claude}`,
190
409
  ` Codex CLI: ${snippets.codex}`,
410
+ ` Gemini CLI: ${snippets.gemini}`,
191
411
  ` Cursor URL: ${buildCursorDeeplink(result.endpoint)}`,
192
- ` T3 Code URL: ${snippets.t3}`,
412
+ ` T3 Code URL: ${result.endpoint} (or run with --client t3)`,
193
413
  );
194
414
  } else {
195
415
  if (result.configs.length > 0) {
@@ -197,8 +417,11 @@ function formatInitText(result) {
197
417
  for (const cfg of result.configs) {
198
418
  if (cfg.status === "error") {
199
419
  lines.push(` [error] ${cfg.label}: ${cfg.path} (${cfg.reason})`);
420
+ } else if (cfg.status === "skipped") {
421
+ lines.push(` [skipped] ${cfg.label}: ${cfg.reason}`);
200
422
  } else {
201
- lines.push(` [${formatStatusLabel(cfg.status)}] ${cfg.label}: ${cfg.path}`);
423
+ const authNote = cfg.authMode === "bearer" ? " (30-day Bearer token configured)" : "";
424
+ lines.push(` [${formatStatusLabel(cfg.status)}] ${cfg.label}: ${cfg.path}${authNote}`);
202
425
  }
203
426
  }
204
427
  lines.push("");
@@ -215,12 +438,50 @@ function formatInitText(result) {
215
438
  }
216
439
  }
217
440
 
218
- lines.push(
219
- "Next steps:",
220
- " 1. Connect your Supabase project at https://app.supabeast.com (if you have not already).",
221
- " 2. Open or restart your coding agent and complete the browser OAuth sign-in prompt.",
222
- ' 3. Ask your agent: "List my top production hotspots with SupaBeast"',
441
+ const activeConfigs = result.configs.filter(
442
+ (c) => c.status !== "skipped" && c.status !== "error",
443
+ );
444
+ const hasBearerConfig = activeConfigs.some((c) => c.authMode === "bearer");
445
+ const hasOAuthConfig = activeConfigs.some((c) => c.authMode !== "bearer");
446
+ const hasUnauthedHeadless = activeConfigs.some(
447
+ (c) => (c.clientId === "t3" || c.clientId === "antigravity") && c.authMode !== "bearer",
223
448
  );
449
+
450
+ if (result.cloud) {
451
+ if (hasBearerConfig && !hasOAuthConfig) {
452
+ lines.push(
453
+ "Next steps:",
454
+ " 1. Start a new thread/chat in your coding agent (a 30-day read-only Bearer token is configured; revoke anytime at https://app.supabeast.com/connections).",
455
+ ' 2. Ask your agent: "List my top production hotspots with SupaBeast"',
456
+ );
457
+ } else if (hasBearerConfig) {
458
+ lines.push(
459
+ "Next steps:",
460
+ " 1. Start a new thread/chat for Bearer-configured agents (T3 Code / Antigravity) and complete the browser OAuth prompt if asked for OAuth agents.",
461
+ ' 2. Ask your agent: "List my top production hotspots with SupaBeast"',
462
+ );
463
+ } else {
464
+ lines.push(
465
+ "Next steps:",
466
+ " 1. Open or restart your coding agent and complete the browser OAuth prompt if asked.",
467
+ ' 2. Ask your agent: "List my top production hotspots with SupaBeast"',
468
+ );
469
+ }
470
+ } else if (hasUnauthedHeadless) {
471
+ lines.push(
472
+ "Next steps:",
473
+ " 1. Connect your Supabase project at https://app.supabeast.com (if you have not already).",
474
+ " 2. Run `npx @supabeast/mcp` (without --local-only) to auto-provision a 30-day Bearer token for T3 Code / Antigravity, or generate one at https://app.supabeast.com/connections.",
475
+ ' 3. Ask your agent: "List my top production hotspots with SupaBeast"',
476
+ );
477
+ } else {
478
+ lines.push(
479
+ "Next steps:",
480
+ " 1. Connect your Supabase project at https://app.supabeast.com (if you have not already).",
481
+ " 2. Open or restart your coding agent and complete the browser OAuth sign-in prompt.",
482
+ ' 3. Ask your agent: "List my top production hotspots with SupaBeast"',
483
+ );
484
+ }
224
485
  if (result.hasErrors) {
225
486
  lines.push(
226
487
  "",
@@ -230,16 +491,554 @@ function formatInitText(result) {
230
491
  return lines.join("\n") + "\n";
231
492
  }
232
493
 
494
+ function shouldRunCloudSetup(args, interactive) {
495
+ if (args.localOnly || args.mcpOnly || args.skillOnly || args.dryRun) {
496
+ return false;
497
+ }
498
+ if (args.setup || args.project || args.repo || args.skipGithub) {
499
+ return true;
500
+ }
501
+ if (args.json) {
502
+ return false;
503
+ }
504
+ return Boolean(interactive);
505
+ }
506
+
507
+ function buildCredentialOptions(ctx) {
508
+ return {
509
+ env: ctx.env,
510
+ homeDir: ctx.homeDir,
511
+ platform: ctx.platform,
512
+ pathApi: ctx.pathApi,
513
+ now: ctx.now,
514
+ };
515
+ }
516
+
517
+ function buildFlowOptions(ctx, args) {
518
+ return {
519
+ appOrigin: ctx.appOrigin,
520
+ noBrowser: args.noBrowser,
521
+ openImmediately: Boolean(args.open),
522
+ interactive: ctx.interactive,
523
+ stdin: ctx.stdin,
524
+ env: ctx.env,
525
+ platform: ctx.platform,
526
+ fetchImpl: ctx.fetchImpl,
527
+ openBrowserImpl: ctx.openBrowserImpl,
528
+ startCallbackServerImpl: ctx.startCallbackServerImpl,
529
+ stdout: ctx.stdout,
530
+ pollIntervalMs: ctx.pollIntervalMs,
531
+ timeoutMs: ctx.timeoutMs,
532
+ json: args.json,
533
+ };
534
+ }
535
+
536
+ async function fetchStatus(ctx, token) {
537
+ return cliRequest({
538
+ appOrigin: ctx.appOrigin,
539
+ path: "/api/cli/status",
540
+ method: "GET",
541
+ token,
542
+ fetchImpl: ctx.fetchImpl,
543
+ });
544
+ }
545
+
546
+ async function performLogin(ctx, args) {
547
+ const result = await runBrowserFlow({
548
+ ...buildFlowOptions(ctx, args),
549
+ flowLabel: "sign in to SupaBeast",
550
+ startPath: "/api/cli/auth/start",
551
+ pollPath: "/api/cli/auth/poll",
552
+ });
553
+ const payload = result.data;
554
+ const nowMs = ctx.now ?? Date.now();
555
+ const expiresAt =
556
+ typeof payload.expires_in === "number" ? nowMs + payload.expires_in * 1_000 : undefined;
557
+ const credentialsPath = saveCredential(
558
+ ctx.appOrigin,
559
+ {
560
+ token: payload.token,
561
+ expiresAt,
562
+ user: payload.user ?? null,
563
+ workspace: payload.workspace ?? null,
564
+ },
565
+ buildCredentialOptions(ctx),
566
+ );
567
+ return {
568
+ token: payload.token,
569
+ expiresAt,
570
+ user: payload.user ?? null,
571
+ workspace: payload.workspace ?? null,
572
+ credentialsPath,
573
+ };
574
+ }
575
+
576
+ async function ensureAuthenticated(ctx, args, log) {
577
+ const credOpts = buildCredentialOptions(ctx);
578
+ const cred = loadCredential(ctx.appOrigin, credOpts);
579
+
580
+ if (cred?.token) {
581
+ const statusRes = await fetchStatus(ctx, cred.token);
582
+ if (statusRes.ok && statusRes.data) {
583
+ return { token: cred.token, statusData: statusRes.data, loggedInNow: false };
584
+ }
585
+ if (statusRes.status === 401) {
586
+ clearCredential(ctx.appOrigin, credOpts);
587
+ log("Stored CLI session expired or was revoked. Starting a new sign-in...");
588
+ } else {
589
+ throw Error(statusRes.data?.error || `Failed to inspect account status (${statusRes.status})`);
590
+ }
591
+ } else {
592
+ log(`Signing in to ${ctx.appOrigin}...`);
593
+ }
594
+
595
+ const login = await performLogin(ctx, args);
596
+ const handle = login.user?.github_login ? `@${login.user.github_login}` : "your account";
597
+ const wsName = login.workspace?.name ?? "Personal";
598
+ log(`Signed in as ${handle} (workspace: ${wsName}).`);
599
+
600
+ const statusRes = await fetchStatus(ctx, login.token);
601
+ if (!statusRes.ok || !statusRes.data) {
602
+ throw Error(statusRes.data?.error || `Failed to load workspace status (${statusRes.status})`);
603
+ }
604
+ return { token: login.token, statusData: statusRes.data, loggedInNow: true };
605
+ }
606
+
607
+ async function maybeSwitchWorkspace(ctx, token, statusData, args, log) {
608
+ const workspaces = Array.isArray(statusData.workspaces) ? statusData.workspaces : [];
609
+ if (workspaces.length <= 1 || !ctx.interactive || args.yes) {
610
+ return statusData;
611
+ }
612
+ const currentId = statusData.workspace?.id;
613
+ const keepCurrent = await ctx.prompter.confirm(
614
+ `Continue in workspace "${statusData.workspace?.name ?? currentId}"?`,
615
+ true,
616
+ );
617
+ if (keepCurrent) {
618
+ return statusData;
619
+ }
620
+ const items = workspaces.map((ws) => ({
621
+ value: ws.id,
622
+ label: `${ws.name} (${ws.role})`,
623
+ badge: ws.id === currentId ? "current" : undefined,
624
+ }));
625
+ const defaultIdx = Math.max(
626
+ 0,
627
+ workspaces.findIndex((ws) => ws.id === currentId),
628
+ );
629
+ const nextTenantId = await ctx.prompter.select("Select a SupaBeast workspace:", items, defaultIdx);
630
+ if (nextTenantId !== currentId) {
631
+ const switchRes = await cliRequest({
632
+ appOrigin: ctx.appOrigin,
633
+ path: "/api/cli/workspace/switch",
634
+ method: "POST",
635
+ token,
636
+ fetchImpl: ctx.fetchImpl,
637
+ body: { tenant_id: nextTenantId },
638
+ });
639
+ if (!switchRes.ok) {
640
+ throw Error(switchRes.data?.error || `Workspace switch failed (${switchRes.status})`);
641
+ }
642
+ const refreshed = await fetchStatus(ctx, token);
643
+ if (!refreshed.ok || !refreshed.data) {
644
+ throw Error(refreshed.data?.error || `Failed to reload status (${refreshed.status})`);
645
+ }
646
+ log(`Switched workspace to ${refreshed.data.workspace?.name ?? nextTenantId}.`);
647
+ return refreshed.data;
648
+ }
649
+ return statusData;
650
+ }
651
+
652
+ async function pickSupabaseProject(projects, ctx, args) {
653
+ if (!Array.isArray(projects) || projects.length === 0) {
654
+ throw Error("No Supabase projects were found in the authorized Supabase account.");
655
+ }
656
+
657
+ if (args.project) {
658
+ const needle = args.project.trim();
659
+ const match = projects.find(
660
+ (item) => item.ref === needle || item.name?.toLowerCase() === needle.toLowerCase(),
661
+ );
662
+ if (!match) {
663
+ throw Error(`Supabase project "${args.project}" was not found in the authorized account.`);
664
+ }
665
+ return match;
666
+ }
667
+
668
+ const localRef = ctx.local.supabaseProjectRef;
669
+ const localMatch = localRef ? projects.find((item) => item.ref === localRef) : null;
670
+ if (localMatch) {
671
+ if (!ctx.interactive || args.yes) {
672
+ return localMatch;
673
+ }
674
+ const confirmed = await ctx.prompter.confirm(
675
+ `Use local Supabase project ${localMatch.name} (${localMatch.ref})?`,
676
+ true,
677
+ );
678
+ if (confirmed) {
679
+ return localMatch;
680
+ }
681
+ }
682
+
683
+ if (projects.length === 1 && (!ctx.interactive || args.yes)) {
684
+ return projects[0];
685
+ }
686
+
687
+ if (!ctx.interactive) {
688
+ throw Error(
689
+ `Multiple Supabase projects found (${projects.map((p) => p.ref).join(", ")}). Re-run with --project <ref>.`,
690
+ );
691
+ }
692
+
693
+ const defaultIdx = localMatch ? projects.indexOf(localMatch) : 0;
694
+ const selectedRef = await ctx.prompter.select(
695
+ "Select the Supabase project to connect:",
696
+ projects.map((item) => ({
697
+ value: item.ref,
698
+ label: `${item.name} (${item.ref})`,
699
+ badge: item.ref === localRef ? "local" : undefined,
700
+ })),
701
+ Math.max(0, defaultIdx),
702
+ );
703
+ return projects.find((item) => item.ref === selectedRef) ?? projects[0];
704
+ }
705
+
706
+ async function connectSupabaseStep(ctx, token, args, log) {
707
+ log("Starting Supabase authorization...");
708
+ const flow = await runBrowserFlow({
709
+ ...buildFlowOptions(ctx, args),
710
+ token,
711
+ flowLabel: "authorize your Supabase account",
712
+ startPath: "/api/cli/supabase/start",
713
+ pollPath: "/api/cli/supabase/projects",
714
+ });
715
+
716
+ const projects = flow.data?.projects ?? [];
717
+ const selected = await pickSupabaseProject(projects, ctx, args);
718
+ log(`Connecting Supabase project ${selected.name} (${selected.ref}) and enabling Remote MCP...`);
719
+
720
+ const selectRes = await cliRequest({
721
+ appOrigin: ctx.appOrigin,
722
+ path: "/api/cli/supabase/select",
723
+ method: "POST",
724
+ token,
725
+ fetchImpl: ctx.fetchImpl,
726
+ body: {
727
+ flow_id: flow.flowId,
728
+ code_verifier: flow.verifier,
729
+ project_ref: selected.ref,
730
+ enable_mcp: true,
731
+ },
732
+ });
733
+ if (!selectRes.ok || !selectRes.data) {
734
+ throw Error(selectRes.data?.error || `Failed to connect Supabase project (${selectRes.status})`);
735
+ }
736
+
737
+ return selectRes.data;
738
+ }
739
+
740
+ async function ensureMcpEnabled(ctx, token, envObj, log) {
741
+ if (envObj.mcp_enabled) {
742
+ return envObj;
743
+ }
744
+ const enableRes = await cliRequest({
745
+ appOrigin: ctx.appOrigin,
746
+ path: "/api/cli/mcp/enable",
747
+ method: "POST",
748
+ token,
749
+ fetchImpl: ctx.fetchImpl,
750
+ body: { environment_id: envObj.id },
751
+ });
752
+ if (!enableRes.ok || !enableRes.data) {
753
+ throw Error(enableRes.data?.error || `Failed to enable Remote MCP (${enableRes.status})`);
754
+ }
755
+ log(`Enabled Remote MCP for ${envObj.project_name} (${envObj.project_ref}).`);
756
+ return { ...envObj, mcp_enabled: Boolean(enableRes.data.mcp_enabled) };
757
+ }
758
+
759
+ async function pickGitHubRepository(repositories, ctx, args) {
760
+ if (!Array.isArray(repositories) || repositories.length === 0) {
761
+ throw Error(
762
+ "No GitHub repositories are accessible to the SupaBeast GitHub App. Install it on your repository and retry.",
763
+ );
764
+ }
765
+
766
+ if (args.repo) {
767
+ const needle = args.repo.trim().toLowerCase();
768
+ const match = repositories.find(
769
+ (item) => item.full_name?.toLowerCase() === needle || String(item.id) === needle,
770
+ );
771
+ if (!match) {
772
+ throw Error(`GitHub repository "${args.repo}" was not found among installed repositories.`);
773
+ }
774
+ return match;
775
+ }
776
+
777
+ const localSlug = ctx.local.githubRepository?.toLowerCase();
778
+ const localMatch = localSlug
779
+ ? repositories.find((item) => item.full_name?.toLowerCase() === localSlug)
780
+ : null;
781
+ if (localMatch) {
782
+ if (!ctx.interactive || args.yes) {
783
+ return localMatch;
784
+ }
785
+ const confirmed = await ctx.prompter.confirm(
786
+ `Link local GitHub repository ${localMatch.full_name}?`,
787
+ true,
788
+ );
789
+ if (confirmed) {
790
+ return localMatch;
791
+ }
792
+ }
793
+
794
+ if (repositories.length === 1 && (!ctx.interactive || args.yes)) {
795
+ return repositories[0];
796
+ }
797
+
798
+ if (!ctx.interactive) {
799
+ throw Error("Multiple GitHub repositories found. Re-run with --repo <owner/repo>.");
800
+ }
801
+
802
+ const defaultIdx = localMatch ? repositories.indexOf(localMatch) : 0;
803
+ const selectedId = await ctx.prompter.select(
804
+ "Select a GitHub repository to link:",
805
+ repositories.map((item) => ({
806
+ value: String(item.id),
807
+ label: `${item.full_name} (default: ${item.default_branch})`,
808
+ badge: item.full_name?.toLowerCase() === localSlug ? "local" : undefined,
809
+ })),
810
+ Math.max(0, defaultIdx),
811
+ );
812
+ return repositories.find((item) => String(item.id) === selectedId) ?? repositories[0];
813
+ }
814
+
815
+ function normalizeRootInput(raw) {
816
+ const trimmed = typeof raw === "string" ? raw.trim() : "";
817
+ if (!trimmed || trimmed === "." || trimmed === "/") return "";
818
+ return trimmed;
819
+ }
820
+
821
+ const RETRYABLE_GITHUB_SELECT_STATUSES = new Set([400, 404, 422]);
822
+
823
+ async function connectGitHubStep(ctx, token, reviewProjectId, args, log, existingRepo = null) {
824
+ if (!reviewProjectId) {
825
+ throw Error(
826
+ "No connected Supabase project environment found. Connect Supabase first with `npx supabeast connect supabase`.",
827
+ );
828
+ }
829
+
830
+ log("Starting SupaBeast GitHub App authorization...");
831
+ const flow = await runBrowserFlow({
832
+ ...buildFlowOptions(ctx, args),
833
+ token,
834
+ flowLabel: "authorize the SupaBeast GitHub App",
835
+ startPath: "/api/cli/github/start",
836
+ pollPath: "/api/cli/github/repositories",
837
+ startBody: { review_project_id: reviewProjectId },
838
+ });
839
+
840
+ const targetReviewProjectId = flow.data?.review_project_id ?? reviewProjectId;
841
+ const repositories = flow.data?.repositories ?? [];
842
+ const selected = await pickGitHubRepository(repositories, ctx, args);
843
+
844
+ const sameExistingRepo =
845
+ Boolean(existingRepo?.repository) &&
846
+ existingRepo.repository.toLowerCase() === selected.full_name?.toLowerCase();
847
+
848
+ let branch =
849
+ args.branch ??
850
+ (sameExistingRepo ? existingRepo.branch : null) ??
851
+ selected.default_branch ??
852
+ "main";
853
+ const explicitFixBranch = typeof args.fixBranch === "string" && args.fixBranch.trim()
854
+ ? args.fixBranch.trim()
855
+ : null;
856
+ const explicitRoot = args.root !== null ? normalizeRootInput(args.root) : null;
857
+
858
+ const interactiveBranchSetup = Boolean(ctx.interactive && !args.yes);
859
+ if (interactiveBranchSetup && !args.branch) {
860
+ log(
861
+ `\nSupaBeast reads the deployed branch of ${selected.full_name} (read-only) to correlate live queries with your code and enable finding rechecks.\n`,
862
+ );
863
+ }
864
+
865
+ const maxAttempts = interactiveBranchSetup ? 3 : 1;
866
+ let retrying = false;
867
+
868
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
869
+ if (interactiveBranchSetup && (!args.branch || retrying)) {
870
+ const enteredBranch = await ctx.prompter.input(
871
+ "Branch deployed to your connected database",
872
+ branch,
873
+ );
874
+ branch = enteredBranch.trim() || branch;
875
+ }
876
+
877
+ const selectRes = await cliRequest({
878
+ appOrigin: ctx.appOrigin,
879
+ path: "/api/cli/github/select",
880
+ method: "POST",
881
+ token,
882
+ fetchImpl: ctx.fetchImpl,
883
+ body: {
884
+ flow_id: flow.flowId,
885
+ code_verifier: flow.verifier,
886
+ repository_id: selected.id,
887
+ branch,
888
+ ...(explicitFixBranch ? { fix_branch: explicitFixBranch } : {}),
889
+ ...(explicitRoot ? { root: explicitRoot } : {}),
890
+ },
891
+ });
892
+ if (selectRes.ok && selectRes.data) {
893
+ return {
894
+ review_project_id: targetReviewProjectId,
895
+ ...selectRes.data,
896
+ };
897
+ }
898
+
899
+ if (
900
+ interactiveBranchSetup &&
901
+ attempt + 1 < maxAttempts &&
902
+ RETRYABLE_GITHUB_SELECT_STATUSES.has(selectRes.status)
903
+ ) {
904
+ log(
905
+ selectRes.data?.error ||
906
+ `GitHub could not verify branch "${branch}" (${selectRes.status}).`,
907
+ );
908
+ const shouldRetry = await ctx.prompter.confirm(
909
+ "Try a different branch name?",
910
+ true,
911
+ );
912
+ if (shouldRetry) {
913
+ retrying = true;
914
+ continue;
915
+ }
916
+ }
917
+
918
+ throw Error(
919
+ selectRes.data?.error || `Failed to link GitHub repository (${selectRes.status})`,
920
+ );
921
+ }
922
+
923
+ throw Error("Failed to link GitHub repository.");
924
+ }
925
+
926
+ function findPreferredEnvironment(statusData, args, local) {
927
+ const environments = Array.isArray(statusData.environments) ? statusData.environments : [];
928
+ if (environments.length === 0) return null;
929
+ if (args.project) {
930
+ const match = environments.find(
931
+ (item) =>
932
+ item.project_ref === args.project ||
933
+ item.project_name?.toLowerCase() === args.project.toLowerCase(),
934
+ );
935
+ if (match) return match;
936
+ }
937
+ if (local.supabaseProjectRef) {
938
+ const match = environments.find((item) => item.project_ref === local.supabaseProjectRef);
939
+ if (match) return match;
940
+ }
941
+ if (statusData.connection?.project_ref) {
942
+ const match = environments.find((item) => item.project_ref === statusData.connection.project_ref);
943
+ if (match) return match;
944
+ }
945
+ return environments[0];
946
+ }
947
+
948
+ function renderStatusLines(appOrigin, mcpUrl, statusData, local) {
949
+ const lines = [
950
+ `App Origin: ${appOrigin}`,
951
+ `User: ${statusData.user?.github_login ? `@${statusData.user.github_login}` : statusData.user?.id ?? "unknown"}`,
952
+ `Workspace: ${statusData.workspace?.name ?? "Personal"} (${statusData.workspace?.plan ?? "free"}, ${statusData.workspace?.role ?? "owner"})`,
953
+ `Remote MCP: ${mcpUrl}`,
954
+ ];
955
+
956
+ const conn = statusData.connection;
957
+ if (conn?.connected) {
958
+ const stateNote = conn.needs_reconnect ? "needs reconnect" : "connected";
959
+ lines.push(`Supabase: ${conn.project_name ?? conn.project_ref} (${conn.project_ref}) [${stateNote}]`);
960
+ } else {
961
+ lines.push("Supabase: not connected");
962
+ }
963
+
964
+ const envs = Array.isArray(statusData.environments) ? statusData.environments : [];
965
+ if (envs.length > 0) {
966
+ lines.push("");
967
+ lines.push("Environments:");
968
+ for (const envObj of envs) {
969
+ const mcp = envObj.mcp_enabled ? "MCP enabled" : "MCP disabled";
970
+ const pg = envObj.postgres_version ? `PG ${envObj.postgres_version}` : "PG unknown";
971
+ const repo = envObj.repository ? formatGitHubSummary(envObj) : "GitHub not linked";
972
+ lines.push(` - ${envObj.project_name ?? envObj.name} (${envObj.project_ref}) — ${pg}, ${mcp}, ${repo}`);
973
+ }
974
+ }
975
+
976
+ if (local.supabaseProjectRef || local.githubRepository) {
977
+ lines.push("");
978
+ lines.push("Detected in current directory:");
979
+ if (local.supabaseProjectRef) {
980
+ lines.push(` - Supabase ref: ${local.supabaseProjectRef}`);
981
+ }
982
+ if (local.githubRepository) {
983
+ lines.push(
984
+ ` - Git repository: ${local.githubRepository}${local.gitBranch ? ` (${local.gitBranch})` : ""}`,
985
+ );
986
+ }
987
+ }
988
+
989
+ return lines;
990
+ }
991
+
992
+ async function mintMcpBearerToken(ctx, authToken, environmentId, clientLabel) {
993
+ const rawHost =
994
+ typeof ctx.hostname === "string"
995
+ ? ctx.hostname
996
+ : typeof os.hostname === "function"
997
+ ? os.hostname()
998
+ : "";
999
+ const cleanHost = rawHost.replace(/[\r\n\0]/g, "").trim().slice(0, 32);
1000
+ const clientName = (cleanHost ? `${clientLabel} (${cleanHost})` : clientLabel).slice(0, 80);
1001
+ const res = await cliRequest({
1002
+ appOrigin: ctx.appOrigin,
1003
+ path: "/api/cli/mcp/token",
1004
+ method: "POST",
1005
+ token: authToken,
1006
+ fetchImpl: ctx.fetchImpl,
1007
+ body: {
1008
+ environment_id: environmentId,
1009
+ client_name: clientName,
1010
+ replace_existing: true,
1011
+ },
1012
+ });
1013
+ if (!res.ok || !res.data?.token) {
1014
+ throw Error(res.data?.error || `Failed to mint MCP connection token (${res.status})`);
1015
+ }
1016
+ return {
1017
+ token: res.data.token,
1018
+ expiresAt: res.data.expires_at ?? null,
1019
+ };
1020
+ }
1021
+
233
1022
  /** Run the SupaBeast CLI entrypoint with injectable IO/env options and return process exit code. */
234
1023
  export async function runCli(argv = process.argv.slice(2), options = {}) {
235
1024
  const {
236
1025
  cwd = process.cwd(),
237
1026
  homeDir = os.homedir(),
238
1027
  env = process.env,
1028
+ platform = process.platform,
1029
+ hostname,
1030
+ pathApi = path,
1031
+ stdin = process.stdin,
239
1032
  stdout = process.stdout,
240
1033
  stderr = process.stderr,
241
1034
  fetchImpl = fetch,
242
- pathApi = path,
1035
+ openBrowserImpl = openBrowser,
1036
+ startCallbackServerImpl = startLoopbackCallbackServer,
1037
+ isInteractiveImpl = isInteractiveTerminal,
1038
+ createPrompterImpl = createTerminalPrompter,
1039
+ pollIntervalMs,
1040
+ timeoutMs,
1041
+ now,
243
1042
  } = options;
244
1043
 
245
1044
  let opts;
@@ -260,73 +1059,480 @@ export async function runCli(argv = process.argv.slice(2), options = {}) {
260
1059
  return 0;
261
1060
  }
262
1061
 
263
- if (opts.check) {
264
- const remote = await probeRemoteMcp({ url: opts.url, fetchImpl });
265
- const local = inspectLocalState({ url: opts.url, homeDir, cwd, env, pathApi });
266
- if (opts.json) {
267
- stdout.write(JSON.stringify({ remote, local }, null, 2) + "\n");
268
- } else {
269
- stdout.write(formatCheckText(remote, local));
1062
+ const interactive = Boolean(isInteractiveImpl(stdin, stdout));
1063
+ const appOrigin = resolveAppOrigin(opts.url);
1064
+ const local = detectLocalProject({ cwd, pathApi });
1065
+ const ctx = {
1066
+ cwd,
1067
+ homeDir,
1068
+ env,
1069
+ platform,
1070
+ hostname,
1071
+ pathApi,
1072
+ stdin,
1073
+ stdout,
1074
+ stderr,
1075
+ fetchImpl,
1076
+ openBrowserImpl,
1077
+ startCallbackServerImpl,
1078
+ interactive,
1079
+ prompter: interactive ? createPrompterImpl({ stdin, stdout }) : null,
1080
+ pollIntervalMs,
1081
+ timeoutMs,
1082
+ now,
1083
+ appOrigin,
1084
+ local,
1085
+ };
1086
+ const log = (line) => {
1087
+ if (!opts.json) {
1088
+ stdout.write(`${line}\n`);
270
1089
  }
271
- return remote.ok ? 0 : 1;
272
- }
1090
+ };
273
1091
 
274
- const explicitClients = [...opts.clients];
275
- const autoDetected =
276
- explicitClients.length > 0 ? [] : detectInstalledClients({ homeDir, cwd, env, pathApi });
277
- const targetClients = explicitClients.length > 0 ? explicitClients : autoDetected;
278
- const autoDetectedNone = explicitClients.length === 0 && autoDetected.length === 0;
1092
+ try {
1093
+ if (opts.check) {
1094
+ const remote = await probeRemoteMcp({ url: opts.url, fetchImpl });
1095
+ const localState = inspectLocalState({ url: opts.url, homeDir, cwd, env, pathApi });
1096
+ const cred = loadCredential(appOrigin, buildCredentialOptions(ctx));
1097
+ const cloudSession = {
1098
+ authenticated: Boolean(cred),
1099
+ user: cred?.user ?? null,
1100
+ workspace: cred?.workspace ?? null,
1101
+ };
1102
+ if (opts.json) {
1103
+ stdout.write(
1104
+ JSON.stringify({ remote, local: localState, cloudSession, project: local }, null, 2) + "\n",
1105
+ );
1106
+ } else {
1107
+ stdout.write(formatCheckText(remote, localState, cred));
1108
+ }
1109
+ return remote.ok ? 0 : 1;
1110
+ }
279
1111
 
280
- const configs = [];
281
- const skillPaths = [];
1112
+ if (opts.command === "login") {
1113
+ log(`Signing in to ${appOrigin}...`);
1114
+ const login = await performLogin(ctx, opts);
1115
+ if (opts.json) {
1116
+ stdout.write(
1117
+ `${JSON.stringify({ ok: true, command: "login", appOrigin, ...login, token: undefined }, null, 2)}\n`,
1118
+ );
1119
+ } else {
1120
+ const handle = login.user?.github_login ? `@${login.user.github_login}` : "your account";
1121
+ log(`Signed in as ${handle} (workspace: ${login.workspace?.name ?? "Personal"}).`);
1122
+ log(`Credentials saved to ${login.credentialsPath}`);
1123
+ }
1124
+ return 0;
1125
+ }
282
1126
 
283
- if (autoDetectedNone) {
284
- if (!opts.mcpOnly) {
285
- const defaultSkillPath =
286
- opts.scope === "project"
287
- ? pathApi.join(cwd, ".agents", "skills", "supabeast", "SKILL.md")
288
- : pathApi.join(homeDir, ".agents", "skills", "supabeast", "SKILL.md");
289
- skillPaths.push(defaultSkillPath);
1127
+ if (opts.command === "logout") {
1128
+ const credOpts = buildCredentialOptions(ctx);
1129
+ const cred = loadCredential(appOrigin, credOpts);
1130
+ if (cred?.token) {
1131
+ try {
1132
+ await cliRequest({
1133
+ appOrigin,
1134
+ path: "/api/cli/auth/logout",
1135
+ method: "POST",
1136
+ token: cred.token,
1137
+ fetchImpl,
1138
+ body: {},
1139
+ });
1140
+ } catch {
1141
+ /* Always clear local credential even if network revocation fails. */
1142
+ }
1143
+ }
1144
+ const cleared = clearCredential(appOrigin, credOpts);
1145
+ if (opts.json) {
1146
+ stdout.write(`${JSON.stringify({ ok: true, command: "logout", appOrigin, cleared }, null, 2)}\n`);
1147
+ } else if (cleared) {
1148
+ log(`Signed out of ${appOrigin}.`);
1149
+ } else {
1150
+ log(`No active CLI session found for ${appOrigin}.`);
1151
+ }
1152
+ return 0;
290
1153
  }
291
- } else {
292
- for (const clientId of targetClients) {
293
- const target = resolveClientTarget(clientId, {
294
- scope: opts.scope,
295
- homeDir,
296
- cwd,
297
- env,
298
- pathApi,
299
- url: opts.url,
300
- });
301
- if (!opts.skillOnly) {
302
- configs.push(applyClientConfig(target, { dryRun: opts.dryRun, pathApi }));
1154
+
1155
+ if (opts.command === "status") {
1156
+ const credOpts = buildCredentialOptions(ctx);
1157
+ const cred = loadCredential(appOrigin, credOpts);
1158
+ const credentialsPath = resolveCredentialsPath(credOpts);
1159
+ if (!cred?.token) {
1160
+ if (opts.json) {
1161
+ stdout.write(
1162
+ `${JSON.stringify(
1163
+ {
1164
+ authenticated: false,
1165
+ appOrigin,
1166
+ mcpUrl: opts.url,
1167
+ credentialsPath,
1168
+ local,
1169
+ },
1170
+ null,
1171
+ 2,
1172
+ )}\n`,
1173
+ );
1174
+ } else {
1175
+ log(`Not signed in for ${appOrigin}.`);
1176
+ log("Run `npx supabeast login` or `npx supabeast init` to connect your account.");
1177
+ }
1178
+ return 0;
303
1179
  }
1180
+
1181
+ const statusRes = await fetchStatus(ctx, cred.token);
1182
+ if (statusRes.status === 401) {
1183
+ clearCredential(appOrigin, credOpts);
1184
+ if (opts.json) {
1185
+ stdout.write(
1186
+ `${JSON.stringify(
1187
+ {
1188
+ authenticated: false,
1189
+ expired: true,
1190
+ appOrigin,
1191
+ mcpUrl: opts.url,
1192
+ credentialsPath,
1193
+ local,
1194
+ },
1195
+ null,
1196
+ 2,
1197
+ )}\n`,
1198
+ );
1199
+ } else {
1200
+ log("CLI session expired or was revoked. Run `npx supabeast login` to sign in again.");
1201
+ }
1202
+ return 0;
1203
+ }
1204
+ if (!statusRes.ok || !statusRes.data) {
1205
+ throw Error(statusRes.data?.error || `Failed to load status (${statusRes.status})`);
1206
+ }
1207
+
1208
+ if (opts.json) {
1209
+ stdout.write(
1210
+ `${JSON.stringify(
1211
+ {
1212
+ authenticated: true,
1213
+ appOrigin,
1214
+ mcpUrl: opts.url,
1215
+ credentialsPath,
1216
+ local,
1217
+ ...statusRes.data,
1218
+ },
1219
+ null,
1220
+ 2,
1221
+ )}\n`,
1222
+ );
1223
+ } else {
1224
+ for (const line of renderStatusLines(appOrigin, opts.url, statusRes.data, local)) {
1225
+ stdout.write(`${line}\n`);
1226
+ }
1227
+ }
1228
+ return 0;
1229
+ }
1230
+
1231
+ if (opts.command === "connect") {
1232
+ const target = opts.connectTarget ?? (opts.repo ? "github" : "supabase");
1233
+ const auth = await ensureAuthenticated(ctx, opts, log);
1234
+ const statusData = await maybeSwitchWorkspace(ctx, auth.token, auth.statusData, opts, log);
1235
+
1236
+ if (target === "supabase") {
1237
+ const connected = await connectSupabaseStep(ctx, auth.token, opts, log);
1238
+ if (opts.json) {
1239
+ stdout.write(`${JSON.stringify({ ok: true, command: "connect", target, ...connected }, null, 2)}\n`);
1240
+ } else {
1241
+ log(
1242
+ `Connected Supabase project ${connected.project_name} (${connected.project_ref}) [PG ${connected.postgres_version ?? "unknown"}, Remote MCP: ${connected.mcp_enabled ? "enabled" : "disabled"}].`,
1243
+ );
1244
+ }
1245
+ return 0;
1246
+ }
1247
+
1248
+ const envMatch = findPreferredEnvironment(statusData, opts, local);
1249
+ const existingRepo = envMatch?.repository
1250
+ ? {
1251
+ repository: envMatch.repository,
1252
+ branch: envMatch.branch ?? "main",
1253
+ fix_branch: envMatch.fix_branch ?? null,
1254
+ root: envMatch.root ?? "",
1255
+ }
1256
+ : null;
1257
+ const githubResult = await connectGitHubStep(
1258
+ ctx,
1259
+ auth.token,
1260
+ envMatch?.review_project_id,
1261
+ opts,
1262
+ log,
1263
+ existingRepo,
1264
+ );
1265
+ if (opts.json) {
1266
+ stdout.write(
1267
+ `${JSON.stringify({ ok: true, command: "connect", target, ...githubResult }, null, 2)}\n`,
1268
+ );
1269
+ } else {
1270
+ log(`Linked GitHub repository ${formatGitHubSummary(githubResult)} to review project.`);
1271
+ }
1272
+ return 0;
1273
+ }
1274
+
1275
+ // Default command: `init`
1276
+ let cloudSummary = null;
1277
+ let cloudAuthToken = null;
1278
+ let cloudEnvironmentId = null;
1279
+ let cloudMcpEnabled = false;
1280
+ if (shouldRunCloudSetup(opts, interactive)) {
1281
+ log("[1/4] Account sign-in");
1282
+ const auth = await ensureAuthenticated(ctx, opts, log);
1283
+ const statusData = await maybeSwitchWorkspace(ctx, auth.token, auth.statusData, opts, log);
1284
+ cloudAuthToken = auth.token;
1285
+
1286
+ log("\n[2/4] Supabase project & Remote MCP");
1287
+ let connectedEnv = findPreferredEnvironment(statusData, opts, local);
1288
+ const wantsProjectChange =
1289
+ Boolean(opts.project) &&
1290
+ connectedEnv?.project_ref !== opts.project &&
1291
+ connectedEnv?.project_name?.toLowerCase() !== opts.project.toLowerCase();
1292
+
1293
+ const needsSupabaseConnect =
1294
+ !statusData.connection?.connected ||
1295
+ Boolean(statusData.connection?.needs_reconnect) ||
1296
+ !connectedEnv ||
1297
+ wantsProjectChange;
1298
+
1299
+ let supabaseResult = null;
1300
+ if (needsSupabaseConnect) {
1301
+ supabaseResult = await connectSupabaseStep(ctx, auth.token, opts, log);
1302
+ } else if (interactive && !opts.yes && !opts.project) {
1303
+ const keepExisting = await ctx.prompter.confirm(
1304
+ `Use connected Supabase project ${connectedEnv.project_name} (${connectedEnv.project_ref})?`,
1305
+ true,
1306
+ );
1307
+ if (!keepExisting) {
1308
+ supabaseResult = await connectSupabaseStep(ctx, auth.token, opts, log);
1309
+ } else {
1310
+ connectedEnv = await ensureMcpEnabled(ctx, auth.token, connectedEnv, log);
1311
+ supabaseResult = {
1312
+ connected: true,
1313
+ project_ref: connectedEnv.project_ref,
1314
+ project_name: connectedEnv.project_name,
1315
+ environment_id: connectedEnv.id,
1316
+ review_project_id: connectedEnv.review_project_id,
1317
+ postgres_version: connectedEnv.postgres_version,
1318
+ mcp_enabled: connectedEnv.mcp_enabled,
1319
+ mcp_endpoint: statusData.mcp_endpoint,
1320
+ };
1321
+ }
1322
+ } else {
1323
+ connectedEnv = await ensureMcpEnabled(ctx, auth.token, connectedEnv, log);
1324
+ supabaseResult = {
1325
+ connected: true,
1326
+ project_ref: connectedEnv.project_ref,
1327
+ project_name: connectedEnv.project_name,
1328
+ environment_id: connectedEnv.id,
1329
+ review_project_id: connectedEnv.review_project_id,
1330
+ postgres_version: connectedEnv.postgres_version,
1331
+ mcp_enabled: connectedEnv.mcp_enabled,
1332
+ mcp_endpoint: statusData.mcp_endpoint,
1333
+ };
1334
+ }
1335
+
1336
+ log("\n[3/4] GitHub repository (optional)");
1337
+ let githubResult = null;
1338
+ const existingRepo =
1339
+ !needsSupabaseConnect && connectedEnv?.repository
1340
+ ? {
1341
+ connected: true,
1342
+ review_project_id: connectedEnv.review_project_id,
1343
+ repository: connectedEnv.repository,
1344
+ branch: connectedEnv.branch ?? "main",
1345
+ fix_branch: connectedEnv.fix_branch ?? null,
1346
+ root: connectedEnv.root ?? null,
1347
+ }
1348
+ : null;
1349
+
1350
+ if (opts.skipGithub) {
1351
+ githubResult = { skipped: true };
1352
+ } else if (opts.repo) {
1353
+ githubResult = await connectGitHubStep(
1354
+ ctx,
1355
+ auth.token,
1356
+ supabaseResult.review_project_id,
1357
+ opts,
1358
+ log,
1359
+ existingRepo,
1360
+ );
1361
+ } else if (existingRepo && (!interactive || opts.yes)) {
1362
+ githubResult = existingRepo;
1363
+ } else if (interactive) {
1364
+ const repoPrompt = existingRepo
1365
+ ? `Change linked GitHub repository (currently ${formatGitHubSummary(existingRepo)})?`
1366
+ : "Link a GitHub repository now for static code and migration analysis? (optional)";
1367
+ const shouldLink = await ctx.prompter.confirm(
1368
+ repoPrompt,
1369
+ !existingRepo && Boolean(local.githubRepository),
1370
+ );
1371
+ if (shouldLink) {
1372
+ githubResult = await connectGitHubStep(
1373
+ ctx,
1374
+ auth.token,
1375
+ supabaseResult.review_project_id,
1376
+ opts,
1377
+ log,
1378
+ existingRepo,
1379
+ );
1380
+ } else {
1381
+ githubResult = existingRepo ?? { skipped: true };
1382
+ }
1383
+ } else {
1384
+ githubResult = existingRepo ?? { skipped: true };
1385
+ }
1386
+
1387
+ cloudAuthToken = auth.token;
1388
+ cloudEnvironmentId = supabaseResult?.environment_id ?? null;
1389
+ cloudMcpEnabled = Boolean(supabaseResult?.mcp_enabled);
1390
+
1391
+ cloudSummary = {
1392
+ appOrigin,
1393
+ user: statusData.user,
1394
+ workspace: statusData.workspace,
1395
+ supabase: supabaseResult,
1396
+ github: githubResult,
1397
+ };
1398
+ log("\n[4/4] Local coding agents & SKILL.md");
1399
+ }
1400
+
1401
+ const explicitClients = [...opts.clients];
1402
+ const autoDetected =
1403
+ explicitClients.length > 0 ? [] : detectInstalledClients({ homeDir, cwd, env, pathApi });
1404
+ const targetClients = explicitClients.length > 0 ? explicitClients : autoDetected;
1405
+ const autoDetectedNone = explicitClients.length === 0 && autoDetected.length === 0;
1406
+ const BEARER_AUTH_CLIENTS = new Set(["antigravity", "t3"]);
1407
+
1408
+ const configs = [];
1409
+ const skillPaths = [];
1410
+
1411
+ if (autoDetectedNone) {
304
1412
  if (!opts.mcpOnly) {
305
- skillPaths.push(target.skillPath);
1413
+ const defaultSkillPath =
1414
+ opts.scope === "project"
1415
+ ? pathApi.join(cwd, ".agents", "skills", "supabeast", "SKILL.md")
1416
+ : pathApi.join(homeDir, ".agents", "skills", "supabeast", "SKILL.md");
1417
+ skillPaths.push(defaultSkillPath);
1418
+ }
1419
+ } else {
1420
+ for (const clientId of targetClients) {
1421
+ const discoveredTargets = resolveClientTargets(clientId, {
1422
+ scope: opts.scope,
1423
+ homeDir,
1424
+ cwd,
1425
+ env,
1426
+ pathApi,
1427
+ url: opts.url,
1428
+ });
1429
+
1430
+ if (discoveredTargets.length === 0) {
1431
+ if (opts.explicitNonAllClients.has(clientId)) {
1432
+ const t3UserdataDir =
1433
+ typeof env?.T3_USERDATA_DIR === "string" && env.T3_USERDATA_DIR.trim()
1434
+ ? env.T3_USERDATA_DIR.trim()
1435
+ : pathApi.join(homeDir, ".t3", "userdata");
1436
+ configs.push({
1437
+ clientId,
1438
+ label: CLIENT_LABELS[clientId],
1439
+ scope: opts.scope,
1440
+ path: pathApi.join(t3UserdataDir, "providers", "antigravity"),
1441
+ status: "skipped",
1442
+ reason:
1443
+ "No T3 Code Antigravity profile found. Open T3 Code with Antigravity once first, then re-run.",
1444
+ });
1445
+ if (!opts.mcpOnly) {
1446
+ skillPaths.push(pathApi.join(homeDir, ".agents", "skills", "supabeast", "SKILL.md"));
1447
+ }
1448
+ }
1449
+ continue;
1450
+ }
1451
+
1452
+ let bearerToken;
1453
+ if (
1454
+ !opts.skillOnly &&
1455
+ !opts.dryRun &&
1456
+ opts.scope === "user" &&
1457
+ BEARER_AUTH_CLIENTS.has(clientId) &&
1458
+ cloudAuthToken &&
1459
+ cloudEnvironmentId &&
1460
+ cloudMcpEnabled
1461
+ ) {
1462
+ const minted = await mintMcpBearerToken(
1463
+ ctx,
1464
+ cloudAuthToken,
1465
+ cloudEnvironmentId,
1466
+ CLIENT_LABELS[clientId],
1467
+ );
1468
+ bearerToken = minted.token;
1469
+ }
1470
+
1471
+ const targets = bearerToken
1472
+ ? resolveClientTargets(clientId, {
1473
+ scope: opts.scope,
1474
+ homeDir,
1475
+ cwd,
1476
+ env,
1477
+ pathApi,
1478
+ url: opts.url,
1479
+ bearerToken,
1480
+ })
1481
+ : discoveredTargets;
1482
+
1483
+ for (const target of targets) {
1484
+ if (!opts.skillOnly) {
1485
+ configs.push(applyClientConfig(target, { dryRun: opts.dryRun, pathApi, platform }));
1486
+ }
1487
+ if (!opts.mcpOnly) {
1488
+ skillPaths.push(target.skillPath);
1489
+ }
1490
+ }
306
1491
  }
307
1492
  }
308
- }
309
1493
 
310
- const skills = opts.mcpOnly ? [] : installSkillFiles(skillPaths, { dryRun: opts.dryRun, pathApi });
311
- const hasErrors = configs.some((c) => c.status === "error");
1494
+ const skills = opts.mcpOnly ? [] : installSkillFiles(skillPaths, { dryRun: opts.dryRun, pathApi });
1495
+ const hasErrors = configs.some((c) => c.status === "error");
312
1496
 
313
- const result = {
314
- endpoint: opts.url,
315
- scope: opts.scope,
316
- dryRun: opts.dryRun,
317
- targets: targetClients.map((id) => id),
318
- targetLabels: targetClients.map((id) => CLIENT_LABELS[id]),
319
- autoDetectedNone,
320
- configs,
321
- skills,
322
- hasErrors,
323
- };
1497
+ const result = {
1498
+ endpoint: opts.url,
1499
+ scope: opts.scope,
1500
+ dryRun: opts.dryRun,
1501
+ targets: targetClients.map((id) => id),
1502
+ targetLabels: targetClients.map((id) => CLIENT_LABELS[id]),
1503
+ autoDetectedNone,
1504
+ configs,
1505
+ skills,
1506
+ hasErrors,
1507
+ ...(cloudSummary ? { cloud: cloudSummary } : {}),
1508
+ };
324
1509
 
325
- if (opts.json) {
326
- stdout.write(JSON.stringify(result, null, 2) + "\n");
327
- } else {
328
- stdout.write(formatInitText(result));
1510
+ if (opts.json) {
1511
+ stdout.write(JSON.stringify(result, null, 2) + "\n");
1512
+ } else {
1513
+ stdout.write(formatInitText(result));
1514
+ }
1515
+
1516
+ return hasErrors ? 1 : 0;
1517
+ } catch (error) {
1518
+ if (
1519
+ error &&
1520
+ typeof error === "object" &&
1521
+ (error.code === "ECANCELLED" || error.code === "ABORT_ERR")
1522
+ ) {
1523
+ stderr.write("Cancelled.\n");
1524
+ return 130;
1525
+ }
1526
+ stderr.write(`Error: ${error instanceof Error ? error.message : String(error)}\n`);
1527
+ return 1;
329
1528
  }
1529
+ }
1530
+
1531
+ function isExecutedDirectly() {
1532
+ if (!process.argv[1]) return false;
1533
+ return import.meta.url === pathToFileURL(process.argv[1]).href;
1534
+ }
330
1535
 
331
- return hasErrors ? 1 : 0;
1536
+ if (isExecutedDirectly()) {
1537
+ process.exitCode = await runCli(process.argv.slice(2));
332
1538
  }