baychat 0.7.0 → 0.8.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
@@ -52,6 +52,7 @@ per session, never one that another integration already uses.
52
52
 
53
53
  | Command | Description |
54
54
  |---------|-------------|
55
+ | `baychat login [--token <PAT>] [--base <url>]` | Log this laptop in to BayChat — scan the QR with your phone, approve, and the BayChat MCP server is registered with Claude Code (`claude mcp add`). Then run `/baychat <name>` in any session |
55
56
  | `baychat onboard [<conv>]` | **Run first.** Print the agent protocol + your live identity, conversations, and (a) room's context |
56
57
  | `baychat pair <code> [--base <url>]` | Redeem a pairing code and store credentials |
57
58
  | `baychat link [--name <n>] [--base <url>]` | Link this session by scanning a QR with your phone — no code to copy. Approve on your phone and the token is stored automatically |
@@ -287,7 +288,8 @@ on the MCP server entry so the launched process inherits it:
287
288
 
288
289
  | Env var | Effect |
289
290
  |---------|--------|
290
- | `BAYCHAT_TOKEN` | Use this API token instead of the credentials file (headless/CI) |
291
+ | `BAYCHAT_TOKEN` | Use this agent API token instead of the credentials file (headless/CI) |
292
+ | `BAYCHAT_DEVICE_TOKEN` | Use this `bay_u_*` device token (from `baychat login`) instead of the credentials file (headless/CI) |
291
293
  | `BAYCHAT_API_URL` | API origin (default `https://api.baychat.io`) |
292
294
  | `BAYCHAT_CONFIG_DIR` | Credentials/cursor directory (default `~/.baychat`) |
293
295
 
package/dist/api.js CHANGED
@@ -6,6 +6,9 @@ exports.fetchContext = fetchContext;
6
6
  exports.pairRequest = pairRequest;
7
7
  exports.createLinkRequest = createLinkRequest;
8
8
  exports.pollLinkRequest = pollLinkRequest;
9
+ exports.createDeviceLink = createDeviceLink;
10
+ exports.pollDeviceLink = pollDeviceLink;
11
+ exports.deviceMe = deviceMe;
9
12
  class ApiError extends Error {
10
13
  status;
11
14
  code;
@@ -114,3 +117,36 @@ async function pollLinkRequest(baseUrl, id, pollSecret) {
114
117
  throw await parseError(res);
115
118
  return (await res.json());
116
119
  }
120
+ /** Create a device link request. `deviceName` labels the laptop in the approve UI. */
121
+ async function createDeviceLink(baseUrl, deviceName) {
122
+ const res = await fetch(`${baseUrl}/api/device-links`, {
123
+ method: "POST",
124
+ headers: { "Content-Type": "application/json" },
125
+ body: JSON.stringify(deviceName ? { deviceName } : {}),
126
+ });
127
+ if (!res.ok)
128
+ throw await parseError(res);
129
+ return (await res.json());
130
+ }
131
+ /**
132
+ * Poll a device link request with its secret (query string, per the server
133
+ * contract). Unlike the agent flow this does NOT translate 404 into a status:
134
+ * pickup is single-use, so 404 covers expired, unknown, wrong-secret and
135
+ * already-consumed alike. It surfaces as an ApiError and the caller decides —
136
+ * `cmdLogin` treats it as "expired" and stops polling.
137
+ */
138
+ async function pollDeviceLink(baseUrl, id, pollSecret) {
139
+ const res = await fetch(`${baseUrl}/api/device-links/${id}?secret=${encodeURIComponent(pollSecret)}`);
140
+ if (!res.ok)
141
+ throw await parseError(res);
142
+ return (await res.json());
143
+ }
144
+ /** Verify a device token and learn whose Bay it opens (`baychat login --token`). */
145
+ async function deviceMe(baseUrl, token) {
146
+ const res = await fetch(`${baseUrl}/api/device-credentials/me`, {
147
+ headers: { Authorization: `Bearer ${token}` },
148
+ });
149
+ if (!res.ok)
150
+ throw await parseError(res);
151
+ return (await res.json());
152
+ }
package/dist/commands.js CHANGED
@@ -16,9 +16,14 @@ exports.resetSessionState = resetSessionState;
16
16
  exports.cmdCheck = cmdCheck;
17
17
  exports.cmdWatch = cmdWatch;
18
18
  exports.cmdLink = cmdLink;
19
+ exports.cmdLogin = cmdLogin;
20
+ exports.deviceExpiryWarning = deviceExpiryWarning;
21
+ exports.printDeviceExpiryWarning = printDeviceExpiryWarning;
19
22
  exports.cmdSearch = cmdSearch;
20
23
  exports.cmdFetch = cmdFetch;
21
24
  exports.cmdQr = cmdQr;
25
+ const node_child_process_1 = require("node:child_process");
26
+ const node_os_1 = __importDefault(require("node:os"));
22
27
  const qrcode_1 = __importDefault(require("qrcode"));
23
28
  const api_1 = require("./api");
24
29
  const protocol_1 = require("./protocol");
@@ -29,9 +34,16 @@ const tools_1 = require("./tools");
29
34
  const DEFAULT_BASE_URL = "https://api.baychat.io";
30
35
  function requireCredentials() {
31
36
  const creds = (0, config_1.loadCredentials)();
32
- if (!creds)
33
- throw new Error("Not connected. Run: baychat pair <code>");
34
- return creds;
37
+ if (creds)
38
+ return creds;
39
+ // A device login (`baychat login`) is not an agent pairing — these commands
40
+ // speak the agent API and still need one. Telling a logged-in user they are
41
+ // "not connected" is false and sends them round the wrong loop, so name what
42
+ // they have and what is missing.
43
+ const device = (0, config_1.loadDeviceCredentials)();
44
+ throw new Error(device
45
+ ? `Logged in as ${device.user.name} (device). No agent paired for this session — run: baychat pair <code>`
46
+ : "Not connected. Run: baychat pair <code>");
35
47
  }
36
48
  async function cmdPair(code, baseUrl) {
37
49
  const base = (baseUrl || process.env.BAYCHAT_API_URL || DEFAULT_BASE_URL).replace(/\/$/, "");
@@ -42,6 +54,11 @@ async function cmdPair(code, baseUrl) {
42
54
  console.log("Credentials saved. Try: baychat whoami");
43
55
  }
44
56
  async function cmdWhoami() {
57
+ // Before requireCredentials, which throws for a device-only setup: a lapsing
58
+ // device login is exactly what a `baychat login`-only user needs to hear, and
59
+ // it would otherwise be unreachable on the one command people run to check
60
+ // their connection.
61
+ printDeviceExpiryWarning();
45
62
  const creds = requireCredentials();
46
63
  const me = await (0, api_1.apiRequest)(creds, "GET", "/api/agent-api/me");
47
64
  console.log(`${me.name} (${me.id}) — status ${me.status} — ${creds.baseUrl}`);
@@ -383,10 +400,15 @@ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
383
400
  * connection can't be made) are transient. Real 4xx errors are not: they signal
384
401
  * a genuine problem the caller must see, so they rethrow. Note ApiError 404 is
385
402
  * handled as a terminal "expired" state by callers before reaching here.
403
+ *
404
+ * 429 is the one 4xx that belongs on the transient side: it is the server saying
405
+ * "later", not "no". Aborting on it would kill a link the user is seconds from
406
+ * approving because the poll loop — or an unrelated tab on the same IP — brushed
407
+ * a rate limit; the next tick is already an interval away.
386
408
  */
387
409
  function isTransientPollError(err) {
388
410
  if (err instanceof api_1.ApiError)
389
- return err.status >= 500;
411
+ return err.status >= 500 || err.status === 429;
390
412
  return err instanceof TypeError; // network-level fetch failure
391
413
  }
392
414
  async function cmdWatch(conversationId, opts = {}) {
@@ -472,6 +494,195 @@ async function cmdLink(opts = {}) {
472
494
  console.log("Link request expired — run baychat link again.");
473
495
  return false;
474
496
  }
497
+ // ─── Device login (`baychat login`) ────────────────────────────────────────
498
+ // The user-credential twin of `cmdLink`: same reverse-QR mechanics, but the
499
+ // approved token acts as the HUMAN and unlocks the remote MCP server, so one
500
+ // command both logs the laptop in and registers BayChat with Claude Code.
501
+ /** The copy-pasteable `claude mcp add`, with a PLACEHOLDER where the token goes:
502
+ * printing the real one would leave the secret in scrollback and in any pasted
503
+ * transcript, which argv exposure (below) does not. */
504
+ function printManualMcpAdd(baseUrl) {
505
+ console.log(` claude mcp add --transport http --scope user baychat ${baseUrl}/api/mcp \\`);
506
+ console.log(` --header "Authorization: Bearer <your token — in ~/.baychat/credentials.json under device.token>"`);
507
+ }
508
+ /**
509
+ * Register the remote BayChat MCP server with Claude Code, carrying the device
510
+ * token as a static Authorization header.
511
+ *
512
+ * The token travels in argv, which is briefly visible in a process listing on a
513
+ * shared machine. That is the accepted trade for a one-command login.
514
+ *
515
+ * Neither a missing `claude` binary nor a rejected add is a login failure — the
516
+ * credential is already saved — so both only print and return. They print
517
+ * DIFFERENTLY, though: the common non-zero exit is a renewal where an MCP server
518
+ * named `baychat` already exists, and reporting that as "CLI not found" would
519
+ * send the user hunting for the wrong problem while Claude Code quietly keeps
520
+ * the old, expiring token. We surface the real reason and suggest the removal —
521
+ * we never run it for them, since that server entry may not be ours.
522
+ */
523
+ function registerWithClaude(baseUrl, token) {
524
+ const args = [
525
+ "mcp",
526
+ "add",
527
+ "--transport",
528
+ "http",
529
+ "--scope",
530
+ "user",
531
+ "baychat",
532
+ `${baseUrl}/api/mcp`,
533
+ "--header",
534
+ `Authorization: Bearer ${token}`,
535
+ ];
536
+ // stderr is captured (not ignored) so a failure can quote claude's own words;
537
+ // the timeout keeps a hung binary from hanging a login whose credential is
538
+ // already on disk — a timeout lands in the failure branch below as ETIMEDOUT.
539
+ const res = (0, node_child_process_1.spawnSync)("claude", args, {
540
+ encoding: "utf8",
541
+ stdio: ["ignore", "ignore", "pipe"],
542
+ timeout: 15_000,
543
+ killSignal: "SIGKILL",
544
+ });
545
+ if (res.error && res.error.code === "ENOENT") {
546
+ console.log("\nClaude Code CLI not found — add BayChat manually:");
547
+ printManualMcpAdd(baseUrl);
548
+ return;
549
+ }
550
+ if (res.error || res.status !== 0) {
551
+ const reason = res.error?.code ??
552
+ res.error?.message ??
553
+ `exit ${res.status}`;
554
+ console.log(`\nCould not add BayChat to Claude Code (${reason}).`);
555
+ // Defensive redaction: the token is in argv, not in output, but a CLI that
556
+ // echoes the failing command back would otherwise print it to scrollback.
557
+ const stderr = String(res.stderr ?? "").split(token).join("<token>").trim();
558
+ if (stderr)
559
+ for (const line of stderr.split("\n").slice(0, 3))
560
+ console.log(` ${line}`);
561
+ console.log('\n If a server named "baychat" is already registered (a renewal), remove it:');
562
+ console.log(" claude mcp remove baychat");
563
+ console.log(" then add it back:");
564
+ printManualMcpAdd(baseUrl);
565
+ return;
566
+ }
567
+ console.log("✓ BayChat added to Claude Code");
568
+ }
569
+ /**
570
+ * `baychat login` — log this laptop in to BayChat as the human.
571
+ *
572
+ * Default path: create a device link request, render its QR, and poll until the
573
+ * user approves it in the app. `--token <PAT>` skips the QR and verifies a
574
+ * pasted device credential against `/api/device-credentials/me` before saving
575
+ * it — a bad token errors out rather than being written to disk.
576
+ *
577
+ * The QR, the printed URL and every log line carry only public data; the token
578
+ * lives in the credentials file (and in the `claude mcp add` handoff) alone.
579
+ * Returns true when logged in, false on expiry/timeout (exit 2 in index.ts).
580
+ */
581
+ async function cmdLogin(opts = {}) {
582
+ const base = (opts.base || process.env.BAYCHAT_API_URL || DEFAULT_BASE_URL).replace(/\/$/, "");
583
+ if (opts.token) {
584
+ const me = await (0, api_1.deviceMe)(base, opts.token);
585
+ (0, config_1.saveDeviceCredentials)({
586
+ baseUrl: base,
587
+ token: opts.token,
588
+ user: me.user,
589
+ expiresAt: me.expiresAt,
590
+ });
591
+ console.log(`✓ Logged in as ${me.user.name} (${me.tenant.name})`);
592
+ registerWithClaude(base, opts.token);
593
+ console.log("\n Run /baychat <name> in any session.");
594
+ return true;
595
+ }
596
+ // The hostname labels this laptop in the approve UI; the server caps the field
597
+ // at 60 chars, so a long corporate hostname must not 400 the whole login.
598
+ const request = await (0, api_1.createDeviceLink)(base, node_os_1.default.hostname().slice(0, 60));
599
+ console.log(await qrcode_1.default.toString(request.url, { type: "terminal", small: true }));
600
+ console.log(request.url);
601
+ console.log("Scan with your phone — BayChat will open to approve this laptop.");
602
+ // Stop polling shortly after the server-declared expiry (+5s for clock skew).
603
+ const deadline = new Date(request.expiresAt).getTime() + 5_000;
604
+ const intervalMs = opts.intervalMs ?? 3_000;
605
+ let warnedUnavailable = false;
606
+ while (Date.now() < deadline) {
607
+ await sleep(intervalMs);
608
+ let status;
609
+ try {
610
+ status = await (0, api_1.pollDeviceLink)(base, request.id, request.pollSecret);
611
+ }
612
+ catch (err) {
613
+ // 404 is the terminal state: expired, unknown, or already picked up (the
614
+ // pickup is single-use). Stop and print the retry hint below.
615
+ if (err instanceof api_1.ApiError && err.status === 404)
616
+ break;
617
+ // A 5xx/network hiccup during an api restart must not orphan a login the
618
+ // user is about to approve — ride it out and keep polling.
619
+ if (!isTransientPollError(err))
620
+ throw err;
621
+ if (!warnedUnavailable) {
622
+ console.log("Server unavailable, retrying…");
623
+ warnedUnavailable = true;
624
+ }
625
+ continue;
626
+ }
627
+ if (status.status === "approved") {
628
+ // The base we RESOLVED is the one we save and hand to Claude Code — never
629
+ // the server's self-reported `status.baseUrl`. That field is the API's
630
+ // configured public URL (API_BASE_URL), which a local or self-hosted server
631
+ // usually leaves at the production default: obeying it would take a login
632
+ // the user aimed at `--base http://localhost:4000` and quietly point both
633
+ // the credentials file and the registered MCP server at api.baychat.io,
634
+ // where this token does not exist. `base` is always a resolved non-empty
635
+ // string (flag → env → default), so there is nothing to fall back to.
636
+ //
637
+ // Never print the token — it lives in the credentials file only.
638
+ (0, config_1.saveDeviceCredentials)({
639
+ baseUrl: base,
640
+ token: status.token,
641
+ user: status.user,
642
+ expiresAt: status.expiresAt,
643
+ });
644
+ console.log(`✓ Logged in as ${status.user.name}`);
645
+ registerWithClaude(base, status.token);
646
+ console.log("\n Run /baychat <name> in any session.");
647
+ return true;
648
+ }
649
+ }
650
+ console.log("Login request expired — run baychat login again.");
651
+ return false;
652
+ }
653
+ /**
654
+ * The renewal nudge for a device credential, or null when none is due. Device
655
+ * credentials expire (30 days), and the failure mode without a warning is an
656
+ * MCP server that silently stops answering mid-session.
657
+ *
658
+ * An unparseable `expiresAt` (the `BAYCHAT_DEVICE_TOKEN` env path, where the
659
+ * server is the authority on expiry) yields null rather than a bogus warning.
660
+ */
661
+ function deviceExpiryWarning(dc, now = new Date()) {
662
+ const msLeft = new Date(dc.expiresAt).getTime() - now.getTime();
663
+ if (Number.isNaN(msLeft))
664
+ return null;
665
+ if (msLeft <= 0)
666
+ return "Your BayChat login has expired — run `npx baychat login`.";
667
+ if (msLeft < 3 * 86_400_000) {
668
+ const hours = Math.max(1, Math.round(msLeft / 3_600_000));
669
+ return `Your BayChat login expires in about ${hours}h — run \`npx baychat login\` to renew.`;
670
+ }
671
+ return null;
672
+ }
673
+ /**
674
+ * Print the device-expiry nudge, if one is due, through `print`. Shared by the
675
+ * CLI (stdout) and the stdio MCP server (stderr — stdout is the JSON-RPC
676
+ * channel there). No device credentials → nothing to say.
677
+ */
678
+ function printDeviceExpiryWarning(print = console.log) {
679
+ const device = (0, config_1.loadDeviceCredentials)();
680
+ if (!device)
681
+ return;
682
+ const warning = deviceExpiryWarning(device);
683
+ if (warning)
684
+ print(warning);
685
+ }
475
686
  // ─── Agent tools (`search` / `fetch`) ──────────────────────────────────────
476
687
  // The shell twins of the `web_search` / `web_fetch` MCP tools — same client
477
688
  // functions, same rendering, same untrusted-content notice, so an agent without
package/dist/config.js CHANGED
@@ -36,35 +36,129 @@ Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.configDir = configDir;
37
37
  exports.saveCredentials = saveCredentials;
38
38
  exports.loadCredentials = loadCredentials;
39
+ exports.saveDeviceCredentials = saveDeviceCredentials;
40
+ exports.loadDeviceCredentials = loadDeviceCredentials;
39
41
  exports.loadCursor = loadCursor;
40
42
  exports.saveCursor = saveCursor;
41
43
  const fs = __importStar(require("fs"));
42
44
  const os = __importStar(require("os"));
43
45
  const path = __importStar(require("path"));
46
+ const DEFAULT_API_URL = "https://api.baychat.io";
44
47
  function configDir() {
45
48
  return process.env.BAYCHAT_CONFIG_DIR || path.join(os.homedir(), ".baychat");
46
49
  }
47
50
  const credentialsPath = () => path.join(configDir(), "credentials.json");
48
51
  const cursorsPath = () => path.join(configDir(), "cursors.json");
49
- function saveCredentials(creds) {
52
+ /**
53
+ * The whole credentials file as a plain object, or `{}` when it is missing or
54
+ * unreadable. credentials.json holds TWO independent credentials — the agent
55
+ * pair (`baseUrl`/`token`/`agent`) and the device login (`device`) — so every
56
+ * write must merge rather than replace: `baychat login` must not log the agent
57
+ * out, and `baychat pair` must not log the laptop out.
58
+ */
59
+ function loadFile() {
60
+ try {
61
+ const parsed = JSON.parse(fs.readFileSync(credentialsPath(), "utf8"));
62
+ return parsed && typeof parsed === "object" ? parsed : {};
63
+ }
64
+ catch {
65
+ // Missing or corrupt file — treat as empty. Callers turn that into "not
66
+ // connected"; nothing here is worth surfacing to the user.
67
+ return {};
68
+ }
69
+ }
70
+ /**
71
+ * The same file, read for a WRITE rather than a read.
72
+ *
73
+ * `loadFile` treats an unreadable file as `{}` — correct for a read, where the
74
+ * answer is "not connected". It is NOT correct here: merging onto `{}` means the
75
+ * next `baychat login` silently overwrites a credentials file it could not parse,
76
+ * destroying the agent pairing (or device login) that may still be sitting in it,
77
+ * intact, behind one stray character. A missing file is genuinely empty; anything
78
+ * else is refused, by name, so the user can look at it before we replace it.
79
+ *
80
+ * @throws when the file exists but is not a readable JSON object.
81
+ */
82
+ function loadFileForMerge() {
83
+ const file = credentialsPath();
84
+ let raw;
85
+ try {
86
+ raw = fs.readFileSync(file, "utf8");
87
+ }
88
+ catch (err) {
89
+ if (err.code === "ENOENT")
90
+ return {};
91
+ throw new Error(`Cannot read ${file}: ${err.message}`);
92
+ }
93
+ let parsed;
94
+ try {
95
+ parsed = JSON.parse(raw);
96
+ }
97
+ catch {
98
+ parsed = undefined;
99
+ }
100
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
101
+ throw new Error(`${file} is not valid JSON — refusing to overwrite it and lose the credential it may still hold. Inspect or delete the file, then run this command again.`);
102
+ }
103
+ return parsed;
104
+ }
105
+ /**
106
+ * Merge `changes` into credentials.json, atomically.
107
+ *
108
+ * Written to a temp file and renamed into place: `rename` is atomic on POSIX, so
109
+ * an interrupted write (^C, a full disk, a crash) leaves the previous file
110
+ * untouched rather than a truncated one — and a truncated credentials file is
111
+ * both credentials gone at once, since the agent pairing and the device login
112
+ * share it. The mode is pinned AFTER the rename because `writeFileSync`'s `mode`
113
+ * only applies when it creates the file: a leftover temp file from a previous
114
+ * run keeps its old permissions and carries them across the rename.
115
+ */
116
+ function writeMerged(changes) {
50
117
  fs.mkdirSync(configDir(), { recursive: true, mode: 0o700 });
51
- fs.writeFileSync(credentialsPath(), JSON.stringify(creds, null, 2) + "\n", { mode: 0o600 });
118
+ const file = credentialsPath();
119
+ const merged = { ...loadFileForMerge(), ...changes };
120
+ const tmp = `${file}.tmp`;
121
+ fs.writeFileSync(tmp, JSON.stringify(merged, null, 2) + "\n", { mode: 0o600 });
122
+ fs.renameSync(tmp, file);
123
+ fs.chmodSync(file, 0o600);
124
+ }
125
+ function saveCredentials(creds) {
126
+ writeMerged({ baseUrl: creds.baseUrl, token: creds.token, agent: creds.agent });
52
127
  }
53
128
  function loadCredentials() {
54
129
  // Env override first — headless setups pass the token without a pair step.
55
130
  if (process.env.BAYCHAT_TOKEN) {
56
131
  return {
57
- baseUrl: process.env.BAYCHAT_API_URL || "https://api.baychat.io",
132
+ baseUrl: process.env.BAYCHAT_API_URL || DEFAULT_API_URL,
58
133
  token: process.env.BAYCHAT_TOKEN,
59
134
  agent: { id: "env", name: "env" },
60
135
  };
61
136
  }
62
- try {
63
- return JSON.parse(fs.readFileSync(credentialsPath(), "utf8"));
64
- }
65
- catch {
137
+ const file = loadFile();
138
+ const agent = file.agent;
139
+ if (typeof file.token !== "string" || !agent)
66
140
  return null;
141
+ return { baseUrl: String(file.baseUrl ?? DEFAULT_API_URL), token: file.token, agent };
142
+ }
143
+ function saveDeviceCredentials(device) {
144
+ writeMerged({ device });
145
+ }
146
+ function loadDeviceCredentials() {
147
+ // Same env-override shape as BAYCHAT_TOKEN: a headless/CI box can supply a
148
+ // device token directly and skip the QR. `expiresAt` is unknown on this path
149
+ // (the server is the authority) — the empty string means "don't warn".
150
+ if (process.env.BAYCHAT_DEVICE_TOKEN) {
151
+ return {
152
+ baseUrl: process.env.BAYCHAT_API_URL || DEFAULT_API_URL,
153
+ token: process.env.BAYCHAT_DEVICE_TOKEN,
154
+ user: { id: "env", name: "env" },
155
+ expiresAt: "",
156
+ };
67
157
  }
158
+ const device = loadFile().device;
159
+ if (!device || typeof device.token !== "string")
160
+ return null;
161
+ return device;
68
162
  }
69
163
  function loadCursors() {
70
164
  try {
package/dist/index.js CHANGED
@@ -11,6 +11,9 @@ Usage:
11
11
  live identity, conversations, and room context.
12
12
  --catch-up also appends the rolling summary +
13
13
  the messages after its boundary
14
+ baychat login [--token <PAT>] [--base <url>]
15
+ Log this laptop in to BayChat (QR) and add the
16
+ BayChat MCP server to Claude Code
14
17
  baychat pair <code> [--base <url>] Redeem a pairing code from the BayChat app
15
18
  baychat link [--name <n>] [--base <url>]
16
19
  Link this session via a QR you scan with your phone
@@ -66,6 +69,10 @@ async function main() {
66
69
  case "onboard":
67
70
  await (0, commands_1.cmdOnboard)(positional(args), { catchUp: args.includes("--catch-up") });
68
71
  return 0;
72
+ case "login": {
73
+ const loggedIn = await (0, commands_1.cmdLogin)({ base: flag(args, "--base"), token: flag(args, "--token") });
74
+ return loggedIn ? 0 : 2; // 2 = the link request expired without approval
75
+ }
69
76
  case "pair": {
70
77
  if (!args[0])
71
78
  throw new Error("Usage: baychat pair <code>");
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ // The one place a `ToolDef` becomes a registered MCP tool.
3
+ //
4
+ // Both servers (the conversation tools in `mcp.ts`, the agent tools in
5
+ // `mcp-tools.ts`) go through this helper so two rules hold identically, and are
6
+ // stated once:
7
+ //
8
+ // 1. A DEFINITION WITHOUT A HANDLER IS A BOOT FAILURE, not a runtime surprise.
9
+ // Registering it anyway would advertise a working tool in `listTools()` and
10
+ // only fail when a model finally calls it — as an isError result reading
11
+ // "not a function", which the model cannot act on and the operator never
12
+ // sees. Throwing here means the mistake surfaces the moment the server is
13
+ // constructed, in the developer's own test run.
14
+ //
15
+ // 2. AN EMPTY INPUT SHAPE IS NOT AN EMPTY OBJECT SCHEMA. The SDK renders an
16
+ // absent `inputSchema` differently from `{}` in `listTools`, so a tool that
17
+ // takes no arguments must omit the key entirely.
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.registerToolDefs = registerToolDefs;
20
+ /**
21
+ * Register every def against its handler, failing loudly if one is missing.
22
+ *
23
+ * @throws if `handlers` has no entry for a def's name — the definitions and the
24
+ * handler map have drifted apart, and every caller of that tool would break.
25
+ */
26
+ function registerToolDefs(server, defs, handlers) {
27
+ for (const def of defs) {
28
+ const handler = handlers[def.name];
29
+ if (!handler)
30
+ throw new Error(`No handler registered for MCP tool "${def.name}"`);
31
+ server.registerTool(def.name, {
32
+ title: def.title,
33
+ description: def.description,
34
+ ...(Object.keys(def.inputSchema).length ? { inputSchema: def.inputSchema } : {}),
35
+ }, async (args) => handler(args));
36
+ }
37
+ }