@sequelsh/cli 0.2.0 → 0.4.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/README.md CHANGED
@@ -35,7 +35,7 @@ sequel skills show seo # print one playbook
35
35
  | Command | Description |
36
36
  | --- | --- |
37
37
  | `sequel upgrade` | Upgrade the CLI to the latest version from npm. |
38
- | `sequel login` | Sign in to Sequel. |
38
+ | `sequel login` | Sign in to Sequel. `--no-browser` prints the sign-in URL instead of opening it; `--detach` (automatic when piped) returns the URL immediately and finishes in the background; `--status` / `--wait` check on or wait for that sign-in. |
39
39
  | `sequel logout` | Sign out and remove cached credentials. |
40
40
  | `sequel switch` | Switch the active organization. |
41
41
  | `sequel connect [source]` | Connect a new data source (interactive, or pass a connector id). |
@@ -43,7 +43,7 @@ sequel skills show seo # print one playbook
43
43
  | `sequel sources active` | List sources with live health status. |
44
44
  | `sequel sources info <id>` | Show details for a source. |
45
45
  | `sequel sources delete <id>` | Delete a source. |
46
- | `sequel install [agent]` | Install the Sequel MCP server into a coding agent (Claude, Cursor, VS Code, and more). |
46
+ | `sequel install [agent]` | Install the Sequel MCP server into a coding agent (Claude, Cursor, VS Code, and more). `--scope global\|local` skips the scope prompt; with an agent slug it runs without prompting. |
47
47
  | `sequel search <use case>` | Find the right tools for a use case across your sources. |
48
48
  | `sequel execute` | Execute a tool against a connection. |
49
49
 
package/dist/index.js CHANGED
@@ -13,10 +13,84 @@ import * as p$3 from "@clack/prompts";
13
13
  import * as p$2 from "@clack/prompts";
14
14
  import * as p$1 from "@clack/prompts";
15
15
  import * as p from "@clack/prompts";
16
- import { execFileSync } from "node:child_process";
16
+ import { execFileSync, spawn } from "node:child_process";
17
17
  import YAML from "yaml";
18
18
  import { writeFile } from "node:fs/promises";
19
19
 
20
+ //#region package.json
21
+ var name = "@sequelsh/cli";
22
+ var version = "0.4.0";
23
+ var description = "Sequel CLI — connect data sources and run tools from your terminal.";
24
+ var license = "MIT";
25
+ var type = "module";
26
+ var bin = { "sequel": "./dist/index.js" };
27
+ var files = ["dist"];
28
+ var exports = { ".": {
29
+ "import": "./dist/index.js",
30
+ "types": "./dist/index.d.ts"
31
+ } };
32
+ var engines = { "node": ">=18" };
33
+ var repository = {
34
+ "type": "git",
35
+ "url": "git+https://github.com/sequelsh/sequel.git",
36
+ "directory": "packages/cli"
37
+ };
38
+ var homepage = "https://sequel.sh";
39
+ var keywords = [
40
+ "sequel",
41
+ "cli",
42
+ "mcp",
43
+ "sql",
44
+ "data",
45
+ "ai",
46
+ "agents"
47
+ ];
48
+ var publishConfig = { "access": "public" };
49
+ var scripts = {
50
+ "dev": "bun run src/index.ts",
51
+ "cli": "bun run src/index.ts",
52
+ "build": "tsdown",
53
+ "build:binaries": "bun run scripts/build-binaries.ts",
54
+ "test": "vitest run",
55
+ "test:watch": "vitest",
56
+ "typecheck": "tsc --noEmit",
57
+ "clean": "rm -rf dist"
58
+ };
59
+ var dependencies = {
60
+ "@clack/prompts": "^0.8.2",
61
+ "commander": "^12.1.0",
62
+ "open": "^10.1.0",
63
+ "picocolors": "^1.1.1",
64
+ "yaml": "^2.5.1"
65
+ };
66
+ var devDependencies = {
67
+ "@sequel/mcp-clients": "workspace:*",
68
+ "@sequel/typescript-config": "workspace:*",
69
+ "@types/node": "^22.10.0",
70
+ "tsdown": "^0.9.0",
71
+ "typescript": "^5.7.0",
72
+ "vitest": "^3.0.0"
73
+ };
74
+ var package_default = {
75
+ name,
76
+ version,
77
+ description,
78
+ license,
79
+ type,
80
+ bin,
81
+ files,
82
+ exports,
83
+ engines,
84
+ repository,
85
+ homepage,
86
+ keywords,
87
+ publishConfig,
88
+ scripts,
89
+ dependencies,
90
+ devDependencies
91
+ };
92
+
93
+ //#endregion
20
94
  //#region src/lib/config.ts
21
95
  /** Default production API base. Override with SEQUEL_API_URL for local/dev. */
22
96
  const DEFAULT_API_URL = "https://api.sequel.sh";
@@ -190,13 +264,6 @@ function waitForCallback(expectedState) {
190
264
  code
191
265
  };
192
266
  }
193
- /**
194
- * Run the full OAuth 2.0 + PKCE loopback flow: register a client, open the
195
- * browser to the consent page (where the user picks an org), capture the code,
196
- * exchange it for an org-bound token, then cache that token keyed by its org.
197
- *
198
- * Shared by `login` and `switch` (for orgs without a cached token).
199
- */
200
267
  async function runLoginFlow(options) {
201
268
  const config = readConfig();
202
269
  const apiUrl = resolveApiUrl(config);
@@ -216,7 +283,12 @@ async function runLoginFlow(options) {
216
283
  authorizeUrl.searchParams.set("state", state);
217
284
  if (!options?.silent) open(authorizeUrl.toString()).catch(() => {});
218
285
  process.stderr.write(`\nOpen this URL to continue:\n${authorizeUrl.toString()}\n\n`);
219
- const code = await codePromise;
286
+ options?.onUrl?.(authorizeUrl.toString());
287
+ let timer;
288
+ const timeout = new Promise((_, reject) => {
289
+ if (options?.timeoutMs) timer = setTimeout(() => reject(new Error("Timed out waiting for the browser sign-in to complete.")), options.timeoutMs);
290
+ });
291
+ const code = await Promise.race([codePromise, timeout]).finally(() => clearTimeout(timer));
220
292
  const token = await postToken(apiUrl, {
221
293
  grant_type: "authorization_code",
222
294
  code,
@@ -415,12 +487,12 @@ function search(useCase, connectionIds) {
415
487
  }
416
488
  });
417
489
  }
418
- async function createApiKey(name) {
490
+ async function createApiKey(name$1) {
419
491
  const orgId = await activeOrgId();
420
492
  return request(`/organizations/${orgId}/api-keys`, {
421
493
  method: "POST",
422
494
  org: "none",
423
- body: { name }
495
+ body: { name: name$1 }
424
496
  });
425
497
  }
426
498
  /** Get a signed URL to download a file produced in a session (by sequel_execute / workbench). */
@@ -476,24 +548,204 @@ function fail(message) {
476
548
  process.stderr.write(`${pc.red("✗")} ${message}\n`);
477
549
  }
478
550
 
551
+ //#endregion
552
+ //#region src/lib/pending-login.ts
553
+ /** How long the background worker waits for the browser before giving up. */
554
+ const LOGIN_TIMEOUT_MS = 10 * 60 * 1e3;
555
+ /** How long the foreground `login` waits for the worker to report its URL. */
556
+ const URL_WAIT_MS = 2e4;
557
+ function pendingLoginPath() {
558
+ return join(configDir(), "pending-login.json");
559
+ }
560
+ function isAlive(pid) {
561
+ try {
562
+ process.kill(pid, 0);
563
+ return true;
564
+ } catch {
565
+ return false;
566
+ }
567
+ }
568
+ /** The current record, or null if there is none, it expired, or its worker died. */
569
+ function readPendingLogin() {
570
+ const path = pendingLoginPath();
571
+ if (!existsSync(path)) return null;
572
+ let parsed;
573
+ try {
574
+ parsed = JSON.parse(readFileSync(path, "utf8"));
575
+ } catch {
576
+ rmSync(path, { force: true });
577
+ return null;
578
+ }
579
+ if (parsed.status === "pending" && (Date.now() > parsed.expiresAt || !isAlive(parsed.pid))) {
580
+ rmSync(path, { force: true });
581
+ return null;
582
+ }
583
+ return parsed;
584
+ }
585
+ function writePendingLogin(record) {
586
+ mkdirSync(configDir(), {
587
+ recursive: true,
588
+ mode: 448
589
+ });
590
+ writeFileSync(pendingLoginPath(), `${JSON.stringify(record, null, 2)}\n`, { mode: 384 });
591
+ }
592
+ function clearPendingLogin() {
593
+ rmSync(pendingLoginPath(), { force: true });
594
+ }
595
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
596
+ /**
597
+ * Spawn the detached worker and return its record once the URL is known.
598
+ * Reuses a still-pending sign-in rather than starting a second one.
599
+ */
600
+ async function startDetachedLogin(opts) {
601
+ const existing = readPendingLogin();
602
+ if (existing?.status === "pending") return existing;
603
+ clearPendingLogin();
604
+ const args = [
605
+ process.argv[1],
606
+ "login-worker",
607
+ ...opts.browser ? [] : ["--no-browser"]
608
+ ];
609
+ const child = spawn(process.execPath, args, {
610
+ detached: true,
611
+ stdio: "ignore"
612
+ });
613
+ child.unref();
614
+ const deadline = Date.now() + URL_WAIT_MS;
615
+ while (Date.now() < deadline) {
616
+ const record = readPendingLogin();
617
+ if (record && record.pid === child.pid) {
618
+ if (record.status === "failed") throw new Error(record.error ?? "Sign-in failed to start.");
619
+ return record;
620
+ }
621
+ await sleep(200);
622
+ }
623
+ throw new Error("Timed out waiting for the sign-in URL. Run `sequel login` again.");
624
+ }
625
+ /**
626
+ * Block until the pending sign-in finishes (or `timeoutMs` passes). Resolves
627
+ * true when a token is now cached. Returns immediately if nothing is pending.
628
+ */
629
+ async function waitForLogin(timeoutMs) {
630
+ const deadline = Date.now() + timeoutMs;
631
+ while (Date.now() < deadline) {
632
+ const record = readPendingLogin();
633
+ if (!record) return isLoggedIn();
634
+ if (record.status === "failed") return false;
635
+ await sleep(1e3);
636
+ }
637
+ return false;
638
+ }
639
+
479
640
  //#endregion
480
641
  //#region src/commands/login.ts
481
- async function loginCommand() {
642
+ /** Instruction that rides along with a pending URL so an agent knows what to do. */
643
+ const PENDING_MESSAGE = "Show this URL to the user and ask them to open it in their browser to sign in. Once they have, run `sequel login --status` to confirm.";
644
+ function printStatus() {
482
645
  const json = isJsonMode();
483
- if (json) info("Opening your browser to authorize…");
484
- else {
485
- p$5.intro(pc.cyan("Sign in to Sequel"));
486
- p$5.log.info("Opening your browser to authorize…");
646
+ const pending = readPendingLogin();
647
+ if (pending?.status === "pending") {
648
+ if (json) return printJson({
649
+ status: "pending",
650
+ url: pending.url,
651
+ expiresAt: pending.expiresAt,
652
+ message: PENDING_MESSAGE
653
+ });
654
+ info(`Sign-in pending. Open this URL to finish:\n${pending.url}`);
655
+ return;
656
+ }
657
+ if (pending?.status === "failed") {
658
+ if (json) return printJson({
659
+ status: "failed",
660
+ error: pending.error ?? "Sign-in failed.",
661
+ message: "Run `sequel login` to try again."
662
+ });
663
+ info(`${pc.red("✗")} Last sign-in failed: ${pending.error ?? "unknown error"}. Run \`sequel login\` to try again.`);
664
+ return;
665
+ }
666
+ if (isLoggedIn()) {
667
+ const config = readConfig();
668
+ const org = config.orgs?.find((o) => o.id === config.activeOrgId) ?? null;
669
+ if (json) return printJson({
670
+ status: "logged_in",
671
+ user: config.user ?? null,
672
+ org
673
+ });
674
+ success(`Logged in as ${pc.bold(config.user?.email ?? "unknown")}${org ? ` · ${pc.bold(org.name)}` : ""}`);
675
+ return;
487
676
  }
488
- const res = await runLoginFlow();
489
677
  if (json) return printJson({
490
- status: "logged_in",
491
- user: res.user,
492
- org: res.org ?? null
678
+ status: "logged_out",
679
+ message: "Run `sequel login` to sign in."
493
680
  });
681
+ info("Not logged in. Run `sequel login` to sign in.");
682
+ }
683
+ async function loginCommand(opts = {}) {
684
+ const json = isJsonMode();
685
+ const openBrowser = opts.browser !== false;
686
+ if (opts.status) return printStatus();
687
+ if (opts.wait) {
688
+ const pending = readPendingLogin();
689
+ if (pending?.status === "pending") {
690
+ info(`Waiting for the sign-in at ${pending.url} to finish…`);
691
+ await waitForLogin(pending.expiresAt - Date.now());
692
+ }
693
+ return printStatus();
694
+ }
695
+ if (opts.detach || json) {
696
+ const pending = await startDetachedLogin({ browser: openBrowser });
697
+ if (json) return printJson({
698
+ status: "pending",
699
+ url: pending.url,
700
+ expiresAt: pending.expiresAt,
701
+ message: PENDING_MESSAGE
702
+ });
703
+ info(`Open this URL to sign in:\n${pending.url}\n\nSign-in continues in the background; run \`sequel login --status\` to check.`);
704
+ return;
705
+ }
706
+ p$5.intro(pc.cyan("Sign in to Sequel"));
707
+ p$5.log.info(openBrowser ? "Opening your browser to authorize…" : "Sign in with the URL below…");
708
+ const res = await runLoginFlow({ silent: !openBrowser });
494
709
  success(`Logged in as ${pc.bold(res.user.email)}${res.org ? ` · ${pc.bold(res.org.name)}` : ""}`);
495
710
  p$5.outro("You're all set. Try `sequel sources list` or `sequel connect`.");
496
711
  }
712
+ /**
713
+ * Hidden: the detached process behind a piped `sequel login`. Owns the loopback
714
+ * server, records the URL for the foreground process, and clears the record
715
+ * (or marks it failed) when the browser flow ends.
716
+ */
717
+ async function loginWorkerCommand(opts = {}) {
718
+ const startedAt = Date.now();
719
+ const base = {
720
+ pid: process.pid,
721
+ startedAt,
722
+ expiresAt: startedAt + LOGIN_TIMEOUT_MS
723
+ };
724
+ let url = "";
725
+ try {
726
+ await runLoginFlow({
727
+ silent: opts.browser === false,
728
+ timeoutMs: LOGIN_TIMEOUT_MS,
729
+ onUrl: (u) => {
730
+ url = u;
731
+ writePendingLogin({
732
+ ...base,
733
+ url,
734
+ status: "pending"
735
+ });
736
+ }
737
+ });
738
+ clearPendingLogin();
739
+ } catch (err) {
740
+ writePendingLogin({
741
+ ...base,
742
+ url,
743
+ status: "failed",
744
+ error: err instanceof Error ? err.message : String(err)
745
+ });
746
+ process.exitCode = 1;
747
+ }
748
+ }
497
749
 
498
750
  //#endregion
499
751
  //#region src/commands/logout.ts
@@ -621,11 +873,11 @@ async function connectCommand(source) {
621
873
  }
622
874
  credentials[field] = value;
623
875
  }
624
- const name = await p$3.text({
876
+ const name$1 = await p$3.text({
625
877
  message: "Name for this source (optional)",
626
878
  placeholder: connector.name
627
879
  });
628
- if (p$3.isCancel(name)) {
880
+ if (p$3.isCancel(name$1)) {
629
881
  p$3.cancel("Cancelled.");
630
882
  return;
631
883
  }
@@ -633,7 +885,7 @@ async function connectCommand(source) {
633
885
  s$1.start("Validating credentials…");
634
886
  const res$1 = await createLink(connector.id, {
635
887
  credentials,
636
- ...name ? { name } : {}
888
+ ...name$1 ? { name: name$1 } : {}
637
889
  });
638
890
  if (res$1.status === "success") {
639
891
  s$1.stop("Connected.");
@@ -1052,13 +1304,22 @@ async function fetchSkillMarkdown() {
1052
1304
 
1053
1305
  //#endregion
1054
1306
  //#region src/commands/install.ts
1055
- async function installCommand(slugArg) {
1056
- if (isJsonMode()) throw new Error("`sequel install` is interactive (it prompts for the agent/scope) — run it in a terminal, not piped/--json.");
1057
- p$1.intro(pc.cyan("Install the Sequel MCP server and skill"));
1058
- if (!isLoggedIn()) {
1307
+ const SCOPES = ["global", "local"];
1308
+ async function installCommand(slugArg, opts = {}) {
1309
+ const interactive = !isJsonMode();
1310
+ const slugList = mcpClients.map((c) => c.slug).join(", ");
1311
+ if (interactive) p$1.intro(pc.cyan("Install the Sequel MCP server and skill"));
1312
+ if (slugArg && !getMcpClient(slugArg)) throw new Error(`Unknown agent "${slugArg}". Options: ${slugList}`);
1313
+ if (!slugArg && !interactive) throw new Error(`Pass the agent slug when running non-interactively: \`sequel install <agent>\`. Options: ${slugList}`);
1314
+ if (!isLoggedIn()) if (!interactive) {
1315
+ const pending = readPendingLogin();
1316
+ if (pending?.status !== "pending") throw new Error("Not signed in. Run `sequel login` first: it prints a sign-in URL for the user to open. Once they have signed in, rerun this command.");
1317
+ info(`Waiting for the sign-in at ${pending.url} to finish…`);
1318
+ if (!await waitForLogin(pending.expiresAt - Date.now())) throw new Error("The sign-in did not complete. Run `sequel login` to get a fresh URL, then rerun this command.");
1319
+ } else {
1059
1320
  p$1.log.info("You need to sign in to Sequel first — opening your browser…");
1060
1321
  try {
1061
- const result$1 = await runLoginFlow();
1322
+ const result$1 = await runLoginFlow({ silent: opts.browser === false });
1062
1323
  p$1.log.success(`Signed in as ${result$1.user.email}${result$1.org ? ` (${result$1.org.name})` : ""}.`);
1063
1324
  } catch (err) {
1064
1325
  p$1.cancel(err instanceof Error ? err.message : String(err));
@@ -1078,9 +1339,13 @@ async function installCommand(slugArg) {
1078
1339
  slug = choice;
1079
1340
  }
1080
1341
  const client = getMcpClient(slug);
1081
- if (!client) throw new Error(`Unknown agent "${slug}". Options: ${mcpClients.map((c) => c.slug).join(", ")}`);
1342
+ if (!client) throw new Error(`Unknown agent "${slug}". Options: ${slugList}`);
1082
1343
  let scope = client.scopes[0];
1083
- if (client.scopes.length > 1) {
1344
+ if (opts.scope !== void 0) {
1345
+ if (!SCOPES.includes(opts.scope)) throw new Error(`Unknown scope "${opts.scope}". Options: ${SCOPES.join(", ")}`);
1346
+ if (!client.scopes.includes(opts.scope)) throw new Error(`${client.name} only supports the ${client.scopes.join("/")} scope.`);
1347
+ scope = opts.scope;
1348
+ } else if (client.scopes.length > 1 && interactive) {
1084
1349
  const choice = await p$1.select({
1085
1350
  message: "Install scope",
1086
1351
  options: [{
@@ -1098,16 +1363,16 @@ async function installCommand(slugArg) {
1098
1363
  }
1099
1364
  const config = readConfig();
1100
1365
  const apiUrl = resolveApiUrl(config);
1101
- const s = p$1.spinner();
1102
- s.start("Creating a Sequel API key for this agent…");
1366
+ const s = interactive ? p$1.spinner() : null;
1367
+ s?.start("Creating a Sequel API key for this agent…");
1103
1368
  let key;
1104
1369
  try {
1105
1370
  ({key} = await createApiKey(`Sequel CLI (${client.name})`));
1106
1371
  } catch (err) {
1107
- s.stop("Failed to create API key.");
1372
+ s?.stop("Failed to create API key.");
1108
1373
  throw err;
1109
1374
  }
1110
- s.stop("API key created.");
1375
+ s ? s.stop("API key created.") : info("API key created.");
1111
1376
  const result = client.install({
1112
1377
  apiUrl,
1113
1378
  apiKey: key,
@@ -1122,7 +1387,7 @@ async function installCommand(slugArg) {
1122
1387
  success(`Installed Sequel into ${client.name} (${scope}).`);
1123
1388
  } else {
1124
1389
  success(`Installed Sequel into ${client.name}.`);
1125
- p$1.log.info(`Config written to ${pc.dim(result.path)}`);
1390
+ info(`Config written to ${pc.dim(result.path)}`);
1126
1391
  }
1127
1392
  const skillsDir = client.skillsDir?.({
1128
1393
  apiUrl,
@@ -1130,22 +1395,26 @@ async function installCommand(slugArg) {
1130
1395
  scope
1131
1396
  }) ?? null;
1132
1397
  if (skillsDir) {
1133
- const sk = p$1.spinner();
1134
- sk.start("Installing the Sequel skill…");
1398
+ const sk = interactive ? p$1.spinner() : null;
1399
+ sk?.start("Installing the Sequel skill…");
1135
1400
  try {
1136
1401
  const markdown = await fetchSkillMarkdown();
1137
1402
  const written = installSkill({
1138
1403
  dir: skillsDir,
1139
1404
  markdown
1140
1405
  });
1141
- sk.stop("Sequel skill installed.");
1142
- p$1.log.info(`Skill written to ${pc.dim(written.path)}`);
1406
+ sk ? sk.stop("Sequel skill installed.") : success("Sequel skill installed.");
1407
+ info(`Skill written to ${pc.dim(written.path)}`);
1143
1408
  } catch (err) {
1144
- sk.stop("Could not install the Sequel skill.");
1145
- p$1.log.warn(`${err instanceof Error ? err.message : String(err)}\nSequel still works through MCP; rerun \`sequel install ${client.slug}\` later to add the skill.`);
1409
+ sk?.stop("Could not install the Sequel skill.");
1410
+ const warning = `${err instanceof Error ? err.message : String(err)}\nSequel still works through MCP; rerun \`sequel install ${client.slug}\` later to add the skill.`;
1411
+ if (interactive) p$1.log.warn(warning);
1412
+ else info(`Could not install the Sequel skill. ${warning}`);
1146
1413
  }
1147
- } else p$1.log.info(`${client.name} has no skills directory the CLI can write to; the Sequel skill is skipped. Playbooks are still available through MCP.`);
1148
- p$1.outro(`Restart ${client.name} and ask it to "list my Sequel connections" to verify.`);
1414
+ } else info(`${client.name} has no skills directory the CLI can write to; the Sequel skill is skipped. Playbooks are still available through MCP.`);
1415
+ const done = `Restart ${client.name} and ask it to "list my Sequel connections" to verify.`;
1416
+ if (interactive) p$1.outro(done);
1417
+ else info(done);
1149
1418
  }
1150
1419
 
1151
1420
  //#endregion
@@ -1287,7 +1556,7 @@ async function upgradeCommand() {
1287
1556
  //#endregion
1288
1557
  //#region src/index.ts
1289
1558
  const program = new Command();
1290
- program.name("sequel").description("Sequel CLI — connect data sources and run tools from your terminal").version("0.1.0").option("--json", "output machine-readable JSON").enablePositionalOptions();
1559
+ program.name("sequel").description("Sequel CLI — connect data sources and run tools from your terminal").version(package_default.version).option("--json", "output machine-readable JSON").enablePositionalOptions();
1291
1560
  /** Wrap a command action with shared --json handling and error reporting. */
1292
1561
  function action(fn) {
1293
1562
  return async (...args) => {
@@ -1302,7 +1571,8 @@ function action(fn) {
1302
1571
  };
1303
1572
  }
1304
1573
  program.command("upgrade").description("Upgrade the Sequel CLI to the latest version").action(action(upgradeCommand));
1305
- program.command("login").description("Sign in to Sequel").action(action(loginCommand));
1574
+ program.command("login").description("Sign in to Sequel").option("--no-browser", "print the sign-in URL instead of opening a browser").option("--detach", "print the sign-in URL and return; finish signing in in the background (default when piped)").option("--status", "report whether you are signed in, or a sign-in is pending, without starting one").option("--wait", "block until a pending background sign-in finishes").action(action(loginCommand));
1575
+ program.command("login-worker", { hidden: true }).option("--no-browser").action(action(loginWorkerCommand));
1306
1576
  program.command("logout").description("Sign out and remove cached credentials").action(action(logoutCommand));
1307
1577
  program.command("switch").description("Switch the active organization").action(action(switchCommand));
1308
1578
  program.command("connect").argument("[source]", "connector id (e.g. postgres); omit to choose interactively").description("Connect a new data source").action(action(connectCommand));
@@ -1314,7 +1584,7 @@ sources.command("delete").argument("[id]", "source id or short id").description(
1314
1584
  const skills = program.command("skills").description("Browse the playbooks your agent can follow");
1315
1585
  skills.command("list", { isDefault: true }).description("List every skill (id and name)").action(action(skillsList));
1316
1586
  skills.command("show").argument("<id>", "skill id, e.g. seo").description("Print a skill's playbook").action(action((id) => skillsShow(id)));
1317
- program.command("install").argument("[agent]", "coding agent slug (e.g. cursor, claude-code)").description("Install the Sequel MCP server into a coding agent").action(action(installCommand));
1587
+ program.command("install").argument("[agent]", "coding agent slug (e.g. cursor, claude-code)").option("-s, --scope <scope>", "global or local; skips the prompt (defaults to global when piped)").option("--no-browser", "print the sign-in URL instead of opening a browser if sign-in is needed").description("Install the Sequel MCP server into a coding agent").action(action(installCommand));
1318
1588
  program.command("search").argument("<usecase>", "what you want to do, e.g. \"monthly revenue\"").option("-c, --connection <id...>", "limit to specific connection short ids").description("Find the right tools for a use case across your sources").action(action((usecase, opts) => searchCommand(usecase, opts)));
1319
1589
  program.command("execute").argument("<connection_id>", "connection short id").argument("<tool>", "tool id, e.g. postgres.query").option("-d, --data <json>", "tool input as a JSON string").description("Execute a tool against a connection").action(action((connectionId, tool, opts) => executeCommand(connectionId, tool, opts)));
1320
1590
  program.command("download").argument("<session_id>", "session id (from `sequel search` or an agent session)").argument("<path>", "file path, e.g. /data/result.csv or result.csv").option("-o, --output <file>", "write to this path (default: the file's own name)").description("Download a file produced by a query or workbench run").action(action((sessionId, path, opts) => downloadCommand(sessionId, path, opts)));
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["config?: AuthConfig | null","config: AuthConfig","isLoggedIn","buf: Buffer","apiUrl: string","params: Record<string, string>","redirectUri: string","accessToken: string","expectedState: string","resolveCode!: (code: string) => void","rejectCode!: (err: Error) => void","title: string","message: string","options?: { silent?: boolean }","next: AuthConfig","entry: TokenEntry","status: number","message: string","path: string","options: RequestOptions","headers: Record<string, string>","body: string | undefined","text","id: string","appId: string","body: Record<string, unknown>","token: string","connectionId: string","tool: string","params: Record<string, unknown>","useCase: string","connectionIds?: string[]","name: string","sessionId: string","on: boolean","data: unknown","value: unknown","rows: Array<Record<string, unknown>>","columns?: string[]","message: string","connector: Connector","token: string","source?: string","connector: Connector | undefined","credentials: Record<string, string>","p","s","res","result","idOrShort: string","message: string","c: Connection","idOrShort?: string","config: { schemaFilters: string[] | null; instructions: string | null } | null","path: string","skills","slug: string","slugArg?: string","result","scope: Scope","key: string","useCase: string","opts: { connection?: string[] }","connectionId: string","tool: string","opts: { data?: string }","params: Record<string, unknown>","n: number","sessionId: string","filePath: string","opts: { output?: string }","MANAGERS: Manager[]","cmd: string","fn: (...args: A) => Promise<void>","id: string","usecase: string","opts: { connection?: string[] }","connectionId: string","tool: string","opts: { data?: string }","sessionId: string","path: string","opts: { output?: string }"],"sources":["../src/lib/config.ts","../src/lib/auth.ts","../src/lib/api.ts","../src/lib/output.ts","../src/commands/login.ts","../src/commands/logout.ts","../src/commands/switch.ts","../src/commands/connect.ts","../src/commands/sources.ts","../src/commands/skills.ts","../../mcp-clients/dist/install.js","../src/lib/skills.ts","../src/commands/install.ts","../src/commands/search.ts","../src/commands/execute.ts","../src/commands/download.ts","../src/commands/upgrade.ts","../src/index.ts"],"sourcesContent":["import { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { mkdirSync, readFileSync, writeFileSync, rmSync, existsSync, chmodSync } from \"node:fs\";\n\n/** Default production API base. Override with SEQUEL_API_URL for local/dev. */\nexport const DEFAULT_API_URL = \"https://api.sequel.sh\";\n\n/** Default marketing site, which publishes the Sequel skill. Override with SEQUEL_SITE_URL. */\nexport const DEFAULT_SITE_URL = \"https://sequel.sh\";\n\nexport function resolveSiteUrl(): string {\n return process.env.SEQUEL_SITE_URL || DEFAULT_SITE_URL;\n}\n\n/** One OAuth token bundle, scoped to a single organization. */\nexport interface TokenEntry {\n accessToken: string;\n refreshToken: string;\n /** ms epoch when the access token expires. */\n expiresAt: number;\n}\n\nexport interface OrgRef {\n id: string;\n name: string;\n slug: string;\n role: string;\n}\n\nexport interface UserRef {\n id: string;\n email: string;\n name: string;\n}\n\n/**\n * The on-disk shape of ~/.sequel/auth.json.\n *\n * Multi-token cache: one genuine org-bound OAuth token per organization, keyed\n * by org id. `activeOrgId` selects which token requests use right now. Switching\n * orgs is an offline swap when the target org already has a cached token.\n */\nexport interface AuthConfig {\n version: 1;\n apiUrl: string;\n /** Persisted dynamic client registration, reused across logins. */\n clientId?: string;\n activeOrgId?: string;\n tokens: Record<string, TokenEntry>;\n user?: UserRef;\n /** Cached membership list for the `switch` UI. */\n orgs?: OrgRef[];\n}\n\n/** Directory holding the CLI's state. Overridable for tests. */\nexport function configDir(): string {\n return process.env.SEQUEL_CONFIG_DIR || join(homedir(), \".sequel\");\n}\n\nexport function configPath(): string {\n return join(configDir(), \"auth.json\");\n}\n\n/** The API base URL: explicit env wins, then a saved value, then the default. */\nexport function resolveApiUrl(config?: AuthConfig | null): string {\n return process.env.SEQUEL_API_URL || config?.apiUrl || DEFAULT_API_URL;\n}\n\nfunction emptyConfig(): AuthConfig {\n return { version: 1, apiUrl: resolveApiUrl(), tokens: {} };\n}\n\n/** Read auth.json, returning a fresh empty config if missing or corrupt. */\nexport function readConfig(): AuthConfig {\n const path = configPath();\n if (!existsSync(path)) return emptyConfig();\n try {\n const parsed = JSON.parse(readFileSync(path, \"utf8\")) as AuthConfig;\n if (!parsed || typeof parsed !== \"object\" || !parsed.tokens) return emptyConfig();\n parsed.tokens ??= {};\n return parsed;\n } catch {\n // Corrupt file — start clean rather than crash.\n return emptyConfig();\n }\n}\n\n/** Persist auth.json with locked-down permissions (dir 0700, file 0600). */\nexport function writeConfig(config: AuthConfig): void {\n const dir = configDir();\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n const path = configPath();\n writeFileSync(path, `${JSON.stringify(config, null, 2)}\\n`, { mode: 0o600 });\n // writeFileSync only applies mode on create; enforce it on existing files too.\n chmodSync(path, 0o600);\n}\n\n/** Remove all stored credentials. Idempotent. */\nexport function clearConfig(): void {\n const path = configPath();\n if (existsSync(path)) rmSync(path);\n}\n\nexport function isLoggedIn(config: AuthConfig): boolean {\n return Boolean(config.activeOrgId && config.tokens[config.activeOrgId]);\n}\n","import { createHash, randomBytes } from \"node:crypto\";\nimport { createServer } from \"node:http\";\nimport { AddressInfo } from \"node:net\";\nimport open from \"open\";\nimport {\n type AuthConfig,\n type OrgRef,\n type TokenEntry,\n type UserRef,\n readConfig,\n writeConfig,\n resolveApiUrl,\n} from \"./config\";\n\n/** Refresh a token this many ms before it actually expires. */\nconst EXPIRY_SKEW_MS = 60_000;\n\nfunction base64url(buf: Buffer): string {\n return buf.toString(\"base64url\");\n}\n\n/** PKCE pair: challenge = base64url(sha256(verifier)), matching the API's S256. */\nexport function generatePkce(): { verifier: string; challenge: string } {\n const verifier = base64url(randomBytes(32));\n const challenge = base64url(createHash(\"sha256\").update(verifier).digest());\n return { verifier, challenge };\n}\n\ninterface TokenResponse {\n access_token: string;\n refresh_token: string;\n expires_in: number;\n token_type: string;\n}\n\ninterface WhoAmI {\n id: string;\n name: string;\n email: string;\n organizationId: string;\n}\n\n/** POST the OAuth token endpoint (form-encoded, per RFC 6749). */\nasync function postToken(apiUrl: string, params: Record<string, string>): Promise<TokenResponse> {\n const res = await fetch(`${apiUrl}/oauth/token`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams(params).toString(),\n });\n if (!res.ok) {\n const body = await res.text().catch(() => \"\");\n throw new Error(`Token request failed (${res.status}): ${body}`);\n }\n return (await res.json()) as TokenResponse;\n}\n\n/** Register a fresh dynamic OAuth client bound to this run's loopback URI. */\nasync function registerClient(apiUrl: string, redirectUri: string): Promise<string> {\n const res = await fetch(`${apiUrl}/oauth/register`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ client_name: \"Sequel CLI\", redirect_uris: [redirectUri] }),\n });\n if (!res.ok) {\n const body = await res.text().catch(() => \"\");\n throw new Error(`Client registration failed (${res.status}): ${body}`);\n }\n const data = (await res.json()) as { client_id: string };\n return data.client_id;\n}\n\nasync function fetchWhoAmI(apiUrl: string, accessToken: string): Promise<WhoAmI> {\n const res = await fetch(`${apiUrl}/users/me`, {\n headers: { Authorization: `Bearer ${accessToken}` },\n });\n if (!res.ok) throw new Error(`Failed to resolve identity (${res.status})`);\n return (await res.json()) as WhoAmI;\n}\n\nexport async function fetchOrganizations(apiUrl: string, accessToken: string): Promise<OrgRef[]> {\n const res = await fetch(`${apiUrl}/organizations`, {\n headers: { Authorization: `Bearer ${accessToken}` },\n });\n if (!res.ok) throw new Error(`Failed to list organizations (${res.status})`);\n const rows = (await res.json()) as Array<{\n role: string;\n organization: { id: string; name: string; slug: string };\n }>;\n return rows.map((r) => ({\n id: r.organization.id,\n name: r.organization.name,\n slug: r.organization.slug,\n role: r.role,\n }));\n}\n\n/**\n * Wait for the browser to hit the loopback redirect and hand back `?code&state`.\n * Resolves with the authorization code once `state` is verified.\n */\nfunction waitForCallback(\n expectedState: string,\n): { server: ReturnType<typeof createServer>; port: Promise<number>; code: Promise<string> } {\n let resolveCode!: (code: string) => void;\n let rejectCode!: (err: Error) => void;\n const code = new Promise<string>((resolve, reject) => {\n resolveCode = resolve;\n rejectCode = reject;\n });\n\n const server = createServer((req, res) => {\n const url = new URL(req.url ?? \"/\", \"http://127.0.0.1\");\n if (url.pathname !== \"/callback\") {\n res.writeHead(404).end(\"Not found\");\n return;\n }\n const error = url.searchParams.get(\"error\");\n const returnedState = url.searchParams.get(\"state\");\n const returnedCode = url.searchParams.get(\"code\");\n\n const finish = (title: string, message: string) => {\n res.writeHead(200, { \"Content-Type\": \"text/html; charset=utf-8\" });\n res.end(\n `<!doctype html><html><head><title>${title}</title></head><body style=\"font-family:system-ui;padding:3rem;text-align:center\"><h2>${title}</h2><p>${message}</p><p>You can close this tab and return to your terminal.</p></body></html>`,\n );\n };\n\n if (error) {\n finish(\"Sign-in failed\", `The authorization server returned: ${error}`);\n rejectCode(new Error(`Authorization failed: ${error}`));\n return;\n }\n if (!returnedState || returnedState !== expectedState) {\n finish(\"Sign-in failed\", \"State mismatch — possible CSRF. Please try again.\");\n rejectCode(new Error(\"State mismatch in OAuth callback\"));\n return;\n }\n if (!returnedCode) {\n finish(\"Sign-in failed\", \"No authorization code was returned.\");\n rejectCode(new Error(\"Missing authorization code\"));\n return;\n }\n finish(\"Signed in to Sequel\", \"Authentication complete.\");\n resolveCode(returnedCode);\n });\n\n const port = new Promise<number>((resolve, reject) => {\n server.on(\"error\", reject);\n server.listen(0, \"127.0.0.1\", () => resolve((server.address() as AddressInfo).port));\n });\n\n return { server, port, code };\n}\n\nexport interface LoginResult {\n user: UserRef;\n org: OrgRef | undefined;\n organizationId: string;\n}\n\n/**\n * Run the full OAuth 2.0 + PKCE loopback flow: register a client, open the\n * browser to the consent page (where the user picks an org), capture the code,\n * exchange it for an org-bound token, then cache that token keyed by its org.\n *\n * Shared by `login` and `switch` (for orgs without a cached token).\n */\nexport async function runLoginFlow(options?: { silent?: boolean }): Promise<LoginResult> {\n const config = readConfig();\n const apiUrl = resolveApiUrl(config);\n\n const { verifier, challenge } = generatePkce();\n const state = base64url(randomBytes(16));\n\n const { server, port: portPromise, code: codePromise } = waitForCallback(state);\n const port = await portPromise;\n const redirectUri = `http://127.0.0.1:${port}/callback`;\n\n try {\n const clientId = await registerClient(apiUrl, redirectUri);\n\n const authorizeUrl = new URL(`${apiUrl}/oauth/authorize`);\n authorizeUrl.searchParams.set(\"client_id\", clientId);\n authorizeUrl.searchParams.set(\"redirect_uri\", redirectUri);\n authorizeUrl.searchParams.set(\"response_type\", \"code\");\n authorizeUrl.searchParams.set(\"code_challenge\", challenge);\n authorizeUrl.searchParams.set(\"code_challenge_method\", \"S256\");\n authorizeUrl.searchParams.set(\"state\", state);\n\n if (!options?.silent) {\n // open() can fail in headless envs — never block the flow on it.\n open(authorizeUrl.toString()).catch(() => {});\n }\n // Always surface the URL so the user can open it manually if needed.\n process.stderr.write(`\\nOpen this URL to continue:\\n${authorizeUrl.toString()}\\n\\n`);\n\n const code = await codePromise;\n\n const token = await postToken(apiUrl, {\n grant_type: \"authorization_code\",\n code,\n redirect_uri: redirectUri,\n client_id: clientId,\n code_verifier: verifier,\n });\n\n const me = await fetchWhoAmI(apiUrl, token.access_token);\n const orgs = await fetchOrganizations(apiUrl, token.access_token).catch(() => config.orgs ?? []);\n\n const next: AuthConfig = {\n ...config,\n version: 1,\n apiUrl,\n clientId,\n activeOrgId: me.organizationId,\n tokens: {\n ...config.tokens,\n [me.organizationId]: {\n accessToken: token.access_token,\n refreshToken: token.refresh_token,\n expiresAt: Date.now() + token.expires_in * 1000,\n },\n },\n user: { id: me.id, email: me.email, name: me.name },\n orgs,\n };\n writeConfig(next);\n\n return {\n user: next.user!,\n org: orgs.find((o) => o.id === me.organizationId),\n organizationId: me.organizationId,\n };\n } finally {\n server.close();\n }\n}\n\n/** True when there's a cached token for the active org (cheap, non-throwing). */\nexport function isLoggedIn(): boolean {\n const config = readConfig();\n const orgId = config.activeOrgId;\n return Boolean(orgId && config.tokens[orgId]);\n}\n\n/**\n * Return a valid access token for the active org, refreshing it in place when\n * expired. Throws a friendly error if there is no token or the refresh fails.\n */\nexport async function getValidAccessToken(): Promise<{ token: string; config: AuthConfig }> {\n const config = readConfig();\n const orgId = config.activeOrgId;\n if (!orgId || !config.tokens[orgId]) {\n throw new Error(\"Not logged in. Run `sequel login` first.\");\n }\n\n const entry: TokenEntry = config.tokens[orgId];\n if (entry.expiresAt - EXPIRY_SKEW_MS > Date.now()) {\n return { token: entry.accessToken, config };\n }\n\n // Access token expired — rotate via the refresh grant.\n const apiUrl = resolveApiUrl(config);\n try {\n const refreshed = await postToken(apiUrl, {\n grant_type: \"refresh_token\",\n refresh_token: entry.refreshToken,\n client_id: config.clientId ?? \"\",\n });\n config.tokens[orgId] = {\n accessToken: refreshed.access_token,\n refreshToken: refreshed.refresh_token,\n expiresAt: Date.now() + refreshed.expires_in * 1000,\n };\n writeConfig(config);\n return { token: refreshed.access_token, config };\n } catch {\n throw new Error(\n \"Your session for this organization has expired. Run `sequel login` (or `sequel switch`) to sign in again.\",\n );\n }\n}\n","import { getValidAccessToken } from \"./auth\";\nimport { resolveApiUrl } from \"./config\";\n\nexport class ApiError extends Error {\n constructor(\n public status: number,\n message: string,\n ) {\n super(message);\n this.name = \"ApiError\";\n }\n}\n\ninterface RequestOptions {\n method?: string;\n query?: Record<string, string | undefined>;\n body?: Record<string, unknown>;\n /**\n * How the active org id is attached to the request:\n * - \"query\" → ?organizationId=<org> (default; most GET/DELETE routes)\n * - \"organizationId\" → merged into the JSON body as organizationId\n * - \"organization_id\" → merged into the JSON body as organization_id (execute)\n * - \"none\" → not attached (e.g. /connectors, /oauth/*)\n */\n org?: \"query\" | \"organizationId\" | \"organization_id\" | \"none\";\n}\n\n/**\n * Authenticated request against the Sequel API using the active org's token.\n * Refreshes the token transparently and scopes the call to that org.\n */\nexport async function request<T = unknown>(path: string, options: RequestOptions = {}): Promise<T> {\n const { token, config } = await getValidAccessToken();\n const apiUrl = resolveApiUrl(config);\n const orgId = config.activeOrgId;\n const orgMode = options.org ?? \"query\";\n\n const url = new URL(`${apiUrl}${path}`);\n if (orgMode === \"query\" && orgId) url.searchParams.set(\"organizationId\", orgId);\n for (const [k, v] of Object.entries(options.query ?? {})) {\n if (v !== undefined) url.searchParams.set(k, v);\n }\n\n let bodyObj = options.body;\n if ((orgMode === \"organizationId\" || orgMode === \"organization_id\") && orgId) {\n bodyObj = { ...(bodyObj ?? {}), [orgMode]: orgId };\n }\n\n const headers: Record<string, string> = { Authorization: `Bearer ${token}` };\n let body: string | undefined;\n if (bodyObj !== undefined) {\n headers[\"Content-Type\"] = \"application/json\";\n body = JSON.stringify(bodyObj);\n }\n\n const res = await fetch(url.toString(), { method: options.method ?? \"GET\", headers, body });\n\n if (!res.ok) {\n let message = `Request failed (${res.status})`;\n const text = await res.text().catch(() => \"\");\n try {\n const json = JSON.parse(text) as { error?: string };\n if (json.error) message = json.error;\n } catch {\n if (text) message = text;\n }\n throw new ApiError(res.status, message);\n }\n\n if (res.status === 204) return undefined as T;\n const text = await res.text();\n return (text ? JSON.parse(text) : undefined) as T;\n}\n\n/** The active organization id, or throws if not logged in. */\nexport async function activeOrgId(): Promise<string> {\n const { config } = await getValidAccessToken();\n if (!config.activeOrgId) throw new Error(\"No active organization. Run `sequel login`.\");\n return config.activeOrgId;\n}\n\n// ── Types ──────────────────────────────────────────────────────────────────────\n\nexport interface Connector {\n id: string;\n name: string;\n description: string;\n icon: string;\n appType: \"database\" | \"app\" | \"mcp\";\n live: boolean;\n authId: string;\n credentialsSchema?: Record<string, unknown>;\n userInputFields?: string[];\n canResolveName?: boolean;\n configuration?: { type: string } | null;\n}\n\nexport interface Connection {\n id: string;\n shortId: string;\n name: string;\n type: string;\n createdBy?: string;\n createdAt: string;\n updatedAt: string;\n}\n\nexport type LinkCreateResponse =\n | { status: \"success\"; connection: Connection }\n | { status: \"pending\"; link_token: string; redirect_url: string; expires_at: string };\n\nexport interface LinkStatus {\n status: \"pending\" | \"oauth_in_progress\" | \"awaiting_configuration\" | \"success\" | \"failed\" | \"completed\";\n connectionId?: string;\n connection_id?: string;\n reason?: string;\n}\n\nexport interface ExecuteResult {\n data: Array<Record<string, unknown>>;\n columns: string[];\n row_count: number;\n truncated: boolean;\n}\n\nexport interface SearchToolRef {\n tool_id: string;\n input_schema: Record<string, unknown>;\n output_schema: Record<string, unknown> | null;\n relevant_tables: string[];\n}\n\nexport interface SearchResult {\n connection_id: string;\n connection_name: string;\n app_id: string;\n use_case: string;\n instructions: string;\n tools: SearchToolRef[];\n}\n\n// ── Endpoint wrappers ───────────────────────────────────────────────────────────\n\nexport function listConnectors(): Promise<Connector[]> {\n return request<Connector[]>(\"/connectors\", { org: \"none\" });\n}\n\nexport function listConnections(): Promise<Connection[]> {\n return request<Connection[]>(\"/connections\");\n}\n\nexport function getConnection(id: string): Promise<Connection> {\n return request<Connection>(`/connections/${id}`);\n}\n\nexport function deleteConnection(id: string): Promise<Connection> {\n return request<Connection>(`/connections/${id}`, { method: \"DELETE\" });\n}\n\nexport function testConnection(id: string): Promise<{ success: boolean; message: string }> {\n return request(`/connections/${id}/test`, { method: \"POST\", org: \"organizationId\" });\n}\n\nexport function getConnectionConfig(\n id: string,\n): Promise<{ schemaFilters: string[] | null; instructions: string | null }> {\n return request(`/connections/${id}/config`);\n}\n\n/** Mint a connect link / create a connection for the given connector. */\nexport function createLink(appId: string, body: Record<string, unknown>): Promise<LinkCreateResponse> {\n // POST /link/:appId resolves the org from the token's session, which always\n // matches the active org in the multi-token model — no org param needed.\n return request<LinkCreateResponse>(`/link/${appId}`, { method: \"POST\", org: \"none\", body });\n}\n\n/**\n * Poll a connect link's status. Uses the authenticated route, which (unlike the\n * public one) reports terminal states — `completed`/`failed` — so the CLI can\n * tell when the browser flow has finished.\n */\nexport function getLinkStatus(token: string): Promise<LinkStatus> {\n return request<LinkStatus>(`/link/${token}/status`, { org: \"none\" });\n}\n\nexport function execute(\n connectionId: string,\n tool: string,\n params: Record<string, unknown>,\n): Promise<ExecuteResult> {\n return request<ExecuteResult>(\"/execute\", {\n method: \"POST\",\n org: \"organization_id\",\n body: { connection_id: connectionId, tool, params },\n });\n}\n\nexport function search(useCase: string, connectionIds?: string[]): Promise<{ results: SearchResult[] }> {\n return request<{ results: SearchResult[] }>(\"/search\", {\n method: \"POST\",\n org: \"organization_id\",\n body: {\n action_info: `CLI search: ${useCase}`,\n use_case: useCase,\n connection_ids: connectionIds,\n },\n });\n}\n\nexport async function createApiKey(name: string): Promise<{ key: string; keyPrefix: string }> {\n const orgId = await activeOrgId();\n return request(`/organizations/${orgId}/api-keys`, { method: \"POST\", org: \"none\", body: { name } });\n}\n\nexport interface FileDownloadInfo {\n url: string;\n filename: string;\n size: number;\n expires_in_seconds: number;\n}\n\n/** Get a signed URL to download a file produced in a session (by sequel_execute / workbench). */\nexport function getFileDownloadUrl(sessionId: string, path: string): Promise<FileDownloadInfo> {\n return request<FileDownloadInfo>(\"/files/download\", { query: { session_id: sessionId, path } });\n}\n","import pc from \"picocolors\";\n\nexport { pc };\n\n/** True when the user passed a global --json flag (set by index.ts). */\nlet jsonMode = false;\nexport function setJsonMode(on: boolean): void {\n jsonMode = on;\n}\nexport function isJsonMode(): boolean {\n return jsonMode;\n}\n\nexport function printJson(data: unknown): void {\n process.stdout.write(`${JSON.stringify(data, null, 2)}\\n`);\n}\n\nfunction cell(value: unknown): string {\n if (value === null || value === undefined) return \"\";\n if (typeof value === \"object\") return JSON.stringify(value);\n return String(value);\n}\n\n/**\n * Render an array of records as an aligned text table. `columns` controls order\n * and which keys are shown; defaults to the union of keys in the first row.\n */\nexport function renderTable(rows: Array<Record<string, unknown>>, columns?: string[]): string {\n if (rows.length === 0) return pc.dim(\"(no rows)\");\n const cols = columns ?? Object.keys(rows[0]);\n const widths = cols.map((c) => Math.max(c.length, ...rows.map((r) => cell(r[c]).length)));\n\n const header = cols.map((c, i) => pc.bold(c.padEnd(widths[i]))).join(\" \");\n const sep = cols.map((_, i) => \"─\".repeat(widths[i])).join(\" \");\n const body = rows\n .map((r) => cols.map((c, i) => cell(r[c]).padEnd(widths[i])).join(\" \"))\n .join(\"\\n\");\n\n return `${header}\\n${pc.dim(sep)}\\n${body}`;\n}\n\nexport function printTable(rows: Array<Record<string, unknown>>, columns?: string[]): void {\n // Never emit human tables to stdout in JSON mode — keep stdout valid JSON for jq.\n if (jsonMode) return;\n process.stdout.write(`${renderTable(rows, columns)}\\n`);\n}\n\n// In JSON mode, human-facing lines go to stderr so stdout stays pure JSON.\nexport function success(message: string): void {\n (jsonMode ? process.stderr : process.stdout).write(`${pc.green(\"✓\")} ${message}\\n`);\n}\n\nexport function info(message: string): void {\n (jsonMode ? process.stderr : process.stdout).write(`${message}\\n`);\n}\n\nexport function fail(message: string): void {\n process.stderr.write(`${pc.red(\"✗\")} ${message}\\n`);\n}\n","import * as p from \"@clack/prompts\";\nimport { runLoginFlow } from \"../lib/auth\";\nimport { info, isJsonMode, pc, printJson, success } from \"../lib/output\";\n\nexport async function loginCommand(): Promise<void> {\n const json = isJsonMode();\n if (json) {\n info(\"Opening your browser to authorize…\"); // → stderr in JSON mode\n } else {\n p.intro(pc.cyan(\"Sign in to Sequel\"));\n p.log.info(\"Opening your browser to authorize…\");\n }\n\n const res = await runLoginFlow();\n\n if (json) return printJson({ status: \"logged_in\", user: res.user, org: res.org ?? null });\n success(`Logged in as ${pc.bold(res.user.email)}${res.org ? ` · ${pc.bold(res.org.name)}` : \"\"}`);\n p.outro(\"You're all set. Try `sequel sources list` or `sequel connect`.\");\n}\n","import { clearConfig, isLoggedIn, readConfig } from \"../lib/config\";\nimport { info, isJsonMode, printJson, success } from \"../lib/output\";\n\nexport async function logoutCommand(): Promise<void> {\n const config = readConfig();\n if (!isLoggedIn(config)) {\n if (isJsonMode()) return printJson({ status: \"not_logged_in\" });\n info(\"You are not logged in.\");\n return;\n }\n clearConfig();\n if (isJsonMode()) return printJson({ status: \"logged_out\" });\n success(\"Logged out. Cached credentials removed from ~/.sequel/auth.json.\");\n}\n","import * as p from \"@clack/prompts\";\nimport { fetchOrganizations, getValidAccessToken, runLoginFlow } from \"../lib/auth\";\nimport { isLoggedIn, readConfig, resolveApiUrl, writeConfig } from \"../lib/config\";\nimport { isJsonMode, pc, success } from \"../lib/output\";\n\nexport async function switchCommand(): Promise<void> {\n if (isJsonMode()) {\n throw new Error(\n \"`sequel switch` is interactive (it prompts for an organization) — run it in a terminal, not piped/--json.\",\n );\n }\n const config = readConfig();\n if (!isLoggedIn(config)) {\n throw new Error(\"Not logged in. Run `sequel login` first.\");\n }\n\n // Refresh the membership list with the active org's token.\n let orgs = config.orgs ?? [];\n try {\n const { token } = await getValidAccessToken();\n orgs = await fetchOrganizations(resolveApiUrl(config), token);\n writeConfig({ ...readConfig(), orgs });\n } catch {\n // fall back to cached orgs\n }\n if (orgs.length === 0) throw new Error(\"No organizations available for this account.\");\n\n const selection = await p.select({\n message: \"Switch to organization\",\n options: orgs.map((o) => ({\n value: o.id,\n label: o.id === config.activeOrgId ? `${o.name} ${pc.dim(\"(current)\")}` : o.name,\n hint: config.tokens[o.id] ? o.role : \"sign-in required\",\n })),\n });\n if (p.isCancel(selection)) {\n p.cancel(\"Cancelled.\");\n return;\n }\n\n const orgId = selection as string;\n const org = orgs.find((o) => o.id === orgId);\n const fresh = readConfig();\n\n if (fresh.tokens[orgId]) {\n // Already authorized — instant, offline swap.\n writeConfig({ ...fresh, activeOrgId: orgId });\n success(`Switched to ${pc.bold(org?.name ?? orgId)}.`);\n return;\n }\n\n // No cached token for this org — sign in so the user can authorize it.\n p.log.info(`You haven't authorized ${pc.bold(org?.name ?? orgId)} yet — opening your browser…`);\n const res = await runLoginFlow();\n success(`Switched to ${pc.bold(res.org?.name ?? res.organizationId)}.`);\n}\n","import * as p from \"@clack/prompts\";\nimport open from \"open\";\nimport {\n type Connector,\n createLink,\n getLinkStatus,\n listConnectors,\n} from \"../lib/api\";\nimport { info, isJsonMode, pc, success } from \"../lib/output\";\n\nconst SECRET_RE = /pass|secret|token|key|connection|credential/i;\n\nfunction fieldsFor(connector: Connector): string[] {\n if (connector.userInputFields?.length) return connector.userInputFields;\n const props = (connector.credentialsSchema as { properties?: Record<string, unknown> } | undefined)?.properties;\n return props ? Object.keys(props) : [];\n}\n\nfunction isOAuth(connector: Connector): boolean {\n return Boolean(connector.configuration) || /oauth/i.test(connector.authId);\n}\n\n/** Poll a pending connect link until it completes or fails (or times out). */\nasync function pollLink(token: string): Promise<{ ok: boolean; reason?: string }> {\n const deadline = Date.now() + 5 * 60_000;\n while (Date.now() < deadline) {\n await new Promise((r) => setTimeout(r, 2000));\n let status;\n try {\n status = await getLinkStatus(token);\n } catch {\n continue; // transient — keep polling\n }\n if (status.status === \"failed\") return { ok: false, reason: status.reason };\n if (status.status === \"success\" || status.status === \"completed\") return { ok: true };\n }\n return { ok: false, reason: \"Timed out waiting for the browser to finish.\" };\n}\n\nexport async function connectCommand(source?: string): Promise<void> {\n if (isJsonMode()) {\n throw new Error(\n \"`sequel connect` is interactive (it prompts for credentials/consent) — run it in a terminal, not piped/--json.\",\n );\n }\n const connectors = await listConnectors();\n\n let connector: Connector | undefined;\n if (source) {\n connector = connectors.find((c) => c.id === source);\n if (!connector) {\n throw new Error(\n `Unknown connector \"${source}\". Available: ${connectors.map((c) => c.id).join(\", \")}`,\n );\n }\n } else {\n const choice = await p.select({\n message: \"Which data source do you want to connect?\",\n options: connectors\n .slice()\n .sort((a, b) => a.appType.localeCompare(b.appType) || a.name.localeCompare(b.name))\n .map((c) => ({ value: c.id, label: c.name, hint: c.appType })),\n });\n if (p.isCancel(choice)) {\n p.cancel(\"Cancelled.\");\n return;\n }\n connector = connectors.find((c) => c.id === (choice as string))!;\n }\n\n p.intro(`Connect ${pc.bold(connector.name)}`);\n\n if (!isOAuth(connector)) {\n // Pre-auth connector: collect credential fields in the terminal.\n const fields = fieldsFor(connector);\n const credentials: Record<string, string> = {};\n for (const field of fields) {\n const secret = SECRET_RE.test(field);\n const value = await (secret ? p.password : p.text)({\n message: field,\n });\n if (p.isCancel(value)) {\n p.cancel(\"Cancelled.\");\n return;\n }\n credentials[field] = value as string;\n }\n const name = await p.text({ message: \"Name for this source (optional)\", placeholder: connector.name });\n if (p.isCancel(name)) {\n p.cancel(\"Cancelled.\");\n return;\n }\n\n const s = p.spinner();\n s.start(\"Validating credentials…\");\n const res = await createLink(connector.id, {\n credentials,\n ...(name ? { name } : {}),\n });\n if (res.status === \"success\") {\n s.stop(\"Connected.\");\n success(`Created source ${pc.bold(res.connection.name)} (${res.connection.shortId}).`);\n return;\n }\n // Fallback: server wants more input — finish in the browser.\n s.stop(\"Continue in your browser…\");\n open(res.redirect_url).catch(() => {});\n info(`Open: ${res.redirect_url}`);\n const result = await pollLink(res.link_token);\n if (result.ok) success(\"Connected.\");\n else throw new Error(result.reason ?? \"Connection failed.\");\n return;\n }\n\n // OAuth connector: mint a link and let the polished web flow handle consent\n // (and any pre-OAuth fields like a project id), then poll for completion.\n const res = await createLink(connector.id, {});\n if (res.status === \"success\") {\n success(`Created source ${pc.bold(res.connection.name)} (${res.connection.shortId}).`);\n return;\n }\n open(res.redirect_url).catch(() => {});\n info(`Complete authorization in your browser:\\n${res.redirect_url}`);\n const s = p.spinner();\n s.start(\"Waiting for you to finish in the browser…\");\n const result = await pollLink(res.link_token);\n if (result.ok) {\n s.stop(\"Connected.\");\n success(\"Source connected.\");\n } else {\n s.stop(\"Failed.\");\n throw new Error(result.reason ?? \"Connection failed.\");\n }\n}\n","import * as p from \"@clack/prompts\";\nimport {\n type Connection,\n deleteConnection,\n getConnection,\n getConnectionConfig,\n listConnections,\n testConnection,\n} from \"../lib/api\";\nimport { info, isJsonMode, pc, printJson, printTable, success } from \"../lib/output\";\n\n/** Resolve a user-supplied id (uuid or shortId) to the connection's real id. */\nasync function resolveConnection(idOrShort: string): Promise<Connection> {\n const all = await listConnections();\n const match = all.find((c) => c.id === idOrShort || c.shortId === idOrShort);\n if (!match) throw new Error(`No source found matching \"${idOrShort}\".`);\n return match;\n}\n\nasync function pickConnection(message: string): Promise<Connection | undefined> {\n const all = await listConnections();\n if (all.length === 0) {\n info(\"No sources connected yet. Run `sequel connect`.\");\n return undefined;\n }\n const choice = await p.select({\n message,\n options: all.map((c) => ({ value: c.shortId, label: `${c.name} (${c.shortId})`, hint: c.type })),\n });\n if (p.isCancel(choice)) return undefined;\n return all.find((c) => c.shortId === (choice as string));\n}\n\nfunction toRow(c: Connection): Record<string, unknown> {\n return { id: c.shortId, name: c.name, type: c.type, created: c.createdAt.slice(0, 10) };\n}\n\nexport async function sourcesList(): Promise<void> {\n const connections = await listConnections();\n if (isJsonMode()) return printJson(connections);\n if (connections.length === 0) return info(\"No sources connected yet. Run `sequel connect`.\");\n printTable(connections.map(toRow), [\"id\", \"name\", \"type\", \"created\"]);\n}\n\nexport async function sourcesActive(): Promise<void> {\n const connections = await listConnections();\n const rows = await Promise.all(\n connections.map(async (c) => {\n let status = \"unknown\";\n try {\n const t = await testConnection(c.id);\n status = t.success ? \"healthy\" : \"error\";\n } catch {\n status = \"error\";\n }\n return { ...toRow(c), status };\n }),\n );\n if (isJsonMode()) return printJson(rows);\n if (rows.length === 0) return info(\"No sources connected yet. Run `sequel connect`.\");\n printTable(rows, [\"id\", \"name\", \"type\", \"status\", \"created\"]);\n}\n\nexport async function sourcesInfo(idOrShort?: string): Promise<void> {\n const conn = idOrShort ? await resolveConnection(idOrShort) : await pickConnection(\"Source to inspect\");\n if (!conn) return;\n const full = await getConnection(conn.id);\n let config: { schemaFilters: string[] | null; instructions: string | null } | null = null;\n try {\n config = await getConnectionConfig(conn.id);\n } catch {\n /* config may be absent */\n }\n if (isJsonMode()) return printJson({ ...full, config });\n\n info(`${pc.bold(full.name)} ${pc.dim(full.shortId)}`);\n info(`type: ${full.type}`);\n info(`id: ${full.id}`);\n info(`created: ${full.createdAt}`);\n if (config?.schemaFilters?.length) info(`schemas: ${config.schemaFilters.join(\", \")}`);\n if (config?.instructions) info(`\\n${pc.dim(config.instructions)}`);\n}\n\nexport async function sourcesDelete(idOrShort?: string): Promise<void> {\n const conn = idOrShort ? await resolveConnection(idOrShort) : await pickConnection(\"Source to delete\");\n if (!conn) return;\n const confirmed = await p.confirm({ message: `Delete ${pc.bold(conn.name)} (${conn.shortId})? This cannot be undone.` });\n if (p.isCancel(confirmed) || !confirmed) {\n info(\"Cancelled.\");\n return;\n }\n await deleteConnection(conn.id);\n success(`Deleted ${conn.name} (${conn.shortId}).`);\n}\n","import { readConfig, resolveApiUrl } from \"../lib/config\";\nimport { info, isJsonMode, pc, printJson, printTable } from \"../lib/output\";\n\ntype PublicSkill = { id: string; slug: string; name: string; category: string; apps: string[] };\ntype PublicSkillDetail = PublicSkill & { description: string; instructions: string };\n\n// Skills are public, so these hit the unauthenticated marketplace endpoints and\n// work before `sequel login`.\nasync function publicGet<T>(path: string): Promise<T> {\n const res = await fetch(`${resolveApiUrl(readConfig())}${path}`, { headers: { Accept: \"application/json\" } });\n if (res.status === 404) throw new Error(`No skill found matching \"${path.split(\"/\").pop()}\". Run \\`sequel skills list\\`.`);\n if (!res.ok) throw new Error(`Request failed (${res.status})`);\n return (await res.json()) as T;\n}\n\nexport async function skillsList(): Promise<void> {\n const skills = await publicGet<PublicSkill[]>(\"/marketplace/skills\");\n const rows = skills.map((s) => ({ id: s.slug, name: s.name }));\n if (isJsonMode()) return printJson(rows);\n printTable(rows, [\"id\", \"name\"]);\n info(`${rows.length} skills. \\`sequel skills show <id>\\` prints one; \\`sequel install\\` gives your agent all of them.`);\n}\n\nexport async function skillsShow(slug: string): Promise<void> {\n const skill = await publicGet<PublicSkillDetail>(`/marketplace/skills/${encodeURIComponent(slug)}`);\n if (isJsonMode()) return printJson(skill);\n process.stdout.write(\n `${pc.bold(skill.name)} ${pc.dim(skill.slug)}\\n${skill.description}\\n` +\n (skill.apps.length ? `${pc.dim(\"apps:\")} ${skill.apps.join(\", \")}\\n` : \"\") +\n `\\n${skill.instructions}\\n`,\n );\n}\n","import { homedir, platform } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport YAML from \"yaml\";\n\n//#region src/install.ts\nconst SERVER_NAME = \"sequel\";\n/** Folder name of the Sequel skill inside an agent's skills directory. */\nconst SKILL_NAME = \"sequel\";\n/**\n* Write the Sequel SKILL.md into `<dir>/sequel/SKILL.md`, replacing any previous\n* copy. Skill files are plain markdown, so unlike the MCP configs there is\n* nothing to merge: the whole file is ours.\n*/\nfunction installSkill({ dir, markdown }) {\n\tconst path = join(dir, SKILL_NAME, \"SKILL.md\");\n\tmkdirSync(dirname(path), { recursive: true });\n\twriteFileSync(path, markdown.endsWith(\"\\n\") ? markdown : `${markdown}\\n`);\n\treturn {\n\t\tkind: \"file\",\n\t\tpath\n\t};\n}\nconst mcpUrl = (apiUrl) => `${apiUrl.replace(/\\/$/, \"\")}/mcp`;\nconst bearer = (apiKey) => `Bearer ${apiKey}`;\nfunction home(opts) {\n\treturn opts.home ?? homedir();\n}\nfunction cwd(opts) {\n\treturn opts.cwd ?? process.cwd();\n}\n/** OS-specific application-support dir for a vendor folder. */\nfunction appSupport(opts, vendor) {\n\tconst h = home(opts);\n\tswitch (platform()) {\n\t\tcase \"darwin\": return join(h, \"Library\", \"Application Support\", vendor);\n\t\tcase \"win32\": return join(process.env.APPDATA ?? join(h, \"AppData\", \"Roaming\"), vendor);\n\t\tdefault: return join(process.env.XDG_CONFIG_HOME ?? join(h, \".config\"), vendor);\n\t}\n}\n/** Read+merge+write a JSON config, preserving every other key already present. */\nfunction mergeJson(path, mutate) {\n\tlet cfg = {};\n\tif (existsSync(path)) try {\n\t\tcfg = JSON.parse(readFileSync(path, \"utf8\"));\n\t} catch {\n\t\tcfg = {};\n\t}\n\tmutate(cfg);\n\tmkdirSync(dirname(path), { recursive: true });\n\twriteFileSync(path, `${JSON.stringify(cfg, null, 2)}\\n`);\n}\nfunction mergeYaml(path, mutate) {\n\tlet cfg = {};\n\tif (existsSync(path)) try {\n\t\tcfg = YAML.parse(readFileSync(path, \"utf8\")) ?? {};\n\t} catch {\n\t\tcfg = {};\n\t}\n\tmutate(cfg);\n\tmkdirSync(dirname(path), { recursive: true });\n\twriteFileSync(path, YAML.stringify(cfg));\n}\nfunction setNested(cfg, key, value) {\n\tconst obj = cfg[key] ?? {};\n\tobj[SERVER_NAME] = value;\n\tcfg[key] = obj;\n}\nconst mcpClients = [\n\t{\n\t\tslug: \"claude\",\n\t\tname: \"Claude Desktop\",\n\t\tscopes: [\"global\"],\n\t\tdescribe: (o) => join(appSupport(o, \"Claude\"), \"claude_desktop_config.json\"),\n\t\tinstall(o) {\n\t\t\tconst path = join(appSupport(o, \"Claude\"), \"claude_desktop_config.json\");\n\t\t\tmergeJson(path, (cfg) => setNested(cfg, \"mcpServers\", {\n\t\t\t\turl: mcpUrl(o.apiUrl),\n\t\t\t\theaders: { Authorization: bearer(o.apiKey) }\n\t\t\t}));\n\t\t\treturn {\n\t\t\t\tkind: \"file\",\n\t\t\t\tpath\n\t\t\t};\n\t\t}\n\t},\n\t{\n\t\tslug: \"claude-code\",\n\t\tname: \"Claude Code\",\n\t\tscopes: [\"global\", \"local\"],\n\t\tdescribe: (o) => `claude mcp add --scope ${o.scope === \"global\" ? \"user\" : \"local\"} --transport http ${SERVER_NAME} …`,\n\t\tskillsDir: (o) => o.scope === \"global\" ? join(home(o), \".claude\", \"skills\") : join(cwd(o), \".claude\", \"skills\"),\n\t\tinstall(o) {\n\t\t\treturn {\n\t\t\t\tkind: \"command\",\n\t\t\t\tcommand: \"claude\",\n\t\t\t\targs: [\n\t\t\t\t\t\"mcp\",\n\t\t\t\t\t\"add\",\n\t\t\t\t\t\"--scope\",\n\t\t\t\t\to.scope === \"global\" ? \"user\" : \"local\",\n\t\t\t\t\t\"--transport\",\n\t\t\t\t\t\"http\",\n\t\t\t\t\tSERVER_NAME,\n\t\t\t\t\tmcpUrl(o.apiUrl),\n\t\t\t\t\t\"--header\",\n\t\t\t\t\t`Authorization: ${bearer(o.apiKey)}`\n\t\t\t\t]\n\t\t\t};\n\t\t}\n\t},\n\t{\n\t\tslug: \"cursor\",\n\t\tname: \"Cursor\",\n\t\tscopes: [\"global\", \"local\"],\n\t\tdescribe: (o) => o.scope === \"global\" ? join(home(o), \".cursor\", \"mcp.json\") : join(cwd(o), \".cursor\", \"mcp.json\"),\n\t\tinstall(o) {\n\t\t\tconst path = o.scope === \"global\" ? join(home(o), \".cursor\", \"mcp.json\") : join(cwd(o), \".cursor\", \"mcp.json\");\n\t\t\tmergeJson(path, (cfg) => setNested(cfg, \"mcpServers\", {\n\t\t\t\turl: mcpUrl(o.apiUrl),\n\t\t\t\theaders: { Authorization: bearer(o.apiKey) }\n\t\t\t}));\n\t\t\treturn {\n\t\t\t\tkind: \"file\",\n\t\t\t\tpath\n\t\t\t};\n\t\t}\n\t},\n\t{\n\t\tslug: \"vscode\",\n\t\tname: \"VS Code\",\n\t\tscopes: [\"global\", \"local\"],\n\t\tdescribe: (o) => o.scope === \"global\" ? join(appSupport(o, \"Code\"), \"User\", \"mcp.json\") : join(cwd(o), \".vscode\", \"mcp.json\"),\n\t\tinstall(o) {\n\t\t\tconst path = o.scope === \"global\" ? join(appSupport(o, \"Code\"), \"User\", \"mcp.json\") : join(cwd(o), \".vscode\", \"mcp.json\");\n\t\t\tmergeJson(path, (cfg) => setNested(cfg, \"servers\", {\n\t\t\t\turl: mcpUrl(o.apiUrl),\n\t\t\t\ttype: \"http\",\n\t\t\t\theaders: { Authorization: bearer(o.apiKey) }\n\t\t\t}));\n\t\t\treturn {\n\t\t\t\tkind: \"file\",\n\t\t\t\tpath\n\t\t\t};\n\t\t}\n\t},\n\t{\n\t\tslug: \"windsurf\",\n\t\tname: \"Windsurf\",\n\t\tscopes: [\"global\"],\n\t\tdescribe: (o) => join(home(o), \".codeium\", \"windsurf\", \"mcp_config.json\"),\n\t\tinstall(o) {\n\t\t\tconst path = join(home(o), \".codeium\", \"windsurf\", \"mcp_config.json\");\n\t\t\tmergeJson(path, (cfg) => setNested(cfg, \"mcpServers\", {\n\t\t\t\tserverUrl: mcpUrl(o.apiUrl),\n\t\t\t\theaders: { Authorization: bearer(o.apiKey) }\n\t\t\t}));\n\t\t\treturn {\n\t\t\t\tkind: \"file\",\n\t\t\t\tpath\n\t\t\t};\n\t\t}\n\t},\n\t{\n\t\tslug: \"zed\",\n\t\tname: \"Zed\",\n\t\tscopes: [\"global\", \"local\"],\n\t\tdescribe: (o) => o.scope === \"global\" ? join(home(o), \".config\", \"zed\", \"settings.json\") : join(cwd(o), \".zed\", \"settings.json\"),\n\t\tinstall(o) {\n\t\t\tconst path = o.scope === \"global\" ? join(home(o), \".config\", \"zed\", \"settings.json\") : join(cwd(o), \".zed\", \"settings.json\");\n\t\t\tmergeJson(path, (cfg) => setNested(cfg, \"context_servers\", {\n\t\t\t\turl: mcpUrl(o.apiUrl),\n\t\t\t\tsettings: { headers: { Authorization: bearer(o.apiKey) } }\n\t\t\t}));\n\t\t\treturn {\n\t\t\t\tkind: \"file\",\n\t\t\t\tpath\n\t\t\t};\n\t\t}\n\t},\n\t{\n\t\tslug: \"codex\",\n\t\tname: \"Codex\",\n\t\tscopes: [\"global\"],\n\t\tdescribe: (o) => join(home(o), \".codex\", \"config.yaml\"),\n\t\tinstall(o) {\n\t\t\tconst path = join(home(o), \".codex\", \"config.yaml\");\n\t\t\tmergeYaml(path, (cfg) => setNested(cfg, \"mcp_servers\", {\n\t\t\t\turl: mcpUrl(o.apiUrl),\n\t\t\t\theaders: { Authorization: bearer(o.apiKey) }\n\t\t\t}));\n\t\t\treturn {\n\t\t\t\tkind: \"file\",\n\t\t\t\tpath\n\t\t\t};\n\t\t}\n\t},\n\t{\n\t\tslug: \"openclaw\",\n\t\tname: \"OpenClaw\",\n\t\tscopes: [\"global\"],\n\t\tdescribe: () => `openclaw mcp set ${SERVER_NAME} …`,\n\t\tinstall(o) {\n\t\t\tconst def = JSON.stringify({\n\t\t\t\turl: mcpUrl(o.apiUrl),\n\t\t\t\ttransport: \"streamable-http\",\n\t\t\t\theaders: { Authorization: bearer(o.apiKey) }\n\t\t\t});\n\t\t\treturn {\n\t\t\t\tkind: \"command\",\n\t\t\t\tcommand: \"openclaw\",\n\t\t\t\targs: [\n\t\t\t\t\t\"mcp\",\n\t\t\t\t\t\"set\",\n\t\t\t\t\tSERVER_NAME,\n\t\t\t\t\tdef\n\t\t\t\t]\n\t\t\t};\n\t\t}\n\t},\n\t{\n\t\tslug: \"hermes\",\n\t\tname: \"Hermes\",\n\t\tscopes: [\"global\"],\n\t\tdescribe: (o) => join(home(o), \".hermes\", \"config.yaml\"),\n\t\tinstall(o) {\n\t\t\tconst path = join(home(o), \".hermes\", \"config.yaml\");\n\t\t\tmergeYaml(path, (cfg) => setNested(cfg, \"mcp_servers\", {\n\t\t\t\turl: mcpUrl(o.apiUrl),\n\t\t\t\theaders: { Authorization: bearer(o.apiKey) }\n\t\t\t}));\n\t\t\treturn {\n\t\t\t\tkind: \"file\",\n\t\t\t\tpath\n\t\t\t};\n\t\t}\n\t}\n];\nfunction getMcpClient(slug) {\n\treturn mcpClients.find((c) => c.slug === slug);\n}\n\n//#endregion\nexport { SKILL_NAME, getMcpClient, installSkill, mcpClients };\n//# sourceMappingURL=install.js.map","import { resolveSiteUrl } from \"./config\";\n\n/**\n * The canonical Sequel skill is published by the marketing site under the Agent\n * Skills discovery convention. The CLI downloads it at install time rather than\n * bundling a copy, so an installed skill is always the current one and there is\n * a single source of truth for its content.\n */\nexport function skillMarkdownUrl(): string {\n return `${resolveSiteUrl().replace(/\\/$/, \"\")}/.well-known/agent-skills/sequel/SKILL.md`;\n}\n\nexport async function fetchSkillMarkdown(): Promise<string> {\n const url = skillMarkdownUrl();\n const res = await fetch(url, { headers: { Accept: \"text/markdown, text/plain;q=0.9, */*;q=0.1\" } });\n if (!res.ok) throw new Error(`Could not download the Sequel skill (${res.status}) from ${url}`);\n const text = await res.text();\n // A SKILL.md starts with YAML frontmatter; anything else is an error page.\n if (!text.trimStart().startsWith(\"---\")) {\n throw new Error(`Unexpected response from ${url}: not a SKILL.md`);\n }\n return text;\n}\n","import { execFileSync } from \"node:child_process\";\nimport * as p from \"@clack/prompts\";\nimport { createApiKey } from \"../lib/api\";\nimport { isLoggedIn, runLoginFlow } from \"../lib/auth\";\nimport { readConfig, resolveApiUrl } from \"../lib/config\";\nimport { type Scope, getMcpClient, installSkill, mcpClients } from \"../lib/mcp-clients\";\nimport { isJsonMode, pc, success } from \"../lib/output\";\nimport { fetchSkillMarkdown } from \"../lib/skills\";\n\nexport async function installCommand(slugArg?: string): Promise<void> {\n if (isJsonMode()) {\n throw new Error(\n \"`sequel install` is interactive (it prompts for the agent/scope) — run it in a terminal, not piped/--json.\",\n );\n }\n p.intro(pc.cyan(\"Install the Sequel MCP server and skill\"));\n\n // Sign in first if needed, then continue with the install.\n if (!isLoggedIn()) {\n p.log.info(\"You need to sign in to Sequel first — opening your browser…\");\n try {\n const result = await runLoginFlow();\n p.log.success(\n `Signed in as ${result.user.email}${result.org ? ` (${result.org.name})` : \"\"}.`,\n );\n } catch (err) {\n p.cancel(err instanceof Error ? err.message : String(err));\n return;\n }\n }\n\n let slug = slugArg;\n if (!slug) {\n const choice = await p.select({\n message: \"Which coding agent do you want to install Sequel into?\",\n options: mcpClients.map((c) => ({ value: c.slug, label: c.name })),\n });\n if (p.isCancel(choice)) return p.cancel(\"Cancelled.\");\n slug = choice as string;\n }\n\n const client = getMcpClient(slug);\n if (!client) throw new Error(`Unknown agent \"${slug}\". Options: ${mcpClients.map((c) => c.slug).join(\", \")}`);\n\n let scope: Scope = client.scopes[0];\n if (client.scopes.length > 1) {\n const choice = await p.select({\n message: \"Install scope\",\n options: [\n { value: \"global\", label: \"Global\", hint: \"available everywhere on this machine\" },\n { value: \"local\", label: \"Local\", hint: \"this project only\" },\n ].filter((o) => client.scopes.includes(o.value as Scope)),\n });\n if (p.isCancel(choice)) return p.cancel(\"Cancelled.\");\n scope = choice as Scope;\n }\n\n const config = readConfig();\n const apiUrl = resolveApiUrl(config);\n\n const s = p.spinner();\n s.start(\"Creating a Sequel API key for this agent…\");\n let key: string;\n try {\n ({ key } = await createApiKey(`Sequel CLI (${client.name})`));\n } catch (err) {\n s.stop(\"Failed to create API key.\");\n throw err;\n }\n s.stop(\"API key created.\");\n\n const result = client.install({ apiUrl, apiKey: key, scope });\n\n if (result.kind === \"command\") {\n // e.g. Claude Code: run `claude mcp add …`.\n try {\n execFileSync(result.command, result.args, { stdio: \"inherit\" });\n } catch {\n throw new Error(\n `Failed to run \\`${result.command}\\`. Make sure it's installed, or run manually:\\n${result.command} ${result.args.join(\" \")}`,\n );\n }\n success(`Installed Sequel into ${client.name} (${scope}).`);\n } else {\n success(`Installed Sequel into ${client.name}.`);\n p.log.info(`Config written to ${pc.dim(result.path)}`);\n }\n\n // The skill teaches the agent that Sequel's playbooks exist and how to reach\n // them; the MCP server above is what runs them. Install both where we can.\n const skillsDir = client.skillsDir?.({ apiUrl, apiKey: key, scope }) ?? null;\n if (skillsDir) {\n const sk = p.spinner();\n sk.start(\"Installing the Sequel skill…\");\n try {\n const markdown = await fetchSkillMarkdown();\n const written = installSkill({ dir: skillsDir, markdown });\n sk.stop(\"Sequel skill installed.\");\n p.log.info(`Skill written to ${pc.dim(written.path)}`);\n } catch (err) {\n // The MCP install already succeeded; a skill download failure should not\n // undo that or look like it did.\n sk.stop(\"Could not install the Sequel skill.\");\n p.log.warn(\n `${err instanceof Error ? err.message : String(err)}\\nSequel still works through MCP; rerun \\`sequel install ${client.slug}\\` later to add the skill.`,\n );\n }\n } else {\n p.log.info(\n `${client.name} has no skills directory the CLI can write to; the Sequel skill is skipped. Playbooks are still available through MCP.`,\n );\n }\n\n p.outro(`Restart ${client.name} and ask it to \"list my Sequel connections\" to verify.`);\n}\n","import { search } from \"../lib/api\";\nimport { info, isJsonMode, pc, printJson } from \"../lib/output\";\n\nexport async function searchCommand(useCase: string, opts: { connection?: string[] }): Promise<void> {\n const res = await search(useCase, opts.connection);\n if (isJsonMode()) return printJson(res);\n\n if (res.results.length === 0) {\n info(\"No matching tools found across your connected sources.\");\n return;\n }\n\n for (const r of res.results) {\n info(`\\n${pc.bold(r.connection_name)} ${pc.dim(`(${r.connection_id} · ${r.app_id})`)}`);\n if (r.instructions) info(pc.dim(r.instructions));\n for (const tool of r.tools) {\n info(` ${pc.cyan(tool.tool_id)}`);\n if (tool.relevant_tables?.length) info(` tables: ${tool.relevant_tables.join(\", \")}`);\n }\n info(pc.dim(` → sequel execute ${r.connection_id} ${r.tools[0]?.tool_id ?? \"<tool>\"} -d '{…}'`));\n }\n}\n","import { execute } from \"../lib/api\";\nimport { info, isJsonMode, pc, printJson, printTable } from \"../lib/output\";\n\nexport async function executeCommand(\n connectionId: string,\n tool: string,\n opts: { data?: string },\n): Promise<void> {\n let params: Record<string, unknown> = {};\n if (opts.data) {\n try {\n params = JSON.parse(opts.data) as Record<string, unknown>;\n } catch {\n throw new Error(\"Invalid JSON passed to -d/--data.\");\n }\n }\n\n const res = await execute(connectionId, tool, params);\n if (isJsonMode()) return printJson(res);\n\n if (res.data.length === 0) {\n info(pc.dim(\"(0 rows)\"));\n return;\n }\n printTable(res.data, res.columns.length ? res.columns : undefined);\n info(pc.dim(`\\n${res.row_count} row(s)${res.truncated ? \" (truncated)\" : \"\"}`));\n}\n","import { writeFile } from \"node:fs/promises\";\nimport { getFileDownloadUrl } from \"../lib/api\";\nimport { info, isJsonMode, pc, printJson } from \"../lib/output\";\n\nfunction formatBytes(n: number): string {\n if (n < 1024) return `${n} B`;\n if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;\n return `${(n / (1024 * 1024)).toFixed(1)} MB`;\n}\n\nexport async function downloadCommand(\n sessionId: string,\n filePath: string,\n opts: { output?: string },\n): Promise<void> {\n const meta = await getFileDownloadUrl(sessionId, filePath);\n\n // JSON mode (explicit --json or piped): emit the metadata + signed URL for\n // scripting; don't write a file as a surprise side effect.\n if (isJsonMode()) return printJson(meta);\n\n const res = await fetch(meta.url);\n if (!res.ok) throw new Error(`Download failed (${res.status} ${res.statusText})`);\n const dest = opts.output ?? meta.filename;\n await writeFile(dest, Buffer.from(await res.arrayBuffer()));\n info(`${pc.green(\"✓\")} Downloaded ${pc.bold(meta.filename)} (${formatBytes(meta.size)}) → ${dest}`);\n}\n","import { execFileSync } from \"node:child_process\";\nimport * as p from \"@clack/prompts\";\nimport { isJsonMode, pc, printJson, success } from \"../lib/output\";\n\nconst PKG = \"@sequelsh/cli@latest\";\n\ntype Manager = { name: string; cmd: string; args: string[] };\n\n// Global-install command per package manager, in preference order.\nconst MANAGERS: Manager[] = [\n { name: \"npm\", cmd: \"npm\", args: [\"install\", \"-g\", PKG] },\n { name: \"pnpm\", cmd: \"pnpm\", args: [\"add\", \"-g\", PKG] },\n { name: \"bun\", cmd: \"bun\", args: [\"add\", \"-g\", PKG] },\n { name: \"yarn\", cmd: \"yarn\", args: [\"global\", \"add\", PKG] },\n];\n\nfunction has(cmd: string): boolean {\n try {\n execFileSync(process.platform === \"win32\" ? \"where\" : \"which\", [cmd], { stdio: \"ignore\" });\n return true;\n } catch {\n return false;\n }\n}\n\nexport async function upgradeCommand(): Promise<void> {\n const json = isJsonMode();\n if (!json) p.intro(pc.cyan(\"Upgrade the Sequel CLI\"));\n\n const manager = MANAGERS.find((m) => has(m.cmd));\n if (!manager) {\n const msg =\n \"No supported package manager found (npm, pnpm, bun, or yarn). Install Node.js from https://nodejs.org and try again.\";\n if (json) return printJson({ status: \"error\", error: msg });\n p.cancel(msg);\n return;\n }\n\n const s = json ? null : p.spinner();\n s?.start(`Updating ${PKG} with ${manager.name}…`);\n try {\n execFileSync(manager.cmd, manager.args, { stdio: \"pipe\" });\n } catch (err) {\n s?.stop(\"Upgrade failed.\");\n throw new Error(\n `Failed to run \\`${manager.cmd} ${manager.args.join(\" \")}\\`.\\n${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n }\n s?.stop(\"Updated.\");\n\n if (json) return printJson({ status: \"upgraded\", package: PKG, manager: manager.name });\n success(\"Sequel CLI is now on the latest version.\");\n p.outro(\"Run `sequel --version` to confirm.\");\n}\n","import { Command } from \"commander\";\nimport { ApiError } from \"./lib/api\";\nimport { fail, setJsonMode } from \"./lib/output\";\nimport { loginCommand } from \"./commands/login\";\nimport { logoutCommand } from \"./commands/logout\";\nimport { switchCommand } from \"./commands/switch\";\nimport { connectCommand } from \"./commands/connect\";\nimport { sourcesActive, sourcesDelete, sourcesInfo, sourcesList } from \"./commands/sources\";\nimport { skillsList, skillsShow } from \"./commands/skills\";\nimport { installCommand } from \"./commands/install\";\nimport { searchCommand } from \"./commands/search\";\nimport { executeCommand } from \"./commands/execute\";\nimport { downloadCommand } from \"./commands/download\";\nimport { upgradeCommand } from \"./commands/upgrade\";\n\nconst program = new Command();\n\nprogram\n .name(\"sequel\")\n .description(\"Sequel CLI — connect data sources and run tools from your terminal\")\n .version(\"0.1.0\")\n .option(\"--json\", \"output machine-readable JSON\")\n .enablePositionalOptions();\n\n/** Wrap a command action with shared --json handling and error reporting. */\nfunction action<A extends unknown[]>(fn: (...args: A) => Promise<void>) {\n return async (...args: A) => {\n // Auto-enable JSON when stdout is piped (e.g. `sequel sources | jq`), not just --json.\n if (program.opts().json || !process.stdout.isTTY) setJsonMode(true);\n try {\n await fn(...args);\n } catch (err) {\n if (err instanceof ApiError && err.status === 401) {\n fail(\"Unauthorized. Run `sequel login` to sign in again.\");\n } else {\n fail(err instanceof Error ? err.message : String(err));\n }\n process.exitCode = 1;\n }\n };\n}\n\nprogram.command(\"upgrade\").description(\"Upgrade the Sequel CLI to the latest version\").action(action(upgradeCommand));\nprogram.command(\"login\").description(\"Sign in to Sequel\").action(action(loginCommand));\nprogram.command(\"logout\").description(\"Sign out and remove cached credentials\").action(action(logoutCommand));\nprogram.command(\"switch\").description(\"Switch the active organization\").action(action(switchCommand));\n\nprogram\n .command(\"connect\")\n .argument(\"[source]\", \"connector id (e.g. postgres); omit to choose interactively\")\n .description(\"Connect a new data source\")\n .action(action(connectCommand));\n\nconst sources = program.command(\"sources\").description(\"Manage connected data sources\");\nsources.command(\"list\", { isDefault: true }).description(\"List connected sources\").action(action(sourcesList));\nsources.command(\"active\").description(\"List sources with live health status\").action(action(sourcesActive));\nsources\n .command(\"info\")\n .argument(\"[id]\", \"source id or short id\")\n .description(\"Show details for a source\")\n .action(action(sourcesInfo));\nsources\n .command(\"delete\")\n .argument(\"[id]\", \"source id or short id\")\n .description(\"Delete a source\")\n .action(action(sourcesDelete));\n\nconst skills = program.command(\"skills\").description(\"Browse the playbooks your agent can follow\");\nskills.command(\"list\", { isDefault: true }).description(\"List every skill (id and name)\").action(action(skillsList));\nskills\n .command(\"show\")\n .argument(\"<id>\", \"skill id, e.g. seo\")\n .description(\"Print a skill's playbook\")\n .action(action((id: string) => skillsShow(id)));\n\nprogram\n .command(\"install\")\n .argument(\"[agent]\", \"coding agent slug (e.g. cursor, claude-code)\")\n .description(\"Install the Sequel MCP server into a coding agent\")\n .action(action(installCommand));\n\nprogram\n .command(\"search\")\n .argument(\"<usecase>\", \"what you want to do, e.g. \\\"monthly revenue\\\"\")\n .option(\"-c, --connection <id...>\", \"limit to specific connection short ids\")\n .description(\"Find the right tools for a use case across your sources\")\n .action(action((usecase: string, opts: { connection?: string[] }) => searchCommand(usecase, opts)));\n\nprogram\n .command(\"execute\")\n .argument(\"<connection_id>\", \"connection short id\")\n .argument(\"<tool>\", \"tool id, e.g. postgres.query\")\n .option(\"-d, --data <json>\", \"tool input as a JSON string\")\n .description(\"Execute a tool against a connection\")\n .action(action((connectionId: string, tool: string, opts: { data?: string }) => executeCommand(connectionId, tool, opts)));\n\nprogram\n .command(\"download\")\n .argument(\"<session_id>\", \"session id (from `sequel search` or an agent session)\")\n .argument(\"<path>\", \"file path, e.g. /data/result.csv or result.csv\")\n .option(\"-o, --output <file>\", \"write to this path (default: the file's own name)\")\n .description(\"Download a file produced by a query or workbench run\")\n .action(action((sessionId: string, path: string, opts: { output?: string }) => downloadCommand(sessionId, path, opts)));\n\nprogram.parseAsync(process.argv).catch((err) => {\n fail(err instanceof Error ? err.message : String(err));\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAKA,MAAa,kBAAkB;;AAG/B,MAAa,mBAAmB;AAEhC,SAAgB,iBAAyB;AACvC,QAAO,QAAQ,IAAI,mBAAmB;AACvC;;AA2CD,SAAgB,YAAoB;AAClC,QAAO,QAAQ,IAAI,qBAAqB,KAAK,SAAS,EAAE,UAAU;AACnE;AAED,SAAgB,aAAqB;AACnC,QAAO,KAAK,WAAW,EAAE,YAAY;AACtC;;AAGD,SAAgB,cAAcA,QAAoC;AAChE,QAAO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","apiUrl: string","params: Record<string, string>","redirectUri: string","accessToken: string","expectedState: string","resolveCode!: (code: string) => void","rejectCode!: (err: Error) => void","title: string","message: string","options?: LoginFlowOptions","timer: NodeJS.Timeout | undefined","next: AuthConfig","entry: TokenEntry","status: number","message: string","path: string","options: RequestOptions","headers: Record<string, string>","body: string | undefined","text","id: string","appId: string","body: Record<string, unknown>","token: string","connectionId: string","tool: string","params: Record<string, unknown>","useCase: string","connectionIds?: string[]","name: string","sessionId: string","on: boolean","data: unknown","value: unknown","rows: Array<Record<string, unknown>>","columns?: string[]","message: string","pid: number","parsed: PendingLogin","record: PendingLogin","ms: number","opts: { browser: boolean }","timeoutMs: number","opts: LoginOptions","opts: { browser?: boolean }","connector: Connector","token: string","source?: string","connector: Connector | undefined","credentials: Record<string, string>","p","name","s","res","result","idOrShort: string","message: string","c: Connection","idOrShort?: string","config: { schemaFilters: string[] | null; instructions: string | null } | null","path: string","skills","slug: string","SCOPES: readonly Scope[]","slugArg?: string","opts: InstallOptions","result","scope: Scope","key: string","useCase: string","opts: { connection?: string[] }","connectionId: string","tool: string","opts: { data?: string }","params: Record<string, unknown>","n: number","sessionId: string","filePath: string","opts: { output?: string }","MANAGERS: Manager[]","cmd: string","pkg","fn: (...args: A) => Promise<void>","id: string","usecase: string","opts: { connection?: string[] }","connectionId: string","tool: string","opts: { data?: string }","sessionId: string","path: string","opts: { output?: string }"],"sources":["../package.json","../src/lib/config.ts","../src/lib/auth.ts","../src/lib/api.ts","../src/lib/output.ts","../src/lib/pending-login.ts","../src/commands/login.ts","../src/commands/logout.ts","../src/commands/switch.ts","../src/commands/connect.ts","../src/commands/sources.ts","../src/commands/skills.ts","../../mcp-clients/dist/install.js","../src/lib/skills.ts","../src/commands/install.ts","../src/commands/search.ts","../src/commands/execute.ts","../src/commands/download.ts","../src/commands/upgrade.ts","../src/index.ts"],"sourcesContent":["{\n \"name\": \"@sequelsh/cli\",\n \"version\": \"0.4.0\",\n \"description\": \"Sequel CLI — connect data sources and run tools from your terminal.\",\n \"license\": \"MIT\",\n \"type\": \"module\",\n \"bin\": {\n \"sequel\": \"./dist/index.js\"\n },\n \"files\": [\n \"dist\"\n ],\n \"exports\": {\n \".\": {\n \"import\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\"\n }\n },\n \"engines\": {\n \"node\": \">=18\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/sequelsh/sequel.git\",\n \"directory\": \"packages/cli\"\n },\n \"homepage\": \"https://sequel.sh\",\n \"keywords\": [\n \"sequel\",\n \"cli\",\n \"mcp\",\n \"sql\",\n \"data\",\n \"ai\",\n \"agents\"\n ],\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"scripts\": {\n \"dev\": \"bun run src/index.ts\",\n \"cli\": \"bun run src/index.ts\",\n \"build\": \"tsdown\",\n \"build:binaries\": \"bun run scripts/build-binaries.ts\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"typecheck\": \"tsc --noEmit\",\n \"clean\": \"rm -rf dist\"\n },\n \"dependencies\": {\n \"@clack/prompts\": \"^0.8.2\",\n \"commander\": \"^12.1.0\",\n \"open\": \"^10.1.0\",\n \"picocolors\": \"^1.1.1\",\n \"yaml\": \"^2.5.1\"\n },\n \"devDependencies\": {\n \"@sequel/mcp-clients\": \"workspace:*\",\n \"@sequel/typescript-config\": \"workspace:*\",\n \"@types/node\": \"^22.10.0\",\n \"tsdown\": \"^0.9.0\",\n \"typescript\": \"^5.7.0\",\n \"vitest\": \"^3.0.0\"\n }\n}\n","import { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { mkdirSync, readFileSync, writeFileSync, rmSync, existsSync, chmodSync } from \"node:fs\";\n\n/** Default production API base. Override with SEQUEL_API_URL for local/dev. */\nexport const DEFAULT_API_URL = \"https://api.sequel.sh\";\n\n/** Default marketing site, which publishes the Sequel skill. Override with SEQUEL_SITE_URL. */\nexport const DEFAULT_SITE_URL = \"https://sequel.sh\";\n\nexport function resolveSiteUrl(): string {\n return process.env.SEQUEL_SITE_URL || DEFAULT_SITE_URL;\n}\n\n/** One OAuth token bundle, scoped to a single organization. */\nexport interface TokenEntry {\n accessToken: string;\n refreshToken: string;\n /** ms epoch when the access token expires. */\n expiresAt: number;\n}\n\nexport interface OrgRef {\n id: string;\n name: string;\n slug: string;\n role: string;\n}\n\nexport interface UserRef {\n id: string;\n email: string;\n name: string;\n}\n\n/**\n * The on-disk shape of ~/.sequel/auth.json.\n *\n * Multi-token cache: one genuine org-bound OAuth token per organization, keyed\n * by org id. `activeOrgId` selects which token requests use right now. Switching\n * orgs is an offline swap when the target org already has a cached token.\n */\nexport interface AuthConfig {\n version: 1;\n apiUrl: string;\n /** Persisted dynamic client registration, reused across logins. */\n clientId?: string;\n activeOrgId?: string;\n tokens: Record<string, TokenEntry>;\n user?: UserRef;\n /** Cached membership list for the `switch` UI. */\n orgs?: OrgRef[];\n}\n\n/** Directory holding the CLI's state. Overridable for tests. */\nexport function configDir(): string {\n return process.env.SEQUEL_CONFIG_DIR || join(homedir(), \".sequel\");\n}\n\nexport function configPath(): string {\n return join(configDir(), \"auth.json\");\n}\n\n/** The API base URL: explicit env wins, then a saved value, then the default. */\nexport function resolveApiUrl(config?: AuthConfig | null): string {\n return process.env.SEQUEL_API_URL || config?.apiUrl || DEFAULT_API_URL;\n}\n\nfunction emptyConfig(): AuthConfig {\n return { version: 1, apiUrl: resolveApiUrl(), tokens: {} };\n}\n\n/** Read auth.json, returning a fresh empty config if missing or corrupt. */\nexport function readConfig(): AuthConfig {\n const path = configPath();\n if (!existsSync(path)) return emptyConfig();\n try {\n const parsed = JSON.parse(readFileSync(path, \"utf8\")) as AuthConfig;\n if (!parsed || typeof parsed !== \"object\" || !parsed.tokens) return emptyConfig();\n parsed.tokens ??= {};\n return parsed;\n } catch {\n // Corrupt file — start clean rather than crash.\n return emptyConfig();\n }\n}\n\n/** Persist auth.json with locked-down permissions (dir 0700, file 0600). */\nexport function writeConfig(config: AuthConfig): void {\n const dir = configDir();\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n const path = configPath();\n writeFileSync(path, `${JSON.stringify(config, null, 2)}\\n`, { mode: 0o600 });\n // writeFileSync only applies mode on create; enforce it on existing files too.\n chmodSync(path, 0o600);\n}\n\n/** Remove all stored credentials. Idempotent. */\nexport function clearConfig(): void {\n const path = configPath();\n if (existsSync(path)) rmSync(path);\n}\n\nexport function isLoggedIn(config: AuthConfig): boolean {\n return Boolean(config.activeOrgId && config.tokens[config.activeOrgId]);\n}\n","import { createHash, randomBytes } from \"node:crypto\";\nimport { createServer } from \"node:http\";\nimport { AddressInfo } from \"node:net\";\nimport open from \"open\";\nimport {\n type AuthConfig,\n type OrgRef,\n type TokenEntry,\n type UserRef,\n readConfig,\n writeConfig,\n resolveApiUrl,\n} from \"./config\";\n\n/** Refresh a token this many ms before it actually expires. */\nconst EXPIRY_SKEW_MS = 60_000;\n\nfunction base64url(buf: Buffer): string {\n return buf.toString(\"base64url\");\n}\n\n/** PKCE pair: challenge = base64url(sha256(verifier)), matching the API's S256. */\nexport function generatePkce(): { verifier: string; challenge: string } {\n const verifier = base64url(randomBytes(32));\n const challenge = base64url(createHash(\"sha256\").update(verifier).digest());\n return { verifier, challenge };\n}\n\ninterface TokenResponse {\n access_token: string;\n refresh_token: string;\n expires_in: number;\n token_type: string;\n}\n\ninterface WhoAmI {\n id: string;\n name: string;\n email: string;\n organizationId: string;\n}\n\n/** POST the OAuth token endpoint (form-encoded, per RFC 6749). */\nasync function postToken(apiUrl: string, params: Record<string, string>): Promise<TokenResponse> {\n const res = await fetch(`${apiUrl}/oauth/token`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams(params).toString(),\n });\n if (!res.ok) {\n const body = await res.text().catch(() => \"\");\n throw new Error(`Token request failed (${res.status}): ${body}`);\n }\n return (await res.json()) as TokenResponse;\n}\n\n/** Register a fresh dynamic OAuth client bound to this run's loopback URI. */\nasync function registerClient(apiUrl: string, redirectUri: string): Promise<string> {\n const res = await fetch(`${apiUrl}/oauth/register`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ client_name: \"Sequel CLI\", redirect_uris: [redirectUri] }),\n });\n if (!res.ok) {\n const body = await res.text().catch(() => \"\");\n throw new Error(`Client registration failed (${res.status}): ${body}`);\n }\n const data = (await res.json()) as { client_id: string };\n return data.client_id;\n}\n\nasync function fetchWhoAmI(apiUrl: string, accessToken: string): Promise<WhoAmI> {\n const res = await fetch(`${apiUrl}/users/me`, {\n headers: { Authorization: `Bearer ${accessToken}` },\n });\n if (!res.ok) throw new Error(`Failed to resolve identity (${res.status})`);\n return (await res.json()) as WhoAmI;\n}\n\nexport async function fetchOrganizations(apiUrl: string, accessToken: string): Promise<OrgRef[]> {\n const res = await fetch(`${apiUrl}/organizations`, {\n headers: { Authorization: `Bearer ${accessToken}` },\n });\n if (!res.ok) throw new Error(`Failed to list organizations (${res.status})`);\n const rows = (await res.json()) as Array<{\n role: string;\n organization: { id: string; name: string; slug: string };\n }>;\n return rows.map((r) => ({\n id: r.organization.id,\n name: r.organization.name,\n slug: r.organization.slug,\n role: r.role,\n }));\n}\n\n/**\n * Wait for the browser to hit the loopback redirect and hand back `?code&state`.\n * Resolves with the authorization code once `state` is verified.\n */\nfunction waitForCallback(\n expectedState: string,\n): { server: ReturnType<typeof createServer>; port: Promise<number>; code: Promise<string> } {\n let resolveCode!: (code: string) => void;\n let rejectCode!: (err: Error) => void;\n const code = new Promise<string>((resolve, reject) => {\n resolveCode = resolve;\n rejectCode = reject;\n });\n\n const server = createServer((req, res) => {\n const url = new URL(req.url ?? \"/\", \"http://127.0.0.1\");\n if (url.pathname !== \"/callback\") {\n res.writeHead(404).end(\"Not found\");\n return;\n }\n const error = url.searchParams.get(\"error\");\n const returnedState = url.searchParams.get(\"state\");\n const returnedCode = url.searchParams.get(\"code\");\n\n const finish = (title: string, message: string) => {\n res.writeHead(200, { \"Content-Type\": \"text/html; charset=utf-8\" });\n res.end(\n `<!doctype html><html><head><title>${title}</title></head><body style=\"font-family:system-ui;padding:3rem;text-align:center\"><h2>${title}</h2><p>${message}</p><p>You can close this tab and return to your terminal.</p></body></html>`,\n );\n };\n\n if (error) {\n finish(\"Sign-in failed\", `The authorization server returned: ${error}`);\n rejectCode(new Error(`Authorization failed: ${error}`));\n return;\n }\n if (!returnedState || returnedState !== expectedState) {\n finish(\"Sign-in failed\", \"State mismatch — possible CSRF. Please try again.\");\n rejectCode(new Error(\"State mismatch in OAuth callback\"));\n return;\n }\n if (!returnedCode) {\n finish(\"Sign-in failed\", \"No authorization code was returned.\");\n rejectCode(new Error(\"Missing authorization code\"));\n return;\n }\n finish(\"Signed in to Sequel\", \"Authentication complete.\");\n resolveCode(returnedCode);\n });\n\n const port = new Promise<number>((resolve, reject) => {\n server.on(\"error\", reject);\n server.listen(0, \"127.0.0.1\", () => resolve((server.address() as AddressInfo).port));\n });\n\n return { server, port, code };\n}\n\nexport interface LoginResult {\n user: UserRef;\n org: OrgRef | undefined;\n organizationId: string;\n}\n\n/**\n * Run the full OAuth 2.0 + PKCE loopback flow: register a client, open the\n * browser to the consent page (where the user picks an org), capture the code,\n * exchange it for an org-bound token, then cache that token keyed by its org.\n *\n * Shared by `login` and `switch` (for orgs without a cached token).\n */\nexport interface LoginFlowOptions {\n /** Don't try to open a browser; just print the URL. */\n silent?: boolean;\n /** Called with the authorize URL as soon as it's known (before the wait). */\n onUrl?: (url: string) => void;\n /** Give up waiting for the browser callback after this long. */\n timeoutMs?: number;\n}\n\nexport async function runLoginFlow(options?: LoginFlowOptions): Promise<LoginResult> {\n const config = readConfig();\n const apiUrl = resolveApiUrl(config);\n\n const { verifier, challenge } = generatePkce();\n const state = base64url(randomBytes(16));\n\n const { server, port: portPromise, code: codePromise } = waitForCallback(state);\n const port = await portPromise;\n const redirectUri = `http://127.0.0.1:${port}/callback`;\n\n try {\n const clientId = await registerClient(apiUrl, redirectUri);\n\n const authorizeUrl = new URL(`${apiUrl}/oauth/authorize`);\n authorizeUrl.searchParams.set(\"client_id\", clientId);\n authorizeUrl.searchParams.set(\"redirect_uri\", redirectUri);\n authorizeUrl.searchParams.set(\"response_type\", \"code\");\n authorizeUrl.searchParams.set(\"code_challenge\", challenge);\n authorizeUrl.searchParams.set(\"code_challenge_method\", \"S256\");\n authorizeUrl.searchParams.set(\"state\", state);\n\n if (!options?.silent) {\n // open() can fail in headless envs — never block the flow on it.\n open(authorizeUrl.toString()).catch(() => {});\n }\n // Always surface the URL so the user can open it manually if needed.\n process.stderr.write(`\\nOpen this URL to continue:\\n${authorizeUrl.toString()}\\n\\n`);\n options?.onUrl?.(authorizeUrl.toString());\n\n let timer: NodeJS.Timeout | undefined;\n const timeout = new Promise<never>((_, reject) => {\n if (options?.timeoutMs) {\n timer = setTimeout(\n () => reject(new Error(\"Timed out waiting for the browser sign-in to complete.\")),\n options.timeoutMs,\n );\n }\n });\n const code = await Promise.race([codePromise, timeout]).finally(() => clearTimeout(timer));\n\n const token = await postToken(apiUrl, {\n grant_type: \"authorization_code\",\n code,\n redirect_uri: redirectUri,\n client_id: clientId,\n code_verifier: verifier,\n });\n\n const me = await fetchWhoAmI(apiUrl, token.access_token);\n const orgs = await fetchOrganizations(apiUrl, token.access_token).catch(() => config.orgs ?? []);\n\n const next: AuthConfig = {\n ...config,\n version: 1,\n apiUrl,\n clientId,\n activeOrgId: me.organizationId,\n tokens: {\n ...config.tokens,\n [me.organizationId]: {\n accessToken: token.access_token,\n refreshToken: token.refresh_token,\n expiresAt: Date.now() + token.expires_in * 1000,\n },\n },\n user: { id: me.id, email: me.email, name: me.name },\n orgs,\n };\n writeConfig(next);\n\n return {\n user: next.user!,\n org: orgs.find((o) => o.id === me.organizationId),\n organizationId: me.organizationId,\n };\n } finally {\n server.close();\n }\n}\n\n/** True when there's a cached token for the active org (cheap, non-throwing). */\nexport function isLoggedIn(): boolean {\n const config = readConfig();\n const orgId = config.activeOrgId;\n return Boolean(orgId && config.tokens[orgId]);\n}\n\n/**\n * Return a valid access token for the active org, refreshing it in place when\n * expired. Throws a friendly error if there is no token or the refresh fails.\n */\nexport async function getValidAccessToken(): Promise<{ token: string; config: AuthConfig }> {\n const config = readConfig();\n const orgId = config.activeOrgId;\n if (!orgId || !config.tokens[orgId]) {\n throw new Error(\"Not logged in. Run `sequel login` first.\");\n }\n\n const entry: TokenEntry = config.tokens[orgId];\n if (entry.expiresAt - EXPIRY_SKEW_MS > Date.now()) {\n return { token: entry.accessToken, config };\n }\n\n // Access token expired — rotate via the refresh grant.\n const apiUrl = resolveApiUrl(config);\n try {\n const refreshed = await postToken(apiUrl, {\n grant_type: \"refresh_token\",\n refresh_token: entry.refreshToken,\n client_id: config.clientId ?? \"\",\n });\n config.tokens[orgId] = {\n accessToken: refreshed.access_token,\n refreshToken: refreshed.refresh_token,\n expiresAt: Date.now() + refreshed.expires_in * 1000,\n };\n writeConfig(config);\n return { token: refreshed.access_token, config };\n } catch {\n throw new Error(\n \"Your session for this organization has expired. Run `sequel login` (or `sequel switch`) to sign in again.\",\n );\n }\n}\n","import { getValidAccessToken } from \"./auth\";\nimport { resolveApiUrl } from \"./config\";\n\nexport class ApiError extends Error {\n constructor(\n public status: number,\n message: string,\n ) {\n super(message);\n this.name = \"ApiError\";\n }\n}\n\ninterface RequestOptions {\n method?: string;\n query?: Record<string, string | undefined>;\n body?: Record<string, unknown>;\n /**\n * How the active org id is attached to the request:\n * - \"query\" → ?organizationId=<org> (default; most GET/DELETE routes)\n * - \"organizationId\" → merged into the JSON body as organizationId\n * - \"organization_id\" → merged into the JSON body as organization_id (execute)\n * - \"none\" → not attached (e.g. /connectors, /oauth/*)\n */\n org?: \"query\" | \"organizationId\" | \"organization_id\" | \"none\";\n}\n\n/**\n * Authenticated request against the Sequel API using the active org's token.\n * Refreshes the token transparently and scopes the call to that org.\n */\nexport async function request<T = unknown>(path: string, options: RequestOptions = {}): Promise<T> {\n const { token, config } = await getValidAccessToken();\n const apiUrl = resolveApiUrl(config);\n const orgId = config.activeOrgId;\n const orgMode = options.org ?? \"query\";\n\n const url = new URL(`${apiUrl}${path}`);\n if (orgMode === \"query\" && orgId) url.searchParams.set(\"organizationId\", orgId);\n for (const [k, v] of Object.entries(options.query ?? {})) {\n if (v !== undefined) url.searchParams.set(k, v);\n }\n\n let bodyObj = options.body;\n if ((orgMode === \"organizationId\" || orgMode === \"organization_id\") && orgId) {\n bodyObj = { ...(bodyObj ?? {}), [orgMode]: orgId };\n }\n\n const headers: Record<string, string> = { Authorization: `Bearer ${token}` };\n let body: string | undefined;\n if (bodyObj !== undefined) {\n headers[\"Content-Type\"] = \"application/json\";\n body = JSON.stringify(bodyObj);\n }\n\n const res = await fetch(url.toString(), { method: options.method ?? \"GET\", headers, body });\n\n if (!res.ok) {\n let message = `Request failed (${res.status})`;\n const text = await res.text().catch(() => \"\");\n try {\n const json = JSON.parse(text) as { error?: string };\n if (json.error) message = json.error;\n } catch {\n if (text) message = text;\n }\n throw new ApiError(res.status, message);\n }\n\n if (res.status === 204) return undefined as T;\n const text = await res.text();\n return (text ? JSON.parse(text) : undefined) as T;\n}\n\n/** The active organization id, or throws if not logged in. */\nexport async function activeOrgId(): Promise<string> {\n const { config } = await getValidAccessToken();\n if (!config.activeOrgId) throw new Error(\"No active organization. Run `sequel login`.\");\n return config.activeOrgId;\n}\n\n// ── Types ──────────────────────────────────────────────────────────────────────\n\nexport interface Connector {\n id: string;\n name: string;\n description: string;\n icon: string;\n appType: \"database\" | \"app\" | \"mcp\";\n live: boolean;\n authId: string;\n credentialsSchema?: Record<string, unknown>;\n userInputFields?: string[];\n canResolveName?: boolean;\n configuration?: { type: string } | null;\n}\n\nexport interface Connection {\n id: string;\n shortId: string;\n name: string;\n type: string;\n createdBy?: string;\n createdAt: string;\n updatedAt: string;\n}\n\nexport type LinkCreateResponse =\n | { status: \"success\"; connection: Connection }\n | { status: \"pending\"; link_token: string; redirect_url: string; expires_at: string };\n\nexport interface LinkStatus {\n status: \"pending\" | \"oauth_in_progress\" | \"awaiting_configuration\" | \"success\" | \"failed\" | \"completed\";\n connectionId?: string;\n connection_id?: string;\n reason?: string;\n}\n\nexport interface ExecuteResult {\n data: Array<Record<string, unknown>>;\n columns: string[];\n row_count: number;\n truncated: boolean;\n}\n\nexport interface SearchToolRef {\n tool_id: string;\n input_schema: Record<string, unknown>;\n output_schema: Record<string, unknown> | null;\n relevant_tables: string[];\n}\n\nexport interface SearchResult {\n connection_id: string;\n connection_name: string;\n app_id: string;\n use_case: string;\n instructions: string;\n tools: SearchToolRef[];\n}\n\n// ── Endpoint wrappers ───────────────────────────────────────────────────────────\n\nexport function listConnectors(): Promise<Connector[]> {\n return request<Connector[]>(\"/connectors\", { org: \"none\" });\n}\n\nexport function listConnections(): Promise<Connection[]> {\n return request<Connection[]>(\"/connections\");\n}\n\nexport function getConnection(id: string): Promise<Connection> {\n return request<Connection>(`/connections/${id}`);\n}\n\nexport function deleteConnection(id: string): Promise<Connection> {\n return request<Connection>(`/connections/${id}`, { method: \"DELETE\" });\n}\n\nexport function testConnection(id: string): Promise<{ success: boolean; message: string }> {\n return request(`/connections/${id}/test`, { method: \"POST\", org: \"organizationId\" });\n}\n\nexport function getConnectionConfig(\n id: string,\n): Promise<{ schemaFilters: string[] | null; instructions: string | null }> {\n return request(`/connections/${id}/config`);\n}\n\n/** Mint a connect link / create a connection for the given connector. */\nexport function createLink(appId: string, body: Record<string, unknown>): Promise<LinkCreateResponse> {\n // POST /link/:appId resolves the org from the token's session, which always\n // matches the active org in the multi-token model — no org param needed.\n return request<LinkCreateResponse>(`/link/${appId}`, { method: \"POST\", org: \"none\", body });\n}\n\n/**\n * Poll a connect link's status. Uses the authenticated route, which (unlike the\n * public one) reports terminal states — `completed`/`failed` — so the CLI can\n * tell when the browser flow has finished.\n */\nexport function getLinkStatus(token: string): Promise<LinkStatus> {\n return request<LinkStatus>(`/link/${token}/status`, { org: \"none\" });\n}\n\nexport function execute(\n connectionId: string,\n tool: string,\n params: Record<string, unknown>,\n): Promise<ExecuteResult> {\n return request<ExecuteResult>(\"/execute\", {\n method: \"POST\",\n org: \"organization_id\",\n body: { connection_id: connectionId, tool, params },\n });\n}\n\nexport function search(useCase: string, connectionIds?: string[]): Promise<{ results: SearchResult[] }> {\n return request<{ results: SearchResult[] }>(\"/search\", {\n method: \"POST\",\n org: \"organization_id\",\n body: {\n action_info: `CLI search: ${useCase}`,\n use_case: useCase,\n connection_ids: connectionIds,\n },\n });\n}\n\nexport async function createApiKey(name: string): Promise<{ key: string; keyPrefix: string }> {\n const orgId = await activeOrgId();\n return request(`/organizations/${orgId}/api-keys`, { method: \"POST\", org: \"none\", body: { name } });\n}\n\nexport interface FileDownloadInfo {\n url: string;\n filename: string;\n size: number;\n expires_in_seconds: number;\n}\n\n/** Get a signed URL to download a file produced in a session (by sequel_execute / workbench). */\nexport function getFileDownloadUrl(sessionId: string, path: string): Promise<FileDownloadInfo> {\n return request<FileDownloadInfo>(\"/files/download\", { query: { session_id: sessionId, path } });\n}\n","import pc from \"picocolors\";\n\nexport { pc };\n\n/** True when the user passed a global --json flag (set by index.ts). */\nlet jsonMode = false;\nexport function setJsonMode(on: boolean): void {\n jsonMode = on;\n}\nexport function isJsonMode(): boolean {\n return jsonMode;\n}\n\nexport function printJson(data: unknown): void {\n process.stdout.write(`${JSON.stringify(data, null, 2)}\\n`);\n}\n\nfunction cell(value: unknown): string {\n if (value === null || value === undefined) return \"\";\n if (typeof value === \"object\") return JSON.stringify(value);\n return String(value);\n}\n\n/**\n * Render an array of records as an aligned text table. `columns` controls order\n * and which keys are shown; defaults to the union of keys in the first row.\n */\nexport function renderTable(rows: Array<Record<string, unknown>>, columns?: string[]): string {\n if (rows.length === 0) return pc.dim(\"(no rows)\");\n const cols = columns ?? Object.keys(rows[0]);\n const widths = cols.map((c) => Math.max(c.length, ...rows.map((r) => cell(r[c]).length)));\n\n const header = cols.map((c, i) => pc.bold(c.padEnd(widths[i]))).join(\" \");\n const sep = cols.map((_, i) => \"─\".repeat(widths[i])).join(\" \");\n const body = rows\n .map((r) => cols.map((c, i) => cell(r[c]).padEnd(widths[i])).join(\" \"))\n .join(\"\\n\");\n\n return `${header}\\n${pc.dim(sep)}\\n${body}`;\n}\n\nexport function printTable(rows: Array<Record<string, unknown>>, columns?: string[]): void {\n // Never emit human tables to stdout in JSON mode — keep stdout valid JSON for jq.\n if (jsonMode) return;\n process.stdout.write(`${renderTable(rows, columns)}\\n`);\n}\n\n// In JSON mode, human-facing lines go to stderr so stdout stays pure JSON.\nexport function success(message: string): void {\n (jsonMode ? process.stderr : process.stdout).write(`${pc.green(\"✓\")} ${message}\\n`);\n}\n\nexport function info(message: string): void {\n (jsonMode ? process.stderr : process.stdout).write(`${message}\\n`);\n}\n\nexport function fail(message: string): void {\n process.stderr.write(`${pc.red(\"✗\")} ${message}\\n`);\n}\n","import { spawn } from \"node:child_process\";\nimport { existsSync, readFileSync, rmSync, writeFileSync, mkdirSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { isLoggedIn } from \"./auth\";\nimport { configDir } from \"./config\";\n\n/**\n * A sign-in that is waiting for the browser in a detached background process.\n *\n * Coding agents run the CLI with stdout piped and block until it exits, so a\n * `sequel login` that waits for the OAuth callback in the foreground never gets\n * its URL in front of the user. Instead the piped form spawns `login-worker`\n * detached, which owns the loopback server, records the URL here as soon as it\n * is known, and clears the record when the sign-in finishes. The foreground\n * process prints the URL and exits; later commands find the record and wait.\n */\nexport interface PendingLogin {\n url: string;\n pid: number;\n startedAt: number;\n expiresAt: number;\n status: \"pending\" | \"failed\";\n error?: string;\n}\n\n/** How long the background worker waits for the browser before giving up. */\nexport const LOGIN_TIMEOUT_MS = 10 * 60 * 1000;\n\n/** How long the foreground `login` waits for the worker to report its URL. */\nconst URL_WAIT_MS = 20_000;\n\nexport function pendingLoginPath(): string {\n return join(configDir(), \"pending-login.json\");\n}\n\nfunction isAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n}\n\n/** The current record, or null if there is none, it expired, or its worker died. */\nexport function readPendingLogin(): PendingLogin | null {\n const path = pendingLoginPath();\n if (!existsSync(path)) return null;\n let parsed: PendingLogin;\n try {\n parsed = JSON.parse(readFileSync(path, \"utf8\")) as PendingLogin;\n } catch {\n rmSync(path, { force: true });\n return null;\n }\n // A failed record is kept (so `--status` can say why) until the next login.\n if (parsed.status === \"pending\" && (Date.now() > parsed.expiresAt || !isAlive(parsed.pid))) {\n rmSync(path, { force: true });\n return null;\n }\n return parsed;\n}\n\nexport function writePendingLogin(record: PendingLogin): void {\n mkdirSync(configDir(), { recursive: true, mode: 0o700 });\n writeFileSync(pendingLoginPath(), `${JSON.stringify(record, null, 2)}\\n`, { mode: 0o600 });\n}\n\nexport function clearPendingLogin(): void {\n rmSync(pendingLoginPath(), { force: true });\n}\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\n/**\n * Spawn the detached worker and return its record once the URL is known.\n * Reuses a still-pending sign-in rather than starting a second one.\n */\nexport async function startDetachedLogin(opts: { browser: boolean }): Promise<PendingLogin> {\n const existing = readPendingLogin();\n if (existing?.status === \"pending\") return existing;\n clearPendingLogin();\n\n // process.argv[1] is dist/index.js under node and src/index.ts under bun; the\n // matching execPath runs either.\n const args = [process.argv[1], \"login-worker\", ...(opts.browser ? [] : [\"--no-browser\"])];\n const child = spawn(process.execPath, args, { detached: true, stdio: \"ignore\" });\n child.unref();\n\n const deadline = Date.now() + URL_WAIT_MS;\n while (Date.now() < deadline) {\n const record = readPendingLogin();\n if (record && record.pid === child.pid) {\n if (record.status === \"failed\") throw new Error(record.error ?? \"Sign-in failed to start.\");\n return record;\n }\n await sleep(200);\n }\n throw new Error(\"Timed out waiting for the sign-in URL. Run `sequel login` again.\");\n}\n\n/**\n * Block until the pending sign-in finishes (or `timeoutMs` passes). Resolves\n * true when a token is now cached. Returns immediately if nothing is pending.\n */\nexport async function waitForLogin(timeoutMs: number): Promise<boolean> {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n const record = readPendingLogin();\n if (!record) return isLoggedIn();\n if (record.status === \"failed\") return false;\n await sleep(1000);\n }\n return false;\n}\n","import * as p from \"@clack/prompts\";\nimport { isLoggedIn, runLoginFlow } from \"../lib/auth\";\nimport { readConfig } from \"../lib/config\";\nimport { info, isJsonMode, pc, printJson, success } from \"../lib/output\";\nimport {\n LOGIN_TIMEOUT_MS,\n clearPendingLogin,\n readPendingLogin,\n startDetachedLogin,\n waitForLogin,\n writePendingLogin,\n} from \"../lib/pending-login\";\n\nexport interface LoginOptions {\n /** Commander's `--no-browser` sets this to false: print the URL, don't open it. */\n browser?: boolean;\n /** Return the sign-in URL immediately and finish in the background. Implied when piped. */\n detach?: boolean;\n /** Report whether a sign-in is cached, pending, or absent, without starting one. */\n status?: boolean;\n /** Block until a pending background sign-in finishes. */\n wait?: boolean;\n}\n\n/** Instruction that rides along with a pending URL so an agent knows what to do. */\nconst PENDING_MESSAGE =\n \"Show this URL to the user and ask them to open it in their browser to sign in. Once they have, run `sequel login --status` to confirm.\";\n\nfunction printStatus(): void {\n const json = isJsonMode();\n const pending = readPendingLogin();\n if (pending?.status === \"pending\") {\n if (json) return printJson({ status: \"pending\", url: pending.url, expiresAt: pending.expiresAt, message: PENDING_MESSAGE });\n info(`Sign-in pending. Open this URL to finish:\\n${pending.url}`);\n return;\n }\n if (pending?.status === \"failed\") {\n if (json) return printJson({ status: \"failed\", error: pending.error ?? \"Sign-in failed.\", message: \"Run `sequel login` to try again.\" });\n info(`${pc.red(\"✗\")} Last sign-in failed: ${pending.error ?? \"unknown error\"}. Run \\`sequel login\\` to try again.`);\n return;\n }\n if (isLoggedIn()) {\n const config = readConfig();\n const org = config.orgs?.find((o) => o.id === config.activeOrgId) ?? null;\n if (json) return printJson({ status: \"logged_in\", user: config.user ?? null, org });\n success(`Logged in as ${pc.bold(config.user?.email ?? \"unknown\")}${org ? ` · ${pc.bold(org.name)}` : \"\"}`);\n return;\n }\n if (json) return printJson({ status: \"logged_out\", message: \"Run `sequel login` to sign in.\" });\n info(\"Not logged in. Run `sequel login` to sign in.\");\n}\n\nexport async function loginCommand(opts: LoginOptions = {}): Promise<void> {\n const json = isJsonMode();\n const openBrowser = opts.browser !== false;\n\n if (opts.status) return printStatus();\n\n if (opts.wait) {\n const pending = readPendingLogin();\n if (pending?.status === \"pending\") {\n info(`Waiting for the sign-in at ${pending.url} to finish…`);\n await waitForLogin(pending.expiresAt - Date.now());\n }\n return printStatus();\n }\n\n // Piped (a coding agent, `| cat`): hand back the URL right away and let a\n // detached worker wait for the browser, otherwise the caller blocks until the\n // user has signed in and never sees the URL.\n if (opts.detach || json) {\n const pending = await startDetachedLogin({ browser: openBrowser });\n if (json) {\n return printJson({ status: \"pending\", url: pending.url, expiresAt: pending.expiresAt, message: PENDING_MESSAGE });\n }\n info(`Open this URL to sign in:\\n${pending.url}\\n\\nSign-in continues in the background; run \\`sequel login --status\\` to check.`);\n return;\n }\n\n p.intro(pc.cyan(\"Sign in to Sequel\"));\n p.log.info(openBrowser ? \"Opening your browser to authorize…\" : \"Sign in with the URL below…\");\n\n const res = await runLoginFlow({ silent: !openBrowser });\n\n success(`Logged in as ${pc.bold(res.user.email)}${res.org ? ` · ${pc.bold(res.org.name)}` : \"\"}`);\n p.outro(\"You're all set. Try `sequel sources list` or `sequel connect`.\");\n}\n\n/**\n * Hidden: the detached process behind a piped `sequel login`. Owns the loopback\n * server, records the URL for the foreground process, and clears the record\n * (or marks it failed) when the browser flow ends.\n */\nexport async function loginWorkerCommand(opts: { browser?: boolean } = {}): Promise<void> {\n const startedAt = Date.now();\n const base = { pid: process.pid, startedAt, expiresAt: startedAt + LOGIN_TIMEOUT_MS };\n let url = \"\";\n try {\n await runLoginFlow({\n silent: opts.browser === false,\n timeoutMs: LOGIN_TIMEOUT_MS,\n onUrl: (u) => {\n url = u;\n writePendingLogin({ ...base, url, status: \"pending\" });\n },\n });\n clearPendingLogin();\n } catch (err) {\n writePendingLogin({ ...base, url, status: \"failed\", error: err instanceof Error ? err.message : String(err) });\n process.exitCode = 1;\n }\n}\n","import { clearConfig, isLoggedIn, readConfig } from \"../lib/config\";\nimport { info, isJsonMode, printJson, success } from \"../lib/output\";\n\nexport async function logoutCommand(): Promise<void> {\n const config = readConfig();\n if (!isLoggedIn(config)) {\n if (isJsonMode()) return printJson({ status: \"not_logged_in\" });\n info(\"You are not logged in.\");\n return;\n }\n clearConfig();\n if (isJsonMode()) return printJson({ status: \"logged_out\" });\n success(\"Logged out. Cached credentials removed from ~/.sequel/auth.json.\");\n}\n","import * as p from \"@clack/prompts\";\nimport { fetchOrganizations, getValidAccessToken, runLoginFlow } from \"../lib/auth\";\nimport { isLoggedIn, readConfig, resolveApiUrl, writeConfig } from \"../lib/config\";\nimport { isJsonMode, pc, success } from \"../lib/output\";\n\nexport async function switchCommand(): Promise<void> {\n if (isJsonMode()) {\n throw new Error(\n \"`sequel switch` is interactive (it prompts for an organization) — run it in a terminal, not piped/--json.\",\n );\n }\n const config = readConfig();\n if (!isLoggedIn(config)) {\n throw new Error(\"Not logged in. Run `sequel login` first.\");\n }\n\n // Refresh the membership list with the active org's token.\n let orgs = config.orgs ?? [];\n try {\n const { token } = await getValidAccessToken();\n orgs = await fetchOrganizations(resolveApiUrl(config), token);\n writeConfig({ ...readConfig(), orgs });\n } catch {\n // fall back to cached orgs\n }\n if (orgs.length === 0) throw new Error(\"No organizations available for this account.\");\n\n const selection = await p.select({\n message: \"Switch to organization\",\n options: orgs.map((o) => ({\n value: o.id,\n label: o.id === config.activeOrgId ? `${o.name} ${pc.dim(\"(current)\")}` : o.name,\n hint: config.tokens[o.id] ? o.role : \"sign-in required\",\n })),\n });\n if (p.isCancel(selection)) {\n p.cancel(\"Cancelled.\");\n return;\n }\n\n const orgId = selection as string;\n const org = orgs.find((o) => o.id === orgId);\n const fresh = readConfig();\n\n if (fresh.tokens[orgId]) {\n // Already authorized — instant, offline swap.\n writeConfig({ ...fresh, activeOrgId: orgId });\n success(`Switched to ${pc.bold(org?.name ?? orgId)}.`);\n return;\n }\n\n // No cached token for this org — sign in so the user can authorize it.\n p.log.info(`You haven't authorized ${pc.bold(org?.name ?? orgId)} yet — opening your browser…`);\n const res = await runLoginFlow();\n success(`Switched to ${pc.bold(res.org?.name ?? res.organizationId)}.`);\n}\n","import * as p from \"@clack/prompts\";\nimport open from \"open\";\nimport {\n type Connector,\n createLink,\n getLinkStatus,\n listConnectors,\n} from \"../lib/api\";\nimport { info, isJsonMode, pc, success } from \"../lib/output\";\n\nconst SECRET_RE = /pass|secret|token|key|connection|credential/i;\n\nfunction fieldsFor(connector: Connector): string[] {\n if (connector.userInputFields?.length) return connector.userInputFields;\n const props = (connector.credentialsSchema as { properties?: Record<string, unknown> } | undefined)?.properties;\n return props ? Object.keys(props) : [];\n}\n\nfunction isOAuth(connector: Connector): boolean {\n return Boolean(connector.configuration) || /oauth/i.test(connector.authId);\n}\n\n/** Poll a pending connect link until it completes or fails (or times out). */\nasync function pollLink(token: string): Promise<{ ok: boolean; reason?: string }> {\n const deadline = Date.now() + 5 * 60_000;\n while (Date.now() < deadline) {\n await new Promise((r) => setTimeout(r, 2000));\n let status;\n try {\n status = await getLinkStatus(token);\n } catch {\n continue; // transient — keep polling\n }\n if (status.status === \"failed\") return { ok: false, reason: status.reason };\n if (status.status === \"success\" || status.status === \"completed\") return { ok: true };\n }\n return { ok: false, reason: \"Timed out waiting for the browser to finish.\" };\n}\n\nexport async function connectCommand(source?: string): Promise<void> {\n if (isJsonMode()) {\n throw new Error(\n \"`sequel connect` is interactive (it prompts for credentials/consent) — run it in a terminal, not piped/--json.\",\n );\n }\n const connectors = await listConnectors();\n\n let connector: Connector | undefined;\n if (source) {\n connector = connectors.find((c) => c.id === source);\n if (!connector) {\n throw new Error(\n `Unknown connector \"${source}\". Available: ${connectors.map((c) => c.id).join(\", \")}`,\n );\n }\n } else {\n const choice = await p.select({\n message: \"Which data source do you want to connect?\",\n options: connectors\n .slice()\n .sort((a, b) => a.appType.localeCompare(b.appType) || a.name.localeCompare(b.name))\n .map((c) => ({ value: c.id, label: c.name, hint: c.appType })),\n });\n if (p.isCancel(choice)) {\n p.cancel(\"Cancelled.\");\n return;\n }\n connector = connectors.find((c) => c.id === (choice as string))!;\n }\n\n p.intro(`Connect ${pc.bold(connector.name)}`);\n\n if (!isOAuth(connector)) {\n // Pre-auth connector: collect credential fields in the terminal.\n const fields = fieldsFor(connector);\n const credentials: Record<string, string> = {};\n for (const field of fields) {\n const secret = SECRET_RE.test(field);\n const value = await (secret ? p.password : p.text)({\n message: field,\n });\n if (p.isCancel(value)) {\n p.cancel(\"Cancelled.\");\n return;\n }\n credentials[field] = value as string;\n }\n const name = await p.text({ message: \"Name for this source (optional)\", placeholder: connector.name });\n if (p.isCancel(name)) {\n p.cancel(\"Cancelled.\");\n return;\n }\n\n const s = p.spinner();\n s.start(\"Validating credentials…\");\n const res = await createLink(connector.id, {\n credentials,\n ...(name ? { name } : {}),\n });\n if (res.status === \"success\") {\n s.stop(\"Connected.\");\n success(`Created source ${pc.bold(res.connection.name)} (${res.connection.shortId}).`);\n return;\n }\n // Fallback: server wants more input — finish in the browser.\n s.stop(\"Continue in your browser…\");\n open(res.redirect_url).catch(() => {});\n info(`Open: ${res.redirect_url}`);\n const result = await pollLink(res.link_token);\n if (result.ok) success(\"Connected.\");\n else throw new Error(result.reason ?? \"Connection failed.\");\n return;\n }\n\n // OAuth connector: mint a link and let the polished web flow handle consent\n // (and any pre-OAuth fields like a project id), then poll for completion.\n const res = await createLink(connector.id, {});\n if (res.status === \"success\") {\n success(`Created source ${pc.bold(res.connection.name)} (${res.connection.shortId}).`);\n return;\n }\n open(res.redirect_url).catch(() => {});\n info(`Complete authorization in your browser:\\n${res.redirect_url}`);\n const s = p.spinner();\n s.start(\"Waiting for you to finish in the browser…\");\n const result = await pollLink(res.link_token);\n if (result.ok) {\n s.stop(\"Connected.\");\n success(\"Source connected.\");\n } else {\n s.stop(\"Failed.\");\n throw new Error(result.reason ?? \"Connection failed.\");\n }\n}\n","import * as p from \"@clack/prompts\";\nimport {\n type Connection,\n deleteConnection,\n getConnection,\n getConnectionConfig,\n listConnections,\n testConnection,\n} from \"../lib/api\";\nimport { info, isJsonMode, pc, printJson, printTable, success } from \"../lib/output\";\n\n/** Resolve a user-supplied id (uuid or shortId) to the connection's real id. */\nasync function resolveConnection(idOrShort: string): Promise<Connection> {\n const all = await listConnections();\n const match = all.find((c) => c.id === idOrShort || c.shortId === idOrShort);\n if (!match) throw new Error(`No source found matching \"${idOrShort}\".`);\n return match;\n}\n\nasync function pickConnection(message: string): Promise<Connection | undefined> {\n const all = await listConnections();\n if (all.length === 0) {\n info(\"No sources connected yet. Run `sequel connect`.\");\n return undefined;\n }\n const choice = await p.select({\n message,\n options: all.map((c) => ({ value: c.shortId, label: `${c.name} (${c.shortId})`, hint: c.type })),\n });\n if (p.isCancel(choice)) return undefined;\n return all.find((c) => c.shortId === (choice as string));\n}\n\nfunction toRow(c: Connection): Record<string, unknown> {\n return { id: c.shortId, name: c.name, type: c.type, created: c.createdAt.slice(0, 10) };\n}\n\nexport async function sourcesList(): Promise<void> {\n const connections = await listConnections();\n if (isJsonMode()) return printJson(connections);\n if (connections.length === 0) return info(\"No sources connected yet. Run `sequel connect`.\");\n printTable(connections.map(toRow), [\"id\", \"name\", \"type\", \"created\"]);\n}\n\nexport async function sourcesActive(): Promise<void> {\n const connections = await listConnections();\n const rows = await Promise.all(\n connections.map(async (c) => {\n let status = \"unknown\";\n try {\n const t = await testConnection(c.id);\n status = t.success ? \"healthy\" : \"error\";\n } catch {\n status = \"error\";\n }\n return { ...toRow(c), status };\n }),\n );\n if (isJsonMode()) return printJson(rows);\n if (rows.length === 0) return info(\"No sources connected yet. Run `sequel connect`.\");\n printTable(rows, [\"id\", \"name\", \"type\", \"status\", \"created\"]);\n}\n\nexport async function sourcesInfo(idOrShort?: string): Promise<void> {\n const conn = idOrShort ? await resolveConnection(idOrShort) : await pickConnection(\"Source to inspect\");\n if (!conn) return;\n const full = await getConnection(conn.id);\n let config: { schemaFilters: string[] | null; instructions: string | null } | null = null;\n try {\n config = await getConnectionConfig(conn.id);\n } catch {\n /* config may be absent */\n }\n if (isJsonMode()) return printJson({ ...full, config });\n\n info(`${pc.bold(full.name)} ${pc.dim(full.shortId)}`);\n info(`type: ${full.type}`);\n info(`id: ${full.id}`);\n info(`created: ${full.createdAt}`);\n if (config?.schemaFilters?.length) info(`schemas: ${config.schemaFilters.join(\", \")}`);\n if (config?.instructions) info(`\\n${pc.dim(config.instructions)}`);\n}\n\nexport async function sourcesDelete(idOrShort?: string): Promise<void> {\n const conn = idOrShort ? await resolveConnection(idOrShort) : await pickConnection(\"Source to delete\");\n if (!conn) return;\n const confirmed = await p.confirm({ message: `Delete ${pc.bold(conn.name)} (${conn.shortId})? This cannot be undone.` });\n if (p.isCancel(confirmed) || !confirmed) {\n info(\"Cancelled.\");\n return;\n }\n await deleteConnection(conn.id);\n success(`Deleted ${conn.name} (${conn.shortId}).`);\n}\n","import { readConfig, resolveApiUrl } from \"../lib/config\";\nimport { info, isJsonMode, pc, printJson, printTable } from \"../lib/output\";\n\ntype PublicSkill = { id: string; slug: string; name: string; category: string; apps: string[] };\ntype PublicSkillDetail = PublicSkill & { description: string; instructions: string };\n\n// Skills are public, so these hit the unauthenticated marketplace endpoints and\n// work before `sequel login`.\nasync function publicGet<T>(path: string): Promise<T> {\n const res = await fetch(`${resolveApiUrl(readConfig())}${path}`, { headers: { Accept: \"application/json\" } });\n if (res.status === 404) throw new Error(`No skill found matching \"${path.split(\"/\").pop()}\". Run \\`sequel skills list\\`.`);\n if (!res.ok) throw new Error(`Request failed (${res.status})`);\n return (await res.json()) as T;\n}\n\nexport async function skillsList(): Promise<void> {\n const skills = await publicGet<PublicSkill[]>(\"/marketplace/skills\");\n const rows = skills.map((s) => ({ id: s.slug, name: s.name }));\n if (isJsonMode()) return printJson(rows);\n printTable(rows, [\"id\", \"name\"]);\n info(`${rows.length} skills. \\`sequel skills show <id>\\` prints one; \\`sequel install\\` gives your agent all of them.`);\n}\n\nexport async function skillsShow(slug: string): Promise<void> {\n const skill = await publicGet<PublicSkillDetail>(`/marketplace/skills/${encodeURIComponent(slug)}`);\n if (isJsonMode()) return printJson(skill);\n process.stdout.write(\n `${pc.bold(skill.name)} ${pc.dim(skill.slug)}\\n${skill.description}\\n` +\n (skill.apps.length ? `${pc.dim(\"apps:\")} ${skill.apps.join(\", \")}\\n` : \"\") +\n `\\n${skill.instructions}\\n`,\n );\n}\n","import { homedir, platform } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport YAML from \"yaml\";\n\n//#region src/install.ts\nconst SERVER_NAME = \"sequel\";\n/** Folder name of the Sequel skill inside an agent's skills directory. */\nconst SKILL_NAME = \"sequel\";\n/**\n* Write the Sequel SKILL.md into `<dir>/sequel/SKILL.md`, replacing any previous\n* copy. Skill files are plain markdown, so unlike the MCP configs there is\n* nothing to merge: the whole file is ours.\n*/\nfunction installSkill({ dir, markdown }) {\n\tconst path = join(dir, SKILL_NAME, \"SKILL.md\");\n\tmkdirSync(dirname(path), { recursive: true });\n\twriteFileSync(path, markdown.endsWith(\"\\n\") ? markdown : `${markdown}\\n`);\n\treturn {\n\t\tkind: \"file\",\n\t\tpath\n\t};\n}\nconst mcpUrl = (apiUrl) => `${apiUrl.replace(/\\/$/, \"\")}/mcp`;\nconst bearer = (apiKey) => `Bearer ${apiKey}`;\nfunction home(opts) {\n\treturn opts.home ?? homedir();\n}\nfunction cwd(opts) {\n\treturn opts.cwd ?? process.cwd();\n}\n/** OS-specific application-support dir for a vendor folder. */\nfunction appSupport(opts, vendor) {\n\tconst h = home(opts);\n\tswitch (platform()) {\n\t\tcase \"darwin\": return join(h, \"Library\", \"Application Support\", vendor);\n\t\tcase \"win32\": return join(process.env.APPDATA ?? join(h, \"AppData\", \"Roaming\"), vendor);\n\t\tdefault: return join(process.env.XDG_CONFIG_HOME ?? join(h, \".config\"), vendor);\n\t}\n}\n/** Read+merge+write a JSON config, preserving every other key already present. */\nfunction mergeJson(path, mutate) {\n\tlet cfg = {};\n\tif (existsSync(path)) try {\n\t\tcfg = JSON.parse(readFileSync(path, \"utf8\"));\n\t} catch {\n\t\tcfg = {};\n\t}\n\tmutate(cfg);\n\tmkdirSync(dirname(path), { recursive: true });\n\twriteFileSync(path, `${JSON.stringify(cfg, null, 2)}\\n`);\n}\nfunction mergeYaml(path, mutate) {\n\tlet cfg = {};\n\tif (existsSync(path)) try {\n\t\tcfg = YAML.parse(readFileSync(path, \"utf8\")) ?? {};\n\t} catch {\n\t\tcfg = {};\n\t}\n\tmutate(cfg);\n\tmkdirSync(dirname(path), { recursive: true });\n\twriteFileSync(path, YAML.stringify(cfg));\n}\nfunction setNested(cfg, key, value) {\n\tconst obj = cfg[key] ?? {};\n\tobj[SERVER_NAME] = value;\n\tcfg[key] = obj;\n}\nconst mcpClients = [\n\t{\n\t\tslug: \"claude\",\n\t\tname: \"Claude Desktop\",\n\t\tscopes: [\"global\"],\n\t\tdescribe: (o) => join(appSupport(o, \"Claude\"), \"claude_desktop_config.json\"),\n\t\tinstall(o) {\n\t\t\tconst path = join(appSupport(o, \"Claude\"), \"claude_desktop_config.json\");\n\t\t\tmergeJson(path, (cfg) => setNested(cfg, \"mcpServers\", {\n\t\t\t\turl: mcpUrl(o.apiUrl),\n\t\t\t\theaders: { Authorization: bearer(o.apiKey) }\n\t\t\t}));\n\t\t\treturn {\n\t\t\t\tkind: \"file\",\n\t\t\t\tpath\n\t\t\t};\n\t\t}\n\t},\n\t{\n\t\tslug: \"claude-code\",\n\t\tname: \"Claude Code\",\n\t\tscopes: [\"global\", \"local\"],\n\t\tdescribe: (o) => `claude mcp add --scope ${o.scope === \"global\" ? \"user\" : \"local\"} --transport http ${SERVER_NAME} …`,\n\t\tskillsDir: (o) => o.scope === \"global\" ? join(home(o), \".claude\", \"skills\") : join(cwd(o), \".claude\", \"skills\"),\n\t\tinstall(o) {\n\t\t\treturn {\n\t\t\t\tkind: \"command\",\n\t\t\t\tcommand: \"claude\",\n\t\t\t\targs: [\n\t\t\t\t\t\"mcp\",\n\t\t\t\t\t\"add\",\n\t\t\t\t\t\"--scope\",\n\t\t\t\t\to.scope === \"global\" ? \"user\" : \"local\",\n\t\t\t\t\t\"--transport\",\n\t\t\t\t\t\"http\",\n\t\t\t\t\tSERVER_NAME,\n\t\t\t\t\tmcpUrl(o.apiUrl),\n\t\t\t\t\t\"--header\",\n\t\t\t\t\t`Authorization: ${bearer(o.apiKey)}`\n\t\t\t\t]\n\t\t\t};\n\t\t}\n\t},\n\t{\n\t\tslug: \"cursor\",\n\t\tname: \"Cursor\",\n\t\tscopes: [\"global\", \"local\"],\n\t\tdescribe: (o) => o.scope === \"global\" ? join(home(o), \".cursor\", \"mcp.json\") : join(cwd(o), \".cursor\", \"mcp.json\"),\n\t\tinstall(o) {\n\t\t\tconst path = o.scope === \"global\" ? join(home(o), \".cursor\", \"mcp.json\") : join(cwd(o), \".cursor\", \"mcp.json\");\n\t\t\tmergeJson(path, (cfg) => setNested(cfg, \"mcpServers\", {\n\t\t\t\turl: mcpUrl(o.apiUrl),\n\t\t\t\theaders: { Authorization: bearer(o.apiKey) }\n\t\t\t}));\n\t\t\treturn {\n\t\t\t\tkind: \"file\",\n\t\t\t\tpath\n\t\t\t};\n\t\t}\n\t},\n\t{\n\t\tslug: \"vscode\",\n\t\tname: \"VS Code\",\n\t\tscopes: [\"global\", \"local\"],\n\t\tdescribe: (o) => o.scope === \"global\" ? join(appSupport(o, \"Code\"), \"User\", \"mcp.json\") : join(cwd(o), \".vscode\", \"mcp.json\"),\n\t\tinstall(o) {\n\t\t\tconst path = o.scope === \"global\" ? join(appSupport(o, \"Code\"), \"User\", \"mcp.json\") : join(cwd(o), \".vscode\", \"mcp.json\");\n\t\t\tmergeJson(path, (cfg) => setNested(cfg, \"servers\", {\n\t\t\t\turl: mcpUrl(o.apiUrl),\n\t\t\t\ttype: \"http\",\n\t\t\t\theaders: { Authorization: bearer(o.apiKey) }\n\t\t\t}));\n\t\t\treturn {\n\t\t\t\tkind: \"file\",\n\t\t\t\tpath\n\t\t\t};\n\t\t}\n\t},\n\t{\n\t\tslug: \"windsurf\",\n\t\tname: \"Windsurf\",\n\t\tscopes: [\"global\"],\n\t\tdescribe: (o) => join(home(o), \".codeium\", \"windsurf\", \"mcp_config.json\"),\n\t\tinstall(o) {\n\t\t\tconst path = join(home(o), \".codeium\", \"windsurf\", \"mcp_config.json\");\n\t\t\tmergeJson(path, (cfg) => setNested(cfg, \"mcpServers\", {\n\t\t\t\tserverUrl: mcpUrl(o.apiUrl),\n\t\t\t\theaders: { Authorization: bearer(o.apiKey) }\n\t\t\t}));\n\t\t\treturn {\n\t\t\t\tkind: \"file\",\n\t\t\t\tpath\n\t\t\t};\n\t\t}\n\t},\n\t{\n\t\tslug: \"zed\",\n\t\tname: \"Zed\",\n\t\tscopes: [\"global\", \"local\"],\n\t\tdescribe: (o) => o.scope === \"global\" ? join(home(o), \".config\", \"zed\", \"settings.json\") : join(cwd(o), \".zed\", \"settings.json\"),\n\t\tinstall(o) {\n\t\t\tconst path = o.scope === \"global\" ? join(home(o), \".config\", \"zed\", \"settings.json\") : join(cwd(o), \".zed\", \"settings.json\");\n\t\t\tmergeJson(path, (cfg) => setNested(cfg, \"context_servers\", {\n\t\t\t\turl: mcpUrl(o.apiUrl),\n\t\t\t\tsettings: { headers: { Authorization: bearer(o.apiKey) } }\n\t\t\t}));\n\t\t\treturn {\n\t\t\t\tkind: \"file\",\n\t\t\t\tpath\n\t\t\t};\n\t\t}\n\t},\n\t{\n\t\tslug: \"codex\",\n\t\tname: \"Codex\",\n\t\tscopes: [\"global\"],\n\t\tdescribe: (o) => join(home(o), \".codex\", \"config.yaml\"),\n\t\tinstall(o) {\n\t\t\tconst path = join(home(o), \".codex\", \"config.yaml\");\n\t\t\tmergeYaml(path, (cfg) => setNested(cfg, \"mcp_servers\", {\n\t\t\t\turl: mcpUrl(o.apiUrl),\n\t\t\t\theaders: { Authorization: bearer(o.apiKey) }\n\t\t\t}));\n\t\t\treturn {\n\t\t\t\tkind: \"file\",\n\t\t\t\tpath\n\t\t\t};\n\t\t}\n\t},\n\t{\n\t\tslug: \"openclaw\",\n\t\tname: \"OpenClaw\",\n\t\tscopes: [\"global\"],\n\t\tdescribe: () => `openclaw mcp set ${SERVER_NAME} …`,\n\t\tinstall(o) {\n\t\t\tconst def = JSON.stringify({\n\t\t\t\turl: mcpUrl(o.apiUrl),\n\t\t\t\ttransport: \"streamable-http\",\n\t\t\t\theaders: { Authorization: bearer(o.apiKey) }\n\t\t\t});\n\t\t\treturn {\n\t\t\t\tkind: \"command\",\n\t\t\t\tcommand: \"openclaw\",\n\t\t\t\targs: [\n\t\t\t\t\t\"mcp\",\n\t\t\t\t\t\"set\",\n\t\t\t\t\tSERVER_NAME,\n\t\t\t\t\tdef\n\t\t\t\t]\n\t\t\t};\n\t\t}\n\t},\n\t{\n\t\tslug: \"hermes\",\n\t\tname: \"Hermes\",\n\t\tscopes: [\"global\"],\n\t\tdescribe: (o) => join(home(o), \".hermes\", \"config.yaml\"),\n\t\tinstall(o) {\n\t\t\tconst path = join(home(o), \".hermes\", \"config.yaml\");\n\t\t\tmergeYaml(path, (cfg) => setNested(cfg, \"mcp_servers\", {\n\t\t\t\turl: mcpUrl(o.apiUrl),\n\t\t\t\theaders: { Authorization: bearer(o.apiKey) }\n\t\t\t}));\n\t\t\treturn {\n\t\t\t\tkind: \"file\",\n\t\t\t\tpath\n\t\t\t};\n\t\t}\n\t}\n];\nfunction getMcpClient(slug) {\n\treturn mcpClients.find((c) => c.slug === slug);\n}\n\n//#endregion\nexport { SKILL_NAME, getMcpClient, installSkill, mcpClients };\n//# sourceMappingURL=install.js.map","import { resolveSiteUrl } from \"./config\";\n\n/**\n * The canonical Sequel skill is published by the marketing site under the Agent\n * Skills discovery convention. The CLI downloads it at install time rather than\n * bundling a copy, so an installed skill is always the current one and there is\n * a single source of truth for its content.\n */\nexport function skillMarkdownUrl(): string {\n return `${resolveSiteUrl().replace(/\\/$/, \"\")}/.well-known/agent-skills/sequel/SKILL.md`;\n}\n\nexport async function fetchSkillMarkdown(): Promise<string> {\n const url = skillMarkdownUrl();\n const res = await fetch(url, { headers: { Accept: \"text/markdown, text/plain;q=0.9, */*;q=0.1\" } });\n if (!res.ok) throw new Error(`Could not download the Sequel skill (${res.status}) from ${url}`);\n const text = await res.text();\n // A SKILL.md starts with YAML frontmatter; anything else is an error page.\n if (!text.trimStart().startsWith(\"---\")) {\n throw new Error(`Unexpected response from ${url}: not a SKILL.md`);\n }\n return text;\n}\n","import { execFileSync } from \"node:child_process\";\nimport * as p from \"@clack/prompts\";\nimport { createApiKey } from \"../lib/api\";\nimport { isLoggedIn, runLoginFlow } from \"../lib/auth\";\nimport { readConfig, resolveApiUrl } from \"../lib/config\";\nimport { type Scope, getMcpClient, installSkill, mcpClients } from \"../lib/mcp-clients\";\nimport { info, isJsonMode, pc, success } from \"../lib/output\";\nimport { readPendingLogin, waitForLogin } from \"../lib/pending-login\";\nimport { fetchSkillMarkdown } from \"../lib/skills\";\n\nexport interface InstallOptions {\n /** `--scope global|local`; skips the scope prompt. Defaults to the agent's first scope when non-interactive. */\n scope?: string;\n /** Commander's `--no-browser` sets this to false: if a sign-in is needed, print its URL instead of opening it. */\n browser?: boolean;\n}\n\nconst SCOPES: readonly Scope[] = [\"global\", \"local\"];\n\nexport async function installCommand(slugArg?: string, opts: InstallOptions = {}): Promise<void> {\n // Piped/--json (how coding agents run us): no prompts at all. Everything the\n // prompts would have asked must come from the argument and flags instead.\n const interactive = !isJsonMode();\n const slugList = mcpClients.map((c) => c.slug).join(\", \");\n\n if (interactive) p.intro(pc.cyan(\"Install the Sequel MCP server and skill\"));\n\n // Reject a bad slug before opening a browser for sign-in.\n if (slugArg && !getMcpClient(slugArg)) throw new Error(`Unknown agent \"${slugArg}\". Options: ${slugList}`);\n if (!slugArg && !interactive) {\n throw new Error(`Pass the agent slug when running non-interactively: \\`sequel install <agent>\\`. Options: ${slugList}`);\n }\n\n // Sign in first if needed, then continue with the install.\n if (!isLoggedIn()) {\n if (!interactive) {\n // Never block a piped caller on a URL it can't see: finish a sign-in that\n // `sequel login` already started, otherwise tell it to start one.\n const pending = readPendingLogin();\n if (pending?.status !== \"pending\") {\n throw new Error(\n \"Not signed in. Run `sequel login` first: it prints a sign-in URL for the user to open. Once they have signed in, rerun this command.\",\n );\n }\n info(`Waiting for the sign-in at ${pending.url} to finish…`);\n if (!(await waitForLogin(pending.expiresAt - Date.now()))) {\n throw new Error(\"The sign-in did not complete. Run `sequel login` to get a fresh URL, then rerun this command.\");\n }\n } else {\n p.log.info(\"You need to sign in to Sequel first — opening your browser…\");\n try {\n const result = await runLoginFlow({ silent: opts.browser === false });\n p.log.success(`Signed in as ${result.user.email}${result.org ? ` (${result.org.name})` : \"\"}.`);\n } catch (err) {\n p.cancel(err instanceof Error ? err.message : String(err));\n return;\n }\n }\n }\n\n let slug = slugArg;\n if (!slug) {\n const choice = await p.select({\n message: \"Which coding agent do you want to install Sequel into?\",\n options: mcpClients.map((c) => ({ value: c.slug, label: c.name })),\n });\n if (p.isCancel(choice)) return p.cancel(\"Cancelled.\");\n slug = choice as string;\n }\n\n const client = getMcpClient(slug);\n if (!client) throw new Error(`Unknown agent \"${slug}\". Options: ${slugList}`);\n\n let scope: Scope = client.scopes[0];\n if (opts.scope !== undefined) {\n if (!SCOPES.includes(opts.scope as Scope)) {\n throw new Error(`Unknown scope \"${opts.scope}\". Options: ${SCOPES.join(\", \")}`);\n }\n if (!client.scopes.includes(opts.scope as Scope)) {\n throw new Error(`${client.name} only supports the ${client.scopes.join(\"/\")} scope.`);\n }\n scope = opts.scope as Scope;\n } else if (client.scopes.length > 1 && interactive) {\n const choice = await p.select({\n message: \"Install scope\",\n options: [\n { value: \"global\", label: \"Global\", hint: \"available everywhere on this machine\" },\n { value: \"local\", label: \"Local\", hint: \"this project only\" },\n ].filter((o) => client.scopes.includes(o.value as Scope)),\n });\n if (p.isCancel(choice)) return p.cancel(\"Cancelled.\");\n scope = choice as Scope;\n }\n\n const config = readConfig();\n const apiUrl = resolveApiUrl(config);\n\n // Clack spinners assume a TTY; when piped, log plain lines instead.\n const s = interactive ? p.spinner() : null;\n s?.start(\"Creating a Sequel API key for this agent…\");\n let key: string;\n try {\n ({ key } = await createApiKey(`Sequel CLI (${client.name})`));\n } catch (err) {\n s?.stop(\"Failed to create API key.\");\n throw err;\n }\n s ? s.stop(\"API key created.\") : info(\"API key created.\");\n\n const result = client.install({ apiUrl, apiKey: key, scope });\n\n if (result.kind === \"command\") {\n // e.g. Claude Code: run `claude mcp add …`.\n try {\n execFileSync(result.command, result.args, { stdio: \"inherit\" });\n } catch {\n throw new Error(\n `Failed to run \\`${result.command}\\`. Make sure it's installed, or run manually:\\n${result.command} ${result.args.join(\" \")}`,\n );\n }\n success(`Installed Sequel into ${client.name} (${scope}).`);\n } else {\n success(`Installed Sequel into ${client.name}.`);\n info(`Config written to ${pc.dim(result.path)}`);\n }\n\n // The skill teaches the agent that Sequel's playbooks exist and how to reach\n // them; the MCP server above is what runs them. Install both where we can.\n const skillsDir = client.skillsDir?.({ apiUrl, apiKey: key, scope }) ?? null;\n if (skillsDir) {\n const sk = interactive ? p.spinner() : null;\n sk?.start(\"Installing the Sequel skill…\");\n try {\n const markdown = await fetchSkillMarkdown();\n const written = installSkill({ dir: skillsDir, markdown });\n sk ? sk.stop(\"Sequel skill installed.\") : success(\"Sequel skill installed.\");\n info(`Skill written to ${pc.dim(written.path)}`);\n } catch (err) {\n // The MCP install already succeeded; a skill download failure should not\n // undo that or look like it did.\n sk?.stop(\"Could not install the Sequel skill.\");\n const warning = `${err instanceof Error ? err.message : String(err)}\\nSequel still works through MCP; rerun \\`sequel install ${client.slug}\\` later to add the skill.`;\n if (interactive) p.log.warn(warning);\n else info(`Could not install the Sequel skill. ${warning}`);\n }\n } else {\n info(\n `${client.name} has no skills directory the CLI can write to; the Sequel skill is skipped. Playbooks are still available through MCP.`,\n );\n }\n\n const done = `Restart ${client.name} and ask it to \"list my Sequel connections\" to verify.`;\n if (interactive) p.outro(done);\n else info(done);\n}\n","import { search } from \"../lib/api\";\nimport { info, isJsonMode, pc, printJson } from \"../lib/output\";\n\nexport async function searchCommand(useCase: string, opts: { connection?: string[] }): Promise<void> {\n const res = await search(useCase, opts.connection);\n if (isJsonMode()) return printJson(res);\n\n if (res.results.length === 0) {\n info(\"No matching tools found across your connected sources.\");\n return;\n }\n\n for (const r of res.results) {\n info(`\\n${pc.bold(r.connection_name)} ${pc.dim(`(${r.connection_id} · ${r.app_id})`)}`);\n if (r.instructions) info(pc.dim(r.instructions));\n for (const tool of r.tools) {\n info(` ${pc.cyan(tool.tool_id)}`);\n if (tool.relevant_tables?.length) info(` tables: ${tool.relevant_tables.join(\", \")}`);\n }\n info(pc.dim(` → sequel execute ${r.connection_id} ${r.tools[0]?.tool_id ?? \"<tool>\"} -d '{…}'`));\n }\n}\n","import { execute } from \"../lib/api\";\nimport { info, isJsonMode, pc, printJson, printTable } from \"../lib/output\";\n\nexport async function executeCommand(\n connectionId: string,\n tool: string,\n opts: { data?: string },\n): Promise<void> {\n let params: Record<string, unknown> = {};\n if (opts.data) {\n try {\n params = JSON.parse(opts.data) as Record<string, unknown>;\n } catch {\n throw new Error(\"Invalid JSON passed to -d/--data.\");\n }\n }\n\n const res = await execute(connectionId, tool, params);\n if (isJsonMode()) return printJson(res);\n\n if (res.data.length === 0) {\n info(pc.dim(\"(0 rows)\"));\n return;\n }\n printTable(res.data, res.columns.length ? res.columns : undefined);\n info(pc.dim(`\\n${res.row_count} row(s)${res.truncated ? \" (truncated)\" : \"\"}`));\n}\n","import { writeFile } from \"node:fs/promises\";\nimport { getFileDownloadUrl } from \"../lib/api\";\nimport { info, isJsonMode, pc, printJson } from \"../lib/output\";\n\nfunction formatBytes(n: number): string {\n if (n < 1024) return `${n} B`;\n if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;\n return `${(n / (1024 * 1024)).toFixed(1)} MB`;\n}\n\nexport async function downloadCommand(\n sessionId: string,\n filePath: string,\n opts: { output?: string },\n): Promise<void> {\n const meta = await getFileDownloadUrl(sessionId, filePath);\n\n // JSON mode (explicit --json or piped): emit the metadata + signed URL for\n // scripting; don't write a file as a surprise side effect.\n if (isJsonMode()) return printJson(meta);\n\n const res = await fetch(meta.url);\n if (!res.ok) throw new Error(`Download failed (${res.status} ${res.statusText})`);\n const dest = opts.output ?? meta.filename;\n await writeFile(dest, Buffer.from(await res.arrayBuffer()));\n info(`${pc.green(\"✓\")} Downloaded ${pc.bold(meta.filename)} (${formatBytes(meta.size)}) → ${dest}`);\n}\n","import { execFileSync } from \"node:child_process\";\nimport * as p from \"@clack/prompts\";\nimport { isJsonMode, pc, printJson, success } from \"../lib/output\";\n\nconst PKG = \"@sequelsh/cli@latest\";\n\ntype Manager = { name: string; cmd: string; args: string[] };\n\n// Global-install command per package manager, in preference order.\nconst MANAGERS: Manager[] = [\n { name: \"npm\", cmd: \"npm\", args: [\"install\", \"-g\", PKG] },\n { name: \"pnpm\", cmd: \"pnpm\", args: [\"add\", \"-g\", PKG] },\n { name: \"bun\", cmd: \"bun\", args: [\"add\", \"-g\", PKG] },\n { name: \"yarn\", cmd: \"yarn\", args: [\"global\", \"add\", PKG] },\n];\n\nfunction has(cmd: string): boolean {\n try {\n execFileSync(process.platform === \"win32\" ? \"where\" : \"which\", [cmd], { stdio: \"ignore\" });\n return true;\n } catch {\n return false;\n }\n}\n\nexport async function upgradeCommand(): Promise<void> {\n const json = isJsonMode();\n if (!json) p.intro(pc.cyan(\"Upgrade the Sequel CLI\"));\n\n const manager = MANAGERS.find((m) => has(m.cmd));\n if (!manager) {\n const msg =\n \"No supported package manager found (npm, pnpm, bun, or yarn). Install Node.js from https://nodejs.org and try again.\";\n if (json) return printJson({ status: \"error\", error: msg });\n p.cancel(msg);\n return;\n }\n\n const s = json ? null : p.spinner();\n s?.start(`Updating ${PKG} with ${manager.name}…`);\n try {\n execFileSync(manager.cmd, manager.args, { stdio: \"pipe\" });\n } catch (err) {\n s?.stop(\"Upgrade failed.\");\n throw new Error(\n `Failed to run \\`${manager.cmd} ${manager.args.join(\" \")}\\`.\\n${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n }\n s?.stop(\"Updated.\");\n\n if (json) return printJson({ status: \"upgraded\", package: PKG, manager: manager.name });\n success(\"Sequel CLI is now on the latest version.\");\n p.outro(\"Run `sequel --version` to confirm.\");\n}\n","import { Command } from \"commander\";\nimport pkg from \"../package.json\" with { type: \"json\" };\nimport { ApiError } from \"./lib/api\";\nimport { fail, setJsonMode } from \"./lib/output\";\nimport { loginCommand, loginWorkerCommand } from \"./commands/login\";\nimport { logoutCommand } from \"./commands/logout\";\nimport { switchCommand } from \"./commands/switch\";\nimport { connectCommand } from \"./commands/connect\";\nimport { sourcesActive, sourcesDelete, sourcesInfo, sourcesList } from \"./commands/sources\";\nimport { skillsList, skillsShow } from \"./commands/skills\";\nimport { installCommand } from \"./commands/install\";\nimport { searchCommand } from \"./commands/search\";\nimport { executeCommand } from \"./commands/execute\";\nimport { downloadCommand } from \"./commands/download\";\nimport { upgradeCommand } from \"./commands/upgrade\";\n\nconst program = new Command();\n\nprogram\n .name(\"sequel\")\n .description(\"Sequel CLI — connect data sources and run tools from your terminal\")\n // Inlined by tsdown at build time, so the reported version always matches\n // what the publish workflow bumped in package.json.\n .version(pkg.version)\n .option(\"--json\", \"output machine-readable JSON\")\n .enablePositionalOptions();\n\n/** Wrap a command action with shared --json handling and error reporting. */\nfunction action<A extends unknown[]>(fn: (...args: A) => Promise<void>) {\n return async (...args: A) => {\n // Auto-enable JSON when stdout is piped (e.g. `sequel sources | jq`), not just --json.\n if (program.opts().json || !process.stdout.isTTY) setJsonMode(true);\n try {\n await fn(...args);\n } catch (err) {\n if (err instanceof ApiError && err.status === 401) {\n fail(\"Unauthorized. Run `sequel login` to sign in again.\");\n } else {\n fail(err instanceof Error ? err.message : String(err));\n }\n process.exitCode = 1;\n }\n };\n}\n\nprogram.command(\"upgrade\").description(\"Upgrade the Sequel CLI to the latest version\").action(action(upgradeCommand));\nprogram\n .command(\"login\")\n .description(\"Sign in to Sequel\")\n .option(\"--no-browser\", \"print the sign-in URL instead of opening a browser\")\n .option(\"--detach\", \"print the sign-in URL and return; finish signing in in the background (default when piped)\")\n .option(\"--status\", \"report whether you are signed in, or a sign-in is pending, without starting one\")\n .option(\"--wait\", \"block until a pending background sign-in finishes\")\n .action(action(loginCommand));\nprogram\n .command(\"login-worker\", { hidden: true })\n .option(\"--no-browser\")\n .action(action(loginWorkerCommand));\nprogram.command(\"logout\").description(\"Sign out and remove cached credentials\").action(action(logoutCommand));\nprogram.command(\"switch\").description(\"Switch the active organization\").action(action(switchCommand));\n\nprogram\n .command(\"connect\")\n .argument(\"[source]\", \"connector id (e.g. postgres); omit to choose interactively\")\n .description(\"Connect a new data source\")\n .action(action(connectCommand));\n\nconst sources = program.command(\"sources\").description(\"Manage connected data sources\");\nsources.command(\"list\", { isDefault: true }).description(\"List connected sources\").action(action(sourcesList));\nsources.command(\"active\").description(\"List sources with live health status\").action(action(sourcesActive));\nsources\n .command(\"info\")\n .argument(\"[id]\", \"source id or short id\")\n .description(\"Show details for a source\")\n .action(action(sourcesInfo));\nsources\n .command(\"delete\")\n .argument(\"[id]\", \"source id or short id\")\n .description(\"Delete a source\")\n .action(action(sourcesDelete));\n\nconst skills = program.command(\"skills\").description(\"Browse the playbooks your agent can follow\");\nskills.command(\"list\", { isDefault: true }).description(\"List every skill (id and name)\").action(action(skillsList));\nskills\n .command(\"show\")\n .argument(\"<id>\", \"skill id, e.g. seo\")\n .description(\"Print a skill's playbook\")\n .action(action((id: string) => skillsShow(id)));\n\nprogram\n .command(\"install\")\n .argument(\"[agent]\", \"coding agent slug (e.g. cursor, claude-code)\")\n .option(\"-s, --scope <scope>\", \"global or local; skips the prompt (defaults to global when piped)\")\n .option(\"--no-browser\", \"print the sign-in URL instead of opening a browser if sign-in is needed\")\n .description(\"Install the Sequel MCP server into a coding agent\")\n .action(action(installCommand));\n\nprogram\n .command(\"search\")\n .argument(\"<usecase>\", \"what you want to do, e.g. \\\"monthly revenue\\\"\")\n .option(\"-c, --connection <id...>\", \"limit to specific connection short ids\")\n .description(\"Find the right tools for a use case across your sources\")\n .action(action((usecase: string, opts: { connection?: string[] }) => searchCommand(usecase, opts)));\n\nprogram\n .command(\"execute\")\n .argument(\"<connection_id>\", \"connection short id\")\n .argument(\"<tool>\", \"tool id, e.g. postgres.query\")\n .option(\"-d, --data <json>\", \"tool input as a JSON string\")\n .description(\"Execute a tool against a connection\")\n .action(action((connectionId: string, tool: string, opts: { data?: string }) => executeCommand(connectionId, tool, opts)));\n\nprogram\n .command(\"download\")\n .argument(\"<session_id>\", \"session id (from `sequel search` or an agent session)\")\n .argument(\"<path>\", \"file path, e.g. /data/result.csv or result.csv\")\n .option(\"-o, --output <file>\", \"write to this path (default: the file's own name)\")\n .description(\"Download a file produced by a query or workbench run\")\n .action(action((sessionId: string, path: string, opts: { output?: string }) => downloadCommand(sessionId, path, opts)));\n\nprogram.parseAsync(process.argv).catch((err) => {\n fail(err instanceof Error ? err.message : String(err));\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;WACU;cACG;kBACI;cACJ;WACH;UACD,EACL,UAAU,kBACX;YACQ,CACP,MACD;cACU,EACT,KAAK;CACH,UAAU;CACV,SAAS;AACV,EACF;cACU,EACT,QAAQ,OACT;iBACa;CACZ,QAAQ;CACR,OAAO;CACP,aAAa;AACd;eACW;eACA;CACV;CACA;CACA;CACA;CACA;CACA;CACA;AACD;oBACgB,EACf,UAAU,SACX;cACU;CACT,OAAO;CACP,OAAO;CACP,SAAS;CACT,kBAAkB;CAClB,QAAQ;CACR,cAAc;CACd,aAAa;CACb,SAAS;AACV;mBACe;CACd,kBAAkB;CAClB,aAAa;CACb,QAAQ;CACR,cAAc;CACd,QAAQ;AACT;sBACkB;CACjB,uBAAuB;CACvB,6BAA6B;CA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,mBAAmB,sBAAsB,CAClD,SAAS,UAAU,+BAA+B,CAClD,OAAO,qBAAqB,8BAA8B,CAC1D,YAAY,sCAAsC,CAClD,OAAO,OAAO,CAACC,cAAsBC,MAAcC,SAA4B,eAAe,cAAc,MAAM,KAAK,CAAC,CAAC;AAE5H,QACG,QAAQ,WAAW,CACnB,SAAS,gBAAgB,wDAAwD,CACjF,SAAS,UAAU,iDAAiD,CACpE,OAAO,uBAAuB,oDAAoD,CAClF,YAAY,uDAAuD,CACnE,OAAO,OAAO,CAACC,WAAmBC,MAAcC,SAA8B,gBAAgB,WAAW,MAAM,KAAK,CAAC,CAAC;AAEzH,QAAQ,WAAW,QAAQ,KAAK,CAAC,MAAM,CAAC,QAAQ;AAC9C,MAAK,eAAe,QAAQ,IAAI,UAAU,OAAO,IAAI,CAAC;AACtD,SAAQ,KAAK,EAAE;AAChB,EAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sequelsh/cli",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "description": "Sequel CLI — connect data sources and run tools from your terminal.",
5
5
  "license": "MIT",
6
6
  "type": "module",